sandforge 0.0.0-stage → 1.80.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) 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-2BA2XKAY.mjs +7 -0
  21. package/lib/chunk-2CNCDM56.mjs +7 -0
  22. package/lib/chunk-2GTBABKU.mjs +7 -0
  23. package/lib/chunk-2NBYT7GR.mjs +7 -0
  24. package/lib/chunk-2UZPIMUC.mjs +7 -0
  25. package/lib/chunk-2YIV2OB2.mjs +7 -0
  26. package/lib/chunk-3F6Q5E7I.mjs +14 -0
  27. package/lib/chunk-3RZQZHEB.mjs +7 -0
  28. package/lib/chunk-3TJON4F3.mjs +7 -0
  29. package/lib/chunk-4HW535YJ.mjs +7 -0
  30. package/lib/chunk-4TLYUZD5.mjs +7 -0
  31. package/lib/chunk-4VS2V6WU.mjs +25 -0
  32. package/lib/chunk-5K5VLULK.mjs +7 -0
  33. package/lib/chunk-5LFSFYFJ.mjs +7 -0
  34. package/lib/chunk-5P4PHJRL.mjs +9 -0
  35. package/lib/chunk-5TC3QB4U.mjs +10 -0
  36. package/lib/chunk-66NMFCWX.mjs +7 -0
  37. package/lib/chunk-6XYKJSGX.mjs +7 -0
  38. package/lib/chunk-74Q6DORA.mjs +7 -0
  39. package/lib/chunk-7ABODJ4G.mjs +7 -0
  40. package/lib/chunk-7EANH5PY.mjs +68 -0
  41. package/lib/chunk-7EGQP6S4.mjs +7 -0
  42. package/lib/chunk-7F54PZUS.mjs +7 -0
  43. package/lib/chunk-7FFGJWHN.mjs +7 -0
  44. package/lib/chunk-7YDNUBO5.mjs +7 -0
  45. package/lib/chunk-A527W53V.mjs +7 -0
  46. package/lib/chunk-ADOAS63R.mjs +7 -0
  47. package/lib/chunk-AEKONPF4.mjs +7 -0
  48. package/lib/chunk-AV5SWEHP.mjs +9 -0
  49. package/lib/chunk-B5QQJ4SI.mjs +7 -0
  50. package/lib/chunk-BGUEWRK2.mjs +7 -0
  51. package/lib/chunk-BKDV4ENO.mjs +7 -0
  52. package/lib/chunk-BOGNK4LV.mjs +7 -0
  53. package/lib/chunk-BTWDMNN3.mjs +7 -0
  54. package/lib/chunk-BV6VTP3J.mjs +7 -0
  55. package/lib/chunk-BXU6WFMH.mjs +7 -0
  56. package/lib/chunk-BY2HJFFG.mjs +7 -0
  57. package/lib/chunk-BZ24IAP5.mjs +7 -0
  58. package/lib/chunk-CA5NAXSU.mjs +7 -0
  59. package/lib/chunk-CE6ZDGBB.mjs +7 -0
  60. package/lib/chunk-CEX3NEZL.mjs +7 -0
  61. package/lib/chunk-CHCHAE4B.mjs +7 -0
  62. package/lib/chunk-CHYDMRSV.mjs +7 -0
  63. package/lib/chunk-CION3VMZ.mjs +7 -0
  64. package/lib/chunk-COFG7Q6R.mjs +7 -0
  65. package/lib/chunk-CSBS5U5I.mjs +7 -0
  66. package/lib/chunk-CU2INBND.mjs +7 -0
  67. package/lib/chunk-DB7RBE5D.mjs +7 -0
  68. package/lib/chunk-DBB3EMIN.mjs +7 -0
  69. package/lib/chunk-DBFJB2B6.mjs +7 -0
  70. package/lib/chunk-DYFALGRT.mjs +7 -0
  71. package/lib/chunk-E5AHXLS6.mjs +7 -0
  72. package/lib/chunk-E5ZB3LU5.mjs +7 -0
  73. package/lib/chunk-EADHKH3A.mjs +7 -0
  74. package/lib/chunk-EFR2Y7E4.mjs +7 -0
  75. package/lib/chunk-EHQ3FX6X.mjs +7 -0
  76. package/lib/chunk-ELFXJHU7.mjs +7 -0
  77. package/lib/chunk-EMNC6YI4.mjs +7 -0
  78. package/lib/chunk-EQNW3UC2.mjs +7 -0
  79. package/lib/chunk-F2424IKX.mjs +7 -0
  80. package/lib/chunk-F43REJDZ.mjs +10 -0
  81. package/lib/chunk-F6GUDTOB.mjs +7 -0
  82. package/lib/chunk-FGRG7ANU.mjs +7 -0
  83. package/lib/chunk-FKG7Q3WH.mjs +7 -0
  84. package/lib/chunk-FPKYYFM7.mjs +7 -0
  85. package/lib/chunk-FQGHL7GR.mjs +259 -0
  86. package/lib/chunk-FXXLX4O6.mjs +7 -0
  87. package/lib/chunk-G35N4P7D.mjs +7 -0
  88. package/lib/chunk-GCOB7K5N.mjs +7 -0
  89. package/lib/chunk-GGD7ON3M.mjs +7 -0
  90. package/lib/chunk-GMY5427L.mjs +7 -0
  91. package/lib/chunk-GSG7WZHM.mjs +7 -0
  92. package/lib/chunk-GSKCGQIP.mjs +7 -0
  93. package/lib/chunk-HEKAZJRH.mjs +7 -0
  94. package/lib/chunk-HF6LAK3G.mjs +7 -0
  95. package/lib/chunk-HLWMJF6Y.mjs +7 -0
  96. package/lib/chunk-HOJYWTP7.mjs +20 -0
  97. package/lib/chunk-HS4YRX4J.mjs +7 -0
  98. package/lib/chunk-HXS7ORUF.mjs +11 -0
  99. package/lib/chunk-I7O6C2B5.mjs +8 -0
  100. package/lib/chunk-IC2C2GOF.mjs +8 -0
  101. package/lib/chunk-IFETCRWE.mjs +10 -0
  102. package/lib/chunk-IG2MTQRP.mjs +8 -0
  103. package/lib/chunk-IGYH7GMA.mjs +7 -0
  104. package/lib/chunk-INIQ23K6.mjs +7 -0
  105. package/lib/chunk-INIT2UKJ.mjs +7 -0
  106. package/lib/chunk-IOIWJ3DJ.mjs +7 -0
  107. package/lib/chunk-IQXHJEYB.mjs +7 -0
  108. package/lib/chunk-IWDREM66.mjs +7 -0
  109. package/lib/chunk-IZQZ6ZUF.mjs +7 -0
  110. package/lib/chunk-J525F5KI.mjs +7 -0
  111. package/lib/chunk-JEERQRLW.mjs +7 -0
  112. package/lib/chunk-JPUR2CFX.mjs +10 -0
  113. package/lib/chunk-JWTSEDIQ.mjs +7 -0
  114. package/lib/chunk-K2FBZIXY.mjs +7 -0
  115. package/lib/chunk-K327QKMD.mjs +7 -0
  116. package/lib/chunk-KBJ5VERV.mjs +7 -0
  117. package/lib/chunk-KDGMAGQR.mjs +7 -0
  118. package/lib/chunk-KRCA6IPH.mjs +8 -0
  119. package/lib/chunk-KYEDBS54.mjs +7 -0
  120. package/lib/chunk-L5FGY6YA.mjs +7 -0
  121. package/lib/chunk-L77FJZEP.mjs +10 -0
  122. package/lib/chunk-LKQ5RKIV.mjs +9 -0
  123. package/lib/chunk-LPBMBW3O.mjs +13 -0
  124. package/lib/chunk-LWW4U276.mjs +7 -0
  125. package/lib/chunk-M3ROUWDX.mjs +7 -0
  126. package/lib/chunk-M6P5ZZLE.mjs +7 -0
  127. package/lib/chunk-MFG4MUIO.mjs +9 -0
  128. package/lib/chunk-MHMH6MTP.mjs +7 -0
  129. package/lib/chunk-MILU7WFN.mjs +7 -0
  130. package/lib/chunk-MJU2PGZQ.mjs +15 -0
  131. package/lib/chunk-MJVTDA5Q.mjs +7 -0
  132. package/lib/chunk-MS4FJDFD.mjs +101 -0
  133. package/lib/chunk-MTMH6H2A.mjs +8 -0
  134. package/lib/chunk-MYW5QNGI.mjs +7 -0
  135. package/lib/chunk-N652NMZ4.mjs +441 -0
  136. package/lib/chunk-NTFIRZP6.mjs +7 -0
  137. package/lib/chunk-NTOVCTRS.mjs +7 -0
  138. package/lib/chunk-NZC67CGR.mjs +9 -0
  139. package/lib/chunk-O2HDYYUV.mjs +8 -0
  140. package/lib/chunk-OAZRPP4I.mjs +7 -0
  141. package/lib/chunk-OHWNPXWW.mjs +7 -0
  142. package/lib/chunk-OLSGVAIL.mjs +341 -0
  143. package/lib/chunk-OO6CLPEH.mjs +7 -0
  144. package/lib/chunk-OPXCV2KL.mjs +7 -0
  145. package/lib/chunk-P33PSCXK.mjs +7 -0
  146. package/lib/chunk-PJ5I73CK.mjs +7 -0
  147. package/lib/chunk-PTTHSSQO.mjs +7 -0
  148. package/lib/chunk-PZPJKATS.mjs +19 -0
  149. package/lib/chunk-Q3DM32KF.mjs +11 -0
  150. package/lib/chunk-QR3WELJQ.mjs +7 -0
  151. package/lib/chunk-QROPNEGY.mjs +14 -0
  152. package/lib/chunk-QSRAEUGZ.mjs +7 -0
  153. package/lib/chunk-QWT2C74M.mjs +7 -0
  154. package/lib/chunk-R3X3LV64.mjs +14 -0
  155. package/lib/chunk-RMBPOTD7.mjs +7 -0
  156. package/lib/chunk-RPI7LRTW.mjs +7 -0
  157. package/lib/chunk-RSWDYIHY.mjs +37 -0
  158. package/lib/chunk-SAR5622P.mjs +7 -0
  159. package/lib/chunk-SCKUIE3R.mjs +7 -0
  160. package/lib/chunk-SE4QEZUG.mjs +7 -0
  161. package/lib/chunk-SIHORWVK.mjs +7 -0
  162. package/lib/chunk-SOGQW4IG.mjs +7 -0
  163. package/lib/chunk-SOU4FRYN.mjs +7 -0
  164. package/lib/chunk-SRPWW4A2.mjs +10 -0
  165. package/lib/chunk-SU65Z2BA.mjs +7 -0
  166. package/lib/chunk-T62WNR54.mjs +7 -0
  167. package/lib/chunk-T63U4OZJ.mjs +7 -0
  168. package/lib/chunk-TLH7AD35.mjs +7 -0
  169. package/lib/chunk-TSLJUSLW.mjs +13 -0
  170. package/lib/chunk-TTFDUKUS.mjs +47 -0
  171. package/lib/chunk-TTKXMDBN.mjs +10 -0
  172. package/lib/chunk-TUACWKIH.mjs +7 -0
  173. package/lib/chunk-TW3N6W5Z.mjs +7 -0
  174. package/lib/chunk-TYYOBZMU.mjs +10 -0
  175. package/lib/chunk-TZE3Y7IQ.mjs +7 -0
  176. package/lib/chunk-UCD54V2M.mjs +7 -0
  177. package/lib/chunk-UNDIBZWG.mjs +7 -0
  178. package/lib/chunk-UNJA4J37.mjs +11 -0
  179. package/lib/chunk-VE6XKGGD.mjs +7 -0
  180. package/lib/chunk-VGW4MXXZ.mjs +7 -0
  181. package/lib/chunk-VS7ZXUII.mjs +824 -0
  182. package/lib/chunk-VXQLDM4R.mjs +7 -0
  183. package/lib/chunk-VYXMVJL5.mjs +7 -0
  184. package/lib/chunk-W622GUAW.mjs +8 -0
  185. package/lib/chunk-W7U5E5ZL.mjs +9 -0
  186. package/lib/chunk-WA7EYLAQ.mjs +7 -0
  187. package/lib/chunk-WIO4XO4F.mjs +7 -0
  188. package/lib/chunk-WR2GIKWE.mjs +7 -0
  189. package/lib/chunk-WR4Q363I.mjs +11 -0
  190. package/lib/chunk-WU3GLFZO.mjs +7 -0
  191. package/lib/chunk-WXAQ7FK3.mjs +115 -0
  192. package/lib/chunk-X5JYBPXP.mjs +7 -0
  193. package/lib/chunk-XAMBCQPU.mjs +7 -0
  194. package/lib/chunk-XCA5AONB.mjs +7 -0
  195. package/lib/chunk-XLXIPIEW.mjs +9 -0
  196. package/lib/chunk-XUWL6ZPC.mjs +7 -0
  197. package/lib/chunk-YAZO75G2.mjs +8 -0
  198. package/lib/chunk-YKKRIEH4.mjs +7 -0
  199. package/lib/chunk-YRQGKDHM.mjs +7 -0
  200. package/lib/chunk-YS4G22C2.mjs +7 -0
  201. package/lib/chunk-YYZL7UGV.mjs +7 -0
  202. package/lib/chunk-ZHJP7L3K.mjs +7 -0
  203. package/lib/chunk-ZM6OJGIG.mjs +7 -0
  204. package/lib/chunk-ZUTYVST5.mjs +7 -0
  205. package/lib/chunk-ZVAED4QV.mjs +7 -0
  206. package/lib/sandforge-autopilot.mjs +162 -0
  207. package/lib/sandforge-backup.mjs +103 -0
  208. package/lib/sandforge-checkpoint.mjs +354 -0
  209. package/lib/sandforge-cleanup.mjs +60 -0
  210. package/lib/sandforge-clone.mjs +7 -0
  211. package/lib/sandforge-compare.mjs +55 -0
  212. package/lib/sandforge-dataops.mjs +7 -0
  213. package/lib/sandforge-empty.mjs +140 -0
  214. package/lib/sandforge-env.mjs +355 -0
  215. package/lib/sandforge-frozen.mjs +272 -0
  216. package/lib/sandforge-mcp.mjs +40 -0
  217. package/lib/sandforge-monitor.mjs +43 -0
  218. package/lib/sandforge-seed.mjs +7 -0
  219. package/lib/sandforge-sync.mjs +7 -0
  220. package/lib/sandforge.mjs +28 -0
  221. 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{b as S,d as z}from"./chunk-GSKCGQIP.mjs";import{h as I}from"./chunk-TZE3Y7IQ.mjs";import{b as h}from"./chunk-CA5NAXSU.mjs";import{yb as R}from"./chunk-TTFDUKUS.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};
@@ -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 l="ObjectPermissions",c="SobjectType",f="SELECT PermissionsModifyAllData FROM UserPermissionAccess",u=/^[A-Za-z][A-Za-z0-9_]{0,79}$/;function d(r){return`SELECT QualifiedApiName, IsEverCreatable FROM EntityDefinition WHERE QualifiedApiName IN (${r.map(e=>`'${e}'`).join(", ")})`}function p(r,a,e){if(e===!1)return"platform";if(a.coverable===void 0)return"user";let t=a.coverable.has(r.toLowerCase());return a.modifyAllData===!0?t?"feature":"setup":t?"user":"parent"}function g(r){return r==="platform"||r==="setup"}async function b(r,a){let e=0,[t,o]=await Promise.allSettled([r.describeFields(a,l),r.query(a,f)]),n={};if(t.status==="fulfilled"){t.value.sent&&e++;let s=t.value.fields.find(i=>i.name===c);s&&s.picklistValues.length>0&&(n.coverable=new Set(s.picklistValues.map(i=>i.toLowerCase())))}else e++;if(o.status==="fulfilled"){e+=o.value.requests;let s=o.value.records[0];s&&typeof s.PermissionsModifyAllData=="boolean"&&(n.modifyAllData=s.PermissionsModifyAllData)}else e++;return{facts:n,requests:e}}async function m(r,a,e){let t=new Map,o=e.filter(n=>u.test(n));if(o.length===0)return{answered:t,requests:0};try{let n=await r(a,d(o));for(let s of n.records){let i=s.QualifiedApiName;typeof i=="string"&&typeof s.IsEverCreatable=="boolean"&&t.set(i.toLowerCase(),s.IsEverCreatable)}return{answered:t,requests:n.requests}}catch{return{answered:t,requests:1}}}function y(r,a){return async(e,t)=>{let[o,n]=await Promise.all([a(e).catch(()=>({})),m(r,e,t)]);return new Map(t.map(s=>[s,p(s,o,n.answered.get(s.toLowerCase()))]))}}function C(r,a){let e=a.coverable;if(!e)return[];let t=new Set;for(let o of r)if(!(o.type!=="reference"||o.nillable))for(let n of o.referenceTo)e.has(n.toLowerCase())&&t.add(n);return[...t]}export{p as a,g as b,b as c,m as d,y as e,C as f};
@@ -0,0 +1,9 @@
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 je,b as He}from"./chunk-TYYOBZMU.mjs";import{a as $e,b as be,c as Le,g as Ue}from"./chunk-HS4YRX4J.mjs";import{a as de,b as Ne,c as Fe}from"./chunk-TUACWKIH.mjs";import{a as De}from"./chunk-4TLYUZD5.mjs";import{b as R}from"./chunk-CA5NAXSU.mjs";import{bd as Ce,cd as ce,dc as ae,dd as Ie,gd as ue,hd as Me,id as _e,j as Pe,jd as xe,yb as ve}from"./chunk-TTFDUKUS.mjs";import{b as q,e as Oe,k as B,l as J,v as Re,z as Y}from"./chunk-7EANH5PY.mjs";var Z=class e{static DEFAULT_MAX_PER_ORG=5;static DEFAULT_RECYCLE_INTERVAL=900*1e3;connections=new Map;config;cleanupTimer;recycleTimer;maxPerOrg;recycleIntervalMs;latencySamples=new Map;constructor(t,n){this.config={maxConnections:t?.maxConnections??10,keepAliveInterval:t?.keepAliveInterval??6e4,connectionTimeout:t?.connectionTimeout??3e4,idleTimeout:t?.idleTimeout??3e5},this.maxPerOrg=n?.maxPerOrg??e.DEFAULT_MAX_PER_ORG,this.recycleIntervalMs=n?.recycleIntervalMs??e.DEFAULT_RECYCLE_INTERVAL}acquire(t,n,s){let r=this.connections.get(t);if(r&&r.active)return r.lastUsedAt=Date.now(),r.accessToken=s,r;this.connections.size>=this.config.maxConnections&&this.evictOldest();let o={orgId:t,instanceUrl:n,accessToken:s,createdAt:Date.now(),lastUsedAt:Date.now(),active:!0};return this.connections.set(t,o),o}release(t){let n=this.connections.get(t);n&&(n.lastUsedAt=Date.now())}remove(t){return this.latencySamples.delete(t),this.connections.delete(t)}get(t){return this.connections.get(t)}get size(){return this.connections.size}getConfig(){return{...this.config}}getMaxPerOrg(){return this.maxPerOrg}recordLatency(t,n){if(!Number.isFinite(n)||n<0)return;let s=this.latencySamples.get(t);s||(s=[],this.latencySamples.set(t,s)),s.push(n),s.length>1e3&&s.splice(0,s.length-1e3)}getLatencyMetrics(t){let n=this.latencySamples.get(t);if(!n||n.length===0)return;let s=[...n].sort((u,f)=>u-f),r=s.reduce((u,f)=>u+f,0),o=Math.floor(s.length*.95),a=Math.floor(s.length*.99);return{min:s[0],max:s[s.length-1],avg:Math.round(r/s.length),p95:s[Math.min(o,s.length-1)],p99:s[Math.min(a,s.length-1)],sampleCount:s.length}}getAllLatencyMetrics(){let t=new Map;for(let n of this.latencySamples.keys()){let s=this.getLatencyMetrics(n);s&&t.set(n,s)}return t}cleanupIdle(){let t=Date.now(),n=0;for(let[s,r]of this.connections)t-r.lastUsedAt>this.config.idleTimeout&&(this.connections.delete(s),n++);return n}recycleStale(){let t=Date.now(),n=0;for(let[s,r]of this.connections)t-r.createdAt>this.recycleIntervalMs&&(r.active=!1,this.connections.delete(s),n++);return n}startCleanup(){this.stopCleanup(),this.cleanupTimer=setInterval(()=>this.cleanupIdle(),this.config.keepAliveInterval)}stopCleanup(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0)}startRecycling(){this.stopRecycling(),this.recycleTimer=setInterval(()=>this.recycleStale(),this.recycleIntervalMs)}stopRecycling(){this.recycleTimer&&(clearInterval(this.recycleTimer),this.recycleTimer=void 0)}evictOldest(){let t,n=1/0;for(let[s,r]of this.connections)r.lastUsedAt<n&&(n=r.lastUsedAt,t=s);t&&this.connections.delete(t)}dispose(){this.stopCleanup(),this.stopRecycling(),this.connections.clear(),this.latencySamples.clear()}};var K=class{state="closed";failureCount=0;lastFailureTime=0;halfOpenSuccesses=0;halfOpenInFlight=0;config;constructor(t){this.config={failureThreshold:t?.failureThreshold??5,resetTimeout:t?.resetTimeout??6e4,halfOpenRequests:t?.halfOpenRequests??1}}getState(){return this.state==="open"&&this.shouldTransitionToHalfOpen()&&(this.state="half_open",this.halfOpenSuccesses=0),this.state}canExecute(){let t=this.getState();return t==="closed"?!0:t==="half_open"?this.halfOpenInFlight<this.config.halfOpenRequests:!1}recordSuccess(){this.state==="half_open"?(this.halfOpenSuccesses++,this.halfOpenInFlight=Math.max(0,this.halfOpenInFlight-1),this.halfOpenSuccesses>=this.config.halfOpenRequests&&this.reset()):this.failureCount=0}recordFailure(){this.failureCount++,this.lastFailureTime=Date.now(),this.state==="half_open"?this.trip():this.failureCount>=this.config.failureThreshold&&this.trip()}trip(){this.state="open",this.lastFailureTime=Date.now()}reset(){this.state="closed",this.failureCount=0,this.halfOpenSuccesses=0,this.halfOpenInFlight=0}getFailureCount(){return this.failureCount}acquirePermit(){return this.canExecute()?(this.getState()==="half_open"&&this.halfOpenInFlight++,!0):!1}releasePermit(){this.halfOpenInFlight=Math.max(0,this.halfOpenInFlight-1)}getConfig(){return{...this.config}}shouldTransitionToHalfOpen(){return Date.now()-this.lastFailureTime>=this.config.resetTimeout}};var ze=0;function An(){return ze}async function le(e,t){let n=Ue(e);try{return await t()}finally{ze+=n()}}var L=class extends Error{constructor(n,s,r){super(`${n}: ${r}`);this.code=n;this.orgId=s;this.name="OrgConnectionError"}code;orgId};import{homedir as kt,userInfo as St}from"node:os";var Tt=[/^ELECTRON_.+$/,/^VSCODE_(?!(PORTABLE|SHELL_LOGIN|ENV_REPLACE|ENV_APPEND|ENV_PREPEND)).+$/,/^SNAP(|_.*)$/,/^GDK_PIXBUF_.+$/],qe=["HTTP_PROXY","HTTPS_PROXY","NO_PROXY","NODE_EXTRA_CA_CERTS","NODE_OPTIONS","NODE_TLS_REJECT_UNAUTHORIZED"];function We(e){return Tt.some(t=>t.test(e))}function fe(e=process.env){let t={};for(let[n,s]of Object.entries(e))We(n)||(t[n]=s);return t.NO_COLOR="1",t}function vn(e=process.env){let t=Object.keys(e).filter(f=>(e[f]??"")!==""),n=qe.filter(f=>t.some(d=>d.toUpperCase()===f)),s=t.filter(f=>/^(SF|SFDX)_/i.test(f)).sort(),r=t.filter(f=>We(f)),o=r.filter(f=>f.startsWith("ELECTRON_")).sort(),a=r.length-o.length,u=r.length===0?"none":[...o,...a>0?[`${a} VSCODE_ or other VS Code variables`]:[]].join(", ");return`set: ${n.length>0?n.join(", "):"none of "+qe.join(", ")}; SF_/SFDX_: ${s.length>0?s.join(", "):"none"}; not passed to sf, as a terminal does not get them: ${u}`}function At(){try{return St().username}catch{return process.env.USERNAME??process.env.USER??""}}function Be(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Je(e,t=kt(),n=At()){let s=e;return t.length>3&&(s=s.replace(new RegExp(Be(t),"gi"),"~")),n.length>=2&&(s=s.replace(new RegExp(`(?<=[\\\\/])${Be(n)}(?=[\\\\/]|$)`,"gim"),"<user>")),s.replace(/00D\w{12,15}![\w.]+/g,"<token>").replace(/[\w.+-]+@[\w-]+(\.[\w-]+)+/g,"<username>")}function Cn(e){return e.split(/\r?\n/).map(t=>t.trim()).find(t=>t.length>0)}function Ot(e,t){if(process.platform!=="win32")return e[0];let s=(Object.entries(t).find(([r])=>r.toUpperCase()==="PATHEXT")?.[1]??".COM;.EXE;.BAT;.CMD").split(";").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0);return e.find(r=>{let o=r.lastIndexOf(".");return o>Math.max(r.lastIndexOf("\\"),r.lastIndexOf("/"))&&s.includes(r.slice(o).toLowerCase())})}async function In(e=1e4){let{exec:t}=await import("child_process"),{promisify:n}=await import("util"),s=process.platform==="win32"?"where sf node":"which -a sf node",r=fe(),o,a;try{let h=await n(t)(s,{timeout:e,windowsHide:!0,env:r});o=String(h.stdout)}catch(h){let i=h;o=String(i.stdout??""),o.trim()===""&&(a=Je(i.message??String(h)))}let u=o.split(/\r?\n/).map(h=>h.trim()).filter(h=>h.length>0).map(h=>Je(h)),f=h=>u.filter(i=>new RegExp(`(^|[\\\\/])${h}(\\.[A-Za-z0-9]+)?$`,"i").test(i)),d=f("sf"),c=Ot(d,r);return{sf:d,node:f("node"),...c!==void 0?{runs:c}:{},...a?{failure:a}:{}}}function Q(e,t){let n=(e[t.toLowerCase()]??e[t.toUpperCase()]??"").trim();return n===""?void 0:n}function Rt(e,t){if(t===void 0)return!1;let n=e.hostname.toLowerCase(),s=e.port||(e.protocol==="https:"?"443":"80");return t.split(/[\s,]+/).filter(r=>r!=="").some(r=>{if(r==="*")return!0;let[,o="",a]=/^(.*?)(?::(\d+))?$/.exec(r.toLowerCase())??[];if(a!==void 0&&a!==s)return!1;let u=o.replace(/^\*?\.?/,"");return u!==""&&(n===u||n.endsWith(`.${u}`))})}function Ve(e,t=process.env){let n;try{n=new URL(e)}catch{return}let s=n.protocol==="https:"?Q(t,"https_proxy")??Q(t,"http_proxy"):Q(t,"http_proxy");if(s!==void 0)return Rt(n,Q(t,"no_proxy"))?void 0:s}var Pt="https://login.salesforce.com";async function F(e,t=process.env){let{jsforce:n,HttpProxyTransport:s}=await import("./chunk-L5FGY6YA.mjs"),r=Ve(e.instanceUrl??e.loginUrl??Pt,t),o=new n.Connection({...e,...r!==void 0?{httpProxy:r}:{}});return r===void 0&&(o._transport=new s("")),o}var vt=10*1024*1024,pe=3e4,Ge=pe+2e3,he=`sf did not answer within ${pe/1e3} s \u2014 check the Salesforce CLI`;function Xe(e){return e instanceof Error&&e.message===he}var ge=2e4;function te(e,t,n){let s,r=new Promise((o,a)=>{s=setTimeout(()=>a(new Error(n)),t)});return Promise.race([e,r]).finally(()=>clearTimeout(s))}var U=new Z,Ct=300*1e3,ee=new Map,It={failureThreshold:3,resetTimeout:3e4},Ye=new Map;function Jn(){return U}function Mt(e){let t=Ye.get(e);return t||(t=new K({...It}),Ye.set(e,t)),t}var Ze;var me="panel";function Wn(e){me=e}function _t(e,t=me){return t==="panel"?"Reconnect it on the Organizations page (Try Reconnect on its card).":`Sign in to it again with "sf org login web --alias ${e}" (in a CI job, "sf org login jwt" or "sf org login sfdx-url"), then run the command again, with its --resume if it stopped a run part way.`}function Ke(e=me){return e==="panel"?"Create a new one and import it.":'Create a new one ("sf org create scratch") and give its alias.'}function Qe(e,t){let n=t?.organization_id;if(!(!Ze||typeof n!="string"))try{Ze(e,{organizationId:n})}catch(s){De.warn("Identity observer threw",{orgId:e,error:R(s)})}}var xt="[REDACTED]";function et(e){return typeof e=="string"&&e.length>0&&!e.startsWith(xt)&&!/\s/.test(e)}async function $t(e){if(!/^[\w.@+-]+$/.test(e))throw new Error(`Invalid username format: "${e}"`);let{execFile:t,exec:n}=await import("child_process"),{promisify:s}=await import("util"),r={maxBuffer:vt,timeout:pe,windowsHide:!0,env:fe()},o=i=>te(s(t)("sf",i,r),Ge,he),a=i=>{let g=!1,m,k=new Promise((T,S)=>{m=n(i,r,(E,C)=>{g=!0,E?S(E):T({stdout:C})})});return te(k,Ge,he).catch(T=>{throw!g&&m?.pid!==void 0&&t("taskkill",["/pid",String(m.pid),"/T","/F"],{windowsHide:!0},()=>{}),T})},u=(i,g)=>process.platform==="win32"?a(i):o(g),f=(i,g)=>{let m=i.replace(/\[[0-9;]*m/g,""),k=m.search(/[{[]/);if(k===-1)throw new Error(`Failed to parse "${g}" output: no JSON found. Ensure Salesforce CLI (sf) is installed and the org is authenticated.`);return JSON.parse(m.slice(k)).result??{}},d;try{let{stdout:i}=await u(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),g=f(i,"sf org display");d=typeof g.instanceUrl=="string"?g.instanceUrl:void 0}catch(i){if(Xe(i))throw i;d=void 0}try{let{stdout:i}=await u(`sf org auth show-access-token -o "${e}" --json`,["org","auth","show-access-token","-o",e,"--json"]),g=f(i,"sf org auth show-access-token");if(et(g.accessToken))return{accessToken:g.accessToken,instanceUrl:d}}catch(i){if(Xe(i))throw i}let{stdout:c}=await u(`sf org display -u "${e}" --json`,["org","display","-u",e,"--json"]),h=f(c,"sf org display");if(!et(h.accessToken))throw new Error('Neither "sf org auth show-access-token" nor "sf org display" returned an access token. The org session may have expired \u2014 try re-authenticating with "sf org login".');return!d&&typeof h.instanceUrl=="string"&&(d=h.instanceUrl),{accessToken:h.accessToken,instanceUrl:d}}async function Vn(e,t){return F({instanceUrl:e.instanceUrl,accessToken:e.accessToken??void 0,version:e.version,callOptions:{client:t}})}async function Gn(e){return F({instanceUrl:e.instanceUrl,accessToken:e.accessToken,version:e.version})}async function Xn(e,t,n){let s=e,r=n.getOrg(e);if(!r)throw new Error(`Org not found: ${e}`);let o=await t.getCredentials(e);if(!o?.accessToken||!o.instanceUrl)throw new Error(`No credentials for org "${r.alias}" (${e}). Reconnect the org.`);let a=r.metadata.apiVersion||Pe.DEFAULT_API_VERSION,u=U.get(s),f=Date.now()-(ee.get(e)??0)<Ct;if(u&&u.active&&u.accessToken===o.accessToken&&f)return u.lastUsedAt=Date.now(),F({instanceUrl:u.instanceUrl,accessToken:u.accessToken,version:a});let d=await F({instanceUrl:o.instanceUrl,accessToken:o.accessToken,version:a}),c=Mt(e);if(!c.acquirePermit())throw new L("ORG_TEMPORARILY_UNREACHABLE",e,`"${r.alias}" failed several times in a row, so SandForge waits a moment before calling it again. Try again in a minute.`);let h=Date.now(),i=`identity check did not answer within ${ge/1e3} s`;try{let g=await le(d,()=>te(d.identity(),ge,i)),m=Date.now()-h;return c.recordSuccess(),U.acquire(s,o.instanceUrl,o.accessToken),U.recordLatency(s,m),ee.set(e,Date.now()),Qe(e,g),d}catch(g){let m=Date.now()-h;if(U.remove(s),ee.delete(e),$e(g))try{let S=await $t(r.username),E=S.instanceUrl??o.instanceUrl;if(S.accessToken===o.accessToken&&E===o.instanceUrl)throw new Error("sf CLI token store is stale too (same expired token) \u2014 re-authenticate the org");let C=await F({instanceUrl:E,accessToken:S.accessToken,version:a}),W=await le(C,()=>te(C.identity(),ge,i));return await t.saveOrg(r,{...o,accessToken:S.accessToken,instanceUrl:E}),c.recordSuccess(),U.acquire(s,E,S.accessToken),U.recordLatency(s,m),ee.set(e,Date.now()),Qe(e,W),C}catch(S){c.recordFailure();let E=R(S);n.updateStatus(e,"expired");let C=ae(r,new Date().toISOString().slice(0,10));throw C!==void 0?new L("SCRATCH_ORG_EXPIRED",e,`The scratch org "${r.alias}" expired on ${C}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${Ke()} (cause: ${E})`):new L("ORG_AUTH_EXPIRED",e,`The session with "${r.alias}" has expired and could not be renewed. ${_t(r.alias)} (cause: ${E})`)}c.recordFailure();let k=R(g),T=ae(r,new Date().toISOString().slice(0,10));throw T!==void 0?(n.updateStatus(e,"expired"),new L("SCRATCH_ORG_EXPIRED",e,`The scratch org "${r.alias}" expired on ${T}: Salesforce deletes a scratch org when it expires, and no reconnect brings it back. ${Ke()} (cause: ${k})`)):new Error(`Connection failed for "${r.alias}": ${k}`)}finally{c.releasePermit()}}import{randomUUID as bt}from"node:crypto";import{hostname as Lt,homedir as Ut,uptime as Dt}from"node:os";import{mkdir as Nt,readFile as ct,readdir as Ft,rename as ut,writeFile as jt}from"node:fs/promises";import{dirname as we,join as Ee}from"node:path";function tt(e){let t=e,n=typeof t?.errorCode=="string"?t.errorCode:typeof t?.name=="string"?t.name:void 0;return{success:!1,errors:[{...n?{statusCode:n}:{},message:R(e)}]}}function nt(e){return(Array.isArray(e)?e[0]:e)??{success:!1,errors:[{message:"the org answered nothing"}]}}function as(e){return{typeOrg:()=>be(e),query:async t=>({records:(await e.query(t)).records}),identity:async()=>{let t=await e.identity();return{user_id:t.user_id,organization_id:t.organization_id}},createAssignment:async t=>e.sobject("PermissionSetAssignment").create(t,{headers:ve()}).then(nt,tt),deleteAssignment:async t=>e.sobject("PermissionSetAssignment").destroy(t).then(nt,tt)}}var j=class extends Error{constructor(n){super(n.message);this.refusal=n;this.name="MuteRefusedError"}refusal;get code(){return this.refusal.code}};function Ht(e){return e instanceof j||e instanceof Error&&e.name==="MuteRefusedError"&&"refusal"in e}var zt=60,qt=5*6e4,Bt=3e4,Jt=6e4,Wt=200,Vt=448,Gt=384,oe=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,H=q().regex(oe),Xt=J({id:H,permissionSetId:H,permissionSet:q().min(1).max(255)}),Yt=J({runId:q().min(1).max(255),host:q().min(1).max(255),pid:Oe().int().nonnegative(),hostStartedAt:Y.datetime({offset:!0}),acquiredAt:Y.datetime({offset:!0}),endsAt:Y.datetime({offset:!0}),needs:B(H),assigning:B(H),created:B(Xt)}),dt=J({version:Re(1),organizationId:H,userId:H,leases:B(Yt)}),Zt=J(je),Kt=He(e=>{let t=Zt.safeParse(e);return t.success?t.data:void 0});function lt(e=process.env,t=Ut()){let n=e.SANDFORGE_MUTE_LEASES_DIR;return n!==void 0&&n.trim()!==""?n:Ee(t,".sandforge","mute-leases")}function Qt(e,t,n){if(!oe.test(t)||!oe.test(n))throw new Error("A mute lease is journaled under an org id and a user id.");return Ee(e,`${t.slice(0,15)}-${n.slice(0,15)}.json`)}var ft={host:Lt(),pid:de.pid,startedAt:de.startedAt},en=6e4,D=new Set;function gt(e,t,n){return`${e}
8
+ ${t}
9
+ ${n}`}function tn(e,t,n,s={}){let r=s.now?.()??Date.now();if(!(Date.parse(e.endsAt)>r)||e.assigning.length>0)return!1;if(e.host!==n.host)return!0;if(e.pid===n.pid&&e.hostStartedAt===n.startedAt)return D.has(gt(t,e.runId,e.acquiredAt));let o=s.bootedAt?.()??Date.now()-Dt()*1e3,a=Date.parse(e.hostStartedAt);return Number.isFinite(a)&&a<o-en?!1:(s.isAlive??Fe)(e.pid)}var nn=e=>new Promise(t=>setTimeout(t,e));function ne(e,t,n){let s=n?.code;return new Error(`The journal of the mute leases in ${we(e)} could not be ${t}${typeof s=="string"?` (${s})`:""}: the user SandForge runs as must read and write that folder, or SANDFORGE_MUTE_LEASES_DIR name another, the same for every run that mutes the org.`)}function sn(e,t){let n=Date.parse(e.acquiredAt);return{pid:e.pid,host:e.host,here:e.host===t.host,until:new Date((Number.isFinite(n)?n:Date.now())+Ne).toISOString()}}function ht(e){return"A run locks it only while it takes, renews or ends a lease of the same org and user, but "+(e.here?`a lock its process could not remove holds until that process has ended, ${e.until} at the latest.`:`a lock a process of another machine could not remove holds until ${e.until}.`)}function rn(e){return`nothing was assigned. ${ht(e)} Run again in a moment, or end process ${e.pid} and run again should none of its runs be muting this org.`}async function se(e,t,n,s,r=rn,o=Jt){let a=n.self??ft,u={self:a,...n.checks?{checks:n.checks}:{}},f=Date.now()+o;for(await Nt(we(e),{recursive:!0,mode:Vt}).catch(d=>{throw ne(e,"made",d)});;){let d;try{d=Kt.acquire(`${e}.lock`,c=>c,u)}catch(c){throw ne(e,"locked",c)}if("lock"in d)try{let c=await on(e,t).catch(i=>{throw ne(e,"read",i)});return await s(c,async i=>{let g=`${e}.${process.pid}-${bt()}.tmp`;try{await jt(g,JSON.stringify(i,null,2),{encoding:"utf8",mode:Gt}),await ut(g,e)}catch(m){throw ne(e,"written",m)}})}finally{d.lock.release()}if(Date.now()>f){let c=sn(d.busy,a);throw new j({code:"MUTE_FAILED",message:`The journal of the mute leases in ${we(e)} stayed locked for a minute by process ${c.pid} on ${c.host}: ${r(c)}`})}await nn(Wt)}}async function on(e,t){let n={version:1,...t,leases:[]},s;try{s=await ct(e,"utf8")}catch(r){if(r.code==="ENOENT")return n;throw r}try{let r=dt.safeParse(JSON.parse(s));if(r.success)return r.data}catch{}return await ut(e,`${e}.${Date.now()}.unreadable`).catch(()=>{}),n}var an=new Set(["ENTITY_IS_DELETED","INVALID_CROSS_REFERENCE_KEY","NOT_FOUND"]);async function re(e,t,n,s){let r=t.leases.filter(c=>c!==n&&s(c)),o=[...n.created],a=new Set,u=n.assigning[0];if(u!==void 0){let c=new Set(t.leases.flatMap(i=>i===n?[]:i.created.map(g=>g.id))),h=await e.query(`SELECT Id, PermissionSetId, PermissionSet.Name FROM PermissionSetAssignment WHERE AssigneeId = '${t.userId}' AND PermissionSetId IN ('${u}')`).then(i=>i.records).catch(()=>[]);for(let i of h){let g=typeof i.Id=="string"?i.Id:void 0,m=typeof i.PermissionSetId=="string"?i.PermissionSetId:void 0;if(!g||!m||c.has(g)||o.some(T=>T.id===g))continue;let k=i.PermissionSet;o.push({id:g,permissionSetId:m,permissionSet:typeof k?.Name=="string"?k.Name:m}),a.add(g)}}let f={removed:[],passed:[],left:[],found:[]};for(let c of o){let h=r.find(m=>m.needs.includes(c.permissionSetId));if(h){h.created.some(m=>m.id===c.id)||h.created.push(c),f.passed.push(c);continue}let i=await e.deleteAssignment(c.id),g=i.errors?.[0]?.statusCode??i.errors?.[0]?.errorCode;i.success||g!==void 0&&an.has(g)?(f.removed.push(c),a.has(c.id)&&f.found.push(c)):f.left.push({...c,why:i.errors?.[0]?.message??g??"the org refused the delete"})}let d=t.leases.indexOf(n);return f.left.length===0?t.leases.splice(d,1):t.leases[d]={...n,endsAt:new Date(0).toISOString(),needs:[],assigning:[],created:f.left.map(({id:c,permissionSetId:h,permissionSet:i})=>({id:c,permissionSetId:h,permissionSet:i}))},f}function N(e){return e.map(t=>t.permissionSet)}function st(e,t){let n=r=>N(r).join(", "),s=[];return e.removed.length>0&&s.push(`What this run had assigned was taken back: ${n(e.removed)}.`),e.passed.length>0&&s.push(`${n(e.passed)} stays assigned for another run that mutes this org as the same user${t?", which takes it back as it ends":""}.`),e.left.length>0&&s.push(`${e.left.map(r=>`${r.permissionSet} (${r.why})`).join(", ")} could not be taken back${t?": the next run that mutes this org takes it back":""}.`),s}function rt(e,t){return`The journal still names this run's lease: this process tries again while it runs, and releases the lease once the journal can be written; the next run that mutes this org from another process releases it at the latest once process ${e} has ended.`+(t?` Until it is released, and before ${t.until}, a run of another process that ends may leave what it holds of ${t.sets.join(", ")} assigned for that lease, which the release takes back.`:"")}function pt(e){let t=e.length===1?"it":"them";return`found assigned to the user the run writes as for a run whose process ended as it assigned ${t}; found by user and set, not by id: had an admin assigned ${t} to that user since, theirs went with ${t}`}async function cn(e,t,n){let s=[];for(let r of[...t.leases])n(r)||s.push(...(await re(e,t,r,n)).found);return s}async function un(e){let t;try{t=(await e.query("SELECT PermissionsAssignPermissionSets, PermissionsManageUsers FROM UserPermissionAccess")).records[0]}catch(n){return`the org would not say whether the user the run writes as may assign permission sets (${R(n)})`}if(!(t?.PermissionsAssignPermissionSets===!0||t?.PermissionsManageUsers===!0))return"the user the run writes as cannot assign permission sets (neither Assign Permission Sets nor Manage Users)"}function ot(e){let t=e.indexOf("__");return t>0&&!e.slice(t+2).includes("__")?{namespace:e.slice(0,t),developerName:e.slice(t+2)}:{namespace:"",developerName:e}}var it=/^[A-Za-z][A-Za-z0-9_]*$/;async function dn(e,t){let s=t.map(ot).filter(a=>it.test(a.developerName)&&(!a.namespace||it.test(a.namespace)));if(s.length===0)return new Map;let r=await e.query("SELECT Id, Name, NamespacePrefix FROM PermissionSet WHERE Name IN ("+[...new Set(s.map(a=>`'${a.developerName}'`))].join(", ")+")"),o=new Map;for(let a of t){let{namespace:u,developerName:f}=ot(a),d=r.records.find(c=>String(c.Name??"").toLowerCase()===f.toLowerCase()&&String(c.NamespacePrefix??"").toLowerCase()===u.toLowerCase());typeof d?.Id=="string"&&o.set(a,d.Id)}return o}async function at(e,t,n){if(n.length===0)return new Map;let s=await e.query(`SELECT Id, PermissionSetId FROM PermissionSetAssignment WHERE AssigneeId = '${t}' AND PermissionSetId IN (${n.map(o=>`'${o}'`).join(", ")})`),r=new Map;for(let o of s.records){let a=o.PermissionSetId,u=o.Id;typeof a=="string"&&typeof u=="string"&&r.set(a,u)}return r}function ye(e,t,n){return{state:t,assigned:[],held:[],permissions:ce(e),silenced:e.silenced.map(s=>({...s})),stillRan:e.stillRuns.map(s=>({...s})),...e.assign.length>0?{alsoLifted:(e.alsoLifts??[]).map(s=>({...s}))}:{},...e.liftsUnread?{liftsUnread:e.liftsUnread.map(s=>({...s}))}:{},...n?{reason:n}:{}}}var mt="nothing found can be muted: no flow, process or workflow rule the run fires has a bypass a permission set of the target holds; the run goes on as without the option";async function ln(e,t,n={}){let s,r;try{let d=await e.typeOrg();s=Le(d),r=d.id}catch(d){return{refused:{code:"MUTE_PRODUCTION",message:`The target did not say what org it is (${R(d)}), and its automation is muted on no org that cannot be told from a production one. Nothing was assigned.`}}}if(s)return{refused:{code:"MUTE_PRODUCTION",message:"The target is a production org: its automation is never muted there, whatever the setting says. Nothing was assigned; run without the option."}};let{plan:o,automation:a,planned:u}=hn(t,n.writes);if(o.assign.length===0)return{plan:o,automation:t,planned:u,acquire:async()=>({outcome:u,release:async()=>u})};let f=await un(e);return f!==void 0?{refused:{code:"MUTE_NO_RIGHT",message:`The target's automation cannot be muted: ${f}. Nothing was assigned: run it without muting the target's automation, or have that user given Assign Permission Sets.`}}:(wt.set(o,await gn(n.dir??lt(),r)),{plan:o,automation:a,planned:u,acquire:d=>pn(e,o,d,n)})}var wt=new WeakMap,fn=/^[A-Za-z0-9]{15}-[A-Za-z0-9]{15}\.json$/;async function gn(e,t){if(!oe.test(t))return 0;let n=`${t.slice(0,15)}-`,s;try{s=await Ft(e)}catch{return 0}let r=0;for(let o of s)if(!(!o.startsWith(n)||!fn.test(o)))try{let a=dt.safeParse(JSON.parse(await ct(Ee(e,o),"utf8")));if(!a.success)continue;for(let u of a.data.leases)r+=(u.assigning.length>0?1:0)+u.created.length}catch{}return r}function hn(e,t){let n=Ce(e,t);return n.assign.length===0?{plan:n,automation:e,planned:ye(n,"nothing",mt)}:{plan:n,automation:Ie(e,ce(n)),planned:ye(n,"planned")}}async function pn(e,t,n,s={}){let r=s.self??ft,o=()=>s.checks?.now?.()??Date.now(),a=s.minutes??zt,u=l=>{throw new j({code:"MUTE_FAILED",message:l})},f=await e.identity().catch(l=>u(`The target would not say who the run writes as (${R(l)}).`)),d={organizationId:f.organization_id,userId:f.user_id},c=Qt(s.dir??lt(),d.organizationId,d.userId),h=t.assign.map(l=>l.permissionSet),i=await dn(e,h).catch(l=>u(`The permission sets to assign could not be read (${R(l)}).`)),g=h.filter(l=>!i.has(l));g.length>0&&u(`The target holds no permission set ${g.join(", ")}: nothing was assigned.`);let m=h.map(l=>i.get(l)),k=new Map(h.map(l=>[i.get(l),l])),T=l=>tn(l,c,r,s.checks),S=new Date(o()).toISOString(),E=gt(c,n,S),C=!1,W=m.map(l=>k.get(l)),yt=s.retryEveryMs??Bt,V,ke=(l,A)=>{if(V!==void 0)return;let p=new Set(l.map(y=>y.id)),O=!1,P=()=>clearInterval(V);V=setInterval(()=>{O||(O=!0,se(c,d,s,async(y,G)=>{let M=y.leases.find(x=>x.runId===n&&x.acquiredAt===S);if(M){M.assigning=[],M.created=[...M.created,...A.filter(b=>!M.created.some(X=>X.id===b.id))].filter(b=>!p.has(b.id));let x=await re(e,y,M,T);for(let b of x.removed)p.add(b.id);await G(y)}P()},void 0,0).catch(()=>{}).finally(()=>{O=!1}))},yt),V.unref?.()},z=await se(c,d,s,async(l,A)=>{let p=N(await cn(e,l,T)),O=await at(e,d.userId,m),P=m.filter(w=>!O.has(w)),y={runId:n,host:r.host,pid:r.pid,hostStartedAt:r.startedAt,acquiredAt:S,endsAt:new Date(o()+a*6e4).toISOString(),needs:m,assigning:[...P],created:[]};l.leases.push(y),D.add(E),await A(l),C=!0;let G=[...y.assigning],M=()=>A(l).then(()=>{G=[...y.assigning]},w=>R(w)),x=async w=>{y.assigning=[];let I=await re(e,l,y,T);D.delete(E);let v=await M();v!==void 0&&ke(I.removed,[...I.passed,...I.left]);let _=v!==void 0&&G.length===0?{sets:W,until:y.endsAt}:void 0,Ae=st(I,v===void 0);return u([w,...v!==void 0&&v!==w?[v]:[],...Ae.length>0?Ae:["Nothing was assigned."],...v!==void 0&&(I.passed.length>0||I.left.length>0||_)?[rt(r.pid,_)]:[],...p.length>0?[`Taking its lease, the run took back ${p.join(", ")}, ${pt(p)}.`]:[]].join(" "))};for(let w of P){let I=await e.createAssignment({AssigneeId:d.userId,PermissionSetId:w});if(y.assigning=y.assigning.filter(_=>_!==w),I.success&&I.id){y.created.push({id:I.id,permissionSetId:w,permissionSet:k.get(w)});let _=await M();if(_!==void 0)return x(_);continue}let v=I.errors?.[0];if((v?.statusCode??v?.errorCode)==="DUPLICATE_VALUE"){let _=await M();if(_!==void 0)return x(_);continue}return x(`${k.get(w)} could not be assigned to the user the run writes as: ${v?.message??v?.statusCode??"the org refused it"}.`)}let b=await at(e,d.userId,m).catch(()=>new Map),X=m.filter(w=>!b.has(w));if(X.length>0)return x(`Read back, the user the run writes as does not hold ${X.map(w=>k.get(w)).join(", ")}.`);let Et=new Set(y.created.map(w=>w.permissionSetId));return{endsAt:y.endsAt,assigned:y.created.map(w=>w.permissionSet),held:m.filter(w=>!Et.has(w)).map(w=>k.get(w)),found:p}}).catch(l=>{if(D.delete(E),Ht(l))throw l;return u(`${R(l)}${C?"":" Nothing was assigned."}`)}),$={...ye(t,"muted"),assigned:z.assigned,held:z.held,leaseEndsAt:z.endsAt,...z.found.length>0?{tookBackOfEnded:z.found}:{}},Se=s.renewEveryMs??qt,ie=Se>0?setInterval(()=>{se(c,d,s,async(l,A)=>{let p=l.leases.find(P=>P.runId===n&&P.acquiredAt===S);if(!p||!D.has(E))return;let O=new Date(o()+a*6e4).toISOString();p.endsAt=O,await A(l),$.leaseEndsAt=O}).catch(()=>{})},Se):void 0;ie?.unref?.();let Te;return{outcome:$,release:()=>(Te??=(async()=>{ie&&clearInterval(ie);let l={};try{await se(c,d,s,async(p,O)=>{let P=p.leases.find(y=>y.runId===n&&y.acquiredAt===S);D.delete(E),P&&(l.done=await re(e,p,P,T),await O(p))},p=>`nothing was taken back. ${ht(p)} Should none of its runs be muting this org, end process ${p.pid}`);let A=l.done?.left??[];return{...$,released:A.length===0,takenBack:N(l.done?.removed??[]),...l.done&&l.done.passed.length>0?{passed:N(l.done.passed)}:{},...A.length>0?{notTakenBack:N(A),reason:`${A.map(p=>`${p.permissionSet} (${p.why})`).join(", ")} could not be taken back: the lease ends at ${$.leaseEndsAt}, and the next run that mutes this org releases it`}:{}}}catch(A){D.delete(E);let p=l.done;if(ke(p?.removed??[],p?[...p.passed,...p.left]:[]),p!==void 0){let O=$.leaseEndsAt,P=O!==void 0&&Date.parse(O)>o()?{sets:W,until:O}:void 0;return{...$,released:!1,takenBack:N(p.removed),notTakenBack:N([...p.passed,...p.left]),reason:[R(A),...st({...p,removed:[]},!1),rt(r.pid,P)].join(" ")}}return{...$,released:!1,takenBack:[],reason:`the assignments could not be taken back (${R(A)}): this process tries again while it runs, and takes them back once it can use the journal; past ${$.leaseEndsAt}, or once process ${r.pid} has ended, the next run that mutes this org releases the lease`}}})(),Te)}}var mn=2,wn=3;function yn(e){return!e||e.assign.length===0?0:mn+wn+2*e.assign.length+(wt.get(e)??0)}function cs(e){let t=yn(e);return t>0?{mute:t}:{}}function En(e){return{state:"nothing",assigned:[],held:[],permissions:[],silenced:[],stillRan:[],reason:`nothing can be muted: ${e}; the run goes on as without the option`}}function us(e){return e?{mutedAutomation:e.muted,...e.plan?{mutePlan:e.plan}:{}}:{}}async function ds(e,t,n={}){if(typeof t.unread=="string")return{automation:void 0,muted:En(`the target's automation could not be read (${t.unread})`)};let s=await ln(await e(),t,n);if("refused"in s)throw new j(s.refused);return{automation:s.automation,...s.plan.assign.length>0?{prepared:s}:{},muted:s.planned,plan:s.plan}}function ls(e){let t=e?.mutedAutomation;return t!==null&&typeof t=="object"?t:void 0}function fs(e,t){let n=[];e.state==="nothing"?n.push(`mute: ${e.reason??mt}`):e.state==="planned"?n.push(`mute: planned, ${e.permissions.length>0?`the permission set(s) holding ${e.permissions.join(", ")}`:"nothing"} for the user it writes as in ${t}, for the run alone; nothing is assigned yet`):n.push(`mute: ${e.assigned.length>0?`assigned ${e.assigned.join(", ")}`:"assigned nothing"}${e.held.length>0?`; ${e.held.join(", ")} held already`:""} to the user the run writes as in ${t}, for the run alone`),e.tookBackOfEnded&&e.tookBackOfEnded.length>0&&n.push(` taken back before the run: ${e.tookBackOfEnded.join(", ")}, `+pt(e.tookBackOfEnded));for(let r of e.silenced)n.push(` silenced: ${ue(r)} (bypass ${r.permission})`);for(let r of e.stillRan)n.push(` still runs: ${ue(r)} (${Me(r.why)})`);for(let r of e.alsoLifted??[])n.push(` also lifts: ${_e(r)}`);for(let r of e.liftsUnread??[])n.push(` ${xe(r)}`);let s=e.takenBack??(e.released===!0?e.assigned:[]);if(s.length>0&&n.push(` taken back: ${s.join(", ")}, as the run ended`),e.passed&&e.passed.length>0&&n.push(` stays assigned: ${e.passed.join(", ")}, for another run that mutes ${t} as the same user, which takes ${e.passed.length===1?"it":"them"} back as it ends`),e.released===!1){let r=e.notTakenBack!==void 0&&e.notTakenBack.length===0;n.push(` ${r?"lease not released":"not taken back"}: ${e.reason??"the assignments stay until the lease ends"}`)}return n}export{An as a,le as b,L as c,fe as d,vn as e,Je as f,Cn as g,In as h,Ve as i,F as j,te as k,Jn as l,Wn as m,et as n,$t as o,Vn as p,Gn as q,Xn as r,as as s,Ht as t,ln as u,hn as v,yn as w,cs as x,us as y,ds as z,ls as A,fs as B};
@@ -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-JPUR2CFX.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-O2HDYYUV.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-TTFDUKUS.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,15 @@
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 ht,b as on,c as sn}from"./chunk-66NMFCWX.mjs";import{a as cn}from"./chunk-LWW4U276.mjs";import{a as Rr,b as fn}from"./chunk-XCA5AONB.mjs";import{a as pn,e as kr,i as yr}from"./chunk-WR2GIKWE.mjs";import{Aa as cr,Ba as pr,Bc as un,Ca as ur,Dc as vr,b as mt,d as Zt,e as en,f as tn,j as se,k as nn,l as jt,m as Mt,n as xe,o as M,pa as Zn,qa as er,ra as tr,s as de,sa as nr,ta as rr,ua as or,uc as le,va as sr,wa as Et,xa as ar,ya as ir,yc as gr,za as dr}from"./chunk-2CNCDM56.mjs";import{d as mr}from"./chunk-SIHORWVK.mjs";import{a as gt,b as Yn}from"./chunk-CE6ZDGBB.mjs";import{a as Tr,b as mn,c as Ir,d as gn,e as bt,f as kt,g as Nr,h as hn,i as Pr,j as bn,k as kn}from"./chunk-B5QQJ4SI.mjs";import{k as Ar}from"./chunk-F43REJDZ.mjs";import{S as hr,U as br,l as lr}from"./chunk-JPUR2CFX.mjs";import{d as wr}from"./chunk-T63U4OZJ.mjs";import{a as ln}from"./chunk-YYZL7UGV.mjs";import{B as Sr,r as Re}from"./chunk-MFG4MUIO.mjs";import{b as an,c as rt,d as dn,h as fr}from"./chunk-GSKCGQIP.mjs";import{a as Be}from"./chunk-5LFSFYFJ.mjs";import{c as $t,e as oe,f as Ct,i as rn,p as Or}from"./chunk-VYXMVJL5.mjs";import{d as Xn,e as Qn,g as Vn,h as Jn}from"./chunk-INIT2UKJ.mjs";import{p as W,q as ft,t as Pt}from"./chunk-A527W53V.mjs";import{a as qn,f as Yt,h as Nt}from"./chunk-TZE3Y7IQ.mjs";import{b as R}from"./chunk-CA5NAXSU.mjs";import{$b as Jt,Ha as Wn,Ia as Un,Id as Gn,Ja as Hn,Wb as De,ec as nt,hc as Kn,ic as St,w as _n,yb as Vt}from"./chunk-TTFDUKUS.mjs";import{b as Q,f as Bn,k as Ke,l as Ge,q as Fn,v as Qt}from"./chunk-7EANH5PY.mjs";var lo={defaultQueryLimit:500,previewQueryLimit:200,exportQueryLimit:1e3},fo={defaultQueryLimit:2e3,previewQueryLimit:2e3,exportQueryLimit:5e3};function yn(s){return s==="production"?{...lo}:{...fo}}function wn(s){return s?"sandbox":"production"}var ot="IsPersonAccount",mo=new Set(["FirstName","LastName","MiddleName","Suffix","Salutation","Phone","Fax"]);function go(s){if(mo.has(s))return s;if(s.endsWith("__c"))return`${s.slice(0,-3)}__pc`;if(/^[A-Za-z][A-Za-z0-9]*$/.test(s))return`Person${s}`}function An(s){let e=(r,o)=>r.fieldPattern.toLowerCase().startsWith(`${o.toLowerCase()}.`)?r.fieldPattern.slice(o.length+1):void 0,t=new Set(s.flatMap(r=>{let o=e(r,W);return o===void 0?[]:[o.toLowerCase()]})),n=[];for(let r of s){let o=e(r,ft),a=o===void 0?void 0:go(o);a===void 0||t.has(a.toLowerCase())||(t.add(a.toLowerCase()),n.push({...r,fieldPattern:`${W}.${a}`}))}return n}function $r(s){if(s.objectApiName.toLowerCase()!==W.toLowerCase()||!s.fields.some(p=>p.name===ot))return;let e=new Map(s.fields.map(p=>[p.name.toLowerCase(),p])),t=new Set(s.kept.map(p=>p.fieldApiName.toLowerCase())),n=[],r=new Set,o=[],a=(p,u)=>{t.add(u.name.toLowerCase()),r.add(u.name),n.push({...p,objectApiName:W,fieldApiName:u.name})};for(let p of s.derived){let u=e.get(p.fieldApiName.toLowerCase());if(!u){o.push(p.fieldApiName);continue}t.has(u.name.toLowerCase())||a(p,u)}let i=s.fields.filter(p=>Kn(p.name)&&p.updateable===!0&&p.calculated!==!0&&!t.has(p.name.toLowerCase())),d=new Map,c=i.map(p=>{let u=jr(p.name);return d.set(u,p),{...p,name:u,label:p.label??p.name,type:p.type??"string"}});for(let p of kr(s.detector,ft,c)){let u=d.get(p.field.name);!u||t.has(u.name.toLowerCase())||a({objectApiName:W,fieldApiName:u.name,method:yr({...p.field,name:u.name}),config:{}},u)}return{rules:n,personOnly:r,unseen:o}}function Cr(s,e){let t=new Set((e??[]).map(n=>n.name.toLowerCase()));return s.filter(n=>!t.has(jr(n).toLowerCase()))}function jr(s){return s.endsWith("__pc")?`${s.slice(0,-4)}__c`:s.startsWith("Person")&&!s.includes("__")?s.slice(6):s}function Mr(s,e,t,n){if(s.toLowerCase()!==W.toLowerCase())return[...t];let r=Pt(e,!1);return t.filter(o=>!St(W,o.fieldApiName,r)&&(r==="person"||!n.has(o.fieldApiName)))}import{randomBytes as Po}from"node:crypto";var yt=[{id:"tpl-gdpr-standard",name:"GDPR Standard",description:"Standard GDPR compliance: anonymize personal data fields across common Salesforce objects.",complianceFramework:"gdpr",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Replace with fake first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Replace with fake last name."},{fieldPattern:"Contact.Email",ruleType:"fake",description:"Replace with fake email address."},{fieldPattern:"Contact.Phone",ruleType:"mask",description:"Mask phone number (keep last 4 digits).",config:{maskKeepLast:4}},{fieldPattern:"Contact.MailingStreet",ruleType:"fake",description:"Replace with fake street address."},{fieldPattern:"Contact.MailingCity",ruleType:"fake",description:"Replace with fake city."},{fieldPattern:"Contact.MailingPostalCode",ruleType:"mask",description:"Mask postal code."},{fieldPattern:"Lead.FirstName",ruleType:"fake",description:"Replace with fake first name."},{fieldPattern:"Lead.LastName",ruleType:"fake",description:"Replace with fake last name."},{fieldPattern:"Lead.Email",ruleType:"fake",description:"Replace with fake email address."},{fieldPattern:"Lead.Phone",ruleType:"mask",description:"Mask phone number."},{fieldPattern:"Lead.Street",ruleType:"fake",description:"Replace with fake street address."},{fieldPattern:"Account.BillingStreet",ruleType:"fake",description:"Replace with fake address."},{fieldPattern:"Account.Phone",ruleType:"mask",description:"Mask phone number."}]},{id:"tpl-ccpa-california",name:"CCPA California",description:"CCPA compliance: anonymize consumer personal information per California privacy regulations.",complianceFramework:"ccpa",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Replace consumer first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Replace consumer last name."},{fieldPattern:"Contact.Email",ruleType:"hash",description:"Hash email for pseudonymization."},{fieldPattern:"Contact.Phone",ruleType:"nullify",description:"Nullify phone number."},{fieldPattern:"Contact.MailingStreet",ruleType:"nullify",description:"Nullify street address."},{fieldPattern:"Contact.MailingCity",ruleType:"nullify",description:"Nullify city."},{fieldPattern:"Contact.MailingPostalCode",ruleType:"nullify",description:"Nullify postal code."},{fieldPattern:"Contact.Birthdate",ruleType:"nullify",description:"Remove date of birth."},{fieldPattern:"Lead.Email",ruleType:"hash",description:"Hash email for pseudonymization."},{fieldPattern:"Lead.Phone",ruleType:"nullify",description:"Nullify phone number."}]},{id:"tpl-hipaa-health",name:"HIPAA Health Data",description:"HIPAA compliance: de-identify protected health information (PHI) in healthcare Salesforce orgs.",complianceFramework:"hipaa",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Replace patient first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Replace patient last name."},{fieldPattern:"Contact.Email",ruleType:"hash",description:"Hash email address."},{fieldPattern:"Contact.Phone",ruleType:"mask",description:"Mask phone number."},{fieldPattern:"Contact.Birthdate",ruleType:"nullify",description:"Remove date of birth (PHI)."},{fieldPattern:"Contact.MailingStreet",ruleType:"nullify",description:"Remove address (PHI)."},{fieldPattern:"Contact.MailingCity",ruleType:"nullify",description:"Remove city (PHI)."},{fieldPattern:"Contact.MailingState",ruleType:"nullify",description:"Remove state (PHI)."},{fieldPattern:"Contact.MailingPostalCode",ruleType:"truncate",description:"Truncate to first 3 digits.",config:{truncateLength:3,truncateKeep:"first"}},{fieldPattern:"Account.Name",ruleType:"fake",description:"Replace facility name."},{fieldPattern:"Account.Phone",ruleType:"mask",description:"Mask facility phone."}]},{id:"tpl-sandbox-scrub",name:"Sandbox Data Scrub",description:"General-purpose sandbox data scrubbing: mask all PII for safe development use.",complianceFramework:"custom",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Fake first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Fake last name."},{fieldPattern:"Contact.Email",ruleType:"preserve_format",description:"Replace keeping email format."},{fieldPattern:"Contact.Phone",ruleType:"preserve_format",description:"Replace keeping phone format."},{fieldPattern:"Lead.FirstName",ruleType:"fake",description:"Fake first name."},{fieldPattern:"Lead.LastName",ruleType:"fake",description:"Fake last name."},{fieldPattern:"Lead.Email",ruleType:"preserve_format",description:"Replace keeping email format."},{fieldPattern:"Lead.Company",ruleType:"fake",description:"Fake company name."},{fieldPattern:"Account.Name",ruleType:"fake",description:"Fake account name."},{fieldPattern:"Account.Website",ruleType:"constant",description:"Replace with placeholder URL.",config:{constantValue:"https://example.com"}},{fieldPattern:"Opportunity.Name",ruleType:"fake",description:"Fake opportunity name."}]}];var zt=class{operations=new Map;ttlMs;nowFn;constructor(e=36e5,t=Date.now){this.ttlMs=e,this.nowFn=t}isDuplicate(e){return this.pruneExpired(),this.operations.has(e)}register(e,t,n,r){if(this.pruneExpired(),this.operations.has(e))throw new Error(`Duplicate DML operation detected: ${e}`);let o={operationId:e,objectApiName:t,dmlType:n,recordCount:r,registeredAt:new Date(this.nowFn()).toISOString(),status:"pending"};return this.operations.set(e,o),o}markCompleted(e){let t=this.operations.get(e);t&&(t.status="completed")}markFailed(e){let t=this.operations.get(e);t&&(t.status="failed")}get(e){return this.operations.get(e)}get size(){return this.operations.size}clear(){this.operations.clear()}pruneExpired(){let e=this.nowFn()-this.ttlMs;for(let[t,n]of this.operations)new Date(n.registeredAt).getTime()<e&&this.operations.delete(t);if(this.operations.size>1e4){let t=Array.from(this.operations.entries()),n=t.length-1e4;for(let r=0;r<n;r++)this.operations.delete(t[r][0])}}};var ho=3e3;function Se(s){return s.slice(0,15)}function bo(s,e){let t=s??null,n=e??null;return t===n?!0:t===null||n===null?!1:typeof t=="object"||typeof n=="object"?JSON.stringify(t)===JSON.stringify(n):String(t)===String(n)}function ko(s){let e=[],t=[],n=0;for(let r of s)t.length>0&&n+r.length+2>ho&&(e.push(t),t=[],n=0),t.push(r),n+=r.length+2;return t.length>0&&e.push(t),e}async function Er(s,e,t){let n=t.map(i=>i.Id).filter(rt),r=[...new Set(t.flatMap(i=>Object.keys(i)))].filter(i=>i.toLowerCase()!=="id");if(n.length===0||r.length===0)return{write:[...t],unchanged:0};let o=new Map;try{for(let i of ko(r))for(let d of await fr(s,e,i,n))typeof d.Id=="string"&&o.set(Se(d.Id),{...o.get(Se(d.Id)),...d})}catch(i){return{write:[...t],unchanged:0,unread:R(i)}}let a=t.filter(i=>{let d=rt(i.Id)?o.get(Se(i.Id)):void 0;return d?Object.keys(i).some(c=>c.toLowerCase()!=="id"&&!bo(i[c],d[c])):!0});return{write:a,unchanged:t.length-a.length}}async function zr(s,e,t,n){let r=Nt(e),o=new Set,a=t.filter(rt);for(let i=0;i<a.length;i+=an){let d=a.slice(i,i+an),[c]=dn(d,d.length),p=new Set,u=await s.query(`SELECT Id, LastModifiedDate FROM ${r} WHERE Id IN (${c})`);for(let h of u.records){if(typeof h.Id!="string")continue;p.add(Se(h.Id)),Date.parse(String(h.LastModifiedDate??""))<=n||o.add(Se(h.Id))}let b=d.filter(h=>!p.has(Se(h)));if(b.length===0)continue;let[l]=dn(b,b.length),f=await s.query(`SELECT Id FROM ${r} WHERE Id IN (${l}) AND IsDeleted = true`,{scanAll:!0});for(let h of f.records)typeof h.Id=="string"&&o.add(Se(h.Id))}return o}function Lr(s,e){return{async*[Symbol.asyncIterator](){for await(let t of s){let n=t.filter(r=>!(rt(r.Id)&&e.has(Se(r.Id))));n.length>0&&(yield n)}}}}function Rn(s,e){let t=0;return{batches:{async*[Symbol.asyncIterator](){let n=new Map,r=[],o=0;for await(let i of s)for(let d of i){if(o++,!rt(d.Id)){r.push({...d});continue}let c=n.get(Se(d.Id));if(!c){n.set(Se(d.Id),{...d});continue}for(let[p,u]of Object.entries(d))p in c||(c[p]=u)}t=o;let a=[...n.values(),...r];for(let i=0;i<a.length;i+=e)yield a.slice(i,i+e)}},lines:()=>t}}var vn="anonymization:template:",Dr="anonymizationTemplates",xr=Ge({id:Q().min(1).max(100),name:Q().trim().min(1).max(Wn),description:Q().max(500),complianceFramework:Qt("custom"),rules:Ke(Fn(Hn,Ge({description:Q().max(500)}))).min(1).max(Un),saved:Qt(!0),createdAt:Q()}),Lt=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${vn}${e.id}`,e,Dr)}load(e){let t=xr.safeParse(this.configStore.get(`${vn}${e}`));return t.success?t.data:void 0}list(){let e=[];for(let t of Object.values(this.configStore.getByCategory(Dr))){let n=xr.safeParse(t);n.success&&e.push(n.data)}return e.sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}delete(e){return this.configStore.delete(`${vn}${e}`)}};import{createHash as Br}from"node:crypto";var wo="anonymization:checkpoint:",Ao="anonymizationCheckpoints",qe=2e3,Tn=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Ro=Q().min(1).max(255),vo=Ge({id:Q().regex(Tn),fields:Ke(Ro).min(1).max(800),digest:Q().regex(/^[0-9a-f]{64}$/)}),To=Ge({objectApiName:Q().min(1).max(255),done:Bn(),afterId:Q().regex(Tn).optional(),refused:Ke(Q().regex(Tn)).max(qe),unconfirmed:Ke(vo).max(qe).optional()}),Io=Ge({id:Q().min(1).max(200),orgId:Q().min(1).max(200),templateId:Q().min(1).max(200),fingerprint:Q().regex(/^[0-9a-f]{64}$/),savedAt:Q(),objects:Ke(To),namesGiven:Q().max(6e4).regex(/^[A-Za-z0-9+/]*={0,2}$/).optional()});function Dt(s,e,t){let n=s.map(o=>[o.fieldPattern,o.ruleType,o.config??null]),r=t?.trim();return Br("sha256").update(JSON.stringify(r?{rules:n,objects:e,where:r}:{rules:n,objects:e})).digest("hex")}function Oo(s){return s==null||s===""?null:typeof s=="string"?s.trim():typeof s=="number"||typeof s=="boolean"?String(s):JSON.stringify(s)}function In(s,e){let t=[...e].sort().map(n=>[n,Oo(s[n])]);return Br("sha256").update(JSON.stringify(t)).digest("hex")}function wt(s){return s.reduce((e,t)=>e+t.refused.length,0)}var st=class{constructor(e){this.configStore=e}configStore;load(e,t,n){let r=Io.safeParse(this.configStore.get(this.key(e,t)));if(!r.success)return;let o=r.data;if(!(o.orgId!==e||o.templateId!==t||o.fingerprint!==n))return o}save(e){if(wt(e.objects)>qe)throw new Error(`A checkpoint keeps at most ${qe} refused records; this run left ${wt(e.objects)}.`);this.configStore.set(this.key(e.orgId,e.templateId),e,Ao)}clear(e,t){this.configStore.delete(this.key(e,t))}key(e,t){return`${wo}${e}:${t}`}};async function So(s){let{open:e,rename:t,rm:n}=await import("node:fs/promises"),{randomBytes:r}=await import("node:crypto"),o=`${s}.${r(4).toString("hex")}.partial`,a=await e(o,"w"),i=!1;return{write:async d=>{let c=Buffer.from(d,"utf8");for(let p=0;p<c.length;){let{bytesWritten:u}=await a.write(c,p,c.length-p,null);p+=u}},close:async()=>{i=!0,await a.close(),await t(o,s)},abort:async()=>{i||await a.close().catch(()=>{}),i=!0,await n(o,{force:!0})}}}function No(s){let e=[];return{write:async t=>{e.push(t)},close:async()=>{await s(new TextEncoder().encode(e.join("")))},abort:async()=>{e.length=0}}}var xt=class s{host;constructor(e){this.host=e??null}async defaultHost(){let e=await import("vscode");return{showSaveDialog:t=>e.window.showSaveDialog(t),writeFile:(t,n)=>e.workspace.fs.writeFile(t,n),fileUri:t=>e.Uri.file(t),openFile:async t=>t.scheme==="file"?So(t.fsPath):No(n=>e.workspace.fs.writeFile(t,n))}}static filtersOf(e,t){let n=e.includes(".")?e.split(".").pop():void 0;return t?.length?{[t.join("/").toUpperCase()]:t}:n?{[n.toUpperCase()]:[n]}:void 0}static ask(e,t,n){let r=s.filtersOf(t,n);return e.showSaveDialog({saveLabel:"Save",defaultUri:e.fileUri(t),...r?{filters:r}:{}})}async save(e,t,n){let r=this.host??await this.defaultHost();try{let o=await s.ask(r,e,n);return o?(await r.writeFile(o,new TextEncoder().encode(t)),{status:"saved",path:o.fsPath}):{status:"cancelled"}}catch(o){return{status:"error",message:o instanceof Error?o.message:String(o)}}}async saveStream(e,t,n){let r=this.host??await this.defaultHost(),o;try{let a=await s.ask(r,e,n);if(!a)return{status:"cancelled"};let i=await r.openFile(a);o=i;let d=await t(c=>i.write(c));return await i.close(),o=void 0,{status:"saved",path:a.fsPath,result:d}}catch(a){return await o?.abort().catch(()=>{}),{status:"error",message:a instanceof Error?a.message:String(a)}}}};function Bt(s,e,t,n,r=0){s?.register(e,t,n,r);let o=!1,a=i=>{o||(o=!0,i())};return{progress:(i,d,c,p)=>{o||s?.updateProgress(e,i,d,c,p)},complete:()=>a(()=>s?.complete(e)),partial:()=>a(()=>s?.partial(e)),fail:i=>a(()=>s?.fail(e,i)),cancel:()=>a(()=>s?.cancel(e))}}var ve={orgUnknown:"ORG_NOT_FOUND",production:"PIPELINE_WRITE_REFUSED",needsApproval:"PIPELINE_WRITE_NEEDS_APPROVAL",retries:"PIPELINE_WRITE_NO_RETRIES",filterNeedsObject:"MASKING_FILTER_NEEDS_OBJECT",invalid:"INVALID_PAYLOAD",templateMissing:"TEMPLATE_NOT_FOUND",fieldsUnseen:"MASKING_FIELDS_UNSEEN",masksNothing:"MASKING_MASKS_NOTHING"};function Fe(s,e){return Object.assign(new Error(e),{code:s})}function Fr(s,e,t){let n=Gn(s);if(n==="refused")return Fe(ve.production,`${t} is a production org, or one SandForge cannot tell is not: a pipeline never masks one, whatever an Approval step answers. Mask a sandbox, a scratch org or a Developer Edition org. Nothing was masked.`);if(n==="needsApproval"&&!e.approved)return Fe(ve.needsApproval,`${t} is a sandbox marked Staging, which a pipeline masks only once an Approval step before the masking has approved the run, and none did: put an Approval step before it. Nothing was masked.`)}function _r(s,e){if(s.retries!==void 0&&s.retries>0)return{refusal:Fe(ve.retries,"A masking step is never tried again: a second try masks again what the first one masked \u2014 an address it hashed is hashed once more, and no longer gives the same pseudonym on Contact and on Lead. Set its retries to 0. Nothing was masked.")};let t=s.where?.trim();if(t&&s.object===void 0)return{refusal:Fe(ve.filterNeedsObject,"A masking condition filters the rows of one object: name the object it holds, or remove the condition. Nothing was masked.")};let n=Et.safeParse({orgId:s.orgId,templateId:s.templateId,...s.object!==void 0?{objects:[s.object]}:{},...t?{where:t}:{},snapshot:!0});if(!n.success){let r=n.error.issues[0];return{refusal:Fe(ve.invalid,`The masking step is not one the DataOps page would run (${r.path.join(".")}: ${r.message}). Nothing was masked.`)}}return e(n.data.templateId)?{asked:n.data}:{refusal:Fe(ve.templateMissing,`No masking template is shipped or saved under ${n.data.templateId}: it was deleted on the DataOps page. Choose another. Nothing was masked.`)}}function ao(s){let e=s.fields;return{name:s.name,label:s.label,labelPlural:s.labelPlural??"",keyPrefix:s.keyPrefix??null,custom:s.custom??!1,createable:s.createable,updateable:s.updateable,deletable:s.deletable,queryable:s.queryable,fields:e.map(t=>({name:t.name,label:t.label,type:t.type,length:t.length??0,nillable:t.nillable??!1,createable:t.createable,updateable:t.updateable,externalId:t.externalId??!1,referenceTo:t.referenceTo??[],relationshipName:t.relationshipName??null,picklistValues:t.picklistValues??[],defaultValue:t.defaultValue??null,calculated:t.calculated??!1,autoNumber:t.autoNumber??!1,unique:t.unique??!1,permissionable:t.permissionable??!0})),recordTypeInfos:s.recordTypeInfos??[],childRelationships:s.childRelationships??[]}}var $o=new Set(["backup:execute","backup:list","backup:objects","backup:export","backup:delete","dataops:rollback","dataops:anonymize","dataops:anonymization-templates","dataops:quality-scan","dataops:anonymization-template:save","dataops:anonymization-template:delete","dataops:anonymize:coverage","dataops:anonymize:preview","dataops:automation","precheck:pii-scan"]),Co=6e4,jo=10,Mo=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function Eo(s,e){return s.slice(0,15)===e.slice(0,15)}var Wr="ORG_REPLACED_SINCE_BACKUP",zo="Backup was cancelled before it finished. Nothing was saved \u2014 run it again to take a complete snapshot.",it=class extends Error{constructor(){super(zo),this.name="BackupCancelledError"}},Rt=class extends Error{constructor(e){super(`The backup could not be written to disk: ${R(e)}`),this.name="BackupWriteError"}},dt=class extends Error{constructor(t,n){super(t);this.retryable=n;this.name="BackupNotWholeError"}retryable},jn="IsDeleted = false",Lo="SystemModstamp",io=5e4,Do=100,At=_n;function xo(s){return typeof s!="number"||!Number.isFinite(s)?io:Math.min(At,Math.max(Do,Math.floor(s)))}var at=200,Bo=1440*6e4,Fo=1440*6e4,Ur="backupRetention:since",_o="BACKUP_BUSY";function Wo(s,e){return e===0?"success":s===0?"failure":"partial"}function On(s){return Jt(s)}function Hr(s,e,t){s.length>=jo||s.push({objectApiName:e,message:t?.[0]?.message??"Unknown DML error"})}function Ft(s,e,t=!1){let n=(e?.rules??[]).map(o=>o.fieldPattern.split(".")[0]).filter((o,a,i)=>i.findIndex(d=>Sn(d,o))===a);if(s.objects)return s.objects.map(o=>n.find(a=>Sn(a,o))??(Sn(o,W)?W:o));if(!e)return[];let r=[...n];return t&&vt(s,e,W)&&r.push(W),r}function Sn(s,e){return s.toLowerCase()===e.toLowerCase()}var Uo=`${ot} = true`;function vt(s,e,t){return s.objects===void 0&&t.toLowerCase()===W.toLowerCase()&&_t(e,W).length===0&&An(e.rules).length>0}function Nn(s,e,t){return vt(s,e,t)?Uo:zn(s)}async function Pn(s,e){try{return(await s.describe(W)).fields.some(t=>t.name===ot)}catch(t){return e(`[WARN] dataops: whether the org has person accounts was not read: ${R(t)}`),!1}}function _t(s,e){let t=`${e.toLowerCase()}.`;return s.rules.filter(n=>n.fieldPattern.toLowerCase().startsWith(t)||n.fieldPattern==="*")}function Mn(s,e){return e.toLowerCase()===W.toLowerCase()?An(s.rules):[]}function Kr(s){let e=new Map;return{describe:t=>{let n=e.get(t)??s.describe(t);return e.set(t,n),n}}}async function Gr(s,e){return new sn(async n=>ao(await s.describe(n))).deniedOf(e.map(({objectApiName:n,rules:r})=>({objectApiName:n,operation:"update",fieldNames:r.map(o=>o.fieldPattern.includes(".")?o.fieldPattern.split(".")[1]:o.fieldPattern).filter(o=>o!=="*")})))}function qr(s,e){return _t(s,e).length>0||Mn(s,e).length>0}function $n(s){return{objectApiName:s.objectApiName,recordCount:s.recordCount,truncated:s.truncated===!0,...s.orgCount!==void 0?{orgCount:s.orgCount}:{},...s.stoppedAt?{stoppedAt:s.stoppedAt}:{},...s.notKept&&s.notKept.length>0?{notKept:[...s.notKept]}:{}}}function Cn(s,e){return s.flatMap(t=>{let n=e?.get(t.objectApiName);if(n!==void 0&&n<t.recordCount)return[`${t.objectApiName} ${n} of the ${t.recordCount} it listed (not found on disk)`];if(!t.truncated)return[];if(t.stoppedAt==="not_reached")return[`${t.objectApiName} none (the backup stopped before it)`];let r=t.orgCount!==void 0?` of ${t.orgCount}`:"",o=t.stoppedAt==="cap"?" (stopped at the cap)":t.stoppedAt==="failure"?" (the read failed)":"";return[`${t.objectApiName} ${t.recordCount}${r}${o}`]}).join(", ")}var Xe=200,Ho=95,Wt=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Ko="NOTHING_TO_RESUME",Xr="TEMPLATE_NOT_FOUND";function Qr(s){return new Error(`Template "${s}" not found.`)}function Go(s){let e=s.Id;if(typeof e!="string"||!Wt.test(e))return[];let t=Object.keys(s).filter(n=>n!=="Id");return t.length>0?[{id:e,fields:t,digest:In(s,t)}]:[]}var qo="COUNT_FAILED",Vr="SNAPSHOT_NOT_TAKEN",Xo=new Set(["QUERY_TIMEOUT","OPERATION_TOO_LARGE"]),Qo=/^([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+):/;function Jr(s){if(typeof s=="object"&&s!==null){let{errorCode:e,code:t}=s;if(typeof e=="string"&&e!=="")return e;if(typeof t=="string"&&t!=="")return t}return Qo.exec(R(s))?.[1]??"UNKNOWN"}var Yr=5;function Zr(s){return s==null?null:typeof s=="string"||typeof s=="number"||typeof s=="boolean"?s:JSON.stringify(s)}function co(s){return s.done?0:Math.max(0,s.total-s.masked-s.nothingToMask-s.refused-s.unanswered)}function Ut(s){return s.refused+s.unanswered+co(s)}function Tt(s){return s.reduce((e,t)=>({recordsProcessed:e.recordsProcessed+t.masked+t.nothingToMask,recordsFailed:e.recordsFailed+t.refused,recordsNotMasked:e.recordsNotMasked+Ut(t)}),{recordsProcessed:0,recordsFailed:0,recordsNotMasked:0})}function Vo(s,e){let{recordsProcessed:t,recordsFailed:n,recordsNotMasked:r}=Tt(s);return r===0?"success":t>0||e&&n===0?"partial":"failure"}function Jo(s,e,t){if(!t||e==="success")return{outcome:e};let{recordsProcessed:n,recordsFailed:r}=Tt(s);return n+r>0?{outcome:"cancelled"}:{outcome:"stopped",code:rn}}function eo(s){return s.filter(e=>Ut(e)>0).map(e=>`${e.objectApiName} ${Ut(e)}`).join(", ")}function to(s){return s.map(e=>({objectApiName:e.objectApiName,total:e.total,processed:e.masked+e.nothingToMask,failed:e.refused,notMasked:Ut(e)}))}function no(s){return s.filter(e=>e.total>0||e.masked+e.refused>0).map(e=>{let t=co(e);return{...Ct(e.objectApiName),updated:e.masked,failed:e.refused+e.unanswered,...e.unanswered>0?{mayHaveBeenWritten:e.unanswered}:{},...t>0?{notSent:t}:{}}})}async function ro(s,e,t,n,r,o){return Yn(s,`SELECT ${t} FROM ${e}${En(o,r)} ORDER BY Id LIMIT ${n}`,n)}function En(s,e){let t=s?.trim(),n=[...t?[`(${Yt(t)})`]:[],...e===void 0?[]:[`Id > '${e}'`]];return n.length===0?"":` WHERE ${n.join(" AND ")}`}function zn(s){let e=s.where?.trim();return e||void 0}function Yo(s){let e=s?.trim();return e?`(${Yt(e)}) AND ${jn}`:jn}function Zo(s){let e=new Map;for(let[t,n]of s){if(n.length===0)throw new Error(`No field of ${t} was named for the snapshot to read.`);e.set(t,n.map(r=>Nt(r)).join(", "))}return e}function oo(s,e,t){let n=e===void 0?"more records":`${e} records`;return new dt(`${s} holds ${n}, past the ${t} a snapshot reads of one object: no snapshot was kept, as one holding part of the object would be taken for all of it.`,!1)}function po(s,e){return`The org stopped answering the read of ${s} after ${e} record(s), before it said the read was done: no snapshot was kept.`}async function es(s,e,t,n){let r={headers:{},maxFetch:1e4,autoFetch:!1,scanAll:t,responseTarget:"QueryResult"},o=await s.query(e,r),a=[...o.records];for(;!o.done;){if(!o.nextRecordsUrl)throw new dt(po(n,a.length),!0);o=await s.queryMore(o.nextRecordsUrl,r),a.push(...o.records)}return a}function ts(s,e,t){let n=s[s.length-1]?.Id;if(typeof n!="string"||!Wt.test(n)||n===e)throw new Error(`The org answered a page of ${t} that does not end past the page before it: masking stopped there rather than write the same rows again.`);return n}var so=class{constructor(e,t){this.deps=e;this.saveDialog=t??new xt}deps;activeOrgOperations=new Set;writing=new Rr;dmlTracker=new zt;backupRecords;syncRuns;expiryListener;sweeping;liveTracker;backupsWriting=new Set;maskingKey=Po(32).toString("hex");saveDialog;get savedTemplates(){return new Lt(this.deps.configStore)}findTemplate(e){return yt.find(t=>t.id===e)??this.savedTemplates.load(e)}ruleConfig(e){let t={...e.config};return e.ruleType==="hash"&&(t.hashSalt=this.maskingKey),t}maskingRules(e,t){return t.map(n=>({objectApiName:e,fieldApiName:n.fieldPattern.includes(".")?n.fieldPattern.split(".")[1]:n.fieldPattern,method:n.ruleType,config:this.ruleConfig(n)}))}refuseUnknownTemplate(e,t,n){M(this.deps,e,"dataops:error",t,Qr(n),{code:Xr})}setLiveOperationTracker(e){this.liveTracker=e}setSyncRuns(e){this.syncRuns=e}targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;muteLeases={};setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}setMuteOffered(e){this.muteOffered=e}muteOffered=!0;setOnCommandLine(e){this.onCommandLine=e}onCommandLine=!1;countGaveUp(e,t){if(!Xo.has(Jr(e)))return e;let n=this.onCommandLine?"narrow --where to an indexed field, such as a range of CreatedDate, and mask the rest in other runs":`mask them in slices from the command line, each a run of its own (sandforge dataops anonymize --object ${t} --where) on an indexed field, such as a range of CreatedDate`;return new Error(`${R(e)} The org gave up counting the ${t} records the run would mask: ${n}. Nothing was masked.`)}duplicatesSettleMs=Tr;setDuplicatesSettle(e){this.duplicatesSettleMs=e}duplicatesWatchOf(e,t){return Ir({query:async n=>e.query(n),serverTime:async()=>(await e.soap.getServerTimestamp()).timestamp},t,{settleMs:this.duplicatesSettleMs})}ownReader(){return this.reader??=import("./chunk-7YDNUBO5.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(n=>Re(n,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}orgNameOf(e){return nt(this.deps.orgManager.getOrg(e),e)}readAct(e,t,n,r,o,a){let i=this.targetAutomation;return Pr({act:n,target:this.orgNameOf(t),objects:r,org:Nr(e,d=>new Or(Co).withTimeout("dataops automation",()=>i.read(t,d)),Jt(this.deps.orgManager.getOrg(t))==="production"),accord:o,mayMute:this.muteOffered,muteLeases:this.muteLeases,...a?{voice:a}:{}})}async releaseMute(e,t){if(!e)return;let n=await e.release();for(let r of Sr(n,this.orgNameOf(t)))this.deps.log(`[INFO] ${r}`);return n}async handleAutomation(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(sr,e,"dataops:error",this.deps);if(t)try{let n=await Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager),r=await this.readAct(n,t.orgId,t.act,t.objects,t,kt(t)),o=se(this.deps,e,"dataops:automation:response",{...r.answer});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} refusals=${r.answer.refusals.length}`)}catch(n){M(this.deps,"dataops:automation","dataops:error",e,n)}}setExpiryListener(e){this.expiryListener=e}setBackupRecordStore(e){this.backupRecords=e,this.sweeping=this.sweepBackupFiles()}swept(){return this.sweeping??Promise.resolve()}async sweepBackupFiles(e=Date.now()){await this.expireBackups(e);let t=this.backupRecords;if(t)try{let n=new Set(this.backupsWriting);for(let o of this.deps.configStore.getKeysByPrefix("backup:"))n.add(o.slice(7).split(":")[0]);let r=await t.sweep(n,Bo,e);r.length>0&&this.deps.log(`[INFO] Removed ${r.length} backup file(s) whose backup never saved its metadata: `+r.join(", "))}catch(n){this.deps.log("[WARN] the files of backups that never saved their metadata were not removed: "+R(n))}}isWritingTo(e){return this.writing.has(e)}async handle(e){if(!$o.has(e.type))return!1;switch(e.type){case"backup:execute":return await this.handleBackup(e),!0;case"backup:list":return this.handleBackupList(e),!0;case"backup:objects":return await this.handleBackupObjects(e),!0;case"backup:export":return await this.handleBackupExport(e),!0;case"backup:delete":return await this.handleBackupDelete(e),!0;case"dataops:rollback":return await this.writing.during(fn(e,"orgId"),()=>this.handleRollback(e)),!0;case"dataops:anonymize":return await this.writing.during(fn(e,"orgId"),()=>this.handleAnonymize(e)),!0;case"dataops:anonymization-templates":return this.handleAnonymizationTemplates(e),!0;case"dataops:quality-scan":return await this.handleQualityScan(e),!0;case"dataops:anonymization-template:save":return this.handleTemplateSave(e),!0;case"dataops:anonymization-template:delete":return this.handleTemplateDelete(e),!0;case"dataops:anonymize:coverage":return await this.handleAnonymizeCoverage(e),!0;case"dataops:anonymize:preview":return await this.handleAnonymizePreview(e),!0;case"dataops:automation":return await this.handleAutomation(e),!0;case"precheck:pii-scan":return await this.handlePIIScan(e),!0;default:return!1}}async selectAllFields(e,t,n){let r=await e.describe(t),o=r.fields.filter(d=>d.type===hr).map(d=>d.name),a=o.length>0&&n&&!await n()?o:[];return{select:r.fields.filter(d=>!a.includes(d.name)).map(d=>d.name).join(", "),notKept:a}}async maskedFields(e,t,n,r=[]){let o=(await e.describe(t)).fields,a=new Map(o.map(l=>[l.name.toLowerCase(),l.name])),i=[],d=[];for(let l of n){let f=a.get(l.fieldApiName.toLowerCase());f!==void 0?i.push({...l,fieldApiName:f}):l.fieldApiName!=="*"&&!d.includes(l.fieldApiName)&&d.push(l.fieldApiName)}let c=$r({objectApiName:t,fields:o,kept:i,derived:r,detector:this.deps.infraServices?.piiDetector??new wr});if(c&&c.unseen.length>0){let l=await e.describe(ft).then(f=>f.fields,()=>{});for(let f of Cr(c.unseen,l))d.includes(f)||d.push(f)}let p=c?[...i,...c.rules]:i,u=p.map(l=>l.fieldApiName).filter((l,f,h)=>l!=="Id"&&h.indexOf(l)===f),b=c&&u.length>0&&!u.includes(ot);return{rules:p,select:["Id",...u,...b?[ot]:[]].join(", "),missing:d,rulesOf:c?l=>Mr(t,l,p,c.personOnly):()=>p}}async countRows(e,t,n,r){let a=(await e.query(`SELECT COUNT() FROM ${t}${En(r,n)}`)).totalSize;if(typeof a!="number"||!Number.isInteger(a)||a<0)throw new Error(`The org did not say how many records ${t} holds.`);return a}async organizationIdOf(e){try{let n=(await gt(e,"SELECT Id FROM Organization"))[0]?.Id;return typeof n=="string"&&Mo.test(n)?n:void 0}catch(t){this.deps.log(`[WARN] dataops: the org did not say which org it is: ${R(t)}`);return}}async handleBackup(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(Zn,e,"dataops:error",this.deps);if(!t)return;let n=e.id,r=await this.takeBackup(n,t,e.type);if("error"in r){M(this.deps,"backup:execute","dataops:error",e,r.error),this.endBackupNotTaken(n,r);return}let o=se(this.deps,e,"dataops:backup:response",{operationId:n,status:"completed",objects:r.objects.map($n),totalRecords:r.totalRecords,...r.partial?{partial:!0}:{},timestamp:r.timestamp});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}async backupForPipeline(e,t){let n=e.fields?Zo(e.fields):void 0,r=await this.takeBackup(e.operationId,{orgId:e.orgId,objects:e.objects,...n?{fields:n}:{},...e.scanAll?{scanAll:new Set(e.scanAll)}:{},...e.origin?{origin:e.origin}:{},...e.failWhenTruncated===!0?{failWhenTruncated:!0}:{},...e.onConnection?{onConnection:e.onConnection}:{}},e.origin==="checkpoint"?"checkpoint:take":"pipeline:execute",t);if("error"in r){let o=R(r.error);throw this.endBackupNotTaken(e.operationId,r),r.cancelled?new cn(o):r.error instanceof Error?r.error:new Error(o)}return r}endBackupNotTaken(e,t){if(t.cancelled){xe(this.deps,e,{aborted:!0});return}de(this.deps,e,R(t.error),t.retryable,{context:t.context})}async takeBackup(e,t,n,r){let o={module:"dataops",operation:n},a=`backup:${t.orgId}`;if(this.activeOrgOperations.has(a)){let m=`A backup or rollback operation is already running for org ${t.orgId}. Please wait for it to complete.`;return this.deps.log(`[WARN] ${m}`),{error:new Error(m),retryable:!1,context:o}}this.activeOrgOperations.add(a);let i=()=>{},d,c=new AbortController,p=()=>c.abort();r?.aborted&&c.abort(),r?.addEventListener("abort",p,{once:!0});let u=this.backupCap(),b=this.backupWriter(e);this.backupsWriting.add(e);let l=[],f,h,w,T=(m,$,O,B)=>{Mt(this.deps,e,m,$,O,B),w?.progress(m,$,O,B)};try{if(this.dmlTracker.isDuplicate(e))return this.deps.log(`[WARN] Duplicate backup operation detected: ${e}`),{error:new Error(`Duplicate operation: ${e}`),retryable:!1,context:o};this.dmlTracker.register(e,"backup","insert",t.objects.length);let m=await Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager);h=m,t.onConnection?.(m);let $=br(async E=>(await m.query(E)).records),O=this.deps.orgManager.getOrg(t.orgId),B=wn(O?.orgType==="Sandbox"||O?.orgType==="Scratch"),Z=yn(B).defaultQueryLimit,K=`Backup ${t.objects.length} object(s)`;jt(this.deps,e,"dataops",K),this.deps.infraServices?.backgroundRegistry?.register(e,"dataops",K,new Promise((E,S)=>{i=C=>{C===void 0?E():S(C instanceof Error?C:new Error(String(C)))}}),c),w=Bt(this.liveTracker,e,"dataops",K,t.objects.length);for(let E of t.objects){if(c.signal.aborted)throw new it;let S=De(E);o.objectName=S;let C={objectApiName:E,recordCount:0,truncated:!1};f=C,await this.readIntoBackup(m,S,C,b,{pageSize:Z,cap:u,select:t.fields?.get(S),where:t.wheres?.get(S),scanAll:t.scanAll?.has(S)===!0,...t.origin==="checkpoint"?{stamp:Lo}:{},whole:t.failWhenTruncated===!0,viewsEncrypted:$},c.signal,()=>{let q=Math.max(1,Math.min(C.orgCount??u,u));T(Math.round((l.length+C.recordCount/q)/t.objects.length*100),l.length,t.objects.length,`Reading ${E} (${C.recordCount} of ${q} records)`)}),f=void 0,l.push(C),C.stoppedAt==="cap"&&this.deps.log(`[WARN] backup of ${S} stopped at the cap of ${u} record(s): the object holds ${C.orgCount??"more"}.`),T(Math.round(l.length/t.objects.length*100),l.length,t.objects.length,`Exported ${E} (${C.recordCount} records)`)}let F=await this.organizationIdOf(m);if(c.signal.aborted)throw new it;let P=this.saveBackupMeta({operationId:e,orgId:t.orgId,organizationId:F,cap:u,...t.origin?{origin:t.origin}:{}},l,b,!1);return this.pruneAfterBackup(t.orgId),xe(this.deps,e,{objects:l.map(E=>({objectApiName:E.objectApiName,recordCount:E.recordCount})),totalRecords:P.totalRecords,...P.partial?{status:"partial"}:{}}),this.dmlTracker.markCompleted(e),P.partial?w?.partial():w?.complete(),{operationId:e,objects:l,totalRecords:P.totalRecords,partial:P.partial,timestamp:P.timestamp}}catch(m){this.dmlTracker.markFailed(e);let $=m instanceof it,O=$||m instanceof Rt||t.failWhenTruncated===!0?void 0:await this.keepFailedBackup({operationId:e,orgId:t.orgId,cap:u,...t.origin?{origin:t.origin}:{}},h,{taken:l,reading:f,planned:t.objects},b);O===void 0&&await b.discard().catch(K=>{this.deps.log(`[WARN] backup ${e}: what it wrote before it stopped was not removed: `+R(K))});let B=O===void 0?m:new Error(`${R(m)} \u2014 the backup keeps the ${O.totalRecords} record(s) read before it stopped, listed as partial: ${Cn(O.objects)}.`);d=B,$&&this.deps.infraServices?.backgroundRegistry?.abort(e),$?w?.cancel():w?.fail(R(B));let Z=!(m instanceof dt)||m.retryable;return{error:B,retryable:Z,context:o,cancelled:$}}finally{r?.removeEventListener("abort",p),i(d),this.activeOrgOperations.delete(a),this.backupsWriting.delete(e)}}backupCap(){return xo(this.deps.services?.getSandforgeSetting?.("backup.maxRecordsPerObject",io))}snapshotCapWay(e){let t=this.backupCap(),n=e.filter(r=>r.tally.total>At).map(r=>r.tally.objectApiName);if(n.length>0||t>=At){let r=n.length>0?n.join(", "):"the object";return this.onCommandLine?`No snapshot holds more than ${At} records of one object, and nothing raises that: mask ${r} in slices, each a run of its own with --object and a --where that selects fewer (a range of CreatedDate, say), each taking its own snapshot.`:`No snapshot holds more than 1,000,000 records of one object, and nothing raises that: mask ${r} in slices from the command line, each a run of its own (sandforge dataops anonymize --object and --where), each taking its own snapshot.`}return this.onCommandLine?`Give --max-records up to ${At} (this run held ${t}), or narrow the run with --object and --where.`:`Raise sandforge.backup.maxRecordsPerObject in Settings (this run held ${t}, 1,000,000 at most), then apply again.`}backupWriter(e){let t=this.backupRecords;if(t){let r=new Set;return{begin:async o=>{r.add(o),await t.begin(e,o).catch(a=>{throw new Rt(a)})},append:async(o,a)=>{await t.append(e,o,a).catch(i=>{throw new Rt(i)})},keep:()=>{},discard:async()=>{for(let o of r)await t.delete(e,o)}}}let n=new Map;return{begin:async r=>{n.set(r,[])},append:async(r,o)=>{n.get(r)?.push(...o)},keep:()=>{for(let[r,o]of n)this.deps.configStore.set(`backup:${e}:${r}`,o,"backups")},discard:async()=>{n.clear()}}}async readIntoBackup(e,t,n,r,o,a,i){let d=o.scanAll===!0,c={headers:{"Sforce-Query-Options":`batchSize=${o.pageSize}`},maxFetch:1e4,autoFetch:!1,scanAll:d,responseTarget:"QueryResult"},p=o.select;if(p===void 0){let T=await this.selectAllFields(e,t,o.viewsEncrypted);p=T.select,T.notKept.length>0&&(n.notKept=T.notKept)}let u=d?Yo(o.where):o.where,b=`SELECT ${p} FROM ${t}${En(u,void 0)}`,l=o.stamp??Xn(b)?.stamp,f=Qn(b,l===void 0?void 0:["Id",l]),h=d||o.whole===!0?T=>es(e,T,d,t):T=>gt(e,T),w=await e.query(f?.first??b,c);if(Be(e.limitInfo,`dataops:backup query ${t}`),typeof w.totalSize=="number"&&Number.isInteger(w.totalSize)&&(n.orgCount=w.totalSize),o.whole===!0&&n.orgCount!==void 0&&n.orgCount>o.cap)throw oo(t,n.orgCount,o.cap);for(await r.begin(n.objectApiName);;){let T=o.cap-n.recordCount,m=w.records.length>T,$=m?w.records.slice(0,T):w.records,O=$;f&&l!==void 0?O=await Jn($,f,h,{stamp:l,...d?{idsWhere:jn}:{}}):f&&await Vn($,f,h);let B=w.done?void 0:w.nextRecordsUrl;if(o.whole===!0&&!w.done&&B===void 0)throw new dt(po(t,n.recordCount+O.length),!0);let Z=m||B!==void 0&&n.recordCount+O.length>=o.cap;if(Z&&o.whole===!0)throw oo(t,n.orgCount,o.cap);if(await r.append(n.objectApiName,O),n.recordCount+=O.length,Z){n.truncated=!0,n.stoppedAt="cap";return}if(B===void 0)return;if(i(),a.aborted)throw new it;w=await e.queryMore(B,c),Be(e.limitInfo,`dataops:backup query ${t}`)}}saveBackupMeta(e,t,n,r){let o={operationId:e.operationId,orgId:e.orgId,...e.organizationId!==void 0?{organizationId:e.organizationId}:{},...e.origin!==void 0?{origin:e.origin}:{},objects:t.map($n),partial:t.some(a=>a.truncated),...r?{status:"failed"}:{},cap:e.cap,timestamp:new Date().toISOString(),totalRecords:t.reduce((a,i)=>a+i.recordCount,0)};return this.deps.configStore.set(`backup:${e.operationId}`,o,"backups"),n.keep(),o}async keepFailedBackup(e,t,n,r){let{taken:o,reading:a}=n,i=a?[...o,{...a,truncated:!0,stoppedAt:"failure"}]:[...o],d=new Set(i.map(u=>u.objectApiName.toLowerCase())),c=n.planned.filter(u=>!d.has(u.toLowerCase())).map(u=>({objectApiName:u,recordCount:0,truncated:!0,stoppedAt:"not_reached"})),p=[...i,...c];if(!p.every(u=>u.recordCount===0))try{let u=t?await this.organizationIdOf(t):void 0,b=this.saveBackupMeta({...e,organizationId:u},p,r,!0);return this.pruneAfterBackup(e.orgId),{...b,objects:p}}catch(u){this.deps.log(`[WARN] backup ${e.operationId}: the rows read before it failed were not kept: `+R(u));try{this.deps.configStore.delete(`backup:${e.operationId}`)}catch{}return}}async expireBackups(e){let t=vr(this.deps.services);if(t<=0)return;let n=e-t*Fo;try{let r=this.retentionSince(e);for(let o of this.backupMetaKeys()){let a=this.deps.configStore.get(o),i=Date.parse(a?.timestamp??"");if(!Number.isFinite(i)||i>=n||i<r||a?.origin==="checkpoint"||a?.orgId!==void 0&&this.backupBusy(a.orgId))continue;await this.removeBackup(o);let d=a?.origin==="sync"?` \u2014 the values the Sync run ${a.runId??"(unknown)"} wrote over, which removing that run no longer puts back`:"";this.deps.log(`[INFO] Removed backup ${o}: taken more than ${t} day(s) ago${d}`),this.expiryListener?.({operationId:o.slice(7),days:t,...a?.timestamp!==void 0?{takenAt:a.timestamp}:{},...a?.origin==="sync"?{syncRunId:a.runId??""}:{}})}}catch(r){this.deps.log(`[WARN] the backups past their age were not removed: ${R(r)}`)}}retentionSince(e){let t=Date.parse(this.deps.configStore.get(Ur)??"");return Number.isFinite(t)?t:(this.deps.configStore.set(Ur,new Date(e).toISOString()),e)}backupMetaKeys(){return this.deps.configStore.getKeysByPrefix("backup:").filter(e=>!e.slice(7).includes(":"))}backupBusy(e){return this.activeOrgOperations.has(`backup:${e}`)}async removeBackup(e){let n=this.deps.configStore.get(e)?.objects??[];for(let o of n)this.deps.configStore.delete(`${e}:${o.objectApiName}`);this.deps.configStore.delete(e);let r=e.slice(7);for(let o of n)await this.backupRecords?.delete(r,o.objectApiName)}async handleBackupDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(rr,e,"dataops:error",this.deps);if(!t)return;if(this.backupBusy(t.orgId)){M(this.deps,"backup:delete","dataops:error",e,new Error(`A backup or rollback operation is already running for org ${t.orgId}. Delete its backups once it has ended.`),{code:_o});return}let n=t.operationIds?new Set(t.operationIds):void 0,r=[];try{for(let a of this.backupMetaKeys()){let i=this.deps.configStore.get(a);if(i?.orgId!==t.orgId)continue;let d=i.operationId??a.slice(7);n&&!n.has(d)||(await this.removeBackup(a),r.push(d))}}catch(a){M(this.deps,"backup:delete","dataops:error",e,a);return}this.deps.log(`[INFO] Deleted ${r.length} backup(s) of org ${t.orgId}`);let o=se(this.deps,e,"backup:delete:result",{orgId:t.orgId,deleted:r});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} deleted=${r.length}`)}pruneAfterBackup(e){try{this.pruneBackups(e)}catch(t){this.deps.log(`[WARN] backup retention failed after the snapshot was written: ${R(t)}`)}this.sweepBackupFiles()}handleBackupList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(er,e,"dataops:error",this.deps);if(!t)return;let n=[];for(let o of this.deps.configStore.getKeysByPrefix("backup:")){if(o.slice(7).includes(":"))continue;let a=this.deps.configStore.get(o);!a||a.orgId!==t.orgId||n.push({operationId:a.operationId??o.slice(7),orgId:a.orgId,timestamp:a.timestamp??"",totalRecords:a.totalRecords??0,totalSize:0,status:a.status==="failed"?"failed":"completed",objectResults:(a.objects??[]).map($n),...a.partial?{partial:!0}:{},...a.origin==="sync"?{origin:"sync"}:{}})}n.sort((o,a)=>a.timestamp.localeCompare(o.timestamp));let r=se(this.deps,e,"backup:list:result",{backups:n});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} count=${n.length}`)}async handleBackupExport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(nr,e,"dataops:error",this.deps);if(!t)return;let n=`backup:${t.operationId}`,r=this.deps.configStore.get(n);if(!r||r.orgId!==t.orgId){M(this.deps,"backup:export","dataops:error",e,new Error(`Backup not found: ${t.operationId}`),{code:"BACKUP_NOT_FOUND"});return}let o=await this.saveDialog.saveStream(`sandforge-backup-${t.operationId}.json`,i=>this.writeBackupDocument(t,r,i),["json"]);if(o.status==="error"){M(this.deps,"backup:export","dataops:error",e,new Error(o.message));return}let a=se(this.deps,e,"backup:export:result",o.status==="saved"?{operationId:t.operationId,status:"saved",path:o.path,objects:o.result}:{operationId:t.operationId,status:"cancelled"});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id} ${o.status}`)}async writeBackupDocument(e,t,n){let{operationId:r}=e,a=[["sandforgeBackupVersion",1],["operationId",r],["orgId",e.orgId],["timestamp",t.timestamp??""],["totalRecords",t.totalRecords??0]].map(([d,c])=>` "${d}": ${JSON.stringify(c)},
8
+ `);await n(`{
9
+ ${a.join("")} "objects": {`);let i=[];for(let{objectApiName:d}of t.objects??[]){if(i.some(p=>p.objectApiName===d))continue;await n(`${i.length>0?",":""}
10
+ ${JSON.stringify(d)}: [`);let c=0;for await(let p of await this.backupBatches(r,d))p.length!==0&&(await n(p.map((u,b)=>`${c+b>0?",":""}
11
+ ${JSON.stringify(u)}`).join("")),c+=p.length);await n(c>0?`
12
+ ]`:"]"),i.push({objectApiName:d,records:c})}return await n(`${i.length>0?`
13
+ `:""}}
14
+ }
15
+ `),i}async backupBatches(e,t){let n=await this.backupRecords?.batches(e,t,at);if(n)return n;let r=this.deps.configStore.get(`backup:${e}:${t}`),o=Array.isArray(r)?r:[];return{async*[Symbol.asyncIterator](){for(let a=0;a<o.length;a+=at)yield o.slice(a,a+at)}}}async firstBackupRecord(e,t,n){let r=await this.backupBatches(e,t),o=n.origin==="sync"?Rn(r,at).batches:r;for await(let a of o)if(a[0]!==void 0)return a[0]}pruneBackups(e){let t=this.deps.services?.getSandforgeSetting?.("backup.maxCount",10)??10,n=[];for(let r of this.deps.configStore.getKeysByPrefix("backup:")){if(r.slice(7).includes(":"))continue;let a=this.deps.configStore.get(r);a?.orgId===e&&a.origin!=="sync"&&a.origin!=="checkpoint"&&n.push({key:r,timestamp:a.timestamp??""})}if(!(n.length<=t)){n.sort((r,o)=>r.timestamp.localeCompare(o.timestamp));for(let{key:r}of n.slice(0,n.length-t))this.removeBackup(r),this.deps.log(`[INFO] Pruned backup ${r} (retention: ${t} per org)`)}}async undeleteFromRecycleBin(e,t,n){let r=[];for await(let a of n){let i=a.map(c=>c.Id).filter(c=>typeof c=="string");if(i.length===0)continue;let d=i.map(c=>`'${qn(c)}'`).join(", ");try{let c=await e.query(`SELECT Id FROM ${t} WHERE Id IN (${d}) AND IsDeleted = true`,{scanAll:!0});r.push(...c.records.map(p=>p.Id))}catch(c){return this.deps.log(`[WARN] Rollback on ${t}: could not look for deleted records \u2014 ${R(c)}`),{undeleted:0}}}let o=0;for(let a=0;a<r.length;a+=200){let i=await e.soap.undelete(r.slice(a,a+200));o+=i.filter(d=>d.success).length}return{undeleted:o}}refuseWithoutGuard(e,t,n,r){oe(this.deps,{...r,outcome:"stopped",source:void 0,code:mt.code}),e(new Error(mt.message),{code:mt.code}),de(this.deps,t,mt.message,!1,{context:n,authored:!0})}async handleRollback(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(or,e,"dataops:error",this.deps);if(!t)return;let n=t,r=e.id,o={module:"dataops",operation:e.type},a=`backup:${n.orgId}`;if(this.activeOrgOperations.has(a)){let h=`A backup or rollback operation is already running for org ${n.orgId}. Please wait for it to complete.`;this.deps.log(`[WARN] ${h}`),M(this.deps,"dataops:rollback","dataops:error",e,new Error(h)),de(this.deps,r,h,!1,{context:o,authored:!0});return}this.activeOrgOperations.add(a);let i,d=[],c=!1,p=new AbortController,u=()=>{},b,l,f;try{if(this.dmlTracker.isDuplicate(r)){this.deps.log(`[WARN] Duplicate rollback operation detected: ${r}`),M(this.deps,"dataops:rollback","dataops:error",e,new Error(`Duplicate operation: ${r}`)),de(this.deps,r,`Duplicate operation: ${r}`,!1,{context:o,authored:!0});return}this.dmlTracker.register(r,"rollback","upsert",0);let h=await Re(n.orgId,this.deps.orgRegistry,this.deps.orgManager),w=new sn(async k=>{let A=await h.describe(k);return ao(A)}),T=`backup:${n.operationId}`,m=this.deps.configStore.get(T);if(!m)throw new Error(`No backup found for operation ${n.operationId}. Cannot rollback.`);if(m.orgId!==n.orgId){let k=nt(this.deps.orgManager.getOrg(m.orgId),m.orgId),A=nt(this.deps.orgManager.getOrg(n.orgId),n.orgId);throw new Error(`Backup ${n.operationId} was taken from org ${m.orgId} and cannot be restored into org ${n.orgId}. A restore writes back by record Id, and an Id belongs to the org that holds it: to bring these records from ${k} into ${A}, copy them with Forge or Sync.`)}i={action:"backup_restore",module:"dataops",operationId:r,orgId:n.orgId,outcome:"failure",source:{origin:"backup",label:m.timestamp?.slice(0,16).replace("T"," ")??n.operationId}};let $=this.deps.infraServices?.productionGuard;if(!$){this.refuseWithoutGuard((k,A)=>M(this.deps,"dataops:rollback","dataops:error",e,k,A),r,o,i);return}let O=[];for(let k of m.objects){let A=await this.firstBackupRecord(n.operationId,k.objectApiName,m);if(A===void 0)continue;let y=De(k.objectApiName);if(!(await w.checkCrudPermission(y,"upsert")).allowed){O.push({objectApiName:y,operation:"upsert",deniedFields:[]});continue}let{denied:be}=await w.partitionWritableFields(y,"upsert",Object.keys(A).filter(me=>me!=="attributes"));be.length>0&&O.push({objectApiName:y,operation:"upsert",deniedFields:be})}if(O.length>0){let k=on(O);this.deps.log(`[WARN] CRUD/FLS check failed for rollback ${r}: ${k}`),oe(this.deps,{...i,outcome:"stopped",source:void 0,code:ht}),M(this.deps,"dataops:rollback","dataops:error",e,new Error(k),{code:ht}),de(this.deps,r,k,!1,{context:o,authored:!0});return}let B=(k,A,y,je=[])=>{oe(this.deps,{...y,outcome:"stopped",source:void 0,code:k}),M(this.deps,"dataops:rollback","dataops:error",e,new Error(A),{code:k,...kn({alsoRefused:je})}),de(this.deps,r,A,!1,{context:o,authored:!0})},Z=await this.readAct(h,n.orgId,"restore",m.objects.map(k=>({objectApiName:k.objectApiName,records:k.recordCount})),n,kt(n)),K=bn(Z.answer);if(K){B(K.code,K.message,i,K.alsoRefused);return}f=this.duplicatesWatchOf(h,mn(Z.answer.automation,m.objects.filter(k=>k.recordCount>0).map(k=>k.objectApiName)));let F=this.deps.orgManager.getOrg(n.orgId),P={orgId:n.orgId,orgTier:On(F),operation:"upsert",objectName:m.objects.map(k=>k.objectApiName).join(", ")||"RollbackData",recordCount:m.totalRecords??0,module:"dataops"},{check:E,decision:S}=await un($,P);if(i.guard=S,(S==="refused"||S==="declined")&&oe(this.deps,{...i,outcome:"stopped",source:void 0}),S==="refused")throw en(E.blockedReason??E.impactSummary);if(S==="declined"){let k="Operation cancelled by user (confirmation declined).";M(this.deps,"dataops:rollback","dataops:error",e,new Error(k),{code:Zt.declined}),de(this.deps,r,k,!1,{context:o,authored:!0});return}if(m.organizationId!==void 0){let k=await this.organizationIdOf(h);if(k!==void 0&&!Eo(m.organizationId,k)){let A=nt(F,n.orgId),y=this.deps.infraServices?.confirmRestoreIntoReplacedOrg;if(!(y?await y({alias:A,backedUpFrom:m.organizationId,now:k}):!1)){oe(this.deps,{...i,outcome:"stopped",source:void 0,code:Wr});let be=`Restore not run: ${A} answers as org ${k}, not as org ${m.organizationId}, which backup ${n.operationId} was taken from, `+(y?"and the restore into the org it is now was not confirmed.":"and nothing here can ask whether to restore into the org it is now.");M(this.deps,"dataops:rollback","dataops:error",e,new Error(be),{code:Wr}),de(this.deps,r,be,!1,{context:o,authored:!0});return}}}let C=await hn(Z,r,n.acceptEmails===!0,kt(n));if("refused"in C){B(C.refused.code,C.refused.message,i);return}l=C.held,jt(this.deps,r,"dataops",`Rollback ${m.objects.length} object(s)`),c=!0,this.deps.infraServices?.backgroundRegistry?.register(r,"dataops",`Rollback ${m.objects.length} object(s)`,new Promise((k,A)=>{u=y=>{y===void 0?k():A(y instanceof Error?y:new Error(String(y)))}}),p),b=Bt(this.liveTracker,r,"dataops",`Rollback ${m.objects.length} object(s)`,m.objects.length);let q=!1,L=0,fe=0,Te=0,Qe=[],Ve=new Map,I=m.origin==="sync"&&n.includeChanged!==!0,D=Number.NEGATIVE_INFINITY,ee=!1;if(I){let k=m.runId!==void 0?await this.syncRuns?.get(m.runId).catch(y=>{this.deps.log(`[WARN] Rollback: the Sync run of backup ${n.operationId} could not be read \u2014 ${R(y)}`)}):void 0,A=k?gr(k):void 0;ee=A===void 0,D=await mr({serverTime:async()=>(await h.soap.getServerTimestamp()).timestamp},A)}let X=[];for(let k=0;k<m.objects.length;k++){if(p.signal.aborted){q=!0;break}let A=m.objects[k],y=De(A.objectApiName);o.objectName=y;let je=await this.backupBatches(n.operationId,A.objectApiName),be=m.origin==="sync"?Rn(je,at):void 0,me=be?.batches??je,Ie;for await(let _ of me)if(Ie=_[0],Ie!==void 0)break;if(I&&Ie!==void 0){let _=[];for await(let ae of me)for(let te of ae)typeof te.Id=="string"&&_.push(te.Id);let ue=await zr({query:async(ae,te)=>({records:(await h.query(ae,te)).records})},y,_,D);ue.size>0&&(X.push({objectApiName:y,count:ue.size}),me=Lr(me,ue))}if(Ie===void 0){Ve.set(A.objectApiName,0),this.deps.log(`[WARN] No backup records for ${A.objectApiName}, skipping.`);continue}let Ht=Object.keys(Ie).filter(_=>_!=="attributes"),{skipped:Kt}=await w.partitionWritableFields(y,"upsert",Ht),Me=new Set(Kt.filter(_=>_.toLowerCase()!=="id").map(_=>_.toLowerCase()));Me.size>0&&this.deps.log(`[INFO] Rollback on ${y}: ${Me.size} non-writable field(s) excluded from the payload \u2014 ${[...Me].sort().join(", ")}`);let It=await this.undeleteFromRecycleBin(h,y,me);It.undeleted>0&&this.deps.log(`[INFO] Rollback on ${y}: ${It.undeleted} record(s) brought back from the recycle bin`),o.batchSize=at;let Ee=0,Ze=0,G=0,We=0;for await(let _ of me){if(p.signal.aborted){q=!0;break}We+=_.length;let ue=_.map(J=>{let we=y===W?Pt(J,!1):void 0,ze={};for(let[tt,Gt]of Object.entries(J))tt!=="attributes"&&(Me.has(tt.toLowerCase())||we!==void 0&&St(W,tt,we)||(ze[tt]=Gt));return ze}),ae=ue;if(n.rewriteAll!==!0){let J=await Er({query:async we=>{let ze=await h.query(we);return{totalSize:ze.totalSize,records:ze.records}}},y,ue);J.unread!==void 0&&this.deps.log(`[WARN] Rollback on ${y}: the org's values could not be read, so ${ue.length} row(s) are written back without comparing \u2014 ${J.unread}`),ae=J.write,G+=J.unchanged}if(ae.length===0)continue;f.beforeWrite(y);let te;try{te=await h.sobject(y).upsert(ae,"Id",{headers:Vt()})}catch(J){throw ln(J)==="may-have-written"&&f.wrote(y,ae.map(we=>we.Id)),J}let et=Array.isArray(te)?te:[te];f.wrote(y,et.flatMap((J,we)=>J.success?[ae[we]?.Id]:[]));for(let J of et){if(J.success){Ee++;continue}Ze++,Hr(Qe,y,J.errors)}}if(Be(h.limitInfo,`dataops:rollback upsert ${y}`),Ve.set(A.objectApiName,be&&!q?be.lines():We),L+=Ee,fe+=Ze,Te+=G,d.push({...Ct(y),updated:Ee,failed:Ze}),q)break;let pt=`Restored ${y} (${Ee}/${We}${G>0?`, ${G} unchanged`:""})`,Oe=Math.round((k+1)/m.objects.length*100);Mt(this.deps,r,Oe,k+1,m.objects.length,pt),b.progress(Oe,k+1,m.objects.length,pt)}let N=X.reduce((k,A)=>k+A.count,0),ce=Wo(L,fe),V=q&&fe===0||N>0&&ce==="success"?"partial":ce;i&&(c=!1,oe(this.deps,{...i,...q?L+fe>0?{outcome:"cancelled"}:{outcome:"stopped",code:rn}:{outcome:V},objects:d}));let Ce=await this.releaseMute(l,n.orgId);l=void 0;let he=await f.read();q?(this.deps.infraServices?.backgroundRegistry?.abort(r),xe(this.deps,r,{aborted:!0,totalRestored:L,totalFailed:fe,totalUnchanged:Te})):xe(this.deps,r,{status:V,totalRestored:L,totalFailed:fe,totalUnchanged:Te}),this.dmlTracker.markCompleted(r),q?b.cancel():V==="failure"?b.fail(`The org refused the ${fe} record(s)`):V==="partial"?b.partial():b.complete();let pe=Cn(m.objects,Ve),Je=(q?`Rollback cancelled: ${L} records restored before the cancel; the rest still hold the values they had, and the same restore puts them back`:fe>0?`Rollback ${V}: ${L} restored, ${fe} rejected by the org`:N>0?`Rollback partial: ${L} records restored`:`Rollback completed: ${L} records restored`)+(Te>0?`; ${Te} already held the backup's values and were not written`:"")+(N>0?`; ${N} changed or deleted since the Sync run were left as they are `+(ee?"(the run is no longer kept here, so every record reads as changed since it) ":"")+"unless the restore includes them":""),Ne=bt(he,this.orgNameOf(n.orgId),"restore"),Ye=pe===""?Je:`${Je}. The backup held only part of the org's records, and the rest were left as they are: ${pe}`,ct=Ne?`${Ye}. ${Ne}`:pe===""?Ye:`${Ye}.`,_e=se(this.deps,e,"dataops:rollback:response",{operationId:n.operationId,status:V,message:ct,totalRestored:L,totalFailed:fe,totalUnchanged:Te,...n.rewriteAll===!0?{rewriteAll:!0}:{},...n.includeChanged===!0?{includeChanged:!0}:{},...N>0?{keptChanged:{total:N,objects:X,...ee?{runNotKept:!0}:{}}}:{},errors:Qe,...pe!==""?{partial:!0}:{},...q?{cancelled:!0}:{},...Ce?{mutedAutomation:Ce}:{},...he?{duplicates:he}:{}});this.deps.broker.postToWebview(_e),this.deps.log(`[TX] ${_e.type} id=${_e.id} status=${V}`),(fe>0||pe!==""||q||N>0||gn(he))&&nn(this.deps,V==="failure"?"error":"warning","Restore",`${ct}${Qe[0]?` \u2014 e.g. ${Qe[0].message}`:""}`)}catch(h){this.dmlTracker.markFailed(r),await this.releaseMute(l,n.orgId),l=void 0;let w=await f?.read(),T=bt(w,this.orgNameOf(n.orgId),"restore");M(this.deps,"dataops:rollback","dataops:error",e,T?new Error(`${R(h)} ${T}`):h,{code:tn(h),...w?{extraPayload:{duplicates:w}}:{}}),de(this.deps,r,R(h),!0,{context:o}),b?.fail(R(h))}finally{await this.releaseMute(l,n.orgId),this.activeOrgOperations.delete(a),u(),c&&i&&oe(this.deps,{...i,outcome:"failure",objects:d})}}async snapshotBeforeMasking(e,t,n,r,o){let a=new Map,i=new Map;try{for(let p of r){if(p.tally.total===0)continue;p.where!==void 0&&i.set(p.tally.objectApiName,p.where);let{select:u}=await this.maskedFields(e,p.tally.objectApiName,this.maskingRules(p.objectName,p.objectRules),this.maskingRules(p.objectName,p.personRules));u!=="Id"&&a.set(p.tally.objectApiName,u)}}catch(p){return{refused:`No snapshot was taken, so nothing was masked: ${R(p)}`,retryable:!0}}if(a.size===0)return{};let d=`${t}-snapshot`,c=await this.takeBackup(d,{orgId:n,objects:[...a.keys()],...i.size>0?{wheres:i}:{},fields:a},o.origin,o.stop);return"error"in c?(this.endBackupNotTaken(d,c),{refused:`No snapshot was taken, so nothing was masked: ${R(c.error)}`,retryable:c.retryable&&c.cancelled!==!0}):c.partial?{refused:`Snapshot ${d} holds only part of the records the run would mask, so nothing was masked: a restore could not put back the rest (${Cn(c.objects)}). `+this.snapshotCapWay(r),retryable:!1}:{taken:{operationId:d,totalRecords:c.totalRecords}}}async maskingNotCovered(e,t,n,r){if(r.length===0)return{code:ve.masksNothing,message:`The template "${t.name}" has no rule for ${n.join(", ")}: the run would mask nothing. Choose an object its rules name, or another template. Nothing was masked.`,gaps:{fieldsNotFound:[],objectsNotCovered:[...n]}};let o=[],a=[];for(let d of r){if(d.tally.total===0)continue;let{objectApiName:c}=d.tally,{rules:p,missing:u}=await this.maskedFields(e,c,this.maskingRules(d.objectName,d.objectRules),this.maskingRules(d.objectName,d.personRules));o.push(...u.map(b=>({objectApiName:c,fieldApiName:b}))),p.length===0&&a.push(c)}let i={fieldsNotFound:o,objectsNotCovered:a};if(o.length>0){let d=o.map(c=>`${c.objectApiName}.${c.fieldApiName}`).join(", ");return{code:ve.fieldsUnseen,message:`The template "${t.name}" masks ${d}, which the org does not show the user SandForge connects as: it has no such field, or field-level security hides it. `+(a.length>0?`No field of ${a.join(", ")} can be masked. `:"")+"A run masks every field its template names, or nothing: give that user read and edit access to the field, or take the field out of the template. Nothing was masked.",gaps:i}}if(a.length>0)return{code:ve.masksNothing,message:`The template "${t.name}" masks no field of ${a.join(", ")} in this org: the run would write nothing over its records. Choose an object its rules name, or another template. Nothing was masked.`,gaps:i}}async anonymizeForPipeline(e,t){let n=this.deps.orgManager.getOrg(e.orgId);if(!n)throw Fe(ve.orgUnknown,`The org the masking writes to is not connected to SandForge (${e.orgId}): connect it, or choose another. Nothing was masked.`);let r=Fr(On(n),e.answer,nt(n,e.orgId));if(r)throw r;let o=_r(e,f=>this.findTemplate(f)!==void 0);if("refusal"in o)throw o.refusal;let a=crypto.randomUUID(),i,d,c,p={origin:"pipeline:execute",pipeline:e.pipeline,accord:e.accord??{},voice:"step",muted:f=>{c=f},refused:(f,h)=>{i??={err:f,...h},this.deps.log(`[ERR] dataops:anonymize ${a} for the pipeline "${e.pipeline.name}": `+R(f))},ended:f=>{d=f}};await this.writing.during(e.orgId,()=>Ar(e.answer,()=>this.mask(o.asked,a,p,t)));let u=i,b=c;if(u){let f=R(u.err),h=u.err,w=u.code??(typeof h?.code=="string"?h.code:void 0),T=u.extraPayload?.snapshot,m={...w!==void 0?{code:w}:{},...T!==void 0?{snapshot:T}:{},...b?{mutedAutomation:b}:{}};throw Object.assign(w===$t?new cn(f):new Error(f),m)}let l=d;if(l===void 0)throw new Error("The masking run ended without a result.");return{operationId:a,result:b?{...l,mutedAutomation:b}:l}}async handleAnonymize(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(Et,e,"dataops:error",this.deps);if(!t)return;let n=kt(t);await this.mask(t,e.id,{...this.pageMaskingReplies(e),accord:{acceptAutomation:t.acceptAutomation===!0,acceptEmails:t.acceptEmails===!0,muteAutomation:t.muteAutomation===!0},...n?{voice:n}:{}})}pageMaskingReplies(e){return{origin:e.type,refused:(t,n)=>M(this.deps,"dataops:anonymize","dataops:error",e,t,n),ended:t=>{let n=se(this.deps,e,"dataops:anonymize:response",t);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id} status=${t.status}`),(t.recordsNotMasked>0||gn(t.duplicates))&&nn(this.deps,t.status==="failure"?"error":"warning","Anonymize",`${t.message}${t.errors[0]?` \u2014 e.g. ${t.errors[0].message}`:""}`)}}}async mask(e,t,n,r){let o,a={},i,d=async()=>(i??={released:await this.releaseMute(o,e.orgId)},i.released),c={...n,refused:(I,D)=>{if(!o){n.refused(I,D);return}a.answer??=ee=>n.refused(I,ee?{...D,extraPayload:{...D.extraPayload,mutedAutomation:ee}}:D)},ended:I=>{if(!o){n.ended(I);return}a.answer??=D=>n.ended(D?{...I,mutedAutomation:D}:I)}},p={module:"dataops",operation:c.origin},u=this.findTemplate(e.templateId),b=Ft(e,u),l={action:"anonymize_execute",module:"dataops",operationId:t,orgId:e.orgId,outcome:"failure",source:{origin:"org",orgId:e.orgId}},f=[],h=[],w=zn(e),T=u?Dt(u.rules,b,w):"",m=!1,$=!1,O=!1,B=!1,Z,K,F=new AbortController,P=()=>{},E,S,C,q=async()=>C?.read(),L=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(t);L?.signal.addEventListener("abort",()=>F.abort(),{once:!0});let fe=()=>F.abort();r?.aborted&&F.abort(),r?.addEventListener("abort",fe,{once:!0});let Te=async()=>{oe(this.deps,{...l,outcome:"stopped",source:void 0,code:$t});let I="The masking run was cancelled before it wrote anything.";c.refused(new Error(I),{code:$t,...K?{extraPayload:{snapshot:K}}:{}}),await d(),xe(this.deps,t,{aborted:!0})},Qe=(I,D,ee)=>{E=I;let X=R(I),N=Tt(f),ce=m&&N.recordsNotMasked>0,V=bt(ee,this.orgNameOf(e.orgId)),Ce={...m?{...N,objects:to(f)}:{},...K?{snapshot:K}:{},...ee?{duplicates:ee}:{}},he=ce?`${X} \u2014 ${N.recordsProcessed} masked before it stopped; ${N.recordsNotMasked} still hold their original values (${eo(f)}).`:X;c.refused(ce||V?new Error(V?`${he} ${V}`:he):I,{code:tn(I),extraPayload:Ce}),de(this.deps,t,X,D,{context:p,extraPayload:Ce}),S?.fail(X)},Ve=()=>{B=!0;let I=new st(this.deps.configStore),{recordsNotMasked:D}=Tt(f),ee=f.reduce((X,N)=>X+N.masked+N.nothingToMask+N.refused+N.unanswered,0);try{if(D===0)return I.clear(e.orgId,e.templateId),!1;if(ee===0)return I.load(e.orgId,e.templateId,T)!==void 0;let X=h.map(N=>N.progress);return wt(X)>qe?(this.deps.log(`[WARN] dataops:anonymize ${t}: the org refused ${wt(X)} record(s), more than a resume retries (${qe}): only a full run masks them.`),I.clear(e.orgId,e.templateId),!1):(I.save({id:t,orgId:e.orgId,templateId:e.templateId,fingerprint:T,savedAt:new Date().toISOString(),objects:X,...Z?{namesGiven:Z.namesGiven()}:{}}),!0)}catch(X){return this.deps.log(`[WARN] dataops:anonymize ${t}: where the run stopped was not kept: `+R(X)),!1}};try{let I=this.deps.infraServices?.productionGuard;if(!I){this.refuseWithoutGuard((g,j)=>c.refused(g,j),t,p,l);return}if(!u){c.refused(Qr(e.templateId),{code:Xr});return}let D=vt(e,u,W)?Ft(e,u,!0):void 0,ee=D?[T,Dt(u.rules,D,w)]:[T],X=()=>c.refused(new Error("There is nothing to resume: the run has finished since, another run of this template has stopped since, or its rules have changed. Apply masks every record of its objects."),{code:Ko}),N;if(e.resumeFrom!==void 0){let g=new st(this.deps.configStore);if(N=ee.map(j=>g.load(e.orgId,e.templateId,j)).find(j=>j?.id===e.resumeFrom),!N){X();return}}let ce=await Re(e.orgId,this.deps.orgRegistry,this.deps.orgManager),V=Kr(ce);if(D&&await Pn(V,this.deps.log)&&(b=D,T=ee[1]),N&&N.fingerprint!==T){X();return}let Ce,he=g=>{let j=Be(ce.limitInfo,g);j&&j.usagePercent>=Ho&&(Ce??=j)},pe=()=>Ce;for(let g of b){let j=_t(u,g),ie=Mn(u,g);if(j.length===0&&ie.length===0)continue;let ge=De(g),U=Nn(e,u,g);p.objectName=ge;let v=N?.objects.find(Ue=>Ue.objectApiName===ge),x={objectApiName:ge,done:v?.done??!1,...v?.afterId!==void 0?{afterId:v.afterId}:{},refused:[...v?.refused??[]],...v?.unconfirmed?.length?{unconfirmed:[...v.unconfirmed]}:{}},Pe=0;if(!x.done){try{Pe=await this.countRows(ce,ge,x.afterId,U)}catch(Ue){throw oe(this.deps,{...l,outcome:"failure",source:void 0,objects:[Ct(ge)],code:qo,details:{reason:Jr(Ue)}}),this.countGaveUp(Ue,ge)}he(`dataops:anonymize count ${ge}`),Pe===0&&(x.done=!0)}let Ot=Pe+x.refused.length+(x.unconfirmed?.length??0),ut={objectApiName:ge,total:Ot,masked:0,nothingToMask:0,refused:0,unanswered:0,done:Ot===0};f.push(ut),h.push({objectName:g,...U!==void 0?{where:U}:{},objectRules:j,personRules:ie,tally:ut,progress:x})}let Je=f.reduce((g,j)=>g+j.total,0),Ne=await this.maskingNotCovered(V,u,b,h);if(Ne){oe(this.deps,{...l,outcome:"stopped",source:void 0,code:Ne.code}),c.refused(new Error(Ne.message),{code:Ne.code,extraPayload:{...Ne.gaps}}),de(this.deps,t,Ne.message,!1,{context:p,authored:!0});return}let Ye=await Gr(V,h.filter(g=>g.tally.total>0).map(g=>({objectApiName:g.tally.objectApiName,rules:[...g.objectRules,...g.personRules]})));if(Ye.length>0){let g=on(Ye);this.deps.log(`[WARN] CRUD/FLS check failed for anonymize ${t}: ${g}`),oe(this.deps,{...l,outcome:"stopped",source:void 0,code:ht}),c.refused(new Error(g),{code:ht}),de(this.deps,t,g,!1,{context:p,authored:!0});return}let ct=(g,j,ie=[])=>{oe(this.deps,{...l,outcome:"stopped",source:void 0,code:g}),c.refused(new Error(j),{code:g,...kn({alsoRefused:ie})}),de(this.deps,t,j,!1,{context:p,authored:!0})},_e=await this.readAct(ce,e.orgId,"masking",f.map(g=>({objectApiName:g.objectApiName,records:g.total})),c.accord,c.voice),k=bn(_e.answer);if(k){ct(k.code,k.message,k.alsoRefused);return}let A=this.duplicatesWatchOf(ce,mn(_e.answer.automation,f.filter(g=>g.total>0).map(g=>g.objectApiName)));C=A;let y=this.deps.orgManager.getOrg(e.orgId),je={orgId:e.orgId,orgTier:On(y),operation:"update",objectName:b.join(", ")||"AnonymizeData",recordCount:Je,module:"dataops"},{check:be,decision:me}=await un(I,je);if(l.guard=me,(me==="refused"||me==="declined")&&oe(this.deps,{...l,outcome:"stopped",source:void 0}),me==="refused")throw en(be.blockedReason??be.impactSummary);if(me==="declined"){let g="Operation cancelled by user (confirmation declined).";c.refused(new Error(g),{code:Zt.declined}),de(this.deps,t,g,!1,{context:p,authored:!0});return}for(let g of be.warnings)this.deps.log(`[WARN] dataops:anonymize ${t}: ${g}`);if(F.signal.aborted){await Te();return}let Ie=await hn(_e,t,c.accord.acceptEmails===!0,c.voice);if("refused"in Ie){ct(Ie.refused.code,Ie.refused.message);return}o=Ie.held,m=!0;let Ht=wn(y?.orgType==="Sandbox"||y?.orgType==="Scratch"),Kt=yn(Ht).defaultQueryLimit;if(e.snapshot===!0){let g=await this.snapshotBeforeMasking(V,t,e.orgId,h,{origin:c.origin,stop:F.signal});if("refused"in g&&F.signal.aborted){await Te();return}if("refused"in g){oe(this.deps,{...l,outcome:"stopped",source:void 0,code:Vr}),c.refused(new Error(g.refused),{code:Vr}),await d(),de(this.deps,t,g.refused,g.retryable,{context:p,authored:!0});return}if(K=g.taken,F.signal.aborted){await Te();return}}let Me=c.pipeline?`Pipeline anonymization with ${u.name}`:`Anonymizing with ${u.name}`;jt(this.deps,t,"dataops",Me),$=!0,O=!0,this.deps.infraServices?.backgroundRegistry?.register(t,"dataops",Me,new Promise((g,j)=>{P=ie=>{ie===void 0?g():j(ie instanceof Error?ie:new Error(String(ie)))}}),F),S=Bt(this.liveTracker,t,"dataops",Me,Je);let{AnonymizationEngine:It}=await import("./chunk-TLH7AD35.mjs"),Ee=new It(void 0,this.maskingKey);Z=Ee,N&&!(N.namesGiven!==void 0&&Ee.continueFrom(N.namesGiven))&&this.deps.log(`[INFO] dataops:anonymize ${t}: the run it resumes kept no record of the names it made up, so this one may give again a name or an address that run gave.`);let Ze=[],G=!1,We=g=>g.masked+g.nothingToMask+g.refused,pt=(g,j)=>{let ie=f.reduce((x,Pe)=>x+We(Pe),0),ge=Math.max(Je,ie),U=Math.round(ie/ge*100),v=`Anonymized ${g} (${We(j)}/${Math.max(j.total,We(j))})`;Mt(this.deps,t,U,ie,ge,v),S?.progress(U,ie,ge,v)};for(let{objectName:g,where:j,objectRules:ie,personRules:ge,tally:U,progress:v}of h){if(U.total===0)continue;if(F.signal.aborted){G=!0;break}if(pe())break;let x=U.objectApiName;p.objectName=x;let{select:Pe,rulesOf:Ot}=await this.maskedFields(V,x,this.maskingRules(g,ie),this.maskingRules(g,ge));p.batchSize=Xe;let ut=async(Y,ke,$e)=>{let Le=Y.map(Ot),Ae=Y.map((re,H)=>Ee.anonymize([re],Le[H])[0]),ne=[];Y.forEach((re,H)=>{let z={Id:re.Id};for(let ye of Le[H])pn(re[ye.fieldApiName])&&(z[ye.fieldApiName]=Ae[H][ye.fieldApiName]);Object.keys(z).length>1?ne.push(z):U.nothingToMask++});for(let re=0;re<ne.length;re+=Xe){if(F.signal.aborted)return G=!0,!0;if(pe())return!0;let H=ne.slice(re,re+Xe),z;A.beforeWrite(x);try{z=await ce.sobject(g).update(H,{headers:Vt()})}catch(He){throw ln(He)==="may-have-written"&&(U.unanswered+=H.length,$e(H,H.flatMap(Go)),A.wrote(x,H.map(lt=>lt.Id))),He}he(`dataops:anonymize update ${x}`);let ye=[],xn=Array.isArray(z)?z:[z];A.wrote(x,xn.flatMap((He,lt)=>He.success?[H[lt]?.Id]:[])),xn.forEach((He,lt)=>{if(He.success){U.masked++;return}U.refused++;let Xt=H[lt]?.Id;typeof Xt=="string"&&Wt.test(Xt)&&ye.push(Xt),Hr(Ze,x,He.errors)}),ke(H,ye),pt(g,U)}return ne.length===0&&pt(g,U),!1},Ue=v.unconfirmed??[];for(let Y=0;Y<Ue.length;Y+=Xe){if(F.signal.aborted){G=!0;break}if(pe())break;let ke=Ue.slice(Y,Y+Xe),$e=ke.map(z=>`'${z.id}'`).join(", "),Le=await gt(ce,`SELECT ${Pe} FROM ${x} WHERE Id IN (${$e})`);he(`dataops:anonymize query ${x}`);let Ae=new Map(Le.map(z=>[String(z.Id),z])),ne=[];for(let z of ke){let ye=Ae.get(z.id);ye===void 0?U.total-=1:In(ye,z.fields)===z.digest?U.nothingToMask++:ne.push(z.id)}let re=new Set(ke.map(z=>z.id)),H=(v.unconfirmed??[]).filter(z=>!re.has(z.id));H.length>0?v.unconfirmed=H:delete v.unconfirmed,v.refused.push(...ne)}if(G||pe())break;let Dn=[...v.refused];for(let Y=0;Y<Dn.length;Y+=Xe){if(F.signal.aborted){G=!0;break}if(pe())break;let ke=Dn.slice(Y,Y+Xe),$e=await gt(ce,`SELECT ${Pe} FROM ${x} WHERE Id IN (${ke.map(re=>`'${re}'`).join(", ")})`);he(`dataops:anonymize query ${x}`),U.total-=ke.length-$e.length;let Le=[];if(await ut($e,(re,H)=>Le.push(...H),(re,H)=>{let z=new Set(H.map(ye=>ye.id));v.refused=v.refused.filter(ye=>!z.has(ye)),v.unconfirmed=[...v.unconfirmed??[],...H]}))break;let ne=new Set(ke);v.refused=[...v.refused.filter(re=>!ne.has(re)),...Le]}if(G||pe())break;if(v.done){U.done=!0;continue}let qt=v.afterId;for(;;){if(F.signal.aborted){G=!0;break}if(pe())break;let Y=await ro(ce,x,Pe,Kt,qt,j);if(he(`dataops:anonymize query ${x}`),Y.records.length===0){U.done=!0,v.done=!0;break}let ke=Y.truncated?ts(Y.records,qt,x):void 0;if(F.signal.aborted){G=!0;break}let $e=Ae=>{let ne=Ae[Ae.length-1]?.Id;typeof ne=="string"&&Wt.test(ne)&&(v.afterId=ne)};if(await ut(Y.records,(Ae,ne)=>{v.refused.push(...ne),$e(Ae)},(Ae,ne)=>{v.unconfirmed=[...v.unconfirmed??[],...ne],$e(Ae)}))break;if(ke===void 0){U.done=!0,v.done=!0;break}qt=ke,v.afterId=ke}if(G||pe())break}let Oe=pe(),_=Vo(f,G),{recordsProcessed:ue,recordsFailed:ae,recordsNotMasked:te}=Tt(f),et=eo(f);$=!1,oe(this.deps,{...l,...Jo(f,_,G),objects:no(f)});let J=Ve();if(te>0){let g=G?"cancelled":Oe?`stopped at ${Oe.usagePercent}% of the org's API requests`:"refused by the org";this.deps.log(`[WARN] dataops:anonymize ${t} ${g}: ${te} record(s) not masked \u2014 ${et}`)}await d();let we=await q();G?(this.deps.infraServices?.backgroundRegistry?.abort(t),xe(this.deps,t,{aborted:!0,totalProcessed:ue,totalFailed:ae,totalNotMasked:te}),S?.cancel()):(xe(this.deps,t,{status:_,totalProcessed:ue,totalFailed:ae,totalNotMasked:te}),_==="failure"?S?.fail(`The org refused the ${ae} record(s)`):_==="partial"?S?.partial():S?.complete());let ze=`${te} still hold their original values (${et})`,tt=G?`Anonymization cancelled: ${ue} masked before the cancel \u2014 ${ze}.`:Oe?`Anonymization stopped at ${Oe.usagePercent}% of the org's daily API requests (${Oe.apiUsage} of ${Oe.apiLimit}): ${ue} masked \u2014 ${ze}. ${J?"Resume it":"Run it again"} once the org has requests to spare.`:ae===0?`Anonymization ${_==="success"?"completed":_}: ${ue} records processed.`:`Anonymization ${_}: ${ue} masked, ${ae} rejected by the org \u2014 those records still hold their original values.`,Gt=J&&te>0?" Resume masks only what this run left.":"",Ln=bt(we,this.orgNameOf(e.orgId)),uo=tt+Gt+(Ln?` ${Ln}`:"");c.ended({templateId:e.templateId,status:_,recordsProcessed:ue,recordsFailed:ae,recordsNotMasked:te,objects:to(f),message:uo,errors:Ze,...G?{cancelled:!0}:{},...Oe?{stoppedAtApiLimit:!0}:{},...K?{snapshot:K}:{},...o?{mutedAutomation:o.outcome}:{},...we?{duplicates:we}:{}})}catch(I){await d();let D=await q().catch(()=>{});Qe(I,!0,D)}finally{let I=await d();if(I&&c.muted?.(I),$){let D=f.some(ee=>ee.masked>0);oe(this.deps,{...l,outcome:D?"partial":"failure",objects:m?no(f):[]})}O&&!B&&Ve(),P(E),L?.release(),r?.removeEventListener("abort",fe),a.answer?.(I)}}handleAnonymizationTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.listedTemplates(),n=se(this.deps,e,"dataops:anonymization-templates:response",{templates:t});this.deps.broker.postToWebview(n),this.deps.log("[TX] dataops:anonymization-templates:response")}listedTemplates(){return[...yt,...this.savedTemplates.list()]}async handleBackupObjects(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(tr,e,"dataops:error",this.deps);if(!t)return;let n=t.templateId!==void 0?this.findTemplate(t.templateId):void 0;if(t.templateId!==void 0&&!n){this.refuseUnknownTemplate("backup:objects",e,t.templateId);return}try{let r,o=()=>r??=Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager).then(d=>Pn(d,this.deps.log)),a=[];for(let d of n?[n]:this.listedTemplates()){let c=vt({},d,W)&&await o();for(let p of Ft({},d,c))p!==""&&p!=="*"&&!a.includes(p)&&a.push(p)}let i=se(this.deps,e,"backup:objects:response",{objects:a});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} objects=${a.length}`)}catch(r){M(this.deps,"backup:objects","dataops:error",e,r)}}async plannedObjectsIn(e,t,n){let r=vt(t,n,W)&&await Pn(e,this.deps.log);return Ft(t,n,r)}async handleAnonymizeCoverage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(ar,e,"dataops:error",this.deps);if(!t)return;let n=this.findTemplate(t.templateId);if(!n){this.refuseUnknownTemplate("dataops:anonymize:coverage",e,t.templateId);return}try{let r=this.latestBackup(t.orgId),o=await Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager),a=[],i=await this.plannedObjectsIn(o,t,n);for(let p of i){if(!qr(n,p))continue;let u=De(p),b=null;try{b=await this.countRows(o,u,void 0,Nn(t,n,p))}catch(f){this.deps.log(`[WARN] dataops:anonymize:coverage: ${u} not counted: ${R(f)}`)}let l=r?.objects.find(f=>f.objectApiName.toLowerCase()===u.toLowerCase());a.push({objectApiName:u,count:b,backedUp:l?.recordCount??0,truncated:l?.truncated===!0,...l?.stoppedAt?{stoppedAt:l.stoppedAt}:{}})}let d=new st(this.deps.configStore).load(t.orgId,t.templateId,Dt(n.rules,i,zn(t))),c=se(this.deps,e,"dataops:anonymize:coverage:response",{templateId:t.templateId,...r?{backup:{operationId:r.operationId,timestamp:r.timestamp}}:{},objects:a,...d?{checkpoint:{id:d.id,savedAt:d.savedAt}}:{}});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id} objects=${a.length}`)}catch(r){M(this.deps,"dataops:anonymize:coverage","dataops:error",e,r)}}async handleAnonymizePreview(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(ir,e,"dataops:error",this.deps);if(!t)return;let n=this.findTemplate(t.templateId);if(!n){this.refuseUnknownTemplate("dataops:anonymize:preview",e,t.templateId);return}try{let r=await Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager),{AnonymizationEngine:o}=await import("./chunk-TLH7AD35.mjs"),a=new o(void 0,this.maskingKey),i=[],d=[],c=Kr(r);for(let u of await this.plannedObjectsIn(r,t,n)){if(!qr(n,u))continue;let b=De(u);try{let l=_t(n,u),f=Mn(n,u),{rules:h,select:w,missing:T,rulesOf:m}=await this.maskedFields(c,b,this.maskingRules(u,l),this.maskingRules(u,f)),$=await ro(r,b,w,Yr,void 0,Nn(t,n,u));Be(r.limitInfo,`dataops:anonymize:preview ${b}`);let O=$.records.length>0;O&&d.push(...T.map(P=>({objectApiName:b,fieldApiName:P})));let[B]=O?await Gr(c,[{objectApiName:b,rules:[...l,...f]}]):[],Z=$.records.map(m),K=$.records.map((P,E)=>a.anonymize([P],Z[E])[0]),F=h.map(P=>P.fieldApiName).filter((P,E,S)=>P!=="Id"&&S.indexOf(P)===E);i.push({objectApiName:b,fields:F,...O&&h.length===0?{notCovered:!0}:{},...B?{writeDenied:{deniedFields:[...B.deniedFields]}}:{},methods:Object.fromEntries(h.map(P=>[P.fieldApiName,P.method])),rows:$.records.slice(0,Yr).map((P,E)=>{let S={},C={},q=new Set(Z[E].map(L=>L.fieldApiName));for(let L of F)S[L]=Zr(P[L]),C[L]=pn(P[L])&&q.has(L)?Zr(K[E][L]):S[L];return{id:String(P.Id??""),before:S,after:C}})})}catch(l){let f=R(l);this.deps.log(`[WARN] dataops:anonymize:preview: ${b} not read: ${f}`),i.push({objectApiName:b,fields:[],rows:[],error:f})}}let p=se(this.deps,e,"dataops:anonymize:preview:response",{templateId:t.templateId,objects:i,fieldsNotFound:d});this.deps.broker.postToWebview(p),this.deps.log(`[TX] ${p.type} id=${p.id} objects=${i.length}`)}catch(r){M(this.deps,"dataops:anonymize:preview","dataops:error",e,r)}}latestBackup(e){let t;for(let n of this.deps.configStore.getKeysByPrefix("backup:")){let r=n.slice(7);if(r.includes(":"))continue;let o=this.deps.configStore.get(n);if(o?.orgId!==e)continue;let a=o.timestamp??"";t&&t.timestamp.localeCompare(a)>=0||(t={operationId:r,timestamp:a,objects:o.objects??[]})}return t}async handleQualityScan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(ur,e,"dataops:error",this.deps);if(t)try{let n=await Re(t.orgId,this.deps.orgRegistry,this.deps.orgManager),r=await lr({describe:a=>n.describe(a),query:async a=>{let i=await n.query(a);return Be(n.limitInfo,"dataops:quality-scan"),{totalSize:i.totalSize,records:i.records}}},t),o=se(this.deps,e,"dataops:quality-scan:response",{...r});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} objects=${r.objects.length}`)}catch(n){M(this.deps,"dataops:quality-scan","dataops:error",e,n)}}handleTemplateSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(dr,e,"dataops:error",this.deps);if(t)try{let n=t.name.trim();if([...yt,...this.savedTemplates.list()].some(i=>i.name.trim().toLowerCase()===n.toLowerCase())){M(this.deps,"dataops:anonymization-template:save","dataops:error",e,new Error(`A template named "${n}" already exists. Pick another name.`),{code:"DUPLICATE_NAME"});return}let o={id:`tpl-saved-${crypto.randomUUID()}`,name:n,description:"",complianceFramework:"custom",rules:t.rules.map(i=>({...i,description:""})),saved:!0,createdAt:new Date().toISOString()};this.savedTemplates.save(o);let a=se(this.deps,e,"dataops:anonymization-template:save:response",{template:o});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id}`)}catch(n){M(this.deps,"dataops:anonymization-template:save","dataops:error",e,n)}}handleTemplateDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(cr,e,"dataops:error",this.deps);if(!t)return;let{templateId:n}=t;if(yt.some(r=>r.id===n)){M(this.deps,"dataops:anonymization-template:delete","dataops:error",e,new Error(`Template "${n}" ships with SandForge and cannot be deleted.`),{code:"BUILT_IN"});return}try{let r=this.savedTemplates.delete(n),o=se(this.deps,e,"dataops:anonymization-template:delete:response",{templateId:n,deleted:r});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(r){M(this.deps,"dataops:anonymization-template:delete","dataops:error",e,r)}}async handlePIIScan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=le(pr,e,"dataops:error",this.deps);if(!t)return;let{orgId:n,objectNames:r}=t;try{if(!this.deps.infraServices?.piiDetector)throw new Error("PII Detector not available.");let o=await Re(n,this.deps.orgRegistry,this.deps.orgManager),a=await Promise.all(r.map(async d=>{let c=De(d),p=await o.describe(c);Be(o.limitInfo,`precheck:pii-scan describe ${c}`);let u=p.fields.map(l=>({apiName:l.name,label:l.label,type:l.type,length:l.length})),b=this.deps.infraServices.piiDetector.detectPII(d,u);return{objectName:d,piiFields:b.piiFields.map(l=>({fieldName:l.fieldApiName,piiType:l.classification,confidence:l.confidence}))}})),i=se(this.deps,e,"precheck:pii-scan:response",{success:!0,results:a});this.deps.broker.postToWebview(i)}catch(o){this.deps.log(`[ERR] precheck:pii-scan: ${R(o)}`);let a=se(this.deps,e,"precheck:pii-scan:response",{success:!1,error:R(o)});this.deps.broker.postToWebview(a)}}};export{yt as a,zt as b,yn as c,wn as d,Lt as e,An as f,xt as g,Bt as h,_r as i,Do as j,At as k,xo as l,so as m};
@@ -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{od as s,pd as d}from"./chunk-TTFDUKUS.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};