sandforge 1.79.0 → 1.80.0
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/lib/{chunk-JVL444U5.mjs → chunk-2BA2XKAY.mjs} +1 -1
- package/lib/chunk-2CNCDM56.mjs +7 -0
- package/lib/{chunk-W7KFAY55.mjs → chunk-2GTBABKU.mjs} +1 -1
- package/lib/{chunk-DLDX6RRC.mjs → chunk-2NBYT7GR.mjs} +1 -1
- package/lib/{chunk-HV2MXMGI.mjs → chunk-2UZPIMUC.mjs} +1 -1
- package/lib/chunk-3F6Q5E7I.mjs +14 -0
- package/lib/{chunk-PBI4BYWW.mjs → chunk-3RZQZHEB.mjs} +1 -1
- package/lib/{chunk-P7GSGFJO.mjs → chunk-3TJON4F3.mjs} +1 -1
- package/lib/chunk-4VS2V6WU.mjs +25 -0
- package/lib/{chunk-TQX3PURV.mjs → chunk-5K5VLULK.mjs} +1 -1
- package/lib/{chunk-MYTIL2JD.mjs → chunk-5TC3QB4U.mjs} +1 -1
- package/lib/{chunk-NM4MDLK4.mjs → chunk-6XYKJSGX.mjs} +1 -1
- package/lib/{chunk-RFEO2KAN.mjs → chunk-74Q6DORA.mjs} +1 -1
- package/lib/chunk-7ABODJ4G.mjs +7 -0
- package/lib/{chunk-ZPYJPGDK.mjs → chunk-7EGQP6S4.mjs} +1 -1
- package/lib/chunk-7FFGJWHN.mjs +7 -0
- package/lib/chunk-7YDNUBO5.mjs +7 -0
- package/lib/{chunk-CGWXQX75.mjs → chunk-A527W53V.mjs} +1 -1
- package/lib/chunk-ADOAS63R.mjs +7 -0
- package/lib/chunk-AEKONPF4.mjs +7 -0
- package/lib/{chunk-4HFRHFGQ.mjs → chunk-B5QQJ4SI.mjs} +1 -1
- package/lib/{chunk-2BVTCNWA.mjs → chunk-BGUEWRK2.mjs} +1 -1
- package/lib/{chunk-GNC27UEU.mjs → chunk-BKDV4ENO.mjs} +1 -1
- package/lib/{chunk-QRV2OSIS.mjs → chunk-BTWDMNN3.mjs} +1 -1
- package/lib/{chunk-FOVVHGEP.mjs → chunk-BV6VTP3J.mjs} +1 -1
- package/lib/{chunk-PZTSVQSF.mjs → chunk-BXU6WFMH.mjs} +1 -1
- package/lib/{chunk-ZQOZ4EFW.mjs → chunk-BY2HJFFG.mjs} +1 -1
- package/lib/{chunk-NZ5ZZLKS.mjs → chunk-CEX3NEZL.mjs} +1 -1
- package/lib/{chunk-HTJ5OGP5.mjs → chunk-CHYDMRSV.mjs} +1 -1
- package/lib/chunk-CION3VMZ.mjs +7 -0
- package/lib/chunk-COFG7Q6R.mjs +7 -0
- package/lib/chunk-CSBS5U5I.mjs +7 -0
- package/lib/{chunk-55HEMHEG.mjs → chunk-CU2INBND.mjs} +1 -1
- package/lib/chunk-DB7RBE5D.mjs +7 -0
- package/lib/{chunk-QPF6C5MX.mjs → chunk-DBB3EMIN.mjs} +1 -1
- package/lib/{chunk-F74IHMGL.mjs → chunk-DYFALGRT.mjs} +1 -1
- package/lib/{chunk-TEOLMRDO.mjs → chunk-E5AHXLS6.mjs} +1 -1
- package/lib/{chunk-LRFAIUN7.mjs → chunk-E5ZB3LU5.mjs} +1 -1
- package/lib/chunk-EFR2Y7E4.mjs +7 -0
- package/lib/chunk-EHQ3FX6X.mjs +7 -0
- package/lib/{chunk-RAAANPPG.mjs → chunk-ELFXJHU7.mjs} +1 -1
- package/lib/{chunk-BN7A4GRQ.mjs → chunk-EMNC6YI4.mjs} +1 -1
- package/lib/{chunk-HJC7AIBK.mjs → chunk-EQNW3UC2.mjs} +1 -1
- package/lib/{chunk-Z7X534S4.mjs → chunk-F43REJDZ.mjs} +2 -2
- package/lib/{chunk-QQZZMKU3.mjs → chunk-F6GUDTOB.mjs} +1 -1
- package/lib/{chunk-6EBMEGZB.mjs → chunk-FGRG7ANU.mjs} +1 -1
- package/lib/{chunk-4NAHW2D3.mjs → chunk-FKG7Q3WH.mjs} +1 -1
- package/lib/{chunk-7UQD6V6F.mjs → chunk-FPKYYFM7.mjs} +1 -1
- package/lib/{chunk-ZJKCWBRJ.mjs → chunk-FXXLX4O6.mjs} +1 -1
- package/lib/chunk-G35N4P7D.mjs +7 -0
- package/lib/{chunk-SIOZXPFG.mjs → chunk-GGD7ON3M.mjs} +1 -1
- package/lib/chunk-GSG7WZHM.mjs +7 -0
- package/lib/{chunk-OTWRDD6L.mjs → chunk-GSKCGQIP.mjs} +1 -1
- package/lib/{chunk-3CA767QB.mjs → chunk-HEKAZJRH.mjs} +1 -1
- package/lib/{chunk-4SNDMJP2.mjs → chunk-HLWMJF6Y.mjs} +1 -1
- package/lib/chunk-HOJYWTP7.mjs +20 -0
- package/lib/chunk-HS4YRX4J.mjs +7 -0
- package/lib/chunk-IFETCRWE.mjs +10 -0
- package/lib/{chunk-PUOX4NBJ.mjs → chunk-IG2MTQRP.mjs} +1 -1
- package/lib/{chunk-RACDTRZA.mjs → chunk-IGYH7GMA.mjs} +1 -1
- package/lib/{chunk-X65MT4W3.mjs → chunk-IOIWJ3DJ.mjs} +1 -1
- package/lib/{chunk-4U6NXJNL.mjs → chunk-IQXHJEYB.mjs} +1 -1
- package/lib/{chunk-P2PJYWGQ.mjs → chunk-IWDREM66.mjs} +1 -1
- package/lib/{chunk-ZOVSMN5C.mjs → chunk-IZQZ6ZUF.mjs} +1 -1
- package/lib/{chunk-XBG5SP6Q.mjs → chunk-J525F5KI.mjs} +1 -1
- package/lib/{chunk-5CD257T7.mjs → chunk-JEERQRLW.mjs} +1 -1
- package/lib/{chunk-6QSM2WIH.mjs → chunk-JPUR2CFX.mjs} +1 -1
- package/lib/chunk-JWTSEDIQ.mjs +7 -0
- package/lib/chunk-K327QKMD.mjs +7 -0
- package/lib/{chunk-J7HVXMSW.mjs → chunk-KBJ5VERV.mjs} +1 -1
- package/lib/chunk-KDGMAGQR.mjs +7 -0
- package/lib/chunk-KRCA6IPH.mjs +8 -0
- package/lib/chunk-KYEDBS54.mjs +7 -0
- package/lib/chunk-L5FGY6YA.mjs +7 -0
- package/lib/{chunk-PNCONNFJ.mjs → chunk-L77FJZEP.mjs} +1 -1
- package/lib/{chunk-3OHPD72J.mjs → chunk-LKQ5RKIV.mjs} +1 -1
- package/lib/{chunk-WJY54JO7.mjs → chunk-LPBMBW3O.mjs} +1 -1
- package/lib/{chunk-LV6G4XTK.mjs → chunk-LWW4U276.mjs} +1 -1
- package/lib/{chunk-IAZB4WIL.mjs → chunk-M3ROUWDX.mjs} +1 -1
- package/lib/chunk-MFG4MUIO.mjs +9 -0
- package/lib/{chunk-H45UXY6G.mjs → chunk-MHMH6MTP.mjs} +1 -1
- package/lib/{chunk-HCIDVIOW.mjs → chunk-MILU7WFN.mjs} +1 -1
- package/lib/chunk-MJU2PGZQ.mjs +15 -0
- package/lib/{chunk-HJKM3E56.mjs → chunk-MJVTDA5Q.mjs} +1 -1
- package/lib/{chunk-SBIMVCXT.mjs → chunk-MS4FJDFD.mjs} +9 -9
- package/lib/{chunk-3SRXFZSD.mjs → chunk-MYW5QNGI.mjs} +1 -1
- package/lib/{chunk-VHI54FBK.mjs → chunk-N652NMZ4.mjs} +26 -26
- package/lib/{chunk-3DCUADVK.mjs → chunk-NTFIRZP6.mjs} +1 -1
- package/lib/{chunk-342FN7AO.mjs → chunk-NZC67CGR.mjs} +1 -1
- package/lib/{chunk-RSYICMZG.mjs → chunk-O2HDYYUV.mjs} +1 -1
- package/lib/chunk-OAZRPP4I.mjs +7 -0
- package/lib/{chunk-BILZ3SSR.mjs → chunk-OHWNPXWW.mjs} +1 -1
- package/lib/chunk-OLSGVAIL.mjs +341 -0
- package/lib/chunk-OO6CLPEH.mjs +7 -0
- package/lib/chunk-OPXCV2KL.mjs +7 -0
- package/lib/chunk-P33PSCXK.mjs +7 -0
- package/lib/{chunk-AUTM6H6Z.mjs → chunk-PJ5I73CK.mjs} +1 -1
- package/lib/{chunk-NTDN2JQZ.mjs → chunk-PZPJKATS.mjs} +1 -1
- package/lib/{chunk-5QKTYCWE.mjs → chunk-Q3DM32KF.mjs} +1 -1
- package/lib/{chunk-K22PA4XL.mjs → chunk-QR3WELJQ.mjs} +1 -1
- package/lib/{chunk-42RER7V4.mjs → chunk-R3X3LV64.mjs} +1 -1
- package/lib/chunk-RMBPOTD7.mjs +7 -0
- package/lib/{chunk-IEYG5ATY.mjs → chunk-RPI7LRTW.mjs} +1 -1
- package/lib/{chunk-5MMXFWPD.mjs → chunk-SE4QEZUG.mjs} +1 -1
- package/lib/{chunk-ALJVEUUS.mjs → chunk-SIHORWVK.mjs} +1 -1
- package/lib/{chunk-AAVJ5XVX.mjs → chunk-SOGQW4IG.mjs} +1 -1
- package/lib/chunk-SOU4FRYN.mjs +7 -0
- package/lib/chunk-SU65Z2BA.mjs +7 -0
- package/lib/chunk-T62WNR54.mjs +7 -0
- package/lib/{chunk-5O6JOMHS.mjs → chunk-TSLJUSLW.mjs} +1 -1
- package/lib/chunk-TTFDUKUS.mjs +47 -0
- package/lib/{chunk-57VHUYNG.mjs → chunk-TTKXMDBN.mjs} +1 -1
- package/lib/chunk-UCD54V2M.mjs +7 -0
- package/lib/{chunk-TBZMC2VV.mjs → chunk-UNJA4J37.mjs} +1 -1
- package/lib/{chunk-NGSMZZDA.mjs → chunk-VE6XKGGD.mjs} +1 -1
- package/lib/chunk-VS7ZXUII.mjs +824 -0
- package/lib/{chunk-ALUFROGA.mjs → chunk-VXQLDM4R.mjs} +1 -1
- package/lib/chunk-VYXMVJL5.mjs +7 -0
- package/lib/{chunk-WFEB5X4U.mjs → chunk-W622GUAW.mjs} +1 -1
- package/lib/chunk-W7U5E5ZL.mjs +9 -0
- package/lib/{chunk-AR7BE5O2.mjs → chunk-WA7EYLAQ.mjs} +1 -1
- package/lib/{chunk-EQF2IJS2.mjs → chunk-WR4Q363I.mjs} +1 -1
- package/lib/{chunk-ZXH4MBWP.mjs → chunk-WU3GLFZO.mjs} +1 -1
- package/lib/chunk-WXAQ7FK3.mjs +115 -0
- package/lib/{chunk-YBU4Z4QV.mjs → chunk-X5JYBPXP.mjs} +1 -1
- package/lib/chunk-XAMBCQPU.mjs +7 -0
- package/lib/{chunk-LQ4DRFUH.mjs → chunk-XLXIPIEW.mjs} +1 -1
- package/lib/{chunk-H2PJNIYJ.mjs → chunk-XUWL6ZPC.mjs} +1 -1
- package/lib/{chunk-P42X3B4D.mjs → chunk-YKKRIEH4.mjs} +1 -1
- package/lib/chunk-YRQGKDHM.mjs +7 -0
- package/lib/chunk-ZM6OJGIG.mjs +7 -0
- package/lib/{chunk-SFURUNJM.mjs → chunk-ZVAED4QV.mjs} +1 -1
- package/lib/sandforge-autopilot.mjs +29 -24
- package/lib/sandforge-backup.mjs +25 -21
- package/lib/sandforge-checkpoint.mjs +15 -14
- package/lib/sandforge-cleanup.mjs +14 -10
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +9 -8
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +15 -15
- package/lib/sandforge-env.mjs +88 -88
- package/lib/sandforge-frozen.mjs +43 -34
- package/lib/sandforge-mcp.mjs +12 -12
- package/lib/sandforge-monitor.mjs +7 -7
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge.mjs +4 -4
- package/package.json +1 -1
- package/lib/chunk-2S5OMIIA.mjs +0 -7
- package/lib/chunk-36U7IQ6Y.mjs +0 -25
- package/lib/chunk-3F5YMM2F.mjs +0 -7
- package/lib/chunk-3RYLICRX.mjs +0 -7
- package/lib/chunk-4GL773D5.mjs +0 -7
- package/lib/chunk-4XZ5YT5O.mjs +0 -7
- package/lib/chunk-5AJRHRXA.mjs +0 -20
- package/lib/chunk-5HMAPZBV.mjs +0 -7
- package/lib/chunk-6LAXTAVN.mjs +0 -7
- package/lib/chunk-6MUEPV7M.mjs +0 -9
- package/lib/chunk-75ADZS6B.mjs +0 -7
- package/lib/chunk-B45CNPUX.mjs +0 -47
- package/lib/chunk-BS5T3MOQ.mjs +0 -7
- package/lib/chunk-D3QRXG63.mjs +0 -787
- package/lib/chunk-EEVVGGM6.mjs +0 -7
- package/lib/chunk-ENLBYECD.mjs +0 -7
- package/lib/chunk-EQOQASDQ.mjs +0 -7
- package/lib/chunk-FQBRBBY4.mjs +0 -7
- package/lib/chunk-GAM726CK.mjs +0 -7
- package/lib/chunk-HUMEKZT5.mjs +0 -8
- package/lib/chunk-I3JKJTLO.mjs +0 -110
- package/lib/chunk-KLX67VPL.mjs +0 -7
- package/lib/chunk-L776PUMV.mjs +0 -7
- package/lib/chunk-NEVXIGR6.mjs +0 -10
- package/lib/chunk-NHWE66K5.mjs +0 -7
- package/lib/chunk-OQOZAPCI.mjs +0 -7
- package/lib/chunk-PA3MKJVH.mjs +0 -7
- package/lib/chunk-RH3N2H7P.mjs +0 -7
- package/lib/chunk-SRQDABQ2.mjs +0 -15
- package/lib/chunk-SVS6UMDU.mjs +0 -323
- package/lib/chunk-TNXUU6W7.mjs +0 -14
- package/lib/chunk-VXHDBYMI.mjs +0 -7
- package/lib/chunk-WRU5FJFC.mjs +0 -7
- package/lib/chunk-X2PY6MWZ.mjs +0 -7
- package/lib/chunk-XEFDB2R4.mjs +0 -7
- package/lib/chunk-XETCPL7E.mjs +0 -7
- package/lib/chunk-Y5CGXLUB.mjs +0 -7
- package/lib/chunk-Y6J6QFI2.mjs +0 -7
- package/lib/chunk-YMJVMFPY.mjs +0 -7
- package/lib/chunk-YPSRZRIT.mjs +0 -7
- package/lib/chunk-YW2SBL4Z.mjs +0 -7
- package/lib/chunk-ZE6HKRR4.mjs +0 -9
- package/lib/chunk-ZLZRU6MO.mjs +0 -7
- package/lib/chunk-ZYEE34WO.mjs +0 -7
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{Ab as O,zb as S}from"./chunk-TTFDUKUS.mjs";import{b as y,f as b,l as R}from"./chunk-7EANH5PY.mjs";var v=["User","Group","Profile","UserRole","RecordType","Organization","Queue","PermissionSet","BusinessProcess","CurrencyType","DandBCompany","DuplicateRecordItem","DuplicateRecordSet","ProcessInstance","LoginHistory","LoginEvent","LoginIp","LoginGeo","AsyncApexJob","ApexLog","ApexTestResult","ApexTestQueueItem","LightningUsageByPageMetrics","LightningExitByPageMetrics","EventBusSubscriber","PlatformEventUsageMetric","CronTrigger","CronJobDetail","AttachedContentDocument","AttachedContentNote","CombinedAttachment","ContentBody","NoteAndAttachment","OwnedContentDocument","EntitySubscription","TopicAssignment","UserRecordAccess","DeclinedEventRelation","UndecidedEventRelation","AcceptedEventRelation","OpenActivity","ActivityHistory","AppUsageAssignment","AuthProvider","Folder","ContentDocument","ContentDocumentLink","OpportunityRelatedDeleteLog","CaseHistory2","Calendar","SlaProcess","AccountCleanInfo","ContactCleanInfo","LeadCleanInfo","ApprovalSubmission","ApprovalSubmissionDetail","ApprovalWorkItem","AIRecordInsight","AIInsightValue","MatchingInformation","Invoice","InvoiceLine","CreditMemo","CreditMemoLine","AppDefinition","BackgroundOperation","ContentTaxonomyTermRelationshipType","Dashboard","DashboardComponent","DeleteEvent","ManagedContentChannel","ManagedContentSpace","ManagedContentVariant","Report","ServiceSetupProvisioning","TabDefinition"],P=new Set(v.map(e=>e.toLowerCase())),W=["History","Feed","Share","ChangeEvent","__hd","__Tag","EventStore"].map(e=>e.toLowerCase()),F=/^vlocity_[a-z0-9]+__/;function B(e,t){return I(e,t,{byNamespace:!0})}function I(e,t,r){let n=e.toLowerCase();return P.has(n)||S(e)||t&&(t.has(e)||U(t).has(n))||r.byNamespace&&F.test(n)?!0:W.some(i=>n.endsWith(i))}var w=new WeakMap;function U(e){let t=w.get(e);if(t&&t.size===e.size)return t.names;let r=new Set([...e].map(n=>n.toLowerCase()));return w.set(e,{size:e.size,names:r}),r}function z(e,t){return O(e)||B(e,t)}function E(e){return O(e)||I(e,void 0,{byNamespace:!1})}function x(e,t=[]){let r=new Set(t);for(let n of e)n.createable===!1&&r.add(n.name);return r}function le(e,t=r=>z(r)){return new Set(e.filter(r=>{let n=r.referenceTo??[];return n.length>0&&n.every(i=>t(i))}).map(r=>r.name))}var ge=R({name:y(),queryable:b().optional(),createable:b().optional(),updateable:b().optional(),deletable:b().optional(),undeletable:b().optional(),customSetting:b().optional(),layoutable:b().optional(),keyPrefix:y().nullish()}).loose(),D="ContentDocument",H="ContentDocumentLink",G="ContentVersion",L="Attachment",J=[D,L],K={AccountContactRelation:["Contact"]},V=new Set(["feeditem","feedcomment","feedattachment"]),X=new Set(["casehistory2"]),Y=new Set(["AccountCleanInfo","ContactCleanInfo","LeadCleanInfo","ApprovalSubmission","ApprovalSubmissionDetail","ApprovalWorkItem","ProcessInstance","ProcessInstanceNode","ProcessInstanceStep","ProcessInstanceWorkitem","AIRecordInsight","AIInsightValue","AIInsightAction","AIInsightFeedback","AIInsightReason","MatchingInformation","Invoice","InvoiceLine","CreditMemo","CreditMemoLine","CreditMemoInvApplication"].map(e=>e.toLowerCase())),Q=new Set([G,H].map(e=>e.toLowerCase())),Z=["__b","__x","__dlm","__kav","__ka","__e"],$=new Set(["AccountContactRole",L,"CaseTeamMember","EmailMessageRelation","EventRelation","OpportunityCompetitor"].map(e=>e.toLowerCase()));function q(e,t,r,n,i){let o=e.name.toLowerCase();return V.has(o)||o.endsWith("feed")?"chatter":o.endsWith("history")||o.endsWith("__hd")||X.has(o)?"history":o.endsWith("share")?"sharing":o.endsWith("changeevent")?"changeEvent":Z.some(c=>o.endsWith(c))?"unsupportedKind":e.customSetting===!0?n?A(e,i)?void 0:"notWritable":"customSetting":Q.has(o)?"heldWithFiles":o===D.toLowerCase()?(i==="delete"?_(e):T(e))?void 0:"notWritable":o===L.toLowerCase()?A(e,i)?void 0:"notWritable":S(e.name)?"files":Y.has(o)?"platformCreated":E(e.name)||r==="everything"&&e.layoutable===!1&&!$.has(o)?"setup":t.out.has(o)?t.tooling.has(o)?"metadata":"notWritable":A(e,i)?void 0:"notWritable"}function A(e,t){return t==="delete"?_(e):ee(e)}function ee(e){return e.createable===!0&&T(e)}function _(e){return e.queryable===!0&&e.deletable===!0}function T(e){return e.queryable===!0&&e.updateable===!0&&e.deletable===!0}function k(e,t){return e.objectApiName<t.objectApiName?-1:e.objectApiName>t.objectApiName?1:0}var te="all";function ne(e){return e.customSetting===!0}function oe(e,t){let r=e.filter(ne);if(t===void 0)return{held:new Set,unknown:[]};if(t===te)return{held:new Set(r.map(c=>c.name.toLowerCase())),unknown:[]};let n=new Set(r.map(c=>c.name.toLowerCase())),i=new Set,o=[];for(let c of t){let p=c.toLowerCase();i.has(p)||o.some(u=>u.toLowerCase()===p)||(n.has(p)?i.add(p):o.push(c))}return{held:i,unknown:o}}function he(e,t,r=[]){let n=t.access??"write",i=n==="delete"?r:x(e,r),o={out:new Set([...i].map(a=>a.toLowerCase())),tooling:new Set(r.map(a=>a.toLowerCase()))},c=new Set((t.excluded??[]).map(a=>a.toLowerCase())),p=new Map(e.map(a=>[a.name.toLowerCase(),a])),u=oe(e,t.customSettings),h=u.unknown.map(a=>({objectApiName:a,reason:"notCustomSetting"})),g=[],f=[],s=[];if(t.mode==="picked"){let a=new Set;for(let d of t.objects??[]){let l=d.toLowerCase();if(a.has(l))continue;a.add(l);let m=p.get(l);m?f.push(m):h.push({objectApiName:d,reason:"notFound"})}for(let d of J){let l=d.toLowerCase(),m=p.get(l);if(!(a.has(l)||m===void 0)){if(c.has(l)){h.push({objectApiName:m.name,reason:"excludedByUser"});continue}f.push(m),s.push(m.name)}}for(let[d,l]of Object.entries(K)){let m=d.toLowerCase(),C=p.get(m);if(!(a.has(m)||C===void 0)&&l.some(j=>a.has(j.toLowerCase()))){if(a.add(m),c.has(m)){h.push({objectApiName:C.name,reason:"excludedByUser"});continue}f.push(C)}}for(let d of u.held){let l=p.get(d);a.has(d)||l===void 0||(a.add(d),f.push(l))}}else f.push(...p.values());for(let a of f){let d=a.name.toLowerCase(),l=c.has(d)?"excludedByUser":q(a,o,t.mode,u.held.has(d),n);l===void 0?g.push(a.name):h.push({objectApiName:a.name,reason:l})}return g.sort(),h.sort(k),{mode:t.mode,candidates:g,leftOut:h,addedToPicked:s}}function be(e){return e.fields.find(r=>r.name==="Name")?.nillable===!0?"hierarchy":"list"}function Ce(e){return e==="hierarchy"?"SetupOwnerId":"Name"}function Se(e){return e.objects.some(t=>t.customSetting!==void 0)}function re(e){let t=e.split("__");return t.length>=3&&t[0]!==""?t[0]:void 0}var se=()=>({first:"child",firmness:0});function ie(e,t,r=se){let n=new Map(e.map((o,c)=>[o.toLowerCase(),c])),i=e.map(()=>new Map);return e.forEach((o,c)=>{for(let p of t.get(o)?.childRelationships??[]){let u=n.get(p.childSObject.toLowerCase());if(u===void 0||u===c)continue;let h=r(p);if(h===void 0)continue;let[g,f]=h.first==="child"?[u,c]:[c,u],s=i[g].get(f);(s===void 0||h.firmness>s)&&i[g].set(f,h.firmness)}}),N(e.map((o,c)=>c),i,Number.NEGATIVE_INFINITY).map(o=>e[o])}function N(e,t,r){let n=new Set(e),i=f=>[...t[f]].filter(([s,a])=>n.has(s)&&a>r).map(([s])=>s),o=ae(e,i,t.length),c=new Map;o.forEach((f,s)=>{for(let a of f)c.set(a,s)});let p=o.map(()=>0),u=o.map(()=>new Set);for(let f of e){let s=c.get(f)??0;for(let a of i(f)){let d=c.get(a)??0;d===s||u[s].has(d)||(u[s].add(d),p[d]++)}}let h=o.map(()=>!1),g=[];for(let f=o.length;f>0;f--){let s=-1;for(let d=0;d<o.length;d++){if(h[d]||p[d]>0)continue;let l=o[d].length===1,m=s>=0&&o[s].length===1;(s<0||l&&!m||l===m&&o[d][0]<o[s][0])&&(s=d)}h[s]=!0;let a=o[s];if(a.length===1)g.push(a[0]);else{let d=Number.POSITIVE_INFINITY;for(let l of a)for(let[m,C]of t[l])C>r&&c.get(m)===s&&C<d&&(d=C);g.push(...N(a,t,d))}for(let d of u[s])p[d]--}return g}function ae(e,t,r){let n=new Array(r).fill(-1),i=new Array(r).fill(0),o=new Array(r).fill(!1),c=[],p=[],u=0;for(let h of e){if(n[h]>=0)continue;let g=[],f=s=>{n[s]=u,i[s]=u,u++,c.push(s),o[s]=!0,g.push({node:s,edges:t(s),at:0})};for(f(h);g.length>0;){let s=g[g.length-1];if(s.at<s.edges.length){let l=s.edges[s.at++];n[l]<0?f(l):o[l]&&(i[s.node]=Math.min(i[s.node],n[l]));continue}g.pop();let a=g[g.length-1];if(a&&(i[a.node]=Math.min(i[a.node],i[s.node])),i[s.node]!==n[s.node])continue;let d=[];for(let l=c.pop();l!==void 0&&(o[l]=!1,d.push(l),l!==s.node);l=c.pop());p.push(d.sort((l,m)=>l-m))}}return p}function M(e){let t=new Map;for(let{objectApiName:r,namespace:n}of e)n!==void 0&&t.set(n,[...t.get(n)??[],r]);return[...t].sort(([r],[n])=>r<n?-1:r>n?1:0).map(([r,n])=>({namespace:r,objects:n.sort()}))}function ce(e,t){return ie(e,t).map((r,n)=>{let i=re(r);return{objectApiName:r,readOrder:n,...i===void 0?{}:{namespace:i}}})}function ye(e,t,r=new Map){let n=[...e.leftOut],i=[];for(let c of e.candidates){let p=t.get(c);if(p)p.fields.some(u=>u.name==="SystemModstamp")?p.fields.some(u=>u.name==="IsDeleted")?i.push(c):n.push({objectApiName:c,reason:"noRecycleBin"}):n.push({objectApiName:c,reason:"noSystemModstamp"});else{let u=r.get(c);n.push({objectApiName:c,reason:"notDescribed",...u===void 0?{}:{detail:u}})}}let o=ce(i,t);return{mode:e.mode,objects:o,leftOut:n.sort(k),packages:M(o)}}function Oe(e,t){if(t.size===0)return e;let r=[...e.leftOut],n=[];for(let i of e.objects){let o=t.get(i.objectApiName);o===void 0?n.push({...i,readOrder:n.length}):r.push({objectApiName:i.objectApiName,reason:"unreadable",detail:o})}return{...e,objects:n,leftOut:r.sort(k),packages:M(n)}}export{B as a,z as b,E as c,x as d,le as e,ge as f,D as g,H as h,G as i,L as j,J as k,te as l,ne as m,he as n,be as o,Ce as p,Se as q,re as r,ie as s,ye as t,Oe as u};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{a,b}from"./chunk-OAZRPP4I.mjs";import"./chunk-JEERQRLW.mjs";import"./chunk-HS4YRX4J.mjs";import"./chunk-JWTSEDIQ.mjs";import"./chunk-SU65Z2BA.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as grantsByObject,b as guardCheckpoint};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a,b}from"./chunk-
|
|
7
|
+
import{a,b}from"./chunk-CHYDMRSV.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as DataPlanBuilder,b as resolveInsertOrder};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{i as g,n as p,o as m}from"./chunk-MFG4MUIO.mjs";import{b as w}from"./chunk-MTMH6H2A.mjs";import{dc as l,o as d,p as u}from"./chunk-TTFDUKUS.mjs";import{A as c}from"./chunk-7EANH5PY.mjs";import{a as b,b as I}from"./chunk-MS4FJDFD.mjs";import{d as f}from"./chunk-NTOVCTRS.mjs";var a=class extends Error{constructor(t,r){super(`${r} Nothing was read from ${t}.`);this.alias=t;this.reason=r;this.name="SfSessionError",this.stack=this.message}alias;reason},$=c.object({name:c.string().optional(),message:c.string().optional()}).loose();function h(e){if(typeof e!="string")return;let n=e.replace(/\u001b\[[0-9;]*m/g,""),t=n.indexOf("{");if(t!==-1)try{let r=$.safeParse(JSON.parse(n.slice(t)));return r.success?r.data:void 0}catch{return}}function C(e,n=process.platform){let t=typeof e=="object"&&e!==null?e:{};return t.code==="ENOENT"?!0:n==="win32"&&(t.status===9009||/is not recognized as an internal or external command/i.test(String(t.stderr??"")))}function S(e,n,t=process.platform){if(C(n,t))return new a(e,`${d} SandForge reads each org through the Salesforce CLI: install it with "npm install -g @salesforce/cli" (${u}), sign in to the org with "sf org login web --alias ${e}", and run again.`);let r=typeof n=="object"&&n!==null?n:{},o=h(r.stdout)??h(r.stderr);if(o?.name==="NamedOrgNotFoundError"||/^No authorization information found for /.test(o?.message??""))return new a(e,`sf does not know ${e}: "sf org list" names the orgs it knows; "sf org login web --alias ${e}" adds it (in a CI job, "sf org login jwt" or "sf org login sfdx-url").`);let s=typeof r.stderr=="string"?r.stderr.split(/\r?\n/).find(y=>y.trim()!==""):void 0,i=o?.message?.trim()||s?.trim()||(n instanceof Error?n.message:String(n));return new a(e,`sf could not show ${e}: ${i}`)}var k=f(I()),x=f(b());import{execFileSync as E}from"node:child_process";function T(e){try{return E("sf",["org","display","--target-org",e,"--json"],{encoding:"utf8",maxBuffer:50*1024*1024,shell:process.platform==="win32"})}catch(n){throw S(e,n)}}async function A(e,n=m){if(!w.test(e))throw new Error(`Invalid SF org alias: "${e}" (an alias or a username: letters, digits, _ . @ + and -, not starting with . @ + or -)`);let t=T(e),r=JSON.parse(t),o=r.result;if(typeof o?.devHubId=="string"&&o.devHubId!==""){let i=typeof o.expirationDate=="string"?l({orgType:"Scratch",metadata:{expirationDate:o.expirationDate}},new Date().toISOString().slice(0,10)):void 0;if(i!==void 0||o.status==="Deleted")throw new Error(`The scratch org '${e}' ${i!==void 0?`expired on ${i}`:"is deleted"}: Salesforce deletes a scratch org when it expires, and no sign-in brings it back. Create a new one ("sf org create scratch") and give its alias.`)}if(!r.result?.instanceUrl)throw new Error(`sf org display did not return a usable session for alias '${e}'.`);let s=await n(e);if(!p(s.accessToken))throw new Error(`The Salesforce CLI showed no usable access token for alias '${e}'. Sign in again with "sf org login web --alias ${e}" where a browser opens; in a CI job, with "sf org login jwt --alias ${e}" (a client id, a key file and a username) or "sf org login sfdx-url --alias ${e} --sfdx-url-file <file>" (see ci-examples/README.md).`);return{alias:e,username:r.result.username??"",instanceUrl:s.instanceUrl??r.result.instanceUrl,accessToken:s.accessToken,...typeof r.result.devHubId=="string"&&r.result.devHubId!==""?{scratch:!0}:{}}}function H(e,n=process.env){let t=g(e.instanceUrl,n),r=new k.default.Connection({instanceUrl:e.instanceUrl,accessToken:e.accessToken,version:"66.0",...t!==void 0?{httpProxy:t}:{}});return t===void 0&&(r._transport=new x.HttpProxyTransport("")),r}export{a,A as b,H as c};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{i as Ye,k as qe}from"./chunk-5TC3QB4U.mjs";import{d as Le,i as xe}from"./chunk-2BA2XKAY.mjs";import{b as ee}from"./chunk-OAZRPP4I.mjs";import{c as Ze,d as et}from"./chunk-JEERQRLW.mjs";import{a as De,b as Me}from"./chunk-5P4PHJRL.mjs";import{c as Ae,d as je,m as Re}from"./chunk-MJU2PGZQ.mjs";import{a as Te}from"./chunk-LWW4U276.mjs";import{A as te,B as ot,o as Ne,u as tt,v as nt}from"./chunk-F43REJDZ.mjs";import{$ as Y,T as Ce,X as We,Z as Be,_ as X,aa as q,ba as Ge,ca as Ue,da as ze,ga as Ve,ha as He,ia as L,ka as Z,na as Ke}from"./chunk-JPUR2CFX.mjs";import{a as _e,v as Je,w as Qe,z as Xe}from"./chunk-LPBMBW3O.mjs";import{F as Fe,I as Ie,a as Pe,e as ve,o as Q,x as Ee,y as $e,z as I}from"./chunk-IFETCRWE.mjs";import{C as Oe}from"./chunk-EQNW3UC2.mjs";import{g as H}from"./chunk-HS4YRX4J.mjs";import{f as be,g as ke,h as F,m as we,n as ye,o as K,t as Se,u as J}from"./chunk-JWTSEDIQ.mjs";import{b as v}from"./chunk-CA5NAXSU.mjs";import{Ba as me,Cd as he,Wb as $,xa as ge,ya as E}from"./chunk-TTFDUKUS.mjs";import{b as fe,k as pe,l as V}from"./chunk-7EANH5PY.mjs";import{readdir as Nt,rm as ct,stat as dt}from"node:fs/promises";import{existsSync as Dt,readFileSync as Mt,writeFileSync as Pt}from"node:fs";import{hostname as vt}from"node:os";import{join as oe}from"node:path";var Et=5e5,x=1e6,$t=100,Ft="taking",st=500;function Wn(e){let t=Be(e),n=[H(e)];return{get version(){return e.version},request:o=>t.request(o),query:(o,s)=>t.query(o,s),queryMore:o=>t.queryMore(o),describeGlobal:async()=>await e.describeGlobal(),toolingObjects:async()=>{try{return(await e.tooling.describeGlobal()).sobjects.map(s=>s.name)}catch{return[]}},serverTime:async()=>(await e.soap.getServerTimestamp()).timestamp,userId:async()=>(await e.soap.getUserInfo()).userId,requestsSent:()=>n.reduce((o,s)=>o+s(),0),countAlso:o=>{n.push(H(o))}}}function It(e){return _e(De(e))}var N=class extends Error{constructor(){super("The checkpoint was stopped before it was taken: nothing of it was kept."),this.name="CheckpointTakeStopped"}},W="No record was read.",Lt={excludedByUser:"Left out as asked.",notFound:"The org has no object of this name.",chatter:"Chatter posts, comments and feeds are left out: Salesforce brings a post back only with what it was posted on.",history:"History is left out: it is the org's own trace of changes.",sharing:"Sharing is left out: the org keeps it itself.",changeEvent:"Change events are left out.",unsupportedKind:"Left out: neither the recycle bin nor an update reaches this kind of object as it reaches a record.",customSetting:"Custom settings are left out unless you pick them as custom settings: they are configuration, which a rewind sets back.",notCustomSetting:"Picked as a custom setting: the org has no custom setting of this name.",files:"Documents of the Documents tab are left out: they are shared content kept in folders, as setup is.",heldWithFiles:"Held with its file (ContentDocument): Salesforce neither deletes nor brings back a file's version on its own, and reads the links of a file through the records they tie it to.",setup:"Users, permissions and setup are left out, and so are the org's own logs and jobs.",platformCreated:"Left out: Salesforce alone creates its records, such as approvals, Einstein insights, Data.com clean info and invoices, and no permission lets a user create one.",metadata:"Left out: it is metadata, which a checkpoint doesn't hold.",notWritable:"Left out: the user SandForge connects as may not create, edit and delete its records.",notDescribed:"Left out: the org would not describe it.",noSystemModstamp:"Left out: it has no SystemModstamp, so nothing would tell a record changed since.",noRecycleBin:"Left out: the org deletes its records for good, with no recycle bin, so nothing would tell one deleted since, nor bring it back.",unreadable:"Left out: the org refuses to read it whole.",noViewAll:"Without View All Data and Modify All Data, an object is held only with View All and Modify All on it, and the user SandForge connects as has neither on this one: a record they cannot see would read as deleted since.",noModifyAll:"Without View All Data and Modify All Data, an object is held only with View All and Modify All on it, and the user SandForge connects as has View All on this one, not Modify All: a rewind could not put back what others changed.",activities:"Without View All Data and Modify All Data, tasks and events are left out: Salesforce has no View All for activities, and a private one linked to no record stays out of sight.",catalog:"Without View All Data and Modify All Data, products and price books are left out: Salesforce has no View All or Modify All for them.",filesNotProven:"Without View All Data and Modify All Data, files are left out: nothing proves the user sees every file.",settingNotProven:"Without View All Data and Modify All Data, custom settings are left out: no permission on an object proves the user sees and writes every row.",parentNotSeen:"Without View All Data and Modify All Data, an object with no permissions of its own is held only when the user has View All and Modify All on every record it hangs from, which is not proven here."};function lt(e){let t=Lt[e.reason],n=e.detail===void 0?t:`${t.replace(/\.$/,"")} (${e.detail}).`;return{objectApiName:e.objectApiName,code:e.reason,reason:it(n),...e.detail===void 0?{}:{detail:it(e.detail)}}}function xt(e,t,n){return{objectApiName:e,code:"pastTheLimit",records:t,limit:n,reason:t>x?`${e} has ${t} records, more than any checkpoint holds of one object (${x}): left out of the checkpoint, and a rewind to it does not touch ${e}. Data Export, in Setup, or a Bulk API query keeps a copy of it.`:`${e} has ${t} records, past the checkpoint's limit of ${n} for one object: left out of the checkpoint, as part of it would be taken for all of it.`}}function Wt(e,t){let n=t;for(;;){let o=e.filter(s=>s<=Math.min(n,x)).reduce((s,a)=>s+a,0);if(o<=n)return n;n=o}}function it(e){return e.length<=st?e:`${e.slice(0,st-1)}\u2026`}function ut(e,t){return{code:"RUN_WRITING",message:`${t.operation==="take"?`A checkpoint of ${e} is being taken`:t.operation==="rewind"?`A rewind is writing to ${e}`:t.operation==="undo"?`An undo is writing to ${e}`:t.operation==="empty"?`An emptying of its objects is writing to ${e}`:`SandForge is deleting checkpoints of ${e}`} (process ${t.pid} on ${t.host}): take the checkpoint once it has ended. ${W}`}}function ft(e){return typeof e!="object"||e===null?void 0:typeof e.errorCode=="string"?v(e):void 0}function B(e,t){return e instanceof X||e instanceof Te||e instanceof N||t?.aborted===!0}var Bt=V({sobjects:pe(be)}).loose();function D(e){return e.toLowerCase()===ke.toLowerCase()}function _t(e,t,n){if(e===void 0)return{why:`the org lists no ${F}`};let o=t.get(e);if(o===void 0)return{why:n.get(e)??"it was not described"};let a=o.fields.find(d=>d.name.toLowerCase()==="linkedentityid")?.referenceTo??[];return a.length===0?{why:"its describe names no record a link ties a file to"}:{linkable:new Set(a.map(d=>d.toLowerCase()))}}async function se(e,t,n){let o=new Map,s=new Map,a=0,d=await Promise.allSettled(n.map(f=>t.describe(f)));for(let[f,i]of d.entries()){let c=n[f],l;if(i.status==="fulfilled"&&"body"in i.value)l=i.value.body;else{if(i.status==="rejected"&&i.reason instanceof X)throw i.reason;a++;try{l=await e.request({method:"GET",url:`/services/data/v${e.version}/sobjects/${$(c)}/describe`})}catch(h){let r=ft(h);if(r===void 0)throw new Error(`The org did not answer the describe of ${c}: ${v(h)}`);s.set(c,r);continue}}let u=Le.safeParse(l);u.success?o.set(c,u.data):s.set(c,"its describe does not read as one")}return{describes:o,errors:s,alone:a}}async function pt(e,t,n){let o=Bt.parse(await e.describeGlobal()),s=await e.toolingObjects?.()??[],a=ye(o.sobjects,{mode:n.mode,...n.objects?{objects:n.objects}:{},...n.excluded?{excluded:n.excluded}:{},...n.customSettings?{customSettings:n.customSettings}:{}},s),d=a.candidates.some(D),f=d?o.sobjects.find(g=>g.name.toLowerCase()===F.toLowerCase())?.name:void 0,i=f===void 0?a.candidates:[...a.candidates,f],{describes:c,errors:l,alone:u}=await se(e,t,i),h,r;if(d){let g=_t(f,c,l);"linkable"in g?h=g.linkable:r=g.why,f!==void 0&&c.delete(f)}let m=Se(a,c,l);if(r!==void 0){let g=m.objects.find(({objectApiName:j})=>D(j));g!==void 0&&(m=J(m,new Map([[g.objectApiName,`its links to records, ${F}, could not be described: ${r}`]])))}let w=await Ce(async g=>(await e.query(g)).records),S=new Map(o.sobjects.map(g=>[g.name,rt(g)])),O=o.sobjects.filter(we),p=new Set(O.map(g=>g.name)),k=[...c.values()],y=[];for(let g of m.objects){let j=c.get(g.objectApiName);j&&y.push({scoped:g,label:S.get(g.objectApiName)??g.objectApiName,describe:j,capture:await xe(j,k,{viewsEncryptedData:w}),...p.has(g.objectApiName)?{customSetting:K(j)}:{}})}return{described:i.length,describedAlone:u,objects:y,leftOut:m.leftOut,addedToPicked:a.addedToPicked,...h!==void 0&&y.some(({scoped:g})=>D(g.objectApiName))?{linkable:h}:{},settings:O.map(g=>({objectApiName:g.name,label:rt(g)}))}}function rt(e){let t=e.label;return typeof t=="string"&&t!==""?t:e.name}async function Gt(e,t,n,o){let s=await Z(t,n.map(({capture:i})=>({objectApiName:i.objectApiName,readMode:i.readMode})),o),a=new Map,d=new Map,f=0;for(let[i,c]of s.entries()){let{objectApiName:l,readMode:u}=n[i].capture;if("count"in c){a.set(l,c.count);continue}f++;let h=Ue(l,u);try{let r=await e.query(h.soql,{scanAll:h.scanAll});if(typeof r.totalSize!="number")throw new Error("The org gave no count of its records.");a.set(l,r.totalSize)}catch(r){let m=ft(r);if(m===void 0)throw new Error(`The org did not count the records of ${l}: ${v(r)}`);d.set(l,m)}}return{counts:a,refused:d,alone:f}}function gt(e,t){return t?.has(e.toLowerCase())===!0&&!D(e)}async function Ut(e,t,n,o,s){let a=[];for(let{objectApiName:i,records:c}of t){let l=$(i);a.push({objectApiName:l,soql:`SELECT COUNT() FROM ${l} WHERE IsDeleted = true AND SystemModstamp < ${q(o)}`,scanAll:!0,counts:"inBin"}),c!==0&&(a.push({objectApiName:l,soql:`SELECT COUNT() FROM ${l} WHERE SystemModstamp >= ${Ge(o)}`,scanAll:!0,counts:"stampedSince"}),gt(l,n)&&a.push({...Ye(l),counts:"links"}))}let d=await Ve(e,a,()=>{},s),f=new Map;return d.forEach((i,c)=>{let{objectApiName:l,counts:u}=a[c],h=i.read?i.totalSize:void 0,r=f.get(l)??{};u==="links"?r.links=h??null:h!==void 0&&(r[u]=h),f.set(l,r)}),{asked:a.length,of:f}}function mt({scoped:e,capture:t,customSetting:n,access:o},s,a,d){return{objectApiName:e.objectApiName,records:s,inBin:a,readOrder:e.readOrder,readMode:t.readMode,undeletable:t.undeletable,cascadeParents:t.cascadeParents,restrictParents:t.restrictParents,fingerprint:d,fields:t.fields,leftOutFields:t.leftOutFields,...n!==void 0?{customSetting:n}:{},...o!==void 0?{access:o}:{}}}function zt(e){let t=e?.orgType==="Sandbox"||e?.orgType==="Scratch";return Ae(je(t)).defaultQueryLimit}async function ht(e,t,n,o,s,a,d,f=kt){let i=n.maxTotal??Et;if(!Number.isInteger(i)||i<1)throw new RangeError(`Not a number of records: ${i}`);let c=Math.min(i,x),{counts:l,refused:u,alone:h}=await Gt(e,t,o.objects,d),r=J({mode:n.mode,objects:o.objects.map(({scoped:b})=>b),leftOut:o.leftOut,packages:[]},u),m=new Map(o.objects.map(b=>[b.scoped.objectApiName,b])),w=r.leftOut.map(lt),S=[];for(let b of r.objects){let A=m.get(b.objectApiName),P=l.get(b.objectApiName);if(!(A===void 0||P===void 0)){if(P>c){w.push(xt(b.objectApiName,P,c));continue}S.push({...A,scoped:{...b,readOrder:S.length},records:P,otherGroups:tt(b.objectApiName,A.capture.fields,A.capture.readMode),recount:{}})}}let O=S.some(({scoped:b})=>D(b.objectApiName))?o.linkable:void 0,p=await Ut(t,S.map(({scoped:b,records:A})=>({objectApiName:b.objectApiName,records:A})),O,a,d);for(let b of S)b.recount=p.of.get(b.scoped.objectApiName)??{};w.sort((b,A)=>b.objectApiName<A.objectApiName?-1:b.objectApiName>A.objectApiName?1:0);let k={};for(let{scoped:b,describe:A}of S)k[b.objectApiName]=Pe(A.fields);let y=Vt(f,nt({described:o.described,describedAlone:o.describedAlone,counted:o.objects.length,countedAlone:h,recounted:p.asked,objects:S.map(b=>({records:b.records,otherGroups:b.otherGroups,...b.recount,entry:mt(b,b.records,0,k[b.scoped.objectApiName].digest)})),pageRows:zt(n.registered),leftOut:w,printsBytes:(await Ie(k)).length})),g={...y,apiRequestsLeft:s.remaining},j={objects:S,leftOut:w,estimate:g,objectLimit:c,prints:k,...O!==void 0?{linkable:O}:{}};if(y.records>i){let b=[...S.map(A=>A.records),...w.flatMap(A=>A.code==="pastTheLimit"?[A.records??0]:[])];return{...j,refusal:{code:"TOO_MANY_RECORDS",message:`The objects this checkpoint would keep hold ${y.records} records in ${n.orgName}, past its limit of ${i}: pick fewer objects. ${W}`,holdingLimit:Wt(b,y.records)}}}let M=ot("take",y.apiRequests,s,n.orgName);return M===void 0?j:{...j,refusal:M}}function bt(e){return{query:t=>e.query(t),queryMore:t=>e.queryMore(t)}}var kt={guard:0,scope:0};function Vt(e,t){if(e.guard+e.scope===0)return t;let n=t.requestsByPhase;return{...t,apiRequests:t.apiRequests+e.guard+e.scope,...n!==void 0?{requestsByPhase:{...n,guard:n.guard+e.guard,scope:n.scope+e.scope}}:{}}}function Ht(e){let t=[...e.mode==="picked"?e.objects??[]:[],...Array.isArray(e.customSettings)?e.customSettings:[]];return new Set(t.map(n=>n.toLowerCase()))}function Kt(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}async function wt(e,t,n,o,s,a){if(s.kind==="org")return{scope:{...o,objects:o.objects.map(p=>({...p,access:"org"}))},reads:kt};let d=o.objects.map(({scoped:p})=>p.objectApiName),f={grants:s.objects,describes:o.objects.map(({describe:p})=>p),customSettings:o.objects.filter(({customSetting:p})=>p!==void 0).map(({scoped:p})=>p.objectApiName)},i=Ze(d,f),c=[],l=0;if(i.length>0)try{let p=await se(e,t,i);c=[...p.describes.values()],l=Math.ceil(i.length/We)+p.alone}catch(p){if(B(p,a))throw p}let u=et(d,{...f,describes:[...f.describes,...c]}),h=Ht(n),r=[],m=[...o.leftOut],w=[];for(let p of o.objects){let k=p.scoped.objectApiName,y=u.get(k);if(y!==void 0&&"access"in y){r.push({...p,access:y.access});continue}let g={objectApiName:k,reason:y?.reason??"noViewAll",...y?.detail!==void 0?{detail:y.detail}:{}};m.push(g),h.has(k.toLowerCase())&&n.unprovenLeftOut!==!0&&w.push(g)}let S=new Set(r.map(({scoped:p})=>p.objectApiName)),O={scope:{...o,objects:r,leftOut:m,addedToPicked:o.addedToPicked.filter(p=>S.has(p))},reads:{guard:s.requests,scope:l}};if(w.length>0){let p=w.length===1;return{...O,refusal:{code:"PERMISSIONS",message:`${n.username} doesn't have View All Data and Modify All Data, and the checkpoint can't hold ${Kt(w.map(k=>k.objectApiName))}, asked for by name. ${w.map(k=>`${k.objectApiName}: ${lt(k).reason}`).join(" ")} Leave ${p?"it":"them"} out, or give the user View All Data and Modify All Data. ${W}`}}}return r.length===0&&o.objects.length>0?{...O,refusal:{code:"PERMISSIONS",message:`${n.username} doesn't have View All Data and Modify All Data, nor View All and Modify All on any object this checkpoint would hold: without them, a checkpoint holds only the objects its user sees and puts back whole. Give the user View All and Modify All on the objects to hold, or View All Data and Modify All Data. `+W}}:O}function Jt(e){return e.objects.map(({scoped:t,label:n,capture:o,records:s,customSetting:a,access:d})=>({objectApiName:t.objectApiName,label:n,...t.namespace!==void 0?{namespace:t.namespace}:{},records:s,undeletable:o.undeletable,leftOutFields:o.leftOutFields,...a!==void 0?{customSetting:a}:{},...d!==void 0?{access:d}:{}}))}function yt(e){let t=e.customSettings;return t!==void 0&&(t==="all"||t.length>0)}async function Qt(e,t,n,o,s){let a=new Map(o.objects.map(u=>[u.scoped.objectApiName,u])),d=n.settings.filter(({objectApiName:u})=>!a.has(u)),f=new Map;if(d.length>0)try{({describes:f}=await se(e,t,d.map(({objectApiName:u})=>u)))}catch(u){if(B(u,s))throw u}let i=d.filter(({objectApiName:u})=>f.has(u)),c=await Z(t,i.map(({objectApiName:u})=>({objectApiName:u,readMode:"query"})),s),l=new Map;return c.forEach((u,h)=>{"count"in u&&l.set(i[h].objectApiName,u.count)}),n.settings.map(({objectApiName:u,label:h})=>{let r=a.get(u);if(r?.customSetting!==void 0)return{objectApiName:u,label:h,kind:r.customSetting,records:r.records};let m=f.get(u),w=l.get(u);return{objectApiName:u,label:h,...m!==void 0?{kind:K(m)}:{},...w!==void 0?{records:w}:{}}})}var Xt={records:0,apiRequests:0,apiRequestsLeft:0,seconds:0,bytes:0};async function Bn(e,t){let n={mode:t.mode,objects:[],leftOut:[],estimate:Xt},o=await ee(bt(e.org),{act:"take",orgName:t.orgName,registered:t.registered,username:t.username,customSettings:yt(t)},{userId:()=>e.org.userId()});if(!o.allowed)return{...n,refusal:o.refusal};let s=e.store.heldBy(o.org.id),a=s===void 0?await e.runWriting?.(o.org.id):void 0,d=Y(e.org,e.signal);try{let f=await te(e.org,t.orgName),i=await wt(e.org,d,t,await pt(e.org,d,t),o.grants,e.signal),{scope:c}=i,l=await e.org.serverTime(),u=await ht(e.org,d,t,c,f,l,e.signal,i.reads),h={mode:t.mode,objects:Jt(u),leftOut:u.leftOut,estimate:u.estimate,files:{held:u.objects.some(({scoped:m})=>D(m.objectApiName)),queryAllFiles:o.queryAllFiles,addedToPicked:c.addedToPicked},customSettings:await Qt(e.org,d,c,u,e.signal)},r=s!==void 0?ut(t.orgName,s):a!==void 0?{code:"RUN_WRITING",message:a}:i.refusal??u.refusal;return r===void 0?h:{...h,refusal:r}}catch(f){throw B(f,e.signal)?new N:f}}function Yt(e){let t=e.requestsSent?()=>e.requestsSent?.()??0:void 0,n={guard:0,scope:0,start:0,counts:0,bin:0,snapshot:0,stability:0},o="guard",s=t?.()??0,a=()=>{if(!t)return;let d=t();n[o]+=d-s,s=d};return{enter(d){a(),o=d},requests(){return t?(a(),{total:Object.values(n).reduce((f,i)=>f+i,0),byPhase:{...n}}):void 0}}}async function qt(e,t){if(t.edition!==void 0)return t.edition;let o=(await e.query("SELECT OrganizationType FROM Organization LIMIT 1")).records[0]?.OrganizationType;if(typeof o!="string"||o==="")throw new Error("The org did not say its edition (Organization.OrganizationType).");return o}var Zt="Automated Process";async function en(e){let n=(await e.query("SELECT Id, Name FROM User WHERE UserType = 'AutomatedProcess'")).records.filter(s=>typeof s.Id=="string"),o=n.find(s=>s.Name===Zt);return o!==void 0?o.Id:n.length===1?n[0].Id:void 0}function St(e){let t=new Date(Date.parse(e)).toISOString();return`${t.slice(0,10)} ${t.slice(11,16)} UTC`}function at(e,t){return e.split(he).join(St(t))}function ne(e){let t=Oe(e);return t===null?Number.NaN:Date.parse(t)}function Ot(e){return typeof e=="string"&&e.length>=15?e.slice(0,15):void 0}async function tn(e,t){let n=new Set;for await(let o of L(Q(e,t))){let s=Ot(o.Id);s!==void 0&&n.add(s)}return n}async function nn(e,t,n,o,s,a){let d={changed:0,deleted:0,created:0};if(!o.live&&!o.deleted)return d;let f=await Xe.read(e,t,n);if(o.live)for await(let i of L(o.live.file)){let c=ne(i.SystemModstamp);if(!(c<=a))continue;let l=f.stampOf(i.Id);l===void 0?d.created++:l!==c&&d.changed++}if(o.deleted){let i;for await(let c of L(o.deleted.file)){if(!(ne(c.SystemModstamp)<=a))continue;if(f.has(c.Id)){d.deleted++;continue}if(!(ne(c.CreatedDate)<s))continue;i??=await tn(e,n);let l=Ot(c.Id);l!==void 0&&!i.has(l)&&d.deleted++}}return d}async function At(e){let t=0;for(let n of await Nt(e,{withFileTypes:!0})){let o=oe(e,n.name);n.isDirectory()?t+=await At(o):n.isFile()&&(t+=(await dt(o)).size)}return t}async function on(e,t){let n=await At(e.dir)-(await dt(e.checkpointFile)).size,o=a=>Buffer.byteLength(`${JSON.stringify({...t,bytes:a},null,2)}
|
|
8
|
+
`,"utf8"),s=n+o(n);return s=n+o(s),s}function sn(e){let t=e.snapshotsFile,n=new Ne({getData:()=>Dt(t)?JSON.parse(Mt(t,"utf8")):{},setData:o=>Pt(t,JSON.stringify(o,null,2),{encoding:"utf8",mode:384})});return n.initialize(),n}var rn=V({organizationId:fe().optional()}).loose();async function an(e,t,n,o,s){let a=sn(e),d=0,f={log:n.handler.log,orgManager:n.handler.orgManager,orgRegistry:n.handler.orgRegistry,configStore:a,broker:{postToWebview:c=>{if(c.type!=="operation:progress")return;let l=c.payload;typeof l.percentage=="number"&&typeof l.currentStep=="string"&&s(l.percentage,l.currentStep)}},services:{getSandforgeSetting:(c,l)=>c==="backup.maxRecordsPerObject"?o:l},nextId:()=>`${e.checkpointId}-${++d}`},i=new Re(f);return i.setBackupRecordStore(new Me(t)),await i.swept(),{handler:i,config:a}}function cn(e,t){return e.slice(0,15)===t.slice(0,15)}async function _n(e,t){let{org:n,store:o,signal:s}=e,a=e.now??(()=>new Date),d=ge.parse([...t.ignoredFields??[]]),f=t.name===void 0?void 0:E.parse(t.name),i=t.nameWithDate;i!==void 0&&E.parse(at(i,a().toISOString()));let c=t.customSettings==="all"?[]:t.customSettings??[];for(let y of[...t.objects??[],...t.excluded??[],...c])$(y);let l=t.beforeRun===void 0?void 0:me.parse(t.beforeRun),u=t.keepDays??ve;I(a(),u);let h=(y,g,j=0,M=0)=>e.onProgress?.({percentage:Math.round(y),processedObjects:j,totalObjects:M,step:g});h(0,`Checking ${t.orgName}`);let r=Yt(n),m=await ee(bt(n),{act:"take",orgName:t.orgName,registered:t.registered,username:t.username,customSettings:yt(t)},{userId:()=>n.userId()});if(!m.allowed)return{taken:!1,refusal:m.refusal};let w=m.org.id,S=$e("ck",a()),O=o.lock(w,"take",S);if("busy"in O)return{taken:!1,refusal:ut(t.orgName,O.busy)};let p,k;try{let y=await e.runWriting?.(w);if(y!==void 0)return{taken:!1,refusal:{code:"RUN_WRITING",message:y}};let g=Y(n,s),j=await qt(n,m.org),M=await te(n,t.orgName);h(2,`Reading the objects of ${t.orgName}`),r.enter("scope");let b=await wt(n,g,t,await pt(n,g,t),m.grants,s);if(b.refusal!==void 0)return{taken:!1,refusal:b.refusal};let{scope:A}=b;r.enter("start");let P=await n.userId(),ie=await en(n),R=await n.serverTime();h(8,`Counting the records of ${A.objects.length} objects`),r.enter("counts");let T=await ht(n,g,t,A,M,R,s,b.reads);if(T.refusal!==void 0)return{taken:!1,refusal:T.refusal};if(T.objects.length===0)throw new Error(`None of the objects asked for can be kept in a checkpoint of ${t.orgName}: ${T.leftOut.map(C=>`${C.objectApiName}: ${C.reason}`).join(" ")||"there are none."}`);if(s?.aborted)throw new N;p=await o.create(w,S);let _=`snapshot-${S}`;k={version:1,checkpointId:S,name:f??(i!==void 0?E.parse(at(i,R)):St(R)),org:{organizationId:w,...t.alias!==void 0?{alias:t.alias}:{},username:t.username,instanceUrl:t.instanceUrl,isSandbox:m.org.sandbox,organizationType:j,tier:m.tier,...t.scratchExpiresAt!==void 0?{scratchExpiresAt:t.scratchExpiresAt}:{}},takenBy:{userId:P,...ie!==void 0?{automatedProcessUserId:ie}:{},viewAllData:m.grants.kind==="org"||m.grants.viewAllData,modifyAllData:m.grants.kind==="org"||m.grants.modifyAllData,queryAllFiles:m.queryAllFiles},readFrom:R,takenAt:R,scope:{mode:t.mode,leftOut:T.leftOut},objects:[],ignoredFields:d,snapshotId:_,movedWhileTaken:{changed:0,deleted:0,created:0},bytes:0,expiresAt:I(a(),u),status:"taking",takenOn:{host:vt(),pid:process.pid},...l!==void 0?{beforeRun:l}:{}},await o.write(k),h(12,"Reading the recycle bin as it was at the checkpoint"),r.enter("bin");let jt=await He(g,T.objects.map(({scoped:C})=>({...ze(C.objectApiName,R),file:Q(p,C.objectApiName)})),s),re=new Map;for(let C of jt){if(!C.read)throw new Error(`The recycle bin of ${C.objectApiName} could not be read whole: ${C.reason}`);re.set(C.objectApiName,C.rows)}r.enter("snapshot");let{records:Ct,files:ae}=await dn(p,_,T,t,e,w,g,h);h(88,"Reading the time on the org"),r.enter("stability");let ce=await n.serverTime();h(90,`Checking what changed in ${t.orgName} while it was read`);let{movedWhileTaken:Tt,notChecked:Rt}=await ln(p,_,T,g,R,ce,s),{prints:de}=T;await o.writeFingerprints(p,de);let G=T.objects.map(C=>{let z=C.scoped.objectApiName;return mt(C,Ct.get(z)??0,re.get(z)??0,de[z].digest)});if(s?.aborted)throw new N;let le={...k,takenAt:ce,objects:G,movedWhileTaken:Tt,bytes:0,expiresAt:I(a(),u),status:"ready",...ae!==void 0?{files:ae}:{}},U={...le,bytes:await on(p,le)};await o.write(U),h(100,`Checkpoint '${U.name}' taken`,G.length,G.length);let ue=r.requests();return{taken:!0,checkpoint:U,notChecked:Rt,...ue!==void 0?{requests:ue}:{},estimate:T.estimate}}catch(y){throw p!==void 0&&await un(o,p,k,e),B(y,s)?new N:y}finally{O.lock.release()}}async function dn(e,t,n,o,s,a,d,f){let i=n.objects.filter(r=>r.records>0),c=new Map,l=(s.snapshotFiles??It)(e.dir);if(i.length>0){let r=Math.max($t,n.objectLimit),{handler:m,config:w}=await an(e,l,s,r,(k,y)=>f(15+k*.65,y)),S=await m.backupForPipeline({operationId:t,orgId:o.orgId,objects:i.map(({scoped:k})=>k.objectApiName),fields:new Map(i.map(({scoped:k,capture:y})=>[k.objectApiName,y.fields])),scanAll:i.filter(({capture:k})=>k.readMode==="scanAllLive").map(({scoped:k})=>k.objectApiName),origin:"checkpoint",failWhenTruncated:!0,onConnection:k=>s.org.countAlso?.(k)},s.signal),O=rn.safeParse(w.get(`backup:${t}`)),p=O.success?O.data.organizationId:void 0;if(p===void 0||!cn(p,a))throw new Error(`The snapshot was read from ${p===void 0?"an org that did not say which it is":`another org (${p})`}, not from ${o.orgName}: it is not kept.`);for(let k of S.objects)c.set(k.objectApiName,k.recordCount)}f(82,"Indexing the snapshot",0,n.objects.length);for(let[r,{scoped:m}]of n.objects.entries()){let w=m.objectApiName,S=c.get(w)??0;c.has(w)||(await Ee(oe(e.dir,"backups")),await l.writeFile(Je(e,t,w),""),c.set(w,0));let O=await Qe(e,t,w);if(O.rows!==S)throw new Fe("damaged",`The snapshot of ${w} holds ${O.rows} records where its read kept ${S}: it is not kept.`);f(82+6*(r+1)/n.objects.length,`Indexed ${w}`,r+1,n.objects.length)}let u=n.objects.find(({scoped:r})=>D(r.objectApiName));if(u===void 0||n.linkable===void 0)return{records:c};f(88,"Reading the links of files to the records read");let h=await qe({reader:d,folder:e,snapshotId:t,linked:n.objects.map(({scoped:r})=>r.objectApiName).filter(r=>(c.get(r)??0)>0&>(r,n.linkable)),documentsInSnapshot:(c.get(u.scoped.objectApiName)??0)>0,...s.signal!==void 0?{signal:s.signal}:{}});return{records:c,files:h}}async function ln(e,t,n,o,s,a,d){let f=oe(e.dir,Ft),i={changed:0,deleted:0,created:0},c=[];try{let l=await Ke(o,n.objects.map(({capture:r})=>({objectApiName:r.objectApiName,readMode:r.readMode,held:!1})),s,f,d),u=Date.parse(q(s)),h=Date.parse(a);for(let r of l){if("unread"in r){c.push({objectApiName:r.objectApiName,reason:r.unread});continue}if(!r.moved)continue;let m=await nn(e,t,r.objectApiName,r,u,h);i.changed+=m.changed,i.deleted+=m.deleted,i.created+=m.created}}finally{await ct(f,{recursive:!0,force:!0})}return{movedWhileTaken:i,notChecked:c}}async function un(e,t,n,o){try{n!==void 0&&await e.write({...n,status:"failed"})}catch(s){o.handler.log(`[WARN] checkpoint ${t.checkpointId}: not marked failed: ${v(s)}`)}try{await ct(t.dir,{recursive:!0,force:!0})}catch(s){o.handler.log(`[WARN] checkpoint ${t.checkpointId}: what its take wrote was not removed: ${v(s)}`)}}export{Et as a,x as b,Wn as c,N as d,xt as e,Wt as f,Bn as g,_n as h};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{c as E}from"./chunk-K2FBZIXY.mjs";import{b as S}from"./chunk-T63U4OZJ.mjs";import{h as N}from"./chunk-TZE3Y7IQ.mjs";import{b as h,e as m,k as y,l as b}from"./chunk-7EANH5PY.mjs";var z={kind:"master"};function w(i){return i.available&&i.active&&!i.master}function B(i){let t=i.find(n=>n.defaultRecordTypeMapping);if(t&&w(t))return{kind:"given",info:t,basis:"userDefault"};let e=i.filter(w);return e.length===1?{kind:"given",info:e[0],basis:"onlyOneOpen"}:z}function ie(i){if(i.kind!=="master")return{developerName:i.info.developerName,label:i.info.name,basis:i.basis}}var L=200,j=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/;function se(i,t){let e=t.filter(n=>j.test(n)).slice(0,L).map(n=>`'${n}'`);return`SELECT RecordTypeId, COUNT(Id) n FROM ${N(i)} WHERE Id IN (${e.join(", ")}) GROUP BY RecordTypeId`}var U=b({RecordTypeId:h().nullish(),n:m().int().nonnegative()});function oe(i,t){let e=y(U).safeParse(i);if(!e.success)return{read:0,types:[],unread:"the org answered rows that name no record type count"};let n=new Map;for(let{RecordTypeId:s,n:o}of e.data){let a=K(s??null,t),d=n.get(a.developerName);d?d.rows+=o:n.set(a.developerName,{...a,rows:o})}let r=[...n.values()].sort((s,o)=>o.rows-s.rows);return{read:r.reduce((s,o)=>s+o.rows,0),types:r}}function K(i,t){if(i===null||E(i)){let n=t.find(r=>r.master);return{developerName:n?.developerName??"Master",label:n?.name??"Master"}}let e=t.find(n=>n.recordTypeId.slice(0,15)===i.slice(0,15));return e?{developerName:e.developerName,label:e.name}:{developerName:i,label:i}}function ae(i){if(!i)return;let t=B(i);return t.kind==="given"?t.info.recordTypeId:i.find(e=>e.master)?.recordTypeId}function fe(i){if(typeof i!="object"||i===null)return!1;let{errorCode:t,name:e}=i;return t==="NOT_FOUND"||e==="NOT_FOUND"}import{createHash as R,createHmac as T}from"node:crypto";var p="SANDFORGE_FROZEN_SALT",me=["keep","clear","firstName","lastName","companyName","phoneE164","email","registrationSIV","contractNumber","postalCodeGeneralize","dateMonthStart","dateShift","geoRound1","kmRound10"],f=class extends Error{constructor(){super(`No pseudonymization salt. In VS Code, the first extraction makes one and keeps it in the editor's secret storage, which could not keep it here. On the command line, give it with --salt-file <file>, or set ${p} (bash or zsh: export ${p}="<salt>"; PowerShell: $env:${p} = "<salt>") and start VS Code from that shell. Use the salt the dataset was built with: another one gives the same records other pseudonyms.`),this.name="MissingSaltError"}},V=["Alix","Camille","Dominique","\xC9loi","Faustine","Gabin","H\xE9lo\xEFse","Ibrahim","Jasmine","Kylian","L\xE9a","Mathis","Nour","Oc\xE9ane","Paul","Quitterie","Rayan","Salom\xE9","Th\xE9o","Ursule","Victor","Wendy","Xavier","Yasmine","Zacharie","Ambre","Bastien","Chlo\xE9","Dorian","Emma","Fabien","Gabrielle","Hugo","In\xE8s","Jules","Klara","Louis","Manon","No\xE9","Oph\xE9lie"],H=["Arnaud","Berthelot","Chevallier","Deschamps","Etcheverry","Fontaine","Guibert","Hamonic","Imbert","Jacquin","Kermarrec","Lefebvre","Mignard","Noirot","Ollivier","Perrin","Quentin","Rochefort","Seguin","Thibault","Uberti","Vasseur","Wagner","Xuereb","Yverneau","Zimmermann","Aubry","Barbier","Charpentier","Delattre","Esnault","Fournier","Gosselin","Hervieux","Leloup","Marchand","Navarro","Pasquier","Renard","Sauvage"],v=["Aster","Boreal","C\xE9drat","Delta","Ellipse","Fulmen","Granit","Halcyon","Isatis","Jaspe","Kelvin","Lumen","M\xE9ridien","Noroit","Obsidienne","Pulsar"],k=["Conseil","Services","Industries","Solutions","Groupe","SAS","Partenaires","Logistique"],$="ABCDEFGHJKLMNPRSTUVWXYZ",x=/^(\d{4})-(\d{2})-(\d{2})$/,A=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d{1,3})?(Z|[+-]\d{2}:?\d{2})$/;function Z(i){return Date.parse(i.replace(/([+-]\d{2})(\d{2})$/,"$1:$2"))}var D=864e5,u=class{salt;constructor(t){if(!t)throw new f;this.salt=t}get saltFingerprint(){return R("sha256").update(this.salt).digest("hex").slice(0,12)}get dateShiftDays(){return 200+R("sha256").update(`${this.salt}|dateShift-offset`).digest().readUInt32BE(0)%201}pseudonymize(t,e){if(e==null)return e;switch(t){case"keep":return e;case"clear":return"";case"firstName":return this.pick(t,String(e),V);case"lastName":return this.pick(t,String(e),H);case"companyName":return this.companyName(String(e));case"phoneE164":return this.phoneE164(String(e));case"email":return this.email(String(e));case"registrationSIV":return this.registrationSIV(String(e));case"contractNumber":return this.contractNumber(String(e));case"postalCodeGeneralize":return this.postalCodeGeneralize(String(e));case"dateMonthStart":return this.dateMonthStart(String(e));case"dateShift":return this.dateShift(e);case"geoRound1":return this.roundNumber(e,1);case"kmRound10":return this.roundTo(e,10)}}digest(t,e){return T("sha256",this.salt).update(`${t}|${e}`).digest()}*bytes(t,e){let n=this.digest(t,e),r=0;for(;;){for(let s of n)yield s;r+=1,n=T("sha256",this.salt).update(`${t}|${e}|#${r}`).digest()}}pick(t,e,n){let r=this.digest(t,e);return n[r.readUInt32BE(0)%n.length]}companyName(t){let e=this.digest("companyName",t),n=v[e.readUInt32BE(0)%v.length],r=k[e.readUInt32BE(4)%k.length];return`${n} ${r}`}phoneE164(t){let e=this.bytes("phoneE164",t),n="";for(let r=0;r<4;r++)n+=String(e.next().value%10);return`+3363998${n}`}email(t){return`user-${this.digest("email",t).subarray(0,4).toString("hex")}@example.invalid`}registrationSIV(t){let e=this.bytes("registrationSIV",t),n=()=>$[e.next().value%$.length],r=()=>String(e.next().value%10);return`${n()}${n()}-${r()}${r()}${r()}-${n()}${n()}`}contractNumber(t){let e=this.bytes("contractNumber",t),n="";for(let r of t)r>="0"&&r<="9"?n+=String(e.next().value%10):r>="A"&&r<="Z"?n+=String.fromCharCode(65+e.next().value%26):r>="a"&&r<="z"?n+=String.fromCharCode(97+e.next().value%26):n+=r;return n}postalCodeGeneralize(t){let e=t.trim();if(e.length<=2)return e;if(/^\d+$/.test(e))return e.slice(0,2)+"0".repeat(e.length-2);let n=e.slice(0,2);for(let r of e.slice(2))r>="0"&&r<="9"?n+="0":r>="A"&&r<="Z"||r>="a"&&r<="z"?n+="X":n+=r;return n}dateMonthStart(t){let e=x.exec(t)??A.exec(t);return e?`${e[1]}-${e[2]}-01`:""}dateShift(t){if(typeof t=="string"&&x.test(t))return new Date(Date.parse(`${t}T00:00:00Z`)-this.dateShiftDays*D).toISOString().slice(0,10);if(typeof t=="string"&&A.test(t)){let e=Z(t);if(Number.isFinite(e))return new Date(e-this.dateShiftDays*D).toISOString()}return""}roundNumber(t,e){let n=typeof t=="number"?t:Number(String(t).trim());if(!Number.isFinite(n))return"";let r=10**e,s=Math.round(n*r)/r;return typeof t=="number"?s:String(s)}roundTo(t,e){let n=typeof t=="number"?t:Number(String(t).trim());if(!Number.isFinite(n))return"";let r=Math.round(n/e)*e;return typeof t=="number"?r:String(r)}};import{createHash as Y,randomBytes as X}from"node:crypto";var G=80,W=40,F=1e4,q=64,I=".invalid",g=/\.invalid$/i,C=/[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+/g,J=/\+?(?<!\d)\d(?:[\s.()/-]{0,2}\d){6,}/g;function M(i){return/^(?:(?:00)?330?|0)63998\d{4}$/.test(i.replace(/\D/g,""))}function O(i){return`+3363998${i.replace(/\D/g,"").slice(-4)}`}var Q=/^[\d\s.()/+-]+$/;function _(i,t){if(!Q.test(i))return null;let e=t.slice(3),n=/^[\s(]*\+/.test(i)?[`33${e}`,`330${e}`]:[`0${e}`,`33${e}`,`330${e}`,`0033${e}`,`00330${e}`],r=i.replace(/\D/g,"").length,s=n.find(a=>a.length===r);if(s===void 0)return null;let o=0;return i.replace(/\d/g,()=>s[o++])}function ee(i,t={}){let e=[];for(let n of i){let r=(n.type??"").toLowerCase(),s=S(n.name,r);if(!s)continue;let o=r==="email"||r==="phone",a=r==="email"?G:r==="phone"?W:0,d=n.length!==void 0&&n.length>0?n.length:a;e.push({name:t[n.name]??n.name,kind:s,typed:o,...d>0?{maxLength:d}:{},...n.externalId===!0?{key:!0}:{}})}return e}var P=class{pseudonymizer;upsertKeys;drawnFor=new Map;taken=new Set;exhausted=0;counted=new Map;constructor(t=X(32).toString("hex"),e={}){this.pseudonymizer=new u(t),this.upsertKeys=e.upsertKeys===!0}forObject(t,e,n={}){let r=ee(e,n);if(r.length!==0)return s=>{for(let o of r){let a=s[o.name];if(typeof a!="string")continue;let d=this.neutralize(o,a);d!==a&&(d===null?delete s[o.name]:s[o.name]=d,this.count(t,o))}}}email(t,e=G,n=!1){let r=t.trim();if(r===""||g.test(r))return t;let s=`${r}${I}`;if(s.length<=e)return s;let o=this.shortAddress(r,n);return o.length<=e?o:null}phone(t,e){return/\d/.test(t)?M(t)?(this.taken.add(O(t)),t):this.fictional(t,e):t}report(){let t=[],e=0;for(let[n,r]of this.counted)for(let[s,{kind:o,values:a}]of r)t.push({objectApiName:n,field:s,kind:o,values:a}),e+=a;return{neutralized:!0,fields:t,values:e,...this.exhausted>0?{numbersExhausted:this.exhausted}:{}}}neutralize(t,e){let n=this.upsertKeys&&t.key===!0;return t.typed?t.kind==="email"?this.email(e,t.maxLength,n):this.phone(e,t.maxLength):t.kind==="email"?this.addressesIn(e,t.maxLength,n):this.numbersIn(e,t.maxLength)}addressesIn(t,e,n=!1){let r=a=>e===void 0||a.length<=e,s=t.replace(C,a=>g.test(a)?a:`${a}${I}`);if(s===t||r(s))return s;let o=t.replace(C,a=>g.test(a)?a:this.shortAddress(a,n));return r(o)?o:null}numbersIn(t,e){let n=d=>e===void 0||d.length<=e,r=!1,s=d=>t.replace(J,c=>{if(M(c))return this.taken.add(O(c)),c;let l=this.drawnNumber(c);return l===null?(r=!0,c):_(c,l)??(d?`0${l.slice(3)}`:l)}),o=s(!1);if(r)return null;if(o===t||n(o))return o;let a=s(!0);return n(a)?a:null}fictional(t,e){let n=this.drawnNumber(t);if(n===null)return null;let r=_(t,n);if(r!==null&&(e===void 0||r.length<=e))return r;if(e===void 0||n.length<=e)return n;let s=`0${n.slice(3)}`;return s.length<=e?s:null}drawnNumber(t){let e=t.replace(/[^\d+]/g,""),n=this.drawnFor.get(e);if(n!==void 0)return n;if(this.taken.size>=F)return this.exhausted+=1,null;let r=o=>String(this.pseudonymizer.pseudonymize("phoneE164",o)),s=r(e);for(let o=1;this.taken.has(s)&&o<=q;o+=1)s=r(`${e}#${o}`);for(let o=Number(s.slice(-4));this.taken.has(s);)o=(o+1)%F,s=`+3363998${String(o).padStart(4,"0")}`;return this.drawnFor.set(e,s),this.taken.add(s),s}shortAddress(t,e=!1){let n=t.toLowerCase();return e?`user-${Y("sha256").update(n).digest("hex").slice(0,16)}@example.invalid`:String(this.pseudonymizer.pseudonymize("email",n))}count(t,e){let n=this.counted.get(t)??new Map,r=n.get(e.name)??{kind:e.kind,values:0};r.values+=1,n.set(e.name,r),this.counted.set(t,n)}};export{p as a,me as b,f as c,u as d,G as e,F as f,ee as g,P as h,B as i,ie as j,L as k,se as l,oe as m,ae as n,fe as o};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{a as o,b as t}from"./chunk-MS4FJDFD.mjs";import{d as r}from"./chunk-NTOVCTRS.mjs";var e=r(t()),f=r(o());var export_HttpProxyTransport=f.HttpProxyTransport;var export_jsforce=e.default;export{export_HttpProxyTransport as HttpProxyTransport,export_jsforce as jsforce};
|
|
@@ -4,7 +4,7 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a as _}from"./chunk-
|
|
7
|
+
import{a as _}from"./chunk-GGD7ON3M.mjs";import{j as S}from"./chunk-TTFDUKUS.mjs";var x="#N/A";function I(e,t,r){let n=[],o=new Map,a=t.map(u=>{let m=new Map;for(let[b,h]of D(e,u)){let p=b.toLowerCase(),i=o.get(p);i===void 0&&(i=n.push(b)-1,o.set(p,i)),m.set(i,$(h))}return m}).map(u=>n.map((m,b)=>u.get(b)??"")),l=[n.map(C).join(",")];for(let u of a)l.push(u.length===1&&u[0]===""?'""':u.map(C).join(","));return{text:`${l.join(`
|
|
8
8
|
`)}
|
|
9
9
|
`,columns:n,rows:a,identity:U(e,n,r)}}function y(e,t,r){let n=r==="exact"?E:A;return JSON.stringify(t.map(o=>n(e[o]??"")))}function ue(e){let t=new Map,r=new Set;return e.rows.forEach((n,o)=>{let c=y(n,e.identity,"canonical"),a=t.get(c);a===void 0?t.set(c,o):(r.add(a),r.add(o))}),r}function ie(e){let t=[];for(let[r,n]of e){let o=A(n);o!==""&&t.push(`${r.toLowerCase()}${o}`)}return t.sort().join("")}function J(e,t){return e.map(r=>{let n=t[r];return typeof n=="string"?n:n==null?"":String(n)})}function D(e,t){if(e==="delete"||e==="hardDelete")return[["Id",t.Id]];let r=[];for(let[n,o]of Object.entries(t))n==="attributes"||n==="type"||e==="insert"&&n.toLowerCase()==="id"||O(n,o,r);return r}function O(e,t,r){if(!N(t)){r.push([e,t]);return}for(let[n,o]of Object.entries(t))n!=="attributes"&&O(`${e}.${n}`,o,r)}function N(e){if(e===null||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function $(e){return e===void 0?"":e===null?x:typeof e=="string"?e:e instanceof Date?Number.isNaN(e.getTime())?"":e.toISOString():typeof e=="object"?JSON.stringify(e):String(e)}function C(e){return/[",\r\n]/.test(e)?`"${e.replaceAll('"','""')}"`:e}function U(e,t,r){let n=e==="insert"?void 0:e==="upsert"?r:"Id",o=n===void 0?-1:t.findIndex(c=>c.toLowerCase()===n.toLowerCase());return o>=0?[o]:t.map((c,a)=>a)}function E(e){return e===x?"":e.replace(/\r\n?/g,`
|
|
10
10
|
`)}var T=/^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/,v=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;function A(e){let t=E(e),r=t.toLowerCase();if(r==="true"||r==="false")return r;if(T.test(t))return String(Number(t));let n=v.exec(t);if(n){let o=t.includes("T")&&n[1]===void 0,c=Date.parse(o?`${t}Z`:t);if(!Number.isNaN(c))return`@${c}`}return _(t)??t}var F="No result returned by Bulk API job",K="Record not processed by Bulk API job",B=10,w=5e3;function H(e){if(e===!0||e==="true")return!0;if(e===!1||e==="false")return!1}function z(e,t,r){let n=t.rows.length,o=[],c=[],a=0,l=[],u=new Array(n).fill(!1),m=(i,s,g)=>{s>=0&&s<n&&!u[s]?(u[s]=!0,o.push({recordIndex:s,id:i,success:!0,...g!==void 0?{created:g}:{}})):(a++,i!==void 0&&c.push(i))},b=(i,s,g)=>{s>=0&&s<n&&!u[s]?(u[s]=!0,o.push({recordIndex:s,success:!1,error:i,...g?{state:g}:{}})):l.push(i)},h=r?` (${r})`:"";if(Array.isArray(e))e.forEach((i,s)=>{i.success?m(i.id,s):b(i.errors?.join(", ")??"Unknown error",s)});else{let i=[];for(let f of e.successfulResults??[]){let k=typeof f.sf__Id=="string"?f.sf__Id:void 0,R=H(f.sf__Created);i.push({row:f,settle:d=>m(k,d,R),orphan:()=>m(k,-1)})}for(let f of e.failedResults??[]){let k=typeof f.sf__Error=="string"&&f.sf__Error.length>0?f.sf__Error:"Unknown error";i.push({row:f,settle:R=>b(k,R),orphan:()=>b(k,-1)})}let s=e.unprocessedRecords;for(let f of Array.isArray(s)?s:[]){let k=`${K}${h}`;i.push({row:f,settle:R=>b(k,R,"unprocessed"),orphan:()=>b(k,-1)})}let g=i;for(let f of["exact","canonical"])g.length>0&&(g=W(f,g,t,u));for(let f of g)f.orphan()}let p=`${F}${h}${Z(c,l)}`;for(let i=0;i<n;i++)u[i]||b(p,i,"no-result");return o.sort((i,s)=>i.recordIndex-s.recordIndex),{outcomes:o,unattributedSuccessIds:c,unattributedSuccesses:a,unattributedFailures:l}}function W(e,t,r,n){let o=new Map;r.rows.forEach((a,l)=>{if(n[l])return;let u=y(a,r.identity,e),m=o.get(u);m?m.push(l):o.set(u,[l])});let c=[];for(let a of t){let l=y(J(r.columns,a.row),r.identity,e),u=o.get(l)?.shift();u===void 0?c.push(a):a.settle(u)}return c}function Z(e,t){let r=[];if(e.length>0){let n=e.slice(0,B).join(", "),o=e.length>B?` and ${e.length-B} more`:"";r.push(`wrote ${e.length} record(s) no row was matched to: ${n}${o}`)}return t.length>0&&r.push(`did not write ${t.length} row(s) no row was matched to, the first for: ${t[0]}`),r.length>0?`; the job ${r.join("; it ")}`:""}function V(e){let t;try{t=e.id}catch{return}return typeof t=="string"&&/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/.test(t)?t:void 0}function q(e){if(e.state!=="JobComplete")return e.errorMessage||`job ${e.state}`}async function X(e){try{await e.abort()}catch{}}var P=class{threshold;constructor(t=S.REST_API_BATCH_SIZE){this.threshold=t}shouldUseBulkApi(t){return t>this.threshold}getThreshold(){return this.threshold}async executeBulk(t,r,n,o,c){if(!t.bulkManager.canStartNewJob())throw new Error("Maximum concurrent bulk jobs reached");let a=I(n,o,c),l=t.connection.bulk2.createJob({operation:n,object:r,...c?{externalIdFieldName:c}:{}}),u=l.id??`bulk-${crypto.randomUUID()}`,m={id:u,operation:n,object:r,state:"UploadComplete",numberRecordsProcessed:0,numberRecordsFailed:0,totalProcessingTime:0,createdDate:new Date().toISOString()};t.bulkManager.registerJob(m);try{await l.open();let b=V(l);b!==void 0&&t.onOpened?.(b);let h=0;if(t.signal?.aborted||(await l.uploadData(a.text),h=o.length),t.signal?.aborted)return await X(l),t.bulkManager.updateJobState(u,"Aborted"),{totalRecords:h,successCount:0,failureCount:0,failures:[],jobId:u,usedBulkApi:!0,successIds:[],outcomes:[],aborted:!0};await l.close();let p=await l.check();for(let d=0;p.state==="InProgress"||p.state==="UploadComplete";d++){t.bulkManager.updateJobState(u,p.state),t.onProgress?.(p.numberRecordsProcessed??0,o.length);let M=t.pollIntervalMs?.(d)??w;await new Promise(j=>setTimeout(j,M)),p=await l.check()}let i=await l.getAllResults(),s=z(i,a,q(p)),g=s.outcomes.filter(d=>!d.success).map(d=>({recordIndex:d.recordIndex,error:d.error??"Unknown error"}));for(let d of s.unattributedFailures)g.push({recordIndex:-1,error:d});let f=s.outcomes.filter(d=>d.success&&d.id!==void 0).map(d=>d.id).concat(s.unattributedSuccessIds),k=s.outcomes.filter(d=>d.success).length+s.unattributedSuccessIds.length,R=p.state==="JobComplete"?"JobComplete":"Failed";return t.bulkManager.updateJobState(u,R),t.bulkManager.updateJobCounts(u,p.numberRecordsProcessed??o.length,g.length),{totalRecords:o.length,successCount:k,failureCount:g.length,failures:g,jobId:u,usedBulkApi:!0,successIds:f,outcomes:s.outcomes,...s.unattributedSuccessIds.length>0?{unmatchedIds:s.unattributedSuccessIds}:{},...s.unattributedSuccesses>0?{unmatchedWrites:s.unattributedSuccesses}:{}}}catch(b){throw t.bulkManager.updateJobState(u,"Failed"),b}}};var G=3,Q=3,Y=24,ee=750,L=()=>w,be=e=>[5e3,1e4,2e4][e]??3e4,te=60;function ne(e){return Q+e.stateReads+(e.resultReads??G)}function re(e,t="delete"){let r=t==="save"?te:ee;return Y+Math.max(0,e)/r}function oe(e,t=L,r="delete"){let n=re(e,r)*1e3,o=0,c=0;for(;o<n;)o+=Math.max(1,t(c)),c++;return 1+c}function ge(e){return ne({stateReads:oe(e,L,"save")})}export{I as a,ue as b,ie as c,z as d,V as e,q as f,X as g,P as h,G as i,be as j,ne as k,re as l,oe as m,ge as n};
|
|
@@ -4,6 +4,6 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{g as A,k as S}from"./chunk-
|
|
7
|
+
import{g as A,k as S}from"./chunk-XAMBCQPU.mjs";import{e as k,f as w}from"./chunk-IG2MTQRP.mjs";import{Va as T,Wa as h}from"./chunk-TTFDUKUS.mjs";import{mkdir as v,rename as D,writeFile as x}from"node:fs/promises";import*as f from"node:path";var y="CaseId",O=80;function $(e){let t=T.safeParse(e.choice);if(!t.success)return{ok:!1,refusals:t.error.issues.map(a=>({code:"choice-invalid",name:a.path.join("."),message:a.message}))};let n=t.data,s=A(e.catalog,n.agent);if(!s)return{ok:!1,refusals:[{code:"agent-absent",name:n.agent,message:`"${n.agent}" is not one of this org's agents`}]};let r=P(n,s,E(e.compiled.tests));if(r.length>0)return{ok:!1,refusals:r};let i=new Map(n.topics.map(a=>[a.packTopic,a])),c=S(s,y)?y:void 0,g=[],o=[];for(let a of e.compiled.tests){if(a.topicKey===null){if(n.guardTopic===null){o.push({test:a.key,reason:"no-guard-topic",message:`"${a.utterance}" is on no topic of the scenario, and no topic of the agent is chosen to decline it: the test is left out`});continue}g.push({key:a.key,utterance:a.utterance,expectedTopic:n.guardTopic,expectedActions:[],expectedOutcome:a.expectedOutcome,contextVariables:[]});continue}let u=i.get(a.topicKey),p=[];if(a.openCase){let m=e.openCaseIds[a.openCase.caseKey];if(m===void 0){o.push({test:a.key,reason:"case-not-written",message:`The case ${a.openCase.caseKey} the test is about was not written by the run: the test is left out`});continue}c!==void 0&&p.push({name:c,value:m})}g.push({key:a.key,utterance:a.utterance,expectedTopic:u.agentTopic,expectedActions:[...u.actions],expectedOutcome:j(a),contextVariables:p})}return g.length===0?{ok:!1,refusals:[{code:"no-test-left",name:e.compiled.packId,message:"No test of the scenario is left to write: "+o.map(a=>a.message).join("; ")}]}:{ok:!0,spec:{name:M(e.compiled.template.name),description:F(e.compiled.packId,e.compiled.seed,e.runId),subjectName:s.name,testCases:g},choice:n,leftOut:o,...c!==void 0?{contextVariable:c}:{}}}function E(e){return[...new Set(e.flatMap(t=>t.topicKey===null?[]:[t.topicKey]))]}function P(e,t,n){let s=[],r=new Map(t.topics.map(o=>[o.name,o])),i=new Set(t.topics.flatMap(o=>o.actions.map(a=>a.name))),c=o=>({code:"topic-absent",name:o,message:`"${o}" is not a topic of the agent ${t.name}`});for(let o of e.topics){n.includes(o.packTopic)||s.push({code:"pack-topic-unknown",name:o.packTopic,message:`"${o.packTopic}" is not a topic of the scenario`});let a=r.get(o.agentTopic);if(!a){s.push(c(o.agentTopic));continue}let u=new Set(a.actions.map(p=>p.name));for(let p of o.actions)u.has(p)||s.push(i.has(p)?{code:"action-not-of-topic",name:p,message:`"${p}" is not an action of the topic ${a.name}, which the agent answers "${o.packTopic}" from`}:{code:"action-absent",name:p,message:`"${p}" is not an action of the agent ${t.name}`})}let g=new Set(e.topics.map(o=>o.packTopic));for(let o of n)g.has(o)||s.push({code:"pack-topic-unmatched",name:o,message:`The topic "${o}" of the scenario is matched to no topic of the agent`});return e.guardTopic!==null&&!r.has(e.guardTopic)&&s.push(c(e.guardTopic)),s}function j(e){if(!e.article)return e.expectedOutcome;let t=e.article.facts.length>0?`, which states: ${e.article.facts.join("; ")}`:"";return`${e.expectedOutcome} The answer draws on the article "${e.article.title}"${t}.`}function M(e){let t=" (SandForge)",n=O-t.length;return`${e.length>n?e.slice(0,n).trimEnd():e}${t}`}function F(e,t,n){let s=n!==void 0?`, written by the seed run ${n}`:"";return`SandForge scenario ${e}, seed ${t}${s}. Its cases are about the records that run wrote: once it is removed, they are about none.`}var C="specs",L=80,V=10;function K(e,t){return G(h(e,t))}function W(e,t,n){let s=n==="agentforce-studio"?"ngtTestSpec":"testSpec";return`${b(e)}-${b(t)}-sandforge-${s}.yaml`}function z(e,t){let n=c=>c.replace(/[^A-Za-z0-9]+/g,"_").replace(/^_+|_+$/g,""),s=`${n(t)}_SandForge`,r=n(e);/^[A-Za-z]/.test(r)||(r=`Agent_${r}`.replace(/_+$/,""));let i=L-s.length-1;return r=r.slice(0,i).replace(/_+$/,""),`${r}_${s}`}function Z(e){let t=e.runner==="agentforce-studio"?["--test-runner","agentforce-studio"]:[],n=["sf","agent","test","create","--spec",e.specPath,"--api-name",e.apiName,...t,"-o",e.alias],s=["sf","agent","test","run","--api-name",e.apiName,"--wait",String(V),...t,"-o",e.alias];return{create:{argv:n,line:R(n)},run:{argv:s,line:R(s)}}}function te(){return{mkdir:async e=>{await v(e,{recursive:!0})},writeNew:async(e,t)=>{try{return await x(e,t,{encoding:"utf8",flag:"wx"}),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}},replace:async(e,t)=>{let n=`${e}.${process.pid}.tmp`;await x(n,t,"utf8"),await D(n,e)}}}async function X(e,t){let n=W(t.model.subjectName,t.packId,t.runner),s=`${C}/${n}`,r=f.join(t.projectDir,C,n),i=K(t.model,t.runner);if(await e.mkdir(f.dirname(r)),t.overwrite===!0)await e.replace(r,i);else if(!await e.writeNew(r,i))return{kind:"exists",path:r,specPath:s};let c=z(t.model.subjectName,t.packId);return{kind:"written",path:r,specPath:s,apiName:c,commands:Z({specPath:s,apiName:c,alias:t.alias,runner:t.runner})}}async function ne(e,t){let n=w(t.sidecar,t.pack);if(!n.ok)return{kind:"refused",refusals:[{code:"pack-changed",name:t.pack.id,message:n.message}]};let s=$({compiled:n.compiled,catalog:t.catalog,choice:t.choice,openCaseIds:t.sidecar.openCases,runId:t.sidecar.runId});if(!s.ok)return{kind:"refused",refusals:s.refusals};let{choice:r}=s,i=await X(e,{projectDir:t.projectDir,model:s.spec,runner:r.runner,packId:t.pack.id,alias:t.alias,...t.overwrite!==void 0?{overwrite:t.overwrite}:{}});return i.kind==="exists"?i:{...i,leftOut:s.leftOut,sidecar:k(t.sidecar,r)}}function G(e){return`${l(e,0).join(`
|
|
8
8
|
`)}
|
|
9
9
|
`}function l(e,t){let n=" ".repeat(t),s=[];for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let c=`${n}${J(r)}:`;Array.isArray(i)?i.length===0?s.push(`${c} []`):s.push(c,...I(i,t+2)):d(i)?Object.values(i).every(g=>g===void 0)?s.push(`${c} {}`):s.push(c,...l(i,t+2)):s.push(`${c} ${_(i)}`)}return s}function I(e,t){let n=" ".repeat(t),s=[];for(let r of e){let i=Array.isArray(r)?r.length===0?void 0:I(r,t+2):d(r)&&Object.values(r).some(c=>c!==void 0)?l(r,t+2):void 0;if(i===void 0){s.push(`${n}- ${Array.isArray(r)?"[]":d(r)?"{}":_(r)}`);continue}s.push(`${n}- ${i[0].slice(t+2)}`,...i.slice(1))}return s}function d(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function J(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)?e:N(e)}function _(e){if(typeof e=="string")return N(e);if(typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return String(e);if(e===null)return"null";throw new TypeError(`No YAML scalar for ${typeof e}`)}function N(e){return JSON.stringify(e).replace(/[\u007f-\u009f\u2028\u2029\ufeff\ufffe\uffff]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}function b(e){return e.replace(/[^A-Za-z0-9_-]/g,"_")}function R(e){return e.map(t=>/^[A-Za-z0-9_./:@=+,-]+$/.test(t)?t:`"${t.replace(/(["\\])/g,"\\$1")}"`).join(" ")}export{C as a,V as b,K as c,W as d,z as e,Z as f,te as g,X as h,ne as i,G as j};
|
|
@@ -4,7 +4,7 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{
|
|
7
|
+
import{F as k,d as I,l as H,m as W,n as K}from"./chunk-IFETCRWE.mjs";import{C as at}from"./chunk-EQNW3UC2.mjs";import{a as J}from"./chunk-GGD7ON3M.mjs";import{b as N,l as j}from"./chunk-7EANH5PY.mjs";import{createReadStream as $t}from"node:fs";import{appendFile as Ut,stat as jt,writeFile as Jt}from"node:fs/promises";import{StringDecoder as Ht}from"node:string_decoder";import{promisify as dt}from"node:util";import{createGunzip as Wt,gunzip as Kt,gzip as Gt}from"node:zlib";var Yt=dt(Gt),Zt=dt(Kt),Xt=64*1024,Vt=".gz",Qt=6,A=10,ft=4,ut=Buffer.from("SF","latin1"),Y=8,F=6+Y,Z=A+F,X=Z+2+8;function B(s){return`${s}${Vt}`}async function qt(s){let t=await Yt(s,{level:Qt});if(t[3]!==0)throw new Error("zlib wrote a gzip header with flags set");let e=Buffer.from(t.subarray(0,A));e[3]=ft;let n=Buffer.alloc(F);return n.writeUInt16LE(F-2,0),ut.copy(n,2),n.writeUInt16LE(Y,4),n.writeUInt32LE(t.length+F,6),n.writeUInt32LE(s.length,10),Buffer.concat([e,n,t.subarray(A)])}function ht(s){if(s.length<Z||s[0]!==31||s[1]!==139||s[2]!==8||s[3]!==ft||s.readUInt16LE(A)!==F-2||!s.subarray(A+2,A+4).equals(ut)||s.readUInt16LE(A+4)!==Y)return;let t=s.readUInt32LE(A+6),e=s.readUInt32LE(A+10);return t>=X&&e>0?{total:t,raw:e}:void 0}function te(s,t=Xt){let e=[],n=0,r=0;for(;r<s.length;){let i=s.indexOf(10,r),o=i<0?s.length:i+1;o-n>t&&r>n&&(e.push(s.subarray(n,r)),n=r),r=o,r-n>=t&&(e.push(s.subarray(n,r)),n=r)}return r>n&&e.push(s.subarray(n,r)),e}async function ct(s){let t=te(Buffer.from(s,"utf8"));return Buffer.concat(await Promise.all(t.map(e=>qt(e))))}function T(s){return s.endsWith(".ndjson")}function _e(s){let t=new Map,e=(n,r)=>{let i=r(t.get(n)??Promise.resolve());return t.set(n,i),i.then(()=>{t.get(n)===i&&t.delete(n)},()=>{}),i};return{...s,writeFile:(n,r)=>{if(!T(n))return s.writeFile(n,r);let i=B(n);return e(i,o=>o.catch(()=>{}).then(async()=>{let a=r===""?Buffer.alloc(0):await ct(r);await Jt(i,a,{mode:I})}))},appendFile:(n,r)=>{if(!T(n))return s.appendFile(n,r);let i=B(n);return e(i,o=>o.then(async()=>{r!==""&&await Ut(i,await ct(r),{mode:I})}))},exists:n=>s.exists(T(n)?B(n):n),rm:n=>s.rm(T(n)?B(n):n),readLines:n=>T(n)?ee(B(n)):s.readLines(n)}}async function*ee(s){if((await jt(s)).size===0)return;let t=$t(s),e=Wt(),n=o=>{e.destroy(o)};t.on("error",n),t.pipe(e);let r=new Ht("utf8"),i="";try{for await(let o of e){let a=(i+r.write(o)).split(`
|
|
8
8
|
`);i=a.pop()??"",yield*a}i+=r.end(),i!==""&&(yield i)}finally{t.off("error",n),t.destroy(),e.destroy()}}async function G(s,t,e){let n=Buffer.alloc(e),r=0;for(;r<e;){let{bytesRead:i}=await s.read(n,r,e-r,t+r);if(i===0)break;r+=i}return r===e?n:n.subarray(0,r)}async function lt(s,t,e,n){let r;try{r=await Zt(s,{maxOutputLength:t.raw})}catch{throw n(`holds a block that does not inflate at byte ${e}`)}if(r.length!==t.raw)throw n(`holds a block at byte ${e} that inflates to other than its header says`);return r}async function pt(s,t,e,n){let r=await G(s,t,e);if(r.length<e)throw n(`is cut short at byte ${t+r.length}`);let i=ht(r);if(i===void 0)throw n(`holds no block where its index says, at byte ${t}`);if(i.total!==e)throw n(`holds another block than its index says at byte ${t}`);return lt(r,i,t,n)}async function*gt(s,t,e){for(let n=0;n<t;){let r=ht(await G(s,n,Math.min(Z,t-n)));if(r===void 0)throw e(`holds no block at byte ${n}`);if(r.total>t-n)throw e(`is cut short: its block at byte ${n} ends past the file's end`);let i=await G(s,n,r.total);yield{at:n,total:r.total,lines:await lt(i,r,n,e)},n+=r.total}}function*mt(s){let t=0;for(;t<s.length;){let e=s.indexOf(10,t),n=e<0?s.length:e;yield{at:t,length:n-t},t=n+1}}import{randomBytes as Se}from"node:crypto";import{open as C,readFile as it,rename as xe,rm as ke,stat as Ae}from"node:fs/promises";import{dirname as Ft,join as Be}from"node:path";import{closeSync as ne,fstatSync as re,openSync as ie,readSync as se,writeSync as oe}from"node:fs";function Ue(s){let t=ie(s,"a+"),e=re(t).size;return{size:()=>e,append:n=>{let r=Buffer.from(n,"utf8"),i=0;for(;i<r.length;)i+=oe(t,r,i);e+=r.length},read:(n,r)=>{let i=Buffer.alloc(r),o=0;for(;o<r;){let a=se(t,i,o,r-o,n+o);if(a===0)break;o+=a}return i.subarray(0,o)},close:()=>ne(t)}}function yt(s,t){return t===void 0?s:`${s}/${t}`}var wt=/^[A-Za-z][A-Za-z0-9]*$/,bt=/^[0-9a-f]{64}$/,x=1,O=2,z=3,S=4,ae={created:x,existing:O,updated:z},St={[x]:"created",[O]:"existing",[z]:"updated"},xt={[x]:"c",[O]:"e",[z]:"u",[S]:"i"},V={c:x,e:O,u:z,i:S},ce="x",de="a",fe="j",Ot="d",Q="n",P="t",kt="found",ue="found-owed";function je(s,t,e,n){return JSON.stringify([Ot,s,t,e,n])}function Je(s){if(!s.startsWith(`["${Ot}"`))return;let t;try{t=JSON.parse(s)}catch{return}if(!Array.isArray(t))return;let[,,,e,n]=t;if(!(typeof e!="string"||!Number.isFinite(Date.parse(e)))&&!(typeof n!="string"||!Number.isFinite(Date.parse(n))))return{orgAt:e,at:n}}function he(s,t=!1){return JSON.stringify([t?"w":"o",s.objectApiName,s.newId,s.sourceId??"",s.fieldName,s.sourceRefId,s.insertOnly?1:0])}var le=1024*1024,pe=1024*1024,ge=2e4,me=2e4,ye=.6,we=3;function g(s){let t=2166136261;for(let e=0;e<s.length;e++)t^=s.charCodeAt(e),t=Math.imul(t,16777619);return t>>>0}function y(s){let t=2538058380;for(let e=0;e<s.length;e++)t=Math.imul(t^s.charCodeAt(e),1540483477),t^=t>>>15;return t>>>0}var v=class{constructor(t){this.keyAt=t}keyAt;capacity=1024;used=0;h1=new Uint32Array(this.capacity);h2=new Uint32Array(this.capacity);at=new Float64Array(this.capacity);len=new Uint16Array(this.capacity);code=new Uint8Array(this.capacity);get size(){return this.used}get slots(){return this.capacity}find(t,e,n,r){let i=this.capacity-1,o=n&i;for(;;){let a=this.at[o];if(a===0)return~o;if(this.h1[o]===e&&this.h2[o]===n&&(r===a-1||this.keyAt(a-1,this.len[o])===t))return o;o=o+1&i}}offsetOf(t){return this.at[t]-1}lengthOf(t){return this.len[t]}codeOf(t){return this.code[t]}put(t,e,n,r,i,o){let a=t;t<0&&(this.used+1>this.capacity*ye?(this.grow(),a=this.freeSlotFor(n)):a=~t,this.used++,this.h1[a]=e,this.h2[a]=n),this.at[a]=r+1,this.len[a]=i,this.code[a]=o}freeSlotFor(t){let e=this.capacity-1,n=t&e;for(;this.at[n]!==0;)n=n+1&e;return n}grow(){let{h1:t,h2:e,at:n,len:r,code:i}=this;this.capacity*=2,this.h1=new Uint32Array(this.capacity),this.h2=new Uint32Array(this.capacity),this.at=new Float64Array(this.capacity),this.len=new Uint16Array(this.capacity),this.code=new Uint8Array(this.capacity);for(let o=0;o<n.length;o++){if(n[o]===0)continue;let a=this.freeSlotFor(e[o]);this.h1[a]=t[o],this.h2[a]=e[o],this.at[a]=n[o],this.len[a]=r[o],this.code[a]=i[o]}}};function At(s){return s?s[0]==="p"&&s.length>=3?tt(String(s[1]),String(s[2])):s[0]==="g"&&s.length>=3?et(String(s[2])):s[0]===P&&s.length>=2?q(String(s[1])):"":""}function q(s){return`t\0${s}`}function tt(s,t){return`p\0${s}\0${t}`}function et(s){return`g\0${s}`}function*be(s){let t=s.size(),e=0,n=Buffer.alloc(0),r=0;for(;e<t;){let i=s.read(e,Math.min(pe,t-e));if(i.length===0)break;e+=i.length;let o=n.length>0?Buffer.concat([n,i]):i,a=0;for(;;){let d=o.indexOf(10,a);if(d<0)break;d>a&&(yield{offset:r+a,length:d-a,text:o.toString("utf8",a,d)}),a=d+1}n=o.subarray(a),r+=a}}var Bt=class s{constructor(t){this.file=t;this.index=new v((e,n)=>this.idOfLine(e,n)),this.marks=new v((e,n)=>At(w(this.lineAt(e,n)))),this.createdTargets=new v((e,n)=>{let r=w(this.lineAt(e,n));return r?M(String(r[2]??"")):""})}file;index;cache=new Map;pending=[];pendingBytes=0;flushQueued=!1;partStart=Number.POSITIVE_INFINITY;parts=0;mappedCount=0;counts=new Map;earlierByObject=new Map;earlierPastCheckpoint=new Map;checkpointsByObject=new Map;owedCount=0;statuses=new Map;given=new Map;marks;createdTargets;createdUnattributedKeys=new Set;readsHeld=[];withTheirRecordMarked=0;callsSent=0;foundAfterStop=new Set;foundOwingUntold=new Set;plan;static open(t){let e=new s(t);return e.readWhatIsThere(),e}get partCount(){return this.parts}get resumes(){return this.checkpointsByObject.size>0||this.earlierByObject.size>0||this.owedCount>0}get earlierMapped(){return this.partStart===Number.POSITIVE_INFINITY?this.mappedCount:this.mappedBeforePart}mappedBeforePart=0;beginPart(t){this.flush(),this.mappedBeforePart=this.mappedCount,this.withTheirRecordMarked=0,this.partStart=this.file.size(),this.write({part:{n:this.parts,startedAt:t.toISOString()}}),this.parts++,this.flush()}nameSamplePlan(t){if(!bt.test(t.sha256))throw new Error("Not the SHA-256 of a plan.");this.write({sample:{dir:t.dir,sha256:t.sha256}}),this.plan={dir:t.dir,sha256:t.sha256},this.flush()}get samplePlan(){return this.plan?{...this.plan}:void 0}setMapping(t,e,n,r){let i=ae[t],o=g(e),a=y(e),d=this.cache.get(e),u=this.index.find(e,o,a,d?.at),h=u>=0&&this.index.codeOf(u)!==S;h&&this.uncount(e,u,d);let c=JSON.stringify([xt[i],e,n,r??""]),f=this.write(c);if(this.index.put(u,o,a,f,Buffer.byteLength(c),i),i===x&&this.indexCreated(n,f,Buffer.byteLength(c)),h||this.mappedCount++,r){let l=this.countsOf(r);i===x?l.created++:i===O?l.linked++:l.updated++}this.remember(e,{at:f,code:i,targetId:n,objectApiName:r??""})}uncount(t,e,n){let r=this.index.offsetOf(e);if(r<this.partStart)return;let i=this.index.codeOf(e),o=n?.at===r?n:this.recordAt(t,e),a=o?.objectApiName?this.counts.get(o.objectApiName):void 0;a&&(i===x?a.created--:i===O?a.linked--:a.updated--)}countsOf(t){let e=this.counts.get(t);return e||(e={created:0,linked:0,updated:0},this.counts.set(t,e)),e}mapping(t){let e=this.lookUp(t);if(!(!e||e.code===S))return{kind:St[e.code],sourceId:t,targetId:e.targetId,...e.objectApiName?{objectApiName:e.objectApiName}:{},earlier:e.at<this.partStart}}createdTarget(t){let e=M(t);if(this.createdUnattributedKeys.has(e))return!0;if(this.createdTargets.size===0)return!1;let n=this.createdTargets.find(e,g(e),y(e));if(n<0)return!1;let r=this.createdTargets.offsetOf(n),i=w(this.lineAt(r,this.createdTargets.lengthOf(n)));if(!i)return!1;let o=String(i[1]),a=this.index.find(o,g(o),y(o));return a>=0&&this.index.offsetOf(a)===r&&this.index.codeOf(a)===x}indexCreated(t,e,n){let r=M(t);if(!r)return;let i=g(r),o=y(r);this.createdTargets.put(this.createdTargets.find(r,i,o),i,o,e,n,x)}targetOf(t){let e=this.lookUp(t);return e&&e.code!==S?e.targetId:void 0}get mappedSize(){return this.mappedCount}countsByObject(){let t=[];for(let[e,{created:n,linked:r,updated:i}]of this.counts)n+r+i!==0&&t.push(i>0?{objectApiName:e,created:n,linked:r,updated:i}:{objectApiName:e,created:n,linked:r});return t}linkedToCreatedCount(){let t=0;for(let c of this.counts.values())t+=c.linked;if(t===0)return 0;let e=this.partStart===Number.POSITIVE_INFINITY?0:this.partStart,n=(c,f)=>{let l=w(this.lineAt(c,f));return l?String(l[2]).slice(0,15):""},r=(c,f)=>{if(c.offset<e)return;let l=V[String(f[0])];if(l===void 0||l===S||!f[3])return;let p=String(f[1]),m=this.index.find(p,g(p),y(p),c.offset);return m>=0&&this.index.offsetOf(m)===c.offset?l:void 0},i=(c,f,l)=>{let p=g(f),m=y(f);c.put(c.find(f,p,m),p,m,l.offset,l.length,0)},o=(c,f)=>c.size>0&&c.find(f,g(f),y(f))>=0,a=new v(n);for(let c of this.lines()){if(!c.text.startsWith('["'))continue;let f=w(c.text);!f||r(c,f)!==O||this.markedWithTheirRecord(String(f[1]))||i(a,String(f[2]).slice(0,15),c)}if(a.size===0)return 0;let d=new v(n),u=new Set;for(let c of this.lines()){if(!c.text.startsWith('["')||c.offset<e)continue;let f=w(c.text);if(!f)continue;if(f[0]===Q&&Array.isArray(f[2])){for(let p of f[2]){let m=String(p).slice(0,15);o(a,m)&&u.add(m)}continue}if(r(c,f)!==x)continue;let l=String(f[2]).slice(0,15);o(a,l)&&i(d,l,c)}if(d.size===0&&u.size===0)return 0;let h=0;for(let c of this.lines()){if(!c.text.startsWith('["'))continue;let f=w(c.text);if(!f||r(c,f)!==O||this.markedWithTheirRecord(String(f[1])))continue;let l=String(f[2]).slice(0,15);(o(d,l)||u.has(l))&&h++}return h}earlierRecordsOf(t,e=!1){return(e?this.earlierPastCheckpoint:this.earlierByObject).get(t)??0}*mappings(){for(let t of this.lines()){if(!t.text.startsWith('["'))continue;let e=w(t.text);if(!e)continue;let n=V[String(e[0])];if(n===void 0||n===S)continue;let r=String(e[1]),i=this.index.find(r,g(r),y(r),t.offset);if(i<0||this.index.offsetOf(i)!==t.offset)continue;let o=String(e[3]??"");yield{kind:St[n],sourceId:r,targetId:String(e[2]),...o?{objectApiName:o}:{},earlier:t.offset<this.partStart}}}noteRead(t){this.readsHeld.push(t),this.readsHeld.length>=me&&this.settleReads()}settleReads(){let t=this.readsHeld;this.readsHeld=[];for(let e of t){let n=g(e),r=y(e),i=this.index.find(e,n,r,this.cache.get(e)?.at);if(i>=0)continue;let o=JSON.stringify([xt[S],e]),a=this.write(o);this.index.put(i,n,r,a,Buffer.byteLength(o),S)}}wasRead(t){return this.readsHeld.includes(t)?!0:this.index.find(t,g(t),y(t),this.cache.get(t)?.at)>=0}checkpoint(t,e,n){if(n!==void 0&&!wt.test(n))throw new Error(`Not the name of a pass: ${JSON.stringify(n.slice(0,40))}`);this.settleReads(),this.write({at:{object:t,...n!==void 0?{pass:n}:{},...e}}),this.checkpointsByObject.set(yt(t,n),{...e}),this.flush()}checkpoints(){return new Map(this.checkpointsByObject)}owe(t,e=!1){this.owedCount++,this.write(he(t,e))}get owed(){return this.owedCount}*owedPages(t){let e=[];for(let n of this.lines()){if(!n.text.startsWith('["o"')&&!n.text.startsWith('["w"'))continue;let r=w(n.text);if(!r||r.length<7)continue;let[i,o,a,d,u,h,c]=r;e.push({update:{objectApiName:String(o),newId:String(a),sourceId:d?String(d):void 0,fieldName:String(u),sourceRefId:String(h),...c===1?{insertOnly:!0}:{}},toRowWrittenBefore:i==="w"}),e.length>=t&&(yield e,e=[])}e.length>0&&(yield e)}patched(t,e){this.mark(JSON.stringify(["p",t,e]),tt(t,e))}wasPatched(t,e){return this.hasMark(tt(t,e))}mark(t,e){let n=g(e),r=y(e),i=this.marks.find(e,n,r),o=this.write(t);this.marks.put(i,n,r,o,Buffer.byteLength(t),0)}hasMark(t){return this.marks.size>0&&this.marks.find(t,g(t),y(t))>=0}owedLeftByEarlierParts(){let t=new Set;for(let n of this.lines()){if(n.offset>=this.partStart)break;if(!n.text.startsWith('["p"'))continue;let r=w(n.text);r&&r.length>=3&&t.add(`${String(r[1])}\0${String(r[2])}`)}let e=[];for(let n of this.lines()){if(n.offset>=this.partStart)break;if(!n.text.startsWith('["o"'))continue;let r=w(n.text);if(!r||r.length<7)continue;let[,i,o,a,d,u,h]=r;t.has(`${String(o)}\0${String(d)}`)||e.push({objectApiName:String(i),newId:String(o),sourceId:a?String(a):void 0,fieldName:String(d),sourceRefId:String(u),...h===1?{insertOnly:!0}:{}})}return e}oweStatus(t,e,n){this.write(JSON.stringify(["s",t,e,n])),this.tallyStatus({objectApiName:t,id:e,status:n})}tallyStatus(t){let e=this.statuses.get(t.objectApiName);e||(e={count:0,samples:[]},this.statuses.set(t.objectApiName,e)),e.count++,e.samples.length<we&&e.samples.push(t)}gaveStatus(t,e){this.statusGiven(e)||(this.mark(JSON.stringify(["g",t,e]),et(e)),this.given.set(t,(this.given.get(t)??0)+1))}statusGiven(t){return this.hasMark(et(t))}statusesOwed(){let t=new Map;for(let[e,n]of this.statuses){let r=n.count-(this.given.get(e)??0);r<=0||t.set(e,{count:r,samples:n.samples.filter(({id:i})=>!this.statusGiven(i))})}return t}*statusLines(){for(let t of this.lines()){if(!t.text.startsWith('["s"'))continue;let e=w(t.text);!e||e.length<4||(yield{objectApiName:String(e[1]),id:String(e[2]),status:String(e[3])})}}withTheirRecord(t){let e=q(t),n=g(e),r=y(e),i=this.marks.find(e,n,r),o=this.partStart===Number.POSITIVE_INFINITY?0:this.partStart;if(i>=0&&this.marks.offsetOf(i)>=o)return;let a=JSON.stringify([P,t]),d=this.write(a);this.marks.put(i,n,r,d,Buffer.byteLength(a),0),this.withTheirRecordMarked++}get withTheirRecordCount(){return this.withTheirRecordMarked}markedWithTheirRecord(t){if(this.withTheirRecordMarked===0)return!1;let e=q(t),n=this.marks.find(e,g(e),y(e)),r=this.partStart===Number.POSITIVE_INFINITY?0:this.partStart;return n>=0&&this.marks.offsetOf(n)>=r}*withTheirRecordIds(){if(this.withTheirRecordMarked!==0)for(let t of this.lines()){if(t.offset<this.partStart||!t.text.startsWith(`["${P}"`))continue;let e=w(t.text);e&&e.length>=2&&(yield String(e[1]))}}sent(t,e,n,r=new Date,i){this.callsSent++;let o=`${Math.max(0,this.parts-1)}.${this.callsSent}`;return this.write(JSON.stringify([ce,o,t,r.toISOString(),e,n.map(({sourceId:a,fingerprint:d,externalKey:u,jobKey:h})=>i!==void 0&&u!==void 0?[a,d,u]:h!==void 0?[a,d,"",h]:[a,d]),n.flatMap(({owes:a},d)=>(a??[]).map(({field:u,sourceRefId:h,insertOnly:c})=>[d,u,h,c?1:0])),...i!==void 0?[i]:[]])),this.flush(),o}answered(t){this.write(JSON.stringify([de,t]))}jobOpened(t,e){this.write(JSON.stringify([fe,t,e])),this.flush()}createdUnattributed(t,e){if(e.length!==0){this.write(JSON.stringify([Q,t,[...e]]));for(let n of e)this.createdUnattributedKeys.add(M(n))}}wasFoundAfterStop(t){return this.foundAfterStop.has(t)}owesUntold(t){return this.foundOwingUntold.has(t)}flush(){if(this.pending.length===0)return;let t=this.pending.join("");this.pending=[],this.pendingBytes=0,this.file.append(t)}close(){this.settleReads(),this.flush(),this.file.close()}write(t){let e=typeof t=="string"?t:JSON.stringify(t),n=this.file.size()+this.pendingBytes,r=`${e}
|
|
9
9
|
`;return this.pending.push(r),this.pendingBytes+=Buffer.byteLength(r),this.pendingBytes>=le?this.flush():this.flushQueued||(this.flushQueued=!0,queueMicrotask(()=>{this.flushQueued=!1,this.flush()})),n}lineAt(t,e){return t+e>this.file.size()&&this.flush(),this.file.read(t,e).toString("utf8")}idOfLine(t,e){let n=w(this.lineAt(t,e));return n?String(n[1]):""}lookUp(t){let e=this.cache.get(t);if(e)return this.cache.delete(t),this.cache.set(t,e),e;let n=this.index.find(t,g(t),y(t));if(n<0)return;let r=this.recordAt(t,n);return r&&this.remember(t,r),r}recordAt(t,e){let n=this.index.offsetOf(e),r=w(this.lineAt(n,this.index.lengthOf(e)));if(!(!r||String(r[1])!==t))return{at:n,code:this.index.codeOf(e),targetId:String(r[2]??""),objectApiName:String(r[3]??"")}}remember(t,e){if(this.cache.delete(t),this.cache.set(t,e),this.cache.size>ge){let n=this.cache.keys().next().value;n!==void 0&&this.cache.delete(n)}}*lines(){this.flush(),yield*be(this.file)}readWhatIsThere(){for(let t of this.lines()){if(t.text.startsWith('["')){let n=w(t.text);n&&this.readRegistration(t,n);continue}let e;try{e=JSON.parse(t.text)}catch{continue}if(!(typeof e!="object"||e===null)){if("part"in e)this.parts++;else if("sample"in e){let n=e.sample;if(typeof n!="object"||n===null)continue;let{dir:r,sha256:i}=n;if(typeof r!="string"||r===""||typeof i!="string"||!bt.test(i))continue;this.plan={dir:r,sha256:i}}else if("at"in e){let n=e.at;if(typeof n!="object"||n===null)continue;let{object:r,pass:i,lastId:o,read:a,done:d}=n;if(typeof r!="string"||typeof o!="string"||typeof a!="number"||i!==void 0&&(typeof i!="string"||!wt.test(i)))continue;this.checkpointsByObject.set(yt(r,i),{lastId:o,read:a,...d===!0?{done:d}:{}}),i===void 0&&this.earlierPastCheckpoint.delete(r)}}}}readRegistration(t,e){let n=String(e[0]);if(n==="o"||n==="w"){this.owedCount++;return}if(n==="s"){e.length>=4&&this.tallyStatus({objectApiName:String(e[1]),id:String(e[2]),status:String(e[3])});return}if(n==="p"||n==="g"||n===P){let c=At(e);if(!c)return;let f=g(c),l=y(c),p=this.marks.find(c,f,l);if(n==="g"&&p<0){let m=String(e[1]);this.given.set(m,(this.given.get(m)??0)+1)}this.marks.put(p,f,l,t.offset,t.length,0);return}if(n===Q){if(Array.isArray(e[2]))for(let c of e[2])this.createdUnattributedKeys.add(M(String(c)));return}let r=V[n];if(r===void 0)return;let i=String(e[1]);r===x&&(e[4]===kt||e[4]===ue)&&(this.foundAfterStop.add(i),e[4]===kt&&this.foundOwingUntold.add(i));let o=g(i),a=y(i),d=this.index.find(i,o,a),u=d>=0&&this.index.codeOf(d)!==S;if(r===S&&d>=0||(this.index.put(d,o,a,t.offset,t.length,r),r===S))return;r===x&&this.indexCreated(String(e[2]??""),t.offset,t.length),u||this.mappedCount++;let h=String(e[3]??"");h&&(this.earlierByObject.set(h,(this.earlierByObject.get(h)??0)+1),this.earlierPastCheckpoint.set(h,(this.earlierPastCheckpoint.get(h)??0)+1))}};function M(s){return s.slice(0,15)}function w(s){try{let t=JSON.parse(s);return Array.isArray(t)?t:void 0}catch{return}}var Et=2e3,b=15,nt=b,E=nt+8,st={format:1,head:Buffer.from("SFCKIDX1","latin1"),lengthAt:E+8,rowBytes:E+8+4},Mt={format:2,head:Buffer.from("SFCKIDX2","latin1"),memberBytesAt:E+8,lineAt:E+12,lengthAt:E+16,rowBytes:E+20},Lt={1:st,2:Mt},L=st.head.length,Rt=1<<20,Oe=500,R=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Ee=/^[A-Za-z0-9]{15}$/,ot=/^[A-Za-z][A-Za-z0-9_]*$/;function tn(s,t){return L+s*Lt[t].rowBytes}function It(s){return s.replace(/[^A-Za-z0-9_-]/g,"_")}function Ct(s,t,e){if(!ot.test(e)||e.length>80)throw new k("invalid","Not a Salesforce API name");return Be(s.dir,"backups",`${It(t)}__${It(e)}.ndjson`)}var D=class{constructor(t,e){this.layout=t;this.rowBytes=t.rowBytes,this.bytes=e??Buffer.alloc(this.rowBytes*1024),this.size=e?e.length/this.rowBytes:0}layout;bytes;rowBytes;size;push(t,e,n){let r=this.size*this.rowBytes;if(r+this.rowBytes>this.bytes.length){let d=Buffer.alloc(Math.max(this.bytes.length*2,this.rowBytes*1024));this.bytes.copy(d,0,0,r),this.bytes=d}let{memberBytesAt:i,lineAt:o,lengthAt:a}=this.layout;return this.bytes.write(t,r,b,"latin1"),this.bytes.writeDoubleLE(e,r+nt),this.bytes.writeDoubleLE(n.offset,r+E),i!==void 0&&this.bytes.writeUInt32LE(n.memberBytes??0,r+i),o!==void 0&&this.bytes.writeUInt32LE(n.line??0,r+o),this.bytes.writeUInt32LE(n.length,r+a),this.size++}keyAt(t){let e=t*this.rowBytes;return this.bytes.toString("latin1",e,e+b)}holds(t,e){let n=t*this.rowBytes;for(let r=0;r<b;r++)if(this.bytes[n+r]!==e.charCodeAt(r))return!1;return!0}stampAt(t){return this.bytes.readDoubleLE(t*this.rowBytes+nt)}offsetAt(t){return this.bytes.readDoubleLE(t*this.rowBytes+E)}memberBytesAt(t){let e=this.layout.memberBytesAt;return e===void 0?0:this.bytes.readUInt32LE(t*this.rowBytes+e)}lineAt(t){let e=this.layout.lineAt;return e===void 0?0:this.bytes.readUInt32LE(t*this.rowBytes+e)}lengthAt(t){return this.bytes.readUInt32LE(t*this.rowBytes+this.layout.lengthAt)}before(t,e){return this.offsetAt(t)-this.offsetAt(e)||this.lineAt(t)-this.lineAt(e)}wellFormed(t){let e=this.stampAt(t),n=this.offsetAt(t);return Ee.test(this.keyAt(t))&&Number.isFinite(e)&&Number.isSafeInteger(n)&&n>=0&&this.lengthAt(t)>0&&(this.layout.format===1||this.memberBytesAt(t)>=X)}written(){return this.bytes.subarray(0,this.size*this.rowBytes)}},$=class{constructor(t,e){this.rows=t;let n=1024;for(;n<e*2;)n*=2;this.slots=new Uint32Array(n)}rows;slots;used=0;find(t){let e=this.slots.length-1;for(let n=g(t)&e;;n=n+1&e){let r=this.slots[n];if(r===0)return-1;if(this.rows.holds(r-1,t))return r-1}}add(t){let e=this.rows.keyAt(t),n=this.find(e);return n>=0?n:((this.used+1)*2>this.slots.length&&this.grow(),this.place(t,e),this.used++,-1)}place(t,e){let n=this.slots.length-1,r=g(e)&n;for(;this.slots[r]!==0;)r=r+1&n;this.slots[r]=t+1}grow(){let t=this.slots;this.slots=new Uint32Array(t.length*2);for(let e of t)e!==0&&this.place(e-1,this.rows.keyAt(e-1))}};async function U(s,t){try{return await C(s,"r")}catch(e){throw e.code!=="ENOENT"?e:new k("damaged",`The checkpoint\u2019s snapshot of ${t} is not on this machine.`)}}async function*Pt(s,t){let e=await U(s,t);try{let n=Buffer.alloc(Rt),r=Buffer.alloc(0),i=0,o=0,a=0;for(;;){let{bytesRead:d}=await e.read(n,0,Rt,o);if(d===0)break;o+=d;let u=r.length>0?Buffer.concat([r,n.subarray(0,d)]):n.subarray(0,d),h=0;for(let c=u.indexOf(10);c>=0;c=u.indexOf(10,h))a++,c>h&&(yield{number:a,offset:i+h,length:c-h,text:u.toString("utf8",h,c)}),h=c+1;r=Buffer.from(u.subarray(h)),i+=h}r.length>0&&(yield{number:a+1,offset:i,length:r.length,text:r.toString("utf8")})}finally{await e.close()}}async function*Re(s,t,e){let n=await U(s,t);try{let r=0;for await(let i of gt(n,(await n.stat()).size,e))for(let o of mt(i.lines))r++,o.length!==0&&(yield{number:r,offset:i.at,memberBytes:i.total,line:o.at,length:o.length,text:i.lines.toString("utf8",o.at,o.at+o.length)})}finally{await n.close()}}async function Ie(s){try{return await Ae(s),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}function zt(s){let t=at(s);return t===null?Number.NaN:Date.parse(t)}function _(s){let t;try{t=JSON.parse(s)}catch{return}return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}async function ve(s,t){let e=`${s}.${process.pid}-${Se(4).toString("hex")}.tmp`,n=await C(e,"wx",I);try{try{await n.writeFile(t),await n.sync()}finally{await n.close()}await xe(e,s)}catch(r){throw await ke(e,{force:!0}),r}}async function en(s,t,e){let n=Ct(s,t,e),r=B(n),i=await Ie(r)?2:1,o=H(s,e),a=new D(Lt[i]),d=new $(a,0),u=(f,l)=>new k("damaged",`The snapshot of ${e} holds ${l} at line ${f} of its file: it cannot be indexed.`),h=i===2?Re(r,e,f=>new k("damaged",`The snapshot of ${e} ${f}: it cannot be indexed.`)):Pt(n,e);for await(let f of h){let l=_(f.text);if(!l)throw u(f.number,"no record");let p=l.Id;if(typeof p!="string"||!R.test(p))throw u(f.number,"a record without its Id");let m=zt(l.SystemModstamp);if(!Number.isFinite(m))throw u(f.number,`record ${p} without its SystemModstamp`);let Dt=a.push(p.slice(0,b),m,f);if(d.add(Dt)>=0)throw u(f.number,`record ${p} a second time`)}let c=Buffer.concat([a.layout.head,a.written()]);return await ve(o,c),{rows:a.size,bytes:c.length}}var Ne=j({objectApiName:N().regex(ot).max(80),from:N().regex(R),to:N().regex(R)});async function _t(s){let t;try{t=await C(s,"r"),await t.sync()}catch{}finally{await t?.close().catch(()=>{})}}var rt=class s{constructor(t,e){this.current=t;this.original=e}current;original;static none=new s(new Map,new Map);static of(t){let e=new Map;for(let{from:r,to:i}of t)e.set(r.slice(0,b),i);let n=new Map;for(let[r,i]of e)n.set(i.slice(0,b),r);return new s(e,n)}static async read(t){let e;try{e=await it(W(t),"utf8")}catch(i){if(i.code==="ENOENT")return s.none;throw i}let n=e.split(`
|
|
10
10
|
`).slice(0,-1),r=[];for(let[i,o]of n.entries()){if(o==="")continue;let a;try{a=JSON.parse(o)}catch{a=void 0}let d=Ne.safeParse(a);if(!d.success)throw new k("damaged",`The checkpoint\u2019s list of the records a rewind made again is damaged at line ${i+1}.`);r.push(d.data)}return s.of(r)}static async add(t,e){if(e.length===0)return;let n=W(t),r=e.map(({objectApiName:a,from:d,to:u})=>`${JSON.stringify({objectApiName:a,from:d,to:u})}
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{b as l}from"./chunk-CA5NAXSU.mjs";import{
|
|
7
|
+
import{b as l}from"./chunk-CA5NAXSU.mjs";import{od as m,pd as S,td as h,ud as g,vd as y}from"./chunk-TTFDUKUS.mjs";var T=576*60*60*1e3,P=T,f=class extends Error{constructor(e){super(e),this.name="StepCancelledError"}},b=Symbol("stopped");function w(t,e,n,i){let r=new Date().toISOString();return{stepId:t.id,stepName:t.name,stepType:t.type,status:"completed",output:e,summary:i,startTime:n,endTime:r,duration:new Date(r).getTime()-new Date(n).getTime()}}function d(t,e,n){let i=new Date().toISOString();return{stepId:t.id,stepName:t.name,stepType:t.type,status:"failed",error:e,startTime:n,endTime:i,duration:new Date(i).getTime()-new Date(n).getTime()}}function v(t){return y(t.type)?`Step "${t.name}" is a ${String(t.type)} step, which SandForge no longer supports: remove it from the pipeline.`:g(t.type)?`Step "${t.name}" is a ${String(t.type)} step, and this step type cannot run in a pipeline yet.`:`Step "${t.name}" is a "${String(t.type)}" step, a step type this release of SandForge does not have: the pipeline was saved by a later release, or written by hand. Remove the step, or update SandForge.`}function x(t){let{timeout:e}=t;if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e))return`Step "${t.name}" has a timeout that is not a number of milliseconds: ${JSON.stringify(e)}.`;if(e>P)return`Step "${t.name}" has a timeout of ${e} ms, longer than a step can be given: set at most 24 days (${P} ms).`}}function D(t){let e=t.seconds,n=e===void 0?t.durationMs:e;if(typeof n!="number"||!Number.isFinite(n)||n<0)return;let i=e===void 0?n:n*1e3;return i<=T?i:void 0}function C(t){if(t.config.seconds===void 0&&t.config.durationMs===void 0)return`Delay step "${t.name}" has no duration: set how many seconds it waits.`;if(D(t.config)===void 0)return`Delay step "${t.name}" has no usable duration: set a number of seconds, from 0 up to 24 days.`}function H(t,e,n){let i=`Condition step "${t.name}"`;switch(n){case"noEarlierStep":return`${i} tests how the previous step went, and no step comes before it.`;case"noCompare":return`${i} tests how many differences a comparison found, and no Compare step comes before it.`;case"noPrecheck":return`${i} tests ${e}, which a Pre-check hands on, and no Pre-check before it takes that reading.`}}function k(t){let e=t.condition;if(!e||typeof e.field!="string"||e.field.trim()==="")return`Condition step "${t.name}" has no condition to evaluate.`;let n=m(e);return n===void 0?void 0:`Condition step "${t.name}" ${n}.`}function M(t,e){let n=k(t);if(n!==void 0||!t.condition||!e)return n;let i=t.condition,r=h(i,e.steps.slice(0,e.index),e.declared);return r===void 0?void 0:H(t,i.field,r)}function E(t,e){return e?.aborted?Promise.resolve(!1):new Promise(n=>{let i=()=>{clearTimeout(r),n(!1)},r=setTimeout(()=>{e?.removeEventListener("abort",i),n(!0)},t);e?.addEventListener("abort",i,{once:!0})})}var $=class{handlers=new Map;checks=new Map;constructor(){this.registerDefaults()}async execute(e,n){let i=new Date().toISOString(),r=this.check(e);if(r)return d(e,r,i);let o=this.getExecutor(e.type),c=e.retries??0,p="";for(let u=0;u<=c;u++){let s=await this.attempt(o,e,n);if("result"in s)return s.result;if(s.stopped)return{...d(e,s.error,i),status:"stopped"};p=s.error}return d(e,p,i)}async attempt(e,n,i){let r=i.signal;if(r?.aborted)return{error:`Step "${n.name}" was stopped before it started.`,stopped:!0};let o=new AbortController,c=new Promise(a=>{o.signal.addEventListener("abort",()=>a(b),{once:!0})}),p=()=>o.abort();r?.addEventListener("abort",p,{once:!0});let u=!1,s=n.timeout,R=s!==void 0&&s>0?setTimeout(()=>{u=!0,o.abort()},s):void 0;try{let a=await Promise.race([e(n,{...i,signal:o.signal}),c]);return a!==b?{result:a}:u?{error:`Step "${n.name}" timed out after ${s} ms.`}:{error:`Step "${n.name}" was stopped before it finished.`,stopped:!0}}catch(a){return a instanceof f?{error:a.message,stopped:!0}:{error:l(a)}}finally{clearTimeout(R),r?.removeEventListener("abort",p)}}check(e,n){return this.handlers.has(e.type)?x(e)??this.checks.get(e.type)?.(e,n):v(e)}getExecutor(e){return this.handlers.get(e)??this.refusingHandler}registerHandler(e,n,i){this.handlers.set(e,n),i?this.checks.set(e,i):this.checks.delete(e)}wrapHandler(e,n){let i=this.handlers.get(e);i&&this.handlers.set(e,n(i))}refusingHandler=async e=>d(e,v(e),new Date().toISOString());registerDefaults(){this.handlers.set("delay",this.createDelayHandler()),this.checks.set("delay",C),this.handlers.set("condition",this.createConditionHandler()),this.checks.set("condition",M)}createDelayHandler(){return async(e,n)=>{let i=new Date().toISOString(),r=D(e.config);return r===void 0?d(e,C(e)??"No usable duration",i):await E(r,n.signal)?w(e,{delayed:r},i,`Waited ${r/1e3} s.`):d(e,`Delay step "${e.name}" was stopped before its ${r} ms wait ended.`,i)}}createConditionHandler(){return async(e,n)=>{let i=new Date().toISOString(),r=k(e);if(r||!e.condition)return d(e,r??"No condition",i);try{let o=S(e.condition,n.variables);return w(e,{conditionMet:o},i,o?"The condition held.":"The condition did not hold.")}catch(o){return d(e,`Condition step "${e.name}" could not be evaluated: ${l(o)}.`,i)}}}};export{f as a,$ as b};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{b as S,d as z}from"./chunk-
|
|
7
|
+
import{b as S,d as z}from"./chunk-GSKCGQIP.mjs";import{h as I}from"./chunk-TZE3Y7IQ.mjs";import{b as h}from"./chunk-CA5NAXSU.mjs";import{yb as R}from"./chunk-TTFDUKUS.mjs";import{b as f,e as b,f as y,i as A,k,l as m,o as K}from"./chunk-7EANH5PY.mjs";var w="Knowledge__kav",j="CaseArticle",T="Case",P="Summary",B=255,D=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,L=m({name:f(),type:f(),length:b().optional(),extraTypeInfo:f().nullish(),htmlFormatted:y().optional(),createable:y().optional()}).loose(),F=m({fields:k(A())}).loose();function M(e){if(!(e.type!=="textarea"||e.createable!==!0))return e.name===P?"summary":e.extraTypeInfo==="richtextarea"||e.htmlFormatted===!0?"richText":(e.length??0)>B?"longText":void 0}var O={richText:0,longText:1,summary:2};function G(e){let r=F.safeParse(e);if(!r.success)return[];let o=[];for(let t of r.data.fields){let n=L.safeParse(t);if(!n.success)continue;let d=M(n.data);d===void 0||typeof n.data.length!="number"||o.push({name:n.data.name,length:n.data.length,kind:d})}return o.sort((t,n)=>O[t.kind]-O[n.kind]||n.length-t.length||t.name.localeCompare(n.name))}function U(e){return{articleBodyField:e.name,articleBodyLength:e.length,...e.kind==="richText"?{articleBodyHtml:!0}:{}}}var x=m({success:y(),errors:k(K([m({statusCode:f().optional(),message:f().optional()}).loose(),f()])).optional()}).loose();function $(e){let r=x.safeParse(e),o=r.success?r.data.errors?.[0]:void 0;return o===void 0?"The org gave no reason.":typeof o=="string"?o:[o.statusCode,o.message].filter(Boolean).join(": ")||"The org gave no reason."}function N(e){let r=x.safeParse(e);return r.success&&r.data.success}function C(e){return e.slice(0,15)}function X(e){return async({ids:r,results:o})=>{let t=r.get(w)??new Map;if(t.size===0)return{skipped:o.find(u=>u.objectApiName===w)?.errors[0]??`The run wrote no ${w} article, so none was published or linked.`};let n={};return e.plan.publish&&(n.publish=await _(e,t)),e.plan.links.length>0&&(n.links=await v(e,t,r.get(T)??new Map)),n}}async function _(e,r){let o={asked:r.size,done:0,notDone:[]};for(let[t,n]of r){if(e.signal?.aborted){o.notDone.push({key:t,reason:"Left a draft: the run was stopped before it was published."});continue}if(!D.test(n)){o.notDone.push({key:t,reason:`Left a draft: ${n} is not a record id.`});continue}try{await e.org.request({method:"PATCH",url:`/knowledgeManagement/articleVersions/masterVersions/${n}`,body:JSON.stringify({publishStatus:"Online"}),headers:{"Content-Type":"application/json"}}),o.done++}catch(d){o.notDone.push({key:t,reason:`Left a draft: ${h(d)}`})}finally{e.journal?.wroteAgain(w,[n])}}return o}async function v(e,r,o){let t={asked:e.plan.links.length,done:0,notDone:[]},n,d;try{n=await q(e.org,[...r.values()])}catch(s){n=new Map,d=h(s)}let u=[],c=(s,a)=>{t.notDone.push({key:s,reason:`Not linked: ${a}.`})};for(let{caseKey:s,articleKey:a}of e.plan.links){let l=o.get(s),g=r.get(a);if(l===void 0){c(s,"its case was not written");continue}if(g===void 0){c(s,`its article ${a} was not written`);continue}let i=n.get(C(g));if(i===void 0){c(s,`the article of ${a} could not be read back`+(d?` (${d})`:": the org no longer holds its version"));continue}u.push({caseKey:s,caseId:l,articleId:i,versionId:g})}for(let s=0;s<u.length;s+=S){let a=u.slice(s,s+S);if(e.signal?.aborted){for(let{caseKey:i}of a)t.notDone.push({key:i,reason:"Not linked: the run was stopped before it."});continue}let l;try{l=await e.org.sobject(j).create(a.map(({caseId:i,articleId:p})=>({CaseId:i,KnowledgeArticleId:p})),{headers:R()})}catch(i){let p=`Not linked: ${h(i)}`;for(let{caseKey:E}of a)t.notDone.push({key:E,reason:p});l=[]}finally{e.journal?.wroteAgain(T,a.map(({caseId:i})=>i)),e.journal?.wroteAgain(w,[...new Set(a.map(({versionId:i})=>i))])}let g=Array.isArray(l)?l:[l];g.length!==0&&a.forEach(({caseKey:i},p)=>{N(g[p])?t.done++:t.notDone.push({key:i,reason:`Not linked: ${$(g[p])}`})})}return t}async function q(e,r){let o=I(w),t=new Map;for(let n of z(r)){let d=await e.query(`SELECT Id, KnowledgeArticleId FROM ${o} WHERE Id IN (${n})`);for(let u of d.records){let c=u;typeof c?.Id=="string"&&typeof c.KnowledgeArticleId=="string"&&t.set(C(c.Id),c.KnowledgeArticleId)}}return t}export{w as a,G as b,U as c,X as d};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{a as je,b as He}from"./chunk-TYYOBZMU.mjs";import{a as $e,b as be,c as Le,g as Ue}from"./chunk-HS4YRX4J.mjs";import{a as de,b as Ne,c as Fe}from"./chunk-TUACWKIH.mjs";import{a as De}from"./chunk-4TLYUZD5.mjs";import{b as R}from"./chunk-CA5NAXSU.mjs";import{bd as Ce,cd as ce,dc as ae,dd as Ie,gd as ue,hd as Me,id as _e,j as Pe,jd as xe,yb as ve}from"./chunk-TTFDUKUS.mjs";import{b as q,e as Oe,k as B,l as J,v as Re,z as Y}from"./chunk-7EANH5PY.mjs";var Z=class e{static DEFAULT_MAX_PER_ORG=5;static DEFAULT_RECYCLE_INTERVAL=900*1e3;connections=new Map;config;cleanupTimer;recycleTimer;maxPerOrg;recycleIntervalMs;latencySamples=new Map;constructor(t,n){this.config={maxConnections:t?.maxConnections??10,keepAliveInterval:t?.keepAliveInterval??6e4,connectionTimeout:t?.connectionTimeout??3e4,idleTimeout:t?.idleTimeout??3e5},this.maxPerOrg=n?.maxPerOrg??e.DEFAULT_MAX_PER_ORG,this.recycleIntervalMs=n?.recycleIntervalMs??e.DEFAULT_RECYCLE_INTERVAL}acquire(t,n,s){let r=this.connections.get(t);if(r&&r.active)return r.lastUsedAt=Date.now(),r.accessToken=s,r;this.connections.size>=this.config.maxConnections&&this.evictOldest();let o={orgId:t,instanceUrl:n,accessToken:s,createdAt:Date.now(),lastUsedAt:Date.now(),active:!0};return this.connections.set(t,o),o}release(t){let n=this.connections.get(t);n&&(n.lastUsedAt=Date.now())}remove(t){return this.latencySamples.delete(t),this.connections.delete(t)}get(t){return this.connections.get(t)}get size(){return this.connections.size}getConfig(){return{...this.config}}getMaxPerOrg(){return this.maxPerOrg}recordLatency(t,n){if(!Number.isFinite(n)||n<0)return;let s=this.latencySamples.get(t);s||(s=[],this.latencySamples.set(t,s)),s.push(n),s.length>1e3&&s.splice(0,s.length-1e3)}getLatencyMetrics(t){let n=this.latencySamples.get(t);if(!n||n.length===0)return;let s=[...n].sort((u,f)=>u-f),r=s.reduce((u,f)=>u+f,0),o=Math.floor(s.length*.95),a=Math.floor(s.length*.99);return{min:s[0],max:s[s.length-1],avg:Math.round(r/s.length),p95:s[Math.min(o,s.length-1)],p99:s[Math.min(a,s.length-1)],sampleCount:s.length}}getAllLatencyMetrics(){let t=new Map;for(let n of this.latencySamples.keys()){let s=this.getLatencyMetrics(n);s&&t.set(n,s)}return t}cleanupIdle(){let t=Date.now(),n=0;for(let[s,r]of this.connections)t-r.lastUsedAt>this.config.idleTimeout&&(this.connections.delete(s),n++);return n}recycleStale(){let t=Date.now(),n=0;for(let[s,r]of this.connections)t-r.createdAt>this.recycleIntervalMs&&(r.active=!1,this.connections.delete(s),n++);return n}startCleanup(){this.stopCleanup(),this.cleanupTimer=setInterval(()=>this.cleanupIdle(),this.config.keepAliveInterval)}stopCleanup(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0)}startRecycling(){this.stopRecycling(),this.recycleTimer=setInterval(()=>this.recycleStale(),this.recycleIntervalMs)}stopRecycling(){this.recycleTimer&&(clearInterval(this.recycleTimer),this.recycleTimer=void 0)}evictOldest(){let t,n=1/0;for(let[s,r]of this.connections)r.lastUsedAt<n&&(n=r.lastUsedAt,t=s);t&&this.connections.delete(t)}dispose(){this.stopCleanup(),this.stopRecycling(),this.connections.clear(),this.latencySamples.clear()}};var K=class{state="closed";failureCount=0;lastFailureTime=0;halfOpenSuccesses=0;halfOpenInFlight=0;config;constructor(t){this.config={failureThreshold:t?.failureThreshold??5,resetTimeout:t?.resetTimeout??6e4,halfOpenRequests:t?.halfOpenRequests??1}}getState(){return this.state==="open"&&this.shouldTransitionToHalfOpen()&&(this.state="half_open",this.halfOpenSuccesses=0),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t==="half_open"?this.halfOpenInFlight<this.config.halfOpenRequests:!1}recordSuccess(){this.state==="half_open"?(this.halfOpenSuccesses++,this.halfOpenInFlight=Math.max(0,this.halfOpenInFlight-1),this.halfOpenSuccesses>=this.config.halfOpenRequests&&this.reset()):this.failureCount=0}recordFailure(){this.failureCount++,this.lastFailureTime=Date.now(),this.state==="half_open"?this.trip():this.failureCount>=this.config.failureThreshold&&this.trip()}trip(){this.state="open",this.lastFailureTime=Date.now()}reset(){this.state="closed",this.failureCount=0,this.halfOpenSuccesses=0,this.halfOpenInFlight=0}getFailureCount(){return this.failureCount}acquirePermit(){return this.canExecute()?(this.getState()==="half_open"&&this.halfOpenInFlight++,!0):!1}releasePermit(){this.halfOpenInFlight=Math.max(0,this.halfOpenInFlight-1)}getConfig(){return{...this.config}}shouldTransitionToHalfOpen(){return Date.now()-this.lastFailureTime>=this.config.resetTimeout}};var ze=0;function An(){return ze}async function le(e,t){let n=Ue(e);try{return await t()}finally{ze+=n()}}var L=class extends Error{constructor(n,s,r){super(`${n}: ${r}`);this.code=n;this.orgId=s;this.name="OrgConnectionError"}code;orgId};import{homedir as kt,userInfo as St}from"node:os";var Tt=[/^ELECTRON_.+$/,/^VSCODE_(?!(PORTABLE|SHELL_LOGIN|ENV_REPLACE|ENV_APPEND|ENV_PREPEND)).+$/,/^SNAP(|_.*)$/,/^GDK_PIXBUF_.+$/],qe=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED"];function We(e){return Tt.some(t=>t.test(e))}function fe(e=process.env){let t={};for(let[n,s]of Object.entries(e))We(n)||(t[n]=s);return t.NO_COLOR="1",t}function vn(e=process.env){let t=Object.keys(e).filter(f=>(e[f]??"")!==""),n=qe.filter(f=>t.some(d=>d.toUpperCase()===f)),s=t.filter(f=>/^(SF|SFDX)_/i.test(f)).sort(),r=t.filter(f=>We(f)),o=r.filter(f=>f.startsWith("ELECTRON_")).sort(),a=r.length-o.length,u=r.length===0?"none":[...o,...a>0?[`${a} VSCODE_ or other VS Code variables`]:[]].join(", ");return`set: ${n.length>0?n.join(", "):"none of "+qe.join(", ")}; SF_/SFDX_: ${s.length>0?s.join(", "):"none"}; not passed to sf, as a terminal does not get them: ${u}`}function At(){try{return St().username}catch{return process.env.USERNAME??process.env.USER??""}}function Be(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Je(e,t=kt(),n=At()){let s=e;return t.length>3&&(s=s.replace(new RegExp(Be(t),"gi"),"~")),n.length>=2&&(s=s.replace(new RegExp(`(?<=[\\\\/])${Be(n)}(?=[\\\\/]|$)`,"gim"),"<user>")),s.replace(/00D\w{12,15}![\w.]+/g,"<token>").replace(/[\w.+-]+@[\w-]+(\.[\w-]+)+/g,"<username>")}function Cn(e){return e.split(/\r?\n/).map(t=>t.trim()).find(t=>t.length>0)}function Ot(e,t){if(process.platform!=="win32")return e[0];let s=(Object.entries(t).find(([r])=>r.toUpperCase()==="PATHEXT")?.[1]??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);return e.find(r=>{let o=r.lastIndexOf(".");return o>Math.max(r.lastIndexOf("\\"),r.lastIndexOf("/"))&&s.includes(r.slice(o).toLowerCase())})}async function In(e=1e4){let{exec:t}=await import("child_process"),{promisify:n}=await import("util"),s=process.platform==="win32"?"where sf node":"which -a sf node",r=fe(),o,a;try{let h=await n(t)(s,{timeout:e,windowsHide:!0,env:r});o=String(h.stdout)}catch(h){let i=h;o=String(i.stdout??""),o.trim()===""&&(a=Je(i.message??String(h)))}let u=o.split(/\r?\n/).map(h=>h.trim()).filter(h=>h.length>0).map(h=>Je(h)),f=h=>u.filter(i=>new RegExp(`(^|[\\\\/])${h}(\\.[A-Za-z0-9]+)?$`,"i").test(i)),d=f("sf"),c=Ot(d,r);return{sf:d,node:f("node"),...c!==void 0?{runs:c}:{},...a?{failure:a}:{}}}function Q(e,t){let n=(e[t.toLowerCase()]??e[t.toUpperCase()]??"").trim();return n===""?void 0:n}function Rt(e,t){if(t===void 0)return!1;let n=e.hostname.toLowerCase(),s=e.port||(e.protocol==="https:"?"443":"80");return t.split(/[\s,]+/).filter(r=>r!=="").some(r=>{if(r==="*")return!0;let[,o="",a]=/^(.*?)(?::(\d+))?$/.exec(r.toLowerCase())??[];if(a!==void 0&&a!==s)return!1;let u=o.replace(/^\*?\.?/,"");return u!==""&&(n===u||n.endsWith(`.${u}`))})}function Ve(e,t=process.env){let n;try{n=new URL(e)}catch{return}let s=n.protocol==="https:"?Q(t,"https_proxy")??Q(t,"http_proxy"):Q(t,"http_proxy");if(s!==void 0)return Rt(n,Q(t,"no_proxy"))?void 0:s}var Pt="https://login.salesforce.com";async function F(e,t=process.env){let{jsforce:n,HttpProxyTransport:s}=await import("./chunk-L5FGY6YA.mjs"),r=Ve(e.instanceUrl??e.loginUrl??Pt,t),o=new n.Connection({...e,...r!==void 0?{httpProxy:r}:{}});return r===void 0&&(o._transport=new s("")),o}var vt=10*1024*1024,pe=3e4,Ge=pe+2e3,he=`sf did not answer within ${pe/1e3} s \u2014 check the Salesforce CLI`;function Xe(e){return e instanceof Error&&e.message===he}var ge=2e4;function te(e,t,n){let s,r=new Promise((o,a)=>{s=setTimeout(()=>a(new Error(n)),t)});return Promise.race([e,r]).finally(()=>clearTimeout(s))}var U=new Z,Ct=300*1e3,ee=new Map,It={failureThreshold:3,resetTimeout:3e4},Ye=new Map;function Jn(){return U}function Mt(e){let t=Ye.get(e);return t||(t=new K({...It}),Ye.set(e,t)),t}var Ze;var me="panel";function Wn(e){me=e}function _t(e,t=me){return t==="panel"?"Reconnect it on the Organizations page (Try Reconnect on its card).":`Sign in to it again with "sf org login web --alias ${e}" (in a CI job, "sf org login jwt" or "sf org login sfdx-url"), then run the command again, with its --resume if it stopped a run part way.`}function Ke(e=me){return e==="panel"?"Create a new one and import it.":'Create a new one ("sf org create scratch") and give its alias.'}function Qe(e,t){let n=t?.organization_id;if(!(!Ze||typeof n!="string"))try{Ze(e,{organizationId:n})}catch(s){De.warn("Identity observer threw",{orgId:e,error:R(s)})}}var xt="[REDACTED]";function et(e){return typeof e=="string"&&e.length>0&&!e.startsWith(xt)&&!/\s/.test(e)}async function $t(e){if(!/^[\w.@+-]+$/.test(e))throw new Error(`Invalid username format: "${e}"`);let{execFile:t,exec:n}=await import("child_process"),{promisify:s}=await import("util"),r={maxBuffer:vt,timeout:pe,windowsHide:!0,env:fe()},o=i=>te(s(t)("sf",i,r),Ge,he),a=i=>{let g=!1,m,k=new Promise((T,S)=>{m=n(i,r,(E,C)=>{g=!0,E?S(E):T({stdout:C})})});return te(k,Ge,he).catch(T=>{throw!g&&m?.pid!==void 0&&t("taskkill",["/pid",String(m.pid),"/T","/F"],{windowsHide:!0},()=>{}),T})},u=(i,g)=>process.platform==="win32"?a(i):o(g),f=(i,g)=>{let m=i.replace(/\[[0-9;]*m/g,""),k=m.search(/[{[]/);if(k===-1)throw new Error(`Failed to parse "${g}" output: no JSON found. Ensure Salesforce CLI (sf) is installed and the org is authenticated.`);return JSON.parse(m.slice(k)).result??{}},d;try{let{stdout:i}=await u(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),g=f(i,"sf org display");d=typeof g.instanceUrl=="string"?g.instanceUrl:void 0}catch(i){if(Xe(i))throw i;d=void 0}try{let{stdout:i}=await u(`sf org auth show-access-token -o "${e}" --json`,["org","auth","show-access-token","-o",e,"--json"]),g=f(i,"sf org auth show-access-token");if(et(g.accessToken))return{accessToken:g.accessToken,instanceUrl:d}}catch(i){if(Xe(i))throw i}let{stdout:c}=await u(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),h=f(c,"sf org display");if(!et(h.accessToken))throw new Error('Neither "sf org auth show-access-token" nor "sf org display" returned an access token. The org session may have expired \u2014 try re-authenticating with "sf org login".');return!d&&typeof h.instanceUrl=="string"&&(d=h.instanceUrl),{accessToken:h.accessToken,instanceUrl:d}}async function Vn(e,t){return F({instanceUrl:e.instanceUrl,accessToken:e.accessToken??void 0,version:e.version,callOptions:{client:t}})}async function Gn(e){return F({instanceUrl:e.instanceUrl,accessToken:e.accessToken,version:e.version})}async function Xn(e,t,n){let s=e,r=n.getOrg(e);if(!r)throw new Error(`Org not found: ${e}`);let o=await t.getCredentials(e);if(!o?.accessToken||!o.instanceUrl)throw new Error(`No credentials for org "${r.alias}" (${e}). Reconnect the org.`);let a=r.metadata.apiVersion||Pe.DEFAULT_API_VERSION,u=U.get(s),f=Date.now()-(ee.get(e)??0)<Ct;if(u&&u.active&&u.accessToken===o.accessToken&&f)return u.lastUsedAt=Date.now(),F({instanceUrl:u.instanceUrl,accessToken:u.accessToken,version:a});let d=await F({instanceUrl:o.instanceUrl,accessToken:o.accessToken,version:a}),c=Mt(e);if(!c.acquirePermit())throw new L("ORG_TEMPORARILY_UNREACHABLE",e,`"${r.alias}" failed several times in a row, so SandForge waits a moment before calling it again. Try again in a minute.`);let h=Date.now(),i=`identity check did not answer within ${ge/1e3} s`;try{let g=await le(d,()=>te(d.identity(),ge,i)),m=Date.now()-h;return c.recordSuccess(),U.acquire(s,o.instanceUrl,o.accessToken),U.recordLatency(s,m),ee.set(e,Date.now()),Qe(e,g),d}catch(g){let m=Date.now()-h;if(U.remove(s),ee.delete(e),$e(g))try{let S=await $t(r.username),E=S.instanceUrl??o.instanceUrl;if(S.accessToken===o.accessToken&&E===o.instanceUrl)throw new Error("sf CLI token store is stale too (same expired token) \u2014 re-authenticate the org");let C=await F({instanceUrl:E,accessToken:S.accessToken,version:a}),W=await le(C,()=>te(C.identity(),ge,i));return await t.saveOrg(r,{...o,accessToken:S.accessToken,instanceUrl:E}),c.recordSuccess(),U.acquire(s,E,S.accessToken),U.recordLatency(s,m),ee.set(e,Date.now()),Qe(e,W),C}catch(S){c.recordFailure();let E=R(S);n.updateStatus(e,"expired");let C=ae(r,new Date().toISOString().slice(0,10));throw C!==void 0?new L("SCRATCH_ORG_EXPIRED",e,`The scratch org "${r.alias}" expired on ${C}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${Ke()} (cause: ${E})`):new L("ORG_AUTH_EXPIRED",e,`The session with "${r.alias}" has expired and could not be renewed. ${_t(r.alias)} (cause: ${E})`)}c.recordFailure();let k=R(g),T=ae(r,new Date().toISOString().slice(0,10));throw T!==void 0?(n.updateStatus(e,"expired"),new L("SCRATCH_ORG_EXPIRED",e,`The scratch org "${r.alias}" expired on ${T}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${Ke()} (cause: ${k})`)):new Error(`Connection failed for "${r.alias}": ${k}`)}finally{c.releasePermit()}}import{randomUUID as bt}from"node:crypto";import{hostname as Lt,homedir as Ut,uptime as Dt}from"node:os";import{mkdir as Nt,readFile as ct,readdir as Ft,rename as ut,writeFile as jt}from"node:fs/promises";import{dirname as we,join as Ee}from"node:path";function tt(e){let t=e,n=typeof t?.errorCode=="string"?t.errorCode:typeof t?.name=="string"?t.name:void 0;return{success:!1,errors:[{...n?{statusCode:n}:{},message:R(e)}]}}function nt(e){return(Array.isArray(e)?e[0]:e)??{success:!1,errors:[{message:"the org answered nothing"}]}}function as(e){return{typeOrg:()=>be(e),query:async t=>({records:(await e.query(t)).records}),identity:async()=>{let t=await e.identity();return{user_id:t.user_id,organization_id:t.organization_id}},createAssignment:async t=>e.sobject("PermissionSetAssignment").create(t,{headers:ve()}).then(nt,tt),deleteAssignment:async t=>e.sobject("PermissionSetAssignment").destroy(t).then(nt,tt)}}var j=class extends Error{constructor(n){super(n.message);this.refusal=n;this.name="MuteRefusedError"}refusal;get code(){return this.refusal.code}};function Ht(e){return e instanceof j||e instanceof Error&&e.name==="MuteRefusedError"&&"refusal"in e}var zt=60,qt=5*6e4,Bt=3e4,Jt=6e4,Wt=200,Vt=448,Gt=384,oe=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,H=q().regex(oe),Xt=J({id:H,permissionSetId:H,permissionSet:q().min(1).max(255)}),Yt=J({runId:q().min(1).max(255),host:q().min(1).max(255),pid:Oe().int().nonnegative(),hostStartedAt:Y.datetime({offset:!0}),acquiredAt:Y.datetime({offset:!0}),endsAt:Y.datetime({offset:!0}),needs:B(H),assigning:B(H),created:B(Xt)}),dt=J({version:Re(1),organizationId:H,userId:H,leases:B(Yt)}),Zt=J(je),Kt=He(e=>{let t=Zt.safeParse(e);return t.success?t.data:void 0});function lt(e=process.env,t=Ut()){let n=e.SANDFORGE_MUTE_LEASES_DIR;return n!==void 0&&n.trim()!==""?n:Ee(t,".sandforge","mute-leases")}function Qt(e,t,n){if(!oe.test(t)||!oe.test(n))throw new Error("A mute lease is journaled under an org id and a user id.");return Ee(e,`${t.slice(0,15)}-${n.slice(0,15)}.json`)}var ft={host:Lt(),pid:de.pid,startedAt:de.startedAt},en=6e4,D=new Set;function gt(e,t,n){return`${e}
|
|
8
|
+
${t}
|
|
9
|
+
${n}`}function tn(e,t,n,s={}){let r=s.now?.()??Date.now();if(!(Date.parse(e.endsAt)>r)||e.assigning.length>0)return!1;if(e.host!==n.host)return!0;if(e.pid===n.pid&&e.hostStartedAt===n.startedAt)return D.has(gt(t,e.runId,e.acquiredAt));let o=s.bootedAt?.()??Date.now()-Dt()*1e3,a=Date.parse(e.hostStartedAt);return Number.isFinite(a)&&a<o-en?!1:(s.isAlive??Fe)(e.pid)}var nn=e=>new Promise(t=>setTimeout(t,e));function ne(e,t,n){let s=n?.code;return new Error(`The journal of the mute leases in ${we(e)} could not be ${t}${typeof s=="string"?` (${s})`:""}: the user SandForge runs as must read and write that folder, or SANDFORGE_MUTE_LEASES_DIR name another, the same for every run that mutes the org.`)}function sn(e,t){let n=Date.parse(e.acquiredAt);return{pid:e.pid,host:e.host,here:e.host===t.host,until:new Date((Number.isFinite(n)?n:Date.now())+Ne).toISOString()}}function ht(e){return"A run locks it only while it takes, renews or ends a lease of the same org and user, but "+(e.here?`a lock its process could not remove holds until that process has ended, ${e.until} at the latest.`:`a lock a process of another machine could not remove holds until ${e.until}.`)}function rn(e){return`nothing was assigned. ${ht(e)} Run again in a moment, or end process ${e.pid} and run again should none of its runs be muting this org.`}async function se(e,t,n,s,r=rn,o=Jt){let a=n.self??ft,u={self:a,...n.checks?{checks:n.checks}:{}},f=Date.now()+o;for(await Nt(we(e),{recursive:!0,mode:Vt}).catch(d=>{throw ne(e,"made",d)});;){let d;try{d=Kt.acquire(`${e}.lock`,c=>c,u)}catch(c){throw ne(e,"locked",c)}if("lock"in d)try{let c=await on(e,t).catch(i=>{throw ne(e,"read",i)});return await s(c,async i=>{let g=`${e}.${process.pid}-${bt()}.tmp`;try{await jt(g,JSON.stringify(i,null,2),{encoding:"utf8",mode:Gt}),await ut(g,e)}catch(m){throw ne(e,"written",m)}})}finally{d.lock.release()}if(Date.now()>f){let c=sn(d.busy,a);throw new j({code:"MUTE_FAILED",message:`The journal of the mute leases in ${we(e)} stayed locked for a minute by process ${c.pid} on ${c.host}: ${r(c)}`})}await nn(Wt)}}async function on(e,t){let n={version:1,...t,leases:[]},s;try{s=await ct(e,"utf8")}catch(r){if(r.code==="ENOENT")return n;throw r}try{let r=dt.safeParse(JSON.parse(s));if(r.success)return r.data}catch{}return await ut(e,`${e}.${Date.now()}.unreadable`).catch(()=>{}),n}var an=new Set(["ENTITY_IS_DELETED","INVALID_CROSS_REFERENCE_KEY","NOT_FOUND"]);async function re(e,t,n,s){let r=t.leases.filter(c=>c!==n&&s(c)),o=[...n.created],a=new Set,u=n.assigning[0];if(u!==void 0){let c=new Set(t.leases.flatMap(i=>i===n?[]:i.created.map(g=>g.id))),h=await e.query(`SELECT Id, PermissionSetId, PermissionSet.Name FROM PermissionSetAssignment WHERE AssigneeId = '${t.userId}' AND PermissionSetId IN ('${u}')`).then(i=>i.records).catch(()=>[]);for(let i of h){let g=typeof i.Id=="string"?i.Id:void 0,m=typeof i.PermissionSetId=="string"?i.PermissionSetId:void 0;if(!g||!m||c.has(g)||o.some(T=>T.id===g))continue;let k=i.PermissionSet;o.push({id:g,permissionSetId:m,permissionSet:typeof k?.Name=="string"?k.Name:m}),a.add(g)}}let f={removed:[],passed:[],left:[],found:[]};for(let c of o){let h=r.find(m=>m.needs.includes(c.permissionSetId));if(h){h.created.some(m=>m.id===c.id)||h.created.push(c),f.passed.push(c);continue}let i=await e.deleteAssignment(c.id),g=i.errors?.[0]?.statusCode??i.errors?.[0]?.errorCode;i.success||g!==void 0&&an.has(g)?(f.removed.push(c),a.has(c.id)&&f.found.push(c)):f.left.push({...c,why:i.errors?.[0]?.message??g??"the org refused the delete"})}let d=t.leases.indexOf(n);return f.left.length===0?t.leases.splice(d,1):t.leases[d]={...n,endsAt:new Date(0).toISOString(),needs:[],assigning:[],created:f.left.map(({id:c,permissionSetId:h,permissionSet:i})=>({id:c,permissionSetId:h,permissionSet:i}))},f}function N(e){return e.map(t=>t.permissionSet)}function st(e,t){let n=r=>N(r).join(", "),s=[];return e.removed.length>0&&s.push(`What this run had assigned was taken back: ${n(e.removed)}.`),e.passed.length>0&&s.push(`${n(e.passed)} stays assigned for another run that mutes this org as the same user${t?", which takes it back as it ends":""}.`),e.left.length>0&&s.push(`${e.left.map(r=>`${r.permissionSet} (${r.why})`).join(", ")} could not be taken back${t?": the next run that mutes this org takes it back":""}.`),s}function rt(e,t){return`The journal still names this run's lease: this process tries again while it runs, and releases the lease once the journal can be written; the next run that mutes this org from another process releases it at the latest once process ${e} has ended.`+(t?` Until it is released, and before ${t.until}, a run of another process that ends may leave what it holds of ${t.sets.join(", ")} assigned for that lease, which the release takes back.`:"")}function pt(e){let t=e.length===1?"it":"them";return`found assigned to the user the run writes as for a run whose process ended as it assigned ${t}; found by user and set, not by id: had an admin assigned ${t} to that user since, theirs went with ${t}`}async function cn(e,t,n){let s=[];for(let r of[...t.leases])n(r)||s.push(...(await re(e,t,r,n)).found);return s}async function un(e){let t;try{t=(await e.query("SELECT PermissionsAssignPermissionSets, PermissionsManageUsers FROM UserPermissionAccess")).records[0]}catch(n){return`the org would not say whether the user the run writes as may assign permission sets (${R(n)})`}if(!(t?.PermissionsAssignPermissionSets===!0||t?.PermissionsManageUsers===!0))return"the user the run writes as cannot assign permission sets (neither Assign Permission Sets nor Manage Users)"}function ot(e){let t=e.indexOf("__");return t>0&&!e.slice(t+2).includes("__")?{namespace:e.slice(0,t),developerName:e.slice(t+2)}:{namespace:"",developerName:e}}var it=/^[A-Za-z][A-Za-z0-9_]*$/;async function dn(e,t){let s=t.map(ot).filter(a=>it.test(a.developerName)&&(!a.namespace||it.test(a.namespace)));if(s.length===0)return new Map;let r=await e.query("SELECT Id, Name, NamespacePrefix FROM PermissionSet WHERE Name IN ("+[...new Set(s.map(a=>`'${a.developerName}'`))].join(", ")+")"),o=new Map;for(let a of t){let{namespace:u,developerName:f}=ot(a),d=r.records.find(c=>String(c.Name??"").toLowerCase()===f.toLowerCase()&&String(c.NamespacePrefix??"").toLowerCase()===u.toLowerCase());typeof d?.Id=="string"&&o.set(a,d.Id)}return o}async function at(e,t,n){if(n.length===0)return new Map;let s=await e.query(`SELECT Id, PermissionSetId FROM PermissionSetAssignment WHERE AssigneeId = '${t}' AND PermissionSetId IN (${n.map(o=>`'${o}'`).join(", ")})`),r=new Map;for(let o of s.records){let a=o.PermissionSetId,u=o.Id;typeof a=="string"&&typeof u=="string"&&r.set(a,u)}return r}function ye(e,t,n){return{state:t,assigned:[],held:[],permissions:ce(e),silenced:e.silenced.map(s=>({...s})),stillRan:e.stillRuns.map(s=>({...s})),...e.assign.length>0?{alsoLifted:(e.alsoLifts??[]).map(s=>({...s}))}:{},...e.liftsUnread?{liftsUnread:e.liftsUnread.map(s=>({...s}))}:{},...n?{reason:n}:{}}}var mt="nothing found can be muted: no flow, process or workflow rule the run fires has a bypass a permission set of the target holds; the run goes on as without the option";async function ln(e,t,n={}){let s,r;try{let d=await e.typeOrg();s=Le(d),r=d.id}catch(d){return{refused:{code:"MUTE_PRODUCTION",message:`The target did not say what org it is (${R(d)}), and its automation is muted on no org that cannot be told from a production one. Nothing was assigned.`}}}if(s)return{refused:{code:"MUTE_PRODUCTION",message:"The target is a production org: its automation is never muted there, whatever the setting says. Nothing was assigned; run without the option."}};let{plan:o,automation:a,planned:u}=hn(t,n.writes);if(o.assign.length===0)return{plan:o,automation:t,planned:u,acquire:async()=>({outcome:u,release:async()=>u})};let f=await un(e);return f!==void 0?{refused:{code:"MUTE_NO_RIGHT",message:`The target's automation cannot be muted: ${f}. Nothing was assigned: run it without muting the target's automation, or have that user given Assign Permission Sets.`}}:(wt.set(o,await gn(n.dir??lt(),r)),{plan:o,automation:a,planned:u,acquire:d=>pn(e,o,d,n)})}var wt=new WeakMap,fn=/^[A-Za-z0-9]{15}-[A-Za-z0-9]{15}\.json$/;async function gn(e,t){if(!oe.test(t))return 0;let n=`${t.slice(0,15)}-`,s;try{s=await Ft(e)}catch{return 0}let r=0;for(let o of s)if(!(!o.startsWith(n)||!fn.test(o)))try{let a=dt.safeParse(JSON.parse(await ct(Ee(e,o),"utf8")));if(!a.success)continue;for(let u of a.data.leases)r+=(u.assigning.length>0?1:0)+u.created.length}catch{}return r}function hn(e,t){let n=Ce(e,t);return n.assign.length===0?{plan:n,automation:e,planned:ye(n,"nothing",mt)}:{plan:n,automation:Ie(e,ce(n)),planned:ye(n,"planned")}}async function pn(e,t,n,s={}){let r=s.self??ft,o=()=>s.checks?.now?.()??Date.now(),a=s.minutes??zt,u=l=>{throw new j({code:"MUTE_FAILED",message:l})},f=await e.identity().catch(l=>u(`The target would not say who the run writes as (${R(l)}).`)),d={organizationId:f.organization_id,userId:f.user_id},c=Qt(s.dir??lt(),d.organizationId,d.userId),h=t.assign.map(l=>l.permissionSet),i=await dn(e,h).catch(l=>u(`The permission sets to assign could not be read (${R(l)}).`)),g=h.filter(l=>!i.has(l));g.length>0&&u(`The target holds no permission set ${g.join(", ")}: nothing was assigned.`);let m=h.map(l=>i.get(l)),k=new Map(h.map(l=>[i.get(l),l])),T=l=>tn(l,c,r,s.checks),S=new Date(o()).toISOString(),E=gt(c,n,S),C=!1,W=m.map(l=>k.get(l)),yt=s.retryEveryMs??Bt,V,ke=(l,A)=>{if(V!==void 0)return;let p=new Set(l.map(y=>y.id)),O=!1,P=()=>clearInterval(V);V=setInterval(()=>{O||(O=!0,se(c,d,s,async(y,G)=>{let M=y.leases.find(x=>x.runId===n&&x.acquiredAt===S);if(M){M.assigning=[],M.created=[...M.created,...A.filter(b=>!M.created.some(X=>X.id===b.id))].filter(b=>!p.has(b.id));let x=await re(e,y,M,T);for(let b of x.removed)p.add(b.id);await G(y)}P()},void 0,0).catch(()=>{}).finally(()=>{O=!1}))},yt),V.unref?.()},z=await se(c,d,s,async(l,A)=>{let p=N(await cn(e,l,T)),O=await at(e,d.userId,m),P=m.filter(w=>!O.has(w)),y={runId:n,host:r.host,pid:r.pid,hostStartedAt:r.startedAt,acquiredAt:S,endsAt:new Date(o()+a*6e4).toISOString(),needs:m,assigning:[...P],created:[]};l.leases.push(y),D.add(E),await A(l),C=!0;let G=[...y.assigning],M=()=>A(l).then(()=>{G=[...y.assigning]},w=>R(w)),x=async w=>{y.assigning=[];let I=await re(e,l,y,T);D.delete(E);let v=await M();v!==void 0&&ke(I.removed,[...I.passed,...I.left]);let _=v!==void 0&&G.length===0?{sets:W,until:y.endsAt}:void 0,Ae=st(I,v===void 0);return u([w,...v!==void 0&&v!==w?[v]:[],...Ae.length>0?Ae:["Nothing was assigned."],...v!==void 0&&(I.passed.length>0||I.left.length>0||_)?[rt(r.pid,_)]:[],...p.length>0?[`Taking its lease, the run took back ${p.join(", ")}, ${pt(p)}.`]:[]].join(" "))};for(let w of P){let I=await e.createAssignment({AssigneeId:d.userId,PermissionSetId:w});if(y.assigning=y.assigning.filter(_=>_!==w),I.success&&I.id){y.created.push({id:I.id,permissionSetId:w,permissionSet:k.get(w)});let _=await M();if(_!==void 0)return x(_);continue}let v=I.errors?.[0];if((v?.statusCode??v?.errorCode)==="DUPLICATE_VALUE"){let _=await M();if(_!==void 0)return x(_);continue}return x(`${k.get(w)} could not be assigned to the user the run writes as: ${v?.message??v?.statusCode??"the org refused it"}.`)}let b=await at(e,d.userId,m).catch(()=>new Map),X=m.filter(w=>!b.has(w));if(X.length>0)return x(`Read back, the user the run writes as does not hold ${X.map(w=>k.get(w)).join(", ")}.`);let Et=new Set(y.created.map(w=>w.permissionSetId));return{endsAt:y.endsAt,assigned:y.created.map(w=>w.permissionSet),held:m.filter(w=>!Et.has(w)).map(w=>k.get(w)),found:p}}).catch(l=>{if(D.delete(E),Ht(l))throw l;return u(`${R(l)}${C?"":" Nothing was assigned."}`)}),$={...ye(t,"muted"),assigned:z.assigned,held:z.held,leaseEndsAt:z.endsAt,...z.found.length>0?{tookBackOfEnded:z.found}:{}},Se=s.renewEveryMs??qt,ie=Se>0?setInterval(()=>{se(c,d,s,async(l,A)=>{let p=l.leases.find(P=>P.runId===n&&P.acquiredAt===S);if(!p||!D.has(E))return;let O=new Date(o()+a*6e4).toISOString();p.endsAt=O,await A(l),$.leaseEndsAt=O}).catch(()=>{})},Se):void 0;ie?.unref?.();let Te;return{outcome:$,release:()=>(Te??=(async()=>{ie&&clearInterval(ie);let l={};try{await se(c,d,s,async(p,O)=>{let P=p.leases.find(y=>y.runId===n&&y.acquiredAt===S);D.delete(E),P&&(l.done=await re(e,p,P,T),await O(p))},p=>`nothing was taken back. ${ht(p)} Should none of its runs be muting this org, end process ${p.pid}`);let A=l.done?.left??[];return{...$,released:A.length===0,takenBack:N(l.done?.removed??[]),...l.done&&l.done.passed.length>0?{passed:N(l.done.passed)}:{},...A.length>0?{notTakenBack:N(A),reason:`${A.map(p=>`${p.permissionSet} (${p.why})`).join(", ")} could not be taken back: the lease ends at ${$.leaseEndsAt}, and the next run that mutes this org releases it`}:{}}}catch(A){D.delete(E);let p=l.done;if(ke(p?.removed??[],p?[...p.passed,...p.left]:[]),p!==void 0){let O=$.leaseEndsAt,P=O!==void 0&&Date.parse(O)>o()?{sets:W,until:O}:void 0;return{...$,released:!1,takenBack:N(p.removed),notTakenBack:N([...p.passed,...p.left]),reason:[R(A),...st({...p,removed:[]},!1),rt(r.pid,P)].join(" ")}}return{...$,released:!1,takenBack:[],reason:`the assignments could not be taken back (${R(A)}): this process tries again while it runs, and takes them back once it can use the journal; past ${$.leaseEndsAt}, or once process ${r.pid} has ended, the next run that mutes this org releases the lease`}}})(),Te)}}var mn=2,wn=3;function yn(e){return!e||e.assign.length===0?0:mn+wn+2*e.assign.length+(wt.get(e)??0)}function cs(e){let t=yn(e);return t>0?{mute:t}:{}}function En(e){return{state:"nothing",assigned:[],held:[],permissions:[],silenced:[],stillRan:[],reason:`nothing can be muted: ${e}; the run goes on as without the option`}}function us(e){return e?{mutedAutomation:e.muted,...e.plan?{mutePlan:e.plan}:{}}:{}}async function ds(e,t,n={}){if(typeof t.unread=="string")return{automation:void 0,muted:En(`the target's automation could not be read (${t.unread})`)};let s=await ln(await e(),t,n);if("refused"in s)throw new j(s.refused);return{automation:s.automation,...s.plan.assign.length>0?{prepared:s}:{},muted:s.planned,plan:s.plan}}function ls(e){let t=e?.mutedAutomation;return t!==null&&typeof t=="object"?t:void 0}function fs(e,t){let n=[];e.state==="nothing"?n.push(`mute: ${e.reason??mt}`):e.state==="planned"?n.push(`mute: planned, ${e.permissions.length>0?`the permission set(s) holding ${e.permissions.join(", ")}`:"nothing"} for the user it writes as in ${t}, for the run alone; nothing is assigned yet`):n.push(`mute: ${e.assigned.length>0?`assigned ${e.assigned.join(", ")}`:"assigned nothing"}${e.held.length>0?`; ${e.held.join(", ")} held already`:""} to the user the run writes as in ${t}, for the run alone`),e.tookBackOfEnded&&e.tookBackOfEnded.length>0&&n.push(` taken back before the run: ${e.tookBackOfEnded.join(", ")}, `+pt(e.tookBackOfEnded));for(let r of e.silenced)n.push(` silenced: ${ue(r)} (bypass ${r.permission})`);for(let r of e.stillRan)n.push(` still runs: ${ue(r)} (${Me(r.why)})`);for(let r of e.alsoLifted??[])n.push(` also lifts: ${_e(r)}`);for(let r of e.liftsUnread??[])n.push(` ${xe(r)}`);let s=e.takenBack??(e.released===!0?e.assigned:[]);if(s.length>0&&n.push(` taken back: ${s.join(", ")}, as the run ended`),e.passed&&e.passed.length>0&&n.push(` stays assigned: ${e.passed.join(", ")}, for another run that mutes ${t} as the same user, which takes ${e.passed.length===1?"it":"them"} back as it ends`),e.released===!1){let r=e.notTakenBack!==void 0&&e.notTakenBack.length===0;n.push(` ${r?"lease not released":"not taken back"}: ${e.reason??"the assignments stay until the lease ends"}`)}return n}export{An as a,le as b,L as c,fe as d,vn as e,Je as f,Cn as g,In as h,Ve as i,F as j,te as k,Jn as l,Wn as m,et as n,$t as o,Vn as p,Gn as q,Xn as r,as as s,Ht as t,ln as u,hn as v,yn as w,cs as x,us as y,ds as z,ls as A,fs as B};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{S as N}from"./chunk-
|
|
7
|
+
import{S as N}from"./chunk-JPUR2CFX.mjs";import{a as j,h as D}from"./chunk-TZE3Y7IQ.mjs";import{b as J}from"./chunk-CA5NAXSU.mjs";function se(e){return`sync-before-${e.replace(/[^A-Za-z0-9-]+/g,"-")}`.slice(0,200)}var oe=1e3;function he(e){let o=se(e.runId),d=new Map,a=e.everyMs??oe,g=()=>(e.now?.()??new Date).getTime(),S,I=Number.NEGATIVE_INFINITY,k,E=!1,R=h=>{if(S===void 0)return;let t=[...d].map(([l,c])=>({objectApiName:l,recordCount:c,truncated:!1}));e.meta.set(`backup:${o}`,{operationId:o,orgId:e.orgId,...e.organizationId!==void 0?{organizationId:e.organizationId}:{},objects:t,partial:h,timestamp:S,totalRecords:t.reduce((l,c)=>l+c.recordCount,0),origin:"sync",runId:e.runId},"backups")},z=()=>{if(E)return;let h=I+a-g();if(h<=0){k!==void 0&&clearTimeout(k),k=void 0,I=g(),R(!0);return}k??=setTimeout(()=>{if(k=void 0,!E){I=g();try{R(!0)}catch{}}},h),k.unref?.()};return{id:o,keep:async(h,t)=>{t.length!==0&&(d.has(h)||(S??=(e.now?.()??new Date).toISOString(),d.set(h,0),R(!0),await e.files.begin(o,h)),await e.files.append(o,h,t),d.set(h,(d.get(h)??0)+t.length),z())},close:()=>{E=!0,k!==void 0&&clearTimeout(k),k=void 0,R(!1)}}}var F=200,de=["LastModifiedDate","LastModifiedById"],ee=100,te=4e3,ae=20,ne=255;function ce(e=ne){return 2*Math.max(0,e)+2}function ke(e,o){let d=o===void 0||o.creatable.size+4>ee;if(e.toLowerCase()==="id")return{characters:ae,wide:d};let a=o?.fields?.find(g=>g.name.toLowerCase()===e.toLowerCase());return a&&["double","int","long","currency","percent"].includes(a.type??"")?{characters:(a.precision??a.digits??18)+2,wide:d}:{characters:ce(a?.length??ne),wide:d}}function fe(e){let o=e.wide?F/4:F,d=Math.floor((te+2)/(Math.max(1,e.characters)+2));return Math.max(1,Math.min(o,d))}function me(e,o){let d=fe(o),a=e.reduce((g,S)=>g+Math.ceil(Math.max(0,S)/d),0);return a>0?a+1:0}function u(e){return e.slice(0,15)}function U(e,o){if(typeof e=="number"&&Number.isFinite(e))return`#${e}`;if(!(typeof e!="string"||e===""))return o?u(e):e.toLowerCase()}function ue(e){return typeof e=="number"?String(e):`'${j(String(e))}'`}function ge(e,o){let d=[],a=[],g=0;for(let S of e){let I=ue(S);a.length>0&&(a.length>=o||g+I.length>te)&&(d.push(a),a=[],g=0),a.push(I),g+=I.length+2}return a.length>0&&d.push(a),d}function le(e,o,d){return`What these ${o} ${e} record(s) would write over in the target could not be read and kept first (${J(d)}), so none of them was written: a run writes over nothing it cannot put back.`}function Se(e){let o=new Map,d=new Map,a=new Set,g=new Map,S=new Map,I=new Map,k=new Map,E=new Map,R=new Map,z=t=>{let l=e.describe,c=e.viewsEncrypted;if(!l||!c)return Promise.resolve(new Set);let y=I.get(t);return y||(y=l(t).then(async f=>{let m=(f.fields??[]).filter(M=>M.type===N).map(M=>M.name);return m.length>0&&!await c()?new Set(m):new Set},()=>new Set),I.set(t,y)),y},h=t=>{let l=e.describe;if(!l)return Promise.resolve(new Set);let c=S.get(t);return c||(c=l(t).then(y=>new Set((y.fields??[]).filter(f=>f.type==="base64"||f.queryable===!1).map(f=>f.name)),()=>new Set),S.set(t,c)),c};return{before:async(t,l,c,y)=>{if(g.delete(t),l!=="update"&&l!=="upsert"||c.length===0)return;let f=l==="update"?"Id":y??"Id",m=f==="Id";try{D(t),D(f);let M=await h(t),p=await z(t),v=new Set,O=new Set,T=new Map;for(let n of c){let i=U(n[f],m);i!==void 0&&!T.has(i)&&T.set(i,n[f]);for(let[r,s]of Object.entries(n))if(!(r==="Id"||r===f||r==="attributes")&&!M.has(r)&&!(typeof s=="object"&&s!==null)){if(p.has(r)){O.add(r);continue}v.add(D(r))}}if(T.size===0||v.size===0&&O.size===0)return;let x=["Id",...m?[]:[f],...v],V=[...x,...de.filter(n=>!x.includes(n))],re=V.length>ee?F/4:F,$=new Map,P=R.get(t)===!1?x:V;for(let n of ge([...T.values()],re)){let i=s=>`SELECT ${s.join(", ")} FROM ${t} WHERE ${f} IN (${n.join(", ")})`,r;try{r=await e.query(i(P))}catch(s){if(P===x)throw s;P=x,R.set(t,!1),r=await e.query(i(P))}for(let s of r){let w=U(m?s.Id:s[f],m);w===void 0||typeof s.Id!="string"||$.set(w,[...$.get(w)??[],s])}}let K=o.get(t)??new Map,_=[],B=new Map,C=new Map,G=new Map;for(let n of c){let i=U(n[f],m),r=i===void 0?void 0:$.get(i),s=r?.length===1?r[0]:void 0,w=s?.Id;if(_.push(w),!s||w===void 0||a.has(u(w)))continue;typeof s.LastModifiedDate=="string"&&G.set(u(w),{id:w,at:s.LastModifiedDate,...typeof s.LastModifiedById=="string"?{by:s.LastModifiedById}:{}});let ie=K.get(u(w)),q=B.get(u(w))??{Id:w},Q=C.get(u(w))??new Set;for(let b of Object.keys(n))!v.has(b)||ie?.has(b)||b in q||(q[b]=s[b]??null,Q.add(b));Q.size!==0&&(B.set(u(w),q),C.set(u(w),Q))}if(O.size>0&&_.some(n=>n!==void 0&&!a.has(u(n)))){let n=k.get(t)??new Set,i=[...O].filter(r=>!n.has(r));if(i.length>0){for(let r of i)n.add(r);k.set(t,n),e.recorder.unkept?.(t,i)}}if(B.size===0){g.set(t,{reaches:_,named:[],added:new Map});return}let X=[...B.values()],L=d.get(t)??new Map,Y=X.flatMap(n=>{let i=L.get(u(n.Id)),r=Object.entries(n).filter(([s])=>s==="Id"||!i?.has(s));return r.length>1?[Object.fromEntries(r)]:[]});Y.length>0&&await e.backup.keep(t,Y);for(let n of Y){let i=L.get(u(n.Id))??new Set;for(let r of Object.keys(n))r!=="Id"&&i.add(r);L.set(u(n.Id),i)}d.set(t,L);let A=X.map(n=>n.Id),W=E.get(t)??new Set,H=[];for(let n of A){let i=u(n);if(W.has(i))continue;W.add(i);let r=G.get(i);r&&H.push(r)}E.set(t,W),H.length>0?e.recorder.overwriting?.(t,e.backup.id,A,H):e.recorder.overwriting?.(t,e.backup.id,A);let Z=await e.recorder.flush();if(Z!==void 0)throw new Error(`the run's file could not be written: ${Z}`);for(let[n,i]of C){let r=K.get(n)??new Set;for(let s of i)r.add(s);K.set(n,r)}o.set(t,K),g.set(t,{reaches:_,named:A,added:C});return}catch(M){return le(t,c.length,M)}},answered:(t,l,c)=>{if(l==="insert"||l==="upsert")for(let p of c)p.success&&typeof p.id=="string"&&p.id!==""&&(l==="insert"||p.created===!0)&&a.add(u(p.id));let y=g.get(t);if(g.delete(t),!y||y.named.length===0)return;let f=new Set;c.forEach((p,v)=>{let O=y.reaches[v];O!==void 0&&p.success&&p.created!==!0&&f.add(u(O))});let m=y.named.filter(p=>!f.has(u(p))),M=o.get(t);for(let p of m){let v=M?.get(u(p));for(let O of y.added.get(u(p))??[])v?.delete(O)}e.recorder.overwrote?.(t,m)}}}export{se as a,he as b,ae as c,ce as d,ke as e,me as f,Se as g};
|
|
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a,b,c,d,e}from"./chunk-
|
|
7
|
+
import{a,b,c,d,e}from"./chunk-O2HDYYUV.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as AIDataGenerator,c as buildPrompt,d as parseAIResponse,b as phoneReplacement,e as reachNobody};
|