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

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 (54) hide show
  1. package/dist/cli.js +3 -3
  2. package/dist/lib.cjs.js +3 -3
  3. package/dist/package.json +172 -0
  4. package/dist/src/cli.js +15 -0
  5. package/dist/src/constants.js +25 -0
  6. package/dist/src/index.js +4 -0
  7. package/dist/src/oauth/authorizationCodeGrant.js +56 -0
  8. package/dist/src/oauth/clientCredentialsGrant.js +25 -0
  9. package/dist/src/oauth/createTokenStore.js +8 -0
  10. package/dist/src/oauth/implicitGrant.js +24 -0
  11. package/dist/src/oauth/makeFetchTokenRequester.js +38 -0
  12. package/dist/src/oauth/maybeUpdateToken.js +44 -0
  13. package/dist/src/oauth/passwordGrant.js +30 -0
  14. package/dist/src/oauth/refreshTokenGrant.js +26 -0
  15. package/dist/src/oauth/requestAndSaveToStore.js +5 -0
  16. package/dist/src/oauth/types.js +1 -0
  17. package/dist/src/rest/delete.js +3 -0
  18. package/dist/src/rest/get.js +3 -0
  19. package/dist/src/rest/index.js +160 -0
  20. package/dist/src/rest/methods/agent.js +26 -0
  21. package/dist/src/rest/methods/app.js +10 -0
  22. package/dist/src/rest/methods/booking.js +6 -0
  23. package/dist/src/rest/methods/bucket.js +22 -0
  24. package/dist/src/rest/methods/conversation.js +28 -0
  25. package/dist/src/rest/methods/file.js +11 -0
  26. package/dist/src/rest/methods/group.js +22 -0
  27. package/dist/src/rest/methods/idLookup.js +12 -0
  28. package/dist/src/rest/methods/notification.js +57 -0
  29. package/dist/src/rest/methods/notificationSettings.js +19 -0
  30. package/dist/src/rest/methods/property.js +17 -0
  31. package/dist/src/rest/methods/registrationCode.js +24 -0
  32. package/dist/src/rest/methods/serviceProvider.js +9 -0
  33. package/dist/src/rest/methods/ticket.js +34 -0
  34. package/dist/src/rest/methods/unit.js +95 -0
  35. package/dist/src/rest/methods/user.js +134 -0
  36. package/dist/src/rest/methods/userRelation.js +22 -0
  37. package/dist/src/rest/methods/utilisationPeriod.js +49 -0
  38. package/dist/src/rest/patch.js +3 -0
  39. package/dist/src/rest/post.js +3 -0
  40. package/dist/src/rest/put.js +3 -0
  41. package/dist/src/rest/request.js +159 -0
  42. package/dist/src/rest/types.js +62 -0
  43. package/dist/src/utils/environment.js +1 -0
  44. package/dist/src/utils/functional.js +14 -0
  45. package/dist/src/utils/logger.js +15 -0
  46. package/dist/src/utils/object.js +6 -0
  47. package/dist/src/utils/queryString.js +13 -0
  48. package/dist/src/utils/random.js +7 -0
  49. package/dist/src/utils/sleep.js +3 -0
  50. package/dist/src/utils/string.js +6 -0
  51. package/dist/src/utils/stringToDate.js +6 -0
  52. package/dist/src/utils/upload.js +24 -0
  53. package/package.json +12 -9
  54. package/dist/lib.esm.js +0 -1350
@@ -0,0 +1,134 @@
1
+ export var EnumGender;
2
+ (function (EnumGender) {
3
+ EnumGender["female"] = "female";
4
+ EnumGender["male"] = "male";
5
+ })(EnumGender || (EnumGender = {}));
6
+ export var EnumUserType;
7
+ (function (EnumUserType) {
8
+ EnumUserType["allthingsUser"] = "allthings_user";
9
+ EnumUserType["allthingsContent"] = "allthings_content";
10
+ EnumUserType["customer"] = "customer";
11
+ EnumUserType["demoContent"] = "demo_content";
12
+ EnumUserType["demoPublic"] = "demo_public";
13
+ EnumUserType["partner"] = "partner";
14
+ })(EnumUserType || (EnumUserType = {}));
15
+ export var EnumCommunicationPreferenceChannel;
16
+ (function (EnumCommunicationPreferenceChannel) {
17
+ EnumCommunicationPreferenceChannel["push"] = "push";
18
+ EnumCommunicationPreferenceChannel["email"] = "email";
19
+ })(EnumCommunicationPreferenceChannel || (EnumCommunicationPreferenceChannel = {}));
20
+ export var EnumUserPermissionRole;
21
+ (function (EnumUserPermissionRole) {
22
+ EnumUserPermissionRole["appAdmin"] = "app-admin";
23
+ EnumUserPermissionRole["appOwner"] = "app-owner";
24
+ EnumUserPermissionRole["articlesAgent"] = "articles-agent";
25
+ EnumUserPermissionRole["articlesViewOnly"] = "articles-view-only";
26
+ EnumUserPermissionRole["bookableAssetAgent"] = "bookable-asset-agent";
27
+ EnumUserPermissionRole["bookingAgent"] = "booking-agent";
28
+ EnumUserPermissionRole["cockpitManager"] = "cockpit-manager";
29
+ EnumUserPermissionRole["dataConnectorAdmin"] = "data-connector-admin";
30
+ EnumUserPermissionRole["documentAdmin"] = "doc-admin";
31
+ EnumUserPermissionRole["externalAgent"] = "external-agent";
32
+ EnumUserPermissionRole["globalOrgAdmin"] = "global-org-admin";
33
+ EnumUserPermissionRole["globalUserAdmin"] = "global-user-admin";
34
+ EnumUserPermissionRole["orgAdmin"] = "org-admin";
35
+ EnumUserPermissionRole["orgTeamManager"] = "org-team-manager";
36
+ EnumUserPermissionRole["pinboardAgent"] = "pinboard-agent";
37
+ EnumUserPermissionRole["platformOwner"] = "platform-owner";
38
+ EnumUserPermissionRole["qa"] = "qa";
39
+ EnumUserPermissionRole["serviceCenterAgent"] = "service-center-agent";
40
+ EnumUserPermissionRole["serviceCenterManager"] = "service-center-manager";
41
+ EnumUserPermissionRole["setup"] = "setup";
42
+ EnumUserPermissionRole["tenantManager"] = "tenant-manager";
43
+ })(EnumUserPermissionRole || (EnumUserPermissionRole = {}));
44
+ export var EnumUserPermissionObjectType;
45
+ (function (EnumUserPermissionObjectType) {
46
+ EnumUserPermissionObjectType["app"] = "App";
47
+ EnumUserPermissionObjectType["group"] = "Group";
48
+ EnumUserPermissionObjectType["property"] = "Property";
49
+ EnumUserPermissionObjectType["unit"] = "Unit";
50
+ })(EnumUserPermissionObjectType || (EnumUserPermissionObjectType = {}));
51
+ const remapUserResult = (user) => {
52
+ const { tenantIDs: tenantIds, ...result } = user;
53
+ return { ...result, tenantIds };
54
+ };
55
+ export const remapEmbeddedUser = (embedded) => embedded.users ? embedded.users.map(remapUserResult) : [];
56
+ export async function userCreate(client, appId, username, data) {
57
+ return client.post('/v1/users', {
58
+ ...data,
59
+ creationContext: appId,
60
+ username,
61
+ });
62
+ }
63
+ export async function getUsers(client, page = 1, limit = -1, filter = {}) {
64
+ const { _embedded: { items: users }, total, } = await client.get('/v1/users', {
65
+ filter: JSON.stringify(filter),
66
+ limit,
67
+ page,
68
+ });
69
+ return { _embedded: { items: users.map(remapUserResult) }, total };
70
+ }
71
+ export async function getCurrentUser(client) {
72
+ return remapUserResult(await client.get('/v1/me'));
73
+ }
74
+ export async function userGetById(client, userId) {
75
+ return remapUserResult(await client.get(`/v1/users/${userId}`));
76
+ }
77
+ export async function userUpdateById(client, userId, data) {
78
+ const { tenantIds: tenantIDs, ...rest } = data;
79
+ return remapUserResult(await client.patch(`/v1/users/${userId}`, { ...rest, tenantIDs }));
80
+ }
81
+ export async function userCreatePermission(client, userId, data) {
82
+ const { objectId: objectID, ...rest } = data;
83
+ const { objectID: resultObjectId, ...result } = await client.post(`/v1/users/${userId}/permissions`, {
84
+ ...rest,
85
+ objectID,
86
+ });
87
+ return {
88
+ ...result,
89
+ objectId: resultObjectId,
90
+ };
91
+ }
92
+ export async function userCreatePermissionBatch(client, userId, permissions) {
93
+ const { objectId, objectType, roles, startDate, endDate } = permissions;
94
+ const batch = {
95
+ batch: roles.map((role) => ({
96
+ endDate: endDate?.toISOString(),
97
+ objectID: objectId,
98
+ objectType,
99
+ restrictions: [],
100
+ role,
101
+ startDate: startDate?.toISOString(),
102
+ })),
103
+ };
104
+ return !(await client.post(`/v1/users/${userId}/permissions`, batch));
105
+ }
106
+ export async function userGetPermissions(client, userId) {
107
+ const { _embedded: { items: permissions }, } = await client.get(`/v1/users/${userId}/roles?limit=-1`);
108
+ return permissions.map(({ objectID: objectId, ...result }) => ({
109
+ ...result,
110
+ objectId,
111
+ }));
112
+ }
113
+ export async function userDeletePermission(client, permissionId) {
114
+ return !(await client.delete(`/v1/permissions/${permissionId}`));
115
+ }
116
+ export async function userGetUtilisationPeriods(client, userId) {
117
+ const { _embedded: { items: utilisationPeriods }, } = await client.get(`/v1/users/${userId}/utilisation-periods`);
118
+ return utilisationPeriods;
119
+ }
120
+ export async function userCheckInToUtilisationPeriod(client, userId, utilisationPeriodId) {
121
+ const { email: userEmail } = await client.userGetById(userId);
122
+ return client.utilisationPeriodCheckInUser(utilisationPeriodId, {
123
+ email: userEmail,
124
+ });
125
+ }
126
+ export async function userGetByEmail(client, email, page = 1, limit = 1000) {
127
+ return client.getUsers(page, limit, { email });
128
+ }
129
+ export async function userChangePassword(client, userId, currentPassword, newPassword) {
130
+ return !(await client.put(`/v1/users/${userId}/password`, {
131
+ currentPassword,
132
+ plainPassword: newPassword,
133
+ }));
134
+ }
@@ -0,0 +1,22 @@
1
+ export var EnumUserRelationType;
2
+ (function (EnumUserRelationType) {
3
+ EnumUserRelationType["isResponsible"] = "is-responsible";
4
+ })(EnumUserRelationType || (EnumUserRelationType = {}));
5
+ export async function userRelationCreate(client, userId, data) {
6
+ return client.post(`/v1/users/${userId}/user-relations/${data.type}`, {
7
+ ids: data.ids,
8
+ level: data.level,
9
+ readOnly: data.readOnly,
10
+ role: data.role,
11
+ });
12
+ }
13
+ export async function userRelationDelete(client, userId, data) {
14
+ return client.delete(`/v1/users/${userId}/user-relations/${data.type}`, {
15
+ ids: data.ids,
16
+ level: data.level,
17
+ role: data.role,
18
+ });
19
+ }
20
+ export async function userRelationsGetByUser(client, userId) {
21
+ return client.get(`/v1/users/${userId}/user-relations`);
22
+ }
@@ -0,0 +1,49 @@
1
+ import { remapRegistationCodeResult, } from './registrationCode';
2
+ import { remapEmbeddedUser } from './user';
3
+ export var EnumUtilisationPeriodType;
4
+ (function (EnumUtilisationPeriodType) {
5
+ EnumUtilisationPeriodType["tenant"] = "tenant";
6
+ EnumUtilisationPeriodType["ownership"] = "ownership";
7
+ EnumUtilisationPeriodType["vacant"] = "vacant";
8
+ })(EnumUtilisationPeriodType || (EnumUtilisationPeriodType = {}));
9
+ export async function utilisationPeriodCreate(client, unitId, data) {
10
+ const { tenantIDs: tenantIds, _embedded, ...result } = await client.post(`/v1/units/${unitId}/utilisation-periods`, data);
11
+ return {
12
+ ...result,
13
+ invitations: _embedded.invitations.map(remapRegistationCodeResult),
14
+ tenantIds,
15
+ users: remapEmbeddedUser(_embedded),
16
+ };
17
+ }
18
+ export async function utilisationPeriodGetById(client, utilisationPeriodId) {
19
+ const { tenantIDs: tenantIds, _embedded, ...result } = await client.get(`/v1/utilisation-periods/${utilisationPeriodId}`);
20
+ return {
21
+ ...result,
22
+ invitations: _embedded.invitations.map(remapRegistationCodeResult),
23
+ tenantIds,
24
+ users: remapEmbeddedUser(_embedded),
25
+ };
26
+ }
27
+ export async function utilisationPeriodUpdateById(client, utilisationPeriodId, data) {
28
+ const { tenantIDs: tenantIds, _embedded, ...result } = await client.patch(`/v1/utilisation-periods/${utilisationPeriodId}`, data);
29
+ return {
30
+ ...result,
31
+ invitations: _embedded.invitations.map(remapRegistationCodeResult),
32
+ tenantIds,
33
+ users: remapEmbeddedUser(_embedded),
34
+ };
35
+ }
36
+ export async function utilisationPeriodDelete(client, utilisationPeriodId) {
37
+ return !(await client.delete(`/v1/utilisation-periods/${utilisationPeriodId}/soft`));
38
+ }
39
+ export async function utilisationPeriodCheckInUser(client, utilisationPeriodId, data) {
40
+ return ((await client.post(`/v1/utilisation-periods/${utilisationPeriodId}/users`, {
41
+ email: data.email,
42
+ })) && client.utilisationPeriodGetById(utilisationPeriodId));
43
+ }
44
+ export async function utilisationPeriodCheckOutUser(client, utilisationPeriodId, userId) {
45
+ return ((await client.delete(`/v1/utilisation-periods/${utilisationPeriodId}/users/${userId}`)) === '');
46
+ }
47
+ export async function utilisationPeriodAddRegistrationCode(client, utilisationPeriodId, code, tenant, permanent = false) {
48
+ return client.post(`/v1/utilisation-periods/${utilisationPeriodId}/registration-codes`, { code, permanent, tenant });
49
+ }
@@ -0,0 +1,3 @@
1
+ export default async function patch(request, method, body, returnRawResultObject, headers) {
2
+ return request('patch', method, { body, headers }, returnRawResultObject);
3
+ }
@@ -0,0 +1,3 @@
1
+ export default async function post(request, method, body, returnRawResultObject, headers) {
2
+ return request('post', method, { body, headers }, returnRawResultObject);
3
+ }
@@ -0,0 +1,3 @@
1
+ export default async function put(request, method, body, returnRawResultObject, headers) {
2
+ return request('put', method, { body, headers }, returnRawResultObject);
3
+ }
@@ -0,0 +1,159 @@
1
+ import Bottleneck from 'bottleneck';
2
+ import { QUEUE_CONCURRENCY, QUEUE_DELAY, QUEUE_RESERVOIR, QUEUE_RESERVOIR_REFILL_INTERVAL, USER_AGENT, } from '../constants';
3
+ import maybeUpdateToken from '../oauth/maybeUpdateToken';
4
+ import { environment } from '../utils/environment';
5
+ import { clearIntervalFunction, until } from '../utils/functional';
6
+ import makeLogger from '../utils/logger';
7
+ import { buildQueryString } from '../utils/queryString';
8
+ import sleep from '../utils/sleep';
9
+ const requestLogger = makeLogger('REST API Request');
10
+ const responseLogger = makeLogger('REST API Response');
11
+ const RETRYABLE_STATUS_CODES = [401, 408, 429, 502, 503, 504];
12
+ const TOKEN_REFRESH_STATUS_CODES = [401];
13
+ const queue = new Bottleneck({
14
+ maxConcurrent: QUEUE_CONCURRENCY,
15
+ minTime: QUEUE_DELAY,
16
+ reservoir: QUEUE_RESERVOIR,
17
+ });
18
+ const refillIntervalSet = new Set();
19
+ function isFormData(body) {
20
+ return typeof body !== 'undefined' && body.formData !== undefined;
21
+ }
22
+ function refillReservoir() {
23
+ if (refillIntervalSet.size === 0) {
24
+ const interval = setInterval(async () => {
25
+ const reservoir = (await queue.currentReservoir());
26
+ if (queue.empty() && (await queue.running()) === 0 && reservoir > 10) {
27
+ return ((await queue.incrementReservoir(1)) &&
28
+ clearIntervalFunction(interval) &&
29
+ refillIntervalSet.delete(interval));
30
+ }
31
+ return reservoir < QUEUE_RESERVOIR
32
+ ? queue.incrementReservoir(1)
33
+ : clearIntervalFunction(interval) && refillIntervalSet.delete(interval);
34
+ }, QUEUE_RESERVOIR_REFILL_INTERVAL);
35
+ return refillIntervalSet.add(interval);
36
+ }
37
+ return refillIntervalSet;
38
+ }
39
+ async function makeResultFromResponse(response) {
40
+ if (RETRYABLE_STATUS_CODES.includes(response.status)) {
41
+ return response.clone();
42
+ }
43
+ if (!response.ok) {
44
+ return new Error(`${response.status} ${response.statusText}\n\n${await response.text()}`);
45
+ }
46
+ if (response.headers.get('content-type') !== 'application/json' &&
47
+ response.status !== 204) {
48
+ return new Error(`Response content type was "${response.headers.get('content-type')}" but expected JSON`);
49
+ }
50
+ return {
51
+ body: response.status === 204 ? '' : await response.json(),
52
+ status: response.status,
53
+ };
54
+ }
55
+ export function responseWasSuccessful(response) {
56
+ return !RETRYABLE_STATUS_CODES.includes(response.status);
57
+ }
58
+ export function makeApiRequest(oauthTokenStore, oauthTokenRequester, options, httpMethod, apiMethod, payload, returnRawResultObject) {
59
+ return async (previousResult, retryCount) => {
60
+ if (retryCount > 0) {
61
+ if (retryCount > options.requestMaxRetries) {
62
+ const error = `Maximum number of retries reached while retrying ${previousResult.method} request ${previousResult.path}.`;
63
+ requestLogger.error(error);
64
+ throw new Error(error);
65
+ }
66
+ requestLogger.warn(`Warning: encountered ${previousResult.status}. Retrying ${previousResult.method} request ${previousResult.path} (retry #${retryCount}).`);
67
+ await sleep(Math.ceil(Math.random() *
68
+ options.requestBackOffInterval *
69
+ 2 ** retryCount));
70
+ }
71
+ await maybeUpdateToken(oauthTokenStore, oauthTokenRequester, options, retryCount > 0 &&
72
+ TOKEN_REFRESH_STATUS_CODES.includes(previousResult.status));
73
+ const payloadQuery = payload?.query
74
+ ? (apiMethod.includes('?') ? '&' : '?') + buildQueryString(payload.query)
75
+ : '';
76
+ const url = `${options.apiUrl}/api${apiMethod}${payloadQuery}`;
77
+ if (!oauthTokenStore.get('accessToken')) {
78
+ throw new Error(`Unable to get OAuth2 access token. Error trying to call endpoint: ${url}`);
79
+ }
80
+ try {
81
+ return (refillReservoir() &&
82
+ (await queue.schedule(async () => {
83
+ const method = httpMethod.toUpperCase();
84
+ const body = payload?.body;
85
+ const hasForm = isFormData(body);
86
+ const form = isFormData(body) ? body.formData : {};
87
+ const formData = Object.entries(form).reduce((previous, [name, value]) => {
88
+ if (Array.isArray(value)) {
89
+ const [content, filename] = value;
90
+ const blobContent = content instanceof Blob ? content : new Blob([content]);
91
+ previous.append(name, blobContent, filename);
92
+ }
93
+ else {
94
+ previous.append(name, value);
95
+ }
96
+ return previous;
97
+ }, new FormData());
98
+ const headers = {
99
+ accept: 'application/json',
100
+ authorization: `Bearer ${oauthTokenStore.get('accessToken')}`,
101
+ 'X-Allthings-Caller': `${options.serviceName
102
+ ? options.serviceName
103
+ :
104
+ environment.SERVICE_NAME
105
+ ? environment.SERVICE_NAME
106
+ : 'unknown service name'} --- clientID ${options.clientId?.split('_')[0] ??
107
+ options.clientId ??
108
+ 'no client id present'}`,
109
+ ...(hasForm ? {} : { 'content-type': 'application/json' }),
110
+ ...(typeof window === 'undefined' &&
111
+ typeof document === 'undefined' && { 'user-agent': USER_AGENT }),
112
+ ...payload?.headers,
113
+ };
114
+ if (environment.LOG_REQUEST) {
115
+ console.log({ sdkLogs: { method, url } });
116
+ }
117
+ requestLogger.log(method, url, {
118
+ body,
119
+ headers,
120
+ });
121
+ const requestBody = {
122
+ body: hasForm ? formData : JSON.stringify(body),
123
+ };
124
+ const response = await fetch(url, {
125
+ cache: 'no-cache',
126
+ credentials: 'omit',
127
+ headers,
128
+ method,
129
+ mode: 'cors',
130
+ ...(hasForm || body ? requestBody : {}),
131
+ });
132
+ const result = await makeResultFromResponse(response);
133
+ responseLogger.log(method, url, result instanceof Error
134
+ ? { error: result }
135
+ : {
136
+ body: result.body,
137
+ status: response.status,
138
+ });
139
+ return result instanceof Error && returnRawResultObject
140
+ ? {
141
+ body: result.message,
142
+ status: response.status,
143
+ }
144
+ : result;
145
+ })));
146
+ }
147
+ catch (error) {
148
+ return error;
149
+ }
150
+ };
151
+ }
152
+ export default async function request(oauthTokenStore, oauthTokenRequester, options, httpMethod, apiMethod, payload, returnRawResultObject) {
153
+ const result = await until(responseWasSuccessful, makeApiRequest(oauthTokenStore, oauthTokenRequester, options, httpMethod, apiMethod, payload, returnRawResultObject));
154
+ if (result instanceof Error) {
155
+ requestLogger.log('Request Error', result, payload);
156
+ throw result;
157
+ }
158
+ return returnRawResultObject ? result : result.body;
159
+ }
@@ -0,0 +1,62 @@
1
+ export var EnumResource;
2
+ (function (EnumResource) {
3
+ EnumResource["group"] = "group";
4
+ EnumResource["property"] = "property";
5
+ EnumResource["serviceProvider"] = "propertyManager";
6
+ EnumResource["registrationCode"] = "registrationCode";
7
+ EnumResource["unit"] = "unit";
8
+ EnumResource["user"] = "user";
9
+ EnumResource["utilisationPeriod"] = "utilisationPeriod";
10
+ })(EnumResource || (EnumResource = {}));
11
+ export var EnumCountryCode;
12
+ (function (EnumCountryCode) {
13
+ EnumCountryCode["CH"] = "CH";
14
+ EnumCountryCode["DE"] = "DE";
15
+ EnumCountryCode["FR"] = "FR";
16
+ EnumCountryCode["IT"] = "IT";
17
+ EnumCountryCode["NL"] = "NL";
18
+ EnumCountryCode["PT"] = "PT";
19
+ EnumCountryCode["US"] = "US";
20
+ })(EnumCountryCode || (EnumCountryCode = {}));
21
+ export var EnumLocale;
22
+ (function (EnumLocale) {
23
+ EnumLocale["ch_de"] = "ch_DE";
24
+ EnumLocale["ch_fr"] = "ch_FR";
25
+ EnumLocale["ch_it"] = "ch_it";
26
+ EnumLocale["de_DE"] = "de_DE";
27
+ EnumLocale["it_IT"] = "it_IT";
28
+ EnumLocale["fr_FR"] = "fr_FR";
29
+ EnumLocale["pt_PT"] = "pt_PT";
30
+ EnumLocale["en_US"] = "en_US";
31
+ })(EnumLocale || (EnumLocale = {}));
32
+ export var EnumTimezone;
33
+ (function (EnumTimezone) {
34
+ EnumTimezone["EuropeBerlin"] = "Europe/Berlin";
35
+ EnumTimezone["EuropeLondon"] = "Europe/London";
36
+ EnumTimezone["EuropeSofia"] = "Europe/Sofia";
37
+ EnumTimezone["EuropeZurich"] = "Europe/Zurich";
38
+ EnumTimezone["UTC"] = "UTC";
39
+ })(EnumTimezone || (EnumTimezone = {}));
40
+ export var EnumServiceProviderType;
41
+ (function (EnumServiceProviderType) {
42
+ EnumServiceProviderType["propertyManager"] = "property-manager";
43
+ EnumServiceProviderType["craftspeople"] = "craftspeople";
44
+ })(EnumServiceProviderType || (EnumServiceProviderType = {}));
45
+ export var EnumCommunicationMethodType;
46
+ (function (EnumCommunicationMethodType) {
47
+ EnumCommunicationMethodType["email"] = "email";
48
+ })(EnumCommunicationMethodType || (EnumCommunicationMethodType = {}));
49
+ export var EnumInputChannel;
50
+ (function (EnumInputChannel) {
51
+ EnumInputChannel["APP"] = "app";
52
+ EnumInputChannel["COCKPIT"] = "cockpit";
53
+ EnumInputChannel["CRAFTSMEN"] = "craftsmen";
54
+ EnumInputChannel["EMAIL"] = "email";
55
+ EnumInputChannel["PHONE"] = "phone";
56
+ EnumInputChannel["WHATS_APP"] = "whats_app";
57
+ })(EnumInputChannel || (EnumInputChannel = {}));
58
+ export var EnumLookupUserType;
59
+ (function (EnumLookupUserType) {
60
+ EnumLookupUserType["agent"] = "agent";
61
+ EnumLookupUserType["tenant"] = "tenant";
62
+ })(EnumLookupUserType || (EnumLookupUserType = {}));
@@ -0,0 +1 @@
1
+ export const environment = typeof process !== 'undefined' && process.env ? process.env : {};
@@ -0,0 +1,14 @@
1
+ export const partial = (function_, ...partialArguments) => (...arguments_) => function_(...partialArguments, ...arguments_);
2
+ export function times(function_, n) {
3
+ return [...new Array(n)].map(function_);
4
+ }
5
+ export async function until(predicate, transformer, initialValue, iterationCount = 0) {
6
+ const transformed = await transformer(initialValue, iterationCount);
7
+ return (await predicate(transformed, iterationCount))
8
+ ? transformed
9
+ : until(predicate, transformer, transformed, iterationCount + 1);
10
+ }
11
+ export function clearIntervalFunction(intervalId) {
12
+ clearInterval(intervalId);
13
+ return true;
14
+ }
@@ -0,0 +1,15 @@
1
+ import { environment } from './environment';
2
+ const SUBSCRIPTIONS = environment.DEBUG?.split(',').map((item) => item.trim()) || [];
3
+ export default function makeLogger(name) {
4
+ return ['log', 'info', 'warn', 'error'].reduce((logger, type) => ({
5
+ ...logger,
6
+ [type]: function log(...logs) {
7
+ if (SUBSCRIPTIONS.includes('*') ||
8
+ SUBSCRIPTIONS.includes(name) ||
9
+ SUBSCRIPTIONS.includes(name.toLocaleLowerCase())) {
10
+ console[type](`${name}:`, ...logs);
11
+ }
12
+ return true;
13
+ },
14
+ }), {});
15
+ }
@@ -0,0 +1,6 @@
1
+ export function remapKeys(input, mapFunction) {
2
+ return Object.entries(input).reduce((accumulator, entry) => ({
3
+ ...accumulator,
4
+ [mapFunction(entry[0])]: entry[1],
5
+ }), {});
6
+ }
@@ -0,0 +1,13 @@
1
+ export function buildQueryString(params) {
2
+ const usp = new URLSearchParams();
3
+ for (const [key, value] of Object.entries(params).sort(([a], [b]) => a.localeCompare(b))) {
4
+ if (value != null && value !== '') {
5
+ usp.append(key, String(value));
6
+ }
7
+ }
8
+ return usp.toString();
9
+ }
10
+ export function parseQueryString(query) {
11
+ const cleaned = query.startsWith('#') ? query.slice(1) : query;
12
+ return Object.fromEntries(new URLSearchParams(cleaned));
13
+ }
@@ -0,0 +1,7 @@
1
+ export function pseudoRandomString(length = 16) {
2
+ let token = '';
3
+ while (token.length < length) {
4
+ token += Math.random().toString(36).slice(2);
5
+ }
6
+ return token.slice(0, Math.max(0, length));
7
+ }
@@ -0,0 +1,3 @@
1
+ export default function sleep(milliseconds) {
2
+ return new Promise((resolve) => setTimeout(() => resolve(true), milliseconds));
3
+ }
@@ -0,0 +1,6 @@
1
+ export function camelCaseToDash(input) {
2
+ return input.replace(/([A-Z])/g, (g) => `-${g[0].toLowerCase()}`);
3
+ }
4
+ export function dashCaseToCamel(input) {
5
+ return input.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
6
+ }
@@ -0,0 +1,6 @@
1
+ export function stringToDate(s) {
2
+ return new Date(Date.parse(s));
3
+ }
4
+ export function dateToString(d) {
5
+ return d.toISOString();
6
+ }
@@ -0,0 +1,24 @@
1
+ export const createManyFiles = async (attachments, apiClient) => {
2
+ const responses = await Promise.all(attachments.map(async (attachment) => {
3
+ try {
4
+ const result = await apiClient.fileCreate({
5
+ file: attachment.content,
6
+ name: attachment.filename,
7
+ });
8
+ return result;
9
+ }
10
+ catch (error) {
11
+ return error instanceof Error ? error : new Error(String(error));
12
+ }
13
+ }));
14
+ return responses;
15
+ };
16
+ export async function createManyFilesSorted(files, client) {
17
+ const result = await createManyFiles(files, client);
18
+ return {
19
+ error: result.filter((item) => item instanceof Error),
20
+ success: result
21
+ .filter((item) => !(item instanceof Error))
22
+ .map((item) => item.id),
23
+ };
24
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@allthings/sdk",
3
- "version": "10.0.0-beta.1",
3
+ "version": "10.0.0-beta.3",
4
4
  "description": "",
5
5
  "author": "Allthings GmbH",
6
6
  "keywords": [
@@ -21,15 +21,15 @@
21
21
  "repositoryUrl": "https://github.com/allthings/node-sdk.git"
22
22
  },
23
23
  "main": "dist/lib.cjs.js",
24
- "module": "dist/lib.esm.js",
25
- "browser": "dist/lib.esm.js",
24
+ "module": "dist/src/index.js",
25
+ "browser": "dist/src/index.js",
26
26
  "types": "dist/src/index.d.ts",
27
27
  "exports": {
28
28
  ".": {
29
29
  "types": "./dist/src/index.d.ts",
30
- "browser": "./dist/lib.esm.js",
31
- "import": "./dist/lib.esm.js",
32
- "require": "./dist/lib.cjs.js"
30
+ "require": "./dist/lib.cjs.js",
31
+ "browser": "./dist/src/index.js",
32
+ "import": "./dist/src/index.js"
33
33
  },
34
34
  "./package.json": "./package.json"
35
35
  },
@@ -37,8 +37,11 @@
37
37
  "./dist/cli.js"
38
38
  ],
39
39
  "files": [
40
- "dist/*.js",
41
- "dist/**/*.d.ts"
40
+ "dist/cli.js",
41
+ "dist/lib.cjs.js",
42
+ "dist/package.json",
43
+ "dist/src/**/*.js",
44
+ "dist/src/**/*.d.ts"
42
45
  ],
43
46
  "bin": {
44
47
  "allthings": "dist/cli.js"
@@ -52,7 +55,7 @@
52
55
  "lint": "yarn lint:tsc && yarn lint:eslint",
53
56
  "lint:eslint": "eslint src",
54
57
  "lint:tsc": "tsc --noEmit --pretty",
55
- "build": "npm run clean && tsc -d -p tsconfig.build.json && cp package.json dist/ && rollup -c --bundleConfigAsCjs && rm dist/package.json",
58
+ "build": "npm run clean && tsc -d -p tsconfig.build.json && cp package.json dist/ && rollup -c --bundleConfigAsCjs",
56
59
  "dev": "tsc -w",
57
60
  "prepare": "husky",
58
61
  "prepublishOnly": "npm run build",