sandforge 0.0.0-stage → 1.79.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +54 -2
  3. package/THIRD-PARTY-NOTICES.md +1624 -0
  4. package/bin/sandforge-autopilot.mjs +12 -0
  5. package/bin/sandforge-backup.mjs +12 -0
  6. package/bin/sandforge-checkpoint.mjs +12 -0
  7. package/bin/sandforge-cleanup.mjs +12 -0
  8. package/bin/sandforge-clone.mjs +12 -0
  9. package/bin/sandforge-compare.mjs +12 -0
  10. package/bin/sandforge-dataops.mjs +12 -0
  11. package/bin/sandforge-empty.mjs +12 -0
  12. package/bin/sandforge-env.mjs +12 -0
  13. package/bin/sandforge-frozen.mjs +12 -0
  14. package/bin/sandforge-mcp.mjs +12 -0
  15. package/bin/sandforge-monitor.mjs +12 -0
  16. package/bin/sandforge-seed.mjs +12 -0
  17. package/bin/sandforge-sync.mjs +12 -0
  18. package/bin/sandforge.mjs +12 -0
  19. package/lib/catalogue.en.json +1 -0
  20. package/lib/chunk-2BVTCNWA.mjs +7 -0
  21. package/lib/chunk-2S5OMIIA.mjs +7 -0
  22. package/lib/chunk-2YIV2OB2.mjs +7 -0
  23. package/lib/chunk-342FN7AO.mjs +9 -0
  24. package/lib/chunk-36U7IQ6Y.mjs +25 -0
  25. package/lib/chunk-3CA767QB.mjs +7 -0
  26. package/lib/chunk-3DCUADVK.mjs +7 -0
  27. package/lib/chunk-3F5YMM2F.mjs +7 -0
  28. package/lib/chunk-3OHPD72J.mjs +9 -0
  29. package/lib/chunk-3RYLICRX.mjs +7 -0
  30. package/lib/chunk-3SRXFZSD.mjs +7 -0
  31. package/lib/chunk-42RER7V4.mjs +14 -0
  32. package/lib/chunk-4GL773D5.mjs +7 -0
  33. package/lib/chunk-4HFRHFGQ.mjs +7 -0
  34. package/lib/chunk-4HW535YJ.mjs +7 -0
  35. package/lib/chunk-4NAHW2D3.mjs +7 -0
  36. package/lib/chunk-4SNDMJP2.mjs +7 -0
  37. package/lib/chunk-4TLYUZD5.mjs +7 -0
  38. package/lib/chunk-4U6NXJNL.mjs +7 -0
  39. package/lib/chunk-4XZ5YT5O.mjs +7 -0
  40. package/lib/chunk-55HEMHEG.mjs +7 -0
  41. package/lib/chunk-57VHUYNG.mjs +10 -0
  42. package/lib/chunk-5AJRHRXA.mjs +20 -0
  43. package/lib/chunk-5CD257T7.mjs +7 -0
  44. package/lib/chunk-5HMAPZBV.mjs +7 -0
  45. package/lib/chunk-5LFSFYFJ.mjs +7 -0
  46. package/lib/chunk-5MMXFWPD.mjs +7 -0
  47. package/lib/chunk-5O6JOMHS.mjs +13 -0
  48. package/lib/chunk-5P4PHJRL.mjs +9 -0
  49. package/lib/chunk-5QKTYCWE.mjs +11 -0
  50. package/lib/chunk-66NMFCWX.mjs +7 -0
  51. package/lib/chunk-6EBMEGZB.mjs +7 -0
  52. package/lib/chunk-6LAXTAVN.mjs +7 -0
  53. package/lib/chunk-6MUEPV7M.mjs +9 -0
  54. package/lib/chunk-6QSM2WIH.mjs +10 -0
  55. package/lib/chunk-75ADZS6B.mjs +7 -0
  56. package/lib/chunk-7EANH5PY.mjs +68 -0
  57. package/lib/chunk-7F54PZUS.mjs +7 -0
  58. package/lib/chunk-7UQD6V6F.mjs +7 -0
  59. package/lib/chunk-AAVJ5XVX.mjs +7 -0
  60. package/lib/chunk-ALJVEUUS.mjs +7 -0
  61. package/lib/chunk-ALUFROGA.mjs +7 -0
  62. package/lib/chunk-AR7BE5O2.mjs +7 -0
  63. package/lib/chunk-AUTM6H6Z.mjs +7 -0
  64. package/lib/chunk-AV5SWEHP.mjs +9 -0
  65. package/lib/chunk-B45CNPUX.mjs +47 -0
  66. package/lib/chunk-BILZ3SSR.mjs +7 -0
  67. package/lib/chunk-BN7A4GRQ.mjs +7 -0
  68. package/lib/chunk-BOGNK4LV.mjs +7 -0
  69. package/lib/chunk-BS5T3MOQ.mjs +7 -0
  70. package/lib/chunk-BZ24IAP5.mjs +7 -0
  71. package/lib/chunk-CA5NAXSU.mjs +7 -0
  72. package/lib/chunk-CE6ZDGBB.mjs +7 -0
  73. package/lib/chunk-CGWXQX75.mjs +7 -0
  74. package/lib/chunk-CHCHAE4B.mjs +7 -0
  75. package/lib/chunk-D3QRXG63.mjs +787 -0
  76. package/lib/chunk-DBFJB2B6.mjs +7 -0
  77. package/lib/chunk-DLDX6RRC.mjs +7 -0
  78. package/lib/chunk-EADHKH3A.mjs +7 -0
  79. package/lib/chunk-EEVVGGM6.mjs +7 -0
  80. package/lib/chunk-ENLBYECD.mjs +7 -0
  81. package/lib/chunk-EQF2IJS2.mjs +11 -0
  82. package/lib/chunk-EQOQASDQ.mjs +7 -0
  83. package/lib/chunk-F2424IKX.mjs +7 -0
  84. package/lib/chunk-F74IHMGL.mjs +7 -0
  85. package/lib/chunk-FOVVHGEP.mjs +7 -0
  86. package/lib/chunk-FQBRBBY4.mjs +7 -0
  87. package/lib/chunk-FQGHL7GR.mjs +259 -0
  88. package/lib/chunk-GAM726CK.mjs +7 -0
  89. package/lib/chunk-GCOB7K5N.mjs +7 -0
  90. package/lib/chunk-GMY5427L.mjs +7 -0
  91. package/lib/chunk-GNC27UEU.mjs +7 -0
  92. package/lib/chunk-H2PJNIYJ.mjs +7 -0
  93. package/lib/chunk-H45UXY6G.mjs +7 -0
  94. package/lib/chunk-HCIDVIOW.mjs +7 -0
  95. package/lib/chunk-HF6LAK3G.mjs +7 -0
  96. package/lib/chunk-HJC7AIBK.mjs +7 -0
  97. package/lib/chunk-HJKM3E56.mjs +7 -0
  98. package/lib/chunk-HTJ5OGP5.mjs +7 -0
  99. package/lib/chunk-HUMEKZT5.mjs +8 -0
  100. package/lib/chunk-HV2MXMGI.mjs +7 -0
  101. package/lib/chunk-HXS7ORUF.mjs +11 -0
  102. package/lib/chunk-I3JKJTLO.mjs +110 -0
  103. package/lib/chunk-I7O6C2B5.mjs +8 -0
  104. package/lib/chunk-IAZB4WIL.mjs +7 -0
  105. package/lib/chunk-IC2C2GOF.mjs +8 -0
  106. package/lib/chunk-IEYG5ATY.mjs +7 -0
  107. package/lib/chunk-INIQ23K6.mjs +7 -0
  108. package/lib/chunk-INIT2UKJ.mjs +7 -0
  109. package/lib/chunk-J7HVXMSW.mjs +7 -0
  110. package/lib/chunk-JVL444U5.mjs +7 -0
  111. package/lib/chunk-K22PA4XL.mjs +7 -0
  112. package/lib/chunk-K2FBZIXY.mjs +7 -0
  113. package/lib/chunk-KLX67VPL.mjs +7 -0
  114. package/lib/chunk-L776PUMV.mjs +7 -0
  115. package/lib/chunk-LQ4DRFUH.mjs +9 -0
  116. package/lib/chunk-LRFAIUN7.mjs +7 -0
  117. package/lib/chunk-LV6G4XTK.mjs +7 -0
  118. package/lib/chunk-M6P5ZZLE.mjs +7 -0
  119. package/lib/chunk-MTMH6H2A.mjs +8 -0
  120. package/lib/chunk-MYTIL2JD.mjs +10 -0
  121. package/lib/chunk-NEVXIGR6.mjs +10 -0
  122. package/lib/chunk-NGSMZZDA.mjs +7 -0
  123. package/lib/chunk-NHWE66K5.mjs +7 -0
  124. package/lib/chunk-NM4MDLK4.mjs +7 -0
  125. package/lib/chunk-NTDN2JQZ.mjs +19 -0
  126. package/lib/chunk-NTOVCTRS.mjs +7 -0
  127. package/lib/chunk-NZ5ZZLKS.mjs +7 -0
  128. package/lib/chunk-OQOZAPCI.mjs +7 -0
  129. package/lib/chunk-OTWRDD6L.mjs +7 -0
  130. package/lib/chunk-P2PJYWGQ.mjs +7 -0
  131. package/lib/chunk-P42X3B4D.mjs +7 -0
  132. package/lib/chunk-P7GSGFJO.mjs +7 -0
  133. package/lib/chunk-PA3MKJVH.mjs +7 -0
  134. package/lib/chunk-PBI4BYWW.mjs +7 -0
  135. package/lib/chunk-PNCONNFJ.mjs +10 -0
  136. package/lib/chunk-PTTHSSQO.mjs +7 -0
  137. package/lib/chunk-PUOX4NBJ.mjs +8 -0
  138. package/lib/chunk-PZTSVQSF.mjs +7 -0
  139. package/lib/chunk-QPF6C5MX.mjs +7 -0
  140. package/lib/chunk-QQZZMKU3.mjs +7 -0
  141. package/lib/chunk-QROPNEGY.mjs +14 -0
  142. package/lib/chunk-QRV2OSIS.mjs +7 -0
  143. package/lib/chunk-QSRAEUGZ.mjs +7 -0
  144. package/lib/chunk-QWT2C74M.mjs +7 -0
  145. package/lib/chunk-RAAANPPG.mjs +7 -0
  146. package/lib/chunk-RACDTRZA.mjs +7 -0
  147. package/lib/chunk-RFEO2KAN.mjs +7 -0
  148. package/lib/chunk-RH3N2H7P.mjs +7 -0
  149. package/lib/chunk-RSWDYIHY.mjs +37 -0
  150. package/lib/chunk-RSYICMZG.mjs +8 -0
  151. package/lib/chunk-SAR5622P.mjs +7 -0
  152. package/lib/chunk-SBIMVCXT.mjs +101 -0
  153. package/lib/chunk-SCKUIE3R.mjs +7 -0
  154. package/lib/chunk-SFURUNJM.mjs +7 -0
  155. package/lib/chunk-SIOZXPFG.mjs +7 -0
  156. package/lib/chunk-SRPWW4A2.mjs +10 -0
  157. package/lib/chunk-SRQDABQ2.mjs +15 -0
  158. package/lib/chunk-SVS6UMDU.mjs +323 -0
  159. package/lib/chunk-T63U4OZJ.mjs +7 -0
  160. package/lib/chunk-TBZMC2VV.mjs +11 -0
  161. package/lib/chunk-TEOLMRDO.mjs +7 -0
  162. package/lib/chunk-TLH7AD35.mjs +7 -0
  163. package/lib/chunk-TNXUU6W7.mjs +14 -0
  164. package/lib/chunk-TQX3PURV.mjs +7 -0
  165. package/lib/chunk-TUACWKIH.mjs +7 -0
  166. package/lib/chunk-TW3N6W5Z.mjs +7 -0
  167. package/lib/chunk-TYYOBZMU.mjs +10 -0
  168. package/lib/chunk-TZE3Y7IQ.mjs +7 -0
  169. package/lib/chunk-UNDIBZWG.mjs +7 -0
  170. package/lib/chunk-VGW4MXXZ.mjs +7 -0
  171. package/lib/chunk-VHI54FBK.mjs +441 -0
  172. package/lib/chunk-VXHDBYMI.mjs +7 -0
  173. package/lib/chunk-W7KFAY55.mjs +7 -0
  174. package/lib/chunk-WFEB5X4U.mjs +8 -0
  175. package/lib/chunk-WIO4XO4F.mjs +7 -0
  176. package/lib/chunk-WJY54JO7.mjs +13 -0
  177. package/lib/chunk-WR2GIKWE.mjs +7 -0
  178. package/lib/chunk-WRU5FJFC.mjs +7 -0
  179. package/lib/chunk-X2PY6MWZ.mjs +7 -0
  180. package/lib/chunk-X65MT4W3.mjs +7 -0
  181. package/lib/chunk-XBG5SP6Q.mjs +7 -0
  182. package/lib/chunk-XCA5AONB.mjs +7 -0
  183. package/lib/chunk-XEFDB2R4.mjs +7 -0
  184. package/lib/chunk-XETCPL7E.mjs +7 -0
  185. package/lib/chunk-Y5CGXLUB.mjs +7 -0
  186. package/lib/chunk-Y6J6QFI2.mjs +7 -0
  187. package/lib/chunk-YAZO75G2.mjs +8 -0
  188. package/lib/chunk-YBU4Z4QV.mjs +7 -0
  189. package/lib/chunk-YMJVMFPY.mjs +7 -0
  190. package/lib/chunk-YPSRZRIT.mjs +7 -0
  191. package/lib/chunk-YS4G22C2.mjs +7 -0
  192. package/lib/chunk-YW2SBL4Z.mjs +7 -0
  193. package/lib/chunk-YYZL7UGV.mjs +7 -0
  194. package/lib/chunk-Z7X534S4.mjs +10 -0
  195. package/lib/chunk-ZE6HKRR4.mjs +9 -0
  196. package/lib/chunk-ZHJP7L3K.mjs +7 -0
  197. package/lib/chunk-ZJKCWBRJ.mjs +7 -0
  198. package/lib/chunk-ZLZRU6MO.mjs +7 -0
  199. package/lib/chunk-ZOVSMN5C.mjs +7 -0
  200. package/lib/chunk-ZPYJPGDK.mjs +7 -0
  201. package/lib/chunk-ZQOZ4EFW.mjs +7 -0
  202. package/lib/chunk-ZUTYVST5.mjs +7 -0
  203. package/lib/chunk-ZXH4MBWP.mjs +7 -0
  204. package/lib/chunk-ZYEE34WO.mjs +7 -0
  205. package/lib/sandforge-autopilot.mjs +157 -0
  206. package/lib/sandforge-backup.mjs +99 -0
  207. package/lib/sandforge-checkpoint.mjs +353 -0
  208. package/lib/sandforge-cleanup.mjs +56 -0
  209. package/lib/sandforge-clone.mjs +7 -0
  210. package/lib/sandforge-compare.mjs +54 -0
  211. package/lib/sandforge-dataops.mjs +7 -0
  212. package/lib/sandforge-empty.mjs +140 -0
  213. package/lib/sandforge-env.mjs +355 -0
  214. package/lib/sandforge-frozen.mjs +263 -0
  215. package/lib/sandforge-mcp.mjs +40 -0
  216. package/lib/sandforge-monitor.mjs +43 -0
  217. package/lib/sandforge-seed.mjs +7 -0
  218. package/lib/sandforge-sync.mjs +7 -0
  219. package/lib/sandforge.mjs +28 -0
  220. package/package.json +52 -4
@@ -0,0 +1,14 @@
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{f as ce}from"./chunk-CGWXQX75.mjs";import{tc as de}from"./chunk-B45CNPUX.mjs";import{b as u,e as f,i as ie,k as w,l as m,r as se,s as N,u as ae,v as D}from"./chunk-7EANH5PY.mjs";import{createHash as fe}from"node:crypto";import*as C from"node:fs/promises";import*as M from"node:path";import*as I from"node:fs/promises";import*as O from"node:path";import*as U from"node:fs";import*as b from"node:path";function Oe(t){let e=b.resolve(t);for(;;){if(U.existsSync(b.join(e,".git"))||U.existsSync(b.join(e,"pnpm-workspace.yaml")))return e;let r=b.dirname(e);if(r===e)throw new Error(`No repository root found above ${t}`);e=r}}function le(t){let e=b.resolve(t);return process.platform==="win32"?e.toLowerCase():e}function _(t){if(!/^[A-Za-z0-9_-]{1,128}$/.test(t))throw new Error(`Not an org id a file of the sas can be named after: "${t}"`);return t}var q=class extends Error{constructor(r,n){super(`Refusing output path inside the repository: ${r} (repo root: ${n}). Frozen-dataset exports, retained-ID lists and working manifests must live in a sas directory OUTSIDE the repo \u2014 versioning them would create a real\u2194anonymized correspondence table.`);this.resolvedPath=r;this.repoRoot=n;this.name="InsideRepoPathError"}resolvedPath;repoRoot},k=class{repoRoot;constructor(e){this.repoRoot=e?b.resolve(e):Oe(process.cwd())}isInsideRepo(e){let r=le(this.repoRoot),n=le(e);if(n===r)return!0;let i=b.relative(r,n);return i!==""&&!i.startsWith("..")&&!b.isAbsolute(i)}assertOutsideRepo(e){if(this.isInsideRepo(e))throw new q(b.resolve(e),this.repoRoot);return b.resolve(e)}};function ot(t){return t.map(({objectApiName:e,why:r,count:n})=>({objectApiName:e,count:n,note:ce(n,r)}))}var ue=/^\d+\.\d+\.\d+$/,Se=/^[0-9a-f]{12}$/,P=class extends Error{constructor(e){super(e),this.name="ManifestError"}};function it(t){let e=(t.now?.()??new Date).toISOString(),r={version:t.version,status:"frozen",frozenAt:e,source:t.source,saltFingerprint:t.saltFingerprint,rulesVersion:t.rulesVersion,volumetry:t.volumetry,controls:{nonReidentification:t.nonReidentification,dryRunLoad:null,author:t.author,date:e},...t.coverage?{coverage:t.coverage}:{}};return W(r),r}function W(t){if(!ue.test(t.version))throw new P(`version must be semver, got ${JSON.stringify(t.version)}`);if(t.status!=="frozen")throw new P(`status must be "frozen", got ${JSON.stringify(t.status)}`);if(!t.frozenAt)throw new P("frozenAt is required");if(!t.source?.orgId||!t.source.decisionDate)throw new P("source.orgId and source.decisionDate are required");if(!Se.test(t.saltFingerprint))throw new P("saltFingerprint must be 12 lowercase hex chars of the salt SHA-256");if(!ue.test(t.rulesVersion))throw new P(`rulesVersion must be semver, got ${JSON.stringify(t.rulesVersion)}`);if(typeof t.volumetry?.budgetMax!="number"||!t.volumetry.measured)throw new P("volumetry.budgetMax and volumetry.measured are required");if(!t.controls?.nonReidentification)throw new P("controls.nonReidentification is required");if(!t.controls.author||!t.controls.date)throw new P("controls.author and controls.date are required");let e=t.coverage;if(e!==void 0&&(typeof e.objects!="number"||typeof e.truncated!="boolean"||typeof e.maxNodes!="number"||!Array.isArray(e.unboundedObjects)||!Array.isArray(e.filesLeftOut)||e.leftToThePlatform!==void 0&&!Array.isArray(e.leftToThePlatform)||e.exclusionCosts!==void 0&&!Array.isArray(e.exclusionCosts)||e.requiredLeftEmpty!==void 0&&!Array.isArray(e.requiredLeftEmpty)||e.keptWithoutARule!==void 0&&!Array.isArray(e.keptWithoutARule)||e.encryptedNotKept!==void 0&&!Array.isArray(e.encryptedNotKept)))throw new P("coverage, when present, needs objects, truncated, maxNodes, unboundedObjects and filesLeftOut, and a list of what it left to the platform, of what its exclusions cost, of the required fields the rules leave empty, of the fields kept without a rule, or of the encrypted fields not kept, if it names any")}function pe(t){return W(t),`${JSON.stringify(t,null,2)}
8
+ `}function st(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new P("Manifest must be a JSON object");let e=t;return W(e),e}var V="platform-records.json",G=class extends Error{constructor(e){let r=e.checks.filter(n=>!n.passed).map(n=>`${n.name} (${n.violations.length} violation(s))`).join(", ");super(`Refusing to write the frozen dataset: non-reidentification control FAILED [${r}]. A FAIL means nothing is written or versioned.`),this.name="ControlNotPassedError"}},ge=class{guard;constructor(e){this.guard=e??new k}async write(e,r,n,i){if(!i.passed)throw new G(i);let o=this.guard.assertOutsideRepo(e),s=this.guard.assertOutsideRepo(O.join(o,"data"));await I.mkdir(s,{recursive:!0});for(let l of await I.readdir(s))l.endsWith(".json")&&await I.rm(this.guard.assertOutsideRepo(O.join(s,l)));let a=[],d=async(l,p)=>{let g=this.guard.assertOutsideRepo(l);await I.writeFile(g,`${JSON.stringify(p)}
9
+ `,"utf8"),a.push(g)},c=this.guard.assertOutsideRepo(O.join(o,"manifest.json"));await I.writeFile(c,pe(n),"utf8"),a.push(c);for(let l of r.objects)await d(O.join(s,`${l.objectApiName}.json`),{objectApiName:l.objectApiName,records:l.records});return await d(O.join(o,"record-types.json"),r.recordTypes),await d(O.join(o,"personcontact-sidecar.json"),r.personContactSidecar),await d(O.join(o,V),{...r.standardPricebook?{standardPricebook:r.standardPricebook}:{}}),{dir:o,files:a}}};var K="manifest.json",Fe=["record-types.json","personcontact-sidecar.json",V],Z="data",Ee="sha256:";async function gt(t){let e=await H(M.join(t,K));if(e===void 0)throw new Error(`No frozen dataset at ${t}: it holds no ${K}.`);let r=[{name:K,content:ke(e)}];for(let i of Fe){let o=await H(M.join(t,i));o!==void 0&&r.push({name:i,content:o})}for(let i of await xe(M.join(t,Z))){let o=await H(M.join(t,Z,i));o!==void 0&&r.push({name:`${Z}/${i}`,content:o})}let n=fe("sha256");for(let{name:i,content:o}of r.sort((s,a)=>me(s.name,a.name)))n.update(`${i}\0${fe("sha256").update(o).digest("hex")}
10
+ `);return`${Ee}${n.digest("hex")}`}async function xe(t){let e;try{e=await C.readdir(t)}catch(r){if(r.code==="ENOENT")return[];throw r}return e.filter(r=>r.endsWith(".json"))}async function H(t){try{return await C.readFile(t)}catch(e){if(e.code==="ENOENT")return;throw e}}function ke(t){let e;try{e=JSON.parse(t.toString("utf8"))}catch{return t}if(Y(e)&&Y(e.controls)){let r={...e.controls};delete r.dryRunLoad,e={...e,controls:r}}return Buffer.from(X(e),"utf8")}function X(t){return Array.isArray(t)?`[${t.map(X).join(",")}]`:Y(t)?`{${Object.keys(t).sort(me).map(r=>`${JSON.stringify(r)}:${X(t[r])}`).join(",")}}`:JSON.stringify(t)??"null"}function Y(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function me(t,e){return t===e?0:t<e?-1:1}import*as h from"node:fs/promises";import*as z from"node:path";var yt=4*1024*1024,wt=64*1024*1024;var he=1e4,L=u().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),S=u().min(1).max(40),bt=m({forgeId:u().min(1).max(200),targetOrgId:u().min(1).max(128),timestamp:S,duration:f().nonnegative(),status:ae(["success","partial","failure"]),cancelled:D(!0).optional(),writtenBetween:m({first:S,last:S}).optional(),retryOf:u().min(1).max(200).optional(),objects:w(m({objectApiName:u().regex(/^[A-Za-z][A-Za-z0-9_]*$/),ids:w(L)})),linked:f().int().nonnegative(),mayHaveBeenWritten:f().int().nonnegative().optional(),undo:m({removedAt:S,deleted:f().int().nonnegative(),alreadyGone:f().int().nonnegative(),kept:f().int().nonnegative(),refused:f().int().nonnegative(),notReached:f().int().nonnegative().optional(),notVisible:f().int().nonnegative().optional()}).optional(),removalStamps:N(L,S).optional(),removalSpans:w(m({first:S,last:S,userId:L})).optional(),removalLeft:w(L).optional(),sweep:m({sweptAt:S,deleted:f().int().nonnegative(),keptChanged:f().int().nonnegative(),refused:f().int().nonnegative()}).optional(),inJournal:m({journalId:u().min(1).max(200),part:f().int().nonnegative(),left:w(m({objectApiName:u().regex(/^[A-Za-z][A-Za-z0-9_]*$/),count:f().int().nonnegative()}))}).optional()}),Rt=m({version:D(1),plans:w(ie())}),Pt=m({version:D(1),runs:w(m({forgeId:u().min(1).max(300),ids:w(L),late:w(L).optional()}))});var J="referenceid-mapping.json",Ne=/^referenceid-mapping\.([A-Za-z0-9_-]{1,128})\.json$/,Me=/^referenceid-mapping\.([A-Za-z0-9_-]{1,128})\.load-\d{1,16}\.ndjson$/,T=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Q=new Set;function De(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}var _e=m({at:u().min(1).max(40),object:u().regex(/^[A-Za-z][A-Za-z0-9_]{0,79}$/),created:w(se([u().min(1).max(400),u().regex(T)])).max(1e4)}),Ce=m({journal:m({startedAt:u().min(1).max(40),pid:f().int().positive(),runUserId:u().regex(T).optional()})});function Be(t){let e,r={},n=new Map,i;for(let o of t.split(`
11
+ `)){if(o.trim()==="")continue;let s;try{s=JSON.parse(o)}catch{continue}if(!e){let c=Ce.safeParse(s);c.success&&(e=c.data.journal);continue}let a=_e.safeParse(s);if(!a.success)continue;let d=n.get(a.data.object)??[];for(let[c,l]of a.data.created)Object.prototype.hasOwnProperty.call(r,c)||d.push(c),r[c]=l;n.set(a.data.object,d),i=a.data.at}if(!(!e||i===void 0||Object.keys(r).length===0))return{startedAt:e.startedAt,pid:e.pid,load:{updatedAt:i,mapping:r,created:[...n].filter(([,o])=>o.length>0).map(([o,s])=>({objectApiName:o,referenceIds:s})),load:{startedAt:e.startedAt,endedAt:i},...e.runUserId?{runUserId:e.runUserId}:{}}}}function Je(t){return`referenceid-mapping.${_(t)}.json`}async function B(t){let e;try{e=await h.readFile(t,"utf8")}catch(r){if(r.code==="ENOENT")return;throw r}return JSON.parse(e)}async function At(t,e){let r=e.assertOutsideRepo(t),n;try{n=await h.readdir(r)}catch(o){if(o.code==="ENOENT")return[];throw o}let i=new Set(n.flatMap(o=>Ne.exec(o)?.[1]??Me.exec(o)?.[1]??[]));if(n.includes(J)){let s=(await B(e.assertOutsideRepo(z.join(r,J))))?.orgId;typeof s=="string"&&$e(s)&&i.add(s)}return[...i].sort()}function $e(t){try{return _(t),!0}catch{return!1}}var Ue=w(m({objectApiName:u(),referenceIds:w(u())})),qe=m({startedAt:u(),endedAt:u()}),We=m({first:u(),last:u()}),Ge=m({removedAt:u(),deleted:f(),alreadyGone:f(),kept:f(),refused:f(),notReached:f().optional()}),Ve=N(u(),u()),Ke=w(m({first:u(),last:u(),userId:u()})),ye=N(u(),u()),ee=u().regex(T);function v(t,e){let r=t.safeParse(e);return r.success?r.data:void 0}function A(t){if(typeof t!="object"||t===null)return;let e=t,r=typeof e.mapping=="object"&&e.mapping!==null?Object.fromEntries(Object.entries(e.mapping).filter(y=>typeof y[1]=="string")):{},n=v(Ue,e.created),i=v(qe,e.load),o=v(We,e.writtenBetween),s=v(Ge,e.removal),a=v(Ve,e.removalStamps),d=v(Ke,e.removalSpans),c=v(ye,e.personContacts),l=v(ye,e.withTheirRecord),p=v(ee,e.runUserId),g=v(w(ee),e.madeEarlier),R=v(w(ee),e.lateEarlier);return{updatedAt:typeof e.updatedAt=="string"?e.updatedAt:"",mapping:r,...n?{created:n}:{},...i?{load:i}:{},...o?{writtenBetween:o}:{},...s?{removal:s}:{},...a?{removalStamps:a}:{},...d?{removalSpans:d}:{},...c?{personContacts:c}:{},...l?{withTheirRecord:l}:{},...p?{runUserId:p}:{},...g?{madeEarlier:g}:{},...R?{lateEarlier:R}:{}}}function F(t){return Array.isArray(t.earlier)?t.earlier.flatMap(e=>A(e)??[]):[]}function E(t){return t.load?.endedAt??t.updatedAt}function Ze(t,e){return t.slice(0,15)===e.slice(0,15)}function j(t){return t.slice(0,15)}function we(t,e){let r={};for(let[n,i]of Object.entries(t??{}))Object.prototype.hasOwnProperty.call(e,i)?Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=i):delete e[n];return r}function be(t,e){if(e.size===0)return t;let r=Object.fromEntries(Object.entries(t.mapping).filter(([,d])=>!e.has(j(d)))),n=we(t.personContacts,r),i=we(t.withTheirRecord,r),o=t.created?.map(({objectApiName:d,referenceIds:c})=>({objectApiName:d,referenceIds:c.filter(l=>Object.prototype.hasOwnProperty.call(r,l))})).filter(d=>d.referenceIds.length>0),s=Object.fromEntries(Object.entries(t.removalStamps??{}).filter(([d])=>!e.has(j(d)))),a={...t,mapping:r};return delete a.removalStamps,delete a.personContacts,delete a.withTheirRecord,{...a,...o?{created:o}:{},...Object.keys(s).length>0?{removalStamps:s}:{},...Object.keys(n).length>0?{personContacts:n}:{},...Object.keys(i).length>0?{withTheirRecord:i}:{}}}function Re(t){return t.created?t.created.some(e=>e.referenceIds.length>0):Object.keys(t.mapping).length>0}var Pe=class{constructor(e,r){this.sasDir=e;this.guard=r?.guard??new k,this.orgId=r?.orgId??"";let n=r?.organizationId;this.askOrganizationId=typeof n=="function"?n:async()=>n,this.now=r?.now??(()=>new Date)}sasDir;guard;orgId;askOrganizationId;organizationId;now;get filePath(){return this.guard.assertOutsideRepo(z.join(this.sasDir,this.orgId===""?J:Je(this.orgId)))}get singleFilePath(){return this.orgId===""?void 0:this.guard.assertOutsideRepo(z.join(this.sasDir,J))}get journalStem(){return this.orgId===""?"referenceid-mapping":`referenceid-mapping.${_(this.orgId)}`}journalPath(e){let r=typeof e=="string"?Date.parse(e):e.getTime();return this.guard.assertOutsideRepo(z.join(this.sasDir,`${this.journalStem}.load-${Math.max(0,Math.trunc(r))}.ndjson`))}retiring=new Map;journal(e){let r=this.journalPath(e),n=!1,i=!1,o=!1,s,a=Promise.resolve(),d;Q.add(r);let c=p=>{a=a.then(async()=>{if(!(d!==void 0||i))try{if(!n){n=!0,await h.mkdir(z.dirname(r),{recursive:!0});let g={journal:{startedAt:e.toISOString(),pid:process.pid,...s?{runUserId:s}:{}}};await h.appendFile(r,`${JSON.stringify(g)}
12
+ `,"utf8")}await h.appendFile(r,`${JSON.stringify(p)}
13
+ `,"utf8")}catch(g){d=g instanceof Error?g.message:String(g)}})},l=async()=>{await a,i=!0,await h.rm(r,{force:!0})};return this.retiring.set(r,l),{writtenAs:p=>{T.test(p)&&(s=p)},created:(p,g)=>{let R=g.filter(([y,x])=>y!==""&&T.test(x));if(R.length!==0){o=!0;for(let y=0;y<R.length;y+=1e4)c({at:this.now().toISOString(),object:p,created:R.slice(y,y+1e4)})}},flush:async()=>(await a,d),close:async()=>{await a,this.retiring.delete(r),(i||!o)&&await h.rm(r,{force:!0}),i=!0,Q.delete(r)}}}async stoppedLoads(e){let r;try{r=await h.readdir(this.guard.assertOutsideRepo(this.sasDir))}catch(s){if(s.code==="ENOENT")return[];throw s}let n=`${this.journalStem}.load-`,i=new Set(e.flatMap(s=>s.load?[s.load.startedAt]:[])),o=[];for(let s of r){if(!s.startsWith(n)||!/^\d{1,16}\.ndjson$/.test(s.slice(n.length)))continue;let a=this.guard.assertOutsideRepo(z.join(this.sasDir,s));if(Q.has(a))continue;let d;try{d=await h.readFile(a,"utf8")}catch{continue}let c=Be(d);!c||i.has(c.startedAt)||c.pid!==process.pid&&De(c.pid)||o.push({file:a,load:c.load})}return o}async load(){let e=await this.read();return e===void 0||await this.writtenToAnotherOrg(e)?new Map:new Map(Object.entries(e.mapping??{}))}async previousLoads(){let e=await this.read();if(e===void 0||await this.writtenToAnotherOrg(e))return[];let r=A(e);return[...r?[r]:[],...F(e)].map(n=>({mapping:new Map(Object.entries(n.mapping)),...n.created?{created:n.created}:{},...n.writtenBetween?{writtenBetween:n.writtenBetween}:{},endedAt:E(n),...n.removalStamps?{removalStamps:n.removalStamps}:{}}))}async recorded(){return(await this.recordedLoads())[0]}async recordedLoads(){let e=await this.read();if(e===void 0)return[];let r=typeof e.orgId=="string"?e.orgId:"",n=A(e);return[...n?[this.recordedOf(n,r)]:[],...F(e).map(i=>({...this.recordedOf(i,r),earlier:!0}))]}recordedOf(e,r){return{orgId:r,mapping:new Map(Object.entries(e.mapping)),...e.created?{created:e.created}:{},...e.load?{startedAt:e.load.startedAt}:{},endedAt:E(e),...e.writtenBetween?{writtenBetween:e.writtenBetween}:{},...e.removal?{removal:e.removal}:{},removalStamps:e.removalStamps??{},removalSpans:e.removalSpans??[],...e.personContacts?{personContacts:e.personContacts}:{},...e.withTheirRecord?{withTheirRecord:e.withTheirRecord}:{},...e.runUserId?{runUserId:e.runUserId}:{},...e.madeEarlier?{madeEarlier:e.madeEarlier}:{},...e.lateEarlier?{lateEarlier:e.lateEarlier}:{}}}async isStale(){let e=await this.read();return e!==void 0&&await this.writtenToAnotherOrg(e)}async writtenToAnotherOrg(e){let r=e.organizationId;if(r===void 0)return!1;let n=await this.currentOrganizationId();return n!==void 0&&!Ze(r,n)}currentOrganizationId(){return this.organizationId??=this.askOrganizationId(),this.organizationId}async read(){return(await this.readWithJournals()).payload}async readFile(){let e=await B(this.filePath);if(e!==void 0)return e;let r=this.singleFilePath;if(r===void 0)return;let n=await B(r);return n?.orgId===this.orgId?n:void 0}async readWithJournals(){let e=await this.readFile(),r=e?[A(e),...F(e)]:[],n=await this.stoppedLoads(r.filter(a=>a!==void 0));if(n.length===0)return{payload:e,journals:[]};let i=[...r.filter(a=>a!==void 0),...n.map(({load:a})=>a)].sort((a,d)=>Date.parse(E(d))-Date.parse(E(a))),[o,...s]=i;return{payload:{version:1,orgId:typeof e?.orgId=="string"?e.orgId:this.orgId,...e?.organizationId!==void 0?{organizationId:e.organizationId}:{},...o,...s.length>0?{earlier:s}:{}},journals:n.map(({file:a})=>a)}}async dropJournals(e){for(let r of e)await h.rm(r,{force:!0}).catch(()=>{})}async write(e){let r=this.filePath;await h.mkdir(z.dirname(r),{recursive:!0}),await h.writeFile(r,`${JSON.stringify(e,null,2)}
14
+ `,"utf8");let n=this.singleFilePath;if(n!==void 0)try{(await B(n))?.orgId===this.orgId&&await h.rm(n)}catch{}}async keptLoads(e,r,n=[]){if(e===void 0||e.orgId!==this.orgId)return[];if(await this.writtenToAnotherOrg(e))return[];let i=new Set(r.map(j)),o=new Set(n),s=A(e);return[...s?[s]:[],...F(e)].map(a=>be(a,i)).filter(a=>Re(a)||o.has(E(a)))}async persist(e,r){let{payload:n,journals:i}=await this.readWithJournals(),o=r?.earlier?await this.keptLoads(n,r.earlier.settled,r.earlier.stillToSweep):[],s=await this.currentOrganizationId(),a=this.now().toISOString(),d=p=>Object.fromEntries(Object.entries(p??{}).filter(([g,R])=>e.has(g)&&e.has(R))),c=d(r?.personContacts),l=d(r?.withTheirRecord);if(await this.write({version:1,orgId:this.orgId,...s!==void 0?{organizationId:s}:{},updatedAt:a,mapping:Object.fromEntries([...e.entries()].sort(([p],[g])=>p.localeCompare(g))),...r?{created:r.created.map(({objectApiName:p,referenceIds:g})=>({objectApiName:p,referenceIds:g.filter(R=>e.has(R))})).filter(p=>p.referenceIds.length>0),load:{startedAt:r.startedAt.toISOString(),endedAt:a},...r.writtenBetween?{writtenBetween:{...r.writtenBetween}}:{},...Object.keys(c).length>0?{personContacts:c}:{},...Object.keys(l).length>0?{withTheirRecord:l}:{},...r.runUserId?{runUserId:r.runUserId}:{}}:{},...o.length>0?{earlier:o}:{}}),r?.earlier&&await this.dropJournals(i),r){let p=this.journalPath(r.startedAt),g=this.retiring.get(p);g?await g():await h.rm(p,{force:!0}).catch(()=>{})}}async recordRemoval(e,r){let{payload:n,journals:i}=await this.readWithJournals(),o=A(n);if(n===void 0||o===void 0)return!1;let s=[o,...F(n)],a=s.findIndex(p=>E(p)===e);if(a<0)return!1;let d=new Set(r.gone.map(j)),[c,...l]=s.map((p,g)=>be(g===a?Xe(p,r):p,d));return await this.write({version:1,orgId:typeof n.orgId=="string"?n.orgId:"",...n.organizationId!==void 0?{organizationId:n.organizationId}:{},...c,updatedAt:this.now().toISOString(),...l.length>0?{earlier:l}:{}}),await this.dropJournals(i),!0}async recordMade(e,r,n=[],i=[]){let{payload:o,journals:s}=await this.readWithJournals(),a=A(o);if(o===void 0||a===void 0)return!1;let d=[a,...F(o)],c=d.findIndex(y=>E(y)===e);if(c<0)return!1;let l=[...i],p=y=>{let x=ve(y.madeEarlier,r,l),oe=ve(y.lateEarlier,n,l),$={...y};return delete $.madeEarlier,delete $.lateEarlier,{...$,...x.length>0?{madeEarlier:x}:{},...oe.length>0?{lateEarlier:oe}:{}}},[g,...R]=d.map((y,x)=>x===c?p(y):y);return await this.write({version:1,orgId:typeof o.orgId=="string"?o.orgId:"",...o.organizationId!==void 0?{organizationId:o.organizationId}:{},...g,...R.length>0?{earlier:R}:{}}),await this.dropJournals(s),!0}async letSweptGo(e){if(e.length===0)return!1;let{payload:r,journals:n}=await this.readWithJournals(),i=A(r);if(r===void 0||i===void 0)return!1;let o=new Set(e),s=F(r),a=s.filter(d=>Re(d)||!o.has(E(d)));return a.length===s.length?!1:(await this.write({version:1,orgId:typeof r.orgId=="string"?r.orgId:"",...r.organizationId!==void 0?{organizationId:r.organizationId}:{},...i,...a.length>0?{earlier:a}:{}}),await this.dropJournals(n),!0)}async recordStamps(e){let{payload:r,journals:n}=await this.readWithJournals(),i=A(r);if(r===void 0||i===void 0)return!1;let o=[i,...F(r)],s=o.map(c=>He(c,e));if(s.every((c,l)=>c===o[l]))return!1;let[a,...d]=s;return await this.write({version:1,orgId:typeof r.orgId=="string"?r.orgId:"",...r.organizationId!==void 0?{organizationId:r.organizationId}:{},...a,...d.length>0?{earlier:d}:{}}),await this.dropJournals(n),!0}};function ve(t,e,r=[]){let n=new Map,i=new Set(r.map(j)),o=[];for(let s of[...t??[],...e]){let a=j(s),d=a.slice(0,3),c=n.get(d)??0;!T.test(s)||i.has(a)||c>=he||(i.add(a),n.set(d,c+1),o.push(s))}return o}function He(t,e){let r=new Set(Object.values(t.mapping).map(j)),n=Object.entries(e).filter(([o])=>r.has(j(o)));if(n.length===0)return t;let i=new Set(n.map(([o])=>j(o)));return{...t,removalStamps:{...Object.fromEntries(Object.entries(t.removalStamps??{}).filter(([o])=>!i.has(j(o)))),...Object.fromEntries(n)}}}function Xe(t,e){let r={...t.removalStamps,...e.stamps},n=[...t.removalSpans??[],...e.span?[e.span]:[]],i=e.mark??t.removal;return{...t,...i?{removal:i}:{},...Object.keys(r).length>0?{removalStamps:r}:{},...n.length>0?{removalSpans:n}:{}}}var je={BusinessHours:["Name"]},Ot=["DUPLICATE_VALUE","DUPLICATES_DETECTED","duplicate value found"];var Ye=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Qe=/^[A-Za-z][A-Za-z0-9_]*$/;function te(t){return t.slice(0,15)}function re(t,e){let r=t.mapping.get(e);return typeof r=="string"&&Ye.test(r)?r:void 0}function Ie(t){let e=new Set((t.created??[]).flatMap(n=>n.referenceIds)),r=new Set;for(let n of t.mapping.keys()){if(e.has(n))continue;let i=re(t,n);i&&r.add(te(i))}return r}function et(t){let e=new Set((t.created??[]).flatMap(i=>i.referenceIds)),r=[...Object.entries(t.personContacts??{}),...Object.entries(t.withTheirRecord??{})];for(let i=!0;i;){i=!1;for(let[o,s]of r)e.has(o)||!e.has(s)||(e.add(o),i=!0)}let n=new Set;for(let[i]of r){let o=e.has(i)?re(t,i):void 0;o&&n.add(te(o))}return n}function Ae(t){let e=Ie(t),r=new Map;for(let{objectApiName:o,referenceIds:s}of t.created??[])Qe.test(o)&&r.set(o,[...r.get(o)??[],...s]);let n=new Set,i=[];for(let[o,s]of[...r].reverse()){let a=[];for(let d of[...s].reverse()){let c=re(t,d);if(!c)continue;let l=te(c);e.has(l)||n.has(l)||(n.add(l),a.push(c))}a.length>0&&i.push({objectApiName:o,ids:a})}return i}function ne(t){return de(t.removal)?[]:Ae(t).filter(e=>!ze(e.objectApiName))}function ze(t){return Object.prototype.hasOwnProperty.call(je,t)}function tt(t){return Ae(t).filter(e=>ze(e.objectApiName)).map(({objectApiName:e,ids:r})=>({objectApiName:e,count:r.length}))}function xt(t){return t.find(e=>ne(e).length>0)??t[0]}function kt(t,e){return t.filter(r=>r.endedAt!==e.endedAt&&r.created!==void 0&&ne(r).length===0)}function Lt(t){let e=t.created!==void 0,r=et(t),n=[...Ie(t)].filter(o=>!r.has(o)),i=tt(t);return{orgId:t.orgId,loadedAt:t.endedAt,created:ne(t).map(({objectApiName:o,ids:s})=>({objectApiName:o,count:s.length})),linked:e?n.length:0,recorded:e,...t.removal?{removed:t.removal}:{},...t.earlier?{earlier:!0}:{},...i.length>0?{keptByThePlatform:i}:{}}}export{Oe as a,_ as b,q as c,k as d,ot as e,it as f,pe as g,st as h,V as i,ge as j,gt as k,je as l,Ot as m,Je as n,At as o,Pe as p,Ae as q,ne as r,tt as s,xt as t,kt as u,Lt as v};
@@ -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{c,j as d}from"./chunk-6MUEPV7M.mjs";import{b as o}from"./chunk-CA5NAXSU.mjs";import{n as a}from"./chunk-B45CNPUX.mjs";var u=6e4,g=class{tokenCache=new Map;sfdxBridge;setSfdxBridge(e){this.sfdxBridge=e}async authenticate(e){switch(e.method){case"oauth_web":return this.authenticateOAuth(e);case"oauth_device":return{success:!1,error:"OAuth device flow handled via DeviceLogin and SfdxBridge.loginWithRefreshToken()"};case"jwt":return this.authenticateJwt(e);case"usernamePassword":return this.authenticateUsernamePassword(e);case"sfdx_import":return this.importFromSfdx(e.username);default:return{success:!1,error:`Unsupported auth method: ${e.method}`}}}buildConnectionConfig(e,r){return{loginUrl:e.loginUrl,clientId:e.clientId,clientSecret:e.clientSecret,accessToken:r.accessToken,refreshToken:r.refreshToken,instanceUrl:r.instanceUrl,username:e.username}}async validateConnection(e,r){let{jsforce:t}=await import("./chunk-GAM726CK.mjs"),n=new t.Connection({accessToken:e,instanceUrl:r}),{identity:i,orgResult:h}=await c(n,async()=>({identity:await n.identity(),orgResult:await n.query(`SELECT Id, Name, OrganizationType, IsSandbox FROM Organization LIMIT ${a.singleRecord}`)})),s=h.records[0];return{userId:i.user_id,username:i.username,displayName:i.display_name,orgId:s.Id,orgName:s.Name,orgType:s.OrganizationType,isSandbox:s.IsSandbox}}isTokenValid(e){let r=this.tokenCache.get(e);return r?Date.now()<r.expiresAt:!1}cacheToken(e,r,t){this.tokenCache.set(e,{token:r,expiresAt:Date.now()+t})}getCachedToken(e){let r=this.tokenCache.get(e);if(!r||Date.now()>=r.expiresAt){this.tokenCache.delete(e);return}return r.token}clearTokenCache(e){this.tokenCache.delete(e)}clearAllTokens(){this.tokenCache.clear()}async authenticateOAuth(e){return{success:!1,error:"OAuth handled via SfdxBridge.loginWeb()"}}async authenticateJwt(e){return{success:!1,error:"JWT handled via SfdxBridge.loginJwt()"}}async authenticateUsernamePassword(e){if(!e.username||!e.password)return{success:!1,error:"Username and password are required"};try{let{jsforce:r}=await import("./chunk-GAM726CK.mjs"),t=new r.Connection({loginUrl:e.loginUrl}),n=await d(t.login(e.username,e.password+(e.securityToken??"")),u,`${new URL(e.loginUrl).host} did not answer within ${u/1e3} s: check that this machine reaches it, through its proxy if it has one`);return{success:!0,accessToken:t.accessToken??void 0,instanceUrl:t.instanceUrl,userId:n.id,orgId:n.organizationId}}catch(r){return{success:!1,error:`Login failed: ${o(r)}`}}}async importFromSfdx(e){if(!this.sfdxBridge)return{success:!1,error:"SFDX bridge not configured"};if(!e)return{success:!1,error:"An SFDX import needs the username of the org to import"};try{let r=await this.sfdxBridge.findOrg(e);return r?{success:!0,accessToken:r.credentials.accessToken,instanceUrl:r.credentials.instanceUrl,orgId:r.org.orgId}:{success:!1,error:`No connected org for ${e} found in SF CLI`}}catch(r){return{success:!1,error:`SFDX import failed: ${o(r)}`}}}};export{g as a};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{j as Z,l as N}from"./chunk-342FN7AO.mjs";import{A as Q,r as Y,s as T,u as K,y as J}from"./chunk-6MUEPV7M.mjs";import{z as H}from"./chunk-HJC7AIBK.mjs";import{d as G}from"./chunk-OTWRDD6L.mjs";import{Pa as se,Qa as M,Za as re,ka as ee,r as V,s as X,va as te,w as z}from"./chunk-VXHDBYMI.mjs";import{b as U,c as B}from"./chunk-ZLZRU6MO.mjs";import{b as $}from"./chunk-CA5NAXSU.mjs";import{Jc as I,Nc as C,Sc as S,Vc as F,Wc as q}from"./chunk-B45CNPUX.mjs";var _e=5e3,x=2e3,le=1e3,me={masking:{during:"during the masking",records:"records it masked"},restore:{during:"during the restore",records:"records it put back"},erasure:{during:"during the erasure",records:"records it overwrote"}};function ne(e,s){let r=new Set(s.map(t=>t.toLowerCase()));return(e?.objects??[]).filter(t=>r.has(t.objectApiName.toLowerCase())).filter(t=>(t.duplicateRules??[]).length>0).map(t=>({objectApiName:t.objectApiName,rules:(t.duplicateRules??[]).map(n=>n.name)}))}function ae(e){return typeof e=="string"?e.slice(0,15):""}async function pe(e,s){let{rules:r}=s,t=0,n=a=>(t++,e.query(a));try{let a=H(new Date(Date.parse(s.since)-le).toISOString()),i=new Set([...s.masked].map(ae)),d=await n(`SELECT Id, DuplicateRecordSetId, RecordId FROM DuplicateRecordItem WHERE CreatedDate >= ${a} LIMIT ${x+1}`),u=d.done===!1||d.records.length>x,c=d.records.slice(0,x),p=new Set(c.filter(o=>i.has(ae(o.RecordId))).map(o=>String(o.DuplicateRecordSetId??"")).filter(o=>o!=="")),l=c.filter(o=>p.has(String(o.DuplicateRecordSetId??""))).length,m=0;for(let o of G([...p])){let f=await n(`SELECT Id FROM DuplicateRecordSet WHERE CreatedDate >= ${a} AND Id IN (${o})`);m+=f.records.length}return{rules:r,sets:m,items:l,...u?{atLeast:!0}:{},requests:t}}catch(a){return{rules:r,sets:0,items:0,unread:$(a),requests:t}}}function Ie(e,s,r){let t=r.now??Date.now,n=r.sleep??(l=>new Promise(m=>setTimeout(m,l))),a=new Set(s.map(l=>l.objectApiName.toLowerCase())),i=l=>a.has(l.toLowerCase()),d,u=0,c=new Set,p=0;return{covers:i,beforeWrite:l=>{i(l)&&d===void 0&&(u=t())},wrote:(l,m)=>{if(!i(l))return;let o=!1;for(let h of m)typeof h!="string"||h===""||(c.add(h),o=!0);if(!o)return;p=t();let f=u;d??=e.serverTime().then(h=>{let A=Date.parse(h);return Number.isNaN(A)?{unread:`it answered "${h}"`}:{at:new Date(A-Math.max(0,t()-f)).toISOString()}},h=>({unread:$(h)}))},read:async()=>{if(c.size===0)return;let l=d?await d:void 0;if(!l||"unread"in l)return{rules:s,sets:0,items:0,unread:l?`the org's clock: ${l.unread}`:"the org's clock was not read",requests:l?1:0};let m=Math.max(0,p+r.settleMs-t());m>0&&await n(m);let o=await pe(e,{rules:s,since:l.at,masked:c});return{...o,requests:(o.requests??0)+1,waitedMs:m}}}}function Ce(e){return e!==void 0&&(e.sets>0||e.items>0||e.unread!==void 0)}function ge(e){return e.map(s=>`"${s}"`).join(", ")}function fe(e){return e<=0?"without waiting":e<1e3?"after waiting less than 1 s":`after waiting ${Math.round(e/1e3)} s`}function Fe(e,s,r="masking"){if(!e||e.rules.length===0)return"";let t=me[r],n=e.rules.map(d=>`${d.objectApiName} (${ge(d.rules)})`).join(", ");if(e.unread!==void 0)return`What the duplicate rules of ${s} on ${n} wrote ${t.during} could not be read (${e.unread}): a duplicate record set they wrote stays.`;let a=e.requests!==void 0?` Read in ${e.requests} request(s), ${fe(e.waitedMs??0)}.`:"";if(e.sets===0&&e.items===0)return`The duplicate rules of ${s} on ${n} wrote nothing for the ${t.records}.`+a;let i=e.atLeast===!0?"at least ":"";return`The duplicate rules of ${s} on ${n} wrote ${i}${e.sets} duplicate record set(s) and ${i}${e.items} item(s) ${t.during}, for ${t.records}: kept, as they name records that stay.${a}`}var he="AUTOMATION_NOT_ACCEPTED",we="EMAILS_EXCEEDED",Oe="ORG_TEMPORARILY_UNREACHABLE";function be(e,s){return e==="cleanup"||e==="empty"?{delete:[...s]}:e==="restore"?{bringBack:[...s],giveBack:[...s]}:e==="emptyUndo"?{bringBack:[...s]}:{giveBack:[...s]}}function Ae(e,s){let r=e==="cleanup"||e==="empty"?"delete":"update";return s.filter(t=>t.records>0).map(t=>({objectApiName:t.objectApiName,write:r,records:t.records}))}var E={masking:{heading:"masking automation: what {org} runs as the masking writes over the records",the:"the masking",this:"this masking",writes:"writes over",verb:"mask",nothing:"Nothing was written.",flag:"to mask all the same"},restore:{heading:"restore automation: what {org} runs as the restore puts the backup's values back",the:"the restore",this:"this restore",writes:"puts back",verb:"restore",nothing:"Nothing was written.",flag:"to restore all the same"},cleanup:{heading:"cleanup automation: what {org} runs as the cleanup deletes the records",the:"the cleanup",this:"this cleanup",writes:"deletes",verb:"delete",nothing:"Nothing was deleted.",flag:"to delete all the same"},empty:{heading:"emptying automation: what {org} runs as the emptying deletes the records",the:"the emptying",this:"this emptying",writes:"deletes",verb:"empty",nothing:"Nothing was deleted.",flag:"to empty all the same"},emptyUndo:{heading:"undo automation: what {org} runs as the undo brings the records back",the:"the undo",this:"this undo",writes:"brings back",verb:"undo",nothing:"Nothing was written.",flag:"to undo all the same"}},$e={masking:"masking",restore:"restore",cleanup:"cleanup",empty:"empty",emptyUndo:"undo"};function Ke(e){return e.erasure===!0?"erasure":e.fromPage===!0?"page":void 0}var ye={"accept-automation":"acceptAutomation","accept-emails":"acceptEmails","mute-automation":"muteAutomation"},De={"accept-emails":"the confirmation's box that lets the org send these emails","mute-automation":"the confirmation's box that mutes the target's automation"},Re={mask:"masking",restore:"restore",delete:"cleanup",erase:"erasure",empty:"emptying",undo:"undo"};function oe(e){let s=r=>De[r]??`--${r}`;return e.replace(/\bAdd --accept-automation to (mask|restore|delete|erase|empty|undo) all the same\b/g,(r,t)=>`Confirm the ${Re[t]??t} from its confirmation, which lists what fires, to ${t} all the same`).replace(/\bWith --mute-automation,/g,`With ${s("mute-automation")} ticked,`).replace(/\bAdd --(accept-emails|mute-automation)\b/g,(r,t)=>`Tick ${s(t)}`).replace(/(^|[.:;] )--(accept-emails|mute-automation)\b/g,(r,t,n)=>`${t}${W(s(n))}`).replace(/--(accept-emails|mute-automation)\b/g,(r,t)=>s(t))}function L(e,s="flags"){return s==="step"?e.replace(/--(accept-automation|accept-emails|mute-automation)\b/g,(r,t)=>`${ye[t]??t} in the step`).replace(/\bAdd (acceptAutomation|acceptEmails|muteAutomation) in the step\b/g,"Turn on $1 in the step"):s==="erasure"?oe(e.replace(/\b(this|the|This|The) (masking|cleanup)\b/g,"$1 erasure").replace(/\bto (mask|delete) all the same\b/g,"to erase all the same").replace(/\b(mask|delete) fewer records\b/g,"erase fewer records")):s==="page"?oe(e):e}var ke={before:"before save",after:"after save",beforeAndAfter:"before and after save"},Ee={before:"before delete",after:"after delete",beforeAndAfter:"before and after delete"},ue={flows:"the flows",triggers:"the Apex triggers",processes:"the Process Builder processes",workflowRules:"the workflow rules",automation:"the automation"};function de({kind:e,name:s}){return e==="flow"?`flow "${s}"`:e==="process"?`process "${s}"`:e==="workflowRule"?`workflow rule "${s}"`:`Apex trigger ${s}`}function ce(e,s){return s.step==="delete"?Ee[s.when]:s.step==="bringBack"?"as it comes back from the recycle bin":`${e==="restore"?"as its values are put back":"as it is masked"}, ${ke[s.when]}`}function W(e){return`${e[0]?.toUpperCase()??""}${e.slice(1)}`}function ve(e,s,r,t){let n=E[r],a=[n.heading.replace("{org}",s)];if(typeof e.unread=="string")return a.push(` what ${s} runs could not be read: ${e.unread}`),a;let i=e;for(let c of S(i,t))a.push(` ${c.objectApiName}: ${ce(r,c)}: ${de(c)}`);let d=M(i);if(a.length===1&&d.length===0){let c=new Set(Object.values(t).flat()).size;a.push(` nothing fires on the ${c} object(s) it ${n.writes} records of`)}for(let c of ne(i,t.giveBack??[]))a.push(` ${c.objectApiName}: duplicate rules ${c.rules.map(p=>`"${p}"`).join(", ")}: ${n.the} saves a record a rule only alerts on, a rule that blocks still refuses it, and what a rule that reports writes (a duplicate record set and its items) stays`);let u=I(i);u.length>0&&a.push(` bypass held: the user ${n.the} writes as holds ${u.join(", ")}, and what names it stays quiet`);for(let{part:c,reason:p}of d)a.push(` ${ue[c]??c} could not be read: ${p}`);return a}function Se(e,s,r){let t=E[r.act],n=`${t.nothing} Add --accept-automation ${t.flag}, or turn that automation off in ${s} first.`;if(typeof e.unread=="string")return`What ${s} runs as ${t.this} ${t.writes} its records could not be read (${e.unread}), so what fires is not known. ${n}`;let a=e,i=S(a,r.steps),d=M(a);if(i.length===0&&d.length===0)return;let u=[];if(i.length>0){let l=i.map(m=>`${m.objectApiName}: ${de(m)} (${ce(r.act,m)})`);u.push(`${s} runs automation as ${t.this} ${t.writes} its records: ${l.join("; ")}.`)}for(let{part:l,reason:m}of d)u.push(`${W(ue[l]??l)} of ${s} could not be read (${m}), so what fires as ${t.the} ${t.writes} its records is not known.`);let c=r.assign??[];u.push(...re(c,s,t.the));let p=[...new Set(c.flatMap(l=>l.permissionSet??[]))];return r.mayMute===!0&&p.length>0&&u.push(`With --mute-automation, ${t.the} assigns ${p.join(", ")} to the user it writes as for ${t.the} alone, under a lease, and what ${p.length===1?"it keeps":"they keep"} quiet does not fire.`),u.push(n),u.join(" ")}function k(e){let s=e.objects.map(r=>`${r.perRecord} per ${r.objectApiName}`).join(", ");return`about ${te(e.emails,e.limit)} (${s}`+(e.alertsCounted?"; its email alerts among them, as a Developer Edition counts them":"")+")"}function Te(e,s,r){let t=e.map(n=>{if(n.verdict==="unread")return` emails: ${k(n)}; what ${s} has left today could not be read (${n.unread??"not said"})`;let a=`${n.remaining??0} of ${n.max??0} left today`;return n.verdict==="exceeds"?` emails: ${k(n)}, past the ${a}`:` emails: ${k(n)}, ${a}`});return r!==void 0&&t.push(` emails not counted: what sends them was not read (${r})`),t}function Ne(e,s,r,t){let n=s.filter(u=>u.verdict==="exceeds");if(n.length===0)return;let a=E[e],i=n.map(u=>`${k(u)}, ${u.remaining??0} of ${u.max??0} left today`).join("; "),d=t?.kind==="enough"?`Turn off what sends them, give the user it writes as the bypass that keeps them quiet (--mute-automation assigns ${t.sets.join(", ")} for ${a.the} alone, and what still sends then fits what is left today), or ${a.verb} fewer records.`:`Turn off what sends them, or ${a.verb} fewer records.`+(t?.kind==="muting"?" What sends them still runs under the mute.":t?.kind==="notEnough"?" --mute-automation would not keep enough of them quiet.":"");return`${W(a.this)} would make ${r} send ${i}: past them, each record whose flow fails in the save is refused (CANNOT_EXECUTE_FLOW_TRIGGER), and the org's own emails stop for the rest of the day. ${d} ${a.nothing}`}function Je(e,s,r){return{readAutomation:s,readLimits:()=>ee(e),readDeliverability:()=>r?Promise.resolve(V):X(e),muteOrg:async()=>Y(e),...r?{production:r}:{}}}async function Qe(e,s,r,t){let n=e?.mute?.prepared;if(!e||!n)return{};let a;try{a=await n.acquire(s)}catch(d){if(!T(d))throw d;return{refused:{code:d.code,message:L(d.message,t)}}}let i=e.emails.afterLease(a.outcome,r);return i?(await a.release(),{refused:{code:i.code,message:L(i.message,t)}}):{held:a}}var Me={objectsRead:[],objects:[],unread:[],conditionsNotRead:0,conditionsBound:0,requests:0};async function Ze(e){let{act:s,target:r,accord:t}=e,n=e.objects.filter(g=>g.records>0),a=n.map(g=>g.objectApiName),i=e.writes?.steps??be(s,a),d=F(i),u=a.length===0?Me:await e.org.readAutomation(a).catch(g=>{let b=U(g);return{unread:b===void 0?$(g):`the org could not be reached (${b})`}}),c=typeof u.unread=="string"?void 0:u,p=B(u),l=E[s],m=[],o;if(t.muteAutomation===!0&&p===void 0)try{o=await J(e.org.muteOrg,u,{...e.muteLeases,writes:d})}catch(g){if(!T(g))throw g;m.push({code:g.code,message:g.message})}let f=o?.automation??c,h=e.mayMute&&t.muteAutomation!==!0&&e.org.production!==!0,A=[...ve(c??u,r,s,i),...o?Q(o.muted,r).map(g=>` ${g}`):[]],j=Se(f??u,r,{act:s,steps:i,...f?{assign:se(f,q(f,i),e.assignTo)}:{},mayMute:h});j!==void 0&&t.acceptAutomation!==!0&&m.push({code:he,message:j});let D=e.writes?e.writes.written.filter(g=>g.records>0):Ae(s,n),y=[],R,P;if(f&&p===void 0){if(D.some(b=>C(f,b.write).some(w=>w.objectApiName===b.objectApiName))){let b=await e.org.readLimits().catch(w=>({unread:$(w)}));if(y=N(D,f,b),y.some(w=>w.verdict==="exceeds")){let w=!o&&h&&c?K(c,d):void 0;P=o?{kind:"muting"}:w&&w.plan.assign.length>0?N(D,w.automation,b).some(v=>v.verdict==="exceeds")?{kind:"notEnough"}:{kind:"enough",sets:w.plan.assign.map(v=>v.permissionSet)}:void 0}}R=Z(D,f)}A.push(...Te(y,r,R));let _=Ne(s,y,r,P);_!==void 0&&m.push({code:we,message:_});let O=await z({read:u,...o?.plan?{plan:o.plan}:{},writes:d,readDeliverability:p===void 0?e.org.readDeliverability:async()=>({reading:{unread:`${r} could not be reached`},requests:0}),accepted:t.acceptEmails===!0,target:r,run:$e[s],keepsAddresses:!0,mayMute:h});return O.gate.line!==void 0&&A.push(` ${O.gate.line}`),O.gate.stop&&m.push({...O.gate.stop}),p!==void 0&&m.splice(0,m.length,{code:Oe,message:`${r} could not be reached as what it runs was read (${p}), so ${l.the} was not started. ${l.nothing} Check the network, then try again.`}),{answer:{act:s,objects:n,steps:i,...c?{automation:c}:{automationUnread:String(u.unread)},lines:A,emails:y,...R!==void 0?{emailsUncounted:R}:{},...O.gate.deliverability?{deliverability:O.gate.deliverability}:{},emailsAsk:O.gate.verdict==="asks",refusals:m.map(g=>({...g,message:L(g.message,e.voice)})),...o?{mutedAutomation:o.muted}:{},...o?.plan?{mutePlan:o.plan}:{}},...o?{mute:o}:{},emails:O}}var xe=/\bnothing (?:was )?(?:written|deleted)\b/i,ie=/\s*\bNothing was (?:written|deleted)\./g;function et(e){let[s,...r]=e.refusals;if(!s)return;let t=!1,n=e.refusals.map(a=>t?a.message.replace(ie,"").trim():(t=xe.test(a.message),a.message)).join(" ");return{code:s.code,message:n,alsoRefused:r.map(a=>({code:a.code,message:a.message.replace(ie,"").trim()}))}}function tt(e){return e.alsoRefused.length>0?{extraPayload:{alsoRefused:[...e.alsoRefused]}}:{}}export{_e as a,ne as b,Ie as c,Ce as d,Fe as e,Ke as f,Je as g,Qe as h,Ze as i,et as j,tt as k};
@@ -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"./chunk-NTOVCTRS.mjs";function o(){return globalThis.crypto.randomUUID()}var d=class{create(e,t){let n=new Date().toISOString();return{id:o(),name:e,description:t,version:1,steps:[],triggers:[],variables:[],tags:[],createdAt:n,updatedAt:n}}addStep(e,t){let n={...t,id:o()};return{...e,steps:[...e.steps,n],updatedAt:new Date().toISOString()}}removeStep(e,t){return{...e,steps:e.steps.filter(n=>n.id!==t),updatedAt:new Date().toISOString()}}moveStep(e,t,n){let s=[...e.steps],i=s.findIndex(g=>g.id===t);if(i===-1)return e;let[a]=s.splice(i,1),r=Math.max(0,Math.min(n,s.length));return s.splice(r,0,a),{...e,steps:s,updatedAt:new Date().toISOString()}}addTrigger(e,t){let n={...t,id:o()};return{...e,triggers:[...e.triggers,n],updatedAt:new Date().toISOString()}}removeTrigger(e,t){return{...e,triggers:e.triggers.filter(n=>n.id!==t),updatedAt:new Date().toISOString()}}addVariable(e,t){return{...e,variables:[...e.variables,t],updatedAt:new Date().toISOString()}}validate(e){let t=[];e.name.trim()||t.push("Pipeline name is required"),e.steps.length===0&&t.push("Pipeline must have at least one step");let n=new Set;for(let i of e.steps)n.has(i.id)&&t.push(`Duplicate step ID: ${i.id}`),n.add(i.id),i.name.trim()||t.push(`Step must have a name (step ID: ${i.id})`),i.onSuccess&&!n.has(i.onSuccess)&&!e.steps.some(a=>a.id===i.onSuccess)&&t.push(`Step "${i.name}" references non-existent onSuccess step: ${i.onSuccess}`),i.onFailure&&!n.has(i.onFailure)&&!e.steps.some(a=>a.id===i.onFailure)&&t.push(`Step "${i.name}" references non-existent onFailure step: ${i.onFailure}`);for(let i of e.variables)i.name.trim()||t.push("Variable must have a name"),i.required&&i.defaultValue===void 0&&t.push(`Required variable "${i.name}" must have a default value`);let s=new Set;for(let i of e.triggers)s.has(i.id)&&t.push(`Duplicate trigger ID: ${i.id}`),s.add(i.id),i.type==="schedule"&&!i.config.cron&&t.push(`Schedule trigger "${i.id}" requires a cron expression`);return t}clone(e){let t=new Date().toISOString(),n=new Map;for(let r of e.steps)n.set(r.id,o());let s=e.steps.map(r=>({...r,id:n.get(r.id),config:{...r.config},condition:r.condition?{...r.condition}:void 0,onSuccess:r.onSuccess?n.get(r.onSuccess):void 0,onFailure:r.onFailure?n.get(r.onFailure):void 0})),i=e.triggers.map(r=>({...r,id:o(),config:{...r.config}})),a=e.variables.map(r=>({...r}));return{...e,id:o(),steps:s,triggers:i,variables:a,tags:[...e.tags],createdAt:t,updatedAt:t}}};export{d as PipelineBuilder};
@@ -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}from"./chunk-YPSRZRIT.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{a as seedObjectAccess,b as templateTheOrgTakes};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{a,b,c,d,e,f,g}from"./chunk-ZXH4MBWP.mjs";import"./chunk-NEVXIGR6.mjs";import"./chunk-TYYOBZMU.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-SIOZXPFG.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{c as acquireEnvLock,g as checkpointLockRefusal,a as defaultEnvLocksDir,b as envLockFileOf,d as envLockHolder,f as envLockLine,e as envLockRefusal};
@@ -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 t=class{channel;init(n){this.channel=n}debug(n,e){this.log("debug",n,e)}info(n,e){this.log("info",n,e)}warn(n,e){this.log("warn",n,e)}error(n,e){this.log("error",n,e)}log(n,e,i){let o=new Date().toISOString(),r=i?` ${JSON.stringify(i)}`:"",a=`[${o}] [${n.toUpperCase()}] ${e}${r}`;this.channel?.appendLine(a)}},s=new t;export{s as a};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{a,b,c,d,e,f,g,h,i,j}from"./chunk-5QKTYCWE.mjs";import"./chunk-WJY54JO7.mjs";import"./chunk-NEVXIGR6.mjs";import"./chunk-HJC7AIBK.mjs";import"./chunk-TYYOBZMU.mjs";import"./chunk-ZUTYVST5.mjs";import"./chunk-55HEMHEG.mjs";import"./chunk-P42X3B4D.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-WIO4XO4F.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import"./chunk-CGWXQX75.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-SIOZXPFG.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{b as ARCHIVE_CHUNK_BYTES,a as ARCHIVE_EXTENSION,f as CheckpointExportError,d as archiveKeyText,h as exportCheckpointArchive,j as importCheckpointArchive,c as newArchiveKey,e as parseArchiveKey,g as portableCheckpointOf,i as readArchiveHeader};
@@ -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{$ as n,Aa as O,Ba as P,Ca as Q,O as a,P as b,Q as c,R as d,S as e,T as f,U as g,V as h,W as i,X as j,Y as k,Z as l,_ as m,aa as o,ba as p,ca as q,da as r,ea as s,fa as t,ga as u,ha as v,ia as w,ja as x,ka as y,la as z,ma as A,na as B,oa as C,pa as D,qa as E,ra as F,sa as G,ta as H,ua as I,va as J,wa as K,xa as L,ya as M,za as N}from"./chunk-ZLZRU6MO.mjs";import"./chunk-WIO4XO4F.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-CGWXQX75.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-B45CNPUX.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-NTOVCTRS.mjs";export{m as ASSIGNMENT_RULES_SOQL,h as AUTOMATION_READ_MOST,b as CONDITIONS_BOUND,f as CONDITION_REQUESTS_BOUND,c as DEFINITIONS_BOUND,g as DEFINITION_REQUESTS_BOUND,n as DUPLICATE_RULES_SOQL,i as FLOWS_SOQL,k as PROCESSES_SOQL,d as TOOLING_QUERIES_PER_REQUEST,e as TOOLING_RETRIEVES_PER_REQUEST,j as TRIGGERS_SOQL,M as TargetAutomationReader,o as USER_PERMISSIONS_SOQL,l as WORKFLOW_RULES_SOQL,a as answerOf,Q as automationLines,p as conditionSoql,z as customObjectIdsSoql,P as customPermissionsByIdSoql,A as customPermissionsSoql,F as decisionChecks,K as inFlight,G as messagesOf,L as objectsTheRunWrites,H as pathsOf,I as permissionKey,C as permissionSetSizesSoql,B as permissionSetsHoldingSoql,D as permissionsNamed,y as processObjectsSoql,N as readBypassGrants,w as readInComposites,x as ruleDefinitionSoql,O as setCustomPermissionsSoql,E as switchesNamed,v as targetAutomationQueries,s as toolingAnswersOf,q as toolingCompositeBody,t as toolingRecordsOf,r as toolingRetrieveBody,u as toolingRetrievesOver,J as unreadPartOf};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{a as c}from"./chunk-P42X3B4D.mjs";var p=class{apply(n,r,t=[]){return m(n,r,t)}applyAddOns(n,r){let t={...n};for(let o of r)(!(o.fieldApiName in t)||o.overwriteExisting)&&(t[o.fieldApiName]=o.value);return t}},g=new Set(["direct","rename","transform","add_on"]),i=e=>e.toLowerCase();function S(e){return new Set(e.filter(n=>n.type!=="exclude").map(n=>i(n.targetField)))}function w(e,n=[]){let r=new Set(n.map(i));for(let t of e)(g.has(t.type)||t.type==="exclude")&&r.add(i(t.sourceField)),r.add(i(t.targetField));return r}var y=new c;function m(e,n,r=[]){if(n.length===0&&r.length===0)return{...e};let t=new Set(r.map(i)),o=Object.fromEntries(Object.entries(e).filter(([s])=>!t.has(i(s)))),d=w(n,r),l=Object.fromEntries(Object.entries(o).filter(([s])=>!d.has(i(s))));for(let s of n){let u=R(o,s);u!==void 0&&(l[s.targetField]=u)}return l}function a(e,n){if(n in e)return e[n];let r=i(n),t=Object.keys(e).find(o=>i(o)===r);return t===void 0?void 0:e[t]}var f=Symbol("exclude");function R(e,n){let r=F[n.type],t=r(e,n);if(!(t===f||t===void 0))return n.transformRules&&n.transformRules.length>0?y.transform(t,n.transformRules):t}var F={direct:(e,n)=>a(e,n.sourceField),rename:(e,n)=>a(e,n.sourceField),transform:(e,n)=>a(e,n.sourceField),constant:(e,n)=>n.targetField?n.sourceField:void 0,formula:(e,n)=>k(e,n.sourceField),exclude:()=>f,add_on:(e,n)=>a(e,n.sourceField)};function k(e,n){return/\{(\w+)\}/g.test(n)?n.replace(/\{(\w+)\}/g,(t,o)=>{let d=e[o];return d!=null?String(d):""}):e[n]}export{p as a,g as b,S as c,w as d,m as e};
@@ -0,0 +1,10 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{a as Je,c as Rn,d as Re,e as Rt,f as Ot,g as At,h as St,j as Ct,l as Bn,m as Fn}from"./chunk-MYTIL2JD.mjs";import{d as tn,e as an,f as dt,g as ft,h as lt,j as ut,k as bn,l as jn}from"./chunk-JVL444U5.mjs";import{c as Pt,d as It}from"./chunk-5CD257T7.mjs";import{a as Nn}from"./chunk-ALJVEUUS.mjs";import{C as ot,W as gt,_ as te,aa as ht,ea as wt,fa as pt,ga as ve,ha as Ln,ia as se,ja as mt,la as $e,ma as cn,na as kt,pa as Z,sa as xe,ua as En}from"./chunk-6QSM2WIH.mjs";import{A as bt,t as Ve,x as vn,y as yt,z as We}from"./chunk-WJY54JO7.mjs";import{F as ct,a as it,b as st,d as nn,o as rt,v as at,x as yn}from"./chunk-NEVXIGR6.mjs";import{C as en}from"./chunk-HJC7AIBK.mjs";import{b as rn,d as Le,e as tt}from"./chunk-OTWRDD6L.mjs";import{f as Yn,g as le,h as me,i as et,p as kn}from"./chunk-PA3MKJVH.mjs";import{i as nt}from"./chunk-INIT2UKJ.mjs";import{p as mn,q as je}from"./chunk-CGWXQX75.mjs";import{h as pn}from"./chunk-TZE3Y7IQ.mjs";import{b as Pe}from"./chunk-CA5NAXSU.mjs";import{Tb as pe}from"./chunk-B45CNPUX.mjs";import{b as Xn,k as hn,l as wn}from"./chunk-7EANH5PY.mjs";import{randomBytes as yi}from"node:crypto";import{appendFile as bi,readdir as Ri,rm as Oi}from"node:fs/promises";import{join as Jn}from"node:path";import{appendFile as No,rm as qn}from"node:fs/promises";import{join as jo}from"node:path";import{appendFile as ho}from"node:fs/promises";import{join as wo}from"node:path";var In=gt*10,po=2e3,mo="005",ko=["Id","IsDeleted","CreatedDate","LastModifiedById","LastModifiedDate","LatestPublishedVersionId","ContentSize"],Mt=1,Tt=2,_t=4,Dt=8,_n=16,An=32,Sn=64,Nt=1,jt=2,Lt=4,On=32768,Cn={toDelete:["createdSince","broughtBackSince"],comesBack:["inBin","withParent","deletedWhileTaken"],lost:["goneForGood","toRecreate"]},Mn={toDelete:["createdSince","broughtBackSince","comesBackWithParent"],comesBack:["inBin","withParent","deletedWhileTaken"],lost:["goneForGood","deletedWithCreatedParent","deletedWithParentOutside"]};function Be(e){return typeof e=="string"&&e.length>=15?e.slice(0,15):void 0}function $n(e){return`${e.ContentDocumentId.slice(0,15)}${e.LinkedEntityId.slice(0,15)}`}function $t(e){return`${e.ShareType}/${e.Visibility}`}async function*dn(e){try{for await(let n of se(e))yield n}catch(n){if(n.code==="ENOENT")return;throw n}}function vt(e){return typeof e=="string"&&/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/.test(e)?e:null}function Tn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:null}function yo(e){let n=en(e);return n===null?Number.NaN:Date.parse(n)}var Ge=class{constructor(n){this.file=n}file;lines=[];count=0;async add(n){this.lines.push(`${JSON.stringify(n)}
8
+ `),this.count++,this.lines.length>=po&&await this.flush()}async flush(){if(this.lines.length===0)return;let n=this.lines.join("");this.lines=[],await ho(this.file,n,{encoding:"utf8",mode:nn,flag:"a"})}};function Bt(e,n,t){let o=pe(n);return wo(e,`${o}.links${t===void 0?"":`.${t}`}.ndjson`)}function*Wt(e,n){let t=[];for(let o of e)t.push(o),t.length>=n&&(yield t,t=[]);t.length>0&&(yield t)}var bo=wn({sobjects:hn(Yn)}).loose(),Wn=class{files=new Z;held=new Map;sharings=[];prefixes;now;constructor(n,t){this.prefixes=n,this.now=t}anchoredNow(n){return(this.files.flagsOf(n)&_t)!==0}anchoredThen(n){return(this.files.flagsOf(n)&Tt)!==0}sharingAt(n){let t=this.sharings.indexOf(n);return t>=0?t:(this.sharings.push(n),this.sharings.length-1)}};function Ro(e,n){let t=n.fields.find(s=>s.name.toLowerCase()==="linkedentityid"),o=new Set((t?.referenceTo??[]).map(s=>s.toLowerCase()));if(o.size===0)throw new Error(`The describe of ${me} names no record a link ties a file to.`);return e.objects.map(({objectApiName:s})=>s).filter(s=>{if(s.toLowerCase()===le.toLowerCase()||!o.has(s.toLowerCase()))return!1;let i=e.changes.get(s);return i!==void 0&&!("unread"in i)&&(i.count??0)>0})}async function*Oo(e,n){let t=await We.read(e.folder,e.snapshotId,n);for(let s=0;s<t.size;s++)yield t.idAt(s);let o=e.changes.get(n);if(!(o===void 0||"unread"in o||!o.live))for await(let s of se(o.live.file))typeof s.Id=="string"&&!t.has(s.Id)&&(yield s.Id)}async function Ao(e,n){let{reader:t,previewDir:o,signal:s}=e,i=n.map(l=>({...St(l),file:Bt(o,l)})),r=await Ln(t,i,s),a=[];for(let[l,w]of r.entries()){let p=n[l];if(w.read){a.push({objectApiName:p,file:i[l].file});continue}let c=0,g=Oo(e,p);for await(let d of So(g,Je*In)){let h=[...Wt(d,Je)].map(j=>({...Ct(p,j),file:Bt(o,p,c++)})),R=(await Ln(t,h,s)).find(j=>!j.read);if(R&&!R.read)throw new Error(`The links of the files of ${p} could not be read whole: ${w.reason}; read by the ids of its records, ${R.reason}`);for(let j of h)a.push({objectApiName:p,file:j.file})}}return a}async function*So(e,n){let t=[];for await(let o of e)t.push(o),t.length>=n&&(yield t,t=[]);t.length>0&&(yield t)}async function xt(e){let n=bo.safeParse(await e.describeGlobal());if(!n.success)throw new Error("The org\u2019s global describe does not read as one.");let t=Ot(n.data.sobjects,e.objects.map(({objectApiName:a})=>a)),o=Ro(e,await e.linkDescribe),s=await Ao(e,o),i=new Wn(t,s);for await(let a of Fn(e.folder))i.files.add(a.Id,Mt|(a.anchored?Tt:0));let r=await vn.read(e.folder);for await(let a of Bn(e.folder))i.held.set($n(Gt(a,r)),i.sharingAt($t(a)));for(let{file:a}of s)for await(let l of se(a))typeof l.ContentDocumentId=="string"&&i.files.add(l.ContentDocumentId,_t);return i}function Gt(e,n){let t=Be(e.LinkedEntityId),o=t===void 0?void 0:n.currentOf(t);return o===void 0?e:{...e,LinkedEntityId:o}}async function Pn(e,n,t,o,s){for(let i of o)for await(let r of dn(n(t,i)))typeof r.Id=="string"&&e.add(r.Id,s)}async function Ft(e){let n=0;for await(let t of dn(e))typeof t.Id=="string"&&n++;return n}async function Et(e,n,t){let o=new Map;if(n.length===0)return o;let s=Le([...n],Je).map(a=>({objectApiName:le,soql:`SELECT ${ko.join(", ")} FROM ${le} WHERE Id IN (${a})`,scanAll:!0})),r=(await ve(e,s,(a,l)=>{for(let w of l){let p=Be(w.Id);p!==void 0&&o.set(p,w)}},t)).find(a=>!a.read);if(r&&!r.read)throw new Error(`The files the checkpoint names could not be read by their ids: ${r.reason}`);return o}function Co(e,n){return n===void 0||n.version===null||e.LatestPublishedVersionId===null?!1:Be(n.version)!==Be(e.LatestPublishedVersionId)}async function Ut(e){let{anchors:n,reader:t,classFileOf:o,signal:s}=e,i=n.files,r=le;await Pn(i,o,r,Cn.toDelete,_n),await Pn(i,o,r,Cn.comesBack,An),await Pn(i,o,r,Cn.lost,Sn);let a=new Map,l=e.fileChanges;if(!("unread"in l)){for(let D of[l.live,l.deleted])if(D!==void 0)for await(let L of se(D.file)){let N=Be(L.Id);N!==void 0&&(i.add(String(L.Id),Dt),a.set(N,{version:vt(L.LatestPublishedVersionId),size:Tn(L.ContentSize)}))}}let w=await We.read(e.folder,e.snapshotId,r),p=D=>(i.flagsOf(D)&Dt)===0&&!w.has(D),c=new Ge(o(r,"createdSince")),g=new Ge(o(r,"deletedWhileTaken")),d=new Ge(o(r,"goneForGood")),f=new Ge(o(r,"newFileVersion")),h=0,b=0,R=async D=>{let L=await Et(t,D.filter(N=>N.anchored&&p(N.Id)).map(N=>N.Id),s);for(let N of D){if(!N.anchored)continue;let V=Be(N.Id)??"",J=a.get(V);if(p(N.Id)){let x=L.get(V);if(x===void 0){i.add(N.Id,Sn),await d.add({Id:N.Id});continue}J={version:vt(x.LatestPublishedVersionId),size:Tn(x.ContentSize)},x.IsDeleted===!0&&(i.add(N.Id,An),await g.add({Id:N.Id}))}let Y=i.flagsOf(N.Id);(Y&Sn)===0&&((Y&An)!==0&&(h+=J?.size??N.ContentSize??0),Co(N,J)&&await f.add({Id:N.Id}))}},j=[];for await(let D of Fn(e.folder))j.push(D),j.length>=Je*In&&(await R(j),j=[]);await R(j);let C=new Z,v=[],O=async D=>{let L=await Et(t,D,s);for(let N of D){let V=L.get(Be(N)??"");V===void 0||V.IsDeleted===!0||yo(V.CreatedDate)>=e.t0s&&(i.add(N,_n),await c.add({Id:N}),v.push(V))}},B=[];for(let{file:D}of n.now)for await(let L of se(D)){let N=L.ContentDocumentId;typeof N!="string"||(i.flagsOf(N)&Mt)!==0||!p(N)||C.add(N)&&(B.push(N),B.length>=Je*In&&(await O(B),B=[]))}await O(B);for await(let D of dn(o(r,"createdSince"))){let L=Be(D.Id);L!==void 0&&(b+=a.get(L)?.size??0)}for await(let D of dn(o(r,"broughtBackSince")))b+=a.get(Be(D.Id)??"")?.size??0;for(let D of v)b+=Tn(D.ContentSize)??0;for(let D of[c,g,d,f])await D.flush();return{files:{...await Po(e),outsideAdded:await Ft(o(r,"outsideAdded")),outsideDeleted:await Ft(o(r,"outsideDeleted")),storage:{bringBack:h,undo:b},...e.queryAllFiles?{}:{blindSpot:!0}},createdSince:c.count,deletedWhileTaken:g.count,goneForGood:d.count,newFileVersion:f.count,changedBy:v}}async function Po(e){let{anchors:n,classFileOf:t}=e,o=new Z,s=new Set;for(let{objectApiName:c}of e.objects){if(c.toLowerCase()===le.toLowerCase())continue;if(!e.told.has(c)){for(let[d,f]of n.prefixes)f.toLowerCase()===c.toLowerCase()&&s.add(d);continue}let g=(d,f)=>Pn(o,t,c,d,f);await g(Mn.toDelete,Nt),await g(Mn.comesBack,jt),await g(Mn.lost,Lt)}let i=c=>s.has(c.LinkedEntityId.slice(0,3)),r=c=>new Ge(Re(e.previewDir,c)),a=r("linkAdded"),l=r("linkRemoved"),w=r("linkChanged");for(let{file:c}of n.now)for await(let g of se(c)){let d=Rn.safeParse(g);if(!d.success)throw new Error(`The org answered a link that does not read as one: ${d.error.message}`);let f=d.data,h=$n(f),b=n.held.get(h);if(b!==void 0){if(n.held.set(h,b|On),i(f)||n.sharings[b&~On]===$t(f))continue;let[R,j]=(n.sharings[b&~On]??"").split("/"),C={...f,ShareType:R,Visibility:j,now:{ShareType:f.ShareType,Visibility:f.Visibility}};await w.add(C);continue}i(f)||(n.files.flagsOf(f.ContentDocumentId)&_n)===0&&(o.flagsOf(f.LinkedEntityId)&Nt)===0&&await a.add(f)}let p=await vn.read(e.folder);for await(let c of Bn(e.folder)){let g=Gt(c,p);((n.held.get($n(g))??0)&On)!==0||i(g)||(n.files.flagsOf(g.ContentDocumentId)&(An|Sn))===0&&(o.flagsOf(g.LinkedEntityId)&(jt|Lt))===0&&await l.add(g)}for(let c of[a,l,w])await c.flush();return{unlink:a.count,relink:l.count,updateLinks:w.count}}async function zt(e){let{anchors:n,reader:t,classFileOf:o,signal:s}=e,i=[];for(let l of Cn.toDelete)for await(let w of dn(o(le,l)))typeof w.Id=="string"&&i.push(w.Id);if(i.length===0)return{links:0,files:0};let r=new Map,a=0;for(let l of Wt(Le(i,Je),In)){let w=l.map(g=>({objectApiName:me,soql:`SELECT Id, ContentDocumentId, LinkedEntityId FROM ${me} WHERE ContentDocumentId IN (${g})`,scanAll:!1})),c=(await ve(t,w,(g,d)=>{for(let f of d){let h=f.LinkedEntityId,b=f.ContentDocumentId;typeof h!="string"||typeof b!="string"||h.startsWith(mo)||At({LinkedEntityId:h},n.prefixes)===void 0&&(a++,r.set(b.slice(0,15),b))}},s)).find(g=>!g.read);if(c&&!c.read)throw new Error(`The links of the files to delete to what the checkpoint does not hold could not be read: ${c.reason}`)}if(r.size>0){let l=new Ge(o(le,"outsideParents"));for(let w of r.values())await l.add({Id:w});await l.flush()}return{links:a,files:r.size}}var Gn=Object.freeze({kind:"org",notHeld:new Map,heldAs:()=>"org",unseenOf:()=>Promise.resolve([]),requests:()=>0,diffAccess:()=>({kind:"org"})});function xn(e){return e.slice(0,15)}function Io(e,n,t,o){let s=n.detail!==void 0?` (${n.detail})`:"";switch(n.reason){case"noViewAll":case"noModifyAll":return`${t} ${o} View All and Modify All on ${e}`;case"parentNotSeen":return`${t} ${o} View All and Modify All on every record ${e} hangs from`+s;case"activities":return`${t} doesn't have View All Data and Modify All Data, which tasks and events need: Salesforce has no View All for activities`;case"catalog":return`${t} doesn't have View All Data and Modify All Data, which products and price books need: Salesforce has no View All or Modify All for them`;case"filesNotProven":return`${t} doesn't have View All Data and Modify All Data, which files need: nothing else proves who sees every file`;case"settingNotProven":return`${t} doesn't have View All Data and Modify All Data, which custom settings need: no permission on an object proves who sees and writes every row`}}async function ss(e){let{grants:n,reader:t}=e;if(n.kind==="org"||e.userId===void 0)return Gn;let o=e.checkpoint.objects,s=o.filter(f=>f.customSetting!==void 0).map(f=>f.objectApiName),i=new Map,r=n.requests,a=async f=>{let h=[...new Set(f)].filter(j=>!i.has(j.toLowerCase()));if(h.length===0)return;let b=t.calls(),R=await Promise.allSettled(h.map(j=>t.describe(j)));r+=t.calls()-b,R.forEach((j,C)=>{if(j.status==="rejected"&&j.reason instanceof te)throw j.reason;let v=j.status==="fulfilled"&&"body"in j.value?j.value.body:void 0,O=tn.safeParse(v);i.set(h[C].toLowerCase(),O.success?O.data:void 0)})},l=()=>[...i.values()].filter(f=>f!==void 0),w=async f=>{let h=f.filter(R=>!n.objects.has(R.toLowerCase()));await a(h);let b={grants:n.objects,describes:l(),customSettings:s};return await a(Pt(f,b)),It(f,{...b,describes:l()})},p=await w(o.map(f=>f.objectApiName)),c=xn(e.userId)===xn(e.checkpoint.takenBy.userId)?"no longer has":"doesn't have",g=new Map,d=new Map;for(let[f,h]of p)"access"in h?g.set(f,h.access):d.set(f,Io(f,h,e.username,c));return{kind:"perObject",userKey:xn(e.userId),notHeld:d,heldAs:f=>g.get(f),unseenOf:async f=>{let h=await w(f);return f.filter(b=>{let R=h.get(b);return R===void 0||!("access"in R)})},requests:()=>r,diffAccess:()=>({kind:"perObject",requests:r})}}var Lo=["giveBack","touched","createdSince","broughtBackSince","comesBackWithParent","unexplained","inBin","withParent","deletedWhileTaken","toRecreate","goneForGood","convertedLead","activatedContract","carrier","deletedWithCreatedParent","deletedWithParentOutside","deletedByOther","outOfReach","undoCannot","outsideParents","outsideAdded","outsideDeleted","newFileVersion"],vo="Lead",Bo="IsConverted",Fo="Contract",Eo="Status",qt="StatusCode",Mo="Activated",To=["createdSince","broughtBackSince"];function X(e,n,t){return jo(e,`${pe(n)}.${t}.ndjson`)}var Dn=1e3,_o=1440*6e4,$o=60*6e4,Wo=100,xo=2e3,Jt=["LastModifiedById","LastModifiedDate"];function ee(e){return typeof e=="string"&&e.length>=15?e.slice(0,15):void 0}function ke(e){let n=en(e);return n===null?Number.NaN:Date.parse(n)}function Hn(e){return e.toLowerCase()===le.toLowerCase()}function Go(e){return e==null||e===""}function Ie(e,n){let t=n.toLowerCase();return e.find(o=>o.toLowerCase()===t)}function Uo(e){return!e.leftOutFields.some(n=>n.reason==="base64")}var fn=class{constructor(n){this.file=n}file;lines=[];written=!1;count=0;async add(n){this.lines.push(`${JSON.stringify(n)}
9
+ `),this.count++,this.lines.length>=xo&&await this.flush()}async flush(){if(this.lines.length===0)return;let n=this.lines.join("");this.lines=[],await No(this.file,n,{encoding:"utf8",mode:nn,flag:this.written?"a":"w"}),this.written=!0}async discard(){this.lines=[],this.written&&await qn(this.file,{force:!0})}};async function Kn(e,n){await Promise.all(Lo.map(t=>qn(X(e,n,t),{force:!0})))}var Un=class{constructor(n){this.activeFrom=n}activeFrom;counts=new Map;active=new Set;add(n){let t=n.LastModifiedById;typeof t!="string"||t===""||(this.counts.set(t,(this.counts.get(t)??0)+1),ke(n.LastModifiedDate)>=this.activeFrom&&this.active.add(t))}byUser(){return Object.fromEntries([...this.counts].sort(([n],[t])=>n<t?-1:n>t?1:0))}};function Qt(e,n){let t,o=async()=>{let s=new Set;try{for await(let i of se(rt(e,n))){let r=ee(i.Id);r!==void 0&&s.add(r)}}catch(i){throw i.code!=="ENOENT"?i:new Error(`The checkpoint\u2019s list of what ${n} held in the recycle bin is not on this machine.`)}return s};return async s=>(await(t??=o())).has(s)}async function zo(e,n,t,o){let s=pe(n.objectApiName),i=n.readMode==="scanAllLive",r=i?" AND IsDeleted = false":"",a=async p=>{let c=e.lane(),g=[];try{let d=await pt(c,{objectApiName:s,soql:p,scanAll:i},f=>{g.push(...f)});if(!d.read)throw new Error(d.reason);return g}finally{c.close()}},l=t.length>Wo?rn/4:rn,w=new Map;for(let p of Le(o,l)){let c=await nt(`SELECT ${t.join(", ")} FROM ${s} WHERE Id IN (${p})${r}`,a,{stamp:"SystemModstamp",...i?{idsWhere:"IsDeleted = false"}:{}});for(let g of c){let d=ee(g.Id);d!==void 0&&w.set(d,g)}}return w}var qo=/__(?:c|pc|s)$/i,Ho=/^(.+)__[A-Za-z]+__s$/i,Ko=/^(.+)__pc$/i,Vo=/^[A-Za-z][A-Za-z0-9_]*$/,Jo=200;function Qo(e,n){if(!qo.test(n)||!Vo.test(n))return;let t=Ko.exec(n);if(t)return{entity:je,name:`${t[1]}__c`};let o=Ho.exec(n);return o?{entity:e,name:`${o[1]}__c`}:{entity:e,name:n}}var Zo=hn(wn({QualifiedApiName:Xn()}).loose());function Xo(e,n){let t=`SELECT QualifiedApiName FROM FieldDefinition WHERE EntityDefinition.QualifiedApiName = '${pe(e)}' AND QualifiedApiName IN (`,o=r=>`${t}${r.map(a=>`'${a}'`).join(", ")})`,s=[],i=[];for(let r of n){let a=[...i,r],l=a.length>Jo||encodeURIComponent(o(a)).length>14e3;i.length>0&&l?(s.push({soql:o(i),names:i}),i=[r]):i=a}return i.length>0&&s.push({soql:o(i),names:i}),s}async function Yo(e,n){let t=new Map,o=new Map;for(let[r,a]of n){let l={removed:[],hidden:[]};t.set(r,l);for(let w of a){let p=Qo(r,w);if(p===void 0){l.hidden.push(w);continue}let c=o.get(p.entity)??new Map;o.set(p.entity,c);let g=p.name.toLowerCase(),d=c.get(g)??{name:p.name,fields:[]};c.set(g,d),d.fields.push({objectApiName:r,field:w})}}let s=0,i=new Map;for(let[r,a]of o){let l=new Set,w=new Map,p=Xo(r,[...a.values()].map(({name:c})=>c));for(let c of p){s++;try{let g=await e.tooling(c.soql);if(!g.done)throw new Error("FieldDefinition answered more than one page");let d=Zo.safeParse(g.records);if(!d.success)throw new Error("FieldDefinition answered rows with no field name");for(let f of d.data)l.add(f.QualifiedApiName.toLowerCase())}catch(g){if(g instanceof te)throw g;let d=Pe(g);for(let f of c.names)w.set(f.toLowerCase(),d)}}for(let[c,{fields:g}]of a){let d=w.get(c);for(let{objectApiName:f,field:h}of g){let b=t.get(f);if(b!==void 0)if(d!==void 0){let R=i.get(f)??{fields:[],reasons:[]};i.set(f,R),R.fields.push(h),R.reasons.includes(d)||R.reasons.push(d)}else l.has(c)?b.hidden.push(h):b.removed.push(h)}}}for(let[r,a]of t){a.removed.sort(),a.hidden.sort();let l=i.get(r);l!==void 0&&(a.uncertain={fields:l.fields.sort(),...l.reasons.length>0?{reason:l.reasons.join("; ")}:{}})}return{gone:t,requests:s}}async function Ht(e,n,t){let{checkpoint:o,folder:s,reader:i}=e,r=new Date(Date.parse(o.readFrom)-_o).toISOString(),a=await Promise.allSettled(n.map(({objectApiName:h})=>i.describe(h,r))),l,w=new Map,p=new Map;for(let[h,b]of a.entries()){let R=n[h].objectApiName;if(b.status==="rejected"){if(b.reason instanceof te)throw b.reason;w.set(R,{unread:`The org did not answer the describe of ${R}: ${Pe(b.reason)}`});continue}if("notModified"in b.value){w.set(R,{gone:new Set});continue}let j=tn.safeParse(b.value.body);if(!j.success){w.set(R,{unread:`The describe of ${R} does not read as one.`});continue}t.set(R,j.data);try{let C=(await(l??=ct(s,o.objects))).get(R);if(C===void 0)throw new Error(`The checkpoint holds no field prints of ${R}.`);p.set(R,st(C,it(j.data.fields)))}catch(C){w.set(R,{unread:Pe(C)})}}let c=new Map(n.map(h=>[h.objectApiName,new Set(bn(h.objectApiName,h.fields,o.ignoredFields).map(b=>b.toLowerCase()))])),g=(h,b)=>b.filter(R=>c.get(h)?.has(R.toLowerCase())===!0),d=new Map([...p].map(([h,b])=>[h,g(h,b.removed)]).filter(([,h])=>h.length>0)),f=d.size>0?await Yo(i,d):{gone:new Map,requests:0};for(let[h,{removed:b,added:R,changed:j}]of p){let C=f.gone.get(h);w.set(h,{...g(h,b).length+R.length+j.length>0?{drift:{removed:C?.removed??[],added:R,changed:j,...C!==void 0&&C.hidden.length>0?{hidden:C.hidden}:{},...C?.uncertain!==void 0?{uncertain:C.uncertain}:{}}}:{},gone:new Set(b.map(v=>v.toLowerCase()))})}return{now:w,requests:f.requests}}function ei(e,n){let t=i=>{let r=n.get(i);return r!==void 0&&!("unread"in r)&&r.moved},o=e.find(({objectApiName:i})=>i===je),s=o!==void 0&&Ie(o.fields,an)!==void 0&&t(je);return e.filter(({objectApiName:i})=>t(i)||s&&i===mn)}function ni(e,n){let t=[...e.cascadeParents,...e.restrictParents??[]].filter(s=>!n.has(s.toLowerCase()));if(e.customSetting!==void 0){let s=Ie(e.fields,kn(e.customSetting));s!==void 0&&!n.has(s.toLowerCase())&&!t.includes(s)&&t.push(s)}if(Hn(e.objectApiName))for(let s of dt){let i=Ie(e.fields,s);i!==void 0&&!n.has(i.toLowerCase())&&t.push(i)}let o=Ie(e.fields,an);if(e.objectApiName===je&&o!==void 0){let s=Ie(e.fields,"AccountId");for(let i of[o,s])i!==void 0&&!n.has(i.toLowerCase())&&t.push(i)}return[...t,...Jt]}async function ti(e,n,t){let{folder:o,checkpoint:s}=e.input,i=new Map,r=new Map;for(let{objectApiName:a,cascadeParents:l,restrictParents:w=[]}of n){let p=t.get(a);if(!p||"unread"in p||!p.deleted||p.deleted.rows===0)continue;let c=new Map,g=new Map;try{let d=await We.read(o,s.snapshotId,a),f=Qt(o,a);for await(let h of se(p.deleted.file)){let b=ee(h.Id);if(b===void 0)continue;let R=v=>v.map(O=>ee(h[O])).filter(O=>O!==void 0&&O!==b),j=ee(h.LastModifiedById),C=()=>({objectApiName:a,id:String(h.Id),stamp:ke(h.SystemModstamp),parents:R(l),restricts:R(w),...j!==void 0?{by:j}:{}});if(!d.retired(h.Id)){if(!d.has(h.Id)){if(await f(b)){g.set(b,C());continue}if(ke(h.CreatedDate)>=e.t0s&&g.set(b,C()),!(ke(h.CreatedDate)<e.t0s))continue}c.set(b,C())}}}catch(d){if(d instanceof te)throw d;continue}for(let[d,f]of c)i.set(d,f);for(let[d,f]of g)r.set(d,f)}return{back:i,gone:r}}function oi(e,n){let t=s=>e.get(s)?.stamp??n.get(s)?.stamp,o=new Set;for(let s of[e,n])for(let[i,r]of s)[...r.parents,...r.restricts].some(l=>(t(l)??0)>r.stamp)&&o.add(i);return zn(o,e,n),o}function zn(e,n,t){let o=s=>n.get(s)?.stamp??t.get(s)?.stamp;for(let s=e.size>0;s;){s=!1;for(let i of[n,t])for(let[r,a]of i){if(e.has(r))continue;a.parents.some(w=>e.has(w)&&o(w)===a.stamp)&&(e.add(r),s=!0)}}for(let s of e)n.delete(s)}function ii(e,n){if(n===void 0)return new Set;let t=[...e].filter(([,o])=>o.by!==n).map(([o])=>o);return Zt(t,e)}function Zt(e,n){let t=new Set(e);for(let o=t.size>0;o;){o=!1;for(let[s,i]of n){if(t.has(s))continue;i.parents.some(a=>t.has(a)&&n.get(a)?.stamp===i.stamp)&&(t.add(s),o=!0)}}return t}function si(e,n,t){let o=new Map(e.map(l=>[l.objectApiName,l.undeletable])),s=new Set,i=new Set,r=(l,w)=>l.parents.find(p=>!w.has(p)&&t.get(p)?.stamp===l.stamp),a=l=>l.parents.some(w=>n.get(w)?.stamp===l.stamp);for(let l of[...n.values()]){if(a(l))continue;let w=new Set,p=[],c=r(l,w),g=!1;for(;c!==void 0;){w.add(c),p.push(c);let h=t.get(c);if(!h)break;if(a(h)){g=!0;break}c=r(h,w)}let d=p[p.length-1];if(d===void 0||g)continue;let f=t.get(d);if(!(!f||o.get(f.objectApiName)!==!0)){s.add(d);for(let h of p.slice(0,-1))i.add(h)}}for(let l of[...s,...i]){let w=t.get(l);w&&n.set(l,w)}return s}function ri(e,n,t){let o=new Map;for(let[s,i]of e){if(t.has(s)){o.set(s,"deletedWithParentOutside");continue}if(n.has(s))continue;i.parents.some(a=>!e.has(a)&&n.get(a)?.stamp===i.stamp)&&o.set(s,"deletedWithCreatedParent")}for(let s=o.size>0;s;){s=!1;for(let[i,r]of e){if(o.has(i))continue;let a=r.parents.find(w=>o.has(w)&&e.get(w)?.stamp===r.stamp),l=a===void 0?void 0:o.get(a);l!==void 0&&(o.set(i,l),s=!0)}}for(let s of o.keys())e.delete(s);return o}async function ai(e,n,t,o,s,i){let r=new Set,a=new Set,l=new Set(n.map(({objectApiName:d})=>d.toLowerCase())),w=new Map(n.map(d=>[d.objectApiName,d])),p=new Map;for(let[d,f]of t)o.has(d)||s.has(d)||f.parents.some(b=>(t.get(b)??o.get(b))?.stamp===f.stamp)||p.set(f.objectApiName,[...p.get(f.objectApiName)??[],f]);if(p.size===0)return{outside:r,stuck:a,requests:0};let c=e.reader.calls(),g=async d=>{try{return await i(d)}catch(f){if(f instanceof te)throw f;return}};for(let[d,f]of p){let h=w.get(d),b=await g(d);if(!h||!b)continue;let R=new Set([...h.cascadeParents,...h.restrictParents??[]].map(P=>P.toLowerCase())),j=b.fields.filter(P=>P.type==="reference"&&!R.has(P.name.toLowerCase())&&(P.referenceTo??[]).some(H=>!l.has(H.toLowerCase())));if(j.length===0)continue;let C=[...new Set(j.flatMap(P=>(P.referenceTo??[]).filter(H=>!l.has(H.toLowerCase()))))],v=await Promise.all(C.map(g)),O=new Map;if(v.forEach((P,H)=>{if(!P)return;let Q=P.keyPrefix;for(let z of P.childRelationships??[]){if(z.cascadeDelete!==!0||z.childSObject.toLowerCase()!==d.toLowerCase())continue;let fe=j.find(oe=>oe.name.toLowerCase()===z.field.toLowerCase());fe&&O.set(fe.name,[...O.get(fe.name)??[],{object:C[H],...typeof Q=="string"?{prefix:Q}:{}}])}}),O.size===0)continue;let B=[...O.keys()].map(pn),W=pe(d),D=f.map(P=>P.id),L=new Map,N=Le(D).map(P=>({objectApiName:W,soql:`SELECT Id, ${B.join(", ")} FROM ${W} WHERE Id IN (${P}) AND IsDeleted = true`,scanAll:!0}));if((await ve(e.reader,N,(P,H)=>{for(let Q of H){let z=ee(Q.Id);if(z!==void 0)for(let[fe,oe]of O){let ue=Q[fe];if(typeof ue!="string"||ee(ue)===void 0)continue;let Ae=oe.length===1?oe[0]:oe.find(he=>he.prefix!==void 0&&ue.startsWith(he.prefix));Ae&&L.set(z,[...L.get(z)??[],{object:Ae.object,id:ue}])}}},e.signal)).some(P=>!P.read))continue;let J=new Map;for(let P of L.values())for(let{object:H,id:Q}of P)J.set(H,[...J.get(H)??[],Q]);let Y=[];for(let[P,H]of J){let Q=pe(P);for(let z of Le([...new Set(H)]))Y.push({object:P,read:{objectApiName:Q,soql:`SELECT Id, IsDeleted, SystemModstamp FROM ${Q} WHERE Id IN (${z})`,scanAll:!0}})}let x=new Map;await ve(e.reader,Y.map(({read:P})=>P),(P,H)=>{for(let Q of H){let z=ee(Q.Id);z!==void 0&&Q.IsDeleted===!0&&x.set(z,ke(Q.SystemModstamp))}},e.signal);for(let P of f){let H=ee(P.id);if(H!==void 0)for(let{id:Q}of L.get(H)??[]){let z=x.get(ee(Q)??"");z!==void 0&&(z===P.stamp?r.add(H):z>P.stamp&&a.add(H))}}}return{outside:r,stuck:a,requests:e.reader.calls()-c}}async function ci(e,n,t,o){let s=[...new Set([...e.values()].map(({objectApiName:l})=>l))],i=await Promise.allSettled(s.map(t)),r=new Map([...n.keys()].map(l=>[l.toLowerCase(),l])),a=new Map;for(let[l,w]of i.entries()){if(w.status==="rejected"){if(w.reason instanceof te)throw w.reason;let p=s[l];o.set(p,Pe(w.reason));for(let[c,g]of e)g.objectApiName===p&&e.delete(c);continue}for(let p of w.value.childRelationships??[]){let c=r.get(p.childSObject.toLowerCase());if(c===void 0)continue;let g=Ie(n.get(c)??[],p.field);if(g===void 0)continue;let d=a.get(c);d||(d=new Set,a.set(c,d)),d.add(g)}}return new Map([...a].map(([l,w])=>[l,[...w]]))}async function di(e,n){let t=new Set,o=e.find(({objectApiName:i})=>i===je);if(!o||Ie(o.fields,an)===void 0)return t;let s=n.get(je);if(!s||"unread"in s||!s.live)return t;try{for await(let i of se(s.live.file)){let r=ee(i.AccountId);r!==void 0&&jn(je,i)&&t.add(r)}}catch{return new Set}return t}async function fi(e,n,t,o){if("unread"in t)return{unread:t.unread};let{input:s,previewDir:i,t0s:r,back:a,carriers:l,stranded:w,stuck:p,others:c,personAccounts:g}=e,{folder:d,reader:f,checkpoint:h,signal:b}=s,R=n.objectApiName,j=Hn(R)?e.files:void 0,C=L=>j===void 0||j.anchoredThen(L),v=new Map,O=L=>{let N=v.get(L);return N||(N=new fn(X(i,R,L)),v.set(L,N)),N},B=L=>v.get(L)?.count??0,W=new Un(e.activeFrom),D=[];try{let L=await We.read(d,h.snapshotId,R),N=Qt(d,R),{gone:V}=o,J=ut(R,h.ignoredFields),Y=bn(R,n.fields,[]),x=m=>J.has(m.toLowerCase())||V.has(m.toLowerCase()),P=Y.filter(m=>!x(m)).map(pn),H=Y.filter(x),Q=R===vo?Ie(n.fields,Bo):void 0,z=Q!==void 0&&!V.has(Q.toLowerCase())?Q:void 0,fe=R===Fo?Ie(n.fields,Eo):void 0,oe=fe!==void 0&&P.includes(fe)?fe:void 0,ue=["Id","SystemModstamp",...Jt,...P,...z!==void 0&&!P.includes(z)?[z]:[],...oe!==void 0?[qt]:[]],Ae=n.cascadeParents.filter(m=>!V.has(m.toLowerCase())),he=(n.restrictParents??[]).filter(m=>!V.has(m.toLowerCase())),Se=R===je&&Ie(n.fields,an)!==void 0,De=m=>Se&&jn(R,m),ye=Uo(n)?"toRecreate":"goneForGood",ze=e.access.heldAs(R)==="parent"?"outOfReach":ye,be=r-Dn,ne={fields:0,cleared:0,liveNotHeld:0,deletedHeld:0},Fe=m=>{let A=ee(m.Id);if(A===void 0)throw new Error(`${R} answered a record without its Id.`);return{id:String(m.Id),key:A}},ge=(m,A,I)=>m.map($=>ee(A[$])).filter($=>$!==void 0&&$!==I),we=(m,A)=>ge(Ae,m,A),Ee=(m,A)=>{let I=ke(m.SystemModstamp);return we(m,A).some($=>a.get($)?.stamp===I)},sn=Date.parse(h.takenAt),Ze=Date.parse(s.readAt)-Dn,Me=(m,A,I,$)=>{W.add(m);let S=we(m,I),F=ge(he,m,I),U=$&&ke(m.CreatedDate)>=sn&&ke(m.LastModifiedDate)<=Ze;n.undeletable&&S.length+F.length===0||D.push({id:A,parents:S,restricts:F,goesAlong:U,undeletable:n.undeletable})},ae=new Map,qe=e.lookups.get(R)??[];if(qe.length>0&&L.size>0)for await(let m of L.records()){if(De(m))continue;let A=ee(m.Id);if(A===void 0)continue;let I=qe.filter($=>{let S=ee(m[$]);return S!==void 0&&a.has(S)});I.length>0&&ae.set(A,{id:String(m.Id),fields:I})}let Te=async m=>{if(m.length===0)return;if(P.length===0){for(let F of m)F.stamp!==F.held&&await O("touched").add({Id:F.id});return}let A=m.map(F=>F.id),I=new Map,$=await L.chunk(A).batches(h.snapshotId,R,rn);for await(let F of $??[])for(let U of F){let G=ee(U.Id);G!==void 0&&I.set(G,U)}if(b?.aborted)throw new te;let S=await zo(f,n,ue,A);for(let F of m){let U=S.get(F.key);if(!U)continue;let G=I.get(F.key);if(!G)throw new Error(`The checkpoint\u2019s snapshot of ${R} does not hold record ${F.id}, which its index names.`);if(z!==void 0&&G[z]!==!0&&U[z]===!0){await O("convertedLead").add({Id:F.id});continue}if(oe!==void 0&&U[qt]===Mo&&!Nn(G[oe],U[oe])){await O("activatedContract").add({Id:F.id});continue}let ie=P.filter(ce=>!Nn(G[ce],U[ce]));if(ie.length>0){ne.fields+=ie.length;let ce=(F.cleared??[]).filter(un=>ie.includes(un)&&Go(U[un]));ce.length>0&&ne.cleared++,await O("giveBack").add({Id:F.id,fields:ie,...ce.length>0?{cleared:ce}:{}}),W.add(U)}else ke(U.SystemModstamp)!==F.held&&await O("touched").add({Id:F.id})}},Ce=[],Ne=async m=>{Ce.push(m),Ce.length>=Ve&&(await Te(Ce),Ce=[])};if(t.live)for await(let m of se(t.live.file)){let{id:A,key:I}=Fe(m),$=De(m),S=L.stampOf(A);if(S!==void 0){if($||!C(A))continue;let U=ae.get(I)?.fields;U&&ae.delete(I);let G=R===mn&&g.delete(I),ie=ke(m.SystemModstamp);(U||G||ie!==S||S>=be)&&await Ne({id:A,key:I,held:S,stamp:ie,...U?{cleared:U}:{}});continue}if(ne.liveNotHeld++,$)continue;let F=await N(I)?"broughtBackSince":ke(m.CreatedDate)>=r?"createdSince":void 0;F===void 0?await O("unexplained").add({Id:A}):j!==void 0&&!j.anchoredNow(A)?await O("outsideAdded").add({Id:A}):(await O(F).add({Id:A}),Me(m,A,I,!0))}for(let[m,A]of ae){let I=L.stampOf(A.id);I!==void 0&&await Ne({id:A.id,key:m,held:I,stamp:I,cleared:A.fields})}if(R===mn)for(let m of g){let A=L.rowOf(m);if(A<0||(g.delete(m),ae.has(m)))continue;let I=L.idAt(A),$=L.stampOf(I);$!==void 0&&await Ne({id:I,key:m,held:$,stamp:$})}if(await Te(Ce),t.deleted)for await(let m of se(t.deleted.file)){let{id:A,key:I}=Fe(m);if(L.retired(A))continue;let $=De(m);if(L.has(A)){if(ne.deletedHeld++,$)continue;if(!C(A)){await O("outsideDeleted").add({Id:A});continue}let S=w.get(I);c.has(I)?await O("deletedByOther").add({Id:A}):p.has(I)?await O(e.answeredGone.has(I)?ze:ye).add({Id:A}):S!==void 0?await O(S).add({Id:A}):Ee(m,I)?await O("withParent").add({Id:A}):n.undeletable?await O("inBin").add({Id:A}):await O(ye).add({Id:A});continue}if(l.has(I)&&!$){await O("carrier").add({Id:A});continue}if(!($||await N(I)))if(ke(m.CreatedDate)<r){let S=w.get(I),F=C(A)?c.has(I)?"deletedByOther":p.has(I)?"goneForGood":S??"deletedWhileTaken":"outsideDeleted";await O(F).add({Id:A})}else Ee(m,I)&&(await O("comesBackWithParent").add({Id:A}),Me(m,A,I,!1))}let He=t.count;if(L.size>0&&He===void 0)throw new Error(`The org gave no count of the ${R} records it holds.`);if(L.size-((He??0)-ne.liveNotHeld)-ne.deletedHeld>0){let m=new bt(L);if(t.deleted)for await(let S of se(t.deleted.file))m.mark(S.Id);let[A]=await ve(f,[wt(R,n.readMode)],(S,F)=>{for(let U of F)m.mark(U.Id)},b);if(!A.read)throw new Error(A.reason);let I=[],$=async()=>{let S=new Set;if(Se){let F=await L.chunk(I).batches(h.snapshotId,R,rn);for await(let U of F??[])for(let G of U){let ie=ee(G.Id);ie!==void 0&&De(G)&&S.add(ie)}}for(let F of I)S.has(F.slice(0,15))||await O(C(F)?ze:"outsideDeleted").add({Id:F});I=[]};for(let S of m.ids())I.push(S),I.length>=Ve&&await $();await $()}for(let m of v.values())await m.flush();let Ye=B("toRecreate"),_e=B("goneForGood"),k=B("convertedLead"),E=B("activatedContract"),K=B("deletedWithCreatedParent"),u=B("deletedWithParentOutside"),y=B("deletedByOther"),T=B("outOfReach"),M=B("carrier");return{told:{diff:{objectApiName:R,toDelete:{createdSince:B("createdSince"),broughtBackSince:B("broughtBackSince"),comesBackWithParent:B("comesBackWithParent")},toGiveBack:{records:B("giveBack"),fields:ne.fields,clearedLookups:ne.cleared},toBringBack:{inBin:B("inBin"),withParent:B("withParent"),deletedWhileTaken:B("deletedWhileTaken"),...M>0?{carriers:M}:{}},...Ye>0?{toRecreate:Ye}:{},cannotUndo:[..._e>0?[{reason:"goneForGood",count:_e}]:[],...k>0?[{reason:"convertedLead",count:k}]:[],...E>0?[{reason:"activatedContract",count:E}]:[],...K>0?[{reason:"deletedWithCreatedParent",count:K}]:[],...u>0?[{reason:"deletedWithParentOutside",count:u}]:[],...y>0?[{reason:"deletedByOther",count:y}]:[],...T>0?[{reason:"outOfReach",count:T}]:[]],outside:[],touched:B("touched"),unexplained:B("unexplained"),lastChangedBy:W.byUser(),...o.drift?{schemaDrift:o.drift}:{},notCompared:H},people:W,pending:D}}}catch(L){for(let N of v.values())await N.discard();if(L instanceof te)throw L;return{unread:Pe(L)}}}async function*Xt(e,n){let t=[];for(let o of To)if(n.diff.toDelete[o]!==0)for await(let s of se(X(e,n.diff.objectApiName,o)))typeof s.Id=="string"&&(t.push(s.Id),t.length>=Ve&&(yield t,t=[]));t.length>0&&(yield t)}async function li(e,n,t,o,s){let{input:i,previewDir:r}=e,a=n.diff.objectApiName,w=((await t(a)).childRelationships??[]).filter(C=>C.cascadeDelete===!0&&!s.has(C.childSObject.toLowerCase()));if(w.length===0)return[];let p=await o(),c=w.filter(C=>p.has(C.childSObject));if(c.length===0)return[];let g=new Set(await e.access.unseenOf([...new Set(c.map(({childSObject:C})=>C))])),d=c.filter(({childSObject:C})=>!g.has(C));if(d.length===0)return[];let f=Date.parse(i.checkpoint.takenAt);if(!Number.isFinite(f))throw new Error(`Not a date: ${i.checkpoint.takenAt}`);let h=ht(Math.ceil(f/Dn)*Dn),b=new Map,R=new Map,j=new Map;for await(let C of Xt(r,n)){let v=d;for(;v.length>0;){let O=[];for(let D of v){let L=pe(D.childSObject),N=pn(D.field),V=ft(L)==="scanAllLive",J=j.get(L)??"CreatedDate";for(let Y of Le(C))O.push({child:L,field:N,read:{objectApiName:L,soql:`SELECT Id, ${N} FROM ${L} WHERE ${N} IN (${Y}) AND ${J} >= ${h}${V?" AND IsDeleted = false":""}`,scanAll:V}})}let B=await ve(i.reader,O.map(({read:D})=>D),(D,L)=>{let{child:N,field:V}=O[D],J=b.get(N);J||(J={records:new Set,parents:new Set},b.set(N,J));for(let Y of L){let x=ee(Y.Id),P=ee(Y[V]);x!==void 0&&J.records.add(x),P!==void 0&&(J.parents.add(P),R.set(P,String(Y[V])))}},i.signal),W=new Set;B.forEach((D,L)=>{if(D.read)return;let{child:N}=O[L];if(!j.has(N)&&/No such column 'CreatedDate'/.test(D.reason)){W.add(N);return}throw new Error(`The ${D.objectApiName} records its deletion would take along could not be read: `+D.reason)});for(let D of W)j.set(D,"SystemModstamp");v=v.filter(D=>W.has(pe(D.childSObject)))}}if(R.size>0){let C=new fn(X(r,a,"outsideParents"));for(let v of R.values())await C.add({Id:v});await C.flush()}return[...b].filter(([,{records:C}])=>C.size>0).sort(([C],[v])=>C<v?-1:C>v?1:0).map(([C,{records:v,parents:O}])=>({objectApiName:C,count:v.size,parents:O.size}))}async function ui(e,n,t,o){if(e.kind==="org")return;let{objectApiName:s,toDelete:i}=n.diff,r=i.createdSince+i.broughtBackSince;if(r===0)return;let l=((await t(s)).childRelationships??[]).filter(d=>d.cascadeDelete===!0).map(d=>d.childSObject);if(l.length===0)return;let w=await o(),p=[...new Set(l.filter(d=>w.has(d)))].sort(),g=[...p.length>0?await e.unseenOf(p):[]].sort((d,f)=>+!Kt.has(d)-+!Kt.has(f));return g.length>0?{objectApiName:s,children:g,records:r}:void 0}var Kt=new Set(["Event","Task"]);async function gi(e,n){let t=new Set(n.flatMap(({pending:c})=>c.flatMap(({parents:g,restricts:d})=>[...g,...d]))),o=new Set;if(t.size>0)for(let c of n)for await(let g of Xt(e,c))for(let d of g){let f=d.slice(0,15);t.has(f)&&o.add(f)}let s=new Map(n.flatMap(({pending:c})=>c.map(g=>[g.id.slice(0,15),g]))),i=c=>c.goesAlong?c.parents.find(g=>o.has(g)):void 0,r=(c,g=new Set)=>{let d=s.get(c),f=d&&!g.has(c)?i(d):void 0;return f===void 0?c:r(f,new Set([...g,c]))},a=new Map,l=(c,g)=>{let d=a.get(c);if(d!==void 0)return d;a.set(c,!1);let f=r(c),h=g.restricts.some(b=>o.has(b)&&r(b)!==f)||g.parents.some(b=>{let R=s.get(b);return R!==void 0&&i(R)!==void 0&&l(b,R)});return a.set(c,h),h},w=[],p=[];for(let{diff:c,pending:g}of n){let d=c.objectApiName,f=O=>i(O)!==void 0&&!l(O.id.slice(0,15),O),h=g.filter(f).length;h>0&&p.push({objectApiName:d,count:h});let b=g.filter(O=>!f(O)),R=b.filter(O=>[...O.parents,...O.restricts].some(B=>o.has(B))),j=new Set(R.map(({id:O})=>O)),C=b.filter(O=>!O.undeletable&&!j.has(O.id));if(C.length+R.length===0)continue;let v=new fn(X(e,d,"undoCannot"));for(let{id:O}of C)await v.add({Id:O});for(let{id:O}of R)await v.add({Id:O,reason:"deletedBeforeParent"});await v.flush(),C.length>0&&w.push({objectApiName:d,count:C.length}),R.length>0&&w.push({objectApiName:d,count:R.length,reason:"deletedBeforeParent"})}return{undoCannot:w,withParentDeleted:p}}async function hi(e,n,t){let o={};if(n.length===0)return o;let s=Le([...n].sort()).map(i=>({objectApiName:"User",soql:`SELECT Id, Name FROM User WHERE Id IN (${i})`,scanAll:!1}));return await ve(e,s,(i,r)=>{for(let a of r)typeof a.Id=="string"&&typeof a.Name=="string"&&(o[a.Id]=a.Name)},t),o}function Vt(e){let{toDelete:n,toGiveBack:t,toBringBack:o}=e;return n.createdSince+n.broughtBackSince+n.comesBackWithParent+t.records+o.inBin+o.withParent+o.deletedWhileTaken+(o.carriers??0)+(e.toRecreate??0)+e.touched+e.unexplained+e.cannotUndo.reduce((s,i)=>s+i.count,0)>0||e.schemaDrift!==void 0}async function wi(e){let n=await e.describe(me),t=tn.safeParse("body"in n?n.body:null);if(!t.success)throw new Error(`The org gave no describe of ${me}.`);return t.data}function Yt(e){return(n,t)=>X(e,n,t)}async function pi(e,n){let t=n.fileObject.objectApiName,o=n.changes.get(t);if(!(n.unread.has(t)||o===void 0||"unread"in o))try{return{anchors:await xt({reader:e.reader,folder:e.folder,previewDir:n.previewDir,snapshotId:e.checkpoint.snapshotId,objects:n.ordered,changes:n.changes,linkDescribe:n.linkDescribe,describeGlobal:e.describeGlobal,...e.signal?{signal:e.signal}:{}})}}catch(s){if(s instanceof te)throw s;return{unread:"The links of its files to the records of the checkpoint could not be read: "+Pe(s)}}}async function eo(e){await Promise.all(["linkAdded","linkRemoved","linkChanged"].map(n=>qn(Re(e,n),{force:!0})))}async function mi(e,n){let t=n.fileObject.objectApiName,o=n.outcomes.get(t),s=n.changes.get(t);if(o===void 0||!("told"in o)||s===void 0)return;let i=new Set([...n.outcomes].filter(([,r])=>"told"in r).map(([r])=>r));try{let r=await Ut({anchors:n.anchors,reader:e.reader,folder:e.folder,snapshotId:e.checkpoint.snapshotId,t0s:n.t0s,objects:n.ordered,fileChanges:s,told:i,classFileOf:Yt(n.previewDir),previewDir:n.previewDir,queryAllFiles:e.checkpoint.takenBy?.queryAllFiles===!0&&e.queryAllFiles!==!1,...e.signal?{signal:e.signal}:{}}),{diff:a,people:l}=o.told;a.toDelete.createdSince+=r.createdSince,a.toBringBack.deletedWhileTaken+=r.deletedWhileTaken;for(let g of r.changedBy)l.add(g);a.lastChangedBy=l.byUser();let w=r.goneForGood,p=r.newFileVersion,c=a.cannotUndo.find(g=>g.reason==="goneForGood");return c!==void 0?c.count+=w:w>0&&a.cannotUndo.unshift({reason:"goneForGood",count:w}),a.cannotUndo.push(...p>0?[{reason:"newFileVersion",count:p}]:[]),r.files}catch(r){if(r instanceof te)throw r;await Kn(n.previewDir,t),await eo(n.previewDir),n.outcomes.set(t,{unread:Pe(r)});return}}async function ki(e,n){let t=n.fileObject.objectApiName,o=n.outcomes.get(t);if(o===void 0||!("told"in o))return;let{diff:s}=o.told;if(s.toDelete.createdSince+s.toDelete.broughtBackSince!==0)try{let{links:i,files:r}=await zt({anchors:n.anchors,reader:e.reader,classFileOf:Yt(n.previewDir),...e.signal?{signal:e.signal}:{}});if(i===0)return;s.outside=[...s.outside.filter(({objectApiName:a})=>a!==me),{objectApiName:me,count:i,parents:r}].sort((a,l)=>a.objectApiName<l.objectApiName?-1:a.objectApiName>l.objectApiName?1:0)}catch(i){if(i instanceof te)throw i;await Kn(n.previewDir,t),await eo(n.previewDir),n.outcomes.set(t,{unread:Pe(i)})}}async function Is(e){let{checkpoint:n,folder:t,reader:o,previewId:s,readAt:i,signal:r}=e,a=Date.parse(n.readFrom);if(!Number.isFinite(a))throw new Error(`Not a date: ${n.readFrom}`);let l=Date.parse(i);if(!Number.isFinite(l))throw new Error(`Not a date: ${i}`);if(r?.aborted)throw new te;let w=a-(a%1e3+1e3)%1e3,p=at(t,s);await yn(p);let c=[...n.objects].sort((k,E)=>k.readOrder-E.readOrder),g=e.access??Gn,d=c.filter(({objectApiName:k})=>!g.notHeld.has(k)),f=new Map,h=n.files!==void 0?d.find(({objectApiName:k})=>Hn(k)):void 0,b=await mt(o,d.map(({objectApiName:k})=>k),n.readFrom,r),R=new Map(d.map(({objectApiName:k},E)=>[k,b[E]])),j=ei(d,R),C=h!==void 0?wi(o):void 0;C?.catch(()=>{});let v=await Ht(e,j,f),O=v.requests,B=new Map,W=new Set,D=[];for(let k of c){let E=k.objectApiName,K=g.notHeld.get(E);if(K!==void 0){B.set(E,K);continue}let u=R.get(E);if(u===void 0||"unread"in u){B.set(E,u?.unread??"Its newest record was not read.");continue}let y=v.now.get(E);y===void 0?(W.add(E),D.push({object:k,fields:{gone:new Set},check:u})):"unread"in y?B.set(E,y.unread):D.push({object:k,fields:y,check:u})}let L=await kt(o,D.map(({object:k,fields:E})=>({objectApiName:k.objectApiName,readMode:k.readMode,held:k.records>0,fields:ni(k,E.gone)})),n.readFrom,p,r,D.map(({check:k})=>k)),N=new Map(D.map(({object:k},E)=>[k.objectApiName,L[E]])),V=D.filter(({object:k})=>{if(!W.has(k.objectApiName))return!1;let E=N.get(k.objectApiName);return E!==void 0&&!("unread"in E)&&E.count!==void 0&&E.count<k.records});if(V.length>0){let k=await Ht(e,V.map(({object:E})=>E),f);O+=k.requests;for(let E of V){let K=E.object.objectApiName;W.delete(K);let u=k.now.get(K);u===void 0||"unread"in u?B.set(K,u?.unread??"Its describe was not read."):E.fields=u}}let J=new Map,Y=k=>{let E=f.get(k);if(E)return Promise.resolve(E);let K=J.get(k);return K||(K=(async()=>{let u=await o.describe(k),y=tn.safeParse("body"in u?u.body:null);if(!y.success)throw new Error(`The org gave no describe of ${k}.`);return y.data})(),J.set(k,K)),K},{back:x,gone:P}=await ti({input:e,t0s:w},c,N),H=ii(x,g.userKey),Q=new Map([...P,...x]),z=oi(x,P),fe=await yt.read(t);for(let k of fe.keys())(x.has(k)||P.has(k))&&z.add(k);let oe=Zt([...fe.keys()].filter(k=>Q.has(k)),Q);zn(z,x,P);for(let k of H)x.delete(k),z.delete(k);let ue=si(c,x,P),Ae=new Map(D.map(({object:k,fields:E})=>[k.objectApiName,bn(k.objectApiName,k.fields,n.ignoredFields).filter(K=>!E.gone.has(K.toLowerCase()))])),he=await ci(x,Ae,Y,B),Se=await ai(e,D.map(({object:k})=>k),x,P,ue,Y);for(let k of Se.stuck)z.add(k);zn(z,x,P);for(let k of[...ue])x.has(k)||ue.delete(k);let De=ri(x,P,Se.outside),ye=0,ze=o.calls(),be=h!==void 0&&C!==void 0?await pi(e,{previewDir:p,ordered:c,changes:N,linkDescribe:C,fileObject:h,unread:B}):void 0;ye+=o.calls()-ze;let ne=be!==void 0&&"anchors"in be?be.anchors:void 0,Fe={input:e,previewDir:p,t0s:w,activeFrom:l-$o,back:x,carriers:ue,stranded:De,stuck:z,answeredGone:oe,others:H,access:g,lookups:he,personAccounts:await di(c,N),...ne!==void 0?{files:ne}:{}},ge=new Map;for(let{object:k,fields:E}of D){if(r?.aborted)throw new te;let K=B.get(k.objectApiName)??(be!==void 0&&"unread"in be&&k===h?be.unread:void 0),u=N.get(k.objectApiName);ge.set(k.objectApiName,K!==void 0||u===void 0?{unread:K??"Its changes were not read."}:await fi(Fe,k,u,E))}let we;if(ne!==void 0&&h!==void 0){let k=o.calls();we=await mi(e,{anchors:ne,fileObject:h,changes:N,outcomes:ge,ordered:c,previewDir:p,t0s:w}),ye+=o.calls()-k}let Ee=new Set(c.map(({objectApiName:k})=>k.toLowerCase()));if(n.files!==void 0&&h!==void 0)for(let k of[me,et])Ee.add(k.toLowerCase());let sn,Ze=()=>sn??=tt({describeGlobal:e.describeGlobal}),Me=[];for(let[k,E]of ge){if(!("told"in E))continue;let{toDelete:K}=E.told.diff;if(K.createdSince+K.broughtBackSince!==0)try{E.told.diff.outside=await li(Fe,E.told,Y,Ze,Ee);let u=await ui(g,E.told,Y,Ze);u!==void 0&&Me.push(u)}catch(u){if(u instanceof te)throw u;await Kn(p,k),ge.set(k,{unread:Pe(u)})}}if(ne!==void 0&&h!==void 0){let k=o.calls();await ki(e,{anchors:ne,fileObject:h,outcomes:ge,previewDir:p}),ye+=o.calls()-k,"told"in(ge.get(h.objectApiName)??{unread:""})||(we=void 0)}let ae=c.flatMap(({objectApiName:k})=>{let E=ge.get(k);return E&&"told"in E?[E.told]:[]}),{undoCannot:qe,withParentDeleted:Te}=await gi(p,ae),Ce=new Set(ae.map(({diff:k})=>k.objectApiName)),Ne=Me.filter(({objectApiName:k})=>Ce.has(k)),He=[...new Set(ae.flatMap(({diff:k})=>Object.keys(k.lastChangedBy)))],Xe=await hi(o,He,r),Ye=new Set(ae.flatMap(({people:k})=>[...k.active])),_e=ae.filter(({diff:k})=>W.has(k.objectApiName)&&!Vt(k)).length;return{checkpointId:n.checkpointId,previewId:s,readAt:i,objects:ae.map(({diff:k})=>k).filter(Vt),undoCannot:qe,...Te.length>0?{withParentDeleted:Te}:{},...Se.requests>0?{parentsOutsideRequests:Se.requests}:{},...O>0?{fieldsRequests:O}:{},described:{first:j.length,later:V.length},..._e>0?{fieldsNotChecked:_e}:{},...we!==void 0?{files:we}:{},...h!==void 0?{filesRequests:ye}:{},access:g.diffAccess(),...Ne.length>0?{unseen:Ne}:{},unread:c.flatMap(({objectApiName:k})=>{let E=ge.get(k),K=E&&"unread"in E?E.unread:E?void 0:B.get(k);return K===void 0?[]:[{objectApiName:k,reason:K}]}),userNames:Xe,activeLastHour:[...Ye].sort()}}var Ai=1e3,Si=25,Ci=2e3,Oe=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,no=["createdSince","broughtBackSince","comesBackWithParent","giveBack","inBin","withParent","deletedWhileTaken","toRecreate","carrier"],de={createdSince:1,broughtBackSince:2,comesBackWithParent:4,giveBack:8,inBin:16,withParent:32,deletedWhileTaken:64,toRecreate:128,carrier:256},to=32768,Pi={createdSince:de.createdSince|de.comesBackWithParent|de.carrier,broughtBackSince:de.broughtBackSince|de.carrier,comesBackWithParent:de.comesBackWithParent,giveBack:de.giveBack|de.inBin|de.withParent,inBin:de.inBin,withParent:de.withParent,deletedWhileTaken:de.deletedWhileTaken,toRecreate:de.toRecreate,carrier:de.carrier},ln=new Set(["createdSince","broughtBackSince"]),Ue={changedSincePreview:1,changedDuringRewind:2,outsideNotAccepted:4,holdsLeft:8,noUndoNotAccepted:16,beforeParentNotAccepted:32,recreateNotAccepted:64,keyTaken:128,needsUnpickedParent:256,heldByUnpicked:512},Ii=[{cls:"linkAdded",as:"unlink"},{cls:"linkRemoved",as:"relink"},{cls:"linkChanged",as:"share"}];function zs(e,n){return[n,e.automatedProcessUserId].filter(t=>typeof t=="string"&&t!=="")}function qs(e,n){let t=n.length>0?n.join(", "):"child";return`${e}: given back once the ${t} records hanging from it that the rewind deletes were gone, as those records held some of its values in place`}function Qe(e){let n=en(e);return n===null?Number.NaN:Date.parse(n)}function re(e,n){let t=e.Id;if(typeof t!="string"||!Oe.test(t))throw new Error(`A line of ${n} names no record: the diff it was read from is not whole.`);return t}async function*q(e){try{for await(let n of se(e))yield n}catch(n){if(n.code!=="ENOENT")throw n}}function Di(e,n){return Jn(e,`${pe(n)}.beforeParent.ndjson`)}var on=class{constructor(n){this.file=n}file;lines=[];written=!1;async add(n){this.lines.push(`${JSON.stringify(n)}
10
+ `),this.lines.length>=Ci&&await this.flush()}async flush(){if(this.lines.length===0)return;let n=this.lines.join("");this.lines=[],await bi(this.file,n,{encoding:"utf8",mode:nn,flag:this.written?"a":"w"}),this.written=!0}},Vn=class{entries=new Map;add(n,t,o,s,i){let r=`${n}\0${t}\0${s??""}\0${i??""}`,a=this.entries.get(r);a||(a={objectApiName:n,reason:t,...s!==void 0?{by:s}:{},...i!==void 0?{needs:i}:{},count:0,ids:[]},this.entries.set(r,a)),a.count++,a.ids.length<Si&&a.ids.push(o)}all(n){let t=(o,s)=>(o??"")<(s??"")?-1:(o??"")>(s??"")?1:0;return[...this.entries.values()].sort((o,s)=>(n.get(o.objectApiName)??0)-(n.get(s.objectApiName)??0)||t(o.reason,s.reason)||t(o.by,s.by)||t(o.needs,s.needs))}};function oo(e,n){if(!(typeof n!="string"||n===""))return e==="SetupOwnerId"&&Oe.test(n)?n.slice(0,15):n}async function Ni(e,n,t,o){let s=new Z;if(e.customSetting===void 0)return s;let i=kn(e.customSetting).toLowerCase(),r=e.fields.find(w=>w.toLowerCase()===i);if(r===void 0)return s;let a=new Z;for(let w of o){let p=X(t,e.objectApiName,w);for await(let c of q(p))a.add(re(c,p))}if(a.size===0)return s;let l=new Set;for await(let w of q($e(n,e.objectApiName))){let p=oo(r,w[r]);p!==void 0&&l.add(p)}if(l.size===0)return s;for await(let w of q(cn(n,e.objectApiName))){if(typeof w.Id!="string"||!a.has(w.Id))continue;let p=oo(r,w[r]);p!==void 0&&l.has(p)&&s.add(w.Id)}return s}function io(e){return{objectApiName:e,deleted:0,withParentDeleted:0,undoCannot:0,nextPassDeleted:0,broughtBack:0,backWithParent:0,recreated:0,givenBackFirst:0,givenBackAfter:0,givenBackNextPass:0,skipped:0}}function ji(e){return Object.entries(e).some(([n,t])=>n!=="objectApiName"&&t!==0)}function so(e){return`${e.ContentDocumentId.slice(0,15)}:${e.LinkedEntityId.slice(0,15)}`}function ro(e,n,t){let s=(n==="linkChanged"?Rt:Rn).safeParse(e);if(!s.success)throw new Error(`A line of ${t} names no link: the diff it was read from is not whole.`);return s.data}function co(e){return{unlink:{file:Re(e,"linkAdded"),count:0},relink:{file:Re(e,"linkRemoved"),count:0},share:{file:Re(e,"linkChanged"),count:0}}}async function Li(e){let n={};for(let{cls:o,as:s}of Ii){let i=new Set,r=Re(e.confirmedDir,o);for await(let p of q(r))i.add(so(ro(p,o,r)));let a=Re(e.freshDir,o),l=new on(Re(e.dir,o)),w=0;for await(let p of q(a)){let c=ro(p,o,a);if(e.deleted(c.ContentDocumentId)||e.deleted(c.LinkedEntityId))continue;let g=e.pass===2&&o==="linkRemoved"&&(e.earlier(c.ContentDocumentId)||e.earlier(c.LinkedEntityId));if(!i.has(so(c))&&!g){e.left.add(me,"changedSincePreview",c.Id);continue}await l.add(p),w++}await l.flush(),n[s]={file:l.file,count:w}}let t=co(e.dir);return{unlink:n.unlink??t.unlink,relink:n.relink??t.relink,share:n.share??t.share}}var vi=["inBin","withParent","deletedWhileTaken","carrier"],Bi=new Set(["id","createdbyid","lastmodifiedbyid","systemmodstamp","createddate","lastmodifieddate"]);function Fi(e,n){return e.flatMap(t=>{let o=n[t];return typeof o=="string"&&Oe.test(o)?[o.slice(0,15)]:[]})}function ao(e,n,t){let o=t===void 0?void 0:new Set(t.map(s=>s.toLowerCase()));return Object.entries(e).flatMap(([s,i])=>{let r=s.toLowerCase();if(Bi.has(r)||o!==void 0&&!o.has(r))return[];if(typeof i!="string"||!Oe.test(i))return[];let a=i.slice(0,15);return n.has(a)?[{field:s,needs:n.get(a)}]:[]})}async function Ei(e,n,t){let{freshDir:o,heldRows:s}=e,i=new Map,r=new Map;for(let d of n)for(let f of[...vi,"toRecreate","comesBackWithParent"]){let h=X(o,d.objectApiName,f);for await(let b of q(h)){let R=re(b,h).slice(0,15);i.set(R,d.objectApiName),r.set(R,f)}}let a=new Map;for(let d of n)if(d.cascadeParents.length!==0)for await(let f of q(cn(o,d.objectApiName))){if(typeof f.Id!="string"||!Oe.test(f.Id))continue;let h=f.Id.slice(0,15),b=r.get(h);(b==="withParent"||b==="comesBackWithParent")&&a.set(h,Fi(d.cascadeParents,f))}let l=new Set;for(let[d,f]of r)(f==="inBin"||f==="deletedWhileTaken"||f==="carrier")&&t(i.get(d)??"")&&l.add(d);for(let d=l.size>0;d;){d=!1;for(let[f,h]of a)l.has(f)||!h.some(b=>l.has(b))||(l.add(f),d=!0)}let w=(d,f=new Set)=>{let h=i.get(d);if(!(h===void 0||f.has(d))){if(!t(h))return h;f.add(d);for(let b of a.get(d)??[]){if(l.has(b))continue;let R=w(b,f);if(R!==void 0)return R}}},p=new Map,c=new Map;for(let[d,f]of r){if(l.has(d)||f==="comesBackWithParent")continue;let h=i.get(d)??"";if(!t(h))p.set(d,h);else if(f==="withParent"){let b=w(d);c.set(d,b),p.set(d,b)}}let g=new Map;if(s===void 0)return{comes:l,left:c,fields:g};for(let d of[...n].reverse()){let f=d.objectApiName;if(!t(f))continue;let h=new Set(d.cascadeParents.map(v=>v.toLowerCase())),b=[],R=X(o,f,"toRecreate");for await(let v of q(R))b.push(re(v,R));if(b.length>0)for await(let v of s(f,b)){if(typeof v.Id!="string"||!Oe.test(v.Id))continue;let O=v.Id.slice(0,15),B=ao(v,p,void 0);if(B.length===0)continue;let W=B.find(({field:D})=>h.has(D.toLowerCase()));W!==void 0?(c.set(O,W.needs),p.set(O,W.needs)):g.set(O,{fields:B.map(({field:D})=>D),needs:B[0].needs})}let j=new Map,C=X(o,f,"giveBack");for await(let v of q(C)){let O=re(v,C),B=Array.isArray(v.fields)?v.fields.filter(W=>typeof W=="string"):void 0;j.set(O.slice(0,15),{id:O,differ:B})}for(let v of["inBin","withParent"]){let O=X(o,f,v);for await(let B of q(O)){let W=re(B,O);l.has(W.slice(0,15))&&j.set(W.slice(0,15),{id:W,differ:void 0})}}if(j.size!==0)for await(let v of s(f,[...j.values()].map(({id:O})=>O))){if(typeof v.Id!="string"||!Oe.test(v.Id))continue;let O=v.Id.slice(0,15),B=j.get(O);if(B===void 0)continue;let W=ao(v,p,B.differ);W.length>0&&g.set(O,{fields:W.map(({field:D})=>D),needs:W[0].needs})}}return{comes:l,left:c,fields:g}}function Mi(e,n){let t=n!==void 0?` Rewind ${n} with it to put it back.`:"",o=n??"an object this rewind was not limited to";switch(e){case"needsUnpickedParent":return`Left: it comes back only with a parent this rewind leaves deleted, or a lookup of it names a record this rewind leaves deleted (${o}), which the org refuses to point at.${t}`;case"heldByUnpicked":return`Given back but for the values records of ${o} created since hold in place: this rewind leaves them, so the org refuses to change those values.${t}`;case"outsideNotAccepted":return`Kept: records of ${o} created since hang from it, which its deletion would take along, and deleting them was not accepted.${t}`;default:return`Kept: records of ${o} this rewind leaves as they are hang from it, and its deletion would take them along.${t}`}}async function Ti(e){let{checkpoint:n,pass:t,confirmedDir:o,freshDir:s,dir:i,signal:r}=e,a=Date.parse(n.takenAt);if(!Number.isFinite(a))throw new Error(`Not a date: ${n.takenAt}`);let l=Date.parse(e.readAt);if(!Number.isFinite(l))throw new Error(`Not a date: ${e.readAt}`);let w=l-Ai;if(await yn(i),(await Ri(i)).length>0)throw new Error(`A rewind's plan is written to a folder of its own: ${i} is not empty.`);let p=()=>{if(r?.aborted)throw new te},c=[...n.objects].map(lt).sort((u,y)=>u.readOrder-y.readOrder),g=new Map(c.map(({objectApiName:u},y)=>[u,y])),d=new Map(c.map(({objectApiName:u})=>[u,io(u)])),f=u=>d.get(u)??io(u),h=new Set(e.ownWriters.map(u=>u.slice(0,15))),b=new Map(Object.entries(e.removalStamps??{}).map(([u,y])=>[u.slice(0,15),Qe(y)])),R=u=>fo(u,w,h,b),j=(u,y)=>u.flatMap(T=>{let M=y[T];return typeof M=="string"&&Oe.test(M)?[M]:[]}),C=(u,y)=>j(u.cascadeParents,y),v=(u,y)=>j(u.restrictParents??[],y),O=new Vn,B=u=>e.objects===void 0||e.objects.has(u),W=e.objects!==void 0?await Ei(e,c,B):void 0,D=new Map,L=new Map,N=new on(Jn(i,"leftFields.ndjson")),V=0,J=(u,y,T,M)=>{if(O.add(u,y,T,void 0,M),D.set(T.slice(0,15),Mi(y,M)),M===void 0)return;let _=L.get(M);_||(_=new Z,L.set(M,_)),_.add(T)},Y=new Z,x=new Z,P=new Z,H=new Z,Q=new Z,z=new Z,fe=[];for(let u of c){p();let y=u.objectApiName,T=B(y),M=(g.get(y)??0)+1,_=f(y),m=new Z;for(let S of no){let F=X(o,y,S);for await(let U of q(F))m.add(re(U,F),de[S])}let A=t===2?await Gi(s,y,w,h,b,fe):void 0,I=new Map,$=S=>{let F=I.get(S);return F||(F=new on(X(i,y,S)),I.set(S,F)),F};for(let S of no){if(!T&&S!=="comesBackWithParent"&&S!=="createdSince")continue;let F=X(s,y,S);for await(let U of q(F)){let G=re(U,F),ie=(m.flagsOf(G)&Pi[S])!==0;if(!T&&!(t===2?ie:S==="comesBackWithParent"&&ie&&W?.comes.has(G.slice(0,15))))continue;ie&&m.add(G,to),ie&&ln.has(S)&&(m.flagsOf(G)&de.carrier)!==0&&z.add(G);let ce=A?.other.flagsOf(G)??0,un=T&&A?.own.has(G)===!0;if(ce>0||!(ie||un)){let Ke=ce>0?"changedDuringRewind":"changedSincePreview";O.add(y,Ke,G,ce>0?fe[ce-1]:void 0),ln.has(S)&&P.add(G,Ue[Ke]);continue}if(W!==void 0&&T){let Ke=G.slice(0,15);if(S==="comesBackWithParent"&&!W.comes.has(Ke))continue;if((S==="withParent"||S==="toRecreate")&&W.left.has(Ke)){J(y,"needsUnpickedParent",G,W.left.get(Ke));continue}let gn=W.fields.get(Ke);if(gn!==void 0&&(S==="giveBack"||S==="toRecreate"||S==="inBin"||S==="withParent")){J(y,"needsUnpickedParent",G,gn.needs),await N.add({Id:G,fields:gn.fields}),V++;let Qn=Array.isArray(U.fields)?U.fields:[],lo=Qn.filter(Zn=>typeof Zn=="string"&&!gn.fields.some(uo=>uo.toLowerCase()===Zn.toLowerCase()));if(S==="giveBack"&&Qn.length>0&&lo.length===0)continue}}if(S==="toRecreate"&&!e.acceptRecreate){O.add(y,"recreateNotAccepted",G);continue}await $(S).add(S==="giveBack"?U:{Id:G}),S==="giveBack"&&W!==void 0&&Y.add(G,M),ln.has(S)?x.add(G,M):S==="comesBackWithParent"?(H.add(G),_.nextPassDeleted++):S==="carrier"?(H.add(G),Q.add(G),_.carriers=(_.carriers??0)+1,_.nextPassDeleted++):S==="inBin"||S==="deletedWhileTaken"?_.broughtBack++:S==="withParent"?_.backWithParent++:S==="toRecreate"&&_.recreated++,(S==="inBin"||S==="withParent")&&await $("giveBack").add({Id:G})}}for(let S of I.values())await S.flush();_.skipped=T?m.count(S=>(S&to)===0):0}await N.flush();let oe=new Map;if(W!==void 0){let u=new Z;for(let y of c){let T=y.objectApiName;if(B(T)||y.cascadeParents.length===0)continue;let M=new Z;for(let _ of ln){let m=X(s,T,_);for await(let A of q(m))M.add(re(A,m))}for await(let _ of q($e(s,T))){if(typeof _.Id!="string"||!Oe.test(_.Id)||x.has(_.Id))continue;let m=M.has(_.Id),A=m&&Qe(_.CreatedDate)>=a&&Qe(_.LastModifiedDate)<=w;for(let I of C(y,_)){let $=x.flagsOf(I);if($>0){if(P.has(I)||A&&e.acceptOutside)continue;let F=c[$-1].objectApiName;oe.set(I.slice(0,15),T),A?(P.add(I,Ue.outsideNotAccepted),J(F,"outsideNotAccepted",I,T)):P.add(I,Ue.holdsLeft);continue}let S=Y.flagsOf(I);m&&S>0&&u.add(I)&&J(c[S-1].objectApiName,"heldByUnpicked",I,T)}}}}if(n.scope.mode==="picked"&&!e.acceptOutside)for(let u of c){let y=X(s,u.objectApiName,"outsideParents");for await(let T of q(y)){let M=re(T,y);!x.has(M)||P.has(M)||z.has(M)||(P.add(M,Ue.outsideNotAccepted),O.add(u.objectApiName,"outsideNotAccepted",M))}}let ue=c.map(u=>({object:u,file:$e(s,u.objectApiName)}));for(let u=P.size>0;u;){p(),u=!1;for(let{object:y,file:T}of ue)for await(let M of q(T)){if(!P.has(M.Id))continue;let _=oe.get(String(M.Id).slice(0,15));for(let m of C(y,M))!x.has(m)||P.has(m)||(P.add(m,Ue.holdsLeft),_!==void 0&&oe.set(m.slice(0,15),_),u=!0)}}for(let{object:u,file:y}of ue)for await(let T of q(y))if(x.has(T.Id)&&P.flagsOf(T.Id)===Ue.holdsLeft){let M=re(T,y),_=oe.get(M.slice(0,15));_!==void 0?J(u.objectApiName,"holdsLeft",M,_):O.add(u.objectApiName,"holdsLeft",M)}let Ae=new Z,he=u=>x.has(u)&&!P.has(u),Se=new Map,De=u=>{let y=u.slice(0,15);return Se.get(y)??y},ye=new Z,ze=[...c].reverse(),be=[];for(let u of ze){p();let y=u.objectApiName,T=$e(s,y),M=new on(Di(i,y)),_=0;for await(let m of q(T)){let A=typeof m.Id=="string"?m.Id:"";if(!he(A))continue;let I=Qe(m.LastModifiedDate),$=C(u,m).filter(he);if($.length>0&&Qe(m.CreatedDate)>=a&&(I<=w||I<=(b.get(A.slice(0,15))??Number.NaN))){let G=De($[0]);if(!($.some(ce=>ye.has(ce))||v(u,m).some(ce=>he(ce)&&De(ce)!==G))){Ae.add(A),Se.set(A.slice(0,15),G),f(y).withParentDeleted++;continue}ye.add(A)}let F=[...C(u,m),...v(u,m)].filter(he);if(u.undeletable&&F.length===0)continue;let U=F.length>0?"beforeParentNotAccepted":"noUndoNotAccepted";e.acceptNoUndo?(f(y).undoCannot++,F.length>0&&(await M.add({Id:A,parents:F}),_++)):(P.add(A,Ue[U]),O.add(y,U,A))}await M.flush(),_>0&&be.push({objectApiName:y,count:_,file:M.file})}let ne=new xe(`${i}/deletes`),Fe=new xe(`${i}/along-to-draft`),ge={},we=new Z,Ee=0;for(let u of c){p();let y=u.objectApiName,T=$e(s,y),M=0;for await(let _ of q(T)){let m=typeof _.Id=="string"?_.Id:"";if(x.has(m)&&(Ee++,!P.has(m))){for(let A of C(u,_))we.has(A)||we.add(A,(g.get(y)??0)+1);if(Ae.has(m)){ot([y]).length>0&&await Fe.add(y,m);continue}await ne.add(y,m),M++,t===2&&R(_)&&typeof _.LastModifiedDate=="string"&&(ge[m]=_.LastModifiedDate)}}f(y).deleted=M}if(Ee!==x.size)throw new Error("The fresh diff's reads do not hold every record its classes name to delete.");let sn=await En.of(ne),Ze=await En.of(Fe),Me=new Z;if(t===1&&H.size>0){for(let u of c)for await(let y of q(cn(s,u.objectApiName)))if(H.has(y.Id))for(let T of C(u,y))Me.add(T)}let ae=new Map;for(let u of c){let y=await Ni(u,s,i,["inBin","deletedWhileTaken"]);if(y.size===0)continue;ae.set(u.objectApiName,y);let T=f(u.objectApiName);T.broughtBack-=y.size,T.keyTaken=y.size;for(let M of["inBin","deletedWhileTaken"]){let _=X(i,u.objectApiName,M);for await(let m of q(_)){let A=re(m,_);y.has(A)&&O.add(u.objectApiName,"keyTaken",A)}}}let qe=new xe(`${i}/giveBackFirst`),Te=new xe(`${i}/giveBackAfter`),Ce=[];for(let u of c){p();let y=u.objectApiName,T=X(i,y,"giveBack"),M=!1;for await(let $ of q(T))if(we.has($.Id)){M=!0;break}let _=new Z;if(M)for await(let $ of q($e(s,y)))we.has($.Id)&&C(u,$).some(he)&&_.add(String($.Id));let m=f(y),A=new Set,I=ae.get(y);for await(let $ of q(T)){let S=re($,T);if(I?.has(S)===!0)continue;let F=we.flagsOf(S),U=_.has(S);if(F>0){if(await Te.add(y,S),m.givenBackAfter++,A.add(c[F-1].objectApiName),!U)continue}else if(!U&&Me.has(S)){m.givenBackNextPass++;continue}await qe.add(y,S),m.givenBackFirst++}A.size>0&&Ce.push({objectApiName:y,by:[...A]})}let Ne=new xe(`${i}/bringBack`),He=new xe(`${i}/recreate`);for(let u of ze){let y=ae.get(u.objectApiName);for(let M of["carrier","inBin","deletedWhileTaken"]){let _=X(i,u.objectApiName,M);for await(let m of q(_)){let A=re(m,_);y?.has(A)!==!0&&await Ne.add(u.objectApiName,A)}}let T=X(i,u.objectApiName,"toRecreate");for await(let M of q(T))await He.add(u.objectApiName,re(M,T))}let Xe=new Z;if(t===2)for(let u of c)for(let y of["inBin","withParent","deletedWhileTaken","carrier","toRecreate"]){let T=X(o,u.objectApiName,y);for await(let M of q(T))Xe.add(re(M,T))}let Ye=n.files===void 0||!B(le)?co(i):await Li({confirmedDir:o,freshDir:s,dir:i,pass:t,deleted:u=>Oe.test(u)&&he(u),earlier:u=>Oe.test(u)&&(Xe.has(u)||Xe.has(e.recreated?.originalOf(u.slice(0,15))??u)),left:O}),_e=new xe(`${i}/unlinkFrom`);for(let u of ln){let y=X(i,le,u);for await(let T of q(y)){let M=re(T,y);(P.flagsOf(M)&Ue.outsideNotAccepted)!==0&&await _e.add(le,M)}}let k={...e.removalStamps,...ge},E=Object.keys(k).length>0,K=c.map(({objectApiName:u})=>f(u)).filter(ji);return{pass:t,dir:i,deletes:sn,removal:{runStartedAt:new Date(a),runEndedAt:new Date(w),includeChanged:!1,...E?{removalStamps:k}:{},...e.removalSpans&&e.removalSpans.length>0?{removalSpans:[...e.removalSpans]}:{}},bringBack:await Ne.finish(),carriers:Q,goesAlong:Ae,alongToDraft:Ze,recreate:await He.finish(),giveBack:{beforeDeletes:await qe.finish(),afterDeletes:await Te.finish(),heldBy:Ce},restore:{changedAfter:e.readAt,ownWriters:[...e.ownWriters],includeChanged:!1,...E?{stamps:k}:{}},objects:K,undoCannot:K.filter(u=>u.undoCannot>0).map(({objectApiName:u,undoCannot:y})=>({objectApiName:u,count:y})),beforeParent:be.reverse(),left:O.all(g),links:{...Ye,unlinkFrom:await _e.finish()},...W!==void 0?{limited:{objects:c.map(({objectApiName:u})=>u).filter(B),needs:[...L].sort(([u],[y])=>(g.get(u)??0)-(g.get(y)??0)).map(([u,y])=>({objectApiName:u,records:y.size})),why:D,leftFields:{file:N.file,count:V}}}:{}}}function Hs(e,n){if(n===void 0)return e;let t=i=>i.filter(r=>n.has(r.objectApiName)),{files:o,...s}=e;return{...s,objects:t(e.objects),undoCannot:t(e.undoCannot),unread:t(e.unread),...e.withParentDeleted?{withParentDeleted:t(e.withParentDeleted)}:{},...e.unseen?{unseen:t(e.unseen)}:{},...o!==void 0&&n.has(le)?{files:o}:{}}}var _i=200;function Ks(e,n){return async function*(t,o){if(o.length===0)return;let s=await We.read(n,e.snapshotId,t);for(let i=0;i<o.length;i+=Ve){let r=await s.chunk(o.slice(i,i+Ve)).batches(e.snapshotId,t,_i);for await(let a of r??[])yield*a}}}var $i=new Set(["needsUnpickedParent","heldByUnpicked","outsideNotAccepted","holdsLeft","keyTaken"]);async function Wi(e,n){let t=0;for await(let o of q(X(e,n,"giveBack")))Array.isArray(o.fields)&&t++;return t}async function xi(e){let n=new Set(e.limited?.objects??e.objects.map(i=>i.objectApiName)),t=[];for(let i of e.objects){let r={objectApiName:i.objectApiName,picked:n.has(i.objectApiName),toDelete:i.deleted+i.withParentDeleted+i.nextPassDeleted-(i.carriers??0),toGiveBack:await Wi(e.dir,i.objectApiName),toBringBack:i.broughtBack+i.backWithParent,toRecreate:i.recreated};r.toDelete+r.toGiveBack+r.toBringBack+r.toRecreate>0&&t.push(r)}let o=new Map;for(let i of e.left){if(!n.has(i.objectApiName)||!$i.has(i.reason))continue;let r=`${i.objectApiName}\0${i.reason}`,a=o.get(r);a?a.count+=i.count:o.set(r,{objectApiName:i.objectApiName,reason:i.reason,count:i.count})}let s=e.undoCannot.flatMap(({objectApiName:i,count:r})=>{let a=e.beforeParent.find(w=>w.objectApiName===i),l=r-(a?.count??0);return[...l>0?[{objectApiName:i,count:l}]:[],...a!==void 0&&a.count>0?[{objectApiName:i,count:a.count,reason:"deletedBeforeParent"}]:[]]});return{objects:[...n],acts:t,left:[...o.values()],needs:e.limited?.needs??[],undoCannot:s}}async function Vs(e){let n=Jn(e.previewDir,`selection-${yi(4).toString("hex")}`);try{let t=await Ti({checkpoint:e.checkpoint,pass:1,confirmedDir:e.previewDir,freshDir:e.previewDir,readAt:e.readAt,ownWriters:[],acceptOutside:e.acceptOutside,acceptNoUndo:!0,acceptRecreate:!0,...e.objects?{objects:e.objects}:{},...e.heldRows?{heldRows:e.heldRows}:{},dir:n,...e.signal?{signal:e.signal}:{}});return await xi(t)}finally{await Oi(n,{recursive:!0,force:!0})}}function fo(e,n,t,o){let s=Qe(e.LastModifiedDate);if(!(s>n))return!1;let i=typeof e.Id=="string"?e.Id:"",r=typeof e.LastModifiedById=="string"?e.LastModifiedById:"";return s<=(o.get(i.slice(0,15))??Number.NaN)||t.has(r.slice(0,15))}async function Gi(e,n,t,o,s,i){let r={own:new Z,other:new Z};for(let a of[$e(e,n),cn(e,n)])for await(let l of q(a)){if(!(Qe(l.LastModifiedDate)>t))continue;let p=re(l,a);if(fo(l,t,o,s)){r.own.add(p);continue}let c=typeof l.LastModifiedById=="string"?l.LastModifiedById:"",g=i.indexOf(c);g<0&&(i.push(c),g=i.length-1),r.other.add(p,g+1)}return r}export{Gn as a,ss as b,X as c,Uo as d,Is as e,zs as f,qs as g,Ti as h,Hs as i,Ks as j,xi as k,Vs as l};