@allthings/sdk
Version:
Allthings Node/Javascript SDK
1,408 lines (1,301 loc) • 300 kB
JavaScript
'use strict';
var querystring = require('query-string');
var fetch = require('cross-fetch');
var Bottleneck = require('bottleneck');
var require$$1 = require('util');
var require$$0$1 = require('stream');
var require$$1$1 = require('path');
var require$$3 = require('http');
var require$$4 = require('https');
var require$$5 = require('url');
var require$$6 = require('fs');
function createTokenStore(initialToken) {
const token = new Map(Object.entries(initialToken || {}));
return {
get: (key) => token.get(key),
reset: () => token.clear(),
set: (update) => Object.entries(update).forEach(([key, value]) => token.set(key, value)),
};
}
const version = "8.0.0";
const REST_API_URL = 'https://api.allthings.me';
const OAUTH_URL = 'https://accounts.allthings.me';
const QUEUE_CONCURRENCY = undefined;
const QUEUE_DELAY = 0;
const QUEUE_RESERVOIR = 30;
const QUEUE_RESERVOIR_REFILL_INTERVAL = 166;
const REQUEST_BACK_OFF_INTERVAL = 200;
const REQUEST_MAX_RETRIES = 50;
const DEFAULT_API_WRAPPER_OPTIONS = {
apiUrl: process.env.ALLTHINGS_REST_API_URL || REST_API_URL,
clientId: process.env.ALLTHINGS_OAUTH_CLIENT_ID,
clientSecret: process.env.ALLTHINGS_OAUTH_CLIENT_SECRET,
oauthUrl: process.env.ALLTHINGS_OAUTH_URL || OAUTH_URL,
password: process.env.ALLTHINGS_OAUTH_PASSWORD,
requestBackOffInterval: REQUEST_BACK_OFF_INTERVAL,
requestMaxRetries: REQUEST_MAX_RETRIES,
scope: 'user:profile',
username: process.env.ALLTHINGS_OAUTH_USERNAME,
};
const USER_AGENT = `Allthings Node SDK REST Client/${version}`;
const RESPONSE_TYPE$1 = 'code';
const GRANT_TYPE$3 = 'authorization_code';
const castToAuthorizationRequestParams$1 = (params) => {
const { redirectUri, clientId, scope, state } = params;
if (!clientId) {
throw new Error('Missing required "clientId" parameter to perform authorization code grant redirect');
}
if (!redirectUri) {
throw new Error('Missing required "redirectUri" parameter to perform authorization code grant redirect');
}
return Object.assign(Object.assign({ client_id: clientId, redirect_uri: redirectUri, response_type: RESPONSE_TYPE$1 }, (scope ? { scope } : {})), (state ? { state } : {}));
};
const isEligibleForClientRedirect$1 = (params) => {
try {
return !!castToAuthorizationRequestParams$1(params);
}
catch (_a) {
return false;
}
};
const getRedirectUrl$1 = (params) => `${params.oauthUrl}/oauth/authorize?${querystring.stringify(castToAuthorizationRequestParams$1(params), {
skipEmptyString: true,
skipNull: true,
})}`;
const castToTokenRequestParams$2 = (params) => {
const { authorizationCode, redirectUri, clientId, clientSecret } = params;
if (!clientId) {
throw new Error('Missing required "clientId" parameter to perform authorization code grant');
}
if (!redirectUri) {
throw new Error('Missing required "redirectUri" parameter to perform authorization code grant');
}
if (!authorizationCode) {
throw new Error('Missing required "authorizationCode" parameter to perform authorization code grant');
}
return Object.assign({ client_id: clientId, code: authorizationCode, grant_type: GRANT_TYPE$3, redirect_uri: redirectUri }, (clientSecret ? { client_secret: clientSecret } : {}));
};
const isEligible$3 = (params) => {
try {
return !!castToTokenRequestParams$2(params);
}
catch (_a) {
return false;
}
};
const requestToken$3 = (tokenRequester, params) => tokenRequester(castToTokenRequestParams$2(params));
const SUBSCRIPTIONS = (process.env.DEBUG &&
process.env.DEBUG.split(',').map((item) => item.trim())) ||
[];
function makeLogger(name) {
return ['log', 'info', 'warn', 'error'].reduce((logger, type) => (Object.assign(Object.assign({}, logger), { [type]: function log(...logs) {
if (SUBSCRIPTIONS.includes('*') ||
SUBSCRIPTIONS.includes(name) ||
SUBSCRIPTIONS.includes(name.toLocaleLowerCase())) {
console[type](`${name}:`, ...logs);
}
return true;
} })), {});
}
const logger = makeLogger('OAuth Token Request');
const makeFetchTokenRequester = (url) => async (params) => {
try {
const response = await fetch(url, {
body: querystring.stringify(params, {
skipEmptyString: true,
skipNull: true,
}),
cache: 'no-cache',
credentials: 'omit',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
accept: 'application/json',
'user-agent': USER_AGENT,
},
method: 'POST',
mode: 'cors',
});
if (response.status !== 200) {
throw response;
}
const { access_token: newAccessToken, refresh_token: newRefreshToken, expires_in: expiresIn, } = await response.json();
return {
accessToken: newAccessToken,
expiresIn,
refreshToken: newRefreshToken,
};
}
catch (error) {
if (!error.status) {
throw error;
}
const errorName = `HTTP ${error.status} — ${error.statusText}`;
logger.error(errorName, error.response);
throw new Error(`HTTP ${error.status} — ${error.statusText}. Could not get token.`);
}
};
const GRANT_TYPE$2 = 'refresh_token';
const castToTokenRequestParams$1 = (params) => {
const { clientId, clientSecret, refreshToken, scope } = params;
if (!clientId) {
throw new Error('Missing required "clientId" parameter to perform refresh token grant');
}
if (!refreshToken) {
throw new Error('Missing required "refreshToken" parameter to perform refresh token grant');
}
return Object.assign(Object.assign({ client_id: clientId, grant_type: GRANT_TYPE$2, refresh_token: refreshToken }, (clientSecret ? { client_secret: clientSecret } : {})), (scope ? { scope } : {}));
};
const isEligible$2 = (params) => {
try {
return !!castToTokenRequestParams$1(params);
}
catch (_a) {
return false;
}
};
const requestToken$2 = (tokenRequester, params) => tokenRequester(castToTokenRequestParams$1(params));
async function requestAndSaveToStore(requester, tokenStore) {
const response = await requester();
tokenStore.set(response);
return response;
}
const partial = (fn, ...partialArgs) => (...args) => fn(...partialArgs, ...args);
async function until(predicate, transformer, initialValue, iterationCount = 0) {
const transformed = await transformer(initialValue, iterationCount);
return (await predicate(transformed, iterationCount))
? transformed
: until(predicate, transformer, transformed, iterationCount + 1);
}
function fnClearInterval(intervalId) {
clearInterval(intervalId);
return true;
}
function pseudoRandomString(length = 16) {
let token = '';
while (token.length < length) {
token += Math.random().toString(36).substr(2);
}
return token.substr(0, length);
}
async function del(request, method, body, returnRawResultObject, headers) {
return request('delete', method, { body, headers }, returnRawResultObject);
}
async function get$1(request, method, query, returnRawResultObject, headers) {
return request('get', method, { headers, query }, returnRawResultObject);
}
var __rest$4 = (undefined && undefined.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var EnumGender;
(function (EnumGender) {
EnumGender["female"] = "female";
EnumGender["male"] = "male";
})(EnumGender || (EnumGender = {}));
var EnumUserType;
(function (EnumUserType) {
EnumUserType["allthingsUser"] = "allthings_user";
EnumUserType["allthingsContent"] = "allthings_content";
EnumUserType["customer"] = "customer";
EnumUserType["demoContent"] = "demo_content";
EnumUserType["demoPublic"] = "demo_public";
EnumUserType["partner"] = "partner";
})(EnumUserType || (EnumUserType = {}));
exports.EnumCommunicationPreferenceChannel = void 0;
(function (EnumCommunicationPreferenceChannel) {
EnumCommunicationPreferenceChannel["push"] = "push";
EnumCommunicationPreferenceChannel["email"] = "email";
})(exports.EnumCommunicationPreferenceChannel || (exports.EnumCommunicationPreferenceChannel = {}));
exports.EnumUserPermissionRole = void 0;
(function (EnumUserPermissionRole) {
EnumUserPermissionRole["appAdmin"] = "app-admin";
EnumUserPermissionRole["appOwner"] = "app-owner";
EnumUserPermissionRole["articlesAgent"] = "articles-agent";
EnumUserPermissionRole["articlesViewOnly"] = "articles-view-only";
EnumUserPermissionRole["bookableAssetAgent"] = "bookable-asset-agent";
EnumUserPermissionRole["bookingAgent"] = "booking-agent";
EnumUserPermissionRole["cockpitManager"] = "cockpit-manager";
EnumUserPermissionRole["dataConnectorAdmin"] = "data-connector-admin";
EnumUserPermissionRole["documentAdmin"] = "doc-admin";
EnumUserPermissionRole["externalAgent"] = "external-agent";
EnumUserPermissionRole["globalOrgAdmin"] = "global-org-admin";
EnumUserPermissionRole["globalUserAdmin"] = "global-user-admin";
EnumUserPermissionRole["orgAdmin"] = "org-admin";
EnumUserPermissionRole["orgTeamManager"] = "org-team-manager";
EnumUserPermissionRole["pinboardAgent"] = "pinboard-agent";
EnumUserPermissionRole["platformOwner"] = "platform-owner";
EnumUserPermissionRole["qa"] = "qa";
EnumUserPermissionRole["serviceCenterAgent"] = "service-center-agent";
EnumUserPermissionRole["serviceCenterManager"] = "service-center-manager";
EnumUserPermissionRole["setup"] = "setup";
EnumUserPermissionRole["tenantManager"] = "tenant-manager";
})(exports.EnumUserPermissionRole || (exports.EnumUserPermissionRole = {}));
exports.EnumUserPermissionObjectType = void 0;
(function (EnumUserPermissionObjectType) {
EnumUserPermissionObjectType["app"] = "App";
EnumUserPermissionObjectType["group"] = "Group";
EnumUserPermissionObjectType["property"] = "Property";
EnumUserPermissionObjectType["unit"] = "Unit";
})(exports.EnumUserPermissionObjectType || (exports.EnumUserPermissionObjectType = {}));
const remapUserResult = (user) => {
const { tenantIDs: tenantIds } = user, result = __rest$4(user, ["tenantIDs"]);
return Object.assign(Object.assign({}, result), { tenantIds });
};
const remapEmbeddedUser = (embedded) => embedded.users ? embedded.users.map(remapUserResult) : [];
async function userCreate(client, appId, username, data) {
return client.post('/v1/users', Object.assign(Object.assign({}, data), { creationContext: appId, username }));
}
async function getUsers(client, page = 1, limit = -1, filter = {}) {
const { _embedded: { items: users }, total, } = await client.get('/v1/users', {
filter: JSON.stringify(filter),
limit,
page,
});
return { _embedded: { items: users.map(remapUserResult) }, total };
}
async function getCurrentUser(client) {
return remapUserResult(await client.get('/v1/me'));
}
async function userGetById(client, userId) {
return remapUserResult(await client.get(`/v1/users/${userId}`));
}
async function userUpdateById(client, userId, data) {
const { tenantIds: tenantIDs } = data, rest = __rest$4(data, ["tenantIds"]);
return remapUserResult(await client.patch(`/v1/users/${userId}`, Object.assign(Object.assign({}, rest), { tenantIDs })));
}
async function userCreatePermission(client, userId, data) {
const { objectId: objectID } = data, rest = __rest$4(data, ["objectId"]);
const _a = await client.post(`/v1/users/${userId}/permissions`, Object.assign(Object.assign({}, rest), { objectID })), { objectID: resultObjectId } = _a, result = __rest$4(_a, ["objectID"]);
return Object.assign(Object.assign({}, result), { objectId: resultObjectId });
}
async function userCreatePermissionBatch(client, userId, permissions) {
const { objectId, objectType, roles, startDate, endDate } = permissions;
const batch = {
batch: roles.map((role) => ({
endDate: endDate && endDate.toISOString(),
objectID: objectId,
objectType,
restrictions: [],
role,
startDate: startDate && startDate.toISOString(),
})),
};
return !(await client.post(`/v1/users/${userId}/permissions`, batch));
}
async function userGetPermissions(client, userId) {
const { _embedded: { items: permissions }, } = await client.get(`/v1/users/${userId}/roles?limit=-1`);
return permissions.map((_a) => {
var { objectID: objectId } = _a, result = __rest$4(_a, ["objectID"]);
return (Object.assign(Object.assign({}, result), { objectId }));
});
}
async function userDeletePermission(client, permissionId) {
return !(await client.delete(`/v1/permissions/${permissionId}`));
}
async function userGetUtilisationPeriods(client, userId) {
const { _embedded: { items: utilisationPeriods }, } = await client.get(`/v1/users/${userId}/utilisation-periods`);
return utilisationPeriods;
}
async function userCheckInToUtilisationPeriod(client, userId, utilisationPeriodId) {
const { email: userEmail } = await client.userGetById(userId);
return client.utilisationPeriodCheckInUser(utilisationPeriodId, {
email: userEmail,
});
}
async function userGetByEmail(client, email, page = 1, limit = 1000) {
return client.getUsers(page, limit, { email });
}
async function userChangePassword(client, userId, currentPassword, newPassword) {
return !(await client.put(`/v1/users/${userId}/password`, {
currentPassword,
plainPassword: newPassword,
}));
}
async function agentCreate(client, appId, propertyManagerId, username, data, sendInvitation, externalAgentCompany) {
const user = await client.userCreate(appId, username, Object.assign(Object.assign({}, data), { type: EnumUserType.customer }));
const manager = await client.post(`/v1/property-managers/${propertyManagerId}/users`, Object.assign({ userID: user.id }, (externalAgentCompany && { externalAgentCompany })));
return (!((typeof sendInvitation !== 'undefined' ? sendInvitation : true) &&
(await client.post(`/v1/users/${user.id}/invitations`))) && Object.assign(Object.assign({}, user), manager));
}
async function agentCreatePermissions(client, agentId, objectId, objectType, permissions, startDate, endDate) {
return client.userCreatePermissionBatch(agentId, {
endDate,
objectId,
objectType,
restrictions: [],
roles: permissions,
startDate,
});
}
async function appCreate(client, userId, data) {
return client.post(`/v1/users/${userId}/apps`, Object.assign(Object.assign({ availableLocales: { '0': 'de_DE' } }, data), { siteUrl: data.siteUrl.replace('_', '') }));
}
async function appGetById(client, appId) {
return client.get(`/v1/apps/${appId}`);
}
async function bookingGetById(client, bookingId) {
return client.get(`/v1/bookings/${bookingId}`);
}
async function bookingUpdateById(client, bookingId, data) {
return client.patch(`/v1/bookings/${bookingId}`, data);
}
async function bucketGet(client, bucketId) {
return client.get(`/v1/buckets/${bucketId}`);
}
async function bucketCreate(client, data) {
return client.post('/v1/buckets', {
channels: data.channels,
name: data.name,
});
}
async function bucketAddFile(client, bucketId, fileId) {
return ((await client.post(`/v1/buckets/${bucketId}/files`, {
id: fileId,
})) === '');
}
async function bucketRemoveFile(client, bucketId, fileId) {
return (await client.delete(`/v1/buckets/${bucketId}/files/${fileId}`)) === '';
}
async function bucketRemoveFilesInPath(client, bucketId, data) {
return ((await client.delete(`/v1/buckets/${bucketId}/files`, {
folder: data.path,
})) === '');
}
const createManyFiles = async (attachments, apiClient) => {
const responses = await Promise.all(attachments.map(async (attachment) => {
try {
const result = await apiClient.fileCreate({
file: attachment.content,
name: attachment.filename,
});
return result;
}
catch (error) {
return error;
}
}));
return responses;
};
async function createManyFilesSorted(files, client) {
const result = await createManyFiles(files, client);
return {
error: result.filter((item) => item instanceof Error),
success: result
.filter((item) => !(item instanceof Error))
.map((item) => item.id),
};
}
async function conversationGetById(client, conversationId) {
return client.get(`/v1/conversations/${conversationId}`);
}
async function conversationCreateMessage(client, conversationId, messageData) {
const url = `/v1/conversations/${conversationId}/messages`;
const payload = messageData.attachments && messageData.attachments.length
? {
content: {
description: messageData.body,
files: (await createManyFilesSorted(messageData.attachments, client)).success,
},
createdBy: messageData.createdBy,
inputChannel: messageData.inputChannel,
internal: false,
type: 'file',
}
: {
content: {
content: messageData.body,
},
createdBy: messageData.createdBy,
inputChannel: messageData.inputChannel,
type: 'text',
};
return client.post(url, payload);
}
async function fileCreate(client, data) {
return client.post('/v1/files', {
formData: {
file: [data.file, data.name],
path: data.path || '',
},
});
}
async function fileDelete(client, fileId) {
return (await client.delete(`/v1/files/${fileId}`)) === '';
}
var __rest$3 = (undefined && undefined.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
async function groupCreate(client, propertyId, data) {
const { propertyManagerId } = data, rest = __rest$3(data, ["propertyManagerId"]);
return client.post(`/v1/properties/${propertyId}/groups`, Object.assign(Object.assign({}, rest), { propertyManagerID: propertyManagerId }));
}
async function groupGetById(client, groupId) {
const _a = await client.get(`/v1/groups/${groupId}`), { propertyManagerID: propertyManagerId } = _a, result = __rest$3(_a, ["propertyManagerID"]);
return Object.assign(Object.assign({}, result), { propertyManagerId });
}
async function groupUpdateById(client, groupId, data) {
return client.patch(`/v1/groups/${groupId}`, data);
}
async function getGroups(client, page = 1, limit = -1, filter = {}) {
const { _embedded: { items: groups }, total, } = await client.get('/v1/groups', {
filter: JSON.stringify(filter),
limit,
page,
});
return { _embedded: { items: groups }, total };
}
async function lookupIds(client, appId, data) {
const url = data.dataSource
? `/v1/id-lookup/${appId}/${data.resource}/${data.dataSource}`
: `/v1/id-lookup/${appId}/${data.resource}`;
return client.post(url, Object.assign(Object.assign({ externalIds: typeof data.externalIds === 'string'
? [data.externalIds]
: data.externalIds }, (data.parentId ? { parentId: data.parentId } : {})), (data.userType ? { userType: data.userType } : {})));
}
function stringToDate(s) {
return new Date(Date.parse(s));
}
function dateToString(d) {
return d.toISOString();
}
var __rest$2 = (undefined && undefined.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var EnumNotificationCategory;
(function (EnumNotificationCategory) {
EnumNotificationCategory["events"] = "events";
EnumNotificationCategory["hintsAndTips"] = "hints-and-tips";
EnumNotificationCategory["lostAndFound"] = "lost-and-found";
EnumNotificationCategory["localDeals"] = "local-deals";
EnumNotificationCategory["localEvents"] = "local-events";
EnumNotificationCategory["miscellaneous"] = "miscellaneous";
EnumNotificationCategory["deals"] = "deals";
EnumNotificationCategory["messages"] = "messages";
EnumNotificationCategory["adminMessages"] = "admin-messages";
EnumNotificationCategory["newThingsToGive"] = "new-things-to-give";
EnumNotificationCategory["newThingsForSale"] = "new-things-for-sale";
EnumNotificationCategory["surveys"] = "surveys";
EnumNotificationCategory["supportOffer"] = "support-offer";
EnumNotificationCategory["supportRequest"] = "support-request";
EnumNotificationCategory["sustainability"] = "sustainability";
EnumNotificationCategory["localServices"] = "local-services";
EnumNotificationCategory["services"] = "services";
EnumNotificationCategory["ticketDigestEmail"] = "ticket-digest-email";
EnumNotificationCategory["appDigestEmail"] = "app-digest-email";
EnumNotificationCategory["newFile"] = "new-file";
})(EnumNotificationCategory || (EnumNotificationCategory = {}));
var EnumNotificationType;
(function (EnumNotificationType) {
EnumNotificationType["clipboardThing"] = "clipboard-thing";
EnumNotificationType["comment"] = "comment";
EnumNotificationType["communityArticle"] = "community-article";
EnumNotificationType["newFile"] = "new-file";
EnumNotificationType["ticketComment"] = "ticket-comment";
EnumNotificationType["welcomeNotification"] = "welcome-notification";
})(EnumNotificationType || (EnumNotificationType = {}));
function remapNotificationResult(_a) {
var { createdAt, objectID, referencedObjectID } = _a, restNotification = __rest$2(_a, ["createdAt", "objectID", "referencedObjectID"]);
return Object.assign({ createdAt: stringToDate(createdAt), objectId: objectID, referencedObjectId: referencedObjectID }, restNotification);
}
async function notificationsGetByUser(client, userId, page = 1, limit = -1) {
const { _embedded: { items: notifications }, total, metaData, } = await client.get(`/v1/users/${userId}/notifications?page=${page}&limit=${limit}`);
return {
_embedded: { items: notifications.map(remapNotificationResult) },
metaData,
total,
};
}
async function notificationsUpdateReadByUser(client, userId, lastReadAt = new Date()) {
return client.patch(`/v1/users/${userId}/notifications`, {
lastReadAt: dateToString(lastReadAt),
});
}
async function notificationUpdateRead(client, notificationId) {
return remapNotificationResult(await client.patch(`/v1/notifications/${notificationId}`, { read: true }));
}
function remapKeys(input, mapFn) {
return Object.entries(input).reduce((acc, entry) => (Object.assign(Object.assign({}, acc), { [mapFn(entry[0])]: entry[1] })), {});
}
function camelCaseToDash(input) {
return input.replace(/([A-Z])/g, (g) => `-${g[0].toLowerCase()}`);
}
function dashCaseToCamel(input) {
return input.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
}
var EnumNotificationSettingsValue;
(function (EnumNotificationSettingsValue) {
EnumNotificationSettingsValue["never"] = "never";
EnumNotificationSettingsValue["immediately"] = "immediately";
EnumNotificationSettingsValue["daily"] = "daily";
EnumNotificationSettingsValue["weekly"] = "weekly";
EnumNotificationSettingsValue["biweekly"] = "biweekly";
EnumNotificationSettingsValue["monthly"] = "monthly";
})(EnumNotificationSettingsValue || (EnumNotificationSettingsValue = {}));
async function notificationSettingsUpdateByUser(client, userId, data) {
const result = await client.patch(`/v1/users/${userId}/notification-settings`, { notificationSettings: remapKeys(data, camelCaseToDash) });
return remapKeys(result, dashCaseToCamel);
}
async function notificationSettingsResetByUser(client, userId) {
const result = await client.delete(`/v1/users/${userId}/notification-settings`);
return remapKeys(result, dashCaseToCamel);
}
async function propertyCreate(client, appId, data) {
return client.post(`/v1/apps/${appId}/properties`, data);
}
async function propertyGetById(client, propertyId) {
return client.get(`/v1/properties/${propertyId}`);
}
async function propertyUpdateById(client, propertyId, data) {
return client.patch(`/v1/properties/${propertyId}`, data);
}
async function getProperties(client, page = 1, limit = -1, filter = {}) {
const { _embedded: { items: properties }, total, } = await client.get('/v1/properties', {
filter: JSON.stringify(filter),
limit,
page,
});
return { _embedded: { items: properties }, total };
}
var __rest$1 = (undefined && undefined.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
const remapRegistationCodeResult = (registrationCode) => {
const { tenantID: externalId } = registrationCode, result = __rest$1(registrationCode, ["tenantID"]);
return Object.assign(Object.assign({}, result), { externalId });
};
async function registrationCodeCreate(client, code, utilisationPeriods, options = { permanent: false }) {
const { externalId } = options, moreOptions = __rest$1(options, ["externalId"]);
return remapRegistationCodeResult(await client.post('/v1/registration-codes', Object.assign(Object.assign({ code, utilisationPeriods: typeof utilisationPeriods === 'string'
? [utilisationPeriods]
: utilisationPeriods }, (externalId ? { externalId, tenantID: externalId } : {})), moreOptions)));
}
async function registrationCodeUpdateById(client, registrationCodeId, data) {
return remapRegistationCodeResult(await client.patch(`/v1/registration-codes/${registrationCodeId}`, data));
}
async function registrationCodeGetById(client, registrationCodeId) {
return remapRegistationCodeResult(await client.get(`/v1/invitations/${registrationCodeId}`));
}
async function registrationCodeDelete(client, registrationCodeId) {
return (await client.delete(`/v1/invitations/${registrationCodeId}`)) === '';
}
async function serviceProviderCreate(client, data) {
return client.post('/v1/service-providers', data);
}
async function serviceProviderGetById(client, serviceProviderId) {
return client.get(`/v1/service-providers/${serviceProviderId}`);
}
async function serviceProviderUpdateById(client, serviceProviderId, data) {
return client.patch(`/v1/service-providers/${serviceProviderId}`, data);
}
var ETicketStatus;
(function (ETicketStatus) {
ETicketStatus["CLOSED"] = "closed";
ETicketStatus["WAITING_FOR_AGENT"] = "waiting-for-agent";
ETicketStatus["WAITING_FOR_CUSTOMER"] = "waiting-for-customer";
ETicketStatus["WAITING_FOR_EXTERNAL"] = "waiting-for-external";
})(ETicketStatus || (ETicketStatus = {}));
var ETrafficLightColor;
(function (ETrafficLightColor) {
ETrafficLightColor["GREEN"] = "green";
ETrafficLightColor["RED"] = "red";
ETrafficLightColor["YELLOW"] = "yellow";
})(ETrafficLightColor || (ETrafficLightColor = {}));
async function ticketGetById(client, ticketId) {
return client.get(`/v1/tickets/${ticketId}`);
}
async function ticketCreateOnUser(client, userId, utilisationPeriodId, payload) {
return client.post(`/v1/users/${userId}/tickets`, Object.assign(Object.assign({}, payload), { files: payload.files
? (await createManyFilesSorted(payload.files, client)).success
: [], utilisationPeriod: utilisationPeriodId }));
}
async function ticketCreateOnServiceProvider(client, serviceProviderId, payload) {
return client.post(`/v1/property-managers/${serviceProviderId}/tickets`, Object.assign(Object.assign({}, payload), { files: payload.files
? (await createManyFilesSorted(payload.files, client)).success
: [] }));
}
exports.EnumUnitObjectType = void 0;
(function (EnumUnitObjectType) {
EnumUnitObjectType["adjoiningRoom"] = "adjoining-room";
EnumUnitObjectType["advertisingSpace"] = "advertising-space";
EnumUnitObjectType["aerial"] = "aerial";
EnumUnitObjectType["apartmentBuilding"] = "apartment-building";
EnumUnitObjectType["atm"] = "atm";
EnumUnitObjectType["atmRoom"] = "atm-room";
EnumUnitObjectType["attic"] = "attic";
EnumUnitObjectType["atticFlat"] = "attic-flat";
EnumUnitObjectType["bank"] = "bank";
EnumUnitObjectType["basment"] = "basment";
EnumUnitObjectType["bikeShed"] = "bike-shed";
EnumUnitObjectType["buildingLaw"] = "building-law";
EnumUnitObjectType["cafeteria"] = "cafeteria";
EnumUnitObjectType["caretakerRoom"] = "caretaker-room";
EnumUnitObjectType["carport"] = "carport";
EnumUnitObjectType["cellar"] = "cellar";
EnumUnitObjectType["commercialProperty"] = "commercial-property";
EnumUnitObjectType["commonRoom"] = "common-room";
EnumUnitObjectType["deliveryZone"] = "delivery-zone";
EnumUnitObjectType["diverse"] = "diverse";
EnumUnitObjectType["doubleParkingSpace"] = "double-parking-space";
EnumUnitObjectType["engineeringRoom"] = "engineering-room";
EnumUnitObjectType["entertainment"] = "entertainment";
EnumUnitObjectType["environment"] = "environment";
EnumUnitObjectType["estate"] = "estate";
EnumUnitObjectType["fillingStation"] = "filling-station";
EnumUnitObjectType["fitnessCenter"] = "fitness-center";
EnumUnitObjectType["flat"] = "flat";
EnumUnitObjectType["freeZone"] = "free-zone";
EnumUnitObjectType["garage"] = "garage";
EnumUnitObjectType["garden"] = "garden";
EnumUnitObjectType["gardenFlat"] = "garden-flat";
EnumUnitObjectType["heatingFacilities"] = "heating-facilities";
EnumUnitObjectType["hotel"] = "hotel";
EnumUnitObjectType["incidentalRentalExpenses"] = "incidental-rental-expenses";
EnumUnitObjectType["industry"] = "industry";
EnumUnitObjectType["kiosk"] = "kiosk";
EnumUnitObjectType["kitchen"] = "kitchen";
EnumUnitObjectType["loft"] = "loft";
EnumUnitObjectType["machine"] = "machine";
EnumUnitObjectType["maisonette"] = "maisonette";
EnumUnitObjectType["medicalPractice"] = "medical-practice";
EnumUnitObjectType["mopedShed"] = "moped-shed";
EnumUnitObjectType["motorcycleParkingSpace"] = "motorcycle-parking-space";
EnumUnitObjectType["office"] = "office";
EnumUnitObjectType["oneFamilyHouse"] = "one-family-house";
EnumUnitObjectType["parkingBox"] = "parking-box";
EnumUnitObjectType["parkingGarage"] = "parking-garage";
EnumUnitObjectType["parkingSpace"] = "parking-space";
EnumUnitObjectType["parkingSpaces"] = "parking-spaces";
EnumUnitObjectType["penthouse"] = "penthouse";
EnumUnitObjectType["productionPlant"] = "production-plant";
EnumUnitObjectType["pub"] = "pub";
EnumUnitObjectType["publicArea"] = "public-area";
EnumUnitObjectType["restaurant"] = "restaurant";
EnumUnitObjectType["retirementHome"] = "retirement-home";
EnumUnitObjectType["salesFloor"] = "sales-floor";
EnumUnitObjectType["school"] = "school";
EnumUnitObjectType["shelter"] = "shelter";
EnumUnitObjectType["storage"] = "storage";
EnumUnitObjectType["store"] = "store";
EnumUnitObjectType["storeroom"] = "storeroom";
EnumUnitObjectType["studio"] = "studio";
EnumUnitObjectType["terrace"] = "terrace";
EnumUnitObjectType["toilets"] = "toilets";
EnumUnitObjectType["utilityRoom"] = "utility-room";
EnumUnitObjectType["variableParkingSpace"] = "variable-parking-space";
EnumUnitObjectType["variableRoom"] = "variable-room";
EnumUnitObjectType["visitorParkingSpace"] = "visitor-parking-space";
EnumUnitObjectType["workshop"] = "workshop";
})(exports.EnumUnitObjectType || (exports.EnumUnitObjectType = {}));
exports.EnumUnitType = void 0;
(function (EnumUnitType) {
EnumUnitType["rented"] = "rented";
EnumUnitType["owned"] = "owned";
})(exports.EnumUnitType || (exports.EnumUnitType = {}));
async function unitCreate(client, groupId, data) {
return client.post(`/v1/groups/${groupId}/units`, data);
}
async function unitGetById(client, unitId) {
return client.get(`/v1/units/${unitId}`);
}
async function unitUpdateById(client, unitId, data) {
return client.patch(`/v1/units/${unitId}`, data);
}
async function getUnits(client, page = 1, limit = -1, filter = {}) {
const { _embedded: { items: units }, total, } = await client.get('/v1/units', {
filter: JSON.stringify(filter),
limit,
page,
});
return { _embedded: { items: units }, total };
}
exports.EnumUserRelationType = void 0;
(function (EnumUserRelationType) {
EnumUserRelationType["isResponsible"] = "is-responsible";
})(exports.EnumUserRelationType || (exports.EnumUserRelationType = {}));
async function userRelationCreate(client, userId, data) {
return client.post(`/v1/users/${userId}/user-relations/${data.type}`, {
ids: data.ids,
level: data.level,
readOnly: data.readOnly,
role: data.role,
});
}
async function userRelationDelete(client, userId, data) {
return client.delete(`/v1/users/${userId}/user-relations/${data.type}`, {
ids: data.ids,
level: data.level,
role: data.role,
});
}
async function userRelationsGetByUser(client, userId) {
return client.get(`/v1/users/${userId}/user-relations`);
}
var __rest = (undefined && undefined.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
exports.EnumUtilisationPeriodType = void 0;
(function (EnumUtilisationPeriodType) {
EnumUtilisationPeriodType["tenant"] = "tenant";
EnumUtilisationPeriodType["ownership"] = "ownership";
EnumUtilisationPeriodType["vacant"] = "vacant";
})(exports.EnumUtilisationPeriodType || (exports.EnumUtilisationPeriodType = {}));
async function utilisationPeriodCreate(client, unitId, data) {
const _a = await client.post(`/v1/units/${unitId}/utilisation-periods`, data), { tenantIDs: tenantIds, _embedded } = _a, result = __rest(_a, ["tenantIDs", "_embedded"]);
return Object.assign(Object.assign({}, result), { invitations: _embedded.invitations.map(remapRegistationCodeResult), tenantIds, users: remapEmbeddedUser(_embedded) });
}
async function utilisationPeriodGetById(client, utilisationPeriodId) {
const _a = await client.get(`/v1/utilisation-periods/${utilisationPeriodId}`), { tenantIDs: tenantIds, _embedded } = _a, result = __rest(_a, ["tenantIDs", "_embedded"]);
return Object.assign(Object.assign({}, result), { invitations: _embedded.invitations.map(remapRegistationCodeResult), tenantIds, users: remapEmbeddedUser(_embedded) });
}
async function utilisationPeriodUpdateById(client, utilisationPeriodId, data) {
const _a = await client.patch(`/v1/utilisation-periods/${utilisationPeriodId}`, data), { tenantIDs: tenantIds, _embedded } = _a, result = __rest(_a, ["tenantIDs", "_embedded"]);
return Object.assign(Object.assign({}, result), { invitations: _embedded.invitations.map(remapRegistationCodeResult), tenantIds, users: remapEmbeddedUser(_embedded) });
}
async function utilisationPeriodDelete(client, utilisationPeriodId) {
return !(await client.delete(`/v1/utilisation-periods/${utilisationPeriodId}/soft`));
}
async function utilisationPeriodCheckInUser(client, utilisationPeriodId, data) {
return ((await client.post(`/v1/utilisation-periods/${utilisationPeriodId}/users`, {
email: data.email,
})) && client.utilisationPeriodGetById(utilisationPeriodId));
}
async function utilisationPeriodCheckOutUser(client, utilisationPeriodId, userId) {
return ((await client.delete(`/v1/utilisation-periods/${utilisationPeriodId}/users/${userId}`)) === '');
}
async function utilisationPeriodAddRegistrationCode(client, utilisationPeriodId, code, tenant, permanent = false) {
return client.post(`/v1/utilisation-periods/${utilisationPeriodId}/registration-codes`, { code, permanent, tenant });
}
async function patch(request, method, body, returnRawResultObject, headers) {
return request('patch', method, { body, headers }, returnRawResultObject);
}
async function post(request, method, body, returnRawResultObject, headers) {
return request('post', method, { body, headers }, returnRawResultObject);
}
async function put(request, method, body, returnRawResultObject, headers) {
return request('put', method, { body, headers }, returnRawResultObject);
}
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var delayed_stream;
var hasRequiredDelayed_stream;
function requireDelayed_stream () {
if (hasRequiredDelayed_stream) return delayed_stream;
hasRequiredDelayed_stream = 1;
var Stream = require$$0$1.Stream;
var util = require$$1;
delayed_stream = DelayedStream;
function DelayedStream() {
this.source = null;
this.dataSize = 0;
this.maxDataSize = 1024 * 1024;
this.pauseStream = true;
this._maxDataSizeExceeded = false;
this._released = false;
this._bufferedEvents = [];
}
util.inherits(DelayedStream, Stream);
DelayedStream.create = function(source, options) {
var delayedStream = new this();
options = options || {};
for (var option in options) {
delayedStream[option] = options[option];
}
delayedStream.source = source;
var realEmit = source.emit;
source.emit = function() {
delayedStream._handleEmit(arguments);
return realEmit.apply(source, arguments);
};
source.on('error', function() {});
if (delayedStream.pauseStream) {
source.pause();
}
return delayedStream;
};
Object.defineProperty(DelayedStream.prototype, 'readable', {
configurable: true,
enumerable: true,
get: function() {
return this.source.readable;
}
});
DelayedStream.prototype.setEncoding = function() {
return this.source.setEncoding.apply(this.source, arguments);
};
DelayedStream.prototype.resume = function() {
if (!this._released) {
this.release();
}
this.source.resume();
};
DelayedStream.prototype.pause = function() {
this.source.pause();
};
DelayedStream.prototype.release = function() {
this._released = true;
this._bufferedEvents.forEach(function(args) {
this.emit.apply(this, args);
}.bind(this));
this._bufferedEvents = [];
};
DelayedStream.prototype.pipe = function() {
var r = Stream.prototype.pipe.apply(this, arguments);
this.resume();
return r;
};
DelayedStream.prototype._handleEmit = function(args) {
if (this._released) {
this.emit.apply(this, args);
return;
}
if (args[0] === 'data') {
this.dataSize += args[1].length;
this._checkIfMaxDataSizeExceeded();
}
this._bufferedEvents.push(args);
};
DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() {
if (this._maxDataSizeExceeded) {
return;
}
if (this.dataSize <= this.maxDataSize) {
return;
}
this._maxDataSizeExceeded = true;
var message =
'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.';
this.emit('error', new Error(message));
};
return delayed_stream;
}
var combined_stream;
var hasRequiredCombined_stream;
function requireCombined_stream () {
if (hasRequiredCombined_stream) return combined_stream;
hasRequiredCombined_stream = 1;
var util = require$$1;
var Stream = require$$0$1.Stream;
var DelayedStream = requireDelayed_stream();
combined_stream = CombinedStream;
function CombinedStream() {
this.writable = false;
this.readable = true;
this.dataSize = 0;
this.maxDataSize = 2 * 1024 * 1024;
this.pauseStreams = true;
this._released = false;
this._streams = [];
this._currentStream = null;
this._insideLoop = false;
this._pendingNext = false;
}
util.inherits(CombinedStream, Stream);
CombinedStream.create = function(options) {
var combinedStream = new this();
options = options || {};
for (var option in options) {
combinedStream[option] = options[option];
}
return combinedStream;
};
CombinedStream.isStreamLike = function(stream) {
return (typeof stream !== 'function')
&& (typeof stream !== 'string')
&& (typeof stream !== 'boolean')
&& (typeof stream !== 'number')
&& (!Buffer.isBuffer(stream));
};
CombinedStream.prototype.append = function(stream) {
var isStreamLike = CombinedStream.isStreamLike(stream);
if (isStreamLike) {
if (!(stream instanceof DelayedStream)) {
var newStream = DelayedStream.create(stream, {
maxDataSize: Infinity,
pauseStream: this.pauseStreams,
});
stream.on('data', this._checkDataSize.bind(this));
stream = newStream;
}
this._handleErrors(stream);
if (this.pauseStreams) {
stream.pause();
}
}
this._streams.push(stream);
return this;
};
CombinedStream.prototype.pipe = function(dest, options) {
Stream.prototype.pipe.call(this, dest, options);
this.resume();
return dest;
};
CombinedStream.prototype._getNext = function() {
this._currentStream = null;
if (this._insideLoop) {
this._pendingNext = true;
return; // defer call
}
this._insideLoop = true;
try {
do {
this._pendingNext = false;
this._realGetNext();
} while (this._pendingNext);
} finally {
this._insideLoop = false;
}
};
CombinedStream.prototype._realGetNext = function() {
var stream = this._streams.shift();
if (typeof stream == 'undefined') {
this.end();
return;
}
if (typeof stream !== 'function') {
this._pipeNext(stream);
return;
}
var getStream = stream;
getStream(function(stream) {
var isStreamLike = CombinedStream.isStreamLike(stream);
if (isStreamLike) {
stream.on('data', this._checkDataSize.bind(this));
this._handleErrors(stream);
}
this._pipeNext(stream);
}.bind(this));
};
CombinedStream.prototype._pipeNext = function(stream) {
this._currentStream = stream;
var isStreamLike = CombinedStream.isStreamLike(stream);
if (isStreamLike) {
stream.on('end', this._getNext.bind(this));
stream.pipe(this, {end: false});
return;
}
var value = stream;
this.write(value);
this._getNext();
};
CombinedStream.prototype._handleErrors = function(stream) {
var self = this;
stream.on('error', function(err) {
self._emitError(err);
});
};
CombinedStream.prototype.write = function(data) {
this.emit('data', data);
};
CombinedStream.prototype.pause = function() {
if (!this.pauseStreams) {
return;
}
if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause();
this.emit('pause');
};
CombinedStream.prototype.resume = function() {
if (!this._released) {
this._released = true;
this.writable = true;
this._getNext();
}
if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume();
this.emit('resume');
};
CombinedStream.prototype.end = function() {
this._reset();
this.emit('end');
};
CombinedStream.prototype.destroy = function() {
this._reset();
this.emit('close');
};
CombinedStream.prototype._reset = function() {
this.writable = false;
this._streams = [];
this._currentStream = null;
};
CombinedStream.prototype._checkDataSize = function() {
this._updateDataSize();
if (this.dataSize <= this.maxDataSize) {
return;
}
var message =
'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.';
this._emitError(new Error(message));
};
CombinedStream.prototype._updateDataSize = function() {
this.dataSize = 0;
var self = this;
this._streams.forEach(function(stream) {
if (!stream.dataSize) {
return;
}
self.dataSize += stream.dataSize;
});
if (this._currentStream && this._currentStream.dataSize) {
this.dataSize += this._currentStream.dataSize;
}
};
CombinedStream.prototype._emitError = function(err) {
this._reset();
this.emit('error', err);
};
return combined_stream;
}
var mimeTypes = {};
var require$$0 = {
"application/1d-interleaved-parityfec": {
source: "iana"
},
"application/3gpdash-qoe-report+xml": {
source: "iana",
charset: "UTF-8",
compressible: true
},
"application/3gpp-ims+xml": {
source: "iana",
compressible: true
},
"application/3gpphal+json": {
source: "iana",
compressible: true
},
"application/3gpphalforms+json": {
source: "iana",
compressible: true
},
"application/a2l": {
source: "iana"
},
"application/ace+cbor": {
source: "iana"
},
"application/activemessage": {
source: "iana"
},
"application/activity+json": {
source: "iana",
compressible: true
},
"application/alto-costmap+json": {
source: "iana",
compressible: true
},
"application/alto-costmapfilter+json": {
source: "iana",
compressible: true
},
"application/alto-directory+json": {
source: "iana",
compressible: true
},
"application/alto-endpointcost+json": {
source: "iana",
compressible: true
},
"application/alto-endpointcostparams+json": {
source: "iana",
compressible: true
},
"application/alto-endpointprop+json": {
source: "iana",
compressible: true
},
"application/alto-endpointpropparams+json": {
source: "iana",
compressible: true
},
"application/alto-error+json": {
source: "iana",
compressible: true
},
"application/alto-networkmap+json": {
source: "iana",
compressible: true
},
"application/alto-networkmapfilter+json": {
source: "iana",
compressible: true
},
"application/alto-updatestreamcontrol+json": {
source: "iana",
compressible: true
},
"application/alto-updatestreamparams+json": {
source: "iana",
compressible: true
},
"application/aml": {
source: "iana"
},
"application/andrew-inset": {
source: "iana",
extensions: [
"ez"
]
},
"application/applefile": {
source: "iana"
},
"application/applixware": {
source: "apache",
extensions: [
"aw"
]
},
"application/at+jwt": {
source: "iana"
},
"application/atf": {
source: "iana"
},
"application/atfx": {
source: "iana"
},
"application/atom+xml": {
source: "iana",
compressible: true,
extensions: [
"atom"
]
},
"application/atomcat+xml": {
source: "iana",
compressible: true,
extensions: [
"atomcat"
]
},
"application/atomdeleted+xml": {
source: "iana",
compressible: true,
extensions: [
"atomdeleted"
]
},
"application/atomicmail": {
source: "iana"
},
"application/atomsvc+xml": {
source: "iana",
compressible: true,
extensions: [
"atomsvc"
]
},
"application/atsc-dwd+xml": {
source: "iana",
compressible: true,
extensions: [
"dwd"
]
},
"application/atsc-dynamic-event-message": {
source: "iana"
},
"application/atsc-held+xml": {
source: "iana",
compressible: true,
extensions: [
"held"
]
},
"application/atsc-rdt+json": {
source: "iana",
compressible: true
},
"application/atsc-rsat+xml": {
source: "iana",
compressible: true,
extensions: [
"rsat"
]
},
"application/atxml": {
source: "iana"
},
"application/auth-policy+xml": {
source: "iana",
compressible: true
},
"application/bacnet-xdd+zip": {
source: "iana",
compressible: false
},
"application/batch-smtp": {
source: "iana"
},
"application/bdoc": {
compressible: false,
extensions: [
"bdoc"
]
},
"application/beep+xml": {
source: "iana",
charset: "UTF-8",
compressible: true
},
"application/calendar+json": {
source: "iana",
compressible: true
},
"application/calendar+xml": {
source: "iana",
compressible: true,
extensions: [
"xcs"
]
},
"application/call-completion": {
source: "iana"
},
"application/cals-1840": {
source: "iana"
},
"application/captive+json": {
source: "iana",
compressible: true
},
"applic