@allthings/sdk 10.0.0-beta.1 → 10.0.0-beta.2

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 (53) hide show
  1. package/dist/cli.js +1 -1
  2. package/dist/lib.cjs.js +1 -1
  3. package/dist/src/cli.js +15 -0
  4. package/dist/src/constants.js +25 -0
  5. package/dist/src/index.js +4 -0
  6. package/dist/src/oauth/authorizationCodeGrant.js +56 -0
  7. package/dist/src/oauth/clientCredentialsGrant.js +25 -0
  8. package/dist/src/oauth/createTokenStore.js +8 -0
  9. package/dist/src/oauth/implicitGrant.js +24 -0
  10. package/dist/src/oauth/makeFetchTokenRequester.js +38 -0
  11. package/dist/src/oauth/maybeUpdateToken.js +44 -0
  12. package/dist/src/oauth/passwordGrant.js +30 -0
  13. package/dist/src/oauth/refreshTokenGrant.js +26 -0
  14. package/dist/src/oauth/requestAndSaveToStore.js +5 -0
  15. package/dist/src/oauth/types.js +1 -0
  16. package/dist/src/rest/delete.js +3 -0
  17. package/dist/src/rest/get.js +3 -0
  18. package/dist/src/rest/index.js +160 -0
  19. package/dist/src/rest/methods/agent.js +26 -0
  20. package/dist/src/rest/methods/app.js +10 -0
  21. package/dist/src/rest/methods/booking.js +6 -0
  22. package/dist/src/rest/methods/bucket.js +22 -0
  23. package/dist/src/rest/methods/conversation.js +28 -0
  24. package/dist/src/rest/methods/file.js +11 -0
  25. package/dist/src/rest/methods/group.js +22 -0
  26. package/dist/src/rest/methods/idLookup.js +12 -0
  27. package/dist/src/rest/methods/notification.js +57 -0
  28. package/dist/src/rest/methods/notificationSettings.js +19 -0
  29. package/dist/src/rest/methods/property.js +17 -0
  30. package/dist/src/rest/methods/registrationCode.js +24 -0
  31. package/dist/src/rest/methods/serviceProvider.js +9 -0
  32. package/dist/src/rest/methods/ticket.js +34 -0
  33. package/dist/src/rest/methods/unit.js +95 -0
  34. package/dist/src/rest/methods/user.js +134 -0
  35. package/dist/src/rest/methods/userRelation.js +22 -0
  36. package/dist/src/rest/methods/utilisationPeriod.js +49 -0
  37. package/dist/src/rest/patch.js +3 -0
  38. package/dist/src/rest/post.js +3 -0
  39. package/dist/src/rest/put.js +3 -0
  40. package/dist/src/rest/request.js +159 -0
  41. package/dist/src/rest/types.js +62 -0
  42. package/dist/src/utils/environment.js +1 -0
  43. package/dist/src/utils/functional.js +14 -0
  44. package/dist/src/utils/logger.js +15 -0
  45. package/dist/src/utils/object.js +6 -0
  46. package/dist/src/utils/queryString.js +13 -0
  47. package/dist/src/utils/random.js +7 -0
  48. package/dist/src/utils/sleep.js +3 -0
  49. package/dist/src/utils/string.js +6 -0
  50. package/dist/src/utils/stringToDate.js +6 -0
  51. package/dist/src/utils/upload.js +24 -0
  52. package/package.json +10 -8
  53. package/dist/lib.esm.js +0 -1350
package/dist/lib.esm.js DELETED
@@ -1,1350 +0,0 @@
1
- import Bottleneck from 'bottleneck';
2
-
3
- function createTokenStore(initialToken) {
4
- const token = new Map(Object.entries(initialToken || {}));
5
- return {
6
- get: (key) => token.get(key),
7
- reset: () => token.clear(),
8
- set: (update) => Object.entries(update).forEach(([key, value]) => token.set(key, value)),
9
- };
10
- }
11
-
12
- const version = "10.0.0-beta.1";
13
-
14
- const environment = typeof process !== 'undefined' && process.env ? process.env : {};
15
-
16
- const REST_API_URL = 'https://api.allthings.me';
17
- const OAUTH_URL = 'https://accounts.allthings.me';
18
- const QUEUE_CONCURRENCY = undefined;
19
- const QUEUE_DELAY = 0;
20
- const QUEUE_RESERVOIR = 30;
21
- const QUEUE_RESERVOIR_REFILL_INTERVAL = 166;
22
- const REQUEST_BACK_OFF_INTERVAL = 200;
23
- const REQUEST_MAX_RETRIES = 50;
24
- const DEFAULT_API_WRAPPER_OPTIONS = {
25
- apiUrl: environment.ALLTHINGS_REST_API_URL || REST_API_URL,
26
- clientId: environment.ALLTHINGS_OAUTH_CLIENT_ID,
27
- clientSecret: environment.ALLTHINGS_OAUTH_CLIENT_SECRET,
28
- oauthUrl: environment.ALLTHINGS_OAUTH_URL || OAUTH_URL,
29
- password: environment.ALLTHINGS_OAUTH_PASSWORD,
30
- requestBackOffInterval: REQUEST_BACK_OFF_INTERVAL,
31
- requestMaxRetries: REQUEST_MAX_RETRIES,
32
- scope: 'user:profile',
33
- username: environment.ALLTHINGS_OAUTH_USERNAME,
34
- };
35
- const USER_AGENT = `Allthings Node SDK REST Client/${version}`;
36
-
37
- function buildQueryString(params) {
38
- const usp = new URLSearchParams();
39
- for (const [key, value] of Object.entries(params).sort(([a], [b]) => a.localeCompare(b))) {
40
- if (value != null && value !== '') {
41
- usp.append(key, String(value));
42
- }
43
- }
44
- return usp.toString();
45
- }
46
- function parseQueryString(query) {
47
- const cleaned = query.startsWith('#') ? query.slice(1) : query;
48
- return Object.fromEntries(new URLSearchParams(cleaned));
49
- }
50
-
51
- const RESPONSE_TYPE$1 = 'code';
52
- const GRANT_TYPE$3 = 'authorization_code';
53
- const castToAuthorizationRequestParameters$1 = (parameters) => {
54
- const { redirectUri, clientId, scope, state } = parameters;
55
- if (!clientId) {
56
- throw new Error('Missing required "clientId" parameter to perform authorization code grant redirect');
57
- }
58
- if (!redirectUri) {
59
- throw new Error('Missing required "redirectUri" parameter to perform authorization code grant redirect');
60
- }
61
- return {
62
- client_id: clientId,
63
- redirect_uri: redirectUri,
64
- response_type: RESPONSE_TYPE$1,
65
- ...(scope ? { scope } : {}),
66
- ...(state ? { state } : {}),
67
- };
68
- };
69
- const isEligibleForClientRedirect$1 = (parameters) => {
70
- try {
71
- return !!castToAuthorizationRequestParameters$1(parameters);
72
- }
73
- catch {
74
- return false;
75
- }
76
- };
77
- const getRedirectUrl$1 = (parameters) => `${parameters.oauthUrl}/oauth/authorize?${buildQueryString(castToAuthorizationRequestParameters$1(parameters))}`;
78
- const castToTokenRequestParameters$2 = (parameters) => {
79
- const { authorizationCode, redirectUri, clientId, clientSecret } = parameters;
80
- if (!clientId) {
81
- throw new Error('Missing required "clientId" parameter to perform authorization code grant');
82
- }
83
- if (!redirectUri) {
84
- throw new Error('Missing required "redirectUri" parameter to perform authorization code grant');
85
- }
86
- if (!authorizationCode) {
87
- throw new Error('Missing required "authorizationCode" parameter to perform authorization code grant');
88
- }
89
- return {
90
- client_id: clientId,
91
- code: authorizationCode,
92
- grant_type: GRANT_TYPE$3,
93
- redirect_uri: redirectUri,
94
- ...(clientSecret ? { client_secret: clientSecret } : {}),
95
- };
96
- };
97
- const isEligible$3 = (parameters) => {
98
- try {
99
- return !!castToTokenRequestParameters$2(parameters);
100
- }
101
- catch {
102
- return false;
103
- }
104
- };
105
- const requestToken$3 = (tokenRequester, parameters) => tokenRequester(castToTokenRequestParameters$2(parameters));
106
-
107
- const SUBSCRIPTIONS = environment.DEBUG?.split(',').map((item) => item.trim()) || [];
108
- function makeLogger(name) {
109
- return ['log', 'info', 'warn', 'error'].reduce((logger, type) => ({
110
- ...logger,
111
- [type]: function log(...logs) {
112
- if (SUBSCRIPTIONS.includes('*') ||
113
- SUBSCRIPTIONS.includes(name) ||
114
- SUBSCRIPTIONS.includes(name.toLocaleLowerCase())) {
115
- console[type](`${name}:`, ...logs);
116
- }
117
- return true;
118
- },
119
- }), {});
120
- }
121
-
122
- const logger = makeLogger('OAuth Token Request');
123
- const makeFetchTokenRequester = (url) => async (parameters) => {
124
- try {
125
- const response = await fetch(url, {
126
- body: buildQueryString(parameters),
127
- cache: 'no-cache',
128
- credentials: 'omit',
129
- headers: {
130
- 'Content-Type': 'application/x-www-form-urlencoded',
131
- accept: 'application/json',
132
- 'user-agent': USER_AGENT,
133
- },
134
- method: 'POST',
135
- mode: 'cors',
136
- });
137
- if (response.status !== 200) {
138
- throw response;
139
- }
140
- const { access_token: newAccessToken, refresh_token: newRefreshToken, expires_in: expiresIn, } = await response.json();
141
- return {
142
- accessToken: newAccessToken,
143
- expiresIn,
144
- refreshToken: newRefreshToken,
145
- };
146
- }
147
- catch (error) {
148
- if (!(error instanceof Response)) {
149
- throw error;
150
- }
151
- const errorName = `HTTP ${error.status} — ${error.statusText}`;
152
- logger.error(errorName, error);
153
- throw new Error(`HTTP ${error.status} — ${error.statusText}. Could not get token.`);
154
- }
155
- };
156
-
157
- const GRANT_TYPE$2 = 'refresh_token';
158
- const castToTokenRequestParameters$1 = (parameters) => {
159
- const { clientId, clientSecret, refreshToken, scope } = parameters;
160
- if (!clientId) {
161
- throw new Error('Missing required "clientId" parameter to perform refresh token grant');
162
- }
163
- if (!refreshToken) {
164
- throw new Error('Missing required "refreshToken" parameter to perform refresh token grant');
165
- }
166
- return {
167
- client_id: clientId,
168
- grant_type: GRANT_TYPE$2,
169
- refresh_token: refreshToken,
170
- ...(clientSecret ? { client_secret: clientSecret } : {}),
171
- ...(scope ? { scope } : {}),
172
- };
173
- };
174
- const isEligible$2 = (parameters) => {
175
- try {
176
- return !!castToTokenRequestParameters$1(parameters);
177
- }
178
- catch {
179
- return false;
180
- }
181
- };
182
- const requestToken$2 = (tokenRequester, parameters) => tokenRequester(castToTokenRequestParameters$1(parameters));
183
-
184
- async function requestAndSaveToStore(requester, tokenStore) {
185
- const response = await requester();
186
- tokenStore.set(response);
187
- return response;
188
- }
189
-
190
- const partial = (function_, ...partialArguments) => (...arguments_) => function_(...partialArguments, ...arguments_);
191
- async function until(predicate, transformer, initialValue, iterationCount = 0) {
192
- const transformed = await transformer(initialValue, iterationCount);
193
- return (await predicate(transformed, iterationCount))
194
- ? transformed
195
- : until(predicate, transformer, transformed, iterationCount + 1);
196
- }
197
- function clearIntervalFunction(intervalId) {
198
- clearInterval(intervalId);
199
- return true;
200
- }
201
-
202
- function pseudoRandomString(length = 16) {
203
- let token = '';
204
- while (token.length < length) {
205
- token += Math.random().toString(36).slice(2);
206
- }
207
- return token.slice(0, Math.max(0, length));
208
- }
209
-
210
- async function del(request, method, body, returnRawResultObject, headers) {
211
- return request('delete', method, { body, headers }, returnRawResultObject);
212
- }
213
-
214
- async function get(request, method, query, returnRawResultObject, headers) {
215
- return request('get', method, { headers, query }, returnRawResultObject);
216
- }
217
-
218
- var EnumGender;
219
- (function (EnumGender) {
220
- EnumGender["female"] = "female";
221
- EnumGender["male"] = "male";
222
- })(EnumGender || (EnumGender = {}));
223
- var EnumUserType;
224
- (function (EnumUserType) {
225
- EnumUserType["allthingsUser"] = "allthings_user";
226
- EnumUserType["allthingsContent"] = "allthings_content";
227
- EnumUserType["customer"] = "customer";
228
- EnumUserType["demoContent"] = "demo_content";
229
- EnumUserType["demoPublic"] = "demo_public";
230
- EnumUserType["partner"] = "partner";
231
- })(EnumUserType || (EnumUserType = {}));
232
- var EnumCommunicationPreferenceChannel;
233
- (function (EnumCommunicationPreferenceChannel) {
234
- EnumCommunicationPreferenceChannel["push"] = "push";
235
- EnumCommunicationPreferenceChannel["email"] = "email";
236
- })(EnumCommunicationPreferenceChannel || (EnumCommunicationPreferenceChannel = {}));
237
- var EnumUserPermissionRole;
238
- (function (EnumUserPermissionRole) {
239
- EnumUserPermissionRole["appAdmin"] = "app-admin";
240
- EnumUserPermissionRole["appOwner"] = "app-owner";
241
- EnumUserPermissionRole["articlesAgent"] = "articles-agent";
242
- EnumUserPermissionRole["articlesViewOnly"] = "articles-view-only";
243
- EnumUserPermissionRole["bookableAssetAgent"] = "bookable-asset-agent";
244
- EnumUserPermissionRole["bookingAgent"] = "booking-agent";
245
- EnumUserPermissionRole["cockpitManager"] = "cockpit-manager";
246
- EnumUserPermissionRole["dataConnectorAdmin"] = "data-connector-admin";
247
- EnumUserPermissionRole["documentAdmin"] = "doc-admin";
248
- EnumUserPermissionRole["externalAgent"] = "external-agent";
249
- EnumUserPermissionRole["globalOrgAdmin"] = "global-org-admin";
250
- EnumUserPermissionRole["globalUserAdmin"] = "global-user-admin";
251
- EnumUserPermissionRole["orgAdmin"] = "org-admin";
252
- EnumUserPermissionRole["orgTeamManager"] = "org-team-manager";
253
- EnumUserPermissionRole["pinboardAgent"] = "pinboard-agent";
254
- EnumUserPermissionRole["platformOwner"] = "platform-owner";
255
- EnumUserPermissionRole["qa"] = "qa";
256
- EnumUserPermissionRole["serviceCenterAgent"] = "service-center-agent";
257
- EnumUserPermissionRole["serviceCenterManager"] = "service-center-manager";
258
- EnumUserPermissionRole["setup"] = "setup";
259
- EnumUserPermissionRole["tenantManager"] = "tenant-manager";
260
- })(EnumUserPermissionRole || (EnumUserPermissionRole = {}));
261
- var EnumUserPermissionObjectType;
262
- (function (EnumUserPermissionObjectType) {
263
- EnumUserPermissionObjectType["app"] = "App";
264
- EnumUserPermissionObjectType["group"] = "Group";
265
- EnumUserPermissionObjectType["property"] = "Property";
266
- EnumUserPermissionObjectType["unit"] = "Unit";
267
- })(EnumUserPermissionObjectType || (EnumUserPermissionObjectType = {}));
268
- const remapUserResult = (user) => {
269
- const { tenantIDs: tenantIds, ...result } = user;
270
- return { ...result, tenantIds };
271
- };
272
- const remapEmbeddedUser = (embedded) => embedded.users ? embedded.users.map(remapUserResult) : [];
273
- async function userCreate(client, appId, username, data) {
274
- return client.post('/v1/users', {
275
- ...data,
276
- creationContext: appId,
277
- username,
278
- });
279
- }
280
- async function getUsers(client, page = 1, limit = -1, filter = {}) {
281
- const { _embedded: { items: users }, total, } = await client.get('/v1/users', {
282
- filter: JSON.stringify(filter),
283
- limit,
284
- page,
285
- });
286
- return { _embedded: { items: users.map(remapUserResult) }, total };
287
- }
288
- async function getCurrentUser(client) {
289
- return remapUserResult(await client.get('/v1/me'));
290
- }
291
- async function userGetById(client, userId) {
292
- return remapUserResult(await client.get(`/v1/users/${userId}`));
293
- }
294
- async function userUpdateById(client, userId, data) {
295
- const { tenantIds: tenantIDs, ...rest } = data;
296
- return remapUserResult(await client.patch(`/v1/users/${userId}`, { ...rest, tenantIDs }));
297
- }
298
- async function userCreatePermission(client, userId, data) {
299
- const { objectId: objectID, ...rest } = data;
300
- const { objectID: resultObjectId, ...result } = await client.post(`/v1/users/${userId}/permissions`, {
301
- ...rest,
302
- objectID,
303
- });
304
- return {
305
- ...result,
306
- objectId: resultObjectId,
307
- };
308
- }
309
- async function userCreatePermissionBatch(client, userId, permissions) {
310
- const { objectId, objectType, roles, startDate, endDate } = permissions;
311
- const batch = {
312
- batch: roles.map((role) => ({
313
- endDate: endDate?.toISOString(),
314
- objectID: objectId,
315
- objectType,
316
- restrictions: [],
317
- role,
318
- startDate: startDate?.toISOString(),
319
- })),
320
- };
321
- return !(await client.post(`/v1/users/${userId}/permissions`, batch));
322
- }
323
- async function userGetPermissions(client, userId) {
324
- const { _embedded: { items: permissions }, } = await client.get(`/v1/users/${userId}/roles?limit=-1`);
325
- return permissions.map(({ objectID: objectId, ...result }) => ({
326
- ...result,
327
- objectId,
328
- }));
329
- }
330
- async function userDeletePermission(client, permissionId) {
331
- return !(await client.delete(`/v1/permissions/${permissionId}`));
332
- }
333
- async function userGetUtilisationPeriods(client, userId) {
334
- const { _embedded: { items: utilisationPeriods }, } = await client.get(`/v1/users/${userId}/utilisation-periods`);
335
- return utilisationPeriods;
336
- }
337
- async function userCheckInToUtilisationPeriod(client, userId, utilisationPeriodId) {
338
- const { email: userEmail } = await client.userGetById(userId);
339
- return client.utilisationPeriodCheckInUser(utilisationPeriodId, {
340
- email: userEmail,
341
- });
342
- }
343
- async function userGetByEmail(client, email, page = 1, limit = 1000) {
344
- return client.getUsers(page, limit, { email });
345
- }
346
- async function userChangePassword(client, userId, currentPassword, newPassword) {
347
- return !(await client.put(`/v1/users/${userId}/password`, {
348
- currentPassword,
349
- plainPassword: newPassword,
350
- }));
351
- }
352
-
353
- async function agentCreate(client, appId, propertyManagerId, username, data, sendInvitation, externalAgentCompany) {
354
- const user = await client.userCreate(appId, username, {
355
- ...data,
356
- type: EnumUserType.customer,
357
- });
358
- const manager = await client.post(`/v1/property-managers/${propertyManagerId}/users`, {
359
- userID: user.id,
360
- ...(externalAgentCompany && { externalAgentCompany }),
361
- });
362
- return (!((typeof sendInvitation !== 'undefined' ? sendInvitation : true) &&
363
- (await client.post(`/v1/users/${user.id}/invitations`))) && {
364
- ...user,
365
- ...manager,
366
- });
367
- }
368
- async function agentCreatePermissions(client, agentId, objectId, objectType, permissions, startDate, endDate) {
369
- return client.userCreatePermissionBatch(agentId, {
370
- endDate,
371
- objectId,
372
- objectType,
373
- restrictions: [],
374
- roles: permissions,
375
- startDate,
376
- });
377
- }
378
-
379
- async function appCreate(client, userId, data) {
380
- return client.post(`/v1/users/${userId}/apps`, {
381
- availableLocales: { '0': 'de_DE' },
382
- ...data,
383
- siteUrl: data.siteUrl.replace('_', ''),
384
- });
385
- }
386
- async function appGetById(client, appId) {
387
- return client.get(`/v1/apps/${appId}`);
388
- }
389
-
390
- async function bookingGetById(client, bookingId) {
391
- return client.get(`/v1/bookings/${bookingId}`);
392
- }
393
- async function bookingUpdateById(client, bookingId, data) {
394
- return client.patch(`/v1/bookings/${bookingId}`, data);
395
- }
396
-
397
- async function bucketGet(client, bucketId) {
398
- return client.get(`/v1/buckets/${bucketId}`);
399
- }
400
- async function bucketCreate(client, data) {
401
- return client.post('/v1/buckets', {
402
- channels: data.channels,
403
- name: data.name,
404
- });
405
- }
406
- async function bucketAddFile(client, bucketId, fileId) {
407
- return ((await client.post(`/v1/buckets/${bucketId}/files`, {
408
- id: fileId,
409
- })) === '');
410
- }
411
- async function bucketRemoveFile(client, bucketId, fileId) {
412
- return (await client.delete(`/v1/buckets/${bucketId}/files/${fileId}`)) === '';
413
- }
414
- async function bucketRemoveFilesInPath(client, bucketId, data) {
415
- return ((await client.delete(`/v1/buckets/${bucketId}/files`, {
416
- folder: data.path,
417
- })) === '');
418
- }
419
-
420
- const createManyFiles = async (attachments, apiClient) => {
421
- const responses = await Promise.all(attachments.map(async (attachment) => {
422
- try {
423
- const result = await apiClient.fileCreate({
424
- file: attachment.content,
425
- name: attachment.filename,
426
- });
427
- return result;
428
- }
429
- catch (error) {
430
- return error instanceof Error ? error : new Error(String(error));
431
- }
432
- }));
433
- return responses;
434
- };
435
- async function createManyFilesSorted(files, client) {
436
- const result = await createManyFiles(files, client);
437
- return {
438
- error: result.filter((item) => item instanceof Error),
439
- success: result
440
- .filter((item) => !(item instanceof Error))
441
- .map((item) => item.id),
442
- };
443
- }
444
-
445
- async function conversationGetById(client, conversationId) {
446
- return client.get(`/v1/conversations/${conversationId}`);
447
- }
448
- async function conversationCreateMessage(client, conversationId, messageData) {
449
- const url = `/v1/conversations/${conversationId}/messages`;
450
- const payload = messageData.attachments?.length
451
- ? {
452
- content: {
453
- description: messageData.body,
454
- files: (await createManyFilesSorted(messageData.attachments, client))
455
- .success,
456
- },
457
- createdBy: messageData.createdBy,
458
- inputChannel: messageData.inputChannel,
459
- internal: false,
460
- type: 'file',
461
- }
462
- : {
463
- content: {
464
- content: messageData.body,
465
- },
466
- createdBy: messageData.createdBy,
467
- inputChannel: messageData.inputChannel,
468
- type: 'text',
469
- };
470
- return client.post(url, payload);
471
- }
472
-
473
- async function fileCreate(client, data) {
474
- return client.post('/v1/files', {
475
- formData: {
476
- file: [data.file, data.name],
477
- path: data.path || '',
478
- },
479
- });
480
- }
481
- async function fileDelete(client, fileId) {
482
- return (await client.delete(`/v1/files/${fileId}`)) === '';
483
- }
484
-
485
- async function groupCreate(client, propertyId, data) {
486
- const { propertyManagerId, ...rest } = data;
487
- return client.post(`/v1/properties/${propertyId}/groups`, {
488
- ...rest,
489
- propertyManagerID: propertyManagerId,
490
- });
491
- }
492
- async function groupGetById(client, groupId) {
493
- const { propertyManagerID: propertyManagerId, ...result } = await client.get(`/v1/groups/${groupId}`);
494
- return { ...result, propertyManagerId };
495
- }
496
- async function groupUpdateById(client, groupId, data) {
497
- return client.patch(`/v1/groups/${groupId}`, data);
498
- }
499
- async function getGroups(client, page = 1, limit = -1, filter = {}) {
500
- const { _embedded: { items: groups }, total, } = await client.get('/v1/groups', {
501
- filter: JSON.stringify(filter),
502
- limit,
503
- page,
504
- });
505
- return { _embedded: { items: groups }, total };
506
- }
507
-
508
- async function lookupIds(client, appId, data) {
509
- const url = data.dataSource
510
- ? `/v1/id-lookup/${appId}/${data.resource}/${data.dataSource}`
511
- : `/v1/id-lookup/${appId}/${data.resource}`;
512
- return client.post(url, {
513
- externalIds: typeof data.externalIds === 'string'
514
- ? [data.externalIds]
515
- : data.externalIds,
516
- ...(data.parentId ? { parentId: data.parentId } : {}),
517
- ...(data.userType ? { userType: data.userType } : {}),
518
- });
519
- }
520
-
521
- function stringToDate(s) {
522
- return new Date(Date.parse(s));
523
- }
524
- function dateToString(d) {
525
- return d.toISOString();
526
- }
527
-
528
- var EnumNotificationCategory;
529
- (function (EnumNotificationCategory) {
530
- EnumNotificationCategory["events"] = "events";
531
- EnumNotificationCategory["hintsAndTips"] = "hints-and-tips";
532
- EnumNotificationCategory["lostAndFound"] = "lost-and-found";
533
- EnumNotificationCategory["localDeals"] = "local-deals";
534
- EnumNotificationCategory["localEvents"] = "local-events";
535
- EnumNotificationCategory["miscellaneous"] = "miscellaneous";
536
- EnumNotificationCategory["deals"] = "deals";
537
- EnumNotificationCategory["messages"] = "messages";
538
- EnumNotificationCategory["adminMessages"] = "admin-messages";
539
- EnumNotificationCategory["newThingsToGive"] = "new-things-to-give";
540
- EnumNotificationCategory["newThingsForSale"] = "new-things-for-sale";
541
- EnumNotificationCategory["surveys"] = "surveys";
542
- EnumNotificationCategory["supportOffer"] = "support-offer";
543
- EnumNotificationCategory["supportRequest"] = "support-request";
544
- EnumNotificationCategory["sustainability"] = "sustainability";
545
- EnumNotificationCategory["localServices"] = "local-services";
546
- EnumNotificationCategory["services"] = "services";
547
- EnumNotificationCategory["ticketDigestEmail"] = "ticket-digest-email";
548
- EnumNotificationCategory["appDigestEmail"] = "app-digest-email";
549
- EnumNotificationCategory["newFile"] = "new-file";
550
- })(EnumNotificationCategory || (EnumNotificationCategory = {}));
551
- var EnumNotificationType;
552
- (function (EnumNotificationType) {
553
- EnumNotificationType["clipboardThing"] = "clipboard-thing";
554
- EnumNotificationType["comment"] = "comment";
555
- EnumNotificationType["communityArticle"] = "community-article";
556
- EnumNotificationType["newFile"] = "new-file";
557
- EnumNotificationType["ticketComment"] = "ticket-comment";
558
- EnumNotificationType["welcomeNotification"] = "welcome-notification";
559
- })(EnumNotificationType || (EnumNotificationType = {}));
560
- function remapNotificationResult({ createdAt, objectID, referencedObjectID, ...restNotification }) {
561
- return {
562
- createdAt: stringToDate(createdAt),
563
- objectId: objectID,
564
- referencedObjectId: referencedObjectID,
565
- ...restNotification,
566
- };
567
- }
568
- async function notificationsGetByUser(client, userId, page = 1, limit = -1) {
569
- const { _embedded: { items: notifications }, total, metaData, } = await client.get(`/v1/users/${userId}/notifications?page=${page}&limit=${limit}`);
570
- return {
571
- _embedded: { items: notifications.map(remapNotificationResult) },
572
- metaData,
573
- total,
574
- };
575
- }
576
- async function notificationsUpdateReadByUser(client, userId, lastReadAt = new Date()) {
577
- return client.patch(`/v1/users/${userId}/notifications`, {
578
- lastReadAt: dateToString(lastReadAt),
579
- });
580
- }
581
- async function notificationUpdateRead(client, notificationId) {
582
- return remapNotificationResult(await client.patch(`/v1/notifications/${notificationId}`, { read: true }));
583
- }
584
-
585
- function remapKeys(input, mapFunction) {
586
- return Object.entries(input).reduce((accumulator, entry) => ({
587
- ...accumulator,
588
- [mapFunction(entry[0])]: entry[1],
589
- }), {});
590
- }
591
-
592
- function camelCaseToDash(input) {
593
- return input.replace(/([A-Z])/g, (g) => `-${g[0].toLowerCase()}`);
594
- }
595
- function dashCaseToCamel(input) {
596
- return input.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
597
- }
598
-
599
- var EnumNotificationSettingsValue;
600
- (function (EnumNotificationSettingsValue) {
601
- EnumNotificationSettingsValue["never"] = "never";
602
- EnumNotificationSettingsValue["immediately"] = "immediately";
603
- EnumNotificationSettingsValue["daily"] = "daily";
604
- EnumNotificationSettingsValue["weekly"] = "weekly";
605
- EnumNotificationSettingsValue["biweekly"] = "biweekly";
606
- EnumNotificationSettingsValue["monthly"] = "monthly";
607
- })(EnumNotificationSettingsValue || (EnumNotificationSettingsValue = {}));
608
- async function notificationSettingsUpdateByUser(client, userId, data) {
609
- const result = await client.patch(`/v1/users/${userId}/notification-settings`, { notificationSettings: remapKeys(data, camelCaseToDash) });
610
- return remapKeys(result, dashCaseToCamel);
611
- }
612
- async function notificationSettingsResetByUser(client, userId) {
613
- const result = await client.delete(`/v1/users/${userId}/notification-settings`);
614
- return remapKeys(result, dashCaseToCamel);
615
- }
616
-
617
- async function propertyCreate(client, appId, data) {
618
- return client.post(`/v1/apps/${appId}/properties`, data);
619
- }
620
- async function propertyGetById(client, propertyId) {
621
- return client.get(`/v1/properties/${propertyId}`);
622
- }
623
- async function propertyUpdateById(client, propertyId, data) {
624
- return client.patch(`/v1/properties/${propertyId}`, data);
625
- }
626
- async function getProperties(client, page = 1, limit = -1, filter = {}) {
627
- const { _embedded: { items: properties }, total, } = await client.get('/v1/properties', {
628
- filter: JSON.stringify(filter),
629
- limit,
630
- page,
631
- });
632
- return { _embedded: { items: properties }, total };
633
- }
634
-
635
- const remapRegistationCodeResult = (registrationCode) => {
636
- const { tenantID: externalId, ...result } = registrationCode;
637
- return { ...result, externalId };
638
- };
639
- async function registrationCodeCreate(client, code, utilisationPeriods, options = { permanent: false }) {
640
- const { externalId, ...moreOptions } = options;
641
- return remapRegistationCodeResult(await client.post('/v1/registration-codes', {
642
- code,
643
- utilisationPeriods: typeof utilisationPeriods === 'string'
644
- ? [utilisationPeriods]
645
- : utilisationPeriods,
646
- ...(externalId ? { externalId, tenantID: externalId } : {}),
647
- ...moreOptions,
648
- }));
649
- }
650
- async function registrationCodeUpdateById(client, registrationCodeId, data) {
651
- return remapRegistationCodeResult(await client.patch(`/v1/registration-codes/${registrationCodeId}`, data));
652
- }
653
- async function registrationCodeGetById(client, registrationCodeId) {
654
- return remapRegistationCodeResult(await client.get(`/v1/invitations/${registrationCodeId}`));
655
- }
656
- async function registrationCodeDelete(client, registrationCodeId) {
657
- return (await client.delete(`/v1/invitations/${registrationCodeId}`)) === '';
658
- }
659
-
660
- async function serviceProviderCreate(client, data) {
661
- return client.post('/v1/service-providers', data);
662
- }
663
- async function serviceProviderGetById(client, serviceProviderId) {
664
- return client.get(`/v1/service-providers/${serviceProviderId}`);
665
- }
666
- async function serviceProviderUpdateById(client, serviceProviderId, data) {
667
- return client.patch(`/v1/service-providers/${serviceProviderId}`, data);
668
- }
669
-
670
- var ETicketStatus;
671
- (function (ETicketStatus) {
672
- ETicketStatus["CLOSED"] = "closed";
673
- ETicketStatus["WAITING_FOR_AGENT"] = "waiting-for-agent";
674
- ETicketStatus["WAITING_FOR_CUSTOMER"] = "waiting-for-customer";
675
- ETicketStatus["WAITING_FOR_EXTERNAL"] = "waiting-for-external";
676
- })(ETicketStatus || (ETicketStatus = {}));
677
- var ETrafficLightColor;
678
- (function (ETrafficLightColor) {
679
- ETrafficLightColor["GREEN"] = "green";
680
- ETrafficLightColor["RED"] = "red";
681
- ETrafficLightColor["YELLOW"] = "yellow";
682
- })(ETrafficLightColor || (ETrafficLightColor = {}));
683
- async function ticketGetById(client, ticketId) {
684
- return client.get(`/v1/tickets/${ticketId}`);
685
- }
686
- async function ticketCreateOnUser(client, userId, utilisationPeriodId, payload) {
687
- return client.post(`/v1/users/${userId}/tickets`, {
688
- ...payload,
689
- files: payload.files
690
- ? (await createManyFilesSorted(payload.files, client)).success
691
- : [],
692
- utilisationPeriod: utilisationPeriodId,
693
- });
694
- }
695
- async function ticketCreateOnServiceProvider(client, serviceProviderId, payload) {
696
- return client.post(`/v1/property-managers/${serviceProviderId}/tickets`, {
697
- ...payload,
698
- files: payload.files
699
- ? (await createManyFilesSorted(payload.files, client)).success
700
- : [],
701
- });
702
- }
703
-
704
- var EnumUnitObjectType;
705
- (function (EnumUnitObjectType) {
706
- EnumUnitObjectType["adjoiningRoom"] = "adjoining-room";
707
- EnumUnitObjectType["advertisingSpace"] = "advertising-space";
708
- EnumUnitObjectType["aerial"] = "aerial";
709
- EnumUnitObjectType["apartmentBuilding"] = "apartment-building";
710
- EnumUnitObjectType["atm"] = "atm";
711
- EnumUnitObjectType["atmRoom"] = "atm-room";
712
- EnumUnitObjectType["attic"] = "attic";
713
- EnumUnitObjectType["atticFlat"] = "attic-flat";
714
- EnumUnitObjectType["bank"] = "bank";
715
- EnumUnitObjectType["basment"] = "basment";
716
- EnumUnitObjectType["bikeShed"] = "bike-shed";
717
- EnumUnitObjectType["buildingLaw"] = "building-law";
718
- EnumUnitObjectType["cafeteria"] = "cafeteria";
719
- EnumUnitObjectType["caretakerRoom"] = "caretaker-room";
720
- EnumUnitObjectType["carport"] = "carport";
721
- EnumUnitObjectType["cellar"] = "cellar";
722
- EnumUnitObjectType["commercialProperty"] = "commercial-property";
723
- EnumUnitObjectType["commonRoom"] = "common-room";
724
- EnumUnitObjectType["deliveryZone"] = "delivery-zone";
725
- EnumUnitObjectType["diverse"] = "diverse";
726
- EnumUnitObjectType["doubleParkingSpace"] = "double-parking-space";
727
- EnumUnitObjectType["engineeringRoom"] = "engineering-room";
728
- EnumUnitObjectType["entertainment"] = "entertainment";
729
- EnumUnitObjectType["environment"] = "environment";
730
- EnumUnitObjectType["estate"] = "estate";
731
- EnumUnitObjectType["fillingStation"] = "filling-station";
732
- EnumUnitObjectType["fitnessCenter"] = "fitness-center";
733
- EnumUnitObjectType["flat"] = "flat";
734
- EnumUnitObjectType["freeZone"] = "free-zone";
735
- EnumUnitObjectType["garage"] = "garage";
736
- EnumUnitObjectType["garden"] = "garden";
737
- EnumUnitObjectType["gardenFlat"] = "garden-flat";
738
- EnumUnitObjectType["heatingFacilities"] = "heating-facilities";
739
- EnumUnitObjectType["hotel"] = "hotel";
740
- EnumUnitObjectType["incidentalRentalExpenses"] = "incidental-rental-expenses";
741
- EnumUnitObjectType["industry"] = "industry";
742
- EnumUnitObjectType["kiosk"] = "kiosk";
743
- EnumUnitObjectType["kitchen"] = "kitchen";
744
- EnumUnitObjectType["loft"] = "loft";
745
- EnumUnitObjectType["machine"] = "machine";
746
- EnumUnitObjectType["maisonette"] = "maisonette";
747
- EnumUnitObjectType["medicalPractice"] = "medical-practice";
748
- EnumUnitObjectType["mopedShed"] = "moped-shed";
749
- EnumUnitObjectType["motorcycleParkingSpace"] = "motorcycle-parking-space";
750
- EnumUnitObjectType["office"] = "office";
751
- EnumUnitObjectType["oneFamilyHouse"] = "one-family-house";
752
- EnumUnitObjectType["parkingBox"] = "parking-box";
753
- EnumUnitObjectType["parkingGarage"] = "parking-garage";
754
- EnumUnitObjectType["parkingSpace"] = "parking-space";
755
- EnumUnitObjectType["parkingSpaces"] = "parking-spaces";
756
- EnumUnitObjectType["penthouse"] = "penthouse";
757
- EnumUnitObjectType["productionPlant"] = "production-plant";
758
- EnumUnitObjectType["pub"] = "pub";
759
- EnumUnitObjectType["publicArea"] = "public-area";
760
- EnumUnitObjectType["restaurant"] = "restaurant";
761
- EnumUnitObjectType["retirementHome"] = "retirement-home";
762
- EnumUnitObjectType["salesFloor"] = "sales-floor";
763
- EnumUnitObjectType["school"] = "school";
764
- EnumUnitObjectType["shelter"] = "shelter";
765
- EnumUnitObjectType["storage"] = "storage";
766
- EnumUnitObjectType["store"] = "store";
767
- EnumUnitObjectType["storeroom"] = "storeroom";
768
- EnumUnitObjectType["studio"] = "studio";
769
- EnumUnitObjectType["terrace"] = "terrace";
770
- EnumUnitObjectType["toilets"] = "toilets";
771
- EnumUnitObjectType["utilityRoom"] = "utility-room";
772
- EnumUnitObjectType["variableParkingSpace"] = "variable-parking-space";
773
- EnumUnitObjectType["variableRoom"] = "variable-room";
774
- EnumUnitObjectType["visitorParkingSpace"] = "visitor-parking-space";
775
- EnumUnitObjectType["workshop"] = "workshop";
776
- })(EnumUnitObjectType || (EnumUnitObjectType = {}));
777
- var EnumUnitType;
778
- (function (EnumUnitType) {
779
- EnumUnitType["rented"] = "rented";
780
- EnumUnitType["owned"] = "owned";
781
- })(EnumUnitType || (EnumUnitType = {}));
782
- async function unitCreate(client, groupId, data) {
783
- return client.post(`/v1/groups/${groupId}/units`, data);
784
- }
785
- async function unitGetById(client, unitId) {
786
- return client.get(`/v1/units/${unitId}`);
787
- }
788
- async function unitUpdateById(client, unitId, data) {
789
- return client.patch(`/v1/units/${unitId}`, data);
790
- }
791
- async function getUnits(client, page = 1, limit = -1, filter = {}) {
792
- const { _embedded: { items: units }, total, } = await client.get('/v1/units', {
793
- filter: JSON.stringify(filter),
794
- limit,
795
- page,
796
- });
797
- return { _embedded: { items: units }, total };
798
- }
799
-
800
- var EnumUserRelationType;
801
- (function (EnumUserRelationType) {
802
- EnumUserRelationType["isResponsible"] = "is-responsible";
803
- })(EnumUserRelationType || (EnumUserRelationType = {}));
804
- async function userRelationCreate(client, userId, data) {
805
- return client.post(`/v1/users/${userId}/user-relations/${data.type}`, {
806
- ids: data.ids,
807
- level: data.level,
808
- readOnly: data.readOnly,
809
- role: data.role,
810
- });
811
- }
812
- async function userRelationDelete(client, userId, data) {
813
- return client.delete(`/v1/users/${userId}/user-relations/${data.type}`, {
814
- ids: data.ids,
815
- level: data.level,
816
- role: data.role,
817
- });
818
- }
819
- async function userRelationsGetByUser(client, userId) {
820
- return client.get(`/v1/users/${userId}/user-relations`);
821
- }
822
-
823
- var EnumUtilisationPeriodType;
824
- (function (EnumUtilisationPeriodType) {
825
- EnumUtilisationPeriodType["tenant"] = "tenant";
826
- EnumUtilisationPeriodType["ownership"] = "ownership";
827
- EnumUtilisationPeriodType["vacant"] = "vacant";
828
- })(EnumUtilisationPeriodType || (EnumUtilisationPeriodType = {}));
829
- async function utilisationPeriodCreate(client, unitId, data) {
830
- const { tenantIDs: tenantIds, _embedded, ...result } = await client.post(`/v1/units/${unitId}/utilisation-periods`, data);
831
- return {
832
- ...result,
833
- invitations: _embedded.invitations.map(remapRegistationCodeResult),
834
- tenantIds,
835
- users: remapEmbeddedUser(_embedded),
836
- };
837
- }
838
- async function utilisationPeriodGetById(client, utilisationPeriodId) {
839
- const { tenantIDs: tenantIds, _embedded, ...result } = await client.get(`/v1/utilisation-periods/${utilisationPeriodId}`);
840
- return {
841
- ...result,
842
- invitations: _embedded.invitations.map(remapRegistationCodeResult),
843
- tenantIds,
844
- users: remapEmbeddedUser(_embedded),
845
- };
846
- }
847
- async function utilisationPeriodUpdateById(client, utilisationPeriodId, data) {
848
- const { tenantIDs: tenantIds, _embedded, ...result } = await client.patch(`/v1/utilisation-periods/${utilisationPeriodId}`, data);
849
- return {
850
- ...result,
851
- invitations: _embedded.invitations.map(remapRegistationCodeResult),
852
- tenantIds,
853
- users: remapEmbeddedUser(_embedded),
854
- };
855
- }
856
- async function utilisationPeriodDelete(client, utilisationPeriodId) {
857
- return !(await client.delete(`/v1/utilisation-periods/${utilisationPeriodId}/soft`));
858
- }
859
- async function utilisationPeriodCheckInUser(client, utilisationPeriodId, data) {
860
- return ((await client.post(`/v1/utilisation-periods/${utilisationPeriodId}/users`, {
861
- email: data.email,
862
- })) && client.utilisationPeriodGetById(utilisationPeriodId));
863
- }
864
- async function utilisationPeriodCheckOutUser(client, utilisationPeriodId, userId) {
865
- return ((await client.delete(`/v1/utilisation-periods/${utilisationPeriodId}/users/${userId}`)) === '');
866
- }
867
- async function utilisationPeriodAddRegistrationCode(client, utilisationPeriodId, code, tenant, permanent = false) {
868
- return client.post(`/v1/utilisation-periods/${utilisationPeriodId}/registration-codes`, { code, permanent, tenant });
869
- }
870
-
871
- async function patch(request, method, body, returnRawResultObject, headers) {
872
- return request('patch', method, { body, headers }, returnRawResultObject);
873
- }
874
-
875
- async function post(request, method, body, returnRawResultObject, headers) {
876
- return request('post', method, { body, headers }, returnRawResultObject);
877
- }
878
-
879
- async function put(request, method, body, returnRawResultObject, headers) {
880
- return request('put', method, { body, headers }, returnRawResultObject);
881
- }
882
-
883
- const GRANT_TYPE$1 = 'client_credentials';
884
- const castClientOptionsToRequestParameters = (clientOptions) => {
885
- const { scope, clientId, clientSecret } = clientOptions;
886
- if (!clientId) {
887
- throw new Error('Missing required "clientId" parameter to perform client credentials grant');
888
- }
889
- if (!clientSecret) {
890
- throw new Error('Missing required "clientSecret" parameter to perform client credentials grant');
891
- }
892
- return {
893
- client_id: clientId,
894
- client_secret: clientSecret,
895
- grant_type: GRANT_TYPE$1,
896
- ...(scope ? { scope } : {}),
897
- };
898
- };
899
- const isEligible$1 = (clientOptions) => {
900
- try {
901
- return !!castClientOptionsToRequestParameters(clientOptions);
902
- }
903
- catch {
904
- return false;
905
- }
906
- };
907
- const requestToken$1 = (oauthTokenRequest, clientOptions) => oauthTokenRequest(castClientOptionsToRequestParameters(clientOptions));
908
-
909
- const RESPONSE_TYPE = 'token';
910
- const castToAuthorizationRequestParameters = (parameters) => {
911
- const { clientId, scope, state, redirectUri } = parameters;
912
- if (!clientId) {
913
- throw new Error('Missing required "clientId" parameter to perform implicit grant');
914
- }
915
- return {
916
- client_id: clientId,
917
- redirect_uri: redirectUri || window.location.href,
918
- response_type: RESPONSE_TYPE,
919
- ...(scope ? { scope } : {}),
920
- ...(state ? { state } : {}),
921
- };
922
- };
923
- const isEligibleForClientRedirect = (parameters) => {
924
- try {
925
- return !!castToAuthorizationRequestParameters(parameters);
926
- }
927
- catch {
928
- return false;
929
- }
930
- };
931
- const getRedirectUrl = (parameters) => `${parameters.oauthUrl}/oauth/authorize?${buildQueryString(castToAuthorizationRequestParameters(parameters))}`;
932
-
933
- const GRANT_TYPE = 'password';
934
- const castToTokenRequestParameters = (parameters) => {
935
- const { username, password, scope, clientId, clientSecret } = parameters;
936
- if (!clientId) {
937
- throw new Error('Missing required "clientId" parameter to perform password grant');
938
- }
939
- if (!username) {
940
- throw new Error('Missing required "username" parameter to perform password grant');
941
- }
942
- if (!password) {
943
- throw new Error('Missing required "password" parameter to perform password grant');
944
- }
945
- return {
946
- client_id: clientId,
947
- grant_type: GRANT_TYPE,
948
- password,
949
- username,
950
- ...(scope ? { scope } : {}),
951
- ...(clientSecret ? { client_secret: clientSecret } : {}),
952
- };
953
- };
954
- const isEligible = (parameters) => {
955
- try {
956
- return !!castToTokenRequestParameters(parameters);
957
- }
958
- catch {
959
- return false;
960
- }
961
- };
962
- const requestToken = (tokenRequester, parameters) => tokenRequester(castToTokenRequestParameters(parameters));
963
-
964
- async function maybeUpdateToken(oauthTokenStore, tokenFetcher, options, mustRefresh = false) {
965
- if (!mustRefresh && oauthTokenStore.get('accessToken')) {
966
- return;
967
- }
968
- const refreshOptions = {
969
- ...options,
970
- refreshToken: oauthTokenStore.get('refreshToken'),
971
- };
972
- if (isEligible$2(refreshOptions)) {
973
- return oauthTokenStore.set(await requestToken$2(tokenFetcher, refreshOptions));
974
- }
975
- if (isEligible(options)) {
976
- return oauthTokenStore.set(await requestToken(tokenFetcher, options));
977
- }
978
- if (typeof window !== 'undefined' && options.implicit) {
979
- const parsedLocationHash = parseQueryString(window.location.hash);
980
- const accessToken = parsedLocationHash.access_token;
981
- if (accessToken) {
982
- window.history.replaceState({}, '', window.location.href.split('#')[0]);
983
- return oauthTokenStore.set({ accessToken });
984
- }
985
- if (isEligibleForClientRedirect(options)) {
986
- window.location.href = getRedirectUrl(options);
987
- return;
988
- }
989
- }
990
- if (!mustRefresh && isEligible$3(options)) {
991
- return oauthTokenStore.set(await requestToken$3(tokenFetcher, options));
992
- }
993
- if (options.authorizationRedirect &&
994
- isEligibleForClientRedirect$1(options)) {
995
- return options.authorizationRedirect(getRedirectUrl$1(options));
996
- }
997
- if (isEligible$1(options)) {
998
- return oauthTokenStore.set(await requestToken$1(tokenFetcher, options));
999
- }
1000
- return;
1001
- }
1002
-
1003
- function sleep(milliseconds) {
1004
- return new Promise((resolve) => setTimeout(() => resolve(true), milliseconds));
1005
- }
1006
-
1007
- const requestLogger = makeLogger('REST API Request');
1008
- const responseLogger = makeLogger('REST API Response');
1009
- const RETRYABLE_STATUS_CODES = [401, 408, 429, 502, 503, 504];
1010
- const TOKEN_REFRESH_STATUS_CODES = [401];
1011
- const queue = new Bottleneck({
1012
- maxConcurrent: QUEUE_CONCURRENCY,
1013
- minTime: QUEUE_DELAY,
1014
- reservoir: QUEUE_RESERVOIR,
1015
- });
1016
- const refillIntervalSet = new Set();
1017
- function isFormData(body) {
1018
- return typeof body !== 'undefined' && body.formData !== undefined;
1019
- }
1020
- function refillReservoir() {
1021
- if (refillIntervalSet.size === 0) {
1022
- const interval = setInterval(async () => {
1023
- const reservoir = (await queue.currentReservoir());
1024
- if (queue.empty() && (await queue.running()) === 0 && reservoir > 10) {
1025
- return ((await queue.incrementReservoir(1)) &&
1026
- clearIntervalFunction(interval) &&
1027
- refillIntervalSet.delete(interval));
1028
- }
1029
- return reservoir < QUEUE_RESERVOIR
1030
- ? queue.incrementReservoir(1)
1031
- : clearIntervalFunction(interval) && refillIntervalSet.delete(interval);
1032
- }, QUEUE_RESERVOIR_REFILL_INTERVAL);
1033
- return refillIntervalSet.add(interval);
1034
- }
1035
- return refillIntervalSet;
1036
- }
1037
- async function makeResultFromResponse(response) {
1038
- if (RETRYABLE_STATUS_CODES.includes(response.status)) {
1039
- return response.clone();
1040
- }
1041
- if (!response.ok) {
1042
- return new Error(`${response.status} ${response.statusText}\n\n${await response.text()}`);
1043
- }
1044
- if (response.headers.get('content-type') !== 'application/json' &&
1045
- response.status !== 204) {
1046
- return new Error(`Response content type was "${response.headers.get('content-type')}" but expected JSON`);
1047
- }
1048
- return {
1049
- body: response.status === 204 ? '' : await response.json(),
1050
- status: response.status,
1051
- };
1052
- }
1053
- function responseWasSuccessful(response) {
1054
- return !RETRYABLE_STATUS_CODES.includes(response.status);
1055
- }
1056
- function makeApiRequest(oauthTokenStore, oauthTokenRequester, options, httpMethod, apiMethod, payload, returnRawResultObject) {
1057
- return async (previousResult, retryCount) => {
1058
- if (retryCount > 0) {
1059
- if (retryCount > options.requestMaxRetries) {
1060
- const error = `Maximum number of retries reached while retrying ${previousResult.method} request ${previousResult.path}.`;
1061
- requestLogger.error(error);
1062
- throw new Error(error);
1063
- }
1064
- requestLogger.warn(`Warning: encountered ${previousResult.status}. Retrying ${previousResult.method} request ${previousResult.path} (retry #${retryCount}).`);
1065
- await sleep(Math.ceil(Math.random() *
1066
- options.requestBackOffInterval *
1067
- 2 ** retryCount));
1068
- }
1069
- await maybeUpdateToken(oauthTokenStore, oauthTokenRequester, options, retryCount > 0 &&
1070
- TOKEN_REFRESH_STATUS_CODES.includes(previousResult.status));
1071
- const payloadQuery = payload?.query
1072
- ? (apiMethod.includes('?') ? '&' : '?') + buildQueryString(payload.query)
1073
- : '';
1074
- const url = `${options.apiUrl}/api${apiMethod}${payloadQuery}`;
1075
- if (!oauthTokenStore.get('accessToken')) {
1076
- throw new Error(`Unable to get OAuth2 access token. Error trying to call endpoint: ${url}`);
1077
- }
1078
- try {
1079
- return (refillReservoir() &&
1080
- (await queue.schedule(async () => {
1081
- const method = httpMethod.toUpperCase();
1082
- const body = payload?.body;
1083
- const hasForm = isFormData(body);
1084
- const form = isFormData(body) ? body.formData : {};
1085
- const formData = Object.entries(form).reduce((previous, [name, value]) => {
1086
- if (Array.isArray(value)) {
1087
- const [content, filename] = value;
1088
- const blobContent = content instanceof Blob ? content : new Blob([content]);
1089
- previous.append(name, blobContent, filename);
1090
- }
1091
- else {
1092
- previous.append(name, value);
1093
- }
1094
- return previous;
1095
- }, new FormData());
1096
- const headers = {
1097
- accept: 'application/json',
1098
- authorization: `Bearer ${oauthTokenStore.get('accessToken')}`,
1099
- 'X-Allthings-Caller': `${options.serviceName
1100
- ? options.serviceName
1101
- :
1102
- environment.SEVICE_NAME
1103
- ? environment.SEVICE_NAME
1104
- : 'unknown service name'} --- clientID ${options.clientId?.split('_')[0] ??
1105
- options.clientId ??
1106
- 'no client id present'}`,
1107
- ...(hasForm ? {} : { 'content-type': 'application/json' }),
1108
- ...(typeof window === 'undefined' &&
1109
- typeof document === 'undefined' && { 'user-agent': USER_AGENT }),
1110
- ...payload?.headers,
1111
- };
1112
- if (environment.LOG_REQUEST) {
1113
- console.log({ sdkLogs: { method, url } });
1114
- }
1115
- requestLogger.log(method, url, {
1116
- body,
1117
- headers,
1118
- });
1119
- const requestBody = {
1120
- body: hasForm ? formData : JSON.stringify(body),
1121
- };
1122
- const response = await fetch(url, {
1123
- cache: 'no-cache',
1124
- credentials: 'omit',
1125
- headers,
1126
- method,
1127
- mode: 'cors',
1128
- ...(hasForm || body ? requestBody : {}),
1129
- });
1130
- const result = await makeResultFromResponse(response);
1131
- responseLogger.log(method, url, result instanceof Error
1132
- ? { error: result }
1133
- : {
1134
- body: result.body,
1135
- status: response.status,
1136
- });
1137
- return result instanceof Error && returnRawResultObject
1138
- ? {
1139
- body: result.message,
1140
- status: response.status,
1141
- }
1142
- : result;
1143
- })));
1144
- }
1145
- catch (error) {
1146
- return error;
1147
- }
1148
- };
1149
- }
1150
- async function request(oauthTokenStore, oauthTokenRequester, options, httpMethod, apiMethod, payload, returnRawResultObject) {
1151
- const result = await until(responseWasSuccessful, makeApiRequest(oauthTokenStore, oauthTokenRequester, options, httpMethod, apiMethod, payload, returnRawResultObject));
1152
- if (result instanceof Error) {
1153
- requestLogger.log('Request Error', result, payload);
1154
- throw result;
1155
- }
1156
- return returnRawResultObject ? result : result.body;
1157
- }
1158
-
1159
- const API_METHODS = [
1160
- agentCreate,
1161
- agentCreatePermissions,
1162
- appCreate,
1163
- appGetById,
1164
- bucketCreate,
1165
- bucketAddFile,
1166
- bucketRemoveFile,
1167
- bucketRemoveFilesInPath,
1168
- bucketGet,
1169
- conversationGetById,
1170
- conversationCreateMessage,
1171
- fileCreate,
1172
- fileDelete,
1173
- notificationSettingsResetByUser,
1174
- notificationSettingsUpdateByUser,
1175
- groupCreate,
1176
- groupGetById,
1177
- groupUpdateById,
1178
- getGroups,
1179
- lookupIds,
1180
- notificationsGetByUser,
1181
- notificationUpdateRead,
1182
- notificationsUpdateReadByUser,
1183
- propertyCreate,
1184
- propertyGetById,
1185
- propertyUpdateById,
1186
- getProperties,
1187
- serviceProviderCreate,
1188
- serviceProviderGetById,
1189
- serviceProviderUpdateById,
1190
- registrationCodeCreate,
1191
- registrationCodeUpdateById,
1192
- registrationCodeDelete,
1193
- registrationCodeGetById,
1194
- ticketCreateOnUser,
1195
- ticketCreateOnServiceProvider,
1196
- ticketGetById,
1197
- unitCreate,
1198
- unitGetById,
1199
- unitUpdateById,
1200
- getUnits,
1201
- userCreate,
1202
- userGetById,
1203
- userUpdateById,
1204
- userChangePassword,
1205
- userCreatePermission,
1206
- userCreatePermissionBatch,
1207
- userGetPermissions,
1208
- userDeletePermission,
1209
- userCheckInToUtilisationPeriod,
1210
- userGetUtilisationPeriods,
1211
- userGetByEmail,
1212
- getCurrentUser,
1213
- getUsers,
1214
- userRelationCreate,
1215
- userRelationDelete,
1216
- userRelationsGetByUser,
1217
- utilisationPeriodCreate,
1218
- utilisationPeriodDelete,
1219
- utilisationPeriodGetById,
1220
- utilisationPeriodUpdateById,
1221
- utilisationPeriodCheckInUser,
1222
- utilisationPeriodCheckOutUser,
1223
- utilisationPeriodAddRegistrationCode,
1224
- bookingUpdateById,
1225
- bookingGetById,
1226
- ];
1227
- function restClient(userOptions = DEFAULT_API_WRAPPER_OPTIONS) {
1228
- const options = {
1229
- ...DEFAULT_API_WRAPPER_OPTIONS,
1230
- ...userOptions,
1231
- };
1232
- if (options.apiUrl === undefined) {
1233
- throw new Error('API URL is undefined.');
1234
- }
1235
- if (options.oauthUrl === undefined) {
1236
- throw new Error('OAuth2 URL is undefined.');
1237
- }
1238
- if (!options.clientId &&
1239
- !(options.accessToken || options.tokenStore) &&
1240
- typeof window === 'undefined') {
1241
- throw new Error('Missing required "clientId" or "accessToken" parameter .');
1242
- }
1243
- const tokenRequester = makeFetchTokenRequester(`${options.oauthUrl}/oauth/token`);
1244
- const tokenStore = options.tokenStore ||
1245
- createTokenStore({
1246
- accessToken: options.accessToken,
1247
- refreshToken: options.refreshToken,
1248
- });
1249
- const request$1 = partial(request, tokenStore, tokenRequester, options);
1250
- const del$1 = partial(del, request$1);
1251
- const get$1 = partial(get, request$1);
1252
- const post$1 = partial(post, request$1);
1253
- const patch$1 = partial(patch, request$1);
1254
- const put$1 = partial(put, request$1);
1255
- const oauth = {
1256
- authorizationCode: {
1257
- getUri: (state = options.state || pseudoRandomString()) => partial(getRedirectUrl$1, {
1258
- ...options,
1259
- state,
1260
- })(),
1261
- requestToken: (authorizationCode) => requestAndSaveToStore(partial(requestToken$3, tokenRequester, {
1262
- ...options,
1263
- authorizationCode: authorizationCode || options.authorizationCode,
1264
- }), tokenStore),
1265
- },
1266
- generateState: pseudoRandomString,
1267
- refreshToken: (refreshToken) => requestAndSaveToStore(partial(requestToken$2, tokenRequester, {
1268
- ...options,
1269
- refreshToken: refreshToken || tokenStore.get('refreshToken'),
1270
- }), tokenStore),
1271
- };
1272
- const client = API_METHODS.reduce((methods, method) => ({
1273
- ...methods,
1274
- [method.name]: (...arguments_) => method(client, ...arguments_),
1275
- }), {
1276
- delete: del$1,
1277
- get: get$1,
1278
- oauth,
1279
- options,
1280
- patch: patch$1,
1281
- post: post$1,
1282
- put: put$1,
1283
- });
1284
- return client;
1285
- }
1286
-
1287
- var EnumResource;
1288
- (function (EnumResource) {
1289
- EnumResource["group"] = "group";
1290
- EnumResource["property"] = "property";
1291
- EnumResource["serviceProvider"] = "propertyManager";
1292
- EnumResource["registrationCode"] = "registrationCode";
1293
- EnumResource["unit"] = "unit";
1294
- EnumResource["user"] = "user";
1295
- EnumResource["utilisationPeriod"] = "utilisationPeriod";
1296
- })(EnumResource || (EnumResource = {}));
1297
- var EnumCountryCode;
1298
- (function (EnumCountryCode) {
1299
- EnumCountryCode["CH"] = "CH";
1300
- EnumCountryCode["DE"] = "DE";
1301
- EnumCountryCode["FR"] = "FR";
1302
- EnumCountryCode["IT"] = "IT";
1303
- EnumCountryCode["NL"] = "NL";
1304
- EnumCountryCode["PT"] = "PT";
1305
- EnumCountryCode["US"] = "US";
1306
- })(EnumCountryCode || (EnumCountryCode = {}));
1307
- var EnumLocale;
1308
- (function (EnumLocale) {
1309
- EnumLocale["ch_de"] = "ch_DE";
1310
- EnumLocale["ch_fr"] = "ch_FR";
1311
- EnumLocale["ch_it"] = "ch_it";
1312
- EnumLocale["de_DE"] = "de_DE";
1313
- EnumLocale["it_IT"] = "it_IT";
1314
- EnumLocale["fr_FR"] = "fr_FR";
1315
- EnumLocale["pt_PT"] = "pt_PT";
1316
- EnumLocale["en_US"] = "en_US";
1317
- })(EnumLocale || (EnumLocale = {}));
1318
- var EnumTimezone;
1319
- (function (EnumTimezone) {
1320
- EnumTimezone["EuropeBerlin"] = "Europe/Berlin";
1321
- EnumTimezone["EuropeLondon"] = "Europe/London";
1322
- EnumTimezone["EuropeSofia"] = "Europe/Sofia";
1323
- EnumTimezone["EuropeZurich"] = "Europe/Zurich";
1324
- EnumTimezone["UTC"] = "UTC";
1325
- })(EnumTimezone || (EnumTimezone = {}));
1326
- var EnumServiceProviderType;
1327
- (function (EnumServiceProviderType) {
1328
- EnumServiceProviderType["propertyManager"] = "property-manager";
1329
- EnumServiceProviderType["craftspeople"] = "craftspeople";
1330
- })(EnumServiceProviderType || (EnumServiceProviderType = {}));
1331
- var EnumCommunicationMethodType;
1332
- (function (EnumCommunicationMethodType) {
1333
- EnumCommunicationMethodType["email"] = "email";
1334
- })(EnumCommunicationMethodType || (EnumCommunicationMethodType = {}));
1335
- var EnumInputChannel;
1336
- (function (EnumInputChannel) {
1337
- EnumInputChannel["APP"] = "app";
1338
- EnumInputChannel["COCKPIT"] = "cockpit";
1339
- EnumInputChannel["CRAFTSMEN"] = "craftsmen";
1340
- EnumInputChannel["EMAIL"] = "email";
1341
- EnumInputChannel["PHONE"] = "phone";
1342
- EnumInputChannel["WHATS_APP"] = "whats_app";
1343
- })(EnumInputChannel || (EnumInputChannel = {}));
1344
- var EnumLookupUserType;
1345
- (function (EnumLookupUserType) {
1346
- EnumLookupUserType["agent"] = "agent";
1347
- EnumLookupUserType["tenant"] = "tenant";
1348
- })(EnumLookupUserType || (EnumLookupUserType = {}));
1349
-
1350
- export { EnumCommunicationMethodType, EnumCommunicationPreferenceChannel, EnumCountryCode, EnumInputChannel, EnumLocale, EnumLookupUserType, EnumResource, EnumServiceProviderType, EnumTimezone, EnumUnitObjectType, EnumUnitType, EnumUserPermissionObjectType, EnumUserPermissionRole, EnumUserRelationType, EnumUtilisationPeriodType, buildQueryString, createTokenStore, parseQueryString, restClient };