@eway-crm/connector 1.0.171 → 1.0.173

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.
package/README.md CHANGED
@@ -1,72 +1,72 @@
1
- ![eWay-CRM Logo](https://www.eway-crm.com/wp-content/themes/eway/img/logo_new-new.svg)
2
- # eWay-CRM API
3
- API used for communication with [eWay-CRM](http://www.eway-crm.com/) web service. This library is a wrapper over HTTP/S communication and sessions. See our [documentation](https://kb.eway-crm.com/documentation/6-add-ins/6-7-api-1) for more information.
4
-
5
- ## Installation
6
- The simpliest way to start using this library is to get the [NPM Package](https://www.nuget.org/packages/eWayCRM.API). To do that, just run this command in your NodeJS project's root dir:
7
-
8
- ```
9
- npm i @eway-crm/connector
10
- ```
11
-
12
- To get the best dev experience, we also recommend using [TypeScript](https://www.typescriptlang.org/) since this library contains the types headers.
13
-
14
- ## Usage
15
-
16
- This library wraps the communication with JSON API. For HTTP requests, it uses [Axios](https://github.com/axios/axios). To provide the most variability, it lets you input JSON data and fetch JSON data in the same structure as the server uses. The only thing you don't have to care about is the `sessionId`.
17
-
18
- The actual usage is then the same as it would be for example with [PHP](https://github.com/rstefko/eway-crm-php-lib). See the [documentation](https://kb.eway-crm.com/documentation/6-add-ins/6-7-api-1) for more.
19
-
20
- ## Version Compatibility
21
-
22
- This library is compatible with **eWay-CRM 6.0.1 and higher**. If you have got a lower version of your eWay-CRM, check the Updates section in the eWay-CRM Administration Application. If there is no update available, contact your eWay-CRM account manager or via other channel listed on our [web page](https://www.eway-crm.com/contact/).
23
-
24
- ## Establishing Connection
25
-
26
- To communicate with eWay-CRM web service, we first have to establish connection. This must be done prior to every action we want to accomplish with use of the web service. To do that, we have to create new instance of ```ApiConnection``` with seven parameters:
27
- 1. Service url address (same as the one you use in Outlook)
28
- 2. Username
29
- 3. Password hash (md5 of the user's UTF8 password or hash created by the tool from eWay-CRM server component)
30
- 4. App version identifier (name and version of the connecting client app - must consist of alphabet string and digits at the end)
31
- 5. Client machine identifier (unique identifier of the connecting machine - MAC address for instance)
32
- 6. Client machine name (human readable client machine - PC name for instance)
33
- 7. Error handling callback (this callback is called everytime an unexpected error occurs)
34
-
35
- ```JS
36
- import ApiConnection from '@eway-crm/connector';
37
-
38
- const serviceUrl = 'https://trial.eway-crm.com/31994';
39
- const username = 'api';
40
- const passwordHash = '470AE7216203E23E1983EF1851E72947';
41
-
42
- const connection = ApiConnection.create(serviceUrl, username, passwordHash, 'JSSample1', '00:00:00:00:00', 'SampleTestMachine', (err) => console.error(err));
43
- ```
44
-
45
- ⚠️ The code above does not support [Microsoft Account Authenticaion](https://kb.eway-crm.com/documentation/2-installation/2-3-installation-the-server-part/adjust-eway-crm-web-service-for-azure-login-office-365?set_language=en). If you log into eWay-CRM with your Microsoft account, you need to implement your own OAuth2 client.
46
-
47
- ## CORS
48
-
49
- If you are developing a web app running on a different host than your eWay-CRM web service, you need to configure your eWay-CRM web service to allow cross-origin requests. To achieve that, put the following setting into `appSettings` section of your web service's web.config file.
50
-
51
- ```XML
52
- <add key="AccessControlAllowOrigin" value="https://YOUR-ORIGIN:PORT" />
53
- ```
54
-
55
- ⚠ If you add the setting above to your web.config, the web-based eWay-CRM Administration Center won't work in Internet Explorer, which will be a huge loss for the whole humankind.
56
-
57
- ## Using the Connection Object
58
-
59
- Once having the `ApiConnection` instance, the API requests look like this searching of our user record.
60
-
61
- ```JS
62
- connection.callMethod(
63
- 'SearchUsers',
64
- {
65
- transmitObject: { Username: username },
66
- },
67
- (result) => {
68
- console.log('My user detail follows:');
69
- console.log(result.Data[0]);
70
- }
71
- );
72
- ```
1
+ ![eWay-CRM Logo](https://www.eway-crm.com/wp-content/themes/eway/img/logo_new-new.svg)
2
+ # eWay-CRM API
3
+ API used for communication with [eWay-CRM](http://www.eway-crm.com/) web service. This library is a wrapper over HTTP/S communication and sessions. See our [documentation](https://kb.eway-crm.com/documentation/6-add-ins/6-7-api-1) for more information.
4
+
5
+ ## Installation
6
+ The simpliest way to start using this library is to get the [NPM Package](https://www.nuget.org/packages/eWayCRM.API). To do that, just run this command in your NodeJS project's root dir:
7
+
8
+ ```
9
+ npm i @eway-crm/connector
10
+ ```
11
+
12
+ To get the best dev experience, we also recommend using [TypeScript](https://www.typescriptlang.org/) since this library contains the types headers.
13
+
14
+ ## Usage
15
+
16
+ This library wraps the communication with JSON API. For HTTP requests, it uses [Axios](https://github.com/axios/axios). To provide the most variability, it lets you input JSON data and fetch JSON data in the same structure as the server uses. The only thing you don't have to care about is the `sessionId`.
17
+
18
+ The actual usage is then the same as it would be for example with [PHP](https://github.com/rstefko/eway-crm-php-lib). See the [documentation](https://kb.eway-crm.com/documentation/6-add-ins/6-7-api-1) for more.
19
+
20
+ ## Version Compatibility
21
+
22
+ This library is compatible with **eWay-CRM 6.0.1 and higher**. If you have got a lower version of your eWay-CRM, check the Updates section in the eWay-CRM Administration Application. If there is no update available, contact your eWay-CRM account manager or via other channel listed on our [web page](https://www.eway-crm.com/contact/).
23
+
24
+ ## Establishing Connection
25
+
26
+ To communicate with eWay-CRM web service, we first have to establish connection. This must be done prior to every action we want to accomplish with use of the web service. To do that, we have to create new instance of ```ApiConnection``` with seven parameters:
27
+ 1. Service url address (same as the one you use in Outlook)
28
+ 2. Username
29
+ 3. Password hash (md5 of the user's UTF8 password or hash created by the tool from eWay-CRM server component)
30
+ 4. App version identifier (name and version of the connecting client app - must consist of alphabet string and digits at the end)
31
+ 5. Client machine identifier (unique identifier of the connecting machine - MAC address for instance)
32
+ 6. Client machine name (human readable client machine - PC name for instance)
33
+ 7. Error handling callback (this callback is called everytime an unexpected error occurs)
34
+
35
+ ```JS
36
+ import ApiConnection from '@eway-crm/connector';
37
+
38
+ const serviceUrl = 'https://trial.eway-crm.com/31994';
39
+ const username = 'api';
40
+ const passwordHash = '470AE7216203E23E1983EF1851E72947';
41
+
42
+ const connection = ApiConnection.create(serviceUrl, username, passwordHash, 'JSSample1', '00:00:00:00:00', 'SampleTestMachine', (err) => console.error(err));
43
+ ```
44
+
45
+ ⚠️ The code above does not support [Microsoft Account Authenticaion](https://kb.eway-crm.com/documentation/2-installation/2-3-installation-the-server-part/adjust-eway-crm-web-service-for-azure-login-office-365?set_language=en). If you log into eWay-CRM with your Microsoft account, you need to implement your own OAuth2 client.
46
+
47
+ ## CORS
48
+
49
+ If you are developing a web app running on a different host than your eWay-CRM web service, you need to configure your eWay-CRM web service to allow cross-origin requests. To achieve that, put the following setting into `appSettings` section of your web service's web.config file.
50
+
51
+ ```XML
52
+ <add key="AccessControlAllowOrigin" value="https://YOUR-ORIGIN:PORT" />
53
+ ```
54
+
55
+ ⚠ If you add the setting above to your web.config, the web-based eWay-CRM Administration Center won't work in Internet Explorer, which will be a huge loss for the whole humankind.
56
+
57
+ ## Using the Connection Object
58
+
59
+ Once having the `ApiConnection` instance, the API requests look like this searching of our user record.
60
+
61
+ ```JS
62
+ connection.callMethod(
63
+ 'SearchUsers',
64
+ {
65
+ transmitObject: { Username: username },
66
+ },
67
+ (result) => {
68
+ console.log('My user detail follows:');
69
+ console.log(result.Data[0]);
70
+ }
71
+ );
72
+ ```
@@ -21,5 +21,12 @@ export declare class ApiMethods {
21
21
  static readonly getBinaryAttachmentLatestRevision = "GetBinaryAttachmentLatestRevision";
22
22
  static readonly canUnlinkItems = "CanUnlinkItems";
23
23
  static readonly unlinkItems = "UnlinkItems";
24
+ /**
25
+ * Return folderName part of API method that is used in API calls. Some API methods have different names than the folder names they are associated with.
26
+ * For example module Calendar has method GetCalendarsByItemGuids, but the folder name is Calendar.
27
+ */
28
+ private static readonly getFolderNameForApiMethod;
24
29
  static readonly getGetFolderNameByItemGuidsMethodName: (folderName: TFolderName) => string;
30
+ static readonly getGetFolderNameMethodName: (folderName: TFolderName) => string;
31
+ static readonly getSearchFolderNameMethodName: (folderName: TFolderName) => string;
25
32
  }
@@ -1,10 +1,13 @@
1
1
  import type { ITokenData } from '../interfaces/ITokenData';
2
2
  import type { IEWJwtPayload } from '../interfaces/IEWJwtPayload';
3
+ export type scope = "api" | "offline_access";
4
+ export type codeChallengeMethod = "plain" | "S256";
3
5
  export declare class OAuthHelper {
4
6
  static finishAuthorization: (wsUrl: string, clientId: string, clientSecret: string, codeVerifier: string, authorizationCode: string, redirectUrl: string, callback: (tokenData: ITokenData) => void) => void;
5
7
  static refreshToken: (wsUrl: string, clientId: string, clientSecret: string, refreshToken: string, callback: (tokenData: ITokenData) => void) => void;
6
8
  static getWebServiceUrl: (refreshToken: string) => string;
7
9
  static getUserName: (accessToken: string) => string | undefined;
8
10
  static decodeAccessToken: (accessToken: string) => IEWJwtPayload;
11
+ static createAuthorizeUrl(clientId: string, scopes: scope[], redirectUri: string, state?: string, codeChallenge?: string, codeChallengeMethod?: codeChallengeMethod, isDev?: boolean): string;
9
12
  private static callTokenEndpoint;
10
13
  }
package/lib/cjs/index.js CHANGED
@@ -1,8 +1,8 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("axios"),t=require("universal-base64url"),s=require("jwt-decode"),o=require("compare-versions");function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(s){if("default"!==s){var o=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,o.get?o:{enumerable:!0,get:function(){return e[s]}})}})),t.default=e,Object.freeze(t)}var r=n(t),i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var a,l={exports:{}},c=l.exports=function(){function e(e){var t=typeof e;return null!==e&&("object"===t||"function"===t)}function t(e){return"function"==typeof e}var s=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},o=0,n=void 0,r=void 0,a=function(e,t){E[o]=e,E[o+1]=t,2===(o+=2)&&(r?r(v):A())};function l(e){r=e}function c(e){a=e}var d="undefined"!=typeof window?window:void 0,u=d||{},m=u.MutationObserver||u.WebKitMutationObserver,p="undefined"==typeof self&&"undefined"!=typeof process&&"[object process]"==={}.toString.call(process),h="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel;function y(){return function(){return process.nextTick(v)}}function C(){return void 0!==n?function(){n(v)}:S()}function f(){var e=0,t=new m(v),s=document.createTextNode("");return t.observe(s,{characterData:!0}),function(){s.data=e=++e%2}}function g(){var e=new MessageChannel;return e.port1.onmessage=v,function(){return e.port2.postMessage(0)}}function S(){var e=setTimeout;return function(){return e(v,1)}}var E=new Array(1e3);function v(){for(var e=0;e<o;e+=2)(0,E[e])(E[e+1]),E[e]=void 0,E[e+1]=void 0;o=0}function P(){try{var e=Function("return this")().require("vertx");return n=e.runOnLoop||e.runOnContext,C()}catch(e){return S()}}var A=void 0;function T(e,t){var s=this,o=new this.constructor(b);void 0===o[I]&&J(o);var n=s._state;if(n){var r=arguments[n-1];a((function(){return _(n,o,r,s._result)}))}else j(s,o,e,t);return o}function k(e){var t=this;if(e&&"object"==typeof e&&e.constructor===t)return e;var s=new t(b);return B(s,e),s}A=p?y():m?f():h?g():void 0===d?P():S();var I=Math.random().toString(36).substring(2);function b(){}var w=void 0,D=1,N=2;function x(){return new TypeError("You cannot resolve a promise with itself")}function O(){return new TypeError("A promises callback cannot return that same promise.")}function R(e,t,s,o){try{e.call(t,s,o)}catch(e){return e}}function M(e,t,s){a((function(e){var o=!1,n=R(s,t,(function(s){o||(o=!0,t!==s?B(e,s):G(e,s))}),(function(t){o||(o=!0,W(e,t))}),"Settle: "+(e._label||" unknown promise"));!o&&n&&(o=!0,W(e,n))}),e)}function L(e,t){t._state===D?G(e,t._result):t._state===N?W(e,t._result):j(t,void 0,(function(t){return B(e,t)}),(function(t){return W(e,t)}))}function F(e,s,o){s.constructor===e.constructor&&o===T&&s.constructor.resolve===k?L(e,s):void 0===o?G(e,s):t(o)?M(e,s,o):G(e,s)}function B(t,s){if(t===s)W(t,x());else if(e(s)){var o=void 0;try{o=s.then}catch(e){return void W(t,e)}F(t,s,o)}else G(t,s)}function U(e){e._onerror&&e._onerror(e._result),H(e)}function G(e,t){e._state===w&&(e._result=t,e._state=D,0!==e._subscribers.length&&a(H,e))}function W(e,t){e._state===w&&(e._state=N,e._result=t,a(U,e))}function j(e,t,s,o){var n=e._subscribers,r=n.length;e._onerror=null,n[r]=t,n[r+D]=s,n[r+N]=o,0===r&&e._state&&a(H,e)}function H(e){var t=e._subscribers,s=e._state;if(0!==t.length){for(var o=void 0,n=void 0,r=e._result,i=0;i<t.length;i+=3)o=t[i],n=t[i+s],o?_(s,o,n,r):n(r);e._subscribers.length=0}}function _(e,s,o,n){var r=t(o),i=void 0,a=void 0,l=!0;if(r){try{i=o(n)}catch(e){l=!1,a=e}if(s===i)return void W(s,O())}else i=n;s._state!==w||(r&&l?B(s,i):!1===l?W(s,a):e===D?G(s,i):e===N&&W(s,i))}function z(e,t){try{t((function(t){B(e,t)}),(function(t){W(e,t)}))}catch(t){W(e,t)}}var V=0;function q(){return V++}function J(e){e[I]=V++,e._state=void 0,e._result=void 0,e._subscribers=[]}function Q(){return new Error("Array Methods must be provided an Array")}var K=function(){function e(e,t){this._instanceConstructor=e,this.promise=new e(b),this.promise[I]||J(this.promise),s(t)?(this.length=t.length,this._remaining=t.length,this._result=new Array(this.length),0===this.length?G(this.promise,this._result):(this.length=this.length||0,this._enumerate(t),0===this._remaining&&G(this.promise,this._result))):W(this.promise,Q())}return e.prototype._enumerate=function(e){for(var t=0;this._state===w&&t<e.length;t++)this._eachEntry(e[t],t)},e.prototype._eachEntry=function(e,t){var s=this._instanceConstructor,o=s.resolve;if(o===k){var n=void 0,r=void 0,i=!1;try{n=e.then}catch(e){i=!0,r=e}if(n===T&&e._state!==w)this._settledAt(e._state,t,e._result);else if("function"!=typeof n)this._remaining--,this._result[t]=e;else if(s===te){var a=new s(b);i?W(a,r):F(a,e,n),this._willSettleAt(a,t)}else this._willSettleAt(new s((function(t){return t(e)})),t)}else this._willSettleAt(o(e),t)},e.prototype._settledAt=function(e,t,s){var o=this.promise;o._state===w&&(this._remaining--,e===N?W(o,s):this._result[t]=s),0===this._remaining&&G(o,this._result)},e.prototype._willSettleAt=function(e,t){var s=this;j(e,void 0,(function(e){return s._settledAt(D,t,e)}),(function(e){return s._settledAt(N,t,e)}))},e}();function $(e){return new K(this,e).promise}function Y(e){var t=this;return s(e)?new t((function(s,o){for(var n=e.length,r=0;r<n;r++)t.resolve(e[r]).then(s,o)})):new t((function(e,t){return t(new TypeError("You must pass an array to race."))}))}function X(e){var t=new this(b);return W(t,e),t}function Z(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function ee(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}var te=function(){function e(t){this[I]=q(),this._result=this._state=void 0,this._subscribers=[],b!==t&&("function"!=typeof t&&Z(),this instanceof e?z(this,t):ee())}return e.prototype.catch=function(e){return this.then(null,e)},e.prototype.finally=function(e){var s=this,o=s.constructor;return t(e)?s.then((function(t){return o.resolve(e()).then((function(){return t}))}),(function(t){return o.resolve(e()).then((function(){throw t}))})):s.then(e,e)},e}();function se(){var e=void 0;if(void 0!==i)e=i;else if("undefined"!=typeof self)e=self;else try{e=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var t=e.Promise;if(t){var s=null;try{s=Object.prototype.toString.call(t.resolve())}catch(e){}if("[object Promise]"===s&&!t.cast)return}e.Promise=te}return te.prototype.then=T,te.all=$,te.race=Y,te.resolve=k,te.reject=X,te._setScheduler=l,te._setAsap=c,te._asap=a,te.polyfill=se,te.Promise=te,te}();
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("axios"),t=require("universal-base64url"),s=require("jwt-decode"),o=require("compare-versions");function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(s){if("default"!==s){var o=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,o.get?o:{enumerable:!0,get:function(){return e[s]}})}})),t.default=e,Object.freeze(t)}var r=n(t),i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var a,l={exports:{}},c=l.exports=function(){function e(e){var t=typeof e;return null!==e&&("object"===t||"function"===t)}function t(e){return"function"==typeof e}var s=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},o=0,n=void 0,r=void 0,a=function(e,t){E[o]=e,E[o+1]=t,2===(o+=2)&&(r?r(v):A())};function l(e){r=e}function c(e){a=e}var d="undefined"!=typeof window?window:void 0,u=d||{},m=u.MutationObserver||u.WebKitMutationObserver,p="undefined"==typeof self&&"undefined"!=typeof process&&"[object process]"==={}.toString.call(process),h="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel;function y(){return function(){return process.nextTick(v)}}function C(){return void 0!==n?function(){n(v)}:S()}function f(){var e=0,t=new m(v),s=document.createTextNode("");return t.observe(s,{characterData:!0}),function(){s.data=e=++e%2}}function g(){var e=new MessageChannel;return e.port1.onmessage=v,function(){return e.port2.postMessage(0)}}function S(){var e=setTimeout;return function(){return e(v,1)}}var E=new Array(1e3);function v(){for(var e=0;e<o;e+=2)(0,E[e])(E[e+1]),E[e]=void 0,E[e+1]=void 0;o=0}function P(){try{var e=Function("return this")().require("vertx");return n=e.runOnLoop||e.runOnContext,C()}catch(e){return S()}}var A=void 0;function T(e,t){var s=this,o=new this.constructor(b);void 0===o[I]&&J(o);var n=s._state;if(n){var r=arguments[n-1];a((function(){return _(n,o,r,s._result)}))}else G(s,o,e,t);return o}function k(e){var t=this;if(e&&"object"==typeof e&&e.constructor===t)return e;var s=new t(b);return U(s,e),s}A=p?y():m?f():h?g():void 0===d?P():S();var I=Math.random().toString(36).substring(2);function b(){}var w=void 0,D=1,N=2;function x(){return new TypeError("You cannot resolve a promise with itself")}function O(){return new TypeError("A promises callback cannot return that same promise.")}function M(e,t,s,o){try{e.call(t,s,o)}catch(e){return e}}function R(e,t,s){a((function(e){var o=!1,n=M(s,t,(function(s){o||(o=!0,t!==s?U(e,s):W(e,s))}),(function(t){o||(o=!0,j(e,t))}),"Settle: "+(e._label||" unknown promise"));!o&&n&&(o=!0,j(e,n))}),e)}function F(e,t){t._state===D?W(e,t._result):t._state===N?j(e,t._result):G(t,void 0,(function(t){return U(e,t)}),(function(t){return j(e,t)}))}function L(e,s,o){s.constructor===e.constructor&&o===T&&s.constructor.resolve===k?F(e,s):void 0===o?W(e,s):t(o)?R(e,s,o):W(e,s)}function U(t,s){if(t===s)j(t,x());else if(e(s)){var o=void 0;try{o=s.then}catch(e){return void j(t,e)}L(t,s,o)}else W(t,s)}function B(e){e._onerror&&e._onerror(e._result),H(e)}function W(e,t){e._state===w&&(e._result=t,e._state=D,0!==e._subscribers.length&&a(H,e))}function j(e,t){e._state===w&&(e._state=N,e._result=t,a(B,e))}function G(e,t,s,o){var n=e._subscribers,r=n.length;e._onerror=null,n[r]=t,n[r+D]=s,n[r+N]=o,0===r&&e._state&&a(H,e)}function H(e){var t=e._subscribers,s=e._state;if(0!==t.length){for(var o=void 0,n=void 0,r=e._result,i=0;i<t.length;i+=3)o=t[i],n=t[i+s],o?_(s,o,n,r):n(r);e._subscribers.length=0}}function _(e,s,o,n){var r=t(o),i=void 0,a=void 0,l=!0;if(r){try{i=o(n)}catch(e){l=!1,a=e}if(s===i)return void j(s,O())}else i=n;s._state!==w||(r&&l?U(s,i):!1===l?j(s,a):e===D?W(s,i):e===N&&j(s,i))}function z(e,t){try{t((function(t){U(e,t)}),(function(t){j(e,t)}))}catch(t){j(e,t)}}var V=0;function q(){return V++}function J(e){e[I]=V++,e._state=void 0,e._result=void 0,e._subscribers=[]}function $(){return new Error("Array Methods must be provided an Array")}var Q=function(){function e(e,t){this._instanceConstructor=e,this.promise=new e(b),this.promise[I]||J(this.promise),s(t)?(this.length=t.length,this._remaining=t.length,this._result=new Array(this.length),0===this.length?W(this.promise,this._result):(this.length=this.length||0,this._enumerate(t),0===this._remaining&&W(this.promise,this._result))):j(this.promise,$())}return e.prototype._enumerate=function(e){for(var t=0;this._state===w&&t<e.length;t++)this._eachEntry(e[t],t)},e.prototype._eachEntry=function(e,t){var s=this._instanceConstructor,o=s.resolve;if(o===k){var n=void 0,r=void 0,i=!1;try{n=e.then}catch(e){i=!0,r=e}if(n===T&&e._state!==w)this._settledAt(e._state,t,e._result);else if("function"!=typeof n)this._remaining--,this._result[t]=e;else if(s===te){var a=new s(b);i?j(a,r):L(a,e,n),this._willSettleAt(a,t)}else this._willSettleAt(new s((function(t){return t(e)})),t)}else this._willSettleAt(o(e),t)},e.prototype._settledAt=function(e,t,s){var o=this.promise;o._state===w&&(this._remaining--,e===N?j(o,s):this._result[t]=s),0===this._remaining&&W(o,this._result)},e.prototype._willSettleAt=function(e,t){var s=this;G(e,void 0,(function(e){return s._settledAt(D,t,e)}),(function(e){return s._settledAt(N,t,e)}))},e}();function K(e){return new Q(this,e).promise}function Y(e){var t=this;return s(e)?new t((function(s,o){for(var n=e.length,r=0;r<n;r++)t.resolve(e[r]).then(s,o)})):new t((function(e,t){return t(new TypeError("You must pass an array to race."))}))}function X(e){var t=new this(b);return j(t,e),t}function Z(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function ee(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}var te=function(){function e(t){this[I]=q(),this._result=this._state=void 0,this._subscribers=[],b!==t&&("function"!=typeof t&&Z(),this instanceof e?z(this,t):ee())}return e.prototype.catch=function(e){return this.then(null,e)},e.prototype.finally=function(e){var s=this,o=s.constructor;return t(e)?s.then((function(t){return o.resolve(e()).then((function(){return t}))}),(function(t){return o.resolve(e()).then((function(){throw t}))})):s.then(e,e)},e}();function se(){var e=void 0;if(void 0!==i)e=i;else if("undefined"!=typeof self)e=self;else try{e=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var t=e.Promise;if(t){var s=null;try{s=Object.prototype.toString.call(t.resolve())}catch(e){}if("[object Promise]"===s&&!t.cast)return}e.Promise=te}return te.prototype.then=T,te.all=K,te.race=Y,te.resolve=k,te.reject=X,te._setScheduler=l,te._setAsap=c,te._asap=a,te.polyfill=se,te.Promise=te,te}();
2
2
  /*!
3
3
  * @overview es6-promise - a tiny implementation of Promises/A+.
4
4
  * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
5
5
  * @license Licensed under MIT license
6
6
  * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
7
7
  * @version v4.2.8+1e68dce6
8
- */class d{}d.rcSuccess="rcSuccess",d.rcBadSession="rcBadSession",d.rcDuplicateContact="rcDuplicateContact",d.rcWebServiceMoved="rcWebServiceMoved",d.rcAccessDenied="rcAccessDenied",d.rcLoginUserNameChanged="rcLoginUserNameChanged",d.rcLicenseExpired="rcLicenseExpired",exports.HttpMethod=void 0,(a=exports.HttpMethod||(exports.HttpMethod={})).get="get",a.post="post";class u{}u.absence="Absence",u.bonusType="BonusType",u.busyStatus="BusyStatus",u.cartType="CartType",u.companyType="CompanyType",u.contactType="ContactType",u.countryCode="CountryCode",u.currency="Currency",u.customFieldCategory="CustomFieldCategory",u.dayType="DayType",u.documentOfflineState="DocumentOfflineState",u.documentType="DocumentType",u.emailCampaignWorkflowStatus="EmailCampaignWorkflowStatus",u.emailOfflineState="EmailOfflineState",u.emailType="EmailType",u.familyStatus="FamilyStatus",u.firstContact="FirstContact",u.globalSettingsCategory="GlobalSettingsCategory",u.goalType="GoalType",u.groupColor="GroupColor",u.importance="Importance",u.journalType="JournalType",u.knowledgeLevel="KnowledgeLevel",u.knowledgeTitle="KnowledgeTitle",u.knowledgeType="KnowledgeType",u.leadType="LeadType",u.marketingType="MarketingType",u.paymentType="PaymentType",u.prefixType="PrefixType",u.productType="ProductType",u.projectOrigin="ProjectOrigin",u.projectType="ProjectType",u.reportCategory="ReportCategory",u.responseForm="ResponseForm",u.responseType="ResponseType",u.salaryDate="SalaryDate",u.salaryType="SalaryType",u.salePriceType="SalePriceType",u.sentimentTone="SentimentTone",u.suffixType="SuffixType",u.taskImportance="TaskImportance",u.tasksSnoozePeriod="TasksSnoozePeriod",u.taskStatus="TaskStatus",u.taskType="TaskType",u.trainingGrade="TrainingGrade",u.trainingTitle="TrainingTitle",u.translations="Translations",u.units="Units",u.userType="UserType",u.usStatesDistrictsTerritories="USStatesDistrictsTerritories",u.vacationType="VacationType",u.vat="VAT",u.workLoad="WorkLoad",u.workReportType="WorkReportType";class m{}m.isValidFolderName=e=>Object.values(m).includes(e),m.actions="Actions",m.additionalFields="AdditionalFields",m.bonuses="Bonuses",m.calendar="Calendar",m.capacityNotes="CapacityNotes",m.capacityNoteTypes="CapacityNoteTypes",m.carts="Carts",m.columnPermissions="ColumnPermissions",m.companies="Companies",m.contacts="Contacts",m.currencyExchangeRates="CurrencyExchangeRates",m.documents="Documents",m.emails="Emails",m.enumTypes="EnumTypes",m.enumValues="EnumValues",m.enumValuesRelations="EnumValuesRelations",m.features="Features",m.flows="Flows",m.globalSettings="GlobalSettings",m.goals="Goals",m.goods="Goods",m.goodsInCart="GoodsInCart",m.goodsInSet="GoodsInSet",m.groups="Groups",m.history="History",m.holidays="Holidays",m.children="Children",m.individualDiscounts="IndividualDiscounts",m.invoiceItems="InvoiceItems",m.invoices="Invoices",m.itemCopyRelations="ItemCopyRelations",m.journal="Journal",m.knowledge="Knowledge",m.layouts="Layouts",m.layoutsModels="LayoutsModels",m.leads="Leads",m.ledger="Ledger",m.mappings="Mappings",m.marketing="Marketing",m.marketingList="MarketingList",m.marketingListSources="MarketingListSources",m.models="Models",m.modulePermissions="ModulePermissions",m.objectTypesOptions="ObjectTypesOptions",m.payments="Payments",m.priceListGroups="PriceListGroups",m.projectAssignments="ProjectAssignments",m.projectAssignmentsPerUserProject="ProjectAssignmentsPerUserProject",m.projectAssignmentsTotal="ProjectAssignmentsTotal",m.projectAssignmentsTotalUserProject="ProjectAssignmentsTotalUserProject",m.projectList="ProjectList",m.projects="Projects",m.projectUsersInCaPlan="ProjectUsersInCaPlan",m.relationData="RelationData",m.relations="Relations",m.reports="Reports",m.revisionsHistory="RevisionsHistory",m.salaries="Salaries",m.salePrices="SalePrices",m.prices="Prices",m.sqlObjects="SqlObjects",m.tasks="Tasks",m.recurrencePatterns="RecurrencePatterns",m.teamRoles="TeamRoles",m.templates="Templates",m.training="Training",m.unifiedRelations="UnifiedRelations",m.users="Users",m.userSettings="UserSettings",m.vacation="Vacation",m.webAccess2Options="WebAccess2Options",m.webAccessOptions="WebAccessOptions",m.workCommitments="WorkCommitments",m.workflowHistory="WorkflowHistory",m.workReports="WorkReports",m.wrongClientVersions="WrongClientVersions",m.xsltTransformations="XsltTransformations",m.getEnumTypeName=e=>e===m.bonuses?u.bonusType:e===m.carts?u.cartType:e===m.companies?u.companyType:e===m.contacts?u.contactType:e===m.documents?u.documentType:e===m.emails?u.emailType:e===m.goals?u.goalType:e===m.goods?u.productType:e===m.journal?u.journalType:e===m.knowledge?u.knowledgeType:e===m.leads?u.leadType:e===m.marketing?u.marketingType:e===m.projects?u.projectType:e===m.salaries?u.salaryType:e===m.salePrices?u.salePriceType:e===m.tasks?u.taskType:e===m.training?u.trainingTitle:e===m.users?u.userType:e===m.vacation?u.vacationType:e===m.workReports?u.workReportType:null,m.getFolderNameByEnumTypeName=e=>e===u.bonusType?m.bonuses:e===u.cartType?m.carts:e===u.companyType?m.companies:e===u.contactType?m.contacts:e===u.documentType?m.documents:e===u.emailType?m.emails:e===u.goalType?m.goals:e===u.journalType?m.journal:e===u.knowledgeType?m.knowledge:e===u.leadType?m.leads:e===u.marketingType?m.marketing:e===u.productType?m.goods:e===u.projectType?m.projects:e===u.salaryType?m.salaries:e===u.salePriceType?m.salePrices:e===u.taskType?m.tasks:e===u.trainingTitle?m.training:e===u.userType?m.users:e===u.vacationType?m.vacation:e===u.workReportType?m.workReports:null;class p{}p.getAllEmailAttachments="GetAllEmailAttachments",p.getCalendarsByItemGuids="GetCalendarsByItemGuids",p.getEmailAttachment="GetEmailAttachment",p.getItemPreview="GetItemPreview",p.getJournalsByItemGuids="GetJournalsByItemGuids",p.getMarketingCampaignsByItemGuids="GetMarketingCampaignsByItemGuids",p.getMarketingListsRecordsByItemGuids="GetMarketingListsRecordsByItemGuids",p.getRevisionHistoryRecordsByItemGuids="GetRevisionHistoryRecordsByItemGuids",p.getVacationsByItemGuids="GetVacationsByItemGuids",p.getWorkflowHistoryRecordsByItemGuids="GetWorkflowHistoryRecordsByItemGuids",p.getCompanyInformationFromTaxRegister="GetCompanyInformationFromTaxRegister",p.logIn="LogIn",p.logOut="LogOut",p.query="Query",p.queryAmount="QueryAmount",p.getServiceAuthSettings="GetServiceAuthSettings",p.getVersion="GetVersion",p.getBinaryAttachment="GetBinaryAttachment",p.getBinaryAttachmentLatestRevision="GetBinaryAttachmentLatestRevision",p.canUnlinkItems="CanUnlinkItems",p.unlinkItems="UnlinkItems",p.getGetFolderNameByItemGuidsMethodName=e=>{switch(e){case m.calendar:return p.getCalendarsByItemGuids;case m.journal:return p.getJournalsByItemGuids;case m.marketing:return p.getMarketingCampaignsByItemGuids;case m.marketingList:return p.getMarketingListsRecordsByItemGuids;case m.revisionsHistory:return p.getRevisionHistoryRecordsByItemGuids;case m.vacation:return p.getVacationsByItemGuids;case m.workflowHistory:return p.getWorkflowHistoryRecordsByItemGuids;default:return`Get${e}ByItemGuids`}};class h{constructor(e,t,s,o,n,r){if(this.invalidateSessionId=(e,t)=>{t&&t()},this.getSessionId=(e,t)=>{e.callWithoutSession(p.logIn,{userName:this.username,passwordHash:this.passwordHash,appVersion:this.appVersion,clientMachineIdentifier:this.clientMachineIdentifier,clientMachineName:this.clientMachineName,createSessionCookie:e.supportsGetItemPreviewMethod},(e=>{this.lastSuccessfulLoginResponse=e;const s=e.SessionId;if(s)t&&t(s);else{const e=new Error("Successful login but no session came.");if(!this.errorCallback)throw e;this.errorCallback(e)}}),(e=>{const t=new Error("Unable to login. Error response follows.\n"+JSON.stringify(e));if(!this.errorCallback)throw t;this.errorCallback(t)}))},!e||!t)throw new Error("Non of the arguments 'username', 'passwordHash' can be empty.");this.username=e,this.passwordHash=t,this.appVersion=s,this.clientMachineIdentifier=o,this.clientMachineName=n,this.errorCallback=r}}class y{constructor(){this.getSessionId=(e,t)=>{throw new Error("With anonymous session handler, use only connection methods without session.")},this.invalidateSessionId=(e,t)=>{throw new Error("With anonymous session handler, use only connection methods without session.")}}}class C{}C.finishAuthorization=(e,t,s,o,n,r,i)=>{const a=new URLSearchParams;a.append("code_verifier",o),a.append("client_id",t),a.append("client_secret",s),a.append("code",n),a.append("redirect_uri",r),a.append("grant_type","authorization_code"),C.callTokenEndpoint(e,a,i)},C.refreshToken=(e,t,s,o,n)=>{const r=new URLSearchParams;r.append("client_id",t),r.append("client_secret",s),r.append("refresh_token",o),r.append("grant_type","refresh_token"),C.callTokenEndpoint(e,r,n)},C.getWebServiceUrl=e=>{const t=e.split(".");if(2!==t.length)throw new Error("Invalid token supplied");return r.decode(t[1])},C.getUserName=e=>C.decodeAccessToken(e).username,C.decodeAccessToken=e=>s(e),C.callTokenEndpoint=(t,s,o)=>{e.post(t+"/auth/connect/token",s,{headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then((e=>{o(e.data)})).catch((e=>{if(!e.response||400!=e.response.status)throw new Error("Token request failed");o(e.response.data)}))};class f extends Error{constructor(e,t){super(),this.returnCode=e,this.message=t}}class g{constructor(e,t,s,o,n){if(this.invalidateSessionId=(e,t)=>{t&&t()},this.getSessionId=(e,t)=>{const s={userName:this.username,appVersion:this.appVersion,createSessionCookie:e.supportsGetItemPreviewMethod},o={Authorization:"Bearer "+this.accessToken};e.callWithoutSession(p.logIn,s,(e=>{this.lastSuccessfulLoginResponse=e;const s=e.SessionId;if(s)t&&t(s);else{const e=new Error("Successful login but no session came.");if(!this.errorCallback)throw e;this.errorCallback(e)}}),(e=>{const t=new f(e.ReturnCode,"Unable to login. Error response follows.\n"+JSON.stringify(e));if(!this.errorCallback)throw t;this.errorCallback(t)}),o,void 0,(s=>{if(401!==(null==s?void 0:s.statusCode)){if(!this.errorCallback)throw s;this.errorCallback(s)}else this.getNewAccessTokenCallback(e,((s,o)=>{this.accessToken=s,o||this.getSessionId(e,t)}))}))},!e)throw new Error("Non of the arguments 'username', 'clientId', 'clientSecret', 'refreshToken' can be empty.");this.username=e,this.accessToken=t,this.appVersion=s,this.getNewAccessTokenCallback=o,this.errorCallback=n}}class S extends g{constructor(e,t,s,o,n,r,i,a){if(!(e&&o&&t&&s))throw new Error("Non of the arguments 'username', 'clientId', 'clientSecret', 'refreshToken' can be empty.");super(e,n,r,((e,t)=>{C.refreshToken(e.wsUrl,this.clientId,this.clientSecret,this.refreshToken,(e=>{try{this.refreshTokenCallback&&this.refreshTokenCallback(e)}catch(e){this.errorCallback&&this.errorCallback(new Error("Refresh token callback failed.\n"+JSON.stringify(e)))}t(e.access_token,e.error)}))}),i),this.refreshToken=o,this.clientId=t,this.clientSecret=s,this.refreshTokenCallback=a}}class E extends Error{constructor(e,t){super(),this.statusCode=e,this.message=t}}class v{}v.stringifyError=e=>JSON.stringify(e,v.replaceErrors),v.replaceErrors=(e,t)=>{if(t instanceof Error){const e={};return Object.getOwnPropertyNames(t).forEach((s=>{e[s]=t[s]})),e}return t};class P{constructor(t,s,o,n){if(this.createOpenLink=(e,t,s,o)=>{const n=r.encode(this.baseUri);let i="eway://"+t;s&&(i+="/"+(null==s?void 0:s.toLowerCase()));const a=e?"open.eway-crm.dev":"open.eway-crm.com";i=r.encode(i);let l="https://"+a+"/?ws="+n+"&l="+i;return o&&(l+="&n="+encodeURIComponent(o)),l},this.askUploadMethod=(e,t,s,o,n)=>new Promise(((r,i)=>{const a=n?e=>{throw i(e),e}:i;this.callUploadMethod(e,t,s,r,a,a,o)})),this.callUploadMethod=(t,s,o,n,r,i,a)=>{const l=()=>{this.sessionHandler.getSessionId(this,(e=>{this.sessionId=e,this.callUploadMethod(t,s,o,n,r,i,a)}))},c=this.sessionId;if(!c)return void l();const u=`${this.svcUri}/SaveBinaryAttachment?sessionId=${this.sessionId}&itemGuid=${t}&fileName=${encodeURIComponent(s)}`,m=e.post(u,o,a);P.handleCallPromise(m,n,(e=>{if(e.ReturnCode===d.rcBadSession)return this.sessionId=null,void this.sessionHandler.invalidateSessionId(c,l);if(r)r(e);else{const t=new Error("Unhandled connection return code "+e.ReturnCode+": "+e.Description);if(!this.errorCallback)throw t;this.errorCallback(t)}}),(e=>{let t=new Error("Unhandled connection error when calling "+u+": "+v.stringifyError(e));if("statusCode"in e&&413===e.statusCode&&(t=new Error("The file has exceeded the maximum allowed file size for uploading. You can contact your IT administrator or eWay-CRM support if you would like to increase the limit.")),i)i(t);else{if(!this.errorCallback)throw t;this.errorCallback(t)}}))},this.askMethod=(e,t,s,o)=>new Promise(((n,r)=>{const i=o?e=>{throw r(e),e}:r;this.callMethod(e,t,n,i,s,i)})),this.callMethod=(e,t,s,o,n,r)=>{n||(n=exports.HttpMethod.post);const i=()=>{this.sessionHandler.getSessionId(this,(i=>{this.sessionId=i,this.callMethod(e,t,s,o,n,r)}))},a=this.sessionId;if(!a)return void i();t.sessionId=a;const l=e!==p.logOut?s:e=>{this.sessionId=null,s(e)};this.callWithoutSession(e,t,l,(s=>{if(s.ReturnCode!==d.rcBadSession||(this.sessionId=null,e===p.logOut))if(o)o(s);else{const e=new Error("Unhandled connection return code "+s.ReturnCode+": "+s.Description);if(!this.errorCallback)throw e;this.errorCallback(e,t)}else this.sessionHandler.invalidateSessionId(a,i)}),null,n,r)},this.callWithoutSession=(t,s,o,n,r,i,a)=>{var l;i||(i=exports.HttpMethod.post);const c=this.svcUri+"/"+t;let d,u;switch(r&&(d={headers:r,withCredentials:null!==(l=this.supportGetItemPreviewMethod)&&void 0!==l?l:t==p.logIn}),i){case exports.HttpMethod.get:if(s)throw new Error("Calling api get method with data specified does not make any sense.");u=e.get(c,d);break;case exports.HttpMethod.post:u=e.post(c,s,d);break;default:throw new Error(`Unknown http method '${i}'.`)}P.handleCallPromise(u,o,n,(e=>{if(a)try{a(e)}catch(e){if(!this.errorCallback)throw e;this.errorCallback(e,s)}else{const t=new Error("Unhandled connection error when calling "+c+": "+v.stringifyError(e));if(!this.errorCallback)throw t;this.errorCallback(t,s)}}))},this.getItemPreviewGetMethodUrl=(e,t,s)=>this.svcUri+"/"+p.getItemPreview+"?folderName="+encodeURIComponent(e)+"&itemGuid="+encodeURIComponent(t)+(s||0===s?"&itemVersion="+encodeURIComponent(s.toString()):""),this.getEmailAttachmentGetMethodUrl=(e,t)=>this.svcUri+"/"+p.getEmailAttachment+"?itemGuid="+encodeURIComponent(e)+"&contentId="+encodeURIComponent(t),this.getAllEmailAttachmentsZipGetMethodUrl=e=>this.svcUri+"/"+p.getAllEmailAttachments+"?itemGuid="+encodeURIComponent(e),this.getBinaryAttachmentGetMethodUrl=(e,t)=>"number"==typeof t?this.svcUri+"/"+p.getBinaryAttachment+"?itemGuid="+encodeURIComponent(e)+`&revision=${t}`:this.svcUri+"/"+p.getBinaryAttachmentLatestRevision+"?itemGuid="+encodeURIComponent(e),this.getActiveSessionId=()=>this.sessionId,this.setActiveSessionId=e=>{this.sessionId=e},!t)throw new Error("The argument 'apiServiceUri' cannot be empty.");if(t.length<8||"https://"!==t.substr(0,8).toLowerCase()&&"http://"!==t.substr(0,7).toLowerCase())throw new Error("Api service uri must start either with 'https://' or with 'http://'.");if(".svc"===t.substr(t.length-4).toLowerCase()){this.svcUri=t;const e=["/API.svc","/InsecureAPI.svc","/WcfService/Service.svc"].find((e=>e.toLowerCase()===t.substr(t.length-e.length).toLowerCase()))||"";this.baseUri=t.substr(0,t.length-e.length)}else this.baseUri=P.normalizeWsUrl(t)||t,"https://"===t.substr(0,8).toLowerCase()?this.svcUri=this.baseUri+"/API.svc":this.svcUri=this.baseUri+"/InsecureAPI.svc";this.sessionHandler=s,this.errorCallback=o,this.sessionId=null,this.supportGetItemPreviewMethod=null!=n&&n}get supportsGetItemPreviewMethod(){return this.supportGetItemPreviewMethod}static create(e,t,s,o,n,r,i,a){return new P(e,new h(t,s,o,n,r,i),i,a)}static createAnonymous(e,t){return new P(e,new y,t)}static createUsingOAuth(e,t,s,o,n,r,i,a,l,c){return new P(e,new S(t,s,o,n,r,i,a,l),a,c)}static normalizeWsUrl(e){return e&&e.endsWith("/")&&(e=e.substring(0,e.length-1)),e}get wsUrl(){return this.baseUri}static handleCallPromise(e,t,s,o){e.then((e=>{200===e.status?e.data.ReturnCode===d.rcSuccess?t(e.data):s(e.data):o(new E(e.status,e.statusText))})).catch((e=>{e.response?o(new E(e.response.status,e.response.statusText)):o(e)}))}}class A{constructor(e,t,s,o,n,r,i){this.isEnabled=(e,t)=>{const s=()=>{this.url&&this.token?e(this.url,this.token):t()};this.url&&this.token?e(this.url,this.token):this.obtainToken(s)},this.callTokenizedApi=(e,t,s,o)=>{this.isEnabled(((n,r)=>{t.token=r,A.call(n,e,t,s,(n=>{if(n.ReturnCodeString!==this.invalidTokenReturnCode){if(o)o(n);else if(this.generalErrorCallback){const e=new Error("Unhandled tokenized service connection return code "+n.ReturnCodeString+".\nDescription: "+n.Description);this.generalErrorCallback(e)}}else this.obtainToken((()=>{this.callTokenizedApi(e,t,s,o)}))}),(e=>{if(this.generalErrorCallback){const t=new Error("Unhandled tokenized service connection communication error: "+JSON.stringify(e));this.generalErrorCallback(t)}}))}),(()=>{o&&o(null)}))},this.obtainToken=e=>{if(!this.isActive)return this.url=null,this.token=null,void e();const t=t=>{const s=this.urlAndTokenObtainer(t);s.url&&s.token?(this.url=s.url,this.token=s.token,this.isActive=!0,e()):(this.url=null,this.token=null,this.isActive=!1,e())},s=()=>{this.url=null,this.token=null,this.isActive=!1,e()};this.needsSession?this.connection.callMethod(this.obtainTokenMethodName,{},t,s,this.obtainTokenMethodType):this.connection.callWithoutSession(this.obtainTokenMethodName,null,t,s,null,this.obtainTokenMethodType)},this.obtainTokenMethodName=e,this.obtainTokenMethodType=t,this.needsSession=s,this.invalidTokenReturnCode=o,this.urlAndTokenObtainer=n,this.connection=r,this.generalErrorCallback=i||null,this.url=null,this.token=null,this.isActive=!0}static call(t,s,o,n,r,i){const a=t+"/"+s;e.post(a,o).then((e=>{200===e.status?"Success"===e.data.ReturnCodeString?n(e.data):r(e.data):i(new E(e.status,e.statusText))})).catch((e=>{e.response?i(new E(e.response.status,e.response.statusText)):i(e)}))}}const T=e=>({url:e.ServiceUrl,token:e.Token});class k{}k.acceptableBackwardWorkReportDays="AcceptableBackwardWorkReportDays",k.adminAppInactiveLogoutTime="AdminAppInactiveLogoutTime",k.applyGeneralDataProtectionRules="ApplyGeneralDataProtectionRules",k.automaticallyCreateJournalAfterCallDuration="AutomaticallyCreateJournalAfterCallDuration",k.bonusesCompletedState="BonusesCompletedState",k.cartInvoicedState="CartInvoicedState",k.cartOrderCanceledState="CartOrderCanceledState",k.cartOrderInProcessState="CartOrderInProcessState",k.cartOrderProcessedState="CartOrderProcessedState",k.cartPaidState="CartPaidState",k.cartProposalInProcessState="CartProposalInProcessState",k.cartProposalProcessedState="CartProposalProcessedState",k.cartSalesVoucherIssuedState="CartSalesVoucherIssuedState",k.cartToBeInvoicedState="CartToBeInvoicedState",k.cartVoidedState="CartVoidedState",k.clickToCallScheme="ClickToCallScheme",k.companyDuplicityCheckEnabled="CompanyDuplicityCheckEnabled",k.completedStateName="CompletedStateName",k.contactDuplicityCheckEnabled="ContactDuplicityCheckEnabled",k.createCompanyWhileImportingContactFromOutlook="CreateCompanyWhileImportingContactFromOutlook",k.enableContactsTwoWaySyncWithM365="EnableContactsTwoWaySyncWithM365",k.deadStateName="DeadStateName",k.enableCompaniesSyncIntoMobileDeviceContacts="EnableCompaniesSyncIntoMobileDeviceContacts",k.enableContactsSyncIntoMobileDevice="EnableContactsSyncIntoMobileDevice",k.enableLeadsSyncIntoMobileDeviceContacts="EnableLeadsSyncIntoMobileDeviceContacts",k.enableLlamaAiFeatures="EnableLlamaAiFeatures",k.enableUsersSyncIntoMobileDeviceContacts="EnableUsersSyncIntoMobileDeviceContacts",k.emailsActiveProjectsLeadsFilter="EmailsActiveProjectsLeadsFilter",k.exchangeRatesAdminGroupName="ExchangeRatesAdminGroupName",k.forcedEmailTrackingGroups="ForcedEmailTrackingGroups",k.ignoreEmailsFromDomainsOnEmailsTracking="IgnoreEmailsFromDomainsOnEmailsTracking",k.trackEmailsFromDomains="TrackEmailsFromDomains",k.groupsForAllUnpaidInvoicesNotification="GroupsForAllUnpaidInvoicesNotification",k.itemPreviewMaxHeight="ItemPreviewMaxHeight",k.lastActivityAttributes="LastActivityAttributes",k.leadsCompletedState="LeadsCompletedState",k.leadDeadlineAlertGroups="LeadDeadlineAlertGroups",k.leadsDeadState="LeadsDeadState",k.marketingCompletedState="MarketingCompletedState",k.marketingDeadState="MarketingDeadState",k.minimumPasswordLength="MinimumPasswordLength",k.nextStepAttributes="NextStepAttributes",k.notifyAboutInvoicedInvoiceInPohodaGroup="NotifyAboutInvoicedInvoiceInPohodaGroup",k.notifyAboutLeadsDeadline="NotifyAboutLeadsDeadline",k.notifyAboutPaidInvoiceInPohodaGroup="NotifyAboutPaidInvoiceInPohodaGroup",k.notifyAboutProjectDeadline="NotifyAboutProjectDeadline",k.numberOfDecimalPlaces="NumberOfDecimalPlaces",k.phoneListTaskSolverGroup="PhoneListTaskSolverGroup",k.projectDeadlineAlert="ProjectDeadlineAlert",k.serverUpdateProgressNotificationGroup="ServerUpdateProgressNotificationGroup",k.sumarizeCartsPricesOnLeads="SumarizeCartsPricesOnLeads",k.sumarizeCartsPricesOnProjects="SumarizeCartsPricesOnProjects",k.sumarizePeopleExpensesOnProjects="SumarizePeopleExpensesOnProjects",k.systemHealthNotificationGroup="SystemHealthNotificationGroup",k.tasksCompletedState="TasksCompletedState",k.tasksDeferredState="TasksDeferredState",k.tasksInProgressState="TasksInProgressState",k.tasksNotStartedState="TasksNotStartedState",k.tasksWaitOnSomeoneElseState="TasksWaitOnSomeoneElseState",k.trackDocumentVersions="TrackDocumentVersions",k.vacationCompletedState="VacationCompletedState",k.workReportApprovedState="WorkReportApprovedState",k.defaultLanguage="DefaultLanguage",k.defaultCurrency="DefaultCurrency",k.myCompanyCountry="MyCompanyCountry",k.myCompanyName="MyCompanyName",k.myCompanyStreet="MyCompanyStreet",k.myCompanyCity="MyCompanyCity",k.myCompanyState="MyCompanyState",k.myCompanyZip="MyCompanyZIP",k.myCompanyId="MyCompanyID",k.myCompanyVat="MyCompanyVAT";class I{}I.ServerCommon={Server_ID:"Server_ID",Server_ItemCreated:"Server_ItemCreated",Server_ItemChanged:"Server_ItemChanged"},I.Common={CreatedByGUID:"CreatedByGUID",CurrencyEn:"CurrencyEn",DefaultCurrencySuffix:"DefaultCurrency",FileAs:"FileAs",ItemCreated:"ItemCreated",ItemChanged:"ItemChanged",ItemGUID:"ItemGUID",ItemVersion:"ItemVersion",ModifiedByGUID:"ModifiedByGUID",OwnerGUID:"OwnerGUID",ParentCurrencySuffix:"ParentCurrency"},I.Calendar={EndDate:"EndDate",Note:"Note"},I.Carts={SuperiorItem:"SuperiorItem",SuperiorCompany:"SuperiorCompany",SuperiorContact:"SuperiorContact",TypeEn:"TypeEn",StateEn:"StateEn"},I.Companies={ID:"ID",CompanyName:"CompanyName",Department:"Department",AccountNumber:"AccountNumber",IdentificationNumber:"IdentificationNumber",VatNumber:"VatNumber",Sales:"Reversal",EmployeesCount:"EmployeesCount",Purchaser:"Purchaser",Suppliers:"Suppliers",Competitor:"Competitor",Address1Street:"Address1Street",Address1City:"Address1City",Address1PostalCode:"Address1PostalCode",Address1CountryEn:"Address1CountryEn",Address1State:"Address1State",Address1POBox:"Address1POBox",Address2Street:"Address2Street",Address2City:"Address2City",Address2PostalCode:"Address2PostalCode",Address2CountryEn:"Address2CountryEn",Address2State:"Address2State",Address2POBox:"Address2POBox",Address3Street:"Address3Street",Address3City:"Address3City",Address3PostalCode:"Address3PostalCode",Address3CountryEn:"Address3CountryEn",Address3State:"Address3State",Address3POBox:"Address3POBox",InvoiceAddress:"InvoiceAddress",PostalAddress:"PostalAddress",Phone:"Phone",Mobile:"Mobile",Fax:"Fax",WebPage:"WebPage",Email:"Email",ICQ:"ICQ",MSN:"MSN",Skype:"Skype",ImportanceEn:"ImportanceEn",FirstContactEn:"FirstContactEn",LineOfBusiness:"LineOfBusiness",EmailOptOut:"EmailOptOut",MailingListOther:"MailingListOther",MailingListOtherValue:"MailingListOtherValue",Note:"Note",IsPrivate:"IsPrivate",NextStep:"NextStep",LastActivity:"LastActivity",AdditionalDiscount:"AdditionalDiscount"},I.Contacts={ProfilePicture:"ProfilePicture",Title:"Title",Email1Address:"Email1Address",Email2Address:"Email2Address",Email3Address:"Email3Address",DoNotSendNewsletter:"DoNotSendNewsletter",ImportanceEn:"ImportanceEn",PrefixEn:"PrefixEn",FirstName:"FirstName",MiddleName:"MiddleName",LastName:"LastName",SuffixEn:"SuffixEn",BusinessAddressStreet:"BusinessAddressStreet",BusinessAddressCity:"BusinessAddressCity",BusinessAddressPostalCode:"BusinessAddressPostalCode",BusinessAddressCountryEn:"BusinessAddressCountryEn",BusinessAddressState:"BusinessAddressState",BusinessAddressPoBox:"BusinessAddressPOBox",HomeAddressStreet:"HomeAddressStreet",HomeAddressCity:"HomeAddressCity",HomeAddressPostalCode:"HomeAddressPostalCode",HomeAddressCountryEn:"HomeAddressCountryEn",HomeAddressState:"HomeAddressState",HomeAddressPOBox:"HomeAddressPOBox",OtherAddressStreet:"OtherAddressStreet",OtherAddressCity:"OtherAddressCity",OtherAddressPostalCode:"OtherAddressPostalCode",OtherAddressCountryEn:"OtherAddressCountryEn",OtherAddressState:"OtherAddressState",OtherAddressPOBox:"OtherAddressPOBox",BusinessPhoneNumber:"TelephoneNumber1",BusinessPhoneNumber2:"TelephoneNumber5",BusinessFaxNumber:"TelephoneNumber6",MobilePhoneNumber:"TelephoneNumber3",HomePhoneNumber:"TelephoneNumber2",OtherPhoneNumber:"TelephoneNumber4",ICQ:"ICQ",MSN:"MSN",Skype:"Skype",WebPage:"WebPage",Note:"Note",Department:"Department",Company:"Company",IsPrivate:"Private",NextStep:"NextStep",LastActivity:"LastActivity"},I.Leads={ID:"ID",FileAs:"FileAs",HumanID:"HID",Customer:"Customer",ContactPerson:"ContactPerson",Marketing:"Marketing",ReceiveDate:"ReceiveDate",Email:"Email",Phone:"Phone",Street:"Street",State:"State",CountryEn:"CountryEn",City:"City",POBox:"POBox",Zip:"Zip",Price:"Price",PriceChanged:"PriceChanged",CurrencyEn:I.Common.CurrencyEn,EstimatedEnd:"EstimatedEnd",Probability:"Probability",LeadOriginEn:"LeadOriginEn",PriceDefaultCurrency:"PriceDefaultCurrency",EstimatedValue:"EstimatedValue",EstimatedValueDefaultCurrency:"EstimatedValueDefaultCurrency",Note:"Note",TypeEn:"TypeEn",StateEn:"StateEn",PrevStateEn:"PrevStateEn",IsPrivate:"Private",EmailOptOut:"EmailOptOut",NextStep:"NextStep",LastActivity:"LastActivity",ItemVersion:"ItemVersion",EstimatedRevenue:"EstimatedRevenue",EstimatedRevenueDefaultCurrency:"EstimatedRevenueDefaultCurrency",CompletedDate:"CompletedDate",LostDate:"LostDate"},I.Documents={FileAs:"FileAs",DocName:"DocName",Preview:"Preview",PreviewWidth:"PreviewWidth",PreviewHeight:"PreviewHeight",DocTypeEn:"DocTypeEn",StateEn:"StateEn",ImportanceEn:"ImportanceEn",SuperiorItem:"SuperiorItem",SuperiorCompany:"Company",SuperiorContact:"Contact",DocSize:"DocSize",Extension:"Extension",CreationTime:"CreationTime",LastWriteTime:"LastWriteTime",IsPrivate:"Private",Note:"Note"},I.Emails={To:"To",From:"SenderEmailAddress",Cc:"Cc",Subject:"Subject",ImportanceEn:"ImportanceEn",SuperiorItem:"SuperiorItem",SentOn:"SentOn",ReceivedTime:"ReceivedTime",FileSize:"FileSize",AttachmentsCount:"AttachmentsCount",Note:"Note",SentimentTone:"SentimentTone",Summary:"Summary"},I.Goods={Code:"Code",Structure:"Structure",Note:"Note",Description:"Description"},I.Journal={FileAs:"FileAs",Subject:"Subject",TypeEn:"TypeEn",StateEn:"StateEn",ImportanceEn:"ImportanceEn",EventStart:"EventStart",EventEnd:"EventEnd",SuperiorItem:"SuperiorItem",Company:"Company",Contact:"Contact",Marketing:"Marketing",IsSystem:"System",IsPrivate:"Private",Note:"Note",Phone:"Phone"},I.Vacation={StartDate:"StartDate",EndDate:"EndDate",User:"User",Duration:"Duration",Place:"Place",Note:"Note",AllDay:"AllDay",TypeEn:"TypeEn",StateEn:"StateEn",IsPrivate:"Private"},I.Marketing={HumanID:"HumanID",EstimatedStart:"EstimatedStart",EstimatedEnd:"EstimatedEnd",RealStart:"RealStart",RealEnd:"RealEnd",TargetGroup:"TargetGroup",EmailsSent:"EmailsSent",EmailsDelivered:"EmailsDelivered",EmailsViewed:"EmailsViewed",PeopleUnsubscribed:"PeopleUnsubscribed",FinalRevenues:"FinalRevenues",TypeEn:"TypeEn",StateEn:"StateEn"},I.Projects={HumanID:"HID",FileAs:"FileAs",ProjectName:"ProjectName",ProjectOriginEn:"ProjectOriginEn",TypeEn:"TypeEn",StateEn:"StateEn",PaymentTypeEn:"PaymentTypeEn",ProjectStart:"ProjectStart",ProjectRealEnd:"ProjectRealEnd",EstimatedEnd:"ProjectEnd",CurrencyEn:I.Common.CurrencyEn,DefaultCurrencyEn:"DefaultCurrencyEn",EstimatedMargin:"EstimatedMargin",EstimatedPeopleExpenses:"EstimatedPeopleExpenses",EstimatedPeopleExpensesDefaultCurrency:"EstimatedPeopleExpensesDefaultCurrency",EstimatedOtherExpenses:"EstimatedOtherExpenses",EstimatedOtherExpensesDefaultCurrency:"EstimatedOtherExpensesDefaultCurrency",EstimatedPrice:"EstimatedPrice",EstimatedPriceDefaultCurrency:"EstimatedPriceDefaultCurrency",EstimatedProfit:"EstimatedProfit",EstimatedProfitDefaultCurrency:"EstimatedProfitDefaultCurrency",EstimatedPriceChanged:"EstimatedPriceChanged",EstimatedPeopleExpensesChanged:"EstimatedPeopleExpensesChanged",EstimatedOtherExpensesChanged:"EstimatedOtherExpensesChanged",Delay:"Delay",EstimatedWorkHours:"EstimatedWorkHours",TotalWorkHours:"TotalWorkHours",PeopleExpenses:"PeopleExpenses",OtherExpenses:"OtherExpenses",PeopleExpensesDefaultCurrency:"PeopleExpensesDefaultCurrency",OtherExpensesDefaultCurrency:"OtherExpensesDefaultCurrency",PeopleExpensesChanged:"PeopleExpensesChanged",OtherExpensesChanged:"OtherExpensesChanged",Price:"Price",PriceDefaultCurrency:"PriceDefaultCurrency",Profit:"Profit",ProfitDefaultCurrency:"ProfitDefaultCurrency",Margin:"Margin",PriceChanged:"PriceChanged",SuperiorProject:"SuperiorProject",Customer:"Customer",ContactPerson:"ContactPerson",Users:"Users",ProjectManager:"ProjectManager",InvoicePaymentDate:"InvoicePaymentDate",PaymentMaturity:"PaymentMaturity",InvoiceIssueDate:"InvoiceIssueDate",LicensesCount:"LicensesCount",LicensePrice:"LicensePrice",LicensePriceDefaultCurrency:"LicensePriceDefaultCurrency",NextStep:"NextStep",LastActivity:"LastActivity",IsPrivate:"Private",LicensePriceChanged:"LicensePriceChanged",Note:"Note",CompletedDate:"CompletedDate",LostDate:"LostDate"},I.Tasks={FileAs:"FileAs",Subject:"Subject",RootItem:"RootItem",SuperiorItem:"SuperiorItem",Company:"Company",Contact:"Contact",StartDate:"StartDate",DueDate:"DueDate",Reminder:"Reminder",ReminderDate:"ReminderDate",ImportanceEn:"ImportanceEn",IsCompleted:"Complete",PercentComplete:"PercentComplete",PercentCompleteDecimal:"PercentCompleteDecimal",CompletedDate:"CompletedDate",Solver:"Solver",Delegator:"Delegator",Level:"Level",IsPrivate:"Private",ActualWorkHours:"ActualWorkHours",TotalWorkHours:"TotalWorkHours",Body:"Body",TypeEn:"TypeEn",StateEn:"StateEn"},I.Training={TitleEn:"TitleEn"},I.WorkReports={Task:"Task",ProjectName:"ProjectName",UserName:"UserName",Subject:"Subject",Date:"Date",FromTime:"FromTime",ToTime:"ToTime",Overtime:"Overtime",Month:"Month",Year:"Year",IsPrivate:"Private",Note:"Note",Duration:"Duration",WorkReportEn:"WorkReportEn",StateEn:"StateEn"},I.Users={ProfilePicture:"ProfilePicture",UserName:"UserName",JobTitle:"JobTitle",IDCardNumber:"IDCardNumber",Birthdate:"Birthdate",BirthPlace:"BirthPlace",PersonalIdentificationNumber:"PersonalIdentificationNumber",Active:"Active",FamilyStatusEn:"FamilyStatusEn",HomeAddressStreet:"HomeAddressStreet",HomeAddressCity:"HomeAddressCity",HomeAddressPostalCode:"HomeAddressPostalCode",HomeAddressCountryEn:"HomeAddressCountryEn",HomeAddressState:"HomeAddressState",HomeAddressPOBox:"HomeAddressPOBox",BankAccount:"BankAccount",BusinessPhoneNumber:"BusinessPhoneNumber",MobilePhoneNumber:"MobilePhoneNumber",Email1Address:"Email1Address",Email2Address:"Email2Address",ICQ:"ICQ",MSN:"MSN",Skype:"Skype",IdentificationNumber:"IdentificationNumber",HealthInsurance:"HealthInsurance",HolidayLength:"HolidayLength",RemainingDaysOfHoliday:"RemainingDaysOfHoliday",SalaryDateEn:"SalaryDateEn",Supervisor:"Supervisor",TravelDistance:"TravelDistance",TimeAccessibility:"TimeAccessibility",TransportMode:"TransportMode",WorkdayStartTime:"WorkdayStartTime",Note:"Note",IsSystem:"IsSystem"},I.Groups={IsAdmin:"IsAdmin",GroupName:"GroupName",FileAs:"FileAs",Description:"Description",IsPM:"IsPM",System:"System",IsRole:"IsRole",IsCategory:"IsCategory",DisallowControlModulePermissions:"DisallowControlModulePermissions",DisallowControlColumnPermissions:"DisallowControlColumnPermissions",IsOutlookCategory:"IsOutlookCategory",DisallowControlUserAssignment:"DisallowControlUserAssignment",ColorEn:"ColorEn",Picture:"Picture"},I.allTypeEnNames=["TypeEn",I.Documents.DocTypeEn,I.WorkReports.WorkReportEn,"TitleEn"],I.getFolderFileAs=e=>{switch(e){case m.leads:return I.Leads.FileAs;case m.projects:return I.Projects.ProjectName;case m.documents:return I.Documents.DocName;case m.companies:return I.Companies.CompanyName;case m.contacts:case m.users:return I.Common.FileAs;case m.emails:return I.Emails.Subject;case m.journal:return I.Journal.FileAs;case m.tasks:return I.Tasks.Subject;case m.workReports:return I.WorkReports.Subject;case m.vacation:return I.Vacation.TypeEn;case m.carts:case m.goods:return I.Common.FileAs;case m.groups:return I.Groups.GroupName;default:return console.warn(`FileAs col name not defined for folderName ${e}`),I.Common.FileAs}};class b{}b.general="GENERAL",b.group="GROUP",b.contactPerson="CONTACTPERSON",b.contact="CONTACT",b.customer="CUSTOMER",b.company="COMPANY",b.outlookProject="OUTLOOKPROJECT",b.supervisor="SUPERVISOR";class w{}w.all="All",w.own="Own",w.readonly="Readonly",w.invisible="Invisible",w.none="None";class D{}var N,x,O,R;D.mandatory="Mandatory",D.optional="Optional",D.unique="Unique",D.none="None",exports.Edition=void 0,(N=exports.Edition||(exports.Edition={})).Free="Free",N.Basic="Basic",N.Professional="Professional",N.Enterprise="Enterprise",exports.Feature=void 0,(x=exports.Feature||(exports.Feature={})).ContactsAndCompanies="ContactsAndCompanies",x.Sales="Sales",x.Projects="Projects",x.Marketing="Marketing",exports.SentimentTone=void 0,(O=exports.SentimentTone||(exports.SentimentTone={}))[O.Negative=0]="Negative",O[O.Neutral=1]="Neutral",O[O.Positive=2]="Positive";class M{}M.contactsSynchronizationWithOutlook="ContactsSynchronizationWithOutlook",M.wordAddin="WordAddin",M.excelAddin="ExcelAddin",M.tasksRecurrentTasks="TasksRecurrentTasks",M.tasksSubtasks="TasksSubtasks",M.tasksSynchronizationWithOutlook="TasksSynchronizationWithOutlook",M.calendarSynchronizationWithOutlook="CalendarSynchronizationWithOutlook",M.emailsAutomaticTracking="EmailsAutomaticTracking",M.convertEmailToProject="ConvertEmailToProject",M.duplicityChecker="DuplicityChecker",M.nextStepAndLastActivityCustomization="NextStepAndLastActivityCustomization",M.subProjects="SubProjects",M.resourceAndPlanning="ResourceAndPlanning",M.professionalEmailCampaigns="ProfessionalEmailCampaigns",M.professionalEmailCampaignsAdvancedStatistics="ProfessionalEmailCampaignsAdvancedStatistics",M.wordEmailMerge="WordEmailMerge",M.printLabels="PrintLabels",M.printEnvelopes="PrintEnvelopes",M.userViews="UserViews",M.sharedUserViews="SharedUserViews",M.gridConditionalFormating="GridConditionalFormating",M.multipleCurrencies="MultipleCurrencies",M.historyTracking="HistoryTracking",M.privateItems="PrivateItems",M.itemTypes="ItemTypes",M.formLayoutCustomization="FormLayoutCustomization",M.workflowBasicDefinitions="WorkflowBasicDefinitions",M.workflowAdvancedDefinitions="WorkflowAdvancedDefinitions",M.workflowAdvancedDefinitionsRules="WorkflowAdvancedDefinitionsRules",M.workflowAdvancedDefinitionsActions="WorkflowAdvancedDefinitionsActions",M.workflowGroupLevelActions="WorkflowGroupLevelActions",M.customFields="CustomFields",M.importantFields="ImportantFields",M.mandatoryFields="MandatoryFields",M.uniqueFields="UniqueFields",M.readOnlyFields="ReadOnlyFields",M.transformationCustomTemplates="TransformationCustomTemplates",M.userRoles="UserRoles",M.modulePermissions="ModulePermissions",M.columnPermissions="ColumnPermissions",M.api="API",M.gate="Gate",M.threeCXIntegration="ThreeCXIntegration",M.tapiIntegration="TapiIntegration",M.pohodaIntegration="PohodaIntegration",M.pohodaSynchronizationIntervalCustomization="PohodaSynchronizationIntervalCustomization",M.pohodaSynchronizationFieldMappingCustomization="PohodaSynchronizationFieldMappingCustomization",M.quickBooksIntegration="QuickBooksIntegration",M.saveBinaryDataOnDisk="SaveBinaryDataOnDisk",M.activeDirectoryLogin="ActiveDirectoryLogin",M.callerIdentificationOnApple="CallerIdentificationOnApple",M.legacyAdministration="LegacyAdministration";class L{}L.customAdditionalFieldsCount="CustomAdditionalFieldsCount",L.customEnabledAdvancedWorkflowsCount="CustomEnabledAdvancedWorkflowsCount",L.customEnabledBasicWorkflowsCount="CustomEnabledBasicWorkflowsCount",L.customMandatoryFieldsCount="CustomMandatoryFieldsCount",L.customOptionalFieldsCount="CustomOptionalFieldsCount",L.customReadonlyFieldsCount="CustomReadonlyFieldsCount",L.customUniqueFieldsCount="CustomUniqueFieldsCount",L.customVisibleTypesCount="CustomVisibleTypesCount",L.visibleCurrenciesCount="VisibleCurrenciesCount";class F{}F.contactsAutomaticSynchronizationWithOutlook="ContactsAutomaticSynchronizationWithOutlook",F.contactsSynchronizationWithOutlook="ContactsSynchronizationWithOutlook",F.contactsSynchronizationWithAndroid="ContactsSynchronizationWithAndroid",F.documentsRevisions="DocumentsRevisions",F.wordAddin="WordAddin",F.excelAddin="ExcelAddin",F.tasksReminders="TasksReminders",F.tasksRecurrentTasks="TasksRecurrentTasks",F.tasksSubtasks="TasksSubtasks",F.tasksSynchronizationWithOutlook="TasksSynchronizationWithOutlook",F.calendarSynchronizationWithOutlook="CalendarSynchronizationWithOutlook",F.emailsManualTracking="EmailsManualTracking",F.emailsAutomaticTracking="EmailsAutomaticTracking",F.emailSummaryAndSentimentToneFromAi="EmailSummaryAndSentimentToneFromAi",F.convertEmailToContact="ConvertEmailToContact",F.convertEmailToContactInBulk="ConvertEmailToContactInBulk",F.convertEmailToDeal="ConvertEmailToDeal",F.convertEmailToProject="ConvertEmailToProject",F.convertEmailToTask="ConvertEmailToTask",F.gravatarIntegration="GravatarIntegration",F.logoboxIntegration="LogoboxIntegration",F.companiesBussinesRegisterApiIntegration="CompaniesBussinesRegisterApiIntegration",F.duplicityChecker="DuplicityChecker",F.nextStepAndLastActivityCustomization="NextStepAndLastActivityCustomization",F.subProjects="SubProjects",F.resourceAndPlanning="ResourceAndPlanning",F.professionalEmailCampaigns="ProfessionalEmailCampaigns",F.professionalEmailCampaignsAdvancedStatistics="ProfessionalEmailCampaignsAdvancedStatistics",F.wordEmailMerge="WordEmailMerge",F.printLabels="PrintLabels",F.printEnvelopes="PrintEnvelopes",F.userViews="UserViews",F.sharedUserViews="SharedUserViews",F.gridRowSummary="GridRowSummary",F.gridConditionalFormating="GridConditionalFormating",F.multipleCurrencies="MultipleCurrencies",F.historyTracking="HistoryTracking",F.privateItems="PrivateItems",F.itemTypes="ItemTypes",F.formLayoutCustomization="FormLayoutCustomization",F.workflowBasicDefinitions="WorkflowBasicDefinitions",F.workflowAdvancedDefinitions="WorkflowAdvancedDefinitions",F.workflowAdvancedDefinitionsRules="WorkflowAdvancedDefinitionsRules",F.workflowAdvancedDefinitionsActions="WorkflowAdvancedDefinitionsActions",F.workflowGroupLevelActions="WorkflowGroupLevelActions",F.customFields="CustomFields",F.importantFields="ImportantFields",F.mandatoryFields="MandatoryFields",F.uniqueFields="UniqueFields",F.readOnlyFields="ReadOnlyFields",F.transformationCustomTemplates="TransformationCustomTemplates",F.userRoles="UserRoles",F.modulePermissions="ModulePermissions",F.columnPermissions="ColumnPermissions",F.commonDataAPI="CommonDataAPI",F.eWayCrmAPI="eWayCrmAPI",F.threeCXIntegration="ThreeCXIntegration",F.tapiIntegration="TapiIntegration",F.pohodaIntegration="PohodaIntegration",F.pohodaSynchronizationIntervalCustomization="PohodaSynchronizationIntervalCustomization",F.pohodaSynchronizationFieldMappingCustomization="PohodaSynchronizationFieldMappingCustomization",F.quickBooksIntegration="QuickBooksIntegration",F.shareByTeams="ShareByTeams",F.convertEmailToContactWithDataFromAi="ConvertEmailToContactWithDataFromAi",F.convertEmailToDealWithDataFromAi="ConvertEmailToDealWithDataFromAi",F.convertEmailToProjectWithDataFromAi="ConvertEmailToProjectWithDataFromAi",function(e){e.UnpaidImportantInvoices="UnpaidImportantInvoices",e.UncollectableSubscriptionPayment="UncollectableSubscriptionPayment",e.UncollectableSubscriptionPaymentWithExpiredCard="UncollectableSubscriptionPaymentWithExpiredCard",e.StandardSubscriptionPeriod="StandardSubscriptionPeriod"}(R||(R={}));var B,U=R;!function(e){e.License="License",e.CloudLicense="CloudLicense",e.MiscLicense="MiscLicense",e.Support="Support",e.Service="Service"}(B||(B={}));var G=B;class W{}W.getIsDebug=e=>{var t;return!!(null===(t=null==e?void 0:e.sessionHandler.lastSuccessfulLoginResponse)||void 0===t?void 0:t.Debug)},W.supportsFeaturesOf=(e,t)=>{var s;const n=null===(s=e.sessionHandler.lastSuccessfulLoginResponse)||void 0===s?void 0:s.WcfVersion;return!!n&&(o.compare(n,t,">=")||o.compare(n,"1.0.0.0","="))};class j{}j.textBox="TextBox",j.comboBox="ComboBox",j.numericBox="NumericBox",j.relation="Relation",j.checkBox="CheckBox",j.linkTextBox="LinkTextBox",j.dateEdit="DateEdit",j.memoBox="MemoBox",j.multiSelectComboBox="MultiSelectComboBox",j.workflowState="WorkflowState",j.image="Image",j.multiSelectRelation="MultiSelectRelation";const H={[m.relations]:0,[m.unifiedRelations]:1,[m.users]:2,[m.groups]:3,[m.enumTypes]:4,[m.enumValues]:5,[m.additionalFields]:6};var _;exports.EnumTypeEditMode=void 0,(_=exports.EnumTypeEditMode||(exports.EnumTypeEditMode={})).Readonly="Readonly",_.VisibleRankDefaultOnly="VisibleRankDefaultOnly",_.Editable="Editable",c.polyfill(),exports.ApiConnectionAsNonDefaultExport=P,exports.ApiMethods=p,exports.ColumnPermissionMandatoryRules=D,exports.ColumnPermissionPermissionRules=w,exports.CommonDataConnection=class{constructor(e,t){this.isCommonDataApiEnabled=(e,t)=>{this.tokenizedConnection.isEnabled(e,t)},this.callCommonDataApi=(e,t,s,o)=>{this.tokenizedConnection.callTokenizedApi(e,t,s,o)},this.tokenizedConnection=new A("ObtainCommonDataApiAccessToken",exports.HttpMethod.get,!1,"InvalidCommonDataToken",T,e,t)}},exports.CustomizationStatsItemKeys=L,exports.EWItem=class{constructor(e,t){if(!e||!t)throw new Error("Both folderName and baseItem has to be defined!");this.folderName=e,this.baseItem=t}getEmailAddress(){switch(this.folderName){case m.contacts:{const e=this.baseItem;return e.Email1Address||e.Email2Address||e.Email3Address}case m.leads:return this.baseItem.Email;case m.companies:return this.baseItem.Email;case m.users:{const e=this.baseItem;return e.Email1Address||e.Email2Address}default:return null}}getInitials(){switch(this.folderName){case m.contacts:{const e=this.baseItem;return this.getInitialsInternal(e.FirstName,e.LastName)}case m.users:{const e=this.baseItem;return this.getInitialsInternal(e.FirstName,e.LastName)}default:return null}}getInitialsInternal(e,t){const s=((null==e?void 0:e.substr(0,1))||"")+((null==t?void 0:t.substr(0,1))||"");return""==s?null:s}getItemPreview(){switch(this.folderName){case m.contacts:{const e=this.baseItem;return e.ProfilePicture?{imageData:e.ProfilePicture,width:e.ProfilePictureWidth||0,height:e.ProfilePictureHeight||0}:null}case m.users:{const e=this.baseItem;return e.ProfilePicture?{imageData:e.ProfilePicture,width:e.ProfilePictureWidth||0,height:e.ProfilePictureHeight||0}:null}default:return null}}},exports.EnumTypes=u,exports.ErrorHelper=v,exports.ExpirationReason=U,exports.FieldNames=I,exports.FieldTypes=j,exports.FolderNames=m,exports.Functionality=M,exports.GlobalSettingsNames=k,exports.HttpRequestError=E,exports.LicenseKeyInvoiceSeverity=G,exports.LicenseRestrictionKeys=F,exports.OAuthHelper=C,exports.OAuthSessionHandlerBase=g,exports.ObjectTypeIds=H,exports.QueryHelper=class{static createHubItemsCountsQuery(e,t,s){return{__type:"HubItemsCountsQuery:#EQ",ParentItemGuids:e,ItemTypes:t,ExcludeSystemItems:s}}},exports.RelationTypes=b,exports.ReturnCodes=d,exports.TokenizedServiceConnection=A,exports.VersionHelperBase=W,exports.default=P;
8
+ */class d{}d.rcSuccess="rcSuccess",d.rcBadSession="rcBadSession",d.rcDuplicateContact="rcDuplicateContact",d.rcWebServiceMoved="rcWebServiceMoved",d.rcAccessDenied="rcAccessDenied",d.rcLoginUserNameChanged="rcLoginUserNameChanged",d.rcLicenseExpired="rcLicenseExpired",exports.HttpMethod=void 0,(a=exports.HttpMethod||(exports.HttpMethod={})).get="get",a.post="post";class u{}u.absence="Absence",u.bonusType="BonusType",u.busyStatus="BusyStatus",u.cartType="CartType",u.companyType="CompanyType",u.contactType="ContactType",u.countryCode="CountryCode",u.currency="Currency",u.customFieldCategory="CustomFieldCategory",u.dayType="DayType",u.documentOfflineState="DocumentOfflineState",u.documentType="DocumentType",u.emailCampaignWorkflowStatus="EmailCampaignWorkflowStatus",u.emailOfflineState="EmailOfflineState",u.emailType="EmailType",u.familyStatus="FamilyStatus",u.firstContact="FirstContact",u.globalSettingsCategory="GlobalSettingsCategory",u.goalType="GoalType",u.groupColor="GroupColor",u.importance="Importance",u.journalType="JournalType",u.knowledgeLevel="KnowledgeLevel",u.knowledgeTitle="KnowledgeTitle",u.knowledgeType="KnowledgeType",u.leadType="LeadType",u.marketingType="MarketingType",u.paymentType="PaymentType",u.prefixType="PrefixType",u.productType="ProductType",u.projectOrigin="ProjectOrigin",u.projectType="ProjectType",u.reportCategory="ReportCategory",u.responseForm="ResponseForm",u.responseType="ResponseType",u.salaryDate="SalaryDate",u.salaryType="SalaryType",u.salePriceType="SalePriceType",u.sentimentTone="SentimentTone",u.suffixType="SuffixType",u.taskImportance="TaskImportance",u.tasksSnoozePeriod="TasksSnoozePeriod",u.taskStatus="TaskStatus",u.taskType="TaskType",u.trainingGrade="TrainingGrade",u.trainingTitle="TrainingTitle",u.translations="Translations",u.units="Units",u.userType="UserType",u.usStatesDistrictsTerritories="USStatesDistrictsTerritories",u.vacationType="VacationType",u.vat="VAT",u.workLoad="WorkLoad",u.workReportType="WorkReportType";class m{}m.isValidFolderName=e=>Object.values(m).includes(e),m.actions="Actions",m.additionalFields="AdditionalFields",m.bonuses="Bonuses",m.calendar="Calendar",m.capacityNotes="CapacityNotes",m.capacityNoteTypes="CapacityNoteTypes",m.carts="Carts",m.columnPermissions="ColumnPermissions",m.companies="Companies",m.contacts="Contacts",m.currencyExchangeRates="CurrencyExchangeRates",m.documents="Documents",m.emails="Emails",m.enumTypes="EnumTypes",m.enumValues="EnumValues",m.enumValuesRelations="EnumValuesRelations",m.features="Features",m.flows="Flows",m.globalSettings="GlobalSettings",m.goals="Goals",m.goods="Goods",m.goodsInCart="GoodsInCart",m.goodsInSet="GoodsInSet",m.groups="Groups",m.history="History",m.holidays="Holidays",m.children="Children",m.individualDiscounts="IndividualDiscounts",m.invoiceItems="InvoiceItems",m.invoices="Invoices",m.itemCopyRelations="ItemCopyRelations",m.journal="Journal",m.knowledge="Knowledge",m.layouts="Layouts",m.layoutsModels="LayoutsModels",m.leads="Leads",m.ledger="Ledger",m.mappings="Mappings",m.marketing="Marketing",m.marketingList="MarketingList",m.marketingListSources="MarketingListSources",m.models="Models",m.modulePermissions="ModulePermissions",m.objectTypesOptions="ObjectTypesOptions",m.payments="Payments",m.priceListGroups="PriceListGroups",m.projectAssignments="ProjectAssignments",m.projectAssignmentsPerUserProject="ProjectAssignmentsPerUserProject",m.projectAssignmentsTotal="ProjectAssignmentsTotal",m.projectAssignmentsTotalUserProject="ProjectAssignmentsTotalUserProject",m.projectList="ProjectList",m.projects="Projects",m.projectUsersInCaPlan="ProjectUsersInCaPlan",m.relationData="RelationData",m.relations="Relations",m.reports="Reports",m.revisionsHistory="RevisionsHistory",m.salaries="Salaries",m.salePrices="SalePrices",m.prices="Prices",m.sqlObjects="SqlObjects",m.tasks="Tasks",m.recurrencePatterns="RecurrencePatterns",m.teamRoles="TeamRoles",m.templates="Templates",m.training="Training",m.unifiedRelations="UnifiedRelations",m.users="Users",m.userSettings="UserSettings",m.vacation="Vacation",m.webAccess2Options="WebAccess2Options",m.webAccessOptions="WebAccessOptions",m.workCommitments="WorkCommitments",m.workflowHistory="WorkflowHistory",m.workReports="WorkReports",m.wrongClientVersions="WrongClientVersions",m.xsltTransformations="XsltTransformations",m.getEnumTypeName=e=>e===m.bonuses?u.bonusType:e===m.carts?u.cartType:e===m.companies?u.companyType:e===m.contacts?u.contactType:e===m.documents?u.documentType:e===m.emails?u.emailType:e===m.goals?u.goalType:e===m.goods?u.productType:e===m.journal?u.journalType:e===m.knowledge?u.knowledgeType:e===m.leads?u.leadType:e===m.marketing?u.marketingType:e===m.projects?u.projectType:e===m.salaries?u.salaryType:e===m.salePrices?u.salePriceType:e===m.tasks?u.taskType:e===m.training?u.trainingTitle:e===m.users?u.userType:e===m.vacation?u.vacationType:e===m.workReports?u.workReportType:null,m.getFolderNameByEnumTypeName=e=>e===u.bonusType?m.bonuses:e===u.cartType?m.carts:e===u.companyType?m.companies:e===u.contactType?m.contacts:e===u.documentType?m.documents:e===u.emailType?m.emails:e===u.goalType?m.goals:e===u.journalType?m.journal:e===u.knowledgeType?m.knowledge:e===u.leadType?m.leads:e===u.marketingType?m.marketing:e===u.productType?m.goods:e===u.projectType?m.projects:e===u.salaryType?m.salaries:e===u.salePriceType?m.salePrices:e===u.taskType?m.tasks:e===u.trainingTitle?m.training:e===u.userType?m.users:e===u.vacationType?m.vacation:e===u.workReportType?m.workReports:null;class p{}p.getAllEmailAttachments="GetAllEmailAttachments",p.getCalendarsByItemGuids="GetCalendarsByItemGuids",p.getEmailAttachment="GetEmailAttachment",p.getItemPreview="GetItemPreview",p.getJournalsByItemGuids="GetJournalsByItemGuids",p.getMarketingCampaignsByItemGuids="GetMarketingCampaignsByItemGuids",p.getMarketingListsRecordsByItemGuids="GetMarketingListsRecordsByItemGuids",p.getRevisionHistoryRecordsByItemGuids="GetRevisionHistoryRecordsByItemGuids",p.getVacationsByItemGuids="GetVacationsByItemGuids",p.getWorkflowHistoryRecordsByItemGuids="GetWorkflowHistoryRecordsByItemGuids",p.getCompanyInformationFromTaxRegister="GetCompanyInformationFromTaxRegister",p.logIn="LogIn",p.logOut="LogOut",p.query="Query",p.queryAmount="QueryAmount",p.getServiceAuthSettings="GetServiceAuthSettings",p.getVersion="GetVersion",p.getBinaryAttachment="GetBinaryAttachment",p.getBinaryAttachmentLatestRevision="GetBinaryAttachmentLatestRevision",p.canUnlinkItems="CanUnlinkItems",p.unlinkItems="UnlinkItems",p.getFolderNameForApiMethod=e=>{switch(e){case m.calendar:return"Calendars";case m.journal:return"Journals";case m.marketing:return"MarketingCampaigns";case m.marketingList:return"MarketingListsRecords";case m.revisionsHistory:return"RevisionHistoryRecords";case m.vacation:return"Vacations";case m.workflowHistory:return"WorkflowHistoryRecords";default:return e}},p.getGetFolderNameByItemGuidsMethodName=e=>`Get${p.getFolderNameForApiMethod(e)}ByItemGuids`,p.getGetFolderNameMethodName=e=>`Get${p.getFolderNameForApiMethod(e)}`,p.getSearchFolderNameMethodName=e=>`Search${e}`;class h{constructor(e,t,s,o,n,r){if(this.invalidateSessionId=(e,t)=>{t&&t()},this.getSessionId=(e,t)=>{e.callWithoutSession(p.logIn,{userName:this.username,passwordHash:this.passwordHash,appVersion:this.appVersion,clientMachineIdentifier:this.clientMachineIdentifier,clientMachineName:this.clientMachineName,createSessionCookie:e.supportsGetItemPreviewMethod},(e=>{this.lastSuccessfulLoginResponse=e;const s=e.SessionId;if(s)t&&t(s);else{const e=new Error("Successful login but no session came.");if(!this.errorCallback)throw e;this.errorCallback(e)}}),(e=>{const t=new Error("Unable to login. Error response follows.\n"+JSON.stringify(e));if(!this.errorCallback)throw t;this.errorCallback(t)}))},!e||!t)throw new Error("Non of the arguments 'username', 'passwordHash' can be empty.");this.username=e,this.passwordHash=t,this.appVersion=s,this.clientMachineIdentifier=o,this.clientMachineName=n,this.errorCallback=r}}class y{constructor(){this.getSessionId=(e,t)=>{throw new Error("With anonymous session handler, use only connection methods without session.")},this.invalidateSessionId=(e,t)=>{throw new Error("With anonymous session handler, use only connection methods without session.")}}}class C{static createAuthorizeUrl(e,t,s,o,n,r,i=!1){if(n&&!r||!n&&r)throw new Error("If codeChallenge is defined, codeChallengeMethod must also be defined and vice versa");let a=`https://login.eway-crm.${i?"dev":"com"}?scope=${encodeURIComponent(t.join(" "))}prompt=login&response_type=code&redirect_uri=${encodeURIComponent(s)}&client_id=${e}`;return o&&(a+=`&state=${encodeURIComponent(o)}`),n&&r&&(a+=`&code_challenge=${encodeURIComponent(n)}&code_challenge_method=${encodeURIComponent(r)}`),a}}C.finishAuthorization=(e,t,s,o,n,r,i)=>{const a=new URLSearchParams;a.append("code_verifier",o),a.append("client_id",t),a.append("client_secret",s),a.append("code",n),a.append("redirect_uri",r),a.append("grant_type","authorization_code"),C.callTokenEndpoint(e,a,i)},C.refreshToken=(e,t,s,o,n)=>{const r=new URLSearchParams;r.append("client_id",t),r.append("client_secret",s),r.append("refresh_token",o),r.append("grant_type","refresh_token"),C.callTokenEndpoint(e,r,n)},C.getWebServiceUrl=e=>{const t=e.split(".");if(2!==t.length)throw new Error("Invalid token supplied");return r.decode(t[1])},C.getUserName=e=>C.decodeAccessToken(e).username,C.decodeAccessToken=e=>s(e),C.callTokenEndpoint=(t,s,o)=>{e.post(t+"/auth/connect/token",s,{headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then((e=>{o(e.data)})).catch((e=>{if(!e.response||400!=e.response.status)throw new Error("Token request failed");o(e.response.data)}))};class f extends Error{constructor(e,t){super(),this.returnCode=e,this.message=t}}class g{constructor(e,t,s,o,n){if(this.invalidateSessionId=(e,t)=>{t&&t()},this.getSessionId=(e,t)=>{const s={userName:this.username,appVersion:this.appVersion,createSessionCookie:e.supportsGetItemPreviewMethod},o={Authorization:"Bearer "+this.accessToken};e.callWithoutSession(p.logIn,s,(e=>{this.lastSuccessfulLoginResponse=e;const s=e.SessionId;if(s)t&&t(s);else{const e=new Error("Successful login but no session came.");if(!this.errorCallback)throw e;this.errorCallback(e)}}),(e=>{const t=new f(e.ReturnCode,"Unable to login. Error response follows.\n"+JSON.stringify(e));if(!this.errorCallback)throw t;this.errorCallback(t)}),o,void 0,(s=>{if(401!==(null==s?void 0:s.statusCode)){if(!this.errorCallback)throw s;this.errorCallback(s)}else this.getNewAccessTokenCallback(e,((s,o)=>{this.accessToken=s,o||this.getSessionId(e,t)}))}))},!e)throw new Error("Non of the arguments 'username', 'clientId', 'clientSecret', 'refreshToken' can be empty.");this.username=e,this.accessToken=t,this.appVersion=s,this.getNewAccessTokenCallback=o,this.errorCallback=n}}class S extends g{constructor(e,t,s,o,n,r,i,a){if(!(e&&o&&t&&s))throw new Error("Non of the arguments 'username', 'clientId', 'clientSecret', 'refreshToken' can be empty.");super(e,n,r,((e,t)=>{C.refreshToken(e.wsUrl,this.clientId,this.clientSecret,this.refreshToken,(e=>{try{this.refreshTokenCallback&&this.refreshTokenCallback(e)}catch(e){this.errorCallback&&this.errorCallback(new Error("Refresh token callback failed.\n"+JSON.stringify(e)))}t(e.access_token,e.error)}))}),i),this.refreshToken=o,this.clientId=t,this.clientSecret=s,this.refreshTokenCallback=a}}class E extends Error{constructor(e,t){super(),this.statusCode=e,this.message=t}}class v{}v.stringifyError=e=>JSON.stringify(e,v.replaceErrors),v.replaceErrors=(e,t)=>{if(t instanceof Error){const e={};return Object.getOwnPropertyNames(t).forEach((s=>{e[s]=t[s]})),e}return t};class P{constructor(t,s,o,n){if(this.createOpenLink=(e,t,s,o)=>{const n=r.encode(this.baseUri);let i="eway://"+t;s&&(i+="/"+(null==s?void 0:s.toLowerCase()));const a=e?"open.eway-crm.dev":"open.eway-crm.com";i=r.encode(i);let l="https://"+a+"/?ws="+n+"&l="+i;return o&&(l+="&n="+encodeURIComponent(o)),l},this.askUploadMethod=(e,t,s,o,n)=>new Promise(((r,i)=>{const a=n?e=>{throw i(e),e}:i;this.callUploadMethod(e,t,s,r,a,a,o)})),this.callUploadMethod=(t,s,o,n,r,i,a)=>{const l=()=>{this.sessionHandler.getSessionId(this,(e=>{this.sessionId=e,this.callUploadMethod(t,s,o,n,r,i,a)}))},c=this.sessionId;if(!c)return void l();const u=`${this.svcUri}/SaveBinaryAttachment?sessionId=${this.sessionId}&itemGuid=${t}&fileName=${encodeURIComponent(s)}`,m=e.post(u,o,a);P.handleCallPromise(m,n,(e=>{if(e.ReturnCode===d.rcBadSession)return this.sessionId=null,void this.sessionHandler.invalidateSessionId(c,l);if(r)r(e);else{const t=new Error("Unhandled connection return code "+e.ReturnCode+": "+e.Description);if(!this.errorCallback)throw t;this.errorCallback(t)}}),(e=>{let t=new Error("Unhandled connection error when calling "+u+": "+v.stringifyError(e));if("statusCode"in e&&413===e.statusCode&&(t=new Error("The file has exceeded the maximum allowed file size for uploading. You can contact your IT administrator or eWay-CRM support if you would like to increase the limit.")),i)i(t);else{if(!this.errorCallback)throw t;this.errorCallback(t)}}))},this.askMethod=(e,t,s,o)=>new Promise(((n,r)=>{const i=o?e=>{throw r(e),e}:r;this.callMethod(e,t,n,i,s,i)})),this.callMethod=(e,t,s,o,n,r)=>{n||(n=exports.HttpMethod.post);const i=()=>{this.sessionHandler.getSessionId(this,(i=>{this.sessionId=i,this.callMethod(e,t,s,o,n,r)}))},a=this.sessionId;if(!a)return void i();t.sessionId=a;const l=e!==p.logOut?s:e=>{this.sessionId=null,s(e)};this.callWithoutSession(e,t,l,(s=>{if(s.ReturnCode!==d.rcBadSession||(this.sessionId=null,e===p.logOut))if(o)o(s);else{const e=new Error("Unhandled connection return code "+s.ReturnCode+": "+s.Description);if(!this.errorCallback)throw e;this.errorCallback(e,t)}else this.sessionHandler.invalidateSessionId(a,i)}),null,n,r)},this.callWithoutSession=(t,s,o,n,r,i,a)=>{var l;i||(i=exports.HttpMethod.post);const c=this.svcUri+"/"+t;let d,u;switch(r&&(d={headers:r,withCredentials:null!==(l=this.supportGetItemPreviewMethod)&&void 0!==l?l:t==p.logIn}),i){case exports.HttpMethod.get:if(s)throw new Error("Calling api get method with data specified does not make any sense.");u=e.get(c,d);break;case exports.HttpMethod.post:u=e.post(c,s,d);break;default:throw new Error(`Unknown http method '${i}'.`)}P.handleCallPromise(u,o,n,(e=>{if(a)try{a(e)}catch(e){if(!this.errorCallback)throw e;this.errorCallback(e,s)}else{const t=new Error("Unhandled connection error when calling "+c+": "+v.stringifyError(e));if(!this.errorCallback)throw t;this.errorCallback(t,s)}}))},this.getItemPreviewGetMethodUrl=(e,t,s)=>this.svcUri+"/"+p.getItemPreview+"?folderName="+encodeURIComponent(e)+"&itemGuid="+encodeURIComponent(t)+(s||0===s?"&itemVersion="+encodeURIComponent(s.toString()):""),this.getEmailAttachmentGetMethodUrl=(e,t)=>this.svcUri+"/"+p.getEmailAttachment+"?itemGuid="+encodeURIComponent(e)+"&contentId="+encodeURIComponent(t),this.getAllEmailAttachmentsZipGetMethodUrl=e=>this.svcUri+"/"+p.getAllEmailAttachments+"?itemGuid="+encodeURIComponent(e),this.getBinaryAttachmentGetMethodUrl=(e,t)=>"number"==typeof t?this.svcUri+"/"+p.getBinaryAttachment+"?itemGuid="+encodeURIComponent(e)+`&revision=${t}`:this.svcUri+"/"+p.getBinaryAttachmentLatestRevision+"?itemGuid="+encodeURIComponent(e),this.getActiveSessionId=()=>this.sessionId,this.setActiveSessionId=e=>{this.sessionId=e},!t)throw new Error("The argument 'apiServiceUri' cannot be empty.");if(t.length<8||"https://"!==t.substr(0,8).toLowerCase()&&"http://"!==t.substr(0,7).toLowerCase())throw new Error("Api service uri must start either with 'https://' or with 'http://'.");if(".svc"===t.substr(t.length-4).toLowerCase()){this.svcUri=t;const e=["/API.svc","/InsecureAPI.svc","/WcfService/Service.svc"].find((e=>e.toLowerCase()===t.substr(t.length-e.length).toLowerCase()))||"";this.baseUri=t.substr(0,t.length-e.length)}else this.baseUri=P.normalizeWsUrl(t)||t,"https://"===t.substr(0,8).toLowerCase()?this.svcUri=this.baseUri+"/API.svc":this.svcUri=this.baseUri+"/InsecureAPI.svc";this.sessionHandler=s,this.errorCallback=o,this.sessionId=null,this.supportGetItemPreviewMethod=null!=n&&n}get supportsGetItemPreviewMethod(){return this.supportGetItemPreviewMethod}static create(e,t,s,o,n,r,i,a){return new P(e,new h(t,s,o,n,r,i),i,a)}static createAnonymous(e,t){return new P(e,new y,t)}static createUsingOAuth(e,t,s,o,n,r,i,a,l,c){return new P(e,new S(t,s,o,n,r,i,a,l),a,c)}static normalizeWsUrl(e){return e&&e.endsWith("/")&&(e=e.substring(0,e.length-1)),e}get wsUrl(){return this.baseUri}static handleCallPromise(e,t,s,o){e.then((e=>{200===e.status?e.data.ReturnCode===d.rcSuccess?t(e.data):s(e.data):o(new E(e.status,e.statusText))})).catch((e=>{e.response?o(new E(e.response.status,e.response.statusText)):o(e)}))}}class A{constructor(e,t,s,o,n,r,i){this.isEnabled=(e,t)=>{const s=()=>{this.url&&this.token?e(this.url,this.token):t()};this.url&&this.token?e(this.url,this.token):this.obtainToken(s)},this.callTokenizedApi=(e,t,s,o)=>{this.isEnabled(((n,r)=>{t.token=r,A.call(n,e,t,s,(n=>{if(n.ReturnCodeString!==this.invalidTokenReturnCode){if(o)o(n);else if(this.generalErrorCallback){const e=new Error("Unhandled tokenized service connection return code "+n.ReturnCodeString+".\nDescription: "+n.Description);this.generalErrorCallback(e)}}else this.obtainToken((()=>{this.callTokenizedApi(e,t,s,o)}))}),(e=>{if(this.generalErrorCallback){const t=new Error("Unhandled tokenized service connection communication error: "+JSON.stringify(e));this.generalErrorCallback(t)}}))}),(()=>{o&&o(null)}))},this.obtainToken=e=>{if(!this.isActive)return this.url=null,this.token=null,void e();const t=t=>{const s=this.urlAndTokenObtainer(t);s.url&&s.token?(this.url=s.url,this.token=s.token,this.isActive=!0,e()):(this.url=null,this.token=null,this.isActive=!1,e())},s=()=>{this.url=null,this.token=null,this.isActive=!1,e()};this.needsSession?this.connection.callMethod(this.obtainTokenMethodName,{},t,s,this.obtainTokenMethodType):this.connection.callWithoutSession(this.obtainTokenMethodName,null,t,s,null,this.obtainTokenMethodType)},this.obtainTokenMethodName=e,this.obtainTokenMethodType=t,this.needsSession=s,this.invalidTokenReturnCode=o,this.urlAndTokenObtainer=n,this.connection=r,this.generalErrorCallback=i||null,this.url=null,this.token=null,this.isActive=!0}static call(t,s,o,n,r,i){const a=t+"/"+s;e.post(a,o).then((e=>{200===e.status?"Success"===e.data.ReturnCodeString?n(e.data):r(e.data):i(new E(e.status,e.statusText))})).catch((e=>{e.response?i(new E(e.response.status,e.response.statusText)):i(e)}))}}const T=e=>({url:e.ServiceUrl,token:e.Token});class k{}k.acceptableBackwardWorkReportDays="AcceptableBackwardWorkReportDays",k.adminAppInactiveLogoutTime="AdminAppInactiveLogoutTime",k.applyGeneralDataProtectionRules="ApplyGeneralDataProtectionRules",k.automaticallyCreateJournalAfterCallDuration="AutomaticallyCreateJournalAfterCallDuration",k.bonusesCompletedState="BonusesCompletedState",k.cartInvoicedState="CartInvoicedState",k.cartOrderCanceledState="CartOrderCanceledState",k.cartOrderInProcessState="CartOrderInProcessState",k.cartOrderProcessedState="CartOrderProcessedState",k.cartPaidState="CartPaidState",k.cartProposalInProcessState="CartProposalInProcessState",k.cartProposalProcessedState="CartProposalProcessedState",k.cartSalesVoucherIssuedState="CartSalesVoucherIssuedState",k.cartToBeInvoicedState="CartToBeInvoicedState",k.cartVoidedState="CartVoidedState",k.clickToCallScheme="ClickToCallScheme",k.companyDuplicityCheckEnabled="CompanyDuplicityCheckEnabled",k.completedStateName="CompletedStateName",k.contactDuplicityCheckEnabled="ContactDuplicityCheckEnabled",k.createCompanyWhileImportingContactFromOutlook="CreateCompanyWhileImportingContactFromOutlook",k.enableContactsTwoWaySyncWithM365="EnableContactsTwoWaySyncWithM365",k.deadStateName="DeadStateName",k.enableCompaniesSyncIntoMobileDeviceContacts="EnableCompaniesSyncIntoMobileDeviceContacts",k.enableContactsSyncIntoMobileDevice="EnableContactsSyncIntoMobileDevice",k.enableLeadsSyncIntoMobileDeviceContacts="EnableLeadsSyncIntoMobileDeviceContacts",k.enableLlamaAiFeatures="EnableLlamaAiFeatures",k.enableUsersSyncIntoMobileDeviceContacts="EnableUsersSyncIntoMobileDeviceContacts",k.emailsActiveProjectsLeadsFilter="EmailsActiveProjectsLeadsFilter",k.exchangeRatesAdminGroupName="ExchangeRatesAdminGroupName",k.forcedEmailTrackingGroups="ForcedEmailTrackingGroups",k.ignoreEmailsFromDomainsOnEmailsTracking="IgnoreEmailsFromDomainsOnEmailsTracking",k.trackEmailsFromDomains="TrackEmailsFromDomains",k.groupsForAllUnpaidInvoicesNotification="GroupsForAllUnpaidInvoicesNotification",k.itemPreviewMaxHeight="ItemPreviewMaxHeight",k.lastActivityAttributes="LastActivityAttributes",k.leadsCompletedState="LeadsCompletedState",k.leadDeadlineAlertGroups="LeadDeadlineAlertGroups",k.leadsDeadState="LeadsDeadState",k.marketingCompletedState="MarketingCompletedState",k.marketingDeadState="MarketingDeadState",k.minimumPasswordLength="MinimumPasswordLength",k.nextStepAttributes="NextStepAttributes",k.notifyAboutInvoicedInvoiceInPohodaGroup="NotifyAboutInvoicedInvoiceInPohodaGroup",k.notifyAboutLeadsDeadline="NotifyAboutLeadsDeadline",k.notifyAboutPaidInvoiceInPohodaGroup="NotifyAboutPaidInvoiceInPohodaGroup",k.notifyAboutProjectDeadline="NotifyAboutProjectDeadline",k.numberOfDecimalPlaces="NumberOfDecimalPlaces",k.phoneListTaskSolverGroup="PhoneListTaskSolverGroup",k.projectDeadlineAlert="ProjectDeadlineAlert",k.serverUpdateProgressNotificationGroup="ServerUpdateProgressNotificationGroup",k.sumarizeCartsPricesOnLeads="SumarizeCartsPricesOnLeads",k.sumarizeCartsPricesOnProjects="SumarizeCartsPricesOnProjects",k.sumarizePeopleExpensesOnProjects="SumarizePeopleExpensesOnProjects",k.systemHealthNotificationGroup="SystemHealthNotificationGroup",k.tasksCompletedState="TasksCompletedState",k.tasksDeferredState="TasksDeferredState",k.tasksInProgressState="TasksInProgressState",k.tasksNotStartedState="TasksNotStartedState",k.tasksWaitOnSomeoneElseState="TasksWaitOnSomeoneElseState",k.trackDocumentVersions="TrackDocumentVersions",k.vacationCompletedState="VacationCompletedState",k.workReportApprovedState="WorkReportApprovedState",k.defaultLanguage="DefaultLanguage",k.defaultCurrency="DefaultCurrency",k.myCompanyCountry="MyCompanyCountry",k.myCompanyName="MyCompanyName",k.myCompanyStreet="MyCompanyStreet",k.myCompanyCity="MyCompanyCity",k.myCompanyState="MyCompanyState",k.myCompanyZip="MyCompanyZIP",k.myCompanyId="MyCompanyID",k.myCompanyVat="MyCompanyVAT";class I{}I.ServerCommon={Server_ID:"Server_ID",Server_ItemCreated:"Server_ItemCreated",Server_ItemChanged:"Server_ItemChanged"},I.Common={CreatedByGUID:"CreatedByGUID",CurrencyEn:"CurrencyEn",DefaultCurrencySuffix:"DefaultCurrency",FileAs:"FileAs",ItemCreated:"ItemCreated",ItemChanged:"ItemChanged",ItemGUID:"ItemGUID",ItemVersion:"ItemVersion",ModifiedByGUID:"ModifiedByGUID",OwnerGUID:"OwnerGUID",ParentCurrencySuffix:"ParentCurrency"},I.Calendar={EndDate:"EndDate",Note:"Note"},I.Carts={SuperiorItem:"SuperiorItem",SuperiorCompany:"SuperiorCompany",SuperiorContact:"SuperiorContact",TypeEn:"TypeEn",StateEn:"StateEn"},I.Companies={ID:"ID",CompanyName:"CompanyName",Department:"Department",AccountNumber:"AccountNumber",IdentificationNumber:"IdentificationNumber",VatNumber:"VatNumber",Sales:"Reversal",EmployeesCount:"EmployeesCount",Purchaser:"Purchaser",Suppliers:"Suppliers",Competitor:"Competitor",Address1Street:"Address1Street",Address1City:"Address1City",Address1PostalCode:"Address1PostalCode",Address1CountryEn:"Address1CountryEn",Address1State:"Address1State",Address1POBox:"Address1POBox",Address2Street:"Address2Street",Address2City:"Address2City",Address2PostalCode:"Address2PostalCode",Address2CountryEn:"Address2CountryEn",Address2State:"Address2State",Address2POBox:"Address2POBox",Address3Street:"Address3Street",Address3City:"Address3City",Address3PostalCode:"Address3PostalCode",Address3CountryEn:"Address3CountryEn",Address3State:"Address3State",Address3POBox:"Address3POBox",InvoiceAddress:"InvoiceAddress",PostalAddress:"PostalAddress",Phone:"Phone",Mobile:"Mobile",Fax:"Fax",WebPage:"WebPage",Email:"Email",ICQ:"ICQ",MSN:"MSN",Skype:"Skype",ImportanceEn:"ImportanceEn",FirstContactEn:"FirstContactEn",LineOfBusiness:"LineOfBusiness",EmailOptOut:"EmailOptOut",MailingListOther:"MailingListOther",MailingListOtherValue:"MailingListOtherValue",Note:"Note",IsPrivate:"IsPrivate",NextStep:"NextStep",LastActivity:"LastActivity",AdditionalDiscount:"AdditionalDiscount"},I.Contacts={ProfilePicture:"ProfilePicture",Title:"Title",Email1Address:"Email1Address",Email2Address:"Email2Address",Email3Address:"Email3Address",DoNotSendNewsletter:"DoNotSendNewsletter",ImportanceEn:"ImportanceEn",PrefixEn:"PrefixEn",FirstName:"FirstName",MiddleName:"MiddleName",LastName:"LastName",SuffixEn:"SuffixEn",BusinessAddressStreet:"BusinessAddressStreet",BusinessAddressCity:"BusinessAddressCity",BusinessAddressPostalCode:"BusinessAddressPostalCode",BusinessAddressCountryEn:"BusinessAddressCountryEn",BusinessAddressState:"BusinessAddressState",BusinessAddressPoBox:"BusinessAddressPOBox",HomeAddressStreet:"HomeAddressStreet",HomeAddressCity:"HomeAddressCity",HomeAddressPostalCode:"HomeAddressPostalCode",HomeAddressCountryEn:"HomeAddressCountryEn",HomeAddressState:"HomeAddressState",HomeAddressPOBox:"HomeAddressPOBox",OtherAddressStreet:"OtherAddressStreet",OtherAddressCity:"OtherAddressCity",OtherAddressPostalCode:"OtherAddressPostalCode",OtherAddressCountryEn:"OtherAddressCountryEn",OtherAddressState:"OtherAddressState",OtherAddressPOBox:"OtherAddressPOBox",BusinessPhoneNumber:"TelephoneNumber1",BusinessPhoneNumber2:"TelephoneNumber5",BusinessFaxNumber:"TelephoneNumber6",MobilePhoneNumber:"TelephoneNumber3",HomePhoneNumber:"TelephoneNumber2",OtherPhoneNumber:"TelephoneNumber4",ICQ:"ICQ",MSN:"MSN",Skype:"Skype",WebPage:"WebPage",Note:"Note",Department:"Department",Company:"Company",IsPrivate:"Private",NextStep:"NextStep",LastActivity:"LastActivity"},I.Leads={ID:"ID",FileAs:"FileAs",HumanID:"HID",Customer:"Customer",ContactPerson:"ContactPerson",Marketing:"Marketing",ReceiveDate:"ReceiveDate",Email:"Email",Phone:"Phone",Street:"Street",State:"State",CountryEn:"CountryEn",City:"City",POBox:"POBox",Zip:"Zip",Price:"Price",PriceChanged:"PriceChanged",CurrencyEn:I.Common.CurrencyEn,EstimatedEnd:"EstimatedEnd",Probability:"Probability",LeadOriginEn:"LeadOriginEn",PriceDefaultCurrency:"PriceDefaultCurrency",EstimatedValue:"EstimatedValue",EstimatedValueDefaultCurrency:"EstimatedValueDefaultCurrency",Note:"Note",TypeEn:"TypeEn",StateEn:"StateEn",PrevStateEn:"PrevStateEn",IsPrivate:"Private",EmailOptOut:"EmailOptOut",NextStep:"NextStep",LastActivity:"LastActivity",ItemVersion:"ItemVersion",EstimatedRevenue:"EstimatedRevenue",EstimatedRevenueDefaultCurrency:"EstimatedRevenueDefaultCurrency",CompletedDate:"CompletedDate",LostDate:"LostDate"},I.Documents={FileAs:"FileAs",DocName:"DocName",Preview:"Preview",PreviewWidth:"PreviewWidth",PreviewHeight:"PreviewHeight",DocTypeEn:"DocTypeEn",StateEn:"StateEn",ImportanceEn:"ImportanceEn",SuperiorItem:"SuperiorItem",SuperiorCompany:"Company",SuperiorContact:"Contact",DocSize:"DocSize",Extension:"Extension",CreationTime:"CreationTime",LastWriteTime:"LastWriteTime",IsPrivate:"Private",Note:"Note"},I.Emails={To:"To",From:"SenderEmailAddress",Cc:"Cc",Subject:"Subject",ImportanceEn:"ImportanceEn",SuperiorItem:"SuperiorItem",SentOn:"SentOn",ReceivedTime:"ReceivedTime",FileSize:"FileSize",AttachmentsCount:"AttachmentsCount",Note:"Note",SentimentTone:"SentimentTone",Summary:"Summary"},I.Goods={Code:"Code",Structure:"Structure",Note:"Note",Description:"Description"},I.Journal={FileAs:"FileAs",Subject:"Subject",TypeEn:"TypeEn",StateEn:"StateEn",ImportanceEn:"ImportanceEn",EventStart:"EventStart",EventEnd:"EventEnd",SuperiorItem:"SuperiorItem",Company:"Company",Contact:"Contact",Marketing:"Marketing",IsSystem:"System",IsPrivate:"Private",Note:"Note",Phone:"Phone"},I.Vacation={StartDate:"StartDate",EndDate:"EndDate",User:"User",Duration:"Duration",Place:"Place",Note:"Note",AllDay:"AllDay",TypeEn:"TypeEn",StateEn:"StateEn",IsPrivate:"Private"},I.Marketing={HumanID:"HumanID",EstimatedStart:"EstimatedStart",EstimatedEnd:"EstimatedEnd",RealStart:"RealStart",RealEnd:"RealEnd",TargetGroup:"TargetGroup",EmailsSent:"EmailsSent",EmailsDelivered:"EmailsDelivered",EmailsViewed:"EmailsViewed",PeopleUnsubscribed:"PeopleUnsubscribed",FinalRevenues:"FinalRevenues",TypeEn:"TypeEn",StateEn:"StateEn"},I.Projects={HumanID:"HID",FileAs:"FileAs",ProjectName:"ProjectName",ProjectOriginEn:"ProjectOriginEn",TypeEn:"TypeEn",StateEn:"StateEn",PaymentTypeEn:"PaymentTypeEn",ProjectStart:"ProjectStart",ProjectRealEnd:"ProjectRealEnd",EstimatedEnd:"ProjectEnd",CurrencyEn:I.Common.CurrencyEn,DefaultCurrencyEn:"DefaultCurrencyEn",EstimatedMargin:"EstimatedMargin",EstimatedPeopleExpenses:"EstimatedPeopleExpenses",EstimatedPeopleExpensesDefaultCurrency:"EstimatedPeopleExpensesDefaultCurrency",EstimatedOtherExpenses:"EstimatedOtherExpenses",EstimatedOtherExpensesDefaultCurrency:"EstimatedOtherExpensesDefaultCurrency",EstimatedPrice:"EstimatedPrice",EstimatedPriceDefaultCurrency:"EstimatedPriceDefaultCurrency",EstimatedProfit:"EstimatedProfit",EstimatedProfitDefaultCurrency:"EstimatedProfitDefaultCurrency",EstimatedPriceChanged:"EstimatedPriceChanged",EstimatedPeopleExpensesChanged:"EstimatedPeopleExpensesChanged",EstimatedOtherExpensesChanged:"EstimatedOtherExpensesChanged",Delay:"Delay",EstimatedWorkHours:"EstimatedWorkHours",TotalWorkHours:"TotalWorkHours",PeopleExpenses:"PeopleExpenses",OtherExpenses:"OtherExpenses",PeopleExpensesDefaultCurrency:"PeopleExpensesDefaultCurrency",OtherExpensesDefaultCurrency:"OtherExpensesDefaultCurrency",PeopleExpensesChanged:"PeopleExpensesChanged",OtherExpensesChanged:"OtherExpensesChanged",Price:"Price",PriceDefaultCurrency:"PriceDefaultCurrency",Profit:"Profit",ProfitDefaultCurrency:"ProfitDefaultCurrency",Margin:"Margin",PriceChanged:"PriceChanged",SuperiorProject:"SuperiorProject",Customer:"Customer",ContactPerson:"ContactPerson",Users:"Users",ProjectManager:"ProjectManager",InvoicePaymentDate:"InvoicePaymentDate",PaymentMaturity:"PaymentMaturity",InvoiceIssueDate:"InvoiceIssueDate",LicensesCount:"LicensesCount",LicensePrice:"LicensePrice",LicensePriceDefaultCurrency:"LicensePriceDefaultCurrency",NextStep:"NextStep",LastActivity:"LastActivity",IsPrivate:"Private",LicensePriceChanged:"LicensePriceChanged",Note:"Note",CompletedDate:"CompletedDate",LostDate:"LostDate"},I.Tasks={FileAs:"FileAs",Subject:"Subject",RootItem:"RootItem",SuperiorItem:"SuperiorItem",Company:"Company",Contact:"Contact",StartDate:"StartDate",DueDate:"DueDate",Reminder:"Reminder",ReminderDate:"ReminderDate",ImportanceEn:"ImportanceEn",IsCompleted:"Complete",PercentComplete:"PercentComplete",PercentCompleteDecimal:"PercentCompleteDecimal",CompletedDate:"CompletedDate",Solver:"Solver",Delegator:"Delegator",Level:"Level",IsPrivate:"Private",ActualWorkHours:"ActualWorkHours",TotalWorkHours:"TotalWorkHours",Body:"Body",TypeEn:"TypeEn",StateEn:"StateEn"},I.Training={TitleEn:"TitleEn"},I.WorkReports={Task:"Task",ProjectName:"ProjectName",UserName:"UserName",Subject:"Subject",Date:"Date",FromTime:"FromTime",ToTime:"ToTime",Overtime:"Overtime",Month:"Month",Year:"Year",IsPrivate:"Private",Note:"Note",Duration:"Duration",WorkReportEn:"WorkReportEn",StateEn:"StateEn"},I.Users={ProfilePicture:"ProfilePicture",UserName:"UserName",JobTitle:"JobTitle",IDCardNumber:"IDCardNumber",Birthdate:"Birthdate",BirthPlace:"BirthPlace",PersonalIdentificationNumber:"PersonalIdentificationNumber",Active:"Active",FamilyStatusEn:"FamilyStatusEn",HomeAddressStreet:"HomeAddressStreet",HomeAddressCity:"HomeAddressCity",HomeAddressPostalCode:"HomeAddressPostalCode",HomeAddressCountryEn:"HomeAddressCountryEn",HomeAddressState:"HomeAddressState",HomeAddressPOBox:"HomeAddressPOBox",BankAccount:"BankAccount",BusinessPhoneNumber:"BusinessPhoneNumber",MobilePhoneNumber:"MobilePhoneNumber",Email1Address:"Email1Address",Email2Address:"Email2Address",ICQ:"ICQ",MSN:"MSN",Skype:"Skype",IdentificationNumber:"IdentificationNumber",HealthInsurance:"HealthInsurance",HolidayLength:"HolidayLength",RemainingDaysOfHoliday:"RemainingDaysOfHoliday",SalaryDateEn:"SalaryDateEn",Supervisor:"Supervisor",TravelDistance:"TravelDistance",TimeAccessibility:"TimeAccessibility",TransportMode:"TransportMode",WorkdayStartTime:"WorkdayStartTime",Note:"Note",IsSystem:"IsSystem"},I.Groups={IsAdmin:"IsAdmin",GroupName:"GroupName",FileAs:"FileAs",Description:"Description",IsPM:"IsPM",System:"System",IsRole:"IsRole",IsCategory:"IsCategory",DisallowControlModulePermissions:"DisallowControlModulePermissions",DisallowControlColumnPermissions:"DisallowControlColumnPermissions",IsOutlookCategory:"IsOutlookCategory",DisallowControlUserAssignment:"DisallowControlUserAssignment",ColorEn:"ColorEn",Picture:"Picture"},I.allTypeEnNames=["TypeEn",I.Documents.DocTypeEn,I.WorkReports.WorkReportEn,"TitleEn"],I.getFolderFileAs=e=>{switch(e){case m.leads:return I.Leads.FileAs;case m.projects:return I.Projects.ProjectName;case m.documents:return I.Documents.DocName;case m.companies:return I.Companies.CompanyName;case m.contacts:case m.users:return I.Common.FileAs;case m.emails:return I.Emails.Subject;case m.journal:return I.Journal.FileAs;case m.tasks:return I.Tasks.Subject;case m.workReports:return I.WorkReports.Subject;case m.vacation:return I.Vacation.TypeEn;case m.carts:case m.goods:return I.Common.FileAs;case m.groups:return I.Groups.GroupName;default:return console.warn(`FileAs col name not defined for folderName ${e}`),I.Common.FileAs}};class b{}b.general="GENERAL",b.group="GROUP",b.contactPerson="CONTACTPERSON",b.contact="CONTACT",b.customer="CUSTOMER",b.company="COMPANY",b.outlookProject="OUTLOOKPROJECT",b.supervisor="SUPERVISOR";class w{}w.all="All",w.own="Own",w.readonly="Readonly",w.invisible="Invisible",w.none="None";class D{}var N,x,O,M;D.mandatory="Mandatory",D.optional="Optional",D.unique="Unique",D.none="None",exports.Edition=void 0,(N=exports.Edition||(exports.Edition={})).Free="Free",N.Basic="Basic",N.Professional="Professional",N.Enterprise="Enterprise",exports.Feature=void 0,(x=exports.Feature||(exports.Feature={})).ContactsAndCompanies="ContactsAndCompanies",x.Sales="Sales",x.Projects="Projects",x.Marketing="Marketing",exports.SentimentTone=void 0,(O=exports.SentimentTone||(exports.SentimentTone={}))[O.Negative=0]="Negative",O[O.Neutral=1]="Neutral",O[O.Positive=2]="Positive";class R{}R.contactsSynchronizationWithOutlook="ContactsSynchronizationWithOutlook",R.wordAddin="WordAddin",R.excelAddin="ExcelAddin",R.tasksRecurrentTasks="TasksRecurrentTasks",R.tasksSubtasks="TasksSubtasks",R.tasksSynchronizationWithOutlook="TasksSynchronizationWithOutlook",R.calendarSynchronizationWithOutlook="CalendarSynchronizationWithOutlook",R.emailsAutomaticTracking="EmailsAutomaticTracking",R.convertEmailToProject="ConvertEmailToProject",R.duplicityChecker="DuplicityChecker",R.nextStepAndLastActivityCustomization="NextStepAndLastActivityCustomization",R.subProjects="SubProjects",R.resourceAndPlanning="ResourceAndPlanning",R.professionalEmailCampaigns="ProfessionalEmailCampaigns",R.professionalEmailCampaignsAdvancedStatistics="ProfessionalEmailCampaignsAdvancedStatistics",R.wordEmailMerge="WordEmailMerge",R.printLabels="PrintLabels",R.printEnvelopes="PrintEnvelopes",R.userViews="UserViews",R.sharedUserViews="SharedUserViews",R.gridConditionalFormating="GridConditionalFormating",R.multipleCurrencies="MultipleCurrencies",R.historyTracking="HistoryTracking",R.privateItems="PrivateItems",R.itemTypes="ItemTypes",R.formLayoutCustomization="FormLayoutCustomization",R.workflowBasicDefinitions="WorkflowBasicDefinitions",R.workflowAdvancedDefinitions="WorkflowAdvancedDefinitions",R.workflowAdvancedDefinitionsRules="WorkflowAdvancedDefinitionsRules",R.workflowAdvancedDefinitionsActions="WorkflowAdvancedDefinitionsActions",R.workflowGroupLevelActions="WorkflowGroupLevelActions",R.customFields="CustomFields",R.importantFields="ImportantFields",R.mandatoryFields="MandatoryFields",R.uniqueFields="UniqueFields",R.readOnlyFields="ReadOnlyFields",R.transformationCustomTemplates="TransformationCustomTemplates",R.userRoles="UserRoles",R.modulePermissions="ModulePermissions",R.columnPermissions="ColumnPermissions",R.api="API",R.gate="Gate",R.threeCXIntegration="ThreeCXIntegration",R.tapiIntegration="TapiIntegration",R.pohodaIntegration="PohodaIntegration",R.pohodaSynchronizationIntervalCustomization="PohodaSynchronizationIntervalCustomization",R.pohodaSynchronizationFieldMappingCustomization="PohodaSynchronizationFieldMappingCustomization",R.quickBooksIntegration="QuickBooksIntegration",R.saveBinaryDataOnDisk="SaveBinaryDataOnDisk",R.activeDirectoryLogin="ActiveDirectoryLogin",R.callerIdentificationOnApple="CallerIdentificationOnApple",R.legacyAdministration="LegacyAdministration";class F{}F.customAdditionalFieldsCount="CustomAdditionalFieldsCount",F.customEnabledAdvancedWorkflowsCount="CustomEnabledAdvancedWorkflowsCount",F.customEnabledBasicWorkflowsCount="CustomEnabledBasicWorkflowsCount",F.customMandatoryFieldsCount="CustomMandatoryFieldsCount",F.customOptionalFieldsCount="CustomOptionalFieldsCount",F.customReadonlyFieldsCount="CustomReadonlyFieldsCount",F.customUniqueFieldsCount="CustomUniqueFieldsCount",F.customVisibleTypesCount="CustomVisibleTypesCount",F.visibleCurrenciesCount="VisibleCurrenciesCount";class L{}L.contactsAutomaticSynchronizationWithOutlook="ContactsAutomaticSynchronizationWithOutlook",L.contactsSynchronizationWithOutlook="ContactsSynchronizationWithOutlook",L.contactsSynchronizationWithAndroid="ContactsSynchronizationWithAndroid",L.documentsRevisions="DocumentsRevisions",L.wordAddin="WordAddin",L.excelAddin="ExcelAddin",L.tasksReminders="TasksReminders",L.tasksRecurrentTasks="TasksRecurrentTasks",L.tasksSubtasks="TasksSubtasks",L.tasksSynchronizationWithOutlook="TasksSynchronizationWithOutlook",L.calendarSynchronizationWithOutlook="CalendarSynchronizationWithOutlook",L.emailsManualTracking="EmailsManualTracking",L.emailsAutomaticTracking="EmailsAutomaticTracking",L.emailSummaryAndSentimentToneFromAi="EmailSummaryAndSentimentToneFromAi",L.convertEmailToContact="ConvertEmailToContact",L.convertEmailToContactInBulk="ConvertEmailToContactInBulk",L.convertEmailToDeal="ConvertEmailToDeal",L.convertEmailToProject="ConvertEmailToProject",L.convertEmailToTask="ConvertEmailToTask",L.gravatarIntegration="GravatarIntegration",L.logoboxIntegration="LogoboxIntegration",L.companiesBussinesRegisterApiIntegration="CompaniesBussinesRegisterApiIntegration",L.duplicityChecker="DuplicityChecker",L.nextStepAndLastActivityCustomization="NextStepAndLastActivityCustomization",L.subProjects="SubProjects",L.resourceAndPlanning="ResourceAndPlanning",L.professionalEmailCampaigns="ProfessionalEmailCampaigns",L.professionalEmailCampaignsAdvancedStatistics="ProfessionalEmailCampaignsAdvancedStatistics",L.wordEmailMerge="WordEmailMerge",L.printLabels="PrintLabels",L.printEnvelopes="PrintEnvelopes",L.userViews="UserViews",L.sharedUserViews="SharedUserViews",L.gridRowSummary="GridRowSummary",L.gridConditionalFormating="GridConditionalFormating",L.multipleCurrencies="MultipleCurrencies",L.historyTracking="HistoryTracking",L.privateItems="PrivateItems",L.itemTypes="ItemTypes",L.formLayoutCustomization="FormLayoutCustomization",L.workflowBasicDefinitions="WorkflowBasicDefinitions",L.workflowAdvancedDefinitions="WorkflowAdvancedDefinitions",L.workflowAdvancedDefinitionsRules="WorkflowAdvancedDefinitionsRules",L.workflowAdvancedDefinitionsActions="WorkflowAdvancedDefinitionsActions",L.workflowGroupLevelActions="WorkflowGroupLevelActions",L.customFields="CustomFields",L.importantFields="ImportantFields",L.mandatoryFields="MandatoryFields",L.uniqueFields="UniqueFields",L.readOnlyFields="ReadOnlyFields",L.transformationCustomTemplates="TransformationCustomTemplates",L.userRoles="UserRoles",L.modulePermissions="ModulePermissions",L.columnPermissions="ColumnPermissions",L.commonDataAPI="CommonDataAPI",L.eWayCrmAPI="eWayCrmAPI",L.threeCXIntegration="ThreeCXIntegration",L.tapiIntegration="TapiIntegration",L.pohodaIntegration="PohodaIntegration",L.pohodaSynchronizationIntervalCustomization="PohodaSynchronizationIntervalCustomization",L.pohodaSynchronizationFieldMappingCustomization="PohodaSynchronizationFieldMappingCustomization",L.quickBooksIntegration="QuickBooksIntegration",L.shareByTeams="ShareByTeams",L.convertEmailToContactWithDataFromAi="ConvertEmailToContactWithDataFromAi",L.convertEmailToDealWithDataFromAi="ConvertEmailToDealWithDataFromAi",L.convertEmailToProjectWithDataFromAi="ConvertEmailToProjectWithDataFromAi",function(e){e.UnpaidImportantInvoices="UnpaidImportantInvoices",e.UncollectableSubscriptionPayment="UncollectableSubscriptionPayment",e.UncollectableSubscriptionPaymentWithExpiredCard="UncollectableSubscriptionPaymentWithExpiredCard",e.StandardSubscriptionPeriod="StandardSubscriptionPeriod"}(M||(M={}));var U,B=M;!function(e){e.License="License",e.CloudLicense="CloudLicense",e.MiscLicense="MiscLicense",e.Support="Support",e.Service="Service"}(U||(U={}));var W=U;class j{}j.getIsDebug=e=>{var t;return!!(null===(t=null==e?void 0:e.sessionHandler.lastSuccessfulLoginResponse)||void 0===t?void 0:t.Debug)},j.supportsFeaturesOf=(e,t)=>{var s;const n=null===(s=e.sessionHandler.lastSuccessfulLoginResponse)||void 0===s?void 0:s.WcfVersion;return!!n&&(o.compare(n,t,">=")||o.compare(n,"1.0.0.0","="))};class G{}G.textBox="TextBox",G.comboBox="ComboBox",G.numericBox="NumericBox",G.relation="Relation",G.checkBox="CheckBox",G.linkTextBox="LinkTextBox",G.dateEdit="DateEdit",G.memoBox="MemoBox",G.multiSelectComboBox="MultiSelectComboBox",G.workflowState="WorkflowState",G.image="Image",G.multiSelectRelation="MultiSelectRelation";const H={[m.relations]:0,[m.unifiedRelations]:1,[m.users]:2,[m.groups]:3,[m.enumTypes]:4,[m.enumValues]:5,[m.additionalFields]:6};var _;exports.EnumTypeEditMode=void 0,(_=exports.EnumTypeEditMode||(exports.EnumTypeEditMode={})).Readonly="Readonly",_.VisibleRankDefaultOnly="VisibleRankDefaultOnly",_.Editable="Editable",c.polyfill(),exports.ApiConnectionAsNonDefaultExport=P,exports.ApiMethods=p,exports.ColumnPermissionMandatoryRules=D,exports.ColumnPermissionPermissionRules=w,exports.CommonDataConnection=class{constructor(e,t){this.isCommonDataApiEnabled=(e,t)=>{this.tokenizedConnection.isEnabled(e,t)},this.callCommonDataApi=(e,t,s,o)=>{this.tokenizedConnection.callTokenizedApi(e,t,s,o)},this.tokenizedConnection=new A("ObtainCommonDataApiAccessToken",exports.HttpMethod.get,!1,"InvalidCommonDataToken",T,e,t)}},exports.CustomizationStatsItemKeys=F,exports.EWItem=class{constructor(e,t){if(!e||!t)throw new Error("Both folderName and baseItem has to be defined!");this.folderName=e,this.baseItem=t}getEmailAddress(){switch(this.folderName){case m.contacts:{const e=this.baseItem;return e.Email1Address||e.Email2Address||e.Email3Address}case m.leads:return this.baseItem.Email;case m.companies:return this.baseItem.Email;case m.users:{const e=this.baseItem;return e.Email1Address||e.Email2Address}default:return null}}getInitials(){switch(this.folderName){case m.contacts:{const e=this.baseItem;return this.getInitialsInternal(e.FirstName,e.LastName)}case m.users:{const e=this.baseItem;return this.getInitialsInternal(e.FirstName,e.LastName)}default:return null}}getInitialsInternal(e,t){const s=((null==e?void 0:e.substr(0,1))||"")+((null==t?void 0:t.substr(0,1))||"");return""==s?null:s}getItemPreview(){switch(this.folderName){case m.contacts:{const e=this.baseItem;return e.ProfilePicture?{imageData:e.ProfilePicture,width:e.ProfilePictureWidth||0,height:e.ProfilePictureHeight||0}:null}case m.users:{const e=this.baseItem;return e.ProfilePicture?{imageData:e.ProfilePicture,width:e.ProfilePictureWidth||0,height:e.ProfilePictureHeight||0}:null}default:return null}}},exports.EnumTypes=u,exports.ErrorHelper=v,exports.ExpirationReason=B,exports.FieldNames=I,exports.FieldTypes=G,exports.FolderNames=m,exports.Functionality=R,exports.GlobalSettingsNames=k,exports.HttpRequestError=E,exports.LicenseKeyInvoiceSeverity=W,exports.LicenseRestrictionKeys=L,exports.OAuthHelper=C,exports.OAuthSessionHandlerBase=g,exports.ObjectTypeIds=H,exports.QueryHelper=class{static createHubItemsCountsQuery(e,t,s){return{__type:"HubItemsCountsQuery:#EQ",ParentItemGuids:e,ItemTypes:t,ExcludeSystemItems:s}}},exports.RelationTypes=b,exports.ReturnCodes=d,exports.TokenizedServiceConnection=A,exports.VersionHelperBase=j,exports.default=P;
@@ -21,5 +21,12 @@ export declare class ApiMethods {
21
21
  static readonly getBinaryAttachmentLatestRevision = "GetBinaryAttachmentLatestRevision";
22
22
  static readonly canUnlinkItems = "CanUnlinkItems";
23
23
  static readonly unlinkItems = "UnlinkItems";
24
+ /**
25
+ * Return folderName part of API method that is used in API calls. Some API methods have different names than the folder names they are associated with.
26
+ * For example module Calendar has method GetCalendarsByItemGuids, but the folder name is Calendar.
27
+ */
28
+ private static readonly getFolderNameForApiMethod;
24
29
  static readonly getGetFolderNameByItemGuidsMethodName: (folderName: TFolderName) => string;
30
+ static readonly getGetFolderNameMethodName: (folderName: TFolderName) => string;
31
+ static readonly getSearchFolderNameMethodName: (folderName: TFolderName) => string;
25
32
  }
@@ -1,10 +1,13 @@
1
1
  import type { ITokenData } from '../interfaces/ITokenData';
2
2
  import type { IEWJwtPayload } from '../interfaces/IEWJwtPayload';
3
+ export type scope = "api" | "offline_access";
4
+ export type codeChallengeMethod = "plain" | "S256";
3
5
  export declare class OAuthHelper {
4
6
  static finishAuthorization: (wsUrl: string, clientId: string, clientSecret: string, codeVerifier: string, authorizationCode: string, redirectUrl: string, callback: (tokenData: ITokenData) => void) => void;
5
7
  static refreshToken: (wsUrl: string, clientId: string, clientSecret: string, refreshToken: string, callback: (tokenData: ITokenData) => void) => void;
6
8
  static getWebServiceUrl: (refreshToken: string) => string;
7
9
  static getUserName: (accessToken: string) => string | undefined;
8
10
  static decodeAccessToken: (accessToken: string) => IEWJwtPayload;
11
+ static createAuthorizeUrl(clientId: string, scopes: scope[], redirectUri: string, state?: string, codeChallenge?: string, codeChallengeMethod?: codeChallengeMethod, isDev?: boolean): string;
9
12
  private static callTokenEndpoint;
10
13
  }
package/lib/esm/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import e from"axios";import*as t from"universal-base64url";import s from"jwt-decode";import{compare as n}from"compare-versions";var o="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var r,i={exports:{}},a=i.exports=function(){function e(e){var t=typeof e;return null!==e&&("object"===t||"function"===t)}function t(e){return"function"==typeof e}var s=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},n=0,r=void 0,i=void 0,a=function(e,t){E[n]=e,E[n+1]=t,2===(n+=2)&&(i?i(v):A())};function l(e){i=e}function c(e){a=e}var d="undefined"!=typeof window?window:void 0,u=d||{},m=u.MutationObserver||u.WebKitMutationObserver,p="undefined"==typeof self&&"undefined"!=typeof process&&"[object process]"==={}.toString.call(process),h="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel;function y(){return function(){return process.nextTick(v)}}function C(){return void 0!==r?function(){r(v)}:S()}function f(){var e=0,t=new m(v),s=document.createTextNode("");return t.observe(s,{characterData:!0}),function(){s.data=e=++e%2}}function g(){var e=new MessageChannel;return e.port1.onmessage=v,function(){return e.port2.postMessage(0)}}function S(){var e=setTimeout;return function(){return e(v,1)}}var E=new Array(1e3);function v(){for(var e=0;e<n;e+=2)(0,E[e])(E[e+1]),E[e]=void 0,E[e+1]=void 0;n=0}function P(){try{var e=Function("return this")().require("vertx");return r=e.runOnLoop||e.runOnContext,C()}catch(e){return S()}}var A=void 0;function k(e,t){var s=this,n=new this.constructor(b);void 0===n[I]&&q(n);var o=s._state;if(o){var r=arguments[o-1];a((function(){return H(o,n,r,s._result)}))}else j(s,n,e,t);return n}function T(e){var t=this;if(e&&"object"==typeof e&&e.constructor===t)return e;var s=new t(b);return F(s,e),s}A=p?y():m?f():h?g():void 0===d?P():S();var I=Math.random().toString(36).substring(2);function b(){}var w=void 0,D=1,N=2;function O(){return new TypeError("You cannot resolve a promise with itself")}function R(){return new TypeError("A promises callback cannot return that same promise.")}function M(e,t,s,n){try{e.call(t,s,n)}catch(e){return e}}function L(e,t,s){a((function(e){var n=!1,o=M(s,t,(function(s){n||(n=!0,t!==s?F(e,s):G(e,s))}),(function(t){n||(n=!0,W(e,t))}),"Settle: "+(e._label||" unknown promise"));!n&&o&&(n=!0,W(e,o))}),e)}function x(e,t){t._state===D?G(e,t._result):t._state===N?W(e,t._result):j(t,void 0,(function(t){return F(e,t)}),(function(t){return W(e,t)}))}function B(e,s,n){s.constructor===e.constructor&&n===k&&s.constructor.resolve===T?x(e,s):void 0===n?G(e,s):t(n)?L(e,s,n):G(e,s)}function F(t,s){if(t===s)W(t,O());else if(e(s)){var n=void 0;try{n=s.then}catch(e){return void W(t,e)}B(t,s,n)}else G(t,s)}function U(e){e._onerror&&e._onerror(e._result),_(e)}function G(e,t){e._state===w&&(e._result=t,e._state=D,0!==e._subscribers.length&&a(_,e))}function W(e,t){e._state===w&&(e._state=N,e._result=t,a(U,e))}function j(e,t,s,n){var o=e._subscribers,r=o.length;e._onerror=null,o[r]=t,o[r+D]=s,o[r+N]=n,0===r&&e._state&&a(_,e)}function _(e){var t=e._subscribers,s=e._state;if(0!==t.length){for(var n=void 0,o=void 0,r=e._result,i=0;i<t.length;i+=3)n=t[i],o=t[i+s],n?H(s,n,o,r):o(r);e._subscribers.length=0}}function H(e,s,n,o){var r=t(n),i=void 0,a=void 0,l=!0;if(r){try{i=n(o)}catch(e){l=!1,a=e}if(s===i)return void W(s,R())}else i=o;s._state!==w||(r&&l?F(s,i):!1===l?W(s,a):e===D?G(s,i):e===N&&W(s,i))}function z(e,t){try{t((function(t){F(e,t)}),(function(t){W(e,t)}))}catch(t){W(e,t)}}var V=0;function J(){return V++}function q(e){e[I]=V++,e._state=void 0,e._result=void 0,e._subscribers=[]}function Q(){return new Error("Array Methods must be provided an Array")}var $=function(){function e(e,t){this._instanceConstructor=e,this.promise=new e(b),this.promise[I]||q(this.promise),s(t)?(this.length=t.length,this._remaining=t.length,this._result=new Array(this.length),0===this.length?G(this.promise,this._result):(this.length=this.length||0,this._enumerate(t),0===this._remaining&&G(this.promise,this._result))):W(this.promise,Q())}return e.prototype._enumerate=function(e){for(var t=0;this._state===w&&t<e.length;t++)this._eachEntry(e[t],t)},e.prototype._eachEntry=function(e,t){var s=this._instanceConstructor,n=s.resolve;if(n===T){var o=void 0,r=void 0,i=!1;try{o=e.then}catch(e){i=!0,r=e}if(o===k&&e._state!==w)this._settledAt(e._state,t,e._result);else if("function"!=typeof o)this._remaining--,this._result[t]=e;else if(s===te){var a=new s(b);i?W(a,r):B(a,e,o),this._willSettleAt(a,t)}else this._willSettleAt(new s((function(t){return t(e)})),t)}else this._willSettleAt(n(e),t)},e.prototype._settledAt=function(e,t,s){var n=this.promise;n._state===w&&(this._remaining--,e===N?W(n,s):this._result[t]=s),0===this._remaining&&G(n,this._result)},e.prototype._willSettleAt=function(e,t){var s=this;j(e,void 0,(function(e){return s._settledAt(D,t,e)}),(function(e){return s._settledAt(N,t,e)}))},e}();function K(e){return new $(this,e).promise}function Y(e){var t=this;return s(e)?new t((function(s,n){for(var o=e.length,r=0;r<o;r++)t.resolve(e[r]).then(s,n)})):new t((function(e,t){return t(new TypeError("You must pass an array to race."))}))}function X(e){var t=new this(b);return W(t,e),t}function Z(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function ee(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}var te=function(){function e(t){this[I]=J(),this._result=this._state=void 0,this._subscribers=[],b!==t&&("function"!=typeof t&&Z(),this instanceof e?z(this,t):ee())}return e.prototype.catch=function(e){return this.then(null,e)},e.prototype.finally=function(e){var s=this,n=s.constructor;return t(e)?s.then((function(t){return n.resolve(e()).then((function(){return t}))}),(function(t){return n.resolve(e()).then((function(){throw t}))})):s.then(e,e)},e}();function se(){var e=void 0;if(void 0!==o)e=o;else if("undefined"!=typeof self)e=self;else try{e=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var t=e.Promise;if(t){var s=null;try{s=Object.prototype.toString.call(t.resolve())}catch(e){}if("[object Promise]"===s&&!t.cast)return}e.Promise=te}return te.prototype.then=k,te.all=K,te.race=Y,te.resolve=T,te.reject=X,te._setScheduler=l,te._setAsap=c,te._asap=a,te.polyfill=se,te.Promise=te,te}();
1
+ import e from"axios";import*as t from"universal-base64url";import s from"jwt-decode";import{compare as o}from"compare-versions";var n="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var r,i={exports:{}},a=i.exports=function(){function e(e){var t=typeof e;return null!==e&&("object"===t||"function"===t)}function t(e){return"function"==typeof e}var s=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},o=0,r=void 0,i=void 0,a=function(e,t){v[o]=e,v[o+1]=t,2===(o+=2)&&(i?i(E):A())};function l(e){i=e}function c(e){a=e}var d="undefined"!=typeof window?window:void 0,u=d||{},m=u.MutationObserver||u.WebKitMutationObserver,p="undefined"==typeof self&&"undefined"!=typeof process&&"[object process]"==={}.toString.call(process),h="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel;function y(){return function(){return process.nextTick(E)}}function C(){return void 0!==r?function(){r(E)}:S()}function f(){var e=0,t=new m(E),s=document.createTextNode("");return t.observe(s,{characterData:!0}),function(){s.data=e=++e%2}}function g(){var e=new MessageChannel;return e.port1.onmessage=E,function(){return e.port2.postMessage(0)}}function S(){var e=setTimeout;return function(){return e(E,1)}}var v=new Array(1e3);function E(){for(var e=0;e<o;e+=2)(0,v[e])(v[e+1]),v[e]=void 0,v[e+1]=void 0;o=0}function P(){try{var e=Function("return this")().require("vertx");return r=e.runOnLoop||e.runOnContext,C()}catch(e){return S()}}var A=void 0;function k(e,t){var s=this,o=new this.constructor(b);void 0===o[I]&&$(o);var n=s._state;if(n){var r=arguments[n-1];a((function(){return H(n,o,r,s._result)}))}else j(s,o,e,t);return o}function T(e){var t=this;if(e&&"object"==typeof e&&e.constructor===t)return e;var s=new t(b);return U(s,e),s}A=p?y():m?f():h?g():void 0===d?P():S();var I=Math.random().toString(36).substring(2);function b(){}var w=void 0,D=1,N=2;function O(){return new TypeError("You cannot resolve a promise with itself")}function R(){return new TypeError("A promises callback cannot return that same promise.")}function M(e,t,s,o){try{e.call(t,s,o)}catch(e){return e}}function L(e,t,s){a((function(e){var o=!1,n=M(s,t,(function(s){o||(o=!0,t!==s?U(e,s):W(e,s))}),(function(t){o||(o=!0,G(e,t))}),"Settle: "+(e._label||" unknown promise"));!o&&n&&(o=!0,G(e,n))}),e)}function F(e,t){t._state===D?W(e,t._result):t._state===N?G(e,t._result):j(t,void 0,(function(t){return U(e,t)}),(function(t){return G(e,t)}))}function x(e,s,o){s.constructor===e.constructor&&o===k&&s.constructor.resolve===T?F(e,s):void 0===o?W(e,s):t(o)?L(e,s,o):W(e,s)}function U(t,s){if(t===s)G(t,O());else if(e(s)){var o=void 0;try{o=s.then}catch(e){return void G(t,e)}x(t,s,o)}else W(t,s)}function B(e){e._onerror&&e._onerror(e._result),_(e)}function W(e,t){e._state===w&&(e._result=t,e._state=D,0!==e._subscribers.length&&a(_,e))}function G(e,t){e._state===w&&(e._state=N,e._result=t,a(B,e))}function j(e,t,s,o){var n=e._subscribers,r=n.length;e._onerror=null,n[r]=t,n[r+D]=s,n[r+N]=o,0===r&&e._state&&a(_,e)}function _(e){var t=e._subscribers,s=e._state;if(0!==t.length){for(var o=void 0,n=void 0,r=e._result,i=0;i<t.length;i+=3)o=t[i],n=t[i+s],o?H(s,o,n,r):n(r);e._subscribers.length=0}}function H(e,s,o,n){var r=t(o),i=void 0,a=void 0,l=!0;if(r){try{i=o(n)}catch(e){l=!1,a=e}if(s===i)return void G(s,R())}else i=n;s._state!==w||(r&&l?U(s,i):!1===l?G(s,a):e===D?W(s,i):e===N&&G(s,i))}function z(e,t){try{t((function(t){U(e,t)}),(function(t){G(e,t)}))}catch(t){G(e,t)}}var V=0;function J(){return V++}function $(e){e[I]=V++,e._state=void 0,e._result=void 0,e._subscribers=[]}function q(){return new Error("Array Methods must be provided an Array")}var Q=function(){function e(e,t){this._instanceConstructor=e,this.promise=new e(b),this.promise[I]||$(this.promise),s(t)?(this.length=t.length,this._remaining=t.length,this._result=new Array(this.length),0===this.length?W(this.promise,this._result):(this.length=this.length||0,this._enumerate(t),0===this._remaining&&W(this.promise,this._result))):G(this.promise,q())}return e.prototype._enumerate=function(e){for(var t=0;this._state===w&&t<e.length;t++)this._eachEntry(e[t],t)},e.prototype._eachEntry=function(e,t){var s=this._instanceConstructor,o=s.resolve;if(o===T){var n=void 0,r=void 0,i=!1;try{n=e.then}catch(e){i=!0,r=e}if(n===k&&e._state!==w)this._settledAt(e._state,t,e._result);else if("function"!=typeof n)this._remaining--,this._result[t]=e;else if(s===te){var a=new s(b);i?G(a,r):x(a,e,n),this._willSettleAt(a,t)}else this._willSettleAt(new s((function(t){return t(e)})),t)}else this._willSettleAt(o(e),t)},e.prototype._settledAt=function(e,t,s){var o=this.promise;o._state===w&&(this._remaining--,e===N?G(o,s):this._result[t]=s),0===this._remaining&&W(o,this._result)},e.prototype._willSettleAt=function(e,t){var s=this;j(e,void 0,(function(e){return s._settledAt(D,t,e)}),(function(e){return s._settledAt(N,t,e)}))},e}();function K(e){return new Q(this,e).promise}function Y(e){var t=this;return s(e)?new t((function(s,o){for(var n=e.length,r=0;r<n;r++)t.resolve(e[r]).then(s,o)})):new t((function(e,t){return t(new TypeError("You must pass an array to race."))}))}function X(e){var t=new this(b);return G(t,e),t}function Z(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function ee(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}var te=function(){function e(t){this[I]=J(),this._result=this._state=void 0,this._subscribers=[],b!==t&&("function"!=typeof t&&Z(),this instanceof e?z(this,t):ee())}return e.prototype.catch=function(e){return this.then(null,e)},e.prototype.finally=function(e){var s=this,o=s.constructor;return t(e)?s.then((function(t){return o.resolve(e()).then((function(){return t}))}),(function(t){return o.resolve(e()).then((function(){throw t}))})):s.then(e,e)},e}();function se(){var e=void 0;if(void 0!==n)e=n;else if("undefined"!=typeof self)e=self;else try{e=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var t=e.Promise;if(t){var s=null;try{s=Object.prototype.toString.call(t.resolve())}catch(e){}if("[object Promise]"===s&&!t.cast)return}e.Promise=te}return te.prototype.then=k,te.all=K,te.race=Y,te.resolve=T,te.reject=X,te._setScheduler=l,te._setAsap=c,te._asap=a,te.polyfill=se,te.Promise=te,te}();
2
2
  /*!
3
3
  * @overview es6-promise - a tiny implementation of Promises/A+.
4
4
  * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
5
5
  * @license Licensed under MIT license
6
6
  * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
7
7
  * @version v4.2.8+1e68dce6
8
- */class l{}l.rcSuccess="rcSuccess",l.rcBadSession="rcBadSession",l.rcDuplicateContact="rcDuplicateContact",l.rcWebServiceMoved="rcWebServiceMoved",l.rcAccessDenied="rcAccessDenied",l.rcLoginUserNameChanged="rcLoginUserNameChanged",l.rcLicenseExpired="rcLicenseExpired",function(e){e.get="get",e.post="post"}(r||(r={}));class c{}c.absence="Absence",c.bonusType="BonusType",c.busyStatus="BusyStatus",c.cartType="CartType",c.companyType="CompanyType",c.contactType="ContactType",c.countryCode="CountryCode",c.currency="Currency",c.customFieldCategory="CustomFieldCategory",c.dayType="DayType",c.documentOfflineState="DocumentOfflineState",c.documentType="DocumentType",c.emailCampaignWorkflowStatus="EmailCampaignWorkflowStatus",c.emailOfflineState="EmailOfflineState",c.emailType="EmailType",c.familyStatus="FamilyStatus",c.firstContact="FirstContact",c.globalSettingsCategory="GlobalSettingsCategory",c.goalType="GoalType",c.groupColor="GroupColor",c.importance="Importance",c.journalType="JournalType",c.knowledgeLevel="KnowledgeLevel",c.knowledgeTitle="KnowledgeTitle",c.knowledgeType="KnowledgeType",c.leadType="LeadType",c.marketingType="MarketingType",c.paymentType="PaymentType",c.prefixType="PrefixType",c.productType="ProductType",c.projectOrigin="ProjectOrigin",c.projectType="ProjectType",c.reportCategory="ReportCategory",c.responseForm="ResponseForm",c.responseType="ResponseType",c.salaryDate="SalaryDate",c.salaryType="SalaryType",c.salePriceType="SalePriceType",c.sentimentTone="SentimentTone",c.suffixType="SuffixType",c.taskImportance="TaskImportance",c.tasksSnoozePeriod="TasksSnoozePeriod",c.taskStatus="TaskStatus",c.taskType="TaskType",c.trainingGrade="TrainingGrade",c.trainingTitle="TrainingTitle",c.translations="Translations",c.units="Units",c.userType="UserType",c.usStatesDistrictsTerritories="USStatesDistrictsTerritories",c.vacationType="VacationType",c.vat="VAT",c.workLoad="WorkLoad",c.workReportType="WorkReportType";class d{}d.isValidFolderName=e=>Object.values(d).includes(e),d.actions="Actions",d.additionalFields="AdditionalFields",d.bonuses="Bonuses",d.calendar="Calendar",d.capacityNotes="CapacityNotes",d.capacityNoteTypes="CapacityNoteTypes",d.carts="Carts",d.columnPermissions="ColumnPermissions",d.companies="Companies",d.contacts="Contacts",d.currencyExchangeRates="CurrencyExchangeRates",d.documents="Documents",d.emails="Emails",d.enumTypes="EnumTypes",d.enumValues="EnumValues",d.enumValuesRelations="EnumValuesRelations",d.features="Features",d.flows="Flows",d.globalSettings="GlobalSettings",d.goals="Goals",d.goods="Goods",d.goodsInCart="GoodsInCart",d.goodsInSet="GoodsInSet",d.groups="Groups",d.history="History",d.holidays="Holidays",d.children="Children",d.individualDiscounts="IndividualDiscounts",d.invoiceItems="InvoiceItems",d.invoices="Invoices",d.itemCopyRelations="ItemCopyRelations",d.journal="Journal",d.knowledge="Knowledge",d.layouts="Layouts",d.layoutsModels="LayoutsModels",d.leads="Leads",d.ledger="Ledger",d.mappings="Mappings",d.marketing="Marketing",d.marketingList="MarketingList",d.marketingListSources="MarketingListSources",d.models="Models",d.modulePermissions="ModulePermissions",d.objectTypesOptions="ObjectTypesOptions",d.payments="Payments",d.priceListGroups="PriceListGroups",d.projectAssignments="ProjectAssignments",d.projectAssignmentsPerUserProject="ProjectAssignmentsPerUserProject",d.projectAssignmentsTotal="ProjectAssignmentsTotal",d.projectAssignmentsTotalUserProject="ProjectAssignmentsTotalUserProject",d.projectList="ProjectList",d.projects="Projects",d.projectUsersInCaPlan="ProjectUsersInCaPlan",d.relationData="RelationData",d.relations="Relations",d.reports="Reports",d.revisionsHistory="RevisionsHistory",d.salaries="Salaries",d.salePrices="SalePrices",d.prices="Prices",d.sqlObjects="SqlObjects",d.tasks="Tasks",d.recurrencePatterns="RecurrencePatterns",d.teamRoles="TeamRoles",d.templates="Templates",d.training="Training",d.unifiedRelations="UnifiedRelations",d.users="Users",d.userSettings="UserSettings",d.vacation="Vacation",d.webAccess2Options="WebAccess2Options",d.webAccessOptions="WebAccessOptions",d.workCommitments="WorkCommitments",d.workflowHistory="WorkflowHistory",d.workReports="WorkReports",d.wrongClientVersions="WrongClientVersions",d.xsltTransformations="XsltTransformations",d.getEnumTypeName=e=>e===d.bonuses?c.bonusType:e===d.carts?c.cartType:e===d.companies?c.companyType:e===d.contacts?c.contactType:e===d.documents?c.documentType:e===d.emails?c.emailType:e===d.goals?c.goalType:e===d.goods?c.productType:e===d.journal?c.journalType:e===d.knowledge?c.knowledgeType:e===d.leads?c.leadType:e===d.marketing?c.marketingType:e===d.projects?c.projectType:e===d.salaries?c.salaryType:e===d.salePrices?c.salePriceType:e===d.tasks?c.taskType:e===d.training?c.trainingTitle:e===d.users?c.userType:e===d.vacation?c.vacationType:e===d.workReports?c.workReportType:null,d.getFolderNameByEnumTypeName=e=>e===c.bonusType?d.bonuses:e===c.cartType?d.carts:e===c.companyType?d.companies:e===c.contactType?d.contacts:e===c.documentType?d.documents:e===c.emailType?d.emails:e===c.goalType?d.goals:e===c.journalType?d.journal:e===c.knowledgeType?d.knowledge:e===c.leadType?d.leads:e===c.marketingType?d.marketing:e===c.productType?d.goods:e===c.projectType?d.projects:e===c.salaryType?d.salaries:e===c.salePriceType?d.salePrices:e===c.taskType?d.tasks:e===c.trainingTitle?d.training:e===c.userType?d.users:e===c.vacationType?d.vacation:e===c.workReportType?d.workReports:null;class u{}u.getAllEmailAttachments="GetAllEmailAttachments",u.getCalendarsByItemGuids="GetCalendarsByItemGuids",u.getEmailAttachment="GetEmailAttachment",u.getItemPreview="GetItemPreview",u.getJournalsByItemGuids="GetJournalsByItemGuids",u.getMarketingCampaignsByItemGuids="GetMarketingCampaignsByItemGuids",u.getMarketingListsRecordsByItemGuids="GetMarketingListsRecordsByItemGuids",u.getRevisionHistoryRecordsByItemGuids="GetRevisionHistoryRecordsByItemGuids",u.getVacationsByItemGuids="GetVacationsByItemGuids",u.getWorkflowHistoryRecordsByItemGuids="GetWorkflowHistoryRecordsByItemGuids",u.getCompanyInformationFromTaxRegister="GetCompanyInformationFromTaxRegister",u.logIn="LogIn",u.logOut="LogOut",u.query="Query",u.queryAmount="QueryAmount",u.getServiceAuthSettings="GetServiceAuthSettings",u.getVersion="GetVersion",u.getBinaryAttachment="GetBinaryAttachment",u.getBinaryAttachmentLatestRevision="GetBinaryAttachmentLatestRevision",u.canUnlinkItems="CanUnlinkItems",u.unlinkItems="UnlinkItems",u.getGetFolderNameByItemGuidsMethodName=e=>{switch(e){case d.calendar:return u.getCalendarsByItemGuids;case d.journal:return u.getJournalsByItemGuids;case d.marketing:return u.getMarketingCampaignsByItemGuids;case d.marketingList:return u.getMarketingListsRecordsByItemGuids;case d.revisionsHistory:return u.getRevisionHistoryRecordsByItemGuids;case d.vacation:return u.getVacationsByItemGuids;case d.workflowHistory:return u.getWorkflowHistoryRecordsByItemGuids;default:return`Get${e}ByItemGuids`}};class m{constructor(e,t,s,n,o,r){if(this.invalidateSessionId=(e,t)=>{t&&t()},this.getSessionId=(e,t)=>{e.callWithoutSession(u.logIn,{userName:this.username,passwordHash:this.passwordHash,appVersion:this.appVersion,clientMachineIdentifier:this.clientMachineIdentifier,clientMachineName:this.clientMachineName,createSessionCookie:e.supportsGetItemPreviewMethod},(e=>{this.lastSuccessfulLoginResponse=e;const s=e.SessionId;if(s)t&&t(s);else{const e=new Error("Successful login but no session came.");if(!this.errorCallback)throw e;this.errorCallback(e)}}),(e=>{const t=new Error("Unable to login. Error response follows.\n"+JSON.stringify(e));if(!this.errorCallback)throw t;this.errorCallback(t)}))},!e||!t)throw new Error("Non of the arguments 'username', 'passwordHash' can be empty.");this.username=e,this.passwordHash=t,this.appVersion=s,this.clientMachineIdentifier=n,this.clientMachineName=o,this.errorCallback=r}}class p{constructor(){this.getSessionId=(e,t)=>{throw new Error("With anonymous session handler, use only connection methods without session.")},this.invalidateSessionId=(e,t)=>{throw new Error("With anonymous session handler, use only connection methods without session.")}}}class h{}h.finishAuthorization=(e,t,s,n,o,r,i)=>{const a=new URLSearchParams;a.append("code_verifier",n),a.append("client_id",t),a.append("client_secret",s),a.append("code",o),a.append("redirect_uri",r),a.append("grant_type","authorization_code"),h.callTokenEndpoint(e,a,i)},h.refreshToken=(e,t,s,n,o)=>{const r=new URLSearchParams;r.append("client_id",t),r.append("client_secret",s),r.append("refresh_token",n),r.append("grant_type","refresh_token"),h.callTokenEndpoint(e,r,o)},h.getWebServiceUrl=e=>{const s=e.split(".");if(2!==s.length)throw new Error("Invalid token supplied");return t.decode(s[1])},h.getUserName=e=>h.decodeAccessToken(e).username,h.decodeAccessToken=e=>s(e),h.callTokenEndpoint=(t,s,n)=>{e.post(t+"/auth/connect/token",s,{headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then((e=>{n(e.data)})).catch((e=>{if(!e.response||400!=e.response.status)throw new Error("Token request failed");n(e.response.data)}))};class y extends Error{constructor(e,t){super(),this.returnCode=e,this.message=t}}class C{constructor(e,t,s,n,o){if(this.invalidateSessionId=(e,t)=>{t&&t()},this.getSessionId=(e,t)=>{const s={userName:this.username,appVersion:this.appVersion,createSessionCookie:e.supportsGetItemPreviewMethod},n={Authorization:"Bearer "+this.accessToken};e.callWithoutSession(u.logIn,s,(e=>{this.lastSuccessfulLoginResponse=e;const s=e.SessionId;if(s)t&&t(s);else{const e=new Error("Successful login but no session came.");if(!this.errorCallback)throw e;this.errorCallback(e)}}),(e=>{const t=new y(e.ReturnCode,"Unable to login. Error response follows.\n"+JSON.stringify(e));if(!this.errorCallback)throw t;this.errorCallback(t)}),n,void 0,(s=>{if(401!==(null==s?void 0:s.statusCode)){if(!this.errorCallback)throw s;this.errorCallback(s)}else this.getNewAccessTokenCallback(e,((s,n)=>{this.accessToken=s,n||this.getSessionId(e,t)}))}))},!e)throw new Error("Non of the arguments 'username', 'clientId', 'clientSecret', 'refreshToken' can be empty.");this.username=e,this.accessToken=t,this.appVersion=s,this.getNewAccessTokenCallback=n,this.errorCallback=o}}class f extends C{constructor(e,t,s,n,o,r,i,a){if(!(e&&n&&t&&s))throw new Error("Non of the arguments 'username', 'clientId', 'clientSecret', 'refreshToken' can be empty.");super(e,o,r,((e,t)=>{h.refreshToken(e.wsUrl,this.clientId,this.clientSecret,this.refreshToken,(e=>{try{this.refreshTokenCallback&&this.refreshTokenCallback(e)}catch(e){this.errorCallback&&this.errorCallback(new Error("Refresh token callback failed.\n"+JSON.stringify(e)))}t(e.access_token,e.error)}))}),i),this.refreshToken=n,this.clientId=t,this.clientSecret=s,this.refreshTokenCallback=a}}class g extends Error{constructor(e,t){super(),this.statusCode=e,this.message=t}}class S{}S.stringifyError=e=>JSON.stringify(e,S.replaceErrors),S.replaceErrors=(e,t)=>{if(t instanceof Error){const e={};return Object.getOwnPropertyNames(t).forEach((s=>{e[s]=t[s]})),e}return t};class E{constructor(s,n,o,i){if(this.createOpenLink=(e,s,n,o)=>{const r=t.encode(this.baseUri);let i="eway://"+s;n&&(i+="/"+(null==n?void 0:n.toLowerCase()));const a=e?"open.eway-crm.dev":"open.eway-crm.com";i=t.encode(i);let l="https://"+a+"/?ws="+r+"&l="+i;return o&&(l+="&n="+encodeURIComponent(o)),l},this.askUploadMethod=(e,t,s,n,o)=>new Promise(((r,i)=>{const a=o?e=>{throw i(e),e}:i;this.callUploadMethod(e,t,s,r,a,a,n)})),this.callUploadMethod=(t,s,n,o,r,i,a)=>{const c=()=>{this.sessionHandler.getSessionId(this,(e=>{this.sessionId=e,this.callUploadMethod(t,s,n,o,r,i,a)}))},d=this.sessionId;if(!d)return void c();const u=`${this.svcUri}/SaveBinaryAttachment?sessionId=${this.sessionId}&itemGuid=${t}&fileName=${encodeURIComponent(s)}`,m=e.post(u,n,a);E.handleCallPromise(m,o,(e=>{if(e.ReturnCode===l.rcBadSession)return this.sessionId=null,void this.sessionHandler.invalidateSessionId(d,c);if(r)r(e);else{const t=new Error("Unhandled connection return code "+e.ReturnCode+": "+e.Description);if(!this.errorCallback)throw t;this.errorCallback(t)}}),(e=>{let t=new Error("Unhandled connection error when calling "+u+": "+S.stringifyError(e));if("statusCode"in e&&413===e.statusCode&&(t=new Error("The file has exceeded the maximum allowed file size for uploading. You can contact your IT administrator or eWay-CRM support if you would like to increase the limit.")),i)i(t);else{if(!this.errorCallback)throw t;this.errorCallback(t)}}))},this.askMethod=(e,t,s,n)=>new Promise(((o,r)=>{const i=n?e=>{throw r(e),e}:r;this.callMethod(e,t,o,i,s,i)})),this.callMethod=(e,t,s,n,o,i)=>{o||(o=r.post);const a=()=>{this.sessionHandler.getSessionId(this,(r=>{this.sessionId=r,this.callMethod(e,t,s,n,o,i)}))},c=this.sessionId;if(!c)return void a();t.sessionId=c;const d=e!==u.logOut?s:e=>{this.sessionId=null,s(e)};this.callWithoutSession(e,t,d,(s=>{if(s.ReturnCode!==l.rcBadSession||(this.sessionId=null,e===u.logOut))if(n)n(s);else{const e=new Error("Unhandled connection return code "+s.ReturnCode+": "+s.Description);if(!this.errorCallback)throw e;this.errorCallback(e,t)}else this.sessionHandler.invalidateSessionId(c,a)}),null,o,i)},this.callWithoutSession=(t,s,n,o,i,a,l)=>{var c;a||(a=r.post);const d=this.svcUri+"/"+t;let m,p;switch(i&&(m={headers:i,withCredentials:null!==(c=this.supportGetItemPreviewMethod)&&void 0!==c?c:t==u.logIn}),a){case r.get:if(s)throw new Error("Calling api get method with data specified does not make any sense.");p=e.get(d,m);break;case r.post:p=e.post(d,s,m);break;default:throw new Error(`Unknown http method '${a}'.`)}E.handleCallPromise(p,n,o,(e=>{if(l)try{l(e)}catch(e){if(!this.errorCallback)throw e;this.errorCallback(e,s)}else{const t=new Error("Unhandled connection error when calling "+d+": "+S.stringifyError(e));if(!this.errorCallback)throw t;this.errorCallback(t,s)}}))},this.getItemPreviewGetMethodUrl=(e,t,s)=>this.svcUri+"/"+u.getItemPreview+"?folderName="+encodeURIComponent(e)+"&itemGuid="+encodeURIComponent(t)+(s||0===s?"&itemVersion="+encodeURIComponent(s.toString()):""),this.getEmailAttachmentGetMethodUrl=(e,t)=>this.svcUri+"/"+u.getEmailAttachment+"?itemGuid="+encodeURIComponent(e)+"&contentId="+encodeURIComponent(t),this.getAllEmailAttachmentsZipGetMethodUrl=e=>this.svcUri+"/"+u.getAllEmailAttachments+"?itemGuid="+encodeURIComponent(e),this.getBinaryAttachmentGetMethodUrl=(e,t)=>"number"==typeof t?this.svcUri+"/"+u.getBinaryAttachment+"?itemGuid="+encodeURIComponent(e)+`&revision=${t}`:this.svcUri+"/"+u.getBinaryAttachmentLatestRevision+"?itemGuid="+encodeURIComponent(e),this.getActiveSessionId=()=>this.sessionId,this.setActiveSessionId=e=>{this.sessionId=e},!s)throw new Error("The argument 'apiServiceUri' cannot be empty.");if(s.length<8||"https://"!==s.substr(0,8).toLowerCase()&&"http://"!==s.substr(0,7).toLowerCase())throw new Error("Api service uri must start either with 'https://' or with 'http://'.");if(".svc"===s.substr(s.length-4).toLowerCase()){this.svcUri=s;const e=["/API.svc","/InsecureAPI.svc","/WcfService/Service.svc"].find((e=>e.toLowerCase()===s.substr(s.length-e.length).toLowerCase()))||"";this.baseUri=s.substr(0,s.length-e.length)}else this.baseUri=E.normalizeWsUrl(s)||s,"https://"===s.substr(0,8).toLowerCase()?this.svcUri=this.baseUri+"/API.svc":this.svcUri=this.baseUri+"/InsecureAPI.svc";this.sessionHandler=n,this.errorCallback=o,this.sessionId=null,this.supportGetItemPreviewMethod=null!=i&&i}get supportsGetItemPreviewMethod(){return this.supportGetItemPreviewMethod}static create(e,t,s,n,o,r,i,a){return new E(e,new m(t,s,n,o,r,i),i,a)}static createAnonymous(e,t){return new E(e,new p,t)}static createUsingOAuth(e,t,s,n,o,r,i,a,l,c){return new E(e,new f(t,s,n,o,r,i,a,l),a,c)}static normalizeWsUrl(e){return e&&e.endsWith("/")&&(e=e.substring(0,e.length-1)),e}get wsUrl(){return this.baseUri}static handleCallPromise(e,t,s,n){e.then((e=>{200===e.status?e.data.ReturnCode===l.rcSuccess?t(e.data):s(e.data):n(new g(e.status,e.statusText))})).catch((e=>{e.response?n(new g(e.response.status,e.response.statusText)):n(e)}))}}class v{constructor(e,t,s,n,o,r,i){this.isEnabled=(e,t)=>{const s=()=>{this.url&&this.token?e(this.url,this.token):t()};this.url&&this.token?e(this.url,this.token):this.obtainToken(s)},this.callTokenizedApi=(e,t,s,n)=>{this.isEnabled(((o,r)=>{t.token=r,v.call(o,e,t,s,(o=>{if(o.ReturnCodeString!==this.invalidTokenReturnCode){if(n)n(o);else if(this.generalErrorCallback){const e=new Error("Unhandled tokenized service connection return code "+o.ReturnCodeString+".\nDescription: "+o.Description);this.generalErrorCallback(e)}}else this.obtainToken((()=>{this.callTokenizedApi(e,t,s,n)}))}),(e=>{if(this.generalErrorCallback){const t=new Error("Unhandled tokenized service connection communication error: "+JSON.stringify(e));this.generalErrorCallback(t)}}))}),(()=>{n&&n(null)}))},this.obtainToken=e=>{if(!this.isActive)return this.url=null,this.token=null,void e();const t=t=>{const s=this.urlAndTokenObtainer(t);s.url&&s.token?(this.url=s.url,this.token=s.token,this.isActive=!0,e()):(this.url=null,this.token=null,this.isActive=!1,e())},s=()=>{this.url=null,this.token=null,this.isActive=!1,e()};this.needsSession?this.connection.callMethod(this.obtainTokenMethodName,{},t,s,this.obtainTokenMethodType):this.connection.callWithoutSession(this.obtainTokenMethodName,null,t,s,null,this.obtainTokenMethodType)},this.obtainTokenMethodName=e,this.obtainTokenMethodType=t,this.needsSession=s,this.invalidTokenReturnCode=n,this.urlAndTokenObtainer=o,this.connection=r,this.generalErrorCallback=i||null,this.url=null,this.token=null,this.isActive=!0}static call(t,s,n,o,r,i){const a=t+"/"+s;e.post(a,n).then((e=>{200===e.status?"Success"===e.data.ReturnCodeString?o(e.data):r(e.data):i(new g(e.status,e.statusText))})).catch((e=>{e.response?i(new g(e.response.status,e.response.statusText)):i(e)}))}}const P=e=>({url:e.ServiceUrl,token:e.Token});class A{constructor(e,t){this.isCommonDataApiEnabled=(e,t)=>{this.tokenizedConnection.isEnabled(e,t)},this.callCommonDataApi=(e,t,s,n)=>{this.tokenizedConnection.callTokenizedApi(e,t,s,n)},this.tokenizedConnection=new v("ObtainCommonDataApiAccessToken",r.get,!1,"InvalidCommonDataToken",P,e,t)}}class k{}k.acceptableBackwardWorkReportDays="AcceptableBackwardWorkReportDays",k.adminAppInactiveLogoutTime="AdminAppInactiveLogoutTime",k.applyGeneralDataProtectionRules="ApplyGeneralDataProtectionRules",k.automaticallyCreateJournalAfterCallDuration="AutomaticallyCreateJournalAfterCallDuration",k.bonusesCompletedState="BonusesCompletedState",k.cartInvoicedState="CartInvoicedState",k.cartOrderCanceledState="CartOrderCanceledState",k.cartOrderInProcessState="CartOrderInProcessState",k.cartOrderProcessedState="CartOrderProcessedState",k.cartPaidState="CartPaidState",k.cartProposalInProcessState="CartProposalInProcessState",k.cartProposalProcessedState="CartProposalProcessedState",k.cartSalesVoucherIssuedState="CartSalesVoucherIssuedState",k.cartToBeInvoicedState="CartToBeInvoicedState",k.cartVoidedState="CartVoidedState",k.clickToCallScheme="ClickToCallScheme",k.companyDuplicityCheckEnabled="CompanyDuplicityCheckEnabled",k.completedStateName="CompletedStateName",k.contactDuplicityCheckEnabled="ContactDuplicityCheckEnabled",k.createCompanyWhileImportingContactFromOutlook="CreateCompanyWhileImportingContactFromOutlook",k.enableContactsTwoWaySyncWithM365="EnableContactsTwoWaySyncWithM365",k.deadStateName="DeadStateName",k.enableCompaniesSyncIntoMobileDeviceContacts="EnableCompaniesSyncIntoMobileDeviceContacts",k.enableContactsSyncIntoMobileDevice="EnableContactsSyncIntoMobileDevice",k.enableLeadsSyncIntoMobileDeviceContacts="EnableLeadsSyncIntoMobileDeviceContacts",k.enableLlamaAiFeatures="EnableLlamaAiFeatures",k.enableUsersSyncIntoMobileDeviceContacts="EnableUsersSyncIntoMobileDeviceContacts",k.emailsActiveProjectsLeadsFilter="EmailsActiveProjectsLeadsFilter",k.exchangeRatesAdminGroupName="ExchangeRatesAdminGroupName",k.forcedEmailTrackingGroups="ForcedEmailTrackingGroups",k.ignoreEmailsFromDomainsOnEmailsTracking="IgnoreEmailsFromDomainsOnEmailsTracking",k.trackEmailsFromDomains="TrackEmailsFromDomains",k.groupsForAllUnpaidInvoicesNotification="GroupsForAllUnpaidInvoicesNotification",k.itemPreviewMaxHeight="ItemPreviewMaxHeight",k.lastActivityAttributes="LastActivityAttributes",k.leadsCompletedState="LeadsCompletedState",k.leadDeadlineAlertGroups="LeadDeadlineAlertGroups",k.leadsDeadState="LeadsDeadState",k.marketingCompletedState="MarketingCompletedState",k.marketingDeadState="MarketingDeadState",k.minimumPasswordLength="MinimumPasswordLength",k.nextStepAttributes="NextStepAttributes",k.notifyAboutInvoicedInvoiceInPohodaGroup="NotifyAboutInvoicedInvoiceInPohodaGroup",k.notifyAboutLeadsDeadline="NotifyAboutLeadsDeadline",k.notifyAboutPaidInvoiceInPohodaGroup="NotifyAboutPaidInvoiceInPohodaGroup",k.notifyAboutProjectDeadline="NotifyAboutProjectDeadline",k.numberOfDecimalPlaces="NumberOfDecimalPlaces",k.phoneListTaskSolverGroup="PhoneListTaskSolverGroup",k.projectDeadlineAlert="ProjectDeadlineAlert",k.serverUpdateProgressNotificationGroup="ServerUpdateProgressNotificationGroup",k.sumarizeCartsPricesOnLeads="SumarizeCartsPricesOnLeads",k.sumarizeCartsPricesOnProjects="SumarizeCartsPricesOnProjects",k.sumarizePeopleExpensesOnProjects="SumarizePeopleExpensesOnProjects",k.systemHealthNotificationGroup="SystemHealthNotificationGroup",k.tasksCompletedState="TasksCompletedState",k.tasksDeferredState="TasksDeferredState",k.tasksInProgressState="TasksInProgressState",k.tasksNotStartedState="TasksNotStartedState",k.tasksWaitOnSomeoneElseState="TasksWaitOnSomeoneElseState",k.trackDocumentVersions="TrackDocumentVersions",k.vacationCompletedState="VacationCompletedState",k.workReportApprovedState="WorkReportApprovedState",k.defaultLanguage="DefaultLanguage",k.defaultCurrency="DefaultCurrency",k.myCompanyCountry="MyCompanyCountry",k.myCompanyName="MyCompanyName",k.myCompanyStreet="MyCompanyStreet",k.myCompanyCity="MyCompanyCity",k.myCompanyState="MyCompanyState",k.myCompanyZip="MyCompanyZIP",k.myCompanyId="MyCompanyID",k.myCompanyVat="MyCompanyVAT";class T{}T.ServerCommon={Server_ID:"Server_ID",Server_ItemCreated:"Server_ItemCreated",Server_ItemChanged:"Server_ItemChanged"},T.Common={CreatedByGUID:"CreatedByGUID",CurrencyEn:"CurrencyEn",DefaultCurrencySuffix:"DefaultCurrency",FileAs:"FileAs",ItemCreated:"ItemCreated",ItemChanged:"ItemChanged",ItemGUID:"ItemGUID",ItemVersion:"ItemVersion",ModifiedByGUID:"ModifiedByGUID",OwnerGUID:"OwnerGUID",ParentCurrencySuffix:"ParentCurrency"},T.Calendar={EndDate:"EndDate",Note:"Note"},T.Carts={SuperiorItem:"SuperiorItem",SuperiorCompany:"SuperiorCompany",SuperiorContact:"SuperiorContact",TypeEn:"TypeEn",StateEn:"StateEn"},T.Companies={ID:"ID",CompanyName:"CompanyName",Department:"Department",AccountNumber:"AccountNumber",IdentificationNumber:"IdentificationNumber",VatNumber:"VatNumber",Sales:"Reversal",EmployeesCount:"EmployeesCount",Purchaser:"Purchaser",Suppliers:"Suppliers",Competitor:"Competitor",Address1Street:"Address1Street",Address1City:"Address1City",Address1PostalCode:"Address1PostalCode",Address1CountryEn:"Address1CountryEn",Address1State:"Address1State",Address1POBox:"Address1POBox",Address2Street:"Address2Street",Address2City:"Address2City",Address2PostalCode:"Address2PostalCode",Address2CountryEn:"Address2CountryEn",Address2State:"Address2State",Address2POBox:"Address2POBox",Address3Street:"Address3Street",Address3City:"Address3City",Address3PostalCode:"Address3PostalCode",Address3CountryEn:"Address3CountryEn",Address3State:"Address3State",Address3POBox:"Address3POBox",InvoiceAddress:"InvoiceAddress",PostalAddress:"PostalAddress",Phone:"Phone",Mobile:"Mobile",Fax:"Fax",WebPage:"WebPage",Email:"Email",ICQ:"ICQ",MSN:"MSN",Skype:"Skype",ImportanceEn:"ImportanceEn",FirstContactEn:"FirstContactEn",LineOfBusiness:"LineOfBusiness",EmailOptOut:"EmailOptOut",MailingListOther:"MailingListOther",MailingListOtherValue:"MailingListOtherValue",Note:"Note",IsPrivate:"IsPrivate",NextStep:"NextStep",LastActivity:"LastActivity",AdditionalDiscount:"AdditionalDiscount"},T.Contacts={ProfilePicture:"ProfilePicture",Title:"Title",Email1Address:"Email1Address",Email2Address:"Email2Address",Email3Address:"Email3Address",DoNotSendNewsletter:"DoNotSendNewsletter",ImportanceEn:"ImportanceEn",PrefixEn:"PrefixEn",FirstName:"FirstName",MiddleName:"MiddleName",LastName:"LastName",SuffixEn:"SuffixEn",BusinessAddressStreet:"BusinessAddressStreet",BusinessAddressCity:"BusinessAddressCity",BusinessAddressPostalCode:"BusinessAddressPostalCode",BusinessAddressCountryEn:"BusinessAddressCountryEn",BusinessAddressState:"BusinessAddressState",BusinessAddressPoBox:"BusinessAddressPOBox",HomeAddressStreet:"HomeAddressStreet",HomeAddressCity:"HomeAddressCity",HomeAddressPostalCode:"HomeAddressPostalCode",HomeAddressCountryEn:"HomeAddressCountryEn",HomeAddressState:"HomeAddressState",HomeAddressPOBox:"HomeAddressPOBox",OtherAddressStreet:"OtherAddressStreet",OtherAddressCity:"OtherAddressCity",OtherAddressPostalCode:"OtherAddressPostalCode",OtherAddressCountryEn:"OtherAddressCountryEn",OtherAddressState:"OtherAddressState",OtherAddressPOBox:"OtherAddressPOBox",BusinessPhoneNumber:"TelephoneNumber1",BusinessPhoneNumber2:"TelephoneNumber5",BusinessFaxNumber:"TelephoneNumber6",MobilePhoneNumber:"TelephoneNumber3",HomePhoneNumber:"TelephoneNumber2",OtherPhoneNumber:"TelephoneNumber4",ICQ:"ICQ",MSN:"MSN",Skype:"Skype",WebPage:"WebPage",Note:"Note",Department:"Department",Company:"Company",IsPrivate:"Private",NextStep:"NextStep",LastActivity:"LastActivity"},T.Leads={ID:"ID",FileAs:"FileAs",HumanID:"HID",Customer:"Customer",ContactPerson:"ContactPerson",Marketing:"Marketing",ReceiveDate:"ReceiveDate",Email:"Email",Phone:"Phone",Street:"Street",State:"State",CountryEn:"CountryEn",City:"City",POBox:"POBox",Zip:"Zip",Price:"Price",PriceChanged:"PriceChanged",CurrencyEn:T.Common.CurrencyEn,EstimatedEnd:"EstimatedEnd",Probability:"Probability",LeadOriginEn:"LeadOriginEn",PriceDefaultCurrency:"PriceDefaultCurrency",EstimatedValue:"EstimatedValue",EstimatedValueDefaultCurrency:"EstimatedValueDefaultCurrency",Note:"Note",TypeEn:"TypeEn",StateEn:"StateEn",PrevStateEn:"PrevStateEn",IsPrivate:"Private",EmailOptOut:"EmailOptOut",NextStep:"NextStep",LastActivity:"LastActivity",ItemVersion:"ItemVersion",EstimatedRevenue:"EstimatedRevenue",EstimatedRevenueDefaultCurrency:"EstimatedRevenueDefaultCurrency",CompletedDate:"CompletedDate",LostDate:"LostDate"},T.Documents={FileAs:"FileAs",DocName:"DocName",Preview:"Preview",PreviewWidth:"PreviewWidth",PreviewHeight:"PreviewHeight",DocTypeEn:"DocTypeEn",StateEn:"StateEn",ImportanceEn:"ImportanceEn",SuperiorItem:"SuperiorItem",SuperiorCompany:"Company",SuperiorContact:"Contact",DocSize:"DocSize",Extension:"Extension",CreationTime:"CreationTime",LastWriteTime:"LastWriteTime",IsPrivate:"Private",Note:"Note"},T.Emails={To:"To",From:"SenderEmailAddress",Cc:"Cc",Subject:"Subject",ImportanceEn:"ImportanceEn",SuperiorItem:"SuperiorItem",SentOn:"SentOn",ReceivedTime:"ReceivedTime",FileSize:"FileSize",AttachmentsCount:"AttachmentsCount",Note:"Note",SentimentTone:"SentimentTone",Summary:"Summary"},T.Goods={Code:"Code",Structure:"Structure",Note:"Note",Description:"Description"},T.Journal={FileAs:"FileAs",Subject:"Subject",TypeEn:"TypeEn",StateEn:"StateEn",ImportanceEn:"ImportanceEn",EventStart:"EventStart",EventEnd:"EventEnd",SuperiorItem:"SuperiorItem",Company:"Company",Contact:"Contact",Marketing:"Marketing",IsSystem:"System",IsPrivate:"Private",Note:"Note",Phone:"Phone"},T.Vacation={StartDate:"StartDate",EndDate:"EndDate",User:"User",Duration:"Duration",Place:"Place",Note:"Note",AllDay:"AllDay",TypeEn:"TypeEn",StateEn:"StateEn",IsPrivate:"Private"},T.Marketing={HumanID:"HumanID",EstimatedStart:"EstimatedStart",EstimatedEnd:"EstimatedEnd",RealStart:"RealStart",RealEnd:"RealEnd",TargetGroup:"TargetGroup",EmailsSent:"EmailsSent",EmailsDelivered:"EmailsDelivered",EmailsViewed:"EmailsViewed",PeopleUnsubscribed:"PeopleUnsubscribed",FinalRevenues:"FinalRevenues",TypeEn:"TypeEn",StateEn:"StateEn"},T.Projects={HumanID:"HID",FileAs:"FileAs",ProjectName:"ProjectName",ProjectOriginEn:"ProjectOriginEn",TypeEn:"TypeEn",StateEn:"StateEn",PaymentTypeEn:"PaymentTypeEn",ProjectStart:"ProjectStart",ProjectRealEnd:"ProjectRealEnd",EstimatedEnd:"ProjectEnd",CurrencyEn:T.Common.CurrencyEn,DefaultCurrencyEn:"DefaultCurrencyEn",EstimatedMargin:"EstimatedMargin",EstimatedPeopleExpenses:"EstimatedPeopleExpenses",EstimatedPeopleExpensesDefaultCurrency:"EstimatedPeopleExpensesDefaultCurrency",EstimatedOtherExpenses:"EstimatedOtherExpenses",EstimatedOtherExpensesDefaultCurrency:"EstimatedOtherExpensesDefaultCurrency",EstimatedPrice:"EstimatedPrice",EstimatedPriceDefaultCurrency:"EstimatedPriceDefaultCurrency",EstimatedProfit:"EstimatedProfit",EstimatedProfitDefaultCurrency:"EstimatedProfitDefaultCurrency",EstimatedPriceChanged:"EstimatedPriceChanged",EstimatedPeopleExpensesChanged:"EstimatedPeopleExpensesChanged",EstimatedOtherExpensesChanged:"EstimatedOtherExpensesChanged",Delay:"Delay",EstimatedWorkHours:"EstimatedWorkHours",TotalWorkHours:"TotalWorkHours",PeopleExpenses:"PeopleExpenses",OtherExpenses:"OtherExpenses",PeopleExpensesDefaultCurrency:"PeopleExpensesDefaultCurrency",OtherExpensesDefaultCurrency:"OtherExpensesDefaultCurrency",PeopleExpensesChanged:"PeopleExpensesChanged",OtherExpensesChanged:"OtherExpensesChanged",Price:"Price",PriceDefaultCurrency:"PriceDefaultCurrency",Profit:"Profit",ProfitDefaultCurrency:"ProfitDefaultCurrency",Margin:"Margin",PriceChanged:"PriceChanged",SuperiorProject:"SuperiorProject",Customer:"Customer",ContactPerson:"ContactPerson",Users:"Users",ProjectManager:"ProjectManager",InvoicePaymentDate:"InvoicePaymentDate",PaymentMaturity:"PaymentMaturity",InvoiceIssueDate:"InvoiceIssueDate",LicensesCount:"LicensesCount",LicensePrice:"LicensePrice",LicensePriceDefaultCurrency:"LicensePriceDefaultCurrency",NextStep:"NextStep",LastActivity:"LastActivity",IsPrivate:"Private",LicensePriceChanged:"LicensePriceChanged",Note:"Note",CompletedDate:"CompletedDate",LostDate:"LostDate"},T.Tasks={FileAs:"FileAs",Subject:"Subject",RootItem:"RootItem",SuperiorItem:"SuperiorItem",Company:"Company",Contact:"Contact",StartDate:"StartDate",DueDate:"DueDate",Reminder:"Reminder",ReminderDate:"ReminderDate",ImportanceEn:"ImportanceEn",IsCompleted:"Complete",PercentComplete:"PercentComplete",PercentCompleteDecimal:"PercentCompleteDecimal",CompletedDate:"CompletedDate",Solver:"Solver",Delegator:"Delegator",Level:"Level",IsPrivate:"Private",ActualWorkHours:"ActualWorkHours",TotalWorkHours:"TotalWorkHours",Body:"Body",TypeEn:"TypeEn",StateEn:"StateEn"},T.Training={TitleEn:"TitleEn"},T.WorkReports={Task:"Task",ProjectName:"ProjectName",UserName:"UserName",Subject:"Subject",Date:"Date",FromTime:"FromTime",ToTime:"ToTime",Overtime:"Overtime",Month:"Month",Year:"Year",IsPrivate:"Private",Note:"Note",Duration:"Duration",WorkReportEn:"WorkReportEn",StateEn:"StateEn"},T.Users={ProfilePicture:"ProfilePicture",UserName:"UserName",JobTitle:"JobTitle",IDCardNumber:"IDCardNumber",Birthdate:"Birthdate",BirthPlace:"BirthPlace",PersonalIdentificationNumber:"PersonalIdentificationNumber",Active:"Active",FamilyStatusEn:"FamilyStatusEn",HomeAddressStreet:"HomeAddressStreet",HomeAddressCity:"HomeAddressCity",HomeAddressPostalCode:"HomeAddressPostalCode",HomeAddressCountryEn:"HomeAddressCountryEn",HomeAddressState:"HomeAddressState",HomeAddressPOBox:"HomeAddressPOBox",BankAccount:"BankAccount",BusinessPhoneNumber:"BusinessPhoneNumber",MobilePhoneNumber:"MobilePhoneNumber",Email1Address:"Email1Address",Email2Address:"Email2Address",ICQ:"ICQ",MSN:"MSN",Skype:"Skype",IdentificationNumber:"IdentificationNumber",HealthInsurance:"HealthInsurance",HolidayLength:"HolidayLength",RemainingDaysOfHoliday:"RemainingDaysOfHoliday",SalaryDateEn:"SalaryDateEn",Supervisor:"Supervisor",TravelDistance:"TravelDistance",TimeAccessibility:"TimeAccessibility",TransportMode:"TransportMode",WorkdayStartTime:"WorkdayStartTime",Note:"Note",IsSystem:"IsSystem"},T.Groups={IsAdmin:"IsAdmin",GroupName:"GroupName",FileAs:"FileAs",Description:"Description",IsPM:"IsPM",System:"System",IsRole:"IsRole",IsCategory:"IsCategory",DisallowControlModulePermissions:"DisallowControlModulePermissions",DisallowControlColumnPermissions:"DisallowControlColumnPermissions",IsOutlookCategory:"IsOutlookCategory",DisallowControlUserAssignment:"DisallowControlUserAssignment",ColorEn:"ColorEn",Picture:"Picture"},T.allTypeEnNames=["TypeEn",T.Documents.DocTypeEn,T.WorkReports.WorkReportEn,"TitleEn"],T.getFolderFileAs=e=>{switch(e){case d.leads:return T.Leads.FileAs;case d.projects:return T.Projects.ProjectName;case d.documents:return T.Documents.DocName;case d.companies:return T.Companies.CompanyName;case d.contacts:case d.users:return T.Common.FileAs;case d.emails:return T.Emails.Subject;case d.journal:return T.Journal.FileAs;case d.tasks:return T.Tasks.Subject;case d.workReports:return T.WorkReports.Subject;case d.vacation:return T.Vacation.TypeEn;case d.carts:case d.goods:return T.Common.FileAs;case d.groups:return T.Groups.GroupName;default:return console.warn(`FileAs col name not defined for folderName ${e}`),T.Common.FileAs}};class I{}I.general="GENERAL",I.group="GROUP",I.contactPerson="CONTACTPERSON",I.contact="CONTACT",I.customer="CUSTOMER",I.company="COMPANY",I.outlookProject="OUTLOOKPROJECT",I.supervisor="SUPERVISOR";class b{}b.all="All",b.own="Own",b.readonly="Readonly",b.invisible="Invisible",b.none="None";class w{}var D,N,O,R;w.mandatory="Mandatory",w.optional="Optional",w.unique="Unique",w.none="None",function(e){e.Free="Free",e.Basic="Basic",e.Professional="Professional",e.Enterprise="Enterprise"}(D||(D={})),function(e){e.ContactsAndCompanies="ContactsAndCompanies",e.Sales="Sales",e.Projects="Projects",e.Marketing="Marketing"}(N||(N={})),function(e){e[e.Negative=0]="Negative",e[e.Neutral=1]="Neutral",e[e.Positive=2]="Positive"}(O||(O={}));class M{}M.contactsSynchronizationWithOutlook="ContactsSynchronizationWithOutlook",M.wordAddin="WordAddin",M.excelAddin="ExcelAddin",M.tasksRecurrentTasks="TasksRecurrentTasks",M.tasksSubtasks="TasksSubtasks",M.tasksSynchronizationWithOutlook="TasksSynchronizationWithOutlook",M.calendarSynchronizationWithOutlook="CalendarSynchronizationWithOutlook",M.emailsAutomaticTracking="EmailsAutomaticTracking",M.convertEmailToProject="ConvertEmailToProject",M.duplicityChecker="DuplicityChecker",M.nextStepAndLastActivityCustomization="NextStepAndLastActivityCustomization",M.subProjects="SubProjects",M.resourceAndPlanning="ResourceAndPlanning",M.professionalEmailCampaigns="ProfessionalEmailCampaigns",M.professionalEmailCampaignsAdvancedStatistics="ProfessionalEmailCampaignsAdvancedStatistics",M.wordEmailMerge="WordEmailMerge",M.printLabels="PrintLabels",M.printEnvelopes="PrintEnvelopes",M.userViews="UserViews",M.sharedUserViews="SharedUserViews",M.gridConditionalFormating="GridConditionalFormating",M.multipleCurrencies="MultipleCurrencies",M.historyTracking="HistoryTracking",M.privateItems="PrivateItems",M.itemTypes="ItemTypes",M.formLayoutCustomization="FormLayoutCustomization",M.workflowBasicDefinitions="WorkflowBasicDefinitions",M.workflowAdvancedDefinitions="WorkflowAdvancedDefinitions",M.workflowAdvancedDefinitionsRules="WorkflowAdvancedDefinitionsRules",M.workflowAdvancedDefinitionsActions="WorkflowAdvancedDefinitionsActions",M.workflowGroupLevelActions="WorkflowGroupLevelActions",M.customFields="CustomFields",M.importantFields="ImportantFields",M.mandatoryFields="MandatoryFields",M.uniqueFields="UniqueFields",M.readOnlyFields="ReadOnlyFields",M.transformationCustomTemplates="TransformationCustomTemplates",M.userRoles="UserRoles",M.modulePermissions="ModulePermissions",M.columnPermissions="ColumnPermissions",M.api="API",M.gate="Gate",M.threeCXIntegration="ThreeCXIntegration",M.tapiIntegration="TapiIntegration",M.pohodaIntegration="PohodaIntegration",M.pohodaSynchronizationIntervalCustomization="PohodaSynchronizationIntervalCustomization",M.pohodaSynchronizationFieldMappingCustomization="PohodaSynchronizationFieldMappingCustomization",M.quickBooksIntegration="QuickBooksIntegration",M.saveBinaryDataOnDisk="SaveBinaryDataOnDisk",M.activeDirectoryLogin="ActiveDirectoryLogin",M.callerIdentificationOnApple="CallerIdentificationOnApple",M.legacyAdministration="LegacyAdministration";class L{}L.customAdditionalFieldsCount="CustomAdditionalFieldsCount",L.customEnabledAdvancedWorkflowsCount="CustomEnabledAdvancedWorkflowsCount",L.customEnabledBasicWorkflowsCount="CustomEnabledBasicWorkflowsCount",L.customMandatoryFieldsCount="CustomMandatoryFieldsCount",L.customOptionalFieldsCount="CustomOptionalFieldsCount",L.customReadonlyFieldsCount="CustomReadonlyFieldsCount",L.customUniqueFieldsCount="CustomUniqueFieldsCount",L.customVisibleTypesCount="CustomVisibleTypesCount",L.visibleCurrenciesCount="VisibleCurrenciesCount";class x{}x.contactsAutomaticSynchronizationWithOutlook="ContactsAutomaticSynchronizationWithOutlook",x.contactsSynchronizationWithOutlook="ContactsSynchronizationWithOutlook",x.contactsSynchronizationWithAndroid="ContactsSynchronizationWithAndroid",x.documentsRevisions="DocumentsRevisions",x.wordAddin="WordAddin",x.excelAddin="ExcelAddin",x.tasksReminders="TasksReminders",x.tasksRecurrentTasks="TasksRecurrentTasks",x.tasksSubtasks="TasksSubtasks",x.tasksSynchronizationWithOutlook="TasksSynchronizationWithOutlook",x.calendarSynchronizationWithOutlook="CalendarSynchronizationWithOutlook",x.emailsManualTracking="EmailsManualTracking",x.emailsAutomaticTracking="EmailsAutomaticTracking",x.emailSummaryAndSentimentToneFromAi="EmailSummaryAndSentimentToneFromAi",x.convertEmailToContact="ConvertEmailToContact",x.convertEmailToContactInBulk="ConvertEmailToContactInBulk",x.convertEmailToDeal="ConvertEmailToDeal",x.convertEmailToProject="ConvertEmailToProject",x.convertEmailToTask="ConvertEmailToTask",x.gravatarIntegration="GravatarIntegration",x.logoboxIntegration="LogoboxIntegration",x.companiesBussinesRegisterApiIntegration="CompaniesBussinesRegisterApiIntegration",x.duplicityChecker="DuplicityChecker",x.nextStepAndLastActivityCustomization="NextStepAndLastActivityCustomization",x.subProjects="SubProjects",x.resourceAndPlanning="ResourceAndPlanning",x.professionalEmailCampaigns="ProfessionalEmailCampaigns",x.professionalEmailCampaignsAdvancedStatistics="ProfessionalEmailCampaignsAdvancedStatistics",x.wordEmailMerge="WordEmailMerge",x.printLabels="PrintLabels",x.printEnvelopes="PrintEnvelopes",x.userViews="UserViews",x.sharedUserViews="SharedUserViews",x.gridRowSummary="GridRowSummary",x.gridConditionalFormating="GridConditionalFormating",x.multipleCurrencies="MultipleCurrencies",x.historyTracking="HistoryTracking",x.privateItems="PrivateItems",x.itemTypes="ItemTypes",x.formLayoutCustomization="FormLayoutCustomization",x.workflowBasicDefinitions="WorkflowBasicDefinitions",x.workflowAdvancedDefinitions="WorkflowAdvancedDefinitions",x.workflowAdvancedDefinitionsRules="WorkflowAdvancedDefinitionsRules",x.workflowAdvancedDefinitionsActions="WorkflowAdvancedDefinitionsActions",x.workflowGroupLevelActions="WorkflowGroupLevelActions",x.customFields="CustomFields",x.importantFields="ImportantFields",x.mandatoryFields="MandatoryFields",x.uniqueFields="UniqueFields",x.readOnlyFields="ReadOnlyFields",x.transformationCustomTemplates="TransformationCustomTemplates",x.userRoles="UserRoles",x.modulePermissions="ModulePermissions",x.columnPermissions="ColumnPermissions",x.commonDataAPI="CommonDataAPI",x.eWayCrmAPI="eWayCrmAPI",x.threeCXIntegration="ThreeCXIntegration",x.tapiIntegration="TapiIntegration",x.pohodaIntegration="PohodaIntegration",x.pohodaSynchronizationIntervalCustomization="PohodaSynchronizationIntervalCustomization",x.pohodaSynchronizationFieldMappingCustomization="PohodaSynchronizationFieldMappingCustomization",x.quickBooksIntegration="QuickBooksIntegration",x.shareByTeams="ShareByTeams",x.convertEmailToContactWithDataFromAi="ConvertEmailToContactWithDataFromAi",x.convertEmailToDealWithDataFromAi="ConvertEmailToDealWithDataFromAi",x.convertEmailToProjectWithDataFromAi="ConvertEmailToProjectWithDataFromAi",function(e){e.UnpaidImportantInvoices="UnpaidImportantInvoices",e.UncollectableSubscriptionPayment="UncollectableSubscriptionPayment",e.UncollectableSubscriptionPaymentWithExpiredCard="UncollectableSubscriptionPaymentWithExpiredCard",e.StandardSubscriptionPeriod="StandardSubscriptionPeriod"}(R||(R={}));var B,F=R;!function(e){e.License="License",e.CloudLicense="CloudLicense",e.MiscLicense="MiscLicense",e.Support="Support",e.Service="Service"}(B||(B={}));var U=B;class G{}G.getIsDebug=e=>{var t;return!!(null===(t=null==e?void 0:e.sessionHandler.lastSuccessfulLoginResponse)||void 0===t?void 0:t.Debug)},G.supportsFeaturesOf=(e,t)=>{var s;const o=null===(s=e.sessionHandler.lastSuccessfulLoginResponse)||void 0===s?void 0:s.WcfVersion;return!!o&&(n(o,t,">=")||n(o,"1.0.0.0","="))};class W{}W.textBox="TextBox",W.comboBox="ComboBox",W.numericBox="NumericBox",W.relation="Relation",W.checkBox="CheckBox",W.linkTextBox="LinkTextBox",W.dateEdit="DateEdit",W.memoBox="MemoBox",W.multiSelectComboBox="MultiSelectComboBox",W.workflowState="WorkflowState",W.image="Image",W.multiSelectRelation="MultiSelectRelation";const j={[d.relations]:0,[d.unifiedRelations]:1,[d.users]:2,[d.groups]:3,[d.enumTypes]:4,[d.enumValues]:5,[d.additionalFields]:6};class _{static createHubItemsCountsQuery(e,t,s){return{__type:"HubItemsCountsQuery:#EQ",ParentItemGuids:e,ItemTypes:t,ExcludeSystemItems:s}}}class H{constructor(e,t){if(!e||!t)throw new Error("Both folderName and baseItem has to be defined!");this.folderName=e,this.baseItem=t}getEmailAddress(){switch(this.folderName){case d.contacts:{const e=this.baseItem;return e.Email1Address||e.Email2Address||e.Email3Address}case d.leads:return this.baseItem.Email;case d.companies:return this.baseItem.Email;case d.users:{const e=this.baseItem;return e.Email1Address||e.Email2Address}default:return null}}getInitials(){switch(this.folderName){case d.contacts:{const e=this.baseItem;return this.getInitialsInternal(e.FirstName,e.LastName)}case d.users:{const e=this.baseItem;return this.getInitialsInternal(e.FirstName,e.LastName)}default:return null}}getInitialsInternal(e,t){const s=((null==e?void 0:e.substr(0,1))||"")+((null==t?void 0:t.substr(0,1))||"");return""==s?null:s}getItemPreview(){switch(this.folderName){case d.contacts:{const e=this.baseItem;return e.ProfilePicture?{imageData:e.ProfilePicture,width:e.ProfilePictureWidth||0,height:e.ProfilePictureHeight||0}:null}case d.users:{const e=this.baseItem;return e.ProfilePicture?{imageData:e.ProfilePicture,width:e.ProfilePictureWidth||0,height:e.ProfilePictureHeight||0}:null}default:return null}}}var z;!function(e){e.Readonly="Readonly",e.VisibleRankDefaultOnly="VisibleRankDefaultOnly",e.Editable="Editable"}(z||(z={})),a.polyfill();export{E as ApiConnectionAsNonDefaultExport,u as ApiMethods,w as ColumnPermissionMandatoryRules,b as ColumnPermissionPermissionRules,A as CommonDataConnection,L as CustomizationStatsItemKeys,H as EWItem,D as Edition,z as EnumTypeEditMode,c as EnumTypes,S as ErrorHelper,F as ExpirationReason,N as Feature,T as FieldNames,W as FieldTypes,d as FolderNames,M as Functionality,k as GlobalSettingsNames,r as HttpMethod,g as HttpRequestError,U as LicenseKeyInvoiceSeverity,x as LicenseRestrictionKeys,h as OAuthHelper,C as OAuthSessionHandlerBase,j as ObjectTypeIds,_ as QueryHelper,I as RelationTypes,l as ReturnCodes,O as SentimentTone,v as TokenizedServiceConnection,G as VersionHelperBase,E as default};
8
+ */class l{}l.rcSuccess="rcSuccess",l.rcBadSession="rcBadSession",l.rcDuplicateContact="rcDuplicateContact",l.rcWebServiceMoved="rcWebServiceMoved",l.rcAccessDenied="rcAccessDenied",l.rcLoginUserNameChanged="rcLoginUserNameChanged",l.rcLicenseExpired="rcLicenseExpired",function(e){e.get="get",e.post="post"}(r||(r={}));class c{}c.absence="Absence",c.bonusType="BonusType",c.busyStatus="BusyStatus",c.cartType="CartType",c.companyType="CompanyType",c.contactType="ContactType",c.countryCode="CountryCode",c.currency="Currency",c.customFieldCategory="CustomFieldCategory",c.dayType="DayType",c.documentOfflineState="DocumentOfflineState",c.documentType="DocumentType",c.emailCampaignWorkflowStatus="EmailCampaignWorkflowStatus",c.emailOfflineState="EmailOfflineState",c.emailType="EmailType",c.familyStatus="FamilyStatus",c.firstContact="FirstContact",c.globalSettingsCategory="GlobalSettingsCategory",c.goalType="GoalType",c.groupColor="GroupColor",c.importance="Importance",c.journalType="JournalType",c.knowledgeLevel="KnowledgeLevel",c.knowledgeTitle="KnowledgeTitle",c.knowledgeType="KnowledgeType",c.leadType="LeadType",c.marketingType="MarketingType",c.paymentType="PaymentType",c.prefixType="PrefixType",c.productType="ProductType",c.projectOrigin="ProjectOrigin",c.projectType="ProjectType",c.reportCategory="ReportCategory",c.responseForm="ResponseForm",c.responseType="ResponseType",c.salaryDate="SalaryDate",c.salaryType="SalaryType",c.salePriceType="SalePriceType",c.sentimentTone="SentimentTone",c.suffixType="SuffixType",c.taskImportance="TaskImportance",c.tasksSnoozePeriod="TasksSnoozePeriod",c.taskStatus="TaskStatus",c.taskType="TaskType",c.trainingGrade="TrainingGrade",c.trainingTitle="TrainingTitle",c.translations="Translations",c.units="Units",c.userType="UserType",c.usStatesDistrictsTerritories="USStatesDistrictsTerritories",c.vacationType="VacationType",c.vat="VAT",c.workLoad="WorkLoad",c.workReportType="WorkReportType";class d{}d.isValidFolderName=e=>Object.values(d).includes(e),d.actions="Actions",d.additionalFields="AdditionalFields",d.bonuses="Bonuses",d.calendar="Calendar",d.capacityNotes="CapacityNotes",d.capacityNoteTypes="CapacityNoteTypes",d.carts="Carts",d.columnPermissions="ColumnPermissions",d.companies="Companies",d.contacts="Contacts",d.currencyExchangeRates="CurrencyExchangeRates",d.documents="Documents",d.emails="Emails",d.enumTypes="EnumTypes",d.enumValues="EnumValues",d.enumValuesRelations="EnumValuesRelations",d.features="Features",d.flows="Flows",d.globalSettings="GlobalSettings",d.goals="Goals",d.goods="Goods",d.goodsInCart="GoodsInCart",d.goodsInSet="GoodsInSet",d.groups="Groups",d.history="History",d.holidays="Holidays",d.children="Children",d.individualDiscounts="IndividualDiscounts",d.invoiceItems="InvoiceItems",d.invoices="Invoices",d.itemCopyRelations="ItemCopyRelations",d.journal="Journal",d.knowledge="Knowledge",d.layouts="Layouts",d.layoutsModels="LayoutsModels",d.leads="Leads",d.ledger="Ledger",d.mappings="Mappings",d.marketing="Marketing",d.marketingList="MarketingList",d.marketingListSources="MarketingListSources",d.models="Models",d.modulePermissions="ModulePermissions",d.objectTypesOptions="ObjectTypesOptions",d.payments="Payments",d.priceListGroups="PriceListGroups",d.projectAssignments="ProjectAssignments",d.projectAssignmentsPerUserProject="ProjectAssignmentsPerUserProject",d.projectAssignmentsTotal="ProjectAssignmentsTotal",d.projectAssignmentsTotalUserProject="ProjectAssignmentsTotalUserProject",d.projectList="ProjectList",d.projects="Projects",d.projectUsersInCaPlan="ProjectUsersInCaPlan",d.relationData="RelationData",d.relations="Relations",d.reports="Reports",d.revisionsHistory="RevisionsHistory",d.salaries="Salaries",d.salePrices="SalePrices",d.prices="Prices",d.sqlObjects="SqlObjects",d.tasks="Tasks",d.recurrencePatterns="RecurrencePatterns",d.teamRoles="TeamRoles",d.templates="Templates",d.training="Training",d.unifiedRelations="UnifiedRelations",d.users="Users",d.userSettings="UserSettings",d.vacation="Vacation",d.webAccess2Options="WebAccess2Options",d.webAccessOptions="WebAccessOptions",d.workCommitments="WorkCommitments",d.workflowHistory="WorkflowHistory",d.workReports="WorkReports",d.wrongClientVersions="WrongClientVersions",d.xsltTransformations="XsltTransformations",d.getEnumTypeName=e=>e===d.bonuses?c.bonusType:e===d.carts?c.cartType:e===d.companies?c.companyType:e===d.contacts?c.contactType:e===d.documents?c.documentType:e===d.emails?c.emailType:e===d.goals?c.goalType:e===d.goods?c.productType:e===d.journal?c.journalType:e===d.knowledge?c.knowledgeType:e===d.leads?c.leadType:e===d.marketing?c.marketingType:e===d.projects?c.projectType:e===d.salaries?c.salaryType:e===d.salePrices?c.salePriceType:e===d.tasks?c.taskType:e===d.training?c.trainingTitle:e===d.users?c.userType:e===d.vacation?c.vacationType:e===d.workReports?c.workReportType:null,d.getFolderNameByEnumTypeName=e=>e===c.bonusType?d.bonuses:e===c.cartType?d.carts:e===c.companyType?d.companies:e===c.contactType?d.contacts:e===c.documentType?d.documents:e===c.emailType?d.emails:e===c.goalType?d.goals:e===c.journalType?d.journal:e===c.knowledgeType?d.knowledge:e===c.leadType?d.leads:e===c.marketingType?d.marketing:e===c.productType?d.goods:e===c.projectType?d.projects:e===c.salaryType?d.salaries:e===c.salePriceType?d.salePrices:e===c.taskType?d.tasks:e===c.trainingTitle?d.training:e===c.userType?d.users:e===c.vacationType?d.vacation:e===c.workReportType?d.workReports:null;class u{}u.getAllEmailAttachments="GetAllEmailAttachments",u.getCalendarsByItemGuids="GetCalendarsByItemGuids",u.getEmailAttachment="GetEmailAttachment",u.getItemPreview="GetItemPreview",u.getJournalsByItemGuids="GetJournalsByItemGuids",u.getMarketingCampaignsByItemGuids="GetMarketingCampaignsByItemGuids",u.getMarketingListsRecordsByItemGuids="GetMarketingListsRecordsByItemGuids",u.getRevisionHistoryRecordsByItemGuids="GetRevisionHistoryRecordsByItemGuids",u.getVacationsByItemGuids="GetVacationsByItemGuids",u.getWorkflowHistoryRecordsByItemGuids="GetWorkflowHistoryRecordsByItemGuids",u.getCompanyInformationFromTaxRegister="GetCompanyInformationFromTaxRegister",u.logIn="LogIn",u.logOut="LogOut",u.query="Query",u.queryAmount="QueryAmount",u.getServiceAuthSettings="GetServiceAuthSettings",u.getVersion="GetVersion",u.getBinaryAttachment="GetBinaryAttachment",u.getBinaryAttachmentLatestRevision="GetBinaryAttachmentLatestRevision",u.canUnlinkItems="CanUnlinkItems",u.unlinkItems="UnlinkItems",u.getFolderNameForApiMethod=e=>{switch(e){case d.calendar:return"Calendars";case d.journal:return"Journals";case d.marketing:return"MarketingCampaigns";case d.marketingList:return"MarketingListsRecords";case d.revisionsHistory:return"RevisionHistoryRecords";case d.vacation:return"Vacations";case d.workflowHistory:return"WorkflowHistoryRecords";default:return e}},u.getGetFolderNameByItemGuidsMethodName=e=>`Get${u.getFolderNameForApiMethod(e)}ByItemGuids`,u.getGetFolderNameMethodName=e=>`Get${u.getFolderNameForApiMethod(e)}`,u.getSearchFolderNameMethodName=e=>`Search${e}`;class m{constructor(e,t,s,o,n,r){if(this.invalidateSessionId=(e,t)=>{t&&t()},this.getSessionId=(e,t)=>{e.callWithoutSession(u.logIn,{userName:this.username,passwordHash:this.passwordHash,appVersion:this.appVersion,clientMachineIdentifier:this.clientMachineIdentifier,clientMachineName:this.clientMachineName,createSessionCookie:e.supportsGetItemPreviewMethod},(e=>{this.lastSuccessfulLoginResponse=e;const s=e.SessionId;if(s)t&&t(s);else{const e=new Error("Successful login but no session came.");if(!this.errorCallback)throw e;this.errorCallback(e)}}),(e=>{const t=new Error("Unable to login. Error response follows.\n"+JSON.stringify(e));if(!this.errorCallback)throw t;this.errorCallback(t)}))},!e||!t)throw new Error("Non of the arguments 'username', 'passwordHash' can be empty.");this.username=e,this.passwordHash=t,this.appVersion=s,this.clientMachineIdentifier=o,this.clientMachineName=n,this.errorCallback=r}}class p{constructor(){this.getSessionId=(e,t)=>{throw new Error("With anonymous session handler, use only connection methods without session.")},this.invalidateSessionId=(e,t)=>{throw new Error("With anonymous session handler, use only connection methods without session.")}}}class h{static createAuthorizeUrl(e,t,s,o,n,r,i=!1){if(n&&!r||!n&&r)throw new Error("If codeChallenge is defined, codeChallengeMethod must also be defined and vice versa");let a=`https://login.eway-crm.${i?"dev":"com"}?scope=${encodeURIComponent(t.join(" "))}prompt=login&response_type=code&redirect_uri=${encodeURIComponent(s)}&client_id=${e}`;return o&&(a+=`&state=${encodeURIComponent(o)}`),n&&r&&(a+=`&code_challenge=${encodeURIComponent(n)}&code_challenge_method=${encodeURIComponent(r)}`),a}}h.finishAuthorization=(e,t,s,o,n,r,i)=>{const a=new URLSearchParams;a.append("code_verifier",o),a.append("client_id",t),a.append("client_secret",s),a.append("code",n),a.append("redirect_uri",r),a.append("grant_type","authorization_code"),h.callTokenEndpoint(e,a,i)},h.refreshToken=(e,t,s,o,n)=>{const r=new URLSearchParams;r.append("client_id",t),r.append("client_secret",s),r.append("refresh_token",o),r.append("grant_type","refresh_token"),h.callTokenEndpoint(e,r,n)},h.getWebServiceUrl=e=>{const s=e.split(".");if(2!==s.length)throw new Error("Invalid token supplied");return t.decode(s[1])},h.getUserName=e=>h.decodeAccessToken(e).username,h.decodeAccessToken=e=>s(e),h.callTokenEndpoint=(t,s,o)=>{e.post(t+"/auth/connect/token",s,{headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then((e=>{o(e.data)})).catch((e=>{if(!e.response||400!=e.response.status)throw new Error("Token request failed");o(e.response.data)}))};class y extends Error{constructor(e,t){super(),this.returnCode=e,this.message=t}}class C{constructor(e,t,s,o,n){if(this.invalidateSessionId=(e,t)=>{t&&t()},this.getSessionId=(e,t)=>{const s={userName:this.username,appVersion:this.appVersion,createSessionCookie:e.supportsGetItemPreviewMethod},o={Authorization:"Bearer "+this.accessToken};e.callWithoutSession(u.logIn,s,(e=>{this.lastSuccessfulLoginResponse=e;const s=e.SessionId;if(s)t&&t(s);else{const e=new Error("Successful login but no session came.");if(!this.errorCallback)throw e;this.errorCallback(e)}}),(e=>{const t=new y(e.ReturnCode,"Unable to login. Error response follows.\n"+JSON.stringify(e));if(!this.errorCallback)throw t;this.errorCallback(t)}),o,void 0,(s=>{if(401!==(null==s?void 0:s.statusCode)){if(!this.errorCallback)throw s;this.errorCallback(s)}else this.getNewAccessTokenCallback(e,((s,o)=>{this.accessToken=s,o||this.getSessionId(e,t)}))}))},!e)throw new Error("Non of the arguments 'username', 'clientId', 'clientSecret', 'refreshToken' can be empty.");this.username=e,this.accessToken=t,this.appVersion=s,this.getNewAccessTokenCallback=o,this.errorCallback=n}}class f extends C{constructor(e,t,s,o,n,r,i,a){if(!(e&&o&&t&&s))throw new Error("Non of the arguments 'username', 'clientId', 'clientSecret', 'refreshToken' can be empty.");super(e,n,r,((e,t)=>{h.refreshToken(e.wsUrl,this.clientId,this.clientSecret,this.refreshToken,(e=>{try{this.refreshTokenCallback&&this.refreshTokenCallback(e)}catch(e){this.errorCallback&&this.errorCallback(new Error("Refresh token callback failed.\n"+JSON.stringify(e)))}t(e.access_token,e.error)}))}),i),this.refreshToken=o,this.clientId=t,this.clientSecret=s,this.refreshTokenCallback=a}}class g extends Error{constructor(e,t){super(),this.statusCode=e,this.message=t}}class S{}S.stringifyError=e=>JSON.stringify(e,S.replaceErrors),S.replaceErrors=(e,t)=>{if(t instanceof Error){const e={};return Object.getOwnPropertyNames(t).forEach((s=>{e[s]=t[s]})),e}return t};class v{constructor(s,o,n,i){if(this.createOpenLink=(e,s,o,n)=>{const r=t.encode(this.baseUri);let i="eway://"+s;o&&(i+="/"+(null==o?void 0:o.toLowerCase()));const a=e?"open.eway-crm.dev":"open.eway-crm.com";i=t.encode(i);let l="https://"+a+"/?ws="+r+"&l="+i;return n&&(l+="&n="+encodeURIComponent(n)),l},this.askUploadMethod=(e,t,s,o,n)=>new Promise(((r,i)=>{const a=n?e=>{throw i(e),e}:i;this.callUploadMethod(e,t,s,r,a,a,o)})),this.callUploadMethod=(t,s,o,n,r,i,a)=>{const c=()=>{this.sessionHandler.getSessionId(this,(e=>{this.sessionId=e,this.callUploadMethod(t,s,o,n,r,i,a)}))},d=this.sessionId;if(!d)return void c();const u=`${this.svcUri}/SaveBinaryAttachment?sessionId=${this.sessionId}&itemGuid=${t}&fileName=${encodeURIComponent(s)}`,m=e.post(u,o,a);v.handleCallPromise(m,n,(e=>{if(e.ReturnCode===l.rcBadSession)return this.sessionId=null,void this.sessionHandler.invalidateSessionId(d,c);if(r)r(e);else{const t=new Error("Unhandled connection return code "+e.ReturnCode+": "+e.Description);if(!this.errorCallback)throw t;this.errorCallback(t)}}),(e=>{let t=new Error("Unhandled connection error when calling "+u+": "+S.stringifyError(e));if("statusCode"in e&&413===e.statusCode&&(t=new Error("The file has exceeded the maximum allowed file size for uploading. You can contact your IT administrator or eWay-CRM support if you would like to increase the limit.")),i)i(t);else{if(!this.errorCallback)throw t;this.errorCallback(t)}}))},this.askMethod=(e,t,s,o)=>new Promise(((n,r)=>{const i=o?e=>{throw r(e),e}:r;this.callMethod(e,t,n,i,s,i)})),this.callMethod=(e,t,s,o,n,i)=>{n||(n=r.post);const a=()=>{this.sessionHandler.getSessionId(this,(r=>{this.sessionId=r,this.callMethod(e,t,s,o,n,i)}))},c=this.sessionId;if(!c)return void a();t.sessionId=c;const d=e!==u.logOut?s:e=>{this.sessionId=null,s(e)};this.callWithoutSession(e,t,d,(s=>{if(s.ReturnCode!==l.rcBadSession||(this.sessionId=null,e===u.logOut))if(o)o(s);else{const e=new Error("Unhandled connection return code "+s.ReturnCode+": "+s.Description);if(!this.errorCallback)throw e;this.errorCallback(e,t)}else this.sessionHandler.invalidateSessionId(c,a)}),null,n,i)},this.callWithoutSession=(t,s,o,n,i,a,l)=>{var c;a||(a=r.post);const d=this.svcUri+"/"+t;let m,p;switch(i&&(m={headers:i,withCredentials:null!==(c=this.supportGetItemPreviewMethod)&&void 0!==c?c:t==u.logIn}),a){case r.get:if(s)throw new Error("Calling api get method with data specified does not make any sense.");p=e.get(d,m);break;case r.post:p=e.post(d,s,m);break;default:throw new Error(`Unknown http method '${a}'.`)}v.handleCallPromise(p,o,n,(e=>{if(l)try{l(e)}catch(e){if(!this.errorCallback)throw e;this.errorCallback(e,s)}else{const t=new Error("Unhandled connection error when calling "+d+": "+S.stringifyError(e));if(!this.errorCallback)throw t;this.errorCallback(t,s)}}))},this.getItemPreviewGetMethodUrl=(e,t,s)=>this.svcUri+"/"+u.getItemPreview+"?folderName="+encodeURIComponent(e)+"&itemGuid="+encodeURIComponent(t)+(s||0===s?"&itemVersion="+encodeURIComponent(s.toString()):""),this.getEmailAttachmentGetMethodUrl=(e,t)=>this.svcUri+"/"+u.getEmailAttachment+"?itemGuid="+encodeURIComponent(e)+"&contentId="+encodeURIComponent(t),this.getAllEmailAttachmentsZipGetMethodUrl=e=>this.svcUri+"/"+u.getAllEmailAttachments+"?itemGuid="+encodeURIComponent(e),this.getBinaryAttachmentGetMethodUrl=(e,t)=>"number"==typeof t?this.svcUri+"/"+u.getBinaryAttachment+"?itemGuid="+encodeURIComponent(e)+`&revision=${t}`:this.svcUri+"/"+u.getBinaryAttachmentLatestRevision+"?itemGuid="+encodeURIComponent(e),this.getActiveSessionId=()=>this.sessionId,this.setActiveSessionId=e=>{this.sessionId=e},!s)throw new Error("The argument 'apiServiceUri' cannot be empty.");if(s.length<8||"https://"!==s.substr(0,8).toLowerCase()&&"http://"!==s.substr(0,7).toLowerCase())throw new Error("Api service uri must start either with 'https://' or with 'http://'.");if(".svc"===s.substr(s.length-4).toLowerCase()){this.svcUri=s;const e=["/API.svc","/InsecureAPI.svc","/WcfService/Service.svc"].find((e=>e.toLowerCase()===s.substr(s.length-e.length).toLowerCase()))||"";this.baseUri=s.substr(0,s.length-e.length)}else this.baseUri=v.normalizeWsUrl(s)||s,"https://"===s.substr(0,8).toLowerCase()?this.svcUri=this.baseUri+"/API.svc":this.svcUri=this.baseUri+"/InsecureAPI.svc";this.sessionHandler=o,this.errorCallback=n,this.sessionId=null,this.supportGetItemPreviewMethod=null!=i&&i}get supportsGetItemPreviewMethod(){return this.supportGetItemPreviewMethod}static create(e,t,s,o,n,r,i,a){return new v(e,new m(t,s,o,n,r,i),i,a)}static createAnonymous(e,t){return new v(e,new p,t)}static createUsingOAuth(e,t,s,o,n,r,i,a,l,c){return new v(e,new f(t,s,o,n,r,i,a,l),a,c)}static normalizeWsUrl(e){return e&&e.endsWith("/")&&(e=e.substring(0,e.length-1)),e}get wsUrl(){return this.baseUri}static handleCallPromise(e,t,s,o){e.then((e=>{200===e.status?e.data.ReturnCode===l.rcSuccess?t(e.data):s(e.data):o(new g(e.status,e.statusText))})).catch((e=>{e.response?o(new g(e.response.status,e.response.statusText)):o(e)}))}}class E{constructor(e,t,s,o,n,r,i){this.isEnabled=(e,t)=>{const s=()=>{this.url&&this.token?e(this.url,this.token):t()};this.url&&this.token?e(this.url,this.token):this.obtainToken(s)},this.callTokenizedApi=(e,t,s,o)=>{this.isEnabled(((n,r)=>{t.token=r,E.call(n,e,t,s,(n=>{if(n.ReturnCodeString!==this.invalidTokenReturnCode){if(o)o(n);else if(this.generalErrorCallback){const e=new Error("Unhandled tokenized service connection return code "+n.ReturnCodeString+".\nDescription: "+n.Description);this.generalErrorCallback(e)}}else this.obtainToken((()=>{this.callTokenizedApi(e,t,s,o)}))}),(e=>{if(this.generalErrorCallback){const t=new Error("Unhandled tokenized service connection communication error: "+JSON.stringify(e));this.generalErrorCallback(t)}}))}),(()=>{o&&o(null)}))},this.obtainToken=e=>{if(!this.isActive)return this.url=null,this.token=null,void e();const t=t=>{const s=this.urlAndTokenObtainer(t);s.url&&s.token?(this.url=s.url,this.token=s.token,this.isActive=!0,e()):(this.url=null,this.token=null,this.isActive=!1,e())},s=()=>{this.url=null,this.token=null,this.isActive=!1,e()};this.needsSession?this.connection.callMethod(this.obtainTokenMethodName,{},t,s,this.obtainTokenMethodType):this.connection.callWithoutSession(this.obtainTokenMethodName,null,t,s,null,this.obtainTokenMethodType)},this.obtainTokenMethodName=e,this.obtainTokenMethodType=t,this.needsSession=s,this.invalidTokenReturnCode=o,this.urlAndTokenObtainer=n,this.connection=r,this.generalErrorCallback=i||null,this.url=null,this.token=null,this.isActive=!0}static call(t,s,o,n,r,i){const a=t+"/"+s;e.post(a,o).then((e=>{200===e.status?"Success"===e.data.ReturnCodeString?n(e.data):r(e.data):i(new g(e.status,e.statusText))})).catch((e=>{e.response?i(new g(e.response.status,e.response.statusText)):i(e)}))}}const P=e=>({url:e.ServiceUrl,token:e.Token});class A{constructor(e,t){this.isCommonDataApiEnabled=(e,t)=>{this.tokenizedConnection.isEnabled(e,t)},this.callCommonDataApi=(e,t,s,o)=>{this.tokenizedConnection.callTokenizedApi(e,t,s,o)},this.tokenizedConnection=new E("ObtainCommonDataApiAccessToken",r.get,!1,"InvalidCommonDataToken",P,e,t)}}class k{}k.acceptableBackwardWorkReportDays="AcceptableBackwardWorkReportDays",k.adminAppInactiveLogoutTime="AdminAppInactiveLogoutTime",k.applyGeneralDataProtectionRules="ApplyGeneralDataProtectionRules",k.automaticallyCreateJournalAfterCallDuration="AutomaticallyCreateJournalAfterCallDuration",k.bonusesCompletedState="BonusesCompletedState",k.cartInvoicedState="CartInvoicedState",k.cartOrderCanceledState="CartOrderCanceledState",k.cartOrderInProcessState="CartOrderInProcessState",k.cartOrderProcessedState="CartOrderProcessedState",k.cartPaidState="CartPaidState",k.cartProposalInProcessState="CartProposalInProcessState",k.cartProposalProcessedState="CartProposalProcessedState",k.cartSalesVoucherIssuedState="CartSalesVoucherIssuedState",k.cartToBeInvoicedState="CartToBeInvoicedState",k.cartVoidedState="CartVoidedState",k.clickToCallScheme="ClickToCallScheme",k.companyDuplicityCheckEnabled="CompanyDuplicityCheckEnabled",k.completedStateName="CompletedStateName",k.contactDuplicityCheckEnabled="ContactDuplicityCheckEnabled",k.createCompanyWhileImportingContactFromOutlook="CreateCompanyWhileImportingContactFromOutlook",k.enableContactsTwoWaySyncWithM365="EnableContactsTwoWaySyncWithM365",k.deadStateName="DeadStateName",k.enableCompaniesSyncIntoMobileDeviceContacts="EnableCompaniesSyncIntoMobileDeviceContacts",k.enableContactsSyncIntoMobileDevice="EnableContactsSyncIntoMobileDevice",k.enableLeadsSyncIntoMobileDeviceContacts="EnableLeadsSyncIntoMobileDeviceContacts",k.enableLlamaAiFeatures="EnableLlamaAiFeatures",k.enableUsersSyncIntoMobileDeviceContacts="EnableUsersSyncIntoMobileDeviceContacts",k.emailsActiveProjectsLeadsFilter="EmailsActiveProjectsLeadsFilter",k.exchangeRatesAdminGroupName="ExchangeRatesAdminGroupName",k.forcedEmailTrackingGroups="ForcedEmailTrackingGroups",k.ignoreEmailsFromDomainsOnEmailsTracking="IgnoreEmailsFromDomainsOnEmailsTracking",k.trackEmailsFromDomains="TrackEmailsFromDomains",k.groupsForAllUnpaidInvoicesNotification="GroupsForAllUnpaidInvoicesNotification",k.itemPreviewMaxHeight="ItemPreviewMaxHeight",k.lastActivityAttributes="LastActivityAttributes",k.leadsCompletedState="LeadsCompletedState",k.leadDeadlineAlertGroups="LeadDeadlineAlertGroups",k.leadsDeadState="LeadsDeadState",k.marketingCompletedState="MarketingCompletedState",k.marketingDeadState="MarketingDeadState",k.minimumPasswordLength="MinimumPasswordLength",k.nextStepAttributes="NextStepAttributes",k.notifyAboutInvoicedInvoiceInPohodaGroup="NotifyAboutInvoicedInvoiceInPohodaGroup",k.notifyAboutLeadsDeadline="NotifyAboutLeadsDeadline",k.notifyAboutPaidInvoiceInPohodaGroup="NotifyAboutPaidInvoiceInPohodaGroup",k.notifyAboutProjectDeadline="NotifyAboutProjectDeadline",k.numberOfDecimalPlaces="NumberOfDecimalPlaces",k.phoneListTaskSolverGroup="PhoneListTaskSolverGroup",k.projectDeadlineAlert="ProjectDeadlineAlert",k.serverUpdateProgressNotificationGroup="ServerUpdateProgressNotificationGroup",k.sumarizeCartsPricesOnLeads="SumarizeCartsPricesOnLeads",k.sumarizeCartsPricesOnProjects="SumarizeCartsPricesOnProjects",k.sumarizePeopleExpensesOnProjects="SumarizePeopleExpensesOnProjects",k.systemHealthNotificationGroup="SystemHealthNotificationGroup",k.tasksCompletedState="TasksCompletedState",k.tasksDeferredState="TasksDeferredState",k.tasksInProgressState="TasksInProgressState",k.tasksNotStartedState="TasksNotStartedState",k.tasksWaitOnSomeoneElseState="TasksWaitOnSomeoneElseState",k.trackDocumentVersions="TrackDocumentVersions",k.vacationCompletedState="VacationCompletedState",k.workReportApprovedState="WorkReportApprovedState",k.defaultLanguage="DefaultLanguage",k.defaultCurrency="DefaultCurrency",k.myCompanyCountry="MyCompanyCountry",k.myCompanyName="MyCompanyName",k.myCompanyStreet="MyCompanyStreet",k.myCompanyCity="MyCompanyCity",k.myCompanyState="MyCompanyState",k.myCompanyZip="MyCompanyZIP",k.myCompanyId="MyCompanyID",k.myCompanyVat="MyCompanyVAT";class T{}T.ServerCommon={Server_ID:"Server_ID",Server_ItemCreated:"Server_ItemCreated",Server_ItemChanged:"Server_ItemChanged"},T.Common={CreatedByGUID:"CreatedByGUID",CurrencyEn:"CurrencyEn",DefaultCurrencySuffix:"DefaultCurrency",FileAs:"FileAs",ItemCreated:"ItemCreated",ItemChanged:"ItemChanged",ItemGUID:"ItemGUID",ItemVersion:"ItemVersion",ModifiedByGUID:"ModifiedByGUID",OwnerGUID:"OwnerGUID",ParentCurrencySuffix:"ParentCurrency"},T.Calendar={EndDate:"EndDate",Note:"Note"},T.Carts={SuperiorItem:"SuperiorItem",SuperiorCompany:"SuperiorCompany",SuperiorContact:"SuperiorContact",TypeEn:"TypeEn",StateEn:"StateEn"},T.Companies={ID:"ID",CompanyName:"CompanyName",Department:"Department",AccountNumber:"AccountNumber",IdentificationNumber:"IdentificationNumber",VatNumber:"VatNumber",Sales:"Reversal",EmployeesCount:"EmployeesCount",Purchaser:"Purchaser",Suppliers:"Suppliers",Competitor:"Competitor",Address1Street:"Address1Street",Address1City:"Address1City",Address1PostalCode:"Address1PostalCode",Address1CountryEn:"Address1CountryEn",Address1State:"Address1State",Address1POBox:"Address1POBox",Address2Street:"Address2Street",Address2City:"Address2City",Address2PostalCode:"Address2PostalCode",Address2CountryEn:"Address2CountryEn",Address2State:"Address2State",Address2POBox:"Address2POBox",Address3Street:"Address3Street",Address3City:"Address3City",Address3PostalCode:"Address3PostalCode",Address3CountryEn:"Address3CountryEn",Address3State:"Address3State",Address3POBox:"Address3POBox",InvoiceAddress:"InvoiceAddress",PostalAddress:"PostalAddress",Phone:"Phone",Mobile:"Mobile",Fax:"Fax",WebPage:"WebPage",Email:"Email",ICQ:"ICQ",MSN:"MSN",Skype:"Skype",ImportanceEn:"ImportanceEn",FirstContactEn:"FirstContactEn",LineOfBusiness:"LineOfBusiness",EmailOptOut:"EmailOptOut",MailingListOther:"MailingListOther",MailingListOtherValue:"MailingListOtherValue",Note:"Note",IsPrivate:"IsPrivate",NextStep:"NextStep",LastActivity:"LastActivity",AdditionalDiscount:"AdditionalDiscount"},T.Contacts={ProfilePicture:"ProfilePicture",Title:"Title",Email1Address:"Email1Address",Email2Address:"Email2Address",Email3Address:"Email3Address",DoNotSendNewsletter:"DoNotSendNewsletter",ImportanceEn:"ImportanceEn",PrefixEn:"PrefixEn",FirstName:"FirstName",MiddleName:"MiddleName",LastName:"LastName",SuffixEn:"SuffixEn",BusinessAddressStreet:"BusinessAddressStreet",BusinessAddressCity:"BusinessAddressCity",BusinessAddressPostalCode:"BusinessAddressPostalCode",BusinessAddressCountryEn:"BusinessAddressCountryEn",BusinessAddressState:"BusinessAddressState",BusinessAddressPoBox:"BusinessAddressPOBox",HomeAddressStreet:"HomeAddressStreet",HomeAddressCity:"HomeAddressCity",HomeAddressPostalCode:"HomeAddressPostalCode",HomeAddressCountryEn:"HomeAddressCountryEn",HomeAddressState:"HomeAddressState",HomeAddressPOBox:"HomeAddressPOBox",OtherAddressStreet:"OtherAddressStreet",OtherAddressCity:"OtherAddressCity",OtherAddressPostalCode:"OtherAddressPostalCode",OtherAddressCountryEn:"OtherAddressCountryEn",OtherAddressState:"OtherAddressState",OtherAddressPOBox:"OtherAddressPOBox",BusinessPhoneNumber:"TelephoneNumber1",BusinessPhoneNumber2:"TelephoneNumber5",BusinessFaxNumber:"TelephoneNumber6",MobilePhoneNumber:"TelephoneNumber3",HomePhoneNumber:"TelephoneNumber2",OtherPhoneNumber:"TelephoneNumber4",ICQ:"ICQ",MSN:"MSN",Skype:"Skype",WebPage:"WebPage",Note:"Note",Department:"Department",Company:"Company",IsPrivate:"Private",NextStep:"NextStep",LastActivity:"LastActivity"},T.Leads={ID:"ID",FileAs:"FileAs",HumanID:"HID",Customer:"Customer",ContactPerson:"ContactPerson",Marketing:"Marketing",ReceiveDate:"ReceiveDate",Email:"Email",Phone:"Phone",Street:"Street",State:"State",CountryEn:"CountryEn",City:"City",POBox:"POBox",Zip:"Zip",Price:"Price",PriceChanged:"PriceChanged",CurrencyEn:T.Common.CurrencyEn,EstimatedEnd:"EstimatedEnd",Probability:"Probability",LeadOriginEn:"LeadOriginEn",PriceDefaultCurrency:"PriceDefaultCurrency",EstimatedValue:"EstimatedValue",EstimatedValueDefaultCurrency:"EstimatedValueDefaultCurrency",Note:"Note",TypeEn:"TypeEn",StateEn:"StateEn",PrevStateEn:"PrevStateEn",IsPrivate:"Private",EmailOptOut:"EmailOptOut",NextStep:"NextStep",LastActivity:"LastActivity",ItemVersion:"ItemVersion",EstimatedRevenue:"EstimatedRevenue",EstimatedRevenueDefaultCurrency:"EstimatedRevenueDefaultCurrency",CompletedDate:"CompletedDate",LostDate:"LostDate"},T.Documents={FileAs:"FileAs",DocName:"DocName",Preview:"Preview",PreviewWidth:"PreviewWidth",PreviewHeight:"PreviewHeight",DocTypeEn:"DocTypeEn",StateEn:"StateEn",ImportanceEn:"ImportanceEn",SuperiorItem:"SuperiorItem",SuperiorCompany:"Company",SuperiorContact:"Contact",DocSize:"DocSize",Extension:"Extension",CreationTime:"CreationTime",LastWriteTime:"LastWriteTime",IsPrivate:"Private",Note:"Note"},T.Emails={To:"To",From:"SenderEmailAddress",Cc:"Cc",Subject:"Subject",ImportanceEn:"ImportanceEn",SuperiorItem:"SuperiorItem",SentOn:"SentOn",ReceivedTime:"ReceivedTime",FileSize:"FileSize",AttachmentsCount:"AttachmentsCount",Note:"Note",SentimentTone:"SentimentTone",Summary:"Summary"},T.Goods={Code:"Code",Structure:"Structure",Note:"Note",Description:"Description"},T.Journal={FileAs:"FileAs",Subject:"Subject",TypeEn:"TypeEn",StateEn:"StateEn",ImportanceEn:"ImportanceEn",EventStart:"EventStart",EventEnd:"EventEnd",SuperiorItem:"SuperiorItem",Company:"Company",Contact:"Contact",Marketing:"Marketing",IsSystem:"System",IsPrivate:"Private",Note:"Note",Phone:"Phone"},T.Vacation={StartDate:"StartDate",EndDate:"EndDate",User:"User",Duration:"Duration",Place:"Place",Note:"Note",AllDay:"AllDay",TypeEn:"TypeEn",StateEn:"StateEn",IsPrivate:"Private"},T.Marketing={HumanID:"HumanID",EstimatedStart:"EstimatedStart",EstimatedEnd:"EstimatedEnd",RealStart:"RealStart",RealEnd:"RealEnd",TargetGroup:"TargetGroup",EmailsSent:"EmailsSent",EmailsDelivered:"EmailsDelivered",EmailsViewed:"EmailsViewed",PeopleUnsubscribed:"PeopleUnsubscribed",FinalRevenues:"FinalRevenues",TypeEn:"TypeEn",StateEn:"StateEn"},T.Projects={HumanID:"HID",FileAs:"FileAs",ProjectName:"ProjectName",ProjectOriginEn:"ProjectOriginEn",TypeEn:"TypeEn",StateEn:"StateEn",PaymentTypeEn:"PaymentTypeEn",ProjectStart:"ProjectStart",ProjectRealEnd:"ProjectRealEnd",EstimatedEnd:"ProjectEnd",CurrencyEn:T.Common.CurrencyEn,DefaultCurrencyEn:"DefaultCurrencyEn",EstimatedMargin:"EstimatedMargin",EstimatedPeopleExpenses:"EstimatedPeopleExpenses",EstimatedPeopleExpensesDefaultCurrency:"EstimatedPeopleExpensesDefaultCurrency",EstimatedOtherExpenses:"EstimatedOtherExpenses",EstimatedOtherExpensesDefaultCurrency:"EstimatedOtherExpensesDefaultCurrency",EstimatedPrice:"EstimatedPrice",EstimatedPriceDefaultCurrency:"EstimatedPriceDefaultCurrency",EstimatedProfit:"EstimatedProfit",EstimatedProfitDefaultCurrency:"EstimatedProfitDefaultCurrency",EstimatedPriceChanged:"EstimatedPriceChanged",EstimatedPeopleExpensesChanged:"EstimatedPeopleExpensesChanged",EstimatedOtherExpensesChanged:"EstimatedOtherExpensesChanged",Delay:"Delay",EstimatedWorkHours:"EstimatedWorkHours",TotalWorkHours:"TotalWorkHours",PeopleExpenses:"PeopleExpenses",OtherExpenses:"OtherExpenses",PeopleExpensesDefaultCurrency:"PeopleExpensesDefaultCurrency",OtherExpensesDefaultCurrency:"OtherExpensesDefaultCurrency",PeopleExpensesChanged:"PeopleExpensesChanged",OtherExpensesChanged:"OtherExpensesChanged",Price:"Price",PriceDefaultCurrency:"PriceDefaultCurrency",Profit:"Profit",ProfitDefaultCurrency:"ProfitDefaultCurrency",Margin:"Margin",PriceChanged:"PriceChanged",SuperiorProject:"SuperiorProject",Customer:"Customer",ContactPerson:"ContactPerson",Users:"Users",ProjectManager:"ProjectManager",InvoicePaymentDate:"InvoicePaymentDate",PaymentMaturity:"PaymentMaturity",InvoiceIssueDate:"InvoiceIssueDate",LicensesCount:"LicensesCount",LicensePrice:"LicensePrice",LicensePriceDefaultCurrency:"LicensePriceDefaultCurrency",NextStep:"NextStep",LastActivity:"LastActivity",IsPrivate:"Private",LicensePriceChanged:"LicensePriceChanged",Note:"Note",CompletedDate:"CompletedDate",LostDate:"LostDate"},T.Tasks={FileAs:"FileAs",Subject:"Subject",RootItem:"RootItem",SuperiorItem:"SuperiorItem",Company:"Company",Contact:"Contact",StartDate:"StartDate",DueDate:"DueDate",Reminder:"Reminder",ReminderDate:"ReminderDate",ImportanceEn:"ImportanceEn",IsCompleted:"Complete",PercentComplete:"PercentComplete",PercentCompleteDecimal:"PercentCompleteDecimal",CompletedDate:"CompletedDate",Solver:"Solver",Delegator:"Delegator",Level:"Level",IsPrivate:"Private",ActualWorkHours:"ActualWorkHours",TotalWorkHours:"TotalWorkHours",Body:"Body",TypeEn:"TypeEn",StateEn:"StateEn"},T.Training={TitleEn:"TitleEn"},T.WorkReports={Task:"Task",ProjectName:"ProjectName",UserName:"UserName",Subject:"Subject",Date:"Date",FromTime:"FromTime",ToTime:"ToTime",Overtime:"Overtime",Month:"Month",Year:"Year",IsPrivate:"Private",Note:"Note",Duration:"Duration",WorkReportEn:"WorkReportEn",StateEn:"StateEn"},T.Users={ProfilePicture:"ProfilePicture",UserName:"UserName",JobTitle:"JobTitle",IDCardNumber:"IDCardNumber",Birthdate:"Birthdate",BirthPlace:"BirthPlace",PersonalIdentificationNumber:"PersonalIdentificationNumber",Active:"Active",FamilyStatusEn:"FamilyStatusEn",HomeAddressStreet:"HomeAddressStreet",HomeAddressCity:"HomeAddressCity",HomeAddressPostalCode:"HomeAddressPostalCode",HomeAddressCountryEn:"HomeAddressCountryEn",HomeAddressState:"HomeAddressState",HomeAddressPOBox:"HomeAddressPOBox",BankAccount:"BankAccount",BusinessPhoneNumber:"BusinessPhoneNumber",MobilePhoneNumber:"MobilePhoneNumber",Email1Address:"Email1Address",Email2Address:"Email2Address",ICQ:"ICQ",MSN:"MSN",Skype:"Skype",IdentificationNumber:"IdentificationNumber",HealthInsurance:"HealthInsurance",HolidayLength:"HolidayLength",RemainingDaysOfHoliday:"RemainingDaysOfHoliday",SalaryDateEn:"SalaryDateEn",Supervisor:"Supervisor",TravelDistance:"TravelDistance",TimeAccessibility:"TimeAccessibility",TransportMode:"TransportMode",WorkdayStartTime:"WorkdayStartTime",Note:"Note",IsSystem:"IsSystem"},T.Groups={IsAdmin:"IsAdmin",GroupName:"GroupName",FileAs:"FileAs",Description:"Description",IsPM:"IsPM",System:"System",IsRole:"IsRole",IsCategory:"IsCategory",DisallowControlModulePermissions:"DisallowControlModulePermissions",DisallowControlColumnPermissions:"DisallowControlColumnPermissions",IsOutlookCategory:"IsOutlookCategory",DisallowControlUserAssignment:"DisallowControlUserAssignment",ColorEn:"ColorEn",Picture:"Picture"},T.allTypeEnNames=["TypeEn",T.Documents.DocTypeEn,T.WorkReports.WorkReportEn,"TitleEn"],T.getFolderFileAs=e=>{switch(e){case d.leads:return T.Leads.FileAs;case d.projects:return T.Projects.ProjectName;case d.documents:return T.Documents.DocName;case d.companies:return T.Companies.CompanyName;case d.contacts:case d.users:return T.Common.FileAs;case d.emails:return T.Emails.Subject;case d.journal:return T.Journal.FileAs;case d.tasks:return T.Tasks.Subject;case d.workReports:return T.WorkReports.Subject;case d.vacation:return T.Vacation.TypeEn;case d.carts:case d.goods:return T.Common.FileAs;case d.groups:return T.Groups.GroupName;default:return console.warn(`FileAs col name not defined for folderName ${e}`),T.Common.FileAs}};class I{}I.general="GENERAL",I.group="GROUP",I.contactPerson="CONTACTPERSON",I.contact="CONTACT",I.customer="CUSTOMER",I.company="COMPANY",I.outlookProject="OUTLOOKPROJECT",I.supervisor="SUPERVISOR";class b{}b.all="All",b.own="Own",b.readonly="Readonly",b.invisible="Invisible",b.none="None";class w{}var D,N,O,R;w.mandatory="Mandatory",w.optional="Optional",w.unique="Unique",w.none="None",function(e){e.Free="Free",e.Basic="Basic",e.Professional="Professional",e.Enterprise="Enterprise"}(D||(D={})),function(e){e.ContactsAndCompanies="ContactsAndCompanies",e.Sales="Sales",e.Projects="Projects",e.Marketing="Marketing"}(N||(N={})),function(e){e[e.Negative=0]="Negative",e[e.Neutral=1]="Neutral",e[e.Positive=2]="Positive"}(O||(O={}));class M{}M.contactsSynchronizationWithOutlook="ContactsSynchronizationWithOutlook",M.wordAddin="WordAddin",M.excelAddin="ExcelAddin",M.tasksRecurrentTasks="TasksRecurrentTasks",M.tasksSubtasks="TasksSubtasks",M.tasksSynchronizationWithOutlook="TasksSynchronizationWithOutlook",M.calendarSynchronizationWithOutlook="CalendarSynchronizationWithOutlook",M.emailsAutomaticTracking="EmailsAutomaticTracking",M.convertEmailToProject="ConvertEmailToProject",M.duplicityChecker="DuplicityChecker",M.nextStepAndLastActivityCustomization="NextStepAndLastActivityCustomization",M.subProjects="SubProjects",M.resourceAndPlanning="ResourceAndPlanning",M.professionalEmailCampaigns="ProfessionalEmailCampaigns",M.professionalEmailCampaignsAdvancedStatistics="ProfessionalEmailCampaignsAdvancedStatistics",M.wordEmailMerge="WordEmailMerge",M.printLabels="PrintLabels",M.printEnvelopes="PrintEnvelopes",M.userViews="UserViews",M.sharedUserViews="SharedUserViews",M.gridConditionalFormating="GridConditionalFormating",M.multipleCurrencies="MultipleCurrencies",M.historyTracking="HistoryTracking",M.privateItems="PrivateItems",M.itemTypes="ItemTypes",M.formLayoutCustomization="FormLayoutCustomization",M.workflowBasicDefinitions="WorkflowBasicDefinitions",M.workflowAdvancedDefinitions="WorkflowAdvancedDefinitions",M.workflowAdvancedDefinitionsRules="WorkflowAdvancedDefinitionsRules",M.workflowAdvancedDefinitionsActions="WorkflowAdvancedDefinitionsActions",M.workflowGroupLevelActions="WorkflowGroupLevelActions",M.customFields="CustomFields",M.importantFields="ImportantFields",M.mandatoryFields="MandatoryFields",M.uniqueFields="UniqueFields",M.readOnlyFields="ReadOnlyFields",M.transformationCustomTemplates="TransformationCustomTemplates",M.userRoles="UserRoles",M.modulePermissions="ModulePermissions",M.columnPermissions="ColumnPermissions",M.api="API",M.gate="Gate",M.threeCXIntegration="ThreeCXIntegration",M.tapiIntegration="TapiIntegration",M.pohodaIntegration="PohodaIntegration",M.pohodaSynchronizationIntervalCustomization="PohodaSynchronizationIntervalCustomization",M.pohodaSynchronizationFieldMappingCustomization="PohodaSynchronizationFieldMappingCustomization",M.quickBooksIntegration="QuickBooksIntegration",M.saveBinaryDataOnDisk="SaveBinaryDataOnDisk",M.activeDirectoryLogin="ActiveDirectoryLogin",M.callerIdentificationOnApple="CallerIdentificationOnApple",M.legacyAdministration="LegacyAdministration";class L{}L.customAdditionalFieldsCount="CustomAdditionalFieldsCount",L.customEnabledAdvancedWorkflowsCount="CustomEnabledAdvancedWorkflowsCount",L.customEnabledBasicWorkflowsCount="CustomEnabledBasicWorkflowsCount",L.customMandatoryFieldsCount="CustomMandatoryFieldsCount",L.customOptionalFieldsCount="CustomOptionalFieldsCount",L.customReadonlyFieldsCount="CustomReadonlyFieldsCount",L.customUniqueFieldsCount="CustomUniqueFieldsCount",L.customVisibleTypesCount="CustomVisibleTypesCount",L.visibleCurrenciesCount="VisibleCurrenciesCount";class F{}F.contactsAutomaticSynchronizationWithOutlook="ContactsAutomaticSynchronizationWithOutlook",F.contactsSynchronizationWithOutlook="ContactsSynchronizationWithOutlook",F.contactsSynchronizationWithAndroid="ContactsSynchronizationWithAndroid",F.documentsRevisions="DocumentsRevisions",F.wordAddin="WordAddin",F.excelAddin="ExcelAddin",F.tasksReminders="TasksReminders",F.tasksRecurrentTasks="TasksRecurrentTasks",F.tasksSubtasks="TasksSubtasks",F.tasksSynchronizationWithOutlook="TasksSynchronizationWithOutlook",F.calendarSynchronizationWithOutlook="CalendarSynchronizationWithOutlook",F.emailsManualTracking="EmailsManualTracking",F.emailsAutomaticTracking="EmailsAutomaticTracking",F.emailSummaryAndSentimentToneFromAi="EmailSummaryAndSentimentToneFromAi",F.convertEmailToContact="ConvertEmailToContact",F.convertEmailToContactInBulk="ConvertEmailToContactInBulk",F.convertEmailToDeal="ConvertEmailToDeal",F.convertEmailToProject="ConvertEmailToProject",F.convertEmailToTask="ConvertEmailToTask",F.gravatarIntegration="GravatarIntegration",F.logoboxIntegration="LogoboxIntegration",F.companiesBussinesRegisterApiIntegration="CompaniesBussinesRegisterApiIntegration",F.duplicityChecker="DuplicityChecker",F.nextStepAndLastActivityCustomization="NextStepAndLastActivityCustomization",F.subProjects="SubProjects",F.resourceAndPlanning="ResourceAndPlanning",F.professionalEmailCampaigns="ProfessionalEmailCampaigns",F.professionalEmailCampaignsAdvancedStatistics="ProfessionalEmailCampaignsAdvancedStatistics",F.wordEmailMerge="WordEmailMerge",F.printLabels="PrintLabels",F.printEnvelopes="PrintEnvelopes",F.userViews="UserViews",F.sharedUserViews="SharedUserViews",F.gridRowSummary="GridRowSummary",F.gridConditionalFormating="GridConditionalFormating",F.multipleCurrencies="MultipleCurrencies",F.historyTracking="HistoryTracking",F.privateItems="PrivateItems",F.itemTypes="ItemTypes",F.formLayoutCustomization="FormLayoutCustomization",F.workflowBasicDefinitions="WorkflowBasicDefinitions",F.workflowAdvancedDefinitions="WorkflowAdvancedDefinitions",F.workflowAdvancedDefinitionsRules="WorkflowAdvancedDefinitionsRules",F.workflowAdvancedDefinitionsActions="WorkflowAdvancedDefinitionsActions",F.workflowGroupLevelActions="WorkflowGroupLevelActions",F.customFields="CustomFields",F.importantFields="ImportantFields",F.mandatoryFields="MandatoryFields",F.uniqueFields="UniqueFields",F.readOnlyFields="ReadOnlyFields",F.transformationCustomTemplates="TransformationCustomTemplates",F.userRoles="UserRoles",F.modulePermissions="ModulePermissions",F.columnPermissions="ColumnPermissions",F.commonDataAPI="CommonDataAPI",F.eWayCrmAPI="eWayCrmAPI",F.threeCXIntegration="ThreeCXIntegration",F.tapiIntegration="TapiIntegration",F.pohodaIntegration="PohodaIntegration",F.pohodaSynchronizationIntervalCustomization="PohodaSynchronizationIntervalCustomization",F.pohodaSynchronizationFieldMappingCustomization="PohodaSynchronizationFieldMappingCustomization",F.quickBooksIntegration="QuickBooksIntegration",F.shareByTeams="ShareByTeams",F.convertEmailToContactWithDataFromAi="ConvertEmailToContactWithDataFromAi",F.convertEmailToDealWithDataFromAi="ConvertEmailToDealWithDataFromAi",F.convertEmailToProjectWithDataFromAi="ConvertEmailToProjectWithDataFromAi",function(e){e.UnpaidImportantInvoices="UnpaidImportantInvoices",e.UncollectableSubscriptionPayment="UncollectableSubscriptionPayment",e.UncollectableSubscriptionPaymentWithExpiredCard="UncollectableSubscriptionPaymentWithExpiredCard",e.StandardSubscriptionPeriod="StandardSubscriptionPeriod"}(R||(R={}));var x,U=R;!function(e){e.License="License",e.CloudLicense="CloudLicense",e.MiscLicense="MiscLicense",e.Support="Support",e.Service="Service"}(x||(x={}));var B=x;class W{}W.getIsDebug=e=>{var t;return!!(null===(t=null==e?void 0:e.sessionHandler.lastSuccessfulLoginResponse)||void 0===t?void 0:t.Debug)},W.supportsFeaturesOf=(e,t)=>{var s;const n=null===(s=e.sessionHandler.lastSuccessfulLoginResponse)||void 0===s?void 0:s.WcfVersion;return!!n&&(o(n,t,">=")||o(n,"1.0.0.0","="))};class G{}G.textBox="TextBox",G.comboBox="ComboBox",G.numericBox="NumericBox",G.relation="Relation",G.checkBox="CheckBox",G.linkTextBox="LinkTextBox",G.dateEdit="DateEdit",G.memoBox="MemoBox",G.multiSelectComboBox="MultiSelectComboBox",G.workflowState="WorkflowState",G.image="Image",G.multiSelectRelation="MultiSelectRelation";const j={[d.relations]:0,[d.unifiedRelations]:1,[d.users]:2,[d.groups]:3,[d.enumTypes]:4,[d.enumValues]:5,[d.additionalFields]:6};class _{static createHubItemsCountsQuery(e,t,s){return{__type:"HubItemsCountsQuery:#EQ",ParentItemGuids:e,ItemTypes:t,ExcludeSystemItems:s}}}class H{constructor(e,t){if(!e||!t)throw new Error("Both folderName and baseItem has to be defined!");this.folderName=e,this.baseItem=t}getEmailAddress(){switch(this.folderName){case d.contacts:{const e=this.baseItem;return e.Email1Address||e.Email2Address||e.Email3Address}case d.leads:return this.baseItem.Email;case d.companies:return this.baseItem.Email;case d.users:{const e=this.baseItem;return e.Email1Address||e.Email2Address}default:return null}}getInitials(){switch(this.folderName){case d.contacts:{const e=this.baseItem;return this.getInitialsInternal(e.FirstName,e.LastName)}case d.users:{const e=this.baseItem;return this.getInitialsInternal(e.FirstName,e.LastName)}default:return null}}getInitialsInternal(e,t){const s=((null==e?void 0:e.substr(0,1))||"")+((null==t?void 0:t.substr(0,1))||"");return""==s?null:s}getItemPreview(){switch(this.folderName){case d.contacts:{const e=this.baseItem;return e.ProfilePicture?{imageData:e.ProfilePicture,width:e.ProfilePictureWidth||0,height:e.ProfilePictureHeight||0}:null}case d.users:{const e=this.baseItem;return e.ProfilePicture?{imageData:e.ProfilePicture,width:e.ProfilePictureWidth||0,height:e.ProfilePictureHeight||0}:null}default:return null}}}var z;!function(e){e.Readonly="Readonly",e.VisibleRankDefaultOnly="VisibleRankDefaultOnly",e.Editable="Editable"}(z||(z={})),a.polyfill();export{v as ApiConnectionAsNonDefaultExport,u as ApiMethods,w as ColumnPermissionMandatoryRules,b as ColumnPermissionPermissionRules,A as CommonDataConnection,L as CustomizationStatsItemKeys,H as EWItem,D as Edition,z as EnumTypeEditMode,c as EnumTypes,S as ErrorHelper,U as ExpirationReason,N as Feature,T as FieldNames,G as FieldTypes,d as FolderNames,M as Functionality,k as GlobalSettingsNames,r as HttpMethod,g as HttpRequestError,B as LicenseKeyInvoiceSeverity,F as LicenseRestrictionKeys,h as OAuthHelper,C as OAuthSessionHandlerBase,j as ObjectTypeIds,_ as QueryHelper,I as RelationTypes,l as ReturnCodes,O as SentimentTone,E as TokenizedServiceConnection,W as VersionHelperBase,v as default};
package/lib/index.d.ts CHANGED
@@ -261,7 +261,14 @@ declare class ApiMethods {
261
261
  static readonly getBinaryAttachmentLatestRevision = "GetBinaryAttachmentLatestRevision";
262
262
  static readonly canUnlinkItems = "CanUnlinkItems";
263
263
  static readonly unlinkItems = "UnlinkItems";
264
+ /**
265
+ * Return folderName part of API method that is used in API calls. Some API methods have different names than the folder names they are associated with.
266
+ * For example module Calendar has method GetCalendarsByItemGuids, but the folder name is Calendar.
267
+ */
268
+ private static readonly getFolderNameForApiMethod;
264
269
  static readonly getGetFolderNameByItemGuidsMethodName: (folderName: TFolderName) => string;
270
+ static readonly getGetFolderNameMethodName: (folderName: TFolderName) => string;
271
+ static readonly getSearchFolderNameMethodName: (folderName: TFolderName) => string;
265
272
  }
266
273
 
267
274
  declare class GlobalSettingsNames {
@@ -759,12 +766,15 @@ interface IEWJwtPayload extends JwtPayload {
759
766
  ws?: string;
760
767
  }
761
768
 
769
+ type scope = "api" | "offline_access";
770
+ type codeChallengeMethod = "plain" | "S256";
762
771
  declare class OAuthHelper {
763
772
  static finishAuthorization: (wsUrl: string, clientId: string, clientSecret: string, codeVerifier: string, authorizationCode: string, redirectUrl: string, callback: (tokenData: ITokenData) => void) => void;
764
773
  static refreshToken: (wsUrl: string, clientId: string, clientSecret: string, refreshToken: string, callback: (tokenData: ITokenData) => void) => void;
765
774
  static getWebServiceUrl: (refreshToken: string) => string;
766
775
  static getUserName: (accessToken: string) => string | undefined;
767
776
  static decodeAccessToken: (accessToken: string) => IEWJwtPayload;
777
+ static createAuthorizeUrl(clientId: string, scopes: scope[], redirectUri: string, state?: string, codeChallenge?: string, codeChallengeMethod?: codeChallengeMethod, isDev?: boolean): string;
768
778
  private static callTokenEndpoint;
769
779
  }
770
780
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eway-crm/connector",
3
- "version": "1.0.171",
3
+ "version": "1.0.173",
4
4
  "description": "eWay-CRM API JavaScript connector library.",
5
5
  "main": "lib/cjs/index.js",
6
6
  "module": "lib/esm/index.js",