@eway-crm/connector 1.0.231 → 1.0.233

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.npmjs.com/package/@eway-crm/connector). 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://free.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.npmjs.com/package/@eway-crm/connector). 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://free.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
+ ```
@@ -40,17 +40,28 @@ export declare class ApiConnection {
40
40
  * @param catchGlobally Optional. If true, raises this the global error handler each time the promise is rejected.
41
41
  */
42
42
  readonly askUploadMethod: (itemGuid: string, fileName: string, data: File, config?: AxiosRequestConfig, catchGlobally?: boolean) => Promise<IApiResult>;
43
+ /**
44
+ *
45
+ * @param file File to be uploaded
46
+ * @param data Additional data to be sent as URL parameters
47
+ * @param methodName API method name. Ex. 'SaveBinaryAttachment'.
48
+ * @param successCallback Handler callback when the method executes well. Gets the whole response JSON object as the only argument.
49
+ * @param unsuccessCallback Optional. Handler callback for eWay-API app level failures. Gets the whole response JSON object as the only argument. If not supplied, the global error handler is used.
50
+ * @param errorCallback Optional. Handler callback for any other failures. If not supplied, the global error handler is used.
51
+ * @param config Optional. Additional config for the request.
52
+ */
53
+ readonly callCustomUploadMethod: (file: File, data: Record<string, string>, methodName: string, successCallback: (res: IApiResult) => void, unsuccessCallback?: ((e: IApiResult) => void) | undefined, errorCallback?: ((e: TUnionError) => void) | undefined, config?: AxiosRequestConfig) => void;
43
54
  /**
44
55
  * Asynchronously uploads file using binary stream
45
56
  * @param itemGuid Item identificator. Ex. '9ac561be-9b7d-4938-8e55-4cce97142483'.
46
57
  * @param fileName File name, ex. 'picture.img'.
47
- * @param data Single file to be uploaded.
58
+ * @param file Single file to be uploaded.
48
59
  * @param successCallback Handler callback when the method executes well. Gets the whole response JSON object as the only argument.
49
60
  * @param unsuccessCallback Optional. Handler callback for eWay-API app level failures. Gets the whole response JSON object as the only argument. If not supplied, the global error handler is used.
50
61
  * @param errorCallback Optional. Handler callback for any other failures. If not supplied, the global error handler is used.
51
62
  * @param config Optional. Additional config for the request.
52
63
  */
53
- readonly callUploadMethod: (itemGuid: string, fileName: string, data: File, successCallback: (res: IApiResult) => void, unsuccessCallback?: ((e: IApiResult) => void) | undefined, errorCallback?: ((e: TUnionError) => void) | undefined, config?: AxiosRequestConfig) => void;
64
+ readonly callUploadMethod: (itemGuid: string, fileName: string, file: File, successCallback: (res: IApiResult) => void, unsuccessCallback?: ((e: IApiResult) => void) | undefined, errorCallback?: ((e: TUnionError) => void) | undefined, config?: AxiosRequestConfig) => void;
54
65
  /**
55
66
  * Creates a promise for async API method call.
56
67
  * @param methodName API method name. Ex. 'GetUsers'.
@@ -75,6 +86,7 @@ export declare class ApiConnection {
75
86
  readonly getAllEmailAttachmentsZipGetMethodUrl: (itemGuid: string) => string;
76
87
  readonly getBinaryAttachmentGetMethodUrl: (itemGuid: string, revision?: number) => string;
77
88
  readonly getTransformItemMethodUrl: (itemGuid: string, folderName: string, transformationGuid: string, outputFormat: TransformItemFormats) => string;
89
+ readonly getXsltTransformationDefinitionMethodUrl: (transformationGuid: string) => string;
78
90
  readonly getActiveSessionId: () => string | null;
79
91
  readonly setActiveSessionId: (sessionId: string | null) => void;
80
92
  private static handleCallPromise;
@@ -24,6 +24,9 @@ export declare class ApiMethods {
24
24
  static readonly unlinkItems = "UnlinkItems";
25
25
  static readonly getGoodsFinalPrices = "GetGoodsFinalPrices";
26
26
  static readonly saveItemCopyRelation = "SaveItemCopyRelation";
27
+ static readonly getXsltTransormationDefinition = "GetXsltTransformationDefinition";
28
+ static readonly saveBinaryAttachment = "SaveBinaryAttachment";
29
+ static readonly saveBinaryXsltTransformation = "SaveBinaryXsltTransformation";
27
30
  /**
28
31
  * 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.
29
32
  * For example module Calendar has method GetCalendarsByItemGuids, but the folder name is Calendar.
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"),r=require("jwt-decode"),o=require("compare-versions");function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,Object.freeze(t)}var s=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 r=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},o=0,n=void 0,s=void 0,a=function(e,t){T[o]=e,T[o+1]=t,2===(o+=2)&&(s?s(E):v())};function l(e){s=e}function c(e){a=e}var u="undefined"!=typeof window?window:void 0,d=u||{},m=d.MutationObserver||d.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!==n?function(){n(E)}:g()}function f(){var e=0,t=new m(E),r=document.createTextNode("");return t.observe(r,{characterData:!0}),function(){r.data=e=++e%2}}function P(){var e=new MessageChannel;return e.port1.onmessage=E,function(){return e.port2.postMessage(0)}}function g(){var e=setTimeout;return function(){return e(E,1)}}var T=new Array(1e3);function E(){for(var e=0;e<o;e+=2)(0,T[e])(T[e+1]),T[e]=void 0,T[e+1]=void 0;o=0}function S(){try{var e=Function("return this")().require("vertx");return n=e.runOnLoop||e.runOnContext,C()}catch(e){return g()}}var v=void 0;function I(e,t){var r=this,o=new this.constructor(b);void 0===o[k]&&$(o);var n=r._state;if(n){var s=arguments[n-1];a(function(){return B(n,o,s,r._result)})}else j(r,o,e,t);return o}function A(e){var t=this;if(e&&"object"==typeof e&&e.constructor===t)return e;var r=new t(b);return V(r,e),r}v=p?y():m?f():h?P():void 0===u?S():g();var k=Math.random().toString(36).substring(2);function b(){}var D=void 0,w=1,x=2;function F(){return new TypeError("You cannot resolve a promise with itself")}function O(){return new TypeError("A promises callback cannot return that same promise.")}function N(e,t,r,o){try{e.call(t,r,o)}catch(e){return e}}function R(e,t,r){a(function(e){var o=!1,n=N(r,t,function(r){o||(o=!0,t!==r?V(e,r):U(e,r))},function(t){o||(o=!0,G(e,t))},"Settle: "+(e._label||" unknown promise"));!o&&n&&(o=!0,G(e,n))},e)}function M(e,t){t._state===w?U(e,t._result):t._state===x?G(e,t._result):j(t,void 0,function(t){return V(e,t)},function(t){return G(e,t)})}function L(e,r,o){r.constructor===e.constructor&&o===I&&r.constructor.resolve===A?M(e,r):void 0===o?U(e,r):t(o)?R(e,r,o):U(e,r)}function V(t,r){if(t===r)G(t,F());else if(e(r)){var o=void 0;try{o=r.then}catch(e){return void G(t,e)}L(t,r,o)}else U(t,r)}function _(e){e._onerror&&e._onerror(e._result),W(e)}function U(e,t){e._state===D&&(e._result=t,e._state=w,0!==e._subscribers.length&&a(W,e))}function G(e,t){e._state===D&&(e._state=x,e._result=t,a(_,e))}function j(e,t,r,o){var n=e._subscribers,s=n.length;e._onerror=null,n[s]=t,n[s+w]=r,n[s+x]=o,0===s&&e._state&&a(W,e)}function W(e){var t=e._subscribers,r=e._state;if(0!==t.length){for(var o=void 0,n=void 0,s=e._result,i=0;i<t.length;i+=3)o=t[i],n=t[i+r],o?B(r,o,n,s):n(s);e._subscribers.length=0}}function B(e,r,o,n){var s=t(o),i=void 0,a=void 0,l=!0;if(s){try{i=o(n)}catch(e){l=!1,a=e}if(r===i)return void G(r,O())}else i=n;r._state!==D||(s&&l?V(r,i):!1===l?G(r,a):e===w?U(r,i):e===x&&G(r,i))}function H(e,t){try{t(function(t){V(e,t)},function(t){G(e,t)})}catch(t){G(e,t)}}var z=0;function Q(){return z++}function $(e){e[k]=z++,e._state=void 0,e._result=void 0,e._subscribers=[]}function q(){return new Error("Array Methods must be provided an Array")}var J=function(){function e(e,t){this._instanceConstructor=e,this.promise=new e(b),this.promise[k]||$(this.promise),r(t)?(this.length=t.length,this._remaining=t.length,this._result=new Array(this.length),0===this.length?U(this.promise,this._result):(this.length=this.length||0,this._enumerate(t),0===this._remaining&&U(this.promise,this._result))):G(this.promise,q())}return e.prototype._enumerate=function(e){for(var t=0;this._state===D&&t<e.length;t++)this._eachEntry(e[t],t)},e.prototype._eachEntry=function(e,t){var r=this._instanceConstructor,o=r.resolve;if(o===A){var n=void 0,s=void 0,i=!1;try{n=e.then}catch(e){i=!0,s=e}if(n===I&&e._state!==D)this._settledAt(e._state,t,e._result);else if("function"!=typeof n)this._remaining--,this._result[t]=e;else if(r===te){var a=new r(b);i?G(a,s):L(a,e,n),this._willSettleAt(a,t)}else this._willSettleAt(new r(function(t){return t(e)}),t)}else this._willSettleAt(o(e),t)},e.prototype._settledAt=function(e,t,r){var o=this.promise;o._state===D&&(this._remaining--,e===x?G(o,r):this._result[t]=r),0===this._remaining&&U(o,this._result)},e.prototype._willSettleAt=function(e,t){var r=this;j(e,void 0,function(e){return r._settledAt(w,t,e)},function(e){return r._settledAt(x,t,e)})},e}();function K(e){return new J(this,e).promise}function X(e){var t=this;return r(e)?new t(function(r,o){for(var n=e.length,s=0;s<n;s++)t.resolve(e[s]).then(r,o)}):new t(function(e,t){return t(new TypeError("You must pass an array to race."))})}function Y(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[k]=Q(),this._result=this._state=void 0,this._subscribers=[],b!==t&&("function"!=typeof t&&Z(),this instanceof e?H(this,t):ee())}return e.prototype.catch=function(e){return this.then(null,e)},e.prototype.finally=function(e){var r=this,o=r.constructor;return t(e)?r.then(function(t){return o.resolve(e()).then(function(){return t})},function(t){return o.resolve(e()).then(function(){throw t})}):r.then(e,e)},e}();function re(){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 r=null;try{r=Object.prototype.toString.call(t.resolve())}catch(e){}if("[object Promise]"===r&&!t.cast)return}e.Promise=te}return te.prototype.then=I,te.all=K,te.race=X,te.resolve=A,te.reject=Y,te._setScheduler=l,te._setAsap=c,te._asap=a,te.polyfill=re,te.Promise=te,te}();
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("axios"),t=require("universal-base64url"),r=require("jwt-decode"),o=require("compare-versions");function n(e){var t=Object.create(null);return e&&Object.keys(e).forEach(function(r){if("default"!==r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})}}),t.default=e,Object.freeze(t)}var s=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 r=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},o=0,n=void 0,s=void 0,a=function(e,t){T[o]=e,T[o+1]=t,2===(o+=2)&&(s?s(E):v())};function l(e){s=e}function c(e){a=e}var u="undefined"!=typeof window?window:void 0,d=u||{},m=d.MutationObserver||d.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!==n?function(){n(E)}:g()}function f(){var e=0,t=new m(E),r=document.createTextNode("");return t.observe(r,{characterData:!0}),function(){r.data=e=++e%2}}function P(){var e=new MessageChannel;return e.port1.onmessage=E,function(){return e.port2.postMessage(0)}}function g(){var e=setTimeout;return function(){return e(E,1)}}var T=new Array(1e3);function E(){for(var e=0;e<o;e+=2)(0,T[e])(T[e+1]),T[e]=void 0,T[e+1]=void 0;o=0}function S(){try{var e=Function("return this")().require("vertx");return n=e.runOnLoop||e.runOnContext,C()}catch(e){return g()}}var v=void 0;function A(e,t){var r=this,o=new this.constructor(b);void 0===o[k]&&$(o);var n=r._state;if(n){var s=arguments[n-1];a(function(){return W(n,o,s,r._result)})}else j(r,o,e,t);return o}function I(e){var t=this;if(e&&"object"==typeof e&&e.constructor===t)return e;var r=new t(b);return V(r,e),r}v=p?y():m?f():h?P():void 0===u?S():g();var k=Math.random().toString(36).substring(2);function b(){}var D=void 0,w=1,x=2;function F(){return new TypeError("You cannot resolve a promise with itself")}function O(){return new TypeError("A promises callback cannot return that same promise.")}function N(e,t,r,o){try{e.call(t,r,o)}catch(e){return e}}function R(e,t,r){a(function(e){var o=!1,n=N(r,t,function(r){o||(o=!0,t!==r?V(e,r):U(e,r))},function(t){o||(o=!0,G(e,t))},"Settle: "+(e._label||" unknown promise"));!o&&n&&(o=!0,G(e,n))},e)}function M(e,t){t._state===w?U(e,t._result):t._state===x?G(e,t._result):j(t,void 0,function(t){return V(e,t)},function(t){return G(e,t)})}function L(e,r,o){r.constructor===e.constructor&&o===A&&r.constructor.resolve===I?M(e,r):void 0===o?U(e,r):t(o)?R(e,r,o):U(e,r)}function V(t,r){if(t===r)G(t,F());else if(e(r)){var o=void 0;try{o=r.then}catch(e){return void G(t,e)}L(t,r,o)}else U(t,r)}function _(e){e._onerror&&e._onerror(e._result),B(e)}function U(e,t){e._state===D&&(e._result=t,e._state=w,0!==e._subscribers.length&&a(B,e))}function G(e,t){e._state===D&&(e._state=x,e._result=t,a(_,e))}function j(e,t,r,o){var n=e._subscribers,s=n.length;e._onerror=null,n[s]=t,n[s+w]=r,n[s+x]=o,0===s&&e._state&&a(B,e)}function B(e){var t=e._subscribers,r=e._state;if(0!==t.length){for(var o=void 0,n=void 0,s=e._result,i=0;i<t.length;i+=3)o=t[i],n=t[i+r],o?W(r,o,n,s):n(s);e._subscribers.length=0}}function W(e,r,o,n){var s=t(o),i=void 0,a=void 0,l=!0;if(s){try{i=o(n)}catch(e){l=!1,a=e}if(r===i)return void G(r,O())}else i=n;r._state!==D||(s&&l?V(r,i):!1===l?G(r,a):e===w?U(r,i):e===x&&G(r,i))}function H(e,t){try{t(function(t){V(e,t)},function(t){G(e,t)})}catch(t){G(e,t)}}var z=0;function Q(){return z++}function $(e){e[k]=z++,e._state=void 0,e._result=void 0,e._subscribers=[]}function q(){return new Error("Array Methods must be provided an Array")}var J=function(){function e(e,t){this._instanceConstructor=e,this.promise=new e(b),this.promise[k]||$(this.promise),r(t)?(this.length=t.length,this._remaining=t.length,this._result=new Array(this.length),0===this.length?U(this.promise,this._result):(this.length=this.length||0,this._enumerate(t),0===this._remaining&&U(this.promise,this._result))):G(this.promise,q())}return e.prototype._enumerate=function(e){for(var t=0;this._state===D&&t<e.length;t++)this._eachEntry(e[t],t)},e.prototype._eachEntry=function(e,t){var r=this._instanceConstructor,o=r.resolve;if(o===I){var n=void 0,s=void 0,i=!1;try{n=e.then}catch(e){i=!0,s=e}if(n===A&&e._state!==D)this._settledAt(e._state,t,e._result);else if("function"!=typeof n)this._remaining--,this._result[t]=e;else if(r===te){var a=new r(b);i?G(a,s):L(a,e,n),this._willSettleAt(a,t)}else this._willSettleAt(new r(function(t){return t(e)}),t)}else this._willSettleAt(o(e),t)},e.prototype._settledAt=function(e,t,r){var o=this.promise;o._state===D&&(this._remaining--,e===x?G(o,r):this._result[t]=r),0===this._remaining&&U(o,this._result)},e.prototype._willSettleAt=function(e,t){var r=this;j(e,void 0,function(e){return r._settledAt(w,t,e)},function(e){return r._settledAt(x,t,e)})},e}();function X(e){return new J(this,e).promise}function K(e){var t=this;return r(e)?new t(function(r,o){for(var n=e.length,s=0;s<n;s++)t.resolve(e[s]).then(r,o)}):new t(function(e,t){return t(new TypeError("You must pass an array to race."))})}function Y(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[k]=Q(),this._result=this._state=void 0,this._subscribers=[],b!==t&&("function"!=typeof t&&Z(),this instanceof e?H(this,t):ee())}return e.prototype.catch=function(e){return this.then(null,e)},e.prototype.finally=function(e){var r=this,o=r.constructor;return t(e)?r.then(function(t){return o.resolve(e()).then(function(){return t})},function(t){return o.resolve(e()).then(function(){throw t})}):r.then(e,e)},e}();function re(){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 r=null;try{r=Object.prototype.toString.call(t.resolve())}catch(e){}if("[object Promise]"===r&&!t.cast)return}e.Promise=te}return te.prototype.then=A,te.all=X,te.race=K,te.resolve=I,te.reject=Y,te._setScheduler=l,te._setAsap=c,te._asap=a,te.polyfill=re,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 u{}u.rcSuccess="rcSuccess",u.rcBadSession="rcBadSession",u.rcDuplicateContact="rcDuplicateContact",u.rcWebServiceMoved="rcWebServiceMoved",u.rcAccessDenied="rcAccessDenied",u.rcLoginUserNameChanged="rcLoginUserNameChanged",u.rcLicenseExpired="rcLicenseExpired",exports.HttpMethod=void 0,(a=exports.HttpMethod||(exports.HttpMethod={})).get="get",a.post="post";class d{}d.absence="Absence",d.bonusType="BonusType",d.busyStatus="BusyStatus",d.cartType="CartType",d.companyType="CompanyType",d.contactType="ContactType",d.countryCode="CountryCode",d.currency="Currency",d.customFieldCategory="CustomFieldCategory",d.dayType="DayType",d.documentOfflineState="DocumentOfflineState",d.documentType="DocumentType",d.emailCampaignWorkflowStatus="EmailCampaignWorkflowStatus",d.emailOfflineState="EmailOfflineState",d.emailType="EmailType",d.familyStatus="FamilyStatus",d.firstContact="FirstContact",d.globalSettingsCategory="GlobalSettingsCategory",d.goalType="GoalType",d.groupColor="GroupColor",d.importance="Importance",d.journalType="JournalType",d.knowledgeLevel="KnowledgeLevel",d.knowledgeTitle="KnowledgeTitle",d.knowledgeType="KnowledgeType",d.leadType="LeadType",d.marketingType="MarketingType",d.paymentType="PaymentType",d.prefixType="PrefixType",d.productType="ProductType",d.projectOrigin="ProjectOrigin",d.projectType="ProjectType",d.reportCategory="ReportCategory",d.responseForm="ResponseForm",d.responseType="ResponseType",d.salaryDate="SalaryDate",d.salaryType="SalaryType",d.salePriceType="SalePriceType",d.sentimentTone="SentimentTone",d.suffixType="SuffixType",d.taskImportance="TaskImportance",d.tasksSnoozePeriod="TasksSnoozePeriod",d.taskStatus="TaskStatus",d.taskType="TaskType",d.trainingGrade="TrainingGrade",d.trainingTitle="TrainingTitle",d.translations="Translations",d.units="Units",d.userType="UserType",d.usStatesDistrictsTerritories="USStatesDistrictsTerritories",d.vacationType="VacationType",d.vat="VAT",d.workLoad="WorkLoad",d.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.contactsSuggestions="ContactsSuggestions",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.xsltTransformationsModels="XsltTransformationsModels",m.getEnumTypeName=e=>e===m.bonuses?d.bonusType:e===m.carts?d.cartType:e===m.companies?d.companyType:e===m.contacts?d.contactType:e===m.documents?d.documentType:e===m.emails?d.emailType:e===m.goals?d.goalType:e===m.goods?d.productType:e===m.journal?d.journalType:e===m.knowledge?d.knowledgeType:e===m.leads?d.leadType:e===m.marketing?d.marketingType:e===m.projects?d.projectType:e===m.salaries?d.salaryType:e===m.salePrices?d.salePriceType:e===m.tasks?d.taskType:e===m.training?d.trainingTitle:e===m.users?d.userType:e===m.vacation?d.vacationType:e===m.workReports?d.workReportType:null,m.getFolderNameByEnumTypeName=e=>e===d.bonusType?m.bonuses:e===d.cartType?m.carts:e===d.companyType?m.companies:e===d.contactType?m.contacts:e===d.documentType?m.documents:e===d.emailType?m.emails:e===d.goalType?m.goals:e===d.journalType?m.journal:e===d.knowledgeType?m.knowledge:e===d.leadType?m.leads:e===d.marketingType?m.marketing:e===d.productType?m.goods:e===d.projectType?m.projects:e===d.salaryType?m.salaries:e===d.salePriceType?m.salePrices:e===d.taskType?m.tasks:e===d.trainingTitle?m.training:e===d.userType?m.users:e===d.vacationType?m.vacation:e===d.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.transformItem="TransformItem",p.canUnlinkItems="CanUnlinkItems",p.unlinkItems="UnlinkItems",p.getGoodsFinalPrices="GetGoodsFinalPrices",p.saveItemCopyRelation="SaveItemCopyRelation",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${p.getFolderNameForApiMethod(e)}`;class h{constructor(e,t,r,o,n,s){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 r=e.SessionId;if(!r){const e=new Error("Successful login but no session came.");if(!this.errorCallback)throw e;return void this.errorCallback(e)}t&&t(r)},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=r,this.clientMachineIdentifier=o,this.clientMachineName=n,this.errorCallback=s}}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,r,o,n,s,i=!1,a){if(n&&!s||!n&&s)throw new Error("If codeChallenge is defined, codeChallengeMethod must also be defined and vice versa");let l=`https://login.eway-crm.${i?"dev":"com"}?scope=${encodeURIComponent(t.join(" "))}&prompt=login&response_type=code&redirect_uri=${encodeURIComponent(r)}&client_id=${e}`;return o&&(l+=`&state=${encodeURIComponent(o)}`),n&&s&&(l+=`&code_challenge=${encodeURIComponent(n)}&code_challenge_method=${encodeURIComponent(s)}`),a&&(l+=`&url=${encodeURIComponent(a)}`),l}}C.finishAuthorization=(e,t,r,o,n,s,i)=>{const a=new URLSearchParams;a.append("code_verifier",o),a.append("client_id",t),a.append("client_secret",r),a.append("code",n),a.append("redirect_uri",s),a.append("grant_type","authorization_code"),C.callTokenEndpoint(e,a,i)},C.refreshToken=(e,t,r,o,n)=>{const s=new URLSearchParams;s.append("client_id",t),s.append("client_secret",r),s.append("refresh_token",o),s.append("grant_type","refresh_token"),C.callTokenEndpoint(e,s,n)},C.getWebServiceUrl=e=>{const t=e.split(".");if(2!==t.length)throw new Error("Invalid token supplied");return s.decode(t[1])},C.getUserName=e=>C.decodeAccessToken(e).username,C.decodeAccessToken=e=>r(e),C.callTokenEndpoint=(t,r,o)=>{e.post(t+"/auth/connect/token",r,{headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(e=>{o(e.data)}).catch(e=>{e.response&&400==e.response.status?o(e.response.data):o({error:"Token request failed"})})};class f extends Error{constructor(e,t){super(),this.returnCode=e,this.message=t}}class P{constructor(e,t,r,o,n){if(this.invalidateSessionId=(e,t)=>{t&&t()},this.getSessionId=(e,t)=>{const r={userName:this.username,appVersion:this.appVersion,createSessionCookie:e.supportsGetItemPreviewMethod},o={Authorization:"Bearer "+this.accessToken};e.callWithoutSession(p.logIn,r,e=>{this.lastSuccessfulLoginResponse=e;const r=e.SessionId;if(!r){const e=new Error("Successful login but no session came.");if(!this.errorCallback)throw e;return void this.errorCallback(e)}t&&t(r)},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,r=>{if(401!==(null==r?void 0:r.statusCode)){if(!this.errorCallback)throw r;this.errorCallback(r)}else this.getNewAccessTokenCallback(e,r=>{this.accessToken=r.accessToken,r.error||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=r,this.getNewAccessTokenCallback=o,this.errorCallback=n}}class g extends P{constructor(e,t,r,o,n,s,i,a){if(!(e&&o&&t&&r))throw new Error("Non of the arguments 'username', 'clientId', 'clientSecret', 'refreshToken' can be empty.");super(e,n,s,(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)))}void 0!==e.error?t({error:e.error}):t({accessToken:e.access_token})})},i),this.refreshToken=o,this.clientId=t,this.clientSecret=r,this.refreshTokenCallback=a}}class T extends Error{constructor(e,t){super(),this.statusCode=e,this.message=t}}class E{}E.stringifyError=e=>JSON.stringify(e,E.replaceErrors),E.replaceErrors=(e,t)=>{if(t instanceof Error){const e={};return Object.getOwnPropertyNames(t).forEach(r=>{e[r]=t[r]}),e}return t};class S{constructor(t,r,o,n){if(this.ensureLogin=()=>new Promise((e,t)=>{if(this.sessionId)e();else{const r=r=>{r&&(this.sessionId=r,e()),t("Session Id cannot be empty")};this.sessionHandler.getSessionId(this,r)}}),this.createOpenLink=(e,t,r,o)=>{const n=s.encode(this.baseUri);let i="eway://"+t;r&&(i+="/"+(null==r?void 0:r.toLowerCase()));const a=e?"open.eway-crm.dev":"open.eway-crm.com";i=s.encode(i);let l="https://"+a+"/?ws="+n+"&l="+i;return o&&(l+="&n="+encodeURIComponent(o)),l},this.askUploadMethod=(e,t,r,o,n)=>new Promise((s,i)=>{const a=n?e=>{throw i(e),e}:i;this.callUploadMethod(e,t,r,s,a,a,o)}),this.callUploadMethod=(t,r,o,n,s,i,a)=>{const l=()=>{this.sessionHandler.getSessionId(this,e=>{this.sessionId=e,this.callUploadMethod(t,r,o,n,s,i,a)})},c=this.sessionId;if(!c)return void l();const d=`${this.svcUri}/SaveBinaryAttachment?sessionId=${this.sessionId}&itemGuid=${t}&fileName=${encodeURIComponent(r)}`,m=e.post(d,o,a);S.handleCallPromise(m,n,e=>{if(e.ReturnCode===u.rcBadSession)return this.sessionId=null,void this.sessionHandler.invalidateSessionId(c,l);if(s)s(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 "+d+": "+E.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,r,o)=>new Promise((n,s)=>{const i=o?e=>{throw s(e),e}:s;this.callMethod(e,t,n,i,r,i)}),this.callMethod=(e,t,r,o,n,s)=>{n||(n=exports.HttpMethod.post);const i=()=>{this.sessionHandler.getSessionId(this,i=>{this.sessionId=i,this.callMethod(e,t,r,o,n,s)})},a=this.sessionId;if(!a)return void i();t.sessionId=a;const l=e!==p.logOut?r:e=>{this.sessionId=null,r(e)};this.callWithoutSession(e,t,l,r=>{if(r.ReturnCode!==u.rcBadSession||(this.sessionId=null,e===p.logOut))if(o)o(r);else{const e=new Error("Unhandled connection return code "+r.ReturnCode+": "+r.Description);if(!this.errorCallback)throw e;this.errorCallback(e,t)}else this.sessionHandler.invalidateSessionId(a,i)},null,n,s)},this.callWithoutSession=(t,r,o,n,s,i,a)=>{var l;i||(i=exports.HttpMethod.post);const c=this.svcUri+"/"+t;let u,d;switch(s&&(u={headers:s,withCredentials:null!==(l=this.supportGetItemPreviewMethod)&&void 0!==l?l:t==p.logIn}),i){case exports.HttpMethod.get:if(r)throw new Error("Calling api get method with data specified does not make any sense.");d=e.get(c,u);break;case exports.HttpMethod.post:d=e.post(c,r,u);break;default:throw new Error(`Unknown http method '${i}'.`)}S.handleCallPromise(d,o,n,e=>{if(a)try{a(e)}catch(e){if(!this.errorCallback)throw e;this.errorCallback(e,r)}else{const t=new Error("Unhandled connection error when calling "+c+": "+E.stringifyError(e));if(!this.errorCallback)throw t;this.errorCallback(t,r)}})},this.getItemPreviewGetMethodUrl=(e,t,r)=>this.svcUri+"/"+p.getItemPreview+"?folderName="+encodeURIComponent(e)+"&itemGuid="+encodeURIComponent(t)+(r||0===r?"&itemVersion="+encodeURIComponent(r.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.getTransformItemMethodUrl=(e,t,r,o)=>`${this.svcUri}/${p.transformItem}?itemGuid=${encodeURIComponent(e)}&itemFolderName=${encodeURIComponent(t)}&transformationGuid=${encodeURIComponent(r)}&outputFormat=${o}`,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=S.normalizeWsUrl(t)||t,"https://"===t.substr(0,8).toLowerCase()?this.svcUri=this.baseUri+"/API.svc":this.svcUri=this.baseUri+"/InsecureAPI.svc";this.sessionHandler=r,this.errorCallback=o,this.sessionId=null,this.supportGetItemPreviewMethod=null!=n&&n}get supportsGetItemPreviewMethod(){return this.supportGetItemPreviewMethod}static create(e,t,r,o,n,s,i,a){return new S(e,new h(t,r,o,n,s,i),i,a)}static createAnonymous(e,t){return new S(e,new y,t)}static createUsingOAuth(e,t,r,o,n,s,i,a,l,c){return new S(e,new g(t,r,o,n,s,i,a,l),a,c)}static normalizeWsUrl(e){return e&&e.endsWith("/")&&(e=e.substring(0,e.length-1)),e}static isCloudUrl(e,t){const r=new URL(e),o=new Set;return o.add("hosting.eway-crm.com"),o.add("free.eway-crm.com"),o.add("hosting.eway-crm.us"),o.add("hosting-vh39276.eway-crm.us"),o.add("free.eway-crm.us"),t&&(o.add("free.eway-crm.dev"),o.add("hosting.eway-crm.dev"),o.add("localhost")),o.has(r.host)}get wsUrl(){return this.baseUri}static handleCallPromise(e,t,r,o){e.then(e=>{200===e.status?e.data.ReturnCode===u.rcSuccess?t(e.data):r(e.data):o(new T(e.status,e.statusText))}).catch(e=>{e.response?o(new T(e.response.status,e.response.statusText)):o(e)})}}class v{constructor(e,t,r,o,n,s,i){this.isEnabled=(e,t)=>{const r=()=>{this.url&&this.token?e(this.url,this.token):t()};this.url&&this.token?e(this.url,this.token):this.obtainToken(r)},this.callTokenizedApi=(e,t,r,o)=>{this.isEnabled((n,s)=>{t.token=s,v.call(n,e,t,r,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,r,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 r=this.urlAndTokenObtainer(t);r.url&&r.token?(this.url=r.url,this.token=r.token,this.isActive=!0,e()):(this.url=null,this.token=null,this.isActive=!1,e())},r=()=>{this.url=null,this.token=null,this.isActive=!1,e()};this.needsSession?this.connection.callMethod(this.obtainTokenMethodName,{},t,r,this.obtainTokenMethodType):this.connection.callWithoutSession(this.obtainTokenMethodName,null,t,r,null,this.obtainTokenMethodType)},this.obtainTokenMethodName=e,this.obtainTokenMethodType=t,this.needsSession=r,this.invalidTokenReturnCode=o,this.urlAndTokenObtainer=n,this.connection=s,this.generalErrorCallback=i||null,this.url=null,this.token=null,this.isActive=!0}static call(t,r,o,n,s,i){const a=t+"/"+r;e.post(a,o).then(e=>{200===e.status?"Success"===e.data.ReturnCodeString?n(e.data):s(e.data):i(new T(e.status,e.statusText))}).catch(e=>{e.response?i(new T(e.response.status,e.response.statusText)):i(e)})}}const I=e=>({url:e.ServiceUrl,token:e.Token});class A{}A.acceptableBackwardWorkReportDays="AcceptableBackwardWorkReportDays",A.adminAppInactiveLogoutTime="AdminAppInactiveLogoutTime",A.applyGeneralDataProtectionRules="ApplyGeneralDataProtectionRules",A.automaticallyCreateJournalAfterCallDuration="AutomaticallyCreateJournalAfterCallDuration",A.bonusesCompletedState="BonusesCompletedState",A.cartInvoicedState="CartInvoicedState",A.cartOrderCanceledState="CartOrderCanceledState",A.cartOrderInProcessState="CartOrderInProcessState",A.cartOrderProcessedState="CartOrderProcessedState",A.cartPaidState="CartPaidState",A.cartProposalInProcessState="CartProposalInProcessState",A.cartProposalProcessedState="CartProposalProcessedState",A.cartSalesVoucherIssuedState="CartSalesVoucherIssuedState",A.cartToBeInvoicedState="CartToBeInvoicedState",A.cartVoidedState="CartVoidedState",A.clickToCallScheme="ClickToCallScheme",A.companyDuplicityCheckEnabled="CompanyDuplicityCheckEnabled",A.completedStateName="CompletedStateName",A.contactDuplicityCheckEnabled="ContactDuplicityCheckEnabled",A.createCompanyWhileImportingContactFromOutlook="CreateCompanyWhileImportingContactFromOutlook",A.defaultProposalValidityPeriod="DefaultProposalValidityPeriod",A.enableContactsTwoWaySyncWithM365="EnableContactsTwoWaySyncWithM365",A.deadStateName="DeadStateName",A.enableCompaniesSyncIntoMobileDeviceContacts="EnableCompaniesSyncIntoMobileDeviceContacts",A.enableContactsSyncIntoMobileDevice="EnableContactsSyncIntoMobileDevice",A.enableLeadsSyncIntoMobileDeviceContacts="EnableLeadsSyncIntoMobileDeviceContacts",A.enableLlamaAiFeatures="EnableLlamaAiFeatures",A.enableUsersSyncIntoMobileDeviceContacts="EnableUsersSyncIntoMobileDeviceContacts",A.emailsActiveProjectsLeadsFilter="EmailsActiveProjectsLeadsFilter",A.exchangeRatesAdminGroupName="ExchangeRatesAdminGroupName",A.forcedEmailTrackingGroups="ForcedEmailTrackingGroups",A.ignoreEmailsFromDomainsOnEmailsTracking="IgnoreEmailsFromDomainsOnEmailsTracking",A.trackEmailsFromDomains="TrackEmailsFromDomains",A.groupsForAllUnpaidInvoicesNotification="GroupsForAllUnpaidInvoicesNotification",A.itemPreviewMaxHeight="ItemPreviewMaxHeight",A.lastActivityAttributes="LastActivityAttributes",A.leadsCompletedState="LeadsCompletedState",A.leadDeadlineAlertGroups="LeadDeadlineAlertGroups",A.leadsDeadState="LeadsDeadState",A.marketingCompletedState="MarketingCompletedState",A.marketingDeadState="MarketingDeadState",A.minimumPasswordLength="MinimumPasswordLength",A.nextStepAttributes="NextStepAttributes",A.notifyAboutInvoicedInvoiceInPohodaGroup="NotifyAboutInvoicedInvoiceInPohodaGroup",A.notifyAboutLeadsDeadline="NotifyAboutLeadsDeadline",A.notifyAboutPaidInvoiceInPohodaGroup="NotifyAboutPaidInvoiceInPohodaGroup",A.notifyAboutProjectDeadline="NotifyAboutProjectDeadline",A.numberOfDecimalPlaces="NumberOfDecimalPlaces",A.phoneListTaskSolverGroup="PhoneListTaskSolverGroup",A.projectDeadlineAlert="ProjectDeadlineAlert",A.serverUpdateProgressNotificationGroup="ServerUpdateProgressNotificationGroup",A.sumarizeCartsPricesOnLeads="SumarizeCartsPricesOnLeads",A.sumarizeCartsPricesOnProjects="SumarizeCartsPricesOnProjects",A.sumarizePeopleExpensesOnProjects="SumarizePeopleExpensesOnProjects",A.systemHealthNotificationGroup="SystemHealthNotificationGroup",A.tasksCompletedState="TasksCompletedState",A.tasksDeferredState="TasksDeferredState",A.tasksInProgressState="TasksInProgressState",A.tasksNotStartedState="TasksNotStartedState",A.tasksWaitOnSomeoneElseState="TasksWaitOnSomeoneElseState",A.trackDocumentVersions="TrackDocumentVersions",A.vacationCompletedState="VacationCompletedState",A.workReportApprovedState="WorkReportApprovedState",A.defaultLanguage="DefaultLanguage",A.defaultCurrency="DefaultCurrency",A.myCompanyCountry="MyCompanyCountry",A.myCompanyName="MyCompanyName",A.myCompanyStreet="MyCompanyStreet",A.myCompanyCity="MyCompanyCity",A.myCompanyState="MyCompanyState",A.myCompanyZip="MyCompanyZIP",A.myCompanyId="MyCompanyID",A.myCompanyVat="MyCompanyVAT",A.mergeGoodsInCart="MergeGoodsInCart",A.cartRefreshLogic="CartRefreshLogic",A.goodsDefaultQuantity="GoodsDefaultQuantity",A.goodsDefaultVAT="GoodsDefaultVAT",A.goodsDefaultVATIncluded="GoodsDefaultVATIncluded";class k{}k.ServerCommon={Server_ID:"Server_ID",Server_ItemCreated:"Server_ItemCreated",Server_ItemChanged:"Server_ItemChanged"},k.Common={CreatedByGUID:"CreatedByGUID",CurrencyEn:"CurrencyEn",DefaultCurrencySuffix:"DefaultCurrency",FileAs:"FileAs",ItemCreated:"ItemCreated",ItemChanged:"ItemChanged",ItemGUID:"ItemGUID",ItemVersion:"ItemVersion",ModifiedByGUID:"ModifiedByGUID",OwnerGUID:"OwnerGUID",ParentCurrencySuffix:"ParentCurrency"},k.Calendar={EndDate:"EndDate",Note:"Note"},k.Carts={SuperiorItem:"SuperiorItem",Customer:"Customer",Contact:"Contact",TypeEn:"TypeEn",StateEn:"StateEn",PriceTotal:"PriceTotal",PriceTotalExcludingVAT:"PriceTotalExcludingVAT",ForPayment:"ForPayment",Paid:"Paid",CurrencyEn:"CurrencyEn",EffectiveFrom:"EffectiveFrom",ValidUntil:"ValidUntil",Active:"Active",Note:"Note",ID:"ID",AccountingCaseDate:"AccountingCaseDate",TaxableSupplyDate:"TaxableSupplyDate",PaymentDate:"PaymentDate",VAT:"VAT",GoodsInCartCount:"GoodsInCartCount",PriceTotalDefaultCurrency:"PriceTotalDefaultCurrency",PriceTotalParentCurrency:"PriceTotalParentCurrency",ForPaymentDefaultCurrency:"ForPaymentDefaultCurrency",ForPaymentParentCurrency:"ForPaymentParentCurrency",PaidDefaultCurrency:"PaidDefaultCurrency",PaidParentCurrency:"PaidParentCurrency",PaidChanged:"PaidChanged",PriceTotalChanged:"PriceTotalChanged",PriceTotalExcludingVATDefaultCurrency:"PriceTotalExcludingVATDefaultCurrency",PriceTotalExcludingVATParentCurrency:"PriceTotalExcludingVATParentCurrency",VATDefaultCurrency:"VATDefaultCurrency",VATParentCurrency:"VATParentCurrency",PrevStateEn:"PrevStateEn",PurchaseExpenses:"PurchaseExpenses",PurchaseExpensesDefaultCurrency:"PurchaseExpensesDefaultCurrency",PurchaseExpensesParentCurrency:"PurchaseExpensesParentCurrency",PurchaseExpensesChanged:"PurchaseExpensesChanged",Profit:"Profit",ProfitDefaultCurrency:"ProfitDefaultCurrency",ProfitParentCurrency:"ProfitParentCurrency",ProfitChanged:"ProfitChanged"},k.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",TrackedDomains:"TrackedDomains",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"},k.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"},k.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:k.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"},k.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",ExternalUrl:"ExternalUrl"},k.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"},k.GoodsBase={Code:"Code",Structure:"Structure",Note:"Note",Description:"Description",TypeEn:"TypeEn",SaleCurrencyEn:"SaleCurrencyEn",PurchaseCurrencyEn:"PurchaseCurrencyEn",UnitEn:"UnitEn",PurchasePrice:"PurchasePrice",PurchasePriceDefaultCurrency:"PurchasePriceDefaultCurrency",PurchasePriceChanged:"PurchasePriceChanged",SalePrice:"SalePrice",SalePriceDefaultCurrency:"SalePriceDefaultCurrency",SalePriceChanged:"SalePriceChanged",IsPriceSum:"IsPriceSum",VATRate:"VATRate",VATIncluded:"VATIncluded"},k.Goods=Object.assign(Object.assign({},k.GoodsBase),{PriceListGroupGUID:"PriceListGroupGUID",InventoryQuantity:"InventoryQuantity"}),k.GoodsInCart=Object.assign(Object.assign({},k.GoodsBase),{Cart:"Cart",GoodsInfo:"GoodsInfo",SuperiorItem:"SuperiorItem",Quantity:"Quantity",PriceTotal:"PriceTotal",PriceTotalDefaultCurrency:"PriceTotalDefaultCurrency",PriceTotalParentCurrency:"PriceTotalParentCurrency",PriceTotalChanged:"PriceTotalChanged",PriceTotalExcludingVAT:"PriceTotalExcludingVAT",PriceTotalExcludingVATDefaultCurrency:"PriceTotalExcludingVATDefaultCurrency",PriceTotalExcludingVATParentCurrency:"PriceTotalExcludingVATParentCurrency",VATTotal:"VATTotal",VATTotalDefaultCurrency:"VATTotalDefaultCurrency",VATTotalParentCurrency:"VATTotalParentCurrency",SalePriceExcludingVAT:"SalePriceExcludingVAT",SalePriceExcludingVATDefaultCurrency:"SalePriceExcludingVATDefaultCurrency",SalePriceExcludingVATParentCurrency:"SalePriceExcludingVATParentCurrency",VAT:"VAT",VATDefaultCurrency:"VATDefaultCurrency",VATParentCurrency:"VATParentCurrency",PurchasePriceParentCurrency:"PurchasePriceParentCurrency",SalePriceParentCurrency:"SalePriceParentCurrency",ListPrice:"ListPrice",ListPriceDefaultCurrency:"ListPriceDefaultCurrency",ListPriceParentCurrency:"ListPriceParentCurrency",ListPriceChanged:"ListPriceChanged",Discount:"Discount",HierarchyInSet:"HierarchyInSet",IsFromSet:"IsFromSet",ParentGUID:"ParentGUID",Rank:"Rank",IncludeInCartPrice:"IncludeInCartPrice",ListPriceCustomized:"ListPriceCustomized",ChildItemsCount:"ChildItemsCount",JoinedToGUID:"JoinedToGUID",PurchasePriceTotal:"PurchasePriceTotal",PurchasePriceTotalDefaultCurrency:"PurchasePriceTotalDefaultCurrency",PurchasePriceTotalParentCurrency:"PurchasePriceTotalParentCurrency",PurchasePriceTotalChanged:"PurchasePriceTotalChanged"}),k.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"},k.Vacation={StartDate:"StartDate",EndDate:"EndDate",User:"User",Duration:"Duration",Place:"Place",Note:"Note",AllDay:"AllDay",TypeEn:"TypeEn",StateEn:"StateEn",IsPrivate:"Private"},k.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"},k.Projects={HumanID:"HID",FileAs:"FileAs",ProjectName:"ProjectName",ProjectOriginEn:"ProjectOriginEn",TypeEn:"TypeEn",StateEn:"StateEn",PaymentTypeEn:"PaymentTypeEn",ProjectStart:"ProjectStart",ProjectRealEnd:"ProjectRealEnd",EstimatedEnd:"ProjectEnd",CurrencyEn:k.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"},k.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"},k.Training={TitleEn:"TitleEn"},k.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"},k.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"},k.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"},k.PriceListGroups={Note:"Note"},k.Prices={SalePriceGUID:"SalePriceGUID",GoodsItemGUID:"GoodsItemGUID",Price:"Price",CurrencyEn:"CurrencyEn"},k.SalePrices={Note:"Note",Discount:"Discount",TypeEn:"TypeEn",StateEn:"StateEn",PrevStateEn:"PrevStateEn"},k.XsltTransformations={LangCode:"LangCode",Definition:"Definition",Namespace:"Namespace",ObjectTypeID:"ObjectTypeID",TransformationVersion:"TransformationVersion"},k.XsltTransformationsModels={ObjectTypeID:"ObjectTypeID",TransformationGUID:"TransformationGUID",ItemTypeGUID:"ItemTypeGUID"},k.allTypeEnNames=["TypeEn",k.Documents.DocTypeEn,k.WorkReports.WorkReportEn,"TitleEn"],k.getFolderFileAs=e=>{switch(e){case m.leads:return k.Leads.FileAs;case m.projects:return k.Projects.ProjectName;case m.documents:return k.Documents.DocName;case m.companies:return k.Companies.CompanyName;case m.contacts:case m.users:return k.Common.FileAs;case m.emails:return k.Emails.Subject;case m.journal:return k.Journal.FileAs;case m.tasks:return k.Tasks.Subject;case m.workReports:return k.WorkReports.Subject;case m.vacation:return k.Vacation.TypeEn;case m.carts:case m.goods:case m.goodsInCart:return k.Common.FileAs;case m.groups:return k.Groups.GroupName;case m.xsltTransformations:return k.Common.FileAs;default:return console.warn(`FileAs col name not defined for folderName ${e}`),k.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",b.projectOrigin="PROJECT_ORIGIN",b.cart="CART",b.goodsInCart="GOODSINCART",b.superiorItem="SUPERIORITEM";class D{}D.general=1,D.group=2,D.contactPerson=10,D.contact=11,D.customer=12,D.company=13,D.outlookProject=28,D.supervisor=32,D.projectOrigin=25,D.cart=9,D.goodsInCart=15,D.superiorItem=31;class w{}w.all="All",w.own="Own",w.readonly="Readonly",w.invisible="Invisible",w.none="None";class x{}var F,O,N,R;x.mandatory="Mandatory",x.optional="Optional",x.unique="Unique",x.none="None",exports.Edition=void 0,(F=exports.Edition||(exports.Edition={})).Free="Free",F.Basic="Basic",F.Professional="Professional",F.Enterprise="Enterprise",exports.Feature=void 0,(O=exports.Feature||(exports.Feature={})).ContactsAndCompanies="ContactsAndCompanies",O.Sales="Sales",O.Projects="Projects",O.Marketing="Marketing",exports.SentimentTone=void 0,(N=exports.SentimentTone||(exports.SentimentTone={}))[N.Negative=0]="Negative",N[N.Neutral=1]="Neutral",N[N.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 V{}V.contactsAutomaticSynchronizationWithOutlook="ContactsAutomaticSynchronizationWithOutlook",V.contactsSynchronizationWithOutlook="ContactsSynchronizationWithOutlook",V.contactsSynchronizationWithAndroid="ContactsSynchronizationWithAndroid",V.documentsRevisions="DocumentsRevisions",V.wordAddin="WordAddin",V.excelAddin="ExcelAddin",V.tasksReminders="TasksReminders",V.tasksRecurrentTasks="TasksRecurrentTasks",V.tasksSubtasks="TasksSubtasks",V.tasksSynchronizationWithOutlook="TasksSynchronizationWithOutlook",V.calendarSynchronizationWithOutlook="CalendarSynchronizationWithOutlook",V.emailsManualTracking="EmailsManualTracking",V.emailsAutomaticTracking="EmailsAutomaticTracking",V.emailSummaryAndSentimentToneFromAi="EmailSummaryAndSentimentToneFromAi",V.convertEmailToContact="ConvertEmailToContact",V.convertEmailToDeal="ConvertEmailToDeal",V.convertEmailToProject="ConvertEmailToProject",V.convertEmailToTask="ConvertEmailToTask",V.convertFromSuggestedContact="ConvertFromSuggestedContact",V.gravatarIntegration="GravatarIntegration",V.logoboxIntegration="LogoboxIntegration",V.companiesBussinesRegisterApiIntegration="CompaniesBussinesRegisterApiIntegration",V.duplicityChecker="DuplicityChecker",V.nextStepAndLastActivityCustomization="NextStepAndLastActivityCustomization",V.subProjects="SubProjects",V.resourceAndPlanning="ResourceAndPlanning",V.professionalEmailCampaigns="ProfessionalEmailCampaigns",V.professionalEmailCampaignsAdvancedStatistics="ProfessionalEmailCampaignsAdvancedStatistics",V.wordEmailMerge="WordEmailMerge",V.printLabels="PrintLabels",V.printEnvelopes="PrintEnvelopes",V.userViews="UserViews",V.sharedUserViews="SharedUserViews",V.gridRowSummary="GridRowSummary",V.gridConditionalFormating="GridConditionalFormating",V.multipleCurrencies="MultipleCurrencies",V.historyTracking="HistoryTracking",V.privateItems="PrivateItems",V.itemTypes="ItemTypes",V.formLayoutCustomization="FormLayoutCustomization",V.workflowBasicDefinitions="WorkflowBasicDefinitions",V.workflowAdvancedDefinitions="WorkflowAdvancedDefinitions",V.workflowAdvancedDefinitionsRules="WorkflowAdvancedDefinitionsRules",V.workflowAdvancedDefinitionsActions="WorkflowAdvancedDefinitionsActions",V.workflowGroupLevelActions="WorkflowGroupLevelActions",V.customFields="CustomFields",V.importantFields="ImportantFields",V.mandatoryFields="MandatoryFields",V.uniqueFields="UniqueFields",V.readOnlyFields="ReadOnlyFields",V.transformationCustomTemplates="TransformationCustomTemplates",V.userRoles="UserRoles",V.modulePermissions="ModulePermissions",V.columnPermissions="ColumnPermissions",V.commonDataAPI="CommonDataAPI",V.eWayCrmAPI="eWayCrmAPI",V.threeCXIntegration="ThreeCXIntegration",V.tapiIntegration="TapiIntegration",V.pohodaIntegration="PohodaIntegration",V.pohodaSynchronizationIntervalCustomization="PohodaSynchronizationIntervalCustomization",V.pohodaSynchronizationFieldMappingCustomization="PohodaSynchronizationFieldMappingCustomization",V.quickBooksIntegration="QuickBooksIntegration",V.shareByTeams="ShareByTeams",V.convertEmailToContactWithDataFromAi="ConvertEmailToContactWithDataFromAi",V.convertEmailToDealWithDataFromAi="ConvertEmailToDealWithDataFromAi",V.convertEmailToProjectWithDataFromAi="ConvertEmailToProjectWithDataFromAi",function(e){e.UnpaidImportantInvoices="UnpaidImportantInvoices",e.UncollectableSubscriptionPayment="UncollectableSubscriptionPayment",e.UncollectableSubscriptionPaymentWithExpiredCard="UncollectableSubscriptionPaymentWithExpiredCard",e.StandardSubscriptionPeriod="StandardSubscriptionPeriod"}(R||(R={}));var _,U=R;!function(e){e.License="License",e.CloudLicense="CloudLicense",e.MiscLicense="MiscLicense",e.Support="Support",e.Service="Service"}(_||(_={}));var G=_;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 r;const o=null===(r=e.sessionHandler.lastSuccessfulLoginResponse)||void 0===r?void 0:r.WcfVersion;return!!o&&j.supportsVersionFeaturesOf(o,t)},j.supportsVersionFeaturesOf=(e,t)=>o.compare(e,t,">=")||o.compare(e,"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 B={[m.relations]:0,[m.unifiedRelations]:1,[m.users]:2,[m.groups]:3,[m.enumTypes]:4,[m.enumValues]:5,[m.additionalFields]:6};var H,z,Q,$;exports.Version=void 0,(H=exports.Version||(exports.Version={})).Version75="7.5",H.Version76="7.6",H.Version77="7.7",H.Version80="8.0",H.Version81="8.1",H.Version82="8.2",H.Version83="8.3",H.Version90="9.0",H.Version91="9.1",H.Version92="9.2",H.Version93="9.3",H.Version94="9.4";class q extends j{}q.is75OrLater=e=>j.supportsFeaturesOf(e,exports.Version.Version75),q.is76OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version76),q.is77OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version77),q.is80OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version80),q.is81OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version81),q.is82OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version82),q.is83OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version83),q.is90OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version90),q.is91OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version91),q.is92OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version92),q.is93OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version93),q.is94OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version94),q.isFeatureSupported=(e,t)=>q.supportsFeaturesOf(e,t);class J{static mainTable(){return{__type:"MainTable:#EQ"}}static relation(e,t,r){return{__type:"Relation:#EQ",Direction:r,ItemTypes:e,RelationType:t}}static join(e,t,r){const o={__type:"Join:#EQ",ItemType:e,Key:t};return r&&(o.TargetColumnName=r),o}static hubRelation(e){const{isToParentDirection:t,childrenFolderNames:r}=e,o={__type:"HubRelation:#EQ"};return void 0!==typeof t&&(o.IsToParentDirection=t),r&&(o.ChildrenFolderNames=r),o}}class K{static createHubItemsCountsQuery(e,t,r){return{__type:"HubItemsCountsQuery:#EQ",ParentItemGuids:e,ItemTypes:t,ExcludeSystemItems:r}}static createRelatedTableQuery(e,t,r){return{__type:r?"RelatedTableQuery:#EQ":"TypelessRelatedTableQuery:#EQ",BaseItemID:e,ItemTypes:Array.isArray(t)?t:[t],RelationType:r}}static createMainTableQuery(e){return{__type:"MainTableQuery:#EQ",ItemTypes:Array.isArray(e)?e:[e]}}}K.column=e=>({__type:"Column:#EQ",Source:J.mainTable(),Name:e}),K.multiSelectComboColumnLegacy=(e,t,r)=>({__type:"Column:#EQ",Source:J.mainTable(),Name:"ItemGUID",Transformation:`[dbo].[GetConcatenatedEnumValuesRelationsValues]({0}, '${e}', '${t}'`,Alias:null!=r?r:e}),K.multiSelectComboColumn=(e,t,r,o,n)=>{if(!q.is77OrLater(e))return K.multiSelectComboColumnLegacy(r,o,n);return{__type:"Column:#EQ",Source:J.mainTable(),Name:"ItemGUID",Transformation:`[dbo].[GetConcatenatedEnumValuesRelationsValues_WithObjectTypeID]({0}, dbo.GetObjectTypeID('${t}'), '${r}', '${o}')`,Alias:null!=n?n:r}},K.joinColumn=(e,t,r,o,n)=>K.joinColumnFromKey(e,K.column(t),r,o,n),K.joinColumnFromKey=(e,t,r,o,n)=>{const s={__type:"Column:#EQ",Source:J.join(e,t,n),Name:r};return o&&(s.Alias=o),s},K.singleVariatedColumn=(e,t,r)=>K.variatedColumn([K.columnVariation(e,t)],r),K.variatedColumn=(e,t)=>{const r={__type:"VariatedColumn:#EQ",Source:J.mainTable(),Variations:e};return t&&(r.Alias=t),r},K.columnVariation=(e,t,r)=>{const o={FolderName:t,Field:{__type:"Column:#EQ",Source:J.mainTable(),Name:e}};return r&&(o.Field.Transformation=r),o},K.joinColumnVariation=(e,t,r,o)=>({FolderName:e,Field:{__type:"Column:#EQ",Source:J.join(t,K.column(r)),Name:o}}),K.relationColumnVariation=(e,t,r,o)=>({FolderName:e,Field:{__type:"Column:#EQ",Source:J.relation(r,t,1),Name:o}}),K.relatedColumn=(e,t,r,o)=>{const n={__type:"Column:#EQ",Source:J.relation(t,e,1),Name:r};return o&&(n.Alias=o),n},K.relatedSubstituableColumn=(e,t,r,o,n)=>{const s={__type:"SubstituableColumn:#EQ",Source:J.relation(t,e,1),Name:r,Substitute:o};return n&&(s.Alias=n),s},K.relatedColumnFolderNameToken=(e,t,r)=>({__type:"Token:#EQ",Source:J.relation(t,e,1),TypeName:"ItemType",Alias:r}),K.hubRelationColumn=(e,t)=>({__type:"Column:#EQ",Source:J.hubRelation(t),Name:e}),K.aggregateColumn=(e,t,r)=>({__type:"AggregateColumn:#EQ",FunctionName:e,Source:t.Source,AggregatedField:t,Alias:r}),K.folderNameToken=e=>({__type:"Token:#EQ",Source:J.mainTable(),TypeName:"ItemType",Alias:null!=e?e:"FolderName"}),K.equalsFilterExpression=(e,t)=>({__type:"EqualsFilterExpressionPredicate:#EQ",Field:e,Value:t}),K.notEqualsExpression=(e,t)=>({__type:"NotFilterExpression:#EQ",Child:K.equalsFilterExpression(e,t)}),K.andFilterExpression=e=>({__type:"AndFilterExpressionOperator:#EQ",Children:e}),K.orFilterExpression=e=>({__type:"OrFilterExpressionOperator:#EQ",Children:e}),K.lessFilterExpression=(e,t)=>({__type:"LessFilterExpressionPredicate:#EQ",Field:e,Value:t}),K.lessOrEqualFilterExpression=(e,t)=>({__type:"LessOrEqualFilterExpressionPredicate:#EQ",Field:e,Value:t}),K.greaterFilterExpression=(e,t)=>({__type:"GreaterFilterExpressionPredicate:#EQ",Field:e,Value:t}),K.greaterOrEqualFilterExpression=(e,t)=>({__type:"GreaterOrEqualFilterExpressionPredicate:#EQ",Field:e,Value:t}),K.likeFilterExpression=(e,t)=>({__type:"LikeFilterExpressionPredicate:#EQ",Field:e,Value:`%${t}%`}),K.inFilterExpression=(e,t)=>({__type:"InFilterExpressionPredicate:#EQ",Field:e,Value:t}),K.relatedToExpression=(e,t)=>({__type:"RelatedToFilterExpressionPredicate:#EQ",Value:e,RelationType:t}),K.isNullOrEmptyFilterExpression=e=>K.orFilterExpression([K.equalsFilterExpression(K.column(e),null),K.equalsFilterExpression(K.column(e),"")]);class X{static toRfc3339String(e){const t=e=>e<10?`0${e}`:String(e);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}${(e=>{if(0===e)return"Z";const r=e>0?"-":"+";return e=Math.abs(e),`${r}${t(Math.floor(e/60))}:${t(e%60)}`})(e.getTimezoneOffset())}`}}function Y(e,t,r,o){return new(r||(r=Promise))(function(n,s){function i(e){try{l(o.next(e))}catch(e){s(e)}}function a(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(i,a)}l((o=o.apply(e,t||[])).next())})}X.isValid=e=>e instanceof Date&&!isNaN(e.getTime()),X.areDaysEqual=(e,t)=>{const r=X.clearTime(e),o=X.clearTime(t);return r.getTime()===o.getTime()},X.areTimesEqual=(e,t)=>e.getHours()===t.getHours()&&e.getMinutes()===t.getMinutes(),X.areDatesEqual=(e,t)=>!!e&&!!t&&X.areDaysEqual(e,t)&&X.areTimesEqual(e,t),X.clearTime=e=>{const t=new Date(e);return t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setMilliseconds(0),t},X.isWithoutTime=e=>0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds(),X.getFormattedSqlDateTime=e=>e.toISOString().slice(0,19).replace("T"," "),X.getRfcWithoutTimezone=e=>e.slice(0,19),exports.TransformItemFormats=void 0,(z=exports.TransformItemFormats||(exports.TransformItemFormats={})).OpenXmlDocx="OpenXmlDocx",z.Pdf="Pdf",z.WordMlXml="WordMlXml","function"==typeof SuppressedError&&SuppressedError;exports.EnumTypeEditMode=void 0,(Q=exports.EnumTypeEditMode||(exports.EnumTypeEditMode={})).Readonly="Readonly",Q.VisibleRankDefaultOnly="VisibleRankDefaultOnly",Q.Editable="Editable",exports.ImportResult=void 0,($=exports.ImportResult||(exports.ImportResult={})).Success="Success",$.Failure="Failed",$.FailureDuplicityFound="Failed_DuplicityFound",$.FailureItemAlreadyRemoved="Failed_ItemAlreadyRemoved",$.FailureColumnsLockedWFAction="Failed_ColumnsLocked",$.FailureItemLockedWFAction="Failed_ItemLocked",$.FailureLicenseLimitReached="Failed_LicenseLimitReached",$.FailureInssuficientModulePermission="Failed_InsufficientModulePermission",$.FailureInssuficientColumnsPermission="Failed_InsufficientColumnsPermission",c.polyfill(),exports.ApiConnectionAsNonDefaultExport=S,exports.ApiFetchClient=class{constructor(e,t,r,o){let n;if(this.sessionId=null,this.isAdmin=null,this.loginResponse=null,!(r||(n=C.decodeAccessToken(t),r=n.ws)))throw new Error("Failed to get web service URL from JWT");if(!(o||(n||(n=C.decodeAccessToken(t)),o=n.username)))throw new Error("Failed to get username from JWT");this.appName=e,this.wsUrl=r,this.userName=o,this.endpoint=r.startsWith("http://")?"InsecureAPI.svc":"API.svc",this.accessToken=t}hasAdminRights(){return this.isAdmin}getWsUrl(){return this.wsUrl}getUserName(){return this.userName}getOutlookClientVersion(){var e;return null===(e=this.loginResponse)||void 0===e?void 0:e.OutlookClientVersion}getWebServiceVersion(){var e;return null===(e=this.loginResponse)||void 0===e?void 0:e.WcfVersion}login(){return Y(this,void 0,void 0,function*(){const e={userName:this.userName,appVersion:this.appName},t=new Request(`${this.wsUrl}/${this.endpoint}/Login`,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify(e)}),r=yield fetch(t),o=200===r.status?yield r.json():void 0;if(!o||"rcSuccess"!==o.ReturnCode)throw new Error(`Login failed: ${(null==o?void 0:o.Description)||"Unknown error"}`);this.sessionId=null==o?void 0:o.SessionId,this.isAdmin=null==o?void 0:o.IsAdmin,this.loginResponse=o})}logout(){return Y(this,void 0,void 0,function*(){const e=new Request(`${this.wsUrl}/${this.endpoint}/LogOut`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:this.sessionId})}),t=yield fetch(e);if("rcSuccess"!==(yield t.json()).ReturnCode)throw new Error("Failed to logout")})}getObjectTypes(){return Y(this,void 0,void 0,function*(){return(yield this.callMethod("GetObjectTypes",{})).Data})}getLicense(){return Y(this,void 0,void 0,function*(){return(yield this.callMethod("GetLicense",{})).Datum})}getClientVersionId(e){var t;return Y(this,void 0,void 0,function*(){const r={versionName:e};return null===(t=(yield this.callMethod("GetClientVersion",r)).Datum)||void 0===t?void 0:t.Id})}queryAmount(e,t=null){return Y(this,void 0,void 0,function*(){const r={query:{__type:"MainTableQuery:#EQ",ItemTypes:[e],Fields:[{__type:"Column:#EQ",Source:{__type:"MainTable:#EQ"},Name:"ItemGUID"}]}};return t&&(r.query.Filter=t),this.callMethod("QueryAmount",r)})}query(e,t=null,r=null,o=null){return Y(this,void 0,void 0,function*(){const n={query:{__type:"MainTableQuery:#EQ",ItemTypes:[e],Fields:t,Paging:{Skip:0,Take:500}}};return r&&(n.query.Filter=r),o&&(n.query.Sort=o),this.callMethod("Query",n)})}callMethod(e,t,r="POST"){return Y(this,void 0,void 0,function*(){if(!this.sessionId)throw new Error("Session ID is not set. Please call init() first.");t.sessionId=this.sessionId;const o=new Request(`${this.wsUrl}/${this.endpoint}/${e}`,{method:r,headers:{"Content-Type":"application/json"},body:"POST"===r?JSON.stringify(t):void 0}),n=yield fetch(o);if(!n.ok)throw new Error(`Error calling method ${e}: ${n.statusText}`);const s=200===n.status?yield n.json():void 0;if(!s||"rcSuccess"!==s.ReturnCode)throw new Error(`API call failed (${null==s?void 0:s.ReturnCode}): ${null==s?void 0:s.Description}`);return s})}static getTokenData(e,t,r,o,n){return Y(this,void 0,void 0,function*(){const s=new URLSearchParams;s.append("client_id",o),s.append("client_secret",n),s.append("code",t),s.append("redirect_uri",r),s.append("grant_type","authorization_code");const i=new Request(`${e}/auth/connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()}),a=yield fetch(i);if(!a.ok)throw new Error(`Error calling token endpoint: ${a.statusText}`);const l=yield a.json();if(!l||!l.access_token)throw new Error("Failed to get access token");return l})}},exports.ApiMethods=p,exports.ColumnPermissionMandatoryRules=x,exports.ColumnPermissionPermissionRules=w,exports.CommonDataConnection=class{constructor(e,t){this.isCommonDataApiEnabled=(e,t)=>{this.tokenizedConnection.isEnabled(e,t)},this.callCommonDataApi=(e,t,r,o)=>{this.tokenizedConnection.callTokenizedApi(e,t,r,o)},this.tokenizedConnection=new v("ObtainCommonDataApiAccessToken",exports.HttpMethod.get,!1,"InvalidCommonDataToken",I,e,t)}},exports.CustomizationStatsItemKeys=L,exports.DateHelper=X,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 r=((null==e?void 0:e.substr(0,1))||"")+((null==t?void 0:t.substr(0,1))||"");return""==r?null:r}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=d,exports.ErrorHelper=E,exports.ExpirationReason=U,exports.FieldNames=k,exports.FieldTypes=W,exports.FolderNames=m,exports.Functionality=M,exports.GlobalSettingsNames=A,exports.HttpRequestError=T,exports.LicenseKeyInvoiceSeverity=G,exports.LicenseRestrictionKeys=V,exports.OAuthHelper=C,exports.OAuthSessionHandlerBase=P,exports.ObjectTypeIds=B,exports.QueryHelper=K,exports.RelationTypeIds=D,exports.RelationTypes=b,exports.ReturnCodes=u,exports.StringHelper=class{static trim(e,t,r=!1){if(null==e)return e;let o=e.trim();return o.length<=t||(o=o.substring(0,t-(r?3:0)),r&&(o+="...")),o}},exports.TokenizedServiceConnection=v,exports.VersionHelper=q,exports.VersionHelperBase=j,exports.default=S;
8
+ */class u{}u.rcSuccess="rcSuccess",u.rcBadSession="rcBadSession",u.rcDuplicateContact="rcDuplicateContact",u.rcWebServiceMoved="rcWebServiceMoved",u.rcAccessDenied="rcAccessDenied",u.rcLoginUserNameChanged="rcLoginUserNameChanged",u.rcLicenseExpired="rcLicenseExpired",exports.HttpMethod=void 0,(a=exports.HttpMethod||(exports.HttpMethod={})).get="get",a.post="post";class d{}d.absence="Absence",d.bonusType="BonusType",d.busyStatus="BusyStatus",d.cartType="CartType",d.companyType="CompanyType",d.contactType="ContactType",d.countryCode="CountryCode",d.currency="Currency",d.customFieldCategory="CustomFieldCategory",d.dayType="DayType",d.documentOfflineState="DocumentOfflineState",d.documentType="DocumentType",d.emailCampaignWorkflowStatus="EmailCampaignWorkflowStatus",d.emailOfflineState="EmailOfflineState",d.emailType="EmailType",d.familyStatus="FamilyStatus",d.firstContact="FirstContact",d.globalSettingsCategory="GlobalSettingsCategory",d.goalType="GoalType",d.groupColor="GroupColor",d.importance="Importance",d.journalType="JournalType",d.knowledgeLevel="KnowledgeLevel",d.knowledgeTitle="KnowledgeTitle",d.knowledgeType="KnowledgeType",d.leadType="LeadType",d.marketingType="MarketingType",d.paymentType="PaymentType",d.prefixType="PrefixType",d.productType="ProductType",d.projectOrigin="ProjectOrigin",d.projectType="ProjectType",d.reportCategory="ReportCategory",d.responseForm="ResponseForm",d.responseType="ResponseType",d.salaryDate="SalaryDate",d.salaryType="SalaryType",d.salePriceType="SalePriceType",d.sentimentTone="SentimentTone",d.suffixType="SuffixType",d.taskImportance="TaskImportance",d.tasksSnoozePeriod="TasksSnoozePeriod",d.taskStatus="TaskStatus",d.taskType="TaskType",d.trainingGrade="TrainingGrade",d.trainingTitle="TrainingTitle",d.translations="Translations",d.units="Units",d.userType="UserType",d.usStatesDistrictsTerritories="USStatesDistrictsTerritories",d.vacationType="VacationType",d.vat="VAT",d.workLoad="WorkLoad",d.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.contactsSuggestions="ContactsSuggestions",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.xsltTransformationsModels="XsltTransformationsModels",m.getEnumTypeName=e=>e===m.bonuses?d.bonusType:e===m.carts?d.cartType:e===m.companies?d.companyType:e===m.contacts?d.contactType:e===m.documents?d.documentType:e===m.emails?d.emailType:e===m.goals?d.goalType:e===m.goods?d.productType:e===m.journal?d.journalType:e===m.knowledge?d.knowledgeType:e===m.leads?d.leadType:e===m.marketing?d.marketingType:e===m.projects?d.projectType:e===m.salaries?d.salaryType:e===m.salePrices?d.salePriceType:e===m.tasks?d.taskType:e===m.training?d.trainingTitle:e===m.users?d.userType:e===m.vacation?d.vacationType:e===m.workReports?d.workReportType:null,m.getFolderNameByEnumTypeName=e=>e===d.bonusType?m.bonuses:e===d.cartType?m.carts:e===d.companyType?m.companies:e===d.contactType?m.contacts:e===d.documentType?m.documents:e===d.emailType?m.emails:e===d.goalType?m.goals:e===d.journalType?m.journal:e===d.knowledgeType?m.knowledge:e===d.leadType?m.leads:e===d.marketingType?m.marketing:e===d.productType?m.goods:e===d.projectType?m.projects:e===d.salaryType?m.salaries:e===d.salePriceType?m.salePrices:e===d.taskType?m.tasks:e===d.trainingTitle?m.training:e===d.userType?m.users:e===d.vacationType?m.vacation:e===d.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.transformItem="TransformItem",p.canUnlinkItems="CanUnlinkItems",p.unlinkItems="UnlinkItems",p.getGoodsFinalPrices="GetGoodsFinalPrices",p.saveItemCopyRelation="SaveItemCopyRelation",p.getXsltTransormationDefinition="GetXsltTransformationDefinition",p.saveBinaryAttachment="SaveBinaryAttachment",p.saveBinaryXsltTransformation="SaveBinaryXsltTransformation",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${p.getFolderNameForApiMethod(e)}`;class h{constructor(e,t,r,o,n,s){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 r=e.SessionId;if(!r){const e=new Error("Successful login but no session came.");if(!this.errorCallback)throw e;return void this.errorCallback(e)}t&&t(r)},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=r,this.clientMachineIdentifier=o,this.clientMachineName=n,this.errorCallback=s}}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,r,o,n,s,i=!1,a){if(n&&!s||!n&&s)throw new Error("If codeChallenge is defined, codeChallengeMethod must also be defined and vice versa");let l=`https://login.eway-crm.${i?"dev":"com"}?scope=${encodeURIComponent(t.join(" "))}&prompt=login&response_type=code&redirect_uri=${encodeURIComponent(r)}&client_id=${e}`;return o&&(l+=`&state=${encodeURIComponent(o)}`),n&&s&&(l+=`&code_challenge=${encodeURIComponent(n)}&code_challenge_method=${encodeURIComponent(s)}`),a&&(l+=`&url=${encodeURIComponent(a)}`),l}}C.finishAuthorization=(e,t,r,o,n,s,i)=>{const a=new URLSearchParams;a.append("code_verifier",o),a.append("client_id",t),a.append("client_secret",r),a.append("code",n),a.append("redirect_uri",s),a.append("grant_type","authorization_code"),C.callTokenEndpoint(e,a,i)},C.refreshToken=(e,t,r,o,n)=>{const s=new URLSearchParams;s.append("client_id",t),s.append("client_secret",r),s.append("refresh_token",o),s.append("grant_type","refresh_token"),C.callTokenEndpoint(e,s,n)},C.getWebServiceUrl=e=>{const t=e.split(".");if(2!==t.length)throw new Error("Invalid token supplied");return s.decode(t[1])},C.getUserName=e=>C.decodeAccessToken(e).username,C.decodeAccessToken=e=>r(e),C.callTokenEndpoint=(t,r,o)=>{e.post(t+"/auth/connect/token",r,{headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(e=>{o(e.data)}).catch(e=>{e.response&&400==e.response.status?o(e.response.data):o({error:"Token request failed"})})};class f extends Error{constructor(e,t){super(),this.returnCode=e,this.message=t}}class P{constructor(e,t,r,o,n){if(this.invalidateSessionId=(e,t)=>{t&&t()},this.getSessionId=(e,t)=>{const r={userName:this.username,appVersion:this.appVersion,createSessionCookie:e.supportsGetItemPreviewMethod},o={Authorization:"Bearer "+this.accessToken};e.callWithoutSession(p.logIn,r,e=>{this.lastSuccessfulLoginResponse=e;const r=e.SessionId;if(!r){const e=new Error("Successful login but no session came.");if(!this.errorCallback)throw e;return void this.errorCallback(e)}t&&t(r)},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,r=>{if(401!==(null==r?void 0:r.statusCode)){if(!this.errorCallback)throw r;this.errorCallback(r)}else this.getNewAccessTokenCallback(e,r=>{this.accessToken=r.accessToken,r.error||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=r,this.getNewAccessTokenCallback=o,this.errorCallback=n}}class g extends P{constructor(e,t,r,o,n,s,i,a){if(!(e&&o&&t&&r))throw new Error("Non of the arguments 'username', 'clientId', 'clientSecret', 'refreshToken' can be empty.");super(e,n,s,(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)))}void 0!==e.error?t({error:e.error}):t({accessToken:e.access_token})})},i),this.refreshToken=o,this.clientId=t,this.clientSecret=r,this.refreshTokenCallback=a}}class T extends Error{constructor(e,t){super(),this.statusCode=e,this.message=t}}class E{}E.stringifyError=e=>JSON.stringify(e,E.replaceErrors),E.replaceErrors=(e,t)=>{if(t instanceof Error){const e={};return Object.getOwnPropertyNames(t).forEach(r=>{e[r]=t[r]}),e}return t};class S{constructor(t,r,o,n){if(this.ensureLogin=()=>new Promise((e,t)=>{if(this.sessionId)e();else{const r=r=>{r&&(this.sessionId=r,e()),t("Session Id cannot be empty")};this.sessionHandler.getSessionId(this,r)}}),this.createOpenLink=(e,t,r,o)=>{const n=s.encode(this.baseUri);let i="eway://"+t;r&&(i+="/"+(null==r?void 0:r.toLowerCase()));const a=e?"open.eway-crm.dev":"open.eway-crm.com";i=s.encode(i);let l="https://"+a+"/?ws="+n+"&l="+i;return o&&(l+="&n="+encodeURIComponent(o)),l},this.askUploadMethod=(e,t,r,o,n)=>new Promise((s,i)=>{const a=n?e=>{throw i(e),e}:i;this.callUploadMethod(e,t,r,s,a,a,o)}),this.callCustomUploadMethod=(t,r,o,n,s,i,a)=>{const l=()=>{this.sessionHandler.getSessionId(this,e=>{this.sessionId=e,this.callCustomUploadMethod(t,r,o,n,s,i,a)})},c=this.sessionId;if(!c)return void l();const d=new URLSearchParams(r),m=`${this.svcUri}/${o}?sessionId=${this.sessionId}&${d.toString()}`,p=e.post(m,r,a);S.handleCallPromise(p,n,e=>{if(e.ReturnCode===u.rcBadSession)return this.sessionId=null,void this.sessionHandler.invalidateSessionId(c,l);if(s)s(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 "+m+": "+E.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.callUploadMethod=(e,t,r,o,n,s,i)=>{this.callCustomUploadMethod(r,{itemGuid:e,fileName:t},p.saveBinaryAttachment,o,n,s,i)},this.askMethod=(e,t,r,o)=>new Promise((n,s)=>{const i=o?e=>{throw s(e),e}:s;this.callMethod(e,t,n,i,r,i)}),this.callMethod=(e,t,r,o,n,s)=>{n||(n=exports.HttpMethod.post);const i=()=>{this.sessionHandler.getSessionId(this,i=>{this.sessionId=i,this.callMethod(e,t,r,o,n,s)})},a=this.sessionId;if(!a)return void i();t.sessionId=a;const l=e!==p.logOut?r:e=>{this.sessionId=null,r(e)};this.callWithoutSession(e,t,l,r=>{if(r.ReturnCode!==u.rcBadSession||(this.sessionId=null,e===p.logOut))if(o)o(r);else{const e=new Error("Unhandled connection return code "+r.ReturnCode+": "+r.Description);if(!this.errorCallback)throw e;this.errorCallback(e,t)}else this.sessionHandler.invalidateSessionId(a,i)},null,n,s)},this.callWithoutSession=(t,r,o,n,s,i,a)=>{var l;i||(i=exports.HttpMethod.post);const c=this.svcUri+"/"+t;let u,d;switch(s&&(u={headers:s,withCredentials:null!==(l=this.supportGetItemPreviewMethod)&&void 0!==l?l:t==p.logIn}),i){case exports.HttpMethod.get:if(r)throw new Error("Calling api get method with data specified does not make any sense.");d=e.get(c,u);break;case exports.HttpMethod.post:d=e.post(c,r,u);break;default:throw new Error(`Unknown http method '${i}'.`)}S.handleCallPromise(d,o,n,e=>{if(a)try{a(e)}catch(e){if(!this.errorCallback)throw e;this.errorCallback(e,r)}else{const t=new Error("Unhandled connection error when calling "+c+": "+E.stringifyError(e));if(!this.errorCallback)throw t;this.errorCallback(t,r)}})},this.getItemPreviewGetMethodUrl=(e,t,r)=>this.svcUri+"/"+p.getItemPreview+"?folderName="+encodeURIComponent(e)+"&itemGuid="+encodeURIComponent(t)+(r||0===r?"&itemVersion="+encodeURIComponent(r.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.getTransformItemMethodUrl=(e,t,r,o)=>`${this.svcUri}/${p.transformItem}?itemGuid=${encodeURIComponent(e)}&itemFolderName=${encodeURIComponent(t)}&transformationGuid=${encodeURIComponent(r)}&outputFormat=${o}`,this.getXsltTransformationDefinitionMethodUrl=e=>`${this.svcUri}/${p.getXsltTransormationDefinition}?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=S.normalizeWsUrl(t)||t,"https://"===t.substr(0,8).toLowerCase()?this.svcUri=this.baseUri+"/API.svc":this.svcUri=this.baseUri+"/InsecureAPI.svc";this.sessionHandler=r,this.errorCallback=o,this.sessionId=null,this.supportGetItemPreviewMethod=null!=n&&n}get supportsGetItemPreviewMethod(){return this.supportGetItemPreviewMethod}static create(e,t,r,o,n,s,i,a){return new S(e,new h(t,r,o,n,s,i),i,a)}static createAnonymous(e,t){return new S(e,new y,t)}static createUsingOAuth(e,t,r,o,n,s,i,a,l,c){return new S(e,new g(t,r,o,n,s,i,a,l),a,c)}static normalizeWsUrl(e){return e&&e.endsWith("/")&&(e=e.substring(0,e.length-1)),e}static isCloudUrl(e,t){const r=new URL(e),o=new Set;return o.add("hosting.eway-crm.com"),o.add("free.eway-crm.com"),o.add("hosting.eway-crm.us"),o.add("hosting-vh39276.eway-crm.us"),o.add("free.eway-crm.us"),t&&(o.add("free.eway-crm.dev"),o.add("hosting.eway-crm.dev"),o.add("localhost")),o.has(r.host)}get wsUrl(){return this.baseUri}static handleCallPromise(e,t,r,o){e.then(e=>{200===e.status?e.data.ReturnCode===u.rcSuccess?t(e.data):r(e.data):o(new T(e.status,e.statusText))}).catch(e=>{e.response?o(new T(e.response.status,e.response.statusText)):o(e)})}}class v{constructor(e,t,r,o,n,s,i){this.isEnabled=(e,t)=>{const r=()=>{this.url&&this.token?e(this.url,this.token):t()};this.url&&this.token?e(this.url,this.token):this.obtainToken(r)},this.callTokenizedApi=(e,t,r,o)=>{this.isEnabled((n,s)=>{t.token=s,v.call(n,e,t,r,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,r,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 r=this.urlAndTokenObtainer(t);r.url&&r.token?(this.url=r.url,this.token=r.token,this.isActive=!0,e()):(this.url=null,this.token=null,this.isActive=!1,e())},r=()=>{this.url=null,this.token=null,this.isActive=!1,e()};this.needsSession?this.connection.callMethod(this.obtainTokenMethodName,{},t,r,this.obtainTokenMethodType):this.connection.callWithoutSession(this.obtainTokenMethodName,null,t,r,null,this.obtainTokenMethodType)},this.obtainTokenMethodName=e,this.obtainTokenMethodType=t,this.needsSession=r,this.invalidTokenReturnCode=o,this.urlAndTokenObtainer=n,this.connection=s,this.generalErrorCallback=i||null,this.url=null,this.token=null,this.isActive=!0}static call(t,r,o,n,s,i){const a=t+"/"+r;e.post(a,o).then(e=>{200===e.status?"Success"===e.data.ReturnCodeString?n(e.data):s(e.data):i(new T(e.status,e.statusText))}).catch(e=>{e.response?i(new T(e.response.status,e.response.statusText)):i(e)})}}const A=e=>({url:e.ServiceUrl,token:e.Token});class I{}I.acceptableBackwardWorkReportDays="AcceptableBackwardWorkReportDays",I.adminAppInactiveLogoutTime="AdminAppInactiveLogoutTime",I.applyGeneralDataProtectionRules="ApplyGeneralDataProtectionRules",I.automaticallyCreateJournalAfterCallDuration="AutomaticallyCreateJournalAfterCallDuration",I.bonusesCompletedState="BonusesCompletedState",I.cartInvoicedState="CartInvoicedState",I.cartOrderCanceledState="CartOrderCanceledState",I.cartOrderInProcessState="CartOrderInProcessState",I.cartOrderProcessedState="CartOrderProcessedState",I.cartPaidState="CartPaidState",I.cartProposalInProcessState="CartProposalInProcessState",I.cartProposalProcessedState="CartProposalProcessedState",I.cartSalesVoucherIssuedState="CartSalesVoucherIssuedState",I.cartToBeInvoicedState="CartToBeInvoicedState",I.cartVoidedState="CartVoidedState",I.clickToCallScheme="ClickToCallScheme",I.companyDuplicityCheckEnabled="CompanyDuplicityCheckEnabled",I.completedStateName="CompletedStateName",I.contactDuplicityCheckEnabled="ContactDuplicityCheckEnabled",I.createCompanyWhileImportingContactFromOutlook="CreateCompanyWhileImportingContactFromOutlook",I.defaultProposalValidityPeriod="DefaultProposalValidityPeriod",I.enableContactsTwoWaySyncWithM365="EnableContactsTwoWaySyncWithM365",I.deadStateName="DeadStateName",I.enableCompaniesSyncIntoMobileDeviceContacts="EnableCompaniesSyncIntoMobileDeviceContacts",I.enableContactsSyncIntoMobileDevice="EnableContactsSyncIntoMobileDevice",I.enableLeadsSyncIntoMobileDeviceContacts="EnableLeadsSyncIntoMobileDeviceContacts",I.enableLlamaAiFeatures="EnableLlamaAiFeatures",I.enableUsersSyncIntoMobileDeviceContacts="EnableUsersSyncIntoMobileDeviceContacts",I.emailsActiveProjectsLeadsFilter="EmailsActiveProjectsLeadsFilter",I.exchangeRatesAdminGroupName="ExchangeRatesAdminGroupName",I.forcedEmailTrackingGroups="ForcedEmailTrackingGroups",I.ignoreEmailsFromDomainsOnEmailsTracking="IgnoreEmailsFromDomainsOnEmailsTracking",I.trackEmailsFromDomains="TrackEmailsFromDomains",I.groupsForAllUnpaidInvoicesNotification="GroupsForAllUnpaidInvoicesNotification",I.itemPreviewMaxHeight="ItemPreviewMaxHeight",I.lastActivityAttributes="LastActivityAttributes",I.leadsCompletedState="LeadsCompletedState",I.leadDeadlineAlertGroups="LeadDeadlineAlertGroups",I.leadsDeadState="LeadsDeadState",I.marketingCompletedState="MarketingCompletedState",I.marketingDeadState="MarketingDeadState",I.minimumPasswordLength="MinimumPasswordLength",I.nextStepAttributes="NextStepAttributes",I.notifyAboutInvoicedInvoiceInPohodaGroup="NotifyAboutInvoicedInvoiceInPohodaGroup",I.notifyAboutLeadsDeadline="NotifyAboutLeadsDeadline",I.notifyAboutPaidInvoiceInPohodaGroup="NotifyAboutPaidInvoiceInPohodaGroup",I.notifyAboutProjectDeadline="NotifyAboutProjectDeadline",I.numberOfDecimalPlaces="NumberOfDecimalPlaces",I.phoneListTaskSolverGroup="PhoneListTaskSolverGroup",I.projectDeadlineAlert="ProjectDeadlineAlert",I.serverUpdateProgressNotificationGroup="ServerUpdateProgressNotificationGroup",I.sumarizeCartsPricesOnLeads="SumarizeCartsPricesOnLeads",I.sumarizeCartsPricesOnProjects="SumarizeCartsPricesOnProjects",I.sumarizePeopleExpensesOnProjects="SumarizePeopleExpensesOnProjects",I.systemHealthNotificationGroup="SystemHealthNotificationGroup",I.tasksCompletedState="TasksCompletedState",I.tasksDeferredState="TasksDeferredState",I.tasksInProgressState="TasksInProgressState",I.tasksNotStartedState="TasksNotStartedState",I.tasksWaitOnSomeoneElseState="TasksWaitOnSomeoneElseState",I.trackDocumentVersions="TrackDocumentVersions",I.vacationCompletedState="VacationCompletedState",I.workReportApprovedState="WorkReportApprovedState",I.defaultLanguage="DefaultLanguage",I.defaultCurrency="DefaultCurrency",I.myCompanyCountry="MyCompanyCountry",I.myCompanyName="MyCompanyName",I.myCompanyStreet="MyCompanyStreet",I.myCompanyCity="MyCompanyCity",I.myCompanyState="MyCompanyState",I.myCompanyZip="MyCompanyZIP",I.myCompanyId="MyCompanyID",I.myCompanyVat="MyCompanyVAT",I.mergeGoodsInCart="MergeGoodsInCart",I.cartRefreshLogic="CartRefreshLogic",I.goodsDefaultQuantity="GoodsDefaultQuantity",I.goodsDefaultVAT="GoodsDefaultVAT",I.goodsDefaultVATIncluded="GoodsDefaultVATIncluded";class k{}k.ServerCommon={Server_ID:"Server_ID",Server_ItemCreated:"Server_ItemCreated",Server_ItemChanged:"Server_ItemChanged"},k.Common={CreatedByGUID:"CreatedByGUID",CurrencyEn:"CurrencyEn",DefaultCurrencySuffix:"DefaultCurrency",FileAs:"FileAs",ItemCreated:"ItemCreated",ItemChanged:"ItemChanged",ItemGUID:"ItemGUID",ItemVersion:"ItemVersion",ModifiedByGUID:"ModifiedByGUID",OwnerGUID:"OwnerGUID",ParentCurrencySuffix:"ParentCurrency"},k.Calendar={EndDate:"EndDate",Note:"Note"},k.Carts={SuperiorItem:"SuperiorItem",Customer:"Customer",Contact:"Contact",TypeEn:"TypeEn",StateEn:"StateEn",PriceTotal:"PriceTotal",PriceTotalExcludingVAT:"PriceTotalExcludingVAT",ForPayment:"ForPayment",Paid:"Paid",CurrencyEn:"CurrencyEn",EffectiveFrom:"EffectiveFrom",ValidUntil:"ValidUntil",Active:"Active",Note:"Note",ID:"ID",AccountingCaseDate:"AccountingCaseDate",TaxableSupplyDate:"TaxableSupplyDate",PaymentDate:"PaymentDate",VAT:"VAT",GoodsInCartCount:"GoodsInCartCount",PriceTotalDefaultCurrency:"PriceTotalDefaultCurrency",PriceTotalParentCurrency:"PriceTotalParentCurrency",ForPaymentDefaultCurrency:"ForPaymentDefaultCurrency",ForPaymentParentCurrency:"ForPaymentParentCurrency",PaidDefaultCurrency:"PaidDefaultCurrency",PaidParentCurrency:"PaidParentCurrency",PaidChanged:"PaidChanged",PriceTotalChanged:"PriceTotalChanged",PriceTotalExcludingVATDefaultCurrency:"PriceTotalExcludingVATDefaultCurrency",PriceTotalExcludingVATParentCurrency:"PriceTotalExcludingVATParentCurrency",VATDefaultCurrency:"VATDefaultCurrency",VATParentCurrency:"VATParentCurrency",PrevStateEn:"PrevStateEn",PurchaseExpenses:"PurchaseExpenses",PurchaseExpensesDefaultCurrency:"PurchaseExpensesDefaultCurrency",PurchaseExpensesParentCurrency:"PurchaseExpensesParentCurrency",PurchaseExpensesChanged:"PurchaseExpensesChanged",Profit:"Profit",ProfitDefaultCurrency:"ProfitDefaultCurrency",ProfitParentCurrency:"ProfitParentCurrency",ProfitChanged:"ProfitChanged"},k.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",TrackedDomains:"TrackedDomains",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"},k.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"},k.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:k.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"},k.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",ExternalUrl:"ExternalUrl"},k.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"},k.GoodsBase={Code:"Code",Structure:"Structure",Note:"Note",Description:"Description",TypeEn:"TypeEn",SaleCurrencyEn:"SaleCurrencyEn",PurchaseCurrencyEn:"PurchaseCurrencyEn",UnitEn:"UnitEn",PurchasePrice:"PurchasePrice",PurchasePriceDefaultCurrency:"PurchasePriceDefaultCurrency",PurchasePriceChanged:"PurchasePriceChanged",SalePrice:"SalePrice",SalePriceDefaultCurrency:"SalePriceDefaultCurrency",SalePriceChanged:"SalePriceChanged",IsPriceSum:"IsPriceSum",VATRate:"VATRate",VATIncluded:"VATIncluded"},k.Goods=Object.assign(Object.assign({},k.GoodsBase),{PriceListGroupGUID:"PriceListGroupGUID",InventoryQuantity:"InventoryQuantity"}),k.GoodsInCart=Object.assign(Object.assign({},k.GoodsBase),{Cart:"Cart",GoodsInfo:"GoodsInfo",SuperiorItem:"SuperiorItem",Quantity:"Quantity",PriceTotal:"PriceTotal",PriceTotalDefaultCurrency:"PriceTotalDefaultCurrency",PriceTotalParentCurrency:"PriceTotalParentCurrency",PriceTotalChanged:"PriceTotalChanged",PriceTotalExcludingVAT:"PriceTotalExcludingVAT",PriceTotalExcludingVATDefaultCurrency:"PriceTotalExcludingVATDefaultCurrency",PriceTotalExcludingVATParentCurrency:"PriceTotalExcludingVATParentCurrency",VATTotal:"VATTotal",VATTotalDefaultCurrency:"VATTotalDefaultCurrency",VATTotalParentCurrency:"VATTotalParentCurrency",SalePriceExcludingVAT:"SalePriceExcludingVAT",SalePriceExcludingVATDefaultCurrency:"SalePriceExcludingVATDefaultCurrency",SalePriceExcludingVATParentCurrency:"SalePriceExcludingVATParentCurrency",VAT:"VAT",VATDefaultCurrency:"VATDefaultCurrency",VATParentCurrency:"VATParentCurrency",PurchasePriceParentCurrency:"PurchasePriceParentCurrency",SalePriceParentCurrency:"SalePriceParentCurrency",ListPrice:"ListPrice",ListPriceDefaultCurrency:"ListPriceDefaultCurrency",ListPriceParentCurrency:"ListPriceParentCurrency",ListPriceChanged:"ListPriceChanged",Discount:"Discount",HierarchyInSet:"HierarchyInSet",IsFromSet:"IsFromSet",ParentGUID:"ParentGUID",Rank:"Rank",IncludeInCartPrice:"IncludeInCartPrice",ListPriceCustomized:"ListPriceCustomized",ChildItemsCount:"ChildItemsCount",JoinedToGUID:"JoinedToGUID",PurchasePriceTotal:"PurchasePriceTotal",PurchasePriceTotalDefaultCurrency:"PurchasePriceTotalDefaultCurrency",PurchasePriceTotalParentCurrency:"PurchasePriceTotalParentCurrency",PurchasePriceTotalChanged:"PurchasePriceTotalChanged"}),k.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"},k.Vacation={StartDate:"StartDate",EndDate:"EndDate",User:"User",Duration:"Duration",Place:"Place",Note:"Note",AllDay:"AllDay",TypeEn:"TypeEn",StateEn:"StateEn",IsPrivate:"Private"},k.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"},k.Projects={HumanID:"HID",FileAs:"FileAs",ProjectName:"ProjectName",ProjectOriginEn:"ProjectOriginEn",TypeEn:"TypeEn",StateEn:"StateEn",PaymentTypeEn:"PaymentTypeEn",ProjectStart:"ProjectStart",ProjectRealEnd:"ProjectRealEnd",EstimatedEnd:"ProjectEnd",CurrencyEn:k.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"},k.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"},k.Training={TitleEn:"TitleEn"},k.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"},k.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"},k.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"},k.PriceListGroups={Note:"Note"},k.Prices={SalePriceGUID:"SalePriceGUID",GoodsItemGUID:"GoodsItemGUID",Price:"Price",CurrencyEn:"CurrencyEn"},k.SalePrices={Note:"Note",Discount:"Discount",TypeEn:"TypeEn",StateEn:"StateEn",PrevStateEn:"PrevStateEn"},k.XsltTransformations={LangCode:"LangCode",Definition:"Definition",Namespace:"Namespace",ObjectTypeID:"ObjectTypeID",TransformationVersion:"TransformationVersion"},k.XsltTransformationsModels={ObjectTypeID:"ObjectTypeID",TransformationGUID:"TransformationGUID",ItemTypeGUID:"ItemTypeGUID"},k.allTypeEnNames=["TypeEn",k.Documents.DocTypeEn,k.WorkReports.WorkReportEn,"TitleEn"],k.getFolderFileAs=e=>{switch(e){case m.leads:return k.Leads.FileAs;case m.projects:return k.Projects.ProjectName;case m.documents:return k.Documents.DocName;case m.companies:return k.Companies.CompanyName;case m.contacts:case m.users:return k.Common.FileAs;case m.emails:return k.Emails.Subject;case m.journal:return k.Journal.FileAs;case m.tasks:return k.Tasks.Subject;case m.workReports:return k.WorkReports.Subject;case m.vacation:return k.Vacation.TypeEn;case m.carts:case m.goods:case m.goodsInCart:return k.Common.FileAs;case m.groups:return k.Groups.GroupName;case m.xsltTransformations:return k.Common.FileAs;default:return console.warn(`FileAs col name not defined for folderName ${e}`),k.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",b.projectOrigin="PROJECT_ORIGIN",b.cart="CART",b.goodsInCart="GOODSINCART",b.superiorItem="SUPERIORITEM";class D{}D.general=1,D.group=2,D.contactPerson=10,D.contact=11,D.customer=12,D.company=13,D.outlookProject=28,D.supervisor=32,D.projectOrigin=25,D.cart=9,D.goodsInCart=15,D.superiorItem=31;class w{}w.all="All",w.own="Own",w.readonly="Readonly",w.invisible="Invisible",w.none="None";class x{}var F,O,N,R;x.mandatory="Mandatory",x.optional="Optional",x.unique="Unique",x.none="None",exports.Edition=void 0,(F=exports.Edition||(exports.Edition={})).Free="Free",F.Basic="Basic",F.Professional="Professional",F.Enterprise="Enterprise",exports.Feature=void 0,(O=exports.Feature||(exports.Feature={})).ContactsAndCompanies="ContactsAndCompanies",O.Sales="Sales",O.Projects="Projects",O.Marketing="Marketing",exports.SentimentTone=void 0,(N=exports.SentimentTone||(exports.SentimentTone={}))[N.Negative=0]="Negative",N[N.Neutral=1]="Neutral",N[N.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 V{}V.contactsAutomaticSynchronizationWithOutlook="ContactsAutomaticSynchronizationWithOutlook",V.contactsSynchronizationWithOutlook="ContactsSynchronizationWithOutlook",V.contactsSynchronizationWithAndroid="ContactsSynchronizationWithAndroid",V.documentsRevisions="DocumentsRevisions",V.wordAddin="WordAddin",V.excelAddin="ExcelAddin",V.tasksReminders="TasksReminders",V.tasksRecurrentTasks="TasksRecurrentTasks",V.tasksSubtasks="TasksSubtasks",V.tasksSynchronizationWithOutlook="TasksSynchronizationWithOutlook",V.calendarSynchronizationWithOutlook="CalendarSynchronizationWithOutlook",V.emailsManualTracking="EmailsManualTracking",V.emailsAutomaticTracking="EmailsAutomaticTracking",V.emailSummaryAndSentimentToneFromAi="EmailSummaryAndSentimentToneFromAi",V.convertEmailToContact="ConvertEmailToContact",V.convertEmailToDeal="ConvertEmailToDeal",V.convertEmailToProject="ConvertEmailToProject",V.convertEmailToTask="ConvertEmailToTask",V.convertFromSuggestedContact="ConvertFromSuggestedContact",V.gravatarIntegration="GravatarIntegration",V.logoboxIntegration="LogoboxIntegration",V.companiesBussinesRegisterApiIntegration="CompaniesBussinesRegisterApiIntegration",V.duplicityChecker="DuplicityChecker",V.nextStepAndLastActivityCustomization="NextStepAndLastActivityCustomization",V.subProjects="SubProjects",V.resourceAndPlanning="ResourceAndPlanning",V.professionalEmailCampaigns="ProfessionalEmailCampaigns",V.professionalEmailCampaignsAdvancedStatistics="ProfessionalEmailCampaignsAdvancedStatistics",V.wordEmailMerge="WordEmailMerge",V.printLabels="PrintLabels",V.printEnvelopes="PrintEnvelopes",V.userViews="UserViews",V.sharedUserViews="SharedUserViews",V.gridRowSummary="GridRowSummary",V.gridConditionalFormating="GridConditionalFormating",V.multipleCurrencies="MultipleCurrencies",V.historyTracking="HistoryTracking",V.privateItems="PrivateItems",V.itemTypes="ItemTypes",V.formLayoutCustomization="FormLayoutCustomization",V.workflowBasicDefinitions="WorkflowBasicDefinitions",V.workflowAdvancedDefinitions="WorkflowAdvancedDefinitions",V.workflowAdvancedDefinitionsRules="WorkflowAdvancedDefinitionsRules",V.workflowAdvancedDefinitionsActions="WorkflowAdvancedDefinitionsActions",V.workflowGroupLevelActions="WorkflowGroupLevelActions",V.customFields="CustomFields",V.importantFields="ImportantFields",V.mandatoryFields="MandatoryFields",V.uniqueFields="UniqueFields",V.readOnlyFields="ReadOnlyFields",V.transformationCustomTemplates="TransformationCustomTemplates",V.userRoles="UserRoles",V.modulePermissions="ModulePermissions",V.columnPermissions="ColumnPermissions",V.commonDataAPI="CommonDataAPI",V.eWayCrmAPI="eWayCrmAPI",V.threeCXIntegration="ThreeCXIntegration",V.tapiIntegration="TapiIntegration",V.pohodaIntegration="PohodaIntegration",V.pohodaSynchronizationIntervalCustomization="PohodaSynchronizationIntervalCustomization",V.pohodaSynchronizationFieldMappingCustomization="PohodaSynchronizationFieldMappingCustomization",V.quickBooksIntegration="QuickBooksIntegration",V.shareByTeams="ShareByTeams",V.convertEmailToContactWithDataFromAi="ConvertEmailToContactWithDataFromAi",V.convertEmailToDealWithDataFromAi="ConvertEmailToDealWithDataFromAi",V.convertEmailToProjectWithDataFromAi="ConvertEmailToProjectWithDataFromAi",function(e){e.UnpaidImportantInvoices="UnpaidImportantInvoices",e.UncollectableSubscriptionPayment="UncollectableSubscriptionPayment",e.UncollectableSubscriptionPaymentWithExpiredCard="UncollectableSubscriptionPaymentWithExpiredCard",e.StandardSubscriptionPeriod="StandardSubscriptionPeriod"}(R||(R={}));var _,U=R;!function(e){e.License="License",e.CloudLicense="CloudLicense",e.MiscLicense="MiscLicense",e.Support="Support",e.Service="Service"}(_||(_={}));var G=_;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 r;const o=null===(r=e.sessionHandler.lastSuccessfulLoginResponse)||void 0===r?void 0:r.WcfVersion;return!!o&&j.supportsVersionFeaturesOf(o,t)},j.supportsVersionFeaturesOf=(e,t)=>o.compare(e,t,">=")||o.compare(e,"1.0.0.0","=");class B{}B.textBox="TextBox",B.comboBox="ComboBox",B.numericBox="NumericBox",B.relation="Relation",B.checkBox="CheckBox",B.linkTextBox="LinkTextBox",B.dateEdit="DateEdit",B.memoBox="MemoBox",B.multiSelectComboBox="MultiSelectComboBox",B.workflowState="WorkflowState",B.image="Image",B.multiSelectRelation="MultiSelectRelation";const W={[m.relations]:0,[m.unifiedRelations]:1,[m.users]:2,[m.groups]:3,[m.enumTypes]:4,[m.enumValues]:5,[m.additionalFields]:6};var H,z,Q,$;exports.Version=void 0,(H=exports.Version||(exports.Version={})).Version75="7.5",H.Version76="7.6",H.Version77="7.7",H.Version80="8.0",H.Version81="8.1",H.Version82="8.2",H.Version83="8.3",H.Version90="9.0",H.Version91="9.1",H.Version92="9.2",H.Version93="9.3",H.Version94="9.4";class q extends j{}q.is75OrLater=e=>j.supportsFeaturesOf(e,exports.Version.Version75),q.is76OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version76),q.is77OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version77),q.is80OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version80),q.is81OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version81),q.is82OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version82),q.is83OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version83),q.is90OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version90),q.is91OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version91),q.is92OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version92),q.is93OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version93),q.is94OrLater=e=>q.supportsFeaturesOf(e,exports.Version.Version94),q.isFeatureSupported=(e,t)=>q.supportsFeaturesOf(e,t);class J{static mainTable(){return{__type:"MainTable:#EQ"}}static relation(e,t,r){return{__type:"Relation:#EQ",Direction:r,ItemTypes:e,RelationType:t}}static join(e,t,r){const o={__type:"Join:#EQ",ItemType:e,Key:t};return r&&(o.TargetColumnName=r),o}static hubRelation(e){const{isToParentDirection:t,childrenFolderNames:r}=e,o={__type:"HubRelation:#EQ"};return void 0!==typeof t&&(o.IsToParentDirection=t),r&&(o.ChildrenFolderNames=r),o}}class X{static createHubItemsCountsQuery(e,t,r){return{__type:"HubItemsCountsQuery:#EQ",ParentItemGuids:e,ItemTypes:t,ExcludeSystemItems:r}}static createRelatedTableQuery(e,t,r){return{__type:r?"RelatedTableQuery:#EQ":"TypelessRelatedTableQuery:#EQ",BaseItemID:e,ItemTypes:Array.isArray(t)?t:[t],RelationType:r}}static createMainTableQuery(e){return{__type:"MainTableQuery:#EQ",ItemTypes:Array.isArray(e)?e:[e]}}}X.column=e=>({__type:"Column:#EQ",Source:J.mainTable(),Name:e}),X.multiSelectComboColumnLegacy=(e,t,r)=>({__type:"Column:#EQ",Source:J.mainTable(),Name:"ItemGUID",Transformation:`[dbo].[GetConcatenatedEnumValuesRelationsValues]({0}, '${e}', '${t}'`,Alias:null!=r?r:e}),X.multiSelectComboColumn=(e,t,r,o,n)=>{if(!q.is77OrLater(e))return X.multiSelectComboColumnLegacy(r,o,n);return{__type:"Column:#EQ",Source:J.mainTable(),Name:"ItemGUID",Transformation:`[dbo].[GetConcatenatedEnumValuesRelationsValues_WithObjectTypeID]({0}, dbo.GetObjectTypeID('${t}'), '${r}', '${o}')`,Alias:null!=n?n:r}},X.joinColumn=(e,t,r,o,n)=>X.joinColumnFromKey(e,X.column(t),r,o,n),X.joinColumnFromKey=(e,t,r,o,n)=>{const s={__type:"Column:#EQ",Source:J.join(e,t,n),Name:r};return o&&(s.Alias=o),s},X.singleVariatedColumn=(e,t,r)=>X.variatedColumn([X.columnVariation(e,t)],r),X.variatedColumn=(e,t)=>{const r={__type:"VariatedColumn:#EQ",Source:J.mainTable(),Variations:e};return t&&(r.Alias=t),r},X.columnVariation=(e,t,r)=>{const o={FolderName:t,Field:{__type:"Column:#EQ",Source:J.mainTable(),Name:e}};return r&&(o.Field.Transformation=r),o},X.joinColumnVariation=(e,t,r,o)=>({FolderName:e,Field:{__type:"Column:#EQ",Source:J.join(t,X.column(r)),Name:o}}),X.relationColumnVariation=(e,t,r,o)=>({FolderName:e,Field:{__type:"Column:#EQ",Source:J.relation(r,t,1),Name:o}}),X.relatedColumn=(e,t,r,o)=>{const n={__type:"Column:#EQ",Source:J.relation(t,e,1),Name:r};return o&&(n.Alias=o),n},X.relatedSubstituableColumn=(e,t,r,o,n)=>{const s={__type:"SubstituableColumn:#EQ",Source:J.relation(t,e,1),Name:r,Substitute:o};return n&&(s.Alias=n),s},X.relatedColumnFolderNameToken=(e,t,r)=>({__type:"Token:#EQ",Source:J.relation(t,e,1),TypeName:"ItemType",Alias:r}),X.hubRelationColumn=(e,t)=>({__type:"Column:#EQ",Source:J.hubRelation(t),Name:e}),X.aggregateColumn=(e,t,r)=>({__type:"AggregateColumn:#EQ",FunctionName:e,Source:t.Source,AggregatedField:t,Alias:r}),X.folderNameToken=e=>({__type:"Token:#EQ",Source:J.mainTable(),TypeName:"ItemType",Alias:null!=e?e:"FolderName"}),X.equalsFilterExpression=(e,t)=>({__type:"EqualsFilterExpressionPredicate:#EQ",Field:e,Value:t}),X.notEqualsExpression=(e,t)=>({__type:"NotFilterExpression:#EQ",Child:X.equalsFilterExpression(e,t)}),X.andFilterExpression=e=>({__type:"AndFilterExpressionOperator:#EQ",Children:e}),X.orFilterExpression=e=>({__type:"OrFilterExpressionOperator:#EQ",Children:e}),X.lessFilterExpression=(e,t)=>({__type:"LessFilterExpressionPredicate:#EQ",Field:e,Value:t}),X.lessOrEqualFilterExpression=(e,t)=>({__type:"LessOrEqualFilterExpressionPredicate:#EQ",Field:e,Value:t}),X.greaterFilterExpression=(e,t)=>({__type:"GreaterFilterExpressionPredicate:#EQ",Field:e,Value:t}),X.greaterOrEqualFilterExpression=(e,t)=>({__type:"GreaterOrEqualFilterExpressionPredicate:#EQ",Field:e,Value:t}),X.likeFilterExpression=(e,t)=>({__type:"LikeFilterExpressionPredicate:#EQ",Field:e,Value:`%${t}%`}),X.inFilterExpression=(e,t)=>({__type:"InFilterExpressionPredicate:#EQ",Field:e,Value:t}),X.relatedToExpression=(e,t)=>({__type:"RelatedToFilterExpressionPredicate:#EQ",Value:e,RelationType:t}),X.isNullOrEmptyFilterExpression=e=>X.orFilterExpression([X.equalsFilterExpression(X.column(e),null),X.equalsFilterExpression(X.column(e),"")]);class K{static toRfc3339String(e){const t=e=>e<10?`0${e}`:String(e);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}${(e=>{if(0===e)return"Z";const r=e>0?"-":"+";return e=Math.abs(e),`${r}${t(Math.floor(e/60))}:${t(e%60)}`})(e.getTimezoneOffset())}`}}function Y(e,t,r,o){return new(r||(r=Promise))(function(n,s){function i(e){try{l(o.next(e))}catch(e){s(e)}}function a(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(i,a)}l((o=o.apply(e,t||[])).next())})}K.isValid=e=>e instanceof Date&&!isNaN(e.getTime()),K.areDaysEqual=(e,t)=>{const r=K.clearTime(e),o=K.clearTime(t);return r.getTime()===o.getTime()},K.areTimesEqual=(e,t)=>e.getHours()===t.getHours()&&e.getMinutes()===t.getMinutes(),K.areDatesEqual=(e,t)=>!!e&&!!t&&K.areDaysEqual(e,t)&&K.areTimesEqual(e,t),K.clearTime=e=>{const t=new Date(e);return t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setMilliseconds(0),t},K.isWithoutTime=e=>0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds(),K.getFormattedSqlDateTime=e=>e.toISOString().slice(0,19).replace("T"," "),K.getRfcWithoutTimezone=e=>e.slice(0,19),exports.TransformItemFormats=void 0,(z=exports.TransformItemFormats||(exports.TransformItemFormats={})).OpenXmlDocx="OpenXmlDocx",z.Pdf="Pdf",z.WordMlXml="WordMlXml","function"==typeof SuppressedError&&SuppressedError;exports.EnumTypeEditMode=void 0,(Q=exports.EnumTypeEditMode||(exports.EnumTypeEditMode={})).Readonly="Readonly",Q.VisibleRankDefaultOnly="VisibleRankDefaultOnly",Q.Editable="Editable",exports.ImportResult=void 0,($=exports.ImportResult||(exports.ImportResult={})).Success="Success",$.Failure="Failed",$.FailureDuplicityFound="Failed_DuplicityFound",$.FailureItemAlreadyRemoved="Failed_ItemAlreadyRemoved",$.FailureColumnsLockedWFAction="Failed_ColumnsLocked",$.FailureItemLockedWFAction="Failed_ItemLocked",$.FailureLicenseLimitReached="Failed_LicenseLimitReached",$.FailureInssuficientModulePermission="Failed_InsufficientModulePermission",$.FailureInssuficientColumnsPermission="Failed_InsufficientColumnsPermission",c.polyfill(),exports.ApiConnectionAsNonDefaultExport=S,exports.ApiFetchClient=class{constructor(e,t,r,o){let n;if(this.sessionId=null,this.isAdmin=null,this.loginResponse=null,!(r||(n=C.decodeAccessToken(t),r=n.ws)))throw new Error("Failed to get web service URL from JWT");if(!(o||(n||(n=C.decodeAccessToken(t)),o=n.username)))throw new Error("Failed to get username from JWT");this.appName=e,this.wsUrl=r,this.userName=o,this.endpoint=r.startsWith("http://")?"InsecureAPI.svc":"API.svc",this.accessToken=t}hasAdminRights(){return this.isAdmin}getWsUrl(){return this.wsUrl}getUserName(){return this.userName}getOutlookClientVersion(){var e;return null===(e=this.loginResponse)||void 0===e?void 0:e.OutlookClientVersion}getWebServiceVersion(){var e;return null===(e=this.loginResponse)||void 0===e?void 0:e.WcfVersion}login(){return Y(this,void 0,void 0,function*(){const e={userName:this.userName,appVersion:this.appName},t=new Request(`${this.wsUrl}/${this.endpoint}/Login`,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify(e)}),r=yield fetch(t),o=200===r.status?yield r.json():void 0;if(!o||"rcSuccess"!==o.ReturnCode)throw new Error(`Login failed: ${(null==o?void 0:o.Description)||"Unknown error"}`);this.sessionId=null==o?void 0:o.SessionId,this.isAdmin=null==o?void 0:o.IsAdmin,this.loginResponse=o})}logout(){return Y(this,void 0,void 0,function*(){const e=new Request(`${this.wsUrl}/${this.endpoint}/LogOut`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:this.sessionId})}),t=yield fetch(e);if("rcSuccess"!==(yield t.json()).ReturnCode)throw new Error("Failed to logout")})}getObjectTypes(){return Y(this,void 0,void 0,function*(){return(yield this.callMethod("GetObjectTypes",{})).Data})}getLicense(){return Y(this,void 0,void 0,function*(){return(yield this.callMethod("GetLicense",{})).Datum})}getClientVersionId(e){var t;return Y(this,void 0,void 0,function*(){const r={versionName:e};return null===(t=(yield this.callMethod("GetClientVersion",r)).Datum)||void 0===t?void 0:t.Id})}queryAmount(e,t=null){return Y(this,void 0,void 0,function*(){const r={query:{__type:"MainTableQuery:#EQ",ItemTypes:[e],Fields:[{__type:"Column:#EQ",Source:{__type:"MainTable:#EQ"},Name:"ItemGUID"}]}};return t&&(r.query.Filter=t),this.callMethod("QueryAmount",r)})}query(e,t=null,r=null,o=null){return Y(this,void 0,void 0,function*(){const n={query:{__type:"MainTableQuery:#EQ",ItemTypes:[e],Fields:t,Paging:{Skip:0,Take:500}}};return r&&(n.query.Filter=r),o&&(n.query.Sort=o),this.callMethod("Query",n)})}callMethod(e,t,r="POST"){return Y(this,void 0,void 0,function*(){if(!this.sessionId)throw new Error("Session ID is not set. Please call init() first.");t.sessionId=this.sessionId;const o=new Request(`${this.wsUrl}/${this.endpoint}/${e}`,{method:r,headers:{"Content-Type":"application/json"},body:"POST"===r?JSON.stringify(t):void 0}),n=yield fetch(o);if(!n.ok)throw new Error(`Error calling method ${e}: ${n.statusText}`);const s=200===n.status?yield n.json():void 0;if(!s||"rcSuccess"!==s.ReturnCode)throw new Error(`API call failed (${null==s?void 0:s.ReturnCode}): ${null==s?void 0:s.Description}`);return s})}static getTokenData(e,t,r,o,n){return Y(this,void 0,void 0,function*(){const s=new URLSearchParams;s.append("client_id",o),s.append("client_secret",n),s.append("code",t),s.append("redirect_uri",r),s.append("grant_type","authorization_code");const i=new Request(`${e}/auth/connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()}),a=yield fetch(i);if(!a.ok)throw new Error(`Error calling token endpoint: ${a.statusText}`);const l=yield a.json();if(!l||!l.access_token)throw new Error("Failed to get access token");return l})}},exports.ApiMethods=p,exports.ColumnPermissionMandatoryRules=x,exports.ColumnPermissionPermissionRules=w,exports.CommonDataConnection=class{constructor(e,t){this.isCommonDataApiEnabled=(e,t)=>{this.tokenizedConnection.isEnabled(e,t)},this.callCommonDataApi=(e,t,r,o)=>{this.tokenizedConnection.callTokenizedApi(e,t,r,o)},this.tokenizedConnection=new v("ObtainCommonDataApiAccessToken",exports.HttpMethod.get,!1,"InvalidCommonDataToken",A,e,t)}},exports.CustomizationStatsItemKeys=L,exports.DateHelper=K,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 r=((null==e?void 0:e.substr(0,1))||"")+((null==t?void 0:t.substr(0,1))||"");return""==r?null:r}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=d,exports.ErrorHelper=E,exports.ExpirationReason=U,exports.FieldNames=k,exports.FieldTypes=B,exports.FolderNames=m,exports.Functionality=M,exports.GlobalSettingsNames=I,exports.HttpRequestError=T,exports.LicenseKeyInvoiceSeverity=G,exports.LicenseRestrictionKeys=V,exports.OAuthHelper=C,exports.OAuthSessionHandlerBase=P,exports.ObjectTypeIds=W,exports.QueryHelper=X,exports.RelationTypeIds=D,exports.RelationTypes=b,exports.ReturnCodes=u,exports.StringHelper=class{static trim(e,t,r=!1){if(null==e)return e;let o=e.trim();return o.length<=t||(o=o.substring(0,t-(r?3:0)),r&&(o+="...")),o}},exports.TokenizedServiceConnection=v,exports.VersionHelper=q,exports.VersionHelperBase=j,exports.default=S;
@@ -40,17 +40,28 @@ export declare class ApiConnection {
40
40
  * @param catchGlobally Optional. If true, raises this the global error handler each time the promise is rejected.
41
41
  */
42
42
  readonly askUploadMethod: (itemGuid: string, fileName: string, data: File, config?: AxiosRequestConfig, catchGlobally?: boolean) => Promise<IApiResult>;
43
+ /**
44
+ *
45
+ * @param file File to be uploaded
46
+ * @param data Additional data to be sent as URL parameters
47
+ * @param methodName API method name. Ex. 'SaveBinaryAttachment'.
48
+ * @param successCallback Handler callback when the method executes well. Gets the whole response JSON object as the only argument.
49
+ * @param unsuccessCallback Optional. Handler callback for eWay-API app level failures. Gets the whole response JSON object as the only argument. If not supplied, the global error handler is used.
50
+ * @param errorCallback Optional. Handler callback for any other failures. If not supplied, the global error handler is used.
51
+ * @param config Optional. Additional config for the request.
52
+ */
53
+ readonly callCustomUploadMethod: (file: File, data: Record<string, string>, methodName: string, successCallback: (res: IApiResult) => void, unsuccessCallback?: ((e: IApiResult) => void) | undefined, errorCallback?: ((e: TUnionError) => void) | undefined, config?: AxiosRequestConfig) => void;
43
54
  /**
44
55
  * Asynchronously uploads file using binary stream
45
56
  * @param itemGuid Item identificator. Ex. '9ac561be-9b7d-4938-8e55-4cce97142483'.
46
57
  * @param fileName File name, ex. 'picture.img'.
47
- * @param data Single file to be uploaded.
58
+ * @param file Single file to be uploaded.
48
59
  * @param successCallback Handler callback when the method executes well. Gets the whole response JSON object as the only argument.
49
60
  * @param unsuccessCallback Optional. Handler callback for eWay-API app level failures. Gets the whole response JSON object as the only argument. If not supplied, the global error handler is used.
50
61
  * @param errorCallback Optional. Handler callback for any other failures. If not supplied, the global error handler is used.
51
62
  * @param config Optional. Additional config for the request.
52
63
  */
53
- readonly callUploadMethod: (itemGuid: string, fileName: string, data: File, successCallback: (res: IApiResult) => void, unsuccessCallback?: ((e: IApiResult) => void) | undefined, errorCallback?: ((e: TUnionError) => void) | undefined, config?: AxiosRequestConfig) => void;
64
+ readonly callUploadMethod: (itemGuid: string, fileName: string, file: File, successCallback: (res: IApiResult) => void, unsuccessCallback?: ((e: IApiResult) => void) | undefined, errorCallback?: ((e: TUnionError) => void) | undefined, config?: AxiosRequestConfig) => void;
54
65
  /**
55
66
  * Creates a promise for async API method call.
56
67
  * @param methodName API method name. Ex. 'GetUsers'.
@@ -75,6 +86,7 @@ export declare class ApiConnection {
75
86
  readonly getAllEmailAttachmentsZipGetMethodUrl: (itemGuid: string) => string;
76
87
  readonly getBinaryAttachmentGetMethodUrl: (itemGuid: string, revision?: number) => string;
77
88
  readonly getTransformItemMethodUrl: (itemGuid: string, folderName: string, transformationGuid: string, outputFormat: TransformItemFormats) => string;
89
+ readonly getXsltTransformationDefinitionMethodUrl: (transformationGuid: string) => string;
78
90
  readonly getActiveSessionId: () => string | null;
79
91
  readonly setActiveSessionId: (sessionId: string | null) => void;
80
92
  private static handleCallPromise;
@@ -24,6 +24,9 @@ export declare class ApiMethods {
24
24
  static readonly unlinkItems = "UnlinkItems";
25
25
  static readonly getGoodsFinalPrices = "GetGoodsFinalPrices";
26
26
  static readonly saveItemCopyRelation = "SaveItemCopyRelation";
27
+ static readonly getXsltTransormationDefinition = "GetXsltTransformationDefinition";
28
+ static readonly saveBinaryAttachment = "SaveBinaryAttachment";
29
+ static readonly saveBinaryXsltTransformation = "SaveBinaryXsltTransformation";
27
30
  /**
28
31
  * 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.
29
32
  * For example module Calendar has method GetCalendarsByItemGuids, but the folder name is Calendar.
package/lib/esm/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import e from"axios";import*as t from"universal-base64url";import r from"jwt-decode";import{compare as n}from"compare-versions";var s="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var o,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 r=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},n=0,o=void 0,i=void 0,a=function(e,t){T[n]=e,T[n+1]=t,2===(n+=2)&&(i?i(E):A())};function l(e){i=e}function c(e){a=e}var u="undefined"!=typeof window?window:void 0,d=u||{},m=d.MutationObserver||d.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!==o?function(){o(E)}:g()}function f(){var e=0,t=new m(E),r=document.createTextNode("");return t.observe(r,{characterData:!0}),function(){r.data=e=++e%2}}function P(){var e=new MessageChannel;return e.port1.onmessage=E,function(){return e.port2.postMessage(0)}}function g(){var e=setTimeout;return function(){return e(E,1)}}var T=new Array(1e3);function E(){for(var e=0;e<n;e+=2)(0,T[e])(T[e+1]),T[e]=void 0,T[e+1]=void 0;n=0}function S(){try{var e=Function("return this")().require("vertx");return o=e.runOnLoop||e.runOnContext,C()}catch(e){return g()}}var A=void 0;function v(e,t){var r=this,n=new this.constructor(b);void 0===n[k]&&$(n);var s=r._state;if(s){var o=arguments[s-1];a(function(){return B(s,n,o,r._result)})}else j(r,n,e,t);return n}function I(e){var t=this;if(e&&"object"==typeof e&&e.constructor===t)return e;var r=new t(b);return _(r,e),r}A=p?y():m?f():h?P():void 0===u?S():g();var k=Math.random().toString(36).substring(2);function b(){}var D=void 0,w=1,F=2;function O(){return new TypeError("You cannot resolve a promise with itself")}function N(){return new TypeError("A promises callback cannot return that same promise.")}function R(e,t,r,n){try{e.call(t,r,n)}catch(e){return e}}function x(e,t,r){a(function(e){var n=!1,s=R(r,t,function(r){n||(n=!0,t!==r?_(e,r):V(e,r))},function(t){n||(n=!0,G(e,t))},"Settle: "+(e._label||" unknown promise"));!n&&s&&(n=!0,G(e,s))},e)}function L(e,t){t._state===w?V(e,t._result):t._state===F?G(e,t._result):j(t,void 0,function(t){return _(e,t)},function(t){return G(e,t)})}function M(e,r,n){r.constructor===e.constructor&&n===v&&r.constructor.resolve===I?L(e,r):void 0===n?V(e,r):t(n)?x(e,r,n):V(e,r)}function _(t,r){if(t===r)G(t,O());else if(e(r)){var n=void 0;try{n=r.then}catch(e){return void G(t,e)}M(t,r,n)}else V(t,r)}function U(e){e._onerror&&e._onerror(e._result),W(e)}function V(e,t){e._state===D&&(e._result=t,e._state=w,0!==e._subscribers.length&&a(W,e))}function G(e,t){e._state===D&&(e._state=F,e._result=t,a(U,e))}function j(e,t,r,n){var s=e._subscribers,o=s.length;e._onerror=null,s[o]=t,s[o+w]=r,s[o+F]=n,0===o&&e._state&&a(W,e)}function W(e){var t=e._subscribers,r=e._state;if(0!==t.length){for(var n=void 0,s=void 0,o=e._result,i=0;i<t.length;i+=3)n=t[i],s=t[i+r],n?B(r,n,s,o):s(o);e._subscribers.length=0}}function B(e,r,n,s){var o=t(n),i=void 0,a=void 0,l=!0;if(o){try{i=n(s)}catch(e){l=!1,a=e}if(r===i)return void G(r,N())}else i=s;r._state!==D||(o&&l?_(r,i):!1===l?G(r,a):e===w?V(r,i):e===F&&G(r,i))}function H(e,t){try{t(function(t){_(e,t)},function(t){G(e,t)})}catch(t){G(e,t)}}var z=0;function Q(){return z++}function $(e){e[k]=z++,e._state=void 0,e._result=void 0,e._subscribers=[]}function q(){return new Error("Array Methods must be provided an Array")}var J=function(){function e(e,t){this._instanceConstructor=e,this.promise=new e(b),this.promise[k]||$(this.promise),r(t)?(this.length=t.length,this._remaining=t.length,this._result=new Array(this.length),0===this.length?V(this.promise,this._result):(this.length=this.length||0,this._enumerate(t),0===this._remaining&&V(this.promise,this._result))):G(this.promise,q())}return e.prototype._enumerate=function(e){for(var t=0;this._state===D&&t<e.length;t++)this._eachEntry(e[t],t)},e.prototype._eachEntry=function(e,t){var r=this._instanceConstructor,n=r.resolve;if(n===I){var s=void 0,o=void 0,i=!1;try{s=e.then}catch(e){i=!0,o=e}if(s===v&&e._state!==D)this._settledAt(e._state,t,e._result);else if("function"!=typeof s)this._remaining--,this._result[t]=e;else if(r===te){var a=new r(b);i?G(a,o):M(a,e,s),this._willSettleAt(a,t)}else this._willSettleAt(new r(function(t){return t(e)}),t)}else this._willSettleAt(n(e),t)},e.prototype._settledAt=function(e,t,r){var n=this.promise;n._state===D&&(this._remaining--,e===F?G(n,r):this._result[t]=r),0===this._remaining&&V(n,this._result)},e.prototype._willSettleAt=function(e,t){var r=this;j(e,void 0,function(e){return r._settledAt(w,t,e)},function(e){return r._settledAt(F,t,e)})},e}();function X(e){return new J(this,e).promise}function K(e){var t=this;return r(e)?new t(function(r,n){for(var s=e.length,o=0;o<s;o++)t.resolve(e[o]).then(r,n)}):new t(function(e,t){return t(new TypeError("You must pass an array to race."))})}function Y(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[k]=Q(),this._result=this._state=void 0,this._subscribers=[],b!==t&&("function"!=typeof t&&Z(),this instanceof e?H(this,t):ee())}return e.prototype.catch=function(e){return this.then(null,e)},e.prototype.finally=function(e){var r=this,n=r.constructor;return t(e)?r.then(function(t){return n.resolve(e()).then(function(){return t})},function(t){return n.resolve(e()).then(function(){throw t})}):r.then(e,e)},e}();function re(){var e=void 0;if(void 0!==s)e=s;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 r=null;try{r=Object.prototype.toString.call(t.resolve())}catch(e){}if("[object Promise]"===r&&!t.cast)return}e.Promise=te}return te.prototype.then=v,te.all=X,te.race=K,te.resolve=I,te.reject=Y,te._setScheduler=l,te._setAsap=c,te._asap=a,te.polyfill=re,te.Promise=te,te}();
1
+ import e from"axios";import*as t from"universal-base64url";import r from"jwt-decode";import{compare as n}from"compare-versions";var s="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var o,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 r=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},n=0,o=void 0,i=void 0,a=function(e,t){T[n]=e,T[n+1]=t,2===(n+=2)&&(i?i(E):v())};function l(e){i=e}function c(e){a=e}var u="undefined"!=typeof window?window:void 0,d=u||{},m=d.MutationObserver||d.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!==o?function(){o(E)}:g()}function f(){var e=0,t=new m(E),r=document.createTextNode("");return t.observe(r,{characterData:!0}),function(){r.data=e=++e%2}}function P(){var e=new MessageChannel;return e.port1.onmessage=E,function(){return e.port2.postMessage(0)}}function g(){var e=setTimeout;return function(){return e(E,1)}}var T=new Array(1e3);function E(){for(var e=0;e<n;e+=2)(0,T[e])(T[e+1]),T[e]=void 0,T[e+1]=void 0;n=0}function S(){try{var e=Function("return this")().require("vertx");return o=e.runOnLoop||e.runOnContext,C()}catch(e){return g()}}var v=void 0;function A(e,t){var r=this,n=new this.constructor(b);void 0===n[k]&&$(n);var s=r._state;if(s){var o=arguments[s-1];a(function(){return W(s,n,o,r._result)})}else j(r,n,e,t);return n}function I(e){var t=this;if(e&&"object"==typeof e&&e.constructor===t)return e;var r=new t(b);return U(r,e),r}v=p?y():m?f():h?P():void 0===u?S():g();var k=Math.random().toString(36).substring(2);function b(){}var D=void 0,w=1,F=2;function O(){return new TypeError("You cannot resolve a promise with itself")}function N(){return new TypeError("A promises callback cannot return that same promise.")}function R(e,t,r,n){try{e.call(t,r,n)}catch(e){return e}}function x(e,t,r){a(function(e){var n=!1,s=R(r,t,function(r){n||(n=!0,t!==r?U(e,r):V(e,r))},function(t){n||(n=!0,G(e,t))},"Settle: "+(e._label||" unknown promise"));!n&&s&&(n=!0,G(e,s))},e)}function L(e,t){t._state===w?V(e,t._result):t._state===F?G(e,t._result):j(t,void 0,function(t){return U(e,t)},function(t){return G(e,t)})}function M(e,r,n){r.constructor===e.constructor&&n===A&&r.constructor.resolve===I?L(e,r):void 0===n?V(e,r):t(n)?x(e,r,n):V(e,r)}function U(t,r){if(t===r)G(t,O());else if(e(r)){var n=void 0;try{n=r.then}catch(e){return void G(t,e)}M(t,r,n)}else V(t,r)}function _(e){e._onerror&&e._onerror(e._result),B(e)}function V(e,t){e._state===D&&(e._result=t,e._state=w,0!==e._subscribers.length&&a(B,e))}function G(e,t){e._state===D&&(e._state=F,e._result=t,a(_,e))}function j(e,t,r,n){var s=e._subscribers,o=s.length;e._onerror=null,s[o]=t,s[o+w]=r,s[o+F]=n,0===o&&e._state&&a(B,e)}function B(e){var t=e._subscribers,r=e._state;if(0!==t.length){for(var n=void 0,s=void 0,o=e._result,i=0;i<t.length;i+=3)n=t[i],s=t[i+r],n?W(r,n,s,o):s(o);e._subscribers.length=0}}function W(e,r,n,s){var o=t(n),i=void 0,a=void 0,l=!0;if(o){try{i=n(s)}catch(e){l=!1,a=e}if(r===i)return void G(r,N())}else i=s;r._state!==D||(o&&l?U(r,i):!1===l?G(r,a):e===w?V(r,i):e===F&&G(r,i))}function H(e,t){try{t(function(t){U(e,t)},function(t){G(e,t)})}catch(t){G(e,t)}}var z=0;function Q(){return z++}function $(e){e[k]=z++,e._state=void 0,e._result=void 0,e._subscribers=[]}function q(){return new Error("Array Methods must be provided an Array")}var J=function(){function e(e,t){this._instanceConstructor=e,this.promise=new e(b),this.promise[k]||$(this.promise),r(t)?(this.length=t.length,this._remaining=t.length,this._result=new Array(this.length),0===this.length?V(this.promise,this._result):(this.length=this.length||0,this._enumerate(t),0===this._remaining&&V(this.promise,this._result))):G(this.promise,q())}return e.prototype._enumerate=function(e){for(var t=0;this._state===D&&t<e.length;t++)this._eachEntry(e[t],t)},e.prototype._eachEntry=function(e,t){var r=this._instanceConstructor,n=r.resolve;if(n===I){var s=void 0,o=void 0,i=!1;try{s=e.then}catch(e){i=!0,o=e}if(s===A&&e._state!==D)this._settledAt(e._state,t,e._result);else if("function"!=typeof s)this._remaining--,this._result[t]=e;else if(r===te){var a=new r(b);i?G(a,o):M(a,e,s),this._willSettleAt(a,t)}else this._willSettleAt(new r(function(t){return t(e)}),t)}else this._willSettleAt(n(e),t)},e.prototype._settledAt=function(e,t,r){var n=this.promise;n._state===D&&(this._remaining--,e===F?G(n,r):this._result[t]=r),0===this._remaining&&V(n,this._result)},e.prototype._willSettleAt=function(e,t){var r=this;j(e,void 0,function(e){return r._settledAt(w,t,e)},function(e){return r._settledAt(F,t,e)})},e}();function X(e){return new J(this,e).promise}function K(e){var t=this;return r(e)?new t(function(r,n){for(var s=e.length,o=0;o<s;o++)t.resolve(e[o]).then(r,n)}):new t(function(e,t){return t(new TypeError("You must pass an array to race."))})}function Y(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[k]=Q(),this._result=this._state=void 0,this._subscribers=[],b!==t&&("function"!=typeof t&&Z(),this instanceof e?H(this,t):ee())}return e.prototype.catch=function(e){return this.then(null,e)},e.prototype.finally=function(e){var r=this,n=r.constructor;return t(e)?r.then(function(t){return n.resolve(e()).then(function(){return t})},function(t){return n.resolve(e()).then(function(){throw t})}):r.then(e,e)},e}();function re(){var e=void 0;if(void 0!==s)e=s;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 r=null;try{r=Object.prototype.toString.call(t.resolve())}catch(e){}if("[object Promise]"===r&&!t.cast)return}e.Promise=te}return te.prototype.then=A,te.all=X,te.race=K,te.resolve=I,te.reject=Y,te._setScheduler=l,te._setAsap=c,te._asap=a,te.polyfill=re,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"}(o||(o={}));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 u{}u.isValidFolderName=e=>Object.values(u).includes(e),u.actions="Actions",u.additionalFields="AdditionalFields",u.bonuses="Bonuses",u.calendar="Calendar",u.capacityNotes="CapacityNotes",u.capacityNoteTypes="CapacityNoteTypes",u.carts="Carts",u.columnPermissions="ColumnPermissions",u.companies="Companies",u.contacts="Contacts",u.contactsSuggestions="ContactsSuggestions",u.currencyExchangeRates="CurrencyExchangeRates",u.documents="Documents",u.emails="Emails",u.enumTypes="EnumTypes",u.enumValues="EnumValues",u.enumValuesRelations="EnumValuesRelations",u.features="Features",u.flows="Flows",u.globalSettings="GlobalSettings",u.goals="Goals",u.goods="Goods",u.goodsInCart="GoodsInCart",u.goodsInSet="GoodsInSet",u.groups="Groups",u.history="History",u.holidays="Holidays",u.children="Children",u.individualDiscounts="IndividualDiscounts",u.invoiceItems="InvoiceItems",u.invoices="Invoices",u.itemCopyRelations="ItemCopyRelations",u.journal="Journal",u.knowledge="Knowledge",u.layouts="Layouts",u.layoutsModels="LayoutsModels",u.leads="Leads",u.ledger="Ledger",u.mappings="Mappings",u.marketing="Marketing",u.marketingList="MarketingList",u.marketingListSources="MarketingListSources",u.models="Models",u.modulePermissions="ModulePermissions",u.objectTypesOptions="ObjectTypesOptions",u.payments="Payments",u.priceListGroups="PriceListGroups",u.projectAssignments="ProjectAssignments",u.projectAssignmentsPerUserProject="ProjectAssignmentsPerUserProject",u.projectAssignmentsTotal="ProjectAssignmentsTotal",u.projectAssignmentsTotalUserProject="ProjectAssignmentsTotalUserProject",u.projectList="ProjectList",u.projects="Projects",u.projectUsersInCaPlan="ProjectUsersInCaPlan",u.relationData="RelationData",u.relations="Relations",u.reports="Reports",u.revisionsHistory="RevisionsHistory",u.salaries="Salaries",u.salePrices="SalePrices",u.prices="Prices",u.sqlObjects="SqlObjects",u.tasks="Tasks",u.recurrencePatterns="RecurrencePatterns",u.teamRoles="TeamRoles",u.templates="Templates",u.training="Training",u.unifiedRelations="UnifiedRelations",u.users="Users",u.userSettings="UserSettings",u.vacation="Vacation",u.webAccess2Options="WebAccess2Options",u.webAccessOptions="WebAccessOptions",u.workCommitments="WorkCommitments",u.workflowHistory="WorkflowHistory",u.workReports="WorkReports",u.wrongClientVersions="WrongClientVersions",u.xsltTransformations="XsltTransformations",u.xsltTransformationsModels="XsltTransformationsModels",u.getEnumTypeName=e=>e===u.bonuses?c.bonusType:e===u.carts?c.cartType:e===u.companies?c.companyType:e===u.contacts?c.contactType:e===u.documents?c.documentType:e===u.emails?c.emailType:e===u.goals?c.goalType:e===u.goods?c.productType:e===u.journal?c.journalType:e===u.knowledge?c.knowledgeType:e===u.leads?c.leadType:e===u.marketing?c.marketingType:e===u.projects?c.projectType:e===u.salaries?c.salaryType:e===u.salePrices?c.salePriceType:e===u.tasks?c.taskType:e===u.training?c.trainingTitle:e===u.users?c.userType:e===u.vacation?c.vacationType:e===u.workReports?c.workReportType:null,u.getFolderNameByEnumTypeName=e=>e===c.bonusType?u.bonuses:e===c.cartType?u.carts:e===c.companyType?u.companies:e===c.contactType?u.contacts:e===c.documentType?u.documents:e===c.emailType?u.emails:e===c.goalType?u.goals:e===c.journalType?u.journal:e===c.knowledgeType?u.knowledge:e===c.leadType?u.leads:e===c.marketingType?u.marketing:e===c.productType?u.goods:e===c.projectType?u.projects:e===c.salaryType?u.salaries:e===c.salePriceType?u.salePrices:e===c.taskType?u.tasks:e===c.trainingTitle?u.training:e===c.userType?u.users:e===c.vacationType?u.vacation:e===c.workReportType?u.workReports:null;class d{}d.getAllEmailAttachments="GetAllEmailAttachments",d.getCalendarsByItemGuids="GetCalendarsByItemGuids",d.getEmailAttachment="GetEmailAttachment",d.getItemPreview="GetItemPreview",d.getJournalsByItemGuids="GetJournalsByItemGuids",d.getMarketingCampaignsByItemGuids="GetMarketingCampaignsByItemGuids",d.getMarketingListsRecordsByItemGuids="GetMarketingListsRecordsByItemGuids",d.getRevisionHistoryRecordsByItemGuids="GetRevisionHistoryRecordsByItemGuids",d.getVacationsByItemGuids="GetVacationsByItemGuids",d.getWorkflowHistoryRecordsByItemGuids="GetWorkflowHistoryRecordsByItemGuids",d.getCompanyInformationFromTaxRegister="GetCompanyInformationFromTaxRegister",d.logIn="LogIn",d.logOut="LogOut",d.query="Query",d.queryAmount="QueryAmount",d.getServiceAuthSettings="GetServiceAuthSettings",d.getVersion="GetVersion",d.getBinaryAttachment="GetBinaryAttachment",d.getBinaryAttachmentLatestRevision="GetBinaryAttachmentLatestRevision",d.transformItem="TransformItem",d.canUnlinkItems="CanUnlinkItems",d.unlinkItems="UnlinkItems",d.getGoodsFinalPrices="GetGoodsFinalPrices",d.saveItemCopyRelation="SaveItemCopyRelation",d.getFolderNameForApiMethod=e=>{switch(e){case u.calendar:return"Calendars";case u.journal:return"Journals";case u.marketing:return"MarketingCampaigns";case u.marketingList:return"MarketingListsRecords";case u.revisionsHistory:return"RevisionHistoryRecords";case u.vacation:return"Vacations";case u.workflowHistory:return"WorkflowHistoryRecords";default:return e}},d.getGetFolderNameByItemGuidsMethodName=e=>`Get${d.getFolderNameForApiMethod(e)}ByItemGuids`,d.getGetFolderNameMethodName=e=>`Get${d.getFolderNameForApiMethod(e)}`,d.getSearchFolderNameMethodName=e=>`Search${d.getFolderNameForApiMethod(e)}`;class m{constructor(e,t,r,n,s,o){if(this.invalidateSessionId=(e,t)=>{t&&t()},this.getSessionId=(e,t)=>{e.callWithoutSession(d.logIn,{userName:this.username,passwordHash:this.passwordHash,appVersion:this.appVersion,clientMachineIdentifier:this.clientMachineIdentifier,clientMachineName:this.clientMachineName,createSessionCookie:e.supportsGetItemPreviewMethod},e=>{this.lastSuccessfulLoginResponse=e;const r=e.SessionId;if(!r){const e=new Error("Successful login but no session came.");if(!this.errorCallback)throw e;return void this.errorCallback(e)}t&&t(r)},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=r,this.clientMachineIdentifier=n,this.clientMachineName=s,this.errorCallback=o}}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,r,n,s,o,i=!1,a){if(s&&!o||!s&&o)throw new Error("If codeChallenge is defined, codeChallengeMethod must also be defined and vice versa");let l=`https://login.eway-crm.${i?"dev":"com"}?scope=${encodeURIComponent(t.join(" "))}&prompt=login&response_type=code&redirect_uri=${encodeURIComponent(r)}&client_id=${e}`;return n&&(l+=`&state=${encodeURIComponent(n)}`),s&&o&&(l+=`&code_challenge=${encodeURIComponent(s)}&code_challenge_method=${encodeURIComponent(o)}`),a&&(l+=`&url=${encodeURIComponent(a)}`),l}}h.finishAuthorization=(e,t,r,n,s,o,i)=>{const a=new URLSearchParams;a.append("code_verifier",n),a.append("client_id",t),a.append("client_secret",r),a.append("code",s),a.append("redirect_uri",o),a.append("grant_type","authorization_code"),h.callTokenEndpoint(e,a,i)},h.refreshToken=(e,t,r,n,s)=>{const o=new URLSearchParams;o.append("client_id",t),o.append("client_secret",r),o.append("refresh_token",n),o.append("grant_type","refresh_token"),h.callTokenEndpoint(e,o,s)},h.getWebServiceUrl=e=>{const r=e.split(".");if(2!==r.length)throw new Error("Invalid token supplied");return t.decode(r[1])},h.getUserName=e=>h.decodeAccessToken(e).username,h.decodeAccessToken=e=>r(e),h.callTokenEndpoint=(t,r,n)=>{e.post(t+"/auth/connect/token",r,{headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(e=>{n(e.data)}).catch(e=>{e.response&&400==e.response.status?n(e.response.data):n({error:"Token request failed"})})};class y extends Error{constructor(e,t){super(),this.returnCode=e,this.message=t}}class C{constructor(e,t,r,n,s){if(this.invalidateSessionId=(e,t)=>{t&&t()},this.getSessionId=(e,t)=>{const r={userName:this.username,appVersion:this.appVersion,createSessionCookie:e.supportsGetItemPreviewMethod},n={Authorization:"Bearer "+this.accessToken};e.callWithoutSession(d.logIn,r,e=>{this.lastSuccessfulLoginResponse=e;const r=e.SessionId;if(!r){const e=new Error("Successful login but no session came.");if(!this.errorCallback)throw e;return void this.errorCallback(e)}t&&t(r)},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,r=>{if(401!==(null==r?void 0:r.statusCode)){if(!this.errorCallback)throw r;this.errorCallback(r)}else this.getNewAccessTokenCallback(e,r=>{this.accessToken=r.accessToken,r.error||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=r,this.getNewAccessTokenCallback=n,this.errorCallback=s}}class f extends C{constructor(e,t,r,n,s,o,i,a){if(!(e&&n&&t&&r))throw new Error("Non of the arguments 'username', 'clientId', 'clientSecret', 'refreshToken' can be empty.");super(e,s,o,(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)))}void 0!==e.error?t({error:e.error}):t({accessToken:e.access_token})})},i),this.refreshToken=n,this.clientId=t,this.clientSecret=r,this.refreshTokenCallback=a}}class P extends Error{constructor(e,t){super(),this.statusCode=e,this.message=t}}class g{}g.stringifyError=e=>JSON.stringify(e,g.replaceErrors),g.replaceErrors=(e,t)=>{if(t instanceof Error){const e={};return Object.getOwnPropertyNames(t).forEach(r=>{e[r]=t[r]}),e}return t};class T{constructor(r,n,s,i){if(this.ensureLogin=()=>new Promise((e,t)=>{if(this.sessionId)e();else{const r=r=>{r&&(this.sessionId=r,e()),t("Session Id cannot be empty")};this.sessionHandler.getSessionId(this,r)}}),this.createOpenLink=(e,r,n,s)=>{const o=t.encode(this.baseUri);let i="eway://"+r;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="+o+"&l="+i;return s&&(l+="&n="+encodeURIComponent(s)),l},this.askUploadMethod=(e,t,r,n,s)=>new Promise((o,i)=>{const a=s?e=>{throw i(e),e}:i;this.callUploadMethod(e,t,r,o,a,a,n)}),this.callUploadMethod=(t,r,n,s,o,i,a)=>{const c=()=>{this.sessionHandler.getSessionId(this,e=>{this.sessionId=e,this.callUploadMethod(t,r,n,s,o,i,a)})},u=this.sessionId;if(!u)return void c();const d=`${this.svcUri}/SaveBinaryAttachment?sessionId=${this.sessionId}&itemGuid=${t}&fileName=${encodeURIComponent(r)}`,m=e.post(d,n,a);T.handleCallPromise(m,s,e=>{if(e.ReturnCode===l.rcBadSession)return this.sessionId=null,void this.sessionHandler.invalidateSessionId(u,c);if(o)o(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 "+d+": "+g.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,r,n)=>new Promise((s,o)=>{const i=n?e=>{throw o(e),e}:o;this.callMethod(e,t,s,i,r,i)}),this.callMethod=(e,t,r,n,s,i)=>{s||(s=o.post);const a=()=>{this.sessionHandler.getSessionId(this,o=>{this.sessionId=o,this.callMethod(e,t,r,n,s,i)})},c=this.sessionId;if(!c)return void a();t.sessionId=c;const u=e!==d.logOut?r:e=>{this.sessionId=null,r(e)};this.callWithoutSession(e,t,u,r=>{if(r.ReturnCode!==l.rcBadSession||(this.sessionId=null,e===d.logOut))if(n)n(r);else{const e=new Error("Unhandled connection return code "+r.ReturnCode+": "+r.Description);if(!this.errorCallback)throw e;this.errorCallback(e,t)}else this.sessionHandler.invalidateSessionId(c,a)},null,s,i)},this.callWithoutSession=(t,r,n,s,i,a,l)=>{var c;a||(a=o.post);const u=this.svcUri+"/"+t;let m,p;switch(i&&(m={headers:i,withCredentials:null!==(c=this.supportGetItemPreviewMethod)&&void 0!==c?c:t==d.logIn}),a){case o.get:if(r)throw new Error("Calling api get method with data specified does not make any sense.");p=e.get(u,m);break;case o.post:p=e.post(u,r,m);break;default:throw new Error(`Unknown http method '${a}'.`)}T.handleCallPromise(p,n,s,e=>{if(l)try{l(e)}catch(e){if(!this.errorCallback)throw e;this.errorCallback(e,r)}else{const t=new Error("Unhandled connection error when calling "+u+": "+g.stringifyError(e));if(!this.errorCallback)throw t;this.errorCallback(t,r)}})},this.getItemPreviewGetMethodUrl=(e,t,r)=>this.svcUri+"/"+d.getItemPreview+"?folderName="+encodeURIComponent(e)+"&itemGuid="+encodeURIComponent(t)+(r||0===r?"&itemVersion="+encodeURIComponent(r.toString()):""),this.getEmailAttachmentGetMethodUrl=(e,t)=>this.svcUri+"/"+d.getEmailAttachment+"?itemGuid="+encodeURIComponent(e)+"&contentId="+encodeURIComponent(t),this.getAllEmailAttachmentsZipGetMethodUrl=e=>this.svcUri+"/"+d.getAllEmailAttachments+"?itemGuid="+encodeURIComponent(e),this.getBinaryAttachmentGetMethodUrl=(e,t)=>"number"==typeof t?this.svcUri+"/"+d.getBinaryAttachment+"?itemGuid="+encodeURIComponent(e)+`&revision=${t}`:this.svcUri+"/"+d.getBinaryAttachmentLatestRevision+"?itemGuid="+encodeURIComponent(e),this.getTransformItemMethodUrl=(e,t,r,n)=>`${this.svcUri}/${d.transformItem}?itemGuid=${encodeURIComponent(e)}&itemFolderName=${encodeURIComponent(t)}&transformationGuid=${encodeURIComponent(r)}&outputFormat=${n}`,this.getActiveSessionId=()=>this.sessionId,this.setActiveSessionId=e=>{this.sessionId=e},!r)throw new Error("The argument 'apiServiceUri' cannot be empty.");if(r.length<8||"https://"!==r.substr(0,8).toLowerCase()&&"http://"!==r.substr(0,7).toLowerCase())throw new Error("Api service uri must start either with 'https://' or with 'http://'.");if(".svc"===r.substr(r.length-4).toLowerCase()){this.svcUri=r;const e=["/API.svc","/InsecureAPI.svc","/WcfService/Service.svc"].find(e=>e.toLowerCase()===r.substr(r.length-e.length).toLowerCase())||"";this.baseUri=r.substr(0,r.length-e.length)}else this.baseUri=T.normalizeWsUrl(r)||r,"https://"===r.substr(0,8).toLowerCase()?this.svcUri=this.baseUri+"/API.svc":this.svcUri=this.baseUri+"/InsecureAPI.svc";this.sessionHandler=n,this.errorCallback=s,this.sessionId=null,this.supportGetItemPreviewMethod=null!=i&&i}get supportsGetItemPreviewMethod(){return this.supportGetItemPreviewMethod}static create(e,t,r,n,s,o,i,a){return new T(e,new m(t,r,n,s,o,i),i,a)}static createAnonymous(e,t){return new T(e,new p,t)}static createUsingOAuth(e,t,r,n,s,o,i,a,l,c){return new T(e,new f(t,r,n,s,o,i,a,l),a,c)}static normalizeWsUrl(e){return e&&e.endsWith("/")&&(e=e.substring(0,e.length-1)),e}static isCloudUrl(e,t){const r=new URL(e),n=new Set;return n.add("hosting.eway-crm.com"),n.add("free.eway-crm.com"),n.add("hosting.eway-crm.us"),n.add("hosting-vh39276.eway-crm.us"),n.add("free.eway-crm.us"),t&&(n.add("free.eway-crm.dev"),n.add("hosting.eway-crm.dev"),n.add("localhost")),n.has(r.host)}get wsUrl(){return this.baseUri}static handleCallPromise(e,t,r,n){e.then(e=>{200===e.status?e.data.ReturnCode===l.rcSuccess?t(e.data):r(e.data):n(new P(e.status,e.statusText))}).catch(e=>{e.response?n(new P(e.response.status,e.response.statusText)):n(e)})}}class E{constructor(e,t,r,n,s,o,i){this.isEnabled=(e,t)=>{const r=()=>{this.url&&this.token?e(this.url,this.token):t()};this.url&&this.token?e(this.url,this.token):this.obtainToken(r)},this.callTokenizedApi=(e,t,r,n)=>{this.isEnabled((s,o)=>{t.token=o,E.call(s,e,t,r,s=>{if(s.ReturnCodeString!==this.invalidTokenReturnCode){if(n)n(s);else if(this.generalErrorCallback){const e=new Error("Unhandled tokenized service connection return code "+s.ReturnCodeString+".\nDescription: "+s.Description);this.generalErrorCallback(e)}}else this.obtainToken(()=>{this.callTokenizedApi(e,t,r,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 r=this.urlAndTokenObtainer(t);r.url&&r.token?(this.url=r.url,this.token=r.token,this.isActive=!0,e()):(this.url=null,this.token=null,this.isActive=!1,e())},r=()=>{this.url=null,this.token=null,this.isActive=!1,e()};this.needsSession?this.connection.callMethod(this.obtainTokenMethodName,{},t,r,this.obtainTokenMethodType):this.connection.callWithoutSession(this.obtainTokenMethodName,null,t,r,null,this.obtainTokenMethodType)},this.obtainTokenMethodName=e,this.obtainTokenMethodType=t,this.needsSession=r,this.invalidTokenReturnCode=n,this.urlAndTokenObtainer=s,this.connection=o,this.generalErrorCallback=i||null,this.url=null,this.token=null,this.isActive=!0}static call(t,r,n,s,o,i){const a=t+"/"+r;e.post(a,n).then(e=>{200===e.status?"Success"===e.data.ReturnCodeString?s(e.data):o(e.data):i(new P(e.status,e.statusText))}).catch(e=>{e.response?i(new P(e.response.status,e.response.statusText)):i(e)})}}const S=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,r,n)=>{this.tokenizedConnection.callTokenizedApi(e,t,r,n)},this.tokenizedConnection=new E("ObtainCommonDataApiAccessToken",o.get,!1,"InvalidCommonDataToken",S,e,t)}}class v{}v.acceptableBackwardWorkReportDays="AcceptableBackwardWorkReportDays",v.adminAppInactiveLogoutTime="AdminAppInactiveLogoutTime",v.applyGeneralDataProtectionRules="ApplyGeneralDataProtectionRules",v.automaticallyCreateJournalAfterCallDuration="AutomaticallyCreateJournalAfterCallDuration",v.bonusesCompletedState="BonusesCompletedState",v.cartInvoicedState="CartInvoicedState",v.cartOrderCanceledState="CartOrderCanceledState",v.cartOrderInProcessState="CartOrderInProcessState",v.cartOrderProcessedState="CartOrderProcessedState",v.cartPaidState="CartPaidState",v.cartProposalInProcessState="CartProposalInProcessState",v.cartProposalProcessedState="CartProposalProcessedState",v.cartSalesVoucherIssuedState="CartSalesVoucherIssuedState",v.cartToBeInvoicedState="CartToBeInvoicedState",v.cartVoidedState="CartVoidedState",v.clickToCallScheme="ClickToCallScheme",v.companyDuplicityCheckEnabled="CompanyDuplicityCheckEnabled",v.completedStateName="CompletedStateName",v.contactDuplicityCheckEnabled="ContactDuplicityCheckEnabled",v.createCompanyWhileImportingContactFromOutlook="CreateCompanyWhileImportingContactFromOutlook",v.defaultProposalValidityPeriod="DefaultProposalValidityPeriod",v.enableContactsTwoWaySyncWithM365="EnableContactsTwoWaySyncWithM365",v.deadStateName="DeadStateName",v.enableCompaniesSyncIntoMobileDeviceContacts="EnableCompaniesSyncIntoMobileDeviceContacts",v.enableContactsSyncIntoMobileDevice="EnableContactsSyncIntoMobileDevice",v.enableLeadsSyncIntoMobileDeviceContacts="EnableLeadsSyncIntoMobileDeviceContacts",v.enableLlamaAiFeatures="EnableLlamaAiFeatures",v.enableUsersSyncIntoMobileDeviceContacts="EnableUsersSyncIntoMobileDeviceContacts",v.emailsActiveProjectsLeadsFilter="EmailsActiveProjectsLeadsFilter",v.exchangeRatesAdminGroupName="ExchangeRatesAdminGroupName",v.forcedEmailTrackingGroups="ForcedEmailTrackingGroups",v.ignoreEmailsFromDomainsOnEmailsTracking="IgnoreEmailsFromDomainsOnEmailsTracking",v.trackEmailsFromDomains="TrackEmailsFromDomains",v.groupsForAllUnpaidInvoicesNotification="GroupsForAllUnpaidInvoicesNotification",v.itemPreviewMaxHeight="ItemPreviewMaxHeight",v.lastActivityAttributes="LastActivityAttributes",v.leadsCompletedState="LeadsCompletedState",v.leadDeadlineAlertGroups="LeadDeadlineAlertGroups",v.leadsDeadState="LeadsDeadState",v.marketingCompletedState="MarketingCompletedState",v.marketingDeadState="MarketingDeadState",v.minimumPasswordLength="MinimumPasswordLength",v.nextStepAttributes="NextStepAttributes",v.notifyAboutInvoicedInvoiceInPohodaGroup="NotifyAboutInvoicedInvoiceInPohodaGroup",v.notifyAboutLeadsDeadline="NotifyAboutLeadsDeadline",v.notifyAboutPaidInvoiceInPohodaGroup="NotifyAboutPaidInvoiceInPohodaGroup",v.notifyAboutProjectDeadline="NotifyAboutProjectDeadline",v.numberOfDecimalPlaces="NumberOfDecimalPlaces",v.phoneListTaskSolverGroup="PhoneListTaskSolverGroup",v.projectDeadlineAlert="ProjectDeadlineAlert",v.serverUpdateProgressNotificationGroup="ServerUpdateProgressNotificationGroup",v.sumarizeCartsPricesOnLeads="SumarizeCartsPricesOnLeads",v.sumarizeCartsPricesOnProjects="SumarizeCartsPricesOnProjects",v.sumarizePeopleExpensesOnProjects="SumarizePeopleExpensesOnProjects",v.systemHealthNotificationGroup="SystemHealthNotificationGroup",v.tasksCompletedState="TasksCompletedState",v.tasksDeferredState="TasksDeferredState",v.tasksInProgressState="TasksInProgressState",v.tasksNotStartedState="TasksNotStartedState",v.tasksWaitOnSomeoneElseState="TasksWaitOnSomeoneElseState",v.trackDocumentVersions="TrackDocumentVersions",v.vacationCompletedState="VacationCompletedState",v.workReportApprovedState="WorkReportApprovedState",v.defaultLanguage="DefaultLanguage",v.defaultCurrency="DefaultCurrency",v.myCompanyCountry="MyCompanyCountry",v.myCompanyName="MyCompanyName",v.myCompanyStreet="MyCompanyStreet",v.myCompanyCity="MyCompanyCity",v.myCompanyState="MyCompanyState",v.myCompanyZip="MyCompanyZIP",v.myCompanyId="MyCompanyID",v.myCompanyVat="MyCompanyVAT",v.mergeGoodsInCart="MergeGoodsInCart",v.cartRefreshLogic="CartRefreshLogic",v.goodsDefaultQuantity="GoodsDefaultQuantity",v.goodsDefaultVAT="GoodsDefaultVAT",v.goodsDefaultVATIncluded="GoodsDefaultVATIncluded";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",Customer:"Customer",Contact:"Contact",TypeEn:"TypeEn",StateEn:"StateEn",PriceTotal:"PriceTotal",PriceTotalExcludingVAT:"PriceTotalExcludingVAT",ForPayment:"ForPayment",Paid:"Paid",CurrencyEn:"CurrencyEn",EffectiveFrom:"EffectiveFrom",ValidUntil:"ValidUntil",Active:"Active",Note:"Note",ID:"ID",AccountingCaseDate:"AccountingCaseDate",TaxableSupplyDate:"TaxableSupplyDate",PaymentDate:"PaymentDate",VAT:"VAT",GoodsInCartCount:"GoodsInCartCount",PriceTotalDefaultCurrency:"PriceTotalDefaultCurrency",PriceTotalParentCurrency:"PriceTotalParentCurrency",ForPaymentDefaultCurrency:"ForPaymentDefaultCurrency",ForPaymentParentCurrency:"ForPaymentParentCurrency",PaidDefaultCurrency:"PaidDefaultCurrency",PaidParentCurrency:"PaidParentCurrency",PaidChanged:"PaidChanged",PriceTotalChanged:"PriceTotalChanged",PriceTotalExcludingVATDefaultCurrency:"PriceTotalExcludingVATDefaultCurrency",PriceTotalExcludingVATParentCurrency:"PriceTotalExcludingVATParentCurrency",VATDefaultCurrency:"VATDefaultCurrency",VATParentCurrency:"VATParentCurrency",PrevStateEn:"PrevStateEn",PurchaseExpenses:"PurchaseExpenses",PurchaseExpensesDefaultCurrency:"PurchaseExpensesDefaultCurrency",PurchaseExpensesParentCurrency:"PurchaseExpensesParentCurrency",PurchaseExpensesChanged:"PurchaseExpensesChanged",Profit:"Profit",ProfitDefaultCurrency:"ProfitDefaultCurrency",ProfitParentCurrency:"ProfitParentCurrency",ProfitChanged:"ProfitChanged"},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",TrackedDomains:"TrackedDomains",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",ExternalUrl:"ExternalUrl"},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.GoodsBase={Code:"Code",Structure:"Structure",Note:"Note",Description:"Description",TypeEn:"TypeEn",SaleCurrencyEn:"SaleCurrencyEn",PurchaseCurrencyEn:"PurchaseCurrencyEn",UnitEn:"UnitEn",PurchasePrice:"PurchasePrice",PurchasePriceDefaultCurrency:"PurchasePriceDefaultCurrency",PurchasePriceChanged:"PurchasePriceChanged",SalePrice:"SalePrice",SalePriceDefaultCurrency:"SalePriceDefaultCurrency",SalePriceChanged:"SalePriceChanged",IsPriceSum:"IsPriceSum",VATRate:"VATRate",VATIncluded:"VATIncluded"},I.Goods=Object.assign(Object.assign({},I.GoodsBase),{PriceListGroupGUID:"PriceListGroupGUID",InventoryQuantity:"InventoryQuantity"}),I.GoodsInCart=Object.assign(Object.assign({},I.GoodsBase),{Cart:"Cart",GoodsInfo:"GoodsInfo",SuperiorItem:"SuperiorItem",Quantity:"Quantity",PriceTotal:"PriceTotal",PriceTotalDefaultCurrency:"PriceTotalDefaultCurrency",PriceTotalParentCurrency:"PriceTotalParentCurrency",PriceTotalChanged:"PriceTotalChanged",PriceTotalExcludingVAT:"PriceTotalExcludingVAT",PriceTotalExcludingVATDefaultCurrency:"PriceTotalExcludingVATDefaultCurrency",PriceTotalExcludingVATParentCurrency:"PriceTotalExcludingVATParentCurrency",VATTotal:"VATTotal",VATTotalDefaultCurrency:"VATTotalDefaultCurrency",VATTotalParentCurrency:"VATTotalParentCurrency",SalePriceExcludingVAT:"SalePriceExcludingVAT",SalePriceExcludingVATDefaultCurrency:"SalePriceExcludingVATDefaultCurrency",SalePriceExcludingVATParentCurrency:"SalePriceExcludingVATParentCurrency",VAT:"VAT",VATDefaultCurrency:"VATDefaultCurrency",VATParentCurrency:"VATParentCurrency",PurchasePriceParentCurrency:"PurchasePriceParentCurrency",SalePriceParentCurrency:"SalePriceParentCurrency",ListPrice:"ListPrice",ListPriceDefaultCurrency:"ListPriceDefaultCurrency",ListPriceParentCurrency:"ListPriceParentCurrency",ListPriceChanged:"ListPriceChanged",Discount:"Discount",HierarchyInSet:"HierarchyInSet",IsFromSet:"IsFromSet",ParentGUID:"ParentGUID",Rank:"Rank",IncludeInCartPrice:"IncludeInCartPrice",ListPriceCustomized:"ListPriceCustomized",ChildItemsCount:"ChildItemsCount",JoinedToGUID:"JoinedToGUID",PurchasePriceTotal:"PurchasePriceTotal",PurchasePriceTotalDefaultCurrency:"PurchasePriceTotalDefaultCurrency",PurchasePriceTotalParentCurrency:"PurchasePriceTotalParentCurrency",PurchasePriceTotalChanged:"PurchasePriceTotalChanged"}),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.PriceListGroups={Note:"Note"},I.Prices={SalePriceGUID:"SalePriceGUID",GoodsItemGUID:"GoodsItemGUID",Price:"Price",CurrencyEn:"CurrencyEn"},I.SalePrices={Note:"Note",Discount:"Discount",TypeEn:"TypeEn",StateEn:"StateEn",PrevStateEn:"PrevStateEn"},I.XsltTransformations={LangCode:"LangCode",Definition:"Definition",Namespace:"Namespace",ObjectTypeID:"ObjectTypeID",TransformationVersion:"TransformationVersion"},I.XsltTransformationsModels={ObjectTypeID:"ObjectTypeID",TransformationGUID:"TransformationGUID",ItemTypeGUID:"ItemTypeGUID"},I.allTypeEnNames=["TypeEn",I.Documents.DocTypeEn,I.WorkReports.WorkReportEn,"TitleEn"],I.getFolderFileAs=e=>{switch(e){case u.leads:return I.Leads.FileAs;case u.projects:return I.Projects.ProjectName;case u.documents:return I.Documents.DocName;case u.companies:return I.Companies.CompanyName;case u.contacts:case u.users:return I.Common.FileAs;case u.emails:return I.Emails.Subject;case u.journal:return I.Journal.FileAs;case u.tasks:return I.Tasks.Subject;case u.workReports:return I.WorkReports.Subject;case u.vacation:return I.Vacation.TypeEn;case u.carts:case u.goods:case u.goodsInCart:return I.Common.FileAs;case u.groups:return I.Groups.GroupName;case u.xsltTransformations:return I.Common.FileAs;default:return console.warn(`FileAs col name not defined for folderName ${e}`),I.Common.FileAs}};class k{}k.general="GENERAL",k.group="GROUP",k.contactPerson="CONTACTPERSON",k.contact="CONTACT",k.customer="CUSTOMER",k.company="COMPANY",k.outlookProject="OUTLOOKPROJECT",k.supervisor="SUPERVISOR",k.projectOrigin="PROJECT_ORIGIN",k.cart="CART",k.goodsInCart="GOODSINCART",k.superiorItem="SUPERIORITEM";class b{}b.general=1,b.group=2,b.contactPerson=10,b.contact=11,b.customer=12,b.company=13,b.outlookProject=28,b.supervisor=32,b.projectOrigin=25,b.cart=9,b.goodsInCart=15,b.superiorItem=31;class D{}D.all="All",D.own="Own",D.readonly="Readonly",D.invisible="Invisible",D.none="None";class w{}var F,O,N,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"}(F||(F={})),function(e){e.ContactsAndCompanies="ContactsAndCompanies",e.Sales="Sales",e.Projects="Projects",e.Marketing="Marketing"}(O||(O={})),function(e){e[e.Negative=0]="Negative",e[e.Neutral=1]="Neutral",e[e.Positive=2]="Positive"}(N||(N={}));class x{}x.contactsSynchronizationWithOutlook="ContactsSynchronizationWithOutlook",x.wordAddin="WordAddin",x.excelAddin="ExcelAddin",x.tasksRecurrentTasks="TasksRecurrentTasks",x.tasksSubtasks="TasksSubtasks",x.tasksSynchronizationWithOutlook="TasksSynchronizationWithOutlook",x.calendarSynchronizationWithOutlook="CalendarSynchronizationWithOutlook",x.emailsAutomaticTracking="EmailsAutomaticTracking",x.convertEmailToProject="ConvertEmailToProject",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.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.api="API",x.gate="Gate",x.threeCXIntegration="ThreeCXIntegration",x.tapiIntegration="TapiIntegration",x.pohodaIntegration="PohodaIntegration",x.pohodaSynchronizationIntervalCustomization="PohodaSynchronizationIntervalCustomization",x.pohodaSynchronizationFieldMappingCustomization="PohodaSynchronizationFieldMappingCustomization",x.quickBooksIntegration="QuickBooksIntegration",x.saveBinaryDataOnDisk="SaveBinaryDataOnDisk",x.activeDirectoryLogin="ActiveDirectoryLogin",x.callerIdentificationOnApple="CallerIdentificationOnApple",x.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 M{}M.contactsAutomaticSynchronizationWithOutlook="ContactsAutomaticSynchronizationWithOutlook",M.contactsSynchronizationWithOutlook="ContactsSynchronizationWithOutlook",M.contactsSynchronizationWithAndroid="ContactsSynchronizationWithAndroid",M.documentsRevisions="DocumentsRevisions",M.wordAddin="WordAddin",M.excelAddin="ExcelAddin",M.tasksReminders="TasksReminders",M.tasksRecurrentTasks="TasksRecurrentTasks",M.tasksSubtasks="TasksSubtasks",M.tasksSynchronizationWithOutlook="TasksSynchronizationWithOutlook",M.calendarSynchronizationWithOutlook="CalendarSynchronizationWithOutlook",M.emailsManualTracking="EmailsManualTracking",M.emailsAutomaticTracking="EmailsAutomaticTracking",M.emailSummaryAndSentimentToneFromAi="EmailSummaryAndSentimentToneFromAi",M.convertEmailToContact="ConvertEmailToContact",M.convertEmailToDeal="ConvertEmailToDeal",M.convertEmailToProject="ConvertEmailToProject",M.convertEmailToTask="ConvertEmailToTask",M.convertFromSuggestedContact="ConvertFromSuggestedContact",M.gravatarIntegration="GravatarIntegration",M.logoboxIntegration="LogoboxIntegration",M.companiesBussinesRegisterApiIntegration="CompaniesBussinesRegisterApiIntegration",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.gridRowSummary="GridRowSummary",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.commonDataAPI="CommonDataAPI",M.eWayCrmAPI="eWayCrmAPI",M.threeCXIntegration="ThreeCXIntegration",M.tapiIntegration="TapiIntegration",M.pohodaIntegration="PohodaIntegration",M.pohodaSynchronizationIntervalCustomization="PohodaSynchronizationIntervalCustomization",M.pohodaSynchronizationFieldMappingCustomization="PohodaSynchronizationFieldMappingCustomization",M.quickBooksIntegration="QuickBooksIntegration",M.shareByTeams="ShareByTeams",M.convertEmailToContactWithDataFromAi="ConvertEmailToContactWithDataFromAi",M.convertEmailToDealWithDataFromAi="ConvertEmailToDealWithDataFromAi",M.convertEmailToProjectWithDataFromAi="ConvertEmailToProjectWithDataFromAi",function(e){e.UnpaidImportantInvoices="UnpaidImportantInvoices",e.UncollectableSubscriptionPayment="UncollectableSubscriptionPayment",e.UncollectableSubscriptionPaymentWithExpiredCard="UncollectableSubscriptionPaymentWithExpiredCard",e.StandardSubscriptionPeriod="StandardSubscriptionPeriod"}(R||(R={}));var _,U=R;!function(e){e.License="License",e.CloudLicense="CloudLicense",e.MiscLicense="MiscLicense",e.Support="Support",e.Service="Service"}(_||(_={}));var V=_;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 r;const n=null===(r=e.sessionHandler.lastSuccessfulLoginResponse)||void 0===r?void 0:r.WcfVersion;return!!n&&G.supportsVersionFeaturesOf(n,t)},G.supportsVersionFeaturesOf=(e,t)=>n(e,t,">=")||n(e,"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 W={[u.relations]:0,[u.unifiedRelations]:1,[u.users]:2,[u.groups]:3,[u.enumTypes]:4,[u.enumValues]:5,[u.additionalFields]:6};var B,H,z,Q;!function(e){e.Version75="7.5",e.Version76="7.6",e.Version77="7.7",e.Version80="8.0",e.Version81="8.1",e.Version82="8.2",e.Version83="8.3",e.Version90="9.0",e.Version91="9.1",e.Version92="9.2",e.Version93="9.3",e.Version94="9.4"}(B||(B={}));class $ extends G{}$.is75OrLater=e=>G.supportsFeaturesOf(e,B.Version75),$.is76OrLater=e=>$.supportsFeaturesOf(e,B.Version76),$.is77OrLater=e=>$.supportsFeaturesOf(e,B.Version77),$.is80OrLater=e=>$.supportsFeaturesOf(e,B.Version80),$.is81OrLater=e=>$.supportsFeaturesOf(e,B.Version81),$.is82OrLater=e=>$.supportsFeaturesOf(e,B.Version82),$.is83OrLater=e=>$.supportsFeaturesOf(e,B.Version83),$.is90OrLater=e=>$.supportsFeaturesOf(e,B.Version90),$.is91OrLater=e=>$.supportsFeaturesOf(e,B.Version91),$.is92OrLater=e=>$.supportsFeaturesOf(e,B.Version92),$.is93OrLater=e=>$.supportsFeaturesOf(e,B.Version93),$.is94OrLater=e=>$.supportsFeaturesOf(e,B.Version94),$.isFeatureSupported=(e,t)=>$.supportsFeaturesOf(e,t);class q{static mainTable(){return{__type:"MainTable:#EQ"}}static relation(e,t,r){return{__type:"Relation:#EQ",Direction:r,ItemTypes:e,RelationType:t}}static join(e,t,r){const n={__type:"Join:#EQ",ItemType:e,Key:t};return r&&(n.TargetColumnName=r),n}static hubRelation(e){const{isToParentDirection:t,childrenFolderNames:r}=e,n={__type:"HubRelation:#EQ"};return void 0!==typeof t&&(n.IsToParentDirection=t),r&&(n.ChildrenFolderNames=r),n}}class J{static createHubItemsCountsQuery(e,t,r){return{__type:"HubItemsCountsQuery:#EQ",ParentItemGuids:e,ItemTypes:t,ExcludeSystemItems:r}}static createRelatedTableQuery(e,t,r){return{__type:r?"RelatedTableQuery:#EQ":"TypelessRelatedTableQuery:#EQ",BaseItemID:e,ItemTypes:Array.isArray(t)?t:[t],RelationType:r}}static createMainTableQuery(e){return{__type:"MainTableQuery:#EQ",ItemTypes:Array.isArray(e)?e:[e]}}}J.column=e=>({__type:"Column:#EQ",Source:q.mainTable(),Name:e}),J.multiSelectComboColumnLegacy=(e,t,r)=>({__type:"Column:#EQ",Source:q.mainTable(),Name:"ItemGUID",Transformation:`[dbo].[GetConcatenatedEnumValuesRelationsValues]({0}, '${e}', '${t}'`,Alias:null!=r?r:e}),J.multiSelectComboColumn=(e,t,r,n,s)=>{if(!$.is77OrLater(e))return J.multiSelectComboColumnLegacy(r,n,s);return{__type:"Column:#EQ",Source:q.mainTable(),Name:"ItemGUID",Transformation:`[dbo].[GetConcatenatedEnumValuesRelationsValues_WithObjectTypeID]({0}, dbo.GetObjectTypeID('${t}'), '${r}', '${n}')`,Alias:null!=s?s:r}},J.joinColumn=(e,t,r,n,s)=>J.joinColumnFromKey(e,J.column(t),r,n,s),J.joinColumnFromKey=(e,t,r,n,s)=>{const o={__type:"Column:#EQ",Source:q.join(e,t,s),Name:r};return n&&(o.Alias=n),o},J.singleVariatedColumn=(e,t,r)=>J.variatedColumn([J.columnVariation(e,t)],r),J.variatedColumn=(e,t)=>{const r={__type:"VariatedColumn:#EQ",Source:q.mainTable(),Variations:e};return t&&(r.Alias=t),r},J.columnVariation=(e,t,r)=>{const n={FolderName:t,Field:{__type:"Column:#EQ",Source:q.mainTable(),Name:e}};return r&&(n.Field.Transformation=r),n},J.joinColumnVariation=(e,t,r,n)=>({FolderName:e,Field:{__type:"Column:#EQ",Source:q.join(t,J.column(r)),Name:n}}),J.relationColumnVariation=(e,t,r,n)=>({FolderName:e,Field:{__type:"Column:#EQ",Source:q.relation(r,t,1),Name:n}}),J.relatedColumn=(e,t,r,n)=>{const s={__type:"Column:#EQ",Source:q.relation(t,e,1),Name:r};return n&&(s.Alias=n),s},J.relatedSubstituableColumn=(e,t,r,n,s)=>{const o={__type:"SubstituableColumn:#EQ",Source:q.relation(t,e,1),Name:r,Substitute:n};return s&&(o.Alias=s),o},J.relatedColumnFolderNameToken=(e,t,r)=>({__type:"Token:#EQ",Source:q.relation(t,e,1),TypeName:"ItemType",Alias:r}),J.hubRelationColumn=(e,t)=>({__type:"Column:#EQ",Source:q.hubRelation(t),Name:e}),J.aggregateColumn=(e,t,r)=>({__type:"AggregateColumn:#EQ",FunctionName:e,Source:t.Source,AggregatedField:t,Alias:r}),J.folderNameToken=e=>({__type:"Token:#EQ",Source:q.mainTable(),TypeName:"ItemType",Alias:null!=e?e:"FolderName"}),J.equalsFilterExpression=(e,t)=>({__type:"EqualsFilterExpressionPredicate:#EQ",Field:e,Value:t}),J.notEqualsExpression=(e,t)=>({__type:"NotFilterExpression:#EQ",Child:J.equalsFilterExpression(e,t)}),J.andFilterExpression=e=>({__type:"AndFilterExpressionOperator:#EQ",Children:e}),J.orFilterExpression=e=>({__type:"OrFilterExpressionOperator:#EQ",Children:e}),J.lessFilterExpression=(e,t)=>({__type:"LessFilterExpressionPredicate:#EQ",Field:e,Value:t}),J.lessOrEqualFilterExpression=(e,t)=>({__type:"LessOrEqualFilterExpressionPredicate:#EQ",Field:e,Value:t}),J.greaterFilterExpression=(e,t)=>({__type:"GreaterFilterExpressionPredicate:#EQ",Field:e,Value:t}),J.greaterOrEqualFilterExpression=(e,t)=>({__type:"GreaterOrEqualFilterExpressionPredicate:#EQ",Field:e,Value:t}),J.likeFilterExpression=(e,t)=>({__type:"LikeFilterExpressionPredicate:#EQ",Field:e,Value:`%${t}%`}),J.inFilterExpression=(e,t)=>({__type:"InFilterExpressionPredicate:#EQ",Field:e,Value:t}),J.relatedToExpression=(e,t)=>({__type:"RelatedToFilterExpressionPredicate:#EQ",Value:e,RelationType:t}),J.isNullOrEmptyFilterExpression=e=>J.orFilterExpression([J.equalsFilterExpression(J.column(e),null),J.equalsFilterExpression(J.column(e),"")]);class X{static trim(e,t,r=!1){if(null==e)return e;let n=e.trim();return n.length<=t||(n=n.substring(0,t-(r?3:0)),r&&(n+="...")),n}}class K{static toRfc3339String(e){const t=e=>e<10?`0${e}`:String(e);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}${(e=>{if(0===e)return"Z";const r=e>0?"-":"+";return e=Math.abs(e),`${r}${t(Math.floor(e/60))}:${t(e%60)}`})(e.getTimezoneOffset())}`}}function Y(e,t,r,n){return new(r||(r=Promise))(function(s,o){function i(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(i,a)}l((n=n.apply(e,t||[])).next())})}K.isValid=e=>e instanceof Date&&!isNaN(e.getTime()),K.areDaysEqual=(e,t)=>{const r=K.clearTime(e),n=K.clearTime(t);return r.getTime()===n.getTime()},K.areTimesEqual=(e,t)=>e.getHours()===t.getHours()&&e.getMinutes()===t.getMinutes(),K.areDatesEqual=(e,t)=>!!e&&!!t&&K.areDaysEqual(e,t)&&K.areTimesEqual(e,t),K.clearTime=e=>{const t=new Date(e);return t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setMilliseconds(0),t},K.isWithoutTime=e=>0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds(),K.getFormattedSqlDateTime=e=>e.toISOString().slice(0,19).replace("T"," "),K.getRfcWithoutTimezone=e=>e.slice(0,19),function(e){e.OpenXmlDocx="OpenXmlDocx",e.Pdf="Pdf",e.WordMlXml="WordMlXml"}(H||(H={})),"function"==typeof SuppressedError&&SuppressedError;class Z{constructor(e,t,r,n){let s;if(this.sessionId=null,this.isAdmin=null,this.loginResponse=null,!(r||(s=h.decodeAccessToken(t),r=s.ws)))throw new Error("Failed to get web service URL from JWT");if(!(n||(s||(s=h.decodeAccessToken(t)),n=s.username)))throw new Error("Failed to get username from JWT");this.appName=e,this.wsUrl=r,this.userName=n,this.endpoint=r.startsWith("http://")?"InsecureAPI.svc":"API.svc",this.accessToken=t}hasAdminRights(){return this.isAdmin}getWsUrl(){return this.wsUrl}getUserName(){return this.userName}getOutlookClientVersion(){var e;return null===(e=this.loginResponse)||void 0===e?void 0:e.OutlookClientVersion}getWebServiceVersion(){var e;return null===(e=this.loginResponse)||void 0===e?void 0:e.WcfVersion}login(){return Y(this,void 0,void 0,function*(){const e={userName:this.userName,appVersion:this.appName},t=new Request(`${this.wsUrl}/${this.endpoint}/Login`,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify(e)}),r=yield fetch(t),n=200===r.status?yield r.json():void 0;if(!n||"rcSuccess"!==n.ReturnCode)throw new Error(`Login failed: ${(null==n?void 0:n.Description)||"Unknown error"}`);this.sessionId=null==n?void 0:n.SessionId,this.isAdmin=null==n?void 0:n.IsAdmin,this.loginResponse=n})}logout(){return Y(this,void 0,void 0,function*(){const e=new Request(`${this.wsUrl}/${this.endpoint}/LogOut`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:this.sessionId})}),t=yield fetch(e);if("rcSuccess"!==(yield t.json()).ReturnCode)throw new Error("Failed to logout")})}getObjectTypes(){return Y(this,void 0,void 0,function*(){return(yield this.callMethod("GetObjectTypes",{})).Data})}getLicense(){return Y(this,void 0,void 0,function*(){return(yield this.callMethod("GetLicense",{})).Datum})}getClientVersionId(e){var t;return Y(this,void 0,void 0,function*(){const r={versionName:e};return null===(t=(yield this.callMethod("GetClientVersion",r)).Datum)||void 0===t?void 0:t.Id})}queryAmount(e,t=null){return Y(this,void 0,void 0,function*(){const r={query:{__type:"MainTableQuery:#EQ",ItemTypes:[e],Fields:[{__type:"Column:#EQ",Source:{__type:"MainTable:#EQ"},Name:"ItemGUID"}]}};return t&&(r.query.Filter=t),this.callMethod("QueryAmount",r)})}query(e,t=null,r=null,n=null){return Y(this,void 0,void 0,function*(){const s={query:{__type:"MainTableQuery:#EQ",ItemTypes:[e],Fields:t,Paging:{Skip:0,Take:500}}};return r&&(s.query.Filter=r),n&&(s.query.Sort=n),this.callMethod("Query",s)})}callMethod(e,t,r="POST"){return Y(this,void 0,void 0,function*(){if(!this.sessionId)throw new Error("Session ID is not set. Please call init() first.");t.sessionId=this.sessionId;const n=new Request(`${this.wsUrl}/${this.endpoint}/${e}`,{method:r,headers:{"Content-Type":"application/json"},body:"POST"===r?JSON.stringify(t):void 0}),s=yield fetch(n);if(!s.ok)throw new Error(`Error calling method ${e}: ${s.statusText}`);const o=200===s.status?yield s.json():void 0;if(!o||"rcSuccess"!==o.ReturnCode)throw new Error(`API call failed (${null==o?void 0:o.ReturnCode}): ${null==o?void 0:o.Description}`);return o})}static getTokenData(e,t,r,n,s){return Y(this,void 0,void 0,function*(){const o=new URLSearchParams;o.append("client_id",n),o.append("client_secret",s),o.append("code",t),o.append("redirect_uri",r),o.append("grant_type","authorization_code");const i=new Request(`${e}/auth/connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString()}),a=yield fetch(i);if(!a.ok)throw new Error(`Error calling token endpoint: ${a.statusText}`);const l=yield a.json();if(!l||!l.access_token)throw new Error("Failed to get access token");return l})}}class ee{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 u.contacts:{const e=this.baseItem;return e.Email1Address||e.Email2Address||e.Email3Address}case u.leads:return this.baseItem.Email;case u.companies:return this.baseItem.Email;case u.users:{const e=this.baseItem;return e.Email1Address||e.Email2Address}default:return null}}getInitials(){switch(this.folderName){case u.contacts:{const e=this.baseItem;return this.getInitialsInternal(e.FirstName,e.LastName)}case u.users:{const e=this.baseItem;return this.getInitialsInternal(e.FirstName,e.LastName)}default:return null}}getInitialsInternal(e,t){const r=((null==e?void 0:e.substr(0,1))||"")+((null==t?void 0:t.substr(0,1))||"");return""==r?null:r}getItemPreview(){switch(this.folderName){case u.contacts:{const e=this.baseItem;return e.ProfilePicture?{imageData:e.ProfilePicture,width:e.ProfilePictureWidth||0,height:e.ProfilePictureHeight||0}:null}case u.users:{const e=this.baseItem;return e.ProfilePicture?{imageData:e.ProfilePicture,width:e.ProfilePictureWidth||0,height:e.ProfilePictureHeight||0}:null}default:return null}}}!function(e){e.Readonly="Readonly",e.VisibleRankDefaultOnly="VisibleRankDefaultOnly",e.Editable="Editable"}(z||(z={})),function(e){e.Success="Success",e.Failure="Failed",e.FailureDuplicityFound="Failed_DuplicityFound",e.FailureItemAlreadyRemoved="Failed_ItemAlreadyRemoved",e.FailureColumnsLockedWFAction="Failed_ColumnsLocked",e.FailureItemLockedWFAction="Failed_ItemLocked",e.FailureLicenseLimitReached="Failed_LicenseLimitReached",e.FailureInssuficientModulePermission="Failed_InsufficientModulePermission",e.FailureInssuficientColumnsPermission="Failed_InsufficientColumnsPermission"}(Q||(Q={})),a.polyfill();export{T as ApiConnectionAsNonDefaultExport,Z as ApiFetchClient,d as ApiMethods,w as ColumnPermissionMandatoryRules,D as ColumnPermissionPermissionRules,A as CommonDataConnection,L as CustomizationStatsItemKeys,K as DateHelper,ee as EWItem,F as Edition,z as EnumTypeEditMode,c as EnumTypes,g as ErrorHelper,U as ExpirationReason,O as Feature,I as FieldNames,j as FieldTypes,u as FolderNames,x as Functionality,v as GlobalSettingsNames,o as HttpMethod,P as HttpRequestError,Q as ImportResult,V as LicenseKeyInvoiceSeverity,M as LicenseRestrictionKeys,h as OAuthHelper,C as OAuthSessionHandlerBase,W as ObjectTypeIds,J as QueryHelper,b as RelationTypeIds,k as RelationTypes,l as ReturnCodes,N as SentimentTone,X as StringHelper,E as TokenizedServiceConnection,H as TransformItemFormats,B as Version,$ as VersionHelper,G as VersionHelperBase,T 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"}(o||(o={}));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 u{}u.isValidFolderName=e=>Object.values(u).includes(e),u.actions="Actions",u.additionalFields="AdditionalFields",u.bonuses="Bonuses",u.calendar="Calendar",u.capacityNotes="CapacityNotes",u.capacityNoteTypes="CapacityNoteTypes",u.carts="Carts",u.columnPermissions="ColumnPermissions",u.companies="Companies",u.contacts="Contacts",u.contactsSuggestions="ContactsSuggestions",u.currencyExchangeRates="CurrencyExchangeRates",u.documents="Documents",u.emails="Emails",u.enumTypes="EnumTypes",u.enumValues="EnumValues",u.enumValuesRelations="EnumValuesRelations",u.features="Features",u.flows="Flows",u.globalSettings="GlobalSettings",u.goals="Goals",u.goods="Goods",u.goodsInCart="GoodsInCart",u.goodsInSet="GoodsInSet",u.groups="Groups",u.history="History",u.holidays="Holidays",u.children="Children",u.individualDiscounts="IndividualDiscounts",u.invoiceItems="InvoiceItems",u.invoices="Invoices",u.itemCopyRelations="ItemCopyRelations",u.journal="Journal",u.knowledge="Knowledge",u.layouts="Layouts",u.layoutsModels="LayoutsModels",u.leads="Leads",u.ledger="Ledger",u.mappings="Mappings",u.marketing="Marketing",u.marketingList="MarketingList",u.marketingListSources="MarketingListSources",u.models="Models",u.modulePermissions="ModulePermissions",u.objectTypesOptions="ObjectTypesOptions",u.payments="Payments",u.priceListGroups="PriceListGroups",u.projectAssignments="ProjectAssignments",u.projectAssignmentsPerUserProject="ProjectAssignmentsPerUserProject",u.projectAssignmentsTotal="ProjectAssignmentsTotal",u.projectAssignmentsTotalUserProject="ProjectAssignmentsTotalUserProject",u.projectList="ProjectList",u.projects="Projects",u.projectUsersInCaPlan="ProjectUsersInCaPlan",u.relationData="RelationData",u.relations="Relations",u.reports="Reports",u.revisionsHistory="RevisionsHistory",u.salaries="Salaries",u.salePrices="SalePrices",u.prices="Prices",u.sqlObjects="SqlObjects",u.tasks="Tasks",u.recurrencePatterns="RecurrencePatterns",u.teamRoles="TeamRoles",u.templates="Templates",u.training="Training",u.unifiedRelations="UnifiedRelations",u.users="Users",u.userSettings="UserSettings",u.vacation="Vacation",u.webAccess2Options="WebAccess2Options",u.webAccessOptions="WebAccessOptions",u.workCommitments="WorkCommitments",u.workflowHistory="WorkflowHistory",u.workReports="WorkReports",u.wrongClientVersions="WrongClientVersions",u.xsltTransformations="XsltTransformations",u.xsltTransformationsModels="XsltTransformationsModels",u.getEnumTypeName=e=>e===u.bonuses?c.bonusType:e===u.carts?c.cartType:e===u.companies?c.companyType:e===u.contacts?c.contactType:e===u.documents?c.documentType:e===u.emails?c.emailType:e===u.goals?c.goalType:e===u.goods?c.productType:e===u.journal?c.journalType:e===u.knowledge?c.knowledgeType:e===u.leads?c.leadType:e===u.marketing?c.marketingType:e===u.projects?c.projectType:e===u.salaries?c.salaryType:e===u.salePrices?c.salePriceType:e===u.tasks?c.taskType:e===u.training?c.trainingTitle:e===u.users?c.userType:e===u.vacation?c.vacationType:e===u.workReports?c.workReportType:null,u.getFolderNameByEnumTypeName=e=>e===c.bonusType?u.bonuses:e===c.cartType?u.carts:e===c.companyType?u.companies:e===c.contactType?u.contacts:e===c.documentType?u.documents:e===c.emailType?u.emails:e===c.goalType?u.goals:e===c.journalType?u.journal:e===c.knowledgeType?u.knowledge:e===c.leadType?u.leads:e===c.marketingType?u.marketing:e===c.productType?u.goods:e===c.projectType?u.projects:e===c.salaryType?u.salaries:e===c.salePriceType?u.salePrices:e===c.taskType?u.tasks:e===c.trainingTitle?u.training:e===c.userType?u.users:e===c.vacationType?u.vacation:e===c.workReportType?u.workReports:null;class d{}d.getAllEmailAttachments="GetAllEmailAttachments",d.getCalendarsByItemGuids="GetCalendarsByItemGuids",d.getEmailAttachment="GetEmailAttachment",d.getItemPreview="GetItemPreview",d.getJournalsByItemGuids="GetJournalsByItemGuids",d.getMarketingCampaignsByItemGuids="GetMarketingCampaignsByItemGuids",d.getMarketingListsRecordsByItemGuids="GetMarketingListsRecordsByItemGuids",d.getRevisionHistoryRecordsByItemGuids="GetRevisionHistoryRecordsByItemGuids",d.getVacationsByItemGuids="GetVacationsByItemGuids",d.getWorkflowHistoryRecordsByItemGuids="GetWorkflowHistoryRecordsByItemGuids",d.getCompanyInformationFromTaxRegister="GetCompanyInformationFromTaxRegister",d.logIn="LogIn",d.logOut="LogOut",d.query="Query",d.queryAmount="QueryAmount",d.getServiceAuthSettings="GetServiceAuthSettings",d.getVersion="GetVersion",d.getBinaryAttachment="GetBinaryAttachment",d.getBinaryAttachmentLatestRevision="GetBinaryAttachmentLatestRevision",d.transformItem="TransformItem",d.canUnlinkItems="CanUnlinkItems",d.unlinkItems="UnlinkItems",d.getGoodsFinalPrices="GetGoodsFinalPrices",d.saveItemCopyRelation="SaveItemCopyRelation",d.getXsltTransormationDefinition="GetXsltTransformationDefinition",d.saveBinaryAttachment="SaveBinaryAttachment",d.saveBinaryXsltTransformation="SaveBinaryXsltTransformation",d.getFolderNameForApiMethod=e=>{switch(e){case u.calendar:return"Calendars";case u.journal:return"Journals";case u.marketing:return"MarketingCampaigns";case u.marketingList:return"MarketingListsRecords";case u.revisionsHistory:return"RevisionHistoryRecords";case u.vacation:return"Vacations";case u.workflowHistory:return"WorkflowHistoryRecords";default:return e}},d.getGetFolderNameByItemGuidsMethodName=e=>`Get${d.getFolderNameForApiMethod(e)}ByItemGuids`,d.getGetFolderNameMethodName=e=>`Get${d.getFolderNameForApiMethod(e)}`,d.getSearchFolderNameMethodName=e=>`Search${d.getFolderNameForApiMethod(e)}`;class m{constructor(e,t,r,n,s,o){if(this.invalidateSessionId=(e,t)=>{t&&t()},this.getSessionId=(e,t)=>{e.callWithoutSession(d.logIn,{userName:this.username,passwordHash:this.passwordHash,appVersion:this.appVersion,clientMachineIdentifier:this.clientMachineIdentifier,clientMachineName:this.clientMachineName,createSessionCookie:e.supportsGetItemPreviewMethod},e=>{this.lastSuccessfulLoginResponse=e;const r=e.SessionId;if(!r){const e=new Error("Successful login but no session came.");if(!this.errorCallback)throw e;return void this.errorCallback(e)}t&&t(r)},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=r,this.clientMachineIdentifier=n,this.clientMachineName=s,this.errorCallback=o}}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,r,n,s,o,i=!1,a){if(s&&!o||!s&&o)throw new Error("If codeChallenge is defined, codeChallengeMethod must also be defined and vice versa");let l=`https://login.eway-crm.${i?"dev":"com"}?scope=${encodeURIComponent(t.join(" "))}&prompt=login&response_type=code&redirect_uri=${encodeURIComponent(r)}&client_id=${e}`;return n&&(l+=`&state=${encodeURIComponent(n)}`),s&&o&&(l+=`&code_challenge=${encodeURIComponent(s)}&code_challenge_method=${encodeURIComponent(o)}`),a&&(l+=`&url=${encodeURIComponent(a)}`),l}}h.finishAuthorization=(e,t,r,n,s,o,i)=>{const a=new URLSearchParams;a.append("code_verifier",n),a.append("client_id",t),a.append("client_secret",r),a.append("code",s),a.append("redirect_uri",o),a.append("grant_type","authorization_code"),h.callTokenEndpoint(e,a,i)},h.refreshToken=(e,t,r,n,s)=>{const o=new URLSearchParams;o.append("client_id",t),o.append("client_secret",r),o.append("refresh_token",n),o.append("grant_type","refresh_token"),h.callTokenEndpoint(e,o,s)},h.getWebServiceUrl=e=>{const r=e.split(".");if(2!==r.length)throw new Error("Invalid token supplied");return t.decode(r[1])},h.getUserName=e=>h.decodeAccessToken(e).username,h.decodeAccessToken=e=>r(e),h.callTokenEndpoint=(t,r,n)=>{e.post(t+"/auth/connect/token",r,{headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(e=>{n(e.data)}).catch(e=>{e.response&&400==e.response.status?n(e.response.data):n({error:"Token request failed"})})};class y extends Error{constructor(e,t){super(),this.returnCode=e,this.message=t}}class C{constructor(e,t,r,n,s){if(this.invalidateSessionId=(e,t)=>{t&&t()},this.getSessionId=(e,t)=>{const r={userName:this.username,appVersion:this.appVersion,createSessionCookie:e.supportsGetItemPreviewMethod},n={Authorization:"Bearer "+this.accessToken};e.callWithoutSession(d.logIn,r,e=>{this.lastSuccessfulLoginResponse=e;const r=e.SessionId;if(!r){const e=new Error("Successful login but no session came.");if(!this.errorCallback)throw e;return void this.errorCallback(e)}t&&t(r)},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,r=>{if(401!==(null==r?void 0:r.statusCode)){if(!this.errorCallback)throw r;this.errorCallback(r)}else this.getNewAccessTokenCallback(e,r=>{this.accessToken=r.accessToken,r.error||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=r,this.getNewAccessTokenCallback=n,this.errorCallback=s}}class f extends C{constructor(e,t,r,n,s,o,i,a){if(!(e&&n&&t&&r))throw new Error("Non of the arguments 'username', 'clientId', 'clientSecret', 'refreshToken' can be empty.");super(e,s,o,(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)))}void 0!==e.error?t({error:e.error}):t({accessToken:e.access_token})})},i),this.refreshToken=n,this.clientId=t,this.clientSecret=r,this.refreshTokenCallback=a}}class P extends Error{constructor(e,t){super(),this.statusCode=e,this.message=t}}class g{}g.stringifyError=e=>JSON.stringify(e,g.replaceErrors),g.replaceErrors=(e,t)=>{if(t instanceof Error){const e={};return Object.getOwnPropertyNames(t).forEach(r=>{e[r]=t[r]}),e}return t};class T{constructor(r,n,s,i){if(this.ensureLogin=()=>new Promise((e,t)=>{if(this.sessionId)e();else{const r=r=>{r&&(this.sessionId=r,e()),t("Session Id cannot be empty")};this.sessionHandler.getSessionId(this,r)}}),this.createOpenLink=(e,r,n,s)=>{const o=t.encode(this.baseUri);let i="eway://"+r;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="+o+"&l="+i;return s&&(l+="&n="+encodeURIComponent(s)),l},this.askUploadMethod=(e,t,r,n,s)=>new Promise((o,i)=>{const a=s?e=>{throw i(e),e}:i;this.callUploadMethod(e,t,r,o,a,a,n)}),this.callCustomUploadMethod=(t,r,n,s,o,i,a)=>{const c=()=>{this.sessionHandler.getSessionId(this,e=>{this.sessionId=e,this.callCustomUploadMethod(t,r,n,s,o,i,a)})},u=this.sessionId;if(!u)return void c();const d=new URLSearchParams(r),m=`${this.svcUri}/${n}?sessionId=${this.sessionId}&${d.toString()}`,p=e.post(m,r,a);T.handleCallPromise(p,s,e=>{if(e.ReturnCode===l.rcBadSession)return this.sessionId=null,void this.sessionHandler.invalidateSessionId(u,c);if(o)o(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 "+m+": "+g.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.callUploadMethod=(e,t,r,n,s,o,i)=>{this.callCustomUploadMethod(r,{itemGuid:e,fileName:t},d.saveBinaryAttachment,n,s,o,i)},this.askMethod=(e,t,r,n)=>new Promise((s,o)=>{const i=n?e=>{throw o(e),e}:o;this.callMethod(e,t,s,i,r,i)}),this.callMethod=(e,t,r,n,s,i)=>{s||(s=o.post);const a=()=>{this.sessionHandler.getSessionId(this,o=>{this.sessionId=o,this.callMethod(e,t,r,n,s,i)})},c=this.sessionId;if(!c)return void a();t.sessionId=c;const u=e!==d.logOut?r:e=>{this.sessionId=null,r(e)};this.callWithoutSession(e,t,u,r=>{if(r.ReturnCode!==l.rcBadSession||(this.sessionId=null,e===d.logOut))if(n)n(r);else{const e=new Error("Unhandled connection return code "+r.ReturnCode+": "+r.Description);if(!this.errorCallback)throw e;this.errorCallback(e,t)}else this.sessionHandler.invalidateSessionId(c,a)},null,s,i)},this.callWithoutSession=(t,r,n,s,i,a,l)=>{var c;a||(a=o.post);const u=this.svcUri+"/"+t;let m,p;switch(i&&(m={headers:i,withCredentials:null!==(c=this.supportGetItemPreviewMethod)&&void 0!==c?c:t==d.logIn}),a){case o.get:if(r)throw new Error("Calling api get method with data specified does not make any sense.");p=e.get(u,m);break;case o.post:p=e.post(u,r,m);break;default:throw new Error(`Unknown http method '${a}'.`)}T.handleCallPromise(p,n,s,e=>{if(l)try{l(e)}catch(e){if(!this.errorCallback)throw e;this.errorCallback(e,r)}else{const t=new Error("Unhandled connection error when calling "+u+": "+g.stringifyError(e));if(!this.errorCallback)throw t;this.errorCallback(t,r)}})},this.getItemPreviewGetMethodUrl=(e,t,r)=>this.svcUri+"/"+d.getItemPreview+"?folderName="+encodeURIComponent(e)+"&itemGuid="+encodeURIComponent(t)+(r||0===r?"&itemVersion="+encodeURIComponent(r.toString()):""),this.getEmailAttachmentGetMethodUrl=(e,t)=>this.svcUri+"/"+d.getEmailAttachment+"?itemGuid="+encodeURIComponent(e)+"&contentId="+encodeURIComponent(t),this.getAllEmailAttachmentsZipGetMethodUrl=e=>this.svcUri+"/"+d.getAllEmailAttachments+"?itemGuid="+encodeURIComponent(e),this.getBinaryAttachmentGetMethodUrl=(e,t)=>"number"==typeof t?this.svcUri+"/"+d.getBinaryAttachment+"?itemGuid="+encodeURIComponent(e)+`&revision=${t}`:this.svcUri+"/"+d.getBinaryAttachmentLatestRevision+"?itemGuid="+encodeURIComponent(e),this.getTransformItemMethodUrl=(e,t,r,n)=>`${this.svcUri}/${d.transformItem}?itemGuid=${encodeURIComponent(e)}&itemFolderName=${encodeURIComponent(t)}&transformationGuid=${encodeURIComponent(r)}&outputFormat=${n}`,this.getXsltTransformationDefinitionMethodUrl=e=>`${this.svcUri}/${d.getXsltTransormationDefinition}?itemGuid=${encodeURIComponent(e)}`,this.getActiveSessionId=()=>this.sessionId,this.setActiveSessionId=e=>{this.sessionId=e},!r)throw new Error("The argument 'apiServiceUri' cannot be empty.");if(r.length<8||"https://"!==r.substr(0,8).toLowerCase()&&"http://"!==r.substr(0,7).toLowerCase())throw new Error("Api service uri must start either with 'https://' or with 'http://'.");if(".svc"===r.substr(r.length-4).toLowerCase()){this.svcUri=r;const e=["/API.svc","/InsecureAPI.svc","/WcfService/Service.svc"].find(e=>e.toLowerCase()===r.substr(r.length-e.length).toLowerCase())||"";this.baseUri=r.substr(0,r.length-e.length)}else this.baseUri=T.normalizeWsUrl(r)||r,"https://"===r.substr(0,8).toLowerCase()?this.svcUri=this.baseUri+"/API.svc":this.svcUri=this.baseUri+"/InsecureAPI.svc";this.sessionHandler=n,this.errorCallback=s,this.sessionId=null,this.supportGetItemPreviewMethod=null!=i&&i}get supportsGetItemPreviewMethod(){return this.supportGetItemPreviewMethod}static create(e,t,r,n,s,o,i,a){return new T(e,new m(t,r,n,s,o,i),i,a)}static createAnonymous(e,t){return new T(e,new p,t)}static createUsingOAuth(e,t,r,n,s,o,i,a,l,c){return new T(e,new f(t,r,n,s,o,i,a,l),a,c)}static normalizeWsUrl(e){return e&&e.endsWith("/")&&(e=e.substring(0,e.length-1)),e}static isCloudUrl(e,t){const r=new URL(e),n=new Set;return n.add("hosting.eway-crm.com"),n.add("free.eway-crm.com"),n.add("hosting.eway-crm.us"),n.add("hosting-vh39276.eway-crm.us"),n.add("free.eway-crm.us"),t&&(n.add("free.eway-crm.dev"),n.add("hosting.eway-crm.dev"),n.add("localhost")),n.has(r.host)}get wsUrl(){return this.baseUri}static handleCallPromise(e,t,r,n){e.then(e=>{200===e.status?e.data.ReturnCode===l.rcSuccess?t(e.data):r(e.data):n(new P(e.status,e.statusText))}).catch(e=>{e.response?n(new P(e.response.status,e.response.statusText)):n(e)})}}class E{constructor(e,t,r,n,s,o,i){this.isEnabled=(e,t)=>{const r=()=>{this.url&&this.token?e(this.url,this.token):t()};this.url&&this.token?e(this.url,this.token):this.obtainToken(r)},this.callTokenizedApi=(e,t,r,n)=>{this.isEnabled((s,o)=>{t.token=o,E.call(s,e,t,r,s=>{if(s.ReturnCodeString!==this.invalidTokenReturnCode){if(n)n(s);else if(this.generalErrorCallback){const e=new Error("Unhandled tokenized service connection return code "+s.ReturnCodeString+".\nDescription: "+s.Description);this.generalErrorCallback(e)}}else this.obtainToken(()=>{this.callTokenizedApi(e,t,r,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 r=this.urlAndTokenObtainer(t);r.url&&r.token?(this.url=r.url,this.token=r.token,this.isActive=!0,e()):(this.url=null,this.token=null,this.isActive=!1,e())},r=()=>{this.url=null,this.token=null,this.isActive=!1,e()};this.needsSession?this.connection.callMethod(this.obtainTokenMethodName,{},t,r,this.obtainTokenMethodType):this.connection.callWithoutSession(this.obtainTokenMethodName,null,t,r,null,this.obtainTokenMethodType)},this.obtainTokenMethodName=e,this.obtainTokenMethodType=t,this.needsSession=r,this.invalidTokenReturnCode=n,this.urlAndTokenObtainer=s,this.connection=o,this.generalErrorCallback=i||null,this.url=null,this.token=null,this.isActive=!0}static call(t,r,n,s,o,i){const a=t+"/"+r;e.post(a,n).then(e=>{200===e.status?"Success"===e.data.ReturnCodeString?s(e.data):o(e.data):i(new P(e.status,e.statusText))}).catch(e=>{e.response?i(new P(e.response.status,e.response.statusText)):i(e)})}}const S=e=>({url:e.ServiceUrl,token:e.Token});class v{constructor(e,t){this.isCommonDataApiEnabled=(e,t)=>{this.tokenizedConnection.isEnabled(e,t)},this.callCommonDataApi=(e,t,r,n)=>{this.tokenizedConnection.callTokenizedApi(e,t,r,n)},this.tokenizedConnection=new E("ObtainCommonDataApiAccessToken",o.get,!1,"InvalidCommonDataToken",S,e,t)}}class A{}A.acceptableBackwardWorkReportDays="AcceptableBackwardWorkReportDays",A.adminAppInactiveLogoutTime="AdminAppInactiveLogoutTime",A.applyGeneralDataProtectionRules="ApplyGeneralDataProtectionRules",A.automaticallyCreateJournalAfterCallDuration="AutomaticallyCreateJournalAfterCallDuration",A.bonusesCompletedState="BonusesCompletedState",A.cartInvoicedState="CartInvoicedState",A.cartOrderCanceledState="CartOrderCanceledState",A.cartOrderInProcessState="CartOrderInProcessState",A.cartOrderProcessedState="CartOrderProcessedState",A.cartPaidState="CartPaidState",A.cartProposalInProcessState="CartProposalInProcessState",A.cartProposalProcessedState="CartProposalProcessedState",A.cartSalesVoucherIssuedState="CartSalesVoucherIssuedState",A.cartToBeInvoicedState="CartToBeInvoicedState",A.cartVoidedState="CartVoidedState",A.clickToCallScheme="ClickToCallScheme",A.companyDuplicityCheckEnabled="CompanyDuplicityCheckEnabled",A.completedStateName="CompletedStateName",A.contactDuplicityCheckEnabled="ContactDuplicityCheckEnabled",A.createCompanyWhileImportingContactFromOutlook="CreateCompanyWhileImportingContactFromOutlook",A.defaultProposalValidityPeriod="DefaultProposalValidityPeriod",A.enableContactsTwoWaySyncWithM365="EnableContactsTwoWaySyncWithM365",A.deadStateName="DeadStateName",A.enableCompaniesSyncIntoMobileDeviceContacts="EnableCompaniesSyncIntoMobileDeviceContacts",A.enableContactsSyncIntoMobileDevice="EnableContactsSyncIntoMobileDevice",A.enableLeadsSyncIntoMobileDeviceContacts="EnableLeadsSyncIntoMobileDeviceContacts",A.enableLlamaAiFeatures="EnableLlamaAiFeatures",A.enableUsersSyncIntoMobileDeviceContacts="EnableUsersSyncIntoMobileDeviceContacts",A.emailsActiveProjectsLeadsFilter="EmailsActiveProjectsLeadsFilter",A.exchangeRatesAdminGroupName="ExchangeRatesAdminGroupName",A.forcedEmailTrackingGroups="ForcedEmailTrackingGroups",A.ignoreEmailsFromDomainsOnEmailsTracking="IgnoreEmailsFromDomainsOnEmailsTracking",A.trackEmailsFromDomains="TrackEmailsFromDomains",A.groupsForAllUnpaidInvoicesNotification="GroupsForAllUnpaidInvoicesNotification",A.itemPreviewMaxHeight="ItemPreviewMaxHeight",A.lastActivityAttributes="LastActivityAttributes",A.leadsCompletedState="LeadsCompletedState",A.leadDeadlineAlertGroups="LeadDeadlineAlertGroups",A.leadsDeadState="LeadsDeadState",A.marketingCompletedState="MarketingCompletedState",A.marketingDeadState="MarketingDeadState",A.minimumPasswordLength="MinimumPasswordLength",A.nextStepAttributes="NextStepAttributes",A.notifyAboutInvoicedInvoiceInPohodaGroup="NotifyAboutInvoicedInvoiceInPohodaGroup",A.notifyAboutLeadsDeadline="NotifyAboutLeadsDeadline",A.notifyAboutPaidInvoiceInPohodaGroup="NotifyAboutPaidInvoiceInPohodaGroup",A.notifyAboutProjectDeadline="NotifyAboutProjectDeadline",A.numberOfDecimalPlaces="NumberOfDecimalPlaces",A.phoneListTaskSolverGroup="PhoneListTaskSolverGroup",A.projectDeadlineAlert="ProjectDeadlineAlert",A.serverUpdateProgressNotificationGroup="ServerUpdateProgressNotificationGroup",A.sumarizeCartsPricesOnLeads="SumarizeCartsPricesOnLeads",A.sumarizeCartsPricesOnProjects="SumarizeCartsPricesOnProjects",A.sumarizePeopleExpensesOnProjects="SumarizePeopleExpensesOnProjects",A.systemHealthNotificationGroup="SystemHealthNotificationGroup",A.tasksCompletedState="TasksCompletedState",A.tasksDeferredState="TasksDeferredState",A.tasksInProgressState="TasksInProgressState",A.tasksNotStartedState="TasksNotStartedState",A.tasksWaitOnSomeoneElseState="TasksWaitOnSomeoneElseState",A.trackDocumentVersions="TrackDocumentVersions",A.vacationCompletedState="VacationCompletedState",A.workReportApprovedState="WorkReportApprovedState",A.defaultLanguage="DefaultLanguage",A.defaultCurrency="DefaultCurrency",A.myCompanyCountry="MyCompanyCountry",A.myCompanyName="MyCompanyName",A.myCompanyStreet="MyCompanyStreet",A.myCompanyCity="MyCompanyCity",A.myCompanyState="MyCompanyState",A.myCompanyZip="MyCompanyZIP",A.myCompanyId="MyCompanyID",A.myCompanyVat="MyCompanyVAT",A.mergeGoodsInCart="MergeGoodsInCart",A.cartRefreshLogic="CartRefreshLogic",A.goodsDefaultQuantity="GoodsDefaultQuantity",A.goodsDefaultVAT="GoodsDefaultVAT",A.goodsDefaultVATIncluded="GoodsDefaultVATIncluded";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",Customer:"Customer",Contact:"Contact",TypeEn:"TypeEn",StateEn:"StateEn",PriceTotal:"PriceTotal",PriceTotalExcludingVAT:"PriceTotalExcludingVAT",ForPayment:"ForPayment",Paid:"Paid",CurrencyEn:"CurrencyEn",EffectiveFrom:"EffectiveFrom",ValidUntil:"ValidUntil",Active:"Active",Note:"Note",ID:"ID",AccountingCaseDate:"AccountingCaseDate",TaxableSupplyDate:"TaxableSupplyDate",PaymentDate:"PaymentDate",VAT:"VAT",GoodsInCartCount:"GoodsInCartCount",PriceTotalDefaultCurrency:"PriceTotalDefaultCurrency",PriceTotalParentCurrency:"PriceTotalParentCurrency",ForPaymentDefaultCurrency:"ForPaymentDefaultCurrency",ForPaymentParentCurrency:"ForPaymentParentCurrency",PaidDefaultCurrency:"PaidDefaultCurrency",PaidParentCurrency:"PaidParentCurrency",PaidChanged:"PaidChanged",PriceTotalChanged:"PriceTotalChanged",PriceTotalExcludingVATDefaultCurrency:"PriceTotalExcludingVATDefaultCurrency",PriceTotalExcludingVATParentCurrency:"PriceTotalExcludingVATParentCurrency",VATDefaultCurrency:"VATDefaultCurrency",VATParentCurrency:"VATParentCurrency",PrevStateEn:"PrevStateEn",PurchaseExpenses:"PurchaseExpenses",PurchaseExpensesDefaultCurrency:"PurchaseExpensesDefaultCurrency",PurchaseExpensesParentCurrency:"PurchaseExpensesParentCurrency",PurchaseExpensesChanged:"PurchaseExpensesChanged",Profit:"Profit",ProfitDefaultCurrency:"ProfitDefaultCurrency",ProfitParentCurrency:"ProfitParentCurrency",ProfitChanged:"ProfitChanged"},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",TrackedDomains:"TrackedDomains",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",ExternalUrl:"ExternalUrl"},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.GoodsBase={Code:"Code",Structure:"Structure",Note:"Note",Description:"Description",TypeEn:"TypeEn",SaleCurrencyEn:"SaleCurrencyEn",PurchaseCurrencyEn:"PurchaseCurrencyEn",UnitEn:"UnitEn",PurchasePrice:"PurchasePrice",PurchasePriceDefaultCurrency:"PurchasePriceDefaultCurrency",PurchasePriceChanged:"PurchasePriceChanged",SalePrice:"SalePrice",SalePriceDefaultCurrency:"SalePriceDefaultCurrency",SalePriceChanged:"SalePriceChanged",IsPriceSum:"IsPriceSum",VATRate:"VATRate",VATIncluded:"VATIncluded"},I.Goods=Object.assign(Object.assign({},I.GoodsBase),{PriceListGroupGUID:"PriceListGroupGUID",InventoryQuantity:"InventoryQuantity"}),I.GoodsInCart=Object.assign(Object.assign({},I.GoodsBase),{Cart:"Cart",GoodsInfo:"GoodsInfo",SuperiorItem:"SuperiorItem",Quantity:"Quantity",PriceTotal:"PriceTotal",PriceTotalDefaultCurrency:"PriceTotalDefaultCurrency",PriceTotalParentCurrency:"PriceTotalParentCurrency",PriceTotalChanged:"PriceTotalChanged",PriceTotalExcludingVAT:"PriceTotalExcludingVAT",PriceTotalExcludingVATDefaultCurrency:"PriceTotalExcludingVATDefaultCurrency",PriceTotalExcludingVATParentCurrency:"PriceTotalExcludingVATParentCurrency",VATTotal:"VATTotal",VATTotalDefaultCurrency:"VATTotalDefaultCurrency",VATTotalParentCurrency:"VATTotalParentCurrency",SalePriceExcludingVAT:"SalePriceExcludingVAT",SalePriceExcludingVATDefaultCurrency:"SalePriceExcludingVATDefaultCurrency",SalePriceExcludingVATParentCurrency:"SalePriceExcludingVATParentCurrency",VAT:"VAT",VATDefaultCurrency:"VATDefaultCurrency",VATParentCurrency:"VATParentCurrency",PurchasePriceParentCurrency:"PurchasePriceParentCurrency",SalePriceParentCurrency:"SalePriceParentCurrency",ListPrice:"ListPrice",ListPriceDefaultCurrency:"ListPriceDefaultCurrency",ListPriceParentCurrency:"ListPriceParentCurrency",ListPriceChanged:"ListPriceChanged",Discount:"Discount",HierarchyInSet:"HierarchyInSet",IsFromSet:"IsFromSet",ParentGUID:"ParentGUID",Rank:"Rank",IncludeInCartPrice:"IncludeInCartPrice",ListPriceCustomized:"ListPriceCustomized",ChildItemsCount:"ChildItemsCount",JoinedToGUID:"JoinedToGUID",PurchasePriceTotal:"PurchasePriceTotal",PurchasePriceTotalDefaultCurrency:"PurchasePriceTotalDefaultCurrency",PurchasePriceTotalParentCurrency:"PurchasePriceTotalParentCurrency",PurchasePriceTotalChanged:"PurchasePriceTotalChanged"}),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.PriceListGroups={Note:"Note"},I.Prices={SalePriceGUID:"SalePriceGUID",GoodsItemGUID:"GoodsItemGUID",Price:"Price",CurrencyEn:"CurrencyEn"},I.SalePrices={Note:"Note",Discount:"Discount",TypeEn:"TypeEn",StateEn:"StateEn",PrevStateEn:"PrevStateEn"},I.XsltTransformations={LangCode:"LangCode",Definition:"Definition",Namespace:"Namespace",ObjectTypeID:"ObjectTypeID",TransformationVersion:"TransformationVersion"},I.XsltTransformationsModels={ObjectTypeID:"ObjectTypeID",TransformationGUID:"TransformationGUID",ItemTypeGUID:"ItemTypeGUID"},I.allTypeEnNames=["TypeEn",I.Documents.DocTypeEn,I.WorkReports.WorkReportEn,"TitleEn"],I.getFolderFileAs=e=>{switch(e){case u.leads:return I.Leads.FileAs;case u.projects:return I.Projects.ProjectName;case u.documents:return I.Documents.DocName;case u.companies:return I.Companies.CompanyName;case u.contacts:case u.users:return I.Common.FileAs;case u.emails:return I.Emails.Subject;case u.journal:return I.Journal.FileAs;case u.tasks:return I.Tasks.Subject;case u.workReports:return I.WorkReports.Subject;case u.vacation:return I.Vacation.TypeEn;case u.carts:case u.goods:case u.goodsInCart:return I.Common.FileAs;case u.groups:return I.Groups.GroupName;case u.xsltTransformations:return I.Common.FileAs;default:return console.warn(`FileAs col name not defined for folderName ${e}`),I.Common.FileAs}};class k{}k.general="GENERAL",k.group="GROUP",k.contactPerson="CONTACTPERSON",k.contact="CONTACT",k.customer="CUSTOMER",k.company="COMPANY",k.outlookProject="OUTLOOKPROJECT",k.supervisor="SUPERVISOR",k.projectOrigin="PROJECT_ORIGIN",k.cart="CART",k.goodsInCart="GOODSINCART",k.superiorItem="SUPERIORITEM";class b{}b.general=1,b.group=2,b.contactPerson=10,b.contact=11,b.customer=12,b.company=13,b.outlookProject=28,b.supervisor=32,b.projectOrigin=25,b.cart=9,b.goodsInCart=15,b.superiorItem=31;class D{}D.all="All",D.own="Own",D.readonly="Readonly",D.invisible="Invisible",D.none="None";class w{}var F,O,N,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"}(F||(F={})),function(e){e.ContactsAndCompanies="ContactsAndCompanies",e.Sales="Sales",e.Projects="Projects",e.Marketing="Marketing"}(O||(O={})),function(e){e[e.Negative=0]="Negative",e[e.Neutral=1]="Neutral",e[e.Positive=2]="Positive"}(N||(N={}));class x{}x.contactsSynchronizationWithOutlook="ContactsSynchronizationWithOutlook",x.wordAddin="WordAddin",x.excelAddin="ExcelAddin",x.tasksRecurrentTasks="TasksRecurrentTasks",x.tasksSubtasks="TasksSubtasks",x.tasksSynchronizationWithOutlook="TasksSynchronizationWithOutlook",x.calendarSynchronizationWithOutlook="CalendarSynchronizationWithOutlook",x.emailsAutomaticTracking="EmailsAutomaticTracking",x.convertEmailToProject="ConvertEmailToProject",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.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.api="API",x.gate="Gate",x.threeCXIntegration="ThreeCXIntegration",x.tapiIntegration="TapiIntegration",x.pohodaIntegration="PohodaIntegration",x.pohodaSynchronizationIntervalCustomization="PohodaSynchronizationIntervalCustomization",x.pohodaSynchronizationFieldMappingCustomization="PohodaSynchronizationFieldMappingCustomization",x.quickBooksIntegration="QuickBooksIntegration",x.saveBinaryDataOnDisk="SaveBinaryDataOnDisk",x.activeDirectoryLogin="ActiveDirectoryLogin",x.callerIdentificationOnApple="CallerIdentificationOnApple",x.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 M{}M.contactsAutomaticSynchronizationWithOutlook="ContactsAutomaticSynchronizationWithOutlook",M.contactsSynchronizationWithOutlook="ContactsSynchronizationWithOutlook",M.contactsSynchronizationWithAndroid="ContactsSynchronizationWithAndroid",M.documentsRevisions="DocumentsRevisions",M.wordAddin="WordAddin",M.excelAddin="ExcelAddin",M.tasksReminders="TasksReminders",M.tasksRecurrentTasks="TasksRecurrentTasks",M.tasksSubtasks="TasksSubtasks",M.tasksSynchronizationWithOutlook="TasksSynchronizationWithOutlook",M.calendarSynchronizationWithOutlook="CalendarSynchronizationWithOutlook",M.emailsManualTracking="EmailsManualTracking",M.emailsAutomaticTracking="EmailsAutomaticTracking",M.emailSummaryAndSentimentToneFromAi="EmailSummaryAndSentimentToneFromAi",M.convertEmailToContact="ConvertEmailToContact",M.convertEmailToDeal="ConvertEmailToDeal",M.convertEmailToProject="ConvertEmailToProject",M.convertEmailToTask="ConvertEmailToTask",M.convertFromSuggestedContact="ConvertFromSuggestedContact",M.gravatarIntegration="GravatarIntegration",M.logoboxIntegration="LogoboxIntegration",M.companiesBussinesRegisterApiIntegration="CompaniesBussinesRegisterApiIntegration",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.gridRowSummary="GridRowSummary",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.commonDataAPI="CommonDataAPI",M.eWayCrmAPI="eWayCrmAPI",M.threeCXIntegration="ThreeCXIntegration",M.tapiIntegration="TapiIntegration",M.pohodaIntegration="PohodaIntegration",M.pohodaSynchronizationIntervalCustomization="PohodaSynchronizationIntervalCustomization",M.pohodaSynchronizationFieldMappingCustomization="PohodaSynchronizationFieldMappingCustomization",M.quickBooksIntegration="QuickBooksIntegration",M.shareByTeams="ShareByTeams",M.convertEmailToContactWithDataFromAi="ConvertEmailToContactWithDataFromAi",M.convertEmailToDealWithDataFromAi="ConvertEmailToDealWithDataFromAi",M.convertEmailToProjectWithDataFromAi="ConvertEmailToProjectWithDataFromAi",function(e){e.UnpaidImportantInvoices="UnpaidImportantInvoices",e.UncollectableSubscriptionPayment="UncollectableSubscriptionPayment",e.UncollectableSubscriptionPaymentWithExpiredCard="UncollectableSubscriptionPaymentWithExpiredCard",e.StandardSubscriptionPeriod="StandardSubscriptionPeriod"}(R||(R={}));var U,_=R;!function(e){e.License="License",e.CloudLicense="CloudLicense",e.MiscLicense="MiscLicense",e.Support="Support",e.Service="Service"}(U||(U={}));var V=U;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 r;const n=null===(r=e.sessionHandler.lastSuccessfulLoginResponse)||void 0===r?void 0:r.WcfVersion;return!!n&&G.supportsVersionFeaturesOf(n,t)},G.supportsVersionFeaturesOf=(e,t)=>n(e,t,">=")||n(e,"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 B={[u.relations]:0,[u.unifiedRelations]:1,[u.users]:2,[u.groups]:3,[u.enumTypes]:4,[u.enumValues]:5,[u.additionalFields]:6};var W,H,z,Q;!function(e){e.Version75="7.5",e.Version76="7.6",e.Version77="7.7",e.Version80="8.0",e.Version81="8.1",e.Version82="8.2",e.Version83="8.3",e.Version90="9.0",e.Version91="9.1",e.Version92="9.2",e.Version93="9.3",e.Version94="9.4"}(W||(W={}));class $ extends G{}$.is75OrLater=e=>G.supportsFeaturesOf(e,W.Version75),$.is76OrLater=e=>$.supportsFeaturesOf(e,W.Version76),$.is77OrLater=e=>$.supportsFeaturesOf(e,W.Version77),$.is80OrLater=e=>$.supportsFeaturesOf(e,W.Version80),$.is81OrLater=e=>$.supportsFeaturesOf(e,W.Version81),$.is82OrLater=e=>$.supportsFeaturesOf(e,W.Version82),$.is83OrLater=e=>$.supportsFeaturesOf(e,W.Version83),$.is90OrLater=e=>$.supportsFeaturesOf(e,W.Version90),$.is91OrLater=e=>$.supportsFeaturesOf(e,W.Version91),$.is92OrLater=e=>$.supportsFeaturesOf(e,W.Version92),$.is93OrLater=e=>$.supportsFeaturesOf(e,W.Version93),$.is94OrLater=e=>$.supportsFeaturesOf(e,W.Version94),$.isFeatureSupported=(e,t)=>$.supportsFeaturesOf(e,t);class q{static mainTable(){return{__type:"MainTable:#EQ"}}static relation(e,t,r){return{__type:"Relation:#EQ",Direction:r,ItemTypes:e,RelationType:t}}static join(e,t,r){const n={__type:"Join:#EQ",ItemType:e,Key:t};return r&&(n.TargetColumnName=r),n}static hubRelation(e){const{isToParentDirection:t,childrenFolderNames:r}=e,n={__type:"HubRelation:#EQ"};return void 0!==typeof t&&(n.IsToParentDirection=t),r&&(n.ChildrenFolderNames=r),n}}class J{static createHubItemsCountsQuery(e,t,r){return{__type:"HubItemsCountsQuery:#EQ",ParentItemGuids:e,ItemTypes:t,ExcludeSystemItems:r}}static createRelatedTableQuery(e,t,r){return{__type:r?"RelatedTableQuery:#EQ":"TypelessRelatedTableQuery:#EQ",BaseItemID:e,ItemTypes:Array.isArray(t)?t:[t],RelationType:r}}static createMainTableQuery(e){return{__type:"MainTableQuery:#EQ",ItemTypes:Array.isArray(e)?e:[e]}}}J.column=e=>({__type:"Column:#EQ",Source:q.mainTable(),Name:e}),J.multiSelectComboColumnLegacy=(e,t,r)=>({__type:"Column:#EQ",Source:q.mainTable(),Name:"ItemGUID",Transformation:`[dbo].[GetConcatenatedEnumValuesRelationsValues]({0}, '${e}', '${t}'`,Alias:null!=r?r:e}),J.multiSelectComboColumn=(e,t,r,n,s)=>{if(!$.is77OrLater(e))return J.multiSelectComboColumnLegacy(r,n,s);return{__type:"Column:#EQ",Source:q.mainTable(),Name:"ItemGUID",Transformation:`[dbo].[GetConcatenatedEnumValuesRelationsValues_WithObjectTypeID]({0}, dbo.GetObjectTypeID('${t}'), '${r}', '${n}')`,Alias:null!=s?s:r}},J.joinColumn=(e,t,r,n,s)=>J.joinColumnFromKey(e,J.column(t),r,n,s),J.joinColumnFromKey=(e,t,r,n,s)=>{const o={__type:"Column:#EQ",Source:q.join(e,t,s),Name:r};return n&&(o.Alias=n),o},J.singleVariatedColumn=(e,t,r)=>J.variatedColumn([J.columnVariation(e,t)],r),J.variatedColumn=(e,t)=>{const r={__type:"VariatedColumn:#EQ",Source:q.mainTable(),Variations:e};return t&&(r.Alias=t),r},J.columnVariation=(e,t,r)=>{const n={FolderName:t,Field:{__type:"Column:#EQ",Source:q.mainTable(),Name:e}};return r&&(n.Field.Transformation=r),n},J.joinColumnVariation=(e,t,r,n)=>({FolderName:e,Field:{__type:"Column:#EQ",Source:q.join(t,J.column(r)),Name:n}}),J.relationColumnVariation=(e,t,r,n)=>({FolderName:e,Field:{__type:"Column:#EQ",Source:q.relation(r,t,1),Name:n}}),J.relatedColumn=(e,t,r,n)=>{const s={__type:"Column:#EQ",Source:q.relation(t,e,1),Name:r};return n&&(s.Alias=n),s},J.relatedSubstituableColumn=(e,t,r,n,s)=>{const o={__type:"SubstituableColumn:#EQ",Source:q.relation(t,e,1),Name:r,Substitute:n};return s&&(o.Alias=s),o},J.relatedColumnFolderNameToken=(e,t,r)=>({__type:"Token:#EQ",Source:q.relation(t,e,1),TypeName:"ItemType",Alias:r}),J.hubRelationColumn=(e,t)=>({__type:"Column:#EQ",Source:q.hubRelation(t),Name:e}),J.aggregateColumn=(e,t,r)=>({__type:"AggregateColumn:#EQ",FunctionName:e,Source:t.Source,AggregatedField:t,Alias:r}),J.folderNameToken=e=>({__type:"Token:#EQ",Source:q.mainTable(),TypeName:"ItemType",Alias:null!=e?e:"FolderName"}),J.equalsFilterExpression=(e,t)=>({__type:"EqualsFilterExpressionPredicate:#EQ",Field:e,Value:t}),J.notEqualsExpression=(e,t)=>({__type:"NotFilterExpression:#EQ",Child:J.equalsFilterExpression(e,t)}),J.andFilterExpression=e=>({__type:"AndFilterExpressionOperator:#EQ",Children:e}),J.orFilterExpression=e=>({__type:"OrFilterExpressionOperator:#EQ",Children:e}),J.lessFilterExpression=(e,t)=>({__type:"LessFilterExpressionPredicate:#EQ",Field:e,Value:t}),J.lessOrEqualFilterExpression=(e,t)=>({__type:"LessOrEqualFilterExpressionPredicate:#EQ",Field:e,Value:t}),J.greaterFilterExpression=(e,t)=>({__type:"GreaterFilterExpressionPredicate:#EQ",Field:e,Value:t}),J.greaterOrEqualFilterExpression=(e,t)=>({__type:"GreaterOrEqualFilterExpressionPredicate:#EQ",Field:e,Value:t}),J.likeFilterExpression=(e,t)=>({__type:"LikeFilterExpressionPredicate:#EQ",Field:e,Value:`%${t}%`}),J.inFilterExpression=(e,t)=>({__type:"InFilterExpressionPredicate:#EQ",Field:e,Value:t}),J.relatedToExpression=(e,t)=>({__type:"RelatedToFilterExpressionPredicate:#EQ",Value:e,RelationType:t}),J.isNullOrEmptyFilterExpression=e=>J.orFilterExpression([J.equalsFilterExpression(J.column(e),null),J.equalsFilterExpression(J.column(e),"")]);class X{static trim(e,t,r=!1){if(null==e)return e;let n=e.trim();return n.length<=t||(n=n.substring(0,t-(r?3:0)),r&&(n+="...")),n}}class K{static toRfc3339String(e){const t=e=>e<10?`0${e}`:String(e);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}${(e=>{if(0===e)return"Z";const r=e>0?"-":"+";return e=Math.abs(e),`${r}${t(Math.floor(e/60))}:${t(e%60)}`})(e.getTimezoneOffset())}`}}function Y(e,t,r,n){return new(r||(r=Promise))(function(s,o){function i(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(i,a)}l((n=n.apply(e,t||[])).next())})}K.isValid=e=>e instanceof Date&&!isNaN(e.getTime()),K.areDaysEqual=(e,t)=>{const r=K.clearTime(e),n=K.clearTime(t);return r.getTime()===n.getTime()},K.areTimesEqual=(e,t)=>e.getHours()===t.getHours()&&e.getMinutes()===t.getMinutes(),K.areDatesEqual=(e,t)=>!!e&&!!t&&K.areDaysEqual(e,t)&&K.areTimesEqual(e,t),K.clearTime=e=>{const t=new Date(e);return t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setMilliseconds(0),t},K.isWithoutTime=e=>0===e.getHours()&&0===e.getMinutes()&&0===e.getSeconds(),K.getFormattedSqlDateTime=e=>e.toISOString().slice(0,19).replace("T"," "),K.getRfcWithoutTimezone=e=>e.slice(0,19),function(e){e.OpenXmlDocx="OpenXmlDocx",e.Pdf="Pdf",e.WordMlXml="WordMlXml"}(H||(H={})),"function"==typeof SuppressedError&&SuppressedError;class Z{constructor(e,t,r,n){let s;if(this.sessionId=null,this.isAdmin=null,this.loginResponse=null,!(r||(s=h.decodeAccessToken(t),r=s.ws)))throw new Error("Failed to get web service URL from JWT");if(!(n||(s||(s=h.decodeAccessToken(t)),n=s.username)))throw new Error("Failed to get username from JWT");this.appName=e,this.wsUrl=r,this.userName=n,this.endpoint=r.startsWith("http://")?"InsecureAPI.svc":"API.svc",this.accessToken=t}hasAdminRights(){return this.isAdmin}getWsUrl(){return this.wsUrl}getUserName(){return this.userName}getOutlookClientVersion(){var e;return null===(e=this.loginResponse)||void 0===e?void 0:e.OutlookClientVersion}getWebServiceVersion(){var e;return null===(e=this.loginResponse)||void 0===e?void 0:e.WcfVersion}login(){return Y(this,void 0,void 0,function*(){const e={userName:this.userName,appVersion:this.appName},t=new Request(`${this.wsUrl}/${this.endpoint}/Login`,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/json"},body:JSON.stringify(e)}),r=yield fetch(t),n=200===r.status?yield r.json():void 0;if(!n||"rcSuccess"!==n.ReturnCode)throw new Error(`Login failed: ${(null==n?void 0:n.Description)||"Unknown error"}`);this.sessionId=null==n?void 0:n.SessionId,this.isAdmin=null==n?void 0:n.IsAdmin,this.loginResponse=n})}logout(){return Y(this,void 0,void 0,function*(){const e=new Request(`${this.wsUrl}/${this.endpoint}/LogOut`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:this.sessionId})}),t=yield fetch(e);if("rcSuccess"!==(yield t.json()).ReturnCode)throw new Error("Failed to logout")})}getObjectTypes(){return Y(this,void 0,void 0,function*(){return(yield this.callMethod("GetObjectTypes",{})).Data})}getLicense(){return Y(this,void 0,void 0,function*(){return(yield this.callMethod("GetLicense",{})).Datum})}getClientVersionId(e){var t;return Y(this,void 0,void 0,function*(){const r={versionName:e};return null===(t=(yield this.callMethod("GetClientVersion",r)).Datum)||void 0===t?void 0:t.Id})}queryAmount(e,t=null){return Y(this,void 0,void 0,function*(){const r={query:{__type:"MainTableQuery:#EQ",ItemTypes:[e],Fields:[{__type:"Column:#EQ",Source:{__type:"MainTable:#EQ"},Name:"ItemGUID"}]}};return t&&(r.query.Filter=t),this.callMethod("QueryAmount",r)})}query(e,t=null,r=null,n=null){return Y(this,void 0,void 0,function*(){const s={query:{__type:"MainTableQuery:#EQ",ItemTypes:[e],Fields:t,Paging:{Skip:0,Take:500}}};return r&&(s.query.Filter=r),n&&(s.query.Sort=n),this.callMethod("Query",s)})}callMethod(e,t,r="POST"){return Y(this,void 0,void 0,function*(){if(!this.sessionId)throw new Error("Session ID is not set. Please call init() first.");t.sessionId=this.sessionId;const n=new Request(`${this.wsUrl}/${this.endpoint}/${e}`,{method:r,headers:{"Content-Type":"application/json"},body:"POST"===r?JSON.stringify(t):void 0}),s=yield fetch(n);if(!s.ok)throw new Error(`Error calling method ${e}: ${s.statusText}`);const o=200===s.status?yield s.json():void 0;if(!o||"rcSuccess"!==o.ReturnCode)throw new Error(`API call failed (${null==o?void 0:o.ReturnCode}): ${null==o?void 0:o.Description}`);return o})}static getTokenData(e,t,r,n,s){return Y(this,void 0,void 0,function*(){const o=new URLSearchParams;o.append("client_id",n),o.append("client_secret",s),o.append("code",t),o.append("redirect_uri",r),o.append("grant_type","authorization_code");const i=new Request(`${e}/auth/connect/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString()}),a=yield fetch(i);if(!a.ok)throw new Error(`Error calling token endpoint: ${a.statusText}`);const l=yield a.json();if(!l||!l.access_token)throw new Error("Failed to get access token");return l})}}class ee{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 u.contacts:{const e=this.baseItem;return e.Email1Address||e.Email2Address||e.Email3Address}case u.leads:return this.baseItem.Email;case u.companies:return this.baseItem.Email;case u.users:{const e=this.baseItem;return e.Email1Address||e.Email2Address}default:return null}}getInitials(){switch(this.folderName){case u.contacts:{const e=this.baseItem;return this.getInitialsInternal(e.FirstName,e.LastName)}case u.users:{const e=this.baseItem;return this.getInitialsInternal(e.FirstName,e.LastName)}default:return null}}getInitialsInternal(e,t){const r=((null==e?void 0:e.substr(0,1))||"")+((null==t?void 0:t.substr(0,1))||"");return""==r?null:r}getItemPreview(){switch(this.folderName){case u.contacts:{const e=this.baseItem;return e.ProfilePicture?{imageData:e.ProfilePicture,width:e.ProfilePictureWidth||0,height:e.ProfilePictureHeight||0}:null}case u.users:{const e=this.baseItem;return e.ProfilePicture?{imageData:e.ProfilePicture,width:e.ProfilePictureWidth||0,height:e.ProfilePictureHeight||0}:null}default:return null}}}!function(e){e.Readonly="Readonly",e.VisibleRankDefaultOnly="VisibleRankDefaultOnly",e.Editable="Editable"}(z||(z={})),function(e){e.Success="Success",e.Failure="Failed",e.FailureDuplicityFound="Failed_DuplicityFound",e.FailureItemAlreadyRemoved="Failed_ItemAlreadyRemoved",e.FailureColumnsLockedWFAction="Failed_ColumnsLocked",e.FailureItemLockedWFAction="Failed_ItemLocked",e.FailureLicenseLimitReached="Failed_LicenseLimitReached",e.FailureInssuficientModulePermission="Failed_InsufficientModulePermission",e.FailureInssuficientColumnsPermission="Failed_InsufficientColumnsPermission"}(Q||(Q={})),a.polyfill();export{T as ApiConnectionAsNonDefaultExport,Z as ApiFetchClient,d as ApiMethods,w as ColumnPermissionMandatoryRules,D as ColumnPermissionPermissionRules,v as CommonDataConnection,L as CustomizationStatsItemKeys,K as DateHelper,ee as EWItem,F as Edition,z as EnumTypeEditMode,c as EnumTypes,g as ErrorHelper,_ as ExpirationReason,O as Feature,I as FieldNames,j as FieldTypes,u as FolderNames,x as Functionality,A as GlobalSettingsNames,o as HttpMethod,P as HttpRequestError,Q as ImportResult,V as LicenseKeyInvoiceSeverity,M as LicenseRestrictionKeys,h as OAuthHelper,C as OAuthSessionHandlerBase,B as ObjectTypeIds,J as QueryHelper,b as RelationTypeIds,k as RelationTypes,l as ReturnCodes,N as SentimentTone,X as StringHelper,E as TokenizedServiceConnection,H as TransformItemFormats,W as Version,$ as VersionHelper,G as VersionHelperBase,T as default};
package/lib/index.d.ts CHANGED
@@ -173,17 +173,28 @@ declare class ApiConnection {
173
173
  * @param catchGlobally Optional. If true, raises this the global error handler each time the promise is rejected.
174
174
  */
175
175
  readonly askUploadMethod: (itemGuid: string, fileName: string, data: File, config?: AxiosRequestConfig, catchGlobally?: boolean) => Promise<IApiResult>;
176
+ /**
177
+ *
178
+ * @param file File to be uploaded
179
+ * @param data Additional data to be sent as URL parameters
180
+ * @param methodName API method name. Ex. 'SaveBinaryAttachment'.
181
+ * @param successCallback Handler callback when the method executes well. Gets the whole response JSON object as the only argument.
182
+ * @param unsuccessCallback Optional. Handler callback for eWay-API app level failures. Gets the whole response JSON object as the only argument. If not supplied, the global error handler is used.
183
+ * @param errorCallback Optional. Handler callback for any other failures. If not supplied, the global error handler is used.
184
+ * @param config Optional. Additional config for the request.
185
+ */
186
+ readonly callCustomUploadMethod: (file: File, data: Record<string, string>, methodName: string, successCallback: (res: IApiResult) => void, unsuccessCallback?: ((e: IApiResult) => void) | undefined, errorCallback?: ((e: TUnionError) => void) | undefined, config?: AxiosRequestConfig) => void;
176
187
  /**
177
188
  * Asynchronously uploads file using binary stream
178
189
  * @param itemGuid Item identificator. Ex. '9ac561be-9b7d-4938-8e55-4cce97142483'.
179
190
  * @param fileName File name, ex. 'picture.img'.
180
- * @param data Single file to be uploaded.
191
+ * @param file Single file to be uploaded.
181
192
  * @param successCallback Handler callback when the method executes well. Gets the whole response JSON object as the only argument.
182
193
  * @param unsuccessCallback Optional. Handler callback for eWay-API app level failures. Gets the whole response JSON object as the only argument. If not supplied, the global error handler is used.
183
194
  * @param errorCallback Optional. Handler callback for any other failures. If not supplied, the global error handler is used.
184
195
  * @param config Optional. Additional config for the request.
185
196
  */
186
- readonly callUploadMethod: (itemGuid: string, fileName: string, data: File, successCallback: (res: IApiResult) => void, unsuccessCallback?: ((e: IApiResult) => void) | undefined, errorCallback?: ((e: TUnionError) => void) | undefined, config?: AxiosRequestConfig) => void;
197
+ readonly callUploadMethod: (itemGuid: string, fileName: string, file: File, successCallback: (res: IApiResult) => void, unsuccessCallback?: ((e: IApiResult) => void) | undefined, errorCallback?: ((e: TUnionError) => void) | undefined, config?: AxiosRequestConfig) => void;
187
198
  /**
188
199
  * Creates a promise for async API method call.
189
200
  * @param methodName API method name. Ex. 'GetUsers'.
@@ -208,6 +219,7 @@ declare class ApiConnection {
208
219
  readonly getAllEmailAttachmentsZipGetMethodUrl: (itemGuid: string) => string;
209
220
  readonly getBinaryAttachmentGetMethodUrl: (itemGuid: string, revision?: number) => string;
210
221
  readonly getTransformItemMethodUrl: (itemGuid: string, folderName: string, transformationGuid: string, outputFormat: TransformItemFormats) => string;
222
+ readonly getXsltTransformationDefinitionMethodUrl: (transformationGuid: string) => string;
211
223
  readonly getActiveSessionId: () => string | null;
212
224
  readonly setActiveSessionId: (sessionId: string | null) => void;
213
225
  private static handleCallPromise;
@@ -281,6 +293,9 @@ declare class ApiMethods {
281
293
  static readonly unlinkItems = "UnlinkItems";
282
294
  static readonly getGoodsFinalPrices = "GetGoodsFinalPrices";
283
295
  static readonly saveItemCopyRelation = "SaveItemCopyRelation";
296
+ static readonly getXsltTransormationDefinition = "GetXsltTransformationDefinition";
297
+ static readonly saveBinaryAttachment = "SaveBinaryAttachment";
298
+ static readonly saveBinaryXsltTransformation = "SaveBinaryXsltTransformation";
284
299
  /**
285
300
  * 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.
286
301
  * For example module Calendar has method GetCalendarsByItemGuids, but the folder name is Calendar.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eway-crm/connector",
3
- "version": "1.0.231",
3
+ "version": "1.0.233",
4
4
  "description": "eWay-CRM API JavaScript connector library.",
5
5
  "main": "lib/cjs/index.js",
6
6
  "module": "lib/esm/index.js",