@mohsinonxrm/pptb-dataverse-request-studio 1.5.0-beta.1 → 1.6.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +380 -0
- package/README.md +44 -18
- package/dist/assets/ActionParamForm-DvTh6hUs.js +1 -0
- package/dist/assets/AllOrNothingOption-C7wGq_-r.js +1 -0
- package/dist/assets/AssociateMode-Dj-iEObO.js +1 -0
- package/dist/assets/BatchMode-Dsa1JVpd.js +10 -0
- package/dist/assets/BinaryColumnPickers-NAaoPcPt.js +1 -0
- package/dist/assets/BinaryPipelineCard-CSklRaME.js +1 -0
- package/dist/assets/BulkDeleteMode-Cqpb47QI.js +1 -0
- package/dist/assets/BulkWriteMode-CRkiw89Q.js +6 -0
- package/dist/assets/CodeView-C65Y5vXN.js +874 -0
- package/dist/assets/CreateMode-CwGffdDR.js +1 -0
- package/dist/assets/DeleteMode-CaWEZkJ1.js +1 -0
- package/dist/assets/DisassociateMode-Ddk9Jm3g.js +2 -0
- package/dist/assets/ExecuteActionMode-BbN_9350.js +1 -0
- package/dist/assets/ExecuteFunctionMode-G3PFBDpl.js +1 -0
- package/dist/assets/ExecuteWorkflowMode-D2MxIt5s.js +1 -0
- package/dist/assets/FieldSetEditor-Dg6WsDgG.js +3 -0
- package/dist/assets/ImportCurlDialog-BiURYtjH.js +7 -0
- package/dist/assets/ManageAttachmentMode-D14EZog8.js +1 -0
- package/dist/assets/ManageFileMode-DMLRV2xg.js +1 -0
- package/dist/assets/ManageImageMode-CoSAt9yh.js +1 -0
- package/dist/assets/MergeMode-PfbLAjOh.js +1 -0
- package/dist/assets/OptionGroup-DYAAm_pt.js +1 -0
- package/dist/assets/PredefinedQueryMode-CdT1I6jB.js +1 -0
- package/dist/assets/RetrieveNextLinkMode-BK9KD3q6.js +1 -0
- package/dist/assets/RetrieveSingleMode-_y2Z1G7C.js +1 -0
- package/dist/assets/UpdateMode-Dvd6cr4i.js +1 -0
- package/dist/assets/UpsertMode-BuyV7FEg.js +1 -0
- package/dist/assets/WriteResultCard-N_Ewu4dP.js +1 -0
- package/dist/assets/bypassAdvisories-BhBeq_oI.js +1 -0
- package/dist/assets/decodeForDisplay-D55DM53E.js +1 -0
- package/dist/assets/index-NW0Z4UWR.js +42 -0
- package/dist/assets/javascript-Dti3Ss-T.js +1 -0
- package/dist/assets/{jsonMode-DOHFeg2H.js → jsonMode-YuJX0ZcQ.js} +1 -1
- package/dist/assets/jsonWorkerInPage-CTjyykdK.js +33 -0
- package/dist/assets/{monacoSetup-CEhMjQNN.js → monacoSetup-Bxl8fgYX.js} +176 -176
- package/dist/assets/multipart-Bd_eOd8a.js +4 -0
- package/dist/assets/{python-DDgBOsRh.js → python-CZnGM3Qv.js} +1 -1
- package/dist/assets/writeResultName-Dw705_0B.js +1 -0
- package/dist/assets/writeState-DgYICTBE.js +1 -0
- package/dist/assets/{xml-BXhJpCm5.js → xml-gySD1GMR.js} +1 -1
- package/dist/icons/icon.svg +9 -6
- package/dist/index.html +7 -1
- package/index.html +6 -0
- package/package.json +2 -1
- package/dist/assets/AssociateMode-mu2ai0TV.js +0 -1
- package/dist/assets/AssociateTargetsEditor-BoH9Qxe8.js +0 -1
- package/dist/assets/BatchMode-BVAfFgPy.js +0 -11
- package/dist/assets/BinaryColumnPickers-DYpKoRIO.js +0 -1
- package/dist/assets/BulkDeleteMode-Df-XirlR.js +0 -1
- package/dist/assets/BulkWriteMode-UXREEvbe.js +0 -6
- package/dist/assets/DisassociateMode-CKBL5nUo.js +0 -2
- package/dist/assets/ExecuteWorkflowMode-4EWco-ze.js +0 -1
- package/dist/assets/ManageFileMode-BFNwxuEY.js +0 -1
- package/dist/assets/ManageImageMode-DX0AdPN1.js +0 -1
- package/dist/assets/MergeMode-BzyXLu1b.js +0 -1
- package/dist/assets/PredefinedQueryMode-BT-HdZHF.js +0 -1
- package/dist/assets/RetrieveNextLinkMode-QBuIwdgS.js +0 -1
- package/dist/assets/abap-CRCWOmpq.js +0 -1
- package/dist/assets/apex-DnsZk_dE.js +0 -1
- package/dist/assets/azcli-1IWB1ccx.js +0 -1
- package/dist/assets/bat-DPkNLes8.js +0 -1
- package/dist/assets/bicep-Corcdgou.js +0 -2
- package/dist/assets/cameligo-CGrWLZr3.js +0 -1
- package/dist/assets/clojure-D9WOWImG.js +0 -1
- package/dist/assets/coffee-B7EJu28W.js +0 -1
- package/dist/assets/cpp-SEyurbux.js +0 -1
- package/dist/assets/csp-C46ZqvIl.js +0 -1
- package/dist/assets/css-DQU6DXDx.js +0 -3
- package/dist/assets/css.worker-CwQehIRV.js +0 -93
- package/dist/assets/cssMode-DRNC4UuD.js +0 -4
- package/dist/assets/cypher-D84EuPTj.js +0 -1
- package/dist/assets/dart-D8lhlL1r.js +0 -1
- package/dist/assets/dockerfile-DLk6rpji.js +0 -1
- package/dist/assets/ecl-BO6FnfXk.js +0 -1
- package/dist/assets/elixir-BRjLKONM.js +0 -1
- package/dist/assets/flow9-Cac8vKd7.js +0 -1
- package/dist/assets/freemarker2-BITb8GyO.js +0 -3
- package/dist/assets/fsharp-fd1GTHhf.js +0 -1
- package/dist/assets/go-O9LJTZXk.js +0 -1
- package/dist/assets/graphql-LQdxqEYJ.js +0 -1
- package/dist/assets/handlebars-BbDVduNH.js +0 -1
- package/dist/assets/hcl-DxDQ3s82.js +0 -1
- package/dist/assets/html-Ru2Cy2VS.js +0 -1
- package/dist/assets/html.worker-4xVL0wjo.js +0 -470
- package/dist/assets/htmlMode-DeMh8vPt.js +0 -4
- package/dist/assets/index-XmEQbXiX.js +0 -703
- package/dist/assets/ini-BvajGCUy.js +0 -1
- package/dist/assets/java-SYsfObOQ.js +0 -1
- package/dist/assets/javascript-DLj2yjBO.js +0 -1
- package/dist/assets/julia-DQXNmw_w.js +0 -1
- package/dist/assets/kotlin-qQ0MG-9I.js +0 -1
- package/dist/assets/less-GGFNNJHn.js +0 -2
- package/dist/assets/lexon-Canl7DCW.js +0 -1
- package/dist/assets/liquid-udbJGOUP.js +0 -1
- package/dist/assets/lua-D28Ae8-K.js +0 -1
- package/dist/assets/m3-DPitgjJI.js +0 -1
- package/dist/assets/markdown-B811l8j2.js +0 -1
- package/dist/assets/mdx-B6ABiFDH.js +0 -1
- package/dist/assets/mips-CdjsipkG.js +0 -1
- package/dist/assets/msdax-CYqgjx_P.js +0 -1
- package/dist/assets/mysql-BHd6q0vd.js +0 -1
- package/dist/assets/objective-c-B1aVtJYH.js +0 -1
- package/dist/assets/pascal-BhNW15KB.js +0 -1
- package/dist/assets/pascaligo-5jv8CcQD.js +0 -1
- package/dist/assets/perl-DlYyT36c.js +0 -1
- package/dist/assets/pgsql-Dy0bjov7.js +0 -1
- package/dist/assets/php-120yhfDK.js +0 -1
- package/dist/assets/pla-CjnFlu4u.js +0 -1
- package/dist/assets/postiats-CQpG440k.js +0 -1
- package/dist/assets/powerquery-DdJtto1Z.js +0 -1
- package/dist/assets/protobuf-IBS6jZEB.js +0 -2
- package/dist/assets/pug-kFxLfcjb.js +0 -1
- package/dist/assets/qsharp-q7JyzKFN.js +0 -1
- package/dist/assets/r-BIFz-_sK.js +0 -1
- package/dist/assets/razor-DGf0KCTP.js +0 -1
- package/dist/assets/redis-CHOsPHWR.js +0 -1
- package/dist/assets/redshift-CBifECDb.js +0 -1
- package/dist/assets/restructuredtext-CghPJEOS.js +0 -1
- package/dist/assets/ruby-CYWGW-b1.js +0 -1
- package/dist/assets/rust-DMDD0SHb.js +0 -1
- package/dist/assets/sb-BYAiYHFx.js +0 -1
- package/dist/assets/scala-Bqvq8jcR.js +0 -1
- package/dist/assets/scheme-Dhb-2j9p.js +0 -1
- package/dist/assets/scss-CTwUZ5N7.js +0 -3
- package/dist/assets/solidity-CME5AdoB.js +0 -1
- package/dist/assets/sophia-RYC1BQQz.js +0 -1
- package/dist/assets/sparql-KEyrF7De.js +0 -1
- package/dist/assets/sql-BdTr02Mf.js +0 -1
- package/dist/assets/st-C7iG7M4S.js +0 -1
- package/dist/assets/swift-D7IUmUK8.js +0 -1
- package/dist/assets/systemverilog-DgMryOEJ.js +0 -1
- package/dist/assets/tcl-PloMZuKG.js +0 -1
- package/dist/assets/ts.worker-B8Ae6930.js +0 -51330
- package/dist/assets/tsMode-D4ZDTisA.js +0 -11
- package/dist/assets/twig-BfRIq3la.js +0 -1
- package/dist/assets/typescript-CJFgy1iR.js +0 -1
- package/dist/assets/typespec-CzxlYoT_.js +0 -1
- package/dist/assets/vb-BwAE3J76.js +0 -1
- package/dist/assets/wgsl-Dksx_ONF.js +0 -298
- package/dist/assets/yaml-B7iGwJkY.js +0 -1
|
@@ -0,0 +1,874 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./monacoSetup-Bxl8fgYX.js","./index-NW0Z4UWR.js","./monacoSetup-DvqauXKu.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{ff as He,fg as We,j as a,r as N,S as ze,fh as Ge,z as Xe,E as j,fi as _e,i as z,a as Je,fj as le,fk as fe,eO as je,aL as Qe,t as k,C as G,B as Ae,aW as X,s as _,ao as re,ap as se,M as de,m as pe,fl as xe,o as Ve,ei as Ke,fm as Ze,bv as Ye,T as et,av as tt,dr as nt,ay as ot,c0 as Te,e$ as be,f0 as ee,fn as rt,fo as st,fp as at,fq as it}from"./index-NW0Z4UWR.js";import{e as lt,C as ct}from"./multipart-Bd_eOd8a.js";const ut={root:"fui-Subtitle1"},dt=He({root:{Bahqtrf:"fk6fouc",Be2twd7:"f1pp30po",Bhrd7zp:"fl43uef",Bg96gwp:"f106mvju"}},{d:[".fk6fouc{font-family:var(--fontFamilyBase);}",".f1pp30po{font-size:var(--fontSizeBase500);}",".fl43uef{font-weight:var(--fontWeightSemibold);}",".f106mvju{line-height:var(--lineHeightBase500);}"]}),pt=We({useStyles:dt,className:ut.root,displayName:"Subtitle1"}),ht=N.lazy(()=>Ge(()=>import("./monacoSetup-Bxl8fgYX.js").then(e=>e.a),__vite__mapDeps([0,1,2]),import.meta.url));function Ce(e){return a.jsx(N.Suspense,{fallback:a.jsx("div",{style:{height:e.height??"100%",width:e.width??"100%",display:"flex",alignItems:"center",justifyContent:"center"},children:a.jsx(ze,{size:"small",label:"Loading editor…"})}),children:a.jsx(ht,{...e})})}const mt=/\(([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}|<[^>]+>)\)/g;function he(e){const t=e.displayName&&e.displayName!==e.logicalName?{title:e.displayName}:{};switch(e.description&&(t.description=e.description),e.attributeType){case"String":case"Memo":return{...t,type:"string",...e.maxLength?{maxLength:e.maxLength}:{}};case"Integer":return{...t,type:"integer",format:"int32",...e.minValue!=null?{minimum:e.minValue}:{},...e.maxValue!=null?{maximum:e.maxValue}:{}};case"BigInt":return{...t,type:"integer",format:"int64"};case"Decimal":case"Money":return{...t,type:"number",format:"decimal"};case"Double":return{...t,type:"number",format:"double"};case"Boolean":return{...t,type:"boolean"};case"DateTime":return{...t,type:"string",format:e.format==="DateOnly"?"date":"date-time"};case"Picklist":case"State":case"Status":return{...t,type:"integer",enum:e.options.map(n=>n.value),"x-enum-labels":Object.fromEntries(e.options.map(n=>[String(n.value),n.label]))};case"MultiSelectPicklist":return{...t,type:"string",description:`Comma-separated option values: ${e.options.map(n=>`${n.value} = ${n.label}`).join(", ")}`};case"Uniqueidentifier":case"Lookup":case"Customer":case"Owner":return{...t,type:"string",format:"uuid"};case"Image":return{...t,type:"string",format:"byte"};case"File":return{...t,type:"string",format:"uuid",description:"File id"};default:return{...t,type:"string"}}}function yt(e){return e.attributeType==="Lookup"||e.attributeType==="Customer"||e.attributeType==="Owner"}function ft(e){return e.oDataName??(yt(e)?`_${e.logicalName}_value`:e.logicalName)}function bt(e,t){const n={"@odata.etag":{type:"string",readOnly:!0}};for(const r of e.columns){if(r.isValidForRead===!1||r.isValidOData===!1||r.isLogical)continue;const s=ft(r);t&&!t.includes(s)&&!t.includes(r.logicalName)||(n[s]=he(r))}const o=e.columns.find(r=>r.logicalName===e.primaryKey);return o&&!n[o.logicalName]&&(n[o.logicalName]=he(o)),{type:"object",title:e.displayName,properties:n,additionalProperties:!0}}function gt(e,t){const n={};for(const[o,r]of Object.entries(e)){if(o.endsWith("@odata.bind")){n[o]={type:"string",description:"Related row: `/<entityset>(<id>)`",example:r};continue}const s=t?.columns.find(d=>d.logicalName===o);n[o]=s?he(s):me(r)}return{type:"object",properties:n}}function me(e){if(e===null)return{nullable:!0};if(Array.isArray(e))return{type:"array",items:e.length?me(e[0]):{}};switch(typeof e){case"string":return{type:"string"};case"number":return Number.isInteger(e)?{type:"integer"}:{type:"number"};case"boolean":return{type:"boolean"};case"object":{const t={};for(const[n,o]of Object.entries(e))t[n]=me(o);return{type:"object",properties:t}}default:return{}}}function ye(e){try{return decodeURIComponent(e)}catch{return e}}function $t(e,t){const n=e.replace(/^https?:\/\/[^/]+/i,""),o=n.indexOf("?");let r=o>=0?n.slice(0,o):n;const s=o>=0?n.slice(o+1):"";r.startsWith(j.apiBase)&&(r=r.slice(j.apiBase.length)),r.startsWith("/")||(r=`/${r}`);const d=[];r=r.replace(mt,(l,i)=>{const p=d.length===0?t?.primaryKey??"id":`id${d.length+1}`;return d.push({name:p,in:"path",required:!0,schema:{type:"string",format:"uuid"},...i.startsWith("<")?{}:{example:i}}),`({${p}})`});const c=s?s.split("&").filter(Boolean).map(l=>{const i=l.indexOf("="),p=ye(i>=0?l.slice(0,i):l),h=ye(i>=0?l.slice(i+1):"");return{name:p,in:"query",required:p.startsWith("@"),schema:{type:"string"},example:h}}):[];return{path:r,pathParams:d,queryParams:c}}const wt=new Set(["accept","content-type"]);function vt(e){return Object.entries(e).filter(([t,n])=>n&&!wt.has(t.toLowerCase())&&!z(t)).map(([t,n])=>Je(t)?{name:t,in:"header",required:!1,description:"Id of the user to impersonate.",schema:{type:"string",format:"uuid"}}:{name:t,in:"header",required:!1,schema:{type:"string"},example:n})}const xt={description:"Error",content:{"application/json":{schema:{$ref:"#/components/schemas/ODataError"}}}};function Tt(e,t,n,o){const r=e.method.toUpperCase(),s=/return=representation/i.test(n.headers.Prefer??""),d=n.built.entitySet,c=!!d&&t===`/${d}`,l=!!d&&new RegExp(`^/${d}\\(\\{[^}]+\\}\\)$`).test(t),i=(p,h)=>({description:h,content:{"application/json":{schema:p}}});return r==="GET"?o&&c?{200:i({type:"object",properties:{"@odata.context":{type:"string"},"@odata.count":{type:"integer"},"@odata.nextLink":{type:"string"},value:{type:"array",items:{$ref:o}}}},"Rows")}:o&&l?{200:i({$ref:o},"Row")}:{200:i({type:"object",additionalProperties:!0},"OK")}:(r==="POST"||r==="PATCH")&&s&&o&&(c||l)?{[r==="POST"?"201":"200"]:i({$ref:o},"Row as written")}:r==="POST"&&c?{204:{description:"Created",headers:{"OData-EntityId":{description:"URL of the created row",schema:{type:"string"}}}}}:r==="POST"&&!t.endsWith("/$ref")?{200:i({type:"object",additionalProperties:!0},"OK"),204:{description:"No content"}}:{204:{description:"No content"}}}function St(e){const t=e.built.entityLogical?Xe(e.built.entityLogical):void 0,n=e.isNextLink?[{method:"GET",relativeUrl:(e.rawNextLink??"").trim()}]:e.multiRequests&&e.multiRequests.length>1?e.multiRequests:[{method:e.method,relativeUrl:e.built.relativeUrl,body:e.body}],o={ODataError:{type:"object",properties:{error:{type:"object",properties:{code:{type:"string"},message:{type:"string"}}}}}};let r=null;if(t){const l=e.built.queryParts.find(i=>i.key==="$select");o[t.logicalName]=bt(t,l?ye(l.value).split(",").filter(Boolean):null),r=`#/components/schemas/${t.logicalName}`}const s={};n.forEach((l,i)=>{if(!l.relativeUrl||l.relativeUrl.startsWith("<"))return;const{path:p,pathParams:h,queryParams:m}=$t(l.relativeUrl,t),u=l.method.toLowerCase(),x=s[p]??(s[p]={});if(x[u])return;const y=l.body;x[u]={operationId:`${u}${n.length>1?`_${i+1}`:""}_${(e.built.entitySet||"request").replace(/[^A-Za-z0-9]/g,"_")}`,summary:l.description??`${l.method.toUpperCase()} ${p}`,...t?{tags:[t.logicalName]}:{},parameters:[...h,...m,...vt(e.headers)],...y?{requestBody:{required:!0,content:{"application/json":{schema:gt(y,t),example:y}}}}:{},responses:{...Tt(l,p,e,r),default:xt}}});const d=j.host||"<org>.crm.dynamics.com",c={openapi:"3.0.3",info:{title:`Dataverse Web API: ${t?.displayName??(e.built.entitySet||"request")}`,version:_e,description:"Generated by Dataverse Request Studio for the request in the builder."},servers:[{url:`https://${d}${j.apiBase}`}],security:[{bearerAuth:[]},{entraId:[`https://${d}/user_impersonation`]}],paths:s,components:{schemas:o,securitySchemes:{bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT",description:"Microsoft Entra ID access token for the Dataverse org."},entraId:{type:"oauth2",flows:{authorizationCode:{authorizationUrl:"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",tokenUrl:"https://login.microsoftonline.com/common/oauth2/v2.0/token",scopes:{[`https://${d}/user_impersonation`]:"Access Dataverse as the signed-in user"}}}}}}};return JSON.stringify(c,null,2)}const qe={fetch:"fetch",xrm:"Xrm.WebApi","xrm-batch":"Xrm.WebApi.executeMultiple",xhr:"XMLHttpRequest",powerautomate:"Power Automate",csharp:"C#",python:"Python",powershell:"PowerShell",curl:"cURL",json:"JSON",openapi:"OpenAPI"},De={fetch:"javascript",xrm:"javascript","xrm-batch":"javascript",xhr:"javascript",powerautomate:"plaintext",csharp:"csharp",python:"python",powershell:"powershell",curl:"shell",json:"json",openapi:"json"},F=e=>e==="GET"||e==="DELETE",Se=new Set(["content-type","content-range","content-length"]);function ce(e,t){switch(e){case"fetch":return $e(t);case"xrm":return Ct(t);case"xrm-batch":return qt(t);case"xhr":return Dt(t);case"powerautomate":return Nt(t);case"csharp":return Ot(t);case"python":return Mt(t);case"powershell":return Bt(t);case"curl":return It(t);case"json":return Ft(t);case"openapi":return St(t)}}function J(e){return fe(`https://${j.host}${e.built.relativeUrl}`)}function H(e){return e.isNextLink&&e.rawNextLink?e.rawNextLink.trim():J(e)}function Q(e){return e.relativeUrl.startsWith("<")?e.relativeUrl:fe(`https://${j.host}${e.relativeUrl}`)}function Pe(e){return e.built.relativeUrl.split("?")[0]}function Le(e){if(e.method!=="GET"||e.isNextLink)return null;const t=Pe(e),n=t.match(/\/Microsoft\.Dynamics\.CRM\.([A-Za-z_]\w*)/);return n?{name:n[1],binding:/\)\/Microsoft\.Dynamics\.CRM\./.test(t)?"entity":"collection"}:!e.built.entitySet&&!e.built.recordId?{name:e.built.relativeNoBase.split("?")[0].match(/^\/([^/(]+)/)?.[1]??"",binding:"unbound"}:null}function Ne(e){return!e.built.recordId&&/^\/[^/]+\([^)]*=/.test(e.built.relativeNoBase.split("?")[0])}function te(e){return e.method!=="PUT"?null:Pe(e).match(/\)\/([A-Za-z_]\w*)$/)?.[1]??null}function Oe(e,t,n){const o=e.built.queryParts.filter(c=>c.key.startsWith("@")).map(c=>`${n}${c.key.replace(/^@/,"")}: ${Rt(c.value)},`),r=t.binding==="entity",s=e.built.entityLogical;return[...o,...r?[`${n}entity: { entityType: '${s}', id: '${g(e.built.recordId??"<id>")}' },`]:[],`${n}getMetadata: () => ({`,`${n} boundParameter: ${r?"'entity'":"null"},`,`${n} operationType: 1, // 1 = Function`,`${n} operationName: '${t.name}',`,r?`${n} parameterTypes: { entity: { typeName: 'mscrm.${s}', structuralProperty: 5 } /* + parameter type descriptors per CSDL */ },`:`${n} parameterTypes: { /* parameter type descriptors per CSDL */ },`,`${n}}),`].join(`
|
|
3
|
+
`)}function I(e){const t={};for(const[n,o]of Object.entries(e))o&&(z(n)||(t[n]=o));return t}function Me(e){return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,t=>{let n;try{n=decodeURIComponent(t)}catch{return t}return n.replace(/[&#+%]/g,o=>encodeURIComponent(o))})}function ge(e){try{return decodeURIComponent(e)}catch{return e}}function g(e){return e.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function Ue(e,t){const n=Object.entries(e).filter(([,o])=>o);return n.length===0?"":n.map(([o,r])=>`${t}'${g(o)}': '${g(r)}'`).join(`,
|
|
4
|
+
`)}function V(e,t){const n=Object.keys(e);if(n.length===0)return"{}";const o=t+" ";return`{
|
|
5
|
+
${n.map(s=>{const d=e[s],c=/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(s)?s:`'${g(s)}'`;return`${o}${c}: ${ae(d,o)}`}).join(`,
|
|
6
|
+
`)},
|
|
7
|
+
${t}}`}function Rt(e){const t=ge(e).trim();if(t.startsWith("[")&&t.endsWith("]"))try{return JSON.stringify(JSON.parse(t))}catch{}if(t.startsWith("'")&&t.endsWith("'")){const n=t.slice(1,-1).replace(/''/g,"'");return`'${g(n)}'`}return t==="true"||t==="false"||/^-?\d+(?:\.\d+)?$/.test(t)?t:`'${g(t)}'`}function ae(e,t){return e===null?"null":typeof e=="string"?`'${g(e)}'`:typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?e.length===0?"[]":`[ ${e.map(n=>ae(n,t)).join(", ")} ]`:typeof e=="object"?V(e,t):JSON.stringify(e)}function $e(e){if(e.multiRequests&&e.multiRequests.length>1)return ne(e);const t=H(e),n=I(e.headers),o=Ue(n," "),r=!F(e.method),s=r?e.rawBody?`
|
|
8
|
+
body: fileBytes,`:`
|
|
9
|
+
body: JSON.stringify(payload),`:"";return`// Dataverse Web API — fetch
|
|
10
|
+
// Run from a browser context (or Node 18+). Provide a bearer token via the
|
|
11
|
+
// Authorization header below. In Power Apps / D365 form scripts you can also
|
|
12
|
+
// call Xrm.WebApi directly — see the Xrm.WebApi tab.
|
|
13
|
+
|
|
14
|
+
(async () => {
|
|
15
|
+
${r?e.rawBody?` // ${e.rawBody}: an ArrayBuffer / Blob / Uint8Array with the file content.
|
|
16
|
+
const fileBytes = new Uint8Array();
|
|
17
|
+
|
|
18
|
+
`:` const payload = ${V(e.body??{}," ")};
|
|
19
|
+
|
|
20
|
+
`:""} const url = '${g(t)}';
|
|
21
|
+
|
|
22
|
+
const res = await fetch(url, {
|
|
23
|
+
method: '${e.method}',
|
|
24
|
+
headers: {
|
|
25
|
+
'Authorization': 'Bearer <access-token>',
|
|
26
|
+
${o}
|
|
27
|
+
},${s}
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
if (!res.ok) {
|
|
31
|
+
const err = await res.json().catch(() => null);
|
|
32
|
+
throw new Error(\`Dataverse \${res.status}: \${err?.error?.message ?? res.statusText}\`);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// 204 No Content (e.g. Delete) doesn't carry a JSON body
|
|
36
|
+
const data = res.status === 204 ? null : await res.json();
|
|
37
|
+
console.log('Result:', data);
|
|
38
|
+
if (data && Array.isArray(data.value)) {
|
|
39
|
+
console.log(\`Returned \${data.value.length} record(s)\`);
|
|
40
|
+
if (typeof data['@odata.count'] === 'number') {
|
|
41
|
+
console.log(\`@odata.count: \${data['@odata.count']}\`);
|
|
42
|
+
}
|
|
43
|
+
if (data['@odata.nextLink']) {
|
|
44
|
+
console.log('nextLink:', data['@odata.nextLink']);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
})().catch(console.error);
|
|
48
|
+
`}function ne(e){if(E(e))return At(e);const t=I(e.headers),n=Ue(t," "),o=e.multiRequests??[];return`// Dataverse Web API — fetch (multi-request)
|
|
49
|
+
//
|
|
50
|
+
// Each association / disassociation is its own HTTP call per the docs:
|
|
51
|
+
// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/associate-disassociate-entities-using-web-api
|
|
52
|
+
//
|
|
53
|
+
// For more than a handful of targets, prefer a $batch request — sending
|
|
54
|
+
// many small requests in sequence is slower and not transactional. (All or
|
|
55
|
+
// nothing sends them as one $batch change set.)
|
|
56
|
+
|
|
57
|
+
(async () => {
|
|
58
|
+
const requests = [
|
|
59
|
+
${o.map(s=>{const d=Q(s),c=s.rawBody?`, body: '${g(s.rawBody)}' /* replace with the bytes (ArrayBuffer / Blob) */`:s.body?`, body: JSON.stringify(${V(s.body," ")})`:"",l=s.headers&&Object.keys(s.headers).length>0?`, headers: { ${Object.entries(s.headers).map(([p,h])=>`'${g(p)}': '${g(h)}'`).join(", ")} }`:"";return`${s.description?` // ${s.description}
|
|
60
|
+
`:""} { method: '${s.method}', url: '${g(d)}'${l}${c} },`}).join(`
|
|
61
|
+
`)}
|
|
62
|
+
];
|
|
63
|
+
|
|
64
|
+
const sharedHeaders = {
|
|
65
|
+
'Authorization': 'Bearer <access-token>',
|
|
66
|
+
${n}
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const results = [];
|
|
70
|
+
for (const r of requests) {
|
|
71
|
+
const res = await fetch(r.url, {
|
|
72
|
+
method: r.method,
|
|
73
|
+
headers: ${o.some(s=>s.headers&&Object.keys(s.headers).length>0)?"{ ...sharedHeaders, ...r.headers }":"sharedHeaders"},${o.some(s=>s.body||s.rawBody)?`
|
|
74
|
+
body: r.body,`:""}
|
|
75
|
+
});
|
|
76
|
+
if (!res.ok) {
|
|
77
|
+
const err = await res.json().catch(() => null);
|
|
78
|
+
console.error(\`\${r.method} \${r.url} → \${res.status}\`, err?.error?.message ?? res.statusText);
|
|
79
|
+
results.push({ status: res.status, ok: false });
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
results.push({ status: res.status, ok: true });
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
console.log(\`\${results.filter(r => r.ok).length}/\${results.length} requests succeeded\`);
|
|
86
|
+
})().catch(console.error);
|
|
87
|
+
`}const E=e=>!!e.changeSet&&!!e.multiRequests&&e.multiRequests.length>1,kt=new Set(["accept","content-type","content-length","odata-version","odata-maxversion"]),jt={batch:"batch_drs",changeset:()=>"changeset_drs"};function K(e){const t=Object.entries(I(e.headers)).filter(([s])=>!kt.has(s.toLowerCase())),n=(e.multiRequests??[]).map((s,d)=>({contentId:String(d+1),wire:{method:s.method,path:s.relativeUrl.startsWith(`${j.apiBase}/`)?s.relativeUrl.slice(j.apiBase.length+1):s.relativeUrl.replace(/^\//,""),headers:{...Object.fromEntries(t),...s.headers??{}},body:s.body?JSON.stringify(s.body):void 0}})),o=lt([{atomic:!0,parts:n}],jt),r=o.body.split(ct);return r[r.length-1]===""&&r.pop(),{url:`https://${j.host}${j.apiBase}/$batch`,headers:[["OData-MaxVersion","4.0"],["OData-Version","4.0"],["Accept","application/json"],["Content-Type",o.contentType]],lines:r}}const Z=e=>`The ${e} requests go in one change set: Dataverse applies all of them or, if
|
|
88
|
+
any fails, none. Every line of the body must end in CRLF.
|
|
89
|
+
https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/execute-batch-operations-using-web-api`,Y=(e,t)=>e.split(`
|
|
90
|
+
`).map(n=>`${t} ${n}`.trimEnd()).join(`
|
|
91
|
+
`);function At(e){const t=K(e);return`// Dataverse Web API — fetch, one $batch change set (all or nothing)
|
|
92
|
+
//
|
|
93
|
+
${Y(Z(e.multiRequests.length),"//")}
|
|
94
|
+
|
|
95
|
+
(async () => {
|
|
96
|
+
const body = [
|
|
97
|
+
${t.lines.map(n=>` ${JSON.stringify(n)},`).join(`
|
|
98
|
+
`)}
|
|
99
|
+
].join('\\r\\n') + '\\r\\n';
|
|
100
|
+
|
|
101
|
+
const res = await fetch('${g(t.url)}', {
|
|
102
|
+
method: 'POST',
|
|
103
|
+
headers: {
|
|
104
|
+
'Authorization': 'Bearer <access-token>',
|
|
105
|
+
${t.headers.map(([n,o])=>` '${g(n)}': '${g(o)}',`).join(`
|
|
106
|
+
`)}
|
|
107
|
+
},
|
|
108
|
+
body,
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
// The response is multipart/mixed: a result per request when the change
|
|
112
|
+
// set succeeds, or the failing request's error when it's rolled back.
|
|
113
|
+
console.log(res.status, res.headers.get('Content-Type'));
|
|
114
|
+
console.log(await res.text());
|
|
115
|
+
})().catch(console.error);
|
|
116
|
+
`}function Ct(e){if(e.isNextLink&&e.rawNextLink)return`// Xrm.WebApi doesn't take a raw nextLink URL — follow it via fetch:
|
|
117
|
+
// (Run this in a model-driven app form script context)
|
|
118
|
+
|
|
119
|
+
const nextLink = '${g(e.rawNextLink.trim())}';
|
|
120
|
+
const res = await fetch(nextLink, {
|
|
121
|
+
headers: { 'Accept': 'application/json' },
|
|
122
|
+
});
|
|
123
|
+
const page = await res.json();
|
|
124
|
+
console.log('Next page:', page.value);
|
|
125
|
+
`;if(e.multiRequests&&e.multiRequests.length>1)return`// Xrm.WebApi doesn't expose Associate / Disassociate $ref endpoints
|
|
126
|
+
// directly — the documented path is Xrm.WebApi.online.execute() with a
|
|
127
|
+
// request descriptor, or fall back to fetch. We emit the ${E(e)?"$batch change set":"fetch loop"}:
|
|
128
|
+
|
|
129
|
+
${ne(e)}`;const t=e.built.entityLogical,n=e.built.recordId,o=e.built.queryParts.map(b=>`${b.key}=${Me(b.value)}`).join("&"),r=o?`?${o}`:"";let s=null;const d=e.headers.Prefer;if(d){const b=d.match(/odata\.maxpagesize\s*=\s*(\d+)/i);b&&(s=Number(b[1]))}const c=e.built.relativeUrl,l=e.method==="POST"&&(c.includes("/Microsoft.Dynamics.CRM.")||c.endsWith("/Merge")||!n&&!e.built.entitySet&&!!e.body),i=Le(e),p=!!i,h=c.endsWith("/$ref")||/\$ref\?/.test(c),m=c.includes("/workflows("),u=e.method==="GET"&&!n&&!p,x=e.method==="GET"&&!!n&&!p,y=e.method!=="GET"&&!l&&!h&&!m,w=e.rawBody?"Xrm.WebApi sends JSON only — binary file content needs a raw request.":i?.binding==="collection"?"Xrm.WebApi.online.execute only binds functions to a single record ('entity'), not to an entity set.":y&&Ne(e)?"Xrm.WebApi.updateRecord / deleteRecord take a GUID, not an alternate key.":e.method==="PUT"&&!te(e)?"Xrm.WebApi has no single-property PUT helper.":null;if(w)return`// ${w}
|
|
130
|
+
// Use fetch from the form script instead:
|
|
131
|
+
|
|
132
|
+
${$e(e)}`;if(l||m){const b=c.match(/\/Microsoft\.Dynamics\.CRM\.([^/?(]+)/),R=b?b[1]:m?"ExecuteWorkflow":c.split("/").pop()??"",q=!!n;return`// Xrm.WebApi.online.execute — actions / workflows / custom APIs.
|
|
133
|
+
// Run inside a model-driven app or D365 form script. The request descriptor
|
|
134
|
+
// must implement getMetadata() so Xrm knows which operation to invoke.
|
|
135
|
+
|
|
136
|
+
(async () => {
|
|
137
|
+
const request = {
|
|
138
|
+
${Object.entries(e.body??{}).map(([S,M])=>` ${/^[a-zA-Z_$][\w$]*$/.test(S)?S:`'${g(S)}'`}: ${ae(M," ")},`).join(`
|
|
139
|
+
`)}
|
|
140
|
+
${q?` entity: { entityType: '${t}', id: '${g(n??"")}' },
|
|
141
|
+
`:""} getMetadata: () => ({
|
|
142
|
+
boundParameter: ${q?"'entity'":"null"},
|
|
143
|
+
operationType: 0, // 0 = Action · 1 = Function · 2 = CRUD
|
|
144
|
+
operationName: '${R}',
|
|
145
|
+
parameterTypes: { /* parameter type descriptors per CSDL */ },
|
|
146
|
+
}),
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
const response = await Xrm.WebApi.online.execute(request);
|
|
150
|
+
if (response.ok) {
|
|
151
|
+
const result = response.status === 204 ? null : await response.json();
|
|
152
|
+
console.log('Action result:', result);
|
|
153
|
+
} else {
|
|
154
|
+
console.error('Action failed:', response.status, response.statusText);
|
|
155
|
+
}
|
|
156
|
+
})().catch(err => console.error('Xrm.WebApi.online.execute error:', err));
|
|
157
|
+
`}if(i)return`// Xrm.WebApi.online.execute — OData function call.
|
|
158
|
+
// Functions are GET requests; the descriptor sets operationType: 1.
|
|
159
|
+
|
|
160
|
+
(async () => {
|
|
161
|
+
const request = {
|
|
162
|
+
${Oe(e,i," ")}
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
const response = await Xrm.WebApi.online.execute(request);
|
|
166
|
+
if (response.ok) {
|
|
167
|
+
const result = await response.json();
|
|
168
|
+
console.log('Function result:', result);
|
|
169
|
+
} else {
|
|
170
|
+
console.error('Function failed:', response.status, response.statusText);
|
|
171
|
+
}
|
|
172
|
+
})().catch(err => console.error('Xrm.WebApi.online.execute error:', err));
|
|
173
|
+
`;if(h)return`// Xrm.WebApi has no direct support for $ref endpoints (Associate /
|
|
174
|
+
// Disassociate). Use the documented Xrm.WebApi.online.execute() pattern
|
|
175
|
+
// with a CreateAssociation / DisassociateRecords descriptor, OR fall back
|
|
176
|
+
// to a fetch loop — see the fetch tab for the multi-request version.
|
|
177
|
+
|
|
178
|
+
${ne(e)}`;if(u)return`// Xrm.WebApi.retrieveMultipleRecords — run inside a model-driven app / D365 form script.
|
|
179
|
+
// The options string mirrors the query string of the underlying REST URL.
|
|
180
|
+
|
|
181
|
+
(async () => {
|
|
182
|
+
const entityLogicalName = '${t}';
|
|
183
|
+
const options = '${g(r)}';${s?`
|
|
184
|
+
const maxPageSize = ${s};`:""}
|
|
185
|
+
|
|
186
|
+
const result = await Xrm.WebApi.retrieveMultipleRecords(entityLogicalName, options${s?", maxPageSize":""});
|
|
187
|
+
|
|
188
|
+
console.log(\`Returned \${result.entities.length} record(s)\`);
|
|
189
|
+
console.log(result.entities);
|
|
190
|
+
|
|
191
|
+
// Annotations attach to each entity row as <prop>@OData.Community.Display.V1.FormattedValue, etc.
|
|
192
|
+
// If a @odata.nextLink is returned, fetch it directly to get the next page:
|
|
193
|
+
if (result.nextLink) {
|
|
194
|
+
console.log('Next page:', result.nextLink);
|
|
195
|
+
}
|
|
196
|
+
})().catch(err => console.error('Xrm.WebApi error:', err));
|
|
197
|
+
`;if(x)return`// Xrm.WebApi.retrieveRecord — run inside a model-driven app / D365 form script.
|
|
198
|
+
|
|
199
|
+
(async () => {
|
|
200
|
+
const entityLogicalName = '${t}';
|
|
201
|
+
const id = '${n??"<id>"}';
|
|
202
|
+
const options = '${g(r)}';
|
|
203
|
+
|
|
204
|
+
const record = await Xrm.WebApi.retrieveRecord(entityLogicalName, id, options);
|
|
205
|
+
console.log('Got record:', record);
|
|
206
|
+
})().catch(err => console.error('Xrm.WebApi error:', err));
|
|
207
|
+
`;if(y){const b=e.method==="POST"?"createRecord":e.method==="DELETE"?"deleteRecord":"updateRecord",R=te(e),q=R?{[R]:e.body?.value??null}:e.body??{},S=b==="deleteRecord"?"":` const data = ${V(q," ")};
|
|
208
|
+
|
|
209
|
+
`,M=b==="deleteRecord"?"entityLogicalName, id":b==="createRecord"?"entityLogicalName, data":"entityLogicalName, id, data",W=b!=="createRecord";return`// Xrm.WebApi.${b} — write-side request.
|
|
210
|
+
// Run inside a model-driven app / D365 form script.
|
|
211
|
+
//
|
|
212
|
+
// Notes:
|
|
213
|
+
// • @odata.bind keys in \`data\` set lookup values — the value is the OData
|
|
214
|
+
// entity-set URL fragment, e.g. '/contacts(<guid>)'.
|
|
215
|
+
// • Multi-select choice columns are sent as comma-separated integer strings.
|
|
216
|
+
// • createRecord / updateRecord resolve to { entityType, id } only — no
|
|
217
|
+
// column values. Call Xrm.WebApi.retrieveRecord if you need the saved row.${R?`
|
|
218
|
+
// • PUT /<set>(<id>)/${R} has no Xrm.WebApi helper — updateRecord with
|
|
219
|
+
// just that column is the equivalent PATCH.`:""}
|
|
220
|
+
|
|
221
|
+
(async () => {
|
|
222
|
+
const entityLogicalName = '${t}';
|
|
223
|
+
${W?` const id = '${g(n??"<id>")}';
|
|
224
|
+
`:""}${S} const result = await Xrm.WebApi.${b}(${M});
|
|
225
|
+
console.log('Result:', result);
|
|
226
|
+
})().catch(err => console.error('Xrm.WebApi error:', err));
|
|
227
|
+
`}return""}function qt(e){if(e.isNextLink&&e.rawNextLink)return`// executeMultiple doesn't follow raw @odata.nextLink URLs — paging on a
|
|
228
|
+
// previously-returned cursor lives outside the batch pattern. Use the
|
|
229
|
+
// Xrm.WebApi tab (which falls back to fetch for next-link follow-ups) or
|
|
230
|
+
// call retrieveMultipleRecords directly with the same options string.
|
|
231
|
+
`;const t=e.built.entityLogical,n=e.built.recordId,o=e.built.relativeUrl,r=e.method==="POST"&&(o.includes("/Microsoft.Dynamics.CRM.")||o.endsWith("/Merge")||!n&&!e.built.entitySet&&!!e.body),s=Le(e),d=!!s,c=o.includes("/workflows("),l=o.endsWith("/$ref")||/\$ref\?/.test(o),i=e.method==="GET"&&!n&&!d,p=e.method==="GET"&&!!n&&!d,h=e.method!=="GET"&&!r&&!l&&!c,m=e.rawBody||e.multiRequests&&e.multiRequests.length>1&&!l?"executeMultiple descriptors send JSON only — binary file uploads / downloads need raw requests.":s?.binding==="collection"?"Function descriptors only bind to a single record ('entity'), not to an entity set.":h&&Ne(e)?"CRUD descriptors address rows by GUID, not by alternate key.":e.method==="PUT"&&!te(e)?"There is no CRUD descriptor for this single-property PUT.":null;if(m)return`// ${m}
|
|
232
|
+
// Use fetch instead:
|
|
233
|
+
|
|
234
|
+
${$e(e)}`;const u=e.built.queryParts.map(y=>`${y.key}=${Me(y.value)}`).join("&"),x=u?`?${u}`:"";if(r||c){const y=o.match(/\/Microsoft\.Dynamics\.CRM\.([^/?(]+)/),w=y?y[1]:c?"ExecuteWorkflow":o.split("/").pop()??"",b=!!n;return`// Xrm.WebApi.online.executeMultiple — batch one action (extend the array
|
|
235
|
+
// to chain more requests). Set the second argument to false for "fail fast"
|
|
236
|
+
// (Change Set semantics — first failure rolls back the rest); true for
|
|
237
|
+
// "continue on error" (Faulted set semantics).
|
|
238
|
+
//
|
|
239
|
+
// Doc: https://learn.microsoft.com/en-us/power-apps/developer/model-driven-apps/clientapi/reference/xrm-webapi/online/executemultiple
|
|
240
|
+
|
|
241
|
+
(async () => {
|
|
242
|
+
const requests = [
|
|
243
|
+
{
|
|
244
|
+
${Object.entries(e.body??{}).map(([q,S])=>` ${/^[a-zA-Z_$][\w$]*$/.test(q)?q:`'${g(q)}'`}: ${ae(S," ")},`).join(`
|
|
245
|
+
`)}
|
|
246
|
+
${b?` entity: { entityType: '${t}', id: '${g(n??"")}' },
|
|
247
|
+
`:""} getMetadata: () => ({
|
|
248
|
+
boundParameter: ${b?"'entity'":"null"},
|
|
249
|
+
operationType: 0, // 0 = Action
|
|
250
|
+
operationName: '${w}',
|
|
251
|
+
parameterTypes: { /* parameter type descriptors per CSDL */ },
|
|
252
|
+
}),
|
|
253
|
+
},
|
|
254
|
+
];
|
|
255
|
+
|
|
256
|
+
const results = await Xrm.WebApi.online.executeMultiple(requests);
|
|
257
|
+
results.forEach((r, idx) => {
|
|
258
|
+
console.log(\`Request \${idx} → status \${r.status} \${r.statusText}\`);
|
|
259
|
+
});
|
|
260
|
+
})().catch(err => console.error('executeMultiple error:', err));
|
|
261
|
+
`}if(s)return`// Xrm.WebApi.online.executeMultiple — batched function call.
|
|
262
|
+
// Functions use operationType: 1 in the metadata descriptor.
|
|
263
|
+
|
|
264
|
+
(async () => {
|
|
265
|
+
const requests = [
|
|
266
|
+
{
|
|
267
|
+
${Oe(e,s," ")}
|
|
268
|
+
},
|
|
269
|
+
];
|
|
270
|
+
|
|
271
|
+
const results = await Xrm.WebApi.online.executeMultiple(requests);
|
|
272
|
+
for (const r of results) {
|
|
273
|
+
if (r.ok) {
|
|
274
|
+
const data = await r.json();
|
|
275
|
+
console.log('Function result:', data);
|
|
276
|
+
} else {
|
|
277
|
+
console.error('Function failed:', r.status, r.statusText);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
})().catch(err => console.error('executeMultiple error:', err));
|
|
281
|
+
`;if(l){const w=e.method==="POST"?"Associate":"Disassociate",b=e.multiRequests&&e.multiRequests.length>0?e.multiRequests:[{url:o,method:e.method,body:e.body??null}],R=E(e);return`// Xrm.WebApi.online.executeMultiple — ${w} via CRUD descriptors.
|
|
282
|
+
// Each request describes one (target, relationship, related) tuple.${R?`
|
|
283
|
+
// The requests go as one change set (the nested array): all succeed or none do.`:""}
|
|
284
|
+
|
|
285
|
+
(async () => {
|
|
286
|
+
const requests = [
|
|
287
|
+
${b.map(S=>` {
|
|
288
|
+
// target: { entityType: '<table>', id: '<guid>' },
|
|
289
|
+
// relationship: '<schemaName>',
|
|
290
|
+
// relatedEntity: { entityType: '<table>', id: '<guid>' },
|
|
291
|
+
getMetadata: () => ({
|
|
292
|
+
boundParameter: null,
|
|
293
|
+
parameterTypes: {},
|
|
294
|
+
operationType: 2, // 2 = CRUD
|
|
295
|
+
operationName: '${w}',
|
|
296
|
+
}),
|
|
297
|
+
},`).join(`
|
|
298
|
+
`)}
|
|
299
|
+
];
|
|
300
|
+
|
|
301
|
+
const results = await Xrm.WebApi.online.executeMultiple(${R?"[requests]":"requests"});
|
|
302
|
+
console.log(\`\${results.filter(r => r.ok).length}/\${results.length} succeeded\`);
|
|
303
|
+
})().catch(err => console.error('executeMultiple error:', err));
|
|
304
|
+
`}if(i)return`// Xrm.WebApi.online.executeMultiple — batched retrieveMultiple.
|
|
305
|
+
|
|
306
|
+
(async () => {
|
|
307
|
+
const requests = [
|
|
308
|
+
{
|
|
309
|
+
collection: '${e.built.entitySet||t+"s"}',
|
|
310
|
+
query: '${g(x)}',
|
|
311
|
+
getMetadata: () => ({
|
|
312
|
+
boundParameter: null,
|
|
313
|
+
parameterTypes: {},
|
|
314
|
+
operationType: 2, // 2 = CRUD
|
|
315
|
+
operationName: 'RetrieveMultiple',
|
|
316
|
+
}),
|
|
317
|
+
},
|
|
318
|
+
];
|
|
319
|
+
|
|
320
|
+
const results = await Xrm.WebApi.online.executeMultiple(requests);
|
|
321
|
+
for (const r of results) {
|
|
322
|
+
if (r.ok) {
|
|
323
|
+
const data = await r.json();
|
|
324
|
+
console.log(\`Returned \${data.value.length} row(s)\`);
|
|
325
|
+
console.log(data.value);
|
|
326
|
+
} else {
|
|
327
|
+
console.error('Request failed:', r.status, r.statusText);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
})().catch(err => console.error('executeMultiple error:', err));
|
|
331
|
+
`;if(p)return`// Xrm.WebApi.online.executeMultiple — batched retrieve of a single record.
|
|
332
|
+
|
|
333
|
+
(async () => {
|
|
334
|
+
const requests = [
|
|
335
|
+
{
|
|
336
|
+
entity: { entityType: '${t}', id: '${n??"<id>"}' },
|
|
337
|
+
query: '${g(x)}',
|
|
338
|
+
getMetadata: () => ({
|
|
339
|
+
boundParameter: null,
|
|
340
|
+
parameterTypes: {},
|
|
341
|
+
operationType: 2, // 2 = CRUD
|
|
342
|
+
operationName: 'Retrieve',
|
|
343
|
+
}),
|
|
344
|
+
},
|
|
345
|
+
];
|
|
346
|
+
|
|
347
|
+
const results = await Xrm.WebApi.online.executeMultiple(requests);
|
|
348
|
+
for (const r of results) {
|
|
349
|
+
if (r.ok) {
|
|
350
|
+
const record = await r.json();
|
|
351
|
+
console.log('Got record:', record);
|
|
352
|
+
} else {
|
|
353
|
+
console.error('Retrieve failed:', r.status, r.statusText);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
})().catch(err => console.error('executeMultiple error:', err));
|
|
357
|
+
`;if(h){const y=e.method==="POST"?"Create":e.method==="PATCH"?"Update":e.method==="DELETE"?"Delete":"Update",w=te(e),b=w?{[w]:e.body?.value??null}:e.body??{},R=y==="Delete"?"":`
|
|
358
|
+
data: ${V(b," ")},
|
|
359
|
+
`,q=e.built.entitySet||(t?`${t}s`:"<entity-set>"),S=n||y!=="Create"?` entity: { entityType: '${t||"<entity-logical>"}', id: '${g(n??"<id>")}' },`:` collection: '${q}',`;return`// Xrm.WebApi.online.executeMultiple — batched ${y.toLowerCase()} via CRUD descriptor.
|
|
360
|
+
//
|
|
361
|
+
// Extending: drop more descriptors into \`requests\` to do them in a batch.
|
|
362
|
+
// Pass \`false\` as the second arg to Xrm.WebApi.online.executeMultiple for
|
|
363
|
+
// Change Set (transactional) semantics; \`true\` for Faulted (continue on error).
|
|
364
|
+
//
|
|
365
|
+
// Notes:
|
|
366
|
+
// • @odata.bind keys in data set lookup values; the value is the OData
|
|
367
|
+
// entity-set URL fragment, e.g. '/contacts(<guid>)'.
|
|
368
|
+
// • Multi-select choice columns are comma-separated integer strings.
|
|
369
|
+
|
|
370
|
+
(async () => {
|
|
371
|
+
const requests = [
|
|
372
|
+
{
|
|
373
|
+
${S}${R} getMetadata: () => ({
|
|
374
|
+
boundParameter: null,
|
|
375
|
+
parameterTypes: {},
|
|
376
|
+
operationType: 2, // 2 = CRUD
|
|
377
|
+
operationName: '${y}',
|
|
378
|
+
}),
|
|
379
|
+
},
|
|
380
|
+
];
|
|
381
|
+
|
|
382
|
+
const results = await Xrm.WebApi.online.executeMultiple(requests);
|
|
383
|
+
results.forEach((r, idx) => {
|
|
384
|
+
if (r.ok) {
|
|
385
|
+
console.log(\`Request \${idx} succeeded — \${r.status} \${r.statusText}\`);
|
|
386
|
+
} else {
|
|
387
|
+
console.error(\`Request \${idx} failed — \${r.status} \${r.statusText}\`);
|
|
388
|
+
}
|
|
389
|
+
});
|
|
390
|
+
})().catch(err => console.error('executeMultiple error:', err));
|
|
391
|
+
`}return""}function Dt(e){if(e.multiRequests&&e.multiRequests.length>1)return ne(e);const t=H(e),n=I(e.headers),o=Object.entries(n).filter(([,r])=>r).map(([r,s])=>`req.setRequestHeader('${g(r)}', '${g(s)}');`).join(`
|
|
392
|
+
`);return`// Dataverse Web API — XMLHttpRequest
|
|
393
|
+
// When running inside a model-driven app, prefer Xrm.Utility.getGlobalContext().getClientUrl()
|
|
394
|
+
// so the snippet works across environments without hardcoding the org URL.
|
|
395
|
+
|
|
396
|
+
(function () {
|
|
397
|
+
var clientUrl = (typeof Xrm !== 'undefined' && Xrm.Utility && Xrm.Utility.getGlobalContext)
|
|
398
|
+
? Xrm.Utility.getGlobalContext().getClientUrl()
|
|
399
|
+
: '${j.host?"https://"+j.host:""}';
|
|
400
|
+
var url = clientUrl + '${g(fe(e.built.relativeUrl)||(e.rawNextLink??""))}';
|
|
401
|
+
|
|
402
|
+
var req = new XMLHttpRequest();
|
|
403
|
+
req.open('${e.method}', url, true);
|
|
404
|
+
req.setRequestHeader('Authorization', 'Bearer <access-token>');
|
|
405
|
+
${o?" "+o.split(`
|
|
406
|
+
`).join(`
|
|
407
|
+
`):""}
|
|
408
|
+
req.onreadystatechange = function () {
|
|
409
|
+
if (req.readyState !== 4) return;
|
|
410
|
+
req.onreadystatechange = null;
|
|
411
|
+
if (req.status >= 200 && req.status < 300) {
|
|
412
|
+
var data = req.status === 204 ? null : JSON.parse(req.responseText);
|
|
413
|
+
console.log('Result:', data);
|
|
414
|
+
} else {
|
|
415
|
+
console.error('Dataverse ' + req.status + ':', req.responseText);
|
|
416
|
+
}
|
|
417
|
+
};
|
|
418
|
+
req.send(${F(e.method)?"":e.rawBody?`/* ${e.rawBody}: ArrayBuffer / Blob with the file content */ new Uint8Array()`:`JSON.stringify(${V(e.body??{}," ")})`});
|
|
419
|
+
})();
|
|
420
|
+
|
|
421
|
+
// XMLHttpRequest example — full URL form (if you can't use Xrm.Utility):
|
|
422
|
+
// var req = new XMLHttpRequest();
|
|
423
|
+
// req.open('${e.method}', '${t}', true);
|
|
424
|
+
// ...
|
|
425
|
+
`}function Ee(e){const t=e.built.entitySet,n=we(e).split("?")[0],o=n.endsWith("/$ref"),r=n.includes("/Microsoft.Dynamics.CRM.")||n.endsWith("/Merge"),s=!!t&&(n==="/"+t||n.startsWith("/"+t+"(")),d=!!t&&n==="/"+t,c=s&&/^\/[^/]+\([^)]*\)$/.test(n),l=c&&(!!e.built.recordId||!/\([^)]*=/.test(n)),i=s&&!o&&!r&&/^\/[^/]+\([^)]*\)\/[^/]+$/.test(n),p=e.method==="GET"&&(r||!t),h=e.method==="POST"&&(r||!e.built.recordId&&!e.built.entitySet&&!!e.body),m=e.method==="GET"&&l&&!p,u=e.method==="POST"&&d&&!!e.body,x=e.method==="PATCH"&&l&&!!e.body,y=e.method==="DELETE"&&l,w=e.method==="GET"&&d;let b=null;return!m&&!u&&!x&&!y&&!h&&!p&&!w&&(b=e.method==="DELETE"&&i?`This DELETE clears a single column (or a file / image column) — it does NOT delete the row. Don't use "Delete a row": send this request with the Dataverse connector's "Invoke an HTTP request" action.`:e.method==="PUT"&&i?'A single-column PUT has no matching row action. Use "Update a row" with just that column, or send this request with "Invoke an HTTP request".':o?`Associate / disassociate via $ref. The connector's "Relate rows" / "Unrelate rows" actions cover this, or send this request with "Invoke an HTTP request".`+(E(e)?' For all or nothing, put one action per target in a "Perform a changeset request" action.':""):c&&!l?`This request addresses the row by alternate key, which the connector's row actions don't take. Send it with "Invoke an HTTP request".`:`The connector's row actions can't express this request. Send it with "Invoke an HTTP request".`),{isRetrieveSingle:m,isCreate:u,isUpdate:x,isDelete:y,isAction:h,isFunction:p,isList:w,httpReason:b}}function we(e){return e.built.relativeUrl.replace(/^\/api\/data\/v\d+\.\d+/,"")}function Pt(e,t){return{actionName:"Invoke an HTTP request",connector:"Microsoft Dataverse connector",banner:t,fields:[{label:"Method",value:e.method},{label:"Relative URI",value:we(e),multiline:!0,hint:`Strip the ${je} prefix — the connector adds it`},{label:"Body",value:e.body?JSON.stringify(e.body,null,2):"",multiline:!!e.body,hint:e.body?"JSON request body":"No body"}],notes:["Request headers (If-Match, Prefer, MSCRM.*) go in the action's Headers field."],httpFallback:{method:e.method,uri:J(e),note:`Generic HTTP action — use this when "Invoke an HTTP request" isn't available in your connector version.`}}}function Lt(e){if(e.isNextLink&&e.rawNextLink)return{actionName:"Follow @odata.nextLink",connector:"Generic HTTP action",banner:`The Dataverse "List rows" action won't accept an opaque nextLink — use the generic HTTP action instead. Most flows don't need this: set Maximum Pagination Size on "List rows" and the connector iterates pages automatically.`,fields:[{label:"Method",value:"GET"},{label:"URI",value:e.rawNextLink,multiline:!0}]};const t=v=>{const f=e.built.queryParts.find(T=>T.key===v);return f?ge(f.value):""},n=t("$select"),o=t("$filter"),r=t("$orderby"),s=t("$expand"),d=t("$top"),c=t("$apply"),l=t("$count")==="true",i=t("savedQuery"),p=t("userQuery");let h="";const m=e.headers.Prefer;if(m){const v=m.match(/odata\.maxpagesize\s*=\s*(\d+)/i);v&&(h=v[1])}const u=!!i||!!p,{isRetrieveSingle:x,isCreate:y,isUpdate:w,isDelete:b,isAction:R,isFunction:q,httpReason:S}=Ee(e);if(S)return Pt(e,S);if(w){const v=e.body??{},f=[{label:"Table name",value:e.built.entitySet,hint:"Entity set name (plural — e.g. accounts)"},{label:"Row ID",value:e.built.recordId??"",hint:"GUID of the record to update"}];for(const[T,$]of Object.entries(v))if(T.endsWith("@odata.bind")){const A=T.replace("@odata.bind",""),O=typeof $=="string"?$.match(/\/([^/(]+)\((.*)\)/):null;if(O){const[,P,U]=O;f.push({label:A,value:U,hint:`Lookup → ${P}`})}else f.push({label:A,value:String($)})}else{const A=typeof $=="string"?$:JSON.stringify($);f.push({label:T,value:A})}return{actionName:"Update a row",connector:"Microsoft Dataverse connector",banner:`Open the "Update a row" action → pick the table, paste the Row ID, then fill only the columns you want to change. Leave others blank — they're left untouched.`,fields:f,notes:["PATCH semantics: only listed columns are updated. Empty fields stay as-is on the row.","Lookup values: pick the related row from the searchable dropdown — the connector handles @odata.bind internally.",'Set a column to null via "Show advanced options" → null fields.']}}if(b)return{actionName:"Delete a row",connector:"Microsoft Dataverse connector",banner:`Open the "Delete a row" action → pick the table + Row ID. There's no body and no "are you sure" — the row is gone on success.`,fields:[{label:"Table name",value:e.built.entitySet,hint:"Entity set name (plural — e.g. accounts)"},{label:"Row ID",value:e.built.recordId??"",hint:"GUID of the row to delete"}],notes:["Deletes cascade per relationship config — review cascade-delete rules first.","For optimistic concurrency, send an If-Match etag header via the generic HTTP action; the Dataverse connector doesn't surface it."]};if(R){const v=!!e.built.recordId,f=e.built.relativeUrl.match(/\/Microsoft\.Dynamics\.CRM\.([^/?(]+)|\/([^/?(]+)$/),T=f&&(f[1]||f[2])||"",$=e.body??{},A=Object.entries($).map(([O,P])=>({label:O,value:typeof P=="string"?P:JSON.stringify(P,null,2),multiline:typeof P=="object"&&P!==null,hint:typeof P=="object"&&P!==null?"Complex / entity-typed param — paste this JSON into the parameter's value field":void 0}));return{actionName:v?"Perform a bound action":"Perform an unbound action",connector:"Microsoft Dataverse connector",banner:v?`Open the "Perform a bound action" → pick the table, paste the Row ID, then pick "${T}" from the action dropdown. Fill the parameters below.`:`Open the "Perform an unbound action" → pick "${T}" from the action dropdown (or paste this name). Fill the parameters below.`,fields:[{label:"Action name",value:T,hint:"Microsoft.Dynamics.CRM.<name> for OOB; <publisher>_<name> for custom"},...v?[{label:"Table name",value:e.built.entitySet,hint:"Bound entity's entity set name"},{label:"Row ID",value:e.built.recordId??"",hint:"GUID of the bound row"}]:[],...A],notes:["The Dataverse connector renders each parameter as a typed dynamic field — pick from dropdowns where the action accepts EntityReferences.","Complex types (PrincipalAccess, OpportunityClose, etc.) are JSON objects — paste the full JSON into the parameter."]}}if(q)return{actionName:"Invoke an HTTP request (function)",connector:"Microsoft Dataverse connector",banner:`The Dataverse connector doesn't expose OData functions directly. Use the connector's "Invoke an HTTP request" action (or the generic HTTP action) to GET the function URL.`,fields:[{label:"Method",value:"GET"},{label:"Relative URI",value:e.built.relativeUrl.replace(/^\/api\/data\/v\d+\.\d+/,""),hint:`Strip the ${je} prefix — the connector adds it`},{label:"Body",value:"",hint:"Functions have no body"}],notes:["Use parameter aliases (e.g. @p1) — they're recommended for any non-trivial value (long strings, GUIDs, DateTimeOffset).","For bound functions, the URL is /<set>(<id>)/Microsoft.Dynamics.CRM.<name>(...). Inline params accepted but aliases preferred."],httpFallback:{method:"GET",uri:J(e),note:`Generic HTTP action — use this when "Invoke an HTTP request" isn't available in your connector version.`}};if(y){const v=e.body??{},f=[{label:"Table name",value:e.built.entitySet,hint:"Entity set name (plural — e.g. accounts)"}];for(const[T,$]of Object.entries(v))if(T.endsWith("@odata.bind")){const A=T.replace("@odata.bind",""),O=typeof $=="string"?$.match(/\/([^/(]+)\((.*)\)/):null;if(O){const[,P,U]=O;f.push({label:A,value:U,hint:`Lookup → ${P} · pick the row in the connector dropdown (or paste this GUID into the dynamic field)`})}else f.push({label:A,value:String($)})}else{const A=typeof $=="string"?$:JSON.stringify($);f.push({label:T,value:A})}return{actionName:"Add a new row",connector:"Microsoft Dataverse connector",banner:'Open the "Add a new row" action in your flow → pick the table, then paste each value into the matching dynamic field. Lookup fields show the related table as a searchable dropdown — paste the GUID or pick the row from there.',fields:f,notes:["The Dataverse connector exposes every writable column as a dynamic field — they appear only after you pick the table.","Lookup values: pick the related row from the searchable dropdown. The connector handles the @odata.bind syntax internally.","Multi-select choice: the action lets you select multiple options from a checkbox list.",'Choose "Show advanced options" to set MSCRM.SuppressDuplicateDetection or set the row owner.']}}if(x)return{actionName:"Get a row by ID",connector:"Microsoft Dataverse connector",banner:'Open the action in your flow → paste each value into the matching field. "Get a row by ID" only supports $select and $expand — Dataverse rejects $filter/$orderby/$top on a single-record URL.',fields:[{label:"Table name",value:e.built.entitySet,hint:"Entity set name (plural — e.g. accounts)"},{label:"Row ID",value:e.built.recordId??"",hint:"GUID of the record"},{label:"Select Columns",value:n,hint:"Logical names, comma-separated"},{label:"Expand Query",value:s,multiline:!0,hint:"Nav property name with optional inner ($select=…) in parens"}]};if(u)return{actionName:"List rows · Saved / User Query",connector:"Microsoft Dataverse connector",banner:"When you set Saved Query or User Query, the connector IGNORES the OData fields (Select / Filter / Sort / Expand) — those live inside the FetchXml the saved query embeds. Only Top Count and Maximum Pagination Size remain editable.",fields:[{label:"Table name",value:e.built.entitySet,hint:"Entity set name (plural — e.g. accounts)"},...i?[{label:"Saved Query",value:i,hint:"GUID of a system saved query"}]:[{label:"User Query",value:p,hint:"GUID of a personal user query"}],{label:"Top Count",value:d,hint:"Optional — limits total rows returned"},{label:"Maximum Pagination Size",value:h,hint:"Per-page size; connector auto-iterates pages"}],notes:["Select Columns / Filter Rows / Sort By / Expand Query are intentionally NOT shown — the saved query owns them.","Fetch Xml Query is mutually exclusive with Saved Query / User Query — leave it blank."]};const M=[{label:"Table name",value:e.built.entitySet,hint:"Entity set name (plural — e.g. accounts)"},{label:"Select Columns",value:n,hint:"Logical names, comma-separated (no $select= prefix)"},{label:"Filter Rows",value:o,multiline:!0,hint:"OData filter expression (no $filter= prefix)"},{label:"Sort By",value:r,hint:'"col asc, col2 desc" (no $orderby= prefix)'},{label:"Top Count",value:d,hint:"Optional — total rows cap; leave blank to use pagination"},{label:"Expand Query",value:s,multiline:!0,hint:"Nav properties with optional inner ($select=…;$filter=…) in parens"},{label:"Row Count",value:l?"Yes":"No",hint:"Adds @odata.count to the response when Yes"},{label:"Maximum Pagination Size",value:h,hint:"Per-page size; connector auto-iterates pages"},{label:"Fetch Xml Query",value:"",hint:"Alternative to OData params above — leave blank when using them"},{label:"Saved Query",value:"",hint:"GUID — for system saved queries"},{label:"User Query",value:"",hint:"GUID — for personal user queries"}],W=['Column names are LOGICAL names (e.g. "name", not "Account Name").','Sort By takes "col asc, col2 desc" — no $orderby= prefix.',"Expand Query uses parens for inner options, e.g. primarycontactid($select=fullname,emailaddress1).","Maximum Pagination Size enables auto-iteration of @odata.nextLink — leave Top Count blank when you want ALL matching rows."];return c&&W.unshift(`⚠ $apply (groupby / aggregate) is set — the "List rows" action doesn't have a field for this. Use the HTTP action below, or rewrite as FetchXml.`),{actionName:"List rows",connector:"Microsoft Dataverse connector",banner:'Open the "List rows" action in your flow and paste each value into the matching field. Empty fields can stay empty.',fields:M,notes:W,httpFallback:c?{method:e.method,uri:J(e),note:`Use this generic HTTP action because $apply / aggregation isn't exposed by the "List rows" action. Replace <access-token> with a valid bearer token.`}:void 0}}function Nt(e){if(e.isNextLink&&e.rawNextLink)return`# Power Automate — follow an @odata.nextLink
|
|
426
|
+
#
|
|
427
|
+
# The Dataverse "List rows" action won't accept an opaque nextLink — it builds
|
|
428
|
+
# its own URL from the connector fields. To follow a nextLink directly, use
|
|
429
|
+
# the generic HTTP action:
|
|
430
|
+
#
|
|
431
|
+
# Method: GET
|
|
432
|
+
# URI: ${e.rawNextLink}
|
|
433
|
+
# Authentication: AAD (use a service-principal or OAuth connection)
|
|
434
|
+
#
|
|
435
|
+
# In most flows you don't need this — set "Maximum Pagination Size" in the
|
|
436
|
+
# Dataverse "List rows" action and the connector iterates pages automatically.
|
|
437
|
+
`;const t=v=>{const f=e.built.queryParts.find(T=>T.key===v);return f?ge(f.value):""},n=t("$select"),o=t("$filter"),r=t("$orderby"),s=t("$expand"),d=t("$top"),c=t("$apply"),l=t("$count")==="true",i=t("savedQuery"),p=t("userQuery");let h="";const m=e.headers.Prefer;if(m){const v=m.match(/odata\.maxpagesize\s*=\s*(\d+)/i);v&&(h=v[1])}const u=(v,f)=>`${v.padEnd(25)} ${f}`,x=!!i||!!p,{isRetrieveSingle:y,isCreate:w,isUpdate:b,isDelete:R,isAction:q,isFunction:S,httpReason:M}=Ee(e);if(M)return`# Power Automate — Dataverse connector ⟶ "Invoke an HTTP request" action
|
|
438
|
+
# ${M}
|
|
439
|
+
|
|
440
|
+
${u("Method",e.method)}
|
|
441
|
+
${u("Relative URI",we(e))}
|
|
442
|
+
${u("Body",e.body?JSON.stringify(e.body):"(none)")}
|
|
443
|
+
|
|
444
|
+
# Request headers (If-Match, Prefer, MSCRM.*) go in the action's Headers field.
|
|
445
|
+
# Generic HTTP action alternative: ${e.method} ${J(e)}
|
|
446
|
+
`;if(b){const v=e.body??{},f=[];f.push(u("Table name",e.built.entitySet)),f.push(u("Row ID",e.built.recordId??""));for(const[T,$]of Object.entries(v)){const A=typeof $=="string"?$:JSON.stringify($);f.push(u(T,A))}return`# Power Automate — Dataverse connector ⟶ "Update a row" action
|
|
447
|
+
# Paste each value into the matching dynamic field. Leave non-listed columns alone — PATCH only touches what's in the body.
|
|
448
|
+
|
|
449
|
+
${f.join(`
|
|
450
|
+
`)}
|
|
451
|
+
|
|
452
|
+
# ── Tips ──
|
|
453
|
+
# • Lookup columns: pick from the searchable dropdown — the connector emits @odata.bind for you.
|
|
454
|
+
# • Set a column to null via "Show advanced options" → null fields list.
|
|
455
|
+
# • For optimistic concurrency, fall back to the HTTP action with an If-Match etag header.
|
|
456
|
+
`}if(R)return`# Power Automate — Dataverse connector ⟶ "Delete a row" action
|
|
457
|
+
# Pick the table + paste the Row ID. No body, no "are you sure".
|
|
458
|
+
|
|
459
|
+
${u("Table name",e.built.entitySet)}
|
|
460
|
+
${u("Row ID",e.built.recordId??"")}
|
|
461
|
+
|
|
462
|
+
# ── Tips ──
|
|
463
|
+
# • Deletes cascade per relationship config — review cascade-delete rules first.
|
|
464
|
+
# • Etag concurrency requires the HTTP action; the connector doesn't surface If-Match.
|
|
465
|
+
`;if(q){const v=!!e.built.recordId,f=e.built.relativeUrl.match(/\/Microsoft\.Dynamics\.CRM\.([^/?(]+)|\/([^/?(]+)$/),T=f&&(f[1]||f[2])||"",$=e.body??{},A=Object.entries($).map(([P,U])=>{const ie=typeof U=="string"?U:JSON.stringify(U);return u(P,ie.length>60?ie.slice(0,57)+"…":ie)});return`# Power Automate — Dataverse connector ⟶ ${v?'"Perform a bound action"':'"Perform an unbound action"'}
|
|
466
|
+
# Pick the action from the dropdown — the connector renders typed parameter fields per metadata.
|
|
467
|
+
|
|
468
|
+
${u("Action name",T)}
|
|
469
|
+
${v?u("Table name",e.built.entitySet)+`
|
|
470
|
+
`+u("Row ID",e.built.recordId??"")+`
|
|
471
|
+
`:""}${A.join(`
|
|
472
|
+
`)}
|
|
473
|
+
|
|
474
|
+
# ── Tips ──
|
|
475
|
+
# • Complex / entity-typed parameters render as nested JSON fields — paste the full object.
|
|
476
|
+
# • For OOB actions use the Microsoft.Dynamics.CRM.<name> form; for custom APIs / actions use the <publisher>_<name> form.
|
|
477
|
+
`}if(S)return`# Power Automate — function call
|
|
478
|
+
# The Dataverse connector doesn't expose OData functions directly. Use the
|
|
479
|
+
# "Invoke an HTTP request" action (Dataverse connector) or the generic HTTP action.
|
|
480
|
+
|
|
481
|
+
Method: GET
|
|
482
|
+
URI: ${e.built.relativeUrl}
|
|
483
|
+
Headers: { "Authorization": "Bearer <access-token>" }
|
|
484
|
+
|
|
485
|
+
# ── Tips ──
|
|
486
|
+
# • Use parameter aliases (@p1) — recommended for long values, GUIDs, DateTimeOffset.
|
|
487
|
+
# • Bound functions: /<set>(<id>)/Microsoft.Dynamics.CRM.<name>(...).
|
|
488
|
+
`;if(w){const v=e.body??{},f=[];f.push(u("Table name",e.built.entitySet));for(const[T,$]of Object.entries(v))if(T.endsWith("@odata.bind")){const A=T.replace("@odata.bind",""),O=typeof $=="string"?$.match(/\/([^/(]+)\((.*)\)/):null;if(O){const[,P,U]=O;f.push(u(A,`${U} (→ ${P})`))}else f.push(u(A,String($)))}else f.push(u(T,typeof $=="string"?$:JSON.stringify($)));return`# Power Automate — Dataverse connector ⟶ "Add a new row" action
|
|
489
|
+
# Paste each value into the matching dynamic field. The Dataverse connector
|
|
490
|
+
# discovers writable columns from the table you pick and renders them inline.
|
|
491
|
+
|
|
492
|
+
${f.join(`
|
|
493
|
+
`)}
|
|
494
|
+
|
|
495
|
+
# ── Tips ──
|
|
496
|
+
# • Lookup dynamic fields show the related table as a searchable dropdown —
|
|
497
|
+
# the GUIDs above can be pasted directly or used to pick the row.
|
|
498
|
+
# • Multi-select choice: the connector exposes a multi-checkbox UI; values
|
|
499
|
+
# above are comma-separated integers.
|
|
500
|
+
# • Show advanced options to set Caller ID for impersonation or toggle
|
|
501
|
+
# duplicate detection (MSCRM.SuppressDuplicateDetection).
|
|
502
|
+
`}if(y)return`# Power Automate — Dataverse connector ⟶ "Get a row by ID" action
|
|
503
|
+
# Paste each value into the matching field. Leave blank rows alone.
|
|
504
|
+
# (Open the action in your flow → switch each parameter to the value below.)
|
|
505
|
+
|
|
506
|
+
${u("Table name",e.built.entitySet)}
|
|
507
|
+
${u("Row ID",e.built.recordId??"")}
|
|
508
|
+
${u("Select Columns",n)}
|
|
509
|
+
${u("Expand Query",s)}
|
|
510
|
+
|
|
511
|
+
# ── Tip ──
|
|
512
|
+
# • "Get a row by ID" only supports $select and $expand — those are the only
|
|
513
|
+
# OData options Dataverse allows when the URL has the (id) segment.
|
|
514
|
+
# • For impersonation, set the "Caller ID" advanced parameter to the user's GUID.
|
|
515
|
+
`;if(x)return`# Power Automate — Dataverse connector ⟶ "List rows" action (with a Saved/User query)
|
|
516
|
+
# Paste each value into the matching field.
|
|
517
|
+
# When you set Saved Query / User Query, the Dataverse connector IGNORES the OData
|
|
518
|
+
# fields (Select / Filter / Sort / Expand) — those live inside the FetchXml the
|
|
519
|
+
# saved query embeds. Top Count and Pagination still apply.
|
|
520
|
+
|
|
521
|
+
${u("Table name",e.built.entitySet)}
|
|
522
|
+
${i?u("Saved Query",i):u("User Query",p)}
|
|
523
|
+
${u("Top Count",d)}
|
|
524
|
+
${u("Maximum Pagination Size",h)}
|
|
525
|
+
|
|
526
|
+
# Leave these blank — the saved query owns them:
|
|
527
|
+
${u("Select Columns","")}
|
|
528
|
+
${u("Filter Rows","")}
|
|
529
|
+
${u("Sort By","")}
|
|
530
|
+
${u("Expand Query","")}
|
|
531
|
+
${u("Row Count","No")}
|
|
532
|
+
`;const W=c?`
|
|
533
|
+
# ⚠ $apply (groupby/aggregate) — the "List rows" action doesn't expose a field for this.
|
|
534
|
+
# Use the generic HTTP action below to send the request directly, or move to FetchXml.
|
|
535
|
+
`:"";return`# Power Automate — Dataverse connector ⟶ "List rows" action
|
|
536
|
+
# Paste each value into the matching field. Leave blank rows alone.
|
|
537
|
+
# (Open the action in your flow → switch each parameter to the value below.)
|
|
538
|
+
|
|
539
|
+
${u("Table name",e.built.entitySet)}
|
|
540
|
+
${u("Select Columns",n)}
|
|
541
|
+
${u("Filter Rows",o)}
|
|
542
|
+
${u("Sort By",r)}
|
|
543
|
+
${u("Top Count",d)}
|
|
544
|
+
${u("Expand Query",s)}
|
|
545
|
+
${u("Row Count",l?"Yes":"No")}
|
|
546
|
+
${u("Maximum Pagination Size",h)}
|
|
547
|
+
${u("Fetch Xml Query","")}
|
|
548
|
+
${u("Saved Query","")}
|
|
549
|
+
${u("User Query","")}
|
|
550
|
+
${W}
|
|
551
|
+
# ── Notes ──
|
|
552
|
+
# • Column names are LOGICAL names (e.g. "name" not "Account Name").
|
|
553
|
+
# • Filter Rows takes the OData expression — no "$filter=" prefix.
|
|
554
|
+
# • Sort By takes "col asc, col2 desc" — no "$orderby=" prefix.
|
|
555
|
+
# • Expand Query takes the inner clauses in parens, e.g.
|
|
556
|
+
# primarycontactid($select=fullname,emailaddress1)
|
|
557
|
+
# • Maximum Pagination Size enables the connector to follow nextLinks automatically;
|
|
558
|
+
# leave Top Count blank when using pagination to fetch ALL matching rows.
|
|
559
|
+
|
|
560
|
+
# ── Fallback — generic HTTP action ──
|
|
561
|
+
# Use this only when the "List rows" action can't express the request
|
|
562
|
+
# (e.g. $apply, raw nextLink, custom URL params). Replace <access-token> with
|
|
563
|
+
# a token from your OAuth / Service Principal step.
|
|
564
|
+
|
|
565
|
+
Method: ${e.method}
|
|
566
|
+
URI: ${J(e)}
|
|
567
|
+
Headers: { "Authorization": "Bearer <access-token>" }
|
|
568
|
+
`}function Ot(e){if(E(e)){const c=K(e),l=c.headers[c.headers.length-1][1],i=c.headers.slice(0,-1).map(([p,h])=>`http.DefaultRequestHeaders.TryAddWithoutValidation("${L(p)}", "${L(h)}");`).join(`
|
|
569
|
+
`);return`// .NET 8 — HttpClient, one $batch change set (all or nothing)
|
|
570
|
+
//
|
|
571
|
+
${Y(Z(e.multiRequests.length),"//")}
|
|
572
|
+
|
|
573
|
+
using System.Net.Http;
|
|
574
|
+
using System.Net.Http.Headers;
|
|
575
|
+
|
|
576
|
+
var http = new HttpClient { BaseAddress = new Uri("https://${j.host}/") };
|
|
577
|
+
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "<access-token>");
|
|
578
|
+
${i}
|
|
579
|
+
|
|
580
|
+
var body = string.Join("\\r\\n", new[]
|
|
581
|
+
{
|
|
582
|
+
${c.lines.map(p=>` "${L(p)}",`).join(`
|
|
583
|
+
`)}
|
|
584
|
+
}) + "\\r\\n";
|
|
585
|
+
var content = new StringContent(body);
|
|
586
|
+
content.Headers.ContentType = MediaTypeHeaderValue.Parse("${L(l)}");
|
|
587
|
+
|
|
588
|
+
var res = await http.PostAsync("${L(c.url.replace(`https://${j.host}/`,""))}", content);
|
|
589
|
+
// The response is multipart/mixed: a result per request when the change set
|
|
590
|
+
// succeeds, or the failing request's error when it's rolled back.
|
|
591
|
+
Console.WriteLine($"{(int)res.StatusCode} {res.ReasonPhrase}");
|
|
592
|
+
Console.WriteLine(await res.Content.ReadAsStringAsync());
|
|
593
|
+
`}if(e.multiRequests&&e.multiRequests.length>1){const c=e.multiRequests,l=Object.entries(e.headers).filter(([,m])=>m).filter(([m])=>!z(m)).map(([m,u])=>`http.DefaultRequestHeaders.TryAddWithoutValidation("${L(m)}", "${L(u)}");`).join(`
|
|
594
|
+
`),i=m=>`@"${Re(m)}"`,p=c.map(m=>{const u=Q(m),x=m.description?` // ${m.description}
|
|
595
|
+
`:"",y=m.rawBody?i(m.rawBody):m.body?i(JSON.stringify(m.body)):"null",w=Object.entries(m.headers??{}).map(([b,R])=>`(${i(b)}, ${i(R)})`).join(", ");return`${x} (HttpMethod.${ke(m.method)}, ${i(u)}, ${y}, new (string, string)[] { ${w} }),`}).join(`
|
|
596
|
+
`);return`// .NET 8 — HttpClient (multi-request)
|
|
597
|
+
// One call per request, sent in order.${c.some(m=>m.rawBody)?`
|
|
598
|
+
// Placeholder bodies like <chunk bytes> stand for the binary content — send the
|
|
599
|
+
// real bytes with ByteArrayContent instead of the placeholder string.`:""}
|
|
600
|
+
|
|
601
|
+
using System.Net.Http;
|
|
602
|
+
using System.Net.Http.Headers;
|
|
603
|
+
|
|
604
|
+
var http = new HttpClient { BaseAddress = new Uri("https://${j.host}/") };
|
|
605
|
+
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "<access-token>");
|
|
606
|
+
${l}
|
|
607
|
+
|
|
608
|
+
var requests = new (HttpMethod Method, string Url, string? Content, (string Name, string Value)[] Headers)[]
|
|
609
|
+
{
|
|
610
|
+
${p}
|
|
611
|
+
};
|
|
612
|
+
|
|
613
|
+
int ok = 0;
|
|
614
|
+
foreach (var r in requests)
|
|
615
|
+
{
|
|
616
|
+
var req = new HttpRequestMessage(r.Method, r.Url);
|
|
617
|
+
if (r.Content is not null)
|
|
618
|
+
req.Content = new StringContent(r.Content, System.Text.Encoding.UTF8, "application/json");
|
|
619
|
+
foreach (var (name, value) in r.Headers)
|
|
620
|
+
{
|
|
621
|
+
// Content-Type / Content-Range / Content-Length belong on the content.
|
|
622
|
+
if (req.Headers.TryAddWithoutValidation(name, value)) continue;
|
|
623
|
+
req.Content?.Headers.Remove(name);
|
|
624
|
+
req.Content?.Headers.TryAddWithoutValidation(name, value);
|
|
625
|
+
}
|
|
626
|
+
using var res = await http.SendAsync(req);
|
|
627
|
+
if (res.IsSuccessStatusCode) ok++;
|
|
628
|
+
else Console.WriteLine($"{r.Method} {r.Url} → {(int)res.StatusCode} {res.ReasonPhrase}");
|
|
629
|
+
}
|
|
630
|
+
Console.WriteLine($"{ok}/{requests.Length} requests succeeded");
|
|
631
|
+
`}const t=H(e),n=!F(e.method),o=Object.entries(e.headers).filter(([,c])=>c).filter(([c])=>!z(c)),r=o.filter(([c])=>!Se.has(c.toLowerCase())).map(([c,l])=>`http.DefaultRequestHeaders.TryAddWithoutValidation("${L(c)}", "${L(l)}");`).join(`
|
|
632
|
+
`),s=n?o.filter(([c])=>Se.has(c.toLowerCase())).map(([c,l])=>`req.Content.Headers.Remove("${L(c)}");
|
|
633
|
+
req.Content.Headers.TryAddWithoutValidation("${L(c)}", "${L(l)}");
|
|
634
|
+
`).join(""):"",d=n?e.rawBody?`// ${e.rawBody}: the file content.
|
|
635
|
+
req.Content = new ByteArrayContent(File.ReadAllBytes("<path-to-file>"));
|
|
636
|
+
`:`req.Content = new StringContent(@"${Re(JSON.stringify(e.body??{},null,2))}", System.Text.Encoding.UTF8, "application/json");
|
|
637
|
+
`:"";return`// .NET 8 — HttpClient. For production use Microsoft.PowerPlatform.Dataverse.Client
|
|
638
|
+
// (ServiceClient) instead — it handles auth, retries, and OData parsing for you.
|
|
639
|
+
|
|
640
|
+
using System.Net.Http;
|
|
641
|
+
using System.Net.Http.Headers;
|
|
642
|
+
|
|
643
|
+
var http = new HttpClient { BaseAddress = new Uri("https://${j.host}/") };
|
|
644
|
+
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "<access-token>");
|
|
645
|
+
${r}
|
|
646
|
+
|
|
647
|
+
var req = new HttpRequestMessage(HttpMethod.${ke(e.method)}, "${t}");
|
|
648
|
+
${d}${s}
|
|
649
|
+
using var res = await http.SendAsync(req);
|
|
650
|
+
res.EnsureSuccessStatusCode();
|
|
651
|
+
var json = await res.Content.ReadAsStringAsync();
|
|
652
|
+
Console.WriteLine(json);
|
|
653
|
+
`}function L(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t").replace(/[\u0000-\u001f]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}function Re(e){return e.replace(/"/g,'""')}function ke(e){switch(e.toUpperCase()){case"GET":return"Get";case"POST":return"Post";case"PATCH":return"Patch";case"PUT":return"Put";case"DELETE":return"Delete";default:return"Get"}}function Mt(e){if(e.multiRequests&&e.multiRequests.length>1)return Et(e);const t=H(e),n=!F(e.method),o=Ie(I(e.headers)," "),r=n?e.rawBody?`# ${Be(e.rawBody)}: the file content.
|
|
654
|
+
with open("<path-to-file>", "rb") as f:
|
|
655
|
+
file_bytes = f.read()
|
|
656
|
+
|
|
657
|
+
`:`payload = ${oe(e.body??{},"")}
|
|
658
|
+
|
|
659
|
+
`:"",s=n?e.rawBody?`,
|
|
660
|
+
data=file_bytes`:`,
|
|
661
|
+
json=payload`:"";return`# Dataverse Web API — Python (requests)
|
|
662
|
+
# pip install requests. Replace <access-token> with a bearer token for
|
|
663
|
+
# https://${j.host} (msal or azure-identity can get one).
|
|
664
|
+
|
|
665
|
+
import requests
|
|
666
|
+
|
|
667
|
+
ACCESS_TOKEN = "<access-token>"
|
|
668
|
+
|
|
669
|
+
url = ${D(t)}
|
|
670
|
+
headers = {
|
|
671
|
+
"Authorization": "Bearer " + ACCESS_TOKEN,
|
|
672
|
+
${o}}
|
|
673
|
+
|
|
674
|
+
${r}res = requests.request(
|
|
675
|
+
${D(e.method)},
|
|
676
|
+
url,
|
|
677
|
+
headers=headers${s},
|
|
678
|
+
timeout=60,
|
|
679
|
+
)
|
|
680
|
+
|
|
681
|
+
if not res.ok:
|
|
682
|
+
try:
|
|
683
|
+
message = res.json()["error"]["message"]
|
|
684
|
+
except (ValueError, KeyError, TypeError):
|
|
685
|
+
message = res.reason
|
|
686
|
+
raise SystemExit(f"Dataverse {res.status_code}: {message}")
|
|
687
|
+
|
|
688
|
+
# 204 No Content (e.g. Delete) doesn't carry a body
|
|
689
|
+
if res.status_code == 204 or not res.content:
|
|
690
|
+
print("Status:", res.status_code)
|
|
691
|
+
elif "json" in res.headers.get("Content-Type", ""):
|
|
692
|
+
data = res.json()
|
|
693
|
+
print(data)
|
|
694
|
+
if isinstance(data, dict) and isinstance(data.get("value"), list):
|
|
695
|
+
print(f"Returned {len(data['value'])} record(s)")
|
|
696
|
+
if "@odata.count" in data:
|
|
697
|
+
print("@odata.count:", data["@odata.count"])
|
|
698
|
+
if "@odata.nextLink" in data:
|
|
699
|
+
print("nextLink:", data["@odata.nextLink"])
|
|
700
|
+
elif res.headers.get("Content-Type", "").startswith("text/"):
|
|
701
|
+
print(res.text)
|
|
702
|
+
else:
|
|
703
|
+
print(f"{len(res.content)} bytes ({res.headers.get('Content-Type')})")
|
|
704
|
+
`}function Ut(e){const t=K(e);return`# Dataverse Web API — Python (requests), one $batch change set (all or nothing)
|
|
705
|
+
#
|
|
706
|
+
${Y(Z(e.multiRequests.length),"#")}
|
|
707
|
+
# pip install requests and replace <access-token> with a bearer token.
|
|
708
|
+
|
|
709
|
+
import requests
|
|
710
|
+
|
|
711
|
+
ACCESS_TOKEN = "<access-token>"
|
|
712
|
+
|
|
713
|
+
body = "\\r\\n".join([
|
|
714
|
+
${t.lines.map(n=>` ${D(n)},`).join(`
|
|
715
|
+
`)}
|
|
716
|
+
]) + "\\r\\n"
|
|
717
|
+
|
|
718
|
+
res = requests.post(
|
|
719
|
+
${D(t.url)},
|
|
720
|
+
headers={
|
|
721
|
+
"Authorization": "Bearer " + ACCESS_TOKEN,
|
|
722
|
+
${t.headers.map(([n,o])=>` ${D(n)}: ${D(o)},`).join(`
|
|
723
|
+
`)}
|
|
724
|
+
},
|
|
725
|
+
data=body.encode("utf-8"),
|
|
726
|
+
timeout=120,
|
|
727
|
+
)
|
|
728
|
+
|
|
729
|
+
# The response is multipart/mixed: a result per request when the change set
|
|
730
|
+
# succeeds, or the failing request's error when it's rolled back.
|
|
731
|
+
print(res.status_code, res.headers.get("Content-Type"))
|
|
732
|
+
print(res.text)
|
|
733
|
+
`}function Et(e){if(E(e))return Ut(e);const t=e.multiRequests??[],n=Ie(I(e.headers)," "),o=t.map(r=>{const s=[`"method": ${D(r.method)}`,`"url": ${D(Q(r))}`],d=Object.entries(r.headers??{}).filter(([,i])=>i);d.length>0&&s.push(`"headers": {${d.map(([i,p])=>`${D(i)}: ${D(p)}`).join(", ")}}`),r.rawBody?s.push(`"data": ${D(r.rawBody)}`):r.body&&s.push(`"json": ${oe(r.body," ")}`);const c=r.description?` # ${Be(r.description)}
|
|
734
|
+
`:"",l=r.rawBody?" # replace with the bytes":"";return`${c} {${s.join(", ")}},${l}`}).join(`
|
|
735
|
+
`);return`# Dataverse Web API — Python (requests), multi-request
|
|
736
|
+
# One call per request, sent in order. pip install requests and replace
|
|
737
|
+
# <access-token> with a bearer token for https://${j.host}.
|
|
738
|
+
|
|
739
|
+
import requests
|
|
740
|
+
|
|
741
|
+
ACCESS_TOKEN = "<access-token>"
|
|
742
|
+
|
|
743
|
+
calls = [
|
|
744
|
+
${o}
|
|
745
|
+
]
|
|
746
|
+
|
|
747
|
+
session = requests.Session()
|
|
748
|
+
session.headers.update({
|
|
749
|
+
"Authorization": "Bearer " + ACCESS_TOKEN,
|
|
750
|
+
${n}})
|
|
751
|
+
|
|
752
|
+
ok = 0
|
|
753
|
+
for call in calls:
|
|
754
|
+
res = session.request(
|
|
755
|
+
call["method"],
|
|
756
|
+
call["url"],
|
|
757
|
+
headers=call.get("headers"),
|
|
758
|
+
json=call.get("json"),
|
|
759
|
+
data=call.get("data"),
|
|
760
|
+
timeout=60,
|
|
761
|
+
)
|
|
762
|
+
if res.ok:
|
|
763
|
+
ok += 1
|
|
764
|
+
else:
|
|
765
|
+
print(f"{call['method']} {call['url']} -> {res.status_code} {res.reason}")
|
|
766
|
+
print(f"{ok}/{len(calls)} requests succeeded")
|
|
767
|
+
`}function D(e){return JSON.stringify(e)}function Be(e){return e.replace(/[\u0000-\u001f\u007f\u2028\u2029]+/g," ").replace(/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g,"�")}function Ie(e,t){return Object.entries(e).filter(([,n])=>n).map(([n,o])=>`${t}${D(n)}: ${D(o)},
|
|
768
|
+
`).join("")}function oe(e,t){if(e==null)return"None";if(typeof e=="boolean")return e?"True":"False";if(typeof e=="number")return Number.isFinite(e)?String(e):"None";if(typeof e=="string")return D(e);const n=t+" ";if(Array.isArray(e))return e.length===0?"[]":`[
|
|
769
|
+
${e.map(o=>`${n}${oe(o,n)},`).join(`
|
|
770
|
+
`)}
|
|
771
|
+
${t}]`;if(typeof e=="object"){const o=Object.entries(e).filter(([,r])=>r!==void 0);return o.length===0?"{}":`{
|
|
772
|
+
${o.map(([r,s])=>`${n}${D(r)}: ${oe(s,n)},`).join(`
|
|
773
|
+
`)}
|
|
774
|
+
${t}}`}return D(String(e))}function B(e){return`'${e.replace(/'/g,"'\\''")}'`}function C(e){return`'${e.replace(/'/g,"''")}'`}function Bt(e){if(E(e)){const l=K(e),i=l.headers[l.headers.length-1][1];return`# PowerShell — Invoke-RestMethod, one $batch change set (all or nothing)
|
|
775
|
+
#
|
|
776
|
+
${Y(Z(e.multiRequests.length),"#")}
|
|
777
|
+
|
|
778
|
+
$token = "<access-token>"
|
|
779
|
+
$headers = @{
|
|
780
|
+
Authorization = "Bearer $token"
|
|
781
|
+
${l.headers.slice(0,-1).map(([p,h])=>` ${C(p)} = ${C(h)}`).join(`
|
|
782
|
+
`)}
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
$body = (@(
|
|
786
|
+
${l.lines.map(p=>` ${C(p)}`).join(`
|
|
787
|
+
`)}
|
|
788
|
+
) -join "\`r\`n") + "\`r\`n"
|
|
789
|
+
|
|
790
|
+
# The response is multipart/mixed: a result per request when the change set
|
|
791
|
+
# succeeds, or the failing request's error when it's rolled back.
|
|
792
|
+
Invoke-RestMethod -Method POST -Uri ${C(l.url)} -Headers $headers \`
|
|
793
|
+
-ContentType ${C(i)} -Body $body
|
|
794
|
+
`}if(e.multiRequests&&e.multiRequests.length>1){const l=e.multiRequests,i=Object.entries(e.headers).filter(([,h])=>h).filter(([h])=>!z(h)).map(([h,m])=>` ${C(h)} = ${C(m)}`).join(`
|
|
795
|
+
`),p=l.map(h=>{const m=Q(h),u=Object.entries(h.headers??{}),x=u.find(([S])=>S.toLowerCase()==="content-type")?.[1],y=u.filter(([S])=>S.toLowerCase()!=="content-type"),w=y.length>0?"$h":"$headers",b=y.length>0?`$h = $headers.Clone()
|
|
796
|
+
${y.map(([S,M])=>`$h[${C(S)}] = ${C(M)}`).join(`
|
|
797
|
+
`)}
|
|
798
|
+
`:"",R=h.rawBody?` -ContentType ${C(x??"application/octet-stream")} -InFile '<path-to-file>' # ${h.rawBody}`:h.body?` -ContentType ${C(x??"application/json")} -Body ${C(JSON.stringify(h.body))}`:"";return`${h.description?`# ${h.description}
|
|
799
|
+
`:""}${b}Invoke-RestMethod -Method ${h.method} -Uri ${C(m)} -Headers ${w}${R}`}).join(`
|
|
800
|
+
|
|
801
|
+
`);return`# PowerShell — Invoke-RestMethod (multi-request)
|
|
802
|
+
$token = "<access-token>"
|
|
803
|
+
$headers = @{
|
|
804
|
+
Authorization = "Bearer $token"
|
|
805
|
+
${i}
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
${p}
|
|
809
|
+
`}const t=H(e),n=!F(e.method),o=Object.entries(e.headers).filter(([,l])=>l).filter(([l])=>!z(l)),r=o.find(([l])=>l.toLowerCase()==="content-type")?.[1],s=o.filter(([l])=>l.toLowerCase()!=="content-type").map(([l,i])=>` ${C(l)} = ${C(i)}`).join(`
|
|
810
|
+
`),d=n&&!e.rawBody?`$body = @'
|
|
811
|
+
${JSON.stringify(e.body??{},null,2)}
|
|
812
|
+
'@
|
|
813
|
+
|
|
814
|
+
`:"",c=n?e.rawBody?` \`
|
|
815
|
+
-ContentType ${C(r??"application/octet-stream")} \`
|
|
816
|
+
-InFile '<path-to-file>' # ${e.rawBody}`:` \`
|
|
817
|
+
-ContentType ${C(r??"application/json")} \`
|
|
818
|
+
-Body $body`:"";return`# PowerShell — Invoke-RestMethod
|
|
819
|
+
# Replace <access-token> with a real bearer token (Get-AzAccessToken / msal-token).
|
|
820
|
+
|
|
821
|
+
$token = "<access-token>"
|
|
822
|
+
$headers = @{
|
|
823
|
+
Authorization = "Bearer $token"
|
|
824
|
+
${s}
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
${d}$response = Invoke-RestMethod \`
|
|
828
|
+
-Method ${e.method} \`
|
|
829
|
+
-Uri ${C(t)} \`
|
|
830
|
+
-Headers $headers${c}
|
|
831
|
+
|
|
832
|
+
$response | ConvertTo-Json -Depth 8
|
|
833
|
+
`}function It(e){if(E(e)){const s=K(e);return`# cURL — one $batch change set (all or nothing)
|
|
834
|
+
#
|
|
835
|
+
${Y(Z(e.multiRequests.length),"#")}
|
|
836
|
+
# printf writes each line with its CRLF; curl reads the body from stdin.
|
|
837
|
+
|
|
838
|
+
printf '%s\\r\\n' \\
|
|
839
|
+
${s.lines.map(d=>` ${B(d)}`).join(` \\
|
|
840
|
+
`)} |
|
|
841
|
+
curl -X POST --globoff ${B(s.url)} \\
|
|
842
|
+
-H "Authorization: Bearer <access-token>" \\
|
|
843
|
+
${s.headers.map(([d,c])=>` -H ${B(`${d}: ${c}`)}`).join(` \\
|
|
844
|
+
`)} \\
|
|
845
|
+
--data-binary @-
|
|
846
|
+
`}if(e.multiRequests&&e.multiRequests.length>1){const s=e.multiRequests,d=I(e.headers),c=Object.entries(d).filter(([,i])=>i).map(([i,p])=>` -H ${B(`${i}: ${p}`)}`).join(` \\
|
|
847
|
+
`);return`# cURL — multi-request (Associate / Disassociate over a collection)
|
|
848
|
+
# Each association is a separate request per the docs.
|
|
849
|
+
|
|
850
|
+
${s.map(i=>{const p=Q(i),h=i.description?`# ${i.description}
|
|
851
|
+
`:"",m=i.rawBody?` \\
|
|
852
|
+
--data-binary '@<path-to-file>' # ${i.rawBody}`:i.body?` \\
|
|
853
|
+
--data-raw '${JSON.stringify(i.body).replace(/'/g,"'\\''")}'`:"",u=Object.entries(i.headers??{}).map(([x,y])=>` \\
|
|
854
|
+
-H ${B(`${x}: ${y}`)}`).join("");return`${h}curl -X ${i.method} --globoff ${B(p)} \\
|
|
855
|
+
-H "Authorization: Bearer <access-token>"${c?` \\
|
|
856
|
+
${c}`:""}${u}${m}`}).join(`
|
|
857
|
+
|
|
858
|
+
`)}
|
|
859
|
+
`}const t=H(e),n=I(e.headers),o=Object.entries(n).filter(([,s])=>s).map(([s,d])=>` -H ${B(`${s}: ${d}`)}`).join(` \\
|
|
860
|
+
`),r=F(e.method)?"":e.rawBody?` \\
|
|
861
|
+
--data-binary '@<path-to-file>' # ${e.rawBody}`:` \\
|
|
862
|
+
--data-raw '${JSON.stringify(e.body??{}).replace(/'/g,"'\\''")}'`;return`# cURL — shell context
|
|
863
|
+
# The URL is single-quoted so the shell doesn't expand $select / $filter / $ref
|
|
864
|
+
# --globoff stops curl's own [] {} URL globbing (OData literals can contain them)
|
|
865
|
+
# --compressed asks the server for gzipped responses
|
|
866
|
+
|
|
867
|
+
curl -X ${e.method} \\
|
|
868
|
+
--globoff \\
|
|
869
|
+
--compressed \\
|
|
870
|
+
${B(t)} \\
|
|
871
|
+
-H "Authorization: Bearer <access-token>" \\
|
|
872
|
+
${o}${r}
|
|
873
|
+
`}function Ft(e){if(e.multiRequests&&e.multiRequests.length>1){const n=E(e)?{mode:"change-set",method:"POST",url:`https://${j.host}${j.apiBase}/$batch`}:{mode:"multi-request"};return JSON.stringify({...n,headers:le(e.headers),requests:e.multiRequests.map(o=>({method:o.method,url:Q(o),relativeUrl:o.relativeUrl,headers:o.headers&&le(o.headers),body:o.rawBody??o.body,description:o.description}))},null,2)}const t={method:e.method,url:H(e),relativeUrl:e.built.relativeUrl,entityLogical:e.built.entityLogical,entitySet:e.built.entitySet,headers:le(e.headers)};return!F(e.method)&&(e.rawBody||e.body)&&(t.body=e.rawBody??e.body),JSON.stringify(t,null,2)}const Ht=Ke({row:{display:"grid",gridTemplateColumns:"180px minmax(0, 1fr) auto",gap:"12px",alignItems:"start",marginBottom:"14px"},rowLabel:{paddingTop:"6px",fontWeight:500,color:k.colorNeutralForeground1},rowLabelEmpty:{color:k.colorNeutralForeground3},hint:{fontSize:"10px",color:k.colorNeutralForeground3,marginTop:"4px",display:"block"},copyBtn:{minWidth:"90px"},fallbackCard:{marginTop:"20px",padding:"14px 16px",borderRadius:k.borderRadiusMedium,border:`1px solid ${k.colorNeutralStroke2}`,backgroundColor:k.colorNeutralBackground2}});function Wt({spec:e}){const t=Ht(),n=e.fields.filter(r=>r.value).length,o=e.fields.filter(r=>r.value).map(r=>`${r.label.padEnd(28)} ${r.value}`).join(`
|
|
874
|
+
`);return a.jsxs("div",{children:[a.jsxs("div",{style:{marginBottom:16,display:"flex",alignItems:"baseline",gap:12,flexWrap:"wrap"},children:[a.jsx(Qe,{style:{color:k.colorBrandForeground1,marginTop:6}}),a.jsx(pt,{style:{fontFamily:k.fontFamilyBase},children:e.actionName}),a.jsxs(G,{style:{color:k.colorNeutralForeground3},children:["· ",e.connector]}),a.jsx("span",{style:{flexGrow:1}}),a.jsxs(Ae,{appearance:"ghost",children:[n," of ",e.fields.length," populated"]}),a.jsx(X,{content:"Copy every populated field as one block",relationship:"description",children:a.jsx(_,{size:"small",appearance:"outline",icon:a.jsx(se,{}),onClick:()=>{re(o,"the fields",{shown:!1})},children:"Copy all"})})]}),e.banner&&a.jsx(de,{layout:"multiline",intent:"info",style:{marginBottom:14},children:a.jsx(pe,{children:e.banner})}),a.jsx(xe,{style:{display:"block",marginBottom:10,color:k.colorNeutralForeground2},children:"Fields"}),a.jsx("div",{children:e.fields.map(r=>a.jsx(ue,{field:r,styles:t},r.label))}),e.notes&&e.notes.length>0&&a.jsx(de,{layout:"multiline",intent:"info",style:{marginTop:14},children:a.jsxs(pe,{children:[a.jsx(Ve,{children:"Notes"}),a.jsx("ul",{style:{margin:"6px 0 0",paddingLeft:18},children:e.notes.map((r,s)=>a.jsx("li",{children:r},s))})]})}),e.httpFallback&&a.jsxs("div",{className:t.fallbackCard,children:[a.jsx(xe,{style:{display:"block",marginBottom:4},children:"HTTP action — fallback"}),a.jsx(G,{style:{display:"block",marginBottom:12,color:k.colorNeutralForeground3},children:e.httpFallback.note}),a.jsx(ue,{field:{label:"Method",value:e.httpFallback.method},styles:t}),a.jsx(ue,{field:{label:"URI",value:e.httpFallback.uri,multiline:!0},styles:t})]})]})}function ue({field:e,styles:t}){const[n,o]=N.useState(!1),r=()=>{e.value&&re(e.value,`the ${e.label} value`,{toastOnSuccess:!1}).then(s=>{s&&(o(!0),setTimeout(()=>o(!1),1400))})};return a.jsxs("div",{className:t.row,children:[a.jsx(Ze,{className:Ye(t.rowLabel,!e.value&&t.rowLabelEmpty),children:e.label}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",minWidth:0},children:[e.multiline?a.jsx(et,{"aria-label":e.label,value:e.value,readOnly:!0,rows:Math.min(4,Math.max(1,Math.ceil(e.value.length/80))),appearance:"filled-lighter",style:{width:"100%",fontFamily:k.fontFamilyMonospace,fontSize:12}}):a.jsx(tt,{"aria-label":e.label,value:e.value,readOnly:!0,appearance:"filled-lighter",style:{width:"100%",fontFamily:k.fontFamilyMonospace,fontSize:12}}),e.hint&&a.jsx(G,{className:t.hint,children:e.hint})]}),a.jsx(X,{content:e.value?"Copy this value":"Empty — nothing to copy",relationship:"label",children:a.jsx(_,{size:"medium",appearance:e.value?"outline":"subtle",disabled:!e.value,icon:n?a.jsx(nt,{style:{color:k.colorPaletteGreenForeground1}}):a.jsx(se,{}),onClick:r,className:t.copyBtn,children:n?"Copied":"Copy"})})]})}const ve=["fetch","xrm","xrm-batch","xhr","powerautomate","csharp","python","powershell","curl","json","openapi"],zt=ve.filter(e=>e!=="powerautomate"&&e!=="openapi");function Gt({themeMode:e,inputs:t,group:n="read"}){const[o,r]=N.useState("code"),[s,d]=N.useState("fetch"),[c,l]=N.useState(""),[i,p]=N.useState("fetch"),[h,m]=N.useState(""),[u,x]=N.useState(!1);N.useEffect(()=>{l(ce(s,t))},[s,t]),N.useEffect(()=>{m(ce(i,t)),x(!1)},[i]);const y={lineNumbers:"on",renderLineHighlight:"line",minimap:{enabled:!1},scrollBeyondLastLine:!1,fontFamily:"Cascadia Mono, Consolas, monospace",fontSize:13,tabSize:2,insertSpaces:!0,wordWrap:"on",automaticLayout:!0,padding:{top:12,bottom:12},formatOnPaste:!0,formatOnType:!0,bracketPairColorization:{enabled:!0},guides:{bracketPairs:!0,indentation:!0},smoothScrolling:!0};return a.jsxs("div",{style:{display:"flex",flexDirection:"column",minHeight:0,height:"100%"},children:[a.jsx(ot,{icon:Te,title:"Generated code",sub:o==="code"?`${ve.length} formats — read-only, regenerated on every builder change.`:"Writable playground — edit the starter and copy it out.",group:n}),a.jsxs(be,{selectedValue:o,onTabSelect:(w,b)=>r(b.value),size:"small",appearance:"subtle",style:{marginBottom:10},children:[a.jsx(ee,{value:"code",icon:a.jsx(Te,{}),children:"Code"}),a.jsx(ee,{value:"editor",icon:a.jsx(rt,{}),children:"Editor"})]}),o==="code"?a.jsx(Xt,{fmt:s,setFmt:d,code:c,inputs:t,themeMode:e,monacoOptions:y}):a.jsx(_t,{fmt:i,setFmt:w=>{p(w)},code:h,setCode:w=>{m(w),x(!0)},onReset:()=>{m(ce(i,t)),x(!1)},dirty:u,themeMode:e,monacoOptions:{...y,readOnly:!1}})]})}function Xt({fmt:e,setFmt:t,code:n,inputs:o,themeMode:r,monacoOptions:s}){const d=e==="powerautomate",c=d?Lt(o):null;return a.jsxs("div",{style:{display:"flex",flexDirection:"column",minHeight:0,flexGrow:1},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10,flexWrap:"wrap"},children:[a.jsx(be,{selectedValue:e,onTabSelect:(l,i)=>t(i.value),appearance:"subtle",size:"small",children:ve.map(l=>a.jsx(ee,{value:l,children:qe[l]},l))}),a.jsx("span",{style:{flexGrow:1}}),!d&&a.jsxs(a.Fragment,{children:[a.jsxs(G,{style:{color:k.colorNeutralForeground3,fontFamily:k.fontFamilyMonospace},children:[n.length.toLocaleString()," chars ·"," ",Math.round(new Blob([n]).size/1024*10)/10," KB"]}),a.jsx(X,{content:"Copy code",relationship:"description",children:a.jsx(_,{icon:a.jsx(se,{}),appearance:"subtle",size:"small",onClick:()=>{re(n,"the code")},children:"Copy"})}),e==="openapi"&&a.jsx(X,{content:"Save the OpenAPI document as a JSON file",relationship:"description",children:a.jsx(_,{icon:a.jsx(at,{}),appearance:"subtle",size:"small",onClick:()=>{st(`${o.built.entitySet||"request"}.openapi.json`,n,[{name:"OpenAPI (JSON)",extensions:["json"]}]).catch(()=>{})},children:"Save"})})]})]}),d&&c?a.jsx("div",{style:{flexGrow:1,overflowY:"auto",paddingRight:4},children:a.jsx(Wt,{spec:c})}):a.jsxs(a.Fragment,{children:[a.jsx(Fe,{children:a.jsx(Ce,{height:"100%",language:De[e],value:n,theme:r==="dark"?"vs-dark":"light",options:{...s,readOnly:!0,domReadOnly:!0}})}),a.jsxs(G,{style:{marginTop:8,color:k.colorNeutralForeground3},children:["Tip: replace ",a.jsx("code",{children:"<access-token>"})," with a real bearer token (e.g. from"," ",a.jsx("code",{children:"Get-AzAccessToken"}),", MSAL, or the connector's auth step) before running."]})]})]})}function _t({fmt:e,setFmt:t,code:n,setCode:o,onReset:r,dirty:s,themeMode:d,monacoOptions:c}){const l=N.useRef(null),i=p=>{l.current=p};return a.jsxs("div",{style:{display:"flex",flexDirection:"column",minHeight:0,flexGrow:1},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:10,flexWrap:"wrap"},children:[a.jsx(G,{style:{color:k.colorNeutralForeground3,marginRight:4},children:"Starter:"}),a.jsx(be,{selectedValue:e,onTabSelect:(p,h)=>t(h.value),appearance:"subtle",size:"small",children:zt.map(p=>a.jsx(ee,{value:p,children:qe[p]},p))}),a.jsx("span",{style:{flexGrow:1}}),s&&a.jsx(Ae,{size:"small",appearance:"ghost",color:"warning",children:"edited"}),a.jsx(X,{content:"Reset to the freshly-generated starter for this format",relationship:"description",children:a.jsx(_,{icon:a.jsx(it,{}),appearance:"subtle",size:"small",onClick:r,children:"Reset"})}),a.jsx(X,{content:"Copy current editor contents",relationship:"description",children:a.jsx(_,{icon:a.jsx(se,{}),appearance:"subtle",size:"small",onClick:()=>{re(n,"the code")},children:"Copy"})})]}),a.jsx(de,{layout:"multiline",intent:"info",style:{marginBottom:10},children:a.jsxs(pe,{children:[a.jsx("strong",{children:"Playground."})," Edit the starter however you like and copy it out. Edits here aren't run: ",a.jsx("strong",{children:"Execute"})," sends the request the builder shows. Reset re-generates the starter from the current builder state."]})}),a.jsx("div",{style:{display:"grid",gridTemplateRows:"1fr",gap:10,minHeight:0,flexGrow:1},children:a.jsx(Fe,{children:a.jsx(Ce,{height:"100%",language:De[e],value:n,onChange:p=>o(p??""),theme:d==="dark"?"vs-dark":"light",options:c,onMount:i})})})]})}function Fe({children:e}){return a.jsx("div",{style:{flexGrow:1,border:`1px solid ${k.colorNeutralStroke2}`,borderRadius:k.borderRadiusMedium,overflow:"hidden",minHeight:320},children:e})}const Vt=Object.freeze(Object.defineProperty({__proto__:null,CodeView:Gt},Symbol.toStringTag,{value:"Module"}));export{Gt as C,Ce as M,Vt as a};
|