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{a as P}from"./chunk-ICIYL45C.mjs";import{d as J}from"./chunk-ZUA5BNAO.mjs";import{d as Z}from"./chunk-HFSBDM7B.mjs";import{c as H,g as Y}from"./chunk-OHEOJISY.mjs";import{a as F}from"./chunk-EADHKH3A.mjs";import{g as W,t as Q}from"./chunk-55LQD3Y3.mjs";import{a as U,f as D,h as k}from"./chunk-TZE3Y7IQ.mjs";import{O as z,Q as B,T as V,vc as R}from"./chunk-DPYTG6DM.mjs";import{b as I,k as G,l as A,v as K,z as _}from"./chunk-WZQEK4WT.mjs";function Le(e){let n=new Set;for(let t of e)t.controllerName&&n.add(t.controllerName);return n}function X(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function je(e,n){let t=X(e.precision),r=typeof e.scale=="number"&&e.scale>=0?e.scale:void 0,o=X(e.digits),s=(e.picklistValues??[]).filter(d=>d!==null&&typeof d.value=="string"),i={};if(e.controllerName)for(let d of s)d.active===!1||typeof d.validFor!="string"||(i[d.value]=d.validFor);return{...t!==void 0?{precision:t}:{},...t!==void 0&&r!==void 0?{scale:r}:{},...o!==void 0?{digits:o}:{},...e.unique===!0?{unique:!0}:{},...e.unique===!0&&typeof e.caseSensitive=="boolean"?{caseSensitive:e.caseSensitive}:{},...e.calculated===!0?{calculated:!0}:{},...e.filteredLookupInfo?{filteredLookup:!0}:{},...Object.keys(i).length>0?{validFor:i}:{},...n.has(e.name)&&s.length>0?{controllingValues:s.map(d=>d.value)}:{}}}function Ce(e,n){return e.caseSensitive===!1?n.toLowerCase():n}function M(e,n){if(n<0)return!1;let r=Buffer.from(e,"base64")[n>>3];return r!==void 0&&(r&128>>n%8)!==0}var ie={picklist_value_refused:["map_value","leave_empty","skip_rows","exclude_object","ignore"],dependent_value_invalid:["map_value","leave_empty","exclude_object","ignore"],picklist_value_absent:["map_value","skip_rows","ignore"],required_field_missing:["set_default","exclude_object","ignore"],value_too_long:["truncate","exclude_object","ignore"],number_out_of_range:["exclude_object","ignore"],record_type_unmapped:["map_record_type","exclude_object","ignore"],record_type_unavailable:["map_record_type","exclude_object","ignore"],currency_inactive:["map_value","skip_rows","exclude_object","ignore"],unique_value_collision:["exclude_object","ignore"]};function w(e){return[...ie[e]??["ignore"]]}var se=100,ae=new Set(["longest","colliding"]),O=class{gaps=new Map;recordTypes=new Map;get size(){return this.gaps.size}knowRecordTypes(n,t,r){let o=de(r);o!==void 0&&this.recordTypes.set(n,{...this.recordTypes.get(n),[t]:o})}add(n){let t=z(n.kind,n.objectApiName,n.field,n.recordType,n.value),r=this.gaps.get(t);if(!r){this.gaps.set(t,{...n,id:t,source:"simulation",decisions:[...n.decisions]});return}r.rows+=n.rows,n.decisions.includes("skip_rows")||(r.decisions=r.decisions.filter(s=>s!=="skip_rows"));let o={...n.detail??{},...r.detail??{}};for(let s of ae){let i=r.detail?.[s],d=n.detail?.[s];typeof i=="number"&&typeof d=="number"&&(o[s]=Math.max(i,d))}r.detail=o}list(n){let t=[...this.gaps.keys()],r=[...this.gaps.values()].map(o=>this.withSameDeveloperName(o)).map(o=>B(n,o,t)!==void 0?{...o,detail:{...o.detail??{},ignored:!0}}:o);return V(r)}withSameDeveloperName(n){let t=n.kind==="record_type_unmapped";return le(n,this.recordTypes.get(n.objectApiName)?.[t?"source":"target"])}};function de(e){let n=e.filter(t=>!t.master);if(!n.some(t=>t.namespacePrefix===void 0))return n.map(Z)}function le(e,n){let t=e.kind==="record_type_unmapped"?e.value:e.recordType;if(t===void 0||n===void 0)return e;let r=Y(t);if(!r.namespacePrefix)return e;let o=n.filter(s=>s.developerName===r.developerName&&s.namespacePrefix!==r.namespacePrefix).map(s=>H(s.namespacePrefix,s.developerName));return o.length===0?e:{...e,detail:{...e.detail??{},sameDeveloperName:[...new Set(o)].sort()}}}function L(e){return[...new Set(e)].sort().slice(0,se)}function We(e,n,t){let r=[];for(let o of n){if(o.field===P)continue;let s=t(o);for(let i of o.values)r.push({kind:"picklist_value_refused",severity:"warning",objectApiName:e,field:o.field,...o.recordType!==void 0?{recordType:o.recordType}:{},value:i,rows:1,detail:{reason:o.reason,...s?{allowed:L(s)}:{},...o.controllingField?{controllingField:o.controllingField}:{},...o.replacedBy!==void 0?{replacement:o.replacedBy}:{}},decisions:w("picklist_value_refused").filter(d=>d!=="skip_rows"||o.reason!=="controlling-value"),defaultDecision:o.replacedBy!==void 0?"map_value":"leave_empty"})}return r}var ce=new Set(["string","textarea","email","phone","url","encryptedstring"]),ue=new Set(["double","currency","percent"]);function fe(e){return e==null||e===""}function ne(e){return e.createable&&e.nillable===!1&&e.defaultedOnCreate!==!0&&e.calculated!==!0&&e.type!=="boolean"}function pe(e,n,t){return e==="Account"&&n==="Name"&&Q(t)}function ge(e,n,t,r){return r.filter(o=>ne(o)&&fe(n[o.name])&&!pe(e,o.name,t))}function me(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||e.trim()==="")return;let n=Number(e);return Number.isFinite(n)?n:void 0}function ee(e){if(e.type==="int"&&e.digits!==void 0)return e.digits;if(e.precision!==void 0)return e.precision-(e.scale??0)}function ye(e,n){return e?e.type==="boolean"?n===!0||n==="true"?1:n===!1||n==="false"?0:-1:typeof n!="string"||n===""?-1:(e.controllingValues??[]).indexOf(n):-1}function te(e,n){let{objectApiName:t,rows:r,targetFields:o,picklistValuesByField:s,picklistFields:i}=e,d=new Map(o.map(u=>[u.name,u])),f=o.filter(ne),y=o.filter(u=>u.createable&&ce.has(u.type??"")&&(u.length??0)>0),g=o.filter(u=>u.createable&&(ue.has(u.type??"")||u.type==="int")&&ee(u)!==void 0),c=[...i].filter(([u,l])=>l.anyValue===!0&&s?.has(u)===!0),p=o.filter(u=>u.createable&&u.controllerName!==void 0&&u.validFor!==void 0);for(let{payload:u,source:l,typed:m}of r){for(let a of ge(t,u,l,f))n.add({kind:"required_field_missing",severity:"blocking",objectApiName:t,field:a.name,rows:1,...a.type?{detail:{type:a.type}}:{},decisions:w("required_field_missing")});for(let a of y){let h=u[a.name],b=a.length??0;typeof h!="string"||h.length<=b||n.add({kind:"value_too_long",severity:"blocking",objectApiName:t,field:a.name,rows:1,detail:{length:b,longest:h.length},decisions:w("value_too_long")})}for(let a of g){let h=me(u[a.name]),b=ee(a);h===void 0||b===void 0||Math.abs(Math.trunc(h))<10**b||n.add({kind:"number_out_of_range",severity:"blocking",objectApiName:t,field:a.name,rows:1,detail:{...a.precision!==void 0?{precision:a.precision}:{},...a.scale!==void 0?{scale:a.scale}:{},...a.type==="int"&&a.digits!==void 0?{digits:a.digits}:{}},decisions:w("number_out_of_range")})}for(let[a,h]of c){let b=u[a];if(typeof b!="string"||b==="")continue;let x=s?.get(a),v=h.multi?b.split(";"):[b];for(let E of new Set(v))x?.has(E)||n.add({kind:"picklist_value_absent",severity:"info",objectApiName:t,field:a,value:E,rows:1,decisions:w("picklist_value_absent")})}if(!m)for(let a of p){let h=u[a.name];if(typeof h!="string"||h==="")continue;let b=d.get(a.controllerName??""),x=ye(b,u[a.controllerName??""]),v=i.get(a.name)?.restricted===!0,E=i.get(a.name)?.multi?h.split(";"):[h];for(let q of new Set(E)){let $=a.validFor?.[q];$!==void 0&&(x>=0&&M($,x)||n.add({kind:"dependent_value_invalid",severity:v?"blocking":"warning",objectApiName:t,field:a.name,value:q,rows:1,detail:{controllingField:a.controllerName??"",allowed:L((b?.controllingValues??[]).filter((Me,oe)=>M($,oe)))},decisions:w("dependent_value_invalid")}))}}}}function Qe(e,n,t,r){return{kind:"currency_inactive",severity:"warning",objectApiName:e,field:P,value:n,rows:t,...r&&r.to.length>0?{detail:{replacement:r.to.join(", "),...r.converted.length>0?{amountsConverted:[...r.converted]}:{},...r.asRead?{amountsAsRead:!0}:{}}}:{},decisions:w("currency_inactive"),defaultDecision:"map_value"}}function He(e,n,t,r){return{kind:"unique_value_collision",severity:"warning",objectApiName:e,field:n,rows:t,detail:{colliding:r,linkedToTheRecordItNames:!0},decisions:w("unique_value_collision"),defaultDecision:"ignore"}}function Ye(e,n,t,r,o){return{kind:e,severity:"blocking",objectApiName:n,field:"RecordTypeId",...e==="record_type_unavailable"?{recordType:t}:{value:t},rows:r,detail:{mapTo:L(o)},decisions:w(e)}}var he=10;function re(e){switch(e.operation){case"insert":return null;case"upsert":return e.externalIdField??"Id";case"update":case"delete":return"Id"}}function S(e){if(e==null||typeof e!="string"&&typeof e!="number"&&typeof e!="boolean")return null;let n=String(e);return n===""?null:n.toLowerCase()}function T(e){return typeof e=="number"&&Number.isFinite(e)?String(e):typeof e=="boolean"?e?"true":"false":`'${U(String(e))}'`}var be=200,Se=4e3;function N(e){let n=[],t=[],r=0;for(let o of e){let s=T(o).length+2;t.length>0&&(t.length>=be||r+s>Se)&&(n.push(t),t=[],r=0),t.push(o),r+=s}return t.length>0&&n.push(t),n}function rn(e,n){return async(t,r,o,s)=>{let i=R(r.objectApiName),d=k(o),f=new Map;for(let y of N(s)){if(n?.aborted)throw new Error("The simulation was cancelled.");let{records:g}=await F(e,`SELECT ${d} FROM ${i} WHERE ${d} IN (${y.map(T).join(", ")})`);for(let c of g){let p=S(c[d]);p!==null&&f.set(p,(f.get(p)??0)+1)}}return f}}var we=new Set(["attributes","Id"]);function Re(e,n,t,r){return n?e.conflictFields.filter(o=>o!==t&&!we.has(o)&&o in n&&(r===null||r.has(o))):[]}var on=new Set(["noKey","notInTarget","ambiguous"]);function _e(e,n,t){let r=e.operation,o=re(e);if(o===null)return"insert";let s=S(n[o]);if(s===null)return r==="delete"?"notSent":"noKey";let i=t.get(s)??0;return r==="upsert"?i===0?o.toLowerCase()==="id"?"notInTarget":"insert":i===1?"update":"ambiguous":i===0?"notInTarget":r==="update"?"update":"delete"}var ke=1e4;function sn(e,n,t){let r=e>t?ke:Math.max(1,n);return{callOf:o=>Math.floor(o/r),job:e>t}}function an(e,n,t,r){let o=new Map;n.forEach((c,p)=>{if(c===null)return;let u=`${r.callOf(p)}\0${c}`,l=o.get(u);l?l.push(p):o.set(u,[p])});let s=new Set;for(let c of o.values())if(c.length>1)for(let p of c)s.add(p);let i=new Map,d=new Set,f=0;n.forEach((c,p)=>{if(c===null||s.has(p))return;let u=r.callOf(p);if(i.get(c)===void 0){t[p]==="insert"&&i.set(c,u);return}r.job?f++:t[p]==="insert"&&d.add(p)});let y=[],g=[];if(s.size>0){let c=`${s.size} record(s) carry the ${e} of another record of the same call: an upsert finds its record by its key, and the target refuses every record of a call whose key another carries (DUPLICATE_VALUE: Duplicate external id specified).`;y.push(c),g.push({code:"DUPLICATE_VALUE",rows:s.size,note:c})}return d.size>0&&y.push(`${d.size} record(s) carry the ${e} of a record sent in an earlier call: the upsert finds the record that one created and updates it with theirs.`),f>0&&y.push(`${f} record(s) carry the ${e} of a record in another batch of the Bulk API job: the platform may write the batches at once, so whether each updates the record the other created or creates one of its own cannot be told before the run.`),{refused:s,updated:d,notes:y,refusedFor:g}}function dn(e){let{objectConfig:n,records:t,inTarget:r}=e,o=n.operation,s=re(n),i={insert:0,update:0,delete:0,noKey:0,notInTarget:0,notSent:0,ambiguous:0},d=new Set;t.forEach((l,m)=>{let a=e.simulated?.[m]??_e(n,l,r);i[a]++,(a==="insert"||a==="update")&&d.add(m)});let f=e.leftOut.map(({why:l,count:m})=>W(m,l));i.noKey>0&&f.push(o==="upsert"?`${i.noKey} record(s) carry no value in ${s}: an upsert matches on it, and the target refuses a record without one.`:`${i.noKey} record(s) carry no Id: an update finds its record by Id, and the target refuses one without it.`),i.notInTarget>0&&f.push(`${i.notInTarget} record(s) carry an Id the target does not hold: ${o==="upsert"?"an upsert on the Id finds no record there and creates none":`${o==="update"?"an update":"a delete"} finds no record there`}, and the target refuses it. Two orgs share a record's Id only when it was copied with the org.`),i.ambiguous>0&&f.push(`${i.ambiguous} record(s) match more than one record of the target on ${s}: an upsert finds no single record to update, and the target refuses it.`),i.notSent>0&&f.push(`${i.notSent} record(s) carry no Id: a delete sends ids alone, so the run leaves them out.`);let y=new Map;e.unsettled.forEach((l,m)=>{let a=String(l[e.matchField]??"");a&&d.has(m)&&y.set(a,l)});let g=new Map,c=0;for(let l of e.conflicts){let m=Re(l,y.get(l.recordId),e.matchField,e.writable);if(m.length!==0){c++;for(let a of m)g.set(a,(g.get(a)??0)+1)}}let p=[...g].sort(([l,m],[a,h])=>h-m||l.localeCompare(a)).slice(0,he).map(([l])=>l),u=e.leftOut.reduce((l,{count:m})=>l+m,0);return{objectApiName:n.objectApiName,operation:o,read:e.read,insert:i.insert,update:i.update,delete:i.delete,skipped:u+i.notSent,refused:i.noKey+i.notInTarget+i.ambiguous,conflicts:c,conflictFields:p,notes:f}}var Fe={required_field_missing:"REQUIRED_FIELD_MISSING",value_too_long:"STRING_TOO_LONG",number_out_of_range:"NUMBER_OUTSIDE_VALID_RANGE"};function Ie(e){let n=e.field??"";switch(e.kind){case"required_field_missing":return`${e.rows} record(s) leave ${n} empty, which the target requires: it refuses them (REQUIRED_FIELD_MISSING).`;case"value_too_long":return`${e.rows} record(s) hold a ${n} longer than the ${String(e.detail?.length)} characters the target's field takes (the longest, ${String(e.detail?.longest)}): it refuses them (STRING_TOO_LONG).`;case"number_out_of_range":return`${e.rows} record(s) hold a ${n} larger than the target's field takes: it refuses them (NUMBER_OUTSIDE_VALID_RANGE).`;default:return}}function ln(e,n,t){let r=new Set,o=new O;n.forEach(({payload:i,source:d,creates:f},y)=>{let g=new O;te({objectApiName:e,rows:[{payload:i,source:d,typed:!0}],targetFields:t,picklistValuesByField:null,picklistFields:new Map},g);let c=g.list(new Set).filter(p=>p.severity==="blocking"&&(f||p.kind!=="required_field_missing"));if(c.length!==0){r.add(y);for(let p of c)o.add(p)}});let s=o.list(new Set).flatMap(i=>{let d=Ie(i),f=Fe[i.kind];return d&&f?[{code:f,rows:i.rows,note:d}]:[]});return{refused:r,notes:s.map(({note:i})=>i),refusedFor:s}}function cn(e,n){let t=new Set,r=new Set,o=[],s=[];for(let[i,d]of n){let f=new Set,y=0,g=0,c=0;if(e.forEach((u,l)=>{let m=S(u[i]);if(m===null)return;let a=d.get(m)??0;a===1?(y++,r.add(l)):a>1?(g++,t.add(l)):f.has(m)&&(c++,t.add(l)),f.add(m)}),y>0&&o.push(`LINKED_TO_EXISTING: ${y} record(s) hold a ${i} the target keeps unique, which a record of the target holds already: it refuses them as duplicates (DUPLICATE_VALUE) and names that record, which the run links them to \u2014 what it writes under them points at that record.`),g+c===0)continue;let p=`${g+c} record(s) hold a ${i} the target keeps unique, which `+[g>0?`several records of the target hold already (${g})`:"",c>0?`a record sent before them holds (${c})`:""].filter(Boolean).join(" or ")+": it refuses them (DUPLICATE_VALUE).";o.push(p),s.push({code:"DUPLICATE_VALUE",rows:g+c,note:p})}for(let i of t)r.delete(i);return{refused:t,linked:r,notes:o,refusedFor:s}}import{createHash as Oe}from"node:crypto";var Te=5*6e4,xe=500,Ee=A({sourceOrgId:I().min(1).max(200),targetOrgId:I().min(1).max(200),objectApiName:I().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),watermark:_.datetime(),fingerprint:I().regex(/^[0-9a-f]{64}$/),recordedAt:_.datetime(),filesSeen:_.datetime().optional(),removedAt:_.datetime().optional()}),Ne=A({version:K(1),entries:G(Ee).max(xe),resetAt:_.datetime().optional()});function Sn(e){if(e==null)return{kind:"none"};let n=Ne.safeParse(e);if(n.success)return{kind:"stored",state:n.data};let t=n.error.issues[0];return{kind:"unreadable",issue:`${t.path.join(".")||"state"}: ${t.message}`}}function j(e){return Array.isArray(e)?`[${e.map(j).join(",")}]`:e!==null&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>`${JSON.stringify(t)}:${j(r)}`).join(",")}}`:JSON.stringify(e)}function C(e){let n=e?.trim();return n||null}function ve(e,n){let t={direction:e.direction,conflictStrategy:e.conflictStrategy,copiesFiles:e.files?!0:void 0,objectApiName:n.objectApiName,operation:n.operation,externalIdField:C(n.externalIdField),where:C(n.where),fieldMappings:n.fieldMappings??[],unmappedSentAsRead:(n.fieldMappings??[]).length>0?!0:void 0,transformRules:n.transformRules??[],excludedFields:n.excludedFields??[],addOnFields:n.addOnFields??[]};return Oe("sha256").update(j(t)).digest("hex")}function wn(e,n,t){let r=ve(e,n);if(t===null)return{read:"full",reason:"not_saved",fingerprint:r};if(t.kind==="unreadable")return{read:"full",reason:"unreadable",fingerprint:r};if(t.kind==="none")return{read:"full",reason:"first_run",fingerprint:r};let o=t.state.entries.find(s=>s.sourceOrgId===e.sourceOrgId&&s.targetOrgId===e.targetOrgId&&s.objectApiName===n.objectApiName);return o?o.fingerprint!==r?{read:"full",reason:"scope_changed",fingerprint:r}:o.removedAt!==void 0?{read:"full",reason:"removed",fingerprint:r}:{read:"delta",since:o.watermark,fingerprint:r,...o.filesSeen!==void 0?{filesSeen:o.filesSeen}:{}}:{read:"full",reason:t.state.resetAt?"reset":"first_run",fingerprint:r}}var $e=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;function Rn(e,n=Te){let t=Date.parse(e);if(!Number.isFinite(t))throw new Error(`Not a watermark: "${e}".`);let r=Math.floor((t-n)/1e3)*1e3;return new Date(r).toISOString().replace(/\.\d{3}Z$/,"Z")}function _n(e){let n=Date.parse(e);if(!Number.isFinite(n))throw new Error(`Not a date: "${e}".`);return new Date(Math.floor(n/1e3)*1e3).toISOString().replace(/\.\d{3}Z$/,"Z")}function Ae(e){if(!$e.test(e)||!Number.isFinite(Date.parse(e)))throw new Error(`Not a SOQL datetime: "${e}".`);return e}function kn(e,n){let t=e?.trim()?D(e):void 0;if(n===void 0)return t;let r=`SystemModstamp > ${Ae(n)}`;return t?`${r} AND (${t})`:r}function De(e){if(typeof e!="string"||e==="")return null;let n=Date.parse(e.replace(/([+-]\d{2})(\d{2})$/,"$1:$2"));return Number.isFinite(n)?new Date(n).toISOString():null}function Fn(e,n,t){let r={query:i=>e.query(i),queryMore:i=>e.queryMore(i)},o={query:i=>e.query(i,{scanAll:!0}),queryMore:i=>e.queryMore(i)},s=()=>{if(t?.aborted)throw new Error("The run was cancelled.")};return{async latestModstamp(i){let d=R(i),y=(await e.query(`SELECT SystemModstamp FROM ${d} ORDER BY SystemModstamp DESC LIMIT 1`)).records[0];if(!y)return null;let g=De(y.SystemModstamp);if(g===null)throw new Error(`${d} answered a SystemModstamp that is not a date.`);return g},async deletedRows(i,d,f){let y=R(i),g=new Set(["Id","SystemModstamp",...d.map(k)]),{records:c,truncated:p}=await F(o,`SELECT ${[...g].join(", ")} FROM ${y} WHERE IsDeleted = true AND (${D(f)})`);return{records:c,truncated:p}},async heldInSource(i,d,f){let y=R(i),g=k(d),c=new Set;for(let p of N(f)){s();let{records:u}=await F(r,`SELECT ${g} FROM ${y} WHERE ${g} IN (${p.map(T).join(", ")})`);for(let l of u){let m=S(l[g]);m!==null&&c.add(m)}}return c},async targetIdsByKey(i,d,f){let y=R(i),g=k(d),c=g==="Id"?"Id":`Id, ${g}`,p=new Map;for(let u of N(f)){s();let{records:l}=await F(n,`SELECT ${c} FROM ${y} WHERE ${g} IN (${u.map(T).join(", ")})`);for(let m of l){let a=S(m[g]);a===null||typeof m.Id!="string"||p.set(a,[...p.get(a)??[],m.Id])}}return p}}}var Pe=new Set(["direct","rename","transform"]);function In(e){let n=e.objectApiName;if(e.operation==="insert"||e.operation==="delete")return{refused:`${n} is written by ${e.operation}, which finds no record by a key: a deleted source record cannot be tied to a target record.`};if(e.operation==="update")return{sourceField:"Id",keyField:"Id"};let t=C(e.externalIdField)??"Id";if((e.addOnFields??[]).some(s=>s.fieldApiName===t))return{refused:`${n}: an add-on writes ${t}, the key the upsert matches on, so it ties no deleted source record to one target record.`};let r=e.fieldMappings??[],o=r.find(s=>s.targetField.toLowerCase()===t.toLowerCase());return!o&&!J(r,e.excludedFields??[]).has(t.toLowerCase())?{sourceField:t,keyField:t}:!o||!Pe.has(o.type)?{refused:`${n}: no source field is carried onto ${t}, the key the upsert matches on, so no deleted source record can be tied to a target record.`}:{sourceField:o.sourceField,keyField:t}}async function On(e,n,t,r,o){let s=n.objectApiName,{records:i,truncated:d}=await e.deletedRows(s,[t.sourceField],r),f={ids:[],read:i.length,stillInSource:0,ambiguous:0,noKey:0,truncated:d};if(i.length===0)return f;let y=[];for(let l of i){let m=l[t.sourceField],a=o(l);if(S(m)===null||S(a)===null){f.noKey++;continue}y.push({raw:m,key:a})}if(y.length===0)return f;let g=t.sourceField==="Id"?new Set:await e.heldInSource(s,t.sourceField,y.map(l=>l.raw)),c=y.filter(l=>g.has(S(l.raw))?(f.stillInSource++,!1):!0);if(c.length===0)return f;let p=await e.targetIdsByKey(s,t.keyField,c.map(l=>l.key)),u=new Set;for(let l of c){let m=p.get(S(l.key))??[];m.length>1?f.ambiguous++:m.length===1&&!u.has(m[0])&&(u.add(m[0]),f.ids.push(m[0]))}return f}function Tn(e,n){let t=[];return e.stillInSource>0&&t.push(`${e.stillInSource} record(s) deleted in the source share their ${n} with a record the source still holds: their target record was kept.`),e.ambiguous>0&&t.push(`${e.ambiguous} record(s) deleted in the source match more than one target record on ${n}: none of those target records was deleted.`),e.noKey>0&&t.push(`${e.noKey} record(s) deleted in the source carry no ${n}: no target record is tied to them.`),e.truncated&&t.push("The source's deleted records were read up to a bound: the rest are read by the next run, from the same watermark."),t}function xn(e,n,t,r,o=0){return{read:e.read,...e.read==="delta"?{since:e.since}:{reason:e.reason},changed:n,deletionsChecked:t!==void 0,deleted:t?.deleted??0,deleteFailed:t?.deleteFailed??0,...t?.error!==void 0?{deletionError:t.error}:{},...r!==void 0?{recorded:r}:{},...o>0?{lookupsOwed:o}:{}}}export{Le as a,je as b,Ce as c,ie as d,O as e,de as f,le as g,We as h,ge as i,te as j,Qe as k,He as l,Ye as m,re as n,S as o,rn as p,on as q,_e as r,sn as s,an as t,dn as u,ln as v,cn as w,Te as x,Sn as y,wn as z,Rn as A,_n as B,Ae as C,kn as D,De as E,Fn as F,In as G,On as H,Tn as I,xn as J};
7
+ import{d as Z}from"./chunk-HFSBDM7B.mjs";import{c as H,g as Y}from"./chunk-OHEOJISY.mjs";import{a as F}from"./chunk-EADHKH3A.mjs";import{g as W,t as Q}from"./chunk-KIMQQ6JQ.mjs";import{a as U,f as D,h as k}from"./chunk-TZE3Y7IQ.mjs";import{a as P}from"./chunk-ICIYL45C.mjs";import{d as J}from"./chunk-PR74GYVI.mjs";import{Hc as R,O as z,Q as B,T as V}from"./chunk-ZQO5PDX5.mjs";import{b as I,k as G,l as A,v as K,z as _}from"./chunk-WZQEK4WT.mjs";function Le(e){let n=new Set;for(let t of e)t.controllerName&&n.add(t.controllerName);return n}function X(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function je(e,n){let t=X(e.precision),r=typeof e.scale=="number"&&e.scale>=0?e.scale:void 0,o=X(e.digits),s=(e.picklistValues??[]).filter(d=>d!==null&&typeof d.value=="string"),i={};if(e.controllerName)for(let d of s)d.active===!1||typeof d.validFor!="string"||(i[d.value]=d.validFor);return{...t!==void 0?{precision:t}:{},...t!==void 0&&r!==void 0?{scale:r}:{},...o!==void 0?{digits:o}:{},...e.unique===!0?{unique:!0}:{},...e.unique===!0&&typeof e.caseSensitive=="boolean"?{caseSensitive:e.caseSensitive}:{},...e.calculated===!0?{calculated:!0}:{},...e.filteredLookupInfo?{filteredLookup:!0}:{},...Object.keys(i).length>0?{validFor:i}:{},...n.has(e.name)&&s.length>0?{controllingValues:s.map(d=>d.value)}:{}}}function Ce(e,n){return e.caseSensitive===!1?n.toLowerCase():n}function M(e,n){if(n<0)return!1;let r=Buffer.from(e,"base64")[n>>3];return r!==void 0&&(r&128>>n%8)!==0}var ie={picklist_value_refused:["map_value","leave_empty","skip_rows","exclude_object","ignore"],dependent_value_invalid:["map_value","leave_empty","exclude_object","ignore"],picklist_value_absent:["map_value","skip_rows","ignore"],required_field_missing:["set_default","exclude_object","ignore"],value_too_long:["truncate","exclude_object","ignore"],number_out_of_range:["exclude_object","ignore"],record_type_unmapped:["map_record_type","exclude_object","ignore"],record_type_unavailable:["map_record_type","exclude_object","ignore"],currency_inactive:["map_value","skip_rows","exclude_object","ignore"],unique_value_collision:["exclude_object","ignore"]};function w(e){return[...ie[e]??["ignore"]]}var se=100,ae=new Set(["longest","colliding"]),O=class{gaps=new Map;recordTypes=new Map;get size(){return this.gaps.size}knowRecordTypes(n,t,r){let o=de(r);o!==void 0&&this.recordTypes.set(n,{...this.recordTypes.get(n),[t]:o})}add(n){let t=z(n.kind,n.objectApiName,n.field,n.recordType,n.value),r=this.gaps.get(t);if(!r){this.gaps.set(t,{...n,id:t,source:"simulation",decisions:[...n.decisions]});return}r.rows+=n.rows,n.decisions.includes("skip_rows")||(r.decisions=r.decisions.filter(s=>s!=="skip_rows"));let o={...n.detail??{},...r.detail??{}};for(let s of ae){let i=r.detail?.[s],d=n.detail?.[s];typeof i=="number"&&typeof d=="number"&&(o[s]=Math.max(i,d))}r.detail=o}list(n){let t=[...this.gaps.keys()],r=[...this.gaps.values()].map(o=>this.withSameDeveloperName(o)).map(o=>B(n,o,t)!==void 0?{...o,detail:{...o.detail??{},ignored:!0}}:o);return V(r)}withSameDeveloperName(n){let t=n.kind==="record_type_unmapped";return le(n,this.recordTypes.get(n.objectApiName)?.[t?"source":"target"])}};function de(e){let n=e.filter(t=>!t.master);if(!n.some(t=>t.namespacePrefix===void 0))return n.map(Z)}function le(e,n){let t=e.kind==="record_type_unmapped"?e.value:e.recordType;if(t===void 0||n===void 0)return e;let r=Y(t);if(!r.namespacePrefix)return e;let o=n.filter(s=>s.developerName===r.developerName&&s.namespacePrefix!==r.namespacePrefix).map(s=>H(s.namespacePrefix,s.developerName));return o.length===0?e:{...e,detail:{...e.detail??{},sameDeveloperName:[...new Set(o)].sort()}}}function L(e){return[...new Set(e)].sort().slice(0,se)}function We(e,n,t){let r=[];for(let o of n){if(o.field===P)continue;let s=t(o);for(let i of o.values)r.push({kind:"picklist_value_refused",severity:"warning",objectApiName:e,field:o.field,...o.recordType!==void 0?{recordType:o.recordType}:{},value:i,rows:1,detail:{reason:o.reason,...s?{allowed:L(s)}:{},...o.controllingField?{controllingField:o.controllingField}:{},...o.replacedBy!==void 0?{replacement:o.replacedBy}:{}},decisions:w("picklist_value_refused").filter(d=>d!=="skip_rows"||o.reason!=="controlling-value"),defaultDecision:o.replacedBy!==void 0?"map_value":"leave_empty"})}return r}var ce=new Set(["string","textarea","email","phone","url","encryptedstring"]),ue=new Set(["double","currency","percent"]);function fe(e){return e==null||e===""}function ne(e){return e.createable&&e.nillable===!1&&e.defaultedOnCreate!==!0&&e.calculated!==!0&&e.type!=="boolean"}function pe(e,n,t){return e==="Account"&&n==="Name"&&Q(t)}function ge(e,n,t,r){return r.filter(o=>ne(o)&&fe(n[o.name])&&!pe(e,o.name,t))}function me(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e!="string"||e.trim()==="")return;let n=Number(e);return Number.isFinite(n)?n:void 0}function ee(e){if(e.type==="int"&&e.digits!==void 0)return e.digits;if(e.precision!==void 0)return e.precision-(e.scale??0)}function ye(e,n){return e?e.type==="boolean"?n===!0||n==="true"?1:n===!1||n==="false"?0:-1:typeof n!="string"||n===""?-1:(e.controllingValues??[]).indexOf(n):-1}function te(e,n){let{objectApiName:t,rows:r,targetFields:o,picklistValuesByField:s,picklistFields:i}=e,d=new Map(o.map(u=>[u.name,u])),f=o.filter(ne),y=o.filter(u=>u.createable&&ce.has(u.type??"")&&(u.length??0)>0),g=o.filter(u=>u.createable&&(ue.has(u.type??"")||u.type==="int")&&ee(u)!==void 0),c=[...i].filter(([u,l])=>l.anyValue===!0&&s?.has(u)===!0),p=o.filter(u=>u.createable&&u.controllerName!==void 0&&u.validFor!==void 0);for(let{payload:u,source:l,typed:m}of r){for(let a of ge(t,u,l,f))n.add({kind:"required_field_missing",severity:"blocking",objectApiName:t,field:a.name,rows:1,...a.type?{detail:{type:a.type}}:{},decisions:w("required_field_missing")});for(let a of y){let h=u[a.name],b=a.length??0;typeof h!="string"||h.length<=b||n.add({kind:"value_too_long",severity:"blocking",objectApiName:t,field:a.name,rows:1,detail:{length:b,longest:h.length},decisions:w("value_too_long")})}for(let a of g){let h=me(u[a.name]),b=ee(a);h===void 0||b===void 0||Math.abs(Math.trunc(h))<10**b||n.add({kind:"number_out_of_range",severity:"blocking",objectApiName:t,field:a.name,rows:1,detail:{...a.precision!==void 0?{precision:a.precision}:{},...a.scale!==void 0?{scale:a.scale}:{},...a.type==="int"&&a.digits!==void 0?{digits:a.digits}:{}},decisions:w("number_out_of_range")})}for(let[a,h]of c){let b=u[a];if(typeof b!="string"||b==="")continue;let x=s?.get(a),v=h.multi?b.split(";"):[b];for(let E of new Set(v))x?.has(E)||n.add({kind:"picklist_value_absent",severity:"info",objectApiName:t,field:a,value:E,rows:1,decisions:w("picklist_value_absent")})}if(!m)for(let a of p){let h=u[a.name];if(typeof h!="string"||h==="")continue;let b=d.get(a.controllerName??""),x=ye(b,u[a.controllerName??""]),v=i.get(a.name)?.restricted===!0,E=i.get(a.name)?.multi?h.split(";"):[h];for(let q of new Set(E)){let $=a.validFor?.[q];$!==void 0&&(x>=0&&M($,x)||n.add({kind:"dependent_value_invalid",severity:v?"blocking":"warning",objectApiName:t,field:a.name,value:q,rows:1,detail:{controllingField:a.controllerName??"",allowed:L((b?.controllingValues??[]).filter((Me,oe)=>M($,oe)))},decisions:w("dependent_value_invalid")}))}}}}function Qe(e,n,t,r){return{kind:"currency_inactive",severity:"warning",objectApiName:e,field:P,value:n,rows:t,...r&&r.to.length>0?{detail:{replacement:r.to.join(", "),...r.converted.length>0?{amountsConverted:[...r.converted]}:{},...r.asRead?{amountsAsRead:!0}:{}}}:{},decisions:w("currency_inactive"),defaultDecision:"map_value"}}function He(e,n,t,r){return{kind:"unique_value_collision",severity:"warning",objectApiName:e,field:n,rows:t,detail:{colliding:r,linkedToTheRecordItNames:!0},decisions:w("unique_value_collision"),defaultDecision:"ignore"}}function Ye(e,n,t,r,o){return{kind:e,severity:"blocking",objectApiName:n,field:"RecordTypeId",...e==="record_type_unavailable"?{recordType:t}:{value:t},rows:r,detail:{mapTo:L(o)},decisions:w(e)}}var he=10;function re(e){switch(e.operation){case"insert":return null;case"upsert":return e.externalIdField??"Id";case"update":case"delete":return"Id"}}function S(e){if(e==null||typeof e!="string"&&typeof e!="number"&&typeof e!="boolean")return null;let n=String(e);return n===""?null:n.toLowerCase()}function T(e){return typeof e=="number"&&Number.isFinite(e)?String(e):typeof e=="boolean"?e?"true":"false":`'${U(String(e))}'`}var be=200,Se=4e3;function N(e){let n=[],t=[],r=0;for(let o of e){let s=T(o).length+2;t.length>0&&(t.length>=be||r+s>Se)&&(n.push(t),t=[],r=0),t.push(o),r+=s}return t.length>0&&n.push(t),n}function rn(e,n){return async(t,r,o,s)=>{let i=R(r.objectApiName),d=k(o),f=new Map;for(let y of N(s)){if(n?.aborted)throw new Error("The simulation was cancelled.");let{records:g}=await F(e,`SELECT ${d} FROM ${i} WHERE ${d} IN (${y.map(T).join(", ")})`);for(let c of g){let p=S(c[d]);p!==null&&f.set(p,(f.get(p)??0)+1)}}return f}}var we=new Set(["attributes","Id"]);function Re(e,n,t,r){return n?e.conflictFields.filter(o=>o!==t&&!we.has(o)&&o in n&&(r===null||r.has(o))):[]}var on=new Set(["noKey","notInTarget","ambiguous"]);function _e(e,n,t){let r=e.operation,o=re(e);if(o===null)return"insert";let s=S(n[o]);if(s===null)return r==="delete"?"notSent":"noKey";let i=t.get(s)??0;return r==="upsert"?i===0?o.toLowerCase()==="id"?"notInTarget":"insert":i===1?"update":"ambiguous":i===0?"notInTarget":r==="update"?"update":"delete"}var ke=1e4;function sn(e,n,t){let r=e>t?ke:Math.max(1,n);return{callOf:o=>Math.floor(o/r),job:e>t}}function an(e,n,t,r){let o=new Map;n.forEach((c,p)=>{if(c===null)return;let u=`${r.callOf(p)}\0${c}`,l=o.get(u);l?l.push(p):o.set(u,[p])});let s=new Set;for(let c of o.values())if(c.length>1)for(let p of c)s.add(p);let i=new Map,d=new Set,f=0;n.forEach((c,p)=>{if(c===null||s.has(p))return;let u=r.callOf(p);if(i.get(c)===void 0){t[p]==="insert"&&i.set(c,u);return}r.job?f++:t[p]==="insert"&&d.add(p)});let y=[],g=[];if(s.size>0){let c=`${s.size} record(s) carry the ${e} of another record of the same call: an upsert finds its record by its key, and the target refuses every record of a call whose key another carries (DUPLICATE_VALUE: Duplicate external id specified).`;y.push(c),g.push({code:"DUPLICATE_VALUE",rows:s.size,note:c})}return d.size>0&&y.push(`${d.size} record(s) carry the ${e} of a record sent in an earlier call: the upsert finds the record that one created and updates it with theirs.`),f>0&&y.push(`${f} record(s) carry the ${e} of a record in another batch of the Bulk API job: the platform may write the batches at once, so whether each updates the record the other created or creates one of its own cannot be told before the run.`),{refused:s,updated:d,notes:y,refusedFor:g}}function dn(e){let{objectConfig:n,records:t,inTarget:r}=e,o=n.operation,s=re(n),i={insert:0,update:0,delete:0,noKey:0,notInTarget:0,notSent:0,ambiguous:0},d=new Set;t.forEach((l,m)=>{let a=e.simulated?.[m]??_e(n,l,r);i[a]++,(a==="insert"||a==="update")&&d.add(m)});let f=e.leftOut.map(({why:l,count:m})=>W(m,l));i.noKey>0&&f.push(o==="upsert"?`${i.noKey} record(s) carry no value in ${s}: an upsert matches on it, and the target refuses a record without one.`:`${i.noKey} record(s) carry no Id: an update finds its record by Id, and the target refuses one without it.`),i.notInTarget>0&&f.push(`${i.notInTarget} record(s) carry an Id the target does not hold: ${o==="upsert"?"an upsert on the Id finds no record there and creates none":`${o==="update"?"an update":"a delete"} finds no record there`}, and the target refuses it. Two orgs share a record's Id only when it was copied with the org.`),i.ambiguous>0&&f.push(`${i.ambiguous} record(s) match more than one record of the target on ${s}: an upsert finds no single record to update, and the target refuses it.`),i.notSent>0&&f.push(`${i.notSent} record(s) carry no Id: a delete sends ids alone, so the run leaves them out.`);let y=new Map;e.unsettled.forEach((l,m)=>{let a=String(l[e.matchField]??"");a&&d.has(m)&&y.set(a,l)});let g=new Map,c=0;for(let l of e.conflicts){let m=Re(l,y.get(l.recordId),e.matchField,e.writable);if(m.length!==0){c++;for(let a of m)g.set(a,(g.get(a)??0)+1)}}let p=[...g].sort(([l,m],[a,h])=>h-m||l.localeCompare(a)).slice(0,he).map(([l])=>l),u=e.leftOut.reduce((l,{count:m})=>l+m,0);return{objectApiName:n.objectApiName,operation:o,read:e.read,insert:i.insert,update:i.update,delete:i.delete,skipped:u+i.notSent,refused:i.noKey+i.notInTarget+i.ambiguous,conflicts:c,conflictFields:p,notes:f}}var Fe={required_field_missing:"REQUIRED_FIELD_MISSING",value_too_long:"STRING_TOO_LONG",number_out_of_range:"NUMBER_OUTSIDE_VALID_RANGE"};function Ie(e){let n=e.field??"";switch(e.kind){case"required_field_missing":return`${e.rows} record(s) leave ${n} empty, which the target requires: it refuses them (REQUIRED_FIELD_MISSING).`;case"value_too_long":return`${e.rows} record(s) hold a ${n} longer than the ${String(e.detail?.length)} characters the target's field takes (the longest, ${String(e.detail?.longest)}): it refuses them (STRING_TOO_LONG).`;case"number_out_of_range":return`${e.rows} record(s) hold a ${n} larger than the target's field takes: it refuses them (NUMBER_OUTSIDE_VALID_RANGE).`;default:return}}function ln(e,n,t){let r=new Set,o=new O;n.forEach(({payload:i,source:d,creates:f},y)=>{let g=new O;te({objectApiName:e,rows:[{payload:i,source:d,typed:!0}],targetFields:t,picklistValuesByField:null,picklistFields:new Map},g);let c=g.list(new Set).filter(p=>p.severity==="blocking"&&(f||p.kind!=="required_field_missing"));if(c.length!==0){r.add(y);for(let p of c)o.add(p)}});let s=o.list(new Set).flatMap(i=>{let d=Ie(i),f=Fe[i.kind];return d&&f?[{code:f,rows:i.rows,note:d}]:[]});return{refused:r,notes:s.map(({note:i})=>i),refusedFor:s}}function cn(e,n){let t=new Set,r=new Set,o=[],s=[];for(let[i,d]of n){let f=new Set,y=0,g=0,c=0;if(e.forEach((u,l)=>{let m=S(u[i]);if(m===null)return;let a=d.get(m)??0;a===1?(y++,r.add(l)):a>1?(g++,t.add(l)):f.has(m)&&(c++,t.add(l)),f.add(m)}),y>0&&o.push(`LINKED_TO_EXISTING: ${y} record(s) hold a ${i} the target keeps unique, which a record of the target holds already: it refuses them as duplicates (DUPLICATE_VALUE) and names that record, which the run links them to \u2014 what it writes under them points at that record.`),g+c===0)continue;let p=`${g+c} record(s) hold a ${i} the target keeps unique, which `+[g>0?`several records of the target hold already (${g})`:"",c>0?`a record sent before them holds (${c})`:""].filter(Boolean).join(" or ")+": it refuses them (DUPLICATE_VALUE).";o.push(p),s.push({code:"DUPLICATE_VALUE",rows:g+c,note:p})}for(let i of t)r.delete(i);return{refused:t,linked:r,notes:o,refusedFor:s}}import{createHash as Oe}from"node:crypto";var Te=5*6e4,xe=500,Ee=A({sourceOrgId:I().min(1).max(200),targetOrgId:I().min(1).max(200),objectApiName:I().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),watermark:_.datetime(),fingerprint:I().regex(/^[0-9a-f]{64}$/),recordedAt:_.datetime(),filesSeen:_.datetime().optional(),removedAt:_.datetime().optional()}),Ne=A({version:K(1),entries:G(Ee).max(xe),resetAt:_.datetime().optional()});function Sn(e){if(e==null)return{kind:"none"};let n=Ne.safeParse(e);if(n.success)return{kind:"stored",state:n.data};let t=n.error.issues[0];return{kind:"unreadable",issue:`${t.path.join(".")||"state"}: ${t.message}`}}function j(e){return Array.isArray(e)?`[${e.map(j).join(",")}]`:e!==null&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>`${JSON.stringify(t)}:${j(r)}`).join(",")}}`:JSON.stringify(e)}function C(e){let n=e?.trim();return n||null}function ve(e,n){let t={direction:e.direction,conflictStrategy:e.conflictStrategy,copiesFiles:e.files?!0:void 0,objectApiName:n.objectApiName,operation:n.operation,externalIdField:C(n.externalIdField),where:C(n.where),fieldMappings:n.fieldMappings??[],unmappedSentAsRead:(n.fieldMappings??[]).length>0?!0:void 0,transformRules:n.transformRules??[],excludedFields:n.excludedFields??[],addOnFields:n.addOnFields??[]};return Oe("sha256").update(j(t)).digest("hex")}function wn(e,n,t){let r=ve(e,n);if(t===null)return{read:"full",reason:"not_saved",fingerprint:r};if(t.kind==="unreadable")return{read:"full",reason:"unreadable",fingerprint:r};if(t.kind==="none")return{read:"full",reason:"first_run",fingerprint:r};let o=t.state.entries.find(s=>s.sourceOrgId===e.sourceOrgId&&s.targetOrgId===e.targetOrgId&&s.objectApiName===n.objectApiName);return o?o.fingerprint!==r?{read:"full",reason:"scope_changed",fingerprint:r}:o.removedAt!==void 0?{read:"full",reason:"removed",fingerprint:r}:{read:"delta",since:o.watermark,fingerprint:r,...o.filesSeen!==void 0?{filesSeen:o.filesSeen}:{}}:{read:"full",reason:t.state.resetAt?"reset":"first_run",fingerprint:r}}var $e=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;function Rn(e,n=Te){let t=Date.parse(e);if(!Number.isFinite(t))throw new Error(`Not a watermark: "${e}".`);let r=Math.floor((t-n)/1e3)*1e3;return new Date(r).toISOString().replace(/\.\d{3}Z$/,"Z")}function _n(e){let n=Date.parse(e);if(!Number.isFinite(n))throw new Error(`Not a date: "${e}".`);return new Date(Math.floor(n/1e3)*1e3).toISOString().replace(/\.\d{3}Z$/,"Z")}function Ae(e){if(!$e.test(e)||!Number.isFinite(Date.parse(e)))throw new Error(`Not a SOQL datetime: "${e}".`);return e}function kn(e,n){let t=e?.trim()?D(e):void 0;if(n===void 0)return t;let r=`SystemModstamp > ${Ae(n)}`;return t?`${r} AND (${t})`:r}function De(e){if(typeof e!="string"||e==="")return null;let n=Date.parse(e.replace(/([+-]\d{2})(\d{2})$/,"$1:$2"));return Number.isFinite(n)?new Date(n).toISOString():null}function Fn(e,n,t){let r={query:i=>e.query(i),queryMore:i=>e.queryMore(i)},o={query:i=>e.query(i,{scanAll:!0}),queryMore:i=>e.queryMore(i)},s=()=>{if(t?.aborted)throw new Error("The run was cancelled.")};return{async latestModstamp(i){let d=R(i),y=(await e.query(`SELECT SystemModstamp FROM ${d} ORDER BY SystemModstamp DESC LIMIT 1`)).records[0];if(!y)return null;let g=De(y.SystemModstamp);if(g===null)throw new Error(`${d} answered a SystemModstamp that is not a date.`);return g},async deletedRows(i,d,f){let y=R(i),g=new Set(["Id","SystemModstamp",...d.map(k)]),{records:c,truncated:p}=await F(o,`SELECT ${[...g].join(", ")} FROM ${y} WHERE IsDeleted = true AND (${D(f)})`);return{records:c,truncated:p}},async heldInSource(i,d,f){let y=R(i),g=k(d),c=new Set;for(let p of N(f)){s();let{records:u}=await F(r,`SELECT ${g} FROM ${y} WHERE ${g} IN (${p.map(T).join(", ")})`);for(let l of u){let m=S(l[g]);m!==null&&c.add(m)}}return c},async targetIdsByKey(i,d,f){let y=R(i),g=k(d),c=g==="Id"?"Id":`Id, ${g}`,p=new Map;for(let u of N(f)){s();let{records:l}=await F(n,`SELECT ${c} FROM ${y} WHERE ${g} IN (${u.map(T).join(", ")})`);for(let m of l){let a=S(m[g]);a===null||typeof m.Id!="string"||p.set(a,[...p.get(a)??[],m.Id])}}return p}}}var Pe=new Set(["direct","rename","transform"]);function In(e){let n=e.objectApiName;if(e.operation==="insert"||e.operation==="delete")return{refused:`${n} is written by ${e.operation}, which finds no record by a key: a deleted source record cannot be tied to a target record.`};if(e.operation==="update")return{sourceField:"Id",keyField:"Id"};let t=C(e.externalIdField)??"Id";if((e.addOnFields??[]).some(s=>s.fieldApiName===t))return{refused:`${n}: an add-on writes ${t}, the key the upsert matches on, so it ties no deleted source record to one target record.`};let r=e.fieldMappings??[],o=r.find(s=>s.targetField.toLowerCase()===t.toLowerCase());return!o&&!J(r,e.excludedFields??[]).has(t.toLowerCase())?{sourceField:t,keyField:t}:!o||!Pe.has(o.type)?{refused:`${n}: no source field is carried onto ${t}, the key the upsert matches on, so no deleted source record can be tied to a target record.`}:{sourceField:o.sourceField,keyField:t}}async function On(e,n,t,r,o){let s=n.objectApiName,{records:i,truncated:d}=await e.deletedRows(s,[t.sourceField],r),f={ids:[],read:i.length,stillInSource:0,ambiguous:0,noKey:0,truncated:d};if(i.length===0)return f;let y=[];for(let l of i){let m=l[t.sourceField],a=o(l);if(S(m)===null||S(a)===null){f.noKey++;continue}y.push({raw:m,key:a})}if(y.length===0)return f;let g=t.sourceField==="Id"?new Set:await e.heldInSource(s,t.sourceField,y.map(l=>l.raw)),c=y.filter(l=>g.has(S(l.raw))?(f.stillInSource++,!1):!0);if(c.length===0)return f;let p=await e.targetIdsByKey(s,t.keyField,c.map(l=>l.key)),u=new Set;for(let l of c){let m=p.get(S(l.key))??[];m.length>1?f.ambiguous++:m.length===1&&!u.has(m[0])&&(u.add(m[0]),f.ids.push(m[0]))}return f}function Tn(e,n){let t=[];return e.stillInSource>0&&t.push(`${e.stillInSource} record(s) deleted in the source share their ${n} with a record the source still holds: their target record was kept.`),e.ambiguous>0&&t.push(`${e.ambiguous} record(s) deleted in the source match more than one target record on ${n}: none of those target records was deleted.`),e.noKey>0&&t.push(`${e.noKey} record(s) deleted in the source carry no ${n}: no target record is tied to them.`),e.truncated&&t.push("The source's deleted records were read up to a bound: the rest are read by the next run, from the same watermark."),t}function xn(e,n,t,r,o=0){return{read:e.read,...e.read==="delta"?{since:e.since}:{reason:e.reason},changed:n,deletionsChecked:t!==void 0,deleted:t?.deleted??0,deleteFailed:t?.deleteFailed??0,...t?.error!==void 0?{deletionError:t.error}:{},...r!==void 0?{recorded:r}:{},...o>0?{lookupsOwed:o}:{}}}export{Le as a,je as b,Ce as c,ie as d,O as e,de as f,le as g,We as h,ge as i,te as j,Qe as k,He as l,Ye as m,re as n,S as o,rn as p,on as q,_e as r,sn as s,an as t,dn as u,ln as v,cn as w,Te as x,Sn as y,wn as z,Rn as A,_n as B,Ae as C,kn as D,De as E,Fn as F,In as G,On as H,Tn as I,xn as J};
@@ -0,0 +1,13 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{d as ae}from"./chunk-JJITOWZK.mjs";import{b as F,d as B}from"./chunk-UV74P4H2.mjs";import{H as ne,d as te,k as E,z as re}from"./chunk-J24TIGSI.mjs";import{Ra as J,Ua as Z,cb as q}from"./chunk-ZQO5PDX5.mjs";import{b as l,e as h,i as X,k as I,l as f,r as Q,s as T,u as _,v as x,z as ee}from"./chunk-WZQEK4WT.mjs";import{randomBytes as _e}from"node:crypto";import{open as Je,readFile as Be,readdir as De,rename as $e,rm as Ue,stat as Ge}from"node:fs/promises";import{homedir as We}from"node:os";import{join as k,resolve as Ze}from"node:path";import*as L from"node:fs";import*as D from"node:path";function Ie(n){return`counting-contract.${F(n)}.json`}function K(n,e,t){return n.assertOutsideRepo(D.join(e,Ie(t)))}function Qe(n,e,t){let r=K(n,e,t.orgId);return L.mkdirSync(D.dirname(r),{recursive:!0}),L.writeFileSync(r,`${JSON.stringify(t,null,2)}
8
+ `,"utf8"),r}function et(n,e){let t=n.assertOutsideRepo(e),r=JSON.parse(L.readFileSync(t,"utf8"));if(r.version!==1||typeof r.objects!="object"||r.objects===null)throw new Error(`Invalid counting contract at ${t}: version 1 with objects expected`);return r}function tt(n,e){if(n.loadStartedAt!==void 0)return n.loadStartedAt===e.startedAt;let t=Date.parse(n.writtenAt),r=Date.parse(e.endedAt);return Number.isFinite(t)&&Number.isFinite(r)&&t>=r}import*as w from"node:fs/promises";import*as O from"node:path";var it=4*1024*1024,ot=64*1024*1024;var oe=1e4,M=l().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),b=l().min(1).max(40),st=f({forgeId:l().min(1).max(200),targetOrgId:l().min(1).max(128),timestamp:b,duration:h().nonnegative(),status:_(["success","partial","failure"]),cancelled:x(!0).optional(),writtenBetween:f({first:b,last:b}).optional(),retryOf:l().min(1).max(200).optional(),objects:I(f({objectApiName:l().regex(/^[A-Za-z][A-Za-z0-9_]*$/),ids:I(M)})),linked:h().int().nonnegative(),mayHaveBeenWritten:h().int().nonnegative().optional(),undo:f({removedAt:b,deleted:h().int().nonnegative(),alreadyGone:h().int().nonnegative(),kept:h().int().nonnegative(),refused:h().int().nonnegative(),notReached:h().int().nonnegative().optional(),notVisible:h().int().nonnegative().optional()}).optional(),removalStamps:T(M,b).optional(),removalSpans:I(f({first:b,last:b,userId:M})).optional(),removalLeft:I(M).optional(),sweep:f({sweptAt:b,deleted:h().int().nonnegative(),keptChanged:h().int().nonnegative(),refused:h().int().nonnegative()}).optional(),inJournal:f({journalId:l().min(1).max(200),part:h().int().nonnegative(),left:I(f({objectApiName:l().regex(/^[A-Za-z][A-Za-z0-9_]*$/),count:h().int().nonnegative()}))}).optional()}),dt=f({version:x(1),plans:I(X())}),ct=f({version:x(1),runs:I(f({forgeId:l().min(1).max(300),ids:I(M),late:I(M).optional()}))});var U="referenceid-mapping.json",ze=/^referenceid-mapping\.([A-Za-z0-9_-]{1,128})\.json$/,Re=/^referenceid-mapping\.([A-Za-z0-9_-]{1,128})\.load-\d{1,16}\.ndjson$/,N=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,V=new Set;function ve(n){try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}var Se=f({at:l().min(1).max(40),object:l().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),created:I(Q([l().min(1).max(400),l().regex(N)])).max(1e4)}),Oe=f({journal:f({startedAt:l().min(1).max(40),pid:h().int().positive(),runUserId:l().regex(N).optional()})});function be(n){let e,t={},r=new Map,o;for(let a of n.split(`
9
+ `)){if(a.trim()==="")continue;let s;try{s=JSON.parse(a)}catch{continue}if(!e){let c=Oe.safeParse(s);c.success&&(e=c.data.journal);continue}let i=Se.safeParse(s);if(!i.success)continue;let d=r.get(i.data.object)??[];for(let[c,u]of i.data.created)Object.prototype.hasOwnProperty.call(t,c)||d.push(c),t[c]=u;r.set(i.data.object,d),o=i.data.at}if(!(!e||o===void 0||Object.keys(t).length===0))return{startedAt:e.startedAt,pid:e.pid,load:{updatedAt:o,mapping:t,created:[...r].filter(([,a])=>a.length>0).map(([a,s])=>({objectApiName:a,referenceIds:s})),load:{startedAt:e.startedAt,endedAt:o},...e.runUserId?{runUserId:e.runUserId}:{}}}}function je(n){return`referenceid-mapping.${F(n)}.json`}async function $(n){let e;try{e=await w.readFile(n,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}return JSON.parse(e)}async function pe(n,e){let t=e.assertOutsideRepo(n),r;try{r=await w.readdir(t)}catch(a){if(a.code==="ENOENT")return[];throw a}let o=new Set(r.flatMap(a=>ze.exec(a)?.[1]??Re.exec(a)?.[1]??[]));if(r.includes(U)){let s=(await $(e.assertOutsideRepo(O.join(t,U))))?.orgId;typeof s=="string"&&Ae(s)&&o.add(s)}return[...o].sort()}function Ae(n){try{return F(n),!0}catch{return!1}}var Ee=I(f({objectApiName:l(),referenceIds:I(l())})),ke=f({startedAt:l(),endedAt:l()}),xe=f({first:l(),last:l()}),Fe=f({removedAt:l(),deleted:h(),alreadyGone:h(),kept:h(),refused:h(),notReached:h().optional()}),Le=T(l(),l()),Me=I(f({first:l(),last:l(),userId:l()})),se=T(l(),l()),Y=l().regex(N);function R(n,e){let t=n.safeParse(e);return t.success?t.data:void 0}function S(n){if(typeof n!="object"||n===null)return;let e=n,t=typeof e.mapping=="object"&&e.mapping!==null?Object.fromEntries(Object.entries(e.mapping).filter(m=>typeof m[1]=="string")):{},r=R(Ee,e.created),o=R(ke,e.load),a=R(xe,e.writtenBetween),s=R(Fe,e.removal),i=R(Le,e.removalStamps),d=R(Me,e.removalSpans),c=R(se,e.personContacts),u=R(se,e.withTheirRecord),g=R(Y,e.runUserId),p=R(I(Y),e.madeEarlier),P=R(I(Y),e.lateEarlier);return{updatedAt:typeof e.updatedAt=="string"?e.updatedAt:"",mapping:t,...r?{created:r}:{},...o?{load:o}:{},...a?{writtenBetween:a}:{},...s?{removal:s}:{},...i?{removalStamps:i}:{},...d?{removalSpans:d}:{},...c?{personContacts:c}:{},...u?{withTheirRecord:u}:{},...g?{runUserId:g}:{},...p?{madeEarlier:p}:{},...P?{lateEarlier:P}:{}}}function j(n){return Array.isArray(n.earlier)?n.earlier.flatMap(e=>S(e)??[]):[]}function A(n){return n.load?.endedAt??n.updatedAt}function Ne(n,e){return n.slice(0,15)===e.slice(0,15)}function v(n){return n.slice(0,15)}function de(n,e){let t={};for(let[r,o]of Object.entries(n??{}))Object.prototype.hasOwnProperty.call(e,o)?Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=o):delete e[r];return t}function ce(n,e){if(e.size===0)return n;let t=Object.fromEntries(Object.entries(n.mapping).filter(([,d])=>!e.has(v(d)))),r=de(n.personContacts,t),o=de(n.withTheirRecord,t),a=n.created?.map(({objectApiName:d,referenceIds:c})=>({objectApiName:d,referenceIds:c.filter(u=>Object.prototype.hasOwnProperty.call(t,u))})).filter(d=>d.referenceIds.length>0),s=Object.fromEntries(Object.entries(n.removalStamps??{}).filter(([d])=>!e.has(v(d)))),i={...n,mapping:t};return delete i.removalStamps,delete i.personContacts,delete i.withTheirRecord,{...i,...a?{created:a}:{},...Object.keys(s).length>0?{removalStamps:s}:{},...Object.keys(r).length>0?{personContacts:r}:{},...Object.keys(o).length>0?{withTheirRecord:o}:{}}}function le(n){return n.created?n.created.some(e=>e.referenceIds.length>0):Object.keys(n.mapping).length>0}var G=class{constructor(e,t){this.sasDir=e;this.guard=t?.guard??new B,this.orgId=t?.orgId??"";let r=t?.organizationId;this.askOrganizationId=typeof r=="function"?r:async()=>r,this.now=t?.now??(()=>new Date)}sasDir;guard;orgId;askOrganizationId;organizationId;now;get filePath(){return this.guard.assertOutsideRepo(O.join(this.sasDir,this.orgId===""?U:je(this.orgId)))}get singleFilePath(){return this.orgId===""?void 0:this.guard.assertOutsideRepo(O.join(this.sasDir,U))}get journalStem(){return this.orgId===""?"referenceid-mapping":`referenceid-mapping.${F(this.orgId)}`}journalPath(e){let t=typeof e=="string"?Date.parse(e):e.getTime();return this.guard.assertOutsideRepo(O.join(this.sasDir,`${this.journalStem}.load-${Math.max(0,Math.trunc(t))}.ndjson`))}retiring=new Map;journal(e){let t=this.journalPath(e),r=!1,o=!1,a=!1,s,i=Promise.resolve(),d;V.add(t);let c=g=>{i=i.then(async()=>{if(!(d!==void 0||o))try{if(!r){r=!0,await w.mkdir(O.dirname(t),{recursive:!0});let p={journal:{startedAt:e.toISOString(),pid:process.pid,...s?{runUserId:s}:{}}};await w.appendFile(t,`${JSON.stringify(p)}
10
+ `,"utf8")}await w.appendFile(t,`${JSON.stringify(g)}
11
+ `,"utf8")}catch(p){d=p instanceof Error?p.message:String(p)}})},u=async()=>{await i,o=!0,await w.rm(t,{force:!0})};return this.retiring.set(t,u),{writtenAs:g=>{N.test(g)&&(s=g)},created:(g,p)=>{let P=p.filter(([m,y])=>m!==""&&N.test(y));if(P.length!==0){a=!0;for(let m=0;m<P.length;m+=1e4)c({at:this.now().toISOString(),object:g,created:P.slice(m,m+1e4)})}},flush:async()=>(await i,d),close:async()=>{await i,this.retiring.delete(t),(o||!a)&&await w.rm(t,{force:!0}),o=!0,V.delete(t)}}}async stoppedLoads(e){let t;try{t=await w.readdir(this.guard.assertOutsideRepo(this.sasDir))}catch(s){if(s.code==="ENOENT")return[];throw s}let r=`${this.journalStem}.load-`,o=new Set(e.flatMap(s=>s.load?[s.load.startedAt]:[])),a=[];for(let s of t){if(!s.startsWith(r)||!/^\d{1,16}\.ndjson$/.test(s.slice(r.length)))continue;let i=this.guard.assertOutsideRepo(O.join(this.sasDir,s));if(V.has(i))continue;let d;try{d=await w.readFile(i,"utf8")}catch{continue}let c=be(d);!c||o.has(c.startedAt)||c.pid!==process.pid&&ve(c.pid)||a.push({file:i,load:c.load})}return a}async load(){let e=await this.read();return e===void 0||await this.writtenToAnotherOrg(e)?new Map:new Map(Object.entries(e.mapping??{}))}async previousLoads(){let e=await this.read();if(e===void 0||await this.writtenToAnotherOrg(e))return[];let t=S(e);return[...t?[t]:[],...j(e)].map(r=>({mapping:new Map(Object.entries(r.mapping)),...r.created?{created:r.created}:{},...r.writtenBetween?{writtenBetween:r.writtenBetween}:{},endedAt:A(r),...r.removalStamps?{removalStamps:r.removalStamps}:{}}))}async recorded(){return(await this.recordedLoads())[0]}async recordedLoads(){let e=await this.read();if(e===void 0)return[];let t=typeof e.orgId=="string"?e.orgId:"",r=S(e);return[...r?[this.recordedOf(r,t)]:[],...j(e).map(o=>({...this.recordedOf(o,t),earlier:!0}))]}recordedOf(e,t){return{orgId:t,mapping:new Map(Object.entries(e.mapping)),...e.created?{created:e.created}:{},...e.load?{startedAt:e.load.startedAt}:{},endedAt:A(e),...e.writtenBetween?{writtenBetween:e.writtenBetween}:{},...e.removal?{removal:e.removal}:{},removalStamps:e.removalStamps??{},removalSpans:e.removalSpans??[],...e.personContacts?{personContacts:e.personContacts}:{},...e.withTheirRecord?{withTheirRecord:e.withTheirRecord}:{},...e.runUserId?{runUserId:e.runUserId}:{},...e.madeEarlier?{madeEarlier:e.madeEarlier}:{},...e.lateEarlier?{lateEarlier:e.lateEarlier}:{}}}async isStale(){let e=await this.read();return e!==void 0&&await this.writtenToAnotherOrg(e)}async writtenToAnotherOrg(e){let t=e.organizationId;if(t===void 0)return!1;let r=await this.currentOrganizationId();return r!==void 0&&!Ne(t,r)}currentOrganizationId(){return this.organizationId??=this.askOrganizationId(),this.organizationId}async read(){return(await this.readWithJournals()).payload}async readFile(){let e=await $(this.filePath);if(e!==void 0)return e;let t=this.singleFilePath;if(t===void 0)return;let r=await $(t);return r?.orgId===this.orgId?r:void 0}async readWithJournals(){let e=await this.readFile(),t=e?[S(e),...j(e)]:[],r=await this.stoppedLoads(t.filter(i=>i!==void 0));if(r.length===0)return{payload:e,journals:[]};let o=[...t.filter(i=>i!==void 0),...r.map(({load:i})=>i)].sort((i,d)=>Date.parse(A(d))-Date.parse(A(i))),[a,...s]=o;return{payload:{version:1,orgId:typeof e?.orgId=="string"?e.orgId:this.orgId,...e?.organizationId!==void 0?{organizationId:e.organizationId}:{},...a,...s.length>0?{earlier:s}:{}},journals:r.map(({file:i})=>i)}}async dropJournals(e){for(let t of e)await w.rm(t,{force:!0}).catch(()=>{})}async write(e){let t=this.filePath;await w.mkdir(O.dirname(t),{recursive:!0}),await w.writeFile(t,`${JSON.stringify(e,null,2)}
12
+ `,"utf8");let r=this.singleFilePath;if(r!==void 0)try{(await $(r))?.orgId===this.orgId&&await w.rm(r)}catch{}}async keptLoads(e,t,r=[]){if(e===void 0||e.orgId!==this.orgId)return[];if(await this.writtenToAnotherOrg(e))return[];let o=new Set(t.map(v)),a=new Set(r),s=S(e);return[...s?[s]:[],...j(e)].map(i=>ce(i,o)).filter(i=>le(i)||a.has(A(i)))}async persist(e,t){let{payload:r,journals:o}=await this.readWithJournals(),a=t?.earlier?await this.keptLoads(r,t.earlier.settled,t.earlier.stillToSweep):[],s=await this.currentOrganizationId(),i=this.now().toISOString(),d=g=>Object.fromEntries(Object.entries(g??{}).filter(([p,P])=>e.has(p)&&e.has(P))),c=d(t?.personContacts),u=d(t?.withTheirRecord);if(await this.write({version:1,orgId:this.orgId,...s!==void 0?{organizationId:s}:{},updatedAt:i,mapping:Object.fromEntries([...e.entries()].sort(([g],[p])=>g.localeCompare(p))),...t?{created:t.created.map(({objectApiName:g,referenceIds:p})=>({objectApiName:g,referenceIds:p.filter(P=>e.has(P))})).filter(g=>g.referenceIds.length>0),load:{startedAt:t.startedAt.toISOString(),endedAt:i},...t.writtenBetween?{writtenBetween:{...t.writtenBetween}}:{},...Object.keys(c).length>0?{personContacts:c}:{},...Object.keys(u).length>0?{withTheirRecord:u}:{},...t.runUserId?{runUserId:t.runUserId}:{}}:{},...a.length>0?{earlier:a}:{}}),t?.earlier&&await this.dropJournals(o),t){let g=this.journalPath(t.startedAt),p=this.retiring.get(g);p?await p():await w.rm(g,{force:!0}).catch(()=>{})}}async recordRemoval(e,t){let{payload:r,journals:o}=await this.readWithJournals(),a=S(r);if(r===void 0||a===void 0)return!1;let s=[a,...j(r)],i=s.findIndex(g=>A(g)===e);if(i<0)return!1;let d=new Set(t.gone.map(v)),[c,...u]=s.map((g,p)=>ce(p===i?Te(g,t):g,d));return await this.write({version:1,orgId:typeof r.orgId=="string"?r.orgId:"",...r.organizationId!==void 0?{organizationId:r.organizationId}:{},...c,updatedAt:this.now().toISOString(),...u.length>0?{earlier:u}:{}}),await this.dropJournals(o),!0}async recordMade(e,t,r=[],o=[]){let{payload:a,journals:s}=await this.readWithJournals(),i=S(a);if(a===void 0||i===void 0)return!1;let d=[i,...j(a)],c=d.findIndex(m=>A(m)===e);if(c<0)return!1;let u=[...o],g=m=>{let y=ge(m.madeEarlier,t,u),z=ge(m.lateEarlier,r,u),C={...m};return delete C.madeEarlier,delete C.lateEarlier,{...C,...y.length>0?{madeEarlier:y}:{},...z.length>0?{lateEarlier:z}:{}}},[p,...P]=d.map((m,y)=>y===c?g(m):m);return await this.write({version:1,orgId:typeof a.orgId=="string"?a.orgId:"",...a.organizationId!==void 0?{organizationId:a.organizationId}:{},...p,...P.length>0?{earlier:P}:{}}),await this.dropJournals(s),!0}async letSweptGo(e){if(e.length===0)return!1;let{payload:t,journals:r}=await this.readWithJournals(),o=S(t);if(t===void 0||o===void 0)return!1;let a=new Set(e),s=j(t),i=s.filter(d=>le(d)||!a.has(A(d)));return i.length===s.length?!1:(await this.write({version:1,orgId:typeof t.orgId=="string"?t.orgId:"",...t.organizationId!==void 0?{organizationId:t.organizationId}:{},...o,...i.length>0?{earlier:i}:{}}),await this.dropJournals(r),!0)}async recordStamps(e){let{payload:t,journals:r}=await this.readWithJournals(),o=S(t);if(t===void 0||o===void 0)return!1;let a=[o,...j(t)],s=a.map(c=>Ce(c,e));if(s.every((c,u)=>c===a[u]))return!1;let[i,...d]=s;return await this.write({version:1,orgId:typeof t.orgId=="string"?t.orgId:"",...t.organizationId!==void 0?{organizationId:t.organizationId}:{},...i,...d.length>0?{earlier:d}:{}}),await this.dropJournals(r),!0}};function ge(n,e,t=[]){let r=new Map,o=new Set(t.map(v)),a=[];for(let s of[...n??[],...e]){let i=v(s),d=i.slice(0,3),c=r.get(d)??0;!N.test(s)||o.has(i)||c>=oe||(o.add(i),r.set(d,c+1),a.push(s))}return a}function Ce(n,e){let t=new Set(Object.values(n.mapping).map(v)),r=Object.entries(e).filter(([a])=>t.has(v(a)));if(r.length===0)return n;let o=new Set(r.map(([a])=>v(a)));return{...n,removalStamps:{...Object.fromEntries(Object.entries(n.removalStamps??{}).filter(([a])=>!o.has(v(a)))),...Object.fromEntries(r)}}}function Te(n,e){let t={...n.removalStamps,...e.stamps},r=[...n.removalSpans??[],...e.span?[e.span]:[]],o=e.mark??n.removal;return{...n,...o?{removal:o}:{},...Object.keys(t).length>0?{removalStamps:t}:{},...r.length>0?{removalSpans:r}:{}}}var qe="replays",ue="replay.json";function St(n=process.env){let e=n.SANDFORGE_JOURNAL_DIR,t=e!==void 0&&e.trim()!==""?Ze(e):k(We(),".sandforge");return k(t,qe)}var H=ee.datetime({offset:!0}),Ke=f({organizationId:Z,name:l().min(1).max(255),choices:q,firstAt:H,lastAt:H}),we=f({version:x(1),checkpoint:f({checkpointId:J,name:l().min(1).max(255),organizationId:Z,alias:l().min(1).max(255).optional(),tier:_(["sandbox","scratch","developer"]),takenAt:H}),targets:I(Ke).max(1e4)}),fe=/^00D[A-Za-z0-9]{15}$/,me=class{root;guard;now;writes=new Map;constructor(e){this.guard=e.guard??new B,this.root=this.guard.assertOutsideRepo(e.root),this.now=e.now??(()=>new Date)}folderOf(e,t){let r=E(e),o=J.safeParse(t);if(!o.success)throw new ne("invalid","Not a checkpoint\u2019s id");return{dir:this.guard.assertOutsideRepo(k(this.root,r,o.data)),sourceOrganizationId:r,checkpointId:o.data}}async record(e,t,r){let o=this.folderOf(e.org.organizationId,e.checkpointId),a=E(t.organizationId),s=q.parse(r);await re(o.dir);let i=k(o.dir,ue),d=async()=>{let g=this.now().toISOString(),p=await he(i),P=p?.targets.find(y=>y.organizationId===a),m={version:1,checkpoint:{checkpointId:o.checkpointId,name:e.name,organizationId:o.sourceOrganizationId,...e.org.alias!==void 0?{alias:e.org.alias}:{},tier:e.org.tier,takenAt:e.takenAt},targets:[...p?.targets.filter(y=>y.organizationId!==a)??[],{organizationId:a,name:t.name,choices:s,firstAt:P?.firstAt??g,lastAt:g}]};await Ye(i,`${JSON.stringify(we.parse(m),null,2)}
13
+ `)},c=(this.writes.get(i)??Promise.resolve()).then(d,d),u=c.catch(()=>{});return this.writes.set(i,u),u.then(()=>{this.writes.get(i)===u&&this.writes.delete(i)}),await c,o}mappingStoreOf(e,t,r={}){return new G(e.dir,{guard:this.guard,orgId:E(t),...r})}contractPathOf(e,t){return K(this.guard,e.dir,E(t))}async read(e){return he(k(e.dir,ue))}async list(e={}){let t=e.sourceOrganizationId!==void 0?E(e.sourceOrganizationId):void 0,r=e.targetOrganizationId!==void 0?E(e.targetOrganizationId):void 0,o=[];for(let a of await ye(this.root))if(!(!fe.test(a)||t!==void 0&&a!==t))for(let s of await ye(k(this.root,a))){if(!J.safeParse(s).success||e.checkpointId!==void 0&&s!==e.checkpointId)continue;let i=this.folderOf(a,s);o.push(...await this.entriesOf(i,r))}return o.sort((a,s)=>W(s.replayedAt??"",a.replayedAt??"")||W(a.checkpointId,s.checkpointId)||W(a.target.organizationId,s.target.organizationId))}async replaysOf(e,t){return this.list({sourceOrganizationId:e,checkpointId:t})}async entriesOf(e,t){let r=await this.read(e),o=new Map(r?.targets.map(d=>[d.organizationId,d])),a=(await pe(e.dir,this.guard)).filter(d=>fe.test(d)),s=[...new Set([...o.keys(),...a])].filter(d=>t===void 0||d===t),i=[];for(let d of s){let c=o.get(d),u=await this.mappingStoreOf(e,d).recordedLoads(),g=new Map;for(let y of u)for(let{objectApiName:z,ids:C}of ae(y))g.set(z,(g.get(z)??0)+C.length);let p=[...g].map(([y,z])=>({objectApiName:y,records:z})).sort((y,z)=>W(y.objectApiName,z.objectApiName)),P=p.reduce((y,z)=>y+z.records,0),m=u.find(y=>y.earlier!==!0);i.push({sourceOrganizationId:e.sourceOrganizationId,checkpointId:e.checkpointId,...r?{checkpointName:r.checkpoint.name}:{},...r?{takenAt:r.checkpoint.takenAt}:{},target:{organizationId:d,...c?{name:c.name}:{}},...c?{choices:c.choices}:{},...m?{replayedAt:m.endedAt}:{},inPlace:P,inPlaceByObject:p,...m!==void 0&&P===0&&m.removal!==void 0?{removed:!0}:{}})}return i}};function Ve(n){return n.filter(e=>e.inPlace>0)}function Ot(n){let e=Ve(n);if(e.length===0)return;let t=e.map(r=>`${r.inPlace.toLocaleString("en-US")} record${r.inPlace===1?"":"s"} in ${r.target.name??r.target.organizationId}`).join(", ");return`${e.length===1?"A replay":`${e.length} replays`} of it ${e.length===1?"is":"are"} still in place: ${t}. Deleting the checkpoint leaves them there, and each replay is still removed without it.`}async function he(n){let e;try{e=await Be(n,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}try{let t=we.safeParse(JSON.parse(e));return t.success?t.data:void 0}catch{return}}async function Ye(n,e){let t=`${n}.${process.pid}-${_e(4).toString("hex")}.tmp`,r=await Je(t,"wx",te);try{try{await r.writeFile(e,"utf8"),await r.sync()}finally{await r.close()}await $e(t,n)}catch(o){throw await Ue(t,{force:!0}),o}}async function ye(n){let e;try{e=await De(n)}catch(r){if(r.code==="ENOENT")return[];throw r}let t=[];for(let r of e)(await Ge(k(n,r)).catch(()=>{}))?.isDirectory()&&t.push(r);return t.sort()}function W(n,e){return n<e?-1:n>e?1:0}export{K as a,Qe as b,et as c,tt as d,je as e,pe as f,G as g,ue as h,St as i,me as j,Ve as k,Ot as l};
@@ -4,5 +4,5 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{b as $e}from"./chunk-OXKZ4Y3B.mjs";import{a as We}from"./chunk-M6P5ZZLE.mjs";import{c as ke,d as Ge}from"./chunk-SW2NUKQL.mjs";import{d as _e,z as Le}from"./chunk-E2YJVSX6.mjs";import{a as k}from"./chunk-4TLYUZD5.mjs";import{a as re}from"./chunk-PPGDAUEQ.mjs";import{a as Me}from"./chunk-VV3B6IC3.mjs";import{m as qe}from"./chunk-CULAOP3U.mjs";import{a as De}from"./chunk-SU65Z2BA.mjs";import{b as xe}from"./chunk-EADHKH3A.mjs";import{a as Te,h as q}from"./chunk-TZE3Y7IQ.mjs";import{a as H,c as Ae,g as oe,j as Pe,n as Ne}from"./chunk-EAFLDSQ2.mjs";import{a as je,b as x}from"./chunk-CA5NAXSU.mjs";import{ac as Z,bc as ee,ca as Ie,cc as te,ja as Fe,wa as ve,za as ue}from"./chunk-DPYTG6DM.mjs";import{b as Ce,e as Ee,i as Re,k as Se,l as de}from"./chunk-WZQEK4WT.mjs";import{appendFile as tt}from"node:fs/promises";var fe=new Set(["Task","Event"]),rt=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,ot="an emptying";function nt(t){let e=q(t.objectApiName),o=fe.has(t.objectApiName),r=[...t.filter!==void 0&&t.filter.trim()!==""?[`(${t.filter})`]:[],...o?["IsDeleted = false"]:[]];return{soql:`SELECT Id FROM ${e}${r.length>0?` WHERE ${r.join(" AND ")}`:""}`,scanAll:o}}async function zt(t,e,o,r={}){let n=()=>r.signal?.aborted===!0,c=[];await Le(e);for(let a of o){let{soql:d,scanAll:u}=nt(a),m={objectApiName:a.objectApiName,count:0};if(c.push(m),n())return{stopped:!0,read:c};let R=ke(e,a.objectApiName),i=!0,h=0,b=await t.query(d,{scanAll:u});for(;;){let S=b.records.map(y=>{let C=y.Id;if(typeof C!="string"||!rt.test(C))throw new Error(`The org answered a ${a.objectApiName} row with no record id: its ids are not read.`);return C});if((S.length>0||i)&&(await tt(R,S.map(y=>`${y}
7
+ import{b as $e}from"./chunk-Q3DY7TO2.mjs";import{a as We}from"./chunk-M6P5ZZLE.mjs";import{c as ke,d as Ge}from"./chunk-6KP6WETK.mjs";import{d as _e,z as Le}from"./chunk-J24TIGSI.mjs";import{a as re}from"./chunk-PPGDAUEQ.mjs";import{a as Me}from"./chunk-VV3B6IC3.mjs";import{a as k}from"./chunk-4TLYUZD5.mjs";import{m as qe}from"./chunk-7PY3VQP3.mjs";import{a as De}from"./chunk-SU65Z2BA.mjs";import{b as xe}from"./chunk-EADHKH3A.mjs";import{a as H,c as Ae,g as oe,j as Pe,n as Ne}from"./chunk-L4INJ5TZ.mjs";import{a as Te,h as q}from"./chunk-TZE3Y7IQ.mjs";import{a as je,b as x}from"./chunk-CA5NAXSU.mjs";import{ca as Ie,ja as Fe,mc as Z,nc as ee,oc as te,wa as ve,za as ue}from"./chunk-ZQO5PDX5.mjs";import{b as Ce,e as Ee,i as Re,k as Se,l as de}from"./chunk-WZQEK4WT.mjs";import{appendFile as tt}from"node:fs/promises";var fe=new Set(["Task","Event"]),rt=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,ot="an emptying";function nt(t){let e=q(t.objectApiName),o=fe.has(t.objectApiName),r=[...t.filter!==void 0&&t.filter.trim()!==""?[`(${t.filter})`]:[],...o?["IsDeleted = false"]:[]];return{soql:`SELECT Id FROM ${e}${r.length>0?` WHERE ${r.join(" AND ")}`:""}`,scanAll:o}}async function zt(t,e,o,r={}){let n=()=>r.signal?.aborted===!0,c=[];await Le(e);for(let a of o){let{soql:d,scanAll:u}=nt(a),m={objectApiName:a.objectApiName,count:0};if(c.push(m),n())return{stopped:!0,read:c};let R=ke(e,a.objectApiName),i=!0,h=0,b=await t.query(d,{scanAll:u});for(;;){let S=b.records.map(y=>{let C=y.Id;if(typeof C!="string"||!rt.test(C))throw new Error(`The org answered a ${a.objectApiName} row with no record id: its ids are not read.`);return C});if((S.length>0||i)&&(await tt(R,S.map(y=>`${y}
8
8
  `).join(""),{encoding:"utf8",mode:_e,flag:i?"w":"a"}),i=!1),m.count+=S.length,r.onPage?.(a.objectApiName,m.count),h=S.length===0?h+1:0,b.done||!b.nextRecordsUrl)break;if(h>=xe)throw new Error(`The org kept answering empty pages of ${a.objectApiName} without saying it was done: ${m.count} id(s) read, the rest not.`);if(n())return{stopped:!0,read:c};b=await t.queryMore(b.nextRecordsUrl)}}return{stopped:!1,spool:await Ge(e,c,ot)}}function ne(t,e,o){return e.nillable!==!1||e.referenceTo.length!==1?!1:e.isMasterDetail||(o??[]).some(r=>r.isCascadeDelete&&r.childSObject===t&&r.field===e.name)}var V=.001,ge=.01,st=50,it=5,at=2,ct=4;function lt(t){return t.level===0||t.recordCount>0||t.status==="error"||t.recordCountUnknown===!0}function Be(t){return t.inputMode==="record"&&typeof t.recordId=="string"&&t.recordId!==""}function pe(t){if(!Fe(t)||t.inputMode!=="soql")return;let e=Ie(t.soqlQuery??"");return e?{where:e.where,limit:e.limit}:void 0}function dt(t,e,o){let r=[];o===0&&Be(t)&&r.push(`Id = '${Te(t.recordId??"")}'`);let n=o===0?pe(t):void 0;n?.where&&r.push(`(${n.where})`);let c=t.objectSoqlFilters?.[e];return c&&r.push(`(${c})`),`SELECT COUNT() FROM ${q(e)}${r.length>0?` WHERE ${r.join(" AND ")}`:""}`}var me=typeof setImmediate=="function"?()=>new Promise(t=>setImmediate(t)):()=>new Promise(t=>setTimeout(t,0)),A=class extends Error{constructor(){super("Discovery cancelled"),this.name="DiscoveryCancelled"}};function M(t,e){return e?e.aborted?Promise.reject(new A):new Promise((o,r)=>{let n=()=>r(new A);e.addEventListener("abort",n,{once:!0}),t().then(c=>{e.removeEventListener("abort",n),o(c)},c=>{e.removeEventListener("abort",n),r(c)})}):t()}function ut(t){return t.fieldCount>0||t.piiFields.length>0}function ft(t,e){if(t.type!=="master-detail")return t;let o=(e.get(t.targetObject)?.fields??[]).filter(n=>n.referenceTo.includes(t.sourceObject)),r=e.get(t.sourceObject)?.childRelationships;return o.some(n=>ne(t.targetObject,n,r))?t:{...t,type:"lookup"}}function Y(){return{nodes:[],edges:[],totalRecords:0,estimatedSizeMB:0,estimatedDurationSeconds:0,truncated:!1}}var Ue=class{deps;constructor(e){this.deps=e}async discover(e,o){if(e.inputMode==="org"||e.depth==="all")return ze(this.deps,e,o);let r=o?.signal;if(r?.aborted)return Y();o?.onProgress?.({phase:"resolving-root",discoveredCount:0,queueRemaining:1});let n=Date.now(),c;try{c=await this.resolveRootObject(e,r)}catch(g){if(g instanceof A)return Y();throw g}let a=Date.now();a-n>2e3&&k.warn(`[forge-discover] resolveRootObject took ${a-n}ms (cold path, consider verifying describeGlobal cache state)`);let d=this.resolveMaxDepth(e),u=o?.maxNodes??st,m=u,R=u*at,i=new Set,h=[],b=u*ct,S=0,y=0,C=new Set,I=[],$=new Map,N=new Map,L=()=>S+y+w.length<m&&I.length+y+w.length<b,W=(g,j)=>{i.has(g)||h.push([g,j]),i.add(g)},D=g=>{i.delete(g)&&(h=h.filter(([j])=>j!==g))},U=new Map,B=(g,j,P,F)=>{if(H(g.sourceObject)||H(g.targetObject)||g.sourceObject===g.targetObject)return;let s=`${g.sourceObject}|${g.targetObject}`,l=U.get(s)??new Map;(P!==void 0||!l.has(j))&&l.set(j,{settable:P,insertOnly:F}),U.set(s,l);let p=$.get(s);if(!p){$.set(s,g);return}let f=g.type==="master-detail"&&p.type==="lookup"?g:p,v=p.required===!0||g.required===!0;$.set(s,v?{...f,required:v}:f)},w=[[c,0]];for(C.add(c);w.length>0&&!r?.aborted;){await me();let g=m-S;if(g<=0)break;let j=Math.min(6,g,w.length),P=w.splice(0,j),F=await Promise.all(P.map(async([s,l])=>{let p,f=!1,v=dt(e,s,l);try{let[E,Q]=await Promise.all([M(()=>this.deps.describeObject(e.sourceOrgId,s,r),r),M(()=>this.deps.queryCount(e.sourceOrgId,v,r),r).catch(_=>{if(_ instanceof A)throw _;return p=x(_),f=se(_),-1})]);return{objectName:s,depth:l,describe:E,recordCount:Q,countError:p,countRefused:f}}catch(E){return E instanceof A||r?.aborted?{objectName:s,depth:l,describe:null,recordCount:-1,cancelled:!0}:{objectName:s,depth:l,describe:null,recordCount:-1,describeError:x(E)}}}));y=F.length;for(let s of F){if(y--,s.cancelled)continue;let{objectName:l,depth:p,describe:f,recordCount:v,countError:E,countRefused:Q,describeError:_}=s;if(!f){I.push({objectApiName:l,recordCount:0,fieldCount:0,status:"error",progress:0,included:!1,piiFields:[],anonymizeFields:[],level:p,successCount:0,failureCount:0,errors:[`Describe unavailable: ${_??"unknown error"}`],createableFieldCount:0,estimatedSizeMB:0,estimatedApiCalls:0,batchStrategy:"auto"}),S++,o?.onProgress?.({phase:"object",objectApiName:l,discoveredCount:I.length,queueRemaining:w.length});continue}N.set(l,f);let ie=v<0,ae=ie&&Q!==!0,ce=ie&&!ae,le=p===0?pe(e)?.limit:void 0,J=ie?0:typeof le=="number"&&Number.isFinite(le)?Math.min(v,le):v,Je=p===0&&(Be(e)||pe(e)!==void 0),be=this.deps.detectPII(f.fields),Ke=f.fields.filter(O=>O.type!=="id").length,Oe={objectApiName:l,...f.label?{label:f.label}:{},recordCount:J,...ae?{recordCountUnknown:!0}:{},fieldCount:f.fields.length,status:ce?"error":"idle",progress:0,included:ce?!1:ae||Je||!e.skipEmpty||J>0,piiFields:be,anonymizeFields:e.anonymizePII?be:[],level:p,successCount:0,failureCount:0,errors:ce?[`Record count unavailable: ${E??"unknown error"}`]:[],createableFieldCount:Ke,estimatedSizeMB:J*V,estimatedApiCalls:Math.ceil(J/200),batchStrategy:"auto"};I.push(Oe);let ye=lt(Oe);if(ye&&S++,p<d&&ye){for(let O of f.fields){if(O.referenceTo.length===0)continue;let we=ee(O),K=we&&Z(l,O.name,O.nillable),Ze=te(O);for(let T of O.referenceTo){B({sourceObject:T,targetObject:l,relationshipName:O.relationshipName??O.name,type:O.isMasterDetail?"master-detail":"lookup",required:K},O.name,we,Ze);let et=i.has(T);(!C.has(T)||K&&et)&&!H(T)&&(L()?(C.add(T),D(T),K?w.unshift([T,p+1]):w.push([T,p+1])):K&&m<R?(C.add(T),D(T),m++,w.unshift([T,p+1])):(C.add(T),W(T,p+1)))}}for(let O of f.childRelationships)B({sourceObject:l,targetObject:O.childSObject,relationshipName:O.relationshipName,type:O.isCascadeDelete?"master-detail":"lookup"},O.field,void 0,void 0),!C.has(O.childSObject)&&!H(O.childSObject)&&(C.add(O.childSObject),L()?w.push([O.childSObject,p+1]):W(O.childSObject,p+1))}o?.onProgress?.({phase:"object",objectApiName:l,discoveredCount:I.length,queueRemaining:w.length})}for(;h.length>0&&L();){let[s,l]=h.shift();i.delete(s),w.push([s,l])}}let z=I.reduce((g,j)=>g+j.recordCount,0),G=[...$].map(([g,j])=>{let P=[...U.get(g)?.values()??[]],F=ft(j,N);return P.length>0&&P.every(s=>s.settable===!1)&&(F={...F,settable:!1}),P.some(s=>s.insertOnly===!0)&&(F={...F,insertOnly:!0}),F});return{nodes:I,edges:G,totalRecords:z,estimatedSizeMB:z*V,estimatedDurationSeconds:z*ge,truncated:h.length>0}}personalFields(e){return this.deps.detectPII(e)}async readPersonalFields(e,o,r){let n=e.nodes.filter(a=>!ut(a)&&a.status!=="error"),c=new Map;for(let a=0;a<n.length&&!r?.aborted;a+=6)await Promise.all(n.slice(a,a+6).map(async({objectApiName:d})=>{try{let u=await this.deps.describeObject(o.sourceOrgId,d,r),m=this.deps.detectPII(u.fields);m.length>0&&c.set(d,m)}catch(u){k.warn(`[forge] personal fields of ${d} not read: ${x(u)}`)}}));return c.size===0?e:{...e,nodes:e.nodes.map(a=>{let d=c.get(a.objectApiName);return d?{...a,piiFields:d,anonymizeFields:o.anonymizePII?[...d]:[]}:a})}}async resolveRootObject(e,o){if(e.inputMode==="record"&&e.recordId){let r=e.recordId.substring(0,3),c=(await M(()=>this.deps.describeGlobal(e.sourceOrgId,o),o)).find(a=>a.keyPrefix===r);if(!c)throw new Error(`No object found for record ID prefix "${r}". The ID may not belong to any accessible object in this org.`);return c.name}if(e.inputMode==="soql"&&e.soqlQuery)return pt(e.soqlQuery);throw new Error(`Cannot resolve root object for inputMode "${e.inputMode}". Provide a valid recordId (for "record" mode) or soqlQuery (for "soql" mode).`)}resolveMaxDepth(e){switch(e.depth){case"direct":return 1;case"full":return it;case"custom":return Math.max(1,Math.min(10,e.customDepth??3));case"all":throw new Error("A clone of the whole org is discovered without a walk (WholeOrgDiscovery)")}}};function pt(t){let e=t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/--[^\n]*/g,"");for(let r=0;r<32;r++){let n=e.replace(/\([^()]*\)/g,"");if(n===e)break;e=n}let o=/\bFROM\s+(\w+)/i.exec(e);if(!o)throw new Error('Could not parse object name from SOQL query. Ensure the query uses standard "SELECT ... FROM ObjectName" syntax.');return q(o[1])}var gt={clone:"write",empty:"delete"},mt=["settings","definition"],ht=new Set(["contentworkspace"]);function bt(t){if(t.name.includes("__"))return!1;let e=t.name.toLowerCase();return ht.has(e)||mt.some(o=>e.endsWith(o))?!0:t.createable===!1&&e!==oe.toLowerCase()}function Ot(t,e){return t.objectApiName<e.objectApiName?-1:t.objectApiName>e.objectApiName?1:0}function yt(t,e,o,r={}){let n=Ne(t,{mode:"everything",access:gt[o],...r.excluded!==void 0?{excluded:r.excluded}:{},...r.customSettings!==void 0?{customSettings:r.customSettings}:{}},e),c=new Map(t.map(u=>[u.name.toLowerCase(),u])),a=[],d=[];for(let u of n.candidates){let m=c.get(u.toLowerCase());m!==void 0&&bt(m)?d.push({objectApiName:u,reason:"configuration"}):a.push(u)}return d.length===0?n:{...n,candidates:a,leftOut:[...n.leftOut,...d].sort(Ot)}}var wt=new Set([oe,Pe].map(t=>t.toLowerCase())),Qe="withTheirRecords",Ct="noLayout";function Et(t){switch(t){case"configuration":return{reason:"setup"};case"chatter":case"history":case"sharing":case"changeEvent":case"unsupportedKind":case"customSetting":case"files":case"setup":case"platformCreated":case"metadata":case"notWritable":case"excludedByUser":return{reason:t};case"heldWithFiles":return{reason:"files",detail:Qe};case"notFound":case"notCustomSetting":return{reason:"missingInTarget"}}}function Rt(t){switch(t){case"platform":return{reason:"platformCreated"};case"setup":return{reason:"setup"};case"feature":case"parent":return{reason:"notWritable",detail:t};case"user":return{reason:"notWritable"}}}function St(t){if(t.createable!==!0||t.queryable!==!0)return;let e=t.updateable===!0,o=t.deletable===!0;if(!(e&&o))return!e&&!o?{reason:"createOnly"}:{reason:"createOnly",detail:e?Ft:It}}var It="noEdit",Ft="noDelete";function vt(t,e){return t.objectApiName<e.objectApiName?-1:t.objectApiName>e.objectApiName?1:0}function He(t,e,o,r={}){let n=yt(e,o,"clone",r),c=new Map(t.map(i=>[i.name.toLowerCase(),i])),a=new Map(e.map(i=>[i.name.toLowerCase(),i])),d=[],u=[],m=new Set,R=(i,h,b)=>{m.add(i.toLowerCase()),u.push({objectApiName:i,reason:h,...b!==void 0?{detail:b}:{}})};for(let i of t)a.has(i.name.toLowerCase())||R(i.name,"missingInTarget");for(let i of n.leftOut){let h=i.objectApiName.toLowerCase(),b=c.get(h);if(!b||m.has(h))continue;let S=a.get(h),y=Et(i.reason),C=h!==oe.toLowerCase();y.reason==="notWritable"&&C&&S?.createable!==!0&&r.createFacts&&(y=Rt(We(b.name,r.createFacts))),y.reason==="notWritable"&&C&&S&&(y=St(S)??y);let I=i.reason==="setup"&&S?.layoutable===!1&&!Ae(i.objectApiName);R(b.name,y.reason,I?Ct:y.detail??i.detail)}for(let i of n.candidates){let h=i.toLowerCase(),b=c.get(h);b&&(b.queryable!==!0?R(b.name,"notQueryable"):wt.has(h)?R(b.name,"files",Qe):d.push(b.name))}return d.sort(),u.sort(vt),{candidates:d,leftOut:u}}var he=1950,Xe=2e4,jt=1e6,Dt=18,Tt=200,At=new Set(["QUERY_TIMEOUT","OPERATION_TOO_LARGE","REQUEST_LIMIT_EXCEEDED","REQUEST_RUNNING_TOO_LONG","SERVER_UNAVAILABLE","UNKNOWN_EXCEPTION"]);function se(t){if(t instanceof Me||De(t))return!1;let e=je(x(t));return e===void 0?!1:!At.has(e)&&!e.startsWith("ERROR_HTTP_")}function Pt(t,e){let o=fe.has(t),r=[...e?[`(${e})`]:[],...o?["IsDeleted = false"]:[]];return{soql:`SELECT COUNT() FROM ${q(t)}${r.length>0?` WHERE ${r.join(" AND ")}`:""}`,all:o}}async function Ve(t,e){let o=0,r=!1,n=()=>r,c=async()=>{for(;!r&&o<t.length;){let a=o++;try{await e(t[a],a,n)}catch(d){throw r=!0,d}}};await Promise.all(Array.from({length:Math.min(6,t.length)},c))}async function Nt(t,e){try{return await t()}catch(o){if(o instanceof A||re(o)||se(o))throw o;return k.warn(`[forge-discover] whole org: describe of ${e} unanswered, asked again: ${x(o)}`),t()}}function Ye(t){if(!(t<=ue))throw new Error(`The source org lists ${t} objects a clone of the whole org leaves out, more than the ${ue} one graph says. Nothing was written. Clone the org in parts instead: a run from a record or from a query for each part.`)}var xt=de({name:Ce().min(1),count:Ee().int().nonnegative()});function Mt(t){let e=de({sObjects:Se(Re())}).safeParse(t);if(!e.success)return;let o=new Map;for(let r of e.data.sObjects){let n=xt.safeParse(r);n.success&&o.set(n.data.name,n.data.count)}return o}function _t(t){let e=new Map;for(let[o,r]of t)for(let n of r.fields){if(n.referenceTo.length===0)continue;let c=ee(n),a=c&&Z(o,n.name,n.nillable),d=te(n);for(let u of n.referenceTo){if(u===o||!t.has(u))continue;let m=`${u}|${o}`,R={sourceObject:u,targetObject:o,relationshipName:n.relationshipName??n.name,type:ne(o,n,t.get(u)?.childRelationships)?"master-detail":"lookup",required:a},i=e.get(m);if(!i){e.set(m,{edge:R,noneSettable:!c,insertOnly:d});continue}let h=R.type==="master-detail"&&i.edge.type==="lookup"?R:i.edge;i.edge={...h,required:i.edge.required===!0||a},i.noneSettable=i.noneSettable&&!c,i.insertOnly=i.insertOnly||d}}return[...e.values()].map(({edge:o,noneSettable:r,insertOnly:n})=>({...o,...r?{settable:!1}:{},...n?{insertOnly:!0}:{}}))}function Lt(t,e){let o=e.filter(qe),r=$e(t,o).reverse(),n=new Map;r.forEach((d,u)=>{for(let m of d)n.set(m,u)});let c=new Map;for(let d of o){let u=c.get(d.targetObject)??[];u.push(d.sourceObject),c.set(d.targetObject,u)}let a=r.map(()=>0);return r.forEach((d,u)=>{for(let m of d)for(let R of c.get(m)??[]){let i=n.get(R);i!==void 0&&i!==u&&(a[u]=Math.max(a[u],a[i]+1))}}),new Map(t.map(d=>[d,Math.min(Dt,1+a[n.get(d)??0])]))}async function ze(t,e,o){let r=ve(e);if(r!==void 0)throw new Error(r);let n=o?.signal;if(n?.aborted)return Y();try{return await kt(t,e,o)}catch(c){if(c instanceof A||n?.aborted)return Y();throw c}}async function kt(t,e,o){let r=o?.signal,n=s=>o?.onProgress?.(s),c=Date.now(),a=s=>l=>{if(l instanceof A)throw l;return k.warn(`[forge-discover] whole org: ${x(l)}`),s},{toolingObjects:d,recordCounts:u,createFacts:m}=t;n({phase:"listing",discoveredCount:0,queueRemaining:0});let[R,i,h,b,S]=await Promise.all([M(()=>t.describeGlobal(e.sourceOrgId,r),r),M(()=>t.describeGlobal(e.targetOrgId,r),r),d?M(()=>d(e.targetOrgId,r),r).catch(a([])):Promise.resolve([]),m?M(()=>m(e.targetOrgId),r).catch(a(void 0)):Promise.resolve(void 0),u?M(()=>u(e.sourceOrgId,r),r).catch(a(void 0)):Promise.resolve(void 0)]),y=Mt(S),C=e.excludedObjects??[],{candidates:I,leftOut:$}=He(R,i,h,{...b?{createFacts:b}:{},...C.length>0?{excluded:C}:{}}),N=[...$];Ye(N.length);let L=I.map(()=>{}),W=0;n({phase:"counting",discoveredCount:0,queueRemaining:I.length,total:I.length}),await Ve(I,async(s,l,p)=>{let f=y?.get(s),v=e.objectSoqlFilters?.[s];if(f!==void 0&&f>jt&&!v)L[l]={objectApiName:s,rows:f,approximate:!0};else try{let{soql:E,all:Q}=Pt(s,v),_=await M(()=>t.queryCount(e.sourceOrgId,E,r,Q?{all:!0}:void 0),r);if(p())return;_>0?L[l]={objectApiName:s,rows:_}:N.push({objectApiName:s,reason:"empty"})}catch(E){if(E instanceof A||re(E))throw E;if(p())return;se(E)?N.push({objectApiName:s,reason:"unreadable",detail:x(E)}):(k.warn(`[forge-discover] whole org: ${s} not counted, kept: ${x(E)}`),L[l]=f!==void 0&&f>0&&!v?{objectApiName:s,rows:f,approximate:!0}:{objectApiName:s,rows:0,unknown:!0})}W++,n({phase:"counting",objectApiName:s,discoveredCount:W,queueRemaining:I.length-W,total:I.length})});let D=L.filter(s=>s!==void 0);if(D.length>he)throw new Error(`The source org holds records in ${D.length} objects a clone of the whole org would take, more than the ${he} one run writes. Nothing was written. Leave ${D.length-he} of them out or more, or clone the org in parts instead: a run from a record or from a query for each part.`);let U=D.map(()=>{}),B=0;n({phase:"describing",discoveredCount:0,queueRemaining:D.length,total:D.length}),await Ve(D,async({objectApiName:s},l,p)=>{try{let f=await Nt(()=>M(()=>t.describeObject(e.sourceOrgId,s,r),r),s);if(p())return;U[l]=f}catch(f){if(f instanceof A||re(f))throw f;if(p())return;N.push({objectApiName:s,reason:"notDescribed",detail:x(f)})}B++,n({phase:"describing",objectApiName:s,discoveredCount:B,queueRemaining:D.length-B,total:D.length})}),await me();let w=new Map,z=new Map;D.forEach((s,l)=>{let p=U[l];p&&(w.set(s.objectApiName,p),z.set(s.objectApiName,s))});let G=_t(w);if(G.length>Xe)throw new Error(`The ${w.size} objects of the source org a clone of the whole org would take relate ${G.length} pairs of objects, more than the ${Xe} one run writes in order. Nothing was written. Clone the org in parts instead: a run from a record or from a query for each part.`);let g=[...w.keys()],j=Lt(g,G),P=g.map(s=>{let l=w.get(s),p=z.get(s),f=p.rows,v=t.detectPII(l.fields);return{objectApiName:s,...l.label?{label:l.label}:{},recordCount:f,...p.approximate?{recordCountApproximate:!0}:{},...p.unknown?{recordCountUnknown:!0}:{},fieldCount:l.fields.length,status:"idle",progress:0,included:!0,piiFields:v,anonymizeFields:e.anonymizePII?[...v]:[],level:j.get(s)??1,successCount:0,failureCount:0,errors:[],createableFieldCount:l.fields.filter(E=>E.type!=="id").length,estimatedSizeMB:f*V,estimatedApiCalls:Math.ceil(f/Tt),batchStrategy:"auto"}});Ye(N.length);let F=P.reduce((s,l)=>s+l.recordCount,0);return N.sort((s,l)=>s.objectApiName<l.objectApiName?-1:s.objectApiName>l.objectApiName?1:0),k.info(`[forge-discover] whole org: ${P.length} object(s), ${G.length} relation(s), ${N.length} left out, ${F} record(s), in ${Date.now()-c}ms`),{nodes:P,edges:G,totalRecords:F,estimatedSizeMB:F*V,estimatedDurationSeconds:F*ge,truncated:!1,leftOut:N}}export{fe as a,ot as b,zt as c,ne as d,st as e,it as f,at as g,lt as h,ut as i,Ue as j,yt as k,he as l,Xe as m,se as n,Ve as o,Mt as p,ze as q};
@@ -4,6 +4,6 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{g as A,k as S}from"./chunk-5WGA5CZB.mjs";import{e as k,f as w}from"./chunk-NWVVCZUK.mjs";import{tb as T,ub as h}from"./chunk-DPYTG6DM.mjs";import{mkdir as v,rename as D,writeFile as x}from"node:fs/promises";import*as f from"node:path";var y="CaseId",O=80;function $(e){let t=T.safeParse(e.choice);if(!t.success)return{ok:!1,refusals:t.error.issues.map(a=>({code:"choice-invalid",name:a.path.join("."),message:a.message}))};let n=t.data,s=A(e.catalog,n.agent);if(!s)return{ok:!1,refusals:[{code:"agent-absent",name:n.agent,message:`"${n.agent}" is not one of this org's agents`}]};let r=P(n,s,E(e.compiled.tests));if(r.length>0)return{ok:!1,refusals:r};let i=new Map(n.topics.map(a=>[a.packTopic,a])),c=S(s,y)?y:void 0,g=[],o=[];for(let a of e.compiled.tests){if(a.topicKey===null){if(n.guardTopic===null){o.push({test:a.key,reason:"no-guard-topic",message:`"${a.utterance}" is on no topic of the scenario, and no topic of the agent is chosen to decline it: the test is left out`});continue}g.push({key:a.key,utterance:a.utterance,expectedTopic:n.guardTopic,expectedActions:[],expectedOutcome:a.expectedOutcome,contextVariables:[]});continue}let u=i.get(a.topicKey),p=[];if(a.openCase){let m=e.openCaseIds[a.openCase.caseKey];if(m===void 0){o.push({test:a.key,reason:"case-not-written",message:`The case ${a.openCase.caseKey} the test is about was not written by the run: the test is left out`});continue}c!==void 0&&p.push({name:c,value:m})}g.push({key:a.key,utterance:a.utterance,expectedTopic:u.agentTopic,expectedActions:[...u.actions],expectedOutcome:j(a),contextVariables:p})}return g.length===0?{ok:!1,refusals:[{code:"no-test-left",name:e.compiled.packId,message:"No test of the scenario is left to write: "+o.map(a=>a.message).join("; ")}]}:{ok:!0,spec:{name:M(e.compiled.template.name),description:F(e.compiled.packId,e.compiled.seed,e.runId),subjectName:s.name,testCases:g},choice:n,leftOut:o,...c!==void 0?{contextVariable:c}:{}}}function E(e){return[...new Set(e.flatMap(t=>t.topicKey===null?[]:[t.topicKey]))]}function P(e,t,n){let s=[],r=new Map(t.topics.map(o=>[o.name,o])),i=new Set(t.topics.flatMap(o=>o.actions.map(a=>a.name))),c=o=>({code:"topic-absent",name:o,message:`"${o}" is not a topic of the agent ${t.name}`});for(let o of e.topics){n.includes(o.packTopic)||s.push({code:"pack-topic-unknown",name:o.packTopic,message:`"${o.packTopic}" is not a topic of the scenario`});let a=r.get(o.agentTopic);if(!a){s.push(c(o.agentTopic));continue}let u=new Set(a.actions.map(p=>p.name));for(let p of o.actions)u.has(p)||s.push(i.has(p)?{code:"action-not-of-topic",name:p,message:`"${p}" is not an action of the topic ${a.name}, which the agent answers "${o.packTopic}" from`}:{code:"action-absent",name:p,message:`"${p}" is not an action of the agent ${t.name}`})}let g=new Set(e.topics.map(o=>o.packTopic));for(let o of n)g.has(o)||s.push({code:"pack-topic-unmatched",name:o,message:`The topic "${o}" of the scenario is matched to no topic of the agent`});return e.guardTopic!==null&&!r.has(e.guardTopic)&&s.push(c(e.guardTopic)),s}function j(e){if(!e.article)return e.expectedOutcome;let t=e.article.facts.length>0?`, which states: ${e.article.facts.join("; ")}`:"";return`${e.expectedOutcome} The answer draws on the article "${e.article.title}"${t}.`}function M(e){let t=" (SandForge)",n=O-t.length;return`${e.length>n?e.slice(0,n).trimEnd():e}${t}`}function F(e,t,n){let s=n!==void 0?`, written by the seed run ${n}`:"";return`SandForge scenario ${e}, seed ${t}${s}. Its cases are about the records that run wrote: once it is removed, they are about none.`}var C="specs",L=80,V=10;function K(e,t){return G(h(e,t))}function W(e,t,n){let s=n==="agentforce-studio"?"ngtTestSpec":"testSpec";return`${b(e)}-${b(t)}-sandforge-${s}.yaml`}function z(e,t){let n=c=>c.replace(/[^A-Za-z0-9]+/g,"_").replace(/^_+|_+$/g,""),s=`${n(t)}_SandForge`,r=n(e);/^[A-Za-z]/.test(r)||(r=`Agent_${r}`.replace(/_+$/,""));let i=L-s.length-1;return r=r.slice(0,i).replace(/_+$/,""),`${r}_${s}`}function Z(e){let t=e.runner==="agentforce-studio"?["--test-runner","agentforce-studio"]:[],n=["sf","agent","test","create","--spec",e.specPath,"--api-name",e.apiName,...t,"-o",e.alias],s=["sf","agent","test","run","--api-name",e.apiName,"--wait",String(V),...t,"-o",e.alias];return{create:{argv:n,line:R(n)},run:{argv:s,line:R(s)}}}function te(){return{mkdir:async e=>{await v(e,{recursive:!0})},writeNew:async(e,t)=>{try{return await x(e,t,{encoding:"utf8",flag:"wx"}),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}},replace:async(e,t)=>{let n=`${e}.${process.pid}.tmp`;await x(n,t,"utf8"),await D(n,e)}}}async function X(e,t){let n=W(t.model.subjectName,t.packId,t.runner),s=`${C}/${n}`,r=f.join(t.projectDir,C,n),i=K(t.model,t.runner);if(await e.mkdir(f.dirname(r)),t.overwrite===!0)await e.replace(r,i);else if(!await e.writeNew(r,i))return{kind:"exists",path:r,specPath:s};let c=z(t.model.subjectName,t.packId);return{kind:"written",path:r,specPath:s,apiName:c,commands:Z({specPath:s,apiName:c,alias:t.alias,runner:t.runner})}}async function ne(e,t){let n=w(t.sidecar,t.pack);if(!n.ok)return{kind:"refused",refusals:[{code:"pack-changed",name:t.pack.id,message:n.message}]};let s=$({compiled:n.compiled,catalog:t.catalog,choice:t.choice,openCaseIds:t.sidecar.openCases,runId:t.sidecar.runId});if(!s.ok)return{kind:"refused",refusals:s.refusals};let{choice:r}=s,i=await X(e,{projectDir:t.projectDir,model:s.spec,runner:r.runner,packId:t.pack.id,alias:t.alias,...t.overwrite!==void 0?{overwrite:t.overwrite}:{}});return i.kind==="exists"?i:{...i,leftOut:s.leftOut,sidecar:k(t.sidecar,r)}}function G(e){return`${l(e,0).join(`
7
+ import{e as k,f as w}from"./chunk-Z42PHCVZ.mjs";import{g as A,k as S}from"./chunk-H4OBZIX3.mjs";import{Fb as T,Gb as h}from"./chunk-ZQO5PDX5.mjs";import{mkdir as v,rename as D,writeFile as x}from"node:fs/promises";import*as f from"node:path";var y="CaseId",O=80;function $(e){let t=T.safeParse(e.choice);if(!t.success)return{ok:!1,refusals:t.error.issues.map(a=>({code:"choice-invalid",name:a.path.join("."),message:a.message}))};let n=t.data,s=A(e.catalog,n.agent);if(!s)return{ok:!1,refusals:[{code:"agent-absent",name:n.agent,message:`"${n.agent}" is not one of this org's agents`}]};let r=P(n,s,E(e.compiled.tests));if(r.length>0)return{ok:!1,refusals:r};let i=new Map(n.topics.map(a=>[a.packTopic,a])),c=S(s,y)?y:void 0,g=[],o=[];for(let a of e.compiled.tests){if(a.topicKey===null){if(n.guardTopic===null){o.push({test:a.key,reason:"no-guard-topic",message:`"${a.utterance}" is on no topic of the scenario, and no topic of the agent is chosen to decline it: the test is left out`});continue}g.push({key:a.key,utterance:a.utterance,expectedTopic:n.guardTopic,expectedActions:[],expectedOutcome:a.expectedOutcome,contextVariables:[]});continue}let u=i.get(a.topicKey),p=[];if(a.openCase){let m=e.openCaseIds[a.openCase.caseKey];if(m===void 0){o.push({test:a.key,reason:"case-not-written",message:`The case ${a.openCase.caseKey} the test is about was not written by the run: the test is left out`});continue}c!==void 0&&p.push({name:c,value:m})}g.push({key:a.key,utterance:a.utterance,expectedTopic:u.agentTopic,expectedActions:[...u.actions],expectedOutcome:j(a),contextVariables:p})}return g.length===0?{ok:!1,refusals:[{code:"no-test-left",name:e.compiled.packId,message:"No test of the scenario is left to write: "+o.map(a=>a.message).join("; ")}]}:{ok:!0,spec:{name:M(e.compiled.template.name),description:F(e.compiled.packId,e.compiled.seed,e.runId),subjectName:s.name,testCases:g},choice:n,leftOut:o,...c!==void 0?{contextVariable:c}:{}}}function E(e){return[...new Set(e.flatMap(t=>t.topicKey===null?[]:[t.topicKey]))]}function P(e,t,n){let s=[],r=new Map(t.topics.map(o=>[o.name,o])),i=new Set(t.topics.flatMap(o=>o.actions.map(a=>a.name))),c=o=>({code:"topic-absent",name:o,message:`"${o}" is not a topic of the agent ${t.name}`});for(let o of e.topics){n.includes(o.packTopic)||s.push({code:"pack-topic-unknown",name:o.packTopic,message:`"${o.packTopic}" is not a topic of the scenario`});let a=r.get(o.agentTopic);if(!a){s.push(c(o.agentTopic));continue}let u=new Set(a.actions.map(p=>p.name));for(let p of o.actions)u.has(p)||s.push(i.has(p)?{code:"action-not-of-topic",name:p,message:`"${p}" is not an action of the topic ${a.name}, which the agent answers "${o.packTopic}" from`}:{code:"action-absent",name:p,message:`"${p}" is not an action of the agent ${t.name}`})}let g=new Set(e.topics.map(o=>o.packTopic));for(let o of n)g.has(o)||s.push({code:"pack-topic-unmatched",name:o,message:`The topic "${o}" of the scenario is matched to no topic of the agent`});return e.guardTopic!==null&&!r.has(e.guardTopic)&&s.push(c(e.guardTopic)),s}function j(e){if(!e.article)return e.expectedOutcome;let t=e.article.facts.length>0?`, which states: ${e.article.facts.join("; ")}`:"";return`${e.expectedOutcome} The answer draws on the article "${e.article.title}"${t}.`}function M(e){let t=" (SandForge)",n=O-t.length;return`${e.length>n?e.slice(0,n).trimEnd():e}${t}`}function F(e,t,n){let s=n!==void 0?`, written by the seed run ${n}`:"";return`SandForge scenario ${e}, seed ${t}${s}. Its cases are about the records that run wrote: once it is removed, they are about none.`}var C="specs",L=80,V=10;function K(e,t){return G(h(e,t))}function W(e,t,n){let s=n==="agentforce-studio"?"ngtTestSpec":"testSpec";return`${b(e)}-${b(t)}-sandforge-${s}.yaml`}function z(e,t){let n=c=>c.replace(/[^A-Za-z0-9]+/g,"_").replace(/^_+|_+$/g,""),s=`${n(t)}_SandForge`,r=n(e);/^[A-Za-z]/.test(r)||(r=`Agent_${r}`.replace(/_+$/,""));let i=L-s.length-1;return r=r.slice(0,i).replace(/_+$/,""),`${r}_${s}`}function Z(e){let t=e.runner==="agentforce-studio"?["--test-runner","agentforce-studio"]:[],n=["sf","agent","test","create","--spec",e.specPath,"--api-name",e.apiName,...t,"-o",e.alias],s=["sf","agent","test","run","--api-name",e.apiName,"--wait",String(V),...t,"-o",e.alias];return{create:{argv:n,line:R(n)},run:{argv:s,line:R(s)}}}function te(){return{mkdir:async e=>{await v(e,{recursive:!0})},writeNew:async(e,t)=>{try{return await x(e,t,{encoding:"utf8",flag:"wx"}),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}},replace:async(e,t)=>{let n=`${e}.${process.pid}.tmp`;await x(n,t,"utf8"),await D(n,e)}}}async function X(e,t){let n=W(t.model.subjectName,t.packId,t.runner),s=`${C}/${n}`,r=f.join(t.projectDir,C,n),i=K(t.model,t.runner);if(await e.mkdir(f.dirname(r)),t.overwrite===!0)await e.replace(r,i);else if(!await e.writeNew(r,i))return{kind:"exists",path:r,specPath:s};let c=z(t.model.subjectName,t.packId);return{kind:"written",path:r,specPath:s,apiName:c,commands:Z({specPath:s,apiName:c,alias:t.alias,runner:t.runner})}}async function ne(e,t){let n=w(t.sidecar,t.pack);if(!n.ok)return{kind:"refused",refusals:[{code:"pack-changed",name:t.pack.id,message:n.message}]};let s=$({compiled:n.compiled,catalog:t.catalog,choice:t.choice,openCaseIds:t.sidecar.openCases,runId:t.sidecar.runId});if(!s.ok)return{kind:"refused",refusals:s.refusals};let{choice:r}=s,i=await X(e,{projectDir:t.projectDir,model:s.spec,runner:r.runner,packId:t.pack.id,alias:t.alias,...t.overwrite!==void 0?{overwrite:t.overwrite}:{}});return i.kind==="exists"?i:{...i,leftOut:s.leftOut,sidecar:k(t.sidecar,r)}}function G(e){return`${l(e,0).join(`
8
8
  `)}
9
9
  `}function l(e,t){let n=" ".repeat(t),s=[];for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let c=`${n}${J(r)}:`;Array.isArray(i)?i.length===0?s.push(`${c} []`):s.push(c,...I(i,t+2)):d(i)?Object.values(i).every(g=>g===void 0)?s.push(`${c} {}`):s.push(c,...l(i,t+2)):s.push(`${c} ${_(i)}`)}return s}function I(e,t){let n=" ".repeat(t),s=[];for(let r of e){let i=Array.isArray(r)?r.length===0?void 0:I(r,t+2):d(r)&&Object.values(r).some(c=>c!==void 0)?l(r,t+2):void 0;if(i===void 0){s.push(`${n}- ${Array.isArray(r)?"[]":d(r)?"{}":_(r)}`);continue}s.push(`${n}- ${i[0].slice(t+2)}`,...i.slice(1))}return s}function d(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function J(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)?e:N(e)}function _(e){if(typeof e=="string")return N(e);if(typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return String(e);if(e===null)return"null";throw new TypeError(`No YAML scalar for ${typeof e}`)}function N(e){return JSON.stringify(e).replace(/[\u007f-\u009f\u2028\u2029\ufeff\ufffe\uffff]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}function b(e){return e.replace(/[^A-Za-z0-9_-]/g,"_")}function R(e){return e.map(t=>/^[A-Za-z0-9_./:@=+,-]+$/.test(t)?t:`"${t.replace(/(["\\])/g,"\\$1")}"`).join(" ")}export{C as a,V as b,K as c,W as d,z as e,Z as f,te as g,X as h,ne as i,G as j};
@@ -4,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{k as be}from"./chunk-YCSFP6ER.mjs";import{a as ge,c as B,d as we}from"./chunk-GYKNCYES.mjs";import{b as fe,e as pe,i as me,j as D,l as S}from"./chunk-YOGMP72T.mjs";import{b as ue}from"./chunk-YIGFYZQY.mjs";import{g as P,j as te,l as T,m as ie,p as ne}from"./chunk-GWRKS3AL.mjs";import{A as ce,B as le,v as se,x as ae,z as de}from"./chunk-6SEDOIO3.mjs";import{j as oe}from"./chunk-ETT5GP4P.mjs";import{A as re,x as I}from"./chunk-E2YJVSX6.mjs";import{v as ee}from"./chunk-T26C576X.mjs";import{e as X}from"./chunk-BNO5GIJ6.mjs";import{c as Z}from"./chunk-6IGEASOF.mjs";import{g as V,h as Y,i as q,q as Q}from"./chunk-EAFLDSQ2.mjs";import{b as K}from"./chunk-CA5NAXSU.mjs";import{zd as J}from"./chunk-DPYTG6DM.mjs";var ve="No record would be read or written.";function je(t,e){return{code:"RUN_WRITING",message:`${e.operation==="take"?`A checkpoint of ${t} is being taken`:e.operation==="rewind"?`A rewind is writing to ${t}`:e.operation==="undo"?`An undo is writing to ${t}`:e.operation==="empty"?`An emptying of its objects is writing to ${t}`:`SandForge is deleting checkpoints of ${t}`} (process ${e.pid} on ${e.host}): rewind once it has ended. ${ve}`}}function Ae(t){return{query:e=>t.query(e),queryMore:e=>t.queryMore(e)}}function Ee(t){let e=t.objects.find(r=>r.objectApiName===V);if(e===void 0)return 0;let n=e.toBringBack;return n.inBin+n.withParent+n.deletedWhileTaken}function Pe(t,e){return{objectsRead:[...t],objects:[],unread:["flows","triggers","processes","workflowRules"].map(n=>({part:n,reason:e})),conditionsNotRead:0,conditionsBound:0,requests:0}}function Te(t,e){let n=new Map,r;return{bodies:n,global:()=>r,describeGlobal:()=>r??=t.describeGlobal(),reader:{lane:()=>e.lane(),tooling:i=>e.tooling(i),calls:()=>e.calls(),describe:async(i,a)=>{let d=await e.describe(i,a);return"body"in d&&n.set(i,d.body),d}}}}async function Je(t,e){let{org:n,signal:r}=t,{checkpoint:i,orgName:a}=e,d,p=await ue(Ae(n),{act:"preview",orgName:a,registered:e.registered,username:e.username,organizationId:i.org.organizationId,customSettings:Q(i)},{userId:async()=>d=await n.userId()});if(!p.allowed)return{previewed:!1,refusal:p.refusal};let m=await de(n,a),g=Te(n,oe(n,r)),ke=await fe({grants:p.grants,...d!==void 0?{userId:d}:{},username:e.username,checkpoint:i,reader:g.reader}),h=await n.serverTime(),R=re("pv",(t.now??(()=>new Date))()),c=await pe({checkpoint:i,folder:e.folder,reader:g.reader,describeGlobal:g.describeGlobal,previewId:R,readAt:h,queryAllFiles:p.queryAllFiles,access:ke,...r?{signal:r}:{}}),O=m.fileStorage;c.files!==void 0&&O!==void 0&&(c.files.storage.remaining=O.remaining*1048576);let w=e.objects!==void 0?new Set(e.objects):void 0,l=me(c,w),b=ge(l),F=w===void 0&&i.scope.mode==="picked"&&c.objects.some(o=>o.outside.length>0),ye=F&&e.acceptOutside===!1,y;if(w!==void 0||ye){y=await S({checkpoint:i,previewDir:I(e.folder,R),readAt:h,...w!==void 0?{objects:w}:{},acceptOutside:e.acceptOutside===!0,heldRows:D(i,e.folder),...r?{signal:r}:{}});for(let{objectApiName:o}of y.acts)b.includes(o)||b.push(o)}let s;if(b.length>0&&t.readAutomation)try{s=await t.readAutomation(b)}catch(o){s=Pe(b,K(o))}let C,k=0,G=y?B(c,y):l,v=we(G),u=s&&e.muteAutomation===!0?ee(s,J(v)):void 0,j=s&&u&&u.plan.assign.length>0&&t.mute?await be(t.mute,s,v):void 0,he=j&&"refusal"in j?j.refusal:void 0;if(s){let o=await ne({act:"rewind",orgName:a,automation:s,steps:v,...u?{plan:u.plan}:{},accepted:!1,mayMute:u===void 0,read:()=>Z(n)});C=o.gate.deliverability,k=o.ofRun.read?.requests??0}let M=g.global(),N=M?new Set((await X({describeGlobal:()=>M})).keys()):void 0,W=new Set(i.objects.map(({objectApiName:o})=>o.toLowerCase()));if(i.files!==void 0)for(let o of[Y,q])W.add(o.toLowerCase());let _=new Map;for(let[o,Oe]of g.bodies)_.set(o,se(Oe,{inCheckpoint:W,...N?{worked:N}:{}}));let L=ae({objects:i.objects,diff:l,automationRequests:s?.requests??0,...k>0?{deliverabilityRequests:k}:{},relationships:_,...e.reusesPreview===!0?{reusesPreview:!0}:{}}),Re={...L,apiRequestsLeft:m.remaining},$=P(G.objects),f=u?.automation??s,A=f?T($,f,m.emails):[],x=f?te($,f):void 0,U=F&&e.acceptOutside===void 0&&f?T(P(B(c,await S({checkpoint:i,previewDir:I(e.folder,R),readAt:h,acceptOutside:!1,heldRows:D(i,e.folder),...r?{signal:r}:{}})).objects),f,m.emails):void 0,E=t.store.heldBy(i.org.organizationId),z=E===void 0?await t.runWriting?.(p.org.id):void 0,H=E!==void 0?je(a,E):z!==void 0?{code:"RUN_WRITING",message:z}:he??ce("rewind",{run:L.apiRequests-k,deliverability:k},m,a)??ie("rewind",A,a)??(l.files!==void 0?le("rewind",{files:Ee(l),bytes:l.files.storage.bringBack},O?.remaining,a):void 0);return{previewed:!0,diff:c,...s?{automation:s}:{},...A.length>0?{emails:A}:{},...U?{emailsKeepingOutside:U}:{},...x!==void 0?{emailsUncounted:x}:{},...C?{deliverability:C}:{},estimate:Re,...H?{refusal:H}:{}}}export{Je as a};
7
+ import{k as be}from"./chunk-JESRFE2Z.mjs";import{a as ge,c as B,d as we}from"./chunk-CBL42DUU.mjs";import{b as fe,e as pe,i as me,j as D,l as S}from"./chunk-MKTXJCXN.mjs";import{b as ue}from"./chunk-DBBPDSFN.mjs";import{g as P,j as te,l as T,m as ie,p as ne}from"./chunk-VZT4E2OJ.mjs";import{A as ce,B as le,v as se,x as ae,z as de}from"./chunk-O2PUGRNW.mjs";import{j as oe}from"./chunk-SAMWHL22.mjs";import{A as re,x as I}from"./chunk-J24TIGSI.mjs";import{d as ee}from"./chunk-HKUWHVI7.mjs";import{e as X}from"./chunk-VPDEJGPS.mjs";import{c as Z}from"./chunk-JQZTMFO7.mjs";import{g as V,h as Y,i as q,q as Q}from"./chunk-L4INJ5TZ.mjs";import{b as K}from"./chunk-CA5NAXSU.mjs";import{Ld as J}from"./chunk-ZQO5PDX5.mjs";var ve="No record would be read or written.";function je(t,e){return{code:"RUN_WRITING",message:`${e.operation==="take"?`A checkpoint of ${t} is being taken`:e.operation==="rewind"?`A rewind is writing to ${t}`:e.operation==="undo"?`An undo is writing to ${t}`:e.operation==="empty"?`An emptying of its objects is writing to ${t}`:`SandForge is deleting checkpoints of ${t}`} (process ${e.pid} on ${e.host}): rewind once it has ended. ${ve}`}}function Ae(t){return{query:e=>t.query(e),queryMore:e=>t.queryMore(e)}}function Ee(t){let e=t.objects.find(r=>r.objectApiName===V);if(e===void 0)return 0;let n=e.toBringBack;return n.inBin+n.withParent+n.deletedWhileTaken}function Pe(t,e){return{objectsRead:[...t],objects:[],unread:["flows","triggers","processes","workflowRules"].map(n=>({part:n,reason:e})),conditionsNotRead:0,conditionsBound:0,requests:0}}function Te(t,e){let n=new Map,r;return{bodies:n,global:()=>r,describeGlobal:()=>r??=t.describeGlobal(),reader:{lane:()=>e.lane(),tooling:i=>e.tooling(i),calls:()=>e.calls(),describe:async(i,a)=>{let d=await e.describe(i,a);return"body"in d&&n.set(i,d.body),d}}}}async function Je(t,e){let{org:n,signal:r}=t,{checkpoint:i,orgName:a}=e,d,p=await ue(Ae(n),{act:"preview",orgName:a,registered:e.registered,username:e.username,organizationId:i.org.organizationId,customSettings:Q(i)},{userId:async()=>d=await n.userId()});if(!p.allowed)return{previewed:!1,refusal:p.refusal};let m=await de(n,a),g=Te(n,oe(n,r)),ke=await fe({grants:p.grants,...d!==void 0?{userId:d}:{},username:e.username,checkpoint:i,reader:g.reader}),h=await n.serverTime(),R=re("pv",(t.now??(()=>new Date))()),c=await pe({checkpoint:i,folder:e.folder,reader:g.reader,describeGlobal:g.describeGlobal,previewId:R,readAt:h,queryAllFiles:p.queryAllFiles,access:ke,...r?{signal:r}:{}}),O=m.fileStorage;c.files!==void 0&&O!==void 0&&(c.files.storage.remaining=O.remaining*1048576);let w=e.objects!==void 0?new Set(e.objects):void 0,l=me(c,w),b=ge(l),F=w===void 0&&i.scope.mode==="picked"&&c.objects.some(o=>o.outside.length>0),ye=F&&e.acceptOutside===!1,y;if(w!==void 0||ye){y=await S({checkpoint:i,previewDir:I(e.folder,R),readAt:h,...w!==void 0?{objects:w}:{},acceptOutside:e.acceptOutside===!0,heldRows:D(i,e.folder),...r?{signal:r}:{}});for(let{objectApiName:o}of y.acts)b.includes(o)||b.push(o)}let s;if(b.length>0&&t.readAutomation)try{s=await t.readAutomation(b)}catch(o){s=Pe(b,K(o))}let C,k=0,G=y?B(c,y):l,v=we(G),u=s&&e.muteAutomation===!0?ee(s,J(v)):void 0,j=s&&u&&u.plan.assign.length>0&&t.mute?await be(t.mute,s,v):void 0,he=j&&"refusal"in j?j.refusal:void 0;if(s){let o=await ne({act:"rewind",orgName:a,automation:s,steps:v,...u?{plan:u.plan}:{},accepted:!1,mayMute:u===void 0,read:()=>Z(n)});C=o.gate.deliverability,k=o.ofRun.read?.requests??0}let M=g.global(),N=M?new Set((await X({describeGlobal:()=>M})).keys()):void 0,W=new Set(i.objects.map(({objectApiName:o})=>o.toLowerCase()));if(i.files!==void 0)for(let o of[Y,q])W.add(o.toLowerCase());let _=new Map;for(let[o,Oe]of g.bodies)_.set(o,se(Oe,{inCheckpoint:W,...N?{worked:N}:{}}));let L=ae({objects:i.objects,diff:l,automationRequests:s?.requests??0,...k>0?{deliverabilityRequests:k}:{},relationships:_,...e.reusesPreview===!0?{reusesPreview:!0}:{}}),Re={...L,apiRequestsLeft:m.remaining},$=P(G.objects),f=u?.automation??s,A=f?T($,f,m.emails):[],x=f?te($,f):void 0,U=F&&e.acceptOutside===void 0&&f?T(P(B(c,await S({checkpoint:i,previewDir:I(e.folder,R),readAt:h,acceptOutside:!1,heldRows:D(i,e.folder),...r?{signal:r}:{}})).objects),f,m.emails):void 0,E=t.store.heldBy(i.org.organizationId),z=E===void 0?await t.runWriting?.(p.org.id):void 0,H=E!==void 0?je(a,E):z!==void 0?{code:"RUN_WRITING",message:z}:he??ce("rewind",{run:L.apiRequests-k,deliverability:k},m,a)??ie("rewind",A,a)??(l.files!==void 0?le("rewind",{files:Ee(l),bytes:l.files.storage.bringBack},O?.remaining,a):void 0);return{previewed:!0,diff:c,...s?{automation:s}:{},...A.length>0?{emails:A}:{},...U?{emailsKeepingOutside:U}:{},...x!==void 0?{emailsUncounted:x}:{},...C?{deliverability:C}:{},estimate:Re,...H?{refusal:H}:{}}}export{Je as a};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{y as he}from"./chunk-SZGGFST2.mjs";import{v as le,x as F}from"./chunk-IRZJU2PG.mjs";import{i as ce,j as x,k as de,l as pe}from"./chunk-Y4TDVDP2.mjs";import{e as C,i as ae,k as D,l as se}from"./chunk-5K2I2DMP.mjs";import{d as j,f as oe,xb as re,yb as ie}from"./chunk-3HEMJTAP.mjs";import{c as ne}from"./chunk-QROPNEGY.mjs";import{a as v}from"./chunk-SCKUIE3R.mjs";import{$a as J}from"./chunk-ISSP2FZ5.mjs";import{L as te,e as X,k as Q,z as ee}from"./chunk-J24TIGSI.mjs";import{mc as S}from"./chunk-JFNLKHY6.mjs";import{Ra as Z,cb as V}from"./chunk-ZQO5PDX5.mjs";import{existsSync as $e,readFileSync as ve}from"node:fs";import{hostname as be}from"node:os";import{join as ge,resolve as T}from"node:path";var Ae=["--custom-settings","--mask","--keep-contact-points","--no-real-data"],Ee=["--objects","--exclude-object","--owners","--owner-map","--link","--replay-config"],Ie=["--again","--accept-emails","--max-records",...j.switches,...j.values],Oe=["--preview","--sweep","--sweep-list",...re,"--include-changed"],Ne=/^[A-Za-z][A-Za-z0-9_]{0,79}$/,A=/^00D[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/,me=e=>Z.safeParse(e).success,Se={ownerMap:"--owner-map",objects:"--objects",excluded:"--exclude-object",link:"--link"};function Rt(e,t){let n=c=>e.includes(c),o=c=>{let p=[];for(let w=1;w<e.length;w++){if(e[w]!==c)continue;let $=e[w+1];if($===void 0||$.startsWith("--"))return t(`${c} wants a value.`);p.push($),w++}return p},r=c=>{let p=o(c);return p.length>1&&t(`${c} is given ${p.length} times: give it once.`),p[0]},s=c=>{let p=r(c);if(p!==void 0)return/^\d{1,15}$/.test(p)||t(`${c} takes a whole number, not "${p}".`),Number(p)},d=["--dry-run","--verify","--remove"].filter(n);d.length>1&&t(`Give one of --dry-run, --verify and --remove, not ${d.join(" and ")}. Nothing was run.`);let i=n("--dry-run")?"dryRun":n("--verify")?"verify":n("--remove")?"remove":"replay",a=c=>c.filter(n);if(i==="verify"||i==="remove"){let c=a([...Ae,...Ee]);c.length>0&&t(`${c.join(", ")} ${c.length===1?"is a choice":"are choices"} of a replay and its dry run: --verify reads the choices its last replay was made with, and --remove takes back what it wrote. Nothing was run.`);let p=a(Ie);p.length>0&&t(`${p.join(", ")} goes with a replay or its dry run, not with --${i}. Nothing was run.`)}if(i!=="remove"){let c=a(Oe);c.length>0&&t(`${c.join(", ")} goes with --remove. Nothing was run.`)}n("--sweep")&&n("--sweep-list")&&t("--sweep deletes and --sweep-list only lists: give one of them. Nothing was run."),n("--preview")&&n("--sweep-list")&&t("--preview deletes nothing, and --sweep-list lists what a sweep would take: give --preview without it, or with --sweep. Nothing was run.");let u=ie(e);if("refusal"in u&&t(`${u.refusal} Nothing was run.`),i==="verify"){let c=a(["--mute-automation","--accept-automation"]);c.length>0&&t(`${c.join(", ")} goes with a replay or its removal: a verification only reads. Nothing was run.`)}let m=r("--checkpoint"),f=r("--file");if(m===void 0&&f===void 0)return t("replay needs --checkpoint <id|name> (list names them) or --file <.sfcheckpoint>. Run with --help.");m!==void 0&&f!==void 0&&t("Give --checkpoint or --file, not both. Nothing was run.");let h=r("--from");if(h!==void 0&&m===void 0&&t("--from goes with --checkpoint <name>: it names the org the checkpoint was taken of."),m!==void 0&&!me(m)&&h===void 0&&t(`--checkpoint '${m}' is not a checkpoint's id: a name names one of an org's checkpoints, so give --from <alias|username|00D\u2026>, the org it was taken of, or its id ("${v("checkpoint")} list" names them). Nothing was run.`),f===void 0){let c=a(["--key-env","--keep-days"]);c.length>0&&t(`${c.join(" and ")} goes with --file. Nothing was run.`)}let k=r("--target")??t("replay needs --target <alias>, the org the checkpoint's records go into. Run with --help."),R=o("--objects").flatMap(c=>c.split(",").map(p=>p.trim()).filter(p=>p!=="")),g=o("--exclude-object");for(let[c,p]of[["--objects",R],["--exclude-object",g]]){let w=p.find($=>!Ne.test($));w!==void 0&&t(`${c} takes objects' API names, not "${w}".`)}let E=c=>c.filter((p,w)=>c.findIndex($=>$.toLowerCase()===p.toLowerCase())===w),I=r("--owners")??"same";I!=="same"&&I!=="me"&&t(`--owners takes same or me, not "${I}".`);let we=o("--link").map(c=>{let p=/^([A-Za-z][A-Za-z0-9_]*)=([A-Za-z0-9_,]+)$/.exec(c);return p?{objectApiName:p[1],fields:p[2].split(",").filter(w=>w!=="")}:t(`--link takes Object=Field or Object=Field,Field \u2014 the fields a record of the other org is found by \u2014, not "${c}".`)}),O=r("--owner-map"),Y=O!==void 0?ye("--owner-map",O,t):void 0,Re={owners:I,...Y!==void 0?{ownerMap:Y}:{},customSettings:n("--custom-settings"),mask:n("--mask"),contactPoints:n("--keep-contact-points")?"kept":"neutralized",objects:E(R),excluded:E(g),link:we,...n("--no-real-data")?{noRealData:!0}:{}},P=V.safeParse(Re);if(!P.success){let c=P.error.issues[0],p=String(c?.path[0]??"");return t(`${Se[p]??p}: ${c?.message??"not read"}. Nothing was run.`)}let K=P.data,N=r("--replay-config"),H=N!==void 0?Ce(N,K,t):void 0,_=s("--max-records");_===0&&t('--max-records takes a whole number of 1 or more, not "0". Nothing was run.');let G=Fe(r("--key-env"),t),q=oe(e);return{action:i,...m!==void 0?{checkpoint:m}:{},...h!==void 0?{from:h}:{},...f!==void 0?{file:T(f)}:{},...G!==void 0?{keyEnv:G}:{},keepDays:s("--keep-days")??X,target:k,choices:K,...O!==void 0?{ownerMapFile:T(O)}:{},...H!==void 0?{config:H}:{},...N!==void 0?{configFile:T(N)}:{},again:n("--again"),muteAutomation:n("--mute-automation"),acceptAutomation:n("--accept-automation"),acceptEmails:n("--accept-emails"),...q!==void 0?{checkpointFirst:q}:{},..._!==void 0?{maxRecords:_}:{},preview:n("--preview"),sweep:n("--sweep"),sweepList:n("--sweep-list"),...u,includeChanged:n("--include-changed"),yes:n("--yes")}}function $t(e,t){let n=e.flatMap((r,s)=>r==="--target"?[e[s+1]]:[]);n.length>1&&t(`--target is given ${n.length} times: give it once.`);let o=n[0];return o!==void 0?{target:o}:{}}function ye(e,t,n){try{return JSON.parse(ve(t,"utf8"))}catch(o){return n(`${e}: ${t} does not read as JSON (${o instanceof Error?o.message:String(o)}). Nothing was run.`)}}function Ce(e,t,n){let o=ye("--replay-config",e,n),r=J.safeParse({targetOrgId:"command-line",replay:{organizationId:"00D000000000000AAA",checkpointId:"ck-20000101-000000-0000",choices:t,config:o}});if(!r.success){let s=r.error.issues[0],d=(s?.path??[]).slice(2).join(".");return n(`--replay-config: ${d!==""?`${d}: `:""}${s?.message??"not read"}. It takes the load\u2019s part of a Frozen project\u2019s configuration: requiredFieldDefaults, requiredLookupPlaceholders, picklistRules, defaultPicklistRule, identityKeys, undeletableObjects, duplicateErrorPatterns, mockDetection, protectedOrgIds. Nothing was run.`)}return o}function Fe(e,t){if(e!==void 0)return!/^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(e)||C(e)!==void 0?t("--key-env takes the name of an environment variable that holds the key, never the key: a key on the command line stays in the shell\u2019s history and the list of processes. Nothing was run."):e}var ze="cli-store.json";function W(e,t){return t?ge(e,".replays"):ce()}var y=class extends Error{constructor(n,o=1){super(n.message);this.refusal=n;this.code=o;this.name="ReplayStop"}refusal;code};function ke(e){try{return new x({root:e})}catch(t){throw new y({code:"STORE_REFUSED",message:`The replays cannot be kept in ${e}: ${t instanceof Error?t.message:String(t)} Name a store outside any repository with --store <folder>. Nothing was read or written.`})}}function B(e,t){let n=D(e);if(!$e(n))return;let o=te({root:n,...t!==void 0?{locksDir:t}:{}});return"store"in o?o.store:void 0}function z(e){return/^[\w./:@+-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function vt(e,t){return`${v("checkpoint")} replay --file ${z(e)} --target ${t}`}function L(e,t,n){return`${v("checkpoint")} replay --checkpoint ${e} --target ${t}`+(n!==void 0?` --store ${z(n)}`:"")}var l=e=>e.toLocaleString("en-US");function b(e){let t=new Date(Date.parse(e)).toISOString();return`${t.slice(0,10)} ${t.slice(11,16)} UTC`}function M(e,t=8){return e.length<=t?e.join(", "):`${e.slice(0,t).join(", ")} and ${l(e.length-t)} more`}function Le(e){return{run:"replay",done:"replayed",source:e,recordedIn:"for this checkpoint on this machine",remove:"--remove",module:"replay",again:"again",againSubject:{purge:"replayAgain",sweep:"replayAgainSweep"},maybeMasks:"the checkpoint does not say whether its take read them unmasked, so they may hold the masks a user without View Encrypted Data reads, such as ****1234"}}var Pe={fileContentNotKept:()=>"a checkpoint keeps no file's content",notInTarget:(e,t)=>`${t} has no such object: deploy it there, or leave it out (--exclude-object ${e})`,notCreateable:(e,t)=>`${t} lets no one create its records`,excluded:()=>"left out as asked"},_e={objectNotReplayed:e=>`the checkpoint holds the records it names and does not replay them: add ${e.split(".")[0]}'s target with --objects`,objectNotHeld:(e,t)=>`the checkpoint does not hold what it names, and ${t} has no record of that Id`,userNotInTarget:(e,t)=>`${t} has no active standard user for it`},fe={requiredLookupMissing:"a required lookup names a record neither replayed nor in the other org",parentRefused:"a parent of theirs is refused, and no orphan is written",personAccountsUnsupported:"the other org has not turned person accounts on",inactiveCurrency:"their currency is not active in the other org",recordTypeUnavailable:"their record type is one the user who replays may not create"};function je(e){return`${Object.hasOwn(fe,e.reason)?fe[e.reason]:e.reason}${e.path?`: ${e.path}`:""}`}var De={byName:"found by its name",byId:"found by its Id",default:"the other org's default for the user who replays"};function xe(e){let{summary:t}=e,n=e.target.name,o=[],{records:r}=t;r.linkedById>0&&o.push(`${l(r.linkedById)} record(s) ${n} holds under the same Id \u2014 a sandbox copied from the same production \u2014: linked, not changed`),r.linkedByKey>0&&o.push(`${l(r.linkedByKey)} record(s) found in ${n} by the fields --link names: linked, not created`);let s=t.owners,d=[s.reasons.notInTarget>0?`their user is not in ${n}: ${l(s.reasons.notInTarget)}`:"",s.reasons.inactive>0?`their user is inactive in ${n}: ${l(s.reasons.inactive)}`:"",s.reasons.queueMissing>0?`their queue is not in ${n}: ${l(s.reasons.queueMissing)}`:""].filter(Boolean);o.push(`owners: ${l(s.kept)} kept, ${l(s.toRunningUser)} to the user who replays`+(d.length>0?` \u2014 ${d.join("; ")}`:""));for(let i of t.recordTypes)o.push(`record type ${i.object}.${i.recordType}: ${De[i.outcome]} \u2014 ${l(i.records)} record(s)`);for(let i of t.refused)o.push(`refused before anything is written: ${i.object} ${l(i.records)} \u2014 `+je(i));for(let i of t.notReplayed)o.push(`not replayed: ${i.object} ${l(i.records)} \u2014 `+Pe[i.reason](i.object,n));e.filesLeft.length>0&&o.push(`${l(e.filesLeft.length)} file(s) left where they were, a checkpoint keeping no file's content:`,...e.filesLeft.map(i=>` ${i.objectApiName}${i.name!==void 0?` '${i.name}'`:""}`));for(let i of t.lookupsEmptied)o.push(`${i.field}: emptied on ${l(i.records)} record(s) \u2014 `+_e[i.reason](i.field,n));for(let i of t.fieldsNotInTarget)o.push(`${i.object}: ${M(i.fields)} left out \u2014 ${n} does not have them`);t.customSettings&&o.push(`custom settings: ${l(t.customSettings.inserted)} row(s) set up, ${l(t.customSettings.alreadyThere)} already in ${n}, kept as they are`);for(let i of t.currencies.refused)o.push(`${i.code}: ${l(i.records)} record(s) refused \u2014 the currency is not active in ${n}: activate it there, or leave those records out`);if(t.currencies.singleCurrencyTarget&&o.push(`${n} has one currency: amounts are kept as they are, in its currency`),t.standardPricebook==="deduced"?o.push("standard price book: told from the price book entries, the checkpoint naming none"):t.standardPricebook==="ambiguous"&&o.push("standard price book: the price book entries do not tell which it was, and those that need it are refused"),t.masked.fields.length>0&&o.push(`masked: ${M(t.masked.fields)}`),(t.masked.unmaskedFreeText??[]).length>0&&o.push(`not masked, free text the masking does not read: ${M(t.masked.unmaskedFreeText??[])}`),o.push(t.contactPoints==="neutralized"?"emails and phone numbers made unreachable (.invalid, numbers that ring nobody); --keep-contact-points keeps them":"emails and phone numbers kept as they are: they reach the people they name"),(t.archivedActivities??0)>0&&o.push(`${l(t.archivedActivities??0)} archived task(s) and event(s) replayed, which ${n} holds live`),t.degraded.length>0&&o.push((e.checkpoint.annex?`its take could not read ${t.degraded.join(", ")}`:"taken before SandForge 1.81, it keeps no record types, users, queues nor standard price book")+`: the records they name get what ${n} gives them, each said above`),o.push("created and modified dates and users are the replay's own: the platform sets them"),e.storage){let{storage:i}=e;o.push(`data storage: about ${S(i.estimateMB)} MB of the ${S(i.remainingMB)} MB ${n} has left of ${S(i.maxMB)} MB`)}return o}var Te=new Set(["REPLAY_SAME_ORG","REPLAY_REAL_DATA","REPLAY_COPY_UNKNOWN","REPLAY_TOO_MANY","REPLAY_NOTHING","REPLAY_CHECKPOINT_UNUSABLE","REPLAY_NO_PILOT","CHECKPOINT_NOT_FOUND","OWNER_MAP_INACTIVE","OWNER_MAP_UNKNOWN","GUARD_REFUSED","NO_LOAD","TARGET_REFRESHED","LOAD_REMOVED","LOAD_STOPPED"]);function Me(e){let t=String(e.type??""),n=e.payload?.code;if(!(!t.endsWith(":error")||typeof n!="string")&&Te.has(n))return{code:n,message:String(e.payload?.message??"")}}function Ue(e,t,n,o={}){switch(e){case"TARGET_REFRESHED":if(/dataset/i.test(t))return`${n} was refreshed after the last replay: the records it created went with the refresh. Replay the checkpoint again, then verify.`;break;case"LOAD_REMOVED":{let r=/removal of (\S+) took part/.exec(t);if(r)return`The removal of ${r[1]} took part of the records the last replay created and left ${l(Number(o.left??0))} in ${n}: a verification would read the ones it took as missing. Remove what is left (--remove), or replay again (--again), which purges or finds it again; then verify.`;let s=/removed on (\S+?)\.(?:\s|$)/.exec(t);return`The records the last replay created were removed${s?` on ${s[1]}`:""}. Replay the checkpoint again, then verify.`}case"LOAD_STOPPED":return"The last replay stopped part way \u2014 it was cancelled, or failed once it had written \u2014 and wrote no counting contract: a verification would judge it by the one before. Replay it again (--again), which purges or finds again what the stopped replay wrote, or take it back (--remove); then verify.";case"NO_LOAD":if(/dataset|\bsas\b/i.test(t))return`No replay of this checkpoint into ${n} is recorded on this machine: nothing names the records to verify. Replay it there, then verify.`;break;case"MAX_RECORDS":{let r=/insert (\d+) record\(s\), more than the (\d+)/.exec(t);if(r)return`This replay would create ${l(Number(r[1]))} record(s), more than the ${l(Number(r[2]))} it may: nothing was written. The checkpoint's records or ${n} changed since that count was taken: run its dry run again, and replay with the count it gives (--max-records).`;break}case"REPLACE_LEAVES_RECORDS":{let r=/would leave (\d+) of their records in the org — (.*?): loaded again/.exec(t);if(r)return`Taking back what the replays before created in ${n} would leave ${r[1]} of their records there \u2014 ${r[2]}: replayed again, the checkpoint's records would stand beside them. Nothing was written. Take the replay back first (--remove; --include-changed takes too what was changed since, and what was added under it since), then replay it again.`;break}case"GUARD_REFUSED":if(o.guard==="non-sandbox")return`A replay goes into a sandbox, a scratch org or a Developer Edition org, never into a production org nor a sandbox marked Staging, which hold real data: ${n} is ${o.tier==="staging"?"a sandbox marked Staging":"a production org"}. Nothing was read or written.`;break}return/dataset/i.test(t)?t.replace(/frozen-dataset load/gi,"replay").replace(/the frozen dataset/gi,"the checkpoint").replace(/the dataset/gi,"the checkpoint").replace(/datasets?/gi,"checkpoint"):t}async function bt(e,t){let n=ke(W(t.storeRoot,t.storeNamed)),o=B(t.storeRoot,t.locksDir);o!==void 0&&await Ye(o,t.say);let r=e.file!==void 0?await qe(e,t):await Ke(e,t,n),s=n.folderOf(r.organizationId,r.checkpointId);await ee(n.root);let d={checkpoints:()=>[t.store,...[B(t.storeRoot,t.locksDir)].filter(f=>f!==void 0)],replays:n},i=t.storeNamed?t.storeRoot:void 0,a=L(r.checkpointId,e.target,i),u=r.name!==void 0?`checkpoint '${r.name}'`:`checkpoint ${r.checkpointId}`,m={request:{organizationId:r.organizationId,checkpointId:r.checkpointId,choices:e.choices,...e.config!==void 0?{config:e.config}:{}},stores:d,folder:s,auditStore:ge(n.root,ze),words:Le(u),refusalOf:Me,reword:(f,h,k)=>Ue(f,h,e.target,k),lines:(f,h)=>Qe(f,h,{asked:e,chosen:r,again:a}),question:f=>`Replay ${u} into ${e.target}, creating ${l(Be(f))} record(s) there${e.again?" once what its replays before created there is purged":""}?`,dryRunEnd:f=>f.length>0?[]:[`To replay it: ${a}${et(e)}`],answer:(f,h)=>nt(f,h,{asked:e,chosen:r,again:a})};await he(We(e,t.json),m)}function Be(e){return e.perObject.reduce((t,n)=>t+n.toInsert,0)}function We(e,t){return{step:e.action==="verify"?"verify":e.action==="remove"?"remove":"load",target:e.target,pilot:!1,reload:e.again,dryRun:e.action==="dryRun",writeEncrypted:!1,muteAutomation:e.muteAutomation,acceptAutomation:e.acceptAutomation,...e.checkpointFirst!==void 0?{checkpointFirst:e.checkpointFirst}:{},includeChanged:e.includeChanged,acceptEmails:e.acceptEmails,sweep:e.sweep,sweepList:e.sweepList,...e.sweepLate?{sweepLate:!0}:{},...e.sweepUntied?{sweepUntied:!0}:{},preview:e.preview,...e.maxRecords!==void 0?{maxTotal:e.maxRecords}:{},yes:e.yes,json:t}}async function Ye(e,t){let n=await e.sweep().catch(()=>{});for(let o of n?.checkpoints??[])t(`deleted the checkpoint '${o.name}' (${o.checkpointId}) of a file received, kept until ${b(o.expiresAt)}: its replays stay, and still take back with --remove`)}async function Ke(e,t,n){let o=e.checkpoint??"",r=B(t.storeRoot,t.locksDir),s=new Set,d=[...await t.listAll(),...await r?.list()??[]].filter(h=>{let k=`${h.organizationId.slice(0,15)}/${h.checkpointId}`;return s.has(k)?!1:(s.add(k),!0)}),i=h=>({organizationId:h.organizationId,checkpointId:h.checkpointId,...h.checkpoint?{name:h.checkpoint.name}:{},of:Ge(h)}),a=e.from;if(me(o)){let h=d.filter(g=>g.checkpointId===o&&(a===void 0||!A.test(a)||ue(g.organizationId,a)));if(h.length===1)return i(h[0]);let k=(await n.list({checkpointId:o})).filter(g=>a===void 0||!A.test(a)||ue(g.sourceOrganizationId,a)),R=[...new Set(k.map(g=>g.sourceOrganizationId))];if(h.length===0&&R.length===1){let g=k[0];return{organizationId:g.sourceOrganizationId,checkpointId:o,...g.checkpointName!==void 0?{name:g.checkpointName}:{}}}if(h.length+R.length>1){let g=[...new Set([...h.map(E=>E.organizationId),...R])];throw new y({code:"AMBIGUOUS",message:`Checkpoints of ${g.length} orgs have the id ${o}: name the org it was taken of with --from (${g.join(", ")}). Nothing was run.`},2)}throw new y({code:"NOT_FOUND",message:`No checkpoint ${o} is kept on this machine, nor a replay of it. `+He(t.storeNamed)})}let u=a??"",m=t.checkpointsOf(d,u,A.test(u)?u:void 0),f=t.resolve(d,m,o,u);if("entry"in f)return i(f.entry);throw"ambiguous"in f?new y({code:"AMBIGUOUS",message:f.ambiguous},2):new y({code:"NOT_FOUND",message:f.none})}function ue(e,t){return e.slice(0,15)===t.slice(0,15)}function He(e){return`"${v("checkpoint")} list" names the checkpoints kept, and "${v("checkpoint")} replays" the replays.${e?"":" One kept in another folder is read with --store <folder>."} A file a teammate sent replays with --file <.sfcheckpoint>.`}function Ge(e){let t=e.checkpoint?.org;if(t===void 0)return;let n=t.alias??t.username;return e.why==="refreshed"?`${n} before its refresh${e.refreshedAt?` on ${e.refreshedAt.slice(0,10)}`:""}`:e.why==="scratchExpired"?`${n}, a scratch org expired since`:n}async function qe(e,t){let n=e.file??"",o=await ae(n);if("refusal"in o)throw new y(o.refusal);let{header:r}=o.read;t.say(`the file holds checkpoint ${r.checkpointId} of org ${r.organizationId}, taken ${b(r.takenAt)}: ${l(r.records)} record(s) of ${l(r.objects)} object(s), exported by SandForge ${r.sandforgeVersion}`);let s={organizationId:r.organizationId,checkpointId:r.checkpointId,file:{path:n,header:r}};if(e.action==="remove")return s;if(e.action!=="verify"){let u=Ze(r,e);if(u!==void 0)throw new y(u)}let d=e.keyEnv!==void 0?Ve(e.keyEnv):await Je(),i=await se({storeRoot:t.storeRoot,...t.locksDir!==void 0?{locksDir:t.locksDir}:{},file:n,key:d,keepDays:e.keepDays,takenOn:{host:be(),pid:process.pid}});if(!i.imported)throw new y(i.refusal);let{checkpoint:a}=i;return t.say(i.outcome==="imported"?`kept checkpoint '${a.name}' of the file on this machine, apart from those it rewinds, to replay it: ${D(t.storeRoot)}, `+(a.expiresAt===null?"until it is deleted":`until ${b(a.expiresAt)} (--keep-days)`):`checkpoint '${a.name}' of the file is kept on this machine already, the same`),{...s,name:a.name,of:a.org.alias??a.org.username}}function Ze(e,t){if(t.choices.mask)return;let n=le({tier:e.orgTier,...e.dataStorageMaxMB!==void 0?{dataStorageMaxMB:e.dataStorageMaxMB}:{},...e.staging?{staging:!0}:{}}),o=`The file holds checkpoint ${e.checkpointId}`;if(n.kind==="real")return{code:"REPLAY_REAL_DATA",message:`${o} of ${n.why==="staging"?"a sandbox marked Staging":`a Partial Copy or Full sandbox, by its data storage (${l(n.dataStorageMaxMB??0)} MB)`}, which may hold real data: it goes into another org masked only. To replay it into ${t.target}, ${F.mask}. Its key was not read, and nothing was kept, read or written.`};if(n.kind==="unknown"&&t.choices.noRealData!==!0)return{code:"REPLAY_COPY_UNKNOWN",message:`${o} of a sandbox, and does not say which: made before SandForge 1.81, it keeps no data storage, and a Partial Copy or a Full sandbox holds production\u2019s records. To replay it into ${t.target}, ${F.mask}, or ${F.noRealData}. Its key was not read, and nothing was kept, read or written.`}}function Ve(e){let t=process.env[e];if(t===void 0||t.trim()==="")throw new y({code:"NO_KEY",message:`${e} is not set: it holds no key. Nothing was run.`},2);let n=C(t);if(n===void 0)throw new y({code:"NO_KEY",message:`${e} holds no key SandForge reads: 52 letters and digits, in groups of four as an export shows one. Nothing was run.`},2);return n}async function Je(){let e=await ne("Key of the file (not shown as you type it):","give --key-env VAR, the name of an environment variable that holds the key");if(e===void 0||e.trim()==="")throw new y({code:"DECLINED",message:"No key was typed. Nothing was run."});let t=C(e);if(t===void 0)throw new y({code:"IMPORT_KEY",message:"That is not a key SandForge draws: 52 letters and digits, in groups of four as the export showed it. Nothing was run."});return t}function Xe(e){let t=e.payload?.replay;return typeof t=="object"&&t!==null?t:void 0}function Qe(e,t,n){let o=Xe(e);if(o===void 0)return t;let{again:r}=n,s=o.target.name,d=o.filesLeft.length>0?` ${l(o.filesLeft.length)} file(s) are not replayed: a checkpoint keeps no file's content.`:"";if(e.type==="frozen:load:preview:response"){let i=n.chosen.of??o.checkpoint.alias??o.checkpoint.organizationId;return[`A replay of checkpoint '${o.checkpoint.name}' (of ${i}, taken ${b(o.checkpoint.takenAt)}) into ${s} would create copies of ${l(o.summary.records.toCreate)} of its records there, parents first, with new Ids; nothing ${s} holds is changed or deleted.${d}`,...t,...xe(o)]}return e.type==="frozen:load:response"?[...t,`To take it back: ${r} --remove`]:t}function et(e){let{choices:t}=e,n=e.checkpointFirst;return[t.objects.length>0?` --objects ${t.objects.join(",")}`:"",...t.excluded.map(o=>` --exclude-object ${o}`),t.owners!=="same"?` --owners ${t.owners}`:"",e.ownerMapFile!==void 0?` --owner-map ${z(e.ownerMapFile)}`:"",...t.link.map(o=>` --link ${o.objectApiName}=${o.fields.join(",")}`),t.customSettings?" --custom-settings":"",t.mask?" --mask":"",t.contactPoints==="kept"?" --keep-contact-points":"",t.noRealData?" --no-real-data":"",e.configFile!==void 0?` --replay-config ${z(e.configFile)}`:"",e.again?" --again":"",e.muteAutomation?" --mute-automation":"",e.acceptAutomation?" --accept-automation":"",e.acceptEmails?" --accept-emails":"",n!==void 0?" --checkpoint-first":"",n?.keepDays!==void 0?` --checkpoint-keep-days ${n.keepDays}`:"",...(n?.excluded??[]).map(o=>` --checkpoint-exclude-object ${o}`),e.maxRecords!==void 0?` --max-records ${e.maxRecords}`:""].join("")}function U(e,t){return e.filter(n=>n.type===t).at(-1)?.payload}var tt=new Set(["tool","step","posted","dataset","checkpoint"]);function nt(e,t,n){let{asked:o,chosen:r,again:s}=n,d=U(e.posted,"frozen:load:preview:response"),i=U(e.posted,"frozen:load:response"),a=i?.replay??d?.replay,u=d?.plan,m=i?.report,f=U(e.posted,"frozen:remove:response")?.result,h=Object.fromEntries(Object.entries(e).filter(([g])=>!tt.has(g))),k=e.checkpoint,R=a?.target.organizationId??t.targetOrgId;return{command:"replay",action:o.action,dryRun:o.action==="dryRun",checkpoint:a?{id:a.checkpoint.checkpointId,name:a.checkpoint.name,organizationId:a.checkpoint.organizationId,takenAt:a.checkpoint.takenAt,tier:a.checkpoint.tier,annex:a.checkpoint.annex}:{id:r.checkpointId,...r.name!==void 0?{name:r.name}:{},organizationId:r.organizationId},target:{alias:o.target,...R!==void 0?{organizationId:Q(R)}:{}},...o.action==="replay"||o.action==="dryRun"?{choices:a?.choices??o.choices}:{},...r.file?{file:r.file.path}:{},...u?{plan:u}:{},...a?{replay:{...a.summary,filesLeft:a.filesLeft,...a.storage?{storage:a.storage}:{},requests:a.requests}}:{},...m?{result:m}:{},...f!==void 0?{removal:f}:{},...h,...k?{checkpointFirst:k}:{},removeWith:`${s} --remove`,...t.refused?{refused:t.refused}:{},...t.ended?{ended:t.ended}:{},exit:t.exit}}function ot(e,t){return{checkpointId:e.checkpointId,...e.checkpointName!==void 0?{checkpointName:e.checkpointName}:{},sourceOrganizationId:e.sourceOrganizationId,...e.takenAt!==void 0?{takenAt:e.takenAt}:{},target:e.target,...e.choices!==void 0?{choices:e.choices}:{},...e.replayedAt!==void 0?{replayedAt:e.replayedAt}:{},inPlace:e.inPlace,inPlaceByObject:e.inPlaceByObject,...e.removed?{removed:!0}:{},removeWith:`${L(e.checkpointId,e.target.name??"<alias>",t)} --remove`}}function rt(e,t,n,o){return e.length===0?[`No replay${n!==void 0?` into ${n}`:""} is kept in ${t}.`]:e.flatMap(r=>{let s=r.target.name??r.target.organizationId,d=r.inPlaceByObject.map(i=>`${i.objectApiName} ${l(i.records)}`).join(", ");return[`${r.checkpointId} ${r.checkpointName!==void 0?`'${r.checkpointName}' `:""}of ${r.sourceOrganizationId}${r.takenAt!==void 0?`, taken ${b(r.takenAt)}`:""} into ${s} (${r.target.organizationId})`+(r.replayedAt!==void 0?` replayed ${b(r.replayedAt)}`:""),r.inPlace>0?` ${l(r.inPlace)} record(s) in place: ${d}`:r.removed?" removed: none of its records is left there":" none of its records is left there",...r.inPlace>0?[` to take it back: ${L(r.checkpointId,r.target.name??"<alias>",o)} --remove`]:[]]})}async function At(e,t){let n=ke(W(t.storeRoot,t.storeNamed)),o=await n.list(e!==void 0&&A.test(e)?{targetOrganizationId:e}:{}),r=e!==void 0&&!A.test(e)?o.filter(d=>d.target.name===e):o,s=t.storeNamed?t.storeRoot:void 0;for(let d of rt(r,n.root,e,s))t.say(d);t.answerJson(r.map(d=>ot(d,s)))}async function Et(e,t){let n;try{n=new x({root:W(t.storeRoot,t.storeNamed)})}catch{return{lines:[],entries:[]}}let o=t.storeNamed?t.storeRoot:void 0,r=[],s=[];for(let d of e){let i=await n.replaysOf(d.organizationId,d.checkpointId).catch(()=>[]),a=pe(i);if(a!==void 0){r.push(` ${a}`);for(let u of de(i))r.push(` to take it back: ${L(u.checkpointId,u.target.name??"<alias>",o)} --remove`),s.push(u)}}return{lines:r,entries:s}}export{Rt as a,$t as b,y as c,vt as d,L as e,je as f,bt as g,ot as h,At as i,Et as j};
@@ -4,7 +4,7 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{h as O}from"./chunk-AITNZWLB.mjs";import{A as R,B as _,e as X,k as S,r as P}from"./chunk-ETT5GP4P.mjs";import{H as E,c as Y,p as A,q as z}from"./chunk-E2YJVSX6.mjs";import{g as w,h as y}from"./chunk-EAFLDSQ2.mjs";import{vc as u}from"./chunk-DPYTG6DM.mjs";import{b as D,e as W,f as Q,l as L}from"./chunk-WZQEK4WT.mjs";import{mkdir as se,rm as M}from"node:fs/promises";import{join as I}from"node:path";var ee=200,ne=X*10,B=2e3,te=["Id","ContentDocumentId","LinkedEntityId","ShareType","Visibility"],ae=["Id","LatestPublishedVersionId","ContentSize"],de="taking",h=D().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record id"),T=D().regex(/^[A-Za-z]{1,40}$/,"Not a sharing value"),V=L({Id:h,ContentDocumentId:h,LinkedEntityId:h,ShareType:T,Visibility:T}),J=L({Id:h,LatestPublishedVersionId:h.nullable(),ContentSize:W().int().nonnegative().nullable(),anchored:Q()});function Re(e,n){return I(e,`${y}.${n}.ndjson`)}var Ce=V.extend({now:L({ShareType:T,Visibility:T})});function Fe(e,n){let t=new Set(n.map(r=>r.toLowerCase())),i=new Map;for(let r of e){let a=r.keyPrefix;t.has(r.name.toLowerCase())&&typeof a=="string"&&a.length===3&&i.set(a,r.name)}return i}function Te(e,n){let t=e.LinkedEntityId;return typeof t=="string"&&t.length>=15?n.get(t.slice(0,3)):void 0}function oe(e){return e.map(n=>{if(!h.safeParse(n).success)throw new Error(`Not a record id: ${n}`);return`'${n}'`}).join(", ")}function ce(e){let n=u(e);return{objectApiName:n,soql:`SELECT ${te.join(", ")} FROM ${y} WHERE LinkedEntityId IN (SELECT Id FROM ${n})`,scanAll:!1}}function be(e){let n=u(e);return{objectApiName:n,soql:`SELECT COUNT() FROM ${y} WHERE LinkedEntityId IN (SELECT Id FROM ${n})`,scanAll:!1}}function le(e,n){return{objectApiName:u(e),soql:`SELECT ${te.join(", ")} FROM ${y} WHERE LinkedEntityId IN (${oe(n)})`,scanAll:!1}}function fe(e){return{objectApiName:w,soql:`SELECT ${ae.join(", ")} FROM ${w} WHERE Id IN (${oe(e)})`,scanAll:!1}}async function*v(e,n){let t=[];for await(let i of e)t.push(i),t.length>=n&&(yield t,t=[]);t.length>0&&(yield t)}function*C(e,n){let t=[];for(let i of e)t.push(i),t.length>=n&&(yield t,t=[]);t.length>0&&(yield t)}function G(e,n,t){let i=e.safeParse(n);if(!i.success)throw new Error(`The org answered a ${t} that does not read as one: ${i.error.message}`);return i.data}function F(e){return e.slice(0,15)}async function xe(e){let{reader:n,folder:t,signal:i}=e,r=e.files??S(O(t.dir)),a=I(t.filesDir,de);await se(a,{recursive:!0,mode:Y});let m=z(t),b=A(t);await r.writeFile(m,""),await r.writeFile(b,"");try{let x=new Map,q=0,H=async d=>{for await(let c of v(_(d),B)){let s=c.map(o=>G(V,o,"link"));for(let o of s)x.has(F(o.ContentDocumentId))||x.set(F(o.ContentDocumentId),o.ContentDocumentId);q+=s.length,await r.appendFile(m,s.map(o=>`${JSON.stringify(o)}
7
+ import{h as O}from"./chunk-XU25YA46.mjs";import{A as R,B as _,e as X,k as S,r as P}from"./chunk-SAMWHL22.mjs";import{H as E,c as Y,p as A,q as z}from"./chunk-J24TIGSI.mjs";import{g as w,h as y}from"./chunk-L4INJ5TZ.mjs";import{Hc as u}from"./chunk-ZQO5PDX5.mjs";import{b as D,e as W,f as Q,l as L}from"./chunk-WZQEK4WT.mjs";import{mkdir as se,rm as M}from"node:fs/promises";import{join as I}from"node:path";var ee=200,ne=X*10,B=2e3,te=["Id","ContentDocumentId","LinkedEntityId","ShareType","Visibility"],ae=["Id","LatestPublishedVersionId","ContentSize"],de="taking",h=D().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record id"),T=D().regex(/^[A-Za-z]{1,40}$/,"Not a sharing value"),V=L({Id:h,ContentDocumentId:h,LinkedEntityId:h,ShareType:T,Visibility:T}),J=L({Id:h,LatestPublishedVersionId:h.nullable(),ContentSize:W().int().nonnegative().nullable(),anchored:Q()});function Re(e,n){return I(e,`${y}.${n}.ndjson`)}var Ce=V.extend({now:L({ShareType:T,Visibility:T})});function Fe(e,n){let t=new Set(n.map(r=>r.toLowerCase())),i=new Map;for(let r of e){let a=r.keyPrefix;t.has(r.name.toLowerCase())&&typeof a=="string"&&a.length===3&&i.set(a,r.name)}return i}function Te(e,n){let t=e.LinkedEntityId;return typeof t=="string"&&t.length>=15?n.get(t.slice(0,3)):void 0}function oe(e){return e.map(n=>{if(!h.safeParse(n).success)throw new Error(`Not a record id: ${n}`);return`'${n}'`}).join(", ")}function ce(e){let n=u(e);return{objectApiName:n,soql:`SELECT ${te.join(", ")} FROM ${y} WHERE LinkedEntityId IN (SELECT Id FROM ${n})`,scanAll:!1}}function be(e){let n=u(e);return{objectApiName:n,soql:`SELECT COUNT() FROM ${y} WHERE LinkedEntityId IN (SELECT Id FROM ${n})`,scanAll:!1}}function le(e,n){return{objectApiName:u(e),soql:`SELECT ${te.join(", ")} FROM ${y} WHERE LinkedEntityId IN (${oe(n)})`,scanAll:!1}}function fe(e){return{objectApiName:w,soql:`SELECT ${ae.join(", ")} FROM ${w} WHERE Id IN (${oe(e)})`,scanAll:!1}}async function*v(e,n){let t=[];for await(let i of e)t.push(i),t.length>=n&&(yield t,t=[]);t.length>0&&(yield t)}function*C(e,n){let t=[];for(let i of e)t.push(i),t.length>=n&&(yield t,t=[]);t.length>0&&(yield t)}function G(e,n,t){let i=e.safeParse(n);if(!i.success)throw new Error(`The org answered a ${t} that does not read as one: ${i.error.message}`);return i.data}function F(e){return e.slice(0,15)}async function xe(e){let{reader:n,folder:t,signal:i}=e,r=e.files??S(O(t.dir)),a=I(t.filesDir,de);await se(a,{recursive:!0,mode:Y});let m=z(t),b=A(t);await r.writeFile(m,""),await r.writeFile(b,"");try{let x=new Map,q=0,H=async d=>{for await(let c of v(_(d),B)){let s=c.map(o=>G(V,o,"link"));for(let o of s)x.has(F(o.ContentDocumentId))||x.set(F(o.ContentDocumentId),o.ContentDocumentId);q+=s.length,await r.appendFile(m,s.map(o=>`${JSON.stringify(o)}
8
8
  `).join(""))}await M(d,{force:!0})},K=e.linked.map(d=>({...ce(d),file:I(a,`${u(d)}.links.ndjson`)})),re=await R(n,K,i),$=[];for(let[d,c]of re.entries()){if(c.read){await H(K[d].file);continue}let s=e.linked[d];$.push(s);let o=await P.read(t,e.snapshotId,s),l=0;for(let g of C(C(pe(o),ee),ne)){let f=g.map(k=>({...le(s,k),file:I(a,`${u(s)}.links.${l++}.ndjson`)})),N=(await R(n,f,i)).find(k=>!k.read);if(N&&!N.read)throw new Error(`The links of the files of ${s} could not be read whole: ${c.reason}; read by the ids of its records, ${N.reason}`);for(let k of f)await H(k.file)}}let j=0,U=0,Z=new Set;for(let d of C(C(x.values(),ee),ne)){let c=d.map((l,g)=>({...fe(l),file:I(a,`documents.${g}.ndjson`)})),o=(await R(n,c,i)).find(l=>!l.read);if(o&&!o.read)throw new Error(`The files the links name could not be read by their ids: ${o.reason}`);for(let l of c){for await(let g of v(_(l.file),B)){let f=g.map(p=>({...G(J.omit({anchored:!0}),p,"file"),anchored:!0}));for(let p of f)Z.add(F(p.Id));j+=f.length,U+=f.length,await r.appendFile(b,f.map(p=>`${JSON.stringify(p)}
9
9
  `).join(""))}await M(l.file,{force:!0})}}if(e.documentsInSnapshot){let d=await P.read(t,e.snapshotId,w);for await(let c of v(d.records(),B)){let s=c.filter(o=>typeof o.Id=="string"&&!Z.has(F(o.Id))).map(o=>({...G(J.omit({anchored:!0}),ue(o),"file"),anchored:!1}));j+=s.length,s.length>0&&await r.appendFile(b,s.map(o=>`${JSON.stringify(o)}
10
10
  `).join(""))}}return{documents:j,links:q,anchored:U,...$.length>0?{readByIds:$}:{}}}finally{await M(a,{recursive:!0,force:!0})}}function*pe(e){for(let n=0;n<e.size;n++)yield e.idAt(n)}function ue(e){return{Id:e.Id,LatestPublishedVersionId:e.LatestPublishedVersionId??null,ContentSize:e.ContentSize??null}}async function*ie(e,n,t,i){if(!await e.exists(n))throw new E("damaged",`The checkpoint\u2019s ${i} are not there`);for await(let r of e.readLines(n)){if(r==="")continue;let a;try{a=JSON.parse(r)}catch{throw new E("damaged",`The checkpoint\u2019s ${i} hold a line that is not JSON`)}let m=t.safeParse(a);if(!m.success)throw new E("damaged",`The checkpoint\u2019s ${i} hold a line that does not parse`);yield m.data}}function $e(e,n=S(O(e.dir))){return ie(n,z(e),V,"file links")}function je(e,n=S(O(e.dir))){return ie(n,A(e),J,"files")}export{ee as a,te as b,V as c,Re as d,Ce as e,Fe as f,Te as g,ce as h,be as i,le as j,xe as k,$e as l,je as m};
@@ -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{c as A}from"./chunk-66NMFCWX.mjs";import{a as D}from"./chunk-ETT5GP4P.mjs";import{c as x,q as g,r as h,t as P,u as k}from"./chunk-55LQD3Y3.mjs";import{g as R}from"./chunk-EAFLDSQ2.mjs";import{Lc as O}from"./chunk-DPYTG6DM.mjs";import{b as d,f as l,k as m,l as b}from"./chunk-WZQEK4WT.mjs";var j=[{child:"Entitlement",field:"AccountId",parent:"Account",refused:"always"},{child:"Order",field:"AccountId",parent:"Account",refused:"pastDraft"},{child:"Opportunity",field:"AccountId",parent:"Account",refused:"closedWon",rows:{field:"IsWon",value:!0}}];function C(e,n,t){let[s,r,a]=[e,n,t??""].map(i=>i.toLowerCase());return j.some(i=>i.refused==="always"&&i.child.toLowerCase()===s&&i.field.toLowerCase()===r&&(t===void 0||i.parent.toLowerCase()===a))}var W=b({name:d(),type:d(),createable:l().optional(),updateable:l().optional(),nillable:l().optional(),calculated:l().optional(),autoNumber:l().optional(),permissionable:l().optional(),encrypted:l().optional(),referenceTo:m(d()).nullish()}).loose(),oe=b({name:d(),undeletable:l().optional(),fields:m(W),childRelationships:m(b({childSObject:d(),field:d(),cascadeDelete:l().optional(),restrictedDelete:l().optional()}).loose()).nullish()}).loose(),F=["Id","SystemModstamp","CreatedDate","CreatedById","LastModifiedDate","LastModifiedById"],S="IsPersonAccount",M="Event",I=["LatestPublishedVersionId","ContentSize"],_=["ParentId","ContentAssetId","IsArchived"],v="VersionData";function N(e){return e.toLowerCase()===R.toLowerCase()}function B(e){return new Set(N(e)?I.map(n=>n.toLowerCase()):[])}function U(e){return e===x||e===M?"scanAllLive":"query"}function V(e){let n={name:e.name,label:e.name,labelPlural:e.name,keyPrefix:null,custom:!1,createable:!0,updateable:!0,deletable:!0,queryable:!0,fields:e.fields.map(t=>({name:t.name,label:t.name,type:t.type,length:0,nillable:t.nillable===!0,createable:t.createable===!0,updateable:t.updateable===!0,externalId:!1,referenceTo:t.referenceTo??[],relationshipName:null,picklistValues:[],defaultValue:null,calculated:t.calculated===!0,autoNumber:t.autoNumber===!0,unique:!1,...t.permissionable===void 0?{}:{permissionable:t.permissionable}})),recordTypeInfos:[],childRelationships:[]};return new A(async()=>n)}function G(e){return e.type==="address"||e.type==="location"}function y(e){return new Map(e.fields.map(n=>[n.name.toLowerCase(),n]))}async function K(e,n){let t=y(e),s=F.filter(o=>t.has(o.toLowerCase())),r=t.get(S.toLowerCase());r&&(e.name===g||e.name===h)&&s.push(r.name);let a=N(e.name);if(a)for(let o of I){let c=t.get(o.toLowerCase());c&&s.push(c.name)}let i=new Set(a?_.map(o=>o.toLowerCase()):[]),p=new Set(s.map(o=>o.toLowerCase())),f=e.fields.map(o=>o.name).filter(o=>!p.has(o.toLowerCase())&&!i.has(o.toLowerCase())),{writable:L,skipped:z,denied:T}=await V(e).partitionWritableFields(e.name,"upsert",f),w=[],u=new Map;for(let o of T)u.set(o,"fls");for(let o of z){let c=t.get(o.toLowerCase());c&&G(c)&&u.set(o,"compound")}let E=new Set(L);for(let o of L){let c=t.get(o.toLowerCase())?.type;c==="base64"?u.set(o,"base64"):c===D&&!n.viewsEncryptedData&&u.set(o,"encrypted")}for(let o of f){let c=u.get(o);c!==void 0?w.push({field:o,reason:c}):E.has(o)&&s.push(o)}return a&&w.push({field:v,reason:"base64"}),{fields:s,leftOutFields:w}}function q(e,n){let t=y(e),s=e.name.toLowerCase(),r=new Set;for(let a of n)for(let i of a.childRelationships??[]){if(i.cascadeDelete!==!0||i.childSObject.toLowerCase()!==s||C(e.name,i.field,a.name))continue;let p=t.get(i.field.toLowerCase());p&&r.add(p.name)}return[...r].sort()}function Y(e,n){let t=y(e),s=e.name.toLowerCase(),r=new Set;for(let a of n)for(let i of a.childRelationships??[]){if(!(i.restrictedDelete===!0&&i.cascadeDelete!==!0||C(e.name,i.field,a.name))||i.childSObject.toLowerCase()!==s)continue;let f=t.get(i.field.toLowerCase());f&&r.add(f.name)}return[...r].sort()}function re(e){let n=e.cascadeParents.filter(t=>C(e.objectApiName,t));return n.length===0?e:{...e,cascadeParents:e.cascadeParents.filter(t=>!n.includes(t)),restrictParents:[...new Set([...e.restrictParents??[],...n])].sort()}}async function se(e,n,t){return{objectApiName:e.name,readMode:U(e.name),undeletable:e.undeletable===!0,cascadeParents:q(e,n),restrictParents:Y(e,n),...await K(e,t)}}function H(e,n){let t=e.toLowerCase(),s=new Set;for(let r of n){let a=r.indexOf(".");a<=0||a===r.length-1||r.slice(0,a).toLowerCase()===t&&s.add(r.slice(a+1).toLowerCase())}return s}function J(e,n){let t=n.toLowerCase();return t!==S.toLowerCase()&&!F.some(s=>s.toLowerCase()===t)&&!B(e).has(t)}function ae(e,n,t){let s=H(e,t);return n.filter(r=>J(e,r)&&!s.has(r.toLowerCase()))}function ie(e,n){return e===h&&P(n)}function ce(e,n,t){let s=e===g?k(n,!1):void 0,r={};typeof n.Id=="string"&&(r.Id=n.Id);for(let a of t)a in n&&(s!==void 0&&O(g,a,s)||(r[a]=n[a]));return r}export{j as a,C as b,W as c,oe as d,F as e,S as f,I as g,U as h,re as i,se as j,H as k,ae as l,ie as m,ce as n};
7
+ import{c as A}from"./chunk-66NMFCWX.mjs";import{a as D}from"./chunk-SAMWHL22.mjs";import{g as R}from"./chunk-L4INJ5TZ.mjs";import{c as x,q as g,r as h,t as P,u as k}from"./chunk-KIMQQ6JQ.mjs";import{Xc as O}from"./chunk-ZQO5PDX5.mjs";import{b as d,f as l,k as m,l as b}from"./chunk-WZQEK4WT.mjs";var j=[{child:"Entitlement",field:"AccountId",parent:"Account",refused:"always"},{child:"Order",field:"AccountId",parent:"Account",refused:"pastDraft"},{child:"Opportunity",field:"AccountId",parent:"Account",refused:"closedWon",rows:{field:"IsWon",value:!0}}];function C(e,n,t){let[s,r,a]=[e,n,t??""].map(i=>i.toLowerCase());return j.some(i=>i.refused==="always"&&i.child.toLowerCase()===s&&i.field.toLowerCase()===r&&(t===void 0||i.parent.toLowerCase()===a))}var W=b({name:d(),type:d(),createable:l().optional(),updateable:l().optional(),nillable:l().optional(),calculated:l().optional(),autoNumber:l().optional(),permissionable:l().optional(),encrypted:l().optional(),referenceTo:m(d()).nullish()}).loose(),oe=b({name:d(),undeletable:l().optional(),fields:m(W),childRelationships:m(b({childSObject:d(),field:d(),cascadeDelete:l().optional(),restrictedDelete:l().optional()}).loose()).nullish()}).loose(),F=["Id","SystemModstamp","CreatedDate","CreatedById","LastModifiedDate","LastModifiedById"],S="IsPersonAccount",M="Event",I=["LatestPublishedVersionId","ContentSize"],_=["ParentId","ContentAssetId","IsArchived"],v="VersionData";function N(e){return e.toLowerCase()===R.toLowerCase()}function B(e){return new Set(N(e)?I.map(n=>n.toLowerCase()):[])}function U(e){return e===x||e===M?"scanAllLive":"query"}function V(e){let n={name:e.name,label:e.name,labelPlural:e.name,keyPrefix:null,custom:!1,createable:!0,updateable:!0,deletable:!0,queryable:!0,fields:e.fields.map(t=>({name:t.name,label:t.name,type:t.type,length:0,nillable:t.nillable===!0,createable:t.createable===!0,updateable:t.updateable===!0,externalId:!1,referenceTo:t.referenceTo??[],relationshipName:null,picklistValues:[],defaultValue:null,calculated:t.calculated===!0,autoNumber:t.autoNumber===!0,unique:!1,...t.permissionable===void 0?{}:{permissionable:t.permissionable}})),recordTypeInfos:[],childRelationships:[]};return new A(async()=>n)}function G(e){return e.type==="address"||e.type==="location"}function y(e){return new Map(e.fields.map(n=>[n.name.toLowerCase(),n]))}async function K(e,n){let t=y(e),s=F.filter(o=>t.has(o.toLowerCase())),r=t.get(S.toLowerCase());r&&(e.name===g||e.name===h)&&s.push(r.name);let a=N(e.name);if(a)for(let o of I){let c=t.get(o.toLowerCase());c&&s.push(c.name)}let i=new Set(a?_.map(o=>o.toLowerCase()):[]),p=new Set(s.map(o=>o.toLowerCase())),f=e.fields.map(o=>o.name).filter(o=>!p.has(o.toLowerCase())&&!i.has(o.toLowerCase())),{writable:L,skipped:z,denied:T}=await V(e).partitionWritableFields(e.name,"upsert",f),w=[],u=new Map;for(let o of T)u.set(o,"fls");for(let o of z){let c=t.get(o.toLowerCase());c&&G(c)&&u.set(o,"compound")}let E=new Set(L);for(let o of L){let c=t.get(o.toLowerCase())?.type;c==="base64"?u.set(o,"base64"):c===D&&!n.viewsEncryptedData&&u.set(o,"encrypted")}for(let o of f){let c=u.get(o);c!==void 0?w.push({field:o,reason:c}):E.has(o)&&s.push(o)}return a&&w.push({field:v,reason:"base64"}),{fields:s,leftOutFields:w}}function q(e,n){let t=y(e),s=e.name.toLowerCase(),r=new Set;for(let a of n)for(let i of a.childRelationships??[]){if(i.cascadeDelete!==!0||i.childSObject.toLowerCase()!==s||C(e.name,i.field,a.name))continue;let p=t.get(i.field.toLowerCase());p&&r.add(p.name)}return[...r].sort()}function Y(e,n){let t=y(e),s=e.name.toLowerCase(),r=new Set;for(let a of n)for(let i of a.childRelationships??[]){if(!(i.restrictedDelete===!0&&i.cascadeDelete!==!0||C(e.name,i.field,a.name))||i.childSObject.toLowerCase()!==s)continue;let f=t.get(i.field.toLowerCase());f&&r.add(f.name)}return[...r].sort()}function re(e){let n=e.cascadeParents.filter(t=>C(e.objectApiName,t));return n.length===0?e:{...e,cascadeParents:e.cascadeParents.filter(t=>!n.includes(t)),restrictParents:[...new Set([...e.restrictParents??[],...n])].sort()}}async function se(e,n,t){return{objectApiName:e.name,readMode:U(e.name),undeletable:e.undeletable===!0,cascadeParents:q(e,n),restrictParents:Y(e,n),...await K(e,t)}}function H(e,n){let t=e.toLowerCase(),s=new Set;for(let r of n){let a=r.indexOf(".");a<=0||a===r.length-1||r.slice(0,a).toLowerCase()===t&&s.add(r.slice(a+1).toLowerCase())}return s}function J(e,n){let t=n.toLowerCase();return t!==S.toLowerCase()&&!F.some(s=>s.toLowerCase()===t)&&!B(e).has(t)}function ae(e,n,t){let s=H(e,t);return n.filter(r=>J(e,r)&&!s.has(r.toLowerCase()))}function ie(e,n){return e===h&&P(n)}function ce(e,n,t){let s=e===g?k(n,!1):void 0,r={};typeof n.Id=="string"&&(r.Id=n.Id);for(let a of t)a in n&&(s!==void 0&&O(g,a,s)||(r[a]=n[a]));return r}export{j as a,C as b,W as c,oe as d,F as e,S as f,I as g,U as h,re as i,se as j,H as k,ae as l,ie as m,ce as n};
@@ -4,5 +4,5 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a as w,b as x}from"./chunk-HYBH5PFM.mjs";import{b as R}from"./chunk-KNIRA333.mjs";import{g as k}from"./chunk-MNITSYI2.mjs";import{Ia as g,La as l,tb as h}from"./chunk-DPYTG6DM.mjs";import{b as d,m as S,s as u,v as f}from"./chunk-WZQEK4WT.mjs";import{createHash as $}from"node:crypto";import{mkdir as y,readFile as C,rename as P,writeFile as O}from"node:fs/promises";import*as a from"node:path";var A=k,N=d().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"A record id"),p=S({version:f(1),runId:d().min(1).max(200),packId:g,packFingerprint:d().regex(/^[0-9a-f]{64}$/,"A sha256, in lower-case hexadecimal"),compile:l.refine(e=>e.seed!==void 0,{message:"The seed the pack was compiled with is kept",path:["seed"]}),openCases:u(d().min(1).max(255),N),agent:h.optional()});function F(e){return $("sha256").update(m(e)).digest("hex")}function v(e){let r={};for(let i of e.compiled.tests){let n=i.openCase?.caseKey;if(n===void 0)continue;let t=e.caseIds[n];t!==void 0&&(r[n]=t)}return p.parse({version:1,runId:e.runId,packId:e.pack.id,packFingerprint:F(e.pack),compile:{...e.options,seed:e.compiled.seed},openCases:r})}function D(e,r){return p.parse({...e,agent:r})}function U(e,r){if(r.id!==e.packId)return{ok:!1,message:`The run was seeded from the scenario ${e.packId}, not ${r.id}`};if(F(r)!==e.packFingerprint)return{ok:!1,message:`The scenario ${r.id} has changed since the run: its tests would be about subjects and addresses no record of the run holds`};try{return{ok:!0,compiled:x(r,e.compile)}}catch(i){if(i instanceof w)return{ok:!1,message:i.message};throw i}}function Z(){return{readFile:e=>C(e,"utf8"),writeFile:(e,r)=>O(e,r,"utf8"),rename:(e,r)=>P(e,r),mkdir:async e=>{await y(e,{recursive:!0})}}}function I(e,r){return a.join(e,R,`${r.replace(/[^A-Za-z0-9_-]/g,"_")}${A}`)}async function K(e,r,i){let n=p.parse(i),t=I(r,n.runId),o=`${t}.${process.pid}.tmp`;return await e.mkdir(a.dirname(t)),await e.writeFile(o,`${JSON.stringify(n,null,2)}
7
+ import{a as w,b as x}from"./chunk-V3R45ZWT.mjs";import{b as R}from"./chunk-JKT5YAQ2.mjs";import{g as k}from"./chunk-3SKLBRPL.mjs";import{Fb as h,Ia as g,La as l}from"./chunk-ZQO5PDX5.mjs";import{b as d,m as S,s as u,v as f}from"./chunk-WZQEK4WT.mjs";import{createHash as $}from"node:crypto";import{mkdir as y,readFile as C,rename as P,writeFile as O}from"node:fs/promises";import*as a from"node:path";var A=k,N=d().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"A record id"),p=S({version:f(1),runId:d().min(1).max(200),packId:g,packFingerprint:d().regex(/^[0-9a-f]{64}$/,"A sha256, in lower-case hexadecimal"),compile:l.refine(e=>e.seed!==void 0,{message:"The seed the pack was compiled with is kept",path:["seed"]}),openCases:u(d().min(1).max(255),N),agent:h.optional()});function F(e){return $("sha256").update(m(e)).digest("hex")}function v(e){let r={};for(let i of e.compiled.tests){let n=i.openCase?.caseKey;if(n===void 0)continue;let t=e.caseIds[n];t!==void 0&&(r[n]=t)}return p.parse({version:1,runId:e.runId,packId:e.pack.id,packFingerprint:F(e.pack),compile:{...e.options,seed:e.compiled.seed},openCases:r})}function D(e,r){return p.parse({...e,agent:r})}function U(e,r){if(r.id!==e.packId)return{ok:!1,message:`The run was seeded from the scenario ${e.packId}, not ${r.id}`};if(F(r)!==e.packFingerprint)return{ok:!1,message:`The scenario ${r.id} has changed since the run: its tests would be about subjects and addresses no record of the run holds`};try{return{ok:!0,compiled:x(r,e.compile)}}catch(i){if(i instanceof w)return{ok:!1,message:i.message};throw i}}function Z(){return{readFile:e=>C(e,"utf8"),writeFile:(e,r)=>O(e,r,"utf8"),rename:(e,r)=>P(e,r),mkdir:async e=>{await y(e,{recursive:!0})}}}function I(e,r){return a.join(e,R,`${r.replace(/[^A-Za-z0-9_-]/g,"_")}${A}`)}async function K(e,r,i){let n=p.parse(i),t=I(r,n.runId),o=`${t}.${process.pid}.tmp`;return await e.mkdir(a.dirname(t)),await e.writeFile(o,`${JSON.stringify(n,null,2)}
8
8
  `),await e.rename(o,t),t}async function X(e,r,i){let n=I(r,i),t;try{t=await e.readFile(n)}catch(c){if(c.code==="ENOENT")return{kind:"absent"};throw c}let o;try{o=JSON.parse(t)}catch{return{kind:"invalid",message:`${a.basename(n)} is not JSON`}}let s=p.safeParse(o);if(!s.success){let c=s.error.issues[0];return{kind:"invalid",message:`${a.basename(n)}: ${c.path.join(".")||"the file"}: ${c.message}`}}return s.data.runId!==i?{kind:"invalid",message:`${a.basename(n)} is the companion of the run ${s.data.runId}, not ${i}`}:{kind:"read",sidecar:s.data}}function m(e){return Array.isArray(e)?`[${e.map(r=>m(r??null)).join(",")}]`:e!==null&&typeof e=="object"?`{${Object.entries(e).filter(([,i])=>i!==void 0).sort(([i],[n])=>i<n?-1:i>n?1:0).map(([i,n])=>`${JSON.stringify(i)}:${m(n)}`).join(",")}}`:JSON.stringify(e??null)}export{A as a,p as b,F as c,v as d,D as e,U as f,Z as g,I as h,K as i,X as j};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a,b}from"./chunk-MHW6DV6T.mjs";import"./chunk-OVOLG3AL.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-DPYTG6DM.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as FieldMapper,b as generateValue};
7
+ import{a,b}from"./chunk-DT3T7FRD.mjs";import"./chunk-NWOI25WY.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-ZQO5PDX5.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as FieldMapper,b as generateValue};