sandforge 1.81.0 → 1.82.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 (208) hide show
  1. package/README.md +48 -0
  2. package/bin/sandforge-users.mjs +12 -0
  3. package/lib/{chunk-C4YGSK6W.mjs → chunk-27Z76O2O.mjs} +1 -1
  4. package/lib/{chunk-TKQQVB2D.mjs → chunk-2JZGCCPG.mjs} +1 -1
  5. package/lib/{chunk-TPHXRHOA.mjs → chunk-2UU42PTD.mjs} +1 -1
  6. package/lib/{chunk-ZWZXQTAK.mjs → chunk-32EUNQT6.mjs} +14 -14
  7. package/lib/{chunk-HYOOJVR6.mjs → chunk-3C2ZZIFN.mjs} +1 -1
  8. package/lib/{chunk-AELFEK3G.mjs → chunk-3CX7GPCR.mjs} +1 -1
  9. package/lib/{chunk-YJEXE6HZ.mjs → chunk-3HEMJTAP.mjs} +2 -2
  10. package/lib/{chunk-DQR5NDMI.mjs → chunk-3HROD5RE.mjs} +1 -1
  11. package/lib/{chunk-D7P7DTWL.mjs → chunk-3MGMNK3Q.mjs} +1 -1
  12. package/lib/{chunk-MNITSYI2.mjs → chunk-3SKLBRPL.mjs} +1 -1
  13. package/lib/{chunk-MAHZMPMZ.mjs → chunk-3XG25GTF.mjs} +1 -1
  14. package/lib/{chunk-N7J6NJQ6.mjs → chunk-42BFLWHR.mjs} +1 -1
  15. package/lib/chunk-466F37VD.mjs +7 -0
  16. package/lib/chunk-47UHTN3Q.mjs +7 -0
  17. package/lib/{chunk-DHGPDSXS.mjs → chunk-52EXDVPN.mjs} +1 -1
  18. package/lib/{chunk-5344TZBT.mjs → chunk-5K2I2DMP.mjs} +1 -1
  19. package/lib/{chunk-2OZG6GRW.mjs → chunk-6GQUZ4IP.mjs} +1 -1
  20. package/lib/{chunk-SW2NUKQL.mjs → chunk-6KP6WETK.mjs} +1 -1
  21. package/lib/{chunk-FSZTXLNW.mjs → chunk-6VSZNZHH.mjs} +1 -1
  22. package/lib/{chunk-6NADW3OI.mjs → chunk-7CVDVBEE.mjs} +1 -1
  23. package/lib/{chunk-67CC7RAE.mjs → chunk-7EYQYZJP.mjs} +1 -1
  24. package/lib/{chunk-IBURU7T7.mjs → chunk-7LKI7OAS.mjs} +1 -1
  25. package/lib/{chunk-CULAOP3U.mjs → chunk-7PY3VQP3.mjs} +1 -1
  26. package/lib/chunk-7SDZR6SR.mjs +7 -0
  27. package/lib/{chunk-V4RKM4QZ.mjs → chunk-7WSLT5VX.mjs} +1 -1
  28. package/lib/chunk-A32ISQ6M.mjs +28 -0
  29. package/lib/{chunk-K77NR3UK.mjs → chunk-A65ADTCR.mjs} +1 -1
  30. package/lib/chunk-A7JJWOLT.mjs +7 -0
  31. package/lib/{chunk-MWLFFVQV.mjs → chunk-AUS6NFLZ.mjs} +1 -1
  32. package/lib/{chunk-NWPQF5XR.mjs → chunk-BMTNTBBM.mjs} +1 -1
  33. package/lib/{chunk-FTA5LOVX.mjs → chunk-BN33LVPQ.mjs} +1 -1
  34. package/lib/chunk-BNKT3R3F.mjs +7 -0
  35. package/lib/{chunk-WM5JI4JI.mjs → chunk-C2N2TNEU.mjs} +1 -1
  36. package/lib/{chunk-5UT2ZBGF.mjs → chunk-C3LNYAVJ.mjs} +1 -1
  37. package/lib/{chunk-GYKNCYES.mjs → chunk-CBL42DUU.mjs} +1 -1
  38. package/lib/{chunk-W2AAGIZF.mjs → chunk-CCEH7L53.mjs} +1 -1
  39. package/lib/{chunk-WWTXRWNZ.mjs → chunk-CELEBWEZ.mjs} +1 -1
  40. package/lib/{chunk-D62KWDDT.mjs → chunk-CV47FDQW.mjs} +1 -1
  41. package/lib/{chunk-AJPSGVMD.mjs → chunk-CZLJZQCS.mjs} +1 -1
  42. package/lib/{chunk-YIGFYZQY.mjs → chunk-DBBPDSFN.mjs} +1 -1
  43. package/lib/{chunk-T5VAULLQ.mjs → chunk-DIL62SUN.mjs} +1 -1
  44. package/lib/chunk-DIS254AN.mjs +7 -0
  45. package/lib/{chunk-GK7VEYFM.mjs → chunk-DJCGURW7.mjs} +1 -1
  46. package/lib/{chunk-MHW6DV6T.mjs → chunk-DT3T7FRD.mjs} +1 -1
  47. package/lib/{chunk-PYUEHBA6.mjs → chunk-DWMRIWV5.mjs} +1 -1
  48. package/lib/{chunk-E2OBAWSH.mjs → chunk-EEFUE2ES.mjs} +1 -1
  49. package/lib/{chunk-MKNAZPOT.mjs → chunk-EOFO3PHS.mjs} +1 -1
  50. package/lib/{chunk-UUSLTW5V.mjs → chunk-FA4ZKDCU.mjs} +1 -1
  51. package/lib/{chunk-DHIW4IO5.mjs → chunk-FKK5YBGZ.mjs} +1 -1
  52. package/lib/{chunk-BZFIOZS3.mjs → chunk-FOIWWK7G.mjs} +1 -1
  53. package/lib/chunk-FZF23M6R.mjs +7 -0
  54. package/lib/{chunk-XIZ5LMQM.mjs → chunk-G2JR3F63.mjs} +1 -1
  55. package/lib/{chunk-2Z54GB6X.mjs → chunk-GBGHJTPC.mjs} +1 -1
  56. package/lib/{chunk-2NAIUKVL.mjs → chunk-GCGHHN4K.mjs} +1 -1
  57. package/lib/{chunk-TQM2XJ27.mjs → chunk-GGNUACTY.mjs} +1 -1
  58. package/lib/{chunk-2IB7I3IQ.mjs → chunk-GGUOIDWP.mjs} +1 -1
  59. package/lib/chunk-GHPR5UVV.mjs +7 -0
  60. package/lib/{chunk-YHIOS2PU.mjs → chunk-GJ6SZVHT.mjs} +1 -1
  61. package/lib/{chunk-WI4HYWV6.mjs → chunk-H4JUYUSL.mjs} +1 -1
  62. package/lib/{chunk-5WGA5CZB.mjs → chunk-H4OBZIX3.mjs} +1 -1
  63. package/lib/{chunk-KRNFVAGC.mjs → chunk-HFUDCNU5.mjs} +1 -1
  64. package/lib/{chunk-OIIL4NVI.mjs → chunk-HIHCYMSL.mjs} +1 -1
  65. package/lib/chunk-HKUWHVI7.mjs +9 -0
  66. package/lib/chunk-HQQVANWQ.mjs +20 -0
  67. package/lib/{chunk-V2QO6KOE.mjs → chunk-IRZJU2PG.mjs} +14 -11
  68. package/lib/{chunk-CAFUNR6D.mjs → chunk-ISSP2FZ5.mjs} +1 -1
  69. package/lib/{chunk-OEHVAJAB.mjs → chunk-IVZJSDJD.mjs} +1 -1
  70. package/lib/{chunk-E2YJVSX6.mjs → chunk-J24TIGSI.mjs} +1 -1
  71. package/lib/{chunk-YCSFP6ER.mjs → chunk-JESRFE2Z.mjs} +1 -1
  72. package/lib/{chunk-KOQV4WXC.mjs → chunk-JFNLKHY6.mjs} +2 -2
  73. package/lib/{chunk-NJ3EOEHS.mjs → chunk-JH27IKCO.mjs} +1 -1
  74. package/lib/{chunk-DXOXLUZA.mjs → chunk-JJITOWZK.mjs} +1 -1
  75. package/lib/{chunk-KNIRA333.mjs → chunk-JKT5YAQ2.mjs} +1 -1
  76. package/lib/{chunk-J6G23RUI.mjs → chunk-JLZRZL5E.mjs} +1 -1
  77. package/lib/{chunk-6FMLW7PH.mjs → chunk-JPEVIXNH.mjs} +1 -1
  78. package/lib/{chunk-6IGEASOF.mjs → chunk-JQZTMFO7.mjs} +1 -1
  79. package/lib/{chunk-55LQD3Y3.mjs → chunk-KIMQQ6JQ.mjs} +1 -1
  80. package/lib/{chunk-EH5YUA5W.mjs → chunk-KJYEQHYP.mjs} +1 -1
  81. package/lib/chunk-KKOA62S4.mjs +474 -0
  82. package/lib/{chunk-56MPPWLA.mjs → chunk-KP5G6FUC.mjs} +1 -1
  83. package/lib/{chunk-EAFLDSQ2.mjs → chunk-L4INJ5TZ.mjs} +1 -1
  84. package/lib/{chunk-MO3N5XVV.mjs → chunk-LAUOSXMN.mjs} +2 -2
  85. package/lib/{chunk-HVC5CYIB.mjs → chunk-LHU6CPGE.mjs} +1 -1
  86. package/lib/{chunk-7PK5QDQI.mjs → chunk-LXDSRP2W.mjs} +1 -1
  87. package/lib/{chunk-YOGMP72T.mjs → chunk-MKTXJCXN.mjs} +1 -1
  88. package/lib/{chunk-VSU74RQ3.mjs → chunk-MUEQRIK7.mjs} +1 -1
  89. package/lib/{chunk-UCHAZ4ZU.mjs → chunk-NLB3RGIY.mjs} +1 -1
  90. package/lib/{chunk-OVOLG3AL.mjs → chunk-NWOI25WY.mjs} +1 -1
  91. package/lib/{chunk-6SEDOIO3.mjs → chunk-O2PUGRNW.mjs} +1 -1
  92. package/lib/chunk-O4BROUGM.mjs +7 -0
  93. package/lib/{chunk-KGYXLSQ5.mjs → chunk-P55MKIZX.mjs} +1 -1
  94. package/lib/{chunk-KE2PGD6C.mjs → chunk-P63WJMXQ.mjs} +1 -1
  95. package/lib/chunk-PBE44M2Y.mjs +7 -0
  96. package/lib/{chunk-OMZJ37JI.mjs → chunk-PE435FVH.mjs} +2 -2
  97. package/lib/{chunk-GR3NGDVM.mjs → chunk-PPHVWUFY.mjs} +1 -1
  98. package/lib/{chunk-ZUA5BNAO.mjs → chunk-PR74GYVI.mjs} +1 -1
  99. package/lib/{chunk-43K2C6H2.mjs → chunk-PWVDNN2C.mjs} +1 -1
  100. package/lib/{chunk-DMBR24CK.mjs → chunk-PYRZFUVU.mjs} +1 -1
  101. package/lib/{chunk-OXKZ4Y3B.mjs → chunk-Q3DY7TO2.mjs} +1 -1
  102. package/lib/{chunk-EOSEMFPU.mjs → chunk-Q6SXNKV2.mjs} +1 -1
  103. package/lib/chunk-QAPVKPEC.mjs +7 -0
  104. package/lib/chunk-QROPNEGY.mjs +14 -0
  105. package/lib/{chunk-6CDIIFNX.mjs → chunk-RCYEBY42.mjs} +1 -1
  106. package/lib/chunk-RLWB7F26.mjs +7 -0
  107. package/lib/{chunk-X2ZVSQ54.mjs → chunk-RTWYLOCA.mjs} +1 -1
  108. package/lib/chunk-RYRMUPMY.mjs +7 -0
  109. package/lib/{chunk-ETT5GP4P.mjs → chunk-SAMWHL22.mjs} +1 -1
  110. package/lib/{chunk-LO527YLT.mjs → chunk-SFGZFB4F.mjs} +1 -1
  111. package/lib/{chunk-33ZX3A56.mjs → chunk-SNEOKYV7.mjs} +1 -1
  112. package/lib/{chunk-GTIXJCGS.mjs → chunk-STRMWSIQ.mjs} +1 -1
  113. package/lib/{chunk-OQQHNYR7.mjs → chunk-SZGGFST2.mjs} +2 -2
  114. package/lib/{chunk-OU5W7SCB.mjs → chunk-T7WREYA5.mjs} +1 -1
  115. package/lib/{chunk-FLNLG43R.mjs → chunk-TCBAE65A.mjs} +1 -1
  116. package/lib/{chunk-RKALOKAU.mjs → chunk-TMA34QMA.mjs} +1 -1
  117. package/lib/{chunk-WEZLXE34.mjs → chunk-TWV4A5RK.mjs} +1 -1
  118. package/lib/{chunk-ONMBSACW.mjs → chunk-UHFLKP26.mjs} +1 -1
  119. package/lib/chunk-UV74P4H2.mjs +7 -0
  120. package/lib/{chunk-HYBH5PFM.mjs → chunk-V3R45ZWT.mjs} +1 -1
  121. package/lib/{chunk-BNO5GIJ6.mjs → chunk-VPDEJGPS.mjs} +1 -1
  122. package/lib/{chunk-3AOKLIVE.mjs → chunk-VQJMP3DC.mjs} +1 -1
  123. package/lib/{chunk-742SSN7I.mjs → chunk-VYOYXTCU.mjs} +1 -1
  124. package/lib/{chunk-GWRKS3AL.mjs → chunk-VZT4E2OJ.mjs} +1 -1
  125. package/lib/{chunk-2OIRJEYE.mjs → chunk-VZVICK7Q.mjs} +1 -1
  126. package/lib/chunk-WEMLDUQA.mjs +7 -0
  127. package/lib/{chunk-FDGFUEK3.mjs → chunk-WOOUISSO.mjs} +1 -1
  128. package/lib/{chunk-UIUPPEFB.mjs → chunk-WSUKC2U3.mjs} +1 -1
  129. package/lib/{chunk-XC2QKQT5.mjs → chunk-WT3SCUHS.mjs} +1 -1
  130. package/lib/{chunk-UT27HXE7.mjs → chunk-XFU3HRUV.mjs} +1 -1
  131. package/lib/{chunk-5VQNKDFU.mjs → chunk-XK5W7BVE.mjs} +1 -1
  132. package/lib/{chunk-OZNLOV4U.mjs → chunk-XO5FBOQF.mjs} +1 -1
  133. package/lib/{chunk-FSDO4DJA.mjs → chunk-XSKPYGMT.mjs} +1 -1
  134. package/lib/{chunk-AITNZWLB.mjs → chunk-XU25YA46.mjs} +1 -1
  135. package/lib/{chunk-XEB6HZ34.mjs → chunk-XZISAZA6.mjs} +1 -1
  136. package/lib/chunk-Y4TDVDP2.mjs +13 -0
  137. package/lib/{chunk-4L7FBOJS.mjs → chunk-YAIIRFKJ.mjs} +1 -1
  138. package/lib/{chunk-T3PLRQ2T.mjs → chunk-YAJQS3OL.mjs} +1 -1
  139. package/lib/{chunk-Y5ZCPY36.mjs → chunk-YGJF55VJ.mjs} +1 -1
  140. package/lib/chunk-YH4DYI6D.mjs +7 -0
  141. package/lib/{chunk-R6TF26V4.mjs → chunk-YMDFF657.mjs} +1 -1
  142. package/lib/{chunk-JU2XEKEO.mjs → chunk-YT22LMF7.mjs} +1 -1
  143. package/lib/{chunk-NWVVCZUK.mjs → chunk-Z42PHCVZ.mjs} +1 -1
  144. package/lib/{chunk-O6ADMP36.mjs → chunk-ZHIZY3ZC.mjs} +1 -1
  145. package/lib/chunk-ZQO5PDX5.mjs +48 -0
  146. package/lib/{chunk-QXLZINZB.mjs → chunk-ZUBBEP75.mjs} +1 -1
  147. package/lib/{chunk-SQGP46QS.mjs → chunk-ZUOPC4W2.mjs} +1 -1
  148. package/lib/{chunk-3B5H24ZG.mjs → chunk-ZUTUYBNW.mjs} +1 -1
  149. package/lib/{chunk-K55LH4ZQ.mjs → chunk-ZXFL2MSN.mjs} +1 -1
  150. package/lib/sandforge-autopilot.mjs +1 -1
  151. package/lib/sandforge-backup.mjs +1 -1
  152. package/lib/sandforge-checkpoint.mjs +1 -1
  153. package/lib/sandforge-cleanup.mjs +1 -1
  154. package/lib/sandforge-clone.mjs +1 -1
  155. package/lib/sandforge-compare.mjs +1 -1
  156. package/lib/sandforge-dataops.mjs +1 -1
  157. package/lib/sandforge-empty.mjs +1 -1
  158. package/lib/sandforge-env.mjs +185 -139
  159. package/lib/sandforge-frozen.mjs +1 -1
  160. package/lib/sandforge-mcp.mjs +14 -14
  161. package/lib/sandforge-monitor.mjs +1 -1
  162. package/lib/sandforge-pipeline.mjs +1 -1
  163. package/lib/sandforge-seed.mjs +1 -1
  164. package/lib/sandforge-sync.mjs +1 -1
  165. package/lib/sandforge-users.mjs +157 -0
  166. package/lib/sandforge.mjs +1 -22
  167. package/lib/sf/sandforge/autopilot.mjs +20 -0
  168. package/lib/sf/sandforge/backup.mjs +20 -0
  169. package/lib/sf/sandforge/checkpoint.mjs +20 -0
  170. package/lib/sf/sandforge/cleanup.mjs +20 -0
  171. package/lib/sf/sandforge/clone.mjs +20 -0
  172. package/lib/sf/sandforge/compare.mjs +20 -0
  173. package/lib/sf/sandforge/dataops.mjs +20 -0
  174. package/lib/sf/sandforge/empty.mjs +20 -0
  175. package/lib/sf/sandforge/env.mjs +20 -0
  176. package/lib/sf/sandforge/frozen.mjs +20 -0
  177. package/lib/sf/sandforge/hardis-commands.mjs +20 -0
  178. package/lib/sf/sandforge/index.mjs +20 -0
  179. package/lib/sf/sandforge/mcp.mjs +20 -0
  180. package/lib/sf/sandforge/monitor.mjs +20 -0
  181. package/lib/sf/sandforge/pipeline.mjs +20 -0
  182. package/lib/sf/sandforge/seed.mjs +20 -0
  183. package/lib/sf/sandforge/sync.mjs +20 -0
  184. package/lib/sf/sandforge/users.mjs +20 -0
  185. package/lib/sfHelpHook.mjs +7 -0
  186. package/lib/sfPlugin.mjs +11 -0
  187. package/oclif.manifest.json +1 -0
  188. package/package.json +17 -3
  189. package/lib/chunk-2ZMGVBLW.mjs +0 -7
  190. package/lib/chunk-5C5XEVZN.mjs +0 -11
  191. package/lib/chunk-5CKWGZX4.mjs +0 -9
  192. package/lib/chunk-5ZKCLBTN.mjs +0 -474
  193. package/lib/chunk-7DALDJMO.mjs +0 -7
  194. package/lib/chunk-DPYTG6DM.mjs +0 -48
  195. package/lib/chunk-G4VXPS3A.mjs +0 -7
  196. package/lib/chunk-GF247DA7.mjs +0 -7
  197. package/lib/chunk-IKGHRYCN.mjs +0 -7
  198. package/lib/chunk-IM2XA6JI.mjs +0 -7
  199. package/lib/chunk-K5HV4YRO.mjs +0 -7
  200. package/lib/chunk-N6HHNR6J.mjs +0 -7
  201. package/lib/chunk-O7DAFE6M.mjs +0 -14
  202. package/lib/chunk-R2BJWO5N.mjs +0 -20
  203. package/lib/chunk-T26C576X.mjs +0 -9
  204. package/lib/chunk-V473C7LY.mjs +0 -7
  205. package/lib/chunk-WD47PGUS.mjs +0 -10
  206. package/lib/chunk-XC54KKKC.mjs +0 -7
  207. package/lib/chunk-XGKSSCW7.mjs +0 -7
  208. package/lib/chunk-ZWCRWF7E.mjs +0 -7
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{b as ie,c as se,d as Vt,e as Jt,f as be}from"./chunk-AITNZWLB.mjs";import{a as Zt,e as Xt}from"./chunk-6SEDOIO3.mjs";import{J as re,P as Ue,a as Kt}from"./chunk-ZWCRWF7E.mjs";import{f as Le,p as ge,s as Be,u as Yt,w as $e}from"./chunk-MNITSYI2.mjs";import{c as qt}from"./chunk-T26C576X.mjs";import{b as me,d as ue}from"./chunk-BNO5GIJ6.mjs";import{G as Ht}from"./chunk-XEB6HZ34.mjs";import{c as Gt,e as Fe,g as Me,h as pe}from"./chunk-TZE3Y7IQ.mjs";import{c as Wt}from"./chunk-EAFLDSQ2.mjs";import{a as $t,b as V}from"./chunk-CA5NAXSU.mjs";import{C as dt,D as pt,E as mt,Ea as zt,F as ut,Fa as St,Gc as Nt,J as gt,K as bt,Ka as ae,Kb as wt,L as ft,La as Ae,M as yt,Mb as vt,N as ht,Nb as At,Pa as M,Qa as xt,Qb as Et,Qc as Dt,Ra as F,Rb as Ct,Rc as Ft,Sa as Ee,Sb as Tt,Sc as Mt,Ta as It,Td as Lt,Ua as kt,Uc as Ut,Ud as Bt,Va as Ce,Vc as De,Wa as Te,Xa as _e,Zb as _t,cb as Ne,fb as jt,gb as Pt,hb as Ot,n as rt,s as we,t as it,tb as Rt,u as st,v as ct,w as ne,y as lt,z as ve}from"./chunk-DPYTG6DM.mjs";import{b as a,c as Oe,e as g,f as r,g as et,i as D,k as c,l as o,m as tt,o as de,p as Re,s as x,u as w,v,w as ot,x as nt,y as G,z as at}from"./chunk-WZQEK4WT.mjs";function sa(e,t,n){return async s=>{let d=s.map(f=>`${f.objectApiName} (${f.records})`).join(", ");e.log(`[WARN] ${n}: the user may not delete ${d} in the target: those records stay`);let p=e.infraServices?.confirmRemovalLeavingUndeletable;if(!p)return!0;let u=e.orgManager.getOrg(t);return p({org:Nt(u,t),objects:s})}}var Qt={code:"NOT_INITIALIZED",message:"Production Guard is not initialized \u2014 infrastructure services missing"};function ca(){return Object.assign(new Error(Qt.message),{code:Qt.code})}var qe={blocked:"GUARD_BLOCKED",declined:"GUARD_DECLINED"};function la(e){return Object.assign(new Error(`Operation blocked by Production Guard: ${e}`),{code:qe.blocked})}function da(e){return e instanceof Error&&e.code===qe.blocked?qe.blocked:void 0}function Bo(e){return e.robustness??zt}function pa(e){return e.bulkManager??new Kt(Bo(e).bulk.maxConcurrentJobs)}var $o={"sync:schedule":"sync:schedule:","sync:pipeline":"sync:pipeline:","seed:pipeline":"seed:pipeline:","offline-replay":"offline-replay-"};function ma(e,t,n){return{id:`${$o[e]}${t}`,type:n,timestamp:Date.now()}}function ua(e,t,n,s){return{id:e.nextId(),type:n,timestamp:Date.now(),correlationId:t.id,payload:s}}function ga(e,t,n,s,d={}){let p=t==="error"?null:d.autoDismissMs===void 0?5e3:d.autoDismissMs,u={id:e.nextId(),type:"notification",timestamp:Date.now(),payload:{level:t,title:n,message:s,...p===null?{}:{autoDismissMs:p},...d.actions?{actions:d.actions}:{},...d.code?{code:d.code}:{}}};e.broker.postToWebview(u),e.log(`[TX] notification: ${n}`)}function ba(e,t,n,s){let d={id:e.nextId(),type:"operation:started",timestamp:Date.now(),payload:{operationId:t,module:n,description:s}};e.broker.postToWebview(d)}function fa(e,t,n,s,d,p){let u={id:e.nextId(),type:"operation:progress",timestamp:Date.now(),payload:{operationId:t,percentage:n,processedRecords:s,totalRecords:d,currentStep:p}};e.broker.postToWebview(u)}function ya(e,t,n){let s={id:e.nextId(),type:"operation:completed",timestamp:Date.now(),payload:{operationId:t,result:n}};e.broker.postToWebview(s)}var qo=Symbol("sandforge.uncorrelated");function eo(e,t,n,s,d,p={}){let u=V(d),f=d instanceof qt?d:void 0,k=qo in s,E=p.code??f?.code??"UNKNOWN";k||Ko(e.broker,u,E),e.log(`[ERR] ${t}: ${u}${k?` (uncorrelated: ${String(s.reason)})`:""}`);let O={id:e.nextId(),type:n,timestamp:Date.now(),...k?{}:{correlationId:s.id},payload:{message:u,code:E,retryable:p.retryable??!1,...f?{orgId:f.orgId}:{},...p.extraPayload}};e.broker.postToWebview(O),e.log(`[TX] ${n}: ${u}`)}function ha(e,t){let n={id:e.nextId(),type:t.type,timestamp:Date.now(),payload:t.payload};e.broker.postToWebview(n)}function za(e){let t=e?.getSandforgeSetting;if(!(!t||!t("grappe.enabled",!1)))return{enabled:!0,autoActivateThreshold:t("grappe.autoActivateThreshold",1e4),maxWorkers:rt.maxWorkers,grappeSize:t("grappe.grappeSize",5e3),strategy:"round_robin",backPressure:{enabled:!1,maxQueueDepth:3,highWaterMark:80,lowWaterMark:60,strategy:"pause",monitoringInterval:5e3},checkpointing:!0,isolationLevel:"per_grappe"}}function Sa(e){let t=new Set(e.map(s=>s.batchSize)),[n]=t;return{...e.length>0?{objectName:e.map(s=>s.objectApiName).join(", ")}:{},...t.size===1&&n!==void 0?{batchSize:n}:{}}}function xa(e,t,n,s,d={}){let p={id:e.nextId(),type:"operation:failed",timestamp:Date.now(),payload:{operationId:t,error:n,retryable:s,...d.extraPayload}};e.broker.postToWebview(p),d.authored!==!0&&Zo(e,n,d.context)}var Go=[/^Operation cancelled by user\b/,/^Operation blocked by Production Guard: /,/^Production Guard is not initialized\b/,/^Duplicate operation: /,/^A backup or rollback operation is already running for org /,/^Object describe not available for '/,/^CRUD_FLS_DENIED: /,/^CRUD\/FLS check failed for /,/^No backup found for operation /,/^Backup \S+ was taken from org /,/^Restore not run: /,/^Pipeline failed$/,/^Pipeline did not start: /,/^Pipeline ran out of time: /,/^Org not found: /,/^No credentials for org /,/^Invalid username format: /];function Wo(e){return Go.some(t=>t.test(e))}var to=1e4,Ge=new WeakMap;function Ko(e,t,n){let s=De(t,{code:n});if(!s?.actionKey)return;let d=Ge.get(e)??new Map,p=Date.now();for(let[u,f]of d)p-f>to&&d.delete(u);d.set(s.code,p),Ge.set(e,d)}function Ho(e,t){let n=Ge.get(e)?.get(t);return n!==void 0&&Date.now()-n<=to}function Zo(e,t,n={}){if(!(e.broker.panelCount>0)||Wo(t))return;let d=$t(t,Ut)??"UNKNOWN",p=De(t,{code:d});if(p?.actionKey){if(Ho(e.broker,p.code))return;e.broker.showFixSuggestion({source:"catalogue",code:p.code,actionKey:p.actionKey});return}let u=e.errorResolver;u&&u.resolveError({errorCode:d,message:t},n).then(f=>{e.broker.showFixSuggestion({source:"model",text:Xo(f)})}).catch(f=>{e.log?.(`[ERR] operation:failed resolution: ${V(f)}`)})}function Xo(e){return e.suggestions[0]?.description||e.explanation}import{isAbsolute as tn}from"node:path";var i=a().min(1).max(128),l=a().regex(/^[A-Za-z][A-Za-z0-9_]*$/,"Invalid Salesforce API name").max(80),so=c(l).max(300),m=a().min(1).max(200),J=a().max(2e3).refine(Fe,{message:Me}),on=a().refine(Gt,{message:"ORDER BY clause must list only field names with optional ASC/DESC and NULLS FIRST/LAST (no LIMIT, OFFSET, FOR UPDATE or subquery)."}),y=100,co=1e4,B=o({keepDays:g().int().min(ve.min).max(ve.max).optional(),excluded:c(l).max(y).refine(e=>new Set(e).size===e.length,"An object is left out twice").optional()}).strict(),he={sweepLate:r().optional(),sweepUntied:r().optional()};function nn(e){return Wt(e)}function an(e,t='turn on "Copy the files of these records"'){return _t(e)?`Sync copies files with the records they hang on, not as an object of their own: "${e}" keeps its content in a file body. Remove it from this configuration and ${t} instead; the sync was not started.`:`Sync does not copy "${e}": no copy writes it \u2014 users and their access, metadata, a record's history, feed or sharing rows, and the records the platform keeps for itself are not data a copy carries. Remove it from this configuration; the sync was not started.`}var rn=w(gt,{error:e=>e.input==="manual"?"Manual conflict review is not available for a sync run: no run shows its conflicts to anyone before it writes. Pick source wins, target wins, newest wins or merge \u2014 target wins keeps every value the target holds where the two orgs differ. The sync was not started.":`Conflict strategy "${String(e.input)}" is not one a sync run acts on: pick source wins, target wins, newest wins or merge. The sync was not started.`}),sn=bt.extend({objectApiName:l.refine(e=>!nn(e),{error:e=>an(String(e.input))}),externalIdField:nt(e=>typeof e=="string"&&e.trim()===""?void 0:e,l.optional()),where:J.optional(),orderBy:on.optional(),batchSize:g().int().positive().max(co).optional()}).strip().refine(e=>e.operation!=="upsert"||(e.externalIdField??"Id").toLowerCase()!=="id",{path:["externalIdField"],error:e=>`An upsert of "${String(e.input.objectApiName)}" needs an External ID field: matching on Id cannot work, because the id belongs to the source org and the target has never issued it. Name an External ID field both orgs share, or set the operation to insert. The sync was not started.`}).superRefine((e,t)=>{let n=Ft([e]);n.length!==0&&t.addIssue({code:G.custom,message:`${Mt(n)} The sync was not started.`,params:{unreadablePatterns:n}})});function oo(e){return et({error:()=>`Sync does not run Apex: remove "${e}" from this configuration. The sync was not started so the script cannot be skipped without you knowing.`}).optional()}var Ke=ft.extend({id:m.optional(),sourceOrgId:i,targetOrgId:i,objects:c(sn).min(1).max(y),conflictStrategy:rn,createdAt:a().max(40).optional(),updatedAt:a().max(40).optional(),preScript:oo("preScript"),postScript:oo("postScript"),dryRun:v(!1,{error:()=>'A sync configuration cannot ask for a dry run: remove "dryRun" from it. A run of it writes to the target org; to see what it would write, simulate it from the Sync page. The run was not started, so it cannot write while you believed it was only reporting.'}).optional()}).strip().superRefine((e,t)=>{e.direction==="target_to_source"&&t.addIssue({code:G.custom,path:["direction"],message:'Sync writes source to target only: direction "target_to_source" is not supported. Swap the source and target orgs to copy the other way. The sync was not started, so it cannot write into the org you meant to read from.'}),e.mode!=="full"&&e.mode!=="delta"&&t.addIssue({code:G.custom,path:["mode"],message:`Sync runs a full or a delta sync only: mode "${e.mode}" is not implemented. Set mode to "full" or "delta". The sync was not started, so it cannot replay the whole object set while you believed it was reading changes only.`}),e.mode==="delta"&&e.objects.forEach((n,s)=>{n.operation==="upsert"||n.operation==="update"||t.addIssue({code:G.custom,path:["objects",s,"operation"],message:`A delta sync writes ${n.objectApiName} again for every record it reads twice, and ${n.operation} would ${n.operation==="insert"?"create a second copy":"delete a record already gone"}. Write it by upsert on an External ID, or by update, or run the configuration in full. The sync was not started.`})}),e.propagateDeletes===!0&&(e.mode!=="delta"?t.addIssue({code:G.custom,path:["propagateDeletes"],message:'Deletions are carried by a delta sync only, which knows since when to look for them: set mode to "delta", or turn deletions off. The sync was not started.'}):e.objects.forEach((n,s)=>{if(n.operation!=="upsert"&&n.operation!=="update")return;let d=Ht(n);"refused"in d&&t.addIssue({code:G.custom,path:["objects",s],message:`${d.refused} Turn deletions off, or carry a source field onto the key. The sync was not started.`})}))}),Ea=o({suggestedName:a().min(1).max(255).refine(e=>!e.includes("/")&&!e.includes("\\"),"suggestedName must not contain a path"),content:a().max(32*1024*1024),extensions:c(a().regex(/^[A-Za-z0-9]+$/)).max(8).optional()}),Ca=o({config:Ke,muteAutomation:r().optional(),checkpointFirst:B.optional()}),Ta=o({config:Ke,checkpointFirst:B.optional()}),_a=o({operationId:m}),Na=o({config:Ke}),Da=o({id:m}),Fa=o({orgId:i,targetOrgId:i.optional()}),Ma=o({sourceOrgId:i,targetOrgId:i,objectApiName:l}),lo=w(["source_wins","target_wins","newest_wins","manual","merge"]),cn=Re("kind",[o({kind:v("id")}),o({kind:v("externalId"),field:l}),o({kind:v("syncConfig"),configId:m})]),Ua=o({sourceOrgId:i,targetOrgId:i,watchedObjects:c(l).min(1).max(y),apply:c(o({objectApiName:l,match:cn,applyDeletes:r()})).max(y),conflictStrategy:lo,flushIntervalMs:g().int().min(50).max(6e4),maxBatchSize:g().int().min(1).max(200),keepContactPoints:r().optional()}).refine(e=>e.apply.every(t=>e.watchedObjects.includes(t.objectApiName)),{message:"Every applied object must be watched.",path:["apply"]}),La=o({sessionId:a().max(200)}),Ba=o({sourceOrgId:i,targetOrgId:i}),$a=o({conflictId:a().min(1).max(500),eventReplayId:g().optional(),resolution:lo,fieldResolutions:x(a(),o({value:D(),source:w(["source","target","manual"])})).optional()}),qa=o({entryId:m}),Ga=o({runId:m}),Wa=o({realtime:v(!0).optional()}).optional(),Ka=o({sourceOrgId:i,targetOrgId:i,objects:c(l).max(y),configId:m.optional()}),Ha=o({runId:m,includeChanged:r().optional(),sweep:r().optional(),again:r().optional(),muteAutomation:r().optional(),...he}),Za=o({runId:m}),Xa=o({runId:m,again:r().optional(),sweptObjects:so.optional()}),Ya=o({runId:m}),Va=o({runId:m,includeChanged:r().optional(),sweep:r().optional(),again:r().optional(),muteAutomation:r().optional(),...he}),Ja=o({runId:m}),Qa=o({format:w(["csv","json"]),entryIds:c(m).max(500).optional()}),ln=o({id:m,name:a().min(1).max(200),configId:m,cron:a().min(1).max(100),timezone:a().min(1).max(100),enabled:r(),maxRetries:g().int().min(0).max(10),notifyOnComplete:r(),notifyOnFailure:r(),createdAt:a().max(40),updatedAt:a().max(40),version:g().int().positive()}).strip(),er=o({schedule:ln}),tr=o({scheduleId:m,enabled:r()}),or=o({scheduleId:m}),dn=dt.extend({objectApiName:l,recordCount:g().int().positive().max(ne),batchSize:g().int().positive().max(co).optional()}).loose(),pn=pt.extend({childObject:l,lookupField:l,parentObject:l}).superRefine((e,t)=>{e.parents.kind==="existing"&&e.parents.where!==void 0&&!Fe(e.parents.where)&&t.addIssue({code:G.custom,path:["parents","where"],message:Me})}),mn=mt.extend({objects:c(dn).min(1).max(y),relations:c(pn).max(y).optional()}).loose().superRefine(ut),nr=o({orgId:i,template:mn,muteAutomation:r().optional(),checkpointFirst:B.optional(),fit:o({share:g().gt(0).max(1),withinMB:g().positive().max(1e6).optional(),before:g().int().positive().max(ne*y)}).strict().optional(),locale:a().regex(/^[a-z]{2,3}(?:_[A-Za-z0-9]{2,4}){0,2}$/).optional(),dryRun:r().optional()}),ar=o({orgId:i}),rr=o({orgId:i,objects:c(l).min(1).max(y),publishes:r().optional()}).strict(),ir=o({orgId:i,objectApiName:l}),sr=o({id:m}),cr=o({template:x(a(),D())}),lr=o({description:a().max(1e4)}),dr=o({}).strict(),pr=o({orgId:i,pack:ae,seed:Ae.shape.seed,articleBodyField:l.optional()}).strict(),mr=o({orgId:i,pack:ae,options:Ae,locale:a().regex(/^[a-z]{2,3}(?:_[A-Za-z0-9]{2,4}){0,2}$/).optional(),muteAutomation:r().optional(),checkpointFirst:B.optional()}).strict(),ur=o({orgId:i}).strict(),gr=o({pack:ae,overwrite:r().optional()}).strict(),br=o({runId:m,choice:Rt,overwrite:r().optional()}).strict(),un=131072,gn=o({objectApiName:l,whereClause:J.optional()}).loose(),fr=o({sourceOrgId:i}),yr=o({sourceOrgId:i,targetOrgId:i,objects:c(gn).min(1).max(y),upsert:r().optional(),externalIdField:l.optional(),previewId:m.optional(),keepContactPoints:r().optional(),checkpointFirst:B.optional()}).refine(e=>!e.upsert||e.externalIdField!==void 0,{message:"externalIdField is required when upsert is true",path:["externalIdField"]}),bn=o({csvHeader:a().min(1).max(500),sfFieldApiName:a().max(80),sfFieldType:a().max(40),sfFieldLength:g().int().positive().nullable()}).loose(),hr=o({orgId:i,objectApiName:l,records:c(x(a(),a().max(un))).min(1).max(st),columnMappings:c(bn).min(1).max(ct),externalIdField:l.optional(),checkpointFirst:B.optional()}),zr=o({orgId:i,objects:c(l).min(1).max(y),wheres:x(l,J).optional(),slices:r().optional()}).refine(e=>Object.keys(e.wheres??{}).every(t=>e.objects.some(n=>n.toLowerCase()===t.toLowerCase())),{message:"A filter names an object the backup reads: give it in objects",path:["wheres"]}),Sr=o({orgId:i}),xr=o({orgId:i,templateId:a().min(1).max(200).optional()}),Ir=o({orgId:i,operationId:a().min(1).max(200)}),kr=o({orgId:i,operationIds:c(a().min(1).max(200)).min(1).max(1e3).optional()}),W={acceptAutomation:r().optional(),acceptEmails:r().optional(),muteAutomation:r().optional()},X={fromPage:v(!0).optional()},jr=o({orgId:i,operationId:m,rewriteAll:r().optional(),includeChanged:r().optional(),slices:c(g().int().positive()).min(1).max(lt*y).optional(),...W,...X}),Pr=o({orgId:i,act:w(["masking","restore","cleanup"]),objects:c(o({objectApiName:l,records:g().int().min(0)})).max(y),erasure:r().optional(),...W,...X}),He={objects:c(l).min(1).max(y).optional(),where:J.optional()},Ze=e=>e.where===void 0||e.where.trim()===""||e.objects?.length===1,Xe={message:"A WHERE clause filters the rows of one object: name exactly one in objects",path:["where"]},Or=o({orgId:i,templateId:m,...He,resumeFrom:m.optional(),snapshot:r().optional(),slices:r().optional(),maxRequests:g().int().positive().max(1e9).optional(),abandon:r().optional(),...W,...X}).refine(Ze,Xe).refine(e=>!(e.snapshot===!0&&e.resumeFrom!==void 0&&e.slices!==!0),{message:"A resume takes no snapshot: the run it resumes has written over some of its rows",path:["snapshot"]}).refine(e=>!(e.slices===!0&&e.snapshot===!1),{message:"A run in slices backs each slice up before it masks it: it cannot keep no snapshot",path:["slices"]}).refine(e=>e.maxRequests===void 0||e.slices===!0,{message:"A bound on requests stops a run in slices between two of them: give slices too",path:["maxRequests"]}).refine(e=>e.abandon!==!0||e.resumeFrom===void 0&&e.snapshot!==!0&&e.maxRequests===void 0,{message:"Giving up a set of slices masks nothing: it takes no resume, snapshot or bound",path:["abandon"]}),Rr=o({orgId:i,templateId:m,...He,slices:r().optional()}).refine(Ze,Xe),wr=o({orgId:i,templateId:m,...He}).refine(Ze,Xe),vr=o({name:a().trim().min(1).max(jt),rules:c(Ot).min(1).max(Pt).refine(e=>new Set(e.map(t=>t.fieldPattern.toLowerCase())).size===e.length,"A field has two rules")}),Ar=o({templateId:m}),Er=o({orgId:i,objectNames:c(l).min(1).max(y)}),Cr=o({orgId:i,objects:c(o({objectApiName:l,duplicateKey:l.optional()})).min(1).max(10).refine(e=>new Set(e.map(t=>t.objectApiName.toLowerCase())).size===e.length,{message:"Each object may be named once per scan"}),staleDays:g().int().min(1).max(3650)}),po=c(l).min(1).max(10).refine(e=>new Set(e.map(t=>t.toLowerCase())).size===e.length,{message:"Each object may be named once per request"}),Tr=o({orgId:i,objects:po}),_r=o({orgId:i,objects:po,requestId:Oe().optional(),email:a().trim().refine(Ct,"Not an email address").optional(),name:a().refine(Tt,"Not a name").optional(),phone:a().refine(Et,"Not a phone number").optional()}).refine(e=>e.email!==void 0||e.name!==void 0||e.phone!==void 0,{message:"A search needs an email address, a name or a phone number"}),fn=o({orgId:i,requestId:Oe()}),ze=a().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record Id"),Nr=o({runId:m,recordId:ze}).strict(),Dr=fn.extend({mode:w(["anonymize","delete"]),records:c(o({objectApiName:l,ids:c(ze).min(1).max(200)})).min(1).max(10).refine(e=>new Set(e.map(t=>t.objectApiName.toLowerCase())).size===e.length,{message:"Each object may be named once per request"}),dryRun:r(),...W}),yn=Re("kind",[o({kind:v("stale"),days:g().int().min(1).max(3650)}),o({kind:v("orphans"),fieldApiName:l}),o({kind:v("duplicates"),keyField:l})]),mo=o({orgId:i,objectApiName:l,recommendation:yn}),Fr=mo.extend({after:o({skip:g().int().nonnegative().max(1e8),id:ze.optional(),modified:a().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:?\d{2})$/).optional()}).strict().optional()}),Mr=mo.extend({dryRun:r(),...W,...X}),We=2e3,uo={mode:w(["objects","org"]),objects:c(l).min(1).max(We).optional(),excluded:c(l).max(We).optional(),customSettings:r().optional(),files:r().optional(),managedPackages:r().optional(),unrestorable:r().optional()},hn=o(uo).strict().refine(e=>e.mode==="objects"==(e.objects!==void 0),{message:"The objects picked are named in objects mode, and only there"}),Ur=o({orgId:i,...uo,objects:c(l).max(We).optional()}).strict().refine(e=>e.mode==="objects"==(e.objects!==void 0),{message:"The objects picked are named in objects mode, and only there"}),Lr=o({orgId:i,request:hn,deleteMode:w(["recycle","hard"]),checkpointFirst:r().optional(),acceptNoUndo:r().optional(),acceptPeopleActive:r().optional(),...W,...X}),Br=o({orgId:i,previewId:m.optional(),resumeRunId:a().regex(/^em-\d{8}-\d{6}-[a-z0-9]{4}$/).optional(),acceptNoUndo:r().optional(),acceptPeopleActive:r().optional(),checkpointFirst:r().optional(),...W,...X}).refine(e=>e.previewId===void 0!=(e.resumeRunId===void 0),{message:"An emptying acts on a preview, or takes up a run: one of them"}),$r=o({operationId:m}),qr=o({orgId:i,runId:a().regex(/^em-\d{8}-\d{6}-[a-z0-9]{4}$/),...W,...X}),Gr=o({orgId:i}),Wr=o({orgId:i}).strict(),Kr=o({alertId:m}),go=o({sourceOrgId:i,targetOrgId:i}),Hr=go.extend({types:c(a().min(1).max(80)).min(1).max(50),includeManaged:r().optional()}),zn=o({componentType:w(At),fullName:a().min(1).max(400).regex(/^[^\u0000-\u001f\u007f]+$/,"A component name holds no control character")}),Zr=go.extend({components:c(zn).min(1).max(500).refine(e=>new Set(e.map(t=>`${t.componentType}:${t.fullName}`)).size===e.length,{message:"Each component may be named once per deployment"}),testLevel:w(wt),runTests:c(a().max(255).regex(vt,"Not an Apex class name")).max(100).optional()}).refine(e=>e.sourceOrgId!==e.targetOrgId,{message:"The source and the target are the same org",path:["targetOrgId"]}).refine(e=>e.testLevel!=="RunSpecifiedTests"||(e.runTests?.length??0)>0,{message:"RunSpecifiedTests names at least one test class",path:["runTests"]}),Xr=o({validationId:a().regex(/^0Af[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/,"Not a deployment id"),targetOrgId:i}).strict(),Sn=a().regex(/^\d+\.\d+\.\d+$/,"Invalid semver"),ye=a().regex(/^[A-Za-z][A-Za-z0-9_]*\.[A-Za-z][A-Za-z0-9_]*$/,"Expected an Object.field key").max(170),xn=o({name:a().min(1).max(80),label:a().min(1).max(200),filterField:l,valuesSoql:a().min(1).max(4e3)}),In=o({name:a().min(1).max(80),label:a().min(1).max(200),whereFragment:J}),no=de([o({action:v("clear")}),o({action:v("replace"),value:a().max(255)})]),bo=o({rootObject:l,axes:c(xn).max(20),edgeCases:c(In).max(50),budgetMaxRecords:g().int().positive().max(1e5).optional(),candidatesPerCombination:g().int().positive().max(20).optional(),expectedObjects:c(l).max(100).optional(),maxNodes:g().int().min(10).max(500).optional(),excludedObjects:c(l).max(200).optional(),excludedFields:x(l,c(l).max(500)).optional(),sasDir:a().min(1).max(500).optional(),datasetDir:a().min(1).max(500).optional(),rulesFilePath:a().min(1).max(500).optional(),datasetVersion:Sn.optional(),protectedOrgIds:c(i).max(50).optional(),identityKeys:x(l,c(l).min(1).max(10)).optional(),undeletableObjects:x(l,l).optional(),requiredLookupPlaceholders:x(ye,o({name:a().min(1).max(200),recordTypeDeveloperName:a().min(1).max(97).optional(),targetObjectApiName:l.optional()})).optional(),requiredFieldDefaults:x(ye,D()).optional(),picklistRules:x(ye,no).optional(),defaultPicklistRule:no.optional(),duplicateErrorPatterns:c(a().min(1).max(200)).max(50).optional(),mockDetection:o({metadataTypeApiName:l,isMockedFieldApiName:l}).optional(),mandatoryLookups:x(l,c(l).min(1).max(50)).optional(),presenceKeys:x(l,l).optional()}),Yr=o({config:bo}),Vr=o({sourceOrgId:i}),Jr=o({fields:c(ye).min(1).max(2e3)}),Qr=o({sourceOrgId:i,author:a().min(1).max(120).optional()}),ce=o({organizationId:kt,checkpointId:F}).strict(),kn=bo.pick({requiredFieldDefaults:!0,requiredLookupPlaceholders:!0,picklistRules:!0,defaultPicklistRule:!0,identityKeys:!0,undeletableObjects:!0,duplicateErrorPatterns:!0,mockDetection:!0,protectedOrgIds:!0}).strict(),fo=ce.extend({choices:Ne,config:kn.optional()}).strict(),jn=fo.extend({choices:Ne.optional()}).strict(),ti=o({targetOrgId:i,replay:fo.optional(),pilot:r().optional(),reload:r().optional(),writeEncrypted:r().optional(),maxRecords:g().int().positive().max(1e6).optional(),muteAutomation:r().optional(),checkpointFirst:B.optional(),sweep:r().optional(),...he,includeChanged:r().optional(),acceptEmails:r().optional(),acceptAutomation:r().optional(),goneFirst:c(ze).max(1e6).optional()}),Pn=o({targetOrgId:i}),oi=Pn.extend({replay:jn.optional()}),ni=o({targetOrgId:i,loadedAt:a().min(1).max(64),includeChanged:r().optional(),sweep:r().optional(),...he,muteAutomation:r().optional(),replay:ce.optional()}),ai=o({targetOrgId:i,loadedAt:a().min(1).max(64),reload:r().optional(),replay:ce.optional()}),ri=o({targetOrgId:i,loadedAt:a().min(1).max(64),sweptObjects:so.optional(),reload:r().optional(),replay:ce.optional()}),ii=o({targetOrgId:i,loadedAt:a().min(1).max(64),includeChanged:r().optional(),replay:ce.optional()}),yo=1e3,ho=3650,On=200,Z=c(l).min(1).max(yo).refine(e=>new Set(e).size===e.length,"An object is named twice");function zo(e){return e.mode==="picked"?e.objects!==void 0:e.objects===void 0}var So=de([v("all"),c(l.refine(e=>e.toLowerCase().endsWith("__c"),"A custom setting's API name ends in __c")).min(1).max(yo).refine(e=>new Set(e.map(t=>t.toLowerCase())).size===e.length,"A custom setting is named twice")]),xo={path:["objects"],message:'Name the objects with "picked", and none with "everything"'},si=o({orgId:i.optional()}).optional(),Rn=1e6,Io=g().int().min(1).max(Rn),ci=o({orgId:i,mode:_e,objects:Z.optional(),excluded:Z.optional(),customSettings:So.optional(),maxTotal:Io.optional()}).refine(zo,xo),li=o({orgId:i,name:Te,mode:_e,objects:Z.optional(),excluded:Z.optional(),customSettings:So.optional(),maxTotal:Io.optional(),keepDays:g().int().min(0).max(ho),ignoredFields:Ce.optional()}).refine(zo,xo),di=o({checkpointId:F,objects:Z.optional(),muteAutomation:r().optional(),acceptOutside:r().optional()}),pi=o({checkpointId:F,previewId:Ee,objects:Z.optional(),acceptAutomation:r(),muteAutomation:r().optional(),acceptEmails:r().optional(),acceptNoUndo:r(),acceptRecreate:r(),acceptOutside:r(),acceptUnseen:r(),fromPage:v(!0).optional()}),mi=o({checkpointId:F,previewId:Ee,objects:Z,acceptOutside:r()}),ui=o({checkpointId:F}),wn=200,gi=o({token:m,orgId:i,key:a().min(1).max(wn),keepDays:g().int().min(0).max(ho)}),bi=o({checkpointId:F,rewindId:It,acceptAutomation:r(),muteAutomation:r().optional(),acceptEmails:r().optional(),fromPage:v(!0).optional()}),fi=o({checkpointIds:c(F).min(1).max(On).refine(e=>new Set(e).size===e.length,"A checkpoint is named twice")}),yi=o({checkpointId:F,keep:r()}),hi=o({checkpointId:F,name:Te}),zi=o({checkpointId:F,fields:Ce}),vn=500,Si=o({orgIds:c(i).min(1).max(vn).refine(e=>new Set(e).size===e.length,"An org is named twice").optional()}).strict().optional(),xi=o({sourceOrgId:i,targetOrgId:i,includeStandardObjects:r()}),Ii=o({sourceOrgId:i,objectApiNames:c(l).min(1).max(it)}),ki=o({sourceOrgId:i,targetOrgId:i,selectedObjects:c(l).max(y),includeStandardObjects:r(),maxDepth:g().int().min(1).max(10).optional(),maxObjects:g().int().min(1).max(500).optional()}),ji=o({complianceFramework:ht,objectFilters:x(a(),J).optional(),overrides:c(o({objectApiName:l,fieldApiName:l,method:de([yt,v("skip")])})).max(500).optional()}),Pi=o({grappeThreshold:g().int().nonnegative(),keepContactPoints:r().optional(),muteAutomation:r().optional(),checkpointFirst:B.optional()}),Oi=o({mode:o({share:v(!0).optional(),caps:x(l,g().int().min(1).max(ne)).refine(e=>Object.keys(e).length<=y,"Too many caps").optional(),all:g().int().min(1).max(ne).optional(),withinMB:g().positive().max(1e6).optional()}).strict().refine(e=>e.share===!0||e.caps!==void 0||e.all!==void 0,"Fit by share, by caps, or both"),muteAutomation:r().optional(),checkpointFirst:B.optional()}),Ri=o({objectApiName:l}),wi=o({orgId:i.optional(),sourceOrgId:i.optional(),alreadySelected:c(l).max(y).optional()}).loose(),vi=o({orgId:i.optional(),sourceOrgId:i.optional(),objectApiName:l.optional(),alreadySelected:c(l).max(y).optional(),selectedObjects:c(l).max(y).optional(),availableObjects:c(l).max(500).optional()}).loose(),Ai=o({sourceOrgId:i,targetOrgId:i.optional(),selectedObjects:c(l).min(1).max(y),parentObjects:c(l).max(y).optional()}).loose(),An=St.extend({sourceOrgId:i,targetOrgId:i,selectedObjects:c(l).min(1).max(y),parentObjects:c(l).max(y).default([])}).loose(),Ei=o({config:An.optional(),sourceOrgId:i.optional(),targetOrgId:i.optional(),selectedObjects:c(l).min(1).max(y).optional(),parentObjects:c(l).max(y).optional()}).loose(),En=a().min(1).max(5e4),Ci=o({conversationId:m,message:a().max(5e4)}),Ti=o({title:a().min(1).max(300)}),_i=o({conversationId:m}),Ni=o({apiKey:a().min(1).max(500),errorResolution:r().optional()}),Di=o({enabled:r().optional(),errorResolution:r().optional()}),Fi=o({orgId:i,objectName:l,sampleSize:g().int().positive().max(1e4).optional()}),Mi=o({orgId:i,prompt:a().trim().min(1).max(2e3).optional(),soql:a().trim().min(1).max(2e4).optional()}).refine(e=>e.prompt===void 0!=(e.soql===void 0),{message:"Send a prompt to draft from or a query to check, not both and not neither"}),Ui=o({description:En,orgIds:c(i).max(50).optional()}),Li=o({requestId:m}),fe=c(a().min(1).max(M.picklistValue)).max(M.picklistValues),ao={label:a().max(M.agentLabel).optional(),description:a().max(M.agentDescription).optional()},Bi=o({text:a().trim().min(1).max(M.text),language:ae.shape.language,casePicklists:o({Status:fe.optional(),Origin:fe.optional(),Priority:fe.optional(),Type:fe.optional()}).optional(),agent:o({topics:c(o({name:a().min(1).max(M.agentName),...ao,actions:c(o({name:a().min(1).max(M.agentName),...ao})).max(M.agentActions)})).max(M.agentTopics)}).optional(),draft:xt.optional(),maskOnly:r().optional()}),$i=o({filePath:a().min(1).max(2e3)}),qi=o({name:a().max(200),config:x(a(),D())}),Gi=o({operationId:m.optional(),executionId:m.optional(),objectName:a().min(1).max(200).optional()}).loose(),Wi=o({policyId:m}),Ki=o({policy:x(a(),D())}),Hi=o({policyId:m,orgId:i}),Zi=o({module:a().min(1).max(50).optional(),orgId:i.optional(),offset:g().int().min(0).max(we).optional(),limit:g().int().min(1).max(we).optional()}).optional(),Xi=o({operationId:m.optional()}).optional(),Cn=w(["syncMappings","forgePlans","pipelines","anonymizationTemplates"]),Yi=o({categories:c(Cn).min(1).max(50)}),Vi=o({json:a().min(1).max(5e6),overwrite:r()}),Ji=o({json:a().min(1).max(5e6)}),Qi=o({orgId:a().max(128),authMethod:a().min(1).max(50),alias:a().max(100).optional(),loginUrl:a().max(500).optional(),username:a().max(300).optional(),password:a().max(500).optional(),securityToken:a().max(100).optional(),clientId:a().max(256).optional(),jwtKeyFile:a().max(4096).optional()}).loose(),ko=a().trim().max(100).regex(/^[\w.-]*$/,"an alias is letters, digits, dots, dashes and underscores").optional(),Tn=a().trim().min(1,"the username is required").max(80).regex(/^[\w.@+-]+$/,"a username is written like an email address"),jo=a().trim().min(1,"the consumer key is required").max(256).regex(/^[A-Za-z0-9._-]+={0,2}$/,"a consumer key is letters, digits, dots, dashes and underscores"),_n=a().trim().min(1,"the private key file is required").max(4096).regex(/^[^\u0000-\u001f\u007f]+$/,"the private key file path holds a control character").refine(e=>tn(e),"give the private key file as an absolute path"),es=o({alias:ko,loginUrl:a().max(500).optional(),username:Tn,clientId:jo,jwtKeyFile:_n}).loose(),ts=o({alias:ko,loginUrl:a().max(500).optional(),clientId:jo}).loose(),os=o({requestId:m}),ns=o({orgId:i}),as=o({orgId:i}),rs=o({orgId:i}).strict(),is=o({orgId:i,alias:a().trim().min(1).max(100),color:a().regex(/^#[0-9A-Fa-f]{6}$/),tags:c(a().trim().min(1).max(50)).max(20),staging:r().optional()}),ss=o({key:a().min(1).max(200),value:D()}),cs=o({enabled:r()}),ls=o({lng:w(["en","fr","de","es","ja","pt-BR"])}),ds=o({targetOrgId:i,sourceOrgId:i.optional()}),ps=o({moduleId:a().min(1).max(64),route:a().min(1).max(64),overlay:r()}),ms=o({moduleId:a().min(1).max(64)}),Nn=80,Dn=ot(e=>Lt(e)||Bt(e)||typeof e=="string"&&e.trim()!==""&&e.length<=Nn,{message:"Not a pipeline step type"}),Fn=o({pipeline:o({name:a().min(1).max(200),steps:c(o({type:Dn,config:x(a(),D()).default({})}).loose()).max(200),variables:c(x(a(),D())).max(200).default([]),triggers:c(x(a(),D())).max(50).default([])}).loose(),variables:x(a(),a().max(2e3)).optional(),dryRun:r().optional()}),Mn=tt({since:at.datetime({offset:!0}),runner:w(["cron","taskScheduler","githubActions"]),file:a().min(1).max(255).refine(e=>!/[\\/]/.test(e),"The file's name, without its folder"),digest:a().regex(/^sha256:[0-9a-f]{64}$/,"Not a digest: sha256: and 64 hex digits")}),us=Fn.shape.pipeline.extend({id:a().min(1).max(200),runsOutside:Mn.optional()}),gs=o({pipelineId:m}),bs=o({id:a().max(200),config:x(a(),D())}),fs=o({id:m}),ys=o({operationId:m,stepId:m,decision:w(["approved","rejected"])}),Un=255,Po={pipelineId:m,stepId:m},hs=o({pipelineId:m}),zs=o({...Po,typed:a().min(1).max(Un)}),Ss=o(Po),xs=o({category:a().max(100).optional(),query:a().max(500).optional()}).loose().optional(),Is=o({templateId:m});function Ln(e){return e.issues.slice(0,3).map(t=>`${t.path.join(".")||"(root)"}: ${t.message}`).join("; ")}function Bn(e){let t=e.issues.map(n=>n.code==="custom"?n.params?.unreadablePatterns:void 0);return t.every(n=>n!==void 0)?t.flat():void 0}function ks(e,t,n,s){let d=e.safeParse(t.payload);if(!d.success){let p=Ln(d.error),u=Bn(d.error);return eo(s,t.type,n,t,new Error(`Invalid payload \u2014 ${p}`),u?{code:Dt,extraPayload:{rules:u}}:{code:"INVALID_PAYLOAD"}),null}return d.data}var $n=5;function Se(e){return e.slice(0,15)}function qn(e){let t=e.errors?.[0];if(t===void 0)return"The org gave no reason.";if(typeof t=="string")return t;let n=t.statusCode??"",s=t.message??"";return n&&s?`${n}: ${s}`:n||s||"The org gave no reason."}function Oo(e){let t=new Set;for(let n of e){let s=n.Id;typeof s=="string"&&t.add(Se(s))}return t}async function Ro(e){let t=[],n=[],s={},d=!1,p=!1,u=e.stampsFor,f=ie(e.org),k=e.org.serverTime?.bind(e.org),E=u&&k?Date.now()+await se({serverTime:k})-re:Number.NaN;for(let{objectApiName:O,ids:A}of e.plan){let I={objectApiName:O,planned:A.length,undeleted:0,alreadyBack:0,goneForGood:0,refused:0,reasons:[]};t.push(I);let h=_=>{I.reasons.length<$n&&!I.reasons.includes(_)&&I.reasons.push(_)},R=pe(O);for(let _=0;_<A.length;_+=me){let C=A.slice(_,_+me);if(p||e.signal?.aborted){p=!0,I.notReached=(I.notReached??0)+C.length,n.push(...C);continue}let[ee]=ue(C,me),K,te;try{K=Oo((await e.org.queryDeleted(`SELECT Id FROM ${R} WHERE Id IN (${ee}) AND IsDeleted = true`)).records),te=Oo((await e.org.query(`SELECT Id FROM ${R} WHERE Id IN (${ee})`)).records)}catch(j){I.refused+=C.length,h(`The recycle bin could not be read: ${V(j)}`),n.push(...C);continue}let z=C.filter(j=>K.has(Se(j)));for(let j of C)K.has(Se(j))||(te.has(Se(j))?I.alreadyBack++:I.goneForGood++);if(z.length===0)continue;let U;try{d=!0;let j=await e.undelete(z),T=Array.isArray(j)?j:[j];U=z.map((H,oe)=>T[oe]??{success:!1})}catch(j){let T=V(j);U=z.map(()=>({success:!1,errors:[T]}))}let Y=[];U.forEach((j,T)=>{if(j.success===!0){I.undeleted++,u?.(z[T])&&Y.push(z[T]);return}I.refused++,h(qn(j)),n.push(z[T])}),Y.length>0&&Number.isFinite(E)&&Object.assign(s,await be(e.org,R,Y,E,f))}}return{objects:t,left:n,wrote:d,cancelled:p,stamps:s}}function wo(e){return e.refused+e.goneForGood+(e.notReached??0)}async function Gn(e,t,n,s){let d=new Map(Object.entries(s).map(([u,f])=>[u.slice(0,15),Date.parse(f)])),p=new Set;for(let{objectApiName:u,ids:f}of t){let k=pe(u);for(let E of ue(f)){let O;try{O=(await e.query(`SELECT Id, LastModifiedDate FROM ${k} WHERE Id IN (${E})`)).records}catch{continue}for(let A of O){if(typeof A.Id!="string")continue;let I=A.Id.slice(0,15),h=Date.parse(String(A.LastModifiedDate??""));(h<=n||h<=(d.get(I)??Number.NaN))&&p.add(I)}}}return p}function vo(e){let t=Date.parse(e.startedAt),n=Date.parse(e.lastWrittenAt??e.end?.at??"");return Number.isFinite(n)?{runRecordedAt:new Date(n),...Number.isFinite(t)?{runDurationMs:Math.max(0,n-t)}:{}}:{}}function Wn(e){return e.filter(t=>t.deleted+t.alreadyGone>0).map(t=>t.objectApiName)}async function Ms(e){let{run:t,includeChanged:n}=e,s=e.again===!0,d=ge(t,s),p=d.reduce((b,S)=>b+S.ids.length,0),u=Be(t),f=u.reduce((b,S)=>b+S.ids.length,0),k=Yt(t),E=k.reduce((b,S)=>b+S.ids.length,0),O=[],A=e.backups,I=e.undelete;k.length>0&&!I&&O.push(`The ${E} record(s) the run deleted could not be brought back from the recycle bin here: the next removal offers them again.`),u.length>0&&!A&&O.push(`The values from before the run of ${f} record(s) it wrote over could not be read here: they were not put back, and the next removal offers them again.`);let h,R,_={},C=(e.earlierRuns??[]).map(b=>({runId:b.runId,keys:new Set([...ge(b),...Be(b)].flatMap(({ids:S})=>S.map(L=>L.slice(0,15))))})),ee=b=>C.some(({keys:S})=>S.has(b.slice(0,15))),K=e.sweep,te=u.length>0&&A||k.length>0&&I||K?async b=>{if(k.length>0&&I){let N=u.length>0&&A?await Gn(e.org,u,await Vt(e.org,xe(t)),t.removal?.removalStamps??{}):void 0,q=N?Date.now()+await se(e.org)-re:0;if(R=await Ro({org:e.org,plan:k,undelete:I,...C.length>0?{stampsFor:ee}:{},...e.signal?{signal:e.signal}:{}}),N&&R.wrote){let P=ie(e.org);for(let{objectApiName:Pe,ids:Mo}of u){let Uo=Mo.filter(Lo=>N.has(Lo.slice(0,15)));Object.assign(_,await be(e.org,Pe,Uo,q,P))}}if(R.cancelled||e.signal?.aborted)return R.wrote}if(u.length>0&&A){let N={...t.removal?.removalStamps,..._};h=await Jt({org:e.org,plan:u,backups:A,...xe(t)!==void 0?{lastWriteAt:xe(t)}:{},includeChanged:n,...Object.keys(N).length>0?{stamps:N}:{},...t.unkept?{unkept:t.unkept}:{},...C.length>0?{stampsFor:ee}:{},...e.signal?{signal:e.signal}:{}})}let S=(R?.wrote??!1)||(h?.wrote??!1);if(h?.cancelled||e.signal?.aborted)return S;let L=K?await K(b):!1;return S||L}:void 0,z=await Ue(e.org,d,{...vo(t),...t.removal?.removalStamps?{removalStamps:t.removal.removalStamps}:{},...t.removal?.removalSpans?{removalSpans:t.removal.removalSpans}:{},includeChanged:n,...te?{sweep:te}:{},...e.afterRemoval?{afterRemoval:e.afterRemoval}:{},...e.automationMade?{automationMade:e.automationMade}:{},...e.runUserId?{runUserId:e.runUserId}:{},...e.onUndeletable?{onUndeletable:e.onUndeletable}:{},...e.beforeFirstWrite?{beforeFirstWrite:e.beforeFirstWrite}:{},signal:e.signal,onProgress:e.onProgress}),U=new Date().toISOString();if(z.stoppedForUndeletable)return{result:{runId:t.runId,status:"cancelled",includeChanged:n,objects:[],finishedAt:U},planned:p,plannedBack:f,plannedUndelete:E,notes:[],stoppedForUndeletable:!0};let Y=s?void 0:t.removal?.undo?.removedAt,j={runId:t.runId,status:Zn(Xn(Zt(z.objects,z.cancelled),z.objects,h),z.objects,h,R),includeChanged:n,objects:z.objects,finishedAt:U,...Y?{leftBy:Y}:{},...h&&h.objects.length>0?{restored:h.objects}:{},...R&&R.objects.length>0?{undeleted:R.objects}:{}},T=Xt(j,p,t.removal?.undo,s),H=new Set(z.gone),oe=H.size>0||s&&T?d.flatMap(({ids:b})=>b.filter(S=>!H.has(S))):void 0,Je={..._,...z.stamps},Qe=Object.keys(Je).length>0,No=h?.objects.some(b=>b.restored+(b.restoredWithout??0)>0)===!0,Do=R!==void 0&&!R.cancelled;if(T||Qe||z.span||oe||h||R)try{await e.store.updateRemoval(t.runId,b=>({...b,...T?{undo:T}:{},...Qe?{removalStamps:{...b.removalStamps,...Je}}:{},...z.span?{removalSpans:[...b.removalSpans??[],z.span]}:{},...oe?{removalLeft:oe}:{},...h?{restoreLeft:h.left}:{},...No?{restoredAt:U}:{},...R?{undeleteLeft:R.left}:{},...Do?{undeletedAt:U}:{}}))}catch(b){O.push(`What this removal did could not be kept (${b instanceof Error?b.message:String(b)}): the next removal of the run may set out to take records already gone.`)}let Fo=Object.keys(h?.stamps??{}).length>0?await Kn(e.org,t,e.earlierRuns??[]):new Map,ke=[];for(let{runId:b,keys:S}of C){let L=Fo.get(b),N=Object.fromEntries(Object.entries({...R?.stamps,...h?.stamps}).filter(([P])=>S.has(P.slice(0,15))&&!L?.has(P.slice(0,15)))),q=Object.keys(N).length;if(q!==0)try{await e.store.updateRemoval(b,P=>({...P,removalStamps:{...P.removalStamps,...N},...z.span?{removalSpans:[...P.removalSpans??[],z.span]}:{}})),ke.push({runId:b,records:q})}catch(P){O.push(`What this removal gave back of ${q} record(s) the run ${b} wrote too could not be kept on it (${P instanceof Error?P.message:String(P)}): its removal reads them as changed since it.`)}}let le=e.configs;if(le&&H.size>0&&le.isSaved(t.configId)){let b={sourceOrgId:t.sourceOrgId,targetOrgId:$e(t)};try{let S=d.filter(P=>Le.includes(P.objectApiName)).flatMap(({ids:P})=>P.filter(Pe=>H.has(Pe))),L=le.forgetFiles(t.configId,b,S),N=Wn(z.objects).filter(P=>!Le.includes(P)),q=le.markRemoved(t.configId,b,[...new Set([...N,...L.map(P=>P.objectApiName)])],U);j={...j,...q.length>0?{readWhole:q}:{},...L.length>0?{filesForgotten:L.length}:{}}}catch(S){O.push(`The configuration could not be told what this removal took (${S instanceof Error?S.message:String(S)}): run it full next time.`)}}let je;if(e.links&&H.size>0)try{je=await e.links.forget(t.configId,{sourceOrgId:t.sourceOrgId,targetOrgId:$e(t)},[...H])}catch(b){O.push(`Which records of the target this removal took could not be forgotten (${b instanceof Error?b.message:String(b)}): a later run of the configuration may point a lookup at one of them.`)}return{result:j,planned:p,plannedBack:f,plannedUndelete:E,notes:O,...je?{linksForgotten:je}:{},...ke.length>0?{earlierStamped:ke}:{}}}async function Us(e){let{run:t}=e,n=ge(t);return{outcome:await Ue(e.org,n,{...vo(t),...t.removal?.removalStamps?{removalStamps:t.removal.removalStamps}:{},...t.removal?.removalSpans?{removalSpans:t.removal.removalSpans}:{},includeChanged:e.includeChanged,...e.runUserId?{runUserId:e.runUserId}:{},previewOnly:!0,...e.signal?{signal:e.signal}:{}}),planned:n.reduce((d,p)=>d+p.ids.length,0)}}async function Kn(e,t,n){let s=new Map,d=Object.entries(t.heldBefore??{});if(d.length===0||n.length===0)return s;let p=await ie(e)(),u=await se(e);for(let f of n){let k=Date.parse(xe(f)??""),E=Number.isFinite(k)?k+u+re:Number.NEGATIVE_INFINITY,O=new Set;for(let[A,{at:I,by:h}]of d)Date.parse(I)>E&&(p!==void 0&&h!==void 0&&h.slice(0,15)===p||O.add(A));O.size>0&&s.set(f.runId,O)}return s}function xe(e){return e.lastWriteAt??e.lastWrittenAt??e.end?.at}function Hn(e){return e.keptChanged+e.refused+e.notKept+(e.notReached??0)+(e.restoredWithout??0)}function Zn(e,t,n,s){if(!s||e==="cancelled")return e;if(s.cancelled)return"cancelled";let d=s.objects.some(u=>wo(u)>0);if(e==="success"&&!d)return"success";let p=t.some(u=>u.deleted>0)||(n?.objects??[]).some(u=>u.restored>0)||s.objects.some(u=>u.undeleted>0);return e==="partial"||p?"partial":"failure"}function Xn(e,t,n){if(!n||e==="cancelled")return e;if(n.cancelled)return"cancelled";let s=n.objects.some(p=>Hn(p)>0);return e==="success"&&!s?"success":t.some(p=>p.deleted>0)||n.objects.some(p=>p.restored+(p.restoredWithout??0)>0)?"partial":"failure"}function Bs(e){let t=e?.getSandforgeSetting?.("backup.maxAgeDays",30);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}function $s(e,t,n){let s=[],d=0,p=Number.POSITIVE_INFINITY;for(let u of e){let f=t(u.backup);if(!f){d+=u.ids.length;continue}s.push(u);let k=Date.parse(f.timestamp??"");n>0&&Number.isFinite(k)&&(p=Math.min(p,k+n*864e5))}return{kept:s,notKept:d,...Number.isFinite(p)?{keptUntil:new Date(p).toISOString()}:{}}}var Ye="backupSet:",Yn="backups",Ve=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Q=a().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/),$=g().int().nonnegative(),Vn=o({index:g().int().positive(),afterId:a().regex(Ve).optional(),lastId:a().regex(Ve).optional(),rows:$,snapshotId:a().min(1).max(240),takenAt:Q.optional(),readSince:Q.optional(),state:w(["pending","snapshotted","masking","masked","restored"]),masked:$,refused:$,deletedSince:$,nothingToMask:$,unanswered:$.optional(),late:v(!0).optional(),sizeUsed:g().int().positive(),lateLeft:$.optional(),lateOf:g().int().positive().optional(),lateAfterId:a().regex(Ve).optional(),restoredAt:Q.optional()}),Jn=o({objectApiName:a().min(1).max(255),where:a().max(2e3).optional(),select:a().max(1e5).optional(),done:r(),tailLeft:$.optional(),slices:c(Vn)}),Ao=o({setId:a().min(1).max(200),kind:w(["masking","backup"]),orgId:a().min(1).max(200),organizationId:a().max(18).optional(),templateId:a().min(1).max(200).optional(),fingerprint:a().regex(/^[0-9a-f]{64}$/).optional(),size:g().int().positive(),state:w(["open","done","abandoned"]),startedAt:Q,serverStartedAt:Q.optional(),lastActivityAt:Q,requestsSpent:$,keyCheck:a().regex(/^[0-9a-f]{16}$/).optional(),objects:c(Jn)});function Gs(e,t){return`${e}-s${String(t).padStart(4,"0")}`}function Ie(e){return e.objects.flatMap(t=>t.slices).sort((t,n)=>t.index-n.index)}function Ws(e){return Ie(e).reduce((t,n)=>Math.max(t,n.index),0)+1}function Co(e){return e.state==="masked"||e.state==="snapshotted"||e.state==="restored"}function Qn(e){return Ie(e).reduce((t,n)=>t+n.rows,0)}function To(e,t,n){return{index:t.index,objectApiName:e,snapshotId:t.snapshotId,rows:t.rows,masked:t.masked,refused:t.refused,deletedSince:t.deletedSince,nothingToMask:t.nothingToMask,state:t.state,...t.late?{late:!0}:{},...t.sizeUsed<n?{sizeUsed:t.sizeUsed}:{},...t.restoredAt?{restoredAt:t.restoredAt}:{}}}function ea(e){return e.objects.reduce((t,n)=>t+(n.tailLeft??0)+n.slices.reduce((s,d)=>s+(d.lateLeft??0),0),0)}function Ks(e,t){return{setId:e.setId,size:e.size,state:e.state,objects:e.objects.map(n=>({objectApiName:n.objectApiName,slices:n.slices.map(s=>To(n.objectApiName,s,e.size))})),lateRecords:ea(e),requestsSpent:t.requestsSpent,...t.stoppedOnBudget?{stoppedOnBudget:!0}:{},slicesLeft:e.objects.some(n=>!n.done||n.slices.some(s=>!Co(s)))}}function ta(e){return e.kind==="backup"&&e.state==="open"?"partial":e.state}function Hs(e){let t=Object.fromEntries(e.objects.flatMap(n=>n.where?[[n.objectApiName,n.where]]:[]));return{setId:e.setId,orgId:e.orgId,kind:e.kind,state:ta(e),startedAt:e.startedAt,lastActivityAt:e.lastActivityAt,size:e.size,totalRecords:Qn(e),...e.templateId?{templateId:e.templateId}:{},slices:e.objects.flatMap(n=>n.slices.map(s=>To(n.objectApiName,s,e.size))),...Object.keys(t).length>0?{wheres:t}:{}}}function Zs(e){let t=Ie(e);return{setId:e.setId,savedAt:e.lastActivityAt,done:t.filter(Co).length,total:t.length,state:e.state,size:e.size}}var Eo=class{constructor(t){this.configStore=t}configStore;get(t){let n=Ao.safeParse(this.configStore.get(this.key(t)));return n.success&&n.data.setId===t?n.data:void 0}save(t){this.configStore.set(this.key(t.setId),Ao.parse(t),Yn)}delete(t){this.configStore.delete(this.key(t))}list(t){return this.configStore.getKeysByPrefix(Ye).map(n=>this.get(n.slice(Ye.length))).filter(n=>n!==void 0).filter(n=>t===void 0||n.orgId===t)}openFor(t,n){return this.list(t).find(s=>s.kind==="masking"&&s.state==="open"&&s.templateId===n)}ofSnapshot(t){return this.list().find(n=>Ie(n).some(s=>s.snapshotId===t))}key(t){return`${Ye}${t}`}};async function Ys(e,t){let n=e.check(t);if(!n.allowed)return{check:n,decision:"refused"};if(!await e.confirmIfNeeded(n,t.orgTier))return{check:n,decision:"declined"};let d=n.requiresConfirmation&&e.canAskForConfirmation===!0;return{check:n,decision:d?"confirmed":"allowed"}}var _o={allowed:0,confirmed:1,declined:2,refused:3};function Vs(e,t){return e===void 0||_o[t]>_o[e]?t:e}export{sa as a,Qt as b,ca as c,qe as d,la as e,da as f,Bo as g,pa as h,ma as i,ua as j,ga as k,ba as l,fa as m,ya as n,eo as o,ha as p,za as q,Sa as r,xa as s,i as t,l as u,so as v,B as w,nn as x,an as y,Ke as z,Ea as A,Ca as B,Ta as C,_a as D,Na as E,Da as F,Fa as G,Ma as H,Ua as I,La as J,Ba as K,$a as L,qa as M,Ga as N,Wa as O,Ka as P,Ha as Q,Za as R,Xa as S,Ya as T,Va as U,Ja as V,Qa as W,er as X,tr as Y,or as Z,mn as _,nr as $,ar as aa,rr as ba,ir as ca,sr as da,cr as ea,lr as fa,dr as ga,pr as ha,mr as ia,ur as ja,gr as ka,br as la,fr as ma,yr as na,hr as oa,zr as pa,Sr as qa,xr as ra,Ir as sa,kr as ta,jr as ua,Pr as va,Or as wa,Rr as xa,wr as ya,vr as za,Ar as Aa,Er as Ba,Cr as Ca,Tr as Da,_r as Ea,fn as Fa,Nr as Ga,Dr as Ha,Fr as Ia,Mr as Ja,Ur as Ka,Lr as La,Br as Ma,$r as Na,qr as Oa,Gr as Pa,Wr as Qa,Kr as Ra,go as Sa,Hr as Ta,Zr as Ua,Xr as Va,bo as Wa,Yr as Xa,Vr as Ya,Jr as Za,Qr as _a,ti as $a,oi as ab,ni as bb,ai as cb,ri as db,ii as eb,si as fb,ci as gb,li as hb,di as ib,pi as jb,mi as kb,ui as lb,gi as mb,bi as nb,fi as ob,yi as pb,hi as qb,zi as rb,Si as sb,xi as tb,Ii as ub,ki as vb,ji as wb,Pi as xb,Oi as yb,Ri as zb,wi as Ab,vi as Bb,Ai as Cb,Ei as Db,Ci as Eb,Ti as Fb,_i as Gb,Ni as Hb,Di as Ib,Fi as Jb,Mi as Kb,Ui as Lb,Li as Mb,Bi as Nb,$i as Ob,qi as Pb,Gi as Qb,Wi as Rb,Ki as Sb,Hi as Tb,Zi as Ub,Xi as Vb,Yi as Wb,Vi as Xb,Ji as Yb,Qi as Zb,es as _b,ts as $b,os as ac,ns as bc,as as cc,rs as dc,is as ec,ss as fc,cs as gc,ls as hc,ds as ic,Fn as jc,Mn as kc,us as lc,gs as mc,bs as nc,fs as oc,ys as pc,hs as qc,zs as rc,Ss as sc,xs as tc,Is as uc,Ln as vc,ks as wc,Ro as xc,Ms as yc,Us as zc,xe as Ac,Zn as Bc,Xn as Cc,Ys as Dc,Vs as Ec,Bs as Fc,$s as Gc,Gs as Hc,Ie as Ic,Ws as Jc,Co as Kc,ea as Lc,Ks as Mc,ta as Nc,Hs as Oc,Zs as Pc,Eo as Qc};
7
+ import{b as ie,c as se,d as Vt,e as Jt,f as be}from"./chunk-XU25YA46.mjs";import{a as Zt,e as Xt}from"./chunk-O2PUGRNW.mjs";import{J as re,P as Ue,a as Kt}from"./chunk-7SDZR6SR.mjs";import{f as Le,p as ge,s as Be,u as Yt,w as $e}from"./chunk-3SKLBRPL.mjs";import{b as me,d as ue}from"./chunk-VPDEJGPS.mjs";import{c as qt}from"./chunk-PBE44M2Y.mjs";import{G as Ht}from"./chunk-XZISAZA6.mjs";import{c as Wt}from"./chunk-L4INJ5TZ.mjs";import{c as Gt,e as Fe,g as Me,h as pe}from"./chunk-TZE3Y7IQ.mjs";import{a as $t,b as V}from"./chunk-CA5NAXSU.mjs";import{C as dt,D as pt,E as mt,Ea as zt,F as ut,Fa as St,Fb as Rt,J as gt,K as bt,Ka as ae,L as ft,La as Ae,M as yt,N as ht,Pa as M,Qa as xt,Ra as F,Sa as Ee,Sc as Nt,Ta as It,Ua as kt,Va as Ce,Wa as Te,Wb as wt,Xa as _e,Yb as vt,Zb as At,ac as Et,ad as Dt,bc as Ct,bd as Ft,cb as Ne,cc as Tt,cd as Mt,de as Lt,ed as Ut,ee as Bt,fb as jt,fd as De,gb as Pt,hb as Ot,jc as _t,n as rt,s as we,t as it,u as st,v as ct,w as ne,y as lt,z as ve}from"./chunk-ZQO5PDX5.mjs";import{b as a,c as Oe,e as g,f as r,g as et,i as D,k as c,l as o,m as tt,o as de,p as Re,s as x,u as w,v,w as ot,x as nt,y as G,z as at}from"./chunk-WZQEK4WT.mjs";function sa(e,t,n){return async s=>{let d=s.map(f=>`${f.objectApiName} (${f.records})`).join(", ");e.log(`[WARN] ${n}: the user may not delete ${d} in the target: those records stay`);let p=e.infraServices?.confirmRemovalLeavingUndeletable;if(!p)return!0;let u=e.orgManager.getOrg(t);return p({org:Nt(u,t),objects:s})}}var Qt={code:"NOT_INITIALIZED",message:"Production Guard is not initialized \u2014 infrastructure services missing"};function ca(){return Object.assign(new Error(Qt.message),{code:Qt.code})}var qe={blocked:"GUARD_BLOCKED",declined:"GUARD_DECLINED"};function la(e){return Object.assign(new Error(`Operation blocked by Production Guard: ${e}`),{code:qe.blocked})}function da(e){return e instanceof Error&&e.code===qe.blocked?qe.blocked:void 0}function Bo(e){return e.robustness??zt}function pa(e){return e.bulkManager??new Kt(Bo(e).bulk.maxConcurrentJobs)}var $o={"sync:schedule":"sync:schedule:","sync:pipeline":"sync:pipeline:","seed:pipeline":"seed:pipeline:","offline-replay":"offline-replay-"};function ma(e,t,n){return{id:`${$o[e]}${t}`,type:n,timestamp:Date.now()}}function ua(e,t,n,s){return{id:e.nextId(),type:n,timestamp:Date.now(),correlationId:t.id,payload:s}}function ga(e,t,n,s,d={}){let p=t==="error"?null:d.autoDismissMs===void 0?5e3:d.autoDismissMs,u={id:e.nextId(),type:"notification",timestamp:Date.now(),payload:{level:t,title:n,message:s,...p===null?{}:{autoDismissMs:p},...d.actions?{actions:d.actions}:{},...d.code?{code:d.code}:{}}};e.broker.postToWebview(u),e.log(`[TX] notification: ${n}`)}function ba(e,t,n,s){let d={id:e.nextId(),type:"operation:started",timestamp:Date.now(),payload:{operationId:t,module:n,description:s}};e.broker.postToWebview(d)}function fa(e,t,n,s,d,p){let u={id:e.nextId(),type:"operation:progress",timestamp:Date.now(),payload:{operationId:t,percentage:n,processedRecords:s,totalRecords:d,currentStep:p}};e.broker.postToWebview(u)}function ya(e,t,n){let s={id:e.nextId(),type:"operation:completed",timestamp:Date.now(),payload:{operationId:t,result:n}};e.broker.postToWebview(s)}var qo=Symbol("sandforge.uncorrelated");function eo(e,t,n,s,d,p={}){let u=V(d),f=d instanceof qt?d:void 0,k=qo in s,E=p.code??f?.code??"UNKNOWN";k||Ko(e.broker,u,E),e.log(`[ERR] ${t}: ${u}${k?` (uncorrelated: ${String(s.reason)})`:""}`);let O={id:e.nextId(),type:n,timestamp:Date.now(),...k?{}:{correlationId:s.id},payload:{message:u,code:E,retryable:p.retryable??!1,...f?{orgId:f.orgId}:{},...p.extraPayload}};e.broker.postToWebview(O),e.log(`[TX] ${n}: ${u}`)}function ha(e,t){let n={id:e.nextId(),type:t.type,timestamp:Date.now(),payload:t.payload};e.broker.postToWebview(n)}function za(e){let t=e?.getSandforgeSetting;if(!(!t||!t("grappe.enabled",!1)))return{enabled:!0,autoActivateThreshold:t("grappe.autoActivateThreshold",1e4),maxWorkers:rt.maxWorkers,grappeSize:t("grappe.grappeSize",5e3),strategy:"round_robin",backPressure:{enabled:!1,maxQueueDepth:3,highWaterMark:80,lowWaterMark:60,strategy:"pause",monitoringInterval:5e3},checkpointing:!0,isolationLevel:"per_grappe"}}function Sa(e){let t=new Set(e.map(s=>s.batchSize)),[n]=t;return{...e.length>0?{objectName:e.map(s=>s.objectApiName).join(", ")}:{},...t.size===1&&n!==void 0?{batchSize:n}:{}}}function xa(e,t,n,s,d={}){let p={id:e.nextId(),type:"operation:failed",timestamp:Date.now(),payload:{operationId:t,error:n,retryable:s,...d.extraPayload}};e.broker.postToWebview(p),d.authored!==!0&&Zo(e,n,d.context)}var Go=[/^Operation cancelled by user\b/,/^Operation blocked by Production Guard: /,/^Production Guard is not initialized\b/,/^Duplicate operation: /,/^A backup or rollback operation is already running for org /,/^Object describe not available for '/,/^CRUD_FLS_DENIED: /,/^CRUD\/FLS check failed for /,/^No backup found for operation /,/^Backup \S+ was taken from org /,/^Restore not run: /,/^Pipeline failed$/,/^Pipeline did not start: /,/^Pipeline ran out of time: /,/^Org not found: /,/^No credentials for org /,/^Invalid username format: /];function Wo(e){return Go.some(t=>t.test(e))}var to=1e4,Ge=new WeakMap;function Ko(e,t,n){let s=De(t,{code:n});if(!s?.actionKey)return;let d=Ge.get(e)??new Map,p=Date.now();for(let[u,f]of d)p-f>to&&d.delete(u);d.set(s.code,p),Ge.set(e,d)}function Ho(e,t){let n=Ge.get(e)?.get(t);return n!==void 0&&Date.now()-n<=to}function Zo(e,t,n={}){if(!(e.broker.panelCount>0)||Wo(t))return;let d=$t(t,Ut)??"UNKNOWN",p=De(t,{code:d});if(p?.actionKey){if(Ho(e.broker,p.code))return;e.broker.showFixSuggestion({source:"catalogue",code:p.code,actionKey:p.actionKey});return}let u=e.errorResolver;u&&u.resolveError({errorCode:d,message:t},n).then(f=>{e.broker.showFixSuggestion({source:"model",text:Xo(f)})}).catch(f=>{e.log?.(`[ERR] operation:failed resolution: ${V(f)}`)})}function Xo(e){return e.suggestions[0]?.description||e.explanation}import{isAbsolute as tn}from"node:path";var i=a().min(1).max(128),l=a().regex(/^[A-Za-z][A-Za-z0-9_]*$/,"Invalid Salesforce API name").max(80),so=c(l).max(300),m=a().min(1).max(200),J=a().max(2e3).refine(Fe,{message:Me}),on=a().refine(Gt,{message:"ORDER BY clause must list only field names with optional ASC/DESC and NULLS FIRST/LAST (no LIMIT, OFFSET, FOR UPDATE or subquery)."}),y=100,co=1e4,B=o({keepDays:g().int().min(ve.min).max(ve.max).optional(),excluded:c(l).max(y).refine(e=>new Set(e).size===e.length,"An object is left out twice").optional()}).strict(),he={sweepLate:r().optional(),sweepUntied:r().optional()};function nn(e){return Wt(e)}function an(e,t='turn on "Copy the files of these records"'){return _t(e)?`Sync copies files with the records they hang on, not as an object of their own: "${e}" keeps its content in a file body. Remove it from this configuration and ${t} instead; the sync was not started.`:`Sync does not copy "${e}": no copy writes it \u2014 users and their access, metadata, a record's history, feed or sharing rows, and the records the platform keeps for itself are not data a copy carries. Remove it from this configuration; the sync was not started.`}var rn=w(gt,{error:e=>e.input==="manual"?"Manual conflict review is not available for a sync run: no run shows its conflicts to anyone before it writes. Pick source wins, target wins, newest wins or merge \u2014 target wins keeps every value the target holds where the two orgs differ. The sync was not started.":`Conflict strategy "${String(e.input)}" is not one a sync run acts on: pick source wins, target wins, newest wins or merge. The sync was not started.`}),sn=bt.extend({objectApiName:l.refine(e=>!nn(e),{error:e=>an(String(e.input))}),externalIdField:nt(e=>typeof e=="string"&&e.trim()===""?void 0:e,l.optional()),where:J.optional(),orderBy:on.optional(),batchSize:g().int().positive().max(co).optional()}).strip().refine(e=>e.operation!=="upsert"||(e.externalIdField??"Id").toLowerCase()!=="id",{path:["externalIdField"],error:e=>`An upsert of "${String(e.input.objectApiName)}" needs an External ID field: matching on Id cannot work, because the id belongs to the source org and the target has never issued it. Name an External ID field both orgs share, or set the operation to insert. The sync was not started.`}).superRefine((e,t)=>{let n=Ft([e]);n.length!==0&&t.addIssue({code:G.custom,message:`${Mt(n)} The sync was not started.`,params:{unreadablePatterns:n}})});function oo(e){return et({error:()=>`Sync does not run Apex: remove "${e}" from this configuration. The sync was not started so the script cannot be skipped without you knowing.`}).optional()}var Ke=ft.extend({id:m.optional(),sourceOrgId:i,targetOrgId:i,objects:c(sn).min(1).max(y),conflictStrategy:rn,createdAt:a().max(40).optional(),updatedAt:a().max(40).optional(),preScript:oo("preScript"),postScript:oo("postScript"),dryRun:v(!1,{error:()=>'A sync configuration cannot ask for a dry run: remove "dryRun" from it. A run of it writes to the target org; to see what it would write, simulate it from the Sync page. The run was not started, so it cannot write while you believed it was only reporting.'}).optional()}).strip().superRefine((e,t)=>{e.direction==="target_to_source"&&t.addIssue({code:G.custom,path:["direction"],message:'Sync writes source to target only: direction "target_to_source" is not supported. Swap the source and target orgs to copy the other way. The sync was not started, so it cannot write into the org you meant to read from.'}),e.mode!=="full"&&e.mode!=="delta"&&t.addIssue({code:G.custom,path:["mode"],message:`Sync runs a full or a delta sync only: mode "${e.mode}" is not implemented. Set mode to "full" or "delta". The sync was not started, so it cannot replay the whole object set while you believed it was reading changes only.`}),e.mode==="delta"&&e.objects.forEach((n,s)=>{n.operation==="upsert"||n.operation==="update"||t.addIssue({code:G.custom,path:["objects",s,"operation"],message:`A delta sync writes ${n.objectApiName} again for every record it reads twice, and ${n.operation} would ${n.operation==="insert"?"create a second copy":"delete a record already gone"}. Write it by upsert on an External ID, or by update, or run the configuration in full. The sync was not started.`})}),e.propagateDeletes===!0&&(e.mode!=="delta"?t.addIssue({code:G.custom,path:["propagateDeletes"],message:'Deletions are carried by a delta sync only, which knows since when to look for them: set mode to "delta", or turn deletions off. The sync was not started.'}):e.objects.forEach((n,s)=>{if(n.operation!=="upsert"&&n.operation!=="update")return;let d=Ht(n);"refused"in d&&t.addIssue({code:G.custom,path:["objects",s],message:`${d.refused} Turn deletions off, or carry a source field onto the key. The sync was not started.`})}))}),Ea=o({suggestedName:a().min(1).max(255).refine(e=>!e.includes("/")&&!e.includes("\\"),"suggestedName must not contain a path"),content:a().max(32*1024*1024),extensions:c(a().regex(/^[A-Za-z0-9]+$/)).max(8).optional()}),Ca=o({config:Ke,muteAutomation:r().optional(),checkpointFirst:B.optional()}),Ta=o({config:Ke,checkpointFirst:B.optional()}),_a=o({operationId:m}),Na=o({config:Ke}),Da=o({id:m}),Fa=o({orgId:i,targetOrgId:i.optional()}),Ma=o({sourceOrgId:i,targetOrgId:i,objectApiName:l}),lo=w(["source_wins","target_wins","newest_wins","manual","merge"]),cn=Re("kind",[o({kind:v("id")}),o({kind:v("externalId"),field:l}),o({kind:v("syncConfig"),configId:m})]),Ua=o({sourceOrgId:i,targetOrgId:i,watchedObjects:c(l).min(1).max(y),apply:c(o({objectApiName:l,match:cn,applyDeletes:r()})).max(y),conflictStrategy:lo,flushIntervalMs:g().int().min(50).max(6e4),maxBatchSize:g().int().min(1).max(200),keepContactPoints:r().optional()}).refine(e=>e.apply.every(t=>e.watchedObjects.includes(t.objectApiName)),{message:"Every applied object must be watched.",path:["apply"]}),La=o({sessionId:a().max(200)}),Ba=o({sourceOrgId:i,targetOrgId:i}),$a=o({conflictId:a().min(1).max(500),eventReplayId:g().optional(),resolution:lo,fieldResolutions:x(a(),o({value:D(),source:w(["source","target","manual"])})).optional()}),qa=o({entryId:m}),Ga=o({runId:m}),Wa=o({realtime:v(!0).optional()}).optional(),Ka=o({sourceOrgId:i,targetOrgId:i,objects:c(l).max(y),configId:m.optional()}),Ha=o({runId:m,includeChanged:r().optional(),sweep:r().optional(),again:r().optional(),muteAutomation:r().optional(),...he}),Za=o({runId:m}),Xa=o({runId:m,again:r().optional(),sweptObjects:so.optional()}),Ya=o({runId:m}),Va=o({runId:m,includeChanged:r().optional(),sweep:r().optional(),again:r().optional(),muteAutomation:r().optional(),...he}),Ja=o({runId:m}),Qa=o({format:w(["csv","json"]),entryIds:c(m).max(500).optional()}),ln=o({id:m,name:a().min(1).max(200),configId:m,cron:a().min(1).max(100),timezone:a().min(1).max(100),enabled:r(),maxRetries:g().int().min(0).max(10),notifyOnComplete:r(),notifyOnFailure:r(),createdAt:a().max(40),updatedAt:a().max(40),version:g().int().positive()}).strip(),er=o({schedule:ln}),tr=o({scheduleId:m,enabled:r()}),or=o({scheduleId:m}),dn=dt.extend({objectApiName:l,recordCount:g().int().positive().max(ne),batchSize:g().int().positive().max(co).optional()}).loose(),pn=pt.extend({childObject:l,lookupField:l,parentObject:l}).superRefine((e,t)=>{e.parents.kind==="existing"&&e.parents.where!==void 0&&!Fe(e.parents.where)&&t.addIssue({code:G.custom,path:["parents","where"],message:Me})}),mn=mt.extend({objects:c(dn).min(1).max(y),relations:c(pn).max(y).optional()}).loose().superRefine(ut),nr=o({orgId:i,template:mn,muteAutomation:r().optional(),checkpointFirst:B.optional(),fit:o({share:g().gt(0).max(1),withinMB:g().positive().max(1e6).optional(),before:g().int().positive().max(ne*y)}).strict().optional(),locale:a().regex(/^[a-z]{2,3}(?:_[A-Za-z0-9]{2,4}){0,2}$/).optional(),dryRun:r().optional()}),ar=o({orgId:i}),rr=o({orgId:i,objects:c(l).min(1).max(y),publishes:r().optional()}).strict(),ir=o({orgId:i,objectApiName:l}),sr=o({id:m}),cr=o({template:x(a(),D())}),lr=o({description:a().max(1e4)}),dr=o({}).strict(),pr=o({orgId:i,pack:ae,seed:Ae.shape.seed,articleBodyField:l.optional()}).strict(),mr=o({orgId:i,pack:ae,options:Ae,locale:a().regex(/^[a-z]{2,3}(?:_[A-Za-z0-9]{2,4}){0,2}$/).optional(),muteAutomation:r().optional(),checkpointFirst:B.optional()}).strict(),ur=o({orgId:i}).strict(),gr=o({pack:ae,overwrite:r().optional()}).strict(),br=o({runId:m,choice:Rt,overwrite:r().optional()}).strict(),un=131072,gn=o({objectApiName:l,whereClause:J.optional()}).loose(),fr=o({sourceOrgId:i}),yr=o({sourceOrgId:i,targetOrgId:i,objects:c(gn).min(1).max(y),upsert:r().optional(),externalIdField:l.optional(),previewId:m.optional(),keepContactPoints:r().optional(),checkpointFirst:B.optional()}).refine(e=>!e.upsert||e.externalIdField!==void 0,{message:"externalIdField is required when upsert is true",path:["externalIdField"]}),bn=o({csvHeader:a().min(1).max(500),sfFieldApiName:a().max(80),sfFieldType:a().max(40),sfFieldLength:g().int().positive().nullable()}).loose(),hr=o({orgId:i,objectApiName:l,records:c(x(a(),a().max(un))).min(1).max(st),columnMappings:c(bn).min(1).max(ct),externalIdField:l.optional(),checkpointFirst:B.optional()}),zr=o({orgId:i,objects:c(l).min(1).max(y),wheres:x(l,J).optional(),slices:r().optional()}).refine(e=>Object.keys(e.wheres??{}).every(t=>e.objects.some(n=>n.toLowerCase()===t.toLowerCase())),{message:"A filter names an object the backup reads: give it in objects",path:["wheres"]}),Sr=o({orgId:i}),xr=o({orgId:i,templateId:a().min(1).max(200).optional()}),Ir=o({orgId:i,operationId:a().min(1).max(200)}),kr=o({orgId:i,operationIds:c(a().min(1).max(200)).min(1).max(1e3).optional()}),W={acceptAutomation:r().optional(),acceptEmails:r().optional(),muteAutomation:r().optional()},X={fromPage:v(!0).optional()},jr=o({orgId:i,operationId:m,rewriteAll:r().optional(),includeChanged:r().optional(),slices:c(g().int().positive()).min(1).max(lt*y).optional(),...W,...X}),Pr=o({orgId:i,act:w(["masking","restore","cleanup"]),objects:c(o({objectApiName:l,records:g().int().min(0)})).max(y),erasure:r().optional(),...W,...X}),He={objects:c(l).min(1).max(y).optional(),where:J.optional()},Ze=e=>e.where===void 0||e.where.trim()===""||e.objects?.length===1,Xe={message:"A WHERE clause filters the rows of one object: name exactly one in objects",path:["where"]},Or=o({orgId:i,templateId:m,...He,resumeFrom:m.optional(),snapshot:r().optional(),slices:r().optional(),maxRequests:g().int().positive().max(1e9).optional(),abandon:r().optional(),...W,...X}).refine(Ze,Xe).refine(e=>!(e.snapshot===!0&&e.resumeFrom!==void 0&&e.slices!==!0),{message:"A resume takes no snapshot: the run it resumes has written over some of its rows",path:["snapshot"]}).refine(e=>!(e.slices===!0&&e.snapshot===!1),{message:"A run in slices backs each slice up before it masks it: it cannot keep no snapshot",path:["slices"]}).refine(e=>e.maxRequests===void 0||e.slices===!0,{message:"A bound on requests stops a run in slices between two of them: give slices too",path:["maxRequests"]}).refine(e=>e.abandon!==!0||e.resumeFrom===void 0&&e.snapshot!==!0&&e.maxRequests===void 0,{message:"Giving up a set of slices masks nothing: it takes no resume, snapshot or bound",path:["abandon"]}),Rr=o({orgId:i,templateId:m,...He,slices:r().optional()}).refine(Ze,Xe),wr=o({orgId:i,templateId:m,...He}).refine(Ze,Xe),vr=o({name:a().trim().min(1).max(jt),rules:c(Ot).min(1).max(Pt).refine(e=>new Set(e.map(t=>t.fieldPattern.toLowerCase())).size===e.length,"A field has two rules")}),Ar=o({templateId:m}),Er=o({orgId:i,objectNames:c(l).min(1).max(y)}),Cr=o({orgId:i,objects:c(o({objectApiName:l,duplicateKey:l.optional()})).min(1).max(10).refine(e=>new Set(e.map(t=>t.objectApiName.toLowerCase())).size===e.length,{message:"Each object may be named once per scan"}),staleDays:g().int().min(1).max(3650)}),po=c(l).min(1).max(10).refine(e=>new Set(e.map(t=>t.toLowerCase())).size===e.length,{message:"Each object may be named once per request"}),Tr=o({orgId:i,objects:po}),_r=o({orgId:i,objects:po,requestId:Oe().optional(),email:a().trim().refine(Ct,"Not an email address").optional(),name:a().refine(Tt,"Not a name").optional(),phone:a().refine(Et,"Not a phone number").optional()}).refine(e=>e.email!==void 0||e.name!==void 0||e.phone!==void 0,{message:"A search needs an email address, a name or a phone number"}),fn=o({orgId:i,requestId:Oe()}),ze=a().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record Id"),Nr=o({runId:m,recordId:ze}).strict(),Dr=fn.extend({mode:w(["anonymize","delete"]),records:c(o({objectApiName:l,ids:c(ze).min(1).max(200)})).min(1).max(10).refine(e=>new Set(e.map(t=>t.objectApiName.toLowerCase())).size===e.length,{message:"Each object may be named once per request"}),dryRun:r(),...W}),yn=Re("kind",[o({kind:v("stale"),days:g().int().min(1).max(3650)}),o({kind:v("orphans"),fieldApiName:l}),o({kind:v("duplicates"),keyField:l})]),mo=o({orgId:i,objectApiName:l,recommendation:yn}),Fr=mo.extend({after:o({skip:g().int().nonnegative().max(1e8),id:ze.optional(),modified:a().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:?\d{2})$/).optional()}).strict().optional()}),Mr=mo.extend({dryRun:r(),...W,...X}),We=2e3,uo={mode:w(["objects","org"]),objects:c(l).min(1).max(We).optional(),excluded:c(l).max(We).optional(),customSettings:r().optional(),files:r().optional(),managedPackages:r().optional(),unrestorable:r().optional()},hn=o(uo).strict().refine(e=>e.mode==="objects"==(e.objects!==void 0),{message:"The objects picked are named in objects mode, and only there"}),Ur=o({orgId:i,...uo,objects:c(l).max(We).optional()}).strict().refine(e=>e.mode==="objects"==(e.objects!==void 0),{message:"The objects picked are named in objects mode, and only there"}),Lr=o({orgId:i,request:hn,deleteMode:w(["recycle","hard"]),checkpointFirst:r().optional(),acceptNoUndo:r().optional(),acceptPeopleActive:r().optional(),...W,...X}),Br=o({orgId:i,previewId:m.optional(),resumeRunId:a().regex(/^em-\d{8}-\d{6}-[a-z0-9]{4}$/).optional(),acceptNoUndo:r().optional(),acceptPeopleActive:r().optional(),checkpointFirst:r().optional(),...W,...X}).refine(e=>e.previewId===void 0!=(e.resumeRunId===void 0),{message:"An emptying acts on a preview, or takes up a run: one of them"}),$r=o({operationId:m}),qr=o({orgId:i,runId:a().regex(/^em-\d{8}-\d{6}-[a-z0-9]{4}$/),...W,...X}),Gr=o({orgId:i}),Wr=o({orgId:i}).strict(),Kr=o({alertId:m}),go=o({sourceOrgId:i,targetOrgId:i}),Hr=go.extend({types:c(a().min(1).max(80)).min(1).max(50),includeManaged:r().optional()}),zn=o({componentType:w(At),fullName:a().min(1).max(400).regex(/^[^\u0000-\u001f\u007f]+$/,"A component name holds no control character")}),Zr=go.extend({components:c(zn).min(1).max(500).refine(e=>new Set(e.map(t=>`${t.componentType}:${t.fullName}`)).size===e.length,{message:"Each component may be named once per deployment"}),testLevel:w(wt),runTests:c(a().max(255).regex(vt,"Not an Apex class name")).max(100).optional()}).refine(e=>e.sourceOrgId!==e.targetOrgId,{message:"The source and the target are the same org",path:["targetOrgId"]}).refine(e=>e.testLevel!=="RunSpecifiedTests"||(e.runTests?.length??0)>0,{message:"RunSpecifiedTests names at least one test class",path:["runTests"]}),Xr=o({validationId:a().regex(/^0Af[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/,"Not a deployment id"),targetOrgId:i}).strict(),Sn=a().regex(/^\d+\.\d+\.\d+$/,"Invalid semver"),ye=a().regex(/^[A-Za-z][A-Za-z0-9_]*\.[A-Za-z][A-Za-z0-9_]*$/,"Expected an Object.field key").max(170),xn=o({name:a().min(1).max(80),label:a().min(1).max(200),filterField:l,valuesSoql:a().min(1).max(4e3)}),In=o({name:a().min(1).max(80),label:a().min(1).max(200),whereFragment:J}),no=de([o({action:v("clear")}),o({action:v("replace"),value:a().max(255)})]),bo=o({rootObject:l,axes:c(xn).max(20),edgeCases:c(In).max(50),budgetMaxRecords:g().int().positive().max(1e5).optional(),candidatesPerCombination:g().int().positive().max(20).optional(),expectedObjects:c(l).max(100).optional(),maxNodes:g().int().min(10).max(500).optional(),excludedObjects:c(l).max(200).optional(),excludedFields:x(l,c(l).max(500)).optional(),sasDir:a().min(1).max(500).optional(),datasetDir:a().min(1).max(500).optional(),rulesFilePath:a().min(1).max(500).optional(),datasetVersion:Sn.optional(),protectedOrgIds:c(i).max(50).optional(),identityKeys:x(l,c(l).min(1).max(10)).optional(),undeletableObjects:x(l,l).optional(),requiredLookupPlaceholders:x(ye,o({name:a().min(1).max(200),recordTypeDeveloperName:a().min(1).max(97).optional(),targetObjectApiName:l.optional()})).optional(),requiredFieldDefaults:x(ye,D()).optional(),picklistRules:x(ye,no).optional(),defaultPicklistRule:no.optional(),duplicateErrorPatterns:c(a().min(1).max(200)).max(50).optional(),mockDetection:o({metadataTypeApiName:l,isMockedFieldApiName:l}).optional(),mandatoryLookups:x(l,c(l).min(1).max(50)).optional(),presenceKeys:x(l,l).optional()}),Yr=o({config:bo}),Vr=o({sourceOrgId:i}),Jr=o({fields:c(ye).min(1).max(2e3)}),Qr=o({sourceOrgId:i,author:a().min(1).max(120).optional()}),ce=o({organizationId:kt,checkpointId:F}).strict(),kn=bo.pick({requiredFieldDefaults:!0,requiredLookupPlaceholders:!0,picklistRules:!0,defaultPicklistRule:!0,identityKeys:!0,undeletableObjects:!0,duplicateErrorPatterns:!0,mockDetection:!0,protectedOrgIds:!0}).strict(),fo=ce.extend({choices:Ne,config:kn.optional()}).strict(),jn=fo.extend({choices:Ne.optional()}).strict(),ti=o({targetOrgId:i,replay:fo.optional(),pilot:r().optional(),reload:r().optional(),writeEncrypted:r().optional(),maxRecords:g().int().positive().max(1e6).optional(),muteAutomation:r().optional(),checkpointFirst:B.optional(),sweep:r().optional(),...he,includeChanged:r().optional(),acceptEmails:r().optional(),acceptAutomation:r().optional(),goneFirst:c(ze).max(1e6).optional()}),Pn=o({targetOrgId:i}),oi=Pn.extend({replay:jn.optional()}),ni=o({targetOrgId:i,loadedAt:a().min(1).max(64),includeChanged:r().optional(),sweep:r().optional(),...he,muteAutomation:r().optional(),replay:ce.optional()}),ai=o({targetOrgId:i,loadedAt:a().min(1).max(64),reload:r().optional(),replay:ce.optional()}),ri=o({targetOrgId:i,loadedAt:a().min(1).max(64),sweptObjects:so.optional(),reload:r().optional(),replay:ce.optional()}),ii=o({targetOrgId:i,loadedAt:a().min(1).max(64),includeChanged:r().optional(),replay:ce.optional()}),yo=1e3,ho=3650,On=200,Z=c(l).min(1).max(yo).refine(e=>new Set(e).size===e.length,"An object is named twice");function zo(e){return e.mode==="picked"?e.objects!==void 0:e.objects===void 0}var So=de([v("all"),c(l.refine(e=>e.toLowerCase().endsWith("__c"),"A custom setting's API name ends in __c")).min(1).max(yo).refine(e=>new Set(e.map(t=>t.toLowerCase())).size===e.length,"A custom setting is named twice")]),xo={path:["objects"],message:'Name the objects with "picked", and none with "everything"'},si=o({orgId:i.optional()}).optional(),Rn=1e6,Io=g().int().min(1).max(Rn),ci=o({orgId:i,mode:_e,objects:Z.optional(),excluded:Z.optional(),customSettings:So.optional(),maxTotal:Io.optional()}).refine(zo,xo),li=o({orgId:i,name:Te,mode:_e,objects:Z.optional(),excluded:Z.optional(),customSettings:So.optional(),maxTotal:Io.optional(),keepDays:g().int().min(0).max(ho),ignoredFields:Ce.optional()}).refine(zo,xo),di=o({checkpointId:F,objects:Z.optional(),muteAutomation:r().optional(),acceptOutside:r().optional()}),pi=o({checkpointId:F,previewId:Ee,objects:Z.optional(),acceptAutomation:r(),muteAutomation:r().optional(),acceptEmails:r().optional(),acceptNoUndo:r(),acceptRecreate:r(),acceptOutside:r(),acceptUnseen:r(),fromPage:v(!0).optional()}),mi=o({checkpointId:F,previewId:Ee,objects:Z,acceptOutside:r()}),ui=o({checkpointId:F}),wn=200,gi=o({token:m,orgId:i,key:a().min(1).max(wn),keepDays:g().int().min(0).max(ho)}),bi=o({checkpointId:F,rewindId:It,acceptAutomation:r(),muteAutomation:r().optional(),acceptEmails:r().optional(),fromPage:v(!0).optional()}),fi=o({checkpointIds:c(F).min(1).max(On).refine(e=>new Set(e).size===e.length,"A checkpoint is named twice")}),yi=o({checkpointId:F,keep:r()}),hi=o({checkpointId:F,name:Te}),zi=o({checkpointId:F,fields:Ce}),vn=500,Si=o({orgIds:c(i).min(1).max(vn).refine(e=>new Set(e).size===e.length,"An org is named twice").optional()}).strict().optional(),xi=o({sourceOrgId:i,targetOrgId:i,includeStandardObjects:r()}),Ii=o({sourceOrgId:i,objectApiNames:c(l).min(1).max(it)}),ki=o({sourceOrgId:i,targetOrgId:i,selectedObjects:c(l).max(y),includeStandardObjects:r(),maxDepth:g().int().min(1).max(10).optional(),maxObjects:g().int().min(1).max(500).optional()}),ji=o({complianceFramework:ht,objectFilters:x(a(),J).optional(),overrides:c(o({objectApiName:l,fieldApiName:l,method:de([yt,v("skip")])})).max(500).optional()}),Pi=o({grappeThreshold:g().int().nonnegative(),keepContactPoints:r().optional(),muteAutomation:r().optional(),checkpointFirst:B.optional()}),Oi=o({mode:o({share:v(!0).optional(),caps:x(l,g().int().min(1).max(ne)).refine(e=>Object.keys(e).length<=y,"Too many caps").optional(),all:g().int().min(1).max(ne).optional(),withinMB:g().positive().max(1e6).optional()}).strict().refine(e=>e.share===!0||e.caps!==void 0||e.all!==void 0,"Fit by share, by caps, or both"),muteAutomation:r().optional(),checkpointFirst:B.optional()}),Ri=o({objectApiName:l}),wi=o({orgId:i.optional(),sourceOrgId:i.optional(),alreadySelected:c(l).max(y).optional()}).loose(),vi=o({orgId:i.optional(),sourceOrgId:i.optional(),objectApiName:l.optional(),alreadySelected:c(l).max(y).optional(),selectedObjects:c(l).max(y).optional(),availableObjects:c(l).max(500).optional()}).loose(),Ai=o({sourceOrgId:i,targetOrgId:i.optional(),selectedObjects:c(l).min(1).max(y),parentObjects:c(l).max(y).optional()}).loose(),An=St.extend({sourceOrgId:i,targetOrgId:i,selectedObjects:c(l).min(1).max(y),parentObjects:c(l).max(y).default([])}).loose(),Ei=o({config:An.optional(),sourceOrgId:i.optional(),targetOrgId:i.optional(),selectedObjects:c(l).min(1).max(y).optional(),parentObjects:c(l).max(y).optional()}).loose(),En=a().min(1).max(5e4),Ci=o({conversationId:m,message:a().max(5e4)}),Ti=o({title:a().min(1).max(300)}),_i=o({conversationId:m}),Ni=o({apiKey:a().min(1).max(500),errorResolution:r().optional()}),Di=o({enabled:r().optional(),errorResolution:r().optional()}),Fi=o({orgId:i,objectName:l,sampleSize:g().int().positive().max(1e4).optional()}),Mi=o({orgId:i,prompt:a().trim().min(1).max(2e3).optional(),soql:a().trim().min(1).max(2e4).optional()}).refine(e=>e.prompt===void 0!=(e.soql===void 0),{message:"Send a prompt to draft from or a query to check, not both and not neither"}),Ui=o({description:En,orgIds:c(i).max(50).optional()}),Li=o({requestId:m}),fe=c(a().min(1).max(M.picklistValue)).max(M.picklistValues),ao={label:a().max(M.agentLabel).optional(),description:a().max(M.agentDescription).optional()},Bi=o({text:a().trim().min(1).max(M.text),language:ae.shape.language,casePicklists:o({Status:fe.optional(),Origin:fe.optional(),Priority:fe.optional(),Type:fe.optional()}).optional(),agent:o({topics:c(o({name:a().min(1).max(M.agentName),...ao,actions:c(o({name:a().min(1).max(M.agentName),...ao})).max(M.agentActions)})).max(M.agentTopics)}).optional(),draft:xt.optional(),maskOnly:r().optional()}),$i=o({filePath:a().min(1).max(2e3)}),qi=o({name:a().max(200),config:x(a(),D())}),Gi=o({operationId:m.optional(),executionId:m.optional(),objectName:a().min(1).max(200).optional()}).loose(),Wi=o({policyId:m}),Ki=o({policy:x(a(),D())}),Hi=o({policyId:m,orgId:i}),Zi=o({module:a().min(1).max(50).optional(),orgId:i.optional(),offset:g().int().min(0).max(we).optional(),limit:g().int().min(1).max(we).optional()}).optional(),Xi=o({operationId:m.optional()}).optional(),Cn=w(["syncMappings","forgePlans","pipelines","anonymizationTemplates"]),Yi=o({categories:c(Cn).min(1).max(50)}),Vi=o({json:a().min(1).max(5e6),overwrite:r()}),Ji=o({json:a().min(1).max(5e6)}),Qi=o({orgId:a().max(128),authMethod:a().min(1).max(50),alias:a().max(100).optional(),loginUrl:a().max(500).optional(),username:a().max(300).optional(),password:a().max(500).optional(),securityToken:a().max(100).optional(),clientId:a().max(256).optional(),jwtKeyFile:a().max(4096).optional()}).loose(),ko=a().trim().max(100).regex(/^[\w.-]*$/,"an alias is letters, digits, dots, dashes and underscores").optional(),Tn=a().trim().min(1,"the username is required").max(80).regex(/^[\w.@+-]+$/,"a username is written like an email address"),jo=a().trim().min(1,"the consumer key is required").max(256).regex(/^[A-Za-z0-9._-]+={0,2}$/,"a consumer key is letters, digits, dots, dashes and underscores"),_n=a().trim().min(1,"the private key file is required").max(4096).regex(/^[^\u0000-\u001f\u007f]+$/,"the private key file path holds a control character").refine(e=>tn(e),"give the private key file as an absolute path"),es=o({alias:ko,loginUrl:a().max(500).optional(),username:Tn,clientId:jo,jwtKeyFile:_n}).loose(),ts=o({alias:ko,loginUrl:a().max(500).optional(),clientId:jo}).loose(),os=o({requestId:m}),ns=o({orgId:i}),as=o({orgId:i}),rs=o({orgId:i}).strict(),is=o({orgId:i,alias:a().trim().min(1).max(100),color:a().regex(/^#[0-9A-Fa-f]{6}$/),tags:c(a().trim().min(1).max(50)).max(20),staging:r().optional()}),ss=o({key:a().min(1).max(200),value:D()}),cs=o({enabled:r()}),ls=o({lng:w(["en","fr","de","es","ja","pt-BR"])}),ds=o({targetOrgId:i,sourceOrgId:i.optional()}),ps=o({moduleId:a().min(1).max(64),route:a().min(1).max(64),overlay:r()}),ms=o({moduleId:a().min(1).max(64)}),Nn=80,Dn=ot(e=>Lt(e)||Bt(e)||typeof e=="string"&&e.trim()!==""&&e.length<=Nn,{message:"Not a pipeline step type"}),Fn=o({pipeline:o({name:a().min(1).max(200),steps:c(o({type:Dn,config:x(a(),D()).default({})}).loose()).max(200),variables:c(x(a(),D())).max(200).default([]),triggers:c(x(a(),D())).max(50).default([])}).loose(),variables:x(a(),a().max(2e3)).optional(),dryRun:r().optional()}),Mn=tt({since:at.datetime({offset:!0}),runner:w(["cron","taskScheduler","githubActions"]),file:a().min(1).max(255).refine(e=>!/[\\/]/.test(e),"The file's name, without its folder"),digest:a().regex(/^sha256:[0-9a-f]{64}$/,"Not a digest: sha256: and 64 hex digits")}),us=Fn.shape.pipeline.extend({id:a().min(1).max(200),runsOutside:Mn.optional()}),gs=o({pipelineId:m}),bs=o({id:a().max(200),config:x(a(),D())}),fs=o({id:m}),ys=o({operationId:m,stepId:m,decision:w(["approved","rejected"])}),Un=255,Po={pipelineId:m,stepId:m},hs=o({pipelineId:m}),zs=o({...Po,typed:a().min(1).max(Un)}),Ss=o(Po),xs=o({category:a().max(100).optional(),query:a().max(500).optional()}).loose().optional(),Is=o({templateId:m});function Ln(e){return e.issues.slice(0,3).map(t=>`${t.path.join(".")||"(root)"}: ${t.message}`).join("; ")}function Bn(e){let t=e.issues.map(n=>n.code==="custom"?n.params?.unreadablePatterns:void 0);return t.every(n=>n!==void 0)?t.flat():void 0}function ks(e,t,n,s){let d=e.safeParse(t.payload);if(!d.success){let p=Ln(d.error),u=Bn(d.error);return eo(s,t.type,n,t,new Error(`Invalid payload \u2014 ${p}`),u?{code:Dt,extraPayload:{rules:u}}:{code:"INVALID_PAYLOAD"}),null}return d.data}var $n=5;function Se(e){return e.slice(0,15)}function qn(e){let t=e.errors?.[0];if(t===void 0)return"The org gave no reason.";if(typeof t=="string")return t;let n=t.statusCode??"",s=t.message??"";return n&&s?`${n}: ${s}`:n||s||"The org gave no reason."}function Oo(e){let t=new Set;for(let n of e){let s=n.Id;typeof s=="string"&&t.add(Se(s))}return t}async function Ro(e){let t=[],n=[],s={},d=!1,p=!1,u=e.stampsFor,f=ie(e.org),k=e.org.serverTime?.bind(e.org),E=u&&k?Date.now()+await se({serverTime:k})-re:Number.NaN;for(let{objectApiName:O,ids:A}of e.plan){let I={objectApiName:O,planned:A.length,undeleted:0,alreadyBack:0,goneForGood:0,refused:0,reasons:[]};t.push(I);let z=_=>{I.reasons.length<$n&&!I.reasons.includes(_)&&I.reasons.push(_)},R=pe(O);for(let _=0;_<A.length;_+=me){let C=A.slice(_,_+me);if(p||e.signal?.aborted){p=!0,I.notReached=(I.notReached??0)+C.length,n.push(...C);continue}let[ee]=ue(C,me),K,te;try{K=Oo((await e.org.queryDeleted(`SELECT Id FROM ${R} WHERE Id IN (${ee}) AND IsDeleted = true`)).records),te=Oo((await e.org.query(`SELECT Id FROM ${R} WHERE Id IN (${ee})`)).records)}catch(j){I.refused+=C.length,z(`The recycle bin could not be read: ${V(j)}`),n.push(...C);continue}let h=C.filter(j=>K.has(Se(j)));for(let j of C)K.has(Se(j))||(te.has(Se(j))?I.alreadyBack++:I.goneForGood++);if(h.length===0)continue;let U;try{d=!0;let j=await e.undelete(h),T=Array.isArray(j)?j:[j];U=h.map((H,oe)=>T[oe]??{success:!1})}catch(j){let T=V(j);U=h.map(()=>({success:!1,errors:[T]}))}let Y=[];U.forEach((j,T)=>{if(j.success===!0){I.undeleted++,u?.(h[T])&&Y.push(h[T]);return}I.refused++,z(qn(j)),n.push(h[T])}),Y.length>0&&Number.isFinite(E)&&Object.assign(s,await be(e.org,R,Y,E,f))}}return{objects:t,left:n,wrote:d,cancelled:p,stamps:s}}function wo(e){return e.refused+e.goneForGood+(e.notReached??0)}async function Gn(e,t,n,s){let d=new Map(Object.entries(s).map(([u,f])=>[u.slice(0,15),Date.parse(f)])),p=new Set;for(let{objectApiName:u,ids:f}of t){let k=pe(u);for(let E of ue(f)){let O;try{O=(await e.query(`SELECT Id, LastModifiedDate FROM ${k} WHERE Id IN (${E})`)).records}catch{continue}for(let A of O){if(typeof A.Id!="string")continue;let I=A.Id.slice(0,15),z=Date.parse(String(A.LastModifiedDate??""));(z<=n||z<=(d.get(I)??Number.NaN))&&p.add(I)}}}return p}function vo(e){let t=Date.parse(e.startedAt),n=Date.parse(e.lastWrittenAt??e.end?.at??"");return Number.isFinite(n)?{runRecordedAt:new Date(n),...Number.isFinite(t)?{runDurationMs:Math.max(0,n-t)}:{}}:{}}function Wn(e){return e.filter(t=>t.deleted+t.alreadyGone>0).map(t=>t.objectApiName)}async function Ms(e){let{run:t,includeChanged:n}=e,s=e.again===!0,d=ge(t,s),p=d.reduce((b,S)=>b+S.ids.length,0),u=Be(t),f=u.reduce((b,S)=>b+S.ids.length,0),k=Yt(t),E=k.reduce((b,S)=>b+S.ids.length,0),O=[],A=e.backups,I=e.undelete;k.length>0&&!I&&O.push(`The ${E} record(s) the run deleted could not be brought back from the recycle bin here: the next removal offers them again.`),u.length>0&&!A&&O.push(`The values from before the run of ${f} record(s) it wrote over could not be read here: they were not put back, and the next removal offers them again.`);let z,R,_={},C=(e.earlierRuns??[]).map(b=>({runId:b.runId,keys:new Set([...ge(b),...Be(b)].flatMap(({ids:S})=>S.map(L=>L.slice(0,15))))})),ee=b=>C.some(({keys:S})=>S.has(b.slice(0,15))),K=e.sweep,te=u.length>0&&A||k.length>0&&I||K?async b=>{if(k.length>0&&I){let N=u.length>0&&A?await Gn(e.org,u,await Vt(e.org,xe(t)),t.removal?.removalStamps??{}):void 0,q=N?Date.now()+await se(e.org)-re:0;if(R=await Ro({org:e.org,plan:k,undelete:I,...C.length>0?{stampsFor:ee}:{},...e.signal?{signal:e.signal}:{}}),N&&R.wrote){let P=ie(e.org);for(let{objectApiName:Pe,ids:Mo}of u){let Uo=Mo.filter(Lo=>N.has(Lo.slice(0,15)));Object.assign(_,await be(e.org,Pe,Uo,q,P))}}if(R.cancelled||e.signal?.aborted)return R.wrote}if(u.length>0&&A){let N={...t.removal?.removalStamps,..._};z=await Jt({org:e.org,plan:u,backups:A,...xe(t)!==void 0?{lastWriteAt:xe(t)}:{},includeChanged:n,...Object.keys(N).length>0?{stamps:N}:{},...t.unkept?{unkept:t.unkept}:{},...C.length>0?{stampsFor:ee}:{},...e.signal?{signal:e.signal}:{}})}let S=(R?.wrote??!1)||(z?.wrote??!1);if(z?.cancelled||e.signal?.aborted)return S;let L=K?await K(b):!1;return S||L}:void 0,h=await Ue(e.org,d,{...vo(t),...t.removal?.removalStamps?{removalStamps:t.removal.removalStamps}:{},...t.removal?.removalSpans?{removalSpans:t.removal.removalSpans}:{},includeChanged:n,...te?{sweep:te}:{},...e.afterRemoval?{afterRemoval:e.afterRemoval}:{},...e.automationMade?{automationMade:e.automationMade}:{},...e.runUserId?{runUserId:e.runUserId}:{},...e.onUndeletable?{onUndeletable:e.onUndeletable}:{},...e.beforeFirstWrite?{beforeFirstWrite:e.beforeFirstWrite}:{},signal:e.signal,onProgress:e.onProgress}),U=new Date().toISOString();if(h.stoppedForUndeletable)return{result:{runId:t.runId,status:"cancelled",includeChanged:n,objects:[],finishedAt:U},planned:p,plannedBack:f,plannedUndelete:E,notes:[],stoppedForUndeletable:!0};let Y=s?void 0:t.removal?.undo?.removedAt,j={runId:t.runId,status:Zn(Xn(Zt(h.objects,h.cancelled),h.objects,z),h.objects,z,R),includeChanged:n,objects:h.objects,finishedAt:U,...Y?{leftBy:Y}:{},...z&&z.objects.length>0?{restored:z.objects}:{},...R&&R.objects.length>0?{undeleted:R.objects}:{}},T=Xt(j,p,t.removal?.undo,s),H=new Set(h.gone),oe=H.size>0||s&&T?d.flatMap(({ids:b})=>b.filter(S=>!H.has(S))):void 0,Je={..._,...h.stamps},Qe=Object.keys(Je).length>0,No=z?.objects.some(b=>b.restored+(b.restoredWithout??0)>0)===!0,Do=R!==void 0&&!R.cancelled;if(T||Qe||h.span||oe||z||R)try{await e.store.updateRemoval(t.runId,b=>({...b,...T?{undo:T}:{},...Qe?{removalStamps:{...b.removalStamps,...Je}}:{},...h.span?{removalSpans:[...b.removalSpans??[],h.span]}:{},...oe?{removalLeft:oe}:{},...z?{restoreLeft:z.left}:{},...No?{restoredAt:U}:{},...R?{undeleteLeft:R.left}:{},...Do?{undeletedAt:U}:{}}))}catch(b){O.push(`What this removal did could not be kept (${b instanceof Error?b.message:String(b)}): the next removal of the run may set out to take records already gone.`)}let Fo=Object.keys(z?.stamps??{}).length>0?await Kn(e.org,t,e.earlierRuns??[]):new Map,ke=[];for(let{runId:b,keys:S}of C){let L=Fo.get(b),N=Object.fromEntries(Object.entries({...R?.stamps,...z?.stamps}).filter(([P])=>S.has(P.slice(0,15))&&!L?.has(P.slice(0,15)))),q=Object.keys(N).length;if(q!==0)try{await e.store.updateRemoval(b,P=>({...P,removalStamps:{...P.removalStamps,...N},...h.span?{removalSpans:[...P.removalSpans??[],h.span]}:{}})),ke.push({runId:b,records:q})}catch(P){O.push(`What this removal gave back of ${q} record(s) the run ${b} wrote too could not be kept on it (${P instanceof Error?P.message:String(P)}): its removal reads them as changed since it.`)}}let le=e.configs;if(le&&H.size>0&&le.isSaved(t.configId)){let b={sourceOrgId:t.sourceOrgId,targetOrgId:$e(t)};try{let S=d.filter(P=>Le.includes(P.objectApiName)).flatMap(({ids:P})=>P.filter(Pe=>H.has(Pe))),L=le.forgetFiles(t.configId,b,S),N=Wn(h.objects).filter(P=>!Le.includes(P)),q=le.markRemoved(t.configId,b,[...new Set([...N,...L.map(P=>P.objectApiName)])],U);j={...j,...q.length>0?{readWhole:q}:{},...L.length>0?{filesForgotten:L.length}:{}}}catch(S){O.push(`The configuration could not be told what this removal took (${S instanceof Error?S.message:String(S)}): run it full next time.`)}}let je;if(e.links&&H.size>0)try{je=await e.links.forget(t.configId,{sourceOrgId:t.sourceOrgId,targetOrgId:$e(t)},[...H])}catch(b){O.push(`Which records of the target this removal took could not be forgotten (${b instanceof Error?b.message:String(b)}): a later run of the configuration may point a lookup at one of them.`)}return{result:j,planned:p,plannedBack:f,plannedUndelete:E,notes:O,...je?{linksForgotten:je}:{},...ke.length>0?{earlierStamped:ke}:{},...h.duplicateSets?{duplicateSets:h.duplicateSets}:{}}}async function Us(e){let{run:t}=e,n=ge(t);return{outcome:await Ue(e.org,n,{...vo(t),...t.removal?.removalStamps?{removalStamps:t.removal.removalStamps}:{},...t.removal?.removalSpans?{removalSpans:t.removal.removalSpans}:{},includeChanged:e.includeChanged,...e.runUserId?{runUserId:e.runUserId}:{},previewOnly:!0,...e.signal?{signal:e.signal}:{}}),planned:n.reduce((d,p)=>d+p.ids.length,0)}}async function Kn(e,t,n){let s=new Map,d=Object.entries(t.heldBefore??{});if(d.length===0||n.length===0)return s;let p=await ie(e)(),u=await se(e);for(let f of n){let k=Date.parse(xe(f)??""),E=Number.isFinite(k)?k+u+re:Number.NEGATIVE_INFINITY,O=new Set;for(let[A,{at:I,by:z}]of d)Date.parse(I)>E&&(p!==void 0&&z!==void 0&&z.slice(0,15)===p||O.add(A));O.size>0&&s.set(f.runId,O)}return s}function xe(e){return e.lastWriteAt??e.lastWrittenAt??e.end?.at}function Hn(e){return e.keptChanged+e.refused+e.notKept+(e.notReached??0)+(e.restoredWithout??0)}function Zn(e,t,n,s){if(!s||e==="cancelled")return e;if(s.cancelled)return"cancelled";let d=s.objects.some(u=>wo(u)>0);if(e==="success"&&!d)return"success";let p=t.some(u=>u.deleted>0)||(n?.objects??[]).some(u=>u.restored>0)||s.objects.some(u=>u.undeleted>0);return e==="partial"||p?"partial":"failure"}function Xn(e,t,n){if(!n||e==="cancelled")return e;if(n.cancelled)return"cancelled";let s=n.objects.some(p=>Hn(p)>0);return e==="success"&&!s?"success":t.some(p=>p.deleted>0)||n.objects.some(p=>p.restored+(p.restoredWithout??0)>0)?"partial":"failure"}function Bs(e){let t=e?.getSandforgeSetting?.("backup.maxAgeDays",30);return typeof t=="number"&&Number.isFinite(t)&&t>0?t:0}function $s(e,t,n){let s=[],d=0,p=Number.POSITIVE_INFINITY;for(let u of e){let f=t(u.backup);if(!f){d+=u.ids.length;continue}s.push(u);let k=Date.parse(f.timestamp??"");n>0&&Number.isFinite(k)&&(p=Math.min(p,k+n*864e5))}return{kept:s,notKept:d,...Number.isFinite(p)?{keptUntil:new Date(p).toISOString()}:{}}}var Ye="backupSet:",Yn="backups",Ve=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Q=a().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/),$=g().int().nonnegative(),Vn=o({index:g().int().positive(),afterId:a().regex(Ve).optional(),lastId:a().regex(Ve).optional(),rows:$,snapshotId:a().min(1).max(240),takenAt:Q.optional(),readSince:Q.optional(),state:w(["pending","snapshotted","masking","masked","restored"]),masked:$,refused:$,deletedSince:$,nothingToMask:$,unanswered:$.optional(),late:v(!0).optional(),sizeUsed:g().int().positive(),lateLeft:$.optional(),lateOf:g().int().positive().optional(),lateAfterId:a().regex(Ve).optional(),restoredAt:Q.optional()}),Jn=o({objectApiName:a().min(1).max(255),where:a().max(2e3).optional(),select:a().max(1e5).optional(),done:r(),tailLeft:$.optional(),slices:c(Vn)}),Ao=o({setId:a().min(1).max(200),kind:w(["masking","backup"]),orgId:a().min(1).max(200),organizationId:a().max(18).optional(),templateId:a().min(1).max(200).optional(),fingerprint:a().regex(/^[0-9a-f]{64}$/).optional(),size:g().int().positive(),state:w(["open","done","abandoned"]),startedAt:Q,serverStartedAt:Q.optional(),lastActivityAt:Q,requestsSpent:$,keyCheck:a().regex(/^[0-9a-f]{16}$/).optional(),objects:c(Jn)});function Gs(e,t){return`${e}-s${String(t).padStart(4,"0")}`}function Ie(e){return e.objects.flatMap(t=>t.slices).sort((t,n)=>t.index-n.index)}function Ws(e){return Ie(e).reduce((t,n)=>Math.max(t,n.index),0)+1}function Co(e){return e.state==="masked"||e.state==="snapshotted"||e.state==="restored"}function Qn(e){return Ie(e).reduce((t,n)=>t+n.rows,0)}function To(e,t,n){return{index:t.index,objectApiName:e,snapshotId:t.snapshotId,rows:t.rows,masked:t.masked,refused:t.refused,deletedSince:t.deletedSince,nothingToMask:t.nothingToMask,state:t.state,...t.late?{late:!0}:{},...t.sizeUsed<n?{sizeUsed:t.sizeUsed}:{},...t.restoredAt?{restoredAt:t.restoredAt}:{}}}function ea(e){return e.objects.reduce((t,n)=>t+(n.tailLeft??0)+n.slices.reduce((s,d)=>s+(d.lateLeft??0),0),0)}function Ks(e,t){return{setId:e.setId,size:e.size,state:e.state,objects:e.objects.map(n=>({objectApiName:n.objectApiName,slices:n.slices.map(s=>To(n.objectApiName,s,e.size))})),lateRecords:ea(e),requestsSpent:t.requestsSpent,...t.stoppedOnBudget?{stoppedOnBudget:!0}:{},slicesLeft:e.objects.some(n=>!n.done||n.slices.some(s=>!Co(s)))}}function ta(e){return e.kind==="backup"&&e.state==="open"?"partial":e.state}function Hs(e){let t=Object.fromEntries(e.objects.flatMap(n=>n.where?[[n.objectApiName,n.where]]:[]));return{setId:e.setId,orgId:e.orgId,kind:e.kind,state:ta(e),startedAt:e.startedAt,lastActivityAt:e.lastActivityAt,size:e.size,totalRecords:Qn(e),...e.templateId?{templateId:e.templateId}:{},slices:e.objects.flatMap(n=>n.slices.map(s=>To(n.objectApiName,s,e.size))),...Object.keys(t).length>0?{wheres:t}:{}}}function Zs(e){let t=Ie(e);return{setId:e.setId,savedAt:e.lastActivityAt,done:t.filter(Co).length,total:t.length,state:e.state,size:e.size}}var Eo=class{constructor(t){this.configStore=t}configStore;get(t){let n=Ao.safeParse(this.configStore.get(this.key(t)));return n.success&&n.data.setId===t?n.data:void 0}save(t){this.configStore.set(this.key(t.setId),Ao.parse(t),Yn)}delete(t){this.configStore.delete(this.key(t))}list(t){return this.configStore.getKeysByPrefix(Ye).map(n=>this.get(n.slice(Ye.length))).filter(n=>n!==void 0).filter(n=>t===void 0||n.orgId===t)}openFor(t,n){return this.list(t).find(s=>s.kind==="masking"&&s.state==="open"&&s.templateId===n)}ofSnapshot(t){return this.list().find(n=>Ie(n).some(s=>s.snapshotId===t))}key(t){return`${Ye}${t}`}};async function Ys(e,t){let n=e.check(t);if(!n.allowed)return{check:n,decision:"refused"};if(!await e.confirmIfNeeded(n,t.orgTier))return{check:n,decision:"declined"};let d=n.requiresConfirmation&&e.canAskForConfirmation===!0;return{check:n,decision:d?"confirmed":"allowed"}}var _o={allowed:0,confirmed:1,declined:2,refused:3};function Vs(e,t){return e===void 0||_o[t]>_o[e]?t:e}export{sa as a,Qt as b,ca as c,qe as d,la as e,da as f,Bo as g,pa as h,ma as i,ua as j,ga as k,ba as l,fa as m,ya as n,eo as o,ha as p,za as q,Sa as r,xa as s,i as t,l as u,so as v,B as w,nn as x,an as y,Ke as z,Ea as A,Ca as B,Ta as C,_a as D,Na as E,Da as F,Fa as G,Ma as H,Ua as I,La as J,Ba as K,$a as L,qa as M,Ga as N,Wa as O,Ka as P,Ha as Q,Za as R,Xa as S,Ya as T,Va as U,Ja as V,Qa as W,er as X,tr as Y,or as Z,mn as _,nr as $,ar as aa,rr as ba,ir as ca,sr as da,cr as ea,lr as fa,dr as ga,pr as ha,mr as ia,ur as ja,gr as ka,br as la,fr as ma,yr as na,hr as oa,zr as pa,Sr as qa,xr as ra,Ir as sa,kr as ta,jr as ua,Pr as va,Or as wa,Rr as xa,wr as ya,vr as za,Ar as Aa,Er as Ba,Cr as Ca,Tr as Da,_r as Ea,fn as Fa,Nr as Ga,Dr as Ha,Fr as Ia,Mr as Ja,Ur as Ka,Lr as La,Br as Ma,$r as Na,qr as Oa,Gr as Pa,Wr as Qa,Kr as Ra,go as Sa,Hr as Ta,Zr as Ua,Xr as Va,bo as Wa,Yr as Xa,Vr as Ya,Jr as Za,Qr as _a,ti as $a,oi as ab,ni as bb,ai as cb,ri as db,ii as eb,si as fb,ci as gb,li as hb,di as ib,pi as jb,mi as kb,ui as lb,gi as mb,bi as nb,fi as ob,yi as pb,hi as qb,zi as rb,Si as sb,xi as tb,Ii as ub,ki as vb,ji as wb,Pi as xb,Oi as yb,Ri as zb,wi as Ab,vi as Bb,Ai as Cb,Ei as Db,Ci as Eb,Ti as Fb,_i as Gb,Ni as Hb,Di as Ib,Fi as Jb,Mi as Kb,Ui as Lb,Li as Mb,Bi as Nb,$i as Ob,qi as Pb,Gi as Qb,Wi as Rb,Ki as Sb,Hi as Tb,Zi as Ub,Xi as Vb,Yi as Wb,Vi as Xb,Ji as Yb,Qi as Zb,es as _b,ts as $b,os as ac,ns as bc,as as cc,rs as dc,is as ec,ss as fc,cs as gc,ls as hc,ds as ic,Fn as jc,Mn as kc,us as lc,gs as mc,bs as nc,fs as oc,ys as pc,hs as qc,zs as rc,Ss as sc,xs as tc,Is as uc,Ln as vc,ks as wc,Ro as xc,Ms as yc,Us as zc,xe as Ac,Zn as Bc,Xn as Cc,Ys as Dc,Vs as Ec,Bs as Fc,$s as Gc,Gs as Hc,Ie as Ic,Ws as Jc,Co as Kc,ea as Lc,Ks as Mc,ta as Nc,Hs as Oc,Zs as Pc,Eo as Qc};
@@ -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{j as Z,l as T}from"./chunk-GWRKS3AL.mjs";import{B as Q,s as Y,t as M,v as K,z as J}from"./chunk-T26C576X.mjs";import{d as G}from"./chunk-BNO5GIJ6.mjs";import{b as V,c as X,g as z}from"./chunk-6IGEASOF.mjs";import{$b as te,Ec as re,Pb as ee,tc as se,uc as N}from"./chunk-KOQV4WXC.mjs";import{b as U,c as B}from"./chunk-SU65Z2BA.mjs";import{B as H}from"./chunk-XEB6HZ34.mjs";import{b as $}from"./chunk-CA5NAXSU.mjs";import{Ad as q,nd as I,rd as C,wd as S,zd as F}from"./chunk-DPYTG6DM.mjs";var _e=5e3,x=2e3,le=1e3,me={masking:{during:"during the masking",records:"records it masked"},restore:{during:"during the restore",records:"records it put back"},erasure:{during:"during the erasure",records:"records it overwrote"}};function ne(e,t){let r=new Set(t.map(s=>s.toLowerCase()));return(e?.objects??[]).filter(s=>r.has(s.objectApiName.toLowerCase())).filter(s=>(s.duplicateRules??[]).length>0).map(s=>({objectApiName:s.objectApiName,rules:(s.duplicateRules??[]).map(n=>n.name)}))}function ae(e){return typeof e=="string"?e.slice(0,15):""}async function pe(e,t){let{rules:r}=t,s=0,n=a=>(s++,e.query(a));try{let a=H(new Date(Date.parse(t.since)-le).toISOString()),i=new Set([...t.masked].map(ae)),c=await n(`SELECT Id, DuplicateRecordSetId, RecordId FROM DuplicateRecordItem WHERE CreatedDate >= ${a} LIMIT ${x+1}`),u=c.done===!1||c.records.length>x,d=c.records.slice(0,x),p=new Set(d.filter(o=>i.has(ae(o.RecordId))).map(o=>String(o.DuplicateRecordSetId??"")).filter(o=>o!=="")),l=d.filter(o=>p.has(String(o.DuplicateRecordSetId??""))).length,m=0;for(let o of G([...p])){let f=await n(`SELECT Id FROM DuplicateRecordSet WHERE CreatedDate >= ${a} AND Id IN (${o})`);m+=f.records.length}return{rules:r,sets:m,items:l,...u?{atLeast:!0}:{},requests:s}}catch(a){return{rules:r,sets:0,items:0,unread:$(a),requests:s}}}function Ie(e,t,r){let s=r.now??Date.now,n=r.sleep??(l=>new Promise(m=>setTimeout(m,l))),a=new Set(t.map(l=>l.objectApiName.toLowerCase())),i=l=>a.has(l.toLowerCase()),c,u=0,d=new Set,p=0;return{covers:i,beforeWrite:l=>{i(l)&&c===void 0&&(u=s())},wrote:(l,m)=>{if(!i(l))return;let o=!1;for(let h of m)typeof h!="string"||h===""||(d.add(h),o=!0);if(!o)return;p=s();let f=u;c??=e.serverTime().then(h=>{let b=Date.parse(h);return Number.isNaN(b)?{unread:`it answered "${h}"`}:{at:new Date(b-Math.max(0,s()-f)).toISOString()}},h=>({unread:$(h)}))},held:()=>d.size,read:async()=>{if(d.size===0)return;let l=c?await c:void 0;if(!l||"unread"in l)return{rules:t,sets:0,items:0,unread:l?`the org's clock: ${l.unread}`:"the org's clock was not read",requests:l?1:0};let m=Math.max(0,p+r.settleMs-s());m>0&&await n(m);let o=await pe(e,{rules:t,since:l.at,masked:d});return{...o,requests:(o.requests??0)+1,waitedMs:m}}}}function Ce(e,t){if(!e)return t;if(!t)return e;let r=[e.unread,t.unread].filter(s=>s!==void 0);return{rules:t.rules.length>=e.rules.length?t.rules:e.rules,sets:e.sets+t.sets,items:e.items+t.items,...e.atLeast||t.atLeast?{atLeast:!0}:{},...r.length>0?{unread:r.join("; ")}:{},requests:(e.requests??0)+(t.requests??0),waitedMs:(e.waitedMs??0)+(t.waitedMs??0)}}function Fe(e){return e!==void 0&&(e.sets>0||e.items>0||e.unread!==void 0)}function ge(e){return e.map(t=>`"${t}"`).join(", ")}function fe(e){return e<=0?"without waiting":e<1e3?"after waiting less than 1 s":`after waiting ${Math.round(e/1e3)} s`}function qe(e,t,r="masking"){if(!e||e.rules.length===0)return"";let s=me[r],n=e.rules.map(c=>`${c.objectApiName} (${ge(c.rules)})`).join(", ");if(e.unread!==void 0)return`What the duplicate rules of ${t} on ${n} wrote ${s.during} could not be read (${e.unread}): a duplicate record set they wrote stays.`;let a=e.requests!==void 0?` Read in ${e.requests} request(s), ${fe(e.waitedMs??0)}.`:"";if(e.sets===0&&e.items===0)return`The duplicate rules of ${t} on ${n} wrote nothing for the ${s.records}.`+a;let i=e.atLeast===!0?"at least ":"";return`The duplicate rules of ${t} on ${n} wrote ${i}${e.sets} duplicate record set(s) and ${i}${e.items} item(s) ${s.during}, for ${s.records}: kept, as they name records that stay.${a}`}var he="AUTOMATION_NOT_ACCEPTED",we="EMAILS_EXCEEDED",Oe="ORG_TEMPORARILY_UNREACHABLE";function Ae(e,t){return e==="cleanup"||e==="empty"?{delete:[...t]}:e==="restore"?{bringBack:[...t],giveBack:[...t]}:e==="emptyUndo"?{bringBack:[...t]}:{giveBack:[...t]}}function be(e,t){let r=e==="cleanup"||e==="empty"?"delete":"update";return t.filter(s=>s.records>0).map(s=>({objectApiName:s.objectApiName,write:r,records:s.records}))}var E={masking:{heading:"masking automation: what {org} runs as the masking writes over the records",the:"the masking",this:"this masking",writes:"writes over",verb:"mask",nothing:"Nothing was written.",flag:"to mask all the same"},restore:{heading:"restore automation: what {org} runs as the restore puts the backup's values back",the:"the restore",this:"this restore",writes:"puts back",verb:"restore",nothing:"Nothing was written.",flag:"to restore all the same"},cleanup:{heading:"cleanup automation: what {org} runs as the cleanup deletes the records",the:"the cleanup",this:"this cleanup",writes:"deletes",verb:"delete",nothing:"Nothing was deleted.",flag:"to delete all the same"},empty:{heading:"emptying automation: what {org} runs as the emptying deletes the records",the:"the emptying",this:"this emptying",writes:"deletes",verb:"empty",nothing:"Nothing was deleted.",flag:"to empty all the same"},emptyUndo:{heading:"undo automation: what {org} runs as the undo brings the records back",the:"the undo",this:"this undo",writes:"brings back",verb:"undo",nothing:"Nothing was written.",flag:"to undo all the same"}},$e={masking:"masking",restore:"restore",cleanup:"cleanup",empty:"empty",emptyUndo:"undo"};function Je(e){return e.erasure===!0?"erasure":e.fromPage===!0?"page":void 0}var ye={"accept-automation":"acceptAutomation","accept-emails":"acceptEmails","mute-automation":"muteAutomation"},De={"accept-emails":"the confirmation's box that lets the org send these emails","mute-automation":"the confirmation's box that mutes the target's automation"},Re={mask:"masking",restore:"restore",delete:"cleanup",erase:"erasure",empty:"emptying",undo:"undo"};function oe(e){let t=r=>De[r]??`--${r}`;return e.replace(/\bAdd --accept-automation to (mask|restore|delete|erase|empty|undo) all the same\b/g,(r,s)=>`Confirm the ${Re[s]??s} from its confirmation, which lists what fires, to ${s} all the same`).replace(/\bWith --mute-automation,/g,`With ${t("mute-automation")} ticked,`).replace(/\bAdd --(accept-emails|mute-automation)\b/g,(r,s)=>`Tick ${t(s)}`).replace(/(^|[.:;] )--(accept-emails|mute-automation)\b/g,(r,s,n)=>`${s}${W(t(n))}`).replace(/--(accept-emails|mute-automation)\b/g,(r,s)=>t(s))}function L(e,t="flags"){return t==="step"?e.replace(/--(accept-automation|accept-emails|mute-automation)\b/g,(r,s)=>`${ye[s]??s} in the step`).replace(/\bAdd (acceptAutomation|acceptEmails|muteAutomation) in the step\b/g,"Turn on $1 in the step"):t==="erasure"?oe(e.replace(/\b(this|the|This|The) (masking|cleanup)\b/g,"$1 erasure").replace(/\bto (mask|delete) all the same\b/g,"to erase all the same").replace(/\b(mask|delete) fewer records\b/g,"erase fewer records")):t==="page"?oe(e):e}var ke={before:"before save",after:"after save",beforeAndAfter:"before and after save"},Ee={before:"before delete",after:"after delete",beforeAndAfter:"before and after delete"},ue={flows:"the flows",triggers:"the Apex triggers",processes:"the Process Builder processes",workflowRules:"the workflow rules",automation:"the automation"};function de({kind:e,name:t}){return e==="flow"?`flow "${t}"`:e==="process"?`process "${t}"`:e==="workflowRule"?`workflow rule "${t}"`:`Apex trigger ${t}`}function ce(e,t){return t.step==="delete"?Ee[t.when]:t.step==="bringBack"?"as it comes back from the recycle bin":`${e==="restore"?"as its values are put back":"as it is masked"}, ${ke[t.when]}`}function W(e){return`${e[0]?.toUpperCase()??""}${e.slice(1)}`}function ve(e,t,r,s){let n=E[r],a=[n.heading.replace("{org}",t)];if(typeof e.unread=="string")return a.push(` what ${t} runs could not be read: ${e.unread}`),a;let i=e;for(let d of S(i,s))a.push(` ${d.objectApiName}: ${ce(r,d)}: ${de(d)}`);let c=N(i);if(a.length===1&&c.length===0){let d=new Set(Object.values(s).flat()).size;a.push(` nothing fires on the ${d} object(s) it ${n.writes} records of`)}for(let d of ne(i,s.giveBack??[]))a.push(` ${d.objectApiName}: duplicate rules ${d.rules.map(p=>`"${p}"`).join(", ")}: ${n.the} saves a record a rule only alerts on, a rule that blocks still refuses it, and what a rule that reports writes (a duplicate record set and its items) stays`);let u=I(i);u.length>0&&a.push(` bypass held: the user ${n.the} writes as holds ${u.join(", ")}, and what names it stays quiet`);for(let{part:d,reason:p}of c)a.push(` ${ue[d]??d} could not be read: ${p}`);return a}function Se(e,t,r){let s=E[r.act],n=`${s.nothing} Add --accept-automation ${s.flag}, or turn that automation off in ${t} first.`;if(typeof e.unread=="string")return`What ${t} runs as ${s.this} ${s.writes} its records could not be read (${e.unread}), so what fires is not known. ${n}`;let a=e,i=S(a,r.steps),c=N(a);if(i.length===0&&c.length===0)return;let u=[];if(i.length>0){let l=i.map(m=>`${m.objectApiName}: ${de(m)} (${ce(r.act,m)})`);u.push(`${t} runs automation as ${s.this} ${s.writes} its records: ${l.join("; ")}.`)}for(let{part:l,reason:m}of c)u.push(`${W(ue[l]??l)} of ${t} could not be read (${m}), so what fires as ${s.the} ${s.writes} its records is not known.`);let d=r.assign??[];u.push(...re(d,t,s.the));let p=[...new Set(d.flatMap(l=>l.permissionSet??[]))];return r.mayMute===!0&&p.length>0&&u.push(`With --mute-automation, ${s.the} assigns ${p.join(", ")} to the user it writes as for ${s.the} alone, under a lease, and what ${p.length===1?"it keeps":"they keep"} quiet does not fire.`),u.push(n),u.join(" ")}function k(e){let t=e.objects.map(r=>`${r.perRecord} per ${r.objectApiName}`).join(", ");return`about ${te(e.emails,e.limit)} (${t}`+(e.alertsCounted?"; its email alerts among them, as a Developer Edition counts them":"")+")"}function Me(e,t,r){let s=e.map(n=>{if(n.verdict==="unread")return` emails: ${k(n)}; what ${t} has left today could not be read (${n.unread??"not said"})`;let a=`${n.remaining??0} of ${n.max??0} left today`;return n.verdict==="exceeds"?` emails: ${k(n)}, past the ${a}`:` emails: ${k(n)}, ${a}`});return r!==void 0&&s.push(` emails not counted: what sends them was not read (${r})`),s}function Te(e,t,r,s){let n=t.filter(u=>u.verdict==="exceeds");if(n.length===0)return;let a=E[e],i=n.map(u=>`${k(u)}, ${u.remaining??0} of ${u.max??0} left today`).join("; "),c=s?.kind==="enough"?`Turn off what sends them, give the user it writes as the bypass that keeps them quiet (--mute-automation assigns ${s.sets.join(", ")} for ${a.the} alone, and what still sends then fits what is left today), or ${a.verb} fewer records.`:`Turn off what sends them, or ${a.verb} fewer records.`+(s?.kind==="muting"?" What sends them still runs under the mute.":s?.kind==="notEnough"?" --mute-automation would not keep enough of them quiet.":"");return`${W(a.this)} would make ${r} send ${i}: past them, each record whose flow fails in the save is refused (CANNOT_EXECUTE_FLOW_TRIGGER), and the org's own emails stop for the rest of the day. ${c} ${a.nothing}`}function Qe(e,t,r){return{readAutomation:t,readLimits:()=>ee(e),readDeliverability:()=>r?Promise.resolve(V):X(e),muteOrg:async()=>Y(e),...r?{production:r}:{}}}async function Ze(e,t,r,s){let n=e?.mute?.prepared;if(!e||!n)return{};let a;try{a=await n.acquire(t)}catch(c){if(!M(c))throw c;return{refused:{code:c.code,message:L(c.message,s)}}}let i=e.emails.afterLease(a.outcome,r);return i?(await a.release(),{refused:{code:i.code,message:L(i.message,s)}}):{held:a}}var Ne={objectsRead:[],objects:[],unread:[],conditionsNotRead:0,conditionsBound:0,requests:0};async function et(e){let{act:t,target:r,accord:s}=e,n=e.objects.filter(g=>g.records>0),a=n.map(g=>g.objectApiName),i=e.writes?.steps??Ae(t,a),c=F(i),u=a.length===0?Ne:await e.org.readAutomation(a).catch(g=>{let A=U(g);return{unread:A===void 0?$(g):`the org could not be reached (${A})`}}),d=typeof u.unread=="string"?void 0:u,p=B(u),l=E[t],m=[],o;if(s.muteAutomation===!0&&p===void 0)try{o=await J(e.org.muteOrg,u,{...e.muteLeases,writes:c})}catch(g){if(!M(g))throw g;m.push({code:g.code,message:g.message})}let f=o?.automation??d,h=e.mayMute&&s.muteAutomation!==!0&&e.org.production!==!0,b=[...ve(d??u,r,t,i),...o?Q(o.muted,r).map(g=>` ${g}`):[]],j=Se(f??u,r,{act:t,steps:i,...f?{assign:se(f,q(f,i),e.assignTo)}:{},mayMute:h});j!==void 0&&s.acceptAutomation!==!0&&m.push({code:he,message:j});let D=e.writes?e.writes.written.filter(g=>g.records>0):be(t,n),y=[],R,P;if(f&&p===void 0){if(D.some(A=>C(f,A.write).some(w=>w.objectApiName===A.objectApiName))){let A=await e.org.readLimits().catch(w=>({unread:$(w)}));if(y=T(D,f,A),y.some(w=>w.verdict==="exceeds")){let w=!o&&h&&d?K(d,c):void 0;P=o?{kind:"muting"}:w&&w.plan.assign.length>0?T(D,w.automation,A).some(v=>v.verdict==="exceeds")?{kind:"notEnough"}:{kind:"enough",sets:w.plan.assign.map(v=>v.permissionSet)}:void 0}}R=Z(D,f)}b.push(...Me(y,r,R));let _=Te(t,y,r,P);_!==void 0&&m.push({code:we,message:_});let O=await z({read:u,...o?.plan?{plan:o.plan}:{},writes:c,readDeliverability:p===void 0?e.org.readDeliverability:async()=>({reading:{unread:`${r} could not be reached`},requests:0}),accepted:s.acceptEmails===!0,target:r,run:$e[t],keepsAddresses:!0,mayMute:h});return O.gate.line!==void 0&&b.push(` ${O.gate.line}`),O.gate.stop&&m.push({...O.gate.stop}),p!==void 0&&m.splice(0,m.length,{code:Oe,message:`${r} could not be reached as what it runs was read (${p}), so ${l.the} was not started. ${l.nothing} Check the network, then try again.`}),{answer:{act:t,objects:n,steps:i,...d?{automation:d}:{automationUnread:String(u.unread)},lines:b,emails:y,...R!==void 0?{emailsUncounted:R}:{},...O.gate.deliverability?{deliverability:O.gate.deliverability}:{},emailsAsk:O.gate.verdict==="asks",refusals:m.map(g=>({...g,message:L(g.message,e.voice)})),...o?{mutedAutomation:o.muted}:{},...o?.plan?{mutePlan:o.plan}:{}},...o?{mute:o}:{},emails:O}}var xe=/\bnothing (?:was )?(?:written|deleted)\b/i,ie=/\s*\bNothing was (?:written|deleted)\./g;function tt(e){let[t,...r]=e.refusals;if(!t)return;let s=!1,n=e.refusals.map(a=>s?a.message.replace(ie,"").trim():(s=xe.test(a.message),a.message)).join(" ");return{code:t.code,message:n,alsoRefused:r.map(a=>({code:a.code,message:a.message.replace(ie,"").trim()}))}}function st(e){return e.alsoRefused.length>0?{extraPayload:{alsoRefused:[...e.alsoRefused]}}:{}}export{_e as a,ne as b,Ie as c,Ce as d,Fe as e,qe as f,Je as g,Qe as h,Ze as i,et as j,tt as k,st as l};
7
+ import{j as Z,l as T}from"./chunk-VZT4E2OJ.mjs";import{a as Y,b as M,d as K,h as J,j as Q}from"./chunk-HKUWHVI7.mjs";import{d as G}from"./chunk-VPDEJGPS.mjs";import{b as V,c as X,g as z}from"./chunk-JQZTMFO7.mjs";import{$b as te,Ec as re,Pb as ee,tc as se,uc as N}from"./chunk-JFNLKHY6.mjs";import{b as U,c as B}from"./chunk-SU65Z2BA.mjs";import{B as H}from"./chunk-XZISAZA6.mjs";import{b as $}from"./chunk-CA5NAXSU.mjs";import{Dd as C,Id as S,Ld as F,Md as q,zd as I}from"./chunk-ZQO5PDX5.mjs";var _e=5e3,x=2e3,le=1e3,me={masking:{during:"during the masking",records:"records it masked"},restore:{during:"during the restore",records:"records it put back"},erasure:{during:"during the erasure",records:"records it overwrote"}};function ne(e,t){let r=new Set(t.map(s=>s.toLowerCase()));return(e?.objects??[]).filter(s=>r.has(s.objectApiName.toLowerCase())).filter(s=>(s.duplicateRules??[]).length>0).map(s=>({objectApiName:s.objectApiName,rules:(s.duplicateRules??[]).map(n=>n.name)}))}function ae(e){return typeof e=="string"?e.slice(0,15):""}async function pe(e,t){let{rules:r}=t,s=0,n=a=>(s++,e.query(a));try{let a=H(new Date(Date.parse(t.since)-le).toISOString()),i=new Set([...t.masked].map(ae)),c=await n(`SELECT Id, DuplicateRecordSetId, RecordId FROM DuplicateRecordItem WHERE CreatedDate >= ${a} LIMIT ${x+1}`),u=c.done===!1||c.records.length>x,d=c.records.slice(0,x),p=new Set(d.filter(o=>i.has(ae(o.RecordId))).map(o=>String(o.DuplicateRecordSetId??"")).filter(o=>o!=="")),l=d.filter(o=>p.has(String(o.DuplicateRecordSetId??""))).length,m=0;for(let o of G([...p])){let f=await n(`SELECT Id FROM DuplicateRecordSet WHERE CreatedDate >= ${a} AND Id IN (${o})`);m+=f.records.length}return{rules:r,sets:m,items:l,...u?{atLeast:!0}:{},requests:s}}catch(a){return{rules:r,sets:0,items:0,unread:$(a),requests:s}}}function Ie(e,t,r){let s=r.now??Date.now,n=r.sleep??(l=>new Promise(m=>setTimeout(m,l))),a=new Set(t.map(l=>l.objectApiName.toLowerCase())),i=l=>a.has(l.toLowerCase()),c,u=0,d=new Set,p=0;return{covers:i,beforeWrite:l=>{i(l)&&c===void 0&&(u=s())},wrote:(l,m)=>{if(!i(l))return;let o=!1;for(let h of m)typeof h!="string"||h===""||(d.add(h),o=!0);if(!o)return;p=s();let f=u;c??=e.serverTime().then(h=>{let b=Date.parse(h);return Number.isNaN(b)?{unread:`it answered "${h}"`}:{at:new Date(b-Math.max(0,s()-f)).toISOString()}},h=>({unread:$(h)}))},held:()=>d.size,read:async()=>{if(d.size===0)return;let l=c?await c:void 0;if(!l||"unread"in l)return{rules:t,sets:0,items:0,unread:l?`the org's clock: ${l.unread}`:"the org's clock was not read",requests:l?1:0};let m=Math.max(0,p+r.settleMs-s());m>0&&await n(m);let o=await pe(e,{rules:t,since:l.at,masked:d});return{...o,requests:(o.requests??0)+1,waitedMs:m}}}}function Ce(e,t){if(!e)return t;if(!t)return e;let r=[e.unread,t.unread].filter(s=>s!==void 0);return{rules:t.rules.length>=e.rules.length?t.rules:e.rules,sets:e.sets+t.sets,items:e.items+t.items,...e.atLeast||t.atLeast?{atLeast:!0}:{},...r.length>0?{unread:r.join("; ")}:{},requests:(e.requests??0)+(t.requests??0),waitedMs:(e.waitedMs??0)+(t.waitedMs??0)}}function Fe(e){return e!==void 0&&(e.sets>0||e.items>0||e.unread!==void 0)}function ge(e){return e.map(t=>`"${t}"`).join(", ")}function fe(e){return e<=0?"without waiting":e<1e3?"after waiting less than 1 s":`after waiting ${Math.round(e/1e3)} s`}function qe(e,t,r="masking"){if(!e||e.rules.length===0)return"";let s=me[r],n=e.rules.map(c=>`${c.objectApiName} (${ge(c.rules)})`).join(", ");if(e.unread!==void 0)return`What the duplicate rules of ${t} on ${n} wrote ${s.during} could not be read (${e.unread}): a duplicate record set they wrote stays.`;let a=e.requests!==void 0?` Read in ${e.requests} request(s), ${fe(e.waitedMs??0)}.`:"";if(e.sets===0&&e.items===0)return`The duplicate rules of ${t} on ${n} wrote nothing for the ${s.records}.`+a;let i=e.atLeast===!0?"at least ":"";return`The duplicate rules of ${t} on ${n} wrote ${i}${e.sets} duplicate record set(s) and ${i}${e.items} item(s) ${s.during}, for ${s.records}: kept, as they name records that stay.${a}`}var he="AUTOMATION_NOT_ACCEPTED",we="EMAILS_EXCEEDED",Oe="ORG_TEMPORARILY_UNREACHABLE";function Ae(e,t){return e==="cleanup"||e==="empty"?{delete:[...t]}:e==="restore"?{bringBack:[...t],giveBack:[...t]}:e==="emptyUndo"?{bringBack:[...t]}:{giveBack:[...t]}}function be(e,t){let r=e==="cleanup"||e==="empty"?"delete":"update";return t.filter(s=>s.records>0).map(s=>({objectApiName:s.objectApiName,write:r,records:s.records}))}var E={masking:{heading:"masking automation: what {org} runs as the masking writes over the records",the:"the masking",this:"this masking",writes:"writes over",verb:"mask",nothing:"Nothing was written.",flag:"to mask all the same"},restore:{heading:"restore automation: what {org} runs as the restore puts the backup's values back",the:"the restore",this:"this restore",writes:"puts back",verb:"restore",nothing:"Nothing was written.",flag:"to restore all the same"},cleanup:{heading:"cleanup automation: what {org} runs as the cleanup deletes the records",the:"the cleanup",this:"this cleanup",writes:"deletes",verb:"delete",nothing:"Nothing was deleted.",flag:"to delete all the same"},empty:{heading:"emptying automation: what {org} runs as the emptying deletes the records",the:"the emptying",this:"this emptying",writes:"deletes",verb:"empty",nothing:"Nothing was deleted.",flag:"to empty all the same"},emptyUndo:{heading:"undo automation: what {org} runs as the undo brings the records back",the:"the undo",this:"this undo",writes:"brings back",verb:"undo",nothing:"Nothing was written.",flag:"to undo all the same"}},$e={masking:"masking",restore:"restore",cleanup:"cleanup",empty:"empty",emptyUndo:"undo"};function Je(e){return e.erasure===!0?"erasure":e.fromPage===!0?"page":void 0}var ye={"accept-automation":"acceptAutomation","accept-emails":"acceptEmails","mute-automation":"muteAutomation"},De={"accept-emails":"the confirmation's box that lets the org send these emails","mute-automation":"the confirmation's box that mutes the target's automation"},Re={mask:"masking",restore:"restore",delete:"cleanup",erase:"erasure",empty:"emptying",undo:"undo"};function oe(e){let t=r=>De[r]??`--${r}`;return e.replace(/\bAdd --accept-automation to (mask|restore|delete|erase|empty|undo) all the same\b/g,(r,s)=>`Confirm the ${Re[s]??s} from its confirmation, which lists what fires, to ${s} all the same`).replace(/\bWith --mute-automation,/g,`With ${t("mute-automation")} ticked,`).replace(/\bAdd --(accept-emails|mute-automation)\b/g,(r,s)=>`Tick ${t(s)}`).replace(/(^|[.:;] )--(accept-emails|mute-automation)\b/g,(r,s,n)=>`${s}${W(t(n))}`).replace(/--(accept-emails|mute-automation)\b/g,(r,s)=>t(s))}function L(e,t="flags"){return t==="step"?e.replace(/--(accept-automation|accept-emails|mute-automation)\b/g,(r,s)=>`${ye[s]??s} in the step`).replace(/\bAdd (acceptAutomation|acceptEmails|muteAutomation) in the step\b/g,"Turn on $1 in the step"):t==="erasure"?oe(e.replace(/\b(this|the|This|The) (masking|cleanup)\b/g,"$1 erasure").replace(/\bto (mask|delete) all the same\b/g,"to erase all the same").replace(/\b(mask|delete) fewer records\b/g,"erase fewer records")):t==="page"?oe(e):e}var ke={before:"before save",after:"after save",beforeAndAfter:"before and after save"},Ee={before:"before delete",after:"after delete",beforeAndAfter:"before and after delete"},ue={flows:"the flows",triggers:"the Apex triggers",processes:"the Process Builder processes",workflowRules:"the workflow rules",automation:"the automation"};function de({kind:e,name:t}){return e==="flow"?`flow "${t}"`:e==="process"?`process "${t}"`:e==="workflowRule"?`workflow rule "${t}"`:`Apex trigger ${t}`}function ce(e,t){return t.step==="delete"?Ee[t.when]:t.step==="bringBack"?"as it comes back from the recycle bin":`${e==="restore"?"as its values are put back":"as it is masked"}, ${ke[t.when]}`}function W(e){return`${e[0]?.toUpperCase()??""}${e.slice(1)}`}function ve(e,t,r,s){let n=E[r],a=[n.heading.replace("{org}",t)];if(typeof e.unread=="string")return a.push(` what ${t} runs could not be read: ${e.unread}`),a;let i=e;for(let d of S(i,s))a.push(` ${d.objectApiName}: ${ce(r,d)}: ${de(d)}`);let c=N(i);if(a.length===1&&c.length===0){let d=new Set(Object.values(s).flat()).size;a.push(` nothing fires on the ${d} object(s) it ${n.writes} records of`)}for(let d of ne(i,s.giveBack??[]))a.push(` ${d.objectApiName}: duplicate rules ${d.rules.map(p=>`"${p}"`).join(", ")}: ${n.the} saves a record a rule only alerts on, a rule that blocks still refuses it, and what a rule that reports writes (a duplicate record set and its items) stays`);let u=I(i);u.length>0&&a.push(` bypass held: the user ${n.the} writes as holds ${u.join(", ")}, and what names it stays quiet`);for(let{part:d,reason:p}of c)a.push(` ${ue[d]??d} could not be read: ${p}`);return a}function Se(e,t,r){let s=E[r.act],n=`${s.nothing} Add --accept-automation ${s.flag}, or turn that automation off in ${t} first.`;if(typeof e.unread=="string")return`What ${t} runs as ${s.this} ${s.writes} its records could not be read (${e.unread}), so what fires is not known. ${n}`;let a=e,i=S(a,r.steps),c=N(a);if(i.length===0&&c.length===0)return;let u=[];if(i.length>0){let l=i.map(m=>`${m.objectApiName}: ${de(m)} (${ce(r.act,m)})`);u.push(`${t} runs automation as ${s.this} ${s.writes} its records: ${l.join("; ")}.`)}for(let{part:l,reason:m}of c)u.push(`${W(ue[l]??l)} of ${t} could not be read (${m}), so what fires as ${s.the} ${s.writes} its records is not known.`);let d=r.assign??[];u.push(...re(d,t,s.the));let p=[...new Set(d.flatMap(l=>l.permissionSet??[]))];return r.mayMute===!0&&p.length>0&&u.push(`With --mute-automation, ${s.the} assigns ${p.join(", ")} to the user it writes as for ${s.the} alone, under a lease, and what ${p.length===1?"it keeps":"they keep"} quiet does not fire.`),u.push(n),u.join(" ")}function k(e){let t=e.objects.map(r=>`${r.perRecord} per ${r.objectApiName}`).join(", ");return`about ${te(e.emails,e.limit)} (${t}`+(e.alertsCounted?"; its email alerts among them, as a Developer Edition counts them":"")+")"}function Me(e,t,r){let s=e.map(n=>{if(n.verdict==="unread")return` emails: ${k(n)}; what ${t} has left today could not be read (${n.unread??"not said"})`;let a=`${n.remaining??0} of ${n.max??0} left today`;return n.verdict==="exceeds"?` emails: ${k(n)}, past the ${a}`:` emails: ${k(n)}, ${a}`});return r!==void 0&&s.push(` emails not counted: what sends them was not read (${r})`),s}function Te(e,t,r,s){let n=t.filter(u=>u.verdict==="exceeds");if(n.length===0)return;let a=E[e],i=n.map(u=>`${k(u)}, ${u.remaining??0} of ${u.max??0} left today`).join("; "),c=s?.kind==="enough"?`Turn off what sends them, give the user it writes as the bypass that keeps them quiet (--mute-automation assigns ${s.sets.join(", ")} for ${a.the} alone, and what still sends then fits what is left today), or ${a.verb} fewer records.`:`Turn off what sends them, or ${a.verb} fewer records.`+(s?.kind==="muting"?" What sends them still runs under the mute.":s?.kind==="notEnough"?" --mute-automation would not keep enough of them quiet.":"");return`${W(a.this)} would make ${r} send ${i}: past them, each record whose flow fails in the save is refused (CANNOT_EXECUTE_FLOW_TRIGGER), and the org's own emails stop for the rest of the day. ${c} ${a.nothing}`}function Qe(e,t,r){return{readAutomation:t,readLimits:()=>ee(e),readDeliverability:()=>r?Promise.resolve(V):X(e),muteOrg:async()=>Y(e),...r?{production:r}:{}}}async function Ze(e,t,r,s){let n=e?.mute?.prepared;if(!e||!n)return{};let a;try{a=await n.acquire(t)}catch(c){if(!M(c))throw c;return{refused:{code:c.code,message:L(c.message,s)}}}let i=e.emails.afterLease(a.outcome,r);return i?(await a.release(),{refused:{code:i.code,message:L(i.message,s)}}):{held:a}}var Ne={objectsRead:[],objects:[],unread:[],conditionsNotRead:0,conditionsBound:0,requests:0};async function et(e){let{act:t,target:r,accord:s}=e,n=e.objects.filter(g=>g.records>0),a=n.map(g=>g.objectApiName),i=e.writes?.steps??Ae(t,a),c=F(i),u=a.length===0?Ne:await e.org.readAutomation(a).catch(g=>{let A=U(g);return{unread:A===void 0?$(g):`the org could not be reached (${A})`}}),d=typeof u.unread=="string"?void 0:u,p=B(u),l=E[t],m=[],o;if(s.muteAutomation===!0&&p===void 0)try{o=await J(e.org.muteOrg,u,{...e.muteLeases,writes:c})}catch(g){if(!M(g))throw g;m.push({code:g.code,message:g.message})}let f=o?.automation??d,h=e.mayMute&&s.muteAutomation!==!0&&e.org.production!==!0,b=[...ve(d??u,r,t,i),...o?Q(o.muted,r).map(g=>` ${g}`):[]],j=Se(f??u,r,{act:t,steps:i,...f?{assign:se(f,q(f,i),e.assignTo)}:{},mayMute:h});j!==void 0&&s.acceptAutomation!==!0&&m.push({code:he,message:j});let D=e.writes?e.writes.written.filter(g=>g.records>0):be(t,n),y=[],R,P;if(f&&p===void 0){if(D.some(A=>C(f,A.write).some(w=>w.objectApiName===A.objectApiName))){let A=await e.org.readLimits().catch(w=>({unread:$(w)}));if(y=T(D,f,A),y.some(w=>w.verdict==="exceeds")){let w=!o&&h&&d?K(d,c):void 0;P=o?{kind:"muting"}:w&&w.plan.assign.length>0?T(D,w.automation,A).some(v=>v.verdict==="exceeds")?{kind:"notEnough"}:{kind:"enough",sets:w.plan.assign.map(v=>v.permissionSet)}:void 0}}R=Z(D,f)}b.push(...Me(y,r,R));let _=Te(t,y,r,P);_!==void 0&&m.push({code:we,message:_});let O=await z({read:u,...o?.plan?{plan:o.plan}:{},writes:c,readDeliverability:p===void 0?e.org.readDeliverability:async()=>({reading:{unread:`${r} could not be reached`},requests:0}),accepted:s.acceptEmails===!0,target:r,run:$e[t],keepsAddresses:!0,mayMute:h});return O.gate.line!==void 0&&b.push(` ${O.gate.line}`),O.gate.stop&&m.push({...O.gate.stop}),p!==void 0&&m.splice(0,m.length,{code:Oe,message:`${r} could not be reached as what it runs was read (${p}), so ${l.the} was not started. ${l.nothing} Check the network, then try again.`}),{answer:{act:t,objects:n,steps:i,...d?{automation:d}:{automationUnread:String(u.unread)},lines:b,emails:y,...R!==void 0?{emailsUncounted:R}:{},...O.gate.deliverability?{deliverability:O.gate.deliverability}:{},emailsAsk:O.gate.verdict==="asks",refusals:m.map(g=>({...g,message:L(g.message,e.voice)})),...o?{mutedAutomation:o.muted}:{},...o?.plan?{mutePlan:o.plan}:{}},...o?{mute:o}:{},emails:O}}var xe=/\bnothing (?:was )?(?:written|deleted)\b/i,ie=/\s*\bNothing was (?:written|deleted)\./g;function tt(e){let[t,...r]=e.refusals;if(!t)return;let s=!1,n=e.refusals.map(a=>s?a.message.replace(ie,"").trim():(s=xe.test(a.message),a.message)).join(" ");return{code:t.code,message:n,alsoRefused:r.map(a=>({code:a.code,message:a.message.replace(ie,"").trim()}))}}function st(e){return e.alsoRefused.length>0?{extraPayload:{alsoRefused:[...e.alsoRefused]}}:{}}export{_e as a,ne as b,Ie as c,Ce as d,Fe as e,qe as f,Je as g,Qe as h,Ze as i,et as j,tt as k,st as l};
@@ -4,7 +4,7 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a as B,b as J}from"./chunk-PC247GKX.mjs";import{a as S}from"./chunk-3B5H24ZG.mjs";import{$a as b,Ra as h,Sa as E,Ta as U,Ua as D}from"./chunk-DPYTG6DM.mjs";import{b as l,l as m,s as C,u as M,v as K}from"./chunk-WZQEK4WT.mjs";import{randomBytes as L}from"node:crypto";import{mkdirSync as ye,statSync as Z}from"node:fs";import{mkdir as w,open as Oe,readFile as R,readdir as _,rename as Fe,rm as f,rmdir as xe,stat as x}from"node:fs/promises";import{homedir as V}from"node:os";import{join as c,resolve as Ie}from"node:path";import{promisify as Q}from"node:util";import{gunzip as Ce,gzip as be}from"node:zlib";import{createHash as me}from"node:crypto";var G=16,Y=m({digest:l().regex(/^[0-9a-f]{64}$/),fields:C(l(),l().regex(new RegExp(`^[0-9a-f]{${G}}$`)))});function W(n){return me("sha256").update(n).digest("hex")}function we(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 dn(n){let e=n.map(t=>({name:t.name,key:t.name.toLowerCase(),line:we(t)})).sort((t,r)=>t.key<r.key?-1:t.key>r.key?1:0);return{digest:W(e.map(({line:t})=>t).join(`
7
+ import{a as B,b as J}from"./chunk-PC247GKX.mjs";import{a as S}from"./chunk-ZUTUYBNW.mjs";import{$a as b,Ra as h,Sa as E,Ta as U,Ua as D}from"./chunk-ZQO5PDX5.mjs";import{b as l,l as m,s as C,u as M,v as K}from"./chunk-WZQEK4WT.mjs";import{randomBytes as L}from"node:crypto";import{mkdirSync as ye,statSync as Z}from"node:fs";import{mkdir as w,open as Oe,readFile as R,readdir as _,rename as Fe,rm as f,rmdir as xe,stat as x}from"node:fs/promises";import{homedir as V}from"node:os";import{join as c,resolve as Ie}from"node:path";import{promisify as Q}from"node:util";import{gunzip as Ce,gzip as be}from"node:zlib";import{createHash as me}from"node:crypto";var G=16,Y=m({digest:l().regex(/^[0-9a-f]{64}$/),fields:C(l(),l().regex(new RegExp(`^[0-9a-f]{${G}}$`)))});function W(n){return me("sha256").update(n).digest("hex")}function we(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 dn(n){let e=n.map(t=>({name:t.name,key:t.name.toLowerCase(),line:we(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
8
  `)),fields:Object.fromEntries(e.map(({name:t,line:r})=>[t,W(r).slice(0,G)]))}}function pn(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,Pe=384,Ee=30,ee=3,De=15,ne=1440*6e4,I=1440*6e4,Se=Q(be),ve=Q(Ce),T="checkpoint.json",ze="fingerprints.json.gz",Ae="fingerprints.json",Le="snapshots.json",te="replay.json.gz",re=/^[A-Za-z][A-Za-z0-9_]*$/;function In(n=process.env){let e=n.SANDFORGE_JOURNAL_DIR,t=e!==void 0&&e.trim()!==""?Ie(e):c(V(),".sandforge");return c(t,"checkpoints")}function Re(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 Ne(n){return n.length===18&&D.safeParse(n).success&&S(n.slice(0,15))===n}function v(n,e,t){return ie(c(n,e,t),e,t)}function ie(n,e,t){return{organizationId:e,checkpointId:t,dir:n,checkpointFile:c(n,T),fingerprintsFile:c(n,ze),plainFingerprintsFile:c(n,Ae),snapshotsFile:c(n,Le),indexDir:c(n,"index"),binDir:c(n,"bin"),filesDir:c(n,"files"),previewsDir:c(n,"previews"),rewindsDir:c(n,"rewinds")}}function oe(n){if(!re.test(n)||n.length>80)throw new d("invalid","Not a Salesforce API name");return n}function Cn(n,e){return c(n.indexDir,`${oe(e)}.idx`)}function bn(n){return c(n.indexDir,"recreated.ndjson")}function Pn(n){return c(n.indexDir,"notInBin.ndjson")}function En(n,e){return c(n.binDir,`${oe(e)}.ids`)}function Dn(n){return c(n.filesDir,"documents.ndjson")}function Sn(n){return c(n.filesDir,"links.ndjson")}function vn(n){return c(n.dir,te)}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$/,/^replay\.json\.gz$/],zn=te,je=["","backups","bin","files","index"],An=T;function se(n){return $e.some(e=>e.test(n))}async function Ln(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()||!se(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)=>ge(t.path,r.path))}function Rn(n,e){if(!se(e))throw new d("invalid","Not a file a checkpoint holds");return c(n,...e.split("/"))}function Nn(n,e){return c(n.previewsDir,O(E,e))}function H(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 $n(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 _e(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 ce(n,e){return n.expiresAt!==null&&Date.parse(n.expiresAt)<=e}function Te(n,e){if(n.expiresAt===null)return!1;let t=Date.parse(n.expiresAt);return t>e&&t-e<=ee*I}function He(n,e){let t=e-De*I;return Date.parse(n.readFrom)<t?new Date(t).toISOString():void 0}function Me(n,e){let t=ae(n);return t!==void 0&&t<=e}function ae(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 Ke(n,e){let t=ae(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 jn(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 de=m({version:K(1),objects:C(l().regex(re).max(80),Y)});async function Ue(n,e){let t;try{t=JSON.parse(await Je(n))}catch{throw new d("damaged","The checkpoint\u2019s field prints cannot be read")}let r=de.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 Be(n){let e=de.safeParse({version:1,objects:n});if(!e.success)throw new d("invalid",`Not field prints: ${e.error.message}`);return Se(`${JSON.stringify(e.data)}
9
9
  `)}async function Je(n){let e;try{e=await R(n.fingerprintsFile)}catch(t){if(t.code!=="ENOENT")throw t;return R(n.plainFingerprintsFile,"utf8")}return(await ve(e)).toString("utf8")}function _n(n){let e=n.uid??(()=>process.getuid?.()),t=n.locksDir??Re();for(let r of[n.root,t]){let i=We(r,e);if(i!==void 0)return{refusal:i}}return{store:new N({...n,locksDir:t})}}function We(n,e){try{let t=Z(n,{throwIfNoEntry:!1});if(t!==void 0&&!t.isDirectory())return{reason:"notAFolder",path:n};ye(n,{recursive:!0,mode:g});let r=e();return r!==void 0&&Z(n).uid!==r?{reason:"otherOwner",path:n}:void 0}catch(t){return{reason:"cannotMake",path:n,detail:cn(t)}}}var N=class{root;locksDir;renameFile;lockOptions;changes=new Map;constructor(e){this.root=e.root,this.locksDir=e.locksDir,this.renameFile=e.rename??((t,r)=>Fe(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,$(t))}async writeFingerprints(e,t){await this.writeWhole(e.fingerprintsFile,await Be(t))}async readFingerprints(e,t){return Ue(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 A(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||j(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:_e(r,Ee)}))}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=qe(s);for(let p of s)i.push(await Qe(p,t,a,e.refreshedAt))}return i.sort((o,s)=>ge(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=ie(c(o,`${Ge}${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||j(a.org.organizationId)!==i.organizationId)throw new d("invalid","An import keeps the checkpoint it was asked to");let p=z({...a,bytes:await Xe(s.dir,a)});if(await this.writeWhole(s.checkpointFile,$(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 xe(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 en(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 nn(await A(a),t,r)}finally{s.lock.release()}}return r}lock(e,t,r){return on(this.locksDir,e,{operation:t,...r!==void 0?{checkpointId:r}:{}},this.lockOptions)}heldBy(e){return sn(this.locksDir,e,this.lockOptions)}async organizationKeys(e){return(await P(this.root)).filter(r=>Ne(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 A(v(this.root,e,i)));return r}async writeWhole(e,t){let r=`${e}.${process.pid}-${L(4).toString("hex")}.tmp`,i=await Oe(r,"wx",Pe);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}}},Ge=".importing-",Ye=/^\.importing-[0-9a-f]{12}$/;async function Ze(n,e){for(let t of await P(n)){if(!Ye.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 $(n){return`${JSON.stringify(n,null,2)}
10
10
  `}async function pe(n,e){let t=0;for(let r of await _(n,{withFileTypes:!0})){let i=c(n,r.name);r.isDirectory()?t+=await pe(i,e):r.isFile()&&i!==e&&(t+=(await x(i)).size)}return t}async function Xe(n,e){let t=await pe(n,c(n,T)),r=o=>Buffer.byteLength($({...e,bytes:o}),"utf8"),i=t+r(t);return i=t+r(i),i}async function A(n){let e;try{e=JSON.parse(await R(n.checkpointFile,"utf8"))}catch{return{folder:n}}let t=b.safeParse(e);return t.success?t.data.checkpointId!==n.checkpointId||j(t.data.org.organizationId)!==n.organizationId?{folder:n}:{folder:n,checkpoint:t.data}:{folder:n}}function qe(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 Ve(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 Qe({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=Ve(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};Te(e,t)&&(a.expiresSoon=!0),Ke(e.org,t)&&(a.scratchExpiresSoon=!0);let p=He(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(H(n,u.rewindId))&&(a.undo={rewindId:u.rewindId,until:u.undoUntil}),a}async function en(n,e){let t=[];for(let{folder:r,checkpoint:i}of n)i!==void 0&&(ce(i,e)||await ue(r,i,e)||(await fe(r,e)).length>0)&&t.push(r);return t}async function ue(n,e,t){let r=e.lastRewind?.undoUntil;return e.lastRewind!==void 0&&r!==void 0&&Date.parse(r)<=t&&await y(H(n,e.lastRewind.rewindId))}async function fe(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 nn(n,e,t){let{folder:r,checkpoint:i}=n;if(i===void 0)return;if(i.expiresAt!==null&&ce(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 ue(r,i,e)&&(await f(H(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 fe(r,e))await f(s,{recursive:!0,force:!0}),t.previews+=1}var tn=m({...B,operation:M(["take","rewind","undo","delete","sweep","empty"]),checkpointId:h.optional()}),le=J(n=>{let e=tn.safeParse(n);return e.success?e.data:void 0});function rn(n,e){return c(n,`${k(e)}.lock`)}function on(n,e,t,r={}){let i=k(e),o=t.checkpointId!==void 0?O(h,t.checkpointId):void 0,s=le.acquire(c(n,`${i}.lock`),a=>({...a,operation:t.operation,...o!==void 0?{checkpointId:o}:{}}),r);return"busy"in s?{busy:he(s.busy)}:{lock:{organizationId:i,release:s.lock.release}}}function sn(n,e,t={}){let r=le.holder(rn(n,e),t);return r!==void 0?he(r):void 0}function he({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 j(n){try{return k(n)}catch{return}}function ge(n,e){return n<e?-1:n>e?1:0}function F(n){return n?.code}function cn(n){return n instanceof Error?n.message:String(n)}export{dn as a,pn as b,g as c,Pe as d,Ee as e,ee as f,De as g,ne as h,In as i,Re as j,k,Cn as l,bn as m,Pn as n,En as o,Dn as p,Sn as q,vn as r,zn as s,An as t,se as u,Ln as v,Rn as w,Nn as x,H as y,X as z,$n as A,_e as B,ce as C,Te as D,He as E,Me as F,Ke as G,d as H,jn as I,Ue as J,Be as K,_n as L,N as M,qe as N,rn as O,on as P,sn as Q};
@@ -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{e as ds,f as cs}from"./chunk-GYKNCYES.mjs";import{a as es,b as ts,c as ye,d as ns,e as ss,f as rt,g as rs,h as is,i as os,j as as}from"./chunk-YOGMP72T.mjs";import{i as ls,l as us}from"./chunk-6CDIIFNX.mjs";import{c as Yn}from"./chunk-MWLFFVQV.mjs";import{b as Vn}from"./chunk-YIGFYZQY.mjs";import{a as jt,b as Gn,c as we,d as Lt,e as Nt,f as Jn,g as Kn,m as Hn}from"./chunk-R6TF26V4.mjs";import{d as Pt,f as Ce,l as At,n as tt}from"./chunk-JU2XEKEO.mjs";import{a as Xn,b as Qn}from"./chunk-K55LH4ZQ.mjs";import{Bc as bn,Cc as Rn,xc as Ze}from"./chunk-CAFUNR6D.mjs";import{a as wn,b as mn,c as yn,e as Ye,f as kn,h as Wn,i as _n}from"./chunk-AITNZWLB.mjs";import{a as It,d as In,f as On,h as Pn,j as An,k as jn,l as Xe,m as Ln,p as Nn,q as Bn}from"./chunk-GWRKS3AL.mjs";import{A as $n,B as zn,a as hn,v as Dn,w as Mn,z as Un}from"./chunk-6SEDOIO3.mjs";import{J as vt,K as fn,N as pn,P as Ve}from"./chunk-ZWCRWF7E.mjs";import{a as Rt,b as un}from"./chunk-54HYHHVL.mjs";import{l as gn}from"./chunk-MNITSYI2.mjs";import{B as nt,E as xn,F as st,i as Me,j as Ot,l as Se,p as Ne,q as Tn,r as et,z as qn}from"./chunk-ETT5GP4P.mjs";import{b as E,e as Be,g as En}from"./chunk-SW2NUKQL.mjs";import{A as $e,H,N as Fn,d as Qe,g as Cn,x as Ue,y as je,z as Le}from"./chunk-E2YJVSX6.mjs";import{t as St,v as Sn}from"./chunk-T26C576X.mjs";import{b as Y,d as ge,e as ln}from"./chunk-BNO5GIJ6.mjs";import{c as vn}from"./chunk-6IGEASOF.mjs";import{fc as Zn}from"./chunk-KOQV4WXC.mjs";import{i as He}from"./chunk-INIT2UKJ.mjs";import{E as cn}from"./chunk-XEB6HZ34.mjs";import{da as Ke,ja as rn,ka as on}from"./chunk-55LQD3Y3.mjs";import{h as de}from"./chunk-TZE3Y7IQ.mjs";import{g as Ae,h as ne,i as an,q as dn}from"./chunk-EAFLDSQ2.mjs";import{b as Q}from"./chunk-CA5NAXSU.mjs";import{Ra as Qt,Ta as Je,Ua as en,Yb as tn,od as sn,vc as nn,wd as kt,zd as bt}from"./chunk-DPYTG6DM.mjs";import{b as X,e as Yt,f as De,i as yt,k as le,l as _,o as Ge,p as Zt,u as Pe,v as Z,z as Xt}from"./chunk-WZQEK4WT.mjs";import{randomBytes as Us}from"node:crypto";import{rm as $s}from"node:fs/promises";import{join as zs}from"node:path";var ar=5,dr="005",cr=new Set(["001"]),Bt="Kept: a file's link to a user is never removed, and Salesforce refuses to remove its owner's ('FIELD_INTEGRITY_EXCEPTION').",it="Its sharing type stays as it is: Salesforce doesn't change the sharing type of a file's link to an account ('The sharing type cannot be updated because updates are not currently supported for the linked Entity type').";function ue(){return{done:0,already:0,refused:0,notSent:0,notReached:0,reasons:[],left:[],made:[],cancelled:!1}}function Fe(i,e){i.done+=e.done,i.already+=e.already,i.refused+=e.refused,i.notSent+=e.notSent,i.notReached+=e.notReached;for(let t of e.reasons)ot(i.reasons,t);i.left.push(...e.left),i.made.push(...e.made),i.cancelled||=e.cancelled}function ot(i,e){i.length<ar&&!i.includes(e)&&i.push(e)}var lr=_({success:De(),id:X().nullish(),errors:le(Ge([X(),_({statusCode:X().optional(),message:X().optional()}).loose()])).optional()}).loose();function ur(i,e){let t=Array.isArray(i)?i:[i];return Array.from({length:e},(n,s)=>{let r=lr.safeParse(t[s]);if(!r.success)return{success:!1,words:"The org gave no answer for it."};let{success:a,id:o,errors:d}=r.data,c=(d??[])[0],p=typeof c=="object"?c.statusCode:void 0,f=(d??[]).map(u=>typeof u=="string"?u:[u.statusCode,u.message].filter(l=>l).join(": ")).filter(u=>u!=="").join("; ");return{success:a,...typeof o=="string"?{id:o}:{},...p!==void 0?{code:p}:{},...f!==""?{words:f}:{}}})}function fr(i){let e=[];for(let t=0;t<i.length;t+=Y)e.push(i.slice(t,t+Y));return e}async function Ct(i,e,t,n){let s=ue();for(let r of fr(i)){if(s.cancelled||e.stopped?.()===!0){s.cancelled=!0,s.notReached+=r.length;for(let d of r)s.left.push({id:d.Id,reason:"Not reached: stopped."});continue}await e.before?.(r);let a=ur(await t(r),r.length),o={done:[],made:[],left:[]};r.forEach((d,c)=>{let p=a[c],f=n(p);if(f==="done"){s.done++,o.done.push(d),p.id!==void 0&&o.made.push({from:d.Id,id:p.id});return}if(o.left.push(d.Id),f==="already"){s.already++;return}let u=p.words??"The org gave no reason.";s.refused++,ot(s.reasons,u),s.left.push({id:d.Id,reason:u})}),s.made.push(...o.made),await e.after?.(o)}return s}function ps(i,e,t,n){let s=[];for(let r of i){if(!e(r)){s.push(r);continue}n.notSent++,ot(n.reasons,t),n.left.push({id:r.Id,reason:t})}return s}async function at(i,e,t={}){let n=ue(),s=ps(e,a=>a.LinkedEntityId?.startsWith(dr)===!0,Bt,n),r=await Ct(s,t,a=>i.destroy(ne,a.map(o=>o.Id)),a=>a.success?"done":a.code==="ENTITY_IS_DELETED"||a.code==="NOT_FOUND"?"already":"refused");return Fe(r,n),r}async function dt(i,e,t={},n=s=>s){return Ct(e,t,s=>i.create(ne,s.map(r=>({ContentDocumentId:n(r.ContentDocumentId),LinkedEntityId:n(r.LinkedEntityId),ShareType:r.ShareType,Visibility:r.Visibility}))),s=>s.success&&s.id!==void 0?"done":s.code==="DUPLICATE_VALUE"?"already":"refused")}async function ct(i,e,t={}){let n=d=>cr.has(d.LinkedEntityId.slice(0,3)),s=ue(),r=new Map,a=ps(e,d=>d.Visibility===d.now.Visibility&&n(d),it,s);for(let d of a){let c=d.ShareType!==d.now.ShareType&&!n(d);d.ShareType!==d.now.ShareType&&n(d)&&ot(s.reasons,it),r.set(d.Id,{Id:d.Id,...c?{ShareType:d.ShareType}:{},...d.Visibility!==d.now.Visibility?{Visibility:d.Visibility}:{}})}let o=await Ct(a,t,d=>i.update(ne,d.map(c=>r.get(c.Id)??{Id:c.Id})),d=>d.success?"done":d.code==="ENTITY_IS_DELETED"?"already":"refused");return Fe(s,o),s}import{randomBytes as ks}from"node:crypto";import{closeSync as pr,createReadStream as bs,fsyncSync as hr,openSync as gr,readFileSync as wr,renameSync as mr,writeSync as yr}from"node:fs";import{open as ut,readdir as Rs,rm as vs,stat as kr,truncate as Ss}from"node:fs/promises";import{dirname as Is,join as ee}from"node:path";import{createInterface as Os}from"node:readline";var Te="journal.ndjson",br="before.json",J=2e3,Ps=X().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record id"),Tt=X().regex(/^005[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/,"Not a User Id"),be=X().regex(/^[A-Za-z][A-Za-z0-9_]*$/,"Not an API name").max(80),V=Xt.datetime({offset:!0}),ae=le(Ps).min(1).max(J),As=Yt().int().positive(),js=_({kind:Z("head"),version:Z(1),rewindId:Je,checkpointId:Qt,organizationId:en,startedAt:V,userId:Tt,automatedProcessUserId:Tt.optional(),backup:X().min(1).max(200),at:V}),Rr=_({kind:Z("resumed"),startedAt:V,userId:Tt,at:V}),vr=_({kind:Pe(["bringingBack","withParent","givingBack"]),objectApiName:be,ids:ae,parents:ae.optional(),carriers:Z(!0).optional(),at:V}),Sr=_({kind:Z("bringBackLeft"),objectApiName:be,ids:ae,at:V}),Ir=_({kind:Z("recreating"),objectApiName:be,ids:ae,at:V}),Or=_({kind:Z("recreated"),objectApiName:be,ids:ae,from:ae,at:V}),Pr=_({kind:Pe(["deleting","deleteLeft"]),step:As,objectApiName:be,ids:ae,at:V}),Ar=_({kind:Z("heldInPlace"),objectApiName:be,by:le(be).min(1).max(100),ids:ae,at:V}),jr=_({kind:Z("beforeParent"),objectApiName:be,ids:ae,parents:ae,at:V}),Lr=_({kind:Z("deleted"),step:As,at:V}),Nr=_({kind:Z("removal"),state:yt(),at:V}),Br=_({kind:Z("unlinking"),links:le(we).min(1).max(J),at:V}),Cr=_({kind:Pe(["unlinkLeft","linksUpdateLeft"]),ids:ae,at:V}),Fr=_({kind:Z("relinked"),ids:ae,from:ae,at:V}),Ls=we.pick({Id:!0,LinkedEntityId:!0,ShareType:!0,Visibility:!0}),Tr=_({kind:Z("linksUpdating"),links:le(Ls).min(1).max(J),at:V}),Er=_({kind:Z("linksUndone"),part:Pe(["reinserted","removed","shared"]),ids:ae,at:V}),Dr=_({kind:Z("wrote"),at:V}),Mr=_({kind:Z("end"),at:V}),Ur=_({kind:Z("undo"),state:yt(),status:Pe(["success","partial","failure","cancelled"]),at:V}),$r=Zt("kind",[js,Rr,vr,Sr,Ar,jr,Ir,Or,Pr,Lr,Nr,Br,Cr,Fr,Tr,Er,Dr,Mr,Ur]),zr=new Set(["bringingBack","withParent","bringBackLeft","givingBack","recreating","recreated","deleting","deleteLeft","deleted","removal","unlinking","unlinkLeft","relinked","linksUpdating","linksUpdateLeft","wrote"]);async function Et(i){let e;try{e=await ut(i,"r"),await e.sync()}catch{}finally{await e?.close().catch(()=>{})}}async function Ut(i,e){let t=await ut(i,"a",Qe);try{await t.appendFile(e,"utf8"),await t.sync()}finally{await t.close()}}function Wr(i,e){let t=`${i}.${process.pid}-${ks(4).toString("hex")}.tmp`,n=Buffer.from(e,"utf8"),s=gr(t,"wx",Qe);try{for(let r=0;r<n.length;)r+=yr(s,n,r,n.length-r);hr(s)}finally{pr(s)}mr(t,i)}function _r(i){let e=[];try{let n=JSON.parse(wr(i,"utf8"));Array.isArray(n.openings)&&(e=n.openings)}catch{}let t=e.length;return{set:(n,s)=>{e[t]=s,Wr(i,`${JSON.stringify({version:1,openings:e})}
7
+ import{e as ds,f as cs}from"./chunk-CBL42DUU.mjs";import{a as es,b as ts,c as ye,d as ns,e as ss,f as rt,g as rs,h as is,i as os,j as as}from"./chunk-MKTXJCXN.mjs";import{i as ls,l as us}from"./chunk-RCYEBY42.mjs";import{c as Yn}from"./chunk-AUS6NFLZ.mjs";import{b as Vn}from"./chunk-DBBPDSFN.mjs";import{a as jt,b as Gn,c as we,d as Lt,e as Nt,f as Jn,g as Kn,m as Hn}from"./chunk-YMDFF657.mjs";import{d as Pt,f as Ce,l as At,n as tt}from"./chunk-YT22LMF7.mjs";import{a as Xn,b as Qn}from"./chunk-ZXFL2MSN.mjs";import{Bc as bn,Cc as Rn,xc as Ze}from"./chunk-ISSP2FZ5.mjs";import{a as wn,b as mn,c as yn,e as Ye,f as kn,h as Wn,i as _n}from"./chunk-XU25YA46.mjs";import{a as It,d as In,f as On,h as Pn,j as An,k as jn,l as Xe,m as Ln,p as Nn,q as Bn}from"./chunk-VZT4E2OJ.mjs";import{A as $n,B as zn,a as hn,v as Dn,w as Mn,z as Un}from"./chunk-O2PUGRNW.mjs";import{J as vt,K as fn,N as pn,P as Ve}from"./chunk-7SDZR6SR.mjs";import{a as Rt,b as un}from"./chunk-54HYHHVL.mjs";import{l as gn}from"./chunk-3SKLBRPL.mjs";import{B as nt,E as xn,F as st,i as Me,j as Ot,l as Se,p as Ne,q as Tn,r as et,z as qn}from"./chunk-SAMWHL22.mjs";import{b as E,e as Be,g as En}from"./chunk-6KP6WETK.mjs";import{A as $e,H,N as Fn,d as Qe,g as Cn,x as Ue,y as je,z as Le}from"./chunk-J24TIGSI.mjs";import{b as St,d as Sn}from"./chunk-HKUWHVI7.mjs";import{b as Y,d as ge,e as ln}from"./chunk-VPDEJGPS.mjs";import{c as vn}from"./chunk-JQZTMFO7.mjs";import{fc as Zn}from"./chunk-JFNLKHY6.mjs";import{i as He}from"./chunk-INIT2UKJ.mjs";import{E as cn}from"./chunk-XZISAZA6.mjs";import{g as Ae,h as ne,i as an,q as dn}from"./chunk-L4INJ5TZ.mjs";import{da as Ke,ja as rn,ka as on}from"./chunk-KIMQQ6JQ.mjs";import{h as de}from"./chunk-TZE3Y7IQ.mjs";import{b as Q}from"./chunk-CA5NAXSU.mjs";import{Ad as sn,Hc as nn,Id as kt,Ld as bt,Ra as Qt,Ta as Je,Ua as en,ic as tn}from"./chunk-ZQO5PDX5.mjs";import{b as X,e as Yt,f as De,i as yt,k as le,l as _,o as Ge,p as Zt,u as Pe,v as Z,z as Xt}from"./chunk-WZQEK4WT.mjs";import{randomBytes as Us}from"node:crypto";import{rm as $s}from"node:fs/promises";import{join as zs}from"node:path";var ar=5,dr="005",cr=new Set(["001"]),Bt="Kept: a file's link to a user is never removed, and Salesforce refuses to remove its owner's ('FIELD_INTEGRITY_EXCEPTION').",it="Its sharing type stays as it is: Salesforce doesn't change the sharing type of a file's link to an account ('The sharing type cannot be updated because updates are not currently supported for the linked Entity type').";function ue(){return{done:0,already:0,refused:0,notSent:0,notReached:0,reasons:[],left:[],made:[],cancelled:!1}}function Fe(i,e){i.done+=e.done,i.already+=e.already,i.refused+=e.refused,i.notSent+=e.notSent,i.notReached+=e.notReached;for(let t of e.reasons)ot(i.reasons,t);i.left.push(...e.left),i.made.push(...e.made),i.cancelled||=e.cancelled}function ot(i,e){i.length<ar&&!i.includes(e)&&i.push(e)}var lr=_({success:De(),id:X().nullish(),errors:le(Ge([X(),_({statusCode:X().optional(),message:X().optional()}).loose()])).optional()}).loose();function ur(i,e){let t=Array.isArray(i)?i:[i];return Array.from({length:e},(n,s)=>{let r=lr.safeParse(t[s]);if(!r.success)return{success:!1,words:"The org gave no answer for it."};let{success:a,id:o,errors:d}=r.data,c=(d??[])[0],p=typeof c=="object"?c.statusCode:void 0,f=(d??[]).map(u=>typeof u=="string"?u:[u.statusCode,u.message].filter(l=>l).join(": ")).filter(u=>u!=="").join("; ");return{success:a,...typeof o=="string"?{id:o}:{},...p!==void 0?{code:p}:{},...f!==""?{words:f}:{}}})}function fr(i){let e=[];for(let t=0;t<i.length;t+=Y)e.push(i.slice(t,t+Y));return e}async function Ct(i,e,t,n){let s=ue();for(let r of fr(i)){if(s.cancelled||e.stopped?.()===!0){s.cancelled=!0,s.notReached+=r.length;for(let d of r)s.left.push({id:d.Id,reason:"Not reached: stopped."});continue}await e.before?.(r);let a=ur(await t(r),r.length),o={done:[],made:[],left:[]};r.forEach((d,c)=>{let p=a[c],f=n(p);if(f==="done"){s.done++,o.done.push(d),p.id!==void 0&&o.made.push({from:d.Id,id:p.id});return}if(o.left.push(d.Id),f==="already"){s.already++;return}let u=p.words??"The org gave no reason.";s.refused++,ot(s.reasons,u),s.left.push({id:d.Id,reason:u})}),s.made.push(...o.made),await e.after?.(o)}return s}function ps(i,e,t,n){let s=[];for(let r of i){if(!e(r)){s.push(r);continue}n.notSent++,ot(n.reasons,t),n.left.push({id:r.Id,reason:t})}return s}async function at(i,e,t={}){let n=ue(),s=ps(e,a=>a.LinkedEntityId?.startsWith(dr)===!0,Bt,n),r=await Ct(s,t,a=>i.destroy(ne,a.map(o=>o.Id)),a=>a.success?"done":a.code==="ENTITY_IS_DELETED"||a.code==="NOT_FOUND"?"already":"refused");return Fe(r,n),r}async function dt(i,e,t={},n=s=>s){return Ct(e,t,s=>i.create(ne,s.map(r=>({ContentDocumentId:n(r.ContentDocumentId),LinkedEntityId:n(r.LinkedEntityId),ShareType:r.ShareType,Visibility:r.Visibility}))),s=>s.success&&s.id!==void 0?"done":s.code==="DUPLICATE_VALUE"?"already":"refused")}async function ct(i,e,t={}){let n=d=>cr.has(d.LinkedEntityId.slice(0,3)),s=ue(),r=new Map,a=ps(e,d=>d.Visibility===d.now.Visibility&&n(d),it,s);for(let d of a){let c=d.ShareType!==d.now.ShareType&&!n(d);d.ShareType!==d.now.ShareType&&n(d)&&ot(s.reasons,it),r.set(d.Id,{Id:d.Id,...c?{ShareType:d.ShareType}:{},...d.Visibility!==d.now.Visibility?{Visibility:d.Visibility}:{}})}let o=await Ct(a,t,d=>i.update(ne,d.map(c=>r.get(c.Id)??{Id:c.Id})),d=>d.success?"done":d.code==="ENTITY_IS_DELETED"?"already":"refused");return Fe(s,o),s}import{randomBytes as ks}from"node:crypto";import{closeSync as pr,createReadStream as bs,fsyncSync as hr,openSync as gr,readFileSync as wr,renameSync as mr,writeSync as yr}from"node:fs";import{open as ut,readdir as Rs,rm as vs,stat as kr,truncate as Ss}from"node:fs/promises";import{dirname as Is,join as ee}from"node:path";import{createInterface as Os}from"node:readline";var Te="journal.ndjson",br="before.json",J=2e3,Ps=X().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record id"),Tt=X().regex(/^005[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/,"Not a User Id"),be=X().regex(/^[A-Za-z][A-Za-z0-9_]*$/,"Not an API name").max(80),V=Xt.datetime({offset:!0}),ae=le(Ps).min(1).max(J),As=Yt().int().positive(),js=_({kind:Z("head"),version:Z(1),rewindId:Je,checkpointId:Qt,organizationId:en,startedAt:V,userId:Tt,automatedProcessUserId:Tt.optional(),backup:X().min(1).max(200),at:V}),Rr=_({kind:Z("resumed"),startedAt:V,userId:Tt,at:V}),vr=_({kind:Pe(["bringingBack","withParent","givingBack"]),objectApiName:be,ids:ae,parents:ae.optional(),carriers:Z(!0).optional(),at:V}),Sr=_({kind:Z("bringBackLeft"),objectApiName:be,ids:ae,at:V}),Ir=_({kind:Z("recreating"),objectApiName:be,ids:ae,at:V}),Or=_({kind:Z("recreated"),objectApiName:be,ids:ae,from:ae,at:V}),Pr=_({kind:Pe(["deleting","deleteLeft"]),step:As,objectApiName:be,ids:ae,at:V}),Ar=_({kind:Z("heldInPlace"),objectApiName:be,by:le(be).min(1).max(100),ids:ae,at:V}),jr=_({kind:Z("beforeParent"),objectApiName:be,ids:ae,parents:ae,at:V}),Lr=_({kind:Z("deleted"),step:As,at:V}),Nr=_({kind:Z("removal"),state:yt(),at:V}),Br=_({kind:Z("unlinking"),links:le(we).min(1).max(J),at:V}),Cr=_({kind:Pe(["unlinkLeft","linksUpdateLeft"]),ids:ae,at:V}),Fr=_({kind:Z("relinked"),ids:ae,from:ae,at:V}),Ls=we.pick({Id:!0,LinkedEntityId:!0,ShareType:!0,Visibility:!0}),Tr=_({kind:Z("linksUpdating"),links:le(Ls).min(1).max(J),at:V}),Er=_({kind:Z("linksUndone"),part:Pe(["reinserted","removed","shared"]),ids:ae,at:V}),Dr=_({kind:Z("wrote"),at:V}),Mr=_({kind:Z("end"),at:V}),Ur=_({kind:Z("undo"),state:yt(),status:Pe(["success","partial","failure","cancelled"]),at:V}),$r=Zt("kind",[js,Rr,vr,Sr,Ar,jr,Ir,Or,Pr,Lr,Nr,Br,Cr,Fr,Tr,Er,Dr,Mr,Ur]),zr=new Set(["bringingBack","withParent","bringBackLeft","givingBack","recreating","recreated","deleting","deleteLeft","deleted","removal","unlinking","unlinkLeft","relinked","linksUpdating","linksUpdateLeft","wrote"]);async function Et(i){let e;try{e=await ut(i,"r"),await e.sync()}catch{}finally{await e?.close().catch(()=>{})}}async function Ut(i,e){let t=await ut(i,"a",Qe);try{await t.appendFile(e,"utf8"),await t.sync()}finally{await t.close()}}function Wr(i,e){let t=`${i}.${process.pid}-${ks(4).toString("hex")}.tmp`,n=Buffer.from(e,"utf8"),s=gr(t,"wx",Qe);try{for(let r=0;r<n.length;)r+=yr(s,n,r,n.length-r);hr(s)}finally{pr(s)}mr(t,i)}function _r(i){let e=[];try{let n=JSON.parse(wr(i,"utf8"));Array.isArray(n.openings)&&(e=n.openings)}catch{}let t=e.length;return{set:(n,s)=>{e[t]=s,Wr(i,`${JSON.stringify({version:1,openings:e})}
8
8
  `)}}}function W(i){return i.slice(0,15)}function pe(i){let e=[];for(let t=0;t<i.length;t+=J)e.push(i.slice(t,t+J));return e}async function*qr(i){if(!fn(i)){for(let{objectApiName:e,ids:t}of i)t.length>0&&(yield{objectApiName:e,ids:[...t]});return}for(let{objectApiName:e}of i.objects)for await(let t of i.pages(e))t.length>0&&(yield{objectApiName:e,ids:[...t]})}var lt=class i{constructor(e,t,n,s,r,a){this.dir=t;this.resumed=n;this.handle=s;this.step=r;this.now=a;this.rewindId=e.rewindId,this.backup=e.backup;let o=new Set,d=new _n({...Wn(t),appendFile:async(p,f)=>{await Ut(p,f),o.has(p)||(o.add(p),await Et(Is(p)))}}),c={begin:()=>Le(ee(t,"backups")),append:(p,f,u)=>d.append(p,f,u)};if(this.kept=Qn({runId:e.rewindId,orgId:e.organizationId,organizationId:e.organizationId,files:c,meta:_r(ee(t,br)),now:a}),this.kept.id!==e.backup)throw new H("damaged","The rewind\u2019s journal names another backup of its values than the one they are kept in.");this.values=d,this.keep=async(p,f)=>{await this.kept.keep(p,f);let u=f.flatMap(l=>typeof l.Id=="string"?[l.Id]:[]);for(let l of pe(u))await this.append({kind:"givingBack",objectApiName:p,ids:l})}}dir;resumed;handle;step;now;keep;values;queue=Promise.resolve();closed=!1;openStep;kept;rewindId;backup;static async opened(e,t,n,s,r){let a=await ut(ee(e,Te),"a",Qe);try{return new i(t,e,n,a,s,r)}catch(o){throw await a.close(),o}}append(e){if(this.closed)return Promise.reject(new Error("The rewind\u2019s journal is closed."));let t=`${JSON.stringify({...e,at:this.now().toISOString()})}
9
9
  `,n=this.queue.then(async()=>{await this.handle.appendFile(t,"utf8"),await this.handle.sync()});return this.queue=n.catch(()=>{}),n}async appendIds(e,t,n,s=!1){for(let r of pe(n))await this.append({kind:e,objectApiName:t,ids:r,...s?{carriers:s}:{}})}bringingBack(e,t,n={}){let s=new Map;for(let{objectApiName:r,ids:a}of e){let[o]=a;o!==void 0&&s.set(o.slice(0,3),r)}return async r=>{let a=new Set(r.map(d=>s.get(d.slice(0,3)))),[o]=[...a];if(a.size!==1||o===void 0)throw new Error("These records are not of the plan the journal names: none was sent.");return await this.appendIds("bringingBack",o,r,n.carriers===!0),t(r)}}async withParent(e,t,n,s={}){let r=s.carriers===!0;if(n===void 0){await this.appendIds("withParent",e,t,r);return}if(n.length!==t.length)throw new Error("Each record that comes back with a parent is named beside that parent.");for(let a=0;a<t.length;a+=J)await this.append({kind:"withParent",objectApiName:e,ids:t.slice(a,a+J),parents:n.slice(a,a+J),...r?{carriers:r}:{}})}async bringBackLeft(e,t){for(let n of pe(t))await this.append({kind:"bringBackLeft",objectApiName:e,ids:n})}async heldInPlace(e,t,n){if(t.length!==0)for(let s of pe(n))await this.append({kind:"heldInPlace",objectApiName:e,by:[...t],ids:s})}async beforeParent(e,t){for(let n=0;n<t.length;n+=J){let s=t.slice(n,n+J);await this.append({kind:"beforeParent",objectApiName:e,ids:s.map(({id:r})=>r),parents:s.map(({parent:r})=>r)})}}async recreating(e,t){for(let n of pe(t))await this.append({kind:"recreating",objectApiName:e,ids:n})}async recreated(e,t){for(let n=0;n<t.length;n+=J){let s=t.slice(n,n+J);await this.append({kind:"recreated",objectApiName:e,ids:s.map(({id:r})=>r),from:s.map(({from:r})=>r)})}}async deleting(e){let t=++this.step;this.openStep=t;for await(let{objectApiName:n,ids:s}of qr(e))for(let r of pe(s))await this.append({kind:"deleting",step:t,objectApiName:n,ids:r})}async deleted(e){let t=this.openStep;if(t===void 0)throw new Error("No removal was named to the journal before it.");for await(let{objectApiName:n,ids:s}of e.left())for(let r of pe(s))await this.append({kind:"deleteLeft",step:t,objectApiName:n,ids:r});await this.append({kind:"deleted",step:t}),this.openStep=void 0}async removal(e){let t={...e.removalStamps&&Object.keys(e.removalStamps).length>0?{removalStamps:e.removalStamps}:{},...e.removalSpans&&e.removalSpans.length>0?{removalSpans:e.removalSpans}:{}};Object.keys(t).length!==0&&await this.append({kind:"removal",state:{version:1,...t}})}async unlinking(e){for(let t=0;t<e.length;t+=J)await this.append({kind:"unlinking",links:e.slice(t,t+J)})}async unlinkLeft(e){for(let t of pe(e))await this.append({kind:"unlinkLeft",ids:t})}async relinked(e){for(let t=0;t<e.length;t+=J){let n=e.slice(t,t+J);await this.append({kind:"relinked",ids:n.map(({id:s})=>s),from:n.map(({from:s})=>s)})}}async linksUpdating(e){for(let t=0;t<e.length;t+=J){let n=e.slice(t,t+J).map(s=>({Id:s.Id,LinkedEntityId:s.LinkedEntityId,ShareType:s.ShareType,Visibility:s.Visibility}));await this.append({kind:"linksUpdating",links:n})}}async linksUpdateLeft(e){for(let t of pe(e))await this.append({kind:"linksUpdateLeft",ids:t})}async linksUndone(e,t){for(let n of pe(t))await this.append({kind:"linksUndone",part:e,ids:n})}async wrote(){await this.append({kind:"wrote"})}async end(){await this.append({kind:"end"})}async undone(e,t){await this.append({kind:"undo",state:{version:1,...e},status:t})}async read(){return await this.queue,Ns(ee(this.dir,Te))}async facts(){return await this.queue,Gr(ee(this.dir,Te))}async close(){if(!this.closed){this.closed=!0;try{this.kept.close()}catch{}await this.queue,await this.handle.close()}}};async function ke(i,e){let t=(await kr(i)).size,n=t===0;if(t>0){let p=await ut(i,"r");try{let f=Buffer.alloc(1);await p.read(f,0,1,t-1),n=f[0]===10}finally{await p.close()}}let s=0,r=0,a=async p=>{r+=Buffer.byteLength(p,"utf8")+1;let f;try{f=JSON.parse(p)}catch{f=void 0}let u=$r.safeParse(f);if(!u.success)throw new H("damaged",`The rewind\u2019s journal is damaged at line ${s+1}: it is not used.`);xr(u.data),s++,await e(u.data)},o=bs(i,{encoding:"utf8"}),d=Os({input:o,crlfDelay:1/0}),c;try{for await(let p of d)c!==void 0&&await a(c),c=p}finally{d.close(),o.destroy()}return c!==void 0&&n&&await a(c),{count:s,whole:r,size:t}}function xr(i){if(i.kind==="relinked"&&i.from.length!==i.ids.length)throw new H("damaged","The rewind\u2019s journal names links inserted again without the links they stand for.");if(i.kind==="recreated"&&i.from.length!==i.ids.length)throw new H("damaged","The rewind\u2019s journal names records made again without the Ids they had.");if(i.kind==="beforeParent"&&i.parents.length!==i.ids.length)throw new H("damaged","The rewind\u2019s journal names records deleted before a parent without their parent.");if((i.kind==="withParent"||i.kind==="bringingBack")&&i.parents!==void 0&&i.parents.length!==i.ids.length)throw new H("damaged","The rewind\u2019s journal names records that came back with a parent without it.")}var he=class{byObject=new Map;add(e,t){let n=this.byObject.get(e)??new Map;for(let s of t)n.has(W(s))||n.set(W(s),s);this.byObject.set(e,n)}drop(e,t){let n=this.byObject.get(e);if(n)for(let s of t)n.delete(W(s))}list(e=()=>!0){return[...this.byObject].flatMap(([t,n])=>{let s=[...n].filter(([r])=>e(r)).map(([,r])=>r);return s.length>0?[{objectApiName:t,ids:s}]:[]})}keys(){return new Set([...this.byObject.values()].flatMap(e=>[...e.keys()]))}};function hs(i){let e={};for(let t of i)e={...e,...t,...t.removalStamps||e.removalStamps?{removalStamps:{...e.removalStamps,...t.removalStamps}}:{},...t.removalSpans||e.removalSpans?{removalSpans:[...e.removalSpans??[],...t.removalSpans??[]]}:{}};return e}function gs(i){let e=gn(i);if(e===void 0)throw new H("damaged","The rewind\u2019s journal holds a state it cannot read.");return e}var ze=class{head;step=0;passes=[];rewindStates=[];undoStates=[];undos=[];lastWrite=Number.NEGATIVE_INFINITY;endedAt;line(e){if(this.head===void 0){if(e.kind!=="head")throw new H("damaged","The rewind\u2019s journal does not begin with its head.");this.head=e,this.passes=[{startedAt:e.startedAt,userId:e.userId}];return}switch(zr.has(e.kind)&&(this.lastWrite=Math.max(this.lastWrite,Date.parse(e.at))),"step"in e&&(this.step=Math.max(this.step,e.step)),e.kind){case"head":throw new H("damaged","The rewind\u2019s journal has two heads.");case"resumed":this.passes.push({startedAt:e.startedAt,userId:e.userId});break;case"removal":this.rewindStates.push(gs(e.state));break;case"end":this.endedAt=e.at;break;case"undo":this.undoStates.push(gs(e.state)),this.undos.push({status:e.status,at:e.at});break;default:break}}result(){let e=this.head;if(e===void 0)throw new H("damaged","The rewind\u2019s journal does not begin with its head.");return{head:{rewindId:e.rewindId,checkpointId:e.checkpointId,organizationId:e.organizationId,startedAt:e.startedAt,userId:e.userId,...e.automatedProcessUserId!==void 0?{automatedProcessUserId:e.automatedProcessUserId}:{},backup:e.backup},passes:this.passes,...Number.isFinite(this.lastWrite)?{lastWriteAt:new Date(this.lastWrite).toISOString()}:{},...this.endedAt!==void 0?{endedAt:this.endedAt}:{},rewind:hs(this.rewindStates),undo:hs(this.undoStates),undos:this.undos}}},Dt=class{broughtBack=new he;recreated=new he;carriers=new he;carried=new Map;givenBack=new he;held=new he;heldBy=new Map;beforeParent=[];withParents=new Map;steps=new Map;stepOf(e){let t=this.steps.get(e);return t||(t={deleting:new he,left:new Set,answered:!1},this.steps.set(e,t)),t}line(e){switch(e.kind){case"bringingBack":case"withParent":this.broughtBack.add(e.objectApiName,e.ids),e.carriers===!0&&e.kind==="bringingBack"&&this.carriers.add(e.objectApiName,e.ids),e.parents?.forEach((t,n)=>{let s=e.ids[n],r=e.carriers===!0?this.carried:this.withParents;r.has(W(s))||r.set(W(s),{objectApiName:e.objectApiName,id:s,parent:t})});break;case"bringBackLeft":this.broughtBack.drop(e.objectApiName,e.ids),this.carriers.drop(e.objectApiName,e.ids);for(let t of e.ids)this.withParents.delete(W(t)),this.carried.delete(W(t));break;case"givingBack":this.givenBack.add(e.objectApiName,e.ids);break;case"recreated":this.recreated.add(e.objectApiName,e.ids);break;case"heldInPlace":{this.held.add(e.objectApiName,e.ids);let t=this.heldBy.get(e.objectApiName)??new Set;for(let n of e.by)t.add(n);this.heldBy.set(e.objectApiName,t);break}case"beforeParent":e.ids.forEach((t,n)=>{this.beforeParent.push({objectApiName:e.objectApiName,id:t,parent:e.parents[n]})});break;case"deleting":this.stepOf(e.step).deleting.add(e.objectApiName,e.ids);break;case"deleteLeft":for(let t of e.ids)this.stepOf(e.step).left.add(W(t));break;case"deleted":this.stepOf(e.step).answered=!0;break;default:break}}result(){let e=new he;for(let{deleting:u,left:l,answered:h}of this.steps.values())for(let{objectApiName:g,ids:w}of u.list(y=>!h||!l.has(y)))e.add(g,w);let t=this.held.list().map(({objectApiName:u,ids:l})=>({objectApiName:u,ids:l,by:[...this.heldBy.get(u)??[]]})),n=e.keys(),s=new Set([...this.steps.values()].flatMap(({deleting:u})=>[...u.keys()])),r=new he;for(let{objectApiName:u,id:l,parent:h}of this.beforeParent){let g=W(h);n.has(W(l))&&(n.has(g)||!s.has(g))&&r.add(u,[l])}let a=r.list(),o=u=>{let l=new Map;for(let{objectApiName:h,id:g,parent:w}of u){let y=l.get(h)??{objectApiName:h,ids:[],parents:[]};y.ids.push(g),y.parents.push(w),l.set(h,y)}return[...l.values()]},d=o(this.withParents.values()),c=o(this.carried.values()),p=this.carriers.list(),f=this.recreated.list();return{broughtBack:this.broughtBack.list(),deleted:e.list(),givenBack:this.givenBack.list(),...t.length>0?{heldInPlace:t}:{},...a.length>0?{deletedBeforeParent:a}:{},...d.length>0?{withParents:d}:{},...f.length>0?{recreated:f}:{},...p.length>0?{carriers:p}:{},...c.length>0?{carried:c}:{}}}};async function Ns(i){let e=new ze,t=new Dt;try{await ke(i,n=>{e.line(n),t.line(n)})}catch(n){throw n instanceof H?n:new H("notFound","No journal of this rewind is kept.")}return{...e.result(),did:t.result()}}async function Gr(i){let e=new ze;try{await ke(i,t=>e.line(t))}catch(t){throw t instanceof H?t:new H("notFound","No journal of this rewind is kept.")}return e.result()}function Jr(i,e,t){if(i.head.rewindId!==t||i.head.checkpointId!==e.checkpointId||i.head.organizationId.slice(0,15)!==e.organizationId.slice(0,15))throw new H("damaged","The rewind\u2019s journal names another rewind, checkpoint or org than its folder.")}async function wo(i,e){let t=await We(i,e);if(!t)throw new H("notFound","No journal of this rewind is kept.");return Ns(t.file)}function Bs(i,e){if(i.organizationId.slice(0,15)!==e.organizationId.slice(0,15))throw new H("invalid","A rewind\u2019s journal is written under its org\u2019s lock.")}async function We(i,e){let t=je(i,e),n=ee(t,Te),s=new ze,r;try{r=await ke(n,o=>s.line(o))}catch(o){if(o instanceof H)throw o;return}if(r.count===0||s.head===void 0)return;let a=s.result();return Jr(a,i,e),{dir:t,file:n,head:s.head,step:s.step,whole:r.whole,size:r.size,facts:a}}async function Cs(i,e){return i.whole<i.size&&await Ss(i.file,i.whole),lt.opened(i.dir,i.head,!0,i.step,e)}var ws=18;async function Kr(i){let e;try{e=(await Rs(i.rewindsDir,{withFileTypes:!0})).filter(n=>n.isDirectory()&&Je.safeParse(n.name).success).map(n=>n.name).sort().reverse()}catch{return[]}let[t]=e;return t===void 0?[]:e.filter(n=>n.slice(0,ws)===t.slice(0,ws))}async function Fs(i){let{folder:e}=i;Bs(i.lock,e);let t=i.now??(()=>new Date),n;for(let d of await Kr(e)){let c=await We(e,d);if(!c){n??=d;continue}if(c.facts.endedAt!==void 0||c.facts.undos.length>0)continue;let p=await Cs(c,t);try{await p.append({kind:"resumed",startedAt:i.startedAt,userId:i.userId})}catch(f){throw await p.close(),f}return p}let s=n??$e("rw",t()),r=je(e,s);await Le(r),await Le(ee(r,"backups")),await Ss(ee(r,Te),0).catch(()=>{});let a=js.safeParse({kind:"head",version:1,rewindId:s,checkpointId:e.checkpointId,organizationId:e.organizationId,startedAt:i.startedAt,userId:i.userId,...i.automatedProcessUserId!==void 0?{automatedProcessUserId:i.automatedProcessUserId}:{},backup:Xn(s),at:t().toISOString()});if(!a.success)throw new H("invalid",`Not a rewind to journal: ${a.error.message}`);let o=await lt.opened(r,a.data,!1,0,t);try{await o.append(a.data),await Et(r),await Et(e.rewindsDir)}catch(d){throw await o.close(),d}return o}async function Ts(i,e,t,n=()=>new Date){Bs(t,i);let s=await We(i,e);if(!s)throw new H("notFound","No journal of this rewind is kept.");return Cs(s,n)}async function Es(i,e,t){let n=await i.checkpointsOf(e.organizationId),s=Fn(n),r=[],a=[...n].sort((o,d)=>o.folder.checkpointId<d.folder.checkpointId?-1:1);for(let{folder:o,checkpoint:d}of a){if(d===void 0)continue;let c;try{c=(await Rs(o.rewindsDir,{withFileTypes:!0})).filter(f=>f.isDirectory()&&Je.safeParse(f.name).success).map(f=>f.name).sort()}catch{continue}let p=(f,u)=>u?.checkpointId===o.checkpointId&&u.rewindId===f;for(let f of c){if(p(f,t)||p(f,s))continue;let u=await We(o,f).catch(()=>{});u===void 0||u.facts.endedAt===void 0&&u.facts.undos.length===0||(await vs(je(o,f),{recursive:!0,force:!0}),r.push({checkpointId:o.checkpointId,name:d.name,rewindId:f}))}}return r}var Mt=class i{constructor(e,t,n){this.dir=e;this.objects=t;this.keys=n}dir;objects;keys;get count(){return this.objects.reduce((e,t)=>e+t.count,0)}static async written(e,t){await Le(e);let n=new E,s=new Map,r=new Map,a=async o=>{let d=r.get(o)??[];d.length!==0&&(await Ut(ms(e,o),d.join("")),r.set(o,[]))};await t(async(o,{id:d,parent:c})=>{if(!n.add(d))return;s.set(o,(s.get(o)??0)+1);let p=r.get(o)??[];p.push(`${d} ${c}
10
10
  `),r.set(o,p),p.length>=J&&await a(o)});for(let o of s.keys())await a(o);return new i(e,[...s].map(([o,d])=>({objectApiName:o,count:d})),n)}async*pages(e,t=J){if(!this.objects.some(a=>a.objectApiName===e))return;let n=bs(ms(this.dir,e),{encoding:"utf8"}),s=Os({input:n,crlfDelay:1/0}),r=[];try{for await(let a of s){let[o,d]=a.split(" ");o===void 0||d===void 0||(r.push({id:o,parent:d}),r.length>=t&&(yield r,r=[]))}}finally{s.close(),n.destroy()}r.length>0&&(yield r)}};function ms(i,e){return ee(i,`${nn(e)}.pairs`)}async function Ft(i,e,t){return e.length>0&&(await Le(Is(i)),await Ut(i,e.map(n=>`${JSON.stringify(n)}