sandforge 1.79.0 → 1.80.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/lib/{chunk-JVL444U5.mjs → chunk-2BA2XKAY.mjs} +1 -1
  2. package/lib/chunk-2CNCDM56.mjs +7 -0
  3. package/lib/{chunk-W7KFAY55.mjs → chunk-2GTBABKU.mjs} +1 -1
  4. package/lib/{chunk-DLDX6RRC.mjs → chunk-2NBYT7GR.mjs} +1 -1
  5. package/lib/{chunk-HV2MXMGI.mjs → chunk-2UZPIMUC.mjs} +1 -1
  6. package/lib/chunk-3F6Q5E7I.mjs +14 -0
  7. package/lib/{chunk-PBI4BYWW.mjs → chunk-3RZQZHEB.mjs} +1 -1
  8. package/lib/{chunk-P7GSGFJO.mjs → chunk-3TJON4F3.mjs} +1 -1
  9. package/lib/chunk-4VS2V6WU.mjs +25 -0
  10. package/lib/{chunk-TQX3PURV.mjs → chunk-5K5VLULK.mjs} +1 -1
  11. package/lib/{chunk-MYTIL2JD.mjs → chunk-5TC3QB4U.mjs} +1 -1
  12. package/lib/{chunk-NM4MDLK4.mjs → chunk-6XYKJSGX.mjs} +1 -1
  13. package/lib/{chunk-RFEO2KAN.mjs → chunk-74Q6DORA.mjs} +1 -1
  14. package/lib/chunk-7ABODJ4G.mjs +7 -0
  15. package/lib/{chunk-ZPYJPGDK.mjs → chunk-7EGQP6S4.mjs} +1 -1
  16. package/lib/chunk-7FFGJWHN.mjs +7 -0
  17. package/lib/chunk-7YDNUBO5.mjs +7 -0
  18. package/lib/{chunk-CGWXQX75.mjs → chunk-A527W53V.mjs} +1 -1
  19. package/lib/chunk-ADOAS63R.mjs +7 -0
  20. package/lib/chunk-AEKONPF4.mjs +7 -0
  21. package/lib/{chunk-4HFRHFGQ.mjs → chunk-B5QQJ4SI.mjs} +1 -1
  22. package/lib/{chunk-2BVTCNWA.mjs → chunk-BGUEWRK2.mjs} +1 -1
  23. package/lib/{chunk-GNC27UEU.mjs → chunk-BKDV4ENO.mjs} +1 -1
  24. package/lib/{chunk-QRV2OSIS.mjs → chunk-BTWDMNN3.mjs} +1 -1
  25. package/lib/{chunk-FOVVHGEP.mjs → chunk-BV6VTP3J.mjs} +1 -1
  26. package/lib/{chunk-PZTSVQSF.mjs → chunk-BXU6WFMH.mjs} +1 -1
  27. package/lib/{chunk-ZQOZ4EFW.mjs → chunk-BY2HJFFG.mjs} +1 -1
  28. package/lib/{chunk-NZ5ZZLKS.mjs → chunk-CEX3NEZL.mjs} +1 -1
  29. package/lib/{chunk-HTJ5OGP5.mjs → chunk-CHYDMRSV.mjs} +1 -1
  30. package/lib/chunk-CION3VMZ.mjs +7 -0
  31. package/lib/chunk-COFG7Q6R.mjs +7 -0
  32. package/lib/chunk-CSBS5U5I.mjs +7 -0
  33. package/lib/{chunk-55HEMHEG.mjs → chunk-CU2INBND.mjs} +1 -1
  34. package/lib/chunk-DB7RBE5D.mjs +7 -0
  35. package/lib/{chunk-QPF6C5MX.mjs → chunk-DBB3EMIN.mjs} +1 -1
  36. package/lib/{chunk-F74IHMGL.mjs → chunk-DYFALGRT.mjs} +1 -1
  37. package/lib/{chunk-TEOLMRDO.mjs → chunk-E5AHXLS6.mjs} +1 -1
  38. package/lib/{chunk-LRFAIUN7.mjs → chunk-E5ZB3LU5.mjs} +1 -1
  39. package/lib/chunk-EFR2Y7E4.mjs +7 -0
  40. package/lib/chunk-EHQ3FX6X.mjs +7 -0
  41. package/lib/{chunk-RAAANPPG.mjs → chunk-ELFXJHU7.mjs} +1 -1
  42. package/lib/{chunk-BN7A4GRQ.mjs → chunk-EMNC6YI4.mjs} +1 -1
  43. package/lib/{chunk-HJC7AIBK.mjs → chunk-EQNW3UC2.mjs} +1 -1
  44. package/lib/{chunk-Z7X534S4.mjs → chunk-F43REJDZ.mjs} +2 -2
  45. package/lib/{chunk-QQZZMKU3.mjs → chunk-F6GUDTOB.mjs} +1 -1
  46. package/lib/{chunk-6EBMEGZB.mjs → chunk-FGRG7ANU.mjs} +1 -1
  47. package/lib/{chunk-4NAHW2D3.mjs → chunk-FKG7Q3WH.mjs} +1 -1
  48. package/lib/{chunk-7UQD6V6F.mjs → chunk-FPKYYFM7.mjs} +1 -1
  49. package/lib/{chunk-ZJKCWBRJ.mjs → chunk-FXXLX4O6.mjs} +1 -1
  50. package/lib/chunk-G35N4P7D.mjs +7 -0
  51. package/lib/{chunk-SIOZXPFG.mjs → chunk-GGD7ON3M.mjs} +1 -1
  52. package/lib/chunk-GSG7WZHM.mjs +7 -0
  53. package/lib/{chunk-OTWRDD6L.mjs → chunk-GSKCGQIP.mjs} +1 -1
  54. package/lib/{chunk-3CA767QB.mjs → chunk-HEKAZJRH.mjs} +1 -1
  55. package/lib/{chunk-4SNDMJP2.mjs → chunk-HLWMJF6Y.mjs} +1 -1
  56. package/lib/chunk-HOJYWTP7.mjs +20 -0
  57. package/lib/chunk-HS4YRX4J.mjs +7 -0
  58. package/lib/chunk-IFETCRWE.mjs +10 -0
  59. package/lib/{chunk-PUOX4NBJ.mjs → chunk-IG2MTQRP.mjs} +1 -1
  60. package/lib/{chunk-RACDTRZA.mjs → chunk-IGYH7GMA.mjs} +1 -1
  61. package/lib/{chunk-X65MT4W3.mjs → chunk-IOIWJ3DJ.mjs} +1 -1
  62. package/lib/{chunk-4U6NXJNL.mjs → chunk-IQXHJEYB.mjs} +1 -1
  63. package/lib/{chunk-P2PJYWGQ.mjs → chunk-IWDREM66.mjs} +1 -1
  64. package/lib/{chunk-ZOVSMN5C.mjs → chunk-IZQZ6ZUF.mjs} +1 -1
  65. package/lib/{chunk-XBG5SP6Q.mjs → chunk-J525F5KI.mjs} +1 -1
  66. package/lib/{chunk-5CD257T7.mjs → chunk-JEERQRLW.mjs} +1 -1
  67. package/lib/{chunk-6QSM2WIH.mjs → chunk-JPUR2CFX.mjs} +1 -1
  68. package/lib/chunk-JWTSEDIQ.mjs +7 -0
  69. package/lib/chunk-K327QKMD.mjs +7 -0
  70. package/lib/{chunk-J7HVXMSW.mjs → chunk-KBJ5VERV.mjs} +1 -1
  71. package/lib/chunk-KDGMAGQR.mjs +7 -0
  72. package/lib/chunk-KRCA6IPH.mjs +8 -0
  73. package/lib/chunk-KYEDBS54.mjs +7 -0
  74. package/lib/chunk-L5FGY6YA.mjs +7 -0
  75. package/lib/{chunk-PNCONNFJ.mjs → chunk-L77FJZEP.mjs} +1 -1
  76. package/lib/{chunk-3OHPD72J.mjs → chunk-LKQ5RKIV.mjs} +1 -1
  77. package/lib/{chunk-WJY54JO7.mjs → chunk-LPBMBW3O.mjs} +1 -1
  78. package/lib/{chunk-LV6G4XTK.mjs → chunk-LWW4U276.mjs} +1 -1
  79. package/lib/{chunk-IAZB4WIL.mjs → chunk-M3ROUWDX.mjs} +1 -1
  80. package/lib/chunk-MFG4MUIO.mjs +9 -0
  81. package/lib/{chunk-H45UXY6G.mjs → chunk-MHMH6MTP.mjs} +1 -1
  82. package/lib/{chunk-HCIDVIOW.mjs → chunk-MILU7WFN.mjs} +1 -1
  83. package/lib/chunk-MJU2PGZQ.mjs +15 -0
  84. package/lib/{chunk-HJKM3E56.mjs → chunk-MJVTDA5Q.mjs} +1 -1
  85. package/lib/{chunk-SBIMVCXT.mjs → chunk-MS4FJDFD.mjs} +9 -9
  86. package/lib/{chunk-3SRXFZSD.mjs → chunk-MYW5QNGI.mjs} +1 -1
  87. package/lib/{chunk-VHI54FBK.mjs → chunk-N652NMZ4.mjs} +26 -26
  88. package/lib/{chunk-3DCUADVK.mjs → chunk-NTFIRZP6.mjs} +1 -1
  89. package/lib/{chunk-342FN7AO.mjs → chunk-NZC67CGR.mjs} +1 -1
  90. package/lib/{chunk-RSYICMZG.mjs → chunk-O2HDYYUV.mjs} +1 -1
  91. package/lib/chunk-OAZRPP4I.mjs +7 -0
  92. package/lib/{chunk-BILZ3SSR.mjs → chunk-OHWNPXWW.mjs} +1 -1
  93. package/lib/chunk-OLSGVAIL.mjs +341 -0
  94. package/lib/chunk-OO6CLPEH.mjs +7 -0
  95. package/lib/chunk-OPXCV2KL.mjs +7 -0
  96. package/lib/chunk-P33PSCXK.mjs +7 -0
  97. package/lib/{chunk-AUTM6H6Z.mjs → chunk-PJ5I73CK.mjs} +1 -1
  98. package/lib/{chunk-NTDN2JQZ.mjs → chunk-PZPJKATS.mjs} +1 -1
  99. package/lib/{chunk-5QKTYCWE.mjs → chunk-Q3DM32KF.mjs} +1 -1
  100. package/lib/{chunk-K22PA4XL.mjs → chunk-QR3WELJQ.mjs} +1 -1
  101. package/lib/{chunk-42RER7V4.mjs → chunk-R3X3LV64.mjs} +1 -1
  102. package/lib/chunk-RMBPOTD7.mjs +7 -0
  103. package/lib/{chunk-IEYG5ATY.mjs → chunk-RPI7LRTW.mjs} +1 -1
  104. package/lib/{chunk-5MMXFWPD.mjs → chunk-SE4QEZUG.mjs} +1 -1
  105. package/lib/{chunk-ALJVEUUS.mjs → chunk-SIHORWVK.mjs} +1 -1
  106. package/lib/{chunk-AAVJ5XVX.mjs → chunk-SOGQW4IG.mjs} +1 -1
  107. package/lib/chunk-SOU4FRYN.mjs +7 -0
  108. package/lib/chunk-SU65Z2BA.mjs +7 -0
  109. package/lib/chunk-T62WNR54.mjs +7 -0
  110. package/lib/{chunk-5O6JOMHS.mjs → chunk-TSLJUSLW.mjs} +1 -1
  111. package/lib/chunk-TTFDUKUS.mjs +47 -0
  112. package/lib/{chunk-57VHUYNG.mjs → chunk-TTKXMDBN.mjs} +1 -1
  113. package/lib/chunk-UCD54V2M.mjs +7 -0
  114. package/lib/{chunk-TBZMC2VV.mjs → chunk-UNJA4J37.mjs} +1 -1
  115. package/lib/{chunk-NGSMZZDA.mjs → chunk-VE6XKGGD.mjs} +1 -1
  116. package/lib/chunk-VS7ZXUII.mjs +824 -0
  117. package/lib/{chunk-ALUFROGA.mjs → chunk-VXQLDM4R.mjs} +1 -1
  118. package/lib/chunk-VYXMVJL5.mjs +7 -0
  119. package/lib/{chunk-WFEB5X4U.mjs → chunk-W622GUAW.mjs} +1 -1
  120. package/lib/chunk-W7U5E5ZL.mjs +9 -0
  121. package/lib/{chunk-AR7BE5O2.mjs → chunk-WA7EYLAQ.mjs} +1 -1
  122. package/lib/{chunk-EQF2IJS2.mjs → chunk-WR4Q363I.mjs} +1 -1
  123. package/lib/{chunk-ZXH4MBWP.mjs → chunk-WU3GLFZO.mjs} +1 -1
  124. package/lib/chunk-WXAQ7FK3.mjs +115 -0
  125. package/lib/{chunk-YBU4Z4QV.mjs → chunk-X5JYBPXP.mjs} +1 -1
  126. package/lib/chunk-XAMBCQPU.mjs +7 -0
  127. package/lib/{chunk-LQ4DRFUH.mjs → chunk-XLXIPIEW.mjs} +1 -1
  128. package/lib/{chunk-H2PJNIYJ.mjs → chunk-XUWL6ZPC.mjs} +1 -1
  129. package/lib/{chunk-P42X3B4D.mjs → chunk-YKKRIEH4.mjs} +1 -1
  130. package/lib/chunk-YRQGKDHM.mjs +7 -0
  131. package/lib/chunk-ZM6OJGIG.mjs +7 -0
  132. package/lib/{chunk-SFURUNJM.mjs → chunk-ZVAED4QV.mjs} +1 -1
  133. package/lib/sandforge-autopilot.mjs +29 -24
  134. package/lib/sandforge-backup.mjs +25 -21
  135. package/lib/sandforge-checkpoint.mjs +15 -14
  136. package/lib/sandforge-cleanup.mjs +14 -10
  137. package/lib/sandforge-clone.mjs +1 -1
  138. package/lib/sandforge-compare.mjs +9 -8
  139. package/lib/sandforge-dataops.mjs +1 -1
  140. package/lib/sandforge-empty.mjs +15 -15
  141. package/lib/sandforge-env.mjs +88 -88
  142. package/lib/sandforge-frozen.mjs +43 -34
  143. package/lib/sandforge-mcp.mjs +12 -12
  144. package/lib/sandforge-monitor.mjs +7 -7
  145. package/lib/sandforge-seed.mjs +1 -1
  146. package/lib/sandforge-sync.mjs +1 -1
  147. package/lib/sandforge.mjs +4 -4
  148. package/package.json +1 -1
  149. package/lib/chunk-2S5OMIIA.mjs +0 -7
  150. package/lib/chunk-36U7IQ6Y.mjs +0 -25
  151. package/lib/chunk-3F5YMM2F.mjs +0 -7
  152. package/lib/chunk-3RYLICRX.mjs +0 -7
  153. package/lib/chunk-4GL773D5.mjs +0 -7
  154. package/lib/chunk-4XZ5YT5O.mjs +0 -7
  155. package/lib/chunk-5AJRHRXA.mjs +0 -20
  156. package/lib/chunk-5HMAPZBV.mjs +0 -7
  157. package/lib/chunk-6LAXTAVN.mjs +0 -7
  158. package/lib/chunk-6MUEPV7M.mjs +0 -9
  159. package/lib/chunk-75ADZS6B.mjs +0 -7
  160. package/lib/chunk-B45CNPUX.mjs +0 -47
  161. package/lib/chunk-BS5T3MOQ.mjs +0 -7
  162. package/lib/chunk-D3QRXG63.mjs +0 -787
  163. package/lib/chunk-EEVVGGM6.mjs +0 -7
  164. package/lib/chunk-ENLBYECD.mjs +0 -7
  165. package/lib/chunk-EQOQASDQ.mjs +0 -7
  166. package/lib/chunk-FQBRBBY4.mjs +0 -7
  167. package/lib/chunk-GAM726CK.mjs +0 -7
  168. package/lib/chunk-HUMEKZT5.mjs +0 -8
  169. package/lib/chunk-I3JKJTLO.mjs +0 -110
  170. package/lib/chunk-KLX67VPL.mjs +0 -7
  171. package/lib/chunk-L776PUMV.mjs +0 -7
  172. package/lib/chunk-NEVXIGR6.mjs +0 -10
  173. package/lib/chunk-NHWE66K5.mjs +0 -7
  174. package/lib/chunk-OQOZAPCI.mjs +0 -7
  175. package/lib/chunk-PA3MKJVH.mjs +0 -7
  176. package/lib/chunk-RH3N2H7P.mjs +0 -7
  177. package/lib/chunk-SRQDABQ2.mjs +0 -15
  178. package/lib/chunk-SVS6UMDU.mjs +0 -323
  179. package/lib/chunk-TNXUU6W7.mjs +0 -14
  180. package/lib/chunk-VXHDBYMI.mjs +0 -7
  181. package/lib/chunk-WRU5FJFC.mjs +0 -7
  182. package/lib/chunk-X2PY6MWZ.mjs +0 -7
  183. package/lib/chunk-XEFDB2R4.mjs +0 -7
  184. package/lib/chunk-XETCPL7E.mjs +0 -7
  185. package/lib/chunk-Y5CGXLUB.mjs +0 -7
  186. package/lib/chunk-Y6J6QFI2.mjs +0 -7
  187. package/lib/chunk-YMJVMFPY.mjs +0 -7
  188. package/lib/chunk-YPSRZRIT.mjs +0 -7
  189. package/lib/chunk-YW2SBL4Z.mjs +0 -7
  190. package/lib/chunk-ZE6HKRR4.mjs +0 -9
  191. package/lib/chunk-ZLZRU6MO.mjs +0 -7
  192. package/lib/chunk-ZYEE34WO.mjs +0 -7
@@ -0,0 +1,10 @@
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 B,b as J}from"./chunk-TYYOBZMU.mjs";import{a as S}from"./chunk-GGD7ON3M.mjs";import{Ca as b,ta as h,ua as E,va as U,wa as D}from"./chunk-TTFDUKUS.mjs";import{b as l,l as m,s as C,u as H,v as K}from"./chunk-7EANH5PY.mjs";import{randomBytes as L}from"node:crypto";import{mkdirSync as we,statSync as Y}from"node:fs";import{mkdir as w,open as ye,readFile as A,readdir as _,rename as Oe,rm as f,rmdir as Fe,stat as x}from"node:fs/promises";import{homedir as V}from"node:os";import{join as c,resolve as xe}from"node:path";import{promisify as Q}from"node:util";import{gunzip as Ie,gzip as Ce}from"node:zlib";import{createHash as ke}from"node:crypto";var G=16,Z=m({digest:l().regex(/^[0-9a-f]{64}$/),fields:C(l(),l().regex(new RegExp(`^[0-9a-f]{${G}}$`)))});function W(n){return ke("sha256").update(n).digest("hex")}function me(n){return JSON.stringify([n.name.toLowerCase(),n.type,n.createable===!0,n.updateable===!0,n.nillable===!0,[...n.referenceTo??[]].sort(),n.encrypted===!0])}function an(n){let e=n.map(t=>({name:t.name,key:t.name.toLowerCase(),line:me(t)})).sort((t,r)=>t.key<r.key?-1:t.key>r.key?1:0);return{digest:W(e.map(({line:t})=>t).join(`
8
+ `)),fields:Object.fromEntries(e.map(({name:t,line:r})=>[t,W(r).slice(0,G)]))}}function dn(n,e){let t={added:[],removed:[],changed:[]};if(n.digest===e.digest)return t;let r=new Map(Object.entries(n.fields).map(([o,s])=>[o.toLowerCase(),{name:o,print:s}])),i=new Map(Object.entries(e.fields).map(([o,s])=>[o.toLowerCase(),{name:o,print:s}]));for(let[o,{name:s,print:a}]of i){let p=r.get(o);p===void 0?t.added.push(s):p.print!==a&&t.changed.push(s)}for(let[o,{name:s}]of r)i.has(o)||t.removed.push(s);return t.added.sort(),t.removed.sort(),t.changed.sort(),t}var g=448,be=384,Pe=30,ee=3,Ee=15,ne=1440*6e4,I=1440*6e4,De=Q(Ce),Se=Q(Ie),T="checkpoint.json",ve="fingerprints.json.gz",ze="fingerprints.json",Re="snapshots.json",te=/^[A-Za-z][A-Za-z0-9_]*$/;function xn(n=process.env){let e=n.SANDFORGE_JOURNAL_DIR,t=e!==void 0&&e.trim()!==""?xe(e):c(V(),".sandforge");return c(t,"checkpoints")}function Le(n=V()){return c(n,".sandforge","locks")}function k(n){let e=D.safeParse(n).success?S(n.slice(0,15)):void 0;if(e===void 0)throw new d("invalid","Not an Organization Id");return e}function Ae(n){return n.length===18&&D.safeParse(n).success&&S(n.slice(0,15))===n}function v(n,e,t){return re(c(n,e,t),e,t)}function re(n,e,t){return{organizationId:e,checkpointId:t,dir:n,checkpointFile:c(n,T),fingerprintsFile:c(n,ve),plainFingerprintsFile:c(n,ze),snapshotsFile:c(n,Re),indexDir:c(n,"index"),binDir:c(n,"bin"),filesDir:c(n,"files"),previewsDir:c(n,"previews"),rewindsDir:c(n,"rewinds")}}function ie(n){if(!te.test(n)||n.length>80)throw new d("invalid","Not a Salesforce API name");return n}function In(n,e){return c(n.indexDir,`${ie(e)}.idx`)}function Cn(n){return c(n.indexDir,"recreated.ndjson")}function bn(n){return c(n.indexDir,"notInBin.ndjson")}function Pn(n,e){return c(n.binDir,`${ie(e)}.ids`)}function En(n){return c(n.filesDir,"documents.ndjson")}function Dn(n){return c(n.filesDir,"links.ndjson")}var $e=[/^checkpoint\.json$/,/^fingerprints\.json(?:\.gz)?$/,/^snapshots\.json$/,/^backups\/[A-Za-z0-9_-]{1,200}__[A-Za-z][A-Za-z0-9_]{0,79}\.ndjson(?:\.gz)?$/,/^bin\/[A-Za-z][A-Za-z0-9_]{0,79}\.ids$/,/^files\/(?:links|documents)\.ndjson(?:\.gz)?$/,/^index\/(?:recreated|notInBin)\.ndjson$/],je=["","backups","bin","files","index"],Sn=T;function oe(n){return $e.some(e=>e.test(n))}async function vn(n){let e=[];for(let t of je){let r;try{r=await _(c(n.dir,t),{withFileTypes:!0})}catch(i){if(F(i)==="ENOENT"||F(i)==="ENOTDIR")continue;throw i}for(let i of r){let o=t===""?i.name:`${t}/${i.name}`;if(!i.isFile()||!oe(o))continue;let s=c(n.dir,t,i.name);e.push({path:o,file:s,bytes:(await x(s)).size})}}return e.sort((t,r)=>he(t.path,r.path))}function zn(n,e){if(!oe(e))throw new d("invalid","Not a file a checkpoint holds");return c(n,...e.split("/"))}function Rn(n,e){return c(n.previewsDir,O(E,e))}function M(n,e){return c(n.rewindsDir,O(U,e))}function O(n,e){let t=n.safeParse(e);if(!t.success)throw new d("invalid","Not an id of this store");return t.data}async function X(n){await w(n,{recursive:!0,mode:g})}var q="abcdefghijklmnopqrstuvwxyz0123456789";function Ln(n,e=new Date){let t=e.toISOString(),r=`${t.slice(0,4)}${t.slice(5,7)}${t.slice(8,10)}`,i=`${t.slice(11,13)}${t.slice(14,16)}${t.slice(17,19)}`,o=Array.from(L(4),s=>q[s%q.length]).join("");return`${n}-${r}-${i}-${o}`}function Ne(n,e){if(!Number.isInteger(e)||e<0)throw new RangeError(`Not a number of days: ${e}`);return e===0?null:new Date(n.getTime()+e*I).toISOString()}function se(n,e){return n.expiresAt!==null&&Date.parse(n.expiresAt)<=e}function _e(n,e){if(n.expiresAt===null)return!1;let t=Date.parse(n.expiresAt);return t>e&&t-e<=ee*I}function Te(n,e){let t=e-Ee*I;return Date.parse(n.readFrom)<t?new Date(t).toISOString():void 0}function Me(n,e){let t=ce(n);return t!==void 0&&t<=e}function ce(n){let e=n.scratchExpiresAt;if(e===void 0)return;let t=Date.parse(e);if(Number.isFinite(t))return/^\d{4}-\d{2}-\d{2}$/.test(e)?t+I:t}function He(n,e){let t=ce(n);return t!==void 0&&t>e&&t-e<=ee*I}var d=class extends Error{constructor(t,r){super(r);this.code=t;this.name="CheckpointStoreError"}code};function An(n,e,t){let r=n.detail!==void 0?` (${n.detail})`:"";if(n.path===e)switch(n.reason){case"otherOwner":return`another user of this machine owns it, and could read and replace the checkpoints in it. ${t} names a folder of your own.`;case"notAFolder":return`it is a file, not a folder. ${t} names a folder for them, or move the file away.`;case"cannotMake":return`it could not be made${r}. ${t} names a folder this user can write.`}let i="the folder of every org\u2019s lock, whatever the store";switch(n.reason){case"otherOwner":return`${i}, is owned by another user of this machine: run as its owner, or remove it.`;case"notAFolder":return`${i}, is a file, not a folder: move the file away.`;case"cannotMake":return`${i}, could not be made${r}: make it a folder this user can write.`}}var ae=m({version:K(1),objects:C(l().regex(te).max(80),Z)});async function Ke(n,e){let t;try{t=JSON.parse(await Be(n))}catch{throw new d("damaged","The checkpoint\u2019s field prints cannot be read")}let r=ae.safeParse(t);if(!r.success)throw new d("damaged","The checkpoint\u2019s field prints do not parse");let i=new Map(Object.entries(r.data.objects));for(let o of e)if(i.get(o.objectApiName)?.digest!==o.fingerprint)throw new d("damaged",`The field prints of ${o.objectApiName} are not the checkpoint\u2019s`);return i}async function Ue(n){let e=ae.safeParse({version:1,objects:n});if(!e.success)throw new d("invalid",`Not field prints: ${e.error.message}`);return De(`${JSON.stringify(e.data)}
9
+ `)}async function Be(n){let e;try{e=await A(n.fingerprintsFile)}catch(t){if(t.code!=="ENOENT")throw t;return A(n.plainFingerprintsFile,"utf8")}return(await Se(e)).toString("utf8")}function $n(n){let e=n.uid??(()=>process.getuid?.()),t=n.locksDir??Le();for(let r of[n.root,t]){let i=Je(r,e);if(i!==void 0)return{refusal:i}}return{store:new $({...n,locksDir:t})}}function Je(n,e){try{let t=Y(n,{throwIfNoEntry:!1});if(t!==void 0&&!t.isDirectory())return{reason:"notAFolder",path:n};we(n,{recursive:!0,mode:g});let r=e();return r!==void 0&&Y(n).uid!==r?{reason:"otherOwner",path:n}:void 0}catch(t){return{reason:"cannotMake",path:n,detail:sn(t)}}}var $=class{root;locksDir;renameFile;lockOptions;changes=new Map;constructor(e){this.root=e.root,this.locksDir=e.locksDir,this.renameFile=e.rename??((t,r)=>Oe(t,r)),this.lockOptions={...e.lockSelf?{self:e.lockSelf}:{},...e.lockChecks?{checks:e.lockChecks}:{}}}folderOf(e,t){return v(this.root,k(e),O(h,t))}async create(e,t){let r=this.folderOf(e,t);await X(c(this.root,r.organizationId));try{await w(r.dir,{mode:g})}catch(i){throw F(i)==="EEXIST"?new d("exists",`A checkpoint ${t} is kept already`):i}return await w(r.indexDir,{mode:g}),await w(r.binDir,{mode:g}),r}async write(e){let t=z(e),r=this.folderOf(t.org.organizationId,t.checkpointId);await this.writeWhole(r.checkpointFile,j(t))}async writeFingerprints(e,t){await this.writeWhole(e.fingerprintsFile,await Ue(t))}async readFingerprints(e,t){return Ke(e,t.objects)}async checkpointsOf(e){return this.readsOf(k(e))}async read(e){let t=O(h,e);for(let r of await this.organizationKeys()){let i=v(this.root,r,t);if(await y(i.dir))return R(i)}}async update(e,t){let r=async()=>{let a=await this.read(e);if(a===void 0)throw new d("notFound",`No checkpoint ${e} is kept`);if(a.checkpoint===void 0)throw new d("damaged",`The checkpoint ${e} is damaged`);let p=t(structuredClone(a.checkpoint));if(p.checkpointId!==a.folder.checkpointId||N(p.org.organizationId)!==a.folder.organizationId)throw new d("invalid","A change never moves a checkpoint");return await this.write(p),b.parse(p)},o=(this.changes.get(e)??Promise.resolve()).then(r,r),s=o.catch(()=>{});return this.changes.set(e,s),s.then(()=>{this.changes.get(e)===s&&this.changes.delete(e)}),o}keep(e,t,r=new Date){return this.update(e,i=>({...i,expiresAt:t?null:Ne(r,Pe)}))}async list(e={}){let t=(e.now??new Date).getTime(),r=e.organizationId!==void 0?k(e.organizationId):void 0,i=[];for(let o of await this.organizationKeys(r)){let s=await this.readsOf(o),a=Xe(s);for(let p of s)i.push(await Ve(p,t,a,e.refreshedAt))}return i.sort((o,s)=>he(s.checkpointId,o.checkpointId))}async delete(e){let t=await this.read(e);if(t===void 0)return{outcome:"notFound"};let r=this.lock(t.folder.organizationId,"delete",t.folder.checkpointId);if("busy"in r)return{outcome:"busy",holder:r.busy};try{await f(t.folder.dir,{recursive:!0,force:!0})}finally{r.lock.release()}return t.checkpoint?{outcome:"deleted",checkpoint:t.checkpoint}:{outcome:"deleted"}}async importInto(e,t,r){let i=this.folderOf(e,t),o=c(this.root,i.organizationId);await X(o);let s=re(c(o,`${We}${L(6).toString("hex")}`),i.organizationId,i.checkpointId);await w(s.dir,{mode:g});try{let a=z(await r(s));if(a.checkpointId!==i.checkpointId||N(a.org.organizationId)!==i.organizationId)throw new d("invalid","An import keeps the checkpoint it was asked to");let p=z({...a,bytes:await Ye(s.dir,a)});if(await this.writeWhole(s.checkpointFile,j(p)),await y(i.dir))return{outcome:"exists"};try{await this.renameFile(s.dir,i.dir)}catch(u){if(await y(i.dir))return{outcome:"exists"};throw u}return{outcome:"imported",checkpoint:p}}finally{await f(s.dir,{recursive:!0,force:!0}),await Fe(o).catch(()=>{})}}async sweep(e=new Date){let t=e.getTime(),r={checkpoints:[],journals:[],previews:0,skipped:[]};for(let i of await this.organizationKeys()){await Ze(c(this.root,i),t);let o=await Qe(await this.readsOf(i),t);if(o.length===0)continue;let s=this.lock(i,"sweep");if("busy"in s){r.skipped.push(i);continue}try{for(let a of o)await en(await R(a),t,r)}finally{s.lock.release()}}return r}lock(e,t,r){return rn(this.locksDir,e,{operation:t,...r!==void 0?{checkpointId:r}:{}},this.lockOptions)}heldBy(e){return on(this.locksDir,e,this.lockOptions)}async organizationKeys(e){return(await P(this.root)).filter(r=>Ae(r)&&(e===void 0||r===e))}async readsOf(e){let t=(await P(c(this.root,e))).filter(i=>h.safeParse(i).success),r=[];for(let i of t)r.push(await R(v(this.root,e,i)));return r}async writeWhole(e,t){let r=`${e}.${process.pid}-${L(4).toString("hex")}.tmp`,i=await ye(r,"wx",be);try{try{await i.writeFile(t,typeof t=="string"?"utf8":void 0),await i.sync()}finally{await i.close()}await this.renameFile(r,e)}catch(o){throw await f(r,{force:!0}),o}}},We=".importing-",Ge=/^\.importing-[0-9a-f]{12}$/;async function Ze(n,e){for(let t of await P(n)){if(!Ge.test(t))continue;let r=c(n,t),i=await x(r).catch(()=>{});i!==void 0&&i.mtimeMs+ne<=e&&await f(r,{recursive:!0,force:!0})}}function z(n){let e=b.safeParse(n);if(!e.success)throw new d("invalid",`Not a checkpoint: ${e.error.message}`);return e.data}function j(n){return`${JSON.stringify(n,null,2)}
10
+ `}async function de(n,e){let t=0;for(let r of await _(n,{withFileTypes:!0})){let i=c(n,r.name);r.isDirectory()?t+=await de(i,e):r.isFile()&&i!==e&&(t+=(await x(i)).size)}return t}async function Ye(n,e){let t=await de(n,c(n,T)),r=o=>Buffer.byteLength(j({...e,bytes:o}),"utf8"),i=t+r(t);return i=t+r(i),i}async function R(n){let e;try{e=JSON.parse(await A(n.checkpointFile,"utf8"))}catch{return{folder:n}}let t=b.safeParse(e);return t.success?t.data.checkpointId!==n.checkpointId||N(t.data.org.organizationId)!==n.organizationId?{folder:n}:{folder:n,checkpoint:t.data}:{folder:n}}function Xe(n){let e;for(let{folder:t,checkpoint:r}of n){let i=r?.lastRewind?.rewindId;i!==void 0&&(e===void 0||i>e.rewindId)&&(e={checkpointId:t.checkpointId,rewindId:i})}return e}function qe(n,e,t,r){if(n.status==="taking")return{why:"taking"};if(n.status==="failed")return{why:"failed"};let i=r?.(e);if(i!==void 0)return{why:"refreshed",refreshedAt:i};if(Me(n.org,t))return{why:"scratchExpired"}}async function Ve({folder:n,checkpoint:e},t,r,i){let o={checkpointId:n.checkpointId,organizationId:n.organizationId};if(e===void 0)return{...o,valid:!1,why:"damaged"};let s=qe(e,n.organizationId,t,i);if(s!==void 0)return{...o,checkpoint:e,valid:!1,why:s.why,...s.refreshedAt!==void 0?{refreshedAt:s.refreshedAt}:{}};let a={...o,checkpoint:e,valid:!0};_e(e,t)&&(a.expiresSoon=!0),He(e.org,t)&&(a.scratchExpiresSoon=!0);let p=Te(e,t);p!==void 0&&(a.binReachSince=p);let u=e.lastRewind;return u!==void 0&&r?.checkpointId===n.checkpointId&&u.undoUntil!==void 0&&u.undoneAt===void 0&&Date.parse(u.undoUntil)>t&&await y(M(n,u.rewindId))&&(a.undo={rewindId:u.rewindId,until:u.undoUntil}),a}async function Qe(n,e){let t=[];for(let{folder:r,checkpoint:i}of n)i!==void 0&&(se(i,e)||await pe(r,i,e)||(await ue(r,e)).length>0)&&t.push(r);return t}async function pe(n,e,t){let r=e.lastRewind?.undoUntil;return e.lastRewind!==void 0&&r!==void 0&&Date.parse(r)<=t&&await y(M(n,e.lastRewind.rewindId))}async function ue(n,e){let t=[];for(let r of await P(n.previewsDir)){if(!E.safeParse(r).success)continue;let i=c(n.previewsDir,r),o=await x(i).catch(()=>{});o!==void 0&&o.mtimeMs+ne<=e&&t.push(i)}return t}async function en(n,e,t){let{folder:r,checkpoint:i}=n;if(i===void 0)return;if(i.expiresAt!==null&&se(i,e)){await f(r.dir,{recursive:!0,force:!0});let s=i.lastRewind?.undoUntil,a=s!==void 0&&i.lastRewind?.undoneAt===void 0&&Date.parse(s)>e;t.checkpoints.push({organizationId:r.organizationId,checkpointId:r.checkpointId,name:i.name,...i.org.alias!==void 0?{alias:i.org.alias}:{},takenAt:i.takenAt,expiresAt:i.expiresAt,...a?{undoUntil:s}:{}});return}let o=i.lastRewind;o?.undoUntil!==void 0&&await pe(r,i,e)&&(await f(M(r,o.rewindId),{recursive:!0,force:!0}),t.journals.push({organizationId:r.organizationId,checkpointId:r.checkpointId,name:i.name,rewindId:o.rewindId,undoUntil:o.undoUntil}));for(let s of await ue(r,e))await f(s,{recursive:!0,force:!0}),t.previews+=1}var nn=m({...B,operation:H(["take","rewind","undo","delete","sweep","empty"]),checkpointId:h.optional()}),fe=J(n=>{let e=nn.safeParse(n);return e.success?e.data:void 0});function tn(n,e){return c(n,`${k(e)}.lock`)}function rn(n,e,t,r={}){let i=k(e),o=t.checkpointId!==void 0?O(h,t.checkpointId):void 0,s=fe.acquire(c(n,`${i}.lock`),a=>({...a,operation:t.operation,...o!==void 0?{checkpointId:o}:{}}),r);return"busy"in s?{busy:le(s.busy)}:{lock:{organizationId:i,release:s.lock.release}}}function on(n,e,t={}){let r=fe.holder(tn(n,e),t);return r!==void 0?le(r):void 0}function le({version:n,token:e,...t}){return t}async function P(n){try{return(await _(n,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name)}catch(e){if(F(e)==="ENOENT"||F(e)==="ENOTDIR")return[];throw e}}async function y(n){return(await x(n).catch(()=>{}))?.isDirectory()===!0}function N(n){try{return k(n)}catch{return}}function he(n,e){return n<e?-1:n>e?1:0}function F(n){return n?.code}function sn(n){return n instanceof Error?n.message:String(n)}export{an as a,dn as b,g as c,be as d,Pe as e,ee as f,Ee as g,ne as h,xn as i,Le as j,k,In as l,Cn as m,bn as n,Pn as o,En as p,Dn as q,Sn as r,oe as s,vn as t,zn as u,Rn as v,M as w,X as x,Ln as y,Ne as z,se as A,_e as B,Te as C,Me as D,He as E,d as F,An as G,Ke as H,Ue as I,$n as J,$ as K,Xe as L,tn as M,rn as N,on as O};
@@ -4,5 +4,5 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a as w,b as x}from"./chunk-EQF2IJS2.mjs";import{b as R}from"./chunk-TEOLMRDO.mjs";import{g as k}from"./chunk-NTDN2JQZ.mjs";import{Sa as h,ia as g,la as l}from"./chunk-B45CNPUX.mjs";import{b as d,m as S,s as u,v as f}from"./chunk-7EANH5PY.mjs";import{createHash as $}from"node:crypto";import{mkdir as y,readFile as C,rename as P,writeFile as O}from"node:fs/promises";import*as a from"node:path";var A=k,N=d().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"A record id"),p=S({version:f(1),runId:d().min(1).max(200),packId:g,packFingerprint:d().regex(/^[0-9a-f]{64}$/,"A sha256, in lower-case hexadecimal"),compile:l.refine(e=>e.seed!==void 0,{message:"The seed the pack was compiled with is kept",path:["seed"]}),openCases:u(d().min(1).max(255),N),agent:h.optional()});function F(e){return $("sha256").update(m(e)).digest("hex")}function v(e){let r={};for(let i of e.compiled.tests){let n=i.openCase?.caseKey;if(n===void 0)continue;let t=e.caseIds[n];t!==void 0&&(r[n]=t)}return p.parse({version:1,runId:e.runId,packId:e.pack.id,packFingerprint:F(e.pack),compile:{...e.options,seed:e.compiled.seed},openCases:r})}function D(e,r){return p.parse({...e,agent:r})}function U(e,r){if(r.id!==e.packId)return{ok:!1,message:`The run was seeded from the scenario ${e.packId}, not ${r.id}`};if(F(r)!==e.packFingerprint)return{ok:!1,message:`The scenario ${r.id} has changed since the run: its tests would be about subjects and addresses no record of the run holds`};try{return{ok:!0,compiled:x(r,e.compile)}}catch(i){if(i instanceof w)return{ok:!1,message:i.message};throw i}}function Z(){return{readFile:e=>C(e,"utf8"),writeFile:(e,r)=>O(e,r,"utf8"),rename:(e,r)=>P(e,r),mkdir:async e=>{await y(e,{recursive:!0})}}}function I(e,r){return a.join(e,R,`${r.replace(/[^A-Za-z0-9_-]/g,"_")}${A}`)}async function K(e,r,i){let n=p.parse(i),t=I(r,n.runId),o=`${t}.${process.pid}.tmp`;return await e.mkdir(a.dirname(t)),await e.writeFile(o,`${JSON.stringify(n,null,2)}
7
+ import{a as w,b as x}from"./chunk-WR4Q363I.mjs";import{b as R}from"./chunk-E5AHXLS6.mjs";import{g as k}from"./chunk-PZPJKATS.mjs";import{Va as h,ka as g,na as l}from"./chunk-TTFDUKUS.mjs";import{b as d,m as S,s as u,v as f}from"./chunk-7EANH5PY.mjs";import{createHash as $}from"node:crypto";import{mkdir as y,readFile as C,rename as P,writeFile as O}from"node:fs/promises";import*as a from"node:path";var A=k,N=d().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"A record id"),p=S({version:f(1),runId:d().min(1).max(200),packId:g,packFingerprint:d().regex(/^[0-9a-f]{64}$/,"A sha256, in lower-case hexadecimal"),compile:l.refine(e=>e.seed!==void 0,{message:"The seed the pack was compiled with is kept",path:["seed"]}),openCases:u(d().min(1).max(255),N),agent:h.optional()});function F(e){return $("sha256").update(m(e)).digest("hex")}function v(e){let r={};for(let i of e.compiled.tests){let n=i.openCase?.caseKey;if(n===void 0)continue;let t=e.caseIds[n];t!==void 0&&(r[n]=t)}return p.parse({version:1,runId:e.runId,packId:e.pack.id,packFingerprint:F(e.pack),compile:{...e.options,seed:e.compiled.seed},openCases:r})}function D(e,r){return p.parse({...e,agent:r})}function U(e,r){if(r.id!==e.packId)return{ok:!1,message:`The run was seeded from the scenario ${e.packId}, not ${r.id}`};if(F(r)!==e.packFingerprint)return{ok:!1,message:`The scenario ${r.id} has changed since the run: its tests would be about subjects and addresses no record of the run holds`};try{return{ok:!0,compiled:x(r,e.compile)}}catch(i){if(i instanceof w)return{ok:!1,message:i.message};throw i}}function Z(){return{readFile:e=>C(e,"utf8"),writeFile:(e,r)=>O(e,r,"utf8"),rename:(e,r)=>P(e,r),mkdir:async e=>{await y(e,{recursive:!0})}}}function I(e,r){return a.join(e,R,`${r.replace(/[^A-Za-z0-9_-]/g,"_")}${A}`)}async function K(e,r,i){let n=p.parse(i),t=I(r,n.runId),o=`${t}.${process.pid}.tmp`;return await e.mkdir(a.dirname(t)),await e.writeFile(o,`${JSON.stringify(n,null,2)}
8
8
  `),await e.rename(o,t),t}async function X(e,r,i){let n=I(r,i),t;try{t=await e.readFile(n)}catch(c){if(c.code==="ENOENT")return{kind:"absent"};throw c}let o;try{o=JSON.parse(t)}catch{return{kind:"invalid",message:`${a.basename(n)} is not JSON`}}let s=p.safeParse(o);if(!s.success){let c=s.error.issues[0];return{kind:"invalid",message:`${a.basename(n)}: ${c.path.join(".")||"the file"}: ${c.message}`}}return s.data.runId!==i?{kind:"invalid",message:`${a.basename(n)} is the companion of the run ${s.data.runId}, not ${i}`}:{kind:"read",sidecar:s.data}}function m(e){return Array.isArray(e)?`[${e.map(r=>m(r??null)).join(",")}]`:e!==null&&typeof e=="object"?`{${Object.entries(e).filter(([,i])=>i!==void 0).sort(([i],[n])=>i<n?-1:i>n?1:0).map(([i,n])=>`${JSON.stringify(i)}:${m(n)}`).join(",")}}`:JSON.stringify(e??null)}export{A as a,p as b,F as c,v as d,D as e,U as f,Z as g,I as h,K as i,X 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{a,b,c,d,e,f,g,h,i,j,k,l,m}from"./chunk-5O6JOMHS.mjs";import"./chunk-NEVXIGR6.mjs";import"./chunk-TYYOBZMU.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-SIOZXPFG.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{c as LEDGER_KEPT_LINES,b as LEDGER_MAX_LINES,i as OrgClockWatch,a as REWIND_LEDGER_FILE,f as appendToRewindLedger,l as noteRewindEnded,m as noteRewindUndone,g as readRewindLedger,h as readRewindLedgers,k as rewindEndedRecord,e as rewindLedgerBeside,d as rewindLedgerFileOf,j as rewindTotalsOf};
7
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m}from"./chunk-TSLJUSLW.mjs";import"./chunk-IFETCRWE.mjs";import"./chunk-TYYOBZMU.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-GGD7ON3M.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{c as LEDGER_KEPT_LINES,b as LEDGER_MAX_LINES,i as OrgClockWatch,a as REWIND_LEDGER_FILE,f as appendToRewindLedger,l as noteRewindEnded,m as noteRewindUndone,g as readRewindLedger,h as readRewindLedgers,k as rewindEndedRecord,e as rewindLedgerBeside,d as rewindLedgerFileOf,j as rewindTotalsOf};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s}from"./chunk-ENLBYECD.mjs";import"./chunk-PA3MKJVH.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{r as BEFORE_RUN_DELETED_WORDS,e as BEFORE_RUN_DISK_ROOM,a as WRITE_PATH_STEPS,j as beforeRunAskedOf,f as beforeRunDiskRefusal,d as beforeRunEstimateOf,q as beforeRunFailedWords,i as beforeRunKeepDaysOf,h as beforeRunNameOf,l as beforeRunOutcomeOf,s as beforeRunProgressWords,p as beforeRunRefusedWords,c as beforeRunScopeOf,k as beforeRunTakenOf,g as freeBytesOf,m as scopeBeforeRun,o as settleBeforeRun,n as takeBeforeRun,b as writePathOrderDefects};
7
+ import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s}from"./chunk-AEKONPF4.mjs";import"./chunk-JWTSEDIQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{r as BEFORE_RUN_DELETED_WORDS,e as BEFORE_RUN_DISK_ROOM,a as WRITE_PATH_STEPS,j as beforeRunAskedOf,f as beforeRunDiskRefusal,d as beforeRunEstimateOf,q as beforeRunFailedWords,i as beforeRunKeepDaysOf,h as beforeRunNameOf,l as beforeRunOutcomeOf,s as beforeRunProgressWords,p as beforeRunRefusedWords,c as beforeRunScopeOf,k as beforeRunTakenOf,g as freeBytesOf,m as scopeBeforeRun,o as settleBeforeRun,n as takeBeforeRun,b as writePathOrderDefects};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a,b,c,d,e,f,g,h,i,j}from"./chunk-5QKTYCWE.mjs";import"./chunk-WJY54JO7.mjs";import"./chunk-NEVXIGR6.mjs";import"./chunk-HJC7AIBK.mjs";import"./chunk-TYYOBZMU.mjs";import"./chunk-ZUTYVST5.mjs";import"./chunk-55HEMHEG.mjs";import"./chunk-P42X3B4D.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-WIO4XO4F.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import"./chunk-CGWXQX75.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-SIOZXPFG.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{b as ARCHIVE_CHUNK_BYTES,a as ARCHIVE_EXTENSION,f as CheckpointExportError,d as archiveKeyText,h as exportCheckpointArchive,j as importCheckpointArchive,c as newArchiveKey,e as parseArchiveKey,g as portableCheckpointOf,i as readArchiveHeader};
7
+ import{a,b,c,d,e,f,g,h,i,j}from"./chunk-Q3DM32KF.mjs";import"./chunk-LPBMBW3O.mjs";import"./chunk-IFETCRWE.mjs";import"./chunk-EQNW3UC2.mjs";import"./chunk-TYYOBZMU.mjs";import"./chunk-ZUTYVST5.mjs";import"./chunk-CU2INBND.mjs";import"./chunk-YKKRIEH4.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-WIO4XO4F.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import"./chunk-A527W53V.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-GGD7ON3M.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{b as ARCHIVE_CHUNK_BYTES,a as ARCHIVE_EXTENSION,f as CheckpointExportError,d as archiveKeyText,h as exportCheckpointArchive,j as importCheckpointArchive,c as newArchiveKey,e as parseArchiveKey,g as portableCheckpointOf,i as readArchiveHeader};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a,b,c,d}from"./chunk-GNC27UEU.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{b as PARENT_IDS_PER_QUERY,a as readExistingParentIds,c as readPresentParentIds,d as recordParentsRefusals};
7
+ import{a,b,c,d}from"./chunk-BKDV4ENO.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{b as PARENT_IDS_PER_QUERY,a as readExistingParentIds,c as readPresentParentIds,d as recordParentsRefusals};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a as v}from"./chunk-SRPWW4A2.mjs";import"./chunk-4TLYUZD5.mjs";import{ib as D}from"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";function x(e){return{async retrieve(n){return{id:(await e.metadata.retrieve(n)).id}},checkRetrieveStatus:n=>e.metadata.checkRetrieveStatus(n),async deploy(n,t){return{id:(await e.metadata.deploy(n,t)).id}},checkDeployStatus:(n,t)=>e.metadata.checkDeployStatus(n,t)}}var N={pollMs:3e3,retrieveTimeoutMs:D.retrieve*6e4,deployTimeoutMs:D.deploy*6e4,sleep:e=>new Promise(n=>setTimeout(n,e)),now:Date.now},b=class extends Error{constructor(t,o,s,a){super(t==="deployment"?`Deployment ${o} was still ${s} after ${a} min; it goes on in the target org, and Setup \u203A Deployment Status follows it.`:`Retrieval ${o} was still ${s} after ${a} min; nothing was deployed.`);this.kind=t;this.asyncId=o;this.status=s;this.name="DeploymentStillRunning"}kind;asyncId;status};function d(e,n){return`${e}\0${k(n)}`}function k(e){try{return decodeURIComponent(e)}catch{return e}}function g(e){return e==null?[]:Array.isArray(e)?e:[e]}function R(e){return e===!0||e==="true"}function h(e){if(e==null||e==="")return;let n=Number(e);return Number.isFinite(n)?n:void 0}var P=/^Entity of type '(.+?)' named '(.+)' cannot be found$/;async function M(e,n,t,o){let s=new Map;for(let{componentType:i,fullName:m}of t)s.set(i,[...s.get(i)??[],m]);let a={apiVersion:Number(n),singlePackage:!0,unpackaged:{objectPermissions:[],types:[...s].map(([i,m])=>({members:m,name:i})),version:n}},{id:p}=await e.retrieve(a),u=o.now();for(;;){let i=await e.checkRetrieveStatus(p);if(i.done){if(i.success===!1||i.status==="Failed")throw new Error(`Retrieval ${p} from the source failed: ${i.errorMessage??i.status??"no reason given"}`);return i}if(o.now()-u>=o.retrieveTimeoutMs)throw new b("retrieval",p,i.status??"running",Math.round(o.retrieveTimeoutMs/6e4));await o.sleep(o.pollMs)}}async function I(e,n,t,o={}){let s=o.waiting??N;o.onProgress?.({step:"retrieve",done:0,total:t.length});let a=await M(e,n,t,s),p=new Map(t.map(l=>[d(l.componentType,l.fullName),l])),u=new Map,i=[];for(let l of g(a.messages)){let f=l.problem??"",T=P.exec(f),y=T?p.get(d(T[1],T[2])):void 0;y?u.set(d(y.componentType,y.fullName),{...y,problem:f}):f&&i.push(l.fileName?`${l.fileName}: ${f}`:f)}let m=t.filter(l=>!u.has(d(l.componentType,l.fullName))),r=a;m.length===0?r={...a,zipFile:""}:u.size>0&&(r=await M(e,n,m,s)),o.onProgress?.({step:"retrieve",done:m.length,total:t.length});let c=g(r.fileProperties).filter(l=>v(l)).map(l=>p.get(d(l.type??"",l.fullName??""))).filter(l=>l!==void 0);return{zipFile:r.zipFile??"",retrieved:m,missing:[...u.values()],managed:c,problems:i}}function A(e,n,t){return{allowMissingFiles:!1,autoUpdatePackage:!1,checkOnly:e,ignoreWarnings:!1,performRetrieve:!1,purgeOnDelete:!1,rollbackOnError:!0,...n==="RunSpecifiedTests"?{runTests:[...t]}:{},singlePackage:!0,testLevel:n}}async function E(e,n,t,o={}){let s=o.waiting??N,{id:a}=await e.deploy(n,t),p=s.now();for(;;){let u=await e.checkDeployStatus(a,!1);if(u.done)return e.checkDeployStatus(a,!0);if(o.onProgress?.(w(u)),s.now()-p>=s.deployTimeoutMs)throw new b("deployment",a,u.status??"running",Math.round(s.deployTimeoutMs/6e4));await s.sleep(s.pollMs)}}function w(e){let n=e.numberTestsTotal??0,t=e.numberComponentsTotal??0,o=(e.numberComponentsDeployed??0)+(e.numberComponentErrors??0);return n>0&&o>=t?{step:"tests",done:(e.numberTestsCompleted??0)+(e.numberTestErrors??0),total:n}:{step:"components",done:o,total:t}}function C(e){let n=/line (\d+), column \d+/.exec(e??"");return n?Number(n[1]):void 0}function O(e){let n=h(e.lineNumber),t=h(e.columnNumber),o=e.problemType==="Warning"||e.problemType==="Error"?e.problemType:void 0,s={componentType:e.componentType??"",fullName:e.fullName??"",...e.fileName?{fileName:e.fileName}:{}};if(!R(e.success))return{...s,outcome:"failed",...e.problem?{problem:e.problem}:{},...o?{problemType:o}:{},...n!==void 0?{line:n}:{},...t!==void 0?{column:t}:{}};let a=R(e.created)?"created":R(e.changed)?"changed":"unchanged";return{...s,outcome:a}}function $(e,n,t){let o=e?.details??void 0,s=new Map,a=[...g(o?.componentFailures),...g(o?.componentSuccesses)];for(let r of a){if(!r.componentType&&r.fullName==="package.xml")continue;let c=O(r),l=d(c.componentType,c.fullName);s.has(l)||s.set(l,c)}let p=n.missing.map(r=>({componentType:r.componentType,fullName:r.fullName,outcome:"not_retrieved",...r.problem?{problem:r.problem}:{}})),u=o?.runTestResult??void 0,i=g(u?.failures).map(r=>{let c=C(r.stackTrace);return{className:r.name??"",...r.methodName?{methodName:r.methodName}:{},message:r.message??"",...r.stackTrace?{stackTrace:r.stackTrace}:{},...c!==void 0?{line:c}:{}}}),m=g(u?.codeCoverageWarnings).map(r=>r.name?`${r.name}: ${r.message??""}`:r.message??"").filter(r=>r!=="");return{...e?.id?{deployId:e.id}:{},checkOnly:t.checkOnly,status:e?.status??"NotStarted",success:e?.success===!0&&n.missing.length===0,...e?.errorMessage?{errorMessage:e.errorMessage}:{},sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,testLevel:t.testLevel,runTests:[...t.runTests],components:[...s.values(),...p],counts:{componentsTotal:e?.numberComponentsTotal??0,componentsDeployed:e?.numberComponentsDeployed??0,componentErrors:e?.numberComponentErrors??0,testsTotal:e?.numberTestsTotal??0,testsCompleted:e?.numberTestsCompleted??0,testErrors:e?.numberTestErrors??0},testFailures:i,coverageWarnings:m,...n.problems.length>0?{retrieveProblems:[...n.problems]}:{},...e?.startDate?{startedAt:e.startDate}:{},...e?.completedDate?{completedAt:e.completedDate}:{}}}export{N as DEFAULT_WAITING,b as DeploymentStillRunning,A as deployOptions,E as deployPackage,$ as deploymentReport,x as metadataApiOf,I as retrieveComponents};
7
+ import{a as v}from"./chunk-SRPWW4A2.mjs";import"./chunk-4TLYUZD5.mjs";import{lb as D}from"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";function x(e){return{async retrieve(n){return{id:(await e.metadata.retrieve(n)).id}},checkRetrieveStatus:n=>e.metadata.checkRetrieveStatus(n),async deploy(n,t){return{id:(await e.metadata.deploy(n,t)).id}},checkDeployStatus:(n,t)=>e.metadata.checkDeployStatus(n,t)}}var N={pollMs:3e3,retrieveTimeoutMs:D.retrieve*6e4,deployTimeoutMs:D.deploy*6e4,sleep:e=>new Promise(n=>setTimeout(n,e)),now:Date.now},b=class extends Error{constructor(t,o,s,a){super(t==="deployment"?`Deployment ${o} was still ${s} after ${a} min; it goes on in the target org, and Setup \u203A Deployment Status follows it.`:`Retrieval ${o} was still ${s} after ${a} min; nothing was deployed.`);this.kind=t;this.asyncId=o;this.status=s;this.name="DeploymentStillRunning"}kind;asyncId;status};function d(e,n){return`${e}\0${k(n)}`}function k(e){try{return decodeURIComponent(e)}catch{return e}}function g(e){return e==null?[]:Array.isArray(e)?e:[e]}function R(e){return e===!0||e==="true"}function h(e){if(e==null||e==="")return;let n=Number(e);return Number.isFinite(n)?n:void 0}var P=/^Entity of type '(.+?)' named '(.+)' cannot be found$/;async function M(e,n,t,o){let s=new Map;for(let{componentType:i,fullName:m}of t)s.set(i,[...s.get(i)??[],m]);let a={apiVersion:Number(n),singlePackage:!0,unpackaged:{objectPermissions:[],types:[...s].map(([i,m])=>({members:m,name:i})),version:n}},{id:p}=await e.retrieve(a),u=o.now();for(;;){let i=await e.checkRetrieveStatus(p);if(i.done){if(i.success===!1||i.status==="Failed")throw new Error(`Retrieval ${p} from the source failed: ${i.errorMessage??i.status??"no reason given"}`);return i}if(o.now()-u>=o.retrieveTimeoutMs)throw new b("retrieval",p,i.status??"running",Math.round(o.retrieveTimeoutMs/6e4));await o.sleep(o.pollMs)}}async function I(e,n,t,o={}){let s=o.waiting??N;o.onProgress?.({step:"retrieve",done:0,total:t.length});let a=await M(e,n,t,s),p=new Map(t.map(l=>[d(l.componentType,l.fullName),l])),u=new Map,i=[];for(let l of g(a.messages)){let f=l.problem??"",T=P.exec(f),y=T?p.get(d(T[1],T[2])):void 0;y?u.set(d(y.componentType,y.fullName),{...y,problem:f}):f&&i.push(l.fileName?`${l.fileName}: ${f}`:f)}let m=t.filter(l=>!u.has(d(l.componentType,l.fullName))),r=a;m.length===0?r={...a,zipFile:""}:u.size>0&&(r=await M(e,n,m,s)),o.onProgress?.({step:"retrieve",done:m.length,total:t.length});let c=g(r.fileProperties).filter(l=>v(l)).map(l=>p.get(d(l.type??"",l.fullName??""))).filter(l=>l!==void 0);return{zipFile:r.zipFile??"",retrieved:m,missing:[...u.values()],managed:c,problems:i}}function A(e,n,t){return{allowMissingFiles:!1,autoUpdatePackage:!1,checkOnly:e,ignoreWarnings:!1,performRetrieve:!1,purgeOnDelete:!1,rollbackOnError:!0,...n==="RunSpecifiedTests"?{runTests:[...t]}:{},singlePackage:!0,testLevel:n}}async function E(e,n,t,o={}){let s=o.waiting??N,{id:a}=await e.deploy(n,t),p=s.now();for(;;){let u=await e.checkDeployStatus(a,!1);if(u.done)return e.checkDeployStatus(a,!0);if(o.onProgress?.(w(u)),s.now()-p>=s.deployTimeoutMs)throw new b("deployment",a,u.status??"running",Math.round(s.deployTimeoutMs/6e4));await s.sleep(s.pollMs)}}function w(e){let n=e.numberTestsTotal??0,t=e.numberComponentsTotal??0,o=(e.numberComponentsDeployed??0)+(e.numberComponentErrors??0);return n>0&&o>=t?{step:"tests",done:(e.numberTestsCompleted??0)+(e.numberTestErrors??0),total:n}:{step:"components",done:o,total:t}}function C(e){let n=/line (\d+), column \d+/.exec(e??"");return n?Number(n[1]):void 0}function O(e){let n=h(e.lineNumber),t=h(e.columnNumber),o=e.problemType==="Warning"||e.problemType==="Error"?e.problemType:void 0,s={componentType:e.componentType??"",fullName:e.fullName??"",...e.fileName?{fileName:e.fileName}:{}};if(!R(e.success))return{...s,outcome:"failed",...e.problem?{problem:e.problem}:{},...o?{problemType:o}:{},...n!==void 0?{line:n}:{},...t!==void 0?{column:t}:{}};let a=R(e.created)?"created":R(e.changed)?"changed":"unchanged";return{...s,outcome:a}}function $(e,n,t){let o=e?.details??void 0,s=new Map,a=[...g(o?.componentFailures),...g(o?.componentSuccesses)];for(let r of a){if(!r.componentType&&r.fullName==="package.xml")continue;let c=O(r),l=d(c.componentType,c.fullName);s.has(l)||s.set(l,c)}let p=n.missing.map(r=>({componentType:r.componentType,fullName:r.fullName,outcome:"not_retrieved",...r.problem?{problem:r.problem}:{}})),u=o?.runTestResult??void 0,i=g(u?.failures).map(r=>{let c=C(r.stackTrace);return{className:r.name??"",...r.methodName?{methodName:r.methodName}:{},message:r.message??"",...r.stackTrace?{stackTrace:r.stackTrace}:{},...c!==void 0?{line:c}:{}}}),m=g(u?.codeCoverageWarnings).map(r=>r.name?`${r.name}: ${r.message??""}`:r.message??"").filter(r=>r!=="");return{...e?.id?{deployId:e.id}:{},checkOnly:t.checkOnly,status:e?.status??"NotStarted",success:e?.success===!0&&n.missing.length===0,...e?.errorMessage?{errorMessage:e.errorMessage}:{},sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,testLevel:t.testLevel,runTests:[...t.runTests],components:[...s.values(),...p],counts:{componentsTotal:e?.numberComponentsTotal??0,componentsDeployed:e?.numberComponentsDeployed??0,componentErrors:e?.numberComponentErrors??0,testsTotal:e?.numberTestsTotal??0,testsCompleted:e?.numberTestsCompleted??0,testErrors:e?.numberTestErrors??0},testFailures:i,coverageWarnings:m,...n.problems.length>0?{retrieveProblems:[...n.problems]}:{},...e?.startDate?{startedAt:e.startDate}:{},...e?.completedDate?{completedAt:e.completedDate}:{}}}export{N as DEFAULT_WAITING,b as DeploymentStillRunning,A as deployOptions,E as deployPackage,$ as deploymentReport,x as metadataApiOf,I as retrieveComponents};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a,b}from"./chunk-5HMAPZBV.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as describedFieldsOf,b as requiredForAccountKinds};
7
+ import{a,b}from"./chunk-P33PSCXK.mjs";import"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as describedFieldsOf,b as requiredForAccountKinds};
@@ -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{g as v}from"./chunk-PA3MKJVH.mjs";var x=!0;function D(t){let e=new Map;for(let n of t){let r=n.SobjectType;if(typeof r!="string"||r==="")continue;let o=r.toLowerCase(),c=e.get(o)??{viewAll:!1,modifyAll:!1};e.set(o,{viewAll:c.viewAll||n.PermissionsViewAllRecords===!0,modifyAll:c.modifyAll||n.PermissionsModifyAllRecords===!0})}return e}function E(t){return[...t.values()].some(e=>e.modifyAll)}var I=new Set(["task","event"]),M=new Set(["product2","pricebook2","pricebookentry"]),N=new Set(["user","group"]);function L(t){let e=[];for(let n of t.fields){if(n.type!=="reference")continue;let r=(n.referenceTo??[]).filter(o=>!N.has(o.toLowerCase()));r.length>0&&e.push({field:n.name,targets:r})}return e}function R(t,e){if(I.has(t))return"activities";if(M.has(t))return"catalog";if(t===v.toLowerCase())return"filesNotProven";if(e.has(t))return"settingNotProven"}function G(t,e){let n=j(e.describes),r=k(e.customSettings),o=new Map;for(let c of t){let f=c.toLowerCase();if(R(f,r)!==void 0||e.grants.has(f))continue;let u=n.get(f);if(u!==void 0)for(let{targets:p}of L(u)){if(p.length!==1)continue;let s=p[0],i=s.toLowerCase();!n.has(i)&&!o.has(i)&&o.set(i,s)}}return[...o.values()]}function j(t){return new Map([...t].map(e=>[e.name.toLowerCase(),e]))}function k(t){return new Set([...t??[]].map(e=>e.toLowerCase()))}function P(t,e,n){return(t.childRelationships??[]).some(r=>r.cascadeDelete===!0&&r.childSObject.toLowerCase()===e&&r.field.toLowerCase()===n.toLowerCase())}function $(t,e,n={}){let r=n.byParent??x,o=j(e.describes),c=k(e.customSettings),f=new Map,u=(s,i)=>{let d=s.toLowerCase(),C=f.get(d);if(C!==void 0)return C;let m=R(d,c);if(m!==void 0)return{reason:m};let h=e.grants.get(d);if(h!==void 0)return h.modifyAll?{access:"object"}:{reason:h.viewAll?"noModifyAll":"noViewAll"};if(!r)return{reason:"parentNotSeen",detail:"held through its parents is not proven"};let A=o.get(d);if(A===void 0)return{reason:"parentNotSeen",detail:"it could not be described"};let w=[];for(let{field:l,targets:a}of L(A)){let b=a.filter(y=>!o.has(y.toLowerCase())),g=a.filter(y=>{let S=o.get(y.toLowerCase());return S!==void 0&&P(S,d,l)});if(a.length>1){if(g.length>0||b.length>0)return{reason:"parentNotSeen",detail:`${l} may name a record of ${a.join(", ")}`};continue}if(b.length>0)return{reason:"parentNotSeen",detail:`${b[0]}, which ${l} names, could not be described`};g.length>0&&w.push({field:l,parent:g[0]})}if(w.length===0)return{reason:"parentNotSeen",detail:"it hangs from no record whose delete takes it along"};let O=new Set([...i,d]);for(let{field:l,parent:a}of w){let b=a.toLowerCase(),g=O.has(b)?void 0:u(a,O);if(g===void 0||!("access"in g))return{reason:"parentNotSeen",detail:`${a}, which ${l} names, is not held whole`}}return{access:"parent"}},p=new Map;for(let s of t){let i=u(s,new Set);f.set(s.toLowerCase(),i),p.set(s,i)}return p}export{D as a,E as b,G as c,$ as d};
7
+ import{g as v}from"./chunk-JWTSEDIQ.mjs";var x=!0;function D(t){let e=new Map;for(let n of t){let r=n.SobjectType;if(typeof r!="string"||r==="")continue;let o=r.toLowerCase(),c=e.get(o)??{viewAll:!1,modifyAll:!1};e.set(o,{viewAll:c.viewAll||n.PermissionsViewAllRecords===!0,modifyAll:c.modifyAll||n.PermissionsModifyAllRecords===!0})}return e}function E(t){return[...t.values()].some(e=>e.modifyAll)}var I=new Set(["task","event"]),M=new Set(["product2","pricebook2","pricebookentry"]),N=new Set(["user","group"]);function L(t){let e=[];for(let n of t.fields){if(n.type!=="reference")continue;let r=(n.referenceTo??[]).filter(o=>!N.has(o.toLowerCase()));r.length>0&&e.push({field:n.name,targets:r})}return e}function R(t,e){if(I.has(t))return"activities";if(M.has(t))return"catalog";if(t===v.toLowerCase())return"filesNotProven";if(e.has(t))return"settingNotProven"}function G(t,e){let n=j(e.describes),r=k(e.customSettings),o=new Map;for(let c of t){let f=c.toLowerCase();if(R(f,r)!==void 0||e.grants.has(f))continue;let u=n.get(f);if(u!==void 0)for(let{targets:p}of L(u)){if(p.length!==1)continue;let s=p[0],i=s.toLowerCase();!n.has(i)&&!o.has(i)&&o.set(i,s)}}return[...o.values()]}function j(t){return new Map([...t].map(e=>[e.name.toLowerCase(),e]))}function k(t){return new Set([...t??[]].map(e=>e.toLowerCase()))}function P(t,e,n){return(t.childRelationships??[]).some(r=>r.cascadeDelete===!0&&r.childSObject.toLowerCase()===e&&r.field.toLowerCase()===n.toLowerCase())}function $(t,e,n={}){let r=n.byParent??x,o=j(e.describes),c=k(e.customSettings),f=new Map,u=(s,i)=>{let d=s.toLowerCase(),C=f.get(d);if(C!==void 0)return C;let m=R(d,c);if(m!==void 0)return{reason:m};let h=e.grants.get(d);if(h!==void 0)return h.modifyAll?{access:"object"}:{reason:h.viewAll?"noModifyAll":"noViewAll"};if(!r)return{reason:"parentNotSeen",detail:"held through its parents is not proven"};let A=o.get(d);if(A===void 0)return{reason:"parentNotSeen",detail:"it could not be described"};let w=[];for(let{field:l,targets:a}of L(A)){let b=a.filter(y=>!o.has(y.toLowerCase())),g=a.filter(y=>{let S=o.get(y.toLowerCase());return S!==void 0&&P(S,d,l)});if(a.length>1){if(g.length>0||b.length>0)return{reason:"parentNotSeen",detail:`${l} may name a record of ${a.join(", ")}`};continue}if(b.length>0)return{reason:"parentNotSeen",detail:`${b[0]}, which ${l} names, could not be described`};g.length>0&&w.push({field:l,parent:g[0]})}if(w.length===0)return{reason:"parentNotSeen",detail:"it hangs from no record whose delete takes it along"};let O=new Set([...i,d]);for(let{field:l,parent:a}of w){let b=a.toLowerCase(),g=O.has(b)?void 0:u(a,O);if(g===void 0||!("access"in g))return{reason:"parentNotSeen",detail:`${a}, which ${l} names, is not held whole`}}return{access:"parent"}},p=new Map;for(let s of t){let i=u(s,new Set);f.set(s.toLowerCase(),i),p.set(s,i)}return p}export{D as a,E as b,G as c,$ as d};
@@ -4,7 +4,7 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{o as ht}from"./chunk-WJY54JO7.mjs";import{E as ze,d as pt,x as mt}from"./chunk-NEVXIGR6.mjs";import{a as dn,d as cn,e as ln,g as un,h as fn,i as gn,j as pn,k as gt}from"./chunk-SAR5622P.mjs";import{C as sn,v as on}from"./chunk-HJC7AIBK.mjs";import{a as Ue,b as re,d as ee,e as an,f as ft,h as z}from"./chunk-OTWRDD6L.mjs";import{c as rn}from"./chunk-EADHKH3A.mjs";import{e as mn,h as hn,i as yn}from"./chunk-PNCONNFJ.mjs";import{ca as Oe,da as ut,fa as Ee,ia as qe}from"./chunk-CGWXQX75.mjs";import{h as F}from"./chunk-TZE3Y7IQ.mjs";import{b as N}from"./chunk-CA5NAXSU.mjs";import{Db as en,Eb as fe,Ib as $e,Lb as ke,Mb as ct,Ob as lt,Pb as tn,Tb as K,nc as nn,yb as Xt}from"./chunk-B45CNPUX.mjs";import{b as x,e as ue,f as $,i as Ae,k as X,l as W,o as Be,s as Fe,v as Zt}from"./chunk-7EANH5PY.mjs";var He=class{activeJobs=new Map;maxConcurrentJobs;maxCompletedJobs=50;constructor(e=5){this.maxConcurrentJobs=e}registerJob(e){this.activeJobs.set(e.id,e)}updateJobState(e,t){let n=this.activeJobs.get(e);return n?(n.state=t,(t==="JobComplete"||t==="Failed"||t==="Aborted")&&this.purgeCompletedJobs(),!0):!1}updateJobCounts(e,t,n){let o=this.activeJobs.get(e);return o?(o.numberRecordsProcessed=t,o.numberRecordsFailed=n,!0):!1}updateTotalRecords(e,t){let n=this.activeJobs.get(e);return n?(n.totalRecords=t,!0):!1}getJob(e){return this.activeJobs.get(e)}getActiveJobs(){return Array.from(this.activeJobs.values()).filter(e=>e.state==="UploadComplete"||e.state==="InProgress")}getCompletedJobs(){return Array.from(this.activeJobs.values()).filter(e=>e.state==="JobComplete"||e.state==="Failed"||e.state==="Aborted")}canStartNewJob(){return this.getActiveJobs().length<this.maxConcurrentJobs}removeJob(e){return this.activeJobs.delete(e)}get totalJobs(){return this.activeJobs.size}purgeCompletedJobs(){let e=Array.from(this.activeJobs.entries()).filter(([,t])=>["JobComplete","Failed","Aborted"].includes(t.state));if(e.length>this.maxCompletedJobs){let t=e.slice(0,e.length-this.maxCompletedJobs);for(let[n]of t)this.activeJobs.delete(n)}}clear(){this.activeJobs.clear()}};function Rr(r,e){let t=gt(r,e);if(t.state==="Open")throw new Error(`Bulk API job ${r||"(no id)"} is still open after its close was sent`);return{state:t.state,...t.numberRecordsProcessed!==void 0?{numberRecordsProcessed:t.numberRecordsProcessed}:{},...t.errorMessage?{errorMessage:t.errorMessage}:{}}}function Je(r){return{bulk2:{createJob:e=>{let t=r.bulk2.createJob(e);return{get id(){return t.id},open:async()=>{await t.open()},uploadData:n=>t.uploadData(n),close:()=>t.close(),abort:()=>t.abort(),check:async()=>Rr(mn(t)??"",await t.check()),getAllResults:()=>t.getAllResults()}},job:(e,{id:t})=>{let n=r.bulk2.job(e,{id:t});return{check:async()=>gt(t,await n.check()),getSuccessfulResults:()=>n.getSuccessfulResults(),getAllResults:()=>n.getAllResults(),abort:()=>n.abort()}}}}}var bn=100,yt=2e3,wn=20,Rn=20,Sr=W({name:x(),label:x(),type:x(),createable:$().optional(),updateable:$().optional(),nillable:$().optional(),defaultedOnCreate:$().optional(),aggregatable:$().optional(),groupable:$().optional(),filterable:$().optional(),nameField:$().optional(),autoNumber:$().optional(),calculated:$().optional(),referenceTo:X(x()).optional()}).loose(),de=W({name:x(),label:x(),queryable:$().optional(),updateable:$().optional(),deletable:$().optional(),fields:X(Sr),childRelationships:X(W({childSObject:x(),field:x(),cascadeDelete:$().optional(),restrictedDelete:$().optional()}).loose()).optional()}).loose(),Ar=Fe(x(),Ae()),kr=W({k:Be([x(),ue(),$()]).nullable(),n:ue().int().nonnegative()}).loose();function Sn(r){return(r.createable===!0||r.updateable===!0)&&r.type!=="boolean"}function Or(r){return r.groupable===!0&&(Sn(r)||r.nameField===!0)}function Er(r,e){return e.createable===!0&&e.nillable===!1&&e.defaultedOnCreate!==!0||Xt(r,e.name)}function Qe(r,e,t){let n=N(t);r.some(o=>o.check===e&&o.message===n)||r.push({check:e,message:n})}async function Dr(r,e,t,n){let o=new Map,s=[],i=[],a=(f,l)=>{s.push({fieldApiName:f.name,label:f.label,reason:l})},d=t.filter(f=>f.aggregatable===!0),c=t.filter(f=>f.aggregatable!==!0&&f.filterable===!0);for(let f of t)f.aggregatable!==!0&&f.filterable!==!0&&a(f,"not-countable");if(n===0)for(let f of[...d,...c])o.set(f.name,0);else{for(let f=0;f<d.length;f+=bn){let l=d.slice(f,f+bn);try{let g=l.map(b=>`COUNT(${F(b.name)})`).join(", "),p=await r.query(`SELECT ${g} FROM ${e}`),m=Ar.parse(p.records[0]??{});l.forEach((b,h)=>{let R=m[`expr${h}`];if(typeof R!="number")throw new Error(`The org answered no count for ${e}.${b.name}.`);o.set(b.name,R)})}catch(g){Qe(i,"fill",g);for(let p of l)o.delete(p.name),a(p,"refused")}}for(let[f,l]of c.entries()){if(f>=Rn){a(l,"query-budget");continue}try{let g=await r.query(`SELECT COUNT() FROM ${e} WHERE ${F(l.name)} != null`);o.set(l.name,g.totalSize)}catch(g){Qe(i,"fill",g),a(l,"refused")}}}return{fields:t.filter(f=>o.has(f.name)).map(f=>({fieldApiName:f.name,label:f.label,filled:o.get(f.name)??0,required:Er(e,f)})).sort((f,l)=>f.filled-l.filled||f.fieldApiName.localeCompare(l.fieldApiName)),unmeasured:s,errors:i}}async function Ir(r,e,t,n,o){let s=[],i=n?t.find(d=>d.name.toLowerCase()===n.toLowerCase()):t.find(d=>d.name==="Email")??t.find(d=>d.nameField===!0);if(!i)return n&&s.push({check:"duplicates",message:`${e} has no field ${n} the org can group records by.`}),{duplicates:null,errors:s};let a={keyField:i.name,keyLabel:i.label,groups:[],groupCount:0,recordCount:0,truncated:!1};if(o===0)return{duplicates:a,errors:s};try{let d=await Pr(r,e,i.name),c=d.rows.map(u=>({value:String(u.value),count:u.count}));return{duplicates:{...a,groups:c.slice(0,wn),groupCount:c.length,recordCount:c.reduce((u,f)=>u+f.count,0),truncated:d.truncated},errors:s}}catch(d){return Qe(s,"duplicates",d),{duplicates:null,errors:s}}}async function Pr(r,e,t){let n=F(t),o=await r.query(`SELECT ${n} k, COUNT(Id) n FROM ${e} WHERE ${n} != null GROUP BY ${n} HAVING COUNT(Id) > 1 ORDER BY COUNT(Id) DESC LIMIT ${yt}`),s=[];for(let i of o.records){let a=kr.safeParse(i);!a.success||a.data.k===null||s.push({value:a.data.k,count:a.data.n})}return{rows:s,truncated:o.records.length>=yt}}async function Cr(r,e,t,n,o){let s=[];if(!t.some(i=>i.name==="LastModifiedDate"&&i.filterable===!0))return{stale:null,errors:s};if(o===0)return{stale:{days:n,records:0},errors:s};try{let i=await r.query(`SELECT COUNT() FROM ${e} WHERE LastModifiedDate < LAST_N_DAYS:${n}`);return{stale:{days:n,records:i.totalSize},errors:s}}catch(i){return Qe(s,"stale",i),{stale:null,errors:s}}}async function Nr(r,e,t){let n,o,s;try{if(n=de.parse(await r.describe(F(e.objectApiName))),o=F(n.name),n.queryable===!1)throw new Error(`${o} cannot be queried.`);s=(await r.query(`SELECT COUNT() FROM ${o}`)).totalSize}catch(u){return{status:"failed",objectApiName:e.objectApiName,message:N(u)}}let i=n.fields.filter(Or).sort((u,f)=>u.label.localeCompare(f.label)),[a,d,c]=await Promise.all([Dr(r,o,n.fields.filter(Sn),s),Ir(r,o,i,e.duplicateKey,s),Cr(r,o,n.fields,t,s)]);return{status:"scanned",objectApiName:e.objectApiName,label:n.label,totalRecords:s,fields:a.fields,unmeasured:a.unmeasured,duplicates:d.duplicates,stale:c.stale,keyFields:i.map(u=>({fieldApiName:u.name,label:u.label})),errors:[...a.errors,...d.errors,...c.errors]}}async function Ps(r,e,t=()=>new Date){if(!Number.isInteger(e.staleDays)||e.staleDays<1)throw new Error(`A staleness threshold is a whole number of days, not ${e.staleDays}.`);let n=t().toISOString(),o=[];for(let s of e.objects)o.push(await Nr(r,s,e.staleDays));return{orgId:e.orgId,staleDays:e.staleDays,scannedAt:n,bounds:{duplicateGroupLimit:yt,duplicateSample:wn,singleFieldQueries:Rn},objects:o}}var wt=1e4,Ve=5e4,An="DELETE_FAILED",Rt="UNABLE_TO_LOCK_ROW",kn=3,jr=2e3,On="FEATURENOTENABLED",St="ContentVersion",En="ContentDocument",At=new Set([St,En]);async function De(r,e,t,n,o="delete"){let s=!1,i={},a=0,d=0,c=(g,p)=>(d+=g,p()),u={bulk2:{createJob:g=>{let p=r.bulk2.createJob(g);return{get id(){return p.id},open:()=>c(1,()=>p.open()),uploadData:m=>c(1,()=>p.uploadData(m)),close:async()=>{await c(1,()=>p.close()),s=!0},abort:()=>c(1,()=>p.abort()),check:async()=>{let m=await c(1,()=>p.check());return i={state:m.state,message:m.errorMessage},m},getAllResults:async()=>{let m=await c(yn,()=>p.getAllResults());return a=Array.isArray(m)?m.length:(m.successfulResults?.length??0)+(m.failedResults?.length??0),m}}}}},f;try{f=await new hn().executeBulk({connection:u,bulkManager:new He(1),...n?{signal:n}:{}},e,o,t.map(g=>({Id:g})))}catch(g){if(!s){let p=g?.errorCode;return{kind:"untouched",reason:N(g),...typeof p=="string"&&p!==""?{code:p}:{},requests:d}}throw g}if(f.aborted)return{kind:"aborted",requests:d};if(i.state!=="JobComplete"&&a===0)return{kind:"untouched",reason:i.message||`job ${i.state??"not complete"}`,requests:d};let l=new Map(f.outcomes.map(g=>[g.recordIndex,g]));return{kind:"answered",requests:d,rows:t.map((g,p)=>{let m=l.get(p);return m?.success?{success:!0}:{success:!1,error:m?.error??"The job gave no result for it."}})}}function $s(r,e){let t=Je(r);return{...Ue(r,e),queryDeleted:async n=>({records:(await r.query(n,{scanAll:!0})).records}),bulkDestroy:(n,o,s)=>De(t,n,o,s),bulkHardDestroy:(n,o,s)=>De(t,n,o,s,"hardDelete")}}var kt=W({success:$(),errors:X(Be([W({statusCode:x().optional(),errorCode:x().optional(),message:x().optional()}).loose(),x()])).optional()}).loose();function ge(r){return r.slice(0,15)}function We(r){return typeof r=="string"?void 0:r.statusCode??r.errorCode}function Ot(r){if(typeof r=="string")return r;let e=We(r),t=r.message??"";return e&&t?`${e}: ${t}`:e||t||"The org gave no reason."}function be(r){return async e=>(await r.query(e)).records.filter(n=>typeof n=="object"&&n!==null)}function vr(r){return new Promise(e=>setTimeout(e,r))}function Mr(r){let e=jr*2**r;return Math.floor(e/2+Math.random()*(e/2))}async function Dn(r,e,t,n){let o=[...t];for(let s=0;s<kn;s++){let i=o.flatMap((d,c)=>d.kind==="refused"&&d.locked===!0?[c]:[]);if(i.length===0||n.stopped?.()===!0||(await(n.wait??vr)(Mr(s)),n.stopped?.()===!0))break;let a=await e(i.map(d=>r[d]));if(a===void 0)break;i.forEach((d,c)=>{let u=a[c];u&&(o[d]={...u,lockResends:s+1})})}return o}async function Et(r,e,t,n={}){if(e===St)return $r(r,t,n);let o=s=>Lr(r,e,s);return Dn(t,o,await o(t),n)}async function Lr(r,e,t){let n;try{n=await r.destroy(e,[...t])}catch(s){let i=N(s);return t.map(()=>({kind:"refused",reason:i,dependency:!1}))}let o=Array.isArray(n)?n:[n];return t.map((s,i)=>{let a=kt.safeParse(o[i]);if(a.success&&a.data.success)return{kind:"deleted"};let d=a.success?a.data.errors??[]:[];if(d.some(u=>We(u)==="ENTITY_IS_DELETED"))return{kind:"gone"};let c=d.length>0&&d.every(u=>We(u)===Rt);return{kind:"refused",reason:d.length>0?Ot(d[0]):"The org gave no reason.",dependency:d.some(u=>We(u)===An),...c?{locked:!0}:{}}})}async function Tr(r,e,t,n="recycle",o={}){let s=n==="hard"?r.bulkHardDestroy?.bind(r):r.bulkDestroy?.bind(r);if(s===void 0)return n==="hard"?{hardRefused:xr}:"untouched";let i=async d=>{let c;try{c=await s(e,d,o.signal)}catch(f){let l=N(f);return d.map(()=>({kind:"refused",reason:l,dependency:!1}))}if(c.kind==="aborted")return"aborted";if(c.kind==="untouched"){if(n!=="hard")return"untouched";if(c.code===On)return{hardRefused:_r(c.reason)};let f=`Not deleted for good: the job was not handed over \u2014 ${c.reason}`;return d.map(()=>({kind:"refused",reason:f,dependency:!1}))}let{rows:u}=c;return d.map((f,l)=>{let g=u[l];if(g?.success===!0)return{kind:"deleted"};let{code:p,message:m}=Fr(g?.error??"");return p==="ENTITY_IS_DELETED"?{kind:"gone"}:{kind:"refused",reason:p&&m?`${p}: ${m}`:g?.error||p||m||"The org gave no reason.",dependency:p===An,...p===Rt?{locked:!0}:{}}})},a=await i(t);return Array.isArray(a)?Dn(t,async d=>{let c=await i(d);return Array.isArray(c)?c:void 0},a,o):a}var xr="Records cannot be deleted for good through this connection: nothing was sent.";function _r(r){return`The user SandForge connects as may not delete records for good in this org: Salesforce refused the job before it held a record (${On}: ${r}). Nothing was deleted for good, and nothing was sent to the recycle bin instead.`}var Br="A file is never deleted for good: that takes a Bulk API job, which no file was ever sent by. Not sent.";function Fr(r){let e=/^([A-Z][A-Z0-9_]*):([\s\S]*?)(?::(?:--|[\w.,]+))?$/.exec(r.trim());return e?{code:e[1],message:e[2].trim()}:{message:r.trim()}}async function $r(r,e,t){let n;try{n=await z(r,St,["ContentDocumentId"],e)}catch(d){let c=N(d);return e.map(()=>({kind:"refused",reason:c,dependency:!1}))}let o=new Map;for(let d of n)typeof d.Id=="string"&&typeof d.ContentDocumentId=="string"&&o.set(ge(d.Id),d.ContentDocumentId);let s=[...new Set(o.values())],i=s.length>0?await Et(r,En,s,t):[],a=new Map(s.map((d,c)=>[d,i[c]]));return e.map(d=>{let c=o.get(ge(d));return c===void 0?{kind:"gone"}:a.get(c)??{kind:"refused",reason:"The org gave no answer for its document.",dependency:!1}})}function In(r){let e=[];for(let t=0;t<r.length;t+=re)e.push({ids:r.slice(t,t+re),byJob:!1});return e}function Pn(r,e,t,n="recycle"){return At.has(e)?!1:n==="hard"||r.bulkDestroy!==void 0&&t>=wt}async function qr(r,e,t,n="recycle"){let o=[],s=!At.has(e)&&(n==="hard"||r.bulkDestroy!==void 0),i=d=>{if(d.length===0)return;if(!s||n!=="hard"&&d.length<wt){o.push(...In(d));return}let c=Math.ceil(d.length/Math.ceil(d.length/Ve));for(let u=0;u<d.length;u+=c)o.push({ids:d.slice(u,u+c),byJob:!0})};if(!$e(e)||t.length===0)return i(t),o;let a=new Set;try{a=new Set([...await Ee(be(r),t)].map(ge))}catch{}return i(t.filter(d=>!a.has(ge(d)))),i(t.filter(d=>a.has(ge(d)))),o}function Cn(r){return{objectApiName:r,op:"delete"}}async function Nn(r,e,t,n,o){let s={stopped:o.stopped,...o.wait?{wait:o.wait}:{}},{stopped:i}=await pn(t,{key:Cn(e),sizes:n.sizes,allowance:n.allowance,beforeEachSend:()=>o.stopped()?"stop":void 0,send:async a=>({answers:await Et(r,e,a,s)}),limited:a=>a?.kind==="refused"?nn([a.reason]):void 0,settle:(a,d,c,u)=>{let f=[],l=[];a.forEach((g,p)=>{if(c.has(p))return;let m=d[p]??{kind:"refused",reason:"The org gave no answer for it.",dependency:!1},b=u.get(p);f.push(g),l.push(b!==void 0&&m.kind==="refused"?{...m,dependency:!1,limit:b}:m)}),f.length>0&&o.settle(f,l)}});return i!==void 0}function Dt(r,e){let t=Cn(r),n=e.sizes.report(t);if(!n)return[];let o=[];return n.rows+n.alone+n.notSplit+n.keptWhole>0&&o.push(un(n)),n.notSplit>0&&o.push(fn(n.notSplit,gn(e.allowance,t),"removal")),n.keptWhole>0?o.push(ln):n.alone>0&&o.push(cn),o}function jn(r){let e=0,t=0,n=0,o=0;for(let i of r)e++,i==="deleted"?t++:i==="gone"?n++:o++;if(e===0)return[];let s=[t>0?`${t} deleted`:"",n>0?`${n} already gone`:"",o>0?`${o} still refused`:""].filter(Boolean);return[`The org could not lock ${e} record(s) (${Rt}), each sent again up to ${kn} times, a wait before each: ${s.join(", ")}.`]}async function vn(r,e,t,n){let o=n.mode??"recycle";if(o==="hard"&&At.has(e))return t.length>0&&n.settle(t,t.map(()=>({kind:"refused",reason:Br,dependency:!1}))),{stopped:!1};let s=n.wait?{wait:n.wait}:{},i=await qr(r,e,t,o);for(let a=i.shift();a!==void 0;a=i.shift()){let{ids:d,byJob:c}=a;if(n.stopped())return{stopped:!0};if(await n.prepare?.(d),!c){if(await Nn(r,e,d,n.splitting,{stopped:n.stopped,settle:n.settle,...s}))return{stopped:!0};continue}let u=await Tr(r,e,d,o,{stopped:n.stopped,...s,...n.signal?{signal:n.signal}:{}});if(u==="aborted")return{stopped:!0};if(u==="untouched"){i.unshift(...In(d));continue}if(!Array.isArray(u))return{stopped:!0,hardRefused:u.hardRefused};n.settle(d,u)}return{stopped:!1}}async function Mn(r,e){for(let t=0,n=!0;n;t++){n=!1;for(let o of r){let s=e.idsOf(o,t);if(s.length===0)continue;if(e.stopped())return!0;let i=e.deleted(o);if(await e.send(o,s,t))return!0;e.deleted(o)>i&&(n=!0)}}return!1}async function Ke(r,e){let t=new Set(e.map(i=>i.objectApiName)),n=new Map;for(let{objectApiName:i}of e){let a;try{a=(de.parse(await r.describe(i)).childRelationships??[]).map(c=>c.childSObject)}catch{continue}for(let d of a){if(d===i||!t.has(d))continue;let c=n.get(d)??new Set;c.add(i),n.set(d,c)}}let o=[...e],s=[];for(;o.length>0;){let i=o.findIndex(a=>!o.some(d=>d!==a&&n.get(d.objectApiName)?.has(a.objectApiName)));s.push(...o.splice(i>=0?i:0,1))}return s}async function It(r,e,t){if(r.length===0)return{gone:[],unchecked:[]};let n;try{n=await e(r)}catch(i){return{gone:[],unchecked:[...r],failure:N(i)}}let o=new Set(n.map(i=>ge(String(i.Id)))),s=r.filter(i=>!o.has(ge(i)));return{gone:s.filter(t),unchecked:s.filter(i=>!t(i))}}function Ur(r){return r.filter(e=>Oe[e]!==void 0&&!ut.has(e))}async function Pt(r,e,t,n,o,s){let i=be(r),a=[];for(let{objectApiName:d}of e){let c=Oe[d];if(!c||ut.has(d))continue;let u;for await(let f of t.pages(d)){let l=f.filter(R=>n(d,R));if(l.length===0)continue;if(o())return{drafted:a,cancelled:!0};u??=await qe(i,c);let g=u,p=g?.draft;if(!g||!p)break;let m=await s(d,l),b;try{b=await z(r,d,["Status"],l)}catch{continue}let h=b.filter(R=>typeof R.Id=="string"&&!m.has(R.Id.slice(0,15))).filter(R=>{let S=g.categoryOf.get(String(R.Status));return S!==void 0&&S!=="Draft"}).map(R=>({objectApiName:d,id:String(R.Id),draft:p,status:String(R.Status)}));for(let R=0;R<h.length;R+=re){if(o())return{drafted:a,cancelled:!0};let S=h.slice(R,R+re);a.push(...S);try{await r.update(d,S.map(({id:j})=>({Id:j,Status:p})))}catch{}}}}return{drafted:a,cancelled:!1}}function Qs(r,e,t,n){if(t)return`${r} ${t.id}: ${e}`;let o=n.filter(s=>s.objectApiName===r).map(s=>`${s.id} (${s.status})`);return o.length>0?`${r}: ${e} Set to Draft, with the status each had: ${o.join(", ")}.`:`${r}: ${e}`}async function Ln(r,e,t){let n=[...new Set(e.map(o=>o.objectApiName))];for(let o of n){let s=e.filter(u=>u.objectApiName===o),i=new Map(s.map(u=>[u.id.slice(0,15),u])),a=s.map(u=>u.id),d;try{d=await z(r,o,["Status"],a)}catch(u){t.note(o,`Status set to ${s[0].draft} for the delete, and not read back to be restored: ${N(u)}`,!0);continue}let c=d.flatMap(u=>{let f=typeof u.Id=="string"?i.get(u.Id.slice(0,15)):void 0;return f&&u.Status===f.draft?[f]:[]});for(let u=0;u<c.length;u+=re){let f=c.slice(u,u+re),l;try{l=await r.update(o,f.map(({id:p,status:m})=>({Id:p,Status:m})))}catch(p){l=f.map(()=>({success:!1,errors:[N(p)]}))}let g=Array.isArray(l)?l:[l];f.forEach(({draft:p,status:m},b)=>{let h=kt.safeParse(g[b]);if(h.success&&h.data.success){t.note(o,`Status set to ${p} for the delete, then back to ${m}.`,!1,f[b]);return}let R=h.success?h.data.errors??[]:[],S=R.length>0?Ot(R[0]):"The org gave no reason.";t.note(o,`Status set to ${p} for the delete, and left there: the org refused ${m} back \u2014 ${S}`,!0,f[b])})}}}var Re="DuplicateRecordSet",zr="DuplicateRecordItem",Ge=2e3,Hr=999,Jr=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function V(r){return r.slice(0,15)}function Tn(r){return new Date(r).toISOString().replace(/\.\d{3}Z$/,"Z")}function Ct(r){return typeof r=="string"?Date.parse(r):Number.NaN}async function xn(r,e){return(await Qr(r,e)).map(t=>({id:t.id,modified:Wr(t,e)}))}async function Qr(r,e){if(!Number.isFinite(e.start)||!Number.isFinite(e.end)||!Jr.test(e.user))return[];let t;try{let d=await r.query(`SELECT Id, CreatedDate, LastModifiedDate, LastModifiedById FROM ${Re} WHERE CreatedDate >= ${Tn(e.start-2e3)} AND CreatedDate <= ${Tn(e.end+6e4)} LIMIT ${Ge}`);if(d.records.length>=Ge)return[];t=d.records.filter(c=>typeof c=="object"&&c!==null)}catch{return[]}let n=t.flatMap(d=>typeof d.Id=="string"?[d.Id]:[]);if(n.length===0)return[];let o=new Set,s=new Map,i=new Map;try{for(let d of ee(n)){let c=await r.query(`SELECT Id, RecordId, DuplicateRecordSetId, CreatedDate FROM ${zr} WHERE DuplicateRecordSetId IN (${d}) LIMIT ${Ge}`);if(c.records.length>=Ge)return[];for(let u of c.records){let f=u??{},l=f.DuplicateRecordSetId,g=f.RecordId;if(typeof l!="string")continue;let p=Ct(f.CreatedDate);Number.isFinite(p)&&!(p<=(i.get(V(l))??Number.NaN))&&i.set(V(l),p),typeof g!="string"||!e.has(V(g))?o.add(V(l)):s.set(V(l),[...s.get(V(l))??[],V(g)])}}}catch{return[]}let a=V(e.user);return t.flatMap(d=>typeof d.Id=="string"&&!o.has(V(d.Id))&&(s.has(V(d.Id))||typeof d.LastModifiedById=="string"&&V(d.LastModifiedById)===a)?[{id:d.Id,created:Ct(d.CreatedDate),modified:Ct(d.LastModifiedDate),...typeof d.LastModifiedById=="string"?{modifiedBy:d.LastModifiedById}:{},names:s.get(V(d.Id))??[],...i.has(V(d.Id))?{itemsMade:i.get(V(d.Id))}:{}}]:[])}function Wr(r,e){if((r.modifiedBy!==void 0?V(r.modifiedBy):"")===V(e.user)&&r.modified<=e.end+6e4)return Math.min(r.modified,e.end);let n=e.end+6e4;return r.names.length>0&&r.created<=n&&r.modified<=n&&(r.modified===r.created||r.modified<=(r.itemsMade??Number.NaN)+Hr)?Math.min(r.modified,e.end):r.modified}async function _n(r,e,t,n="recycle"){let o=F(e),s=new Set;try{for(let i of ee(t)){let a=await r.queryDeleted(`SELECT Id FROM ${o} WHERE Id IN (${i}) AND IsDeleted = true`);for(let d of a.records){let c=d?.Id;typeof c=="string"&&s.add(c.slice(0,15))}}}catch(i){return{error:N(i)}}return{deleted:s,inBin:n!=="hard"}}var Vr=/__kav$/i;function Ie(r){return Vr.test(r)}function Fn(r){return r.replace(/v$/i,"")}var Nt="Kept: its article holds a version the run did not write \u2014 a draft begun on it, or a version published since \u2014 which deleting the article would take with it. A removal that takes what changed since the run takes it too.",Kr={statusCode:"ENTITY_IS_DELETED",message:"The version is no longer in the org: it went with its article."},Bn=" AND IsLatestVersion = false AND PublishStatus = 'Archived'",Gr="An article version is deleted through its article, over REST.",Yr={success:!1,errors:[{message:"The org gave no reason."}]};function te(r){return r.slice(0,15)}function $n(r,e){let t=r.bulkDestroy?.bind(r);return{query:n=>r.query(n),queryDeleted:n=>r.queryDeleted(n),update:(n,o)=>r.update(n,o),serverTime:()=>r.serverTime(),userId:()=>r.userId(),describeGlobal:()=>r.describeGlobal(),describe:n=>Ie(n)?Zr(r,n):r.describe(n),destroy:(n,o)=>Ie(n)?Xr(r,n,o,e):r.destroy(n,o),...t?{bulkDestroy:(n,o,s)=>Ie(n)?Promise.resolve({kind:"untouched",reason:Gr,requests:0}):t(n,o,s)}:{}}}async function Zr(r,e){let t=await r.describe(e);if(typeof t!="object"||t===null)return t;let n;try{n=(await r.describe(Fn(e)))?.deletable}catch{n=void 0}let o={...t};return delete o.deletable,typeof n=="boolean"?{...o,deletable:n}:o}async function qn(r,e,t){let n=F(e),o=new Map,s=new Map,i=(d,c)=>{for(let u of d){let f=u;if(typeof f?.Id!="string"||typeof f.KnowledgeArticleId!="string")continue;c?.set(te(f.Id),f.KnowledgeArticleId);let l=te(f.KnowledgeArticleId),g=s.get(l)??new Set;g.add(te(f.Id)),s.set(l,g)}};for(let d of["",Bn])for(let c of ee(t)){let u=await r.query(`SELECT Id, KnowledgeArticleId FROM ${n} WHERE Id IN (${c})${d}`);i(u.records,o)}let a=[...new Set(o.values())];for(let d of["",Bn])for(let c of ee(a)){let u=await r.query(`SELECT Id, KnowledgeArticleId FROM ${n} WHERE KnowledgeArticleId IN (${c})${d}`);i(u.records)}return{articleOf:o,versions:s}}function Un({articleOf:r,versions:e},t,n){if(n.includeChanged)return new Set;let o=new Set(t.map(te)),s=i=>[...e.get(i)??[]].some(a=>!o.has(a));return new Set([...r.values()].map(te).filter(s))}async function zn(r,e,t,n){let o=await qn(r,e,t),s=Un(o,t,n);return new Set(t.map(te).filter(i=>{let a=o.articleOf.get(i);return a!==void 0&&s.has(te(a))}))}async function Xr(r,e,t,n){let o=await qn(r,e,t),{articleOf:s}=o,i=[...new Set(s.values())],a=Un(o,t,n),d=i.filter(u=>!a.has(te(u))),c=new Map;if(d.length>0){let u;try{u=await r.destroy(Fn(e),d)}catch(l){let g=N(l);u=d.map(()=>({success:!1,errors:[{message:g}]}))}let f=Array.isArray(u)?u:[u];d.forEach((l,g)=>c.set(te(l),f[g]))}return t.map(u=>{let f=s.get(te(u));return f===void 0?{success:!1,errors:[Kr]}:a.has(te(f))?{success:!1,errors:[{message:Nt}]}:c.get(te(f))??Yr})}var Ze="Quote",Ce="QuoteLineItem",Pe="Opportunity",Ne="OpportunityLineItem",Hn=2e3;function eo(r){return r.slice(0,15)}function Jn(r){return typeof r=="string"?Date.parse(r):Number.NaN}function G(r,e){let t=r[e];return typeof t=="string"&&t!==""?eo(t):void 0}function vt(r,e){return r.has(e)||r.otherParts?.has(e)===!0}function to(r,e){let t=new Set,n=new Set;for(let g of r.syncing){let p=G(g,"Id"),m=G(g,"SyncedQuoteId");!p||!m||!vt(e,p)||!e.has(m)||(t.add(m),n.add(p))}if(t.size===0)return[];let o=r.quoteLines.filter(g=>{let p=G(g,"QuoteId");return p!==void 0&&t.has(p)&&G(g,"Id")!==void 0}),s=r.opportunityLines.filter(g=>{let p=G(g,"OpportunityId");return p!==void 0&&n.has(p)&&G(g,"Id")!==void 0}),i=g=>G(g,"CreatedById"),a=(g,p)=>{let m=G(g,"Id");if(!m||vt(e,m)||!p)return!1;let b=e.user??i(p),h=Jn(g.CreatedDate);return b!==void 0&&i(g)===b&&h>=e.start&&h<=e.end},d=g=>({id:String(g.Id),modified:Jn(g.LastModifiedDate)}),c=new Map(s.flatMap(g=>{let p=G(g,"Id");return p&&e.has(p)?[[p,g]]:[]})),u=new Map;for(let g of o){let p=G(g,"Id"),m=G(g,"OpportunityLineItemId");p&&m&&e.has(p)&&!u.has(m)&&u.set(m,g)}let f=o.filter(g=>{let p=G(g,"OpportunityLineItemId");return a(g,p?c.get(p):void 0)}).map(d),l=s.filter(g=>{let p=G(g,"Id");return a(g,p?u.get(p):void 0)}).map(d);return[...f.length>0?[{objectApiName:Ce,copies:f}]:[],...l.length>0?[{objectApiName:Ne,copies:l}]:[]]}function Qn(r,e=[]){let t=new Set(r),n=t.has(Pe)||new Set(e).has(Pe);if(!t.has(Ze)||!n)return[];let o=t.has(Ce),s=t.has(Ne);return o===s?[]:[o?Ne:Ce]}async function jt(r,e,t,n,o){let s=t.map(F).join(", "),i=[];for(let a of ee(o)){let d=await r.query(`SELECT ${s} FROM ${F(e)} WHERE ${F(n)} IN (${a}) LIMIT ${Hn}`);if(d.records.length>=Hn)throw new Error(`More ${e} records than one read takes.`);for(let c of d.records)typeof c=="object"&&c!==null&&i.push(c)}return i}async function Wn(r,e,t,n){let o=n.has(Ce)||n.has(Ne),s=n.has(Pe)||e.otherParts?.objects.has(Pe)===!0;if(t.length===0||!s||!o)return[];try{let a=(await jt(r,Pe,["Id","SyncedQuoteId"],"SyncedQuoteId",t)).filter(u=>{let f=G(u,"Id");return f!==void 0&&vt(e,f)});if(a.length===0)return[];let d=await jt(r,Ce,["Id","QuoteId","OpportunityLineItemId","CreatedById","CreatedDate","LastModifiedDate"],"QuoteId",[...new Set(a.map(u=>String(u.SyncedQuoteId)))]),c=await jt(r,Ne,["Id","OpportunityId","CreatedById","CreatedDate","LastModifiedDate"],"OpportunityId",a.map(u=>String(u.Id)));return to({syncing:a,quoteLines:d,opportunityLines:c},e)}catch{return[]}}var no=5,ve=4,Xe=2e3,ro=4,nt=[["CreatedDate","LastModifiedDate","CreatedById","LastModifiedById"],["CreatedDate","LastModifiedDate","CreatedById"],["SystemModstamp"],[]],Lt=1e4,oo="005",Vn="ContentDocumentLink",so="ContentDocument",io="ContentVersion",ao=5;function rt(r){let e=new Set(r.flatMap(n=>n.ids.map(w))),t=new Map;for(let{objectApiName:n,ids:o}of r)t.set(n,[...t.get(n)??[],...o]);return{objects:[...t].map(([n,o])=>({objectApiName:n,count:o.length})),pages:async function*(n){let o=t.get(n);o&&o.length>0&&(yield o)},has:n=>e.has(n)}}function pe(r){return!Array.isArray(r)}function ki(r){return pe(r)?r.objects.reduce((e,t)=>e+t.count,0):r.reduce((e,t)=>e+t.ids.length,0)}function Oi(r){return(pe(r)?r.objects:r).map(e=>e.objectApiName)}var ot=class{bits=new Uint8Array(0);add(e){let t=e>>3;if(t>=this.bits.length){let n=new Uint8Array(Math.max(t+1,this.bits.length*2,64));n.set(this.bits),this.bits=n}this.bits[t]|=1<<(e&7)}has(e){let t=e>>3;return t<this.bits.length&&(this.bits[t]&1<<(e&7))!==0}},Tt=class{dates=new Float64Array(0);set(e,t){if(e>=this.dates.length){let n=new Float64Array(Math.max(e+1,this.dates.length*2,64)).fill(Number.NaN);n.set(this.dates),this.dates=n}this.dates[e]=t}at(e){return e<this.dates.length?this.dates[e]:Number.NaN}latestWithin(e,t){let n=Number.NaN;for(let o of this.dates)o>=e&&o<=t&&!(o<=n)&&(n=o);return n}};function je(r,e){return typeof r=="string"&&e.has(w(r))}var Kn=[{created:"CreatedDate",modified:"LastModifiedDate"},{modified:"SystemModstamp"}],Mt={ContentDocumentLink:{ends:["ContentDocumentId","LinkedEntityId"],cameWithRun:(r,e)=>{let t=r.LinkedEntityId;return je(r.ContentDocumentId,e)&&(je(t,e)||typeof t=="string"&&t.startsWith(oo))}},DuplicateRecordItem:{ends:["RecordId"],cameWithRun:(r,e)=>je(r.RecordId,e)},ContentVersion:{ends:["ContentDocumentId"],cameWithRun:(r,e)=>je(r.ContentDocumentId,e)}};function Ei(r,e){return{...Ue(r,e),serverTime:async()=>(await r.soap.getServerTimestamp()).timestamp,userId:async()=>(await r.soap.getUserInfo()).userId,queryDeleted:async t=>({records:(await r.query(t,{scanAll:!0})).records}),bulkDestroy:(t,n,o)=>De(Je(r),t,n,o)}}function xt(r,e,t){let n=new Map;for(let o of r??[]){let s=Ft(o.span,[],t);if(Number.isFinite(s.end))for(let i of o[e]??[]){let a=w(i);s.end<=(n.get(a)?.end??Number.NEGATIVE_INFINITY)||n.set(a,s)}}return n}function co(r=[],e=[]){if(r.length===0&&e.length===0)return;let t=[...r.map(({plan:n})=>pe(n)?n:rt(n)),rt(e)];return{has:n=>t.some(o=>o.has(n))}}function lo(r=[],e=[]){return new Set([...r.map(({plan:t})=>pe(t)?t.objects:t),e].flat().map(t=>t.objectApiName))}function er(r,e){return new Map([...xt(r,"wrote",e)].map(([t,{end:n}])=>[t,n]))}function tr(r,e){return`The user SandForge connects as may not delete ${r} records in this org: the ${e} record(s) of the run stay, and were not sent.`}function _t(r,e){return`Not visible: ${r} record(s) found neither in the org nor in its recycle bin, as the user the removal runs as sees them \u2014 out of that user's sight, or deleted for good \u2014 are not counted as removed`+(e?` (the recycle bin could not be read: ${e})`:".")}function Gn(r,e,t){for(let o of r){let s=o.deleted+o.alreadyGone+o.keptChanged+o.keptDependents+o.refused+(o.notVisible??0);o.planned>s&&(o.notReached=o.planned-s)}let n=new Set(r.map(o=>o.objectApiName));for(let{objectApiName:o,count:s}of e)s===0||n.has(o)||(n.add(o),r.push({...new Me(o,s,t(o)).result,notReached:s}));return r}var Di={objects:[],cancelled:!1,gone:[],stamps:{},left:async function*(){}};function w(r){return r.slice(0,15)}function uo(r){return r?.errorCode==="INVALID_FIELD"||/no such column/i.test(N(r))}function fo(r,e){let t=/no such column '(\w+)'/i.exec(N(r))?.[1],n=nt.findIndex((o,s)=>s>e&&(t===void 0||!o.includes(t)));return n===-1?nt.length:n}function q(r){return typeof r=="string"?Date.parse(r):Number.NaN}function nr(){return{modified:new Tt,missing:new Set,firstCreated:Number.NaN,lastCreated:Number.NaN,binned:new Set}}var Me=class{result;notes=[];refused=new Map;unread;held=[];goneAt=new ot;goneLater=new Set;deletedLater=new Set;notVisible=0;notVisibleNote;secondTry=new Set;filesLeft=new Map;automationHeld=new Map;automationHeldAfter=new Set;automationHeldAlong=new Set;tookAlong=new Map;cameAlong=new Map;limitNotes=[];lockResent=new Map;constructor(e,t,n=0){this.result={objectApiName:e,planned:t,deleted:0,alreadyGone:0,keptChanged:0,keptDependents:0,refused:0,heldBy:[],...n>0?{platformCopies:n}:{},unchecked:[],reasons:[]}}note(e){this.notes.includes(e)||this.notes.push(e)}isGone(e,t){return this.goneAt.has(t)||this.goneLater.has(w(e))}waiting(){return[...[...this.refused].filter(([,e])=>e.dependency).map(([e])=>e),...this.held]}refusedSent(){return[...this.refused].filter(([,e])=>e.sent).map(([e])=>e)}refusedToSendAgain(){return[...this.refused].filter(([,e])=>e.sent&&e.limit!==!0).map(([e])=>e)}secondTryNote(){if(this.secondTry.size===0)return[];let e=0,t=0,n=0,o=0;for(let i of this.secondTry){let a=w(i);this.deletedLater.has(a)?e++:this.goneLater.has(a)?t++:this.refused.has(i)?o++:n++}return[`Refused at first, sent again once the rest had gone: ${[e>0?`${e} deleted`:"",t>0?`${t} already gone`:"",n>0?`${n} kept for records that stay`:"",o>0?`${o} refused again`:""].filter(Boolean).join(", ")}.`]}settle(){this.result.keptDependents=this.held.length,this.result.refused=this.refused.size+(this.unread?.count??0),this.notVisible>0&&(this.result.notVisible=this.notVisible),this.held.length===0&&(this.result.heldBy=[]);let e=this.held.flatMap(s=>{let i=this.automationHeld.get(w(s));return i?[i]:[]}),t=this.held.filter(s=>{let i=w(s);return this.automationHeld.has(i)&&this.automationHeldAfter.has(i)}).length,n=this.held.filter(s=>{let i=w(s);return this.automationHeld.has(i)&&this.automationHeldAlong.has(i)}).length;e.length>0?(this.result.heldByAutomation=e.length,t>0?this.result.heldByAutomationAfterRun=t:delete this.result.heldByAutomationAfterRun,n>0?this.result.heldByAutomationAlong=n:delete this.result.heldByAutomationAlong,this.result.automationHolders=[...new Set(e.flatMap(s=>[...s]))]):(delete this.result.heldByAutomation,delete this.result.heldByAutomationAfterRun,delete this.result.heldByAutomationAlong,delete this.result.automationHolders);let o=[...this.notVisibleNote?[this.notVisibleNote]:[],...this.notes,...this.limitNotes,...jn(this.lockResent.values()),...this.secondTryNote(),...this.unread?[this.unread.reason]:[],...[...this.refused.values()].map(s=>s.reason)];return this.result.reasons=[...new Set(o)].slice(0,no),this.filesLeft.size>0&&(this.result.filesLeft={count:this.filesLeft.size,names:[...this.filesLeft.values()].slice(0,ao)}),this.tookAlong.size>0&&(this.result.tookAlong={count:this.tookAlong.size,objects:[...new Set(this.tookAlong.values())]}),this.cameAlong.size>0&&(this.result.cameAlong={count:this.cameAlong.size,objects:[...new Set(this.cameAlong.values())]}),this.result}};async function Ii(r,e,t){let n=pe(e)?e:rt(e),o=n,s=o.objects.reduce((y,A)=>y+A.count,0),i=new Map,a=y=>i.get(y)??0,d=()=>t.signal?.aborted===!0,c=t.splitting??dn(),u=()=>({objects:Gn([],o.objects,a),cancelled:!0,gone:[],stamps:{},left:()=>Xn(n)}),f=new Map,l=new Map;for(let{objectApiName:y}of o.objects){let A=nr();f.set(y,A);let E=0;for await(let P of o.pages(y)){if(d())return u();let J=P[0];J!==void 0&&!l.has(J.slice(0,3))&&l.set(J.slice(0,3),y);let B=E;if(E+=P.length,A.error!==void 0)continue;let C=await wo(r,y,P,B,A);if(A.error!==void 0||C.length===0)continue;if(d())return u();let Q=await _n(r,y,C);if("error"in Q)A.binError=Q.error;else for(let ne of Q.deleted)A.binned.add(ne)}}let g=new Map,p=!1,m=r.bulkDestroy?.bind(r),b={query:y=>r.query(y),destroy:(y,A)=>(p=!0,r.destroy(y,A)),...m?{bulkDestroy:(y,A)=>(p=!0,m(y,A,t.signal))}:{},update:(y,A)=>(p=!0,r.update(y,A)),serverTime:()=>r.serverTime(),userId:()=>r.userId(),queryDeleted:y=>r.queryDeleted(y),describeGlobal:()=>r.describeGlobal(),describe:y=>{let A=g.get(y);return A||(A=r.describe(y),g.set(y,A)),A}},h=$n(b,{includeChanged:t.includeChanged}),R=await Ke(h,o.objects),S=await yo(h,R,(y,A)=>A-(f.get(y)?.missing.size??0)),j=new Set(S.map(y=>y.objectApiName));if(S.length>0&&t.onUndeletable&&t.previewOnly!==!0){if(d())return u();if(!await t.onUndeletable(S))return{...u(),objects:[],undeletable:S,stoppedForUndeletable:!0}}let[_,U]=await Promise.all([Ao(h),t.previewOnly===!0?void 0:ko(h)]),{start:k,end:O}=Ft(t,f.values(),_.aheadMs);if(d())return u();let I=co(t.otherParts,t.otherPartRecords),D=lo(t.otherParts,t.otherPartRecords),M=await Ro(h,o,{start:k,end:O,...t.runUserId?{user:w(t.runUserId)}:{},...I?{otherParts:{has:y=>I.has(y),objects:D}}:{},undeletable:j,snapshots:f});if(t.runUserId&&t.alongAccepted!==!0){let y=await xn(h,{has:A=>o.has(A),start:k,end:O,user:t.runUserId});y.length>0&&!o.objects.some(A=>A.objectApiName===Re)&&await rr(h,Re)&&M.push({objectApiName:Re,copies:y})}if(M.length>0){o=await So(o,M,f,l);for(let{objectApiName:y,copies:A}of M)i.set(y,A.length);s=o.objects.reduce((y,A)=>y+A.count,0),R=await Ke(h,o.objects)}let H=new Map(Object.entries(t.removalStamps??{}).map(([y,A])=>[w(y),q(A)])),v=er(t.laterParts,_.aheadMs),T=new Set;for(let{objectApiName:y}of o.objects){let A=f.get(y);if(!A||A.error!==void 0)continue;let E=0;for await(let P of o.pages(y))for(let J of P){let B=A.modified.at(E++),C=w(J);if(A.missing.has(C))continue;B<=O||B<=(H.get(C)??Number.NaN)||B<=(v.get(C)??Number.NaN)||T.add(C)}}if(t.previewOnly===!0){if(d())return u();let y=new Set,A=await po(h,o,R,{snapshots:f,changed:T,undeletable:j,includeChanged:t.includeChanged,stopped:d,copiesOf:a,...t.previewHeld===!0?{held:{notSent:y,check:new Le(h,{runRecords:o,reached:{has:()=>!1},stays:E=>y.has(E),runStart:k,runEnd:O,removalStart:_.start,removalUser:void 0,earlierRemovals:(t.removalSpans??[]).map(E=>({start:q(E.first),end:q(E.last),user:w(E.userId)})),includeChanged:t.includeChanged,previewing:!0,...t.goesWithParent?{goesWithParent:t.goesWithParent}:{},...t.goesWithParentReadBelow?{goesWithParentReadBelow:!0}:{},...t.alongAccepted?{alongAccepted:t.alongAccepted}:{},...t.runUserId?{runUser:w(t.runUserId)}:{},...t.laterParts?{linkedLater:xt(t.laterParts,"linked",_.aheadMs)}:{},...I?{otherPartRecords:I,otherPartObjects:D}:{}})}}:{}});return A?{...S.length>0?{undeletable:S}:{},objects:[],cancelled:!1,gone:[],stamps:{},left:()=>Xn(n),preview:A}:u()}let L=await bo(h,t.otherParts??[],_.aheadMs,d);if(!L)return u();let xe=new Set,hr={has:y=>o.has(y)&&xe.has(l.get(y.slice(0,3))??"")},at=new Le(h,{runRecords:o,reached:hr,stays:y=>T.has(y)&&!t.includeChanged,runStart:k,runEnd:O,removalStart:_.start,removalUser:U,earlierRemovals:(t.removalSpans??[]).map(y=>({start:q(y.first),end:q(y.last),user:w(y.userId)})),includeChanged:t.includeChanged,...t.goesWithParent?{goesWithParent:t.goesWithParent}:{},...t.goesWithParentReadBelow?{goesWithParentReadBelow:!0}:{},...t.alongAccepted?{alongAccepted:t.alongAccepted}:{},...t.alongToDraft?{alongToDraft:t.alongToDraft}:{},...t.runUserId?{runUser:w(t.runUserId)}:{},...t.automationMade?{automationMade:ir(t.automationMade)}:{},...t.laterParts?{linkedLater:xt(t.laterParts,"linked",_.aheadMs)}:{},...I?{otherPartRecords:I,otherPartObjects:D}:{}});if(d())return u();await t.beforeFirstWrite?.(),t.sweep&&await t.sweep(c)&&(p=!0);let le=[],Kt=y=>le.find(A=>A.result.objectApiName===y);async function*dt(y,A,E){for(let{objectApiName:P}of A){let J=Kt(P),B=0;for await(let C of y.pages(P)){let Q=C.filter(ne=>E(P,ne,J?.isGone(ne,B++)===!0));Q.length>0&&(yield{objectApiName:P,ids:Q})}}}let yr=()=>dt(o,R,(y,A,E)=>{let P=f.get(y),J=w(A);return P?.modifiedColumn==="LastModifiedDate"&&!P.missing.has(J)&&!T.has(J)&&!E}),_e=[],Z=async y=>{await Ln(h,_e,{note:(C,Q,ne)=>{let Y=Kt(C);if(!Y){if(!ne)return;let se=o.objects.find(ie=>ie.objectApiName===C);Y=new Me(C,se?.count??0,a(C)),le.push(Y)}Y.note(Q)}});let A=p?await Yn(h,yr(),{start:_.start,user:U}):{},E=[];if(p)for(let C of L)E.push(await Yn(h,C.unchanged(),{start:_.start,user:U}));let P=p?Oo(_,U):void 0,J=[];if(!pe(e))for await(let{ids:C}of dt(n,R,(Q,ne,Y)=>Y))for(let Q of C)J.push(Q);for(let C of le)C.limitNotes=Dt(C.result.objectApiName,c);let B=le.map(C=>C.settle());return{...S.length>0?{undeletable:S}:{},objects:y?Gn(B,R,a):B,cancelled:y,gone:J,left:()=>dt(n,n.objects,(C,Q,ne)=>!ne),stamps:A,...P?{span:P}:{},...E.length>0?{otherPartStamps:E}:{}}};if(d())return p?Z(!0):u();let Gt=async(y,A)=>(await at.heldAmong(y,A)).held,Yt=await Pt(h,R,o,(y,A)=>{let E=w(A),P=f.get(y);return P!==void 0&&P.error===void 0&&!j.has(y)&&!P.missing.has(E)&&!(T.has(E)&&!t.includeChanged)},d,Gt);if(_e=Yt.drafted,Yt.cancelled)return Z(!0);if(t.alongToDraft){let y=await Pt(h,t.alongToDraft.objects,t.alongToDraft,()=>!0,d,Gt);if(_e=[..._e,...y.drafted],y.cancelled)return Z(!0)}let ae=0;for(let{objectApiName:y,count:A}of R){if(d())return Z(!0);let E=new Me(y,A,a(y));le.push(E),xe.add(y);let P=f.get(y);if(!P||P.error!==void 0){E.unread={reason:P?.error??"The org gave no reason.",count:A},ae+=A,t.onProgress?.(ae,s,y);continue}if(j.has(y)){let Y=0,se=0;for await(let ie of o.pages(y))for(let ye of ie){let Se=w(ye),wr=Y++;P.missing.has(Se)?P.binned.has(Se)?(E.result.alreadyGone++,E.goneAt.add(wr)):E.notVisible++:se++}E.notVisible>0&&(E.notVisibleNote=_t(E.notVisible,P.binError)),se>0&&(E.unread={reason:tr(y,se),count:se}),ae+=A,t.onProgress?.(ae,s,y);continue}let J=Pn(h,y,A),B=[],C=new Map,Q=async()=>{let Y=B,se=C;return B=[],C=new Map,Zn(h,at,E,Y,{stopped:d,splitting:c,placeOf:se,onDeleted:ie=>{ae+=ie,t.onProgress?.(ae,s,y)},onHeld:ie=>{ae+=ie,t.onProgress?.(ae,s,y)}})},ne=0;for await(let Y of o.pages(y)){if(d())return Z(!0);let se=B.length;for(let ie of Y){let ye=w(ie),Se=ne++;P.missing.has(ye)?P.binned.has(ye)?(E.result.alreadyGone++,E.goneAt.add(Se)):E.notVisible++:T.has(ye)&&!t.includeChanged?E.result.keptChanged++:(B.push(ie),C.set(ye,Se))}if(E.notVisible>0&&(E.notVisibleNote=_t(E.notVisible,P.binError)),ae+=Y.length-(B.length-se),!(J&&B.length<Ve)&&await Q())return Z(!0)}if(J&&B.length>0&&(d()||await Q()))return Z(!0)}let br=le.some(y=>y.result.deleted>0);if(await Mn(le,{stopped:d,idsOf:(y,A)=>{if(A>0)return y.waiting();let E=y.refusedToSendAgain();return E.length>0||br?[...E,...y.held]:[]},send:async(y,A,E)=>{let P=new Set(E===0?y.refusedToSendAgain():[]),J=await Zn(h,at,y,A,{stopped:d,splitting:c,onSent:B=>{for(let C of B)P.has(C)&&y.secondTry.add(C)}});for(let B of y.held)P.has(B)&&y.secondTry.add(B);return J},deleted:y=>y.result.deleted}))return Z(!0);if(t.afterRemoval){if(d())return Z(!0);await t.afterRemoval(c)&&(p=!0)}for(let y of le){if(d())return Z(!0);await ho(h,y,f.get(y.result.objectApiName))}return Z(!1)}async function go(r,e,t,n,o){let{changed:s,includeChanged:i}=o,a=[];for await(let d of e.pages(t))for(let c of d){let u=w(c);!n.has(u)&&(i||!s.has(u))&&a.push(c)}try{return{kept:await zn(r,t,a,{includeChanged:i})}}catch(d){return{kept:new Set,unread:N(d)}}}async function po(r,e,t,n){let o=[],s=new Set;for(let{objectApiName:i,count:a}of t){let d=n.copiesOf(i),c={objectApiName:i,planned:a,toDelete:0,alreadyGone:0,changedSince:0,keptChanged:0,changedBy:{},undeletable:0,notVisible:0,unread:0,...d>0?{platformCopies:d}:{},reasons:[]};o.push(c);let u=n.snapshots.get(i);if(!u||u.error!==void 0){if(c.unread=a,c.reasons.push(u?.error??"The org gave no reason."),n.held)for await(let m of e.pages(i))for(let b of m)n.held.notSent.add(w(b));continue}let f=Ie(i)&&!n.undeletable.has(i)?await go(r,e,i,u.missing,n):void 0,l=[],g=[],p=m=>{n.held?.notSent.add(m)};for await(let m of e.pages(i))for(let b of m){let h=w(b);u.missing.has(h)?u.binned.has(h)?c.alreadyGone++:c.notVisible++:n.undeletable.has(i)?(c.undeletable++,p(h)):f?.unread!==void 0?(c.unread++,p(h)):n.changed.has(h)?(c.changedSince++,l.push(b),n.includeChanged?(c.toDelete++,g.push(b)):(c.keptChanged++,p(h))):f?.kept.has(h)?(c.changedSince++,c.keptChanged++,p(h)):(c.toDelete++,g.push(b))}if(n.held&&g.length>0){if(n.stopped())return;let m=await n.held.check.heldAmong(i,g),b=g.filter(R=>m.held.has(w(R)));if(b.length>0){c.toDelete-=b.length,c.keptDependents=b.length,c.heldBy=[...m.holders];for(let S of b)n.held.notSent.add(w(S));let R=b.filter(S=>m.byAutomation.has(w(S)));R.length>0&&(c.heldByAutomation=R.length)}let h=new Map;for(let R of g)if(!m.held.has(w(R)))for(let[S,j]of m.cameAlong.get(w(R))??[])h.set(S,j);h.size>0&&(c.cameAlong={count:h.size,objects:[...new Set(h.values())]}),m.reason!==void 0&&c.reasons.push(m.reason),m.unchecked.size>0&&c.reasons.push(`Not checked: what hangs from them through ${[...m.unchecked].join(", ")}, which the org deletes along but does not let be read by the record it hangs from.`)}if(f?.unread!==void 0?c.reasons.push(`Its articles could not be read: ${f.unread}`):f!==void 0&&f.kept.size>0&&c.reasons.push(Nt),c.notVisible>0&&c.reasons.push(_t(c.notVisible,u.binError)),c.undeletable>0&&c.reasons.push(tr(i,c.undeletable)),!(l.length===0||u.modifiedColumn!=="LastModifiedDate")){if(n.stopped())return;try{let m=await z(r,i,["LastModifiedById"],l,ve);for(let b of m){let h=b.LastModifiedById;typeof h!="string"||h===""||(c.changedBy[h]=(c.changedBy[h]??0)+1,s.add(h))}}catch(m){c.reasons.push(`Who changed them since the run could not be read: ${N(m)}`)}}}if(!n.stopped())return{objects:o,userNames:await mo(r,[...s])}}async function mo(r,e){let t={};if(e.length===0)return t;try{for(let n of await z(r,"User",["Name"],[...e].sort()))typeof n.Id=="string"&&typeof n.Name=="string"&&(t[n.Id]=n.Name)}catch{}return t}async function ho(r,e,t){let{gone:n,unchecked:o,failure:s}=await It(e.refusedSent(),i=>z(r,e.result.objectApiName,[],i),i=>t!==void 0&&t.error===void 0&&!t.missing.has(w(i)));for(let i of n)e.refused.delete(i),e.goneLater.add(w(i)),e.result.alreadyGone++;o.length>0&&e.note(`Not checked: ${o.length} refused record(s) could not be read back once the rest had gone, to tell whether a parent deleted after them took them along`+(s?` \u2014 ${s}`:"."))}function Pi(r,e=[],t={}){return[...new Set([...r,...Qn(r,e),...t.userKept===!0&&r.length>0?[Re]:[]])]}async function yo(r,e,t){let n=[];for(let{objectApiName:o,count:s}of e){if(o===io||s===0)continue;let i=t(o,s);if(i!==0)try{let a=de.safeParse(await r.describe(o));a.success&&a.data.deletable===!1&&n.push({objectApiName:o,records:i})}catch{}}return n}async function Yn(r,e,t){let n={},{start:o,user:s}=t;if(s===void 0||!Number.isFinite(o))return n;for await(let{objectApiName:i,ids:a}of e){let d;try{d=await z(r,i,["LastModifiedDate","LastModifiedById"],a)}catch{continue}for(let c of d)typeof c.Id=="string"&&typeof c.LastModifiedDate=="string"&&typeof c.LastModifiedById=="string"&&w(c.LastModifiedById)===s&&q(c.LastModifiedDate)>=o&&(n[c.Id]=c.LastModifiedDate)}return n}async function bo(r,e,t,n){let o=[];for(let s of e){let i=pe(s.plan)?s.plan:rt(s.plan),{end:a}=Ft(s.span,[],t),d=new Map(Object.entries(s.removalStamps??{}).map(([f,l])=>[w(f),q(l)])),c=er(s.laterParts,t),u=new Map;if(Number.isFinite(a))for(let{objectApiName:f}of i.objects){let l=new ot,g=0,p=!1;for await(let m of i.pages(f)){if(n())return;let b=g;if(g+=m.length,p)continue;let h;try{h=await z(r,f,["LastModifiedDate"],m,ve)}catch{p=!0;continue}let R=new Map;for(let S of h)typeof S.Id=="string"&&R.set(w(S.Id),q(S.LastModifiedDate));m.forEach((S,j)=>{let _=w(S),U=R.get(_);U!==void 0&&(U<=a||U<=(d.get(_)??Number.NaN)||U<=(c.get(_)??Number.NaN))&&l.add(b+j)})}p||u.set(f,l)}o.push({unchanged:async function*(){for(let{objectApiName:f}of i.objects){let l=u.get(f);if(!l)continue;let g=0;for await(let p of i.pages(f)){let m=p.filter(()=>l.has(g++));m.length>0&&(yield{objectApiName:f,ids:m})}}}})}return o}async function Zn(r,e,t,n,o){let{objectApiName:s}=t.result,i=await e.heldAmong(s,n);i.reason!==void 0&&t.note(i.reason);for(let l of i.unchecked)t.result.unchecked.includes(l)||t.result.unchecked.push(l);let a=n.filter(l=>i.held.has(w(l)));if(o.placeOf){for(let l of a)t.held.push(l);t.result.heldBy=[...new Set([...t.result.heldBy,...i.holders])]}else t.held=a,t.result.heldBy=[...i.holders];for(let l of a)t.refused.delete(l);for(let l of n){let g=w(l),p=i.byAutomation.get(g);p?t.automationHeld.set(g,p):t.automationHeld.delete(g),p&&i.automationAfter.has(g)?t.automationHeldAfter.add(g):t.automationHeldAfter.delete(g),p&&i.automationAlong.has(g)?t.automationHeldAlong.add(g):t.automationHeldAlong.delete(g)}o.onHeld?.(a.length);let d=n.filter(l=>!i.held.has(w(l))),c=new Map,u=(l,g)=>{l.forEach((p,m)=>{let b=g[m],h=w(p);if((b.lockResends!==void 0||t.lockResent.has(h))&&t.lockResent.set(h,b.kind),b.kind==="refused"){t.refused.set(p,{reason:b.reason,dependency:b.dependency,sent:!0,...b.limit?{limit:!0}:{}});return}t.refused.delete(p);let R=o.placeOf?.get(h);if(R!==void 0?t.goneAt.add(R):t.goneLater.add(h),b.kind==="deleted"){t.result.deleted++,R===void 0&&t.deletedLater.add(h);for(let S of c.get(h)??[])t.filesLeft.set(S.key,S.name);for(let[S,j]of i.along.get(h)??[])t.tookAlong.set(S,j);for(let[S,j]of i.cameAlong.get(h)??[])t.cameAlong.set(S,j)}else t.result.alreadyGone++}),o.onSent?.(l),o.onDeleted?.(l.length)},{stopped:f}=await vn(r,s,d,{stopped:o.stopped,splitting:o.splitting,prepare:async l=>{c=await e.filesOn(l)},settle:u});return f}async function wo(r,e,t,n,o){let s,i=o.modifiedColumn?Kn.filter(({modified:a})=>a===o.modifiedColumn):Kn;for(let{created:a,modified:d}of i)try{let u=await z(r,e,a?[a,d]:[d],t,ve),f=new Map;for(let g of u)typeof g.Id=="string"&&f.set(w(g.Id),q(g[d])),a&&(o.firstCreated=or(o.firstCreated,q(g[a])),o.lastCreated=Bt(o.lastCreated,q(g[a])));o.modifiedColumn=d;let l=[];return t.forEach((g,p)=>{let m=w(g),b=f.get(m);b===void 0&&(o.missing.add(m),l.push(g)),o.modified.set(n+p,b??Number.NaN)}),l}catch(c){s??=N(c)}return o.error=s,o.modifiedColumn=void 0,[]}async function*Xn(r){for(let{objectApiName:e}of r.objects)for await(let t of r.pages(e))t.length>0&&(yield{objectApiName:e,ids:[...t]})}async function Ro(r,e,t){let n=new Set(e.objects.filter(a=>a.count>0).map(a=>a.objectApiName));if(!n.has(Ze))return[];let o=[];for await(let a of e.pages(Ze))o.push(...a);let s=await Wn(r,{has:a=>e.has(a),start:t.start,end:t.end,...t.user!==void 0?{user:t.user}:{},...t.otherParts?{otherParts:t.otherParts}:{}},o,n),i=[];for(let a of s){let{objectApiName:d}=a;if(t.undeletable.has(d))continue;let c=t.snapshots.get(d);if(c){if(c.error!==void 0||c.modifiedColumn!=="LastModifiedDate")continue}else if(!await rr(r,d))continue;i.push(a)}return i}async function rr(r,e){try{let t=de.safeParse(await r.describe(e));return t.success&&t.data.deletable!==!1}catch{return!1}}async function So(r,e,t,n){let o=new Map(e.map(({objectApiName:a,copies:d})=>[a,d])),s=new Set(e.flatMap(({copies:a})=>a.map(d=>w(d.id)))),i=r.objects.map(a=>{let d=o.get(a.objectApiName);return d?{objectApiName:a.objectApiName,count:a.count+d.length}:a});for(let[a,d]of o){r.objects.some(l=>l.objectApiName===a)||i.push({objectApiName:a,count:d.length});let c=t.get(a);c||(c={...nr(),modifiedColumn:"LastModifiedDate"},t.set(a,c));let u=0;for await(let l of r.pages(a))u+=l.length;for(let l of d)c.modified.set(u++,l.modified);let f=d[0]?.id.slice(0,3);f!==void 0&&!n.has(f)&&n.set(f,a)}return{objects:i,pages:async function*(a){yield*r.pages(a);let d=o.get(a);d&&d.length>0&&(yield d.map(c=>c.id))},has:a=>r.has(a)||s.has(a)}}async function Ao(r){let e=Date.now(),t=Number.NaN;try{t=q(await r.serverTime())}catch{}return Number.isFinite(t)?{start:Math.floor(t/1e3)*1e3,aheadMs:t-(e+Date.now())/2}:{start:Number.POSITIVE_INFINITY,aheadMs:Number.NaN}}async function ko(r){try{let e=await r.userId();return typeof e=="string"&&e!==""?w(e):void 0}catch{return}}function Oo(r,e){if(!(e===void 0||!Number.isFinite(r.start)))return{first:new Date(r.start).toISOString(),last:new Date(Date.now()+r.aheadMs+Lt).toISOString(),userId:e}}function or(r,e){return Number.isNaN(r)||e<r?e:r}function Bt(r,e){return Number.isNaN(r)||e>r?e:r}var sr=999;function Eo(r,e,t){let n=Number.NaN;for(let o of r)o.lastCreated>=e&&o.lastCreated<=t&&(n=Bt(n,o.lastCreated)),n=Bt(n,o.modified.latestWithin(e,t));return n}function Ft(r,e,t){let n=Do(r,e,t),o=(r.writtenUntil?.getTime()??Number.NaN)+sr;return Number.isFinite(n.end)&&o>n.end?{...n,end:o}:n}function Do(r,e,t){let n=[...e],o=Number.NaN;for(let c of n)o=or(o,c.firstCreated);let s=r.runDurationMs??0,i=(r.runRecordedAt?.getTime()??Number.NaN)+t;if(r.runEndedAt===void 0&&Number.isFinite(i)){let c=i-s-Lt,u=i+Lt,f=r.endedByItsWrites===!0?Eo(n,c,u):Number.NaN;return{start:r.runStartedAt?.getTime()??(o>c?o:c),end:Number.isFinite(f)?Math.min(f+sr,u):u}}let a=r.runStartedAt?.getTime()??o,d=r.runEndedAt?.getTime()??a+s;return{start:a,end:d}}function ir(r){let e=new Set,t=-1;return{has:n=>(r.size!==t&&(e=new Set([...r].map(w)),t=r.size),e.has(n))}}function Ci(r,e){let t=new Le(r,{runRecords:e.runRecords,reached:{has:()=>!1},stays:()=>!1,runStart:e.runStart,runEnd:e.runEnd,removalStart:Number.POSITIVE_INFINITY,removalUser:void 0,earlierRemovals:(e.removalSpans??[]).map(n=>({start:q(n.first),end:q(n.last),user:w(n.userId)})),includeChanged:e.includeChanged,automationMade:ir(e.taken),...e.runUserId?{runUser:w(e.runUserId)}:{}});return async(n,o)=>{let s=await t.heldAmong(n,o,1);return{held:s.held,holders:[...s.holders],...s.reason!==void 0?{reason:s.reason}:{}}}}var et="IsPersonAccount",Io=50;function tt(r,e){return JSON.stringify(e.map(t=>r[t]??null))}var Le=class{constructor(e,t){this.org=e;this.context=t}org;context;worked;statuses=new Map;lockedUnder=new Map;files=new Map;datesKept=new Map;cascadeEnds=new Map;async heldAmong(e,t,n=0){let o={held:new Set,holders:new Set,otherwise:new Set,mayBeAutomation:[],byAutomation:new Map,automationAfter:new Set,automationAlong:new Set,along:new Map,cameAlong:new Map,unchecked:new Set};if(t.length===0)return o;let s;try{let l=de.parse(await this.org.describe(e)),g=await this.workedObjects(),p=e==="Account"&&l.fields.some(m=>m.name===et);s=(l.childRelationships??[]).filter(m=>(m.cascadeDelete===!0||m.restrictedDelete===!0)&&g.has(m.childSObject)).map(m=>({childSObject:m.childSObject,field:m.field,restricted:m.cascadeDelete!==!0,...p&&m.childSObject==="Contact"&&m.field==="AccountId"?{personContacts:!0}:{}}))}catch(l){return o.reason=N(l),t.forEach(g=>this.hold(o,w(g))),o}let i=[];for(let l=0;l<t.length;l+=re)i.push(t.slice(l,l+re));let a=i.length>1?await ft(s.map(l=>()=>this.anyPointing(l)),ve):s.map(()=>!0),d=s.filter((l,g)=>a[g]).flatMap(l=>i.map(g=>async()=>({relationship:l,...await this.holdingIn(l,g)}))),c=o.mayBeAutomation,u=new Map;for(let{relationship:l,holding:g,unchecked:p,automation:m,along:b,goes:h}of await ft(d,ve)){p&&o.unchecked.add(l.childSObject),(g.size>0||m.length>0)&&o.holders.add(l.childSObject),g.forEach(R=>this.hold(o,R));for(let R of m)o.held.add(w(R.parent));c.push(...m);for(let{parent:R,key:S}of b){let j=o.along.get(R)??new Map;j.set(S,l.childSObject),o.along.set(R,j)}h.length>0&&u.set(l.childSObject,[...u.get(l.childSObject)??[],...h])}if(await this.heldBelow(u,o,n),n>0)return o;this.context.previewing!==!0&&await this.lockedPastDraft(e,t,o),$e(e)&&await this.standardPricesHeld(t,o),e===lt&&await this.sellingModelOptionsHeld(t,o),this.context.alongAccepted!==!0&&await this.automationHeldBelow(c,o);let f=await this.byAutomationOnly(e,c,o.otherwise);return o.byAutomation=f.objects,o.automationAfter=f.after,o.automationAlong=f.along,o}hold(e,t){e.held.add(t),e.otherwise.add(t)}async heldBelow(e,t,n){let o=(s,i,a,d)=>{let c=s.get(i)??new Map;c.set(a,d),s.set(i,c)};for(let[s,i]of e){let a=[...new Set(i.map(c=>c.id))],d=n+1<ro?await this.heldAmong(s,a,n+1):void 0;for(let{parent:c,id:u,came:f}of i){let l=w(u);if(!d||d.held.has(l)){this.hold(t,c),t.holders.add(s),d?.holders.forEach(g=>t.holders.add(g));continue}f&&o(t.cameAlong,c,l,s);for(let[g,p]of d.along.get(l)??[])o(t.along,c,g,p);for(let[g,p]of d.cameAlong.get(l)??[])o(t.cameAlong,c,g,p)}d?.unchecked.forEach(c=>t.unchecked.add(c))}}async automationHeldBelow(e,t){let n=new Map;for(let o of e)t.otherwise.has(w(o.parent))||n.set(o.object,[...n.get(o.object)??[],o]);for(let[o,s]of n){let i=await this.heldAmong(o,[...new Set(s.map(a=>a.id))],1);for(let a of s){let d=w(a.id),c=i.mayBeAutomation.some(u=>w(u.parent)===d&&u.creator!==a.creator);!i.otherwise.has(d)&&!c||(this.hold(t,w(a.parent)),i.holders.forEach(u=>t.holders.add(u)))}i.unchecked.forEach(a=>t.unchecked.add(a))}}async byAutomationOnly(e,t,n){let o=new Map,s=new Set,i=t.filter(f=>!n.has(w(f.parent)));if(i.length===0)return{objects:o,after:s,along:new Set};let a;try{let f=await z(this.org,e,["CreatedDate","CreatedById"],[...new Set(i.map(l=>l.parent))]);a=new Map(f.flatMap(l=>typeof l.Id=="string"?[[w(l.Id),l]]:[]))}catch{return{objects:o,after:s,along:new Set}}let d=new Set,c=new Set;for(let f of i){let l=w(f.parent),g=a.get(l),p=q(g?.CreatedDate),m=g?.CreatedById,b=this.context.runUser??(typeof m=="string"?w(m):void 0),h=f.created-p;if(!(b!==void 0&&f.creator===b&&h>=-2e3&&h<=6e4)){d.add(l);continue}let S=o.get(l)??new Set;S.add(f.object),o.set(l,S),f.created>this.context.runEnd&&s.add(l),f.along||c.add(l)}for(let f of d)o.delete(f),s.delete(f);let u=new Set([...o.keys()].filter(f=>!c.has(f)));return{objects:o,after:s,along:u}}async holdingIn(e,t){let n=F(e.childSObject),o=F(e.field),[s]=ee(t,t.length),i=new Set(["Id",o,...Mt[n]?.ends??[],...e.personContacts?[et]:[]]),a=this.datesKept.get(n)??0;for(;a<nt.length;){let d=nt[a],c;try{c=await this.org.query(`SELECT ${[...i,...d].join(", ")} FROM ${n} WHERE ${o} IN (${s}) LIMIT ${Xe}`)}catch(b){uo(b)?(a=fo(b,a),this.datesKept.set(n,a)):a++;continue}if(c.records.length>=Xe)return{holding:new Set(t.map(w)),automation:[],along:[],goes:[],unchecked:!1};let u=new Set,f=[],l=[],g=[],p=new Map;for(let b of c.records){if(typeof b!="object"||b===null)continue;let h=b,R=h[e.field];if(typeof R!="string"||typeof h.Id!="string"||(n===Vn&&o==="LinkedEntityId"&&this.noteFile(h),this.lockedUnder.get(w(h.Id))===w(R)))continue;let S={onlyIncluded:!1};if(!this.stays(h,n,e.restricted,e.personContacts,S)){if(S.onlyIncluded&&l.push({parent:w(R),key:w(h.Id)}),n!==Vn&&this.goesAlongUnread(h)){let U=!(Mt[n]?.cameWithRun(h,this.context.runRecords)===!0||e.personContacts===!0&&h[et]===!0)&&!S.onlyIncluded&&S.byRemoval!==!0&&this.context.goesWithParent?.(h,this.context.runEnd)!==!0;g.push({parent:w(R),id:h.Id,came:U})}continue}let j=this.mayBeAutomation(h);if(j){let _={parent:R,id:h.Id,object:n,along:!e.restricted,...j};f.push(_),e.restricted&&p.set(h.Id,_)}else u.add(w(R))}let m=await this.ofOtherParts(n,[...p.keys()]);for(let[b,h]of p)m.has(w(b))&&(f.splice(f.indexOf(h),1),u.add(w(h.parent)));return{holding:u,automation:f,along:l,goes:g,unchecked:!1}}return{holding:new Set,automation:[],along:[],goes:[],unchecked:!e.restricted}}goesAlongUnread(e){let t=w(e.Id),{runRecords:n,otherPartRecords:o,automationMade:s,goesWithParent:i,runEnd:a}=this.context;return this.context.alongAccepted!==!0&&!n.has(t)&&o?.has(t)!==!0&&s?.has(t)!==!0&&(this.context.goesWithParentReadBelow===!0||i?.(e,a)!==!0)}async ofOtherParts(e,t){let n=new Set,{otherPartRecords:o,otherPartObjects:s,runRecords:i}=this.context;if(t.length===0||!o||!s)return n;let a=this.cascadeEnds.get(e);a||(a=(async()=>{let u=new Set;for(let f of s)try{let l=de.parse(await this.org.describe(f));for(let g of l.childRelationships??[])g.childSObject===e&&g.cascadeDelete===!0&&u.add(g.field)}catch{}return[...u]})(),this.cascadeEnds.set(e,a));let d=await a;if(d.length===0)return n;let c;try{c=await z(this.org,e,d,t)}catch{return n}for(let u of c){if(typeof u.Id!="string")continue;let f=d.flatMap(l=>{let g=u[l];return typeof g=="string"?[w(g)]:[]});f.some(l=>i.has(l))||f.some(l=>o.has(l))&&n.add(w(u.Id))}return n}mayBeAutomation(e){let{runRecords:t,runStart:n,runEnd:o,runUser:s,otherPartRecords:i}=this.context;if(typeof e.Id!="string"||t.has(w(e.Id))||i?.has(w(e.Id))===!0||typeof e.CreatedById!="string")return;let a=w(e.CreatedById);if(s!==void 0&&a!==s)return;let d=q(e.CreatedDate);if(!(d>=n-2e3&&d<=o+6e4))return;let c=q(e.LastModifiedDate),u=typeof e.LastModifiedById=="string"?w(e.LastModifiedById):void 0;if(!(c>o&&u!==void 0&&u!==a))return{created:d,creator:a}}async anyPointing(e){try{let t=F(e.childSObject),n=F(e.field);return(await this.org.query(`SELECT Id FROM ${t} WHERE ${n} != null LIMIT 1`)).records.length>0}catch{return!0}}noteFile(e){let t=e.LinkedEntityId,n=e.ContentDocumentId;if(typeof t!="string"||typeof n!="string"||je(n,this.context.runRecords))return;let o=this.files.get(w(t))??new Set;o.add(n),this.files.set(w(t),o)}async filesOn(e){let t=new Map;for(let s of e){let i=this.files.get(w(s));i&&i.size>0&&t.set(w(s),[...i])}let n=[...new Set([...t.values()].flat())];if(n.length===0)return new Map;let o=new Map;try{for(let s of await z(this.org,so,["Title"],n))typeof s.Id=="string"&&typeof s.Title=="string"&&s.Title!==""&&o.set(w(s.Id),s.Title)}catch{}return new Map([...t].map(([s,i])=>[s,i.map(a=>({key:w(a),name:o.get(w(a))??a}))]))}async lockedPastDraft(e,t,n){for(let[o,s]of Object.entries(en)){let i=s.find(l=>l.object===e)?.lookup,a=Oe[o];if(!i||!a)continue;let d=await this.statusCategoriesOf(a);if(!d)continue;let c,u;try{c=await z(this.org,e,[i],t);let l=[...new Set(c.map(g=>g[i]).filter(g=>typeof g=="string"))];u=l.length>0?await z(this.org,o,["Status"],l):[]}catch{continue}let f=new Set(u.filter(l=>{let g=d.categoryOf.get(String(l.Status));return g!==void 0&&g!=="Draft"}).map(l=>w(String(l.Id))));for(let l of c){let g=l[i];typeof l.Id!="string"||typeof g!="string"||f.has(w(g))&&(this.hold(n,w(l.Id)),n.holders.add(o),this.lockedUnder.set(w(l.Id),w(g)))}}}statusCategoriesOf(e){let t=this.statuses.get(e);return t||(t=qe(be(this.org),e),this.statuses.set(e,t)),t}async standardPricesHeld(e,t){try{let n=be(this.org),o=[...await Ee(n,e)];if(o.length===0)return;let s=await this.priceKeyFields(),i=await z(this.org,fe,s,o),a=await this.pricesOfProducts(i,s),d=a.flatMap(l=>typeof l.Id=="string"?[l.Id]:[]),c=new Set([...await Ee(n,d)].map(w)),u=new Set(e.map(w)),f=new Set;for(let l of a){if(typeof l.Id!="string")continue;let g=w(l.Id);if(c.has(g))continue;(u.has(g)?t.held.has(g):this.stays(l,fe,!0))&&f.add(tt(l,s))}for(let l of i)typeof l.Id!="string"||!f.has(tt(l,s))||(this.hold(t,w(l.Id)),t.holders.add(fe))}catch{}}async sellingModelOptionsHeld(e,t){let n=[ke,ct];try{let o=await z(this.org,lt,n,e),s=await this.pricesOfProducts(o,[...n,"IsActive"]),i=new Set(s.filter(a=>typeof a.Id=="string"&&a.IsActive===!0&&this.stays(a,fe,!0)).map(a=>tt(a,n)));for(let a of o)typeof a.Id!="string"||!i.has(tt(a,n))||(this.hold(t,w(a.Id)),t.holders.add(fe))}catch{}}async priceKeyFields(){let e=de.parse(await this.org.describe(fe)),t=new Set(e.fields.map(n=>n.name));return[ke,...[ct,tn].filter(n=>t.has(n))]}async pricesOfProducts(e,t){let n=[...new Set(e.map(i=>i[ke]).filter(i=>typeof i=="string"))],o=[...new Set(["Id",...t])].map(F).join(", "),s=[];for(let i of ee(n,Io)){let a=await this.org.query(`SELECT ${o} FROM ${fe} WHERE ${ke} IN (${i}) LIMIT ${Xe}`);if(a.records.length>=Xe)throw new Error("More prices than one read takes.");for(let d of a.records)typeof d=="object"&&d!==null&&s.push(d)}return s}stays(e,t,n=!1,o=!1,s){let i=w(e.Id),{runRecords:a,reached:d,runStart:c,runEnd:u,removalStart:f,removalUser:l,earlierRemovals:g,includeChanged:p}=this.context;if(a.has(i))return d.has(i)||this.context.stays(i);if(n)return!0;if(this.context.automationMade?.has(i)===!0||this.context.goesWithParent?.(e,u)===!0||this.context.alongToDraft?.has(i)===!0||Mt[t]?.cameWithRun(e,a))return!1;if(o&&e[et]===!0)return!(q(e.LastModifiedDate??e.SystemModstamp)<=u)&&!p;let m="CreatedDate"in e?"CreatedDate":"SystemModstamp"in e?"SystemModstamp":void 0;if(!m)return!0;let b=q(e[m]),h=q(m==="CreatedDate"?e.LastModifiedDate:e.SystemModstamp);if(!(b>=c))return!0;let R=this.context.linkedLater?.get(i);if(R&&(b<=u||b>=R.start)&&h<=R.end)return!1;let S=typeof e.CreatedById=="string"?w(e.CreatedById):void 0,j=(U,k)=>U!==void 0&&(U===l&&k>=f||g.some(O=>U===O.user&&k>=O.start&&k<=O.end));if(j(S,b))return s&&(s.byRemoval=!0),!1;if(h<=u)return!1;let _=typeof e.LastModifiedById=="string"?w(e.LastModifiedById):void 0;return b<=u&&j(_,h)?!1:(p&&s&&(s.onlyIncluded=!0),!p)}workedObjects(){return this.worked??=an(this.org),this.worked}};var Po="encryptedstring";async function Co(r){try{let[e]=await r("SELECT PermissionsViewEncryptedData FROM UserPermissionAccess");return e?.PermissionsViewEncryptedData===!0}catch{return!1}}function Mi(r){let e;return()=>(e??=Co(r),e)}function Li(r,e){let t=new Map;return n=>{let o=t.get(n);return o||(o=(async()=>{let s;try{s=(await e(n)).fields.filter(a=>a.type===Po).map(a=>a.name)}catch{return[]}return s.length>0&&!await r()?s:[]})(),t.set(n,o)),o}}var me=5,qt=25,Ut=3;function Bi(r){return{get version(){return r.version},request:async e=>await r.request(e),query:async(e,t)=>await r.query(e,{scanAll:t?.scanAll===!0}),queryMore:async e=>await r.queryMore(e)}}var oe=class extends Error{constructor(){super("The read was stopped."),this.name="OrgReadStopped"}},No="PROCESSING_HALTED",ar="If-Modified-Since",jo=/^\d{1,3}\.\d$/,vo=/^\/services\/data\/v\d{1,3}\.\d\/query(?:All)?\/[A-Za-z0-9-]+$/,Mo=W({records:X(Fe(x(),Ae())),done:$(),totalSize:ue().optional(),nextRecordsUrl:x().optional()}).loose(),Lo=W({compositeResponse:X(W({body:Ae(),httpStatusCode:ue(),referenceId:x()}).loose())}),To=X(W({errorCode:x().optional(),message:x().optional()}).loose());function xo(r,e,t){if(!jo.test(r))throw new Error(`Not an API version: ${r}`);if(e.length>me)throw new Error(`A composite runs ${me} queries, not ${e.length}`);if(e.length+t.length>qt)throw new Error(`A composite holds ${qt} subrequests, not ${e.length+t.length}`);let n=`/services/data/v${r}`;return{allOrNone:!1,compositeRequest:[...e.map((o,s)=>({method:"GET",url:o.kind==="first"?`${n}/${o.scanAll?"queryAll":"query"}?q=${encodeURIComponent(o.soql)}`:o.path,referenceId:`q${s}`})),...t.map(({path:o,headers:s},i)=>({method:"GET",url:`${n}/${o}`,referenceId:`d${i}`,...s?{httpHeaders:s}:{}}))]}}function _o(r){let e=Lo.safeParse(r);if(!e.success)return;let t=new Map;for(let n of e.data.compositeResponse){if(n.httpStatusCode<400){t.set(n.referenceId,{ok:!0,status:n.httpStatusCode,body:n.body});continue}let o=To.safeParse(n.body),s=o.success?o.data[0]:void 0;t.set(n.referenceId,{ok:!1,refused:s?[s.errorCode,s.message].filter(Boolean).join(": "):`status ${n.httpStatusCode}`,halted:s?.errorCode===No})}return t}function $t(r){let e=Mo.safeParse(r);return e.success?e.data:void 0}function Bo(r){return typeof r=="object"&&r!==null&&typeof r.errorCode=="string"}function Fo(r){let e=/^https:\/\//i.test(r)?new URL(r).pathname:r;if(!vo.test(e))throw new Error(`Not the next page of a query: ${r}`);return e}function Fi(r,e){let t=new Set,n=[],o=me,s="composite",i=0,a=!1,d=!1,c=0,u=0,f=!1,l=()=>{for(let k of t)k.state==="pending"&&(k.state="idle",k.settle?.reject(new oe));for(let k of n.splice(0))k.settle.reject(new oe)},g=()=>{d||(d=!0,queueMicrotask(()=>{d=!1,R()}))},p=(k,O)=>{k.state="idle";let I=k.settle;k.ask=void 0,k.settle=void 0,O instanceof Error?I?.reject(O):I?.resolve(O)},m=async(k,O)=>{let I=xo(r.version,k.map(v=>v.ask),O),D;u++;try{D=await r.request({method:"POST",url:"/composite",body:JSON.stringify(I),headers:{"Content-Type":"application/json"}})}catch(v){if(Bo(v)){s="single";for(let L of k)L.state="pending";n.unshift(...O);return}let T=new Error(N(v));for(let L of k)p(L,T);for(let L of O)L.settle.reject(T);return}let M=_o(D);if(!M){s="single";for(let v of k)v.state="pending";n.unshift(...O);return}let H=0;if(k.forEach((v,T)=>{let L=M.get(`q${T}`);if(L&&!L.ok&&L.halted){H++,v.state="pending";return}if(!L){p(v,new Error("The org gave no answer to this query of the composite"));return}if(!L.ok){p(v,new Error(L.refused));return}let xe=$t(L.body);p(v,xe??new Error(`The org answered a query with status ${L.status} and no page`))}),H>0){let v=k.length-H;v===0?s="single":o=Math.min(o,v)}O.forEach((v,T)=>{let L=M.get(`d${T}`);L?L.ok?v.settle.resolve(L.status===304?{notModified:!0}:{body:L.body}):v.settle.reject(new Error(L.refused)):v.settle.reject(new Error("The org gave no answer to this describe of the composite"))})},b=async(k,O)=>{for(let I of k){let D=I.ask;u++;try{let M=D.kind==="first"?await r.query(D.soql,{scanAll:D.scanAll}):await r.queryMore(D.path);p(I,$t(M)??new Error("The org answered a query with no page"))}catch(M){p(I,new Error(N(M)))}}for(let I of O){u++;try{let D=await r.request({method:"GET",url:`/services/data/v${r.version}/${I.path}`,...I.headers?{headers:I.headers}:{}}),M=I.headers?.[ar]!==void 0&&(D==null||D==="");I.settle.resolve(M?{notModified:!0}:{body:D})}catch(D){I.settle.reject(new Error(N(D)))}}},h=async(k,O,I)=>{try{s==="composite"?await m(k,O):await b(k,O)}catch(D){let M=new Error(N(D));for(let H of k)H.state==="sent"&&p(H,M);for(let H of O)H.settle.reject(M)}finally{i--,I||(a=!1),g(),_()}},R=()=>{if(e?.aborted){l();return}for(;;){if(a)return;let k=[...t],O=k.filter(T=>T.state==="pending").sort((T,L)=>T.order-L.order);if(!(O.length>0&&!k.some(T=>T.state==="idle"))&&n.length===0)return;let D=O.slice(0,o),M=qt-D.length,H=s==="composite"&&n.length===0&&D.length>0&&D.every(T=>T.oneRow&&T.ask?.kind==="first");if(i>=(H?Ut:1))return;let v=n.splice(0,M);if(D.length===0&&v.length===0)return;for(let T of D)T.state="sent";i++,H||(a=!0),h(D,v,H)}},S=()=>{f=!1,g()},j=()=>{f||e===void 0||e.aborted||(e.addEventListener("abort",S,{once:!0}),f=!0)},_=()=>{!f||i>0||t.size>0||n.length>0||(e?.removeEventListener("abort",S),f=!1)},U=(k,O)=>t.has(k)?k.state!=="idle"?Promise.reject(new Error("A read asks one page at a time.")):e?.aborted?Promise.reject(new oe):new Promise((I,D)=>{k.ask=O,k.settle={resolve:I,reject:D},k.state="pending",k.order=++c,g()}):Promise.reject(new Error("This read is closed."));return{lane(k){let O={state:"idle",order:0,oneRow:k?.oneRow===!0};return t.add(O),j(),{query:(I,D)=>U(O,{kind:"first",soql:I,scanAll:D?.scanAll===!0}),queryMore:I=>{let D;try{D=Fo(I)}catch(M){return Promise.reject(M instanceof Error?M:new Error(String(M)))}return U(O,{kind:"next",path:D})},close(){t.delete(O)&&(O.state==="pending"&&p(O,new Error("This read is closed.")),g(),_())}}},describe(k,O){return e?.aborted?Promise.reject(new oe):new Promise((I,D)=>{let M=K(k),H;if(O!==void 0){let v=Date.parse(O);if(!Number.isFinite(v))throw new Error(`Not a date: ${O}`);H={[ar]:new Date(v).toUTCString()}}j(),n.push({path:`sobjects/${M}/describe`,...H?{headers:H}:{},settle:{resolve:I,reject:D}}),g()})},async tooling(k){if(e?.aborted)throw new oe;u++;let O;try{O=await r.request({method:"GET",url:`/services/data/v${r.version}/tooling/query?q=${encodeURIComponent(k)}`})}catch(D){throw new Error(N(D))}let I=$t(O);if(!I)throw new Error("The org answered a Tooling API query with no page");return I},calls:()=>u}}import{createReadStream as $o}from"node:fs";import{appendFile as qo,mkdir as Uo,rm as zo,writeFile as Ho}from"node:fs/promises";import*as he from"node:path";import{createInterface as Jo}from"node:readline";var Qo="The org stopped answering before it said the read was done: some of its records were not read.",dr=384,Wo=448;function cr(r){let e=typeof r=="number"?r:Date.parse(r);if(!Number.isFinite(e))throw new Error(`Not a date: ${String(r)}`);let t=e-(e%1e3+1e3)%1e3;return new Date(t).toISOString().replace(/\.\d{3}Z$/,"Z")}function zt(r){let e=Date.parse(r);if(!Number.isFinite(e))throw new Error(`Not a date: ${r}`);return cr(e-on)}function lr(r,e){return[...new Set([...r,...e.map(F)])].join(", ")}function Ht(r,e,t,n){let o=K(r),s=[n,e==="scanAllLive"?"IsDeleted = false":void 0].filter(i=>i!==void 0);return{objectApiName:o,soql:`SELECT ${t} FROM ${o}${s.length>0?` WHERE ${s.join(" AND ")}`:""}`,scanAll:e==="scanAllLive"}}function Vo(r){let e=K(r);return{objectApiName:e,soql:`SELECT SystemModstamp FROM ${e} ORDER BY SystemModstamp DESC LIMIT 1`,scanAll:!0}}var Ko=["Id","SystemModstamp","CreatedDate","LastModifiedDate","LastModifiedById"],Go=["Id","SystemModstamp","CreatedDate"];function Yo(r,e,t,n=[]){return Ht(r,e,lr(Ko,n),`SystemModstamp >= ${zt(t)}`)}function Zo(r,e,t=[]){let n=K(r);return{objectApiName:n,soql:`SELECT ${lr(Go,t)} FROM ${n} WHERE IsDeleted = true AND SystemModstamp >= ${zt(e)}`,scanAll:!0}}function Xo(r,e){return Ht(r,e,"COUNT()")}function Gi(r,e){let t=K(r);return{objectApiName:t,soql:`SELECT Id FROM ${t} WHERE IsDeleted = true AND SystemModstamp < ${cr(e)}`,scanAll:!0}}function Yi(r,e){return Ht(r,e,"Id")}async function es(r,e,t){let n,o,s={query:async a=>{let d=await r.query(a,{scanAll:e.scanAll});return n=d,o=d.totalSize,d},queryMore:async a=>(n=await r.queryMore(a),n)},i=0;try{for await(let a of rn(s,e.soql))await t(a),i+=a.length}catch(a){if(a instanceof oe)throw a;return{objectApiName:e.objectApiName,read:!1,rows:i,reason:N(a)}}return n?.done!==!0?{objectApiName:e.objectApiName,read:!1,rows:i,reason:Qo}:{objectApiName:e.objectApiName,read:!0,rows:i,...o!==void 0?{totalSize:o}:{}}}async function Jt(r,e,t,n,o={}){let s=o.oneRow===!0,i=new Array(e.length),a=async l=>{let g=e.slice(l,l+me),p=g.map(()=>r.lane({oneRow:s})),m=await Promise.allSettled(g.map(async(b,h)=>{let R=p[h];try{return await es(R,b,S=>t(l+h,S))}finally{R.close()}}));for(let[b,h]of m.entries()){if(h.status==="rejected")throw h.reason instanceof Error?h.reason:new Error(String(h.reason));i[l+b]=h.value}},d=0,c=async()=>{for(;d<e.length;){if(n?.aborted)throw new oe;let l=d;d+=me,await a(l)}},u=Math.ceil(e.length/me),f=await Promise.allSettled(Array.from({length:Math.min(s?Ut:1,u)},c));for(let l of f)if(l.status==="rejected")throw l.reason instanceof Error?l.reason:new Error(String(l.reason));if(n?.aborted)throw new oe;return i}function ts(r){return`${JSON.stringify(Object.fromEntries(Object.entries(r).filter(([e])=>e!=="attributes")))}
7
+ import{o as ht}from"./chunk-LPBMBW3O.mjs";import{F as ze,d as pt,x as mt}from"./chunk-IFETCRWE.mjs";import{a as dn,d as cn,e as ln,g as un,h as fn,i as gn,j as pn,k as gt}from"./chunk-SAR5622P.mjs";import{C as sn,v as on}from"./chunk-EQNW3UC2.mjs";import{a as Ue,b as re,d as ee,e as an,f as ft,h as z}from"./chunk-GSKCGQIP.mjs";import{c as rn}from"./chunk-EADHKH3A.mjs";import{e as mn,h as hn,i as yn}from"./chunk-L77FJZEP.mjs";import{ca as Oe,da as ut,fa as Ee,ia as qe}from"./chunk-A527W53V.mjs";import{h as F}from"./chunk-TZE3Y7IQ.mjs";import{b as N}from"./chunk-CA5NAXSU.mjs";import{Bb as Xt,Gb as en,Hb as fe,Lb as $e,Ob as ke,Pb as ct,Rb as lt,Sb as tn,Wb as K,qc as nn}from"./chunk-TTFDUKUS.mjs";import{b as x,e as ue,f as $,i as Ae,k as X,l as W,o as Be,s as Fe,v as Zt}from"./chunk-7EANH5PY.mjs";var He=class{activeJobs=new Map;maxConcurrentJobs;maxCompletedJobs=50;constructor(e=5){this.maxConcurrentJobs=e}registerJob(e){this.activeJobs.set(e.id,e)}updateJobState(e,t){let n=this.activeJobs.get(e);return n?(n.state=t,(t==="JobComplete"||t==="Failed"||t==="Aborted")&&this.purgeCompletedJobs(),!0):!1}updateJobCounts(e,t,n){let o=this.activeJobs.get(e);return o?(o.numberRecordsProcessed=t,o.numberRecordsFailed=n,!0):!1}updateTotalRecords(e,t){let n=this.activeJobs.get(e);return n?(n.totalRecords=t,!0):!1}getJob(e){return this.activeJobs.get(e)}getActiveJobs(){return Array.from(this.activeJobs.values()).filter(e=>e.state==="UploadComplete"||e.state==="InProgress")}getCompletedJobs(){return Array.from(this.activeJobs.values()).filter(e=>e.state==="JobComplete"||e.state==="Failed"||e.state==="Aborted")}canStartNewJob(){return this.getActiveJobs().length<this.maxConcurrentJobs}removeJob(e){return this.activeJobs.delete(e)}get totalJobs(){return this.activeJobs.size}purgeCompletedJobs(){let e=Array.from(this.activeJobs.entries()).filter(([,t])=>["JobComplete","Failed","Aborted"].includes(t.state));if(e.length>this.maxCompletedJobs){let t=e.slice(0,e.length-this.maxCompletedJobs);for(let[n]of t)this.activeJobs.delete(n)}}clear(){this.activeJobs.clear()}};function Rr(r,e){let t=gt(r,e);if(t.state==="Open")throw new Error(`Bulk API job ${r||"(no id)"} is still open after its close was sent`);return{state:t.state,...t.numberRecordsProcessed!==void 0?{numberRecordsProcessed:t.numberRecordsProcessed}:{},...t.errorMessage?{errorMessage:t.errorMessage}:{}}}function Je(r){return{bulk2:{createJob:e=>{let t=r.bulk2.createJob(e);return{get id(){return t.id},open:async()=>{await t.open()},uploadData:n=>t.uploadData(n),close:()=>t.close(),abort:()=>t.abort(),check:async()=>Rr(mn(t)??"",await t.check()),getAllResults:()=>t.getAllResults()}},job:(e,{id:t})=>{let n=r.bulk2.job(e,{id:t});return{check:async()=>gt(t,await n.check()),getSuccessfulResults:()=>n.getSuccessfulResults(),getAllResults:()=>n.getAllResults(),abort:()=>n.abort()}}}}}var bn=100,yt=2e3,wn=20,Rn=20,Sr=W({name:x(),label:x(),type:x(),createable:$().optional(),updateable:$().optional(),nillable:$().optional(),defaultedOnCreate:$().optional(),aggregatable:$().optional(),groupable:$().optional(),filterable:$().optional(),nameField:$().optional(),autoNumber:$().optional(),calculated:$().optional(),referenceTo:X(x()).optional()}).loose(),de=W({name:x(),label:x(),queryable:$().optional(),updateable:$().optional(),deletable:$().optional(),fields:X(Sr),childRelationships:X(W({childSObject:x(),field:x(),cascadeDelete:$().optional(),restrictedDelete:$().optional()}).loose()).optional()}).loose(),Ar=Fe(x(),Ae()),kr=W({k:Be([x(),ue(),$()]).nullable(),n:ue().int().nonnegative()}).loose();function Sn(r){return(r.createable===!0||r.updateable===!0)&&r.type!=="boolean"}function Or(r){return r.groupable===!0&&(Sn(r)||r.nameField===!0)}function Er(r,e){return e.createable===!0&&e.nillable===!1&&e.defaultedOnCreate!==!0||Xt(r,e.name)}function Qe(r,e,t){let n=N(t);r.some(o=>o.check===e&&o.message===n)||r.push({check:e,message:n})}async function Dr(r,e,t,n){let o=new Map,s=[],i=[],a=(f,l)=>{s.push({fieldApiName:f.name,label:f.label,reason:l})},d=t.filter(f=>f.aggregatable===!0),c=t.filter(f=>f.aggregatable!==!0&&f.filterable===!0);for(let f of t)f.aggregatable!==!0&&f.filterable!==!0&&a(f,"not-countable");if(n===0)for(let f of[...d,...c])o.set(f.name,0);else{for(let f=0;f<d.length;f+=bn){let l=d.slice(f,f+bn);try{let g=l.map(b=>`COUNT(${F(b.name)})`).join(", "),p=await r.query(`SELECT ${g} FROM ${e}`),m=Ar.parse(p.records[0]??{});l.forEach((b,h)=>{let R=m[`expr${h}`];if(typeof R!="number")throw new Error(`The org answered no count for ${e}.${b.name}.`);o.set(b.name,R)})}catch(g){Qe(i,"fill",g);for(let p of l)o.delete(p.name),a(p,"refused")}}for(let[f,l]of c.entries()){if(f>=Rn){a(l,"query-budget");continue}try{let g=await r.query(`SELECT COUNT() FROM ${e} WHERE ${F(l.name)} != null`);o.set(l.name,g.totalSize)}catch(g){Qe(i,"fill",g),a(l,"refused")}}}return{fields:t.filter(f=>o.has(f.name)).map(f=>({fieldApiName:f.name,label:f.label,filled:o.get(f.name)??0,required:Er(e,f)})).sort((f,l)=>f.filled-l.filled||f.fieldApiName.localeCompare(l.fieldApiName)),unmeasured:s,errors:i}}async function Ir(r,e,t,n,o){let s=[],i=n?t.find(d=>d.name.toLowerCase()===n.toLowerCase()):t.find(d=>d.name==="Email")??t.find(d=>d.nameField===!0);if(!i)return n&&s.push({check:"duplicates",message:`${e} has no field ${n} the org can group records by.`}),{duplicates:null,errors:s};let a={keyField:i.name,keyLabel:i.label,groups:[],groupCount:0,recordCount:0,truncated:!1};if(o===0)return{duplicates:a,errors:s};try{let d=await Pr(r,e,i.name),c=d.rows.map(u=>({value:String(u.value),count:u.count}));return{duplicates:{...a,groups:c.slice(0,wn),groupCount:c.length,recordCount:c.reduce((u,f)=>u+f.count,0),truncated:d.truncated},errors:s}}catch(d){return Qe(s,"duplicates",d),{duplicates:null,errors:s}}}async function Pr(r,e,t){let n=F(t),o=await r.query(`SELECT ${n} k, COUNT(Id) n FROM ${e} WHERE ${n} != null GROUP BY ${n} HAVING COUNT(Id) > 1 ORDER BY COUNT(Id) DESC LIMIT ${yt}`),s=[];for(let i of o.records){let a=kr.safeParse(i);!a.success||a.data.k===null||s.push({value:a.data.k,count:a.data.n})}return{rows:s,truncated:o.records.length>=yt}}async function Cr(r,e,t,n,o){let s=[];if(!t.some(i=>i.name==="LastModifiedDate"&&i.filterable===!0))return{stale:null,errors:s};if(o===0)return{stale:{days:n,records:0},errors:s};try{let i=await r.query(`SELECT COUNT() FROM ${e} WHERE LastModifiedDate < LAST_N_DAYS:${n}`);return{stale:{days:n,records:i.totalSize},errors:s}}catch(i){return Qe(s,"stale",i),{stale:null,errors:s}}}async function Nr(r,e,t){let n,o,s;try{if(n=de.parse(await r.describe(F(e.objectApiName))),o=F(n.name),n.queryable===!1)throw new Error(`${o} cannot be queried.`);s=(await r.query(`SELECT COUNT() FROM ${o}`)).totalSize}catch(u){return{status:"failed",objectApiName:e.objectApiName,message:N(u)}}let i=n.fields.filter(Or).sort((u,f)=>u.label.localeCompare(f.label)),[a,d,c]=await Promise.all([Dr(r,o,n.fields.filter(Sn),s),Ir(r,o,i,e.duplicateKey,s),Cr(r,o,n.fields,t,s)]);return{status:"scanned",objectApiName:e.objectApiName,label:n.label,totalRecords:s,fields:a.fields,unmeasured:a.unmeasured,duplicates:d.duplicates,stale:c.stale,keyFields:i.map(u=>({fieldApiName:u.name,label:u.label})),errors:[...a.errors,...d.errors,...c.errors]}}async function Ps(r,e,t=()=>new Date){if(!Number.isInteger(e.staleDays)||e.staleDays<1)throw new Error(`A staleness threshold is a whole number of days, not ${e.staleDays}.`);let n=t().toISOString(),o=[];for(let s of e.objects)o.push(await Nr(r,s,e.staleDays));return{orgId:e.orgId,staleDays:e.staleDays,scannedAt:n,bounds:{duplicateGroupLimit:yt,duplicateSample:wn,singleFieldQueries:Rn},objects:o}}var wt=1e4,Ve=5e4,An="DELETE_FAILED",Rt="UNABLE_TO_LOCK_ROW",kn=3,jr=2e3,On="FEATURENOTENABLED",St="ContentVersion",En="ContentDocument",At=new Set([St,En]);async function De(r,e,t,n,o="delete"){let s=!1,i={},a=0,d=0,c=(g,p)=>(d+=g,p()),u={bulk2:{createJob:g=>{let p=r.bulk2.createJob(g);return{get id(){return p.id},open:()=>c(1,()=>p.open()),uploadData:m=>c(1,()=>p.uploadData(m)),close:async()=>{await c(1,()=>p.close()),s=!0},abort:()=>c(1,()=>p.abort()),check:async()=>{let m=await c(1,()=>p.check());return i={state:m.state,message:m.errorMessage},m},getAllResults:async()=>{let m=await c(yn,()=>p.getAllResults());return a=Array.isArray(m)?m.length:(m.successfulResults?.length??0)+(m.failedResults?.length??0),m}}}}},f;try{f=await new hn().executeBulk({connection:u,bulkManager:new He(1),...n?{signal:n}:{}},e,o,t.map(g=>({Id:g})))}catch(g){if(!s){let p=g?.errorCode;return{kind:"untouched",reason:N(g),...typeof p=="string"&&p!==""?{code:p}:{},requests:d}}throw g}if(f.aborted)return{kind:"aborted",requests:d};if(i.state!=="JobComplete"&&a===0)return{kind:"untouched",reason:i.message||`job ${i.state??"not complete"}`,requests:d};let l=new Map(f.outcomes.map(g=>[g.recordIndex,g]));return{kind:"answered",requests:d,rows:t.map((g,p)=>{let m=l.get(p);return m?.success?{success:!0}:{success:!1,error:m?.error??"The job gave no result for it."}})}}function $s(r,e){let t=Je(r);return{...Ue(r,e),queryDeleted:async n=>({records:(await r.query(n,{scanAll:!0})).records}),bulkDestroy:(n,o,s)=>De(t,n,o,s),bulkHardDestroy:(n,o,s)=>De(t,n,o,s,"hardDelete")}}var kt=W({success:$(),errors:X(Be([W({statusCode:x().optional(),errorCode:x().optional(),message:x().optional()}).loose(),x()])).optional()}).loose();function ge(r){return r.slice(0,15)}function We(r){return typeof r=="string"?void 0:r.statusCode??r.errorCode}function Ot(r){if(typeof r=="string")return r;let e=We(r),t=r.message??"";return e&&t?`${e}: ${t}`:e||t||"The org gave no reason."}function be(r){return async e=>(await r.query(e)).records.filter(n=>typeof n=="object"&&n!==null)}function vr(r){return new Promise(e=>setTimeout(e,r))}function Mr(r){let e=jr*2**r;return Math.floor(e/2+Math.random()*(e/2))}async function Dn(r,e,t,n){let o=[...t];for(let s=0;s<kn;s++){let i=o.flatMap((d,c)=>d.kind==="refused"&&d.locked===!0?[c]:[]);if(i.length===0||n.stopped?.()===!0||(await(n.wait??vr)(Mr(s)),n.stopped?.()===!0))break;let a=await e(i.map(d=>r[d]));if(a===void 0)break;i.forEach((d,c)=>{let u=a[c];u&&(o[d]={...u,lockResends:s+1})})}return o}async function Et(r,e,t,n={}){if(e===St)return $r(r,t,n);let o=s=>Lr(r,e,s);return Dn(t,o,await o(t),n)}async function Lr(r,e,t){let n;try{n=await r.destroy(e,[...t])}catch(s){let i=N(s);return t.map(()=>({kind:"refused",reason:i,dependency:!1}))}let o=Array.isArray(n)?n:[n];return t.map((s,i)=>{let a=kt.safeParse(o[i]);if(a.success&&a.data.success)return{kind:"deleted"};let d=a.success?a.data.errors??[]:[];if(d.some(u=>We(u)==="ENTITY_IS_DELETED"))return{kind:"gone"};let c=d.length>0&&d.every(u=>We(u)===Rt);return{kind:"refused",reason:d.length>0?Ot(d[0]):"The org gave no reason.",dependency:d.some(u=>We(u)===An),...c?{locked:!0}:{}}})}async function Tr(r,e,t,n="recycle",o={}){let s=n==="hard"?r.bulkHardDestroy?.bind(r):r.bulkDestroy?.bind(r);if(s===void 0)return n==="hard"?{hardRefused:xr}:"untouched";let i=async d=>{let c;try{c=await s(e,d,o.signal)}catch(f){let l=N(f);return d.map(()=>({kind:"refused",reason:l,dependency:!1}))}if(c.kind==="aborted")return"aborted";if(c.kind==="untouched"){if(n!=="hard")return"untouched";if(c.code===On)return{hardRefused:_r(c.reason)};let f=`Not deleted for good: the job was not handed over \u2014 ${c.reason}`;return d.map(()=>({kind:"refused",reason:f,dependency:!1}))}let{rows:u}=c;return d.map((f,l)=>{let g=u[l];if(g?.success===!0)return{kind:"deleted"};let{code:p,message:m}=Fr(g?.error??"");return p==="ENTITY_IS_DELETED"?{kind:"gone"}:{kind:"refused",reason:p&&m?`${p}: ${m}`:g?.error||p||m||"The org gave no reason.",dependency:p===An,...p===Rt?{locked:!0}:{}}})},a=await i(t);return Array.isArray(a)?Dn(t,async d=>{let c=await i(d);return Array.isArray(c)?c:void 0},a,o):a}var xr="Records cannot be deleted for good through this connection: nothing was sent.";function _r(r){return`The user SandForge connects as may not delete records for good in this org: Salesforce refused the job before it held a record (${On}: ${r}). Nothing was deleted for good, and nothing was sent to the recycle bin instead.`}var Br="A file is never deleted for good: that takes a Bulk API job, which no file was ever sent by. Not sent.";function Fr(r){let e=/^([A-Z][A-Z0-9_]*):([\s\S]*?)(?::(?:--|[\w.,]+))?$/.exec(r.trim());return e?{code:e[1],message:e[2].trim()}:{message:r.trim()}}async function $r(r,e,t){let n;try{n=await z(r,St,["ContentDocumentId"],e)}catch(d){let c=N(d);return e.map(()=>({kind:"refused",reason:c,dependency:!1}))}let o=new Map;for(let d of n)typeof d.Id=="string"&&typeof d.ContentDocumentId=="string"&&o.set(ge(d.Id),d.ContentDocumentId);let s=[...new Set(o.values())],i=s.length>0?await Et(r,En,s,t):[],a=new Map(s.map((d,c)=>[d,i[c]]));return e.map(d=>{let c=o.get(ge(d));return c===void 0?{kind:"gone"}:a.get(c)??{kind:"refused",reason:"The org gave no answer for its document.",dependency:!1}})}function In(r){let e=[];for(let t=0;t<r.length;t+=re)e.push({ids:r.slice(t,t+re),byJob:!1});return e}function Pn(r,e,t,n="recycle"){return At.has(e)?!1:n==="hard"||r.bulkDestroy!==void 0&&t>=wt}async function qr(r,e,t,n="recycle"){let o=[],s=!At.has(e)&&(n==="hard"||r.bulkDestroy!==void 0),i=d=>{if(d.length===0)return;if(!s||n!=="hard"&&d.length<wt){o.push(...In(d));return}let c=Math.ceil(d.length/Math.ceil(d.length/Ve));for(let u=0;u<d.length;u+=c)o.push({ids:d.slice(u,u+c),byJob:!0})};if(!$e(e)||t.length===0)return i(t),o;let a=new Set;try{a=new Set([...await Ee(be(r),t)].map(ge))}catch{}return i(t.filter(d=>!a.has(ge(d)))),i(t.filter(d=>a.has(ge(d)))),o}function Cn(r){return{objectApiName:r,op:"delete"}}async function Nn(r,e,t,n,o){let s={stopped:o.stopped,...o.wait?{wait:o.wait}:{}},{stopped:i}=await pn(t,{key:Cn(e),sizes:n.sizes,allowance:n.allowance,beforeEachSend:()=>o.stopped()?"stop":void 0,send:async a=>({answers:await Et(r,e,a,s)}),limited:a=>a?.kind==="refused"?nn([a.reason]):void 0,settle:(a,d,c,u)=>{let f=[],l=[];a.forEach((g,p)=>{if(c.has(p))return;let m=d[p]??{kind:"refused",reason:"The org gave no answer for it.",dependency:!1},b=u.get(p);f.push(g),l.push(b!==void 0&&m.kind==="refused"?{...m,dependency:!1,limit:b}:m)}),f.length>0&&o.settle(f,l)}});return i!==void 0}function Dt(r,e){let t=Cn(r),n=e.sizes.report(t);if(!n)return[];let o=[];return n.rows+n.alone+n.notSplit+n.keptWhole>0&&o.push(un(n)),n.notSplit>0&&o.push(fn(n.notSplit,gn(e.allowance,t),"removal")),n.keptWhole>0?o.push(ln):n.alone>0&&o.push(cn),o}function jn(r){let e=0,t=0,n=0,o=0;for(let i of r)e++,i==="deleted"?t++:i==="gone"?n++:o++;if(e===0)return[];let s=[t>0?`${t} deleted`:"",n>0?`${n} already gone`:"",o>0?`${o} still refused`:""].filter(Boolean);return[`The org could not lock ${e} record(s) (${Rt}), each sent again up to ${kn} times, a wait before each: ${s.join(", ")}.`]}async function vn(r,e,t,n){let o=n.mode??"recycle";if(o==="hard"&&At.has(e))return t.length>0&&n.settle(t,t.map(()=>({kind:"refused",reason:Br,dependency:!1}))),{stopped:!1};let s=n.wait?{wait:n.wait}:{},i=await qr(r,e,t,o);for(let a=i.shift();a!==void 0;a=i.shift()){let{ids:d,byJob:c}=a;if(n.stopped())return{stopped:!0};if(await n.prepare?.(d),!c){if(await Nn(r,e,d,n.splitting,{stopped:n.stopped,settle:n.settle,...s}))return{stopped:!0};continue}let u=await Tr(r,e,d,o,{stopped:n.stopped,...s,...n.signal?{signal:n.signal}:{}});if(u==="aborted")return{stopped:!0};if(u==="untouched"){i.unshift(...In(d));continue}if(!Array.isArray(u))return{stopped:!0,hardRefused:u.hardRefused};n.settle(d,u)}return{stopped:!1}}async function Mn(r,e){for(let t=0,n=!0;n;t++){n=!1;for(let o of r){let s=e.idsOf(o,t);if(s.length===0)continue;if(e.stopped())return!0;let i=e.deleted(o);if(await e.send(o,s,t))return!0;e.deleted(o)>i&&(n=!0)}}return!1}async function Ke(r,e){let t=new Set(e.map(i=>i.objectApiName)),n=new Map;for(let{objectApiName:i}of e){let a;try{a=(de.parse(await r.describe(i)).childRelationships??[]).map(c=>c.childSObject)}catch{continue}for(let d of a){if(d===i||!t.has(d))continue;let c=n.get(d)??new Set;c.add(i),n.set(d,c)}}let o=[...e],s=[];for(;o.length>0;){let i=o.findIndex(a=>!o.some(d=>d!==a&&n.get(d.objectApiName)?.has(a.objectApiName)));s.push(...o.splice(i>=0?i:0,1))}return s}async function It(r,e,t){if(r.length===0)return{gone:[],unchecked:[]};let n;try{n=await e(r)}catch(i){return{gone:[],unchecked:[...r],failure:N(i)}}let o=new Set(n.map(i=>ge(String(i.Id)))),s=r.filter(i=>!o.has(ge(i)));return{gone:s.filter(t),unchecked:s.filter(i=>!t(i))}}function Ur(r){return r.filter(e=>Oe[e]!==void 0&&!ut.has(e))}async function Pt(r,e,t,n,o,s){let i=be(r),a=[];for(let{objectApiName:d}of e){let c=Oe[d];if(!c||ut.has(d))continue;let u;for await(let f of t.pages(d)){let l=f.filter(R=>n(d,R));if(l.length===0)continue;if(o())return{drafted:a,cancelled:!0};u??=await qe(i,c);let g=u,p=g?.draft;if(!g||!p)break;let m=await s(d,l),b;try{b=await z(r,d,["Status"],l)}catch{continue}let h=b.filter(R=>typeof R.Id=="string"&&!m.has(R.Id.slice(0,15))).filter(R=>{let S=g.categoryOf.get(String(R.Status));return S!==void 0&&S!=="Draft"}).map(R=>({objectApiName:d,id:String(R.Id),draft:p,status:String(R.Status)}));for(let R=0;R<h.length;R+=re){if(o())return{drafted:a,cancelled:!0};let S=h.slice(R,R+re);a.push(...S);try{await r.update(d,S.map(({id:j})=>({Id:j,Status:p})))}catch{}}}}return{drafted:a,cancelled:!1}}function Qs(r,e,t,n){if(t)return`${r} ${t.id}: ${e}`;let o=n.filter(s=>s.objectApiName===r).map(s=>`${s.id} (${s.status})`);return o.length>0?`${r}: ${e} Set to Draft, with the status each had: ${o.join(", ")}.`:`${r}: ${e}`}async function Ln(r,e,t){let n=[...new Set(e.map(o=>o.objectApiName))];for(let o of n){let s=e.filter(u=>u.objectApiName===o),i=new Map(s.map(u=>[u.id.slice(0,15),u])),a=s.map(u=>u.id),d;try{d=await z(r,o,["Status"],a)}catch(u){t.note(o,`Status set to ${s[0].draft} for the delete, and not read back to be restored: ${N(u)}`,!0);continue}let c=d.flatMap(u=>{let f=typeof u.Id=="string"?i.get(u.Id.slice(0,15)):void 0;return f&&u.Status===f.draft?[f]:[]});for(let u=0;u<c.length;u+=re){let f=c.slice(u,u+re),l;try{l=await r.update(o,f.map(({id:p,status:m})=>({Id:p,Status:m})))}catch(p){l=f.map(()=>({success:!1,errors:[N(p)]}))}let g=Array.isArray(l)?l:[l];f.forEach(({draft:p,status:m},b)=>{let h=kt.safeParse(g[b]);if(h.success&&h.data.success){t.note(o,`Status set to ${p} for the delete, then back to ${m}.`,!1,f[b]);return}let R=h.success?h.data.errors??[]:[],S=R.length>0?Ot(R[0]):"The org gave no reason.";t.note(o,`Status set to ${p} for the delete, and left there: the org refused ${m} back \u2014 ${S}`,!0,f[b])})}}}var Re="DuplicateRecordSet",zr="DuplicateRecordItem",Ge=2e3,Hr=999,Jr=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function V(r){return r.slice(0,15)}function Tn(r){return new Date(r).toISOString().replace(/\.\d{3}Z$/,"Z")}function Ct(r){return typeof r=="string"?Date.parse(r):Number.NaN}async function xn(r,e){return(await Qr(r,e)).map(t=>({id:t.id,modified:Wr(t,e)}))}async function Qr(r,e){if(!Number.isFinite(e.start)||!Number.isFinite(e.end)||!Jr.test(e.user))return[];let t;try{let d=await r.query(`SELECT Id, CreatedDate, LastModifiedDate, LastModifiedById FROM ${Re} WHERE CreatedDate >= ${Tn(e.start-2e3)} AND CreatedDate <= ${Tn(e.end+6e4)} LIMIT ${Ge}`);if(d.records.length>=Ge)return[];t=d.records.filter(c=>typeof c=="object"&&c!==null)}catch{return[]}let n=t.flatMap(d=>typeof d.Id=="string"?[d.Id]:[]);if(n.length===0)return[];let o=new Set,s=new Map,i=new Map;try{for(let d of ee(n)){let c=await r.query(`SELECT Id, RecordId, DuplicateRecordSetId, CreatedDate FROM ${zr} WHERE DuplicateRecordSetId IN (${d}) LIMIT ${Ge}`);if(c.records.length>=Ge)return[];for(let u of c.records){let f=u??{},l=f.DuplicateRecordSetId,g=f.RecordId;if(typeof l!="string")continue;let p=Ct(f.CreatedDate);Number.isFinite(p)&&!(p<=(i.get(V(l))??Number.NaN))&&i.set(V(l),p),typeof g!="string"||!e.has(V(g))?o.add(V(l)):s.set(V(l),[...s.get(V(l))??[],V(g)])}}}catch{return[]}let a=V(e.user);return t.flatMap(d=>typeof d.Id=="string"&&!o.has(V(d.Id))&&(s.has(V(d.Id))||typeof d.LastModifiedById=="string"&&V(d.LastModifiedById)===a)?[{id:d.Id,created:Ct(d.CreatedDate),modified:Ct(d.LastModifiedDate),...typeof d.LastModifiedById=="string"?{modifiedBy:d.LastModifiedById}:{},names:s.get(V(d.Id))??[],...i.has(V(d.Id))?{itemsMade:i.get(V(d.Id))}:{}}]:[])}function Wr(r,e){if((r.modifiedBy!==void 0?V(r.modifiedBy):"")===V(e.user)&&r.modified<=e.end+6e4)return Math.min(r.modified,e.end);let n=e.end+6e4;return r.names.length>0&&r.created<=n&&r.modified<=n&&(r.modified===r.created||r.modified<=(r.itemsMade??Number.NaN)+Hr)?Math.min(r.modified,e.end):r.modified}async function _n(r,e,t,n="recycle"){let o=F(e),s=new Set;try{for(let i of ee(t)){let a=await r.queryDeleted(`SELECT Id FROM ${o} WHERE Id IN (${i}) AND IsDeleted = true`);for(let d of a.records){let c=d?.Id;typeof c=="string"&&s.add(c.slice(0,15))}}}catch(i){return{error:N(i)}}return{deleted:s,inBin:n!=="hard"}}var Vr=/__kav$/i;function Ie(r){return Vr.test(r)}function Fn(r){return r.replace(/v$/i,"")}var Nt="Kept: its article holds a version the run did not write \u2014 a draft begun on it, or a version published since \u2014 which deleting the article would take with it. A removal that takes what changed since the run takes it too.",Kr={statusCode:"ENTITY_IS_DELETED",message:"The version is no longer in the org: it went with its article."},Bn=" AND IsLatestVersion = false AND PublishStatus = 'Archived'",Gr="An article version is deleted through its article, over REST.",Yr={success:!1,errors:[{message:"The org gave no reason."}]};function te(r){return r.slice(0,15)}function $n(r,e){let t=r.bulkDestroy?.bind(r);return{query:n=>r.query(n),queryDeleted:n=>r.queryDeleted(n),update:(n,o)=>r.update(n,o),serverTime:()=>r.serverTime(),userId:()=>r.userId(),describeGlobal:()=>r.describeGlobal(),describe:n=>Ie(n)?Zr(r,n):r.describe(n),destroy:(n,o)=>Ie(n)?Xr(r,n,o,e):r.destroy(n,o),...t?{bulkDestroy:(n,o,s)=>Ie(n)?Promise.resolve({kind:"untouched",reason:Gr,requests:0}):t(n,o,s)}:{}}}async function Zr(r,e){let t=await r.describe(e);if(typeof t!="object"||t===null)return t;let n;try{n=(await r.describe(Fn(e)))?.deletable}catch{n=void 0}let o={...t};return delete o.deletable,typeof n=="boolean"?{...o,deletable:n}:o}async function qn(r,e,t){let n=F(e),o=new Map,s=new Map,i=(d,c)=>{for(let u of d){let f=u;if(typeof f?.Id!="string"||typeof f.KnowledgeArticleId!="string")continue;c?.set(te(f.Id),f.KnowledgeArticleId);let l=te(f.KnowledgeArticleId),g=s.get(l)??new Set;g.add(te(f.Id)),s.set(l,g)}};for(let d of["",Bn])for(let c of ee(t)){let u=await r.query(`SELECT Id, KnowledgeArticleId FROM ${n} WHERE Id IN (${c})${d}`);i(u.records,o)}let a=[...new Set(o.values())];for(let d of["",Bn])for(let c of ee(a)){let u=await r.query(`SELECT Id, KnowledgeArticleId FROM ${n} WHERE KnowledgeArticleId IN (${c})${d}`);i(u.records)}return{articleOf:o,versions:s}}function Un({articleOf:r,versions:e},t,n){if(n.includeChanged)return new Set;let o=new Set(t.map(te)),s=i=>[...e.get(i)??[]].some(a=>!o.has(a));return new Set([...r.values()].map(te).filter(s))}async function zn(r,e,t,n){let o=await qn(r,e,t),s=Un(o,t,n);return new Set(t.map(te).filter(i=>{let a=o.articleOf.get(i);return a!==void 0&&s.has(te(a))}))}async function Xr(r,e,t,n){let o=await qn(r,e,t),{articleOf:s}=o,i=[...new Set(s.values())],a=Un(o,t,n),d=i.filter(u=>!a.has(te(u))),c=new Map;if(d.length>0){let u;try{u=await r.destroy(Fn(e),d)}catch(l){let g=N(l);u=d.map(()=>({success:!1,errors:[{message:g}]}))}let f=Array.isArray(u)?u:[u];d.forEach((l,g)=>c.set(te(l),f[g]))}return t.map(u=>{let f=s.get(te(u));return f===void 0?{success:!1,errors:[Kr]}:a.has(te(f))?{success:!1,errors:[{message:Nt}]}:c.get(te(f))??Yr})}var Ze="Quote",Ce="QuoteLineItem",Pe="Opportunity",Ne="OpportunityLineItem",Hn=2e3;function eo(r){return r.slice(0,15)}function Jn(r){return typeof r=="string"?Date.parse(r):Number.NaN}function G(r,e){let t=r[e];return typeof t=="string"&&t!==""?eo(t):void 0}function vt(r,e){return r.has(e)||r.otherParts?.has(e)===!0}function to(r,e){let t=new Set,n=new Set;for(let g of r.syncing){let p=G(g,"Id"),m=G(g,"SyncedQuoteId");!p||!m||!vt(e,p)||!e.has(m)||(t.add(m),n.add(p))}if(t.size===0)return[];let o=r.quoteLines.filter(g=>{let p=G(g,"QuoteId");return p!==void 0&&t.has(p)&&G(g,"Id")!==void 0}),s=r.opportunityLines.filter(g=>{let p=G(g,"OpportunityId");return p!==void 0&&n.has(p)&&G(g,"Id")!==void 0}),i=g=>G(g,"CreatedById"),a=(g,p)=>{let m=G(g,"Id");if(!m||vt(e,m)||!p)return!1;let b=e.user??i(p),h=Jn(g.CreatedDate);return b!==void 0&&i(g)===b&&h>=e.start&&h<=e.end},d=g=>({id:String(g.Id),modified:Jn(g.LastModifiedDate)}),c=new Map(s.flatMap(g=>{let p=G(g,"Id");return p&&e.has(p)?[[p,g]]:[]})),u=new Map;for(let g of o){let p=G(g,"Id"),m=G(g,"OpportunityLineItemId");p&&m&&e.has(p)&&!u.has(m)&&u.set(m,g)}let f=o.filter(g=>{let p=G(g,"OpportunityLineItemId");return a(g,p?c.get(p):void 0)}).map(d),l=s.filter(g=>{let p=G(g,"Id");return a(g,p?u.get(p):void 0)}).map(d);return[...f.length>0?[{objectApiName:Ce,copies:f}]:[],...l.length>0?[{objectApiName:Ne,copies:l}]:[]]}function Qn(r,e=[]){let t=new Set(r),n=t.has(Pe)||new Set(e).has(Pe);if(!t.has(Ze)||!n)return[];let o=t.has(Ce),s=t.has(Ne);return o===s?[]:[o?Ne:Ce]}async function jt(r,e,t,n,o){let s=t.map(F).join(", "),i=[];for(let a of ee(o)){let d=await r.query(`SELECT ${s} FROM ${F(e)} WHERE ${F(n)} IN (${a}) LIMIT ${Hn}`);if(d.records.length>=Hn)throw new Error(`More ${e} records than one read takes.`);for(let c of d.records)typeof c=="object"&&c!==null&&i.push(c)}return i}async function Wn(r,e,t,n){let o=n.has(Ce)||n.has(Ne),s=n.has(Pe)||e.otherParts?.objects.has(Pe)===!0;if(t.length===0||!s||!o)return[];try{let a=(await jt(r,Pe,["Id","SyncedQuoteId"],"SyncedQuoteId",t)).filter(u=>{let f=G(u,"Id");return f!==void 0&&vt(e,f)});if(a.length===0)return[];let d=await jt(r,Ce,["Id","QuoteId","OpportunityLineItemId","CreatedById","CreatedDate","LastModifiedDate"],"QuoteId",[...new Set(a.map(u=>String(u.SyncedQuoteId)))]),c=await jt(r,Ne,["Id","OpportunityId","CreatedById","CreatedDate","LastModifiedDate"],"OpportunityId",a.map(u=>String(u.Id)));return to({syncing:a,quoteLines:d,opportunityLines:c},e)}catch{return[]}}var no=5,ve=4,Xe=2e3,ro=4,nt=[["CreatedDate","LastModifiedDate","CreatedById","LastModifiedById"],["CreatedDate","LastModifiedDate","CreatedById"],["SystemModstamp"],[]],Lt=1e4,oo="005",Vn="ContentDocumentLink",so="ContentDocument",io="ContentVersion",ao=5;function rt(r){let e=new Set(r.flatMap(n=>n.ids.map(w))),t=new Map;for(let{objectApiName:n,ids:o}of r)t.set(n,[...t.get(n)??[],...o]);return{objects:[...t].map(([n,o])=>({objectApiName:n,count:o.length})),pages:async function*(n){let o=t.get(n);o&&o.length>0&&(yield o)},has:n=>e.has(n)}}function pe(r){return!Array.isArray(r)}function ki(r){return pe(r)?r.objects.reduce((e,t)=>e+t.count,0):r.reduce((e,t)=>e+t.ids.length,0)}function Oi(r){return(pe(r)?r.objects:r).map(e=>e.objectApiName)}var ot=class{bits=new Uint8Array(0);add(e){let t=e>>3;if(t>=this.bits.length){let n=new Uint8Array(Math.max(t+1,this.bits.length*2,64));n.set(this.bits),this.bits=n}this.bits[t]|=1<<(e&7)}has(e){let t=e>>3;return t<this.bits.length&&(this.bits[t]&1<<(e&7))!==0}},Tt=class{dates=new Float64Array(0);set(e,t){if(e>=this.dates.length){let n=new Float64Array(Math.max(e+1,this.dates.length*2,64)).fill(Number.NaN);n.set(this.dates),this.dates=n}this.dates[e]=t}at(e){return e<this.dates.length?this.dates[e]:Number.NaN}latestWithin(e,t){let n=Number.NaN;for(let o of this.dates)o>=e&&o<=t&&!(o<=n)&&(n=o);return n}};function je(r,e){return typeof r=="string"&&e.has(w(r))}var Kn=[{created:"CreatedDate",modified:"LastModifiedDate"},{modified:"SystemModstamp"}],Mt={ContentDocumentLink:{ends:["ContentDocumentId","LinkedEntityId"],cameWithRun:(r,e)=>{let t=r.LinkedEntityId;return je(r.ContentDocumentId,e)&&(je(t,e)||typeof t=="string"&&t.startsWith(oo))}},DuplicateRecordItem:{ends:["RecordId"],cameWithRun:(r,e)=>je(r.RecordId,e)},ContentVersion:{ends:["ContentDocumentId"],cameWithRun:(r,e)=>je(r.ContentDocumentId,e)}};function Ei(r,e){return{...Ue(r,e),serverTime:async()=>(await r.soap.getServerTimestamp()).timestamp,userId:async()=>(await r.soap.getUserInfo()).userId,queryDeleted:async t=>({records:(await r.query(t,{scanAll:!0})).records}),bulkDestroy:(t,n,o)=>De(Je(r),t,n,o)}}function xt(r,e,t){let n=new Map;for(let o of r??[]){let s=Ft(o.span,[],t);if(Number.isFinite(s.end))for(let i of o[e]??[]){let a=w(i);s.end<=(n.get(a)?.end??Number.NEGATIVE_INFINITY)||n.set(a,s)}}return n}function co(r=[],e=[]){if(r.length===0&&e.length===0)return;let t=[...r.map(({plan:n})=>pe(n)?n:rt(n)),rt(e)];return{has:n=>t.some(o=>o.has(n))}}function lo(r=[],e=[]){return new Set([...r.map(({plan:t})=>pe(t)?t.objects:t),e].flat().map(t=>t.objectApiName))}function er(r,e){return new Map([...xt(r,"wrote",e)].map(([t,{end:n}])=>[t,n]))}function tr(r,e){return`The user SandForge connects as may not delete ${r} records in this org: the ${e} record(s) of the run stay, and were not sent.`}function _t(r,e){return`Not visible: ${r} record(s) found neither in the org nor in its recycle bin, as the user the removal runs as sees them \u2014 out of that user's sight, or deleted for good \u2014 are not counted as removed`+(e?` (the recycle bin could not be read: ${e})`:".")}function Gn(r,e,t){for(let o of r){let s=o.deleted+o.alreadyGone+o.keptChanged+o.keptDependents+o.refused+(o.notVisible??0);o.planned>s&&(o.notReached=o.planned-s)}let n=new Set(r.map(o=>o.objectApiName));for(let{objectApiName:o,count:s}of e)s===0||n.has(o)||(n.add(o),r.push({...new Me(o,s,t(o)).result,notReached:s}));return r}var Di={objects:[],cancelled:!1,gone:[],stamps:{},left:async function*(){}};function w(r){return r.slice(0,15)}function uo(r){return r?.errorCode==="INVALID_FIELD"||/no such column/i.test(N(r))}function fo(r,e){let t=/no such column '(\w+)'/i.exec(N(r))?.[1],n=nt.findIndex((o,s)=>s>e&&(t===void 0||!o.includes(t)));return n===-1?nt.length:n}function q(r){return typeof r=="string"?Date.parse(r):Number.NaN}function nr(){return{modified:new Tt,missing:new Set,firstCreated:Number.NaN,lastCreated:Number.NaN,binned:new Set}}var Me=class{result;notes=[];refused=new Map;unread;held=[];goneAt=new ot;goneLater=new Set;deletedLater=new Set;notVisible=0;notVisibleNote;secondTry=new Set;filesLeft=new Map;automationHeld=new Map;automationHeldAfter=new Set;automationHeldAlong=new Set;tookAlong=new Map;cameAlong=new Map;limitNotes=[];lockResent=new Map;constructor(e,t,n=0){this.result={objectApiName:e,planned:t,deleted:0,alreadyGone:0,keptChanged:0,keptDependents:0,refused:0,heldBy:[],...n>0?{platformCopies:n}:{},unchecked:[],reasons:[]}}note(e){this.notes.includes(e)||this.notes.push(e)}isGone(e,t){return this.goneAt.has(t)||this.goneLater.has(w(e))}waiting(){return[...[...this.refused].filter(([,e])=>e.dependency).map(([e])=>e),...this.held]}refusedSent(){return[...this.refused].filter(([,e])=>e.sent).map(([e])=>e)}refusedToSendAgain(){return[...this.refused].filter(([,e])=>e.sent&&e.limit!==!0).map(([e])=>e)}secondTryNote(){if(this.secondTry.size===0)return[];let e=0,t=0,n=0,o=0;for(let i of this.secondTry){let a=w(i);this.deletedLater.has(a)?e++:this.goneLater.has(a)?t++:this.refused.has(i)?o++:n++}return[`Refused at first, sent again once the rest had gone: ${[e>0?`${e} deleted`:"",t>0?`${t} already gone`:"",n>0?`${n} kept for records that stay`:"",o>0?`${o} refused again`:""].filter(Boolean).join(", ")}.`]}settle(){this.result.keptDependents=this.held.length,this.result.refused=this.refused.size+(this.unread?.count??0),this.notVisible>0&&(this.result.notVisible=this.notVisible),this.held.length===0&&(this.result.heldBy=[]);let e=this.held.flatMap(s=>{let i=this.automationHeld.get(w(s));return i?[i]:[]}),t=this.held.filter(s=>{let i=w(s);return this.automationHeld.has(i)&&this.automationHeldAfter.has(i)}).length,n=this.held.filter(s=>{let i=w(s);return this.automationHeld.has(i)&&this.automationHeldAlong.has(i)}).length;e.length>0?(this.result.heldByAutomation=e.length,t>0?this.result.heldByAutomationAfterRun=t:delete this.result.heldByAutomationAfterRun,n>0?this.result.heldByAutomationAlong=n:delete this.result.heldByAutomationAlong,this.result.automationHolders=[...new Set(e.flatMap(s=>[...s]))]):(delete this.result.heldByAutomation,delete this.result.heldByAutomationAfterRun,delete this.result.heldByAutomationAlong,delete this.result.automationHolders);let o=[...this.notVisibleNote?[this.notVisibleNote]:[],...this.notes,...this.limitNotes,...jn(this.lockResent.values()),...this.secondTryNote(),...this.unread?[this.unread.reason]:[],...[...this.refused.values()].map(s=>s.reason)];return this.result.reasons=[...new Set(o)].slice(0,no),this.filesLeft.size>0&&(this.result.filesLeft={count:this.filesLeft.size,names:[...this.filesLeft.values()].slice(0,ao)}),this.tookAlong.size>0&&(this.result.tookAlong={count:this.tookAlong.size,objects:[...new Set(this.tookAlong.values())]}),this.cameAlong.size>0&&(this.result.cameAlong={count:this.cameAlong.size,objects:[...new Set(this.cameAlong.values())]}),this.result}};async function Ii(r,e,t){let n=pe(e)?e:rt(e),o=n,s=o.objects.reduce((y,A)=>y+A.count,0),i=new Map,a=y=>i.get(y)??0,d=()=>t.signal?.aborted===!0,c=t.splitting??dn(),u=()=>({objects:Gn([],o.objects,a),cancelled:!0,gone:[],stamps:{},left:()=>Xn(n)}),f=new Map,l=new Map;for(let{objectApiName:y}of o.objects){let A=nr();f.set(y,A);let E=0;for await(let P of o.pages(y)){if(d())return u();let J=P[0];J!==void 0&&!l.has(J.slice(0,3))&&l.set(J.slice(0,3),y);let B=E;if(E+=P.length,A.error!==void 0)continue;let C=await wo(r,y,P,B,A);if(A.error!==void 0||C.length===0)continue;if(d())return u();let Q=await _n(r,y,C);if("error"in Q)A.binError=Q.error;else for(let ne of Q.deleted)A.binned.add(ne)}}let g=new Map,p=!1,m=r.bulkDestroy?.bind(r),b={query:y=>r.query(y),destroy:(y,A)=>(p=!0,r.destroy(y,A)),...m?{bulkDestroy:(y,A)=>(p=!0,m(y,A,t.signal))}:{},update:(y,A)=>(p=!0,r.update(y,A)),serverTime:()=>r.serverTime(),userId:()=>r.userId(),queryDeleted:y=>r.queryDeleted(y),describeGlobal:()=>r.describeGlobal(),describe:y=>{let A=g.get(y);return A||(A=r.describe(y),g.set(y,A)),A}},h=$n(b,{includeChanged:t.includeChanged}),R=await Ke(h,o.objects),S=await yo(h,R,(y,A)=>A-(f.get(y)?.missing.size??0)),j=new Set(S.map(y=>y.objectApiName));if(S.length>0&&t.onUndeletable&&t.previewOnly!==!0){if(d())return u();if(!await t.onUndeletable(S))return{...u(),objects:[],undeletable:S,stoppedForUndeletable:!0}}let[_,U]=await Promise.all([Ao(h),t.previewOnly===!0?void 0:ko(h)]),{start:k,end:O}=Ft(t,f.values(),_.aheadMs);if(d())return u();let I=co(t.otherParts,t.otherPartRecords),D=lo(t.otherParts,t.otherPartRecords),M=await Ro(h,o,{start:k,end:O,...t.runUserId?{user:w(t.runUserId)}:{},...I?{otherParts:{has:y=>I.has(y),objects:D}}:{},undeletable:j,snapshots:f});if(t.runUserId&&t.alongAccepted!==!0){let y=await xn(h,{has:A=>o.has(A),start:k,end:O,user:t.runUserId});y.length>0&&!o.objects.some(A=>A.objectApiName===Re)&&await rr(h,Re)&&M.push({objectApiName:Re,copies:y})}if(M.length>0){o=await So(o,M,f,l);for(let{objectApiName:y,copies:A}of M)i.set(y,A.length);s=o.objects.reduce((y,A)=>y+A.count,0),R=await Ke(h,o.objects)}let H=new Map(Object.entries(t.removalStamps??{}).map(([y,A])=>[w(y),q(A)])),v=er(t.laterParts,_.aheadMs),T=new Set;for(let{objectApiName:y}of o.objects){let A=f.get(y);if(!A||A.error!==void 0)continue;let E=0;for await(let P of o.pages(y))for(let J of P){let B=A.modified.at(E++),C=w(J);if(A.missing.has(C))continue;B<=O||B<=(H.get(C)??Number.NaN)||B<=(v.get(C)??Number.NaN)||T.add(C)}}if(t.previewOnly===!0){if(d())return u();let y=new Set,A=await po(h,o,R,{snapshots:f,changed:T,undeletable:j,includeChanged:t.includeChanged,stopped:d,copiesOf:a,...t.previewHeld===!0?{held:{notSent:y,check:new Le(h,{runRecords:o,reached:{has:()=>!1},stays:E=>y.has(E),runStart:k,runEnd:O,removalStart:_.start,removalUser:void 0,earlierRemovals:(t.removalSpans??[]).map(E=>({start:q(E.first),end:q(E.last),user:w(E.userId)})),includeChanged:t.includeChanged,previewing:!0,...t.goesWithParent?{goesWithParent:t.goesWithParent}:{},...t.goesWithParentReadBelow?{goesWithParentReadBelow:!0}:{},...t.alongAccepted?{alongAccepted:t.alongAccepted}:{},...t.runUserId?{runUser:w(t.runUserId)}:{},...t.laterParts?{linkedLater:xt(t.laterParts,"linked",_.aheadMs)}:{},...I?{otherPartRecords:I,otherPartObjects:D}:{}})}}:{}});return A?{...S.length>0?{undeletable:S}:{},objects:[],cancelled:!1,gone:[],stamps:{},left:()=>Xn(n),preview:A}:u()}let L=await bo(h,t.otherParts??[],_.aheadMs,d);if(!L)return u();let xe=new Set,hr={has:y=>o.has(y)&&xe.has(l.get(y.slice(0,3))??"")},at=new Le(h,{runRecords:o,reached:hr,stays:y=>T.has(y)&&!t.includeChanged,runStart:k,runEnd:O,removalStart:_.start,removalUser:U,earlierRemovals:(t.removalSpans??[]).map(y=>({start:q(y.first),end:q(y.last),user:w(y.userId)})),includeChanged:t.includeChanged,...t.goesWithParent?{goesWithParent:t.goesWithParent}:{},...t.goesWithParentReadBelow?{goesWithParentReadBelow:!0}:{},...t.alongAccepted?{alongAccepted:t.alongAccepted}:{},...t.alongToDraft?{alongToDraft:t.alongToDraft}:{},...t.runUserId?{runUser:w(t.runUserId)}:{},...t.automationMade?{automationMade:ir(t.automationMade)}:{},...t.laterParts?{linkedLater:xt(t.laterParts,"linked",_.aheadMs)}:{},...I?{otherPartRecords:I,otherPartObjects:D}:{}});if(d())return u();await t.beforeFirstWrite?.(),t.sweep&&await t.sweep(c)&&(p=!0);let le=[],Kt=y=>le.find(A=>A.result.objectApiName===y);async function*dt(y,A,E){for(let{objectApiName:P}of A){let J=Kt(P),B=0;for await(let C of y.pages(P)){let Q=C.filter(ne=>E(P,ne,J?.isGone(ne,B++)===!0));Q.length>0&&(yield{objectApiName:P,ids:Q})}}}let yr=()=>dt(o,R,(y,A,E)=>{let P=f.get(y),J=w(A);return P?.modifiedColumn==="LastModifiedDate"&&!P.missing.has(J)&&!T.has(J)&&!E}),_e=[],Z=async y=>{await Ln(h,_e,{note:(C,Q,ne)=>{let Y=Kt(C);if(!Y){if(!ne)return;let se=o.objects.find(ie=>ie.objectApiName===C);Y=new Me(C,se?.count??0,a(C)),le.push(Y)}Y.note(Q)}});let A=p?await Yn(h,yr(),{start:_.start,user:U}):{},E=[];if(p)for(let C of L)E.push(await Yn(h,C.unchanged(),{start:_.start,user:U}));let P=p?Oo(_,U):void 0,J=[];if(!pe(e))for await(let{ids:C}of dt(n,R,(Q,ne,Y)=>Y))for(let Q of C)J.push(Q);for(let C of le)C.limitNotes=Dt(C.result.objectApiName,c);let B=le.map(C=>C.settle());return{...S.length>0?{undeletable:S}:{},objects:y?Gn(B,R,a):B,cancelled:y,gone:J,left:()=>dt(n,n.objects,(C,Q,ne)=>!ne),stamps:A,...P?{span:P}:{},...E.length>0?{otherPartStamps:E}:{}}};if(d())return p?Z(!0):u();let Gt=async(y,A)=>(await at.heldAmong(y,A)).held,Yt=await Pt(h,R,o,(y,A)=>{let E=w(A),P=f.get(y);return P!==void 0&&P.error===void 0&&!j.has(y)&&!P.missing.has(E)&&!(T.has(E)&&!t.includeChanged)},d,Gt);if(_e=Yt.drafted,Yt.cancelled)return Z(!0);if(t.alongToDraft){let y=await Pt(h,t.alongToDraft.objects,t.alongToDraft,()=>!0,d,Gt);if(_e=[..._e,...y.drafted],y.cancelled)return Z(!0)}let ae=0;for(let{objectApiName:y,count:A}of R){if(d())return Z(!0);let E=new Me(y,A,a(y));le.push(E),xe.add(y);let P=f.get(y);if(!P||P.error!==void 0){E.unread={reason:P?.error??"The org gave no reason.",count:A},ae+=A,t.onProgress?.(ae,s,y);continue}if(j.has(y)){let Y=0,se=0;for await(let ie of o.pages(y))for(let ye of ie){let Se=w(ye),wr=Y++;P.missing.has(Se)?P.binned.has(Se)?(E.result.alreadyGone++,E.goneAt.add(wr)):E.notVisible++:se++}E.notVisible>0&&(E.notVisibleNote=_t(E.notVisible,P.binError)),se>0&&(E.unread={reason:tr(y,se),count:se}),ae+=A,t.onProgress?.(ae,s,y);continue}let J=Pn(h,y,A),B=[],C=new Map,Q=async()=>{let Y=B,se=C;return B=[],C=new Map,Zn(h,at,E,Y,{stopped:d,splitting:c,placeOf:se,onDeleted:ie=>{ae+=ie,t.onProgress?.(ae,s,y)},onHeld:ie=>{ae+=ie,t.onProgress?.(ae,s,y)}})},ne=0;for await(let Y of o.pages(y)){if(d())return Z(!0);let se=B.length;for(let ie of Y){let ye=w(ie),Se=ne++;P.missing.has(ye)?P.binned.has(ye)?(E.result.alreadyGone++,E.goneAt.add(Se)):E.notVisible++:T.has(ye)&&!t.includeChanged?E.result.keptChanged++:(B.push(ie),C.set(ye,Se))}if(E.notVisible>0&&(E.notVisibleNote=_t(E.notVisible,P.binError)),ae+=Y.length-(B.length-se),!(J&&B.length<Ve)&&await Q())return Z(!0)}if(J&&B.length>0&&(d()||await Q()))return Z(!0)}let br=le.some(y=>y.result.deleted>0);if(await Mn(le,{stopped:d,idsOf:(y,A)=>{if(A>0)return y.waiting();let E=y.refusedToSendAgain();return E.length>0||br?[...E,...y.held]:[]},send:async(y,A,E)=>{let P=new Set(E===0?y.refusedToSendAgain():[]),J=await Zn(h,at,y,A,{stopped:d,splitting:c,onSent:B=>{for(let C of B)P.has(C)&&y.secondTry.add(C)}});for(let B of y.held)P.has(B)&&y.secondTry.add(B);return J},deleted:y=>y.result.deleted}))return Z(!0);if(t.afterRemoval){if(d())return Z(!0);await t.afterRemoval(c)&&(p=!0)}for(let y of le){if(d())return Z(!0);await ho(h,y,f.get(y.result.objectApiName))}return Z(!1)}async function go(r,e,t,n,o){let{changed:s,includeChanged:i}=o,a=[];for await(let d of e.pages(t))for(let c of d){let u=w(c);!n.has(u)&&(i||!s.has(u))&&a.push(c)}try{return{kept:await zn(r,t,a,{includeChanged:i})}}catch(d){return{kept:new Set,unread:N(d)}}}async function po(r,e,t,n){let o=[],s=new Set;for(let{objectApiName:i,count:a}of t){let d=n.copiesOf(i),c={objectApiName:i,planned:a,toDelete:0,alreadyGone:0,changedSince:0,keptChanged:0,changedBy:{},undeletable:0,notVisible:0,unread:0,...d>0?{platformCopies:d}:{},reasons:[]};o.push(c);let u=n.snapshots.get(i);if(!u||u.error!==void 0){if(c.unread=a,c.reasons.push(u?.error??"The org gave no reason."),n.held)for await(let m of e.pages(i))for(let b of m)n.held.notSent.add(w(b));continue}let f=Ie(i)&&!n.undeletable.has(i)?await go(r,e,i,u.missing,n):void 0,l=[],g=[],p=m=>{n.held?.notSent.add(m)};for await(let m of e.pages(i))for(let b of m){let h=w(b);u.missing.has(h)?u.binned.has(h)?c.alreadyGone++:c.notVisible++:n.undeletable.has(i)?(c.undeletable++,p(h)):f?.unread!==void 0?(c.unread++,p(h)):n.changed.has(h)?(c.changedSince++,l.push(b),n.includeChanged?(c.toDelete++,g.push(b)):(c.keptChanged++,p(h))):f?.kept.has(h)?(c.changedSince++,c.keptChanged++,p(h)):(c.toDelete++,g.push(b))}if(n.held&&g.length>0){if(n.stopped())return;let m=await n.held.check.heldAmong(i,g),b=g.filter(R=>m.held.has(w(R)));if(b.length>0){c.toDelete-=b.length,c.keptDependents=b.length,c.heldBy=[...m.holders];for(let S of b)n.held.notSent.add(w(S));let R=b.filter(S=>m.byAutomation.has(w(S)));R.length>0&&(c.heldByAutomation=R.length)}let h=new Map;for(let R of g)if(!m.held.has(w(R)))for(let[S,j]of m.cameAlong.get(w(R))??[])h.set(S,j);h.size>0&&(c.cameAlong={count:h.size,objects:[...new Set(h.values())]}),m.reason!==void 0&&c.reasons.push(m.reason),m.unchecked.size>0&&c.reasons.push(`Not checked: what hangs from them through ${[...m.unchecked].join(", ")}, which the org deletes along but does not let be read by the record it hangs from.`)}if(f?.unread!==void 0?c.reasons.push(`Its articles could not be read: ${f.unread}`):f!==void 0&&f.kept.size>0&&c.reasons.push(Nt),c.notVisible>0&&c.reasons.push(_t(c.notVisible,u.binError)),c.undeletable>0&&c.reasons.push(tr(i,c.undeletable)),!(l.length===0||u.modifiedColumn!=="LastModifiedDate")){if(n.stopped())return;try{let m=await z(r,i,["LastModifiedById"],l,ve);for(let b of m){let h=b.LastModifiedById;typeof h!="string"||h===""||(c.changedBy[h]=(c.changedBy[h]??0)+1,s.add(h))}}catch(m){c.reasons.push(`Who changed them since the run could not be read: ${N(m)}`)}}}if(!n.stopped())return{objects:o,userNames:await mo(r,[...s])}}async function mo(r,e){let t={};if(e.length===0)return t;try{for(let n of await z(r,"User",["Name"],[...e].sort()))typeof n.Id=="string"&&typeof n.Name=="string"&&(t[n.Id]=n.Name)}catch{}return t}async function ho(r,e,t){let{gone:n,unchecked:o,failure:s}=await It(e.refusedSent(),i=>z(r,e.result.objectApiName,[],i),i=>t!==void 0&&t.error===void 0&&!t.missing.has(w(i)));for(let i of n)e.refused.delete(i),e.goneLater.add(w(i)),e.result.alreadyGone++;o.length>0&&e.note(`Not checked: ${o.length} refused record(s) could not be read back once the rest had gone, to tell whether a parent deleted after them took them along`+(s?` \u2014 ${s}`:"."))}function Pi(r,e=[],t={}){return[...new Set([...r,...Qn(r,e),...t.userKept===!0&&r.length>0?[Re]:[]])]}async function yo(r,e,t){let n=[];for(let{objectApiName:o,count:s}of e){if(o===io||s===0)continue;let i=t(o,s);if(i!==0)try{let a=de.safeParse(await r.describe(o));a.success&&a.data.deletable===!1&&n.push({objectApiName:o,records:i})}catch{}}return n}async function Yn(r,e,t){let n={},{start:o,user:s}=t;if(s===void 0||!Number.isFinite(o))return n;for await(let{objectApiName:i,ids:a}of e){let d;try{d=await z(r,i,["LastModifiedDate","LastModifiedById"],a)}catch{continue}for(let c of d)typeof c.Id=="string"&&typeof c.LastModifiedDate=="string"&&typeof c.LastModifiedById=="string"&&w(c.LastModifiedById)===s&&q(c.LastModifiedDate)>=o&&(n[c.Id]=c.LastModifiedDate)}return n}async function bo(r,e,t,n){let o=[];for(let s of e){let i=pe(s.plan)?s.plan:rt(s.plan),{end:a}=Ft(s.span,[],t),d=new Map(Object.entries(s.removalStamps??{}).map(([f,l])=>[w(f),q(l)])),c=er(s.laterParts,t),u=new Map;if(Number.isFinite(a))for(let{objectApiName:f}of i.objects){let l=new ot,g=0,p=!1;for await(let m of i.pages(f)){if(n())return;let b=g;if(g+=m.length,p)continue;let h;try{h=await z(r,f,["LastModifiedDate"],m,ve)}catch{p=!0;continue}let R=new Map;for(let S of h)typeof S.Id=="string"&&R.set(w(S.Id),q(S.LastModifiedDate));m.forEach((S,j)=>{let _=w(S),U=R.get(_);U!==void 0&&(U<=a||U<=(d.get(_)??Number.NaN)||U<=(c.get(_)??Number.NaN))&&l.add(b+j)})}p||u.set(f,l)}o.push({unchanged:async function*(){for(let{objectApiName:f}of i.objects){let l=u.get(f);if(!l)continue;let g=0;for await(let p of i.pages(f)){let m=p.filter(()=>l.has(g++));m.length>0&&(yield{objectApiName:f,ids:m})}}}})}return o}async function Zn(r,e,t,n,o){let{objectApiName:s}=t.result,i=await e.heldAmong(s,n);i.reason!==void 0&&t.note(i.reason);for(let l of i.unchecked)t.result.unchecked.includes(l)||t.result.unchecked.push(l);let a=n.filter(l=>i.held.has(w(l)));if(o.placeOf){for(let l of a)t.held.push(l);t.result.heldBy=[...new Set([...t.result.heldBy,...i.holders])]}else t.held=a,t.result.heldBy=[...i.holders];for(let l of a)t.refused.delete(l);for(let l of n){let g=w(l),p=i.byAutomation.get(g);p?t.automationHeld.set(g,p):t.automationHeld.delete(g),p&&i.automationAfter.has(g)?t.automationHeldAfter.add(g):t.automationHeldAfter.delete(g),p&&i.automationAlong.has(g)?t.automationHeldAlong.add(g):t.automationHeldAlong.delete(g)}o.onHeld?.(a.length);let d=n.filter(l=>!i.held.has(w(l))),c=new Map,u=(l,g)=>{l.forEach((p,m)=>{let b=g[m],h=w(p);if((b.lockResends!==void 0||t.lockResent.has(h))&&t.lockResent.set(h,b.kind),b.kind==="refused"){t.refused.set(p,{reason:b.reason,dependency:b.dependency,sent:!0,...b.limit?{limit:!0}:{}});return}t.refused.delete(p);let R=o.placeOf?.get(h);if(R!==void 0?t.goneAt.add(R):t.goneLater.add(h),b.kind==="deleted"){t.result.deleted++,R===void 0&&t.deletedLater.add(h);for(let S of c.get(h)??[])t.filesLeft.set(S.key,S.name);for(let[S,j]of i.along.get(h)??[])t.tookAlong.set(S,j);for(let[S,j]of i.cameAlong.get(h)??[])t.cameAlong.set(S,j)}else t.result.alreadyGone++}),o.onSent?.(l),o.onDeleted?.(l.length)},{stopped:f}=await vn(r,s,d,{stopped:o.stopped,splitting:o.splitting,prepare:async l=>{c=await e.filesOn(l)},settle:u});return f}async function wo(r,e,t,n,o){let s,i=o.modifiedColumn?Kn.filter(({modified:a})=>a===o.modifiedColumn):Kn;for(let{created:a,modified:d}of i)try{let u=await z(r,e,a?[a,d]:[d],t,ve),f=new Map;for(let g of u)typeof g.Id=="string"&&f.set(w(g.Id),q(g[d])),a&&(o.firstCreated=or(o.firstCreated,q(g[a])),o.lastCreated=Bt(o.lastCreated,q(g[a])));o.modifiedColumn=d;let l=[];return t.forEach((g,p)=>{let m=w(g),b=f.get(m);b===void 0&&(o.missing.add(m),l.push(g)),o.modified.set(n+p,b??Number.NaN)}),l}catch(c){s??=N(c)}return o.error=s,o.modifiedColumn=void 0,[]}async function*Xn(r){for(let{objectApiName:e}of r.objects)for await(let t of r.pages(e))t.length>0&&(yield{objectApiName:e,ids:[...t]})}async function Ro(r,e,t){let n=new Set(e.objects.filter(a=>a.count>0).map(a=>a.objectApiName));if(!n.has(Ze))return[];let o=[];for await(let a of e.pages(Ze))o.push(...a);let s=await Wn(r,{has:a=>e.has(a),start:t.start,end:t.end,...t.user!==void 0?{user:t.user}:{},...t.otherParts?{otherParts:t.otherParts}:{}},o,n),i=[];for(let a of s){let{objectApiName:d}=a;if(t.undeletable.has(d))continue;let c=t.snapshots.get(d);if(c){if(c.error!==void 0||c.modifiedColumn!=="LastModifiedDate")continue}else if(!await rr(r,d))continue;i.push(a)}return i}async function rr(r,e){try{let t=de.safeParse(await r.describe(e));return t.success&&t.data.deletable!==!1}catch{return!1}}async function So(r,e,t,n){let o=new Map(e.map(({objectApiName:a,copies:d})=>[a,d])),s=new Set(e.flatMap(({copies:a})=>a.map(d=>w(d.id)))),i=r.objects.map(a=>{let d=o.get(a.objectApiName);return d?{objectApiName:a.objectApiName,count:a.count+d.length}:a});for(let[a,d]of o){r.objects.some(l=>l.objectApiName===a)||i.push({objectApiName:a,count:d.length});let c=t.get(a);c||(c={...nr(),modifiedColumn:"LastModifiedDate"},t.set(a,c));let u=0;for await(let l of r.pages(a))u+=l.length;for(let l of d)c.modified.set(u++,l.modified);let f=d[0]?.id.slice(0,3);f!==void 0&&!n.has(f)&&n.set(f,a)}return{objects:i,pages:async function*(a){yield*r.pages(a);let d=o.get(a);d&&d.length>0&&(yield d.map(c=>c.id))},has:a=>r.has(a)||s.has(a)}}async function Ao(r){let e=Date.now(),t=Number.NaN;try{t=q(await r.serverTime())}catch{}return Number.isFinite(t)?{start:Math.floor(t/1e3)*1e3,aheadMs:t-(e+Date.now())/2}:{start:Number.POSITIVE_INFINITY,aheadMs:Number.NaN}}async function ko(r){try{let e=await r.userId();return typeof e=="string"&&e!==""?w(e):void 0}catch{return}}function Oo(r,e){if(!(e===void 0||!Number.isFinite(r.start)))return{first:new Date(r.start).toISOString(),last:new Date(Date.now()+r.aheadMs+Lt).toISOString(),userId:e}}function or(r,e){return Number.isNaN(r)||e<r?e:r}function Bt(r,e){return Number.isNaN(r)||e>r?e:r}var sr=999;function Eo(r,e,t){let n=Number.NaN;for(let o of r)o.lastCreated>=e&&o.lastCreated<=t&&(n=Bt(n,o.lastCreated)),n=Bt(n,o.modified.latestWithin(e,t));return n}function Ft(r,e,t){let n=Do(r,e,t),o=(r.writtenUntil?.getTime()??Number.NaN)+sr;return Number.isFinite(n.end)&&o>n.end?{...n,end:o}:n}function Do(r,e,t){let n=[...e],o=Number.NaN;for(let c of n)o=or(o,c.firstCreated);let s=r.runDurationMs??0,i=(r.runRecordedAt?.getTime()??Number.NaN)+t;if(r.runEndedAt===void 0&&Number.isFinite(i)){let c=i-s-Lt,u=i+Lt,f=r.endedByItsWrites===!0?Eo(n,c,u):Number.NaN;return{start:r.runStartedAt?.getTime()??(o>c?o:c),end:Number.isFinite(f)?Math.min(f+sr,u):u}}let a=r.runStartedAt?.getTime()??o,d=r.runEndedAt?.getTime()??a+s;return{start:a,end:d}}function ir(r){let e=new Set,t=-1;return{has:n=>(r.size!==t&&(e=new Set([...r].map(w)),t=r.size),e.has(n))}}function Ci(r,e){let t=new Le(r,{runRecords:e.runRecords,reached:{has:()=>!1},stays:()=>!1,runStart:e.runStart,runEnd:e.runEnd,removalStart:Number.POSITIVE_INFINITY,removalUser:void 0,earlierRemovals:(e.removalSpans??[]).map(n=>({start:q(n.first),end:q(n.last),user:w(n.userId)})),includeChanged:e.includeChanged,automationMade:ir(e.taken),...e.runUserId?{runUser:w(e.runUserId)}:{}});return async(n,o)=>{let s=await t.heldAmong(n,o,1);return{held:s.held,holders:[...s.holders],...s.reason!==void 0?{reason:s.reason}:{}}}}var et="IsPersonAccount",Io=50;function tt(r,e){return JSON.stringify(e.map(t=>r[t]??null))}var Le=class{constructor(e,t){this.org=e;this.context=t}org;context;worked;statuses=new Map;lockedUnder=new Map;files=new Map;datesKept=new Map;cascadeEnds=new Map;async heldAmong(e,t,n=0){let o={held:new Set,holders:new Set,otherwise:new Set,mayBeAutomation:[],byAutomation:new Map,automationAfter:new Set,automationAlong:new Set,along:new Map,cameAlong:new Map,unchecked:new Set};if(t.length===0)return o;let s;try{let l=de.parse(await this.org.describe(e)),g=await this.workedObjects(),p=e==="Account"&&l.fields.some(m=>m.name===et);s=(l.childRelationships??[]).filter(m=>(m.cascadeDelete===!0||m.restrictedDelete===!0)&&g.has(m.childSObject)).map(m=>({childSObject:m.childSObject,field:m.field,restricted:m.cascadeDelete!==!0,...p&&m.childSObject==="Contact"&&m.field==="AccountId"?{personContacts:!0}:{}}))}catch(l){return o.reason=N(l),t.forEach(g=>this.hold(o,w(g))),o}let i=[];for(let l=0;l<t.length;l+=re)i.push(t.slice(l,l+re));let a=i.length>1?await ft(s.map(l=>()=>this.anyPointing(l)),ve):s.map(()=>!0),d=s.filter((l,g)=>a[g]).flatMap(l=>i.map(g=>async()=>({relationship:l,...await this.holdingIn(l,g)}))),c=o.mayBeAutomation,u=new Map;for(let{relationship:l,holding:g,unchecked:p,automation:m,along:b,goes:h}of await ft(d,ve)){p&&o.unchecked.add(l.childSObject),(g.size>0||m.length>0)&&o.holders.add(l.childSObject),g.forEach(R=>this.hold(o,R));for(let R of m)o.held.add(w(R.parent));c.push(...m);for(let{parent:R,key:S}of b){let j=o.along.get(R)??new Map;j.set(S,l.childSObject),o.along.set(R,j)}h.length>0&&u.set(l.childSObject,[...u.get(l.childSObject)??[],...h])}if(await this.heldBelow(u,o,n),n>0)return o;this.context.previewing!==!0&&await this.lockedPastDraft(e,t,o),$e(e)&&await this.standardPricesHeld(t,o),e===lt&&await this.sellingModelOptionsHeld(t,o),this.context.alongAccepted!==!0&&await this.automationHeldBelow(c,o);let f=await this.byAutomationOnly(e,c,o.otherwise);return o.byAutomation=f.objects,o.automationAfter=f.after,o.automationAlong=f.along,o}hold(e,t){e.held.add(t),e.otherwise.add(t)}async heldBelow(e,t,n){let o=(s,i,a,d)=>{let c=s.get(i)??new Map;c.set(a,d),s.set(i,c)};for(let[s,i]of e){let a=[...new Set(i.map(c=>c.id))],d=n+1<ro?await this.heldAmong(s,a,n+1):void 0;for(let{parent:c,id:u,came:f}of i){let l=w(u);if(!d||d.held.has(l)){this.hold(t,c),t.holders.add(s),d?.holders.forEach(g=>t.holders.add(g));continue}f&&o(t.cameAlong,c,l,s);for(let[g,p]of d.along.get(l)??[])o(t.along,c,g,p);for(let[g,p]of d.cameAlong.get(l)??[])o(t.cameAlong,c,g,p)}d?.unchecked.forEach(c=>t.unchecked.add(c))}}async automationHeldBelow(e,t){let n=new Map;for(let o of e)t.otherwise.has(w(o.parent))||n.set(o.object,[...n.get(o.object)??[],o]);for(let[o,s]of n){let i=await this.heldAmong(o,[...new Set(s.map(a=>a.id))],1);for(let a of s){let d=w(a.id),c=i.mayBeAutomation.some(u=>w(u.parent)===d&&u.creator!==a.creator);!i.otherwise.has(d)&&!c||(this.hold(t,w(a.parent)),i.holders.forEach(u=>t.holders.add(u)))}i.unchecked.forEach(a=>t.unchecked.add(a))}}async byAutomationOnly(e,t,n){let o=new Map,s=new Set,i=t.filter(f=>!n.has(w(f.parent)));if(i.length===0)return{objects:o,after:s,along:new Set};let a;try{let f=await z(this.org,e,["CreatedDate","CreatedById"],[...new Set(i.map(l=>l.parent))]);a=new Map(f.flatMap(l=>typeof l.Id=="string"?[[w(l.Id),l]]:[]))}catch{return{objects:o,after:s,along:new Set}}let d=new Set,c=new Set;for(let f of i){let l=w(f.parent),g=a.get(l),p=q(g?.CreatedDate),m=g?.CreatedById,b=this.context.runUser??(typeof m=="string"?w(m):void 0),h=f.created-p;if(!(b!==void 0&&f.creator===b&&h>=-2e3&&h<=6e4)){d.add(l);continue}let S=o.get(l)??new Set;S.add(f.object),o.set(l,S),f.created>this.context.runEnd&&s.add(l),f.along||c.add(l)}for(let f of d)o.delete(f),s.delete(f);let u=new Set([...o.keys()].filter(f=>!c.has(f)));return{objects:o,after:s,along:u}}async holdingIn(e,t){let n=F(e.childSObject),o=F(e.field),[s]=ee(t,t.length),i=new Set(["Id",o,...Mt[n]?.ends??[],...e.personContacts?[et]:[]]),a=this.datesKept.get(n)??0;for(;a<nt.length;){let d=nt[a],c;try{c=await this.org.query(`SELECT ${[...i,...d].join(", ")} FROM ${n} WHERE ${o} IN (${s}) LIMIT ${Xe}`)}catch(b){uo(b)?(a=fo(b,a),this.datesKept.set(n,a)):a++;continue}if(c.records.length>=Xe)return{holding:new Set(t.map(w)),automation:[],along:[],goes:[],unchecked:!1};let u=new Set,f=[],l=[],g=[],p=new Map;for(let b of c.records){if(typeof b!="object"||b===null)continue;let h=b,R=h[e.field];if(typeof R!="string"||typeof h.Id!="string"||(n===Vn&&o==="LinkedEntityId"&&this.noteFile(h),this.lockedUnder.get(w(h.Id))===w(R)))continue;let S={onlyIncluded:!1};if(!this.stays(h,n,e.restricted,e.personContacts,S)){if(S.onlyIncluded&&l.push({parent:w(R),key:w(h.Id)}),n!==Vn&&this.goesAlongUnread(h)){let U=!(Mt[n]?.cameWithRun(h,this.context.runRecords)===!0||e.personContacts===!0&&h[et]===!0)&&!S.onlyIncluded&&S.byRemoval!==!0&&this.context.goesWithParent?.(h,this.context.runEnd)!==!0;g.push({parent:w(R),id:h.Id,came:U})}continue}let j=this.mayBeAutomation(h);if(j){let _={parent:R,id:h.Id,object:n,along:!e.restricted,...j};f.push(_),e.restricted&&p.set(h.Id,_)}else u.add(w(R))}let m=await this.ofOtherParts(n,[...p.keys()]);for(let[b,h]of p)m.has(w(b))&&(f.splice(f.indexOf(h),1),u.add(w(h.parent)));return{holding:u,automation:f,along:l,goes:g,unchecked:!1}}return{holding:new Set,automation:[],along:[],goes:[],unchecked:!e.restricted}}goesAlongUnread(e){let t=w(e.Id),{runRecords:n,otherPartRecords:o,automationMade:s,goesWithParent:i,runEnd:a}=this.context;return this.context.alongAccepted!==!0&&!n.has(t)&&o?.has(t)!==!0&&s?.has(t)!==!0&&(this.context.goesWithParentReadBelow===!0||i?.(e,a)!==!0)}async ofOtherParts(e,t){let n=new Set,{otherPartRecords:o,otherPartObjects:s,runRecords:i}=this.context;if(t.length===0||!o||!s)return n;let a=this.cascadeEnds.get(e);a||(a=(async()=>{let u=new Set;for(let f of s)try{let l=de.parse(await this.org.describe(f));for(let g of l.childRelationships??[])g.childSObject===e&&g.cascadeDelete===!0&&u.add(g.field)}catch{}return[...u]})(),this.cascadeEnds.set(e,a));let d=await a;if(d.length===0)return n;let c;try{c=await z(this.org,e,d,t)}catch{return n}for(let u of c){if(typeof u.Id!="string")continue;let f=d.flatMap(l=>{let g=u[l];return typeof g=="string"?[w(g)]:[]});f.some(l=>i.has(l))||f.some(l=>o.has(l))&&n.add(w(u.Id))}return n}mayBeAutomation(e){let{runRecords:t,runStart:n,runEnd:o,runUser:s,otherPartRecords:i}=this.context;if(typeof e.Id!="string"||t.has(w(e.Id))||i?.has(w(e.Id))===!0||typeof e.CreatedById!="string")return;let a=w(e.CreatedById);if(s!==void 0&&a!==s)return;let d=q(e.CreatedDate);if(!(d>=n-2e3&&d<=o+6e4))return;let c=q(e.LastModifiedDate),u=typeof e.LastModifiedById=="string"?w(e.LastModifiedById):void 0;if(!(c>o&&u!==void 0&&u!==a))return{created:d,creator:a}}async anyPointing(e){try{let t=F(e.childSObject),n=F(e.field);return(await this.org.query(`SELECT Id FROM ${t} WHERE ${n} != null LIMIT 1`)).records.length>0}catch{return!0}}noteFile(e){let t=e.LinkedEntityId,n=e.ContentDocumentId;if(typeof t!="string"||typeof n!="string"||je(n,this.context.runRecords))return;let o=this.files.get(w(t))??new Set;o.add(n),this.files.set(w(t),o)}async filesOn(e){let t=new Map;for(let s of e){let i=this.files.get(w(s));i&&i.size>0&&t.set(w(s),[...i])}let n=[...new Set([...t.values()].flat())];if(n.length===0)return new Map;let o=new Map;try{for(let s of await z(this.org,so,["Title"],n))typeof s.Id=="string"&&typeof s.Title=="string"&&s.Title!==""&&o.set(w(s.Id),s.Title)}catch{}return new Map([...t].map(([s,i])=>[s,i.map(a=>({key:w(a),name:o.get(w(a))??a}))]))}async lockedPastDraft(e,t,n){for(let[o,s]of Object.entries(en)){let i=s.find(l=>l.object===e)?.lookup,a=Oe[o];if(!i||!a)continue;let d=await this.statusCategoriesOf(a);if(!d)continue;let c,u;try{c=await z(this.org,e,[i],t);let l=[...new Set(c.map(g=>g[i]).filter(g=>typeof g=="string"))];u=l.length>0?await z(this.org,o,["Status"],l):[]}catch{continue}let f=new Set(u.filter(l=>{let g=d.categoryOf.get(String(l.Status));return g!==void 0&&g!=="Draft"}).map(l=>w(String(l.Id))));for(let l of c){let g=l[i];typeof l.Id!="string"||typeof g!="string"||f.has(w(g))&&(this.hold(n,w(l.Id)),n.holders.add(o),this.lockedUnder.set(w(l.Id),w(g)))}}}statusCategoriesOf(e){let t=this.statuses.get(e);return t||(t=qe(be(this.org),e),this.statuses.set(e,t)),t}async standardPricesHeld(e,t){try{let n=be(this.org),o=[...await Ee(n,e)];if(o.length===0)return;let s=await this.priceKeyFields(),i=await z(this.org,fe,s,o),a=await this.pricesOfProducts(i,s),d=a.flatMap(l=>typeof l.Id=="string"?[l.Id]:[]),c=new Set([...await Ee(n,d)].map(w)),u=new Set(e.map(w)),f=new Set;for(let l of a){if(typeof l.Id!="string")continue;let g=w(l.Id);if(c.has(g))continue;(u.has(g)?t.held.has(g):this.stays(l,fe,!0))&&f.add(tt(l,s))}for(let l of i)typeof l.Id!="string"||!f.has(tt(l,s))||(this.hold(t,w(l.Id)),t.holders.add(fe))}catch{}}async sellingModelOptionsHeld(e,t){let n=[ke,ct];try{let o=await z(this.org,lt,n,e),s=await this.pricesOfProducts(o,[...n,"IsActive"]),i=new Set(s.filter(a=>typeof a.Id=="string"&&a.IsActive===!0&&this.stays(a,fe,!0)).map(a=>tt(a,n)));for(let a of o)typeof a.Id!="string"||!i.has(tt(a,n))||(this.hold(t,w(a.Id)),t.holders.add(fe))}catch{}}async priceKeyFields(){let e=de.parse(await this.org.describe(fe)),t=new Set(e.fields.map(n=>n.name));return[ke,...[ct,tn].filter(n=>t.has(n))]}async pricesOfProducts(e,t){let n=[...new Set(e.map(i=>i[ke]).filter(i=>typeof i=="string"))],o=[...new Set(["Id",...t])].map(F).join(", "),s=[];for(let i of ee(n,Io)){let a=await this.org.query(`SELECT ${o} FROM ${fe} WHERE ${ke} IN (${i}) LIMIT ${Xe}`);if(a.records.length>=Xe)throw new Error("More prices than one read takes.");for(let d of a.records)typeof d=="object"&&d!==null&&s.push(d)}return s}stays(e,t,n=!1,o=!1,s){let i=w(e.Id),{runRecords:a,reached:d,runStart:c,runEnd:u,removalStart:f,removalUser:l,earlierRemovals:g,includeChanged:p}=this.context;if(a.has(i))return d.has(i)||this.context.stays(i);if(n)return!0;if(this.context.automationMade?.has(i)===!0||this.context.goesWithParent?.(e,u)===!0||this.context.alongToDraft?.has(i)===!0||Mt[t]?.cameWithRun(e,a))return!1;if(o&&e[et]===!0)return!(q(e.LastModifiedDate??e.SystemModstamp)<=u)&&!p;let m="CreatedDate"in e?"CreatedDate":"SystemModstamp"in e?"SystemModstamp":void 0;if(!m)return!0;let b=q(e[m]),h=q(m==="CreatedDate"?e.LastModifiedDate:e.SystemModstamp);if(!(b>=c))return!0;let R=this.context.linkedLater?.get(i);if(R&&(b<=u||b>=R.start)&&h<=R.end)return!1;let S=typeof e.CreatedById=="string"?w(e.CreatedById):void 0,j=(U,k)=>U!==void 0&&(U===l&&k>=f||g.some(O=>U===O.user&&k>=O.start&&k<=O.end));if(j(S,b))return s&&(s.byRemoval=!0),!1;if(h<=u)return!1;let _=typeof e.LastModifiedById=="string"?w(e.LastModifiedById):void 0;return b<=u&&j(_,h)?!1:(p&&s&&(s.onlyIncluded=!0),!p)}workedObjects(){return this.worked??=an(this.org),this.worked}};var Po="encryptedstring";async function Co(r){try{let[e]=await r("SELECT PermissionsViewEncryptedData FROM UserPermissionAccess");return e?.PermissionsViewEncryptedData===!0}catch{return!1}}function Mi(r){let e;return()=>(e??=Co(r),e)}function Li(r,e){let t=new Map;return n=>{let o=t.get(n);return o||(o=(async()=>{let s;try{s=(await e(n)).fields.filter(a=>a.type===Po).map(a=>a.name)}catch{return[]}return s.length>0&&!await r()?s:[]})(),t.set(n,o)),o}}var me=5,qt=25,Ut=3;function Bi(r){return{get version(){return r.version},request:async e=>await r.request(e),query:async(e,t)=>await r.query(e,{scanAll:t?.scanAll===!0}),queryMore:async e=>await r.queryMore(e)}}var oe=class extends Error{constructor(){super("The read was stopped."),this.name="OrgReadStopped"}},No="PROCESSING_HALTED",ar="If-Modified-Since",jo=/^\d{1,3}\.\d$/,vo=/^\/services\/data\/v\d{1,3}\.\d\/query(?:All)?\/[A-Za-z0-9-]+$/,Mo=W({records:X(Fe(x(),Ae())),done:$(),totalSize:ue().optional(),nextRecordsUrl:x().optional()}).loose(),Lo=W({compositeResponse:X(W({body:Ae(),httpStatusCode:ue(),referenceId:x()}).loose())}),To=X(W({errorCode:x().optional(),message:x().optional()}).loose());function xo(r,e,t){if(!jo.test(r))throw new Error(`Not an API version: ${r}`);if(e.length>me)throw new Error(`A composite runs ${me} queries, not ${e.length}`);if(e.length+t.length>qt)throw new Error(`A composite holds ${qt} subrequests, not ${e.length+t.length}`);let n=`/services/data/v${r}`;return{allOrNone:!1,compositeRequest:[...e.map((o,s)=>({method:"GET",url:o.kind==="first"?`${n}/${o.scanAll?"queryAll":"query"}?q=${encodeURIComponent(o.soql)}`:o.path,referenceId:`q${s}`})),...t.map(({path:o,headers:s},i)=>({method:"GET",url:`${n}/${o}`,referenceId:`d${i}`,...s?{httpHeaders:s}:{}}))]}}function _o(r){let e=Lo.safeParse(r);if(!e.success)return;let t=new Map;for(let n of e.data.compositeResponse){if(n.httpStatusCode<400){t.set(n.referenceId,{ok:!0,status:n.httpStatusCode,body:n.body});continue}let o=To.safeParse(n.body),s=o.success?o.data[0]:void 0;t.set(n.referenceId,{ok:!1,refused:s?[s.errorCode,s.message].filter(Boolean).join(": "):`status ${n.httpStatusCode}`,halted:s?.errorCode===No})}return t}function $t(r){let e=Mo.safeParse(r);return e.success?e.data:void 0}function Bo(r){return typeof r=="object"&&r!==null&&typeof r.errorCode=="string"}function Fo(r){let e=/^https:\/\//i.test(r)?new URL(r).pathname:r;if(!vo.test(e))throw new Error(`Not the next page of a query: ${r}`);return e}function Fi(r,e){let t=new Set,n=[],o=me,s="composite",i=0,a=!1,d=!1,c=0,u=0,f=!1,l=()=>{for(let k of t)k.state==="pending"&&(k.state="idle",k.settle?.reject(new oe));for(let k of n.splice(0))k.settle.reject(new oe)},g=()=>{d||(d=!0,queueMicrotask(()=>{d=!1,R()}))},p=(k,O)=>{k.state="idle";let I=k.settle;k.ask=void 0,k.settle=void 0,O instanceof Error?I?.reject(O):I?.resolve(O)},m=async(k,O)=>{let I=xo(r.version,k.map(v=>v.ask),O),D;u++;try{D=await r.request({method:"POST",url:"/composite",body:JSON.stringify(I),headers:{"Content-Type":"application/json"}})}catch(v){if(Bo(v)){s="single";for(let L of k)L.state="pending";n.unshift(...O);return}let T=new Error(N(v));for(let L of k)p(L,T);for(let L of O)L.settle.reject(T);return}let M=_o(D);if(!M){s="single";for(let v of k)v.state="pending";n.unshift(...O);return}let H=0;if(k.forEach((v,T)=>{let L=M.get(`q${T}`);if(L&&!L.ok&&L.halted){H++,v.state="pending";return}if(!L){p(v,new Error("The org gave no answer to this query of the composite"));return}if(!L.ok){p(v,new Error(L.refused));return}let xe=$t(L.body);p(v,xe??new Error(`The org answered a query with status ${L.status} and no page`))}),H>0){let v=k.length-H;v===0?s="single":o=Math.min(o,v)}O.forEach((v,T)=>{let L=M.get(`d${T}`);L?L.ok?v.settle.resolve(L.status===304?{notModified:!0}:{body:L.body}):v.settle.reject(new Error(L.refused)):v.settle.reject(new Error("The org gave no answer to this describe of the composite"))})},b=async(k,O)=>{for(let I of k){let D=I.ask;u++;try{let M=D.kind==="first"?await r.query(D.soql,{scanAll:D.scanAll}):await r.queryMore(D.path);p(I,$t(M)??new Error("The org answered a query with no page"))}catch(M){p(I,new Error(N(M)))}}for(let I of O){u++;try{let D=await r.request({method:"GET",url:`/services/data/v${r.version}/${I.path}`,...I.headers?{headers:I.headers}:{}}),M=I.headers?.[ar]!==void 0&&(D==null||D==="");I.settle.resolve(M?{notModified:!0}:{body:D})}catch(D){I.settle.reject(new Error(N(D)))}}},h=async(k,O,I)=>{try{s==="composite"?await m(k,O):await b(k,O)}catch(D){let M=new Error(N(D));for(let H of k)H.state==="sent"&&p(H,M);for(let H of O)H.settle.reject(M)}finally{i--,I||(a=!1),g(),_()}},R=()=>{if(e?.aborted){l();return}for(;;){if(a)return;let k=[...t],O=k.filter(T=>T.state==="pending").sort((T,L)=>T.order-L.order);if(!(O.length>0&&!k.some(T=>T.state==="idle"))&&n.length===0)return;let D=O.slice(0,o),M=qt-D.length,H=s==="composite"&&n.length===0&&D.length>0&&D.every(T=>T.oneRow&&T.ask?.kind==="first");if(i>=(H?Ut:1))return;let v=n.splice(0,M);if(D.length===0&&v.length===0)return;for(let T of D)T.state="sent";i++,H||(a=!0),h(D,v,H)}},S=()=>{f=!1,g()},j=()=>{f||e===void 0||e.aborted||(e.addEventListener("abort",S,{once:!0}),f=!0)},_=()=>{!f||i>0||t.size>0||n.length>0||(e?.removeEventListener("abort",S),f=!1)},U=(k,O)=>t.has(k)?k.state!=="idle"?Promise.reject(new Error("A read asks one page at a time.")):e?.aborted?Promise.reject(new oe):new Promise((I,D)=>{k.ask=O,k.settle={resolve:I,reject:D},k.state="pending",k.order=++c,g()}):Promise.reject(new Error("This read is closed."));return{lane(k){let O={state:"idle",order:0,oneRow:k?.oneRow===!0};return t.add(O),j(),{query:(I,D)=>U(O,{kind:"first",soql:I,scanAll:D?.scanAll===!0}),queryMore:I=>{let D;try{D=Fo(I)}catch(M){return Promise.reject(M instanceof Error?M:new Error(String(M)))}return U(O,{kind:"next",path:D})},close(){t.delete(O)&&(O.state==="pending"&&p(O,new Error("This read is closed.")),g(),_())}}},describe(k,O){return e?.aborted?Promise.reject(new oe):new Promise((I,D)=>{let M=K(k),H;if(O!==void 0){let v=Date.parse(O);if(!Number.isFinite(v))throw new Error(`Not a date: ${O}`);H={[ar]:new Date(v).toUTCString()}}j(),n.push({path:`sobjects/${M}/describe`,...H?{headers:H}:{},settle:{resolve:I,reject:D}}),g()})},async tooling(k){if(e?.aborted)throw new oe;u++;let O;try{O=await r.request({method:"GET",url:`/services/data/v${r.version}/tooling/query?q=${encodeURIComponent(k)}`})}catch(D){throw new Error(N(D))}let I=$t(O);if(!I)throw new Error("The org answered a Tooling API query with no page");return I},calls:()=>u}}import{createReadStream as $o}from"node:fs";import{appendFile as qo,mkdir as Uo,rm as zo,writeFile as Ho}from"node:fs/promises";import*as he from"node:path";import{createInterface as Jo}from"node:readline";var Qo="The org stopped answering before it said the read was done: some of its records were not read.",dr=384,Wo=448;function cr(r){let e=typeof r=="number"?r:Date.parse(r);if(!Number.isFinite(e))throw new Error(`Not a date: ${String(r)}`);let t=e-(e%1e3+1e3)%1e3;return new Date(t).toISOString().replace(/\.\d{3}Z$/,"Z")}function zt(r){let e=Date.parse(r);if(!Number.isFinite(e))throw new Error(`Not a date: ${r}`);return cr(e-on)}function lr(r,e){return[...new Set([...r,...e.map(F)])].join(", ")}function Ht(r,e,t,n){let o=K(r),s=[n,e==="scanAllLive"?"IsDeleted = false":void 0].filter(i=>i!==void 0);return{objectApiName:o,soql:`SELECT ${t} FROM ${o}${s.length>0?` WHERE ${s.join(" AND ")}`:""}`,scanAll:e==="scanAllLive"}}function Vo(r){let e=K(r);return{objectApiName:e,soql:`SELECT SystemModstamp FROM ${e} ORDER BY SystemModstamp DESC LIMIT 1`,scanAll:!0}}var Ko=["Id","SystemModstamp","CreatedDate","LastModifiedDate","LastModifiedById"],Go=["Id","SystemModstamp","CreatedDate"];function Yo(r,e,t,n=[]){return Ht(r,e,lr(Ko,n),`SystemModstamp >= ${zt(t)}`)}function Zo(r,e,t=[]){let n=K(r);return{objectApiName:n,soql:`SELECT ${lr(Go,t)} FROM ${n} WHERE IsDeleted = true AND SystemModstamp >= ${zt(e)}`,scanAll:!0}}function Xo(r,e){return Ht(r,e,"COUNT()")}function Gi(r,e){let t=K(r);return{objectApiName:t,soql:`SELECT Id FROM ${t} WHERE IsDeleted = true AND SystemModstamp < ${cr(e)}`,scanAll:!0}}function Yi(r,e){return Ht(r,e,"Id")}async function es(r,e,t){let n,o,s={query:async a=>{let d=await r.query(a,{scanAll:e.scanAll});return n=d,o=d.totalSize,d},queryMore:async a=>(n=await r.queryMore(a),n)},i=0;try{for await(let a of rn(s,e.soql))await t(a),i+=a.length}catch(a){if(a instanceof oe)throw a;return{objectApiName:e.objectApiName,read:!1,rows:i,reason:N(a)}}return n?.done!==!0?{objectApiName:e.objectApiName,read:!1,rows:i,reason:Qo}:{objectApiName:e.objectApiName,read:!0,rows:i,...o!==void 0?{totalSize:o}:{}}}async function Jt(r,e,t,n,o={}){let s=o.oneRow===!0,i=new Array(e.length),a=async l=>{let g=e.slice(l,l+me),p=g.map(()=>r.lane({oneRow:s})),m=await Promise.allSettled(g.map(async(b,h)=>{let R=p[h];try{return await es(R,b,S=>t(l+h,S))}finally{R.close()}}));for(let[b,h]of m.entries()){if(h.status==="rejected")throw h.reason instanceof Error?h.reason:new Error(String(h.reason));i[l+b]=h.value}},d=0,c=async()=>{for(;d<e.length;){if(n?.aborted)throw new oe;let l=d;d+=me,await a(l)}},u=Math.ceil(e.length/me),f=await Promise.allSettled(Array.from({length:Math.min(s?Ut:1,u)},c));for(let l of f)if(l.status==="rejected")throw l.reason instanceof Error?l.reason:new Error(String(l.reason));if(n?.aborted)throw new oe;return i}function ts(r){return`${JSON.stringify(Object.fromEntries(Object.entries(r).filter(([e])=>e!=="attributes")))}
8
8
  `}async function ns(r,e,t){for(let o of e)await Uo(he.dirname(o.file),{recursive:!0,mode:Wo}),await Ho(o.file,"",{encoding:"utf8",mode:dr});let n=await Jt(r,e,async(o,s)=>{s.length!==0&&await qo(e[o].file,s.map(ts).join(""),{encoding:"utf8",mode:dr})},t);return await Promise.all(n.map((o,s)=>o.read?void 0:zo(e[s].file,{force:!0}))),n}async function*Zi(r){let e=$o(r,{encoding:"utf8"}),t=Jo({input:e,crlfDelay:1/0});try{for await(let n of t){if(n==="")continue;let o=JSON.parse(n);if(typeof o!="object"||o===null||Array.isArray(o))throw new Error(`${he.basename(r)} holds a line that is no record.`);yield o}}finally{t.close(),e.destroy()}}async function rs(r,e,t,n){let o=Date.parse(zt(t)),s=[];return(await Jt(r,e.map(Vo),(a,d)=>{d.length>0&&(s[a]=d[0].SystemModstamp)},n,{oneRow:!0})).map((a,d)=>{if(!a.read)return{objectApiName:a.objectApiName,unread:a.reason};if(s[d]===void 0)return{objectApiName:a.objectApiName,latest:null,moved:!1};let c=sn(s[d]);return c===null?{objectApiName:a.objectApiName,unread:`${a.objectApiName} answered a SystemModstamp that is not a date.`}:{objectApiName:a.objectApiName,latest:c,moved:Date.parse(c)>=o}})}async function os(r,e,t){return(await Jt(r,e.map(({objectApiName:o,readMode:s})=>Xo(o,s)),()=>{},t,{oneRow:!0})).map(o=>o.read?o.totalSize===void 0?{objectApiName:o.objectApiName,unread:"The org gave no count of its records."}:{objectApiName:o.objectApiName,count:o.totalSize}:{objectApiName:o.objectApiName,unread:o.reason})}function ss(r,e){return he.join(r,`${K(e)}.live.ndjson`)}function is(r,e){return he.join(r,`${K(e)}.deleted.ndjson`)}async function Xi(r,e,t,n,o,s){if(s!==void 0&&s.length!==e.length)throw new Error(`${s.length} pre-checks for ${e.length} objects`);let i=s??await rs(r,e.map(({objectApiName:m})=>m),t,o),a=new Map,d=[];i.forEach((m,b)=>{"unread"in m?a.set(b,m.unread):m.moved&&d.push(b)});let c=d.flatMap(m=>{let{objectApiName:b,readMode:h,fields:R=[]}=e[m],S=K(b);return[{...Yo(S,h,t,R),file:ss(n,S)},{...Zo(S,t,R),file:is(n,S)}]}),u=await ns(r,c,o),f=new Map;d.forEach((m,b)=>{let h=u[b*2],R=u[b*2+1],S=[h,R].find(j=>!j.read);if(S&&!S.read){a.set(m,S.reason);return}f.set(m,{live:{file:c[b*2].file,rows:h.rows},deleted:{file:c[b*2+1].file,rows:R.rows}})});let l=e.map((m,b)=>({object:m,index:b})).filter(({object:m,index:b})=>!a.has(b)&&(f.has(b)||m.held)).map(({index:m})=>m),g=await os(r,l.map(m=>e[m]),o),p=new Map;return l.forEach((m,b)=>{let h=g[b];"unread"in h?a.set(m,h.unread):p.set(m,h.count)}),i.map((m,b)=>{if("unread"in m)return m;let h=a.get(b);if(h!==void 0)return{objectApiName:m.objectApiName,unread:h};let R=f.get(b),S=p.get(b);return{objectApiName:m.objectApiName,latest:m.latest,moved:m.moved,...R?.live?{live:R.live}:{},...R?.deleted?{deleted:R.deleted}:{},...S!==void 0?{count:S}:{}}})}import{randomBytes as as}from"node:crypto";import{createReadStream as ds}from"node:fs";import{appendFile as cs,open as gr,readFile as ls,rename as us,rm as fs}from"node:fs/promises";import{join as Wt}from"node:path";import{createInterface as gs}from"node:readline";var ps=2e3,ce=15,pr=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,ms=2e3,mr="spool.json",Te="a rewind";function Qt(r){return typeof r=="string"&&pr.test(r)?r.slice(0,ce):void 0}var st=class{bytes=Buffer.alloc(ce*1024);flags=new Uint16Array(1024);slots=new Uint32Array(2048);used=0;get size(){return this.used}find(e){let t=this.slots.length-1;for(let n=ht(e)&t;;n=n+1&t){let o=this.slots[n];if(o===0)return-1;if(this.holds(o-1,e))return o-1}}holds(e,t){let n=e*ce;for(let o=0;o<ce;o++)if(this.bytes[n+o]!==t.charCodeAt(o))return!1;return!0}keyAt(e){let t=e*ce;return this.bytes.toString("latin1",t,t+ce)}place(e,t){let n=this.slots.length-1,o=ht(t)&n;for(;this.slots[o]!==0;)o=o+1&n;this.slots[o]=e+1}add(e,t=0){let n=Qt(e);if(n===void 0)throw new RangeError(`Not a Salesforce id: ${String(e)}`);let o=this.find(n);if(o>=0)return this.flags[o]|=t,!1;if((this.used+1)*2>this.slots.length){let s=this.slots;this.slots=new Uint32Array(s.length*2);for(let i of s)i!==0&&this.place(i-1,this.keyAt(i-1))}if((this.used+1)*ce>this.bytes.length){let s=Buffer.alloc(this.bytes.length*2);this.bytes.copy(s),this.bytes=s;let i=new Uint16Array(this.flags.length*2);i.set(this.flags),this.flags=i}return this.bytes.write(n,this.used*ce,ce,"latin1"),this.flags[this.used]=t,this.place(this.used,n),this.used++,!0}has(e){let t=Qt(e);return t!==void 0&&this.find(t)>=0}count(e){let t=0;for(let n=0;n<this.used;n++)e(this.flags[n])&&t++;return t}flagsOf(e){let t=Qt(e);if(t===void 0)return 0;let n=this.find(t);return n<0?0:this.flags[n]}},hs=W({version:Zt(1),objects:X(W({objectApiName:x().min(1),count:ue().int().nonnegative()}))});function Vt(r,e){return Wt(r,`${K(e)}.ids`)}async function ys(r,e){let t=`${r}.${process.pid}-${as(4).toString("hex")}.tmp`,n=await gr(t,"wx",pt);try{try{await n.writeFile(e,"utf8"),await n.sync()}finally{await n.close()}await us(t,r)}catch(o){throw await fs(t,{force:!0}),o}}async function bs(r){let e=await gr(r,"r+");try{await e.sync()}finally{await e.close()}}async function ws(r,e,t=Te){for(let{objectApiName:n,count:o}of e)o>0&&await bs(Vt(r,n));return await ys(Wt(r,mr),`${JSON.stringify({version:1,objects:e})}
9
9
  `),new it(r,e,t)}var ur=class{constructor(e,t=Te){this.dir=e;this.act=t}dir;act;order=[];counts=new Map;lines=new Map;written=new Set;keys=new st;made=!1;async add(e,t){if(!this.keys.add(t))return!1;let n=this.lines.get(e);return n||(K(e),n=[],this.lines.set(e,n),this.order.push(e)),n.push(t),this.counts.set(e,(this.counts.get(e)??0)+1),n.length>=ms&&await this.flush(e),!0}async flush(e){let t=this.lines.get(e)??[];this.made||(await mt(this.dir),this.made=!0);let n=!this.written.has(e);t.length===0&&!n||(await cs(Vt(this.dir,e),t.map(o=>`${o}
10
10
  `).join(""),{encoding:"utf8",mode:pt,flag:n?"w":"a"}),this.written.add(e),this.lines.set(e,[]))}get objects(){return this.order.map(e=>({objectApiName:e,count:this.counts.get(e)??0}))}async finish(e){this.made||(await mt(this.dir),this.made=!0);for(let t of this.order)await this.flush(t);return ws(this.dir,e?e(this.objects):this.objects,this.act)}},it=class r{constructor(e,t,n=Te){this.dir=e;this.objects=t;this.act=n}dir;objects;act;get count(){return this.objects.reduce((e,t)=>e+t.count,0)}static async open(e,t=Te){let n;try{n=JSON.parse(await ls(Wt(e,mr),"utf8"))}catch{throw new ze("damaged",`The list of what ${t} sets out to do is not on this machine.`)}let o=hs.safeParse(n);if(!o.success)throw new ze("damaged",`The list of what ${t} sets out to do does not read as one.`);for(let{objectApiName:s}of o.data.objects)K(s);return new r(e,o.data.objects,t)}async*pages(e,t=ps){let n=this.objects.find(u=>u.objectApiName===e);if(!n||n.count===0)return;let o=()=>new ze("damaged",`The ${e} records ${this.act} sets out to act on are not as they were written.`),s=Math.max(1,Math.floor(t)),i=ds(Vt(this.dir,e),{encoding:"utf8"}),a=gs({input:i,crlfDelay:1/0}),d=0,c=[];try{for await(let u of a)if(u!==""){if(!pr.test(u))throw o();d++,c.push(u),c.length>=s&&(yield c,c=[])}}catch(u){throw u.code==="ENOENT"?o():u}finally{a.close(),i.destroy()}if(d!==n.count)throw o();c.length>0&&(yield c)}},fr=class r{constructor(e,t){this.spool=e;this.keys=t}spool;keys;static async of(e,t){return new r(await e.finish(t),e.keys)}static async open(e,t=Te){let n=await it.open(e,t),o=new st;for(let{objectApiName:s}of n.objects)for await(let i of n.pages(s))for(let a of i)o.add(a);return new r(n,o)}get objects(){return this.spool.objects}pages(e){return this.spool.pages(e)}has(e){return this.keys.has(e)}};export{He as a,yt as b,wn as c,Rn as d,de as e,Sn as f,Or as g,Dr as h,Ir as i,Pr as j,Cr as k,Ps as l,Je as m,wt as n,Ve as o,De as p,$s as q,Et as r,xr as s,Br as t,Pn as u,Nn as v,Dt as w,jn as x,vn as y,Mn as z,Ke as A,It as B,Ur as C,Pt as D,Qs as E,Ln as F,Wn as G,Re as H,Qr as I,Lt as J,pe as K,ki as L,Oi as M,Ei as N,Di as O,Ii as P,Pi as Q,Ci as R,Po as S,Co as T,Mi as U,Li as V,me as W,qt as X,Ut as Y,Bi as Z,oe as _,Fi as $,cr as aa,zt as ba,Xo as ca,Gi as da,Yi as ea,es as fa,Jt as ga,ns as ha,Zi as ia,rs as ja,os as ka,ss as la,is as ma,Xi as na,ps as oa,st as pa,Vt as qa,ws as ra,ur as sa,it as ta,fr as ua};