sandforge 1.83.0 → 1.84.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/README.md +1 -1
- package/lib/chunk-23SEDORH.mjs +11 -0
- package/lib/{chunk-I5C4O3VA.mjs → chunk-24RFOFYT.mjs} +1 -1
- package/lib/chunk-26POJDIT.mjs +7 -0
- package/lib/{chunk-WJAZ5LHL.mjs → chunk-2AZQHBEF.mjs} +1 -1
- package/lib/{chunk-IHGYJZZ2.mjs → chunk-2HVOZUM4.mjs} +1 -1
- package/lib/{chunk-3V4YH5KO.mjs → chunk-2JDAOWUW.mjs} +1 -1
- package/lib/{chunk-BNKT3R3F.mjs → chunk-2METQHGG.mjs} +1 -1
- package/lib/chunk-2WFIVO4F.mjs +13 -0
- package/lib/chunk-2YHZBUZE.mjs +7 -0
- package/lib/{chunk-7DPHZWA4.mjs → chunk-326AJTIU.mjs} +14 -14
- package/lib/{chunk-UIR77ZJD.mjs → chunk-36JOHEJL.mjs} +1 -1
- package/lib/chunk-3PVRGTVK.mjs +7 -0
- package/lib/{chunk-2WMKJVD2.mjs → chunk-3Q353S2R.mjs} +1 -1
- package/lib/chunk-3TZSBHEY.mjs +7 -0
- package/lib/{chunk-T36DZJPH.mjs → chunk-43TOMFV4.mjs} +1 -1
- package/lib/{chunk-XAMMIPZ4.mjs → chunk-4CVUUVGJ.mjs} +1 -1
- package/lib/{chunk-6YC2ELCU.mjs → chunk-4EOHEDFP.mjs} +1 -1
- package/lib/{chunk-ZB5E7NHU.mjs → chunk-4JE4BYXK.mjs} +1 -1
- package/lib/{chunk-JREKJO3D.mjs → chunk-54WZUS7J.mjs} +1 -1
- package/lib/{chunk-CGZGL6VT.mjs → chunk-5CRLRHOJ.mjs} +1 -1
- package/lib/{chunk-UOHZW2L4.mjs → chunk-5IZTFMJM.mjs} +1 -1
- package/lib/{chunk-6VOQFISN.mjs → chunk-5M5FQ7RP.mjs} +1 -1
- package/lib/{chunk-U4YFYSF3.mjs → chunk-5SMWFNE7.mjs} +1 -1
- package/lib/{chunk-HQZUQXDC.mjs → chunk-5XTUSN72.mjs} +1 -1
- package/lib/chunk-6I6TWNV5.mjs +7 -0
- package/lib/{chunk-QLRWU3MB.mjs → chunk-6JWWSDM6.mjs} +1 -1
- package/lib/chunk-6O222PW6.mjs +7 -0
- package/lib/{chunk-J3TIHLWG.mjs → chunk-6PD6K7LP.mjs} +1 -1
- package/lib/{chunk-ISAUCWYK.mjs → chunk-6QE6R6RL.mjs} +1 -1
- package/lib/{chunk-2KTGDYUH.mjs → chunk-6WX5ZU7Q.mjs} +1 -1
- package/lib/{chunk-XAUQXYPW.mjs → chunk-6YL7BNYD.mjs} +1 -1
- package/lib/chunk-6ZLKIT3H.mjs +7 -0
- package/lib/{chunk-XKFHTBAB.mjs → chunk-7QYHEHMA.mjs} +1 -1
- package/lib/chunk-7SQSWVAU.mjs +9 -0
- package/lib/{chunk-NNV7IGM7.mjs → chunk-7UVKIWKV.mjs} +1 -1
- package/lib/{chunk-RZKJQOOC.mjs → chunk-7WATA4SB.mjs} +1 -1
- package/lib/{chunk-DMT5SCO3.mjs → chunk-7YNM6KFZ.mjs} +1 -1
- package/lib/{chunk-TMIESDE5.mjs → chunk-A3MYSOOC.mjs} +1 -1
- package/lib/chunk-AL4C3GFT.mjs +7 -0
- package/lib/chunk-B3FBHVNN.mjs +21 -0
- package/lib/{chunk-CDWZGQAJ.mjs → chunk-B63POIPQ.mjs} +1 -1
- package/lib/{chunk-YEVB7LVK.mjs → chunk-BAWCOKRW.mjs} +1 -1
- package/lib/{chunk-FVLFO2S6.mjs → chunk-BBRWFKS5.mjs} +1 -1
- package/lib/chunk-BEA27DLS.mjs +7 -0
- package/lib/chunk-BRY3PLIZ.mjs +7 -0
- package/lib/chunk-CBH3TOWK.mjs +341 -0
- package/lib/{chunk-7V2UYZ6S.mjs → chunk-CPQIZGG5.mjs} +1 -1
- package/lib/chunk-CVHNXJH3.mjs +7 -0
- package/lib/{chunk-ZOSESZ22.mjs → chunk-D4GF4FAB.mjs} +1 -1
- package/lib/chunk-DGDRQRCW.mjs +7 -0
- package/lib/{chunk-2N73W63D.mjs → chunk-DPMRIMUC.mjs} +1 -1
- package/lib/chunk-DUN2EPRC.mjs +7 -0
- package/lib/chunk-E3A3LOCY.mjs +7 -0
- package/lib/{chunk-KWAVSZ2B.mjs → chunk-EAC5QCE3.mjs} +1 -1
- package/lib/{chunk-JUOQUG7U.mjs → chunk-EC72TIEG.mjs} +1 -1
- package/lib/chunk-EPFCERGL.mjs +7 -0
- package/lib/{chunk-6KOUYHEY.mjs → chunk-ETDCBLGU.mjs} +1 -1
- package/lib/{chunk-2R6GFNKF.mjs → chunk-F3AQW6IU.mjs} +1 -1
- package/lib/{chunk-AHUGG3WU.mjs → chunk-FITPY3L4.mjs} +1 -1
- package/lib/chunk-FNJ4SGWO.mjs +7 -0
- package/lib/{chunk-EOQON3E5.mjs → chunk-FP7CYB2F.mjs} +1 -1
- package/lib/{chunk-262TP6UU.mjs → chunk-GKY2JMHY.mjs} +1 -1
- package/lib/{chunk-JBWJ6UEZ.mjs → chunk-GMIGWR6U.mjs} +1 -1
- package/lib/{chunk-OS5GE52G.mjs → chunk-GNRSF65U.mjs} +1 -1
- package/lib/chunk-GOOVPVWX.mjs +7 -0
- package/lib/{chunk-DB5RVDC5.mjs → chunk-GWZRR3MM.mjs} +1 -1
- package/lib/{chunk-SX6QWYCQ.mjs → chunk-H2BHESDA.mjs} +2 -2
- package/lib/chunk-H4CGM6YO.mjs +7 -0
- package/lib/{chunk-NFEBX75O.mjs → chunk-HCGXK7G7.mjs} +1 -1
- package/lib/{chunk-4X5D3MSV.mjs → chunk-HIDW7FNV.mjs} +1 -1
- package/lib/chunk-HSBXRQTI.mjs +7 -0
- package/lib/chunk-HUZPBE47.mjs +7 -0
- package/lib/{chunk-F5SBGJWW.mjs → chunk-HV7VPEXP.mjs} +1 -1
- package/lib/chunk-I6E6T6YY.mjs +7 -0
- package/lib/chunk-IUM4NFKI.mjs +10 -0
- package/lib/chunk-IVFVNNGB.mjs +37 -0
- package/lib/{chunk-L4MSL4U7.mjs → chunk-IZGCEOYO.mjs} +1 -1
- package/lib/{chunk-E3RQ575Y.mjs → chunk-J3DND3BC.mjs} +1 -1
- package/lib/{chunk-MJD6CPZZ.mjs → chunk-JAEDM4SI.mjs} +1 -1
- package/lib/chunk-JCFBFF4Y.mjs +7 -0
- package/lib/{chunk-U2CTKIPE.mjs → chunk-JE6SCT6R.mjs} +1 -1
- package/lib/{chunk-XJICAOAQ.mjs → chunk-JGZPD4IM.mjs} +1 -1
- package/lib/{chunk-XCJUNX63.mjs → chunk-JKJ74BX5.mjs} +1 -1
- package/lib/{chunk-WAYQLQAD.mjs → chunk-JLSIWO4Z.mjs} +1 -1
- package/lib/{chunk-D7XUNWWU.mjs → chunk-JSAJS3MY.mjs} +1 -1
- package/lib/chunk-JTJK2D36.mjs +7 -0
- package/lib/{chunk-OTJH6AEA.mjs → chunk-KAZS5Z6W.mjs} +1 -1
- package/lib/chunk-KB4ZHM4Q.mjs +10 -0
- package/lib/{chunk-N2HYG3BL.mjs → chunk-KGU4SVIT.mjs} +1 -1
- package/lib/{chunk-FKCIGJOI.mjs → chunk-KJWFYBMU.mjs} +2 -2
- package/lib/{chunk-KXUOHACP.mjs → chunk-KZTZDC7H.mjs} +1 -1
- package/lib/{chunk-S4PRKKGC.mjs → chunk-L2E5WBGD.mjs} +1 -1
- package/lib/{chunk-X2XZQ434.mjs → chunk-L53JWJ3S.mjs} +1 -1
- package/lib/{chunk-CQAFVEKP.mjs → chunk-LA4KIATH.mjs} +6 -6
- package/lib/chunk-LC3NDW4N.mjs +7 -0
- package/lib/{chunk-4V3QO7HF.mjs → chunk-LKTNQEBS.mjs} +1 -1
- package/lib/chunk-M2ABR4JM.mjs +7 -0
- package/lib/{chunk-3CM7LAPE.mjs → chunk-M4BLK6HJ.mjs} +1 -1
- package/lib/{chunk-Z3MGN42K.mjs → chunk-M6K34KGF.mjs} +1 -1
- package/lib/{chunk-TUPZY2QJ.mjs → chunk-MDMPJEV3.mjs} +1 -1
- package/lib/{chunk-BVZ5H3N4.mjs → chunk-MJZU3U5O.mjs} +68 -63
- package/lib/{chunk-OUU47Y7A.mjs → chunk-MSIEU5MR.mjs} +1 -1
- package/lib/{chunk-QQDZQCO2.mjs → chunk-N4WPCWJO.mjs} +1 -1
- package/lib/{chunk-MTM4KG3T.mjs → chunk-NCZKWSC7.mjs} +1 -1
- package/lib/{chunk-Y7YUNRKK.mjs → chunk-NED4MBIM.mjs} +1 -1
- package/lib/{chunk-QKJXIY6L.mjs → chunk-NOBQTEQD.mjs} +1 -1
- package/lib/{chunk-WBELLGNE.mjs → chunk-NSQWI7ZY.mjs} +1 -1
- package/lib/{chunk-BPHTA6KP.mjs → chunk-O677VOGO.mjs} +1 -1
- package/lib/chunk-OFTT7J2M.mjs +7 -0
- package/lib/{chunk-JH4ZTVQN.mjs → chunk-OLCVHL7I.mjs} +1 -1
- package/lib/chunk-OM5NORJG.mjs +7 -0
- package/lib/{chunk-QP3JLFIO.mjs → chunk-OMNMLKDT.mjs} +1 -1
- package/lib/{chunk-WABXKL4N.mjs → chunk-OPMO6I45.mjs} +1 -1
- package/lib/{chunk-7ZBDACVG.mjs → chunk-OUZQPYT3.mjs} +1 -1
- package/lib/chunk-OVNMB6Q2.mjs +7 -0
- package/lib/{chunk-DKDKCGXV.mjs → chunk-PAXNWTYK.mjs} +1 -1
- package/lib/{chunk-GLN4PI5P.mjs → chunk-PBY2O6OF.mjs} +1 -1
- package/lib/chunk-PEDQPM2P.mjs +926 -0
- package/lib/chunk-PH7SP4YK.mjs +21 -0
- package/lib/{chunk-BT43WSOS.mjs → chunk-PMN4PAC3.mjs} +1 -1
- package/lib/chunk-PMWAFDUB.mjs +48 -0
- package/lib/chunk-PPLVFX6N.mjs +7 -0
- package/lib/{chunk-L3I6DAHX.mjs → chunk-PR3XCSPO.mjs} +1 -1
- package/lib/{chunk-WZN36ACK.mjs → chunk-PR42EZSR.mjs} +1 -1
- package/lib/{chunk-NDFFIJL5.mjs → chunk-PWRJRL5U.mjs} +1 -1
- package/lib/{chunk-NS6ONPWL.mjs → chunk-Q7GIJBCD.mjs} +1 -1
- package/lib/chunk-Q7TLC3I2.mjs +7 -0
- package/lib/{chunk-ALBY5SOH.mjs → chunk-QAFPQ3YB.mjs} +1 -1
- package/lib/{chunk-KKS2KFBT.mjs → chunk-QKEKG2LD.mjs} +1 -1
- package/lib/{chunk-OOIDCHBQ.mjs → chunk-QO53K5W2.mjs} +2 -2
- package/lib/{chunk-HVX2AFYW.mjs → chunk-QTG6LUZT.mjs} +1 -1
- package/lib/{chunk-K7G3W7XH.mjs → chunk-RE7RYF3B.mjs} +1 -1
- package/lib/{chunk-JIPT5FUD.mjs → chunk-RGBGUCJA.mjs} +1 -1
- package/lib/{chunk-GT5ZKU6V.mjs → chunk-RGUQOSBU.mjs} +1 -1
- package/lib/{chunk-VXZ5PTOM.mjs → chunk-RHNTHGNU.mjs} +1 -1
- package/lib/chunk-RKTFFCNS.mjs +7 -0
- package/lib/chunk-RMFU4BAL.mjs +28 -0
- package/lib/{chunk-DNQKVCUV.mjs → chunk-ROV3QXEF.mjs} +11 -11
- package/lib/chunk-RT47RKLY.mjs +7 -0
- package/lib/{chunk-ISOSTAJR.mjs → chunk-S42RBRH2.mjs} +1 -1
- package/lib/{chunk-27BBEGUD.mjs → chunk-SI267LYR.mjs} +1 -1
- package/lib/chunk-T3G6VZNS.mjs +7 -0
- package/lib/chunk-TNT27RBG.mjs +7 -0
- package/lib/chunk-UBIKR5VO.mjs +7 -0
- package/lib/chunk-UI3JQVRU.mjs +8 -0
- package/lib/{chunk-RVCPQVKM.mjs → chunk-UIOMAX56.mjs} +1 -1
- package/lib/chunk-UX3BVH2Y.mjs +7 -0
- package/lib/{chunk-L4RJX7DG.mjs → chunk-VCUXCK36.mjs} +1 -1
- package/lib/chunk-VINGECAJ.mjs +10 -0
- package/lib/chunk-VOXJHJIE.mjs +7 -0
- package/lib/chunk-W6PN6TJG.mjs +7 -0
- package/lib/{chunk-D6JT4PAB.mjs → chunk-WAPSSYMT.mjs} +1 -1
- package/lib/{chunk-7BQMBXKX.mjs → chunk-WUUKFE2U.mjs} +1 -1
- package/lib/chunk-WWTCWWZI.mjs +7 -0
- package/lib/chunk-WXDLQT2O.mjs +10 -0
- package/lib/{chunk-TCEXCHXR.mjs → chunk-WY5V5PR3.mjs} +1 -1
- package/lib/chunk-X4BXESMQ.mjs +7 -0
- package/lib/chunk-XBQGZGWR.mjs +7 -0
- package/lib/{chunk-AXFD2OH6.mjs → chunk-XGGOUNPP.mjs} +1 -1
- package/lib/chunk-XKWW3GKF.mjs +7 -0
- package/lib/{chunk-PDRXM5WN.mjs → chunk-Y2DRK37K.mjs} +1 -1
- package/lib/{chunk-ZXOUWHYE.mjs → chunk-YA6ATMTB.mjs} +1 -1
- package/lib/{chunk-54HYHHVL.mjs → chunk-YDXMTWAT.mjs} +1 -1
- package/lib/chunk-YHR4WQPR.mjs +7 -0
- package/lib/{chunk-LWES2KZE.mjs → chunk-YTLUYSMF.mjs} +1 -1
- package/lib/{chunk-2K5BYZQM.mjs → chunk-YWEQQL3C.mjs} +1 -1
- package/lib/{chunk-C6RKM4BB.mjs → chunk-Z4LKKOFY.mjs} +1 -1
- package/lib/chunk-ZBAWJUG2.mjs +7 -0
- package/lib/{chunk-446GBKAC.mjs → chunk-ZJW6YOMV.mjs} +1 -1
- package/lib/chunk-ZQQXSCVI.mjs +7 -0
- package/lib/{chunk-L6CLN664.mjs → chunk-ZQWIVYVM.mjs} +1 -1
- package/lib/{chunk-CXKZ6TYV.mjs → chunk-ZV7ZFQQC.mjs} +1 -1
- package/lib/sandforge-autopilot.mjs +25 -25
- package/lib/sandforge-backup.mjs +1 -1
- package/lib/sandforge-checkpoint.mjs +1 -1
- package/lib/sandforge-cleanup.mjs +1 -1
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +52 -21
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +1 -1
- package/lib/sandforge-env.mjs +95 -95
- package/lib/sandforge-frozen.mjs +1 -1
- package/lib/sandforge-mcp.mjs +12 -12
- package/lib/sandforge-monitor.mjs +1 -1
- package/lib/sandforge-pipeline.mjs +1 -1
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge-users.mjs +1 -1
- package/lib/sandforge.mjs +1 -1
- package/lib/sf/sandforge/compare.mjs +2 -2
- package/lib/sfPlugin.mjs +1 -1
- package/oclif.manifest.json +1 -1
- package/package.json +1 -1
- package/lib/chunk-2ADSD5WK.mjs +0 -7
- package/lib/chunk-2GSMHGIV.mjs +0 -7
- package/lib/chunk-36Y225OM.mjs +0 -7
- package/lib/chunk-3OVTKRS4.mjs +0 -7
- package/lib/chunk-4GCYGQXD.mjs +0 -7
- package/lib/chunk-4JKR4PTZ.mjs +0 -8
- package/lib/chunk-5OGNK3JP.mjs +0 -37
- package/lib/chunk-6QSHWIZI.mjs +0 -48
- package/lib/chunk-77IVKH7R.mjs +0 -7
- package/lib/chunk-77MZRBWX.mjs +0 -7
- package/lib/chunk-7WSQ65WG.mjs +0 -9
- package/lib/chunk-A32ISQ6M.mjs +0 -28
- package/lib/chunk-AG24QMSY.mjs +0 -7
- package/lib/chunk-BH76USTQ.mjs +0 -11
- package/lib/chunk-BZ24IAP5.mjs +0 -7
- package/lib/chunk-CN5HGFG4.mjs +0 -7
- package/lib/chunk-CTPLYUXA.mjs +0 -7
- package/lib/chunk-DIGUC7S4.mjs +0 -341
- package/lib/chunk-DSR2MSBH.mjs +0 -7
- package/lib/chunk-ETNQHIDI.mjs +0 -9
- package/lib/chunk-FBXH4VRQ.mjs +0 -7
- package/lib/chunk-FYWNSMOZ.mjs +0 -10
- package/lib/chunk-GEEWPTV5.mjs +0 -7
- package/lib/chunk-GTRU5AV5.mjs +0 -7
- package/lib/chunk-I3ZO76LL.mjs +0 -21
- package/lib/chunk-ISA2NYJV.mjs +0 -7
- package/lib/chunk-IXIY6Q4M.mjs +0 -7
- package/lib/chunk-JAV6F6OA.mjs +0 -7
- package/lib/chunk-JYUMD357.mjs +0 -7
- package/lib/chunk-L47JCNP3.mjs +0 -7
- package/lib/chunk-LI2XNV7F.mjs +0 -7
- package/lib/chunk-LP2D3JJP.mjs +0 -7
- package/lib/chunk-LYOGCIYD.mjs +0 -925
- package/lib/chunk-N5UIE4IR.mjs +0 -7
- package/lib/chunk-O7GCCRPW.mjs +0 -7
- package/lib/chunk-OO24ZYYJ.mjs +0 -7
- package/lib/chunk-OS6HFJ7L.mjs +0 -7
- package/lib/chunk-P6WRYJN3.mjs +0 -7
- package/lib/chunk-PGRY365W.mjs +0 -7
- package/lib/chunk-PPGDAUEQ.mjs +0 -7
- package/lib/chunk-Q4PPI3KG.mjs +0 -7
- package/lib/chunk-QFTF2PGS.mjs +0 -21
- package/lib/chunk-QO4MPHZD.mjs +0 -7
- package/lib/chunk-QXB6U3ZP.mjs +0 -7
- package/lib/chunk-R3OM3X4L.mjs +0 -8
- package/lib/chunk-R7GKMAT4.mjs +0 -7
- package/lib/chunk-SCKUIE3R.mjs +0 -7
- package/lib/chunk-SU65Z2BA.mjs +0 -7
- package/lib/chunk-T7DDS4UQ.mjs +0 -7
- package/lib/chunk-TQJ5NPRC.mjs +0 -7
- package/lib/chunk-VZLJZEV2.mjs +0 -7
- package/lib/chunk-W3BQGMTR.mjs +0 -7
- package/lib/chunk-WXU6ZJIV.mjs +0 -7
- package/lib/chunk-X4HZD5U2.mjs +0 -7
- package/lib/chunk-X6XNTOGO.mjs +0 -7
- package/lib/chunk-XMQ5R6TC.mjs +0 -10
- package/lib/chunk-XPXEQKLR.mjs +0 -7
- package/lib/chunk-YBZIDW6W.mjs +0 -7
- package/lib/chunk-ZCOSME6P.mjs +0 -7
- package/lib/chunk-ZTHC42X6.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{a as T,b as F,d as B,k as R}from"./chunk-YHR4WQPR.mjs";import{a as L,f as C,i as $,j as _}from"./chunk-YDXMTWAT.mjs";import{b as N}from"./chunk-26POJDIT.mjs";import{a as I}from"./chunk-4TLYUZD5.mjs";import{a as j,d as x}from"./chunk-CVHNXJH3.mjs";import{b as P}from"./chunk-CA5NAXSU.mjs";import{qd as A}from"./chunk-PMWAFDUB.mjs";var w=class{byObject=new Map;add(e){let t=this.byObject.get(e.objectApiName);t||(t=new Map,this.byObject.set(e.objectApiName,t));let s=t.get(e.recordId),r=s?.[e.fieldName];if(r!==void 0&&r!==e.value)return{taken:!1,kept:r};let n=s??{Id:e.recordId};return n[e.fieldName]=e.value,t.set(e.recordId,n),{taken:!0}}updates(){return[...this.byObject].map(([e,t])=>[e,[...t.values()]])}};var J="DUPLICATES_DETECTED",X=3,Y=2e3;function Z(i){return new Promise(e=>setTimeout(e,i))}function z(i){let e=i.errorDetails??[];return x(i.errors,e.length===i.errors.length?e:void 0)}function q(i){let e=i.errorDetails;return e?.length!==1||e[0].statusCode===J||z(i)}function Q(i){let e=Object.keys(i).find(s=>s!=="Id"),t=e===void 0?void 0:i[e];return typeof t=="string"?t:""}function U(i){return{objectApiName:i,op:"update"}}function V(i){let e=i.automation??"the target's automation";I.warn(`[forge] ${i.objectApiName}: ${e} hit ${i.limit??"a Salesforce limit"} on an update of ${i.from} records \u2014 sending a record on its own, then smaller calls.`)}function y(i){return Object.keys(i).filter(e=>e!=="Id").length}async function fe(i){if(!i.enabled||!i.updateRecords||i.pendingFkUpdates.length===0)return null;let e=new E(i);return await e.patch(i.pendingFkUpdates),e.finish()}var ee=1024,te=.6;function K(i){let e=2166136261;for(let t=0;t<i.length;t++)e^=i.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function M(i){let e=2538058380;for(let t=0;t<i.length;t++)e=Math.imul(e^i.charCodeAt(t),1540483477),e^=e>>>15;return e>>>0}var H=class{capacity=ee;used=0;h1=new Uint32Array(this.capacity);h2=new Uint32Array(this.capacity);firstPart=new Float64Array(this.capacity);several=new Uint8Array(this.capacity);note(e,t){let s=K(t),r=M(t),n=this.find(s,r);if(n>=0){this.firstPart[n]!==e+1&&(this.several[n]=1);return}this.used+1>this.capacity*te&&this.grow();let o=this.freeSlotFor(r);this.h1[o]=s,this.h2[o]=r,this.firstPart[o]=e+1,this.used++}spans(e){let t=this.find(K(e),M(e));return t>=0&&this.several[t]===1}find(e,t){let s=this.capacity-1;for(let r=t&s;;r=r+1&s){if(this.firstPart[r]===0)return-1;if(this.h1[r]===e&&this.h2[r]===t)return r}}freeSlotFor(e){let t=this.capacity-1,s=e&t;for(;this.firstPart[s]!==0;)s=s+1&t;return s}grow(){let{h1:e,h2:t,firstPart:s,several:r}=this;this.capacity*=2,this.h1=new Uint32Array(this.capacity),this.h2=new Uint32Array(this.capacity),this.firstPart=new Float64Array(this.capacity),this.several=new Uint8Array(this.capacity);for(let n=0;n<s.length;n++){if(s[n]===0)continue;let o=this.freeSlotFor(t[n]);this.h1[o]=e[n],this.h2[o]=t[n],this.firstPart[o]=s[n],this.several[o]=r[n]}}},E=class{constructor(e){this.input=e;this.splits=e.splitting!==void 0,this.splitting=e.splitting??L(0),this.bulkUnsupported=e.bulkUnsupported??new Set}input;resolvedCount=0;unresolvedCount=0;insertOnlyLost=0;unresolved=[];pass2Failed=0;pass2Samples=[];notSent=0;notSentObjects=new Set;cancelled=!1;handed=0;held=new w;splitting;splits;bulkUnsupported;backoff=new j({initialDelay:Y});limitOf(e){return this.splits&&e&&!e.success?A(e.errors):void 0}async patch(e,t){let{input:s}=this;if(!s.enabled||!s.updateRecords||e.length===0)return;this.handed+=e.length;let r=new w;for(let n of e)this.take(n,t?.(n)===!0?this.held:r);await this.send(r)}async sendHeld(){await this.send(this.held)}take(e,t){let{input:s}=this,{remapper:r}=s,n=r.get(e.sourceRefId);if(!n){if(s.deferUnresolved){s.stillPending?.push(e);return}if(s.outsideTheSample?.(e)){s.onLeftOutsideTheSample?.(e.objectApiName,e.fieldName);return}this.unresolvedCount++,this.unresolved.length<3&&this.unresolved.push({recordSummary:`${e.objectApiName} source=${e.sourceId??"?"} target=${e.newId} ${e.fieldName}=<source ${e.sourceRefId}>`,messages:[`Cycle FK '${e.fieldName}' could not be resolved \u2014 referenced parent (source ${e.sourceRefId}) was not cloned`]});return}if(e.insertOnly){this.insertOnlyLost++,this.unresolved.length<3&&this.unresolved.push({recordSummary:`${e.objectApiName} source=${e.sourceId??"?"} target=${e.newId} ${e.fieldName}`,messages:[`Lookup '${e.fieldName}' left empty: only an insert sets it, and the record it names (source ${e.sourceRefId}) was written after this one`]});return}let o=t.add({objectApiName:e.objectApiName,recordId:e.newId,fieldName:e.fieldName,value:n});if(!o.taken){this.unresolvedCount++,this.unresolved.length<3&&this.unresolved.push({recordSummary:`${e.objectApiName} source=${e.sourceId??"?"} target=${e.newId} ${e.fieldName}`,messages:[`Conflicting cycle FK update for ${e.fieldName}: ${String(o.kept)} vs ${n}`]});return}this.resolvedCount++}async send(e){for(let[t,s]of e.updates()){if(this.jobsFor(t,s.length)){await this.sendAsJobs(t,s);continue}await this.sendObject(t,s)}}jobsFor(e,t){let{input:s}=this;return s.bulkUpdate!==void 0&&t>=2e3&&s.restOnly?.has(e)!==!0&&!this.bulkUnsupported.has(e)}leaveNotSent(e,t){for(let s of t)this.notSent+=y(s);t.length>0&&this.notSentObjects.add(e)}async sendObject(e,t,s,r){let{input:n}=this,{targetOrgId:o}=n,d=n.updateRecords;if(!d||t.length===0)return;let c=()=>(this.cancelled||(this.cancelled=n.stopped?.()===!0),this.cancelled);if(c()){this.leaveNotSent(e,t);return}let l,a=await _(t,{key:U(e),sizes:this.splitting.sizes,allowance:this.splitting.allowance,maxSize:B.rest,...r,beforeEachSend:()=>c()?"stop":void 0,send:async p=>{try{return{answers:await d(o,e,[...p])}}catch(h){return l={error:h},{answers:[]}}},limited:p=>this.limitOf(p),settle:(p,h,k,S)=>{let v=l;l=void 0,v?this.callThrew(e,p,v.error):this.settleAnswers(e,p,h,k,S,s),n.onAnswered?.()},onFirstRefusal:V});a.stopped&&this.leaveNotSent(e,[...a.stopped.part,...a.stopped.rest])}settleAnswers(e,t,s,r,n,o){let{input:d}=this;for(let c=0;c<t.length;c++){if(r.has(c))continue;let l=s[c];l?l.success?d.onPatched?.(e,t[c]):o&&z(l)?o.push(t[c]):this.refused(e,t[c],l,n.get(c)):(this.pass2Failed+=y(t[c]),this.pass2Samples.length<3&&this.pass2Samples.push({recordSummary:R(t[c]),messages:[`No result returned for record (API truncated batch: ${s.length}/${t.length})`]}))}}refused(e,t,s,r){this.tellRefusedByFilter(e,t,s),this.pass2Failed+=y(t),this.pass2Samples.length<3&&this.pass2Samples.push({recordSummary:R(t),messages:r===void 0?s.errors:[...s.errors,C(r,$(this.splitting.allowance,U(e)),"run")]})}callThrew(e,t,s){for(let r of t)this.pass2Failed+=y(r);this.pass2Samples.length<3&&this.pass2Samples.push({recordSummary:`${e} batch failed`,messages:[P(s)]})}async sendAsJobs(e,t){let{input:s}=this,r=s.bulkUpdate;if(!r)return;let n=t.map((l,a)=>({record:l,at:a,value:Q(l)})).sort((l,a)=>l.value===a.value?l.at-a.at:l.value<a.value?-1:1).map(({record:l})=>l),o=U(e),{sizes:d,allowance:c}=this.splitting;for(let l=0;l<n.length;l+=F){let a=n.slice(l,l+F);if(this.cancelled||(this.cancelled=s.stopped?.()===!0),this.cancelled){this.leaveNotSent(e,a);continue}let p=d.of(o);if(p<200){let u=Math.ceil(a.length/p),f=c.take(o,u);d.countExtraCalls(o,f);let m=a.slice(0,f*p);try{await this.sendObject(e,m,void 0,{pricedAs:"job",paid:{calls:f}})}finally{f<u&&d.spend(o)}if(f===u)continue;if(a=a.slice(m.length),this.cancelled){this.leaveNotSent(e,a);continue}if(a.length<2e3){await this.sendObject(e,a);continue}}let h;try{h=await r(e,a)}catch(u){if(!(u instanceof T)){await this.sendObject(e,a);continue}for(let f of a)this.pass2Failed+=y(f);this.pass2Samples.length<3&&this.pass2Samples.push({recordSummary:`${e}: a Bulk API job of ${a.length} updates was lost`,messages:[P(u),"The target may hold any of these lookups: they are counted as left empty."]}),s.onAnswered?.();continue}if(h.aborted){this.cancelled=!0,this.leaveNotSent(e,a);continue}if(h.untouched){h.untouched.unsupported&&this.bulkUnsupported.add(e),await this.sendObject(e,a);continue}let k=[],S=[],v=[],b;a.forEach((u,f)=>{let m=h.rows[f]??"unprocessed",g=h.answers[f],O=m==="answered"?this.limitOf(g):void 0;O&&g?(b??=O,S.push(u),v.push(g)):m==="answered"&&g?.success?s.onPatched?.(e,u):m==="may-have-written"?(this.pass2Failed+=y(u),this.pass2Samples.length<3&&this.pass2Samples.push({recordSummary:R(u),messages:["The Bulk API job may have written this update without saying so."]})):m!=="answered"||!g||q(g)?k.push(u):this.refused(e,u,g)}),s.onAnswered?.(),await this.sendAgainByRest(e,k),await this.sendObject(e,S,void 0,{refusedIn:{from:200,answers:v,...b?{cause:b}:{}}})}}async sendAgainByRest(e,t){let s=t;for(let r=0;s.length>0;r++){r>0&&await(this.input.wait??Z)(this.backoff.calculateDelay(r-1));let n=[];await this.sendObject(e,s,r<X-1?n:void 0),s=n}}tellRefusedByFilter(e,t,s){let r=this.input.onRefusedByFilter,n=t.Id;if(!r||typeof n!="string")return;let o=new Set((s.errorDetails??[]).filter(d=>d.statusCode===N).flatMap(d=>d.fields));for(let d of Object.keys(t))d!=="Id"&&o.has(d)&&r(e,d,n)}finish(){let{resolvedCount:e,unresolvedCount:t,insertOnlyLost:s,pass2Failed:r,notSent:n}=this;if(this.handed===0)return null;let o=e+t+s;if(this.input.deferUnresolved&&e===0&&r===0&&s===0)return null;let d=r+t+s+n;if(this.input.onProgress({objectName:"__pass2__",status:d>0?"error":"done",progress:100,message:`Pass 2 (cycle FK update): ${e-r-n}/${o} resolved`+(n>0?`; cancelled with ${n} not sent`:"")}),d>0){let c=n>0?[{recordSummary:`${[...this.notSentObjects].join(", ")}: ${n} lookup${n===1?"":"s"} not sent`,messages:["The run was cancelled before they were filled in: they stay empty."]}]:[];return{objectApiName:"__pass2__",stage:"insert",failedCount:d,attemptedCount:o,samples:[...c,...this.pass2Samples,...this.unresolved].slice(0,3)}}return null}};export{w as a,fe as b,H as c,E as d};
|
|
@@ -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,c,d,e,f,g,h,i,j}from"./chunk-DPMRIMUC.mjs";import"./chunk-SI267LYR.mjs";import"./chunk-H4OBZIX3.mjs";import"./chunk-KAZS5Z6W.mjs";import"./chunk-BBRWFKS5.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-EPFCERGL.mjs";import"./chunk-IUM4NFKI.mjs";import"./chunk-PMN4PAC3.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-PMWAFDUB.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{b as AGENT_TEST_RUN_WAIT_MINUTES,a as AGENT_TEST_SPECS_DIR,e as agentTestApiName,f as agentTestCommands,d as agentTestSpecFileName,c as agentTestSpecYaml,g as nodeAgentTestSpecFiles,h as writeAgentTestSpec,i as writeScenarioTestSpec,j as yamlOf};
|
|
@@ -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 ie,c as se,d as Vt,e as Jt,f as be}from"./chunk-X2XZQ434.mjs";import{a as Zt,e as Xt}from"./chunk-XMQ5R6TC.mjs";import{I as re,O as Ue,a as Kt}from"./chunk-IXIY6Q4M.mjs";import{f as Le,p as ge,s as Be,u as Yt,w as $e}from"./chunk-BT43WSOS.mjs";import{b as me,d as ue}from"./chunk-MJD6CPZZ.mjs";import{c as qt}from"./chunk-OUU47Y7A.mjs";import{G as Ht}from"./chunk-ZXOUWHYE.mjs";import{c as Wt}from"./chunk-Z3MGN42K.mjs";import{c as Gt,e as Fe,g as Me,h as pe}from"./chunk-TZE3Y7IQ.mjs";import{a as $t,b as V}from"./chunk-CA5NAXSU.mjs";import{C as dt,D as pt,E as mt,Ea as zt,F as ut,Fa as St,J as gt,K as bt,Ka as ae,L as ft,La as Ae,M as yt,N as ht,Pa as M,Qa as xt,Ra as F,Sa as Ee,Sb as Rt,Ta as It,Ua as kt,Va as Ce,Wa as Te,Xa as _e,cb as Ne,dd as Nt,fb as jt,gb as Pt,hb as Ot,hc as wt,jc as vt,kc as At,n as rt,nc as Et,nd as Dt,oc as Ct,od as Ft,pc as Tt,pd as Mt,qe as Lt,rd as Ut,re as Bt,s as we,sd as De,t as it,u as st,v as ct,w as ne,wc as _t,y as lt,z as ve}from"./chunk-6QSHWIZI.mjs";import{b as a,c as Oe,e as g,f as r,g as et,i as D,k as c,l as o,m as tt,o as de,p as Re,s as x,u as w,v,w as ot,x as nt,y as G,z as at}from"./chunk-WZQEK4WT.mjs";function sa(e,t,n){return async s=>{let d=s.map(f=>`${f.objectApiName} (${f.records})`).join(", ");e.log(`[WARN] ${n}: the user may not delete ${d} in the target: those records stay`);let p=e.infraServices?.confirmRemovalLeavingUndeletable;if(!p)return!0;let u=e.orgManager.getOrg(t);return p({org:Nt(u,t),objects:s})}}var Qt={code:"NOT_INITIALIZED",message:"Production Guard is not initialized \u2014 infrastructure services missing"};function ca(){return Object.assign(new Error(Qt.message),{code:Qt.code})}var qe={blocked:"GUARD_BLOCKED",declined:"GUARD_DECLINED"};function la(e){return Object.assign(new Error(`Operation blocked by Production Guard: ${e}`),{code:qe.blocked})}function da(e){return e instanceof Error&&e.code===qe.blocked?qe.blocked:void 0}function Bo(e){return e.robustness??zt}function pa(e){return e.bulkManager??new Kt(Bo(e).bulk.maxConcurrentJobs)}var $o={"sync:schedule":"sync:schedule:","sync:pipeline":"sync:pipeline:","seed:pipeline":"seed:pipeline:","offline-replay":"offline-replay-"};function ma(e,t,n){return{id:`${$o[e]}${t}`,type:n,timestamp:Date.now()}}function ua(e,t,n,s){return{id:e.nextId(),type:n,timestamp:Date.now(),correlationId:t.id,payload:s}}function ga(e,t,n,s,d={}){let p=t==="error"?null:d.autoDismissMs===void 0?5e3:d.autoDismissMs,u={id:e.nextId(),type:"notification",timestamp:Date.now(),payload:{level:t,title:n,message:s,...p===null?{}:{autoDismissMs:p},...d.actions?{actions:d.actions}:{},...d.code?{code:d.code}:{}}};e.broker.postToWebview(u),e.log(`[TX] notification: ${n}`)}function ba(e,t,n,s){let d={id:e.nextId(),type:"operation:started",timestamp:Date.now(),payload:{operationId:t,module:n,description:s}};e.broker.postToWebview(d)}function fa(e,t,n,s,d,p){let u={id:e.nextId(),type:"operation:progress",timestamp:Date.now(),payload:{operationId:t,percentage:n,processedRecords:s,totalRecords:d,currentStep:p}};e.broker.postToWebview(u)}function ya(e,t,n){let s={id:e.nextId(),type:"operation:completed",timestamp:Date.now(),payload:{operationId:t,result:n}};e.broker.postToWebview(s)}var qo=Symbol("sandforge.uncorrelated");function eo(e,t,n,s,d,p={}){let u=V(d),f=d instanceof qt?d:void 0,k=qo in s,E=p.code??f?.code??"UNKNOWN";k||Ko(e.broker,u,E),e.log(`[ERR] ${t}: ${u}${k?` (uncorrelated: ${String(s.reason)})`:""}`);let O={id:e.nextId(),type:n,timestamp:Date.now(),...k?{}:{correlationId:s.id},payload:{message:u,code:E,retryable:p.retryable??!1,...f?{orgId:f.orgId}:{},...p.extraPayload}};e.broker.postToWebview(O),e.log(`[TX] ${n}: ${u}`)}function ha(e,t){let n={id:e.nextId(),type:t.type,timestamp:Date.now(),payload:t.payload};e.broker.postToWebview(n)}function za(e){let t=e?.getSandforgeSetting;if(!(!t||!t("grappe.enabled",!1)))return{enabled:!0,autoActivateThreshold:t("grappe.autoActivateThreshold",1e4),maxWorkers:rt.maxWorkers,grappeSize:t("grappe.grappeSize",5e3),strategy:"round_robin",backPressure:{enabled:!1,maxQueueDepth:3,highWaterMark:80,lowWaterMark:60,strategy:"pause",monitoringInterval:5e3},checkpointing:!0,isolationLevel:"per_grappe"}}function Sa(e){let t=new Set(e.map(s=>s.batchSize)),[n]=t;return{...e.length>0?{objectName:e.map(s=>s.objectApiName).join(", ")}:{},...t.size===1&&n!==void 0?{batchSize:n}:{}}}function xa(e,t,n,s,d={}){let p={id:e.nextId(),type:"operation:failed",timestamp:Date.now(),payload:{operationId:t,error:n,retryable:s,...d.extraPayload}};e.broker.postToWebview(p),d.authored!==!0&&Zo(e,n,d.context)}var Go=[/^Operation cancelled by user\b/,/^Operation blocked by Production Guard: /,/^Production Guard is not initialized\b/,/^Duplicate operation: /,/^A backup or rollback operation is already running for org /,/^Object describe not available for '/,/^CRUD_FLS_DENIED: /,/^CRUD\/FLS check failed for /,/^No backup found for operation /,/^Backup \S+ was taken from org /,/^Restore not run: /,/^Pipeline failed$/,/^Pipeline did not start: /,/^Pipeline ran out of time: /,/^Org not found: /,/^No credentials for org /,/^Invalid username format: /];function Wo(e){return Go.some(t=>t.test(e))}var to=1e4,Ge=new WeakMap;function Ko(e,t,n){let s=De(t,{code:n});if(!s?.actionKey)return;let d=Ge.get(e)??new Map,p=Date.now();for(let[u,f]of d)p-f>to&&d.delete(u);d.set(s.code,p),Ge.set(e,d)}function Ho(e,t){let n=Ge.get(e)?.get(t);return n!==void 0&&Date.now()-n<=to}function Zo(e,t,n={}){if(!(e.broker.panelCount>0)||Wo(t))return;let d=$t(t,Ut)??"UNKNOWN",p=De(t,{code:d});if(p?.actionKey){if(Ho(e.broker,p.code))return;e.broker.showFixSuggestion({source:"catalogue",code:p.code,actionKey:p.actionKey});return}let u=e.errorResolver;u&&u.resolveError({errorCode:d,message:t},n).then(f=>{e.broker.showFixSuggestion({source:"model",text:Xo(f)})}).catch(f=>{e.log?.(`[ERR] operation:failed resolution: ${V(f)}`)})}function Xo(e){return e.suggestions[0]?.description||e.explanation}import{isAbsolute as tn}from"node:path";var i=a().min(1).max(128),l=a().regex(/^[A-Za-z][A-Za-z0-9_]*$/,"Invalid Salesforce API name").max(80),so=c(l).max(300),m=a().min(1).max(200),J=a().max(2e3).refine(Fe,{message:Me}),on=a().refine(Gt,{message:"ORDER BY clause must list only field names with optional ASC/DESC and NULLS FIRST/LAST (no LIMIT, OFFSET, FOR UPDATE or subquery)."}),y=100,co=1e4,B=o({keepDays:g().int().min(ve.min).max(ve.max).optional(),excluded:c(l).max(y).refine(e=>new Set(e).size===e.length,"An object is left out twice").optional()}).strict(),he={sweepLate:r().optional(),sweepUntied:r().optional()};function nn(e){return Wt(e)}function an(e,t='turn on "Copy the files of these records"'){return _t(e)?`Sync copies files with the records they hang on, not as an object of their own: "${e}" keeps its content in a file body. Remove it from this configuration and ${t} instead; the sync was not started.`:`Sync does not copy "${e}": no copy writes it \u2014 users and their access, metadata, a record's history, feed or sharing rows, and the records the platform keeps for itself are not data a copy carries. Remove it from this configuration; the sync was not started.`}var rn=w(gt,{error:e=>e.input==="manual"?"Manual conflict review is not available for a sync run: no run shows its conflicts to anyone before it writes. Pick source wins, target wins, newest wins or merge \u2014 target wins keeps every value the target holds where the two orgs differ. The sync was not started.":`Conflict strategy "${String(e.input)}" is not one a sync run acts on: pick source wins, target wins, newest wins or merge. The sync was not started.`}),sn=bt.extend({objectApiName:l.refine(e=>!nn(e),{error:e=>an(String(e.input))}),externalIdField:nt(e=>typeof e=="string"&&e.trim()===""?void 0:e,l.optional()),where:J.optional(),orderBy:on.optional(),batchSize:g().int().positive().max(co).optional()}).strip().refine(e=>e.operation!=="upsert"||(e.externalIdField??"Id").toLowerCase()!=="id",{path:["externalIdField"],error:e=>`An upsert of "${String(e.input.objectApiName)}" needs an External ID field: matching on Id cannot work, because the id belongs to the source org and the target has never issued it. Name an External ID field both orgs share, or set the operation to insert. The sync was not started.`}).superRefine((e,t)=>{let n=Ft([e]);n.length!==0&&t.addIssue({code:G.custom,message:`${Mt(n)} The sync was not started.`,params:{unreadablePatterns:n}})});function oo(e){return et({error:()=>`Sync does not run Apex: remove "${e}" from this configuration. The sync was not started so the script cannot be skipped without you knowing.`}).optional()}var Ke=ft.extend({id:m.optional(),sourceOrgId:i,targetOrgId:i,objects:c(sn).min(1).max(y),conflictStrategy:rn,createdAt:a().max(40).optional(),updatedAt:a().max(40).optional(),preScript:oo("preScript"),postScript:oo("postScript"),dryRun:v(!1,{error:()=>'A sync configuration cannot ask for a dry run: remove "dryRun" from it. A run of it writes to the target org; to see what it would write, simulate it from the Sync page. The run was not started, so it cannot write while you believed it was only reporting.'}).optional()}).strip().superRefine((e,t)=>{e.direction==="target_to_source"&&t.addIssue({code:G.custom,path:["direction"],message:'Sync writes source to target only: direction "target_to_source" is not supported. Swap the source and target orgs to copy the other way. The sync was not started, so it cannot write into the org you meant to read from.'}),e.mode!=="full"&&e.mode!=="delta"&&t.addIssue({code:G.custom,path:["mode"],message:`Sync runs a full or a delta sync only: mode "${e.mode}" is not implemented. Set mode to "full" or "delta". The sync was not started, so it cannot replay the whole object set while you believed it was reading changes only.`}),e.mode==="delta"&&e.objects.forEach((n,s)=>{n.operation==="upsert"||n.operation==="update"||t.addIssue({code:G.custom,path:["objects",s,"operation"],message:`A delta sync writes ${n.objectApiName} again for every record it reads twice, and ${n.operation} would ${n.operation==="insert"?"create a second copy":"delete a record already gone"}. Write it by upsert on an External ID, or by update, or run the configuration in full. The sync was not started.`})}),e.propagateDeletes===!0&&(e.mode!=="delta"?t.addIssue({code:G.custom,path:["propagateDeletes"],message:'Deletions are carried by a delta sync only, which knows since when to look for them: set mode to "delta", or turn deletions off. The sync was not started.'}):e.objects.forEach((n,s)=>{if(n.operation!=="upsert"&&n.operation!=="update")return;let d=Ht(n);"refused"in d&&t.addIssue({code:G.custom,path:["objects",s],message:`${d.refused} Turn deletions off, or carry a source field onto the key. The sync was not started.`})}))}),Ea=o({suggestedName:a().min(1).max(255).refine(e=>!e.includes("/")&&!e.includes("\\"),"suggestedName must not contain a path"),content:a().max(32*1024*1024),extensions:c(a().regex(/^[A-Za-z0-9]+$/)).max(8).optional()}),Ca=o({config:Ke,muteAutomation:r().optional(),checkpointFirst:B.optional()}),Ta=o({config:Ke,checkpointFirst:B.optional()}),_a=o({operationId:m}),Na=o({config:Ke}),Da=o({id:m}),Fa=o({orgId:i,targetOrgId:i.optional()}),Ma=o({sourceOrgId:i,targetOrgId:i,objectApiName:l}),lo=w(["source_wins","target_wins","newest_wins","manual","merge"]),cn=Re("kind",[o({kind:v("id")}),o({kind:v("externalId"),field:l}),o({kind:v("syncConfig"),configId:m})]),Ua=o({sourceOrgId:i,targetOrgId:i,watchedObjects:c(l).min(1).max(y),apply:c(o({objectApiName:l,match:cn,applyDeletes:r()})).max(y),conflictStrategy:lo,flushIntervalMs:g().int().min(50).max(6e4),maxBatchSize:g().int().min(1).max(200),keepContactPoints:r().optional()}).refine(e=>e.apply.every(t=>e.watchedObjects.includes(t.objectApiName)),{message:"Every applied object must be watched.",path:["apply"]}),La=o({sessionId:a().max(200)}),Ba=o({sourceOrgId:i,targetOrgId:i}),$a=o({conflictId:a().min(1).max(500),eventReplayId:g().optional(),resolution:lo,fieldResolutions:x(a(),o({value:D(),source:w(["source","target","manual"])})).optional()}),qa=o({entryId:m}),Ga=o({runId:m}),Wa=o({realtime:v(!0).optional()}).optional(),Ka=o({sourceOrgId:i,targetOrgId:i,objects:c(l).max(y),configId:m.optional()}),Ha=o({runId:m,includeChanged:r().optional(),sweep:r().optional(),again:r().optional(),muteAutomation:r().optional(),...he}),Za=o({runId:m}),Xa=o({runId:m,again:r().optional(),sweptObjects:so.optional()}),Ya=o({runId:m}),Va=o({runId:m,includeChanged:r().optional(),sweep:r().optional(),again:r().optional(),muteAutomation:r().optional(),...he}),Ja=o({runId:m}),Qa=o({format:w(["csv","json"]),entryIds:c(m).max(500).optional()}),ln=o({id:m,name:a().min(1).max(200),configId:m,cron:a().min(1).max(100),timezone:a().min(1).max(100),enabled:r(),maxRetries:g().int().min(0).max(10),notifyOnComplete:r(),notifyOnFailure:r(),createdAt:a().max(40),updatedAt:a().max(40),version:g().int().positive()}).strip(),er=o({schedule:ln}),tr=o({scheduleId:m,enabled:r()}),or=o({scheduleId:m}),dn=dt.extend({objectApiName:l,recordCount:g().int().positive().max(ne),batchSize:g().int().positive().max(co).optional()}).loose(),pn=pt.extend({childObject:l,lookupField:l,parentObject:l}).superRefine((e,t)=>{e.parents.kind==="existing"&&e.parents.where!==void 0&&!Fe(e.parents.where)&&t.addIssue({code:G.custom,path:["parents","where"],message:Me})}),mn=mt.extend({objects:c(dn).min(1).max(y),relations:c(pn).max(y).optional()}).loose().superRefine(ut),nr=o({orgId:i,template:mn,muteAutomation:r().optional(),checkpointFirst:B.optional(),fit:o({share:g().gt(0).max(1),withinMB:g().positive().max(1e6).optional(),before:g().int().positive().max(ne*y)}).strict().optional(),locale:a().regex(/^[a-z]{2,3}(?:_[A-Za-z0-9]{2,4}){0,2}$/).optional(),dryRun:r().optional()}),ar=o({orgId:i}),rr=o({orgId:i,objects:c(l).min(1).max(y),publishes:r().optional()}).strict(),ir=o({orgId:i,objectApiName:l}),sr=o({id:m}),cr=o({template:x(a(),D())}),lr=o({description:a().max(1e4)}),dr=o({}).strict(),pr=o({orgId:i,pack:ae,seed:Ae.shape.seed,articleBodyField:l.optional()}).strict(),mr=o({orgId:i,pack:ae,options:Ae,locale:a().regex(/^[a-z]{2,3}(?:_[A-Za-z0-9]{2,4}){0,2}$/).optional(),muteAutomation:r().optional(),checkpointFirst:B.optional()}).strict(),ur=o({orgId:i}).strict(),gr=o({pack:ae,overwrite:r().optional()}).strict(),br=o({runId:m,choice:Rt,overwrite:r().optional()}).strict(),un=131072,gn=o({objectApiName:l,whereClause:J.optional()}).loose(),fr=o({sourceOrgId:i}),yr=o({sourceOrgId:i,targetOrgId:i,objects:c(gn).min(1).max(y),upsert:r().optional(),externalIdField:l.optional(),previewId:m.optional(),keepContactPoints:r().optional(),checkpointFirst:B.optional()}).refine(e=>!e.upsert||e.externalIdField!==void 0,{message:"externalIdField is required when upsert is true",path:["externalIdField"]}),bn=o({csvHeader:a().min(1).max(500),sfFieldApiName:a().max(80),sfFieldType:a().max(40),sfFieldLength:g().int().positive().nullable()}).loose(),hr=o({orgId:i,objectApiName:l,records:c(x(a(),a().max(un))).min(1).max(st),columnMappings:c(bn).min(1).max(ct),externalIdField:l.optional(),checkpointFirst:B.optional()}),zr=o({orgId:i,objects:c(l).min(1).max(y),wheres:x(l,J).optional(),slices:r().optional()}).refine(e=>Object.keys(e.wheres??{}).every(t=>e.objects.some(n=>n.toLowerCase()===t.toLowerCase())),{message:"A filter names an object the backup reads: give it in objects",path:["wheres"]}),Sr=o({orgId:i}),xr=o({orgId:i,templateId:a().min(1).max(200).optional()}),Ir=o({orgId:i,operationId:a().min(1).max(200)}),kr=o({orgId:i,operationIds:c(a().min(1).max(200)).min(1).max(1e3).optional()}),W={acceptAutomation:r().optional(),acceptEmails:r().optional(),muteAutomation:r().optional()},X={fromPage:v(!0).optional()},jr=o({orgId:i,operationId:m,rewriteAll:r().optional(),includeChanged:r().optional(),slices:c(g().int().positive()).min(1).max(lt*y).optional(),...W,...X}),Pr=o({orgId:i,act:w(["masking","restore","cleanup"]),objects:c(o({objectApiName:l,records:g().int().min(0)})).max(y),erasure:r().optional(),...W,...X}),He={objects:c(l).min(1).max(y).optional(),where:J.optional()},Ze=e=>e.where===void 0||e.where.trim()===""||e.objects?.length===1,Xe={message:"A WHERE clause filters the rows of one object: name exactly one in objects",path:["where"]},Or=o({orgId:i,templateId:m,...He,resumeFrom:m.optional(),snapshot:r().optional(),slices:r().optional(),maxRequests:g().int().positive().max(1e9).optional(),abandon:r().optional(),...W,...X}).refine(Ze,Xe).refine(e=>!(e.snapshot===!0&&e.resumeFrom!==void 0&&e.slices!==!0),{message:"A resume takes no snapshot: the run it resumes has written over some of its rows",path:["snapshot"]}).refine(e=>!(e.slices===!0&&e.snapshot===!1),{message:"A run in slices backs each slice up before it masks it: it cannot keep no snapshot",path:["slices"]}).refine(e=>e.maxRequests===void 0||e.slices===!0,{message:"A bound on requests stops a run in slices between two of them: give slices too",path:["maxRequests"]}).refine(e=>e.abandon!==!0||e.resumeFrom===void 0&&e.snapshot!==!0&&e.maxRequests===void 0,{message:"Giving up a set of slices masks nothing: it takes no resume, snapshot or bound",path:["abandon"]}),Rr=o({orgId:i,templateId:m,...He,slices:r().optional()}).refine(Ze,Xe),wr=o({orgId:i,templateId:m,...He}).refine(Ze,Xe),vr=o({name:a().trim().min(1).max(jt),rules:c(Ot).min(1).max(Pt).refine(e=>new Set(e.map(t=>t.fieldPattern.toLowerCase())).size===e.length,"A field has two rules")}),Ar=o({templateId:m}),Er=o({orgId:i,objectNames:c(l).min(1).max(y)}),Cr=o({orgId:i,objects:c(o({objectApiName:l,duplicateKey:l.optional()})).min(1).max(10).refine(e=>new Set(e.map(t=>t.objectApiName.toLowerCase())).size===e.length,{message:"Each object may be named once per scan"}),staleDays:g().int().min(1).max(3650)}),po=c(l).min(1).max(10).refine(e=>new Set(e.map(t=>t.toLowerCase())).size===e.length,{message:"Each object may be named once per request"}),Tr=o({orgId:i,objects:po}),_r=o({orgId:i,objects:po,requestId:Oe().optional(),email:a().trim().refine(Ct,"Not an email address").optional(),name:a().refine(Tt,"Not a name").optional(),phone:a().refine(Et,"Not a phone number").optional()}).refine(e=>e.email!==void 0||e.name!==void 0||e.phone!==void 0,{message:"A search needs an email address, a name or a phone number"}),fn=o({orgId:i,requestId:Oe()}),ze=a().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record Id"),Nr=o({runId:m,recordId:ze}).strict(),Dr=fn.extend({mode:w(["anonymize","delete"]),records:c(o({objectApiName:l,ids:c(ze).min(1).max(200)})).min(1).max(10).refine(e=>new Set(e.map(t=>t.objectApiName.toLowerCase())).size===e.length,{message:"Each object may be named once per request"}),dryRun:r(),...W}),yn=Re("kind",[o({kind:v("stale"),days:g().int().min(1).max(3650)}),o({kind:v("orphans"),fieldApiName:l}),o({kind:v("duplicates"),keyField:l})]),mo=o({orgId:i,objectApiName:l,recommendation:yn}),Fr=mo.extend({after:o({skip:g().int().nonnegative().max(1e8),id:ze.optional(),modified:a().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:?\d{2})$/).optional()}).strict().optional()}),Mr=mo.extend({dryRun:r(),...W,...X}),We=2e3,uo={mode:w(["objects","org"]),objects:c(l).min(1).max(We).optional(),excluded:c(l).max(We).optional(),customSettings:r().optional(),files:r().optional(),managedPackages:r().optional(),unrestorable:r().optional()},hn=o(uo).strict().refine(e=>e.mode==="objects"==(e.objects!==void 0),{message:"The objects picked are named in objects mode, and only there"}),Ur=o({orgId:i,...uo,objects:c(l).max(We).optional()}).strict().refine(e=>e.mode==="objects"==(e.objects!==void 0),{message:"The objects picked are named in objects mode, and only there"}),Lr=o({orgId:i,request:hn,deleteMode:w(["recycle","hard"]),checkpointFirst:r().optional(),acceptNoUndo:r().optional(),acceptPeopleActive:r().optional(),...W,...X}),Br=o({orgId:i,previewId:m.optional(),resumeRunId:a().regex(/^em-\d{8}-\d{6}-[a-z0-9]{4}$/).optional(),acceptNoUndo:r().optional(),acceptPeopleActive:r().optional(),checkpointFirst:r().optional(),...W,...X}).refine(e=>e.previewId===void 0!=(e.resumeRunId===void 0),{message:"An emptying acts on a simulation, or takes up a run: one of them"}),$r=o({operationId:m}),qr=o({orgId:i,runId:a().regex(/^em-\d{8}-\d{6}-[a-z0-9]{4}$/),...W,...X}),Gr=o({orgId:i}),Wr=o({orgId:i}).strict(),Kr=o({alertId:m}),go=o({sourceOrgId:i,targetOrgId:i}),Hr=go.extend({types:c(a().min(1).max(80)).min(1).max(50),includeManaged:r().optional()}),zn=o({componentType:w(At),fullName:a().min(1).max(400).regex(/^[^\u0000-\u001f\u007f]+$/,"A component name holds no control character")}),Zr=go.extend({components:c(zn).min(1).max(500).refine(e=>new Set(e.map(t=>`${t.componentType}:${t.fullName}`)).size===e.length,{message:"Each component may be named once per deployment"}),testLevel:w(wt),runTests:c(a().max(255).regex(vt,"Not an Apex class name")).max(100).optional()}).refine(e=>e.sourceOrgId!==e.targetOrgId,{message:"The source and the target are the same org",path:["targetOrgId"]}).refine(e=>e.testLevel!=="RunSpecifiedTests"||(e.runTests?.length??0)>0,{message:"RunSpecifiedTests names at least one test class",path:["runTests"]}),Xr=o({validationId:a().regex(/^0Af[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/,"Not a deployment id"),targetOrgId:i}).strict(),Sn=a().regex(/^\d+\.\d+\.\d+$/,"Invalid semver"),ye=a().regex(/^[A-Za-z][A-Za-z0-9_]*\.[A-Za-z][A-Za-z0-9_]*$/,"Expected an Object.field key").max(170),xn=o({name:a().min(1).max(80),label:a().min(1).max(200),filterField:l,valuesSoql:a().min(1).max(4e3)}),In=o({name:a().min(1).max(80),label:a().min(1).max(200),whereFragment:J}),no=de([o({action:v("clear")}),o({action:v("replace"),value:a().max(255)})]),bo=o({rootObject:l,axes:c(xn).max(20),edgeCases:c(In).max(50),budgetMaxRecords:g().int().positive().max(1e5).optional(),candidatesPerCombination:g().int().positive().max(20).optional(),expectedObjects:c(l).max(100).optional(),maxNodes:g().int().min(10).max(500).optional(),excludedObjects:c(l).max(200).optional(),excludedFields:x(l,c(l).max(500)).optional(),sasDir:a().min(1).max(500).optional(),datasetDir:a().min(1).max(500).optional(),rulesFilePath:a().min(1).max(500).optional(),datasetVersion:Sn.optional(),protectedOrgIds:c(i).max(50).optional(),identityKeys:x(l,c(l).min(1).max(10)).optional(),undeletableObjects:x(l,l).optional(),requiredLookupPlaceholders:x(ye,o({name:a().min(1).max(200),recordTypeDeveloperName:a().min(1).max(97).optional(),targetObjectApiName:l.optional()})).optional(),requiredFieldDefaults:x(ye,D()).optional(),picklistRules:x(ye,no).optional(),defaultPicklistRule:no.optional(),duplicateErrorPatterns:c(a().min(1).max(200)).max(50).optional(),mockDetection:o({metadataTypeApiName:l,isMockedFieldApiName:l}).optional(),mandatoryLookups:x(l,c(l).min(1).max(50)).optional(),presenceKeys:x(l,l).optional()}),Yr=o({config:bo}),Vr=o({sourceOrgId:i}),Jr=o({fields:c(ye).min(1).max(2e3)}),Qr=o({sourceOrgId:i,author:a().min(1).max(120).optional()}),ce=o({organizationId:kt,checkpointId:F}).strict(),kn=bo.pick({requiredFieldDefaults:!0,requiredLookupPlaceholders:!0,picklistRules:!0,defaultPicklistRule:!0,identityKeys:!0,undeletableObjects:!0,duplicateErrorPatterns:!0,mockDetection:!0,protectedOrgIds:!0}).strict(),fo=ce.extend({choices:Ne,config:kn.optional(),confirmStaging:a().min(1).max(255).optional()}).strict(),jn=fo.extend({choices:Ne.optional()}).strict(),ti=o({targetOrgId:i,replay:fo.optional(),pilot:r().optional(),reload:r().optional(),writeEncrypted:r().optional(),maxRecords:g().int().positive().max(1e6).optional(),muteAutomation:r().optional(),checkpointFirst:B.optional(),sweep:r().optional(),...he,includeChanged:r().optional(),acceptEmails:r().optional(),acceptAutomation:r().optional(),goneFirst:c(ze).max(1e6).optional()}),Pn=o({targetOrgId:i}),oi=Pn.extend({replay:jn.optional()}),ni=o({targetOrgId:i,loadedAt:a().min(1).max(64),includeChanged:r().optional(),sweep:r().optional(),...he,muteAutomation:r().optional(),replay:ce.optional()}),ai=o({targetOrgId:i,loadedAt:a().min(1).max(64),reload:r().optional(),replay:ce.optional()}),ri=o({targetOrgId:i,loadedAt:a().min(1).max(64),sweptObjects:so.optional(),reload:r().optional(),replay:ce.optional()}),ii=o({targetOrgId:i,loadedAt:a().min(1).max(64),includeChanged:r().optional(),replay:ce.optional()}),yo=1e3,ho=3650,On=200,Z=c(l).min(1).max(yo).refine(e=>new Set(e).size===e.length,"An object is named twice");function zo(e){return e.mode==="picked"?e.objects!==void 0:e.objects===void 0}var So=de([v("all"),c(l.refine(e=>e.toLowerCase().endsWith("__c"),"A custom setting's API name ends in __c")).min(1).max(yo).refine(e=>new Set(e.map(t=>t.toLowerCase())).size===e.length,"A custom setting is named twice")]),xo={path:["objects"],message:'Name the objects with "picked", and none with "everything"'},si=o({orgId:i.optional()}).optional(),Rn=1e6,Io=g().int().min(1).max(Rn),ci=o({orgId:i,mode:_e,objects:Z.optional(),excluded:Z.optional(),customSettings:So.optional(),maxTotal:Io.optional()}).refine(zo,xo),li=o({orgId:i,name:Te,mode:_e,objects:Z.optional(),excluded:Z.optional(),customSettings:So.optional(),maxTotal:Io.optional(),keepDays:g().int().min(0).max(ho),ignoredFields:Ce.optional()}).refine(zo,xo),di=o({checkpointId:F,objects:Z.optional(),muteAutomation:r().optional(),acceptOutside:r().optional()}),pi=o({checkpointId:F,previewId:Ee,objects:Z.optional(),acceptAutomation:r(),muteAutomation:r().optional(),acceptEmails:r().optional(),acceptNoUndo:r(),acceptRecreate:r(),acceptOutside:r(),acceptUnseen:r(),fromPage:v(!0).optional()}),mi=o({checkpointId:F,previewId:Ee,objects:Z,acceptOutside:r()}),ui=o({checkpointId:F}),wn=200,gi=o({token:m,orgId:i,key:a().min(1).max(wn),keepDays:g().int().min(0).max(ho)}),bi=o({checkpointId:F,rewindId:It,acceptAutomation:r(),muteAutomation:r().optional(),acceptEmails:r().optional(),fromPage:v(!0).optional()}),fi=o({checkpointIds:c(F).min(1).max(On).refine(e=>new Set(e).size===e.length,"A checkpoint is named twice")}),yi=o({checkpointId:F,keep:r()}),hi=o({checkpointId:F,name:Te}),zi=o({checkpointId:F,fields:Ce}),vn=500,Si=o({orgIds:c(i).min(1).max(vn).refine(e=>new Set(e).size===e.length,"An org is named twice").optional()}).strict().optional(),xi=o({sourceOrgId:i,targetOrgId:i,includeStandardObjects:r()}),Ii=o({sourceOrgId:i,objectApiNames:c(l).min(1).max(it)}),ki=o({sourceOrgId:i,targetOrgId:i,selectedObjects:c(l).max(y),includeStandardObjects:r(),maxDepth:g().int().min(1).max(10).optional(),maxObjects:g().int().min(1).max(500).optional()}),ji=o({complianceFramework:ht,objectFilters:x(a(),J).optional(),overrides:c(o({objectApiName:l,fieldApiName:l,method:de([yt,v("skip")])})).max(500).optional()}),Pi=o({grappeThreshold:g().int().nonnegative(),keepContactPoints:r().optional(),muteAutomation:r().optional(),checkpointFirst:B.optional()}),Oi=o({mode:o({share:v(!0).optional(),caps:x(l,g().int().min(1).max(ne)).refine(e=>Object.keys(e).length<=y,"Too many caps").optional(),all:g().int().min(1).max(ne).optional(),withinMB:g().positive().max(1e6).optional()}).strict().refine(e=>e.share===!0||e.caps!==void 0||e.all!==void 0,"Fit by share, by caps, or both"),muteAutomation:r().optional(),checkpointFirst:B.optional()}),Ri=o({objectApiName:l}),wi=o({orgId:i.optional(),sourceOrgId:i.optional(),alreadySelected:c(l).max(y).optional()}).loose(),vi=o({orgId:i.optional(),sourceOrgId:i.optional(),objectApiName:l.optional(),alreadySelected:c(l).max(y).optional(),selectedObjects:c(l).max(y).optional(),availableObjects:c(l).max(500).optional()}).loose(),Ai=o({sourceOrgId:i,targetOrgId:i.optional(),selectedObjects:c(l).min(1).max(y),parentObjects:c(l).max(y).optional()}).loose(),An=St.extend({sourceOrgId:i,targetOrgId:i,selectedObjects:c(l).min(1).max(y),parentObjects:c(l).max(y).default([])}).loose(),Ei=o({config:An.optional(),sourceOrgId:i.optional(),targetOrgId:i.optional(),selectedObjects:c(l).min(1).max(y).optional(),parentObjects:c(l).max(y).optional()}).loose(),En=a().min(1).max(5e4),Ci=o({conversationId:m,message:a().max(5e4)}),Ti=o({title:a().min(1).max(300)}),_i=o({conversationId:m}),Ni=o({apiKey:a().min(1).max(500),errorResolution:r().optional()}),Di=o({enabled:r().optional(),errorResolution:r().optional()}),Fi=o({orgId:i,objectName:l,sampleSize:g().int().positive().max(1e4).optional()}),Mi=o({orgId:i,prompt:a().trim().min(1).max(2e3).optional(),soql:a().trim().min(1).max(2e4).optional()}).refine(e=>e.prompt===void 0!=(e.soql===void 0),{message:"Send a prompt to draft from or a query to check, not both and not neither"}),Ui=o({description:En,orgIds:c(i).max(50).optional()}),Li=o({requestId:m}),fe=c(a().min(1).max(M.picklistValue)).max(M.picklistValues),ao={label:a().max(M.agentLabel).optional(),description:a().max(M.agentDescription).optional()},Bi=o({text:a().trim().min(1).max(M.text),language:ae.shape.language,casePicklists:o({Status:fe.optional(),Origin:fe.optional(),Priority:fe.optional(),Type:fe.optional()}).optional(),agent:o({topics:c(o({name:a().min(1).max(M.agentName),...ao,actions:c(o({name:a().min(1).max(M.agentName),...ao})).max(M.agentActions)})).max(M.agentTopics)}).optional(),draft:xt.optional(),maskOnly:r().optional()}),$i=o({filePath:a().min(1).max(2e3)}),qi=o({name:a().max(200),config:x(a(),D())}),Gi=o({operationId:m.optional(),executionId:m.optional(),objectName:a().min(1).max(200).optional()}).loose(),Wi=o({policyId:m}),Ki=o({policy:x(a(),D())}),Hi=o({policyId:m,orgId:i}),Zi=o({module:a().min(1).max(50).optional(),orgId:i.optional(),offset:g().int().min(0).max(we).optional(),limit:g().int().min(1).max(we).optional()}).optional(),Xi=o({operationId:m.optional()}).optional(),Cn=w(["syncMappings","forgePlans","pipelines","anonymizationTemplates"]),Yi=o({categories:c(Cn).min(1).max(50)}),Vi=o({json:a().min(1).max(5e6),overwrite:r()}),Ji=o({json:a().min(1).max(5e6)}),Qi=o({orgId:a().max(128),authMethod:a().min(1).max(50),alias:a().max(100).optional(),loginUrl:a().max(500).optional(),username:a().max(300).optional(),password:a().max(500).optional(),securityToken:a().max(100).optional(),clientId:a().max(256).optional(),jwtKeyFile:a().max(4096).optional()}).loose(),ko=a().trim().max(100).regex(/^[\w.-]*$/,"an alias is letters, digits, dots, dashes and underscores").optional(),Tn=a().trim().min(1,"the username is required").max(80).regex(/^[\w.@+-]+$/,"a username is written like an email address"),jo=a().trim().min(1,"the consumer key is required").max(256).regex(/^[A-Za-z0-9._-]+={0,2}$/,"a consumer key is letters, digits, dots, dashes and underscores"),_n=a().trim().min(1,"the private key file is required").max(4096).regex(/^[^\u0000-\u001f\u007f]+$/,"the private key file path holds a control character").refine(e=>tn(e),"give the private key file as an absolute path"),es=o({alias:ko,loginUrl:a().max(500).optional(),username:Tn,clientId:jo,jwtKeyFile:_n}).loose(),ts=o({alias:ko,loginUrl:a().max(500).optional(),clientId:jo}).loose(),os=o({requestId:m}),ns=o({orgId:i}),as=o({orgId:i}),rs=o({orgId:i}).strict(),is=o({orgId:i,alias:a().trim().min(1).max(100),color:a().regex(/^#[0-9A-Fa-f]{6}$/),tags:c(a().trim().min(1).max(50)).max(20),staging:r().optional()}),ss=o({key:a().min(1).max(200),value:D()}),cs=o({enabled:r()}),ls=o({lng:w(["en","fr","de","es","ja","pt-BR"])}),ds=o({targetOrgId:i,sourceOrgId:i.optional()}),ps=o({moduleId:a().min(1).max(64),route:a().min(1).max(64),overlay:r()}),ms=o({moduleId:a().min(1).max(64)}),Nn=80,Dn=ot(e=>Lt(e)||Bt(e)||typeof e=="string"&&e.trim()!==""&&e.length<=Nn,{message:"Not a pipeline step type"}),Fn=o({pipeline:o({name:a().min(1).max(200),steps:c(o({type:Dn,config:x(a(),D()).default({})}).loose()).max(200),variables:c(x(a(),D())).max(200).default([]),triggers:c(x(a(),D())).max(50).default([])}).loose(),variables:x(a(),a().max(2e3)).optional(),dryRun:r().optional()}),Mn=tt({since:at.datetime({offset:!0}),runner:w(["cron","taskScheduler","githubActions"]),file:a().min(1).max(255).refine(e=>!/[\\/]/.test(e),"The file's name, without its folder"),digest:a().regex(/^sha256:[0-9a-f]{64}$/,"Not a digest: sha256: and 64 hex digits")}),us=Fn.shape.pipeline.extend({id:a().min(1).max(200),runsOutside:Mn.optional()}),gs=o({pipelineId:m}),bs=o({id:a().max(200),config:x(a(),D())}),fs=o({id:m}),ys=o({operationId:m,stepId:m,decision:w(["approved","rejected"])}),Un=255,Po={pipelineId:m,stepId:m},hs=o({pipelineId:m}),zs=o({...Po,typed:a().min(1).max(Un)}),Ss=o(Po),xs=o({category:a().max(100).optional(),query:a().max(500).optional()}).loose().optional(),Is=o({templateId:m});function Ln(e){return e.issues.slice(0,3).map(t=>`${t.path.join(".")||"(root)"}: ${t.message}`).join("; ")}function Bn(e){let t=e.issues.map(n=>n.code==="custom"?n.params?.unreadablePatterns:void 0);return t.every(n=>n!==void 0)?t.flat():void 0}function ks(e,t,n,s){let d=e.safeParse(t.payload);if(!d.success){let p=Ln(d.error),u=Bn(d.error);return eo(s,t.type,n,t,new Error(`Invalid payload \u2014 ${p}`),u?{code:Dt,extraPayload:{rules:u}}:{code:"INVALID_PAYLOAD"}),null}return d.data}var $n=5;function Se(e){return e.slice(0,15)}function qn(e){let t=e.errors?.[0];if(t===void 0)return"The org gave no reason.";if(typeof t=="string")return t;let n=t.statusCode??"",s=t.message??"";return n&&s?`${n}: ${s}`:n||s||"The org gave no reason."}function Oo(e){let t=new Set;for(let n of e){let s=n.Id;typeof s=="string"&&t.add(Se(s))}return t}async function Ro(e){let t=[],n=[],s={},d=!1,p=!1,u=e.stampsFor,f=ie(e.org),k=e.org.serverTime?.bind(e.org),E=u&&k?Date.now()+await se({serverTime:k})-re:Number.NaN;for(let{objectApiName:O,ids:A}of e.plan){let I={objectApiName:O,planned:A.length,undeleted:0,alreadyBack:0,goneForGood:0,refused:0,reasons:[]};t.push(I);let z=_=>{I.reasons.length<$n&&!I.reasons.includes(_)&&I.reasons.push(_)},R=pe(O);for(let _=0;_<A.length;_+=me){let C=A.slice(_,_+me);if(p||e.signal?.aborted){p=!0,I.notReached=(I.notReached??0)+C.length,n.push(...C);continue}let[ee]=ue(C,me),K,te;try{K=Oo((await e.org.queryDeleted(`SELECT Id FROM ${R} WHERE Id IN (${ee}) AND IsDeleted = true`)).records),te=Oo((await e.org.query(`SELECT Id FROM ${R} WHERE Id IN (${ee})`)).records)}catch(j){I.refused+=C.length,z(`The recycle bin could not be read: ${V(j)}`),n.push(...C);continue}let h=C.filter(j=>K.has(Se(j)));for(let j of C)K.has(Se(j))||(te.has(Se(j))?I.alreadyBack++:I.goneForGood++);if(h.length===0)continue;let U;try{d=!0;let j=await e.undelete(h),T=Array.isArray(j)?j:[j];U=h.map((H,oe)=>T[oe]??{success:!1})}catch(j){let T=V(j);U=h.map(()=>({success:!1,errors:[T]}))}let Y=[];U.forEach((j,T)=>{if(j.success===!0){I.undeleted++,u?.(h[T])&&Y.push(h[T]);return}I.refused++,z(qn(j)),n.push(h[T])}),Y.length>0&&Number.isFinite(E)&&Object.assign(s,await be(e.org,R,Y,E,f))}}return{objects:t,left:n,wrote:d,cancelled:p,stamps:s}}function wo(e){return e.refused+e.goneForGood+(e.notReached??0)}async function Gn(e,t,n,s){let d=new Map(Object.entries(s).map(([u,f])=>[u.slice(0,15),Date.parse(f)])),p=new Set;for(let{objectApiName:u,ids:f}of t){let k=pe(u);for(let E of ue(f)){let O;try{O=(await e.query(`SELECT Id, LastModifiedDate FROM ${k} WHERE Id IN (${E})`)).records}catch{continue}for(let A of O){if(typeof A.Id!="string")continue;let I=A.Id.slice(0,15),z=Date.parse(String(A.LastModifiedDate??""));(z<=n||z<=(d.get(I)??Number.NaN))&&p.add(I)}}}return p}function vo(e){let t=Date.parse(e.startedAt),n=Date.parse(e.lastWrittenAt??e.end?.at??"");return Number.isFinite(n)?{runRecordedAt:new Date(n),...Number.isFinite(t)?{runDurationMs:Math.max(0,n-t)}:{}}:{}}function Wn(e){return e.filter(t=>t.deleted+t.alreadyGone>0).map(t=>t.objectApiName)}async function Ms(e){let{run:t,includeChanged:n}=e,s=e.again===!0,d=ge(t,s),p=d.reduce((b,S)=>b+S.ids.length,0),u=Be(t),f=u.reduce((b,S)=>b+S.ids.length,0),k=Yt(t),E=k.reduce((b,S)=>b+S.ids.length,0),O=[],A=e.backups,I=e.undelete;k.length>0&&!I&&O.push(`The ${E} record(s) the run deleted could not be brought back from the recycle bin here: the next removal offers them again.`),u.length>0&&!A&&O.push(`The values from before the run of ${f} record(s) it wrote over could not be read here: they were not put back, and the next removal offers them again.`);let z,R,_={},C=(e.earlierRuns??[]).map(b=>({runId:b.runId,keys:new Set([...ge(b),...Be(b)].flatMap(({ids:S})=>S.map(L=>L.slice(0,15))))})),ee=b=>C.some(({keys:S})=>S.has(b.slice(0,15))),K=e.sweep,te=u.length>0&&A||k.length>0&&I||K?async b=>{if(k.length>0&&I){let N=u.length>0&&A?await Gn(e.org,u,await Vt(e.org,xe(t)),t.removal?.removalStamps??{}):void 0,q=N?Date.now()+await se(e.org)-re:0;if(R=await Ro({org:e.org,plan:k,undelete:I,...C.length>0?{stampsFor:ee}:{},...e.signal?{signal:e.signal}:{}}),N&&R.wrote){let P=ie(e.org);for(let{objectApiName:Pe,ids:Mo}of u){let Uo=Mo.filter(Lo=>N.has(Lo.slice(0,15)));Object.assign(_,await be(e.org,Pe,Uo,q,P))}}if(R.cancelled||e.signal?.aborted)return R.wrote}if(u.length>0&&A){let N={...t.removal?.removalStamps,..._};z=await Jt({org:e.org,plan:u,backups:A,...xe(t)!==void 0?{lastWriteAt:xe(t)}:{},includeChanged:n,...Object.keys(N).length>0?{stamps:N}:{},...t.unkept?{unkept:t.unkept}:{},...C.length>0?{stampsFor:ee}:{},...e.signal?{signal:e.signal}:{}})}let S=(R?.wrote??!1)||(z?.wrote??!1);if(z?.cancelled||e.signal?.aborted)return S;let L=K?await K(b):!1;return S||L}:void 0,h=await Ue(e.org,d,{...vo(t),...t.removal?.removalStamps?{removalStamps:t.removal.removalStamps}:{},...t.removal?.removalSpans?{removalSpans:t.removal.removalSpans}:{},includeChanged:n,...te?{sweep:te}:{},...e.afterRemoval?{afterRemoval:e.afterRemoval}:{},...e.automationMade?{automationMade:e.automationMade}:{},...e.runUserId?{runUserId:e.runUserId}:{},...e.onUndeletable?{onUndeletable:e.onUndeletable}:{},...e.beforeFirstWrite?{beforeFirstWrite:e.beforeFirstWrite}:{},signal:e.signal,onProgress:e.onProgress}),U=new Date().toISOString();if(h.stoppedForUndeletable)return{result:{runId:t.runId,status:"cancelled",includeChanged:n,objects:[],finishedAt:U},planned:p,plannedBack:f,plannedUndelete:E,notes:[],stoppedForUndeletable:!0};let Y=s?void 0:t.removal?.undo?.removedAt,j={runId:t.runId,status:Zn(Xn(Zt(h.objects,h.cancelled),h.objects,z),h.objects,z,R),includeChanged:n,objects:h.objects,finishedAt:U,...Y?{leftBy:Y}:{},...z&&z.objects.length>0?{restored:z.objects}:{},...R&&R.objects.length>0?{undeleted:R.objects}:{}},T=Xt(j,p,t.removal?.undo,s),H=new Set(h.gone),oe=H.size>0||s&&T?d.flatMap(({ids:b})=>b.filter(S=>!H.has(S))):void 0,Je={..._,...h.stamps},Qe=Object.keys(Je).length>0,No=z?.objects.some(b=>b.restored+(b.restoredWithout??0)>0)===!0,Do=R!==void 0&&!R.cancelled;if(T||Qe||h.span||oe||z||R)try{await e.store.updateRemoval(t.runId,b=>({...b,...T?{undo:T}:{},...Qe?{removalStamps:{...b.removalStamps,...Je}}:{},...h.span?{removalSpans:[...b.removalSpans??[],h.span]}:{},...oe?{removalLeft:oe}:{},...z?{restoreLeft:z.left}:{},...No?{restoredAt:U}:{},...R?{undeleteLeft:R.left}:{},...Do?{undeletedAt:U}:{}}))}catch(b){O.push(`What this removal did could not be kept (${b instanceof Error?b.message:String(b)}): the next removal of the run may set out to take records already gone.`)}let Fo=Object.keys(z?.stamps??{}).length>0?await Kn(e.org,t,e.earlierRuns??[]):new Map,ke=[];for(let{runId:b,keys:S}of C){let L=Fo.get(b),N=Object.fromEntries(Object.entries({...R?.stamps,...z?.stamps}).filter(([P])=>S.has(P.slice(0,15))&&!L?.has(P.slice(0,15)))),q=Object.keys(N).length;if(q!==0)try{await e.store.updateRemoval(b,P=>({...P,removalStamps:{...P.removalStamps,...N},...h.span?{removalSpans:[...P.removalSpans??[],h.span]}:{}})),ke.push({runId:b,records:q})}catch(P){O.push(`What this removal gave back of ${q} record(s) the run ${b} wrote too could not be kept on it (${P instanceof Error?P.message:String(P)}): its removal reads them as changed since it.`)}}let le=e.configs;if(le&&H.size>0&&le.isSaved(t.configId)){let b={sourceOrgId:t.sourceOrgId,targetOrgId:$e(t)};try{let S=d.filter(P=>Le.includes(P.objectApiName)).flatMap(({ids:P})=>P.filter(Pe=>H.has(Pe))),L=le.forgetFiles(t.configId,b,S),N=Wn(h.objects).filter(P=>!Le.includes(P)),q=le.markRemoved(t.configId,b,[...new Set([...N,...L.map(P=>P.objectApiName)])],U);j={...j,...q.length>0?{readWhole:q}:{},...L.length>0?{filesForgotten:L.length}:{}}}catch(S){O.push(`The configuration could not be told what this removal took (${S instanceof Error?S.message:String(S)}): run it full next time.`)}}let je;if(e.links&&H.size>0)try{je=await e.links.forget(t.configId,{sourceOrgId:t.sourceOrgId,targetOrgId:$e(t)},[...H])}catch(b){O.push(`Which records of the target this removal took could not be forgotten (${b instanceof Error?b.message:String(b)}): a later run of the configuration may point a lookup at one of them.`)}return{result:j,planned:p,plannedBack:f,plannedUndelete:E,notes:O,...je?{linksForgotten:je}:{},...ke.length>0?{earlierStamped:ke}:{},...h.duplicateSets?{duplicateSets:h.duplicateSets}:{}}}async function Us(e){let{run:t}=e,n=ge(t);return{outcome:await Ue(e.org,n,{...vo(t),...t.removal?.removalStamps?{removalStamps:t.removal.removalStamps}:{},...t.removal?.removalSpans?{removalSpans:t.removal.removalSpans}:{},includeChanged:e.includeChanged,...e.runUserId?{runUserId:e.runUserId}:{},previewOnly:!0,...e.signal?{signal:e.signal}:{}}),planned:n.reduce((d,p)=>d+p.ids.length,0)}}async function Kn(e,t,n){let s=new Map,d=Object.entries(t.heldBefore??{});if(d.length===0||n.length===0)return s;let p=await ie(e)(),u=await se(e);for(let f of n){let k=Date.parse(xe(f)??""),E=Number.isFinite(k)?k+u+re:Number.NEGATIVE_INFINITY,O=new Set;for(let[A,{at:I,by:z}]of d)Date.parse(I)>E&&(p!==void 0&&z!==void 0&&z.slice(0,15)===p||O.add(A));O.size>0&&s.set(f.runId,O)}return s}function xe(e){return e.lastWriteAt??e.lastWrittenAt??e.end?.at}function Hn(e){return e.keptChanged+e.refused+e.notKept+(e.notReached??0)+(e.restoredWithout??0)}function Zn(e,t,n,s){if(!s||e==="cancelled")return e;if(s.cancelled)return"cancelled";let d=s.objects.some(u=>wo(u)>0);if(e==="success"&&!d)return"success";let p=t.some(u=>u.deleted>0)||(n?.objects??[]).some(u=>u.restored>0)||s.objects.some(u=>u.undeleted>0);return e==="partial"||p?"partial":"failure"}function Xn(e,t,n){if(!n||e==="cancelled")return e;if(n.cancelled)return"cancelled";let s=n.objects.some(p=>Hn(p)>0);return e==="success"&&!s?"success":t.some(p=>p.deleted>0)||n.objects.some(p=>p.restored+(p.restoredWithout??0)>0)?"partial":"failure"}function Bs(e){let t=e?.getSandforgeSetting?.("backup.maxAgeDays",30);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}function $s(e,t,n){let s=[],d=0,p=Number.POSITIVE_INFINITY;for(let u of e){let f=t(u.backup);if(!f){d+=u.ids.length;continue}s.push(u);let k=Date.parse(f.timestamp??"");n>0&&Number.isFinite(k)&&(p=Math.min(p,k+n*864e5))}return{kept:s,notKept:d,...Number.isFinite(p)?{keptUntil:new Date(p).toISOString()}:{}}}var Ye="backupSet:",Yn="backups",Ve=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Q=a().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/),$=g().int().nonnegative(),Vn=o({index:g().int().positive(),afterId:a().regex(Ve).optional(),lastId:a().regex(Ve).optional(),rows:$,snapshotId:a().min(1).max(240),takenAt:Q.optional(),readSince:Q.optional(),state:w(["pending","snapshotted","masking","masked","restored"]),masked:$,refused:$,deletedSince:$,nothingToMask:$,unanswered:$.optional(),late:v(!0).optional(),sizeUsed:g().int().positive(),lateLeft:$.optional(),lateOf:g().int().positive().optional(),lateAfterId:a().regex(Ve).optional(),restoredAt:Q.optional()}),Jn=o({objectApiName:a().min(1).max(255),where:a().max(2e3).optional(),select:a().max(1e5).optional(),done:r(),tailLeft:$.optional(),slices:c(Vn)}),Ao=o({setId:a().min(1).max(200),kind:w(["masking","backup"]),orgId:a().min(1).max(200),organizationId:a().max(18).optional(),templateId:a().min(1).max(200).optional(),fingerprint:a().regex(/^[0-9a-f]{64}$/).optional(),size:g().int().positive(),state:w(["open","done","abandoned"]),startedAt:Q,serverStartedAt:Q.optional(),lastActivityAt:Q,requestsSpent:$,keyCheck:a().regex(/^[0-9a-f]{16}$/).optional(),objects:c(Jn)});function Gs(e,t){return`${e}-s${String(t).padStart(4,"0")}`}function Ie(e){return e.objects.flatMap(t=>t.slices).sort((t,n)=>t.index-n.index)}function Ws(e){return Ie(e).reduce((t,n)=>Math.max(t,n.index),0)+1}function Co(e){return e.state==="masked"||e.state==="snapshotted"||e.state==="restored"}function Qn(e){return Ie(e).reduce((t,n)=>t+n.rows,0)}function To(e,t,n){return{index:t.index,objectApiName:e,snapshotId:t.snapshotId,rows:t.rows,masked:t.masked,refused:t.refused,deletedSince:t.deletedSince,nothingToMask:t.nothingToMask,state:t.state,...t.late?{late:!0}:{},...t.sizeUsed<n?{sizeUsed:t.sizeUsed}:{},...t.restoredAt?{restoredAt:t.restoredAt}:{}}}function ea(e){return e.objects.reduce((t,n)=>t+(n.tailLeft??0)+n.slices.reduce((s,d)=>s+(d.lateLeft??0),0),0)}function Ks(e,t){return{setId:e.setId,size:e.size,state:e.state,objects:e.objects.map(n=>({objectApiName:n.objectApiName,slices:n.slices.map(s=>To(n.objectApiName,s,e.size))})),lateRecords:ea(e),requestsSpent:t.requestsSpent,...t.stoppedOnBudget?{stoppedOnBudget:!0}:{},slicesLeft:e.objects.some(n=>!n.done||n.slices.some(s=>!Co(s)))}}function ta(e){return e.kind==="backup"&&e.state==="open"?"partial":e.state}function Hs(e){let t=Object.fromEntries(e.objects.flatMap(n=>n.where?[[n.objectApiName,n.where]]:[]));return{setId:e.setId,orgId:e.orgId,kind:e.kind,state:ta(e),startedAt:e.startedAt,lastActivityAt:e.lastActivityAt,size:e.size,totalRecords:Qn(e),...e.templateId?{templateId:e.templateId}:{},slices:e.objects.flatMap(n=>n.slices.map(s=>To(n.objectApiName,s,e.size))),...Object.keys(t).length>0?{wheres:t}:{}}}function Zs(e){let t=Ie(e);return{setId:e.setId,savedAt:e.lastActivityAt,done:t.filter(Co).length,total:t.length,state:e.state,size:e.size}}var Eo=class{constructor(t){this.configStore=t}configStore;get(t){let n=Ao.safeParse(this.configStore.get(this.key(t)));return n.success&&n.data.setId===t?n.data:void 0}save(t){this.configStore.set(this.key(t.setId),Ao.parse(t),Yn)}delete(t){this.configStore.delete(this.key(t))}list(t){return this.configStore.getKeysByPrefix(Ye).map(n=>this.get(n.slice(Ye.length))).filter(n=>n!==void 0).filter(n=>t===void 0||n.orgId===t)}openFor(t,n){return this.list(t).find(s=>s.kind==="masking"&&s.state==="open"&&s.templateId===n)}ofSnapshot(t){return this.list().find(n=>Ie(n).some(s=>s.snapshotId===t))}key(t){return`${Ye}${t}`}};async function Ys(e,t){let n=e.check(t);if(!n.allowed)return{check:n,decision:"refused"};if(!await e.confirmIfNeeded(n,t.orgTier))return{check:n,decision:"declined"};let d=n.requiresConfirmation&&e.canAskForConfirmation===!0;return{check:n,decision:d?"confirmed":"allowed"}}var _o={allowed:0,confirmed:1,declined:2,refused:3};function Vs(e,t){return e===void 0||_o[t]>_o[e]?t:e}export{sa as a,Qt as b,ca as c,qe as d,la as e,da as f,Bo as g,pa as h,ma as i,ua as j,ga as k,ba as l,fa as m,ya as n,eo as o,ha as p,za as q,Sa as r,xa as s,i as t,l as u,so as v,B as w,nn as x,an as y,Ke as z,Ea as A,Ca as B,Ta as C,_a as D,Na as E,Da as F,Fa as G,Ma as H,Ua as I,La as J,Ba as K,$a as L,qa as M,Ga as N,Wa as O,Ka as P,Ha as Q,Za as R,Xa as S,Ya as T,Va as U,Ja as V,Qa as W,er as X,tr as Y,or as Z,mn as _,nr as $,ar as aa,rr as ba,ir as ca,sr as da,cr as ea,lr as fa,dr as ga,pr as ha,mr as ia,ur as ja,gr as ka,br as la,fr as ma,yr as na,hr as oa,zr as pa,Sr as qa,xr as ra,Ir as sa,kr as ta,jr as ua,Pr as va,Or as wa,Rr as xa,wr as ya,vr as za,Ar as Aa,Er as Ba,Cr as Ca,Tr as Da,_r as Ea,fn as Fa,Nr as Ga,Dr as Ha,Fr as Ia,Mr as Ja,Ur as Ka,Lr as La,Br as Ma,$r as Na,qr as Oa,Gr as Pa,Wr as Qa,Kr as Ra,go as Sa,Hr as Ta,Zr as Ua,Xr as Va,bo as Wa,Yr as Xa,Vr as Ya,Jr as Za,Qr as _a,ti as $a,oi as ab,ni as bb,ai as cb,ri as db,ii as eb,si as fb,ci as gb,li as hb,di as ib,pi as jb,mi as kb,ui as lb,gi as mb,bi as nb,fi as ob,yi as pb,hi as qb,zi as rb,Si as sb,xi as tb,Ii as ub,ki as vb,ji as wb,Pi as xb,Oi as yb,Ri as zb,wi as Ab,vi as Bb,Ai as Cb,Ei as Db,Ci as Eb,Ti as Fb,_i as Gb,Ni as Hb,Di as Ib,Fi as Jb,Mi as Kb,Ui as Lb,Li as Mb,Bi as Nb,$i as Ob,qi as Pb,Gi as Qb,Wi as Rb,Ki as Sb,Hi as Tb,Zi as Ub,Xi as Vb,Yi as Wb,Vi as Xb,Ji as Yb,Qi as Zb,es as _b,ts as $b,os as ac,ns as bc,as as cc,rs as dc,is as ec,ss as fc,cs as gc,ls as hc,ds as ic,Fn as jc,Mn as kc,us as lc,gs as mc,bs as nc,fs as oc,ys as pc,hs as qc,zs as rc,Ss as sc,xs as tc,Is as uc,Ln as vc,ks as wc,Ro as xc,Ms as yc,Us as zc,xe as Ac,Zn as Bc,Xn as Cc,Ys as Dc,Vs as Ec,Bs as Fc,$s as Gc,Gs as Hc,Ie as Ic,Ws as Jc,Co as Kc,ea as Lc,Ks as Mc,ta as Nc,Hs as Oc,Zs as Pc,Eo as Qc};
|
|
7
|
+
import{b as ie,c as se,d as Vt,e as Jt,f as be}from"./chunk-L53JWJ3S.mjs";import{a as Zt,e as Xt}from"./chunk-VINGECAJ.mjs";import{I as re,O as Ue,a as Kt}from"./chunk-H4CGM6YO.mjs";import{f as Le,p as ge,s as Be,u as Yt,w as $e}from"./chunk-PMN4PAC3.mjs";import{b as me,d as ue}from"./chunk-JAEDM4SI.mjs";import{c as qt}from"./chunk-MSIEU5MR.mjs";import{G as Ht}from"./chunk-YA6ATMTB.mjs";import{c as Wt}from"./chunk-M6K34KGF.mjs";import{c as Gt,e as Fe,g as Me,h as pe}from"./chunk-TZE3Y7IQ.mjs";import{a as $t,b as V}from"./chunk-CA5NAXSU.mjs";import{C as dt,D as pt,E as mt,Ea as zt,F as ut,Fa as St,J as gt,K as bt,Ka as ae,L as ft,La as Ae,M as yt,N as ht,Pa as M,Qa as xt,Ra as F,Sa as Ee,Sb as Rt,Ta as It,Ua as kt,Va as Ce,Wa as Te,Xa as _e,cb as Ne,dd as Nt,fb as jt,gb as Pt,hb as Ot,hc as wt,jc as vt,kc as At,n as rt,nc as Et,nd as Dt,oc as Ct,od as Ft,pc as Tt,pd as Mt,qe as Lt,rd as Ut,re as Bt,s as we,sd as De,t as it,u as st,v as ct,w as ne,wc as _t,y as lt,z as ve}from"./chunk-PMWAFDUB.mjs";import{b as a,c as Oe,e as g,f as r,g as et,i as D,k as c,l as o,m as tt,o as de,p as Re,s as x,u as w,v,w as ot,x as nt,y as G,z as at}from"./chunk-WZQEK4WT.mjs";function sa(e,t,n){return async s=>{let d=s.map(f=>`${f.objectApiName} (${f.records})`).join(", ");e.log(`[WARN] ${n}: the user may not delete ${d} in the target: those records stay`);let p=e.infraServices?.confirmRemovalLeavingUndeletable;if(!p)return!0;let u=e.orgManager.getOrg(t);return p({org:Nt(u,t),objects:s})}}var Qt={code:"NOT_INITIALIZED",message:"Production Guard is not initialized \u2014 infrastructure services missing"};function ca(){return Object.assign(new Error(Qt.message),{code:Qt.code})}var qe={blocked:"GUARD_BLOCKED",declined:"GUARD_DECLINED"};function la(e){return Object.assign(new Error(`Operation blocked by Production Guard: ${e}`),{code:qe.blocked})}function da(e){return e instanceof Error&&e.code===qe.blocked?qe.blocked:void 0}function Bo(e){return e.robustness??zt}function pa(e){return e.bulkManager??new Kt(Bo(e).bulk.maxConcurrentJobs)}var $o={"sync:schedule":"sync:schedule:","sync:pipeline":"sync:pipeline:","seed:pipeline":"seed:pipeline:","offline-replay":"offline-replay-"};function ma(e,t,n){return{id:`${$o[e]}${t}`,type:n,timestamp:Date.now()}}function ua(e,t,n,s){return{id:e.nextId(),type:n,timestamp:Date.now(),correlationId:t.id,payload:s}}function ga(e,t,n,s,d={}){let p=t==="error"?null:d.autoDismissMs===void 0?5e3:d.autoDismissMs,u={id:e.nextId(),type:"notification",timestamp:Date.now(),payload:{level:t,title:n,message:s,...p===null?{}:{autoDismissMs:p},...d.actions?{actions:d.actions}:{},...d.code?{code:d.code}:{}}};e.broker.postToWebview(u),e.log(`[TX] notification: ${n}`)}function ba(e,t,n,s){let d={id:e.nextId(),type:"operation:started",timestamp:Date.now(),payload:{operationId:t,module:n,description:s}};e.broker.postToWebview(d)}function fa(e,t,n,s,d,p){let u={id:e.nextId(),type:"operation:progress",timestamp:Date.now(),payload:{operationId:t,percentage:n,processedRecords:s,totalRecords:d,currentStep:p}};e.broker.postToWebview(u)}function ya(e,t,n){let s={id:e.nextId(),type:"operation:completed",timestamp:Date.now(),payload:{operationId:t,result:n}};e.broker.postToWebview(s)}var qo=Symbol("sandforge.uncorrelated");function eo(e,t,n,s,d,p={}){let u=V(d),f=d instanceof qt?d:void 0,k=qo in s,E=p.code??f?.code??"UNKNOWN";k||Ko(e.broker,u,E),e.log(`[ERR] ${t}: ${u}${k?` (uncorrelated: ${String(s.reason)})`:""}`);let O={id:e.nextId(),type:n,timestamp:Date.now(),...k?{}:{correlationId:s.id},payload:{message:u,code:E,retryable:p.retryable??!1,...f?{orgId:f.orgId}:{},...p.extraPayload}};e.broker.postToWebview(O),e.log(`[TX] ${n}: ${u}`)}function ha(e,t){let n={id:e.nextId(),type:t.type,timestamp:Date.now(),payload:t.payload};e.broker.postToWebview(n)}function za(e){let t=e?.getSandforgeSetting;if(!(!t||!t("grappe.enabled",!1)))return{enabled:!0,autoActivateThreshold:t("grappe.autoActivateThreshold",1e4),maxWorkers:rt.maxWorkers,grappeSize:t("grappe.grappeSize",5e3),strategy:"round_robin",backPressure:{enabled:!1,maxQueueDepth:3,highWaterMark:80,lowWaterMark:60,strategy:"pause",monitoringInterval:5e3},checkpointing:!0,isolationLevel:"per_grappe"}}function Sa(e){let t=new Set(e.map(s=>s.batchSize)),[n]=t;return{...e.length>0?{objectName:e.map(s=>s.objectApiName).join(", ")}:{},...t.size===1&&n!==void 0?{batchSize:n}:{}}}function xa(e,t,n,s,d={}){let p={id:e.nextId(),type:"operation:failed",timestamp:Date.now(),payload:{operationId:t,error:n,retryable:s,...d.extraPayload}};e.broker.postToWebview(p),d.authored!==!0&&Zo(e,n,d.context)}var Go=[/^Operation cancelled by user\b/,/^Operation blocked by Production Guard: /,/^Production Guard is not initialized\b/,/^Duplicate operation: /,/^A backup or rollback operation is already running for org /,/^Object describe not available for '/,/^CRUD_FLS_DENIED: /,/^CRUD\/FLS check failed for /,/^No backup found for operation /,/^Backup \S+ was taken from org /,/^Restore not run: /,/^Pipeline failed$/,/^Pipeline did not start: /,/^Pipeline ran out of time: /,/^Org not found: /,/^No credentials for org /,/^Invalid username format: /];function Wo(e){return Go.some(t=>t.test(e))}var to=1e4,Ge=new WeakMap;function Ko(e,t,n){let s=De(t,{code:n});if(!s?.actionKey)return;let d=Ge.get(e)??new Map,p=Date.now();for(let[u,f]of d)p-f>to&&d.delete(u);d.set(s.code,p),Ge.set(e,d)}function Ho(e,t){let n=Ge.get(e)?.get(t);return n!==void 0&&Date.now()-n<=to}function Zo(e,t,n={}){if(!(e.broker.panelCount>0)||Wo(t))return;let d=$t(t,Ut)??"UNKNOWN",p=De(t,{code:d});if(p?.actionKey){if(Ho(e.broker,p.code))return;e.broker.showFixSuggestion({source:"catalogue",code:p.code,actionKey:p.actionKey});return}let u=e.errorResolver;u&&u.resolveError({errorCode:d,message:t},n).then(f=>{e.broker.showFixSuggestion({source:"model",text:Xo(f)})}).catch(f=>{e.log?.(`[ERR] operation:failed resolution: ${V(f)}`)})}function Xo(e){return e.suggestions[0]?.description||e.explanation}import{isAbsolute as tn}from"node:path";var i=a().min(1).max(128),l=a().regex(/^[A-Za-z][A-Za-z0-9_]*$/,"Invalid Salesforce API name").max(80),so=c(l).max(300),m=a().min(1).max(200),J=a().max(2e3).refine(Fe,{message:Me}),on=a().refine(Gt,{message:"ORDER BY clause must list only field names with optional ASC/DESC and NULLS FIRST/LAST (no LIMIT, OFFSET, FOR UPDATE or subquery)."}),y=100,co=1e4,B=o({keepDays:g().int().min(ve.min).max(ve.max).optional(),excluded:c(l).max(y).refine(e=>new Set(e).size===e.length,"An object is left out twice").optional()}).strict(),he={sweepLate:r().optional(),sweepUntied:r().optional()};function nn(e){return Wt(e)}function an(e,t='turn on "Copy the files of these records"'){return _t(e)?`Sync copies files with the records they hang on, not as an object of their own: "${e}" keeps its content in a file body. Remove it from this configuration and ${t} instead; the sync was not started.`:`Sync does not copy "${e}": no copy writes it \u2014 users and their access, metadata, a record's history, feed or sharing rows, and the records the platform keeps for itself are not data a copy carries. Remove it from this configuration; the sync was not started.`}var rn=w(gt,{error:e=>e.input==="manual"?"Manual conflict review is not available for a sync run: no run shows its conflicts to anyone before it writes. Pick source wins, target wins, newest wins or merge \u2014 target wins keeps every value the target holds where the two orgs differ. The sync was not started.":`Conflict strategy "${String(e.input)}" is not one a sync run acts on: pick source wins, target wins, newest wins or merge. The sync was not started.`}),sn=bt.extend({objectApiName:l.refine(e=>!nn(e),{error:e=>an(String(e.input))}),externalIdField:nt(e=>typeof e=="string"&&e.trim()===""?void 0:e,l.optional()),where:J.optional(),orderBy:on.optional(),batchSize:g().int().positive().max(co).optional()}).strip().refine(e=>e.operation!=="upsert"||(e.externalIdField??"Id").toLowerCase()!=="id",{path:["externalIdField"],error:e=>`An upsert of "${String(e.input.objectApiName)}" needs an External ID field: matching on Id cannot work, because the id belongs to the source org and the target has never issued it. Name an External ID field both orgs share, or set the operation to insert. The sync was not started.`}).superRefine((e,t)=>{let n=Ft([e]);n.length!==0&&t.addIssue({code:G.custom,message:`${Mt(n)} The sync was not started.`,params:{unreadablePatterns:n}})});function oo(e){return et({error:()=>`Sync does not run Apex: remove "${e}" from this configuration. The sync was not started so the script cannot be skipped without you knowing.`}).optional()}var Ke=ft.extend({id:m.optional(),sourceOrgId:i,targetOrgId:i,objects:c(sn).min(1).max(y),conflictStrategy:rn,createdAt:a().max(40).optional(),updatedAt:a().max(40).optional(),preScript:oo("preScript"),postScript:oo("postScript"),dryRun:v(!1,{error:()=>'A sync configuration cannot ask for a dry run: remove "dryRun" from it. A run of it writes to the target org; to see what it would write, simulate it from the Sync page. The run was not started, so it cannot write while you believed it was only reporting.'}).optional()}).strip().superRefine((e,t)=>{e.direction==="target_to_source"&&t.addIssue({code:G.custom,path:["direction"],message:'Sync writes source to target only: direction "target_to_source" is not supported. Swap the source and target orgs to copy the other way. The sync was not started, so it cannot write into the org you meant to read from.'}),e.mode!=="full"&&e.mode!=="delta"&&t.addIssue({code:G.custom,path:["mode"],message:`Sync runs a full or a delta sync only: mode "${e.mode}" is not implemented. Set mode to "full" or "delta". The sync was not started, so it cannot replay the whole object set while you believed it was reading changes only.`}),e.mode==="delta"&&e.objects.forEach((n,s)=>{n.operation==="upsert"||n.operation==="update"||t.addIssue({code:G.custom,path:["objects",s,"operation"],message:`A delta sync writes ${n.objectApiName} again for every record it reads twice, and ${n.operation} would ${n.operation==="insert"?"create a second copy":"delete a record already gone"}. Write it by upsert on an External ID, or by update, or run the configuration in full. The sync was not started.`})}),e.propagateDeletes===!0&&(e.mode!=="delta"?t.addIssue({code:G.custom,path:["propagateDeletes"],message:'Deletions are carried by a delta sync only, which knows since when to look for them: set mode to "delta", or turn deletions off. The sync was not started.'}):e.objects.forEach((n,s)=>{if(n.operation!=="upsert"&&n.operation!=="update")return;let d=Ht(n);"refused"in d&&t.addIssue({code:G.custom,path:["objects",s],message:`${d.refused} Turn deletions off, or carry a source field onto the key. The sync was not started.`})}))}),Ea=o({suggestedName:a().min(1).max(255).refine(e=>!e.includes("/")&&!e.includes("\\"),"suggestedName must not contain a path"),content:a().max(32*1024*1024),extensions:c(a().regex(/^[A-Za-z0-9]+$/)).max(8).optional()}),Ca=o({config:Ke,muteAutomation:r().optional(),checkpointFirst:B.optional()}),Ta=o({config:Ke,checkpointFirst:B.optional()}),_a=o({operationId:m}),Na=o({config:Ke}),Da=o({id:m}),Fa=o({orgId:i,targetOrgId:i.optional()}),Ma=o({sourceOrgId:i,targetOrgId:i,objectApiName:l}),lo=w(["source_wins","target_wins","newest_wins","manual","merge"]),cn=Re("kind",[o({kind:v("id")}),o({kind:v("externalId"),field:l}),o({kind:v("syncConfig"),configId:m})]),Ua=o({sourceOrgId:i,targetOrgId:i,watchedObjects:c(l).min(1).max(y),apply:c(o({objectApiName:l,match:cn,applyDeletes:r()})).max(y),conflictStrategy:lo,flushIntervalMs:g().int().min(50).max(6e4),maxBatchSize:g().int().min(1).max(200),keepContactPoints:r().optional()}).refine(e=>e.apply.every(t=>e.watchedObjects.includes(t.objectApiName)),{message:"Every applied object must be watched.",path:["apply"]}),La=o({sessionId:a().max(200)}),Ba=o({sourceOrgId:i,targetOrgId:i}),$a=o({conflictId:a().min(1).max(500),eventReplayId:g().optional(),resolution:lo,fieldResolutions:x(a(),o({value:D(),source:w(["source","target","manual"])})).optional()}),qa=o({entryId:m}),Ga=o({runId:m}),Wa=o({realtime:v(!0).optional()}).optional(),Ka=o({sourceOrgId:i,targetOrgId:i,objects:c(l).max(y),configId:m.optional()}),Ha=o({runId:m,includeChanged:r().optional(),sweep:r().optional(),again:r().optional(),muteAutomation:r().optional(),...he}),Za=o({runId:m}),Xa=o({runId:m,again:r().optional(),sweptObjects:so.optional()}),Ya=o({runId:m}),Va=o({runId:m,includeChanged:r().optional(),sweep:r().optional(),again:r().optional(),muteAutomation:r().optional(),...he}),Ja=o({runId:m}),Qa=o({format:w(["csv","json"]),entryIds:c(m).max(500).optional()}),ln=o({id:m,name:a().min(1).max(200),configId:m,cron:a().min(1).max(100),timezone:a().min(1).max(100),enabled:r(),maxRetries:g().int().min(0).max(10),notifyOnComplete:r(),notifyOnFailure:r(),createdAt:a().max(40),updatedAt:a().max(40),version:g().int().positive()}).strip(),er=o({schedule:ln}),tr=o({scheduleId:m,enabled:r()}),or=o({scheduleId:m}),dn=dt.extend({objectApiName:l,recordCount:g().int().positive().max(ne),batchSize:g().int().positive().max(co).optional()}).loose(),pn=pt.extend({childObject:l,lookupField:l,parentObject:l}).superRefine((e,t)=>{e.parents.kind==="existing"&&e.parents.where!==void 0&&!Fe(e.parents.where)&&t.addIssue({code:G.custom,path:["parents","where"],message:Me})}),mn=mt.extend({objects:c(dn).min(1).max(y),relations:c(pn).max(y).optional()}).loose().superRefine(ut),nr=o({orgId:i,template:mn,muteAutomation:r().optional(),checkpointFirst:B.optional(),fit:o({share:g().gt(0).max(1),withinMB:g().positive().max(1e6).optional(),before:g().int().positive().max(ne*y)}).strict().optional(),locale:a().regex(/^[a-z]{2,3}(?:_[A-Za-z0-9]{2,4}){0,2}$/).optional(),dryRun:r().optional()}),ar=o({orgId:i}),rr=o({orgId:i,objects:c(l).min(1).max(y),publishes:r().optional()}).strict(),ir=o({orgId:i,objectApiName:l}),sr=o({id:m}),cr=o({template:x(a(),D())}),lr=o({description:a().max(1e4)}),dr=o({}).strict(),pr=o({orgId:i,pack:ae,seed:Ae.shape.seed,articleBodyField:l.optional()}).strict(),mr=o({orgId:i,pack:ae,options:Ae,locale:a().regex(/^[a-z]{2,3}(?:_[A-Za-z0-9]{2,4}){0,2}$/).optional(),muteAutomation:r().optional(),checkpointFirst:B.optional()}).strict(),ur=o({orgId:i}).strict(),gr=o({pack:ae,overwrite:r().optional()}).strict(),br=o({runId:m,choice:Rt,overwrite:r().optional()}).strict(),un=131072,gn=o({objectApiName:l,whereClause:J.optional()}).loose(),fr=o({sourceOrgId:i}),yr=o({sourceOrgId:i,targetOrgId:i,objects:c(gn).min(1).max(y),upsert:r().optional(),externalIdField:l.optional(),previewId:m.optional(),keepContactPoints:r().optional(),checkpointFirst:B.optional()}).refine(e=>!e.upsert||e.externalIdField!==void 0,{message:"externalIdField is required when upsert is true",path:["externalIdField"]}),bn=o({csvHeader:a().min(1).max(500),sfFieldApiName:a().max(80),sfFieldType:a().max(40),sfFieldLength:g().int().positive().nullable()}).loose(),hr=o({orgId:i,objectApiName:l,records:c(x(a(),a().max(un))).min(1).max(st),columnMappings:c(bn).min(1).max(ct),externalIdField:l.optional(),checkpointFirst:B.optional()}),zr=o({orgId:i,objects:c(l).min(1).max(y),wheres:x(l,J).optional(),slices:r().optional()}).refine(e=>Object.keys(e.wheres??{}).every(t=>e.objects.some(n=>n.toLowerCase()===t.toLowerCase())),{message:"A filter names an object the backup reads: give it in objects",path:["wheres"]}),Sr=o({orgId:i}),xr=o({orgId:i,templateId:a().min(1).max(200).optional()}),Ir=o({orgId:i,operationId:a().min(1).max(200)}),kr=o({orgId:i,operationIds:c(a().min(1).max(200)).min(1).max(1e3).optional()}),W={acceptAutomation:r().optional(),acceptEmails:r().optional(),muteAutomation:r().optional()},X={fromPage:v(!0).optional()},jr=o({orgId:i,operationId:m,rewriteAll:r().optional(),includeChanged:r().optional(),slices:c(g().int().positive()).min(1).max(lt*y).optional(),...W,...X}),Pr=o({orgId:i,act:w(["masking","restore","cleanup"]),objects:c(o({objectApiName:l,records:g().int().min(0)})).max(y),erasure:r().optional(),...W,...X}),He={objects:c(l).min(1).max(y).optional(),where:J.optional()},Ze=e=>e.where===void 0||e.where.trim()===""||e.objects?.length===1,Xe={message:"A WHERE clause filters the rows of one object: name exactly one in objects",path:["where"]},Or=o({orgId:i,templateId:m,...He,resumeFrom:m.optional(),snapshot:r().optional(),slices:r().optional(),maxRequests:g().int().positive().max(1e9).optional(),abandon:r().optional(),...W,...X}).refine(Ze,Xe).refine(e=>!(e.snapshot===!0&&e.resumeFrom!==void 0&&e.slices!==!0),{message:"A resume takes no snapshot: the run it resumes has written over some of its rows",path:["snapshot"]}).refine(e=>!(e.slices===!0&&e.snapshot===!1),{message:"A run in slices backs each slice up before it masks it: it cannot keep no snapshot",path:["slices"]}).refine(e=>e.maxRequests===void 0||e.slices===!0,{message:"A bound on requests stops a run in slices between two of them: give slices too",path:["maxRequests"]}).refine(e=>e.abandon!==!0||e.resumeFrom===void 0&&e.snapshot!==!0&&e.maxRequests===void 0,{message:"Giving up a set of slices masks nothing: it takes no resume, snapshot or bound",path:["abandon"]}),Rr=o({orgId:i,templateId:m,...He,slices:r().optional()}).refine(Ze,Xe),wr=o({orgId:i,templateId:m,...He}).refine(Ze,Xe),vr=o({name:a().trim().min(1).max(jt),rules:c(Ot).min(1).max(Pt).refine(e=>new Set(e.map(t=>t.fieldPattern.toLowerCase())).size===e.length,"A field has two rules")}),Ar=o({templateId:m}),Er=o({orgId:i,objectNames:c(l).min(1).max(y)}),Cr=o({orgId:i,objects:c(o({objectApiName:l,duplicateKey:l.optional()})).min(1).max(10).refine(e=>new Set(e.map(t=>t.objectApiName.toLowerCase())).size===e.length,{message:"Each object may be named once per scan"}),staleDays:g().int().min(1).max(3650)}),po=c(l).min(1).max(10).refine(e=>new Set(e.map(t=>t.toLowerCase())).size===e.length,{message:"Each object may be named once per request"}),Tr=o({orgId:i,objects:po}),_r=o({orgId:i,objects:po,requestId:Oe().optional(),email:a().trim().refine(Ct,"Not an email address").optional(),name:a().refine(Tt,"Not a name").optional(),phone:a().refine(Et,"Not a phone number").optional()}).refine(e=>e.email!==void 0||e.name!==void 0||e.phone!==void 0,{message:"A search needs an email address, a name or a phone number"}),fn=o({orgId:i,requestId:Oe()}),ze=a().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record Id"),Nr=o({runId:m,recordId:ze}).strict(),Dr=fn.extend({mode:w(["anonymize","delete"]),records:c(o({objectApiName:l,ids:c(ze).min(1).max(200)})).min(1).max(10).refine(e=>new Set(e.map(t=>t.objectApiName.toLowerCase())).size===e.length,{message:"Each object may be named once per request"}),dryRun:r(),...W}),yn=Re("kind",[o({kind:v("stale"),days:g().int().min(1).max(3650)}),o({kind:v("orphans"),fieldApiName:l}),o({kind:v("duplicates"),keyField:l})]),mo=o({orgId:i,objectApiName:l,recommendation:yn}),Fr=mo.extend({after:o({skip:g().int().nonnegative().max(1e8),id:ze.optional(),modified:a().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:?\d{2})$/).optional()}).strict().optional()}),Mr=mo.extend({dryRun:r(),...W,...X}),We=2e3,uo={mode:w(["objects","org"]),objects:c(l).min(1).max(We).optional(),excluded:c(l).max(We).optional(),customSettings:r().optional(),files:r().optional(),managedPackages:r().optional(),unrestorable:r().optional()},hn=o(uo).strict().refine(e=>e.mode==="objects"==(e.objects!==void 0),{message:"The objects picked are named in objects mode, and only there"}),Ur=o({orgId:i,...uo,objects:c(l).max(We).optional()}).strict().refine(e=>e.mode==="objects"==(e.objects!==void 0),{message:"The objects picked are named in objects mode, and only there"}),Lr=o({orgId:i,request:hn,deleteMode:w(["recycle","hard"]),checkpointFirst:r().optional(),acceptNoUndo:r().optional(),acceptPeopleActive:r().optional(),...W,...X}),Br=o({orgId:i,previewId:m.optional(),resumeRunId:a().regex(/^em-\d{8}-\d{6}-[a-z0-9]{4}$/).optional(),acceptNoUndo:r().optional(),acceptPeopleActive:r().optional(),checkpointFirst:r().optional(),...W,...X}).refine(e=>e.previewId===void 0!=(e.resumeRunId===void 0),{message:"An emptying acts on a simulation, or takes up a run: one of them"}),$r=o({operationId:m}),qr=o({orgId:i,runId:a().regex(/^em-\d{8}-\d{6}-[a-z0-9]{4}$/),...W,...X}),Gr=o({orgId:i}),Wr=o({orgId:i}).strict(),Kr=o({alertId:m}),go=o({sourceOrgId:i,targetOrgId:i}),Hr=go.extend({types:c(a().min(1).max(80)).min(1).max(50),includeManaged:r().optional()}),zn=o({componentType:w(At),fullName:a().min(1).max(400).regex(/^[^\u0000-\u001f\u007f]+$/,"A component name holds no control character")}),Zr=go.extend({components:c(zn).min(1).max(500).refine(e=>new Set(e.map(t=>`${t.componentType}:${t.fullName}`)).size===e.length,{message:"Each component may be named once per deployment"}),testLevel:w(wt),runTests:c(a().max(255).regex(vt,"Not an Apex class name")).max(100).optional()}).refine(e=>e.sourceOrgId!==e.targetOrgId,{message:"The source and the target are the same org",path:["targetOrgId"]}).refine(e=>e.testLevel!=="RunSpecifiedTests"||(e.runTests?.length??0)>0,{message:"RunSpecifiedTests names at least one test class",path:["runTests"]}),Xr=o({validationId:a().regex(/^0Af[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/,"Not a deployment id"),targetOrgId:i}).strict(),Sn=a().regex(/^\d+\.\d+\.\d+$/,"Invalid semver"),ye=a().regex(/^[A-Za-z][A-Za-z0-9_]*\.[A-Za-z][A-Za-z0-9_]*$/,"Expected an Object.field key").max(170),xn=o({name:a().min(1).max(80),label:a().min(1).max(200),filterField:l,valuesSoql:a().min(1).max(4e3)}),In=o({name:a().min(1).max(80),label:a().min(1).max(200),whereFragment:J}),no=de([o({action:v("clear")}),o({action:v("replace"),value:a().max(255)})]),bo=o({rootObject:l,axes:c(xn).max(20),edgeCases:c(In).max(50),budgetMaxRecords:g().int().positive().max(1e5).optional(),candidatesPerCombination:g().int().positive().max(20).optional(),expectedObjects:c(l).max(100).optional(),maxNodes:g().int().min(10).max(500).optional(),excludedObjects:c(l).max(200).optional(),excludedFields:x(l,c(l).max(500)).optional(),sasDir:a().min(1).max(500).optional(),datasetDir:a().min(1).max(500).optional(),rulesFilePath:a().min(1).max(500).optional(),datasetVersion:Sn.optional(),protectedOrgIds:c(i).max(50).optional(),identityKeys:x(l,c(l).min(1).max(10)).optional(),undeletableObjects:x(l,l).optional(),requiredLookupPlaceholders:x(ye,o({name:a().min(1).max(200),recordTypeDeveloperName:a().min(1).max(97).optional(),targetObjectApiName:l.optional()})).optional(),requiredFieldDefaults:x(ye,D()).optional(),picklistRules:x(ye,no).optional(),defaultPicklistRule:no.optional(),duplicateErrorPatterns:c(a().min(1).max(200)).max(50).optional(),mockDetection:o({metadataTypeApiName:l,isMockedFieldApiName:l}).optional(),mandatoryLookups:x(l,c(l).min(1).max(50)).optional(),presenceKeys:x(l,l).optional()}),Yr=o({config:bo}),Vr=o({sourceOrgId:i}),Jr=o({fields:c(ye).min(1).max(2e3)}),Qr=o({sourceOrgId:i,author:a().min(1).max(120).optional()}),ce=o({organizationId:kt,checkpointId:F}).strict(),kn=bo.pick({requiredFieldDefaults:!0,requiredLookupPlaceholders:!0,picklistRules:!0,defaultPicklistRule:!0,identityKeys:!0,undeletableObjects:!0,duplicateErrorPatterns:!0,mockDetection:!0,protectedOrgIds:!0}).strict(),fo=ce.extend({choices:Ne,config:kn.optional(),confirmStaging:a().min(1).max(255).optional()}).strict(),jn=fo.extend({choices:Ne.optional()}).strict(),ti=o({targetOrgId:i,replay:fo.optional(),pilot:r().optional(),reload:r().optional(),writeEncrypted:r().optional(),maxRecords:g().int().positive().max(1e6).optional(),muteAutomation:r().optional(),checkpointFirst:B.optional(),sweep:r().optional(),...he,includeChanged:r().optional(),acceptEmails:r().optional(),acceptAutomation:r().optional(),goneFirst:c(ze).max(1e6).optional()}),Pn=o({targetOrgId:i}),oi=Pn.extend({replay:jn.optional()}),ni=o({targetOrgId:i,loadedAt:a().min(1).max(64),includeChanged:r().optional(),sweep:r().optional(),...he,muteAutomation:r().optional(),replay:ce.optional()}),ai=o({targetOrgId:i,loadedAt:a().min(1).max(64),reload:r().optional(),replay:ce.optional()}),ri=o({targetOrgId:i,loadedAt:a().min(1).max(64),sweptObjects:so.optional(),reload:r().optional(),replay:ce.optional()}),ii=o({targetOrgId:i,loadedAt:a().min(1).max(64),includeChanged:r().optional(),replay:ce.optional()}),yo=1e3,ho=3650,On=200,Z=c(l).min(1).max(yo).refine(e=>new Set(e).size===e.length,"An object is named twice");function zo(e){return e.mode==="picked"?e.objects!==void 0:e.objects===void 0}var So=de([v("all"),c(l.refine(e=>e.toLowerCase().endsWith("__c"),"A custom setting's API name ends in __c")).min(1).max(yo).refine(e=>new Set(e.map(t=>t.toLowerCase())).size===e.length,"A custom setting is named twice")]),xo={path:["objects"],message:'Name the objects with "picked", and none with "everything"'},si=o({orgId:i.optional()}).optional(),Rn=1e6,Io=g().int().min(1).max(Rn),ci=o({orgId:i,mode:_e,objects:Z.optional(),excluded:Z.optional(),customSettings:So.optional(),maxTotal:Io.optional()}).refine(zo,xo),li=o({orgId:i,name:Te,mode:_e,objects:Z.optional(),excluded:Z.optional(),customSettings:So.optional(),maxTotal:Io.optional(),keepDays:g().int().min(0).max(ho),ignoredFields:Ce.optional()}).refine(zo,xo),di=o({checkpointId:F,objects:Z.optional(),muteAutomation:r().optional(),acceptOutside:r().optional()}),pi=o({checkpointId:F,previewId:Ee,objects:Z.optional(),acceptAutomation:r(),muteAutomation:r().optional(),acceptEmails:r().optional(),acceptNoUndo:r(),acceptRecreate:r(),acceptOutside:r(),acceptUnseen:r(),fromPage:v(!0).optional()}),mi=o({checkpointId:F,previewId:Ee,objects:Z,acceptOutside:r()}),ui=o({checkpointId:F}),wn=200,gi=o({token:m,orgId:i,key:a().min(1).max(wn),keepDays:g().int().min(0).max(ho)}),bi=o({checkpointId:F,rewindId:It,acceptAutomation:r(),muteAutomation:r().optional(),acceptEmails:r().optional(),fromPage:v(!0).optional()}),fi=o({checkpointIds:c(F).min(1).max(On).refine(e=>new Set(e).size===e.length,"A checkpoint is named twice")}),yi=o({checkpointId:F,keep:r()}),hi=o({checkpointId:F,name:Te}),zi=o({checkpointId:F,fields:Ce}),vn=500,Si=o({orgIds:c(i).min(1).max(vn).refine(e=>new Set(e).size===e.length,"An org is named twice").optional()}).strict().optional(),xi=o({sourceOrgId:i,targetOrgId:i,includeStandardObjects:r()}),Ii=o({sourceOrgId:i,objectApiNames:c(l).min(1).max(it)}),ki=o({sourceOrgId:i,targetOrgId:i,selectedObjects:c(l).max(y),includeStandardObjects:r(),maxDepth:g().int().min(1).max(10).optional(),maxObjects:g().int().min(1).max(500).optional()}),ji=o({complianceFramework:ht,objectFilters:x(a(),J).optional(),overrides:c(o({objectApiName:l,fieldApiName:l,method:de([yt,v("skip")])})).max(500).optional()}),Pi=o({grappeThreshold:g().int().nonnegative(),keepContactPoints:r().optional(),muteAutomation:r().optional(),checkpointFirst:B.optional()}),Oi=o({mode:o({share:v(!0).optional(),caps:x(l,g().int().min(1).max(ne)).refine(e=>Object.keys(e).length<=y,"Too many caps").optional(),all:g().int().min(1).max(ne).optional(),withinMB:g().positive().max(1e6).optional()}).strict().refine(e=>e.share===!0||e.caps!==void 0||e.all!==void 0,"Fit by share, by caps, or both"),muteAutomation:r().optional(),checkpointFirst:B.optional()}),Ri=o({objectApiName:l}),wi=o({orgId:i.optional(),sourceOrgId:i.optional(),alreadySelected:c(l).max(y).optional()}).loose(),vi=o({orgId:i.optional(),sourceOrgId:i.optional(),objectApiName:l.optional(),alreadySelected:c(l).max(y).optional(),selectedObjects:c(l).max(y).optional(),availableObjects:c(l).max(500).optional()}).loose(),Ai=o({sourceOrgId:i,targetOrgId:i.optional(),selectedObjects:c(l).min(1).max(y),parentObjects:c(l).max(y).optional()}).loose(),An=St.extend({sourceOrgId:i,targetOrgId:i,selectedObjects:c(l).min(1).max(y),parentObjects:c(l).max(y).default([])}).loose(),Ei=o({config:An.optional(),sourceOrgId:i.optional(),targetOrgId:i.optional(),selectedObjects:c(l).min(1).max(y).optional(),parentObjects:c(l).max(y).optional()}).loose(),En=a().min(1).max(5e4),Ci=o({conversationId:m,message:a().max(5e4)}),Ti=o({title:a().min(1).max(300)}),_i=o({conversationId:m}),Ni=o({apiKey:a().min(1).max(500),errorResolution:r().optional()}),Di=o({enabled:r().optional(),errorResolution:r().optional()}),Fi=o({orgId:i,objectName:l,sampleSize:g().int().positive().max(1e4).optional()}),Mi=o({orgId:i,prompt:a().trim().min(1).max(2e3).optional(),soql:a().trim().min(1).max(2e4).optional()}).refine(e=>e.prompt===void 0!=(e.soql===void 0),{message:"Send a prompt to draft from or a query to check, not both and not neither"}),Ui=o({description:En,orgIds:c(i).max(50).optional()}),Li=o({requestId:m}),fe=c(a().min(1).max(M.picklistValue)).max(M.picklistValues),ao={label:a().max(M.agentLabel).optional(),description:a().max(M.agentDescription).optional()},Bi=o({text:a().trim().min(1).max(M.text),language:ae.shape.language,casePicklists:o({Status:fe.optional(),Origin:fe.optional(),Priority:fe.optional(),Type:fe.optional()}).optional(),agent:o({topics:c(o({name:a().min(1).max(M.agentName),...ao,actions:c(o({name:a().min(1).max(M.agentName),...ao})).max(M.agentActions)})).max(M.agentTopics)}).optional(),draft:xt.optional(),maskOnly:r().optional()}),$i=o({filePath:a().min(1).max(2e3)}),qi=o({name:a().max(200),config:x(a(),D())}),Gi=o({operationId:m.optional(),executionId:m.optional(),objectName:a().min(1).max(200).optional()}).loose(),Wi=o({policyId:m}),Ki=o({policy:x(a(),D())}),Hi=o({policyId:m,orgId:i}),Zi=o({module:a().min(1).max(50).optional(),orgId:i.optional(),offset:g().int().min(0).max(we).optional(),limit:g().int().min(1).max(we).optional()}).optional(),Xi=o({operationId:m.optional()}).optional(),Cn=w(["syncMappings","forgePlans","pipelines","anonymizationTemplates"]),Yi=o({categories:c(Cn).min(1).max(50)}),Vi=o({json:a().min(1).max(5e6),overwrite:r()}),Ji=o({json:a().min(1).max(5e6)}),Qi=o({orgId:a().max(128),authMethod:a().min(1).max(50),alias:a().max(100).optional(),loginUrl:a().max(500).optional(),username:a().max(300).optional(),password:a().max(500).optional(),securityToken:a().max(100).optional(),clientId:a().max(256).optional(),jwtKeyFile:a().max(4096).optional()}).loose(),ko=a().trim().max(100).regex(/^[\w.-]*$/,"an alias is letters, digits, dots, dashes and underscores").optional(),Tn=a().trim().min(1,"the username is required").max(80).regex(/^[\w.@+-]+$/,"a username is written like an email address"),jo=a().trim().min(1,"the consumer key is required").max(256).regex(/^[A-Za-z0-9._-]+={0,2}$/,"a consumer key is letters, digits, dots, dashes and underscores"),_n=a().trim().min(1,"the private key file is required").max(4096).regex(/^[^\u0000-\u001f\u007f]+$/,"the private key file path holds a control character").refine(e=>tn(e),"give the private key file as an absolute path"),es=o({alias:ko,loginUrl:a().max(500).optional(),username:Tn,clientId:jo,jwtKeyFile:_n}).loose(),ts=o({alias:ko,loginUrl:a().max(500).optional(),clientId:jo}).loose(),os=o({requestId:m}),ns=o({orgId:i}),as=o({orgId:i}),rs=o({orgId:i}).strict(),is=o({orgId:i,alias:a().trim().min(1).max(100),color:a().regex(/^#[0-9A-Fa-f]{6}$/),tags:c(a().trim().min(1).max(50)).max(20),staging:r().optional()}),ss=o({key:a().min(1).max(200),value:D()}),cs=o({enabled:r()}),ls=o({lng:w(["en","fr","de","es","ja","pt-BR"])}),ds=o({targetOrgId:i,sourceOrgId:i.optional()}),ps=o({moduleId:a().min(1).max(64),route:a().min(1).max(64),overlay:r()}),ms=o({moduleId:a().min(1).max(64)}),Nn=80,Dn=ot(e=>Lt(e)||Bt(e)||typeof e=="string"&&e.trim()!==""&&e.length<=Nn,{message:"Not a pipeline step type"}),Fn=o({pipeline:o({name:a().min(1).max(200),steps:c(o({type:Dn,config:x(a(),D()).default({})}).loose()).max(200),variables:c(x(a(),D())).max(200).default([]),triggers:c(x(a(),D())).max(50).default([])}).loose(),variables:x(a(),a().max(2e3)).optional(),dryRun:r().optional()}),Mn=tt({since:at.datetime({offset:!0}),runner:w(["cron","taskScheduler","githubActions"]),file:a().min(1).max(255).refine(e=>!/[\\/]/.test(e),"The file's name, without its folder"),digest:a().regex(/^sha256:[0-9a-f]{64}$/,"Not a digest: sha256: and 64 hex digits")}),us=Fn.shape.pipeline.extend({id:a().min(1).max(200),runsOutside:Mn.optional()}),gs=o({pipelineId:m}),bs=o({id:a().max(200),config:x(a(),D())}),fs=o({id:m}),ys=o({operationId:m,stepId:m,decision:w(["approved","rejected"])}),Un=255,Po={pipelineId:m,stepId:m},hs=o({pipelineId:m}),zs=o({...Po,typed:a().min(1).max(Un)}),Ss=o(Po),xs=o({category:a().max(100).optional(),query:a().max(500).optional()}).loose().optional(),Is=o({templateId:m});function Ln(e){return e.issues.slice(0,3).map(t=>`${t.path.join(".")||"(root)"}: ${t.message}`).join("; ")}function Bn(e){let t=e.issues.map(n=>n.code==="custom"?n.params?.unreadablePatterns:void 0);return t.every(n=>n!==void 0)?t.flat():void 0}function ks(e,t,n,s){let d=e.safeParse(t.payload);if(!d.success){let p=Ln(d.error),u=Bn(d.error);return eo(s,t.type,n,t,new Error(`Invalid payload \u2014 ${p}`),u?{code:Dt,extraPayload:{rules:u}}:{code:"INVALID_PAYLOAD"}),null}return d.data}var $n=5;function Se(e){return e.slice(0,15)}function qn(e){let t=e.errors?.[0];if(t===void 0)return"The org gave no reason.";if(typeof t=="string")return t;let n=t.statusCode??"",s=t.message??"";return n&&s?`${n}: ${s}`:n||s||"The org gave no reason."}function Oo(e){let t=new Set;for(let n of e){let s=n.Id;typeof s=="string"&&t.add(Se(s))}return t}async function Ro(e){let t=[],n=[],s={},d=!1,p=!1,u=e.stampsFor,f=ie(e.org),k=e.org.serverTime?.bind(e.org),E=u&&k?Date.now()+await se({serverTime:k})-re:Number.NaN;for(let{objectApiName:O,ids:A}of e.plan){let I={objectApiName:O,planned:A.length,undeleted:0,alreadyBack:0,goneForGood:0,refused:0,reasons:[]};t.push(I);let z=_=>{I.reasons.length<$n&&!I.reasons.includes(_)&&I.reasons.push(_)},R=pe(O);for(let _=0;_<A.length;_+=me){let C=A.slice(_,_+me);if(p||e.signal?.aborted){p=!0,I.notReached=(I.notReached??0)+C.length,n.push(...C);continue}let[ee]=ue(C,me),K,te;try{K=Oo((await e.org.queryDeleted(`SELECT Id FROM ${R} WHERE Id IN (${ee}) AND IsDeleted = true`)).records),te=Oo((await e.org.query(`SELECT Id FROM ${R} WHERE Id IN (${ee})`)).records)}catch(j){I.refused+=C.length,z(`The recycle bin could not be read: ${V(j)}`),n.push(...C);continue}let h=C.filter(j=>K.has(Se(j)));for(let j of C)K.has(Se(j))||(te.has(Se(j))?I.alreadyBack++:I.goneForGood++);if(h.length===0)continue;let U;try{d=!0;let j=await e.undelete(h),T=Array.isArray(j)?j:[j];U=h.map((H,oe)=>T[oe]??{success:!1})}catch(j){let T=V(j);U=h.map(()=>({success:!1,errors:[T]}))}let Y=[];U.forEach((j,T)=>{if(j.success===!0){I.undeleted++,u?.(h[T])&&Y.push(h[T]);return}I.refused++,z(qn(j)),n.push(h[T])}),Y.length>0&&Number.isFinite(E)&&Object.assign(s,await be(e.org,R,Y,E,f))}}return{objects:t,left:n,wrote:d,cancelled:p,stamps:s}}function wo(e){return e.refused+e.goneForGood+(e.notReached??0)}async function Gn(e,t,n,s){let d=new Map(Object.entries(s).map(([u,f])=>[u.slice(0,15),Date.parse(f)])),p=new Set;for(let{objectApiName:u,ids:f}of t){let k=pe(u);for(let E of ue(f)){let O;try{O=(await e.query(`SELECT Id, LastModifiedDate FROM ${k} WHERE Id IN (${E})`)).records}catch{continue}for(let A of O){if(typeof A.Id!="string")continue;let I=A.Id.slice(0,15),z=Date.parse(String(A.LastModifiedDate??""));(z<=n||z<=(d.get(I)??Number.NaN))&&p.add(I)}}}return p}function vo(e){let t=Date.parse(e.startedAt),n=Date.parse(e.lastWrittenAt??e.end?.at??"");return Number.isFinite(n)?{runRecordedAt:new Date(n),...Number.isFinite(t)?{runDurationMs:Math.max(0,n-t)}:{}}:{}}function Wn(e){return e.filter(t=>t.deleted+t.alreadyGone>0).map(t=>t.objectApiName)}async function Ms(e){let{run:t,includeChanged:n}=e,s=e.again===!0,d=ge(t,s),p=d.reduce((b,S)=>b+S.ids.length,0),u=Be(t),f=u.reduce((b,S)=>b+S.ids.length,0),k=Yt(t),E=k.reduce((b,S)=>b+S.ids.length,0),O=[],A=e.backups,I=e.undelete;k.length>0&&!I&&O.push(`The ${E} record(s) the run deleted could not be brought back from the recycle bin here: the next removal offers them again.`),u.length>0&&!A&&O.push(`The values from before the run of ${f} record(s) it wrote over could not be read here: they were not put back, and the next removal offers them again.`);let z,R,_={},C=(e.earlierRuns??[]).map(b=>({runId:b.runId,keys:new Set([...ge(b),...Be(b)].flatMap(({ids:S})=>S.map(L=>L.slice(0,15))))})),ee=b=>C.some(({keys:S})=>S.has(b.slice(0,15))),K=e.sweep,te=u.length>0&&A||k.length>0&&I||K?async b=>{if(k.length>0&&I){let N=u.length>0&&A?await Gn(e.org,u,await Vt(e.org,xe(t)),t.removal?.removalStamps??{}):void 0,q=N?Date.now()+await se(e.org)-re:0;if(R=await Ro({org:e.org,plan:k,undelete:I,...C.length>0?{stampsFor:ee}:{},...e.signal?{signal:e.signal}:{}}),N&&R.wrote){let P=ie(e.org);for(let{objectApiName:Pe,ids:Mo}of u){let Uo=Mo.filter(Lo=>N.has(Lo.slice(0,15)));Object.assign(_,await be(e.org,Pe,Uo,q,P))}}if(R.cancelled||e.signal?.aborted)return R.wrote}if(u.length>0&&A){let N={...t.removal?.removalStamps,..._};z=await Jt({org:e.org,plan:u,backups:A,...xe(t)!==void 0?{lastWriteAt:xe(t)}:{},includeChanged:n,...Object.keys(N).length>0?{stamps:N}:{},...t.unkept?{unkept:t.unkept}:{},...C.length>0?{stampsFor:ee}:{},...e.signal?{signal:e.signal}:{}})}let S=(R?.wrote??!1)||(z?.wrote??!1);if(z?.cancelled||e.signal?.aborted)return S;let L=K?await K(b):!1;return S||L}:void 0,h=await Ue(e.org,d,{...vo(t),...t.removal?.removalStamps?{removalStamps:t.removal.removalStamps}:{},...t.removal?.removalSpans?{removalSpans:t.removal.removalSpans}:{},includeChanged:n,...te?{sweep:te}:{},...e.afterRemoval?{afterRemoval:e.afterRemoval}:{},...e.automationMade?{automationMade:e.automationMade}:{},...e.runUserId?{runUserId:e.runUserId}:{},...e.onUndeletable?{onUndeletable:e.onUndeletable}:{},...e.beforeFirstWrite?{beforeFirstWrite:e.beforeFirstWrite}:{},signal:e.signal,onProgress:e.onProgress}),U=new Date().toISOString();if(h.stoppedForUndeletable)return{result:{runId:t.runId,status:"cancelled",includeChanged:n,objects:[],finishedAt:U},planned:p,plannedBack:f,plannedUndelete:E,notes:[],stoppedForUndeletable:!0};let Y=s?void 0:t.removal?.undo?.removedAt,j={runId:t.runId,status:Zn(Xn(Zt(h.objects,h.cancelled),h.objects,z),h.objects,z,R),includeChanged:n,objects:h.objects,finishedAt:U,...Y?{leftBy:Y}:{},...z&&z.objects.length>0?{restored:z.objects}:{},...R&&R.objects.length>0?{undeleted:R.objects}:{}},T=Xt(j,p,t.removal?.undo,s),H=new Set(h.gone),oe=H.size>0||s&&T?d.flatMap(({ids:b})=>b.filter(S=>!H.has(S))):void 0,Je={..._,...h.stamps},Qe=Object.keys(Je).length>0,No=z?.objects.some(b=>b.restored+(b.restoredWithout??0)>0)===!0,Do=R!==void 0&&!R.cancelled;if(T||Qe||h.span||oe||z||R)try{await e.store.updateRemoval(t.runId,b=>({...b,...T?{undo:T}:{},...Qe?{removalStamps:{...b.removalStamps,...Je}}:{},...h.span?{removalSpans:[...b.removalSpans??[],h.span]}:{},...oe?{removalLeft:oe}:{},...z?{restoreLeft:z.left}:{},...No?{restoredAt:U}:{},...R?{undeleteLeft:R.left}:{},...Do?{undeletedAt:U}:{}}))}catch(b){O.push(`What this removal did could not be kept (${b instanceof Error?b.message:String(b)}): the next removal of the run may set out to take records already gone.`)}let Fo=Object.keys(z?.stamps??{}).length>0?await Kn(e.org,t,e.earlierRuns??[]):new Map,ke=[];for(let{runId:b,keys:S}of C){let L=Fo.get(b),N=Object.fromEntries(Object.entries({...R?.stamps,...z?.stamps}).filter(([P])=>S.has(P.slice(0,15))&&!L?.has(P.slice(0,15)))),q=Object.keys(N).length;if(q!==0)try{await e.store.updateRemoval(b,P=>({...P,removalStamps:{...P.removalStamps,...N},...h.span?{removalSpans:[...P.removalSpans??[],h.span]}:{}})),ke.push({runId:b,records:q})}catch(P){O.push(`What this removal gave back of ${q} record(s) the run ${b} wrote too could not be kept on it (${P instanceof Error?P.message:String(P)}): its removal reads them as changed since it.`)}}let le=e.configs;if(le&&H.size>0&&le.isSaved(t.configId)){let b={sourceOrgId:t.sourceOrgId,targetOrgId:$e(t)};try{let S=d.filter(P=>Le.includes(P.objectApiName)).flatMap(({ids:P})=>P.filter(Pe=>H.has(Pe))),L=le.forgetFiles(t.configId,b,S),N=Wn(h.objects).filter(P=>!Le.includes(P)),q=le.markRemoved(t.configId,b,[...new Set([...N,...L.map(P=>P.objectApiName)])],U);j={...j,...q.length>0?{readWhole:q}:{},...L.length>0?{filesForgotten:L.length}:{}}}catch(S){O.push(`The configuration could not be told what this removal took (${S instanceof Error?S.message:String(S)}): run it full next time.`)}}let je;if(e.links&&H.size>0)try{je=await e.links.forget(t.configId,{sourceOrgId:t.sourceOrgId,targetOrgId:$e(t)},[...H])}catch(b){O.push(`Which records of the target this removal took could not be forgotten (${b instanceof Error?b.message:String(b)}): a later run of the configuration may point a lookup at one of them.`)}return{result:j,planned:p,plannedBack:f,plannedUndelete:E,notes:O,...je?{linksForgotten:je}:{},...ke.length>0?{earlierStamped:ke}:{},...h.duplicateSets?{duplicateSets:h.duplicateSets}:{}}}async function Us(e){let{run:t}=e,n=ge(t);return{outcome:await Ue(e.org,n,{...vo(t),...t.removal?.removalStamps?{removalStamps:t.removal.removalStamps}:{},...t.removal?.removalSpans?{removalSpans:t.removal.removalSpans}:{},includeChanged:e.includeChanged,...e.runUserId?{runUserId:e.runUserId}:{},previewOnly:!0,...e.signal?{signal:e.signal}:{}}),planned:n.reduce((d,p)=>d+p.ids.length,0)}}async function Kn(e,t,n){let s=new Map,d=Object.entries(t.heldBefore??{});if(d.length===0||n.length===0)return s;let p=await ie(e)(),u=await se(e);for(let f of n){let k=Date.parse(xe(f)??""),E=Number.isFinite(k)?k+u+re:Number.NEGATIVE_INFINITY,O=new Set;for(let[A,{at:I,by:z}]of d)Date.parse(I)>E&&(p!==void 0&&z!==void 0&&z.slice(0,15)===p||O.add(A));O.size>0&&s.set(f.runId,O)}return s}function xe(e){return e.lastWriteAt??e.lastWrittenAt??e.end?.at}function Hn(e){return e.keptChanged+e.refused+e.notKept+(e.notReached??0)+(e.restoredWithout??0)}function Zn(e,t,n,s){if(!s||e==="cancelled")return e;if(s.cancelled)return"cancelled";let d=s.objects.some(u=>wo(u)>0);if(e==="success"&&!d)return"success";let p=t.some(u=>u.deleted>0)||(n?.objects??[]).some(u=>u.restored>0)||s.objects.some(u=>u.undeleted>0);return e==="partial"||p?"partial":"failure"}function Xn(e,t,n){if(!n||e==="cancelled")return e;if(n.cancelled)return"cancelled";let s=n.objects.some(p=>Hn(p)>0);return e==="success"&&!s?"success":t.some(p=>p.deleted>0)||n.objects.some(p=>p.restored+(p.restoredWithout??0)>0)?"partial":"failure"}function Bs(e){let t=e?.getSandforgeSetting?.("backup.maxAgeDays",30);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}function $s(e,t,n){let s=[],d=0,p=Number.POSITIVE_INFINITY;for(let u of e){let f=t(u.backup);if(!f){d+=u.ids.length;continue}s.push(u);let k=Date.parse(f.timestamp??"");n>0&&Number.isFinite(k)&&(p=Math.min(p,k+n*864e5))}return{kept:s,notKept:d,...Number.isFinite(p)?{keptUntil:new Date(p).toISOString()}:{}}}var Ye="backupSet:",Yn="backups",Ve=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Q=a().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/),$=g().int().nonnegative(),Vn=o({index:g().int().positive(),afterId:a().regex(Ve).optional(),lastId:a().regex(Ve).optional(),rows:$,snapshotId:a().min(1).max(240),takenAt:Q.optional(),readSince:Q.optional(),state:w(["pending","snapshotted","masking","masked","restored"]),masked:$,refused:$,deletedSince:$,nothingToMask:$,unanswered:$.optional(),late:v(!0).optional(),sizeUsed:g().int().positive(),lateLeft:$.optional(),lateOf:g().int().positive().optional(),lateAfterId:a().regex(Ve).optional(),restoredAt:Q.optional()}),Jn=o({objectApiName:a().min(1).max(255),where:a().max(2e3).optional(),select:a().max(1e5).optional(),done:r(),tailLeft:$.optional(),slices:c(Vn)}),Ao=o({setId:a().min(1).max(200),kind:w(["masking","backup"]),orgId:a().min(1).max(200),organizationId:a().max(18).optional(),templateId:a().min(1).max(200).optional(),fingerprint:a().regex(/^[0-9a-f]{64}$/).optional(),size:g().int().positive(),state:w(["open","done","abandoned"]),startedAt:Q,serverStartedAt:Q.optional(),lastActivityAt:Q,requestsSpent:$,keyCheck:a().regex(/^[0-9a-f]{16}$/).optional(),objects:c(Jn)});function Gs(e,t){return`${e}-s${String(t).padStart(4,"0")}`}function Ie(e){return e.objects.flatMap(t=>t.slices).sort((t,n)=>t.index-n.index)}function Ws(e){return Ie(e).reduce((t,n)=>Math.max(t,n.index),0)+1}function Co(e){return e.state==="masked"||e.state==="snapshotted"||e.state==="restored"}function Qn(e){return Ie(e).reduce((t,n)=>t+n.rows,0)}function To(e,t,n){return{index:t.index,objectApiName:e,snapshotId:t.snapshotId,rows:t.rows,masked:t.masked,refused:t.refused,deletedSince:t.deletedSince,nothingToMask:t.nothingToMask,state:t.state,...t.late?{late:!0}:{},...t.sizeUsed<n?{sizeUsed:t.sizeUsed}:{},...t.restoredAt?{restoredAt:t.restoredAt}:{}}}function ea(e){return e.objects.reduce((t,n)=>t+(n.tailLeft??0)+n.slices.reduce((s,d)=>s+(d.lateLeft??0),0),0)}function Ks(e,t){return{setId:e.setId,size:e.size,state:e.state,objects:e.objects.map(n=>({objectApiName:n.objectApiName,slices:n.slices.map(s=>To(n.objectApiName,s,e.size))})),lateRecords:ea(e),requestsSpent:t.requestsSpent,...t.stoppedOnBudget?{stoppedOnBudget:!0}:{},slicesLeft:e.objects.some(n=>!n.done||n.slices.some(s=>!Co(s)))}}function ta(e){return e.kind==="backup"&&e.state==="open"?"partial":e.state}function Hs(e){let t=Object.fromEntries(e.objects.flatMap(n=>n.where?[[n.objectApiName,n.where]]:[]));return{setId:e.setId,orgId:e.orgId,kind:e.kind,state:ta(e),startedAt:e.startedAt,lastActivityAt:e.lastActivityAt,size:e.size,totalRecords:Qn(e),...e.templateId?{templateId:e.templateId}:{},slices:e.objects.flatMap(n=>n.slices.map(s=>To(n.objectApiName,s,e.size))),...Object.keys(t).length>0?{wheres:t}:{}}}function Zs(e){let t=Ie(e);return{setId:e.setId,savedAt:e.lastActivityAt,done:t.filter(Co).length,total:t.length,state:e.state,size:e.size}}var Eo=class{constructor(t){this.configStore=t}configStore;get(t){let n=Ao.safeParse(this.configStore.get(this.key(t)));return n.success&&n.data.setId===t?n.data:void 0}save(t){this.configStore.set(this.key(t.setId),Ao.parse(t),Yn)}delete(t){this.configStore.delete(this.key(t))}list(t){return this.configStore.getKeysByPrefix(Ye).map(n=>this.get(n.slice(Ye.length))).filter(n=>n!==void 0).filter(n=>t===void 0||n.orgId===t)}openFor(t,n){return this.list(t).find(s=>s.kind==="masking"&&s.state==="open"&&s.templateId===n)}ofSnapshot(t){return this.list().find(n=>Ie(n).some(s=>s.snapshotId===t))}key(t){return`${Ye}${t}`}};async function Ys(e,t){let n=e.check(t);if(!n.allowed)return{check:n,decision:"refused"};if(!await e.confirmIfNeeded(n,t.orgTier))return{check:n,decision:"declined"};let d=n.requiresConfirmation&&e.canAskForConfirmation===!0;return{check:n,decision:d?"confirmed":"allowed"}}var _o={allowed:0,confirmed:1,declined:2,refused:3};function Vs(e,t){return e===void 0||_o[t]>_o[e]?t:e}export{sa as a,Qt as b,ca as c,qe as d,la as e,da as f,Bo as g,pa as h,ma as i,ua as j,ga as k,ba as l,fa as m,ya as n,eo as o,ha as p,za as q,Sa as r,xa as s,i as t,l as u,so as v,B as w,nn as x,an as y,Ke as z,Ea as A,Ca as B,Ta as C,_a as D,Na as E,Da as F,Fa as G,Ma as H,Ua as I,La as J,Ba as K,$a as L,qa as M,Ga as N,Wa as O,Ka as P,Ha as Q,Za as R,Xa as S,Ya as T,Va as U,Ja as V,Qa as W,er as X,tr as Y,or as Z,mn as _,nr as $,ar as aa,rr as ba,ir as ca,sr as da,cr as ea,lr as fa,dr as ga,pr as ha,mr as ia,ur as ja,gr as ka,br as la,fr as ma,yr as na,hr as oa,zr as pa,Sr as qa,xr as ra,Ir as sa,kr as ta,jr as ua,Pr as va,Or as wa,Rr as xa,wr as ya,vr as za,Ar as Aa,Er as Ba,Cr as Ca,Tr as Da,_r as Ea,fn as Fa,Nr as Ga,Dr as Ha,Fr as Ia,Mr as Ja,Ur as Ka,Lr as La,Br as Ma,$r as Na,qr as Oa,Gr as Pa,Wr as Qa,Kr as Ra,go as Sa,Hr as Ta,Zr as Ua,Xr as Va,bo as Wa,Yr as Xa,Vr as Ya,Jr as Za,Qr as _a,ti as $a,oi as ab,ni as bb,ai as cb,ri as db,ii as eb,si as fb,ci as gb,li as hb,di as ib,pi as jb,mi as kb,ui as lb,gi as mb,bi as nb,fi as ob,yi as pb,hi as qb,zi as rb,Si as sb,xi as tb,Ii as ub,ki as vb,ji as wb,Pi as xb,Oi as yb,Ri as zb,wi as Ab,vi as Bb,Ai as Cb,Ei as Db,Ci as Eb,Ti as Fb,_i as Gb,Ni as Hb,Di as Ib,Fi as Jb,Mi as Kb,Ui as Lb,Li as Mb,Bi as Nb,$i as Ob,qi as Pb,Gi as Qb,Wi as Rb,Ki as Sb,Hi as Tb,Zi as Ub,Xi as Vb,Yi as Wb,Vi as Xb,Ji as Yb,Qi as Zb,es as _b,ts as $b,os as ac,ns as bc,as as cc,rs as dc,is as ec,ss as fc,cs as gc,ls as hc,ds as ic,Fn as jc,Mn as kc,us as lc,gs as mc,bs as nc,fs as oc,ys as pc,hs as qc,zs as rc,Ss as sc,xs as tc,Is as uc,Ln as vc,ks as wc,Ro as xc,Ms as yc,Us as zc,xe as Ac,Zn as Bc,Xn as Cc,Ys as Dc,Vs as Ec,Bs as Fc,$s as Gc,Gs as Hc,Ie as Ic,Ws as Jc,Co as Kc,ea as Lc,Ks as Mc,ta as Nc,Hs as Oc,Zs as Pc,Eo as Qc};
|
|
@@ -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 l,$b as la,Ab as M,Ac as Ma,Bb as N,Bc as Na,Cb as O,Cc as Oa,Db as P,Dc as Pa,Eb as Q,Ec as Qa,Fb as R,Fc as Ra,Gb as S,Gc as Sa,Hb as T,Hc as Ta,Ib as U,Ic as Ua,Jb as V,Jc as Va,Kb as W,Kc as Wa,Lb as X,Lc as Xa,Mb as Y,Mc as Ya,Nb as Z,Nc as Za,Ob as _,Oc as _a,Pb as $,Pc as $a,Qa as a,Qb as aa,Qc as ab,Ra as b,Rb as ba,Rc as bb,Sa as c,Sb as ca,Sc as cb,Ta as d,Tb as da,Tc as db,Ua as e,Ub as ea,Va as f,Vb as fa,Wa as g,Wb as ga,Xa as h,Xb as ha,Ya as i,Yb as ia,Za as j,Zb as ja,_a as k,_b as ka,ab as m,ac as ma,bb as n,bc as na,cb as o,cc as oa,db as p,dc as pa,eb as q,ec as qa,fb as r,fc as ra,gb as s,gc as sa,hb as t,hc as ta,ib as u,ic as ua,jb as v,jc as va,kb as w,kc as wa,lb as x,lc as xa,mb as y,mc as ya,nb as z,nc as za,ob as A,oc as Aa,pb as B,pc as Ba,qb as C,qc as Ca,rb as D,rc as Da,sb as E,sc as Ea,tb as F,tc as Fa,ub as G,uc as Ga,vb as H,vc as Ha,wb as I,wc as Ia,xb as J,xc as Ja,yb as K,yc as Ka,zb as L,zc as La}from"./chunk-KB4ZHM4Q.mjs";import"./chunk-23SEDORH.mjs";import"./chunk-W6PN6TJG.mjs";import"./chunk-3Q353S2R.mjs";import"./chunk-RHNTHGNU.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-Q7TLC3I2.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-D4GF4FAB.mjs";import"./chunk-CVHNXJH3.mjs";import"./chunk-TQ2TQHTT.mjs";import"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-M6K34KGF.mjs";import"./chunk-TNT27RBG.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-PC247GKX.mjs";import"./chunk-S42RBRH2.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-PMWAFDUB.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{y as API_BUDGET_EXCEEDED,u as API_BUDGET_NEAR_SHARE,r as API_REQUESTS_NOT_TOLD,L as BULK_BATCHES_NOT_TOLD,B as CHECKPOINT_REFUSED,E as CHECKPOINT_STOPPED_WORDS,a as DEFAULT_CONFIRM_ABOVE_RECORDS,b as DEFAULT_MAX_TOTAL,$ as DELIVERABILITY_READ_MOST,ka as DEVELOPER_EDITION_SINGLE_EMAILS,ya as EMAILS_NOT_ACCEPTED,Ta as ForgeRunGateError,l as LastSimulations,Ra as OWNER_MAP_INACTIVE,Sa as OWNER_MAP_UNKNOWN,c as READ_CEILING_PER_OBJECT,ca as SAMPLE_CANNOT_FIT,fa as SAMPLE_PLAN_GONE,ea as SAMPLE_PLAN_MISMATCH,ba as SAMPLE_STORAGE_UNREAD,da as SAMPLE_TOO_LARGE,e as STORAGE_NEAR_SHARE,f as STORAGE_ROUNDING_MARGIN_MB,I as WHOLE_ORG_SOURCE_READS_PER_OBJECT,H as WHOLE_ORG_TARGET_READS_PER_OBJECT,la as alertsCountAsSingle,x as apiBudgetCheckOf,z as apiBudgetRefusal,W as automationBytesOf,Aa as automationReadRequests,$a as automationRefusal,Qa as automationUnreadOf,M as bulkBatchesRefusal,_a as bypassAssistantSentences,Pa as bypassesToAssign,C as checkpointPartOf,D as checkpointScopeStop,A as confirmationApiOf,n as confirmationSimulatedOf,Ha as confirmationStorageOf,pa as countedEmailChecksOf,i as countedStorageBytes,qa as countedTargetEmails,Ga as deliverabilityAfterLeaseStop,Da as deliverabilityGate,Ca as deliverabilityLineOf,Ba as deliverabilityPartOf,xa as emailCheckLines,oa as emailChecksOf,wa as emailRefusal,na as emailsCountedPerRecord,va as emailsOfLimit,sa as emailsUncountedOf,m as farPastTheSimulation,O as fileStorageRefusal,Va as filesRefusalStop,Ka as firedOnInsertOf,La as firedOnUpdateOf,J as forgeRequestPartsOf,k as forgeVolumeCaseKey,S as forgeWriteBudgetOf,G as forgeWritesOf,Ia as formatMB,Ja as formatMBPast,ra as insertsOf,Ua as isForgeRunGateError,Ya as leftOutLines,q as limitsOfOrg,d as objectsAboveReadCeiling,Ma as objectsUpdatedAfterInsert,ta as overEmailOf,Z as personalFieldsAsIsOf,o as pricesForLinesOf,t as readApiBudget,P as readBoundRefusal,Q as readBoundStopOf,s as readDataStorage,ja as readEmailLimits,bb as removalAutomationLines,ab as removalAutomationRefusal,Za as removalRiskLines,cb as removalStepsAutomationLines,db as removalStepsAutomationRefusal,p as rolesMayBeOf,h as rowStorageBytes,Oa as runBypassesOf,v as runRequestsEstimate,w as runRequestsTotal,ia as sampleGateErrorOf,ha as sampleGateStopOf,ga as sampleStorageUnreadStopOf,Ea as sendersOfNothingWritten,Fa as sendersOfNothingWrittenLine,za as sendersUnreadOf,ma as singleCountAsWorkflow,N as sourceApiBudgetRefusal,T as storageCheckOf,U as storageCountedOf,V as storageCountedWords,Wa as storageRefusal,g as storageRoomMB,X as storageTakesWords,F as takeCheckpointFirst,ua as unreadEmailOf,Na as updateStepsOf,K as wholeOrgCostOf,aa as wholeOrgDryRunOf,R as wholeOrgFilesOf,_ as wholeOrgLeftOutOf,Y as wholeOrgWritePlanOf,Xa as writePlanLines,j as writePlanOf};
|
|
@@ -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{wd as u}from"./chunk-
|
|
7
|
+
import{wd as u}from"./chunk-PMWAFDUB.mjs";var f={BusinessHours:["Name"]},j=["DUPLICATE_VALUE","DUPLICATES_DETECTED","duplicate value found"];var y=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,k=/^[A-Za-z][A-Za-z0-9_]*$/;function l(e){return e.slice(0,15)}function g(e,r){let t=e.mapping.get(r);return typeof t=="string"&&y.test(t)?t:void 0}function m(e){let r=new Set((e.created??[]).flatMap(i=>i.referenceIds)),t=new Set;for(let i of e.mapping.keys()){if(r.has(i))continue;let n=g(e,i);n&&t.add(l(n))}return t}function P(e){let r=new Set((e.created??[]).flatMap(n=>n.referenceIds)),t=[...Object.entries(e.personContacts??{}),...Object.entries(e.withTheirRecord??{})];for(let n=!0;n;){n=!1;for(let[o,s]of t)r.has(o)||!r.has(s)||(r.add(o),n=!0)}let i=new Set;for(let[n]of t){let o=r.has(n)?g(e,n):void 0;o&&i.add(l(o))}return i}function b(e){let r=m(e),t=new Map;for(let{objectApiName:o,referenceIds:s}of e.created??[])k.test(o)&&t.set(o,[...t.get(o)??[],...s]);let i=new Set,n=[];for(let[o,s]of[...t].reverse()){let a=[];for(let A of[...s].reverse()){let c=g(e,A);if(!c)continue;let d=l(c);r.has(d)||i.has(d)||(i.add(d),a.push(c))}a.length>0&&n.push({objectApiName:o,ids:a})}return n}function p(e){return u(e.removal)?[]:b(e).filter(r=>!R(r.objectApiName))}function R(e){return Object.prototype.hasOwnProperty.call(f,e)}function h(e){return b(e).filter(r=>R(r.objectApiName)).map(({objectApiName:r,ids:t})=>({objectApiName:r,count:t.length}))}function O(e){return e.find(r=>p(r).length>0)??e[0]}function I(e,r){return e.filter(t=>t.endedAt!==r.endedAt&&t.created!==void 0&&p(t).length===0)}function v(e){let r=e.created!==void 0,t=P(e),i=[...m(e)].filter(o=>!t.has(o)),n=h(e);return{orgId:e.orgId,loadedAt:e.endedAt,created:p(e).map(({objectApiName:o,ids:s})=>({objectApiName:o,count:s.length})),linked:r?i.length:0,recorded:r,...e.removal?{removed:e.removal}:{},...e.earlier?{earlier:!0}:{},...n.length>0?{keptByThePlatform:n}:{}}}export{f as a,j as b,b as c,p as d,h as e,O as f,I as g,v as h};
|
|
@@ -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{d as Z}from"./chunk-HFSBDM7B.mjs";import{c as H,g as Y}from"./chunk-OHEOJISY.mjs";import{a as F}from"./chunk-EADHKH3A.mjs";import{g as W,t as Q}from"./chunk-2GSMHGIV.mjs";import{a as U,f as D,h as k}from"./chunk-TZE3Y7IQ.mjs";import{a as P}from"./chunk-ICIYL45C.mjs";import{d as J}from"./chunk-7BQMBXKX.mjs";import{O as z,Q as B,T as V,Uc as R}from"./chunk-6QSHWIZI.mjs";import{b as I,k as G,l as A,v as K,z as _}from"./chunk-WZQEK4WT.mjs";function Le(e){let n=new Set;for(let t of e)t.controllerName&&n.add(t.controllerName);return n}function X(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function je(e,n){let t=X(e.precision),r=typeof e.scale=="number"&&e.scale>=0?e.scale:void 0,o=X(e.digits),s=(e.picklistValues??[]).filter(d=>d!==null&&typeof d.value=="string"),i={};if(e.controllerName)for(let d of s)d.active===!1||typeof d.validFor!="string"||(i[d.value]=d.validFor);return{...t!==void 0?{precision:t}:{},...t!==void 0&&r!==void 0?{scale:r}:{},...o!==void 0?{digits:o}:{},...e.unique===!0?{unique:!0}:{},...e.unique===!0&&typeof e.caseSensitive=="boolean"?{caseSensitive:e.caseSensitive}:{},...e.calculated===!0?{calculated:!0}:{},...e.filteredLookupInfo?{filteredLookup:!0}:{},...Object.keys(i).length>0?{validFor:i}:{},...n.has(e.name)&&s.length>0?{controllingValues:s.map(d=>d.value)}:{}}}function Ce(e,n){return e.caseSensitive===!1?n.toLowerCase():n}function M(e,n){if(n<0)return!1;let r=Buffer.from(e,"base64")[n>>3];return r!==void 0&&(r&128>>n%8)!==0}var ie={picklist_value_refused:["map_value","leave_empty","skip_rows","exclude_object","ignore"],dependent_value_invalid:["map_value","leave_empty","exclude_object","ignore"],picklist_value_absent:["map_value","skip_rows","ignore"],required_field_missing:["set_default","exclude_object","ignore"],value_too_long:["truncate","exclude_object","ignore"],number_out_of_range:["exclude_object","ignore"],record_type_unmapped:["map_record_type","exclude_object","ignore"],record_type_unavailable:["map_record_type","exclude_object","ignore"],currency_inactive:["map_value","skip_rows","exclude_object","ignore"],unique_value_collision:["exclude_object","ignore"]};function w(e){return[...ie[e]??["ignore"]]}var se=100,ae=new Set(["longest","colliding"]),O=class{gaps=new Map;recordTypes=new Map;get size(){return this.gaps.size}knowRecordTypes(n,t,r){let o=de(r);o!==void 0&&this.recordTypes.set(n,{...this.recordTypes.get(n),[t]:o})}add(n){let t=z(n.kind,n.objectApiName,n.field,n.recordType,n.value),r=this.gaps.get(t);if(!r){this.gaps.set(t,{...n,id:t,source:"simulation",decisions:[...n.decisions]});return}r.rows+=n.rows,n.decisions.includes("skip_rows")||(r.decisions=r.decisions.filter(s=>s!=="skip_rows"));let o={...n.detail??{},...r.detail??{}};for(let s of ae){let i=r.detail?.[s],d=n.detail?.[s];typeof i=="number"&&typeof d=="number"&&(o[s]=Math.max(i,d))}r.detail=o}list(n){let t=[...this.gaps.keys()],r=[...this.gaps.values()].map(o=>this.withSameDeveloperName(o)).map(o=>B(n,o,t)!==void 0?{...o,detail:{...o.detail??{},ignored:!0}}:o);return V(r)}withSameDeveloperName(n){let t=n.kind==="record_type_unmapped";return le(n,this.recordTypes.get(n.objectApiName)?.[t?"source":"target"])}};function de(e){let n=e.filter(t=>!t.master);if(!n.some(t=>t.namespacePrefix===void 0))return n.map(Z)}function le(e,n){let t=e.kind==="record_type_unmapped"?e.value:e.recordType;if(t===void 0||n===void 0)return e;let r=Y(t);if(!r.namespacePrefix)return e;let o=n.filter(s=>s.developerName===r.developerName&&s.namespacePrefix!==r.namespacePrefix).map(s=>H(s.namespacePrefix,s.developerName));return o.length===0?e:{...e,detail:{...e.detail??{},sameDeveloperName:[...new Set(o)].sort()}}}function L(e){return[...new Set(e)].sort().slice(0,se)}function We(e,n,t){let r=[];for(let o of n){if(o.field===P)continue;let s=t(o);for(let i of o.values)r.push({kind:"picklist_value_refused",severity:"warning",objectApiName:e,field:o.field,...o.recordType!==void 0?{recordType:o.recordType}:{},value:i,rows:1,detail:{reason:o.reason,...s?{allowed:L(s)}:{},...o.controllingField?{controllingField:o.controllingField}:{},...o.replacedBy!==void 0?{replacement:o.replacedBy}:{}},decisions:w("picklist_value_refused").filter(d=>d!=="skip_rows"||o.reason!=="controlling-value"),defaultDecision:o.replacedBy!==void 0?"map_value":"leave_empty"})}return r}var ce=new Set(["string","textarea","email","phone","url","encryptedstring"]),ue=new Set(["double","currency","percent"]);function fe(e){return e==null||e===""}function ne(e){return e.createable&&e.nillable===!1&&e.defaultedOnCreate!==!0&&e.calculated!==!0&&e.type!=="boolean"}function pe(e,n,t){return e==="Account"&&n==="Name"&&Q(t)}function ge(e,n,t,r){return r.filter(o=>ne(o)&&fe(n[o.name])&&!pe(e,o.name,t))}function me(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||e.trim()==="")return;let n=Number(e);return Number.isFinite(n)?n:void 0}function ee(e){if(e.type==="int"&&e.digits!==void 0)return e.digits;if(e.precision!==void 0)return e.precision-(e.scale??0)}function ye(e,n){return e?e.type==="boolean"?n===!0||n==="true"?1:n===!1||n==="false"?0:-1:typeof n!="string"||n===""?-1:(e.controllingValues??[]).indexOf(n):-1}function te(e,n){let{objectApiName:t,rows:r,targetFields:o,picklistValuesByField:s,picklistFields:i}=e,d=new Map(o.map(u=>[u.name,u])),f=o.filter(ne),y=o.filter(u=>u.createable&&ce.has(u.type??"")&&(u.length??0)>0),g=o.filter(u=>u.createable&&(ue.has(u.type??"")||u.type==="int")&&ee(u)!==void 0),c=[...i].filter(([u,l])=>l.anyValue===!0&&s?.has(u)===!0),p=o.filter(u=>u.createable&&u.controllerName!==void 0&&u.validFor!==void 0);for(let{payload:u,source:l,typed:m}of r){for(let a of ge(t,u,l,f))n.add({kind:"required_field_missing",severity:"blocking",objectApiName:t,field:a.name,rows:1,...a.type?{detail:{type:a.type}}:{},decisions:w("required_field_missing")});for(let a of y){let h=u[a.name],b=a.length??0;typeof h!="string"||h.length<=b||n.add({kind:"value_too_long",severity:"blocking",objectApiName:t,field:a.name,rows:1,detail:{length:b,longest:h.length},decisions:w("value_too_long")})}for(let a of g){let h=me(u[a.name]),b=ee(a);h===void 0||b===void 0||Math.abs(Math.trunc(h))<10**b||n.add({kind:"number_out_of_range",severity:"blocking",objectApiName:t,field:a.name,rows:1,detail:{...a.precision!==void 0?{precision:a.precision}:{},...a.scale!==void 0?{scale:a.scale}:{},...a.type==="int"&&a.digits!==void 0?{digits:a.digits}:{}},decisions:w("number_out_of_range")})}for(let[a,h]of c){let b=u[a];if(typeof b!="string"||b==="")continue;let x=s?.get(a),v=h.multi?b.split(";"):[b];for(let E of new Set(v))x?.has(E)||n.add({kind:"picklist_value_absent",severity:"info",objectApiName:t,field:a,value:E,rows:1,decisions:w("picklist_value_absent")})}if(!m)for(let a of p){let h=u[a.name];if(typeof h!="string"||h==="")continue;let b=d.get(a.controllerName??""),x=ye(b,u[a.controllerName??""]),v=i.get(a.name)?.restricted===!0,E=i.get(a.name)?.multi?h.split(";"):[h];for(let q of new Set(E)){let $=a.validFor?.[q];$!==void 0&&(x>=0&&M($,x)||n.add({kind:"dependent_value_invalid",severity:v?"blocking":"warning",objectApiName:t,field:a.name,value:q,rows:1,detail:{controllingField:a.controllerName??"",allowed:L((b?.controllingValues??[]).filter((Me,oe)=>M($,oe)))},decisions:w("dependent_value_invalid")}))}}}}function Qe(e,n,t,r){return{kind:"currency_inactive",severity:"warning",objectApiName:e,field:P,value:n,rows:t,...r&&r.to.length>0?{detail:{replacement:r.to.join(", "),...r.converted.length>0?{amountsConverted:[...r.converted]}:{},...r.asRead?{amountsAsRead:!0}:{}}}:{},decisions:w("currency_inactive"),defaultDecision:"map_value"}}function He(e,n,t,r){return{kind:"unique_value_collision",severity:"warning",objectApiName:e,field:n,rows:t,detail:{colliding:r,linkedToTheRecordItNames:!0},decisions:w("unique_value_collision"),defaultDecision:"ignore"}}function Ye(e,n,t,r,o){return{kind:e,severity:"blocking",objectApiName:n,field:"RecordTypeId",...e==="record_type_unavailable"?{recordType:t}:{value:t},rows:r,detail:{mapTo:L(o)},decisions:w(e)}}var he=10;function re(e){switch(e.operation){case"insert":return null;case"upsert":return e.externalIdField??"Id";case"update":case"delete":return"Id"}}function S(e){if(e==null||typeof e!="string"&&typeof e!="number"&&typeof e!="boolean")return null;let n=String(e);return n===""?null:n.toLowerCase()}function T(e){return typeof e=="number"&&Number.isFinite(e)?String(e):typeof e=="boolean"?e?"true":"false":`'${U(String(e))}'`}var be=200,Se=4e3;function N(e){let n=[],t=[],r=0;for(let o of e){let s=T(o).length+2;t.length>0&&(t.length>=be||r+s>Se)&&(n.push(t),t=[],r=0),t.push(o),r+=s}return t.length>0&&n.push(t),n}function rn(e,n){return async(t,r,o,s)=>{let i=R(r.objectApiName),d=k(o),f=new Map;for(let y of N(s)){if(n?.aborted)throw new Error("The simulation was cancelled.");let{records:g}=await F(e,`SELECT ${d} FROM ${i} WHERE ${d} IN (${y.map(T).join(", ")})`);for(let c of g){let p=S(c[d]);p!==null&&f.set(p,(f.get(p)??0)+1)}}return f}}var we=new Set(["attributes","Id"]);function Re(e,n,t,r){return n?e.conflictFields.filter(o=>o!==t&&!we.has(o)&&o in n&&(r===null||r.has(o))):[]}var on=new Set(["noKey","notInTarget","ambiguous"]);function _e(e,n,t){let r=e.operation,o=re(e);if(o===null)return"insert";let s=S(n[o]);if(s===null)return r==="delete"?"notSent":"noKey";let i=t.get(s)??0;return r==="upsert"?i===0?o.toLowerCase()==="id"?"notInTarget":"insert":i===1?"update":"ambiguous":i===0?"notInTarget":r==="update"?"update":"delete"}var ke=1e4;function sn(e,n,t){let r=e>t?ke:Math.max(1,n);return{callOf:o=>Math.floor(o/r),job:e>t}}function an(e,n,t,r){let o=new Map;n.forEach((c,p)=>{if(c===null)return;let u=`${r.callOf(p)}\0${c}`,l=o.get(u);l?l.push(p):o.set(u,[p])});let s=new Set;for(let c of o.values())if(c.length>1)for(let p of c)s.add(p);let i=new Map,d=new Set,f=0;n.forEach((c,p)=>{if(c===null||s.has(p))return;let u=r.callOf(p);if(i.get(c)===void 0){t[p]==="insert"&&i.set(c,u);return}r.job?f++:t[p]==="insert"&&d.add(p)});let y=[],g=[];if(s.size>0){let c=`${s.size} record(s) carry the ${e} of another record of the same call: an upsert finds its record by its key, and the target refuses every record of a call whose key another carries (DUPLICATE_VALUE: Duplicate external id specified).`;y.push(c),g.push({code:"DUPLICATE_VALUE",rows:s.size,note:c})}return d.size>0&&y.push(`${d.size} record(s) carry the ${e} of a record sent in an earlier call: the upsert finds the record that one created and updates it with theirs.`),f>0&&y.push(`${f} record(s) carry the ${e} of a record in another batch of the Bulk API job: the platform may write the batches at once, so whether each updates the record the other created or creates one of its own cannot be told before the run.`),{refused:s,updated:d,notes:y,refusedFor:g}}function dn(e){let{objectConfig:n,records:t,inTarget:r}=e,o=n.operation,s=re(n),i={insert:0,update:0,delete:0,noKey:0,notInTarget:0,notSent:0,ambiguous:0},d=new Set;t.forEach((l,m)=>{let a=e.simulated?.[m]??_e(n,l,r);i[a]++,(a==="insert"||a==="update")&&d.add(m)});let f=e.leftOut.map(({why:l,count:m})=>W(m,l));i.noKey>0&&f.push(o==="upsert"?`${i.noKey} record(s) carry no value in ${s}: an upsert matches on it, and the target refuses a record without one.`:`${i.noKey} record(s) carry no Id: an update finds its record by Id, and the target refuses one without it.`),i.notInTarget>0&&f.push(`${i.notInTarget} record(s) carry an Id the target does not hold: ${o==="upsert"?"an upsert on the Id finds no record there and creates none":`${o==="update"?"an update":"a delete"} finds no record there`}, and the target refuses it. Two orgs share a record's Id only when it was copied with the org.`),i.ambiguous>0&&f.push(`${i.ambiguous} record(s) match more than one record of the target on ${s}: an upsert finds no single record to update, and the target refuses it.`),i.notSent>0&&f.push(`${i.notSent} record(s) carry no Id: a delete sends ids alone, so the run leaves them out.`);let y=new Map;e.unsettled.forEach((l,m)=>{let a=String(l[e.matchField]??"");a&&d.has(m)&&y.set(a,l)});let g=new Map,c=0;for(let l of e.conflicts){let m=Re(l,y.get(l.recordId),e.matchField,e.writable);if(m.length!==0){c++;for(let a of m)g.set(a,(g.get(a)??0)+1)}}let p=[...g].sort(([l,m],[a,h])=>h-m||l.localeCompare(a)).slice(0,he).map(([l])=>l),u=e.leftOut.reduce((l,{count:m})=>l+m,0);return{objectApiName:n.objectApiName,operation:o,read:e.read,insert:i.insert,update:i.update,delete:i.delete,skipped:u+i.notSent,refused:i.noKey+i.notInTarget+i.ambiguous,conflicts:c,conflictFields:p,notes:f}}var Fe={required_field_missing:"REQUIRED_FIELD_MISSING",value_too_long:"STRING_TOO_LONG",number_out_of_range:"NUMBER_OUTSIDE_VALID_RANGE"};function Ie(e){let n=e.field??"";switch(e.kind){case"required_field_missing":return`${e.rows} record(s) leave ${n} empty, which the target requires: it refuses them (REQUIRED_FIELD_MISSING).`;case"value_too_long":return`${e.rows} record(s) hold a ${n} longer than the ${String(e.detail?.length)} characters the target's field takes (the longest, ${String(e.detail?.longest)}): it refuses them (STRING_TOO_LONG).`;case"number_out_of_range":return`${e.rows} record(s) hold a ${n} larger than the target's field takes: it refuses them (NUMBER_OUTSIDE_VALID_RANGE).`;default:return}}function ln(e,n,t){let r=new Set,o=new O;n.forEach(({payload:i,source:d,creates:f},y)=>{let g=new O;te({objectApiName:e,rows:[{payload:i,source:d,typed:!0}],targetFields:t,picklistValuesByField:null,picklistFields:new Map},g);let c=g.list(new Set).filter(p=>p.severity==="blocking"&&(f||p.kind!=="required_field_missing"));if(c.length!==0){r.add(y);for(let p of c)o.add(p)}});let s=o.list(new Set).flatMap(i=>{let d=Ie(i),f=Fe[i.kind];return d&&f?[{code:f,rows:i.rows,note:d}]:[]});return{refused:r,notes:s.map(({note:i})=>i),refusedFor:s}}function cn(e,n){let t=new Set,r=new Set,o=[],s=[];for(let[i,d]of n){let f=new Set,y=0,g=0,c=0;if(e.forEach((u,l)=>{let m=S(u[i]);if(m===null)return;let a=d.get(m)??0;a===1?(y++,r.add(l)):a>1?(g++,t.add(l)):f.has(m)&&(c++,t.add(l)),f.add(m)}),y>0&&o.push(`LINKED_TO_EXISTING: ${y} record(s) hold a ${i} the target keeps unique, which a record of the target holds already: it refuses them as duplicates (DUPLICATE_VALUE) and names that record, which the run links them to \u2014 what it writes under them points at that record.`),g+c===0)continue;let p=`${g+c} record(s) hold a ${i} the target keeps unique, which `+[g>0?`several records of the target hold already (${g})`:"",c>0?`a record sent before them holds (${c})`:""].filter(Boolean).join(" or ")+": it refuses them (DUPLICATE_VALUE).";o.push(p),s.push({code:"DUPLICATE_VALUE",rows:g+c,note:p})}for(let i of t)r.delete(i);return{refused:t,linked:r,notes:o,refusedFor:s}}import{createHash as Oe}from"node:crypto";var Te=5*6e4,xe=500,Ee=A({sourceOrgId:I().min(1).max(200),targetOrgId:I().min(1).max(200),objectApiName:I().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),watermark:_.datetime(),fingerprint:I().regex(/^[0-9a-f]{64}$/),recordedAt:_.datetime(),filesSeen:_.datetime().optional(),removedAt:_.datetime().optional()}),Ne=A({version:K(1),entries:G(Ee).max(xe),resetAt:_.datetime().optional()});function Sn(e){if(e==null)return{kind:"none"};let n=Ne.safeParse(e);if(n.success)return{kind:"stored",state:n.data};let t=n.error.issues[0];return{kind:"unreadable",issue:`${t.path.join(".")||"state"}: ${t.message}`}}function j(e){return Array.isArray(e)?`[${e.map(j).join(",")}]`:e!==null&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>`${JSON.stringify(t)}:${j(r)}`).join(",")}}`:JSON.stringify(e)}function C(e){let n=e?.trim();return n||null}function ve(e,n){let t={direction:e.direction,conflictStrategy:e.conflictStrategy,copiesFiles:e.files?!0:void 0,objectApiName:n.objectApiName,operation:n.operation,externalIdField:C(n.externalIdField),where:C(n.where),fieldMappings:n.fieldMappings??[],unmappedSentAsRead:(n.fieldMappings??[]).length>0?!0:void 0,transformRules:n.transformRules??[],excludedFields:n.excludedFields??[],addOnFields:n.addOnFields??[]};return Oe("sha256").update(j(t)).digest("hex")}function wn(e,n,t){let r=ve(e,n);if(t===null)return{read:"full",reason:"not_saved",fingerprint:r};if(t.kind==="unreadable")return{read:"full",reason:"unreadable",fingerprint:r};if(t.kind==="none")return{read:"full",reason:"first_run",fingerprint:r};let o=t.state.entries.find(s=>s.sourceOrgId===e.sourceOrgId&&s.targetOrgId===e.targetOrgId&&s.objectApiName===n.objectApiName);return o?o.fingerprint!==r?{read:"full",reason:"scope_changed",fingerprint:r}:o.removedAt!==void 0?{read:"full",reason:"removed",fingerprint:r}:{read:"delta",since:o.watermark,fingerprint:r,...o.filesSeen!==void 0?{filesSeen:o.filesSeen}:{}}:{read:"full",reason:t.state.resetAt?"reset":"first_run",fingerprint:r}}var $e=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;function Rn(e,n=Te){let t=Date.parse(e);if(!Number.isFinite(t))throw new Error(`Not a watermark: "${e}".`);let r=Math.floor((t-n)/1e3)*1e3;return new Date(r).toISOString().replace(/\.\d{3}Z$/,"Z")}function _n(e){let n=Date.parse(e);if(!Number.isFinite(n))throw new Error(`Not a date: "${e}".`);return new Date(Math.floor(n/1e3)*1e3).toISOString().replace(/\.\d{3}Z$/,"Z")}function Ae(e){if(!$e.test(e)||!Number.isFinite(Date.parse(e)))throw new Error(`Not a SOQL datetime: "${e}".`);return e}function kn(e,n){let t=e?.trim()?D(e):void 0;if(n===void 0)return t;let r=`SystemModstamp > ${Ae(n)}`;return t?`${r} AND (${t})`:r}function De(e){if(typeof e!="string"||e==="")return null;let n=Date.parse(e.replace(/([+-]\d{2})(\d{2})$/,"$1:$2"));return Number.isFinite(n)?new Date(n).toISOString():null}function Fn(e,n,t){let r={query:i=>e.query(i),queryMore:i=>e.queryMore(i)},o={query:i=>e.query(i,{scanAll:!0}),queryMore:i=>e.queryMore(i)},s=()=>{if(t?.aborted)throw new Error("The run was cancelled.")};return{async latestModstamp(i){let d=R(i),y=(await e.query(`SELECT SystemModstamp FROM ${d} ORDER BY SystemModstamp DESC LIMIT 1`)).records[0];if(!y)return null;let g=De(y.SystemModstamp);if(g===null)throw new Error(`${d} answered a SystemModstamp that is not a date.`);return g},async deletedRows(i,d,f){let y=R(i),g=new Set(["Id","SystemModstamp",...d.map(k)]),{records:c,truncated:p}=await F(o,`SELECT ${[...g].join(", ")} FROM ${y} WHERE IsDeleted = true AND (${D(f)})`);return{records:c,truncated:p}},async heldInSource(i,d,f){let y=R(i),g=k(d),c=new Set;for(let p of N(f)){s();let{records:u}=await F(r,`SELECT ${g} FROM ${y} WHERE ${g} IN (${p.map(T).join(", ")})`);for(let l of u){let m=S(l[g]);m!==null&&c.add(m)}}return c},async targetIdsByKey(i,d,f){let y=R(i),g=k(d),c=g==="Id"?"Id":`Id, ${g}`,p=new Map;for(let u of N(f)){s();let{records:l}=await F(n,`SELECT ${c} FROM ${y} WHERE ${g} IN (${u.map(T).join(", ")})`);for(let m of l){let a=S(m[g]);a===null||typeof m.Id!="string"||p.set(a,[...p.get(a)??[],m.Id])}}return p}}}var Pe=new Set(["direct","rename","transform"]);function In(e){let n=e.objectApiName;if(e.operation==="insert"||e.operation==="delete")return{refused:`${n} is written by ${e.operation}, which finds no record by a key: a deleted source record cannot be tied to a target record.`};if(e.operation==="update")return{sourceField:"Id",keyField:"Id"};let t=C(e.externalIdField)??"Id";if((e.addOnFields??[]).some(s=>s.fieldApiName===t))return{refused:`${n}: an add-on writes ${t}, the key the upsert matches on, so it ties no deleted source record to one target record.`};let r=e.fieldMappings??[],o=r.find(s=>s.targetField.toLowerCase()===t.toLowerCase());return!o&&!J(r,e.excludedFields??[]).has(t.toLowerCase())?{sourceField:t,keyField:t}:!o||!Pe.has(o.type)?{refused:`${n}: no source field is carried onto ${t}, the key the upsert matches on, so no deleted source record can be tied to a target record.`}:{sourceField:o.sourceField,keyField:t}}async function On(e,n,t,r,o){let s=n.objectApiName,{records:i,truncated:d}=await e.deletedRows(s,[t.sourceField],r),f={ids:[],read:i.length,stillInSource:0,ambiguous:0,noKey:0,truncated:d};if(i.length===0)return f;let y=[];for(let l of i){let m=l[t.sourceField],a=o(l);if(S(m)===null||S(a)===null){f.noKey++;continue}y.push({raw:m,key:a})}if(y.length===0)return f;let g=t.sourceField==="Id"?new Set:await e.heldInSource(s,t.sourceField,y.map(l=>l.raw)),c=y.filter(l=>g.has(S(l.raw))?(f.stillInSource++,!1):!0);if(c.length===0)return f;let p=await e.targetIdsByKey(s,t.keyField,c.map(l=>l.key)),u=new Set;for(let l of c){let m=p.get(S(l.key))??[];m.length>1?f.ambiguous++:m.length===1&&!u.has(m[0])&&(u.add(m[0]),f.ids.push(m[0]))}return f}function Tn(e,n){let t=[];return e.stillInSource>0&&t.push(`${e.stillInSource} record(s) deleted in the source share their ${n} with a record the source still holds: their target record was kept.`),e.ambiguous>0&&t.push(`${e.ambiguous} record(s) deleted in the source match more than one target record on ${n}: none of those target records was deleted.`),e.noKey>0&&t.push(`${e.noKey} record(s) deleted in the source carry no ${n}: no target record is tied to them.`),e.truncated&&t.push("The source's deleted records were read up to a bound: the rest are read by the next run, from the same watermark."),t}function xn(e,n,t,r,o=0){return{read:e.read,...e.read==="delta"?{since:e.since}:{reason:e.reason},changed:n,deletionsChecked:t!==void 0,deleted:t?.deleted??0,deleteFailed:t?.deleteFailed??0,...t?.error!==void 0?{deletionError:t.error}:{},...r!==void 0?{recorded:r}:{},...o>0?{lookupsOwed:o}:{}}}export{Le as a,je as b,Ce as c,ie as d,O as e,de as f,le as g,We as h,ge as i,te as j,Qe as k,He as l,Ye as m,re as n,S as o,rn as p,on as q,_e as r,sn as s,an as t,dn as u,ln as v,cn as w,Te as x,Sn as y,wn as z,Rn as A,_n as B,Ae as C,kn as D,De as E,Fn as F,In as G,On as H,Tn as I,xn as J};
|
|
7
|
+
import{d as Z}from"./chunk-HFSBDM7B.mjs";import{c as H,g as Y}from"./chunk-OHEOJISY.mjs";import{a as F}from"./chunk-EADHKH3A.mjs";import{g as W,t as Q}from"./chunk-TNT27RBG.mjs";import{a as U,f as D,h as k}from"./chunk-TZE3Y7IQ.mjs";import{a as P}from"./chunk-ICIYL45C.mjs";import{d as J}from"./chunk-WUUKFE2U.mjs";import{O as z,Q as B,T as V,Uc as R}from"./chunk-PMWAFDUB.mjs";import{b as I,k as G,l as A,v as K,z as _}from"./chunk-WZQEK4WT.mjs";function Le(e){let n=new Set;for(let t of e)t.controllerName&&n.add(t.controllerName);return n}function X(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function je(e,n){let t=X(e.precision),r=typeof e.scale=="number"&&e.scale>=0?e.scale:void 0,o=X(e.digits),s=(e.picklistValues??[]).filter(d=>d!==null&&typeof d.value=="string"),i={};if(e.controllerName)for(let d of s)d.active===!1||typeof d.validFor!="string"||(i[d.value]=d.validFor);return{...t!==void 0?{precision:t}:{},...t!==void 0&&r!==void 0?{scale:r}:{},...o!==void 0?{digits:o}:{},...e.unique===!0?{unique:!0}:{},...e.unique===!0&&typeof e.caseSensitive=="boolean"?{caseSensitive:e.caseSensitive}:{},...e.calculated===!0?{calculated:!0}:{},...e.filteredLookupInfo?{filteredLookup:!0}:{},...Object.keys(i).length>0?{validFor:i}:{},...n.has(e.name)&&s.length>0?{controllingValues:s.map(d=>d.value)}:{}}}function Ce(e,n){return e.caseSensitive===!1?n.toLowerCase():n}function M(e,n){if(n<0)return!1;let r=Buffer.from(e,"base64")[n>>3];return r!==void 0&&(r&128>>n%8)!==0}var ie={picklist_value_refused:["map_value","leave_empty","skip_rows","exclude_object","ignore"],dependent_value_invalid:["map_value","leave_empty","exclude_object","ignore"],picklist_value_absent:["map_value","skip_rows","ignore"],required_field_missing:["set_default","exclude_object","ignore"],value_too_long:["truncate","exclude_object","ignore"],number_out_of_range:["exclude_object","ignore"],record_type_unmapped:["map_record_type","exclude_object","ignore"],record_type_unavailable:["map_record_type","exclude_object","ignore"],currency_inactive:["map_value","skip_rows","exclude_object","ignore"],unique_value_collision:["exclude_object","ignore"]};function w(e){return[...ie[e]??["ignore"]]}var se=100,ae=new Set(["longest","colliding"]),O=class{gaps=new Map;recordTypes=new Map;get size(){return this.gaps.size}knowRecordTypes(n,t,r){let o=de(r);o!==void 0&&this.recordTypes.set(n,{...this.recordTypes.get(n),[t]:o})}add(n){let t=z(n.kind,n.objectApiName,n.field,n.recordType,n.value),r=this.gaps.get(t);if(!r){this.gaps.set(t,{...n,id:t,source:"simulation",decisions:[...n.decisions]});return}r.rows+=n.rows,n.decisions.includes("skip_rows")||(r.decisions=r.decisions.filter(s=>s!=="skip_rows"));let o={...n.detail??{},...r.detail??{}};for(let s of ae){let i=r.detail?.[s],d=n.detail?.[s];typeof i=="number"&&typeof d=="number"&&(o[s]=Math.max(i,d))}r.detail=o}list(n){let t=[...this.gaps.keys()],r=[...this.gaps.values()].map(o=>this.withSameDeveloperName(o)).map(o=>B(n,o,t)!==void 0?{...o,detail:{...o.detail??{},ignored:!0}}:o);return V(r)}withSameDeveloperName(n){let t=n.kind==="record_type_unmapped";return le(n,this.recordTypes.get(n.objectApiName)?.[t?"source":"target"])}};function de(e){let n=e.filter(t=>!t.master);if(!n.some(t=>t.namespacePrefix===void 0))return n.map(Z)}function le(e,n){let t=e.kind==="record_type_unmapped"?e.value:e.recordType;if(t===void 0||n===void 0)return e;let r=Y(t);if(!r.namespacePrefix)return e;let o=n.filter(s=>s.developerName===r.developerName&&s.namespacePrefix!==r.namespacePrefix).map(s=>H(s.namespacePrefix,s.developerName));return o.length===0?e:{...e,detail:{...e.detail??{},sameDeveloperName:[...new Set(o)].sort()}}}function L(e){return[...new Set(e)].sort().slice(0,se)}function We(e,n,t){let r=[];for(let o of n){if(o.field===P)continue;let s=t(o);for(let i of o.values)r.push({kind:"picklist_value_refused",severity:"warning",objectApiName:e,field:o.field,...o.recordType!==void 0?{recordType:o.recordType}:{},value:i,rows:1,detail:{reason:o.reason,...s?{allowed:L(s)}:{},...o.controllingField?{controllingField:o.controllingField}:{},...o.replacedBy!==void 0?{replacement:o.replacedBy}:{}},decisions:w("picklist_value_refused").filter(d=>d!=="skip_rows"||o.reason!=="controlling-value"),defaultDecision:o.replacedBy!==void 0?"map_value":"leave_empty"})}return r}var ce=new Set(["string","textarea","email","phone","url","encryptedstring"]),ue=new Set(["double","currency","percent"]);function fe(e){return e==null||e===""}function ne(e){return e.createable&&e.nillable===!1&&e.defaultedOnCreate!==!0&&e.calculated!==!0&&e.type!=="boolean"}function pe(e,n,t){return e==="Account"&&n==="Name"&&Q(t)}function ge(e,n,t,r){return r.filter(o=>ne(o)&&fe(n[o.name])&&!pe(e,o.name,t))}function me(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||e.trim()==="")return;let n=Number(e);return Number.isFinite(n)?n:void 0}function ee(e){if(e.type==="int"&&e.digits!==void 0)return e.digits;if(e.precision!==void 0)return e.precision-(e.scale??0)}function ye(e,n){return e?e.type==="boolean"?n===!0||n==="true"?1:n===!1||n==="false"?0:-1:typeof n!="string"||n===""?-1:(e.controllingValues??[]).indexOf(n):-1}function te(e,n){let{objectApiName:t,rows:r,targetFields:o,picklistValuesByField:s,picklistFields:i}=e,d=new Map(o.map(u=>[u.name,u])),f=o.filter(ne),y=o.filter(u=>u.createable&&ce.has(u.type??"")&&(u.length??0)>0),g=o.filter(u=>u.createable&&(ue.has(u.type??"")||u.type==="int")&&ee(u)!==void 0),c=[...i].filter(([u,l])=>l.anyValue===!0&&s?.has(u)===!0),p=o.filter(u=>u.createable&&u.controllerName!==void 0&&u.validFor!==void 0);for(let{payload:u,source:l,typed:m}of r){for(let a of ge(t,u,l,f))n.add({kind:"required_field_missing",severity:"blocking",objectApiName:t,field:a.name,rows:1,...a.type?{detail:{type:a.type}}:{},decisions:w("required_field_missing")});for(let a of y){let h=u[a.name],b=a.length??0;typeof h!="string"||h.length<=b||n.add({kind:"value_too_long",severity:"blocking",objectApiName:t,field:a.name,rows:1,detail:{length:b,longest:h.length},decisions:w("value_too_long")})}for(let a of g){let h=me(u[a.name]),b=ee(a);h===void 0||b===void 0||Math.abs(Math.trunc(h))<10**b||n.add({kind:"number_out_of_range",severity:"blocking",objectApiName:t,field:a.name,rows:1,detail:{...a.precision!==void 0?{precision:a.precision}:{},...a.scale!==void 0?{scale:a.scale}:{},...a.type==="int"&&a.digits!==void 0?{digits:a.digits}:{}},decisions:w("number_out_of_range")})}for(let[a,h]of c){let b=u[a];if(typeof b!="string"||b==="")continue;let x=s?.get(a),v=h.multi?b.split(";"):[b];for(let E of new Set(v))x?.has(E)||n.add({kind:"picklist_value_absent",severity:"info",objectApiName:t,field:a,value:E,rows:1,decisions:w("picklist_value_absent")})}if(!m)for(let a of p){let h=u[a.name];if(typeof h!="string"||h==="")continue;let b=d.get(a.controllerName??""),x=ye(b,u[a.controllerName??""]),v=i.get(a.name)?.restricted===!0,E=i.get(a.name)?.multi?h.split(";"):[h];for(let q of new Set(E)){let $=a.validFor?.[q];$!==void 0&&(x>=0&&M($,x)||n.add({kind:"dependent_value_invalid",severity:v?"blocking":"warning",objectApiName:t,field:a.name,value:q,rows:1,detail:{controllingField:a.controllerName??"",allowed:L((b?.controllingValues??[]).filter((Me,oe)=>M($,oe)))},decisions:w("dependent_value_invalid")}))}}}}function Qe(e,n,t,r){return{kind:"currency_inactive",severity:"warning",objectApiName:e,field:P,value:n,rows:t,...r&&r.to.length>0?{detail:{replacement:r.to.join(", "),...r.converted.length>0?{amountsConverted:[...r.converted]}:{},...r.asRead?{amountsAsRead:!0}:{}}}:{},decisions:w("currency_inactive"),defaultDecision:"map_value"}}function He(e,n,t,r){return{kind:"unique_value_collision",severity:"warning",objectApiName:e,field:n,rows:t,detail:{colliding:r,linkedToTheRecordItNames:!0},decisions:w("unique_value_collision"),defaultDecision:"ignore"}}function Ye(e,n,t,r,o){return{kind:e,severity:"blocking",objectApiName:n,field:"RecordTypeId",...e==="record_type_unavailable"?{recordType:t}:{value:t},rows:r,detail:{mapTo:L(o)},decisions:w(e)}}var he=10;function re(e){switch(e.operation){case"insert":return null;case"upsert":return e.externalIdField??"Id";case"update":case"delete":return"Id"}}function S(e){if(e==null||typeof e!="string"&&typeof e!="number"&&typeof e!="boolean")return null;let n=String(e);return n===""?null:n.toLowerCase()}function T(e){return typeof e=="number"&&Number.isFinite(e)?String(e):typeof e=="boolean"?e?"true":"false":`'${U(String(e))}'`}var be=200,Se=4e3;function N(e){let n=[],t=[],r=0;for(let o of e){let s=T(o).length+2;t.length>0&&(t.length>=be||r+s>Se)&&(n.push(t),t=[],r=0),t.push(o),r+=s}return t.length>0&&n.push(t),n}function rn(e,n){return async(t,r,o,s)=>{let i=R(r.objectApiName),d=k(o),f=new Map;for(let y of N(s)){if(n?.aborted)throw new Error("The simulation was cancelled.");let{records:g}=await F(e,`SELECT ${d} FROM ${i} WHERE ${d} IN (${y.map(T).join(", ")})`);for(let c of g){let p=S(c[d]);p!==null&&f.set(p,(f.get(p)??0)+1)}}return f}}var we=new Set(["attributes","Id"]);function Re(e,n,t,r){return n?e.conflictFields.filter(o=>o!==t&&!we.has(o)&&o in n&&(r===null||r.has(o))):[]}var on=new Set(["noKey","notInTarget","ambiguous"]);function _e(e,n,t){let r=e.operation,o=re(e);if(o===null)return"insert";let s=S(n[o]);if(s===null)return r==="delete"?"notSent":"noKey";let i=t.get(s)??0;return r==="upsert"?i===0?o.toLowerCase()==="id"?"notInTarget":"insert":i===1?"update":"ambiguous":i===0?"notInTarget":r==="update"?"update":"delete"}var ke=1e4;function sn(e,n,t){let r=e>t?ke:Math.max(1,n);return{callOf:o=>Math.floor(o/r),job:e>t}}function an(e,n,t,r){let o=new Map;n.forEach((c,p)=>{if(c===null)return;let u=`${r.callOf(p)}\0${c}`,l=o.get(u);l?l.push(p):o.set(u,[p])});let s=new Set;for(let c of o.values())if(c.length>1)for(let p of c)s.add(p);let i=new Map,d=new Set,f=0;n.forEach((c,p)=>{if(c===null||s.has(p))return;let u=r.callOf(p);if(i.get(c)===void 0){t[p]==="insert"&&i.set(c,u);return}r.job?f++:t[p]==="insert"&&d.add(p)});let y=[],g=[];if(s.size>0){let c=`${s.size} record(s) carry the ${e} of another record of the same call: an upsert finds its record by its key, and the target refuses every record of a call whose key another carries (DUPLICATE_VALUE: Duplicate external id specified).`;y.push(c),g.push({code:"DUPLICATE_VALUE",rows:s.size,note:c})}return d.size>0&&y.push(`${d.size} record(s) carry the ${e} of a record sent in an earlier call: the upsert finds the record that one created and updates it with theirs.`),f>0&&y.push(`${f} record(s) carry the ${e} of a record in another batch of the Bulk API job: the platform may write the batches at once, so whether each updates the record the other created or creates one of its own cannot be told before the run.`),{refused:s,updated:d,notes:y,refusedFor:g}}function dn(e){let{objectConfig:n,records:t,inTarget:r}=e,o=n.operation,s=re(n),i={insert:0,update:0,delete:0,noKey:0,notInTarget:0,notSent:0,ambiguous:0},d=new Set;t.forEach((l,m)=>{let a=e.simulated?.[m]??_e(n,l,r);i[a]++,(a==="insert"||a==="update")&&d.add(m)});let f=e.leftOut.map(({why:l,count:m})=>W(m,l));i.noKey>0&&f.push(o==="upsert"?`${i.noKey} record(s) carry no value in ${s}: an upsert matches on it, and the target refuses a record without one.`:`${i.noKey} record(s) carry no Id: an update finds its record by Id, and the target refuses one without it.`),i.notInTarget>0&&f.push(`${i.notInTarget} record(s) carry an Id the target does not hold: ${o==="upsert"?"an upsert on the Id finds no record there and creates none":`${o==="update"?"an update":"a delete"} finds no record there`}, and the target refuses it. Two orgs share a record's Id only when it was copied with the org.`),i.ambiguous>0&&f.push(`${i.ambiguous} record(s) match more than one record of the target on ${s}: an upsert finds no single record to update, and the target refuses it.`),i.notSent>0&&f.push(`${i.notSent} record(s) carry no Id: a delete sends ids alone, so the run leaves them out.`);let y=new Map;e.unsettled.forEach((l,m)=>{let a=String(l[e.matchField]??"");a&&d.has(m)&&y.set(a,l)});let g=new Map,c=0;for(let l of e.conflicts){let m=Re(l,y.get(l.recordId),e.matchField,e.writable);if(m.length!==0){c++;for(let a of m)g.set(a,(g.get(a)??0)+1)}}let p=[...g].sort(([l,m],[a,h])=>h-m||l.localeCompare(a)).slice(0,he).map(([l])=>l),u=e.leftOut.reduce((l,{count:m})=>l+m,0);return{objectApiName:n.objectApiName,operation:o,read:e.read,insert:i.insert,update:i.update,delete:i.delete,skipped:u+i.notSent,refused:i.noKey+i.notInTarget+i.ambiguous,conflicts:c,conflictFields:p,notes:f}}var Fe={required_field_missing:"REQUIRED_FIELD_MISSING",value_too_long:"STRING_TOO_LONG",number_out_of_range:"NUMBER_OUTSIDE_VALID_RANGE"};function Ie(e){let n=e.field??"";switch(e.kind){case"required_field_missing":return`${e.rows} record(s) leave ${n} empty, which the target requires: it refuses them (REQUIRED_FIELD_MISSING).`;case"value_too_long":return`${e.rows} record(s) hold a ${n} longer than the ${String(e.detail?.length)} characters the target's field takes (the longest, ${String(e.detail?.longest)}): it refuses them (STRING_TOO_LONG).`;case"number_out_of_range":return`${e.rows} record(s) hold a ${n} larger than the target's field takes: it refuses them (NUMBER_OUTSIDE_VALID_RANGE).`;default:return}}function ln(e,n,t){let r=new Set,o=new O;n.forEach(({payload:i,source:d,creates:f},y)=>{let g=new O;te({objectApiName:e,rows:[{payload:i,source:d,typed:!0}],targetFields:t,picklistValuesByField:null,picklistFields:new Map},g);let c=g.list(new Set).filter(p=>p.severity==="blocking"&&(f||p.kind!=="required_field_missing"));if(c.length!==0){r.add(y);for(let p of c)o.add(p)}});let s=o.list(new Set).flatMap(i=>{let d=Ie(i),f=Fe[i.kind];return d&&f?[{code:f,rows:i.rows,note:d}]:[]});return{refused:r,notes:s.map(({note:i})=>i),refusedFor:s}}function cn(e,n){let t=new Set,r=new Set,o=[],s=[];for(let[i,d]of n){let f=new Set,y=0,g=0,c=0;if(e.forEach((u,l)=>{let m=S(u[i]);if(m===null)return;let a=d.get(m)??0;a===1?(y++,r.add(l)):a>1?(g++,t.add(l)):f.has(m)&&(c++,t.add(l)),f.add(m)}),y>0&&o.push(`LINKED_TO_EXISTING: ${y} record(s) hold a ${i} the target keeps unique, which a record of the target holds already: it refuses them as duplicates (DUPLICATE_VALUE) and names that record, which the run links them to \u2014 what it writes under them points at that record.`),g+c===0)continue;let p=`${g+c} record(s) hold a ${i} the target keeps unique, which `+[g>0?`several records of the target hold already (${g})`:"",c>0?`a record sent before them holds (${c})`:""].filter(Boolean).join(" or ")+": it refuses them (DUPLICATE_VALUE).";o.push(p),s.push({code:"DUPLICATE_VALUE",rows:g+c,note:p})}for(let i of t)r.delete(i);return{refused:t,linked:r,notes:o,refusedFor:s}}import{createHash as Oe}from"node:crypto";var Te=5*6e4,xe=500,Ee=A({sourceOrgId:I().min(1).max(200),targetOrgId:I().min(1).max(200),objectApiName:I().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),watermark:_.datetime(),fingerprint:I().regex(/^[0-9a-f]{64}$/),recordedAt:_.datetime(),filesSeen:_.datetime().optional(),removedAt:_.datetime().optional()}),Ne=A({version:K(1),entries:G(Ee).max(xe),resetAt:_.datetime().optional()});function Sn(e){if(e==null)return{kind:"none"};let n=Ne.safeParse(e);if(n.success)return{kind:"stored",state:n.data};let t=n.error.issues[0];return{kind:"unreadable",issue:`${t.path.join(".")||"state"}: ${t.message}`}}function j(e){return Array.isArray(e)?`[${e.map(j).join(",")}]`:e!==null&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>`${JSON.stringify(t)}:${j(r)}`).join(",")}}`:JSON.stringify(e)}function C(e){let n=e?.trim();return n||null}function ve(e,n){let t={direction:e.direction,conflictStrategy:e.conflictStrategy,copiesFiles:e.files?!0:void 0,objectApiName:n.objectApiName,operation:n.operation,externalIdField:C(n.externalIdField),where:C(n.where),fieldMappings:n.fieldMappings??[],unmappedSentAsRead:(n.fieldMappings??[]).length>0?!0:void 0,transformRules:n.transformRules??[],excludedFields:n.excludedFields??[],addOnFields:n.addOnFields??[]};return Oe("sha256").update(j(t)).digest("hex")}function wn(e,n,t){let r=ve(e,n);if(t===null)return{read:"full",reason:"not_saved",fingerprint:r};if(t.kind==="unreadable")return{read:"full",reason:"unreadable",fingerprint:r};if(t.kind==="none")return{read:"full",reason:"first_run",fingerprint:r};let o=t.state.entries.find(s=>s.sourceOrgId===e.sourceOrgId&&s.targetOrgId===e.targetOrgId&&s.objectApiName===n.objectApiName);return o?o.fingerprint!==r?{read:"full",reason:"scope_changed",fingerprint:r}:o.removedAt!==void 0?{read:"full",reason:"removed",fingerprint:r}:{read:"delta",since:o.watermark,fingerprint:r,...o.filesSeen!==void 0?{filesSeen:o.filesSeen}:{}}:{read:"full",reason:t.state.resetAt?"reset":"first_run",fingerprint:r}}var $e=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;function Rn(e,n=Te){let t=Date.parse(e);if(!Number.isFinite(t))throw new Error(`Not a watermark: "${e}".`);let r=Math.floor((t-n)/1e3)*1e3;return new Date(r).toISOString().replace(/\.\d{3}Z$/,"Z")}function _n(e){let n=Date.parse(e);if(!Number.isFinite(n))throw new Error(`Not a date: "${e}".`);return new Date(Math.floor(n/1e3)*1e3).toISOString().replace(/\.\d{3}Z$/,"Z")}function Ae(e){if(!$e.test(e)||!Number.isFinite(Date.parse(e)))throw new Error(`Not a SOQL datetime: "${e}".`);return e}function kn(e,n){let t=e?.trim()?D(e):void 0;if(n===void 0)return t;let r=`SystemModstamp > ${Ae(n)}`;return t?`${r} AND (${t})`:r}function De(e){if(typeof e!="string"||e==="")return null;let n=Date.parse(e.replace(/([+-]\d{2})(\d{2})$/,"$1:$2"));return Number.isFinite(n)?new Date(n).toISOString():null}function Fn(e,n,t){let r={query:i=>e.query(i),queryMore:i=>e.queryMore(i)},o={query:i=>e.query(i,{scanAll:!0}),queryMore:i=>e.queryMore(i)},s=()=>{if(t?.aborted)throw new Error("The run was cancelled.")};return{async latestModstamp(i){let d=R(i),y=(await e.query(`SELECT SystemModstamp FROM ${d} ORDER BY SystemModstamp DESC LIMIT 1`)).records[0];if(!y)return null;let g=De(y.SystemModstamp);if(g===null)throw new Error(`${d} answered a SystemModstamp that is not a date.`);return g},async deletedRows(i,d,f){let y=R(i),g=new Set(["Id","SystemModstamp",...d.map(k)]),{records:c,truncated:p}=await F(o,`SELECT ${[...g].join(", ")} FROM ${y} WHERE IsDeleted = true AND (${D(f)})`);return{records:c,truncated:p}},async heldInSource(i,d,f){let y=R(i),g=k(d),c=new Set;for(let p of N(f)){s();let{records:u}=await F(r,`SELECT ${g} FROM ${y} WHERE ${g} IN (${p.map(T).join(", ")})`);for(let l of u){let m=S(l[g]);m!==null&&c.add(m)}}return c},async targetIdsByKey(i,d,f){let y=R(i),g=k(d),c=g==="Id"?"Id":`Id, ${g}`,p=new Map;for(let u of N(f)){s();let{records:l}=await F(n,`SELECT ${c} FROM ${y} WHERE ${g} IN (${u.map(T).join(", ")})`);for(let m of l){let a=S(m[g]);a===null||typeof m.Id!="string"||p.set(a,[...p.get(a)??[],m.Id])}}return p}}}var Pe=new Set(["direct","rename","transform"]);function In(e){let n=e.objectApiName;if(e.operation==="insert"||e.operation==="delete")return{refused:`${n} is written by ${e.operation}, which finds no record by a key: a deleted source record cannot be tied to a target record.`};if(e.operation==="update")return{sourceField:"Id",keyField:"Id"};let t=C(e.externalIdField)??"Id";if((e.addOnFields??[]).some(s=>s.fieldApiName===t))return{refused:`${n}: an add-on writes ${t}, the key the upsert matches on, so it ties no deleted source record to one target record.`};let r=e.fieldMappings??[],o=r.find(s=>s.targetField.toLowerCase()===t.toLowerCase());return!o&&!J(r,e.excludedFields??[]).has(t.toLowerCase())?{sourceField:t,keyField:t}:!o||!Pe.has(o.type)?{refused:`${n}: no source field is carried onto ${t}, the key the upsert matches on, so no deleted source record can be tied to a target record.`}:{sourceField:o.sourceField,keyField:t}}async function On(e,n,t,r,o){let s=n.objectApiName,{records:i,truncated:d}=await e.deletedRows(s,[t.sourceField],r),f={ids:[],read:i.length,stillInSource:0,ambiguous:0,noKey:0,truncated:d};if(i.length===0)return f;let y=[];for(let l of i){let m=l[t.sourceField],a=o(l);if(S(m)===null||S(a)===null){f.noKey++;continue}y.push({raw:m,key:a})}if(y.length===0)return f;let g=t.sourceField==="Id"?new Set:await e.heldInSource(s,t.sourceField,y.map(l=>l.raw)),c=y.filter(l=>g.has(S(l.raw))?(f.stillInSource++,!1):!0);if(c.length===0)return f;let p=await e.targetIdsByKey(s,t.keyField,c.map(l=>l.key)),u=new Set;for(let l of c){let m=p.get(S(l.key))??[];m.length>1?f.ambiguous++:m.length===1&&!u.has(m[0])&&(u.add(m[0]),f.ids.push(m[0]))}return f}function Tn(e,n){let t=[];return e.stillInSource>0&&t.push(`${e.stillInSource} record(s) deleted in the source share their ${n} with a record the source still holds: their target record was kept.`),e.ambiguous>0&&t.push(`${e.ambiguous} record(s) deleted in the source match more than one target record on ${n}: none of those target records was deleted.`),e.noKey>0&&t.push(`${e.noKey} record(s) deleted in the source carry no ${n}: no target record is tied to them.`),e.truncated&&t.push("The source's deleted records were read up to a bound: the rest are read by the next run, from the same watermark."),t}function xn(e,n,t,r,o=0){return{read:e.read,...e.read==="delta"?{since:e.since}:{reason:e.reason},changed:n,deletionsChecked:t!==void 0,deleted:t?.deleted??0,deleteFailed:t?.deleteFailed??0,...t?.error!==void 0?{deletionError:t.error}:{},...r!==void 0?{recorded:r}:{},...o>0?{lookupsOwed:o}:{}}}export{Le as a,je as b,Ce as c,ie as d,O as e,de as f,le as g,We as h,ge as i,te as j,Qe as k,He as l,Ye as m,re as n,S as o,rn as p,on as q,_e as r,sn as s,an as t,dn as u,ln as v,cn as w,Te as x,Sn as y,wn as z,Rn as A,_n as B,Ae as C,kn as D,De as E,Fn as F,In as G,On as H,Tn as I,xn as J};
|
|
@@ -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 W}from"./chunk-CA5NAXSU.mjs";import{b as I,e as z,l as F,u as U}from"./chunk-WZQEK4WT.mjs";function p(n){return`${n.op}\0${n.objectApiName}`}var j=class{entries=new Map;keys=new Map;of(t){let e=this.entries.get(p(t));return!e||e.spent?200:e.size}wasRefused(t){return this.entries.has(p(t))}wasCut(t){let e=this.entries.get(p(t));return e!==void 0&&e.size<200}firstRefusal(t,e,r){if(this.entries.has(p(t)))return;let o=this.entry(t,e);o.limit=r?.limit,o.automation=r?.automation,o.event=r?.event}refusedAt(t,e,r){this.firstRefusal(t,e,r);let o=this.entry(t,e);return o.size=Math.min(o.size,Math.max(1,Math.ceil(e/2))),this.of(t)}probes(t){return this.entries.get(p(t))?.probes??0}probed(t){let e=this.entries.get(p(t));e&&e.probes++}keepWhole(t){let e=this.entries.get(p(t));e&&(e.wholeAlone=!0)}isKeptWhole(t){return this.entries.get(p(t))?.wholeAlone===!0}spend(t){let e=this.entries.get(p(t));e&&(e.spent=!0)}isSpent(t){return this.entries.get(p(t))?.spent===!0}countExtraCalls(t,e){let r=this.entries.get(p(t));r&&e>0&&(r.extraCalls+=e)}countSmallCallRows(t,e){let r=this.entries.get(p(t));r&&e>0&&(r.rows+=e)}countNoted(t,e,r=1){let o=this.entries.get(p(t));!o||r<=0||(e===T?o.alone+=r:e===L?o.notSplit+=r:o.keptWhole+=r)}report(t){let e=this.entries.get(p(t));if(e)return{objectApiName:t.objectApiName,op:t.op,from:e.from,to:e.size,rows:e.rows,extraCalls:e.extraCalls,...e.limit!==void 0?{limit:e.limit}:{},...e.automation!==void 0?{automation:e.automation}:{},...e.event!==void 0?{event:e.event}:{},alone:e.alone,notSplit:e.notSplit,keptWhole:e.keptWhole,wholeAlone:e.wholeAlone,spent:e.spent}}reports(t){let e=[];for(let r of this.keys.values()){if(t!==void 0&&r.op!==t)continue;let o=this.report(r);o&&e.push(o)}return e}entry(t,e){let r=p(t),o=this.entries.get(r);return o||(o={size:200,from:e,spent:!1,wholeAlone:!1,probes:0,rows:0,extraCalls:0,alone:0,notSplit:0,keptWhole:0},this.entries.set(r,o),this.keys.set(r,{objectApiName:t.objectApiName,op:t.op})),o}};function E(n){return Math.max(0,Math.floor(Number.isFinite(n)?n:0))}var J=class{grantedCalls;perObject;takenInAll=0;byObject=new Map;constructor(t=2e3,e=500){this.grantedCalls=E(t),this.perObject=E(e)}get granted(){return this.grantedCalls}limitTo(t){this.grantedCalls=Math.min(this.grantedCalls,E(t))}left(t){let e=this.byObject.get(t.objectApiName)??0;return Math.max(0,Math.min(this.grantedCalls-this.takenInAll,this.perObject-e))}take(t,e){let r=Math.max(0,Math.min(Math.floor(e),this.left(t)));return r>0&&(this.takenInAll+=r,this.byObject.set(t.objectApiName,(this.byObject.get(t.objectApiName)??0)+r)),r}get spent(){return this.takenInAll}taken(t){return this.byObject.get(t.objectApiName)??0}};function se(n=2e3){return{sizes:new j,allowance:new J(n)}}function D(n,t){let e=Math.floor((n-t)/2);return Number.isFinite(e)?Math.min(2e3,Math.max(0,e)):0}function oe(n){return n.remaining===void 0?{}:{splitAllowance:D(n.remaining,n.estimate)}}function
|
|
7
|
+
import{b as W}from"./chunk-CA5NAXSU.mjs";import{b as I,e as z,l as F,u as U}from"./chunk-WZQEK4WT.mjs";function p(n){return`${n.op}\0${n.objectApiName}`}var j=class{entries=new Map;keys=new Map;of(t){let e=this.entries.get(p(t));return!e||e.spent?200:e.size}wasRefused(t){return this.entries.has(p(t))}wasCut(t){let e=this.entries.get(p(t));return e!==void 0&&e.size<200}firstRefusal(t,e,r){if(this.entries.has(p(t)))return;let o=this.entry(t,e);o.limit=r?.limit,o.automation=r?.automation,o.event=r?.event}refusedAt(t,e,r){this.firstRefusal(t,e,r);let o=this.entry(t,e);return o.size=Math.min(o.size,Math.max(1,Math.ceil(e/2))),this.of(t)}probes(t){return this.entries.get(p(t))?.probes??0}probed(t){let e=this.entries.get(p(t));e&&e.probes++}keepWhole(t){let e=this.entries.get(p(t));e&&(e.wholeAlone=!0)}isKeptWhole(t){return this.entries.get(p(t))?.wholeAlone===!0}spend(t){let e=this.entries.get(p(t));e&&(e.spent=!0)}isSpent(t){return this.entries.get(p(t))?.spent===!0}countExtraCalls(t,e){let r=this.entries.get(p(t));r&&e>0&&(r.extraCalls+=e)}countSmallCallRows(t,e){let r=this.entries.get(p(t));r&&e>0&&(r.rows+=e)}countNoted(t,e,r=1){let o=this.entries.get(p(t));!o||r<=0||(e===T?o.alone+=r:e===L?o.notSplit+=r:o.keptWhole+=r)}report(t){let e=this.entries.get(p(t));if(e)return{objectApiName:t.objectApiName,op:t.op,from:e.from,to:e.size,rows:e.rows,extraCalls:e.extraCalls,...e.limit!==void 0?{limit:e.limit}:{},...e.automation!==void 0?{automation:e.automation}:{},...e.event!==void 0?{event:e.event}:{},alone:e.alone,notSplit:e.notSplit,keptWhole:e.keptWhole,wholeAlone:e.wholeAlone,spent:e.spent}}reports(t){let e=[];for(let r of this.keys.values()){if(t!==void 0&&r.op!==t)continue;let o=this.report(r);o&&e.push(o)}return e}entry(t,e){let r=p(t),o=this.entries.get(r);return o||(o={size:200,from:e,spent:!1,wholeAlone:!1,probes:0,rows:0,extraCalls:0,alone:0,notSplit:0,keptWhole:0},this.entries.set(r,o),this.keys.set(r,{objectApiName:t.objectApiName,op:t.op})),o}};function E(n){return Math.max(0,Math.floor(Number.isFinite(n)?n:0))}var J=class{grantedCalls;perObject;takenInAll=0;byObject=new Map;constructor(t=2e3,e=500){this.grantedCalls=E(t),this.perObject=E(e)}get granted(){return this.grantedCalls}limitTo(t){this.grantedCalls=Math.min(this.grantedCalls,E(t))}left(t){let e=this.byObject.get(t.objectApiName)??0;return Math.max(0,Math.min(this.grantedCalls-this.takenInAll,this.perObject-e))}take(t,e){let r=Math.max(0,Math.min(Math.floor(e),this.left(t)));return r>0&&(this.takenInAll+=r,this.byObject.set(t.objectApiName,(this.byObject.get(t.objectApiName)??0)+r)),r}get spent(){return this.takenInAll}taken(t){return this.byObject.get(t.objectApiName)??0}};function se(n=2e3){return{sizes:new j,allowance:new J(n)}}function D(n,t){let e=Math.floor((n-t)/2);return Number.isFinite(e)?Math.min(2e3,Math.max(0,e)):0}function oe(n){return n.remaining===void 0?{}:{splitAllowance:D(n.remaining,n.estimate)}}function v(n,t,e,r){if(r<=0||n.isSpent(e))return 0;let o=t.take(e,r);return n.countExtraCalls(e,o),o<r&&n.spend(e),o}var T="alone",L="notSplit",N="keptWhole",Q="Sent on its own, the record still made the target's automation hit a Salesforce limit: the automation does too much for this record alone \u2014 fix it, or have it honour the bypass Forge's automation mute sets.",V="Not sent in smaller calls: records of the same object sent on their own were refused for a Salesforce limit too, so a smaller call would not take it \u2014 fix the target's automation, or have it honour the bypass Forge's automation mute sets.";function B(n,t){return n>0?`the ${t} had spent the ${n} smaller calls it allows itself`:`what the org has left today allowed the ${t} none`}function q(n,t="run"){return`Not sent in smaller calls: ${B(n,t)}.`}function ie(n,t,e="run"){return n===T?Q:n===N?V:q(t,e)}function M(n){return`${n} ${n===1?"call":"calls"} more`}function X(n){return`${n} ${n===1?"record":"records"}`}function Y(n){return n.automation===void 0?"The target's automation":n.event===void 0?n.automation:`${n.automation} (${n.event})`}function ae(n){let t=`${Y(n)} hit ${n.limit??"a Salesforce limit"} on a call of ${n.from}`;return n.wholeAlone?`${t}, and ${X(n.alone)} sent on ${n.alone===1?"its":"their"} own were refused too: not sent in smaller calls, ${M(n.extraCalls)}.`:n.to<200&&n.rows>0?`${t}: sent ${n.to} at a time, ${M(n.extraCalls)}.`:n.extraCalls>0?`${t}: ${M(n.extraCalls)}.`:`${t}.`}function le(n,t,e="run"){return`${n} not sent in smaller calls: ${B(t,e)}.`}function ue(n,t){let e=n.perObject-n.taken(t),r=n.granted-n.spent;return e<r?n.perObject:n.granted}function ee(n,t,e=200){return n<=t?!1:Math.ceil(n/e)===Math.ceil((n-t)/e)}var te=new Set;async function ce(n,t){let{key:e,sizes:r,allowance:o}=t,c=Math.min(t.maxSize??200,200),h=[],m,f=0,S=()=>[...h.flatMap(s=>s.items),...m?.items??[],...n.slice(f)],K=()=>{let s=Math.min(c,r.of(e)),l=s<c,g=t.pricedAs==="job"||ee(n.length-f,s,c);l&&g&&(t.paid&&t.paid.calls>0?t.paid.calls--:v(r,o,e,1)===0&&(s=c,l=!1));let i=n.slice(f,f+s);return f+=i.length,{items:i,reduced:l}},A=async s=>{let l=m;if(m=void 0,!l||l.items.length===0)return;r.countNoted(e,s,l.items.length);let g=new Map(l.items.map((i,d)=>[d,s]));try{await t.settle(l.items,l.answers,te,g,!0)}catch(i){throw t.onThrow?.(S(),i),i}},k=async()=>{let s=m;if(!s)return;if(s.items.length===0){m=void 0;return}let l=r.refusedAt(e,s.from,s.cause),g=v(r,o,e,Math.ceil(s.items.length/l)),i=Math.min(s.items.length,g*l),d=[];for(let b=0;b<i;b+=l)d.push({items:s.items.slice(b,Math.min(i,b+l)),reduced:!0});h.unshift(...d),m={...s,items:s.items.slice(i),answers:s.answers.slice(i)},await A(L)},_=async()=>{let s=m;if(!s||s.items.length===0){m=void 0;return}if(v(r,o,e,1)===0){await A(L);return}r.probed(e),h.unshift({items:[s.items[0]],reduced:!0,probe:!0}),m={...s,items:s.items.slice(1),answers:s.answers.slice(1)}},P=!0,w=t.refusedIn;if(w&&n.length>0){if(f=n.length,P=!1,!r.wasRefused(e)){r.firstRefusal(e,w.from,w.cause);let s=r.report(e);s&&t.onFirstRefusal?.(s)}m={items:[...n],answers:[...w.answers],from:w.from,...w.cause?{cause:w.cause}:{}},r.isSpent(e)?await A(L):r.isKeptWhole(e)?await A(N):!r.wasCut(e)&&r.probes(e)<2?await _():await k()}for(;;){let s;if(P){if(n.length===0)return{};s=K()}else{if(s=h.shift()??(f<n.length?K():void 0),!s)return{};try{if(await t.beforeEachSend?.()==="stop")return{stopped:{part:s.items,rest:S(),sent:!1}}}catch(u){throw t.onThrow?.([...s.items,...S()],u),u}}P=!1;let l;try{l=await t.send(s.items)}catch(u){throw t.onThrow?.([...s.items,...S()],u),u}if(l==="stop")return{stopped:{part:s.items,rest:S(),sent:!0}};let{answers:g}=l,i=s.items,d=[],b;for(let u=0;u<i.length;u++){let a=t.limited(g[u],i[u]);a&&(d.push(u),b??=a)}let R=new Set,C=new Map,x;if(s.probe)d.length>0?(C.set(0,T),x=r.probes(e)<2&&(m?.items.length??0)>0?_:async()=>{r.probes(e)>=2&&r.keepWhole(e),await A(N)}):x=k;else if(d.length>0){if(!r.wasRefused(e)){r.firstRefusal(e,i.length,b);let a=r.report(e);a&&t.onFirstRefusal?.(a)}let u=!r.wasCut(e)&&!r.isKeptWhole(e)&&r.probes(e)<2;if(i.length===1)C.set(0,T),u&&!r.isSpent(e)&&(r.probed(e),r.probes(e)>=2&&r.keepWhole(e));else if(r.isSpent(e))for(let a of d)C.set(a,L);else if(r.isKeptWhole(e))for(let a of d)C.set(a,N);else if(u){for(let a of d)R.add(a);m={items:d.map(a=>i[a]),answers:d.map(a=>g[a]),from:i.length,...b?{cause:b}:{}},x=_}else{let a=r.refusedAt(e,i.length,b),Z=v(r,o,e,Math.ceil(d.length/a)),O=d.slice(0,Z*a);for(let y of O)R.add(y);for(let y of d.slice(O.length))C.set(y,L);let $=[];for(let y=0;y<O.length;y+=a)$.push({items:O.slice(y,y+a).map(H=>i[H]),reduced:!0});h.unshift(...$)}}for(let u of C.values())r.countNoted(e,u);s.reduced&&r.countSmallCallRows(e,i.length-R.size);try{await t.settle(i,g,R,C)}catch(u){throw t.onThrow?.(S(),u),u}await x?.()}}var ne=60*6e4,re=F({state:U(["Open","UploadComplete","InProgress","JobComplete","Failed","Aborted"]),numberRecordsProcessed:z().int().nonnegative().optional(),errorMessage:I().nullish(),systemModstamp:I().optional(),createdDate:I().optional()});function G(n,t){let e=re.safeParse(t);if(e.success)return e.data;let r=typeof t=="object"&&t!==null&&"state"in t?String(JSON.stringify(t.state)):"none";throw new Error(`The org's answer about Bulk API job ${n||"(no id)"} is not an ingest job's state (state: ${r})`)}async function fe(n,t,e={}){let r=e.now??(()=>Date.now());try{let o=n.bulk2.job("ingest",{id:t}),c=G(t,await o.check());if(c.state==="Open"){let h=Date.parse(c.createdDate??""),m=e.openGraceMs??ne,f=m-(r()-h);if(Number.isFinite(h)&&(f>0||e.leaveOpen))return{state:"running",info:c,openUntil:new Date(h+m).toISOString(),graceLeftMs:Math.max(0,f)};if(e.leaveOpen)return{state:"running",info:c};if(!await o.abort().then(()=>!1,()=>!0)&&m>0)return{state:"never-closed"};if(c=G(t,await o.check()),c.state==="Open"||c.state==="Aborted"&&c.numberRecordsProcessed===0)return{state:"never-closed"}}if(c.state==="UploadComplete"||c.state==="InProgress")return{state:"running",info:c};if(e.successfulOnly)return{state:"ended",info:c,results:{successfulResults:[...await o.getSuccessfulResults()]}};if(o.getAllResults===void 0)throw new Error(`Bulk API job ${t}: this connection reads no failed or unprocessed rows`);return{state:"ended",info:c,results:await o.getAllResults()}}catch(o){return{state:"unread",reason:W(o)}}}export{se as a,D as b,oe as c,Q as d,V as e,ie as f,ae as g,le as h,ue as i,ce as j,G as k,fe as l};
|
|
@@ -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 Le}from"./chunk-YYZL7UGV.mjs";import{a as be,f as we,i as ke,j as ve,l as re}from"./chunk-YDXMTWAT.mjs";import{a as Pe,b as $e,c as _e,d as xe,e as _,f as Me,g as Je,h as q,i as se}from"./chunk-26POJDIT.mjs";import{a as S}from"./chunk-4TLYUZD5.mjs";import{c as je}from"./chunk-HF6LAK3G.mjs";import{a as $,b as Be,d as Fe,e as Ce,f as ne,h as Ne,i as We,j as Ee}from"./chunk-D4GF4FAB.mjs";import{a as Se,d as Oe}from"./chunk-CVHNXJH3.mjs";import{Y as ee,Z as fe,_ as he,a as D,ba as pe,ca as ge,d as Z,fa as me,ha as ye,ia as Re}from"./chunk-TNT27RBG.mjs";import{b as v}from"./chunk-CA5NAXSU.mjs";import{d as Ie,e as te,f as Ae,k as Te}from"./chunk-S42RBRH2.mjs";import{Oc as ue,qd as ce,tc as Q}from"./chunk-PMWAFDUB.mjs";function Ye(a){return Array.isArray(a)?a.length:(a.successfulResults?.length??0)+(a.failedResults?.length??0)}function Ue(a,e){let t=!1,n=!1,s,r={},o=0,i=0,d=(u,h)=>(i+=u,e?.(u),h()),l=async u=>{let h=await d(We,u);return o=Ye(h),h},c={createJob:u=>{let h=a.bulk2.createJob(u);return{get id(){return h.id},open:async()=>{await d(1,()=>h.open()),s=Ce(h)},uploadData:w=>d(1,()=>h.uploadData(w)),close:async()=>{t=!0,await d(1,()=>h.close()),n=!0},abort:()=>d(1,()=>h.abort()),check:async()=>{let w=await d(1,()=>h.check());return r={state:w.state,message:w.errorMessage},w},getAllResults:()=>l(()=>h.getAllResults())}}};if("job"in a.bulk2){let u=a.bulk2;c.job=(h,w)=>{let k=u.job(h,w);return{check:async()=>{let p=await d(1,()=>k.check());return r={state:p.state,message:p.errorMessage??void 0},p},getSuccessfulResults:()=>d(1,()=>k.getSuccessfulResults()),getAllResults:()=>l(()=>k.getAllResults()),abort:()=>d(1,()=>k.abort())}}}return{connection:{bulk2:c},closeSent:()=>t,closed:()=>n,jobId:()=>s,last:()=>r,processed:()=>o,requests:()=>i}}var L=class extends Error{constructor(t,n,s=0,r=[]){super(`Bulk API job ${t||"(no id)"} was closed, and what it wrote could not be read back: ${n}`);this.jobId=t;this.requests=s;this.twins=r;this.name="BulkJobLostError"}jobId;requests;twins},M=1e4,H=50*1024*1024,Xe=10,Qe=/not supported by the Bulk API|InvalidEntity/i,Ze={unprocessed:"The Bulk API job did not write this row.",twin:"Kept out of the Bulk API job: another row carries the same values, and the job's results could not tell them apart.","may-have-written":"The Bulk API job may have written this row without saying so: it is not sent again."};async function _t(a,e,t,n,s,r={}){let o=n==="insert"?s.map(nt):s,i=Be($(n,o,r.externalIdField)),d=[];o.forEach((b,F)=>{i.has(F)||d.push(F)});let l=d.map(b=>o[b]),c=o.map((b,F)=>i.has(F)?"twin":"unprocessed"),u=b=>({answers:c.map(F=>x(F==="twin"?"twin":"unprocessed")),rows:c,unmatchedIds:[],...b});if(l.length===0)return u({requests:0});let h=$(n,l,r.externalIdField),w=Buffer.byteLength(h.text,"utf8");if(l.length>M||w>H)return u({requests:0,untouched:{reason:`${l.length} rows, ${w} bytes of CSV: past what one job takes (${M} rows, ${H} bytes)`}});let k=(b,F,N,g)=>{let A={requests:b.requests,...b.jobId?{jobId:b.jobId}:{}};if(b.info.state!=="JobComplete"&&b.processed===0&&g===0)return u({...A,untouched:oe(ne(b.info)??"job not complete")});let C=new Map(F.map(y=>[y.recordIndex,y])),f=c.map(y=>x(y==="twin"?"twin":"unprocessed"));return d.forEach((y,T)=>{let W=tt(C.get(T),g>0);c[y]=W.state,f[y]=W.answer}),{answers:f,rows:c,unmatchedIds:[...N],...A}},p=Ue(a),m,E=()=>m?{jobId:m}:{},B=r.pollDelay??Ee,R;try{R=await new Ne().executeBulk({connection:p.connection,bulkManager:e,pollIntervalMs:B,...r.signal?{signal:r.signal}:{},...r.onProgress?{onProgress:r.onProgress}:{},onOpened:b=>{m=b,r.onOpened?.(b)}},t,n,l,r.externalIdField)}catch(b){let F=v(b);if(!p.closeSent())return u({requests:p.requests(),...E(),untouched:oe(F)});if(m===void 0)throw new L("",F,p.requests(),[...i]);let N=await et(p.connection,m,B);if(N.state==="never-closed")return u({requests:p.requests(),jobId:m,untouched:oe(F)});if(N.state!=="ended")throw new L(m,N.state==="unread"?N.reason:"still running",p.requests(),[...i]);let g=Fe(N.results,h,ne(N.info));return k({info:N.info,processed:p.processed(),requests:p.requests(),jobId:m},g.outcomes,g.unattributedSuccessIds,g.unattributedSuccesses)}if(R.aborted)return u({requests:p.requests(),...E(),aborted:!0});let I=p.last();return k({info:{state:I.state??"JobComplete",...I.message?{errorMessage:I.message}:{}},processed:p.processed(),requests:p.requests(),...E()},R.outcomes,R.unmatchedIds??[],R.unmatchedWrites??0)}async function et(a,e,t){let n=await re(a,e,{openGraceMs:0});for(let s=1;s<Xe;s++){if(n.state==="ended"||n.state==="never-closed")return n;await new Promise(r=>setTimeout(r,t(s-1))),n=await re(a,e,{openGraceMs:0})}return n}function oe(a){return Qe.test(a)?{reason:a,unsupported:!0}:{reason:a}}function x(a){return{id:"",success:!1,errors:[Ze[a]]}}function tt(a,e){if(a===void 0||a.state==="no-result"){let s=e?"may-have-written":"unprocessed";return{state:s,answer:x(s)}}if(a.state==="unprocessed")return{state:"unprocessed",answer:x("unprocessed")};if(a.success)return a.id?{state:"answered",answer:{id:a.id,success:!0,errors:[],...a.created!==void 0?{created:a.created}:{}}}:{state:"may-have-written",answer:x("may-have-written")};let t=a.error??"Unknown error",n=Ie(t);return{state:"answered",answer:n?{id:"",success:!1,errors:[Ae(n)],errorDetails:[n]}:{id:"",success:!1,errors:[t]}}}function nt(a){let e;for(let[t,n]of Object.entries(a))n===""&&(e??={...a},e[t]=null);return e??a}var le={rest:200,bulk:1e4},Ke=3,ot=3,De=3,it=2e3;function at(a){return new Promise(e=>setTimeout(e,a))}function dt(a,e,t={bulk:!1}){let n=t.bulk&&a.api==="bulk"&&e>=2e3?"bulk":"rest",s=Math.min(a.batchSize,le[n]);return{api:n,batchSize:s,batchCount:Math.ceil(e/s),clamped:s<a.batchSize}}function G(a){return a.refusals.flatMap(e=>e.leftOut)}function ie(a){let e=a.built?.source.Id;return typeof e=="string"?e:void 0}function qe(a){return(a.built?.nullifiedFks??[]).map(({field:e,sourceRefId:t,insertOnly:n})=>({field:e,sourceRefId:t,...n?{insertOnly:n}:{}}))}function lt(a){let e=a.RecordTypeId;return typeof e=="string"&&e!==""}function ae(a){return a.refusals.length===0?a.payload:q(a.payload,G(a))}function He(a,e){let t=new Map;return e?.refusedIn?.answers.forEach((n,s)=>{let r=a[s];n&&r&&t.set(r,n.errors)}),t}var ut=new Set,ct=new Map;function V(a){return{objectApiName:a.objectApiName,op:a.upsertField?"upsert":"insert"}}function Ve(a){return a!==void 0&&!a.success?ce(a.errors):void 0}function ft(a){let e=a.automation??"the target's automation";S.warn(`[forge] ${a.objectApiName}: ${e} hit ${a.limit??"a Salesforce limit"} on a call of ${a.from} \u2014 sending a record on its own, then smaller calls`+(a.op==="upsert"?" (upsert).":"."))}var z={"validation-rule":"a validation rule","restricted-picklist":"a restricted picklist","lookup-filter":"a lookup filter","inactive-owner":"the target, the owner being inactive there"};function ht(a){let e=new Set(a.map(o=>o.refusedBy)),t=Object.keys(z).filter(o=>o!=="inactive-owner"&&e.has(o)).map(o=>z[o]),n=t.length>1?`${t.slice(0,-1).join(", ")} or ${t[t.length-1]}`:t[0],s=n===void 0?void 0:`${n} of the target`;if(!e.has("inactive-owner"))return s??`${z["validation-rule"]} of the target`;let r=`${z["inactive-owner"]},`;return s===void 0?r:`${s} or ${r}`}function de(a,e){if(!a.ownersMapped||a.ownersMapped.size===0)return!1;let t=_(e,"OwnerId"),n=t===void 0?void 0:e[t];return typeof n=="string"&&a.ownersMapped.has(n.slice(0,15))}function pt(a,e,t,n,s){let r=a.errorDetails??[];if(r.length===a.errors.length)return Me(r,e,t,n,s)}function ze(a){a.linkedToCreatedCount=(a.linkedToCreatedCount??0)+1}function gt(a){let e=a.errorDetails??[];return Oe(a.errors,e.length===a.errors.length?e:void 0)}function Y(a){return a.map(e=>e.field).join(", ")}function mt(a,e){return`Sent again without ${Y(a)} after the first refusal: ${e.join("; ")}`}var yt=["first","second","third"];function J(a){return a.map(({leftOut:e,errors:t},n)=>n===0?mt(e,t):`Sent again without ${Y(e)} too after the ${yt[n]} refusal: `+t.join("; "))}function U(a){let e=(t,n)=>t.length===0?[]:[`Sent without ${Y(t)}: ${n} earlier in the run, `+[...new Set(t.map(s=>s.reason))].join("; ")];return[...e(a.filter(t=>t.refusedBy!=="inactive-owner"),"the target refused the same value under the same record type"),...e(a.filter(t=>t.refusedBy==="inactive-owner"),"the target refused the same owner, inactive there,")]}function O(a){return`${a} record${a===1?"":"s"}`}var Rt="The call was sent and its answer never came back: the target may hold any of these records, and which of them is unknown. Counted as failed and never sent again, they are not among the records the run created, which removing its records takes back.",bt="Counted as failed and never sent again, they are not among the records the run created; the records the job wrote that no row was matched to are, and removing the run's records takes them back.",wt="DUPLICATES_DETECTED";function kt(a,e){if(a==="twin"||a==="unprocessed")return!0;if(a!=="answered"||e.success)return!1;let t=e.errorDetails;return t?.length!==1||t[0].statusCode===wt}function vt(a,e){let t=i=>i.reduce((d,l)=>d+Math.max(Buffer.byteLength(l,"utf8"),4)+(l.split('"').length-1)+3,1),n=t(e.columns),s=[],r=0,o=n;return e.rows.forEach((i,d)=>{let l=t(i);d>r&&o+l>a&&(s.push([r,d]),r=d,o=n),o+=l}),e.rows.length>r&&s.push([r,e.rows.length]),s}function It(a,e,t){let n=a.find(r=>r.isReference&&r.nillable===!1&&r.name!=="OwnerId"&&e.has(r.name))?.name;if(n===void 0)return;let s=r=>{let o=t[r][n];return typeof o=="string"?o:""};if(t.some((r,o)=>s(o)!==""))return t.map((r,o)=>o).sort((r,o)=>{let i=s(r),d=s(o);return i===d?r-o:i===""?1:d===""||i<d?-1:1})}var At="The target refused the call for its API request limit, which no retry gets past: the node stopped there.",Tt="A validation rule of the target, or a trigger with its code, refused the row without naming a field: there was none to send it again without.";function Bt(){return{successCount:0,updatedCount:0,linkedExistingCount:0,failureCount:0,alreadyExistsCount:0,unidentifiedExistingCount:0,errorSamples:[],pendingFkUpdates:[]}}var Ge=class{constructor(e,t,n=at,s=be()){this.deps=e;this.wait=n;this.splitting=s;this.batchStrategy=t??new je}deps;wait;splitting;batchStrategy;refusedValues=new Map;refusedOwners=new Map;backoff=new Se({initialDelay:it});async writeNode(e,t=Bt()){let{node:n,fieldInfos:s,creatableFields:r,targetOrgId:o,remapper:i}=e,d=await this.heldBeforeInsert(n.objectApiName,o,e.records),l=ee[n.objectApiName];for(let[g,A]of d){let C=e.cleanedRecords[g]?.source,f=C?.Id;if(typeof f!="string")continue;i.addExisting(f,A,n.objectApiName);let y=C?.ContactId;n.objectApiName===D&&typeof y=="string"&&i.wasCreated(y)&&(t.withTheirRecord=[...t.withTheirRecord??[],f]);let T=n.objectApiName===D?"ContactId":l,W=T===void 0?void 0:C?.[T];typeof W=="string"&&i.wasCreated(W)&&(t.writtenByThePlatformCount=(t.writtenByThePlatformCount??0)+1)}t.linkedExistingCount+=d.size;let c=await this.giveFlagsBack(n.objectApiName,o,e,d);c&&(t.flagsNotKept=pe(t.flagsNotKept,c));let u=e.records.filter((g,A)=>!d.has(A)),h=e.cleanedRecords.filter((g,A)=>!d.has(A)),w=this.batchStrategy.resolve(n.batchStrategy,u.length),{api:k,batchSize:p,batchCount:m,clamped:E}=dt(w,u.length,{bulk:this.jobsCanCarry(e.bulk,n.objectApiName)});if(E&&S.warn(`[forge] ${n.objectApiName}: batch strategy asked for ${w.batchSize} records per call (api="${w.api}") but the write path is "${k}" (max ${le[k]}) \u2014 using ${p} per call (${m} batch(es)).`),k==="bulk"){let g=It(s,r,u);if(g){let A={records:u,cleanedRecords:h};u=g.map(C=>A.records[C]),h=g.map(C=>A.cleanedRecords[C])}}e.onProgress({objectName:n.objectApiName,status:"running",progress:0,recordCount:u.length,fieldCount:s.length,createableFieldCount:r.size,message:`Inserting ${u.length} ${n.objectApiName} records in ${m} batch(es)...`});let B=0,R=this.pickUpsertField(s,r,u,e.upsertMode==="auto"&&this.deps.upsertRecords?"auto":"off",e.tableKeys),I={objectApiName:n.objectApiName,targetOrgId:o,targetKeyPrefix:e.targetKeyPrefix,remapper:i,tally:t,oweLookups:e.oweLookups,onWritten:e.onWritten,onCreatedWithoutRecordType:e.onCreatedWithoutRecordType,calls:e.calls,bulk:e.bulk,byNaturalKey:[],refusedOnTheirFields:[],locked:[],upsertField:R,ownersMapped:e.ownersMapped,remembered:new Set([...e.picklistFields??[]].filter(([,g])=>g.controllerName===void 0).map(([g])=>g.toLowerCase()))},{byNaturalKey:b}=I,F=g=>{let A=v(g);this.leaveLockedAsFailed(I,I.locked.splice(0),A),this.leaveRefusedAsFailed(I,I.refusedOnTheirFields.splice(0),A),this.settleByNaturalKey(n.objectApiName,b,[],i,t,`The record the target holds under the same key was not looked up: ${A}`)};for(let g=0;g<m;g++){let A=u.slice(g*p,(g+1)*p).map((T,W)=>{let{sent:P,before:X}=this.withoutRefusedValues(I,T);return{payload:P,built:h[B+W],before:X,refusals:[],lockResends:0}}),C=`${n.objectApiName} batch ${g+1}/${m}`,f;try{f=await this.sendRows(I,e,A,C,u.length-B-A.length)}catch(T){throw F(T),T}if(f){let T=v(f.thrown);this.leaveLockedAsFailed(I,I.locked.splice(0),T),this.leaveRefusedAsFailed(I,I.refusedOnTheirFields.splice(0),T);break}B+=A.length;let y;try{y=await this.sendLockedAgain(I,e,u.length-B)}catch(T){throw F(T),T}if(y){this.leaveRefusedAsFailed(I,I.refusedOnTheirFields.splice(0),v(y.thrown));break}e.onProgress({objectName:n.objectApiName,status:"running",progress:Math.round((g+1)/m*100),message:`batch ${g+1}/${m} \u2014 ${Math.min((g+1)*p,u.length)}/${u.length} records`})}try{await this.writeAgainWithoutTheirFields(I,e,Math.min(p,le.rest))}catch(g){throw F(g),g}let N=Z[n.objectApiName];if(N&&b.length>0){let g,A;try{g=await this.recordsByNaturalKey(o,n.objectApiName,N,b.map(C=>C.payload))}catch(C){g=[],A=`The record the target holds under the same key could not be looked up: ${v(C)}`}this.settleByNaturalKey(n.objectApiName,b,g,i,t,A)}return t}send(e,t){return e.upsertField&&this.deps.upsertRecords?this.deps.upsertRecords(e.targetOrgId,e.objectApiName,e.upsertField,t):this.deps.insertRecords(e.targetOrgId,e.objectApiName,t)}jobsCanCarry(e,t){return e!==void 0&&this.deps.bulkWriteRecords!==void 0&&!e.restOnly.has(t)&&!e.bulkUnsupported.has(t)}goesSmallerByRest(e){return this.splitting.sizes.of(e)<200}async sendRows(e,t,n,s,r,o){let{bulk:i}=e;if(!i||!this.jobsCanCarry(i,e.objectApiName)||n.length<2e3)return this.sendByRest(e,t,n,s,r,o);for(let d=0;d<n.length;d+=M){let l=n.slice(d,d+M),c=n.length-d-l.length+r,u;try{u=l.length>=2e3?await this.writeAsJobs(e,t,i,l,s,c,o):await this.sendByRest(e,t,l,s,c,o)}catch(h){throw o?.(n.slice(d+l.length),v(h)),h}if(u)return u}}async sendByRest(e,t,n,s,r,o,i){if(n.length===0)return;try{await t.waitIfPaused()}catch(l){let c=v(l);throw o?o(n,c):this.leaveLimitedAsFailed(e,n,He(n,i),c),l}let d=await this.callAndSettle(e,t,n,o,i);if(d)return this.settleThrown(e,d.threw,d.rows,s,d.rest.length+r),d.threw}async writeAsJobs(e,t,n,s,r,o,i){let d=this.deps.bulkWriteRecords;if(!d)return this.sendByRest(e,t,s,r,o,i);let l=V(e);if(this.goesSmallerByRest(l))return this.sendJobByRest(e,t,n,s,r,o,i);let c=e.upsertField?"upsert":"insert",u=s.map(ae),h=vt(H,$(c,u,e.upsertField));for(let[w,k]of h){let p=s.slice(w,k),m=s.length-k+o;if(this.goesSmallerByRest(l)){let f;try{f=await this.sendJobByRest(e,t,n,p,r,m,i)}catch(y){throw i?.(s.slice(k),v(y)),y}if(f)return f;continue}try{await t.waitIfPaused()}catch(f){throw i?.(s.slice(w),v(f)),f}let E=u.slice(w,k),B=e.calls?.sending(e.objectApiName,p.map((f,y)=>({sourceId:ie(f),payload:E[y],owes:qe(f)})),e.upsertField,!0),R;try{R=await d(e.targetOrgId,e.objectApiName,c,E,{bulkManager:n.manager,signal:n.signal,...e.upsertField?{externalIdField:e.upsertField}:{},onOpened:f=>{B!==void 0&&e.calls?.opened?.(B,f)}})}catch(f){if(f instanceof L){let y={thrown:f,left:"may-have-written",tries:1},T=new Set(f.twins),W=p.filter((P,X)=>!T.has(X));return this.settleThrown(e,y,W,`${r} (Bulk API job)`,m),this.leaveTwinsUnsent(e,p.length-W.length,r,f),y}R={answers:[],rows:[],unmatchedIds:[],untouched:{reason:v(f)},requests:0}}if(R.aborted){try{await t.waitIfPaused()}catch(f){throw B!==void 0&&e.calls?.answered(B),i?.(s.slice(w),v(f)),f}R={...R,untouched:{reason:"the job was aborted"}}}if(R.untouched){B!==void 0&&e.calls?.answered(B),R.untouched.unsupported&&n.bulkUnsupported.add(e.objectApiName),S.warn(`[forge] ${e.objectApiName}: a Bulk API job of ${O(p.length)} wrote nothing (${R.untouched.reason}) \u2014 sent by REST`+(R.untouched.unsupported?", as every write of the object in the run.":"."));let f;try{f=await this.sendByRest(e,t,p,r,m,i)}catch(y){throw i?.(s.slice(k),v(y)),y}if(f)return f;continue}R.unmatchedIds.length>0&&(e.calls?.unattributed?.(e.objectApiName,R.unmatchedIds),S.warn(`[forge] ${e.objectApiName}: Bulk API job ${R.jobId??""} wrote ${O(R.unmatchedIds.length)} no row was matched to \u2014 kept for removal.`));let I=[],b=[],F=[],N=[],g=[],A=[],C;if(p.forEach((f,y)=>{let T=R.rows[y]??"unprocessed",W=R.answers[y],P=T==="answered"?Ve(W):void 0;T==="may-have-written"?A.push(f):P!==void 0&&W!==void 0?(C??=P,N.push(f),g.push(W)):!W||kt(T,W)?F.push(f):(I.push(f),b.push(W))}),this.settleMayHaveBeenWritten(e,A,r,R.jobId),await this.settleAnswers(e,I,B===void 0?{answers:b}:{answers:b,callId:B}),F.length>0){let f;try{f=await this.sendByRest(e,t,F,`${r}, by REST`,N.length+m,i)}catch(y){throw i?.([...N,...s.slice(k)],v(y)),y}if(f)return f}if(N.length>0){let f;try{f=await this.sendByRest(e,t,N,`${r}, by REST`,m,i,{refusedIn:{from:200,answers:g,...C?{cause:C}:{}}})}catch(y){throw i?.(s.slice(k),v(y)),y}if(f)return f}}}async sendJobByRest(e,t,n,s,r,o,i){let d=V(e),{sizes:l,allowance:c}=this.splitting,u=l.of(d),h=Math.ceil(s.length/u),w=c.take(d,h);l.countExtraCalls(d,w);let k=s.slice(0,w*u),p=s.slice(k.length);if(k.length>0){let m;try{m=await this.sendByRest(e,t,k,r,p.length+o,i,{pricedAs:"job",paid:{calls:w}})}catch(E){throw i?.(p,v(E)),E}finally{w<h&&l.spend(d)}if(m)return m}else w<h&&l.spend(d);if(p.length!==0)return p.length>=2e3?this.writeAsJobs(e,t,n,p,r,o,i):this.sendByRest(e,t,p,r,o,i)}leaveTwinsUnsent(e,t,n,s){t!==0&&(e.tally.failureCount+=t,this.sample(e.tally,{recordSummary:`${n}: ${O(t)} not written`,messages:[v(s),"Kept out of the Bulk API job as twins of other rows, to be written by REST once it answered: never sent, the target holds none of them."]}))}settleMayHaveBeenWritten(e,t,n,s){if(t.length===0)return;let{tally:r}=e;r.failureCount+=t.length;let o=t.map(ie).filter(i=>i!==void 0);r.mayHaveBeenWritten=[...r.mayHaveBeenWritten??[],...o],this.sampleAhead(r,{recordSummary:`${n}: ${O(t.length)} may have been written`,messages:[`Bulk API job ${s??""} gave them no result of their own, and wrote records no row was matched to: the target may hold any of these records, and which of them is unknown.`,bt]})}async call(e,t,n){let s=n.map(ae);for(let r=0;;r++){let o=e.calls?.sending(e.objectApiName,n.map((i,d)=>({sourceId:ie(i),payload:s[d],owes:qe(i)})),e.upsertField);try{let i=await this.send(e,s);return o===void 0?{answers:i}:{answers:i,callId:o}}catch(i){let d=Le(i);if(o!==void 0&&d!=="may-have-written"&&e.calls?.answered(o),d!=="not-received"||r===Ke)return{thrown:i,left:d,tries:r+1};let l=this.backoff.calculateDelay(r);S.warn(`[forge] ${e.objectApiName}: a call of ${O(s.length)} never reached the target (${v(i)}) \u2014 sent again in ${l} ms (${r+1}/${Ke}).`),await this.wait(l),await t.waitIfPaused()}}}async callAndSettle(e,t,n,s,r){let o,i={answers:[]},d=He(n,r),{stopped:l}=await ve(n,{key:V(e),sizes:this.splitting.sizes,allowance:this.splitting.allowance,...r,beforeEachSend:()=>t.waitIfPaused(),send:async c=>{let u=await this.call(e,t,c);return"thrown"in u?(o=u,"stop"):(i=u,{answers:u.answers})},limited:(c,u)=>{let h=Ve(c);return h&&c&&d.set(u,c.errors),h},settle:(c,u,h,w,k)=>this.settleAnswers(e,c,k?{answers:u}:i,h,w),onThrow:(c,u)=>{let h=v(u);s?s(c,h):this.leaveLimitedAsFailed(e,c,d,h)},onFirstRefusal:ft});if(!(!l||o===void 0))return{threw:o,rows:l.part,rest:l.rest}}sample(e,t){e.errorSamples.length<3&&e.errorSamples.push(t)}sampleAhead(e,t){e.errorSamples.unshift(t),e.errorSamples.splice(3)}async settleAnswers(e,t,{answers:n,callId:s},r=ut,o=ct){t.forEach((i,d)=>{let l=n[d];l?.success&&!r.has(d)&&this.settle(e,l,i)}),e.remapper.persist(),await this.readWhatMayBeEmpty(e,n.filter(i=>i!==void 0)),t.forEach((i,d)=>{if(r.has(d))return;let l=n[d];if(l){l.success||this.settle(e,l,i,o.get(d));return}e.tally.failureCount++,this.sample(e.tally,{recordSummary:j(i.payload),messages:[`No result returned for record (API truncated batch: ${n.length}/${t.length})`,...J(i.refusals),...U(i.before)]})}),e.remapper.persist(),s!==void 0&&e.calls?.answered(s)}async readWhatMayBeEmpty(e,t){if(e.mayBeEmpty!==void 0||!t.some(r=>(r.errorDetails??[]).some(o=>o.statusCode===$e)))return;let s=await this.deps.describeFields?.(e.targetOrgId,e.objectApiName).catch(()=>{});e.mayBeEmpty=new Set((s??[]).filter(r=>r.nillable===!0).map(r=>r.name.toLowerCase()))}settleThrown(e,t,n,s,r){let{tally:o}=e,i=v(t.thrown);if(o.failureCount+=n.length+r,t.left==="may-have-written"){let l=n.map(c=>c.built?.source.Id).filter(c=>typeof c=="string");o.mayHaveBeenWritten=[...o.mayHaveBeenWritten??[],...l],this.sampleAhead(o,{recordSummary:`${s}: ${O(n.length)} may have been written`,messages:[i,Rt,...r>0?[`${O(r)} after them not sent.`]:[]]});return}let d=n.length+r;this.sample(o,{recordSummary:`${s}: ${O(d)} not written`,messages:[i,...t.left==="request-limit"?[At]:[],...t.left==="not-received"?[`Sent ${t.tries} times, the call never reached the target: it holds none of them.`]:[]]})}async sendLockedAgain(e,t,n){for(let s=0;e.locked.length>0;s++){let r=this.backoff.calculateDelay(s);S.warn(`[forge] ${e.objectApiName}: the target could not lock a record for ${O(e.locked.length)} \u2014 sent again in ${r} ms.`),await this.wait(r),await t.waitIfPaused();let o=e.locked.splice(0),i=o.map(({row:c})=>({...c,lockResends:c.lockResends+1})),d=new Map(i.map((c,u)=>[c,o[u]])),l=await this.callAndSettle(e,t,i,(c,u)=>this.leaveLockedAsFailed(e,c.flatMap(h=>d.get(h)??[]),u));if(l)return this.settleThrown(e,l.threw,l.rows,`${e.objectApiName}, sent again`,n+l.rest.length),this.leaveLockedAsFailed(e,e.locked.splice(0),v(l.threw.thrown)),l.threw}}settle(e,t,n,s){let{tally:r,remapper:o,objectApiName:i}=e,{built:d,before:l}=n,c=ae(n);if(t.success){let m=d?.source.Id,E=t.created===!1;if(E?r.updatedCount++:r.successCount++,typeof m=="string"&&(E?o.addUpdated(m,t.id,i):o.add(m,t.id,i)),d&&e.onWritten?.(d,t.id),!E&&!lt(c)&&e.onCreatedWithoutRecordType?.(d,t.id),d&&d.nullifiedFks.length>0){let R=typeof d.source.Id=="string"?d.source.Id:void 0,I=d.nullifiedFks.map(b=>({objectApiName:i,newId:t.id,sourceId:R,fieldName:b.field,sourceRefId:b.sourceRefId,...b.insertOnly?{insertOnly:!0}:{}}));e.oweLookups?e.oweLookups(I):r.pendingFkUpdates.push(...I)}let B=[...l,...G(n)];B.length>0&&(r.writtenWithoutFields=se(r.writtenWithoutFields,{rows:1,fields:B.map(R=>({...R,rows:1}))}));for(let{field:R,refusedBy:I}of B)I!=="lookup-filter"||!t.id||(r.leftEmptyByFilter??=[]).push({field:R,recordId:t.id});return}this.rememberRefusedValues(e,t,c),this.rememberRefusedOwners(e,t,c);let u=Te(t,e.targetKeyPrefix);if(u.kind==="linked"){r.linkedExistingCount++,o.createdTarget(u.id)&&ze(r);let m=d?.source.Id;typeof m=="string"&&o.addExisting(m,u.id,i);return}if(u.kind==="unidentified"&&Z[i]){e.byNaturalKey.push({payload:c,sourceId:d?.source.Id,errors:t.errors});return}let h=gt(t);if(h&&n.lockResends<ot){e.locked.push({row:n,errors:t.errors});return}let w=m=>e.mayBeEmpty?.has(m.toLowerCase())??!1,k=pt(t,c,e.upsertField,w,{inactiveOwner:!de(e,c)}),p=n.refusals.length<De;if(k&&p){e.refusedOnTheirFields.push({...n,refusals:[...n.refusals,{errors:t.errors,leftOut:k}]});return}r.failureCount++,u.kind==="unidentified"&&r.unidentifiedExistingCount++,t.errors.every(m=>Q(m))&&r.alreadyExistsCount++,this.sample(r,{recordSummary:j(n.payload),messages:[...t.errors,...J(n.refusals),...h?[`Sent again ${n.lockResends} times, the target still could not lock a record the write needed.`]:[],...k&&!p?[`Not sent again: a row goes again without the fields the target refused ${De} times at most.`]:[],...Je(t.errorDetails)?[Tt]:[],...s?[we(s,ke(this.splitting.allowance,V(e)),"run")]:[],...U(l)]})}refusedValueKey(e,t,n){let s=t.RecordTypeId,r=t[n];if(typeof s!="string"||s===""||typeof r!="string"||r==="")return;let o=n.toLowerCase();if(!(!e.remembered.has(o)||o===e.upsertField?.toLowerCase()))return[e.objectApiName,s,o,r].join("\0")}rememberRefusedValues(e,t,n){for(let s of t.errorDetails??[])if(s.statusCode===Pe)for(let r of s.fields){let o=_(n,r),i=o===void 0?void 0:this.refusedValueKey(e,n,o);o===void 0||i===void 0||this.refusedValues.has(i)||this.refusedValues.set(i,{field:o,refusedBy:"restricted-picklist",reason:te(s)})}}rememberRefusedOwners(e,t,n){let s=_(n,"OwnerId");if(!(s===void 0||s.toLowerCase()===e.upsertField?.toLowerCase())&&!de(e,n))for(let r of t.errorDetails??[]){if(r.statusCode!==_e)continue;let o=xe(r,n);o===void 0||this.refusedOwners.has(o)||this.refusedOwners.set(o,{field:"OwnerId",refusedBy:"inactive-owner",reason:te(r)})}}withoutRefusedValues(e,t){let n=[];if(this.refusedValues.size===0&&this.refusedOwners.size===0)return{sent:t,before:n};for(let o of Object.keys(t)){let i=this.refusedValueKey(e,t,o),d=i===void 0?void 0:this.refusedValues.get(i);d&&n.push({...d,field:o})}let s=_(t,"OwnerId"),r=s===void 0?void 0:t[s];if(s!==void 0&&typeof r=="string"&&s.toLowerCase()!==e.upsertField?.toLowerCase()&&!de(e,t)){let o=this.refusedOwners.get(r.slice(0,15));o&&n.push({...o,field:s})}return n.length===0?{sent:t,before:n}:{sent:q(t,n),before:n}}leaveRefusedAsFailed(e,t,n){for(let s of t){let r=s.refusals[s.refusals.length-1];e.tally.failureCount++,this.sample(e.tally,{recordSummary:j(s.payload),messages:[...r?.errors??[],...J(s.refusals.slice(0,-1)),`Not written again without ${Y(G(s))}: ${n}`,...U(s.before)]})}}leaveLimitedAsFailed(e,t,n,s){for(let r of t){let o=n.get(r);o&&(e.tally.failureCount++,this.sample(e.tally,{recordSummary:j(r.payload),messages:[...o,...J(r.refusals),`Not sent again in a smaller call: ${s}`,...U(r.before)]}))}}leaveLockedAsFailed(e,t,n){for(let{row:s,errors:r}of t)e.tally.failureCount++,this.sample(e.tally,{recordSummary:j(s.payload),messages:[...r,...J(s.refusals),`Not sent again: ${n}`,...U(s.before)]})}async writeAgainWithoutTheirFields(e,t,n){for(;e.refusedOnTheirFields.length>0;){let s=e.refusedOnTheirFields.splice(0);if(t.onProgress({objectName:e.objectApiName,status:"running",progress:100,message:`Writing ${s.length} ${e.objectApiName} record${s.length===1?"":"s"} again without the fields ${ht(s.flatMap(G))} refused...`}),this.jobsCanCarry(e.bulk,e.objectApiName)&&s.length>=2e3){let r=`${e.objectApiName}, sent again`,o=await this.sendRows(e,t,s,r,0,(i,d)=>this.leaveRefusedAsFailed(e,i,d));if(o??=await this.sendLockedAgain(e,t,0),o){let i=v(o.thrown);this.leaveLockedAsFailed(e,e.locked.splice(0),i),this.leaveRefusedAsFailed(e,e.refusedOnTheirFields.splice(0),i);return}continue}for(let r=0;r<s.length;r+=n){let o=s.slice(r,r+n),i;try{await t.waitIfPaused()}catch(l){throw this.leaveRefusedAsFailed(e,s.slice(r),v(l)),l}try{i=await this.callAndSettle(e,t,o,(l,c)=>this.leaveRefusedAsFailed(e,l,c))}catch(l){throw this.leaveRefusedAsFailed(e,s.slice(r+n),v(l)),l}let d;if(i){d=i.threw;let l=v(i.threw.thrown),c=[...i.rest,...s.slice(r+n)];i.threw.left==="may-have-written"?(this.settleThrown(e,i.threw,i.rows,`${e.objectApiName}, sent again`,0),this.leaveRefusedAsFailed(e,c,l)):this.leaveRefusedAsFailed(e,[...i.rows,...c],l)}else{try{d=await this.sendLockedAgain(e,t,0)}catch(l){throw this.leaveRefusedAsFailed(e,s.slice(r+n),v(l)),l}d&&this.leaveRefusedAsFailed(e,s.slice(r+n),v(d.thrown))}if(d){this.leaveRefusedAsFailed(e,e.refusedOnTheirFields.splice(0),v(d.thrown));return}}}}settleByNaturalKey(e,t,n,s,r,o){t.forEach((i,d)=>{let l=n[d];if(l&&typeof i.sourceId=="string"){s.createdTarget(l)&&ze(r),s.addExisting(i.sourceId,l,e),r.linkedExistingCount++;return}r.failureCount++,r.unidentifiedExistingCount++,i.errors.every(c=>Q(c))&&r.alreadyExistsCount++,r.errorSamples.length<3&&r.errorSamples.push({recordSummary:j(i.payload),messages:o?[...i.errors,o]:i.errors})})}async recordsByNaturalKey(e,t,n,s){let r=this.deps.queryRecords;return r?Re(o=>r(e,o),t,n,s):s.map(()=>{})}async giveFlagsBack(e,t,n,s){let r=this.deps.updateRecords;if(!r||s.size===0||!he[e])return;let o=[];for(let[d,l]of s){let c=n.cleanedRecords[d]?.source;c&&o.push([c,l])}let i=await this.deps.describeFields?.(t,e).catch(()=>{});return ge(e,o,d=>i?.find(l=>l.name===d)?.updateable!==!1,d=>r(t,e,d),n.stopped)}async heldBeforeInsert(e,t,n){let s=this.deps.queryRecords;if(!s)return new Map;let r=o=>s(t,o);return e===D?me(r,n):ee[e]!==void 0?fe(r,e,n):e===ue?ye(r,n):new Map}pickUpsertField(e,t,n,s,r){if(s==="off"||!this.deps.upsertRecords)return;let o=e.filter(i=>i.externalId&&t.has(i.name)).sort((i,d)=>i.name.localeCompare(d.name));if(r)return this.tableKeyOfThePage(o,n,r);if(o.length!==0){for(let i of o){let d=new Set,l=!0;for(let c of n){let u=c[i.name];if(typeof u!="string"||u.length===0){l=!1;break}if(d.has(u)){l=!1;break}d.add(u)}if(l)return S.info(`[forge] upsert: using "${i.name}" as external Id (unique across ${n.length} records)`),i.name}S.warn(`[forge] upsert: no externalId candidate is non-null+unique across batch (${o.map(i=>i.name).join(", ")}) \u2014 falling back to insert`)}}tableKeyOfThePage(e,t,n){let s=e.find(o=>n.unique.has(o.name))?.name;if(s===void 0){e.length>0&&S.warn(`[forge] upsert: no externalId candidate is non-null+unique across the rows read (${e.map(o=>o.name).join(", ")}) \u2014 falling back to insert`);return}let r=new Set;for(let o of t){let i=o[s];if(typeof i!="string"||i.length===0||r.has(i)){S.warn(`[forge] upsert: a row of this page leaves "${s}" empty or repeats it \u2014 inserting the page`);return}if(n.sent.has(i)){S.warn(`[forge] upsert: a row of this page repeats a "${s}" an earlier page sent \u2014 inserting the page`);return}r.add(i)}n.sent.size===0&&S.info(`[forge] upsert: using "${s}" as external Id (unique across the rows read of the object)`);for(let o of r)n.sent.add(o);return s}};function j(a){let e=Object.keys(a).slice(0,4),t=[];for(let n of e){let s=a[n],r;if(s===null)r="null";else if(s===void 0)r="undefined";else if(typeof s=="string")r=s.length>30?s.slice(0,30)+"\u2026":s;else if(typeof s=="object")try{let o=JSON.stringify(s);r=o.length>30?o.slice(0,30)+"\u2026":o}catch{r="<unserializable>"}else r=String(s);t.push(`${n}=${r}`)}return t.join(" ")||"(empty)"}export{L as a,M as b,_t as c,le as d,dt as e,lt as f,pt as g,mt as h,Bt as i,Ge as j,j as k};
|