diff --git a/.github/CHANGELOG.md b/.github/CHANGELOG.md
index 0c38344..9617cad 100644
--- a/.github/CHANGELOG.md
+++ b/.github/CHANGELOG.md
@@ -1,3 +1,12 @@
+
+# [v2.1.5](https://github.com/AleksandrRogov/DynamicsWebApi/releases/tag/v2.1.5) - 11 Jul 2024
+
+**Fixes**
+- Missing authorization token when request with a long URL is converted into a Batch request. [#175](https://github.com/AleksandrRogov/DynamicsWebApi/issues/175)
+
+[Changes][v2.1.5]
+
+
# [v2.1.4](https://github.com/AleksandrRogov/DynamicsWebApi/releases/tag/v2.1.4) - 11 Apr 2024
@@ -954,6 +963,7 @@ Added:
[Changes][v1.2.0]
+[v2.1.5]: https://github.com/AleksandrRogov/DynamicsWebApi/compare/v2.1.4...v2.1.5
[v2.1.4]: https://github.com/AleksandrRogov/DynamicsWebApi/compare/v2.1.3...v2.1.4
[v2.1.3]: https://github.com/AleksandrRogov/DynamicsWebApi/compare/v1.7.12...v2.1.3
[v1.7.12]: https://github.com/AleksandrRogov/DynamicsWebApi/compare/v2.1.2...v1.7.12
diff --git a/.github/README.md b/.github/README.md
index d819526..6d52b8d 100644
--- a/.github/README.md
+++ b/.github/README.md
@@ -157,11 +157,16 @@ Once the web file is uploaded, it can be included in a template, a page or a for
With CDN, it is a bit easier: no need to create and upload a web file - just include the script in your template, page or a form:
```html
-
+
```
And you are good to go! DynamicsWebApi will automatically detect if the library is running on Power Pages and will supply an anti-forgery token with each request.
+#### Limitations
+Currently, there are some ootb limitations in the Power Pages:
+1. Batch operations are not supported. Hopefully, Microsoft will add it in the future.
+2. Long requests (with URL more than 2000 chars) are not supported. This is because of the 1st limitation. DynamicsWebApi will try to convert it to a Batch operation which will ultimately fail because it's not supported.
+
### Node.js
To use DynamicsWebApi in Node.js install the `dynamics-web-api` package from NPM:
@@ -173,13 +178,13 @@ Then include it in your script:
```ts
//CommonJS
-const DynamicsWebApi = require("dynamics-web-api");
+const DynamicsWebApi = require("dynamics-web-api").DynamicsWebApi;
//ESM
import { DynamicsWebApi } from "dynamics-web-api";
```
-DynamicsWebApi does not fetch authorization tokens, so you will need to acquire them in your code and pass them back to the library.
+DynamicsWebApi does not fetch authorization tokens, thus you will need to acquire them in your code and pass them back to the library.
Authorization tokens can be acquired using [Microsoft Authentication Library for Node](https://www.npmjs.com/package/@azure/msal-node) or you can write your own logic to retrieve the tokens.
Here is an example using `@azure/msal-node`:
@@ -288,7 +293,7 @@ timeout | `number` | Sets a number of milliseconds before a request times out.
useEntityNames | `boolean` | Indicates whether to use entity logical names instead of collection logical names during requests.
**Note!**
-`serverUrl` and `onTokenRefresh` are required when DynamicsWebApi used in a Node.js application.
+`serverUrl` and `onTokenRefresh` are required when DynamicsWebApi is used in a Node.js application.
**Important!**
If you are using `DynamicsWebApi` **outside Microsoft Dynamics 365** and set `useEntityNames` to `true` **the first request** to Web Api will fetch `LogicalCollectionName` and `LogicalName` from `EntityMetadata` for all entities. It does not happen when `DynamicsWebApi` is used in Microsoft Dynamics 365 Web Resources (there is no additional request, no impact on perfomance).
@@ -319,22 +324,22 @@ Both `dataApi` and `searchApi` can be omitted from a configuration. Their defaul
**dataApi** properties:
| Property Name | Type | Description |
|--------|--------|--------|
-| path | `String` | Optional. A path to API, default: "data". |
-| version | `String` | Optional. API Version, default: "9.2". |
+| path | `string` | Optional. A path to API, default: "data". |
+| version | `string` | Optional. API Version, default: "9.2". |
**searchApi** properties:
| Property Name | Type | Description |
|--------|--------|--------|
-| path | `String` | Optional. A path to API, default: "search". |
-| version | `String` | Optional. API Version, default: "1.0". |
+| path | `string` | Optional. A path to API, default: "search". |
+| version | `string` | Optional. API Version, default: "1.0". |
## Request Examples
Please use [DynamicsWebApi Wiki](../../../wiki/) for an object reference. It is automatically generated and I could not find a better doc generator, pardon me for that. If you know a good ".d.ts -> .md" doc generator - let me know!
-The following table describes all __possible__ properties that can be set in `request` object. Some parameters may still be absent in a table, please refer to [DynamicsWebApi Wiki](../../../wiki/).
+The following table describes all __possible__ properties that can be set in a `request` object. Some parameters may still be absent in a table, please refer to [DynamicsWebApi Wiki](../../../wiki/).
-__Please note!__ Not all operaions accept all properties and if
+__Please note!__ Not all operations accept all properties and if
by mistake an invalid property has been specified you will receive either an error saying that the request is invalid or the response will not have expected results.
Property Name | Type | Operation(s) Supported | Description
@@ -351,7 +356,7 @@ continueOnError | `boolean` | `executeBatch` | **BATCH REQUESTS ONLY!** Sets Pre
count | `boolean` | `retrieveMultiple`, `retrieveAll` | Boolean that sets the $count system query option with a value of true to include a count of entities that match the filter criteria up to 5000 (per page). Do not use $top with $count!
data | `Object` or `ArrayBuffer` / `Buffer` (for node.js) | `create`, `update`, `upsert`, `uploadFile` | A JavaScript object that represents Dynamics 365 entity, action, metadata and etc.
duplicateDetection | `boolean` | `create`, `update`, `upsert` | **D365 Web API v9+** Boolean that enables duplicate detection. [More Info](https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/webapi/update-delete-entities-using-web-api#check-for-duplicate-records)
-expand | `Expand[]` | `retrieve`, `retrieveMultiple`, `create`, `update`, `upsert` | An array of Expand Objects (described below the table) representing the $expand OData System Query Option value to control which related records are also returned.
+expand | `Expand[]` | `retrieve`, `retrieveMultiple`, `create`, `update`, `upsert` | An array of `Expand` Objects (described below the table) representing the $expand OData System Query Option value to control which related records are also returned.
fetchXml | `string` | `fetch`, `fetchAll` | Property that sets FetchXML - a proprietary query language that provides capabilities to perform aggregation.
fieldName | `string` | `uploadFile`, `downloadFile`, `deleteRequest` | **D365 Web API v9.1+** Use this option to specify the name of the file attribute in Dynamics 365. [More Info](https://docs.microsoft.com/en-us/powerapps/developer/common-data-service/file-attributes)
fileName | `string` | `uploadFile` | **D365 Web API v9.1+** Specifies the name of the file
@@ -388,11 +393,11 @@ top | `number` | `retrieveMultiple`, `retrieveAll` | Limit the number of results
trackChanges | `boolean` | `retrieveMultiple`, `retrieveAll` | Sets Prefer header with value 'odata.track-changes' to request that a delta link be returned which can subsequently be used to retrieve entity changes. __Important!__ Change Tracking must be enabled for the entity. [More Info](https://docs.microsoft.com/en-us/powerapps/developer/common-data-service/use-change-tracking-synchronize-data-external-systems#enable-change-tracking-for-an-entity)
userQuery | `string` | `retrieve` | A String representing the GUID value of the user query.
-The following table describes Expand Object properties:
+The following table describes `Expand` Object properties:
Property Name | Type | Description
------------ | ------------- | -------------
-expand | `Expand[]` | An array of Expand Objects representing the $expand OData System Query Option value to control which related records are also returned.
+expand | `Expand[]` | An array of `Expand` Objects representing the $expand OData System Query Option value to control which related records are also returned.
filter | `string` | Use the $filter system query option to set criteria for which related entities will be returned.
orderBy | `string[]` | An Array (of strings) representing the order in which related items are returned using the $orderby system query option. Use the asc or desc suffix to specify ascending or descending order respectively. The default is ascending if the suffix isn't applied.
property | `string` | A name of a single-valued navigation property which needs to be expanded.
@@ -402,6 +407,8 @@ top | `number` | Limit the number of results returned by using the $top system q
All requests to Web API that have long URLs (more than 2000 characters) are automatically converted to a Batch Request.
This feature is very convenient when you make a call with big Fetch XMLs. No special parameters needed to do a convertation.
+**Heads up!** This feature may cause an issue in Microsoft Power Pages because Batch Requests are not supported there out of the box. Please keep your requests short :)
+
### Create a table row
```ts
@@ -1235,10 +1242,10 @@ The first two requests will be atomic (included in a Change Set) and the last on
```ts
dynamicsWebApi.startBatch();
//Change Set A starts
-dynamicsWebApi.create({
- data: contact,
- collection: "contacts",
- contentId: "1",
+dynamicsWebApi.create({
+ data: contact,
+ collection: "contacts",
+ contentId: "1",
});
//Change Set A ends
dynamicsWebApi.create({
@@ -1247,9 +1254,9 @@ dynamicsWebApi.create({
inChangeSet: false //<--- do not include in a change set
});
//Change Set B starts
-dynamicsWebApi.create({
- data: order,
- collection: "salesorders",
+dynamicsWebApi.create({
+ data: order,
+ collection: "salesorders",
//"$1" parameter cannot be used here because it is defined in a Change Set A
//otherwise, you will get an error
});
@@ -1274,6 +1281,7 @@ You will get an error saying that the operation is incompatible with a 'batch mo
There are also out of the box Web API limitations for batch operations:
* Batch requests can contain up to 1000 individual requests and cannot contain other batch requests.
+* Not supported in Microsoft Power Pages. (checked June 2024)
You can find an official documentation that covers Web API batch requests here: [Execute batch operations using the Web API](https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/webapi/execute-batch-operations-using-web-api).
@@ -2181,9 +2189,12 @@ const isDeleted = await dynamicsWebApi.deleteRecord({
## Work with Dataverse Search API
-DynamicsWebApi can be used to call Dataverse Search API and utilize its powerful Search, Suggest and Autocomplete capabilities. Before using, I highly recommend to get familiar with it by reading an [official documentation](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/relevance-search).
+**Important!** Currently only Search API 1.0 is supported. Search API 2.0 is coming with `v.2.2.0`.
+If you must use 2.0, you could [use corresponding Actions](#execute-web-api-actions) for now. [more info](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/search/overview?tabs=sdk)
+
+DynamicsWebApi can be used to call Dataverse Search API and utilize its powerful Search, Suggest and Autocomplete capabilities. Before using, I highly recommend to get familiar with it by reading an [official documentation](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/search/legacy).
-To set Search API version use: `new DynamicsWebApi({ searchApi: { version: "2.0" }})`.
+To set Search API version use: `new DynamicsWebApi({ searchApi: { version: "1.0" }})`.
Search, Suggest and Autocomplete requests have a common property `query`. This is the main property that configures a relevance search request.
@@ -2441,7 +2452,7 @@ The declaration file is an ESM module, so if you are not using any bundler, you
import { DynamicsWebApi } from "./dynamics-web-api"
//make the DynamicsWebApi class available globally
export = DynamicsWebApi;
-//wrap all other exports with in namespace
+//wrap all other exports in a namespace
export as namespace DynamicsWebApi;
```
@@ -2472,7 +2483,7 @@ const createRequest: Dwa.CreateRequest = {
const id = await dynamicsWebApi.create(createRequest) as string;
```
-**DynamicsWebApi as an external library.** For those who use bundlers, but want to keep DynamicsWebApi as an external library (meaning that you don't want to bundle the library but reference it separately in a script tag somewhere): 1. you will have to make sure that your bundler supports `externals` configuraiton. 2. you will need to set the replacement for the import of `dynamics-web-api` with `_dynamicsWebApiExports`. For example, in webpack's case, you will have something like that:
+**DynamicsWebApi as an external library.** For those who use bundlers, but want to keep DynamicsWebApi as an external library (meaning that you don't want to bundle the library but reference it separately in a script tag somewhere): 1. you will have to make sure that your bundler supports `externals` configuraiton. 2. you will need to set the replacement for the import of `dynamics-web-api` with `_dynamicsWebApiExports`. For example, in webpack's case, you will have something like this:
```json
{
//...your bundle configuration
@@ -2482,7 +2493,7 @@ const id = await dynamicsWebApi.create(createRequest) as string;
}
```
-This will work __only__ if in your scripts you import the library like this: `import { DynamicsWebApi } from "dynamics-web-api"`. In case if you don't install the package with npm but just keep the declaration files somewhere and import it with relative paths, you can set the [paths](https://www.typescriptlang.org/tsconfig#paths) option in your `tsconfig.json` which will create a consistent alias for all your relative import paths.
+This will work __only__ if you import the library like this: `import { DynamicsWebApi } from "dynamics-web-api"`. If you don't install the package with npm but just keep the declaration files somewhere and import it with relative paths, you can set the [paths](https://www.typescriptlang.org/tsconfig#paths) option in your `tsconfig.json` which will create a consistent alias for all your relative import paths.
```json
{
@@ -2518,11 +2529,12 @@ the config option "formatted" will enable developers to retrieve all information
- [X] Impersonate a user based on their Azure Active Directory (AAD) object id. `Added in v.1.6.12`
- [X] File upload/download/delete for a File Field. `Added in v.1.7.0`
- [X] Full proxy support. `Added in v.1.7.2`
-- [X] Full proxy support. `Added in v.1.7.2`
- [X] Refactoring and conversion to TypeScript. `Added in v.2.0.0`
-- [X] Implement [Dataverse Search API](https://docs.microsoft.com/en-us/power-apps/developer/data-platform/webapi/relevance-search). `Added in v.2.0.0`
-- [X] Allow custom headers to be passed to the request. [#151](https://github.com/AleksandrRogov/DynamicsWebApi/issues/151). `Added in v.2.1.0`
+- [X] Implement [Dataverse Search API 1.0](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/search/legacy). `Added in v.2.0.0`
+- [X] Allow custom headers to be passed to the request [#151](https://github.com/AleksandrRogov/DynamicsWebApi/issues/151). `Added in v.2.1.0`
- [X] Support Microsoft Power Pages. `Added in v.2.1.0`
+- [ ] Support Search API 2.0 [#174](https://github.com/AleksandrRogov/DynamicsWebApi/issues/174). `Coming with v.2.2.0`
+- [ ] Custom requests.
Many more features to come!
diff --git a/README.md b/README.md
index 8304ab4..946ac88 100644
--- a/README.md
+++ b/README.md
@@ -61,7 +61,7 @@ Once the web file is uploaded, it can be included in a template, a page or a for
With CDN, it is a bit easier: no need to create and upload a web file - just include the script in your template, page or a form:
```html
-
+
```
And you are good to go! DynamicsWebApi will automatically detect if the library is running on Power Pages and will supply an anti-forgery token with each request.
@@ -77,7 +77,7 @@ Then include it in your script:
```ts
//CommonJS
-const DynamicsWebApi = require("dynamics-web-api");
+const DynamicsWebApi = require("dynamics-web-api").DynamicsWebApi;
//ESM
import { DynamicsWebApi } from "dynamics-web-api";
diff --git a/dist/browser/esm/dynamics-web-api.js b/dist/browser/esm/dynamics-web-api.js
index a605103..0758155 100644
--- a/dist/browser/esm/dynamics-web-api.js
+++ b/dist/browser/esm/dynamics-web-api.js
@@ -1,4 +1,4 @@
-/*! dynamics-web-api v2.1.4 (c) 2024 Aleksandr Rogov */
+/*! dynamics-web-api v2.1.5 (c) 2024 Aleksandr Rogov */
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -683,7 +683,7 @@ function executeRequest(options) {
}
function _executeRequest(options, successCallback, errorCallback) {
const data = options.data;
- const additionalHeaders = options.additionalHeaders;
+ const headers = options.headers;
const responseParams = options.responseParams;
const signal = options.abortSignal;
if (signal?.aborted) {
@@ -698,8 +698,8 @@ function _executeRequest(options, successCallback, errorCallback) {
}
let request = new XMLHttpRequest();
request.open(options.method, options.uri, options.isAsync || false);
- for (let key in additionalHeaders) {
- request.setRequestHeader(key, additionalHeaders[key]);
+ for (let key in headers) {
+ request.setRequestHeader(key, headers[key]);
}
request.onreadystatechange = function() {
if (request.readyState === 4) {
@@ -728,10 +728,10 @@ function _executeRequest(options, successCallback, errorCallback) {
if (!request)
break;
let error;
- let headers;
+ let headers2;
try {
- headers = parseResponseHeaders(request.getAllResponseHeaders());
- const errorParsed = parseResponse(request.responseText, headers, responseParams[options.requestId]);
+ headers2 = parseResponseHeaders(request.getAllResponseHeaders());
+ const errorParsed = parseResponse(request.responseText, headers2, responseParams[options.requestId]);
if (Array.isArray(errorParsed)) {
errorCallback(errorParsed);
break;
@@ -747,7 +747,7 @@ function _executeRequest(options, successCallback, errorCallback) {
const errorParameters = {
status: request.status,
statusText: request.statusText,
- headers
+ headers: headers2
};
request = null;
errorCallback(ErrorHelper.handleHttpError(error, errorParameters));
@@ -759,26 +759,26 @@ function _executeRequest(options, successCallback, errorCallback) {
request.timeout = options.timeout;
}
request.onerror = function() {
- const headers = parseResponseHeaders(request.getAllResponseHeaders());
+ const headers2 = parseResponseHeaders(request.getAllResponseHeaders());
errorCallback(
ErrorHelper.handleHttpError({
status: request.status,
statusText: request.statusText,
message: request.responseText || "Network Error",
- headers
+ headers: headers2
})
);
request = null;
};
request.ontimeout = function() {
- const headers = parseResponseHeaders(request.getAllResponseHeaders());
+ const headers2 = parseResponseHeaders(request.getAllResponseHeaders());
errorCallback(
ErrorHelper.handleHttpError({
name: "TimeoutError",
status: request.status,
statusText: request.statusText,
message: request.responseText || "Request Timed Out",
- headers
+ headers: headers2
})
);
request = null;
@@ -786,13 +786,13 @@ function _executeRequest(options, successCallback, errorCallback) {
request.onabort = function() {
if (!request)
return;
- const headers = parseResponseHeaders(request.getAllResponseHeaders());
+ const headers2 = parseResponseHeaders(request.getAllResponseHeaders());
errorCallback(
ErrorHelper.handleHttpError({
status: request.status,
statusText: request.statusText,
message: "Request aborted",
- headers
+ headers: headers2
})
);
request = null;
@@ -800,7 +800,7 @@ function _executeRequest(options, successCallback, errorCallback) {
const abort = () => {
if (!request)
return;
- const headers = parseResponseHeaders(request.getAllResponseHeaders());
+ const headers2 = parseResponseHeaders(request.getAllResponseHeaders());
errorCallback(
ErrorHelper.handleHttpError({
name: "AbortError",
@@ -808,7 +808,7 @@ function _executeRequest(options, successCallback, errorCallback) {
status: request.status,
statusText: request.statusText,
message: "The user aborted a request.",
- headers
+ headers: headers2
})
);
request.abort();
@@ -946,482 +946,449 @@ init_Utility();
// src/utils/Request.ts
init_Utility();
init_ErrorHelper();
-var _RequestUtility = class _RequestUtility {
- /**
- * Converts a request object to URL link
- *
- * @param {Object} request - Request object
- * @param {Object} [config] - DynamicsWebApi config
- * @returns {ConvertedRequest} Converted request
- */
- static compose(request, config) {
- request.path = request.path || "";
- request.functionName = request.functionName || "";
- if (!request.url) {
- if (!request._isUnboundRequest && !request.contentId && !request.collection) {
- ErrorHelper.parameterCheck(request.collection, `DynamicsWebApi.${request.functionName}`, "request.collection");
- }
- if (request.collection != null) {
- ErrorHelper.stringParameterCheck(request.collection, `DynamicsWebApi.${request.functionName}`, "request.collection");
- request.path = request.collection;
- if (request.key) {
- request.key = ErrorHelper.keyParameterCheck(request.key, `DynamicsWebApi.${request.functionName}`, "request.key");
- request.path += `(${request.key})`;
- }
- }
- if (request.contentId) {
- ErrorHelper.stringParameterCheck(request.contentId, `DynamicsWebApi.${request.functionName}`, "request.contentId");
- if (request.contentId.startsWith("$")) {
- request.path = request.path ? `${request.contentId}/${request.path}` : request.contentId;
- }
+var entityNames = null;
+var setEntityNames = (newEntityNames) => {
+ entityNames = newEntityNames;
+};
+var compose = (request, config) => {
+ request.path = request.path || "";
+ request.functionName = request.functionName || "";
+ if (!request.url) {
+ if (!request._isUnboundRequest && !request.contentId && !request.collection) {
+ ErrorHelper.parameterCheck(request.collection, `DynamicsWebApi.${request.functionName}`, "request.collection");
+ }
+ if (request.collection != null) {
+ ErrorHelper.stringParameterCheck(request.collection, `DynamicsWebApi.${request.functionName}`, "request.collection");
+ request.path = request.collection;
+ if (request.key) {
+ request.key = ErrorHelper.keyParameterCheck(request.key, `DynamicsWebApi.${request.functionName}`, "request.key");
+ request.path += `(${request.key})`;
}
- if (request._additionalUrl) {
- if (request.path) {
- request.path += "/";
- }
- request.path += request._additionalUrl;
+ }
+ if (request.contentId) {
+ ErrorHelper.stringParameterCheck(request.contentId, `DynamicsWebApi.${request.functionName}`, "request.contentId");
+ if (request.contentId.startsWith("$")) {
+ request.path = request.path ? `${request.contentId}/${request.path}` : request.contentId;
}
- request.path = _RequestUtility.composeUrl(request, config, request.path);
- if (request.fetchXml) {
- ErrorHelper.stringParameterCheck(request.fetchXml, `DynamicsWebApi.${request.functionName}`, "request.fetchXml");
- let join = request.path.indexOf("?") === -1 ? "?" : "&";
- request.path += `${join}fetchXml=${encodeURIComponent(request.fetchXml)}`;
+ }
+ if (request.addPath) {
+ if (request.path) {
+ request.path += "/";
}
- } else {
- ErrorHelper.stringParameterCheck(request.url, `DynamicsWebApi.${request.functionName}`, "request.url");
- request.path = request.url.replace(config.dataApi.url, "");
+ request.path += request.addPath;
}
- if (request.hasOwnProperty("async") && request.async != null) {
- ErrorHelper.boolParameterCheck(request.async, `DynamicsWebApi.${request.functionName}`, "request.async");
- } else {
- request.async = true;
+ request.path = composeUrl(request, config, request.path);
+ if (request.fetchXml) {
+ ErrorHelper.stringParameterCheck(request.fetchXml, `DynamicsWebApi.${request.functionName}`, "request.fetchXml");
+ let join = request.path.indexOf("?") === -1 ? "?" : "&";
+ request.path += `${join}fetchXml=${encodeURIComponent(request.fetchXml)}`;
}
- request.headers = _RequestUtility.composeHeaders(request, config);
- return request;
+ } else {
+ ErrorHelper.stringParameterCheck(request.url, `DynamicsWebApi.${request.functionName}`, "request.url");
+ request.path = request.url.replace(config.dataApi.url, "");
}
- /**
- * Converts optional parameters of the request to URL. If expand parameter exists this function is called recursively.
- *
- * @param {Object} request - Request object
- * @param {string} request.functionName - Name of the function that converts a request (for Error Handling)
- * @param {string} url - URL beginning (with required parameters)
- * @param {string} [joinSymbol] - URL beginning (with required parameters)
- * @param {Object} [config] - DynamicsWebApi config
- * @returns {ConvertedRequestOptions} Additional options in request
- */
- static composeUrl(request, config, url = "", joinSymbol = "&") {
- const queryArray = [];
- if (request) {
- if (request.navigationProperty) {
- ErrorHelper.stringParameterCheck(request.navigationProperty, `DynamicsWebApi.${request.functionName}`, "request.navigationProperty");
- url += "/" + request.navigationProperty;
- if (request.navigationPropertyKey) {
- let navigationKey = ErrorHelper.keyParameterCheck(
- request.navigationPropertyKey,
- `DynamicsWebApi.${request.functionName}`,
- "request.navigationPropertyKey"
- );
- url += "(" + navigationKey + ")";
- }
- if (request.navigationProperty === "Attributes") {
- if (request.metadataAttributeType) {
- ErrorHelper.stringParameterCheck(
- request.metadataAttributeType,
- `DynamicsWebApi.${request.functionName}`,
- "request.metadataAttributeType"
- );
- url += "/" + request.metadataAttributeType;
- }
- }
+ if (request.hasOwnProperty("async") && request.async != null) {
+ ErrorHelper.boolParameterCheck(request.async, `DynamicsWebApi.${request.functionName}`, "request.async");
+ } else {
+ request.async = true;
+ }
+ request.headers = composeHeaders(request, config);
+ return request;
+};
+var composeUrl = (request, config, url = "", joinSymbol = "&") => {
+ const queryArray = [];
+ if (request) {
+ if (request.navigationProperty) {
+ ErrorHelper.stringParameterCheck(request.navigationProperty, `DynamicsWebApi.${request.functionName}`, "request.navigationProperty");
+ url += "/" + request.navigationProperty;
+ if (request.navigationPropertyKey) {
+ let navigationKey = ErrorHelper.keyParameterCheck(
+ request.navigationPropertyKey,
+ `DynamicsWebApi.${request.functionName}`,
+ "request.navigationPropertyKey"
+ );
+ url += "(" + navigationKey + ")";
}
- if (request.select?.length) {
- ErrorHelper.arrayParameterCheck(request.select, `DynamicsWebApi.${request.functionName}`, "request.select");
- if (request.functionName == "retrieve" && request.select.length == 1 && request.select[0].endsWith("/$ref")) {
- url += "/" + request.select[0];
- } else {
- if (request.select[0].startsWith("/") && request.functionName == "retrieve") {
- if (request.navigationProperty == null) {
- url += request.select.shift();
- } else {
- request.select.shift();
- }
- }
- if (request.select.length) {
- queryArray.push("$select=" + request.select.join(","));
- }
+ if (request.navigationProperty === "Attributes") {
+ if (request.metadataAttributeType) {
+ ErrorHelper.stringParameterCheck(request.metadataAttributeType, `DynamicsWebApi.${request.functionName}`, "request.metadataAttributeType");
+ url += "/" + request.metadataAttributeType;
}
}
- if (request.filter) {
- ErrorHelper.stringParameterCheck(request.filter, `DynamicsWebApi.${request.functionName}`, "request.filter");
- const removeBracketsFromGuidReg = /[^"']{([\w\d]{8}[-]?(?:[\w\d]{4}[-]?){3}[\w\d]{12})}(?:[^"']|$)/g;
- let filterResult = request.filter;
- let m = null;
- while ((m = removeBracketsFromGuidReg.exec(filterResult)) !== null) {
- if (m.index === removeBracketsFromGuidReg.lastIndex) {
- removeBracketsFromGuidReg.lastIndex++;
+ }
+ if (request.select?.length) {
+ ErrorHelper.arrayParameterCheck(request.select, `DynamicsWebApi.${request.functionName}`, "request.select");
+ if (request.functionName == "retrieve" && request.select.length == 1 && request.select[0].endsWith("/$ref")) {
+ url += "/" + request.select[0];
+ } else {
+ if (request.select[0].startsWith("/") && request.functionName == "retrieve") {
+ if (request.navigationProperty == null) {
+ url += request.select.shift();
+ } else {
+ request.select.shift();
}
- let replacement = m[0].endsWith(")") ? ")" : " ";
- filterResult = filterResult.replace(m[0], " " + m[1] + replacement);
}
- queryArray.push("$filter=" + encodeURIComponent(filterResult));
- }
- if (request.fieldName) {
- ErrorHelper.stringParameterCheck(request.fieldName, `DynamicsWebApi.${request.functionName}`, "request.fieldName");
- url += "/" + request.fieldName;
- }
- if (request.savedQuery) {
- queryArray.push(
- "savedQuery=" + ErrorHelper.guidParameterCheck(request.savedQuery, `DynamicsWebApi.${request.functionName}`, "request.savedQuery")
- );
- }
- if (request.userQuery) {
- queryArray.push(
- "userQuery=" + ErrorHelper.guidParameterCheck(request.userQuery, `DynamicsWebApi.${request.functionName}`, "request.userQuery")
- );
- }
- if (request.apply) {
- ErrorHelper.stringParameterCheck(request.apply, `DynamicsWebApi.${request.functionName}`, "request.apply");
- queryArray.push("$apply=" + request.apply);
- }
- if (request.count) {
- ErrorHelper.boolParameterCheck(request.count, `DynamicsWebApi.${request.functionName}`, "request.count");
- queryArray.push("$count=" + request.count);
- }
- if (request.top && request.top > 0) {
- ErrorHelper.numberParameterCheck(request.top, `DynamicsWebApi.${request.functionName}`, "request.top");
- queryArray.push("$top=" + request.top);
- }
- if (request.orderBy != null && request.orderBy.length) {
- ErrorHelper.arrayParameterCheck(request.orderBy, `DynamicsWebApi.${request.functionName}`, "request.orderBy");
- queryArray.push("$orderby=" + request.orderBy.join(","));
- }
- if (request.partitionId) {
- ErrorHelper.stringParameterCheck(request.partitionId, `DynamicsWebApi.${request.functionName}`, "request.partitionId");
- queryArray.push("partitionid='" + request.partitionId + "'");
- }
- if (request.downloadSize) {
- ErrorHelper.stringParameterCheck(request.downloadSize, `DynamicsWebApi.${request.functionName}`, "request.downloadSize");
- queryArray.push("size=" + request.downloadSize);
- }
- if (request.queryParams?.length) {
- ErrorHelper.arrayParameterCheck(request.queryParams, `DynamicsWebApi.${request.functionName}`, "request.queryParams");
- queryArray.push(request.queryParams.join("&"));
- }
- if (request.fileName) {
- ErrorHelper.stringParameterCheck(request.fileName, `DynamicsWebApi.${request.functionName}`, "request.fileName");
- queryArray.push("x-ms-file-name=" + request.fileName);
- }
- if (request.data) {
- ErrorHelper.parameterCheck(request.data, `DynamicsWebApi.${request.functionName}`, "request.data");
- }
- if (request.isBatch) {
- ErrorHelper.boolParameterCheck(request.isBatch, `DynamicsWebApi.${request.functionName}`, "request.isBatch");
- }
- if (!Utility.isNull(request.inChangeSet)) {
- ErrorHelper.boolParameterCheck(request.inChangeSet, `DynamicsWebApi.${request.functionName}`, "request.inChangeSet");
- }
- if (request.isBatch && Utility.isNull(request.inChangeSet))
- request.inChangeSet = true;
- if (request.timeout) {
- ErrorHelper.numberParameterCheck(request.timeout, `DynamicsWebApi.${request.functionName}`, "request.timeout");
- }
- if (request.expand?.length) {
- ErrorHelper.stringOrArrayParameterCheck(request.expand, `DynamicsWebApi.${request.functionName}`, "request.expand");
- if (typeof request.expand === "string") {
- queryArray.push("$expand=" + request.expand);
- } else {
- const expandQueryArray = [];
- for (let i = 0; i < request.expand.length; i++) {
- if (request.expand[i].property) {
- const expand = request.expand[i];
- expand.functionName = `${request.functionName} $expand`;
- let expandConverted = _RequestUtility.composeUrl(expand, config, "", ";");
- if (expandConverted) {
- expandConverted = `(${expandConverted.substr(1)})`;
- }
- expandQueryArray.push(request.expand[i].property + expandConverted);
- }
- }
- if (expandQueryArray.length) {
- queryArray.push("$expand=" + expandQueryArray.join(","));
- }
+ if (request.select.length) {
+ queryArray.push("$select=" + request.select.join(","));
}
}
}
- return !queryArray.length ? url : url + "?" + queryArray.join(joinSymbol);
- }
- static composeHeaders(request, config) {
- const headers = { ...config.headers, ...request.userHeaders };
- const prefer = _RequestUtility.composePreferHeader(request, config);
- if (prefer.length) {
- headers["Prefer"] = prefer;
+ if (request.filter) {
+ ErrorHelper.stringParameterCheck(request.filter, `DynamicsWebApi.${request.functionName}`, "request.filter");
+ const removeBracketsFromGuidReg = /[^"']{([\w\d]{8}[-]?(?:[\w\d]{4}[-]?){3}[\w\d]{12})}(?:[^"']|$)/g;
+ let filterResult = request.filter;
+ let m = null;
+ while ((m = removeBracketsFromGuidReg.exec(filterResult)) !== null) {
+ if (m.index === removeBracketsFromGuidReg.lastIndex) {
+ removeBracketsFromGuidReg.lastIndex++;
+ }
+ let replacement = m[0].endsWith(")") ? ")" : " ";
+ filterResult = filterResult.replace(m[0], " " + m[1] + replacement);
+ }
+ queryArray.push("$filter=" + encodeURIComponent(filterResult));
}
- if (request.collection === "$metadata") {
- headers["Accept"] = "application/xml";
+ if (request.fieldName) {
+ ErrorHelper.stringParameterCheck(request.fieldName, `DynamicsWebApi.${request.functionName}`, "request.fieldName");
+ url += "/" + request.fieldName;
}
- if (request.transferMode) {
- headers["x-ms-transfer-mode"] = request.transferMode;
+ if (request.savedQuery) {
+ queryArray.push("savedQuery=" + ErrorHelper.guidParameterCheck(request.savedQuery, `DynamicsWebApi.${request.functionName}`, "request.savedQuery"));
}
- if (request.ifmatch != null && request.ifnonematch != null) {
- throw new Error(
- `DynamicsWebApi.${request.functionName}. Either one of request.ifmatch or request.ifnonematch parameters should be used in a call, not both.`
- );
+ if (request.userQuery) {
+ queryArray.push("userQuery=" + ErrorHelper.guidParameterCheck(request.userQuery, `DynamicsWebApi.${request.functionName}`, "request.userQuery"));
}
- if (request.ifmatch) {
- ErrorHelper.stringParameterCheck(request.ifmatch, `DynamicsWebApi.${request.functionName}`, "request.ifmatch");
- headers["If-Match"] = request.ifmatch;
+ if (request.apply) {
+ ErrorHelper.stringParameterCheck(request.apply, `DynamicsWebApi.${request.functionName}`, "request.apply");
+ queryArray.push("$apply=" + request.apply);
}
- if (request.ifnonematch) {
- ErrorHelper.stringParameterCheck(request.ifnonematch, `DynamicsWebApi.${request.functionName}`, "request.ifnonematch");
- headers["If-None-Match"] = request.ifnonematch;
+ if (request.count) {
+ ErrorHelper.boolParameterCheck(request.count, `DynamicsWebApi.${request.functionName}`, "request.count");
+ queryArray.push("$count=" + request.count);
}
- if (request.impersonate) {
- ErrorHelper.stringParameterCheck(request.impersonate, `DynamicsWebApi.${request.functionName}`, "request.impersonate");
- headers["MSCRMCallerID"] = ErrorHelper.guidParameterCheck(request.impersonate, `DynamicsWebApi.${request.functionName}`, "request.impersonate");
+ if (request.top && request.top > 0) {
+ ErrorHelper.numberParameterCheck(request.top, `DynamicsWebApi.${request.functionName}`, "request.top");
+ queryArray.push("$top=" + request.top);
}
- if (request.impersonateAAD) {
- ErrorHelper.stringParameterCheck(request.impersonateAAD, `DynamicsWebApi.${request.functionName}`, "request.impersonateAAD");
- headers["CallerObjectId"] = ErrorHelper.guidParameterCheck(
- request.impersonateAAD,
- `DynamicsWebApi.${request.functionName}`,
- "request.impersonateAAD"
- );
+ if (request.orderBy != null && request.orderBy.length) {
+ ErrorHelper.arrayParameterCheck(request.orderBy, `DynamicsWebApi.${request.functionName}`, "request.orderBy");
+ queryArray.push("$orderby=" + request.orderBy.join(","));
}
- if (request.token) {
- ErrorHelper.stringParameterCheck(request.token, `DynamicsWebApi.${request.functionName}`, "request.token");
- headers["Authorization"] = "Bearer " + request.token;
+ if (request.partitionId) {
+ ErrorHelper.stringParameterCheck(request.partitionId, `DynamicsWebApi.${request.functionName}`, "request.partitionId");
+ queryArray.push("partitionid='" + request.partitionId + "'");
}
- if (request.duplicateDetection) {
- ErrorHelper.boolParameterCheck(request.duplicateDetection, `DynamicsWebApi.${request.functionName}`, "request.duplicateDetection");
- headers["MSCRM.SuppressDuplicateDetection"] = "false";
+ if (request.downloadSize) {
+ ErrorHelper.stringParameterCheck(request.downloadSize, `DynamicsWebApi.${request.functionName}`, "request.downloadSize");
+ queryArray.push("size=" + request.downloadSize);
}
- if (request.bypassCustomPluginExecution) {
- ErrorHelper.boolParameterCheck(
- request.bypassCustomPluginExecution,
- `DynamicsWebApi.${request.functionName}`,
- "request.bypassCustomPluginExecution"
- );
- headers["MSCRM.BypassCustomPluginExecution"] = "true";
+ if (request.queryParams?.length) {
+ ErrorHelper.arrayParameterCheck(request.queryParams, `DynamicsWebApi.${request.functionName}`, "request.queryParams");
+ queryArray.push(request.queryParams.join("&"));
}
- if (request.noCache) {
- ErrorHelper.boolParameterCheck(request.noCache, `DynamicsWebApi.${request.functionName}`, "request.noCache");
- headers["Cache-Control"] = "no-cache";
+ if (request.fileName) {
+ ErrorHelper.stringParameterCheck(request.fileName, `DynamicsWebApi.${request.functionName}`, "request.fileName");
+ queryArray.push("x-ms-file-name=" + request.fileName);
}
- if (request.mergeLabels) {
- ErrorHelper.boolParameterCheck(request.mergeLabels, `DynamicsWebApi.${request.functionName}`, "request.mergeLabels");
- headers["MSCRM.MergeLabels"] = "true";
+ if (request.data) {
+ ErrorHelper.parameterCheck(request.data, `DynamicsWebApi.${request.functionName}`, "request.data");
}
- if (request.contentId) {
- ErrorHelper.stringParameterCheck(request.contentId, `DynamicsWebApi.${request.functionName}`, "request.contentId");
- if (!request.contentId.startsWith("$")) {
- headers["Content-ID"] = request.contentId;
- }
+ if (request.isBatch) {
+ ErrorHelper.boolParameterCheck(request.isBatch, `DynamicsWebApi.${request.functionName}`, "request.isBatch");
}
- if (request.contentRange) {
- ErrorHelper.stringParameterCheck(request.contentRange, `DynamicsWebApi.${request.functionName}`, "request.contentRange");
- headers["Content-Range"] = request.contentRange;
+ if (!Utility.isNull(request.inChangeSet)) {
+ ErrorHelper.boolParameterCheck(request.inChangeSet, `DynamicsWebApi.${request.functionName}`, "request.inChangeSet");
}
- if (request.range) {
- ErrorHelper.stringParameterCheck(request.range, `DynamicsWebApi.${request.functionName}`, "request.range");
- headers["Range"] = request.range;
+ if (request.isBatch && Utility.isNull(request.inChangeSet))
+ request.inChangeSet = true;
+ if (request.timeout) {
+ ErrorHelper.numberParameterCheck(request.timeout, `DynamicsWebApi.${request.functionName}`, "request.timeout");
}
- return headers;
- }
- static composePreferHeader(request, config) {
- let returnRepresentation = request.returnRepresentation;
- let includeAnnotations = request.includeAnnotations;
- let maxPageSize = request.maxPageSize;
- let trackChanges = request.trackChanges;
- let continueOnError = request.continueOnError;
- let prefer = [];
- if (request.prefer && request.prefer.length) {
- ErrorHelper.stringOrArrayParameterCheck(request.prefer, `DynamicsWebApi.${request.functionName}`, "request.prefer");
- if (typeof request.prefer === "string") {
- prefer = request.prefer.split(",");
- }
- for (let i in prefer) {
- let item = prefer[i].trim();
- if (item === "return=representation") {
- returnRepresentation = true;
- } else if (item.includes("odata.include-annotations=")) {
- includeAnnotations = item.replace("odata.include-annotations=", "").replace(/"/g, "");
- } else if (item.startsWith("odata.maxpagesize=")) {
- maxPageSize = Number(item.replace("odata.maxpagesize=", "").replace(/"/g, "")) || 0;
- } else if (item.includes("odata.track-changes")) {
- trackChanges = true;
- } else if (item.includes("odata.continue-on-error")) {
- continueOnError = true;
+ if (request.expand?.length) {
+ ErrorHelper.stringOrArrayParameterCheck(request.expand, `DynamicsWebApi.${request.functionName}`, "request.expand");
+ if (typeof request.expand === "string") {
+ queryArray.push("$expand=" + request.expand);
+ } else {
+ const expandQueryArray = [];
+ for (let i = 0; i < request.expand.length; i++) {
+ if (request.expand[i].property) {
+ const expand = request.expand[i];
+ expand.functionName = `${request.functionName} $expand`;
+ let expandConverted = composeUrl(expand, config, "", ";");
+ if (expandConverted) {
+ expandConverted = `(${expandConverted.substr(1)})`;
+ }
+ expandQueryArray.push(request.expand[i].property + expandConverted);
+ }
+ }
+ if (expandQueryArray.length) {
+ queryArray.push("$expand=" + expandQueryArray.join(","));
}
}
}
- prefer = [];
- if (config) {
- if (returnRepresentation == null) {
- returnRepresentation = config.returnRepresentation;
- }
- includeAnnotations = includeAnnotations ? includeAnnotations : config.includeAnnotations;
- maxPageSize = maxPageSize ? maxPageSize : config.maxPageSize;
- }
- if (returnRepresentation) {
- ErrorHelper.boolParameterCheck(returnRepresentation, `DynamicsWebApi.${request.functionName}`, "request.returnRepresentation");
- prefer.push("return=representation");
- }
- if (includeAnnotations) {
- ErrorHelper.stringParameterCheck(includeAnnotations, `DynamicsWebApi.${request.functionName}`, "request.includeAnnotations");
- prefer.push(`odata.include-annotations="${includeAnnotations}"`);
- }
- if (maxPageSize && maxPageSize > 0) {
- ErrorHelper.numberParameterCheck(maxPageSize, `DynamicsWebApi.${request.functionName}`, "request.maxPageSize");
- prefer.push("odata.maxpagesize=" + maxPageSize);
+ }
+ return !queryArray.length ? url : url + "?" + queryArray.join(joinSymbol);
+};
+var composeHeaders = (request, config) => {
+ const headers = { ...config.headers, ...request.userHeaders };
+ const prefer = composePreferHeader(request, config);
+ if (prefer.length) {
+ headers["Prefer"] = prefer;
+ }
+ if (request.collection === "$metadata") {
+ headers["Accept"] = "application/xml";
+ }
+ if (request.transferMode) {
+ headers["x-ms-transfer-mode"] = request.transferMode;
+ }
+ if (request.ifmatch != null && request.ifnonematch != null) {
+ throw new Error(
+ `DynamicsWebApi.${request.functionName}. Either one of request.ifmatch or request.ifnonematch parameters should be used in a call, not both.`
+ );
+ }
+ if (request.ifmatch) {
+ ErrorHelper.stringParameterCheck(request.ifmatch, `DynamicsWebApi.${request.functionName}`, "request.ifmatch");
+ headers["If-Match"] = request.ifmatch;
+ }
+ if (request.ifnonematch) {
+ ErrorHelper.stringParameterCheck(request.ifnonematch, `DynamicsWebApi.${request.functionName}`, "request.ifnonematch");
+ headers["If-None-Match"] = request.ifnonematch;
+ }
+ if (request.impersonate) {
+ ErrorHelper.stringParameterCheck(request.impersonate, `DynamicsWebApi.${request.functionName}`, "request.impersonate");
+ headers["MSCRMCallerID"] = ErrorHelper.guidParameterCheck(request.impersonate, `DynamicsWebApi.${request.functionName}`, "request.impersonate");
+ }
+ if (request.impersonateAAD) {
+ ErrorHelper.stringParameterCheck(request.impersonateAAD, `DynamicsWebApi.${request.functionName}`, "request.impersonateAAD");
+ headers["CallerObjectId"] = ErrorHelper.guidParameterCheck(request.impersonateAAD, `DynamicsWebApi.${request.functionName}`, "request.impersonateAAD");
+ }
+ if (request.token) {
+ ErrorHelper.stringParameterCheck(request.token, `DynamicsWebApi.${request.functionName}`, "request.token");
+ headers["Authorization"] = "Bearer " + request.token;
+ }
+ if (request.duplicateDetection) {
+ ErrorHelper.boolParameterCheck(request.duplicateDetection, `DynamicsWebApi.${request.functionName}`, "request.duplicateDetection");
+ headers["MSCRM.SuppressDuplicateDetection"] = "false";
+ }
+ if (request.bypassCustomPluginExecution) {
+ ErrorHelper.boolParameterCheck(request.bypassCustomPluginExecution, `DynamicsWebApi.${request.functionName}`, "request.bypassCustomPluginExecution");
+ headers["MSCRM.BypassCustomPluginExecution"] = "true";
+ }
+ if (request.noCache) {
+ ErrorHelper.boolParameterCheck(request.noCache, `DynamicsWebApi.${request.functionName}`, "request.noCache");
+ headers["Cache-Control"] = "no-cache";
+ }
+ if (request.mergeLabels) {
+ ErrorHelper.boolParameterCheck(request.mergeLabels, `DynamicsWebApi.${request.functionName}`, "request.mergeLabels");
+ headers["MSCRM.MergeLabels"] = "true";
+ }
+ if (request.contentId) {
+ ErrorHelper.stringParameterCheck(request.contentId, `DynamicsWebApi.${request.functionName}`, "request.contentId");
+ if (!request.contentId.startsWith("$")) {
+ headers["Content-ID"] = request.contentId;
}
- if (trackChanges) {
- ErrorHelper.boolParameterCheck(trackChanges, `DynamicsWebApi.${request.functionName}`, "request.trackChanges");
- prefer.push("odata.track-changes");
+ }
+ if (request.contentRange) {
+ ErrorHelper.stringParameterCheck(request.contentRange, `DynamicsWebApi.${request.functionName}`, "request.contentRange");
+ headers["Content-Range"] = request.contentRange;
+ }
+ if (request.range) {
+ ErrorHelper.stringParameterCheck(request.range, `DynamicsWebApi.${request.functionName}`, "request.range");
+ headers["Range"] = request.range;
+ }
+ return headers;
+};
+var composePreferHeader = (request, config) => {
+ let returnRepresentation = request.returnRepresentation;
+ let includeAnnotations = request.includeAnnotations;
+ let maxPageSize = request.maxPageSize;
+ let trackChanges = request.trackChanges;
+ let continueOnError = request.continueOnError;
+ let prefer = [];
+ if (request.prefer && request.prefer.length) {
+ ErrorHelper.stringOrArrayParameterCheck(request.prefer, `DynamicsWebApi.${request.functionName}`, "request.prefer");
+ if (typeof request.prefer === "string") {
+ prefer = request.prefer.split(",");
+ }
+ for (let i in prefer) {
+ let item = prefer[i].trim();
+ if (item === "return=representation") {
+ returnRepresentation = true;
+ } else if (item.includes("odata.include-annotations=")) {
+ includeAnnotations = item.replace("odata.include-annotations=", "").replace(/"/g, "");
+ } else if (item.startsWith("odata.maxpagesize=")) {
+ maxPageSize = Number(item.replace("odata.maxpagesize=", "").replace(/"/g, "")) || 0;
+ } else if (item.includes("odata.track-changes")) {
+ trackChanges = true;
+ } else if (item.includes("odata.continue-on-error")) {
+ continueOnError = true;
+ }
}
- if (continueOnError) {
- ErrorHelper.boolParameterCheck(continueOnError, `DynamicsWebApi.${request.functionName}`, "request.continueOnError");
- prefer.push("odata.continue-on-error");
+ }
+ prefer = [];
+ if (config) {
+ if (returnRepresentation == null) {
+ returnRepresentation = config.returnRepresentation;
}
- return prefer.join(",");
+ includeAnnotations = includeAnnotations ? includeAnnotations : config.includeAnnotations;
+ maxPageSize = maxPageSize ? maxPageSize : config.maxPageSize;
}
- static convertToBatch(requests, config, batchRequest) {
- const batchBoundary = `dwa_batch_${Utility.generateUUID()}`;
- const batchBody = [];
- let currentChangeSet = null;
- let contentId = 1e5;
- requests.forEach((internalRequest) => {
- internalRequest.functionName = "executeBatch";
- if (batchRequest?.inChangeSet === false)
- internalRequest.inChangeSet = false;
- const inChangeSet = internalRequest.method === "GET" ? false : !!internalRequest.inChangeSet;
- if (!inChangeSet && currentChangeSet) {
- batchBody.push(`
+ if (returnRepresentation) {
+ ErrorHelper.boolParameterCheck(returnRepresentation, `DynamicsWebApi.${request.functionName}`, "request.returnRepresentation");
+ prefer.push("return=representation");
+ }
+ if (includeAnnotations) {
+ ErrorHelper.stringParameterCheck(includeAnnotations, `DynamicsWebApi.${request.functionName}`, "request.includeAnnotations");
+ prefer.push(`odata.include-annotations="${includeAnnotations}"`);
+ }
+ if (maxPageSize && maxPageSize > 0) {
+ ErrorHelper.numberParameterCheck(maxPageSize, `DynamicsWebApi.${request.functionName}`, "request.maxPageSize");
+ prefer.push("odata.maxpagesize=" + maxPageSize);
+ }
+ if (trackChanges) {
+ ErrorHelper.boolParameterCheck(trackChanges, `DynamicsWebApi.${request.functionName}`, "request.trackChanges");
+ prefer.push("odata.track-changes");
+ }
+ if (continueOnError) {
+ ErrorHelper.boolParameterCheck(continueOnError, `DynamicsWebApi.${request.functionName}`, "request.continueOnError");
+ prefer.push("odata.continue-on-error");
+ }
+ return prefer.join(",");
+};
+var convertToBatch = (requests, config, batchRequest) => {
+ const batchBoundary = `dwa_batch_${Utility.generateUUID()}`;
+ const batchBody = [];
+ let currentChangeSet = null;
+ let contentId = 1e5;
+ requests.forEach((internalRequest) => {
+ internalRequest.functionName = "executeBatch";
+ if (batchRequest?.inChangeSet === false)
+ internalRequest.inChangeSet = false;
+ const inChangeSet = internalRequest.method === "GET" ? false : !!internalRequest.inChangeSet;
+ if (!inChangeSet && currentChangeSet) {
+ batchBody.push(`
--${currentChangeSet}--`);
- currentChangeSet = null;
- contentId = 1e5;
- }
- if (!currentChangeSet) {
- batchBody.push(`
+ currentChangeSet = null;
+ contentId = 1e5;
+ }
+ if (!currentChangeSet) {
+ batchBody.push(`
--${batchBoundary}`);
- if (inChangeSet) {
- currentChangeSet = `changeset_${Utility.generateUUID()}`;
- batchBody.push("Content-Type: multipart/mixed;boundary=" + currentChangeSet);
- }
- }
if (inChangeSet) {
- batchBody.push(`
---${currentChangeSet}`);
+ currentChangeSet = `changeset_${Utility.generateUUID()}`;
+ batchBody.push("Content-Type: multipart/mixed;boundary=" + currentChangeSet);
}
- batchBody.push("Content-Type: application/http");
- batchBody.push("Content-Transfer-Encoding: binary");
- if (inChangeSet) {
- const contentIdValue = internalRequest.headers.hasOwnProperty("Content-ID") ? internalRequest.headers["Content-ID"] : ++contentId;
- batchBody.push(`Content-ID: ${contentIdValue}`);
- }
- if (!internalRequest.path?.startsWith("$")) {
- batchBody.push(`
+ }
+ if (inChangeSet) {
+ batchBody.push(`
+--${currentChangeSet}`);
+ }
+ batchBody.push("Content-Type: application/http");
+ batchBody.push("Content-Transfer-Encoding: binary");
+ if (inChangeSet) {
+ const contentIdValue = internalRequest.headers.hasOwnProperty("Content-ID") ? internalRequest.headers["Content-ID"] : ++contentId;
+ batchBody.push(`Content-ID: ${contentIdValue}`);
+ }
+ if (!internalRequest.path?.startsWith("$")) {
+ batchBody.push(`
${internalRequest.method} ${config.dataApi.url}${internalRequest.path} HTTP/1.1`);
- } else {
- batchBody.push(`
+ } else {
+ batchBody.push(`
${internalRequest.method} ${internalRequest.path} HTTP/1.1`);
- }
- if (internalRequest.method === "GET") {
- batchBody.push("Accept: application/json");
- } else {
- batchBody.push("Content-Type: application/json");
- }
- for (let key in internalRequest.headers) {
- if (key === "Authorization" || key === "Content-ID")
- continue;
- batchBody.push(`${key}: ${internalRequest.headers[key]}`);
- }
- if (internalRequest.data) {
- batchBody.push(`
-${_RequestUtility.processData(internalRequest.data, config)}`);
- }
- });
- if (currentChangeSet) {
+ }
+ if (internalRequest.method === "GET") {
+ batchBody.push("Accept: application/json");
+ } else {
+ batchBody.push("Content-Type: application/json");
+ }
+ for (let key in internalRequest.headers) {
+ if (key === "Authorization" || key === "Content-ID")
+ continue;
+ batchBody.push(`${key}: ${internalRequest.headers[key]}`);
+ }
+ if (internalRequest.data) {
batchBody.push(`
---${currentChangeSet}--`);
+${processData(internalRequest.data, config)}`);
}
+ });
+ if (currentChangeSet) {
batchBody.push(`
+--${currentChangeSet}--`);
+ }
+ batchBody.push(`
--${batchBoundary}--`);
- const headers = _RequestUtility.setStandardHeaders(batchRequest?.userHeaders);
- headers["Content-Type"] = `multipart/mixed;boundary=${batchBoundary}`;
- return { headers, body: batchBody.join("\n") };
- }
- static findCollectionName(entityName) {
- let collectionName = null;
- if (!Utility.isNull(_RequestUtility.entityNames)) {
- collectionName = _RequestUtility.entityNames[entityName];
- if (Utility.isNull(collectionName)) {
- for (let key in _RequestUtility.entityNames) {
- if (_RequestUtility.entityNames[key] === entityName) {
- return entityName;
- }
+ const headers = setStandardHeaders(batchRequest?.userHeaders);
+ headers["Content-Type"] = `multipart/mixed;boundary=${batchBoundary}`;
+ return { headers, body: batchBody.join("\n") };
+};
+var findCollectionName = (entityName) => {
+ let collectionName = null;
+ if (!Utility.isNull(entityNames)) {
+ collectionName = entityNames[entityName];
+ if (!collectionName) {
+ for (let key in entityNames) {
+ if (entityNames[key] === entityName) {
+ return entityName;
}
}
}
- return collectionName;
}
- static processData(data, config) {
- let stringifiedData = null;
- if (data) {
- if (data instanceof Uint8Array || data instanceof Uint16Array || data instanceof Uint32Array)
- return data;
- stringifiedData = JSON.stringify(data, (key, value) => {
- if (key.endsWith("@odata.bind") || key.endsWith("@odata.id")) {
- if (typeof value === "string" && !value.startsWith("$")) {
- if (/\(\{[\w\d-]+\}\)/g.test(value)) {
- value = value.replace(/(.+)\(\{([\w\d-]+)\}\)/g, "$1($2)");
- }
- if (config.useEntityNames) {
- const regularExpression = /([\w_]+)(\([\d\w-]+\))$/;
- const valueParts = regularExpression.exec(value);
- if (valueParts && valueParts.length > 2) {
- const collectionName = _RequestUtility.findCollectionName(valueParts[1]);
- if (!Utility.isNull(collectionName)) {
- value = value.replace(regularExpression, collectionName + "$2");
- }
+ return collectionName;
+};
+var processData = (data, config) => {
+ let stringifiedData = null;
+ if (data) {
+ if (data instanceof Uint8Array || data instanceof Uint16Array || data instanceof Uint32Array)
+ return data;
+ stringifiedData = JSON.stringify(data, (key, value) => {
+ if (key.endsWith("@odata.bind") || key.endsWith("@odata.id")) {
+ if (typeof value === "string" && !value.startsWith("$")) {
+ if (/\(\{[\w\d-]+\}\)/g.test(value)) {
+ value = value.replace(/(.+)\(\{([\w\d-]+)\}\)/g, "$1($2)");
+ }
+ if (config.useEntityNames) {
+ const regularExpression = /([\w_]+)(\([\d\w-]+\))$/;
+ const valueParts = regularExpression.exec(value);
+ if (valueParts && valueParts.length > 2) {
+ const collectionName = findCollectionName(valueParts[1]);
+ if (!Utility.isNull(collectionName)) {
+ value = value.replace(regularExpression, collectionName + "$2");
}
}
- if (!value.startsWith(config.dataApi.url)) {
- if (key.endsWith("@odata.bind")) {
- if (!value.startsWith("/")) {
- value = "/" + value;
- }
- } else {
- value = config.dataApi.url + value.replace(/^\//, "");
+ }
+ if (!value.startsWith(config.dataApi.url)) {
+ if (key.endsWith("@odata.bind")) {
+ if (!value.startsWith("/")) {
+ value = "/" + value;
}
+ } else {
+ value = config.dataApi.url + value.replace(/^\//, "");
}
}
- } else if (key.startsWith("oData") || key.endsWith("_Formatted") || key.endsWith("_NavigationProperty") || key.endsWith("_LogicalName")) {
- value = void 0;
}
- return value;
- });
- stringifiedData = stringifiedData.replace(/[\u007F-\uFFFF]/g, function(chr) {
- return "\\u" + ("0000" + chr.charCodeAt(0).toString(16)).slice(-4);
- });
- }
- return stringifiedData;
- }
- static setStandardHeaders(headers = {}) {
- if (!headers["Accept"])
- headers["Accept"] = "application/json";
- if (!headers["OData-MaxVersion"])
- headers["OData-MaxVersion"] = "4.0";
- if (!headers["OData-Version"])
- headers["OData-Version"] = "4.0";
- if (headers["Content-Range"])
- headers["Content-Type"] = "application/octet-stream";
- else if (!headers["Content-Type"])
- headers["Content-Type"] = "application/json; charset=utf-8";
- return headers;
+ } else if (key.startsWith("oData") || key.endsWith("_Formatted") || key.endsWith("_NavigationProperty") || key.endsWith("_LogicalName")) {
+ value = void 0;
+ }
+ return value;
+ });
+ stringifiedData = stringifiedData.replace(/[\u007F-\uFFFF]/g, function(chr) {
+ return "\\u" + ("0000" + chr.charCodeAt(0).toString(16)).slice(-4);
+ });
}
+ return stringifiedData;
+};
+var setStandardHeaders = (headers = {}) => {
+ if (!headers["Accept"])
+ headers["Accept"] = "application/json";
+ if (!headers["OData-MaxVersion"])
+ headers["OData-MaxVersion"] = "4.0";
+ if (!headers["OData-Version"])
+ headers["OData-Version"] = "4.0";
+ if (headers["Content-Range"])
+ headers["Content-Type"] = "application/octet-stream";
+ else if (!headers["Content-Type"])
+ headers["Content-Type"] = "application/json; charset=utf-8";
+ return headers;
};
-_RequestUtility.entityNames = null;
-var RequestUtility = _RequestUtility;
// src/client/RequestClient.ts
init_ErrorHelper();
@@ -1463,7 +1430,55 @@ var _runRequest = async (request, config) => {
};
var _batchRequestCollection = {};
var _responseParseParams = {};
-var RequestClient = class _RequestClient {
+var _nameExceptions = [
+ "$metadata",
+ "EntityDefinitions",
+ "RelationshipDefinitions",
+ "GlobalOptionSetDefinitions",
+ "ManagedPropertyDefinitions",
+ "query",
+ "suggest",
+ "autocomplete"
+];
+var _isEntityNameException = (entityName) => {
+ return _nameExceptions.indexOf(entityName) > -1;
+};
+var _getCollectionNames = async (entityName, config) => {
+ if (!Utility.isNull(entityNames)) {
+ return findCollectionName(entityName) || entityName;
+ }
+ const request = compose(
+ {
+ method: "GET",
+ collection: "EntityDefinitions",
+ select: ["EntitySetName", "LogicalName"],
+ noCache: true,
+ functionName: "retrieveMultiple"
+ },
+ config
+ );
+ const result = await _runRequest(request, config);
+ setEntityNames({});
+ for (let i = 0; i < result.data.value.length; i++) {
+ entityNames[result.data.value[i].LogicalName] = result.data.value[i].EntitySetName;
+ }
+ return findCollectionName(entityName) || entityName;
+};
+var _checkCollectionName = async (entityName, config) => {
+ if (!entityName || _isEntityNameException(entityName)) {
+ return entityName;
+ }
+ entityName = entityName.toLowerCase();
+ if (!config.useEntityNames) {
+ return entityName;
+ }
+ try {
+ return await _getCollectionNames(entityName, config);
+ } catch (error) {
+ throw new Error("Unable to fetch Collection Names. Error: " + error.message);
+ }
+};
+var RequestClient = class {
/**
* Sends a request to given URL with given parameters
*
@@ -1481,14 +1496,14 @@ var RequestClient = class _RequestClient {
const batchRequest = _batchRequestCollection[request.requestId];
if (!batchRequest)
throw ErrorHelper.batchIsEmpty();
- const batchResult = RequestUtility.convertToBatch(batchRequest, config, request);
+ const batchResult = convertToBatch(batchRequest, config, request);
processedData = batchResult.body;
request.headers = { ...batchResult.headers, ...request.headers };
delete _batchRequestCollection[request.requestId];
} else {
- processedData = !isBatchConverted ? RequestUtility.processData(request.data, config) : request.data;
+ processedData = !isBatchConverted ? processData(request.data, config) : request.data;
if (!isBatchConverted)
- request.headers = RequestUtility.setStandardHeaders(request.headers);
+ request.headers = setStandardHeaders(request.headers);
}
if (config.impersonate && !request.headers["MSCRMCallerID"]) {
request.headers["MSCRMCallerID"] = config.impersonate;
@@ -1513,74 +1528,29 @@ var RequestClient = class _RequestClient {
method: request.method,
uri: url.toString() + request.path,
data: processedData,
- additionalHeaders: request.headers,
- responseParams: _responseParseParams,
- isAsync: request.async,
- timeout: request.timeout || config.timeout,
proxy: config.proxy,
+ isAsync: request.async,
+ headers: request.headers,
requestId: request.requestId,
- abortSignal: request.signal
+ abortSignal: request.signal,
+ responseParams: _responseParseParams,
+ timeout: request.timeout || config.timeout
});
}
- static async _getCollectionNames(entityName, config) {
- if (!Utility.isNull(RequestUtility.entityNames)) {
- return RequestUtility.findCollectionName(entityName) || entityName;
- }
- const request = RequestUtility.compose(
- {
- method: "GET",
- collection: "EntityDefinitions",
- select: ["EntitySetName", "LogicalName"],
- noCache: true,
- functionName: "retrieveMultiple"
- },
- config
- );
- const result = await _runRequest(request, config);
- RequestUtility.entityNames = {};
- for (let i = 0; i < result.data.value.length; i++) {
- RequestUtility.entityNames[result.data.value[i].LogicalName] = result.data.value[i].EntitySetName;
- }
- return RequestUtility.findCollectionName(entityName) || entityName;
- }
- static _isEntityNameException(entityName) {
- const exceptions = [
- "$metadata",
- "EntityDefinitions",
- "RelationshipDefinitions",
- "GlobalOptionSetDefinitions",
- "ManagedPropertyDefinitions",
- "query",
- "suggest",
- "autocomplete"
- ];
- return exceptions.indexOf(entityName) > -1;
- }
- static async _checkCollectionName(entityName, config) {
- if (!entityName || _RequestClient._isEntityNameException(entityName)) {
- return entityName;
- }
- entityName = entityName.toLowerCase();
- if (!config.useEntityNames) {
- return entityName;
- }
- try {
- return await _RequestClient._getCollectionNames(entityName, config);
- } catch (error) {
- throw new Error("Unable to fetch Collection Names. Error: " + error.message);
- }
- }
static async makeRequest(request, config) {
request.responseParameters = request.responseParameters || {};
request.userHeaders = request.headers;
delete request.headers;
if (!request.isBatch) {
- const collectionName = await _RequestClient._checkCollectionName(request.collection, config);
+ const collectionName = await _checkCollectionName(request.collection, config);
request.collection = collectionName;
- RequestUtility.compose(request, config);
+ compose(request, config);
request.responseParameters.convertedToBatch = false;
if (request.path.length > 2e3) {
- const batchRequest = RequestUtility.convertToBatch([request], config);
+ const batchRequest = convertToBatch([request], config);
+ if (request.headers["Authorization"]) {
+ batchRequest.headers["Authorization"] = request.headers["Authorization"];
+ }
request.method = "POST";
request.path = "$batch";
request.data = batchRequest.body;
@@ -1589,17 +1559,17 @@ var RequestClient = class _RequestClient {
}
return _runRequest(request, config);
}
- RequestUtility.compose(request, config);
+ compose(request, config);
_addResponseParams(request.requestId, request.responseParameters);
_addRequestToBatchCollection(request.requestId, request);
}
static _clearTestData() {
- RequestUtility.entityNames = null;
+ setEntityNames(null);
_responseParseParams = {};
_batchRequestCollection = {};
}
static getCollectionName(entityName) {
- return RequestUtility.findCollectionName(entityName);
+ return findCollectionName(entityName);
}
};
@@ -2071,7 +2041,7 @@ var DynamicsWebApi = class _DynamicsWebApi {
ErrorHelper.stringParameterCheck(functionName, `DynamicsWebApi.callFunction`, parameterName);
const functionParameters = Utility.buildFunctionParameters(internalRequest.parameters);
internalRequest.method = "GET";
- internalRequest._additionalUrl = functionName + functionParameters.key;
+ internalRequest.addPath = functionName + functionParameters.key;
internalRequest.queryParams = functionParameters.queryParams;
internalRequest._isUnboundRequest = !internalRequest.collection;
internalRequest.functionName = "callFunction";
@@ -2090,7 +2060,7 @@ var DynamicsWebApi = class _DynamicsWebApi {
const internalRequest = Utility.copyRequest(request, ["action"]);
internalRequest.method = "POST";
internalRequest.functionName = "callAction";
- internalRequest._additionalUrl = request.actionName;
+ internalRequest.addPath = request.actionName;
internalRequest._isUnboundRequest = !internalRequest.collection;
internalRequest.data = request.action;
const response = await this._makeRequest(internalRequest);
diff --git a/dist/browser/esm/dynamics-web-api.js.map b/dist/browser/esm/dynamics-web-api.js.map
index 5b1ff3f..8beb001 100644
--- a/dist/browser/esm/dynamics-web-api.js.map
+++ b/dist/browser/esm/dynamics-web-api.js.map
@@ -1,7 +1,7 @@
{
"version": 3,
"sources": ["../../../src/helpers/Crypto.ts", "../../../src/helpers/Regex.ts", "../../../src/utils/Utility.ts", "../../../src/helpers/ErrorHelper.ts", "../../../src/dwa.ts", "../../../src/client/helpers/dateReviver.ts", "../../../src/client/helpers/parseResponse.ts", "../../../src/client/helpers/parseResponseHeaders.ts", "../../../src/client/xhr.ts", "../../../src/utils/Config.ts", "../../../src/dynamics-web-api.ts", "../../../src/client/RequestClient.ts", "../../../src/utils/Request.ts", "../../../src/client/helpers/executeRequest.ts"],
- "sourcesContent": ["export function getCrypto(): T {\r\n return global.DWA_BROWSER ? global.window.crypto : require(\"./crypto/node\").getCrypto();\r\n}\r\n\r\nexport function generateRandomBytes() {\r\n return global.DWA_BROWSER ? getCrypto().getRandomValues(new Uint8Array(1)) : getCrypto().randomBytes(1);\r\n}\r\n", "const uuid = \"[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}\";\r\n\r\nexport function isUuid(value: string): boolean {\r\n const match = new RegExp(uuid, \"i\").exec(value);\r\n return !!match;\r\n}\r\n\r\nexport function extractUuid(value: string): string | null {\r\n const match = new RegExp(\"^{?(\" + uuid + \")}?$\", \"i\").exec(value);\r\n return match ? match[1] : null;\r\n}\r\n\r\nexport function extractUuidFromUrl(url: string): string | null {\r\n const match = new RegExp(\"(\" + uuid + \")\\\\)$\", \"i\").exec(url);\r\n return match ? match[1] : null;\r\n}\r\n", "\uFEFFimport { Core } from \"../types\";\r\nimport { generateRandomBytes } from \"../helpers/Crypto\";\r\nimport { isUuid, extractUuid } from \"../helpers/Regex\";\r\n\r\ndeclare var GetGlobalContext: any;\r\ndeclare var Xrm: any;\r\n\r\n// function isNodeEnv(): boolean {\r\n// // tslint:disable:strict-type-predicates\r\n// return Object.prototype.toString.call(typeof process !== \"undefined\" ? process : 0) === \"[object process]\";\r\n// }\r\n\r\n// function getGlobalObject(): T {\r\n// return (isNodeEnv() ? global : typeof window !== \"undefined\" ? window : typeof self !== \"undefined\" ? self : {}) as T;\r\n// }\r\n\r\nconst downloadChunkSize = 4194304;\r\n\r\nexport class Utility {\r\n /**\r\n * Builds parametes for a funciton. Returns '()' (if no parameters) or '([params])?[query]'\r\n *\r\n * @param {Object} [parameters] - Function's input parameters. Example: { param1: \"test\", param2: 3 }.\r\n * @returns {string}\r\n */\r\n static buildFunctionParameters(parameters?: any): Core.FunctionParameters {\r\n if (parameters) {\r\n const parameterNames = Object.keys(parameters);\r\n const functionParams: string[] = [];\r\n const urlQuery: string[] = [];\r\n\r\n for (let i = 1; i <= parameterNames.length; i++) {\r\n const parameterName = parameterNames[i - 1];\r\n let value = parameters[parameterName];\r\n\r\n if (value == null) continue;\r\n\r\n if (typeof value === \"string\" && !value.startsWith(\"Microsoft.Dynamics.CRM\") && !isUuid(value)) {\r\n value = `'${value}'`;\r\n } else if (typeof value === \"object\") {\r\n value = JSON.stringify(value);\r\n }\r\n\r\n functionParams.push(`${parameterName}=@p${i}`);\r\n urlQuery.push(`@p${i}=${extractUuid(value) || value}`);\r\n }\r\n\r\n return {\r\n key: `(${functionParams.join(\",\")})`,\r\n queryParams: urlQuery,\r\n };\r\n } else {\r\n return {\r\n key: \"()\",\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Parses a paging cookie returned in response\r\n *\r\n * @param {string} pageCookies - Page cookies returned in @Microsoft.Dynamics.CRM.fetchxmlpagingcookie.\r\n * @param {number} currentPageNumber - A current page number. Fix empty paging-cookie for complex fetch xmls.\r\n * @returns {{cookie: \"\", number: 0, next: 1}}\r\n */\r\n static getFetchXmlPagingCookie(pageCookies: string = \"\", currentPageNumber: number = 1): Core.FetchXmlCookie {\r\n //get the page cokies\r\n pageCookies = decodeURIComponent(decodeURIComponent(pageCookies));\r\n\r\n const info = /pagingcookie=\"()/.exec(pageCookies);\r\n\r\n if (info != null) {\r\n let page = parseInt(info[2]);\r\n return {\r\n cookie: info[1]\r\n .replace(//g, \">\")\r\n .replace(/\\\"/g, \"'\")\r\n .replace(/\\'/g, \"&\" + \"quot;\"),\r\n page: page,\r\n nextPage: page + 1,\r\n };\r\n } else {\r\n //http://stackoverflow.com/questions/41262772/execution-of-fetch-xml-using-web-api-dynamics-365 workaround\r\n return {\r\n cookie: \"\",\r\n page: currentPageNumber,\r\n nextPage: currentPageNumber + 1,\r\n };\r\n }\r\n }\r\n\r\n // static isNodeEnv = isNodeEnv;\r\n\r\n static downloadChunkSize = downloadChunkSize;\r\n\r\n /**\r\n * Converts a response to a reference object\r\n *\r\n * @param {Object} responseData - Response object\r\n * @returns {ReferenceObject}\r\n */\r\n static convertToReferenceObject(responseData: any): Core.ReferenceObject {\r\n const result = /\\/(\\w+)\\(([0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12})/i.exec(responseData[\"@odata.id\"]);\r\n return { id: result![2], collection: result![1], oDataContext: responseData[\"@odata.context\"] };\r\n }\r\n\r\n /**\r\n * Checks whether the value is JS Null.\r\n * @param {Object} value\r\n * @returns {boolean}\r\n */\r\n static isNull(value: any): boolean {\r\n return typeof value === \"undefined\" || value == null;\r\n }\r\n\r\n /** Generates UUID */\r\n static generateUUID(): string {\r\n return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) => (c ^ (generateRandomBytes()[0] & (15 >> (c / 4)))).toString(16));\r\n }\r\n\r\n static getXrmContext(): any {\r\n if (typeof GetGlobalContext !== \"undefined\") {\r\n return GetGlobalContext();\r\n } else {\r\n if (typeof Xrm !== \"undefined\") {\r\n //d365 v.9.0\r\n if (!Utility.isNull(Xrm.Utility) && !Utility.isNull(Xrm.Utility.getGlobalContext)) {\r\n return Xrm.Utility.getGlobalContext();\r\n } else if (!Utility.isNull(Xrm.Page) && !Utility.isNull(Xrm.Page.context)) {\r\n return Xrm.Page.context;\r\n }\r\n }\r\n }\r\n\r\n throw new Error(\r\n \"Xrm Context is not available. In most cases, it can be resolved by adding a reference to a ClientGlobalContext.js.aspx. Please refer to MSDN documentation for more details.\"\r\n );\r\n }\r\n\r\n // static getXrmUtility(): any {\r\n // return typeof Xrm !== \"undefined\" ? Xrm.Utility : null;\r\n // }\r\n\r\n static getClientUrl(): string {\r\n const context = Utility.getXrmContext();\r\n\r\n let clientUrl = context.getClientUrl();\r\n\r\n if (clientUrl.match(/\\/$/)) {\r\n clientUrl = clientUrl.substring(0, clientUrl.length - 1);\r\n }\r\n return clientUrl;\r\n }\r\n\r\n /**\r\n * Checks whether the app is currently running in a Dynamics Portals Environment.\r\n *\r\n * In that case we switch to the Web API for Dynamics Portals.\r\n * @returns {boolean}\r\n */\r\n static isRunningWithinPortals(): boolean {\r\n return global.DWA_BROWSER ? !!global.window.shell : false;\r\n }\r\n\r\n static isObject(obj: any): boolean {\r\n return typeof obj === \"object\" && !!obj && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== \"[object Date]\";\r\n }\r\n\r\n static copyObject(src: any, excludeProps?: string[]): T {\r\n let target = {};\r\n for (let prop in src) {\r\n if (src.hasOwnProperty(prop) && !excludeProps?.includes(prop)) {\r\n // if the value is a nested object, recursively copy all its properties\r\n if (Utility.isObject(src[prop])) {\r\n target[prop] = Utility.copyObject(src[prop]);\r\n } else if (Array.isArray(src[prop])) {\r\n target[prop] = src[prop].slice();\r\n } else {\r\n target[prop] = src[prop];\r\n }\r\n }\r\n }\r\n return target;\r\n }\r\n\r\n static copyRequest(src: any, excludeProps: string[] = []): Core.InternalRequest {\r\n //todo: do we need to include \"data\" in here?\r\n if (!excludeProps.includes(\"signal\")) excludeProps.push(\"signal\");\r\n\r\n const result = Utility.copyObject(src, excludeProps);\r\n result.signal = src.signal;\r\n\r\n return result;\r\n }\r\n\r\n static setFileChunk(request: Core.InternalRequest, fileBuffer: Uint8Array | Buffer, chunkSize: number, offset: number): void {\r\n offset = offset || 0;\r\n\r\n const count = offset + chunkSize > fileBuffer.length ? fileBuffer.length % chunkSize : chunkSize;\r\n\r\n let content: any;\r\n\r\n if (global.DWA_BROWSER) {\r\n content = new Uint8Array(count);\r\n for (let i = 0; i < count; i++) {\r\n content[i] = fileBuffer[offset + i];\r\n }\r\n } else {\r\n content = fileBuffer.slice(offset, offset + count);\r\n }\r\n\r\n request.data = content;\r\n request.contentRange = \"bytes \" + offset + \"-\" + (offset + count - 1) + \"/\" + fileBuffer.length;\r\n }\r\n\r\n static convertToFileBuffer(binaryString: string): Uint8Array | Buffer {\r\n if (!global.DWA_BROWSER) return Buffer.from(binaryString, \"binary\");\r\n\r\n const bytes = new Uint8Array(binaryString.length);\r\n for (var i = 0; i < binaryString.length; i++) {\r\n bytes[i] = binaryString.charCodeAt(i);\r\n }\r\n return bytes;\r\n }\r\n}\r\n", "\uFEFFimport { AccessToken } from \"../dynamics-web-api\";\r\nimport { extractUuid } from \"./Regex\";\r\n\r\nexport interface DynamicsWebApiError extends Error {\r\n status: number;\r\n}\r\n\r\nfunction throwParameterError(functionName: string, parameterName: string, type: string | null | undefined): void {\r\n throw new Error(\r\n type ? `${functionName} requires a ${parameterName} parameter to be of type ${type}.` : `${functionName} requires a ${parameterName} parameter.`\r\n );\r\n}\r\n\r\nexport class ErrorHelper {\r\n static handleErrorResponse(req): void {\r\n throw new Error(`Error: ${req.status}: ${req.message}`);\r\n }\r\n\r\n static parameterCheck(parameter: any, functionName: string, parameterName: string, type?: string): void {\r\n if (typeof parameter === \"undefined\" || parameter === null || parameter === \"\") {\r\n throwParameterError(functionName, parameterName, type);\r\n }\r\n }\r\n\r\n static stringParameterCheck(parameter: any, functionName: string, parameterName: string): void {\r\n if (typeof parameter !== \"string\") {\r\n throwParameterError(functionName, parameterName, \"String\");\r\n }\r\n }\r\n\r\n static maxLengthStringParameterCheck(parameter: string | null, functionName: string, parameterName: string, maxLength: number): void {\r\n if (!parameter) return;\r\n\r\n if (parameter.length > maxLength) {\r\n throw new Error(`${parameterName} has a ${maxLength} character limit.`);\r\n }\r\n }\r\n\r\n static arrayParameterCheck(parameter: any, functionName: string, parameterName: string): void {\r\n if (parameter.constructor !== Array) {\r\n throwParameterError(functionName, parameterName, \"Array\");\r\n }\r\n }\r\n\r\n static stringOrArrayParameterCheck(parameter: any, functionName: string, parameterName: string): void {\r\n if (parameter.constructor !== Array && typeof parameter !== \"string\") {\r\n throwParameterError(functionName, parameterName, \"String or Array\");\r\n }\r\n }\r\n\r\n static numberParameterCheck(parameter: any, functionName: string, parameterName: string): void {\r\n if (typeof parameter != \"number\") {\r\n if (typeof parameter === \"string\" && parameter) {\r\n if (!isNaN(parseInt(parameter))) {\r\n return;\r\n }\r\n }\r\n throwParameterError(functionName, parameterName, \"Number\");\r\n }\r\n }\r\n\r\n static batchIsEmpty(): Error[] {\r\n return [\r\n new Error(\r\n \"Payload of the batch operation is empty. Please make that you have other operations in between startBatch() and executeBatch() to successfuly build a batch payload.\"\r\n ),\r\n ];\r\n }\r\n\r\n static handleHttpError(parsedError: any, parameters?: any): DynamicsWebApiError {\r\n const error = new Error();\r\n\r\n Object.keys(parsedError).forEach((k) => {\r\n error[k] = parsedError[k];\r\n });\r\n\r\n if (parameters) {\r\n Object.keys(parameters).forEach((k) => {\r\n error[k] = parameters[k];\r\n });\r\n }\r\n\r\n return error;\r\n }\r\n\r\n static boolParameterCheck(parameter: any, functionName: string, parameterName: string): void {\r\n if (typeof parameter != \"boolean\") {\r\n throwParameterError(functionName, parameterName, \"Boolean\");\r\n }\r\n }\r\n\r\n /**\r\n * Private function used to check whether required parameter is a valid GUID\r\n * @param parameter The GUID parameter to check\r\n * @param functionName\r\n * @param parameterName\r\n * @returns\r\n */\r\n static guidParameterCheck(parameter: any, functionName: string, parameterName: string): string {\r\n const match = extractUuid(parameter);\r\n if (!match) throwParameterError(functionName, parameterName, \"GUID String\");\r\n\r\n return match!;\r\n }\r\n\r\n static keyParameterCheck(parameter: any, functionName: string, parameterName: string): string | undefined {\r\n try {\r\n ErrorHelper.stringParameterCheck(parameter, functionName, parameterName);\r\n\r\n //check if the param is a guid\r\n const match = extractUuid(parameter);\r\n if (match) return match;\r\n\r\n //check the alternate key\r\n const alternateKeys = parameter.split(\",\");\r\n\r\n if (alternateKeys.length) {\r\n for (let i = 0; i < alternateKeys.length; i++) {\r\n alternateKeys[i] = alternateKeys[i].trim().replace(/\"/g, \"'\");\r\n /^[\\w\\d\\_]+\\=(.+)$/i.exec(alternateKeys[i])![0];\r\n }\r\n }\r\n\r\n return alternateKeys.join(\",\");\r\n } catch (error) {\r\n throwParameterError(functionName, parameterName, \"String representing GUID or Alternate Key\");\r\n }\r\n }\r\n\r\n static callbackParameterCheck(callbackParameter: () => Promise, functionName: string, parameterName: string): void {\r\n if (typeof callbackParameter != \"function\") {\r\n throwParameterError(functionName, parameterName, \"Function\");\r\n }\r\n }\r\n\r\n static throwBatchIncompatible(functionName: string, isBatch: boolean): void {\r\n if (isBatch) {\r\n isBatch = false;\r\n throw new Error(functionName + \" cannot be used in a BATCH request.\");\r\n }\r\n }\r\n\r\n static throwBatchNotStarted(isBatch: boolean): void {\r\n if (!isBatch) {\r\n throw new Error(\r\n \"Batch operation has not been started. Please call a DynamicsWebApi.startBatch() function prior to calling DynamicsWebApi.executeBatch() to perform a batch request correctly.\"\r\n );\r\n }\r\n }\r\n}\r\n", "class DWA {\r\n\tstatic Prefer = class {\r\n\t\tstatic ReturnRepresentation: string = \"return=representation\";\r\n\t\tstatic Annotations = class {\r\n\t\t\tstatic AssociatedNavigationProperty: string = \"Microsoft.Dynamics.CRM.associatednavigationproperty\";\r\n\t\t\tstatic LookupLogicalName: string = \"Microsoft.Dynamics.CRM.lookuplogicalname\";\r\n\t\t\tstatic All: string = \"*\";\r\n\t\t\tstatic FormattedValue: string = \"OData.Community.Display.V1.FormattedValue\";\r\n\t\t\tstatic FetchXmlPagingCookie: string = \"Microsoft.Dynamics.CRM.fetchxmlpagingcookie\";\r\n\t\t};\r\n\t\tstatic IncludeAnnotations: string = \"odata.include-annotations\";\r\n\t\tstatic get(annotation: string) {\r\n\t\t\treturn `${DWA.Prefer.IncludeAnnotations}=\"${annotation}\"`;\r\n\t\t}\r\n\t};\r\n}\r\n\r\nexport { DWA };\r\n", "\uFEFFexport function dateReviver(key: string, value: any): Date {\r\n\tif (typeof value === \"string\") {\r\n\t\tconst a = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:Z|[-+]\\d{2}:\\d{2})$/.exec(value);\r\n\t\tif (a) {\r\n\t\t\treturn new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));\r\n\t\t}\r\n\t}\r\n\treturn value;\r\n}\r\n", "\uFEFFimport { DWA } from \"../../dwa\";\r\nimport { Utility } from \"../../utils/Utility\";\r\nimport { ErrorHelper, DynamicsWebApiError } from \"../../helpers/ErrorHelper\";\r\nimport { dateReviver } from \"./dateReviver\";\r\nimport { Core } from \"../../types\";\r\nimport { extractUuidFromUrl } from \"../../helpers/Regex\";\r\n\r\nfunction getFormattedKeyValue(keyName: string, value: any): any[] {\r\n let newKey: string | null = null;\r\n if (keyName.indexOf(\"@\") !== -1) {\r\n const format = keyName.split(\"@\");\r\n switch (format[1]) {\r\n case \"odata.context\":\r\n newKey = \"oDataContext\";\r\n break;\r\n case \"odata.count\":\r\n newKey = \"oDataCount\";\r\n value = value != null ? parseInt(value) : 0;\r\n break;\r\n case \"odata.nextLink\":\r\n newKey = \"oDataNextLink\";\r\n break;\r\n case \"odata.deltaLink\":\r\n newKey = \"oDataDeltaLink\";\r\n break;\r\n case DWA.Prefer.Annotations.FormattedValue:\r\n newKey = format[0] + \"_Formatted\";\r\n break;\r\n case DWA.Prefer.Annotations.AssociatedNavigationProperty:\r\n newKey = format[0] + \"_NavigationProperty\";\r\n break;\r\n case DWA.Prefer.Annotations.LookupLogicalName:\r\n newKey = format[0] + \"_LogicalName\";\r\n break;\r\n }\r\n }\r\n\r\n return [newKey, value];\r\n}\r\n\r\n/**\r\n *\r\n * @param {any} object - parsed JSON object\r\n * @param {any} parseParams - parameters for parsing the response\r\n * @returns {any} parsed batch response\r\n */\r\nfunction parseData(object: any, parseParams?: any): any {\r\n if (parseParams) {\r\n if (parseParams.isRef && object[\"@odata.id\"] != null) {\r\n return Utility.convertToReferenceObject(object);\r\n }\r\n\r\n if (parseParams.toCount) {\r\n return getFormattedKeyValue(\"@odata.count\", object[\"@odata.count\"])[1] || 0;\r\n }\r\n }\r\n\r\n const keys = Object.keys(object);\r\n\r\n for (let i = 0; i < keys.length; i++) {\r\n const currentKey = keys[i];\r\n\r\n if (object[currentKey] != null) {\r\n if (object[currentKey].constructor === Array) {\r\n for (var j = 0; j < object[currentKey].length; j++) {\r\n object[currentKey][j] = parseData(object[currentKey][j]);\r\n }\r\n } else if (typeof object[currentKey] === \"object\") {\r\n parseData(object[currentKey]);\r\n }\r\n }\r\n\r\n //parse formatted values\r\n let formattedKeyValue = getFormattedKeyValue(currentKey, object[currentKey]);\r\n if (formattedKeyValue[0]) {\r\n object[formattedKeyValue[0]] = formattedKeyValue[1];\r\n }\r\n\r\n //parse aliased values\r\n if (currentKey.indexOf(\"_x002e_\") !== -1) {\r\n const aliasKeys = currentKey.split(\"_x002e_\");\r\n\r\n if (!object.hasOwnProperty(aliasKeys[0])) {\r\n object[aliasKeys[0]] = { _dwaType: \"alias\" };\r\n }\r\n //throw an error if there is already a property which is not an 'alias'\r\n else if (\r\n typeof object[aliasKeys[0]] !== \"object\" ||\r\n (typeof object[aliasKeys[0]] === \"object\" && !object[aliasKeys[0]].hasOwnProperty(\"_dwaType\"))\r\n ) {\r\n throw new Error(\"The alias name of the linked entity must be unique!\");\r\n }\r\n\r\n object[aliasKeys[0]][aliasKeys[1]] = object[currentKey];\r\n\r\n //aliases also contain formatted values\r\n formattedKeyValue = getFormattedKeyValue(aliasKeys[1], object[currentKey]);\r\n if (formattedKeyValue[0]) {\r\n object[aliasKeys[0]][formattedKeyValue[0]] = formattedKeyValue[1];\r\n }\r\n }\r\n }\r\n\r\n if (parseParams) {\r\n if (parseParams.hasOwnProperty(\"pageNumber\") && object[\"@\" + DWA.Prefer.Annotations.FetchXmlPagingCookie] != null) {\r\n object.PagingInfo = Utility.getFetchXmlPagingCookie(object[\"@\" + DWA.Prefer.Annotations.FetchXmlPagingCookie], parseParams.pageNumber);\r\n }\r\n }\r\n\r\n return object;\r\n}\r\n\r\nconst responseHeaderRegex = /^([^()<>@,;:\\\\\"\\/[\\]?={} \\t]+)\\s?:\\s?(.*)/;\r\n\r\n//partially taken from http://olingo.apache.org/doc/javascript/apidoc/batch.js.html\r\nfunction parseBatchHeaders(text: string): any {\r\n const ctx = { position: 0 };\r\n const headers = {};\r\n let parts;\r\n let line;\r\n let pos;\r\n\r\n do {\r\n pos = ctx.position;\r\n line = readLine(text, ctx);\r\n parts = responseHeaderRegex.exec(line);\r\n if (parts !== null) {\r\n headers[parts[1].toLowerCase()] = parts[2];\r\n } else {\r\n // Whatever was found is not a header, so reset the context position.\r\n ctx.position = pos;\r\n }\r\n } while (line && parts);\r\n\r\n return headers;\r\n}\r\n\r\n//partially taken from http://olingo.apache.org/doc/javascript/apidoc/batch.js.html\r\nfunction readLine(text: string, ctx: { position: number }): string | null {\r\n return readTo(text, ctx, \"\\r\\n\");\r\n}\r\n\r\n//partially taken from http://olingo.apache.org/doc/javascript/apidoc/batch.js.html\r\nfunction readTo(text: string, ctx: { position: number }, str: string): string | null {\r\n const start = ctx.position || 0;\r\n let end = text.length;\r\n if (str) {\r\n end = text.indexOf(str, start);\r\n if (end === -1) {\r\n return null;\r\n }\r\n ctx.position = end + str.length;\r\n } else {\r\n ctx.position = end;\r\n }\r\n\r\n return text.substring(start, end);\r\n}\r\n\r\n//partially taken from https://github.com/emiltholin/google-api-batch-utils\r\n/**\r\n *\r\n * @param {string} response - response that needs to be parsed\r\n * @param {Array} parseParams - parameters for parsing the response\r\n * @param {Number} [requestNumber] - number of the request\r\n * @returns {any} parsed batch response\r\n */\r\nfunction parseBatchResponse(response: string, parseParams: any, requestNumber: number = 0): (string | undefined | DynamicsWebApiError | Number)[] {\r\n // Not the same delimiter in the response as we specify ourselves in the request,\r\n // so we have to extract it.\r\n const delimiter = response.substr(0, response.indexOf(\"\\r\\n\"));\r\n const batchResponseParts = response.split(delimiter);\r\n // The first part will always be an empty string. Just remove it.\r\n batchResponseParts.shift();\r\n // The last part will be the \"--\". Just remove it.\r\n batchResponseParts.pop();\r\n\r\n let result: (string | undefined | DynamicsWebApiError | Number)[] = [];\r\n for (let i = 0; i < batchResponseParts.length; i++) {\r\n let batchResponse = batchResponseParts[i];\r\n if (batchResponse.indexOf(\"--changesetresponse_\") > -1) {\r\n batchResponse = batchResponse.trim();\r\n const batchToProcess = batchResponse.substring(batchResponse.indexOf(\"\\r\\n\") + 1).trim();\r\n\r\n result = result.concat(parseBatchResponse(batchToProcess, parseParams, requestNumber));\r\n } else {\r\n //check http status\r\n const httpStatusReg = /HTTP\\/?\\s*[\\d.]*\\s+(\\d{3})\\s+([\\w\\s]*)$/gm.exec(batchResponse);\r\n //todo: add error handler for httpStatus and httpStatusMessage; remove \"!\" operator\r\n const httpStatus = parseInt(httpStatusReg![1]);\r\n const httpStatusMessage = httpStatusReg![2].trim();\r\n\r\n const responseData = batchResponse.substring(batchResponse.indexOf(\"{\"), batchResponse.lastIndexOf(\"}\") + 1);\r\n\r\n if (!responseData) {\r\n if (/Content-Type: text\\/plain/i.test(batchResponse)) {\r\n const plainContentReg = /\\w+$/gi.exec(batchResponse.trim());\r\n const plainContent = plainContentReg && plainContentReg.length ? plainContentReg[0] : undefined;\r\n\r\n //check if a plain content is a number or not\r\n result.push(isNaN(Number(plainContent)) ? plainContent : Number(plainContent));\r\n } else {\r\n if (parseParams.length && parseParams[requestNumber] && parseParams[requestNumber].hasOwnProperty(\"valueIfEmpty\")) {\r\n result.push(parseParams[requestNumber].valueIfEmpty);\r\n } else {\r\n const entityUrl = /OData-EntityId.+/i.exec(batchResponse);\r\n\r\n if (entityUrl && entityUrl.length) {\r\n const guidResult = extractUuidFromUrl(entityUrl[0]);\r\n result.push(guidResult ? guidResult : undefined);\r\n } else {\r\n result.push(undefined);\r\n }\r\n }\r\n }\r\n } else {\r\n const parsedResponse = parseData(JSON.parse(responseData, dateReviver), parseParams[requestNumber]);\r\n\r\n if (httpStatus >= 400) {\r\n const responseHeaders = parseBatchHeaders(\r\n //todo: add error handler for httpStatusReg; remove \"!\" operator\r\n batchResponse.substring(batchResponse.indexOf(httpStatusReg![0]) + httpStatusReg![0].length + 1, batchResponse.indexOf(\"{\"))\r\n );\r\n\r\n result.push(\r\n ErrorHelper.handleHttpError(parsedResponse, {\r\n status: httpStatus,\r\n statusText: httpStatusMessage,\r\n statusMessage: httpStatusMessage,\r\n headers: responseHeaders,\r\n })\r\n );\r\n } else {\r\n result.push(parsedResponse);\r\n }\r\n }\r\n }\r\n\r\n requestNumber++;\r\n }\r\n\r\n return result;\r\n}\r\n\r\nfunction base64ToString(base64: string): string {\r\n return global.DWA_BROWSER ? global.window.atob(base64) : Buffer.from(base64, \"base64\").toString(\"binary\");\r\n}\r\n\r\nfunction parseFileResponse(response: any, responseHeaders: any, parseParams: any): Core.FileParseResult {\r\n let data = response;\r\n\r\n if (parseParams.hasOwnProperty(\"parse\")) {\r\n data = JSON.parse(data).value;\r\n data = base64ToString(data);\r\n }\r\n\r\n var parseResult: Core.FileParseResult = {\r\n value: data,\r\n };\r\n\r\n if (responseHeaders[\"x-ms-file-name\"]) parseResult.fileName = responseHeaders[\"x-ms-file-name\"];\r\n\r\n if (responseHeaders[\"x-ms-file-size\"]) parseResult.fileSize = parseInt(responseHeaders[\"x-ms-file-size\"]);\r\n\r\n if (hasHeader(responseHeaders, \"Location\")) parseResult.location = getHeader(responseHeaders, \"Location\");\r\n\r\n return parseResult;\r\n}\r\n\r\nfunction hasHeader(headers: any, name: string): boolean {\r\n return headers.hasOwnProperty(name) || headers.hasOwnProperty(name.toLowerCase());\r\n}\r\n\r\nfunction getHeader(headers: any, name: string): string {\r\n if (headers[name]) return headers[name];\r\n\r\n return headers[name.toLowerCase()];\r\n}\r\n\r\n/**\r\n *\r\n * @param {string} response - response that needs to be parsed\r\n * @param {Array} responseHeaders - response headers\r\n * @param {Array} parseParams - parameters for parsing the response\r\n * @returns {any} parsed response\r\n */\r\nexport function parseResponse(response: string, responseHeaders: any, parseParams: any[]): any {\r\n let parseResult: any = undefined;\r\n if (response.length) {\r\n if (response.indexOf(\"--batchresponse_\") > -1) {\r\n const batch = parseBatchResponse(response, parseParams);\r\n\r\n parseResult = parseParams.length === 1 && parseParams[0].convertedToBatch ? batch[0] : batch;\r\n } else {\r\n if (hasHeader(responseHeaders, \"Content-Disposition\")) {\r\n parseResult = parseFileResponse(response, responseHeaders, parseParams[0]);\r\n } else {\r\n const contentType = getHeader(responseHeaders, \"Content-Type\");\r\n if (contentType.startsWith(\"application/json\")) {\r\n parseResult = parseData(JSON.parse(response, dateReviver), parseParams[0]);\r\n } else {\r\n parseResult = isNaN(Number(response)) ? response : Number(response);\r\n }\r\n }\r\n }\r\n } else {\r\n if (parseParams.length && parseParams[0].hasOwnProperty(\"valueIfEmpty\")) {\r\n parseResult = parseParams[0].valueIfEmpty;\r\n } else if (hasHeader(responseHeaders, \"OData-EntityId\")) {\r\n const entityUrl = getHeader(responseHeaders, \"OData-EntityId\");\r\n\r\n const guidResult = extractUuidFromUrl(entityUrl);\r\n\r\n if (guidResult) {\r\n parseResult = guidResult;\r\n }\r\n } else if (hasHeader(responseHeaders, \"Location\")) {\r\n parseResult = {\r\n location: getHeader(responseHeaders, \"Location\"),\r\n };\r\n\r\n if (responseHeaders[\"x-ms-chunk-size\"]) parseResult.chunkSize = parseInt(responseHeaders[\"x-ms-chunk-size\"]);\r\n }\r\n }\r\n\r\n return parseResult;\r\n}\r\n", "\uFEFFexport function parseResponseHeaders(headerStr: string): any {\r\n\tconst headers = {};\r\n\tif (!headerStr) {\r\n\t\treturn headers;\r\n\t}\r\n\tconst headerPairs = headerStr.split(\"\\u000d\\u000a\");\r\n\tfor (let i = 0, ilen = headerPairs.length; i < ilen; i++) {\r\n\t\tconst headerPair = headerPairs[i];\r\n\t\tconst index = headerPair.indexOf(\"\\u003a\\u0020\");\r\n\t\tif (index > 0) {\r\n\t\t\theaders[headerPair.substring(0, index)] = headerPair.substring(index + 2);\r\n\t\t}\r\n\t}\r\n\treturn headers;\r\n}\r\n", "\uFEFFimport { Core } from \"../types\";\r\nimport { ErrorHelper } from \"./../helpers/ErrorHelper\";\r\nimport { parseResponse } from \"./helpers/parseResponse\";\r\nimport { parseResponseHeaders } from \"./helpers/parseResponseHeaders\";\r\n\r\nexport function executeRequest(options: Core.RequestOptions): Promise {\r\n return new Promise((resolve, reject) => {\r\n _executeRequest(options, resolve, reject);\r\n });\r\n}\r\n\r\nfunction _executeRequest(\r\n options: Core.RequestOptions,\r\n successCallback: (response: Core.WebApiResponse) => void,\r\n errorCallback: (error: Core.WebApiErrorResponse | Core.WebApiErrorResponse[]) => void\r\n) {\r\n const data = options.data;\r\n const additionalHeaders = options.additionalHeaders;\r\n const responseParams = options.responseParams;\r\n const signal = options.abortSignal;\r\n\r\n if (signal?.aborted) {\r\n errorCallback(\r\n ErrorHelper.handleHttpError({\r\n name: \"AbortError\",\r\n code: 20,\r\n message: \"The user aborted a request.\",\r\n })\r\n );\r\n\r\n return;\r\n }\r\n\r\n let request = new XMLHttpRequest();\r\n request.open(options.method, options.uri, options.isAsync || false);\r\n\r\n //set additional headers\r\n for (let key in additionalHeaders) {\r\n request.setRequestHeader(key, additionalHeaders[key]);\r\n }\r\n\r\n request.onreadystatechange = function () {\r\n if (request.readyState === 4) {\r\n if (signal) signal.removeEventListener(\"abort\", abort);\r\n\r\n switch (request.status) {\r\n case 200: // Success with content returned in response body.\r\n case 201: // Success with content returned in response body.\r\n case 204: // Success with no content returned in response body.\r\n case 206: // Success with partial content.\r\n case 304: {\r\n // Success with Not Modified\r\n const responseHeaders = parseResponseHeaders(request.getAllResponseHeaders());\r\n const responseData = parseResponse(request.responseText, responseHeaders, responseParams[options.requestId]);\r\n\r\n const response = {\r\n data: responseData,\r\n headers: responseHeaders,\r\n status: request.status,\r\n };\r\n\r\n request = null as any;\r\n\r\n successCallback(response);\r\n break;\r\n }\r\n case 0:\r\n break; //response will be handled by onerror\r\n default:\r\n if (!request) break; //response was handled somewhere else\r\n\r\n // All other statuses are error cases.\r\n let error;\r\n let headers;\r\n try {\r\n headers = parseResponseHeaders(request.getAllResponseHeaders());\r\n const errorParsed = parseResponse(request.responseText, headers, responseParams[options.requestId]);\r\n\r\n if (Array.isArray(errorParsed)) {\r\n errorCallback(errorParsed);\r\n break;\r\n }\r\n\r\n error = errorParsed.error;\r\n } catch (e) {\r\n if (request.response.length > 0) {\r\n error = { message: request.response };\r\n } else {\r\n error = { message: \"Unexpected Error\" };\r\n }\r\n }\r\n\r\n const errorParameters = {\r\n status: request.status,\r\n statusText: request.statusText,\r\n headers: headers,\r\n };\r\n\r\n request = null as any;\r\n\r\n errorCallback(ErrorHelper.handleHttpError(error, errorParameters));\r\n\r\n break;\r\n }\r\n }\r\n };\r\n\r\n if (options.timeout) {\r\n request.timeout = options.timeout;\r\n }\r\n\r\n request.onerror = function () {\r\n const headers = parseResponseHeaders(request.getAllResponseHeaders());\r\n errorCallback(\r\n ErrorHelper.handleHttpError({\r\n status: request.status,\r\n statusText: request.statusText,\r\n message: request.responseText || \"Network Error\",\r\n headers: headers,\r\n })\r\n );\r\n request = null as any;\r\n };\r\n\r\n request.ontimeout = function () {\r\n const headers = parseResponseHeaders(request.getAllResponseHeaders());\r\n errorCallback(\r\n ErrorHelper.handleHttpError({\r\n name: \"TimeoutError\",\r\n status: request.status,\r\n statusText: request.statusText,\r\n message: request.responseText || \"Request Timed Out\",\r\n headers: headers,\r\n })\r\n );\r\n request = null as any;\r\n };\r\n\r\n //browser abort\r\n request.onabort = function () {\r\n if (!request) return;\r\n\r\n const headers = parseResponseHeaders(request.getAllResponseHeaders());\r\n errorCallback(\r\n ErrorHelper.handleHttpError({\r\n status: request.status,\r\n statusText: request.statusText,\r\n message: \"Request aborted\",\r\n headers: headers,\r\n })\r\n );\r\n request = null as any;\r\n };\r\n\r\n //manual abort/cancellation\r\n const abort = () => {\r\n if (!request) return;\r\n\r\n const headers = parseResponseHeaders(request.getAllResponseHeaders());\r\n\r\n errorCallback(\r\n ErrorHelper.handleHttpError({\r\n name: \"AbortError\",\r\n code: 20,\r\n status: request.status,\r\n statusText: request.statusText,\r\n message: \"The user aborted a request.\",\r\n headers: headers,\r\n })\r\n );\r\n\r\n request.abort();\r\n\r\n request = null as any;\r\n };\r\n\r\n if (signal) {\r\n signal.addEventListener(\"abort\", abort);\r\n }\r\n\r\n data ? request.send(data) : request.send();\r\n\r\n //called for testing\r\n if (XhrWrapper.afterSendEvent) XhrWrapper.afterSendEvent();\r\n}\r\n\r\n/**\r\n * Sends a request to given URL with given parameters\r\n */\r\nexport class XhrWrapper {\r\n //for testing\r\n static afterSendEvent: () => void;\r\n}\r\n", "import { Utility } from \"./Utility\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport { ApiConfig, Config } from \"../dynamics-web-api\";\r\n\r\ntype ApiType = \"dataApi\" | \"searchApi\";\r\n\r\nexport interface InternalApiConfig extends ApiConfig {\r\n url: string;\r\n}\r\n\r\nexport interface InternalConfig extends Config {\r\n dataApi: InternalApiConfig;\r\n searchApi: InternalApiConfig;\r\n}\r\n\r\nconst getApiUrl = (serverUrl: string | undefined | null, apiConfig: ApiConfig): string => {\r\n if (Utility.isRunningWithinPortals()) {\r\n return new URL(\"_api\", global.window.location.origin).toString() + \"/\";\r\n } else {\r\n if (!serverUrl) serverUrl = Utility.getClientUrl();\r\n return new URL(`api/${apiConfig.path}/v${apiConfig.version}`, serverUrl).toString() + \"/\";\r\n }\r\n};\r\n\r\nconst mergeApiConfigs = (apiConfig: ApiConfig | undefined, apiType: ApiType, internalConfig: InternalConfig): void => {\r\n const internalApiConfig = internalConfig[apiType] as InternalApiConfig;\r\n\r\n if (apiConfig?.version) {\r\n ErrorHelper.stringParameterCheck(apiConfig.version, \"DynamicsWebApi.setConfig\", `config.${apiType}.version`);\r\n internalApiConfig.version = apiConfig.version;\r\n }\r\n\r\n if (apiConfig?.path) {\r\n ErrorHelper.stringParameterCheck(apiConfig.path, \"DynamicsWebApi.setConfig\", `config.${apiType}.path`);\r\n internalApiConfig.path = apiConfig.path;\r\n }\r\n\r\n internalApiConfig.url = getApiUrl(internalConfig.serverUrl, internalApiConfig);\r\n};\r\n\r\nexport class ConfigurationUtility {\r\n static mergeApiConfigs = mergeApiConfigs;\r\n\r\n static merge(internalConfig: InternalConfig, config?: Config): void {\r\n if (config?.serverUrl) {\r\n ErrorHelper.stringParameterCheck(config.serverUrl, \"DynamicsWebApi.setConfig\", \"config.serverUrl\");\r\n internalConfig.serverUrl = config.serverUrl;\r\n }\r\n\r\n mergeApiConfigs(config?.dataApi, \"dataApi\", internalConfig);\r\n mergeApiConfigs(config?.searchApi, \"searchApi\", internalConfig);\r\n\r\n if (config?.impersonate) {\r\n internalConfig.impersonate = ErrorHelper.guidParameterCheck(config.impersonate, \"DynamicsWebApi.setConfig\", \"config.impersonate\");\r\n }\r\n\r\n if (config?.impersonateAAD) {\r\n internalConfig.impersonateAAD = ErrorHelper.guidParameterCheck(config.impersonateAAD, \"DynamicsWebApi.setConfig\", \"config.impersonateAAD\");\r\n }\r\n\r\n if (config?.onTokenRefresh) {\r\n ErrorHelper.callbackParameterCheck(config.onTokenRefresh, \"DynamicsWebApi.setConfig\", \"config.onTokenRefresh\");\r\n internalConfig.onTokenRefresh = config.onTokenRefresh;\r\n }\r\n\r\n if (config?.includeAnnotations) {\r\n ErrorHelper.stringParameterCheck(config.includeAnnotations, \"DynamicsWebApi.setConfig\", \"config.includeAnnotations\");\r\n internalConfig.includeAnnotations = config.includeAnnotations;\r\n }\r\n\r\n if (config?.timeout) {\r\n ErrorHelper.numberParameterCheck(config.timeout, \"DynamicsWebApi.setConfig\", \"config.timeout\");\r\n internalConfig.timeout = config.timeout;\r\n }\r\n\r\n if (config?.maxPageSize) {\r\n ErrorHelper.numberParameterCheck(config.maxPageSize, \"DynamicsWebApi.setConfig\", \"config.maxPageSize\");\r\n internalConfig.maxPageSize = config.maxPageSize;\r\n }\r\n\r\n if (config?.returnRepresentation) {\r\n ErrorHelper.boolParameterCheck(config.returnRepresentation, \"DynamicsWebApi.setConfig\", \"config.returnRepresentation\");\r\n internalConfig.returnRepresentation = config.returnRepresentation;\r\n }\r\n\r\n if (config?.useEntityNames) {\r\n ErrorHelper.boolParameterCheck(config.useEntityNames, \"DynamicsWebApi.setConfig\", \"config.useEntityNames\");\r\n internalConfig.useEntityNames = config.useEntityNames;\r\n }\r\n\r\n if (config?.headers) {\r\n internalConfig.headers = config.headers;\r\n }\r\n\r\n if (!global.DWA_BROWSER && config?.proxy) {\r\n ErrorHelper.parameterCheck(config.proxy, \"DynamicsWebApi.setConfig\", \"config.proxy\");\r\n\r\n if (config.proxy.url) {\r\n ErrorHelper.stringParameterCheck(config.proxy.url, \"DynamicsWebApi.setConfig\", \"config.proxy.url\");\r\n\r\n if (config.proxy.auth) {\r\n ErrorHelper.parameterCheck(config.proxy.auth, \"DynamicsWebApi.setConfig\", \"config.proxy.auth\");\r\n ErrorHelper.stringParameterCheck(config.proxy.auth.username, \"DynamicsWebApi.setConfig\", \"config.proxy.auth.username\");\r\n ErrorHelper.stringParameterCheck(config.proxy.auth.password, \"DynamicsWebApi.setConfig\", \"config.proxy.auth.password\");\r\n }\r\n }\r\n\r\n internalConfig.proxy = config.proxy;\r\n }\r\n }\r\n\r\n static default(): InternalConfig {\r\n return {\r\n serverUrl: null,\r\n impersonate: null,\r\n impersonateAAD: null,\r\n onTokenRefresh: null,\r\n includeAnnotations: null,\r\n maxPageSize: null,\r\n returnRepresentation: null,\r\n proxy: null,\r\n dataApi: {\r\n path: \"data\",\r\n version: \"9.2\",\r\n url: \"\"\r\n },\r\n searchApi: {\r\n path: \"search\",\r\n version: \"1.0\",\r\n url: \"\"\r\n },\r\n };\r\n }\r\n}\r\n", "\uFEFFimport { ConfigurationUtility } from \"./utils/Config\";\r\nimport { Utility } from \"./utils/Utility\";\r\nimport { ErrorHelper } from \"./helpers/ErrorHelper\";\r\nimport { RequestClient } from \"./client/RequestClient\";\r\nimport type { Core } from \"./types\";\r\n\r\n/**\r\n * Microsoft Dynamics CRM Web API helper library written in JavaScript.\r\n * It is compatible with: Dynamics 365 (online), Dynamics 365 (on-premise), Dynamics CRM 2016, Dynamics CRM Online.\r\n */\r\nexport class DynamicsWebApi {\r\n private _config = ConfigurationUtility.default();\r\n private _isBatch = false;\r\n private _batchRequestId: string | null = null;\r\n\r\n /**\r\n * Initializes a new instance of DynamicsWebApi\r\n * @param config - Configuration object\r\n */\r\n constructor(config?: Config) {\r\n ConfigurationUtility.merge(this._config, config);\r\n }\r\n\r\n /**\r\n\t * Merges provided configuration properties with an existing one.\r\n\t *\r\n\t * @param {DynamicsWebApi.Config} config - Configuration\r\n\t * @example\r\n\t dynamicsWebApi.setConfig({ serverUrl: 'https://contoso.api.crm.dynamics.com/' });\r\n\t */\r\n setConfig = (config: Config) => ConfigurationUtility.merge(this._config, config);\r\n\r\n private _makeRequest = async (request: Core.InternalRequest): Promise => {\r\n request.isBatch = this._isBatch;\r\n if (this._batchRequestId) request.requestId = this._batchRequestId;\r\n return RequestClient.makeRequest(request, this._config);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to create a new record.\r\n *\r\n * @param {DWARequest} request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n * @example\r\n *const lead = {\r\n * subject: \"Test WebAPI\",\r\n * firstname: \"Test\",\r\n * lastname: \"WebAPI\",\r\n * jobtitle: \"Title\"\r\n *};\r\n *\r\n *const request = {\r\n * data: lead,\r\n * collection: \"leads\",\r\n * returnRepresentation: true\r\n *}\r\n *\r\n *const response = await dynamicsWebApi.create(request);\r\n *\r\n */\r\n create = async (request: CreateRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.create\", \"request\");\r\n\r\n let internalRequest: Core.InternalRequest;\r\n\r\n if (!(request).functionName) {\r\n internalRequest = Utility.copyRequest(request);\r\n internalRequest.functionName = \"create\";\r\n } else internalRequest = request;\r\n\r\n internalRequest.method = \"POST\";\r\n\r\n const response = await this._makeRequest(internalRequest);\r\n\r\n return response?.data;\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve a record.\r\n *\r\n * @param {DWARequest} request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n * @example\r\n *const request = {\r\n * key: '7d577253-3ef0-4a0a-bb7f-8335c2596e70',\r\n * collection: \"leads\",\r\n * select: [\"fullname\", \"subject\"],\r\n * ifnonematch: 'W/\"468026\"',\r\n * includeAnnotations: \"OData.Community.Display.V1.FormattedValue\"\r\n *};\r\n *\r\n *const response = await dynamicsWebApi.retrieve(request);\r\n */\r\n retrieve = async (request: RetrieveRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.retrieve\", \"request\");\r\n\r\n let internalRequest: Core.InternalRequest;\r\n\r\n if (!(request).functionName) {\r\n internalRequest = Utility.copyRequest(request);\r\n internalRequest.functionName = \"retrieve\";\r\n } else internalRequest = request;\r\n\r\n internalRequest.method = \"GET\";\r\n internalRequest.responseParameters = {\r\n isRef: internalRequest.select?.length === 1 && internalRequest.select[0].endsWith(\"/$ref\"),\r\n };\r\n\r\n const response = await this._makeRequest(internalRequest);\r\n return response?.data;\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to update a record.\r\n *\r\n * @param {DWARequest} request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n update = async (request: UpdateRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.update\", \"request\");\r\n\r\n let internalRequest: Core.InternalRequest;\r\n\r\n if (!(request).functionName) {\r\n internalRequest = Utility.copyRequest(request);\r\n internalRequest.functionName = \"update\";\r\n } else internalRequest = request;\r\n\r\n //Metadata definitions, cannot be updated using \"PATCH\" method\r\n if (!internalRequest.method)\r\n internalRequest.method = /EntityDefinitions|RelationshipDefinitions|GlobalOptionSetDefinitions/.test(internalRequest.collection || \"\")\r\n ? \"PUT\"\r\n : \"PATCH\";\r\n\r\n internalRequest.responseParameters = { valueIfEmpty: true };\r\n\r\n if (internalRequest.ifmatch == null) {\r\n internalRequest.ifmatch = \"*\"; //to prevent upsert\r\n }\r\n\r\n //copy locally\r\n const ifmatch = internalRequest.ifmatch;\r\n\r\n try {\r\n const response = await this._makeRequest(internalRequest);\r\n return response?.data;\r\n } catch (error: any) {\r\n if (ifmatch && error.status === 412) {\r\n //precondition failed - not updated\r\n return false; //todo: check this\r\n }\r\n //rethrow error otherwise\r\n throw error;\r\n }\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to update a single value in the record.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n updateSingleProperty = async (request: UpdateSinglePropertyRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.updateSingleProperty\", \"request\");\r\n ErrorHelper.parameterCheck(request.fieldValuePair, \"DynamicsWebApi.updateSingleProperty\", \"request.fieldValuePair\");\r\n\r\n var field = Object.keys(request.fieldValuePair)[0];\r\n var fieldValue = request.fieldValuePair[field];\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.navigationProperty = field;\r\n internalRequest.data = { value: fieldValue };\r\n internalRequest.functionName = \"updateSingleProperty\";\r\n internalRequest.method = \"PUT\";\r\n\r\n delete internalRequest[\"fieldValuePair\"];\r\n\r\n const response = await this._makeRequest(internalRequest);\r\n return response?.data;\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to delete a record.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n deleteRecord = async (request: DeleteRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.deleteRecord\", \"request\");\r\n\r\n let internalRequest: Core.InternalRequest;\r\n\r\n if (!(request).functionName) {\r\n internalRequest = Utility.copyRequest(request);\r\n internalRequest.functionName = \"deleteRecord\";\r\n } else internalRequest = request;\r\n\r\n internalRequest.method = \"DELETE\";\r\n internalRequest.responseParameters = { valueIfEmpty: true };\r\n\r\n //copy locally\r\n const ifmatch = internalRequest.ifmatch;\r\n\r\n try {\r\n const response = await this._makeRequest(internalRequest);\r\n return response?.data;\r\n } catch (error: any) {\r\n if (ifmatch && error.status === 412) {\r\n //precondition failed - not updated\r\n return false; //todo: check this\r\n }\r\n //rethrow error otherwise\r\n throw error;\r\n }\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to upsert a record.\r\n *\r\n * @param {DWARequest} request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n upsert = async (request: UpsertRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.upsert\", \"request\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.method = \"PATCH\";\r\n internalRequest.functionName = \"upsert\";\r\n\r\n //copy locally\r\n const ifnonematch = internalRequest.ifnonematch;\r\n const ifmatch = internalRequest.ifmatch;\r\n try {\r\n const response = await this._makeRequest(internalRequest);\r\n return response?.data;\r\n } catch (error: any) {\r\n if (ifnonematch && error.status === 412) {\r\n //if prevent update\r\n return null; //todo: check this\r\n } else if (ifmatch && error.status === 404) {\r\n //if prevent create\r\n return null; //todo: check this\r\n }\r\n //rethrow error otherwise\r\n throw error;\r\n }\r\n };\r\n\r\n private _uploadFileChunk = async (request: Core.InternalRequest, fileBytes: Uint8Array | Buffer, chunkSize: number, offset: number = 0): Promise => {\r\n // offset = offset || 0;\r\n Utility.setFileChunk(request, fileBytes, chunkSize, offset);\r\n\r\n await this._makeRequest(request);\r\n\r\n offset += chunkSize;\r\n if (offset <= fileBytes.length) {\r\n return this._uploadFileChunk(request, fileBytes, chunkSize, offset);\r\n }\r\n };\r\n\r\n /**\r\n * Upload file to a File Attribute\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n */\r\n uploadFile = async (request: UploadRequest): Promise => {\r\n ErrorHelper.throwBatchIncompatible(\"DynamicsWebApi.uploadFile\", this._isBatch);\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.uploadFile\", \"request\");\r\n\r\n const internalRequest = Utility.copyRequest(request, [\"data\"]);\r\n internalRequest.method = \"PATCH\";\r\n internalRequest.functionName = \"uploadFile\";\r\n internalRequest.transferMode = \"chunked\";\r\n\r\n const response = await this._makeRequest(internalRequest);\r\n\r\n internalRequest.url = response?.data.location;\r\n delete internalRequest.transferMode;\r\n delete internalRequest.fieldName;\r\n delete internalRequest.fileName;\r\n return this._uploadFileChunk(internalRequest, request.data, response?.data.chunkSize);\r\n };\r\n\r\n private _downloadFileChunk = async (\r\n request: Core.InternalRequest,\r\n bytesDownloaded: number = 0,\r\n // fileSize: number = 0,\r\n data: string = \"\"\r\n ): Promise => {\r\n // bytesDownloaded = bytesDownloaded || 0;\r\n // fileSize = fileSize || 0;\r\n // data = data || \"\";\r\n\r\n request.range = \"bytes=\" + bytesDownloaded + \"-\" + (bytesDownloaded + Utility.downloadChunkSize - 1);\r\n request.downloadSize = \"full\";\r\n\r\n const response = await this._makeRequest(request);\r\n\r\n request.url = response?.data.location;\r\n data += response?.data.value;\r\n\r\n bytesDownloaded += Utility.downloadChunkSize;\r\n\r\n if (bytesDownloaded <= response?.data.fileSize) {\r\n return this._downloadFileChunk(request, bytesDownloaded, data);\r\n }\r\n\r\n return {\r\n fileName: response?.data.fileName,\r\n fileSize: response?.data.fileSize,\r\n data: Utility.convertToFileBuffer(data),\r\n };\r\n };\r\n\r\n /**\r\n * Download a file from a File Attribute\r\n * @param request - An object that represents all possible options for a current request.\r\n */\r\n downloadFile = (request: DownloadRequest): Promise => {\r\n ErrorHelper.throwBatchIncompatible(\"DynamicsWebApi.downloadFile\", this._isBatch);\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.downloadFile\", \"request\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.method = \"GET\";\r\n internalRequest.functionName = \"downloadFile\";\r\n internalRequest.responseParameters = { parse: true };\r\n\r\n return this._downloadFileChunk(internalRequest);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve records.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @param {string} [nextPageLink] - Use the value of the @odata.nextLink property with a new GET request to return the next page of data. Pass null to retrieveMultipleOptions.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveMultiple = async (request: RetrieveMultipleRequest, nextPageLink?: string): Promise> => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.retrieveMultiple\", \"request\");\r\n\r\n let internalRequest: Core.InternalRequest;\r\n\r\n if (!(request).functionName) {\r\n internalRequest = Utility.copyRequest(request);\r\n internalRequest.functionName = \"retrieveMultiple\";\r\n } else internalRequest = request;\r\n\r\n internalRequest.method = \"GET\";\r\n\r\n if (nextPageLink) {\r\n ErrorHelper.stringParameterCheck(nextPageLink, \"DynamicsWebApi.retrieveMultiple\", \"nextPageLink\");\r\n internalRequest.url = nextPageLink;\r\n }\r\n\r\n const response = await this._makeRequest(internalRequest);\r\n\r\n return response?.data;\r\n };\r\n\r\n private _retrieveAllRequest = async (request: RetrieveMultipleRequest, nextPageLink?: string, records: any[] = []): Promise> => {\r\n const response = await this.retrieveMultiple(request, nextPageLink);\r\n records = records.concat(response.value);\r\n\r\n const pageLink = response.oDataNextLink;\r\n\r\n if (pageLink) {\r\n return this._retrieveAllRequest(request, pageLink, records);\r\n }\r\n\r\n const result: AllResponse = { value: records };\r\n\r\n if (response.oDataDeltaLink) {\r\n result[\"@odata.deltaLink\"] = response.oDataDeltaLink;\r\n result.oDataDeltaLink = response.oDataDeltaLink;\r\n }\r\n\r\n return result;\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve all records.\r\n *\r\n * @param {DWARequest} request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveAll = (request: RetrieveMultipleRequest): Promise> => {\r\n ErrorHelper.throwBatchIncompatible(\"DynamicsWebApi.retrieveAll\", this._isBatch);\r\n return this._retrieveAllRequest(request);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to count records. IMPORTANT! The count value does not represent the total number of entities in the system. It is limited by the maximum number of entities that can be returned. Returns: Number\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n count = async (request: CountRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.count\", \"request\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.method = \"GET\";\r\n internalRequest.functionName = \"count\";\r\n\r\n if (internalRequest.filter?.length) {\r\n internalRequest.count = true;\r\n } else {\r\n internalRequest.navigationProperty = \"$count\";\r\n }\r\n\r\n internalRequest.responseParameters = { toCount: internalRequest.count };\r\n\r\n //if filter has not been specified then simplify the request\r\n const response = await this._makeRequest(internalRequest);\r\n return response?.data;\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to count records. Returns: Number\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n countAll = async (request: CountAllRequest): Promise => {\r\n ErrorHelper.throwBatchIncompatible(\"DynamicsWebApi.countAll\", this._isBatch);\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.countAll\", \"request\");\r\n\r\n const response = await this._retrieveAllRequest(request);\r\n\r\n return response ? (response.value ? response.value.length : 0) : 0;\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to execute FetchXml to retrieve records. Returns: DWA.Types.FetchXmlResponse\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n fetch = async (request: FetchXmlRequest): Promise> => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.fetch\", \"request\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.method = \"GET\";\r\n internalRequest.functionName = \"fetch\";\r\n\r\n ErrorHelper.stringParameterCheck(internalRequest.fetchXml, \"DynamicsWebApi.fetch\", \"request.fetchXml\");\r\n\r\n //only add paging if there is no top\r\n if (internalRequest.fetchXml && !/^(request: FetchAllRequest): Promise> => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.fetchAll\", \"request\");\r\n\r\n const _executeFetchXmlAll = async (request: FetchXmlRequest, records: any[] = []): Promise> => {\r\n // records = records || [];\r\n\r\n const response = await this.fetch(request);\r\n\r\n records = records.concat(response.value);\r\n\r\n if (response.PagingInfo) {\r\n request.pageNumber = response.PagingInfo.nextPage;\r\n request.pagingCookie = response.PagingInfo.cookie;\r\n\r\n return _executeFetchXmlAll(request, records);\r\n }\r\n\r\n return { value: records };\r\n };\r\n\r\n ErrorHelper.throwBatchIncompatible(\"DynamicsWebApi.fetchAll\", this._isBatch);\r\n return _executeFetchXmlAll(request);\r\n };\r\n\r\n /**\r\n * Associate for a collection-valued navigation property. (1:N or N:N)\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n associate = async (request: AssociateRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.associate\", \"request\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.method = \"POST\";\r\n internalRequest.functionName = \"associate\";\r\n\r\n ErrorHelper.stringParameterCheck(request.relatedCollection, \"DynamicsWebApi.associate\", \"request.relatedcollection\");\r\n ErrorHelper.stringParameterCheck(request.relationshipName, \"DynamicsWebApi.associate\", \"request.relationshipName\");\r\n const primaryKey = ErrorHelper.keyParameterCheck(request.primaryKey, \"DynamicsWebApi.associate\", \"request.primaryKey\");\r\n const relatedKey = ErrorHelper.keyParameterCheck(request.relatedKey, \"DynamicsWebApi.associate\", \"request.relatedKey\");\r\n\r\n internalRequest.navigationProperty = request.relationshipName + \"/$ref\";\r\n internalRequest.key = primaryKey;\r\n internalRequest.data = { \"@odata.id\": `${request.relatedCollection}(${relatedKey})` };\r\n\r\n await this._makeRequest(internalRequest);\r\n };\r\n\r\n /**\r\n * Disassociate for a collection-valued navigation property.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n disassociate = async (request: DisassociateRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.disassociate\", \"request\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.method = \"DELETE\";\r\n internalRequest.functionName = \"disassociate\";\r\n\r\n ErrorHelper.stringParameterCheck(request.relationshipName, \"DynamicsWebApi.disassociate\", \"request.relationshipName\");\r\n const primaryKey = ErrorHelper.keyParameterCheck(request.primaryKey, \"DynamicsWebApi.disassociate\", \"request.primaryKey\");\r\n const relatedKey = ErrorHelper.keyParameterCheck(request.relatedKey, \"DynamicsWebApi.disassociate\", \"request.relatedId\");\r\n\r\n internalRequest.key = primaryKey;\r\n internalRequest.navigationProperty = `${request.relationshipName}(${relatedKey})/$ref`;\r\n\r\n await this._makeRequest(internalRequest);\r\n };\r\n\r\n /**\r\n * Associate for a single-valued navigation property. (1:N)\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n associateSingleValued = async (request: AssociateSingleValuedRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.associateSingleValued\", \"request\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.method = \"PUT\";\r\n internalRequest.functionName = \"associateSingleValued\";\r\n\r\n const primaryKey = ErrorHelper.keyParameterCheck(request.primaryKey, \"DynamicsWebApi.associateSingleValued\", \"request.primaryKey\");\r\n const relatedKey = ErrorHelper.keyParameterCheck(request.relatedKey, \"DynamicsWebApi.associateSingleValued\", \"request.relatedKey\");\r\n ErrorHelper.stringParameterCheck(request.navigationProperty, \"DynamicsWebApi.associateSingleValued\", \"request.navigationProperty\");\r\n ErrorHelper.stringParameterCheck(request.relatedCollection, \"DynamicsWebApi.associateSingleValued\", \"request.relatedcollection\");\r\n\r\n internalRequest.navigationProperty += \"/$ref\";\r\n internalRequest.key = primaryKey;\r\n internalRequest.data = { \"@odata.id\": `${request.relatedCollection}(${relatedKey})` };\r\n\r\n await this._makeRequest(internalRequest);\r\n };\r\n\r\n /**\r\n * Removes a reference to an entity for a single-valued navigation property. (1:N)\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n disassociateSingleValued = async (request: DisassociateSingleValuedRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.disassociateSingleValued\", \"request\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.method = \"DELETE\";\r\n internalRequest.functionName = \"disassociateSingleValued\";\r\n\r\n const primaryKey = ErrorHelper.keyParameterCheck(request.primaryKey, \"DynamicsWebApi.disassociateSingleValued\", \"request.primaryKey\");\r\n ErrorHelper.stringParameterCheck(request.navigationProperty, \"DynamicsWebApi.disassociateSingleValued\", \"request.navigationProperty\");\r\n\r\n internalRequest.navigationProperty += \"/$ref\";\r\n internalRequest.key = primaryKey;\r\n\r\n await this._makeRequest(internalRequest);\r\n };\r\n\r\n /**\r\n * Calls a Web API function\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n callFunction: CallFunction = async (request: string | BoundFunctionRequest | UnboundFunctionRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, `DynamicsWebApi.callFunction`, \"request\");\r\n\r\n const getFunctionName = (request: BoundFunctionRequest | UnboundFunctionRequest) => request.name || request.functionName;\r\n\r\n const isObject = typeof request !== \"string\";\r\n const functionName = isObject ? getFunctionName(request) : request;\r\n const parameterName = isObject ? \"request.name\" : \"name\";\r\n const internalRequest: Core.InternalRequest = isObject ? Utility.copyObject(request, [\"name\"]) : { functionName: functionName };\r\n\r\n ErrorHelper.stringParameterCheck(functionName, `DynamicsWebApi.callFunction`, parameterName);\r\n\r\n const functionParameters = Utility.buildFunctionParameters(internalRequest.parameters);\r\n\r\n internalRequest.method = \"GET\";\r\n internalRequest._additionalUrl = functionName + functionParameters.key;\r\n internalRequest.queryParams = functionParameters.queryParams;\r\n internalRequest._isUnboundRequest = !internalRequest.collection;\r\n internalRequest.functionName = \"callFunction\";\r\n\r\n const response = await this._makeRequest(internalRequest);\r\n return response?.data;\r\n };\r\n\r\n /**\r\n * Calls a Web API action\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n callAction: CallAction = async (\r\n request: BoundActionRequest | UnboundActionRequest\r\n ): Promise => {\r\n ErrorHelper.parameterCheck(request, `DynamicsWebApi.callAction`, \"request\");\r\n ErrorHelper.stringParameterCheck(request.actionName, `DynamicsWebApi.callAction`, \"request.actionName\");\r\n\r\n const internalRequest = Utility.copyRequest(request, [\"action\"]);\r\n internalRequest.method = \"POST\";\r\n internalRequest.functionName = \"callAction\";\r\n\r\n internalRequest._additionalUrl = request.actionName;\r\n internalRequest._isUnboundRequest = !internalRequest.collection;\r\n internalRequest.data = request.action;\r\n\r\n const response = await this._makeRequest(internalRequest);\r\n return response?.data;\r\n };\r\n /**\r\n * Sends an asynchronous request to create an entity definition.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n createEntity = (request: CreateEntityRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, `DynamicsWebApi.createEntity`, \"request\");\r\n ErrorHelper.parameterCheck(request.data, \"DynamicsWebApi.createEntity\", \"request.data\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.collection = \"EntityDefinitions\";\r\n internalRequest.functionName = \"createEntity\";\r\n\r\n return this.create(internalRequest);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to update an entity definition.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n updateEntity = (request: UpdateEntityRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.updateEntity\", \"request\");\r\n ErrorHelper.parameterCheck(request.data, \"DynamicsWebApi.updateEntity\", \"request.data\");\r\n ErrorHelper.guidParameterCheck(request.data.MetadataId, \"DynamicsWebApi.updateEntity\", \"request.data.MetadataId\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.collection = \"EntityDefinitions\";\r\n internalRequest.key = internalRequest.data.MetadataId;\r\n internalRequest.functionName = \"updateEntity\";\r\n internalRequest.method = \"PUT\";\r\n\r\n return this.update(internalRequest);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve a specific entity definition.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveEntity = (request: RetrieveEntityRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.retrieveEntity\", \"request\");\r\n ErrorHelper.keyParameterCheck(request.key, \"DynamicsWebApi.retrieveEntity\", \"request.key\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.collection = \"EntityDefinitions\";\r\n internalRequest.functionName = \"retrieveEntity\";\r\n\r\n return this.retrieve(internalRequest);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve entity definitions.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveEntities = (request?: RetrieveEntitiesRequest): Promise> => {\r\n const internalRequest: Core.InternalRequest = !request ? {} : Utility.copyRequest(request);\r\n\r\n internalRequest.collection = \"EntityDefinitions\";\r\n internalRequest.functionName = \"retrieveEntities\";\r\n\r\n return this.retrieveMultiple(internalRequest);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to create an attribute.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n createAttribute = (request: CreateAttributeRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.createAttribute\", \"request\");\r\n ErrorHelper.parameterCheck(request.data, \"DynamicsWebApi.createAttribute\", \"request.data\");\r\n ErrorHelper.keyParameterCheck(request.entityKey, \"DynamicsWebApi.createAttribute\", \"request.entityKey\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.collection = \"EntityDefinitions\";\r\n internalRequest.functionName = \"retrieveEntity\";\r\n internalRequest.navigationProperty = \"Attributes\";\r\n internalRequest.key = request.entityKey;\r\n\r\n return this.create(internalRequest);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to update an attribute.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n updateAttribute = (request: UpdateAttributeRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.updateAttribute\", \"request\");\r\n ErrorHelper.parameterCheck(request.data, \"DynamicsWebApi.updateAttribute\", \"request.data\");\r\n ErrorHelper.keyParameterCheck(request.entityKey, \"DynamicsWebApi.updateAttribute\", \"request.entityKey\");\r\n ErrorHelper.guidParameterCheck(request.data.MetadataId, \"DynamicsWebApi.updateAttribute\", \"request.data.MetadataId\");\r\n\r\n if (request.castType) {\r\n ErrorHelper.stringParameterCheck(request.castType, \"DynamicsWebApi.updateAttribute\", \"request.castType\");\r\n }\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.collection = \"EntityDefinitions\";\r\n internalRequest.navigationProperty = \"Attributes\";\r\n internalRequest.navigationPropertyKey = request.data.MetadataId;\r\n internalRequest.metadataAttributeType = request.castType;\r\n internalRequest.key = request.entityKey;\r\n internalRequest.functionName = \"updateAttribute\";\r\n internalRequest.method = \"PUT\";\r\n\r\n return this.update(internalRequest);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve attribute metadata for a specified entity definition.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveAttributes = (request: RetrieveAttributesRequest): Promise> => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.retrieveAttributes\", \"request\");\r\n ErrorHelper.keyParameterCheck(request.entityKey, \"DynamicsWebApi.retrieveAttributes\", \"request.entityKey\");\r\n\r\n if (request.castType) {\r\n ErrorHelper.stringParameterCheck(request.castType, \"DynamicsWebApi.retrieveAttributes\", \"request.castType\");\r\n }\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.collection = \"EntityDefinitions\";\r\n internalRequest.navigationProperty = \"Attributes\";\r\n internalRequest.metadataAttributeType = request.castType;\r\n internalRequest.key = request.entityKey;\r\n internalRequest.functionName = \"retrieveAttributes\";\r\n\r\n return this.retrieveMultiple(internalRequest);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve a specific attribute metadata for a specified entity definition.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveAttribute = (request: RetrieveAttributeRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.retrieveAttributes\", \"request\");\r\n ErrorHelper.keyParameterCheck(request.entityKey, \"DynamicsWebApi.retrieveAttribute\", \"request.entityKey\");\r\n ErrorHelper.keyParameterCheck(request.attributeKey, \"DynamicsWebApi.retrieveAttribute\", \"request.attributeKey\");\r\n\r\n if (request.castType) {\r\n ErrorHelper.stringParameterCheck(request.castType, \"DynamicsWebApi.retrieveAttribute\", \"request.castType\");\r\n }\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.collection = \"EntityDefinitions\";\r\n internalRequest.navigationProperty = \"Attributes\";\r\n internalRequest.navigationPropertyKey = request.attributeKey;\r\n internalRequest.metadataAttributeType = request.castType;\r\n internalRequest.key = request.entityKey;\r\n internalRequest.functionName = \"retrieveAttribute\";\r\n\r\n return this.retrieve(internalRequest);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to create a relationship definition.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n createRelationship = (request: CreateRelationshipRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.createRelationship\", \"request\");\r\n ErrorHelper.parameterCheck(request.data, \"DynamicsWebApi.createRelationship\", \"request.data\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.collection = \"RelationshipDefinitions\";\r\n internalRequest.functionName = \"createRelationship\";\r\n\r\n return this.create(internalRequest);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to update a relationship definition.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n updateRelationship = (request: UpdateRelationshipRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.updateRelationship\", \"request\");\r\n ErrorHelper.parameterCheck(request.data, \"DynamicsWebApi.updateRelationship\", \"request.data\");\r\n ErrorHelper.guidParameterCheck(request.data.MetadataId, \"DynamicsWebApi.updateRelationship\", \"request.data.MetadataId\");\r\n\r\n if (request.castType) {\r\n ErrorHelper.stringParameterCheck(request.castType, \"DynamicsWebApi.updateRelationship\", \"request.castType\");\r\n }\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.collection = \"RelationshipDefinitions\";\r\n internalRequest.key = request.data.MetadataId;\r\n internalRequest.navigationProperty = request.castType;\r\n internalRequest.functionName = \"updateRelationship\";\r\n internalRequest.method = \"PUT\";\r\n\r\n return this.update(internalRequest);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to delete a relationship definition.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n deleteRelationship = (request: DeleteRelationshipRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.deleteRelationship\", \"request\");\r\n ErrorHelper.keyParameterCheck(request.key, \"DynamicsWebApi.deleteRelationship\", \"request.key\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.collection = \"RelationshipDefinitions\";\r\n internalRequest.functionName = \"deleteRelationship\";\r\n\r\n return this.deleteRecord(internalRequest);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve relationship definitions.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveRelationships = (request?: RetrieveRelationshipsRequest): Promise> => {\r\n const internalRequest: Core.InternalRequest = !request ? {} : Utility.copyRequest(request);\r\n\r\n internalRequest.collection = \"RelationshipDefinitions\";\r\n internalRequest.functionName = \"retrieveRelationships\";\r\n\r\n if (request) {\r\n if (request.castType) {\r\n ErrorHelper.stringParameterCheck(request.castType, \"DynamicsWebApi.retrieveRelationships\", \"request.castType\");\r\n internalRequest.navigationProperty = request.castType;\r\n }\r\n }\r\n\r\n return this.retrieveMultiple(internalRequest);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve a specific relationship definition.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveRelationship = (request: RetrieveRelationshipRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.retrieveRelationship\", \"request\");\r\n ErrorHelper.keyParameterCheck(request.key, \"DynamicsWebApi.retrieveRelationship\", \"request.key\");\r\n\r\n if (request.castType) {\r\n ErrorHelper.stringParameterCheck(request.castType, \"DynamicsWebApi.retrieveRelationship\", \"request.castType\");\r\n }\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.collection = \"RelationshipDefinitions\";\r\n internalRequest.navigationProperty = request.castType;\r\n internalRequest.functionName = \"retrieveRelationship\";\r\n\r\n return this.retrieve(internalRequest);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to create a Global Option Set definition\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n createGlobalOptionSet = (request: CreateGlobalOptionSetRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.createGlobalOptionSet\", \"request\");\r\n ErrorHelper.parameterCheck(request.data, \"DynamicsWebApi.createGlobalOptionSet\", \"request.data\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.collection = \"GlobalOptionSetDefinitions\";\r\n internalRequest.functionName = \"createGlobalOptionSet\";\r\n\r\n return this.create(internalRequest);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to update a Global Option Set.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n updateGlobalOptionSet = (request: UpdateGlobalOptionSetRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.updateGlobalOptionSet\", \"request\");\r\n ErrorHelper.parameterCheck(request.data, \"DynamicsWebApi.updateGlobalOptionSet\", \"request.data\");\r\n ErrorHelper.guidParameterCheck(request.data.MetadataId, \"DynamicsWebApi.updateGlobalOptionSet\", \"request.data.MetadataId\");\r\n\r\n if (request.castType) {\r\n ErrorHelper.stringParameterCheck(request.castType, \"DynamicsWebApi.updateGlobalOptionSet\", \"request.castType\");\r\n }\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.collection = \"GlobalOptionSetDefinitions\";\r\n internalRequest.key = request.data.MetadataId;\r\n internalRequest.functionName = \"updateGlobalOptionSet\";\r\n internalRequest.method = \"PUT\";\r\n\r\n return this.update(internalRequest);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to delete a Global Option Set.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n deleteGlobalOptionSet = (request: DeleteGlobalOptionSetRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.deleteGlobalOptionSet\", \"request\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.collection = \"GlobalOptionSetDefinitions\";\r\n internalRequest.functionName = \"deleteGlobalOptionSet\";\r\n\r\n return this.deleteRecord(internalRequest);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve Global Option Set definitions.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveGlobalOptionSet = (request: RetrieveGlobalOptionSetRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.retrieveGlobalOptionSet\", \"request\");\r\n\r\n if (request.castType) {\r\n ErrorHelper.stringParameterCheck(request.castType, \"DynamicsWebApi.retrieveGlobalOptionSet\", \"request.castType\");\r\n }\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.collection = \"GlobalOptionSetDefinitions\";\r\n internalRequest.navigationProperty = request.castType;\r\n internalRequest.functionName = \"retrieveGlobalOptionSet\";\r\n\r\n return this.retrieve(internalRequest);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve Global Option Set definitions.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveGlobalOptionSets = (request?: RetrieveGlobalOptionSetsRequest): Promise> => {\r\n const internalRequest: Core.InternalRequest = !request ? {} : Utility.copyRequest(request);\r\n\r\n internalRequest.collection = \"GlobalOptionSetDefinitions\";\r\n internalRequest.functionName = \"retrieveGlobalOptionSets\";\r\n\r\n if (request?.castType) {\r\n ErrorHelper.stringParameterCheck(request.castType, \"DynamicsWebApi.retrieveGlobalOptionSets\", \"request.castType\");\r\n internalRequest.navigationProperty = request.castType;\r\n }\r\n\r\n return this.retrieveMultiple(internalRequest);\r\n };\r\n\r\n /**\r\n * Retrieves a CSDL Document Metadata\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} A raw CSDL $metadata document.\r\n */\r\n retrieveCsdlMetadata = async (request?: CsdlMetadataRequest): Promise => {\r\n const internalRequest: Core.InternalRequest = !request ? {} : Utility.copyRequest(request);\r\n\r\n internalRequest.collection = \"$metadata\";\r\n internalRequest.functionName = \"retrieveCsdlMetadata\";\r\n\r\n if (request?.addAnnotations) {\r\n ErrorHelper.boolParameterCheck(request.addAnnotations, \"DynamicsWebApi.retrieveCsdlMetadata\", \"request.addAnnotations\");\r\n internalRequest.includeAnnotations = \"*\";\r\n }\r\n\r\n const response = await this._makeRequest(internalRequest);\r\n return response?.data;\r\n };\r\n\r\n /**\r\n * Provides a search results page.\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise>} Search result\r\n */\r\n search: SearchFunction = async (request: string | SearchRequest): Promise> => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.search\", \"request\");\r\n\r\n const isObject = Utility.isObject(request);\r\n const parameterName = isObject ? \"request.query.search\" : \"term\";\r\n const internalRequest: Core.InternalRequest = isObject ? Utility.copyObject(request) : { query: { search: request as string } };\r\n\r\n ErrorHelper.parameterCheck(internalRequest.query, \"DynamicsWebApi.search\", \"request.query\");\r\n ErrorHelper.stringParameterCheck(internalRequest.query.search, \"DynamicsWebApi.search\", parameterName);\r\n ErrorHelper.maxLengthStringParameterCheck(internalRequest.query.search, \"DynamicsWebApi.search\", parameterName, 100);\r\n\r\n internalRequest.collection = \"query\";\r\n internalRequest.functionName = \"search\";\r\n internalRequest.method = \"POST\";\r\n internalRequest.data = internalRequest.query;\r\n internalRequest.apiConfig = this._config.searchApi;\r\n\r\n delete internalRequest.query;\r\n\r\n const response = await this._makeRequest(internalRequest);\r\n return response?.data;\r\n };\r\n\r\n /**\r\n * Provides suggestions as the user enters text into a form field.\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise>} Suggestions result\r\n */\r\n suggest: SuggestFunction = async (request: string | SuggestRequest): Promise> => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.suggest\", \"request\");\r\n\r\n const isObject = Utility.isObject(request);\r\n const parameterName = isObject ? \"request.query.search\" : \"term\";\r\n const internalRequest: Core.InternalRequest = isObject ? Utility.copyObject(request) : { query: { search: request as string } };\r\n\r\n ErrorHelper.parameterCheck(internalRequest.query, \"DynamicsWebApi.suggest\", \"request.query\");\r\n ErrorHelper.stringParameterCheck(internalRequest.query.search, \"DynamicsWebApi.suggest\", parameterName);\r\n ErrorHelper.maxLengthStringParameterCheck(internalRequest.query.search, \"DynamicsWebApi.suggest\", parameterName, 100);\r\n\r\n internalRequest.functionName = internalRequest.collection = \"suggest\";\r\n internalRequest.method = \"POST\";\r\n internalRequest.data = internalRequest.query;\r\n internalRequest.apiConfig = this._config.searchApi;\r\n\r\n delete internalRequest.query;\r\n\r\n const response = await this._makeRequest(internalRequest);\r\n return response?.data;\r\n };\r\n\r\n /**\r\n * Provides autocompletion of input as the user enters text into a form field.\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} Result of autocomplete\r\n */\r\n autocomplete: AutocompleteFunction = async (request: string | AutocompleteRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.autocomplete\", \"request\");\r\n\r\n const isObject = Utility.isObject(request);\r\n const parameterName = isObject ? \"request.query.search\" : \"term\";\r\n const internalRequest: Core.InternalRequest = isObject ? Utility.copyObject(request) : { query: { search: request as string } };\r\n\r\n if (isObject) ErrorHelper.parameterCheck(internalRequest.query, \"DynamicsWebApi.autocomplete\", \"request.query\");\r\n ErrorHelper.stringParameterCheck(internalRequest.query.search, `DynamicsWebApi.autocomplete`, parameterName);\r\n ErrorHelper.maxLengthStringParameterCheck(internalRequest.query.search, \"DynamicsWebApi.autocomplete\", parameterName, 100);\r\n\r\n internalRequest.functionName = internalRequest.collection = \"autocomplete\";\r\n internalRequest.method = \"POST\";\r\n internalRequest.data = internalRequest.query;\r\n internalRequest.apiConfig = this._config.searchApi;\r\n\r\n delete internalRequest.query;\r\n\r\n const response = await this._makeRequest(internalRequest);\r\n return response?.data;\r\n };\r\n\r\n /**\r\n * Starts/executes a batch request.\r\n */\r\n startBatch = (): void => {\r\n this._isBatch = true;\r\n this._batchRequestId = Utility.generateUUID();\r\n };\r\n\r\n /**\r\n * Executes a batch request. Please call DynamicsWebApi.startBatch() first to start a batch request.\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n executeBatch = async (request?: BatchRequest): Promise => {\r\n ErrorHelper.throwBatchNotStarted(this._isBatch);\r\n\r\n const internalRequest: Core.InternalRequest = !request ? {} : Utility.copyRequest(request);\r\n\r\n internalRequest.collection = \"$batch\";\r\n internalRequest.method = \"POST\";\r\n internalRequest.functionName = \"executeBatch\";\r\n internalRequest.requestId = this._batchRequestId;\r\n\r\n this._batchRequestId = null;\r\n this._isBatch = false;\r\n\r\n const response = await this._makeRequest(internalRequest);\r\n return response?.data;\r\n };\r\n\r\n /**\r\n * Creates a new instance of DynamicsWebApi. If config is not provided, it is copied from a current instance.\r\n *\r\n * @param {Config} config configuration object.\r\n * @returns {DynamicsWebApi} A new instance of DynamicsWebApi\r\n */\r\n initializeInstance = (config?: Config): DynamicsWebApi => new DynamicsWebApi(config || this._config);\r\n\r\n Utility = {\r\n /**\r\n * Searches for a collection name by provided entity name in a cached entity metadata.\r\n * The returned collection name can be null.\r\n *\r\n * @param {string} entityName entity name\r\n * @returns {string | null} collection name\r\n */\r\n getCollectionName: (entityName: string): string | null => RequestClient.getCollectionName(entityName),\r\n };\r\n}\r\n\r\nexport interface Expand {\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**Use the $filter system query option to set criteria for which entities will be returned. */\r\n filter?: string;\r\n /**Limit the number of results returned by using the $top system query option.Do not use $top with $count! */\r\n top?: number;\r\n /**An Array(of Strings) representing the order in which items are returned using the $orderby system query option.Use the asc or desc suffix to specify ascending or descending order respectively.The default is ascending if the suffix isn't applied. */\r\n orderBy?: string[];\r\n /**A name of a single-valued navigation property which needs to be expanded. */\r\n property?: string;\r\n /**An Array of Expand Objects representing the $expand Query Option value to control which related records need to be returned. */\r\n expand?: Expand[];\r\n}\r\n\r\nexport interface BaseRequest {\r\n /**XHR requests only! Indicates whether the requests should be made synchronously or asynchronously.Default value is 'true'(asynchronously). */\r\n async?: boolean;\r\n /**Impersonates a user based on their systemuserid by adding \"MSCRMCallerID\" header. A String representing the GUID value for the Dynamics 365 systemuserid. */\r\n impersonate?: string;\r\n /**Impersonates a user based on their Azure Active Directory (AAD) object id by passing that value along with the header \"CallerObjectId\". A String should represent a GUID value. */\r\n impersonateAAD?: string;\r\n /**If set to 'true', DynamicsWebApi adds a request header 'Cache-Control: no-cache'.Default value is 'false'. */\r\n noCache?: boolean;\r\n /** Authorization Token. If set, onTokenRefresh will not be called. */\r\n token?: string;\r\n /**Sets a number of milliseconds before a request times out. */\r\n timeout?: number;\r\n /**The AbortSignal interface represents a signal object that allows you to communicate with a DOM request and abort it if required via an AbortController object. */\r\n signal?: AbortSignal;\r\n /**Indicates if an operation must be included in a Change Set or not. Works in Batch Operations only. By default, it's \"true\", except for GET operations - they are not allowed in Change Sets. */\r\n inChangeSet?: boolean;\r\n /**Headers to supply with a request. These headers will override configuraiton headers if the identical ones were set. */\r\n headers?: HeaderCollection;\r\n /**Custom query parameters. Can be used to set parameter aliases for \"$filter\" and \"$orderBy\". Important! These parameters ARE NOT URI encoded! */\r\n queryParams?: string[];\r\n}\r\n\r\nexport interface BatchRequest extends BaseRequest {\r\n /** Sets Prefer header to \"odata.continue-on-error\" that allows more requests be processed when errors occur. The batch request will return '200 OK' and individual response errors will be returned in the batch response body. */\r\n continueOnError?: boolean;\r\n}\r\n\r\nexport interface Request extends BaseRequest {\r\n /**A name of the Entity Collection or Entity Logical name. */\r\n collection?: string;\r\n}\r\n\r\nexport interface CRUDRequest extends Request {\r\n /**A String representing collection record's Primary Key (GUID) or Alternate Key(s). */\r\n key?: string;\r\n}\r\n\r\nexport interface CountRequest extends Request {\r\n /**Use the $filter system query option to set criteria for which entities will be returned. */\r\n filter?: string;\r\n}\r\n\r\nexport interface CountAllRequest extends CountRequest {\r\n /**A name of the Entity Collection or Entity Logical name. */\r\n collection: string;\r\n /**An Array (of strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n}\r\n\r\nexport interface FetchAllRequest extends Request {\r\n /**Sets FetchXML - a proprietary query language that provides capabilities to perform aggregation. */\r\n fetchXml: string;\r\n /**Sets Prefer header with value \"odata.include-annotations=\" and the specified annotation. Annotations provide additional information about lookups, options sets and other complex attribute types. For example: * or Microsoft.Dynamics.CRM.fetchxmlpagingcookie */\r\n includeAnnotations?: string;\r\n}\r\n\r\nexport interface FetchXmlRequest extends FetchAllRequest {\r\n /**Page number. */\r\n pageNumber?: number;\r\n /**Paging cookie. To retrive the first page, pagingCookie must be null. */\r\n pagingCookie?: string;\r\n}\r\n\r\nexport interface CreateRequest extends CRUDRequest {\r\n /**If set to true, the request bypasses custom business logic, all synchronous plug-ins and real-time workflows are disabled. Check for special exceptions in Microsft Docs. */\r\n bypassCustomPluginExecution?: boolean;\r\n /**Web API v9+ only! Boolean that enables duplicate detection. */\r\n duplicateDetection?: boolean;\r\n /**A JavaScript object with properties corresponding to the logical name of entity attributes(exceptions are lookups and single-valued navigation properties). */\r\n data?: T;\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n /**Sets Prefer header with value \"odata.include-annotations=\" and the specified annotation.Annotations provide additional information about lookups, options sets and other complex attribute types. */\r\n includeAnnotations?: string;\r\n /**A String representing the name of a single - valued navigation property.Useful when needed to retrieve information about a related record in a single request. */\r\n navigationProperty?: string;\r\n /**A String representing navigation property's Primary Key (GUID) or Alternate Key(s). (For example, to retrieve Attribute Metadata). */\r\n navigationPropertyKey?: string;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**Sets Prefer header request with value \"return=representation\".Use this property to return just created or updated entity in a single request. */\r\n returnRepresentation?: boolean;\r\n /**BATCH REQUESTS ONLY! Sets Content-ID header or references request in a Change Set. */\r\n contentId?: string;\r\n /**A unique partition key value of a logical partition for non-relational custom entity data stored in NoSql tables of Azure heterogenous storage. */\r\n partitionId?: string;\r\n}\r\n\r\nexport interface UpdateRequestBase extends CRUDRequest {\r\n /**If set to true, the request bypasses custom business logic, all synchronous plug-ins and real-time workflows are disabled. Check for special exceptions in Microsft Docs. */\r\n bypassCustomPluginExecution?: boolean;\r\n /**Web API v9+ only! Boolean that enables duplicate detection. */\r\n duplicateDetection?: boolean;\r\n /**A JavaScript object with properties corresponding to the logical name of entity attributes(exceptions are lookups and single-valued navigation properties). */\r\n data?: T;\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n /**Sets If-Match header value that enables to use conditional retrieval or optimistic concurrency in applicable requests.*/\r\n ifmatch?: string;\r\n /**Sets Prefer header with value \"odata.include-annotations=\" and the specified annotation.Annotations provide additional information about lookups, options sets and other complex attribute types. */\r\n includeAnnotations?: string;\r\n /**Sets Prefer header request with value \"return=representation\".Use this property to return just created or updated entity in a single request. */\r\n returnRepresentation?: boolean;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**BATCH REQUESTS ONLY! Sets Content-ID header or references request in a Change Set. */\r\n contentId?: string;\r\n /**Casts the AttributeMetadata to a specific type. (Used in requests to Attribute Metadata). */\r\n metadataAttributeType?: string;\r\n /**A String representing the name of a single - valued navigation property.Useful when needed to retrieve information about a related record in a single request. */\r\n navigationProperty?: string;\r\n /**A String representing navigation property's Primary Key (GUID) or Alternate Key(s). (For example, to retrieve Attribute Metadata). */\r\n navigationPropertyKey?: string;\r\n /**A unique partition key value of a logical partition for non-relational custom entity data stored in NoSql tables of Azure heterogenous storage. */\r\n partitionId?: string;\r\n}\r\n\r\nexport interface UpdateRequest extends UpdateRequestBase {\r\n /**If set to 'true', DynamicsWebApi adds a request header 'MSCRM.MergeLabels: true'. Default value is 'false' */\r\n mergeLabels?: boolean;\r\n}\r\n\r\nexport interface UpdateSinglePropertyRequest extends CRUDRequest {\r\n /**Object with a logical name of the field as a key and a value to update with. Example: {subject: \"Update Record\"} */\r\n fieldValuePair: { [key: string]: any };\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n /**Sets If-Match header value that enables to use conditional retrieval or optimistic concurrency in applicable requests.*/\r\n ifmatch?: string;\r\n /**Sets Prefer header with value \"odata.include-annotations=\" and the specified annotation.Annotations provide additional information about lookups, options sets and other complex attribute types. */\r\n includeAnnotations?: string;\r\n /**Sets Prefer header request with value \"return=representation\".Use this property to return just created or updated entity in a single request. */\r\n returnRepresentation?: boolean;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**BATCH REQUESTS ONLY! Sets Content-ID header or references request in a Change Set. */\r\n contentId?: string;\r\n}\r\n\r\nexport interface UpsertRequest extends UpdateRequestBase {\r\n /**Sets If-None-Match header value that enables to use conditional retrieval in applicable requests. */\r\n ifnonematch?: string;\r\n}\r\n\r\nexport interface DeleteRequest extends CRUDRequest {\r\n /**If set to true, the request bypasses custom business logic, all synchronous plug-ins and real-time workflows are disabled. Check for special exceptions in Microsft Docs. */\r\n bypassCustomPluginExecution?: boolean;\r\n /**Sets If-Match header value that enables to use conditional retrieval or optimistic concurrency in applicable requests.*/\r\n ifmatch?: string;\r\n /**BATCH REQUESTS ONLY! Sets Content-ID header or references request in a Change Set. */\r\n contentId?: string;\r\n /**Field name that needs to be cleared (for example File Field) */\r\n fieldName?: string;\r\n}\r\n\r\nexport interface RetrieveRequest extends CRUDRequest {\r\n /**A name of the Entity Collection or Entity Logical name. */\r\n collection: string;\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n /**Sets If-Match header value that enables to use conditional retrieval or optimistic concurrency in applicable requests.*/\r\n ifmatch?: string;\r\n /**Sets If-None-Match header value that enables to use conditional retrieval in applicable requests. */\r\n ifnonematch?: string;\r\n /**Sets Prefer header with value \"odata.include-annotations=\" and the specified annotation.Annotations provide additional information about lookups, options sets and other complex attribute types. */\r\n includeAnnotations?: string;\r\n /**Casts the AttributeMetadata to a specific type. (Used in requests to Attribute Metadata). */\r\n metadataAttributeType?: string;\r\n /**A String representing the name of a single - valued navigation property.Useful when needed to retrieve information about a related record in a single request. */\r\n navigationProperty?: string;\r\n /**A String representing navigation property's Primary Key (GUID) or Alternate Key(s). (For example, to retrieve Attribute Metadata). */\r\n navigationPropertyKey?: string;\r\n /**A String representing the GUID value of the saved query. */\r\n savedQuery?: string;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**A String representing the GUID value of the user query. */\r\n userQuery?: string;\r\n /**A unique partition key value of a logical partition for non-relational custom entity data stored in NoSql tables of Azure heterogenous storage. */\r\n partitionId?: string;\r\n}\r\n\r\nexport interface RetrieveMultipleRequest extends Request {\r\n /**A name of the Entity Collection or Entity Logical name. */\r\n collection: string;\r\n /**Use the $apply to aggregate and group your data dynamically */\r\n apply?: string;\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n /**Boolean that sets the $count system query option with a value of true to include a count of entities that match the filter criteria up to 5000(per page).Do not use $top with $count! */\r\n count?: boolean;\r\n /**Use the $filter system query option to set criteria for which entities will be returned. */\r\n filter?: string;\r\n /**Sets Prefer header with value \"odata.include-annotations=\" and the specified annotation.Annotations provide additional information about lookups, options sets and other complex attribute types. */\r\n includeAnnotations?: string;\r\n /**Sets the odata.maxpagesize preference value to request the number of entities returned in the response. */\r\n maxPageSize?: number;\r\n /**An Array(of string) representing the order in which items are returned using the $orderby system query option.Use the asc or desc suffix to specify ascending or descending order respectively.The default is ascending if the suffix isn't applied. */\r\n orderBy?: string[];\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**Limit the number of results returned by using the $top system query option.Do not use $top with $count! */\r\n top?: number;\r\n /**Sets Prefer header with value 'odata.track-changes' to request that a delta link be returned which can subsequently be used to retrieve entity changes. */\r\n trackChanges?: boolean;\r\n /**A unique partition key value of a logical partition for non-relational custom entity data stored in NoSql tables of Azure heterogenous storage. */\r\n partitionId?: string;\r\n}\r\n\r\nexport interface AssociateRequest extends Request {\r\n /**Primary entity record id/key. */\r\n primaryKey: string;\r\n /**Relationship name. */\r\n relationshipName: string;\r\n /**Related name of the Entity Collection or Entity Logical name. */\r\n relatedCollection: string;\r\n /**Related entity record id/key. */\r\n relatedKey: string;\r\n}\r\n\r\nexport interface AssociateSingleValuedRequest extends Request {\r\n /**Primary entity record id/key. */\r\n primaryKey: string;\r\n /**Navigation property name. */\r\n navigationProperty: string;\r\n /**Related name of the Entity Collection or Entity Logical name. */\r\n relatedCollection: string;\r\n /**Related entity record id/key. */\r\n relatedKey: string;\r\n}\r\n\r\nexport interface DisassociateRequest extends Request {\r\n /**Primary entity record id/key. */\r\n primaryKey: string;\r\n /**Relationship name. */\r\n relationshipName: string;\r\n /**Related entity record id/key. */\r\n relatedKey: string;\r\n}\r\n\r\nexport interface DisassociateSingleValuedRequest extends Request {\r\n /**Primary entity record id/key. */\r\n primaryKey: string;\r\n /**Navigation property name. */\r\n navigationProperty: string;\r\n}\r\n\r\nexport interface UnboundFunctionRequest extends BaseRequest {\r\n /**\r\n * Name of the function.\r\n */\r\n name?: string;\r\n /**\r\n * Name of the function. \r\n * @deprecated Use \"name\" parameter.\r\n */\r\n functionName?: string;\r\n /**Function's input parameters. Example: { param1: \"test\", param2: 3 }. */\r\n parameters?: any;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**Use the $filter system query option to set criteria for which entities will be returned. */\r\n filter?: string;\r\n}\r\n\r\nexport interface BoundFunctionRequest extends UnboundFunctionRequest, Request {\r\n /**A String representing the GUID value for the record. */\r\n key?: string;\r\n}\r\n\r\nexport interface UnboundActionRequest extends BaseRequest {\r\n /**A name of the Web API action. */\r\n actionName: string;\r\n /**An object that represents a Dynamics 365 action. */\r\n action?: TAction;\r\n}\r\n\r\nexport interface BoundActionRequest extends UnboundActionRequest, Request {\r\n /**A String representing the GUID value for the record. */\r\n key?: string;\r\n}\r\n\r\nexport interface CreateEntityRequest extends BaseRequest {\r\n /**An object with properties corresponding to the logical name of entity attributes(exceptions are lookups and single-valued navigation properties). */\r\n data: any;\r\n}\r\n\r\nexport interface UpdateEntityRequest extends CRUDRequest {\r\n /**An object with properties corresponding to the logical name of entity attributes(exceptions are lookups and single-valued navigation properties). */\r\n data: any;\r\n /**Sets MSCRM.MergeLabels header that controls whether to overwrite the existing labels or merge your new label with any existing language labels. Default value is false. */\r\n mergeLabels?: boolean;\r\n}\r\n\r\nexport interface RetrieveEntityRequest extends BaseRequest {\r\n /**An Entity MetadataId or Alternate Key (such as LogicalName). */\r\n key: string;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n}\r\n\r\nexport interface RetrieveEntitiesRequest extends BaseRequest {\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**Use the $filter system query option to set criteria for which entities will be returned. */\r\n filter?: string;\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n}\r\n\r\nexport interface CreateAttributeRequest extends BaseRequest {\r\n /**An Entity MetadataId or Alternate Key (such as LogicalName). */\r\n entityKey: string;\r\n /**Attribute metadata object. */\r\n data: any;\r\n}\r\n\r\nexport interface UpdateAttributeRequest extends CreateAttributeRequest {\r\n /**Use this parameter to cast the Attribute to a specific type. */\r\n castType?: string;\r\n /**Sets MSCRM.MergeLabels header that controls whether to overwrite the existing labels or merge your new label with any existing language labels. Default value is false. */\r\n mergeLabels?: boolean;\r\n}\r\n\r\nexport interface RetrieveAttributesRequest extends BaseRequest {\r\n /**An Entity MetadataId or Alternate Key (such as LogicalName). */\r\n entityKey: string;\r\n /**Use this parameter to cast the Attribute to a specific type. */\r\n castType?: string;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**Use the $filter system query option to set criteria for which entities will be returned. */\r\n filter?: string;\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n}\r\n\r\nexport interface RetrieveAttributeRequest extends BaseRequest {\r\n /**An Attribute MetadataId or Alternate Key (such as LogicalName). */\r\n attributeKey: string;\r\n /**An Entity MetadataId or Alternate Key (such as LogicalName). */\r\n entityKey: string;\r\n /**Use this parameter to cast the Attribute to a specific type. */\r\n castType?: string;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n}\r\n\r\nexport interface CreateRelationshipRequest extends BaseRequest {\r\n /**Relationship Definition. */\r\n data: any;\r\n}\r\n\r\nexport interface UpdateRelationshipRequest extends CreateRelationshipRequest {\r\n /**Use this parameter to cast the Relationship metadata to a specific type. */\r\n castType?: string;\r\n /**Sets MSCRM.MergeLabels header that controls whether to overwrite the existing labels or merge your new label with any existing language labels. Default value is false. */\r\n mergeLabels?: boolean;\r\n}\r\n\r\nexport interface DeleteRelationshipRequest extends BaseRequest {\r\n /**A Relationship MetadataId or Alternate Key (such as LogicalName). */\r\n key: string;\r\n}\r\n\r\nexport interface RetrieveRelationshipsRequest extends BaseRequest {\r\n /**Use this parameter to cast the Relationship metadata to a specific type. */\r\n castType?: string;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**Use the $filter system query option to set criteria for which entities will be returned. */\r\n filter?: string;\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n}\r\n\r\nexport interface RetrieveRelationshipRequest extends BaseRequest {\r\n /**A Relationship MetadataId or Alternate Key (such as LogicalName). */\r\n key: string;\r\n /**Use this parameter to cast the Relationship metadata to a specific type. */\r\n castType?: string;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n}\r\n\r\nexport interface CreateGlobalOptionSetRequest extends BaseRequest {\r\n /**Global Option Set Definition. */\r\n data: any;\r\n}\r\n\r\nexport interface UpdateGlobalOptionSetRequest extends CreateRelationshipRequest {\r\n /**Use this parameter to cast the Global Option Set metadata to a specific type. */\r\n castType?: string;\r\n /**Sets MSCRM.MergeLabels header that controls whether to overwrite the existing labels or merge your new label with any existing language labels. Default value is false. */\r\n mergeLabels?: boolean;\r\n}\r\n\r\nexport interface DeleteGlobalOptionSetRequest extends BaseRequest {\r\n /**A Global Option Set MetadataId or Alternate Key (such as LogicalName). */\r\n key: string;\r\n}\r\n\r\nexport interface RetrieveGlobalOptionSetsRequest extends BaseRequest {\r\n /**Use this parameter to cast the Global Option Set metadata to a specific type. */\r\n castType?: string;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**Use the $filter system query option to set criteria for which entities will be returned. */\r\n filter?: string;\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n}\r\n\r\nexport interface RetrieveGlobalOptionSetRequest extends BaseRequest {\r\n /**A Global Option Set MetadataId or Alternate Key (such as LogicalName). */\r\n key: string;\r\n /**Use this parameter to cast the Global Option Set metadata to a specific type. */\r\n castType?: string;\r\n /**An Array(of Strings) representing the $select OData System Query Option to control which attributes will be returned. */\r\n select?: string[];\r\n /**An array of Expand Objects(described below the table) representing the $expand OData System Query Option value to control which related records are also returned. */\r\n expand?: Expand[];\r\n}\r\n\r\nexport interface UploadRequest extends CRUDRequest {\r\n /**Binary Buffer*/\r\n data: Uint8Array | Buffer;\r\n /**Name of the file */\r\n fileName: string;\r\n /**File Field Name */\r\n fieldName: string;\r\n}\r\n\r\nexport interface DownloadRequest extends CRUDRequest {\r\n /**File Field Name */\r\n fieldName: string;\r\n}\r\n\r\nexport interface CsdlMetadataRequest extends BaseRequest {\r\n /**If set to \"true\" the document will include many different kinds of annotations that can be useful. Most annotations are not included by default because they increase the total size of the document. */\r\n addAnnotations?: boolean;\r\n}\r\n\r\nexport type SearchMode = \"any\" | \"all\";\r\nexport type SearchType = \"simple\" | \"full\";\r\n\r\nexport interface SearchQueryBase {\r\n /**The search parameter value contains the term to be searched for and has a 100-character limit. For suggestions, min 3 characters in addition. */\r\n search: string;\r\n /**The default table list searches across all Dataverse search\u2013configured tables and columns. The default list is configured by your administrator when Dataverse search is enabled. */\r\n entities?: string[];\r\n /**Filters are applied while searching data and are specified in standard OData syntax. */\r\n filter?: string;\r\n}\r\n\r\nexport interface Search extends SearchQueryBase {\r\n /**Facets support the ability to drill down into data results after they've been retrieved. */\r\n facets?: string[];\r\n /**Specify true to return the total record count; otherwise false. The default is false. */\r\n returnTotalRecordCount?: boolean;\r\n /**Specifies the number of search results to skip. */\r\n skip?: number;\r\n /**Specifies the number of search results to retrieve. The default is 50, and the maximum value is 100. */\r\n top?: number;\r\n /**A list of comma-separated clauses where each clause consists of a column name followed by 'asc' (ascending, which is the default) or 'desc' (descending). This list specifies how to order the results in order of precedence. */\r\n orderBy?: string[];\r\n /**Specifies whether any or all the search terms must be matched to count the document as a match. The default is 'any'. */\r\n searchMode?: SearchMode;\r\n /**The search type specifies the syntax of a search query. Using 'simple' selects simple query syntax and 'full' selects Lucene query syntax. The default is 'simple'. */\r\n searchType?: SearchType;\r\n}\r\n\r\nexport interface Suggest extends SearchQueryBase {\r\n /**Use fuzzy search to aid with misspellings. The default is false. */\r\n useFuzzy?: boolean;\r\n /**Number of suggestions to retrieve. The default is 5. */\r\n top?: number;\r\n /**A list of comma-separated clauses where each clause consists of a column name followed by 'asc' (ascending, which is the default) or 'desc' (descending). This list specifies how to order the results in order of precedence. */\r\n orderBy?: string[];\r\n}\r\n\r\nexport interface Autocomplete extends SearchQueryBase {\r\n /**Use fuzzy search to aid with misspellings. The default is false. */\r\n useFuzzy?: boolean;\r\n}\r\n\r\nexport interface SearchRequest extends BaseRequest {\r\n /**Search query object */\r\n query: Search;\r\n}\r\n\r\nexport interface SuggestRequest extends BaseRequest {\r\n /**Suggestion query object */\r\n query: Suggest;\r\n}\r\n\r\nexport interface AutocompleteRequest extends BaseRequest {\r\n /**Autocomplete query object */\r\n query: Autocomplete;\r\n}\r\n\r\nexport interface ApiConfig {\r\n /** API Version to use, for example: \"9.2\" or \"1.0\" */\r\n version?: string;\r\n /** API Path, for example: \"data\" or \"search\" */\r\n path?: string;\r\n}\r\n\r\nexport interface AccessToken {\r\n /** Access Token */\r\n accessToken: string;\r\n}\r\n\r\nexport interface Config {\r\n /**The url to Dataverse API server, for example: https://contoso.api.crm.dynamics.com/. It is required when used in Node.js application. */\r\n serverUrl?: string | null;\r\n /**Impersonates a user based on their systemuserid by adding \"MSCRMCallerID\" header. A String representing the GUID value for the Dynamics 365 systemuserid. */\r\n impersonate?: string | null;\r\n /**Impersonates a user based on their Azure Active Directory (AAD) object id by passing that value along with the header \"CallerObjectId\". A String should represent a GUID value. */\r\n impersonateAAD?: string | null;\r\n /**A function that is called when a security token needs to be refreshed. */\r\n onTokenRefresh?: (() => Promise) | null;\r\n /**Sets Prefer header with value \"odata.include-annotations=\" and the specified annotation.Annotations provide additional information about lookups, options sets and other complex attribute types.*/\r\n includeAnnotations?: string | null;\r\n /**Sets the odata.maxpagesize preference value to request the number of entities returned in the response. */\r\n maxPageSize?: number | null;\r\n /**Sets Prefer header request with value \"return=representation\".Use this property to return just created or updated entity in a single request.*/\r\n returnRepresentation?: boolean | null;\r\n /**Indicates whether to use Entity Logical Names instead of Collection Logical Names.*/\r\n useEntityNames?: boolean | null;\r\n /**Sets a number of milliseconds before a request times out. */\r\n timeout?: number | null;\r\n /**Proxy configuration object. */\r\n proxy?: ProxyConfig | null;\r\n /**Configuration object for Dataverse Web API (with path \"data\"). */\r\n dataApi?: ApiConfig;\r\n /**Configuration object for Dataverse Search API (with path \"search\"). */\r\n searchApi?: ApiConfig;\r\n /**Default headers to supply with each request. */\r\n headers?: HeaderCollection;\r\n}\r\n\r\n/**Header collection type */\r\nexport type HeaderCollection = {\r\n /**key-value */\r\n [key: string]: string;\r\n};\r\n\r\nexport interface ProxyConfig {\r\n /**Proxy server url */\r\n url: string;\r\n /**Basic authentication credentials */\r\n auth?: {\r\n /**Username */\r\n username: string;\r\n /**Password */\r\n password: string;\r\n };\r\n}\r\n\r\n/** Callback with an acquired token called by DynamicsWebApi; \"token\" argument can be a string or an object with a property {accessToken: } */\r\n// export interface OnTokenAcquiredCallback {\r\n// (token: any): void;\r\n// }\r\n\r\nexport interface RequestError extends Error {\r\n /**The name of the error */\r\n name: string;\r\n /**This code is not related to the http status code and is frequently empty */\r\n code?: string;\r\n /**A message describing the error */\r\n message: string;\r\n /**HTTP status code */\r\n status?: number;\r\n /**HTTP status text. Frequently empty */\r\n statusText?: string;\r\n /**HTTP Response headers */\r\n headers?: any;\r\n /**Details about an error */\r\n innererror?: {\r\n /**A message describing the error, this is frequently the same as the outer message */\r\n message?: string;\r\n /**Microsoft.Crm.CrmHttpException */\r\n type?: string;\r\n /**Details from the server about where the error occurred */\r\n stacktrace?: string;\r\n };\r\n}\r\n\r\nexport interface MultipleResponse {\r\n /**Multiple respone entities */\r\n value: T[];\r\n oDataCount?: number;\r\n \"@odata.count\"?: number;\r\n oDataContext?: string;\r\n \"@odata.context\"?: number;\r\n}\r\n\r\nexport interface AllResponse extends MultipleResponse {\r\n /**@odata.deltaLink value */\r\n oDataDeltaLink?: string;\r\n}\r\n\r\nexport interface RetrieveMultipleResponse extends MultipleResponse {\r\n \"@Microsoft.Dynamics.CRM.totalrecordcount\"?: number;\r\n \"@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded\"?: boolean;\r\n /**@odata.nextLink value */\r\n oDataNextLink?: string;\r\n /**@odata.deltaLink value */\r\n oDataDeltaLink?: string;\r\n \"@odata.deltaLink\"?: string;\r\n \"@odata.nextLink\"?: string;\r\n}\r\n\r\nexport interface FetchXmlResponse extends MultipleResponse {\r\n \"@Microsoft.Dynamics.CRM.totalrecordcount\"?: number;\r\n \"@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded\"?: boolean;\r\n /**Paging information */\r\n PagingInfo?: {\r\n /**Number of the next page */\r\n nextPage?: number;\r\n /**Next page cookie */\r\n cookie?: string;\r\n };\r\n}\r\n\r\nexport interface DownloadResponse {\r\n /**The name of the file */\r\n fileName: string;\r\n /**File size */\r\n fileSize: number;\r\n /**File Data */\r\n data: Uint8Array | Buffer;\r\n}\r\n\r\nexport interface SearchResponse {\r\n /**Search results*/\r\n value: TValue[];\r\n facets: any | null;\r\n totalrecordcount: number;\r\n querycontext: any | null;\r\n}\r\n\r\nexport interface SuggestResponseValue {\r\n text: string;\r\n document: TDocument;\r\n}\r\n\r\nexport interface SuggestResponse {\r\n /**Suggestions*/\r\n value: SuggestResponseValue[];\r\n querycontext: any | null;\r\n}\r\n\r\nexport interface AutocompleteResponse {\r\n /**Autocomplete result*/\r\n value: string | null;\r\n querycontext: any | null;\r\n}\r\n\r\n//function overloads\r\n\r\ntype CallFunction = {\r\n /**\r\n * Calls a Web API function\r\n *\r\n * @param name - The name of a function.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n (name: string): Promise;\r\n /**\r\n * Calls a bound Web API function\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n (request: BoundFunctionRequest): Promise;\r\n /**\r\n * Calls an unbound Web API function (not bound to a particular table row)\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n (request: UnboundFunctionRequest): Promise;\r\n};\r\n\r\ntype CallAction = {\r\n /**\r\n * Calls a bound Web API action (bound to a particular table row)\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @type {T} Type of the value in a response\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n (request: BoundActionRequest): Promise;\r\n /**\r\n * Calls an unbound Web API action (not bound to a particular table row)\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @type {T} Type of the value in a response\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n (request: UnboundActionRequest): Promise;\r\n /**\r\n * Calls a bound Web API action (bound to a particular table row)\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @type {TResponse} Type of the value in a response\r\n * @type {TAction} Type of an action object\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n (request: BoundActionRequest): Promise;\r\n /**\r\n * Calls an unbound Web API action (not bound to a particular table row)\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @type {TResponse} Type of the value in a response\r\n * @type {TAction} Type of an action object\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n (request: UnboundActionRequest): Promise;\r\n};\r\n\r\ntype SearchFunction = {\r\n /**\r\n * Provides a search results page.\r\n * @param term - The term to be searched for and has a max 100-character limit.\r\n * @returns {Promise} Search result\r\n */\r\n (term: string): Promise;\r\n /**\r\n * Provides a search results page.\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise>} Search result\r\n */\r\n (request: SearchRequest): Promise>;\r\n};\r\n\r\ntype SuggestFunction = {\r\n /**\r\n * Provides suggestions as the user enters text into a form field.\r\n * @param term - The term to be searched for and has min 3 characters to a max 100-character limit.\r\n * @returns {Promise} Suggestions result\r\n */\r\n (term: string): Promise;\r\n /**\r\n * Provides suggestions as the user enters text into a form field.\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise>} Suggestions result\r\n */\r\n (request: SuggestRequest): Promise>;\r\n};\r\n\r\ntype AutocompleteFunction = {\r\n /**\r\n * Provides autocompletion of input as the user enters text into a form field.\r\n * @param term - The term to be searched for and has a 100-character limit.\r\n * @returns {Promise} Result of autocomplete\r\n */\r\n (term: string): Promise;\r\n /**\r\n * Provides autocompletion of input as the user enters text into a form field.\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} Result of autocomplete\r\n */\r\n (request: AutocompleteRequest): Promise;\r\n};\r\n", "import { Utility } from \"../utils/Utility\";\r\nimport { InternalConfig } from \"../utils/Config\";\r\nimport { RequestUtility } from \"../utils/Request\";\r\nimport { DynamicsWebApiError, ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport { Core } from \"../types\";\r\nimport { executeRequest } from \"./helpers/executeRequest\";\r\nimport { AccessToken } from \"../dynamics-web-api\";\r\n\r\nconst _addResponseParams = (requestId, responseParams) => {\r\n if (_responseParseParams[requestId]) _responseParseParams[requestId].push(responseParams);\r\n else _responseParseParams[requestId] = [responseParams];\r\n};\r\n\r\nconst _addRequestToBatchCollection = (requestId, request) => {\r\n if (_batchRequestCollection[requestId]) _batchRequestCollection[requestId].push(request);\r\n else _batchRequestCollection[requestId] = [request];\r\n};\r\n\r\nconst _clearRequestData = (requestId: string): void => {\r\n delete _responseParseParams[requestId];\r\n if (_batchRequestCollection.hasOwnProperty(requestId)) delete _batchRequestCollection[requestId];\r\n};\r\n\r\nconst _runRequest = async (request: Core.InternalRequest, config: InternalConfig): Promise => {\r\n try {\r\n const result = await RequestClient.sendRequest(request, config);\r\n _clearRequestData(request.requestId!);\r\n\r\n return result;\r\n } catch (error) {\r\n _clearRequestData(request.requestId!);\r\n throw error;\r\n } finally {\r\n _clearRequestData(request.requestId!);\r\n }\r\n};\r\n\r\nlet _batchRequestCollection: Core.BatchRequestCollection = {};\r\nlet _responseParseParams: { [key: string]: any[] } = {};\r\n\r\nexport class RequestClient {\r\n /**\r\n * Sends a request to given URL with given parameters\r\n *\r\n * @param {InternalRequest} request - Composed request to D365 Web Api\r\n * @param {InternalConfig} config - DynamicsWebApi config.\r\n */\r\n static async sendRequest(request: Core.InternalRequest, config: InternalConfig): Promise {\r\n request.headers = request.headers || {};\r\n request.responseParameters = request.responseParameters || {};\r\n request.requestId = request.requestId || Utility.generateUUID();\r\n\r\n //add response parameters to parse\r\n _addResponseParams(request.requestId, request.responseParameters);\r\n\r\n //stringify passed data\r\n let processedData = null;\r\n\r\n const isBatchConverted = request.responseParameters?.convertedToBatch;\r\n\r\n if (request.path === \"$batch\" && !isBatchConverted) {\r\n const batchRequest = _batchRequestCollection[request.requestId];\r\n\r\n if (!batchRequest) throw ErrorHelper.batchIsEmpty();\r\n\r\n const batchResult = RequestUtility.convertToBatch(batchRequest, config, request);\r\n\r\n processedData = batchResult.body;\r\n request.headers = { ...batchResult.headers, ...request.headers };\r\n\r\n //clear an array of requests\r\n delete _batchRequestCollection[request.requestId];\r\n } else {\r\n processedData = !isBatchConverted ? RequestUtility.processData(request.data, config) : request.data;\r\n\r\n if (!isBatchConverted) request.headers = RequestUtility.setStandardHeaders(request.headers);\r\n }\r\n\r\n if (config.impersonate && !request.headers![\"MSCRMCallerID\"]) {\r\n request.headers![\"MSCRMCallerID\"] = config.impersonate;\r\n }\r\n\r\n if (config.impersonateAAD && !request.headers![\"CallerObjectId\"]) {\r\n request.headers![\"CallerObjectId\"] = config.impersonateAAD;\r\n }\r\n\r\n let token: AccessToken | string | null = null;\r\n\r\n //call a token refresh callback only if it is set and there is no \"Authorization\" header set yet\r\n if (config.onTokenRefresh && (!request.headers || (request.headers && !request.headers[\"Authorization\"]))) {\r\n token = await config.onTokenRefresh();\r\n if (!token) throw new Error(\"Token is empty. Request is aborted.\");\r\n }\r\n\r\n if (token) {\r\n request.headers![\"Authorization\"] = \"Bearer \" + (token.hasOwnProperty(\"accessToken\") ? (token as AccessToken).accessToken : token);\r\n }\r\n\r\n if (Utility.isRunningWithinPortals()) {\r\n request.headers![\"__RequestVerificationToken\"] = await global.window.shell!.getTokenDeferred();\r\n }\r\n\r\n const url = request.apiConfig ? request.apiConfig.url : config.dataApi.url;\r\n\r\n return await executeRequest({\r\n method: request.method!,\r\n uri: url!.toString() + request.path,\r\n data: processedData,\r\n additionalHeaders: request.headers,\r\n responseParams: _responseParseParams,\r\n isAsync: request.async,\r\n timeout: request.timeout || config.timeout,\r\n proxy: config.proxy,\r\n requestId: request.requestId!,\r\n abortSignal: request.signal,\r\n });\r\n }\r\n\r\n private static async _getCollectionNames(entityName: string, config: InternalConfig): Promise {\r\n if (!Utility.isNull(RequestUtility.entityNames)) {\r\n return RequestUtility.findCollectionName(entityName) || entityName;\r\n }\r\n\r\n const request = RequestUtility.compose(\r\n {\r\n method: \"GET\",\r\n collection: \"EntityDefinitions\",\r\n select: [\"EntitySetName\", \"LogicalName\"],\r\n noCache: true,\r\n functionName: \"retrieveMultiple\",\r\n },\r\n config\r\n );\r\n\r\n const result = await _runRequest(request, config);\r\n RequestUtility.entityNames = {};\r\n for (let i = 0; i < result.data.value.length; i++) {\r\n RequestUtility.entityNames[result.data.value[i].LogicalName] = result.data.value[i].EntitySetName;\r\n }\r\n\r\n return RequestUtility.findCollectionName(entityName) || entityName;\r\n }\r\n\r\n private static _isEntityNameException(entityName: string): boolean {\r\n const exceptions = [\r\n \"$metadata\",\r\n \"EntityDefinitions\",\r\n \"RelationshipDefinitions\",\r\n \"GlobalOptionSetDefinitions\",\r\n \"ManagedPropertyDefinitions\",\r\n \"query\",\r\n \"suggest\",\r\n \"autocomplete\",\r\n ];\r\n\r\n return exceptions.indexOf(entityName) > -1;\r\n }\r\n\r\n private static async _checkCollectionName(entityName: string | null | undefined, config: InternalConfig): Promise {\r\n if (!entityName || RequestClient._isEntityNameException(entityName)) {\r\n return entityName;\r\n }\r\n\r\n entityName = entityName.toLowerCase();\r\n\r\n if (!config.useEntityNames) {\r\n return entityName;\r\n }\r\n\r\n try {\r\n return await RequestClient._getCollectionNames(entityName, config);\r\n } catch (error: any) {\r\n throw new Error(\"Unable to fetch Collection Names. Error: \" + (error as DynamicsWebApiError).message);\r\n }\r\n }\r\n\r\n static async makeRequest(request: Core.InternalRequest, config: InternalConfig): Promise {\r\n request.responseParameters = request.responseParameters || {};\r\n //we don't want to mix headers set by the library and by the user\r\n request.userHeaders = request.headers;\r\n delete request.headers;\r\n\r\n if (!request.isBatch) {\r\n const collectionName = await RequestClient._checkCollectionName(request.collection, config);\r\n\r\n request.collection = collectionName;\r\n RequestUtility.compose(request, config);\r\n request.responseParameters.convertedToBatch = false;\r\n\r\n //the URL contains more characters than max possible limit, convert the request to a batch request\r\n if (request.path!.length > 2000) {\r\n const batchRequest = RequestUtility.convertToBatch([request], config);\r\n\r\n request.method = \"POST\";\r\n request.path = \"$batch\";\r\n request.data = batchRequest.body;\r\n request.headers = { ...batchRequest.headers, ...request.userHeaders };\r\n request.responseParameters.convertedToBatch = true;\r\n }\r\n\r\n return _runRequest(request, config);\r\n }\r\n\r\n //no need to make a request to web api if it's a part of batch\r\n RequestUtility.compose(request, config);\r\n //add response parameters to parse\r\n _addResponseParams(request.requestId, request.responseParameters);\r\n _addRequestToBatchCollection(request.requestId, request);\r\n }\r\n\r\n static _clearTestData(): void {\r\n RequestUtility.entityNames = null;\r\n _responseParseParams = {};\r\n _batchRequestCollection = {};\r\n }\r\n\r\n static getCollectionName(entityName: string): string | null {\r\n return RequestUtility.findCollectionName(entityName);\r\n }\r\n}\r\n", "import { Utility } from \"./Utility\";\r\nimport { Config, HeaderCollection } from \"../dynamics-web-api\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport { Core } from \"../types\";\r\nimport { InternalConfig } from \"./Config\";\r\n\r\n/**\r\n * @typedef {Object} ConvertedRequestOptions\r\n * @property {string} url URL (without query)\r\n * @property {string} query Query String\r\n * @property {Object} headers Heades object (always an Object; can be empty: {})\r\n */\r\n\r\n/**\r\n * @typedef {Object} ConvertedRequest\r\n * @property {string} url URL (including Query String)\r\n * @property {Object} headers Heades object (always an Object; can be empty: {})\r\n * @property {boolean} async\r\n */\r\n\r\nexport class RequestUtility {\r\n /**\r\n * Converts a request object to URL link\r\n *\r\n * @param {Object} request - Request object\r\n * @param {Object} [config] - DynamicsWebApi config\r\n * @returns {ConvertedRequest} Converted request\r\n */\r\n static compose(request: Core.InternalRequest, config: InternalConfig): Core.InternalRequest {\r\n request.path = request.path || \"\";\r\n request.functionName = request.functionName || \"\";\r\n if (!request.url) {\r\n if (!request._isUnboundRequest && !request.contentId && !request.collection) {\r\n ErrorHelper.parameterCheck(request.collection, `DynamicsWebApi.${request.functionName}`, \"request.collection\");\r\n }\r\n if (request.collection != null) {\r\n ErrorHelper.stringParameterCheck(request.collection, `DynamicsWebApi.${request.functionName}`, \"request.collection\");\r\n request.path = request.collection;\r\n\r\n //add alternate key feature\r\n if (request.key) {\r\n request.key = ErrorHelper.keyParameterCheck(request.key, `DynamicsWebApi.${request.functionName}`, \"request.key\");\r\n request.path += `(${request.key})`;\r\n }\r\n }\r\n\r\n if (request.contentId) {\r\n ErrorHelper.stringParameterCheck(request.contentId, `DynamicsWebApi.${request.functionName}`, \"request.contentId\");\r\n if (request.contentId.startsWith(\"$\")) {\r\n request.path = request.path ? `${request.contentId}/${request.path}` : request.contentId;\r\n }\r\n }\r\n\r\n if (request._additionalUrl) {\r\n if (request.path) {\r\n request.path += \"/\";\r\n }\r\n request.path += request._additionalUrl;\r\n }\r\n\r\n request.path = RequestUtility.composeUrl(request, config, request.path);\r\n\r\n if (request.fetchXml) {\r\n ErrorHelper.stringParameterCheck(request.fetchXml, `DynamicsWebApi.${request.functionName}`, \"request.fetchXml\");\r\n let join = request.path.indexOf(\"?\") === -1 ? \"?\" : \"&\";\r\n request.path += `${join}fetchXml=${encodeURIComponent(request.fetchXml)}`;\r\n }\r\n } else {\r\n ErrorHelper.stringParameterCheck(request.url, `DynamicsWebApi.${request.functionName}`, \"request.url\");\r\n request.path = request.url.replace(config.dataApi.url, \"\");\r\n }\r\n\r\n if (request.hasOwnProperty(\"async\") && request.async != null) {\r\n ErrorHelper.boolParameterCheck(request.async, `DynamicsWebApi.${request.functionName}`, \"request.async\");\r\n } else {\r\n request.async = true;\r\n }\r\n\r\n request.headers = RequestUtility.composeHeaders(request, config);\r\n\r\n return request;\r\n }\r\n\r\n /**\r\n * Converts optional parameters of the request to URL. If expand parameter exists this function is called recursively.\r\n *\r\n * @param {Object} request - Request object\r\n * @param {string} request.functionName - Name of the function that converts a request (for Error Handling)\r\n * @param {string} url - URL beginning (with required parameters)\r\n * @param {string} [joinSymbol] - URL beginning (with required parameters)\r\n * @param {Object} [config] - DynamicsWebApi config\r\n * @returns {ConvertedRequestOptions} Additional options in request\r\n */\r\n static composeUrl(request: Core.InternalRequest, config: Config, url: string = \"\", joinSymbol: string = \"&\"): string {\r\n const queryArray: string[] = [];\r\n\r\n if (request) {\r\n if (request.navigationProperty) {\r\n ErrorHelper.stringParameterCheck(request.navigationProperty, `DynamicsWebApi.${request.functionName}`, \"request.navigationProperty\");\r\n url += \"/\" + request.navigationProperty;\r\n\r\n if (request.navigationPropertyKey) {\r\n let navigationKey = ErrorHelper.keyParameterCheck(\r\n request.navigationPropertyKey,\r\n `DynamicsWebApi.${request.functionName}`,\r\n \"request.navigationPropertyKey\"\r\n );\r\n url += \"(\" + navigationKey + \")\";\r\n }\r\n\r\n if (request.navigationProperty === \"Attributes\") {\r\n if (request.metadataAttributeType) {\r\n ErrorHelper.stringParameterCheck(\r\n request.metadataAttributeType,\r\n `DynamicsWebApi.${request.functionName}`,\r\n \"request.metadataAttributeType\"\r\n );\r\n url += \"/\" + request.metadataAttributeType;\r\n }\r\n }\r\n }\r\n\r\n if (request.select?.length) {\r\n ErrorHelper.arrayParameterCheck(request.select, `DynamicsWebApi.${request.functionName}`, \"request.select\");\r\n\r\n if (request.functionName == \"retrieve\" && request.select.length == 1 && request.select[0].endsWith(\"/$ref\")) {\r\n url += \"/\" + request.select[0];\r\n } else {\r\n if (request.select[0].startsWith(\"/\") && request.functionName == \"retrieve\") {\r\n if (request.navigationProperty == null) {\r\n url += request.select.shift();\r\n } else {\r\n request.select.shift();\r\n }\r\n }\r\n\r\n //check if anything left in the array\r\n if (request.select.length) {\r\n queryArray.push(\"$select=\" + request.select.join(\",\"));\r\n }\r\n }\r\n }\r\n\r\n if (request.filter) {\r\n ErrorHelper.stringParameterCheck(request.filter, `DynamicsWebApi.${request.functionName}`, \"request.filter\");\r\n const removeBracketsFromGuidReg = /[^\"']{([\\w\\d]{8}[-]?(?:[\\w\\d]{4}[-]?){3}[\\w\\d]{12})}(?:[^\"']|$)/g;\r\n let filterResult = request.filter;\r\n\r\n //fix bug 2018-06-11\r\n let m: RegExpExecArray | null = null;\r\n while ((m = removeBracketsFromGuidReg.exec(filterResult)) !== null) {\r\n if (m.index === removeBracketsFromGuidReg.lastIndex) {\r\n removeBracketsFromGuidReg.lastIndex++;\r\n }\r\n\r\n let replacement = m[0].endsWith(\")\") ? \")\" : \" \";\r\n filterResult = filterResult.replace(m[0], \" \" + m[1] + replacement);\r\n }\r\n\r\n queryArray.push(\"$filter=\" + encodeURIComponent(filterResult));\r\n }\r\n\r\n if (request.fieldName) {\r\n ErrorHelper.stringParameterCheck(request.fieldName, `DynamicsWebApi.${request.functionName}`, \"request.fieldName\");\r\n url += \"/\" + request.fieldName;\r\n }\r\n\r\n if (request.savedQuery) {\r\n queryArray.push(\r\n \"savedQuery=\" + ErrorHelper.guidParameterCheck(request.savedQuery, `DynamicsWebApi.${request.functionName}`, \"request.savedQuery\")\r\n );\r\n }\r\n\r\n if (request.userQuery) {\r\n queryArray.push(\r\n \"userQuery=\" + ErrorHelper.guidParameterCheck(request.userQuery, `DynamicsWebApi.${request.functionName}`, \"request.userQuery\")\r\n );\r\n }\r\n\r\n if (request.apply) {\r\n ErrorHelper.stringParameterCheck(request.apply, `DynamicsWebApi.${request.functionName}`, \"request.apply\");\r\n queryArray.push(\"$apply=\" + request.apply);\r\n }\r\n\r\n if (request.count) {\r\n ErrorHelper.boolParameterCheck(request.count, `DynamicsWebApi.${request.functionName}`, \"request.count\");\r\n queryArray.push(\"$count=\" + request.count);\r\n }\r\n\r\n if (request.top && request.top > 0) {\r\n ErrorHelper.numberParameterCheck(request.top, `DynamicsWebApi.${request.functionName}`, \"request.top\");\r\n queryArray.push(\"$top=\" + request.top);\r\n }\r\n\r\n if (request.orderBy != null && request.orderBy.length) {\r\n ErrorHelper.arrayParameterCheck(request.orderBy, `DynamicsWebApi.${request.functionName}`, \"request.orderBy\");\r\n queryArray.push(\"$orderby=\" + request.orderBy.join(\",\"));\r\n }\r\n\r\n if (request.partitionId) {\r\n ErrorHelper.stringParameterCheck(request.partitionId, `DynamicsWebApi.${request.functionName}`, \"request.partitionId\");\r\n queryArray.push(\"partitionid='\" + request.partitionId + \"'\");\r\n }\r\n\r\n if (request.downloadSize) {\r\n ErrorHelper.stringParameterCheck(request.downloadSize, `DynamicsWebApi.${request.functionName}`, \"request.downloadSize\");\r\n queryArray.push(\"size=\" + request.downloadSize);\r\n }\r\n\r\n if (request.queryParams?.length) {\r\n ErrorHelper.arrayParameterCheck(request.queryParams, `DynamicsWebApi.${request.functionName}`, \"request.queryParams\");\r\n queryArray.push(request.queryParams.join(\"&\"));\r\n }\r\n\r\n if (request.fileName) {\r\n ErrorHelper.stringParameterCheck(request.fileName, `DynamicsWebApi.${request.functionName}`, \"request.fileName\");\r\n queryArray.push(\"x-ms-file-name=\" + request.fileName);\r\n }\r\n\r\n if (request.data) {\r\n ErrorHelper.parameterCheck(request.data, `DynamicsWebApi.${request.functionName}`, \"request.data\");\r\n }\r\n\r\n if (request.isBatch) {\r\n ErrorHelper.boolParameterCheck(request.isBatch, `DynamicsWebApi.${request.functionName}`, \"request.isBatch\");\r\n }\r\n\r\n if (!Utility.isNull(request.inChangeSet)) {\r\n ErrorHelper.boolParameterCheck(request.inChangeSet, `DynamicsWebApi.${request.functionName}`, \"request.inChangeSet\");\r\n }\r\n\r\n if (request.isBatch && Utility.isNull(request.inChangeSet)) request.inChangeSet = true;\r\n\r\n if (request.timeout) {\r\n ErrorHelper.numberParameterCheck(request.timeout, `DynamicsWebApi.${request.functionName}`, \"request.timeout\");\r\n }\r\n\r\n if (request.expand?.length) {\r\n ErrorHelper.stringOrArrayParameterCheck(request.expand, `DynamicsWebApi.${request.functionName}`, \"request.expand\");\r\n if (typeof request.expand === \"string\") {\r\n queryArray.push(\"$expand=\" + request.expand);\r\n } else {\r\n const expandQueryArray: string[] = [];\r\n for (let i = 0; i < request.expand.length; i++) {\r\n if (request.expand[i].property) {\r\n const expand = request.expand[i];\r\n expand.functionName = `${request.functionName} $expand`;\r\n let expandConverted = RequestUtility.composeUrl(expand, config, \"\", \";\");\r\n if (expandConverted) {\r\n expandConverted = `(${expandConverted.substr(1)})`;\r\n }\r\n expandQueryArray.push(request.expand[i].property + expandConverted);\r\n }\r\n }\r\n if (expandQueryArray.length) {\r\n queryArray.push(\"$expand=\" + expandQueryArray.join(\",\"));\r\n }\r\n }\r\n }\r\n }\r\n\r\n return !queryArray.length ? url : url + \"?\" + queryArray.join(joinSymbol);\r\n }\r\n\r\n static composeHeaders(request: Core.InternalRequest, config: Config): HeaderCollection {\r\n const headers: HeaderCollection = { ...config.headers, ...request.userHeaders };\r\n\r\n const prefer = RequestUtility.composePreferHeader(request, config);\r\n if (prefer.length) {\r\n headers[\"Prefer\"] = prefer;\r\n }\r\n\r\n if (request.collection === \"$metadata\") {\r\n headers[\"Accept\"] = \"application/xml\";\r\n }\r\n\r\n if (request.transferMode) {\r\n headers[\"x-ms-transfer-mode\"] = request.transferMode;\r\n }\r\n\r\n if (request.ifmatch != null && request.ifnonematch != null) {\r\n throw new Error(\r\n `DynamicsWebApi.${request.functionName}. Either one of request.ifmatch or request.ifnonematch parameters should be used in a call, not both.`\r\n );\r\n }\r\n\r\n if (request.ifmatch) {\r\n ErrorHelper.stringParameterCheck(request.ifmatch, `DynamicsWebApi.${request.functionName}`, \"request.ifmatch\");\r\n headers[\"If-Match\"] = request.ifmatch;\r\n }\r\n\r\n if (request.ifnonematch) {\r\n ErrorHelper.stringParameterCheck(request.ifnonematch, `DynamicsWebApi.${request.functionName}`, \"request.ifnonematch\");\r\n headers[\"If-None-Match\"] = request.ifnonematch;\r\n }\r\n\r\n if (request.impersonate) {\r\n ErrorHelper.stringParameterCheck(request.impersonate, `DynamicsWebApi.${request.functionName}`, \"request.impersonate\");\r\n headers[\"MSCRMCallerID\"] = ErrorHelper.guidParameterCheck(request.impersonate, `DynamicsWebApi.${request.functionName}`, \"request.impersonate\");\r\n }\r\n\r\n if (request.impersonateAAD) {\r\n ErrorHelper.stringParameterCheck(request.impersonateAAD, `DynamicsWebApi.${request.functionName}`, \"request.impersonateAAD\");\r\n headers[\"CallerObjectId\"] = ErrorHelper.guidParameterCheck(\r\n request.impersonateAAD,\r\n `DynamicsWebApi.${request.functionName}`,\r\n \"request.impersonateAAD\"\r\n );\r\n }\r\n\r\n if (request.token) {\r\n ErrorHelper.stringParameterCheck(request.token, `DynamicsWebApi.${request.functionName}`, \"request.token\");\r\n headers[\"Authorization\"] = \"Bearer \" + request.token;\r\n }\r\n\r\n if (request.duplicateDetection) {\r\n ErrorHelper.boolParameterCheck(request.duplicateDetection, `DynamicsWebApi.${request.functionName}`, \"request.duplicateDetection\");\r\n headers[\"MSCRM.SuppressDuplicateDetection\"] = \"false\";\r\n }\r\n\r\n if (request.bypassCustomPluginExecution) {\r\n ErrorHelper.boolParameterCheck(\r\n request.bypassCustomPluginExecution,\r\n `DynamicsWebApi.${request.functionName}`,\r\n \"request.bypassCustomPluginExecution\"\r\n );\r\n headers[\"MSCRM.BypassCustomPluginExecution\"] = \"true\";\r\n }\r\n\r\n if (request.noCache) {\r\n ErrorHelper.boolParameterCheck(request.noCache, `DynamicsWebApi.${request.functionName}`, \"request.noCache\");\r\n headers[\"Cache-Control\"] = \"no-cache\";\r\n }\r\n\r\n if (request.mergeLabels) {\r\n ErrorHelper.boolParameterCheck(request.mergeLabels, `DynamicsWebApi.${request.functionName}`, \"request.mergeLabels\");\r\n headers[\"MSCRM.MergeLabels\"] = \"true\";\r\n }\r\n\r\n if (request.contentId) {\r\n ErrorHelper.stringParameterCheck(request.contentId, `DynamicsWebApi.${request.functionName}`, \"request.contentId\");\r\n if (!request.contentId.startsWith(\"$\")) {\r\n headers[\"Content-ID\"] = request.contentId;\r\n }\r\n }\r\n\r\n if (request.contentRange) {\r\n ErrorHelper.stringParameterCheck(request.contentRange, `DynamicsWebApi.${request.functionName}`, \"request.contentRange\");\r\n headers[\"Content-Range\"] = request.contentRange;\r\n }\r\n\r\n if (request.range) {\r\n ErrorHelper.stringParameterCheck(request.range, `DynamicsWebApi.${request.functionName}`, \"request.range\");\r\n headers[\"Range\"] = request.range;\r\n }\r\n\r\n return headers;\r\n }\r\n\r\n static composePreferHeader(request: Core.InternalRequest, config: Config): string {\r\n let returnRepresentation: boolean | null | undefined = request.returnRepresentation;\r\n let includeAnnotations: string | null | undefined = request.includeAnnotations;\r\n let maxPageSize: number | null | undefined = request.maxPageSize;\r\n let trackChanges: boolean | null | undefined = request.trackChanges;\r\n let continueOnError: boolean | null | undefined = request.continueOnError;\r\n\r\n let prefer: string[] = [];\r\n\r\n if (request.prefer && request.prefer.length) {\r\n ErrorHelper.stringOrArrayParameterCheck(request.prefer, `DynamicsWebApi.${request.functionName}`, \"request.prefer\");\r\n if (typeof request.prefer === \"string\") {\r\n prefer = request.prefer.split(\",\");\r\n }\r\n for (let i in prefer) {\r\n let item = prefer[i].trim();\r\n if (item === \"return=representation\") {\r\n returnRepresentation = true;\r\n } else if (item.includes(\"odata.include-annotations=\")) {\r\n includeAnnotations = item.replace(\"odata.include-annotations=\", \"\").replace(/\"/g, \"\");\r\n } else if (item.startsWith(\"odata.maxpagesize=\")) {\r\n maxPageSize = Number(item.replace(\"odata.maxpagesize=\", \"\").replace(/\"/g, \"\")) || 0;\r\n } else if (item.includes(\"odata.track-changes\")) {\r\n trackChanges = true;\r\n } else if (item.includes(\"odata.continue-on-error\")) {\r\n continueOnError = true;\r\n }\r\n }\r\n }\r\n\r\n //clear array\r\n prefer = [];\r\n\r\n if (config) {\r\n if (returnRepresentation == null) {\r\n returnRepresentation = config.returnRepresentation;\r\n }\r\n includeAnnotations = includeAnnotations ? includeAnnotations : config.includeAnnotations;\r\n maxPageSize = maxPageSize ? maxPageSize : config.maxPageSize;\r\n }\r\n\r\n if (returnRepresentation) {\r\n ErrorHelper.boolParameterCheck(returnRepresentation, `DynamicsWebApi.${request.functionName}`, \"request.returnRepresentation\");\r\n prefer.push(\"return=representation\");\r\n }\r\n\r\n if (includeAnnotations) {\r\n ErrorHelper.stringParameterCheck(includeAnnotations, `DynamicsWebApi.${request.functionName}`, \"request.includeAnnotations\");\r\n prefer.push(`odata.include-annotations=\"${includeAnnotations}\"`);\r\n }\r\n\r\n if (maxPageSize && maxPageSize > 0) {\r\n ErrorHelper.numberParameterCheck(maxPageSize, `DynamicsWebApi.${request.functionName}`, \"request.maxPageSize\");\r\n prefer.push(\"odata.maxpagesize=\" + maxPageSize);\r\n }\r\n\r\n if (trackChanges) {\r\n ErrorHelper.boolParameterCheck(trackChanges, `DynamicsWebApi.${request.functionName}`, \"request.trackChanges\");\r\n prefer.push(\"odata.track-changes\");\r\n }\r\n\r\n if (continueOnError) {\r\n ErrorHelper.boolParameterCheck(continueOnError, `DynamicsWebApi.${request.functionName}`, \"request.continueOnError\");\r\n prefer.push(\"odata.continue-on-error\");\r\n }\r\n\r\n return prefer.join(\",\");\r\n }\r\n\r\n static convertToBatch(requests: Core.InternalRequest[], config: InternalConfig, batchRequest?: Core.InternalRequest): Core.InternalBatchRequest {\r\n const batchBoundary = `dwa_batch_${Utility.generateUUID()}`;\r\n\r\n const batchBody: string[] = [];\r\n let currentChangeSet: string | null = null;\r\n let contentId = 100000;\r\n\r\n requests.forEach((internalRequest) => {\r\n internalRequest.functionName = \"executeBatch\";\r\n if (batchRequest?.inChangeSet === false) internalRequest.inChangeSet = false;\r\n const inChangeSet = internalRequest.method === \"GET\" ? false : !!internalRequest.inChangeSet;\r\n\r\n if (!inChangeSet && currentChangeSet) {\r\n //end current change set\r\n batchBody.push(`\\n--${currentChangeSet}--`);\r\n\r\n currentChangeSet = null;\r\n contentId = 100000;\r\n }\r\n\r\n if (!currentChangeSet) {\r\n batchBody.push(`\\n--${batchBoundary}`);\r\n\r\n if (inChangeSet) {\r\n currentChangeSet = `changeset_${Utility.generateUUID()}`;\r\n batchBody.push(\"Content-Type: multipart/mixed;boundary=\" + currentChangeSet);\r\n }\r\n }\r\n\r\n if (inChangeSet) {\r\n batchBody.push(`\\n--${currentChangeSet}`);\r\n }\r\n\r\n batchBody.push(\"Content-Type: application/http\");\r\n batchBody.push(\"Content-Transfer-Encoding: binary\");\r\n\r\n if (inChangeSet) {\r\n const contentIdValue = internalRequest.headers!.hasOwnProperty(\"Content-ID\") ? internalRequest.headers![\"Content-ID\"] : ++contentId;\r\n\r\n batchBody.push(`Content-ID: ${contentIdValue}`);\r\n }\r\n\r\n if (!internalRequest.path?.startsWith(\"$\")) {\r\n batchBody.push(`\\n${internalRequest.method} ${config.dataApi.url}${internalRequest.path} HTTP/1.1`);\r\n } else {\r\n batchBody.push(`\\n${internalRequest.method} ${internalRequest.path} HTTP/1.1`);\r\n }\r\n\r\n if (internalRequest.method === \"GET\") {\r\n batchBody.push(\"Accept: application/json\");\r\n } else {\r\n batchBody.push(\"Content-Type: application/json\");\r\n }\r\n\r\n for (let key in internalRequest.headers) {\r\n if (key === \"Authorization\" || key === \"Content-ID\") continue;\r\n\r\n batchBody.push(`${key}: ${internalRequest.headers[key]}`);\r\n }\r\n\r\n if (internalRequest.data) {\r\n batchBody.push(`\\n${RequestUtility.processData(internalRequest.data, config)}`);\r\n }\r\n });\r\n\r\n if (currentChangeSet) {\r\n batchBody.push(`\\n--${currentChangeSet}--`);\r\n }\r\n\r\n batchBody.push(`\\n--${batchBoundary}--`);\r\n\r\n const headers = RequestUtility.setStandardHeaders(batchRequest?.userHeaders);\r\n headers[\"Content-Type\"] = `multipart/mixed;boundary=${batchBoundary}`;\r\n\r\n return { headers: headers, body: batchBody.join(\"\\n\") };\r\n }\r\n\r\n static entityNames: any = null;\r\n\r\n static findCollectionName(entityName: string): string | null {\r\n let collectionName = null;\r\n\r\n if (!Utility.isNull(RequestUtility.entityNames)) {\r\n collectionName = RequestUtility.entityNames[entityName];\r\n if (Utility.isNull(collectionName)) {\r\n for (let key in RequestUtility.entityNames) {\r\n if (RequestUtility.entityNames[key] === entityName) {\r\n return entityName;\r\n }\r\n }\r\n }\r\n }\r\n\r\n return collectionName;\r\n }\r\n\r\n static processData(data: any, config: InternalConfig): string | Uint8Array | Uint16Array | Uint32Array | null {\r\n let stringifiedData: string | null = null;\r\n if (data) {\r\n if (data instanceof Uint8Array || data instanceof Uint16Array || data instanceof Uint32Array) return data;\r\n\r\n stringifiedData = JSON.stringify(data, (key, value) => {\r\n if (key.endsWith(\"@odata.bind\") || key.endsWith(\"@odata.id\")) {\r\n if (typeof value === \"string\" && !value.startsWith(\"$\")) {\r\n //remove brackets in guid\r\n if (/\\(\\{[\\w\\d-]+\\}\\)/g.test(value)) {\r\n value = value.replace(/(.+)\\(\\{([\\w\\d-]+)\\}\\)/g, \"$1($2)\");\r\n }\r\n\r\n if (config.useEntityNames) {\r\n //replace entity name with collection name\r\n const regularExpression = /([\\w_]+)(\\([\\d\\w-]+\\))$/;\r\n const valueParts = regularExpression.exec(value);\r\n if (valueParts && valueParts.length > 2) {\r\n const collectionName = RequestUtility.findCollectionName(valueParts[1]);\r\n\r\n if (!Utility.isNull(collectionName)) {\r\n value = value.replace(regularExpression, collectionName + \"$2\");\r\n }\r\n }\r\n }\r\n\r\n if (!value.startsWith(config.dataApi.url)) {\r\n //add full web api url if it's not set\r\n if (key.endsWith(\"@odata.bind\")) {\r\n if (!value.startsWith(\"/\")) {\r\n value = \"/\" + value;\r\n }\r\n } else {\r\n value = config.dataApi.url + value.replace(/^\\//, \"\");\r\n }\r\n }\r\n }\r\n } else if (key.startsWith(\"oData\") || key.endsWith(\"_Formatted\") || key.endsWith(\"_NavigationProperty\") || key.endsWith(\"_LogicalName\")) {\r\n value = undefined;\r\n }\r\n\r\n return value;\r\n });\r\n\r\n stringifiedData = stringifiedData.replace(/[\\u007F-\\uFFFF]/g, function (chr: string) {\r\n return \"\\\\u\" + (\"0000\" + chr.charCodeAt(0).toString(16)).slice(-4);\r\n });\r\n }\r\n\r\n return stringifiedData;\r\n }\r\n\r\n static setStandardHeaders(headers: HeaderCollection = {}): any {\r\n if (!headers[\"Accept\"]) headers[\"Accept\"] = \"application/json\";\r\n if (!headers[\"OData-MaxVersion\"]) headers[\"OData-MaxVersion\"] = \"4.0\";\r\n if (!headers[\"OData-Version\"]) headers[\"OData-Version\"] = \"4.0\";\r\n if (headers[\"Content-Range\"]) headers[\"Content-Type\"] = \"application/octet-stream\";\r\n else if (!headers[\"Content-Type\"]) headers[\"Content-Type\"] = \"application/json; charset=utf-8\";\r\n\r\n return headers;\r\n }\r\n}\r\n", "import { Core } from \"../../types\";\r\n\r\nexport async function executeRequest(options: Core.RequestOptions): Promise {\r\n return global.DWA_BROWSER ? require(\"../xhr\").executeRequest(options) : require(\"../http\").executeRequest(options);\r\n}\r\n"],
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;AAAO,SAAS,YAAwB;AACpC,SAAO,OAAqB,OAAc,SAAS,KAAyB,UAAU;AAC1F;AAEO,SAAS,sBAAsB;AAClC,SAAO,OAAqB,UAAU,EAAE,gBAAgB,IAAI,WAAW,CAAC,CAAC,IAAI,UAAU,EAAE,YAAY,CAAC;AAC1G;AANA;AAAA;AAAA;AAAA;AAAA;;;ACEO,SAAS,OAAO,OAAwB;AAC3C,QAAM,QAAQ,IAAI,OAAO,MAAM,GAAG,EAAE,KAAK,KAAK;AAC9C,SAAO,CAAC,CAAC;AACb;AAEO,SAAS,YAAY,OAA8B;AACtD,QAAM,QAAQ,IAAI,OAAO,SAAS,OAAO,QAAQ,GAAG,EAAE,KAAK,KAAK;AAChE,SAAO,QAAQ,MAAM,CAAC,IAAI;AAC9B;AAEO,SAAS,mBAAmB,KAA4B;AAC3D,QAAM,QAAQ,IAAI,OAAO,MAAM,OAAO,SAAS,GAAG,EAAE,KAAK,GAAG;AAC5D,SAAO,QAAQ,MAAM,CAAC,IAAI;AAC9B;AAfA,IAAM;AAAN;AAAA;AAAA;AAAA,IAAM,OAAO;AAAA;AAAA;;;ACAb,IAgBM,mBAEO;AAlBb;AAAA;AAAA;AACA;AACA;AAcA,IAAM,oBAAoB;AAEnB,IAAM,WAAN,MAAM,SAAQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOjB,OAAO,wBAAwB,YAA2C;AACtE,YAAI,YAAY;AACZ,gBAAM,iBAAiB,OAAO,KAAK,UAAU;AAC7C,gBAAM,iBAA2B,CAAC;AAClC,gBAAM,WAAqB,CAAC;AAE5B,mBAAS,IAAI,GAAG,KAAK,eAAe,QAAQ,KAAK;AAC7C,kBA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AAW,MAAM,KAAK,aAAa,eAAe;AACxD,aAAO,UAAU;AAAA,IACrB;AAKA;AAAA;AAAA;AAAA,sBAAa,MAAY;AACrB,WAAK,WAAW;AAChB,WAAK,kBAAkB,QAAQ,aAAa;AAAA,IAChD;AAOA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAe,OAAO,YAA2C;AAC7D,kBAAY,qBAAqB,KAAK,QAAQ;AAE9C,YAAM,kBAAwC,CAAC,UAAU,CAAC,IAAI,QAAQ,YAAY,OAAO;AAEzF,sBAAgB,aAAa;AAC7B,sBAAgB,SAAS;AACzB,sBAAgB,eAAe;AAC/B,sBAAgB,YAAY,KAAK;AAEjC,WAAK,kBAAkB;AACvB,WAAK,WAAW;AAEhB,YAAM,WAAW,MAAM,KAAK,aAAa,eAAe;AACxD,aAAO,UAAU;AAAA,IACrB;AAQA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,8BAAqB,CAAC,WAAoC,IAAI,gBAAe,UAAU,KAAK,OAAO;AAEnG,mBAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAQN,mBAAmB,CAAC,eAAsC,cAAc,kBAAkB,UAAU;AAAA,IACxG;AA3nCI,yBAAqB,MAAM,KAAK,SAAS,MAAM;AAAA,EACnD;AA2nCJ;",
- "names": ["executeRequest", "executeRequest", "request"]
+ "sourcesContent": ["export function getCrypto(): T {\r\n return global.DWA_BROWSER ? global.window.crypto : require(\"./crypto/node\").getCrypto();\r\n}\r\n\r\nexport function generateRandomBytes() {\r\n return global.DWA_BROWSER ? getCrypto().getRandomValues(new Uint8Array(1)) : getCrypto().randomBytes(1);\r\n}\r\n", "const uuid = \"[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}\";\r\n\r\nexport function isUuid(value: string): boolean {\r\n const match = new RegExp(uuid, \"i\").exec(value);\r\n return !!match;\r\n}\r\n\r\nexport function extractUuid(value: string): string | null {\r\n const match = new RegExp(\"^{?(\" + uuid + \")}?$\", \"i\").exec(value);\r\n return match ? match[1] : null;\r\n}\r\n\r\nexport function extractUuidFromUrl(url: string): string | null {\r\n const match = new RegExp(\"(\" + uuid + \")\\\\)$\", \"i\").exec(url);\r\n return match ? match[1] : null;\r\n}\r\n", "\uFEFFimport type * as Core from \"../types\";\r\nimport { generateRandomBytes } from \"../helpers/Crypto\";\r\nimport { isUuid, extractUuid } from \"../helpers/Regex\";\r\n\r\ndeclare var GetGlobalContext: any;\r\ndeclare var Xrm: any;\r\n\r\n// function isNodeEnv(): boolean {\r\n// // tslint:disable:strict-type-predicates\r\n// return Object.prototype.toString.call(typeof process !== \"undefined\" ? process : 0) === \"[object process]\";\r\n// }\r\n\r\n// function getGlobalObject(): T {\r\n// return (isNodeEnv() ? global : typeof window !== \"undefined\" ? window : typeof self !== \"undefined\" ? self : {}) as T;\r\n// }\r\n\r\nconst downloadChunkSize = 4194304;\r\n\r\nexport class Utility {\r\n /**\r\n * Builds parametes for a funciton. Returns '()' (if no parameters) or '([params])?[query]'\r\n *\r\n * @param {Object} [parameters] - Function's input parameters. Example: { param1: \"test\", param2: 3 }.\r\n * @returns {string}\r\n */\r\n static buildFunctionParameters(parameters?: any): Core.FunctionParameters {\r\n if (parameters) {\r\n const parameterNames = Object.keys(parameters);\r\n const functionParams: string[] = [];\r\n const urlQuery: string[] = [];\r\n\r\n for (let i = 1; i <= parameterNames.length; i++) {\r\n const parameterName = parameterNames[i - 1];\r\n let value = parameters[parameterName];\r\n\r\n if (value == null) continue;\r\n\r\n if (typeof value === \"string\" && !value.startsWith(\"Microsoft.Dynamics.CRM\") && !isUuid(value)) {\r\n value = `'${value}'`;\r\n } else if (typeof value === \"object\") {\r\n value = JSON.stringify(value);\r\n }\r\n\r\n functionParams.push(`${parameterName}=@p${i}`);\r\n urlQuery.push(`@p${i}=${extractUuid(value) || value}`);\r\n }\r\n\r\n return {\r\n key: `(${functionParams.join(\",\")})`,\r\n queryParams: urlQuery,\r\n };\r\n } else {\r\n return {\r\n key: \"()\",\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Parses a paging cookie returned in response\r\n *\r\n * @param {string} pageCookies - Page cookies returned in @Microsoft.Dynamics.CRM.fetchxmlpagingcookie.\r\n * @param {number} currentPageNumber - A current page number. Fix empty paging-cookie for complex fetch xmls.\r\n * @returns {{cookie: \"\", number: 0, next: 1}}\r\n */\r\n static getFetchXmlPagingCookie(pageCookies: string = \"\", currentPageNumber: number = 1): Core.FetchXmlCookie {\r\n //get the page cokies\r\n pageCookies = decodeURIComponent(decodeURIComponent(pageCookies));\r\n\r\n const info = /pagingcookie=\"()/.exec(pageCookies);\r\n\r\n if (info != null) {\r\n let page = parseInt(info[2]);\r\n return {\r\n cookie: info[1]\r\n .replace(//g, \">\")\r\n .replace(/\\\"/g, \"'\")\r\n .replace(/\\'/g, \"&\" + \"quot;\"),\r\n page: page,\r\n nextPage: page + 1,\r\n };\r\n } else {\r\n //http://stackoverflow.com/questions/41262772/execution-of-fetch-xml-using-web-api-dynamics-365 workaround\r\n return {\r\n cookie: \"\",\r\n page: currentPageNumber,\r\n nextPage: currentPageNumber + 1,\r\n };\r\n }\r\n }\r\n\r\n // static isNodeEnv = isNodeEnv;\r\n\r\n static downloadChunkSize = downloadChunkSize;\r\n\r\n /**\r\n * Converts a response to a reference object\r\n *\r\n * @param {Object} responseData - Response object\r\n * @returns {ReferenceObject}\r\n */\r\n static convertToReferenceObject(responseData: any): Core.ReferenceObject {\r\n const result = /\\/(\\w+)\\(([0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12})/i.exec(responseData[\"@odata.id\"]);\r\n return { id: result![2], collection: result![1], oDataContext: responseData[\"@odata.context\"] };\r\n }\r\n\r\n /**\r\n * Checks whether the value is JS Null.\r\n * @param {Object} value\r\n * @returns {boolean}\r\n */\r\n static isNull(value: any): boolean {\r\n return typeof value === \"undefined\" || value == null;\r\n }\r\n\r\n /** Generates UUID */\r\n static generateUUID(): string {\r\n return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) => (c ^ (generateRandomBytes()[0] & (15 >> (c / 4)))).toString(16));\r\n }\r\n\r\n static getXrmContext(): any {\r\n if (typeof GetGlobalContext !== \"undefined\") {\r\n return GetGlobalContext();\r\n } else {\r\n if (typeof Xrm !== \"undefined\") {\r\n //d365 v.9.0\r\n if (!Utility.isNull(Xrm.Utility) && !Utility.isNull(Xrm.Utility.getGlobalContext)) {\r\n return Xrm.Utility.getGlobalContext();\r\n } else if (!Utility.isNull(Xrm.Page) && !Utility.isNull(Xrm.Page.context)) {\r\n return Xrm.Page.context;\r\n }\r\n }\r\n }\r\n\r\n throw new Error(\r\n \"Xrm Context is not available. In most cases, it can be resolved by adding a reference to a ClientGlobalContext.js.aspx. Please refer to MSDN documentation for more details.\"\r\n );\r\n }\r\n\r\n // static getXrmUtility(): any {\r\n // return typeof Xrm !== \"undefined\" ? Xrm.Utility : null;\r\n // }\r\n\r\n static getClientUrl(): string {\r\n const context = Utility.getXrmContext();\r\n\r\n let clientUrl = context.getClientUrl();\r\n\r\n if (clientUrl.match(/\\/$/)) {\r\n clientUrl = clientUrl.substring(0, clientUrl.length - 1);\r\n }\r\n return clientUrl;\r\n }\r\n\r\n /**\r\n * Checks whether the app is currently running in a Dynamics Portals Environment.\r\n *\r\n * In that case we switch to the Web API for Dynamics Portals.\r\n * @returns {boolean}\r\n */\r\n static isRunningWithinPortals(): boolean {\r\n return global.DWA_BROWSER ? !!global.window.shell : false;\r\n }\r\n\r\n static isObject(obj: any): boolean {\r\n return typeof obj === \"object\" && !!obj && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== \"[object Date]\";\r\n }\r\n\r\n static copyObject(src: any, excludeProps?: string[]): T {\r\n let target = {};\r\n for (let prop in src) {\r\n if (src.hasOwnProperty(prop) && !excludeProps?.includes(prop)) {\r\n // if the value is a nested object, recursively copy all its properties\r\n if (Utility.isObject(src[prop])) {\r\n target[prop] = Utility.copyObject(src[prop]);\r\n } else if (Array.isArray(src[prop])) {\r\n target[prop] = src[prop].slice();\r\n } else {\r\n target[prop] = src[prop];\r\n }\r\n }\r\n }\r\n return target;\r\n }\r\n\r\n static copyRequest(src: any, excludeProps: string[] = []): Core.InternalRequest {\r\n //todo: do we need to include \"data\" in here?\r\n if (!excludeProps.includes(\"signal\")) excludeProps.push(\"signal\");\r\n\r\n const result = Utility.copyObject(src, excludeProps);\r\n result.signal = src.signal;\r\n\r\n return result;\r\n }\r\n\r\n static setFileChunk(request: Core.InternalRequest, fileBuffer: Uint8Array | Buffer, chunkSize: number, offset: number): void {\r\n offset = offset || 0;\r\n\r\n const count = offset + chunkSize > fileBuffer.length ? fileBuffer.length % chunkSize : chunkSize;\r\n\r\n let content: any;\r\n\r\n if (global.DWA_BROWSER) {\r\n content = new Uint8Array(count);\r\n for (let i = 0; i < count; i++) {\r\n content[i] = fileBuffer[offset + i];\r\n }\r\n } else {\r\n content = fileBuffer.slice(offset, offset + count);\r\n }\r\n\r\n request.data = content;\r\n request.contentRange = \"bytes \" + offset + \"-\" + (offset + count - 1) + \"/\" + fileBuffer.length;\r\n }\r\n\r\n static convertToFileBuffer(binaryString: string): Uint8Array | Buffer {\r\n if (!global.DWA_BROWSER) return Buffer.from(binaryString, \"binary\");\r\n\r\n const bytes = new Uint8Array(binaryString.length);\r\n for (var i = 0; i < binaryString.length; i++) {\r\n bytes[i] = binaryString.charCodeAt(i);\r\n }\r\n return bytes;\r\n }\r\n}\r\n", "\uFEFFimport { AccessToken } from \"../dynamics-web-api\";\r\nimport { extractUuid } from \"./Regex\";\r\n\r\nexport interface DynamicsWebApiError extends Error {\r\n status: number;\r\n}\r\n\r\nfunction throwParameterError(functionName: string, parameterName: string, type: string | null | undefined): void {\r\n throw new Error(\r\n type ? `${functionName} requires a ${parameterName} parameter to be of type ${type}.` : `${functionName} requires a ${parameterName} parameter.`\r\n );\r\n}\r\n\r\nexport class ErrorHelper {\r\n static handleErrorResponse(req): void {\r\n throw new Error(`Error: ${req.status}: ${req.message}`);\r\n }\r\n\r\n static parameterCheck(parameter: any, functionName: string, parameterName: string, type?: string): void {\r\n if (typeof parameter === \"undefined\" || parameter === null || parameter === \"\") {\r\n throwParameterError(functionName, parameterName, type);\r\n }\r\n }\r\n\r\n static stringParameterCheck(parameter: any, functionName: string, parameterName: string): void {\r\n if (typeof parameter !== \"string\") {\r\n throwParameterError(functionName, parameterName, \"String\");\r\n }\r\n }\r\n\r\n static maxLengthStringParameterCheck(parameter: string | null, functionName: string, parameterName: string, maxLength: number): void {\r\n if (!parameter) return;\r\n\r\n if (parameter.length > maxLength) {\r\n throw new Error(`${parameterName} has a ${maxLength} character limit.`);\r\n }\r\n }\r\n\r\n static arrayParameterCheck(parameter: any, functionName: string, parameterName: string): void {\r\n if (parameter.constructor !== Array) {\r\n throwParameterError(functionName, parameterName, \"Array\");\r\n }\r\n }\r\n\r\n static stringOrArrayParameterCheck(parameter: any, functionName: string, parameterName: string): void {\r\n if (parameter.constructor !== Array && typeof parameter !== \"string\") {\r\n throwParameterError(functionName, parameterName, \"String or Array\");\r\n }\r\n }\r\n\r\n static numberParameterCheck(parameter: any, functionName: string, parameterName: string): void {\r\n if (typeof parameter != \"number\") {\r\n if (typeof parameter === \"string\" && parameter) {\r\n if (!isNaN(parseInt(parameter))) {\r\n return;\r\n }\r\n }\r\n throwParameterError(functionName, parameterName, \"Number\");\r\n }\r\n }\r\n\r\n static batchIsEmpty(): Error[] {\r\n return [\r\n new Error(\r\n \"Payload of the batch operation is empty. Please make that you have other operations in between startBatch() and executeBatch() to successfuly build a batch payload.\"\r\n ),\r\n ];\r\n }\r\n\r\n static handleHttpError(parsedError: any, parameters?: any): DynamicsWebApiError {\r\n const error = new Error();\r\n\r\n Object.keys(parsedError).forEach((k) => {\r\n error[k] = parsedError[k];\r\n });\r\n\r\n if (parameters) {\r\n Object.keys(parameters).forEach((k) => {\r\n error[k] = parameters[k];\r\n });\r\n }\r\n\r\n return error;\r\n }\r\n\r\n static boolParameterCheck(parameter: any, functionName: string, parameterName: string): void {\r\n if (typeof parameter != \"boolean\") {\r\n throwParameterError(functionName, parameterName, \"Boolean\");\r\n }\r\n }\r\n\r\n /**\r\n * Private function used to check whether required parameter is a valid GUID\r\n * @param parameter The GUID parameter to check\r\n * @param functionName\r\n * @param parameterName\r\n * @returns\r\n */\r\n static guidParameterCheck(parameter: any, functionName: string, parameterName: string): string {\r\n const match = extractUuid(parameter);\r\n if (!match) throwParameterError(functionName, parameterName, \"GUID String\");\r\n\r\n return match!;\r\n }\r\n\r\n static keyParameterCheck(parameter: any, functionName: string, parameterName: string): string | undefined {\r\n try {\r\n ErrorHelper.stringParameterCheck(parameter, functionName, parameterName);\r\n\r\n //check if the param is a guid\r\n const match = extractUuid(parameter);\r\n if (match) return match;\r\n\r\n //check the alternate key\r\n const alternateKeys = parameter.split(\",\");\r\n\r\n if (alternateKeys.length) {\r\n for (let i = 0; i < alternateKeys.length; i++) {\r\n alternateKeys[i] = alternateKeys[i].trim().replace(/\"/g, \"'\");\r\n /^[\\w\\d\\_]+\\=(.+)$/i.exec(alternateKeys[i])![0];\r\n }\r\n }\r\n\r\n return alternateKeys.join(\",\");\r\n } catch (error) {\r\n throwParameterError(functionName, parameterName, \"String representing GUID or Alternate Key\");\r\n }\r\n }\r\n\r\n static callbackParameterCheck(callbackParameter: () => Promise, functionName: string, parameterName: string): void {\r\n if (typeof callbackParameter != \"function\") {\r\n throwParameterError(functionName, parameterName, \"Function\");\r\n }\r\n }\r\n\r\n static throwBatchIncompatible(functionName: string, isBatch: boolean): void {\r\n if (isBatch) {\r\n isBatch = false;\r\n throw new Error(functionName + \" cannot be used in a BATCH request.\");\r\n }\r\n }\r\n\r\n static throwBatchNotStarted(isBatch: boolean): void {\r\n if (!isBatch) {\r\n throw new Error(\r\n \"Batch operation has not been started. Please call a DynamicsWebApi.startBatch() function prior to calling DynamicsWebApi.executeBatch() to perform a batch request correctly.\"\r\n );\r\n }\r\n }\r\n}\r\n", "class DWA {\r\n\tstatic Prefer = class {\r\n\t\tstatic ReturnRepresentation: string = \"return=representation\";\r\n\t\tstatic Annotations = class {\r\n\t\t\tstatic AssociatedNavigationProperty: string = \"Microsoft.Dynamics.CRM.associatednavigationproperty\";\r\n\t\t\tstatic LookupLogicalName: string = \"Microsoft.Dynamics.CRM.lookuplogicalname\";\r\n\t\t\tstatic All: string = \"*\";\r\n\t\t\tstatic FormattedValue: string = \"OData.Community.Display.V1.FormattedValue\";\r\n\t\t\tstatic FetchXmlPagingCookie: string = \"Microsoft.Dynamics.CRM.fetchxmlpagingcookie\";\r\n\t\t};\r\n\t\tstatic IncludeAnnotations: string = \"odata.include-annotations\";\r\n\t\tstatic get(annotation: string) {\r\n\t\t\treturn `${DWA.Prefer.IncludeAnnotations}=\"${annotation}\"`;\r\n\t\t}\r\n\t};\r\n}\r\n\r\nexport { DWA };\r\n", "\uFEFFexport function dateReviver(key: string, value: any): Date {\r\n\tif (typeof value === \"string\") {\r\n\t\tconst a = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:Z|[-+]\\d{2}:\\d{2})$/.exec(value);\r\n\t\tif (a) {\r\n\t\t\treturn new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));\r\n\t\t}\r\n\t}\r\n\treturn value;\r\n}\r\n", "\uFEFFimport { DWA } from \"../../dwa\";\r\nimport { Utility } from \"../../utils/Utility\";\r\nimport { ErrorHelper, DynamicsWebApiError } from \"../../helpers/ErrorHelper\";\r\nimport { dateReviver } from \"./dateReviver\";\r\nimport type * as Core from \"../../types\";\r\nimport { extractUuidFromUrl } from \"../../helpers/Regex\";\r\n\r\nfunction getFormattedKeyValue(keyName: string, value: any): any[] {\r\n let newKey: string | null = null;\r\n if (keyName.indexOf(\"@\") !== -1) {\r\n const format = keyName.split(\"@\");\r\n switch (format[1]) {\r\n case \"odata.context\":\r\n newKey = \"oDataContext\";\r\n break;\r\n case \"odata.count\":\r\n newKey = \"oDataCount\";\r\n value = value != null ? parseInt(value) : 0;\r\n break;\r\n case \"odata.nextLink\":\r\n newKey = \"oDataNextLink\";\r\n break;\r\n case \"odata.deltaLink\":\r\n newKey = \"oDataDeltaLink\";\r\n break;\r\n case DWA.Prefer.Annotations.FormattedValue:\r\n newKey = format[0] + \"_Formatted\";\r\n break;\r\n case DWA.Prefer.Annotations.AssociatedNavigationProperty:\r\n newKey = format[0] + \"_NavigationProperty\";\r\n break;\r\n case DWA.Prefer.Annotations.LookupLogicalName:\r\n newKey = format[0] + \"_LogicalName\";\r\n break;\r\n }\r\n }\r\n\r\n return [newKey, value];\r\n}\r\n\r\n/**\r\n *\r\n * @param {any} object - parsed JSON object\r\n * @param {any} parseParams - parameters for parsing the response\r\n * @returns {any} parsed batch response\r\n */\r\nfunction parseData(object: any, parseParams?: any): any {\r\n if (parseParams) {\r\n if (parseParams.isRef && object[\"@odata.id\"] != null) {\r\n return Utility.convertToReferenceObject(object);\r\n }\r\n\r\n if (parseParams.toCount) {\r\n return getFormattedKeyValue(\"@odata.count\", object[\"@odata.count\"])[1] || 0;\r\n }\r\n }\r\n\r\n const keys = Object.keys(object);\r\n\r\n for (let i = 0; i < keys.length; i++) {\r\n const currentKey = keys[i];\r\n\r\n if (object[currentKey] != null) {\r\n if (object[currentKey].constructor === Array) {\r\n for (var j = 0; j < object[currentKey].length; j++) {\r\n object[currentKey][j] = parseData(object[currentKey][j]);\r\n }\r\n } else if (typeof object[currentKey] === \"object\") {\r\n parseData(object[currentKey]);\r\n }\r\n }\r\n\r\n //parse formatted values\r\n let formattedKeyValue = getFormattedKeyValue(currentKey, object[currentKey]);\r\n if (formattedKeyValue[0]) {\r\n object[formattedKeyValue[0]] = formattedKeyValue[1];\r\n }\r\n\r\n //parse aliased values\r\n if (currentKey.indexOf(\"_x002e_\") !== -1) {\r\n const aliasKeys = currentKey.split(\"_x002e_\");\r\n\r\n if (!object.hasOwnProperty(aliasKeys[0])) {\r\n object[aliasKeys[0]] = { _dwaType: \"alias\" };\r\n }\r\n //throw an error if there is already a property which is not an 'alias'\r\n else if (\r\n typeof object[aliasKeys[0]] !== \"object\" ||\r\n (typeof object[aliasKeys[0]] === \"object\" && !object[aliasKeys[0]].hasOwnProperty(\"_dwaType\"))\r\n ) {\r\n throw new Error(\"The alias name of the linked entity must be unique!\");\r\n }\r\n\r\n object[aliasKeys[0]][aliasKeys[1]] = object[currentKey];\r\n\r\n //aliases also contain formatted values\r\n formattedKeyValue = getFormattedKeyValue(aliasKeys[1], object[currentKey]);\r\n if (formattedKeyValue[0]) {\r\n object[aliasKeys[0]][formattedKeyValue[0]] = formattedKeyValue[1];\r\n }\r\n }\r\n }\r\n\r\n if (parseParams) {\r\n if (parseParams.hasOwnProperty(\"pageNumber\") && object[\"@\" + DWA.Prefer.Annotations.FetchXmlPagingCookie] != null) {\r\n object.PagingInfo = Utility.getFetchXmlPagingCookie(object[\"@\" + DWA.Prefer.Annotations.FetchXmlPagingCookie], parseParams.pageNumber);\r\n }\r\n }\r\n\r\n return object;\r\n}\r\n\r\nconst responseHeaderRegex = /^([^()<>@,;:\\\\\"\\/[\\]?={} \\t]+)\\s?:\\s?(.*)/;\r\n\r\n//partially taken from http://olingo.apache.org/doc/javascript/apidoc/batch.js.html\r\nfunction parseBatchHeaders(text: string): any {\r\n const ctx = { position: 0 };\r\n const headers = {};\r\n let parts;\r\n let line;\r\n let pos;\r\n\r\n do {\r\n pos = ctx.position;\r\n line = readLine(text, ctx);\r\n parts = responseHeaderRegex.exec(line);\r\n if (parts !== null) {\r\n headers[parts[1].toLowerCase()] = parts[2];\r\n } else {\r\n // Whatever was found is not a header, so reset the context position.\r\n ctx.position = pos;\r\n }\r\n } while (line && parts);\r\n\r\n return headers;\r\n}\r\n\r\n//partially taken from http://olingo.apache.org/doc/javascript/apidoc/batch.js.html\r\nfunction readLine(text: string, ctx: { position: number }): string | null {\r\n return readTo(text, ctx, \"\\r\\n\");\r\n}\r\n\r\n//partially taken from http://olingo.apache.org/doc/javascript/apidoc/batch.js.html\r\nfunction readTo(text: string, ctx: { position: number }, str: string): string | null {\r\n const start = ctx.position || 0;\r\n let end = text.length;\r\n if (str) {\r\n end = text.indexOf(str, start);\r\n if (end === -1) {\r\n return null;\r\n }\r\n ctx.position = end + str.length;\r\n } else {\r\n ctx.position = end;\r\n }\r\n\r\n return text.substring(start, end);\r\n}\r\n\r\n//partially taken from https://github.com/emiltholin/google-api-batch-utils\r\n/**\r\n *\r\n * @param {string} response - response that needs to be parsed\r\n * @param {Array} parseParams - parameters for parsing the response\r\n * @param {Number} [requestNumber] - number of the request\r\n * @returns {any} parsed batch response\r\n */\r\nfunction parseBatchResponse(response: string, parseParams: any, requestNumber: number = 0): (string | undefined | DynamicsWebApiError | Number)[] {\r\n // Not the same delimiter in the response as we specify ourselves in the request,\r\n // so we have to extract it.\r\n const delimiter = response.substr(0, response.indexOf(\"\\r\\n\"));\r\n const batchResponseParts = response.split(delimiter);\r\n // The first part will always be an empty string. Just remove it.\r\n batchResponseParts.shift();\r\n // The last part will be the \"--\". Just remove it.\r\n batchResponseParts.pop();\r\n\r\n let result: (string | undefined | DynamicsWebApiError | Number)[] = [];\r\n for (let i = 0; i < batchResponseParts.length; i++) {\r\n let batchResponse = batchResponseParts[i];\r\n if (batchResponse.indexOf(\"--changesetresponse_\") > -1) {\r\n batchResponse = batchResponse.trim();\r\n const batchToProcess = batchResponse.substring(batchResponse.indexOf(\"\\r\\n\") + 1).trim();\r\n\r\n result = result.concat(parseBatchResponse(batchToProcess, parseParams, requestNumber));\r\n } else {\r\n //check http status\r\n const httpStatusReg = /HTTP\\/?\\s*[\\d.]*\\s+(\\d{3})\\s+([\\w\\s]*)$/gm.exec(batchResponse);\r\n //todo: add error handler for httpStatus and httpStatusMessage; remove \"!\" operator\r\n const httpStatus = parseInt(httpStatusReg![1]);\r\n const httpStatusMessage = httpStatusReg![2].trim();\r\n\r\n const responseData = batchResponse.substring(batchResponse.indexOf(\"{\"), batchResponse.lastIndexOf(\"}\") + 1);\r\n\r\n if (!responseData) {\r\n if (/Content-Type: text\\/plain/i.test(batchResponse)) {\r\n const plainContentReg = /\\w+$/gi.exec(batchResponse.trim());\r\n const plainContent = plainContentReg && plainContentReg.length ? plainContentReg[0] : undefined;\r\n\r\n //check if a plain content is a number or not\r\n result.push(isNaN(Number(plainContent)) ? plainContent : Number(plainContent));\r\n } else {\r\n if (parseParams.length && parseParams[requestNumber] && parseParams[requestNumber].hasOwnProperty(\"valueIfEmpty\")) {\r\n result.push(parseParams[requestNumber].valueIfEmpty);\r\n } else {\r\n const entityUrl = /OData-EntityId.+/i.exec(batchResponse);\r\n\r\n if (entityUrl && entityUrl.length) {\r\n const guidResult = extractUuidFromUrl(entityUrl[0]);\r\n result.push(guidResult ? guidResult : undefined);\r\n } else {\r\n result.push(undefined);\r\n }\r\n }\r\n }\r\n } else {\r\n const parsedResponse = parseData(JSON.parse(responseData, dateReviver), parseParams[requestNumber]);\r\n\r\n if (httpStatus >= 400) {\r\n const responseHeaders = parseBatchHeaders(\r\n //todo: add error handler for httpStatusReg; remove \"!\" operator\r\n batchResponse.substring(batchResponse.indexOf(httpStatusReg![0]) + httpStatusReg![0].length + 1, batchResponse.indexOf(\"{\"))\r\n );\r\n\r\n result.push(\r\n ErrorHelper.handleHttpError(parsedResponse, {\r\n status: httpStatus,\r\n statusText: httpStatusMessage,\r\n statusMessage: httpStatusMessage,\r\n headers: responseHeaders,\r\n })\r\n );\r\n } else {\r\n result.push(parsedResponse);\r\n }\r\n }\r\n }\r\n\r\n requestNumber++;\r\n }\r\n\r\n return result;\r\n}\r\n\r\nfunction base64ToString(base64: string): string {\r\n return global.DWA_BROWSER ? global.window.atob(base64) : Buffer.from(base64, \"base64\").toString(\"binary\");\r\n}\r\n\r\nfunction parseFileResponse(response: any, responseHeaders: any, parseParams: any): Core.FileParseResult {\r\n let data = response;\r\n\r\n if (parseParams.hasOwnProperty(\"parse\")) {\r\n data = JSON.parse(data).value;\r\n data = base64ToString(data);\r\n }\r\n\r\n var parseResult: Core.FileParseResult = {\r\n value: data,\r\n };\r\n\r\n if (responseHeaders[\"x-ms-file-name\"]) parseResult.fileName = responseHeaders[\"x-ms-file-name\"];\r\n\r\n if (responseHeaders[\"x-ms-file-size\"]) parseResult.fileSize = parseInt(responseHeaders[\"x-ms-file-size\"]);\r\n\r\n if (hasHeader(responseHeaders, \"Location\")) parseResult.location = getHeader(responseHeaders, \"Location\");\r\n\r\n return parseResult;\r\n}\r\n\r\nfunction hasHeader(headers: any, name: string): boolean {\r\n return headers.hasOwnProperty(name) || headers.hasOwnProperty(name.toLowerCase());\r\n}\r\n\r\nfunction getHeader(headers: any, name: string): string {\r\n if (headers[name]) return headers[name];\r\n\r\n return headers[name.toLowerCase()];\r\n}\r\n\r\n/**\r\n *\r\n * @param {string} response - response that needs to be parsed\r\n * @param {Array} responseHeaders - response headers\r\n * @param {Array} parseParams - parameters for parsing the response\r\n * @returns {any} parsed response\r\n */\r\nexport function parseResponse(response: string, responseHeaders: any, parseParams: any[]): any {\r\n let parseResult: any = undefined;\r\n if (response.length) {\r\n if (response.indexOf(\"--batchresponse_\") > -1) {\r\n const batch = parseBatchResponse(response, parseParams);\r\n\r\n parseResult = parseParams.length === 1 && parseParams[0].convertedToBatch ? batch[0] : batch;\r\n } else {\r\n if (hasHeader(responseHeaders, \"Content-Disposition\")) {\r\n parseResult = parseFileResponse(response, responseHeaders, parseParams[0]);\r\n } else {\r\n const contentType = getHeader(responseHeaders, \"Content-Type\");\r\n if (contentType.startsWith(\"application/json\")) {\r\n parseResult = parseData(JSON.parse(response, dateReviver), parseParams[0]);\r\n } else {\r\n parseResult = isNaN(Number(response)) ? response : Number(response);\r\n }\r\n }\r\n }\r\n } else {\r\n if (parseParams.length && parseParams[0].hasOwnProperty(\"valueIfEmpty\")) {\r\n parseResult = parseParams[0].valueIfEmpty;\r\n } else if (hasHeader(responseHeaders, \"OData-EntityId\")) {\r\n const entityUrl = getHeader(responseHeaders, \"OData-EntityId\");\r\n\r\n const guidResult = extractUuidFromUrl(entityUrl);\r\n\r\n if (guidResult) {\r\n parseResult = guidResult;\r\n }\r\n } else if (hasHeader(responseHeaders, \"Location\")) {\r\n parseResult = {\r\n location: getHeader(responseHeaders, \"Location\"),\r\n };\r\n\r\n if (responseHeaders[\"x-ms-chunk-size\"]) parseResult.chunkSize = parseInt(responseHeaders[\"x-ms-chunk-size\"]);\r\n }\r\n }\r\n\r\n return parseResult;\r\n}\r\n", "\uFEFFexport function parseResponseHeaders(headerStr: string): any {\r\n\tconst headers = {};\r\n\tif (!headerStr) {\r\n\t\treturn headers;\r\n\t}\r\n\tconst headerPairs = headerStr.split(\"\\u000d\\u000a\");\r\n\tfor (let i = 0, ilen = headerPairs.length; i < ilen; i++) {\r\n\t\tconst headerPair = headerPairs[i];\r\n\t\tconst index = headerPair.indexOf(\"\\u003a\\u0020\");\r\n\t\tif (index > 0) {\r\n\t\t\theaders[headerPair.substring(0, index)] = headerPair.substring(index + 2);\r\n\t\t}\r\n\t}\r\n\treturn headers;\r\n}\r\n", "\uFEFFimport type * as Core from \"../types\";\r\nimport { ErrorHelper } from \"./../helpers/ErrorHelper\";\r\nimport { parseResponse } from \"./helpers/parseResponse\";\r\nimport { parseResponseHeaders } from \"./helpers/parseResponseHeaders\";\r\n\r\nexport function executeRequest(options: Core.RequestOptions): Promise {\r\n return new Promise((resolve, reject) => {\r\n _executeRequest(options, resolve, reject);\r\n });\r\n}\r\n\r\nfunction _executeRequest(\r\n options: Core.RequestOptions,\r\n successCallback: (response: Core.WebApiResponse) => void,\r\n errorCallback: (error: Core.WebApiErrorResponse | Core.WebApiErrorResponse[]) => void\r\n) {\r\n const data = options.data;\r\n const headers = options.headers;\r\n const responseParams = options.responseParams;\r\n const signal = options.abortSignal;\r\n\r\n if (signal?.aborted) {\r\n errorCallback(\r\n ErrorHelper.handleHttpError({\r\n name: \"AbortError\",\r\n code: 20,\r\n message: \"The user aborted a request.\",\r\n })\r\n );\r\n\r\n return;\r\n }\r\n\r\n let request = new XMLHttpRequest();\r\n request.open(options.method, options.uri, options.isAsync || false);\r\n\r\n //set additional headers\r\n for (let key in headers) {\r\n request.setRequestHeader(key, headers[key]);\r\n }\r\n\r\n request.onreadystatechange = function () {\r\n if (request.readyState === 4) {\r\n if (signal) signal.removeEventListener(\"abort\", abort);\r\n\r\n switch (request.status) {\r\n case 200: // Success with content returned in response body.\r\n case 201: // Success with content returned in response body.\r\n case 204: // Success with no content returned in response body.\r\n case 206: // Success with partial content.\r\n case 304: {\r\n // Success with Not Modified\r\n const responseHeaders = parseResponseHeaders(request.getAllResponseHeaders());\r\n const responseData = parseResponse(request.responseText, responseHeaders, responseParams[options.requestId]);\r\n\r\n const response = {\r\n data: responseData,\r\n headers: responseHeaders,\r\n status: request.status,\r\n };\r\n\r\n request = null as any;\r\n\r\n successCallback(response);\r\n break;\r\n }\r\n case 0:\r\n break; //response will be handled by onerror\r\n default:\r\n if (!request) break; //response was handled somewhere else\r\n\r\n // All other statuses are error cases.\r\n let error;\r\n let headers;\r\n try {\r\n headers = parseResponseHeaders(request.getAllResponseHeaders());\r\n const errorParsed = parseResponse(request.responseText, headers, responseParams[options.requestId]);\r\n\r\n if (Array.isArray(errorParsed)) {\r\n errorCallback(errorParsed);\r\n break;\r\n }\r\n\r\n error = errorParsed.error;\r\n } catch (e) {\r\n if (request.response.length > 0) {\r\n error = { message: request.response };\r\n } else {\r\n error = { message: \"Unexpected Error\" };\r\n }\r\n }\r\n\r\n const errorParameters = {\r\n status: request.status,\r\n statusText: request.statusText,\r\n headers: headers,\r\n };\r\n\r\n request = null as any;\r\n\r\n errorCallback(ErrorHelper.handleHttpError(error, errorParameters));\r\n\r\n break;\r\n }\r\n }\r\n };\r\n\r\n if (options.timeout) {\r\n request.timeout = options.timeout;\r\n }\r\n\r\n request.onerror = function () {\r\n const headers = parseResponseHeaders(request.getAllResponseHeaders());\r\n errorCallback(\r\n ErrorHelper.handleHttpError({\r\n status: request.status,\r\n statusText: request.statusText,\r\n message: request.responseText || \"Network Error\",\r\n headers: headers,\r\n })\r\n );\r\n request = null as any;\r\n };\r\n\r\n request.ontimeout = function () {\r\n const headers = parseResponseHeaders(request.getAllResponseHeaders());\r\n errorCallback(\r\n ErrorHelper.handleHttpError({\r\n name: \"TimeoutError\",\r\n status: request.status,\r\n statusText: request.statusText,\r\n message: request.responseText || \"Request Timed Out\",\r\n headers: headers,\r\n })\r\n );\r\n request = null as any;\r\n };\r\n\r\n //browser abort\r\n request.onabort = function () {\r\n if (!request) return;\r\n\r\n const headers = parseResponseHeaders(request.getAllResponseHeaders());\r\n errorCallback(\r\n ErrorHelper.handleHttpError({\r\n status: request.status,\r\n statusText: request.statusText,\r\n message: \"Request aborted\",\r\n headers: headers,\r\n })\r\n );\r\n request = null as any;\r\n };\r\n\r\n //manual abort/cancellation\r\n const abort = () => {\r\n if (!request) return;\r\n\r\n const headers = parseResponseHeaders(request.getAllResponseHeaders());\r\n\r\n errorCallback(\r\n ErrorHelper.handleHttpError({\r\n name: \"AbortError\",\r\n code: 20,\r\n status: request.status,\r\n statusText: request.statusText,\r\n message: \"The user aborted a request.\",\r\n headers: headers,\r\n })\r\n );\r\n\r\n request.abort();\r\n\r\n request = null as any;\r\n };\r\n\r\n if (signal) {\r\n signal.addEventListener(\"abort\", abort);\r\n }\r\n\r\n data ? request.send(data) : request.send();\r\n\r\n //called for testing\r\n if (XhrWrapper.afterSendEvent) XhrWrapper.afterSendEvent();\r\n}\r\n\r\n/**\r\n * Sends a request to given URL with given parameters\r\n */\r\nexport class XhrWrapper {\r\n //for testing\r\n static afterSendEvent: () => void;\r\n}\r\n", "import { Utility } from \"./Utility\";\r\nimport { ErrorHelper } from \"../helpers/ErrorHelper\";\r\nimport { ApiConfig, Config } from \"../dynamics-web-api\";\r\n\r\ntype ApiType = \"dataApi\" | \"searchApi\";\r\n\r\nexport interface InternalApiConfig extends ApiConfig {\r\n url: string;\r\n}\r\n\r\nexport interface InternalConfig extends Config {\r\n dataApi: InternalApiConfig;\r\n searchApi: InternalApiConfig;\r\n}\r\n\r\nconst getApiUrl = (serverUrl: string | undefined | null, apiConfig: ApiConfig): string => {\r\n if (Utility.isRunningWithinPortals()) {\r\n return new URL(\"_api\", global.window.location.origin).toString() + \"/\";\r\n } else {\r\n if (!serverUrl) serverUrl = Utility.getClientUrl();\r\n return new URL(`api/${apiConfig.path}/v${apiConfig.version}`, serverUrl).toString() + \"/\";\r\n }\r\n};\r\n\r\nconst mergeApiConfigs = (apiConfig: ApiConfig | undefined, apiType: ApiType, internalConfig: InternalConfig): void => {\r\n const internalApiConfig = internalConfig[apiType] as InternalApiConfig;\r\n\r\n if (apiConfig?.version) {\r\n ErrorHelper.stringParameterCheck(apiConfig.version, \"DynamicsWebApi.setConfig\", `config.${apiType}.version`);\r\n internalApiConfig.version = apiConfig.version;\r\n }\r\n\r\n if (apiConfig?.path) {\r\n ErrorHelper.stringParameterCheck(apiConfig.path, \"DynamicsWebApi.setConfig\", `config.${apiType}.path`);\r\n internalApiConfig.path = apiConfig.path;\r\n }\r\n\r\n internalApiConfig.url = getApiUrl(internalConfig.serverUrl, internalApiConfig);\r\n};\r\n\r\nexport class ConfigurationUtility {\r\n static mergeApiConfigs = mergeApiConfigs;\r\n\r\n static merge(internalConfig: InternalConfig, config?: Config): void {\r\n if (config?.serverUrl) {\r\n ErrorHelper.stringParameterCheck(config.serverUrl, \"DynamicsWebApi.setConfig\", \"config.serverUrl\");\r\n internalConfig.serverUrl = config.serverUrl;\r\n }\r\n\r\n mergeApiConfigs(config?.dataApi, \"dataApi\", internalConfig);\r\n mergeApiConfigs(config?.searchApi, \"searchApi\", internalConfig);\r\n\r\n if (config?.impersonate) {\r\n internalConfig.impersonate = ErrorHelper.guidParameterCheck(config.impersonate, \"DynamicsWebApi.setConfig\", \"config.impersonate\");\r\n }\r\n\r\n if (config?.impersonateAAD) {\r\n internalConfig.impersonateAAD = ErrorHelper.guidParameterCheck(config.impersonateAAD, \"DynamicsWebApi.setConfig\", \"config.impersonateAAD\");\r\n }\r\n\r\n if (config?.onTokenRefresh) {\r\n ErrorHelper.callbackParameterCheck(config.onTokenRefresh, \"DynamicsWebApi.setConfig\", \"config.onTokenRefresh\");\r\n internalConfig.onTokenRefresh = config.onTokenRefresh;\r\n }\r\n\r\n if (config?.includeAnnotations) {\r\n ErrorHelper.stringParameterCheck(config.includeAnnotations, \"DynamicsWebApi.setConfig\", \"config.includeAnnotations\");\r\n internalConfig.includeAnnotations = config.includeAnnotations;\r\n }\r\n\r\n if (config?.timeout) {\r\n ErrorHelper.numberParameterCheck(config.timeout, \"DynamicsWebApi.setConfig\", \"config.timeout\");\r\n internalConfig.timeout = config.timeout;\r\n }\r\n\r\n if (config?.maxPageSize) {\r\n ErrorHelper.numberParameterCheck(config.maxPageSize, \"DynamicsWebApi.setConfig\", \"config.maxPageSize\");\r\n internalConfig.maxPageSize = config.maxPageSize;\r\n }\r\n\r\n if (config?.returnRepresentation) {\r\n ErrorHelper.boolParameterCheck(config.returnRepresentation, \"DynamicsWebApi.setConfig\", \"config.returnRepresentation\");\r\n internalConfig.returnRepresentation = config.returnRepresentation;\r\n }\r\n\r\n if (config?.useEntityNames) {\r\n ErrorHelper.boolParameterCheck(config.useEntityNames, \"DynamicsWebApi.setConfig\", \"config.useEntityNames\");\r\n internalConfig.useEntityNames = config.useEntityNames;\r\n }\r\n\r\n if (config?.headers) {\r\n internalConfig.headers = config.headers;\r\n }\r\n\r\n if (!global.DWA_BROWSER && config?.proxy) {\r\n ErrorHelper.parameterCheck(config.proxy, \"DynamicsWebApi.setConfig\", \"config.proxy\");\r\n\r\n if (config.proxy.url) {\r\n ErrorHelper.stringParameterCheck(config.proxy.url, \"DynamicsWebApi.setConfig\", \"config.proxy.url\");\r\n\r\n if (config.proxy.auth) {\r\n ErrorHelper.parameterCheck(config.proxy.auth, \"DynamicsWebApi.setConfig\", \"config.proxy.auth\");\r\n ErrorHelper.stringParameterCheck(config.proxy.auth.username, \"DynamicsWebApi.setConfig\", \"config.proxy.auth.username\");\r\n ErrorHelper.stringParameterCheck(config.proxy.auth.password, \"DynamicsWebApi.setConfig\", \"config.proxy.auth.password\");\r\n }\r\n }\r\n\r\n internalConfig.proxy = config.proxy;\r\n }\r\n }\r\n\r\n static default(): InternalConfig {\r\n return {\r\n serverUrl: null,\r\n impersonate: null,\r\n impersonateAAD: null,\r\n onTokenRefresh: null,\r\n includeAnnotations: null,\r\n maxPageSize: null,\r\n returnRepresentation: null,\r\n proxy: null,\r\n dataApi: {\r\n path: \"data\",\r\n version: \"9.2\",\r\n url: \"\"\r\n },\r\n searchApi: {\r\n path: \"search\",\r\n version: \"1.0\",\r\n url: \"\"\r\n },\r\n };\r\n }\r\n}\r\n", "\uFEFFimport { ConfigurationUtility } from \"./utils/Config\";\r\nimport { Utility } from \"./utils/Utility\";\r\nimport { ErrorHelper } from \"./helpers/ErrorHelper\";\r\nimport { RequestClient } from \"./client/RequestClient\";\r\nimport type { InternalRequest, WebApiResponse } from \"./types\";\r\n\r\n/**\r\n * Microsoft Dynamics CRM Web API helper library written in JavaScript.\r\n * It is compatible with: Dynamics 365 (online), Dynamics 365 (on-premise), Dynamics CRM 2016, Dynamics CRM Online.\r\n */\r\nexport class DynamicsWebApi {\r\n private _config = ConfigurationUtility.default();\r\n private _isBatch = false;\r\n private _batchRequestId: string | null = null;\r\n\r\n /**\r\n * Initializes a new instance of DynamicsWebApi\r\n * @param config - Configuration object\r\n */\r\n constructor(config?: Config) {\r\n ConfigurationUtility.merge(this._config, config);\r\n }\r\n\r\n /**\r\n\t * Merges provided configuration properties with an existing one.\r\n\t *\r\n\t * @param {DynamicsWebApi.Config} config - Configuration\r\n\t * @example\r\n\t dynamicsWebApi.setConfig({ serverUrl: 'https://contoso.api.crm.dynamics.com/' });\r\n\t */\r\n setConfig = (config: Config) => ConfigurationUtility.merge(this._config, config);\r\n\r\n private _makeRequest = async (request: InternalRequest): Promise => {\r\n request.isBatch = this._isBatch;\r\n if (this._batchRequestId) request.requestId = this._batchRequestId;\r\n return RequestClient.makeRequest(request, this._config);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to create a new record.\r\n *\r\n * @param {DWARequest} request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n * @example\r\n *const lead = {\r\n * subject: \"Test WebAPI\",\r\n * firstname: \"Test\",\r\n * lastname: \"WebAPI\",\r\n * jobtitle: \"Title\"\r\n *};\r\n *\r\n *const request = {\r\n * data: lead,\r\n * collection: \"leads\",\r\n * returnRepresentation: true\r\n *}\r\n *\r\n *const response = await dynamicsWebApi.create(request);\r\n *\r\n */\r\n create = async (request: CreateRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.create\", \"request\");\r\n\r\n let internalRequest: InternalRequest;\r\n\r\n if (!(request).functionName) {\r\n internalRequest = Utility.copyRequest(request);\r\n internalRequest.functionName = \"create\";\r\n } else internalRequest = request;\r\n\r\n internalRequest.method = \"POST\";\r\n\r\n const response = await this._makeRequest(internalRequest);\r\n\r\n return response?.data;\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve a record.\r\n *\r\n * @param {DWARequest} request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n * @example\r\n *const request = {\r\n * key: '7d577253-3ef0-4a0a-bb7f-8335c2596e70',\r\n * collection: \"leads\",\r\n * select: [\"fullname\", \"subject\"],\r\n * ifnonematch: 'W/\"468026\"',\r\n * includeAnnotations: \"OData.Community.Display.V1.FormattedValue\"\r\n *};\r\n *\r\n *const response = await dynamicsWebApi.retrieve(request);\r\n */\r\n retrieve = async (request: RetrieveRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.retrieve\", \"request\");\r\n\r\n let internalRequest: InternalRequest;\r\n\r\n if (!(request).functionName) {\r\n internalRequest = Utility.copyRequest(request);\r\n internalRequest.functionName = \"retrieve\";\r\n } else internalRequest = request;\r\n\r\n internalRequest.method = \"GET\";\r\n internalRequest.responseParameters = {\r\n isRef: internalRequest.select?.length === 1 && internalRequest.select[0].endsWith(\"/$ref\"),\r\n };\r\n\r\n const response = await this._makeRequest(internalRequest);\r\n return response?.data;\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to update a record.\r\n *\r\n * @param {DWARequest} request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n update = async (request: UpdateRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.update\", \"request\");\r\n\r\n let internalRequest: InternalRequest;\r\n\r\n if (!(request).functionName) {\r\n internalRequest = Utility.copyRequest(request);\r\n internalRequest.functionName = \"update\";\r\n } else internalRequest = request;\r\n\r\n //Metadata definitions, cannot be updated using \"PATCH\" method\r\n if (!internalRequest.method)\r\n internalRequest.method = /EntityDefinitions|RelationshipDefinitions|GlobalOptionSetDefinitions/.test(internalRequest.collection || \"\")\r\n ? \"PUT\"\r\n : \"PATCH\";\r\n\r\n internalRequest.responseParameters = { valueIfEmpty: true };\r\n\r\n if (internalRequest.ifmatch == null) {\r\n internalRequest.ifmatch = \"*\"; //to prevent upsert\r\n }\r\n\r\n //copy locally\r\n const ifmatch = internalRequest.ifmatch;\r\n\r\n try {\r\n const response = await this._makeRequest(internalRequest);\r\n return response?.data;\r\n } catch (error: any) {\r\n if (ifmatch && error.status === 412) {\r\n //precondition failed - not updated\r\n return false; //todo: check this\r\n }\r\n //rethrow error otherwise\r\n throw error;\r\n }\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to update a single value in the record.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n updateSingleProperty = async (request: UpdateSinglePropertyRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.updateSingleProperty\", \"request\");\r\n ErrorHelper.parameterCheck(request.fieldValuePair, \"DynamicsWebApi.updateSingleProperty\", \"request.fieldValuePair\");\r\n\r\n var field = Object.keys(request.fieldValuePair)[0];\r\n var fieldValue = request.fieldValuePair[field];\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.navigationProperty = field;\r\n internalRequest.data = { value: fieldValue };\r\n internalRequest.functionName = \"updateSingleProperty\";\r\n internalRequest.method = \"PUT\";\r\n\r\n delete internalRequest[\"fieldValuePair\"];\r\n\r\n const response = await this._makeRequest(internalRequest);\r\n return response?.data;\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to delete a record.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n deleteRecord = async (request: DeleteRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.deleteRecord\", \"request\");\r\n\r\n let internalRequest: InternalRequest;\r\n\r\n if (!(request).functionName) {\r\n internalRequest = Utility.copyRequest(request);\r\n internalRequest.functionName = \"deleteRecord\";\r\n } else internalRequest = request;\r\n\r\n internalRequest.method = \"DELETE\";\r\n internalRequest.responseParameters = { valueIfEmpty: true };\r\n\r\n //copy locally\r\n const ifmatch = internalRequest.ifmatch;\r\n\r\n try {\r\n const response = await this._makeRequest(internalRequest);\r\n return response?.data;\r\n } catch (error: any) {\r\n if (ifmatch && error.status === 412) {\r\n //precondition failed - not updated\r\n return false; //todo: check this\r\n }\r\n //rethrow error otherwise\r\n throw error;\r\n }\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to upsert a record.\r\n *\r\n * @param {DWARequest} request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n upsert = async (request: UpsertRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.upsert\", \"request\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.method = \"PATCH\";\r\n internalRequest.functionName = \"upsert\";\r\n\r\n //copy locally\r\n const ifnonematch = internalRequest.ifnonematch;\r\n const ifmatch = internalRequest.ifmatch;\r\n try {\r\n const response = await this._makeRequest(internalRequest);\r\n return response?.data;\r\n } catch (error: any) {\r\n if (ifnonematch && error.status === 412) {\r\n //if prevent update\r\n return null; //todo: check this\r\n } else if (ifmatch && error.status === 404) {\r\n //if prevent create\r\n return null; //todo: check this\r\n }\r\n //rethrow error otherwise\r\n throw error;\r\n }\r\n };\r\n\r\n private _uploadFileChunk = async (request: InternalRequest, fileBytes: Uint8Array | Buffer, chunkSize: number, offset: number = 0): Promise => {\r\n // offset = offset || 0;\r\n Utility.setFileChunk(request, fileBytes, chunkSize, offset);\r\n\r\n await this._makeRequest(request);\r\n\r\n offset += chunkSize;\r\n if (offset <= fileBytes.length) {\r\n return this._uploadFileChunk(request, fileBytes, chunkSize, offset);\r\n }\r\n };\r\n\r\n /**\r\n * Upload file to a File Attribute\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n */\r\n uploadFile = async (request: UploadRequest): Promise => {\r\n ErrorHelper.throwBatchIncompatible(\"DynamicsWebApi.uploadFile\", this._isBatch);\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.uploadFile\", \"request\");\r\n\r\n const internalRequest = Utility.copyRequest(request, [\"data\"]);\r\n internalRequest.method = \"PATCH\";\r\n internalRequest.functionName = \"uploadFile\";\r\n internalRequest.transferMode = \"chunked\";\r\n\r\n const response = await this._makeRequest(internalRequest);\r\n\r\n internalRequest.url = response?.data.location;\r\n delete internalRequest.transferMode;\r\n delete internalRequest.fieldName;\r\n delete internalRequest.fileName;\r\n return this._uploadFileChunk(internalRequest, request.data, response?.data.chunkSize);\r\n };\r\n\r\n private _downloadFileChunk = async (\r\n request: InternalRequest,\r\n bytesDownloaded: number = 0,\r\n // fileSize: number = 0,\r\n data: string = \"\"\r\n ): Promise => {\r\n // bytesDownloaded = bytesDownloaded || 0;\r\n // fileSize = fileSize || 0;\r\n // data = data || \"\";\r\n\r\n request.range = \"bytes=\" + bytesDownloaded + \"-\" + (bytesDownloaded + Utility.downloadChunkSize - 1);\r\n request.downloadSize = \"full\";\r\n\r\n const response = await this._makeRequest(request);\r\n\r\n request.url = response?.data.location;\r\n data += response?.data.value;\r\n\r\n bytesDownloaded += Utility.downloadChunkSize;\r\n\r\n if (bytesDownloaded <= response?.data.fileSize) {\r\n return this._downloadFileChunk(request, bytesDownloaded, data);\r\n }\r\n\r\n return {\r\n fileName: response?.data.fileName,\r\n fileSize: response?.data.fileSize,\r\n data: Utility.convertToFileBuffer(data),\r\n };\r\n };\r\n\r\n /**\r\n * Download a file from a File Attribute\r\n * @param request - An object that represents all possible options for a current request.\r\n */\r\n downloadFile = (request: DownloadRequest): Promise => {\r\n ErrorHelper.throwBatchIncompatible(\"DynamicsWebApi.downloadFile\", this._isBatch);\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.downloadFile\", \"request\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.method = \"GET\";\r\n internalRequest.functionName = \"downloadFile\";\r\n internalRequest.responseParameters = { parse: true };\r\n\r\n return this._downloadFileChunk(internalRequest);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve records.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @param {string} [nextPageLink] - Use the value of the @odata.nextLink property with a new GET request to return the next page of data. Pass null to retrieveMultipleOptions.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveMultiple = async (request: RetrieveMultipleRequest, nextPageLink?: string): Promise> => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.retrieveMultiple\", \"request\");\r\n\r\n let internalRequest: InternalRequest;\r\n\r\n if (!(request).functionName) {\r\n internalRequest = Utility.copyRequest(request);\r\n internalRequest.functionName = \"retrieveMultiple\";\r\n } else internalRequest = request;\r\n\r\n internalRequest.method = \"GET\";\r\n\r\n if (nextPageLink) {\r\n ErrorHelper.stringParameterCheck(nextPageLink, \"DynamicsWebApi.retrieveMultiple\", \"nextPageLink\");\r\n internalRequest.url = nextPageLink;\r\n }\r\n\r\n const response = await this._makeRequest(internalRequest);\r\n\r\n return response?.data;\r\n };\r\n\r\n private _retrieveAllRequest = async (request: RetrieveMultipleRequest, nextPageLink?: string, records: any[] = []): Promise> => {\r\n const response = await this.retrieveMultiple(request, nextPageLink);\r\n records = records.concat(response.value);\r\n\r\n const pageLink = response.oDataNextLink;\r\n\r\n if (pageLink) {\r\n return this._retrieveAllRequest(request, pageLink, records);\r\n }\r\n\r\n const result: AllResponse = { value: records };\r\n\r\n if (response.oDataDeltaLink) {\r\n result[\"@odata.deltaLink\"] = response.oDataDeltaLink;\r\n result.oDataDeltaLink = response.oDataDeltaLink;\r\n }\r\n\r\n return result;\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve all records.\r\n *\r\n * @param {DWARequest} request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveAll = (request: RetrieveMultipleRequest): Promise> => {\r\n ErrorHelper.throwBatchIncompatible(\"DynamicsWebApi.retrieveAll\", this._isBatch);\r\n return this._retrieveAllRequest(request);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to count records. IMPORTANT! The count value does not represent the total number of entities in the system. It is limited by the maximum number of entities that can be returned. Returns: Number\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n count = async (request: CountRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.count\", \"request\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.method = \"GET\";\r\n internalRequest.functionName = \"count\";\r\n\r\n if (internalRequest.filter?.length) {\r\n internalRequest.count = true;\r\n } else {\r\n internalRequest.navigationProperty = \"$count\";\r\n }\r\n\r\n internalRequest.responseParameters = { toCount: internalRequest.count };\r\n\r\n //if filter has not been specified then simplify the request\r\n const response = await this._makeRequest(internalRequest);\r\n return response?.data;\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to count records. Returns: Number\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n countAll = async (request: CountAllRequest): Promise => {\r\n ErrorHelper.throwBatchIncompatible(\"DynamicsWebApi.countAll\", this._isBatch);\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.countAll\", \"request\");\r\n\r\n const response = await this._retrieveAllRequest(request);\r\n\r\n return response ? (response.value ? response.value.length : 0) : 0;\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to execute FetchXml to retrieve records. Returns: DWA.Types.FetchXmlResponse\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n fetch = async (request: FetchXmlRequest): Promise> => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.fetch\", \"request\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.method = \"GET\";\r\n internalRequest.functionName = \"fetch\";\r\n\r\n ErrorHelper.stringParameterCheck(internalRequest.fetchXml, \"DynamicsWebApi.fetch\", \"request.fetchXml\");\r\n\r\n //only add paging if there is no top\r\n if (internalRequest.fetchXml && !/^(request: FetchAllRequest): Promise> => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.fetchAll\", \"request\");\r\n\r\n const _executeFetchXmlAll = async (request: FetchXmlRequest, records: any[] = []): Promise> => {\r\n // records = records || [];\r\n\r\n const response = await this.fetch(request);\r\n\r\n records = records.concat(response.value);\r\n\r\n if (response.PagingInfo) {\r\n request.pageNumber = response.PagingInfo.nextPage;\r\n request.pagingCookie = response.PagingInfo.cookie;\r\n\r\n return _executeFetchXmlAll(request, records);\r\n }\r\n\r\n return { value: records };\r\n };\r\n\r\n ErrorHelper.throwBatchIncompatible(\"DynamicsWebApi.fetchAll\", this._isBatch);\r\n return _executeFetchXmlAll(request);\r\n };\r\n\r\n /**\r\n * Associate for a collection-valued navigation property. (1:N or N:N)\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n associate = async (request: AssociateRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.associate\", \"request\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.method = \"POST\";\r\n internalRequest.functionName = \"associate\";\r\n\r\n ErrorHelper.stringParameterCheck(request.relatedCollection, \"DynamicsWebApi.associate\", \"request.relatedcollection\");\r\n ErrorHelper.stringParameterCheck(request.relationshipName, \"DynamicsWebApi.associate\", \"request.relationshipName\");\r\n const primaryKey = ErrorHelper.keyParameterCheck(request.primaryKey, \"DynamicsWebApi.associate\", \"request.primaryKey\");\r\n const relatedKey = ErrorHelper.keyParameterCheck(request.relatedKey, \"DynamicsWebApi.associate\", \"request.relatedKey\");\r\n\r\n internalRequest.navigationProperty = request.relationshipName + \"/$ref\";\r\n internalRequest.key = primaryKey;\r\n internalRequest.data = { \"@odata.id\": `${request.relatedCollection}(${relatedKey})` };\r\n\r\n await this._makeRequest(internalRequest);\r\n };\r\n\r\n /**\r\n * Disassociate for a collection-valued navigation property.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n disassociate = async (request: DisassociateRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.disassociate\", \"request\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.method = \"DELETE\";\r\n internalRequest.functionName = \"disassociate\";\r\n\r\n ErrorHelper.stringParameterCheck(request.relationshipName, \"DynamicsWebApi.disassociate\", \"request.relationshipName\");\r\n const primaryKey = ErrorHelper.keyParameterCheck(request.primaryKey, \"DynamicsWebApi.disassociate\", \"request.primaryKey\");\r\n const relatedKey = ErrorHelper.keyParameterCheck(request.relatedKey, \"DynamicsWebApi.disassociate\", \"request.relatedId\");\r\n\r\n internalRequest.key = primaryKey;\r\n internalRequest.navigationProperty = `${request.relationshipName}(${relatedKey})/$ref`;\r\n\r\n await this._makeRequest(internalRequest);\r\n };\r\n\r\n /**\r\n * Associate for a single-valued navigation property. (1:N)\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n associateSingleValued = async (request: AssociateSingleValuedRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.associateSingleValued\", \"request\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.method = \"PUT\";\r\n internalRequest.functionName = \"associateSingleValued\";\r\n\r\n const primaryKey = ErrorHelper.keyParameterCheck(request.primaryKey, \"DynamicsWebApi.associateSingleValued\", \"request.primaryKey\");\r\n const relatedKey = ErrorHelper.keyParameterCheck(request.relatedKey, \"DynamicsWebApi.associateSingleValued\", \"request.relatedKey\");\r\n ErrorHelper.stringParameterCheck(request.navigationProperty, \"DynamicsWebApi.associateSingleValued\", \"request.navigationProperty\");\r\n ErrorHelper.stringParameterCheck(request.relatedCollection, \"DynamicsWebApi.associateSingleValued\", \"request.relatedcollection\");\r\n\r\n internalRequest.navigationProperty += \"/$ref\";\r\n internalRequest.key = primaryKey;\r\n internalRequest.data = { \"@odata.id\": `${request.relatedCollection}(${relatedKey})` };\r\n\r\n await this._makeRequest(internalRequest);\r\n };\r\n\r\n /**\r\n * Removes a reference to an entity for a single-valued navigation property. (1:N)\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n disassociateSingleValued = async (request: DisassociateSingleValuedRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.disassociateSingleValued\", \"request\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.method = \"DELETE\";\r\n internalRequest.functionName = \"disassociateSingleValued\";\r\n\r\n const primaryKey = ErrorHelper.keyParameterCheck(request.primaryKey, \"DynamicsWebApi.disassociateSingleValued\", \"request.primaryKey\");\r\n ErrorHelper.stringParameterCheck(request.navigationProperty, \"DynamicsWebApi.disassociateSingleValued\", \"request.navigationProperty\");\r\n\r\n internalRequest.navigationProperty += \"/$ref\";\r\n internalRequest.key = primaryKey;\r\n\r\n await this._makeRequest(internalRequest);\r\n };\r\n\r\n /**\r\n * Calls a Web API function\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n callFunction: CallFunction = async (request: string | BoundFunctionRequest | UnboundFunctionRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, `DynamicsWebApi.callFunction`, \"request\");\r\n\r\n const getFunctionName = (request: BoundFunctionRequest | UnboundFunctionRequest) => request.name || request.functionName;\r\n\r\n const isObject = typeof request !== \"string\";\r\n const functionName = isObject ? getFunctionName(request) : request;\r\n const parameterName = isObject ? \"request.name\" : \"name\";\r\n const internalRequest: InternalRequest = isObject ? Utility.copyObject(request, [\"name\"]) : { functionName: functionName };\r\n\r\n ErrorHelper.stringParameterCheck(functionName, `DynamicsWebApi.callFunction`, parameterName);\r\n\r\n const functionParameters = Utility.buildFunctionParameters(internalRequest.parameters);\r\n\r\n internalRequest.method = \"GET\";\r\n internalRequest.addPath = functionName + functionParameters.key;\r\n internalRequest.queryParams = functionParameters.queryParams;\r\n internalRequest._isUnboundRequest = !internalRequest.collection;\r\n internalRequest.functionName = \"callFunction\";\r\n\r\n const response = await this._makeRequest(internalRequest);\r\n return response?.data;\r\n };\r\n\r\n /**\r\n * Calls a Web API action\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n callAction: CallAction = async (\r\n request: BoundActionRequest | UnboundActionRequest\r\n ): Promise => {\r\n ErrorHelper.parameterCheck(request, `DynamicsWebApi.callAction`, \"request\");\r\n ErrorHelper.stringParameterCheck(request.actionName, `DynamicsWebApi.callAction`, \"request.actionName\");\r\n\r\n const internalRequest = Utility.copyRequest(request, [\"action\"]);\r\n internalRequest.method = \"POST\";\r\n internalRequest.functionName = \"callAction\";\r\n\r\n internalRequest.addPath = request.actionName;\r\n internalRequest._isUnboundRequest = !internalRequest.collection;\r\n internalRequest.data = request.action;\r\n\r\n const response = await this._makeRequest(internalRequest);\r\n return response?.data;\r\n };\r\n /**\r\n * Sends an asynchronous request to create an entity definition.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n createEntity = (request: CreateEntityRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, `DynamicsWebApi.createEntity`, \"request\");\r\n ErrorHelper.parameterCheck(request.data, \"DynamicsWebApi.createEntity\", \"request.data\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.collection = \"EntityDefinitions\";\r\n internalRequest.functionName = \"createEntity\";\r\n\r\n return this.create(internalRequest);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to update an entity definition.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n updateEntity = (request: UpdateEntityRequest): Promise => {\r\n ErrorHelper.parameterCheck(request, \"DynamicsWebApi.updateEntity\", \"request\");\r\n ErrorHelper.parameterCheck(request.data, \"DynamicsWebApi.updateEntity\", \"request.data\");\r\n ErrorHelper.guidParameterCheck(request.data.MetadataId, \"DynamicsWebApi.updateEntity\", \"request.data.MetadataId\");\r\n\r\n const internalRequest = Utility.copyRequest(request);\r\n internalRequest.collection = \"EntityDefinitions\";\r\n internalRequest.key = internalRequest.data.MetadataId;\r\n internalRequest.functionName = \"updateEntity\";\r\n internalRequest.method = \"PUT\";\r\n\r\n return this.update(internalRequest);\r\n };\r\n\r\n /**\r\n * Sends an asynchronous request to retrieve a specific entity definition.\r\n *\r\n * @param request - An object that represents all possible options for a current request.\r\n * @returns {Promise} D365 Web Api Response\r\n */\r\n retrieveEntity = (request: RetrieveEntityRequest): Promise