New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

dynamics-web-api

Package Overview
Dependencies
Maintainers
1
Versions
88
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

dynamics-web-api - npm Package Compare versions

Comparing version 1.3.4 to 1.4.0

2

dist/dwa.js

@@ -1,2 +0,2 @@

/*! dwa v1.3.4 (c) 2017 Aleksandr Rogov */
/*! dwa v1.4.0 (c) 2017 Aleksandr Rogov */
(function webpackUniversalModuleDefinition(root, factory) {

@@ -3,0 +3,0 @@ if(typeof exports === 'object' && typeof module === 'object')

@@ -1,2 +0,2 @@

/*! dynamics-web-api-callbacks v1.3.4 (c) 2017 Aleksandr Rogov */
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("DynamicsWebApi",[],t):"object"==typeof exports?exports.DynamicsWebApi=t():e.DynamicsWebApi=t()}(this,function(){return function(e){function t(r){if(a[r])return a[r].exports;var n=a[r]={i:r,l:!1,exports:{}};return e[r].call(n.exports,n,n.exports,t),n.l=!0,n.exports}var a={};return t.m=e,t.c=a,t.i=function(e){return e},t.d=function(e,a,r){t.o(e,a)||Object.defineProperty(e,a,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var a=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(a,"a",a),a},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=6)}([function(e,t){var a={Types:{ResponseBase:function(){this.oDataContext=""},Response:function(){a.Types.ResponseBase.call(this),this.value={}},ReferenceResponse:function(){a.Types.ResponseBase.call(this),this.id="",this.collection=""},MultipleResponse:function(){a.Types.ResponseBase.call(this),this.oDataNextLink="",this.oDataCount=0,this.value=[]},FetchXmlResponse:function(){a.Types.ResponseBase.call(this),this.value=[],this.PagingInfo={cookie:"",page:0,nextPage:1}}},Prefer:{ReturnRepresentation:"return=representation",Annotations:{AssociatedNavigationProperty:"Microsoft.Dynamics.CRM.associatednavigationproperty",LookupLogicalName:"Microsoft.Dynamics.CRM.lookuplogicalname",All:"*",FormattedValue:"OData.Community.Display.V1.FormattedValue",FetchXmlPagingCookie:"Microsoft.Dynamics.CRM.fetchxmlpagingcookie"}}};e.exports=a},function(e,t){function a(e,t,a){throw new Error(a?e+" requires the "+t+" parameter to be of type "+a:e+" requires the "+t+" parameter.")}var r={handleErrorResponse:function(e){throw new Error("Error: "+e.status+": "+e.message)},parameterCheck:function(e,t,r,n){void 0!==e&&null!==e&&""!=e||a(t,r,n)},stringParameterCheck:function(e,t,r){"string"!=typeof e&&a(t,r,"String")},arrayParameterCheck:function(e,t,r){e.constructor!==Array&&a(t,r,"Array")},stringOrArrayParameterCheck:function(e,t,r){e.constructor!==Array&&"string"!=typeof e&&a(t,r,"String or Array")},numberParameterCheck:function(e,t,r){if("number"!=typeof e){if("string"==typeof e&&e&&!isNaN(parseInt(e)))return;a(t,r,"Number")}},boolParameterCheck:function(e,t,r){"boolean"!=typeof e&&a(t,r,"Boolean")},guidParameterCheck:function(e,t,r){try{return/[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}/i.exec(e)[0]}catch(e){a(t,r,"GUID String")}},keyParameterCheck:function(e,t,n){try{r.stringParameterCheck(e,t,n);var i=/[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}/i.exec(e);if(i)return i[0];var c=e.split(",");if(c.length)for(var s=0;s<c.length;s++)c[s]=c[s].trim(),/^[\w\d\_]+\='[^\'\r\n]+'$/i.exec(c[s])[0];return c.join(",")}catch(e){a(t,n,"String representing GUID or Alternate Key")}},callbackParameterCheck:function(e,t,r){"function"!=typeof e&&a(t,r,"Function")}};e.exports=r},function(e,t){String.prototype.endsWith=function(e,t){var a=this.toString();("number"!=typeof t||!isFinite(t)||Math.floor(t)!==t||t>a.length)&&(t=a.length),t-=e.length;var r=a.lastIndexOf(e,t);return-1!==r&&r===t},String.prototype.startsWith=function(e,t){return t=t||0,this.substr(t,e.length)===e}},function(e,t,a){function r(){var e=(new Date).getTime();return"undefined"!=typeof performance&&"function"==typeof performance.now&&(e+=performance.now()),"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var a=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"===t?a:3&a|8).toString(16)})}function n(e){return e.Accept="application/json",e["OData-MaxVersion"]="4.0",e["OData-Version"]="4.0",e["Content-Type"]="application/json; charset=utf-8",e}function i(e,t){var a;return e&&(a=JSON.stringify(e,function(e,a){return e.endsWith("@odata.bind")&&"string"==typeof a&&(/\(\{[\w\d-]+\}\)/g.test(a)&&(a=a.replace(/(.+)\(\{([\w\d-]+)\}\)/g,"$1($2)")),a.startsWith(t.webApiUrl)||(a=t.webApiUrl+a.replace(/^\\/,""))),a}),a=a.replace(/[\u007F-\uFFFF]/g,function(e){return"\\u"+("0000"+e.charCodeAt(0).toString(16)).substr(-4)})),a}a(0);e.exports=function(e,t,c,s,o,l,u,p){o||(o={}),o=n(o);var m=i(s,c);if(t.length>2e3){var h="dwa_batch_"+r(),y=[];y.push("--"+h),y.push("Content-Type: application/http"),y.push("Content-Transfer-Encoding: binary\n"),y.push(e+" "+c.webApiUrl+t+" HTTP/1.1");for(var f in o)y.push(f+": "+o[f]),delete o[f];y.push("\n--"+h+"--"),m=y.join("\n"),o=n(o),o["Content-Type"]="multipart/mixed;boundary="+h,t="$batch",e="POST"}c.impersonate&&!o.MSCRMCallerID&&(o.MSCRMCallerID=c.impersonate);var d;"undefined"!=typeof XMLHttpRequest&&(d=a(10));var b=function(a){a&&(o||(o={}),o.Authorization="Bearer "+a.accessToken),d(e,c.webApiUrl+t,m,o,l,u,p)};c.onTokenRefresh&&(!o||o&&!o.Authorization)?c.onTokenRefresh(b):b()}},function(e,t,a){function r(e,t,a,n,i){var o={},l=[];if(n=null!=n?n:"&",e){e.navigationProperty&&(c.stringParameterCheck(e.navigationProperty,"DynamicsWebApi."+t,"request.navigationProperty"),a+="/"+e.navigationProperty),null!=e.select&&e.select.length&&(c.arrayParameterCheck(e.select,"DynamicsWebApi."+t,"request.select"),"retrieve"==t&&1==e.select.length&&e.select[0].endsWith("/$ref")?a+="/"+e.select[0]:(e.select[0].startsWith("/")&&"retrieve"==t&&(null==e.navigationProperty?a+=e.select.shift():e.select.shift()),e.select.length&&l.push("$select="+e.select.join(",")))),e.filter&&(c.stringParameterCheck(e.filter,"DynamicsWebApi."+t,"request.filter"),l.push("$filter="+e.filter)),e.savedQuery&&l.push("savedQuery="+c.guidParameterCheck(e.savedQuery,"DynamicsWebApi."+t,"request.savedQuery")),e.userQuery&&l.push("userQuery="+c.guidParameterCheck(e.userQuery,"DynamicsWebApi."+t,"request.userQuery")),e.count&&(c.boolParameterCheck(e.count,"DynamicsWebApi."+t,"request.count"),l.push("$count="+e.count)),e.top&&e.top>0&&(c.numberParameterCheck(e.top,"DynamicsWebApi."+t,"request.top"),l.push("$top="+e.top)),null!=e.orderBy&&e.orderBy.length&&(c.arrayParameterCheck(e.orderBy,"DynamicsWebApi."+t,"request.orderBy"),l.push("$orderby="+e.orderBy.join(",")));var u=s(e,t,i);if(u.length&&(o.Prefer=u),null!=e.ifmatch&&null!=e.ifnonematch)throw new Error("DynamicsWebApi."+t+". Either one of request.ifmatch or request.ifnonematch parameters should be used in a call, not both.");if(e.ifmatch&&(c.stringParameterCheck(e.ifmatch,"DynamicsWebApi."+t,"request.ifmatch"),o["If-Match"]=e.ifmatch),e.ifnonematch&&(c.stringParameterCheck(e.ifnonematch,"DynamicsWebApi."+t,"request.ifnonematch"),o["If-None-Match"]=e.ifnonematch),e.impersonate&&(c.stringParameterCheck(e.impersonate,"DynamicsWebApi."+t,"request.impersonate"),o.MSCRMCallerID=c.guidParameterCheck(e.impersonate,"DynamicsWebApi."+t,"request.impersonate")),e.token&&(c.stringParameterCheck(e.token,"DynamicsWebApi."+t,"request.token"),o.Authorization="Bearer "+e.token),e.duplicateDetection&&(c.boolParameterCheck(e.duplicateDetection,"DynamicsWebApi."+t,"request.duplicateDetection"),o["MSCRM.SuppressDuplicateDetection"]="false"),e.expand&&e.expand.length)if(c.stringOrArrayParameterCheck(e.expand,"DynamicsWebApi."+t,"request.expand"),"string"==typeof e.expand)l.push("$expand="+e.expand);else{for(var p=[],m=0;m<e.expand.length;m++)if(e.expand[m].property){var h=r(e.expand[m],t+" $expand",null,";"),y=h.query;y&&y.length&&(y="("+y+")"),p.push(e.expand[m].property+y)}p.length&&l.push("$expand="+p.join(","))}}return{url:a,query:l.join(n),headers:o}}function n(e){return["EntityDefinitions"].indexOf(e)>-1?e:e.toLowerCase()}function i(e,t,a){e.collection?c.stringParameterCheck(e.collection,"DynamicsWebApi."+t,"request.collection"):c.parameterCheck(e.collection,"DynamicsWebApi."+t,"request.collection");var i=n(e.collection);e.key?e.key=c.keyParameterCheck(e.key,"DynamicsWebApi."+t,"request.key"):e.id&&(e.key=c.guidParameterCheck(e.id,"DynamicsWebApi."+t,"request.id")),e.key&&(i+="("+e.key+")");var s=r(e,t,i,"&",a);return s.query&&(s.url+="?"+encodeURI(s.query)),e.hasOwnProperty("async")&&null!=e.async?(c.boolParameterCheck(e.async,"DynamicsWebApi."+t,"request.async"),s.async=e.async):s.async=!0,{url:s.url,headers:s.headers,async:s.async}}var c=(a(0),a(1)),s=a(12),o={convertRequestOptions:r,convertRequest:i};e.exports=o},function(e,t,a){var r={buildFunctionParameters:a(11),getFetchXmlPagingCookie:a(14),convertToReferenceObject:a(13)};e.exports=r},function(e,t,a){function r(e){var t={webApiVersion:"8.0",webApiUrl:"",impersonate:null,onTokenRefresh:null,includeAnnotations:null,maxPageSize:null,returnRepresentation:null};e||(e=t);var a=function(){if("undefined"!=typeof GetGlobalContext)return GetGlobalContext();if("undefined"!=typeof Xrm)return Xrm.Page.context;throw new Error("Xrm Context is not available.")},l=function(){var e=a();if(e){var t=e.getClientUrl();return t.match(/\/$/)&&(t=t.substring(0,t.length-1)),t}return""},u=function(){return l()+"/api/data/v"+t.webApiVersion+"/"};this.setConfig=function(e){e.webApiVersion&&(s.stringParameterCheck(e.webApiVersion,"DynamicsWebApi.setConfig","config.webApiVersion"),t.webApiVersion=e.webApiVersion),e.webApiUrl?(s.stringParameterCheck(e.webApiUrl,"DynamicsWebApi.setConfig","config.webApiUrl"),t.webApiUrl=e.webApiUrl):t.webApiUrl=u(),e.impersonate&&(t.impersonate=s.guidParameterCheck(e.impersonate,"DynamicsWebApi.setConfig","config.impersonate")),e.onTokenRefresh&&(s.callbackParameterCheck(e.onTokenRefresh,"DynamicsWebApi.setConfig","config.onTokenRefresh"),t.onTokenRefresh=e.onTokenRefresh),e.includeAnnotations&&(s.stringParameterCheck(e.includeAnnotations,"DynamicsWebApi.setConfig","config.includeAnnotations"),t.includeAnnotations=e.includeAnnotations),e.maxPageSize&&(s.numberParameterCheck(e.maxPageSize,"DynamicsWebApi.setConfig","config.maxPageSize"),t.maxPageSize=e.maxPageSize),e.returnRepresentation&&(s.boolParameterCheck(e.returnRepresentation,"DynamicsWebApi.setConfig","config.returnRepresentation"),t.returnRepresentation=e.returnRepresentation)},this.setConfig(e);var p=function(e,a,r,n,i,c,s){o(e,a,t,r,n,i,c,s)};this.create=function(e,a,r,n,i,o){s.parameterCheck(e,"DynamicsWebApi.create","object"),s.stringParameterCheck(a,"DynamicsWebApi.create","collection"),s.callbackParameterCheck(r,"DynamicsWebApi.create","successCallback"),s.callbackParameterCheck(n,"DynamicsWebApi.create","errorCallback"),i&&s.stringOrArrayParameterCheck(i,"DynamicsWebApi.create","prefer"),o&&s.arrayParameterCheck(o,"DynamicsWebApi.create","select");var l={collection:a,select:o,prefer:i},u=c.convertRequest(l,"create",t),m=function(e){if(e.data)r(e.data);else{var t=e.headers["OData-EntityId"]?e.headers["OData-EntityId"]:e.headers["odata-entityid"],a=/[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}/i.exec(t)[0];r(a)}};p("POST",u.url,e,u.headers,m,n,u.async)},this.updateRequest=function(e,a,r){s.parameterCheck(e,"DynamicsWebApi.update","request"),s.parameterCheck(e.entity,"DynamicsWebApi.update","request.entity"),s.callbackParameterCheck(a,"DynamicsWebApi.update","successCallback"),s.callbackParameterCheck(r,"DynamicsWebApi.update","errorCallback");var n=c.convertRequest(e,"update",t);null==e.ifmatch&&(n.headers["If-Match"]="*");var i=function(e){a(e.data?e.data:!0)},o=e.ifmatch,l=function(e){o&&412==e.status?a(!1):r(e)};p("PATCH",n.url,e.entity,n.headers,i,l,n.async)},this.update=function(e,t,a,r,n,i,c){s.stringParameterCheck(e,"DynamicsWebApi.update","key"),e=s.keyParameterCheck(e,"DynamicsWebApi.update","key"),s.parameterCheck(a,"DynamicsWebApi.update","object"),s.stringParameterCheck(t,"DynamicsWebApi.update","collection"),s.callbackParameterCheck(r,"DynamicsWebApi.update","successCallback"),s.callbackParameterCheck(n,"DynamicsWebApi.update","errorCallback"),i&&s.stringOrArrayParameterCheck(i,"DynamicsWebApi.update","prefer"),c&&s.arrayParameterCheck(c,"DynamicsWebApi.update","select");var o={collection:t,key:e,select:c,prefer:i,entity:a};this.updateRequest(o,r,n)},this.updateSingleProperty=function(e,a,r,n,i,o,l){s.stringParameterCheck(e,"DynamicsWebApi.updateSingleProperty","key"),e=s.keyParameterCheck(e,"DynamicsWebApi.updateSingleProperty","key"),s.parameterCheck(r,"DynamicsWebApi.updateSingleProperty","keyValuePair"),s.stringParameterCheck(a,"DynamicsWebApi.updateSingleProperty","collection"),s.callbackParameterCheck(n,"DynamicsWebApi.updateSingleProperty","successCallback"),s.callbackParameterCheck(i,"DynamicsWebApi.updateSingleProperty","errorCallback"),o&&s.stringOrArrayParameterCheck(o,"DynamicsWebApi.updateSingleProperty","prefer"),l&&s.arrayParameterCheck(l,"DynamicsWebApi.updateSingleProperty","select");var u=Object.keys(r)[0],m=r[u],h={collection:a,key:e,select:l,prefer:o,navigationProperty:u},y=c.convertRequest(h,"updateSingleProperty",t),f=function(e){e.data?n(e.data):n()};p("PUT",y.url,{value:m},y.headers,f,i,y.async)},this.deleteRequest=function(e,a,r){s.parameterCheck(e,"DynamicsWebApi.delete","request"),s.callbackParameterCheck(a,"DynamicsWebApi.delete","successCallback"),s.callbackParameterCheck(r,"DynamicsWebApi.delete","errorCallback");var n=c.convertRequest(e,"delete",t),i=function(){a(!0)},o=e.ifmatch,l=function(e){o&&412==e.status?a(!1):r(e)};p("DELETE",n.url,null,n.headers,i,l,n.async)},this.deleteRecord=function(e,t,a,r,n){s.stringParameterCheck(e,"DynamicsWebApi.delete","key"),e=s.keyParameterCheck(e,"DynamicsWebApi.delete","key"),s.stringParameterCheck(t,"DynamicsWebApi.delete","collection"),s.callbackParameterCheck(a,"DynamicsWebApi.delete","successCallback"),s.callbackParameterCheck(r,"DynamicsWebApi.delete","errorCallback"),null!=n&&s.stringParameterCheck(n,"DynamicsWebApi.delete","propertyName");var i=t.toLowerCase()+"("+e+")";null!=n&&(i+="/"+n),p("DELETE",i,null,null,function(e){a()},r,!0)},this.retrieveRequest=function(e,a,r){s.parameterCheck(e,"DynamicsWebApi.retrieve","request"),s.callbackParameterCheck(a,"DynamicsWebApi.retrieve","successCallback"),s.callbackParameterCheck(r,"DynamicsWebApi.retrieve","errorCallback");var n=c.convertRequest(e,"retrieve",t),o=e.select,l=function(e){a(null!=o&&1==o.length&&o[0].endsWith("/$ref")&&null!=e.data["@odata.id"]?i.convertToReferenceObject(e.data):e.data)};p("GET",n.url,null,n.headers,l,r,n.async)},this.retrieve=function(e,t,a,r,n,i){s.stringParameterCheck(e,"DynamicsWebApi.retrieve","key"),e=s.keyParameterCheck(e,"DynamicsWebApi.retrieve","key"),s.stringParameterCheck(t,"DynamicsWebApi.retrieve","collection"),s.callbackParameterCheck(a,"DynamicsWebApi.retrieve","successCallback"),s.callbackParameterCheck(r,"DynamicsWebApi.retrieve","errorCallback"),n&&n.length&&s.arrayParameterCheck(n,"DynamicsWebApi.retrieve","select"),i&&i.length&&s.stringOrArrayParameterCheck(i,"DynamicsWebApi.retrieve","expand");var c={collection:t,key:e,select:n,expand:i};this.retrieveRequest(c,a,r)},this.upsertRequest=function(e,a,r){s.parameterCheck(e,"DynamicsWebApi.upsert","request"),s.parameterCheck(e.entity,"DynamicsWebApi.upsert","request.entity"),s.callbackParameterCheck(a,"DynamicsWebApi.upsert","successCallback"),s.callbackParameterCheck(r,"DynamicsWebApi.upsert","errorCallback");var n=c.convertRequest(e,"upsert",t),i=e.ifnonematch,o=e.ifmatch,l=function(e){if(e.headers["OData-EntityId"]||e.headers["odata-entityid"]){var t=e.headers["OData-EntityId"]?e.headers["OData-EntityId"]:e.headers["odata-entityid"],r=/[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}/i.exec(t)[0];a(r)}else e.data?a(e.data):a()},u=function(e){i&&412==e.status?a():o&&404==e.status?a():r(e)};p("PATCH",n.url,e.entity,n.headers,l,u,n.async)},this.upsert=function(e,t,a,r,n,i,c){s.stringParameterCheck(e,"DynamicsWebApi.upsert","key"),e=s.keyParameterCheck(e,"DynamicsWebApi.upsert","key"),s.parameterCheck(a,"DynamicsWebApi.upsert","object"),s.stringParameterCheck(t,"DynamicsWebApi.upsert","collection"),s.callbackParameterCheck(r,"DynamicsWebApi.upsert","successCallback"),s.callbackParameterCheck(n,"DynamicsWebApi.upsert","errorCallback"),i&&s.stringOrArrayParameterCheck(i,"DynamicsWebApi.upsert","prefer"),c&&s.arrayParameterCheck(c,"DynamicsWebApi.upsert","select");var o={collection:t,key:e,select:c,prefer:i,entity:a};this.upsertRequest(o,r,n)},this.count=function(e,t,a,r){if(null!=r&&(null==r||r.length))return this.retrieveMultipleRequest({collection:e,filter:r,count:!0},function(e){t(e.oDataCount?e.oDataCount:0)},a);s.stringParameterCheck(e,"DynamicsWebApi.count","collection"),s.callbackParameterCheck(t,"DynamicsWebApi.count","successCallback"),s.callbackParameterCheck(a,"DynamicsWebApi.count","errorCallback");var n=function(e){t(e.data?parseInt(e.data):0)};p("GET",e.toLowerCase()+"/$count",null,null,n,a)},this.countAll=function(e,t,a,r,n){return this.retrieveAllRequest({collection:e,filter:r,select:n},function(e){t(e&&e.value?e.value.length:0)},a)},this.retrieveMultiple=function(e,t,a,r,n,i){return this.retrieveMultipleRequest({collection:e,select:r,filter:n},t,a,i)},this.retrieveAll=function(e,t,a,r,n){return h({collection:e,select:r,filter:n},t,a)};var m=function(e,a,r,n){s.callbackParameterCheck(a,"DynamicsWebApi.retrieveMultiple","successCallback"),s.callbackParameterCheck(r,"DynamicsWebApi.retrieveMultiple","errorCallback"),n&&!e.collection&&(e.collection="any");var i=c.convertRequest(e,"retrieveMultiple",t);n&&(s.stringParameterCheck(n,"DynamicsWebApi.retrieveMultiple","nextPageLink"),i.url=n.replace(t.webApiUrl,""));var o=e.count,l=function(e){o&&(e.data.oDataCount=e.data.oDataCount||0),a(e.data)};p("GET",i.url,null,i.headers,l,r,i.async)};this.retrieveMultipleRequest=m;var h=function(e,t,a,r,n){var n=n||[];m(e,function(r){n=n.concat(r.value),r.oDataNextLink?h(e,t,a,r.oDataNextLink,n):t({value:n})},a,r)};this.retrieveAllRequest=function(e,t,a){h(e,t,a)};var y=function(e,a,r,o,l,u,m,h){s.stringParameterCheck(e,"DynamicsWebApi.executeFetchXml","collection"),s.stringParameterCheck(a,"DynamicsWebApi.executeFetchXml","fetchXml"),s.callbackParameterCheck(r,"DynamicsWebApi.executeFetchXml","successCallback"),s.callbackParameterCheck(o,"DynamicsWebApi.executeFetchXml","errorCallback"),null==u&&(u=1),s.numberParameterCheck(u,"DynamicsWebApi.executeFetchXml","pageNumber");var y='$1 page="'+u+'"';null!=m&&(s.stringParameterCheck(m,"DynamicsWebApi.executeFetchXml","pagingCookie"),y+=' paging-cookie="'+m+'"'),a=a.replace(/^(<fetch[\w\d\s'"=]+)/,y),l&&s.stringParameterCheck(l,"DynamicsWebApi.executeFetchXml","includeAnnotations"),h&&(h=s.guidParameterCheck(h,"DynamicsWebApi.executeFetchXml","impersonateUserId"));var f={collection:e,includeAnnotations:l,impersonate:h},d=c.convertRequest(f,"executeFetchXml",t),b=encodeURIComponent(a),k=function(e){null!=e.data["@"+n.Prefer.Annotations.FetchXmlPagingCookie]&&(e.data.PagingInfo=i.getFetchXmlPagingCookie(e.data["@"+n.Prefer.Annotations.FetchXmlPagingCookie],u)),r(e.data)};p("GET",d.url+"?fetchXml="+b,null,d.headers,k,o,d.async)};this.fetch=this.executeFetchXml=y;var f=function(e,t,a,r,n,i,c,s,o){var o=o||[];y(e,t,function(i){o=o.concat(i.value),i.PagingInfo?f(e,t,a,r,n,i.PagingInfo.nextPage,i.PagingInfo.cookie,s,o):a({value:o})},r,n,i,c,s)};this.fetchAll=this.executeFetchXmlAll=function(e,t,a,r,n,i){return f(e,t,a,r,n,null,null,i)},this.associate=function(e,a,r,n,i,c,o,l){s.stringParameterCheck(e,"DynamicsWebApi.associate","primarycollection"),s.stringParameterCheck(n,"DynamicsWebApi.associate","relatedcollection"),s.stringParameterCheck(r,"DynamicsWebApi.associate","relationshipName"),a=s.guidParameterCheck(a,"DynamicsWebApi.associate","primaryId"),i=s.guidParameterCheck(i,"DynamicsWebApi.associate","relatedId"),s.callbackParameterCheck(c,"DynamicsWebApi.associate","successCallback"),s.callbackParameterCheck(o,"DynamicsWebApi.associate","errorCallback");var u=function(){c()},m={};null!=l&&(l=s.guidParameterCheck(l,"DynamicsWebApi.associate","impersonateUserId"),m.MSCRMCallerID=l);var h={"@odata.id":t.webApiUrl+n+"("+i+")"};p("POST",e+"("+a+")/"+r+"/$ref",h,m,u,o)},this.disassociate=function(e,t,a,r,n,i,c){s.stringParameterCheck(e,"DynamicsWebApi.disassociate","primarycollection"),s.stringParameterCheck(a,"DynamicsWebApi.disassociate","relationshipName"),t=s.guidParameterCheck(t,"DynamicsWebApi.disassociate","primaryId"),r=s.guidParameterCheck(r,"DynamicsWebApi.disassociate","relatedId"),s.callbackParameterCheck(n,"DynamicsWebApi.disassociate","successCallback"),s.callbackParameterCheck(i,"DynamicsWebApi.disassociate","errorCallback");var o=function(){n()},l={};null!=c&&(c=s.guidParameterCheck(c,"DynamicsWebApi.associate","impersonateUserId"),l.MSCRMCallerID=c),p("DELETE",e+"("+t+")/"+a+"("+r+")/$ref",null,l,o,i)},this.associateSingleValued=function(e,a,r,n,i,c,o,l){s.stringParameterCheck(e,"DynamicsWebApi.associateSingleValued","collection"),a=s.guidParameterCheck(a,"DynamicsWebApi.associateSingleValued","id"),i=s.guidParameterCheck(i,"DynamicsWebApi.associateSingleValued","relatedId"),s.stringParameterCheck(r,"DynamicsWebApi.associateSingleValued","singleValuedNavigationPropertyName"),s.stringParameterCheck(n,"DynamicsWebApi.associateSingleValued","relatedcollection"),s.callbackParameterCheck(c,"DynamicsWebApi.associateSingleValued","successCallback"),s.callbackParameterCheck(o,"DynamicsWebApi.associateSingleValued","errorCallback");var u=function(){c()},m={};null!=l&&(l=s.guidParameterCheck(l,"DynamicsWebApi.associate","impersonateUserId"),m.MSCRMCallerID=l);var h={"@odata.id":t.webApiUrl+n+"("+i+")"};p("PUT",e+"("+a+")/"+r+"/$ref",h,m,u,o)},this.disassociateSingleValued=function(e,t,a,r,n,i){s.stringParameterCheck(e,"DynamicsWebApi.disassociateSingleValued","collection"),t=s.guidParameterCheck(t,"DynamicsWebApi.disassociateSingleValued","id"),s.stringParameterCheck(a,"DynamicsWebApi.disassociateSingleValued","singleValuedNavigationPropertyName"),s.callbackParameterCheck(r,"DynamicsWebApi.disassociateSingleValued","successCallback"),s.callbackParameterCheck(n,"DynamicsWebApi.disassociateSingleValued","errorCallback");var c={};null!=i&&(i=s.guidParameterCheck(i,"DynamicsWebApi.associate","impersonateUserId"),c.MSCRMCallerID=i),p("DELETE",e+"("+t+")/"+a+"/$ref",null,c,function(){r()},n)},this.executeUnboundFunction=function(e,t,a,r,n){return d(e,r,null,null,t,a,n)},this.executeBoundFunction=function(e,t,a,r,n,i,c){return d(a,i,t,e,r,n,c)};var d=function(e,t,a,r,n,c,o){s.stringParameterCheck(e,"DynamicsWebApi.executeFunction","functionName"),s.callbackParameterCheck(n,"DynamicsWebApi.executeFunction","successCallback"),s.callbackParameterCheck(c,"DynamicsWebApi.executeFunction","errorCallback");var l=e+i.buildFunctionParameters(t);null!=a&&(s.stringParameterCheck(a,"DynamicsWebApi.executeFunction","collection"),r=s.guidParameterCheck(r,"DynamicsWebApi.executeFunction","id"),l=a+"("+r+")/"+l);var u={};o&&(u.MSCRMCallerID=s.guidParameterCheck(o,"DynamicsWebApi.executionFunction","impersonateUserId")),p("GET",l,null,u,function(e){e.data?n(e.data):n()},c)};this.executeUnboundAction=function(e,t,a,r,n){return b(e,t,null,null,a,r,n)},this.executeBoundAction=function(e,t,a,r,n,i,c){return b(a,r,t,e,n,i,c)};var b=function(e,t,a,r,n,i,c){s.stringParameterCheck(e,"DynamicsWebApi.executeAction","actionName"),s.callbackParameterCheck(n,"DynamicsWebApi.executeAction","successCallback"),s.callbackParameterCheck(i,"DynamicsWebApi.executeAction","errorCallback");var o=e;null!=a&&(s.stringParameterCheck(a,"DynamicsWebApi.executeAction","collection"),r=s.guidParameterCheck(r,"DynamicsWebApi.executeAction","id"),o=a+"("+r+")/"+o);var l={};null!=c&&(c=s.guidParameterCheck(c,"DynamicsWebApi.associate","impersonateUserId"),l.MSCRMCallerID=c),p("POST",o,t,l,function(e){e.data?n(e.data):n()},i)};this.initializeInstance=function(e){return e||(e=t),new r(e)}}var n=a(0),i=a(5),c=a(4),s=a(1),o=a(3);String.prototype.endsWith&&String.prototype.startsWith||a(2),e.exports=r},function(e,t){e.exports=function(e,t){return"string"==typeof t&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.exec(t)?new Date(t):t}},function(e,t,a){function r(e){var t=e.substr(0,e.indexOf("\r\n")),a=e.split(t);a.shift(),a.pop();for(var r=[],n=0;n<a.length;n++){var i=a[n],s=i.substring(i.indexOf("{"),i.lastIndexOf("}")+1);r.push(JSON.parse(s,c))}return r}function n(e){for(var t=Object.keys(e),a=0;a<t.length;a++){if(null!=e[t[a]]&&e[t[a]].constructor===Array)for(var r=0;r<e[t[a]].length;r++)e[t[a]][r]=n(e[t[a]][r]);if(-1!=t[a].indexOf("@")){var c=t[a].split("@"),s=null;switch(c[1]){case"odata.context":s="oDataContext";break;case"odata.count":s="oDataCount",e[t[a]]=null!=e[t[a]]?parseInt(e[t[a]]):0;break;case"odata.nextLink":s="oDataNextLink";break;case i.Prefer.Annotations.FormattedValue:s=c[0]+"_Formatted";break;case i.Prefer.Annotations.AssociatedNavigationProperty:s=c[0]+"_NavigationProperty";break;case i.Prefer.Annotations.LookupLogicalName:s=c[0]+"_LogicalName"}s&&(e[s]=e[t[a]])}}return e}var i=a(0),c=a(7);String.prototype.endsWith&&String.prototype.startsWith||a(2),e.exports=function(e){var t=null;return e.length&&(t=t=e.indexOf("--batchresponse_")>-1?r(e)[0]:JSON.parse(e,c),t=n(t)),t}},function(e,t){e.exports=function(e){var t={};if(!e)return t;for(var a=e.split("\r\n"),r=0,n=a.length;r<n;r++){var i=a[r],c=i.indexOf(": ");c>0&&(t[i.substring(0,c)]=i.substring(c+2))}return t}},function(e,t,a){var r=a(8),n=a(9),i=function(e,t,a,i,c,s,o){var l=new XMLHttpRequest;l.open(e,t,o);for(var u in i)l.setRequestHeader(u,i[u]);l.onreadystatechange=function(){if(4===l.readyState){switch(l.status){case 200:case 201:case 204:case 304:var e=r(l.responseText),t={data:e,headers:n(l.getAllResponseHeaders()),status:l.status};c(t);break;default:var a;try{a=JSON.parse(l.response).error}catch(e){a=l.response.length>0?{message:l.response}:{message:"Unexpected Error"}}a.status=l.status,s(a)}l=null}},l.onerror=function(){s({message:"Network Error"}),l=null},l.ontimeout=function(e){s({message:"Request Timed Out"}),l=null},a?l.send(a):l.send()};e.exports=i},function(e,t){e.exports=function(e){if(e){for(var t=Object.keys(e),a="",r="",n=1;n<=t.length;n++){var i=t[n-1],c=e[i];n>1&&(a+=",",r+="&"),a+=i+"=@p"+n,r+="@p"+n+"="+("string"==typeof c?"'"+c+"'":c)}return"("+a+")?"+r}return"()"}},function(e,t,a){var r=a(0),n=a(1);e.exports=function(e,t,a){var i=e.returnRepresentation,c=e.includeAnnotations,s=e.maxPageSize;if(e.prefer&&e.prefer.length){n.stringOrArrayParameterCheck(e.prefer,"DynamicsWebApi."+t,"request.prefer");var o=e.prefer;"string"==typeof o&&(o=o.split(","));for(var l in o){var u=o[l].trim();u===r.Prefer.ReturnRepresentation?i=!0:u.startsWith("odata.include-annotations=")?c=u.replace("odata.include-annotations=","").replace(/"/g,""):u.startsWith("odata.maxpagesize=")&&(s=u.replace("odata.maxpagesize=","").replace(/"/g,""))}}a&&(null==i&&(i=a.returnRepresentation),c=c||a.includeAnnotations,s=s||a.maxPageSize);var o=[];return i&&(n.boolParameterCheck(i,"DynamicsWebApi."+t,"request.returnRepresentation"),o.push(r.Prefer.ReturnRepresentation)),c&&(n.stringParameterCheck(c,"DynamicsWebApi."+t,"request.includeAnnotations"),o.push('odata.include-annotations="'+c+'"')),s&&s>0&&(n.numberParameterCheck(s,"DynamicsWebApi."+t,"request.maxPageSize"),o.push("odata.maxpagesize="+s)),o.join(",")}},function(e,t){e.exports=function(e){var t=/\/(\w+)\(([0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12})/i.exec(e["@odata.id"]);return{id:t[2],collection:t[1],oDataContext:e["@odata.context"]}}},function(e,t){e.exports=function(e,t){e=e||"",t=t||1,e=unescape(unescape(e));var a=/pagingcookie="(<cookie page="(\d+)".+<\/cookie>)/.exec(e);if(null!=a){var r=parseInt(a[2]);return{cookie:a[1].replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"'").replace(/\'/g,"&quot;"),page:r,nextPage:r+1}}return{cookie:"",page:t,nextPage:t+1}}}])});
/*! dynamics-web-api-callbacks v1.4.0 (c) 2017 Aleksandr Rogov */
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("DynamicsWebApi",[],t):"object"==typeof exports?exports.DynamicsWebApi=t():e.DynamicsWebApi=t()}(this,function(){return function(e){function t(r){if(a[r])return a[r].exports;var n=a[r]={i:r,l:!1,exports:{}};return e[r].call(n.exports,n,n.exports,t),n.l=!0,n.exports}var a={};return t.m=e,t.c=a,t.i=function(e){return e},t.d=function(e,a,r){t.o(e,a)||Object.defineProperty(e,a,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var a=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(a,"a",a),a},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=6)}([function(e,t){var a={Types:{ResponseBase:function(){this.oDataContext=""},Response:function(){a.Types.ResponseBase.call(this),this.value={}},ReferenceResponse:function(){a.Types.ResponseBase.call(this),this.id="",this.collection=""},MultipleResponse:function(){a.Types.ResponseBase.call(this),this.oDataNextLink="",this.oDataCount=0,this.value=[]},FetchXmlResponse:function(){a.Types.ResponseBase.call(this),this.value=[],this.PagingInfo={cookie:"",page:0,nextPage:1}}},Prefer:{ReturnRepresentation:"return=representation",Annotations:{AssociatedNavigationProperty:"Microsoft.Dynamics.CRM.associatednavigationproperty",LookupLogicalName:"Microsoft.Dynamics.CRM.lookuplogicalname",All:"*",FormattedValue:"OData.Community.Display.V1.FormattedValue",FetchXmlPagingCookie:"Microsoft.Dynamics.CRM.fetchxmlpagingcookie"}}};e.exports=a},function(e,t){function a(e,t,a){throw new Error(a?e+" requires the "+t+" parameter to be of type "+a:e+" requires the "+t+" parameter.")}var r={handleErrorResponse:function(e){throw new Error("Error: "+e.status+": "+e.message)},parameterCheck:function(e,t,r,n){void 0!==e&&null!==e&&""!=e||a(t,r,n)},stringParameterCheck:function(e,t,r){"string"!=typeof e&&a(t,r,"String")},arrayParameterCheck:function(e,t,r){e.constructor!==Array&&a(t,r,"Array")},stringOrArrayParameterCheck:function(e,t,r){e.constructor!==Array&&"string"!=typeof e&&a(t,r,"String or Array")},numberParameterCheck:function(e,t,r){if("number"!=typeof e){if("string"==typeof e&&e&&!isNaN(parseInt(e)))return;a(t,r,"Number")}},boolParameterCheck:function(e,t,r){"boolean"!=typeof e&&a(t,r,"Boolean")},guidParameterCheck:function(e,t,r){try{return/[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}/i.exec(e)[0]}catch(e){a(t,r,"GUID String")}},keyParameterCheck:function(e,t,n){try{r.stringParameterCheck(e,t,n);var i=/[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}/i.exec(e);if(i)return i[0];var c=e.split(",");if(c.length)for(var s=0;s<c.length;s++)c[s]=c[s].trim(),/^[\w\d\_]+\='[^\'\r\n]+'$/i.exec(c[s])[0];return c.join(",")}catch(e){a(t,n,"String representing GUID or Alternate Key")}},callbackParameterCheck:function(e,t,r){"function"!=typeof e&&a(t,r,"Function")}};e.exports=r},function(e,t){String.prototype.endsWith=function(e,t){var a=this.toString();("number"!=typeof t||!isFinite(t)||Math.floor(t)!==t||t>a.length)&&(t=a.length),t-=e.length;var r=a.lastIndexOf(e,t);return-1!==r&&r===t},String.prototype.startsWith=function(e,t){return t=t||0,this.substr(t,e.length)===e}},function(e,t,a){function r(e,t,a,n,s){var o={},l=[];if(n=null!=n?n:"&",e){e.navigationProperty&&(i.stringParameterCheck(e.navigationProperty,"DynamicsWebApi."+t,"request.navigationProperty"),a+="/"+e.navigationProperty),null!=e.select&&e.select.length&&(i.arrayParameterCheck(e.select,"DynamicsWebApi."+t,"request.select"),"retrieve"==t&&1==e.select.length&&e.select[0].endsWith("/$ref")?a+="/"+e.select[0]:(e.select[0].startsWith("/")&&"retrieve"==t&&(null==e.navigationProperty?a+=e.select.shift():e.select.shift()),e.select.length&&l.push("$select="+e.select.join(",")))),e.filter&&(i.stringParameterCheck(e.filter,"DynamicsWebApi."+t,"request.filter"),l.push("$filter="+e.filter)),e.savedQuery&&l.push("savedQuery="+i.guidParameterCheck(e.savedQuery,"DynamicsWebApi."+t,"request.savedQuery")),e.userQuery&&l.push("userQuery="+i.guidParameterCheck(e.userQuery,"DynamicsWebApi."+t,"request.userQuery")),e.count&&(i.boolParameterCheck(e.count,"DynamicsWebApi."+t,"request.count"),l.push("$count="+e.count)),e.top&&e.top>0&&(i.numberParameterCheck(e.top,"DynamicsWebApi."+t,"request.top"),l.push("$top="+e.top)),null!=e.orderBy&&e.orderBy.length&&(i.arrayParameterCheck(e.orderBy,"DynamicsWebApi."+t,"request.orderBy"),l.push("$orderby="+e.orderBy.join(",")));var u=c(e,t,s);if(u.length&&(o.Prefer=u),null!=e.ifmatch&&null!=e.ifnonematch)throw new Error("DynamicsWebApi."+t+". Either one of request.ifmatch or request.ifnonematch parameters should be used in a call, not both.");if(e.ifmatch&&(i.stringParameterCheck(e.ifmatch,"DynamicsWebApi."+t,"request.ifmatch"),o["If-Match"]=e.ifmatch),e.ifnonematch&&(i.stringParameterCheck(e.ifnonematch,"DynamicsWebApi."+t,"request.ifnonematch"),o["If-None-Match"]=e.ifnonematch),e.impersonate&&(i.stringParameterCheck(e.impersonate,"DynamicsWebApi."+t,"request.impersonate"),o.MSCRMCallerID=i.guidParameterCheck(e.impersonate,"DynamicsWebApi."+t,"request.impersonate")),e.token&&(i.stringParameterCheck(e.token,"DynamicsWebApi."+t,"request.token"),o.Authorization="Bearer "+e.token),e.duplicateDetection&&(i.boolParameterCheck(e.duplicateDetection,"DynamicsWebApi."+t,"request.duplicateDetection"),o["MSCRM.SuppressDuplicateDetection"]="false"),e.entity&&i.parameterCheck(e.entity,"DynamicsWebApi."+t,"request.entity"),e.data&&i.parameterCheck(e.data,"DynamicsWebApi."+t,"request.data"),e.noCache&&(i.boolParameterCheck(e.noCache,"DynamicsWebApi."+t,"request.noCache"),o["Cache-Control"]="no-cache"),e.expand&&e.expand.length)if(i.stringOrArrayParameterCheck(e.expand,"DynamicsWebApi."+t,"request.expand"),"string"==typeof e.expand)l.push("$expand="+e.expand);else{for(var p=[],m=0;m<e.expand.length;m++)if(e.expand[m].property){var h=r(e.expand[m],t+" $expand",null,";"),y=h.query;y&&y.length&&(y="("+y+")"),p.push(e.expand[m].property+y)}p.length&&l.push("$expand="+p.join(","))}}return{url:a,query:l.join(n),headers:o}}function n(e,t,a){var n,c="";return e.url?(i.stringParameterCheck(e.url,"DynamicsWebApi."+t,"request.url"),c=e.url.replace(a.webApiUrl,""),n=r(e,t,c,"&",a)):(e._unboundRequest||e.collection||i.parameterCheck(e.collection,"DynamicsWebApi."+t,"request.collection"),e.collection&&(i.stringParameterCheck(e.collection,"DynamicsWebApi."+t,"request.collection"),c=e.collection,e.key?e.key=i.keyParameterCheck(e.key,"DynamicsWebApi."+t,"request.key"):e.id&&(e.key=i.guidParameterCheck(e.id,"DynamicsWebApi."+t,"request.id")),e.key&&(c+="("+e.key+")")),e._additionalUrl&&(c&&(c+="/"),c+=e._additionalUrl),n=r(e,t,c,"&",a),e.fetchXml?(i.stringParameterCheck(e.fetchXml,"DynamicsWebApi."+t,"request.fetchXml"),n.url+="?fetchXml="+encodeURIComponent(e.fetchXml)):n.query&&(n.url+="?"+encodeURI(n.query))),e.hasOwnProperty("async")&&null!=e.async?(i.boolParameterCheck(e.async,"DynamicsWebApi."+t,"request.async"),n.async=e.async):n.async=!0,{url:n.url,headers:n.headers,async:n.async}}var i=(a(0),a(1)),c=a(12),s={convertRequestOptions:r,convertRequest:n};e.exports=s},function(e,t,a){function r(e){return void 0===e||"unknown"==typeof e||null==e}function n(){var e=(new Date).getTime();return"undefined"!=typeof performance&&"function"==typeof performance.now&&(e+=performance.now()),"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var a=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"===t?a:3&a|8).toString(16)})}function i(){if("undefined"!=typeof GetGlobalContext)return GetGlobalContext();if("undefined"!=typeof Xrm){if(!r(Xrm.Utility)&&!r(Xrm.Utility.getGlobalContext))return Xrm.Utility.getGlobalContext();if(!r(Xrm.Page)&&!r(Xrm.Page.context))return Xrm.Page.context}throw new Error("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.")}function c(){var e=i();if(e){var t=e.getClientUrl();return t.match(/\/$/)&&(t=t.substring(0,t.length-1)),t}return""}function s(e){return c()+"/api/data/v"+e+"/"}function o(){return"undefined"!=typeof Xrm?Xrm.Internal:null}var l={buildFunctionParameters:a(11),getFetchXmlPagingCookie:a(14),convertToReferenceObject:a(13),isNull:r,generateUUID:n,getXrmContext:i,getXrmInternal:o,getClientUrl:c,initWebApiUrl:s};e.exports=l},function(e,t,a){function r(e){var t=m.getXrmInternal();if(!m.isNull(t)){var a=t.getEntitySetName(e);return a||e}var a=null;if(!m.isNull(p)&&(a=p[e],m.isNull(a)))for(var r in p)if(p[r]==e)return e;return a}function n(e){return e.Accept="application/json",e["OData-MaxVersion"]="4.0",e["OData-Version"]="4.0",e["Content-Type"]="application/json; charset=utf-8",e}function i(e,t){var a;return e&&(a=JSON.stringify(e,function(e,a){if((e.endsWith("@odata.bind")||e.endsWith("@odata.id"))&&"string"==typeof a){if(/\(\{[\w\d-]+\}\)/g.test(a)&&(a=a.replace(/(.+)\(\{([\w\d-]+)\}\)/g,"$1($2)")),t.useEntityNames){var n=/([\w_]+)(\([\d\w-]+\))$/,i=n.exec(a);if(i.length>2){var c=r(i[1]);m.isNull(c)||(a=a.replace(n,c+"$2"))}}a.startsWith(t.webApiUrl)||(a=t.webApiUrl+a.replace(/^\\/,""))}return a}),a=a.replace(/[\u007F-\uFFFF]/g,function(e){return"\\u"+("0000"+e.charCodeAt(0).toString(16)).substr(-4)})),a}function c(e,t,r,c,s,o,l,u){s||(s={}),s=n(s);var p=i(c,r);if(t.length>2e3){var h="dwa_batch_"+m.generateUUID(),y=[];y.push("--"+h),y.push("Content-Type: application/http"),y.push("Content-Transfer-Encoding: binary\n"),y.push(e+" "+r.webApiUrl+t+" HTTP/1.1");for(var f in s)y.push(f+": "+s[f]),delete s[f];y.push("\n--"+h+"--"),p=y.join("\n"),s=n(s),s["Content-Type"]="multipart/mixed;boundary="+h,t="$batch",e="POST"}r.impersonate&&!s.MSCRMCallerID&&(s.MSCRMCallerID=r.impersonate);var d;d=a(10);var k=function(a){a&&(s||(s={}),s.Authorization="Bearer "+a.accessToken),d(e,r.webApiUrl+t,p,s,o,l,u)};r.onTokenRefresh&&(!s||s&&!s.Authorization)?r.onTokenRefresh(k):k()}function s(e,t,a,n){var i=function(t){p={};for(var n=0;n<t.data.value.length;n++)p[t.data.value[n].LogicalName]=t.data.value[n].LogicalCollectionName;a(r(e))},s=function(e){n({message:"Unable to fetch EntityDefinitions. Error: "+e.message})},o=h.convertRequest({collection:"EntityDefinitions",select:["LogicalCollectionName","LogicalName"],noCache:!0},"retrieveMultiple",t);c("GET",o.url,t,null,o.headers,i,s,o.async)}function o(e){return["EntityDefinitions","$metadata"].indexOf(e)>-1}function l(e,t,a,n){if(o(e)||m.isNull(e))return void a(e);if(e=e.toLowerCase(),!t.useEntityNames)return void a(e);try{var i=r(e);m.isNull(i)?s(e,t,a,n):a(i)}catch(e){n({message:"Unable to fetch Collection Names. Error: "+e.message})}}function u(e,t,a,r,n,i){var s=function(s){t.collection=s;var o=h.convertRequest(t,a,r);c(e,o.url,r,t.data||t.entity,o.headers,n,i,o.async)};l(t.collection,r,s,i)}var p,m=(a(0),a(4)),h=a(3);e.exports={sendRequest:c,makeRequest:u,getCollectionName:r}},function(e,t,a){function r(e){var t={webApiVersion:"8.0",webApiUrl:"",impersonate:null,onTokenRefresh:null,includeAnnotations:null,maxPageSize:null,returnRepresentation:null};e||(e=t),this.setConfig=function(e){e.webApiVersion&&(s.stringParameterCheck(e.webApiVersion,"DynamicsWebApi.setConfig","config.webApiVersion"),t.webApiVersion=e.webApiVersion),e.webApiUrl?(s.stringParameterCheck(e.webApiUrl,"DynamicsWebApi.setConfig","config.webApiUrl"),t.webApiUrl=e.webApiUrl):t.webApiUrl=i.initWebApiUrl(t.webApiVersion),e.impersonate&&(t.impersonate=s.guidParameterCheck(e.impersonate,"DynamicsWebApi.setConfig","config.impersonate")),e.onTokenRefresh&&(s.callbackParameterCheck(e.onTokenRefresh,"DynamicsWebApi.setConfig","config.onTokenRefresh"),t.onTokenRefresh=e.onTokenRefresh),e.includeAnnotations&&(s.stringParameterCheck(e.includeAnnotations,"DynamicsWebApi.setConfig","config.includeAnnotations"),t.includeAnnotations=e.includeAnnotations),e.maxPageSize&&(s.numberParameterCheck(e.maxPageSize,"DynamicsWebApi.setConfig","config.maxPageSize"),t.maxPageSize=e.maxPageSize),e.returnRepresentation&&(s.boolParameterCheck(e.returnRepresentation,"DynamicsWebApi.setConfig","config.returnRepresentation"),t.returnRepresentation=e.returnRepresentation),e.useEntityNames&&(s.boolParameterCheck(e.useEntityNames,"DynamicsWebApi.setConfig","config.useEntityNames"),t.useEntityNames=e.useEntityNames)},this.setConfig(e);var a=function(e,a,r,n,i){o.makeRequest(e,a,r,t,n,i)};this.create=function(e,r,n,i,o,l){s.parameterCheck(e,"DynamicsWebApi.create","object"),s.stringParameterCheck(r,"DynamicsWebApi.create","collection"),s.callbackParameterCheck(n,"DynamicsWebApi.create","successCallback"),s.callbackParameterCheck(i,"DynamicsWebApi.create","errorCallback"),o&&s.stringOrArrayParameterCheck(o,"DynamicsWebApi.create","prefer"),l&&s.arrayParameterCheck(l,"DynamicsWebApi.create","select");var u={collection:r,select:l,prefer:o,entity:e};c.convertRequest(u,"create",t);a("POST",u,"create",function(e){if(e.data)n(e.data);else{var t=e.headers["OData-EntityId"]?e.headers["OData-EntityId"]:e.headers["odata-entityid"],a=/[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}/i.exec(t)[0];n(a)}},i)},this.updateRequest=function(e,t,r){s.parameterCheck(e,"DynamicsWebApi.update","request"),s.callbackParameterCheck(t,"DynamicsWebApi.update","successCallback"),s.callbackParameterCheck(r,"DynamicsWebApi.update","errorCallback"),null==e.ifmatch&&(e.ifmatch="*");var n=function(e){t(e.data?e.data:!0)},i=e.ifmatch;a("PATCH",e,"update",n,function(e){i&&412==e.status?t(!1):r(e)})},this.update=function(e,t,a,r,n,i,c){s.stringParameterCheck(e,"DynamicsWebApi.update","key"),e=s.keyParameterCheck(e,"DynamicsWebApi.update","key"),s.parameterCheck(a,"DynamicsWebApi.update","object"),s.stringParameterCheck(t,"DynamicsWebApi.update","collection"),s.callbackParameterCheck(r,"DynamicsWebApi.update","successCallback"),s.callbackParameterCheck(n,"DynamicsWebApi.update","errorCallback"),i&&s.stringOrArrayParameterCheck(i,"DynamicsWebApi.update","prefer"),c&&s.arrayParameterCheck(c,"DynamicsWebApi.update","select");var o={collection:t,key:e,select:c,prefer:i,entity:a};this.updateRequest(o,r,n)},this.updateSingleProperty=function(e,t,r,n,i,c,o){s.stringParameterCheck(e,"DynamicsWebApi.updateSingleProperty","key"),e=s.keyParameterCheck(e,"DynamicsWebApi.updateSingleProperty","key"),s.parameterCheck(r,"DynamicsWebApi.updateSingleProperty","keyValuePair"),s.stringParameterCheck(t,"DynamicsWebApi.updateSingleProperty","collection"),s.callbackParameterCheck(n,"DynamicsWebApi.updateSingleProperty","successCallback"),s.callbackParameterCheck(i,"DynamicsWebApi.updateSingleProperty","errorCallback"),c&&s.stringOrArrayParameterCheck(c,"DynamicsWebApi.updateSingleProperty","prefer"),o&&s.arrayParameterCheck(o,"DynamicsWebApi.updateSingleProperty","select");var l=Object.keys(r)[0],u=r[l];a("PUT",{collection:t,key:e,select:o,prefer:c,navigationProperty:l,data:{value:u}},"updateSingleProperty",function(e){e.data?n(e.data):n()},i)},this.deleteRequest=function(e,t,r){s.parameterCheck(e,"DynamicsWebApi.delete","request"),s.callbackParameterCheck(t,"DynamicsWebApi.delete","successCallback"),s.callbackParameterCheck(r,"DynamicsWebApi.delete","errorCallback");var n=function(){t(!0)},i=e.ifmatch;a("DELETE",e,"delete",n,function(e){i&&412==e.status?t(!1):r(e)})},this.deleteRecord=function(e,t,r,n,i){s.stringParameterCheck(e,"DynamicsWebApi.delete","key"),e=s.keyParameterCheck(e,"DynamicsWebApi.delete","key"),s.stringParameterCheck(t,"DynamicsWebApi.delete","collection"),s.callbackParameterCheck(r,"DynamicsWebApi.delete","successCallback"),s.callbackParameterCheck(n,"DynamicsWebApi.delete","errorCallback"),null!=i&&s.stringParameterCheck(i,"DynamicsWebApi.delete","propertyName"),a("DELETE",{key:e,collection:t,navigationProperty:i},"delete",function(e){r()},n)},this.retrieveRequest=function(e,t,r){s.parameterCheck(e,"DynamicsWebApi.retrieve","request"),s.callbackParameterCheck(t,"DynamicsWebApi.retrieve","successCallback"),s.callbackParameterCheck(r,"DynamicsWebApi.retrieve","errorCallback");var n=e.select;a("GET",e,"retrieve",function(e){t(null!=n&&1==n.length&&n[0].endsWith("/$ref")&&null!=e.data["@odata.id"]?i.convertToReferenceObject(e.data):e.data)},r)},this.retrieve=function(e,t,a,r,n,i){s.stringParameterCheck(e,"DynamicsWebApi.retrieve","key"),e=s.keyParameterCheck(e,"DynamicsWebApi.retrieve","key"),s.stringParameterCheck(t,"DynamicsWebApi.retrieve","collection"),s.callbackParameterCheck(a,"DynamicsWebApi.retrieve","successCallback"),s.callbackParameterCheck(r,"DynamicsWebApi.retrieve","errorCallback"),n&&n.length&&s.arrayParameterCheck(n,"DynamicsWebApi.retrieve","select"),i&&i.length&&s.stringOrArrayParameterCheck(i,"DynamicsWebApi.retrieve","expand");var c={collection:t,key:e,select:n,expand:i};this.retrieveRequest(c,a,r)},this.upsertRequest=function(e,t,r){s.parameterCheck(e,"DynamicsWebApi.upsert","request"),s.parameterCheck(e.entity,"DynamicsWebApi.upsert","request.entity"),s.callbackParameterCheck(t,"DynamicsWebApi.upsert","successCallback"),s.callbackParameterCheck(r,"DynamicsWebApi.upsert","errorCallback");var n=e.ifnonematch,i=e.ifmatch;a("PATCH",e,"upsert",function(e){if(e.headers["OData-EntityId"]||e.headers["odata-entityid"]){var a=e.headers["OData-EntityId"]?e.headers["OData-EntityId"]:e.headers["odata-entityid"],r=/[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}/i.exec(a)[0];t(r)}else e.data?t(e.data):t()},function(e){n&&412==e.status?t():i&&404==e.status?t():r(e)})},this.upsert=function(e,t,a,r,n,i,c){s.stringParameterCheck(e,"DynamicsWebApi.upsert","key"),e=s.keyParameterCheck(e,"DynamicsWebApi.upsert","key"),s.parameterCheck(a,"DynamicsWebApi.upsert","object"),s.stringParameterCheck(t,"DynamicsWebApi.upsert","collection"),s.callbackParameterCheck(r,"DynamicsWebApi.upsert","successCallback"),s.callbackParameterCheck(n,"DynamicsWebApi.upsert","errorCallback"),i&&s.stringOrArrayParameterCheck(i,"DynamicsWebApi.upsert","prefer"),c&&s.arrayParameterCheck(c,"DynamicsWebApi.upsert","select");var o={collection:t,key:e,select:c,prefer:i,entity:a};this.upsertRequest(o,r,n)},this.count=function(e,t,r,n){if(null!=n&&(null==n||n.length))return this.retrieveMultipleRequest({collection:e,filter:n,count:!0},function(e){t(e.oDataCount?e.oDataCount:0)},r);s.stringParameterCheck(e,"DynamicsWebApi.count","collection"),s.callbackParameterCheck(t,"DynamicsWebApi.count","successCallback"),s.callbackParameterCheck(r,"DynamicsWebApi.count","errorCallback"),a("GET",{collection:e,navigationProperty:"$count"},"count",function(e){t(e.data?parseInt(e.data):0)},r)},this.countAll=function(e,t,a,r,n){return this.retrieveAllRequest({collection:e,filter:r,select:n},function(e){t(e&&e.value?e.value.length:0)},a)},this.retrieveMultiple=function(e,t,a,r,n,i){return this.retrieveMultipleRequest({collection:e,select:r,filter:n},t,a,i)},this.retrieveAll=function(e,t,a,r,n){return u({collection:e,select:r,filter:n},t,a)};var l=function(e,t,r,n){s.callbackParameterCheck(t,"DynamicsWebApi.retrieveMultiple","successCallback"),s.callbackParameterCheck(r,"DynamicsWebApi.retrieveMultiple","errorCallback"),n&&(s.stringParameterCheck(n,"DynamicsWebApi.retrieveMultiple","nextPageLink"),e.url=n);var i=e.count;a("GET",e,"retrieveMultiple",function(e){i&&(e.data.oDataCount=e.data.oDataCount||0),t(e.data)},r)};this.retrieveMultipleRequest=l;var u=function(e,t,a,r,n){var n=n||[];l(e,function(r){n=n.concat(r.value),r.oDataNextLink?u(e,t,a,r.oDataNextLink,n):t({value:n})},a,r)};this.retrieveAllRequest=function(e,t,a){u(e,t,a)};var p=function(e,t,r,c,o,l,u,p){s.stringParameterCheck(e,"DynamicsWebApi.executeFetchXml","collection"),s.stringParameterCheck(t,"DynamicsWebApi.executeFetchXml","fetchXml"),s.callbackParameterCheck(r,"DynamicsWebApi.executeFetchXml","successCallback"),s.callbackParameterCheck(c,"DynamicsWebApi.executeFetchXml","errorCallback"),l=l||1,s.numberParameterCheck(l,"DynamicsWebApi.executeFetchXml","pageNumber");var m='$1 page="'+l+'"';null!=u&&(s.stringParameterCheck(u,"DynamicsWebApi.executeFetchXml","pagingCookie"),m+=' paging-cookie="'+u+'"'),t=t.replace(/^(<fetch[\w\d\s'"=]+)/,m),a("GET",{collection:e,includeAnnotations:o,impersonate:p,fetchXml:t,impersonate:p,includeAnnotations:o},"executeFetchXml",function(e){null!=e.data["@"+n.Prefer.Annotations.FetchXmlPagingCookie]&&(e.data.PagingInfo=i.getFetchXmlPagingCookie(e.data["@"+n.Prefer.Annotations.FetchXmlPagingCookie],l)),r(e.data)},c)};this.fetch=this.executeFetchXml=p;var m=function(e,t,a,r,n,i,c,s,o){var o=o||[];p(e,t,function(i){o=o.concat(i.value),i.PagingInfo?m(e,t,a,r,n,i.PagingInfo.nextPage,i.PagingInfo.cookie,s,o):a({value:o})},r,n,i,c,s)};this.fetchAll=this.executeFetchXmlAll=function(e,t,a,r,n,i){return m(e,t,a,r,n,null,null,i)},this.associate=function(e,t,r,n,i,c,o,l){s.stringParameterCheck(e,"DynamicsWebApi.associate","collection"),s.stringParameterCheck(n,"DynamicsWebApi.associate","relatedCollection"),s.stringParameterCheck(r,"DynamicsWebApi.associate","relationshipName"),t=s.keyParameterCheck(t,"DynamicsWebApi.associate","primaryKey"),i=s.keyParameterCheck(i,"DynamicsWebApi.associate","relatedKey"),s.callbackParameterCheck(c,"DynamicsWebApi.associate","successCallback"),s.callbackParameterCheck(o,"DynamicsWebApi.associate","errorCallback"),a("POST",{_additionalUrl:r+"/$ref",collection:e,key:t,impersonate:l,data:{"@odata.id":n+"("+i+")"}},"associate",function(){c()},o)},this.disassociate=function(e,t,r,n,i,c,o){s.stringParameterCheck(e,"DynamicsWebApi.disassociate","collection"),s.stringParameterCheck(r,"DynamicsWebApi.disassociate","relationshipName"),t=s.keyParameterCheck(t,"DynamicsWebApi.disassociate","primaryKey"),n=s.keyParameterCheck(n,"DynamicsWebApi.disassociate","relatedKey"),s.callbackParameterCheck(i,"DynamicsWebApi.disassociate","successCallback"),s.callbackParameterCheck(c,"DynamicsWebApi.disassociate","errorCallback"),a("DELETE",{_additionalUrl:r+"("+n+")/$ref",collection:e,key:t,impersonate:o},"disassociate",function(){i()},c)},this.associateSingleValued=function(e,t,r,n,i,c,o,l){s.stringParameterCheck(e,"DynamicsWebApi.associateSingleValued","collection"),t=s.keyParameterCheck(t,"DynamicsWebApi.associateSingleValued","key"),i=s.keyParameterCheck(i,"DynamicsWebApi.associateSingleValued","relatedKey"),s.stringParameterCheck(r,"DynamicsWebApi.associateSingleValued","singleValuedNavigationPropertyName"),s.stringParameterCheck(n,"DynamicsWebApi.associateSingleValued","relatedCollection"),s.callbackParameterCheck(c,"DynamicsWebApi.associateSingleValued","successCallback"),s.callbackParameterCheck(o,"DynamicsWebApi.associateSingleValued","errorCallback"),a("PUT",{_additionalUrl:r+"/$ref",collection:e,key:t,impersonate:l,data:{"@odata.id":n+"("+i+")"}},"associateSingleValued",function(){c()},o)},this.disassociateSingleValued=function(e,t,r,n,i,c){s.stringParameterCheck(e,"DynamicsWebApi.disassociateSingleValued","collection"),t=s.keyParameterCheck(t,"DynamicsWebApi.disassociateSingleValued","key"),s.stringParameterCheck(r,"DynamicsWebApi.disassociateSingleValued","singleValuedNavigationPropertyName"),s.callbackParameterCheck(n,"DynamicsWebApi.disassociateSingleValued","successCallback"),s.callbackParameterCheck(i,"DynamicsWebApi.disassociateSingleValued","errorCallback"),a("DELETE",{_additionalUrl:r+"/$ref",key:t,collection:e,impersonate:c},"disassociateSingleValued",function(){n()},i)},this.executeUnboundFunction=function(e,t,a,r,n){return h(e,r,null,null,t,a,n,!0)},this.executeBoundFunction=function(e,t,a,r,n,i,c){return h(a,i,t,e,r,n,c)};var h=function(e,t,r,n,c,o,l,u){s.stringParameterCheck(e,"DynamicsWebApi.executeFunction","functionName"),s.callbackParameterCheck(c,"DynamicsWebApi.executeFunction","successCallback"),s.callbackParameterCheck(o,"DynamicsWebApi.executeFunction","errorCallback");var p={_additionalUrl:e+i.buildFunctionParameters(t),_unboundRequest:u,key:n,collection:r,impersonate:l};a("GET",p,"executeFunction",function(e){e.data?c(e.data):c()},o)};this.executeUnboundAction=function(e,t,a,r,n){return y(e,t,null,null,a,r,n,!0)},this.executeBoundAction=function(e,t,a,r,n,i,c){return y(a,r,t,e,n,i,c)};var y=function(e,t,r,n,i,c,o,l){s.stringParameterCheck(e,"DynamicsWebApi.executeAction","actionName"),s.callbackParameterCheck(i,"DynamicsWebApi.executeAction","successCallback"),s.callbackParameterCheck(c,"DynamicsWebApi.executeAction","errorCallback"),a("POST",{_additionalUrl:e,_unboundRequest:l,collection:r,key:n,impersonate:o,data:t},"executeAction",function(e){e.data?i(e.data):i()},c)};this.initializeInstance=function(e){return e||(e=t),new r(e)}}var n=a(0),i=a(4),c=a(3),s=a(1),o=a(5);String.prototype.endsWith&&String.prototype.startsWith||a(2),r.prototype.utility={getCollectionName:o.getCollectionName},e.exports=r},function(e,t){e.exports=function(e,t){var a;return"string"==typeof t&&(a=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:Z|[-+]\d{2}:\d{2})$/.exec(t))?new Date(Date.UTC(+a[1],+a[2]-1,+a[3],+a[4],+a[5],+a[6])):t}},function(e,t,a){function r(e){var t=e.substr(0,e.indexOf("\r\n")),a=e.split(t);a.shift(),a.pop();for(var r=[],n=0;n<a.length;n++){var i=a[n],s=i.substring(i.indexOf("{"),i.lastIndexOf("}")+1);r.push(JSON.parse(s,c))}return r}function n(e){for(var t=Object.keys(e),a=0;a<t.length;a++){if(null!=e[t[a]]&&e[t[a]].constructor===Array)for(var r=0;r<e[t[a]].length;r++)e[t[a]][r]=n(e[t[a]][r]);if(-1!=t[a].indexOf("@")){var c=t[a].split("@"),s=null;switch(c[1]){case"odata.context":s="oDataContext";break;case"odata.count":s="oDataCount",e[t[a]]=null!=e[t[a]]?parseInt(e[t[a]]):0;break;case"odata.nextLink":s="oDataNextLink";break;case i.Prefer.Annotations.FormattedValue:s=c[0]+"_Formatted";break;case i.Prefer.Annotations.AssociatedNavigationProperty:s=c[0]+"_NavigationProperty";break;case i.Prefer.Annotations.LookupLogicalName:s=c[0]+"_LogicalName"}s&&(e[s]=e[t[a]])}}return e}var i=a(0),c=a(7);String.prototype.endsWith&&String.prototype.startsWith||a(2),e.exports=function(e){var t=null;return e.length&&(t=t=e.indexOf("--batchresponse_")>-1?r(e)[0]:JSON.parse(e,c),t=n(t)),t}},function(e,t){e.exports=function(e){var t={};if(!e)return t;for(var a=e.split("\r\n"),r=0,n=a.length;r<n;r++){var i=a[r],c=i.indexOf(": ");c>0&&(t[i.substring(0,c)]=i.substring(c+2))}return t}},function(e,t,a){var r=a(8),n=a(9),i=function(e,t,a,i,c,s,o){var l=new XMLHttpRequest;l.open(e,t,o);for(var u in i)l.setRequestHeader(u,i[u]);l.onreadystatechange=function(){if(4===l.readyState){switch(l.status){case 200:case 201:case 204:case 304:var e=r(l.responseText),t={data:e,headers:n(l.getAllResponseHeaders()),status:l.status};c(t);break;default:var a;try{a=JSON.parse(l.response).error}catch(e){a=l.response.length>0?{message:l.response}:{message:"Unexpected Error"}}a.status=l.status,s(a)}l=null}},l.onerror=function(){s({message:"Network Error"}),l=null},l.ontimeout=function(e){s({message:"Request Timed Out"}),l=null},a?l.send(a):l.send()};e.exports=i},function(e,t){e.exports=function(e){if(e){for(var t=Object.keys(e),a="",r="",n=1;n<=t.length;n++){var i=t[n-1],c=e[i];n>1&&(a+=",",r+="&"),a+=i+"=@p"+n,r+="@p"+n+"="+("string"==typeof c?"'"+c+"'":c)}return"("+a+")?"+r}return"()"}},function(e,t,a){var r=a(0),n=a(1);e.exports=function(e,t,a){var i=e.returnRepresentation,c=e.includeAnnotations,s=e.maxPageSize;if(e.prefer&&e.prefer.length){n.stringOrArrayParameterCheck(e.prefer,"DynamicsWebApi."+t,"request.prefer");var o=e.prefer;"string"==typeof o&&(o=o.split(","));for(var l in o){var u=o[l].trim();u===r.Prefer.ReturnRepresentation?i=!0:u.startsWith("odata.include-annotations=")?c=u.replace("odata.include-annotations=","").replace(/"/g,""):u.startsWith("odata.maxpagesize=")&&(s=u.replace("odata.maxpagesize=","").replace(/"/g,""))}}a&&(null==i&&(i=a.returnRepresentation),c=c||a.includeAnnotations,s=s||a.maxPageSize);var o=[];return i&&(n.boolParameterCheck(i,"DynamicsWebApi."+t,"request.returnRepresentation"),o.push(r.Prefer.ReturnRepresentation)),c&&(n.stringParameterCheck(c,"DynamicsWebApi."+t,"request.includeAnnotations"),o.push('odata.include-annotations="'+c+'"')),s&&s>0&&(n.numberParameterCheck(s,"DynamicsWebApi."+t,"request.maxPageSize"),o.push("odata.maxpagesize="+s)),o.join(",")}},function(e,t){e.exports=function(e){var t=/\/(\w+)\(([0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12})/i.exec(e["@odata.id"]);return{id:t[2],collection:t[1],oDataContext:e["@odata.context"]}}},function(e,t){e.exports=function(e,t){e=e||"",t=t||1,e=unescape(unescape(e));var a=/pagingcookie="(<cookie page="(\d+)".+<\/cookie>)/.exec(e);if(null!=a){var r=parseInt(a[2]);return{cookie:a[1].replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"'").replace(/\'/g,"&quot;"),page:r,nextPage:r+1}}return{cookie:"",page:t,nextPage:t+1}}}])});

@@ -1,2 +0,2 @@

/*! dynamics-web-api v1.3.4 (c) 2017 Aleksandr Rogov */
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("DynamicsWebApi",[],t):"object"==typeof exports?exports.DynamicsWebApi=t():e.DynamicsWebApi=t()}(this,function(){return function(e){function t(n){if(r[n])return r[n].exports;var a=r[n]={i:n,l:!1,exports:{}};return e[n].call(a.exports,a,a.exports,t),a.l=!0,a.exports}var r={};return t.m=e,t.c=r,t.i=function(e){return e},t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=6)}([function(e,t){var r={Types:{ResponseBase:function(){this.oDataContext=""},Response:function(){r.Types.ResponseBase.call(this),this.value={}},ReferenceResponse:function(){r.Types.ResponseBase.call(this),this.id="",this.collection=""},MultipleResponse:function(){r.Types.ResponseBase.call(this),this.oDataNextLink="",this.oDataCount=0,this.value=[]},FetchXmlResponse:function(){r.Types.ResponseBase.call(this),this.value=[],this.PagingInfo={cookie:"",page:0,nextPage:1}}},Prefer:{ReturnRepresentation:"return=representation",Annotations:{AssociatedNavigationProperty:"Microsoft.Dynamics.CRM.associatednavigationproperty",LookupLogicalName:"Microsoft.Dynamics.CRM.lookuplogicalname",All:"*",FormattedValue:"OData.Community.Display.V1.FormattedValue",FetchXmlPagingCookie:"Microsoft.Dynamics.CRM.fetchxmlpagingcookie"}}};e.exports=r},function(e,t){function r(e,t,r){throw new Error(r?e+" requires the "+t+" parameter to be of type "+r:e+" requires the "+t+" parameter.")}var n={handleErrorResponse:function(e){throw new Error("Error: "+e.status+": "+e.message)},parameterCheck:function(e,t,n,a){void 0!==e&&null!==e&&""!=e||r(t,n,a)},stringParameterCheck:function(e,t,n){"string"!=typeof e&&r(t,n,"String")},arrayParameterCheck:function(e,t,n){e.constructor!==Array&&r(t,n,"Array")},stringOrArrayParameterCheck:function(e,t,n){e.constructor!==Array&&"string"!=typeof e&&r(t,n,"String or Array")},numberParameterCheck:function(e,t,n){if("number"!=typeof e){if("string"==typeof e&&e&&!isNaN(parseInt(e)))return;r(t,n,"Number")}},boolParameterCheck:function(e,t,n){"boolean"!=typeof e&&r(t,n,"Boolean")},guidParameterCheck:function(e,t,n){try{return/[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}/i.exec(e)[0]}catch(e){r(t,n,"GUID String")}},keyParameterCheck:function(e,t,a){try{n.stringParameterCheck(e,t,a);var i=/[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}/i.exec(e);if(i)return i[0];var o=e.split(",");if(o.length)for(var c=0;c<o.length;c++)o[c]=o[c].trim(),/^[\w\d\_]+\='[^\'\r\n]+'$/i.exec(o[c])[0];return o.join(",")}catch(e){r(t,a,"String representing GUID or Alternate Key")}},callbackParameterCheck:function(e,t,n){"function"!=typeof e&&r(t,n,"Function")}};e.exports=n},function(e,t){String.prototype.endsWith=function(e,t){var r=this.toString();("number"!=typeof t||!isFinite(t)||Math.floor(t)!==t||t>r.length)&&(t=r.length),t-=e.length;var n=r.lastIndexOf(e,t);return-1!==n&&n===t},String.prototype.startsWith=function(e,t){return t=t||0,this.substr(t,e.length)===e}},function(e,t,r){function n(){var e=(new Date).getTime();return"undefined"!=typeof performance&&"function"==typeof performance.now&&(e+=performance.now()),"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var r=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"===t?r:3&r|8).toString(16)})}function a(e){return e.Accept="application/json",e["OData-MaxVersion"]="4.0",e["OData-Version"]="4.0",e["Content-Type"]="application/json; charset=utf-8",e}function i(e,t){var r;return e&&(r=JSON.stringify(e,function(e,r){return e.endsWith("@odata.bind")&&"string"==typeof r&&(/\(\{[\w\d-]+\}\)/g.test(r)&&(r=r.replace(/(.+)\(\{([\w\d-]+)\}\)/g,"$1($2)")),r.startsWith(t.webApiUrl)||(r=t.webApiUrl+r.replace(/^\\/,""))),r}),r=r.replace(/[\u007F-\uFFFF]/g,function(e){return"\\u"+("0000"+e.charCodeAt(0).toString(16)).substr(-4)})),r}r(0);e.exports=function(e,t,o,c,s,u,l,p){s||(s={}),s=a(s);var h=i(c,o);if(t.length>2e3){var m="dwa_batch_"+n(),f=[];f.push("--"+m),f.push("Content-Type: application/http"),f.push("Content-Transfer-Encoding: binary\n"),f.push(e+" "+o.webApiUrl+t+" HTTP/1.1");for(var d in s)f.push(d+": "+s[d]),delete s[d];f.push("\n--"+m+"--"),h=f.join("\n"),s=a(s),s["Content-Type"]="multipart/mixed;boundary="+m,t="$batch",e="POST"}o.impersonate&&!s.MSCRMCallerID&&(s.MSCRMCallerID=o.impersonate);var y;"undefined"!=typeof XMLHttpRequest&&(y=r(10));var g=function(r){r&&(s||(s={}),s.Authorization="Bearer "+r.accessToken),y(e,o.webApiUrl+t,h,s,u,l,p)};o.onTokenRefresh&&(!s||s&&!s.Authorization)?o.onTokenRefresh(g):g()}},function(e,t,r){function n(e,t,r,a,i){var s={},u=[];if(a=null!=a?a:"&",e){e.navigationProperty&&(o.stringParameterCheck(e.navigationProperty,"DynamicsWebApi."+t,"request.navigationProperty"),r+="/"+e.navigationProperty),null!=e.select&&e.select.length&&(o.arrayParameterCheck(e.select,"DynamicsWebApi."+t,"request.select"),"retrieve"==t&&1==e.select.length&&e.select[0].endsWith("/$ref")?r+="/"+e.select[0]:(e.select[0].startsWith("/")&&"retrieve"==t&&(null==e.navigationProperty?r+=e.select.shift():e.select.shift()),e.select.length&&u.push("$select="+e.select.join(",")))),e.filter&&(o.stringParameterCheck(e.filter,"DynamicsWebApi."+t,"request.filter"),u.push("$filter="+e.filter)),e.savedQuery&&u.push("savedQuery="+o.guidParameterCheck(e.savedQuery,"DynamicsWebApi."+t,"request.savedQuery")),e.userQuery&&u.push("userQuery="+o.guidParameterCheck(e.userQuery,"DynamicsWebApi."+t,"request.userQuery")),e.count&&(o.boolParameterCheck(e.count,"DynamicsWebApi."+t,"request.count"),u.push("$count="+e.count)),e.top&&e.top>0&&(o.numberParameterCheck(e.top,"DynamicsWebApi."+t,"request.top"),u.push("$top="+e.top)),null!=e.orderBy&&e.orderBy.length&&(o.arrayParameterCheck(e.orderBy,"DynamicsWebApi."+t,"request.orderBy"),u.push("$orderby="+e.orderBy.join(",")));var l=c(e,t,i);if(l.length&&(s.Prefer=l),null!=e.ifmatch&&null!=e.ifnonematch)throw new Error("DynamicsWebApi."+t+". Either one of request.ifmatch or request.ifnonematch parameters should be used in a call, not both.");if(e.ifmatch&&(o.stringParameterCheck(e.ifmatch,"DynamicsWebApi."+t,"request.ifmatch"),s["If-Match"]=e.ifmatch),e.ifnonematch&&(o.stringParameterCheck(e.ifnonematch,"DynamicsWebApi."+t,"request.ifnonematch"),s["If-None-Match"]=e.ifnonematch),e.impersonate&&(o.stringParameterCheck(e.impersonate,"DynamicsWebApi."+t,"request.impersonate"),s.MSCRMCallerID=o.guidParameterCheck(e.impersonate,"DynamicsWebApi."+t,"request.impersonate")),e.token&&(o.stringParameterCheck(e.token,"DynamicsWebApi."+t,"request.token"),s.Authorization="Bearer "+e.token),e.duplicateDetection&&(o.boolParameterCheck(e.duplicateDetection,"DynamicsWebApi."+t,"request.duplicateDetection"),s["MSCRM.SuppressDuplicateDetection"]="false"),e.expand&&e.expand.length)if(o.stringOrArrayParameterCheck(e.expand,"DynamicsWebApi."+t,"request.expand"),"string"==typeof e.expand)u.push("$expand="+e.expand);else{for(var p=[],h=0;h<e.expand.length;h++)if(e.expand[h].property){var m=n(e.expand[h],t+" $expand",null,";"),f=m.query;f&&f.length&&(f="("+f+")"),p.push(e.expand[h].property+f)}p.length&&u.push("$expand="+p.join(","))}}return{url:r,query:u.join(a),headers:s}}function a(e){return["EntityDefinitions"].indexOf(e)>-1?e:e.toLowerCase()}function i(e,t,r){e.collection?o.stringParameterCheck(e.collection,"DynamicsWebApi."+t,"request.collection"):o.parameterCheck(e.collection,"DynamicsWebApi."+t,"request.collection");var i=a(e.collection);e.key?e.key=o.keyParameterCheck(e.key,"DynamicsWebApi."+t,"request.key"):e.id&&(e.key=o.guidParameterCheck(e.id,"DynamicsWebApi."+t,"request.id")),e.key&&(i+="("+e.key+")");var c=n(e,t,i,"&",r);return c.query&&(c.url+="?"+encodeURI(c.query)),e.hasOwnProperty("async")&&null!=e.async?(o.boolParameterCheck(e.async,"DynamicsWebApi."+t,"request.async"),c.async=e.async):c.async=!0,{url:c.url,headers:c.headers,async:c.async}}var o=(r(0),r(1)),c=r(12),s={convertRequestOptions:n,convertRequest:i};e.exports=s},function(e,t,r){var n={buildFunctionParameters:r(11),getFetchXmlPagingCookie:r(14),convertToReferenceObject:r(13)};e.exports=n},function(e,t,r){function n(e){var t={webApiVersion:"8.0",webApiUrl:null,impersonate:null,onTokenRefresh:null,includeAnnotations:null,maxPageSize:null,returnRepresentation:null};e||(e=t);var r=function(){if("undefined"!=typeof GetGlobalContext)return GetGlobalContext();if("undefined"!=typeof Xrm)return Xrm.Page.context;throw new Error("Xrm Context is not available.")},u=function(){var e=r();if(e){var t=e.getClientUrl();return t.match(/\/$/)&&(t=t.substring(0,t.length-1)),t}return""},l=function(){return u()+"/api/data/v"+t.webApiVersion+"/"};this.setConfig=function(e){e.webApiVersion&&(c.stringParameterCheck(e.webApiVersion,"DynamicsWebApi.setConfig","config.webApiVersion"),t.webApiVersion=e.webApiVersion),e.webApiUrl?(c.stringParameterCheck(e.webApiUrl,"DynamicsWebApi.setConfig","config.webApiUrl"),t.webApiUrl=e.webApiUrl):t.webApiUrl=l(),e.impersonate&&(t.impersonate=c.guidParameterCheck(e.impersonate,"DynamicsWebApi.setConfig","config.impersonate")),e.onTokenRefresh&&(c.callbackParameterCheck(e.onTokenRefresh,"DynamicsWebApi.setConfig","config.onTokenRefresh"),t.onTokenRefresh=e.onTokenRefresh),e.includeAnnotations&&(c.stringParameterCheck(e.includeAnnotations,"DynamicsWebApi.setConfig","config.includeAnnotations"),t.includeAnnotations=e.includeAnnotations),e.maxPageSize&&(c.numberParameterCheck(e.maxPageSize,"DynamicsWebApi.setConfig","config.maxPageSize"),t.maxPageSize=e.maxPageSize),e.returnRepresentation&&(c.boolParameterCheck(e.returnRepresentation,"DynamicsWebApi.setConfig","config.returnRepresentation"),t.returnRepresentation=e.returnRepresentation)},this.setConfig(e);var p=function(e,r,n,a,i){return new Promise(function(o,c){s(e,r,t,n,a,o,c,i)})};this.create=function(e,r,n,a){c.parameterCheck(e,"DynamicsWebApi.create","object"),c.stringParameterCheck(r,"DynamicsWebApi.create","collection"),n&&c.stringOrArrayParameterCheck(n,"DynamicsWebApi.create","prefer"),a&&c.arrayParameterCheck(a,"DynamicsWebApi.create","select");var i={collection:r,select:a,prefer:n},s=o.convertRequest(i,"create",t);return p("POST",s.url,e,s.headers,s.async).then(function(e){return e.data?e.data:/[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}/i.exec(e.headers["OData-EntityId"]?e.headers["OData-EntityId"]:e.headers["odata-entityid"])[0]})},this.retrieveRequest=function(e){c.parameterCheck(e,"DynamicsWebApi.retrieve","request");var r=o.convertRequest(e,"retrieve",t),n=e.select;return p("GET",r.url,null,r.headers,r.async).then(function(e){return null!=n&&1==n.length&&n[0].endsWith("/$ref")&&null!=e.data["@odata.id"]?i.convertToReferenceObject(e.data):e.data})},this.retrieve=function(e,t,r,n){c.stringParameterCheck(e,"DynamicsWebApi.retrieve","key"),e=c.keyParameterCheck(e,"DynamicsWebApi.retrieve","key"),c.stringParameterCheck(t,"DynamicsWebApi.retrieve","collection"),r&&r.length&&c.arrayParameterCheck(r,"DynamicsWebApi.retrieve","select"),n&&n.length&&c.stringOrArrayParameterCheck(n,"DynamicsWebApi.retrieve","expand");var a={collection:t,key:e,select:r,expand:n};return this.retrieveRequest(a)},this.updateRequest=function(e){c.parameterCheck(e,"DynamicsWebApi.update","request"),c.parameterCheck(e.entity,"DynamicsWebApi.update","request.entity"),null==e.ifmatch&&(e.ifmatch="*");var r=o.convertRequest(e,"update",t),n=e.ifmatch;return p("PATCH",r.url,e.entity,r.headers,r.async).then(function(e){return!e.data||e.data}).catch(function(e){if(n&&412==e.status)return!1;throw e})},this.update=function(e,t,r,n,a){c.stringParameterCheck(e,"DynamicsWebApi.update","key"),e=c.keyParameterCheck(e,"DynamicsWebApi.update","key"),c.parameterCheck(r,"DynamicsWebApi.update","object"),c.stringParameterCheck(t,"DynamicsWebApi.update","collection"),n&&c.stringOrArrayParameterCheck(n,"DynamicsWebApi.update","prefer"),a&&c.arrayParameterCheck(a,"DynamicsWebApi.update","select");var i={collection:t,key:e,select:a,prefer:n,entity:r};return this.updateRequest(i)},this.updateSingleProperty=function(e,r,n,a,i){c.stringParameterCheck(e,"DynamicsWebApi.updateSingleProperty","key"),e=c.keyParameterCheck(e,"DynamicsWebApi.updateSingleProperty","key"),c.parameterCheck(n,"DynamicsWebApi.updateSingleProperty","keyValuePair"),c.stringParameterCheck(r,"DynamicsWebApi.updateSingleProperty","collection");var s=Object.keys(n)[0],u=n[s];a&&c.stringOrArrayParameterCheck(a,"DynamicsWebApi.updateSingleProperty","prefer"),i&&c.arrayParameterCheck(i,"DynamicsWebApi.updateSingleProperty","select");var l={collection:r,key:e,select:i,prefer:a,navigationProperty:s},h=o.convertRequest(l,"updateSingleProperty",t);return p("PUT",h.url,{value:u},h.headers,h.async).then(function(e){if(e.data)return e.data})},this.deleteRequest=function(e){c.parameterCheck(e,"DynamicsWebApi.delete","request");var r=o.convertRequest(e,"deleteRequest",t),n=e.ifmatch;return p("DELETE",r.url,null,r.headers,r.async).then(function(){return!0}).catch(function(e){if(n&&412==e.status)return!1;throw e})},this.deleteRecord=function(e,t,r){c.stringParameterCheck(e,"DynamicsWebApi.deleteRecord","key"),e=c.keyParameterCheck(e,"DynamicsWebApi.deleteRecord","key"),c.stringParameterCheck(t,"DynamicsWebApi.deleteRecord","collection"),null!=r&&c.stringParameterCheck(r,"DynamicsWebApi.deleteRecord","propertyName");var n=t.toLowerCase()+"("+e+")";return null!=r&&(n+="/"+r),p("DELETE",n,null,null,!0).then(function(){})},this.upsertRequest=function(e){c.parameterCheck(e,"DynamicsWebApi.upsert","request"),c.parameterCheck(e.entity,"DynamicsWebApi.upsert","request.entity");var r=o.convertRequest(e,"upsert",t),n=e.ifnonematch,a=e.ifmatch;return p("PATCH",r.url,e.entity,r.headers,r.async).then(function(e){if(e.headers["OData-EntityId"]||e.headers["odata-entityid"]){return/[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}/i.exec(e.headers["OData-EntityId"]?e.headers["OData-EntityId"]:e.headers["odata-entityid"])[0]}if(e.data)return e.data}).catch(function(e){if(!(n&&412==e.status||a&&404==e.status))throw e})},this.upsert=function(e,t,r,n,a){c.stringParameterCheck(e,"DynamicsWebApi.upsert","key"),e=c.keyParameterCheck(e,"DynamicsWebApi.upsert","key"),c.parameterCheck(r,"DynamicsWebApi.upsert","object"),c.stringParameterCheck(t,"DynamicsWebApi.upsert","collection"),n&&c.stringOrArrayParameterCheck(n,"DynamicsWebApi.upsert","prefer"),a&&c.arrayParameterCheck(a,"DynamicsWebApi.upsert","select");var i={collection:t,key:e,select:a,prefer:n,entity:r};return this.upsertRequest(i)};var h=function(e,r){r&&!e.collection&&(e.collection="any");var n=o.convertRequest(e,"retrieveMultiple",t);r&&(c.stringParameterCheck(r,"DynamicsWebApi.retrieveMultiple","nextPageLink"),n.url=r.replace(t.webApiUrl,""));var a=e.count;return p("GET",n.url,null,n.headers,n.async).then(function(e){return a&&(e.data.oDataCount=e.data.oDataCount||0),e.data})};this.retrieveMultipleRequest=h;var m=function(e,t,r){var r=r||[];return h(e,t).then(function(t){return r=r.concat(t.value),t.oDataNextLink?m(e,t.oDataNextLink,r):{value:r}})};this.retrieveAllRequest=function(e){return m(e)},this.count=function(e,t){return null==t||null!=t&&!t.length?(c.stringParameterCheck(e,"DynamicsWebApi.count","collection"),p("GET",e.toLowerCase()+"/$count").then(function(e){return e.data?parseInt(e.data):0})):this.retrieveMultipleRequest({collection:e,filter:t,count:!0},null).then(function(e){return e.oDataCount?e.oDataCount:0})},this.countAll=function(e,t,r){return m({collection:e,filter:t,select:r}).then(function(e){return e&&e.value?e.value.length:0})},this.retrieveMultiple=function(e,t,r,n){return this.retrieveMultipleRequest({collection:e,select:t,filter:r},n)},this.retrieveAll=function(e,t,r){return m({collection:e,select:t,filter:r})};var f=function(e,r,n,s,u,l){c.stringParameterCheck(e,"DynamicsWebApi.executeFetchXml","type"),c.stringParameterCheck(r,"DynamicsWebApi.executeFetchXml","fetchXml"),s=s||1,c.numberParameterCheck(s,"DynamicsWebApi.executeFetchXml","pageNumber");var h='$1 page="'+s+'"';null!=u&&(c.stringParameterCheck(u,"DynamicsWebApi.executeFetchXml","pagingCookie"),h+=' paging-cookie="'+u+'"'),r=r.replace(/^(<fetch[\w\d\s'"=]+)/,h),n&&c.stringParameterCheck(n,"DynamicsWebApi.executeFetchXml","includeAnnotations"),l&&(l=c.guidParameterCheck(l,"DynamicsWebApi.executeFetchXml","impersonateUserId"));var m={collection:e,includeAnnotations:n,impersonate:l},f=o.convertRequest(m,"executeFetchXml",t),d=encodeURIComponent(r);return p("GET",f.url+"?fetchXml="+d,null,f.headers,f.async).then(function(e){return null!=e.data["@"+a.Prefer.Annotations.FetchXmlPagingCookie]&&(e.data.PagingInfo=i.getFetchXmlPagingCookie(e.data["@"+a.Prefer.Annotations.FetchXmlPagingCookie],s)),e.data})};this.fetch=this.executeFetchXml=f;var d=function(e,t,r,n,a,i,o){var o=o||[];return f(e,t,r,n,a,i).then(function(n){return o=o.concat(n.value),n.PagingInfo?d(e,t,r,n.PagingInfo.nextPage,n.PagingInfo.cookie,i,o):{value:o}})};this.fetchAll=this.executeFetchXmlAll=function(e,t,r,n){return d(e,t,r,null,null,n)},this.associate=function(e,r,n,a,i,o){c.stringParameterCheck(e,"DynamicsWebApi.associate","primarycollection"),c.stringParameterCheck(a,"DynamicsWebApi.associate","relatedcollection"),c.stringParameterCheck(n,"DynamicsWebApi.associate","relationshipName"),r=c.guidParameterCheck(r,"DynamicsWebApi.associate","primaryId"),i=c.guidParameterCheck(i,"DynamicsWebApi.associate","relatedId");var s={};return null!=o&&(o=c.guidParameterCheck(o,"DynamicsWebApi.associate","impersonateUserId"),s.MSCRMCallerID=o),p("POST",e+"("+r+")/"+n+"/$ref",{"@odata.id":t.webApiUrl+a+"("+i+")"},s).then(function(){})},this.disassociate=function(e,t,r,n,a){c.stringParameterCheck(e,"DynamicsWebApi.disassociate","primarycollection"),c.stringParameterCheck(r,"DynamicsWebApi.disassociate","relationshipName"),t=c.guidParameterCheck(t,"DynamicsWebApi.disassociate","primaryId"),n=c.guidParameterCheck(n,"DynamicsWebApi.disassociate","relatedId");var i={};return null!=a&&(a=c.guidParameterCheck(a,"DynamicsWebApi.associate","impersonateUserId"),i.MSCRMCallerID=a),p("DELETE",e+"("+t+")/"+r+"("+n+")/$ref",null,i).then(function(){})},this.associateSingleValued=function(e,r,n,a,i,o){c.stringParameterCheck(e,"DynamicsWebApi.associateSingleValued","collection"),r=c.guidParameterCheck(r,"DynamicsWebApi.associateSingleValued","id"),i=c.guidParameterCheck(i,"DynamicsWebApi.associateSingleValued","relatedId"),c.stringParameterCheck(n,"DynamicsWebApi.associateSingleValued","singleValuedNavigationPropertyName"),c.stringParameterCheck(a,"DynamicsWebApi.associateSingleValued","relatedcollection");var s={};return null!=o&&(o=c.guidParameterCheck(o,"DynamicsWebApi.associate","impersonateUserId"),s.MSCRMCallerID=o),p("PUT",e+"("+r+")/"+n+"/$ref",{"@odata.id":t.webApiUrl+a+"("+i+")"},s).then(function(){})},this.disassociateSingleValued=function(e,t,r,n){c.stringParameterCheck(e,"DynamicsWebApi.disassociateSingleValued","collection"),t=c.guidParameterCheck(t,"DynamicsWebApi.disassociateSingleValued","id"),c.stringParameterCheck(r,"DynamicsWebApi.disassociateSingleValued","singleValuedNavigationPropertyName");var a={};return null!=n&&(n=c.guidParameterCheck(n,"DynamicsWebApi.associate","impersonateUserId"),a.MSCRMCallerID=n),p("DELETE",e+"("+t+")/"+r+"/$ref",null,a).then(function(){})},this.executeUnboundFunction=function(e,t,r){return y(e,t,null,null,r)},this.executeBoundFunction=function(e,t,r,n,a){return y(r,n,t,e,a)};var y=function(e,t,r,n,a){c.stringParameterCheck(e,"DynamicsWebApi.executeFunction","functionName");var o=e+i.buildFunctionParameters(t);null!=r&&(c.stringParameterCheck(r,"DynamicsWebApi.executeFunction","collection"),n=c.guidParameterCheck(n,"DynamicsWebApi.executeFunction","id"),o=r+"("+n+")/"+o);var s={};return a&&(s.MSCRMCallerID=c.guidParameterCheck(a,"DynamicsWebApi.executeFunction","impersonateUserId")),p("GET",o,null,s).then(function(e){if(e.data)return e.data})};this.executeUnboundAction=function(e,t,r){return g(e,t,null,null,r)},this.executeBoundAction=function(e,t,r,n,a){return g(r,n,t,e,a)};var g=function(e,t,r,n,a){c.stringParameterCheck(e,"DynamicsWebApi.executeAction","actionName");var i=e;null!=r&&(c.stringParameterCheck(r,"DynamicsWebApi.executeAction","collection"),n=c.guidParameterCheck(n,"DynamicsWebApi.executeAction","id"),i=r+"("+n+")/"+i);var o={};return null!=a&&(a=c.guidParameterCheck(a,"DynamicsWebApi.executeAction","impersonateUserId"),o.MSCRMCallerID=a),p("POST",i,t,o).then(function(e){if(e.data)return e.data})};this.initializeInstance=function(e){return e||(e=t),new n(e)}}var a=r(0),i=r(5),o=r(4),c=r(1),s=r(3);String.prototype.endsWith&&String.prototype.startsWith||r(2),e.exports=n},function(e,t){e.exports=function(e,t){return"string"==typeof t&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.exec(t)?new Date(t):t}},function(e,t,r){function n(e){var t=e.substr(0,e.indexOf("\r\n")),r=e.split(t);r.shift(),r.pop();for(var n=[],a=0;a<r.length;a++){var i=r[a],c=i.substring(i.indexOf("{"),i.lastIndexOf("}")+1);n.push(JSON.parse(c,o))}return n}function a(e){for(var t=Object.keys(e),r=0;r<t.length;r++){if(null!=e[t[r]]&&e[t[r]].constructor===Array)for(var n=0;n<e[t[r]].length;n++)e[t[r]][n]=a(e[t[r]][n]);if(-1!=t[r].indexOf("@")){var o=t[r].split("@"),c=null;switch(o[1]){case"odata.context":c="oDataContext";break;case"odata.count":c="oDataCount",e[t[r]]=null!=e[t[r]]?parseInt(e[t[r]]):0;break;case"odata.nextLink":c="oDataNextLink";break;case i.Prefer.Annotations.FormattedValue:c=o[0]+"_Formatted";break;case i.Prefer.Annotations.AssociatedNavigationProperty:c=o[0]+"_NavigationProperty";break;case i.Prefer.Annotations.LookupLogicalName:c=o[0]+"_LogicalName"}c&&(e[c]=e[t[r]])}}return e}var i=r(0),o=r(7);String.prototype.endsWith&&String.prototype.startsWith||r(2),e.exports=function(e){var t=null;return e.length&&(t=t=e.indexOf("--batchresponse_")>-1?n(e)[0]:JSON.parse(e,o),t=a(t)),t}},function(e,t){e.exports=function(e){var t={};if(!e)return t;for(var r=e.split("\r\n"),n=0,a=r.length;n<a;n++){var i=r[n],o=i.indexOf(": ");o>0&&(t[i.substring(0,o)]=i.substring(o+2))}return t}},function(e,t,r){var n=r(8),a=r(9),i=function(e,t,r,i,o,c,s){var u=new XMLHttpRequest;u.open(e,t,s);for(var l in i)u.setRequestHeader(l,i[l]);u.onreadystatechange=function(){if(4===u.readyState){switch(u.status){case 200:case 201:case 204:case 304:var e=n(u.responseText),t={data:e,headers:a(u.getAllResponseHeaders()),status:u.status};o(t);break;default:var r;try{r=JSON.parse(u.response).error}catch(e){r=u.response.length>0?{message:u.response}:{message:"Unexpected Error"}}r.status=u.status,c(r)}u=null}},u.onerror=function(){c({message:"Network Error"}),u=null},u.ontimeout=function(e){c({message:"Request Timed Out"}),u=null},r?u.send(r):u.send()};e.exports=i},function(e,t){e.exports=function(e){if(e){for(var t=Object.keys(e),r="",n="",a=1;a<=t.length;a++){var i=t[a-1],o=e[i];a>1&&(r+=",",n+="&"),r+=i+"=@p"+a,n+="@p"+a+"="+("string"==typeof o?"'"+o+"'":o)}return"("+r+")?"+n}return"()"}},function(e,t,r){var n=r(0),a=r(1);e.exports=function(e,t,r){var i=e.returnRepresentation,o=e.includeAnnotations,c=e.maxPageSize;if(e.prefer&&e.prefer.length){a.stringOrArrayParameterCheck(e.prefer,"DynamicsWebApi."+t,"request.prefer");var s=e.prefer;"string"==typeof s&&(s=s.split(","));for(var u in s){var l=s[u].trim();l===n.Prefer.ReturnRepresentation?i=!0:l.startsWith("odata.include-annotations=")?o=l.replace("odata.include-annotations=","").replace(/"/g,""):l.startsWith("odata.maxpagesize=")&&(c=l.replace("odata.maxpagesize=","").replace(/"/g,""))}}r&&(null==i&&(i=r.returnRepresentation),o=o||r.includeAnnotations,c=c||r.maxPageSize);var s=[];return i&&(a.boolParameterCheck(i,"DynamicsWebApi."+t,"request.returnRepresentation"),s.push(n.Prefer.ReturnRepresentation)),o&&(a.stringParameterCheck(o,"DynamicsWebApi."+t,"request.includeAnnotations"),s.push('odata.include-annotations="'+o+'"')),c&&c>0&&(a.numberParameterCheck(c,"DynamicsWebApi."+t,"request.maxPageSize"),s.push("odata.maxpagesize="+c)),s.join(",")}},function(e,t){e.exports=function(e){var t=/\/(\w+)\(([0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12})/i.exec(e["@odata.id"]);return{id:t[2],collection:t[1],oDataContext:e["@odata.context"]}}},function(e,t){e.exports=function(e,t){e=e||"",t=t||1,e=unescape(unescape(e));var r=/pagingcookie="(<cookie page="(\d+)".+<\/cookie>)/.exec(e);if(null!=r){var n=parseInt(r[2]);return{cookie:r[1].replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"'").replace(/\'/g,"&quot;"),page:n,nextPage:n+1}}return{cookie:"",page:t,nextPage:t+1}}}])});
/*! dynamics-web-api v1.4.0 (c) 2017 Aleksandr Rogov */
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("DynamicsWebApi",[],t):"object"==typeof exports?exports.DynamicsWebApi=t():e.DynamicsWebApi=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var a=n[r]={i:r,l:!1,exports:{}};return e[r].call(a.exports,a,a.exports,t),a.l=!0,a.exports}var n={};return t.m=e,t.c=n,t.i=function(e){return e},t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=5)}([function(e,t){var n={Types:{ResponseBase:function(){this.oDataContext=""},Response:function(){n.Types.ResponseBase.call(this),this.value={}},ReferenceResponse:function(){n.Types.ResponseBase.call(this),this.id="",this.collection=""},MultipleResponse:function(){n.Types.ResponseBase.call(this),this.oDataNextLink="",this.oDataCount=0,this.value=[]},FetchXmlResponse:function(){n.Types.ResponseBase.call(this),this.value=[],this.PagingInfo={cookie:"",page:0,nextPage:1}}},Prefer:{ReturnRepresentation:"return=representation",Annotations:{AssociatedNavigationProperty:"Microsoft.Dynamics.CRM.associatednavigationproperty",LookupLogicalName:"Microsoft.Dynamics.CRM.lookuplogicalname",All:"*",FormattedValue:"OData.Community.Display.V1.FormattedValue",FetchXmlPagingCookie:"Microsoft.Dynamics.CRM.fetchxmlpagingcookie"}}};e.exports=n},function(e,t){function n(e,t,n){throw new Error(n?e+" requires the "+t+" parameter to be of type "+n:e+" requires the "+t+" parameter.")}var r={handleErrorResponse:function(e){throw new Error("Error: "+e.status+": "+e.message)},parameterCheck:function(e,t,r,a){void 0!==e&&null!==e&&""!=e||n(t,r,a)},stringParameterCheck:function(e,t,r){"string"!=typeof e&&n(t,r,"String")},arrayParameterCheck:function(e,t,r){e.constructor!==Array&&n(t,r,"Array")},stringOrArrayParameterCheck:function(e,t,r){e.constructor!==Array&&"string"!=typeof e&&n(t,r,"String or Array")},numberParameterCheck:function(e,t,r){if("number"!=typeof e){if("string"==typeof e&&e&&!isNaN(parseInt(e)))return;n(t,r,"Number")}},boolParameterCheck:function(e,t,r){"boolean"!=typeof e&&n(t,r,"Boolean")},guidParameterCheck:function(e,t,r){try{return/[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}/i.exec(e)[0]}catch(e){n(t,r,"GUID String")}},keyParameterCheck:function(e,t,a){try{r.stringParameterCheck(e,t,a);var i=/[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}/i.exec(e);if(i)return i[0];var o=e.split(",");if(o.length)for(var c=0;c<o.length;c++)o[c]=o[c].trim(),/^[\w\d\_]+\='[^\'\r\n]+'$/i.exec(o[c])[0];return o.join(",")}catch(e){n(t,a,"String representing GUID or Alternate Key")}},callbackParameterCheck:function(e,t,r){"function"!=typeof e&&n(t,r,"Function")}};e.exports=r},function(e,t){String.prototype.endsWith=function(e,t){var n=this.toString();("number"!=typeof t||!isFinite(t)||Math.floor(t)!==t||t>n.length)&&(t=n.length),t-=e.length;var r=n.lastIndexOf(e,t);return-1!==r&&r===t},String.prototype.startsWith=function(e,t){return t=t||0,this.substr(t,e.length)===e}},function(e,t,n){function r(e){return void 0===e||"unknown"==typeof e||null==e}function a(){var e=(new Date).getTime();return"undefined"!=typeof performance&&"function"==typeof performance.now&&(e+=performance.now()),"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var n=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"===t?n:3&n|8).toString(16)})}function i(){if("undefined"!=typeof GetGlobalContext)return GetGlobalContext();if("undefined"!=typeof Xrm){if(!r(Xrm.Utility)&&!r(Xrm.Utility.getGlobalContext))return Xrm.Utility.getGlobalContext();if(!r(Xrm.Page)&&!r(Xrm.Page.context))return Xrm.Page.context}throw new Error("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.")}function o(){var e=i();if(e){var t=e.getClientUrl();return t.match(/\/$/)&&(t=t.substring(0,t.length-1)),t}return""}function c(e){return o()+"/api/data/v"+e+"/"}function s(){return"undefined"!=typeof Xrm?Xrm.Internal:null}var u={buildFunctionParameters:n(11),getFetchXmlPagingCookie:n(14),convertToReferenceObject:n(13),isNull:r,generateUUID:a,getXrmContext:i,getXrmInternal:s,getClientUrl:o,initWebApiUrl:c};e.exports=u},function(e,t,n){function r(e){var t=f.getXrmInternal();if(!f.isNull(t)){var n=t.getEntitySetName(e);return n||e}var n=null;if(!f.isNull(p)&&(n=p[e],f.isNull(n)))for(var r in p)if(p[r]==e)return e;return n}function a(e){return e.Accept="application/json",e["OData-MaxVersion"]="4.0",e["OData-Version"]="4.0",e["Content-Type"]="application/json; charset=utf-8",e}function i(e,t){var n;return e&&(n=JSON.stringify(e,function(e,n){if((e.endsWith("@odata.bind")||e.endsWith("@odata.id"))&&"string"==typeof n){if(/\(\{[\w\d-]+\}\)/g.test(n)&&(n=n.replace(/(.+)\(\{([\w\d-]+)\}\)/g,"$1($2)")),t.useEntityNames){var a=/([\w_]+)(\([\d\w-]+\))$/,i=a.exec(n);if(i.length>2){var o=r(i[1]);f.isNull(o)||(n=n.replace(a,o+"$2"))}}n.startsWith(t.webApiUrl)||(n=t.webApiUrl+n.replace(/^\\/,""))}return n}),n=n.replace(/[\u007F-\uFFFF]/g,function(e){return"\\u"+("0000"+e.charCodeAt(0).toString(16)).substr(-4)})),n}function o(e,t,r,o,c,s,u,l){c||(c={}),c=a(c);var p=i(o,r);if(t.length>2e3){var m="dwa_batch_"+f.generateUUID(),h=[];h.push("--"+m),h.push("Content-Type: application/http"),h.push("Content-Transfer-Encoding: binary\n"),h.push(e+" "+r.webApiUrl+t+" HTTP/1.1");for(var d in c)h.push(d+": "+c[d]),delete c[d];h.push("\n--"+m+"--"),p=h.join("\n"),c=a(c),c["Content-Type"]="multipart/mixed;boundary="+m,t="$batch",e="POST"}r.impersonate&&!c.MSCRMCallerID&&(c.MSCRMCallerID=r.impersonate);var y;y=n(9);var g=function(n){n&&(c||(c={}),c.Authorization="Bearer "+n.accessToken),y(e,r.webApiUrl+t,p,c,s,u,l)};r.onTokenRefresh&&(!c||c&&!c.Authorization)?r.onTokenRefresh(g):g()}function c(e,t,n,a){var i=function(t){p={};for(var a=0;a<t.data.value.length;a++)p[t.data.value[a].LogicalName]=t.data.value[a].LogicalCollectionName;n(r(e))},c=function(e){a({message:"Unable to fetch EntityDefinitions. Error: "+e.message})},s=m.convertRequest({collection:"EntityDefinitions",select:["LogicalCollectionName","LogicalName"],noCache:!0},"retrieveMultiple",t);o("GET",s.url,t,null,s.headers,i,c,s.async)}function s(e){return["EntityDefinitions","$metadata"].indexOf(e)>-1}function u(e,t,n,a){if(s(e)||f.isNull(e))return void n(e);if(e=e.toLowerCase(),!t.useEntityNames)return void n(e);try{var i=r(e);f.isNull(i)?c(e,t,n,a):n(i)}catch(e){a({message:"Unable to fetch Collection Names. Error: "+e.message})}}function l(e,t,n,r,a,i){var c=function(c){t.collection=c;var s=m.convertRequest(t,n,r);o(e,s.url,r,t.data||t.entity,s.headers,a,i,s.async)};u(t.collection,r,c,i)}var p,f=(n(0),n(3)),m=n(10);e.exports={sendRequest:o,makeRequest:l,getCollectionName:r}},function(e,t,n){function r(e){var t={webApiVersion:"8.0",webApiUrl:null,impersonate:null,onTokenRefresh:null,includeAnnotations:null,maxPageSize:null,returnRepresentation:null};e||(e=t),this.setConfig=function(e){e.webApiVersion&&(o.stringParameterCheck(e.webApiVersion,"DynamicsWebApi.setConfig","config.webApiVersion"),t.webApiVersion=e.webApiVersion),e.webApiUrl?(o.stringParameterCheck(e.webApiUrl,"DynamicsWebApi.setConfig","config.webApiUrl"),t.webApiUrl=e.webApiUrl):t.webApiUrl=i.initWebApiUrl(t.webApiVersion),e.impersonate&&(t.impersonate=o.guidParameterCheck(e.impersonate,"DynamicsWebApi.setConfig","config.impersonate")),e.onTokenRefresh&&(o.callbackParameterCheck(e.onTokenRefresh,"DynamicsWebApi.setConfig","config.onTokenRefresh"),t.onTokenRefresh=e.onTokenRefresh),e.includeAnnotations&&(o.stringParameterCheck(e.includeAnnotations,"DynamicsWebApi.setConfig","config.includeAnnotations"),t.includeAnnotations=e.includeAnnotations),e.maxPageSize&&(o.numberParameterCheck(e.maxPageSize,"DynamicsWebApi.setConfig","config.maxPageSize"),t.maxPageSize=e.maxPageSize),e.returnRepresentation&&(o.boolParameterCheck(e.returnRepresentation,"DynamicsWebApi.setConfig","config.returnRepresentation"),t.returnRepresentation=e.returnRepresentation),e.useEntityNames&&(o.boolParameterCheck(e.useEntityNames,"DynamicsWebApi.setConfig","config.useEntityNames"),t.useEntityNames=e.useEntityNames)},this.setConfig(e);var n=function(e,n,r){return new Promise(function(a,i){c.makeRequest(e,n,r,t,a,i)})};this.create=function(e,t,r,a){return o.parameterCheck(e,"DynamicsWebApi.create","object"),o.stringParameterCheck(t,"DynamicsWebApi.create","collection"),r&&o.stringOrArrayParameterCheck(r,"DynamicsWebApi.create","prefer"),a&&o.arrayParameterCheck(a,"DynamicsWebApi.create","select"),n("POST",{collection:t,select:a,prefer:r,entity:e},"create").then(function(e){return e.data?e.data:/[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}/i.exec(e.headers["OData-EntityId"]?e.headers["OData-EntityId"]:e.headers["odata-entityid"])[0]})},this.retrieveRequest=function(e){o.parameterCheck(e,"DynamicsWebApi.retrieve","request");var t=e.select;return n("GET",e,"retrieve").then(function(e){return null!=t&&1==t.length&&t[0].endsWith("/$ref")&&null!=e.data["@odata.id"]?i.convertToReferenceObject(e.data):e.data})},this.retrieve=function(e,t,n,r){o.stringParameterCheck(e,"DynamicsWebApi.retrieve","key"),e=o.keyParameterCheck(e,"DynamicsWebApi.retrieve","key"),o.stringParameterCheck(t,"DynamicsWebApi.retrieve","collection"),n&&n.length&&o.arrayParameterCheck(n,"DynamicsWebApi.retrieve","select"),r&&r.length&&o.stringOrArrayParameterCheck(r,"DynamicsWebApi.retrieve","expand");var a={collection:t,key:e,select:n,expand:r};return this.retrieveRequest(a)},this.updateRequest=function(e){o.parameterCheck(e,"DynamicsWebApi.update","request"),null==e.ifmatch&&(e.ifmatch="*");var t=e.ifmatch;return n("PATCH",e,"update").then(function(e){return!e.data||e.data}).catch(function(e){if(t&&412==e.status)return!1;throw e})},this.update=function(e,t,n,r,a){o.stringParameterCheck(e,"DynamicsWebApi.update","key"),e=o.keyParameterCheck(e,"DynamicsWebApi.update","key"),o.parameterCheck(n,"DynamicsWebApi.update","object"),o.stringParameterCheck(t,"DynamicsWebApi.update","collection"),r&&o.stringOrArrayParameterCheck(r,"DynamicsWebApi.update","prefer"),a&&o.arrayParameterCheck(a,"DynamicsWebApi.update","select");var i={collection:t,key:e,select:a,prefer:r,entity:n};return this.updateRequest(i)},this.updateSingleProperty=function(e,t,r,a,i){o.stringParameterCheck(e,"DynamicsWebApi.updateSingleProperty","key"),e=o.keyParameterCheck(e,"DynamicsWebApi.updateSingleProperty","key"),o.parameterCheck(r,"DynamicsWebApi.updateSingleProperty","keyValuePair"),o.stringParameterCheck(t,"DynamicsWebApi.updateSingleProperty","collection");var c=Object.keys(r)[0],s=r[c];return a&&o.stringOrArrayParameterCheck(a,"DynamicsWebApi.updateSingleProperty","prefer"),i&&o.arrayParameterCheck(i,"DynamicsWebApi.updateSingleProperty","select"),n("PUT",{collection:t,key:e,select:i,prefer:a,navigationProperty:c,data:{value:s}},"updateSingleProperty").then(function(e){if(e.data)return e.data})},this.deleteRequest=function(e){o.parameterCheck(e,"DynamicsWebApi.delete","request");var t=e.ifmatch;return n("DELETE",e,"delete").then(function(){return!0}).catch(function(e){if(t&&412==e.status)return!1;throw e})},this.deleteRecord=function(e,t,r){return o.stringParameterCheck(t,"DynamicsWebApi.deleteRecord","collection"),null!=r&&o.stringParameterCheck(r,"DynamicsWebApi.deleteRecord","propertyName"),n("DELETE",{navigationProperty:r,collection:t,key:e},"deleteRecord").then(function(){})},this.upsertRequest=function(e){o.parameterCheck(e,"DynamicsWebApi.upsert","request");var t=e.ifnonematch,r=e.ifmatch;return n("PATCH",e,"upsert").then(function(e){if(e.headers["OData-EntityId"]||e.headers["odata-entityid"]){return/[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}/i.exec(e.headers["OData-EntityId"]?e.headers["OData-EntityId"]:e.headers["odata-entityid"])[0]}if(e.data)return e.data}).catch(function(e){if(!(t&&412==e.status||r&&404==e.status))throw e})},this.upsert=function(e,t,n,r,a){o.stringParameterCheck(e,"DynamicsWebApi.upsert","key"),e=o.keyParameterCheck(e,"DynamicsWebApi.upsert","key"),o.parameterCheck(n,"DynamicsWebApi.upsert","object"),o.stringParameterCheck(t,"DynamicsWebApi.upsert","collection"),r&&o.stringOrArrayParameterCheck(r,"DynamicsWebApi.upsert","prefer"),a&&o.arrayParameterCheck(a,"DynamicsWebApi.upsert","select");var i={collection:t,key:e,select:a,prefer:r,entity:n};return this.upsertRequest(i)};var s=function(e,t){t&&(o.stringParameterCheck(t,"DynamicsWebApi.retrieveMultiple","nextPageLink"),e.url=t);var r=e.count;return n("GET",e,"retrieveMultiple").then(function(e){return r&&(e.data.oDataCount=e.data.oDataCount||0),e.data})};this.retrieveMultipleRequest=s;var u=function(e,t,n){var n=n||[];return s(e,t).then(function(t){return n=n.concat(t.value),t.oDataNextLink?u(e,t.oDataNextLink,n):{value:n}})};this.retrieveAllRequest=function(e){return u(e)},this.count=function(e,t){if(null==t||null!=t&&!t.length){return n("GET",{collection:e,navigationProperty:"$count"},"count").then(function(e){return e.data?parseInt(e.data):0})}return this.retrieveMultipleRequest({collection:e,filter:t,count:!0},null).then(function(e){return e.oDataCount?e.oDataCount:0})},this.countAll=function(e,t,n){return u({collection:e,filter:t,select:n}).then(function(e){return e&&e.value?e.value.length:0})},this.retrieveMultiple=function(e,t,n,r){return this.retrieveMultipleRequest({collection:e,select:t,filter:n},r)},this.retrieveAll=function(e,t,n){return u({collection:e,select:t,filter:n})};var l=function(e,t,r,c,s,u){o.stringParameterCheck(t,"DynamicsWebApi.executeFetchXml","fetchXml"),c=c||1,o.numberParameterCheck(c,"DynamicsWebApi.executeFetchXml","pageNumber");var l='$1 page="'+c+'"';return null!=s&&(o.stringParameterCheck(s,"DynamicsWebApi.executeFetchXml","pagingCookie"),l+=' paging-cookie="'+s+'"'),t=t.replace(/^(<fetch[\w\d\s'"=]+)/,l),n("GET",{collection:e,includeAnnotations:r,impersonate:u,fetchXml:t,impersonate:u,includeAnnotations:r},"executeFetchXml").then(function(e){return null!=e.data["@"+a.Prefer.Annotations.FetchXmlPagingCookie]&&(e.data.PagingInfo=i.getFetchXmlPagingCookie(e.data["@"+a.Prefer.Annotations.FetchXmlPagingCookie],c)),e.data})};this.fetch=this.executeFetchXml=l;var p=function(e,t,n,r,a,i,o){var o=o||[];return l(e,t,n,r,a,i).then(function(r){return o=o.concat(r.value),r.PagingInfo?p(e,t,n,r.PagingInfo.nextPage,r.PagingInfo.cookie,i,o):{value:o}})};this.fetchAll=this.executeFetchXmlAll=function(e,t,n,r){return p(e,t,n,null,null,r)},this.associate=function(e,t,r,a,i,c){return o.stringParameterCheck(a,"DynamicsWebApi.associate","relatedcollection"),o.stringParameterCheck(r,"DynamicsWebApi.associate","relationshipName"),t=o.keyParameterCheck(t,"DynamicsWebApi.associate","primaryKey"),i=o.keyParameterCheck(i,"DynamicsWebApi.associate","relatedKey"),n("POST",{_additionalUrl:r+"/$ref",collection:e,key:t,impersonate:c,data:{"@odata.id":a+"("+i+")"}},"associate").then(function(){})},this.disassociate=function(e,t,r,a,i){return o.stringParameterCheck(r,"DynamicsWebApi.disassociate","relationshipName"),a=o.keyParameterCheck(a,"DynamicsWebApi.disassociate","relatedId"),n("DELETE",{_additionalUrl:r+"("+a+")/$ref",collection:e,key:t,impersonate:i},"disassociate").then(function(){})},this.associateSingleValued=function(e,t,r,a,i,c){return i=o.keyParameterCheck(i,"DynamicsWebApi.associateSingleValued","relatedKey"),o.stringParameterCheck(r,"DynamicsWebApi.associateSingleValued","singleValuedNavigationPropertyName"),o.stringParameterCheck(a,"DynamicsWebApi.associateSingleValued","relatedcollection"),n("PUT",{_additionalUrl:r+"/$ref",collection:e,key:t,impersonate:c,data:{"@odata.id":a+"("+i+")"}},"associateSingleValued").then(function(){})},this.disassociateSingleValued=function(e,t,r,a){return o.stringParameterCheck(r,"DynamicsWebApi.disassociateSingleValued","singleValuedNavigationPropertyName"),n("DELETE",{_additionalUrl:r+"/$ref",key:t,collection:e,impersonate:a},"disassociateSingleValued").then(function(){})},this.executeUnboundFunction=function(e,t,n){return f(e,t,null,null,n,!0)},this.executeBoundFunction=function(e,t,n,r,a){return f(n,r,t,e,a)};var f=function(e,t,r,a,c,s){o.stringParameterCheck(e,"DynamicsWebApi.executeFunction","functionName");var u={_additionalUrl:e+i.buildFunctionParameters(t),_unboundRequest:s,key:a,collection:r,impersonate:c};return n("GET",u,"executeFunction").then(function(e){if(e.data)return e.data})};this.executeUnboundAction=function(e,t,n){return m(e,t,null,null,n,!0)},this.executeBoundAction=function(e,t,n,r,a){return m(n,r,t,e,a)};var m=function(e,t,r,a,i,c){return o.stringParameterCheck(e,"DynamicsWebApi.executeAction","actionName"),n("POST",{_additionalUrl:e,_unboundRequest:c,collection:r,key:a,impersonate:i,data:t},"executeAction").then(function(e){if(e.data)return e.data})};this.initializeInstance=function(e){return e||(e=t),new r(e)}}var a=n(0),i=n(3),o=n(1),c=n(4);String.prototype.endsWith&&String.prototype.startsWith||n(2),r.prototype.utility={getCollectionName:c.getCollectionName},e.exports=r},function(e,t){e.exports=function(e,t){var n;return"string"==typeof t&&(n=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:Z|[-+]\d{2}:\d{2})$/.exec(t))?new Date(Date.UTC(+n[1],+n[2]-1,+n[3],+n[4],+n[5],+n[6])):t}},function(e,t,n){function r(e){var t=e.substr(0,e.indexOf("\r\n")),n=e.split(t);n.shift(),n.pop();for(var r=[],a=0;a<n.length;a++){var i=n[a],c=i.substring(i.indexOf("{"),i.lastIndexOf("}")+1);r.push(JSON.parse(c,o))}return r}function a(e){for(var t=Object.keys(e),n=0;n<t.length;n++){if(null!=e[t[n]]&&e[t[n]].constructor===Array)for(var r=0;r<e[t[n]].length;r++)e[t[n]][r]=a(e[t[n]][r]);if(-1!=t[n].indexOf("@")){var o=t[n].split("@"),c=null;switch(o[1]){case"odata.context":c="oDataContext";break;case"odata.count":c="oDataCount",e[t[n]]=null!=e[t[n]]?parseInt(e[t[n]]):0;break;case"odata.nextLink":c="oDataNextLink";break;case i.Prefer.Annotations.FormattedValue:c=o[0]+"_Formatted";break;case i.Prefer.Annotations.AssociatedNavigationProperty:c=o[0]+"_NavigationProperty";break;case i.Prefer.Annotations.LookupLogicalName:c=o[0]+"_LogicalName"}c&&(e[c]=e[t[n]])}}return e}var i=n(0),o=n(6);String.prototype.endsWith&&String.prototype.startsWith||n(2),e.exports=function(e){var t=null;return e.length&&(t=t=e.indexOf("--batchresponse_")>-1?r(e)[0]:JSON.parse(e,o),t=a(t)),t}},function(e,t){e.exports=function(e){var t={};if(!e)return t;for(var n=e.split("\r\n"),r=0,a=n.length;r<a;r++){var i=n[r],o=i.indexOf(": ");o>0&&(t[i.substring(0,o)]=i.substring(o+2))}return t}},function(e,t,n){var r=n(7),a=n(8),i=function(e,t,n,i,o,c,s){var u=new XMLHttpRequest;u.open(e,t,s);for(var l in i)u.setRequestHeader(l,i[l]);u.onreadystatechange=function(){if(4===u.readyState){switch(u.status){case 200:case 201:case 204:case 304:var e=r(u.responseText),t={data:e,headers:a(u.getAllResponseHeaders()),status:u.status};o(t);break;default:var n;try{n=JSON.parse(u.response).error}catch(e){n=u.response.length>0?{message:u.response}:{message:"Unexpected Error"}}n.status=u.status,c(n)}u=null}},u.onerror=function(){c({message:"Network Error"}),u=null},u.ontimeout=function(e){c({message:"Request Timed Out"}),u=null},n?u.send(n):u.send()};e.exports=i},function(e,t,n){function r(e,t,n,a,c){var s={},u=[];if(a=null!=a?a:"&",e){e.navigationProperty&&(i.stringParameterCheck(e.navigationProperty,"DynamicsWebApi."+t,"request.navigationProperty"),n+="/"+e.navigationProperty),null!=e.select&&e.select.length&&(i.arrayParameterCheck(e.select,"DynamicsWebApi."+t,"request.select"),"retrieve"==t&&1==e.select.length&&e.select[0].endsWith("/$ref")?n+="/"+e.select[0]:(e.select[0].startsWith("/")&&"retrieve"==t&&(null==e.navigationProperty?n+=e.select.shift():e.select.shift()),e.select.length&&u.push("$select="+e.select.join(",")))),e.filter&&(i.stringParameterCheck(e.filter,"DynamicsWebApi."+t,"request.filter"),u.push("$filter="+e.filter)),e.savedQuery&&u.push("savedQuery="+i.guidParameterCheck(e.savedQuery,"DynamicsWebApi."+t,"request.savedQuery")),e.userQuery&&u.push("userQuery="+i.guidParameterCheck(e.userQuery,"DynamicsWebApi."+t,"request.userQuery")),e.count&&(i.boolParameterCheck(e.count,"DynamicsWebApi."+t,"request.count"),u.push("$count="+e.count)),e.top&&e.top>0&&(i.numberParameterCheck(e.top,"DynamicsWebApi."+t,"request.top"),u.push("$top="+e.top)),null!=e.orderBy&&e.orderBy.length&&(i.arrayParameterCheck(e.orderBy,"DynamicsWebApi."+t,"request.orderBy"),u.push("$orderby="+e.orderBy.join(",")));var l=o(e,t,c);if(l.length&&(s.Prefer=l),null!=e.ifmatch&&null!=e.ifnonematch)throw new Error("DynamicsWebApi."+t+". Either one of request.ifmatch or request.ifnonematch parameters should be used in a call, not both.");if(e.ifmatch&&(i.stringParameterCheck(e.ifmatch,"DynamicsWebApi."+t,"request.ifmatch"),s["If-Match"]=e.ifmatch),e.ifnonematch&&(i.stringParameterCheck(e.ifnonematch,"DynamicsWebApi."+t,"request.ifnonematch"),s["If-None-Match"]=e.ifnonematch),e.impersonate&&(i.stringParameterCheck(e.impersonate,"DynamicsWebApi."+t,"request.impersonate"),s.MSCRMCallerID=i.guidParameterCheck(e.impersonate,"DynamicsWebApi."+t,"request.impersonate")),e.token&&(i.stringParameterCheck(e.token,"DynamicsWebApi."+t,"request.token"),s.Authorization="Bearer "+e.token),e.duplicateDetection&&(i.boolParameterCheck(e.duplicateDetection,"DynamicsWebApi."+t,"request.duplicateDetection"),s["MSCRM.SuppressDuplicateDetection"]="false"),e.entity&&i.parameterCheck(e.entity,"DynamicsWebApi."+t,"request.entity"),e.data&&i.parameterCheck(e.data,"DynamicsWebApi."+t,"request.data"),e.noCache&&(i.boolParameterCheck(e.noCache,"DynamicsWebApi."+t,"request.noCache"),s["Cache-Control"]="no-cache"),e.expand&&e.expand.length)if(i.stringOrArrayParameterCheck(e.expand,"DynamicsWebApi."+t,"request.expand"),"string"==typeof e.expand)u.push("$expand="+e.expand);else{for(var p=[],f=0;f<e.expand.length;f++)if(e.expand[f].property){var m=r(e.expand[f],t+" $expand",null,";"),h=m.query;h&&h.length&&(h="("+h+")"),p.push(e.expand[f].property+h)}p.length&&u.push("$expand="+p.join(","))}}return{url:n,query:u.join(a),headers:s}}function a(e,t,n){var a,o="";return e.url?(i.stringParameterCheck(e.url,"DynamicsWebApi."+t,"request.url"),o=e.url.replace(n.webApiUrl,""),a=r(e,t,o,"&",n)):(e._unboundRequest||e.collection||i.parameterCheck(e.collection,"DynamicsWebApi."+t,"request.collection"),e.collection&&(i.stringParameterCheck(e.collection,"DynamicsWebApi."+t,"request.collection"),o=e.collection,e.key?e.key=i.keyParameterCheck(e.key,"DynamicsWebApi."+t,"request.key"):e.id&&(e.key=i.guidParameterCheck(e.id,"DynamicsWebApi."+t,"request.id")),e.key&&(o+="("+e.key+")")),e._additionalUrl&&(o&&(o+="/"),o+=e._additionalUrl),a=r(e,t,o,"&",n),e.fetchXml?(i.stringParameterCheck(e.fetchXml,"DynamicsWebApi."+t,"request.fetchXml"),a.url+="?fetchXml="+encodeURIComponent(e.fetchXml)):a.query&&(a.url+="?"+encodeURI(a.query))),e.hasOwnProperty("async")&&null!=e.async?(i.boolParameterCheck(e.async,"DynamicsWebApi."+t,"request.async"),a.async=e.async):a.async=!0,{url:a.url,headers:a.headers,async:a.async}}var i=(n(0),n(1)),o=n(12),c={convertRequestOptions:r,convertRequest:a};e.exports=c},function(e,t){e.exports=function(e){if(e){for(var t=Object.keys(e),n="",r="",a=1;a<=t.length;a++){var i=t[a-1],o=e[i];a>1&&(n+=",",r+="&"),n+=i+"=@p"+a,r+="@p"+a+"="+("string"==typeof o?"'"+o+"'":o)}return"("+n+")?"+r}return"()"}},function(e,t,n){var r=n(0),a=n(1);e.exports=function(e,t,n){var i=e.returnRepresentation,o=e.includeAnnotations,c=e.maxPageSize;if(e.prefer&&e.prefer.length){a.stringOrArrayParameterCheck(e.prefer,"DynamicsWebApi."+t,"request.prefer");var s=e.prefer;"string"==typeof s&&(s=s.split(","));for(var u in s){var l=s[u].trim();l===r.Prefer.ReturnRepresentation?i=!0:l.startsWith("odata.include-annotations=")?o=l.replace("odata.include-annotations=","").replace(/"/g,""):l.startsWith("odata.maxpagesize=")&&(c=l.replace("odata.maxpagesize=","").replace(/"/g,""))}}n&&(null==i&&(i=n.returnRepresentation),o=o||n.includeAnnotations,c=c||n.maxPageSize);var s=[];return i&&(a.boolParameterCheck(i,"DynamicsWebApi."+t,"request.returnRepresentation"),s.push(r.Prefer.ReturnRepresentation)),o&&(a.stringParameterCheck(o,"DynamicsWebApi."+t,"request.includeAnnotations"),s.push('odata.include-annotations="'+o+'"')),c&&c>0&&(a.numberParameterCheck(c,"DynamicsWebApi."+t,"request.maxPageSize"),s.push("odata.maxpagesize="+c)),s.join(",")}},function(e,t){e.exports=function(e){var t=/\/(\w+)\(([0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12})/i.exec(e["@odata.id"]);return{id:t[2],collection:t[1],oDataContext:e["@odata.context"]}}},function(e,t){e.exports=function(e,t){e=e||"",t=t||1,e=unescape(unescape(e));var n=/pagingcookie="(<cookie page="(\d+)".+<\/cookie>)/.exec(e);if(null!=n){var r=parseInt(n[2]);return{cookie:n[1].replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"'").replace(/\'/g,"&quot;"),page:r,nextPage:r+1}}return{cookie:"",page:t,nextPage:t+1}}}])});

@@ -5,3 +5,3 @@ var DWA = require("./dwa");

var ErrorHelper = require('./helpers/ErrorHelper');
var sendRequest = require('./requests/sendRequest');
var Request = require('./requests/sendRequest');

@@ -57,3 +57,30 @@ //string es6 polyfill

* @property {string} maxPageSize - Sets the odata.maxpagesize preference value to request the number of entities returned in the response.
* @property {string} returnRepresentation - Sets Prefer header request with value "return=representation". Use this property to return just created or updated entity in a single request.
* @property {boolean} returnRepresentation - Sets Prefer header request with value "return=representation". Use this property to return just created or updated entity in a single request.
* @property {boolean} useEntityNames - Indicates whether to use Entity Logical Names instead of Collection Logical Names.
*/
/**
* Dynamics Web Api Request
* @typedef {Object} DWARequest
* @property {boolean} async - XHR requests only! Indicates whether the requests should be made synchronously or asynchronously. Default value is true (asynchronously).
* @property {string} collection - The name of the Entity Collection or Entity Logical name.
* @property {string} id - A String representing the Primary Key (GUID) of the record.
* @property {Array} select - An Array (of Strings) representing the $select OData System Query Option to control which attributes will be returned.
* @property {Array} expand - 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.
* @property {string} key - A String representing collection record's Primary Key (GUID) or Alternate Key(s).
* @property {string} filter - Use the $filter system query option to set criteria for which entities will be returned.
* @property {number} maxPageSize - Sets the odata.maxpagesize preference value to request the number of entities returned in the response.
* @property {boolean} count - 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!
* @property {number} top - Limit the number of results returned by using the $top system query option. Do not use $top with $count!
* @property {Array} orderBy - 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.
* @property {string} includeAnnotations - 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.
* @property {string} ifmatch - Sets If-Match header value that enables to use conditional retrieval or optimistic concurrency in applicable requests.
* @property {string} ifnonematch - Sets If-None-Match header value that enables to use conditional retrieval in applicable requests.
* @property {boolean} returnRepresentation - Sets Prefer header request with value "return=representation". Use this property to return just created or updated entity in a single request.
* @property {Object} entity - A JavaScript object with properties corresponding to the logical name of entity attributes (exceptions are lookups and single-valued navigation properties).
* @property {string} impersonate - Impersonates the user. A String representing the GUID value for the Dynamics 365 system user id.
* @property {string} navigationProperty - 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.
* @property {boolean} noCache - If set to 'true', DynamicsWebApi adds a request header 'Cache-Control: no-cache'. Default value is 'false'.
* @property {string} savedQuery - A String representing the GUID value of the saved query.
* @property {string} userQuery - A String representing the GUID value of the user query.
*/

@@ -82,37 +109,2 @@

var _context = function () {
if (typeof GetGlobalContext != "undefined") {
return GetGlobalContext();
}
else {
if (typeof Xrm != "undefined") {
return Xrm.Page.context;
}
else {
throw new Error("Xrm Context is not available.");
}
}
};
var _getClientUrl = function () {
var context = _context();
if (context) {
var clientUrl = context.getClientUrl();
if (clientUrl.match(/\/$/)) {
clientUrl = clientUrl.substring(0, clientUrl.length - 1);
}
return clientUrl;
}
return "";
};
var _initUrl = function () {
return _getClientUrl() + "/api/data/v" + _internalConfig.webApiVersion + "/";
};
/**

@@ -134,3 +126,3 @@ * Sets the configuration parameters for DynamicsWebApi helper.

} else {
_internalConfig.webApiUrl = _initUrl();
_internalConfig.webApiUrl = Utility.initWebApiUrl(_internalConfig.webApiVersion);
}

@@ -161,2 +153,7 @@

}
if (config.useEntityNames) {
ErrorHelper.boolParameterCheck(config.useEntityNames, 'DynamicsWebApi.setConfig', 'config.useEntityNames');
_internalConfig.useEntityNames = config.useEntityNames;
}
};

@@ -167,15 +164,13 @@

/**
* Sends a request to given URL with given parameters
* Makes a request to web api
*
* @param {string} method - Method of the request.
* @param {string} uri - Request URI.
* @param {Function} successCallback - A callback called on success of the request.
* @param {Function} errorCallback - A callback called when a request failed.
* @param {Object} [data] - Data to send in the request.
* @param {Object} [additionalHeaders] - Object with additional headers. IMPORTANT! This object does not contain default headers needed for every request.
* @param {boolean} [isAsync] - Indicates whether the request should be made synchronously or asynchronously.
* @param {DWARequest} request - Request to Web Api
* @param {string} [functionName] - Indictes the name of the function that called make request.
* @param {Function} successCallback - The function that will be passed through and be called by a successful response.
* @param {Function} errorCallback - The function that will be passed through and be called by a failed response.
*/
var _sendRequest = function (method, uri, data, additionalHeaders, successCallback, errorCallback, isAsync) {
sendRequest(method, uri, _internalConfig, data, additionalHeaders, successCallback, errorCallback, isAsync);
}
var _makeRequest = function (method, request, functionName, successCallback, errorCallback) {
Request.makeRequest(method, request, functionName, _internalConfig, successCallback, errorCallback);
};

@@ -186,3 +181,3 @@ /**

* @param {Object} object - A JavaScript object valid for create operations.
* @param {string} collection - The Name of the Entity Collection.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Function} successCallback - The function that will be passed through and be called by a successful response.

@@ -211,3 +206,4 @@ * @param {Function} errorCallback - The function that will be passed through and be called by a failed response.

select: select,
prefer: prefer
prefer: prefer,
entity: object
};

@@ -230,3 +226,3 @@

_sendRequest("POST", result.url, object, result.headers, onSuccess, errorCallback, result.async);
_makeRequest("POST", request, 'create', onSuccess, errorCallback);
};

@@ -237,3 +233,3 @@

*
* @param {Object} request - An object that represents all possible options for a current request.
* @param {DWARequest} request - An object that represents all possible options for a current request.
* @param {Function} successCallback - The function that will be passed through and be called by a successful response.

@@ -244,11 +240,8 @@ * @param {Function} errorCallback - The function that will be passed through and be called by a failed response.

ErrorHelper.parameterCheck(request, "DynamicsWebApi.update", "request");
ErrorHelper.parameterCheck(request.entity, "DynamicsWebApi.update", "request.entity");
ErrorHelper.callbackParameterCheck(successCallback, "DynamicsWebApi.update", "successCallback");
ErrorHelper.callbackParameterCheck(errorCallback, "DynamicsWebApi.update", "errorCallback");
ErrorHelper.parameterCheck(request, 'DynamicsWebApi.update', 'request');
ErrorHelper.callbackParameterCheck(successCallback, 'DynamicsWebApi.update', 'successCallback');
ErrorHelper.callbackParameterCheck(errorCallback, 'DynamicsWebApi.update', 'errorCallback');
var result = RequestConverter.convertRequest(request, "update", _internalConfig);
if (request.ifmatch == null) {
result.headers['If-Match'] = '*'; //to prevent upsert
request.ifmatch = '*'; //to prevent upsert
}

@@ -275,3 +268,3 @@

_sendRequest("PATCH", result.url, request.entity, result.headers, onSuccess, onError, result.async);
_makeRequest("PATCH", request, 'update', onSuccess, onError);
}

@@ -283,3 +276,3 @@

* @param {string} key - A String representing the GUID value or Alternate Key(s) for the record to update.
* @param {string} collection - The Name of the Entity Collection.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Object} object - A JavaScript object valid for update operations.

@@ -294,3 +287,3 @@ * @param {Function} successCallback - The function that will be passed through and be called by a successful response.

ErrorHelper.stringParameterCheck(key, "DynamicsWebApi.update", "key");
key = ErrorHelper.keyParameterCheck(key, "DynamicsWebApi.update", "key")
key = ErrorHelper.keyParameterCheck(key, "DynamicsWebApi.update", "key");
ErrorHelper.parameterCheck(object, "DynamicsWebApi.update", "object");

@@ -324,3 +317,3 @@ ErrorHelper.stringParameterCheck(collection, "DynamicsWebApi.update", "collection");

* @param {string} key - A String representing the GUID value or Alternate Key(s) for the record to update.
* @param {string} collection - The Name of the Entity Collection.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Object} keyValuePair - keyValuePair object with a logical name of the field as a key and a value to update with. Example: {subject: "Update Record"}

@@ -357,7 +350,6 @@ * @param {Function} successCallback - The function that will be passed through and be called by a successful response.

prefer: prefer,
navigationProperty: field
navigationProperty: field,
data: { value: fieldValue }
};
var result = RequestConverter.convertRequest(request, "updateSingleProperty", _internalConfig);
var onSuccess = function (response) {

@@ -369,3 +361,3 @@ response.data

_sendRequest("PUT", result.url, { value: fieldValue }, result.headers, onSuccess, errorCallback, result.async);
_makeRequest('PUT', request, 'updateSingleProperty', onSuccess, errorCallback);
};

@@ -376,3 +368,3 @@

*
* @param {Object} request - An object that represents all possible options for a current request.
* @param {DWARequest} request - An object that represents all possible options for a current request.
* @param {Function} successCallback - The function that will be passed through and be called by a successful response.

@@ -387,4 +379,2 @@ * @param {Function} errorCallback - The function that will be passed through and be called by a failed response.

var result = RequestConverter.convertRequest(request, "delete", _internalConfig);
var onSuccess = function () {

@@ -407,3 +397,3 @@ successCallback(true);

_sendRequest("DELETE", result.url, null, result.headers, onSuccess, onError, result.async);
_makeRequest('DELETE', request, 'delete', onSuccess, onError);
}

@@ -415,3 +405,3 @@

* @param {string} key - A String representing the GUID value or Alternate Key(s) for the record to delete.
* @param {string} collection - The Name of the Entity Collection.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Function} successCallback - The function that will be passed through and be called by a successful response.

@@ -432,7 +422,2 @@ * @param {Function} errorCallback - The function that will be passed through and be called by a failed response.

var url = collection.toLowerCase() + "(" + key + ")";
if (propertyName != null)
url += "/" + propertyName;
var onSuccess = function (xhr) {

@@ -443,3 +428,9 @@ // Nothing is returned to the success function.

_sendRequest("DELETE", url, null, null, onSuccess, errorCallback, true);
var request = {
key: key,
collection: collection,
navigationProperty: propertyName
};
_makeRequest('DELETE', request, 'delete', onSuccess, errorCallback);
};

@@ -450,3 +441,3 @@

*
* @param {Object} request - An object that represents all possible options for a current request.
* @param {DWARequest} request - An object that represents all possible options for a current request.
* @param {Function} successCallback - The function that will be passed through and be called by a successful response.

@@ -461,4 +452,2 @@ * @param {Function} errorCallback - The function that will be passed through and be called by a failed response.

var result = RequestConverter.convertRequest(request, "retrieve", _internalConfig);
//copy locally

@@ -475,3 +464,3 @@ var select = request.select;

_sendRequest("GET", result.url, null, result.headers, onSuccess, errorCallback, result.async);
_makeRequest('GET', request, 'retrieve', onSuccess, errorCallback);
}

@@ -483,3 +472,3 @@

* @param {string} key - A String representing the GUID value or Alternate Key(s) for the record to retrieve.
* @param {string} collection - The Name of the Entity Collection.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Function} successCallback - The function that will be passed through and be called by a successful response.

@@ -519,3 +508,3 @@ * @param {Function} errorCallback - The function that will be passed through and be called by a failed response.

*
* @param {Object} request - An object that represents all possible options for a current request.
* @param {DWARequest} request - An object that represents all possible options for a current request.
* @param {Function} successCallback - The function that will be passed through and be called by a successful response.

@@ -531,4 +520,2 @@ * @param {Function} errorCallback - The function that will be passed through and be called by a failed response.

var result = RequestConverter.convertRequest(request, "upsert", _internalConfig);
//copy locally

@@ -568,3 +555,3 @@ var ifnonematch = request.ifnonematch;

_sendRequest("PATCH", result.url, request.entity, result.headers, onSuccess, onError, result.async);
_makeRequest('PATCH', request, 'upsert', onSuccess, onError);
}

@@ -576,3 +563,3 @@

* @param {string} key - A String representing the GUID value or Alternate Key(s) for the record to upsert.
* @param {string} collection - The Name of the Entity Collection.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Object} object - A JavaScript object valid for update operations.

@@ -617,3 +604,3 @@ * @param {Function} successCallback - The function that will be passed through and be called by a successful response.

*
* @param {string} collection - The Name of the Entity Collection.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Function} successCallback - The function that will be passed through and be called by a successful response.

@@ -636,3 +623,8 @@ * @param {Function} errorCallback - The function that will be passed through and be called by a failed response.

_sendRequest("GET", collection.toLowerCase() + "/$count", null, null, onSuccess, errorCallback)
var request = {
collection: collection,
navigationProperty: '$count'
};
_makeRequest('GET', request, 'count', onSuccess, errorCallback)
}

@@ -653,3 +645,3 @@ else {

*
* @param {string} collection - The Name of the Entity Collection.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Function} successCallback - The function that will be passed through and be called by a successful response.

@@ -675,3 +667,3 @@ * @param {Function} errorCallback - The function that will be passed through and be called by a failed response.

*
* @param {string} collection - The Name of the Entity Collection.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Array} [select] - Use the $select system query option to limit the properties returned.

@@ -695,3 +687,3 @@ * @param {Function} successCallback - The function that will be passed through and be called by a successful response.

*
* @param {string} collection - The Name of the Entity Collection.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Function} successCallback - The function that will be passed through and be called by a successful response.

@@ -713,3 +705,3 @@ * @param {Function} errorCallback - The function that will be passed through and be called by a failed response.

*
* @param {Object} request - An object that represents all possible options for a current request.
* @param {DWARequest} request - An object that represents all possible options for a current request.
* @param {Function} successCallback - The function that will be passed through and be called by a successful response.

@@ -724,11 +716,5 @@ * @param {Function} errorCallback - The function that will be passed through and be called by a failed response.

if (nextPageLink && !request.collection) {
request.collection = "any";
}
var result = RequestConverter.convertRequest(request, "retrieveMultiple", _internalConfig);
if (nextPageLink) {
ErrorHelper.stringParameterCheck(nextPageLink, "DynamicsWebApi.retrieveMultiple", "nextPageLink");
result.url = nextPageLink.replace(_internalConfig.webApiUrl, "");
ErrorHelper.stringParameterCheck(nextPageLink, 'DynamicsWebApi.retrieveMultiple', 'nextPageLink');
request.url = nextPageLink;
}

@@ -747,3 +733,3 @@

_sendRequest("GET", result.url, null, result.headers, onSuccess, errorCallback, result.async);
_makeRequest('GET', request, 'retrieveMultiple', onSuccess, errorCallback);
}

@@ -774,3 +760,3 @@

*
* @param {Object} request - An object that represents all possible options for a current request.
* @param {DWARequest} request - An object that represents all possible options for a current request.
* @param {Function} successCallback - The function that will be passed through and be called by a successful response.

@@ -786,3 +772,3 @@ * @param {Function} errorCallback - The function that will be passed through and be called by a failed response.

*
* @param {string} collection - An object that represents all possible options for a current request.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} fetchXml - FetchXML is a proprietary query language that provides capabilities to perform aggregation.

@@ -803,5 +789,3 @@ * @param {Function} successCallback - The function that will be passed through and be called by a successful response.

if (pageNumber == null) {
pageNumber = 1;
}
pageNumber = pageNumber || 1;

@@ -819,20 +803,11 @@ ErrorHelper.numberParameterCheck(pageNumber, "DynamicsWebApi.executeFetchXml", "pageNumber");

if (includeAnnotations) {
ErrorHelper.stringParameterCheck(includeAnnotations, "DynamicsWebApi.executeFetchXml", "includeAnnotations");
}
if (impersonateUserId) {
impersonateUserId = ErrorHelper.guidParameterCheck(impersonateUserId, "DynamicsWebApi.executeFetchXml", "impersonateUserId");
}
var request = {
collection: collection,
includeAnnotations: includeAnnotations,
impersonate: impersonateUserId
impersonate: impersonateUserId,
fetchXml: fetchXml,
impersonate: impersonateUserId,
includeAnnotations: includeAnnotations
};
var result = RequestConverter.convertRequest(request, "executeFetchXml", _internalConfig);
var encodedFetchXml = encodeURIComponent(fetchXml);
var onSuccess = function (response) {

@@ -846,3 +821,3 @@ if (response.data['@' + DWA.Prefer.Annotations.FetchXmlPagingCookie] != null) {

_sendRequest("GET", result.url + "?fetchXml=" + encodedFetchXml, null, result.headers, onSuccess, errorCallback, result.async);
_makeRequest('GET', request, 'executeFetchXml', onSuccess, errorCallback);
}

@@ -872,3 +847,3 @@

*
* @param {string} collection - An object that represents all possible options for a current request.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} fetchXml - FetchXML is a proprietary query language that provides capabilities to perform aggregation.

@@ -887,7 +862,7 @@ * @param {Function} successCallback - The function that will be passed through and be called by a successful response.

*
* @param {string} primaryCollection - Primary entity collection name.
* @param {string} primaryId - Primary entity record id.
* @param {string} collection - Primary Entity Collection name or Entity Name.
* @param {string} primaryKey - Primary entity record id.
* @param {string} relationshipName - Relationship name.
* @param {string} relatedCollection - Related colletion name.
* @param {string} relatedId - Related entity record id.
* @param {string} relatedCollection - Related Entity Collection name or Entity Name.
* @param {string} relatedKey - Related entity record id.
* @param {Function} successCallback - The function that will be passed through and be called by a successful response.

@@ -897,9 +872,9 @@ * @param {Function} errorCallback - The function that will be passed through and be called by a failed response.

*/
this.associate = function (primarycollection, primaryId, relationshipName, relatedcollection, relatedId, successCallback, errorCallback, impersonateUserId) {
this.associate = function (collection, primaryKey, relationshipName, relatedCollection, relatedKey, successCallback, errorCallback, impersonateUserId) {
ErrorHelper.stringParameterCheck(primarycollection, "DynamicsWebApi.associate", "primarycollection");
ErrorHelper.stringParameterCheck(relatedcollection, "DynamicsWebApi.associate", "relatedcollection");
ErrorHelper.stringParameterCheck(collection, "DynamicsWebApi.associate", "collection");
ErrorHelper.stringParameterCheck(relatedCollection, "DynamicsWebApi.associate", "relatedCollection");
ErrorHelper.stringParameterCheck(relationshipName, "DynamicsWebApi.associate", "relationshipName");
primaryId = ErrorHelper.guidParameterCheck(primaryId, "DynamicsWebApi.associate", "primaryId");
relatedId = ErrorHelper.guidParameterCheck(relatedId, "DynamicsWebApi.associate", "relatedId");
primaryKey = ErrorHelper.keyParameterCheck(primaryKey, "DynamicsWebApi.associate", "primaryKey");
relatedKey = ErrorHelper.keyParameterCheck(relatedKey, "DynamicsWebApi.associate", "relatedKey");
ErrorHelper.callbackParameterCheck(successCallback, "DynamicsWebApi.associate", "successCallback");

@@ -912,14 +887,11 @@ ErrorHelper.callbackParameterCheck(errorCallback, "DynamicsWebApi.associate", "errorCallback");

var header = {};
var request = {
_additionalUrl: relationshipName + '/$ref',
collection: collection,
key: primaryKey,
impersonate: impersonateUserId,
data: { "@odata.id": relatedCollection + "(" + relatedKey + ")" }
};
if (impersonateUserId != null) {
impersonateUserId = ErrorHelper.guidParameterCheck(impersonateUserId, "DynamicsWebApi.associate", "impersonateUserId");
header["MSCRMCallerID"] = impersonateUserId;
}
var object = { "@odata.id": _internalConfig.webApiUrl + relatedcollection + "(" + relatedId + ")" };
_sendRequest("POST",
primarycollection + "(" + primaryId + ")/" + relationshipName + "/$ref", object, header,
onSuccess, errorCallback);
_makeRequest('POST', request, 'associate', onSuccess, errorCallback);
}

@@ -930,6 +902,6 @@

*
* @param {string} primaryCollection - Primary entity collection name.
* @param {string} primaryId - Primary entity record id.
* @param {string} collection - Primary Entity Collection name or Entity Name.
* @param {string} primaryKey - Primary entity record id.
* @param {string} relationshipName - Relationship name.
* @param {string} relatedId - Related entity record id.
* @param {string} relatedKey - Related entity record id.
* @param {Function} successCallback - The function that will be passed through and be called by a successful response.

@@ -939,8 +911,8 @@ * @param {Function} errorCallback - The function that will be passed through and be called by a failed response.

*/
this.disassociate = function (primarycollection, primaryId, relationshipName, relatedId, successCallback, errorCallback, impersonateUserId) {
this.disassociate = function (collection, primaryKey, relationshipName, relatedKey, successCallback, errorCallback, impersonateUserId) {
ErrorHelper.stringParameterCheck(primarycollection, "DynamicsWebApi.disassociate", "primarycollection");
ErrorHelper.stringParameterCheck(collection, "DynamicsWebApi.disassociate", "collection");
ErrorHelper.stringParameterCheck(relationshipName, "DynamicsWebApi.disassociate", "relationshipName");
primaryId = ErrorHelper.guidParameterCheck(primaryId, "DynamicsWebApi.disassociate", "primaryId");
relatedId = ErrorHelper.guidParameterCheck(relatedId, "DynamicsWebApi.disassociate", "relatedId");
primaryKey = ErrorHelper.keyParameterCheck(primaryKey, "DynamicsWebApi.disassociate", "primaryKey");
relatedKey = ErrorHelper.keyParameterCheck(relatedKey, "DynamicsWebApi.disassociate", "relatedKey");
ErrorHelper.callbackParameterCheck(successCallback, "DynamicsWebApi.disassociate", "successCallback");

@@ -953,11 +925,10 @@ ErrorHelper.callbackParameterCheck(errorCallback, "DynamicsWebApi.disassociate", "errorCallback");

var header = {};
var request = {
_additionalUrl: relationshipName + '(' + relatedKey + ')/$ref',
collection: collection,
key: primaryKey,
impersonate: impersonateUserId,
};
if (impersonateUserId != null) {
impersonateUserId = ErrorHelper.guidParameterCheck(impersonateUserId, "DynamicsWebApi.associate", "impersonateUserId");
header["MSCRMCallerID"] = impersonateUserId;
}
_sendRequest("DELETE", primarycollection + "(" + primaryId + ")/" + relationshipName + "(" + relatedId + ")/$ref", null, header,
onSuccess, errorCallback);
_makeRequest('DELETE', request, 'disassociate', onSuccess, errorCallback);
}

@@ -968,7 +939,7 @@

*
* @param {string} collection - Entity collection name that contains an attribute.
* @param {string} id - Entity record Id that contains an attribute.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} key - Entity record Id that contains an attribute.
* @param {string} singleValuedNavigationPropertyName - Single-valued navigation property name (usually it's a Schema Name of the lookup attribute).
* @param {string} relatedCollection - Related collection name that the lookup (attribute) points to.
* @param {string} relatedId - Related entity record id that needs to be associated.
* @param {string} relatedKey - Related entity record id that needs to be associated.
* @param {Function} successCallback - The function that will be passed through and be called by a successful response.

@@ -978,9 +949,9 @@ * @param {Function} errorCallback - The function that will be passed through and be called by a failed response.

*/
this.associateSingleValued = function (collection, id, singleValuedNavigationPropertyName, relatedcollection, relatedId, successCallback, errorCallback, impersonateUserId) {
this.associateSingleValued = function (collection, key, singleValuedNavigationPropertyName, relatedCollection, relatedKey, successCallback, errorCallback, impersonateUserId) {
ErrorHelper.stringParameterCheck(collection, "DynamicsWebApi.associateSingleValued", "collection");
id = ErrorHelper.guidParameterCheck(id, "DynamicsWebApi.associateSingleValued", "id");
relatedId = ErrorHelper.guidParameterCheck(relatedId, "DynamicsWebApi.associateSingleValued", "relatedId");
key = ErrorHelper.keyParameterCheck(key, "DynamicsWebApi.associateSingleValued", "key");
relatedKey = ErrorHelper.keyParameterCheck(relatedKey, "DynamicsWebApi.associateSingleValued", "relatedKey");
ErrorHelper.stringParameterCheck(singleValuedNavigationPropertyName, "DynamicsWebApi.associateSingleValued", "singleValuedNavigationPropertyName");
ErrorHelper.stringParameterCheck(relatedcollection, "DynamicsWebApi.associateSingleValued", "relatedcollection");
ErrorHelper.stringParameterCheck(relatedCollection, "DynamicsWebApi.associateSingleValued", "relatedCollection");
ErrorHelper.callbackParameterCheck(successCallback, "DynamicsWebApi.associateSingleValued", "successCallback");

@@ -993,14 +964,11 @@ ErrorHelper.callbackParameterCheck(errorCallback, "DynamicsWebApi.associateSingleValued", "errorCallback");

var header = {};
var request = {
_additionalUrl: singleValuedNavigationPropertyName + '/$ref',
collection: collection,
key: key,
impersonate: impersonateUserId,
data: { "@odata.id": relatedCollection + "(" + relatedKey + ")" }
};
if (impersonateUserId != null) {
impersonateUserId = ErrorHelper.guidParameterCheck(impersonateUserId, "DynamicsWebApi.associate", "impersonateUserId");
header["MSCRMCallerID"] = impersonateUserId;
}
var object = { "@odata.id": _internalConfig.webApiUrl + relatedcollection + "(" + relatedId + ")" };
_sendRequest("PUT",
collection + "(" + id + ")/" + singleValuedNavigationPropertyName + "/$ref", object, header,
onSuccess, errorCallback);
_makeRequest('PUT', request, 'associateSingleValued', onSuccess, errorCallback);
}

@@ -1011,4 +979,4 @@

*
* @param {string} collection - Entity collection name that contains an attribute.
* @param {string} id - Entity record Id that contains an attribute.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} key - Entity record Id that contains an attribute.
* @param {string} singleValuedNavigationPropertyName - Single-valued navigation property name (usually it's a Schema Name of the lookup attribute).

@@ -1019,6 +987,6 @@ * @param {Function} successCallback - The function that will be passed through and be called by a successful response.

*/
this.disassociateSingleValued = function (collection, id, singleValuedNavigationPropertyName, successCallback, errorCallback, impersonateUserId) {
this.disassociateSingleValued = function (collection, key, singleValuedNavigationPropertyName, successCallback, errorCallback, impersonateUserId) {
ErrorHelper.stringParameterCheck(collection, "DynamicsWebApi.disassociateSingleValued", "collection");
id = ErrorHelper.guidParameterCheck(id, "DynamicsWebApi.disassociateSingleValued", "id");
key = ErrorHelper.keyParameterCheck(key, "DynamicsWebApi.disassociateSingleValued", "key");
ErrorHelper.stringParameterCheck(singleValuedNavigationPropertyName, "DynamicsWebApi.disassociateSingleValued", "singleValuedNavigationPropertyName");

@@ -1028,9 +996,9 @@ ErrorHelper.callbackParameterCheck(successCallback, "DynamicsWebApi.disassociateSingleValued", "successCallback");

var header = {};
var request = {
_additionalUrl: singleValuedNavigationPropertyName + "/$ref",
key: key,
collection: collection,
impersonate: impersonateUserId,
};
if (impersonateUserId != null) {
impersonateUserId = ErrorHelper.guidParameterCheck(impersonateUserId, "DynamicsWebApi.associate", "impersonateUserId");
header["MSCRMCallerID"] = impersonateUserId;
}
var onSuccess = function () {

@@ -1040,4 +1008,3 @@ successCallback();

_sendRequest("DELETE", collection + "(" + id + ")/" + singleValuedNavigationPropertyName + "/$ref", null, header,
onSuccess, errorCallback);
_makeRequest('DELETE', request, 'disassociateSingleValued', onSuccess, errorCallback);
}

@@ -1055,3 +1022,3 @@

this.executeUnboundFunction = function (functionName, successCallback, errorCallback, parameters, impersonateUserId) {
return _executeFunction(functionName, parameters, null, null, successCallback, errorCallback, impersonateUserId);
return _executeFunction(functionName, parameters, null, null, successCallback, errorCallback, impersonateUserId, true);
}

@@ -1063,3 +1030,3 @@

* @param {string} id - A String representing the GUID value for the record.
* @param {string} collection - The name of the Entity Collection, for example, for account use accounts, opportunity - opportunities and etc.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} functionName - The name of the function.

@@ -1079,3 +1046,3 @@ * @param {Function} successCallback - The function that will be passed through and be called by a successful response.

* @param {string} id - A String representing the GUID value for the record.
* @param {string} collection - The name of the Entity Collection, for example, for account use accounts, opportunity - opportunities and etc.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} functionName - The name of the function.

@@ -1087,3 +1054,3 @@ * @param {Function} successCallback - The function that will be passed through and be called by a successful response.

*/
var _executeFunction = function (functionName, parameters, collection, id, successCallback, errorCallback, impersonateUserId) {
var _executeFunction = function (functionName, parameters, collection, id, successCallback, errorCallback, impersonateUserId, isUnbound) {

@@ -1093,17 +1060,11 @@ ErrorHelper.stringParameterCheck(functionName, "DynamicsWebApi.executeFunction", "functionName");

ErrorHelper.callbackParameterCheck(errorCallback, "DynamicsWebApi.executeFunction", "errorCallback");
var url = functionName + Utility.buildFunctionParameters(parameters);
if (collection != null) {
ErrorHelper.stringParameterCheck(collection, "DynamicsWebApi.executeFunction", "collection");
id = ErrorHelper.guidParameterCheck(id, "DynamicsWebApi.executeFunction", "id");
var request = {
_additionalUrl: functionName + Utility.buildFunctionParameters(parameters),
_unboundRequest: isUnbound,
key: id,
collection: collection,
impersonate: impersonateUserId,
};
url = collection + "(" + id + ")/" + url;
}
var header = {};
if (impersonateUserId) {
header["MSCRMCallerID"] = ErrorHelper.guidParameterCheck(impersonateUserId, "DynamicsWebApi.executionFunction", "impersonateUserId");
}
var onSuccess = function (response) {

@@ -1115,3 +1076,3 @@ response.data

_sendRequest("GET", url, null, header, onSuccess, errorCallback);
_makeRequest('GET', request, 'executeFunction', onSuccess, errorCallback);
}

@@ -1130,3 +1091,3 @@

return _executeAction(actionName, requestObject, null, null, successCallback, errorCallback, impersonateUserId);
return _executeAction(actionName, requestObject, null, null, successCallback, errorCallback, impersonateUserId, true);
}

@@ -1138,3 +1099,3 @@

* @param {string} id - A String representing the GUID value for the record.
* @param {string} collection - The name of the Entity Collection, for example, for account use accounts, opportunity - opportunities and etc.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} actionName - The name of the Web API action.

@@ -1154,3 +1115,3 @@ * @param {Object} requestObject - Action request body object.

* @param {string} [id] - A String representing the GUID value for the record.
* @param {string} [collection] - The name of the Entity Collection, for example, for account use accounts, opportunity - opportunities and etc.
* @param {string} [collection] - The name of the Entity Collection or Entity Logical name.
* @param {string} actionName - The name of the Web API action.

@@ -1162,3 +1123,3 @@ * @param {Object} requestObject - Action request body object.

*/
var _executeAction = function (actionName, requestObject, collection, id, successCallback, errorCallback, impersonateUserId) {
var _executeAction = function (actionName, requestObject, collection, id, successCallback, errorCallback, impersonateUserId, isUnbound) {

@@ -1168,18 +1129,12 @@ ErrorHelper.stringParameterCheck(actionName, "DynamicsWebApi.executeAction", "actionName");

ErrorHelper.callbackParameterCheck(errorCallback, "DynamicsWebApi.executeAction", "errorCallback");
var url = actionName;
if (collection != null) {
ErrorHelper.stringParameterCheck(collection, "DynamicsWebApi.executeAction", "collection");
id = ErrorHelper.guidParameterCheck(id, "DynamicsWebApi.executeAction", "id");
var request = {
_additionalUrl: actionName,
_unboundRequest: isUnbound,
collection: collection,
key: id,
impersonate: impersonateUserId,
data: requestObject
};
url = collection + "(" + id + ")/" + url;
}
var header = {};
if (impersonateUserId != null) {
impersonateUserId = ErrorHelper.guidParameterCheck(impersonateUserId, "DynamicsWebApi.associate", "impersonateUserId");
header["MSCRMCallerID"] = impersonateUserId;
}
var onSuccess = function (response) {

@@ -1191,3 +1146,3 @@ response.data

_sendRequest("POST", url, requestObject, header, onSuccess, errorCallback);
_makeRequest('POST', request, 'executeAction', onSuccess, errorCallback);
}

@@ -1211,2 +1166,6 @@

DynamicsWebApi.prototype.utility = {
getCollectionName: Request.getCollectionName
};
module.exports = DynamicsWebApi;
var DWA = require("./dwa");
var Utility = require('./utilities/Utility');
var RequestConverter = require('./utilities/RequestConverter');
var ErrorHelper = require('./helpers/ErrorHelper');
var sendRequest = require('./requests/sendRequest');
var Request = require('./requests/sendRequest');

@@ -51,10 +50,11 @@ //string es6 polyfill

* @typedef {object} DWAConfig
* @property {string} webApiUrl - A String representing a URL to Web API (webApiVersion not required if webApiUrl specified) [not used inside of CRM]
* @property {string} webApiUrl - A String representing the GUID value for the Dynamics 365 system user id. Impersonates the user.
* @property {string} webApiVersion - The version of Web API to use, for example: "8.1"
* @property {string} impersonate - A String representing the GUID value for the Dynamics 365 system user id. Impersonates the user.
* @property {string} impersonate - A String representing a URL to Web API (webApiVersion not required if webApiUrl specified) [not used inside of CRM]
* @property {Function} onTokenRefresh - A function that is called when a security token needs to be refreshed.
* @property {string} includeAnnotations - 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.
* @property {string} maxPageSize - Sets the odata.maxpagesize preference value to request the number of entities returned in the response.
* @property {string} returnRepresentation - Sets Prefer header request with value "return=representation". Use this property to return just created or updated entity in a single request.
*/
* @property {boolean} returnRepresentation - Sets Prefer header request with value "return=representation". Use this property to return just created or updated entity in a single request.
* @property {boolean} useEntityNames - Indicates whether to use Entity Logical Names instead of Collection Logical Names.
*/

@@ -64,20 +64,23 @@ /**

* @typedef {Object} DWARequest
* @property {string} collection
* @property {string} id
* @property {Array} select
* @property {Array} expand
* @property {string} filter
* @property {number} maxPageSize
* @property {boolean} count
* @property {number} top
* @property {Array} orderBy
* @property {string} includeAnnotations
* @property {string} ifmatch
* @property {string} ifnonematch
* @property {boolean} returnRepresentation
* @property {Object} entity
* @property {string} impersonate: "",
* @property {string} navigationProperty: "",
* @property {string} savedQuery: "",
* @property {string} userQuery: ""
* @property {boolean} async - XHR requests only! Indicates whether the requests should be made synchronously or asynchronously. Default value is true (asynchronously).
* @property {string} collection - The name of the Entity Collection or Entity Logical name.
* @property {string} id - A String representing the Primary Key (GUID) of the record.
* @property {Array} select - An Array (of Strings) representing the $select OData System Query Option to control which attributes will be returned.
* @property {Array} expand - 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.
* @property {string} key - A String representing collection record's Primary Key (GUID) or Alternate Key(s).
* @property {string} filter - Use the $filter system query option to set criteria for which entities will be returned.
* @property {number} maxPageSize - Sets the odata.maxpagesize preference value to request the number of entities returned in the response.
* @property {boolean} count - 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!
* @property {number} top - Limit the number of results returned by using the $top system query option. Do not use $top with $count!
* @property {Array} orderBy - 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.
* @property {string} includeAnnotations - 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.
* @property {string} ifmatch - Sets If-Match header value that enables to use conditional retrieval or optimistic concurrency in applicable requests.
* @property {string} ifnonematch - Sets If-None-Match header value that enables to use conditional retrieval in applicable requests.
* @property {boolean} returnRepresentation - Sets Prefer header request with value "return=representation". Use this property to return just created or updated entity in a single request.
* @property {Object} entity - A JavaScript object with properties corresponding to the logical name of entity attributes (exceptions are lookups and single-valued navigation properties).
* @property {string} impersonate - Impersonates the user. A String representing the GUID value for the Dynamics 365 system user id.
* @property {string} navigationProperty - 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.
* @property {boolean} noCache - If set to 'true', DynamicsWebApi adds a request header 'Cache-Control: no-cache'. Default value is 'false'.
* @property {string} savedQuery - A String representing the GUID value of the saved query.
* @property {string} userQuery - A String representing the GUID value of the user query.
*/

@@ -106,37 +109,2 @@

var _context = function () {
if (typeof GetGlobalContext != "undefined") {
return GetGlobalContext();
}
else {
if (typeof Xrm != "undefined") {
return Xrm.Page.context;
}
else {
throw new Error("Xrm Context is not available.");
}
}
};
var _getClientUrl = function () {
var context = _context();
if (context) {
var clientUrl = context.getClientUrl();
if (clientUrl.match(/\/$/)) {
clientUrl = clientUrl.substring(0, clientUrl.length - 1);
}
return clientUrl;
}
return "";
};
var _initUrl = function () {
return _getClientUrl() + "/api/data/v" + _internalConfig.webApiVersion + "/";
};
/**

@@ -158,3 +126,3 @@ * Sets the configuration parameters for DynamicsWebApi helper.

} else {
_internalConfig.webApiUrl = _initUrl();
_internalConfig.webApiUrl = Utility.initWebApiUrl(_internalConfig.webApiVersion);
}

@@ -185,2 +153,7 @@

}
if (config.useEntityNames) {
ErrorHelper.boolParameterCheck(config.useEntityNames, 'DynamicsWebApi.setConfig', 'config.useEntityNames');
_internalConfig.useEntityNames = config.useEntityNames;
}
};

@@ -191,14 +164,12 @@

/**
* Sends a request to given URL with given parameters
* Makes a request to web api
*
* @param {string} method - Method of the request.
* @param {string} uri - Request URI.
* @param {Object} [data] - Data to send in the request.
* @param {Object} [additionalHeaders] - Object with additional headers. IMPORTANT! This object does not contain default headers needed for every request.
* @param {boolean} [isAsync] - Indicates whether the request should be made synchronously or asynchronously.
* @param {DWARequest} request - Request to Web Api
* @param {string} [functionName] - Indictes the name of the function that called make request.
* @returns {Promise}
*/
var _sendRequest = function (method, uri, data, additionalHeaders, isAsync) {
var _makeRequest = function (method, request, functionName) {
return new Promise(function (resolve, reject) {
sendRequest(method, uri, _internalConfig, data, additionalHeaders, resolve, reject, isAsync);
Request.makeRequest(method, request, functionName, _internalConfig, resolve, reject);
});

@@ -211,3 +182,3 @@ };

* @param {Object} object - A JavaScript object valid for create operations.
* @param {string} collection - The Name of the Entity Collection.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string|Array} [prefer] - Sets a Prefer header value. For example: ['retrun=representation', 'odata.include-annotations="*"']

@@ -232,8 +203,7 @@ * @param {Array} [select] - An Array representing the $select Query Option to control which attributes will be returned.

select: select,
prefer: prefer
prefer: prefer,
entity: object
};
var result = RequestConverter.convertRequest(request, "create", _internalConfig);
return _sendRequest("POST", result.url, object, result.headers, result.async)
return _makeRequest('POST', request, 'create')
.then(function (response) {

@@ -255,13 +225,11 @@ if (response.data) {

*
* @param {Object} request - An object that represents all possible options for a current request.
* @param {DWARequest} request - An object that represents all possible options for a current request.
* @returns {Promise}
*/
this.retrieveRequest = function (request) {
ErrorHelper.parameterCheck(request, "DynamicsWebApi.retrieve", "request");
ErrorHelper.parameterCheck(request, 'DynamicsWebApi.retrieve', 'request');
var result = RequestConverter.convertRequest(request, "retrieve", _internalConfig);
//copy locally
var select = request.select;
return _sendRequest("GET", result.url, null, result.headers, result.async).then(function (response) {
return _makeRequest('GET', request, 'retrieve').then(function (response) {
if (select != null && select.length == 1 && select[0].endsWith("/$ref") && response.data["@odata.id"] != null) {

@@ -279,3 +247,3 @@ return Utility.convertToReferenceObject(response.data);

* @param {string} key - A String representing the GUID value or Aternate Key for the record to retrieve.
* @param {string} collection - The Name of the Entity Collection.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Array} [select] - An Array representing the $select Query Option to control which attributes will be returned.

@@ -312,3 +280,3 @@ * @param {string|Array} [expand] - A String or Array of Expand Objects representing the $expand Query Option value to control which related records need to be returned.

*
* @param {Object} request - An object that represents all possible options for a current request.
* @param {DWARequest} request - An object that represents all possible options for a current request.
* @returns {Promise}

@@ -319,3 +287,2 @@ */

ErrorHelper.parameterCheck(request, "DynamicsWebApi.update", "request");
ErrorHelper.parameterCheck(request.entity, "DynamicsWebApi.update", "request.entity");

@@ -326,7 +293,5 @@ if (request.ifmatch == null) {

var result = RequestConverter.convertRequest(request, "update", _internalConfig);
//copy locally
var ifmatch = request.ifmatch;
return _sendRequest("PATCH", result.url, request.entity, result.headers, result.async)
return _makeRequest('PATCH', request, 'update')
.then(function (response) {

@@ -353,3 +318,3 @@ if (response.data) {

* @param {string} key - A String representing the GUID value or Alternate Key for the record to update.
* @param {string} collection - The Name of the Entity Collection.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Object} object - A JavaScript object valid for update operations.

@@ -390,3 +355,3 @@ * @param {string} [prefer] - If set to "return=representation" the function will return an updated object

* @param {string} key - A String representing the GUID value or Alternate Key for the record to update.
* @param {string} collection - The Name of the Entity Collection.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Object} keyValuePair - keyValuePair object with a logical name of the field as a key and a value to update with. Example: {subject: "Update Record"}

@@ -420,8 +385,7 @@ * @param {string|Array} [prefer] - If set to "return=representation" the function will return an updated object

prefer: prefer,
navigationProperty: field
navigationProperty: field,
data: { value: fieldValue }
};
var result = RequestConverter.convertRequest(request, "updateSingleProperty", _internalConfig);
return _sendRequest("PUT", result.url, { value: fieldValue }, result.headers, result.async)
return _makeRequest('PUT', request, 'updateSingleProperty')
.then(function (response) {

@@ -437,3 +401,3 @@ if (response.data) {

*
* @param {Object} request - An object that represents all possible options for a current request.
* @param {DWARequest} request - An object that represents all possible options for a current request.
* @returns {Promise}

@@ -443,9 +407,7 @@ */

ErrorHelper.parameterCheck(request, "DynamicsWebApi.delete", "request")
ErrorHelper.parameterCheck(request, 'DynamicsWebApi.delete', 'request')
var result = RequestConverter.convertRequest(request, "deleteRequest", _internalConfig);
//copy locally
var ifmatch = request.ifmatch;
return _sendRequest("DELETE", result.url, null, result.headers, result.async).then(function () {
return _makeRequest('DELETE', request, 'delete').then(function () {
return true; //deleted

@@ -468,3 +430,3 @@ }).catch(function (error) {

* @param {string} key - A String representing the GUID value or Alternate Key for the record to delete.
* @param {string} collection - The Name of the Entity Collection.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} [propertyName] - The name of the property which needs to be emptied. Instead of removing a whole record only the specified property will be cleared.

@@ -474,16 +436,14 @@ * @returns {Promise}

this.deleteRecord = function (key, collection, propertyName) {
ErrorHelper.stringParameterCheck(collection, 'DynamicsWebApi.deleteRecord', 'collection');
ErrorHelper.stringParameterCheck(key, "DynamicsWebApi.deleteRecord", "key");
key = ErrorHelper.keyParameterCheck(key, "DynamicsWebApi.deleteRecord", "key")
ErrorHelper.stringParameterCheck(collection, "DynamicsWebApi.deleteRecord", "collection");
if (propertyName != null)
ErrorHelper.stringParameterCheck(propertyName, "DynamicsWebApi.deleteRecord", "propertyName");
ErrorHelper.stringParameterCheck(propertyName, 'DynamicsWebApi.deleteRecord', 'propertyName');
var url = collection.toLowerCase() + "(" + key + ")";
var request = {
navigationProperty: propertyName,
collection: collection,
key: key
};
if (propertyName != null)
url += "/" + propertyName;
return _sendRequest("DELETE", url, null, null, true).then(function () {
return _makeRequest('DELETE', request, 'deleteRecord').then(function () {
return;

@@ -496,16 +456,12 @@ })

*
* @param {Object} request - An object that represents all possible options for a current request.
* @param {DWARequest} request - An object that represents all possible options for a current request.
* @returns {Promise}
*/
this.upsertRequest = function (request) {
ErrorHelper.parameterCheck(request, "DynamicsWebApi.upsert", "request")
ErrorHelper.parameterCheck(request.entity, "DynamicsWebApi.upsert", "request.entity")
var result = RequestConverter.convertRequest(request, "upsert", _internalConfig);
//copy locally
var ifnonematch = request.ifnonematch;
var ifmatch = request.ifmatch;
return _sendRequest("PATCH", result.url, request.entity, result.headers, result.async)
return _makeRequest("PATCH", request, 'upsert')
.then(function (response) {

@@ -540,3 +496,3 @@ if (response.headers['OData-EntityId'] || response.headers['odata-entityid']) {

* @param {string} key - A String representing the GUID value or Alternate Key for the record to upsert.
* @param {string} collection - The Name of the Entity Collection.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Object} object - A JavaScript object valid for update operations.

@@ -577,3 +533,3 @@ * @param {string|Array} [prefer] - If set to "return=representation" the function will return an updated object

*
* @param {Object} request - An object that represents all possible options for a current request.
* @param {DWARequest} request - An object that represents all possible options for a current request.
* @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.

@@ -584,11 +540,5 @@ * @returns {Promise}

if (nextPageLink && !request.collection) {
request.collection = "any";
}
var result = RequestConverter.convertRequest(request, "retrieveMultiple", _internalConfig);
if (nextPageLink) {
ErrorHelper.stringParameterCheck(nextPageLink, "DynamicsWebApi.retrieveMultiple", "nextPageLink");
result.url = nextPageLink.replace(_internalConfig.webApiUrl, "");
ErrorHelper.stringParameterCheck(nextPageLink, 'DynamicsWebApi.retrieveMultiple', 'nextPageLink');
request.url = nextPageLink;
}

@@ -599,3 +549,3 @@

return _sendRequest("GET", result.url, null, result.headers, result.async)
return _makeRequest("GET", request, 'retrieveMultiple')
.then(function (response) {

@@ -630,3 +580,3 @@

*
* @param {Object} request - An object that represents all possible options for a current request.
* @param {DWARequest} request - An object that represents all possible options for a current request.
* @returns {Promise}

@@ -641,3 +591,3 @@ */

*
* @param {string} collection - The Name of the Entity Collection.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} [filter] - Use the $filter system query option to set criteria for which entities will be returned.

@@ -648,6 +598,8 @@ * @returns {Promise}

if (filter == null || (filter != null && !filter.length)) {
ErrorHelper.stringParameterCheck(collection, "DynamicsWebApi.count", "collection");
var request = {
collection: collection,
navigationProperty: '$count'
};
//if filter has not been specified then simplify the request
return _sendRequest("GET", collection.toLowerCase() + "/$count")
return _makeRequest('GET', request, 'count')
.then(function (response) {

@@ -674,3 +626,3 @@ return response.data ? parseInt(response.data) : 0;

*
* @param {string} collection - The Name of the Entity Collection.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} [filter] - Use the $filter system query option to set criteria for which entities will be returned.

@@ -696,3 +648,3 @@ * @param {Array} [select] - An Array representing the $select Query Option to control which attributes will be returned.

*
* @param {string} collection - The Name of the Entity Collection.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Array} [select] - Use the $select system query option to limit the properties returned.

@@ -714,3 +666,3 @@ * @param {string} [filter] - Use the $filter system query option to set criteria for which entities will be returned.

*
* @param {string} collection - The Name of the Entity Collection.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {Array} [select] - Use the $select system query option to limit the properties returned.

@@ -731,3 +683,3 @@ * @param {string} [filter] - Use the $filter system query option to set criteria for which entities will be returned.

*
* @param {string} collection - An object that represents all possible options for a current request.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} fetchXml - FetchXML is a proprietary query language that provides capabilities to perform aggregation.

@@ -742,3 +694,2 @@ * @param {string} [includeAnnotations] - Use this parameter to include annotations to a result. For example: * or Microsoft.Dynamics.CRM.fetchxmlpagingcookie

ErrorHelper.stringParameterCheck(collection, "DynamicsWebApi.executeFetchXml", "type");
ErrorHelper.stringParameterCheck(fetchXml, "DynamicsWebApi.executeFetchXml", "fetchXml");

@@ -759,21 +710,12 @@

if (includeAnnotations) {
ErrorHelper.stringParameterCheck(includeAnnotations, "DynamicsWebApi.executeFetchXml", "includeAnnotations");
}
if (impersonateUserId) {
impersonateUserId = ErrorHelper.guidParameterCheck(impersonateUserId, "DynamicsWebApi.executeFetchXml", "impersonateUserId");
}
var request = {
collection: collection,
includeAnnotations: includeAnnotations,
impersonate: impersonateUserId
impersonate: impersonateUserId,
fetchXml: fetchXml,
impersonate: impersonateUserId,
includeAnnotations: includeAnnotations
};
var result = RequestConverter.convertRequest(request, "executeFetchXml", _internalConfig);
var encodedFetchXml = encodeURIComponent(fetchXml);
return _sendRequest("GET", result.url + "?fetchXml=" + encodedFetchXml, null, result.headers, result.async)
return _makeRequest("GET", request, 'executeFetchXml')
.then(function (response) {

@@ -792,3 +734,3 @@

*
* @param {string} collection - An object that represents all possible options for a current request.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} fetchXml - FetchXML is a proprietary query language that provides capabilities to perform aggregation.

@@ -820,3 +762,3 @@ * @param {string} [includeAnnotations] - Use this parameter to include annotations to a result. For example: * or Microsoft.Dynamics.CRM.fetchxmlpagingcookie

*
* @param {string} collection - An object that represents all possible options for a current request.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} fetchXml - FetchXML is a proprietary query language that provides capabilities to perform aggregation.

@@ -834,26 +776,25 @@ * @param {string} [includeAnnotations] - Use this parameter to include annotations to a result. For example: * or Microsoft.Dynamics.CRM.fetchxmlpagingcookie

*
* @param {string} primaryCollection - Primary entity collection name.
* @param {string} primaryId - Primary entity record id.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} primaryKey - Primary entity record id.
* @param {string} relationshipName - Relationship name.
* @param {string} relatedCollection - Related colletion name.
* @param {string} relatedId - Related entity record id.
* @param {string} relatedCollection - Related name of the Entity Collection or Entity Logical name.
* @param {string} relatedKey - Related entity record id.
* @param {string} [impersonateUserId] - A String representing the GUID value for the Dynamics 365 system user id. Impersonates the user.
* @returns {Promise}
*/
this.associate = function (primaryCollection, primaryId, relationshipName, relatedCollection, relatedId, impersonateUserId) {
ErrorHelper.stringParameterCheck(primaryCollection, "DynamicsWebApi.associate", "primarycollection");
this.associate = function (collection, primaryKey, relationshipName, relatedCollection, relatedKey, impersonateUserId) {
ErrorHelper.stringParameterCheck(relatedCollection, "DynamicsWebApi.associate", "relatedcollection");
ErrorHelper.stringParameterCheck(relationshipName, "DynamicsWebApi.associate", "relationshipName");
primaryId = ErrorHelper.guidParameterCheck(primaryId, "DynamicsWebApi.associate", "primaryId");
relatedId = ErrorHelper.guidParameterCheck(relatedId, "DynamicsWebApi.associate", "relatedId");
primaryKey = ErrorHelper.keyParameterCheck(primaryKey, "DynamicsWebApi.associate", "primaryKey");
relatedKey = ErrorHelper.keyParameterCheck(relatedKey, "DynamicsWebApi.associate", "relatedKey");
var header = {};
var request = {
_additionalUrl: relationshipName + '/$ref',
collection: collection,
key: primaryKey,
impersonate: impersonateUserId,
data: { "@odata.id": relatedCollection + "(" + relatedKey + ")" }
};
if (impersonateUserId != null) {
impersonateUserId = ErrorHelper.guidParameterCheck(impersonateUserId, "DynamicsWebApi.associate", "impersonateUserId");
header["MSCRMCallerID"] = impersonateUserId;
}
return _sendRequest("POST", primaryCollection + "(" + primaryId + ")/" + relationshipName + "/$ref",
{ "@odata.id": _internalConfig.webApiUrl + relatedCollection + "(" + relatedId + ")" }, header)
return _makeRequest("POST", request, 'associate')
.then(function () { });

@@ -865,23 +806,21 @@ }

*
* @param {string} primaryCollection - Primary entity collection name.
* @param {string} primaryId - Primary entity record id.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} primaryKey - Primary entity record id.
* @param {string} relationshipName - Relationship name.
* @param {string} relatedId - Related entity record id.
* @param {string} relatedKey - Related entity record id.
* @param {string} [impersonateUserId] - A String representing the GUID value for the Dynamics 365 system user id. Impersonates the user.
* @returns {Promise}
*/
this.disassociate = function (primaryCollection, primaryId, relationshipName, relatedId, impersonateUserId) {
ErrorHelper.stringParameterCheck(primaryCollection, "DynamicsWebApi.disassociate", "primarycollection");
this.disassociate = function (collection, primaryKey, relationshipName, relatedKey, impersonateUserId) {
ErrorHelper.stringParameterCheck(relationshipName, "DynamicsWebApi.disassociate", "relationshipName");
primaryId = ErrorHelper.guidParameterCheck(primaryId, "DynamicsWebApi.disassociate", "primaryId");
relatedId = ErrorHelper.guidParameterCheck(relatedId, "DynamicsWebApi.disassociate", "relatedId");
relatedKey = ErrorHelper.keyParameterCheck(relatedKey, "DynamicsWebApi.disassociate", "relatedId");
var header = {};
var request = {
_additionalUrl: relationshipName + '(' + relatedKey + ')/$ref',
collection: collection,
key: primaryKey,
impersonate: impersonateUserId,
};
if (impersonateUserId != null) {
impersonateUserId = ErrorHelper.guidParameterCheck(impersonateUserId, "DynamicsWebApi.associate", "impersonateUserId");
header["MSCRMCallerID"] = impersonateUserId;
}
return _sendRequest("DELETE", primaryCollection + "(" + primaryId + ")/" + relationshipName + "(" + relatedId + ")/$ref", null, header)
return _makeRequest("DELETE", request, 'disassociate')
.then(function () { });

@@ -893,4 +832,4 @@ }

*
* @param {string} collection - Entity collection name that contains an attribute.
* @param {string} id - Entity record Id that contains an attribute.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} key - Entity record Id that contains an attribute.
* @param {string} singleValuedNavigationPropertyName - Single-valued navigation property name (usually it's a Schema Name of the lookup attribute).

@@ -902,19 +841,17 @@ * @param {string} relatedCollection - Related collection name that the lookup (attribute) points to.

*/
this.associateSingleValued = function (collection, id, singleValuedNavigationPropertyName, relatedCollection, relatedId, impersonateUserId) {
this.associateSingleValued = function (collection, key, singleValuedNavigationPropertyName, relatedCollection, relatedKey, impersonateUserId) {
ErrorHelper.stringParameterCheck(collection, "DynamicsWebApi.associateSingleValued", "collection");
id = ErrorHelper.guidParameterCheck(id, "DynamicsWebApi.associateSingleValued", "id");
relatedId = ErrorHelper.guidParameterCheck(relatedId, "DynamicsWebApi.associateSingleValued", "relatedId");
relatedKey = ErrorHelper.keyParameterCheck(relatedKey, "DynamicsWebApi.associateSingleValued", "relatedKey");
ErrorHelper.stringParameterCheck(singleValuedNavigationPropertyName, "DynamicsWebApi.associateSingleValued", "singleValuedNavigationPropertyName");
ErrorHelper.stringParameterCheck(relatedCollection, "DynamicsWebApi.associateSingleValued", "relatedcollection");
var header = {};
var request = {
_additionalUrl: singleValuedNavigationPropertyName + '/$ref',
collection: collection,
key: key,
impersonate: impersonateUserId,
data: { "@odata.id": relatedCollection + "(" + relatedKey + ")" }
};
if (impersonateUserId != null) {
impersonateUserId = ErrorHelper.guidParameterCheck(impersonateUserId, "DynamicsWebApi.associate", "impersonateUserId");
header["MSCRMCallerID"] = impersonateUserId;
}
return _sendRequest("PUT", collection + "(" + id + ")/" + singleValuedNavigationPropertyName + "/$ref",
{ "@odata.id": _internalConfig.webApiUrl + relatedCollection + "(" + relatedId + ")" }, header)
return _makeRequest("PUT", request, 'associateSingleValued')
.then(function () { });

@@ -926,4 +863,4 @@ }

*
* @param {string} collection - Entity collection name that contains an attribute.
* @param {string} id - Entity record Id that contains an attribute.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} key - Entity record Id that contains an attribute.
* @param {string} singleValuedNavigationPropertyName - Single-valued navigation property name (usually it's a Schema Name of the lookup attribute).

@@ -933,16 +870,14 @@ * @param {string} [impersonateUserId] - A String representing the GUID value for the Dynamics 365 system user id. Impersonates the user.

*/
this.disassociateSingleValued = function (collection, id, singleValuedNavigationPropertyName, impersonateUserId) {
this.disassociateSingleValued = function (collection, key, singleValuedNavigationPropertyName, impersonateUserId) {
ErrorHelper.stringParameterCheck(collection, "DynamicsWebApi.disassociateSingleValued", "collection");
id = ErrorHelper.guidParameterCheck(id, "DynamicsWebApi.disassociateSingleValued", "id");
ErrorHelper.stringParameterCheck(singleValuedNavigationPropertyName, "DynamicsWebApi.disassociateSingleValued", "singleValuedNavigationPropertyName");
var header = {};
var request = {
_additionalUrl: singleValuedNavigationPropertyName + "/$ref",
key: key,
collection: collection,
impersonate: impersonateUserId,
};
if (impersonateUserId != null) {
impersonateUserId = ErrorHelper.guidParameterCheck(impersonateUserId, "DynamicsWebApi.associate", "impersonateUserId");
header["MSCRMCallerID"] = impersonateUserId;
}
return _sendRequest("DELETE", collection + "(" + id + ")/" + singleValuedNavigationPropertyName + "/$ref", null, header)
return _makeRequest("DELETE", request, 'disassociateSingleValued')
.then(function () { });

@@ -960,3 +895,3 @@ }

this.executeUnboundFunction = function (functionName, parameters, impersonateUserId) {
return _executeFunction(functionName, parameters, null, null, impersonateUserId);
return _executeFunction(functionName, parameters, null, null, impersonateUserId, true);
}

@@ -968,3 +903,3 @@

* @param {string} id - A String representing the GUID value for the record.
* @param {string} collection - The name of the Entity Collection, for example, for account use accounts, opportunity - opportunities and etc.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} functionName - The name of the function.

@@ -983,3 +918,3 @@ * @param {Object} [parameters] - Function's input parameters. Example: { param1: "test", param2: 3 }.

* @param {string} id - A String representing the GUID value for the record.
* @param {string} collection - The name of the Entity Collection, for example, for account use accounts, opportunity - opportunities and etc.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} functionName - The name of the function.

@@ -990,21 +925,15 @@ * @param {Object} [parameters] - Function's input parameters. Example: { param1: "test", param2: 3 }.

*/
var _executeFunction = function (functionName, parameters, collection, id, impersonateUserId) {
var _executeFunction = function (functionName, parameters, collection, id, impersonateUserId, isUnbound) {
ErrorHelper.stringParameterCheck(functionName, "DynamicsWebApi.executeFunction", "functionName");
var url = functionName + Utility.buildFunctionParameters(parameters);
if (collection != null) {
ErrorHelper.stringParameterCheck(collection, "DynamicsWebApi.executeFunction", "collection");
id = ErrorHelper.guidParameterCheck(id, "DynamicsWebApi.executeFunction", "id");
var request = {
_additionalUrl: functionName + Utility.buildFunctionParameters(parameters),
_unboundRequest: isUnbound,
key: id,
collection: collection,
impersonate: impersonateUserId,
};
url = collection + "(" + id + ")/" + url;
}
var header = {};
if (impersonateUserId) {
header["MSCRMCallerID"] = ErrorHelper.guidParameterCheck(impersonateUserId, "DynamicsWebApi.executeFunction", "impersonateUserId");
}
return _sendRequest("GET", url, null, header).then(function (response) {
return _makeRequest("GET", request, 'executeFunction').then(function (response) {
if (response.data) {

@@ -1025,3 +954,3 @@ return response.data;

this.executeUnboundAction = function (actionName, requestObject, impersonateUserId) {
return _executeAction(actionName, requestObject, null, null, impersonateUserId);
return _executeAction(actionName, requestObject, null, null, impersonateUserId, true);
}

@@ -1033,3 +962,3 @@

* @param {string} id - A String representing the GUID value for the record.
* @param {string} collection - The name of the Entity Collection, for example, for account use accounts, opportunity - opportunities and etc.
* @param {string} collection - The name of the Entity Collection or Entity Logical name.
* @param {string} actionName - The name of the Web API action.

@@ -1048,3 +977,3 @@ * @param {Object} requestObject - Action request body object.

* @param {string} [id] - A String representing the GUID value for the record.
* @param {string} [collection] - The name of the Entity Collection, for example, for account use accounts, opportunity - opportunities and etc.
* @param {string} [collection] - The name of the Entity Collection or Entity Logical name.
* @param {string} actionName - The name of the Web API action.

@@ -1055,22 +984,16 @@ * @param {Object} requestObject - Action request body object.

*/
var _executeAction = function (actionName, requestObject, collection, id, impersonateUserId) {
var _executeAction = function (actionName, requestObject, collection, id, impersonateUserId, isUnbound) {
ErrorHelper.stringParameterCheck(actionName, "DynamicsWebApi.executeAction", "actionName");
var url = actionName;
if (collection != null) {
ErrorHelper.stringParameterCheck(collection, "DynamicsWebApi.executeAction", "collection");
id = ErrorHelper.guidParameterCheck(id, "DynamicsWebApi.executeAction", "id");
var request = {
_additionalUrl: actionName,
_unboundRequest: isUnbound,
collection: collection,
key: id,
impersonate: impersonateUserId,
data: requestObject
};
url = collection + "(" + id + ")/" + url;
}
var header = {};
if (impersonateUserId != null) {
impersonateUserId = ErrorHelper.guidParameterCheck(impersonateUserId, "DynamicsWebApi.executeAction", "impersonateUserId");
header["MSCRMCallerID"] = impersonateUserId;
}
return _sendRequest("POST", url, requestObject, header).then(function (response) {
return _makeRequest("POST", request, 'executeAction').then(function (response) {
if (response.data) {

@@ -1097,2 +1020,6 @@ return response.data;

DynamicsWebApi.prototype.utility = {
getCollectionName: Request.getCollectionName
};
module.exports = DynamicsWebApi;

@@ -13,5 +13,5 @@ module.exports = function dateReviver(key, value) {

if (typeof value === 'string') {
a = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.exec(value);
a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:Z|[-+]\d{2}:\d{2})$/.exec(value);
if (a) {
return new Date(value);
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
}

@@ -18,0 +18,0 @@ }

@@ -76,3 +76,7 @@ var http = require('http');

try {
error = JSON.parse(rawData).error;
var errorParsed = JSON.parse(rawData);
error = errorParsed.hasOwnProperty('error') && errorParsed.error
? errorParsed.error
: { message: errorParsed.Message };
} catch (e) {

@@ -79,0 +83,0 @@ if (rawData.length > 0) {

var DWA = require('../dwa');
//var RequestConverter = require('../utilities/RequestConverter');
var Utility = require('../utilities/Utility');
var RequestConverter = require('../utilities/RequestConverter');
//https://stackoverflow.com/a/8809472
function generateUUID() { // Public Domain/MIT
var d = new Date().getTime();
if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
d += performance.now(); //use high-precision timer if available
var _entityNames;
/**
* Searches for a collection name by provided entity name in a cached entity metadata.
* The returned collection name can be null.
*
* @param {string} entityName - entity name
* @returns {string} - a collection name
*/
function findCollectionName(entityName) {
var xrmInternal = Utility.getXrmInternal();
if (!Utility.isNull(xrmInternal)) {
var collectionName = xrmInternal.getEntitySetName(entityName);
return collectionName || entityName;
}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
var collectionName = null;
if (!Utility.isNull(_entityNames)) {
collectionName = _entityNames[entityName];
if (Utility.isNull(collectionName)) {
for (var key in _entityNames) {
if (_entityNames[key] == entityName) {
return entityName;
}
}
}
}
return collectionName;
}

@@ -31,4 +51,4 @@

/// <param name="key" type="String">Description</param>
if (key.endsWith("@odata.bind")) {
if (typeof value === "string") {
if (key.endsWith('@odata.bind') || key.endsWith('@odata.id')) {
if (typeof value === 'string') {
//remove brackets in guid

@@ -38,2 +58,16 @@ if (/\(\{[\w\d-]+\}\)/g.test(value)) {

}
if (config.useEntityNames) {
//replace entity name with collection name
var regularExpression = /([\w_]+)(\([\d\w-]+\))$/;
var valueParts = regularExpression.exec(value);
if (valueParts.length > 2) {
var collectionName = findCollectionName(valueParts[1]);
if (!Utility.isNull(collectionName)) {
value = value.replace(regularExpression, collectionName + '$2');
}
}
}
//add full web api url if it's not set

@@ -70,3 +104,3 @@ if (!value.startsWith(config.webApiUrl)) {

*/
module.exports = function sendRequest(method, path, config, data, additionalHeaders, successCallback, errorCallback, isAsync) {
function sendRequest(method, path, config, data, additionalHeaders, successCallback, errorCallback, isAsync) {

@@ -84,3 +118,3 @@ if (!additionalHeaders) {

if (path.length > 2000) {
var batchBoundary = 'dwa_batch_' + generateUUID();
var batchBoundary = 'dwa_batch_' + Utility.generateUUID();

@@ -113,6 +147,8 @@ var batchBody = [];

var executeRequest;
/* develblock:start */
if (typeof XMLHttpRequest !== 'undefined') {
/* develblock:end */
executeRequest = require('./xhr');
/* develblock:start */
}
/* develblock:start */
else if (typeof process !== 'undefined') {

@@ -141,2 +177,79 @@ executeRequest = require('./http');

}
};
};
function _getEntityNames(entityName, config, successCallback, errorCallback) {
var resolve = function (result) {
_entityNames = {};
for (var i = 0; i < result.data.value.length; i++) {
_entityNames[result.data.value[i].LogicalName] = result.data.value[i].LogicalCollectionName;
}
successCallback(findCollectionName(entityName));
};
var reject = function (error) {
errorCallback({ message: 'Unable to fetch EntityDefinitions. Error: ' + error.message });
};
var request = RequestConverter.convertRequest({
collection: 'EntityDefinitions',
select: ['LogicalCollectionName', 'LogicalName'],
noCache: true
}, 'retrieveMultiple', config);
sendRequest('GET', request.url, config, null, request.headers, resolve, reject, request.async);
}
function _isEntityNameException(entityName) {
var exceptions = ['EntityDefinitions', '$metadata'];
return exceptions.indexOf(entityName) > -1;
}
function _getCollectionName(entityName, config, successCallback, errorCallback) {
if (_isEntityNameException(entityName) || Utility.isNull(entityName)) {
successCallback(entityName);
return;
}
entityName = entityName.toLowerCase();
if (!config.useEntityNames) {
successCallback(entityName);
return;
}
try {
var collectionName = findCollectionName(entityName);
if (Utility.isNull(collectionName)) {
_getEntityNames(entityName, config, successCallback, errorCallback);
}
else {
successCallback(collectionName);
}
}
catch (error) {
errorCallback({ message: 'Unable to fetch Collection Names. Error: ' + error.message });
}
};
function makeRequest(method, request, functionName, config, resolve, reject) {
var successCallback = function (collectionName) {
request.collection = collectionName;
var result = RequestConverter.convertRequest(request, functionName, config);
sendRequest(method, result.url, config, request.data || request.entity, result.headers, resolve, reject, result.async);
}
_getCollectionName(request.collection, config, successCallback, reject);
};
module.exports = {
sendRequest: sendRequest,
makeRequest: makeRequest,
getCollectionName: findCollectionName,
/* develblock:start */
_clearEntityNames: function () { _entityNames = null; }
/* develblock:end */
}

@@ -16,2 +16,3 @@ var DWA = require('../dwa');

* @property {Object} headers Heades object (always an Object; can be empty: {})
* @property {boolean} async
*/

@@ -126,2 +127,15 @@

if (request.entity) {
ErrorHelper.parameterCheck(request.entity, 'DynamicsWebApi.' + functionName, 'request.entity')
}
if (request.data) {
ErrorHelper.parameterCheck(request.data, 'DynamicsWebApi.' + functionName, 'request.data')
}
if (request.noCache) {
ErrorHelper.boolParameterCheck(request.noCache, 'DynamicsWebApi.' + functionName, 'request.noCache');
headers['Cache-Control'] = 'no-cache';
}
if (request.expand && request.expand.length) {

@@ -155,13 +169,2 @@ ErrorHelper.stringOrArrayParameterCheck(request.expand, 'DynamicsWebApi.' + functionName, "request.expand");

/**
* @param {string} collectionName - name of the collection to check
*/
function getCollectionName(collectionName) {
var exceptions = ['EntityDefinitions'];
return exceptions.indexOf(collectionName) > -1
? collectionName
: collectionName.toLowerCase();
}
/**
* Converts a request object to URL link

@@ -175,28 +178,46 @@ *

function convertRequest(request, functionName, config) {
var url = '';
var result;
if (!request.url) {
if (!request._unboundRequest && !request.collection) {
ErrorHelper.parameterCheck(request.collection, 'DynamicsWebApi.' + functionName, "request.collection");
}
if (request.collection) {
ErrorHelper.stringParameterCheck(request.collection, 'DynamicsWebApi.' + functionName, "request.collection");
url = request.collection;
if (!request.collection) {
ErrorHelper.parameterCheck(request.collection, 'DynamicsWebApi.' + functionName, "request.collection");
}
else {
ErrorHelper.stringParameterCheck(request.collection, 'DynamicsWebApi.' + functionName, "request.collection");
}
//add alternate key feature
if (request.key) {
request.key = ErrorHelper.keyParameterCheck(request.key, 'DynamicsWebApi.' + functionName, "request.key");
}
else if (request.id) {
request.key = ErrorHelper.guidParameterCheck(request.id, 'DynamicsWebApi.' + functionName, "request.id");
}
var url = getCollectionName(request.collection);
if (request.key) {
url += "(" + request.key + ")";
}
}
//add alternate key feature
if (request.key) {
request.key = ErrorHelper.keyParameterCheck(request.key, 'DynamicsWebApi.' + functionName, "request.key");
}
else if (request.id) {
request.key = ErrorHelper.guidParameterCheck(request.id, 'DynamicsWebApi.' + functionName, "request.id");
}
if (request._additionalUrl) {
if (url) {
url += '/';
}
url += request._additionalUrl;
}
if (request.key) {
url += "(" + request.key + ")";
result = convertRequestOptions(request, functionName, url, '&', config);
if (request.fetchXml) {
ErrorHelper.stringParameterCheck(request.fetchXml, 'DynamicsWebApi.' + functionName, "request.fetchXml");
result.url += "?fetchXml=" + encodeURIComponent(request.fetchXml);
}
else
if (result.query) {
result.url += "?" + encodeURI(result.query);
}
}
var result = convertRequestOptions(request, functionName, url, '&', config);
if (result.query) {
result.url += "?" + encodeURI(result.query);
else {
ErrorHelper.stringParameterCheck(request.url, 'DynamicsWebApi.' + functionName, "request.url");
url = request.url.replace(config.webApiUrl, '');
result = convertRequestOptions(request, functionName, url, '&', config);
}

@@ -203,0 +224,0 @@

@@ -1,2 +0,66 @@

var Utility = {
function isNull (value) {
return typeof value === "undefined" || typeof value === "unknown" || value == null;
};
//https://stackoverflow.com/a/8809472
function generateUUID() { // Public Domain/MIT
var d = new Date().getTime();
if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
d += performance.now(); //use high-precision timer if available
}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
};
function getXrmContext() {
if (typeof GetGlobalContext != 'undefined') {
return GetGlobalContext();
}
else {
if (typeof Xrm != 'undefined') {
//d365 v.9.0
if ((!isNull(Xrm.Utility) && !isNull(Xrm.Utility.getGlobalContext))) {
return Xrm.Utility.getGlobalContext();
}
else if (!isNull(Xrm.Page) && !isNull(Xrm.Page.context)) {
return Xrm.Page.context;
}
}
}
throw new Error('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.');
};
function getClientUrl() {
var context = getXrmContext();
if (context) {
var clientUrl = context.getClientUrl();
if (clientUrl.match(/\/$/)) {
clientUrl = clientUrl.substring(0, clientUrl.length - 1);
}
return clientUrl;
}
return '';
};
function initWebApiUrl(version) {
return getClientUrl() + '/api/data/v' + version + '/';
};
function getXrmInternal() {
//todo: Xrm.Internal namespace is not supported
if (typeof Xrm !== 'undefined') {
return Xrm.Internal;
}
return null;
};
var Utility = {
/**

@@ -25,5 +89,22 @@ * Builds parametes for a funciton. Returns '()' (if no parameters) or '([params])?[query]'

*/
convertToReferenceObject: require('./convertToReferenceObject')
convertToReferenceObject: require('./convertToReferenceObject'),
/**
* Checks whether the value is JS Null.
* @param {Object} value
* @returns {boolean}
*/
isNull: isNull,
generateUUID: generateUUID,
getXrmContext: getXrmContext,
getXrmInternal: getXrmInternal,
getClientUrl: getClientUrl,
initWebApiUrl: initWebApiUrl
}
module.exports = Utility;
{
"name": "dynamics-web-api",
"version": "1.3.4",
"version": "1.4.0",
"description": "DynamicsWebApi is a Microsoft Dynamics CRM Web API helper library",

@@ -5,0 +5,0 @@ "keywords": [

@@ -41,3 +41,4 @@ # DynamicsWebApi for Microsoft Dynamics CRM Web API

* [Formatted Values and Lookup Properties](#formatted-values-and-lookup-properties)
* [Alternate Key](#alternate-key)
* [Using Alternate Keys](#using-alternate-keys)
* [Making requests using Entity Logical Names](#making-requests-using-entity-logical-names)
* [JavaScript Promises](#javascript-promises)

@@ -121,3 +122,3 @@ * [JavaScript Callbacks](#javascript-callbacks)

var dynamicsWebApi = new DynamicsWebApi({
webApiUrl: 'https:/myorg.api.crm.dynamics.com/api/data/v8.2/',
webApiUrl: 'https:/myorg.api.crm.dynamics.com/api/data/v9.0/',
onTokenRefresh: acquireToken

@@ -139,3 +140,3 @@ });

//config can be passed directly to the constructor
var dynamicsWebApi = new DynamicsWebApi({ webApiVersion: "8.2" });
var dynamicsWebApi = new DynamicsWebApi({ webApiVersion: '9.0' });
```

@@ -147,3 +148,3 @@

//or can be set dynamically
dynamicsWebApi.setConfig({ webApiVersion: "8.2" });
dynamicsWebApi.setConfig({ webApiVersion: '9.0' });
```

@@ -159,2 +160,3 @@

returnRepresentation | Boolean | Defaults Prefer header with value "return=representation". Use this property to return just created or updated entity in a single request.
useEntityNames | Boolean | `v.1.4.0+` Indicates whether to use entity logical names instead of collection logical names during requests.
webApiUrl | String | A complete URL string to Web API. Example of the URL: "https:/myorg.api.crm.dynamics.com/api/data/v8.2/". If it is specified then webApiVersion property will not be used even if it is not empty.

@@ -164,5 +166,10 @@ webApiVersion | String | Version of the Web API. Default version is "8.0".

Configuration property `webApiVersion` is required only when DynamicsWebApi used inside CRM.
Property `webApiUrl` is required when DynamicsWebApi used externally.
If both configuration properties set then `webApiUrl` will have a higher priority than `webApiVersion`, so the last one will be skipped.
Property `webApiUrl` is required when DynamicsWebApi used externally.
**Important!** If both configuration properties set then `webApiUrl` will have a higher priority than `webApiVersion`, so the last one will be skipped.
**Important!** Please note, 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 entity metadata 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).
## Request Examples

@@ -189,3 +196,3 @@

async | Boolean | All | **Important! XHR requests only!** Indicates whether the requests should be made synchronously or asynchronously. Default value is `true` (asynchronously).
collection | String | All | The name of the Entity Collection, for example, for `account` use `accounts`, `opportunity` - `opportunities` and etc.
collection | String | All | The name of the Entity Collection (or Entity Logical name in `v1.4.0+`).
count | Boolean | `retrieveMultipleRequest`, `retrieveAllRequest` | 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!

@@ -204,2 +211,3 @@ duplicateDetection | Boolean | `createRequest`, `updateRequest`, `upsertRequest` | `v.1.3.4+` **Web API v9+ only!** 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)

navigationProperty | String | `retrieveRequest` | 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.
noCache | Boolean | All | `v.1.4.0+` If set to `true`, DynamicsWebApi adds a request header `Cache-Control: no-cache`. Default value is `false`.
orderBy | Array | `retrieveMultipleRequest`, `retrieveAllRequest` | 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.

@@ -307,3 +315,3 @@ returnRepresentation | Boolean | `updateRequest`, `upsertRequest` | Sets Prefer header request with value "return=representation". Use this property to return just created or updated entity in a single request.

var request = {
id: '7d577253-3ef0-4a0a-bb7f-8335c2596e70',
key: '7d577253-3ef0-4a0a-bb7f-8335c2596e70',
collection: "leads",

@@ -373,3 +381,3 @@ entity: {

var request = {
id: leadId,
key: leadId,
collection: "leads",

@@ -419,3 +427,3 @@ returnRepresentation: true,

var request = {
id: recordId,
key: recordId,
collection: "leads",

@@ -473,3 +481,3 @@ ifmatch: 'W/"470867"'

var request = {
id: '7d577253-3ef0-4a0a-bb7f-8335c2596e70',
key: '7d577253-3ef0-4a0a-bb7f-8335c2596e70',
collection: "leads",

@@ -531,3 +539,3 @@ select: ["fullname", "subject"],

var request = {
id: recordId,
key: recordId,
collection: "new_tests",

@@ -541,3 +549,3 @@ navigationProperty: "new_ParentLead", //use request.navigationProperty

request = {
id: recordId,
key: recordId,
collection: "new_tests",

@@ -636,4 +644,2 @@ select: ["/new_ParentLead", "fullname", "subject"] //inline with prefix "/"

For now please use dynamicsWebApi.retrieveMultipleRequest function and loop through all pages to rollup all records. dynamicsWebApi.countAll will be available soon.
```js

@@ -663,3 +669,3 @@ dynamicsWebApi.count("leads", "statecode eq 0").then(function (count) {

Downside of this workaround is that it not only returns a count number but also all data for records in a collection. In order to make a small
Downside of this workaround is that it does not only return a count number but also all data for records in a collection. In order to make a small
optimisation I added the third parameter to the function that can be used to reduce the length of the response. The third parameter represents

@@ -922,3 +928,3 @@ a select query option.

## Alternate Key
## Using Alternate Keys
Starting from version 1.3.4, you can use alternate keys to Update, Upsert, Retrieve and Delete records. [More Info](https://msdn.microsoft.com/en-us/library/mt607871.aspx#Retrieve%20using%20an%20alternate%20key)

@@ -950,4 +956,2 @@

key: "alternateKey='keyValue'",
//key can be used as a primary key (id)
//key: '00000000-0000-0000-0000-000000000001',
collection: 'leads',

@@ -969,3 +973,3 @@ select: ['fullname', 'subject']

var request = {
key: '00000000-0000-0000-0000-000000000001',
key: '00000000-0000-0000-0000-000000000001',
collection: 'leads',

@@ -983,2 +987,65 @@ select: ['fullname', 'subject']

## Making requests using Entity Logical Names
Starting from version 1.4.0, it is possible to make requests using Entity Logical Names (for example: `account`, instead of `accounts`).
There's a small perfomance impact when this feature is used **outside CRM/D365 Web Resources**: DynamicsWebApi makes a request to
Entity Metadata and retrieves LogicalCollectionName and LogicalName for all entities during **the first call to Web Api** on the page.
To enable this feature set `useEntityNames: true` in DynamicsWebApi config.
```js
var dynamicsWebApi = new DynamicsWebApi({ useEntityNames: true });
//make request using entity names
dynamicsWebApi.retrieve(leadId, 'lead', ['fullname', 'subject']).then(function (record) {
//do something with a record here
})
.catch(function (error) {
//catch an error
});
//this will also work in request functions, even though the name of the property is a collection
var request = {
collection: 'lead',
key: leadId,
select: ['fullname', 'subject']
};
dynamicsWebApi.retrieveRequest(request).then(function (record) {
//do something with a record here
})
.catch(function (error) {
//catch an error
});
```
This feature also applies when you set a navigation property and provide an entity name in the value:
```js
var account = {
name: 'account name',
'primarycontactid@odata.bind': 'contact(00000000-0000-0000-0000-000000000001)'
}
dynamicsWebApi.create(account, 'account').then(function(accountId)){
//newly created accountId
}).catch(function (error) {
//catch error here
});
```
In the example above, entity names will be replaced with collection names: `contact` with `contacts`, `account` with `accounts`.
This happens, because DynamicsWebApi automatically checks all properties that end with `@odata.bind` or `@odata.id`.
Thus, there may be a case when those properties are not used but you still need a collection name instead of an entity name.
Please use the following method to get a collection name from a cached entity metadata:
```js
//IMPORTANT! collectionName will be null if there was no call to Web API prior to that
//this restriction does not apply if DynamicsWebApi used inside CRM/D365
var collectionName = dynamicsWebApi.utility.getCollectionName('account');
```
Please note, everything said above will happen only if you set `useEntityNames: true` in the DynamicsWebApi config.
### In Progress

@@ -995,11 +1062,10 @@

- [X] Duplicate Detection for Web API v.9. `Implemented in v.1.3.4`
- [X] Ability to use entity names instead of collection names. `Implemented in v.1.4.0`
- [ ] Batch requests.
- [ ] Web API Authentication for On-Premise instances.
- [ ] Intellisense for request objects.
- [ ] Use entity names instead of collection names. I have not done an investigation about it but if you, by any chance, know how to do that,
I will be very grateful for an advice! Quick guess, does it work like in English language?
Many more features to come!
Thank you for your patience!
Thank you for your patience and for using DynamcisWebApi!

@@ -1006,0 +1072,0 @@ ## JavaScript Promises

@@ -13,3 +13,3 @@ var chai = require('chai');

var dateReviver = require('../lib/requests/helpers/dateReviver');
var sendRequest = require('../lib/requests/sendRequest');
var Request = require('../lib/requests/sendRequest');
var parseResponse = require('../lib/requests/helpers/parseResponse');

@@ -798,5 +798,5 @@

}, {
property: "property2",
select: ["name3"]
}];
property: "property2",
select: ["name3"]
}];

@@ -1069,3 +1069,3 @@ result = RequestConverter.convertRequestOptions(dwaRequest, "", stubUrl);

var result = RequestConverter.convertRequest(dwaRequest);
expect(result).to.deep.equal({ url: "cols", headers: {}, async: true });
expect(result).to.deep.equal({ url: "Cols", headers: {}, async: true });
});

@@ -1413,3 +1413,212 @@

describe("sendRequest", function () {
describe('Request.makeRequest', function () {
describe('useEntityNames', function () {
var scope;
before(function () {
var response = mocks.responses.response200;
var response2 = mocks.responses.responseEntityDefinitions;
scope = nock(mocks.webApiUrl)
.get('/EntityDefinitions?$select=LogicalCollectionName,LogicalName')
.once()
.reply(response2.status, response2.responseText, response2.responseHeaders)
.get('/tests(' + mocks.data.testEntityId + ')')
.reply(response.status, response.responseText, response.responseHeaders);
});
after(function () {
nock.cleanAll();
Request._clearEntityNames();
});
it("returns a correct response", function (done) {
//{ webApiUrl: mocks.webApiUrl }
var request = {
collection: 'test',
key: mocks.data.testEntityId
};
var config = {
webApiUrl: mocks.webApiUrl,
useEntityNames: true
};
Request.makeRequest('GET', request, 'any', config, function (object) {
var expectedO = {
status: 200,
headers: {},
data: mocks.data.testEntity
};
expect(object).to.deep.equal(expectedO);
done();
}, function (object) {
expect(object).to.be.undefined;
done();
});
});
it("all requests have been made", function () {
expect(scope.isDone()).to.be.true;
});
});
describe('useEntityNames - entity metadata requested only once', function () {
var scope;
before(function () {
var response = mocks.responses.response200;
var response2 = mocks.responses.responseEntityDefinitions;
scope = nock(mocks.webApiUrl)
.get('/EntityDefinitions?$select=LogicalCollectionName,LogicalName')
.once()
.reply(response2.status, response2.responseText, response2.responseHeaders)
.get('/tests(' + mocks.data.testEntityId + ')')
.twice()
.reply(response.status, response.responseText, response.responseHeaders);
});
after(function () {
nock.cleanAll();
Request._clearEntityNames();
});
it("returns a correct response", function (done) {
var request = {
collection: 'test',
key: mocks.data.testEntityId
};
var config = {
webApiUrl: mocks.webApiUrl,
useEntityNames: true
};
var error = function (object) {
expect(object).to.be.undefined;
done();
};
Request.makeRequest('GET', request, 'any', config, function (object) {
var expectedO = {
status: 200,
headers: {},
data: mocks.data.testEntity
};
expect(object).to.deep.equal(expectedO);
var request2 = {
collection: 'test',
key: mocks.data.testEntityId
};
Request.makeRequest('GET', request2, 'any', config, function (object1) {
var expectedO1 = {
status: 200,
headers: {},
data: mocks.data.testEntity
};
expect(object1).to.deep.equal(expectedO1);
done();
}, error);
}, error);
});
it("all requests have been made", function () {
expect(scope.isDone()).to.be.true;
});
});
describe('useEntityNames - request with collection name does not fail', function () {
var scope;
before(function () {
var response = mocks.responses.response200;
var response2 = mocks.responses.responseEntityDefinitions;
scope = nock(mocks.webApiUrl)
.get('/EntityDefinitions?$select=LogicalCollectionName,LogicalName')
.once()
.reply(response2.status, response2.responseText, response2.responseHeaders)
.get('/tests(' + mocks.data.testEntityId + ')')
.reply(response.status, response.responseText, response.responseHeaders);
});
after(function () {
nock.cleanAll();
Request._clearEntityNames();
});
it("returns a correct response", function (done) {
var request = {
collection: 'tests',
key: mocks.data.testEntityId
};
var config = {
webApiUrl: mocks.webApiUrl,
useEntityNames: true
};
Request.makeRequest('GET', request, 'any', config, function (object) {
var expectedO = {
status: 200,
headers: {},
data: mocks.data.testEntity
};
expect(object).to.deep.equal(expectedO);
done();
}, function (object) {
expect(object).to.be.undefined;
done();
});
});
it("all requests have been made", function () {
expect(scope.isDone()).to.be.true;
});
});
describe('useEntityNames - Xrm.Internal', function () {
var scope;
before(function () {
var response = mocks.responses.response200;
var response2 = mocks.responses.responseEntityDefinitions;
scope = nock(mocks.webApiUrl)
.get('/tests(' + mocks.data.testEntityId + ')')
.reply(response.status, response.responseText, response.responseHeaders);
});
after(function () {
nock.cleanAll();
Request._clearEntityNames();
global.Xrm.Internal = null;
});
it("returns a correct response", function (done) {
global.Xrm.Internal = {
getEntitySetName: function (entityName) {
return entityName + 's';
}
};
var request = {
collection: 'test',
key: mocks.data.testEntityId
};
var config = {
webApiUrl: mocks.webApiUrl,
useEntityNames: true
};
Request.makeRequest('GET', request, 'any', config, function (object) {
var expectedO = {
status: 200,
headers: {},
data: mocks.data.testEntity
};
expect(object).to.deep.equal(expectedO);
done();
}, function (object) {
expect(object).to.be.undefined;
done();
});
});
it("all requests have been made", function () {
expect(scope.isDone()).to.be.true;
});
});
});
describe("Request.sendRequest", function () {
describe("when url is long, request is converted to batch", function () {

@@ -1450,3 +1659,3 @@ var scope;

it("returns a correct response", function (done) {
sendRequest('GET', url, { webApiUrl: mocks.webApiUrl }, null, null, function (object) {
Request.sendRequest('GET', url, { webApiUrl: mocks.webApiUrl }, null, null, function (object) {
var multiple = mocks.responses.multiple();

@@ -1453,0 +1662,0 @@ //delete multiple.oDataContext;

@@ -33,2 +33,14 @@ //<cookie pagenumber="2" pagingcookie="<cookie page="1"><accountid last="{EF72AE29-B3DE-E611-8102-5065F38A7BF1}" first="{475B158C-541C-E511-80D3-3863BB347BA8}" /></cookie>" istracking="False" />

},
entityDefinitionList: {
'@odata.contxt': 'context',
value: [{
"LogicalCollectionName": "tests",
"LogicalName": "test",
"MetadataId": "9dceed2b-9513-4a14-b09e-c176a6f1d9c3"
}, {
"LogicalCollectionName": "records",
"LogicalName": "record",
"MetadataId": "18eb9672-3070-478c-be5b-e0324acb1188"
}]
},
updatedEntity: {

@@ -80,11 +92,11 @@ fullname: "test record"

batch:
'--dwa_batch_XXX\n' +
'Content-Type: application/http\n' +
'Content-Transfer-Encoding: binary\n\n' +
'GET {0} HTTP/1.1\n' +
'Accept: application/json\n' +
'OData-MaxVersion: 4.0\n' +
'OData-Version: 4.0\n' +
'Content-Type: application/json; charset=utf-8\n\n' +
'--dwa_batch_XXX--',
'--dwa_batch_XXX\n' +
'Content-Type: application/http\n' +
'Content-Transfer-Encoding: binary\n\n' +
'GET {0} HTTP/1.1\n' +
'Accept: application/json\n' +
'OData-MaxVersion: 4.0\n' +
'OData-Version: 4.0\n' +
'Content-Type: application/json; charset=utf-8\n\n' +
'--dwa_batch_XXX--',

@@ -95,29 +107,29 @@ fetchXmls: {

fetchXml:
'<fetch mapping="logical" count="5">' +
'<entity name="account">' +
'<attribute name="accountid"/>' +
'<attribute name="name"/>' +
'</entity>' +
'</fetch>',
'<fetch mapping="logical" count="5">' +
'<entity name="account">' +
'<attribute name="accountid"/>' +
'<attribute name="name"/>' +
'</entity>' +
'</fetch>',
fetchXml1:
'<fetch mapping="logical" count="5" page="1">' +
'<entity name="account">' +
'<attribute name="accountid"/>' +
'<attribute name="name"/>' +
'</entity>' +
'</fetch>',
'<fetch mapping="logical" count="5" page="1">' +
'<entity name="account">' +
'<attribute name="accountid"/>' +
'<attribute name="name"/>' +
'</entity>' +
'</fetch>',
fetchXml2cookie:
'<fetch mapping="logical" count="5" page="2" paging-cookie="&lt;cookie page=&quot;1&quot;&gt;&lt;accountid last=&quot;{EF72AE29-B3DE-E611-8102-5065F38A7BF1}&quot; first=&quot;{475B158C-541C-E511-80D3-3863BB347BA8}&quot; /&gt;&lt;/cookie&gt;">' +
'<entity name="account">' +
'<attribute name="accountid"/>' +
'<attribute name="name"/>' +
'</entity>' +
'</fetch>',
'<fetch mapping="logical" count="5" page="2" paging-cookie="&lt;cookie page=&quot;1&quot;&gt;&lt;accountid last=&quot;{EF72AE29-B3DE-E611-8102-5065F38A7BF1}&quot; first=&quot;{475B158C-541C-E511-80D3-3863BB347BA8}&quot; /&gt;&lt;/cookie&gt;">' +
'<entity name="account">' +
'<attribute name="accountid"/>' +
'<attribute name="name"/>' +
'</entity>' +
'</fetch>',
fetchXml2:
'<fetch mapping="logical" count="5" page="2">' +
'<entity name="account">' +
'<attribute name="accountid"/>' +
'<attribute name="name"/>' +
'</entity>' +
'</fetch>',
'<fetch mapping="logical" count="5" page="2">' +
'<entity name="account">' +
'<attribute name="accountid"/>' +
'<attribute name="name"/>' +
'</entity>' +
'</fetch>',
fetchXmlResponsePage1Cookie: {

@@ -212,2 +224,3 @@ "@odata.context": "context",

testEntityUrl: webApiUrl + "tests(" + dataStubs.testEntityId + ")",
entityDefinitionsUrl: webApiUrl + 'EntityDefinitions',
basicEmptyResponseSuccess: {

@@ -224,2 +237,6 @@ status: 204

},
responseEntityDefinitions: {
status: 200,
responseText: JSON.stringify(dataStubs.entityDefinitionList)
},
retrieveReferenceResponse: {

@@ -256,13 +273,13 @@ status: 200,

responseText:
'--batchresponse_904020fa-6213-43d4-a26a-5347b70095e8\r\n' +
'Content-Type: application/http\r\n' +
'Content-Transfer-Encoding: binary\r\n\r\n' +
'--batchresponse_904020fa-6213-43d4-a26a-5347b70095e8\r\n' +
'Content-Type: application/http\r\n' +
'Content-Transfer-Encoding: binary\r\n\r\n' +
'HTTP/ 1.1 200 OK\r\n' +
'Access-Control-Expose-Headers: Preference-Applied, OData-EntityId, Location, ETag, OData-Version, Content-Encoding, Transfer-Encoding, Content-Length, Retry-After\r\n' +
'Content-Type: application/json; odata.metadata=minimal\r\n' +
'OData-Version: 4.0\r\n\r\n' +
'HTTP/ 1.1 200 OK\r\n' +
'Access-Control-Expose-Headers: Preference-Applied, OData-EntityId, Location, ETag, OData-Version, Content-Encoding, Transfer-Encoding, Content-Length, Retry-After\r\n' +
'Content-Type: application/json; odata.metadata=minimal\r\n' +
'OData-Version: 4.0\r\n\r\n' +
JSON.stringify(dataStubs.multiple) + '\r\n' +
'--batchresponse_904020fa-6213-43d4-a26a-5347b70095e8--'
JSON.stringify(dataStubs.multiple) + '\r\n' +
'--batchresponse_904020fa-6213-43d4-a26a-5347b70095e8--'
},

@@ -269,0 +286,0 @@ fetchXmlResponsePage1Cookie: {

@@ -61,2 +61,146 @@ var chai = require('chai');

});
describe("crm error", function () {
var responseObject;
before(function (done) {
global.XMLHttpRequest = sinon.useFakeXMLHttpRequest();
var requests = this.requests = [];
global.XMLHttpRequest.onCreate = function (xhr) {
requests.push(xhr);
};
dynamicsWebApiTest.create(mocks.data.testEntity, "tests").then(function (object) {
responseObject = object;
done();
}).catch(function (object) {
responseObject = object;
done();
});
var response = mocks.responses.upsertPreventCreateResponse;
this.requests[0].respond(response.status, response.responseHeaders, response.responseText);
});
after(function () {
global.XMLHttpRequest.restore();
global.XMLHttpRequest = null;
});
it("sends the request to the right end point", function () {
expect(this.requests[0].url).to.equal(mocks.responses.collectionUrl);
});
it("uses the correct method", function () {
expect(this.requests[0].method).to.equal('POST');
});
it("sends the right data", function () {
expect(JSON.parse(this.requests[0].requestBody)).to.deep.equal(mocks.data.testEntity);
});
it("does not have Prefer header", function () {
expect(this.requests[0].requestHeaders['Prefer']).to.be.undefined;
});
it("returns the correct response", function () {
expect(responseObject).to.deep.equal({ message: "message", status: 404 });
});
});
describe("unexpected error", function () {
var responseObject;
before(function (done) {
global.XMLHttpRequest = sinon.useFakeXMLHttpRequest();
var requests = this.requests = [];
global.XMLHttpRequest.onCreate = function (xhr) {
requests.push(xhr);
};
dynamicsWebApiTest.create(mocks.data.testEntity, "tests").then(function (object) {
responseObject = object;
done();
}).catch(function (object) {
responseObject = object;
done();
});
var response = mocks.responses.upsertPreventCreateResponse;
this.requests[0].respond(response.status, response.responseHeaders);
});
after(function () {
global.XMLHttpRequest.restore();
global.XMLHttpRequest = null;
});
it("sends the request to the right end point", function () {
expect(this.requests[0].url).to.equal(mocks.responses.collectionUrl);
});
it("uses the correct method", function () {
expect(this.requests[0].method).to.equal('POST');
});
it("sends the right data", function () {
expect(JSON.parse(this.requests[0].requestBody)).to.deep.equal(mocks.data.testEntity);
});
it("does not have Prefer header", function () {
expect(this.requests[0].requestHeaders['Prefer']).to.be.undefined;
});
it("returns the correct response", function () {
expect(responseObject).to.deep.equal({ message: "Unexpected Error", status: 404 });
});
});
describe("not crm error", function () {
var responseObject;
before(function (done) {
global.XMLHttpRequest = sinon.useFakeXMLHttpRequest();
var requests = this.requests = [];
global.XMLHttpRequest.onCreate = function (xhr) {
requests.push(xhr);
};
dynamicsWebApiTest.create(mocks.data.testEntity, "tests").then(function (object) {
responseObject = object;
done();
}).catch(function (object) {
responseObject = object;
done();
});
var response = mocks.responses.upsertPreventCreateResponse;
this.requests[0].respond(response.status, response.responseHeaders, 'something');
});
after(function () {
global.XMLHttpRequest.restore();
global.XMLHttpRequest = null;
});
it("sends the request to the right end point", function () {
expect(this.requests[0].url).to.equal(mocks.responses.collectionUrl);
});
it("uses the correct method", function () {
expect(this.requests[0].method).to.equal('POST');
});
it("sends the right data", function () {
expect(JSON.parse(this.requests[0].requestBody)).to.deep.equal(mocks.data.testEntity);
});
it("does not have Prefer header", function () {
expect(this.requests[0].requestHeaders['Prefer']).to.be.undefined;
});
it("returns the correct response", function () {
expect(responseObject).to.deep.equal({ message: "something", status: 404 });
});
});
});

@@ -63,0 +207,0 @@

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc