@ppdostudio/ppdo-cli 1.0.0-beta.0 → 1.0.0-beta.2
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 +96 -54
- package/LICENSE +114 -114
- package/README.md +381 -331
- package/THIRD-PARTY-NOTICES +1 -0
- package/dist/bin.js +2 -2
- package/dist/chunks/{ado-NLCWVIVQ.js → ado-OTSVKTOE.js} +6 -6
- package/dist/chunks/{api-YKKPVMTX.js → api-IRGGH5DJ.js} +1 -1
- package/dist/chunks/{api-T5SWGOFX.js → api-TZJXGWWQ.js} +1 -1
- package/dist/chunks/auth-7CDWOYJE.js +6 -0
- package/dist/chunks/azCli-UEDQHRLP.js +2 -0
- package/dist/chunks/batch-LKWCBKAB.js +2 -0
- package/dist/chunks/{build-XDCWMEEL.js → build-PBPXO3GJ.js} +3 -3
- package/dist/chunks/bulk-NY5XX752.js +2 -0
- package/dist/chunks/chunk-2IUXH534.js +2 -0
- package/dist/chunks/chunk-3L7657R3.js +5 -0
- package/dist/chunks/{chunk-5KZDCOFA.js → chunk-46KBBWEH.js} +1 -1
- package/dist/chunks/chunk-6NBCHK6X.js +2 -0
- package/dist/chunks/chunk-6VLFO5FJ.js +7 -0
- package/dist/chunks/chunk-B3TJ3RJN.js +2 -0
- package/dist/chunks/chunk-BG2OIOSN.js +2 -0
- package/dist/chunks/chunk-BWOEIEFY.js +6 -0
- package/dist/chunks/chunk-ELSYHAYC.js +2 -0
- package/dist/chunks/chunk-FOEBNCSD.js +3 -0
- package/dist/chunks/{chunk-XL7E7LX5.js → chunk-GLU4X7PT.js} +2 -2
- package/dist/chunks/chunk-GQLXEQVQ.js +4 -0
- package/dist/chunks/chunk-GY6BUIDP.js +2 -0
- package/dist/chunks/chunk-H4OY4EFC.js +3 -0
- package/dist/chunks/chunk-HJQJ77F2.js +3 -0
- package/dist/chunks/chunk-I7MHI5CU.js +151 -0
- package/dist/chunks/chunk-ITP35SAY.js +2 -0
- package/dist/chunks/{chunk-J777TCSE.js → chunk-J67P6QFC.js} +2 -2
- package/dist/chunks/{chunk-NNHEYYF5.js → chunk-KBZI5UDL.js} +1 -1
- package/dist/chunks/chunk-LB7WNZVK.js +5 -0
- package/dist/chunks/chunk-MBNUMAAZ.js +2 -0
- package/dist/chunks/chunk-MNGA7IHQ.js +4 -0
- package/dist/chunks/chunk-P4IFCLVF.js +2 -0
- package/dist/chunks/chunk-Q2RD4TRK.js +2 -0
- package/dist/chunks/chunk-S6NK6GX2.js +5 -0
- package/dist/chunks/chunk-SWXCK5C2.js +2 -0
- package/dist/chunks/chunk-T4IH34D7.js +2 -0
- package/dist/chunks/{chunk-HLE2WURE.js → chunk-TADCW6ZI.js} +1 -1
- package/dist/chunks/{chunk-UYDBLVAM.js → chunk-TCLZ4XM6.js} +1 -1
- package/dist/chunks/chunk-VC7ADQ6E.js +2 -0
- package/dist/chunks/{chunk-GT52BRS2.js → chunk-XUHLW6B2.js} +18 -18
- package/dist/chunks/{commands-GHYN6GZT.js → commands-EOUU353W.js} +1 -1
- package/dist/chunks/component-JCIJQELN.js +2 -0
- package/dist/chunks/config-WV3NZGTI.js +2 -0
- package/dist/chunks/connection-L6CUFUPJ.js +2 -0
- package/dist/chunks/connref-IT6K56UT.js +2 -0
- package/dist/chunks/convert-ILMJ2HHN.js +5 -0
- package/dist/chunks/customizations-AX7ZSXCK.js +2 -0
- package/dist/chunks/data-UWOV3LBO.js +5 -0
- package/dist/chunks/dependency-V4ZJIWQL.js +3 -0
- package/dist/chunks/{discovery-XXVLVHD6.js → discovery-PSGWFMJH.js} +1 -1
- package/dist/chunks/{dv-3OESFBNW.js → dv-SD5LTNZJ.js} +109 -48
- package/dist/chunks/{env-MZPI3UA2.js → env-6RZCHQUC.js} +2 -2
- package/dist/chunks/environment-IBLJHUAL.js +2 -0
- package/dist/chunks/{environments-WMBLSAQF.js → environments-3P2I4QUC.js} +1 -1
- package/dist/chunks/envvar-KJ2TUZGJ.js +2 -0
- package/dist/chunks/fanout-2WQYFUWL.js +2 -0
- package/dist/chunks/{fetchxml-ONTNTA6Z.js → fetchxml-M6EOF7N6.js} +1 -1
- package/dist/chunks/functions-NILMLS4R.js +2 -0
- package/dist/chunks/{graph-JI23YQB5.js → graph-NO2OT2TL.js} +1 -1
- package/dist/chunks/{group-DKEPSVRV.js → group-ISSJ4H2A.js} +2 -2
- package/dist/chunks/history-JPMLQDJI.js +2 -0
- package/dist/chunks/identity-SBQNHSBF.js +2 -0
- package/dist/chunks/init-X2VEK4T2.js +2 -0
- package/dist/chunks/jobs-XC7EYPBP.js +2 -0
- package/dist/chunks/lifecycle-2F7MF6EP.js +2 -0
- package/dist/chunks/{main-ZVIKC3VA.js → main-J3O5YMIY.js} +2 -2
- package/dist/chunks/metadata-NZFQIAAG.js +2 -0
- package/dist/chunks/metadataCreate-XSHK32TR.js +2 -0
- package/dist/chunks/msalUser-KC75VDVV.js +2 -0
- package/dist/chunks/names-N5JRXO33.js +2 -0
- package/dist/chunks/{pack-2UDE25IY.js → pack-3OYGV36R.js} +1 -1
- package/dist/chunks/pat-PCMOZYM5.js +2 -0
- package/dist/chunks/{pipelines-O3OYNCHT.js → pipelines-OCHSIQ2E.js} +1 -1
- package/dist/chunks/pluginRegister-LEVZNDZN.js +4 -0
- package/dist/chunks/{plugins-EUDJ7QIS.js → plugins-TEME2R77.js} +1 -1
- package/dist/chunks/{policies-KVPQVUHS.js → policies-EWCANNBE.js} +1 -1
- package/dist/chunks/{pools-7H2L4QJC.js → pools-54KMEL5D.js} +1 -1
- package/dist/chunks/process-KR7LIXZB.js +2 -0
- package/dist/chunks/{projects-BHG2B4IX.js → projects-LPVDFLPC.js} +1 -1
- package/dist/chunks/protect-X2J7LU7X.js +2 -0
- package/dist/chunks/provider-D7DMMAS6.js +2 -0
- package/dist/chunks/{prs-NOXIZ7AT.js → prs-C4EKGJWA.js} +1 -1
- package/dist/chunks/records-C4RLQXFK.js +2 -0
- package/dist/chunks/{run-BXFENCN6.js → run-27MYTWHY.js} +1 -1
- package/dist/chunks/run-46PEJS3S.js +2 -0
- package/dist/chunks/run-7L6W2YWJ.js +3 -0
- package/dist/chunks/run-CD3ZOB5V.js +4 -0
- package/dist/chunks/run-EUNN6OZO.js +2 -0
- package/dist/chunks/{run-JYU5BTWN.js → run-JDNEQMJC.js} +1 -1
- package/dist/chunks/{run-MGLIIM7Z.js → run-T3IIJ7SK.js} +1 -1
- package/dist/chunks/run-ZHIDOKQH.js +2 -0
- package/dist/chunks/{runtime-VOF7XYXW.js → runtime-FJJPTBEE.js} +1 -1
- package/dist/chunks/security-SBIAK6QD.js +2 -0
- package/dist/chunks/{service-V2TQEEID.js → service-4N3YP4Z7.js} +1 -1
- package/dist/chunks/{service-4PIAYFYF.js → service-HASXLUGE.js} +1 -1
- package/dist/chunks/services-C6G4XRXR.js +2 -0
- package/dist/chunks/{skills-GD6Z6P3R.js → skills-FW4F3EIW.js} +1 -1
- package/dist/chunks/solution-CNBNIS7Z.js +2 -0
- package/dist/chunks/solutionExport-Y524HMGN.js +2 -0
- package/dist/chunks/{solutionfiles-P223QW2J.js → solutionfiles-2TP3Y2RW.js} +1 -1
- package/dist/chunks/spn-YSYMDTOI.js +2 -0
- package/dist/chunks/tokenCache-TQFT6LAD.js +2 -0
- package/dist/chunks/{unpack-XZLTBUGC.js → unpack-HUH7OJMP.js} +1 -1
- package/dist/chunks/{users-KFAPPGF4.js → users-Q7BJKBPP.js} +1 -1
- package/dist/chunks/{vargroups-33EZAHGZ.js → vargroups-GNZBODVJ.js} +1 -1
- package/dist/chunks/{whoami-ULK5UMZV.js → whoami-6G6UFTNS.js} +1 -1
- package/dist/chunks/{workitems-YGES6KKN.js → workitems-2IOGD3EL.js} +1 -1
- package/package.json +61 -57
- package/schema/ppdo-cli.schema.json +16 -4
- package/schema/reference-data.schema.json +192 -0
- package/skills/ppdo-cli/SKILL.md +2 -1
- package/skills/ppdo-cli-data/SKILL.md +669 -0
- package/skills/ppdo-cli-dataverse/SKILL.md +6 -0
- package/skills/ppdo-cli-plugins/PluginRegistration.cs +229 -0
- package/skills/ppdo-cli-plugins/SKILL.md +95 -0
- package/skills/ppdo-cli-plugins/reference.md +72 -0
- package/dist/chunks/auth-IP7AOWSF.js +0 -6
- package/dist/chunks/azCli-T67ZMIC3.js +0 -2
- package/dist/chunks/batch-GCXLGQET.js +0 -4
- package/dist/chunks/bulk-5QO343HO.js +0 -2
- package/dist/chunks/chunk-3C3GSN3J.js +0 -2
- package/dist/chunks/chunk-4S5ETLH4.js +0 -2
- package/dist/chunks/chunk-5SBBTR3Y.js +0 -2
- package/dist/chunks/chunk-5UOZCXQF.js +0 -5
- package/dist/chunks/chunk-BWZ6HZXM.js +0 -2
- package/dist/chunks/chunk-JGLUQBCK.js +0 -2
- package/dist/chunks/chunk-MME53RWW.js +0 -4
- package/dist/chunks/chunk-OP6EXLWQ.js +0 -5
- package/dist/chunks/chunk-PDFXH652.js +0 -2
- package/dist/chunks/chunk-QE4DELWW.js +0 -2
- package/dist/chunks/chunk-RHQP7X6H.js +0 -3
- package/dist/chunks/chunk-UKKSN4F7.js +0 -3
- package/dist/chunks/chunk-UWFDJKOJ.js +0 -2
- package/dist/chunks/chunk-WXCLWAE2.js +0 -2
- package/dist/chunks/chunk-X7VWUI6N.js +0 -2
- package/dist/chunks/component-PAASRIK6.js +0 -2
- package/dist/chunks/config-JN3I5EII.js +0 -2
- package/dist/chunks/connection-IWFELK5W.js +0 -2
- package/dist/chunks/connref-ZDY7JYK5.js +0 -2
- package/dist/chunks/customizations-IE2KO275.js +0 -7
- package/dist/chunks/dependency-EFDSIKSN.js +0 -3
- package/dist/chunks/environment-NUQHU74A.js +0 -2
- package/dist/chunks/envvar-YN35IDWJ.js +0 -2
- package/dist/chunks/fanout-DUP5CD5X.js +0 -2
- package/dist/chunks/functions-K5TYRB2C.js +0 -2
- package/dist/chunks/history-SNSJRV6B.js +0 -2
- package/dist/chunks/identity-OW4WCDOA.js +0 -2
- package/dist/chunks/jobs-PXNJFWWF.js +0 -2
- package/dist/chunks/lifecycle-7RMWV26J.js +0 -2
- package/dist/chunks/metadata-74WGGOV5.js +0 -2
- package/dist/chunks/metadataCreate-W3NDI5FB.js +0 -2
- package/dist/chunks/msalUser-JRNX5HPO.js +0 -2
- package/dist/chunks/names-SFYZQY6Q.js +0 -2
- package/dist/chunks/process-G7LCTGKS.js +0 -2
- package/dist/chunks/protect-WZO3MAHF.js +0 -2
- package/dist/chunks/provider-VXRAQRN2.js +0 -2
- package/dist/chunks/records-TN7ZKUJ7.js +0 -2
- package/dist/chunks/run-F6H4QCWR.js +0 -2
- package/dist/chunks/run-HBQCSGYY.js +0 -3
- package/dist/chunks/run-MHM3GTGH.js +0 -2
- package/dist/chunks/run-SRQPP6N3.js +0 -3
- package/dist/chunks/run-ZNDSC7LR.js +0 -2
- package/dist/chunks/security-FLEAZ4EA.js +0 -2
- package/dist/chunks/services-B6V4VVX5.js +0 -2
- package/dist/chunks/solution-HF57MP27.js +0 -2
- package/dist/chunks/solutionExport-TLGHMUM5.js +0 -2
- package/dist/chunks/spn-AIUWML5R.js +0 -2
- package/dist/chunks/tokenCache-3LMJRUTI.js +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
+
import{a as B,b as k,c as me}from"./chunk-6VLFO5FJ.js";import{A as de,B as F,F as ue,G as u,d as Q,e as A,f as c,g as le,h as C,i as h,k as N,n as _,t as x,u as g,v as q,w as P,z as Z}from"./chunk-BG2OIOSN.js";import"./chunk-UCTMKA2J.js";import{a as ce,b as Y,d as z,e as j,f as J,i as K}from"./chunk-FOEBNCSD.js";import{y as se}from"./chunk-BALEFXOL.js";import{a as re}from"./chunk-J4R6QXW7.js";import{b as E}from"./chunk-2IUXH534.js";import"./chunk-S4KF5Z3S.js";import{a as ae,b as y,d as W}from"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";import{randomUUID as Te}from"node:crypto";import{readFileSync as je,writeFileSync as we}from"node:fs";import{extname as ke}from"node:path";var ye=new Map([[0,"public"],[1,"advanced-find"],[2,"associated"],[4,"quick-find"],[8,"reporting"],[16,"offline-filters"],[64,"lookup"],[128,"appointment-book"],[256,"outlook-filters"],[512,"address-book-filters"],[1024,"main-without-subject"],[2048,"other"],[4096,"interactive-workflow"],[8192,"offline-template"],[16384,"custom-defined"]]),ge=new Map([[0,"dashboard"],[2,"main"],[5,"mobile"],[6,"quick-view"],[7,"quick-create"],[11,"card"],[12,"main-interactive"]]),fe={main:2,"quick-create":7,"quick-view":6,card:11},ne=new Map([[1,"html"],[2,"css"],[3,"js"],[4,"xml"],[5,"png"],[6,"jpg"],[7,"gif"],[8,"xap"],[9,"xsl"],[10,"ico"],[11,"svg"],[12,"resx"]]),Ce={".htm":1,".html":1,".css":2,".js":3,".xml":4,".png":5,".jpg":6,".jpeg":6,".gif":7,".xap":8,".xsl":9,".xslt":9,".ico":10,".svg":11,".resx":12},Ne=new Set([1,2,3,4,9,11,12]),Be="{4273EDBD-AC1D-40d3-9FB2-095C621B552D}",be="name,returnedtypecode,querytype,isdefault,statecode,ismanaged,description,savedqueryid",he="name,objecttypecode,type,formactivationstate,isdefault,ismanaged,description,formid",xe="name,displayname,webresourcetype,ismanaged,description,modifiedon,webresourceid",I=Buffer.from("{}");function D(e,t){for(let[o,n]of e)if(n===t)return o;throw new Error(`unknown type ${t}`)}function oe(e,t){return typeof t=="number"&&e.has(t)?e.get(t):t}function R(e){return e.publish===!1}function L(e){return typeof e!="string"||!e?null:ue(se(e).toString("utf8"))}function ee(e,t,o){let n;try{n=k(J(e))}catch(i){throw i instanceof B?new y(`the ${o} is not well-formed XML: ${i.message}`):i}if(n.tag!==t)throw new y(`the ${o} must have a <${t}> root, not <${n.tag}>`);return n}async function S(e,t,o,n,i){let a=await g(e,t,"GET",`${o}(${n})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`,{params:[["$select",i]]});return q(a)}async function H(e,t,o){ce(o,"table logical name");let n=q(await g(e,t,"GET",`EntityDefinitions(LogicalName='${o}')`,{params:[["$select","LogicalName,EntitySetName,ObjectTypeCode,PrimaryIdAttribute,PrimaryNameAttribute"]]})),i=q(await g(e,t,"GET",`EntityDefinitions(LogicalName='${o}')/Attributes`,{params:[["$select","LogicalName"]]}));return n.attributes=new Set(C(i.value).map(a=>a.LogicalName)),n}async function M(e,t,o){let n=[];o.table&&n.push(`<entities><entity>${o.table}</entity></entities>`),o.webresource&&n.push(`<webresources><webresource>{${o.webresource}}</webresource></webresources>`);let i={ParameterXml:"<importexportxml>"+n.join("")+"</importexportxml>"};await g(e,t,"POST","PublishXml",{body:P(i)})}async function ve(e,t,o,n,i,a,s,r,d){let l=Y(s)?`${n} eq ${z(s)}`:`name eq ${j(s)}`;r&&(l+=` and ${i} eq ${j(r)}`);let f=C(q(await g(e,t,"GET",o,{params:[["$select",a],["$filter",l]]})).value);if(!f.length)throw new W(`no ${d} '${s}'`+(r?` on ${r}`:""),{service:"dataverse",hint:`run: ppdo-cli dv ${d} list <table>`});if(f.length>1)throw new y(`${f.length} ${d}s are named '${s}'`,{hint:"pass --table, or use an id: "+f.slice(0,5).map(m=>m[n]).join(", ")});return f[0]}async function ie(e,t,o){if(!o)return{};let{find:n}=await import("./solution-CNBNIS7Z.js");return await n(e,t,o),{"MSCRM.SolutionUniqueName":o}}function Le(e){let t=e.get("attribute"),o=e.get("operator"),n=e.findall("value").map(s=>s.text),i=e.get("value")!==null?e.get("value"):n.length?n.map(s=>s??"None").join(","):null;return`${e.get("entityname")?`${e.get("entityname")}.`:""}${t??"None"} ${o??"None"}`+(i!==null?` ${i}`:"")}function $e(e){if(e===null)return null;let t=` ${e.get("type","and")} `;return e.children.filter(n=>n.tag==="condition"||n.tag==="filter").map(n=>n.tag==="condition"?Le(n):`(${$e(n)??"None"})`).filter(n=>n).join(t)||null}function Re(e,t){let o={};try{let a=k(e||"").find("entity");a!==null&&(o.sort=a.findall("order").map(s=>(s.get("descending")==="true"?"-":"")+(s.get("attribute")||s.get("alias")||"")),o.filter=$e(a.find("filter")),o.links=[...a.iter("link-entity")].map(s=>({table:s.get("name"),alias:s.get("alias"),from:s.get("from"),to:s.get("to"),type:s.get("link-type","inner")})))}catch(i){if(!(i instanceof B))throw i;o.fetch_error="not well-formed"}try{let i=k(t||"");o.columns=[...i.iter("cell")].map(a=>{let s=a.get("width");return{name:a.get("name"),width:/^[0-9]+$/.test(s||"")?parseInt(s,10):s}})}catch(i){if(!(i instanceof B))throw i;o.layout_error="not well-formed"}let n={};for(let[i,a]of Object.entries(o))a!==null&&!(Array.isArray(a)&&!a.length)&&(n[i]=a);return n}async function Ee(e,t,o,n,i){let s=ee(n,"fetch","FetchXML").find("entity");if(s===null||s.get("name")!==o)throw new y(`the FetchXML's <entity name> must be ${o}`);let r=ee(i,"grid","layout XML"),d=new Set(s.findall("attribute").map(p=>p.get("name"))),l=s.find("all-attributes")!==null,f=new Set([...s.iter("link-entity")].map(p=>p.get("alias")).filter(p=>p)),m=[];for(let p of r.iter("cell")){let T=p.get("name")||"";T.includes(".")?f.has(T.slice(0,T.indexOf(".")))||m.push(T):!l&&!d.has(T)&&m.push(T)}if(m.length)throw new y("layout columns not in the query: "+m.join(", "),{hint:"add <attribute name=...> (or the link-entity alias) to the FetchXML"});let w=e,v=t,$=await H(w,v,o),b=k(J(n));for(let p of["page","paging-cookie","top"])b.attrib.delete(p);b.set("count","1");try{await v.request("GET",`${$.EntitySetName}?fetchXml=`+re(me(b),""))}catch(p){throw p instanceof ae?new y(`the FetchXML doesn't run: ${p.message}`):p}}function U(e){return h({name:c(e,"name"),table:c(e,"returnedtypecode"),type:oe(ye,c(e,"querytype")),default:A(c(e,"isdefault"),null),state:c(e,"statecode")===1?"inactive":"active",managed:c(e,"ismanaged"),id:c(e,"savedqueryid")})}async function Je(e){let t=e.args,o=await x(e);E(e,o,"GET","savedqueries",null);let n=[`returnedtypecode eq ${j(String(t.table))}`];u(t.type)&&n.push(`querytype eq ${D(ye,u(t.type))}`),u(t.name)&&n.push(K("name",u(t.name)));let[i]=await Z(e,o,"savedqueries",[["$select",be],["$filter",n.join(" and ")],["$orderby","name"]],null,_(t),"views");await e.emit(i.map(U))}function G(e,t,o,n){return ve(e,t,"savedqueries","savedqueryid","returnedtypecode",be,o,n,"view")}function Se(e,t){we(e,t,"utf8")}async function Ke(e){let t=e.args,o=await x(e),n=await G(e,o,String(t.view),u(t.table)),i=await S(e,o,"savedqueries",n.savedqueryid,"fetchxml,layoutxml,name,description"),a={...U(n),description:c(i,"description"),...Re(c(i,"fetchxml"),c(i,"layoutxml"))};for(let[s,r]of[[u(t.saveFetchxml),"fetchxml"],[u(t.saveLayoutxml),"layoutxml"]])s&&(Se(s,c(i,r)||""),(a.saved??=[]).push(s));await e.emit(h(a))}function Oe(e){let t=e.PrimaryNameAttribute,o=e.PrimaryIdAttribute,n=e.ObjectTypeCode,i='<filter type="and"><condition attribute="statecode" operator="eq" value="0" /></filter>',a=`<fetch version="1.0" mapping="logical"><entity name="${e.LogicalName}"><attribute name="${t}" /><attribute name="${o}" /><order attribute="${t}" descending="false" />${i}</entity></fetch>`;e.attributes.has("statecode")||(a=a.split(i).join(""));let s=`<grid name="resultset" object="${n}" jump="${t}" select="1" icon="1" preview="1"><row name="result" id="${o}"><cell name="${t}" width="300" /></row></grid>`;return[a,s]}async function Qe(e){let t=e.args,o=String(t.table),n=await x(e);E(e,n,"POST","savedqueries",I);let i=L(t.fetchxml),a=L(t.layoutxml),s=await n.lookups(async()=>{let f=await H(e,n,o);if(u(t.copy)){let m=await G(e,n,u(t.copy),o),w=await S(e,n,"savedqueries",m.savedqueryid,"fetchxml,layoutxml");i=i||c(w,"fetchxml"),a=a||c(w,"layoutxml")}if(!i||!a){let[m,w]=Oe(f);i=i||m,a=a||w}return await Ee(e,n,o,i,a),ie(e,n,u(t.solution))}),r={name:t.name,returnedtypecode:o,querytype:0,fetchxml:i,layoutxml:a};u(t.description)&&(r.description=t.description);let d=await g(e,n,"POST","savedqueries",{body:P(r),headers:s}),l=F(d);R(t)||await M(e,n,{table:o}),await e.emit({...U(await G(e,n,String(l),null)),published:!R(t)})}async function Ze(e){let t=e.args,o=u(t.name),n=u(t.description);if(!(o||n!==null||t.fetchxml||t.layoutxml))throw new y("nothing to update",{hint:"pass --name, --description, --fetchxml or --layoutxml"});let i=await x(e);E(e,i,"PATCH","savedqueries",I);let a=L(t.fetchxml),s=L(t.layoutxml),r=await i.lookups(async()=>{let f=await G(e,i,String(t.view),u(t.table));if(a||s){let m=await S(e,i,"savedqueries",f.savedqueryid,"fetchxml,layoutxml");await Ee(e,i,f.returnedtypecode,a||c(m,"fetchxml")||"",s||c(m,"layoutxml")||"")}return f}),d=h({name:o,description:n,fetchxml:a,layoutxml:s});await g(e,i,"PATCH",`savedqueries(${r.savedqueryid})`,{body:P(d),headers:{"If-Match":"*"}}),R(t)||await M(e,i,{table:r.returnedtypecode});let l=await S(e,i,"savedqueries",r.savedqueryid,"fetchxml,layoutxml,name");await e.emit({...U({...r,name:c(l,"name")||c(r,"name")}),changed:N(Object.keys(d),f=>f),published:!R(t),...Re(c(l,"fetchxml"),c(l,"layoutxml"))})}function pe(e){if(e===null)return null;let t=e.find("labels/label");return t!==null?t.get("description"):null}function Pe(e){let t;try{t=k(e||"")}catch(r){if(r instanceof B)return{form_error:"not well-formed"};throw r}let o=[];for(let r of t.iter("tab")){let d=[];for(let l of r.iter("section")){let f=[...l.iter("control")].map(m=>m.get("datafieldname")||m.get("id"));d.push(h({name:l.get("name"),label:pe(l),visible:l.get("visible")!=="false"?null:!1,fields:f}))}o.push(h({name:r.get("name"),label:pe(r),visible:r.get("visible")!=="false"?null:!1,sections:d}))}let n=t.find("header"),i=[...t.iter("Library")].map(r=>r.get("name")),a={tabs:o,header:n!==null?[...n.iter("control")].map(r=>r.get("datafieldname")||r.get("id")):null,libraries:i.length?i:null},s={};for(let[r,d]of Object.entries(a))Q(d)&&(s[r]=d);return s}async function qe(e,t,o,n){let i=ee(n,"form","form XML"),a=[...i.iter("control")].map(l=>l.get("id")).filter(l=>!!l),s=N(new Set(a.filter(l=>a.indexOf(l)!==a.lastIndexOf(l))),l=>l);if(s.length)throw new y("control ids used more than once: "+s.join(", "));let r=(await H(e,t,o)).attributes,d=N(new Set([...i.iter("control")].map(l=>l.get("datafieldname")).filter(l=>!!l&&!r.has(l.toLowerCase()))),l=>l);if(d.length)throw new y(`fields not on ${o}: `+d.join(", "))}function V(e){return h({name:c(e,"name"),table:c(e,"objecttypecode"),type:oe(ge,c(e,"type")),default:A(c(e,"isdefault"),null),state:c(e,"formactivationstate")===0?"inactive":"active",managed:c(e,"ismanaged"),id:c(e,"formid")})}async function et(e){let t=e.args,o=await x(e);E(e,o,"GET","systemforms",null);let n=[`objecttypecode eq ${j(String(t.table))}`];u(t.type)&&n.push(`type eq ${D(ge,u(t.type))}`);let[i]=await Z(e,o,"systemforms",[["$select",he],["$filter",n.join(" and ")],["$orderby","name"]],null,_(t),"forms");await e.emit(i.map(V))}function O(e,t,o,n){return ve(e,t,"systemforms","formid","objecttypecode",he,o,n,"form")}async function tt(e){let t=e.args,o=await x(e),n=await O(e,o,String(t.form),u(t.table)),i=await S(e,o,"systemforms",n.formid,"formxml,description"),a={...V(n),description:c(i,"description"),...Pe(c(i,"formxml"))},s=u(t.save);s&&(Se(s,c(i,"formxml")||""),a.saved=s),await e.emit(h(a))}function Ie(e,t){let o=()=>"{"+Te()+"}",n=e.PrimaryNameAttribute;return`<form><tabs><tab name="general" id="${o()}" verticallayout="true" showlabel="true" expanded="true"><labels><label description="General" languagecode="${t}" /></labels><columns><column width="100%"><sections><section name="general_section" id="${o()}" showlabel="false" showbar="false" columns="1"><labels><label description="General" languagecode="${t}" /></labels><rows><row><cell id="${o()}"><labels><label description="Name" languagecode="${t}" /></labels><control id="${n}" classid="${Be}" datafieldname="${n}" disabled="false" /></cell></row></rows></section></sections></column></columns></tab></tabs></form>`}async function nt(e){let t=e.args,o=String(t.table),n=u(t.type),i=await x(e);E(e,i,"POST","systemforms",I);let[a,s,r]=await i.lookups(async()=>{let m=await H(e,i,o),w,v;if(u(t.copy)){let $=await O(e,i,u(t.copy),o);w=c(await S(e,i,"systemforms",$.formid,"formxml"),"formxml")||"",v=n?fe[n]:c($,"type")}else{let $=q(await g(e,i,"GET","organizations",{params:[["$select","languagecode"]]})).value,b=A(c(Q($)?C($)[0]:{},"languagecode"),1033);w=Ie(m,b),v=fe[n||"main"]}return await qe(e,i,o,w),[w,v,await ie(e,i,u(t.solution))]}),d={name:t.name,objecttypecode:o,type:s??null,formxml:a};u(t.description)&&(d.description=t.description);let l=await g(e,i,"POST","systemforms",{body:P(d),headers:r}),f=F(l);R(t)||await M(e,i,{table:o}),await e.emit({...V(await O(e,i,String(f),null)),published:!R(t)})}async function ot(e){let t=e.args,o=u(t.name),n=u(t.description),i=u(t.state);if(!(o||n!==null||i||t.body))throw new y("nothing to update",{hint:"pass --name, --description, --state or --body"});let a=await x(e);E(e,a,"PATCH","systemforms",I);let s=L(t.body),r=await a.lookups(async()=>{let m=await O(e,a,String(t.form),u(t.table));if(i==="inactive"&&c(m,"type")!==2)throw new y("only main forms can be made inactive");return s&&await qe(e,a,m.objecttypecode,s),m}),d=h({name:o,description:n,formxml:s,formactivationstate:i==="active"?1:i==="inactive"?0:null});await g(e,a,"PATCH",`systemforms(${r.formid})`,{body:P(d),headers:{"If-Match":"*"}}),R(t)||await M(e,a,{table:r.objecttypecode});let l=await O(e,a,r.formid,null),f=await S(e,a,"systemforms",r.formid,"formxml,name");await e.emit({...V({...l,name:c(f,"name")||c(l,"name")}),changed:N(Object.keys(d),m=>m),published:!R(t),...Pe(c(f,"formxml"))})}function X(e){return h({name:c(e,"name"),display_name:c(e,"displayname"),type:oe(ne,c(e,"webresourcetype")),managed:c(e,"ismanaged"),modified:c(e,"modifiedon"),id:c(e,"webresourceid")})}async function it(e){let t=e.args,o=await x(e);E(e,o,"GET","webresourceset",null);let n=u(t.solution),i=null;if(n){let{names:d,objectIds:l}=await import("./solution-CNBNIS7Z.js");i=await l(e,o,d(n),61)}let a=t.hidden?[]:["ishidden/Value eq false"];u(t.name)&&a.push(K("name",u(t.name))),u(t.type)&&a.push(`webresourcetype eq ${D(ne,u(t.type))}`);let s=[["$select",xe],["$orderby","name"]];a.length&&s.push(["$filter",a.join(" and ")]);let r=await de(e,o,"webresourceset","webresourceid",i,s,null,_(t),"web resources",d=>(c(d,"name")||"").toLowerCase());await e.emit(r.map(X))}async function te(e,t,o){let n=Y(o)?`webresourceid eq ${z(o)}`:`name eq ${j(o)}`,i=C(q(await g(e,t,"GET","webresourceset",{params:[["$select",xe],["$filter",n]]})).value);return i.length?i[0]:null}async function at(e){let t=e.args,o=String(t.name),n=await x(e),i=await te(e,n,o);if(!i)throw new W(`no web resource '${o}'`,{service:"dataverse",hint:"run: ppdo-cli dv webresource list --name '*<part>*'"});let a=await S(e,n,"webresourceset",i.webresourceid,"content,description"),s=Buffer.from(c(a,"content")||"","base64"),r={...X(i),description:c(a,"description"),bytes:s.length},d=u(t.save);d?(we(d,s),r.saved=d):Ne.has(c(i,"webresourcetype"))?r.content=s.toString("utf8"):r.hint="binary content: pass --save <file>",await e.emit(h(r))}var Me={ENOENT:"No such file or directory",EACCES:"Permission denied",EPERM:"Operation not permitted",EISDIR:"Is a directory"};async function st(e){let t=e.args,o=String(t.file),n=String(t.name),i;try{i=je(o)}catch(b){let p=b;throw new y(`cannot read ${o}: ${Me[p.code??""]??p.message}`)}let a=i.toString("base64"),s=u(t.type),r=s?D(ne,s):Ce[ke(o).toLowerCase()];if(r===void 0)throw new y(`can't tell the web resource type from '${o}'`,{hint:"pass --type"});if(!n.split("/",1)[0].includes("_"))throw new y(`'${n}' has no publisher prefix`,{hint:"e.g. contoso_/scripts/app.js"});let d=await x(e);E(e,d,"POST","webresourceset",I);let[l,f,m]=await d.lookups(async()=>{let b=await te(e,d,n),p=b?c(await S(e,d,"webresourceset",b.webresourceid,"content"),"content"):null;return[b,p,await ie(e,d,u(t.solution))]}),w=h({displayname:u(t.displayName),description:u(t.description)});if(l&&f===a&&!Object.keys(w).length){await e.emit({...X(l),action:"unchanged",published:!1});return}let v,$;if(l)await g(e,d,"PATCH",`webresourceset(${l.webresourceid})`,{headers:{"If-Match":"*",...m},body:P({content:a,...w})}),v=l.webresourceid,$="updated";else{let b={name:n,webresourcetype:r,content:a,displayname:u(t.displayName)||n.slice(n.lastIndexOf("/")+1),...w},p=await g(e,d,"POST","webresourceset",{body:P(b),headers:m});v=F(p),$="created"}R(t)||await M(e,d,{webresource:v}),await e.emit({...X(le(await te(e,d,String(v)))),action:$,bytes:i.length,published:!R(t)})}export{fe as CREATE_FORM_TYPES,ge as FORM_TYPES,ye as VIEW_TYPES,Ce as WR_EXTENSIONS,ne as WR_TYPES,qe as checkForm,Ee as checkView,O as findForm,G as findView,te as findWebresource,nt as formCreate,tt as formGet,et as formList,Pe as formSummary,ot as formUpdate,M as publish,ie as solutionHeaders,H as tableInfo,Qe as viewCreate,Ke as viewGet,Je as viewList,Re as viewSummary,Ze as viewUpdate,at as wrGet,it as wrList,st as wrPush};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
+
import{a as Y,b as G,c as Ve,e as q,f as A,g as Z,h as We,i as ge,j as ee,k as Ge,l as He,m as Qe,n as Xe,o as Ze,p as et,q as nt,r as ot,s as ye,v as st}from"./chunk-S6NK6GX2.js";import{$ as Ye,E as Ke,G as Be,J as re,L as Ae,M as _e,N as me,O as je,P as qe,Q as Je,R as Ue,S,T as j,W as le,X as z,Y as W,a as K,b as V,ca as tt,d as ae,h as xe,i as Ie,r as De,s as X,u as he,w as Fe,x as Ee,y as Ne,z as ze}from"./chunk-I7MHI5CU.js";import"./chunk-6VLFO5FJ.js";import{b as pe,d as Pe,e as Ce,f as Te}from"./chunk-MNGA7IHQ.js";import{n as Le,t as U}from"./chunk-BG2OIOSN.js";import"./chunk-UCTMKA2J.js";import{b as Oe}from"./chunk-FOEBNCSD.js";import{b as Me}from"./chunk-KBZI5UDL.js";import"./chunk-BALEFXOL.js";import{a as $e,b as Se}from"./chunk-LB7WNZVK.js";import"./chunk-GY6BUIDP.js";import"./chunk-J4R6QXW7.js";import{c as Re}from"./chunk-2IUXH534.js";import"./chunk-TCLZ4XM6.js";import"./chunk-H4OY4EFC.js";import"./chunk-TQLZ3TRU.js";import"./chunk-S4KF5Z3S.js";import{a as H,b as J,g as Q,j as ve}from"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";import{mkdirSync as Kt,writeFileSync as Bt}from"node:fs";import{dirname as At}from"node:path";function te(r){return r.key.slice(2)}async function it(r,e,n,t,s,d,o,l,u,a){let i=n.relationship(d.name),c=[],f=ze(e,d.name,c);if(!f&&!c.length&&c.push(`data/relationships/${d.name.toLowerCase()}.yaml: the relationship is in the schema and has no data file; run: ppdo-cli dv data export`),f&&(f.from!==i.entity1||f.to!==i.entity2)&&c.push(`${f.file}: from and to must be ${i.entity1} and ${i.entity2}`),c.length||!f)throw K("data_invalid","the data files are not valid",c);let h=n.meta(i.entity1),m=n.meta(i.entity2),y=ye("from",i.entity1),g=ye("to",i.entity2),$=o.get(i.entity1),I=o.get(i.entity2),R=[],L=[];for(let w of f.links)try{let O=await s.lookupKey(y,w.from),b=[];for(let P of w.to)b.push(await s.lookupKey(g,P));L.push({from:O,to:b,file:w.file,index:w.index})}catch(O){throw O instanceof A?K("data_invalid","the data files are not valid",[`${w.file} link ${w.index+1}: ${O.message}`]):O}let F=(w,O,b)=>{let P=w?.get(O.key);if(P&&!P.logged)return P.id?{table:b,id:P.id,pending:null}:{table:b,id:null,pending:P};let C=l.get(b)?.get(O.key);return C?{table:b,id:String(C[b===i.entity1?h.primaryId:m.primaryId]).toLowerCase(),pending:null}:null};for(let w of L)for(let O of w.to)F(I,O,i.entity2)||R.push(O);let T=R.length?await t.findByKeys(i.entity2,R):new Map,B=await n.other(i.intersect);if(!B)throw K("not_found",`the environment has no intersect table '${i.intersect}'`);let ue=await r.rows(B.entitySet,[["$select",`${i.attr1},${i.attr2}`]],!1),p=new Map;for(let w of ue){let O=String(w[i.attr1]).toLowerCase(),b=p.get(O);b||p.set(O,b=new Set),b.add(String(w[i.attr2]).toLowerCase())}let k=[],v=new Map,M=new Map,x=0,E=new Set;for(let w of L){if($?.get(w.from.key)?.logged){E.add(w.from.key);continue}w.to=w.to.filter(C=>!I?.get(C.key)?.logged);let O=F($,w.from,i.entity1);if(!O){u.push(`${w.file} link ${w.index+1}: the from record ${JSON.stringify(te(w.from))} is not in the data file of ${i.entity1} and not in the environment`);continue}if(E.has(w.from.key)){u.push(`${w.file} link ${w.index+1}: the from record ${JSON.stringify(te(w.from))} is in the file two times`);continue}E.add(w.from.key);let b=O.id?p.get(O.id)??new Set:new Set,P=new Set;for(let C of w.to){let D=F(I,C,i.entity2);if(!D){let N=T.get(C.key);N&&(D={table:i.entity2,id:String(N[m.primaryId]).toLowerCase(),pending:null})}if(!D){u.push(`${w.file} link ${w.index+1}: no ${i.entity2} with the key ${JSON.stringify(te(C))}`);continue}D.id&&P.add(D.id),D.id&&b.has(D.id)?x++:k.push({from:O,to:D,fromOut:te(w.from),toOut:te(C)})}if(O.id&&M.set(O.id,P),d.delete.mode==="mirror"&&O.id)for(let C of b)P.has(C)||v.set(`${O.id}|${C}`,ke(i,O.id,C,"mirror"))}if(d.delete.mode==="mirror"){for(let w of $?.values()??[])if(!(w.logged||!w.id||E.has(w.key)))for(let O of p.get(w.id)??[])v.set(`${w.id}|${O}`,ke(i,w.id,O,"mirror"))}if(d.delete.mode!=="off"){let w=[],O=He(e,d.name,w);if(w.length)throw K("data_invalid","the data files are not valid",w);for(let b of O?.entries??[]){if(M.get(b.from)?.has(b.to)){a.push(`${O.file}: the link ${b.from}|${b.to} is in the relationship file and in the deletion log; the import uses the relationship file and does not remove it`);continue}p.get(b.from)?.has(b.to)&&v.set(`${b.from}|${b.to}`,ke(i,b.from,b.to,"manifest"))}}return{spec:d,rel:i,fromMeta:h,toMeta:m,link:k,unlink:[...v.values()],unchanged:x}}function ke(r,e,n,t){return{from:{table:r.entity1,id:e,pending:null},to:{table:r.entity2,id:n,pending:null},fromOut:e,toOut:n,reason:t}}async function at(r,e,n,t,s){let d=r.origin,o=[],l=[];for(let h of e.link){let m=h.from.id??h.from.pending?.id,y=h.to.id??h.to.pending?.id;if(!m||!y){h.failed="not run: a record of the link was not created",o.push(h);continue}l.push({change:h,method:"POST",path:`${e.fromMeta.entitySet}(${m})/${e.rel.nav1}/$ref`,body:{"@odata.id":`${d}/api/data/v9.2/${e.toMeta.entitySet}(${y})`}})}for(let h of e.unlink)l.push({change:h,method:"DELETE",path:`${e.fromMeta.entitySet}(${h.from.id})/${e.rel.nav1}(${h.to.id})/$ref`});let u=[];for(let h=0;h<l.length;h+=100)u.push(l.slice(h,h+100));let a=0,i=0,c=[],f=0;return await z(u,n,async h=>{let m=await s(h.map(y=>({method:y.method,path:y.path,body:y.body,headers:t})));h.forEach((y,g)=>{let $=m[g];$&&$.status>=200&&$.status<300?y.method==="POST"?a++:(i++,c.push(y.change)):(y.change.failed=$?.error??`HTTP ${$?.status??0}`,o.push(y.change))}),f+=h.length,r.progress.log(`${e.spec.name}: ${f.toLocaleString("en-US")} of ${l.length.toLocaleString("en-US")} link requests`)}),{linked:a,unlinked:i,removed:c,failed:o}}var rt=/0x80044150|deadlock|\b1205\b/i,bt=/Sql Number: (2812|2766)\b/,vt=["skip","delete","deactivate","unlink"],lt=r=>new Promise(e=>setTimeout(e,r)),ne=class{constructor(e,n,t){this.dv=e;this.plan=n;this.opts=t}done={created:new Set,updated:new Set,deleted:new Set,deactivated:new Set,skipped:new Set,failed:new Set,links:new Map,failures:[],stopped:!1};sets=new Map;batchOf(e,n=!1){let t=e.t.batchSize??this.opts.batchSize;return n?Math.min(t,Be):t}tableOf(e){return this.plan.tables.find(n=>n.t.table===e.t.table)}fail(e,n,t){this.done.failed.has(e)||this.done.skipped.has(e)||(n==="skip"?this.done.skipped.add(e):(this.done.failed.add(e),this.dv.progress.log(`failed: ${n} ${e.t.table} ${ce(e.keyOut)}: ${t.error}`)),e.failed=t.error,this.done.failures.push({table:e.t.table,action:n,key:e.keyOut,name:e.name,...t.status!==void 0?{status:t.status}:{},...t.code?{code:t.code}:{},error:t.error}))}async prepare(){let e=new Set;for(let n of this.plan.tables)for(let t of n.records)for(let s of t.lookups.values())s&&e.add(s.table);for(let n of e){let t=await this.plan.model.other(n);t&&this.sets.set(n,t.entitySet)}}bind(e,n,t){return[`${e.navigation.get(n.table)??(e.navigation.size===1?[...e.navigation.values()][0]:void 0)??e.name}@odata.bind`,`/${this.sets.get(n.table)??n.table+"s"}(${t})`]}targetId(e){return e.id??e.pending?.id??null}createBody(e){let n=e.m,t={};for(let[s,d]of e.values){let o=n.columns.get(s);t[s]=o?ge(d,o):d}for(let[s,d]of e.lookups){if(!d||e.later.has(s))continue;let o=this.targetId(d);if(!o)continue;let[l,u]=this.bind(n.columns.get(s),d,o);t[l]=u}return t}updateBody(e,n){let t=e.m,s={};if(!n){for(let[d,o]of e.values)s[d]=ge(o,t.columns.get(d));for(let[d,o]of e.lookups){let l=t.columns.get(d);if(o===null){let c=St(l,e.row);s[c]=null;continue}let u=this.targetId(o);if(!u)return null;let[a,i]=this.bind(l,o,u);s[a]=i}}for(let[d,o]of e.later){let l=this.targetId(o);if(!l)return null;let[u,a]=this.bind(t.columns.get(d),o,l);s[u]=a}for(let d of e.binaries)d.column.kind==="image"&&(s[d.column.name]=d.bytes?d.bytes.toString("base64"):null);return Object.keys(s).length?s:null}async sendBatch(e){let[n,t,s]=Pe(e,this.dv.origin,!1),d=Buffer.from(t,"utf8"),o=await this.dv.request("POST","$batch",{headers:{"Content-Type":`multipart/mixed; boundary=${n}`,Prefer:"odata.continue-on-error"},body:d,check:!1});if(o.status>=400&&!(o.header("content-type")||"").includes("multipart"))throw this.dv.client.service.error(o);let l=/boundary=([^\s;]+)/.exec(o.header("content-type")||"");return Te(s,l?Ce(o.text,l[1]):[],e.length)}outcome(e){if(!e)return{ok:!1,error:"no response"};if(e.status>=200&&e.status<300){let s=e.headers?.["odata-entityid"]??"",d=/\(([0-9a-fA-F-]{36})\)\s*$/.exec(s);return{ok:!0,...d?{id:d[1].toLowerCase()}:{}}}let n=e.body,t=(n&&typeof n=="object"?n.error:void 0)??{};return{ok:!1,status:e.status,...typeof t.code=="string"?{code:t.code}:{},error:Me(typeof t.message=="string"?t.message:null)??e.error??`HTTP ${e.status}`}}async bulk(e,n,t,s,d){if(!(n==="CreateMultiple"?e.bulkCreate:e.bulkUpdate))return this.oneByOne(e,n,t,s,d);let l=s.map(a=>({"@odata.type":`Microsoft.Dynamics.CRM.${e.table}`,...a})),u=Buffer.from(le({Targets:l}),"utf8");for(let a=1;;a++){let i=0,c="",f=!1;try{let h=await this.dv.request("POST",`${e.entitySet}/Microsoft.Dynamics.CRM.${n}`,{body:u,headers:d,check:!1});if(i=h.status,c=h.text,i<300){if(n==="UpdateMultiple")return t.map(()=>({ok:!0}));let m=JSON.parse(c||"{}").Ids;return t.map((y,g)=>({ok:!0,...m?.[g]?{id:String(m[g]).toLowerCase()}:{}}))}f=i>=500&&!rt.test(c)}catch(h){if(!(h instanceof H)||h.status!==void 0)throw h;f=!0}if(bt.test(c)&&a<=8){let h=5*a;this.dv.progress.log(`${e.table}: ${n} is not ready for the table yet (SQL ${/Sql Number: (\d+)/.exec(c)?.[1]}); waiting ${h} s (${a} of 8)`),await lt(h*1e3);continue}if(rt.test(c)&&a<=5){this.dv.progress.log(`${e.table}: ${n} of ${S(t.length)} records gave a SQL error that can pass (${/Sql Number: (\d+)/.exec(c)?.[1]??"deadlock"}); sending it again (${a} of 5)`),await lt(500+Math.random()*1500);continue}return f&&n==="CreateMultiple"?(this.dv.progress.log(`${e.table}: ${n} of ${S(t.length)} records has no known result (status ${i||"none"}); reading the records again`),this.recheckCreates(e,t,s,d)):(this.dv.progress.log(`${e.table}: ${n} of ${S(t.length)} records failed (status ${i||"none"}); sending one request for each record to find the records that fail`),this.oneByOne(e,n,t,s,d))}}async recheckCreates(e,n,t,s){let o=await this.plan.keys.findByKeys(e.table,n.map(a=>a.fileKey).filter(Boolean)),l=n.map(()=>({ok:!1,error:"not known"})),u=[];if(n.forEach((a,i)=>{let c=o.get(a.key);c?l[i]={ok:!0,id:String(c[e.primaryId]).toLowerCase()}:u.push(i)}),u.length){let a=await this.oneByOne(e,"CreateMultiple",u.map(i=>n[i]),u.map(i=>t[i]),s);u.forEach((i,c)=>l[i]=a[c])}return l}async oneByOne(e,n,t,s,d){let o=t.map((u,a)=>{let i=s[a];if(n==="CreateMultiple")return{method:"POST",path:e.entitySet,body:new pe(le(i)),headers:d};let c={};for(let[f,h]of Object.entries(i))f!==e.primaryId&&(c[f]=h);return{method:"PATCH",path:`${e.entitySet}(${u.id})`,body:new pe(le(c)),headers:{...d,"If-Match":"*"}}}),l=[];for(let u=0;u<o.length;u+=100){let a=await this.sendBatch(o.slice(u,u+100));for(let i of a)l.push(this.outcome(i))}return l}async run(){let e=this.dv.progress,n=Date.now(),t=async(d,o)=>{let l=Date.now();await o(),e.log(`${d}: done (${((Date.now()-l)/1e3).toFixed(1)} s)`)};await this.prepare(),await t("phase 1, creates",()=>this.creates()),this.stopNow()||await t("phase 2, updates",()=>this.updates()),this.stopNow()||await t("phase 3, files",()=>this.files()),this.stopNow()||await t("phase 4, links",()=>this.links()),this.stopNow()||await t("phase 5, deletes",()=>this.deletes()),this.done.stopped&&(e.log("stopped after a failure (--continue-on-error continues)"),this.markNotRun());let s=this.done;return e.log(`writes: ${S(s.created.size)} created, ${S(s.updated.size)} updated, ${S(s.deleted.size)} deleted, ${S(s.deactivated.size)} deactivated, ${S(s.failed.size)} failed, ${S(s.skipped.size)} skipped (${((Date.now()-n)/1e3).toFixed(1)} s)`),this.done}stopNow(){return this.done.failures.some(e=>!vt.includes(e.action))&&!this.opts.continueOnError&&(this.done.stopped=!0),this.done.stopped}markNotRun(){let e="not run: the run stopped after a failure (--continue-on-error continues)";for(let n of this.plan.tables)for(let t of[...n.records,...n.unmanaged])this.done.created.has(t)||this.done.updated.has(t)||this.done.deleted.has(t)||this.done.deactivated.has(t)||this.done.failed.has(t)||this.done.skipped.has(t)||t.action==="unchanged"||t.action==="none"||this.fail(t,"skip",{error:e})}async creates(){let e=this.plan.tables.flatMap(l=>l.records.filter(u=>u.action==="create")),n=e.length,t=0,s=0,d=l=>{for(let u of l.lookups.values())if(u?.pending&&(this.done.failed.has(u.pending)||this.done.skipped.has(u.pending)))return u.pending;return null},o=l=>[...l.lookups].every(([u,a])=>!a||l.later.has(u)||this.targetId(a)!==null);for(;e.length&&!this.stopNow();){for(let c of e){let f=d(c);f&&this.fail(c,"skip",{error:`depends on ${f.t.table} ${ce(f.keyOut)}, which failed`})}e=e.filter(c=>!this.done.skipped.has(c));let l=e.filter(o);if(!l.length&&e.length){let c=$t(e);this.dv.progress.log(`${S(c.length)} circles of lookups (${S(c.reduce((f,h)=>f+h.size,0))} records): their lookups inside the circle wait for phase 2`);for(let f of c)for(let h of f)for(let[m,y]of h.lookups)y?.pending&&f.has(y.pending)&&this.targetId(y)===null&&h.later.set(m,y);if(l=e.filter(o),!l.length){for(let f of e)for(let[h,m]of f.lookups)m&&this.targetId(m)===null&&f.later.set(h,m);l=e.filter(o)}if(!l.length){for(let f of e)this.fail(f,"skip",{error:"a lookup of the match key waits for a record that is not created"});return}}let u=new Set(l);e=e.filter(c=>!u.has(c)),t++;let a=new Map;for(let c of l)a.set(c.t.table,(a.get(c.t.table)??0)+1);this.dv.progress.log(`create wave ${t}: ${[...a].map(([c,f])=>`${S(f)} ${c}`).join(", ")}; ${S(e.length)} wait for a lookup target`);let i=[];for(let c of this.plan.tables){let f=l.filter(m=>m.t.table===c.t.table),h=this.batchOf(c);for(let m=0;m<f.length;m+=h)i.push({tp:c,recs:f.slice(m,m+h)})}await z(i,this.opts.parallel,async({tp:c,recs:f})=>{let h=await this.bulk(c.m,"CreateMultiple",f,f.map(m=>this.createBody(m)),c.headers);s+=f.length,this.dv.progress.log(`created ${S(s)} of ${S(n)} (${c.t.table})`),f.forEach((m,y)=>{let g=h[y];g.ok?(m.id=m.id??g.id??m.values.get(c.m.primaryId)??null,this.done.created.add(m)):this.fail(m,"create",{...g.status!==void 0?{status:g.status}:{},...g.code?{code:g.code}:{},error:g.error??"failed"})})})}for(let l of e){if(this.done.failed.has(l)||this.done.skipped.has(l))continue;let u=d(l);this.fail(l,"skip",{error:u?`depends on ${u.t.table} ${ce(u.keyOut)}, which failed`:"not run: the import stopped after a failure (--continue-on-error continues)"})}}async updates(){let e=[];for(let s of this.plan.tables){let d=[],o=[];for(let l of s.records){let u=this.done.created.has(l);if(!(l.action==="update"||u&&(l.later.size||l.binaries.some(c=>c.column.kind==="image")))||!l.id||this.done.failed.has(l)||this.done.skipped.has(l))continue;let a=[...l.lookups.values(),...l.later.values()].find(c=>c?.pending&&!this.targetId(c));if(a?.pending){this.fail(l,"skip",{error:`depends on ${a.pending.t.table} ${ce(a.pending.keyOut)}, which failed`});continue}let i=this.updateBody(l,u);if(!i){!u&&!l.binaries.some(c=>c.column.kind==="file")&&this.done.updated.add(l);continue}i[s.m.primaryId]=l.id,(l.binaries.some(c=>c.column.kind==="image")?o:d).push([l,i])}for(let[l,u]of[[d,!1],[o,!0]]){let a=this.batchOf(s,u);for(let i=0;i<l.length;i+=a){let c=l.slice(i,i+a);e.push({tp:s,recs:c.map(([f])=>f),bodies:c.map(([,f])=>f)})}}}let n=e.reduce((s,d)=>s+d.recs.length,0);n&&this.dv.progress.log(`update ${S(n)} records in ${S(e.length)} requests, ${this.opts.parallel} at the same time`);let t=0;await z(e,this.opts.parallel,async({tp:s,recs:d,bodies:o})=>{let l=await this.bulk(s.m,"UpdateMultiple",d,o,s.headers);t+=d.length,this.dv.progress.log(`updated ${S(t)} of ${S(n)} (${s.t.table})`),d.forEach((u,a)=>{let i=l[a];i.ok?this.done.created.has(u)||this.done.updated.add(u):this.fail(u,(this.done.created.has(u),"update"),{...i.status!==void 0?{status:i.status}:{},...i.code?{code:i.code}:{},error:i.error??"failed"})})})}async files(){let e=[];for(let n of this.plan.tables)for(let t of n.records)if(!(!t.id||this.done.failed.has(t)||this.done.skipped.has(t)))for(let s of t.binaries)s.column.kind==="file"&&e.push({tp:n,r:t,b:s});e.length&&this.dv.progress.log(`upload or remove ${S(e.length)} files`),await z(e,this.opts.parallel,async({tp:n,r:t,b:s})=>{try{s.bytes?await qe(this.dv,n.m,t.id,s.column,s.bytes,s.name??s.column.name,n.headers):await Je(this.dv,n.m,t.id,s.column,n.headers),this.done.created.has(t)||this.done.updated.add(t)}catch(d){if(!(d instanceof H)||d.status===void 0)throw d;this.fail(t,"upload",{status:d.status,...d.code?{code:d.code}:{},error:`${s.column.name}: ${d.message}`})}})}async links(){for(let e of this.plan.links){let n=this.plan.tables.find(s=>s.t.table===e.rel.entity1);this.dv.progress.log(`${e.spec.name}: ${S(e.link.length)} links to add, ${S(e.unlink.length)} to remove`);let t=await at(this.dv,e,this.opts.parallel,n?.headers??{},async s=>(await this.sendBatch(s.map(o=>({method:o.method,path:o.path,body:o.body,headers:o.headers??null})))).map(o=>{let l=this.outcome(o);return{status:o.status,...l.error?{error:l.error}:{}}}));this.done.links.set(e.spec.name,{linked:t.linked,unlinked:t.unlinked,skipped:0,failed:t.failed.length,failures:t.failed,removed:t.removed});for(let s of t.failed){let d=s.failed?.startsWith("not run")?"skip":e.unlink.includes(s)?"unlink":"link";this.done.failures.push({table:e.spec.name,action:d,key:{from:s.fromOut,to:s.toOut},name:null,error:s.failed??"failed"})}}}async deletes(){for(let e of Rt(this.plan.tables)){let n=[...e.records,...e.unmanaged].filter(t=>(t.action==="delete"||t.action==="deactivate")&&t.id);if(n.length){this.dv.progress.log(`${e.t.table}: ${e.t.delete.action==="deactivate"?"deactivate":"delete"} ${S(n.length)} records`);for(let t of Mt(e,n))if(e.t.delete.action==="deactivate"){let d=e.m.columns.get("statecode").stateOf.get(1),o=this.batchOf(e),l=[];for(let u=0;u<t.length;u+=o)l.push(t.slice(u,u+o));await z(l,this.opts.parallel,async u=>{let a=u.map(c=>({[e.m.primaryId]:c.id,statecode:1,...d!==void 0?{statuscode:d}:{}})),i=await this.bulk(e.m,"UpdateMultiple",u,a,e.headers);u.forEach((c,f)=>{let h=i[f];h.ok?this.done.deactivated.add(c):this.fail(c,"deactivate",{...h.status!==void 0?{status:h.status}:{},error:h.error??"failed"})})})}else{let s=[];for(let d=0;d<t.length;d+=100)s.push(t.slice(d,d+100));await z(s,this.opts.parallel,async d=>{let o=await this.sendBatch(d.map(l=>({method:"DELETE",path:`${e.m.entitySet}(${l.id})`,headers:e.headers})));d.forEach((l,u)=>{let a=this.outcome(o[u]);a.ok||a.status===404?this.done.deleted.add(l):this.fail(l,"delete",{...a.status!==void 0?{status:a.status}:{},...a.code?{code:a.code}:{},error:a.error??"failed"})})})}}}}};function $t(r){let e=new Set(r),n=a=>{let i=[];for(let c of a.lookups.values())c?.pending&&e.has(c.pending)&&c.pending.id===null&&i.push(c.pending);return i},t=new Map,s=new Map,d=new Set,o=[],l=[],u=0;for(let a of r){if(t.has(a))continue;let i=[],c=f=>{t.set(f,u),s.set(f,u),u++,o.push(f),d.add(f),i.push({r:f,edges:n(f),i:0})};for(c(a);i.length;){let f=i[i.length-1];if(f.i<f.edges.length){let m=f.edges[f.i++];t.has(m)?d.has(m)&&s.set(f.r,Math.min(s.get(f.r),t.get(m))):c(m);continue}i.pop();let h=i[i.length-1];if(h&&s.set(h.r,Math.min(s.get(h.r),s.get(f.r))),s.get(f.r)===t.get(f.r)){let m=new Set;for(;;){let y=o.pop();if(d.delete(y),m.add(y),y===f.r)break}(m.size>1||n(f.r).includes(f.r))&&l.push(m)}}}return l}function ce(r){return r&&typeof r=="object"?Object.values(r).map(String).join(", "):String(r)}function St(r,e){let n=e?q(e,r):null,t=Y(n)?n.table:r.targets[0];return(t?r.navigation.get(t):void 0)??(r.navigation.size===1?[...r.navigation.values()][0]:r.name)}function Rt(r){let e=new Set(r.map(o=>o.t.table)),n=new Map;for(let o of r){let l=new Set;for(let u of o.t.columns){let a=o.m.columns.get(u.name);if(a?.kind==="lookup")for(let i of a.targets)i!==o.t.table&&e.has(i)&&l.add(i)}n.set(o.t.table,l)}let t=[],s=new Set,d=(o,l)=>{if(!(s.has(o.t.table)||l.has(o.t.table))){l.add(o.t.table);for(let u of r)n.get(u.t.table)?.has(o.t.table)&&d(u,l);s.add(o.t.table),t.push(o)}};for(let o of r)d(o,new Set);return t}function Mt(r,e){let n=r.t.columns.map(a=>r.m.columns.get(a.name)).filter(a=>!!a&&a.kind==="lookup"&&a.targets.includes(r.t.table));if(!n.length)return[e];let t=new Set(e.map(a=>a.id)),s=new Map;for(let a of e){let i=[];for(let c of n){let f=a.row?q(a.row,c):null;Y(f)&&t.has(f.id)&&i.push(f.id)}s.set(a.id,i)}let d=new Map,o=(a,i)=>{if(i.has(a))return 0;i.add(a);let c=0;for(let f of s.get(a)??[])c=Math.max(c,o(f,i)+1);return c};for(let a of e)d.set(a.id,o(a.id,new Set));let l=Math.max(...d.values()),u=[];for(let a=l;a>=0;a--){let i=e.filter(c=>d.get(c.id)===a);i.length&&u.push(i)}return u}import{existsSync as ft,readdirSync as Ot,readFileSync as Pt,statSync as pt}from"node:fs";import{join as ht}from"node:path";function Ct(r){return De(r??null)}function Tt(r,e){let n={},t=e.bypassPlugins??(r.bypass.plugins==="none"?null:r.bypass.plugins),s=e.bypassSteps??r.bypass.steps,d={sync:"CustomSync",async:"CustomAsync",all:"CustomSync,CustomAsync"};return t&&d[t]&&(n["MSCRM.BypassBusinessLogicExecution"]=d[t]),s.length&&(n["MSCRM.BypassBusinessLogicExecutionStepIds"]=s.join(",")),r.bypass.flows&&(n["MSCRM.SuppressCallbackRegistrationExpanderJob"]="true"),n}async function we(r,e,n){let t=r.progress,s=tt(e),d=et(e,n.overlay,n.noOverlay);t.log(`import ${e}: ${s.tables.length} schema files${d?`, overlay ${d}`:""}${n.check?", --check":""}`);let o=new Ye(r,s);await j(t,"read the metadata",()=>o.load(),()=>`${S(o.tables.size)} tables`);let l=new Qe(o,r),u=new Xe(l),a=[],i=[],c=n.only?new Set(n.only.map(p=>p.toLowerCase())):null,f=o.dataTables();if(c){let p=new Set([...f.map(v=>v.table),...s.relationships.map(v=>v.name.toLowerCase())]),k=[...c].filter(v=>!p.has(v));if(k.length)throw K("usage",`--only: the schema has no table or relationship '${k[0]}'`)}let h=f.filter(p=>!c||c.has(p.table)),m=[],y=[],g=[],$=new Map;for(let p of h){let k=o.meta(p.table),v=Date.now(),M=Ne(e,p.table,m);if(M&&n.purpose!=="delete"&&Ae(e,M,m),M&&t.log(`read ${M.file}: ${S(M.records.length)} records (${((Date.now()-v)/1e3).toFixed(1)} s)`),!M){m.some(b=>b.startsWith(`${X}/${p.table}`))||m.push(`${X}/${p.table}.yaml: the table ${p.table} is in the schema and has no data file; run: ppdo-cli dv data export`);continue}let x=Ee(M.header,Fe(p,k.primaryId));x.length&&y.push(`${M.file}: ${x.join("; ")}`);let E={t:p,m:k,records:[],unmanaged:[],missingLines:0,headers:Tt(p,n)},w=new Map,O=[k.primaryId];for(let b of M.records){let P=b.file+(M.header.layout==="table"?` record ${b.index+1}`:""),C;try{C=await u.recordKey(p.table,b.values)}catch(N){if(N instanceof A){m.push(`${P}: ${N.message}`);continue}throw N}if(w.has(C.key)){m.push(`${P}: two records have the same GUID (${C.key.slice(2)})`);continue}if("$deleted"in b.values){m.push(`${P}: $deleted is not in a data file since issue 11; the deletion log in data/.deleted keeps deletes (run: ppdo-cli dv data export)`);continue}let D={t:p,m:k,src:b,key:C.key,fileKey:C,keyOut:Lt(O,b.values),name:ct(k,b.values),logged:!1,row:null,inScope:!1,id:null,action:"none",values:new Map,lookups:new Map,later:new Map,changes:{},binaries:[],overlay:new Set,nullsIgnored:0};{let N=!1;for(let _ of p.columns){if(!(_.name in b.values)){N=!0;continue}let ie=k.columns.get(_.name);if((_.name==="statecode"||_.name==="statuscode")&&b.values[_.name]===null&&m.push(`${P}: ${_.name} cannot be null`),!(ie.kind==="lookup"||ie.kind==="file"||ie.kind==="image"))try{Z(b.values[_.name],ie)}catch(fe){if(fe instanceof A)m.push(`${P}: ${fe.message}`);else throw fe}}N&&E.missingLines++}w.set(C.key,D),E.records.push(D)}if(p.delete.mode!=="off"){let b=Ge(e,p.table,m);if(b)for(let P of b.entries){let C={table:p.table,key:"g:"+P.id,parts:[{col:k.primaryId,value:P.id}]};if(w.has(C.key)){a.push(`${p.table} ${P.id}: the record is in the data file and in the deletion log; the import uses the data file and does not delete it`);continue}let D={[k.primaryId]:P.id};k.primaryName&&typeof P.name=="string"&&(D[k.primaryName]=P.name);let N={t:p,m:k,src:{file:b.file,index:P.index,values:D},key:C.key,fileKey:C,keyOut:{[k.primaryId]:P.id},name:ct(k,D),logged:!0,row:null,inScope:!1,id:null,action:"none",values:new Map,lookups:new Map,later:new Map,changes:{},binaries:[],overlay:new Set,nullsIgnored:0};w.set(C.key,N),E.records.push(N)}}$.set(p.table,w),g.push(E)}if(m.length)throw K("data_invalid","the data files are not valid",m);if(y.length)throw V("schema_mismatch","a data file header does not agree with the schema; the schema changed after the export",y,"run: ppdo-cli dv data export <folder> against the source environment, and commit the result");for(let p of g)p.missingLines&&a.push(`${p.t.table}: ${p.missingLines} records have no line for one or more columns of the schema; the import does not change those columns`);xt(e,s,a),d&&await Dt(e,d,s,u,g,$,a);let I=new Map;await z(g,4,async p=>{I.set(p.t.table,await j(t,`read the target ${p.t.table}`,()=>ot(r,o,l,p.t),k=>`${S(k.length)} records in the scope`))});let R=new Map;for(let p of g){let k=I.get(p.t.table)??[];await l.seed(p.t.table,k);let v=new Map;for(let M of k)v.set("g:"+String(M[p.m.primaryId]).toLowerCase(),M);R.set(p.t.table,v)}for(let p of g){let k=R.get(p.t.table);for(let v of p.records){let M=k.get(v.key);M&&(v.row=M,v.inScope=!0,v.id=String(M[p.m.primaryId]).toLowerCase())}}await z(g,4,async p=>{if(!p.t.filter&&!p.t.fetchXmlFilter)return;let k=p.records.filter(x=>!x.row&&x.fileKey);if(!k.length)return;let v=await nt(l,p.t,p.m),M=await j(t,`read ${S(k.length)} records of ${p.t.table} that are not in the scope, by their GUID`,()=>l.findByKeys(p.t.table,k.map(x=>x.fileKey),v),x=>`${S(x.size)} found`);for(let x of k){let E=M.get(x.key);E&&(x.row=E,x.id=String(E[p.m.primaryId]).toLowerCase())}});let L=n.purpose==="delete";if(L||await j(t,"resolve the lookups",()=>Ft(l,u,g,$,a,m)),m.length)throw V("unresolved_lookup","a lookup has no target in the environment",m,"add the target to the environment or to the data, or set missingLookup: skip for the column");for(let p of g){Et(p,R.get(p.t.table),a);let k=v=>p.records.concat(p.unmanaged).filter(M=>M.action===v).length;t.log(`compare ${p.t.table}: ${S(k("create"))} to create, ${S(k("update"))} to update, ${S(k("delete")+k("deactivate"))} to delete or deactivate, ${S(k("unchanged"))} unchanged`)}if(L||await j(t,"compare the files and images",()=>Nt(r,e,g,m)),m.length){let p=m[0].startsWith("[file_too_large]")?"file_too_large":m[0].startsWith("[file_name_unsupported]")?"file_name_unsupported":"file_missing";throw K(p,"a file of a file column or an image column cannot be imported",m.map(k=>k.replace(/^\[[a-z_]+\] /,"")))}let F=s.relationships.filter(p=>!c||c.has(p.name.toLowerCase())),T=[];for(let p of F){let k=L?[]:m,v=await j(t,`compare the links of ${p.name}`,()=>it(r,e,o,l,u,p,$,R,k,a),M=>M?`${S(M.link.length)} to link, ${S(M.unlink.length)} to unlink, ${S(M.unchanged)} unchanged`:"none");v&&T.push(v)}if(m.length)throw V("unresolved_lookup","a link has no target in the environment",m);let B=p=>p.action==="delete"||p.action==="deactivate";if(L){for(let p of g)for(let k of[...p.records,...p.unmanaged])B(k)||(k.action!=="none"&&(k.action="unchanged"),k.values.clear(),k.lookups.clear(),k.later.clear(),k.binaries=[],k.changes={});for(let p of T)p.link=[]}else{let p=0,k=0;for(let v of g)for(let M of[...v.records,...v.unmanaged])B(M)&&(M.action="none",delete M.reason,p++);for(let v of T)k+=v.unlink.length,v.unlink=[];(p||k)&&a.push(`the delete modes give ${p} records to delete or deactivate and ${k} links to remove; the import never deletes: run ppdo-cli dv data delete`)}for(let p of g){let k=p.records.filter(v=>v.action==="delete"||v.action==="deactivate").length+p.unmanaged.filter(v=>v.action==="delete"||v.action==="deactivate").length;k&&p.t.delete.action==="delete"&&i.push(`${p.t.table}: ${k} deletes`),k&&p.t.delete.action==="delete"&&p.m.cascades.length&&a.push(`${p.t.table}: a delete also deletes the child records of these relationships (cascade): ${p.m.cascades.join(", ")}`)}for(let p of T)p.unlink.length&&i.push(`${p.spec.name}: ${p.unlink.length} link removals`);let ue=g.filter(p=>Object.keys(p.headers).length&&[...p.records,...p.unmanaged].some(k=>k.action!=="unchanged"&&k.action!=="none"));for(let p of ue)i.push(`${p.t.table}: bypass`);if(!n.check&&i.length&&r.client.target.mode!=="full")throw new Q(`blocked: the plan has requests that need mode 'full' (${i.join("; ")}); mode is '${r.client.target.mode}'`,{service:"dataverse",code:"blocked",hint:Re(r.client.target)});n.check&&i.length&&r.client.target.mode!=="full"&&a.push(`a run without --check needs mode 'full' for: ${i.join("; ")}`);for(let p of a)t.log(`warning: ${p}`);return{schema:s,model:o,keys:l,overlay:d,tables:g,links:T,warnings:a,needsFull:i}}function Lt(r,e){let n={};for(let t of r)n[t]=e[t]??null;return n}function ct(r,e){let n=r.primaryName?e[r.primaryName]:void 0;return typeof n=="string"?n:n instanceof Ie?n.text:null}function xt(r,e,n){let t=ht(r,X);if(ft(t))for(let s of It(t)){if(!s.endsWith(".yaml"))continue;let d=s.slice(0,-5);e.byName.get(d)||n.push(`${X}/${s}: the schema has no table '${d}'; the import ignores the file`)}}function It(r){try{return pt(r).isDirectory()?Ot(r).sort():[]}catch{return[]}}async function Dt(r,e,n,t,s,d,o){let l=[],u=Ze(r,e,n,l);for(let a of u){let i=s.find(m=>m.t.table===a.table);if(!i)continue;let c=d.get(a.table),f=[i.m.primaryId],h=new Set;for(let m of a.records){let y=`${m.file} record ${m.index+1}`,g;try{g=await t.recordKey(a.table,m.values)}catch(R){if(R instanceof A){l.push(`${y}: ${R.message}`);continue}throw R}if(h.has(g.key)){l.push(`${y}: two records have the same GUID`);continue}h.add(g.key);let $=c.get(g.key);if(!$){l.push(`${y}: no record of the base file has the GUID ${g.key.slice(2)}`);continue}if($.logged){o.push(`${y}: the record is in the deletion log; the import ignores the overlay record`);continue}let I=Object.keys(m.values).filter(R=>!f.includes(R));I.length||l.push(`${y}: the record has no column to change`);for(let R of I){let L=i.t.columns.find(T=>T.name===R);if(R==="$deleted")continue;if(!L){l.push(`${y}: '${R}' is not in columns of the schema`);continue}let F=i.m.columns.get(R);if(F.kind==="file"||F.kind==="image"||re(i.t.table,R)){l.push(`${y}: '${R}' is a ${re(i.t.table,R)?"base64 file":F.kind} column; version 1 has no overlay value for it`);continue}if(F.kind!=="lookup")try{Z(m.values[R],F)}catch(T){if(T instanceof A)l.push(`${y}: ${T.message}`);else throw T;continue}$.src.values={...$.src.values,[R]:m.values[R]},$.overlay.add(R)}}}if(l.length)throw K("overlay_invalid",`the overlay '${e}' is not valid`,l)}async function Ft(r,e,n,t,s,d){let o=[];for(let c of n)for(let f of c.records)if(!(f.logged||!f.src))for(let h of c.t.columns){let m=c.m.columns.get(h.name);if(m.kind!=="lookup"||!(h.name in f.src.values))continue;let y=f.src.values[h.name];if(y===null||y===""){f.lookups.set(h.name,null);continue}try{o.push({rec:f,col:h,key:await e.lookupKey(m,y)})}catch(g){if(g instanceof A)d.push(`${f.src.file}: ${JSON.stringify(f.keyOut)}: ${g.message}`);else throw g}}let l=new Map,u=(c,f)=>`${c}|${f}`,a=async(c,f)=>{let h=f.filter(g=>!l.has(u(c,g.key)));if(!h.length)return;let m=t.get(c),y=[];for(let g of h){let $=m?.get(g.key);$?.id?l.set(u(c,g.key),{table:c,id:$.id,pending:null}):$&&!$.logged?l.set(u(c,g.key),{table:c,id:null,pending:$}):y.push(g)}if(y.length){await r.ensure(c,y.map(g=>g.key.slice(2)));for(let g of y){let $=r.get(c,g.key.slice(2));l.set(u(c,g.key),$?{table:c,id:$.id,pending:null}:null)}}},i=new Map;for(let c of o){let f=i.get(c.key.table);f||i.set(c.key.table,f=[]),f.push(c.key)}for(let[c,f]of i)await a(c,f);for(let c of o){let f=l.get(u(c.key.table,c.key.key))??null;if(f){c.rec.lookups.set(c.col.name,f);continue}let h=`${c.rec.t.table} ${JSON.stringify(c.rec.keyOut)} ${c.col.name}: no ${c.key.table} with the GUID ${c.key.key.slice(2)}`;c.col.missingLookup==="skip"?(s.push(`${h} (missingLookup: skip; the column is not written)`),c.rec.lookups.delete(c.col.name),c.rec.skippedLookups=(c.rec.skippedLookups??0)+1):d.push(h)}}function Et(r,e,n){let{t,m:s}=r,d=new Set(r.records.map(o=>o.key));for(let o of r.records){let l=o.src;if(o.logged){if(!o.row){o.action="none";continue}if(!o.inScope){o.action="none",t.delete.mode!=="off"&&n.push(`${t.table} ${JSON.stringify(o.keyOut)}: the record is in the deletion log, but it is not in the scope in the environment; the import does not delete it`);continue}if(t.delete.mode==="off"){o.action="none",n.push(`${t.table} ${JSON.stringify(o.keyOut)}: the record is in the deletion log, but the table has no delete mode; the import does not delete it`);continue}dt(o,t,"manifest");continue}if(!o.row){o.action="create";for(let i of t.columns){if(!(i.name in l.values))continue;let c=s.columns.get(i.name);if(c.kind==="file"||c.kind==="image"||c.kind==="lookup")continue;let f=Z(l.values[i.name],c);f===null&&i.nullValues==="ignore"||o.values.set(i.name,f)}o.values.set(s.primaryId,o.key.slice(2));for(let i of t.columns)s.columns.get(i.name).kind==="lookup"&&o.lookups.get(i.name)===null&&i.nullValues==="ignore"&&o.lookups.delete(i.name);continue}let u=o.row;if(t.write==="create"){o.action="unchanged",o.lookups.clear();continue}let a=new Map(o.lookups);o.lookups.clear();for(let i of t.columns){if(!(i.name in l.values)||i.write==="create")continue;let c=s.columns.get(i.name);if(c.kind==="file"||c.kind==="image")continue;let f=q(u,c),h=o.overlay.has(i.name)?{overlay:!0}:{};if(c.kind==="lookup"){if(!a.has(i.name))continue;let y=a.get(i.name)??null;if(y===null){if(f===null)continue;if(i.nullValues==="ignore"){o.nullsIgnored++;continue}o.lookups.set(i.name,null),o.changes[i.name]={from:ee(f),to:null,...h};continue}if(Y(f)&&y.id!==null&&f.id===y.id)continue;o.lookups.set(i.name,y),o.changes[i.name]={from:ee(f),to:y.id??`(new) ${JSON.stringify(y.pending?.keyOut)}`,...h};continue}let m=Z(l.values[i.name],c);if(!We(f,m)){if(m===null&&i.nullValues==="ignore"){o.nullsIgnored++;continue}o.values.set(i.name,m),o.changes[i.name]=re(t.table,i.name)?{from:ut(f),to:ut(m),...h}:{from:ee(f),to:ee(m),...h}}}o.action=o.values.size||o.lookups.size?"update":"unchanged"}for(let[o,l]of e){if(d.has(o))continue;let u=String(l[s.primaryId]).toLowerCase(),a=s.primaryName?l[s.primaryName]:null,i={t,m:s,src:null,key:o,fileKey:null,keyOut:{[s.primaryId]:u},name:typeof a=="string"?a:null,logged:!1,row:l,inScope:!0,id:u,action:"none",values:new Map,lookups:new Map,later:new Map,changes:{},binaries:[],overlay:new Set,nullsIgnored:0};t.delete.mode==="mirror"&&dt(i,t,"mirror"),r.unmanaged.push(i)}r.unmanaged.length&&t.delete.mode!=="mirror"&&n.push(`${t.table}: ${r.unmanaged.length} records are in the scope in the environment and are not in the data file (unmanaged)`)}function dt(r,e,n){if(e.delete.action==="deactivate"){let t=r.row?.statecode;if(t!=null&&String(t)!=="0"){r.action="none";return}r.action="deactivate"}else r.action="delete";r.reason=n}async function Nt(r,e,n,t){for(let s of n){let d=s.t.columns.filter(a=>{let i=s.m.columns.get(a.name);return i.kind==="file"||i.kind==="image"});if(!d.length)continue;let o=[];for(let a of s.records)if(!(!a.row||a.logged))for(let i of d){let c=q(a.row,s.m.columns.get(i.name));G(c)&&o.push(c.id)}let l=o.length?await je(r,o):new Map,u=[];for(let a of s.records)if(!(a.logged||a.action==="none"||!a.src))for(let i of d){if(!(i.name in a.src.values)||i.write==="create"&&a.row||s.t.write==="create"&&a.row)continue;let c=s.m.columns.get(i.name),f=a.src.values[i.name],h=a.row?q(a.row,c):null,m=`${a.src.file}: ${JSON.stringify(a.keyOut)} ${i.name}`;if(f===null){if(h===null)continue;if(i.nullValues==="ignore"){a.nullsIgnored++;continue}a.binaries.push({column:c,bytes:null,name:null}),a.changes[i.name]={from:G(h)?{name:h.name,size:l.get(h.id)?.size??null}:{size:null},to:null};continue}let y=Ct(f),g=y?.$file;if(!y||typeof g!="string"||!g){t.push(`[file_missing] ${m}: the value must be { $file: <name> }`);continue}let $=ht(e,he,s.t.table,g);if(!xe(g)||!ft($)){t.push(`[file_missing] ${m}: ${he}/${s.t.table}/${g} is not in the folder`);continue}let I=pt($).size;if(I>Ke){t.push(`[file_too_large] ${m}: ${g} is ${I} bytes; version 1 handles files to 40 MB`);continue}let R=c.kind==="file"?typeof y.name=="string"?y.name:g:null;if(R!==null&&_e(R)&&!zt){t.push(`[file_name_unsupported] ${m}: the file name '${R}' has a character that is not ASCII`);continue}u.push(async()=>{let L=Pt($);if(h!==null&&a.id){if(G(h)){let T=l.get(h.id);if(T&&T.size===L.length&&(T.name??h.name)===R){let B=await me(r,s.m,a.id,c);if(B&&B.equals(L))return}}else if(Ve(h)){let T=await me(r,s.m,a.id,c);if(T&&T.equals(L))return}}a.binaries.push({column:c,bytes:L,name:R});let F=G(h)?l.get(h.id)?.size??null:null;a.changes[i.name]=c.kind==="file"?{from:G(h)?{name:h.name,size:F}:null,to:{name:R,size:L.length}}:{from:h===null?null:{size:null},to:{size:L.length}}})}await z(u,8,a=>a());for(let a of s.records)a.binaries.length&&a.action==="unchanged"&&(a.action="update")}}function ut(r){return typeof r=="string"?{size:Buffer.from(r,"base64").length}:null}var zt=!0;function de(r){if(typeof r!="string")return null;let e=r.split(",").map(n=>n.trim()).filter(n=>n);return e.length?e:null}function oe(r,e,n,t,s){if(r==null)return s;let d=Number(r);if(!Number.isInteger(d)||d<n||d>t)throw new J(`argument ${e}: must be ${n} to ${t}`);return d}function se(r){let e=r.args.folder;if(typeof e!="string"||!e)throw new J("the following arguments are required: folder");return e}async function be(r,e,n){let t=typeof r.args.logFile=="string"?r.args.logFile:null,s=new Ue(r.verbose,t,e),d=r.log.bind(r);r.log=o=>{d(o),s.http(o)};try{let o=await n(s);o!==void 0&&s.raw("result",JSON.stringify(o,null,2))}catch(o){throw o instanceof H?s.raw("error",ve(o.envelope())):o instanceof Error&&s.raw("error",o.stack??o.message),o}finally{s.retries&&s.log(`${s.retries} requests were sent again (throttling, a time limit or a server error)`),s.log(`end (peak memory ${Math.round(Math.max(s.peakMemory,process.memoryUsage().rss)/1048576)} MB)`),s.close()}}async function Gn(r){let e=se(r),n=oe(r.args.parallel,"--parallel",1,16,8),t=!!r.args.check;await be(r,"dv data export",async s=>{let d=new W(r,await U(r),"R",s),o=await st(d,e,{only:de(r.args.only),check:t,parallel:n});if(await r.emit(o),t&&(o.tables.some(l=>l.written)||o.relationships.some(l=>l.written)||o.warnings.some(l=>l.startsWith("would remove"))))throw s.raw("result",JSON.stringify(o,null,2)),ae("out_of_date","one or more data files are out of date","run it again without --check to update the folder");return o})}var _t=/,/;function yt(r){let e=typeof r.args.bypassPlugins=="string"?r.args.bypassPlugins:null,n=typeof r.args.bypassStep=="string"?r.args.bypassStep:null,t=null;if(n){t=n.split(_t).map(d=>d.trim()).filter(d=>d);let s=t.find(d=>!Oe(d));if(s)throw new J(`--bypass-step takes plugin step ids, got '${s}'`);t=t.map(d=>d.toLowerCase())}return{plugins:e,steps:t}}function kt(r,e){let n={action:e,key:r.keyOut,name:r.name};return r.id&&e!=="create"&&(n.id=r.id),e==="update"&&(n.columns=r.changes),(e==="delete"||e==="deactivate")&&(n.reason=r.reason),n}function mt(r,e,n,t){let s={create:0,update:0,link:0,unchanged:0,unmanaged:0,skipped:0,failed:0},d=e.tables.map(l=>{let u={create:0,update:0,unchanged:0,unmanaged:0,skipped:0,failed:0},a=[],i=0,c=0;for(let f of[...l.records,...l.unmanaged]){if(c+=f.nullsIgnored,!f.src&&f.action==="none"){u.unmanaged++;continue}if(f.action==="unchanged"){u.unchanged++;continue}f.action!=="create"&&f.action!=="update"||(n?n.failed.has(f)?u.failed++:n.skipped.has(f)?u.skipped++:n.created.has(f)?u.create++:n.updated.has(f)&&u.update++:u[f.action]++,(t===null||i<t)&&(a.push(kt(f,f.action)),i++))}for(let f of Object.keys(u))s[f]+=u[f];return{table:l.t.table,...u,...c?{nulls_ignored:c}:{},changes:a}}),o=e.links.map(l=>{let u=n?.links.get(l.spec.name),a={name:l.spec.name,link:u?u.linked:l.link.length,unchanged:l.unchanged,skipped:u?u.skipped:0,failed:u?u.failed:0};s.link+=a.link,s.skipped+=a.skipped,s.failed+=a.failed;let i=[];for(let c of l.link){if(t!==null&&i.length>=t)break;i.push({action:"link",from:c.fromOut,to:c.toOut})}return{...a,changes:i}});return{folder:r,overlay:e.overlay,checked_only:n===null,summary:s,tables:d,relationships:o,failures:n?.failures??[],warnings:e.warnings}}function gt(r,e,n){let t={delete:0,deactivate:0,unlink:0,failed:0},s=e.tables.map(o=>{let l={delete:0,deactivate:0,failed:0},u=[];for(let a of[...o.records,...o.unmanaged])a.action!=="delete"&&a.action!=="deactivate"||(n?n.failed.has(a)?l.failed++:n.deleted.has(a)?l.delete++:n.deactivated.has(a)&&l.deactivate++:l[a.action]++,u.push(kt(a,a.action)));return t.delete+=l.delete,t.deactivate+=l.deactivate,t.failed+=l.failed,{table:o.t.table,mode:o.t.delete.mode,...l,changes:u}}),d=e.links.map(o=>{let l=n?.links.get(o.spec.name),u={name:o.spec.name,mode:o.spec.delete.mode,unlink:l?l.unlinked:o.unlink.length,failed:l?l.failed:0};return t.unlink+=u.unlink,t.failed+=u.failed,{...u,changes:o.unlink.map(a=>({action:"unlink",from:a.fromOut,to:a.toOut,reason:a.reason}))}});return{folder:r,checked_only:n===null,summary:t,tables:s,relationships:d,failures:n?.failures??[],warnings:e.warnings}}function jt(r,e,n,t,s){let d=[];for(let l of n.tables)for(let u of[...l.records,...l.unmanaged]){let a=t.deleted.has(u)?"delete":t.deactivated.has(u)?"deactivate":null;!a||!u.id||d.push({table:l.t.table,id:u.id,name:u.name,action:a,reason:u.reason})}let o=[];for(let[l,u]of t.links)for(let a of u.removed)o.push({relationship:l,from:a.from.id,to:a.to.id,reason:a.reason});return JSON.stringify({folder:r,environment:e,time:s,records:d,links:o},null,2)+`
|
|
3
|
+
`}function qt(r,e){Kt(At(r),{recursive:!0}),Bt(r,e,"utf8")}function wt(r,e,n){let t=r.failures.filter(s=>s.action!=="skip").length;if(r.failures.length)throw V("rows_failed",`${t} records failed and ${r.failures.length-t} were not sent`,[],"see failures in the output"+(e?"":"; --continue-on-error keeps going after a failure")+`; the ${n} can run again`)}async function Hn(r){let e=r.args,n=se(r),t=!!e.check,s=oe(e.batchSize,"--batch-size",1,1e3,100),d=oe(e.parallel,"--parallel",1,16,8),o=e.overlay,l=typeof o=="string"?o:null,u=o===!1,a=yt(r);await be(r,"dv data import",async i=>{let c=new W(r,await U(r),"R",i),f=await we(c,n,{only:de(e.only),overlay:l,noOverlay:u,purpose:"import",check:t,bypassPlugins:a.plugins,bypassSteps:a.steps}),h=Le(e);if(t){let g=mt(n,f,null,h);await r.emit(g),i.raw("result",JSON.stringify(g,null,2));let $=g.summary,I=($.create??0)+($.update??0)+($.link??0);if(I)throw ae("changes_pending",`the plan has ${I} changes`,"run it again without --check to apply the changes");return}i.log(`write the changes: --batch-size ${s}, --parallel ${d}${e.continueOnError?", --continue-on-error":""}`);let m=await new ne(c,f,{batchSize:s,parallel:d,continueOnError:!!e.continueOnError}).run(),y=mt(n,f,m,h);await r.emit(y),i.raw("result",JSON.stringify(y,null,2)),wt(m,!!e.continueOnError,"import")})}function Jt(r,e){let n=[`dv data delete in ${r}:`];for(let t of e.tables){let s=[...t.records,...t.unmanaged].filter(o=>o.action==="delete"||o.action==="deactivate");if(!s.length)continue;let d=t.t.delete.action==="deactivate"?"deactivate":"delete";n.push(` ${t.t.table}: ${d} ${s.length} records (mode ${t.t.delete.mode})`);for(let o of s.slice(0,20))n.push(` ${o.id} ${o.name??""} (${o.reason})`.trimEnd());s.length>20&&n.push(` ... and ${s.length-20} more (--check lists each one)`)}for(let t of e.links)t.unlink.length&&n.push(` ${t.spec.name}: remove ${t.unlink.length} links (mode ${t.spec.delete.mode})`);return n}async function Ut(r,e){if(!$e(e))throw new Q("dv data delete needs a confirmation: no person at a terminal can give it",{hint:"run it at a terminal, or give --yes (for a pipeline, after a review of --check)"});if((e??{stderr:process.stderr}).stderr.write(r.join(`
|
|
4
|
+
`)+`
|
|
5
|
+
Type 'delete' to confirm: `),(await Se((e??{stdin:process.stdin}).stdin)).trim()!=="delete")throw new Q("not confirmed; nothing was deleted")}async function Qn(r){let e=r.args,n=se(r),t=!!e.check,s=oe(e.batchSize,"--batch-size",1,1e3,100),d=oe(e.parallel,"--parallel",1,16,8),o=typeof e.deleteLogFile=="string"?e.deleteLogFile:null,l=yt(r);await be(r,"dv data delete",async u=>{let a=new W(r,await U(r),"R",u),i=await we(a,n,{only:de(e.only),overlay:null,noOverlay:!0,purpose:"delete",check:t,bypassPlugins:l.plugins,bypassSteps:l.steps}),c=gt(n,i,null),f=c.summary,h=(f.delete??0)+(f.deactivate??0)+(f.unlink??0);if(t){if(await r.emit(c),u.raw("result",JSON.stringify(c,null,2)),h)throw ae("changes_pending",`the plan has ${h} deletes, deactivates and link removals`,"run it again without --check to delete them");return}if(!h)return await r.emit(c),c;e.yes?u.log("--yes: no confirmation"):await Ut(Jt(a.origin,i)),u.log(`delete: --batch-size ${s}, --parallel ${d}`);let m=new ne(a,i,{batchSize:s,parallel:d,continueOnError:!0}),y;try{y=await m.run()}finally{o&&qt(o,jt(n,a.origin,i,m.done,new Date().toISOString()))}let g=gt(n,i,y);await r.emit(g),u.raw("result",JSON.stringify(g,null,2)),wt(y,!0,"delete")})}async function Xn(r){let{runConvert:e}=await import("./convert-ILMJ2HHN.js"),n=r.args.source;if(typeof n!="string"||!n)throw new J("the following arguments are required: source");let t=typeof r.args.cmtSchema=="string"?r.args.cmtSchema:null,s=new W(r,await U(r),"R");await r.emit(await e(s,n,se(r),{cmtSchema:t,force:!!r.args.force}))}async function Yn(r){let{runInit:e}=await import("./init-X2VEK4T2.js"),n=de(r.args.table);if(!n)throw new J("the following arguments are required: --table");let t=new W(r,await U(r));await r.emit(await e(t,se(r),n))}export{Ut as confirmDelete,Xn as convertData,Qn as deleteData,jt as deleteLog,gt as deleteOutput,Jt as deleteSummary,Gn as exportData,Hn as importData,mt as importOutput,Yn as initData};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
+
import{e as Z}from"./chunk-VC7ADQ6E.js";import"./chunk-T4IH34D7.js";import{G as T,H as Q,a as B,d as b,e as q,f as u,g as L,h as E,k as _,l as H,n as J,s as K,t as W,u as X,v as P,x as V,y as Y,z as k}from"./chunk-BG2OIOSN.js";import"./chunk-UCTMKA2J.js";import{a as v,b as O,d as I,e as N}from"./chunk-FOEBNCSD.js";import"./chunk-BALEFXOL.js";import"./chunk-J4R6QXW7.js";import{b as F}from"./chunk-2IUXH534.js";import{e as A}from"./chunk-S4KF5Z3S.js";import{a as z,b as R,d as U}from"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";import{writeFileSync as dt}from"node:fs";import{basename as ut}from"node:path";import{crc32 as mt,deflateRawSync as pt}from"node:zlib";var it=500,tt=25,G=["required","dependent"],rt=["componenttype","componentobjectid","componentparentid","componentbasesolutionid"],ft=["dependencyid","dependencytype",...G.flatMap(t=>rt.map(e=>t+e))].join(","),et="($select=_topsolutionid_value)",gt=`requiredcomponentnodeid${et},dependentcomponentnodeid${et}`,yt=["PicklistAttributeMetadata","MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata","BooleanAttributeMetadata"],at=[["Attributes","columns"],["Keys","keys"],["OneToManyRelationships","relationships"],["ManyToOneRelationships","relationships"],["ManyToManyRelationships","relationships"]];function ht(t){let e=b(t.solution)||b(t.required)||b(t.dependent);if(!e&&t.all&&!t.includeSystem)throw new R("--all with no filter reads every dependency row in the environment",{hint:"filter with --solution, --required or --dependent, or pass --include-system"});if(t.type!==void 0&&t.type!==null&&!e)throw new R("--type needs --solution, --required or --dependent")}function wt(t,e){let n=e.filter(o=>!O(o));if(n.length)throw new R(`not a component id: '${n[0]}'`);let s=e.map(o=>`'${I(o)}'`).join(",");return`Microsoft.Dynamics.CRM.In(PropertyName='${t}',PropertyValues=[${s}])`}function bt(t,e,n=it,s=[]){let o=[];for(let r of G){let m=r==="required"?"dependent":"required",g=e!=null?` and ${m}componenttype eq ${Math.trunc(e)}`:"",y=t[r]??[];for(let p=0;p<y.length;p+=n)o.push(wt(`${r}componentobjectid`,y.slice(p,p+n))+g);for(let p of s){if(!O(p))throw new R(`not a solution id: '${p}'`);o.push(`${r}componentbasesolutionid eq ${I(p)}${g}`)}}return o}var Tt=["membership","base-solution","component"];function $t(t,e,n){return n?"component":e.has(String(q(u(t,"requiredcomponentobjectid"),"")).toLowerCase())||e.has(String(q(u(t,"dependentcomponentobjectid"),"")).toLowerCase())?"membership":"base-solution"}function nt(t,e,n=null){let s={dependencyid:u(t,"dependencyid"),dependencytype:u(t,"dependencytype")};n&&(s.found_by=n);for(let o of G){for(let g of rt)s[o+g]=u(t,o+g);let r=u(t,o+"componentbasesolutionid"),m=u(L(u(t,o+"componentnodeid")),"_topsolutionid_value");s[o+"componentbasesolution"]=e.get(String(q(r,"")).toLowerCase())??null,s[o+"componenttopsolutionid"]=m,s[o+"componenttopsolution"]=e.get(String(q(m,"")).toLowerCase())??null}return s}function Rt(t){let e={};for(let[n,s]of at){let o=e[s]??=[];for(let r of E(u(t,n)))b(u(r,"MetadataId"))&&o.push(r.MetadataId)}return e}function St(t){return t.filter(e=>b(u(L(u(e,"OptionSet")),"MetadataId"))&&!b(e.OptionSet.IsGlobal)).map(e=>e.OptionSet.MetadataId)}function Mt(t){let e=new Set;for(let n of E(u(t,"ManyToManyRelationships")))b(u(n,"IntersectEntityName"))&&e.add(n.IntersectEntityName);return _(e,n=>n)}async function xt(t,e,n){let{find:s}=await import("./solution-CNBNIS7Z.js"),o=new Set,r=new Set,m=[];for(let l of n){let c=await s(t,e,l);b(u(c,"ismanaged"))&&m.push(c.solutionid);let[a]=await k(t,e,"solutioncomponents",[["$select","objectid,componenttype,rootcomponentbehavior"],["$filter",`_solutionid_value eq ${c.solutionid}`]],null,null);for(let i of a)o.add(String(i.objectid).toLowerCase()),u(i,"componenttype")===1&&u(i,"rootcomponentbehavior")===0&&r.add(String(i.objectid).toLowerCase())}let g=o.size,y={columns:0,keys:0,relationships:0,intersect_tables:0,choices:0,forms:0,views:0},p=[],h=at.map(([l])=>`${l}($select=MetadataId${l.startsWith("ManyToMany")?",IntersectEntityName":""})`).join(","),f=(l,c)=>{let a=H(c.map(i=>i.toLowerCase()).filter(i=>!o.has(i)));for(let i of a)o.add(i);y[l]=(y[l]??0)+a.length},C=[],x=[...r].map(l=>[`EntityDefinitions(${l})`,!1]),$=new Set;for(;x.length;){let[l,c]=x.shift(),a;try{a=P(await X(t,e,"GET",l,{params:[["$select","LogicalName"],["$expand",h]]}))}catch(i){if(i instanceof U){C.push(l);continue}throw i}if(!$.has(a.LogicalName)){$.add(a.LogicalName),p.push(a.LogicalName),c&&f("intersect_tables",[a.MetadataId]);for(let[i,d]of Object.entries(Rt(a)))f(i,d);for(let i of Mt(a))$.has(i)||x.push([`EntityDefinitions(LogicalName=${N(v(i,"table"))})`,!0])}}let w=p.flatMap(l=>yt.map(c=>({method:"GET",path:`EntityDefinitions(LogicalName=${N(l)})/Attributes/Microsoft.Dynamics.CRM.${c}?$select=LogicalName&$expand=OptionSet($select=MetadataId,IsGlobal)`})));for await(let[,l,c]of Q(t,e,w,!1,!0))l.forEach((a,i)=>{let d=c[i];if(!d||d.status!==200)throw new z(`couldn't list the choices of a table: ${a.path}`,{service:"dataverse",...d?{status:d.status}:{},hint:(typeof d?.body=="string"?d.body:Z(d?.body??null)).slice(0,300)});f("choices",St(E(u(L(d.body),"value"))))});for(let[l,c,a,i]of[["systemforms","objecttypecode","formid","forms"],["savedqueries","returnedtypecode","savedqueryid","views"]])for(let d=0;d<p.length;d+=tt){let S=p.slice(d,d+tt).map(j=>`${c} eq ${N(v(j,"table"))}`).join(" or "),[M]=await k(t,e,l,[["$select",a],["$filter",S]],null,null);f(i,M.map(j=>j[a]))}return[[...o],{solutions:n,components:g,full_tables:r.size,added:y,managed:m,missing_tables:C}]}function ct(t){return[["$select",ft],["$expand",gt],...t?[["$filter",t]]:[]]}async function jt(t,e,n){let s=V(`odata.maxpagesize=${n?Math.min(B,n):B}`),o=[];for await(let r of Y(t,"dependencies",e,s))if(o=o.concat(E(P(r).value)),n!==null&&o.length>=n)break;return o}async function qt(t,e,n){let s=new Map;for(let o of e){for(let r of await jt(t,ct(o),n===null?null:n+1-s.size))s.has(r.dependencyid)||s.set(r.dependencyid,r);if(n!==null&&s.size>n)return[s,!0]}return[s,!1]}async function Et(t,e,n,s,o,r){let[m]=await k(t,e,"solutions",[["$select","solutionid,uniquename"]],null,null),g=new Map(m.map(h=>[String(h.solutionid).toLowerCase(),h.uniquename])),y=new Set;if(o)for(let h of Object.values(s))for(let f of h??[])y.add(f.toLowerCase());let p=Object.keys(s).length>0;return _(n.keys(),h=>h).map(h=>{let f=n.get(h);return p?nt(f,g,$t(f,y,r)):nt(f,g)})}function ot(t,e){if(t==null)return null;let n=t;if(n.length<2)throw new R(`argument ${e}: expected 2 arguments`,{hint:"run: ppdo-cli dv dependency list --help"});if(n.length>2)throw new R(`unrecognized arguments: ${n.slice(2).join(" ")}`,{hint:"run: ppdo-cli --help"});return[n[0],n[1]]}async function Dt(t){let e=t.args;K(e,{solution:"--solution",required:"--required",dependent:"--dependent"},!1,"dv dependency list");let n=ot(e.required,"--required"),s=ot(e.dependent,"--dependent");ht(e);let o=await W(t);F(t,o,"GET","dependencies",null);let r={},m=[],g=T(e.solution),y=await o.lookups(async()=>{if(g){let{names:c}=await import("./solution-CNBNIS7Z.js"),[a,i]=await xt(t,o,c(g));m=i.managed??[],delete i.managed,i.base_solution_filter=m.length>0,r=i;let d=Object.values(i.added).reduce((j,lt)=>j+lt,0);i.missing_tables.length&&A(`${i.missing_tables.length} table(s) in the solution no longer exist: `+i.missing_tables.join(", "));let S=i.components,M=i.full_tables;return A(`${S} component${S!==1?"s":""} in ${i.solutions.join(", ")}`+(d?`, plus ${d} subcomponents of ${M} full table${M!==1?"s":""}`:"")),{required:a,dependent:a}}if(n||s){let c=n?"required":"dependent",[a,i]=n??s,{componentId:d,componentType:S}=await import("./lifecycle-2F7MF6EP.js"),M=await S(t,o,a);return{[c]:[await d(t,o,M,i,a)]}}return{}},["$batch"]),p=typeof e.type=="number"?e.type:null,h=Object.keys(y).length?bt(y,p,it,m):[null];if(t.dryRun){await t.emit({dry_run:!0,...r,requests:h.map(c=>({method:"GET",path:"dependencies",params:Object.fromEntries(ct(c))}))});return}let f=J(e),[C,x]=await qt(o,h,f),$=x,w=await Et(t,o,C,y,!!g,!!(n||s));if(g){let c=new Map;for(let a of w)c.set(a.found_by,(c.get(a.found_by)??0)+1);r.found_by=Object.fromEntries(_(c.entries(),([a])=>a))}f!==null&&w.length>f&&($=!0,w=w.slice(0,f)),$&&A(`showing the first ${f} rows; pass --limit n or --all for more`);let l=T(e.save);l?(await Ct(l,w),await t.emit({saved:l,rows:w.length,truncated:$,...r})):await t.emit(w)}function D(t){if(Array.isArray(t))return"["+t.map(e=>D(e===void 0?null:e)).join(", ")+"]";if(typeof t=="object"&&t!==null){let e=Object.entries(t).filter(([,s])=>s!==void 0);return"{"+_(e,([s])=>s).map(([s,o])=>`${st(s)}: ${D(o)}`).join(", ")+"}"}return typeof t=="string"?st(t):JSON.stringify(t)??"null"}function st(t){return JSON.stringify(t).replace(/[^\x00-\x7f]/g,e=>"\\u"+e.charCodeAt(0).toString(16).padStart(4,"0"))}function _t(t,e){let n=ut(e);n.endsWith(".gz")&&(n=n.slice(0,-3));let s=Buffer.from(n,"latin1"),o=Buffer.from([31,139,8,s.length?8:0,0,0,0,0,2,255]),r=Buffer.alloc(8);r.writeUInt32LE(mt(t)>>>0,0),r.writeUInt32LE(t.length%4294967296,4);let m=[o];return s.length&&m.push(s,Buffer.from([0])),m.push(pt(t,{level:9,memLevel:8}),r),Buffer.concat(m)}async function Ct(t,e){let n=Buffer.from(e.map(s=>D(s)+`
|
|
3
|
+
`).join(""),"ascii");dt(t,t.toLowerCase().endsWith(".gz")?_t(n,t):n)}export{it as CHUNK,Tt as FOUND_BY,tt as NAME_CHUNK,G as SIDES,ht as checkScope,bt as filters,$t as foundBy,wt as inFilter,Mt as intersects,Dt as list,St as localChoices,nt as row,Ct as save,Rt as subcomponents};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
2
|
-
import{b as u,d}from"./chunk-
|
|
2
|
+
import{b as u,d}from"./chunk-GY6BUIDP.js";import{c as l,g as a}from"./chunk-J4R6QXW7.js";import"./chunk-2IUXH534.js";import"./chunk-TCLZ4XM6.js";import"./chunk-H4OY4EFC.js";import"./chunk-TQLZ3TRU.js";import"./chunk-S4KF5Z3S.js";import"./chunk-WXOTXJNG.js";import"./chunk-ZHHVG47C.js";var s="globaldisco.crm.dynamics.com",v={0:"production",5:"sandbox",6:"sandbox-free",7:"preview",9:"test-drive",11:"email-trial",12:"default",13:"developer",14:"trial",15:"teams"},i=class extends u{name="discovery";scope(){return`https://${s}//.default`}url(t,e){let n=t.includes("://")?t:`https://${s}/${t.replace(/^\/+/,"")}`;return e&&e.length&&(n+=(n.includes("?")?"&":"?")+l(e)),n}allowed(t){let e=a(t);return e.scheme==="https"&&e.host===s}};async function w(r,t){let e=new i,{getToken:n}=await import("./provider-D7DMMAS6.js"),o=(await new d(e,r,p=>n(t,e.scope(),{forceRefresh:p,log:m=>r.log(m)})).request("GET","api/discovery/v2.0/Instances")).json(),c=o&&typeof o=="object"?o.value:null;return Array.isArray(c)?c:[]}export{i as Discovery,s as HOST,v as ORG_TYPES,w as instances};
|