oneentry 1.0.142 → 1.0.143

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/dist/admins/adminsApi.d.ts +50 -0
  2. package/dist/admins/adminsApi.js +65 -0
  3. package/dist/admins/adminsInterfaces.d.ts +98 -0
  4. package/dist/admins/adminsInterfaces.js +2 -0
  5. package/dist/admins/adminsSchemas.d.ts +30 -0
  6. package/dist/admins/adminsSchemas.js +27 -0
  7. package/dist/attribute-sets/attributeSetsApi.d.ts +63 -0
  8. package/dist/attribute-sets/attributeSetsApi.js +98 -0
  9. package/dist/attribute-sets/attributeSetsInterfaces.d.ts +185 -0
  10. package/dist/attribute-sets/attributeSetsInterfaces.js +2 -0
  11. package/dist/attribute-sets/attributeSetsSchemas.d.ts +90 -0
  12. package/dist/attribute-sets/attributeSetsSchemas.js +74 -0
  13. package/dist/auth-provider/authProviderApi.d.ts +249 -0
  14. package/dist/auth-provider/authProviderApi.js +354 -0
  15. package/dist/auth-provider/authProviderSchemas.d.ts +131 -0
  16. package/dist/auth-provider/authProviderSchemas.js +82 -0
  17. package/dist/auth-provider/authProvidersInterfaces.d.ts +412 -0
  18. package/dist/auth-provider/authProvidersInterfaces.js +2 -0
  19. package/dist/base/asyncModules.d.ts +80 -0
  20. package/dist/base/asyncModules.js +448 -0
  21. package/dist/base/result.d.ts +39 -0
  22. package/dist/base/result.js +154 -0
  23. package/dist/base/stateModule.d.ts +41 -0
  24. package/dist/base/stateModule.js +128 -0
  25. package/dist/base/syncModules.d.ts +286 -0
  26. package/dist/base/syncModules.js +716 -0
  27. package/dist/base/utils.d.ts +197 -0
  28. package/dist/base/utils.js +2 -0
  29. package/dist/base/validation.d.ts +118 -0
  30. package/dist/base/validation.js +132 -0
  31. package/dist/blocks/blocksApi.d.ts +76 -0
  32. package/dist/blocks/blocksApi.js +188 -0
  33. package/dist/blocks/blocksInterfaces.d.ts +168 -0
  34. package/dist/blocks/blocksInterfaces.js +2 -0
  35. package/dist/blocks/blocksSchemas.d.ts +195 -0
  36. package/dist/blocks/blocksSchemas.js +43 -0
  37. package/dist/discounts/discountsApi.d.ts +56 -0
  38. package/dist/discounts/discountsApi.js +82 -0
  39. package/dist/discounts/discountsInterfaces.d.ts +145 -0
  40. package/dist/discounts/discountsInterfaces.js +2 -0
  41. package/dist/events/eventsApi.d.ts +60 -0
  42. package/dist/events/eventsApi.js +97 -0
  43. package/dist/events/eventsInterfaces.d.ts +87 -0
  44. package/dist/events/eventsInterfaces.js +2 -0
  45. package/dist/file-uploading/fileUploadingApi.d.ts +88 -0
  46. package/dist/file-uploading/fileUploadingApi.js +129 -0
  47. package/dist/file-uploading/fileUploadingInterfaces.d.ts +114 -0
  48. package/dist/file-uploading/fileUploadingInterfaces.js +2 -0
  49. package/dist/file-uploading/fileUploadingSchemas.d.ts +22 -0
  50. package/dist/file-uploading/fileUploadingSchemas.js +21 -0
  51. package/dist/forms/formsApi.d.ts +42 -0
  52. package/dist/forms/formsApi.js +57 -0
  53. package/dist/forms/formsInterfaces.d.ts +134 -0
  54. package/dist/forms/formsInterfaces.js +2 -0
  55. package/dist/forms/formsSchemas.d.ts +50 -0
  56. package/dist/forms/formsSchemas.js +31 -0
  57. package/dist/forms-data/formsDataApi.d.ts +106 -0
  58. package/dist/forms-data/formsDataApi.js +189 -0
  59. package/dist/forms-data/formsDataInterfaces.d.ts +522 -0
  60. package/dist/forms-data/formsDataInterfaces.js +2 -0
  61. package/dist/forms-data/formsDataSchemas.d.ts +115 -0
  62. package/dist/forms-data/formsDataSchemas.js +86 -0
  63. package/dist/general-types/generalTypesApi.d.ts +28 -0
  64. package/dist/general-types/generalTypesApi.js +38 -0
  65. package/dist/general-types/generalTypesInterfaces.d.ts +29 -0
  66. package/dist/general-types/generalTypesInterfaces.js +2 -0
  67. package/dist/general-types/generalTypesSchemas.d.ts +50 -0
  68. package/dist/general-types/generalTypesSchemas.js +35 -0
  69. package/dist/index.d.ts +100 -0
  70. package/dist/index.js +103 -0
  71. package/dist/integration-collections/integrationCollectionsApi.d.ts +163 -0
  72. package/dist/integration-collections/integrationCollectionsApi.js +220 -0
  73. package/dist/integration-collections/integrationCollectionsInterfaces.d.ts +313 -0
  74. package/dist/integration-collections/integrationCollectionsInterfaces.js +2 -0
  75. package/dist/integration-collections/integrationCollectionsSchemas.d.ts +80 -0
  76. package/dist/integration-collections/integrationCollectionsSchemas.js +61 -0
  77. package/dist/locales/localesApi.d.ts +27 -0
  78. package/dist/locales/localesApi.js +37 -0
  79. package/dist/locales/localesInterfaces.d.ts +40 -0
  80. package/dist/locales/localesInterfaces.js +2 -0
  81. package/dist/locales/localesSchemas.d.ts +32 -0
  82. package/dist/locales/localesSchemas.js +26 -0
  83. package/dist/menus/menusApi.d.ts +29 -0
  84. package/dist/menus/menusApi.js +39 -0
  85. package/dist/menus/menusInterfaces.d.ts +87 -0
  86. package/dist/menus/menusInterfaces.js +3 -0
  87. package/dist/menus/menusSchemas.d.ts +16 -0
  88. package/dist/menus/menusSchemas.js +28 -0
  89. package/dist/orders/ordersApi.d.ts +149 -0
  90. package/dist/orders/ordersApi.js +203 -0
  91. package/dist/orders/ordersInterfaces.d.ts +520 -0
  92. package/dist/orders/ordersInterfaces.js +2 -0
  93. package/dist/orders/ordersSchemas.d.ts +120 -0
  94. package/dist/orders/ordersSchemas.js +101 -0
  95. package/dist/pages/pagesApi.d.ts +151 -0
  96. package/dist/pages/pagesApi.js +390 -0
  97. package/dist/pages/pagesInterfaces.d.ts +284 -0
  98. package/dist/pages/pagesInterfaces.js +2 -0
  99. package/dist/pages/pagesSchemas.d.ts +85 -0
  100. package/dist/pages/pagesSchemas.js +46 -0
  101. package/dist/payments/paymentsApi.d.ts +82 -0
  102. package/dist/payments/paymentsApi.js +121 -0
  103. package/dist/payments/paymentsInterfaces.d.ts +200 -0
  104. package/dist/payments/paymentsInterfaces.js +2 -0
  105. package/dist/payments/paymentsSchemas.d.ts +100 -0
  106. package/dist/payments/paymentsSchemas.js +65 -0
  107. package/dist/product-statuses/productStatusesApi.d.ts +47 -0
  108. package/dist/product-statuses/productStatusesApi.js +70 -0
  109. package/dist/product-statuses/productStatusesInterfaces.d.ts +62 -0
  110. package/dist/product-statuses/productStatusesInterfaces.js +2 -0
  111. package/dist/product-statuses/productStatusesSchemas.d.ts +34 -0
  112. package/dist/product-statuses/productStatusesSchemas.js +30 -0
  113. package/dist/products/productsApi.d.ts +365 -0
  114. package/dist/products/productsApi.js +459 -0
  115. package/dist/products/productsInterfaces.d.ts +577 -0
  116. package/dist/products/productsInterfaces.js +2 -0
  117. package/dist/products/productsSchemas.d.ts +200 -0
  118. package/dist/products/productsSchemas.js +98 -0
  119. package/dist/sitemap/sitemapApi.d.ts +35 -0
  120. package/dist/sitemap/sitemapApi.js +45 -0
  121. package/dist/sitemap/sitemapInterfaces.d.ts +40 -0
  122. package/dist/sitemap/sitemapInterfaces.js +2 -0
  123. package/dist/system/systemApi.d.ts +43 -0
  124. package/dist/system/systemApi.js +56 -0
  125. package/dist/system/systemInterfaces.d.ts +29 -0
  126. package/dist/system/systemInterfaces.js +2 -0
  127. package/dist/templates/templatesApi.d.ts +49 -0
  128. package/dist/templates/templatesApi.js +75 -0
  129. package/dist/templates/templatesInterfaces.d.ts +67 -0
  130. package/dist/templates/templatesInterfaces.js +2 -0
  131. package/dist/templates/templatesSchemas.d.ts +48 -0
  132. package/dist/templates/templatesSchemas.js +31 -0
  133. package/dist/templates-preview/templatesPreviewApi.d.ts +38 -0
  134. package/dist/templates-preview/templatesPreviewApi.js +53 -0
  135. package/dist/templates-preview/templatesPreviewInterfaces.d.ts +119 -0
  136. package/dist/templates-preview/templatesPreviewInterfaces.js +2 -0
  137. package/dist/templates-preview/templatesPreviewSchemas.d.ts +83 -0
  138. package/dist/templates-preview/templatesPreviewSchemas.js +48 -0
  139. package/dist/users/usersApi.d.ts +143 -0
  140. package/dist/users/usersApi.js +171 -0
  141. package/dist/users/usersInterfaces.d.ts +229 -0
  142. package/dist/users/usersInterfaces.js +2 -0
  143. package/dist/users/usersSchemas.d.ts +38 -0
  144. package/dist/users/usersSchemas.js +28 -0
  145. package/dist/web-socket/wsApi.d.ts +25 -0
  146. package/dist/web-socket/wsApi.js +45 -0
  147. package/dist/web-socket/wsInterfaces.d.ts +16 -0
  148. package/dist/web-socket/wsInterfaces.js +2 -0
  149. package/package.json +3 -81
@@ -0,0 +1,448 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ /* eslint-disable jsdoc/no-undefined-types */
7
+ /* eslint-disable @typescript-eslint/no-explicit-any */
8
+ const buffer_1 = require("buffer");
9
+ const syncModules_1 = __importDefault(require("./syncModules"));
10
+ const validation_1 = require("./validation");
11
+ /**
12
+ * Abstract class AsyncModules extends SyncModules to provide asynchronous HTTP request functionalities.
13
+ * @description Abstract class AsyncModules extends SyncModules to provide asynchronous HTTP request functionalities.
14
+ */
15
+ class AsyncModules extends syncModules_1.default {
16
+ /**
17
+ * Constructor initializes the AsyncModules with a given state.
18
+ * @param {StateModule} state - Instance of StateModule containing configuration and state data.
19
+ * @description Constructor initializes the AsyncModules with a given state.
20
+ */
21
+ constructor(state) {
22
+ var _a;
23
+ super(state);
24
+ this.state = state;
25
+ this._url = this.state.url;
26
+ this._NO_FETCH = state._NO_FETCH;
27
+ this._https = (_a = state._https) !== null && _a !== void 0 ? _a : null;
28
+ }
29
+ /**
30
+ * Validates API response against a Zod schema (optional)
31
+ * @param {unknown} data - The data to validate
32
+ * @param {z.ZodSchema<T>} [schema] - Optional Zod schema for validation
33
+ * @returns {T | IError} Validated data or error object
34
+ * @description Validates response data if validation is enabled in config
35
+ */
36
+ _validateResponse(data, schema) {
37
+ // Skip validation if not enabled or no schema provided
38
+ if (!this.state.validationEnabled || !schema) {
39
+ return data;
40
+ }
41
+ // Skip validation for error responses (statusCode indicates API error)
42
+ if (data !== null &&
43
+ typeof data === 'object' &&
44
+ 'statusCode' in data &&
45
+ typeof data.statusCode === 'number' &&
46
+ data.statusCode >= 400) {
47
+ return data;
48
+ }
49
+ // Use strict or safe validation based on config
50
+ if (this.state.validationStrictMode) {
51
+ const result = (0, validation_1.validateResponse)(schema, data, {
52
+ logErrors: this.state.validationLogErrors,
53
+ });
54
+ if (!result.success) {
55
+ // Return error object compatible with IError interface
56
+ return {
57
+ statusCode: 422,
58
+ message: 'Response validation failed',
59
+ pageData: null,
60
+ timestamp: new Date().toISOString(),
61
+ localizeMessage: result.error.issues
62
+ .map((e) => `${e.path.join('.')}: ${e.message}`)
63
+ .join(', '),
64
+ validationErrors: result.error.issues,
65
+ };
66
+ }
67
+ return result.data;
68
+ }
69
+ else {
70
+ // Non-strict mode: log errors but return original data
71
+ return (0, validation_1.validateResponseSafe)(schema, data, this.state.validationLogErrors);
72
+ }
73
+ }
74
+ /**
75
+ * Performs an HTTP GET request.
76
+ * @param {string} path - The path to append to the base URL.
77
+ * @returns {Promise<T>} A promise resolving to the response data.
78
+ * @description Define a protected asynchronous method '_fetchGet' that performs a GET request
79
+ */
80
+ async _fetchGet(path) {
81
+ // Create options for the GET request using the 'makeOptions' method
82
+ const options = this.makeOptions('GET');
83
+ // Check if the fetch operation should be performed using the Fetch API or an alternative method
84
+ if (!this._NO_FETCH) {
85
+ // If Fetch API is allowed, use 'browserResponse' to perform the request and return the result
86
+ return await this.browserResponse(path, options);
87
+ }
88
+ else {
89
+ // If Fetch API is not allowed, perform the request using Node.js HTTPS module
90
+ // Return a new promise to handle the asynchronous nature of the HTTPS request
91
+ return new Promise((resolve, reject) => {
92
+ // Use the HTTPS module to send a GET request to the specified path with the given options
93
+ const req = this._https.get(this._getFullPath(path), // Get the full URL path for the request
94
+ options, // Pass the options for the request
95
+ (res) => {
96
+ // Handle the response from the server
97
+ let responseData = ''; // Initialize a variable to accumulate response data
98
+ // Listen for 'data' events to receive chunks of data from the response
99
+ res.on('data', (chunk) => {
100
+ responseData += chunk; // Append each chunk to the accumulated response data
101
+ });
102
+ // Listen for the 'end' event to know when the response has been fully received
103
+ res.on('end', () => {
104
+ try {
105
+ // Attempt to parse the accumulated response data as JSON and resolve the promise with it
106
+ resolve(JSON.parse(responseData));
107
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
108
+ }
109
+ catch (error) {
110
+ // If parsing fails, resolve the promise with the raw response data
111
+ resolve(responseData);
112
+ }
113
+ });
114
+ });
115
+ // Listen for 'error' events on the request to handle any errors that occur
116
+ req.on('error', (error) => {
117
+ // Reject the promise with the error
118
+ reject(error);
119
+ });
120
+ });
121
+ }
122
+ }
123
+ /**
124
+ * Performs an HTTP POST request.
125
+ * @param {string} path - The path to append to the base URL.
126
+ * @param {unknown} [data] - The data to send in the request body.
127
+ * @returns {Promise<T>} A promise resolving to the response data.
128
+ * @description Define a protected asynchronous method '_fetchPost' that performs a POST request
129
+ */
130
+ async _fetchPost(path, data) {
131
+ // Create options for the POST request using the 'makeOptions' method, including the data to be sent
132
+ const options = this.makeOptions('POST', data);
133
+ // Check if the fetch operation should be performed using the Fetch API or an alternative method
134
+ if (!this._NO_FETCH) {
135
+ // If Fetch API is allowed, use 'browserResponse' to perform the request and return the result
136
+ return await this.browserResponse(path, options);
137
+ }
138
+ else {
139
+ // If Fetch API is not allowed, perform the request using Node.js HTTPS module
140
+ // Return a new promise to handle the asynchronous nature of the HTTPS request
141
+ return new Promise((resolve, reject) => {
142
+ // Use the HTTPS module to send a POST request to the specified path with the given options
143
+ const req = this._https.request(this._getFullPath(path), // Get the full URL path for the request
144
+ options, // Pass the options for the request
145
+ (res) => {
146
+ // Handle the response from the server
147
+ // Accumulate response chunks in an array for efficient memory usage
148
+ const chunks = [];
149
+ // Listen for 'data' events to receive chunks of data from the response
150
+ res.on('data', (chunk) => {
151
+ chunks.push(buffer_1.Buffer.isBuffer(chunk) ? chunk : buffer_1.Buffer.from(chunk));
152
+ });
153
+ // Listen for the 'end' event to know when the response has been fully received
154
+ res.on('end', () => {
155
+ try {
156
+ // Concatenate all chunks efficiently and parse as JSON
157
+ const responseData = buffer_1.Buffer.concat(chunks).toString('utf8');
158
+ resolve(JSON.parse(responseData));
159
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
160
+ }
161
+ catch (error) {
162
+ // If parsing fails, resolve the promise with the raw response data
163
+ const responseData = buffer_1.Buffer.concat(chunks).toString('utf8');
164
+ resolve(responseData);
165
+ }
166
+ });
167
+ });
168
+ // Listen for 'error' events on the request to handle any errors that occur
169
+ req.on('error', (error) => {
170
+ // Reject the promise with the error
171
+ reject(error);
172
+ });
173
+ // Write the provided data to the request body in JSON format
174
+ req.write(JSON.stringify(data));
175
+ // End the request to signal that all data has been sent
176
+ req.end();
177
+ });
178
+ }
179
+ }
180
+ /**
181
+ * Performs an HTTP PUT request.
182
+ * @param {string} path - The path to append to the base URL.
183
+ * @param {unknown} body - The data to send in the request body.
184
+ * @returns {Promise<T>} A promise resolving to the response data.
185
+ * @description Define a protected asynchronous method '_fetchPut' that performs a PUT request
186
+ */
187
+ async _fetchPut(path, body) {
188
+ // Create options for the PUT request using the 'makeOptions' method, including the data to be sent
189
+ const options = this.makeOptions('PUT', body);
190
+ // Check if the fetch operation should be performed using the Fetch API or an alternative method
191
+ if (!this._NO_FETCH) {
192
+ // If Fetch API is allowed, use 'browserResponse' to perform the request and return the result
193
+ return await this.browserResponse(path, options);
194
+ }
195
+ else {
196
+ // If Fetch API is not allowed, perform the request using Node.js HTTPS module
197
+ // Return a new promise to handle the asynchronous nature of the HTTPS request
198
+ return new Promise((resolve, reject) => {
199
+ // Use the HTTPS module to send a PUT request to the specified path with the given options
200
+ const req = this._https.request(this._getFullPath(path), // Get the full URL path for the request
201
+ options, // Pass the options for the request
202
+ (res) => {
203
+ // Handle the response from the server
204
+ let responseData = ''; // Initialize a variable to accumulate response data
205
+ // Listen for 'data' events to receive chunks of data from the response
206
+ res.on('data', (chunk) => {
207
+ responseData += chunk; // Append each chunk to the accumulated response data
208
+ });
209
+ // Listen for the 'end' event to know when the response has been fully received
210
+ res.on('end', () => {
211
+ try {
212
+ // Attempt to parse the accumulated response data as JSON and resolve the promise with it
213
+ resolve(JSON.parse(responseData));
214
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
215
+ }
216
+ catch (error) {
217
+ // If parsing fails, resolve the promise with the raw response data
218
+ resolve(responseData);
219
+ }
220
+ });
221
+ });
222
+ // Listen for 'error' events on the request to handle any errors that occur
223
+ req.on('error', (error) => {
224
+ // Reject the promise with the error
225
+ reject(error);
226
+ });
227
+ // Write the provided data to the request body in JSON format
228
+ req.write(JSON.stringify(body));
229
+ // End the request to signal that all data has been sent
230
+ req.end();
231
+ });
232
+ }
233
+ }
234
+ /**
235
+ * Performs an HTTP DELETE request.
236
+ * @param {string} path - The path to append to the base URL.
237
+ * @param {unknown} body - The body of the request.
238
+ * @returns {Promise<T>} A promise resolving to the response data.
239
+ * @description Define a protected asynchronous method '_fetchDelete' that performs a DELETE request
240
+ */
241
+ async _fetchDelete(path, body) {
242
+ // Create options for the DELETE request using the 'makeOptions' method
243
+ const options = this.makeOptions('DELETE', body);
244
+ // Check if the fetch operation should be performed using the Fetch API or an alternative method
245
+ if (!this._NO_FETCH) {
246
+ // If Fetch API is allowed, use 'browserResponse' to perform the request and return the result
247
+ return await this.browserResponse(path, options);
248
+ }
249
+ else {
250
+ // If Fetch API is not allowed, perform the request using Node.js HTTPS module
251
+ // Return a new promise to handle the asynchronous nature of the HTTPS request
252
+ return new Promise((resolve, reject) => {
253
+ // Use the HTTPS module to send a DELETE request to the specified path with the given options
254
+ const req = this._https.delete(this._getFullPath(path), // Get the full URL path for the request
255
+ options, // Pass the options for the request
256
+ (res) => {
257
+ // Handle the response from the server
258
+ let responseData = ''; // Initialize a variable to accumulate response data
259
+ // Listen for 'data' events to receive chunks of data from the response
260
+ res.on('data', (chunk) => {
261
+ responseData += chunk; // Append each chunk to the accumulated response data
262
+ });
263
+ // Listen for the 'end' event to know when the response has been fully received
264
+ res.on('end', () => {
265
+ try {
266
+ // Attempt to parse the accumulated response data as JSON and resolve the promise with it
267
+ resolve(JSON.parse(responseData));
268
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
269
+ }
270
+ catch (error) {
271
+ // If parsing fails, resolve the promise with the raw response data
272
+ resolve(responseData);
273
+ }
274
+ });
275
+ });
276
+ // Listen for 'error' events on the request to handle any errors that occur
277
+ req.on('error', (error) => {
278
+ // Reject the promise with the error
279
+ reject(error);
280
+ });
281
+ });
282
+ }
283
+ }
284
+ /**
285
+ * Refreshes the authentication token.
286
+ * @returns {Promise<boolean>} A promise resolving to a boolean indicating success or failure.
287
+ * @description Define an asynchronous method 'refreshToken' that attempts to refresh the authentication token
288
+ */
289
+ async refreshToken() {
290
+ const url = this.state.url +
291
+ `/api/content/users-auth-providers/marker/` +
292
+ this.state.providerMarker +
293
+ `/users/refresh`;
294
+ /**
295
+ * Perform a fetch request to the specified URL to refresh the token
296
+ * @param {string} url - The URL to which the request will be sent
297
+ * @param {object} options - The options for the fetch request
298
+ * @param {string} options.method - The HTTP method to use for the request (default: 'POST')
299
+ * @param {object} options.headers - Set the necessary headers for the request
300
+ * @param {object} options.body - Send the current refresh token in the request body as a JSON string
301
+ */
302
+ const response = await fetch(url, {
303
+ method: 'POST',
304
+ headers: {
305
+ // Indicate that the request body is in JSON format
306
+ 'Content-Type': 'application/json',
307
+ // Include the application token from the state
308
+ 'x-app-token': this.state.token,
309
+ // Include the device fingerprint
310
+ 'x-device-metadata': this._getDeviceMetadata(),
311
+ },
312
+ body: JSON.stringify({ refreshToken: this.state.refreshToken }),
313
+ });
314
+ // Check if the response status is OK (status code 200-299)
315
+ if (response.ok) {
316
+ // Parse the response body as JSON and store the result
317
+ const result = await response.json();
318
+ // Update the state's refreshToken and accessToken with the new tokens from the response
319
+ this.state.refreshToken = result.refreshToken;
320
+ this.state.accessToken = result.accessToken;
321
+ // If a save function is defined in the state, call it with the new refresh token
322
+ if (this.state.saveFunction) {
323
+ this.state.saveFunction(result.refreshToken);
324
+ }
325
+ // Return true to indicate that the token refresh was successful
326
+ return true;
327
+ }
328
+ else {
329
+ // Return false to indicate that the token refresh failed
330
+ return false;
331
+ }
332
+ }
333
+ /**
334
+ * Creates options for HTTP requests.
335
+ * @param {string} method - The HTTP method (GET, POST, PUT, DELETE, etc.).
336
+ * @param {unknown} data - Optional data to include in the request body.
337
+ * @returns {IHttpOptions} An object representing the request options.
338
+ */
339
+ makeOptions(method, data) {
340
+ const options = {
341
+ method: method,
342
+ headers: {
343
+ 'Content-Type': 'application/json',
344
+ 'x-app-token': this.state.token,
345
+ },
346
+ };
347
+ // if method = 'POST' add x-device-metadata
348
+ if (method === 'POST') {
349
+ options.headers = {
350
+ ...options.headers,
351
+ 'x-device-metadata': this._getDeviceMetadata(),
352
+ };
353
+ }
354
+ // Check if 'data' is an instance of FormData or Blob
355
+ if (data instanceof FormData || data instanceof Blob) {
356
+ // Remove the 'Content-Type' header from options.headers
357
+ delete options.headers['Content-Type'];
358
+ // Set the 'accept' header to 'application/json', while preserving existing headers
359
+ options.headers = {
360
+ ...options.headers,
361
+ accept: 'application/json',
362
+ };
363
+ // Assign 'data' to options.body for sending as request payload
364
+ options.body = data;
365
+ }
366
+ else if (data) {
367
+ // If 'data' exists and is not FormData or Blob, convert it to a JSON string
368
+ // and assign it to options.body
369
+ options.body = JSON.stringify(data);
370
+ }
371
+ // Check if there is an access token available in the state
372
+ if (this.state.accessToken) {
373
+ // Add an 'Authorization' header with the Bearer token to options.headers
374
+ options.headers['Authorization'] = 'Bearer ' + this.state.accessToken;
375
+ }
376
+ return options;
377
+ }
378
+ /**
379
+ * Handles responses from the browser's fetch API.
380
+ * @param {string} path - The path to append to the base URL.
381
+ * @param {IHttpOptions} options - The options for the fetch request.
382
+ * @returns {Promise<T>} A promise resolving to the response data.
383
+ * @description Define an asynchronous method 'browserResponse' that takes a path and options as parameters
384
+ */
385
+ async browserResponse(path, options) {
386
+ try {
387
+ // Perform a fetch request using the full URL obtained from '_getFullPath' and the provided options
388
+ const response = await fetch(this._getFullPath(path), options);
389
+ // Check if the response status is OK (status code 200-299)
390
+ if (response.ok) {
391
+ try {
392
+ // Attempt to read the response body as text
393
+ const text = await response.text();
394
+ // If the response body is not empty, parse it as JSON; otherwise, return an empty object
395
+ return (text ? JSON.parse(text) : {});
396
+ // Alternatively, you could directly return the parsed JSON with 'await response.json()'
397
+ }
398
+ catch (e) {
399
+ // If parsing the response fails, return the error
400
+ return e;
401
+ }
402
+ }
403
+ else {
404
+ // Handle non-OK responses
405
+ // Check if the status is 401 (Unauthorized) and custom authentication is not used
406
+ if (response.status === 401 && !this.state.customAuth) {
407
+ // Attempt to refresh the access token
408
+ const refresh = await this.refreshToken();
409
+ if (refresh) {
410
+ // Update the Authorization header with the new access token
411
+ options.headers['Authorization'] =
412
+ 'Bearer ' + this.state.accessToken;
413
+ // Retry the fetch request with updated headers
414
+ const secondResponse = await fetch(this._getFullPath(path), options);
415
+ // Return the JSON-parsed response of the retry request
416
+ return (await secondResponse.json());
417
+ }
418
+ }
419
+ // Store the response status and parse the response body as JSON
420
+ const status = response.status;
421
+ const res = await response.json();
422
+ const statusKey = status;
423
+ if (this.state.errorsFunctions &&
424
+ this.state.errorsFunctions[statusKey]) {
425
+ this.state.errorsFunctions[statusKey](res);
426
+ }
427
+ // Determine whether to return or throw the response based on 'isShell' state
428
+ if (this.state.isShell) {
429
+ return res;
430
+ }
431
+ else {
432
+ throw res;
433
+ }
434
+ }
435
+ }
436
+ catch (e) {
437
+ // Handle any errors that occur during the fetch process
438
+ // Determine whether to return or throw the error based on 'isShell' state
439
+ if (this.state.isShell) {
440
+ return e;
441
+ }
442
+ else {
443
+ throw e;
444
+ }
445
+ }
446
+ }
447
+ }
448
+ exports.default = AsyncModules;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Result class for handling response data.
3
+ * @description Result class for handling response data.
4
+ */
5
+ export default class Result {
6
+ body: any;
7
+ /**
8
+ * Constructor that initializes the class with a given data.
9
+ * @param {Response | string} data - Response or string data.
10
+ * @description Constructor that initializes the class with a given data, which can be of type Response or string.
11
+ */
12
+ constructor(data: Response | string);
13
+ /**
14
+ * Asynchronously converts the body to a blob and returns the current instance.
15
+ * @returns {Promise<Result>} Current instance.
16
+ * @description Asynchronously converts the body to a blob and returns the current instance.
17
+ */
18
+ blob(): Promise<Result>;
19
+ /**
20
+ * Asynchronously parses the body as JSON and returns the current instance.
21
+ * @returns {Promise<Result>} Current instance.
22
+ * @description Asynchronously parses the body as JSON and returns the current instance.
23
+ */
24
+ json(): Promise<Result>;
25
+ /**
26
+ * Recursively removes language-specific data from the provided data or the body.
27
+ * @param {string} langCode - Language code.
28
+ * @param {any} [data] - Data to process.
29
+ * @returns {any} Processed data.
30
+ * @description Recursively removes language-specific data from the provided data or the body.
31
+ */
32
+ makeDataWithoutLang(langCode: string, data?: any): any;
33
+ /**
34
+ * Recursively simplifies arrays in the provided data or the body by removing single-element arrays.
35
+ * @param {any} data - The data to simplify.
36
+ * @returns {any} The simplified data.
37
+ */
38
+ makeDataWithoutArray(data?: any): any;
39
+ }
@@ -0,0 +1,154 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /* eslint-disable jsdoc/reject-any-type */
4
+ /* eslint-disable no-restricted-syntax */
5
+ /* eslint-disable @typescript-eslint/no-explicit-any */
6
+ /**
7
+ * Result class for handling response data.
8
+ * @description Result class for handling response data.
9
+ */
10
+ class Result {
11
+ /**
12
+ * Constructor that initializes the class with a given data.
13
+ * @param {Response | string} data - Response or string data.
14
+ * @description Constructor that initializes the class with a given data, which can be of type Response or string.
15
+ */
16
+ constructor(data) {
17
+ this.body = data;
18
+ }
19
+ /**
20
+ * Asynchronously converts the body to a blob and returns the current instance.
21
+ * @returns {Promise<Result>} Current instance.
22
+ * @description Asynchronously converts the body to a blob and returns the current instance.
23
+ */
24
+ async blob() {
25
+ // Convert the body to a blob using the blob() method.
26
+ this.body = await this.body.blob();
27
+ return this;
28
+ }
29
+ /**
30
+ * Asynchronously parses the body as JSON and returns the current instance.
31
+ * @returns {Promise<Result>} Current instance.
32
+ * @description Asynchronously parses the body as JSON and returns the current instance.
33
+ */
34
+ async json() {
35
+ // Check if the body is a string, then parse it as JSON, otherwise call the json() method.
36
+ this.body =
37
+ (await typeof this.body) === 'string'
38
+ ? JSON.parse(this.body)
39
+ : this.body.json();
40
+ return this;
41
+ }
42
+ /**
43
+ * Recursively removes language-specific data from the provided data or the body.
44
+ * @param {string} langCode - Language code.
45
+ * @param {any} [data] - Data to process.
46
+ * @returns {any} Processed data.
47
+ * @description Recursively removes language-specific data from the provided data or the body.
48
+ */
49
+ makeDataWithoutLang(langCode, data) {
50
+ if (data) {
51
+ // If data is an array, recursively process each item.
52
+ if (Array.isArray(data)) {
53
+ return data.map((item) => this.makeDataWithoutLang(langCode, item));
54
+ }
55
+ else {
56
+ // Iterate through each key in the data object.
57
+ for (const key in data) {
58
+ // If the value is an object containing the specified language code, replace it with the language-specific value.
59
+ if (typeof data[key] === 'object' &&
60
+ data[key] &&
61
+ langCode in data[key]) {
62
+ data[key] = data[key][langCode];
63
+ }
64
+ else if (typeof data[key] === 'object' && data[key] != null) {
65
+ // If the value is an object, recursively process it.
66
+ data[key] = this.makeDataWithoutLang(langCode, data[key]);
67
+ }
68
+ else if (Array.isArray(data[key])) {
69
+ // If the value is an array, recursively process each item.
70
+ data[key] = data.map((item) => this.makeDataWithoutLang(langCode, item));
71
+ }
72
+ }
73
+ // Return the processed data.
74
+ return data;
75
+ }
76
+ }
77
+ else {
78
+ // Process the body if no specific data is provided.
79
+ if (Array.isArray(this.body)) {
80
+ this.body = this.body.map((item) => this.makeDataWithoutLang(langCode, item));
81
+ }
82
+ else {
83
+ // Iterate through each key in the body object.
84
+ for (const key in this.body) {
85
+ // Similar processing as above but applied to the body.
86
+ if (typeof this.body[key] === 'object' &&
87
+ this.body[key] &&
88
+ langCode in this.body[key]) {
89
+ this.body[key] = this.body[key][langCode];
90
+ }
91
+ else if (typeof this.body[key] === 'object' &&
92
+ this.body[key] != null) {
93
+ this.body[key] = this.makeDataWithoutLang(langCode, this.body[key]);
94
+ }
95
+ else if (Array.isArray(this.body[key])) {
96
+ this.body[key] = this.body[key].map((item) => this.makeDataWithoutLang(langCode, item));
97
+ }
98
+ }
99
+ }
100
+ return this;
101
+ }
102
+ }
103
+ /**
104
+ * Recursively simplifies arrays in the provided data or the body by removing single-element arrays.
105
+ * @param {any} data - The data to simplify.
106
+ * @returns {any} The simplified data.
107
+ */
108
+ makeDataWithoutArray(data) {
109
+ if (data) {
110
+ // If data is an array, recursively process each item.
111
+ if (Array.isArray(data)) {
112
+ return data.map((item) => this.makeDataWithoutArray(item));
113
+ }
114
+ else {
115
+ // Iterate through each key in the data object.
116
+ for (const key in data) {
117
+ // If the value is a single-element array, replace it with the element itself.
118
+ if (Array.isArray(data[key]) && data[key].length === 1) {
119
+ data[key] = data[key][0];
120
+ }
121
+ else if (typeof data[key] === 'object' &&
122
+ data[key] &&
123
+ !Array.isArray(data[key])) {
124
+ // If the value is an object, recursively process it.
125
+ data[key] = this.makeDataWithoutArray(data[key]);
126
+ }
127
+ }
128
+ return data;
129
+ }
130
+ }
131
+ else {
132
+ // Process the body if no specific data is provided.
133
+ if (Array.isArray(this.body)) {
134
+ return this.body.map((item) => this.makeDataWithoutArray(item));
135
+ }
136
+ else {
137
+ // Iterate through each key in the body object.
138
+ for (const key in this.body) {
139
+ // Similar processing as above but applied to the body.
140
+ if (Array.isArray(this.body[key]) && this.body[key].length === 1) {
141
+ this.body[key] = this.body[key][0];
142
+ }
143
+ else if (typeof this.body[key] === 'object' &&
144
+ this.body[key] &&
145
+ !Array.isArray(this.body[key])) {
146
+ this.body[key] = this.makeDataWithoutArray(this.body[key]);
147
+ }
148
+ }
149
+ return this;
150
+ }
151
+ }
152
+ }
153
+ }
154
+ exports.default = Result;