sandforge 0.0.0-stage → 1.79.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 (220) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +54 -2
  3. package/THIRD-PARTY-NOTICES.md +1624 -0
  4. package/bin/sandforge-autopilot.mjs +12 -0
  5. package/bin/sandforge-backup.mjs +12 -0
  6. package/bin/sandforge-checkpoint.mjs +12 -0
  7. package/bin/sandforge-cleanup.mjs +12 -0
  8. package/bin/sandforge-clone.mjs +12 -0
  9. package/bin/sandforge-compare.mjs +12 -0
  10. package/bin/sandforge-dataops.mjs +12 -0
  11. package/bin/sandforge-empty.mjs +12 -0
  12. package/bin/sandforge-env.mjs +12 -0
  13. package/bin/sandforge-frozen.mjs +12 -0
  14. package/bin/sandforge-mcp.mjs +12 -0
  15. package/bin/sandforge-monitor.mjs +12 -0
  16. package/bin/sandforge-seed.mjs +12 -0
  17. package/bin/sandforge-sync.mjs +12 -0
  18. package/bin/sandforge.mjs +12 -0
  19. package/lib/catalogue.en.json +1 -0
  20. package/lib/chunk-2BVTCNWA.mjs +7 -0
  21. package/lib/chunk-2S5OMIIA.mjs +7 -0
  22. package/lib/chunk-2YIV2OB2.mjs +7 -0
  23. package/lib/chunk-342FN7AO.mjs +9 -0
  24. package/lib/chunk-36U7IQ6Y.mjs +25 -0
  25. package/lib/chunk-3CA767QB.mjs +7 -0
  26. package/lib/chunk-3DCUADVK.mjs +7 -0
  27. package/lib/chunk-3F5YMM2F.mjs +7 -0
  28. package/lib/chunk-3OHPD72J.mjs +9 -0
  29. package/lib/chunk-3RYLICRX.mjs +7 -0
  30. package/lib/chunk-3SRXFZSD.mjs +7 -0
  31. package/lib/chunk-42RER7V4.mjs +14 -0
  32. package/lib/chunk-4GL773D5.mjs +7 -0
  33. package/lib/chunk-4HFRHFGQ.mjs +7 -0
  34. package/lib/chunk-4HW535YJ.mjs +7 -0
  35. package/lib/chunk-4NAHW2D3.mjs +7 -0
  36. package/lib/chunk-4SNDMJP2.mjs +7 -0
  37. package/lib/chunk-4TLYUZD5.mjs +7 -0
  38. package/lib/chunk-4U6NXJNL.mjs +7 -0
  39. package/lib/chunk-4XZ5YT5O.mjs +7 -0
  40. package/lib/chunk-55HEMHEG.mjs +7 -0
  41. package/lib/chunk-57VHUYNG.mjs +10 -0
  42. package/lib/chunk-5AJRHRXA.mjs +20 -0
  43. package/lib/chunk-5CD257T7.mjs +7 -0
  44. package/lib/chunk-5HMAPZBV.mjs +7 -0
  45. package/lib/chunk-5LFSFYFJ.mjs +7 -0
  46. package/lib/chunk-5MMXFWPD.mjs +7 -0
  47. package/lib/chunk-5O6JOMHS.mjs +13 -0
  48. package/lib/chunk-5P4PHJRL.mjs +9 -0
  49. package/lib/chunk-5QKTYCWE.mjs +11 -0
  50. package/lib/chunk-66NMFCWX.mjs +7 -0
  51. package/lib/chunk-6EBMEGZB.mjs +7 -0
  52. package/lib/chunk-6LAXTAVN.mjs +7 -0
  53. package/lib/chunk-6MUEPV7M.mjs +9 -0
  54. package/lib/chunk-6QSM2WIH.mjs +10 -0
  55. package/lib/chunk-75ADZS6B.mjs +7 -0
  56. package/lib/chunk-7EANH5PY.mjs +68 -0
  57. package/lib/chunk-7F54PZUS.mjs +7 -0
  58. package/lib/chunk-7UQD6V6F.mjs +7 -0
  59. package/lib/chunk-AAVJ5XVX.mjs +7 -0
  60. package/lib/chunk-ALJVEUUS.mjs +7 -0
  61. package/lib/chunk-ALUFROGA.mjs +7 -0
  62. package/lib/chunk-AR7BE5O2.mjs +7 -0
  63. package/lib/chunk-AUTM6H6Z.mjs +7 -0
  64. package/lib/chunk-AV5SWEHP.mjs +9 -0
  65. package/lib/chunk-B45CNPUX.mjs +47 -0
  66. package/lib/chunk-BILZ3SSR.mjs +7 -0
  67. package/lib/chunk-BN7A4GRQ.mjs +7 -0
  68. package/lib/chunk-BOGNK4LV.mjs +7 -0
  69. package/lib/chunk-BS5T3MOQ.mjs +7 -0
  70. package/lib/chunk-BZ24IAP5.mjs +7 -0
  71. package/lib/chunk-CA5NAXSU.mjs +7 -0
  72. package/lib/chunk-CE6ZDGBB.mjs +7 -0
  73. package/lib/chunk-CGWXQX75.mjs +7 -0
  74. package/lib/chunk-CHCHAE4B.mjs +7 -0
  75. package/lib/chunk-D3QRXG63.mjs +787 -0
  76. package/lib/chunk-DBFJB2B6.mjs +7 -0
  77. package/lib/chunk-DLDX6RRC.mjs +7 -0
  78. package/lib/chunk-EADHKH3A.mjs +7 -0
  79. package/lib/chunk-EEVVGGM6.mjs +7 -0
  80. package/lib/chunk-ENLBYECD.mjs +7 -0
  81. package/lib/chunk-EQF2IJS2.mjs +11 -0
  82. package/lib/chunk-EQOQASDQ.mjs +7 -0
  83. package/lib/chunk-F2424IKX.mjs +7 -0
  84. package/lib/chunk-F74IHMGL.mjs +7 -0
  85. package/lib/chunk-FOVVHGEP.mjs +7 -0
  86. package/lib/chunk-FQBRBBY4.mjs +7 -0
  87. package/lib/chunk-FQGHL7GR.mjs +259 -0
  88. package/lib/chunk-GAM726CK.mjs +7 -0
  89. package/lib/chunk-GCOB7K5N.mjs +7 -0
  90. package/lib/chunk-GMY5427L.mjs +7 -0
  91. package/lib/chunk-GNC27UEU.mjs +7 -0
  92. package/lib/chunk-H2PJNIYJ.mjs +7 -0
  93. package/lib/chunk-H45UXY6G.mjs +7 -0
  94. package/lib/chunk-HCIDVIOW.mjs +7 -0
  95. package/lib/chunk-HF6LAK3G.mjs +7 -0
  96. package/lib/chunk-HJC7AIBK.mjs +7 -0
  97. package/lib/chunk-HJKM3E56.mjs +7 -0
  98. package/lib/chunk-HTJ5OGP5.mjs +7 -0
  99. package/lib/chunk-HUMEKZT5.mjs +8 -0
  100. package/lib/chunk-HV2MXMGI.mjs +7 -0
  101. package/lib/chunk-HXS7ORUF.mjs +11 -0
  102. package/lib/chunk-I3JKJTLO.mjs +110 -0
  103. package/lib/chunk-I7O6C2B5.mjs +8 -0
  104. package/lib/chunk-IAZB4WIL.mjs +7 -0
  105. package/lib/chunk-IC2C2GOF.mjs +8 -0
  106. package/lib/chunk-IEYG5ATY.mjs +7 -0
  107. package/lib/chunk-INIQ23K6.mjs +7 -0
  108. package/lib/chunk-INIT2UKJ.mjs +7 -0
  109. package/lib/chunk-J7HVXMSW.mjs +7 -0
  110. package/lib/chunk-JVL444U5.mjs +7 -0
  111. package/lib/chunk-K22PA4XL.mjs +7 -0
  112. package/lib/chunk-K2FBZIXY.mjs +7 -0
  113. package/lib/chunk-KLX67VPL.mjs +7 -0
  114. package/lib/chunk-L776PUMV.mjs +7 -0
  115. package/lib/chunk-LQ4DRFUH.mjs +9 -0
  116. package/lib/chunk-LRFAIUN7.mjs +7 -0
  117. package/lib/chunk-LV6G4XTK.mjs +7 -0
  118. package/lib/chunk-M6P5ZZLE.mjs +7 -0
  119. package/lib/chunk-MTMH6H2A.mjs +8 -0
  120. package/lib/chunk-MYTIL2JD.mjs +10 -0
  121. package/lib/chunk-NEVXIGR6.mjs +10 -0
  122. package/lib/chunk-NGSMZZDA.mjs +7 -0
  123. package/lib/chunk-NHWE66K5.mjs +7 -0
  124. package/lib/chunk-NM4MDLK4.mjs +7 -0
  125. package/lib/chunk-NTDN2JQZ.mjs +19 -0
  126. package/lib/chunk-NTOVCTRS.mjs +7 -0
  127. package/lib/chunk-NZ5ZZLKS.mjs +7 -0
  128. package/lib/chunk-OQOZAPCI.mjs +7 -0
  129. package/lib/chunk-OTWRDD6L.mjs +7 -0
  130. package/lib/chunk-P2PJYWGQ.mjs +7 -0
  131. package/lib/chunk-P42X3B4D.mjs +7 -0
  132. package/lib/chunk-P7GSGFJO.mjs +7 -0
  133. package/lib/chunk-PA3MKJVH.mjs +7 -0
  134. package/lib/chunk-PBI4BYWW.mjs +7 -0
  135. package/lib/chunk-PNCONNFJ.mjs +10 -0
  136. package/lib/chunk-PTTHSSQO.mjs +7 -0
  137. package/lib/chunk-PUOX4NBJ.mjs +8 -0
  138. package/lib/chunk-PZTSVQSF.mjs +7 -0
  139. package/lib/chunk-QPF6C5MX.mjs +7 -0
  140. package/lib/chunk-QQZZMKU3.mjs +7 -0
  141. package/lib/chunk-QROPNEGY.mjs +14 -0
  142. package/lib/chunk-QRV2OSIS.mjs +7 -0
  143. package/lib/chunk-QSRAEUGZ.mjs +7 -0
  144. package/lib/chunk-QWT2C74M.mjs +7 -0
  145. package/lib/chunk-RAAANPPG.mjs +7 -0
  146. package/lib/chunk-RACDTRZA.mjs +7 -0
  147. package/lib/chunk-RFEO2KAN.mjs +7 -0
  148. package/lib/chunk-RH3N2H7P.mjs +7 -0
  149. package/lib/chunk-RSWDYIHY.mjs +37 -0
  150. package/lib/chunk-RSYICMZG.mjs +8 -0
  151. package/lib/chunk-SAR5622P.mjs +7 -0
  152. package/lib/chunk-SBIMVCXT.mjs +101 -0
  153. package/lib/chunk-SCKUIE3R.mjs +7 -0
  154. package/lib/chunk-SFURUNJM.mjs +7 -0
  155. package/lib/chunk-SIOZXPFG.mjs +7 -0
  156. package/lib/chunk-SRPWW4A2.mjs +10 -0
  157. package/lib/chunk-SRQDABQ2.mjs +15 -0
  158. package/lib/chunk-SVS6UMDU.mjs +323 -0
  159. package/lib/chunk-T63U4OZJ.mjs +7 -0
  160. package/lib/chunk-TBZMC2VV.mjs +11 -0
  161. package/lib/chunk-TEOLMRDO.mjs +7 -0
  162. package/lib/chunk-TLH7AD35.mjs +7 -0
  163. package/lib/chunk-TNXUU6W7.mjs +14 -0
  164. package/lib/chunk-TQX3PURV.mjs +7 -0
  165. package/lib/chunk-TUACWKIH.mjs +7 -0
  166. package/lib/chunk-TW3N6W5Z.mjs +7 -0
  167. package/lib/chunk-TYYOBZMU.mjs +10 -0
  168. package/lib/chunk-TZE3Y7IQ.mjs +7 -0
  169. package/lib/chunk-UNDIBZWG.mjs +7 -0
  170. package/lib/chunk-VGW4MXXZ.mjs +7 -0
  171. package/lib/chunk-VHI54FBK.mjs +441 -0
  172. package/lib/chunk-VXHDBYMI.mjs +7 -0
  173. package/lib/chunk-W7KFAY55.mjs +7 -0
  174. package/lib/chunk-WFEB5X4U.mjs +8 -0
  175. package/lib/chunk-WIO4XO4F.mjs +7 -0
  176. package/lib/chunk-WJY54JO7.mjs +13 -0
  177. package/lib/chunk-WR2GIKWE.mjs +7 -0
  178. package/lib/chunk-WRU5FJFC.mjs +7 -0
  179. package/lib/chunk-X2PY6MWZ.mjs +7 -0
  180. package/lib/chunk-X65MT4W3.mjs +7 -0
  181. package/lib/chunk-XBG5SP6Q.mjs +7 -0
  182. package/lib/chunk-XCA5AONB.mjs +7 -0
  183. package/lib/chunk-XEFDB2R4.mjs +7 -0
  184. package/lib/chunk-XETCPL7E.mjs +7 -0
  185. package/lib/chunk-Y5CGXLUB.mjs +7 -0
  186. package/lib/chunk-Y6J6QFI2.mjs +7 -0
  187. package/lib/chunk-YAZO75G2.mjs +8 -0
  188. package/lib/chunk-YBU4Z4QV.mjs +7 -0
  189. package/lib/chunk-YMJVMFPY.mjs +7 -0
  190. package/lib/chunk-YPSRZRIT.mjs +7 -0
  191. package/lib/chunk-YS4G22C2.mjs +7 -0
  192. package/lib/chunk-YW2SBL4Z.mjs +7 -0
  193. package/lib/chunk-YYZL7UGV.mjs +7 -0
  194. package/lib/chunk-Z7X534S4.mjs +10 -0
  195. package/lib/chunk-ZE6HKRR4.mjs +9 -0
  196. package/lib/chunk-ZHJP7L3K.mjs +7 -0
  197. package/lib/chunk-ZJKCWBRJ.mjs +7 -0
  198. package/lib/chunk-ZLZRU6MO.mjs +7 -0
  199. package/lib/chunk-ZOVSMN5C.mjs +7 -0
  200. package/lib/chunk-ZPYJPGDK.mjs +7 -0
  201. package/lib/chunk-ZQOZ4EFW.mjs +7 -0
  202. package/lib/chunk-ZUTYVST5.mjs +7 -0
  203. package/lib/chunk-ZXH4MBWP.mjs +7 -0
  204. package/lib/chunk-ZYEE34WO.mjs +7 -0
  205. package/lib/sandforge-autopilot.mjs +157 -0
  206. package/lib/sandforge-backup.mjs +99 -0
  207. package/lib/sandforge-checkpoint.mjs +353 -0
  208. package/lib/sandforge-cleanup.mjs +56 -0
  209. package/lib/sandforge-clone.mjs +7 -0
  210. package/lib/sandforge-compare.mjs +54 -0
  211. package/lib/sandforge-dataops.mjs +7 -0
  212. package/lib/sandforge-empty.mjs +140 -0
  213. package/lib/sandforge-env.mjs +355 -0
  214. package/lib/sandforge-frozen.mjs +263 -0
  215. package/lib/sandforge-mcp.mjs +40 -0
  216. package/lib/sandforge-monitor.mjs +43 -0
  217. package/lib/sandforge-seed.mjs +7 -0
  218. package/lib/sandforge-sync.mjs +7 -0
  219. package/lib/sandforge.mjs +28 -0
  220. package/package.json +52 -4
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{a,b,c,d,e,f,g,h,i,j}from"./chunk-PUOX4NBJ.mjs";import"./chunk-EQF2IJS2.mjs";import"./chunk-RSYICMZG.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-TEOLMRDO.mjs";import"./chunk-NTDN2JQZ.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as SCENARIO_SIDECAR_SUFFIX,f as compiledForSidecar,g as nodeScenarioSidecarFiles,j as readScenarioRunSidecar,c as scenarioPackFingerprint,d as scenarioRunSidecar,b as scenarioRunSidecarSchema,h as scenarioSidecarPath,e as withAgentChoice,i as writeScenarioRunSidecar};
@@ -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{S as N}from"./chunk-6QSM2WIH.mjs";import{a as j,h as D}from"./chunk-TZE3Y7IQ.mjs";import{b as J}from"./chunk-CA5NAXSU.mjs";function se(e){return`sync-before-${e.replace(/[^A-Za-z0-9-]+/g,"-")}`.slice(0,200)}var oe=1e3;function he(e){let o=se(e.runId),d=new Map,a=e.everyMs??oe,g=()=>(e.now?.()??new Date).getTime(),S,I=Number.NEGATIVE_INFINITY,k,E=!1,R=h=>{if(S===void 0)return;let t=[...d].map(([l,c])=>({objectApiName:l,recordCount:c,truncated:!1}));e.meta.set(`backup:${o}`,{operationId:o,orgId:e.orgId,...e.organizationId!==void 0?{organizationId:e.organizationId}:{},objects:t,partial:h,timestamp:S,totalRecords:t.reduce((l,c)=>l+c.recordCount,0),origin:"sync",runId:e.runId},"backups")},z=()=>{if(E)return;let h=I+a-g();if(h<=0){k!==void 0&&clearTimeout(k),k=void 0,I=g(),R(!0);return}k??=setTimeout(()=>{if(k=void 0,!E){I=g();try{R(!0)}catch{}}},h),k.unref?.()};return{id:o,keep:async(h,t)=>{t.length!==0&&(d.has(h)||(S??=(e.now?.()??new Date).toISOString(),d.set(h,0),R(!0),await e.files.begin(o,h)),await e.files.append(o,h,t),d.set(h,(d.get(h)??0)+t.length),z())},close:()=>{E=!0,k!==void 0&&clearTimeout(k),k=void 0,R(!1)}}}var F=200,de=["LastModifiedDate","LastModifiedById"],ee=100,te=4e3,ae=20,ne=255;function ce(e=ne){return 2*Math.max(0,e)+2}function ke(e,o){let d=o===void 0||o.creatable.size+4>ee;if(e.toLowerCase()==="id")return{characters:ae,wide:d};let a=o?.fields?.find(g=>g.name.toLowerCase()===e.toLowerCase());return a&&["double","int","long","currency","percent"].includes(a.type??"")?{characters:(a.precision??a.digits??18)+2,wide:d}:{characters:ce(a?.length??ne),wide:d}}function fe(e){let o=e.wide?F/4:F,d=Math.floor((te+2)/(Math.max(1,e.characters)+2));return Math.max(1,Math.min(o,d))}function me(e,o){let d=fe(o),a=e.reduce((g,S)=>g+Math.ceil(Math.max(0,S)/d),0);return a>0?a+1:0}function u(e){return e.slice(0,15)}function U(e,o){if(typeof e=="number"&&Number.isFinite(e))return`#${e}`;if(!(typeof e!="string"||e===""))return o?u(e):e.toLowerCase()}function ue(e){return typeof e=="number"?String(e):`'${j(String(e))}'`}function ge(e,o){let d=[],a=[],g=0;for(let S of e){let I=ue(S);a.length>0&&(a.length>=o||g+I.length>te)&&(d.push(a),a=[],g=0),a.push(I),g+=I.length+2}return a.length>0&&d.push(a),d}function le(e,o,d){return`What these ${o} ${e} record(s) would write over in the target could not be read and kept first (${J(d)}), so none of them was written: a run writes over nothing it cannot put back.`}function Se(e){let o=new Map,d=new Map,a=new Set,g=new Map,S=new Map,I=new Map,k=new Map,E=new Map,R=new Map,z=t=>{let l=e.describe,c=e.viewsEncrypted;if(!l||!c)return Promise.resolve(new Set);let y=I.get(t);return y||(y=l(t).then(async f=>{let m=(f.fields??[]).filter(M=>M.type===N).map(M=>M.name);return m.length>0&&!await c()?new Set(m):new Set},()=>new Set),I.set(t,y)),y},h=t=>{let l=e.describe;if(!l)return Promise.resolve(new Set);let c=S.get(t);return c||(c=l(t).then(y=>new Set((y.fields??[]).filter(f=>f.type==="base64"||f.queryable===!1).map(f=>f.name)),()=>new Set),S.set(t,c)),c};return{before:async(t,l,c,y)=>{if(g.delete(t),l!=="update"&&l!=="upsert"||c.length===0)return;let f=l==="update"?"Id":y??"Id",m=f==="Id";try{D(t),D(f);let M=await h(t),p=await z(t),v=new Set,O=new Set,T=new Map;for(let n of c){let i=U(n[f],m);i!==void 0&&!T.has(i)&&T.set(i,n[f]);for(let[r,s]of Object.entries(n))if(!(r==="Id"||r===f||r==="attributes")&&!M.has(r)&&!(typeof s=="object"&&s!==null)){if(p.has(r)){O.add(r);continue}v.add(D(r))}}if(T.size===0||v.size===0&&O.size===0)return;let x=["Id",...m?[]:[f],...v],V=[...x,...de.filter(n=>!x.includes(n))],re=V.length>ee?F/4:F,$=new Map,P=R.get(t)===!1?x:V;for(let n of ge([...T.values()],re)){let i=s=>`SELECT ${s.join(", ")} FROM ${t} WHERE ${f} IN (${n.join(", ")})`,r;try{r=await e.query(i(P))}catch(s){if(P===x)throw s;P=x,R.set(t,!1),r=await e.query(i(P))}for(let s of r){let w=U(m?s.Id:s[f],m);w===void 0||typeof s.Id!="string"||$.set(w,[...$.get(w)??[],s])}}let K=o.get(t)??new Map,_=[],B=new Map,C=new Map,G=new Map;for(let n of c){let i=U(n[f],m),r=i===void 0?void 0:$.get(i),s=r?.length===1?r[0]:void 0,w=s?.Id;if(_.push(w),!s||w===void 0||a.has(u(w)))continue;typeof s.LastModifiedDate=="string"&&G.set(u(w),{id:w,at:s.LastModifiedDate,...typeof s.LastModifiedById=="string"?{by:s.LastModifiedById}:{}});let ie=K.get(u(w)),q=B.get(u(w))??{Id:w},Q=C.get(u(w))??new Set;for(let b of Object.keys(n))!v.has(b)||ie?.has(b)||b in q||(q[b]=s[b]??null,Q.add(b));Q.size!==0&&(B.set(u(w),q),C.set(u(w),Q))}if(O.size>0&&_.some(n=>n!==void 0&&!a.has(u(n)))){let n=k.get(t)??new Set,i=[...O].filter(r=>!n.has(r));if(i.length>0){for(let r of i)n.add(r);k.set(t,n),e.recorder.unkept?.(t,i)}}if(B.size===0){g.set(t,{reaches:_,named:[],added:new Map});return}let X=[...B.values()],L=d.get(t)??new Map,Y=X.flatMap(n=>{let i=L.get(u(n.Id)),r=Object.entries(n).filter(([s])=>s==="Id"||!i?.has(s));return r.length>1?[Object.fromEntries(r)]:[]});Y.length>0&&await e.backup.keep(t,Y);for(let n of Y){let i=L.get(u(n.Id))??new Set;for(let r of Object.keys(n))r!=="Id"&&i.add(r);L.set(u(n.Id),i)}d.set(t,L);let A=X.map(n=>n.Id),W=E.get(t)??new Set,H=[];for(let n of A){let i=u(n);if(W.has(i))continue;W.add(i);let r=G.get(i);r&&H.push(r)}E.set(t,W),H.length>0?e.recorder.overwriting?.(t,e.backup.id,A,H):e.recorder.overwriting?.(t,e.backup.id,A);let Z=await e.recorder.flush();if(Z!==void 0)throw new Error(`the run's file could not be written: ${Z}`);for(let[n,i]of C){let r=K.get(n)??new Set;for(let s of i)r.add(s);K.set(n,r)}o.set(t,K),g.set(t,{reaches:_,named:A,added:C});return}catch(M){return le(t,c.length,M)}},answered:(t,l,c)=>{if(l==="insert"||l==="upsert")for(let p of c)p.success&&typeof p.id=="string"&&p.id!==""&&(l==="insert"||p.created===!0)&&a.add(u(p.id));let y=g.get(t);if(g.delete(t),!y||y.named.length===0)return;let f=new Set;c.forEach((p,v)=>{let O=y.reaches[v];O!==void 0&&p.success&&p.created!==!0&&f.add(u(O))});let m=y.named.filter(p=>!f.has(u(p))),M=o.get(t);for(let p of m){let v=M?.get(u(p));for(let O of y.added.get(u(p))??[])v?.delete(O)}e.recorder.overwrote?.(t,m)}}}export{se as a,he as b,ae as c,ce as d,ke as e,me as f,Se as g};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{a,b,c,d,e}from"./chunk-RSYICMZG.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as AIDataGenerator,c as buildPrompt,d as parseAIResponse,b as phoneReplacement,e as reachNobody};
@@ -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
+ var _=new Set(["ContentVersion","Attachment","EmailMessage","Task"]),c=new Set(["Account","Contact","Lead"]),a=class{resolve(t,e){let n=t==="auto"?e>200?"bulk":"rest":t,o=n==="bulk"?1e4:200,s=Math.ceil(e/o);return{api:n,batchSize:o,batchCount:s}}};export{_ as a,c as b,a as c};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{a as P}from"./chunk-ZUTYVST5.mjs";import{d as X}from"./chunk-55HEMHEG.mjs";import{d as Z}from"./chunk-WIO4XO4F.mjs";import{a as F}from"./chunk-EADHKH3A.mjs";import{c as H,g as Y}from"./chunk-GCOB7K5N.mjs";import{f as Q,s as W}from"./chunk-CGWXQX75.mjs";import{a as U,f as D,h as _}from"./chunk-TZE3Y7IQ.mjs";import{J as B,L as z,O as V,Tb as k}from"./chunk-B45CNPUX.mjs";import{b as I,k as C,l as A,v as K,z as R}from"./chunk-7EANH5PY.mjs";function Pe(e){let n=new Set;for(let t of e)t.controllerName&&n.add(t.controllerName);return n}function J(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}function Me(e,n){let t=J(e.precision),r=typeof e.scale=="number"&&e.scale>=0?e.scale:void 0,o=J(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 je(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 S(e){return[...ie[e]??["ignore"]]}var se=100,ae=new Set(["longest","colliding"]),T=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=B(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=>z(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 j(e){return[...new Set(e)].sort().slice(0,se)}function Ve(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:j(s)}:{},...o.controllingField?{controllingField:o.controllingField}:{},...o.replacedBy!==void 0?{replacement:o.replacedBy}:{}},decisions:S("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"&&W(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(l=>[l.name,l])),u=o.filter(ne),g=o.filter(l=>l.createable&&ce.has(l.type??"")&&(l.length??0)>0),f=o.filter(l=>l.createable&&(ue.has(l.type??"")||l.type==="int")&&ee(l)!==void 0),y=[...i].filter(([l,c])=>c.anyValue===!0&&s?.has(l)===!0),m=o.filter(l=>l.createable&&l.controllerName!==void 0&&l.validFor!==void 0);for(let{payload:l,source:c,typed:p}of r){for(let a of ge(t,l,c,u))n.add({kind:"required_field_missing",severity:"blocking",objectApiName:t,field:a.name,rows:1,...a.type?{detail:{type:a.type}}:{},decisions:S("required_field_missing")});for(let a of g){let h=l[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:S("value_too_long")})}for(let a of f){let h=me(l[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:S("number_out_of_range")})}for(let[a,h]of y){let b=l[a];if(typeof b!="string"||b==="")continue;let O=s?.get(a),E=h.multi?b.split(";"):[b];for(let v of new Set(E))O?.has(v)||n.add({kind:"picklist_value_absent",severity:"info",objectApiName:t,field:a,value:v,rows:1,decisions:S("picklist_value_absent")})}if(!p)for(let a of m){let h=l[a.name];if(typeof h!="string"||h==="")continue;let b=d.get(a.controllerName??""),O=ye(b,l[a.controllerName??""]),E=i.get(a.name)?.restricted===!0,v=i.get(a.name)?.multi?h.split(";"):[h];for(let G of new Set(v)){let $=a.validFor?.[G];$!==void 0&&(O>=0&&M($,O)||n.add({kind:"dependent_value_invalid",severity:E?"blocking":"warning",objectApiName:t,field:a.name,value:G,rows:1,detail:{controllingField:a.controllerName??"",allowed:j((b?.controllingValues??[]).filter((De,oe)=>M($,oe)))},decisions:S("dependent_value_invalid")}))}}}}function Ue(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:S("currency_inactive"),defaultDecision:"map_value"}}function Qe(e,n,t,r){return{kind:"unique_value_collision",severity:"warning",objectApiName:e,field:n,rows:t,detail:{colliding:r,linkedToTheRecordItNames:!0},decisions:S("unique_value_collision"),defaultDecision:"ignore"}}function We(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:j(o)},decisions:S(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 w(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 x(e){return typeof e=="number"&&Number.isFinite(e)?String(e):typeof e=="boolean"?e?"true":"false":`'${U(String(e))}'`}var be=200,we=4e3;function N(e){let n=[],t=[],r=0;for(let o of e){let s=x(o).length+2;t.length>0&&(t.length>=be||r+s>we)&&(n.push(t),t=[],r=0),t.push(o),r+=s}return t.length>0&&n.push(t),n}function nn(e,n){return async(t,r,o,s)=>{let i=k(r.objectApiName),d=_(o),u=new Map;for(let g of N(s)){if(n?.aborted)throw new Error("The simulation was cancelled.");let{records:f}=await F(e,`SELECT ${d} FROM ${i} WHERE ${d} IN (${g.map(x).join(", ")})`);for(let y of f){let m=w(y[d]);m!==null&&u.set(m,(u.get(m)??0)+1)}}return u}}var Se=new Set(["attributes","Id"]);function ke(e,n,t,r){return n?e.conflictFields.filter(o=>o!==t&&!Se.has(o)&&o in n&&(r===null||r.has(o))):[]}var tn=new Set(["noKey","notInTarget","ambiguous"]);function Re(e,n,t){let r=e.operation,o=re(e);if(o===null)return"insert";let s=w(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"}function rn(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((c,p)=>{let a=Re(n,c,r);i[a]++,(a==="insert"||a==="update")&&d.add(p)});let u=e.leftOut.map(({why:c,count:p})=>Q(p,c));i.noKey>0&&u.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&&u.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&&u.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&&u.push(`${i.notSent} record(s) carry no Id: a delete sends ids alone, so the run leaves them out.`);let g=new Map;e.unsettled.forEach((c,p)=>{let a=String(c[e.matchField]??"");a&&d.has(p)&&g.set(a,c)});let f=new Map,y=0;for(let c of e.conflicts){let p=ke(c,g.get(c.recordId),e.matchField,e.writable);if(p.length!==0){y++;for(let a of p)f.set(a,(f.get(a)??0)+1)}}let m=[...f].sort(([c,p],[a,h])=>h-p||c.localeCompare(a)).slice(0,he).map(([c])=>c),l=e.leftOut.reduce((c,{count:p})=>c+p,0);return{objectApiName:n.objectApiName,operation:o,read:e.read,insert:i.insert,update:i.update,delete:i.delete,skipped:l+i.notSent,refused:i.noKey+i.notInTarget+i.ambiguous,conflicts:y,conflictFields:m,notes:u}}function _e(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 on(e,n,t){let r=new Set,o=new T;n.forEach(({payload:i,source:d,creates:u},g)=>{let f=new T;te({objectApiName:e,rows:[{payload:i,source:d,typed:!0}],targetFields:t,picklistValuesByField:null,picklistFields:new Map},f);let y=f.list(new Set).filter(m=>m.severity==="blocking"&&(u||m.kind!=="required_field_missing"));if(y.length!==0){r.add(g);for(let m of y)o.add(m)}});let s=o.list(new Set).flatMap(i=>{let d=_e(i);return d?[d]:[]});return{refused:r,notes:s}}function sn(e,n){let t=new Set,r=new Set,o=[];for(let[s,i]of n){let d=new Set,u=0,g=0,f=0;e.forEach((y,m)=>{let l=w(y[s]);if(l===null)return;let c=i.get(l)??0;c===1?(u++,r.add(m)):c>1?(g++,t.add(m)):d.has(l)&&(f++,t.add(m)),d.add(l)}),u>0&&o.push(`LINKED_TO_EXISTING: ${u} record(s) hold a ${s} 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+f!==0&&o.push(`${g+f} record(s) hold a ${s} the target keeps unique, which `+[g>0?`several records of the target hold already (${g})`:"",f>0?`a record sent before them holds (${f})`:""].filter(Boolean).join(" or ")+": it refuses them (DUPLICATE_VALUE).")}for(let s of t)r.delete(s);return{refused:t,linked:r,notes:o}}import{createHash as Fe}from"node:crypto";var Ie=5*6e4,Te=500,xe=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:R.datetime(),fingerprint:I().regex(/^[0-9a-f]{64}$/),recordedAt:R.datetime(),filesSeen:R.datetime().optional(),removedAt:R.datetime().optional()}),Oe=A({version:K(1),entries:C(xe).max(Te),resetAt:R.datetime().optional()});function mn(e){if(e==null)return{kind:"none"};let n=Oe.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 L(e){return Array.isArray(e)?`[${e.map(L).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)}:${L(r)}`).join(",")}}`:JSON.stringify(e)}function q(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:q(n.externalIdField),where:q(n.where),fieldMappings:n.fieldMappings??[],unmappedSentAsRead:(n.fieldMappings??[]).length>0?!0:void 0,transformRules:n.transformRules??[],excludedFields:n.excludedFields??[],addOnFields:n.addOnFields??[]};return Fe("sha256").update(L(t)).digest("hex")}function yn(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 Ne=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;function hn(e,n=Ie){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 bn(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 Ee(e){if(!Ne.test(e)||!Number.isFinite(Date.parse(e)))throw new Error(`Not a SOQL datetime: "${e}".`);return e}function wn(e,n){let t=e?.trim()?D(e):void 0;if(n===void 0)return t;let r=`SystemModstamp > ${Ee(n)}`;return t?`${r} AND (${t})`:r}function $e(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 Sn(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=k(i),g=(await e.query(`SELECT SystemModstamp FROM ${d} ORDER BY SystemModstamp DESC LIMIT 1`)).records[0];if(!g)return null;let f=$e(g.SystemModstamp);if(f===null)throw new Error(`${d} answered a SystemModstamp that is not a date.`);return f},async deletedRows(i,d,u){let g=k(i),f=new Set(["Id","SystemModstamp",...d.map(_)]),{records:y,truncated:m}=await F(o,`SELECT ${[...f].join(", ")} FROM ${g} WHERE IsDeleted = true AND (${D(u)})`);return{records:y,truncated:m}},async heldInSource(i,d,u){let g=k(i),f=_(d),y=new Set;for(let m of N(u)){s();let{records:l}=await F(r,`SELECT ${f} FROM ${g} WHERE ${f} IN (${m.map(x).join(", ")})`);for(let c of l){let p=w(c[f]);p!==null&&y.add(p)}}return y},async targetIdsByKey(i,d,u){let g=k(i),f=_(d),y=f==="Id"?"Id":`Id, ${f}`,m=new Map;for(let l of N(u)){s();let{records:c}=await F(n,`SELECT ${y} FROM ${g} WHERE ${f} IN (${l.map(x).join(", ")})`);for(let p of c){let a=w(p[f]);a===null||typeof p.Id!="string"||m.set(a,[...m.get(a)??[],p.Id])}}return m}}}var Ae=new Set(["direct","rename","transform"]);function kn(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=q(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&&!X(r,e.excludedFields??[]).has(t.toLowerCase())?{sourceField:t,keyField:t}:!o||!Ae.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 Rn(e,n,t,r,o){let s=n.objectApiName,{records:i,truncated:d}=await e.deletedRows(s,[t.sourceField],r),u={ids:[],read:i.length,stillInSource:0,ambiguous:0,noKey:0,truncated:d};if(i.length===0)return u;let g=[];for(let c of i){let p=c[t.sourceField],a=o(c);if(w(p)===null||w(a)===null){u.noKey++;continue}g.push({raw:p,key:a})}if(g.length===0)return u;let f=t.sourceField==="Id"?new Set:await e.heldInSource(s,t.sourceField,g.map(c=>c.raw)),y=g.filter(c=>f.has(w(c.raw))?(u.stillInSource++,!1):!0);if(y.length===0)return u;let m=await e.targetIdsByKey(s,t.keyField,y.map(c=>c.key)),l=new Set;for(let c of y){let p=m.get(w(c.key))??[];p.length>1?u.ambiguous++:p.length===1&&!l.has(p[0])&&(l.add(p[0]),u.ids.push(p[0]))}return u}function _n(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 Fn(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{Pe as a,Me as b,je as c,ie as d,T as e,de as f,le as g,Ve as h,ge as i,te as j,Ue as k,Qe as l,We as m,re as n,w as o,nn as p,tn as q,Re as r,rn as s,on as t,sn as u,Ie as v,mn as w,yn as x,hn as y,bn as z,Ee as A,wn as B,$e as C,Sn as D,kn as E,Rn as F,_n as G,Fn as H};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{ld as s,md as d}from"./chunk-B45CNPUX.mjs";function c(l,e){return l.type==="condition"&&e.status==="completed"&&e.output?.conditionMet===!1}var f=class{evaluate(e,n){return d(e,n)}check(e){return s(e)}evaluateGroup(e,n){return e.length===0?!0:e.some(t=>t.logicalGroup==="or")?e.some(t=>this.evaluate(t,n)):e.every(t=>this.evaluate(t,n))}getNextStep(e,n){if(n.status==="completed")return c(e,n)?e.onFailure:e.onSuccess;if(n.status==="failed")return e.onFailure}endsRun(e,n){return c(e,n)&&!e.onFailure}findBranch(e,n,o){let t=new Map(e.map(r=>[r.id,r])),u=[],a=new Set,i=n,p=t.get(i);if(!p)return u;for(i=o?p.onSuccess:p.onFailure;i&&!a.has(i);){a.add(i);let r=t.get(i);if(!r)break;u.push(r),i=o?r.onSuccess:r.onFailure}return u}};export{f 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{h as u,i as f}from"./chunk-B45CNPUX.mjs";var p=1e4,g=150,m=200,l=class{build(o){let t=o.relations??[],c=j(o.objects,t),i=S(c),r=b(c),n=r*g,s=i>p;return{objects:c.map(a=>({objectApiName:a.objectApiName,recordCount:a.recordCount,sampleRecords:C(a,3,u(a.objectApiName,t)),dependsOn:f(a,t)})),totalRecords:i,estimatedApiCalls:r,estimatedDuration:n,grappeRecommended:s}}};function S(e){return e.reduce((o,t)=>o+t.recordCount,0)}function b(e){return e.reduce((o,t)=>{let c=t.batchSize>0?t.batchSize:m;return o+Math.ceil(t.recordCount/c)},0)}function C(e,o,t){let c=Math.min(o,e.recordCount),i=[];for(let r=0;r<c;r++){let n={};for(let d of e.fieldRules)n[d.fieldApiName]=R(d,r);let s=e.rows?.[r];s&&(Object.assign(n,s.values),t?.distribution.mode==="byKey"&&s.parentKey!==void 0&&(n[t.lookupField]=`[key:${s.parentKey}]`)),i.push(n)}return i}function R(e,o){switch(e.ruleType){case"static":return e.config.staticValue??null;case"sequence":{let t=e.config.sequenceStart??1,c=e.config.sequenceStep??1;return`${e.config.sequencePrefix??""}${t+o*c}`}case"picklist_random":return e.config.picklistValues&&e.config.picklistValues.length>0?e.config.picklistValues[o%e.config.picklistValues.length]:null;case"reference":return`[ref:${e.config.referenceObject??"unknown"}]`;case"faker":return`[faker:${e.config.fakerMethod??"lorem"}]`;case"ai_generate":return`[ai:${e.config.aiPrompt??"generated"}]`;case"random":return`sample_${o}`;case"formula":return`[formula:${e.config.formula??""}]`;case"regex":return`[regex:${e.config.regexPattern??""}]`;case"from_csv":return`[csv:${e.config.csvColumn??""}]`;default:return null}}function j(e,o=[]){let t=new Map;for(let n of e)t.set(n.objectApiName,n);let c=new Set,i=[];function r(n){if(c.has(n))return;c.add(n);let s=t.get(n);if(!s)return;let d=f(s,o);for(let a of d)r(a);i.push(s)}for(let n of e)r(n.objectApiName);return i}export{l as a,j as b};
@@ -0,0 +1,8 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{i as Xe,k as Ye}from"./chunk-MYTIL2JD.mjs";import{d as Ie,i as Le}from"./chunk-JVL444U5.mjs";import{b as Z}from"./chunk-KLX67VPL.mjs";import{c as qe,d as Ze}from"./chunk-5CD257T7.mjs";import{a as Ne,b as De}from"./chunk-5P4PHJRL.mjs";import{c as Oe,d as Ae,j as Te}from"./chunk-SRQDABQ2.mjs";import{a as Ce}from"./chunk-LV6G4XTK.mjs";import{A as ee,B as nt,o as Re,u as et,v as tt}from"./chunk-Z7X534S4.mjs";import{$ as X,T as je,X as xe,Z as We,_ as Q,aa as Y,ba as _e,ca as Ge,da as Ue,ga as ze,ha as Ve,ia as L,ka as q,na as He}from"./chunk-6QSM2WIH.mjs";import{a as Be,v as Ke,w as Je,z as Qe}from"./chunk-WJY54JO7.mjs";import{E as $e,G as Fe,a as Me,e as Pe,o as J,x as ve,y as Ee,z as I}from"./chunk-NEVXIGR6.mjs";import{C as Se}from"./chunk-HJC7AIBK.mjs";import{c as V}from"./chunk-RH3N2H7P.mjs";import{f as he,g as be,h as F,m as ke,n as we,o as H,t as ye,u as K}from"./chunk-PA3MKJVH.mjs";import{b as v}from"./chunk-CA5NAXSU.mjs";import{Tb as $,va as pe,wa as E,za as ge,zd as me}from"./chunk-B45CNPUX.mjs";import{b as ue,k as fe,l as z}from"./chunk-7EANH5PY.mjs";import{readdir as Rt,rm as at,stat as ct}from"node:fs/promises";import{existsSync as Nt,readFileSync as Dt,writeFileSync as Mt}from"node:fs";import{hostname as Pt}from"node:os";import{join as ne}from"node:path";var vt=5e5,Et=1e6,$t=100,Ft="taking",ot=500;function xn(e){let t=We(e),n=[V(e)];return{get version(){return e.version},request:o=>t.request(o),query:(o,s)=>t.query(o,s),queryMore:o=>t.queryMore(o),describeGlobal:async()=>await e.describeGlobal(),toolingObjects:async()=>{try{return(await e.tooling.describeGlobal()).sobjects.map(s=>s.name)}catch{return[]}},serverTime:async()=>(await e.soap.getServerTimestamp()).timestamp,userId:async()=>(await e.soap.getUserInfo()).userId,requestsSent:()=>n.reduce((o,s)=>o+s(),0),countAlso:o=>{n.push(V(o))}}}function It(e){return Be(Ne(e))}var N=class extends Error{constructor(){super("The checkpoint was stopped before it was taken: nothing of it was kept."),this.name="CheckpointTakeStopped"}},x="No record was read.",Lt={excludedByUser:"Left out as asked.",notFound:"The org has no object of this name.",chatter:"Chatter posts, comments and feeds are left out: Salesforce brings a post back only with what it was posted on.",history:"History is left out: it is the org's own trace of changes.",sharing:"Sharing is left out: the org keeps it itself.",changeEvent:"Change events are left out.",unsupportedKind:"Left out: neither the recycle bin nor an update reaches this kind of object as it reaches a record.",customSetting:"Custom settings are left out unless you pick them as custom settings: they are configuration, which a rewind sets back.",notCustomSetting:"Picked as a custom setting: the org has no custom setting of this name.",files:"Documents of the Documents tab are left out: they are shared content kept in folders, as setup is.",heldWithFiles:"Held with its file (ContentDocument): Salesforce neither deletes nor brings back a file's version on its own, and reads the links of a file through the records they tie it to.",setup:"Users, permissions and setup are left out, and so are the org's own logs and jobs.",platformCreated:"Left out: Salesforce alone creates its records, such as approvals, Einstein insights, Data.com clean info and invoices, and no permission lets a user create one.",metadata:"Left out: it is metadata, which a checkpoint doesn't hold.",notWritable:"Left out: the user SandForge connects as may not create, edit and delete its records.",notDescribed:"Left out: the org would not describe it.",noSystemModstamp:"Left out: it has no SystemModstamp, so nothing would tell a record changed since.",noRecycleBin:"Left out: the org deletes its records for good, with no recycle bin, so nothing would tell one deleted since, nor bring it back.",unreadable:"Left out: the org refuses to read it whole.",noViewAll:"Without View All Data and Modify All Data, an object is held only with View All and Modify All on it, and the user SandForge connects as has neither on this one: a record they cannot see would read as deleted since.",noModifyAll:"Without View All Data and Modify All Data, an object is held only with View All and Modify All on it, and the user SandForge connects as has View All on this one, not Modify All: a rewind could not put back what others changed.",activities:"Without View All Data and Modify All Data, tasks and events are left out: Salesforce has no View All for activities, and a private one linked to no record stays out of sight.",catalog:"Without View All Data and Modify All Data, products and price books are left out: Salesforce has no View All or Modify All for them.",filesNotProven:"Without View All Data and Modify All Data, files are left out: nothing proves the user sees every file.",settingNotProven:"Without View All Data and Modify All Data, custom settings are left out: no permission on an object proves the user sees and writes every row.",parentNotSeen:"Without View All Data and Modify All Data, an object with no permissions of its own is held only when the user has View All and Modify All on every record it hangs from, which is not proven here."};function dt(e){let t=Lt[e.reason],n=e.detail===void 0?t:`${t.replace(/\.$/,"")} (${e.detail}).`;return{objectApiName:e.objectApiName,code:e.reason,reason:st(n),...e.detail===void 0?{}:{detail:st(e.detail)}}}function xt(e,t,n){return{objectApiName:e,code:"pastTheLimit",records:t,limit:n,reason:`${e} has ${t} records, past the checkpoint's limit of ${n} for one object: left out of the checkpoint, as part of it would be taken for all of it.`}}function st(e){return e.length<=ot?e:`${e.slice(0,ot-1)}\u2026`}function lt(e,t){return{code:"RUN_WRITING",message:`${t.operation==="take"?`A checkpoint of ${e} is being taken`:t.operation==="rewind"?`A rewind is writing to ${e}`:t.operation==="undo"?`An undo is writing to ${e}`:t.operation==="empty"?`An emptying of its objects is writing to ${e}`:`SandForge is deleting checkpoints of ${e}`} (process ${t.pid} on ${t.host}): take the checkpoint once it has ended. ${x}`}}function ut(e){return typeof e!="object"||e===null?void 0:typeof e.errorCode=="string"?v(e):void 0}function W(e,t){return e instanceof Q||e instanceof Ce||e instanceof N||t?.aborted===!0}var Wt=z({sobjects:fe(he)}).loose();function D(e){return e.toLowerCase()===be.toLowerCase()}function Bt(e,t,n){if(e===void 0)return{why:`the org lists no ${F}`};let o=t.get(e);if(o===void 0)return{why:n.get(e)??"it was not described"};let a=o.fields.find(d=>d.name.toLowerCase()==="linkedentityid")?.referenceTo??[];return a.length===0?{why:"its describe names no record a link ties a file to"}:{linkable:new Set(a.map(d=>d.toLowerCase()))}}async function oe(e,t,n){let o=new Map,s=new Map,a=0,d=await Promise.allSettled(n.map(f=>t.describe(f)));for(let[f,i]of d.entries()){let c=n[f],l;if(i.status==="fulfilled"&&"body"in i.value)l=i.value.body;else{if(i.status==="rejected"&&i.reason instanceof Q)throw i.reason;a++;try{l=await e.request({method:"GET",url:`/services/data/v${e.version}/sobjects/${$(c)}/describe`})}catch(h){let r=ut(h);if(r===void 0)throw new Error(`The org did not answer the describe of ${c}: ${v(h)}`);s.set(c,r);continue}}let u=Ie.safeParse(l);u.success?o.set(c,u.data):s.set(c,"its describe does not read as one")}return{describes:o,errors:s,alone:a}}async function ft(e,t,n){let o=Wt.parse(await e.describeGlobal()),s=await e.toolingObjects?.()??[],a=we(o.sobjects,{mode:n.mode,...n.objects?{objects:n.objects}:{},...n.excluded?{excluded:n.excluded}:{},...n.customSettings?{customSettings:n.customSettings}:{}},s),d=a.candidates.some(D),f=d?o.sobjects.find(g=>g.name.toLowerCase()===F.toLowerCase())?.name:void 0,i=f===void 0?a.candidates:[...a.candidates,f],{describes:c,errors:l,alone:u}=await oe(e,t,i),h,r;if(d){let g=Bt(f,c,l);"linkable"in g?h=g.linkable:r=g.why,f!==void 0&&c.delete(f)}let m=ye(a,c,l);if(r!==void 0){let g=m.objects.find(({objectApiName:A})=>D(A));g!==void 0&&(m=K(m,new Map([[g.objectApiName,`its links to records, ${F}, could not be described: ${r}`]])))}let w=await je(async g=>(await e.query(g)).records),S=new Map(o.sobjects.map(g=>[g.name,it(g)])),O=o.sobjects.filter(ke),p=new Set(O.map(g=>g.name)),b=[...c.values()],y=[];for(let g of m.objects){let A=c.get(g.objectApiName);A&&y.push({scoped:g,label:S.get(g.objectApiName)??g.objectApiName,describe:A,capture:await Le(A,b,{viewsEncryptedData:w}),...p.has(g.objectApiName)?{customSetting:H(A)}:{}})}return{described:i.length,describedAlone:u,objects:y,leftOut:m.leftOut,addedToPicked:a.addedToPicked,...h!==void 0&&y.some(({scoped:g})=>D(g.objectApiName))?{linkable:h}:{},settings:O.map(g=>({objectApiName:g.name,label:it(g)}))}}function it(e){let t=e.label;return typeof t=="string"&&t!==""?t:e.name}async function _t(e,t,n,o){let s=await q(t,n.map(({capture:i})=>({objectApiName:i.objectApiName,readMode:i.readMode})),o),a=new Map,d=new Map,f=0;for(let[i,c]of s.entries()){let{objectApiName:l,readMode:u}=n[i].capture;if("count"in c){a.set(l,c.count);continue}f++;let h=Ge(l,u);try{let r=await e.query(h.soql,{scanAll:h.scanAll});if(typeof r.totalSize!="number")throw new Error("The org gave no count of its records.");a.set(l,r.totalSize)}catch(r){let m=ut(r);if(m===void 0)throw new Error(`The org did not count the records of ${l}: ${v(r)}`);d.set(l,m)}}return{counts:a,refused:d,alone:f}}function pt(e,t){return t?.has(e.toLowerCase())===!0&&!D(e)}async function Gt(e,t,n,o,s){let a=[];for(let{objectApiName:i,records:c}of t){let l=$(i);a.push({objectApiName:l,soql:`SELECT COUNT() FROM ${l} WHERE IsDeleted = true AND SystemModstamp < ${Y(o)}`,scanAll:!0,counts:"inBin"}),c!==0&&(a.push({objectApiName:l,soql:`SELECT COUNT() FROM ${l} WHERE SystemModstamp >= ${_e(o)}`,scanAll:!0,counts:"stampedSince"}),pt(l,n)&&a.push({...Xe(l),counts:"links"}))}let d=await ze(e,a,()=>{},s),f=new Map;return d.forEach((i,c)=>{let{objectApiName:l,counts:u}=a[c],h=i.read?i.totalSize:void 0,r=f.get(l)??{};u==="links"?r.links=h??null:h!==void 0&&(r[u]=h),f.set(l,r)}),{asked:a.length,of:f}}function gt({scoped:e,capture:t,customSetting:n,access:o},s,a,d){return{objectApiName:e.objectApiName,records:s,inBin:a,readOrder:e.readOrder,readMode:t.readMode,undeletable:t.undeletable,cascadeParents:t.cascadeParents,restrictParents:t.restrictParents,fingerprint:d,fields:t.fields,leftOutFields:t.leftOutFields,...n!==void 0?{customSetting:n}:{},...o!==void 0?{access:o}:{}}}function Ut(e){let t=e?.orgType==="Sandbox"||e?.orgType==="Scratch";return Oe(Ae(t)).defaultQueryLimit}async function mt(e,t,n,o,s,a,d,f=bt){let i=n.maxTotal??vt;if(!Number.isInteger(i)||i<1)throw new RangeError(`Not a number of records: ${i}`);let c=Math.min(i,Et),{counts:l,refused:u,alone:h}=await _t(e,t,o.objects,d),r=K({mode:n.mode,objects:o.objects.map(({scoped:k})=>k),leftOut:o.leftOut,packages:[]},u),m=new Map(o.objects.map(k=>[k.scoped.objectApiName,k])),w=r.leftOut.map(dt),S=[];for(let k of r.objects){let j=m.get(k.objectApiName),P=l.get(k.objectApiName);if(!(j===void 0||P===void 0)){if(P>c){w.push(xt(k.objectApiName,P,c));continue}S.push({...j,scoped:{...k,readOrder:S.length},records:P,otherGroups:et(k.objectApiName,j.capture.fields,j.capture.readMode),recount:{}})}}let O=S.some(({scoped:k})=>D(k.objectApiName))?o.linkable:void 0,p=await Gt(t,S.map(({scoped:k,records:j})=>({objectApiName:k.objectApiName,records:j})),O,a,d);for(let k of S)k.recount=p.of.get(k.scoped.objectApiName)??{};w.sort((k,j)=>k.objectApiName<j.objectApiName?-1:k.objectApiName>j.objectApiName?1:0);let b={};for(let{scoped:k,describe:j}of S)b[k.objectApiName]=Me(j.fields);let y=zt(f,tt({described:o.described,describedAlone:o.describedAlone,counted:o.objects.length,countedAlone:h,recounted:p.asked,objects:S.map(k=>({records:k.records,otherGroups:k.otherGroups,...k.recount,entry:gt(k,k.records,0,b[k.scoped.objectApiName].digest)})),pageRows:Ut(n.registered),leftOut:w,printsBytes:(await Fe(b)).length})),g={...y,apiRequestsLeft:s.remaining},A={objects:S,leftOut:w,estimate:g,objectLimit:c,prints:b,...O!==void 0?{linkable:O}:{}};if(y.records>i)return{...A,refusal:{code:"TOO_MANY_RECORDS",message:`The objects this checkpoint would keep hold ${y.records} records in ${n.orgName}, past its limit of ${i}: pick fewer objects, or raise the limit. ${x}`}};let M=nt("take",y.apiRequests,s,n.orgName);return M===void 0?A:{...A,refusal:M}}function ht(e){return{query:t=>e.query(t),queryMore:t=>e.queryMore(t)}}var bt={guard:0,scope:0};function zt(e,t){if(e.guard+e.scope===0)return t;let n=t.requestsByPhase;return{...t,apiRequests:t.apiRequests+e.guard+e.scope,...n!==void 0?{requestsByPhase:{...n,guard:n.guard+e.guard,scope:n.scope+e.scope}}:{}}}function Vt(e){let t=[...e.mode==="picked"?e.objects??[]:[],...Array.isArray(e.customSettings)?e.customSettings:[]];return new Set(t.map(n=>n.toLowerCase()))}function Ht(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}async function kt(e,t,n,o,s,a){if(s.kind==="org")return{scope:{...o,objects:o.objects.map(p=>({...p,access:"org"}))},reads:bt};let d=o.objects.map(({scoped:p})=>p.objectApiName),f={grants:s.objects,describes:o.objects.map(({describe:p})=>p),customSettings:o.objects.filter(({customSetting:p})=>p!==void 0).map(({scoped:p})=>p.objectApiName)},i=qe(d,f),c=[],l=0;if(i.length>0)try{let p=await oe(e,t,i);c=[...p.describes.values()],l=Math.ceil(i.length/xe)+p.alone}catch(p){if(W(p,a))throw p}let u=Ze(d,{...f,describes:[...f.describes,...c]}),h=Vt(n),r=[],m=[...o.leftOut],w=[];for(let p of o.objects){let b=p.scoped.objectApiName,y=u.get(b);if(y!==void 0&&"access"in y){r.push({...p,access:y.access});continue}let g={objectApiName:b,reason:y?.reason??"noViewAll",...y?.detail!==void 0?{detail:y.detail}:{}};m.push(g),h.has(b.toLowerCase())&&n.unprovenLeftOut!==!0&&w.push(g)}let S=new Set(r.map(({scoped:p})=>p.objectApiName)),O={scope:{...o,objects:r,leftOut:m,addedToPicked:o.addedToPicked.filter(p=>S.has(p))},reads:{guard:s.requests,scope:l}};if(w.length>0){let p=w.length===1;return{...O,refusal:{code:"PERMISSIONS",message:`${n.username} doesn't have View All Data and Modify All Data, and the checkpoint can't hold ${Ht(w.map(b=>b.objectApiName))}, asked for by name. ${w.map(b=>`${b.objectApiName}: ${dt(b).reason}`).join(" ")} Leave ${p?"it":"them"} out, or give the user View All Data and Modify All Data. ${x}`}}}return r.length===0&&o.objects.length>0?{...O,refusal:{code:"PERMISSIONS",message:`${n.username} doesn't have View All Data and Modify All Data, nor View All and Modify All on any object this checkpoint would hold: without them, a checkpoint holds only the objects its user sees and puts back whole. Give the user View All and Modify All on the objects to hold, or View All Data and Modify All Data. `+x}}:O}function Kt(e){return e.objects.map(({scoped:t,label:n,capture:o,records:s,customSetting:a,access:d})=>({objectApiName:t.objectApiName,label:n,...t.namespace!==void 0?{namespace:t.namespace}:{},records:s,undeletable:o.undeletable,leftOutFields:o.leftOutFields,...a!==void 0?{customSetting:a}:{},...d!==void 0?{access:d}:{}}))}function wt(e){let t=e.customSettings;return t!==void 0&&(t==="all"||t.length>0)}async function Jt(e,t,n,o,s){let a=new Map(o.objects.map(u=>[u.scoped.objectApiName,u])),d=n.settings.filter(({objectApiName:u})=>!a.has(u)),f=new Map;if(d.length>0)try{({describes:f}=await oe(e,t,d.map(({objectApiName:u})=>u)))}catch(u){if(W(u,s))throw u}let i=d.filter(({objectApiName:u})=>f.has(u)),c=await q(t,i.map(({objectApiName:u})=>({objectApiName:u,readMode:"query"})),s),l=new Map;return c.forEach((u,h)=>{"count"in u&&l.set(i[h].objectApiName,u.count)}),n.settings.map(({objectApiName:u,label:h})=>{let r=a.get(u);if(r?.customSetting!==void 0)return{objectApiName:u,label:h,kind:r.customSetting,records:r.records};let m=f.get(u),w=l.get(u);return{objectApiName:u,label:h,...m!==void 0?{kind:H(m)}:{},...w!==void 0?{records:w}:{}}})}var Qt={records:0,apiRequests:0,apiRequestsLeft:0,seconds:0,bytes:0};async function Wn(e,t){let n={mode:t.mode,objects:[],leftOut:[],estimate:Qt},o=await Z(ht(e.org),{act:"take",orgName:t.orgName,registered:t.registered,username:t.username,customSettings:wt(t)},{userId:()=>e.org.userId()});if(!o.allowed)return{...n,refusal:o.refusal};let s=e.store.heldBy(o.org.id),a=s===void 0?await e.runWriting?.(o.org.id):void 0,d=X(e.org,e.signal);try{let f=await ee(e.org,t.orgName),i=await kt(e.org,d,t,await ft(e.org,d,t),o.grants,e.signal),{scope:c}=i,l=await e.org.serverTime(),u=await mt(e.org,d,t,c,f,l,e.signal,i.reads),h={mode:t.mode,objects:Kt(u),leftOut:u.leftOut,estimate:u.estimate,files:{held:u.objects.some(({scoped:m})=>D(m.objectApiName)),queryAllFiles:o.queryAllFiles,addedToPicked:c.addedToPicked},customSettings:await Jt(e.org,d,c,u,e.signal)},r=s!==void 0?lt(t.orgName,s):a!==void 0?{code:"RUN_WRITING",message:a}:i.refusal??u.refusal;return r===void 0?h:{...h,refusal:r}}catch(f){throw W(f,e.signal)?new N:f}}function Xt(e){let t=e.requestsSent?()=>e.requestsSent?.()??0:void 0,n={guard:0,scope:0,start:0,counts:0,bin:0,snapshot:0,stability:0},o="guard",s=t?.()??0,a=()=>{if(!t)return;let d=t();n[o]+=d-s,s=d};return{enter(d){a(),o=d},requests(){return t?(a(),{total:Object.values(n).reduce((f,i)=>f+i,0),byPhase:{...n}}):void 0}}}async function Yt(e,t){if(t.edition!==void 0)return t.edition;let o=(await e.query("SELECT OrganizationType FROM Organization LIMIT 1")).records[0]?.OrganizationType;if(typeof o!="string"||o==="")throw new Error("The org did not say its edition (Organization.OrganizationType).");return o}var qt="Automated Process";async function Zt(e){let n=(await e.query("SELECT Id, Name FROM User WHERE UserType = 'AutomatedProcess'")).records.filter(s=>typeof s.Id=="string"),o=n.find(s=>s.Name===qt);return o!==void 0?o.Id:n.length===1?n[0].Id:void 0}function yt(e){let t=new Date(Date.parse(e)).toISOString();return`${t.slice(0,10)} ${t.slice(11,16)} UTC`}function rt(e,t){return e.split(me).join(yt(t))}function te(e){let t=Se(e);return t===null?Number.NaN:Date.parse(t)}function St(e){return typeof e=="string"&&e.length>=15?e.slice(0,15):void 0}async function en(e,t){let n=new Set;for await(let o of L(J(e,t))){let s=St(o.Id);s!==void 0&&n.add(s)}return n}async function tn(e,t,n,o,s,a){let d={changed:0,deleted:0,created:0};if(!o.live&&!o.deleted)return d;let f=await Qe.read(e,t,n);if(o.live)for await(let i of L(o.live.file)){let c=te(i.SystemModstamp);if(!(c<=a))continue;let l=f.stampOf(i.Id);l===void 0?d.created++:l!==c&&d.changed++}if(o.deleted){let i;for await(let c of L(o.deleted.file)){if(!(te(c.SystemModstamp)<=a))continue;if(f.has(c.Id)){d.deleted++;continue}if(!(te(c.CreatedDate)<s))continue;i??=await en(e,n);let l=St(c.Id);l!==void 0&&!i.has(l)&&d.deleted++}}return d}async function Ot(e){let t=0;for(let n of await Rt(e,{withFileTypes:!0})){let o=ne(e,n.name);n.isDirectory()?t+=await Ot(o):n.isFile()&&(t+=(await ct(o)).size)}return t}async function nn(e,t){let n=await Ot(e.dir)-(await ct(e.checkpointFile)).size,o=a=>Buffer.byteLength(`${JSON.stringify({...t,bytes:a},null,2)}
8
+ `,"utf8"),s=n+o(n);return s=n+o(s),s}function on(e){let t=e.snapshotsFile,n=new Re({getData:()=>Nt(t)?JSON.parse(Dt(t,"utf8")):{},setData:o=>Mt(t,JSON.stringify(o,null,2),{encoding:"utf8",mode:384})});return n.initialize(),n}var sn=z({organizationId:ue().optional()}).loose();async function rn(e,t,n,o,s){let a=on(e),d=0,f={log:n.handler.log,orgManager:n.handler.orgManager,orgRegistry:n.handler.orgRegistry,configStore:a,broker:{postToWebview:c=>{if(c.type!=="operation:progress")return;let l=c.payload;typeof l.percentage=="number"&&typeof l.currentStep=="string"&&s(l.percentage,l.currentStep)}},services:{getSandforgeSetting:(c,l)=>c==="backup.maxRecordsPerObject"?o:l},nextId:()=>`${e.checkpointId}-${++d}`},i=new Te(f);return i.setBackupRecordStore(new De(t)),await i.swept(),{handler:i,config:a}}function an(e,t){return e.slice(0,15)===t.slice(0,15)}async function Bn(e,t){let{org:n,store:o,signal:s}=e,a=e.now??(()=>new Date),d=pe.parse([...t.ignoredFields??[]]),f=t.name===void 0?void 0:E.parse(t.name),i=t.nameWithDate;i!==void 0&&E.parse(rt(i,a().toISOString()));let c=t.customSettings==="all"?[]:t.customSettings??[];for(let y of[...t.objects??[],...t.excluded??[],...c])$(y);let l=t.beforeRun===void 0?void 0:ge.parse(t.beforeRun),u=t.keepDays??Pe;I(a(),u);let h=(y,g,A=0,M=0)=>e.onProgress?.({percentage:Math.round(y),processedObjects:A,totalObjects:M,step:g});h(0,`Checking ${t.orgName}`);let r=Xt(n),m=await Z(ht(n),{act:"take",orgName:t.orgName,registered:t.registered,username:t.username,customSettings:wt(t)},{userId:()=>n.userId()});if(!m.allowed)return{taken:!1,refusal:m.refusal};let w=m.org.id,S=Ee("ck",a()),O=o.lock(w,"take",S);if("busy"in O)return{taken:!1,refusal:lt(t.orgName,O.busy)};let p,b;try{let y=await e.runWriting?.(w);if(y!==void 0)return{taken:!1,refusal:{code:"RUN_WRITING",message:y}};let g=X(n,s),A=await Yt(n,m.org),M=await ee(n,t.orgName);h(2,`Reading the objects of ${t.orgName}`),r.enter("scope");let k=await kt(n,g,t,await ft(n,g,t),m.grants,s);if(k.refusal!==void 0)return{taken:!1,refusal:k.refusal};let{scope:j}=k;r.enter("start");let P=await n.userId(),se=await Zt(n),R=await n.serverTime();h(8,`Counting the records of ${j.objects.length} objects`),r.enter("counts");let T=await mt(n,g,t,j,M,R,s,k.reads);if(T.refusal!==void 0)return{taken:!1,refusal:T.refusal};if(T.objects.length===0)throw new Error(`None of the objects asked for can be kept in a checkpoint of ${t.orgName}: ${T.leftOut.map(C=>`${C.objectApiName}: ${C.reason}`).join(" ")||"there are none."}`);if(s?.aborted)throw new N;p=await o.create(w,S);let B=`snapshot-${S}`;b={version:1,checkpointId:S,name:f??(i!==void 0?E.parse(rt(i,R)):yt(R)),org:{organizationId:w,...t.alias!==void 0?{alias:t.alias}:{},username:t.username,instanceUrl:t.instanceUrl,isSandbox:m.org.sandbox,organizationType:A,tier:m.tier,...t.scratchExpiresAt!==void 0?{scratchExpiresAt:t.scratchExpiresAt}:{}},takenBy:{userId:P,...se!==void 0?{automatedProcessUserId:se}:{},viewAllData:m.grants.kind==="org"||m.grants.viewAllData,modifyAllData:m.grants.kind==="org"||m.grants.modifyAllData,queryAllFiles:m.queryAllFiles},readFrom:R,takenAt:R,scope:{mode:t.mode,leftOut:T.leftOut},objects:[],ignoredFields:d,snapshotId:B,movedWhileTaken:{changed:0,deleted:0,created:0},bytes:0,expiresAt:I(a(),u),status:"taking",takenOn:{host:Pt(),pid:process.pid},...l!==void 0?{beforeRun:l}:{}},await o.write(b),h(12,"Reading the recycle bin as it was at the checkpoint"),r.enter("bin");let At=await Ve(g,T.objects.map(({scoped:C})=>({...Ue(C.objectApiName,R),file:J(p,C.objectApiName)})),s),ie=new Map;for(let C of At){if(!C.read)throw new Error(`The recycle bin of ${C.objectApiName} could not be read whole: ${C.reason}`);ie.set(C.objectApiName,C.rows)}r.enter("snapshot");let{records:jt,files:re}=await cn(p,B,T,t,e,w,g,h);h(88,"Reading the time on the org"),r.enter("stability");let ae=await n.serverTime();h(90,`Checking what changed in ${t.orgName} while it was read`);let{movedWhileTaken:Ct,notChecked:Tt}=await dn(p,B,T,g,R,ae,s),{prints:ce}=T;await o.writeFingerprints(p,ce);let _=T.objects.map(C=>{let U=C.scoped.objectApiName;return gt(C,jt.get(U)??0,ie.get(U)??0,ce[U].digest)});if(s?.aborted)throw new N;let de={...b,takenAt:ae,objects:_,movedWhileTaken:Ct,bytes:0,expiresAt:I(a(),u),status:"ready",...re!==void 0?{files:re}:{}},G={...de,bytes:await nn(p,de)};await o.write(G),h(100,`Checkpoint '${G.name}' taken`,_.length,_.length);let le=r.requests();return{taken:!0,checkpoint:G,notChecked:Tt,...le!==void 0?{requests:le}:{},estimate:T.estimate}}catch(y){throw p!==void 0&&await ln(o,p,b,e),W(y,s)?new N:y}finally{O.lock.release()}}async function cn(e,t,n,o,s,a,d,f){let i=n.objects.filter(r=>r.records>0),c=new Map,l=(s.snapshotFiles??It)(e.dir);if(i.length>0){let r=Math.max($t,n.objectLimit),{handler:m,config:w}=await rn(e,l,s,r,(b,y)=>f(15+b*.65,y)),S=await m.backupForPipeline({operationId:t,orgId:o.orgId,objects:i.map(({scoped:b})=>b.objectApiName),fields:new Map(i.map(({scoped:b,capture:y})=>[b.objectApiName,y.fields])),scanAll:i.filter(({capture:b})=>b.readMode==="scanAllLive").map(({scoped:b})=>b.objectApiName),origin:"checkpoint",failWhenTruncated:!0,onConnection:b=>s.org.countAlso?.(b)},s.signal),O=sn.safeParse(w.get(`backup:${t}`)),p=O.success?O.data.organizationId:void 0;if(p===void 0||!an(p,a))throw new Error(`The snapshot was read from ${p===void 0?"an org that did not say which it is":`another org (${p})`}, not from ${o.orgName}: it is not kept.`);for(let b of S.objects)c.set(b.objectApiName,b.recordCount)}f(82,"Indexing the snapshot",0,n.objects.length);for(let[r,{scoped:m}]of n.objects.entries()){let w=m.objectApiName,S=c.get(w)??0;c.has(w)||(await ve(ne(e.dir,"backups")),await l.writeFile(Ke(e,t,w),""),c.set(w,0));let O=await Je(e,t,w);if(O.rows!==S)throw new $e("damaged",`The snapshot of ${w} holds ${O.rows} records where its read kept ${S}: it is not kept.`);f(82+6*(r+1)/n.objects.length,`Indexed ${w}`,r+1,n.objects.length)}let u=n.objects.find(({scoped:r})=>D(r.objectApiName));if(u===void 0||n.linkable===void 0)return{records:c};f(88,"Reading the links of files to the records read");let h=await Ye({reader:d,folder:e,snapshotId:t,linked:n.objects.map(({scoped:r})=>r.objectApiName).filter(r=>(c.get(r)??0)>0&&pt(r,n.linkable)),documentsInSnapshot:(c.get(u.scoped.objectApiName)??0)>0,...s.signal!==void 0?{signal:s.signal}:{}});return{records:c,files:h}}async function dn(e,t,n,o,s,a,d){let f=ne(e.dir,Ft),i={changed:0,deleted:0,created:0},c=[];try{let l=await He(o,n.objects.map(({capture:r})=>({objectApiName:r.objectApiName,readMode:r.readMode,held:!1})),s,f,d),u=Date.parse(Y(s)),h=Date.parse(a);for(let r of l){if("unread"in r){c.push({objectApiName:r.objectApiName,reason:r.unread});continue}if(!r.moved)continue;let m=await tn(e,t,r.objectApiName,r,u,h);i.changed+=m.changed,i.deleted+=m.deleted,i.created+=m.created}}finally{await at(f,{recursive:!0,force:!0})}return{movedWhileTaken:i,notChecked:c}}async function ln(e,t,n,o){try{n!==void 0&&await e.write({...n,status:"failed"})}catch(s){o.handler.log(`[WARN] checkpoint ${t.checkpointId}: not marked failed: ${v(s)}`)}try{await at(t.dir,{recursive:!0,force:!0})}catch(s){o.handler.log(`[WARN] checkpoint ${t.checkpointId}: what its take wrote was not removed: ${v(s)}`)}}export{vt as a,xn as b,N as c,Wn as d,Bn as e};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{a,b,c,d,e}from"./chunk-TEOLMRDO.mjs";import"./chunk-NTDN2JQZ.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{b as SEED_RUNS_DIR,a as SEED_RUNS_KEPT,e as SeedRunCreations,d as nodeSeedRunCreations,c as seedRunKept};
@@ -0,0 +1,11 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{a as l}from"./chunk-CE6ZDGBB.mjs";import{a as c}from"./chunk-5LFSFYFJ.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-NTOVCTRS.mjs";var p={ApexClass:"source",ApexTrigger:"source",CustomObject:"metadata",CustomField:"metadata",RecordType:"metadata",LightningComponentBundle:"metadata",Flow:"metadata",WorkflowRule:"metadata",ValidationRule:"metadata",Profile:"metadata",PermissionSet:"metadata",Layout:"metadata",CustomLabel:"metadata",CustomMetadata:"metadata",StaticResource:"metadata",EmailTemplate:"metadata",Report:"metadata",Dashboard:"metadata",CustomSetting:void 0,Other:void 0},C=50,R=10;function B(n,t){return{batchSize(e){let r=p[e];if(r==="source")return C;if(r==="metadata")return R},async read(e,r,o){let a=n(e),d=p[r];return d==="source"?A(a,r,o,t):d==="metadata"?S(a,r,o,t):new Map}}}async function A(n,t,e,r){let o=[...new Set(e.map($))],a=await l(n,`SELECT NamespacePrefix, Name, Body FROM ${t} WHERE Name IN (${o.map(k).join(", ")})`,void 0,r);c(n.limitInfo,`compare:content ${t}`);let d=new Set(e),i=new Map;for(let s of a){let u=s.NamespacePrefix?`${s.NamespacePrefix}__${s.Name}`:s.Name;d.has(u)&&i.set(u,s.NamespacePrefix?null:h(s.Body))}return i}async function S(n,t,e,r){let o=await y(n,t,e,r);if(t!=="Layout")return o;let a=new Map;for(let i of e){let s=o.has(i)?void 0:L(i);s&&a.set(s,i)}if(a.size===0)return o;let d=await y(n,t,[...a.keys()],r);for(let[i,s]of d)o.set(a.get(i)??i,s);return o}async function y(n,t,e,r){r?.throwIfAborted();let o=await n.metadata.read(t,[...e]);c(n.limitInfo,`compare:content ${t}`);let a=(Array.isArray(o)?o:[o]).filter(f),d=new Map;return e.forEach((i,s)=>{let u=a.length===e.length?a[s]:void 0,m=a.find(w=>w.fullName===i)??(typeof u?.fullName=="string"&&u.fullName.endsWith(`/${i}`)?u:void 0);m&&d.set(i,I(t,m))}),d}function L(n){let t=n.indexOf("-");if(t<0)return;let e=n.slice(0,t),r=n.slice(t+1),o=/^([A-Za-z][A-Za-z0-9]*)__[A-Za-z0-9_]+__[a-z]+$/.exec(e)?.[1];if(!(!o||r.startsWith(`${o}__`)))return`${e}-${o}__${r}`}function $(n){let t=n.indexOf("__");return t>0?n.slice(t+2):n}function k(n){return`'${n.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}function h(n){return n.replace(/\r\n?/g,`
8
+ `)}function f(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function E(n,t){return typeof n=="string"&&n.startsWith(t)&&/^[a-zA-Z0-9]{15}(?:[a-zA-Z0-9]{3})?$/.test(n)}function x(n,t){let e={...t};if(n==="Dashboard"&&(delete e.runningUser,delete e.owner),n==="Layout"&&f(e.summaryLayout)){let{masterLabel:r,...o}=e.summaryLayout;e.summaryLayout=E(r,"00h")?o:e.summaryLayout}if(n==="Profile"||n==="PermissionSet")for(let[r,o]of Object.entries(e))Array.isArray(o)&&(e[r]=o.filter(M));return e}function M(n){if(!f(n))return!0;let t=Object.values(n).filter(e=>typeof e=="boolean");return t.length===0||t.some(Boolean)}function b(n,t){if(n==="EmailTemplate"&&typeof t.content=="string"&&(t.content=Buffer.from(t.content,"base64").toString("utf8")),n==="StaticResource"&&typeof t.content=="string"){let e=P(Buffer.from(t.content,"base64"));e&&(t.content={archive:e})}if(n==="LightningComponentBundle"&&f(t.lwcResources)){let e=t.lwcResources.lwcResource;for(let r of Array.isArray(e)?e:[e])f(r)&&typeof r.source=="string"&&(r.source=Buffer.from(r.source,"base64").toString("utf8"))}}function P(n){let t=-1;for(let o=n.length-22;o>=Math.max(0,n.length-65557);o-=1)if(n.readUInt32LE(o)===101010256){t=o;break}if(t<0||n.length<4||n.readUInt32LE(0)!==67324752)return;let e=[],r=n.readUInt32LE(t+16);for(let o=0;o<n.readUInt16LE(t+10);o+=1){if(r+46>n.length||n.readUInt32LE(r)!==33639248)return;let a=n.readUInt16LE(r+28);e.push({file:n.subarray(r+46,r+46+a).toString("utf8"),crc32:n.readUInt32LE(r+16).toString(16).padStart(8,"0"),size:n.readUInt32LE(r+24)}),r+=46+a+n.readUInt16LE(r+30)+n.readUInt16LE(r+32)}return e.sort((o,a)=>o.file<a.file?-1:o.file>a.file?1:0)}function _(n){return n.length>1&&n.every(t=>f(t)&&t.sortOrder!==void 0)?[...n].sort((t,e)=>Number(t.sortOrder)-Number(e.sortOrder)):n.length>1&&n.every(t=>f(t)&&typeof t.filePath=="string")?[...n].sort((t,e)=>String(t.filePath).localeCompare(String(e.filePath))):n}function I(n,t){let e=x(n,structuredClone(t));b(n,e);let r=[];return g(r,"",e),r.join(`
9
+ `)}function g(n,t,e){if(e!=null){if(Array.isArray(e)){if(e.length===0){n.push(`${t}: []`);return}_(e).forEach((r,o)=>g(n,`${t}[${o}]`,r));return}if(f(e)){let r=Object.keys(e).filter(o=>e[o]!==null&&e[o]!==void 0).sort();if(r.length===0){n.push(`${t}: {}`);return}for(let o of r)g(n,t?`${t}.${o}`:o,e[o]);return}if(typeof e=="string"){let r=h(e);if(r.includes(`
10
+ `)){n.push(`${t}: |`);for(let o of r.split(`
11
+ `))n.push(` ${o}`)}else n.push(`${t}: ${JSON.stringify(r)}`);return}n.push(`${t}: ${String(e)}`)}}export{I as canonicalMetadata,B as createContentReader,h as normalizeLineEndings};
@@ -0,0 +1,110 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{a as $e}from"./chunk-TW3N6W5Z.mjs";import{a as ne,b as ae}from"./chunk-5P4PHJRL.mjs";import{a as ge,b as we,c as ye,d as be}from"./chunk-RSWDYIHY.mjs";import{K as ce,c as ie}from"./chunk-D3QRXG63.mjs";import{a as U}from"./chunk-SCKUIE3R.mjs";import{a as D}from"./chunk-QROPNEGY.mjs";import{b as _,e as z}from"./chunk-BZ24IAP5.mjs";import{c as W}from"./chunk-AV5SWEHP.mjs";import{a as le,c as pe,d as me,e as fe,f as he}from"./chunk-I7O6C2B5.mjs";import{a as ke}from"./chunk-4GL773D5.mjs";import{f as re,j as se}from"./chunk-SRQDABQ2.mjs";import{za as ee}from"./chunk-YMJVMFPY.mjs";import{x as de}from"./chunk-36U7IQ6Y.mjs";import{l as oe}from"./chunk-Z7X534S4.mjs";import{h as te}from"./chunk-NTDN2JQZ.mjs";import{b as Q}from"./chunk-L776PUMV.mjs";import{p as Y}from"./chunk-CGWXQX75.mjs";import{e as V,g as K}from"./chunk-TZE3Y7IQ.mjs";import{a as J,b as q,d as X,e as Z,g as ue}from"./chunk-MTMH6H2A.mjs";import{Vb as H}from"./chunk-B45CNPUX.mjs";import{readFileSync as xe}from"node:fs";import{basename as Oe,join as Ie}from"node:path";var Le=`sandforge dataops \u2014 mask an org's records, and put them back, without the editor.
8
+
9
+ Usage:
10
+ npx sandforge dataops anonymize \\
11
+ --org <alias> [--object <ApiName>] (--template <id> | --rules <file>) [options]
12
+ npx sandforge dataops anonymize \\
13
+ --org <alias> --restore <snapshot> [--rewrite-all] [--include-changed] [--store <dir>] [--yes]
14
+ Either takes [--accept-automation] [--accept-emails] [--mute-automation].
15
+
16
+ Required:
17
+ anonymize the command
18
+ --org <alias> sf CLI alias of the org
19
+ --template <id> a template that ships (tpl-gdpr-standard, tpl-ccpa-california,
20
+ tpl-hipaa-health, tpl-sandbox-scrub) or one saved in the store
21
+ --rules <file> or a JSON file of rules, saved in the store as a template:
22
+ {"name": "...", "rules": [{"fieldPattern": "Contact.Email",
23
+ "ruleType": "hash"}]} \u2014 a rule as the panel's editor saves it
24
+
25
+ Options:
26
+ --object <ApiName> the object to mask, one per run; without it, every object
27
+ the template masks, as the panel's Apply masks them \u2014
28
+ Account's person accounts among them, in an org that has
29
+ person accounts, when the template masks contacts
30
+ --where <clause> with --object: mask only the records this SOQL condition
31
+ selects, written without WHERE
32
+ --dry-run say what a run would mask \u2014 the fields, the records, the
33
+ first records masked as a run masks them \u2014 and write
34
+ nothing
35
+ --resume mask only what the last run of the same template, object
36
+ and filter left, from where it stopped
37
+ --restore <snapshot> put back the values a snapshot holds, by Id: the id a run
38
+ printed. It reads the org's values first and writes only
39
+ the rows where one of them differs from the snapshot, and
40
+ says how many it found unchanged
41
+ --rewrite-all with --restore: write every row of the snapshot back,
42
+ the ones the org already holds as the snapshot does
43
+ included
44
+ --include-changed with --restore of the snapshot a Sync run kept of what
45
+ it wrote over: put back the records changed or deleted
46
+ since the run too, which a restore of it otherwise
47
+ leaves as they are and counts, as removing the run does
48
+ --max-age-days <n> the retention, as sandforge.backup.maxAgeDays sets it:
49
+ snapshots taken more than <n> days ago are removed as
50
+ the command starts, each named on stderr \u2014 the one a
51
+ Sync run kept of what it wrote over too, which removing
52
+ that run then no longer puts back; 0 keeps them all
53
+ (default: 30)
54
+ --store <dir> where snapshots, saved templates and checkpoints live, a
55
+ folder of your own; the one sandforge backup reads and
56
+ lists (default: ~/.sandforge/backups, under the folder
57
+ SANDFORGE_JOURNAL_DIR names when it is set)
58
+ --max-records <n> most records of the object a snapshot holds, as
59
+ sandforge.backup.maxRecordsPerObject sets it; a run with
60
+ more writes nothing (default: 50000; 100 to 1000000)
61
+ ${ye("written over","--dry-run")} --yes do not ask before writing. Without it, a command with no
62
+ terminal to answer the question \u2014 a CI step \u2014 stops
63
+ there, exit 2, and writes nothing
64
+ --json emit what the panel would receive, every other line on
65
+ stderr; a preview's original values are left out
66
+ --help this text
67
+
68
+ A run takes a snapshot of the records it masks, their masked fields as they are,
69
+ before its first write, and writes nothing unless the snapshot holds every one of
70
+ them. A production org is refused.
71
+
72
+ Before it writes, a run and a --restore say what the org runs as the records are
73
+ written over \u2014 its record-triggered flows, Apex triggers, processes and workflow
74
+ rules on update, and on undelete for what a restore brings back from the recycle
75
+ bin \u2014, the emails that sends against what the org has left today, and whether
76
+ the org delivers them; a dry run says it too, and what a real run would be
77
+ refused for (with --json, the dataops:automation:response it carries).
78
+
79
+ Ctrl-C stops a run as the panel's Cancel does: before its next page, what it
80
+ masked recorded in the audit trail of the store, and --resume masks only what it
81
+ left. It stops a --restore before its next batch, what it put back recorded the
82
+ same way, and the same --restore puts back the rest. Ctrl-C again ends the
83
+ process at once. A SIGTERM \u2014 a CI job cancelled or timed out \u2014 or a SIGHUP
84
+ stops it the same way.
85
+
86
+ Exit codes: 0 the run masked every record it counted, or the restore put back
87
+ every value; 1 it could not start, was refused or failed \u2014 what the org runs as
88
+ it writes, without --accept-automation (AUTOMATION_NOT_ACCEPTED), emails it
89
+ delivers, without --accept-emails (EMAILS_NOT_ACCEPTED), more emails than it
90
+ has left today (EMAILS_EXCEEDED), or a mute refused among the reasons \u2014, or a
91
+ --dry-run saw that a run would be refused; 2 a bad command line,
92
+ or a question with no terminal to answer it (give --yes); 3 the run left
93
+ records unmasked, their personal data still in the org (--resume masks what
94
+ it left), or the restore left values as they are (rows the org refused, a
95
+ snapshot that holds part of the records, or records of a Sync run's snapshot
96
+ changed since the run, held back without --include-changed); 130 Ctrl-C
97
+ stopped the run, 143 a SIGTERM, 129 a SIGHUP.
98
+ `,De=/^[A-Za-z][A-Za-z0-9_]{0,79}$/,Te={words:1,switches:["--dry-run","--resume","--rewrite-all","--include-changed","--yes","--json",...ge],values:["--org","--object","--template","--rules","--where","--restore","--store","--max-records","--max-age-days"]};function h(o){process.stderr.write(`${o}
99
+ `),process.exit(2)}function Pe(o){let e;try{e=JSON.parse(xe(o,"utf8"))}catch(a){h(`Cannot read the rules in ${o}: ${a instanceof Error?a.message:String(a)}`)}let r=Array.isArray(e)?{rules:e}:e,s=typeof r=="object"&&r!==null&&!("name"in r)?{...r,name:`Rules from ${Oe(o)}`}:r,i=ee.safeParse(s);if(!i.success){let a=i.error.issues.map(g=>`${g.path.join(".")||"(file)"}: ${g.message}`).join("; ");h(`The rules in ${o} are not rules the panel saves: ${a}`)}return i.data}function Ee(o){let e=o.slice(2);(e.includes("--help")||e.includes("-h"))&&(process.stdout.write(Le),process.exit(0)),e[0]!=="anonymize"&&h(`The command is anonymize: ${U("dataops")} anonymize --org \u2026 Run with --help.`),J(e,Te);let r=p=>{let m=e.indexOf(p),O=m>=0?e[m+1]:void 0;return m>=0&&(O===void 0||O.startsWith("--"))&&h(`${p} needs a value.`),O},s=p=>e.filter(m=>m===p).length,i=r("--org");i||h("Missing --org. Run with --help."),q.test(i)||h(`Not an sf alias: "${i}"`);let a=r("--restore"),g=e.includes("--dry-run"),S=e.includes("--resume"),k=r("--max-records");k!==void 0&&!/^[1-9]\d*$/.test(k)&&h(`Not a number of records: "${k}"`);let c=e.includes("--rewrite-all");c&&a===void 0&&h("--rewrite-all goes with --restore.");let A=e.includes("--include-changed");A&&a===void 0&&h("--include-changed goes with --restore.");let f=me(r("--max-age-days")),$={org:i,rewriteAll:c,includeChanged:A,...f!==void 0?{maxAgeDays:f}:{},storeDir:r("--store")??le(),...k!==void 0?{maxRecords:Number(k)}:{},yes:e.includes("--yes"),json:e.includes("--json"),accord:we(e)};if(a!==void 0){let p=["--object","--template","--rules","--where","--dry-run","--resume"].filter(m=>e.includes(m));return p.length>0&&h(`--restore puts a snapshot back as it is: drop ${p.join(", ")}.`),{...$,mode:"restore",restoreId:a}}s("--object")>1&&h("Give one --object at most: a run masks one object, or every object its template masks.");let l=r("--object");l!==void 0&&!De.test(l)&&h(`Not an SObject API name: "${l}"`);let w=r("--template"),b=r("--rules");w===void 0==(b===void 0)&&h("Give one of --template or --rules: the rules a run masks with."),g&&S&&h("Give one of --dry-run or --resume.");let d=r("--where")?.trim();return d!==void 0&&(d===""||!V(d))&&h(`Not a filter --where can take: "${d}". ${K}`),d!==void 0&&l===void 0&&h("--where filters the records of one object: give it with --object."),{...$,mode:g?"dry-run":S?"resume":"run",...l!==void 0?{object:l}:{},...w!==void 0?{templateId:w}:{},...b!==void 0?{rules:Pe(b)}:{},...d!==void 0?{where:d}:{}}}function ve(o,e){let r=`${e.toLowerCase()}.`;return o.rules.filter(s=>s.fieldPattern.toLowerCase().startsWith(r)||s.fieldPattern==="*")}function Fe(o,e){return ve(o,e).length>0?!0:e.toLowerCase()===Y.toLowerCase()&&re(o.rules).length>0}function Me(o,e){let r=s=>JSON.stringify(s.map(i=>[i.fieldPattern.toLowerCase(),i.ruleType,i.config??null]).sort((i,a)=>String(i[0]).localeCompare(String(a[0]))));return r(o)===r(e)}function _e(o){if(o==null||o==="")return"(empty)";let e=typeof o=="string"?o:JSON.stringify(o);return JSON.stringify(e.length>40?`${e.slice(0,39)}\u2026`:e)}function ze(o,e){let r=[];typeof o.message=="string"&&r.push(o.message);for(let a of o.objects??[])r.push(` ${a.objectApiName.padEnd(28)} counted ${a.total} masked ${a.processed} refused ${a.failed} still original ${a.notMasked}`);let s=o.errors??[];s[0]&&r.push(` e.g. ${s[0].objectApiName}: ${s[0].message}`);let i=o.snapshot;return i&&r.push(`snapshot ${i.operationId}: ${i.totalRecords} record(s) as they were before the run. To put their values back:`,` ${e(i.operationId)}`),r}function We(o,e){return`${o}.${e}: the org has no such field, or field-level security hides it from this user \u2014 a run is refused and masks nothing (give the user read and edit access to it, or take it out of the template)`}function je(o,e){return e===void 0?`${o}: this user may not edit its records \u2014 a run is refused (CRUD_FLS_DENIED) and masks nothing (give the user edit access to the object)`:`${o}.${e}: this user may read it and not edit it \u2014 a run is refused (CRUD_FLS_DENIED) and masks nothing (give the user edit access to it, or take it out of the template)`}function Ue(o,e={}){let r=o.fieldsNotFound??[],s=o.objects??[],i=e.objects??[];return r.length>0||s.some(a=>a.notCovered===!0||a.error!==void 0||a.writeDenied!==void 0)||i.some(a=>a.count===null)}function Ge(o,e,r){let s=["dry run \u2014 nothing is written"],i=e.objects??[],a=r.objects??[],g=r.fieldsNotFound??[];for(let c of i){let A=c.count===null?"an unknown number of":String(c.count);s.push(` ${c.objectApiName}: ${A} record(s) to mask`),c.count===null&&s.push(" not counted by the org: a run stops at its count and masks nothing");let f=a.find(d=>d.objectApiName===c.objectApiName);if(f?.error){s.push(` not read: ${f.error}`);continue}let $=new Map([...ve(o,c.objectApiName).map(d=>[d.fieldPattern.split(".").pop()?.toLowerCase()??"",d.ruleType]),...Object.entries(f?.methods??{}).map(([d,p])=>[d.toLowerCase(),p])]),l=f?.fields??[];s.push(` fields: ${l.map(d=>`${d} (${$.get(d.toLowerCase())??"?"})`).join(", ")||"(none)"}`);for(let d of g.filter(p=>p.objectApiName===c.objectApiName))s.push(` ${We(d.objectApiName,d.fieldApiName)}`);f?.notCovered&&s.push(" no field of it can be masked: a run is refused and masks nothing");let w=f?.writeDenied?.deniedFields;w?.length===0&&s.push(` ${je(c.objectApiName)}`);for(let d of w??[])s.push(` ${je(c.objectApiName,d)}`);let b=f?.rows??[];if(b.length>0){s.push(" the first records, masked as a run masks them (a run draws its own key, so its made-up names and digests differ from these):");for(let d of b)s.push(` ${d.id}: ${l.map(p=>`${p} ${_e(d.after[p])}`).join(", ")}`)}}let S=i.reduce((c,A)=>c+(A.count??0),0);S>0&&s.push(` a run takes a snapshot of these ${S} record(s) first, and writes nothing without it`);let k=e.checkpoint;return k&&s.push(` a run of this template, object and filter stopped short on ${k.savedAt}: --resume masks only what it left`),s}function Be(o){return`interrupted: the restore stopped before it was through; what it restored is in the audit trail, and the same line puts back the rest: ${o}`}function He(){return"interrupted: the masking stopped before it was through; what it masked is in the audit trail, the snapshot puts their values back (--restore), and the same line with --resume masks only what it left"}function Je(o){return o.map(e=>{if(e.type!=="dataops:anonymize:preview:response")return e;let r=e.payload?.objects??[];return{...e,payload:{...e.payload,objects:r.map(s=>({...s,rows:(s.rows??[]).map(({id:i,after:a})=>({id:i,after:a}))}))}}})}async function qe(o=process.argv){let e=Ee(o),r=t=>{process[e.json?"stderr":"stdout"].write(`${t}
100
+ `)},s=t=>{process.stderr.write(`${t}
101
+ `),process.exitCode=1},i=pe(e.storeDir);if(i!==void 0){s(i);return}let a=await Q(e.org),g=await new ke().validateConnection(a.accessToken,a.instanceUrl),S={alias:e.org,orgType:H({isSandbox:g.isSandbox,edition:g.orgType}),metadata:{apiVersion:"66.0",edition:g.orgType}};r(`sandforge dataops ${e.org} (${g.isSandbox?"sandbox":g.orgType||"production"}) store: ${e.storeDir}`);let k=de(Ie(e.storeDir,"snapshots.json")),c=[],A=new Map,f=new $e,$=new se({log:t=>{/^\[(WARN|INFO)\]/.test(t)&&r(` ${t}`)},broker:{postToWebview:t=>{if(c.push(t),t.type!=="operation:progress")return;let n=String(t.payload?.operationId??""),u=Number(t.payload?.percentage??0);(u-(A.get(n)??-10)>=10||u===100)&&(A.set(n,u),r(` ${u}% ${String(t.payload?.currentStep??"")}`))}},orgManager:{getOrg:()=>S},orgRegistry:{getCredentials:async()=>({accessToken:a.accessToken,instanceUrl:a.instanceUrl})},configStore:k,services:{getSandforgeSetting:fe(e)},infraServices:{backgroundRegistry:f,productionGuard:new oe({requestConfirmation:(t,n)=>(r(`refused: ${e.org} is taken for a ${n} org, and this command writes to none (${t})`),Promise.resolve(!1))}),confirmRestoreIntoReplacedOrg:({alias:t,backedUpFrom:n,now:u})=>e.yes?Promise.resolve(!1):D(`${t} answered as org ${n} when this snapshot was taken and answers as org ${u} now. Write its saved values into the org it is now?`)},nextId:()=>`cli-${Date.now()}-${Math.random().toString(36).slice(2,8)}`});$.setExpiryListener(t=>process.stderr.write(`${he(t)}
102
+ `)),$.setBackupRecordStore(new ae(ne(e.storeDir))),await $.swept(),$.setSyncRuns(te(ce())),$.setMuteOffered(ie("--mute-automation"));let l=async(t,n)=>{let u=`cli-${t.replaceAll(":","-")}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;return await $.handle({id:u,type:t,timestamp:Date.now(),payload:n}),c.find(v=>v.correlationId===u&&(v.type===`${t}:response`||v.type==="dataops:error"))??{type:"dataops:error",payload:{message:`${t} was not answered.`}}},w=t=>t.type==="dataops:error",b=t=>String(t.payload?.message??t.type),d=t=>`${U("dataops")} anonymize --org ${e.org} --restore ${t} --store ${e.storeDir}`,p=async(t,n)=>{let u=await l("dataops:automation",{orgId:e.org,act:t,objects:n,...e.accord});if(w(u)){s(b(u));return}let C=u.payload;for(let v of C.lines)r(v);return C},m=t=>{e.json&&process.stdout.write(`${JSON.stringify({tool:"sandforge-dataops",command:t,org:e.org,posted:Je(c)},null,2)}
103
+ `)};if(e.mode==="restore"){let t=e.restoreId,n=k.get(`backup:${t}`);if(!n){s(`No snapshot "${t}" in ${e.storeDir}.`);return}let u=(n.objects??[]).map(R=>R.objectApiName).join(", "),C=await p("restore",(n.objects??[]).map(R=>({objectApiName:R.objectApiName,records:R.recordCount??0})));if(!C){m("restore");return}if(C.refusals.length>0){m("restore");for(let R of C.refusals)s(W(R));return}if(!e.yes&&!await D(`Put back into ${e.org} the values snapshot ${t} holds? ${n.totalRecords??"?"} record(s) of ${u} will have those fields written over.`)){r("Nothing written.");return}r(`restoring ${t} into ${e.org}${e.rewriteAll?", every row written back":""}\u2026`);let v,Se=z(R=>{v=R,process.stderr.write(`
104
+ interrupted: the restore stops before its next batch, and says what it restored (Ctrl-C again ends it at once)
105
+ `);for(let Ce of f.getRunning())f.abort(Ce.operationId)}),x;try{x=await l("dataops:rollback",{orgId:e.org,operationId:t,...e.rewriteAll?{rewriteAll:!0}:{},...e.includeChanged?{includeChanged:!0}:{},...e.accord})}finally{Se()}if(m("restore"),w(x)){s(b(x));return}if(r(String(x.payload?.message??"")),v){process.stderr.write(`${Be(d(t))}
106
+ `),process.exitCode=_(v);return}Z(X(x.payload??{}));return}let T=(await l("dataops:anonymization-templates",{})).payload?.templates??[],y;if(e.rules){let t=e.rules,n=T.find(u=>u.saved===!0&&u.name.trim().toLowerCase()===t.name.toLowerCase());if(n&&Me(n.rules,t.rules))y=n;else{n&&await l("dataops:anonymization-template:delete",{templateId:n.id});let u=await l("dataops:anonymization-template:save",{name:t.name,rules:t.rules});if(w(u)){s(b(u));return}y=u.payload?.template,r(`rules saved in the store as template "${y.name}" (${y.id})`)}}else if(y=T.find(t=>t.id===e.templateId),!y){s(`No template "${e.templateId??""}". Templates: `+T.map(t=>`${t.id}${t.saved?` (saved: ${t.name})`:""}`).join(", "));return}let j=e.object;if(j!==void 0&&!Fe(y,j)){s(`Template "${y.name}" has no rule for ${j}: a run would mask nothing.`);return}let P={orgId:e.org,templateId:y.id,...j!==void 0?{objects:[j]}:{},...e.where!==void 0?{where:e.where}:{}};r(`template: ${y.name} (${y.id}) `+(j!==void 0?`object: ${j}`:"objects: every object the template masks")+(e.where!==void 0?` where: ${e.where}`:""));let N=await l("dataops:anonymize:coverage",P);if(w(N)){s(b(N));return}let I=N.payload?.objects??[],G=I.reduce((t,n)=>t+(n.count??0),0),B=I.map(t=>({objectApiName:t.objectApiName,records:t.count??0}));if(e.mode==="dry-run"){let t=await l("dataops:anonymize:preview",P);if(w(t)){m("dry-run"),s(b(t));return}for(let u of Ge(y,N.payload??{},t.payload??{}))r(u);let n=await p("masking",B);if(m("dry-run"),!n)return;for(let u of be(n))r(u);(n.refusals.length>0||Ue(t.payload??{},N.payload??{}))&&(process.exitCode=1);return}let E=N.payload?.checkpoint;if(e.mode==="resume"&&!E){s(`There is nothing to resume: no run of this template, object and filter stopped short in ${e.storeDir}.`);return}if(e.mode==="run"&&G===0){let t=I.filter(n=>n.count===null).map(n=>n.objectApiName);if(t.length>0){s(`${t.join(", ")}: the org did not count the records a run would mask, so nothing was masked (its reason is in the warning above).`);return}r(j!==void 0?"Nothing to mask: no record of the object is under the filter.":"Nothing to mask: no object the template masks holds a record."),m("run");return}let F=await p("masking",B);if(!F){m(e.mode);return}if(F.refusals.length>0){m(e.mode);for(let t of F.refusals)s(W(t));return}if(!e.yes){let t=j??I.map(u=>u.objectApiName).join(", "),n=e.mode==="resume"?`Resume the masking of ${t} in ${e.org} that stopped on ${E.savedAt}? What it left is written over; the snapshot the first run took holds their values.`:`Mask ${G} record(s) of ${t} in ${e.org} with ${y.name}? A snapshot of their values is taken first.`;if(!await D(n)){r("Nothing written.");return}}r(e.mode==="resume"?"resuming\u2026":"masking\u2026");let M,Re=z(t=>{M=t,process.stderr.write(`
107
+ interrupted: the masking stops before its next page, and says what it masked (Ctrl-C again ends it at once)
108
+ `);for(let n of f.getRunning())f.abort(n.operationId)}),L;try{L=await l("dataops:anonymize",{...P,...e.mode==="resume"?{resumeFrom:E.id}:{snapshot:!0},...e.accord})}finally{Re()}m(e.mode);for(let t of ze(L.payload??{},d))r(t);if(M){process.stderr.write(`${He()}
109
+ `),process.exitCode=_(M);return}if(w(L)){process.exitCode=1;return}Number(L.payload?.recordsNotMasked??0)>0&&(r("A resume masks only what this run left: the same line with --resume, in place of the snapshot it does not take again."),process.exitCode=3)}/sandforge-dataops\.[cm]?[jt]s$/.test(process.argv[1]??"")&&(ue(),qe().then(()=>process.exit()).catch(o=>{process.stderr.write(`${o instanceof Error?o.message:String(o)}
110
+ `),process.exit(1)}));export{Ee as a,Fe as b,ze as c,We as d,je as e,Ue as f,Ge as g,Be as h,He as i,qe as j};
@@ -0,0 +1,8 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{mkdirSync as s,statSync as i}from"node:fs";import{homedir as d}from"node:os";import{join as o,resolve as u}from"node:path";var a=448;function h(e=process.env){return c("backups",e)}function c(e,n=process.env){let r=n.SANDFORGE_JOURNAL_DIR,t=r!==void 0&&r.trim()!==""?u(r):o(d(),".sandforge");return o(t,e)}var f={mkdir:(e,n)=>{s(e,n)},stat:e=>i(e),...typeof process.getuid=="function"?{uid:()=>process.getuid?.()??-1}:{}};function y(e,n=f){try{n.mkdir(e,{recursive:!0,mode:a});let r=n.stat(e);if(!r.isDirectory())return`The store ${e} is not a folder.`;let t=n.uid?.();return t!==void 0&&r.uid!==t?`The store ${e} belongs to another user, who can read its snapshots and change them: name a folder of your own with --store.`:void 0}catch(r){return`The store ${e} could not be made: ${r instanceof Error?r.message:String(r)}`}}function k(e){if(e!==void 0)return/^\d{1,5}$/.test(e)||(process.stderr.write(`Not a number of days: "${e}"
8
+ `),process.exit(2)),Number(e)}function b(e){return(n,r)=>n==="backup.maxRecordsPerObject"&&e.maxRecords!==void 0?e.maxRecords:n==="backup.maxAgeDays"&&e.maxAgeDays!==void 0?e.maxAgeDays:r}function l(e){let n=`removed snapshot ${e.operationId}${e.takenAt!==void 0?`, taken ${e.takenAt}`:""}: past the retention of ${e.days} day(s) (--max-age-days, 0 keeps them all)`;return e.syncRunId!==void 0?`${n}. It held what the Sync run ${e.syncRunId||"(unknown)"} wrote over: removing that run with sandforge sync --remove no longer puts those values back`:n}export{h as a,c as b,y as c,k as d,b as e,l as f};
@@ -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{b as S,d as z}from"./chunk-OTWRDD6L.mjs";import{h as I}from"./chunk-TZE3Y7IQ.mjs";import{b as h}from"./chunk-CA5NAXSU.mjs";import{vb as R}from"./chunk-B45CNPUX.mjs";import{b as f,e as b,f as y,i as A,k,l as m,o as K}from"./chunk-7EANH5PY.mjs";var w="Knowledge__kav",j="CaseArticle",T="Case",P="Summary",B=255,D=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,L=m({name:f(),type:f(),length:b().optional(),extraTypeInfo:f().nullish(),htmlFormatted:y().optional(),createable:y().optional()}).loose(),F=m({fields:k(A())}).loose();function M(e){if(!(e.type!=="textarea"||e.createable!==!0))return e.name===P?"summary":e.extraTypeInfo==="richtextarea"||e.htmlFormatted===!0?"richText":(e.length??0)>B?"longText":void 0}var O={richText:0,longText:1,summary:2};function G(e){let r=F.safeParse(e);if(!r.success)return[];let o=[];for(let t of r.data.fields){let n=L.safeParse(t);if(!n.success)continue;let d=M(n.data);d===void 0||typeof n.data.length!="number"||o.push({name:n.data.name,length:n.data.length,kind:d})}return o.sort((t,n)=>O[t.kind]-O[n.kind]||n.length-t.length||t.name.localeCompare(n.name))}function U(e){return{articleBodyField:e.name,articleBodyLength:e.length,...e.kind==="richText"?{articleBodyHtml:!0}:{}}}var x=m({success:y(),errors:k(K([m({statusCode:f().optional(),message:f().optional()}).loose(),f()])).optional()}).loose();function $(e){let r=x.safeParse(e),o=r.success?r.data.errors?.[0]:void 0;return o===void 0?"The org gave no reason.":typeof o=="string"?o:[o.statusCode,o.message].filter(Boolean).join(": ")||"The org gave no reason."}function N(e){let r=x.safeParse(e);return r.success&&r.data.success}function C(e){return e.slice(0,15)}function X(e){return async({ids:r,results:o})=>{let t=r.get(w)??new Map;if(t.size===0)return{skipped:o.find(u=>u.objectApiName===w)?.errors[0]??`The run wrote no ${w} article, so none was published or linked.`};let n={};return e.plan.publish&&(n.publish=await _(e,t)),e.plan.links.length>0&&(n.links=await v(e,t,r.get(T)??new Map)),n}}async function _(e,r){let o={asked:r.size,done:0,notDone:[]};for(let[t,n]of r){if(e.signal?.aborted){o.notDone.push({key:t,reason:"Left a draft: the run was stopped before it was published."});continue}if(!D.test(n)){o.notDone.push({key:t,reason:`Left a draft: ${n} is not a record id.`});continue}try{await e.org.request({method:"PATCH",url:`/knowledgeManagement/articleVersions/masterVersions/${n}`,body:JSON.stringify({publishStatus:"Online"}),headers:{"Content-Type":"application/json"}}),o.done++}catch(d){o.notDone.push({key:t,reason:`Left a draft: ${h(d)}`})}finally{e.journal?.wroteAgain(w,[n])}}return o}async function v(e,r,o){let t={asked:e.plan.links.length,done:0,notDone:[]},n,d;try{n=await q(e.org,[...r.values()])}catch(s){n=new Map,d=h(s)}let u=[],c=(s,a)=>{t.notDone.push({key:s,reason:`Not linked: ${a}.`})};for(let{caseKey:s,articleKey:a}of e.plan.links){let l=o.get(s),g=r.get(a);if(l===void 0){c(s,"its case was not written");continue}if(g===void 0){c(s,`its article ${a} was not written`);continue}let i=n.get(C(g));if(i===void 0){c(s,`the article of ${a} could not be read back`+(d?` (${d})`:": the org no longer holds its version"));continue}u.push({caseKey:s,caseId:l,articleId:i,versionId:g})}for(let s=0;s<u.length;s+=S){let a=u.slice(s,s+S);if(e.signal?.aborted){for(let{caseKey:i}of a)t.notDone.push({key:i,reason:"Not linked: the run was stopped before it."});continue}let l;try{l=await e.org.sobject(j).create(a.map(({caseId:i,articleId:p})=>({CaseId:i,KnowledgeArticleId:p})),{headers:R()})}catch(i){let p=`Not linked: ${h(i)}`;for(let{caseKey:E}of a)t.notDone.push({key:E,reason:p});l=[]}finally{e.journal?.wroteAgain(T,a.map(({caseId:i})=>i)),e.journal?.wroteAgain(w,[...new Set(a.map(({versionId:i})=>i))])}let g=Array.isArray(l)?l:[l];g.length!==0&&a.forEach(({caseKey:i},p)=>{N(g[p])?t.done++:t.notDone.push({key:i,reason:`Not linked: ${$(g[p])}`})})}return t}async function q(e,r){let o=I(w),t=new Map;for(let n of z(r)){let d=await e.query(`SELECT Id, KnowledgeArticleId FROM ${o} WHERE Id IN (${n})`);for(let u of d.records){let c=u;typeof c?.Id=="string"&&typeof c.KnowledgeArticleId=="string"&&t.set(C(c.Id),c.KnowledgeArticleId)}}return t}export{w as a,G as b,U as c,X as d};