sandforge 1.80.0 → 1.82.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -0
- package/bin/sandforge-pipeline.mjs +12 -0
- package/bin/sandforge-users.mjs +12 -0
- package/lib/{chunk-J525F5KI.mjs → chunk-27Z76O2O.mjs} +1 -1
- package/lib/chunk-2JZGCCPG.mjs +9 -0
- package/lib/{chunk-ELFXJHU7.mjs → chunk-2UU42PTD.mjs} +1 -1
- package/lib/{chunk-N652NMZ4.mjs → chunk-32EUNQT6.mjs} +52 -52
- package/lib/chunk-3C2ZZIFN.mjs +7 -0
- package/lib/chunk-3CX7GPCR.mjs +7 -0
- package/lib/chunk-3HEMJTAP.mjs +925 -0
- package/lib/{chunk-BY2HJFFG.mjs → chunk-3HROD5RE.mjs} +1 -1
- package/lib/{chunk-OHWNPXWW.mjs → chunk-3MGMNK3Q.mjs} +1 -1
- package/lib/{chunk-PZPJKATS.mjs → chunk-3SKLBRPL.mjs} +8 -8
- package/lib/chunk-3XG25GTF.mjs +7 -0
- package/lib/chunk-42BFLWHR.mjs +7 -0
- package/lib/chunk-466F37VD.mjs +7 -0
- package/lib/chunk-47UHTN3Q.mjs +7 -0
- package/lib/chunk-4JKR4PTZ.mjs +8 -0
- package/lib/{chunk-COFG7Q6R.mjs → chunk-52EXDVPN.mjs} +1 -1
- package/lib/{chunk-SAR5622P.mjs → chunk-54HYHHVL.mjs} +1 -1
- package/lib/{chunk-RSWDYIHY.mjs → chunk-5GBO4KD5.mjs} +1 -1
- package/lib/chunk-5K2I2DMP.mjs +11 -0
- package/lib/{chunk-AV5SWEHP.mjs → chunk-6FARZYMJ.mjs} +1 -1
- package/lib/{chunk-BV6VTP3J.mjs → chunk-6GQUZ4IP.mjs} +1 -1
- package/lib/chunk-6KP6WETK.mjs +9 -0
- package/lib/{chunk-MJVTDA5Q.mjs → chunk-6VSZNZHH.mjs} +1 -1
- package/lib/{chunk-XUWL6ZPC.mjs → chunk-7CVDVBEE.mjs} +1 -1
- package/lib/{chunk-UCD54V2M.mjs → chunk-7EYQYZJP.mjs} +1 -1
- package/lib/{chunk-5K5VLULK.mjs → chunk-7LKI7OAS.mjs} +1 -1
- package/lib/chunk-7PY3VQP3.mjs +7 -0
- package/lib/chunk-7SDZR6SR.mjs +7 -0
- package/lib/chunk-7WSLT5VX.mjs +8 -0
- package/lib/chunk-A32ISQ6M.mjs +28 -0
- package/lib/{chunk-M3ROUWDX.mjs → chunk-A65ADTCR.mjs} +1 -1
- package/lib/chunk-A7JJWOLT.mjs +7 -0
- package/lib/chunk-AUS6NFLZ.mjs +8 -0
- package/lib/chunk-BMTNTBBM.mjs +7 -0
- package/lib/{chunk-SOU4FRYN.mjs → chunk-BN33LVPQ.mjs} +1 -1
- package/lib/chunk-BNKT3R3F.mjs +7 -0
- package/lib/{chunk-K2FBZIXY.mjs → chunk-BWWQXU2B.mjs} +1 -1
- package/lib/{chunk-IC2C2GOF.mjs → chunk-BXZ73A5M.mjs} +1 -1
- package/lib/{chunk-WA7EYLAQ.mjs → chunk-C2N2TNEU.mjs} +1 -1
- package/lib/{chunk-BKDV4ENO.mjs → chunk-C3LNYAVJ.mjs} +1 -1
- package/lib/{chunk-XLXIPIEW.mjs → chunk-CBL42DUU.mjs} +1 -1
- package/lib/chunk-CCEH7L53.mjs +7 -0
- package/lib/chunk-CELEBWEZ.mjs +7 -0
- package/lib/chunk-CV47FDQW.mjs +7 -0
- package/lib/{chunk-2UZPIMUC.mjs → chunk-CZLJZQCS.mjs} +1 -1
- package/lib/chunk-DBBPDSFN.mjs +7 -0
- package/lib/chunk-DIL62SUN.mjs +7 -0
- package/lib/chunk-DIS254AN.mjs +7 -0
- package/lib/{chunk-BTWDMNN3.mjs → chunk-DJCGURW7.mjs} +1 -1
- package/lib/{chunk-F6GUDTOB.mjs → chunk-DT3T7FRD.mjs} +1 -1
- package/lib/{chunk-IGYH7GMA.mjs → chunk-DWMRIWV5.mjs} +1 -1
- package/lib/{chunk-YRQGKDHM.mjs → chunk-EEFUE2ES.mjs} +1 -1
- package/lib/{chunk-FGRG7ANU.mjs → chunk-EOFO3PHS.mjs} +1 -1
- package/lib/{chunk-KBJ5VERV.mjs → chunk-FA4ZKDCU.mjs} +1 -1
- package/lib/{chunk-WU3GLFZO.mjs → chunk-FKK5YBGZ.mjs} +1 -1
- package/lib/chunk-FOIWWK7G.mjs +156 -0
- package/lib/chunk-FZF23M6R.mjs +7 -0
- package/lib/chunk-G2JR3F63.mjs +7 -0
- package/lib/{chunk-JEERQRLW.mjs → chunk-GBGHJTPC.mjs} +1 -1
- package/lib/{chunk-3RZQZHEB.mjs → chunk-GCGHHN4K.mjs} +1 -1
- package/lib/{chunk-RPI7LRTW.mjs → chunk-GGNUACTY.mjs} +1 -1
- package/lib/{chunk-EMNC6YI4.mjs → chunk-GGUOIDWP.mjs} +1 -1
- package/lib/chunk-GHPR5UVV.mjs +7 -0
- package/lib/{chunk-X5JYBPXP.mjs → chunk-GJ6SZVHT.mjs} +1 -1
- package/lib/{chunk-W622GUAW.mjs → chunk-H4JUYUSL.mjs} +1 -1
- package/lib/{chunk-XAMBCQPU.mjs → chunk-H4OBZIX3.mjs} +1 -1
- package/lib/{chunk-WIO4XO4F.mjs → chunk-HFSBDM7B.mjs} +1 -1
- package/lib/{chunk-L77FJZEP.mjs → chunk-HFUDCNU5.mjs} +1 -1
- package/lib/chunk-HIHCYMSL.mjs +7 -0
- package/lib/chunk-HKUWHVI7.mjs +9 -0
- package/lib/chunk-HQQVANWQ.mjs +20 -0
- package/lib/chunk-ICIYL45C.mjs +7 -0
- package/lib/chunk-IRZJU2PG.mjs +22 -0
- package/lib/chunk-ISSP2FZ5.mjs +7 -0
- package/lib/chunk-IVZJSDJD.mjs +7 -0
- package/lib/chunk-J24TIGSI.mjs +10 -0
- package/lib/{chunk-UNJA4J37.mjs → chunk-JESRFE2Z.mjs} +4 -4
- package/lib/chunk-JFNLKHY6.mjs +8 -0
- package/lib/chunk-JH27IKCO.mjs +9 -0
- package/lib/chunk-JJITOWZK.mjs +7 -0
- package/lib/{chunk-E5AHXLS6.mjs → chunk-JKT5YAQ2.mjs} +1 -1
- package/lib/{chunk-IWDREM66.mjs → chunk-JLZRZL5E.mjs} +1 -1
- package/lib/{chunk-FPKYYFM7.mjs → chunk-JPEVIXNH.mjs} +1 -1
- package/lib/chunk-JQZTMFO7.mjs +7 -0
- package/lib/chunk-KIMQQ6JQ.mjs +7 -0
- package/lib/{chunk-MILU7WFN.mjs → chunk-KJYEQHYP.mjs} +1 -1
- package/lib/chunk-KKOA62S4.mjs +474 -0
- package/lib/chunk-KP5G6FUC.mjs +7 -0
- package/lib/{chunk-JWTSEDIQ.mjs → chunk-L4INJ5TZ.mjs} +1 -1
- package/lib/{chunk-OLSGVAIL.mjs → chunk-LAUOSXMN.mjs} +53 -53
- package/lib/{chunk-MTMH6H2A.mjs → chunk-LCDPCUXS.mjs} +1 -1
- package/lib/{chunk-KDGMAGQR.mjs → chunk-LHU6CPGE.mjs} +1 -1
- package/lib/{chunk-YAZO75G2.mjs → chunk-LNXBCE7E.mjs} +1 -1
- package/lib/chunk-LXDSRP2W.mjs +7 -0
- package/lib/{chunk-2YIV2OB2.mjs → chunk-MIDBQ7SD.mjs} +1 -1
- package/lib/{chunk-TTKXMDBN.mjs → chunk-MKTXJCXN.mjs} +4 -4
- package/lib/chunk-MUEQRIK7.mjs +9 -0
- package/lib/{chunk-IOIWJ3DJ.mjs → chunk-NLB3RGIY.mjs} +1 -1
- package/lib/{chunk-O2HDYYUV.mjs → chunk-NWOI25WY.mjs} +1 -1
- package/lib/chunk-O2PUGRNW.mjs +10 -0
- package/lib/chunk-O4BROUGM.mjs +7 -0
- package/lib/chunk-OETEC3P7.mjs +7 -0
- package/lib/{chunk-GCOB7K5N.mjs → chunk-OHEOJISY.mjs} +1 -1
- package/lib/chunk-P55MKIZX.mjs +37 -0
- package/lib/chunk-P63WJMXQ.mjs +7 -0
- package/lib/chunk-PBE44M2Y.mjs +7 -0
- package/lib/{chunk-TYYOBZMU.mjs → chunk-PC247GKX.mjs} +1 -1
- package/lib/chunk-PE435FVH.mjs +15 -0
- package/lib/chunk-PPGDAUEQ.mjs +7 -0
- package/lib/{chunk-SE4QEZUG.mjs → chunk-PPHVWUFY.mjs} +1 -1
- package/lib/{chunk-CU2INBND.mjs → chunk-PR74GYVI.mjs} +1 -1
- package/lib/chunk-PWVDNN2C.mjs +7 -0
- package/lib/{chunk-6XYKJSGX.mjs → chunk-PYRZFUVU.mjs} +1 -1
- package/lib/{chunk-TLH7AD35.mjs → chunk-PZBZ7MNC.mjs} +1 -1
- package/lib/{chunk-DYFALGRT.mjs → chunk-Q3DY7TO2.mjs} +1 -1
- package/lib/{chunk-BGUEWRK2.mjs → chunk-Q6SXNKV2.mjs} +1 -1
- package/lib/chunk-QAPVKPEC.mjs +7 -0
- package/lib/{chunk-DBFJB2B6.mjs → chunk-QIRO4HTE.mjs} +1 -1
- package/lib/{chunk-TSLJUSLW.mjs → chunk-RCYEBY42.mjs} +1 -1
- package/lib/chunk-RLWB7F26.mjs +7 -0
- package/lib/{chunk-FXXLX4O6.mjs → chunk-RTWYLOCA.mjs} +1 -1
- package/lib/chunk-RYRMUPMY.mjs +7 -0
- package/lib/chunk-SAMWHL22.mjs +13 -0
- package/lib/{chunk-IZQZ6ZUF.mjs → chunk-SFGZFB4F.mjs} +1 -1
- package/lib/{chunk-FKG7Q3WH.mjs → chunk-SNEOKYV7.mjs} +1 -1
- package/lib/{chunk-3TJON4F3.mjs → chunk-STRMWSIQ.mjs} +1 -1
- package/lib/chunk-SZGGFST2.mjs +272 -0
- package/lib/{chunk-SOGQW4IG.mjs → chunk-T7WREYA5.mjs} +1 -1
- package/lib/{chunk-NTFIRZP6.mjs → chunk-TCBAE65A.mjs} +1 -1
- package/lib/{chunk-KYEDBS54.mjs → chunk-TEIBWMJM.mjs} +1 -1
- package/lib/{chunk-YKKRIEH4.mjs → chunk-TMA34QMA.mjs} +1 -1
- package/lib/chunk-TQ2TQHTT.mjs +9 -0
- package/lib/{chunk-HEKAZJRH.mjs → chunk-TWV4A5RK.mjs} +1 -1
- package/lib/{chunk-CEX3NEZL.mjs → chunk-UHFLKP26.mjs} +1 -1
- package/lib/chunk-UV74P4H2.mjs +7 -0
- package/lib/{chunk-WR4Q363I.mjs → chunk-V3R45ZWT.mjs} +1 -1
- package/lib/{chunk-GSKCGQIP.mjs → chunk-VPDEJGPS.mjs} +1 -1
- package/lib/{chunk-HLWMJF6Y.mjs → chunk-VQJMP3DC.mjs} +1 -1
- package/lib/chunk-VV3B6IC3.mjs +7 -0
- package/lib/{chunk-PJ5I73CK.mjs → chunk-VYOYXTCU.mjs} +1 -1
- package/lib/{chunk-NZC67CGR.mjs → chunk-VZT4E2OJ.mjs} +1 -1
- package/lib/{chunk-AEKONPF4.mjs → chunk-VZVICK7Q.mjs} +1 -1
- package/lib/{chunk-WR2GIKWE.mjs → chunk-WB2RIVO3.mjs} +1 -1
- package/lib/chunk-WEMLDUQA.mjs +7 -0
- package/lib/{chunk-MYW5QNGI.mjs → chunk-WOOUISSO.mjs} +1 -1
- package/lib/{chunk-G35N4P7D.mjs → chunk-WSUKC2U3.mjs} +1 -1
- package/lib/{chunk-ZVAED4QV.mjs → chunk-WT3SCUHS.mjs} +1 -1
- package/lib/{chunk-7EANH5PY.mjs → chunk-WZQEK4WT.mjs} +1 -1
- package/lib/{chunk-DBB3EMIN.mjs → chunk-XFU3HRUV.mjs} +1 -1
- package/lib/chunk-XK5W7BVE.mjs +7 -0
- package/lib/{chunk-2GTBABKU.mjs → chunk-XO5FBOQF.mjs} +1 -1
- package/lib/{chunk-CHYDMRSV.mjs → chunk-XSKPYGMT.mjs} +1 -1
- package/lib/chunk-XU25YA46.mjs +9 -0
- package/lib/chunk-XZISAZA6.mjs +7 -0
- package/lib/chunk-Y4TDVDP2.mjs +13 -0
- package/lib/chunk-YAIIRFKJ.mjs +8 -0
- package/lib/{chunk-LKQ5RKIV.mjs → chunk-YAJQS3OL.mjs} +1 -1
- package/lib/{chunk-74Q6DORA.mjs → chunk-YGJF55VJ.mjs} +1 -1
- package/lib/chunk-YH4DYI6D.mjs +7 -0
- package/lib/chunk-YMDFF657.mjs +10 -0
- package/lib/{chunk-2BA2XKAY.mjs → chunk-YT22LMF7.mjs} +1 -1
- package/lib/{chunk-IG2MTQRP.mjs → chunk-Z42PHCVZ.mjs} +1 -1
- package/lib/{chunk-2NBYT7GR.mjs → chunk-ZHIZY3ZC.mjs} +1 -1
- package/lib/chunk-ZQO5PDX5.mjs +48 -0
- package/lib/chunk-ZRUDYB7O.mjs +7 -0
- package/lib/{chunk-BXU6WFMH.mjs → chunk-ZUBBEP75.mjs} +1 -1
- package/lib/chunk-ZUOPC4W2.mjs +7 -0
- package/lib/{chunk-GGD7ON3M.mjs → chunk-ZUTUYBNW.mjs} +1 -1
- package/lib/{chunk-MHMH6MTP.mjs → chunk-ZXFL2MSN.mjs} +1 -1
- package/lib/sandforge-autopilot.mjs +11 -11
- package/lib/sandforge-backup.mjs +63 -32
- package/lib/sandforge-checkpoint.mjs +1 -348
- package/lib/sandforge-cleanup.mjs +1 -1
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +1 -1
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +11 -11
- package/lib/sandforge-env.mjs +186 -140
- package/lib/sandforge-frozen.mjs +1 -266
- package/lib/sandforge-mcp.mjs +33 -14
- package/lib/sandforge-monitor.mjs +1 -1
- package/lib/sandforge-pipeline.mjs +88 -0
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge-users.mjs +157 -0
- package/lib/sandforge.mjs +1 -22
- package/lib/sf/sandforge/autopilot.mjs +20 -0
- package/lib/sf/sandforge/backup.mjs +20 -0
- package/lib/sf/sandforge/checkpoint.mjs +20 -0
- package/lib/sf/sandforge/cleanup.mjs +20 -0
- package/lib/sf/sandforge/clone.mjs +20 -0
- package/lib/sf/sandforge/compare.mjs +20 -0
- package/lib/sf/sandforge/dataops.mjs +20 -0
- package/lib/sf/sandforge/empty.mjs +20 -0
- package/lib/sf/sandforge/env.mjs +20 -0
- package/lib/sf/sandforge/frozen.mjs +20 -0
- package/lib/sf/sandforge/hardis-commands.mjs +20 -0
- package/lib/sf/sandforge/index.mjs +20 -0
- package/lib/sf/sandforge/mcp.mjs +20 -0
- package/lib/sf/sandforge/monitor.mjs +20 -0
- package/lib/sf/sandforge/pipeline.mjs +20 -0
- package/lib/sf/sandforge/seed.mjs +20 -0
- package/lib/sf/sandforge/sync.mjs +20 -0
- package/lib/sf/sandforge/users.mjs +20 -0
- package/lib/sfHelpHook.mjs +7 -0
- package/lib/sfPlugin.mjs +11 -0
- package/oclif.manifest.json +1 -0
- package/package.json +18 -3
- package/lib/chunk-2CNCDM56.mjs +0 -7
- package/lib/chunk-3F6Q5E7I.mjs +0 -14
- package/lib/chunk-4VS2V6WU.mjs +0 -25
- package/lib/chunk-5P4PHJRL.mjs +0 -9
- package/lib/chunk-5TC3QB4U.mjs +0 -10
- package/lib/chunk-7ABODJ4G.mjs +0 -7
- package/lib/chunk-7EGQP6S4.mjs +0 -7
- package/lib/chunk-7FFGJWHN.mjs +0 -7
- package/lib/chunk-7YDNUBO5.mjs +0 -7
- package/lib/chunk-A527W53V.mjs +0 -7
- package/lib/chunk-ADOAS63R.mjs +0 -7
- package/lib/chunk-B5QQJ4SI.mjs +0 -7
- package/lib/chunk-CION3VMZ.mjs +0 -7
- package/lib/chunk-CSBS5U5I.mjs +0 -7
- package/lib/chunk-DB7RBE5D.mjs +0 -7
- package/lib/chunk-E5ZB3LU5.mjs +0 -7
- package/lib/chunk-EFR2Y7E4.mjs +0 -7
- package/lib/chunk-EHQ3FX6X.mjs +0 -7
- package/lib/chunk-EQNW3UC2.mjs +0 -7
- package/lib/chunk-F43REJDZ.mjs +0 -10
- package/lib/chunk-GSG7WZHM.mjs +0 -7
- package/lib/chunk-HOJYWTP7.mjs +0 -20
- package/lib/chunk-HS4YRX4J.mjs +0 -7
- package/lib/chunk-I7O6C2B5.mjs +0 -8
- package/lib/chunk-IFETCRWE.mjs +0 -10
- package/lib/chunk-IQXHJEYB.mjs +0 -7
- package/lib/chunk-JPUR2CFX.mjs +0 -10
- package/lib/chunk-K327QKMD.mjs +0 -7
- package/lib/chunk-KRCA6IPH.mjs +0 -8
- package/lib/chunk-LPBMBW3O.mjs +0 -13
- package/lib/chunk-LWW4U276.mjs +0 -7
- package/lib/chunk-MFG4MUIO.mjs +0 -9
- package/lib/chunk-MJU2PGZQ.mjs +0 -15
- package/lib/chunk-OAZRPP4I.mjs +0 -7
- package/lib/chunk-OO6CLPEH.mjs +0 -7
- package/lib/chunk-OPXCV2KL.mjs +0 -7
- package/lib/chunk-P33PSCXK.mjs +0 -7
- package/lib/chunk-Q3DM32KF.mjs +0 -11
- package/lib/chunk-QR3WELJQ.mjs +0 -7
- package/lib/chunk-QWT2C74M.mjs +0 -7
- package/lib/chunk-R3X3LV64.mjs +0 -14
- package/lib/chunk-RMBPOTD7.mjs +0 -7
- package/lib/chunk-SIHORWVK.mjs +0 -7
- package/lib/chunk-T62WNR54.mjs +0 -7
- package/lib/chunk-TTFDUKUS.mjs +0 -47
- package/lib/chunk-VE6XKGGD.mjs +0 -7
- package/lib/chunk-VGW4MXXZ.mjs +0 -7
- package/lib/chunk-VS7ZXUII.mjs +0 -824
- package/lib/chunk-VXQLDM4R.mjs +0 -7
- package/lib/chunk-VYXMVJL5.mjs +0 -7
- package/lib/chunk-W7U5E5ZL.mjs +0 -9
- package/lib/chunk-WXAQ7FK3.mjs +0 -115
- package/lib/chunk-YS4G22C2.mjs +0 -7
- package/lib/chunk-ZM6OJGIG.mjs +0 -7
- package/lib/chunk-ZUTYVST5.mjs +0 -7
package/lib/sandforge-env.mjs
CHANGED
|
@@ -4,152 +4,155 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a as
|
|
8
|
-
`)}};
|
|
9
|
-
`)?
|
|
7
|
+
import{a as Gd,c as Qe,d as Qd,e as Xd,f as Zd,g as jr}from"./chunk-FKK5YBGZ.mjs";import{a as iu}from"./chunk-6GQUZ4IP.mjs";import{f as Ho}from"./chunk-YH4DYI6D.mjs";import"./chunk-SZGGFST2.mjs";import"./chunk-LAUOSXMN.mjs";import"./chunk-INIQ23K6.mjs";import"./chunk-2UU42PTD.mjs";import"./chunk-GCGHHN4K.mjs";import{a as Rd}from"./chunk-2JZGCCPG.mjs";import{i as lu,w as Pr}from"./chunk-IRZJU2PG.mjs";import{f as mn,g as Dr}from"./chunk-Y4TDVDP2.mjs";import{c as du,d as uu}from"./chunk-JJITOWZK.mjs";import"./chunk-YMDFF657.mjs";import{a as Cr,d as Ke}from"./chunk-UV74P4H2.mjs";import{i as au,k as cu}from"./chunk-5K2I2DMP.mjs";import"./chunk-7WSLT5VX.mjs";import"./chunk-YT22LMF7.mjs";import{f as su}from"./chunk-FQGHL7GR.mjs";import"./chunk-A7JJWOLT.mjs";import"./chunk-ZXFL2MSN.mjs";import"./chunk-VYOYXTCU.mjs";import"./chunk-C3LNYAVJ.mjs";import"./chunk-GJ6SZVHT.mjs";import"./chunk-52EXDVPN.mjs";import"./chunk-GMY5427L.mjs";import{b as fu,e as Jo,f as Yo}from"./chunk-FOIWWK7G.mjs";import"./chunk-TW3N6W5Z.mjs";import"./chunk-5GBO4KD5.mjs";import{Gb as nu,Hb as ru,eb as Ir,hb as tu}from"./chunk-3HEMJTAP.mjs";import"./chunk-BN33LVPQ.mjs";import{b as Ue,c as Yd}from"./chunk-JKT5YAQ2.mjs";import"./chunk-QAPVKPEC.mjs";import{b as bt,c as Kd}from"./chunk-BNKT3R3F.mjs";import{b as Vd}from"./chunk-QROPNEGY.mjs";import{a as Sd,b as xe,e as Ge}from"./chunk-BZ24IAP5.mjs";import{a as B,b as Ne}from"./chunk-SCKUIE3R.mjs";import{i as $d}from"./chunk-6FARZYMJ.mjs";import"./chunk-EEFUE2ES.mjs";import{a as Wo}from"./chunk-PE435FVH.mjs";import"./chunk-PWVDNN2C.mjs";import"./chunk-6VSZNZHH.mjs";import"./chunk-XCA5AONB.mjs";import"./chunk-66NMFCWX.mjs";import"./chunk-WB2RIVO3.mjs";import{b as ou}from"./chunk-MUEQRIK7.mjs";import{Wa as jd,_ as Ad,za as Od}from"./chunk-ISSP2FZ5.mjs";import"./chunk-XU25YA46.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-IVZJSDJD.mjs";import"./chunk-VZT4E2OJ.mjs";import"./chunk-BOGNK4LV.mjs";import{ha as Or,m as Wd,oa as Hd,ta as Jd}from"./chunk-P55MKIZX.mjs";import"./chunk-PYRZFUVU.mjs";import"./chunk-O2PUGRNW.mjs";import{N as Id}from"./chunk-7SDZR6SR.mjs";import"./chunk-TEIBWMJM.mjs";import"./chunk-BWWQXU2B.mjs";import"./chunk-T63U4OZJ.mjs";import"./chunk-YAIIRFKJ.mjs";import"./chunk-Q3DY7TO2.mjs";import"./chunk-3XG25GTF.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-54HYHHVL.mjs";import"./chunk-M6P5ZZLE.mjs";import"./chunk-WSUKC2U3.mjs";import"./chunk-QIRO4HTE.mjs";import{h as Cd,l as Dd,n as Pd,p as Vo}from"./chunk-3SKLBRPL.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-JH27IKCO.mjs";import"./chunk-SAMWHL22.mjs";import"./chunk-6KP6WETK.mjs";import"./chunk-4JKR4PTZ.mjs";import{I as Ld,L as Fd,M as Md,k as re}from"./chunk-J24TIGSI.mjs";import"./chunk-HKUWHVI7.mjs";import"./chunk-VPDEJGPS.mjs";import"./chunk-5LFSFYFJ.mjs";import{a as Ko,b as bd,c as Ed}from"./chunk-LHU6CPGE.mjs";import"./chunk-PBE44M2Y.mjs";import{a as Sr,b as $r,d as vd}from"./chunk-ZUOPC4W2.mjs";import{c as xd}from"./chunk-JQZTMFO7.mjs";import{$a as Bd,F as zd,K as _d,Pb as Ud,Ra as Ar,_a as qd,mc as kt}from"./chunk-JFNLKHY6.mjs";import"./chunk-VZVICK7Q.mjs";import"./chunk-PPGDAUEQ.mjs";import{a as Nd,b as Td}from"./chunk-VV3B6IC3.mjs";import"./chunk-4TLYUZD5.mjs";import"./chunk-7PY3VQP3.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-SU65Z2BA.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-HFUDCNU5.mjs";import"./chunk-MS4FJDFD.mjs";import"./chunk-XZISAZA6.mjs";import{b as kd,f as Be,g as hn,h as eu}from"./chunk-LCDPCUXS.mjs";import"./chunk-TQ2TQHTT.mjs";import"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-PC247GKX.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-L4INJ5TZ.mjs";import"./chunk-KIMQQ6JQ.mjs";import"./chunk-TZE3Y7IQ.mjs";import{b as wd}from"./chunk-CA5NAXSU.mjs";import"./chunk-ZUTUYBNW.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-ICIYL45C.mjs";import"./chunk-PR74GYVI.mjs";import"./chunk-TMA34QMA.mjs";import"./chunk-TUACWKIH.mjs";import{Ab as md,Bb as pn,Cb as gd,Da as _o,Db as Bo,Qb as Uo,Ra as wt,Ua as id,cb as ad,e as kr,eb as cd,hd as yd,j as sd,mb as dd,ob as ud,pb as br,rb as vt,sb as Er,tb as fn,ub as qo,vb as ld,wb as fd,x as od,xb as pd,yb as Rr,zb as hd}from"./chunk-ZQO5PDX5.mjs";import{A as p,b as Te,f as Xc,i as Zc,k as vr,l as ed,m as zo,s as td,v as nd,z as rd}from"./chunk-WZQEK4WT.mjs";import{a as wr,b as I,d as ww}from"./chunk-NTOVCTRS.mjs";var _=I(ae=>{"use strict";var Di=Symbol.for("yaml.alias"),Mp=Symbol.for("yaml.document"),fs=Symbol.for("yaml.map"),zp=Symbol.for("yaml.pair"),Pi=Symbol.for("yaml.scalar"),ps=Symbol.for("yaml.seq"),Ve=Symbol.for("yaml.node.type"),Ek=e=>!!e&&typeof e=="object"&&e[Ve]===Di,Rk=e=>!!e&&typeof e=="object"&&e[Ve]===Mp,Sk=e=>!!e&&typeof e=="object"&&e[Ve]===fs,$k=e=>!!e&&typeof e=="object"&&e[Ve]===zp,_p=e=>!!e&&typeof e=="object"&&e[Ve]===Pi,Ak=e=>!!e&&typeof e=="object"&&e[Ve]===ps;function qp(e){if(e&&typeof e=="object")switch(e[Ve]){case fs:case ps:return!0}return!1}function Ok(e){if(e&&typeof e=="object")switch(e[Ve]){case Di:case fs:case Pi:case ps:return!0}return!1}var jk=e=>(_p(e)||qp(e))&&!!e.anchor;ae.ALIAS=Di;ae.DOC=Mp;ae.MAP=fs;ae.NODE_TYPE=Ve;ae.PAIR=zp;ae.SCALAR=Pi;ae.SEQ=ps;ae.hasAnchor=jk;ae.isAlias=Ek;ae.isCollection=qp;ae.isDocument=Rk;ae.isMap=Sk;ae.isNode=Ok;ae.isPair=$k;ae.isScalar=_p;ae.isSeq=Ak});var Nn=I(Ni=>{"use strict";var ee=_(),ge=Symbol("break visit"),Bp=Symbol("skip children"),ze=Symbol("remove node");function hs(e,t){let n=Up(t);ee.isDocument(e)?Gt(null,e.contents,n,Object.freeze([e]))===ze&&(e.contents=null):Gt(null,e,n,Object.freeze([]))}hs.BREAK=ge;hs.SKIP=Bp;hs.REMOVE=ze;function Gt(e,t,n,r){let s=Kp(e,t,n,r);if(ee.isNode(s)||ee.isPair(s))return Wp(e,r,s),Gt(e,s,n,r);if(typeof s!="symbol"){if(ee.isCollection(t)){r=Object.freeze(r.concat(t));for(let o=0;o<t.items.length;++o){let i=Gt(o,t.items[o],n,r);if(typeof i=="number")o=i-1;else{if(i===ge)return ge;i===ze&&(t.items.splice(o,1),o-=1)}}}else if(ee.isPair(t)){r=Object.freeze(r.concat(t));let o=Gt("key",t.key,n,r);if(o===ge)return ge;o===ze&&(t.key=null);let i=Gt("value",t.value,n,r);if(i===ge)return ge;i===ze&&(t.value=null)}}return s}async function ms(e,t){let n=Up(t);ee.isDocument(e)?await Qt(null,e.contents,n,Object.freeze([e]))===ze&&(e.contents=null):await Qt(null,e,n,Object.freeze([]))}ms.BREAK=ge;ms.SKIP=Bp;ms.REMOVE=ze;async function Qt(e,t,n,r){let s=await Kp(e,t,n,r);if(ee.isNode(s)||ee.isPair(s))return Wp(e,r,s),Qt(e,s,n,r);if(typeof s!="symbol"){if(ee.isCollection(t)){r=Object.freeze(r.concat(t));for(let o=0;o<t.items.length;++o){let i=await Qt(o,t.items[o],n,r);if(typeof i=="number")o=i-1;else{if(i===ge)return ge;i===ze&&(t.items.splice(o,1),o-=1)}}}else if(ee.isPair(t)){r=Object.freeze(r.concat(t));let o=await Qt("key",t.key,n,r);if(o===ge)return ge;o===ze&&(t.key=null);let i=await Qt("value",t.value,n,r);if(i===ge)return ge;i===ze&&(t.value=null)}}return s}function Up(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Kp(e,t,n,r){if(typeof n=="function")return n(e,t,r);if(ee.isMap(t))return n.Map?.(e,t,r);if(ee.isSeq(t))return n.Seq?.(e,t,r);if(ee.isPair(t))return n.Pair?.(e,t,r);if(ee.isScalar(t))return n.Scalar?.(e,t,r);if(ee.isAlias(t))return n.Alias?.(e,t,r)}function Wp(e,t,n){let r=t[t.length-1];if(ee.isCollection(r))r.items[e]=n;else if(ee.isPair(r))e==="key"?r.key=n:r.value=n;else if(ee.isDocument(r))r.contents=n;else{let s=ee.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}Ni.visit=hs;Ni.visitAsync=ms});var Ti=I(Hp=>{"use strict";var Vp=_(),Ik=Nn(),Ck={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Dk=e=>e.replace(/[!,[\]{}]/g,t=>Ck[t]),Tn=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&(this.yaml={explicit:e.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},e.defaultTags),this.atNextDocument=!1);let r=t.trim().split(/[ \t]+/),s=r.shift();switch(s){case"%TAG":{if(r.length!==2&&(n(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[o,i]=r;return this.tags[o]=i,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return n(0,"%YAML directive should contain exactly one part"),!1;let[o]=r;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let i=/^\d+\.\d+$/.test(o);return n(6,`Unsupported YAML version ${o}`,i),!1}}default:return n(0,`Unknown directive ${s}`,!0),!1}}tagName(t,n){if(t==="!")return"!";if(t[0]!=="!")return n(`Not a valid tag: ${t}`),null;if(t[1]==="<"){let i=t.slice(2,-1);return i==="!"||i==="!!"?(n(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&n("Verbatim tags must end with a >"),i)}let[,r,s]=t.match(/^(.*!)([^!]*)$/s);s||n(`The ${t} tag has no suffix`);let o=this.tags[r];if(o)try{return o+decodeURIComponent(s)}catch(i){return n(String(i)),null}return r==="!"?t:(n(`Could not resolve tag: ${t}`),null)}tagString(t){for(let[n,r]of Object.entries(this.tags))if(t.startsWith(r))return n+Dk(t.substring(r.length));return t[0]==="!"?t:`!<${t}>`}toString(t){let n=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),s;if(t&&r.length>0&&Vp.isNode(t.contents)){let o={};Ik.visit(t.contents,(i,a)=>{Vp.isNode(a)&&a.tag&&(o[a.tag]=!0)}),s=Object.keys(o)}else s=[];for(let[o,i]of r)o==="!!"&&i==="tag:yaml.org,2002:"||(!t||s.some(a=>a.startsWith(i)))&&n.push(`%TAG ${o} ${i}`);return n.join(`
|
|
8
|
+
`)}};Tn.defaultYaml={explicit:!1,version:"1.2"};Tn.defaultTags={"!!":"tag:yaml.org,2002:"};Hp.Directives=Tn});var gs=I(xn=>{"use strict";var Jp=_(),Pk=Nn();function Nk(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let n=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(n)}return!0}function Yp(e){let t=new Set;return Pk.visit(e,{Value(n,r){r.anchor&&t.add(r.anchor)}}),t}function Gp(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function Tk(e,t){let n=[],r=new Map,s=null;return{onAnchor:o=>{n.push(o),s??(s=Yp(e));let i=Gp(t,s);return s.add(i),i},setAnchors:()=>{for(let o of n){let i=r.get(o);if(typeof i=="object"&&i.anchor&&(Jp.isScalar(i.node)||Jp.isCollection(i.node)))i.node.anchor=i.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=o,a}}},sourceObjects:r}}xn.anchorIsValid=Nk;xn.anchorNames=Yp;xn.createNodeAnchors=Tk;xn.findNewAnchor=Gp});var xi=I(Qp=>{"use strict";function Ln(e,t,n,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let s=0,o=r.length;s<o;++s){let i=r[s],a=Ln(e,r,String(s),i);a===void 0?delete r[s]:a!==i&&(r[s]=a)}else if(r instanceof Map)for(let s of Array.from(r.keys())){let o=r.get(s),i=Ln(e,r,s,o);i===void 0?r.delete(s):i!==o&&r.set(s,i)}else if(r instanceof Set)for(let s of Array.from(r)){let o=Ln(e,r,s,s);o===void 0?r.delete(s):o!==s&&(r.delete(s),r.add(o))}else for(let[s,o]of Object.entries(r)){let i=Ln(e,r,s,o);i===void 0?delete r[s]:i!==o&&(r[s]=i)}return e.call(t,n,r)}Qp.applyReviver=Ln});var ot=I(Zp=>{"use strict";var xk=_();function Xp(e,t,n){if(Array.isArray(e))return e.map((r,s)=>Xp(r,String(s),n));if(e&&typeof e.toJSON=="function"){if(!n||!xk.hasAnchor(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=o=>{r.res=o,delete n.onCreate};let s=e.toJSON(t,n);return n.onCreate&&n.onCreate(s),s}return typeof e=="bigint"&&!n?.keep?Number(e):e}Zp.toJS=Xp});var ys=I(th=>{"use strict";var Lk=xi(),eh=_(),Fk=ot(),Li=class{constructor(t){Object.defineProperty(this,eh.NODE_TYPE,{value:t})}clone(){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(t.range=this.range.slice()),t}toJS(t,{mapAsMap:n,maxAliasCount:r,onAnchor:s,reviver:o}={}){if(!eh.isDocument(t))throw new TypeError("A document argument is required");let i={anchors:new Map,doc:t,keep:!0,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=Fk.toJS(this,"",i);if(typeof s=="function")for(let{count:c,res:d}of i.anchors.values())s(d,c);return typeof o=="function"?Lk.applyReviver(o,{"":a},"",a):a}};th.NodeBase=Li});var Fn=I(nh=>{"use strict";var Mk=gs(),zk=Nn(),Xt=_(),_k=ys(),qk=ot(),Fi=class extends _k.NodeBase{constructor(t){super(Xt.ALIAS),this.source=t,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(t,n){if(n?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;n?.aliasResolveCache?r=n.aliasResolveCache:(r=[],zk.visit(t,{Node:(o,i)=>{(Xt.isAlias(i)||Xt.hasAnchor(i))&&r.push(i)}}),n&&(n.aliasResolveCache=r));let s;for(let o of r){if(o===this)break;o.anchor===this.source&&(s=o)}if(s&&n){let{anchors:o,doc:i,maxAliasCount:a}=n,c=o.get(s);if(c||(qk.toJS(s,null,n),c=o.get(s)),c?.res===void 0){let d="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(d)}if(a>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=ws(i,s,o)),c.count*c.aliasCount>a)){let d="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(d)}}return s}toJSON(t,n){if(!n)return{source:this.source};let r=this.resolve(n.doc,n);if(!r){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(s)}return n.anchors.get(r).res}toString(t,n,r){let s=`*${this.source}`;if(t){if(Mk.anchorIsValid(this.source),t.options.verifyAliasOrder&&!t.anchors.has(this.source)){let o=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(o)}if(t.implicitKey)return`${s} `}return s}};function ws(e,t,n){if(Xt.isAlias(t)){let r=t.resolve(e),s=n&&r&&n.get(r);return s?s.count*s.aliasCount:0}else if(Xt.isCollection(t)){let r=0;for(let s of t.items){let o=ws(e,s,n);o>r&&(r=o)}return r}else if(Xt.isPair(t)){let r=ws(e,t.key,n),s=ws(e,t.value,n);return Math.max(r,s)}return 1}nh.Alias=Fi});var X=I(Mi=>{"use strict";var Bk=_(),Uk=ys(),Kk=ot(),Wk=e=>!e||typeof e!="function"&&typeof e!="object",it=class extends Uk.NodeBase{constructor(t){super(Bk.SCALAR),this.value=t}toJSON(t,n){return n?.keep?this.value:Kk.toJS(this.value,t,n)}toString(){return String(this.value)}};it.BLOCK_FOLDED="BLOCK_FOLDED";it.BLOCK_LITERAL="BLOCK_LITERAL";it.PLAIN="PLAIN";it.QUOTE_DOUBLE="QUOTE_DOUBLE";it.QUOTE_SINGLE="QUOTE_SINGLE";Mi.Scalar=it;Mi.isScalarValue=Wk});var Mn=I(sh=>{"use strict";var Vk=Fn(),Ot=_(),rh=X(),Hk="tag:yaml.org,2002:";function Jk(e,t,n){if(t){let r=n.filter(o=>o.tag===t),s=r.find(o=>!o.format)??r[0];if(!s)throw new Error(`Tag ${t} not found`);return s}return n.find(r=>r.identify?.(e)&&!r.format)}function Yk(e,t,n){if(Ot.isDocument(e)&&(e=e.contents),Ot.isNode(e))return e;if(Ot.isPair(e)){let l=n.schema[Ot.MAP].createNode?.(n.schema,null,n);return l.items.push(e),l}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:s,onTagObj:o,schema:i,sourceObjects:a}=n,c;if(r&&e&&typeof e=="object"){if(c=a.get(e),c)return c.anchor??(c.anchor=s(e)),new Vk.Alias(c.anchor);c={anchor:null,node:null},a.set(e,c)}t?.startsWith("!!")&&(t=Hk+t.slice(2));let d=Jk(e,t,i.tags);if(!d){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){let l=new rh.Scalar(e);return c&&(c.node=l),l}d=e instanceof Map?i[Ot.MAP]:Symbol.iterator in Object(e)?i[Ot.SEQ]:i[Ot.MAP]}o&&(o(d),delete n.onTagObj);let u=d?.createNode?d.createNode(n.schema,e,n):typeof d?.nodeClass?.from=="function"?d.nodeClass.from(n.schema,e,n):new rh.Scalar(e);return t?u.tag=t:d.default||(u.tag=d.tag),c&&(c.node=u),u}sh.createNode=Yk});var ks=I(vs=>{"use strict";var Gk=Mn(),_e=_(),Qk=ys();function zi(e,t,n){let r=n;for(let s=t.length-1;s>=0;--s){let o=t[s];if(typeof o=="number"&&Number.isInteger(o)&&o>=0){let i=[];i[o]=r,r=i}else r=new Map([[o,r]])}return Gk.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var oh=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,_i=class extends Qk.NodeBase{constructor(t,n){super(t),Object.defineProperty(this,"schema",{value:n,configurable:!0,enumerable:!1,writable:!0})}clone(t){let n=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return t&&(n.schema=t),n.items=n.items.map(r=>_e.isNode(r)||_e.isPair(r)?r.clone(t):r),this.range&&(n.range=this.range.slice()),n}addIn(t,n){if(oh(t))this.add(n);else{let[r,...s]=t,o=this.get(r,!0);if(_e.isCollection(o))o.addIn(s,n);else if(o===void 0&&this.schema)this.set(r,zi(this.schema,s,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${s}`)}}deleteIn(t){let[n,...r]=t;if(r.length===0)return this.delete(n);let s=this.get(n,!0);if(_e.isCollection(s))return s.deleteIn(r);throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}getIn(t,n){let[r,...s]=t,o=this.get(r,!0);return s.length===0?!n&&_e.isScalar(o)?o.value:o:_e.isCollection(o)?o.getIn(s,n):void 0}hasAllNullValues(t){return this.items.every(n=>{if(!_e.isPair(n))return!1;let r=n.value;return r==null||t&&_e.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(t){let[n,...r]=t;if(r.length===0)return this.has(n);let s=this.get(n,!0);return _e.isCollection(s)?s.hasIn(r):!1}setIn(t,n){let[r,...s]=t;if(s.length===0)this.set(r,n);else{let o=this.get(r,!0);if(_e.isCollection(o))o.setIn(s,n);else if(o===void 0&&this.schema)this.set(r,zi(this.schema,s,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${s}`)}}};vs.Collection=_i;vs.collectionFromPath=zi;vs.isEmptyPath=oh});var zn=I(bs=>{"use strict";var Xk=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function qi(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Zk=(e,t,n)=>e.endsWith(`
|
|
9
|
+
`)?qi(n,t):n.includes(`
|
|
10
10
|
`)?`
|
|
11
|
-
`+
|
|
12
|
-
`)n===
|
|
13
|
-
`&&
|
|
14
|
-
`&&
|
|
15
|
-
${t}${e.slice(0,
|
|
16
|
-
${t}${e.slice(
|
|
17
|
-
`);r=t,s=t+1,
|
|
18
|
-
`){if(i
|
|
11
|
+
`+qi(n,t):(e.endsWith(" ")?"":" ")+n;bs.indentComment=qi;bs.lineComment=Zk;bs.stringifyComment=Xk});var ah=I(_n=>{"use strict";var eb="flow",Bi="block",Es="quoted";function tb(e,t,n="flow",{indentAtStart:r,lineWidth:s=80,minContentWidth:o=20,onFold:i,onOverflow:a}={}){if(!s||s<0)return e;s<o&&(o=0);let c=Math.max(1+o,1+s-t.length);if(e.length<=c)return e;let d=[],u={},l=s-t.length;typeof r=="number"&&(r>s-Math.max(2,o)?d.push(0):l=s-r);let f,h,g=!1,m=-1,w=-1,y=-1;n===Bi&&(m=ih(e,m,t.length),m!==-1&&(l=m+c));for(let b;b=e[m+=1];){if(n===Es&&b==="\\"){switch(w=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}y=m}if(b===`
|
|
12
|
+
`)n===Bi&&(m=ih(e,m,t.length)),l=m+t.length+c,f=void 0;else{if(b===" "&&h&&h!==" "&&h!==`
|
|
13
|
+
`&&h!==" "){let k=e[m+1];k&&k!==" "&&k!==`
|
|
14
|
+
`&&k!==" "&&(f=m)}if(m>=l)if(f)d.push(f),l=f+c,f=void 0;else if(n===Es){for(;h===" "||h===" ";)h=b,b=e[m+=1],g=!0;let k=m>y+1?m-2:w-1;if(u[k])return e;d.push(k),u[k]=!0,l=k+c,f=void 0}else g=!0}h=b}if(g&&a&&a(),d.length===0)return e;i&&i();let v=e.slice(0,d[0]);for(let b=0;b<d.length;++b){let k=d[b],E=d[b+1]||e.length;k===0?v=`
|
|
15
|
+
${t}${e.slice(0,E)}`:(n===Es&&u[k]&&(v+=`${e[k]}\\`),v+=`
|
|
16
|
+
${t}${e.slice(k+1,E)}`)}return v}function ih(e,t,n){let r=t,s=t+1,o=e[s];for(;o===" "||o===" ";)if(t<s+n)o=e[++t];else{do o=e[++t];while(o&&o!==`
|
|
17
|
+
`);r=t,s=t+1,o=e[s]}return r}_n.FOLD_BLOCK=Bi;_n.FOLD_FLOW=eb;_n.FOLD_QUOTED=Es;_n.foldFlowLines=tb});var Bn=I(ch=>{"use strict";var Ae=X(),at=ah(),Ss=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),$s=e=>/^(%|---|\.\.\.)/m.test(e);function nb(e,t,n){if(!t||t<0)return!1;let r=t-n,s=e.length;if(s<=r)return!1;for(let o=0,i=0;o<s;++o)if(e[o]===`
|
|
18
|
+
`){if(o-i>r)return!0;if(i=o+1,s-i<=r)return!1}return!0}function qn(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,s=t.options.doubleQuotedMinMultiLineLength,o=t.indent||($s(e)?" ":""),i="",a=0;for(let c=0,d=n[c];d;d=n[++c])if(d===" "&&n[c+1]==="\\"&&n[c+2]==="n"&&(i+=n.slice(a,c)+"\\ ",c+=1,a=c,d="\\"),d==="\\")switch(n[c+1]){case"u":{i+=n.slice(a,c);let u=n.substr(c+2,4);switch(u){case"0000":i+="\\0";break;case"0007":i+="\\a";break;case"000b":i+="\\v";break;case"001b":i+="\\e";break;case"0085":i+="\\N";break;case"00a0":i+="\\_";break;case"2028":i+="\\L";break;case"2029":i+="\\P";break;default:u.substr(0,2)==="00"?i+="\\x"+u.substr(2):i+=n.substr(c,6)}c+=5,a=c+1}break;case"n":if(r||n[c+2]==='"'||n.length<s)c+=1;else{for(i+=n.slice(a,c)+`
|
|
19
19
|
|
|
20
|
-
`;n[c+2]==="\\"&&n[c+3]==="n"&&n[c+4]!=='"';)
|
|
21
|
-
`,c+=2;o
|
|
22
|
-
`)||/[ \t]\n|\n[ \t]/.test(e))return
|
|
23
|
-
${n}`)+"'";return t.implicitKey?r:
|
|
20
|
+
`;n[c+2]==="\\"&&n[c+3]==="n"&&n[c+4]!=='"';)i+=`
|
|
21
|
+
`,c+=2;i+=o,n[c+2]===" "&&(i+="\\"),c+=1,a=c+1}break;default:c+=1}return i=a?i+n.slice(a):n,r?i:at.foldFlowLines(i,o,at.FOLD_QUOTED,Ss(t,!1))}function Ui(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
22
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return qn(e,t);let n=t.indent||($s(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
23
|
+
${n}`)+"'";return t.implicitKey?r:at.foldFlowLines(r,n,at.FOLD_FLOW,Ss(t,!1))}function Zt(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=qn;else{let s=e.includes('"'),o=e.includes("'");s&&!o?r=Ui:o&&!s?r=qn:r=n?Ui:qn}return r(e,t)}var Ki;try{Ki=new RegExp(`(^|(?<!
|
|
24
24
|
))
|
|
25
25
|
+(?!
|
|
26
|
-
|$)`,"g")}catch{
|
|
26
|
+
|$)`,"g")}catch{Ki=/\n+(?!\n|$)/g}function Rs({comment:e,type:t,value:n},r,s,o){let{blockQuote:i,commentString:a,lineWidth:c}=r.options;if(!i||/\n[\t ]+$/.test(n))return Zt(n,r);let d=r.indent||(r.forceBlockIndent||$s(n)?" ":""),u=i==="literal"?!0:i==="folded"||t===Ae.Scalar.BLOCK_FOLDED?!1:t===Ae.Scalar.BLOCK_LITERAL?!0:!nb(n,c,d.length);if(!n)return u?`|
|
|
27
27
|
`:`>
|
|
28
|
-
`;let
|
|
29
|
-
`&&
|
|
30
|
-
`);
|
|
31
|
-
`&&(
|
|
32
|
-
`)w
|
|
33
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${
|
|
34
|
-
${
|
|
35
|
-
${
|
|
36
|
-
`)||u&&/[[\]{},]/.test(
|
|
37
|
-
`)?
|
|
38
|
-
`))return
|
|
39
|
-
${c}`);if(
|
|
40
|
-
${t.indent}${a}`:a}
|
|
41
|
-
${a}:`):(
|
|
42
|
-
`:"",v){let
|
|
43
|
-
${
|
|
44
|
-
`&&
|
|
28
|
+
`;let l,f;for(f=n.length;f>0;--f){let E=n[f-1];if(E!==`
|
|
29
|
+
`&&E!==" "&&E!==" ")break}let h=n.substring(f),g=h.indexOf(`
|
|
30
|
+
`);g===-1?l="-":n===h||g!==h.length-1?(l="+",o&&o()):l="",h&&(n=n.slice(0,-h.length),h[h.length-1]===`
|
|
31
|
+
`&&(h=h.slice(0,-1)),h=h.replace(Ki,`$&${d}`));let m=!1,w,y=-1;for(w=0;w<n.length;++w){let E=n[w];if(E===" ")m=!0;else if(E===`
|
|
32
|
+
`)y=w;else break}let v=n.substring(0,y<w?y+1:w);v&&(n=n.substring(v.length),v=v.replace(/\n+/g,`$&${d}`));let k=(m?d?"2":"1":"")+l;if(e&&(k+=" "+a(e.replace(/ ?[\r\n]+/g," ")),s&&s()),!u){let E=n.replace(/\n+/g,`
|
|
33
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${d}`),S=!1,$=Ss(r,!0);i!=="folded"&&t!==Ae.Scalar.BLOCK_FOLDED&&($.onOverflow=()=>{S=!0});let j=at.foldFlowLines(`${v}${E}${h}`,d,at.FOLD_BLOCK,$);if(!S)return`>${k}
|
|
34
|
+
${d}${j}`}return n=n.replace(/\n+/g,`$&${d}`),`|${k}
|
|
35
|
+
${d}${v}${n}${h}`}function rb(e,t,n,r){let{type:s,value:o}=e,{actualString:i,implicitKey:a,indent:c,indentStep:d,inFlow:u}=t;if(a&&o.includes(`
|
|
36
|
+
`)||u&&/[[\]{},]/.test(o))return Zt(o,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(o))return a||u||!o.includes(`
|
|
37
|
+
`)?Zt(o,t):Rs(e,t,n,r);if(!a&&!u&&s!==Ae.Scalar.PLAIN&&o.includes(`
|
|
38
|
+
`))return Rs(e,t,n,r);if($s(o)){if(c==="")return t.forceBlockIndent=!0,Rs(e,t,n,r);if(a&&c===d)return Zt(o,t)}let l=o.replace(/\n+/g,`$&
|
|
39
|
+
${c}`);if(i){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(l),{compat:h,tags:g}=t.doc.schema;if(g.some(f)||h?.some(f))return Zt(o,t)}return a?l:at.foldFlowLines(l,c,at.FOLD_FLOW,Ss(t,!1))}function sb(e,t,n,r){let{implicitKey:s,inFlow:o}=t,i=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)}),{type:a}=e;a!==Ae.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(i.value)&&(a=Ae.Scalar.QUOTE_DOUBLE);let c=u=>{switch(u){case Ae.Scalar.BLOCK_FOLDED:case Ae.Scalar.BLOCK_LITERAL:return s||o?Zt(i.value,t):Rs(i,t,n,r);case Ae.Scalar.QUOTE_DOUBLE:return qn(i.value,t);case Ae.Scalar.QUOTE_SINGLE:return Ui(i.value,t);case Ae.Scalar.PLAIN:return rb(i,t,n,r);default:return null}},d=c(a);if(d===null){let{defaultKeyType:u,defaultStringType:l}=t.options,f=s&&u||l;if(d=c(f),d===null)throw new Error(`Unsupported default string type ${f}`)}return d}ch.stringifyString=sb});var Un=I(Wi=>{"use strict";var ob=gs(),ct=_(),ib=zn(),ab=Bn();function cb(e,t){let n=Object.assign({blockQuote:!0,commentString:ib.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?" ":"",indent:"",indentStep:typeof n.indent=="number"?" ".repeat(n.indent):" ",inFlow:r,options:n}}function db(e,t){if(t.tag){let s=e.filter(o=>o.tag===t.tag);if(s.length>0)return s.find(o=>o.format===t.format)??s[0]}let n,r;if(ct.isScalar(t)){r=t.value;let s=e.filter(o=>o.identify?.(r));if(s.length>1){let o=s.filter(i=>i.test);o.length>0&&(s=o)}n=s.find(o=>o.format===t.format)??s.find(o=>!o.format)}else r=t,n=e.find(s=>s.nodeClass&&r instanceof s.nodeClass);if(!n){let s=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${s} value`)}return n}function ub(e,t,{anchors:n,doc:r}){if(!r.directives)return"";let s=[],o=(ct.isScalar(e)||ct.isCollection(e))&&e.anchor;o&&ob.anchorIsValid(o)&&(n.add(o),s.push(`&${o}`));let i=e.tag??(t.default?null:t.tag);return i&&s.push(r.directives.tagString(i)),s.join(" ")}function lb(e,t,n,r){if(ct.isPair(e))return e.toString(t,n,r);if(ct.isAlias(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let s,o=ct.isNode(e)?e:t.doc.createNode(e,{onTagObj:c=>s=c});s??(s=db(t.doc.schema.tags,o));let i=ub(o,s,t);i.length>0&&(t.indentAtStart=(t.indentAtStart??0)+i.length+1);let a=typeof s.stringify=="function"?s.stringify(o,t,n,r):ct.isScalar(o)?ab.stringifyString(o,t,n,r):o.toString(t,n,r);return i?ct.isScalar(o)||a[0]==="{"||a[0]==="["?`${i} ${a}`:`${i}
|
|
40
|
+
${t.indent}${a}`:a}Wi.createStringifyContext=cb;Wi.stringify=lb});var fh=I(lh=>{"use strict";var He=_(),dh=X(),uh=Un(),Kn=zn();function fb({key:e,value:t},n,r,s){let{allNullValues:o,doc:i,indent:a,indentStep:c,options:{commentString:d,indentSeq:u,simpleKeys:l}}=n,f=He.isNode(e)&&e.comment||null;if(l){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(He.isCollection(e)||!He.isNode(e)&&typeof e=="object"){let $="With simple keys, collection cannot be used as a key value";throw new Error($)}}let h=!l&&(!e||f&&t==null&&!n.inFlow||He.isCollection(e)||(He.isScalar(e)?e.type===dh.Scalar.BLOCK_FOLDED||e.type===dh.Scalar.BLOCK_LITERAL:typeof e=="object"));n=Object.assign({},n,{allNullValues:!1,implicitKey:!h&&(l||!o),indent:a+c});let g=!1,m=!1,w=uh.stringify(e,n,()=>g=!0,()=>m=!0);if(!h&&!n.inFlow&&w.length>1024){if(l)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");h=!0}if(n.inFlow){if(o||t==null)return g&&r&&r(),w===""?"?":h?`? ${w}`:w}else if(o&&!l||t==null&&h)return w=`? ${w}`,f&&!g?w+=Kn.lineComment(w,n.indent,d(f)):m&&s&&s(),w;g&&(f=null),h?(f&&(w+=Kn.lineComment(w,n.indent,d(f))),w=`? ${w}
|
|
41
|
+
${a}:`):(w=`${w}:`,f&&(w+=Kn.lineComment(w,n.indent,d(f))));let y,v,b;He.isNode(t)?(y=!!t.spaceBefore,v=t.commentBefore,b=t.comment):(y=!1,v=null,b=null,t&&typeof t=="object"&&(t=i.createNode(t))),n.implicitKey=!1,!h&&!f&&He.isScalar(t)&&(n.indentAtStart=w.length+1),m=!1,!u&&c.length>=2&&!n.inFlow&&!h&&He.isSeq(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let k=!1,E=uh.stringify(t,n,()=>k=!0,()=>m=!0),S=" ";if(f||y||v){if(S=y?`
|
|
42
|
+
`:"",v){let $=d(v);S+=`
|
|
43
|
+
${Kn.indentComment($,n.indent)}`}E===""&&!n.inFlow?S===`
|
|
44
|
+
`&&b&&(S=`
|
|
45
45
|
|
|
46
|
-
`)
|
|
47
|
-
${n.indent}`}else if(!
|
|
48
|
-
`),j
|
|
49
|
-
${n.indent}`)}}else(
|
|
50
|
-
`)&&(
|
|
46
|
+
`):S+=`
|
|
47
|
+
${n.indent}`}else if(!h&&He.isCollection(t)){let $=E[0],j=E.indexOf(`
|
|
48
|
+
`),A=j!==-1,P=n.inFlow??t.flow??t.items.length===0;if(A||!P){let D=!1;if(A&&($==="&"||$==="!")){let x=E.indexOf(" ");$==="&"&&x!==-1&&x<j&&E[x+1]==="!"&&(x=E.indexOf(" ",x+1)),(x===-1||j<x)&&(D=!0)}D||(S=`
|
|
49
|
+
${n.indent}`)}}else(E===""||E[0]===`
|
|
50
|
+
`)&&(S="");return w+=S+E,n.inFlow?k&&r&&r():b&&!k?w+=Kn.lineComment(w,n.indent,d(b)):m&&s&&s(),w}lh.stringifyPair=fb});var Hi=I(Vi=>{"use strict";var ph=wr("process");function pb(e,...t){e==="debug"&&console.log(...t)}function hb(e,t){(e==="debug"||e==="warn")&&(typeof ph.emitWarning=="function"?ph.emitWarning(t):console.warn(t))}Vi.debug=pb;Vi.warn=hb});var Cs=I(Is=>{"use strict";var js=_(),hh=X(),As="<<",Os={identify:e=>e===As||typeof e=="symbol"&&e.description===As,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new hh.Scalar(Symbol(As)),{addToJSMap:mh}),stringify:()=>As},mb=(e,t)=>(Os.identify(t)||js.isScalar(t)&&(!t.type||t.type===hh.Scalar.PLAIN)&&Os.identify(t.value))&&e?.doc.schema.tags.some(n=>n.tag===Os.tag&&n.default);function mh(e,t,n){let r=gh(e,n);if(js.isSeq(r))for(let s of r.items)Ji(e,t,s);else if(Array.isArray(r))for(let s of r)Ji(e,t,s);else Ji(e,t,r)}function Ji(e,t,n){let r=gh(e,n);if(!js.isMap(r))throw new Error("Merge sources must be maps or map aliases");let s=r.toJSON(null,e,Map);for(let[o,i]of s)t instanceof Map?t.has(o)||t.set(o,i):t instanceof Set?t.add(o):Object.prototype.hasOwnProperty.call(t,o)||Object.defineProperty(t,o,{value:i,writable:!0,enumerable:!0,configurable:!0});return t}function gh(e,t){return e&&js.isAlias(t)?t.resolve(e.doc,e):t}Is.addMergeToJSMap=mh;Is.isMergeKey=mb;Is.merge=Os});var Gi=I(vh=>{"use strict";var gb=Hi(),yh=Cs(),yb=Un(),wh=_(),Yi=ot();function wb(e,t,{key:n,value:r}){if(wh.isNode(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(yh.isMergeKey(e,n))yh.addMergeToJSMap(e,t,r);else{let s=Yi.toJS(n,"",e);if(t instanceof Map)t.set(s,Yi.toJS(r,s,e));else if(t instanceof Set)t.add(s);else{let o=vb(n,s,e),i=Yi.toJS(r,o,e);o in t?Object.defineProperty(t,o,{value:i,writable:!0,enumerable:!0,configurable:!0}):t[o]=i}}return t}function vb(e,t,n){if(t===null)return"";if(typeof t!="object")return String(t);if(wh.isNode(e)&&n?.doc){let r=yb.createStringifyContext(n.doc,{});r.anchors=new Set;for(let o of n.anchors.keys())r.anchors.add(o.anchor);r.inFlow=!0,r.inStringifyKey=!0;let s=e.toString(r);if(!n.mapKeyWarned){let o=JSON.stringify(s);o.length>40&&(o=o.substring(0,36)+'..."'),gb.warn(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${o}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return s}return JSON.stringify(t)}vh.addPairToJSMap=wb});var dt=I(Qi=>{"use strict";var kh=Mn(),kb=fh(),bb=Gi(),Ds=_();function Eb(e,t,n){let r=kh.createNode(e,void 0,n),s=kh.createNode(t,void 0,n);return new Ps(r,s)}var Ps=class e{constructor(t,n=null){Object.defineProperty(this,Ds.NODE_TYPE,{value:Ds.PAIR}),this.key=t,this.value=n}clone(t){let{key:n,value:r}=this;return Ds.isNode(n)&&(n=n.clone(t)),Ds.isNode(r)&&(r=r.clone(t)),new e(n,r)}toJSON(t,n){let r=n?.mapAsMap?new Map:{};return bb.addPairToJSMap(n,r,this)}toString(t,n,r){return t?.doc?kb.stringifyPair(this,t,n,r):JSON.stringify(this)}};Qi.Pair=Ps;Qi.createPair=Eb});var Xi=I(Eh=>{"use strict";var jt=_(),bh=Un(),Ns=zn();function Rb(e,t,n){return(t.inFlow??e.flow?$b:Sb)(e,t,n)}function Sb({comment:e,items:t},n,{blockItemPrefix:r,flowChars:s,itemIndent:o,onChompKeep:i,onComment:a}){let{indent:c,options:{commentString:d}}=n,u=Object.assign({},n,{indent:o,type:null}),l=!1,f=[];for(let g=0;g<t.length;++g){let m=t[g],w=null;if(jt.isNode(m))!l&&m.spaceBefore&&f.push(""),Ts(n,f,m.commentBefore,l),m.comment&&(w=m.comment);else if(jt.isPair(m)){let v=jt.isNode(m.key)?m.key:null;v&&(!l&&v.spaceBefore&&f.push(""),Ts(n,f,v.commentBefore,l))}l=!1;let y=bh.stringify(m,u,()=>w=null,()=>l=!0);w&&(y+=Ns.lineComment(y,o,d(w))),l&&w&&(l=!1),f.push(r+y)}let h;if(f.length===0)h=s.start+s.end;else{h=f[0];for(let g=1;g<f.length;++g){let m=f[g];h+=m?`
|
|
51
51
|
${c}${m}`:`
|
|
52
|
-
`}}return e?(
|
|
53
|
-
`+
|
|
54
|
-
`)),
|
|
55
|
-
${
|
|
56
|
-
`;return`${
|
|
57
|
-
${s}${
|
|
58
|
-
`:" ")}return
|
|
59
|
-
${s.key.commentBefore}`:r.commentBefore),r.comment){let
|
|
60
|
-
${i.comment}`:r.comment}r=s}e.items[n]=fs.isPair(r)?r:new lo.Pair(r)}}else t("Expected a sequence for this tag");return e}function yf(e,t,n){let{replacer:r}=n,s=new Ow.YAMLSeq(e);s.tag="tag:yaml.org,2002:pairs";let i=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof r=="function"&&(o=r.call(t,String(i++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;s.items.push(lo.createPair(a,c,n))}return s}var Cw={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:gf,createNode:yf};ps.createPairs=yf;ps.pairs=Cw;ps.resolvePairs=gf});var po=C(fo=>{"use strict";var wf=x(),uo=We(),In=Xe(),jw=Ze(),vf=hs(),ft=class e extends jw.YAMLSeq{constructor(){super(),this.add=In.YAMLMap.prototype.add.bind(this),this.delete=In.YAMLMap.prototype.delete.bind(this),this.get=In.YAMLMap.prototype.get.bind(this),this.has=In.YAMLMap.prototype.has.bind(this),this.set=In.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,n){if(!n)return super.toJSON(t);let r=new Map;n?.onCreate&&n.onCreate(r);for(let s of this.items){let i,o;if(wf.isPair(s)?(i=uo.toJS(s.key,"",n),o=uo.toJS(s.value,i,n)):i=uo.toJS(s,"",n),r.has(i))throw new Error("Ordered maps must not include duplicate keys");r.set(i,o)}return r}static from(t,n,r){let s=vf.createPairs(t,n,r),i=new this;return i.items=s.items,i}};ft.tag="tag:yaml.org,2002:omap";var Nw={collection:"seq",identify:e=>e instanceof Map,nodeClass:ft,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let n=vf.resolvePairs(e,t),r=[];for(let{key:s}of n.items)wf.isScalar(s)&&(r.includes(s.value)?t(`Ordered maps must not include duplicate keys: ${s.value}`):r.push(s.value));return Object.assign(new ft,n)},createNode:(e,t,n)=>ft.from(e,t,n)};fo.YAMLOMap=ft;fo.omap=Nw});var Rf=C(ho=>{"use strict";var kf=V();function bf({value:e,source:t},n){return t&&(e?Ef:Sf).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var Ef={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new kf.Scalar(!0),stringify:bf},Sf={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new kf.Scalar(!1),stringify:bf};ho.falseTag=Sf;ho.trueTag=Ef});var $f=C(ms=>{"use strict";var Iw=V(),mo=qt(),Dw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:mo.stringifyNumber},Tw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():mo.stringifyNumber(e)}},Pw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new Iw.Scalar(parseFloat(e.replace(/_/g,""))),n=e.indexOf(".");if(n!==-1){let r=e.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:mo.stringifyNumber};ms.float=Pw;ms.floatExp=Tw;ms.floatNaN=Dw});var Of=C(Tn=>{"use strict";var Af=qt(),Dn=e=>typeof e=="bigint"||Number.isInteger(e);function gs(e,t,n,{intAsBigInt:r}){let s=e[0];if((s==="-"||s==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let o=BigInt(e);return s==="-"?BigInt(-1)*o:o}let i=parseInt(e,n);return s==="-"?-1*i:i}function go(e,t,n){let{value:r}=e;if(Dn(r)){let s=r.toString(t);return r<0?"-"+n+s.substr(1):n+s}return Af.stringifyNumber(e)}var Lw={identify:Dn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>gs(e,2,2,n),stringify:e=>go(e,2,"0b")},Fw={identify:Dn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>gs(e,1,8,n),stringify:e=>go(e,8,"0")},xw={identify:Dn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>gs(e,0,10,n),stringify:Af.stringifyNumber},Mw={identify:Dn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>gs(e,2,16,n),stringify:e=>go(e,16,"0x")};Tn.int=xw;Tn.intBin=Lw;Tn.intHex=Mw;Tn.intOct=Fw});var wo=C(yo=>{"use strict";var vs=x(),ys=He(),ws=Xe(),pt=class e extends ws.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let n;vs.isPair(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new ys.Pair(t.key,null):n=new ys.Pair(t,null),ws.findPair(this.items,n.key)||this.items.push(n)}get(t,n){let r=ws.findPair(this.items,t);return!n&&vs.isPair(r)?vs.isScalar(r.key)?r.key.value:r.key:r}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=ws.findPair(this.items,t);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new ys.Pair(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(t,n,r){let{replacer:s}=r,i=new this(t);if(n&&Symbol.iterator in Object(n))for(let o of n)typeof s=="function"&&(o=s.call(n,o,o)),i.items.push(ys.createPair(o,null,r));return i}};pt.tag="tag:yaml.org,2002:set";var _w={collection:"map",identify:e=>e instanceof Set,nodeClass:pt,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>pt.from(e,t,n),resolve(e,t){if(vs.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new pt,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};yo.YAMLSet=pt;yo.set=_w});var ko=C(ks=>{"use strict";var qw=qt();function vo(e,t){let n=e[0],r=n==="-"||n==="+"?e.substring(1):e,s=o=>t?BigInt(o):Number(o),i=r.replace(/_/g,"").split(":").reduce((o,a)=>o*s(60)+s(a),s(0));return n==="-"?s(-1)*i:i}function Cf(e){let{value:t}=e,n=o=>o;if(typeof t=="bigint")n=o=>BigInt(o);else if(isNaN(t)||!isFinite(t))return qw.stringifyNumber(e);let r="";t<0&&(r="-",t*=n(-1));let s=n(60),i=[t%s];return t<60?i.unshift(0):(t=(t-i[0])/s,i.unshift(t%s),t>=60&&(t=(t-i[0])/s,i.unshift(t))),r+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var zw={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>vo(e,n),stringify:Cf},Bw={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>vo(e,!1),stringify:Cf},jf={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(jf.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,s,i,o,a]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,l=Date.UTC(n,r-1,s,i||0,o||0,a||0,c),u=t[8];if(u&&u!=="Z"){let d=vo(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};ks.floatTime=Bw;ks.intTime=zw;ks.timestamp=jf});var Df=C(If=>{"use strict";var Kw=Mt(),Uw=as(),Vw=_t(),Ww=jn(),Jw=co(),Nf=Rf(),bo=$f(),bs=Of(),Yw=Zr(),Gw=po(),Hw=hs(),Qw=wo(),Eo=ko(),Xw=[Kw.map,Vw.seq,Ww.string,Uw.nullTag,Nf.trueTag,Nf.falseTag,bs.intBin,bs.intOct,bs.int,bs.intHex,bo.floatNaN,bo.floatExp,bo.float,Jw.binary,Yw.merge,Gw.omap,Hw.pairs,Qw.set,Eo.intTime,Eo.floatTime,Eo.timestamp];If.schema=Xw});var Bf=C($o=>{"use strict";var Ff=Mt(),Zw=as(),xf=_t(),ev=jn(),tv=eo(),So=no(),Ro=so(),nv=df(),rv=hf(),Mf=co(),Pn=Zr(),_f=po(),qf=hs(),Tf=Df(),zf=wo(),Es=ko(),Pf=new Map([["core",nv.schema],["failsafe",[Ff.map,xf.seq,ev.string]],["json",rv.schema],["yaml11",Tf.schema],["yaml-1.1",Tf.schema]]),Lf={binary:Mf.binary,bool:tv.boolTag,float:So.float,floatExp:So.floatExp,floatNaN:So.floatNaN,floatTime:Es.floatTime,int:Ro.int,intHex:Ro.intHex,intOct:Ro.intOct,intTime:Es.intTime,map:Ff.map,merge:Pn.merge,null:Zw.nullTag,omap:_f.omap,pairs:qf.pairs,seq:xf.seq,set:zf.set,timestamp:Es.timestamp},sv={"tag:yaml.org,2002:binary":Mf.binary,"tag:yaml.org,2002:merge":Pn.merge,"tag:yaml.org,2002:omap":_f.omap,"tag:yaml.org,2002:pairs":qf.pairs,"tag:yaml.org,2002:set":zf.set,"tag:yaml.org,2002:timestamp":Es.timestamp};function iv(e,t,n){let r=Pf.get(t);if(r&&!e)return n&&!r.includes(Pn.merge)?r.concat(Pn.merge):r.slice();let s=r;if(!s)if(Array.isArray(e))s=[];else{let i=Array.from(Pf.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${i} or define customTags array`)}if(Array.isArray(e))for(let i of e)s=s.concat(i);else typeof e=="function"&&(s=e(s.slice()));return n&&(s=s.concat(Pn.merge)),s.reduce((i,o)=>{let a=typeof o=="string"?Lf[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Lf).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}$o.coreKnownTags=sv;$o.getTags=iv});var Co=C(Kf=>{"use strict";var Ao=x(),ov=Mt(),av=_t(),cv=jn(),Ss=Bf(),lv=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,Oo=class e{constructor({compat:t,customTags:n,merge:r,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(t)?Ss.getTags(t,"compat"):t?Ss.getTags(null,t):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?Ss.coreKnownTags:{},this.tags=Ss.getTags(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,Ao.MAP,{value:ov.map}),Object.defineProperty(this,Ao.SCALAR,{value:cv.string}),Object.defineProperty(this,Ao.SEQ,{value:av.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?lv:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};Kf.Schema=Oo});var Vf=C(Uf=>{"use strict";var uv=x(),jo=An(),Ln=En();function dv(e,t){let n=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(n.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&n.push("---");let s=jo.createStringifyContext(e,t),{commentString:i}=s.options;if(e.commentBefore){n.length!==1&&n.unshift("");let c=i(e.commentBefore);n.unshift(Ln.indentComment(c,""))}let o=!1,a=null;if(e.contents){if(uv.isNode(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){let u=i(e.contents.commentBefore);n.push(Ln.indentComment(u,""))}s.forceBlockIndent=!!e.comment,a=e.contents.comment}let c=a?void 0:()=>o=!0,l=jo.stringify(e.contents,s,()=>a=null,c);a&&(l+=Ln.lineComment(l,"",i(a))),(l[0]==="|"||l[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${l}`:n.push(l)}else n.push(jo.stringify(e.contents,s));if(e.directives?.docEnd)if(e.comment){let c=i(e.comment);c.includes(`
|
|
61
|
-
`)?(n.push("..."),n.push(
|
|
52
|
+
`}}return e?(h+=`
|
|
53
|
+
`+Ns.indentComment(d(e),c),a&&a()):l&&i&&i(),h}function $b({items:e},t,{flowChars:n,itemIndent:r}){let{indent:s,indentStep:o,flowCollectionPadding:i,options:{commentString:a}}=t;r+=o;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),d=!1,u=0,l=[];for(let g=0;g<e.length;++g){let m=e[g],w=null;if(jt.isNode(m))m.spaceBefore&&l.push(""),Ts(t,l,m.commentBefore,!1),m.comment&&(w=m.comment);else if(jt.isPair(m)){let v=jt.isNode(m.key)?m.key:null;v&&(v.spaceBefore&&l.push(""),Ts(t,l,v.commentBefore,!1),v.comment&&(d=!0));let b=jt.isNode(m.value)?m.value:null;b?(b.comment&&(w=b.comment),b.commentBefore&&(d=!0)):m.value==null&&v?.comment&&(w=v.comment)}w&&(d=!0);let y=bh.stringify(m,c,()=>w=null);d||(d=l.length>u||y.includes(`
|
|
54
|
+
`)),g<e.length-1?y+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(d||(d=l.reduce((v,b)=>v+b.length+2,2)+(y.length+2)>t.options.lineWidth)),d&&(y+=",")),w&&(y+=Ns.lineComment(y,r,a(w))),l.push(y),u=l.length}let{start:f,end:h}=n;if(l.length===0)return f+h;if(!d){let g=l.reduce((m,w)=>m+w.length+2,2);d=t.options.lineWidth>0&&g>t.options.lineWidth}if(d){let g=f;for(let m of l)g+=m?`
|
|
55
|
+
${o}${s}${m}`:`
|
|
56
|
+
`;return`${g}
|
|
57
|
+
${s}${h}`}else return`${f}${i}${l.join(" ")}${i}${h}`}function Ts({indent:e,options:{commentString:t}},n,r,s){if(r&&s&&(r=r.replace(/^\n+/,"")),r){let o=Ns.indentComment(t(r),e);n.push(o.trimStart())}}Eh.stringifyCollection=Rb});var lt=I(ea=>{"use strict";var Ab=Xi(),Ob=Gi(),jb=ks(),ut=_(),xs=dt(),Ib=X();function Wn(e,t){let n=ut.isScalar(t)?t.value:t;for(let r of e)if(ut.isPair(r)&&(r.key===t||r.key===n||ut.isScalar(r.key)&&r.key.value===n))return r}var Zi=class extends jb.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(t){super(ut.MAP,t),this.items=[]}static from(t,n,r){let{keepUndefined:s,replacer:o}=r,i=new this(t),a=(c,d)=>{if(typeof o=="function")d=o.call(n,c,d);else if(Array.isArray(o)&&!o.includes(c))return;(d!==void 0||s)&&i.items.push(xs.createPair(c,d,r))};if(n instanceof Map)for(let[c,d]of n)a(c,d);else if(n&&typeof n=="object")for(let c of Object.keys(n))a(c,n[c]);return typeof t.sortMapEntries=="function"&&i.items.sort(t.sortMapEntries),i}add(t,n){let r;ut.isPair(t)?r=t:!t||typeof t!="object"||!("key"in t)?r=new xs.Pair(t,t?.value):r=new xs.Pair(t.key,t.value);let s=Wn(this.items,r.key),o=this.schema?.sortMapEntries;if(s){if(!n)throw new Error(`Key ${r.key} already set`);ut.isScalar(s.value)&&Ib.isScalarValue(r.value)?s.value.value=r.value:s.value=r.value}else if(o){let i=this.items.findIndex(a=>o(r,a)<0);i===-1?this.items.push(r):this.items.splice(i,0,r)}else this.items.push(r)}delete(t){let n=Wn(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){let s=Wn(this.items,t)?.value;return(!n&&ut.isScalar(s)?s.value:s)??void 0}has(t){return!!Wn(this.items,t)}set(t,n){this.add(new xs.Pair(t,n),!0)}toJSON(t,n,r){let s=r?new r:n?.mapAsMap?new Map:{};n?.onCreate&&n.onCreate(s);for(let o of this.items)Ob.addPairToJSMap(n,s,o);return s}toString(t,n,r){if(!t)return JSON.stringify(this);for(let s of this.items)if(!ut.isPair(s))throw new Error(`Map items must all be pairs; found ${JSON.stringify(s)} instead`);return!t.allNullValues&&this.hasAllNullValues(!1)&&(t=Object.assign({},t,{allNullValues:!0})),Ab.stringifyCollection(this,t,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:t.indent||"",onChompKeep:r,onComment:n})}};ea.YAMLMap=Zi;ea.findPair=Wn});var en=I(Sh=>{"use strict";var Cb=_(),Rh=lt(),Db={collection:"map",default:!0,nodeClass:Rh.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(e,t){return Cb.isMap(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,n)=>Rh.YAMLMap.from(e,t,n)};Sh.map=Db});var ft=I($h=>{"use strict";var Pb=Mn(),Nb=Xi(),Tb=ks(),Fs=_(),xb=X(),Lb=ot(),ta=class extends Tb.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(t){super(Fs.SEQ,t),this.items=[]}add(t){this.items.push(t)}delete(t){let n=Ls(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){let r=Ls(t);if(typeof r!="number")return;let s=this.items[r];return!n&&Fs.isScalar(s)?s.value:s}has(t){let n=Ls(t);return typeof n=="number"&&n<this.items.length}set(t,n){let r=Ls(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);let s=this.items[r];Fs.isScalar(s)&&xb.isScalarValue(n)?s.value=n:this.items[r]=n}toJSON(t,n){let r=[];n?.onCreate&&n.onCreate(r);let s=0;for(let o of this.items)r.push(Lb.toJS(o,String(s++),n));return r}toString(t,n,r){return t?Nb.stringifyCollection(this,t,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(t.indent||"")+" ",onChompKeep:r,onComment:n}):JSON.stringify(this)}static from(t,n,r){let{replacer:s}=r,o=new this(t);if(n&&Symbol.iterator in Object(n)){let i=0;for(let a of n){if(typeof s=="function"){let c=n instanceof Set?a:String(i++);a=s.call(n,c,a)}o.items.push(Pb.createNode(a,void 0,r))}}return o}};function Ls(e){let t=Fs.isScalar(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}$h.YAMLSeq=ta});var tn=I(Oh=>{"use strict";var Fb=_(),Ah=ft(),Mb={collection:"seq",default:!0,nodeClass:Ah.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(e,t){return Fb.isSeq(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,n)=>Ah.YAMLSeq.from(e,t,n)};Oh.seq=Mb});var Vn=I(jh=>{"use strict";var zb=Bn(),_b={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),zb.stringifyString(e,t,n,r)}};jh.string=_b});var Ms=I(Dh=>{"use strict";var Ih=X(),Ch={identify:e=>e==null,createNode:()=>new Ih.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Ih.Scalar(null),stringify:({source:e},t)=>typeof e=="string"&&Ch.test.test(e)?e:t.options.nullStr};Dh.nullTag=Ch});var na=I(Nh=>{"use strict";var qb=X(),Ph={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new qb.Scalar(e[0]==="t"||e[0]==="T"),stringify({source:e,value:t},n){if(e&&Ph.test.test(e)){let r=e[0]==="t"||e[0]==="T";if(t===r)return e}return t?n.options.trueStr:n.options.falseStr}};Nh.boolTag=Ph});var nn=I(Th=>{"use strict";function Bb({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r=="bigint")return String(r);let s=typeof r=="number"?r:Number(r);if(!isFinite(s))return isNaN(s)?".nan":s<0?"-.inf":".inf";let o=Object.is(r,-0)?"-0":JSON.stringify(r);if(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^-?\d/.test(o)&&!o.includes("e")){let i=o.indexOf(".");i<0&&(i=o.length,o+=".");let a=t-(o.length-i-1);for(;a-- >0;)o+="0"}return o}Th.stringifyNumber=Bb});var sa=I(zs=>{"use strict";var Ub=X(),ra=nn(),Kb={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ra.stringifyNumber},Wb={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():ra.stringifyNumber(e)}},Vb={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new Ub.Scalar(parseFloat(e)),n=e.indexOf(".");return n!==-1&&e[e.length-1]==="0"&&(t.minFractionDigits=e.length-n-1),t},stringify:ra.stringifyNumber};zs.float=Vb;zs.floatExp=Wb;zs.floatNaN=Kb});var ia=I(qs=>{"use strict";var xh=nn(),_s=e=>typeof e=="bigint"||Number.isInteger(e),oa=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function Lh(e,t,n){let{value:r}=e;return _s(r)&&r>=0?n+r.toString(t):xh.stringifyNumber(e)}var Hb={identify:e=>_s(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(e,t,n)=>oa(e,2,8,n),stringify:e=>Lh(e,8,"0o")},Jb={identify:_s,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>oa(e,0,10,n),stringify:xh.stringifyNumber},Yb={identify:e=>_s(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>oa(e,2,16,n),stringify:e=>Lh(e,16,"0x")};qs.int=Jb;qs.intHex=Yb;qs.intOct=Hb});var Mh=I(Fh=>{"use strict";var Gb=en(),Qb=Ms(),Xb=tn(),Zb=Vn(),eE=na(),aa=sa(),ca=ia(),tE=[Gb.map,Xb.seq,Zb.string,Qb.nullTag,eE.boolTag,ca.intOct,ca.int,ca.intHex,aa.floatNaN,aa.floatExp,aa.float];Fh.schema=tE});var qh=I(_h=>{"use strict";var nE=X(),rE=en(),sE=tn();function zh(e){return typeof e=="bigint"||Number.isInteger(e)}var Bs=({value:e})=>JSON.stringify(e),oE=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Bs},{identify:e=>e==null,createNode:()=>new nE.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Bs},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Bs},{identify:zh,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>zh(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Bs}],iE={default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}},aE=[rE.map,sE.seq].concat(oE,iE);_h.schema=aE});var ua=I(Bh=>{"use strict";var Hn=wr("buffer"),da=X(),cE=Bn(),dE={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(e,t){if(typeof Hn.Buffer=="function")return Hn.Buffer.from(e,"base64");if(typeof atob=="function"){let n=atob(e.replace(/[\n\r]/g,"")),r=new Uint8Array(n.length);for(let s=0;s<n.length;++s)r[s]=n.charCodeAt(s);return r}else return t("This environment does not support reading binary tags; either Buffer or atob is required"),e},stringify({comment:e,type:t,value:n},r,s,o){if(!n)return"";let i=n,a;if(typeof Hn.Buffer=="function")a=i instanceof Hn.Buffer?i.toString("base64"):Hn.Buffer.from(i.buffer).toString("base64");else if(typeof btoa=="function"){let c="";for(let d=0;d<i.length;++d)c+=String.fromCharCode(i[d]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(t??(t=da.Scalar.BLOCK_LITERAL),t!==da.Scalar.QUOTE_DOUBLE){let c=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),d=Math.ceil(a.length/c),u=new Array(d);for(let l=0,f=0;l<d;++l,f+=c)u[l]=a.substr(f,c);a=u.join(t===da.Scalar.BLOCK_LITERAL?`
|
|
58
|
+
`:" ")}return cE.stringifyString({comment:e,type:t,value:a},r,s,o)}};Bh.binary=dE});var Ws=I(Ks=>{"use strict";var Us=_(),la=dt(),uE=X(),lE=ft();function Uh(e,t){if(Us.isSeq(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!Us.isPair(r)){if(Us.isMap(r)){r.items.length>1&&t("Each pair must have its own sequence indicator");let s=r.items[0]||new la.Pair(new uE.Scalar(null));if(r.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${r.commentBefore}
|
|
59
|
+
${s.key.commentBefore}`:r.commentBefore),r.comment){let o=s.value??s.key;o.comment=o.comment?`${r.comment}
|
|
60
|
+
${o.comment}`:r.comment}r=s}e.items[n]=Us.isPair(r)?r:new la.Pair(r)}}else t("Expected a sequence for this tag");return e}function Kh(e,t,n){let{replacer:r}=n,s=new lE.YAMLSeq(e);s.tag="tag:yaml.org,2002:pairs";let o=0;if(t&&Symbol.iterator in Object(t))for(let i of t){typeof r=="function"&&(i=r.call(t,String(o++),i));let a,c;if(Array.isArray(i))if(i.length===2)a=i[0],c=i[1];else throw new TypeError(`Expected [key, value] tuple: ${i}`);else if(i&&i instanceof Object){let d=Object.keys(i);if(d.length===1)a=d[0],c=i[a];else throw new TypeError(`Expected tuple with one key, not ${d.length} keys`)}else a=i;s.items.push(la.createPair(a,c,n))}return s}var fE={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Uh,createNode:Kh};Ks.createPairs=Kh;Ks.pairs=fE;Ks.resolvePairs=Uh});var ha=I(pa=>{"use strict";var Wh=_(),fa=ot(),Jn=lt(),pE=ft(),Vh=Ws(),It=class e extends pE.YAMLSeq{constructor(){super(),this.add=Jn.YAMLMap.prototype.add.bind(this),this.delete=Jn.YAMLMap.prototype.delete.bind(this),this.get=Jn.YAMLMap.prototype.get.bind(this),this.has=Jn.YAMLMap.prototype.has.bind(this),this.set=Jn.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(t,n){if(!n)return super.toJSON(t);let r=new Map;n?.onCreate&&n.onCreate(r);for(let s of this.items){let o,i;if(Wh.isPair(s)?(o=fa.toJS(s.key,"",n),i=fa.toJS(s.value,o,n)):o=fa.toJS(s,"",n),r.has(o))throw new Error("Ordered maps must not include duplicate keys");r.set(o,i)}return r}static from(t,n,r){let s=Vh.createPairs(t,n,r),o=new this;return o.items=s.items,o}};It.tag="tag:yaml.org,2002:omap";var hE={collection:"seq",identify:e=>e instanceof Map,nodeClass:It,default:!1,tag:"tag:yaml.org,2002:omap",resolve(e,t){let n=Vh.resolvePairs(e,t),r=[];for(let{key:s}of n.items)Wh.isScalar(s)&&(r.includes(s.value)?t(`Ordered maps must not include duplicate keys: ${s.value}`):r.push(s.value));return Object.assign(new It,n)},createNode:(e,t,n)=>It.from(e,t,n)};pa.YAMLOMap=It;pa.omap=hE});var Qh=I(ma=>{"use strict";var Hh=X();function Jh({value:e,source:t},n){return t&&(e?Yh:Gh).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var Yh={identify:e=>e===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Hh.Scalar(!0),stringify:Jh},Gh={identify:e=>e===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new Hh.Scalar(!1),stringify:Jh};ma.falseTag=Gh;ma.trueTag=Yh});var Xh=I(Vs=>{"use strict";var mE=X(),ga=nn(),gE={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()==="nan"?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ga.stringifyNumber},yE={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():ga.stringifyNumber(e)}},wE={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new mE.Scalar(parseFloat(e.replace(/_/g,""))),n=e.indexOf(".");if(n!==-1){let r=e.substring(n+1).replace(/_/g,"");r[r.length-1]==="0"&&(t.minFractionDigits=r.length)}return t},stringify:ga.stringifyNumber};Vs.float=wE;Vs.floatExp=yE;Vs.floatNaN=gE});var em=I(Gn=>{"use strict";var Zh=nn(),Yn=e=>typeof e=="bigint"||Number.isInteger(e);function Hs(e,t,n,{intAsBigInt:r}){let s=e[0];if((s==="-"||s==="+")&&(t+=1),e=e.substring(t).replace(/_/g,""),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`;break}let i=BigInt(e);return s==="-"?BigInt(-1)*i:i}let o=parseInt(e,n);return s==="-"?-1*o:o}function ya(e,t,n){let{value:r}=e;if(Yn(r)){let s=r.toString(t);return r<0?"-"+n+s.substr(1):n+s}return Zh.stringifyNumber(e)}var vE={identify:Yn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Hs(e,2,2,n),stringify:e=>ya(e,2,"0b")},kE={identify:Yn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Hs(e,1,8,n),stringify:e=>ya(e,8,"0")},bE={identify:Yn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Hs(e,0,10,n),stringify:Zh.stringifyNumber},EE={identify:Yn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Hs(e,2,16,n),stringify:e=>ya(e,16,"0x")};Gn.int=bE;Gn.intBin=vE;Gn.intHex=EE;Gn.intOct=kE});var va=I(wa=>{"use strict";var Gs=_(),Js=dt(),Ys=lt(),Ct=class e extends Ys.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(t){let n;Gs.isPair(t)?n=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?n=new Js.Pair(t.key,null):n=new Js.Pair(t,null),Ys.findPair(this.items,n.key)||this.items.push(n)}get(t,n){let r=Ys.findPair(this.items,t);return!n&&Gs.isPair(r)?Gs.isScalar(r.key)?r.key.value:r.key:r}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);let r=Ys.findPair(this.items,t);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new Js.Pair(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),n,r);throw new Error("Set items must all have null values")}static from(t,n,r){let{replacer:s}=r,o=new this(t);if(n&&Symbol.iterator in Object(n))for(let i of n)typeof s=="function"&&(i=s.call(n,i,i)),o.items.push(Js.createPair(i,null,r));return o}};Ct.tag="tag:yaml.org,2002:set";var RE={collection:"map",identify:e=>e instanceof Set,nodeClass:Ct,default:!1,tag:"tag:yaml.org,2002:set",createNode:(e,t,n)=>Ct.from(e,t,n),resolve(e,t){if(Gs.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new Ct,e);t("Set items must all have null values")}else t("Expected a mapping for this tag");return e}};wa.YAMLSet=Ct;wa.set=RE});var ba=I(Qs=>{"use strict";var SE=nn();function ka(e,t){let n=e[0],r=n==="-"||n==="+"?e.substring(1):e,s=i=>t?BigInt(i):Number(i),o=r.replace(/_/g,"").split(":").reduce((i,a)=>i*s(60)+s(a),s(0));return n==="-"?s(-1)*o:o}function tm(e){let{value:t}=e,n=i=>i;if(typeof t=="bigint")n=i=>BigInt(i);else if(isNaN(t)||!isFinite(t))return SE.stringifyNumber(e);let r="";t<0&&(r="-",t*=n(-1));let s=n(60),o=[t%s];return t<60?o.unshift(0):(t=(t-o[0])/s,o.unshift(t%s),t>=60&&(t=(t-o[0])/s,o.unshift(t))),r+o.map(i=>String(i).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var $E={identify:e=>typeof e=="bigint"||Number.isInteger(e),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>ka(e,n),stringify:tm},AE={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>ka(e,!1),stringify:tm},nm={identify:e=>e instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(e){let t=e.match(nm.test);if(!t)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,n,r,s,o,i,a]=t.map(Number),c=t[7]?Number((t[7]+"00").substr(1,3)):0,d=Date.UTC(n,r-1,s,o||0,i||0,a||0,c),u=t[8];if(u&&u!=="Z"){let l=ka(u,!1);Math.abs(l)<30&&(l*=60),d-=6e4*l}return new Date(d)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Qs.floatTime=AE;Qs.intTime=$E;Qs.timestamp=nm});var om=I(sm=>{"use strict";var OE=en(),jE=Ms(),IE=tn(),CE=Vn(),DE=ua(),rm=Qh(),Ea=Xh(),Xs=em(),PE=Cs(),NE=ha(),TE=Ws(),xE=va(),Ra=ba(),LE=[OE.map,IE.seq,CE.string,jE.nullTag,rm.trueTag,rm.falseTag,Xs.intBin,Xs.intOct,Xs.int,Xs.intHex,Ea.floatNaN,Ea.floatExp,Ea.float,DE.binary,PE.merge,NE.omap,TE.pairs,xE.set,Ra.intTime,Ra.floatTime,Ra.timestamp];sm.schema=LE});var mm=I(Aa=>{"use strict";var dm=en(),FE=Ms(),um=tn(),ME=Vn(),zE=na(),Sa=sa(),$a=ia(),_E=Mh(),qE=qh(),lm=ua(),Qn=Cs(),fm=ha(),pm=Ws(),im=om(),hm=va(),Zs=ba(),am=new Map([["core",_E.schema],["failsafe",[dm.map,um.seq,ME.string]],["json",qE.schema],["yaml11",im.schema],["yaml-1.1",im.schema]]),cm={binary:lm.binary,bool:zE.boolTag,float:Sa.float,floatExp:Sa.floatExp,floatNaN:Sa.floatNaN,floatTime:Zs.floatTime,int:$a.int,intHex:$a.intHex,intOct:$a.intOct,intTime:Zs.intTime,map:dm.map,merge:Qn.merge,null:FE.nullTag,omap:fm.omap,pairs:pm.pairs,seq:um.seq,set:hm.set,timestamp:Zs.timestamp},BE={"tag:yaml.org,2002:binary":lm.binary,"tag:yaml.org,2002:merge":Qn.merge,"tag:yaml.org,2002:omap":fm.omap,"tag:yaml.org,2002:pairs":pm.pairs,"tag:yaml.org,2002:set":hm.set,"tag:yaml.org,2002:timestamp":Zs.timestamp};function UE(e,t,n){let r=am.get(t);if(r&&!e)return n&&!r.includes(Qn.merge)?r.concat(Qn.merge):r.slice();let s=r;if(!s)if(Array.isArray(e))s=[];else{let o=Array.from(am.keys()).filter(i=>i!=="yaml11").map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown schema "${t}"; use one of ${o} or define customTags array`)}if(Array.isArray(e))for(let o of e)s=s.concat(o);else typeof e=="function"&&(s=e(s.slice()));return n&&(s=s.concat(Qn.merge)),s.reduce((o,i)=>{let a=typeof i=="string"?cm[i]:i;if(!a){let c=JSON.stringify(i),d=Object.keys(cm).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${d}`)}return o.includes(a)||o.push(a),o},[])}Aa.coreKnownTags=BE;Aa.getTags=UE});var Ia=I(gm=>{"use strict";var Oa=_(),KE=en(),WE=tn(),VE=Vn(),eo=mm(),HE=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0,ja=class e{constructor({compat:t,customTags:n,merge:r,resolveKnownTags:s,schema:o,sortMapEntries:i,toStringDefaults:a}){this.compat=Array.isArray(t)?eo.getTags(t,"compat"):t?eo.getTags(null,t):null,this.name=typeof o=="string"&&o||"core",this.knownTags=s?eo.coreKnownTags:{},this.tags=eo.getTags(n,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,Oa.MAP,{value:KE.map}),Object.defineProperty(this,Oa.SCALAR,{value:VE.string}),Object.defineProperty(this,Oa.SEQ,{value:WE.seq}),this.sortMapEntries=typeof i=="function"?i:i===!0?HE:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};gm.Schema=ja});var wm=I(ym=>{"use strict";var JE=_(),Ca=Un(),Xn=zn();function YE(e,t){let n=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let c=e.directives.toString(e);c?(n.push(c),r=!0):e.directives.docStart&&(r=!0)}r&&n.push("---");let s=Ca.createStringifyContext(e,t),{commentString:o}=s.options;if(e.commentBefore){n.length!==1&&n.unshift("");let c=o(e.commentBefore);n.unshift(Xn.indentComment(c,""))}let i=!1,a=null;if(e.contents){if(JE.isNode(e.contents)){if(e.contents.spaceBefore&&r&&n.push(""),e.contents.commentBefore){let u=o(e.contents.commentBefore);n.push(Xn.indentComment(u,""))}s.forceBlockIndent=!!e.comment,a=e.contents.comment}let c=a?void 0:()=>i=!0,d=Ca.stringify(e.contents,s,()=>a=null,c);a&&(d+=Xn.lineComment(d,"",o(a))),(d[0]==="|"||d[0]===">")&&n[n.length-1]==="---"?n[n.length-1]=`--- ${d}`:n.push(d)}else n.push(Ca.stringify(e.contents,s));if(e.directives?.docEnd)if(e.comment){let c=o(e.comment);c.includes(`
|
|
61
|
+
`)?(n.push("..."),n.push(Xn.indentComment(c,""))):n.push(`... ${c}`)}else n.push("...");else{let c=e.comment;c&&i&&(c=c.replace(/^\n+/,"")),c&&((!i||a)&&n[n.length-1]!==""&&n.push(""),n.push(Xn.indentComment(o(c),"")))}return n.join(`
|
|
62
62
|
`)+`
|
|
63
|
-
`}
|
|
64
|
-
`),
|
|
63
|
+
`}ym.stringifyDocument=YE});var Zn=I(vm=>{"use strict";var GE=Fn(),rn=ks(),Re=_(),QE=dt(),XE=ot(),ZE=Ia(),eR=wm(),Da=gs(),tR=xi(),nR=Mn(),Pa=Ti(),Na=class e{constructor(t,n,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Re.NODE_TYPE,{value:Re.DOC});let s=null;typeof n=="function"||Array.isArray(n)?s=n:r===void 0&&n&&(r=n,n=void 0);let o=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=o;let{version:i}=o;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(i=this.directives.yaml.version)):this.directives=new Pa.Directives({version:i}),this.setSchema(i,r),this.contents=t===void 0?null:this.createNode(t,s,r)}clone(){let t=Object.create(e.prototype,{[Re.NODE_TYPE]:{value:Re.DOC}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Re.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(t){sn(this.contents)&&this.contents.add(t)}addIn(t,n){sn(this.contents)&&this.contents.addIn(t,n)}createAlias(t,n){if(!t.anchor){let r=Da.anchorNames(this);t.anchor=!n||r.has(n)?Da.findNewAnchor(n||"a",r):n}return new GE.Alias(t.anchor)}createNode(t,n,r){let s;if(typeof n=="function")t=n.call({"":t},"",t),s=n;else if(Array.isArray(n)){let w=v=>typeof v=="number"||v instanceof String||v instanceof Number,y=n.filter(w).map(String);y.length>0&&(n=n.concat(y)),s=n}else r===void 0&&n&&(r=n,n=void 0);let{aliasDuplicateObjects:o,anchorPrefix:i,flow:a,keepUndefined:c,onTagObj:d,tag:u}=r??{},{onAnchor:l,setAnchors:f,sourceObjects:h}=Da.createNodeAnchors(this,i||"a"),g={aliasDuplicateObjects:o??!0,keepUndefined:c??!1,onAnchor:l,onTagObj:d,replacer:s,schema:this.schema,sourceObjects:h},m=nR.createNode(t,u,g);return a&&Re.isCollection(m)&&(m.flow=!0),f(),m}createPair(t,n,r={}){let s=this.createNode(t,null,r),o=this.createNode(n,null,r);return new QE.Pair(s,o)}delete(t){return sn(this.contents)?this.contents.delete(t):!1}deleteIn(t){return rn.isEmptyPath(t)?this.contents==null?!1:(this.contents=null,!0):sn(this.contents)?this.contents.deleteIn(t):!1}get(t,n){return Re.isCollection(this.contents)?this.contents.get(t,n):void 0}getIn(t,n){return rn.isEmptyPath(t)?!n&&Re.isScalar(this.contents)?this.contents.value:this.contents:Re.isCollection(this.contents)?this.contents.getIn(t,n):void 0}has(t){return Re.isCollection(this.contents)?this.contents.has(t):!1}hasIn(t){return rn.isEmptyPath(t)?this.contents!==void 0:Re.isCollection(this.contents)?this.contents.hasIn(t):!1}set(t,n){this.contents==null?this.contents=rn.collectionFromPath(this.schema,[t],n):sn(this.contents)&&this.contents.set(t,n)}setIn(t,n){rn.isEmptyPath(t)?this.contents=n:this.contents==null?this.contents=rn.collectionFromPath(this.schema,Array.from(t),n):sn(this.contents)&&this.contents.setIn(t,n)}setSchema(t,n={}){typeof t=="number"&&(t=String(t));let r;switch(t){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Pa.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=t:this.directives=new Pa.Directives({version:t}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let s=JSON.stringify(t);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${s}`)}}if(n.schema instanceof Object)this.schema=n.schema;else if(r)this.schema=new ZE.Schema(Object.assign(r,n));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:t,jsonArg:n,mapAsMap:r,maxAliasCount:s,onAnchor:o,reviver:i}={}){let a={anchors:new Map,doc:this,keep:!t,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},c=XE.toJS(this.contents,n??"",a);if(typeof o=="function")for(let{count:d,res:u}of a.anchors.values())o(u,d);return typeof i=="function"?tR.applyReviver(i,{"":c},"",c):c}toJSON(t,n){return this.toJS({json:!0,jsonArg:t,mapAsMap:!1,onAnchor:n})}toString(t={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in t&&(!Number.isInteger(t.indent)||Number(t.indent)<=0)){let n=JSON.stringify(t.indent);throw new Error(`"indent" option must be a positive integer, not ${n}`)}return eR.stringifyDocument(this,t)}};function sn(e){if(Re.isCollection(e))return!0;throw new Error("Expected a YAML collection as document contents")}vm.Document=Na});var nr=I(tr=>{"use strict";var er=class extends Error{constructor(t,n,r,s){super(),this.name=t,this.code=r,this.message=s,this.pos=n}},Ta=class extends er{constructor(t,n,r){super("YAMLParseError",t,n,r)}},xa=class extends er{constructor(t,n,r){super("YAMLWarning",t,n,r)}},rR=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(a=>t.linePos(a));let{line:r,col:s}=n.linePos[0];n.message+=` at line ${r}, column ${s}`;let o=s-1,i=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,"");if(o>=60&&i.length>80){let a=Math.min(o-39,i.length-79);i="\u2026"+i.substring(a),o-=a-1}if(i.length>80&&(i=i.substring(0,79)+"\u2026"),r>1&&/^ *$/.test(i.substring(0,o))){let a=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
|
|
64
|
+
`),i=a+i}if(/[^ ]/.test(i)){let a=1,c=n.linePos[1];c?.line===r&&c.col>s&&(a=Math.max(1,Math.min(c.col-s,80-o)));let d=" ".repeat(o)+"^".repeat(a);n.message+=`:
|
|
65
65
|
|
|
66
|
-
${
|
|
67
|
-
${
|
|
68
|
-
`}};
|
|
69
|
-
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let n of t.start)if(n.type==="newline")return!0;if(t.sep){for(let n of t.sep)if(n.type==="newline")return!0}if(
|
|
70
|
-
`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp
|
|
71
|
-
`+
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
`+
|
|
75
|
-
`+
|
|
76
|
-
`.repeat(Math.max(1,
|
|
77
|
-
`;for(let m=u;m<a;++m){let[
|
|
78
|
-
`):
|
|
79
|
-
`:!
|
|
66
|
+
${i}
|
|
67
|
+
${d}
|
|
68
|
+
`}};tr.YAMLError=er;tr.YAMLParseError=Ta;tr.YAMLWarning=xa;tr.prettifyError=rR});var rr=I(km=>{"use strict";function sR(e,{flow:t,indicator:n,next:r,offset:s,onError:o,parentIndent:i,startOnNewline:a}){let c=!1,d=a,u=a,l="",f="",h=!1,g=!1,m=null,w=null,y=null,v=null,b=null,k=null,E=null;for(let j of e)switch(g&&(j.type!=="space"&&j.type!=="newline"&&j.type!=="comma"&&o(j.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g=!1),m&&(d&&j.type!=="comment"&&j.type!=="newline"&&o(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),j.type){case"space":!t&&(n!=="doc-start"||r?.type!=="flow-collection")&&j.source.includes(" ")&&(m=j),u=!0;break;case"comment":{u||o(j,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let A=j.source.substring(1)||" ";l?l+=f+A:l=A,f="",d=!1;break}case"newline":d?l?l+=j.source:(!k||n!=="seq-item-ind")&&(c=!0):f+=j.source,d=!0,h=!0,(w||y)&&(v=j),u=!0;break;case"anchor":w&&o(j,"MULTIPLE_ANCHORS","A node can have at most one anchor"),j.source.endsWith(":")&&o(j.offset+j.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),w=j,E??(E=j.offset),d=!1,u=!1,g=!0;break;case"tag":{y&&o(j,"MULTIPLE_TAGS","A node can have at most one tag"),y=j,E??(E=j.offset),d=!1,u=!1,g=!0;break}case n:(w||y)&&o(j,"BAD_PROP_ORDER",`Anchors and tags must be after the ${j.source} indicator`),k&&o(j,"UNEXPECTED_TOKEN",`Unexpected ${j.source} in ${t??"collection"}`),k=j,d=n==="seq-item-ind"||n==="explicit-key-ind",u=!1;break;case"comma":if(t){b&&o(j,"UNEXPECTED_TOKEN",`Unexpected , in ${t}`),b=j,d=!1,u=!1;break}default:o(j,"UNEXPECTED_TOKEN",`Unexpected ${j.type} token`),d=!1,u=!1}let S=e[e.length-1],$=S?S.offset+S.source.length:s;return g&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&o(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(d&&m.indent<=i||r?.type==="block-map"||r?.type==="block-seq")&&o(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:b,found:k,spaceBefore:c,comment:l,hasNewline:h,anchor:w,tag:y,newlineAfterProp:v,end:$,start:E??$}}km.resolveProps=sR});var to=I(bm=>{"use strict";function La(e){if(!e)return null;switch(e.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(e.source.includes(`
|
|
69
|
+
`))return!0;if(e.end){for(let t of e.end)if(t.type==="newline")return!0}return!1;case"flow-collection":for(let t of e.items){for(let n of t.start)if(n.type==="newline")return!0;if(t.sep){for(let n of t.sep)if(n.type==="newline")return!0}if(La(t.key)||La(t.value))return!0}return!1;default:return!0}}bm.containsNewline=La});var Fa=I(Em=>{"use strict";var oR=to();function iR(e,t,n){if(t?.type==="flow-collection"){let r=t.end[0];r.indent===e&&(r.source==="]"||r.source==="}")&&oR.containsNewline(t)&&n(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Em.flowIndentCheck=iR});var Ma=I(Sm=>{"use strict";var Rm=_();function aR(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let s=typeof r=="function"?r:(o,i)=>o===i||Rm.isScalar(o)&&Rm.isScalar(i)&&o.value===i.value;return t.some(o=>s(o.key,n))}Sm.mapIncludes=aR});var Cm=I(Im=>{"use strict";var $m=dt(),cR=lt(),Am=rr(),dR=to(),Om=Fa(),uR=Ma(),jm="All mapping items must start at the same column";function lR({composeNode:e,composeEmptyNode:t},n,r,s,o){let i=o?.nodeClass??cR.YAMLMap,a=new i(n.schema);n.atRoot&&(n.atRoot=!1);let c=r.offset,d=null;for(let u of r.items){let{start:l,key:f,sep:h,value:g}=u,m=Am.resolveProps(l,{indicator:"explicit-key-ind",next:f??h?.[0],offset:c,onError:s,parentIndent:r.indent,startOnNewline:!0}),w=!m.found;if(w){if(f&&(f.type==="block-seq"?s(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&s(c,"BAD_INDENT",jm)),!m.anchor&&!m.tag&&!h){d=m.end,m.comment&&(a.comment?a.comment+=`
|
|
70
|
+
`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||dR.containsNewline(f))&&s(f??l[l.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==r.indent&&s(c,"BAD_INDENT",jm);n.atKey=!0;let y=m.end,v=f?e(n,f,m,s):t(n,y,l,null,m,s);n.schema.compat&&Om.flowIndentCheck(r.indent,f,s),n.atKey=!1,uR.mapIncludes(n,a.items,v)&&s(y,"DUPLICATE_KEY","Map keys must be unique");let b=Am.resolveProps(h??[],{indicator:"map-value-ind",next:g,offset:v.range[2],onError:s,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=b.end,b.found){w&&(g?.type==="block-map"&&!b.hasNewline&&s(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),n.options.strict&&m.start<b.found.offset-1024&&s(v.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let k=g?e(n,g,b,s):t(n,c,h,null,b,s);n.schema.compat&&Om.flowIndentCheck(r.indent,g,s),c=k.range[2];let E=new $m.Pair(v,k);n.options.keepSourceTokens&&(E.srcToken=u),a.items.push(E)}else{w&&s(v.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),b.comment&&(v.comment?v.comment+=`
|
|
71
|
+
`+b.comment:v.comment=b.comment);let k=new $m.Pair(v);n.options.keepSourceTokens&&(k.srcToken=u),a.items.push(k)}}return d&&d<c&&s(d,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,c,d??c],a}Im.resolveBlockMap=lR});var Pm=I(Dm=>{"use strict";var fR=ft(),pR=rr(),hR=Fa();function mR({composeNode:e,composeEmptyNode:t},n,r,s,o){let i=o?.nodeClass??fR.YAMLSeq,a=new i(n.schema);n.atRoot&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let c=r.offset,d=null;for(let{start:u,value:l}of r.items){let f=pR.resolveProps(u,{indicator:"seq-item-ind",next:l,offset:c,onError:s,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||l)l?.type==="block-seq"?s(f.end,"BAD_INDENT","All sequence items must start at the same column"):s(c,"MISSING_CHAR","Sequence item without - indicator");else{d=f.end,f.comment&&(a.comment=f.comment);continue}let h=l?e(n,l,f,s):t(n,f.end,u,null,f,s);n.schema.compat&&hR.flowIndentCheck(r.indent,l,s),c=h.range[2],a.items.push(h)}return a.range=[r.offset,c,d??c],a}Dm.resolveBlockSeq=mR});var on=I(Nm=>{"use strict";function gR(e,t,n,r){let s="";if(e){let o=!1,i="";for(let a of e){let{source:c,type:d}=a;switch(d){case"space":o=!0;break;case"comment":{n&&!o&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=c.substring(1)||" ";s?s+=i+u:s=u,i="";break}case"newline":s&&(i+=c),o=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${d} at node end`)}t+=c.length}}return{comment:s,offset:t}}Nm.resolveEnd=gR});var Fm=I(Lm=>{"use strict";var yR=_(),wR=dt(),Tm=lt(),vR=ft(),kR=on(),xm=rr(),bR=to(),ER=Ma(),za="Block collections are not allowed within flow collections",_a=e=>e&&(e.type==="block-map"||e.type==="block-seq");function RR({composeNode:e,composeEmptyNode:t},n,r,s,o){let i=r.start.source==="{",a=i?"flow map":"flow sequence",c=o?.nodeClass??(i?Tm.YAMLMap:vR.YAMLSeq),d=new c(n.schema);d.flow=!0;let u=n.atRoot;u&&(n.atRoot=!1),n.atKey&&(n.atKey=!1);let l=r.offset+r.start.source.length;for(let w=0;w<r.items.length;++w){let y=r.items[w],{start:v,key:b,sep:k,value:E}=y,S=xm.resolveProps(v,{flow:a,indicator:"explicit-key-ind",next:b??k?.[0],offset:l,onError:s,parentIndent:r.indent,startOnNewline:!1});if(!S.found){if(!S.anchor&&!S.tag&&!k&&!E){w===0&&S.comma?s(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):w<r.items.length-1&&s(S.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),S.comment&&(d.comment?d.comment+=`
|
|
72
|
+
`+S.comment:d.comment=S.comment),l=S.end;continue}!i&&n.options.strict&&bR.containsNewline(b)&&s(b,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(w===0)S.comma&&s(S.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(S.comma||s(S.start,"MISSING_CHAR",`Missing , between ${a} items`),S.comment){let $="";e:for(let j of v)switch(j.type){case"comma":case"space":break;case"comment":$=j.source.substring(1);break e;default:break e}if($){let j=d.items[d.items.length-1];yR.isPair(j)&&(j=j.value??j.key),j.comment?j.comment+=`
|
|
73
|
+
`+$:j.comment=$,S.comment=S.comment.substring($.length+1)}}if(!i&&!k&&!S.found){let $=E?e(n,E,S,s):t(n,S.end,k,null,S,s);d.items.push($),l=$.range[2],_a(E)&&s($.range,"BLOCK_IN_FLOW",za)}else{n.atKey=!0;let $=S.end,j=b?e(n,b,S,s):t(n,$,v,null,S,s);_a(b)&&s(j.range,"BLOCK_IN_FLOW",za),n.atKey=!1;let A=xm.resolveProps(k??[],{flow:a,indicator:"map-value-ind",next:E,offset:j.range[2],onError:s,parentIndent:r.indent,startOnNewline:!1});if(A.found){if(!i&&!S.found&&n.options.strict){if(k)for(let x of k){if(x===A.found)break;if(x.type==="newline"){s(x,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}S.start<A.found.offset-1024&&s(A.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else E&&("source"in E&&E.source?.[0]===":"?s(E,"MISSING_CHAR",`Missing space after : in ${a}`):s(A.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let P=E?e(n,E,A,s):A.found?t(n,A.end,k,null,A,s):null;P?_a(E)&&s(P.range,"BLOCK_IN_FLOW",za):A.comment&&(j.comment?j.comment+=`
|
|
74
|
+
`+A.comment:j.comment=A.comment);let D=new wR.Pair(j,P);if(n.options.keepSourceTokens&&(D.srcToken=y),i){let x=d;ER.mapIncludes(n,x.items,j)&&s($,"DUPLICATE_KEY","Map keys must be unique"),x.items.push(D)}else{let x=new Tm.YAMLMap(n.schema);x.flow=!0,x.items.push(D);let G=(P??j).range;x.range=[j.range[0],G[1],G[2]],d.items.push(x)}l=P?P.range[2]:A.end}}let f=i?"}":"]",[h,...g]=r.end,m=l;if(h?.source===f)m=h.offset+h.source.length;else{let w=a[0].toUpperCase()+a.substring(1),y=u?`${w} must end with a ${f}`:`${w} in block collection must be sufficiently indented and end with a ${f}`;s(l,u?"MISSING_CHAR":"BAD_INDENT",y),h&&h.source.length!==1&&g.unshift(h)}if(g.length>0){let w=kR.resolveEnd(g,m,n.options.strict,s);w.comment&&(d.comment?d.comment+=`
|
|
75
|
+
`+w.comment:d.comment=w.comment),d.range=[r.offset,m,w.offset]}else d.range=[r.offset,m,m];return d}Lm.resolveFlowCollection=RR});var zm=I(Mm=>{"use strict";var SR=_(),$R=X(),AR=lt(),OR=ft(),jR=Cm(),IR=Pm(),CR=Fm();function qa(e,t,n,r,s,o){let i=n.type==="block-map"?jR.resolveBlockMap(e,t,n,r,o):n.type==="block-seq"?IR.resolveBlockSeq(e,t,n,r,o):CR.resolveFlowCollection(e,t,n,r,o),a=i.constructor;return s==="!"||s===a.tagName?(i.tag=a.tagName,i):(s&&(i.tag=s),i)}function DR(e,t,n,r,s){let o=r.tag,i=o?t.directives.tagName(o.source,f=>s(o,"TAG_RESOLVE_FAILED",f)):null;if(n.type==="block-seq"){let{anchor:f,newlineAfterProp:h}=r,g=f&&o?f.offset>o.offset?f:o:f??o;g&&(!h||h.offset<g.offset)&&s(g,"MISSING_CHAR","Missing newline after block sequence props")}let a=n.type==="block-map"?"map":n.type==="block-seq"?"seq":n.start.source==="{"?"map":"seq";if(!o||!i||i==="!"||i===AR.YAMLMap.tagName&&a==="map"||i===OR.YAMLSeq.tagName&&a==="seq")return qa(e,t,n,s,i);let c=t.schema.tags.find(f=>f.tag===i&&f.collection===a);if(!c){let f=t.schema.knownTags[i];if(f?.collection===a)t.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?s(o,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):s(o,"TAG_RESOLVE_FAILED",`Unresolved tag: ${i}`,!0),qa(e,t,n,s,i)}let d=qa(e,t,n,s,i,c),u=c.resolve?.(d,f=>s(o,"TAG_RESOLVE_FAILED",f),t.options)??d,l=SR.isNode(u)?u:new $R.Scalar(u);return l.range=d.range,l.tag=i,c?.format&&(l.format=c.format),l}Mm.composeCollection=DR});var Ua=I(_m=>{"use strict";var Ba=X();function PR(e,t,n){let r=t.offset,s=NR(t,e.options.strict,n);if(!s)return{value:"",type:null,comment:"",range:[r,r,r]};let o=s.mode===">"?Ba.Scalar.BLOCK_FOLDED:Ba.Scalar.BLOCK_LITERAL,i=t.source?TR(t.source):[],a=i.length;for(let m=i.length-1;m>=0;--m){let w=i[m][1];if(w===""||w==="\r")a=m;else break}if(a===0){let m=s.chomp==="+"&&i.length>0?`
|
|
76
|
+
`.repeat(Math.max(1,i.length-1)):"",w=r+s.length;return t.source&&(w+=t.source.length),{value:m,type:o,comment:s.comment,range:[r,w,w]}}let c=t.indent+s.indent,d=t.offset+s.length,u=0;for(let m=0;m<a;++m){let[w,y]=i[m];if(y===""||y==="\r")s.indent===0&&w.length>c&&(c=w.length);else{w.length<c&&n(d+w.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),s.indent===0&&(c=w.length),u=m,c===0&&!e.atRoot&&n(d,"BAD_INDENT","Block scalar values in collections must be indented");break}d+=w.length+y.length+1}for(let m=i.length-1;m>=a;--m)i[m][0].length>c&&(a=m+1);let l="",f="",h=!1;for(let m=0;m<u;++m)l+=i[m][0].slice(c)+`
|
|
77
|
+
`;for(let m=u;m<a;++m){let[w,y]=i[m];d+=w.length+y.length+1;let v=y[y.length-1]==="\r";if(v&&(y=y.slice(0,-1)),y&&w.length<c){let k=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;n(d-y.length-(v?2:1),"BAD_INDENT",k),w=""}o===Ba.Scalar.BLOCK_LITERAL?(l+=f+w.slice(c)+y,f=`
|
|
78
|
+
`):w.length>c||y[0]===" "?(f===" "?f=`
|
|
79
|
+
`:!h&&f===`
|
|
80
80
|
`&&(f=`
|
|
81
81
|
|
|
82
|
-
`),
|
|
83
|
-
`,
|
|
84
|
-
`?
|
|
82
|
+
`),l+=f+w.slice(c)+y,f=`
|
|
83
|
+
`,h=!0):y===""?f===`
|
|
84
|
+
`?l+=`
|
|
85
85
|
`:f=`
|
|
86
|
-
`:(
|
|
87
|
-
`+
|
|
88
|
-
`&&(
|
|
89
|
-
`);break;default:
|
|
90
|
-
`}let
|
|
91
|
-
`?i
|
|
92
|
-
`:(i
|
|
86
|
+
`:(l+=f+y,f=" ",h=!1)}switch(s.chomp){case"-":break;case"+":for(let m=a;m<i.length;++m)l+=`
|
|
87
|
+
`+i[m][0].slice(c);l[l.length-1]!==`
|
|
88
|
+
`&&(l+=`
|
|
89
|
+
`);break;default:l+=`
|
|
90
|
+
`}let g=r+s.length+t.source.length;return{value:l,type:o,comment:s.comment,range:[r,g,g]}}function NR({offset:e,props:t},n,r){if(t[0].type!=="block-scalar-header")return r(t[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:s}=t[0],o=s[0],i=0,a="",c=-1;for(let f=1;f<s.length;++f){let h=s[f];if(!a&&(h==="-"||h==="+"))a=h;else{let g=Number(h);!i&&g?i=g:c===-1&&(c=e+f)}}c!==-1&&r(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${s}`);let d=!1,u="",l=s.length;for(let f=1;f<t.length;++f){let h=t[f];switch(h.type){case"space":d=!0;case"newline":l+=h.source.length;break;case"comment":n&&!d&&r(h,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),l+=h.source.length,u=h.source.substring(1);break;case"error":r(h,"UNEXPECTED_TOKEN",h.message),l+=h.source.length;break;default:{let g=`Unexpected token in block scalar header: ${h.type}`;r(h,"UNEXPECTED_TOKEN",g);let m=h.source;m&&typeof m=="string"&&(l+=m.length)}}}return{mode:o,indent:i,chomp:a,comment:u,length:l}}function TR(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),o=[r?.[1]?[r[1],n.slice(r[1].length)]:["",n]];for(let i=1;i<t.length;i+=2)o.push([t[i],t[i+1]]);return o}_m.resolveBlockScalar=PR});var Wa=I(Bm=>{"use strict";var Ka=X(),xR=on();function LR(e,t,n){let{offset:r,type:s,source:o,end:i}=e,a,c,d=(f,h,g)=>n(r+f,h,g);switch(s){case"scalar":a=Ka.Scalar.PLAIN,c=FR(o,d);break;case"single-quoted-scalar":a=Ka.Scalar.QUOTE_SINGLE,c=MR(o,d);break;case"double-quoted-scalar":a=Ka.Scalar.QUOTE_DOUBLE,c=zR(o,d);break;default:return n(e,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${s}`),{value:"",type:null,comment:"",range:[r,r+o.length,r+o.length]}}let u=r+o.length,l=xR.resolveEnd(i,u,t,n);return{value:c,type:a,comment:l.comment,range:[r,u,l.offset]}}function FR(e,t){let n="";switch(e[0]){case" ":n="a tab character";break;case",":n="flow indicator character ,";break;case"%":n="directive indicator character %";break;case"|":case">":{n=`block scalar indicator ${e[0]}`;break}case"@":case"`":{n=`reserved character ${e[0]}`;break}}return n&&t(0,"BAD_SCALAR_START",`Plain value cannot start with ${n}`),qm(e)}function MR(e,t){return(e[e.length-1]!=="'"||e.length===1)&&t(e.length,"MISSING_CHAR","Missing closing 'quote"),qm(e.slice(1,-1)).replace(/''/g,"'")}function qm(e){let t=/(.*?)\r?\n/sy,n=t.exec(e);if(!n)return e;let r,s;try{r=new RegExp("(?<![ ])[ ]+$"),s=new RegExp("^[ ]+|(?<![ ])[ ]+$","g")}catch{r=/[ \t]+$/,s=/^[ \t]+|[ \t]+$/g}let o=n[1].replace(r,""),i=" ",a=t.lastIndex;for(;n=t.exec(e);){let d=n[1].replace(s,"");d===""?i===`
|
|
91
|
+
`?o+=i:i=`
|
|
92
|
+
`:(o+=i+d,i=" "),a=t.lastIndex}let c=/[ \t]*(.*)/sy;return c.lastIndex=a,n=c.exec(e),o+i+(n?.[1]??"")}function zR(e,t){let n="";for(let r=1;r<e.length-1;++r){let s=e[r];if(!(s==="\r"&&e[r+1]===`
|
|
93
93
|
`))if(s===`
|
|
94
|
-
`){let{fold:
|
|
95
|
-
`)for(
|
|
96
|
-
`)for(
|
|
97
|
-
`&&!(
|
|
98
|
-
`)&&(n+=r>
|
|
94
|
+
`){let{fold:o,offset:i}=_R(e,r);n+=o,r=i}else if(s==="\\"){let o=e[++r],i=qR[o];if(i)n+=i;else if(o===`
|
|
95
|
+
`)for(o=e[r+1];o===" "||o===" ";)o=e[++r+1];else if(o==="\r"&&e[r+1]===`
|
|
96
|
+
`)for(o=e[++r+1];o===" "||o===" ";)o=e[++r+1];else if(o==="x"||o==="u"||o==="U"){let a=o==="x"?2:o==="u"?4:8;n+=BR(e,r+1,a,t),r+=a}else{let a=e.substr(r-1,2);t(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),n+=a}}else if(s===" "||s===" "){let o=r,i=e[r+1];for(;i===" "||i===" ";)i=e[++r+1];i!==`
|
|
97
|
+
`&&!(i==="\r"&&e[r+2]===`
|
|
98
|
+
`)&&(n+=r>o?e.slice(o,r+1):s)}else n+=s}return(e[e.length-1]!=='"'||e.length===1)&&t(e.length,"MISSING_CHAR",'Missing closing "quote'),n}function _R(e,t){let n="",r=e[t+1];for(;(r===" "||r===" "||r===`
|
|
99
99
|
`||r==="\r")&&!(r==="\r"&&e[t+2]!==`
|
|
100
100
|
`);)r===`
|
|
101
101
|
`&&(n+=`
|
|
102
|
-
`),t+=1,r=e[t+1];return n||(n=" "),{fold:n,offset:t}}var
|
|
103
|
-
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
102
|
+
`),t+=1,r=e[t+1];return n||(n=" "),{fold:n,offset:t}}var qR={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
103
|
+
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function BR(e,t,n,r){let s=e.substr(t,n),i=s.length===n&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;try{return String.fromCodePoint(i)}catch{let a=e.substr(t-2,n+2);return r(t-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}Bm.resolveFlowScalar=LR});var Wm=I(Km=>{"use strict";var Dt=_(),Um=X(),UR=Ua(),KR=Wa();function WR(e,t,n,r){let{value:s,type:o,comment:i,range:a}=t.type==="block-scalar"?UR.resolveBlockScalar(e,t,r):KR.resolveFlowScalar(t,e.options.strict,r),c=n?e.directives.tagName(n.source,l=>r(n,"TAG_RESOLVE_FAILED",l)):null,d;e.options.stringKeys&&e.atKey?d=e.schema[Dt.SCALAR]:c?d=VR(e.schema,s,c,n,r):t.type==="scalar"?d=HR(e,s,t,r):d=e.schema[Dt.SCALAR];let u;try{let l=d.resolve(s,f=>r(n??t,"TAG_RESOLVE_FAILED",f),e.options);u=Dt.isScalar(l)?l:new Um.Scalar(l)}catch(l){let f=l instanceof Error?l.message:String(l);r(n??t,"TAG_RESOLVE_FAILED",f),u=new Um.Scalar(s)}return u.range=a,u.source=s,o&&(u.type=o),c&&(u.tag=c),d.format&&(u.format=d.format),i&&(u.comment=i),u}function VR(e,t,n,r,s){if(n==="!")return e[Dt.SCALAR];let o=[];for(let a of e.tags)if(!a.collection&&a.tag===n)if(a.default&&a.test)o.push(a);else return a;for(let a of o)if(a.test?.test(t))return a;let i=e.knownTags[n];return i&&!i.collection?(e.tags.push(Object.assign({},i,{default:!1,test:void 0})),i):(s(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${n}`,n!=="tag:yaml.org,2002:str"),e[Dt.SCALAR])}function HR({atKey:e,directives:t,schema:n},r,s,o){let i=n.tags.find(a=>(a.default===!0||e&&a.default==="key")&&a.test?.test(r))||n[Dt.SCALAR];if(n.compat){let a=n.compat.find(c=>c.default&&c.test?.test(r))??n[Dt.SCALAR];if(i.tag!==a.tag){let c=t.tagString(i.tag),d=t.tagString(a.tag),u=`Value may be parsed as either ${c} or ${d}`;o(s,"TAG_RESOLVE_FAILED",u,!0)}}return i}Km.composeScalar=WR});var Hm=I(Vm=>{"use strict";function JR(e,t,n){if(t){n??(n=t.length);for(let r=n-1;r>=0;--r){let s=t[r];switch(s.type){case"space":case"comment":case"newline":e-=s.source.length;continue}for(s=t[++r];s?.type==="space";)e+=s.source.length,s=t[++r];break}}return e}Vm.emptyScalarPosition=JR});var Gm=I(Ha=>{"use strict";var YR=Fn(),GR=_(),QR=zm(),Jm=Wm(),XR=on(),ZR=Hm(),eS={composeNode:Ym,composeEmptyNode:Va};function Ym(e,t,n,r){let s=e.atKey,{spaceBefore:o,comment:i,anchor:a,tag:c}=n,d,u=!0;switch(t.type){case"alias":d=tS(e,t,r),(a||c)&&r(t,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":d=Jm.composeScalar(e,t,c,r),a&&(d.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{d=QR.composeCollection(eS,e,t,n,r),a&&(d.anchor=a.source.substring(1))}catch(l){let f=l instanceof Error?l.message:String(l);r(t,"RESOURCE_EXHAUSTION",f)}break;default:{let l=t.type==="error"?t.message:`Unsupported token (type: ${t.type})`;r(t,"UNEXPECTED_TOKEN",l),u=!1}}return d??(d=Va(e,t.offset,void 0,null,n,r)),a&&d.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),s&&e.options.stringKeys&&(!GR.isScalar(d)||typeof d.value!="string"||d.tag&&d.tag!=="tag:yaml.org,2002:str")&&r(c??t,"NON_STRING_KEY","With stringKeys, all keys must be strings"),o&&(d.spaceBefore=!0),i&&(t.type==="scalar"&&t.source===""?d.comment=i:d.commentBefore=i),e.options.keepSourceTokens&&u&&(d.srcToken=t),d}function Va(e,t,n,r,{spaceBefore:s,comment:o,anchor:i,tag:a,end:c},d){let u={type:"scalar",offset:ZR.emptyScalarPosition(t,n,r),indent:-1,source:""},l=Jm.composeScalar(e,u,a,d);return i&&(l.anchor=i.source.substring(1),l.anchor===""&&d(i,"BAD_ALIAS","Anchor cannot be an empty string")),s&&(l.spaceBefore=!0),o&&(l.comment=o,l.range[2]=c),l}function tS({options:e},{offset:t,source:n,end:r},s){let o=new YR.Alias(n.substring(1));o.source===""&&s(t,"BAD_ALIAS","Alias cannot be an empty string"),o.source.endsWith(":")&&s(t+n.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let i=t+n.length,a=XR.resolveEnd(r,i,e.strict,s);return o.range=[t,i,a.offset],a.comment&&(o.comment=a.comment),o}Ha.composeEmptyNode=Va;Ha.composeNode=Ym});var Zm=I(Xm=>{"use strict";var nS=Zn(),Qm=Gm(),rS=on(),sS=rr();function oS(e,t,{offset:n,start:r,value:s,end:o},i){let a=Object.assign({_directives:t},e),c=new nS.Document(void 0,a),d={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=sS.resolveProps(r,{indicator:"doc-start",next:s??o?.[0],offset:n,onError:i,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,s&&(s.type==="block-map"||s.type==="block-seq")&&!u.hasNewline&&i(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=s?Qm.composeNode(d,s,u,i):Qm.composeEmptyNode(d,u.end,r,null,u,i);let l=c.contents.range[2],f=rS.resolveEnd(o,l,!1,i);return f.comment&&(c.comment=f.comment),c.range=[n,l,f.offset],c}Xm.composeDoc=oS});var Ya=I(ng=>{"use strict";var iS=wr("process"),aS=Ti(),cS=Zn(),sr=nr(),eg=_(),dS=Zm(),uS=on();function or(e){if(typeof e=="number")return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n=="string"?n.length:1)]}function tg(e){let t="",n=!1,r=!1;for(let s=0;s<e.length;++s){let o=e[s];switch(o[0]){case"#":t+=(t===""?"":r?`
|
|
104
104
|
|
|
105
105
|
`:`
|
|
106
|
-
`)+(
|
|
107
|
-
${r}`:r;else if(s||t.directives.docStart||!
|
|
108
|
-
${a}`:r}else{let o
|
|
109
|
-
${
|
|
110
|
-
${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new
|
|
111
|
-
`}];switch(a[0]){case"|":case">":{let
|
|
112
|
-
`),u=a.substring(0,
|
|
113
|
-
`,f=[{type:"block-scalar-header",offset:
|
|
114
|
-
`}),{type:"block-scalar",offset:
|
|
106
|
+
`)+(o.substring(1)||" "),n=!0,r=!1;break;case"%":e[s+1]?.[0]!=="#"&&(s+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var Ja=class{constructor(t={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(n,r,s,o)=>{let i=or(n);o?this.warnings.push(new sr.YAMLWarning(i,r,s)):this.errors.push(new sr.YAMLParseError(i,r,s))},this.directives=new aS.Directives({version:t.version||"1.2"}),this.options=t}decorate(t,n){let{comment:r,afterEmptyLine:s}=tg(this.prelude);if(r){let o=t.contents;if(n)t.comment=t.comment?`${t.comment}
|
|
107
|
+
${r}`:r;else if(s||t.directives.docStart||!o)t.commentBefore=r;else if(eg.isCollection(o)&&!o.flow&&o.items.length>0){let i=o.items[0];eg.isPair(i)&&(i=i.key);let a=i.commentBefore;i.commentBefore=a?`${r}
|
|
108
|
+
${a}`:r}else{let i=o.commentBefore;o.commentBefore=i?`${r}
|
|
109
|
+
${i}`:r}}if(n){for(let o=0;o<this.errors.length;++o)t.errors.push(this.errors[o]);for(let o=0;o<this.warnings.length;++o)t.warnings.push(this.warnings[o])}else t.errors=this.errors,t.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:tg(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(t,n=!1,r=-1){for(let s of t)yield*this.next(s);yield*this.end(n,r)}*next(t){switch(iS.env.LOG_STREAM&&console.dir(t,{depth:null}),t.type){case"directive":this.directives.add(t.source,(n,r,s)=>{let o=or(t);o[0]+=n,this.onError(o,"BAD_DIRECTIVE",r,s)}),this.prelude.push(t.source),this.atDirectives=!0;break;case"document":{let n=dS.composeDoc(this.options,this.directives,t,this.onError);this.atDirectives&&!n.directives.docStart&&this.onError(t,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(n,!1),this.doc&&(yield this.doc),this.doc=n,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(t.source);break;case"error":{let n=t.source?`${t.message}: ${JSON.stringify(t.source)}`:t.message,r=new sr.YAMLParseError(or(t),"UNEXPECTED_TOKEN",n);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new sr.YAMLParseError(or(t),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let n=uS.resolveEnd(t.end,t.offset+t.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),n.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
|
|
110
|
+
${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.push(new sr.YAMLParseError(or(t),"UNEXPECTED_TOKEN",`Unsupported token ${t.type}`))}}*end(t=!1,n=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(t){let r=Object.assign({_directives:this.directives},this.options),s=new cS.Document(void 0,r);this.atDirectives&&this.onError(n,"MISSING_CHAR","Missing directives-end indicator line"),s.range=[0,n,n],this.decorate(s,!1),yield s}}};ng.Composer=Ja});var og=I(no=>{"use strict";var lS=Ua(),fS=Wa(),pS=nr(),rg=Bn();function hS(e,t=!0,n){if(e){let r=(s,o,i)=>{let a=typeof s=="number"?s:Array.isArray(s)?s[0]:s.offset;if(n)n(a,o,i);else throw new pS.YAMLParseError([a,a+1],o,i)};switch(e.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return fS.resolveFlowScalar(e,t,r);case"block-scalar":return lS.resolveBlockScalar({options:{strict:t}},e,r)}}return null}function mS(e,t){let{implicitKey:n=!1,indent:r,inFlow:s=!1,offset:o=-1,type:i="PLAIN"}=t,a=rg.stringifyString({type:i,value:e},{implicitKey:n,indent:r>0?" ".repeat(r):"",inFlow:s,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:"newline",offset:-1,indent:r,source:`
|
|
111
|
+
`}];switch(a[0]){case"|":case">":{let d=a.indexOf(`
|
|
112
|
+
`),u=a.substring(0,d),l=a.substring(d+1)+`
|
|
113
|
+
`,f=[{type:"block-scalar-header",offset:o,indent:r,source:u}];return sg(f,c)||f.push({type:"newline",offset:-1,indent:r,source:`
|
|
114
|
+
`}),{type:"block-scalar",offset:o,indent:r,props:f,source:l}}case'"':return{type:"double-quoted-scalar",offset:o,indent:r,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:o,indent:r,source:a,end:c};default:return{type:"scalar",offset:o,indent:r,source:a,end:c}}}function gS(e,t,n={}){let{afterKey:r=!1,implicitKey:s=!1,inFlow:o=!1,type:i}=n,a="indent"in e?e.indent:null;if(r&&typeof a=="number"&&(a+=2),!i)switch(e.type){case"single-quoted-scalar":i="QUOTE_SINGLE";break;case"double-quoted-scalar":i="QUOTE_DOUBLE";break;case"block-scalar":{let d=e.props[0];if(d.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i=d.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:i="PLAIN"}let c=rg.stringifyString({type:i,value:t},{implicitKey:s||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:o,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":yS(e,c);break;case'"':Ga(e,c,"double-quoted-scalar");break;case"'":Ga(e,c,"single-quoted-scalar");break;default:Ga(e,c,"scalar")}}function yS(e,t){let n=t.indexOf(`
|
|
115
115
|
`),r=t.substring(0,n),s=t.substring(n+1)+`
|
|
116
|
-
`;if(e.type==="block-scalar"){let
|
|
117
|
-
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:
|
|
118
|
-
`};delete e.items,Object.assign(e,{type:n,source:t,end:[s]});break}default:{let r="indent"in e?e.indent:-1,s="end"in e&&Array.isArray(e.end)?e.end.filter(
|
|
116
|
+
`;if(e.type==="block-scalar"){let o=e.props[0];if(o.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o.source=r,e.source=s}else{let{offset:o}=e,i="indent"in e?e.indent:-1,a=[{type:"block-scalar-header",offset:o,indent:i,source:r}];sg(a,"end"in e?e.end:void 0)||a.push({type:"newline",offset:-1,indent:i,source:`
|
|
117
|
+
`});for(let c of Object.keys(e))c!=="type"&&c!=="offset"&&delete e[c];Object.assign(e,{type:"block-scalar",indent:i,props:a,source:s})}}function sg(e,t){if(t)for(let n of t)switch(n.type){case"space":case"comment":e.push(n);break;case"newline":return e.push(n),!0}return!1}function Ga(e,t,n){switch(e.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":e.type=n,e.source=t;break;case"block-scalar":{let r=e.props.slice(1),s=t.length;e.props[0].type==="block-scalar-header"&&(s-=e.props[0].source.length);for(let o of r)o.offset+=s;delete e.props,Object.assign(e,{type:n,source:t,end:r});break}case"block-map":case"block-seq":{let s={type:"newline",offset:e.offset+t.length,indent:e.indent,source:`
|
|
118
|
+
`};delete e.items,Object.assign(e,{type:n,source:t,end:[s]});break}default:{let r="indent"in e?e.indent:-1,s="end"in e&&Array.isArray(e.end)?e.end.filter(o=>o.type==="space"||o.type==="comment"||o.type==="newline"):[];for(let o of Object.keys(e))o!=="type"&&o!=="offset"&&delete e[o];Object.assign(e,{type:n,indent:r,source:t,end:s})}}}no.createScalarToken=mS;no.resolveAsScalar=hS;no.setScalarValue=gS});var ag=I(ig=>{"use strict";var wS=e=>"type"in e?so(e):ro(e);function so(e){switch(e.type){case"block-scalar":{let t="";for(let n of e.props)t+=so(n);return t+e.source}case"block-map":case"block-seq":{let t="";for(let n of e.items)t+=ro(n);return t}case"flow-collection":{let t=e.start.source;for(let n of e.items)t+=ro(n);for(let n of e.end)t+=n.source;return t}case"document":{let t=ro(e);if(e.end)for(let n of e.end)t+=n.source;return t}default:{let t=e.source;if("end"in e&&e.end)for(let n of e.end)t+=n.source;return t}}}function ro({start:e,key:t,sep:n,value:r}){let s="";for(let o of e)s+=o.source;if(t&&(s+=so(t)),n)for(let o of n)s+=o.source;return r&&(s+=so(r)),s}ig.stringify=wS});var lg=I(ug=>{"use strict";var Qa=Symbol("break visit"),vS=Symbol("skip children"),cg=Symbol("remove item");function Pt(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),dg(Object.freeze([]),e,t)}Pt.BREAK=Qa;Pt.SKIP=vS;Pt.REMOVE=cg;Pt.itemAtPath=(e,t)=>{let n=e;for(let[r,s]of t){let o=n?.[r];if(o&&"items"in o)n=o.items[s];else return}return n};Pt.parentCollection=(e,t)=>{let n=Pt.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],s=n?.[r];if(s&&"items"in s)return s;throw new Error("Parent collection not found")};function dg(e,t,n){let r=n(t,e);if(typeof r=="symbol")return r;for(let s of["key","value"]){let o=t[s];if(o&&"items"in o){for(let i=0;i<o.items.length;++i){let a=dg(Object.freeze(e.concat([[s,i]])),o.items[i],n);if(typeof a=="number")i=a-1;else{if(a===Qa)return Qa;a===cg&&(o.items.splice(i,1),i-=1)}}typeof r=="function"&&s==="key"&&(r=r(t,e))}}return typeof r=="function"?r(t,e):r}ug.visit=Pt});var oo=I(ye=>{"use strict";var Xa=og(),kS=ag(),bS=lg(),Za="\uFEFF",ec="",tc="",nc="",ES=e=>!!e&&"items"in e,RS=e=>!!e&&(e.type==="scalar"||e.type==="single-quoted-scalar"||e.type==="double-quoted-scalar"||e.type==="block-scalar");function SS(e){switch(e){case Za:return"<BOM>";case ec:return"<DOC>";case tc:return"<FLOW_END>";case nc:return"<SCALAR>";default:return JSON.stringify(e)}}function $S(e){switch(e){case Za:return"byte-order-mark";case ec:return"doc-mode";case tc:return"flow-error-end";case nc:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
119
119
|
`:case`\r
|
|
120
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}
|
|
121
|
-
`:case"\r":case" ":return!0;default:return!1}}var
|
|
122
|
-
\r `),
|
|
120
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(e[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}ye.createScalarToken=Xa.createScalarToken;ye.resolveAsScalar=Xa.resolveAsScalar;ye.setScalarValue=Xa.setScalarValue;ye.stringify=kS.stringify;ye.visit=bS.visit;ye.BOM=Za;ye.DOCUMENT=ec;ye.FLOW_END=tc;ye.SCALAR=nc;ye.isCollection=ES;ye.isScalar=RS;ye.prettyToken=SS;ye.tokenType=$S});var oc=I(pg=>{"use strict";var ir=oo();function Oe(e){switch(e){case void 0:case" ":case`
|
|
121
|
+
`:case"\r":case" ":return!0;default:return!1}}var fg=new Set("0123456789ABCDEFabcdef"),AS=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),io=new Set(",[]{}"),OS=new Set(` ,[]{}
|
|
122
|
+
\r `),rc=e=>!e||OS.has(e),sc=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(t,n=!1){if(t){if(typeof t!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+t:t,this.lineEndPos=null}this.atEnd=!n;let r=this.next??"stream";for(;r&&(n||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let t=this.pos,n=this.buffer[t];for(;n===" "||n===" ";)n=this.buffer[++t];return!n||n==="#"||n===`
|
|
123
123
|
`?!0:n==="\r"?this.buffer[t+1]===`
|
|
124
124
|
`:!1}charAt(t){return this.buffer[this.pos+t]}continueScalar(t){let n=this.buffer[t];if(this.indentNext>0){let r=0;for(;n===" ";)n=this.buffer[++r+t];if(n==="\r"){let s=this.buffer[r+t+1];if(s===`
|
|
125
125
|
`||!s&&!this.atEnd)return t+r+1}return n===`
|
|
126
|
-
`||r>=this.indentNext||!n&&!this.atEnd?t+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&
|
|
127
|
-
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===
|
|
128
|
-
`,this.pos);if(s!==-1){for(;s!==-1;){let
|
|
129
|
-
`,
|
|
130
|
-
`:t=
|
|
131
|
-
`)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=n:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let
|
|
132
|
-
`,
|
|
133
|
-
`;)r=this.buffer[++s];t=s-1}else if(!this.blockScalarKeep)do{let
|
|
134
|
-
`&&
|
|
126
|
+
`||r>=this.indentNext||!n&&!this.atEnd?t+r:-1}if(n==="-"||n==="."){let r=this.buffer.substr(t,3);if((r==="---"||r==="...")&&Oe(this.buffer[t+3]))return-1}return t}getLine(){let t=this.lineEndPos;return(typeof t!="number"||t!==-1&&t<this.pos)&&(t=this.buffer.indexOf(`
|
|
127
|
+
`,this.pos),this.lineEndPos=t),t===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[t-1]==="\r"&&(t-=1),this.buffer.substring(this.pos,t))}hasChars(t){return this.pos+t<=this.buffer.length}setNext(t){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=t,null}peek(t){return this.buffer.substr(this.pos,t)}*parseNext(t){switch(t){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let t=this.getLine();if(t===null)return this.setNext("stream");if(t[0]===ir.BOM&&(yield*this.pushCount(1),t=t.substring(1)),t[0]==="%"){let n=t.length,r=t.indexOf("#");for(;r!==-1;){let o=t[r-1];if(o===" "||o===" "){n=r-1;break}else r=t.indexOf("#",r+1)}for(;;){let o=t[n-1];if(o===" "||o===" ")n-=1;else break}let s=(yield*this.pushCount(n))+(yield*this.pushSpaces(!0));return yield*this.pushCount(t.length-s),this.pushNewline(),"stream"}if(this.atLineEnd()){let n=yield*this.pushSpaces(!0);return yield*this.pushCount(t.length-n),yield*this.pushNewline(),"stream"}return yield ir.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let t=this.charAt(0);if(!t&&!this.atEnd)return this.setNext("line-start");if(t==="-"||t==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let n=this.peek(3);if((n==="---"||n==="...")&&Oe(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,n==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Oe(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[t,n]=this.peek(2);if(!n&&!this.atEnd)return this.setNext("block-start");if((t==="-"||t==="?"||t===":")&&Oe(n)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let t=this.getLine();if(t===null)return this.setNext("doc");let n=yield*this.pushIndicators();switch(t[n]){case"#":yield*this.pushCount(t.length-n);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(rc),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return n+=yield*this.parseBlockScalarHeader(),n+=yield*this.pushSpaces(!0),yield*this.pushCount(t.length-n),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let t,n,r=-1;do t=yield*this.pushNewline(),t>0?(n=yield*this.pushSpaces(!1),this.indentValue=r=n):n=0,n+=yield*this.pushSpaces(!0);while(t+n>0);let s=this.getLine();if(s===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&s[0]!=="#"||r===0&&(s.startsWith("---")||s.startsWith("..."))&&Oe(s[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(s[0]==="]"||s[0]==="}")))return this.flowLevel=0,yield ir.FLOW_END,yield*this.parseLineStart();let o=0;for(;s[o]===",";)o+=yield*this.pushCount(1),o+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(o+=yield*this.pushIndicators(),s[o]){case void 0:return"flow";case"#":return yield*this.pushCount(s.length-o),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(rc),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let i=this.charAt(1);if(this.flowKey||Oe(i)||i===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let t=this.charAt(0),n=this.buffer.indexOf(t,this.pos+1);if(t==="'")for(;n!==-1&&this.buffer[n+1]==="'";)n=this.buffer.indexOf("'",n+2);else for(;n!==-1;){let o=0;for(;this.buffer[n-1-o]==="\\";)o+=1;if(o%2===0)break;n=this.buffer.indexOf('"',n+1)}let r=this.buffer.substring(0,n),s=r.indexOf(`
|
|
128
|
+
`,this.pos);if(s!==-1){for(;s!==-1;){let o=this.continueScalar(s+1);if(o===-1)break;s=r.indexOf(`
|
|
129
|
+
`,o)}s!==-1&&(n=s-(r[s-1]==="\r"?2:1))}if(n===-1){if(!this.atEnd)return this.setNext("quoted-scalar");n=this.buffer.length}return yield*this.pushToIndex(n+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let t=this.pos;for(;;){let n=this.buffer[++t];if(n==="+")this.blockScalarKeep=!0;else if(n>"0"&&n<="9")this.blockScalarIndent=Number(n)-1;else if(n!=="-")break}return yield*this.pushUntil(n=>Oe(n)||n==="#")}*parseBlockScalar(){let t=this.pos-1,n=0,r;e:for(let o=this.pos;r=this.buffer[o];++o)switch(r){case" ":n+=1;break;case`
|
|
130
|
+
`:t=o,n=0;break;case"\r":{let i=this.buffer[o+1];if(!i&&!this.atEnd)return this.setNext("block-scalar");if(i===`
|
|
131
|
+
`)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(n>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=n:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let o=this.continueScalar(t+1);if(o===-1)break;t=this.buffer.indexOf(`
|
|
132
|
+
`,o)}while(t!==-1);if(t===-1){if(!this.atEnd)return this.setNext("block-scalar");t=this.buffer.length}}let s=t+1;for(r=this.buffer[s];r===" ";)r=this.buffer[++s];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
|
|
133
|
+
`;)r=this.buffer[++s];t=s-1}else if(!this.blockScalarKeep)do{let o=t-1,i=this.buffer[o];i==="\r"&&(i=this.buffer[--o]);let a=o;for(;i===" ";)i=this.buffer[--o];if(i===`
|
|
134
|
+
`&&o>=this.pos&&o+1+n>a)t=o;else break}while(!0);return yield ir.SCALAR,yield*this.pushToIndex(t+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let t=this.flowLevel>0,n=this.pos-1,r=this.pos-1,s;for(;s=this.buffer[++r];)if(s===":"){let o=this.buffer[r+1];if(Oe(o)||t&&io.has(o))break;n=r}else if(Oe(s)){let o=this.buffer[r+1];if(s==="\r"&&(o===`
|
|
135
135
|
`?(r+=1,s=`
|
|
136
|
-
`,
|
|
137
|
-
`){let
|
|
136
|
+
`,o=this.buffer[r+1]):n=r),o==="#"||t&&io.has(o))break;if(s===`
|
|
137
|
+
`){let i=this.continueScalar(r+1);if(i===-1)break;r=Math.max(r,i-2)}}else{if(t&&io.has(s))break;n=r}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield ir.SCALAR,yield*this.pushToIndex(n+1,!0),t?"flow":"doc")}*pushCount(t){return t>0?(yield this.buffer.substr(this.pos,t),this.pos+=t,t):0}*pushToIndex(t,n){let r=this.buffer.slice(this.pos,t);return r?(yield r,this.pos+=r.length,r.length):(n&&(yield""),0)}*pushIndicators(){let t=0;e:for(;;){switch(this.charAt(0)){case"!":t+=yield*this.pushTag(),t+=yield*this.pushSpaces(!0);continue e;case"&":t+=yield*this.pushUntil(rc),t+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let n=this.flowLevel>0,r=this.charAt(1);if(Oe(r)||n&&io.has(r)){n?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,t+=yield*this.pushCount(1),t+=yield*this.pushSpaces(!0);continue e}}}break e}return t}*pushTag(){if(this.charAt(1)==="<"){let t=this.pos+2,n=this.buffer[t];for(;!Oe(n)&&n!==">";)n=this.buffer[++t];return yield*this.pushToIndex(n===">"?t+1:t,!1)}else{let t=this.pos+1,n=this.buffer[t];for(;n;)if(AS.has(n))n=this.buffer[++t];else if(n==="%"&&fg.has(this.buffer[t+1])&&fg.has(this.buffer[t+2]))n=this.buffer[t+=3];else break;return yield*this.pushToIndex(t,!1)}}*pushNewline(){let t=this.buffer[this.pos];return t===`
|
|
138
138
|
`?yield*this.pushCount(1):t==="\r"&&this.charAt(1)===`
|
|
139
|
-
`?yield*this.pushCount(2):0}*pushSpaces(t){let n=this.pos-1,r;do r=this.buffer[++n];while(r===" "||t&&r===" ");let s=n-this.pos;return s>0&&(yield this.buffer.substr(this.pos,s),this.pos=n),s}*pushUntil(t){let n=this.pos,r=this.buffer[n];for(;!t(r);)r=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};
|
|
139
|
+
`?yield*this.pushCount(2):0}*pushSpaces(t){let n=this.pos-1,r;do r=this.buffer[++n];while(r===" "||t&&r===" ");let s=n-this.pos;return s>0&&(yield this.buffer.substr(this.pos,s),this.pos=n),s}*pushUntil(t){let n=this.pos,r=this.buffer[n];for(;!t(r);)r=this.buffer[++n];return yield*this.pushToIndex(n,!1)}};pg.Lexer=sc});var ac=I(hg=>{"use strict";var ic=class{constructor(){this.lineStarts=[],this.addNewLine=t=>this.lineStarts.push(t),this.linePos=t=>{let n=0,r=this.lineStarts.length;for(;n<r;){let o=n+r>>1;this.lineStarts[o]<t?n=o+1:r=o}if(this.lineStarts[n]===t)return{line:n+1,col:1};if(n===0)return{line:0,col:t};let s=this.lineStarts[n-1];return{line:n,col:t-s+1}}}};hg.LineCounter=ic});var dc=I(vg=>{"use strict";var jS=wr("process"),mg=oo(),IS=oc();function pt(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function gg(e){for(let t=0;t<e.length;++t)switch(e[t].type){case"space":case"comment":case"newline":break;default:return t}return-1}function wg(e){switch(e?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function ao(e){switch(e.type){case"document":return e.start;case"block-map":{let t=e.items[e.items.length-1];return t.sep??t.start}case"block-seq":return e.items[e.items.length-1].start;default:return[]}}function an(e){if(e.length===0)return[];let t=e.length;e:for(;--t>=0;)switch(e[t].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;e[++t]?.type==="space";);return e.splice(t,e.length)}function co(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function yg(e){if(e.start.type==="flow-seq-start")for(let t of e.items)t.sep&&!t.value&&!pt(t.start,"explicit-key-ind")&&!pt(t.sep,"map-value-ind")&&(t.key&&(t.value=t.key),delete t.key,wg(t.value)?t.value.end?co(t.value.end,t.sep):t.value.end=t.sep:co(t.start,t.sep),delete t.sep)}var cc=class{constructor(t){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new IS.Lexer,this.onNewLine=t}*parse(t,n=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(t,n))yield*this.next(r);n||(yield*this.end())}*next(t){if(this.source=t,jS.env.LOG_TOKENS&&console.log("|",mg.prettyToken(t)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=t.length;return}let n=mg.tokenType(t);if(n)if(n==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=n,yield*this.step(),n){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+t.length);break;case"space":this.atNewLine&&t[0]===" "&&(this.indent+=t.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=t.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=t.length}else{let r=`Not a YAML token: ${t}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:t}),this.offset+=t.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let t=this.peek(1);if(this.type==="doc-end"&&t?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!t)return yield*this.stream();switch(t.type){case"document":return yield*this.document(t);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(t);case"block-scalar":return yield*this.blockScalar(t);case"block-map":return yield*this.blockMap(t);case"block-seq":return yield*this.blockSequence(t);case"flow-collection":return yield*this.flowCollection(t);case"doc-end":return yield*this.documentEnd(t)}yield*this.pop()}peek(t){return this.stack[this.stack.length-t]}*pop(t){let n=t??this.stack.pop();if(!n)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield n;else{let r=this.peek(1);switch(n.type==="block-scalar"?n.indent="indent"in r?r.indent:0:n.type==="flow-collection"&&r.type==="document"&&(n.indent=0),n.type==="flow-collection"&&yg(n),r.type){case"document":r.value=n;break;case"block-scalar":r.props.push(n);break;case"block-map":{let s=r.items[r.items.length-1];if(s.value){r.items.push({start:[],key:n,sep:[]}),this.onKeyLine=!0;return}else if(s.sep)s.value=n;else{Object.assign(s,{key:n,sep:[]}),this.onKeyLine=!s.explicitKey;return}break}case"block-seq":{let s=r.items[r.items.length-1];s.value?r.items.push({start:[],value:n}):s.value=n;break}case"flow-collection":{let s=r.items[r.items.length-1];!s||s.value?r.items.push({start:[],key:n,sep:[]}):s.sep?s.value=n:Object.assign(s,{key:n,sep:[]});return}default:yield*this.pop(),yield*this.pop(n)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(n.type==="block-map"||n.type==="block-seq")){let s=n.items[n.items.length-1];s&&!s.sep&&!s.value&&s.start.length>0&&gg(s.start)===-1&&(n.indent===0||s.start.every(o=>o.type!=="comment"||o.indent<n.indent))&&(r.type==="document"?r.end=s.start:r.items.push({start:s.start}),n.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let t={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&t.start.push(this.sourceToken),this.stack.push(t);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(t){if(t.value)return yield*this.lineEnd(t);switch(this.type){case"doc-start":{gg(t.start)!==-1?(yield*this.pop(),yield*this.step()):t.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":t.start.push(this.sourceToken);return}let n=this.startBlockValue(t);n?this.stack.push(n):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(t){if(this.type==="map-value-ind"){let n=ao(this.peek(2)),r=an(n),s;t.end?(s=t.end,s.push(this.sourceToken),delete t.end):s=[this.sourceToken];let o={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:r,key:t,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=o}else yield*this.lineEnd(t)}*blockScalar(t){switch(this.type){case"space":case"comment":case"newline":t.props.push(this.sourceToken);return;case"scalar":if(t.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let n=this.source.indexOf(`
|
|
140
140
|
`)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
|
|
141
|
-
`,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,t.indent)){let s=t.items[t.items.length-2]?.value?.end;if(Array.isArray(s)){
|
|
141
|
+
`,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,t.indent)){let s=t.items[t.items.length-2]?.value?.end;if(Array.isArray(s)){co(s,n.start),s.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=t.indent){let r=!this.onKeyLine&&this.indent===t.indent,s=r&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",o=[];if(s&&n.sep&&!n.value){let i=[];for(let a=0;a<n.sep.length;++a){let c=n.sep[a];switch(c.type){case"newline":i.push(a);break;case"space":break;case"comment":c.indent>t.indent&&(i.length=0);break;default:i.length=0}}i.length>=2&&(o=n.sep.splice(i[1]))}switch(this.type){case"anchor":case"tag":s||n.value?(o.push(this.sourceToken),t.items.push({start:o}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):s||n.value?(o.push(this.sourceToken),t.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(n.explicitKey)if(n.sep)if(n.value)t.items.push({start:[],key:null,sep:[this.sourceToken]});else if(pt(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(wg(n.key)&&!pt(n.sep,"newline")){let i=an(n.start),a=n.key,c=n.sep;c.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:a,sep:c}]})}else o.length>0?n.sep=n.sep.concat(o,this.sourceToken):n.sep.push(this.sourceToken);else if(pt(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let i=an(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||s?t.items.push({start:o,key:null,sep:[this.sourceToken]}):pt(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);s||n.value?(t.items.push({start:o,key:i,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(i):(Object.assign(n,{key:i,sep:[]}),this.onKeyLine=!0);return}default:{let i=this.startBlockValue(t);if(i){if(i.type==="block-seq"){if(!n.explicitKey&&n.sep&&!pt(n.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&t.items.push({start:o});this.stack.push(i);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(t){let n=t.items[t.items.length-1];switch(this.type){case"newline":if(n.value){let r="end"in n.value?n.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):t.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)t.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,t.indent)){let s=t.items[t.items.length-2]?.value?.end;if(Array.isArray(s)){co(s,n.start),s.push(this.sourceToken),t.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=t.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==t.indent)break;n.value||pt(n.start,"seq-item-ind")?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>t.indent){let r=this.startBlockValue(t);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(t){let n=t.items[t.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(t.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?t.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?t.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?t.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);!n||n.value?t.items.push({start:[],key:s,sep:[]}):n.sep?this.stack.push(s):Object.assign(n,{key:s,sep:[]});return}case"flow-map-end":case"flow-seq-end":t.end.push(this.sourceToken);return}let r=this.startBlockValue(t);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===t.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let s=ao(r),o=an(s);yg(t);let i=t.end.splice(1,t.end.length);i.push(this.sourceToken);let a={type:"block-map",offset:t.offset,indent:t.indent,items:[{start:o,key:t,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(t)}}flowScalar(t){if(this.onNewLine){let n=this.source.indexOf(`
|
|
142
142
|
`)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
|
|
143
|
-
`,n)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=Ns(t),r=Ut(n);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=Ns(t),r=Ut(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,n){return this.type!=="comment"||this.indent<=n?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Wp.Parser=aa});var Qp=C(Vn=>{"use strict";var Jp=Yo(),Wk=Fn(),Un=_n(),Jk=Vi(),Yk=x(),Gk=oa(),Yp=ca();function Gp(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Gk.LineCounter||null,prettyErrors:t}}function Hk(e,t={}){let{lineCounter:n,prettyErrors:r}=Gp(t),s=new Yp.Parser(n?.addNewLine),i=new Jp.Composer(t),o=Array.from(i.compose(s.parse(e)));if(r&&n)for(let a of o)a.errors.forEach(Un.prettifyError(e,n)),a.warnings.forEach(Un.prettifyError(e,n));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function Hp(e,t={}){let{lineCounter:n,prettyErrors:r}=Gp(t),s=new Yp.Parser(n?.addNewLine),i=new Jp.Composer(t),o=null;for(let a of i.compose(s.parse(e),!0,e.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Un.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(o.errors.forEach(Un.prettifyError(e,n)),o.warnings.forEach(Un.prettifyError(e,n))),o}function Qk(e,t,n){let r;typeof t=="function"?r=t:n===void 0&&t&&typeof t=="object"&&(n=t);let s=Hp(e,n);if(!s)return null;if(s.warnings.forEach(i=>Jk.warn(s.options.logLevel,i)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:r},n))}function Xk(e,t,n){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:n===void 0&&t&&(n=t),typeof n=="string"&&(n=n.length),typeof n=="number"){let s=Math.round(n);n=s<1?void 0:s>8?{indent:8}:{indent:s}}if(e===void 0){let{keepUndefined:s}=n??t??{};if(!s)return}return Yk.isDocument(e)&&!r?e.toString(n):new Wk.Document(e,r,n).toString(n)}Vn.parse=Qk;Vn.parseAllDocuments=Hk;Vn.parseDocument=Hp;Vn.stringify=Xk});var Zp=C(_=>{"use strict";var Zk=Yo(),eb=Fn(),tb=Co(),la=_n(),nb=kn(),tt=x(),rb=He(),sb=V(),ib=Xe(),ob=Ze(),ab=Cs(),cb=sa(),lb=oa(),ub=ca(),Ds=Qp(),Xp=gn();_.Composer=Zk.Composer;_.Document=eb.Document;_.Schema=tb.Schema;_.YAMLError=la.YAMLError;_.YAMLParseError=la.YAMLParseError;_.YAMLWarning=la.YAMLWarning;_.Alias=nb.Alias;_.isAlias=tt.isAlias;_.isCollection=tt.isCollection;_.isDocument=tt.isDocument;_.isMap=tt.isMap;_.isNode=tt.isNode;_.isPair=tt.isPair;_.isScalar=tt.isScalar;_.isSeq=tt.isSeq;_.Pair=rb.Pair;_.Scalar=sb.Scalar;_.YAMLMap=ib.YAMLMap;_.YAMLSeq=ob.YAMLSeq;_.CST=ab;_.Lexer=cb.Lexer;_.LineCounter=lb.LineCounter;_.Parser=ub.Parser;_.parse=Ds.parse;_.parseAllDocuments=Ds.parseAllDocuments;_.parseDocument=Ds.parseDocument;_.stringify=Ds.stringify;_.visit=Xp.visit;_.visitAsync=Xp.visitAsync});import{existsSync as TE,mkdtempSync as PE,readFileSync as Gh,rmSync as LE,writeFileSync as Wh}from"node:fs";import{tmpdir as FE}from"node:os";import{dirname as Te,join as wt,resolve as _a}from"node:path";import{existsSync as Yn,readFileSync as Mb}from"node:fs";import{join as uh}from"node:path";import{join as Em}from"node:path";import{randomBytes as im,randomUUID as zc}from"node:crypto";import{mkdirSync as om,realpathSync as am,statSync as ur}from"node:fs";import{open as cm,readFile as lm,readdir as um,rename as dm,rm as ri}from"node:fs/promises";import{basename as ii,dirname as Ee,join as ge,resolve as dr}from"node:path";var fm=448,ci=384,li=30,pm=1440*6e4,si="state.json",hm=/^runs\/[a-z][a-z0-9-]{0,62}\/[1-9][0-9]{0,5}\.summary\.json$/,mm=/^runs\/[a-z][a-z0-9-]{0,62}\/[1-9][0-9]{0,5}\.summary\.removals\.json$/,gm=/^templates\/[a-z][a-z0-9-]{0,62}\.[1-9][0-9]{0,5}\.json$/,xc=/^(?:frozen|dataops)\/[a-z][a-z0-9-]{0,62}$/,L=class extends Error{constructor(n,r){super(r);this.code=n;this.name="EnvStateError"}code};function fr(e=process.env){return Ee(Ic("env",e))}function pr(e,t){let n=ui(e,t);if(n!==void 0)return`The journal directory ${dr(t)} is inside the repository ${n} that holds the file: the state, the run summaries and the templates of its runs would be committed with it, and they name the org\u2019s records by their ids. Point SANDFORGE_JOURNAL_DIR at a folder outside the repository \u2014 in CI, $RUNNER_TEMP/sandforge \u2014 and keep it between the jobs that apply and destroy, in a cache keyed by the org.`}function ui(e,t){let n;try{n=cr(Mc(e))}catch{return}return new Oe(n).isInsideRepo(Mc(t))?n:void 0}function Mc(e){let t=[],n=dr(e);for(;;)try{return ge(am(n),...t.reverse())}catch{let r=Ee(n);if(r===n)return dr(e);t.push(ii(n)),n=r}}function ae(e,t){return`runs/${_e(e)}/${mr(t)}.summary.json`}function di(e,t){return`runs/${_e(e)}/${mr(t)}.summary.removals.json`}function kt(e,t){return`templates/${_e(e)}.${mr(t)}.json`}function hr(e,t,n,r=zc()){return`env-${_e(e)}-${_e(t)}-${mr(n)}-${r}`}function _e(e){let t=Gt.safeParse(e);if(!t.success)throw new L("invalid",`Not a name of the file: "${e}"`);return t.data}function mr(e){if(!Number.isInteger(e)||e<1||e>999999)throw new L("invalid",`Not a run's rank: ${e}`);return e}function gr(e){return{version:1,env:_e(e.env),lineage:zc(),serial:0,sandforgeVersion:e.sandforgeVersion,updatedAt:(e.now??new Date).toISOString(),org:{organizationId:xe(e.org.organizationId),kind:e.org.kind,username:e.org.username,...e.org.alias!==void 0?{alias:e.org.alias}:{}},file:{digest:e.fileDigest},resources:{}}}function en(e){return(e?.runs.at(-1)?.n??0)+1}function tn(e,t){let n=e.resources[t.resource],r={...t.run,n:en(n),objects:[]};return wr(e,t.resource,{kind:t.kind,fingerprint:t.fingerprint,dependsOn:[...t.dependsOn],status:"applying",runs:[...n?.runs??[],r]})}function fi(e,t){let n=e.resources[t];if(n===void 0)throw new L("invalid",`The state holds no resource ${t} to take back`);return wr(e,t,{...n,status:"destroying"})}function yr(e,t,n){let r=e.resources[t];if(r===void 0)throw new L("invalid",`The state holds no resource ${t}`);let s=r.runs.map(i=>i.n===n?{...i,takenBack:!0}:i);return wr(e,t,{...r,runs:s})}function bt(e,t){let n=e.resources[t.resource];if(n===void 0)throw new L("invalid",`The state holds no resource ${t.resource}`);let r=[...n.runs],s=r.at(-1);if(t.run!==void 0){if(s===void 0)throw new L("invalid",`The resource ${t.resource} has no run to end`);r[r.length-1]={...s,...t.run}}return wr(e,t.resource,{...n,status:t.status,runs:r})}function wr(e,t,n){return{...e,resources:{...e.resources,[_e(t)]:n}}}function pi(e){if(e.org.kind==="scratch")return new Date(Date.parse(e.updatedAt)+li*pm).toISOString()}function vr(e){if(e.fileFolder!==null){let r=pr(e.fileFolder,e.journalDir);if(r!==void 0)return{refusal:r}}let t=new oi(e),n=Zt(t.root,e.uid??Bc);return n!==void 0?{refusal:n}:{store:t}}var oi=class{root;fileFolder;uid;renameFile;now;constructor(t){this.root=ge(dr(t.journalDir),"env"),this.fileFolder=t.fileFolder,this.uid=t.uid??Bc,this.renameFile=t.rename??((n,r)=>dm(n,r)),this.now=t.now??Date.now}folderOf(t,n){let r=_c(t);if(r===void 0)throw new L("invalid",`Not an Organization Id: "${t}"`);return ge(this.root,r,_e(n))}fileOf(t,n,r){if(!hm.test(r)&&!gm.test(r)&&!mm.test(r))throw new L("invalid",`Not a file of a state's folder: "${r}"`);return ge(this.folderOf(t,n),...r.split("/"))}async read(t,n){let r=this.folderOf(t,n),s=ge(r,si),i;try{i=await lm(s,"utf8")}catch(o){if(ai(o)==="ENOENT")return;throw o}return ym(i,s,r)}stateFileOf(t,n){return ge(this.folderOf(t,n),si)}async setAside(t,n){if(this.fileFolder===null)throw new L("invalid","The states were opened to be listed, not written");let r=this.stateFileOf(t,n),s=new Date(this.now()).toISOString().replace(/\.\d{3}Z$/,"").replace(/[-:]/g,"").replace("T","-"),i=`${r}.damaged-${s}`;for(let o=2;ur(i,{throwIfNoEntry:!1})!==void 0;o++)i=`${r}.damaged-${s}-${o}`;return await this.renameFile(r,i),i}async write(t,n){if(this.fileFolder===null)throw new L("invalid","The states were opened to be listed, not written");if(t.lineage!==n.lineage)throw new L("invalid","A state is written over its own lineage only");let r=this.folderOf(t.org.organizationId,t.env),s=await this.read(t.org.organizationId,t.env),i=s?.serial??0;if(i!==n.serial||s!==void 0&&s.lineage!==n.lineage){let a=s===void 0?"it is gone":s.lineage!==n.lineage?"it is another state, made since":`serial ${i}, not ${n.serial}`;throw new L("moved",`The state of ${t.env} on ${t.org.organizationId} changed since it was read (${a}): another apply or destroy ran, or a cache put back another state. Nothing was written: plan again.`)}let o=Ht.safeParse({...t,org:{...t.org,organizationId:xe(t.org.organizationId)},serial:n.serial+1,updatedAt:new Date(this.now()).toISOString()});if(!o.success)throw new L("invalid",`Not a state: ${o.error.message}`);for(let a of[Ee(r),r]){let c=Zt(a,this.uid);if(c!==void 0)throw new L("folder",c)}return await this.writeWhole(ge(r,si),`${JSON.stringify(o.data,null,2)}
|
|
144
|
-
`),
|
|
145
|
-
`).map(t=>t.trim()).filter(t=>t!==""&&!
|
|
146
|
-
`).map(t=>t.trim()).filter(Boolean).at(-1)??"it said nothing"}function $t(e,t){try{return{answer:t(e.stdout),raw:JSON.parse(e.stdout)}}catch(n){if(!(n instanceof re))throw n;return{unread:`exit ${e.code}: ${Lm(e)}`}}}function br(e,t,n){let r=[],s=rn(e,"before");s!==void 0&&n&&Fm(t)&&r.push({step:"before",name:s});let i=rn(e,"after");return i!==void 0&&(n||t?.checkpoints?.after===void 0)&&r.push({step:"after",name:i}),r}function Gc(e){return Object.values(e?.resources??{}).some(t=>t.status!=="destroyed")}function Fm(e){return e?.checkpoints?.before===void 0&&!Gc(e)}function Hc(e,t){return e.checkpoint?.before!==!0||t?.checkpoints?.before!==void 0?[]:Gc(t)?["checkpoint.before is taken before the first apply of an environment, and the org holds what an earlier apply wrote without one: it is not taken now, since a rewind to it would keep those records. Destroy the environment, then apply, to take it"]:[]}function Qc(e){let t=$t(e,Im);if("unread"in t)return t;let n=t.answer;if(!("estimate"in n))return{refusal:yi(n.refusal)};let{records:r,apiRequests:s,seconds:i,bytes:o}=n.estimate;return{estimate:{records:r,apiRequests:s,seconds:i,bytes:o},...n.refusal!==void 0?{refusal:yi(n.refusal)}:{}}}function Xc(e,t,n=0){return e.map(({step:r,name:s})=>t===void 0?{step:r,name:s,unread:"not read: --quick"}:"unread"in t?{step:r,name:s,unread:t.unread}:{step:r,name:s,..."estimate"in t?{estimate:r==="after"?{...t.estimate,records:t.estimate.records+n}:t.estimate}:{},...t.refusal!==void 0?{refusal:t.refusal}:{}})}var Er={before:"before the first write",after:"once applied"};function Zc(e){let t=e.filter(n=>n.refusal!==void 0);if(t.length!==0)return t.map(n=>`The checkpoint the file asks ${Er[n.step]}, '${n.name}', would be refused: ${n.refusal?.message??""}`).join(" ")+" Take checkpoint.before or checkpoint.after out of the file, or fix what refuses it."}function el(e){let t=0,n=[];for(let r of e)r.estimate!==void 0?t+=r.estimate.apiRequests:n.push(`the checkpoint ${Er[r.step]}, not estimated`);return{estimate:t,notCounted:n}}function tl(e,t){let n=$t(t,Yc);if("unread"in n)return{checkpoint:e,differs:!1,unread:n.unread};let r=n.answer;return"differs"in r?{checkpoint:e,differs:r.differs,toDelete:r.toDelete,toGiveBack:r.toGiveBack,toBringBack:r.toBringBack}:{checkpoint:e,differs:!1,unread:r.refusal.message}}var Se=e=>e.toLocaleString("en-US");function nl(e){let t=[];for(let r of e.checkpoints??[]){let s=`checkpoint ${Er[r.step]}: '${r.name}'`,{estimate:i}=r;i!==void 0?t.push(`${s}, about ${Se(i.records)} records, ${Se(i.apiRequests)} API requests, ${Se(Math.ceil(i.seconds))} s, ${at(i.bytes/(1024*1024))} MB on this machine`):t.push(`${s}, not estimated (${r.unread??"no estimate"})`),r.refusal!==void 0&&t.push(` refused: ${r.refusal.message}`)}let n=e.drift;if(n!==void 0){let r=`the whole org against the checkpoint after the last apply (${n.checkpoint})`;t.push(n.unread!==void 0?`${r}: not compared, ${n.unread}`:n.differs?`${r}: differs, ${Se(n.toDelete??0)} to delete \xB7 ${Se(n.toGiveBack??0)} to give back \xB7 ${Se(n.toBringBack??0)} to bring back`:`${r}: nothing differs among the objects and fields it compares`)}return t}async function ki(e,t,n){e.say(`checkpoint ${Er[t.step]}: taking '${t.name}'`);let r=await e.runner(ce,Rm({org:t.org.alias,store:ye(e.journalDir),name:t.name,keepDays:Sm(t.org.kind),...t.ignoreFields!==void 0?{ignoreFields:t.ignoreFields}:{},...t.maxTotal!==void 0?{maxTotal:t.maxTotal}:{},...t.excludeObjects!==void 0?{excludeObjects:t.excludeObjects}:{}}),n),s=$t(r,Dm),i="answer"in s?s.answer:void 0,o="raw"in s?s.raw:void 0;if(r.code===0&&i!==void 0&&"checkpoint"in i)return{result:{step:t.step,checkpoint:i.checkpoint.checkpointId,exitCode:r.code,answer:o},checkpoint:i.checkpoint.checkpointId};let a=i!==void 0&&"refusal"in i?`${i.refusal.code}: ${yi(i.refusal).message}`:"unread"in s?s.unread:`exit ${r.code}`;return{result:{step:t.step,exitCode:r.code===0?1:r.code,refusal:a.slice(0,4e3),...o!==void 0?{answer:o}:{}}}}async function At(e,t,n){e.say(`checkpoint ${t.checkpoint}: deleted from this machine, ${t.why}`);let r=await e.runner(ce,$m({org:t.org.alias,store:ye(e.journalDir),checkpoint:t.checkpoint}),n),s=$t(r,Pm),i="answer"in s?s.answer:void 0,o=i!==void 0&&"deleted"in i&&i.deleted.includes(t.checkpoint),a=i!==void 0&&"refusal"in i&&i.refusal.code==="NOT_FOUND";if(o||a)return{step:"delete",checkpoint:t.checkpoint,exitCode:0};let c=i!==void 0&&"refusal"in i?`${i.refusal.code}: ${i.refusal.message}`:i!==void 0&&"kept"in i?"kept: a take, a rewind or an undo of the org is running":"unread"in s?s.unread:`exit ${r.code}`;return e.say(` not deleted: ${c}`),{step:"delete",checkpoint:t.checkpoint,exitCode:r.code===0?1:r.code,refusal:c.slice(0,4e3)}}function Sr(e){let t=[];return e?.checkpoints?.after!==void 0&&t.push({step:"after",checkpoint:e.checkpoints.after}),e?.checkpoints?.before!==void 0&&t.push({step:"before",checkpoint:e.checkpoints.before}),t}function Be(e,t,n){let r={...e.checkpoints};n!==void 0?r[t]=n:delete r[t];let s={...e,checkpoints:r};return Object.keys(r).length===0&&delete s.checkpoints,s}function rl(e){let t=$t(e,Yc);if("unread"in t)return{refusal:t.unread};let n=t.answer;if(!("differs"in n))return{refusal:n.refusal.message};let r={};for(let s of n.diff.objects)for(let[i,o]of Object.entries(s.lastChangedBy)){let a=n.diff.userNames[i]??i;r[a]=(r[a]??0)+o}return{checkpoint:n.checkpoint,toDelete:n.toDelete,toGiveBack:n.toGiveBack,toBringBack:n.toBringBack,lastChangedBy:r,differs:n.differs,...n.refusal!==void 0?{refusal:n.refusal}:{}}}function Rr(e){return Object.entries(e).sort((t,n)=>n[1]-t[1]).map(([t,n])=>`${t} ${Se(n)}`).join(", ")}function sl(e,t,n){let r=`'${n.checkpoint.name}' (${n.checkpoint.id}), taken ${n.checkpoint.takenAt}`,s=[e==="reset"?`reset ${t} to the checkpoint taken after the last apply, ${r}:`:`destroy by rewinding ${t} to the checkpoint taken before the first apply, ${r}:`,` ${Se(n.toDelete)} to delete \xB7 ${Se(n.toGiveBack)} to give back \xB7 ${Se(n.toBringBack)} to bring back`+(n.differs?"":" \u2014 nothing differs: nothing to rewind")],i=Rr(n.lastChangedBy);return i!==""&&s.push(` last changed by: ${i}`),n.refusal!==void 0&&s.push(` refused: ${n.refusal.message}`),s}function il(e){let t=$t(e,Tm),n="answer"in t?t.answer:void 0,r="raw"in t?t.raw:void 0;if(n!==void 0&&"status"in n)return{exitCode:e.code,status:n.status,answer:r,done:{deleted:n.deleted.done,givenBack:n.givenBack.done,broughtBack:n.broughtBack.done,differing:n.residual.reduce((i,o)=>i+o.count,0)},...n.undo!==void 0?{undoUntil:n.undo.until}:{}};let s=n!==void 0&&"refusal"in n?n.refusal:{code:"UNREAD",message:"unread"in t?t.unread:`exit ${e.code}`};return{exitCode:e.code===0?1:e.code,status:e.code>=128?"cancelled":"failure",...r!==void 0?{answer:r}:{},refusal:s}}function ol(e,t){return e.deleted?{offered:!1,why:"the environment\u2019s checkpoints are deleted with it, the journal of this rewind among them: a destroy is undone by applying again"}:t.undoUntil===void 0?{offered:!1,why:t.status==="failure"||t.status==="cancelled"?"the checkpoint script offers no undo of a rewind that wrote nothing it can take back":"the checkpoint script offers none: the rewind wrote nothing"}:{offered:!0,until:new Date(Date.parse(t.undoUntil)).toISOString(),line:`${ue("checkpoint")} undo --org ${e.alias} --checkpoint ${e.checkpoint} --store ${ye(e.journalDir)}`}}function al(e){return e.offered?`undo it until ${e.until}, sooner if the recycle bin fills: ${e.line}`:`no undo: ${e.why}`}var $r="STATE_MOVED",cl="No flag lifts this: an environment is never applied to a production org.";function de(e,t){return e.length>=15&&t.length>=15&&e.slice(0,15)===t.slice(0,15)}function ll(e,t,n){if("unread"in t)return t.error!==void 0&&Za(t.error)!==void 0?{refusal:{code:"UNTYPED",message:rc(e,t.error,{tool:"sandforge env",action:"write",readOnly:"plan"}),exit:1}}:{refusal:{code:"PRODUCTION",message:`${e} did not say what org it is (${t.unread}), and an environment is applied to no org it cannot tell from a production one. Nothing was read or written. ${cl}`,exit:1}};if(sr(t)){let s=t.edition?`IsSandbox false, edition ${t.edition}`:"IsSandbox false, and no edition";return{refusal:{code:"PRODUCTION",message:`${e} is a production org (its Organization record says ${s}): an environment is applied to scratch orgs, Developer Edition orgs and the sandboxes its file lists. Nothing was read or written. ${cl}`,exit:1}}}let r=t.sandbox?n.scratch===!0?"scratch":"sandbox":"developer";return{target:{alias:e,organizationId:t.id,kind:r,username:n.username}}}var ul={scratch:"a scratch org",developer:"a Developer Edition org",sandbox:"a sandbox"};function dl(e,t){let n=t.organizationId;if(e.protect.some(r=>de(r,n)))return{code:"PROTECTED",message:`${t.alias} (${xe(n)}) is listed under targets.protect: the file refuses it whatever else it says. Nothing was read or written.`,exit:1};if(!e.kinds.includes(t.kind)){let r=t.kind==="sandbox"?" If it is a scratch org, the sf CLI did not say so: its display names no Dev Hub for it, as when the org was logged in with an auth URL alone. Log its Dev Hub in on this machine, or list the org as a sandbox.":"";return{code:"KIND",message:`${t.alias} is ${ul[t.kind]}, and the file's targets.kinds allows ${e.kinds.join(", ")}: add ${t.kind} to targets.kinds to apply it there. Nothing was read or written.${r}`,exit:1}}if(t.kind==="sandbox"&&!e.sandboxes.some(r=>de(r,n)))return{code:"NOT_LISTED",message:`${t.alias} is a sandbox, and its Organization Id ${xe(n)} is not listed under targets.sandboxes: nothing Salesforce says tells a sandbox that holds a client's records from a developer's, so each one the file writes to is listed, reviewed with the file. A refresh changes the Id: a sandbox listed before its refresh is listed again. Nothing was read or written. If it is a scratch org, the sf CLI did not say so: its display names no Dev Hub for it, as when the org was logged in with an auth URL alone.`,exit:1}}function Ke(e){return{code:e.code==="otherOrg"?"OTHER_ORG":"STATE_DAMAGED",message:`${e.message} Nothing was read or written in the org.`,exit:1}}function fl(e,t,n){if(!(e.env===t&&de(e.org.organizationId,n.organizationId)))return{code:"OTHER_ORG",message:`The state read for ${t} on ${n.alias} is of ${e.env} on ${e.org.organizationId}: a state of another org is never applied. Nothing was read or written.`,exit:1}}function pl(e,t,n,r=!1){let s=`this machine keeps no state of ${t} on ${e.alias}: records an earlier apply left there, from another machine or a cache that was not restored, cannot be told from the org\u2019s own, and would be created twice`+(r?`; it keeps runs of ${t} on ${e.alias}, and ${ue("env")} state recover rebuilds the state from them`:"");return e.kind==="scratch"||n?{warning:s}:{refusal:{code:"NO_STATE",message:`${s.charAt(0).toUpperCase()}${s.slice(1)}. On ${ul[e.kind]} that lives on, apply asks --accept-no-state to go ahead: restore the journal directory of the apply before it, or give the flag. Nothing was written.`,exit:1}}}function Ar(e,t){return t?{code:"STORE_IN_REPOSITORY",message:e,exit:2}:{code:"STORE",message:e,exit:1}}function Ue(e){return{code:"LOCKED",message:Rc(e),exit:1}}function an(e){return{code:"CHECKPOINT_ACT",message:`${e.charAt(0).toUpperCase()}${e.slice(1)}`,exit:1}}import{readFileSync as xm}from"node:fs";import{join as Mm}from"node:path";var U="sandforge-clone",gl=1e4,hl=1e6,_m=["inputMode","recordId","soqlQuery","templateId","aiPrompt","dryRun"];function qm(e){let[t]=e;return`SELECT Id FROM ${t?.object??""}${t?.where!==void 0?` WHERE ${t.where}`:""}`}function zm(e,t,n){let r=["resources",e,"template"],s=u=>({refusals:[T(r,u)]}),i;try{i=xm(Mm(n,t.file),"utf8")}catch(u){return s(`${t.file} cannot be read: ${u instanceof Error?u.message:String(u)}`)}if(i.length>hl)return s(`${t.file} is larger than ${hl} bytes`);let o;try{o=JSON.parse(i.replace(/^\uFEFF/,""))}catch{return s(`${t.file} is not JSON`)}let a=Array.isArray(o)?o:[o],c=a.find(u=>u!==null&&typeof u=="object"&&u.id===t.id);if(c===void 0){let u=a.map(d=>d!==null&&typeof d=="object"?d.id:"").filter(d=>typeof d=="string"&&d!=="");return s(`${t.file} holds no template "${t.id}"`+(u.length>0?`: it holds ${u.join(", ")}`:": it holds none"))}let l=Gs.safeParse(c);return l.success?{entry:l.data}:{refusals:l.error.issues.map(u=>T(r,`the template "${t.id}" of ${t.file} is refused by Forge's template schema at ${u.path.map(String).join(".")||"its top"}: ${u.message}`))}}function yl(e,t,n,r,s){let i=["resources",t],o=[];if(n.depth==="all")return{run:{source:n.source,wholeOrg:{anonymize:n.anonymize!==void 0,keepContactPoints:n.keepContactPoints===!0,...n.fit!==void 0?{fit:n.fit==="share"?{}:{withinMB:n.fit.withinMB}}:{}},...n.maxTotal!==void 0?{maxTotal:n.maxTotal}:{},acceptAutomation:n.accept?.automation===!0,acceptRealData:n.accept?.realData===!0},warnings:o};let a;if(n.template!==void 0){let y=zm(t,n.template,r);if("refusals"in y)return y;a=y.entry}let c={...a?.config};for(let y of _m)delete c[y];if(n.tables!==void 0&&c.expandOrphanParents===!0)return{refusals:[T([...i,"template"],"the template brings orphan parents (expandOrphanParents), which go with a clone of one record: a clone of tables reads the parents its tables point at, named with them")]};a?.files!==void 0&&o.push(T([...i,"template"],"the template copies the files of the cloned records: an environment copies none, and the clone writes the records alone"));let l=n.depth??c.depth,u=(l??"custom")==="custom"?n.customDepth??c.customDepth:void 0;delete c.customDepth;let d=s.toISOString(),f={id:`env-${e}-${t}`,name:`${e}/${t}`,description:`The ${t} resource of the ${e} environment`,config:{anonymizePII:!1,skipEmpty:!0,batchSize:"auto",...c,...n.tables!==void 0?{inputMode:"soql",soqlQuery:qm(n.tables)}:{inputMode:"record",...n.record?.id!==void 0?{recordId:n.record.id}:{}},depth:l??"custom",...u!==void 0?{customDepth:u}:{},...n.maxNodes!==void 0?{maxNodes:n.maxNodes}:{},...n.keepContactPoints!==void 0?{keepContactPoints:n.keepContactPoints}:{},...n.anonymize!==void 0?{anonymizePII:!0}:{}},...n.anonymize!==void 0?{anonymization:structuredClone(n.anonymize)}:a?.anonymization!==void 0?{anonymization:structuredClone(a.anonymization)}:{},objectCount:0,recordCount:0,createdAt:d,lastUsedAt:d},g=Gs.safeParse(f);return g.success?{run:{source:n.source,template:g.data,...n.record!==void 0?{record:{...n.record}}:{},...n.tables!==void 0?{tables:n.tables.map(y=>({...y}))}:{},...n.maxTotal!==void 0?{maxTotal:n.maxTotal}:{},acceptAutomation:n.accept?.automation===!0,acceptRealData:n.accept?.realData===!0},warnings:o}:{refusals:g.error.issues.map(y=>T(i,`the template it converts into is refused by Forge's template schema at ${y.path.map(String).join(".")||"its top"}: ${y.message}`))}}function wl(e){return e.tables!==void 0?e.tables.map(t=>({object:t.object})):e.record?.object!==void 0?[{object:e.record.object}]:[]}function vl(e){if(e.wholeOrg)return e.wholeOrg.anonymize;let t=e.template?.anonymization?.rules??{};return e.template?.config.anonymizePII===!0&&Object.values(t).some(n=>n!==void 0)}function Bm(e){return e.edition?`its Organization record says IsSandbox false, edition ${e.edition}`:"its Organization record says IsSandbox false, and no edition"}function Km(e,t,n){if(e.acceptRealData||vl(e))return;let r=e.template?.config.anonymizePII===!0?" Its anonymize sets a method for no category of personal field, so it does not count.":"";return`its source, ${t}, is a production org (${Bm(n)}): what it clones is real people\u2019s data, written as read into an org built for tests.${r} Give the resource anonymize \u2014 Forge\u2019s anonymization, a method for each category of personal field \u2014 or, reviewed in the file, accept: { realData: true }. Emails and phone numbers are neutralized either way, unless keepContactPoints: true`}function kl(e,t){let n=t.read;if(n===void 0||"refusal"in n||n.production!==!0)return[];let r=Object.entries(e.template?.anonymization?.rules??{}).filter(([,o])=>o!==void 0).map(([o,a])=>`${o} ${String(a)}`),s=vl(e)?e.wholeOrg?"anonymized, every personal field by its category\u2019s default method":`anonymized as its anonymize says (${r.join(", ")})`:"written as read, as the file accepts (accept: { realData: true })",i=e.wholeOrg?e.wholeOrg.keepContactPoints:e.template?.config.keepContactPoints===!0;return[`real data: its source, the ${t.role} org (${t.alias}), is a production org; what it clones is ${s}`,i?"contact points: written as read (keepContactPoints: true)":"contact points: neutralized before writing (emails under .invalid, phone numbers in a fictional range), as the clone does unless keepContactPoints"]}async function bl(e,t,n,r){let s=`the ${n} org (${r})`,i;try{i=await rr(e)}catch(d){return{refusal:`${s} could not be read: ${ml(d)}`}}let o=i.id,a=sr(i);if(a){let d=Km(t,s,i);if(d!==void 0)return{refusal:d}}let c={organizationId:o,...a?{production:!0}:{}},l=t.record;if(l?.object===void 0||l.where===void 0)return c;let u=`${l.object} WHERE ${l.where}`;try{let d=(await e.query(`SELECT Id FROM ${u} LIMIT 2`)).records;return d.length===1&&typeof d[0]?.Id=="string"?{...c,recordId:d[0].Id}:d.length===0?{refusal:`its record query finds no ${l.object} in ${s} (WHERE ${l.where}): a record named by a query is one its source answers with exactly one row`}:{refusal:`its record query finds ${(await e.query(`SELECT COUNT() FROM ${u}`)).totalSize} ${l.object} records in ${s} (WHERE ${l.where}), not one: narrow the where to one row, or name the record by its id`}}catch(d){return{refusal:`its record query could not be read in ${s}: ${ml(d)}`}}}function El(e,t){let n=t!==void 0&&"organizationId"in t?t:void 0;return{kind:"forge",kindVersion:1,source:n?.organizationId.slice(0,15)??null,record:e.record===void 0?null:(e.record.id??n?.recordId)?.slice(0,15)??{unread:e.record},tables:e.tables??null,config:e.template?.config??null,anonymization:e.template?.anonymization??null,...e.wholeOrg?{wholeOrg:e.wholeOrg}:{}}}function Sl(e){if(e.wholeOrg)return Um(e,e.wholeOrg);if(e.recordId===void 0&&(e.tables??[]).length===0)throw new Error("A forge resource clones a record or tables: its line names neither.");return["--source",I("--source",e.source),"--target",I("--target",e.target),...e.recordId!==void 0?["--record",I("--record",e.recordId)]:(e.tables??[]).flatMap(t=>["--object",I("--object",t.object),...t.where!==void 0?["--where",I("--where",t.where)]:[]]),"--template",I("--template",e.templateFile),"--max-total",String(e.maxTotal),"--skip-preflight",...e.acceptAutomation?["--accept-automation"]:[]]}function Um(e,t){return["--source",I("--source",e.source),"--target",I("--target",e.target),"--depth","all","--config",I("--config",e.templateFile),"--max-total",String(e.maxTotal),"--skip-preflight",t.anonymize?"--anonymize":"--no-anonymize",...t.keepContactPoints?["--keep-contact-points"]:[],...t.fit!==void 0?["--fit","share",...t.fit.withinMB!==void 0?["--fit-within",String(t.fit.withinMB)]:[]]:[],...e.acceptAutomation?["--accept-automation"]:[]]}function Rl(e){return[...Sl(e),"--dry-run","--json"]}function $l(e){return[...Sl(e),...e.wholeOrg?["--yes"]:[],"--summary",I("--summary",e.summary),"--json"]}function Al(e){return["--remove",I("--remove",e.summary),"--target",I("--target",e.target),...e.includeChanged===!0?["--include-changed"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[]]}function Ol(e){return[...Al(e),...Ce(e),"--json"]}function Cl(e){return[...Al(e),"--preview",...Ce(e),"--json"]}function jl(e){return["--verify",I("--verify",e.summary),"--target",I("--target",e.target),"--source",I("--source",e.source),"--json"]}var Vm=p.enum(["SingleEmail","DailyWorkflowEmails"]),Wm=p.object({tool:p.literal(U),version:p.literal(1),dryRun:p.literal(!0),result:p.object({wouldInsertCount:A,failedCount:A}),writePlan:p.object({totalRows:A,storageBytes:A,objects:p.array(p.object({objectApiName:p.string().min(1),rows:A,storageBytes:A,mayAdd:A.optional()})),emails:p.array(p.object({limit:Vm,emails:A})).optional()}).optional(),wouldBeRefused:p.array(p.string()).optional(),wouldBeRefusedCodes:p.array(p.string()).optional(),targetGaps:p.object({gaps:p.array(p.object({kind:p.string().min(1),severity:p.string().min(1),objectApiName:p.string().min(1),field:p.string().min(1).optional()}).loose())}).loose().optional()}),Jm=p.object({tool:p.literal(U),version:p.literal(1),dryRun:p.literal(!1),targetOrgId:qe.optional(),result:p.object({successCount:A,failedCount:A,createdByObject:p.array(p.object({objectApiName:p.string().min(1),sourceIds:p.array(qe)})),remapInJournal:p.literal(!0).optional(),createdCountByObject:p.array(p.object({objectApiName:p.string().min(1),created:A})).optional(),errors:p.array(p.object({objectApiName:p.string().min(1),failedCount:A,samples:p.array(p.unknown()).optional()}))}),running:p.literal(!0).optional(),interrupted:p.literal(!0).optional(),error:p.string().optional()}),Ym=p.object({tool:p.literal(U),version:p.literal(1),action:p.literal("remove"),summary:p.string().min(1),target:p.string().min(1),includeChanged:p.boolean(),result:p.object({status:p.enum(["success","partial","failure","cancelled"]),planned:A,objects:p.array(St),sweep:p.object({status:p.string()}).loose().optional()}),elapsedMs:A}),Gm=p.object({tool:p.literal(U),version:p.literal(1),action:p.literal("remove-preview"),summary:p.string().min(1),target:p.string().min(1),includeChanged:p.boolean(),preview:Rt,refusals:p.array(p.string()),refusalCodes:p.array(p.string()).optional(),notes:p.array(p.string()),elapsedMs:A}),Hm=p.object({tool:p.literal(U),version:p.literal(1),action:p.literal("verify"),result:p.object({verdict:p.enum(["verified","partial","unstable"]),attempts:A,objects:p.array(p.object({objectApiName:p.string().min(1),expected:A,present:A,deleted:A,notVisible:A,changed:A,linksChecked:A,linksBroken:A,error:p.string().optional()})),linksUnchecked:p.string().optional()})});function Nl(e,t){let n=new Set((t?.config.defaultValues??[]).map(s=>`${s.object}.${s.field}`.toLowerCase())),r=(e.targetGaps?.gaps??[]).filter(s=>s.severity==="blocking").flatMap(s=>{let i=s.field!==void 0?`${s.objectApiName}.${s.field}`:s.objectApiName;switch(s.kind){case"required_field_missing":return n.has(i.toLowerCase())?[]:[`${i}, which the org requires and the clone does not write`];case"object_not_createable":case"object_through_parent":return[`${i}, which the user it writes as may not create`];case"object_feature_off":return[`${i}, which a feature or licence the org has not turned on keeps closed`];case"api_budget":return["more API requests than the org has left today"];default:return[`${i} (${s.kind})`]}});if(r.length!==0)return`the org to fill would refuse its rows: ${r.join("; ")}. Give a field the org requires a value in the template's defaultValues (template: { file, id }), leave out an object its user may not create, or run it once the org has requests left`}function Il(e){return z(U,"the summary of a dry run",Wm,e)}function cn(e){return z(U,"the summary of a run",Jm,e)}function Dl(e){return z(U,"the outcome of a removal",Ym,e)}function Tl(e){return z(U,"the preview of a removal",Gm,e)}function Pl(e){return z(U,"a verification",Hm,e)}function Ll(e){let t=e.writePlan,n=(e.wouldBeRefused??[]).join(" "),r=ze(n,e.wouldBeRefused,e.wouldBeRefusedCodes),s=r.length>0?{refusalCodes:r}:{};if(t===void 0)return{objects:[],total:0,created:0,storageBytes:0,emails:[],refusal:n!==""?n:"the clone never came to count what it would write, and a run held to no count is held to nothing",...s};let i=e.result.wouldInsertCount===t.totalRows,o=n!==""?n:t.totalRows===0?"it would write nothing: the clone reads no record to write; look at its record or the conditions of its tables":void 0;return{objects:t.objects.map(a=>({object:a.objectApiName,wouldCreate:a.rows,...i?{}:{atMost:!0}})),total:t.totalRows,created:e.result.wouldInsertCount,storageBytes:t.storageBytes,emails:t.emails??[],...o!==void 0?{refusal:o,...s}:{}}}function Or(e){let n=((e.result.remapInJournal===!0?e.result.createdCountByObject:void 0)??e.result.createdByObject.map(r=>({objectApiName:r.objectApiName,created:r.sourceIds.length}))).map(r=>({object:r.objectApiName,created:r.created,refused:0,errors:[]}));for(let r of e.result.errors){if(r.failedCount===0)continue;let s=n.find(o=>o.object===r.objectApiName),i=`${r.failedCount} refused by the org`;s!==void 0?(s.refused+=r.failedCount,s.errors.push(i)):n.push({object:r.objectApiName,created:0,refused:r.failedCount,errors:[i]})}return{objects:n,created:e.result.successCount}}function Fl(e){let{result:t}=e;if(t.verdict==="unstable")return`no two of ${t.attempts} readings agreed: something still writes to the run's records; verify again once it is done`;let n=t.objects.flatMap(r=>{if(r.error!==void 0)return[`${r.objectApiName} not read (${r.error})`];let s=r.deleted+r.notVisible;return[...s>0?[`${r.objectApiName} ${s} of ${r.expected} not there`]:[],...r.linksBroken>0?[`${r.objectApiName} ${r.linksBroken} lookup(s) that do not hold`]:[]]});return n.length>0?n.join("; "):void 0}function ml(e){return e instanceof Error?e.message:String(e)}import{readFileSync as Ml}from"node:fs";import{join as _l}from"node:path";var Q="sandforge-frozen",xl=1e6,Qm=["sasDir","datasetDir"],Xm=["rootObject","excludedObjects","identityKeys","undeletableObjects","requiredLookupPlaceholders","requiredFieldDefaults","picklistRules","defaultPicklistRule","duplicateErrorPatterns"],ql=new Set(["NO_LOAD","ALREADY_REMOVED","NOTHING_TO_REMOVE"]);function zl(e,t,n){let r=["resources",e,"config"],s=f=>({refusals:[T(r,f)]}),i;try{i=Ml(_l(n,t.config),"utf8")}catch(f){return s(`${t.config} cannot be read: ${f instanceof Error?f.message:String(f)}`)}if(i.length>xl)return s(`${t.config} is larger than ${xl} bytes`);let o;try{o=JSON.parse(i.replace(/^\uFEFF/,""))}catch{return s(`${t.config} is not JSON: a Frozen configuration is the panel's, as JSON`)}let a=nr(o);if(a.length>0)return{refusals:a.map(({path:f,secret:g})=>T(r,`${t.config} holds a key shaped like a secret (${g}) at ${f.join(".")}: a load never reads the salt, and the configuration holds no secret. Take it out.`))};let c=cc.strict().safeParse(o);if(!c.success)return{refusals:c.error.issues.map(f=>T(r,`${t.config} is refused by Frozen's configuration schema at ${f.path.map(String).join(".")||"its top"}: ${f.message}`))};let l=[],u={...c.data},d=Qm.filter(f=>u[f]!==void 0);for(let f of d)delete u[f];return d.length>0&&l.push(T(r,`${t.config} gives ${d.join(" and ")}, which the environment sets: the loads are kept beside the state, and the dataset is the one the file pins`)),{run:{configFile:t.config,config:u,dataset:{...t.dataset}},warnings:l}}function Bl(e){return{kind:"frozen",kindVersion:1,dataset:{digest:e.dataset.digest,version:e.dataset.version},load:Object.fromEntries(Xm.map(t=>[t,e.config[t]??null]))}}function Kl(e,t){return{...e.config,sasDir:t.sasDir,datasetDir:t.datasetDir}}async function Ul(e,t){let n,r;try{n=await Tc(e),r=JSON.parse(Ml(_l(e,"manifest.json"),"utf8")).version}catch(s){return{refusal:`its dataset at ${e} cannot be read: ${s instanceof Error?s.message:String(s)}`}}return n!==t.digest?{refusal:`its dataset at ${e} has the digest ${n}, and the file pins ${t.digest}: it is not the dataset the file was reviewed with. Point the path at that one, or pin this digest once this dataset is reviewed`}:r!==t.version?{refusal:`its dataset at ${e} is version ${String(r)}, and the file pins version ${t.version}: pin the version its manifest says`}:{digest:n,version:t.version}}function ln(e,t){return[e,"--config",I("--config",t.configFile),"--target",I("--target",t.target)]}function Vl(e){return[...ln("load",e),...e.reload?["--reload"]:[],...e.reload&&e.goneFirst!==void 0?["--gone-first",I("--gone-first",e.goneFirst)]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],...e.store!==void 0?["--store",I("--store",e.store)]:[],"--dry-run","--json"]}function Wl(e){return[...ln("load",e),...e.reload?["--reload"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],"--max-total",String(e.maxTotal),"--yes","--json"]}function Jl(e){return[...ln("verify",e),"--json"]}function Yl(e){return[...ln("remove",e),...e.includeChanged===!0?["--include-changed"]:[],...Ce(e),...e.acceptAutomation===!0?["--accept-automation"]:[],"--yes","--json"]}function Gl(e){return[...ln("remove",e),...e.includeChanged===!0?["--include-changed"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],"--preview",...Ce(e),"--json"]}var Zm=p.object({type:p.string().min(1),payload:p.record(p.string(),p.unknown()).optional()}).loose(),un={tool:p.literal(Q),posted:p.array(Zm),dataset:p.object({dir:p.string().min(1),digest:p.string().min(1),version:p.string().optional()}).optional(),mapping:p.string().min(1).optional(),refusals:p.array(p.string()).optional(),refusalCodes:p.array(p.string()).optional(),ended:p.literal(!0).optional()},Hl=p.object({status:p.enum(["PASSED","PARTIAL","FAILED","UNSTABLE"]),objects:p.array(p.object({objectApiName:p.string().min(1),verdict:p.enum(["PASSED","FAILED"]),expected:A,found:A,notLoaded:A,orphans:A,missingKeys:A}))}),eg=p.object({...un,step:p.literal("load"),objects:p.array(p.object({objectApiName:p.string().min(1),fromFiles:A,toInsert:A,toLink:A,notSent:A,toPurge:A,toDeactivate:A})).optional()}),tg=p.object({...un,step:p.literal("load"),objects:p.array(p.object({objectApiName:p.string().min(1),fromFiles:A,inserted:A,reused:A,duplicates:A,failed:A})).optional(),verdict:Hl.optional()}),ng=p.object({...un,step:p.literal("verify"),verdict:Hl.optional()});function dn(e,t){return e.filter(n=>n.type===t).at(-1)?.payload}function fn(e){let t=e.find(s=>s.type.endsWith(":error"))?.payload;if(t===void 0)return;let n=typeof t.message=="string"?t.message:"refused",r=typeof t.code=="string"?t.code:void 0;return{message:n,...r!==void 0?{code:r}:{}}}var rg=p.object({...un,step:p.literal("remove")}).transform((e,t)=>{let n=fn(e.posted.filter(g=>g.type!=="frozen:remove:automation:error")),r={planned:0,objects:[],userNames:{}};if(n!==void 0&&!ql.has(n.code??""))return{tool:e.tool,preview:r,refusals:[n.message],...n.code!==void 0?{refusalCodes:[n.code]}:{},removalAlone:[]};let s=dn(e.posted,"frozen:remove:preview:response")?.preview;if(s===void 0)return{tool:e.tool,preview:r,refusals:[],removalAlone:[]};let i=Rt.extend({refusals:p.array(p.string()),refusalCodes:p.array(p.string()).optional()}).loose().safeParse(s);if(!i.success)return t.addIssue({code:"custom",message:`its preview: ${i.error.issues[0]?.message}`}),p.NEVER;let{refusals:o,refusalCodes:a,...c}=i.data,l=e.refusals??[],u=new Map(e.refusalCodes?.length===l.length?l.map((g,y)=>[g,e.refusalCodes?.[y]??""]):[]),d=l.filter(g=>!o.includes(g)),f=d.flatMap(g=>u.get(g)??[]);return{tool:e.tool,preview:c,refusals:o,...a?.length===o.length?{refusalCodes:a}:{},removalAlone:d,...f.length===d.length&&f.length>0?{removalAloneCodes:f}:{}}}),sg=p.object({...un,step:p.literal("remove"),status:p.string().optional()}).transform((e,t)=>{let n=fn(e.posted),r={tool:e.tool,result:{status:"success",planned:0,objects:[]}};if(n!==void 0)return ql.has(n.code??"")?r:(t.addIssue({code:"custom",message:`the removal was refused: ${n.message}`}),p.NEVER);let s=dn(e.posted,"frozen:remove:response")?.result;if(s===void 0)return r;let i=p.object({status:p.enum(["success","partial","failure","cancelled"]),objects:p.array(St.loose())}).loose().safeParse(s);return i.success?{tool:e.tool,result:{status:i.data.status,planned:i.data.objects.reduce((o,a)=>o+a.planned,0),objects:i.data.objects}}:(t.addIssue({code:"custom",message:`its result: ${i.error.issues[0]?.message}`}),p.NEVER)});function Ql(e){return z(Q,"the answer of a dry run",eg,e)}function Cr(e){return z(Q,"the answer of a load",tg,e)}function Xl(e){return z(Q,"a verification",ng,e)}function Zl(e){return z(Q,"the preview of a removal",rg,e)}function eu(e){return z(Q,"the outcome of a removal",sg,e)}function ig(e){let n=(Array.isArray(e?.removals)?e.removals:[]).flatMap(r=>{let s=r;return s.reason==="may-hold-masks"?[`${String(s.objectApiName)}.${String(s.field)} (${Number(s.affectedRecords??0)})`]:[]});return n.length>0?[`it would leave out, encrypted in the target, ${n.join(", ")}: the dataset's manifest does not say its extraction left out what it read masked, so they may hold masks such as ****1234`]:[]}function og(e){return(Array.isArray(e?.perObject)?e.perObject:[]).flatMap(n=>{let r=n,s=Number(r.picklistsRewritten??0),i=Number(r.fieldsDropped??0),o=[s>0?`${s} picklist value(s) a restricted picklist of the target refuses, rewritten by their rule`:"",i>0?`${i} field(s) the target lacks or takes no value of, dropped`:""].filter(Boolean);return o.length>0?[`${String(r.objectApiName)}: ${o.join(", ")}`]:[]})}function ag(e){let t=e?.emails?.counted;return Array.isArray(t)?t.flatMap(n=>{let{limit:r,emails:s}=n??{};return(r==="SingleEmail"||r==="DailyWorkflowEmails")&&typeof s=="number"?[{limit:r,emails:s}]:[]}):[]}function tu(e){let t=fn(e.posted),n=[...t!==void 0?[t.message]:[],...e.refusals??[]],r=e.objects??[],s=r.reduce((u,d)=>u+d.toInsert,0),i=dn(e.posted,"frozen:load:preview:response")?.plan,o=n.length>0?n.join(" "):e.objects===void 0?"the load never came to say what it would write, and a run held to no count is held to nothing":s===0?"it would insert nothing: every record of the dataset is one the org holds already, linked by its identity keys, or one the load does not send":void 0,a=[...ig(i),...og(i)],c=e.refusals??[],l=o!==void 0?ze(o,n,[...t!==void 0?[t.code??""]:[],...e.refusalCodes?.length===c.length?e.refusalCodes:c.map(()=>"")]):[];return{objects:r.map(u=>({object:u.objectApiName,wouldCreate:u.toInsert})),total:s,created:s,storageBytes:r.reduce((u,d)=>u+hc(d.objectApiName,{rows:d.toInsert}),0),emails:ag(i),...o!==void 0?{refusal:o}:{},...l.length>0?{refusalCodes:l}:{},...a.length>0?{notes:a}:{}}}function pn(e){let t=fn(e.posted),n=(e.objects??[]).map(r=>({object:r.objectApiName,created:r.inserted,refused:r.failed,errors:r.failed>0?[`${r.failed} refused by the org`]:[]}));return n.length===0&&t!==void 0?{objects:[],created:0,refusal:t.message}:{objects:n,created:n.reduce((r,s)=>r+s.created,0)}}function jr(e){let n=dn(e.posted,"frozen:load:response")?.report?.purge;if(n===void 0)return!1;let r=Object.values(n.leftUnrecorded??{}).reduce((s,i)=>s+i,0);return(n.failures??[]).length===0&&r===0}function nu(e){let t=dn(e.posted,"frozen:load:response")?.report;return[...Object.values(t?.purge?.deleted??{}),...Object.values(t?.purge?.deactivated??{})].some(r=>r>0)}function bi(e){if(e.status==="UNSTABLE")return{unstable:!0,short:"no two readings of the org agreed: something still writes to the load\u2019s records; verify again once it is done"};let t=e.objects.filter(n=>n.verdict==="FAILED").map(n=>{let r=[`${n.found} of ${n.expected} found`,n.orphans>0?`${n.orphans} orphan(s)`:"",n.missingKeys>0?`${n.missingKeys} key(s) missing`:"",n.notLoaded>0?`${n.notLoaded} not loaded`:""].filter(Boolean);return`${n.objectApiName} FAILED (${r.join(", ")})`});return t.length>0?{unstable:!1,short:t.join("; ")}:e.status!=="PASSED"?{unstable:!1,short:`its verdict is ${e.status}`}:{unstable:!1}}function ru(e){let t=fn(e.posted);if(e.verdict===void 0)return{unread:t?.message??"the verification gave no verdict"};let{short:n,unstable:r}=bi(e.verdict);return r?{unread:n??"no two readings agreed"}:{failed:n!==void 0?[n]:[]}}function Ve(e){return`frozen/${e}`}function Nr(e){return e!==void 0&&/^frozen\/[a-z][a-z0-9-]{0,62}$/.test(e)?e.slice(7):void 0}import{existsSync as Ei}from"node:fs";import{rm as cg}from"node:fs/promises";import{join as su}from"node:path";var se="sandforge-dataops",iu="snapshots.json";function ou(e){let t={},n=[];for(let[r,s]of Object.entries(e)){let i=ac.safeParse({name:r,rules:s.rules});if(!i.success){n.push(...i.error.issues.map(o=>T(["masking",r,...o.path],`refused by the rules the DataOps panel saves: ${o.message}`)));continue}t[r]={name:r,rules:s.rules}}return n.length>0?{refusals:n}:{sets:t}}function lg(e){let t=Zs.find(r=>r.id===e);if(t===void 0)return;let n=t.rules.flatMap(r=>{if(!Va(r.ruleType))return[];let s="config"in r?r.config:void 0;return[{fieldPattern:r.fieldPattern,ruleType:r.ruleType,...s!==void 0?{config:{...s}}:{}}]});return{name:t.name,rules:n}}function au(e,t,n){let r=["resources",e,"rules"],s,i;if(typeof t.rules=="string"){if(s=n[t.rules],i={set:t.rules},s===void 0)return{refusals:[T(r,`the rule set ${t.rules} is refused: see masking`)]}}else{let d=t.rules.template;if(s=lg(d),i={template:d},s===void 0)return{refusals:[T([...r,"template"],`there is no DataOps template "${d}" that ships: there is `+Zs.map(f=>f.id).join(", "))]}}let o=t.object;if(o!==void 0&&!Fc({id:s.name,name:s.name,rules:s.rules},o))return{refusals:[T(["resources",e,"object"],`${"set"in i?`the rule set ${i.set}`:`the template ${i.template}`} has no rule for ${o}: a run would mask nothing. Name an object its rules mask, or give it a rule for this one`)]};let a=[],c=`${(o??"").toLowerCase()}.`,l=new Map(s.rules.filter(d=>o!==void 0&&d.fieldPattern.toLowerCase().startsWith(c)).map(d=>[(d.fieldPattern.split(".")[1]??"").toLowerCase(),d.ruleType])),u=ug(t.where).filter(({field:d,empty:f})=>{let g=l.get(d.toLowerCase());return g!==void 0&&(!f||g==="nullify")}).map(({field:d})=>d);return u.length>0&&a.push(T(["resources",e,"where"],`its condition reads ${u.join(", ")}, which its rules write over: once masked, its records may no longer be those it selects, and a plan after reads them as gone. Select them by a field its rules leave as it is`)),{run:{source:i,rules:s,...o!==void 0?{object:o}:{},...t.where!==void 0?{where:t.where}:{},...t.accept?.automation===!0?{acceptAutomation:!0}:{}},warnings:a}}function ug(e){if(e===void 0)return[];let t=e.replace(/'(?:[^'\\]|\\.)*'/g,"''"),n=new Map;for(let r of t.matchAll(/\b([A-Za-z][A-Za-z0-9_]*)\s*(=|!=|<>|<=|>=|<|>|\s(?:NOT\s+)?(?:LIKE|IN|INCLUDES|EXCLUDES)\b)\s*(null\b)?/gi)){let s=r[1]??"";if(/^(?:AND|OR|NOT)$/i.test(s))continue;let i=/^(?:=|!=|<>)$/.test(r[2]??"")&&r[3]!==void 0;n.set(s,(n.get(s)??!0)&&i)}return[...n].map(([r,s])=>({field:r,empty:s}))}function cu(e){return{kind:"mask",kindVersion:1,rules:[...e.rules.rules].map(t=>({...t,fieldPattern:t.fieldPattern.toLowerCase()})).sort((t,n)=>Et(t).localeCompare(Et(n))),object:e.object??null,where:e.where??null}}function lu(e){if(e.object!==void 0)return[{object:e.object}];let t=[];for(let n of e.rules.rules){let r=n.fieldPattern.split(".")[0]??"";t.includes(r)||t.push(r)}return t.map(n=>({object:n}))}function uu(e){return{name:e.rules.name,rules:e.rules.rules}}function jt(e){return`dataops/${e}`}function du(e){let{run:t}=e;return["anonymize","--org",I("--org",e.target),...t.object!==void 0?["--object",I("--object",t.object)]:[],...t.where!==void 0?["--where",I("--where",t.where)]:[],..."template"in t.source?["--template",I("--template",t.source.template)]:["--rules",I("--rules",e.rulesFile)],"--store",I("--store",e.store),...t.acceptAutomation===!0?["--accept-automation"]:[]]}function fu(e){return[...du(e),"--dry-run","--json"]}function pu(e){return[...du(e),"--yes","--json"]}var dg=p.object({type:p.string().min(1),payload:p.record(p.string(),p.unknown()).optional()}).loose(),Ot=p.number().int().nonnegative(),hu={tool:p.literal(se),org:p.string().min(1),posted:p.array(dg)},fg=p.object({...hu,command:p.literal("dry-run")}),pg=p.object({...hu,command:p.literal("run")});function mu(e){return z(se,"the answer of a dry run",fg,e)}function Ir(e){return z(se,"the answer of a masking",pg,e)}function Ct(e,t){return e.filter(n=>n.type===t).at(-1)?.payload}function gu(e){let t=Ct(e,"dataops:error");if(t!==void 0)return typeof t.message=="string"?t.message:"refused"}var hg=p.object({objects:p.array(p.object({objectApiName:p.string().min(1),count:Ot.nullable()}).loose())}),mg=p.object({objects:p.array(p.object({objectApiName:p.string().min(1),fields:p.array(p.string()),error:p.string().optional(),notCovered:p.literal(!0).optional(),writeDenied:p.object({deniedFields:p.array(p.string())}).optional()}).loose()),fieldsNotFound:p.array(p.object({objectApiName:p.string(),fieldApiName:p.string()}))}),gg=p.object({emails:p.array(p.object({limit:p.enum(["SingleEmail","DailyWorkflowEmails"]),emails:Ot}).loose()),refusals:p.array(p.object({code:p.string(),message:p.string()}).loose())}).loose();function yu(e){let t=[],n=gu(e.posted);n!==void 0&&t.push(n);let r=hg.safeParse(Ct(e.posted,"dataops:anonymize:coverage:response")),s=mg.safeParse(Ct(e.posted,"dataops:anonymize:preview:response"));if(!r.success||!s.success)return n===void 0&&t.push("the masking never came to say what it would mask, and a run nobody counted is masked blind"),{objects:[],refusals:t,refusalCodes:t.map(()=>""),emails:[]};let i=gg.safeParse(Ct(e.posted,"dataops:automation:response")),o=r.data.objects.map(l=>({object:l.objectApiName,count:l.count}));for(let l of o)l.count===null&&t.push(`${l.object}: the org did not count the records it would mask`);for(let l of s.data.objects){l.error!==void 0?t.push(`${l.objectApiName}: not read: ${l.error}`):l.notCovered===!0&&t.push(`${l.objectApiName}: its rules mask no field the org shows this user: a run would mask nothing there`);let u=l.writeDenied?.deniedFields;u?.length===0&&t.push(ni(l.objectApiName));for(let d of u??[])t.push(ni(l.objectApiName,d))}for(let l of s.data.fieldsNotFound)t.push(ti(l.objectApiName,l.fieldApiName));let a=new Map;for(let l of i.success?i.data.refusals:[])t.push(l.message),a.set(l.message,l.code);let c=i.success?i.data.emails.map(({limit:l,emails:u})=>({limit:l,emails:u})):[];return{objects:o,refusals:t,refusalCodes:t.map(l=>a.get(l)??""),emails:c}}function wu(e){let t=yu(e),n=t.objects.map(i=>({object:i.object,wouldCreate:i.count??0})),r=t.refusals.length>0?t.refusals.join(" "):void 0,s=r!==void 0?ze(r,t.refusals,t.refusalCodes):[];return{objects:n,total:n.reduce((i,o)=>i+o.wouldCreate,0),created:0,storageBytes:0,emails:t.emails,...r!==void 0?{refusal:r}:{},...s.length>0?{refusalCodes:s}:{}}}var yg=p.object({status:p.string().optional(),objects:p.array(p.object({objectApiName:p.string().min(1),total:Ot,processed:Ot,failed:Ot,notMasked:Ot}).loose()).optional(),fieldsNotFound:p.array(p.object({objectApiName:p.string(),fieldApiName:p.string()})).optional(),snapshot:p.object({operationId:p.string().min(1).max(200)}).loose().optional(),message:p.string().optional(),errors:p.array(p.object({objectApiName:p.string(),message:p.string()})).optional()}).loose();function hn(e){let t=yg.safeParse(Ct(e.posted,"dataops:anonymize:response")??Ct(e.posted,"dataops:error")??{}),n=t.success?t.data:{},r=(n.objects??[]).map(o=>({object:o.objectApiName,masked:o.processed,refused:o.failed,notMasked:o.notMasked})),s=gu(e.posted),i=(n.fieldsNotFound??[]).map(o=>ti(o.objectApiName,o.fieldApiName));return{objects:r,...n.snapshot!==void 0?{snapshotId:n.snapshot.operationId}:{},...s!==void 0?{refusal:s}:{},...i.length>0?{short:i.join("; ")}:{}}}function vu(e,t){let n=yu(t),r=e.runs.at(-1),s=new Map((r?.objects??[]).map(a=>[a.objectApiName,a.masked??0]));if(n.refusals.length>0)return{objects:[],masked:0,unread:n.refusals.join(" ")};let i=[],o=[];for(let{object:a,count:c}of n.objects){let l=c??0,u=s.get(a)??0;o.push({object:a,present:Math.min(l,u),...l<u?{gone:u-l}:{}}),l>u?i.push(`${a} ${l} under its condition, ${u} masked: ${l-u} more, which hold their original values`):l<u&&i.push(`${a} ${l} under its condition, ${u} masked: ${u-l} gone`)}return{objects:o,masked:[...s.values()].reduce((a,c)=>a+c,0),...i.length>0?{drift:i.join("; ")}:{}}}function Si(e,t){return`${ue("dataops")} anonymize --org ${e.alias} --restore ${t} --store ${e.store??"<its store>"}`}function ku(e,t){return t.store??`${jt(e)} beside the state`}function bu(e,t){return[`masking is one-way: each run first takes a snapshot of the values it writes over, kept on this machine in ${ku(e,t)}, and destroy never puts them back: it deletes the snapshots. Putting them back is your own act, before a destroy: `+Si(t,"<the snapshot its run names>")]}function Eu(e){return e.runs.find(t=>t.takenBack!==!0)}function wg(e){let t=Eu(e);return t?.snapshotId!==void 0?`snapshot ${t.snapshotId}, run ${t.n}'s`:t!==void 0?`the snapshot run ${t.n} took`:"the snapshot its first run took"}function Ri(e){return`it masks again what its condition selects, the records it masked before a second time, and takes nothing back first: the values they held before any masking stay only in ${wg(e)}, which destroy deletes`}var Su={applying:"its last masking was stopped part way",partial:"its last masking left values as they were: records the org refused, or fields it does not show this user",failed:"its last masking failed",destroying:"a deletion of its snapshots was stopped part way"};function Ru(e){return`applied, and its condition selects the ${e} record(s) it masked, with the same rules: masked again they would only be masked twice`}function $u(e,t){return`its condition selects other records than it masked: ${t}. Left as they are: --replace ${e} or --replace-drifted masks them all again`}function $i(e,t,n,r){let s=Eu(n)?.snapshotId;return`${e==="destroy"?"taken back by destroy, which never unmasks":"in the state, gone from the file"}: its records stay masked, and its store, ${ku(t,r)}, is deleted from this machine with its snapshots, the only copy of the values they held. `+(s!==void 0?`To put back those they held before any masking, before this ${e}, as your own act: ${Si(r,s)}`:`Its snapshots are listed in its store: ${Si(r,"<snapshot>")} puts one back, before this ${e}, as your own act`)}async function Au(e){if(!Ei(e))return{snapshots:[]};let t=Ei(su(e,iu))?vc(su(e,iu)).getKeysByPrefix("backup:").map(n=>n.slice(7)).filter(n=>!n.includes(":")):[];if(await cg(e,{recursive:!0,force:!0}),Ei(e))throw new Error(`${e} is still there: delete it, it holds the values a masking wrote over`);return{snapshots:[...new Set(t)].sort()}}function Ou(e,t){let n=t.snapshots.length>0?`its snapshot${t.snapshots.length===1?"":"s"} ${t.snapshots.join(", ")}`:"no snapshot";return`${e}: its records stay masked \u2014 destroy never unmasks \u2014, and ${n}, the only copy of the values they held, deleted from this machine with its store`}var Y="sandforge-seed",vg="In the file: fit: share seeds the largest share of each count that fits, fit: { withinMB: <MB> } no more than that; or lower each object\u2019s count.";function Nu(e,t,n,r){let s=kg(e,t,n,r);if("refusal"in s)return{refusals:[s.refusal]};let i=Eg(t,n,s.run);return i.refusals.length>0?{refusals:i.refusals}:{run:s.run,warnings:i.warnings}}function kg(e,t,n,r){let s=r.toISOString(),i={id:`env-${e}-${t}`,name:`${e}/${t}`,description:`The ${t} resource of the ${e} environment`,version:1,tags:["sandforge-env"],createdAt:s,updatedAt:s},o,a=[];if(n.template!==void 0){let l=Qs.find(u=>u.id===n.template);if(l===void 0)return{refusal:T(["resources",t,"template"],`there is no built-in template "${n.template}": there is ${Qs.map(u=>u.id).join(", ")}`)};o={...i,strategy:l.strategy,objects:structuredClone(l.objects),...l.relations!==void 0?{relations:structuredClone(l.relations)}:{}}}else o={...i,strategy:"faker",objects:(n.objects??[]).map((l,u)=>({objectApiName:l.object,recordCount:l.count,fieldRules:structuredClone(l.fields??[]),excludedFields:[],insertOrder:u,batchSize:l.batchSize??200})),...n.relations!==void 0?{relations:n.relations.flatMap((l,u)=>{let d=l.parents.from;if(d===void 0)return[Cu(l)];let{childObject:f,lookupField:g,parentObject:y,distribution:m}=Cu(l);return a.push({at:u,relation:{childObject:f,lookupField:g,parentObject:y,distribution:m},from:d.split(".")[0]??d,...l.parents.limit!==void 0?{limit:l.parents.limit}:{}}),[]})}:{}};let c=Object.fromEntries((n.objects??[]).filter(l=>l.recordTypes!==void 0).map(l=>[l.object,[...new Set(l.recordTypes)]]));return{run:{template:o,...n.locale!==void 0?{locale:n.locale}:{},...n.seed!==void 0?{seed:n.seed}:{},...Object.keys(c).length>0?{recordTypes:c}:{},...n.fit!==void 0?{fit:n.fit==="share"?{}:{withinMB:n.fit.withinMB}}:{},acceptAutomation:n.accept?.automation===!0,...a.length>0?{draws:a}:{}}}}function bg(e){return e.object??e.from?.split(".")[1]??""}function Cu(e){let[t="",n=""]=e.lookup.split("."),r=e.parents.existing;return{childObject:t,lookupField:n,parentObject:bg(e.parents),parents:r===void 0?{kind:"generated"}:{kind:"existing",...r.where!==void 0?{where:r.where}:{},limit:r.limit},distribution:e.distribution}}function Iu(e){return{kind:"existing",limit:e.limit??tr.maxExistingParents}}function Du(e,t){let n=[...e.template.relations??[]],r=e.draws??[],s=[];for(let i=0;i<n.length+r.length;i++){let o=r.find(c=>c.at===i),a=o!==void 0?{...o.relation,parents:t(o)}:n.shift();a!==void 0&&s.push(a)}return s}function Ai(e,t,n){return(e.draws??[]).length===0?e.template:{...e.template,relations:Du(e,r=>{let s=t?.get(r.at);if(s!==void 0&&s.length>0)return{kind:"records",ids:[...s]};if(!n.standIns)throw new Error(`The relation on ${r.relation.childObject}.${r.relation.lookupField} draws its parents from ${r.from}, whose records are not known: plan again.`);return Iu(r)})}}var ju=Object.keys(Nc);function Eg(e,t,n){let r=["resources",e],s=Ai(n,void 0,{standIns:!0}),i=oc.safeParse(s);if(!i.success)return{refusals:i.error.issues.map(l=>T(Sg(r,t,l.path),l.message)),warnings:[]};let o=new Dc().validate(s),a=({field:l,message:u})=>T(Rg(r,t,s,l),u),c=n.locale!==void 0&&!ju.includes(n.locale)?[T([...r,"locale"],`the seed draws in ${ju.join(", ")}, not ${n.locale}: name one of them, or leave locale out to draw in the org\u2019s own`)]:[];return{refusals:[...o.errors.map(a),...c],warnings:o.warnings.map(a)}}function Sg(e,t,n){if(t.template!==void 0)return[...e,"template"];let[r,s,i,...o]=n;if(r==="objects"&&typeof s=="number"){let a=[...e,"objects",s];return i==="objectApiName"?[...a,"object"]:i==="recordCount"?[...a,"count"]:i==="fieldRules"?[...a,"fields",...o]:i===void 0?a:[...a,i]}if(r==="relations"&&typeof s=="number"){let a=[...e,"relations",s];return i==="childObject"||i==="lookupField"?[...a,"lookup"]:i==="parentObject"?[...a,"parents","object"]:i==="parents"?[...a,"parents","existing",...o]:i===void 0?a:[...a,i,...o]}return e}function Rg(e,t,n,r){if(t.template!==void 0)return[...e,"template"];let s=/^objects\[([^\]]+)\](?:\.fieldRules\[([^\]]+)\])?/.exec(r);if(s!==null){let o=n.objects.findIndex(l=>l.objectApiName===s[1]);if(o<0)return e;let a=s[2],c=a===void 0?-1:(n.objects[o]?.fieldRules??[]).findIndex(l=>l.fieldApiName===a);return c<0?[...e,"objects",o]:[...e,"objects",o,"fields",c]}let i=/^relations\[([^\]]+)\]/.exec(r);if(i!==null){let o=(n.relations??[]).findIndex(a=>`${a.childObject}.${a.lookupField}`===i[1]);return o<0?e:[...e,"relations",o]}return e}function Tu(e){let{template:t}=e;return{kind:"seed",kindVersion:1,strategy:t.strategy,objects:t.objects.map(n=>({objectApiName:n.objectApiName,recordCount:n.recordCount,recordTypeId:n.recordTypeId,fieldRules:n.fieldRules,excludedFields:n.excludedFields,insertOrder:n.insertOrder})),relations:t.relations??[],locale:e.locale??null,seed:e.seed??null,recordTypes:e.recordTypes??{},draws:e.draws,...e.fit!==void 0?{fit:e.fit}:{}}}function Pu(e){return e.template.objects.map(t=>({object:t.objectApiName,count:t.recordCount}))}function Lu(e){let{template:t}=e,n=Du(e,Iu),r=new Set(n.filter(s=>s.parents.kind==="existing").map(s=>s.childObject));for(let s=!0;s;){s=!1;for(let i of t.objects)r.has(i.objectApiName)||Ua(i,n).some(o=>r.has(o))&&(r.add(i.objectApiName),s=!0)}return new Map(t.objects.filter(s=>r.has(s.objectApiName)).map(s=>[s.objectApiName,s.recordCount]))}function Fu(e){return["--target",I("--target",e.target),"--template-file",I("--template-file",e.templateFile),"--run-id",I("--run-id",e.runId),...e.seed!==void 0?["--seed",String(e.seed)]:[],...e.locale!==void 0?["--locale",I("--locale",e.locale)]:[],...Object.entries(e.recordTypes??{}).flatMap(([t,n])=>["--record-type",I("--record-type",`${t}=${n.join(",")}`)]),...e.fit!==void 0?["--fit","share",...e.fit.withinMB!==void 0?["--fit-within",String(e.fit.withinMB)]:[]]:[]]}function xu(e){return[...Fu(e),"--json","--fail-on-partial"]}function Mu(e){return[...Fu(e),"--dry-run","--json"]}function _u(e){return[...e.includeChanged===!0?["--include-changed"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],...e.leaveUndeletable===!0?["--leave-undeletable"]:[]]}function qu(e){return["--remove",I("--remove",e.summary),"--target",I("--target",e.target),..._u(e),...Ce(e),"--json"]}function zu(e){return["--remove",I("--remove",e.summary),"--target",I("--target",e.target),"--preview",..._u(e),...Ce(e),"--json"]}var $g=p.object({limit:p.enum(["SingleEmail","DailyWorkflowEmails"]),emails:A,verdict:p.enum(["fits","exceeds","unread"]),remaining:p.number().int().optional(),max:p.number().int().optional(),unread:p.string().optional()}),Ag=p.object({checks:p.array($g),refusal:p.string().optional(),unknown:p.array(p.string()).optional()}),Og=p.object({records:A,given:A,refusal:p.string().optional()}),Cg=e=>p.object({objectApiName:p.string().min(1),recordsCreated:A,recordsFailed:A,createdIds:p.array(e),errors:p.array(p.string()),truncated:p.boolean().optional(),writtenByThePlatform:Og.optional()}),Bu=e=>p.object({templateId:p.string().optional(),operationId:p.string().min(1),status:p.enum(["success","partial","failure"]),cancelled:p.boolean().optional(),objectResults:p.array(Cg(e)),totalRecordsCreated:A,totalRecordsFailed:A}),Ku={tool:p.literal(Y),target:p.string().min(1),seed:p.number().int().nonnegative(),startedAt:p.string().min(1),finishedAt:p.string().min(1),notes:p.array(p.string()).optional(),emails:Ag,elapsedMs:A,interrupted:p.literal(!0).optional()},jg=p.object({...Ku,dryRun:p.literal(!1),targetOrgId:qe.optional(),result:Bu(qe),runFile:p.string().min(1).optional()}),Ng=p.object({bytes:A,verdict:p.enum(["fits","near","exceeds","unread"]),estimateMB:p.number().nonnegative(),maxMB:p.number().optional(),remainingMB:p.number().optional(),unread:p.string().optional(),refusal:p.string().optional()}),Ig=p.object({estimate:A,verdict:p.enum(["fits","near","exceeds","unread"]),max:p.number().int().optional(),remaining:p.number().int().optional(),unread:p.string().optional(),refusal:p.string().optional()}),Dg=p.object({...Ku,dryRun:p.literal(!0),storage:Ng,apiRequests:Ig,wouldBeRefused:p.array(p.string()).optional(),wouldBeRefusedCodes:p.array(p.string()).optional(),result:Bu(p.string())}),Tg=p.object({tool:p.literal(Y),action:p.literal("remove"),summary:p.string().min(1),target:p.string().min(1),includeChanged:p.boolean(),result:p.object({status:p.enum(["success","partial","failure","cancelled"]),planned:A,objects:p.array(St),sweep:p.object({status:p.string()}).loose().optional()}),elapsedMs:A}),Pg=p.object({tool:p.literal(Y),action:p.literal("remove-preview"),summary:p.string().min(1),target:p.string().min(1),includeChanged:p.boolean(),preview:Rt,refusals:p.array(p.string()),refusalCodes:p.array(p.string()).optional(),notes:p.array(p.string()),elapsedMs:A});function Nt(e){return z(Y,"the summary of a run",jg,e)}function Uu(e){return z(Y,"the summary of a dry run",Dg,e)}function Vu(e){return z(Y,"the preview of a removal",Pg,e)}function Wu(e){return z(Y,"the outcome of a removal",Tg,e)}var Ju="validation";function Yu(e,t){let n=e.result.objectResults,r=c=>{let l=ze(c,e.wouldBeRefused,e.wouldBeRefusedCodes);return l.length>0?{refusalCodes:l}:{}};if(e.result.status==="failure"&&n.length>0&&n.every(c=>c.objectApiName===Ju)){let c=n.flatMap(u=>u.errors),l=c.length>0?c.join(" "):"the seed refused its dry run";return{objects:[],total:0,created:0,apiRequests:e.apiRequests.estimate,storageBytes:0,emails:[],refusal:l,...r(l)}}let s=e.result.objectResults.map(c=>{let l=t?.get(c.objectApiName);return l!==void 0?{object:c.objectApiName,wouldCreate:Math.max(c.recordsCreated,l),atMost:!0}:{object:c.objectApiName,wouldCreate:c.recordsCreated}}),i=e.storage.refusal??e.apiRequests.refusal??e.emails.refusal,o=i!==void 0&&i===e.storage.refusal?`${i} ${vg}`:i,a=e.result.objectResults.flatMap(c=>c.writtenByThePlatform!==void 0?[Lg(c.objectApiName,c.writtenByThePlatform.records)]:[]);return{objects:s,total:e.result.totalRecordsCreated,created:e.result.totalRecordsCreated,apiRequests:e.apiRequests.estimate,storageBytes:e.storage.bytes,emails:e.emails.checks.map(c=>({limit:c.limit,emails:c.emails})),...o!==void 0&&i!==void 0?{refusal:o,...r(i)}:{},...a.length>0?{notes:a}:{}}}function Lg(e,t){return`${e}: ${t} record(s) linked to the contact role the platform writes with their opportunity, for its contact, not written: given the fields the seed generates for ${t===1?"it":"them"}`}function Dr(e){let t=e.result.objectResults;if(e.result.status==="failure"&&t.length>0&&t.every(n=>n.objectApiName===Ju)){let n=t.flatMap(r=>r.errors);return{objects:[],created:0,refusal:n.length>0?n.join(" "):"the seed refused its run before it wrote"}}return{objects:e.result.objectResults.map(n=>({object:n.objectApiName,created:n.recordsCreated,refused:n.recordsFailed,errors:n.errors})),created:e.result.totalRecordsCreated}}var Fg={seed:Y,forge:U,frozen:Q,mask:se};function xg(e){return e==="seed"||e==="forge"||e==="frozen"||e==="mask"}function Tr(e){if(!xg(e))throw new Error(`The state holds a resource of kind ${e}, which a later SandForge applies: this one applies seed, forge, frozen and mask resources, and takes back nothing of another kind.`);return Fg[e]}function Gu(e,t,n,r,s,i={}){switch(n.kind){case"seed":{let o=Nu(e,t,n,s);return"refusals"in o?o:{run:{kind:"seed",...o.run},warnings:o.warnings}}case"forge":{let o=yl(e,t,n,r,s);return"refusals"in o?o:{run:{kind:"forge",...o.run},warnings:o.warnings}}case"frozen":{let o=zl(t,n,r);return"refusals"in o?o:{run:{kind:"frozen",...o.run},warnings:o.warnings}}case"mask":{let o=au(t,n,i);return"refusals"in o?o:{run:{kind:"mask",...o.run},warnings:o.warnings}}}}function Hu(e){switch(e.kind){case"seed":return Tu(e.run);case"forge":return El(e.run,e.source.read);case"frozen":return Bl(e.run);case"mask":return cu(e.run)}}function It(e){switch(e.kind){case"seed":return Pu(e);case"forge":return wl(e);case"frozen":return[];case"mask":return lu(e)}}function lt(e){return e==="frozen"||e==="mask"}function Dt(e,t){switch(e.kind){case"seed":return Ai(e.run,t.drawn,{standIns:t.standIns===!0});case"forge":return e.run.template??{};case"frozen":{if(t.sasDir===void 0)throw new Error(`${e.name} is given no folder to keep its loads in: plan again.`);return Kl(e.run,{sasDir:t.sasDir,datasetDir:e.dataset.dir})}case"mask":return uu(e.run)}}function Qu(e,t){switch(e.kind){case"seed":{let n=e.run.seed??t.seed;return{script:Y,args:Mu({target:t.target,templateFile:t.templateFile,runId:t.runId,...n!==void 0?{seed:n}:{},...e.run.locale!==void 0?{locale:e.run.locale}:{},...e.run.recordTypes!==void 0?{recordTypes:e.run.recordTypes}:{},...e.run.fit!==void 0?{fit:e.run.fit}:{}})}}case"forge":return{script:U,args:Rl({...Zu(e),target:t.target,templateFile:t.templateFile,maxTotal:e.run.maxTotal??gl})};case"frozen":return{script:Q,args:Vl({configFile:t.templateFile,target:t.target,reload:t.replace===!0,acceptAutomation:t.acceptAutomation===!0,...t.storeFile!==void 0?{store:t.storeFile}:{},...t.goneFirstFile!==void 0?{goneFirst:t.goneFirstFile}:{}})};case"mask":return{script:se,args:fu({target:t.target,run:e.run,rulesFile:t.templateFile,store:Xu(e,t)})}}}function Xu(e,t){if(t.store===void 0)throw new Error(`${e.name} is given no store to keep its snapshots in: plan again.`);return t.store}function Zu(e){let{run:t,source:n}=e;if(t.wholeOrg)return{source:n.alias,wholeOrg:t.wholeOrg,acceptAutomation:t.acceptAutomation};if(t.tables!==void 0)return{source:n.alias,tables:t.tables,acceptAutomation:t.acceptAutomation};let r=n.read,s=t.record?.id??(r!==void 0&&"recordId"in r?r.recordId:void 0);if(s===void 0)throw new Error(`${e.name} names its record by a query its source has not answered: plan again.`);return{source:n.alias,recordId:s,acceptAutomation:t.acceptAutomation}}function ed(e,t){switch(e){case"seed":return Uu(t);case"forge":return Il(t);case"frozen":return Ql(t);case"mask":return mu(t)}}function Oi(e){return e.kind==="seed"?Lu(e.run):void 0}function td(e,t){return e.kind==="forge"&&t.tool===U?Nl(t,e.run.template):void 0}function Tt(e,t){switch(e.tool){case Y:return Yu(e,t);case U:return Ll(e);case Q:return tu(e);case se:return wu(e)}}function mn(e,t){switch(e.kind){case"seed":return{script:Y,args:xu({target:t.target,templateFile:t.templateFile,runId:t.runId,...t.seed!==void 0?{seed:t.seed}:{},...e.run.locale!==void 0?{locale:e.run.locale}:{},...e.run.recordTypes!==void 0?{recordTypes:e.run.recordTypes}:{},...e.run.fit!==void 0?{fit:e.run.fit}:{}})};case"forge":{if(t.maxTotal===void 0)throw new Error(`${e.name} has no count from its dry run to be held to: plan again.`);return{script:U,args:$l({...Zu(e),target:t.target,templateFile:t.templateFile,maxTotal:t.maxTotal,summary:t.summaryFile})}}case"frozen":{if(t.maxTotal===void 0)throw new Error(`${e.name} has no count from its dry run to be held to: plan again.`);return{script:Q,args:Wl({configFile:t.templateFile,target:t.target,reload:t.replace===!0,acceptAutomation:t.acceptAutomation===!0,maxTotal:t.maxTotal})}}case"mask":return{script:se,args:pu({target:t.target,run:e.run,rulesFile:t.templateFile,store:Xu(e,t)})}}}function Pr(e){throw new Error(`${Pe(e)} takes no run back: a masking is never undone, and its destroy deletes its store`)}function nd(e,t){let n=Tr(e),r=t.sweep===!0?{sweep:!0}:{},s={target:t.target,summary:t.subject,includeChanged:t.includeChanged,acceptAutomation:t.acceptAutomation,...r};switch(n){case Y:return{script:n,args:zu(s)};case U:return{script:n,args:Cl(s)};case Q:return{script:n,args:Gl({configFile:t.subject,target:t.target,includeChanged:t.includeChanged,acceptAutomation:t.acceptAutomation,...r})};case se:return Pr(n)}}function rd(e,t){let n=Tr(e);switch(n){case Y:return Vu(t);case U:return Tl(t);case Q:return Zl(t);case se:return Pr(n)}}function sd(e,t){if(e==="mask")return[];let n=[...t].reverse().filter(r=>r.takenBack!==!0);return e==="frozen"?n.slice(0,1):n}function id(e,t){if(e==="frozen")return{script:Q,args:Jl({configFile:t.subject,target:t.target})}}function od(e){return ru(Xl(e))}function ad(e,t){let n=Tr(e),r={target:t.target,summary:t.subject,includeChanged:t.includeChanged,acceptAutomation:t.acceptAutomation,sweep:t.sweep};switch(n){case Y:return{script:n,args:qu(r)};case U:return{script:n,args:Ol(r)};case Q:return{script:n,args:Yl({configFile:t.subject,target:t.target,includeChanged:t.includeChanged,sweep:t.sweep,acceptAutomation:t.acceptAutomation})};case se:return Pr(n)}}function cd(e,t){let n=Tr(e);switch(n){case Y:return Wu(t);case U:return Dl(t);case Q:return eu(t);case se:return Pr(n)}}function Ci(e){return e?.result.objects??[]}function ld(e,t){return e.kind==="mask"?bu(e.name,t):e.kind==="forge"?kl(e.run,e.source):[]}var nt=sm(Zp());import{isAbsolute as db,resolve as Wn}from"node:path";function da(e){return`${nn(e.path)}: ${e.message}`}var fb=100;function th(e){let t=e.startsWith("\uFEFF")?e.slice(1):e,n=(0,nt.parseDocument)(t,{version:"1.2",schema:"core",merge:!1,uniqueKeys:!1,prettyErrors:!0}),r=n.errors[0]??n.warnings[0];if(r)return{refusal:`The file does not read as YAML 1.2: ${r.message.split(`
|
|
147
|
-
`)[0]}`};let s=ua(n.contents,[]);if(s!==void 0)return{refusal:`${nn(s.path)} holds the key "${s.key}" twice: a mapping holds each key once, and the second would replace the first unseen. Keep one.`};try{return{document:n.toJS({maxAliasCount:fb})}}catch(i){return{refusal:`The file does not read as YAML 1.2: ${i instanceof Error?i.message:String(i)}`}}}function ua(e,t){if((0,nt.isMap)(e)){let n=new Set;for(let r of e.items){let s=(0,nt.isScalar)(r.key)?String(r.key.value):String(r.key);if(n.has(s))return{path:t,key:s};n.add(s);let i=ua(r.value,[...t,s]);if(i)return i}}else if((0,nt.isSeq)(e))for(let[n,r]of e.items.entries()){let s=ua(r,[...t,n]);if(s)return s}}function pb(e){return e==="salt"?"a Frozen load never reads its salt, and DataOps templates carry no hash salt: leave it out":"org credentials stay with the sf CLI \u2014 log the org in with sf org login sfdx-url or sf org login jwt before the step, and name it in the file by its alias"}function Jn(e,t,n={}){let r=[...nr(e).map(({path:f,secret:g})=>T(f,`a key shaped like a secret (${g}). The file holds no secret: ${pb(g)}.`)),...Ha(e).filter(({path:f})=>!Ja(f)).map(({path:f})=>T(f,`{ env } stands in ${Wa.join(" and ")} alone: write this value in the file. A variable inside a query or a field value would let a CI variable into what is written.`))];if(r.length>0)return{refusals:r};let s=Ga.safeParse(e);if(!s.success)return{refusals:s.error.issues.map(f=>{let g=f.path,y=f.code==="invalid_key"?f.issues.map(m=>m.message):[];return T(g,y.join("; ")||f.message)})};let i=s.data,o=mb(i);if("refusals"in o)return o;let a=ou(i.masking);if("refusals"in a)return a;let c=[],l=[...hb(i)],u={};for(let[f,g]of Object.entries(i.resources)){let y=Gu(i.name,f,g,Wn(t),n.now??new Date,a.sets);if("refusals"in y){c.push(...y.refusals);continue}l.push(...y.warnings),u[f]=y.run}if(c.push(...gb(u)),c.length>0)return{refusals:c};let d=[];for(let[f,{alias:g}]of Object.entries(i.orgs))typeof g!="string"&&d.push({name:g.env,path:["orgs",f,"alias"],role:f});for(let[f,g]of Object.entries(i.resources))g.kind==="frozen"&&typeof g.dataset.path!="string"&&d.push({name:g.dataset.path.env,path:["resources",f,"dataset","path"],resource:f});return{checked:{file:i,folder:Wn(t),order:o.order,runs:u,variables:d,warnings:l}}}function hb(e){let t=new Set(Object.values(e.resources).flatMap(n=>n.kind==="mask"&&typeof n.rules=="string"?[n.rules]:[]));return Object.keys(e.masking).filter(n=>!t.has(n)).map(n=>T(["masking",n],"no mask resource names this rule set: nothing masks with it"))}function nh(e,t){return e.variables.filter(n=>(t[n.name]??"").trim()==="")}function rh(e,t){return t.kind!=="seed"?[]:(t.relations??[]).flatMap((n,r)=>{let s=n.parents.from?.split(".")[0];return s===void 0?[]:[{from:s,path:["resources",e,"relations",r,"parents","from"]}]})}function fa(e,t){return[...new Set([...t.dependsOn??[],...rh(e,t).map(({from:n})=>n)])]}function mb(e){let t=Object.keys(e.resources),n=[],r=new Map;for(let[a,c]of Object.entries(e.resources)){let l=[];for(let{from:u,path:d}of rh(a,c))u===a?n.push(T(d,`a relation draws its parents from the records another resource created: ${a}'s own are drawn by their object alone, without from`)):u in e.resources?l.includes(u)||l.push(u):n.push(T(d,`"${u}" is no resource of this file: name one of ${t.join(", ")}`));(c.dependsOn??[]).forEach((u,d)=>{let f=["resources",a,"dependsOn",d];u===a?n.push(T(f,`a resource does not depend on itself: take ${a} out of its dependsOn`)):u in e.resources?l.includes(u)||l.push(u):n.push(T(f,`"${u}" is no resource of this file: name one of ${t.join(", ")}`))}),r.set(a,l)}if(n.length>0)return{refusals:n};let s=yb(t,r);if(s!==void 0)return{refusals:[T(["resources",s[0]??""],`the resources depend on each other in a circle, ${s.join(" \u2192 ")}: no order applies them. Take one of them out of the dependsOn of the next, or out of what its relations draw their parents from.`)]};let i=[],o=new Set;for(;i.length<t.length;){let a=t.find(c=>!o.has(c)&&(r.get(c)??[]).every(l=>o.has(l)));if(a===void 0)break;i.push(a),o.add(a)}return{order:i}}function gb(e){let t=[];for(let[n,r]of Object.entries(e))if(r.kind==="seed")for(let s of r.draws??[]){let i=e[s.from];if(i?.kind==="mask"){t.push(T(["resources",n,"relations",s.at,"parents","from"],`${s.from} is a mask resource, which creates no record: a relation draws its parents from the records a seed, a forge or a frozen resource created`));continue}if(i?.kind!=="seed")continue;let o=It(i).map(({object:a})=>a);o.includes(s.relation.parentObject)||t.push(T(["resources",n,"relations",s.at,"parents","from"],`${s.from} writes no ${s.relation.parentObject} records: it writes ${o.join(", ")||"none"}`))}return t}function yb(e,t){let n=new Set,r=[],s=i=>{let o=r.indexOf(i);if(o>=0)return[...r.slice(o),i];if(!n.has(i)){r.push(i);for(let a of t.get(i)??[]){let c=s(a);if(c!==void 0)return c}r.pop(),n.add(i)}};for(let i of e){let o=s(i);if(o!==void 0)return o}}function pa(e,t){return mi(Et({...Hu(e),dependsOn:t}))}var eh=/^[^-\s][^\s]{0,199}$/;function ha(e,t,n={}){let r=Object.keys(e.file.orgs),s=[],i=n.aliases??{};for(let[d,f]of Object.entries(i))r.includes(d)?eh.test(f)||s.push(T(["orgs",d,"alias"],`--alias ${d}= gives no alias: one holds no space and does not start with "-"`)):s.push(T(["orgs"],`--alias names the role ${d}, which the file's orgs do not declare: `+(r.length>0?`its roles are ${r.join(", ")}`:"it declares none")));let o={};for(let[d,{alias:f}]of Object.entries(e.file.orgs)){let g=i[d];if(g!==void 0){o[d]=g;continue}if(typeof f=="string"){o[d]=f;continue}let y=(t[f.env]??"").trim();y===""?s.push(T(["orgs",d,"alias"],`the variable ${f.env} is not set: set it in the job's environment to the alias of the ${d} org, or give --alias ${d}=<alias>`)):eh.test(y)?o[d]=y:s.push(T(["orgs",d,"alias"],`the variable ${f.env} holds no alias: one holds no space and does not start with "-"`))}let a={};for(let[d,f]of Object.entries(e.file.resources)){if(f.kind!=="frozen")continue;let g=wb(d,f.dataset.path,t,e.folder);"refusal"in g?s.push(g.refusal):a[d]=g.dir}if(s.length>0)return{refusals:s};let c={},l=[];for(let d of e.order){let f=e.runs[d],g=e.file.resources[d];if(f===void 0||g===void 0)continue;let y=fa(d,g),m;if(f.kind==="seed"){let{kind:h,...w}=f;m={name:d,kind:h,dependsOn:y,fingerprint:"",run:w}}else if(f.kind==="mask"){let{kind:h,...w}=f;m={name:d,kind:h,dependsOn:y,fingerprint:"",run:w}}else if(f.kind==="frozen"){let{kind:h,...w}=f,v=n.datasets?.[d];m={name:d,kind:h,dependsOn:y,fingerprint:"",run:w,dataset:{dir:a[d]??"",...v!==void 0?{read:v}:{}}}}else{let{kind:h,...w}=f,v=n.sources?.[d];m={name:d,kind:h,dependsOn:y,fingerprint:"",run:w,source:{role:w.source,alias:o[w.source]??"",...v!==void 0?{read:v}:{}}}}m.fingerprint=pa(m,Object.fromEntries(y.map(h=>[h,c[h]]))),c[d]=m.fingerprint,l.push(m)}let u=mi(Et({...e.file,orgs:Object.fromEntries(Object.entries(o).map(([d,f])=>[d,{alias:f}]))}));return{resolved:{checked:e,orgs:o,resources:l,digest:u}}}function wb(e,t,n,r){let s=["resources",e,"dataset","path"],i;if(typeof t=="string")i=t;else{if(i=(n[t.env]??"").trim(),i==="")return{refusal:T(s,`the variable ${t.env} is not set: set it in the job's environment to the folder the dataset of ${e} was downloaded to`)};if(!db(i))return{refusal:T(s,`the variable ${t.env} holds ${i}, which is not a path from the root: give the folder of the dataset from the root`)}}let o;try{o=cr(r)}catch{o=void 0}return o!==void 0&&new Oe(o).isInsideRepo(Wn(i))?{refusal:T(s,`the dataset of ${e}, ${Wn(i)}, is inside the repository ${o} that holds the file: a frozen dataset is pseudonymized business data, and stays outside the project. Keep it where the pipeline downloads it, and name that folder.`)}:{dir:Wn(i)}}function sh(e,t,n,r={}){let s=Jn(e,t,r.now?{now:r.now}:{});return"refusals"in s?s:ha(s.checked,n,{...r.aliases?{aliases:r.aliases}:{},...r.sources?{sources:r.sources}:{},...r.datasets?{datasets:r.datasets}:{}})}var oh=new Set(["create","replace","delete"]),Ie=new Set(["create","replace"]);function wa(e){return oh.has(e.action)}function De(e){return Object.entries(e?.resources??{}).filter(([,t])=>t.status!=="destroyed")}function va(e,t){let n=[],r=new Set,s=new Set(e);for(;n.length<e.length;){let i=e.find(o=>!r.has(o)&&t(o).every(a=>!s.has(a)||r.has(a)||a===o))??e.find(o=>!r.has(o));if(i===void 0)break;n.push(i),r.add(i)}return n}function rt(e,t){let n=e?.resources??{};return va(t,r=>n[r]?.dependsOn??[]).reverse()}function vb(e,t){return t===void 0||t.differs||t.unread!==void 0?!1:[...e.objects.values()].every(n=>n.gone===0&&n.unread===0)}function ma(e){let t={objects:new Map,changedBy:new Map,refusals:[],removalAlone:[],codes:new Map,failed:[],verified:[]};for(let n of e){if("failed"in n){t.failed.push(`run ${n.n}: ${n.failed}`);continue}if("nothing"in n)continue;let r=n.refreshed;r!==void 0&&"unread"in r?t.failed.push(`run ${n.n}: its verification did not say (${r.unread})`):r!==void 0&&t.verified.push(...r.failed);let{preview:s}=n.preview;for(let i of s.objects){let o=t.objects.get(i.objectApiName)??{present:0,gone:0,changed:0,unread:0};o.present+=i.toDelete+i.keptChanged+i.undeletable,o.gone+=i.alreadyGone+i.notVisible,o.changed+=i.changedSince,o.unread+=i.unread,t.objects.set(i.objectApiName,o);for(let[a,c]of Object.entries(i.changedBy)){let l=s.userNames[a]??a;t.changedBy.set(l,(t.changedBy.get(l)??0)+c)}}for(let i of n.preview.refusals)t.refusals.includes(i)||t.refusals.push(i);if(ih(t.codes,n.preview.refusals,n.preview.refusalCodes),"removalAlone"in n.preview){t.removalAlone.push(...n.preview.removalAlone);let i="removalAloneCodes"in n.preview?n.preview.removalAloneCodes:void 0;ih(t.codes,n.preview.removalAlone,i)}}return t}function ih(e,t,n){n?.length===t.length&&t.forEach((r,s)=>e.set(r,n[s]??""))}function ka(e){return[...e.refusals,...e.removalAlone]}function ga(e,t=ka(e)){return[...new Set(t.flatMap(n=>e.codes.get(n)||[]))]}function Ps(e){return e.length>0?{refusalCodes:[...new Set(e)]}:{}}function ya(e){return[...e.objects].map(([t,n])=>({object:t,present:n.present,gone:n.gone,changed:n.changed}))}function kb(e){let t=[...e.objects].flatMap(([s,i])=>{let o=[i.gone>0?`${i.gone} gone`:"",i.changed>0?`${i.changed} changed`:"",i.unread>0?`${i.unread} not read`:""].filter(Boolean);return o.length>0?[`${s} ${o.join(", ")}`]:[]});if(e.verified.length>0&&t.push(`its verification: ${e.verified.join("; ")}`),t.length===0)return;let n=[...e.changedBy].sort((s,i)=>i[1]-s[1]),r=n.length>0?` (last changed by ${n.map(([s,i])=>`${s} ${i}`).join(", ")})`:"";return`${t.join("; ")}${r}`}var bb="its state was recovered from its run files, which do not say what it was applied from",Eb={applying:"its last run was stopped part way: what it wrote is taken back from its run file, then it runs again",partial:"its last run was partial: the org refused records of it, or kept some of its records",failed:"its last run failed",destroying:"a removal of it was stopped part way"};function Sb(e){if(e.kind==="frozen"){let n=e.dataset.read;return n===void 0?`its dataset at ${e.dataset.dir} was not read: plan again`:"refusal"in n?n.refusal:void 0}if(e.kind!=="forge")return;let t=e.source.read;return t===void 0?`its source, the ${e.source.role} org, was not read: plan again`:"refusal"in t?t.refusal:void 0}function ba(e){let{resolved:t,state:n,previews:r}=e,s=r===void 0,i=new Set(e.replace??[]),o=new Map(De(n)),a=new Set(t.resources.map(u=>u.name)),c=new Map;for(let u of t.resources){let d=o.get(u.name),f=Sb(u),g=u.kind;if(d===void 0){c.set(u.name,{resource:u.name,kind:g,action:"create",why:n?.resources[u.name]?.status==="destroyed"?"taken back by an earlier destroy: applied again":"not applied to this org yet",objects:[],...f!==void 0?{refusal:f}:{}});continue}let y=ma(r?.[u.name]??[]),m=[],h=pa(u,Object.fromEntries(u.dependsOn.map(j=>[j,n?.resources[j]?.fingerprint])));d.recovered===!0?m.push(bb):d.fingerprint!==u.fingerprint&&d.fingerprint!==h&&m.push("what it writes changed in the file since it was applied");let w=(g==="mask"?Su:Eb)[d.status];w!==void 0&&m.push(w);let v=u.dependsOn.filter(j=>{let D=c.get(j);return D!==void 0&&Ie.has(D.action)&&D.kind!=="mask"});if(v.length>0&&m.push(`the resources it depends on run again, with new records: ${v.join(", ")}`),i.has(u.name)&&m.push("--replace asks it"),g==="mask"){c.set(u.name,Rb(u.name,d,m,e,s));continue}let k=s?void 0:kb(y),b=k!==void 0&&vb(y,e.drift),S=b?void 0:k;m.length===0&&S!==void 0&&e.replaceDrifted===!0&&m.push(`its records drifted (${S}), and --replace-drifted asks it`);let $=ya(y),E=f??(y.refusals.length>0?`a removal of its runs would be refused now: ${y.refusals.join(" ")}`:y.failed.length>0?`what the org holds of it could not be read (${y.failed.join("; ")}): plan again`:void 0),R=f===void 0&&y.refusals.length>0?ga(y,y.refusals):[];if(m.length>0)c.set(u.name,{resource:u.name,kind:g,action:"replace",why:`replaced: ${m.join("; ")}`,objects:$,...E!==void 0?{refusal:E,...Ps(R)}:{}});else if(s)c.set(u.name,{resource:u.name,kind:g,action:"keep",why:"applied from the same file; what the org holds of it was not read (--quick)",objects:$,...f!==void 0?{refusal:f}:{}});else if(f!==void 0||y.failed.length>0)c.set(u.name,{resource:u.name,kind:g,action:"keep",why:"applied from the same file",objects:$,refusal:f??`what the org holds of it could not be read (${y.failed.join("; ")}): plan again`});else if(S!==void 0)c.set(u.name,{resource:u.name,kind:g,action:"drifted",why:`its records changed since it was applied: ${S}. Left as they are: --replace ${u.name} or --replace-drifted replaces it`,objects:$});else{let j=$.reduce((N,P)=>N+(P.present??0),0),D=$.reduce((N,P)=>N+(P.changed??0),0);c.set(u.name,{resource:u.name,kind:g,action:"keep",why:b?`applied, and the org holds its ${j} record(s) as the checkpoint taken after the apply holds them: ${D} written since hold their values again, as a reset gives them back`:`applied, and the org holds its ${j} record(s) as written`,objects:$})}}return[...rt(n,[...o.keys()].filter(u=>!a.has(u))).map(u=>{let d=o.get(u);if(d?.kind==="mask")return{resource:u,kind:"mask",action:"delete",why:$i("apply",u,d,Ea(e,u)),objects:ah(d)};let f=ma(r?.[u]??[]),g=ka(f),y=g.length>0?`a removal of its runs would be refused now: ${g.join(" ")}`:f.failed.length>0?`what the org holds of it could not be read (${f.failed.join("; ")}): plan again`:void 0;return{resource:u,kind:o.get(u)?.kind??"seed",action:"delete",why:"in the state, gone from the file: its records are taken back",objects:ya(f),...y!==void 0?{refusal:y,...Ps(g.length>0?ga(f):[])}:{}}}),...t.resources.flatMap(u=>c.get(u.name)??[])]}function Rb(e,t,n,r,s){let i=(c,l,u=[],d)=>({resource:e,kind:"mask",action:c,why:l,objects:u,...d!==void 0?{refusal:d}:{}});if(n.length>0)return i("replace",`replaced: ${n.join("; ")}; ${Ri(t)}`);if(s)return i("keep","applied from the same file; what the org holds of it was not read (--quick)");if(r.dryRuns===void 0)return i("keep","applied from the same file");let o=r.dryRuns[e];if(o===void 0)return i("keep","applied from the same file",[],"it was not dry-run: plan again");if("failed"in o||o.answer.tool!==se){let c="failed"in o?o.failed:`${Pe(o.answer.tool)} answered its dry run`;return i("keep","applied from the same file",[],`what the org holds of it could not be read (its dry run: ${c}): plan again`)}let a=vu(t,o.answer);return a.unread!==void 0?i("keep","applied from the same file",a.objects,`what the org holds of it could not be read: ${a.unread}`):a.drift===void 0?i("keep",Ru(a.masked),a.objects):r.replaceDrifted===!0?i("replace",`replaced: its condition selects other records than it masked (${a.drift}), and --replace-drifted asks it; ${Ri(t)}`,a.objects):i("drifted",$u(e,a.drift),a.objects)}function Ea(e,t){let n=e.maskStores?.[t],r=e.org??e.state?.org;return{alias:r?.alias??r?.organizationId??"<alias>",...n!==void 0?{store:n}:{}}}function ah(e){return(e.runs.at(-1)?.objects??[]).map(t=>({object:t.objectApiName,present:t.masked??0}))}function $b(e,t){let n=new Set(t.filter(i=>Ie.has(i.action)).map(i=>i.resource)),r=new Set(t.filter(i=>Ie.has(i.action)&&i.kind!=="mask").map(i=>i.resource)),s=new Map;for(let i of e.resources){if(!n.has(i.name))continue;let o=i.dependsOn.filter(a=>r.has(a));o.length>0&&s.set(i.name,o)}return s}function Ab(e,t){let n=e.map(r=>({...r}));for(let r of t.objects){let s={wouldCreate:r.wouldCreate,...r.atMost===!0?{atMost:!0}:{}},i=n.find(o=>o.object===r.object);i?Object.assign(i,s):n.push({object:r.object,...s})}return n}function Ob(e,t,n,r){let s=e.resources.find(c=>c.name===t),i=r&&s!==void 0?Oi(s):void 0,o=Tt(n,i),a=s!==void 0?td(s,n):void 0;return{count:a!==void 0&&o.refusal===void 0?{...o,refusal:a}:o}}function Cb(e,t){let n=e.resources.find(r=>r.name===t);return n!==void 0&&(Oi(n)?.size??0)>0}function jb(e,t,n){let r=e.resources.find(i=>i.name===t);if(r?.kind!=="seed")return[];let s=new Set((r.run.draws??[]).map(i=>i.from));return n.filter(i=>s.has(i))}function Sa(e){return e!==void 0&&"answer"in e?Tt(e.answer).total:void 0}function Nb(e,t){let n=[],{apiRequests:r,storage:s,emails:i}=e;r.leftToday!==void 0&&r.estimate>r.leftToday&&n.push(`The resources the plan writes take about ${r.estimate} API requests, and ${t} has ${r.leftToday} left today: the apply would stop part way. Apply once the org has requests to spare \u2014 the limit is counted over the last 24 hours \u2014 or write fewer records.`),s.left!==void 0&&s.bytes>s.left&&n.push(`The resources the plan writes take about ${at(s.bytes/1048576)} MB of data storage, and ${t} has ${at(s.left/1048576)} MB left: the org would refuse records part way. Write fewer records, or free storage first.`);for(let o of i)o.left!==void 0&&o.emails>o.left&&n.push(`The resources the plan writes make ${t} send ${o.emails} ${o.limit} emails, and it has ${o.left} left today: each resource alone may fit, the day does not. Apply the resources over two days, or keep the automation that sends them quiet.`);return n}function Ib(e,t,n,r,s){let i=s.estimate,o=0,a=new Map,c=[...s.notCounted];for(let f of e){if((f.action==="delete"||f.action==="replace")&&f.kind!=="mask"&&c.push(`the removal of the runs of ${f.resource}`),!Ie.has(f.action))continue;let g=t?.[f.resource];if(g===void 0||"failed"in g){c.push(`the run of ${f.resource}, not dry-run`);continue}let y=r.get(f.resource);y!==void 0&&f.kind!=="mask"&&c.push(`what ${f.resource} draws from the records ${y.join(", ")} writes first`);let m=Tt(g.answer);m.apiRequests===void 0?c.push(`the requests of the run of ${f.resource}, which its script does not estimate`):i+=m.apiRequests,o+=m.storageBytes;for(let{limit:h,emails:w}of m.emails)a.set(h,(a.get(h)??0)+w)}let l=n?.apiRequests,u=n?.storage,d=n?.emails;return{apiRequests:{estimate:i,...l!==void 0&&!("unread"in l)?{leftToday:l.remaining}:{},partial:c.length>0,...c.length>0?{notCounted:c}:{},...l!==void 0&&"unread"in l?{unread:l.unread}:{},...n===void 0?{unread:"not read: --quick"}:{}},storage:{bytes:o,...u!==void 0&&!("unread"in u)?{left:Math.floor(u.remainingMB*1048576)}:{},...u!==void 0&&"unread"in u?{unread:u.unread}:{},...n===void 0?{unread:"not read: --quick"}:{}},emails:[...a].map(([f,g])=>{let y=d!==void 0&&!("unread"in d)?d[f]?.remaining:void 0;return{limit:f,emails:g,...y!==void 0?{left:y}:{}}})}}function Ra(e){let t=e.previews===void 0,n=ba(e),r=$b(e.resolved,n),s=n.map(h=>{let w=h.objects,v,k=h.refusal,b=h.refusal!==void 0?h.refusalCodes??[]:[],S=Ie.has(h.action)?e.dryRuns?.[h.resource]:void 0,$=r.get(h.resource),E=$!==void 0&&Cb(e.resolved,h.resource),R=Ie.has(h.action)?e.draws?.[h.resource]:void 0;R!==void 0&&R.refusals.length>0&&(k??=R.refusals.join(" "));let j=[];if(S!==void 0&&"failed"in S)S.refused!==void 0&&k===void 0&&(k=`its own dry run says a real run would be refused: ${S.refused.message}`,b=[S.refused.code]),k??=`its dry run did not answer: ${S.failed}`;else if(S!==void 0){let O=Ob(e.resolved,h.resource,S.answer,$!==void 0);w=Ab(w,O.count),v={...O.count.apiRequests!==void 0?{apiRequests:O.count.apiRequests}:{},storageBytes:O.count.storageBytes,emails:O.count.emails};let q=O.count.refusal;q!==void 0&&k===void 0&&(k=`its own dry run says a real run would be refused: ${q}`,b=O.count.refusalCodes??[]),j=O.count.notes??[]}else Ie.has(h.action)&&!t&&(k??="it was not dry-run: plan again");let D=$!==void 0?jb(e.resolved,h.resource,$):[],N=$!==void 0&&S!==void 0&&h.kind==="mask"?`; its dry run read the org before ${$.join(", ")} writes: what they write under its condition it masks too, uncounted here`:$!==void 0&&S!==void 0&&E?D.length>0?`; it draws its parents from the records ${D.join(", ")} creates in this apply, which nobody knows before it runs: counted at most as the file gives it`:`; its dry run read the org before ${$.join(", ")} writes: what it draws from those records is counted at most as the file gives it`:"",P=`${h.why}${N}${j.length>0?`; ${j.join("; ")}`:""}`,le=e.resolved.resources.find(O=>O.name===h.resource),me=le!==void 0&&Ie.has(h.action)?ld(le,Ea(e,h.resource)):[];return{resource:h.resource,kind:h.kind,action:k!==void 0?"blocked":h.action,why:P,objects:w,...R!==void 0&&R.draws.length>0?{draws:R.draws}:{},...v!==void 0?{gates:v}:{},...k!==void 0?{refusal:k,...Ps(b)}:{},...me.length>0?{notes:me}:{}}}),i=e.resolved.checked.file,o=Xc(br(i,e.state,n.some(h=>oh.has(h.action))),t?void 0:e.checkpointEstimate??{unread:"not estimated"},s.filter(h=>Ie.has(h.action)&&h.kind!=="mask").flatMap(h=>h.objects).reduce((h,w)=>h+(w.wouldCreate??0),0)),a=Ib(n,e.dryRuns,e.budget,r,el(o)),c=e.org.alias??e.org.organizationId,l=Nb(a,c);if(l.length>0)for(let h of s)wa(h)&&(h.refusal=l.join(" "),h.action="blocked");let u=s.filter(h=>h.action==="blocked"),d=e.refusal??(l.length>0?`${l.join(" ")} Nothing was written.`:u.length>0?`${u.length===1?"A resource is":`${u.length} resources are`} blocked, and the apply refuses before its first write: ${u.map(h=>`${h.resource} (${h.refusal??h.why})`).join("; ")}`:void 0)??Zc(o),f=e.refusal!==void 0?[...e.refusalCodes??[]]:l.length>0?[]:u.length>0?u.flatMap(h=>h.refusalCodes??[]):o.flatMap(h=>h.refusal!==void 0?[h.refusal.code]:[]),g=[...e.warnings??[],...Hc(i,e.state)],y=h=>s.filter(w=>w.action===h).length,m=e.state;return{env:e.resolved.checked.file.name,org:e.org,state:m!==void 0?{found:!0,serial:m.serial}:{found:!1},actions:s,totals:{create:y("create"),keep:y("keep"),replace:y("replace"),delete:y("delete"),drifted:y("drifted"),blocked:y("blocked")},gates:a,...o.length>0?{checkpoints:o}:{},...e.drift!==void 0?{drift:e.drift}:{},...d!==void 0?{refusal:d,...Ps(f)}:{},...t?{quick:!0}:{},...g.length>0?{warnings:g}:{}}}function ch(e){let n=rt(e.state,De(e.state).map(([a])=>a)).map(a=>{let c=e.state?.resources[a];if(c?.kind==="mask")return{resource:a,kind:"mask",action:"delete",why:$i("destroy",a,c,Ea(e,a)),objects:ah(c)};let l=ma(e.previews?.[a]??[]),u=ka(l),d=u.length>0?`a removal of its runs would be refused now: ${u.join(" ")}`:l.failed.length>0?`what the org holds of it could not be read (${l.failed.join("; ")}): run destroy again`:void 0,f=u.length>0?ga(l):[];return{resource:a,kind:c?.kind??"seed",action:d!==void 0?"blocked":"delete",why:"taken back by destroy, into the recycle bin",objects:ya(l),...d!==void 0?{refusal:d}:{},...f.length>0?{refusalCodes:f}:{}}}),r=n.filter(a=>a.action==="blocked"),s=[...new Set(r.flatMap(a=>a.refusalCodes??[]))],i=n.filter(a=>a.kind!=="mask").map(a=>`the removal of the runs of ${a.resource}`),o=e.state;return{env:e.resolved.checked.file.name,org:e.org,state:o!==void 0?{found:!0,serial:o.serial}:{found:!1},actions:n,totals:{create:0,keep:0,replace:0,delete:n.length-r.length,drifted:0,blocked:r.length},gates:{apiRequests:{estimate:0,partial:i.length>0,...i.length>0?{notCounted:i}:{}},storage:{bytes:0},emails:[]},...r.length>0?{refusal:`${r.map(a=>`${a.resource}: ${a.refusal??""}`).join(" ")} Nothing was deleted.`,...s.length>0?{refusalCodes:s}:{}}:{},...e.previews===void 0?{quick:!0}:{},...e.warnings!==void 0&&e.warnings.length>0?{warnings:[...e.warnings]}:{}}}function $a(e){return e.actions.some(t=>t.action!=="keep"&&t.action!=="drifted")}function lh(e){let t=e.drift;if(t!==void 0&&(t.differs||t.unread!==void 0))return!0;let n=t!==void 0;return e.actions.some(r=>r.action==="drifted"||!(n&&r.action==="keep")&&r.objects.some(s=>(s.gone??0)>0||(s.changed??0)>0))}function Aa(e){let t=e.kind==="mask";return e.objects.map(n=>{let r=[n.wouldCreate!==void 0?`${n.atMost===!0?"at most ":""}${n.wouldCreate} `+(t?"to mask":"to write"):"",n.present!==void 0&&n.present>0?`${n.present} ${t?"masked":"in the org"}`:"",(n.gone??0)>0?`${n.gone} gone`:"",(n.changed??0)>0?`${n.changed} changed`:""].filter(Boolean);return r.length>0?`${n.object} ${r.join(", ")}`:""}).filter(Boolean).join("; ")}var Db={apply:"an apply now",destroy:"a destroy now"};function Ls(e,t="apply"){let n=[`plan of ${e.env} on ${e.org.alias??e.org.organizationId} (${e.org.kind}, ${e.org.organizationId})`,e.state.found?`state: kept on this machine, serial ${e.state.serial??0}`:"state: none on this machine"];for(let c of e.actions){let l=Aa(c);n.push(` ${c.action.padEnd(8)} ${c.resource}${l?` ${l}`:""}`),n.push(` ${c.why}`);for(let u of c.draws??[])n.push(` ${u.lookup} draws its parents from `+(u.parents!==void 0?`the ${u.parents} ${u.object} record(s) ${u.from} created`:`the ${u.object} records ${u.from} creates first`));for(let u of c.notes??[])n.push(` ${u}`);c.refusal!==void 0&&n.push(` refused: ${c.refusal}`)}let{totals:r}=e;n.push(`totals: ${r.create} to create, ${r.replace} to replace, ${r.delete} to delete, ${r.keep} kept, ${r.drifted} drifted, ${r.blocked} blocked`);let{apiRequests:s,storage:i,emails:o}=e.gates,a=(c,l)=>c!==void 0?`, ${c} left`:l!==void 0?` (left: ${l})`:"";n.push(`API requests: about ${s.estimate}`+a(s.leftToday?.toString(),s.unread)+(s.partial?`; not counted: ${(s.notCounted??[]).join(", ")}`:"")),n.push(`data storage: about ${at(i.bytes/1048576)} MB`+a(i.left!==void 0?`${at(i.left/1048576)} MB`:void 0,i.unread));for(let c of o)n.push(`emails (${c.limit}): ${c.emails}`+(c.left!==void 0?`, ${c.left} left today`:""));n.push(...nl(e));for(let c of e.warnings??[])n.push(`warning: ${c}`);return e.refusal!==void 0&&n.push(`${Db[t]} would be refused: ${e.refusal}`),n}import{existsSync as Oa,readFileSync as Ca}from"node:fs";import{join as Tb}from"node:path";function Fs(e){return e.slice(0,15)}function xs(e){let t=new Map,n=new Set;for(let{objectApiName:r,ids:s}of e){let i=t.get(r)??[];for(let o of s)n.has(Fs(o))||(n.add(Fs(o)),i.push(o));t.set(r,i)}return t}function Pb(e,t,n){let r=e.runId!==void 0?Tb(n.journalDir,Ae,`${e.runId}.ndjson`):void 0;if(r!==void 0&&Oa(r)){let o=fc(Ca(r,"utf8"));if(o!==void 0)return{created:xs(o.created)}}if(e.summary===void 0)return{refusal:"its run keeps no record of what it created"};let s=n.store.fileOf(t.organizationId,t.env,e.summary);if(!Oa(s))return{refusal:"its run keeps no record of what it created"};let i=Nt(Ca(s,"utf8"));return i.result.objectResults.some(o=>o.truncated===!0)?{refusal:"its summary names the first of the records it created alone, and its run file is gone"}:{created:xs(i.result.objectResults.map(o=>({objectApiName:o.objectApiName,ids:o.createdIds})))}}async function Lb(e,t,n){if(e.summary===void 0)return{refusal:"its run keeps no summary"};let r=n.store.fileOf(t.organizationId,t.env,e.summary);if(!Oa(r))return{refusal:"its run keeps no summary"};let s=await ar(r,Ca(r,"utf8"),t.target,ir(n.journalDir));if("refusal"in s)return{refusal:`its summary ${s.refusal}`};let{result:i}=s.summary,o=Xa({idRemapTable:i.remapTable,idRemapExisting:[...i.existingSourceIds,...i.updatedSourceIds],idRemapCreated:i.createdByObject});return{created:xs([...o].reverse().map(a=>({objectApiName:a.objectApiName,ids:[...a.ids].reverse()})))}}async function Fb(e,t,n){if(Nr(e.sas)===void 0||e.sas===void 0)return{refusal:"its run names no sas"};let r=n.store.sasOf(t.organizationId,t.env,e.sas),s=new Oe,i=(await Xt(r,s)).find(c=>Fs(c)===Fs(t.organizationId));if(i===void 0)return{refusal:"its sas holds no mapping of a load into this org"};let o=await new lr(r,{orgId:i,guard:s}).recorded();if(o?.created===void 0)return{refusal:"its sas holds no load that says which records it created"};let a=Pc(o);return{created:xs([...a].reverse().map(c=>({objectApiName:c.objectApiName,ids:[...c.ids].reverse()})))}}async function ja(e,t,n,r){let s=e?.resources[t];if(s===void 0||s.status==="destroyed")return{refusal:`${t} has not created its records in this org yet`};if(s.status!=="applied")return{refusal:`${t} is ${s.status}, not applied whole: apply it again first`};let i=s.runs.at(-1);if(i===void 0||i.takenBack===!0)return{refusal:`${t} holds no run whose records are in the org`};let o=await Na(i,n,r);return"refusal"in o?{refusal:`${t}: ${o.refusal}`}:o}async function Na(e,t,n){switch(e.script){case"sandforge-seed":return Pb(e,t,n);case"sandforge-clone":return Lb(e,t,n);case"sandforge-frozen":return Fb(e,t,n);default:return{refusal:`its records are kept by ${Pe(e.script)}, which this SandForge reads not`}}}function xb(e,t){let n=e.relation.parentObject,r=`${e.relation.childObject}.${e.relation.lookupField}`,s=[...t.get(n)??[]],i=tr.maxExistingParents;if(s.length===0){let o=[...t.keys()].filter(a=>(t.get(a)??[]).length>0);return{refusal:`the relation on ${r} draws its parents from the ${n} records ${e.from} created, and it created none: it created ${o.join(", ")||"no record"}`}}return e.limit!==void 0?{ids:s.slice(0,e.limit)}:s.length>i?{refusal:`the relation on ${r} draws its parents from the ${s.length} ${n} records ${e.from} created, more than the ${i} a relation's parents hold: give the relation a limit, and its parents are the first ${i} or fewer`}:{ids:s}}async function Ms(e,t,n,r,s){let i={ids:new Map,draws:[],refusals:[]};if(e.kind!=="seed")return i;let o=new Map;for(let a of e.run.draws??[]){let c={lookup:`${a.relation.childObject}.${a.relation.lookupField}`,from:a.from,object:a.relation.parentObject};if(n.has(a.from)){i.draws.push(c);continue}let l=o.get(a.from);if(l===void 0&&(l=await ja(t,a.from,r,s),o.set(a.from,l)),"refusal"in l){i.draws.push(c),i.refusals.push(`the relation on ${c.lookup} draws its parents from ${a.from}, whose records cannot be read: ${l.refusal}`);continue}let u=xb(a,l.created);if("refusal"in u){i.draws.push(c),i.refusals.push(u.refusal);continue}i.ids.set(a.at,u.ids),i.draws.push({...c,parents:u.ids.length})}return i}function pe(e){return sc.some(t=>be(t)===e)}function dh(e,t,n){let r=e===0||e===3||e===4||pe(e),s=t??(r?void 0:Uc(n));return s!==void 0&&s!==""?s.slice(0,4e3):void 0}function _b(e){return Ci(e).map(t=>{let n=[t.keptChanged>0?`${t.keptChanged} changed since the run, kept`:"",t.keptDependents>0?`${t.keptDependents} kept for records that stay (${t.heldBy.join(", ")||"records that stay"})`:"",t.refused>0?`${t.refused} refused`:"",(t.notVisible??0)>0?`${t.notVisible} not visible to the user`:"",(t.notReached??0)>0?`${t.notReached} not reached`:"",...t.reasons].filter(Boolean);return{object:t.objectApiName,created:0,refused:t.refused,deleted:t.deleted,kept:t.keptChanged+t.keptDependents+t.refused,...n.length>0?{reason:n.join("; ").slice(0,2e3)}:{}}})}function qb(e){return(e?.objects??[]).map(t=>({object:t.object,created:t.created,refused:t.refused,deleted:0,kept:0,...t.errors.length>0?{reason:t.errors.slice(0,5).join("; ").slice(0,2e3)}:{}}))}function zb(e){try{return typeof JSON.parse(e)?.refused?.code=="string"}catch{return!1}}function gt(e,t,n){if(!(t.trim()===""||zb(t)))try{return e(t)}catch(r){if(r instanceof re){n(` ${r.message}`);return}throw r}}function Ia(e,t,n){let r=Nr(e.sas);if(r!==void 0){let s=n.store.fileOf(t.organizationId,t.env,kt(r,e.n));return Yn(s)?s:void 0}if(e.summary!==void 0){let s=n.store.fileOf(t.organizationId,t.env,e.summary);if(Yn(s))return s}if(e.runId!==void 0&&Yn(uh(n.journalDir,Ae,`${e.runId}.ndjson`)))return e.runId}async function Da(e,t,n,r){let s={organizationId:t.org.organizationId,env:t.env},i=t.resources[n.resource];if(i===void 0)throw new L("invalid",`The state holds no resource ${n.resource} to take back`);if(i.kind==="mask")return Bb(e,t,n);let o=await e.store.update(t,u=>fi(u,n.resource)),a=[],c=!1,l=!1;for(let u of[...i.runs].reverse()){if(u.takenBack===!0)continue;let d=Ia(u,s,e);if(d===void 0)continue;e.say(`${n.resource}: taking back run ${u.n}`);let f=ad(i.kind,{target:n.target.alias,subject:d,includeChanged:n.includeChanged,acceptAutomation:n.acceptAutomation,sweep:n.sweep}),g=await e.runner(f.script,f.args,r),y=gt(b=>cd(i.kind,b),g.stdout,e.say),m=Ci(y).reduce((b,S)=>b+S.deleted,0);l||=y!==void 0?m>0:g.code!==1&&g.code!==2;let h=pe(g.code),w=g.code===0||g.code===3,v=h?"destroying":w?g.code===3?n.ends.left:n.ends.whole:i.status,k=dh(g.code,void 0,g.stderr);if(a.push({resource:n.resource,action:n.action,phase:"remove",run:u.n,script:f.script,exitCode:g.code,status:v,...u.summary!==void 0?{summary:u.summary}:{},objects:_b(y),...y!==void 0?{answer:y}:{},...k!==void 0?{refusal:k}:{}}),g.code===3&&(c=!0),g.code===0&&(o=await e.store.update(o,b=>yr(b,n.resource,u.n))),!w)return h||(o=await e.store.update(o,b=>bt(b,{resource:n.resource,status:i.status}))),{whole:!1,code:h?g.code:1,wrote:l,steps:a,state:o}}return o=await e.store.update(o,u=>bt(u,{resource:n.resource,status:c?n.ends.left:n.ends.whole})),{whole:!c,code:c?3:0,wrote:l,steps:a,state:o}}async function Bb(e,t,n){let r=t.resources[n.resource];if(r===void 0)throw new L("invalid",`The state holds no resource ${n.resource} to take back`);let s=await e.store.update(t,u=>fi(u,n.resource)),i=e.store.sasOf(t.org.organizationId,t.env,jt(n.resource)),o=r.runs.at(-1),a=(u,d,f)=>({resource:n.resource,action:n.action,phase:"remove",run:o?.n??1,script:"sandforge-dataops",exitCode:d,status:u,objects:(o?.objects??[]).map(g=>({object:g.objectApiName,created:0,refused:0,deleted:0,kept:0,masked:g.masked??0,reason:f}))});e.say(`${n.resource}: deleting its store ${i}`);let c;try{c=await Au(i)}catch(u){let d=u instanceof Error?u.message:String(u);return e.say(`${n.resource}: ${d}`),s=await e.store.update(s,f=>bt(f,{resource:n.resource,status:r.status})),{whole:!1,code:1,wrote:!1,steps:[a(r.status,1,d)],state:s}}e.say(Ou(n.resource,c));for(let u of r.runs)u.takenBack!==!0&&(s=await e.store.update(s,d=>yr(d,n.resource,u.n)));s=await e.store.update(s,u=>bt(u,{resource:n.resource,status:n.ends.whole}));let l=c.snapshots.length>0?`snapshot${c.snapshots.length===1?"":"s"} ${c.snapshots.join(", ")}`:"its store";return{whole:!0,code:0,wrote:!1,steps:[a(n.ends.whole,0,`left masked, as destroy leaves a masking; ${l} deleted`)],state:s}}var Kb=new Set(["sandforge-seed","sandforge-clone","sandforge-dataops","sandforge-frozen"]);function Vt(e,t){return t&&Kb.has(e.script)?{...e,args:[...e.args,"--accept-emails"]}:e}function Ub(e,t){let n=new Map(e.actions.map(o=>[o.resource,o])),r=new Set(De(t).map(([o])=>o)),s=rt(t,e.actions.filter(o=>(o.action==="delete"||o.action==="replace"&&!lt(o.kind))&&r.has(o.resource)).map(o=>o.resource)).map(o=>({phase:"remove",resource:o,action:n.get(o)?.action??"delete"})),i=e.actions.filter(o=>o.action==="create"||o.action==="replace").map(o=>({phase:"run",resource:o.resource,action:o.action}));return[...s,...i]}function fh(e,t,n){if(pe(e))return{status:"applying",counts:e,stops:!0};if(e===0&&t!==void 0){let r=t.created;return n!==void 0&&r!==n?{status:"partial",counts:3,stops:!1,short:`it created ${r} record(s) of the ${n} its dry run counted`}:{status:"applied",counts:0,stops:!1}}return e===3?{status:"partial",counts:3,stops:!1}:e===4?{status:"partial",counts:4,stops:!0}:{status:"failed",counts:1,stops:!0}}function Vb(e,t){return t===void 0?e:e.status==="partial"&&e.short===void 0&&"short"in t?t.short===void 0||t.unstable?e:{...e,short:`its verification found ${t.short}`}:e.status!=="applied"?e:"unread"in t?{...e,short:`not verified: ${t.unread}`}:t.unstable?{status:"partial",counts:4,stops:!0,short:`its verification is unstable: ${t.short??""}`}:t.short===void 0?e:{status:"partial",counts:3,stops:!1,short:`its verification found ${t.short}`}}async function Wb(e,t,n){let{resource:r,n:s,where:i,target:o,templateFile:a,dry:c,signal:l}=n,u=i.env,d=c!==void 0&&"answer"in c?c.answer:void 0,f=d===void 0||n.readTooEarly?void 0:Tt(d).created,g=await e.orgNow();if(r.kind==="seed"){let j=hr(u,r.name,s),D=r.run.seed??(d?.tool==="sandforge-seed"?d.seed:void 0),N=await e.store.update(t,Jt=>tn(Jt,{resource:r.name,kind:"seed",fingerprint:r.fingerprint,dependsOn:r.dependsOn,run:{script:"sandforge-seed",runId:j,...D!==void 0?{seed:D}:{},startedAt:g}})),P=Vt(mn(r,{target:o.alias,templateFile:a,runId:j,summaryFile:"",...D!==void 0?{seed:D}:{}}),n.acceptEmails),le=await e.runner(P.script,P.args,l),me=gt(Nt,le.stdout,e.say),O=me!==void 0?Dr(me):void 0,q=(O?.created??0)>0||Yn(uh(e.journalDir,Ae,`${j}.ndjson`)),te=me!==void 0?await e.store.writeFile(i.organizationId,u,ae(r.name,s),le.stdout).then(()=>ae(r.name,s)):void 0;return{state:N,script:P.script,code:le.code,...O!==void 0?{count:O}:{},...me!==void 0?{answer:me}:{},...te!==void 0?{summary:te}:{},wrote:q,...f!==void 0?{planned:f}:{},...O?.refusal!==void 0?{answered:O.refusal}:{},stderr:le.stderr}}if(r.kind==="frozen")return Jb(e,t,n,g,f);if(r.kind==="mask")return Yb(e,t,n,g);let y=ae(r.name,s),m=await e.store.prepareFile(i.organizationId,u,y),h=await e.store.update(t,j=>tn(j,{resource:r.name,kind:"forge",fingerprint:r.fingerprint,dependsOn:r.dependsOn,run:{script:"sandforge-clone",summary:y,startedAt:g}})),w=Sa(c),v=Vt(mn(r,{target:o.alias,templateFile:a,runId:"",summaryFile:m,...w!==void 0?{maxTotal:w}:{}}),n.acceptEmails),k=await e.runner(v.script,v.args,l),b=Yn(m)?Mb(m,"utf8"):void 0,S=gt(cn,b??"",e.say)??gt(cn,k.stdout,e.say),$=S!==void 0?Or(S):void 0,E=$!==void 0?$.created>0:b!==void 0,R;if(k.code===0&&b!==void 0&&($?.created??0)>0){e.say(`${r.name}: verifying run ${s}`);let j=await e.runner(v.script,jl({summary:m,target:o.alias,source:r.source.alias}),l),D=j.stdout.trim()===""?void 0:gt(Pl,j.stdout,e.say);if(D!==void 0){let N=Fl(D);R={unstable:D.result.verdict==="unstable",...N!==void 0?{short:N}:{}}}else j.code!==0&&(R={unread:`its verification ended ${j.code} without an answer`})}return{state:h,script:v.script,code:k.code,...$!==void 0?{count:$}:{},...S!==void 0?{answer:S}:{},...b!==void 0?{summary:y}:{},wrote:E,...f!==void 0?{planned:f}:{},...R!==void 0?{verified:R}:{},...S?.error!==void 0?{answered:S.error}:{},stderr:k.stderr}}async function Jb(e,t,n,r,s){let{resource:i,n:o,where:a,target:c,templateFile:l,dry:u,signal:d}=n,f=await e.store.update(t,$=>tn($,{resource:i.name,kind:"frozen",fingerprint:i.fingerprint,dependsOn:i.dependsOn,run:{script:"sandforge-frozen",sas:Ve(i.name),startedAt:r}})),g=Sa(u),y=Vt(mn(i,{target:c.alias,templateFile:l,runId:"",summaryFile:"",replace:n.replace,acceptAutomation:n.acceptAutomation,...g!==void 0?{maxTotal:g}:{}}),n.acceptEmails),m=await e.runner(y.script,y.args,d),h=gt(Cr,m.stdout,e.say),w=h!==void 0?pn(h):void 0;w?.refusal!==void 0&&e.say(`${i.name}: ${w.refusal}`);let v=h===void 0?pe(m.code):(w?.created??0)>0||nu(h),k=h!==void 0?await e.store.writeFile(a.organizationId,a.env,ae(i.name,o),m.stdout).then(()=>ae(i.name,o)):void 0,b=h?.verdict,S=b!==void 0?bi(b):m.code===0&&(w?.created??0)>0?{unread:"the load chained no verification"}:void 0;return{state:f,script:y.script,code:m.code,...w!==void 0?{count:w}:{},...h!==void 0?{answer:h}:{},...k!==void 0?{summary:k}:{},wrote:v,...s!==void 0?{planned:s}:{},...S!==void 0?{verified:S}:{},...n.replace&&h!==void 0&&jr(h)?{tookBackEarlier:!0}:{},...w?.refusal!==void 0?{answered:w.refusal}:{},stderr:m.stderr}}async function Yb(e,t,n,r){let{resource:s,n:i,where:o,target:a,templateFile:c,signal:l}=n,u=await e.store.update(t,v=>tn(v,{resource:s.name,kind:"mask",fingerprint:s.fingerprint,dependsOn:s.dependsOn,run:{script:"sandforge-dataops",startedAt:r}})),d=await e.store.prepareFolder(o.organizationId,o.env,jt(s.name)),f=Vt(mn(s,{target:a.alias,templateFile:c,runId:"",summaryFile:"",store:d}),n.acceptEmails),g=await e.runner(f.script,f.args,l),y=gt(Ir,g.stdout,e.say),m=y!==void 0?hn(y):void 0;m?.refusal!==void 0&&e.say(`${s.name}: ${m.refusal}`);let h=m!==void 0?m.objects.some(v=>v.masked>0):pe(g.code),w=y!==void 0?await e.store.writeFile(o.organizationId,o.env,ae(s.name,i),g.stdout).then(()=>ae(s.name,i)):void 0;return{state:u,script:f.script,code:g.code,...y!==void 0?{answer:y}:{},...w!==void 0?{summary:w}:{},wrote:h,...m!==void 0?{masking:m}:{},...m?.refusal!==void 0?{answered:m.refusal}:{},stderr:g.stderr}}function Gb(e,t){let n=fh(e,void 0,void 0);if(e!==0)return n;let r=(t?.objects??[]).reduce((s,i)=>s+i.notMasked,0);return t?.short!==void 0||r>0?{status:"partial",counts:3,stops:!1,short:t?.short??`${r} record(s) still hold their original values: the next apply masks them again`}:{status:"applied",counts:0,stops:!1}}function Hb(e){return(e?.objects??[]).map((t,n)=>({object:t.object,created:0,refused:t.refused,deleted:0,kept:0,masked:t.masked,...n===0&&e?.snapshotId!==void 0?{reason:`snapshot ${e.snapshotId} of the values it wrote over, taken first, kept on this machine until destroy deletes it`}:{}}))}async function Qb(e,t,n,r,s){if(n.kind==="frozen"){let o=await e.store.prepareFolder(r.organizationId,r.env,Ve(n.name));return{payload:Dt(n,{sasDir:o})}}if(n.kind!=="seed"||(n.run.draws??[]).length===0)return{payload:Dt(n,{})};let i=await Ms(n,t,new Set,{...r,target:s.alias},{store:e.store,journalDir:e.journalDir});return i.refusals.length>0?{refusal:i.refusals.join(" ")}:{payload:Dt(n,{drawn:i.ids})}}function qs(e){return e===0?"success":pe(e)?"cancelled":e===1?"failure":"partial"}async function ph(e,t){let{plan:n,target:r,resolved:s}=t,i=s.checked.file.name,o=(y,m=t.state,h=[])=>({result:{plan:n,steps:[],status:"failure",refusal:y,...h.length>0?{refusalCodes:[...h]}:{},state:{serial:m?.serial??0}},exitCode:1});if(n.refusal!==void 0)return o(n.refusal,t.state,n.refusalCodes);let a=Ub(n,t.state),c=n.checkpoints?.find(y=>y.step==="before"),l=n.checkpoints?.find(y=>y.step==="after");if(a.length===0&&l===void 0)return e.say("nothing to do: the org holds the environment as the file describes it"),{result:{plan:n,steps:[],status:"success",state:{serial:t.state?.serial??0}},exitCode:0};let u=Me(e.locksDir,r.organizationId,{operation:"apply",env:i,alias:r.alias},e.lockOptions);if("busy"in u){let y=Ue(u.busy);return o(y.message,t.state,[y.code])}let d=new AbortController,f,g=(e.onStop??Le)(y=>{f=y,e.say(`
|
|
148
|
-
stopped by ${
|
|
149
|
-
`),nm=q.dependsOn.some(ne=>E.has(ne));e.say(`${O.resource}: run ${Yt} (${O.action})`);let B=await Wb(e,y,{resource:q,n:Yt,where:m,target:r,templateFile:tm,dry:t.dryRuns[O.resource],readTooEarly:nm,replace:O.action==="replace"&<(q.kind),acceptAutomation:t.acceptAutomation||s.checked.file.resources[O.resource]?.accept?.automation===!0,acceptEmails:t.acceptEmails===!0,signal:d.signal});y=B.state,b||=B.wrote,q.kind!=="mask"&&E.add(O.resource);let vt=B.masking,ke=q.kind==="mask"?Gb(B.code,vt):Vb(fh(B.code,B.count,B.planned),B.verified),rm=await e.orgNow();if(y=await e.store.update(y,ne=>bt(ne,{resource:O.resource,status:ke.status,run:{endedAt:rm,exitCode:B.code,objects:vt!==void 0?vt.objects.map(J=>({objectApiName:J.object,created:0,refused:J.refused,masked:J.masked})):(B.count?.objects??[]).map(J=>({objectApiName:J.object,created:J.created,refused:J.refused})),...B.summary!==void 0?{summary:B.summary}:{},...vt?.snapshotId!==void 0?{snapshotId:vt.snapshotId}:{}}})),B.tookBackEarlier===!0)for(let ne of y.resources[O.resource]?.runs??[])ne.n===Yt||ne.takenBack===!0||(y=await e.store.update(y,J=>yr(J,O.resource,ne.n)));let Zn=q.kind==="mask"?Hb(vt):qb(B.count),Ka=dh(B.code,B.answered,B.stderr);if(h.push({resource:O.resource,action:O.action,phase:"run",run:Yt,script:B.script,exitCode:B.code,status:ke.status,...B.summary!==void 0?{summary:B.summary}:{},objects:ke.short!==void 0&&Zn[0]!==void 0?[{...Zn[0],reason:ke.short},...Zn.slice(1)]:Zn,...B.answer!==void 0?{answer:B.answer}:{},...Ka!==void 0?{refusal:Ka}:{}}),ke.short!==void 0&&e.say(`${O.resource}: ${ke.short}`),pe(B.code)){S=B.code,e.say(q.kind==="mask"?`${O.resource}: its masking was stopped; the state keeps it applying, and its store the snapshot it took first: apply again masks what its condition selects`:`${O.resource}: its run was stopped; the state keeps it applying, and its ${q.kind==="forge"?"summary what it created":q.kind==="frozen"?"sas what it loaded":"run file what it wrote"}: apply again takes it back and runs it whole`);continue}if(v.push(ke.counts),ke.status!=="applied"&&k.set(O.resource,ke.status),ke.stops)break}}catch(O){let q=`the apply stopped on an error: ${O instanceof Error?O.message:String(O)}`;e.say(q),v.push(1);for(let te of a.slice(R))w.push({resource:te.resource,why:q})}let P=y.checkpoints?.after;if(b&&P!==void 0&&f===void 0){let O=await At(e,{org:D,checkpoint:P,why:"taken before this apply wrote"},d.signal);j.push(O),y=await e.store.update(y,q=>Be(q,"after",void 0))}let le=f===void 0&&S===void 0&&Qt(v)===0;if(l!==void 0&&le){let O=await ki(e,{org:D,step:"after",name:l.name,...N},d.signal);j.push(O.result);let q=O.checkpoint;q!==void 0?y=await e.store.update(y,te=>Be(te,"after",q)):pe(O.result.exitCode)?S=O.result.exitCode:(e.say(`the checkpoint once applied, '${l.name}', was not taken: reset has nothing to rewind to until an apply takes it, which the next one does`),v.push(1))}let me=f!==void 0?be(f):S!==void 0?S:(()=>{let O=Qt(v);return O===1&&b?3:O})();return{result:{plan:n,steps:h,...j.length>0?{checkpoints:j}:{},...w.length>0?{skipped:w}:{},status:qs(me),state:{serial:y.serial}},exitCode:me}}finally{g(),u.lock.release()}}function Xb(e){return e.map(t=>{let n=t.step==="delete"?`checkpoint ${t.checkpoint??""} deleted`:`checkpoint ${t.step==="before"?"before the first write":"once applied"}`;return t.exitCode!==0?` ${n}: exit ${t.exitCode}, ${t.step==="delete"?"kept":"not taken"}: ${t.refusal??""}`:t.step==="delete"?` ${n}`:` ${n}: exit 0, taken ${t.checkpoint??""}`})}function Ta(e,t){let n=[""];for(let r of e.steps){if(r.script==="sandforge-dataops"){let i=r.objects.map(o=>r.phase==="run"?`${o.object} ${o.masked??0} masked${o.refused>0?`, ${o.refused} refused`:""}`:`${o.object} ${o.masked??0} left masked`).join("; ");n.push(` ${r.resource} ${r.phase==="run"?`masking ${r.run}: exit ${r.exitCode}`:"store deleted"}, ${r.status}${i?` ${i}`:""}`),r.refusal!==void 0&&n.push(` ${r.refusal}`);for(let o of r.objects)o.reason!==void 0&&n.push(` ${o.object}: ${o.reason}`);continue}let s=r.objects.map(i=>r.phase==="run"?`${i.object} ${i.created} created${i.refused>0?`, ${i.refused} refused`:""}`:`${i.object} ${i.deleted} deleted${i.kept>0?`, ${i.kept} kept`:""}`).join("; ");n.push(` ${r.resource} ${r.phase==="run"?"run":"removal of run"} ${r.run}: exit ${r.exitCode}, ${r.status}${s?` ${s}`:""}`),r.refusal!==void 0&&n.push(` ${r.refusal}`);for(let i of r.objects)i.reason!==void 0&&n.push(` ${i.object}: ${i.reason}`)}for(let r of e.skipped??[])n.push(` ${r.resource}: not run, ${r.why}`);return n.push(...Xb(e.checkpoints??[])),e.refusal!==void 0&&n.push(`${t} refused: ${e.refusal}`),n.push(`${t}: ${e.status}; state serial ${e.state.serial}`),n}import{readFile as Hn,readdir as Zb,stat as eE}from"node:fs/promises";import{join as st}from"node:path";var tE={"sandforge-seed":"seed","sandforge-clone":"forge","sandforge-frozen":"frozen","sandforge-dataops":"mask"},nE=/^([1-9][0-9]{0,5})\.summary\.json$/,rE=/^([a-z][a-z0-9-]{0,62})\.([1-9][0-9]{0,5})\.json$/,sE=/^([a-z][a-z0-9-]{0,62})-([1-9][0-9]{0,5})-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,iE=/\.load-\d{1,16}\.ndjson$/,K=class extends Error{constructor(n,r){super(r);this.code=n;this.name="Refused"}code},X="Nothing was written.";async function it(e,t){try{return(await Zb(e,{withFileTypes:!0})).filter(r=>t?r.isDirectory():r.isFile()).map(r=>r.name).sort()}catch(n){let r=n?.code;if(r==="ENOENT"||r==="ENOTDIR")return[];throw n}}function Pa(e,t,n){let r=e.ranks.get(t);r===void 0&&(r=new Map,e.ranks.set(t,r));let s=r.get(n);return s===void 0&&(s={seedRuns:[]},r.set(n,s)),s}async function yh(e,t){let n=t.resolved.checked.file.name,r=t.target.organizationId,s=e.store.folderOf(r,n),i={ranks:new Map,frozen:new Set,dataops:new Set,unclaimed:[]},o=f=>Gt.safeParse(f).success;for(let f of(await it(st(s,"runs"),!0)).filter(o))for(let g of await it(st(s,"runs",f),!1)){let y=nE.exec(g)?.[1];y!==void 0&&(Pa(i,f,Number(y)).summary=ae(f,Number(y)))}for(let f of await it(st(s,"templates"),!1)){let g=rE.exec(f);g?.[1]===void 0||g[2]===void 0||!o(g[1])||(Pa(i,g[1],Number(g[2])).template=kt(g[1],Number(g[2])))}for(let f of(await it(st(s,"frozen"),!0)).filter(o))i.frozen.add(f);for(let f of(await it(st(s,"dataops"),!0)).filter(o))i.dataops.add(f);let a=new Set(t.resolved.resources.map(f=>f.name)),c=new Set([...i.ranks.keys(),...i.frozen,...i.dataops]),l=(await it(st(s,".."),!0)).filter(f=>f!==n&&f.startsWith(`${n}-`)),u=`env-${n}-`,d=uc(e.journalDir,Ae);for(let f of await it(st(e.journalDir,Ae),!1)){if(!f.endsWith(".ndjson")||!f.startsWith(u))continue;let g=f.slice(0,-7),y=sE.exec(g.slice(u.length));if(y?.[1]===void 0||y[2]===void 0)continue;let m=y[1],h=a.has(m)||c.has(m),w=l.find(b=>g.startsWith(`env-${b}-`));if(w!==void 0&&!h)continue;let v=st(e.journalDir,Ae,f),k=await d.get(g);if(k===void 0)throw new K("RUN_UNREAD",`The seed run file ${v} does not read as a run: a state rebuilt without it would leave what it created to nobody. Move it aside if it is not a run of ${n}. ${X}`);if(k.targetOrganizationId===void 0)throw new K("RUN_UNREAD",`The seed run file ${v} names no Organization Id: nothing tells whether it wrote to ${t.target.alias} or to another org. Move it aside if it is not a run of ${n} on ${t.target.alias}. ${X}`);if(de(k.targetOrganizationId,r)){if(w!==void 0)throw new K("RUN_UNCLAIMED",`The seed run file ${v} may be run ${y[2]} of ${m} of ${n}, or a run of ${w}, kept on this machine too: their names begin alike, and nothing tells them apart. Move it out of the folder while ${n} is recovered if it is ${w}'s. ${X}`);if(!h){i.unclaimed.push({file:v,resource:m,run:k});continue}Pa(i,m,Number(y[2])).seedRuns.push({runId:g,run:k})}}return i}async function zs(e,t){try{let n=await yh(e,t);return n.unclaimed.length>0||n.frozen.size>0||n.dataops.size>0||[...n.ranks.values()].some(r=>[...r.values()].some(s=>s.summary!==void 0||s.seedRuns.length>0))}catch(n){return n instanceof K}}function Gn(e){if(typeof e!="string")return;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}async function wh(e){try{return(await eE(e)).mtime.toISOString()}catch{return}}async function oE(e){let t=o=>new K("RUN_UNREAD",`The summary ${e} does not read (${o}): a state rebuilt without it would leave what its run created to nobody. ${X}`),n;try{n=await Hn(e,"utf8")}catch(o){throw t(o instanceof Error?o.message:String(o))}let r;try{r=JSON.parse(n)}catch{throw t("not JSON")}let s=r?.tool,i=typeof s=="string"?tE[s]:void 0;try{if(i==="seed")return{kind:i,answer:Nt(n)};if(i==="frozen")return{kind:i,answer:Cr(n)};if(i==="mask")return{kind:i,answer:Ir(n)};if(i==="forge"){let o=r,a=Gn(o.finishedAt),c=typeof o.elapsedMs=="number"&&Number.isFinite(o.elapsedMs)&&o.elapsedMs>=0?o.elapsedMs:void 0;return{kind:i,answer:cn(n),...a!==void 0?{finishedAt:a}:{},...c!==void 0?{elapsedMs:c}:{}}}}catch(o){throw o instanceof re?t(o.message):o}throw t("it names no script of an environment")}function vh(e){return e.removal!==void 0&&ei(e).length===0}function aE(e){return e.interrupted===!0||e.result.cancelled===!0?"applying":e.result.status==="success"?"applied":e.result.status==="partial"?"partial":"failed"}function La(e){return e.map(t=>({objectApiName:t.object,created:t.created,refused:t.refused}))}function hh(e,t,n){if(!(t===void 0||de(t,n.target.organizationId)))throw new K("RUN_OTHER_ORG",`The summary ${e} is of a run that wrote to ${t}, not to ${n.target.alias} (${n.target.organizationId}): it was copied from another org's folder. Put it back where it came from. ${X}`)}async function cE(e,t,n,r,s,i){let o=t.resolved.checked.file.name,a=m=>e.store.fileOf(t.target.organizationId,o,m);if(s.seedRuns.length>1)throw new K("RUNS_CONFLICT",`Two seed runs are kept for run ${r} of ${n}: ${s.seedRuns.map(m=>m.runId).join(", ")}. One rank is one run: the state they come from cannot be told. ${X}`);let c=s.seedRuns[0],l=i?.kind==="seed"?i.answer:void 0,u=l?.result.operationId??c?.runId;if(l!==void 0&&c!==void 0&&l.result.operationId!==c.runId)throw new K("RUNS_CONFLICT",`The summary of run ${r} of ${n} is of the run ${l.result.operationId}, and the seed run file of that rank of ${c.runId}: one rank is one run. ${X}`);if(l!==void 0&&!l.result.operationId.startsWith(`env-${o}-${n}-${r}-`))throw new K("RUNS_CONFLICT",`The summary ${a(ae(n,r))} is of the run ${l.result.operationId}, which is not run ${r} of ${n}. ${X}`);let d=c!==void 0&&vh(c.run);if(l!==void 0&&!d){let m=await Hn(a(di(n,r)),"utf8").catch(()=>{}),h;try{h=m!==void 0?JSON.parse(m):void 0}catch{h=void 0}let w=h?.runId===l.result.operationId?dc(h):void 0;d=w!==void 0&&l.result.objectResults.every(v=>v.truncated!==!0)&&ei(bc({runId:l.result.operationId,targetOrgId:l.target,status:l.result.status,objectResults:l.result.objectResults},w)).length===0}let f=Gn(l?.startedAt)??Gn(c?.run.startedAt)??new Date(0).toISOString(),g=Gn(l!==void 0?l.finishedAt:c?.run.end?.at),y=l!==void 0?La(Dr(l).objects):(c?.run.created??[]).map(m=>({objectApiName:m.objectApiName,created:m.ids.length,refused:0}));return{run:{n:r,script:"sandforge-seed",...u!==void 0?{runId:u}:{},...s.summary!==void 0&&l!==void 0?{summary:s.summary}:{},...l!==void 0?{seed:l.seed}:{},startedAt:f,...g!==void 0?{endedAt:g}:{},objects:y,...d?{takenBack:!0}:{}},status:l!==void 0?aE(l):"applying"}}async function lE(e,t,n,r,s){let i=t.resolved.checked.file.name,o=ae(n,r),a=e.store.fileOf(t.target.organizationId,i,o),{answer:c}=s,l=!1,u=await Hn(e.store.fileOf(t.target.organizationId,i,di(n,r)),"utf8").catch(()=>{});if(u!==void 0){let m=await ar(a,await Hn(a,"utf8"),t.target.alias,ir(e.journalDir));if(!("refusal"in m)){let h=jc(u,Cc(Oc(m.summary)));l="earlier"in h&&h.earlier?.removalLeft?.length===0}}let d=c.running===!0||c.interrupted===!0?void 0:s.finishedAt,f=s.finishedAt??await wh(a)??new Date(0).toISOString(),g=new Date(Date.parse(f)-(s.elapsedMs??0)).toISOString(),y=c.running===!0||c.interrupted===!0?"applying":c.error!==void 0?"failed":c.result.failedCount>0?"partial":"applied";return{run:{n:r,script:"sandforge-clone",summary:o,startedAt:g,...d!==void 0?{endedAt:d}:{},objects:La(Or(c).objects),...l?{takenBack:!0}:{}},status:y}}async function mh(e,t,n){let r=t.resolved.checked.file.name,s=a=>a!==void 0?wh(e.store.fileOf(t.target.organizationId,r,a)):Promise.resolve(void 0),i=await s(n.template),o=await s(n.summary);return{startedAt:i??o??new Date(0).toISOString(),...o!==void 0?{endedAt:o}:{}}}async function uE(e,t){if((await it(e,!1)).some(i=>iE.test(i)))return!1;let n=new Oe,r=(await Xt(e,n)).find(i=>de(i,t));if(r===void 0)return!1;let s=await new lr(e,{orgId:r,guard:n}).recordedLoads();return s.length>0&&s.some(i=>i.removal!==void 0)&&s.every(i=>i.created!==void 0&&Lc(i).length===0)}async function dE(e,t){let n=(await Xt(e,new Oe)).filter(r=>!de(r,t.target.organizationId));if(n.length!==0)throw new K("RUN_OTHER_ORG",`The sas ${e} keeps loads into ${n.join(", ")}, not into ${t.target.alias} (${t.target.organizationId}): it was copied from another org's folder. Put it back where it came from. ${X}`)}function fE(e){let t=pn(e);return t.refusal!==void 0?"failed":t.objects.some(n=>n.refused>0)?"partial":e.verdict===void 0||e.verdict.status==="PASSED"?"applied":"partial"}function pE(e){let t=hn(e);return t.refusal!==void 0?"failed":t.short!==void 0||t.objects.some(n=>n.notMasked>0)?"partial":"applied"}function hE(e,t,n){let r=new Set;for(let s of n.values())r.add(s.kind);if(t.frozen.has(e)&&r.add("frozen"),t.dataops.has(e)&&r.add("mask"),[...t.ranks.get(e)?.values()??[]].some(s=>s.seedRuns.length>0)&&r.add("seed"),r.size>1)throw new K("RUNS_CONFLICT",`The run files of ${e} are of ${[...r].join(" and ")} runs: one resource is of one kind, and the state they come from cannot be told. ${X}`);return[...r][0]}async function mE(e,t,n,r){let s=t.resolved.checked.file.name,i=t.target.organizationId,o=n.ranks.get(r)??new Map,a=new Map;for(let[w,v]of o)v.summary!==void 0&&a.set(w,await oE(e.store.fileOf(i,s,v.summary)));let c=hE(r,n,a);if(c===void 0)return;for(let[w,v]of a){let k=e.store.fileOf(i,s,ae(r,w));v.kind==="seed"&&hh(k,v.answer.targetOrgId,t),v.kind==="forge"&&hh(k,v.answer.targetOrgId,t)}let l=[],u=[...o.keys()].sort((w,v)=>w-v);if(c==="seed")for(let w of u){let v=o.get(w);v===void 0||v.summary===void 0&&v.seedRuns.length===0||l.push(await cE(e,t,r,w,v,a.get(w)))}else if(c==="forge")for(let w of u){let v=a.get(w);v?.kind==="forge"&&l.push(await lE(e,t,r,w,v))}else if(c==="frozen"){let w=e.store.sasOf(i,s,Ve(r));await dE(w,t);let v=await uE(w,i);for(let k of u){let b=o.get(k),S=a.get(k);if(b?.template===void 0){if(S?.kind!=="frozen"||v)continue;throw new K("RUN_UNREAD",`Run ${k} of ${r} keeps its summary and not the payload its load was given, ${e.store.fileOf(i,s,kt(r,k))}, which its removal is run from: a state rebuilt without it would leave what the load created to nobody. ${X}`)}let $=S?.kind==="frozen"?S.answer:void 0;if(l.push({run:{n:k,script:"sandforge-frozen",sas:Ve(r),...$!==void 0&&b.summary!==void 0?{summary:b.summary}:{},...await mh(e,t,b),objects:$!==void 0?La(pn($).objects):[],...v?{takenBack:!0}:{}},status:$!==void 0?fE($):"applying"}),$!==void 0&&jr($))for(let E of l.slice(0,-1))E.run.takenBack=!0}}else{let w=!n.dataops.has(r);for(let v of u){let k=o.get(v),b=a.get(v);if(k===void 0)continue;let S=b?.kind==="mask"?b.answer:void 0;if(S===void 0&&w)continue;let $=S!==void 0?hn(S):void 0;l.push({run:{n:v,script:"sandforge-dataops",...S!==void 0&&k.summary!==void 0?{summary:k.summary}:{},...$?.snapshotId!==void 0?{snapshotId:$.snapshotId}:{},...await mh(e,t,k),objects:($?.objects??[]).map(E=>({objectApiName:E.object,created:0,refused:E.refused,masked:E.masked})),...w?{takenBack:!0}:{}},status:S!==void 0?pE(S):"applying"})}}if(l.length===0)return;let d=l.map(w=>w.run),f=l.at(-1),g=d.every(w=>w.takenBack===!0)?"destroyed":f?.run.takenBack===!0?"partial":f?.status??"applying",y=t.resolved.resources.find(w=>w.name===r),m=d.flatMap(w=>w.endedAt!==void 0?[w.endedAt]:[]).sort(),h=d.map(w=>w.startedAt).sort();return{name:r,state:{kind:c,fingerprint:Qa,dependsOn:y!==void 0?[...y.dependsOn]:[],status:g,runs:d,recovered:!0},firstStartedAt:h[0]??new Date(0).toISOString(),...m.length>0?{lastEndedAt:m.at(-1)}:{}}}async function gE(e,t,n){let r=t.resolved.checked.file,i=(await new pc({root:ye(e.journalDir),locksDir:e.locksDir}).list({organizationId:t.target.organizationId})).flatMap(d=>d.valid&&d.checkpoint!==void 0?[d.checkpoint]:[]),o=[],a={},c=`${r.name} before`,l=i.filter(d=>d.name===c&&Date.parse(d.takenAt)<=Date.parse(n.first));l.length===1&&l[0]!==void 0?a.before=l[0].checkpointId:rn(r,"before")===void 0&&l.length===0?o.push("checkpoint.before: the file asks none"):o.push(`checkpoint.before: ${l.length===0?"no":`${l.length}`} checkpoint(s) of this org named '${c}' taken before the first run: none is linked, and destroy --rewind has none to return to`);let u=rn(r,"after");if(u===void 0)o.push("checkpoint.after: the file asks none");else{let d=n.last,f=i.filter(g=>g.name===u&&d!==void 0&&Date.parse(g.readFrom)>=Date.parse(d));f.length===1&&f[0]!==void 0?a.after=f[0].checkpointId:o.push(`checkpoint.after: ${f.length===0?"no":`${f.length}`} checkpoint(s) of this org named '${u}' taken after the last run: none is linked, and reset has none to rewind to until an apply takes it`)}return{...a,notLinked:o}}function yE(e,t){let n=i=>{let o=/^(\d+)\.(\d+)\.(\d+)/.exec(i);return o?[Number(o[1]),Number(o[2]),Number(o[3])]:void 0},r=typeof e=="string"?n(e):void 0,s=n(t);if(r===void 0||s===void 0)return!1;for(let i=0;i<3;i++)if((r[i]??0)!==(s[i]??0))return(r[i]??0)>(s[i]??0);return!1}async function wE(e,t){let n=t.resolved.checked.file.name,{alias:r,organizationId:s}=t.target;try{let l=await e.store.read(s,n);if(l===void 0)return{damaged:!1};throw new K("STATE_KEPT",`This machine keeps a state of ${n} on ${r} that reads, serial ${l.serial}: state recover never writes over one, and plan reads it. ${X}`)}catch(l){if(!(l instanceof L))throw l;if(l.code!=="damaged"){let u=Ke(l);throw new K(u.code,u.message)}}let i=e.store.stateFileOf(s,n),o;try{o=JSON.parse(await Hn(i,"utf8"))}catch{o=void 0}let a=o,c=a?.version;if(typeof c=="number"&&c>1||yE(a?.sandforgeVersion,e.sandforgeVersion))throw new K("STATE_NEWER",`The state ${i} was written by a later SandForge (${String(a?.sandforgeVersion??`version ${String(c)}`)}; this one is ${e.sandforgeVersion}): update it, and plan again. ${X}`);return{damaged:!0}}async function kh(e,t){let n=t.resolved.checked.file.name,{target:r}=t,s=Me(e.locksDir,r.organizationId,{operation:"recover",env:n,alias:r.alias},e.lockOptions);if("busy"in s)return{refusal:Ue(s.busy)};try{let{damaged:i}=await wE(e,t),o=await yh(e,t),a=[];for(let k of[...o.ranks.keys(),...o.frozen,...o.dataops]){if(a.some(S=>S.name===k))continue;let b=await mE(e,t,o,k);b!==void 0&&a.push(b)}let c=[];for(let k of o.unclaimed){if(vh(k.run)){c.push(`${k.file}: a run of ${k.resource}, which neither the file nor the environment's folder has, taken back whole: passed over`);continue}throw new K("RUN_UNCLAIMED",`The seed run file ${k.file} is of a resource ${k.resource} that neither the file nor the environment's folder has: it may be another environment's, whose name begins as ${n} does. Move it out of the folder if it is, or put ${k.resource} back in the file. ${X}`)}if(a.length===0)throw new K("NO_RUNS",`This machine keeps no run of ${n} on ${r.alias}: there is nothing to rebuild a state from. If the org holds nothing of the environment, apply it with --accept-no-state. ${X}`);a.sort((k,b)=>Date.parse(k.firstStartedAt)-Date.parse(b.firstStartedAt)||k.name.localeCompare(b.name));let l=a[0]?.firstStartedAt??new Date(0).toISOString(),d=a.flatMap(k=>k.lastEndedAt!==void 0?[k.lastEndedAt]:[]).sort().at(-1),f=await gE(e,t,{first:l,...d!==void 0?{last:d}:{}}),y={...gr({env:n,org:{organizationId:r.organizationId,kind:r.kind,username:r.username,alias:r.alias},fileDigest:t.resolved.digest,sandforgeVersion:e.sandforgeVersion}),resources:Object.fromEntries(a.map(k=>[k.name,k.state])),...f.before!==void 0||f.after!==void 0?{checkpoints:{...f.before!==void 0?{before:f.before}:{},...f.after!==void 0?{after:f.after}:{}}}:{}},m=Ht.safeParse({...y,serial:1});if(!m.success){let k=m.error.issues[0];throw new K("RUN_UNREAD",`The run files of ${n} do not make a state (${k?.path.join(".")??""}: ${k?.message??"refused"}). ${X}`)}let h=i?await e.store.setAside(r.organizationId,n):void 0,w=await e.store.write(y,{serial:0,lineage:y.lineage}),v=new Set(t.resolved.resources.map(k=>k.name));return{state:w,result:{env:n,org:{organizationId:w.org.organizationId,kind:w.org.kind,alias:r.alias},state:{serial:w.serial,lineage:w.lineage},...h!==void 0?{setAside:h}:{},resources:Object.fromEntries(a.map(k=>[k.name,{kind:k.state.kind,status:k.state.status,runs:k.state.runs.map(b=>b.n),takenBack:k.state.runs.filter(b=>b.takenBack===!0).map(b=>b.n),inFile:v.has(k.name)}])),checkpoints:{...f.before!==void 0?{before:f.before}:{},...f.after!==void 0?{after:f.after}:{}},notLinked:[...f.notLinked,...c].slice(0,20)}}}catch(i){if(i instanceof K)return{refusal:{code:i.code,message:i.message,exit:1}};throw i}finally{s.lock.release()}}function gh(e){return`${e.length===1?"run":"runs"} ${e.join(", ")}`}function bh(e){let t=[`state of ${e.env} on ${e.org.alias??e.org.organizationId} rebuilt from its run files: serial ${e.state.serial}`],n=Math.max(...Object.keys(e.resources).map(r=>r.length));for(let[r,s]of Object.entries(e.resources)){let i=s.takenBack.length===0?"":s.takenBack.length===s.runs.length?", taken back":`; ${gh(s.takenBack)} taken back`;t.push(` ${r.padEnd(n)} ${s.kind}, ${s.status}: ${gh(s.runs)}${i}`+(s.inFile?"":"; gone from the file"))}e.checkpoints.before!==void 0&&t.push(` checkpoint.before: ${e.checkpoints.before}`),e.checkpoints.after!==void 0&&t.push(` checkpoint.after: ${e.checkpoints.after}`);for(let r of e.notLinked)t.push(` ${r}`);return e.setAside!==void 0&&t.push(`the state that did not read is kept, set aside: ${e.setAside}`),t.push("next: plan replaces each resource still in the org, whose run files do not say what it was applied from, and asks no --accept-no-state"),t}function vE(e){return rt(e,De(e).map(([t])=>t))}async function Eh(e,t){let{plan:n,target:r,resolved:s}=t,i=s.checked.file.name,o=(f,g=[])=>({result:{plan:n,steps:[],status:"failure",refusal:f,...g.length>0?{refusalCodes:[...g]}:{},state:{serial:t.state?.serial??0}},exitCode:1});if(t.state===void 0)return await zs(e,{resolved:s,target:r})?o(`This machine keeps no state of ${i} on ${r.alias}, but keeps runs of it: the records they wrote are still in the org, and destroy reaches only what a state names. "${ue("env")} state recover --file <file> --org ${r.alias}" rebuilds the state from them; then destroy again. Nothing was deleted.`,["NO_STATE"]):(e.say(`this machine keeps no state of ${i} on ${r.alias}, nor any run of it: nothing applied from here is left to take back. Records an apply from another machine or a CI job left are not known here: restore its journal directory (SANDFORGE_JOURNAL_DIR), then destroy again`),{result:{plan:n,steps:[],status:"success",state:{serial:0}},exitCode:0});if(n.refusal!==void 0)return o(n.refusal,n.refusalCodes);let a=vE(t.state),c=Me(e.locksDir,r.organizationId,{operation:"destroy",env:i,alias:r.alias},e.lockOptions);if("busy"in c){let f=Ue(c.busy);return o(f.message,[f.code])}let l=new AbortController,u,d=(e.onStop??Le)(f=>{u=f,e.say(`
|
|
150
|
-
stopped by ${f}: the removal under way stops before its next call to the org; destroy again takes up from the state`),l.abort()});try{let f;try{let E=await e.store.read(r.organizationId,i);if(E===void 0||E.serial!==t.state.serial||E.lineage!==t.state.lineage)return o(`The state of ${i} on ${r.alias} changed since the plan of the destruction (another apply or destroy ran, or a cache put back another state). Nothing was deleted: run destroy again.`,[$r]);f=E}catch(E){if(E instanceof L)return o(E.message,[Ke(E).code]);throw E}let g=[],y=[],m=[],h=!1,w,v;for(let[E,R]of a.entries()){if(u!==void 0||w!==void 0){v??=E;break}let j=or(e.locksDir,r.organizationId,e.lockOptions);if(j!==void 0){e.say(an(j).message),m.push(1),v=E;break}let D=t.acceptAutomation||s.checked.file.resources[R]?.accept?.automation===!0,N=await Da(e,f,{resource:R,action:"delete",target:r,includeChanged:t.includeChanged,sweep:t.sweep,acceptAutomation:D,ends:{whole:"destroyed",left:"partial"}},l.signal);if(f=N.state,g.push(...N.steps),h||=N.wrote,pe(N.code)){w=N.code,v=E+1;break}if(m.push(N.code),N.code!==0&&N.code!==3){v=E+1;break}}for(let E of v!==void 0?a.slice(v):[])y.push({resource:E,why:u!==void 0||w!==void 0?"the destroy was stopped before it":"a removal before it was refused or failed: its records would be kept for it"});let k=Object.values(f.resources).every(E=>E.status==="destroyed"),b=[];if(k&&v===void 0){let E=Object.values(f.resources).some(R=>R.kind==="mask");e.say(`every record of ${i} is taken back from ${r.alias}${E?", and what it masked left masked":""}: the state keeps it as destroyed, and the next apply creates it again`);for(let{step:R,checkpoint:j}of Sr(f)){let D=await At(e,{org:{alias:r.alias,kind:r.kind},checkpoint:j,why:"the environment it was taken of is taken back"},l.signal);b.push(D),D.exitCode===0&&(f=await e.store.update(f,N=>Be(N,R,void 0)))}}let S=u!==void 0?be(u):w!==void 0?w:(()=>{let E=Qt(m);return E===1&&h?3:E})();return{result:{plan:n,steps:g,...b.length>0?{checkpoints:b}:{},...y.length>0?{skipped:y}:{},status:qs(S),state:{serial:f.serial}},exitCode:S}}finally{d(),c.lock.release()}}var kE="taken back by a destroy: none of the org's records is its",bE="taken back by a destroy, which deleted its store and left its records masked: a masking creates no record",Sh="a masking creates no record: it writes over those the org holds that its condition selects",EE={applying:"its last run was stopped part way",partial:"its last run was partial",failed:"its last run failed",destroying:"a removal of it was stopped part way"};function Rh(e){return`${EE[e]??e}: it names no record until it is applied whole \u2014 apply again`}function $h(e,t,n){let r=e.filter(i=>i.env===t&&(i.state?.org.alias===n||i.organizationId.slice(0,15)===n.slice(0,15)));if(r.length>1){let i=r.map(o=>`${o.organizationId}, written ${o.state?.updatedAt??"?"}`).join("; ");return{refusal:{code:"TWO_STATES",message:`${r.length} states of ${t} on this machine are of ${n}: ${i} \u2014 an alias reused for another org. Give --org the Organization Id of the one meant.`,exit:1}}}let[s]=r;return s===void 0?{refusal:{code:"NO_STATE",message:`This machine keeps no state of ${t} on ${n}: nothing was applied to it from here, or the journal directory of the apply was not restored. output reads the state alone, and reaches no org.`,exit:1}}:s.state===void 0?{refusal:{code:"STATE_DAMAGED",message:`${s.damaged??"The state does not read."} Nothing was read.`,exit:1}}:{state:s.state}}async function Ah(e,t){let n={organizationId:e.org.organizationId,env:e.env,target:e.org.alias??e.org.organizationId},r=va(Object.keys(e.resources),o=>e.resources[o]?.dependsOn??[]),s={},i=!0;for(let o of r){let a=e.resources[o];if(a===void 0)continue;let c=a.runs.at(-1),l={kind:a.kind,status:a.status,...c!==void 0?{run:c.n}:{},records:{}};if(a.status==="destroyed"){s[o]={...l,why:a.kind==="mask"?bE:kE};continue}if(a.status!=="applied"&&(i=!1),a.kind==="mask"){s[o]={...l,masked:Object.fromEntries((c?.objects??[]).map(d=>[d.objectApiName,d.masked??0])),...c?.snapshotId!==void 0?{snapshotId:c.snapshotId}:{},why:a.status==="applied"?Sh:`${Rh(a.status)}; ${Sh}`};continue}if(a.status!=="applied"){s[o]={...l,why:Rh(a.status)};continue}if(c===void 0||c.takenBack===!0){i=!1,s[o]={...l,why:"it holds no run whose records are in the org"};continue}let u=await Na(c,n,t);if("refusal"in u){i=!1,s[o]={...l,why:u.refusal};continue}s[o]={...l,records:Object.fromEntries(u.created)}}return{output:{env:e.env,org:{organizationId:e.org.organizationId,kind:e.org.kind,...e.org.alias!==void 0?{alias:e.org.alias}:{}},state:{serial:e.serial,updatedAt:e.updatedAt},resources:s},whole:i}}function Oh(e){let{org:t}=e,n=[`${e.env} on ${t.alias??t.organizationId} (${t.kind}, ${t.organizationId}): state serial ${e.state.serial}, written ${e.state.updatedAt}`];for(let[r,s]of Object.entries(e.resources)){n.push(` ${r} ${s.kind}, ${s.status}`+(s.run!==void 0?`, run ${s.run}`:""));for(let[i,o]of Object.entries(s.records))n.push(` ${i} ${o.length>0?o.join(" "):"none"}`);for(let[i,o]of Object.entries(s.masked??{}))n.push(` ${i} ${o} masked`);s.snapshotId!==void 0&&n.push(` snapshot ${s.snapshotId}, taken first`),s.why!==void 0&&n.push(` ${s.why}`)}return n}var Ch={reset:"after",destroy:"before"};function Fa(e,t){let n=Ch[e],r=t?.checkpoints?.[n];return r!==void 0?{step:n,checkpoint:r}:void 0}function xa(e){let t=e.resolved.checked.file.name,{alias:n}=e.target,r=a=>({code:"NO_CHECKPOINT",message:`${a} Nothing was written.`,exit:1}),s=e.verb==="reset"?"reset":"destroy --rewind",i=e.state;if(i===void 0)return r(`This machine keeps no state of ${t} on ${n}: ${s} rewinds the org to a checkpoint its state names. Restore the journal directory of the apply, or apply first.`);if(Fa(e.verb,i)===void 0)return r(e.verb==="reset"?`The state of ${t} on ${n} names no checkpoint taken after an apply: the file asks none (checkpoint.after), or the last apply did not take it. Apply with checkpoint.after in the file, then reset.`:`The state of ${t} on ${n} names no checkpoint taken before its first apply: the file asked none (checkpoint.before: true) when it was first applied. destroy without --rewind takes back what the environment wrote.`);let o=Object.entries(i.resources).filter(([,a])=>a.kind==="mask");if(e.verb==="destroy"&&o.length>0)return{code:"MASKED",message:`The state of ${t} on ${n} names mask resources (${o.map(([a])=>a).join(", ")}): the checkpoint taken before the first apply holds the values they wrote over, and a rewind to it would put them back into the org. destroy never unmasks: destroy without --rewind takes back what the environment wrote, and leaves its maskings as they are. Nothing was written.`,exit:1};if(e.verb==="reset"){let a=Object.entries(i.resources).filter(([,c])=>c.status!=="applied"&&c.status!=="destroyed");if(a.length>0)return r(`${a.map(([c,l])=>`${c} is ${l.status}`).join(", ")}: the last apply did not end whole, and the checkpoint taken after the apply before it no longer holds the environment the state names. Apply again, then reset.`)}}async function jh(e,t,n){let r=Fa(t.verb,t.state);if(r===void 0)return{refusal:"no checkpoint to rewind to"};e.say(`checkpoint ${r.checkpoint}: reading what a rewind to it would do`);let s=await e.runner(ce,wi({org:t.target.alias,store:ye(e.journalDir),checkpoint:r.checkpoint,dryRun:!0,acceptAutomation:t.acceptAutomation,acceptEmails:t.acceptEmails,acceptNoUndo:t.acceptNoUndo,acceptUnseen:t.acceptUnseen}),n);return rl(s)}var yt=e=>e.toLocaleString("en-US");function Nh(e,t){let{alias:n}=e.target,r=`it deletes ${yt(t.toDelete)} record(s) created since, gives ${yt(t.toGiveBack)} their values back and brings ${yt(t.toBringBack)} back from the recycle bin \u2014 whoever made these changes`+(Rr(t.lastChangedBy)!==""?`, last changed by ${Rr(t.lastChangedBy)}`:"");return e.verb==="reset"?`Type ${n} to reset it to '${t.checkpoint.name}', as ${e.resolved.checked.file.name} was applied: ${r}:`:`Type ${n} to rewind it to before ${e.resolved.checked.file.name} was first applied: ${r}; the environment's checkpoints are then deleted, and this is not undone:`}function SE(e){return{...e,resources:Object.fromEntries(Object.entries(e.resources).map(([t,n])=>[t,{...n,status:"destroyed",runs:n.runs.map(r=>({...r,takenBack:!0}))}]))}}async function Ih(e,t,n){let{target:r,resolved:s,verb:i}=t,o=s.checked.file.name,a=Fa(i,t.state),c={env:o,org:{organizationId:r.organizationId,kind:r.kind,alias:r.alias},verb:i,checkpoint:{step:Ch[i],id:a?.checkpoint??"",...n!==void 0?{name:n.checkpoint.name,takenAt:new Date(n.checkpoint.takenAt).toISOString()}:{}},...n!==void 0?{preview:{toDelete:n.toDelete,toGiveBack:n.toGiveBack,toBringBack:n.toBringBack,lastChangedBy:n.lastChangedBy}}:{}},l=(h,w)=>({result:{...c,exitCode:1,status:"failure",undo:{offered:!1,why:"nothing was rewound"},refusal:h,state:{serial:w}},exitCode:1}),u=xa(t);if(u!==void 0||a===void 0||t.state===void 0)throw new Error(u?.message??"There is no checkpoint to rewind to.");let d=t.state,f=Me(e.locksDir,r.organizationId,{operation:i,env:o,alias:r.alias},e.lockOptions);if("busy"in f)return l(Ue(f.busy).message,d.serial);let g=new AbortController,y,m=(e.onStop??Le)(h=>{y=h,e.say(`
|
|
151
|
-
|
|
152
|
-
`,"utf8"),await r.sync()}finally{await r.close()}try{await jE(n,e)}catch(s){throw await NE(n,{force:!0}),s}}function _h(e){let t=i=>({refusal:{code:"PLAN_UNREAD",message:`--plan ${e} ${i}. Nothing was read or written.`,exit:2}}),n;try{n=AE(e,"utf8")}catch(i){return t(`cannot be read: ${i instanceof Error?i.message:String(i)}`)}let r;try{r=JSON.parse(n)}catch{return t("is not JSON: it is no plan plan --out kept")}let s=Hs.safeParse(r);if(!s.success){let i=s.error.issues[0],o=i?.path.map(String).join(".")||"the plan";return t(`is no plan plan --out kept (${o}: ${i?.message??"refused"})`)}return{saved:s.data}}function Wt(e,t){return{code:"PLAN_STALE",message:`The plan kept in ${e} ${t}. Nothing was written: plan again.`.slice(0,8e3),exit:1}}function qh(e,t,n){if(e.plan.refusal!==void 0)return{code:"PLAN_REFUSED",message:`The plan kept in ${t} was refused when it was made: ${e.plan.refusal} Nothing was written: plan again.`.slice(0,8e3),exit:1};if(e.plan.quick===!0)return Wt(t,"was made with --quick, which counts nothing an apply is held to");if(e.sandforgeVersion!==n.sandforgeVersion)return Wt(t,`was made by SandForge ${e.sandforgeVersion}, and this one is ${n.sandforgeVersion}, which may read the file and the org otherwise`);if(n.now-Date.parse(e.madeAt)>Lh)return Wt(t,`was made at ${e.madeAt}, more than a day ago`)}function DE(e){return e.found?`the state at serial ${e.serial}`:"no state"}function zh(e,t,n){let r=e.plan.org;if(!de(r.organizationId,n.target.organizationId))return{code:"PLAN_OTHER_ORG",message:`The plan kept in ${t} was made for ${r.alias??r.organizationId} (${r.organizationId}), and ${n.target.alias} is ${n.target.organizationId}: a plan is applied to the org it was made for. Nothing was written.`,exit:1};if(e.file.digest!==n.digest)return Wt(t,"was made from another file: the file, or a variable or an alias it reads, changed since");let s=n.state,i=e.state;if(!(i.found===(s!==void 0)&&(!i.found||s!==void 0&&s.serial===i.serial&&s.lineage===i.lineage))){let a=s===void 0?"none":i.found&&s.lineage!==i.lineage?`at serial ${s.serial}, made again since`:`at serial ${s.serial}`;return Wt(t,`was made against ${DE(i)}, and the state is now ${a}: an apply or a destroy ran since, or a cache put back another state`)}}function Th(e){return JSON.stringify([e.kind,e.action,e.objects.map(t=>[t.object,t.wouldCreate,t.atMost,t.present,t.gone,t.changed]),(e.draws??[]).map(t=>[t.lookup,t.from,t.object,t.parents])])}function Ph(e){if(e===void 0)return"nothing of it";let t=Aa(e),n=(e.draws??[]).map(s=>s.parents!==void 0?`${s.lookup} under ${s.parents} ${s.object} record(s) of ${s.from}`:`${s.lookup} under the ${s.object} records ${s.from} creates first`).join(", "),r=[t,n].filter(Boolean).join("; ");return`${e.action}${r?` (${r})`:""}`}function Bs(e){let t=(e.checkpoints??[]).map(n=>`${n.step==="before"?"before the first write":"once applied"} '${n.name}'`+(n.refusal!==void 0?", refused":""));return t.length>0?t.join(", "):"none"}function Ks(e){let t=e.drift;return t===void 0?"not compared":t.unread!==void 0?"not read":t.differs?`differs, ${t.toDelete??0} to delete \xB7 ${t.toGiveBack??0} to give back \xB7 ${t.toBringBack??0} to bring back`:"nothing differs"}function Bh(e,t){let n=[],r=[...new Set([...e.actions,...t.actions].map(i=>i.resource))];for(let i of r){let o=e.actions.find(c=>c.resource===i),a=t.actions.find(c=>c.resource===i);o!==void 0&&a!==void 0&&Th(o)===Th(a)||n.push(`${i}: planned ${Ph(o)}, now ${Ph(a)}`)}let s=i=>i.actions.map(o=>o.resource).join(", ");return n.length===0&&s(e)!==s(t)&&n.push(`the order of the resources: planned ${s(e)}, now ${s(t)}`),Bs(e)!==Bs(t)&&n.push(`the checkpoints it takes: planned ${Bs(e)}, now ${Bs(t)}`),Ks(e)!==Ks(t)&&n.push(`the whole org against the checkpoint after the last apply: planned ${Ks(e)}, now ${Ks(t)}`),n}function Kh(e,t){return Wt(e,`is not what the org holds now, read again: ${t.join("; ")}`)}function Uh(e,t){let n=new Date(Date.parse(t.madeAt)+Lh).toISOString();return`plan kept in ${e}, for apply --plan until ${n}`}function Vh(e,t){return`the plan kept in ${e} at ${t.madeAt} holds: the org, its state, the file and every count are as it planned them`}var xE=`sandforge env \u2014 apply a sandforge.yaml to an org: the data an environment needs, declared in
|
|
143
|
+
`,n)+1}return{type:t,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(t){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let n=ao(t),r=an(n);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=ao(t),r=an(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(t,n){return this.type!=="comment"||this.indent<=n?!1:t.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(t){this.type!=="doc-mode"&&(t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(t){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:t.end?t.end.push(this.sourceToken):t.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};vg.Parser=cc});var Sg=I(cr=>{"use strict";var kg=Ya(),CS=Zn(),ar=nr(),DS=Hi(),PS=_(),NS=ac(),bg=dc();function Eg(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new NS.LineCounter||null,prettyErrors:t}}function TS(e,t={}){let{lineCounter:n,prettyErrors:r}=Eg(t),s=new bg.Parser(n?.addNewLine),o=new kg.Composer(t),i=Array.from(o.compose(s.parse(e)));if(r&&n)for(let a of i)a.errors.forEach(ar.prettifyError(e,n)),a.warnings.forEach(ar.prettifyError(e,n));return i.length>0?i:Object.assign([],{empty:!0},o.streamInfo())}function Rg(e,t={}){let{lineCounter:n,prettyErrors:r}=Eg(t),s=new bg.Parser(n?.addNewLine),o=new kg.Composer(t),i=null;for(let a of o.compose(s.parse(e),!0,e.length))if(!i)i=a;else if(i.options.logLevel!=="silent"){i.errors.push(new ar.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&n&&(i.errors.forEach(ar.prettifyError(e,n)),i.warnings.forEach(ar.prettifyError(e,n))),i}function xS(e,t,n){let r;typeof t=="function"?r=t:n===void 0&&t&&typeof t=="object"&&(n=t);let s=Rg(e,n);if(!s)return null;if(s.warnings.forEach(o=>DS.warn(s.options.logLevel,o)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:r},n))}function LS(e,t,n){let r=null;if(typeof t=="function"||Array.isArray(t)?r=t:n===void 0&&t&&(n=t),typeof n=="string"&&(n=n.length),typeof n=="number"){let s=Math.round(n);n=s<1?void 0:s>8?{indent:8}:{indent:s}}if(e===void 0){let{keepUndefined:s}=n??t??{};if(!s)return}return PS.isDocument(e)&&!r?e.toString(n):new CS.Document(e,r,n).toString(n)}cr.parse=xS;cr.parseAllDocuments=TS;cr.parseDocument=Rg;cr.stringify=LS});var Ag=I(q=>{"use strict";var FS=Ya(),MS=Zn(),zS=Ia(),uc=nr(),_S=Fn(),ht=_(),qS=dt(),BS=X(),US=lt(),KS=ft(),WS=oo(),VS=oc(),HS=ac(),JS=dc(),uo=Sg(),$g=Nn();q.Composer=FS.Composer;q.Document=MS.Document;q.Schema=zS.Schema;q.YAMLError=uc.YAMLError;q.YAMLParseError=uc.YAMLParseError;q.YAMLWarning=uc.YAMLWarning;q.Alias=_S.Alias;q.isAlias=ht.isAlias;q.isCollection=ht.isCollection;q.isDocument=ht.isDocument;q.isMap=ht.isMap;q.isNode=ht.isNode;q.isPair=ht.isPair;q.isScalar=ht.isScalar;q.isSeq=ht.isSeq;q.Pair=qS.Pair;q.Scalar=BS.Scalar;q.YAMLMap=US.YAMLMap;q.YAMLSeq=KS.YAMLSeq;q.CST=WS;q.Lexer=VS.Lexer;q.LineCounter=HS.LineCounter;q.Parser=JS.Parser;q.parse=uo.parse;q.parseAllDocuments=uo.parseAllDocuments;q.parseDocument=uo.parseDocument;q.stringify=uo.stringify;q.visit=$g.visit;q.visitAsync=$g.visitAsync});import{existsSync as aw,mkdtempSync as MO,readFileSync as cw,rmSync as zO,statSync as _O,writeFileSync as rw}from"node:fs";import{tmpdir as qO}from"node:os";import{dirname as Ce,join as Lt,resolve as To}from"node:path";import{existsSync as cn,readFileSync as Dc,readdirSync as A$,rmSync as O$}from"node:fs";import{join as vo}from"node:path";import{join as Mw}from"node:path";import{randomBytes as bw,randomUUID as yu}from"node:crypto";import{mkdirSync as Ew,realpathSync as Rw,statSync as Lr}from"node:fs";import{open as Sw,readFile as $w,readdir as Aw,rename as Ow,rm as Qo}from"node:fs/promises";import{basename as ti,dirname as Le,join as $e,resolve as Fr}from"node:path";var Nr=".my.salesforce.com",vw=/^[a-z0-9-]+--[a-z0-9]+$/,kw="scratch";function pu(e){if(e===void 0||e==="")return;let t;try{t=new URL(e).hostname.toLowerCase()}catch{return}return t.endsWith(Nr)&&t.length>Nr.length?t:void 0}function Go(e){if(e===void 0||!e.endsWith(Nr))return;let t=e.slice(0,-Nr.length).split(".");return t.every(n=>n!=="")?t:void 0}function Tr(e){return Go(e)?.slice(1).includes(kw)===!0}function ke(e){let t=Go(e);if(t===void 0||t.length>2||Tr(e))return;let[n]=t;return n!==void 0&&vw.test(n)?n:void 0}function hu(e,t){return Go(e)?.[0]===t}function xr(e,t){return e.kind!=="sandbox"||t.kind!=="sandbox"||e.host===void 0||ke(t.host)===void 0||e.organizationId.slice(0,15)===t.organizationId.slice(0,15)?!1:Pr({tier:"sandbox",organizationId:e.organizationId,username:e.username??"",instanceUrl:`https://${e.host}`},{name:t.organizationId,organizationId:t.organizationId,instanceUrl:`https://${t.host??""}`})==="myDomain"}var jw=448,si=384,oi=30,Iw=1440*6e4,Xo="state.json",Cw=/^runs\/[a-z][a-z0-9-]{0,62}\/[1-9][0-9]{0,5}\.summary\.json$/,Dw=/^runs\/[a-z][a-z0-9-]{0,62}\/[1-9][0-9]{0,5}\.summary\.removals\.json$/,Pw=/^templates\/[a-z][a-z0-9-]{0,62}\.[1-9][0-9]{0,5}\.json$/,mu=/^(?:frozen|dataops)\/[a-z][a-z0-9-]{0,62}$/,L=class extends Error{constructor(n,r){super(r);this.code=n;this.name="EnvStateError"}code};function Mr(e=process.env){return Le(ou("env",e))}function zr(e,t){let n=yn(e,t);if(n!==void 0)return`The journal directory ${Fr(t)} is inside the repository ${n} that holds the file: the state, the run summaries and the templates of its runs would be committed with it, and they name the org\u2019s records by their ids. Point SANDFORGE_JOURNAL_DIR at a folder outside the repository \u2014 in CI, $RUNNER_TEMP/sandforge \u2014 and keep it between the jobs that apply and destroy, in a cache keyed by the org.`}function yn(e,t){let n;try{n=Cr(gu(e))}catch{return}return new Ke(n).isInsideRepo(gu(t))?n:void 0}function gu(e){let t=[],n=Fr(e);for(;;)try{return $e(Rw(n),...t.reverse())}catch{let r=Le(n);if(r===n)return Fr(e);t.push(ti(n)),n=r}}function oe(e,t){return`runs/${We(e)}/${qr(t)}.summary.json`}function ii(e,t){return`runs/${We(e)}/${qr(t)}.summary.removals.json`}function Et(e,t){return`templates/${We(e)}.${qr(t)}.json`}function _r(e,t,n,r=yu()){return`env-${We(e)}-${We(t)}-${qr(n)}-${r}`}function We(e){let t=fn.safeParse(e);if(!t.success)throw new L("invalid",`Not a name of the file: "${e}"`);return t.data}function qr(e){if(!Number.isInteger(e)||e<1||e>999999)throw new L("invalid",`Not a run's rank: ${e}`);return e}function Br(e){return{version:1,env:We(e.env),lineage:yu(),serial:0,sandforgeVersion:e.sandforgeVersion,updatedAt:(e.now??new Date).toISOString(),org:{organizationId:re(e.org.organizationId),kind:e.org.kind,username:e.org.username,...e.org.alias!==void 0?{alias:e.org.alias}:{},...e.org.host!==void 0?{host:e.org.host}:{}},file:{digest:e.fileDigest},resources:{}}}function wu(e,t){return t===void 0||e.org.host===t?e:{...e,org:{...e.org,host:t}}}function wn(e){return(e?.runs.at(-1)?.n??0)+1}function Rt(e,t){let n=e.resources[t.resource],r={...t.run,n:wn(n),objects:[]};return Ur(e,t.resource,{kind:t.kind,fingerprint:t.fingerprint,dependsOn:[...t.dependsOn],status:"applying",runs:[...n?.runs??[],r]})}function ai(e,t){let n=e.resources[t];if(n===void 0)throw new L("invalid",`The state holds no resource ${t} to take back`);return Ur(e,t,{...n,status:"destroying"})}function vn(e,t,n){let r=e.resources[t];if(r===void 0)throw new L("invalid",`The state holds no resource ${t}`);let s=r.runs.map(o=>o.n===n?{...o,takenBack:!0}:o);return Ur(e,t,{...r,runs:s})}function Mt(e,t){let n=e.resources[t.resource];if(n===void 0)throw new L("invalid",`The state holds no resource ${t.resource}`);let r=[...n.runs],s=r.at(-1);if(t.run!==void 0){if(s===void 0)throw new L("invalid",`The resource ${t.resource} has no run to end`);r[r.length-1]={...s,...t.run}}return Ur(e,t.resource,{...n,status:t.status,runs:r})}function Ur(e,t,n){return{...e,resources:{...e.resources,[We(t)]:n}}}function ci(e){if(e.org.kind==="scratch")return new Date(Date.parse(e.updatedAt)+oi*Iw).toISOString()}function Kr(e){if(e.fileFolder!==null){let r=zr(e.fileFolder,e.journalDir);if(r!==void 0)return{refusal:r}}let t=new ni(e),n=gn(t.root,e.uid??vu);return n!==void 0?{refusal:n}:{store:t}}var ni=class{root;fileFolder;uid;renameFile;now;constructor(t){this.root=$e(Fr(t.journalDir),"env"),this.fileFolder=t.fileFolder,this.uid=t.uid??vu,this.renameFile=t.rename??((n,r)=>Ow(n,r)),this.now=t.now??Date.now}folderOf(t,n){let r=Zo(t);if(r===void 0)throw new L("invalid",`Not an Organization Id: "${t}"`);return $e(this.root,r,We(n))}fileOf(t,n,r){if(!Cw.test(r)&&!Pw.test(r)&&!Dw.test(r))throw new L("invalid",`Not a file of a state's folder: "${r}"`);return $e(this.folderOf(t,n),...r.split("/"))}async read(t,n){let r=this.folderOf(t,n),s=$e(r,Xo),o;try{o=await $w(s,"utf8")}catch(i){if(ri(i)==="ENOENT")return;throw i}return Nw(o,s,r)}stateFileOf(t,n){return $e(this.folderOf(t,n),Xo)}async setAside(t,n){if(this.fileFolder===null)throw new L("invalid","The states were opened to be listed, not written");let r=this.stateFileOf(t,n),s=new Date(this.now()).toISOString().replace(/\.\d{3}Z$/,"").replace(/[-:]/g,"").replace("T","-"),o=`${r}.damaged-${s}`;for(let i=2;Lr(o,{throwIfNoEntry:!1})!==void 0;i++)o=`${r}.damaged-${s}-${i}`;return await this.renameFile(r,o),o}async write(t,n){if(this.fileFolder===null)throw new L("invalid","The states were opened to be listed, not written");if(t.lineage!==n.lineage)throw new L("invalid","A state is written over its own lineage only");let r=this.folderOf(t.org.organizationId,t.env),s=await this.read(t.org.organizationId,t.env),o=s?.serial??0;if(o!==n.serial||s!==void 0&&s.lineage!==n.lineage){let a=s===void 0?"it is gone":s.lineage!==n.lineage?"it is another state, made since":`serial ${o}, not ${n.serial}`;throw new L("moved",`The state of ${t.env} on ${t.org.organizationId} changed since it was read (${a}): another apply or destroy ran, or a cache put back another state. Nothing was written: plan again.`)}let i=pn.safeParse({...t,org:{...t.org,organizationId:re(t.org.organizationId)},serial:n.serial+1,updatedAt:new Date(this.now()).toISOString()});if(!i.success)throw new L("invalid",`Not a state: ${i.error.message}`);for(let a of[Le(r),r]){let c=gn(a,this.uid);if(c!==void 0)throw new L("folder",c)}return await this.writeWhole($e(r,Xo),`${JSON.stringify(i.data,null,2)}
|
|
144
|
+
`),i.data}async update(t,n){return this.write(n(t),t)}async writeFile(t,n,r,s){if(this.fileFolder===null)throw new L("invalid","The states were opened to be listed, not written");let o=this.fileOf(t,n,r),i=this.folderOf(t,n);for(let a of[Le(i),i,Le(o)]){let c=gn(a,this.uid);if(c!==void 0)throw new L("folder",c)}return await this.writeWhole(o,s),o}async prepareFile(t,n,r){if(this.fileFolder===null)throw new L("invalid","The states were opened to be listed, not written");let s=this.fileOf(t,n,r),o=this.folderOf(t,n);for(let i of[Le(o),o,Le(s)]){let a=gn(i,this.uid);if(a!==void 0)throw new L("folder",a)}return s}async prepareFolder(t,n,r){if(this.fileFolder===null)throw new L("invalid","The states were opened to be listed, not written");if(!mu.test(r))throw new L("invalid",`Not a folder of a state's folder: "${r}"`);let s=this.folderOf(t,n),o=$e(s,...r.split("/"));for(let i of[Le(s),s,Le(o),o]){let a=gn(i,this.uid);if(a!==void 0)throw new L("folder",a)}return o}sasOf(t,n,r){if(!mu.test(r))throw new L("invalid",`Not a folder of a state's folder: "${r}"`);return $e(this.folderOf(t,n),...r.split("/"))}async remove(t,n){let r=this.folderOf(t,n);return Lr(r,{throwIfNoEntry:!1})===void 0?!1:(await Qo(r,{recursive:!0,force:!0}),!0)}async refreshedOf(t,n){let r=We(n),s;for(let o of await ei(this.root)){if(Zo(o)!==o)continue;let i;try{i=await this.read(o,r)}catch{continue}i?.org.host===void 0||!xr(i.org,t)||s!==void 0&&Date.parse(s.updatedAt)>=Date.parse(i.updatedAt)||(s={organizationId:i.org.organizationId,serial:i.serial,updatedAt:i.updatedAt,host:i.org.host,setAside:this.folderOf(o,r)})}return s}async list(){let t=[];for(let n of await ei(this.root))if(Zo(n)===n)for(let r of await ei($e(this.root,n))){if(!fn.safeParse(r).success)continue;let s=$e(this.root,n,r);try{let o=await this.read(n,r);if(o===void 0)continue;let i=ci(o);t.push({organizationId:n,env:r,folder:s,state:o,...i!==void 0?{expiresAt:i}:{}})}catch(o){t.push({organizationId:n,env:r,folder:s,damaged:ku(o)})}}return t}async sweep(){let t=this.now(),n=[];for(let{state:r,expiresAt:s,folder:o,organizationId:i,env:a}of await this.list())r===void 0||s===void 0||Date.parse(s)>t||(await Qo(o,{recursive:!0,force:!0}),n.push({organizationId:i,env:a,...r.org.alias!==void 0?{alias:r.org.alias}:{},updatedAt:r.updatedAt,expiresAt:s}));return n}async writeWhole(t,n){let r=`${t}.${process.pid}-${bw(4).toString("hex")}.tmp`,s=await Sw(r,"wx",si);try{try{await s.writeFile(n,"utf8"),await s.sync()}finally{await s.close()}await this.renameFile(r,t)}catch(o){throw await Qo(r,{force:!0}),o}}};function Nw(e,t,n){let r;try{r=JSON.parse(e)}catch{r=void 0}let s=pn.safeParse(r);if(!s.success)throw new L("damaged",`The state ${t} does not read as a state of this SandForge, and is not used: a plan made from part of it would create again what the rest names. Run ${B("env")} state recover: it sets this file aside and rebuilds the state from the run files beside it.`);let o=s.data;if(re(o.org.organizationId)!==ti(Le(n))||o.env!==ti(n))throw new L("otherOrg",`The state ${t} is of ${o.env} on ${o.org.organizationId}, not of the org and environment its folder names: it was copied or moved, and is not used. Put it back where it came from, or delete it.`);return o}function vu(){return process.getuid?.()}function gn(e,t){try{let n=Lr(e,{throwIfNoEntry:!1});if(n!==void 0&&!n.isDirectory())return`${e} is not a folder.`;Ew(e,{recursive:!0,mode:jw});let r=t();return r!==void 0&&Lr(e).uid!==r?`${e} belongs to another user, who can read the states kept there and replace them: point SANDFORGE_JOURNAL_DIR at a folder of your own.`:void 0}catch(n){return`${e} could not be made: ${ku(n)}`}}function Zo(e){try{return re(e)}catch{return}}async function ei(e){try{return(await Aw(e,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name).sort()}catch(t){if(ri(t)==="ENOENT"||ri(t)==="ENOTDIR")return[];throw t}}function ri(e){return e?.code}function ku(e){return e instanceof Error?e.message:String(e)}import{createHash as Tw}from"node:crypto";function kn(e){return e.length===0?"the file":e.map((t,n)=>typeof t=="number"?`[${t}]`:/^[A-Za-z_][A-Za-z0-9_-]*$/.test(t)?`${n===0?"":"."}${t}`:`[${JSON.stringify(t)}]`).join("")}function N(e,t){let n=e[0]==="resources"&&typeof e[1]=="string"?e[1]:void 0;return{path:e,...n!==void 0?{resource:n}:{},message:t}}function zt(e){return JSON.stringify(di(e))}function di(e){if(Array.isArray(e))return e.map(di);if(e===null||typeof e!="object")return e;let t=e;return Object.fromEntries(Object.keys(t).filter(n=>t[n]!==void 0).sort().map(n=>[n,di(t[n])]))}function ui(e){return Tw("sha256").update(e,"utf8").digest("hex")}var xw=200;function C(e,t){if(t===""||t.startsWith("-"))throw new Error(`${e} cannot be "${t}": a value that starts with "-" reads as a flag.`);return t}function be(e){return e.sweep===!0?["--sweep"]:[]}var Xe=p.string().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/),R=p.number().int().nonnegative(),Ze=p.object({objectApiName:p.string().min(1),planned:R,deleted:R,alreadyGone:R,keptChanged:R,keptDependents:R,refused:R,notVisible:R.optional(),notReached:R.optional(),heldBy:p.array(p.string()),reasons:p.array(p.string())}),Lw=p.object({objectApiName:p.string().min(1),planned:R,toDelete:R,alreadyGone:R,changedSince:R,keptChanged:R,changedBy:p.record(Xe,R),undeletable:R,notVisible:R,unread:R,reasons:p.array(p.string())}),_t=p.object({planned:R,objects:p.array(Lw),undeletable:p.array(p.object({objectApiName:p.string().min(1),records:R})).optional(),userNames:p.record(Xe,p.string())});function Fe(e,t,n){if(t===void 0||n?.length!==t.length)return[];let r=t.flatMap((s,o)=>{let i=n[o];return i!==void 0&&i!==""&&s!==""&&e.includes(s)?[i]:[]});return[...new Set(r)]}var Fw=/^Nothing(?: was)? (?:written|deleted)\.?$/i;function bu(e){return e.split(`
|
|
145
|
+
`).map(t=>t.trim()).filter(t=>t!==""&&!Fw.test(t)).at(-1)}var de=class extends Error{constructor(n,r,s,o){super(`${Ne(n)} did not answer ${r} (${s}): `+(o===""?"it printed nothing on stdout":`it printed ${JSON.stringify(o)}`));this.script=n;this.expected=r;this.reason=s;this.excerpt=o;this.name="StepAnswerError"}script;expected;reason;excerpt};function z(e,t,n,r){let s=r.trim().slice(0,xw),o;try{o=JSON.parse(r)}catch{throw new de(e,t,"not JSON",s)}let i=n.safeParse(o);if(!i.success){let a=i.error.issues[0],c=a?.path.join(".")||"the answer";throw new de(e,t,`${c}: ${a?.message??"refused"}`,s)}return i.data}var we="sandforge-checkpoint";function ie(e){return Mw(e,"checkpoints")}function zw(e){return e==="scratch"?oi:0}function bn(e,t){if(t==="before")return e.checkpoint?.before===!0?`${e.name} before`:void 0;let n=e.checkpoint?.after;return typeof n=="string"?n:void 0}function En(e){return["--org",C("--org",e.org),"--store",C("--store",e.store)]}function Wr(e){let{ignoreFields:t,maxTotal:n,excludeObjects:r}=e.checkpoint??{};return{...t!==void 0?{ignoreFields:t}:{},...n!==void 0?{maxTotal:n}:{},...r!==void 0?{excludeObjects:r}:{}}}function Eu(e){return[...(e.ignoreFields??[]).flatMap(t=>["--ignore-field",C("--ignore-field",t)]),...e.maxTotal!==void 0?["--max-total",String(e.maxTotal)]:[],...(e.excludeObjects??[]).flatMap(t=>["--exclude-object",C("--exclude-object",t)])]}function Ru(e){return["take",...En(e),...Eu(e),"--estimate","--json"]}function _w(e){return["take",...En(e),"--name",C("--name",e.name),"--keep-days",String(e.keepDays),...Eu(e),"--json"]}function fi(e){if(e.code!=="TOO_MANY_RECORDS")return e;let t=e.message.indexOf(": pick fewer objects"),n=t===-1?e.message.replace(/\s*No record was read\.$/,""):e.message.slice(0,t);return{...e,message:`${n}: leave objects out with checkpoint.excludeObjects, or raise checkpoint.maxTotal in the file, ${fd.toLocaleString("en-US")} at most. No record was read.`}}function Su(e){return["preview",...En(e),"--checkpoint",wt.parse(e.checkpoint),"--json"]}function pi(e){return["rewind",...En(e),"--checkpoint",wt.parse(e.checkpoint),e.dryRun?"--dry-run":"--yes",...e.acceptAutomation?["--accept-automation"]:[],...e.acceptEmails===!0?["--accept-emails"]:[],...e.acceptNoUndo?["--accept-no-undo"]:[],...e.acceptUnseen===!0?["--accept-unseen"]:[],"--json"]}function qw(e){return["delete",...En(e),"--checkpoint",wt.parse(e.checkpoint),"--yes","--json"]}var hi=p.object({code:p.string().min(1),message:p.string().min(1)}),Rn=p.object({refusal:hi}),Bw=p.union([p.object({mode:p.string(),estimate:p.object({records:R,apiRequests:R,apiRequestsLeft:p.number(),seconds:p.number().nonnegative(),bytes:R}),refusal:hi.optional()}),Rn]),Uw=p.union([p.object({checkpoint:p.object({checkpointId:wt,name:p.string().min(1),takenAt:p.string().min(1)})}),Rn]),Kw=p.union([p.object({checkpoint:p.object({id:wt,name:p.string().min(1),takenAt:p.string().min(1)}),toDelete:R,toGiveBack:R,toBringBack:R,toRecreate:R,differs:p.boolean(),diff:p.object({objects:p.array(p.object({objectApiName:p.string().min(1),lastChangedBy:p.record(p.string(),R),touched:R})),userNames:p.record(p.string(),p.string())}),refusal:hi.optional()}),Rn]),li=p.object({planned:R,done:R,left:R}),Ww=p.union([p.object({checkpoint:p.object({id:wt,name:p.string().min(1)}),rewindId:p.string().min(1),status:p.enum(["success","partial","unstable","failure","cancelled"]),deleted:li,givenBack:li,broughtBack:li,undo:p.object({until:p.string().min(1)}).optional(),residual:p.array(p.object({object:p.string(),reason:p.string(),count:R}))}),Rn]),Vw=p.union([p.object({deleted:p.array(p.string()),kept:p.array(p.string())}),Rn]);function Hw(e){return z(we,"the estimate of a take",Bw,e)}function Jw(e){return z(we,"a take",Uw,e)}function $u(e){return z(we,"a preview",Kw,e)}function Yw(e){return z(we,"a rewind",Ww,e)}function Gw(e){return z(we,"a deletion",Vw,e)}function Qw(e){return e.stderr.trim().split(`
|
|
146
|
+
`).map(t=>t.trim()).filter(Boolean).at(-1)??"it said nothing"}function qt(e,t){try{return{answer:t(e.stdout),raw:JSON.parse(e.stdout)}}catch(n){if(!(n instanceof de))throw n;return{unread:`exit ${e.code}: ${Qw(e)}`}}}function Vr(e,t,n){let r=[],s=bn(e,"before");s!==void 0&&n&&Xw(t)&&r.push({step:"before",name:s});let o=bn(e,"after");return o!==void 0&&(n||t?.checkpoints?.after===void 0)&&r.push({step:"after",name:o}),r}function Au(e){return Object.values(e?.resources??{}).some(t=>t.status!=="destroyed")}function Xw(e){return e?.checkpoints?.before===void 0&&!Au(e)}function Ou(e,t){return e.checkpoint?.before!==!0||t?.checkpoints?.before!==void 0?[]:Au(t)?["checkpoint.before is taken before the first apply of an environment, and the org holds what an earlier apply wrote without one: it is not taken now, since a rewind to it would keep those records. Destroy the environment, then apply, to take it"]:[]}function ju(e){let t=qt(e,Hw);if("unread"in t)return t;let n=t.answer;if(!("estimate"in n))return{refusal:fi(n.refusal)};let{records:r,apiRequests:s,seconds:o,bytes:i}=n.estimate;return{estimate:{records:r,apiRequests:s,seconds:o,bytes:i},...n.refusal!==void 0?{refusal:fi(n.refusal)}:{}}}function Iu(e,t,n=0){return e.map(({step:r,name:s})=>t===void 0?{step:r,name:s,unread:"not read: --quick"}:"unread"in t?{step:r,name:s,unread:t.unread}:{step:r,name:s,..."estimate"in t?{estimate:r==="after"?{...t.estimate,records:t.estimate.records+n}:t.estimate}:{},...t.refusal!==void 0?{refusal:t.refusal}:{}})}var Hr={before:"before the first write",after:"once applied"};function Cu(e){let t=e.filter(n=>n.refusal!==void 0);if(t.length!==0)return t.map(n=>`The checkpoint the file asks ${Hr[n.step]}, '${n.name}', would be refused: ${n.refusal?.message??""}`).join(" ")+" Take checkpoint.before or checkpoint.after out of the file, or fix what refuses it."}function Du(e){let t=0,n=[];for(let r of e)r.estimate!==void 0?t+=r.estimate.apiRequests:n.push(`the checkpoint ${Hr[r.step]}, not estimated`);return{estimate:t,notCounted:n}}function Pu(e,t){let n=qt(t,$u);if("unread"in n)return{checkpoint:e,differs:!1,unread:n.unread};let r=n.answer;return"differs"in r?{checkpoint:e,differs:r.differs,toDelete:r.toDelete,toGiveBack:r.toGiveBack,toBringBack:r.toBringBack}:{checkpoint:e,differs:!1,unread:r.refusal.message}}var Me=e=>e.toLocaleString("en-US");function Nu(e){let t=[];for(let r of e.checkpoints??[]){let s=`checkpoint ${Hr[r.step]}: '${r.name}'`,{estimate:o}=r;o!==void 0?t.push(`${s}, about ${Me(o.records)} records, ${Me(o.apiRequests)} API requests, ${Me(Math.ceil(o.seconds))} s, ${kt(o.bytes/(1024*1024))} MB on this machine`):t.push(`${s}, not estimated (${r.unread??"no estimate"})`),r.refusal!==void 0&&t.push(` refused: ${r.refusal.message}`)}let n=e.drift;if(n!==void 0){let r=`the whole org against the checkpoint after the last apply (${n.checkpoint})`;t.push(n.unread!==void 0?`${r}: not compared, ${n.unread}`:n.differs?`${r}: differs, ${Me(n.toDelete??0)} to delete \xB7 ${Me(n.toGiveBack??0)} to give back \xB7 ${Me(n.toBringBack??0)} to bring back`:`${r}: nothing differs among the objects and fields it compares`)}return t}async function mi(e,t,n){e.say(`checkpoint ${Hr[t.step]}: taking '${t.name}'`);let r=await e.runner(we,_w({org:t.org.alias,store:ie(e.journalDir),name:t.name,keepDays:zw(t.org.kind),...t.ignoreFields!==void 0?{ignoreFields:t.ignoreFields}:{},...t.maxTotal!==void 0?{maxTotal:t.maxTotal}:{},...t.excludeObjects!==void 0?{excludeObjects:t.excludeObjects}:{}}),n),s=qt(r,Jw),o="answer"in s?s.answer:void 0,i="raw"in s?s.raw:void 0;if(r.code===0&&o!==void 0&&"checkpoint"in o)return{result:{step:t.step,checkpoint:o.checkpoint.checkpointId,exitCode:r.code,answer:i},checkpoint:o.checkpoint.checkpointId};let a=o!==void 0&&"refusal"in o?`${o.refusal.code}: ${fi(o.refusal).message}`:"unread"in s?s.unread:`exit ${r.code}`;return{result:{step:t.step,exitCode:r.code===0?1:r.code,refusal:a.slice(0,4e3),...i!==void 0?{answer:i}:{}}}}async function Bt(e,t,n){e.say(`checkpoint ${t.checkpoint}: deleted from this machine, ${t.why}`);let r=await e.runner(we,qw({org:t.org.alias,store:ie(e.journalDir),checkpoint:t.checkpoint}),n),s=qt(r,Gw),o="answer"in s?s.answer:void 0,i=o!==void 0&&"deleted"in o&&o.deleted.includes(t.checkpoint),a=o!==void 0&&"refusal"in o&&o.refusal.code==="NOT_FOUND";if(i||a)return{step:"delete",checkpoint:t.checkpoint,exitCode:0};let c=o!==void 0&&"refusal"in o?`${o.refusal.code}: ${o.refusal.message}`:o!==void 0&&"kept"in o?"kept: a take, a rewind or an undo of the org is running":"unread"in s?s.unread:`exit ${r.code}`;return e.say(` not deleted: ${c}`),{step:"delete",checkpoint:t.checkpoint,exitCode:r.code===0?1:r.code,refusal:c.slice(0,4e3)}}function Jr(e){let t=[];return e?.checkpoints?.after!==void 0&&t.push({step:"after",checkpoint:e.checkpoints.after}),e?.checkpoints?.before!==void 0&&t.push({step:"before",checkpoint:e.checkpoints.before}),t}function et(e,t,n){let r={...e.checkpoints};n!==void 0?r[t]=n:delete r[t];let s={...e,checkpoints:r};return Object.keys(r).length===0&&delete s.checkpoints,s}function Tu(e){let t=qt(e,$u);if("unread"in t)return{refusal:t.unread};let n=t.answer;if(!("differs"in n))return{refusal:n.refusal.message};let r={};for(let s of n.diff.objects)for(let[o,i]of Object.entries(s.lastChangedBy)){let a=n.diff.userNames[o]??o;r[a]=(r[a]??0)+i}return{checkpoint:n.checkpoint,toDelete:n.toDelete,toGiveBack:n.toGiveBack,toBringBack:n.toBringBack,lastChangedBy:r,differs:n.differs,...n.refusal!==void 0?{refusal:n.refusal}:{}}}function Yr(e){return Object.entries(e).sort((t,n)=>n[1]-t[1]).map(([t,n])=>`${t} ${Me(n)}`).join(", ")}function xu(e,t,n){let r=`'${n.checkpoint.name}' (${n.checkpoint.id}), taken ${n.checkpoint.takenAt}`,s=[e==="reset"?`reset ${t} to the checkpoint taken after the last apply, ${r}:`:`destroy by rewinding ${t} to the checkpoint taken before the first apply, ${r}:`,` ${Me(n.toDelete)} to delete \xB7 ${Me(n.toGiveBack)} to give back \xB7 ${Me(n.toBringBack)} to bring back`+(n.differs?"":" \u2014 nothing differs: nothing to rewind")],o=Yr(n.lastChangedBy);return o!==""&&s.push(` last changed by: ${o}`),n.refusal!==void 0&&s.push(` refused: ${n.refusal.message}`),s}function Lu(e){let t=qt(e,Yw),n="answer"in t?t.answer:void 0,r="raw"in t?t.raw:void 0;if(n!==void 0&&"status"in n)return{exitCode:e.code,status:n.status,answer:r,done:{deleted:n.deleted.done,givenBack:n.givenBack.done,broughtBack:n.broughtBack.done,differing:n.residual.reduce((o,i)=>o+i.count,0)},...n.undo!==void 0?{undoUntil:n.undo.until}:{}};let s=n!==void 0&&"refusal"in n?n.refusal:{code:"UNREAD",message:"unread"in t?t.unread:`exit ${e.code}`};return{exitCode:e.code===0?1:e.code,status:e.code>=128?"cancelled":"failure",...r!==void 0?{answer:r}:{},refusal:s}}function Fu(e,t){return e.deleted?{offered:!1,why:"the environment\u2019s checkpoints are deleted with it, the journal of this rewind among them: a destroy is undone by applying again"}:t.undoUntil===void 0?{offered:!1,why:t.status==="failure"||t.status==="cancelled"?"the checkpoint script offers no undo of a rewind that wrote nothing it can take back":"the checkpoint script offers none: the rewind wrote nothing"}:{offered:!0,until:new Date(Date.parse(t.undoUntil)).toISOString(),line:`${B("checkpoint")} undo --org ${e.alias} --checkpoint ${e.checkpoint} --store ${ie(e.journalDir)}`}}function Mu(e){return e.offered?`undo it until ${e.until}, sooner if the recycle bin fills: ${e.line}`:`no undo: ${e.why}`}var Gr="STATE_MOVED",zu="No flag lifts this: an environment is never applied to a production org.";function Ee(e,t){return e.length>=15&&t.length>=15&&e.slice(0,15)===t.slice(0,15)}function _u(e,t,n){if("unread"in t)return t.error!==void 0&&vd(t.error)!==void 0?{refusal:{code:"UNTYPED",message:Rd(e,t.error,{tool:"sandforge env",action:"write",readOnly:"plan"}),exit:1}}:{refusal:{code:"PRODUCTION",message:`${e} did not say what org it is (${t.unread}), and an environment is applied to no org it cannot tell from a production one. Nothing was read or written. ${zu}`,exit:1}};if($r(t)){let o=t.edition?`IsSandbox false, edition ${t.edition}`:"IsSandbox false, and no edition";return{refusal:{code:"PRODUCTION",message:`${e} is a production org (its Organization record says ${o}): an environment is applied to scratch orgs, Developer Edition orgs and the sandboxes its file lists. Nothing was read or written. ${zu}`,exit:1}}}let r=t.sandbox?n.scratch===!0?"scratch":"sandbox":"developer",s=pu(n.instanceUrl);return{target:{alias:e,organizationId:t.id,kind:r,username:n.username,...s!==void 0?{host:s}:{}}}}var qu={scratch:"a scratch org",developer:"a Developer Edition org",sandbox:"a sandbox"};function gi(e,t){if(t.kind!=="sandbox")return;if(e.sandboxes.some(r=>typeof r=="string"&&Ee(r,t.organizationId)))return{by:"organizationId"};let n=ke(t.host);if(n!==void 0&&e.sandboxes.some(r=>typeof r!="string"&&r.myDomain===n))return{by:"myDomain",myDomain:n}}function Bu(e){return e?"listed by its My Domain; its Organization Id changed since the last apply":"listed by its My Domain"}function Zw(e,t){let n=t.organizationId,r=re(n);if(e.protect.some(i=>typeof i=="string"&&Ee(i,n)))return{code:"PROTECTED",message:`${t.alias} (${r}) is listed under targets.protect: the file refuses it whatever else it says. Nothing was read or written.`,exit:1};let s=e.protect.flatMap(i=>typeof i=="string"?[]:[i.myDomain]),o=s.find(i=>hu(t.host,i));if(o!==void 0)return{code:"PROTECTED",message:`${t.alias} (${r}, on ${t.host??""}) is listed under targets.protect by its My Domain ${o}: the file refuses it whatever else it says. Nothing was read or written.`,exit:1};if(s.length>0&&t.kind==="sandbox"&&t.host===void 0){let i=s.length===1?`lists ${s.join(", ")} by its My Domain: whether it is that sandbox`:`lists ${s.join(", ")} by their My Domains: whether it is one of them`;return{code:"PROTECTED",message:`${t.alias} (${r}) is a sandbox the sf CLI reaches by no My Domain host, and targets.protect ${i} cannot be told, and a protected org is never let through on a guess. Nothing was read or written. Sign in to it by its My Domain's URL to have it told apart.`,exit:1}}}function ev(e,t){let n=re(t.organizationId),r=ke(t.host),s=e.sandboxes.some(c=>typeof c!="string"),o="nothing Salesforce says tells a sandbox that holds a client's records from a developer's, so each one the file writes to is listed, reviewed with the file.",i=" If it is a scratch org, the sf CLI did not say so: its display names no Dev Hub for it, as when the org was logged in with an auth URL alone.";if(r!==void 0)return{code:"NOT_LISTED",message:`${t.alias} is a sandbox, and its Organization Id ${n} is not listed under targets.sandboxes, nor its My Domain ${r}: ${o} A refresh changes the Id: a sandbox listed by it before its refresh is listed again, or listed by its My Domain, which a refresh keeps: { myDomain: ${r} }. Nothing was read or written.`,exit:1};let a=Tr(t.host)?` Its host, ${t.host??""}, is a scratch org's, which no My Domain lists: the sf CLI did not say it is one, its display naming no Dev Hub for it, as when the org was logged in with an auth URL alone. Log its Dev Hub in on this machine.`:s?t.host===void 0?" The sf CLI reaches it by no My Domain host: no My Domain the file lists can name it.":` Its host, ${t.host}, is no sandbox's: no My Domain the file lists can name it.`:"";return{code:"NOT_LISTED",message:`${t.alias} is a sandbox, and its Organization Id ${n} is not listed under targets.sandboxes: ${o} A refresh changes the Id: a sandbox listed before its refresh is listed again.${a} Nothing was read or written.`+(Tr(t.host)?"":i),exit:1}}function Uu(e,t){let n=Zw(e,t);if(n!==void 0)return n;if(!e.kinds.includes(t.kind)){let r=t.kind==="sandbox"?" If it is a scratch org, the sf CLI did not say so: its display names no Dev Hub for it, as when the org was logged in with an auth URL alone. Log its Dev Hub in on this machine, or list the org as a sandbox.":"";return{code:"KIND",message:`${t.alias} is ${qu[t.kind]}, and the file's targets.kinds allows ${e.kinds.join(", ")}: add ${t.kind} to targets.kinds to apply it there. Nothing was read or written.${r}`,exit:1}}if(t.kind==="sandbox"&&gi(e,t)===void 0)return ev(e,t)}function tt(e){return{code:e.code==="otherOrg"?"OTHER_ORG":"STATE_DAMAGED",message:`${e.message} Nothing was read or written in the org.`,exit:1}}function Ku(e,t,n){if(!(e.env===t&&Ee(e.org.organizationId,n.organizationId)))return{code:"OTHER_ORG",message:`The state read for ${t} on ${n.alias} is of ${e.env} on ${e.org.organizationId}: a state of another org is never applied. Nothing was read or written.`,exit:1}}function Wu(e,t,n,r=!1,s){if(s!==void 0&&!r&&xr({...s,kind:"sandbox"},e)){let{organizationId:i,serial:a,updatedAt:c,setAside:d}=s,u={organizationId:i,serial:a,updatedAt:c,setAside:d};return{warning:yi(e.alias,u),refreshed:u}}let o=`this machine keeps no state of ${t} on ${e.alias}: records an earlier apply left there, from another machine or a cache that was not restored, cannot be told from the org\u2019s own, and would be created twice`+(r?`; it keeps runs of ${t} on ${e.alias}, and ${B("env")} state recover rebuilds the state from them`:"");return e.kind==="scratch"||n?{warning:o}:{refusal:{code:"NO_STATE",message:`${o.charAt(0).toUpperCase()}${o.slice(1)}. On ${qu[e.kind]} that lives on, apply asks --accept-no-state to go ahead: restore the journal directory of the apply before it, or give the flag. Nothing was written.`,exit:1}}}function yi(e,t){return`none for this Organization Id; ${e} was refreshed since the last apply, which this machine kept under ${t.organizationId} (serial ${t.serial}, ${t.updatedAt.slice(0,10)}): the refresh took what it held, and this apply starts anew. That state is set aside, kept: ${t.setAside}`}function Qr(e,t){return t?{code:"STORE_IN_REPOSITORY",message:e,exit:2}:{code:"STORE",message:e,exit:1}}function nt(e){return{code:"LOCKED",message:Xd(e),exit:1}}function Sn(e){return{code:"CHECKPOINT_ACT",message:`${e.charAt(0).toUpperCase()}${e.slice(1)}`,exit:1}}import{readFileSync as tv}from"node:fs";import{join as Hu}from"node:path";var Q="sandforge-clone",Ju=1e4,Vu=1e6,nv=["inputMode","recordId","soqlQuery","queryScope","maxRoots","templateId","aiPrompt","dryRun"];function rv(e){let[t]=e;return`SELECT Id FROM ${t?.object??""}${t?.where!==void 0?` WHERE ${t.where}`:""}`}function sv(e,t,n){let r=["resources",e,"template"],s=u=>({refusals:[N(r,u)]}),o;try{o=tv(Hu(n,t.file),"utf8")}catch(u){return s(`${t.file} cannot be read: ${u instanceof Error?u.message:String(u)}`)}if(o.length>Vu)return s(`${t.file} is larger than ${Vu} bytes`);let i;try{i=JSON.parse(o.replace(/^\uFEFF/,""))}catch{return s(`${t.file} is not JSON`)}let a=Array.isArray(i)?i:[i],c=a.find(u=>u!==null&&typeof u=="object"&&u.id===t.id);if(c===void 0){let u=a.map(l=>l!==null&&typeof l=="object"?l.id:"").filter(l=>typeof l=="string"&&l!=="");return s(`${t.file} holds no template "${t.id}"`+(u.length>0?`: it holds ${u.join(", ")}`:": it holds none"))}let d=_o.safeParse(c);return d.success?{entry:d.data}:{refusals:d.error.issues.map(u=>N(r,`the template "${t.id}" of ${t.file} is refused by Forge's template schema at ${u.path.map(String).join(".")||"its top"}: ${u.message}`))}}function Yu(e,t,n,r,s){let o=["resources",t],i=[];if(n.depth==="all")return{run:{source:n.source,wholeOrg:{anonymize:n.anonymize!==void 0,keepContactPoints:n.keepContactPoints===!0,...n.fit!==void 0?{fit:n.fit==="share"?{}:structuredClone(n.fit)}:{}},...n.maxTotal!==void 0?{maxTotal:n.maxTotal}:{},acceptAutomation:n.accept?.automation===!0,acceptRealData:n.accept?.realData===!0},warnings:i};let a;if(n.template!==void 0){let g=sv(t,n.template,r);if("refusals"in g)return g;a=g.entry}let c={...a?.config};for(let g of nv)delete c[g];if(n.tables!==void 0&&c.expandOrphanParents===!0)return{refusals:[N([...o,"template"],"the template brings orphan parents (expandOrphanParents), which go with a clone of one record: a clone of tables reads the parents its tables point at, named with them")]};a?.files!==void 0&&i.push(N([...o,"template"],"the template copies the files of the cloned records: an environment copies none, and the clone writes the records alone"));let d=n.depth??c.depth,u=(d??"custom")==="custom"?n.customDepth??c.customDepth:void 0;delete c.customDepth;let l=s.toISOString(),f={id:`env-${e}-${t}`,name:`${e}/${t}`,description:`The ${t} resource of the ${e} environment`,config:{anonymizePII:!1,skipEmpty:!0,batchSize:"auto",...c,...n.tables!==void 0?{inputMode:"soql",soqlQuery:rv(n.tables)}:{inputMode:"record",...n.record?.id!==void 0?{recordId:n.record.id}:{}},depth:d??"custom",...u!==void 0?{customDepth:u}:{},...n.maxNodes!==void 0?{maxNodes:n.maxNodes}:{},...n.keepContactPoints!==void 0?{keepContactPoints:n.keepContactPoints}:{},...n.anonymize!==void 0?{anonymizePII:!0}:{}},...n.anonymize!==void 0?{anonymization:structuredClone(n.anonymize)}:a?.anonymization!==void 0?{anonymization:structuredClone(a.anonymization)}:{},objectCount:0,recordCount:0,createdAt:l,lastUsedAt:l},h=_o.safeParse(f);return h.success?{run:{source:n.source,template:h.data,...n.record!==void 0?{record:{...n.record}}:{},...n.records!==void 0?{records:{...n.records}}:{},...n.tables!==void 0?{tables:n.tables.map(g=>({...g}))}:{},...n.maxTotal!==void 0?{maxTotal:n.maxTotal}:{},acceptAutomation:n.accept?.automation===!0,acceptRealData:n.accept?.realData===!0},warnings:i}:{refusals:h.error.issues.map(g=>N(o,`the template it converts into is refused by Forge's template schema at ${g.path.map(String).join(".")||"its top"}: ${g.message}`))}}function Gu(e){return e.tables!==void 0?e.tables.map(t=>({object:t.object})):e.records!==void 0?[{object:e.records.object}]:e.record?.object!==void 0?[{object:e.record.object}]:[]}function Xr(e){return zd(e.object,{...e.where!==void 0?{where:e.where}:{},...e.orderBy!==void 0?{orderBy:e.orderBy}:{},limit:e.limit},void 0,e.limit)}function Zr(e,t,n,r){let s=o=>o.replace(/[^A-Za-z0-9_-]/g,"-");return Hu(Hd(e),`env-${s(t.slice(0,15))}-${s(n)}-${s(r)}.json`)}function Qu(e){if(e.wholeOrg)return e.wholeOrg.anonymize;let t=e.template?.anonymization?.rules??{};return e.template?.config.anonymizePII===!0&&Object.values(t).some(n=>n!==void 0)}function ov(e){return e.edition?`its Organization record says IsSandbox false, edition ${e.edition}`:"its Organization record says IsSandbox false, and no edition"}function iv(e,t,n){if(e.acceptRealData||Qu(e))return;let r=e.template?.config.anonymizePII===!0?" Its anonymize sets a method for no category of personal field, so it does not count.":"";return`its source, ${t}, is a production org (${ov(n)}): what it clones is real people\u2019s data, written as read into an org built for tests.${r} Give the resource anonymize \u2014 Forge\u2019s anonymization, a method for each category of personal field \u2014 or, reviewed in the file, accept: { realData: true }. Emails and phone numbers are neutralized either way, unless keepContactPoints: true`}function Xu(e,t){let n=t.read;if(n===void 0||"refusal"in n||n.production!==!0)return[];let r=Object.entries(e.template?.anonymization?.rules??{}).filter(([,i])=>i!==void 0).map(([i,a])=>`${i} ${String(a)}`),s=Qu(e)?e.wholeOrg?"anonymized, every personal field by its category\u2019s default method":`anonymized as its anonymize says (${r.join(", ")})`:"written as read, as the file accepts (accept: { realData: true })",o=e.wholeOrg?e.wholeOrg.keepContactPoints:e.template?.config.keepContactPoints===!0;return[`real data: its source, the ${t.role} org (${t.alias}), is a production org; what it clones is ${s}`,o?"contact points: written as read (keepContactPoints: true)":"contact points: neutralized before writing (emails under .invalid, phone numbers in a fictional range), as the clone does unless keepContactPoints"]}async function Zu(e,t,n,r){let s=`the ${n} org (${r})`,o;try{o=await Sr(e)}catch(l){return{refusal:`${s} could not be read: ${wi(l)}`}}let i=o.id,a=$r(o);if(a){let l=iv(t,s,o);if(l!==void 0)return{refusal:l}}let c={organizationId:i,...a?{production:!0}:{}};if(t.records!==void 0){let{records:l}=t;try{let h=(await e.query(Xr(l))).records.flatMap(g=>typeof g.Id=="string"?[g.Id]:[]);if(h.length===0){let g=l.where!==void 0?` WHERE ${l.where}`:"";return{refusal:`its records query chooses no ${l.object} in ${s}${g!==""?` (${g.trim()})`:""}: there is nothing to clone. Count what it chooses there with sf data query -o ${r} -q "SELECT COUNT() FROM ${l.object}${g}", and check its where`}}return{...c,roots:{count:h.length,sha256:_d(h)}}}catch(f){return{refusal:`its records query could not be read in ${s}: ${wi(f)}`}}}let d=t.record;if(d?.object===void 0||d.where===void 0)return c;let u=`${d.object} WHERE ${d.where}`;try{let l=(await e.query(`SELECT Id FROM ${u} LIMIT 2`)).records;return l.length===1&&typeof l[0]?.Id=="string"?{...c,recordId:l[0].Id}:l.length===0?{refusal:`its record query finds no ${d.object} in ${s} (WHERE ${d.where}): a record named by a query is one its source answers with exactly one row`}:{refusal:`its record query finds ${(await e.query(`SELECT COUNT() FROM ${u}`)).totalSize} ${d.object} records in ${s} (WHERE ${d.where}), not one: narrow the where to one row, or name the record by its id`}}catch(l){return{refusal:`its record query could not be read in ${s}: ${wi(l)}`}}}function el(e,t){let n=t!==void 0&&"organizationId"in t?t:void 0;return{kind:"forge",kindVersion:1,source:n?.organizationId.slice(0,15)??null,record:e.record===void 0?null:(e.record.id??n?.recordId)?.slice(0,15)??{unread:e.record},tables:e.tables??null,config:e.template?.config??null,anonymization:e.template?.anonymization??null,...e.wholeOrg?{wholeOrg:e.wholeOrg}:{},...e.records?{records:{...e.records,roots:n?.roots?.sha256??{unread:!0}}}:{}}}function tl(e){if(e.wholeOrg)return av(e,e.wholeOrg);if(e.recordId===void 0&&e.records===void 0&&(e.tables??[]).length===0)throw new Error("A forge resource clones a record, the records a query chooses or tables: its line names none.");return["--source",C("--source",e.source),"--target",C("--target",e.target),...e.recordId!==void 0?["--record",C("--record",e.recordId)]:e.records!==void 0?["--query",C("--query",Xr(e.records)),"--max-roots",String(e.records.limit),...e.rootsPlanFile!==void 0?["--roots-plan",C("--roots-plan",e.rootsPlanFile)]:[]]:(e.tables??[]).flatMap(t=>["--object",C("--object",t.object),...t.where!==void 0?["--where",C("--where",t.where)]:[]]),"--template",C("--template",e.templateFile),"--max-total",String(e.maxTotal),"--skip-preflight",...e.acceptAutomation?["--accept-automation"]:[]]}function av(e,t){return["--source",C("--source",e.source),"--target",C("--target",e.target),"--depth","all","--config",C("--config",e.templateFile),"--max-total",String(e.maxTotal),"--skip-preflight",t.anonymize?"--anonymize":"--no-anonymize",...t.keepContactPoints?["--keep-contact-points"]:[],...t.fit!==void 0?["--fit","share",...cv(t.fit)]:[],...e.acceptAutomation?["--accept-automation"]:[]]}function cv(e){let t=e.window;return[...e.withinMB!==void 0?["--fit-within",String(e.withinMB)]:[],...e.seed!==void 0?["--fit-seed",String(e.seed)]:[],...e.draw!==void 0?["--fit-draw",e.draw]:[],...t!==void 0?["--fit-window",t.lastDays!==void 0?`${t.field}:${t.lastDays}d`:`${t.field}:${t.from??""}..${t.to??""}`]:[],...Object.entries(e.where??{}).flatMap(([n,r])=>["--fit-where",C("--fit-where",`${n}=${r}`)]),...(e.strata??[]).flatMap(n=>["--fit-strata",C("--fit-strata",n)])]}function nl(e){return[...tl(e),"--dry-run","--json"]}function rl(e){return[...tl(e),...e.wholeOrg?["--yes"]:[],"--summary",C("--summary",e.summary),"--json"]}function sl(e){return["--remove",C("--remove",e.summary),"--target",C("--target",e.target),...e.includeChanged===!0?["--include-changed"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[]]}function ol(e){return[...sl(e),...be(e),"--json"]}function il(e){return[...sl(e),"--preview",...be(e),"--json"]}function al(e){return["--verify",C("--verify",e.summary),"--target",C("--target",e.target),"--source",C("--source",e.source),"--json"]}var dv=p.enum(["SingleEmail","DailyWorkflowEmails"]),uv=p.object({tool:p.literal(Q),version:p.literal(1),dryRun:p.literal(!0),result:p.object({wouldInsertCount:R,failedCount:R}),writePlan:p.object({totalRows:R,storageBytes:R,objects:p.array(p.object({objectApiName:p.string().min(1),rows:R,storageBytes:R,mayAdd:R.optional()})),emails:p.array(p.object({limit:dv,emails:R})).optional()}).optional(),wouldBeRefused:p.array(p.string()).optional(),wouldBeRefusedCodes:p.array(p.string()).optional(),targetGaps:p.object({gaps:p.array(p.object({kind:p.string().min(1),severity:p.string().min(1),objectApiName:p.string().min(1),field:p.string().min(1).optional()}).loose())}).loose().optional()}),lv=p.object({tool:p.literal(Q),version:p.literal(1),dryRun:p.literal(!1),targetOrgId:Xe.optional(),result:p.object({successCount:R,failedCount:R,createdByObject:p.array(p.object({objectApiName:p.string().min(1),sourceIds:p.array(Xe)})),remapInJournal:p.literal(!0).optional(),createdCountByObject:p.array(p.object({objectApiName:p.string().min(1),created:R})).optional(),errors:p.array(p.object({objectApiName:p.string().min(1),failedCount:R,samples:p.array(p.unknown()).optional()}))}),running:p.literal(!0).optional(),interrupted:p.literal(!0).optional(),error:p.string().optional()}),fv=p.object({tool:p.literal(Q),version:p.literal(1),action:p.literal("remove"),summary:p.string().min(1),target:p.string().min(1),includeChanged:p.boolean(),result:p.object({status:p.enum(["success","partial","failure","cancelled"]),planned:R,objects:p.array(Ze),sweep:p.object({status:p.string()}).loose().optional()}),elapsedMs:R}),pv=p.object({tool:p.literal(Q),version:p.literal(1),action:p.literal("remove-preview"),summary:p.string().min(1),target:p.string().min(1),includeChanged:p.boolean(),preview:_t,refusals:p.array(p.string()),refusalCodes:p.array(p.string()).optional(),notes:p.array(p.string()),elapsedMs:R}),hv=p.object({tool:p.literal(Q),version:p.literal(1),action:p.literal("verify"),result:p.object({verdict:p.enum(["verified","partial","unstable"]),attempts:R,objects:p.array(p.object({objectApiName:p.string().min(1),expected:R,present:R,deleted:R,notVisible:R,changed:R,linksChecked:R,linksBroken:R,error:p.string().optional()})),linksUnchecked:p.string().optional()})});function cl(e,t){let n=new Set((t?.config.defaultValues??[]).map(s=>`${s.object}.${s.field}`.toLowerCase())),r=(e.targetGaps?.gaps??[]).filter(s=>s.severity==="blocking").flatMap(s=>{let o=s.field!==void 0?`${s.objectApiName}.${s.field}`:s.objectApiName;switch(s.kind){case"required_field_missing":return n.has(o.toLowerCase())?[]:[`${o}, which the org requires and the clone does not write`];case"object_not_createable":case"object_through_parent":return[`${o}, which the user it writes as may not create`];case"object_feature_off":return[`${o}, which a feature or licence the org has not turned on keeps closed`];case"api_budget":return["more API requests than the org has left today"];default:return[`${o} (${s.kind})`]}});if(r.length!==0)return`the org to fill would refuse its rows: ${r.join("; ")}. Give a field the org requires a value in the template's defaultValues (template: { file, id }), leave out an object its user may not create, or run it once the org has requests left`}function dl(e){return z(Q,"the summary of a dry run",uv,e)}function $n(e){return z(Q,"the summary of a run",lv,e)}function ul(e){return z(Q,"the outcome of a removal",fv,e)}function ll(e){return z(Q,"the preview of a removal",pv,e)}function fl(e){return z(Q,"a verification",hv,e)}function pl(e){let t=e.writePlan,n=(e.wouldBeRefused??[]).join(" "),r=Fe(n,e.wouldBeRefused,e.wouldBeRefusedCodes),s=r.length>0?{refusalCodes:r}:{};if(t===void 0)return{objects:[],total:0,created:0,storageBytes:0,emails:[],refusal:n!==""?n:"the clone never came to count what it would write, and a run held to no count is held to nothing",...s};let o=e.result.wouldInsertCount===t.totalRows,i=n!==""?n:t.totalRows===0?"it would write nothing: the clone reads no record to write; look at its record or the conditions of its tables":void 0;return{objects:t.objects.map(a=>({object:a.objectApiName,wouldCreate:a.rows,...o?{}:{atMost:!0}})),total:t.totalRows,created:e.result.wouldInsertCount,storageBytes:t.storageBytes,emails:t.emails??[],...i!==void 0?{refusal:i,...s}:{}}}function es(e){let n=((e.result.remapInJournal===!0?e.result.createdCountByObject:void 0)??e.result.createdByObject.map(r=>({objectApiName:r.objectApiName,created:r.sourceIds.length}))).map(r=>({object:r.objectApiName,created:r.created,refused:0,errors:[]}));for(let r of e.result.errors){if(r.failedCount===0)continue;let s=n.find(i=>i.object===r.objectApiName),o=`${r.failedCount} refused by the org`;s!==void 0?(s.refused+=r.failedCount,s.errors.push(o)):n.push({object:r.objectApiName,created:0,refused:r.failedCount,errors:[o]})}return{objects:n,created:e.result.successCount}}function hl(e){let{result:t}=e;if(t.verdict==="unstable")return`no two of ${t.attempts} readings agreed: something still writes to the run's records; verify again once it is done`;let n=t.objects.flatMap(r=>{if(r.error!==void 0)return[`${r.objectApiName} not read (${r.error})`];let s=r.deleted+r.notVisible;return[...s>0?[`${r.objectApiName} ${s} of ${r.expected} not there`]:[],...r.linksBroken>0?[`${r.objectApiName} ${r.linksBroken} lookup(s) that do not hold`]:[]]});return n.length>0?n.join("; "):void 0}function wi(e){return e instanceof Error?e.message:String(e)}import{readFileSync as gl}from"node:fs";import{join as yl}from"node:path";var ue="sandforge-frozen",ml=1e6,mv=["sasDir","datasetDir"],gv=["rootObject","excludedObjects","identityKeys","undeletableObjects","requiredLookupPlaceholders","requiredFieldDefaults","picklistRules","defaultPicklistRule","duplicateErrorPatterns"],wl=new Set(["NO_LOAD","ALREADY_REMOVED","NOTHING_TO_REMOVE"]);function vl(e,t,n){let r=["resources",e,"config"],s=f=>({refusals:[N(r,f)]}),o;try{o=gl(yl(n,t.config),"utf8")}catch(f){return s(`${t.config} cannot be read: ${f instanceof Error?f.message:String(f)}`)}if(o.length>ml)return s(`${t.config} is larger than ${ml} bytes`);let i;try{i=JSON.parse(o.replace(/^\uFEFF/,""))}catch{return s(`${t.config} is not JSON: a Frozen configuration is the panel's, as JSON`)}let a=Rr(i);if(a.length>0)return{refusals:a.map(({path:f,secret:h})=>N(r,`${t.config} holds a key shaped like a secret (${h}) at ${f.join(".")}: a load never reads the salt, and the configuration holds no secret. Take it out.`))};let c=jd.strict().safeParse(i);if(!c.success)return{refusals:c.error.issues.map(f=>N(r,`${t.config} is refused by Frozen's configuration schema at ${f.path.map(String).join(".")||"its top"}: ${f.message}`))};let d=[],u={...c.data},l=mv.filter(f=>u[f]!==void 0);for(let f of l)delete u[f];return l.length>0&&d.push(N(r,`${t.config} gives ${l.join(" and ")}, which the environment sets: the loads are kept beside the state, and the dataset is the one the file pins`)),{run:{configFile:t.config,config:u,dataset:{...t.dataset}},warnings:d}}function kl(e){return{kind:"frozen",kindVersion:1,dataset:{digest:e.dataset.digest,version:e.dataset.version},load:Object.fromEntries(gv.map(t=>[t,e.config[t]??null]))}}function bl(e,t){return{...e.config,sasDir:t.sasDir,datasetDir:t.datasetDir}}async function El(e,t){let n,r;try{n=await lu(e),r=JSON.parse(gl(yl(e,"manifest.json"),"utf8")).version}catch(s){return{refusal:`its dataset at ${e} cannot be read: ${s instanceof Error?s.message:String(s)}`}}return n!==t.digest?{refusal:`its dataset at ${e} has the digest ${n}, and the file pins ${t.digest}: it is not the dataset the file was reviewed with. Point the path at that one, or pin this digest once this dataset is reviewed`}:r!==t.version?{refusal:`its dataset at ${e} is version ${String(r)}, and the file pins version ${t.version}: pin the version its manifest says`}:{digest:n,version:t.version}}function An(e,t){return[e,"--config",C("--config",t.configFile),"--target",C("--target",t.target)]}function Rl(e){return[...An("load",e),...e.reload?["--reload"]:[],...e.reload&&e.goneFirst!==void 0?["--gone-first",C("--gone-first",e.goneFirst)]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],...e.store!==void 0?["--store",C("--store",e.store)]:[],"--dry-run","--json"]}function Sl(e){return[...An("load",e),...e.reload?["--reload"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],"--max-total",String(e.maxTotal),"--yes","--json"]}function $l(e){return[...An("verify",e),"--json"]}function Al(e){return[...An("remove",e),...e.includeChanged===!0?["--include-changed"]:[],...be(e),...e.acceptAutomation===!0?["--accept-automation"]:[],"--yes","--json"]}function Ol(e){return[...An("remove",e),...e.includeChanged===!0?["--include-changed"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],"--preview",...be(e),"--json"]}var yv=p.object({type:p.string().min(1),payload:p.record(p.string(),p.unknown()).optional()}).loose(),On={tool:p.literal(ue),posted:p.array(yv),dataset:p.object({dir:p.string().min(1),digest:p.string().min(1),version:p.string().optional()}).optional(),mapping:p.string().min(1).optional(),refusals:p.array(p.string()).optional(),refusalCodes:p.array(p.string()).optional(),ended:p.literal(!0).optional()},jl=p.object({status:p.enum(["PASSED","PARTIAL","FAILED","UNSTABLE"]),objects:p.array(p.object({objectApiName:p.string().min(1),verdict:p.enum(["PASSED","FAILED"]),expected:R,found:R,notLoaded:R,orphans:R,missingKeys:R}))}),wv=p.object({...On,step:p.literal("load"),objects:p.array(p.object({objectApiName:p.string().min(1),fromFiles:R,toInsert:R,toLink:R,notSent:R,toPurge:R,toDeactivate:R})).optional()}),vv=p.object({...On,step:p.literal("load"),objects:p.array(p.object({objectApiName:p.string().min(1),fromFiles:R,inserted:R,reused:R,duplicates:R,failed:R})).optional(),verdict:jl.optional()}),kv=p.object({...On,step:p.literal("verify"),verdict:jl.optional()});function jn(e,t){return e.filter(n=>n.type===t).at(-1)?.payload}function In(e){let t=e.find(s=>s.type.endsWith(":error"))?.payload;if(t===void 0)return;let n=typeof t.message=="string"?t.message:"refused",r=typeof t.code=="string"?t.code:void 0;return{message:n,...r!==void 0?{code:r}:{}}}var bv=p.object({...On,step:p.literal("remove")}).transform((e,t)=>{let n=In(e.posted.filter(h=>h.type!=="frozen:remove:automation:error")),r={planned:0,objects:[],userNames:{}};if(n!==void 0&&!wl.has(n.code??""))return{tool:e.tool,preview:r,refusals:[n.message],...n.code!==void 0?{refusalCodes:[n.code]}:{},removalAlone:[]};let s=jn(e.posted,"frozen:remove:preview:response")?.preview;if(s===void 0)return{tool:e.tool,preview:r,refusals:[],removalAlone:[]};let o=_t.extend({refusals:p.array(p.string()),refusalCodes:p.array(p.string()).optional()}).loose().safeParse(s);if(!o.success)return t.addIssue({code:"custom",message:`its preview: ${o.error.issues[0]?.message}`}),p.NEVER;let{refusals:i,refusalCodes:a,...c}=o.data,d=e.refusals??[],u=new Map(e.refusalCodes?.length===d.length?d.map((h,g)=>[h,e.refusalCodes?.[g]??""]):[]),l=d.filter(h=>!i.includes(h)),f=l.flatMap(h=>u.get(h)??[]);return{tool:e.tool,preview:c,refusals:i,...a?.length===i.length?{refusalCodes:a}:{},removalAlone:l,...f.length===l.length&&f.length>0?{removalAloneCodes:f}:{}}}),Ev=p.object({...On,step:p.literal("remove"),status:p.string().optional()}).transform((e,t)=>{let n=In(e.posted),r={tool:e.tool,result:{status:"success",planned:0,objects:[]}};if(n!==void 0)return wl.has(n.code??"")?r:(t.addIssue({code:"custom",message:`the removal was refused: ${n.message}`}),p.NEVER);let s=jn(e.posted,"frozen:remove:response")?.result;if(s===void 0)return r;let o=p.object({status:p.enum(["success","partial","failure","cancelled"]),objects:p.array(Ze.loose())}).loose().safeParse(s);return o.success?{tool:e.tool,result:{status:o.data.status,planned:o.data.objects.reduce((i,a)=>i+a.planned,0),objects:o.data.objects}}:(t.addIssue({code:"custom",message:`its result: ${o.error.issues[0]?.message}`}),p.NEVER)});function Il(e){return z(ue,"the answer of a dry run",wv,e)}function ts(e){return z(ue,"the answer of a load",vv,e)}function Cl(e){return z(ue,"a verification",kv,e)}function Dl(e){return z(ue,"the preview of a removal",bv,e)}function Pl(e){return z(ue,"the outcome of a removal",Ev,e)}function Rv(e){let n=(Array.isArray(e?.removals)?e.removals:[]).flatMap(r=>{let s=r;return s.reason==="may-hold-masks"?[`${String(s.objectApiName)}.${String(s.field)} (${Number(s.affectedRecords??0)})`]:[]});return n.length>0?[`it would leave out, encrypted in the target, ${n.join(", ")}: the dataset's manifest does not say its extraction left out what it read masked, so they may hold masks such as ****1234`]:[]}function Sv(e){return(Array.isArray(e?.perObject)?e.perObject:[]).flatMap(n=>{let r=n,s=Number(r.picklistsRewritten??0),o=Number(r.fieldsDropped??0),i=[s>0?`${s} picklist value(s) a restricted picklist of the target refuses, rewritten by their rule`:"",o>0?`${o} field(s) the target lacks or takes no value of, dropped`:""].filter(Boolean);return i.length>0?[`${String(r.objectApiName)}: ${i.join(", ")}`]:[]})}function $v(e){let t=e?.emails?.counted;return Array.isArray(t)?t.flatMap(n=>{let{limit:r,emails:s}=n??{};return(r==="SingleEmail"||r==="DailyWorkflowEmails")&&typeof s=="number"?[{limit:r,emails:s}]:[]}):[]}function Nl(e){let t=In(e.posted),n=[...t!==void 0?[t.message]:[],...e.refusals??[]],r=e.objects??[],s=r.reduce((u,l)=>u+l.toInsert,0),o=jn(e.posted,"frozen:load:preview:response")?.plan,i=n.length>0?n.join(" "):e.objects===void 0?"the load never came to say what it would write, and a run held to no count is held to nothing":s===0?"it would insert nothing: every record of the dataset is one the org holds already, linked by its identity keys, or one the load does not send":void 0,a=[...Rv(o),...Sv(o)],c=e.refusals??[],d=i!==void 0?Fe(i,n,[...t!==void 0?[t.code??""]:[],...e.refusalCodes?.length===c.length?e.refusalCodes:c.map(()=>"")]):[];return{objects:r.map(u=>({object:u.objectApiName,wouldCreate:u.toInsert})),total:s,created:s,storageBytes:r.reduce((u,l)=>u+Ar(l.objectApiName,{rows:l.toInsert}),0),emails:$v(o),...i!==void 0?{refusal:i}:{},...d.length>0?{refusalCodes:d}:{},...a.length>0?{notes:a}:{}}}function Cn(e){let t=In(e.posted),n=(e.objects??[]).map(r=>({object:r.objectApiName,created:r.inserted,refused:r.failed,errors:r.failed>0?[`${r.failed} refused by the org`]:[]}));return n.length===0&&t!==void 0?{objects:[],created:0,refusal:t.message}:{objects:n,created:n.reduce((r,s)=>r+s.created,0)}}function ns(e){let n=jn(e.posted,"frozen:load:response")?.report?.purge;if(n===void 0)return!1;let r=Object.values(n.leftUnrecorded??{}).reduce((s,o)=>s+o,0);return(n.failures??[]).length===0&&r===0}function Tl(e){let t=jn(e.posted,"frozen:load:response")?.report;return[...Object.values(t?.purge?.deleted??{}),...Object.values(t?.purge?.deactivated??{})].some(r=>r>0)}function vi(e){if(e.status==="UNSTABLE")return{unstable:!0,short:"no two readings of the org agreed: something still writes to the load\u2019s records; verify again once it is done"};let t=e.objects.filter(n=>n.verdict==="FAILED").map(n=>{let r=[`${n.found} of ${n.expected} found`,n.orphans>0?`${n.orphans} orphan(s)`:"",n.missingKeys>0?`${n.missingKeys} key(s) missing`:"",n.notLoaded>0?`${n.notLoaded} not loaded`:""].filter(Boolean);return`${n.objectApiName} FAILED (${r.join(", ")})`});return t.length>0?{unstable:!1,short:t.join("; ")}:e.status!=="PASSED"?{unstable:!1,short:`its verdict is ${e.status}`}:{unstable:!1}}function xl(e){let t=In(e.posted);if(e.verdict===void 0)return{unread:t?.message??"the verification gave no verdict"};let{short:n,unstable:r}=vi(e.verdict);return r?{unread:n??"no two readings agreed"}:{failed:n!==void 0?[n]:[]}}function rt(e){return`frozen/${e}`}function rs(e){return e!==void 0&&/^frozen\/[a-z][a-z0-9-]{0,62}$/.test(e)?e.slice(7):void 0}import{existsSync as ki}from"node:fs";import{rm as Av}from"node:fs/promises";import{join as Ll}from"node:path";var me="sandforge-dataops",Fl="snapshots.json";function Ml(e){let t={},n=[];for(let[r,s]of Object.entries(e)){let o=Od.safeParse({name:r,rules:s.rules});if(!o.success){n.push(...o.error.issues.map(i=>N(["masking",r,...i.path],`refused by the rules the DataOps panel saves: ${i.message}`)));continue}t[r]={name:r,rules:s.rules}}return n.length>0?{refusals:n}:{sets:t}}function Ov(e){let t=Wo.find(r=>r.id===e);if(t===void 0)return;let n=t.rules.flatMap(r=>{if(!cd(r.ruleType))return[];let s="config"in r?r.config:void 0;return[{fieldPattern:r.fieldPattern,ruleType:r.ruleType,...s!==void 0?{config:{...s}}:{}}]});return{name:t.name,rules:n}}function zl(e,t,n){let r=["resources",e,"rules"],s,o;if(typeof t.rules=="string"){if(s=n[t.rules],o={set:t.rules},s===void 0)return{refusals:[N(r,`the rule set ${t.rules} is refused: see masking`)]}}else{let l=t.rules.template;if(s=Ov(l),o={template:l},s===void 0)return{refusals:[N([...r,"template"],`there is no DataOps template "${l}" that ships: there is `+Wo.map(f=>f.id).join(", "))]}}let i=t.object;if(i!==void 0&&!fu({id:s.name,name:s.name,rules:s.rules},i))return{refusals:[N(["resources",e,"object"],`${"set"in o?`the rule set ${o.set}`:`the template ${o.template}`} has no rule for ${i}: a run would mask nothing. Name an object its rules mask, or give it a rule for this one`)]};let a=[],c=`${(i??"").toLowerCase()}.`,d=new Map(s.rules.filter(l=>i!==void 0&&l.fieldPattern.toLowerCase().startsWith(c)).map(l=>[(l.fieldPattern.split(".")[1]??"").toLowerCase(),l.ruleType])),u=jv(t.where).filter(({field:l,empty:f})=>{let h=d.get(l.toLowerCase());return h!==void 0&&(!f||h==="nullify")}).map(({field:l})=>l);return u.length>0&&a.push(N(["resources",e,"where"],`its condition reads ${u.join(", ")}, which its rules write over: once masked, its records may no longer be those it selects, and a plan after reads them as gone. Select them by a field its rules leave as it is`)),{run:{source:o,rules:s,...i!==void 0?{object:i}:{},...t.where!==void 0?{where:t.where}:{},...t.accept?.automation===!0?{acceptAutomation:!0}:{},...t.slices===!0?{slices:!0}:{},...t.maxRecords!==void 0?{maxRecords:t.maxRecords}:{},...t.maxRequests!==void 0?{maxRequests:t.maxRequests}:{}},warnings:a}}function jv(e){if(e===void 0)return[];let t=e.replace(/'(?:[^'\\]|\\.)*'/g,"''"),n=new Map;for(let r of t.matchAll(/\b([A-Za-z][A-Za-z0-9_]*)\s*(=|!=|<>|<=|>=|<|>|\s(?:NOT\s+)?(?:LIKE|IN|INCLUDES|EXCLUDES)\b)\s*(null\b)?/gi)){let s=r[1]??"";if(/^(?:AND|OR|NOT)$/i.test(s))continue;let o=/^(?:=|!=|<>)$/.test(r[2]??"")&&r[3]!==void 0;n.set(s,(n.get(s)??!0)&&o)}return[...n].map(([r,s])=>({field:r,empty:s}))}function _l(e){return{kind:"mask",kindVersion:1,rules:[...e.rules.rules].map(t=>({...t,fieldPattern:t.fieldPattern.toLowerCase()})).sort((t,n)=>zt(t).localeCompare(zt(n))),object:e.object??null,where:e.where??null}}function ql(e){if(e.object!==void 0)return[{object:e.object}];let t=[];for(let n of e.rules.rules){let r=n.fieldPattern.split(".")[0]??"";t.includes(r)||t.push(r)}return t.map(n=>({object:n}))}function Bl(e){return{name:e.rules.name,rules:e.rules.rules}}function Kt(e){return`dataops/${e}`}function Ul(e){let{run:t}=e;return["anonymize","--org",C("--org",e.target),...t.object!==void 0?["--object",C("--object",t.object)]:[],...t.where!==void 0?["--where",C("--where",t.where)]:[],..."template"in t.source?["--template",C("--template",t.source.template)]:["--rules",C("--rules",e.rulesFile)],"--store",C("--store",e.store),...t.acceptAutomation===!0?["--accept-automation"]:[],...t.slices===!0?["--slices"]:[],...t.maxRecords!==void 0?["--max-records",String(t.maxRecords)]:[],...t.maxRequests!==void 0?["--max-requests",String(t.maxRequests)]:[]]}function Kl(e){return[...Ul(e),"--dry-run","--json"]}function Wl(e){return[...Ul(e),"--yes","--json"]}var Iv=p.object({type:p.string().min(1),payload:p.record(p.string(),p.unknown()).optional()}).loose(),st=p.number().int().nonnegative(),Vl={tool:p.literal(me),org:p.string().min(1),posted:p.array(Iv)},Cv=p.object({...Vl,command:p.literal("dry-run"),slices:p.literal(!0).optional()}),Dv=p.object({...Vl,command:p.literal("run")});function Hl(e){return z(me,"the answer of a dry run",Cv,e)}function ss(e){return z(me,"the answer of a masking",Dv,e)}function Ut(e,t){return e.filter(n=>n.type===t).at(-1)?.payload}function Jl(e){let t=Ut(e,"dataops:error");if(t!==void 0)return typeof t.message=="string"?t.message:"refused"}var Pv=p.object({objects:p.array(p.object({objectApiName:p.string().min(1),count:st.nullable(),slicePlan:p.object({size:p.number().int().positive(),slices:p.number().int().positive()}).loose().optional()}).loose()),sliceSet:p.object({setId:p.string().min(1),done:st,total:st,savedAt:p.string(),state:p.string()}).loose().optional()}),Nv=p.object({objects:p.array(p.object({objectApiName:p.string().min(1),fields:p.array(p.string()),error:p.string().optional(),notCovered:p.literal(!0).optional(),writeDenied:p.object({deniedFields:p.array(p.string())}).optional()}).loose()),fieldsNotFound:p.array(p.object({objectApiName:p.string(),fieldApiName:p.string()}))}),Tv=p.object({emails:p.array(p.object({limit:p.enum(["SingleEmail","DailyWorkflowEmails"]),emails:st}).loose()),refusals:p.array(p.object({code:p.string(),message:p.string()}).loose())}).loose();function Yl(e){let t=[],n=Jl(e.posted);n!==void 0&&t.push(n);let r=Pv.safeParse(Ut(e.posted,"dataops:anonymize:coverage:response")),s=Nv.safeParse(Ut(e.posted,"dataops:anonymize:preview:response"));if(!r.success||!s.success)return n===void 0&&t.push("the masking never came to say what it would mask, and a run nobody counted is masked blind"),{objects:[],refusals:t,refusalCodes:t.map(()=>""),emails:[]};let o=Tv.safeParse(Ut(e.posted,"dataops:automation:response")),i=r.data.objects.map(u=>({object:u.objectApiName,count:u.count}));for(let u of r.data.objects){let l=u.slicePlan;u.count===null&&!(e.slices===!0&&l!==void 0)&&t.push(`${u.objectApiName}: the org did not count the records it would mask`),e.slices!==!0&&l!==void 0&&(u.count??0)>l.size&&t.push(`${u.objectApiName} holds ${u.count??0} record(s), more than the ${l.size} a snapshot holds of one object: a run is refused and masks nothing (slices: true masks it in ${l.slices} slices, each backed up just before it is masked, or maxRecords takes up to ${od})`)}let a=r.data.sliceSet;a!==void 0&&a.state==="open"&&t.push(`a masking in slices of its rules stopped part way and is still open in its store (set ${a.setId}, ${a.done} of ${a.total} slice(s) masked, last moved ${a.savedAt}): a run is refused until it is resumed or given up, with ${B("dataops")} anonymize and the resource's store, --resume or --abandon`);for(let u of s.data.objects){u.error!==void 0?t.push(`${u.objectApiName}: not read: ${u.error}`):u.notCovered===!0&&t.push(`${u.objectApiName}: its rules mask no field the org shows this user: a run would mask nothing there`);let l=u.writeDenied?.deniedFields;l?.length===0&&t.push(Yo(u.objectApiName));for(let f of l??[])t.push(Yo(u.objectApiName,f))}for(let u of s.data.fieldsNotFound)t.push(Jo(u.objectApiName,u.fieldApiName));let c=new Map;for(let u of o.success?o.data.refusals:[])t.push(u.message),c.set(u.message,u.code);let d=o.success?o.data.emails.map(({limit:u,emails:l})=>({limit:u,emails:l})):[];return{objects:i,refusals:t,refusalCodes:t.map(u=>c.get(u)??""),emails:d}}function Gl(e){let t=Yl(e),n=t.objects.map(o=>({object:o.object,wouldCreate:o.count??0})),r=t.refusals.length>0?t.refusals.join(" "):void 0,s=r!==void 0?Fe(r,t.refusals,t.refusalCodes):[];return{objects:n,total:n.reduce((o,i)=>o+i.wouldCreate,0),created:0,storageBytes:0,emails:t.emails,...r!==void 0?{refusal:r}:{},...s.length>0?{refusalCodes:s}:{}}}var xv=p.object({status:p.string().optional(),objects:p.array(p.object({objectApiName:p.string().min(1),total:st,processed:st,failed:st,notMasked:st}).loose()).optional(),fieldsNotFound:p.array(p.object({objectApiName:p.string(),fieldApiName:p.string()})).optional(),snapshot:p.object({operationId:p.string().min(1).max(200)}).loose().optional(),slices:p.object({setId:p.string().min(1).max(200)}).loose().optional(),message:p.string().optional(),errors:p.array(p.object({objectApiName:p.string(),message:p.string()})).optional()}).loose();function Dn(e){let t=xv.safeParse(Ut(e.posted,"dataops:anonymize:response")??Ut(e.posted,"dataops:error")??{}),n=t.success?t.data:{},r=(n.objects??[]).map(a=>({object:a.objectApiName,masked:a.processed,refused:a.failed,notMasked:a.notMasked})),s=Jl(e.posted),o=(n.fieldsNotFound??[]).map(a=>Jo(a.objectApiName,a.fieldApiName)),i=n.snapshot?.operationId??n.slices?.setId;return{objects:r,...i!==void 0?{snapshotId:i}:{},...s!==void 0?{refusal:s}:{},...o.length>0?{short:o.join("; ")}:{}}}function Ql(e,t,n,r){let s=new Map,o=t?.resources[e]?.runs.at(-1)?.startedAt,i=n.indexOf(e);if(t!==void 0&&o!==void 0&&i>=0)for(let a of n.slice(i+1)){let c=t.resources[a];if(c===void 0||c.status==="destroyed")continue;let d=c.runs.filter(u=>u.takenBack!==!0);for(let u of c.kind==="frozen"?d.slice(-1):d)if(!(Date.parse(u.startedAt)<Date.parse(o)))for(let l of u.objects)l.created<=0||s.set(l.objectApiName,(s.get(l.objectApiName)??0)+l.created)}return r===void 0?{theirs:s,unsure:new Map}:{theirs:new Map,unsure:s}}function Xl(e,t,n={theirs:new Map,unsure:new Map}){let r=Yl(t),s=e.runs.at(-1),o=new Map((s?.objects??[]).map(d=>[d.objectApiName,d.masked??0]));if(r.refusals.length>0)return{objects:[],masked:0,unread:r.refusals.join(" ")};let i=[],a=[],c=0;for(let{object:d,count:u}of r.objects){let l=u??0,f=o.get(d)??0,h=Math.min(Math.max(0,l-f),n.theirs.get(d)??0);if(c+=h,a.push({object:d,present:Math.min(l,f),...l<f?{gone:f-l}:{}}),l-h>f){let g=h>0?`, ${h} created since by the resources applied after it`:"",m=n.unsure.get(d)??0,w=m>0?`, unless they are among the ${m} the resources applied after it created since, which a count under its condition does not tell apart`:"";i.push(`${d} ${l} under its condition, ${f} masked${g}: ${l-h-f} more, which hold their original values${w}`)}else l<f&&i.push(`${d} ${l} under its condition, ${f} masked: ${f-l} gone`)}return{objects:a,masked:[...o.values()].reduce((d,u)=>d+u,0),...c>0?{theirs:c}:{},...i.length>0?{drift:i.join("; ")}:{}}}function bi(e,t){return`${B("dataops")} anonymize --org ${e.alias} --restore ${t} --store ${e.store??"<its store>"}`}function Zl(e,t){return t.store??`${Kt(e)} beside the state`}function ef(e,t){return[`masking is one-way: each run first takes a snapshot of the values it writes over, kept on this machine in ${Zl(e,t)}, and destroy never puts them back: it deletes the snapshots. Putting them back is your own act, before a destroy: `+bi(t,"<the snapshot its run names>")]}function tf(e){return e.runs.find(t=>t.takenBack!==!0)}function Lv(e){let t=tf(e);return t?.snapshotId!==void 0?`snapshot ${t.snapshotId}, run ${t.n}'s`:t!==void 0?`the snapshot run ${t.n} took`:"the snapshot its first run took"}function Ei(e){return`it masks again what its condition selects, the records it masked before a second time, and takes nothing back first: the values they held before any masking stay only in ${Lv(e)}, which destroy deletes`}var nf={applying:"its last masking was stopped part way",partial:"its last masking left values as they were: records the org refused, or fields it does not show this user",failed:"its last masking failed",destroying:"a deletion of its snapshots was stopped part way"};function rf(e,t=0){return`applied, and its condition selects the ${e} record(s) it masked, with the same rules${t>0?`, beside ${t} the resources applied after it created since`:""}: masked again they would only be masked twice`}function sf(e,t){return`its condition selects other records than it masked: ${t}. Left as they are: --replace ${e} or --replace-drifted masks them all again`}function Ri(e,t,n,r){let s=tf(n)?.snapshotId;return`${e==="destroy"?"taken back by destroy, which never unmasks":"in the state, gone from the file"}: its records stay masked, and its store, ${Zl(t,r)}, is deleted from this machine with its snapshots, the only copy of the values they held. `+(s!==void 0?`To put back those they held before any masking, before this ${e}, as your own act: ${bi(r,s)}`:`Its snapshots are listed in its store: ${bi(r,"<snapshot>")} puts one back, before this ${e}, as your own act`)}async function of(e){if(!ki(e))return{snapshots:[]};let t=ki(Ll(e,Fl))?Wd(Ll(e,Fl)).getKeysByPrefix("backup:").map(n=>n.slice(7)).filter(n=>!n.includes(":")):[];if(await Av(e,{recursive:!0,force:!0}),ki(e))throw new Error(`${e} is still there: delete it, it holds the values a masking wrote over`);return{snapshots:[...new Set(t)].sort()}}function af(e,t){let n=t.snapshots.length>0?`its snapshot${t.snapshots.length===1?"":"s"} ${t.snapshots.join(", ")}`:"no snapshot";return`${e}: its records stay masked \u2014 destroy never unmasks \u2014, and ${n}, the only copy of the values they held, deleted from this machine with its store`}import{existsSync as Fv,readFileSync as Mv}from"node:fs";import{isAbsolute as zv}from"node:path";var V="sandforge-checkpoint",Si="REPLAY_CHECKPOINT_NOT_FOUND",lf=new Set(["NO_LOAD","ALREADY_REMOVED","NOTHING_TO_REMOVE"]);function ff(e){return{owners:e.owners??"same",customSettings:e.customSettings===!0,mask:e.mask===!0,contactPoints:e.keepContactPoints===!0?"kept":"neutralized",objects:e.objects??[],excluded:e.excludeObjects??[],link:[]}}var _v={owners:"owners",customSettings:"customSettings",mask:"mask",contactPoints:"keepContactPoints",objects:"objects",excluded:"excludeObjects"};function pf(e,t){let n={checkpoint:t.checkpoint,...t.from!==void 0?{from:t.from}:{},...t.objects!==void 0?{objects:t.objects}:{},...t.excludeObjects!==void 0?{excludeObjects:t.excludeObjects}:{},...t.owners!==void 0?{owners:t.owners}:{},...t.customSettings!==void 0?{customSettings:t.customSettings}:{},...t.mask!==void 0?{mask:t.mask}:{},...t.keepContactPoints!==void 0?{keepContactPoints:t.keepContactPoints}:{},...t.maxRecords!==void 0?{maxRecords:t.maxRecords}:{},...t.accept?.automation===!0?{acceptAutomation:!0}:{}},r=ad.safeParse(ff(n));return r.success?{run:n,warnings:[]}:{refusals:r.error.issues.map(s=>{let[o,...i]=s.path,a=_v[String(o)]??String(o);return N(["resources",e,a,...i],`refused by the choices a replay takes: ${s.message}`)})}}function cf(e){return e===void 0||e.length===0?null:[...new Set(e.map(t=>t.toLowerCase()))].sort()}function hf(e){return(e.objects??[]).map(t=>({object:t}))}function mf(e,t,n){if(typeof t=="string")return{file:t};let r=["resources",e,"checkpoint","file"],s=(n[t.env]??"").trim();return s===""?{refusal:N(r,`the variable ${t.env} is not set: set it in the job's environment to the path of the checkpoint file ${e} replays`)}:zv(s)?{file:s}:{refusal:N(r,`the variable ${t.env} holds ${s}, which is not a path from the root: give the checkpoint file from the root`)}}function qv(e){return e.checkpoint!==void 0&&(e.valid||e.why==="refreshed"||e.why==="scratchExpired")}function df(e,t){return e.slice(0,15)===t.slice(0,15)}function Bv(e){return[...e].sort((t,n)=>(n.checkpoint?.takenAt??"").localeCompare(t.checkpoint?.takenAt??""))[0]}function uf(e){return{checkpointId:e.checkpointId,organizationId:e.organizationId,...e.checkpoint!==void 0?{name:e.checkpoint.name,takenAt:e.checkpoint.takenAt}:{}}}function Uv(e,t){return`take one before the next refresh: ${B("checkpoint")} take --org ${t} --name ${e}; or name an exported file: checkpoint: { file: \u2026, keyEnv: \u2026 }`}function Kv(e,t,n,r){let{checkpoint:s}=e,o=n.filter(qv);if(s.id!==void 0){let u=o.filter(h=>h.checkpointId===s.id),l=[...new Set(u.map(h=>h.organizationId.slice(0,15)))],f=u[0];return f!==void 0&&l.length===1?uf(f):l.length>1?{code:"AMBIGUOUS",refusal:`checkpoints of ${l.length} orgs have the id ${s.id} on this machine: name it by name with from, the org role it was taken of`}:{code:Si,refusal:`no checkpoint ${s.id} is kept on this machine: "${B("checkpoint")} list" names those it keeps`}}let i=s.name??"",a,c;if(t.from!==void 0){let u=t.from,l=o.filter(f=>{let h=f.checkpoint?.org;return h!==void 0&&(h.alias===u||h.username.toLowerCase()===u.toLowerCase())}).map(f=>f.organizationId);a=o.filter(f=>l.some(h=>df(h,f.organizationId))),c=`of ${u}`}else{let u={name:r.alias,organizationId:r.organizationId,...r.username!==void 0?{username:r.username}:{},...r.instanceUrl!==void 0?{instanceUrl:r.instanceUrl}:{}};a=o.filter(l=>l.checkpoint!==void 0&&!df(l.organizationId,r.organizationId)&&Pr(l.checkpoint.org,u)!==void 0),c=`of ${r.alias} before its refresh`}let d=Bv(a.filter(u=>u.checkpoint?.name===i));return d!==void 0?uf(d):{code:Si,refusal:`no checkpoint ${c} named '${i}' is kept on this machine: `+Uv(i,t.from??r.alias)}}async function gf(e,t,n,r){if(e.checkpoint.file!==void 0){if(t.file===void 0)return{code:Si,refusal:"its checkpoint file was not resolved"};let o=await(r.readHeader??au)(t.file);if("refusal"in o)return{code:o.refusal.code,refusal:o.refusal.message};let{header:i}=o.read;return{checkpointId:i.checkpointId,organizationId:i.organizationId,takenAt:i.takenAt}}let s=[];for(let o of[r.storeRoot,cu(r.storeRoot)]){if(!Fv(o))continue;let i=Fd({root:o,...r.locksDir!==void 0?{locksDir:r.locksDir}:{}});if("refusal"in i)return{code:"STORE_REFUSED",refusal:`the checkpoints kept in ${o} cannot be read: `+Ld(i.refusal,o,"SANDFORGE_JOURNAL_DIR")};s.push(...await i.store.list())}return Kv(e,t,s,n)}function yf(e,t){let n=t!==void 0&&"checkpointId"in t?t:void 0,r=ff(e);return{kind:"replay",kindVersion:1,checkpoint:n!==void 0?{id:n.checkpointId,organizationId:n.organizationId.slice(0,15)}:{unread:e.checkpoint.id??(e.checkpoint.name!==void 0?{name:e.checkpoint.name,from:e.from??null}:"file")},owners:r.owners,customSettings:r.customSettings,mask:r.mask,contactPoints:r.contactPoints,objects:cf(e.objects),excludeObjects:cf(e.excludeObjects)}}function Wv(e){let{run:t,place:n}=e;if(t.checkpoint.file!==void 0){if(n.file===void 0||t.checkpoint.keyEnv===void 0)throw new Error(`${e.name} names a checkpoint file that was not resolved: plan again.`);return["--file",C("--file",n.file),"--key-env",C("--key-env",t.checkpoint.keyEnv)]}let r=n.read;if(r!==void 0&&"checkpointId"in r)return["--checkpoint",C("--checkpoint",r.checkpointId),"--from",C("--from",r.organizationId)];if(t.checkpoint.id!==void 0)return["--checkpoint",C("--checkpoint",t.checkpoint.id)];throw new Error(`${e.name} names its checkpoint by a name this plan has not resolved: plan again.`)}function Vv(e){return[...e.objects!==void 0&&e.objects.length>0?["--objects",C("--objects",e.objects.join(","))]:[],...(e.excludeObjects??[]).flatMap(t=>["--exclude-object",C("--exclude-object",t)]),...e.owners!==void 0?["--owners",e.owners]:[],...e.customSettings===!0?["--custom-settings"]:[],...e.mask===!0?["--mask"]:[],...e.keepContactPoints===!0?["--keep-contact-points"]:[]]}function wf(e){return["replay",...Wv(e),"--target",C("--target",e.target),"--store",C("--store",e.store),...Vv(e.run),...e.again?["--again"]:[],...e.acceptAutomation===!0||e.run.acceptAutomation===!0?["--accept-automation"]:[]]}function vf(e){return[...wf(e),...e.run.maxRecords!==void 0?["--max-records",String(e.run.maxRecords)]:[],"--dry-run","--json"]}function kf(e){if(!Number.isInteger(e.maxRecords)||e.maxRecords<1)throw new Error(`${e.name} has no count from its dry run to be held to: plan again.`);return[...wf(e),"--max-records",String(e.maxRecords),"--yes","--json"]}function bf(e){return["replay","--checkpoint",C("--checkpoint",e.replayed.checkpointId),"--from",C("--from",e.replayed.organizationId),"--target",C("--target",e.target),"--store",C("--store",e.store),"--remove",...e.includeChanged===!0?["--include-changed"]:[]]}function Ef(e){return[...bf(e),...be(e),...e.acceptAutomation===!0?["--accept-automation"]:[],"--yes","--json"]}function Rf(e){return[...bf(e),"--preview",...be(e),...e.acceptAutomation===!0?["--accept-automation"]:[],"--json"]}var Hv=p.object({command:p.literal("replay"),checkpoint:p.object({id:p.string().min(1),organizationId:p.string().min(1)}).loose()}).loose();function Sf(e){let t;try{let n=Hv.safeParse(JSON.parse(Mv(e,"utf8")));t=n.success?n.data:void 0}catch{t=void 0}if(t===void 0)throw new Error(`${e} names no checkpoint a replay wrote from: the replay it is the summary of cannot be taken back from it.`);return{checkpointId:t.checkpoint.id,organizationId:t.checkpoint.organizationId}}var Jv=p.object({code:p.string().min(1),message:p.string().min(1)}).loose(),$i={command:p.literal("replay"),checkpoint:p.object({id:p.string().min(1),name:p.string().optional(),organizationId:p.string().min(1),takenAt:p.string().optional()}).loose(),target:p.object({alias:p.string().min(1),organizationId:p.string().optional()}).loose(),refusals:p.array(p.string()).optional(),refusalCodes:p.array(p.string()).optional(),refused:Jv.optional(),ended:p.literal(!0).optional(),exit:p.number().int()},$f=p.object({records:p.object({toCreate:R}).loose(),owners:p.object({kept:R,toRunningUser:R}).loose().optional(),filesLeft:p.array(p.object({objectApiName:p.string()}).loose()),refused:p.array(p.object({object:p.string().min(1),records:R,reason:p.string().min(1),path:p.string().optional()}).loose()).optional(),requests:R}).loose(),Yv=p.object({apiRequests:p.object({estimate:R}).loose()}).loose(),Gv=p.object({...$i,action:p.literal("dryRun"),objects:p.array(p.object({objectApiName:p.string().min(1),fromFiles:R,toInsert:R,toLink:R,notSent:R,toPurge:R}).loose()).optional(),plan:p.record(p.string(),p.unknown()).optional(),replay:$f.optional()}),Qv=p.object({...$i,action:p.literal("replay"),status:p.string().optional(),objects:p.array(p.object({objectApiName:p.string().min(1),fromFiles:R,inserted:R,failed:R}).loose()).optional(),result:p.record(p.string(),p.unknown()).optional(),replay:$f.optional()}),Af=p.object({...$i,action:p.literal("remove"),preview:p.literal(!0).optional(),objects:p.array(p.record(p.string(),p.unknown())).optional(),removal:p.record(p.string(),p.unknown()).optional()}),Xv=p.object({objectApiName:p.string().min(1),planned:R,toDelete:R,alreadyGone:R,changedSince:R,keptChanged:R,undeletable:R,notVisible:R,unread:R}).loose(),Zv=Af.transform((e,t)=>{let n={planned:0,objects:[],userNames:{}},r=e.refused;if(r!==void 0&&lf.has(r.code))return{tool:V,preview:n,refusals:[],removalAlone:[]};let s=[...r!==void 0?[r.message]:[],...e.refusals??[]],o=e.refusalCodes??[],i=[...r!==void 0?[r.code]:[],...o.length===(e.refusals??[]).length?o:[]],a=p.array(Xv).safeParse(e.objects??[]);if(!a.success)return t.addIssue({code:"custom",message:`its preview: ${a.error.issues[0]?.message}`}),p.NEVER;let c=a.data.map(d=>({objectApiName:d.objectApiName,planned:d.planned,toDelete:d.toDelete,alreadyGone:d.alreadyGone,changedSince:d.changedSince,keptChanged:d.keptChanged,changedBy:{},undeletable:d.undeletable,notVisible:d.notVisible,unread:d.unread,reasons:[]}));return{tool:V,preview:{planned:c.reduce((d,u)=>d+u.planned,0),objects:c,userNames:{}},refusals:s,...i.length===s.length&&i.length>0?{refusalCodes:i}:{},removalAlone:[]}}),ek=Af.transform((e,t)=>{let n={tool:V,result:{status:"success",planned:0,objects:[]}},r=e.refused;if(e.removal===void 0)return r===void 0||lf.has(r.code)?n:(t.addIssue({code:"custom",message:`the removal was refused: ${r.message}`}),p.NEVER);let s=p.object({status:p.enum(["success","partial","failure","cancelled"]),objects:p.array(Ze.loose())}).loose().safeParse(e.removal);return s.success?{tool:V,result:{status:s.data.status,planned:s.data.objects.reduce((o,i)=>o+i.planned,0),objects:s.data.objects}}:(t.addIssue({code:"custom",message:`its result: ${s.error.issues[0]?.message}`}),p.NEVER)});function Of(e){let t=z(V,"the answer of a replay\u2019s dry run",Gv,e);return{tool:V,...t}}function os(e){return z(V,"the answer of a replay",Qv,e)}function jf(e){return z(V,"the preview of a removal",Zv,e)}function If(e){return z(V,"the outcome of a removal",ek,e)}function tk(e){let t=e?.emails?.counted;return Array.isArray(t)?t.flatMap(n=>{let{limit:r,emails:s}=n??{};return(r==="SingleEmail"||r==="DailyWorkflowEmails")&&typeof s=="number"?[{limit:r,emails:s}]:[]}):[]}function Cf(e){let t=[...e.refused!==void 0?[e.refused.message]:[],...e.refusals??[]],n=e.objects??[],r=n.reduce((u,l)=>u+l.toInsert,0),s=t.length>0?t.join(" "):e.objects===void 0?"the replay never came to say what it would create, and a run held to no count is held to nothing":r===0?"it would create nothing: every record of the checkpoint is one the org holds already, linked, or one the replay leaves out":void 0,o=e.refusals??[],i=s!==void 0?Fe(s,t,[...e.refused!==void 0?[e.refused.code]:[],...e.refusalCodes?.length===o.length?e.refusalCodes:o.map(()=>"")]):[],a=e.replay,c=[...a!==void 0&&a.filesLeft.length>0?[`${a.filesLeft.length} file(s) of the checkpoint are not replayed: a checkpoint keeps no file\u2019s content`]:[],...a?.owners!==void 0&&a.owners.toRunningUser>0?[`${a.owners.toRunningUser} record(s) go to the user connected: their owner is not an active user of the org`]:[],...Df(a).map(u=>`${u.object}: ${u.records} record(s) refused before anything is written, which leave a run partial \u2014 ${Ho(u)}`)],d=Yv.safeParse(e.plan);return{objects:n.map(u=>({object:u.objectApiName,wouldCreate:u.toInsert})),total:r,created:r,...d.success?{apiRequests:d.data.apiRequests.estimate}:{},storageBytes:n.reduce((u,l)=>u+Ar(l.objectApiName,{rows:l.toInsert}),0),emails:tk(e.plan),...s!==void 0?{refusal:s}:{},...i.length>0?{refusalCodes:i}:{},...c.length>0?{notes:c}:{}}}function Df(e){return(e?.refused??[]).filter(t=>t.records>0)}function is(e){let t=(e.objects??[]).map(n=>({object:n.objectApiName,created:n.inserted,refused:n.failed,errors:n.failed>0?[`${n.failed} refused by the org`]:[]}));if(t.length===0&&e.refused!==void 0)return{objects:[],created:0,refusal:e.refused.message};for(let n of Df(e.replay)){let r=`${n.records} refused before anything is written \u2014 ${Ho(n)}`,s=t.find(o=>o.object===n.object);s!==void 0?(s.refused+=n.records,s.errors.push(r)):t.push({object:n.object,created:0,refused:n.records,errors:[r]})}return{objects:t,created:t.reduce((n,r)=>n+r.created,0)}}function as(e){let t=e.result?.purge;if(t===void 0)return!1;let n=Object.values(t.leftUnrecorded??{}).reduce((r,s)=>r+s,0);return(t.failures??[]).length===0&&n===0}var se="sandforge-seed",nk="In the file: fit: share seeds the largest share of each count that fits, fit: { withinMB: <MB> } no more than that; or lower each object\u2019s count.";function Tf(e,t,n,r){let s=rk(e,t,n,r);if("refusal"in s)return{refusals:[s.refusal]};let o=ok(t,n,s.run);return o.refusals.length>0?{refusals:o.refusals}:{run:s.run,warnings:o.warnings}}function rk(e,t,n,r){let s=r.toISOString(),o={id:`env-${e}-${t}`,name:`${e}/${t}`,description:`The ${t} resource of the ${e} environment`,version:1,tags:["sandforge-env"],createdAt:s,updatedAt:s},i,a=[];if(n.template!==void 0){let d=Uo.find(u=>u.id===n.template);if(d===void 0)return{refusal:N(["resources",t,"template"],`there is no built-in template "${n.template}": there is ${Uo.map(u=>u.id).join(", ")}`)};i={...o,strategy:d.strategy,objects:structuredClone(d.objects),...d.relations!==void 0?{relations:structuredClone(d.relations)}:{}}}else i={...o,strategy:"faker",objects:(n.objects??[]).map((d,u)=>({objectApiName:d.object,recordCount:d.count,fieldRules:structuredClone(d.fields??[]),excludedFields:[],insertOrder:u,batchSize:d.batchSize??200})),...n.relations!==void 0?{relations:n.relations.flatMap((d,u)=>{let l=d.parents.from;if(l===void 0)return[Pf(d)];let{childObject:f,lookupField:h,parentObject:g,distribution:m}=Pf(d);return a.push({at:u,relation:{childObject:f,lookupField:h,parentObject:g,distribution:m},from:l.split(".")[0]??l,...d.parents.limit!==void 0?{limit:d.parents.limit}:{}}),[]})}:{}};let c=Object.fromEntries((n.objects??[]).filter(d=>d.recordTypes!==void 0).map(d=>[d.object,[...new Set(d.recordTypes)]]));return{run:{template:i,...n.locale!==void 0?{locale:n.locale}:{},...n.seed!==void 0?{seed:n.seed}:{},...Object.keys(c).length>0?{recordTypes:c}:{},...n.fit!==void 0?{fit:n.fit==="share"?{}:{withinMB:n.fit.withinMB}}:{},acceptAutomation:n.accept?.automation===!0,...a.length>0?{draws:a}:{}}}}function sk(e){return e.object??e.from?.split(".")[1]??""}function Pf(e){let[t="",n=""]=e.lookup.split("."),r=e.parents.existing;return{childObject:t,lookupField:n,parentObject:sk(e.parents),parents:r===void 0?{kind:"generated"}:{kind:"existing",...r.where!==void 0?{where:r.where}:{},limit:r.limit},distribution:e.distribution}}function xf(e){return{kind:"existing",limit:e.limit??kr.maxExistingParents}}function Lf(e,t){let n=[...e.template.relations??[]],r=e.draws??[],s=[];for(let o=0;o<n.length+r.length;o++){let i=r.find(c=>c.at===o),a=i!==void 0?{...i.relation,parents:t(i)}:n.shift();a!==void 0&&s.push(a)}return s}function Ai(e,t,n){return(e.draws??[]).length===0?e.template:{...e.template,relations:Lf(e,r=>{let s=t?.get(r.at);if(s!==void 0&&s.length>0)return{kind:"records",ids:[...s]};if(!n.standIns)throw new Error(`The relation on ${r.relation.childObject}.${r.relation.lookupField} draws its parents from ${r.from}, whose records are not known: plan again.`);return xf(r)})}}var Nf=Object.keys(su);function ok(e,t,n){let r=["resources",e],s=Ai(n,void 0,{standIns:!0}),o=Ad.safeParse(s);if(!o.success)return{refusals:o.error.issues.map(d=>N(ik(r,t,d.path),d.message)),warnings:[]};let i=new iu().validate(s),a=({field:d,message:u})=>N(ak(r,t,s,d),u),c=n.locale!==void 0&&!Nf.includes(n.locale)?[N([...r,"locale"],`the seed draws in ${Nf.join(", ")}, not ${n.locale}: name one of them, or leave locale out to draw in the org\u2019s own`)]:[];return{refusals:[...i.errors.map(a),...c],warnings:i.warnings.map(a)}}function ik(e,t,n){if(t.template!==void 0)return[...e,"template"];let[r,s,o,...i]=n;if(r==="objects"&&typeof s=="number"){let a=[...e,"objects",s];return o==="objectApiName"?[...a,"object"]:o==="recordCount"?[...a,"count"]:o==="fieldRules"?[...a,"fields",...i]:o===void 0?a:[...a,o]}if(r==="relations"&&typeof s=="number"){let a=[...e,"relations",s];return o==="childObject"||o==="lookupField"?[...a,"lookup"]:o==="parentObject"?[...a,"parents","object"]:o==="parents"?[...a,"parents","existing",...i]:o===void 0?a:[...a,o,...i]}return e}function ak(e,t,n,r){if(t.template!==void 0)return[...e,"template"];let s=/^objects\[([^\]]+)\](?:\.fieldRules\[([^\]]+)\])?/.exec(r);if(s!==null){let i=n.objects.findIndex(d=>d.objectApiName===s[1]);if(i<0)return e;let a=s[2],c=a===void 0?-1:(n.objects[i]?.fieldRules??[]).findIndex(d=>d.fieldApiName===a);return c<0?[...e,"objects",i]:[...e,"objects",i,"fields",c]}let o=/^relations\[([^\]]+)\]/.exec(r);if(o!==null){let i=(n.relations??[]).findIndex(a=>`${a.childObject}.${a.lookupField}`===o[1]);return i<0?e:[...e,"relations",i]}return e}function Ff(e){let{template:t}=e;return{kind:"seed",kindVersion:1,strategy:t.strategy,objects:t.objects.map(n=>({objectApiName:n.objectApiName,recordCount:n.recordCount,recordTypeId:n.recordTypeId,fieldRules:n.fieldRules,excludedFields:n.excludedFields,insertOrder:n.insertOrder})),relations:t.relations??[],locale:e.locale??null,seed:e.seed??null,recordTypes:e.recordTypes??{},draws:e.draws,...e.fit!==void 0?{fit:e.fit}:{}}}function Mf(e){return e.template.objects.map(t=>({object:t.objectApiName,count:t.recordCount}))}function zf(e){let{template:t}=e,n=Lf(e,xf),r=new Set(n.filter(s=>s.parents.kind==="existing").map(s=>s.childObject));for(let s=!0;s;){s=!1;for(let o of t.objects)r.has(o.objectApiName)||sd(o,n).some(i=>r.has(i))&&(r.add(o.objectApiName),s=!0)}return new Map(t.objects.filter(s=>r.has(s.objectApiName)).map(s=>[s.objectApiName,s.recordCount]))}function _f(e){return["--target",C("--target",e.target),"--template-file",C("--template-file",e.templateFile),"--run-id",C("--run-id",e.runId),...e.seed!==void 0?["--seed",String(e.seed)]:[],...e.locale!==void 0?["--locale",C("--locale",e.locale)]:[],...Object.entries(e.recordTypes??{}).flatMap(([t,n])=>["--record-type",C("--record-type",`${t}=${n.join(",")}`)]),...e.fit!==void 0?["--fit","share",...e.fit.withinMB!==void 0?["--fit-within",String(e.fit.withinMB)]:[]]:[]]}function qf(e){return[..._f(e),"--json","--fail-on-partial"]}function Bf(e){return[..._f(e),"--dry-run","--json"]}function Uf(e){return[...e.includeChanged===!0?["--include-changed"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],...e.leaveUndeletable===!0?["--leave-undeletable"]:[]]}function Kf(e){return["--remove",C("--remove",e.summary),"--target",C("--target",e.target),...Uf(e),...be(e),"--json"]}function Wf(e){return["--remove",C("--remove",e.summary),"--target",C("--target",e.target),"--preview",...Uf(e),...be(e),"--json"]}var ck=p.object({limit:p.enum(["SingleEmail","DailyWorkflowEmails"]),emails:R,verdict:p.enum(["fits","exceeds","unread"]),remaining:p.number().int().optional(),max:p.number().int().optional(),unread:p.string().optional()}),dk=p.object({checks:p.array(ck),refusal:p.string().optional(),unknown:p.array(p.string()).optional()}),uk=p.object({records:R,given:R,refusal:p.string().optional()}),lk=e=>p.object({objectApiName:p.string().min(1),recordsCreated:R,recordsFailed:R,createdIds:p.array(e),errors:p.array(p.string()),truncated:p.boolean().optional(),writtenByThePlatform:uk.optional()}),Vf=e=>p.object({templateId:p.string().optional(),operationId:p.string().min(1),status:p.enum(["success","partial","failure"]),cancelled:p.boolean().optional(),objectResults:p.array(lk(e)),totalRecordsCreated:R,totalRecordsFailed:R}),Hf={tool:p.literal(se),target:p.string().min(1),seed:p.number().int().nonnegative(),startedAt:p.string().min(1),finishedAt:p.string().min(1),notes:p.array(p.string()).optional(),emails:dk,elapsedMs:R,interrupted:p.literal(!0).optional()},fk=p.object({...Hf,dryRun:p.literal(!1),targetOrgId:Xe.optional(),result:Vf(Xe),runFile:p.string().min(1).optional()}),pk=p.object({bytes:R,verdict:p.enum(["fits","near","exceeds","unread"]),estimateMB:p.number().nonnegative(),maxMB:p.number().optional(),remainingMB:p.number().optional(),unread:p.string().optional(),refusal:p.string().optional()}),hk=p.object({estimate:R,verdict:p.enum(["fits","near","exceeds","unread"]),max:p.number().int().optional(),remaining:p.number().int().optional(),unread:p.string().optional(),refusal:p.string().optional()}),mk=p.object({...Hf,dryRun:p.literal(!0),storage:pk,apiRequests:hk,wouldBeRefused:p.array(p.string()).optional(),wouldBeRefusedCodes:p.array(p.string()).optional(),result:Vf(p.string())}),gk=p.object({tool:p.literal(se),action:p.literal("remove"),summary:p.string().min(1),target:p.string().min(1),includeChanged:p.boolean(),result:p.object({status:p.enum(["success","partial","failure","cancelled"]),planned:R,objects:p.array(Ze),sweep:p.object({status:p.string()}).loose().optional()}),elapsedMs:R}),yk=p.object({tool:p.literal(se),action:p.literal("remove-preview"),summary:p.string().min(1),target:p.string().min(1),includeChanged:p.boolean(),preview:_t,refusals:p.array(p.string()),refusalCodes:p.array(p.string()).optional(),notes:p.array(p.string()),elapsedMs:R});function Wt(e){return z(se,"the summary of a run",fk,e)}function Jf(e){return z(se,"the summary of a dry run",mk,e)}function Yf(e){return z(se,"the preview of a removal",yk,e)}function Gf(e){return z(se,"the outcome of a removal",gk,e)}var Qf="validation";function Xf(e,t){let n=e.result.objectResults,r=c=>{let d=Fe(c,e.wouldBeRefused,e.wouldBeRefusedCodes);return d.length>0?{refusalCodes:d}:{}};if(e.result.status==="failure"&&n.length>0&&n.every(c=>c.objectApiName===Qf)){let c=n.flatMap(u=>u.errors),d=c.length>0?c.join(" "):"the seed refused its dry run";return{objects:[],total:0,created:0,apiRequests:e.apiRequests.estimate,storageBytes:0,emails:[],refusal:d,...r(d)}}let s=e.result.objectResults.map(c=>{let d=t?.get(c.objectApiName);return d!==void 0?{object:c.objectApiName,wouldCreate:Math.max(c.recordsCreated,d),atMost:!0}:{object:c.objectApiName,wouldCreate:c.recordsCreated}}),o=e.storage.refusal??e.apiRequests.refusal??e.emails.refusal,i=o!==void 0&&o===e.storage.refusal?`${o} ${nk}`:o,a=e.result.objectResults.flatMap(c=>c.writtenByThePlatform!==void 0?[wk(c.objectApiName,c.writtenByThePlatform.records)]:[]);return{objects:s,total:e.result.totalRecordsCreated,created:e.result.totalRecordsCreated,apiRequests:e.apiRequests.estimate,storageBytes:e.storage.bytes,emails:e.emails.checks.map(c=>({limit:c.limit,emails:c.emails})),...i!==void 0&&o!==void 0?{refusal:i,...r(o)}:{},...a.length>0?{notes:a}:{}}}function wk(e,t){return`${e}: ${t} record(s) linked to the contact role the platform writes with their opportunity, for its contact, not written: given the fields the seed generates for ${t===1?"it":"them"}`}function cs(e){let t=e.result.objectResults;if(e.result.status==="failure"&&t.length>0&&t.every(n=>n.objectApiName===Qf)){let n=t.flatMap(r=>r.errors);return{objects:[],created:0,refusal:n.length>0?n.join(" "):"the seed refused its run before it wrote"}}return{objects:e.result.objectResults.map(n=>({object:n.objectApiName,created:n.recordsCreated,refused:n.recordsFailed,errors:n.errors})),created:e.result.totalRecordsCreated}}import{readFileSync as vk}from"node:fs";var H="sandforge-users",ep=999999;function tp(e){return{run:{...e.defaults!==void 0?{defaults:e.defaults}:{},users:e.users,...e.accept?.automation===!0?{acceptAutomation:!0}:{}},warnings:[]}}function Oi(e){return e===void 0||e.length===0?null:[...new Set(e.map(t=>t.toLowerCase()))].sort()}function np(e){return{kind:"users",kindVersion:1,users:ud(ji(e)).map(n=>({username:dd(n.username),email:n.email??"keep",active:n.active??null,frozen:n.frozen??null,profile:n.profile??null,permissionSets:Oi(n.permissionSets),permissionSetGroups:Oi(n.permissionSetGroups),groups:Oi(n.groups)})).sort((n,r)=>n.username<r.username?-1:n.username>r.username?1:0)}}function rp(e){return[{object:"User",count:e.users.length}]}function ji(e){return{...e.defaults!==void 0?{defaults:e.defaults}:{},users:e.users}}function sp(e,t){if(!Number.isInteger(t)||t<1||t>ep)throw new Error(`${e} takes the number of a run of sandforge users, not ${t}.`);return String(t)}function op(e,t){return[e,"--org",C("--org",t.target),"--config",C("--config",t.configFile),...t.replacesRun!==void 0?["--replaces",sp("--replaces",t.replacesRun)]:[],...t.acceptUserEmails===!0?["--accept-user-emails"]:[],...t.acceptAutomation===!0?["--accept-automation"]:[]]}function ip(e){return[...op("plan",e),"--json"]}function ap(e){return[...op("apply",e),"--yes","--json"]}function cp(e){return["remove","--org",C("--org",e.target),"--run",sp("--run",e.run),...e.includeChanged===!0?["--include-changed"]:[],...e.acceptAutomation===!0?["--accept-automation"]:[],"--yes","--json"]}var kk=p.object({run:p.number().int().positive().max(ep)}).loose();function Pn(e){try{let t=kk.safeParse(JSON.parse(e));return t.success?t.data.run:void 0}catch{return}}function dp(e){let t;try{t=vk(e,"utf8")}catch(r){throw new Error(`${e} cannot be read (${r instanceof Error?r.message:String(r)}): the run of sandforge users it names cannot be taken back from it.`)}let n=Pn(t);if(n===void 0)throw new Error(`${e} names no run of sandforge users: the run it is the summary of cannot be taken back from it.`);return n}function up(e){let t=z(H,"the answer of a plan",br,e);return{tool:H,...t}}function Vt(e){return z(H,"the answer of a run",vt,e)}function Zf(e){return e.what==="permissionSet"||e.what==="permissionSetGroup"?"PermissionSetAssignment":e.what==="group"?"GroupMember":void 0}function lp(e){let t=z(H,"the outcome of a removal",Er,e),n=new Map,r=i=>{let a=n.get(i)??{deleted:0,refused:0,reasons:[]};return n.set(i,a),a},s=[];for(let i of t.users){for(let a of i.undone){let c=Zf(a);c!==void 0&&(r(c).deleted+=1)}for(let a of i.kept??[]){s.push({username:i.username,change:a.change,why:a.why});let c=Zf(a.change);if(c===void 0)continue;let d=r(c);d.refused+=1,d.reasons.push(`${i.username}: ${St(a.change)}: ${a.why}`)}}let o=[...n].map(([i,a])=>({objectApiName:i,planned:a.deleted+a.refused,deleted:a.deleted,alreadyGone:0,keptChanged:0,keptDependents:0,refused:a.refused,heldBy:[],reasons:a.reasons}));return{tool:H,result:{status:t.status,planned:o.reduce((i,a)=>i+a.planned,0),objects:o},undone:t.users.reduce((i,a)=>i+a.undone.length,0),kept:s,answer:t}}function St(e){switch(e.what){case"email":return"address asked back, awaiting its owner\u2019s confirmation";case"active":return e.to?"activated":"deactivated";case"frozen":return e.to?"frozen":"unfrozen";case"profile":return`profile ${e.to} in place of ${e.from}`;case"permissionSet":return`permission set ${e.name} ${e.to==="added"?"added":"taken back"}`;case"permissionSetGroup":return`permission set group ${e.name} ${e.to==="added"?"added":"taken back"}`;case"group":return`${e.type==="Queue"?"queue":"group"} ${e.name} `+(e.to==="added"?"joined":"left")}}function fp(e){return e.users.filter(t=>t.changes.length>0)}function pp(e){let t=fp(e).length,n=e.refusals??[],r=n.length>0?n.map(i=>i.message).join(" "):void 0,s=[...new Set(n.map(i=>i.code))],o=(e.licenses??[]).filter(i=>i.toUse>0).map(i=>`${i.name}: ${i.used} of ${i.total} used, ${i.toUse} more taken by the activations and the profiles`);return{objects:[{object:"User",wouldCreate:t}],total:t,created:0,apiRequests:e.apiRequests,storageBytes:0,emails:[],emailsToPeople:e.emailsToPeople,...r!==void 0?{refusal:r}:{},...r!==void 0&&s.length>0?{refusalCodes:s}:{},...o.length>0?{notes:o}:{}}}function hp(e){let t=e.refusals??[];if(t.length>0)return{objects:[],users:0,unread:t.map(o=>o.message).join(" ")};let n=fp(e),r=e.users.length-n.length,s=n.map(o=>`${o.username} would be ${o.changes.map(St).join(", ")}`);return{objects:[{object:"User",present:r}],users:r,...s.length>0?{drift:s.join("; ")}:{}}}function mp(e){return`applied, and the org holds its ${e} user(s) as the last run left them`}function gp(e,t){return`its users changed since it was applied: ${t}. Left as they are: --replace ${e} or --replace-drifted sets them up again, converging from what the last run left`}function ds(e){let t=e.users.filter(a=>(a.refused??[]).length>0),n=e.users.reduce((a,c)=>a+c.created.permissionSetAssignments.length,0),r=e.users.reduce((a,c)=>a+c.created.groupMembers.length,0),s=[{object:"User",created:0,refused:t.length,errors:t.flatMap(a=>(a.refused??[]).map(c=>`${a.username}: ${St(c.change)} refused, ${c.code}: ${c.message}`))},...n>0?[{object:"PermissionSetAssignment",created:n,refused:0,errors:[]}]:[],...r>0?[{object:"GroupMember",created:r,refused:0,errors:[]}]:[]],o=e.users.some(a=>a.done.length>0),i=e.refusals??[];return{objects:s,created:n+r,...!o&&i.length>0?{refusal:i.map(a=>a.message).join(" ")}:{}}}function yp(e){return e.users.map(t=>({username:t.username,userId:t.userId}))}var wp={seed:se,forge:Q,frozen:ue,mask:me,users:H,replay:V};function bk(e){return Object.prototype.hasOwnProperty.call(wp,e)}function us(e){if(!bk(e))throw new Error(`The state holds a resource of kind ${e}, which a later SandForge applies: this one applies seed, forge, frozen, mask, users and replay resources, and takes back nothing of another kind.`);return wp[e]}function vp(e,t,n,r,s,o={}){switch(n.kind){case"seed":{let i=Tf(e,t,n,s);return"refusals"in i?i:{run:{kind:"seed",...i.run},warnings:i.warnings}}case"forge":{let i=Yu(e,t,n,r,s);return"refusals"in i?i:{run:{kind:"forge",...i.run},warnings:i.warnings}}case"frozen":{let i=vl(t,n,r);return"refusals"in i?i:{run:{kind:"frozen",...i.run},warnings:i.warnings}}case"mask":{let i=zl(t,n,o);return"refusals"in i?i:{run:{kind:"mask",...i.run},warnings:i.warnings}}case"users":{let i=tp(n);return{run:{kind:"users",...i.run},warnings:i.warnings}}case"replay":{let i=pf(t,n);return"refusals"in i?i:{run:{kind:"replay",...i.run},warnings:i.warnings}}}}function kp(e){switch(e.kind){case"seed":return Ff(e.run);case"forge":return el(e.run,e.source.read);case"frozen":return kl(e.run);case"mask":return _l(e.run);case"users":return np(e.run);case"replay":return yf(e.run,e.checkpoint.read)}}function Ht(e){switch(e.kind){case"seed":return Mf(e);case"forge":return Gu(e);case"frozen":return[];case"mask":return ql(e);case"users":return rp(e);case"replay":return hf(e)}}function $t(e){return e==="frozen"||e==="mask"||e==="users"||e==="replay"}function Jt(e,t){switch(e.kind){case"seed":return Ai(e.run,t.drawn,{standIns:t.standIns===!0});case"forge":return e.run.template??{};case"frozen":{if(t.sasDir===void 0)throw new Error(`${e.name} is given no folder to keep its loads in: plan again.`);return bl(e.run,{sasDir:t.sasDir,datasetDir:e.dataset.dir})}case"mask":return Bl(e.run);case"users":return ji(e.run);case"replay":return{}}}function bp(e,t){switch(e.kind){case"seed":{let n=e.run.seed??t.seed;return{script:se,args:Bf({target:t.target,templateFile:t.templateFile,runId:t.runId,...n!==void 0?{seed:n}:{},...e.run.locale!==void 0?{locale:e.run.locale}:{},...e.run.recordTypes!==void 0?{recordTypes:e.run.recordTypes}:{},...e.run.fit!==void 0?{fit:e.run.fit}:{}})}}case"forge":return{script:Q,args:nl({...$p(e),target:t.target,templateFile:t.templateFile,...t.rootsPlanFile!==void 0?{rootsPlanFile:t.rootsPlanFile}:{},maxTotal:e.run.maxTotal??Ju})};case"frozen":return{script:ue,args:Rl({configFile:t.templateFile,target:t.target,reload:t.replace===!0,acceptAutomation:t.acceptAutomation===!0,...t.storeFile!==void 0?{store:t.storeFile}:{},...t.goneFirstFile!==void 0?{goneFirst:t.goneFirstFile}:{}})};case"mask":return{script:me,args:Kl({target:t.target,run:e.run,rulesFile:t.templateFile,store:Sp(e,t)})};case"users":return{script:H,args:ip(Ep(e,t))};case"replay":return{script:V,args:vf({...Rp(e,t),again:t.replace===!0})}}}function Ep(e,t){return{target:t.target,configFile:t.templateFile,...t.replacesRun!==void 0?{replacesRun:t.replacesRun}:{},...t.acceptUserEmails===!0?{acceptUserEmails:!0}:{},...t.acceptAutomation===!0||e.run.acceptAutomation===!0?{acceptAutomation:!0}:{}}}function Rp(e,t){if(t.checkpointStore===void 0)throw new Error(`${e.name} is given no store of checkpoints to replay from: plan again.`);return{name:e.name,run:e.run,place:e.checkpoint,target:t.target,store:t.checkpointStore,again:!1,...t.acceptAutomation===!0?{acceptAutomation:!0}:{}}}function Sp(e,t){if(t.store===void 0)throw new Error(`${e.name} is given no store to keep its snapshots in: plan again.`);return t.store}function $p(e){let{run:t,source:n}=e;if(t.wholeOrg)return{source:n.alias,wholeOrg:t.wholeOrg,acceptAutomation:t.acceptAutomation};if(t.tables!==void 0)return{source:n.alias,tables:t.tables,acceptAutomation:t.acceptAutomation};if(t.records!==void 0)return{source:n.alias,records:t.records,acceptAutomation:t.acceptAutomation};let r=n.read,s=t.record?.id??(r!==void 0&&"recordId"in r?r.recordId:void 0);if(s===void 0)throw new Error(`${e.name} names its record by a query its source has not answered: plan again.`);return{source:n.alias,recordId:s,acceptAutomation:t.acceptAutomation}}function Ap(e,t){switch(e){case"seed":return Jf(t);case"forge":return dl(t);case"frozen":return Il(t);case"mask":return Hl(t);case"users":return up(t);case"replay":return Of(t)}}function Ii(e){return e.kind==="seed"?zf(e.run):void 0}function Op(e,t){return e.kind==="forge"&&t.tool===Q?cl(t,e.run.template):void 0}function Yt(e,t){switch(e.tool){case se:return Xf(e,t);case Q:return pl(e);case ue:return Nl(e);case me:return Gl(e);case H:return pp(e);case V:return Cf(e)}}function At(e,t){switch(e.kind){case"seed":return{script:se,args:qf({target:t.target,templateFile:t.templateFile,runId:t.runId,...t.seed!==void 0?{seed:t.seed}:{},...e.run.locale!==void 0?{locale:e.run.locale}:{},...e.run.recordTypes!==void 0?{recordTypes:e.run.recordTypes}:{},...e.run.fit!==void 0?{fit:e.run.fit}:{}})};case"forge":{if(t.maxTotal===void 0)throw new Error(`${e.name} has no count from its dry run to be held to: plan again.`);return{script:Q,args:rl({...$p(e),target:t.target,templateFile:t.templateFile,...t.rootsPlanFile!==void 0?{rootsPlanFile:t.rootsPlanFile}:{},maxTotal:t.maxTotal,summary:t.summaryFile})}}case"frozen":{if(t.maxTotal===void 0)throw new Error(`${e.name} has no count from its dry run to be held to: plan again.`);return{script:ue,args:Sl({configFile:t.templateFile,target:t.target,reload:t.replace===!0,acceptAutomation:t.acceptAutomation===!0,maxTotal:t.maxTotal})}}case"mask":return{script:me,args:Wl({target:t.target,run:e.run,rulesFile:t.templateFile,store:Sp(e,t)})};case"users":return{script:H,args:ap(Ep(e,t))};case"replay":{if(t.maxTotal===void 0)throw new Error(`${e.name} has no count from its dry run to be held to: plan again.`);return{script:V,args:kf({...Rp(e,t),again:t.replace===!0,maxRecords:t.maxTotal})}}}}function ls(e){throw new Error(`${Ne(e)} takes no run back: a masking is never undone, and its destroy deletes its store`)}function jp(e){if(e.checkpointStore===void 0)throw new Error("a replay is given no store of checkpoints to take it back from: plan again.");return{replayed:Sf(e.subject),target:e.target,store:e.checkpointStore,includeChanged:e.includeChanged,acceptAutomation:e.acceptAutomation,...e.sweep===!0?{sweep:!0}:{}}}function Ip(e){throw new Error(`${Ne(e)} previews no removal: its plan reads what the org holds of its users`)}function Cp(e,t){let n=us(e),r=t.sweep===!0?{sweep:!0}:{},s={target:t.target,summary:t.subject,includeChanged:t.includeChanged,acceptAutomation:t.acceptAutomation,...r};switch(n){case se:return{script:n,args:Wf(s)};case Q:return{script:n,args:il(s)};case ue:return{script:n,args:Ol({configFile:t.subject,target:t.target,includeChanged:t.includeChanged,acceptAutomation:t.acceptAutomation,...r})};case me:return ls(n);case H:return Ip(n);case V:return{script:n,args:Rf(jp(t))}}}function Dp(e,t){let n=us(e);switch(n){case se:return Yf(t);case Q:return ll(t);case ue:return Dl(t);case me:return ls(n);case H:return Ip(n);case V:return jf(t)}}function Pp(e,t){if(e==="mask"||e==="users")return[];let n=[...t].reverse().filter(r=>r.takenBack!==!0);return e==="frozen"||e==="replay"?n.slice(0,1):n}function Np(e,t){if(e==="frozen")return{script:ue,args:$l({configFile:t.subject,target:t.target})}}function Tp(e){return xl(Cl(e))}function xp(e,t){let n=us(e),r={target:t.target,summary:t.subject,includeChanged:t.includeChanged,acceptAutomation:t.acceptAutomation,sweep:t.sweep};switch(n){case se:return{script:n,args:Kf(r)};case Q:return{script:n,args:ol(r)};case ue:return{script:n,args:Al({configFile:t.subject,target:t.target,includeChanged:t.includeChanged,sweep:t.sweep,acceptAutomation:t.acceptAutomation})};case me:return ls(n);case H:return{script:n,args:cp({target:t.target,run:dp(t.subject),includeChanged:t.includeChanged,acceptAutomation:t.acceptAutomation})};case V:return{script:n,args:Ef(jp(t))}}}function Lp(e,t){let n=us(e);switch(n){case se:return Gf(t);case Q:return ul(t);case ue:return Pl(t);case me:return ls(n);case H:return lp(t);case V:return If(t)}}function Ci(e){return e?.result.objects??[]}function Fp(e,t){return e.kind==="mask"?ef(e.name,t):e.kind==="forge"?Xu(e.run,e.source):[]}var mt=ww(Ag());import{isAbsolute as YS,resolve as dr}from"node:path";function fc(e){return`${kn(e.path)}: ${e.message}`}var GS=100;function jg(e){let t=e.startsWith("\uFEFF")?e.slice(1):e,n=(0,mt.parseDocument)(t,{version:"1.2",schema:"core",merge:!1,uniqueKeys:!1,prettyErrors:!0}),r=n.errors[0]??n.warnings[0];if(r)return{refusal:`The file does not read as YAML 1.2: ${r.message.split(`
|
|
147
|
+
`)[0]}`};let s=lc(n.contents,[]);if(s!==void 0)return{refusal:`${kn(s.path)} holds the key "${s.key}" twice: a mapping holds each key once, and the second would replace the first unseen. Keep one.`};try{return{document:n.toJS({maxAliasCount:GS})}}catch(o){return{refusal:`The file does not read as YAML 1.2: ${o instanceof Error?o.message:String(o)}`}}}function lc(e,t){if((0,mt.isMap)(e)){let n=new Set;for(let r of e.items){let s=(0,mt.isScalar)(r.key)?String(r.key.value):String(r.key);if(n.has(s))return{path:t,key:s};n.add(s);let o=lc(r.value,[...t,s]);if(o)return o}}else if((0,mt.isSeq)(e))for(let[n,r]of e.items.entries()){let s=lc(r,[...t,n]);if(s)return s}}function QS(e){return e==="salt"?"a Frozen load never reads its salt, and DataOps templates carry no hash salt: leave it out":"org credentials stay with the sf CLI \u2014 log the org in with sf org login sfdx-url or sf org login jwt before the step, and name it in the file by its alias"}function ur(e,t,n={}){let r=[...Rr(e).map(({path:f,secret:h})=>N(f,`a key shaped like a secret (${h}). The file holds no secret: ${QS(h)}.`)),...hd(e).filter(({path:f})=>!ld(f)).map(({path:f})=>N(f,`{ env } stands in ${qo.slice(0,-1).join(", ")} and ${qo.at(-1)??""} alone: write this value in the file. A variable inside a query or a field value would let a CI variable into what is written.`))];if(r.length>0)return{refusals:r};let s=pd.safeParse(e);if(!s.success)return{refusals:s.error.issues.map(f=>{let h=f.path,g=f.code==="invalid_key"?f.issues.map(m=>m.message):[];return N(h,g.join("; ")||f.message)})};let o=s.data,i=ZS(o);if("refusals"in i)return i;let a=Ml(o.masking);if("refusals"in a)return a;let c=[],d=[...XS(o)],u={};for(let[f,h]of Object.entries(o.resources)){let g=vp(o.name,f,h,dr(t),n.now??new Date,a.sets);if("refusals"in g){c.push(...g.refusals);continue}d.push(...g.warnings),u[f]=g.run}if(c.push(...e$(u)),c.length>0)return{refusals:c};let l=[];for(let[f,{alias:h}]of Object.entries(o.orgs))typeof h!="string"&&l.push({name:h.env,path:["orgs",f,"alias"],role:f});for(let[f,h]of Object.entries(o.resources)){h.kind==="frozen"&&typeof h.dataset.path!="string"&&l.push({name:h.dataset.path.env,path:["resources",f,"dataset","path"],resource:f});let g=h.kind==="replay"?h.checkpoint.file:void 0;g!==void 0&&typeof g!="string"&&l.push({name:g.env,path:["resources",f,"checkpoint","file"],resource:f})}return{checked:{file:o,folder:dr(t),order:i.order,runs:u,variables:l,warnings:d}}}function XS(e){let t=new Set(Object.values(e.resources).flatMap(n=>n.kind==="mask"&&typeof n.rules=="string"?[n.rules]:[]));return Object.keys(e.masking).filter(n=>!t.has(n)).map(n=>N(["masking",n],"no mask resource names this rule set: nothing masks with it"))}function Ig(e,t){return e.variables.filter(n=>(t[n.name]??"").trim()==="")}function Cg(e,t){return t.kind!=="seed"?[]:(t.relations??[]).flatMap((n,r)=>{let s=n.parents.from?.split(".")[0];return s===void 0?[]:[{from:s,path:["resources",e,"relations",r,"parents","from"]}]})}function pc(e,t){return[...new Set([...t.kind==="users"?[]:t.dependsOn??[],...Cg(e,t).map(({from:n})=>n)])]}function ZS(e){let t=Object.keys(e.resources),n=[],r=new Map;for(let[d,u]of Object.entries(e.resources)){let l=[];for(let{from:h,path:g}of Cg(d,u))h===d?n.push(N(g,`a relation draws its parents from the records another resource created: ${d}'s own are drawn by their object alone, without from`)):h in e.resources?l.includes(h)||l.push(h):n.push(N(g,`"${h}" is no resource of this file: name one of ${t.join(", ")}`));(u.kind==="users"?[]:u.dependsOn??[]).forEach((h,g)=>{let m=["resources",d,"dependsOn",g];h===d?n.push(N(m,`a resource does not depend on itself: take ${d} out of its dependsOn`)):h in e.resources?l.includes(h)||l.push(h):n.push(N(m,`"${h}" is no resource of this file: name one of ${t.join(", ")}`))}),r.set(d,l)}if(n.length>0)return{refusals:n};let s=t$(t,r);if(s!==void 0)return{refusals:[N(["resources",s[0]??""],`the resources depend on each other in a circle, ${s.join(" \u2192 ")}: no order applies them. Take one of them out of the dependsOn of the next, or out of what its relations draw their parents from.`)]};let o=t.filter(d=>e.resources[d]?.kind==="users"),i=[...o,...t.filter(d=>!o.includes(d))],a=[],c=new Set;for(;a.length<t.length;){let d=i.find(u=>!c.has(u)&&(r.get(u)??[]).every(l=>c.has(l)));if(d===void 0)break;a.push(d),c.add(d)}return{order:a}}function e$(e){let t=[];for(let[n,r]of Object.entries(e))if(r.kind==="seed")for(let s of r.draws??[]){let o=e[s.from];if(o?.kind==="mask"){t.push(N(["resources",n,"relations",s.at,"parents","from"],`${s.from} is a mask resource, which creates no record: a relation draws its parents from the records a seed, a forge or a frozen resource created`));continue}if(o?.kind!=="seed")continue;let i=Ht(o).map(({object:a})=>a);i.includes(s.relation.parentObject)||t.push(N(["resources",n,"relations",s.at,"parents","from"],`${s.from} writes no ${s.relation.parentObject} records: it writes ${i.join(", ")||"none"}`))}return t}function t$(e,t){let n=new Set,r=[],s=o=>{let i=r.indexOf(o);if(i>=0)return[...r.slice(i),o];if(!n.has(o)){r.push(o);for(let a of t.get(o)??[]){let c=s(a);if(c!==void 0)return c}r.pop(),n.add(o)}};for(let o of e){let i=s(o);if(i!==void 0)return i}}function hc(e,t){return ui(zt({...kp(e),dependsOn:t}))}var Og=/^[^-\s][^\s]{0,199}$/;function mc(e,t,n={}){let r=Object.keys(e.file.orgs),s=[],o=n.aliases??{};for(let[f,h]of Object.entries(o))r.includes(f)?Og.test(h)||s.push(N(["orgs",f,"alias"],`--alias ${f}= gives no alias: one holds no space and does not start with "-"`)):s.push(N(["orgs"],`--alias names the role ${f}, which the file's orgs do not declare: `+(r.length>0?`its roles are ${r.join(", ")}`:"it declares none")));let i={};for(let[f,{alias:h}]of Object.entries(e.file.orgs)){let g=o[f];if(g!==void 0){i[f]=g;continue}if(typeof h=="string"){i[f]=h;continue}let m=(t[h.env]??"").trim();m===""?s.push(N(["orgs",f,"alias"],`the variable ${h.env} is not set: set it in the job's environment to the alias of the ${f} org, or give --alias ${f}=<alias>`)):Og.test(m)?i[f]=m:s.push(N(["orgs",f,"alias"],`the variable ${h.env} holds no alias: one holds no space and does not start with "-"`))}let a={};for(let[f,h]of Object.entries(e.file.resources)){if(h.kind!=="frozen")continue;let g=n$(f,h.dataset.path,t,e.folder);"refusal"in g?s.push(g.refusal):a[f]=g.dir}let c={};for(let[f,h]of Object.entries(e.file.resources)){if(h.kind!=="replay"||h.checkpoint.file===void 0)continue;let g=mf(f,h.checkpoint.file,t);"refusal"in g?s.push(g.refusal):c[f]=g.file}if(s.length>0)return{refusals:s};let d={},u=[];for(let f of e.order){let h=e.runs[f],g=e.file.resources[f];if(h===void 0||g===void 0)continue;let m=pc(f,g),w;if(h.kind==="seed"){let{kind:y,...v}=h;w={name:f,kind:y,dependsOn:m,fingerprint:"",run:v}}else if(h.kind==="mask"){let{kind:y,...v}=h;w={name:f,kind:y,dependsOn:m,fingerprint:"",run:v}}else if(h.kind==="users"){let{kind:y,...v}=h;w={name:f,kind:y,dependsOn:m,fingerprint:"",run:v}}else if(h.kind==="replay"){let{kind:y,...v}=h,b=n.checkpoints?.[f],k=v.from!==void 0?i[v.from]:void 0,E=c[f];w={name:f,kind:y,dependsOn:m,fingerprint:"",run:v,checkpoint:{...k!==void 0?{from:k}:{},...E!==void 0?{file:E}:{},...b!==void 0?{read:b}:{}}}}else if(h.kind==="frozen"){let{kind:y,...v}=h,b=n.datasets?.[f];w={name:f,kind:y,dependsOn:m,fingerprint:"",run:v,dataset:{dir:a[f]??"",...b!==void 0?{read:b}:{}}}}else{let{kind:y,...v}=h,b=n.sources?.[f];w={name:f,kind:y,dependsOn:m,fingerprint:"",run:v,source:{role:v.source,alias:i[v.source]??"",...b!==void 0?{read:b}:{}}}}w.fingerprint=hc(w,Object.fromEntries(m.map(y=>[y,d[y]]))),d[f]=w.fingerprint,u.push(w)}let l=ui(zt({...e.file,orgs:Object.fromEntries(Object.entries(i).map(([f,h])=>[f,{alias:h}]))}));return{resolved:{checked:e,orgs:i,resources:u,digest:l}}}function n$(e,t,n,r){let s=["resources",e,"dataset","path"],o;if(typeof t=="string")o=t;else{if(o=(n[t.env]??"").trim(),o==="")return{refusal:N(s,`the variable ${t.env} is not set: set it in the job's environment to the folder the dataset of ${e} was downloaded to`)};if(!YS(o))return{refusal:N(s,`the variable ${t.env} holds ${o}, which is not a path from the root: give the folder of the dataset from the root`)}}let i;try{i=Cr(r)}catch{i=void 0}return i!==void 0&&new Ke(i).isInsideRepo(dr(o))?{refusal:N(s,`the dataset of ${e}, ${dr(o)}, is inside the repository ${i} that holds the file: a frozen dataset is pseudonymized business data, and stays outside the project. Keep it where the pipeline downloads it, and name that folder.`)}:{dir:dr(o)}}function Dg(e,t,n,r={}){let s=ur(e,t,r.now?{now:r.now}:{});return"refusals"in s?s:mc(s.checked,n,{...r.aliases?{aliases:r.aliases}:{},...r.sources?{sources:r.sources}:{},...r.datasets?{datasets:r.datasets}:{},...r.checkpoints?{checkpoints:r.checkpoints}:{}})}var Ng="USERS_EMAILS_NOT_ACCEPTED";function Tg(e){if(e.tool!==H)return e;let t=e,n=(t.refusals??[]).filter(s=>s.code!==Ng),r={...t};return delete r.refusals,n.length>0?{...r,refusals:n}:r}var xg=new Set(["create","replace","delete"]),je=new Set(["create","replace"]);function vc(e){return xg.has(e.action)}function qe(e){return Object.entries(e?.resources??{}).filter(([,t])=>t.status!=="destroyed")}function kc(e,t){let n=[],r=new Set,s=new Set(e);for(;n.length<e.length;){let o=e.find(i=>!r.has(i)&&t(i).every(a=>!s.has(a)||r.has(a)||a===i))??e.find(i=>!r.has(i));if(o===void 0)break;n.push(o),r.add(o)}return n}function gt(e,t){let n=e?.resources??{},r=kc(t,o=>n[o]?.dependsOn??[]).reverse(),s=o=>n[o]?.kind==="users";return[...r.filter(o=>!s(o)),...r.filter(s)]}function r$(e,t){return t===void 0||t.differs||t.unread!==void 0?!1:[...e.objects.values()].every(n=>n.gone===0&&n.unread===0)}function gc(e){let t={objects:new Map,changedBy:new Map,refusals:[],removalAlone:[],codes:new Map,failed:[],verified:[]};for(let n of e){if("failed"in n){t.failed.push(`run ${n.n}: ${n.failed}`);continue}if("nothing"in n)continue;let r=n.refreshed;r!==void 0&&"unread"in r?t.failed.push(`run ${n.n}: its verification did not say (${r.unread})`):r!==void 0&&t.verified.push(...r.failed);let{preview:s}=n.preview;for(let o of s.objects){let i=t.objects.get(o.objectApiName)??{present:0,gone:0,changed:0,unread:0};i.present+=o.toDelete+o.keptChanged+o.undeletable,i.gone+=o.alreadyGone+o.notVisible,i.changed+=o.changedSince,i.unread+=o.unread,t.objects.set(o.objectApiName,i);for(let[a,c]of Object.entries(o.changedBy)){let d=s.userNames[a]??a;t.changedBy.set(d,(t.changedBy.get(d)??0)+c)}}for(let o of n.preview.refusals)t.refusals.includes(o)||t.refusals.push(o);if(Pg(t.codes,n.preview.refusals,n.preview.refusalCodes),"removalAlone"in n.preview){t.removalAlone.push(...n.preview.removalAlone);let o="removalAloneCodes"in n.preview?n.preview.removalAloneCodes:void 0;Pg(t.codes,n.preview.removalAlone,o)}}return t}function Pg(e,t,n){n?.length===t.length&&t.forEach((r,s)=>e.set(r,n[s]??""))}function bc(e){return[...e.refusals,...e.removalAlone]}function yc(e,t=bc(e)){return[...new Set(t.flatMap(n=>e.codes.get(n)||[]))]}function fo(e){return e.length>0?{refusalCodes:[...new Set(e)]}:{}}function wc(e){return[...e.objects].map(([t,n])=>({object:t,present:n.present,gone:n.gone,changed:n.changed}))}function s$(e){let t=[...e.objects].flatMap(([s,o])=>{let i=[o.gone>0?`${o.gone} gone`:"",o.changed>0?`${o.changed} changed`:"",o.unread>0?`${o.unread} not read`:""].filter(Boolean);return i.length>0?[`${s} ${i.join(", ")}`]:[]});if(e.verified.length>0&&t.push(`its verification: ${e.verified.join("; ")}`),t.length===0)return;let n=[...e.changedBy].sort((s,o)=>o[1]-s[1]),r=n.length>0?` (last changed by ${n.map(([s,o])=>`${s} ${o}`).join(", ")})`:"";return`${t.join("; ")}${r}`}var Lg="taken back: the assignments and memberships the environment created deleted by id, each user put back as it was before; an address asked back stays, and no user is deleted",o$="its state was recovered from its run files, which do not say what it was applied from",i$={applying:"its last run was stopped part way: what it wrote is taken back from its run file, then it runs again",partial:"its last run was partial: the org refused records of it, or kept some of its records",failed:"its last run failed",destroying:"a removal of it was stopped part way"},a$={applying:"its last run was stopped part way: a run converges from what it left",partial:"its last run was partial: the org refused changes to its users",failed:"its last run failed",destroying:"a removal of it was stopped part way"};function c$(e){if(e.kind==="frozen"){let n=e.dataset.read;return n===void 0?`its dataset at ${e.dataset.dir} was not read: plan again`:"refusal"in n?n.refusal:void 0}if(e.kind==="replay"){let n=e.checkpoint.read;return n===void 0?"its checkpoint was not resolved: plan again":"refusal"in n?n.refusal:void 0}if(e.kind!=="forge")return;let t=e.source.read;return t===void 0?`its source, the ${e.source.role} org, was not read: plan again`:"refusal"in t?t.refusal:void 0}function Ec(e){let{resolved:t,state:n,previews:r}=e,s=r===void 0,o=new Set(e.replace??[]),i=new Map(qe(n)),a=new Set(t.resources.map(u=>u.name)),c=new Map;for(let u of t.resources){let l=i.get(u.name),f=c$(u),h=u.kind;if(l===void 0){c.set(u.name,{resource:u.name,kind:h,action:"create",why:n?.resources[u.name]?.status==="destroyed"?"taken back by an earlier destroy: applied again":"not applied to this org yet",objects:[],...f!==void 0?{refusal:f}:{}});continue}let g=gc(r?.[u.name]??[]),m=[],w=hc(u,Object.fromEntries(u.dependsOn.map(A=>[A,n?.resources[A]?.fingerprint])));l.recovered===!0?m.push(o$):l.fingerprint!==u.fingerprint&&l.fingerprint!==w&&m.push("what it writes changed in the file since it was applied");let y=(h==="mask"?nf:h==="users"?a$:i$)[l.status];y!==void 0&&m.push(y);let v=u.dependsOn.filter(A=>{let P=c.get(A);return P!==void 0&&je.has(P.action)&&P.kind!=="mask"});if(v.length>0&&m.push(`the resources it depends on run again, with new records: ${v.join(", ")}`),o.has(u.name)&&m.push("--replace asks it"),h==="mask"){c.set(u.name,d$(u.name,l,m,e,s));continue}if(h==="users"){c.set(u.name,u$(u.name,m,e,s));continue}let b=s?void 0:s$(g),k=b!==void 0&&r$(g,e.drift),E=k?void 0:b;m.length===0&&E!==void 0&&e.replaceDrifted===!0&&m.push(`its records drifted (${E}), and --replace-drifted asks it`);let S=wc(g),$=f??(g.refusals.length>0?`a removal of its runs would be refused now: ${g.refusals.join(" ")}`:g.failed.length>0?`what the org holds of it could not be read (${g.failed.join("; ")}): plan again`:void 0),j=f===void 0&&g.refusals.length>0?yc(g,g.refusals):[];if(m.length>0)c.set(u.name,{resource:u.name,kind:h,action:"replace",why:`replaced: ${m.join("; ")}`,objects:S,...$!==void 0?{refusal:$,...fo(j)}:{}});else if(s)c.set(u.name,{resource:u.name,kind:h,action:"keep",why:"applied from the same file; what the org holds of it was not read (--quick)",objects:S,...f!==void 0?{refusal:f}:{}});else if(f!==void 0||g.failed.length>0)c.set(u.name,{resource:u.name,kind:h,action:"keep",why:"applied from the same file",objects:S,refusal:f??`what the org holds of it could not be read (${g.failed.join("; ")}): plan again`});else if(E!==void 0)c.set(u.name,{resource:u.name,kind:h,action:"drifted",why:`its records changed since it was applied: ${E}. Left as they are: --replace ${u.name} or --replace-drifted replaces it`,objects:S});else{let A=S.reduce((D,x)=>D+(x.present??0),0),P=S.reduce((D,x)=>D+(x.changed??0),0);c.set(u.name,{resource:u.name,kind:h,action:"keep",why:k?`applied, and the org holds its ${A} record(s) as the checkpoint taken after the apply holds them: ${P} written since hold their values again, as a reset gives them back`:`applied, and the org holds its ${A} record(s) as written`,objects:S})}}return[...gt(n,[...i.keys()].filter(u=>!a.has(u))).map(u=>{let l=i.get(u);if(l?.kind==="mask")return{resource:u,kind:"mask",action:"delete",why:Ri("apply",u,l,Rc(e,u)),objects:Fg(l)};let f=gc(r?.[u]??[]),h=bc(f),g=h.length>0?`a removal of its runs would be refused now: ${h.join(" ")}`:f.failed.length>0?`what the org holds of it could not be read (${f.failed.join("; ")}): plan again`:void 0;return{resource:u,kind:i.get(u)?.kind??"seed",action:"delete",why:l?.kind==="users"?`in the state, gone from the file: ${Lg}`:"in the state, gone from the file: its records are taken back",objects:wc(f),...g!==void 0?{refusal:g,...fo(h.length>0?yc(f):[])}:{}}}),...t.resources.flatMap(u=>c.get(u.name)??[])]}function d$(e,t,n,r,s){let o=(l,f,h=[],g)=>({resource:e,kind:"mask",action:l,why:f,objects:h,...g!==void 0?{refusal:g}:{}});if(n.length>0)return o("replace",`replaced: ${n.join("; ")}; ${Ei(t)}`);if(s)return o("keep","applied from the same file; what the org holds of it was not read (--quick)");if(r.dryRuns===void 0)return o("keep","applied from the same file");let i=r.dryRuns[e];if(i===void 0)return o("keep","applied from the same file",[],"it was not dry-run: plan again");if("failed"in i||i.answer.tool!==me){let l="failed"in i?i.failed:`${Ne(i.answer.tool)} answered its dry run`;return o("keep","applied from the same file",[],`what the org holds of it could not be read (its dry run: ${l}): plan again`)}let a=r.resolved.resources.map(l=>l.name),c=r.resolved.resources.find(l=>l.name===e),d=c?.kind==="mask"?c.run.where:void 0,u=Xl(t,i.answer,Ql(e,r.state,a,d));return u.unread!==void 0?o("keep","applied from the same file",u.objects,`what the org holds of it could not be read: ${u.unread}`):u.drift===void 0?o("keep",rf(u.masked,u.theirs),u.objects):r.replaceDrifted===!0?o("replace",`replaced: its condition selects other records than it masked (${u.drift}), and --replace-drifted asks it; ${Ei(t)}`,u.objects):o("drifted",sf(e,u.drift),u.objects)}function u$(e,t,n,r){let s=(d,u,l=[],f)=>({resource:e,kind:"users",action:d,why:u,objects:l,...f!==void 0?{refusal:f}:{}}),o=n.usersUnknown?.[e],i=o!==void 0?[...t,o]:t;if(t.length>0)return s("replace",`replaced: ${i.join("; ")}`);if(r)return s("keep","applied from the same file; no word on its users (--quick)");if(n.dryRuns===void 0)return s("keep","applied from the same file");let a=n.dryRuns[e];if(a===void 0)return s("keep","applied from the same file",[],"it was not dry-run: plan again");if("failed"in a||a.answer.tool!==H){let d="failed"in a?a.failed:`${Ne(a.answer.tool)} answered its plan`;return s("keep","applied from the same file",[],`what the org holds of its users could not be read (its plan: ${d}): plan again`)}let c=hp(Tg(a.answer));return c.unread!==void 0?s("keep","applied from the same file",c.objects,`what the org holds of its users could not be read: ${c.unread}`):c.drift===void 0?s("keep",mp(c.users),c.objects):n.replaceDrifted===!0?s("replace",`replaced: its users changed since it was applied (${c.drift}), and --replace-drifted asks it; a run converges from what the last one left`,c.objects):s("drifted",gp(e,c.drift),c.objects)}function Rc(e,t){let n=e.maskStores?.[t],r=e.org??e.state?.org;return{alias:r?.alias??r?.organizationId??"<alias>",...n!==void 0?{store:n}:{}}}function Fg(e){return(e.runs.at(-1)?.objects??[]).map(t=>({object:t.objectApiName,present:t.masked??0}))}function l$(e,t){let n=new Set(t.filter(o=>je.has(o.action)).map(o=>o.resource)),r=new Set(t.filter(o=>je.has(o.action)&&o.kind!=="mask").map(o=>o.resource)),s=new Map;for(let o of e.resources){if(!n.has(o.name))continue;let i=o.dependsOn.filter(a=>r.has(a));i.length>0&&s.set(o.name,i)}return s}function f$(e,t){let n=e.map(r=>({...r}));for(let r of t.objects){let s={wouldCreate:r.wouldCreate,...r.atMost===!0?{atMost:!0}:{}},o=n.find(i=>i.object===r.object);o?Object.assign(o,s):n.push({object:r.object,...s})}return n}function p$(e,t,n,r){let s=e.resources.find(c=>c.name===t),o=r&&s!==void 0?Ii(s):void 0,i=Yt(Tg(n),o),a=s!==void 0?Op(s,n):void 0;return{count:a!==void 0&&i.refusal===void 0?{...i,refusal:a}:i}}function h$(e,t){let n=e.resources.find(r=>r.name===t);return n!==void 0&&(Ii(n)?.size??0)>0}function m$(e,t,n){let r=e.resources.find(o=>o.name===t);if(r?.kind!=="seed")return[];let s=new Set((r.run.draws??[]).map(o=>o.from));return n.filter(o=>s.has(o))}function po(e){return e!==void 0&&"answer"in e?Yt(e.answer).total:void 0}function g$(e,t){let n=[],{apiRequests:r,storage:s,emails:o}=e;r.leftToday!==void 0&&r.estimate>r.leftToday&&n.push(`The resources the plan writes take about ${r.estimate} API requests, and ${t} has ${r.leftToday} left today: the apply would stop part way. Apply once the org has requests to spare \u2014 the limit is counted over the last 24 hours \u2014 or write fewer records.`),s.left!==void 0&&s.bytes>s.left&&n.push(`The resources the plan writes take about ${kt(s.bytes/1048576)} MB of data storage, and ${t} has ${kt(s.left/1048576)} MB left: the org would refuse records part way. Write fewer records, or free storage first.`);for(let i of o)i.left!==void 0&&i.emails>i.left&&n.push(`The resources the plan writes make ${t} send ${i.emails} ${i.limit} emails, and it has ${i.left} left today: each resource alone may fit, the day does not. Apply the resources over two days, or keep the automation that sends them quiet.`);return n}function y$(e,t,n,r,s,o=!1){let i=s.estimate,a=0,c=new Map,d=[...s.notCounted],u;for(let g of e){if((g.action==="delete"||g.action==="replace")&&g.kind!=="mask"&&!(g.action==="replace"&&g.kind==="users")&&d.push(`the removal of the runs of ${g.resource}`),!je.has(g.action))continue;g.kind==="users"&&(u??=0);let m=t?.[g.resource];if(m===void 0||"failed"in m){d.push(`the run of ${g.resource}, not dry-run`);continue}let w=r.get(g.resource);w!==void 0&&g.kind!=="mask"&&d.push(`what ${g.resource} draws from the records ${w.join(", ")} writes first`);let y=Yt(m.answer);y.apiRequests===void 0?d.push(`the requests of the run of ${g.resource}, which its script does not estimate`):i+=y.apiRequests,a+=y.storageBytes;for(let{limit:v,emails:b}of y.emails)c.set(v,(c.get(v)??0)+b);y.emailsToPeople!==void 0&&(u=(u??0)+y.emailsToPeople)}let l=n?.apiRequests,f=n?.storage,h=n?.emails;return{apiRequests:{estimate:i,...l!==void 0&&!("unread"in l)?{leftToday:l.remaining}:{},partial:d.length>0,...d.length>0?{notCounted:d}:{},...l!==void 0&&"unread"in l?{unread:l.unread}:{},...n===void 0?{unread:"not read: --quick"}:{}},storage:{bytes:a,...f!==void 0&&!("unread"in f)?{left:Math.floor(f.remainingMB*1048576)}:{},...f!==void 0&&"unread"in f?{unread:f.unread}:{},...n===void 0?{unread:"not read: --quick"}:{}},emails:[...c].map(([g,m])=>{let w=h!==void 0&&!("unread"in h)?h[g]?.remaining:void 0;return{limit:g,emails:m,...w!==void 0?{left:w}:{}}}),...u!==void 0?{emailsToPeople:{count:u,accepted:o}}:{}}}function w$(e,t){let n=e.emailsToPeople;return n===void 0||n.count===0||n.accepted?void 0:`${t.flatMap(s=>{let o=s.gates?.emailsToPeople??0;return s.kind!=="users"||!je.has(s.action)||o===0?[]:[`${s.resource} has Salesforce email ${o} ${o===1?"person":"people"} (the confirmation of ${o===1?"an address":`${o} addresses`} asked back)`]}).join(", ")}, which only the line accepts: --accept-user-emails. Nothing was written.`}function Sc(e){let t=e.previews===void 0,n=Ec(e),r=l$(e.resolved,n),s=n.map(y=>{let v=y.objects,b,k=y.refusal,E=y.refusal!==void 0?y.refusalCodes??[]:[],S=je.has(y.action)?e.dryRuns?.[y.resource]:void 0,$=r.get(y.resource),j=$!==void 0&&h$(e.resolved,y.resource),A=je.has(y.action)?e.draws?.[y.resource]:void 0;A!==void 0&&A.refusals.length>0&&(k??=A.refusals.join(" "));let P=[],D=e.dryRuns?.[y.resource],x=y.kind==="users"&&D!==void 0&&"answer"in D&&D.answer.tool===H?D.answer.users:void 0;if(S!==void 0&&"failed"in S)S.refused!==void 0&&k===void 0&&(k=`its own dry run says a real run would be refused: ${S.refused.message}`,E=[S.refused.code]),k??=`its dry run did not answer: ${S.failed}`;else if(S!==void 0){let Z=p$(e.resolved,y.resource,S.answer,$!==void 0);v=f$(v,Z.count),b={...Z.count.apiRequests!==void 0?{apiRequests:Z.count.apiRequests}:{},storageBytes:Z.count.storageBytes,emails:Z.count.emails,...Z.count.emailsToPeople!==void 0?{emailsToPeople:Z.count.emailsToPeople}:{}};let De=Z.count.refusal;De!==void 0&&k===void 0&&(k=`its own dry run says a real run would be refused: ${De}`,E=Z.count.refusalCodes??[]),P=Z.count.notes??[]}else je.has(y.action)&&!t&&(k??="it was not dry-run: plan again");let G=$!==void 0?m$(e.resolved,y.resource,$):[],K=$!==void 0&&S!==void 0&&y.kind==="mask"?`; its dry run read the org before ${$.join(", ")} writes: what they write under its condition it masks too, uncounted here`:$!==void 0&&S!==void 0&&j?G.length>0?`; it draws its parents from the records ${G.join(", ")} creates in this apply, which nobody knows before it runs: counted at most as the file gives it`:`; its dry run read the org before ${$.join(", ")} writes: what it draws from those records is counted at most as the file gives it`:"",O=`${y.why}${K}${P.length>0?`; ${P.join("; ")}`:""}`,M=e.resolved.resources.find(Z=>Z.name===y.resource),ce=M!==void 0&&je.has(y.action)?Fp(M,Rc(e,y.resource)):[];return{resource:y.resource,kind:y.kind,action:k!==void 0?"blocked":y.action,why:O,objects:v,...A!==void 0&&A.draws.length>0?{draws:A.draws}:{},...b!==void 0?{gates:b}:{},...k!==void 0?{refusal:k,...fo(E)}:{},...ce.length>0?{notes:ce}:{},...x!==void 0?{users:x}:{}}}),o=e.resolved.checked.file,i=Iu(Vr(o,e.state,n.some(y=>xg.has(y.action))),t?void 0:e.checkpointEstimate??{unread:"not estimated"},s.filter(y=>je.has(y.action)&&y.kind!=="mask").flatMap(y=>y.objects).reduce((y,v)=>y+(v.wouldCreate??0),0)),a=y$(n,e.dryRuns,e.budget,r,Du(i),e.acceptUserEmails===!0),c=e.org.alias??e.org.organizationId,d=g$(a,c);if(d.length>0)for(let y of s)vc(y)&&(y.refusal=d.join(" "),y.action="blocked");let u=s.filter(y=>y.action==="blocked"),l=w$(a,s),f=e.refusal??(d.length>0?`${d.join(" ")} Nothing was written.`:u.length>0?`${u.length===1?"A resource is":`${u.length} resources are`} blocked, and the apply refuses before its first write: ${u.map(y=>`${y.resource} (${y.refusal??y.why})`).join("; ")}`:void 0)??l??Cu(i),h=e.refusal!==void 0?[...e.refusalCodes??[]]:d.length>0?[]:u.length>0?u.flatMap(y=>y.refusalCodes??[]):l!==void 0?[Ng]:i.flatMap(y=>y.refusal!==void 0?[y.refusal.code]:[]),g=[...e.warnings??[],...Ou(o,e.state)],m=y=>s.filter(v=>v.action===y).length,w=e.state;return{env:e.resolved.checked.file.name,org:e.org,state:w!==void 0?{found:!0,serial:w.serial}:{found:!1,...e.refreshed!==void 0?{refreshed:e.refreshed}:{}},actions:s,totals:{create:m("create"),keep:m("keep"),replace:m("replace"),delete:m("delete"),drifted:m("drifted"),blocked:m("blocked")},gates:a,...i.length>0?{checkpoints:i}:{},...e.drift!==void 0?{drift:e.drift}:{},...f!==void 0?{refusal:f,...fo(h)}:{},...t?{quick:!0}:{},...g.length>0?{warnings:g}:{}}}function Mg(e){let n=gt(e.state,qe(e.state).map(([a])=>a)).map(a=>{let c=e.state?.resources[a];if(c?.kind==="mask")return{resource:a,kind:"mask",action:"delete",why:Ri("destroy",a,c,Rc(e,a)),objects:Fg(c)};let d=gc(e.previews?.[a]??[]),u=bc(d),l=u.length>0?`a removal of its runs would be refused now: ${u.join(" ")}`:d.failed.length>0?`what the org holds of it could not be read (${d.failed.join("; ")}): run destroy again`:void 0,f=u.length>0?yc(d):[];return{resource:a,kind:c?.kind??"seed",action:l!==void 0?"blocked":"delete",why:c?.kind==="users"?`${Lg}, after every other resource`:"taken back by destroy, into the recycle bin",objects:wc(d),...l!==void 0?{refusal:l}:{},...f.length>0?{refusalCodes:f}:{}}}),r=n.filter(a=>a.action==="blocked"),s=[...new Set(r.flatMap(a=>a.refusalCodes??[]))],o=n.filter(a=>a.kind!=="mask").map(a=>`the removal of the runs of ${a.resource}`),i=e.state;return{env:e.resolved.checked.file.name,org:e.org,state:i!==void 0?{found:!0,serial:i.serial}:{found:!1},actions:n,totals:{create:0,keep:0,replace:0,delete:n.length-r.length,drifted:0,blocked:r.length},gates:{apiRequests:{estimate:0,partial:o.length>0,...o.length>0?{notCounted:o}:{}},storage:{bytes:0},emails:[]},...r.length>0?{refusal:`${r.map(a=>`${a.resource}: ${a.refusal??""}`).join(" ")} Nothing was deleted.`,...s.length>0?{refusalCodes:s}:{}}:{},...e.previews===void 0?{quick:!0}:{},...e.warnings!==void 0&&e.warnings.length>0?{warnings:[...e.warnings]}:{}}}function $c(e){return e.actions.some(t=>t.action!=="keep"&&t.action!=="drifted")}function zg(e){let t=e.drift;if(t!==void 0&&(t.differs||t.unread!==void 0))return!0;let n=t!==void 0;return e.actions.some(r=>r.action==="drifted"||!(n&&r.action==="keep")&&r.objects.some(s=>(s.gone??0)>0||(s.changed??0)>0))}function Ac(e){let t=e.kind==="mask",n=e.kind==="users";return e.objects.map(r=>{let s=[r.wouldCreate!==void 0?`${r.atMost===!0?"at most ":""}${r.wouldCreate} `+(t?"to mask":n?"to set up":"to write"):"",r.present!==void 0&&r.present>0?`${r.present} ${t?"masked":n?"set up":"in the org"}`:"",(r.gone??0)>0?`${r.gone} gone`:"",(r.changed??0)>0?`${r.changed} changed`:""].filter(Boolean);return s.length>0?`${r.object} ${s.join(", ")}`:""}).filter(Boolean).join("; ")}var v$={apply:"an apply now",destroy:"a destroy now"};function k$(e){if(e.kind!=="users"||!je.has(e.action)||e.users===void 0)return[];let t=e.users.map(s=>` ${s.username}: `+(s.changes.length>0?s.changes.map(St).join(", "):"as the file says already: nothing to do")),n=e.users.filter(s=>(s.emailsToPeople??0)>0),r=e.gates?.emailsToPeople??0;if(r>0){let s=n.map(o=>o.username).join(", ");t.push(r===1?` Salesforce sends 1 email to a person: the confirmation of ${s}'s address asked back, a system email, which leaves under System email only too`:` Salesforce sends ${r} emails to people: the confirmation of each address asked back (${s}), system emails, which leave under System email only too`)}return t}function ho(e,t="apply",n={}){let r=e.org.kind==="sandbox"?ke(e.org.host):void 0,s=e.org.alias??e.org.organizationId,o=e.state.refreshed,i=[`plan of ${e.env} on ${s} (${e.org.kind}${r!==void 0?` ${r}`:""}, ${e.org.organizationId})`,e.state.found?`state: kept on this machine, serial ${e.state.serial??0}`:o!==void 0?`state: ${yi(s,o)}`:"state: none on this machine"];for(let h of e.actions){let g=Ac(h);i.push(` ${h.action.padEnd(8)} ${h.resource}${g?` ${g}`:""}`),i.push(` ${h.why}`),i.push(...k$(h));for(let m of h.draws??[])i.push(` ${m.lookup} draws its parents from `+(m.parents!==void 0?`the ${m.parents} ${m.object} record(s) ${m.from} created`:`the ${m.object} records ${m.from} creates first`));for(let m of h.notes??[])i.push(` ${m}`);h.refusal!==void 0&&i.push(` refused: ${h.refusal}`)}let{totals:a}=e;i.push(`totals: ${a.create} to create, ${a.replace} to replace, ${a.delete} to delete, ${a.keep} kept, ${a.drifted} drifted, ${a.blocked} blocked`);let{apiRequests:c,storage:d,emails:u}=e.gates,l=(h,g)=>h!==void 0?`, ${h} left`:g!==void 0?` (left: ${g})`:"";i.push(`API requests: about ${c.estimate}`+l(c.leftToday?.toString(),c.unread)+(c.partial?`; not counted: ${(c.notCounted??[]).join(", ")}`:"")),i.push(`data storage: about ${kt(d.bytes/1048576)} MB`+l(d.left!==void 0?`${kt(d.left/1048576)} MB`:void 0,d.unread));for(let h of u)i.push(`emails (${h.limit}): ${h.emails}`+(h.left!==void 0?`, ${h.left} left today`:""));let f=e.gates.emailsToPeople;f!==void 0&&f.count>0&&i.push(`emails to people: ${f.count}, `+(f.accepted?"accepted by the line (--accept-user-emails)":"which the line accepts with --accept-user-emails")),i.push(...Nu(e)),n.audits!==void 0&&i.push(n.audits);for(let h of e.warnings??[])i.push(`warning: ${h}`);return e.refusal!==void 0&&i.push(`${v$[t]} would be refused: ${e.refusal}`),i}import{existsSync as Oc,readFileSync as jc}from"node:fs";import{join as b$}from"node:path";function mo(e){return e.slice(0,15)}function go(e){let t=new Map,n=new Set;for(let{objectApiName:r,ids:s}of e){let o=t.get(r)??[];for(let i of s)n.has(mo(i))||(n.add(mo(i)),o.push(i));t.set(r,o)}return t}function E$(e,t,n){let r=e.runId!==void 0?b$(n.journalDir,Ue,`${e.runId}.ndjson`):void 0;if(r!==void 0&&Oc(r)){let i=Pd(jc(r,"utf8"));if(i!==void 0)return{created:go(i.created)}}if(e.summary===void 0)return{refusal:"its run keeps no record of what it created"};let s=n.store.fileOf(t.organizationId,t.env,e.summary);if(!Oc(s))return{refusal:"its run keeps no record of what it created"};let o=Wt(jc(s,"utf8"));return o.result.objectResults.some(i=>i.truncated===!0)?{refusal:"its summary names the first of the records it created alone, and its run file is gone"}:{created:go(o.result.objectResults.map(i=>({objectApiName:i.objectApiName,ids:i.createdIds})))}}async function R$(e,t,n){if(e.summary===void 0)return{refusal:"its run keeps no summary"};let r=n.store.fileOf(t.organizationId,t.env,e.summary);if(!Oc(r))return{refusal:"its run keeps no summary"};let s=await Ir(r,jc(r,"utf8"),t.target,Or(n.journalDir));if("refusal"in s)return{refusal:`its summary ${s.refusal}`};let{result:o}=s.summary,i=yd({idRemapTable:o.remapTable,idRemapExisting:[...o.existingSourceIds,...o.updatedSourceIds],idRemapCreated:o.createdByObject});return{created:go([...i].reverse().map(a=>({objectApiName:a.objectApiName,ids:[...a.ids].reverse()})))}}async function S$(e,t,n){if(rs(e.sas)===void 0||e.sas===void 0)return{refusal:"its run names no sas"};let r=n.store.sasOf(t.organizationId,t.env,e.sas),s=new Ke,o=(await mn(r,s)).find(c=>mo(c)===mo(t.organizationId));if(o===void 0)return{refusal:"its sas holds no mapping of a load into this org"};let i=await new Dr(r,{orgId:o,guard:s}).recorded();if(i?.created===void 0)return{refusal:"its sas holds no load that says which records it created"};let a=du(i);return{created:go([...a].reverse().map(c=>({objectApiName:c.objectApiName,ids:[...c.ids].reverse()})))}}async function Ic(e,t,n,r){let s=e?.resources[t];if(s===void 0||s.status==="destroyed")return{refusal:`${t} has not created its records in this org yet`};if(s.status!=="applied")return{refusal:`${t} is ${s.status}, not applied whole: apply it again first`};let o=s.runs.at(-1);if(o===void 0||o.takenBack===!0)return{refusal:`${t} holds no run whose records are in the org`};let i=await Cc(o,n,r);return"refusal"in i?{refusal:`${t}: ${i.refusal}`}:i}async function Cc(e,t,n){switch(e.script){case"sandforge-seed":return E$(e,t,n);case"sandforge-clone":return R$(e,t,n);case"sandforge-frozen":return S$(e,t,n);default:return{refusal:`its records are kept by ${Ne(e.script)}, which this SandForge reads not`}}}function $$(e,t){let n=e.relation.parentObject,r=`${e.relation.childObject}.${e.relation.lookupField}`,s=[...t.get(n)??[]],o=kr.maxExistingParents;if(s.length===0){let i=[...t.keys()].filter(a=>(t.get(a)??[]).length>0);return{refusal:`the relation on ${r} draws its parents from the ${n} records ${e.from} created, and it created none: it created ${i.join(", ")||"no record"}`}}return e.limit!==void 0?{ids:s.slice(0,e.limit)}:s.length>o?{refusal:`the relation on ${r} draws its parents from the ${s.length} ${n} records ${e.from} created, more than the ${o} a relation's parents hold: give the relation a limit, and its parents are the first ${o} or fewer`}:{ids:s}}async function yo(e,t,n,r,s){let o={ids:new Map,draws:[],refusals:[]};if(e.kind!=="seed")return o;let i=new Map;for(let a of e.run.draws??[]){let c={lookup:`${a.relation.childObject}.${a.relation.lookupField}`,from:a.from,object:a.relation.parentObject};if(n.has(a.from)){o.draws.push(c);continue}let d=i.get(a.from);if(d===void 0&&(d=await Ic(t,a.from,r,s),i.set(a.from,d)),"refusal"in d){o.draws.push(c),o.refusals.push(`the relation on ${c.lookup} draws its parents from ${a.from}, whose records cannot be read: ${d.refusal}`);continue}let u=$$(a,d.created);if("refusal"in u){o.draws.push(c),o.refusals.push(u.refusal);continue}o.ids.set(a.at,u.ids),o.draws.push({...c,parents:u.ids.length})}return o}function ve(e){return Sd.some(t=>xe(t)===e)}function Bg(e,t,n){let r=e===0||e===3||e===4||ve(e),s=t??(r?void 0:bu(n));return s!==void 0&&s!==""?s.slice(0,4e3):void 0}function j$(e){return Ci(e).map(t=>{let n=[t.keptChanged>0?`${t.keptChanged} changed since the run, kept`:"",t.keptDependents>0?`${t.keptDependents} kept for records that stay (${t.heldBy.join(", ")||"records that stay"})`:"",t.refused>0?`${t.refused} refused`:"",(t.notVisible??0)>0?`${t.notVisible} not visible to the user`:"",(t.notReached??0)>0?`${t.notReached} not reached`:"",...t.reasons].filter(Boolean);return{object:t.objectApiName,created:0,refused:t.refused,deleted:t.deleted,kept:t.keptChanged+t.keptDependents+t.refused,...n.length>0?{reason:n.join("; ").slice(0,2e3)}:{}}})}function I$(e){return(e?.objects??[]).map(t=>({object:t.object,created:t.created,refused:t.refused,deleted:0,kept:0,...t.errors.length>0?{reason:t.errors.slice(0,5).join("; ").slice(0,2e3)}:{}}))}function C$(e){try{return typeof JSON.parse(e)?.refused?.code=="string"}catch{return!1}}function Je(e,t,n){if(!(t.trim()===""||C$(t)))try{return e(t)}catch(r){if(r instanceof de){n(` ${r.message}`);return}throw r}}function Pc(e,t,n,r){let s=rs(e.sas);if(s!==void 0){let o=n.store.fileOf(t.organizationId,t.env,Et(s,e.n));return cn(o)?o:void 0}if(e.summary!==void 0){let o=n.store.fileOf(t.organizationId,t.env,e.summary);if(cn(o))return o}if(e.runId!==void 0&&cn(vo(n.journalDir,Ue,`${e.runId}.ndjson`)))return e.runId;if(e.script===V&&r!==void 0){let o=n.store.fileOf(t.organizationId,t.env,Et(r,e.n));return cn(o)?o:void 0}}var D$=/^run-([1-9]\d{0,5})\.json$/,P$=6e4,N$=p.object({run:p.number().int().positive(),startedAt:p.string(),removals:p.array(p.object({status:p.string()}).loose()).optional()}).loose();function Ug(e,t,n,r){let s=f=>{if(f===void 0)return;let h=r.store.fileOf(n.organizationId,n.env,f),g;try{g=Dc(h,"utf8")}catch{return}let m=Pn(g);return m!==void 0?{run:m,file:h}:void 0},o=s(e.summary);if(o!==void 0)return o;let i=new Set(t.flatMap(f=>f.n===e.n?[]:[s(f.summary)?.run??0])),a=vo(r.journalDir,"users",re(n.organizationId)),c;try{c=A$(a)}catch{c=[]}let d=Date.parse(e.startedAt)-P$,u=c.flatMap(f=>{let h=Number(D$.exec(f)?.[1]??0);if(h===0||i.has(h))return[];let g=vo(a,f);try{let m=N$.safeParse(JSON.parse(Dc(g,"utf8"))),w=m.success&&m.data.removals?.at(-1)?.status==="success";return m.success&&m.data.run===h&&!w&&Date.parse(m.data.startedAt)>=d?[{run:h,file:g}]:[]}catch{return[]}}),[l]=u;return l!==void 0&&u.length===1?{...l,adopted:!0}:u.length===0&&(e.exitCode===1||e.exitCode===2)?{none:!0}:{unknown:u.length===0?`its run ${e.n} stopped before it answered, and no run of ${B("users")} began on this machine after it was launched: which it was, nobody can say`:`its run ${e.n} stopped before it answered, and ${u.length} runs of ${B("users")} began on this machine after it was launched (${u.map(f=>f.run).join(", ")}): which is its, nobody can say. ${B("users")} remove --run <n> takes one back`}}function bo(e,t,n){let r;for(let s of[...e?.runs??[]].reverse()){if(s.takenBack===!0)continue;let o=Ug(s,e?.runs??[],t,n);if("run"in o)return{run:o.run,...r!==void 0?{unknown:r}:{}};"unknown"in o&&(r??=o.unknown)}return r!==void 0?{unknown:r}:{}}async function Nc(e,t,n,r){let s={organizationId:t.org.organizationId,env:t.env},o=t.resources[n.resource];if(o===void 0)throw new L("invalid",`The state holds no resource ${n.resource} to take back`);if(o.kind==="mask")return T$(e,t,n);let i=await e.store.update(t,l=>ai(l,n.resource)),a=[],c=!1,d=!1,u=!1;for(let l of[...o.runs].reverse()){if(l.takenBack===!0)continue;let f;if(o.kind==="users"){if(u){i=await e.store.update(i,S=>vn(S,n.resource,l.n));continue}let E=Ug(l,o.runs,s,e);if("unknown"in E){e.say(`${n.resource}: run ${l.n} is not taken back: ${E.unknown}`),c=!0;continue}f="run"in E?E.file:void 0}else f=Pc(l,s,e,n.resource);if(f===void 0)continue;e.say(`${n.resource}: taking back run ${l.n}`);let h=xp(o.kind,{target:n.target.alias,subject:f,includeChanged:n.includeChanged,acceptAutomation:n.acceptAutomation,sweep:n.sweep,checkpointStore:ie(e.journalDir)}),g=await e.runner(h.script,h.args,r),m=Je(E=>Lp(o.kind,E),g.stdout,e.say),w=Ci(m).reduce((E,S)=>E+S.deleted,0);d||=m!==void 0?w>0:g.code!==1&&g.code!==2;let y=ve(g.code),v=g.code===0||g.code===3,b=y?"destroying":v?g.code===3?n.ends.left:n.ends.whole:o.status,k=Bg(g.code,void 0,g.stderr);if(a.push({resource:n.resource,action:n.action,phase:"remove",run:l.n,script:h.script,exitCode:g.code,status:b,...l.summary!==void 0?{summary:l.summary}:{},objects:j$(m),...m!==void 0?{answer:m}:{},...k!==void 0?{refusal:k}:{}}),g.code===3&&(c=!0),g.code===0)i=await e.store.update(i,E=>vn(E,n.resource,l.n)),u=o.kind==="users";else if(o.kind==="users"&&v)break;if(!v)return y||(i=await e.store.update(i,E=>Mt(E,{resource:n.resource,status:o.status}))),{whole:!1,code:y?g.code:1,wrote:d,steps:a,state:i}}return i=await e.store.update(i,l=>Mt(l,{resource:n.resource,status:c?n.ends.left:n.ends.whole})),{whole:!c,code:c?3:0,wrote:d,steps:a,state:i}}async function T$(e,t,n){let r=t.resources[n.resource];if(r===void 0)throw new L("invalid",`The state holds no resource ${n.resource} to take back`);let s=await e.store.update(t,u=>ai(u,n.resource)),o=e.store.sasOf(t.org.organizationId,t.env,Kt(n.resource)),i=r.runs.at(-1),a=(u,l,f)=>({resource:n.resource,action:n.action,phase:"remove",run:i?.n??1,script:"sandforge-dataops",exitCode:l,status:u,objects:(i?.objects??[]).map(h=>({object:h.objectApiName,created:0,refused:0,deleted:0,kept:0,masked:h.masked??0,reason:f}))});e.say(`${n.resource}: deleting its store ${o}`);let c;try{c=await of(o)}catch(u){let l=u instanceof Error?u.message:String(u);return e.say(`${n.resource}: ${l}`),s=await e.store.update(s,f=>Mt(f,{resource:n.resource,status:r.status})),{whole:!1,code:1,wrote:!1,steps:[a(r.status,1,l)],state:s}}e.say(af(n.resource,c));for(let u of r.runs)u.takenBack!==!0&&(s=await e.store.update(s,l=>vn(l,n.resource,u.n)));s=await e.store.update(s,u=>Mt(u,{resource:n.resource,status:n.ends.whole}));let d=c.snapshots.length>0?`snapshot${c.snapshots.length===1?"":"s"} ${c.snapshots.join(", ")}`:"its store";return{whole:!0,code:0,wrote:!1,steps:[a(n.ends.whole,0,`left masked, as destroy leaves a masking; ${d} deleted`)],state:s}}var x$=new Set(["sandforge-seed","sandforge-clone","sandforge-dataops","sandforge-frozen","sandforge-users","sandforge-checkpoint"]);function yt(e,t){return t&&x$.has(e.script)?{...e,args:[...e.args,"--accept-emails"]}:e}function L$(e,t){let n=new Map(e.actions.map(i=>[i.resource,i])),r=new Set(qe(t).map(([i])=>i)),s=gt(t,e.actions.filter(i=>(i.action==="delete"||i.action==="replace"&&!$t(i.kind))&&r.has(i.resource)).map(i=>i.resource)).map(i=>({phase:"remove",resource:i,action:n.get(i)?.action??"delete"})),o=e.actions.filter(i=>i.action==="create"||i.action==="replace").map(i=>({phase:"run",resource:i.resource,action:i.action}));return[...s,...o]}function Kg(e,t,n){if(ve(e))return{status:"applying",counts:e,stops:!0};if(e===0&&t!==void 0){let r=t.created;return n!==void 0&&r!==n?{status:"partial",counts:3,stops:!1,short:`it created ${r} record(s) of the ${n} its dry run counted`}:{status:"applied",counts:0,stops:!1}}return e===3?{status:"partial",counts:3,stops:!1}:e===4?{status:"partial",counts:4,stops:!0}:{status:"failed",counts:1,stops:!0}}function F$(e,t){return t===void 0?e:e.status==="partial"&&e.short===void 0&&"short"in t?t.short===void 0||t.unstable?e:{...e,short:`its verification found ${t.short}`}:e.status!=="applied"?e:"unread"in t?{...e,short:`not verified: ${t.unread}`}:t.unstable?{status:"partial",counts:4,stops:!0,short:`its verification is unstable: ${t.short??""}`}:t.short===void 0?e:{status:"partial",counts:3,stops:!1,short:`its verification found ${t.short}`}}async function M$(e,t,n){let{resource:r,n:s,where:o,target:i,templateFile:a,dry:c,signal:d}=n,u=o.env,l=c!==void 0&&"answer"in c?c.answer:void 0,f=l===void 0||n.readTooEarly?void 0:Yt(l).created,h=await e.orgNow();if(r.kind==="seed"){let P=_r(u,r.name,s),D=r.run.seed??(l?.tool==="sandforge-seed"?l.seed:void 0),x=await e.store.update(t,De=>Rt(De,{resource:r.name,kind:"seed",fingerprint:r.fingerprint,dependsOn:r.dependsOn,run:{script:"sandforge-seed",runId:P,...D!==void 0?{seed:D}:{},startedAt:h}})),G=yt(At(r,{target:i.alias,templateFile:a,runId:P,summaryFile:"",...D!==void 0?{seed:D}:{}}),n.acceptEmails),K=await e.runner(G.script,G.args,d),O=Je(Wt,K.stdout,e.say),M=O!==void 0?cs(O):void 0,ce=(M?.created??0)>0||cn(vo(e.journalDir,Ue,`${P}.ndjson`)),Z=O!==void 0?await e.store.writeFile(o.organizationId,u,oe(r.name,s),K.stdout).then(()=>oe(r.name,s)):void 0;return{state:x,script:G.script,code:K.code,...M!==void 0?{count:M}:{},...O!==void 0?{answer:O}:{},...Z!==void 0?{summary:Z}:{},wrote:ce,...f!==void 0?{planned:f}:{},...M?.refusal!==void 0?{answered:M.refusal}:{},stderr:K.stderr}}if(r.kind==="frozen")return z$(e,t,n,h,f);if(r.kind==="mask")return _$(e,t,n,h);if(r.kind==="users")return B$(e,t,n,h);if(r.kind==="replay")return U$(e,t,n,h,f);let g=oe(r.name,s),m=await e.store.prepareFile(o.organizationId,u,g),w=await e.store.update(t,P=>Rt(P,{resource:r.name,kind:"forge",fingerprint:r.fingerprint,dependsOn:r.dependsOn,run:{script:"sandforge-clone",summary:g,startedAt:h}})),y=po(c),v=r.kind==="forge"&&r.run.records!==void 0?Zr(e.journalDir,o.organizationId,u,r.name):void 0,b=yt(At(r,{target:i.alias,templateFile:a,runId:"",summaryFile:m,...y!==void 0?{maxTotal:y}:{},...v!==void 0?{rootsPlanFile:v}:{}}),n.acceptEmails),k=await e.runner(b.script,b.args,d);v!==void 0&&O$(v,{force:!0});let E=cn(m)?Dc(m,"utf8"):void 0,S=Je($n,E??"",e.say)??Je($n,k.stdout,e.say),$=S!==void 0?es(S):void 0,j=$!==void 0?$.created>0:E!==void 0,A;if(k.code===0&&E!==void 0&&($?.created??0)>0){e.say(`${r.name}: verifying run ${s}`);let P=await e.runner(b.script,al({summary:m,target:i.alias,source:r.source.alias}),d),D=P.stdout.trim()===""?void 0:Je(fl,P.stdout,e.say);if(D!==void 0){let x=hl(D);A={unstable:D.result.verdict==="unstable",...x!==void 0?{short:x}:{}}}else P.code!==0&&(A={unread:`its verification ended ${P.code} without an answer`})}return{state:w,script:b.script,code:k.code,...$!==void 0?{count:$}:{},...S!==void 0?{answer:S}:{},...E!==void 0?{summary:g}:{},wrote:j,...f!==void 0?{planned:f}:{},...A!==void 0?{verified:A}:{},...S?.error!==void 0?{answered:S.error}:{},stderr:k.stderr}}async function z$(e,t,n,r,s){let{resource:o,n:i,where:a,target:c,templateFile:d,dry:u,signal:l}=n,f=await e.store.update(t,S=>Rt(S,{resource:o.name,kind:"frozen",fingerprint:o.fingerprint,dependsOn:o.dependsOn,run:{script:"sandforge-frozen",sas:rt(o.name),startedAt:r}})),h=po(u),g=yt(At(o,{target:c.alias,templateFile:d,runId:"",summaryFile:"",replace:n.replace,acceptAutomation:n.acceptAutomation,...h!==void 0?{maxTotal:h}:{}}),n.acceptEmails),m=await e.runner(g.script,g.args,l),w=Je(ts,m.stdout,e.say),y=w!==void 0?Cn(w):void 0;y?.refusal!==void 0&&e.say(`${o.name}: ${y.refusal}`);let v=w===void 0?ve(m.code):(y?.created??0)>0||Tl(w),b=w!==void 0?await e.store.writeFile(a.organizationId,a.env,oe(o.name,i),m.stdout).then(()=>oe(o.name,i)):void 0,k=w?.verdict,E=k!==void 0?vi(k):m.code===0&&(y?.created??0)>0?{unread:"the load chained no verification"}:void 0;return{state:f,script:g.script,code:m.code,...y!==void 0?{count:y}:{},...w!==void 0?{answer:w}:{},...b!==void 0?{summary:b}:{},wrote:v,...s!==void 0?{planned:s}:{},...E!==void 0?{verified:E}:{},...n.replace&&w!==void 0&&ns(w)?{tookBackEarlier:!0}:{},...y?.refusal!==void 0?{answered:y.refusal}:{},stderr:m.stderr}}async function _$(e,t,n,r){let{resource:s,n:o,where:i,target:a,templateFile:c,signal:d}=n,u=await e.store.update(t,v=>Rt(v,{resource:s.name,kind:"mask",fingerprint:s.fingerprint,dependsOn:s.dependsOn,run:{script:"sandforge-dataops",startedAt:r}})),l=await e.store.prepareFolder(i.organizationId,i.env,Kt(s.name)),f=yt(At(s,{target:a.alias,templateFile:c,runId:"",summaryFile:"",store:l}),n.acceptEmails),h=await e.runner(f.script,f.args,d),g=Je(ss,h.stdout,e.say),m=g!==void 0?Dn(g):void 0;m?.refusal!==void 0&&e.say(`${s.name}: ${m.refusal}`);let w=m!==void 0?m.objects.some(v=>v.masked>0):ve(h.code),y=g!==void 0?await e.store.writeFile(i.organizationId,i.env,oe(s.name,o),h.stdout).then(()=>oe(s.name,o)):void 0;return{state:u,script:f.script,code:h.code,...g!==void 0?{answer:g}:{},...y!==void 0?{summary:y}:{},wrote:w,...m!==void 0?{masking:m}:{},...m?.refusal!==void 0?{answered:m.refusal}:{},stderr:h.stderr}}function q$(e){let t;try{t=JSON.parse(e)}catch{return}if(vt.safeParse(t).success)return;let n=br.safeParse(t);return n.success?(n.data.refusals??[]).map(r=>r.message):void 0}async function B$(e,t,n,r){let{resource:s,n:o,where:i,target:a,templateFile:c,signal:d}=n,u=await e.store.update(t,b=>Rt(b,{resource:s.name,kind:"users",fingerprint:s.fingerprint,dependsOn:s.dependsOn,run:{script:H,startedAt:r}})),l=yt(At(s,{target:a.alias,templateFile:c,runId:"",summaryFile:"",acceptAutomation:n.acceptAutomation,acceptUserEmails:n.acceptUserEmails,...n.replacesRun!==void 0?{replacesRun:n.replacesRun}:{}}),n.acceptEmails),f=await e.runner(l.script,l.args,d),h=q$(f.stdout),g=h===void 0?Je(Vt,f.stdout,e.say):void 0,m=g!==void 0?ds(g):void 0,w=g!==void 0?g.users.some(b=>b.done.length>0):h===void 0&&f.code!==1&&f.code!==2,y=g!==void 0?await e.store.writeFile(i.organizationId,i.env,oe(s.name,o),f.stdout).then(()=>oe(s.name,o)):void 0,v=m?.refusal??(h!==void 0?h.join(" "):void 0);return{state:u,script:l.script,code:f.code,...m!==void 0?{count:m}:{},...g!==void 0?{answer:g}:{},...y!==void 0?{summary:y}:{},wrote:w,...n.replacesRun!==void 0&&g!==void 0?{tookBackEarlier:!0}:{},...v!==void 0&&v!==""?{answered:v}:{},stderr:f.stderr}}async function U$(e,t,n,r,s){let{resource:o,n:i,where:a,target:c,templateFile:d,dry:u,signal:l}=n,f=await e.store.update(t,k=>Rt(k,{resource:o.name,kind:"replay",fingerprint:o.fingerprint,dependsOn:o.dependsOn,run:{script:V,startedAt:r}})),h=po(u),g=yt(At(o,{target:c.alias,templateFile:d,runId:"",summaryFile:"",replace:n.replace,acceptAutomation:n.acceptAutomation,checkpointStore:ie(e.journalDir),...h!==void 0?{maxTotal:h}:{}}),n.acceptEmails),m=await e.runner(g.script,g.args,l),w=Je(os,m.stdout,e.say),y=w!==void 0?is(w):void 0,v=w!==void 0?(y?.created??0)>0:ve(m.code),b=w!==void 0?await e.store.writeFile(a.organizationId,a.env,oe(o.name,i),m.stdout).then(()=>oe(o.name,i)):void 0;return{state:f,script:g.script,code:m.code,...y!==void 0?{count:y}:{},...w!==void 0?{answer:w}:{},...b!==void 0?{summary:b}:{},wrote:v,...s!==void 0?{planned:s}:{},...n.replace&&w!==void 0&&as(w)?{tookBackEarlier:!0}:{},...y?.refusal!==void 0?{answered:y.refusal}:{},stderr:m.stderr}}function K$(e,t){let n=Kg(e,void 0,void 0);if(e!==0)return n;let r=(t?.objects??[]).reduce((s,o)=>s+o.notMasked,0);return t?.short!==void 0||r>0?{status:"partial",counts:3,stops:!1,short:t?.short??`${r} record(s) still hold their original values: the next apply masks them again`}:{status:"applied",counts:0,stops:!1}}function W$(e){return(e?.objects??[]).map((t,n)=>({object:t.object,created:0,refused:t.refused,deleted:0,kept:0,masked:t.masked,...n===0&&e?.snapshotId!==void 0?{reason:`snapshot ${e.snapshotId} of the values it wrote over, taken first, kept on this machine until destroy deletes it`}:{}}))}async function V$(e,t,n,r,s){if(n.kind==="frozen"){let i=await e.store.prepareFolder(r.organizationId,r.env,rt(n.name));return{payload:Jt(n,{sasDir:i})}}if(n.kind==="replay"){let i=n.checkpoint.read;return i===void 0||"refusal"in i?{refusal:i?.refusal??"its checkpoint was not resolved: plan again"}:{payload:{command:"replay",checkpoint:{id:i.checkpointId,organizationId:i.organizationId}}}}if(n.kind!=="seed"||(n.run.draws??[]).length===0)return{payload:Jt(n,{})};let o=await yo(n,t,new Set,{...r,target:s.alias},{store:e.store,journalDir:e.journalDir});return o.refusals.length>0?{refusal:o.refusals.join(" ")}:{payload:Jt(n,{drawn:o.ids})}}function _g(e,t,n){let r=e;for(let s of t.actions){if(s.action!=="keep"&&s.action!=="drifted")continue;let o=r.resources[s.resource],i=n.get(s.resource)?.fingerprint;o===void 0||i===void 0||o.recovered===!0||o.status==="destroyed"||o.fingerprint===i||(r={...r,resources:{...r.resources,[s.resource]:{...o,fingerprint:i}}})}return r}function ko(e){return e===0?"success":ve(e)?"cancelled":e===1?"failure":"partial"}async function Wg(e,t){let{plan:n,target:r,resolved:s}=t,o=s.checked.file.name,i=(g,m=t.state,w=[])=>({result:{plan:n,steps:[],status:"failure",refusal:g,...w.length>0?{refusalCodes:[...w]}:{},state:{serial:m?.serial??0}},exitCode:1});if(n.refusal!==void 0)return i(n.refusal,t.state,n.refusalCodes);let a=L$(n,t.state),c=n.checkpoints?.find(g=>g.step==="before"),d=n.checkpoints?.find(g=>g.step==="after");if(a.length===0&&d===void 0)return e.say("nothing to do: the org holds the environment as the file describes it"),{result:{plan:n,steps:[],status:"success",state:{serial:t.state?.serial??0}},exitCode:0};let u=Qe(e.locksDir,r.organizationId,{operation:"apply",env:o,alias:r.alias},e.lockOptions);if("busy"in u){let g=nt(u.busy);return i(g.message,t.state,[g.code])}let l=new AbortController,f,h=(e.onStop??Ge)(g=>{f=g,e.say(`
|
|
148
|
+
stopped by ${g}: the step under way stops before its next call to the org, and the state keeps what it wrote; apply again takes up from there`),l.abort()});try{let g;try{let O=await e.store.read(r.organizationId,o);if(O===void 0!=(t.state===void 0)||O!==void 0&&(O.serial!==t.state?.serial||O.lineage!==t.state.lineage))return i(`The state of ${o} on ${r.alias} changed since the plan (another apply or destroy ran, or a cache put back another state). Nothing was written: plan again.`,O,[Gr]);g=O??Br({env:o,org:{organizationId:r.organizationId,kind:r.kind,username:r.username,alias:r.alias,...r.host!==void 0?{host:r.host}:{}},fileDigest:s.digest,sandforgeVersion:e.sandforgeVersion})}catch(O){if(O instanceof L)return i(O.message,t.state,[tt(O).code]);throw O}g={...wu(g,r.host),file:{digest:s.digest},sandforgeVersion:e.sandforgeVersion};let m={organizationId:r.organizationId,env:o},w=[],y=[],v=[],b=new Map,k=!1,E,S=new Map(s.resources.map(O=>[O.name,O])),$=new Set,j=0,A=[],P={alias:r.alias,kind:r.kind},D=Wr(s.checked.file);if(c!==void 0&&a.length>0){let O=await mi(e,{org:P,step:"before",name:c.name,...D},l.signal);if(A.push(O.result),O.checkpoint===void 0){let ce=f!==void 0?xe(f):ve(O.result.exitCode)?O.result.exitCode:1;return{result:{plan:n,steps:[],checkpoints:A,status:ko(ce),refusal:`The checkpoint before the first write, '${c.name}', was not taken (${O.result.refusal??`exit ${O.result.exitCode}`}). Nothing was written.`,state:{serial:g.serial}},exitCode:ce}}let M=O.checkpoint;g=await e.store.update(g,ce=>et(ce,"before",M))}_g(g,n,S)!==g&&(g=await e.store.update(g,O=>_g(O,n,S)));try{for(let O of a){if(j+=1,E!==void 0||f!==void 0){y.push({resource:O.resource,why:"the apply was stopped before it"});continue}let M=S.get(O.resource),ce=(M?.dependsOn??[]).filter(he=>b.has(he));if(O.phase==="run"&&ce.length>0){y.push({resource:O.resource,why:`it depends on ${ce.map(he=>`${he} (${b.get(he)??"not whole"})`).join(", ")}`});continue}let Z=jr(e.locksDir,r.organizationId,e.lockOptions);if(Z!==void 0){e.say(Sn(Z).message),v.push(1),y.push({resource:O.resource,why:Sn(Z).message});break}if(O.phase==="remove"){let he=t.acceptAutomation||s.checked.file.resources[O.resource]?.accept?.automation===!0,ne=await Nc(e,g,{resource:O.resource,action:O.action,target:r,includeChanged:!1,sweep:!1,acceptAutomation:he,ends:{whole:"destroyed",left:"partial"}},l.signal);if(g=ne.state,w.push(...ne.steps),k||=ne.wrote,ve(ne.code)){E=ne.code;continue}if(v.push(ne.code),ne.code!==0&&ne.code!==3)break;continue}if(M===void 0)continue;let De=wn(g.resources[O.resource]),gr=await V$(e,g,M,m,r);if("refusal"in gr){e.say(`${O.resource}: not run, ${gr.refusal}`),v.push(1),y.push({resource:O.resource,why:gr.refusal}),b.set(O.resource,"not run");break}let mw=await e.store.writeFile(m.organizationId,o,Et(O.resource,De),`${JSON.stringify(gr.payload,null,2)}
|
|
149
|
+
`),gw=M.dependsOn.some(he=>$.has(he)),Gc=M.kind==="users"&&O.action==="replace"?bo(g.resources[O.resource],m,e).run:void 0;e.say(`${O.resource}: run ${De} (${O.action})`);let W=await M$(e,g,{resource:M,n:De,where:m,target:r,templateFile:mw,dry:t.dryRuns[O.resource],readTooEarly:gw,replace:O.action==="replace"&&$t(M.kind),acceptAutomation:t.acceptAutomation||s.checked.file.resources[O.resource]?.accept?.automation===!0,acceptEmails:t.acceptEmails===!0,acceptUserEmails:t.acceptUserEmails===!0,...Gc!==void 0?{replacesRun:Gc}:{},signal:l.signal});g=W.state,k||=W.wrote,M.kind!=="mask"&&$.add(O.resource);let Ft=W.masking,Pe=M.kind==="mask"?K$(W.code,Ft):F$(Kg(W.code,W.count,W.planned),W.verified),yw=await e.orgNow();if(g=await e.store.update(g,he=>Mt(he,{resource:O.resource,status:Pe.status,run:{endedAt:yw,exitCode:W.code,objects:Ft!==void 0?Ft.objects.map(ne=>({objectApiName:ne.object,created:0,refused:ne.refused,masked:ne.masked})):(W.count?.objects??[]).map(ne=>({objectApiName:ne.object,created:ne.created,refused:ne.refused})),...W.summary!==void 0?{summary:W.summary}:{},...Ft?.snapshotId!==void 0?{snapshotId:Ft.snapshotId}:{}}})),W.tookBackEarlier===!0)for(let he of g.resources[O.resource]?.runs??[])he.n===De||he.takenBack===!0||(g=await e.store.update(g,ne=>vn(ne,O.resource,he.n)));let yr=M.kind==="mask"?W$(Ft):I$(W.count),Qc=Bg(W.code,W.answered,W.stderr);if(w.push({resource:O.resource,action:O.action,phase:"run",run:De,script:W.script,exitCode:W.code,status:Pe.status,...W.summary!==void 0?{summary:W.summary}:{},objects:Pe.short!==void 0&&yr[0]!==void 0?[{...yr[0],reason:Pe.short},...yr.slice(1)]:yr,...W.answer!==void 0?{answer:W.answer}:{},...Qc!==void 0?{refusal:Qc}:{}}),Pe.short!==void 0&&e.say(`${O.resource}: ${Pe.short}`),ve(W.code)){E=W.code,e.say(M.kind==="mask"?`${O.resource}: its masking was stopped; the state keeps it applying, and its store the snapshot it took first: apply again masks what its condition selects`:M.kind==="users"?`${O.resource}: its run was stopped; the state keeps it applying, and the run file of sandforge users what it changed: apply again converges from it`:`${O.resource}: its run was stopped; the state keeps it applying, and its ${M.kind==="forge"?"summary what it created":M.kind==="frozen"?"sas what it loaded":M.kind==="replay"?"payload the checkpoint it replays":"run file what it wrote"}: apply again takes it back and runs it whole`);continue}if(v.push(Pe.counts),Pe.status!=="applied"&&b.set(O.resource,Pe.status),Pe.stops)break}}catch(O){let M=`the apply stopped on an error: ${O instanceof Error?O.message:String(O)}`;e.say(M),v.push(1);for(let ce of a.slice(j))y.push({resource:ce.resource,why:M})}let x=g.checkpoints?.after;if(k&&x!==void 0&&f===void 0){let O=await Bt(e,{org:P,checkpoint:x,why:"taken before this apply wrote"},l.signal);A.push(O),g=await e.store.update(g,M=>et(M,"after",void 0))}let G=f===void 0&&E===void 0&&hn(v)===0;if(d!==void 0&&G){let O=await mi(e,{org:P,step:"after",name:d.name,...D},l.signal);A.push(O.result);let M=O.checkpoint;M!==void 0?g=await e.store.update(g,ce=>et(ce,"after",M)):ve(O.result.exitCode)?E=O.result.exitCode:(e.say(`the checkpoint once applied, '${d.name}', was not taken: reset has nothing to rewind to until an apply takes it, which the next one does`),v.push(1))}let K=f!==void 0?xe(f):E!==void 0?E:(()=>{let O=hn(v);return O===1&&k?3:O})();return{result:{plan:n,steps:w,...A.length>0?{checkpoints:A}:{},...y.length>0?{skipped:y}:{},status:ko(K),state:{serial:g.serial}},exitCode:K}}finally{h(),u.lock.release()}}function H$(e){return e.map(t=>{let n=t.step==="delete"?`checkpoint ${t.checkpoint??""} deleted`:`checkpoint ${t.step==="before"?"before the first write":"once applied"}`;return t.exitCode!==0?` ${n}: exit ${t.exitCode}, ${t.step==="delete"?"kept":"not taken"}: ${t.refusal??""}`:t.step==="delete"?` ${n}`:` ${n}: exit 0, taken ${t.checkpoint??""}`})}var J$=72;function Y$(e){let t=` ${e.resource} ${e.phase==="run"?"run":"removal of run"} ${e.run}: exit ${e.exitCode}, ${e.status}`;if(e.phase==="run"){let i=vt.safeParse(e.answer),a=[];if(i.success){let c=i.data.users.filter(u=>u.done.length>0).length,d=i.data.users.filter(u=>(u.refused??[]).length>0).length;a.push(`${t} User ${c} set up${d>0?`, ${d} refused`:""}`);for(let u of i.data.users)u.address==="awaiting"&&a.push(` ${u.username}: address awaiting its owner's confirmation \u2014 Salesforce sent the link to it; until it is clicked (${J$} h), the address stays .invalid`)}else a.push(t);e.refusal!==void 0&&a.push(` ${e.refusal}`);for(let c of e.objects)c.reason!==void 0&&a.push(` ${c.object}: ${c.reason}`);return a}let n=e.answer,s=[e.objects.map(i=>`${i.object} ${i.deleted} deleted`).join("; "),G$(n?.answer)].filter(Boolean),o=[`${t}${s.length>0?` ${s.join("; ")}`:""}`];e.refusal!==void 0&&o.push(` ${e.refusal}`);for(let i of Array.isArray(n?.kept)?n.kept:[])o.push(` ${i.username}: ${St(i.change)} kept, ${i.why}`);return o}var qg=[["frozen","freeze(s)"],["active","activation(s)"],["profile","profile(s)"]];function G$(e){let t=Er.safeParse(e);if(!t.success)return"";let n=new Set(qg.map(([o])=>o)),r=t.data.users.filter(o=>o.undone.some(i=>n.has(i.what)));if(r.length===0)return"";let s=qg.flatMap(([o,i])=>{let a=r.reduce((c,d)=>c+d.undone.filter(u=>u.what===o).length,0);return a>0?[`${a} ${i}`]:[]});return`User ${r.length} put back: ${s.join(", ")}`}function Q$(e){let t=e.objects.map(c=>`${c.object} ${c.created}`).join(", "),n=e.objects.reduce((c,d)=>c+d.refused,0),r=e.answer?.replay?.owners,s=typeof r?.kept=="number"?r.kept:void 0,o=typeof r?.toRunningUser=="number"?r.toRunningUser:void 0,i=(t!==""?`${t} created`:"")+(n>0?`, ${n} refused`:"")+(s!==void 0&&o!==void 0?`; ${s} records kept their owner, ${o} went to you`:""),a=[` ${e.resource} replay ${e.run}: exit ${e.exitCode}, ${e.status}`+(i!==""?` ${i}`:"")];e.refusal!==void 0&&a.push(` ${e.refusal}`);for(let c of e.objects)c.reason!==void 0&&a.push(` ${c.object}: ${c.reason}`);return a}function Tc(e,t,n=[]){let r=[""];for(let s of e.steps){if(s.script===H){r.push(...Y$(s));continue}if(s.script===V&&s.phase==="run"){r.push(...Q$(s));continue}if(s.script==="sandforge-dataops"){let i=s.objects.map(a=>s.phase==="run"?`${a.object} ${a.masked??0} masked${a.refused>0?`, ${a.refused} refused`:""}`:`${a.object} ${a.masked??0} left masked`).join("; ");r.push(` ${s.resource} ${s.phase==="run"?`masking ${s.run}: exit ${s.exitCode}`:"store deleted"}, ${s.status}${i?` ${i}`:""}`),s.refusal!==void 0&&r.push(` ${s.refusal}`);for(let a of s.objects)a.reason!==void 0&&r.push(` ${a.object}: ${a.reason}`);continue}let o=s.objects.map(i=>s.phase==="run"?`${i.object} ${i.created} created${i.refused>0?`, ${i.refused} refused`:""}`:`${i.object} ${i.deleted} deleted${i.kept>0?`, ${i.kept} kept`:""}`).join("; ");r.push(` ${s.resource} ${s.phase==="run"?"run":"removal of run"} ${s.run}: exit ${s.exitCode}, ${s.status}${o?` ${o}`:""}`),s.refusal!==void 0&&r.push(` ${s.refusal}`);for(let i of s.objects)i.reason!==void 0&&r.push(` ${i.object}: ${i.reason}`)}for(let s of e.skipped??[])r.push(` ${s.resource}: not run, ${s.why}`);return r.push(...H$(e.checkpoints??[])),e.refusal!==void 0&&r.push(`${t} refused: ${e.refusal}`),r.push(...n),r.push(`${t}: ${e.status}; state serial ${e.state.serial}`),r}var Jg=3e4,Z$=5,Vg=300,eA=ed({records:vr(td(Te(),Zc())),done:Xc(),nextRecordsUrl:Te().optional()}).loose();function Nt(e,t=Jg){let r=(e instanceof Nd?`the org did not answer within ${Math.round(t/1e3)} s`:`the org refused it: ${wd(e)}`).replace(/\s+/g," ").trim();return r.length>Vg?`${r.slice(0,Vg-1)}\u2026`:r}var Eo=class{constructor(t,n={}){this.transport=t;this.timeoutMs=n.timeoutMs??Jg}transport;sent=0;timeoutMs;get requests(){return this.sent}get timeout(){return this.timeoutMs}async get(t){return this.sent++,new Td(this.timeoutMs).withTimeout("env:audit",()=>this.transport.request({method:"GET",url:t}))}asTransport(){return{request:t=>this.get(t.url)}}async query(t,n={}){let r=n.maxPages??Z$,s=n.tooling===!0?"/tooling/query":"/query",o=Hg(await this.get(`${s}?q=${encodeURIComponent(t)}`)),i=[...o.records],a=1;for(;!o.done&&o.nextRecordsUrl!==void 0&&a<r&&o.nextRecordsUrl.startsWith("/services/data/");)o=Hg(await this.get(o.nextRecordsUrl)),i.push(...o.records),a++;return{records:i,truncated:!o.done}}};function Hg(e){let t=eA.safeParse(e);if(!t.success)throw new Error("its answer is not one a query gives");return t.data}function Ro(e,t){if(t in e)return e[t];let n=t.toLowerCase();for(let r of Object.keys(e))if(r.toLowerCase()===n)return e[r]}function le(e,t){let n=Ro(e,t);return typeof n=="string"&&n.trim()!==""?n:void 0}function lr(e,t){let n=Ro(e,t);return typeof n=="boolean"?n:void 0}function xc(e){if(typeof e!="string")return;let t=Date.parse(e.replace(/([+-]\d\d)(\d\d)$/,"$1:$2"));return Number.isFinite(t)?new Date(t).toISOString():void 0}import{randomBytes as tA}from"node:crypto";import{mkdir as nA,open as rA,readFile as sA,readdir as oA,rename as iA,rm as aA}from"node:fs/promises";import{join as fr,resolve as cA}from"node:path";var dA=448,uA=384,lA=1e4,Yg=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/,fA=/^\d{8}T\d{9}Z-00D[A-Za-z0-9]{15}\.json$/,Lc=rd.datetime({offset:!0}),pA=zo({name:Te().min(1).max(255),type:Te().min(1).max(80),cronExpression:Te().min(1).max(255).optional(),state:Te().min(1).max(40),nextFireTime:Lc.optional(),previousFireTime:Lc.optional(),owner:Te().min(1).max(255).optional()}),Gg=zo({version:nd(1),savedAt:Lc,organizationId:id,host:Te().regex(Yg),jobs:vr(pA).max(lA)});function Qg(e){return fr(cA(e),"audits")}function Xg(e){let t=e.trim().toLowerCase().replace(/\.$/,"");return Yg.test(t)?t:void 0}function hA(e,t){let n=Xg(t);if(n===void 0)throw new Error(`Not a host name: "${t}"`);return fr(Qg(e),n)}function mA(e){return`${new Date(e.savedAt).toISOString().replace(/[-:.]/g,"")}-${re(e.organizationId)}.json`}async function Zg(e,t){let n=Gg.parse(t),r=hA(e,n.host);await nA(r,{recursive:!0,mode:dA});let s=fr(r,mA(n)),o=`${s}.${process.pid}-${tA(4).toString("hex")}.tmp`,i=await rA(o,"wx",uA);try{try{await i.writeFile(`${JSON.stringify(n,null,2)}
|
|
150
|
+
`,"utf8"),await i.sync()}finally{await i.close()}await iA(o,s)}catch(a){throw await aA(o,{force:!0}),a}return s}async function ey(e,t){let n=Xg(t);if(n===void 0)return{kept:[],setAside:[],unread:`${t} is not a host name`};let r=fr(Qg(e),n),s;try{s=(await oA(r,{withFileTypes:!0})).filter(a=>a.isFile()&&a.name.endsWith(".json")).map(a=>a.name).sort()}catch(a){let c=a?.code;return c==="ENOENT"||c==="ENOTDIR"?{kept:[],setAside:[]}:{kept:[],setAside:[],unread:`${r} could not be read: ${a instanceof Error?a.message:String(a)}`}}let o=[],i=[];for(let a of s){let c=fr(r,a);if(!fA.test(a)){i.push({path:c,why:"its name is not one --save gives"});continue}let d;try{d=JSON.parse(await sA(c,"utf8"))}catch{i.push({path:c,why:"it does not read as JSON"});continue}let u=Gg.safeParse(d);if(!u.success){i.push({path:c,why:"it does not read as an inventory of this SandForge"});continue}if(u.data.host!==n){i.push({path:c,why:`it is of ${u.data.host}, not of the host its folder names`});continue}o.push({inventory:u.data,path:c})}return o.sort((a,c)=>Date.parse(c.inventory.savedAt)-Date.parse(a.inventory.savedAt)),{kept:o,setAside:i}}function ty(e,t){let n=re(t),r=e.find(o=>re(o.inventory.organizationId)!==n);if(r!==void 0)return{kept:r,refreshed:!0};let s=e[0];return s!==void 0?{kept:s,refreshed:!1}:void 0}var gA="login.salesforce.com",yA=/^([a-z0-9](?:[a-z0-9-]*[a-z0-9])?)--([a-z0-9]+)\.sandbox\.my\.salesforce\.com$/,ny=/^[a-z][a-z0-9+.-]*:\/\/[^\s/?#@]+(?:\/[^\s?#]*)?$/,wA=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/,So={listed:"a production host the file lists",myDomain:"production's My Domain",lightning:"production's Lightning host",site:"production's sites host",login:"where production orgs sign in"},$o={namedCredential:"Named Credential",remoteSite:"Remote Site",field:"Field"};function vA(e,t=[]){let n=[],r=(i,a)=>{let c=i.toLowerCase().replace(/\.$/,"");n.some(d=>d.host===c)||n.push({host:c,why:a})},s=e!==void 0?yA.exec(e.toLowerCase()):null,o;if(s?.[1]!==void 0){let i=s[1];r(`${i}.my.salesforce.com`,"myDomain"),r(`${i}.lightning.force.com`,"lightning"),r(`${i}.my.site.com`,"site")}else o=e===void 0?"the org's host is not known: production's own hosts are not deduced":`${e} is no sandbox's host of the form <domain>--<sandbox>.sandbox.my.salesforce.com: production's own hosts are not deduced`;r(gA,"login");for(let i of t)r(i,"listed");return{hosts:n,...o!==void 0?{notDeduced:o}:{}}}function kA(e){let t;try{t=new URL(e.trim())}catch{return}let n=t.hostname.toLowerCase().replace(/\.$/,"");if(!wA.test(n))return;let r=t.protocol.replace(/:$/,"").toLowerCase(),s=t.port!==""?`${n}:${t.port}`:n,o=t.pathname.startsWith("/")?t.pathname:"/",i=`${r}://${s}${o}`;if(ny.test(i))return{url:i,host:n};let a=`${r}://${s}/`;return ny.test(a)?{url:a,host:n}:void 0}function sy(e){let t=[];for(let n of e){let r=n.indexOf(".");if(r<=0)continue;let s=n.slice(0,r),o=n.slice(r+1),i=t.find(a=>a.object.toLowerCase()===s.toLowerCase());i===void 0?t.push({object:s,fields:[o]}):i.fields.some(a=>a.toLowerCase()===o.toLowerCase())||i.fields.push(o)}return t}var ry=/^[A-Za-z][A-Za-z0-9_]*$/;function oy(e=[]){return 2+sy(e).length}async function iy(e,t){let n=vA(t.host,t.productionHosts??[]),r=[],s=[],o=a=>`${a}: more than the pages read were there, and those past them were not read`;try{let a=await e.query("SELECT DeveloperName, Endpoint FROM NamedCredential",{tooling:!0});for(let c of a.records){let d=le(c,"DeveloperName"),u=le(c,"Endpoint");d!==void 0&&u!==void 0&&r.push({source:"namedCredential",name:d,raw:u})}a.truncated&&s.push(o("Named Credentials"))}catch(a){s.push(`Named Credentials: ${Nt(a,e.timeout)}`)}try{let a=await e.query("SELECT SiteName, EndpointUrl, IsActive FROM RemoteProxy",{tooling:!0});for(let c of a.records){let d=le(c,"SiteName"),u=le(c,"EndpointUrl");lr(c,"IsActive")!==!1&&d!==void 0&&u!==void 0&&r.push({source:"remoteSite",name:d,raw:u})}a.truncated&&s.push(o("Remote Sites"))}catch(a){s.push(`Remote Sites: ${Nt(a,e.timeout)}`)}for(let{object:a,fields:c}of sy(t.fields??[])){if(!ry.test(a)||!c.every(f=>ry.test(f)))continue;let d=a.toLowerCase().endsWith("__mdt"),u=d?"DeveloperName":"Name",l=d?["DeveloperName",...c]:["Id","Name",...c];try{let f=await e.query(`SELECT ${l.join(", ")} FROM ${a}`,{maxPages:1});for(let h of f.records){let g=le(h,u)??le(h,"Id")??"?";for(let m of c){let w=Ro(h,m);typeof w!="string"||w.trim()===""||r.push({source:"field",name:`${a}.${g}.${m}`,raw:w})}}f.truncated&&s.push(`${a}: more records than one page were there, and those past it were not read \u2014 a Custom Setting holds a few: is it one?`)}catch(f){s.push(`${a}: ${Nt(f,e.timeout)}`)}}let i=[];for(let a of r){let c=kA(a.raw);if(c===void 0)continue;let d=n.hosts.find(u=>u.host===c.host);d!==void 0&&i.push({source:a.source,name:a.name.slice(0,400),url:c.url,host:c.host,why:d.why})}return{productionHosts:n.hosts.map(a=>a.host),found:i,...n.notDeduced!==void 0?{notDeduced:n.notDeduced}:{},...s.length>0?{unread:s.join("; ").slice(0,2e3)}:{}}}var bA="SELECT CronJobDetail.Name, CronJobDetail.JobType, CronExpression, State, NextFireTime, PreviousFireTime, OwnerId FROM CronTrigger",EA={0:"Data Export",3:"Dashboard Refresh",4:"Reporting Snapshot",7:"Scheduled Apex",8:"Report Run",9:"Batch Job",A:"Analytics Notification"},RA=new Set(["COMPLETE","DELETED"]),ay=200,SA=/^005[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/;function $A(e){return e===void 0?"job of no type":EA[e]??`job type ${e}`}function AA(e){let t=[];for(let n=0;n<e.length;n+=ay)t.push(e.slice(n,n+ay));return t}function dn(e){return e.slice(0,15)}async function dy(e){let t;try{t=await e.query(bA)}catch(a){return{unread:Nt(a,e.timeout)}}let n=[];for(let a of t.records){let c=a.CronJobDetail,d=typeof c=="object"&&c!==null?c:{},u=le(d,"Name"),l=le(a,"State");if(u===void 0||l===void 0)continue;let f=le(a,"CronExpression"),h=xc(a.NextFireTime),g=xc(a.PreviousFireTime),m=le(a,"OwnerId");n.push({job:{name:u.slice(0,255),type:$A(le(d,"JobType")),...f!==void 0?{cronExpression:f.slice(0,255)}:{},state:l.slice(0,40),...h!==void 0?{nextFireTime:h}:{},...g!==void 0?{previousFireTime:g}:{}},...m!==void 0&&SA.test(m)?{ownerId:m}:{}})}let r=[...new Set(n.flatMap(a=>a.ownerId!==void 0&&Fc(a.job)?[dn(a.ownerId)]:[]))],s=new Map,o;try{for(let a of AA(r)){let c=a.map(l=>`'${l}'`).join(", "),d=await e.query(`SELECT Id, Username, IsActive FROM User WHERE Id IN (${c})`);for(let l of d.records){let f=le(l,"Id");f!==void 0&&s.set(dn(f),{...s.get(dn(f)),username:le(l,"Username"),active:lr(l,"IsActive")})}let u=await e.query(`SELECT UserId, IsFrozen FROM UserLogin WHERE UserId IN (${c})`);for(let l of u.records){let f=le(l,"UserId");f!==void 0&&s.set(dn(f),{...s.get(dn(f)),frozen:lr(l,"IsFrozen")})}}}catch(a){o=Nt(a,e.timeout)}return{jobs:n.map(({job:a,ownerId:c})=>{let d=c!==void 0?s.get(dn(c)):void 0;return{...a,...d?.username!==void 0?{owner:d.username.slice(0,255)}:{},...d?.active!==void 0?{ownerActive:d.active}:{},...d?.frozen!==void 0?{ownerFrozen:d.frozen}:{}}}),truncated:t.truncated,...o!==void 0?{ownersUnread:o}:{}}}function Fc(e){return!RA.has(e.state.toUpperCase())}function Ao(e){return`${e.type}\0${e.name}`}function uy(e,t){return{version:1,savedAt:t.savedAt,organizationId:t.organizationId,host:t.host,jobs:e.map(n=>({name:n.name,type:n.type,...n.cronExpression!==void 0?{cronExpression:n.cronExpression}:{},state:n.state,...n.nextFireTime!==void 0?{nextFireTime:n.nextFireTime}:{},...n.previousFireTime!==void 0?{previousFireTime:n.previousFireTime}:{},...n.owner!==void 0?{owner:n.owner}:{}}))}}function Oo(e,t){return{status:e,name:t.name,type:t.type,...t.cronExpression!==void 0?{cronExpression:t.cronExpression}:{},...t.owner!==void 0?{owner:t.owner}:{},...t.nextFireTime!==void 0?{nextFireTime:t.nextFireTime}:{}}}var cy=["gone","inactive","frozen","new"];function ly(e,t){let n=e.jobs.filter(Fc),r=t?.kept.inventory.jobs.filter(Fc)??[],s=new Map;for(let c of r)s.set(Ao(c),(s.get(Ao(c))??0)+1);let o=[],i=0;for(let c of n){let d=Ao(c),u=(s.get(d)??0)>0;u&&s.set(d,(s.get(d)??0)-1),c.ownerActive===!1?o.push(Oo("inactive",c)):c.ownerFrozen===!0?o.push(Oo("frozen",c)):t!==void 0&&!u?o.push(Oo("new",c)):i++}if(t!==void 0&&!e.truncated)for(let c of r){let d=Ao(c);(s.get(d)??0)!==0&&(s.set(d,(s.get(d)??0)-1),o.push(Oo("gone",c)))}o.sort((c,d)=>cy.indexOf(c.status)-cy.indexOf(d.status)||c.name.localeCompare(d.name));let a=[e.truncated?`more jobs than ${e.jobs.length} were there: those past them were not read, and none is said gone`:void 0,e.ownersUnread!==void 0?`the users the jobs run as could not be read (${e.ownersUnread}): a job run as a frozen or inactive user is not told`:void 0].filter(c=>c!==void 0);return{now:n.length,...t!==void 0?{against:{savedAt:t.kept.inventory.savedAt,organizationId:t.kept.inventory.organizationId,refreshed:t.refreshed}}:{},jobs:o,kept:i,...a.length>0?{unread:a.join("; ")}:{}}}var py={words:1,switches:["--json","--save","--fail-on-findings"],values:["--file","--org","--alias"]},OA=2;function jo(e,t){let n=o=>typeof o=="object"?{productionHosts:o.productionHosts??[],fields:o.fields??[]}:{productionHosts:[],fields:[]};if(t==="verb")return{deliverability:!0,schedules:e?.schedules!==!1,endpoints:e?.endpoints===!1?!1:n(e?.endpoints)};let r=e?.schedules===!0,s=e?.endpoints!==void 0&&e.endpoints!==!1?n(e.endpoints):!1;if(!(!r&&s===!1))return{deliverability:!0,schedules:r,endpoints:s}}function jA(e){let t=0,n=0;if(e.deliverability&&(t+=1,n+=2),e.schedules&&(t+=1,n+=3),e.endpoints!==!1){let r=oy(e.endpoints.fields);t+=r,n+=r}return{fewest:t,most:n}}function hy(e){let t=[e.deliverability?"deliverability":void 0,e.schedules?"scheduled jobs":void 0,e.endpoints!==!1?"endpoints":void 0].filter(o=>o!==void 0),{fewest:n,most:r}=jA(e),s=n===r?`${r}`:`${n} to ${r}`;return`audits after the apply: ${t.join(", ")}, about ${s} API requests`}function IA(e){let t=(e.schedules?.jobs??[]).filter(s=>s.status!=="new").length,n=e.endpoints?.found.length??0,r=e.deliverability?.read==="open"?1:0;return t+n+r}async function Mc(e,t){let n=(e.now??(()=>new Date))(),r=new Eo(e.transport,{...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{}}),s=[],o,i=!1,a={org:{organizationId:t.org.organizationId,kind:t.org.kind,...t.org.alias!==void 0?{alias:t.org.alias}:{},...t.org.host!==void 0?{host:t.org.host}:{}},at:n.toISOString()};if(t.asked.deliverability){let d=await xd(r.asTransport(),{timeoutMs:r.timeout}).catch(u=>({reading:{unread:u instanceof Error?u.message:String(u)},requests:0}));a.deliverability="unread"in d.reading?{unread:d.reading.unread.slice(0,2e3)}:{read:d.reading.level==="all"?"open":"closed"}}if(t.asked.schedules){let d=await dy(r);if("unread"in d)a.schedules={now:0,jobs:[],kept:0,unread:d.unread.slice(0,2e3)},t.save===!0&&(o="the scheduled jobs were not read");else{let u;if(t.org.host!==void 0){let l=await ey(e.journalDir,t.org.host);for(let f of l.setAside)s.push(`inventory set aside: ${f.path}: ${f.why}`);l.unread!==void 0&&s.push(`no inventory read: ${l.unread}`),u=ty(l.kept,t.org.organizationId)}if(a.schedules=ly(d,u),t.save===!0)if(t.org.host===void 0)i=!0,o="the org's host is not known, and an inventory is kept by its host";else if(d.truncated)o="more jobs were there than were read: an inventory of part of them would have the next comparison call the others new";else try{let l=await Zg(e.journalDir,uy(d.jobs,{savedAt:n.toISOString(),organizationId:t.org.organizationId,host:t.org.host}));a.schedules={...a.schedules,saved:l}}catch(l){i=!0,o=`it could not be written: ${l instanceof Error?l.message:String(l)}`}}}else t.save===!0&&(o="the file reads no scheduled jobs (audits.schedules: false)");return t.asked.endpoints!==!1&&(a.endpoints=await iy(r,{...t.org.host!==void 0?{host:t.org.host}:{},productionHosts:t.asked.endpoints.productionHosts,fields:t.asked.endpoints.fields})),o!==void 0&&s.push(`nothing saved: ${o}`),{result:gd.parse({...a,apiRequests:r.requests,findings:IA(a)}),notes:s,...i&&o!==void 0?{saveFailed:o}:{}}}function fy(e){return e.replace(/\.\d{3}Z$/,"Z")}function CA(e){let t=ke(e.host),n=e.kind==="sandbox"?t!==void 0?`sandbox ${t}`:"sandbox":e.kind==="scratch"?"scratch org":"Developer Edition org";return e.alias!==void 0?`${e.alias} (${n}, ${e.organizationId})`:`${e.organizationId} (${n})`}function DA(e){return e.unread!==void 0&&e.now===0&&e.jobs.length===0&&e.kept===0&&e.against===void 0}function zc(e,t){let n=[],r=`${e.apiRequests} API request${e.apiRequests===1?"":"s"}`;n.push(`audit of ${CA(e.org)}, ${fy(e.at)}, ${r}`);let s=e.deliverability;s?.read==="closed"?n.push("deliverability: closed \u2014 System email only or No access: what runs there emails nobody. Which of the two, no API says."):s?.read==="open"?n.push("deliverability: open \u2014 All email: what runs there emails whoever its records name, the addresses copied from production's among them."):s?.unread!==void 0&&n.push(`deliverability: not read \u2014 ${s.unread}`);let o=e.schedules;if(o!==void 0&&DA(o))n.push(`scheduled jobs: not read \u2014 ${o.unread??""}`);else if(o!==void 0){let a=o.against,c=e.org.kind==="sandbox"?"this sandbox":"this org";if(a===void 0){let d=e.org.host??"its host";n.push(`scheduled jobs: ${o.now} now, nothing to compare them with: no inventory of ${d} is kept on this machine`)}else n.push(`scheduled jobs: ${o.now} now, against the inventory saved on ${a.savedAt.slice(0,10)} from ${a.organizationId}, `+(a.refreshed?`${c} before its refresh`:`${c}: no refresh since`));for(let d of o.jobs){let u=` ${d.status.padEnd(8)} `,l=f=>`${u}${d.name} (${d.type}) runs as ${d.owner??"a user not read"}, who is ${f}: its next run${d.nextFireTime!==void 0?`, ${fy(d.nextFireTime)},`:""} fails`;if(d.status==="gone"){let f=d.cronExpression!==void 0?`${d.type}, ${d.cronExpression}`:d.type;n.push(`${u}${d.name} (${f}): `+(a?.refreshed===!0?"scheduled before the refresh, not since":`in the inventory of ${a?.savedAt.slice(0,10)??"?"}, not since`))}else d.status==="frozen"||d.status==="inactive"?n.push(l(d.status)):n.push(`${u}${d.name} (${d.type})`)}if(a!==void 0&&n.push(` ${"kept".padEnd(8)} ${o.kept}`),o.unread!==void 0&&n.push(` not read: ${o.unread}`),o.saved!==void 0)n.push(` inventory saved in ${o.saved}, to compare with after the next refresh`);else if(a===void 0){let d=e.org.alias??e.org.organizationId;n.push(` before the next refresh, keep one: ${B("env")} audit --file ${t.file} --org ${d} --save`)}}for(let a of t.notes??[])n.push(` ${a}`);let i=e.endpoints;if(i!==void 0){let a=i.productionHosts.join(", "),c=i.found.length===0;n.push(`endpoints that still name production (${a}):`+(c?i.unread!==void 0?" none among those read":" none":"")),i.notDeduced!==void 0&&n.push(` ${i.notDeduced}`);let d=h=>Math.max(...h.map(g=>g.length))+2,u=i.found.map(h=>$o[h.source]),l=i.found.map(h=>h.name),f=i.found.map(h=>h.url);i.found.forEach((h,g)=>{n.push(` ${(u[g]??"").padEnd(d(u))}${(l[g]??"").padEnd(d(l))}${h.url.padEnd(d(f))}${So[h.why]}`)}),i.unread!==void 0&&n.push(` not read: ${i.unread}`)}return e.findings>0&&n.push("SandForge changes none of these: Setup, sf or your deployment put them right."),n}function PA(e,t){return e.saveFailed!==void 0?1:t&&e.result.findings>0?3:0}async function my(e,t){let n=jo(t.audits,"verb");if(n===void 0)throw new Error("env audit reads the deliverability at least");if(t.save&&!n.schedules)return{refusal:{code:"BAD_LINE",message:"--save keeps the scheduled jobs, which the file does not read (audits.schedules: false): take --save off the line, or the line off the file. Nothing was read."},exitCode:OA};let r=await Mc(e,{org:t.org,asked:n,save:t.save}),s=zc(r.result,{file:t.file,notes:r.notes});return{result:r.result,lines:s,exitCode:PA(r,t.failOnFindings)}}import{randomBytes as NA}from"node:crypto";import{mkdir as TA,open as xA,rename as LA,rm as FA}from"node:fs/promises";import{dirname as MA,join as zA,resolve as _A}from"node:path";var qA=448,BA=384,gy=72;function U(e){return`\`${e.replace(/[`\r\n]+/g," ").trim()}\``}function yy(e){return e.replace(/[\r\n]+/g," ").trim()}function ky(e){return e.replace(/\.\d{3}Z$/,"Z")}function _c(e){return e.map(([t,n])=>`${t} ${n}`).join(", ")}function wy(e){switch(e.what){case"email":return"address asked back, awaiting its owner";case"active":return e.to?"activated":"deactivated";case"frozen":return e.to?"frozen":"unfrozen";case"profile":return`profile ${U(e.to)}`;case"permissionSet":return`${e.to==="added"?"permission set":"permission set taken off:"} ${U(e.name)}`;case"permissionSetGroup":return`${e.to==="added"?"permission set group":"permission set group taken off:"} ${U(e.name)}`;case"group":{let t=e.type==="Queue"?"queue":"public group";return`${e.to==="added"?t:`${t} taken off:`} ${U(e.name)}`}}}function UA(e){let t=vt.safeParse(e.answer);return t.success?t.data.users:void 0}function by(e,t){return e.steps.filter(n=>n.resource===t&&n.phase==="run").at(-1)}function Ey(e){switch(e.status){case"applied":return"applied";case"partial":return"applied in part";case"failed":return"failed";default:return"stopped part way"}}function KA(e){let t=["## Access",""],n=[],r=new Date(Date.parse(e.at)+gy*36e5).toISOString(),s=e.run.plan.actions.filter(o=>o.kind==="users");s.length===0&&t.push("- No users resource: SandForge set up no user.");for(let o of s){let i=by(e.run,o.resource);if(i===void 0){t.push(`- ${U(o.resource)}: ${o.action==="keep"?"kept, as the last apply left its users":"not run"}.`);continue}let a=UA(i);if(a===void 0){t.push(`- ${U(o.resource)}: ${Ey(i)}; what it did to each user does not read from its answer: ${B("env")} output names its users.`);continue}for(let c of a){let d=c.done.map(wy),u=(c.refused??[]).map(f=>`${wy(f.change)} refused (${f.code})`),l=[...d,...u];t.push(`- ${U(c.username)}: ${l.length>0?l.join("; "):"as the file says already"}.`),c.address==="awaiting"&&n.push(c.username)}}if(n.length>0){t.push("","### Addresses awaiting their owner","");for(let o of n)t.push(`- ${U(o)}: the address stays under \`.invalid\` until its owner follows the link Salesforce sent to it, by about ${ky(r)} (${gy} hours).`)}return t.push("","SandForge resets no password: a user without one sets it by **Forgot your password?** on the sandbox's login page, once the address is theirs again."),t}function WA(e,t){let n=e.resources?.[t];if(n?.kind!=="mask")return;if(typeof n.rules!="string")return`the rules of the template ${U(n.rules.template)}`;let r=e.masking?.[n.rules];if(r===void 0)return;let s=[...new Set(r.rules.map(o=>o.fieldPattern))];return s.length>0?s.map(U).join(", "):void 0}function VA(e){let t=["## Data",""],n=e.run.plan.actions.filter(o=>o.kind!=="users");n.length===0&&t.push("- No data resource.");for(let o of n){let i=`${U(o.resource)} (${o.kind})`,a=by(e.run,o.resource);if(a===void 0){let d=e.run.skipped?.some(u=>u.resource===o.resource)===!0;t.push(`- ${i}: `+(o.action==="keep"?"kept, as applied before":o.action==="blocked"?"not applied: refused before it wrote":d?"not run: a resource it depends on did not end whole":"not run"));continue}let c=[Ey(a)];if(o.kind==="mask"){let d=e.output?.resources[o.resource],u=d?.masked?Object.entries(d.masked):a.objects.flatMap(f=>f.masked!==void 0?[[f.object,f.masked]]:[]);u.length>0&&c.push(`masked ${_c(u)}`);let l=WA(e,o.resource);l!==void 0&&c.push(`fields ${l}`),d?.snapshotId!==void 0&&c.push(`snapshot ${U(d.snapshotId)}, taken first`)}else{let d=a.objects.filter(f=>f.created>0);d.length>0&&c.push(`created ${_c(d.map(f=>[f.object,f.created]))}`);let u=a.objects.filter(f=>f.refused>0);u.length>0&&c.push(`refused ${_c(u.map(f=>[f.object,f.refused]))}`);let l=e.resources?.[o.resource];l?.kind==="replay"&&l.owners!==void 0&&c.push(l.owners==="same"?"owners kept as the checkpoint names them":"owned by the user the apply connected as")}t.push(`- ${i}: ${c.join("; ")}.`)}let r=e.run.checkpoints?.find(o=>o.step==="after"),s=e.run.plan.checkpoints?.find(o=>o.step==="after");if(r!==void 0||s!==void 0){t.push("","### Starting point","");let o=e.org.alias??e.org.organizationId;if(r?.checkpoint!==void 0){let i=s?.estimate!==void 0?`, about ${s.estimate.records} records`:"";t.push(`- Checkpoint ${s!==void 0?`${U(s.name)} `:""}${U(r.checkpoint)}${i}: the org as the testers get it.`,`- Back to it between two test runs: \`${B("env")} reset --file ${e.file} --org ${o}\``)}else t.push(`- The checkpoint ${s!==void 0?`${U(s.name)} `:""}was not taken${r!==void 0?` (exit ${r.exitCode})`:""}: no reset returns to this apply's end.`)}return t}function vy(e){let t=e.org.alias??e.org.organizationId;return`\`${B("env")} audit --file ${e.file} --org ${t}\``}function HA(e){let t=e.run.audits,n=["## Still to do, in this order",""];n.push("1. Credentials and technical components: point them away from production.");let r=t?.endpoints;if(r===void 0)n.push(` - Not audited: ${vy(e)} lists those that still name production.`);else{for(let i of r.found)n.push(` - ${$o[i.source]} ${U(i.name)} names ${U(i.host)}, ${So[i.why]}.`);r.found.length===0&&r.unread===void 0&&n.push(" - None of those read names production."),r.unread!==void 0&&n.push(" - Not all read: check the Named Credentials, the Remote Site Settings and the Custom Metadata in Setup.")}n.push("2. Scheduled jobs: schedule again those gone, and give those stuck a user who can run them.");let s=t?.schedules;if(s===void 0)n.push(` - Not audited: ${vy(e)} compares them with their inventory.`);else{for(let i of s.jobs)i.status==="gone"?n.push(` - ${U(i.name)} (${yy(i.type)}) was scheduled in the inventory of ${s.against?.savedAt.slice(0,10)??"?"}, and is not now.`):(i.status==="frozen"||i.status==="inactive")&&n.push(` - ${U(i.name)} (${yy(i.type)}) runs as ${i.owner!==void 0?U(i.owner):"a user not read"}, who is ${i.status}: its next run fails.`);s.against===void 0&&n.push(" - No inventory from before the refresh was kept on this machine: what is gone is not known."),s.unread!==void 0&&n.push(" - Not all read: Setup > Scheduled Jobs lists them."),!s.jobs.some(i=>i.status!=="new")&&s.unread===void 0&&n.push(s.against!==void 0?" - None gone, none stuck.":" - None stuck.")}n.push("3. Automations that send emails \u2014 flows, workflow rules, Apex \u2014: turn them on last, once the addresses and the masking are as the testers need them."),n.push("4. Deliverability.");let o=t?.deliverability;return o?.read==="closed"?n.push(" - Read closed, System email only or No access: leave it so until the masking is done."):o?.read==="open"?n.push(" - Read open, All email: what runs there emails whoever its records name. Set it to System email only in Setup > Deliverability until the masking is done."):n.push(" - Not read: Setup > Deliverability shows it."),n}var JA=["- Named and External Credentials: Setup, or a deployment of your project by `sf`.","- Metadata: your deployment.","- Single sign-on and DKIM keys: Setup.","- Deliverability: Setup > Deliverability.","- Passwords: each user's own, by Forgot your password? on the sandbox's login page."];function Ry(e){let{run:t,org:n}=e,r=ke(n.host),s=n.kind==="sandbox"?`sandbox${r!==void 0?` ${U(r)}`:""}`:n.kind==="scratch"?"scratch org":"Developer Edition org";return`${[`# Handoff: ${U(t.plan.env)} on ${U(n.alias??n.organizationId)}`,"","## Environment","",`- Environment: ${U(t.plan.env)}, state serial ${t.state.serial}.`,`- Org: ${n.alias!==void 0?`${U(n.alias)}, `:""}${s}, ${U(n.organizationId)}.`,`- Applied: ${ky(e.at)}, by SandForge ${e.sandforgeVersion}; it ended ${t.status}.`,"",...KA(e),"",...VA(e),"",...HA(e),"","## Not touched by SandForge","",...JA].join(`
|
|
151
|
+
`)}
|
|
152
|
+
`}function Sy(e,t){if(!/^[a-z][a-z0-9-]{0,62}$/.test(t.env))throw new Error(`Not an environment's name: "${t.env}"`);let n=new Date(t.at).toISOString().replace(/[-:.]/g,"");return zA(_A(e),"handoff",t.env,`${n}-${re(t.organizationId)}.md`)}async function $y(e,t){await TA(MA(e),{recursive:!0,mode:qA});let n=`${e}.${process.pid}-${NA(4).toString("hex")}.tmp`,r=await xA(n,"wx",BA);try{try{await r.writeFile(t,"utf8"),await r.sync()}finally{await r.close()}await LA(n,e)}catch(s){throw await FA(n,{force:!0}),s}}import{readFile as Tt,readdir as YA,stat as GA}from"node:fs/promises";import{join as Ie}from"node:path";var QA={"sandforge-seed":"seed","sandforge-clone":"forge","sandforge-frozen":"frozen","sandforge-dataops":"mask"},XA=/^([1-9][0-9]{0,5})\.summary\.json$/,ZA=/^([a-z][a-z0-9-]{0,62})\.([1-9][0-9]{0,5})\.json$/,eO=/^([a-z][a-z0-9-]{0,62})-([1-9][0-9]{0,5})-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,tO=/\.load-\d{1,16}\.ndjson$/,Y=class extends Error{constructor(n,r){super(r);this.code=n;this.name="Refused"}code},fe="Nothing was written.";async function Ye(e,t){try{return(await YA(e,{withFileTypes:!0})).filter(r=>t?r.isDirectory():r.isFile()).map(r=>r.name).sort()}catch(n){let r=n?.code;if(r==="ENOENT"||r==="ENOTDIR")return[];throw n}}function qc(e,t,n){let r=e.ranks.get(t);r===void 0&&(r=new Map,e.ranks.set(t,r));let s=r.get(n);return s===void 0&&(s={seedRuns:[]},r.set(n,s)),s}async function Oy(e,t){let n=t.resolved.checked.file.name,r=t.target.organizationId,s=e.store.folderOf(r,n),o={ranks:new Map,frozen:new Set,dataops:new Set,unclaimed:[]},i=f=>fn.safeParse(f).success;for(let f of(await Ye(Ie(s,"runs"),!0)).filter(i))for(let h of await Ye(Ie(s,"runs",f),!1)){let g=XA.exec(h)?.[1];g!==void 0&&(qc(o,f,Number(g)).summary=oe(f,Number(g)))}for(let f of await Ye(Ie(s,"templates"),!1)){let h=ZA.exec(f);h?.[1]===void 0||h[2]===void 0||!i(h[1])||(qc(o,h[1],Number(h[2])).template=Et(h[1],Number(h[2])))}for(let f of(await Ye(Ie(s,"frozen"),!0)).filter(i))o.frozen.add(f);for(let f of(await Ye(Ie(s,"dataops"),!0)).filter(i))o.dataops.add(f);let a=new Set(t.resolved.resources.map(f=>f.name)),c=new Set([...o.ranks.keys(),...o.frozen,...o.dataops]),d=(await Ye(Ie(s,".."),!0)).filter(f=>f!==n&&f.startsWith(`${n}-`)),u=`env-${n}-`,l=Cd(e.journalDir,Ue);for(let f of await Ye(Ie(e.journalDir,Ue),!1)){if(!f.endsWith(".ndjson")||!f.startsWith(u))continue;let h=f.slice(0,-7),g=eO.exec(h.slice(u.length));if(g?.[1]===void 0||g[2]===void 0)continue;let m=g[1],w=a.has(m)||c.has(m),y=d.find(k=>h.startsWith(`env-${k}-`));if(y!==void 0&&!w)continue;let v=Ie(e.journalDir,Ue,f),b=await l.get(h);if(b===void 0)throw new Y("RUN_UNREAD",`The seed run file ${v} does not read as a run: a state rebuilt without it would leave what it created to nobody. Move it aside if it is not a run of ${n}. ${fe}`);if(b.targetOrganizationId===void 0)throw new Y("RUN_UNREAD",`The seed run file ${v} names no Organization Id: nothing tells whether it wrote to ${t.target.alias} or to another org. Move it aside if it is not a run of ${n} on ${t.target.alias}. ${fe}`);if(Ee(b.targetOrganizationId,r)){if(y!==void 0)throw new Y("RUN_UNCLAIMED",`The seed run file ${v} may be run ${g[2]} of ${m} of ${n}, or a run of ${y}, kept on this machine too: their names begin alike, and nothing tells them apart. Move it out of the folder while ${n} is recovered if it is ${y}'s. ${fe}`);if(!w){o.unclaimed.push({file:v,resource:m,run:b});continue}qc(o,m,Number(g[2])).seedRuns.push({runId:h,run:b})}}return o}async function Do(e,t){try{let n=await Oy(e,t);return n.unclaimed.length>0||n.frozen.size>0||n.dataops.size>0||[...n.ranks.values()].some(r=>[...r.values()].some(s=>s.summary!==void 0||s.seedRuns.length>0))}catch(n){return n instanceof Y}}function nO(e){let t=e??{};return t.command==="replay"&&t.action==="replay"?"replay":typeof t.run=="number"&&Array.isArray(t.users)?"users":void 0}function pr(e){if(typeof e!="string")return;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}async function jy(e){try{return(await GA(e)).mtime.toISOString()}catch{return}}async function rO(e){let t=i=>new Y("RUN_UNREAD",`The summary ${e} does not read (${i}): a state rebuilt without it would leave what its run created to nobody. ${fe}`),n;try{n=await Tt(e,"utf8")}catch(i){throw t(i instanceof Error?i.message:String(i))}let r;try{r=JSON.parse(n)}catch{throw t("not JSON")}let s=r?.tool,o=typeof s=="string"?QA[s]:nO(r);try{if(o==="users")return{kind:o,answer:Vt(n)};if(o==="replay")return{kind:o,answer:os(n)};if(o==="seed")return{kind:o,answer:Wt(n)};if(o==="frozen")return{kind:o,answer:ts(n)};if(o==="mask")return{kind:o,answer:ss(n)};if(o==="forge"){let i=r,a=pr(i.finishedAt),c=typeof i.elapsedMs=="number"&&Number.isFinite(i.elapsedMs)&&i.elapsedMs>=0?i.elapsedMs:void 0;return{kind:o,answer:$n(n),...a!==void 0?{finishedAt:a}:{},...c!==void 0?{elapsedMs:c}:{}}}}catch(i){throw i instanceof de?t(i.message):i}throw t("it names no script of an environment")}function Iy(e){return e.removal!==void 0&&Vo(e).length===0}function sO(e){return e.interrupted===!0||e.result.cancelled===!0?"applying":e.result.status==="success"?"applied":e.result.status==="partial"?"partial":"failed"}function hr(e){return e.map(t=>({objectApiName:t.object,created:t.created,refused:t.refused}))}function Io(e,t,n){if(!(t===void 0||Ee(t,n.target.organizationId)))throw new Y("RUN_OTHER_ORG",`The summary ${e} is of a run that wrote to ${t}, not to ${n.target.alias} (${n.target.organizationId}): it was copied from another org's folder. Put it back where it came from. ${fe}`)}async function oO(e,t,n,r,s,o){let i=t.resolved.checked.file.name,a=m=>e.store.fileOf(t.target.organizationId,i,m);if(s.seedRuns.length>1)throw new Y("RUNS_CONFLICT",`Two seed runs are kept for run ${r} of ${n}: ${s.seedRuns.map(m=>m.runId).join(", ")}. One rank is one run: the state they come from cannot be told. ${fe}`);let c=s.seedRuns[0],d=o?.kind==="seed"?o.answer:void 0,u=d?.result.operationId??c?.runId;if(d!==void 0&&c!==void 0&&d.result.operationId!==c.runId)throw new Y("RUNS_CONFLICT",`The summary of run ${r} of ${n} is of the run ${d.result.operationId}, and the seed run file of that rank of ${c.runId}: one rank is one run. ${fe}`);if(d!==void 0&&!d.result.operationId.startsWith(`env-${i}-${n}-${r}-`))throw new Y("RUNS_CONFLICT",`The summary ${a(oe(n,r))} is of the run ${d.result.operationId}, which is not run ${r} of ${n}. ${fe}`);let l=c!==void 0&&Iy(c.run);if(d!==void 0&&!l){let m=await Tt(a(ii(n,r)),"utf8").catch(()=>{}),w;try{w=m!==void 0?JSON.parse(m):void 0}catch{w=void 0}let y=w?.runId===d.result.operationId?Dd(w):void 0;l=y!==void 0&&d.result.objectResults.every(v=>v.truncated!==!0)&&Vo(Yd({runId:d.result.operationId,targetOrgId:d.target,status:d.result.status,objectResults:d.result.objectResults},y)).length===0}let f=pr(d?.startedAt)??pr(c?.run.startedAt)??new Date(0).toISOString(),h=pr(d!==void 0?d.finishedAt:c?.run.end?.at),g=d!==void 0?hr(cs(d).objects):(c?.run.created??[]).map(m=>({objectApiName:m.objectApiName,created:m.ids.length,refused:0}));return{run:{n:r,script:"sandforge-seed",...u!==void 0?{runId:u}:{},...s.summary!==void 0&&d!==void 0?{summary:s.summary}:{},...d!==void 0?{seed:d.seed}:{},startedAt:f,...h!==void 0?{endedAt:h}:{},objects:g,...l?{takenBack:!0}:{}},status:d!==void 0?sO(d):"applying"}}async function iO(e,t,n,r,s){let o=t.resolved.checked.file.name,i=oe(n,r),a=e.store.fileOf(t.target.organizationId,o,i),{answer:c}=s,d=!1,u=await Tt(e.store.fileOf(t.target.organizationId,o,ii(n,r)),"utf8").catch(()=>{});if(u!==void 0){let m=await Ir(a,await Tt(a,"utf8"),t.target.alias,Or(e.journalDir));if(!("refusal"in m)){let w=ru(u,nu(tu(m.summary)));d="earlier"in w&&w.earlier?.removalLeft?.length===0}}let l=c.running===!0||c.interrupted===!0?void 0:s.finishedAt,f=s.finishedAt??await jy(a)??new Date(0).toISOString(),h=new Date(Date.parse(f)-(s.elapsedMs??0)).toISOString(),g=c.running===!0||c.interrupted===!0?"applying":c.error!==void 0?"failed":c.result.failedCount>0?"partial":"applied";return{run:{n:r,script:"sandforge-clone",summary:i,startedAt:h,...l!==void 0?{endedAt:l}:{},objects:hr(es(c).objects),...d?{takenBack:!0}:{}},status:g}}async function Co(e,t,n){let r=t.resolved.checked.file.name,s=a=>a!==void 0?jy(e.store.fileOf(t.target.organizationId,r,a)):Promise.resolve(void 0),o=await s(n.template),i=await s(n.summary);return{startedAt:o??i??new Date(0).toISOString(),...i!==void 0?{endedAt:i}:{}}}async function aO(e,t){if((await Ye(e,!1)).some(o=>tO.test(o)))return!1;let n=new Ke,r=(await mn(e,n)).find(o=>Ee(o,t));if(r===void 0)return!1;let s=await new Dr(e,{orgId:r,guard:n}).recordedLoads();return s.length>0&&s.some(o=>o.removal!==void 0)&&s.every(o=>o.created!==void 0&&uu(o).length===0)}async function cO(e,t){let n=(await mn(e,new Ke)).filter(r=>!Ee(r,t.target.organizationId));if(n.length!==0)throw new Y("RUN_OTHER_ORG",`The sas ${e} keeps loads into ${n.join(", ")}, not into ${t.target.alias} (${t.target.organizationId}): it was copied from another org's folder. Put it back where it came from. ${fe}`)}function dO(e){let t=Cn(e);return t.refusal!==void 0?"failed":t.objects.some(n=>n.refused>0)?"partial":e.verdict===void 0||e.verdict.status==="PASSED"?"applied":"partial"}function uO(e){return e.status==="success"?"applied":e.status==="partial"?"partial":e.status==="cancelled"?"applying":"failed"}function lO(e){return e.exit===0?"applied":e.exit===3?"partial":"failed"}var fO=p.object({run:p.number().int().positive(),replaces:p.number().int().positive().optional(),startedAt:p.string().optional(),removals:p.array(p.object({status:p.string()}).loose()).optional()}).loose();function Cy(e,t){return Ie(e.journalDir,"users",re(t.target.organizationId))}async function Dy(e,t,n){let r=await Tt(Ie(Cy(e,t),`run-${n}.json`),"utf8").catch(()=>{});if(r!==void 0)try{let s=fO.safeParse(JSON.parse(r));return!s.success||s.data.run!==n?void 0:{...s.data.replaces!==void 0?{replaces:s.data.replaces}:{},takenBackWhole:s.data.removals?.at(-1)?.status==="success"}}catch{return}}async function pO(e,t,n){let r=Cy(e,t),s=[];for(let o of await Ye(r,!1)){let i=Number(/^run-([1-9]\d{0,5})\.json$/.exec(o)?.[1]??0);i===0||n.has(i)||(await Dy(e,t,i))?.takenBackWhole===!0||s.push(`${Ie(r,o)}: run ${i} of ${B("users")}, which no summary names \u2014 a run of a users resource stopped before it answered, or one run alone: the state holds it not; ${B("users")} remove --org ${t.target.alias} --run ${i} takes it back`)}return s}async function hO(e,t,n){let r=t.resolved.checked.file.name,s=new Set;for(let o of n)if(o.state.kind==="users")for(let i of o.state.runs){if(i.summary===void 0)continue;let a=e.store.fileOf(t.target.organizationId,r,i.summary),c=await Tt(a,"utf8").catch(()=>{}),d=c!==void 0?Pn(c):void 0;d!==void 0&&s.add(d)}return s}function mO(e){let t=Dn(e);return t.refusal!==void 0?"failed":t.short!==void 0||t.objects.some(n=>n.notMasked>0)?"partial":"applied"}function gO(e,t,n){let r=new Set;for(let s of n.values())r.add(s.kind);if(t.frozen.has(e)&&r.add("frozen"),t.dataops.has(e)&&r.add("mask"),[...t.ranks.get(e)?.values()??[]].some(s=>s.seedRuns.length>0)&&r.add("seed"),r.size>1)throw new Y("RUNS_CONFLICT",`The run files of ${e} are of ${[...r].join(" and ")} runs: one resource is of one kind, and the state they come from cannot be told. ${fe}`);return[...r][0]}async function yO(e,t,n,r){let s=t.resolved.checked.file.name,o=t.target.organizationId,i=n.ranks.get(r)??new Map,a=new Map;for(let[y,v]of i)v.summary!==void 0&&a.set(y,await rO(e.store.fileOf(o,s,v.summary)));let c=gO(r,n,a);if(c===void 0)return;for(let[y,v]of a){let b=e.store.fileOf(o,s,oe(r,y));v.kind==="seed"&&Io(b,v.answer.targetOrgId,t),v.kind==="forge"&&Io(b,v.answer.targetOrgId,t),v.kind==="users"&&Io(b,v.answer.org.organizationId,t),v.kind==="replay"&&Io(b,v.answer.target.organizationId,t)}let d=[],u=[...i.keys()].sort((y,v)=>y-v);if(c==="seed")for(let y of u){let v=i.get(y);v===void 0||v.summary===void 0&&v.seedRuns.length===0||d.push(await oO(e,t,r,y,v,a.get(y)))}else if(c==="forge")for(let y of u){let v=a.get(y);v?.kind==="forge"&&d.push(await iO(e,t,r,y,v))}else if(c==="frozen"){let y=e.store.sasOf(o,s,rt(r));await cO(y,t);let v=await aO(y,o);for(let b of u){let k=i.get(b),E=a.get(b);if(k?.template===void 0){if(E?.kind!=="frozen"||v)continue;throw new Y("RUN_UNREAD",`Run ${b} of ${r} keeps its summary and not the payload its load was given, ${e.store.fileOf(o,s,Et(r,b))}, which its removal is run from: a state rebuilt without it would leave what the load created to nobody. ${fe}`)}let S=E?.kind==="frozen"?E.answer:void 0;if(d.push({run:{n:b,script:"sandforge-frozen",sas:rt(r),...S!==void 0&&k.summary!==void 0?{summary:k.summary}:{},...await Co(e,t,k),objects:S!==void 0?hr(Cn(S).objects):[],...v?{takenBack:!0}:{}},status:S!==void 0?dO(S):"applying"}),S!==void 0&&ns(S))for(let $ of d.slice(0,-1))$.run.takenBack=!0}}else if(c==="users")for(let y of u){let v=i.get(y),b=a.get(y);if(v?.summary===void 0||b?.kind!=="users")continue;let k=await Dy(e,t,b.answer.run);if(k?.replaces!==void 0)for(let E of d)E.users===k.replaces&&(E.run.takenBack=!0);d.push({run:{n:y,script:"sandforge-users",summary:v.summary,...await Co(e,t,v),objects:hr(ds(b.answer).objects),...k?.takenBackWhole===!0?{takenBack:!0}:{}},status:uO(b.answer),users:b.answer.run})}else if(c==="replay")for(let y of u){let v=i.get(y),b=a.get(y);if(!(v?.summary===void 0||b?.kind!=="replay")&&(d.push({run:{n:y,script:"sandforge-checkpoint",summary:v.summary,...await Co(e,t,v),objects:hr(is(b.answer).objects)},status:lO(b.answer)}),as(b.answer)))for(let k of d.slice(0,-1))k.run.takenBack=!0}else{let y=!n.dataops.has(r);for(let v of u){let b=i.get(v),k=a.get(v);if(b===void 0)continue;let E=k?.kind==="mask"?k.answer:void 0;if(E===void 0&&y)continue;let S=E!==void 0?Dn(E):void 0;d.push({run:{n:v,script:"sandforge-dataops",...E!==void 0&&b.summary!==void 0?{summary:b.summary}:{},...S?.snapshotId!==void 0?{snapshotId:S.snapshotId}:{},...await Co(e,t,b),objects:(S?.objects??[]).map($=>({objectApiName:$.object,created:0,refused:$.refused,masked:$.masked})),...y?{takenBack:!0}:{}},status:E!==void 0?mO(E):"applying"})}}if(d.length===0)return;let l=d.map(y=>y.run),f=d.at(-1),h=l.every(y=>y.takenBack===!0)?"destroyed":f?.run.takenBack===!0?"partial":f?.status??"applying",g=t.resolved.resources.find(y=>y.name===r),m=l.flatMap(y=>y.endedAt!==void 0?[y.endedAt]:[]).sort(),w=l.map(y=>y.startedAt).sort();return{name:r,state:{kind:c,fingerprint:md,dependsOn:g!==void 0?[...g.dependsOn]:[],status:h,runs:l,recovered:!0},firstStartedAt:w[0]??new Date(0).toISOString(),...m.length>0?{lastEndedAt:m.at(-1)}:{}}}async function wO(e,t,n){let r=t.resolved.checked.file,o=(await new Md({root:ie(e.journalDir),locksDir:e.locksDir}).list({organizationId:t.target.organizationId})).flatMap(l=>l.valid&&l.checkpoint!==void 0?[l.checkpoint]:[]),i=[],a={},c=`${r.name} before`,d=o.filter(l=>l.name===c&&Date.parse(l.takenAt)<=Date.parse(n.first));d.length===1&&d[0]!==void 0?a.before=d[0].checkpointId:bn(r,"before")===void 0&&d.length===0?i.push("checkpoint.before: the file asks none"):i.push(`checkpoint.before: ${d.length===0?"no":`${d.length}`} checkpoint(s) of this org named '${c}' taken before the first run: none is linked, and destroy --rewind has none to return to`);let u=bn(r,"after");if(u===void 0)i.push("checkpoint.after: the file asks none");else{let l=n.last,f=o.filter(h=>h.name===u&&l!==void 0&&Date.parse(h.readFrom)>=Date.parse(l));f.length===1&&f[0]!==void 0?a.after=f[0].checkpointId:i.push(`checkpoint.after: ${f.length===0?"no":`${f.length}`} checkpoint(s) of this org named '${u}' taken after the last run: none is linked, and reset has none to rewind to until an apply takes it`)}return{...a,notLinked:i}}function vO(e,t){let n=o=>{let i=/^(\d+)\.(\d+)\.(\d+)/.exec(o);return i?[Number(i[1]),Number(i[2]),Number(i[3])]:void 0},r=typeof e=="string"?n(e):void 0,s=n(t);if(r===void 0||s===void 0)return!1;for(let o=0;o<3;o++)if((r[o]??0)!==(s[o]??0))return(r[o]??0)>(s[o]??0);return!1}async function kO(e,t){let n=t.resolved.checked.file.name,{alias:r,organizationId:s}=t.target;try{let d=await e.store.read(s,n);if(d===void 0)return{damaged:!1};throw new Y("STATE_KEPT",`This machine keeps a state of ${n} on ${r} that reads, serial ${d.serial}: state recover never writes over one, and plan reads it. ${fe}`)}catch(d){if(!(d instanceof L))throw d;if(d.code!=="damaged"){let u=tt(d);throw new Y(u.code,u.message)}}let o=e.store.stateFileOf(s,n),i;try{i=JSON.parse(await Tt(o,"utf8"))}catch{i=void 0}let a=i,c=a?.version;if(typeof c=="number"&&c>1||vO(a?.sandforgeVersion,e.sandforgeVersion))throw new Y("STATE_NEWER",`The state ${o} was written by a later SandForge (${String(a?.sandforgeVersion??`version ${String(c)}`)}; this one is ${e.sandforgeVersion}): update it, and plan again. ${fe}`);return{damaged:!0}}async function Py(e,t){let n=t.resolved.checked.file.name,{target:r}=t,s=Qe(e.locksDir,r.organizationId,{operation:"recover",env:n,alias:r.alias},e.lockOptions);if("busy"in s)return{refusal:nt(s.busy)};try{let{damaged:o}=await kO(e,t),i=await Oy(e,t),a=[];for(let k of[...i.ranks.keys(),...i.frozen,...i.dataops]){if(a.some(S=>S.name===k))continue;let E=await yO(e,t,i,k);E!==void 0&&a.push(E)}let c=[];for(let k of i.unclaimed){if(Iy(k.run)){c.push(`${k.file}: a run of ${k.resource}, which neither the file nor the environment's folder has, taken back whole: passed over`);continue}throw new Y("RUN_UNCLAIMED",`The seed run file ${k.file} is of a resource ${k.resource} that neither the file nor the environment's folder has: it may be another environment's, whose name begins as ${n} does. Move it out of the folder if it is, or put ${k.resource} back in the file. ${fe}`)}if(a.length===0)throw new Y("NO_RUNS",`This machine keeps no run of ${n} on ${r.alias}: there is nothing to rebuild a state from. If the org holds nothing of the environment, apply it with --accept-no-state. ${fe}`);a.sort((k,E)=>Date.parse(k.firstStartedAt)-Date.parse(E.firstStartedAt)||k.name.localeCompare(E.name));let d=a[0]?.firstStartedAt??new Date(0).toISOString(),l=a.flatMap(k=>k.lastEndedAt!==void 0?[k.lastEndedAt]:[]).sort().at(-1),f=await wO(e,t,{first:d,...l!==void 0?{last:l}:{}}),h=a.some(k=>k.state.kind==="users")||t.resolved.resources.some(k=>k.kind==="users")?await pO(e,t,await hO(e,t,a)):[],m={...Br({env:n,org:{organizationId:r.organizationId,kind:r.kind,username:r.username,alias:r.alias,...r.host!==void 0?{host:r.host}:{}},fileDigest:t.resolved.digest,sandforgeVersion:e.sandforgeVersion}),resources:Object.fromEntries(a.map(k=>[k.name,k.state])),...f.before!==void 0||f.after!==void 0?{checkpoints:{...f.before!==void 0?{before:f.before}:{},...f.after!==void 0?{after:f.after}:{}}}:{}},w=pn.safeParse({...m,serial:1});if(!w.success){let k=w.error.issues[0];throw new Y("RUN_UNREAD",`The run files of ${n} do not make a state (${k?.path.join(".")??""}: ${k?.message??"refused"}). ${fe}`)}let y=o?await e.store.setAside(r.organizationId,n):void 0,v=await e.store.write(m,{serial:0,lineage:m.lineage}),b=new Set(t.resolved.resources.map(k=>k.name));return{state:v,result:{env:n,org:{organizationId:v.org.organizationId,kind:v.org.kind,alias:r.alias},state:{serial:v.serial,lineage:v.lineage},...y!==void 0?{setAside:y}:{},resources:Object.fromEntries(a.map(k=>[k.name,{kind:k.state.kind,status:k.state.status,runs:k.state.runs.map(E=>E.n),takenBack:k.state.runs.filter(E=>E.takenBack===!0).map(E=>E.n),inFile:b.has(k.name)}])),checkpoints:{...f.before!==void 0?{before:f.before}:{},...f.after!==void 0?{after:f.after}:{}},notLinked:[...f.notLinked,...c,...h].slice(0,20)}}}catch(o){if(o instanceof Y)return{refusal:{code:o.code,message:o.message,exit:1}};throw o}finally{s.lock.release()}}function Ay(e){return`${e.length===1?"run":"runs"} ${e.join(", ")}`}function Ny(e){let t=[`state of ${e.env} on ${e.org.alias??e.org.organizationId} rebuilt from its run files: serial ${e.state.serial}`],n=Math.max(...Object.keys(e.resources).map(r=>r.length));for(let[r,s]of Object.entries(e.resources)){let o=s.takenBack.length===0?"":s.takenBack.length===s.runs.length?", taken back":`; ${Ay(s.takenBack)} taken back`;t.push(` ${r.padEnd(n)} ${s.kind}, ${s.status}: ${Ay(s.runs)}${o}`+(s.inFile?"":"; gone from the file"))}e.checkpoints.before!==void 0&&t.push(` checkpoint.before: ${e.checkpoints.before}`),e.checkpoints.after!==void 0&&t.push(` checkpoint.after: ${e.checkpoints.after}`);for(let r of e.notLinked)t.push(` ${r}`);return e.setAside!==void 0&&t.push(`the state that did not read is kept, set aside: ${e.setAside}`),t.push("next: plan replaces each resource still in the org, whose run files do not say what it was applied from, and asks no --accept-no-state"),t}function bO(e,t,n){let r=n.includes("users"),s=n.includes("mask")?", and what it masked left masked":"",o=": the state keeps it as destroyed";return r&&n.every(i=>i==="users"||i==="mask")?`${e} is taken back from ${t}, the assignments and memberships it created deleted and each user put back as it was, but for an address asked back${s}${o}, and the next apply sets them up again`:`every record of ${e} is taken back from ${t}${r?", each user put back as it was but for an address asked back":""}${s}${o}, and the next apply creates it again`}function EO(e){return gt(e,qe(e).map(([t])=>t))}async function Ty(e,t){let{plan:n,target:r,resolved:s}=t,o=s.checked.file.name,i=(f,h=[])=>({result:{plan:n,steps:[],status:"failure",refusal:f,...h.length>0?{refusalCodes:[...h]}:{},state:{serial:t.state?.serial??0}},exitCode:1});if(t.state===void 0)return await Do(e,{resolved:s,target:r})?i(`This machine keeps no state of ${o} on ${r.alias}, but keeps runs of it: the records they wrote are still in the org, and destroy reaches only what a state names. "${B("env")} state recover --file <file> --org ${r.alias}" rebuilds the state from them; then destroy again. Nothing was deleted.`,["NO_STATE"]):(e.say(`this machine keeps no state of ${o} on ${r.alias}, nor any run of it: nothing applied from here is left to take back. Records an apply from another machine or a CI job left are not known here: restore its journal directory (SANDFORGE_JOURNAL_DIR), then destroy again`),{result:{plan:n,steps:[],status:"success",state:{serial:0}},exitCode:0});if(n.refusal!==void 0)return i(n.refusal,n.refusalCodes);let a=EO(t.state),c=Qe(e.locksDir,r.organizationId,{operation:"destroy",env:o,alias:r.alias},e.lockOptions);if("busy"in c){let f=nt(c.busy);return i(f.message,[f.code])}let d=new AbortController,u,l=(e.onStop??Ge)(f=>{u=f,e.say(`
|
|
153
|
+
stopped by ${f}: the removal under way stops before its next call to the org; destroy again takes up from the state`),d.abort()});try{let f;try{let $=await e.store.read(r.organizationId,o);if($===void 0||$.serial!==t.state.serial||$.lineage!==t.state.lineage)return i(`The state of ${o} on ${r.alias} changed since the plan of the destruction (another apply or destroy ran, or a cache put back another state). Nothing was deleted: run destroy again.`,[Gr]);f=$}catch($){if($ instanceof L)return i($.message,[tt($).code]);throw $}let h=[],g=[],m=[],w=!1,y,v;for(let[$,j]of a.entries()){if(u!==void 0||y!==void 0){v??=$;break}let A=jr(e.locksDir,r.organizationId,e.lockOptions);if(A!==void 0){e.say(Sn(A).message),m.push(1),v=$;break}let P=t.acceptAutomation||s.checked.file.resources[j]?.accept?.automation===!0,D=await Nc(e,f,{resource:j,action:"delete",target:r,includeChanged:t.includeChanged,sweep:t.sweep,acceptAutomation:P,ends:{whole:"destroyed",left:"partial"}},d.signal);if(f=D.state,h.push(...D.steps),w||=D.wrote,ve(D.code)){y=D.code,v=$+1;break}if(m.push(D.code),D.code!==0&&D.code!==3){v=$+1;break}}for(let $ of v!==void 0?a.slice(v):[])g.push({resource:$,why:u!==void 0||y!==void 0?"the destroy was stopped before it":"a removal before it was refused or failed: its records would be kept for it"});let b=Object.values(f.resources).every($=>$.status==="destroyed"),k=[];if(b&&v===void 0){e.say(bO(o,r.alias,Object.values(f.resources).map($=>$.kind)));for(let{step:$,checkpoint:j}of Jr(f)){let A=await Bt(e,{org:{alias:r.alias,kind:r.kind},checkpoint:j,why:"the environment it was taken of is taken back"},d.signal);k.push(A),A.exitCode===0&&(f=await e.store.update(f,P=>et(P,$,void 0)))}}let E=u!==void 0?xe(u):y!==void 0?y:(()=>{let $=hn(m);return $===1&&w?3:$})();return{result:{plan:n,steps:h,...k.length>0?{checkpoints:k}:{},...g.length>0?{skipped:g}:{},status:ko(E),state:{serial:f.serial}},exitCode:E}}finally{l(),c.lock.release()}}import{readFileSync as RO}from"node:fs";var SO="taken back by a destroy: none of the org's records is its",$O="taken back by a destroy, which deleted its store and left its records masked: a masking creates no record",xy="a masking creates no record: it writes over those the org holds that its condition selects",Ly="a users resource creates no record of its own: it sets up users the org holds, named here";function AO(e,t,n){if(e?.summary===void 0)return{refusal:"its last run stopped before it answered: it names no user"};try{let r=RO(n.store.fileOf(t.organizationId,t.env,e.summary),"utf8");return{users:yp(Vt(r))}}catch(r){if(r instanceof de||r instanceof Error)return{refusal:`its last run's summary does not read: ${r.message}`};throw r}}var OO={applying:"its last run was stopped part way",partial:"its last run was partial",failed:"its last run failed",destroying:"a removal of it was stopped part way"};function Bc(e){return`${OO[e]??e}: it names no record until it is applied whole \u2014 apply again`}function Fy(e,t,n){let r=e.filter(o=>o.env===t&&(o.state?.org.alias===n||o.organizationId.slice(0,15)===n.slice(0,15)));if(r.length>1){let o=r.map(i=>`${i.organizationId}, written ${i.state?.updatedAt??"?"}`).join("; ");return{refusal:{code:"TWO_STATES",message:`${r.length} states of ${t} on this machine are of ${n}: ${o} \u2014 an alias reused for another org. Give --org the Organization Id of the one meant.`,exit:1}}}let[s]=r;return s===void 0?{refusal:{code:"NO_STATE",message:`This machine keeps no state of ${t} on ${n}: nothing was applied to it from here, or the journal directory of the apply was not restored. output reads the state alone, and reaches no org.`,exit:1}}:s.state===void 0?{refusal:{code:"STATE_DAMAGED",message:`${s.damaged??"The state does not read."} Nothing was read.`,exit:1}}:{state:s.state}}async function Uc(e,t){let n={organizationId:e.org.organizationId,env:e.env,target:e.org.alias??e.org.organizationId},r=kc(Object.keys(e.resources),i=>e.resources[i]?.dependsOn??[]),s={},o=!0;for(let i of r){let a=e.resources[i];if(a===void 0)continue;let c=a.runs.at(-1),d={kind:a.kind,status:a.status,...c!==void 0?{run:c.n}:{},records:{}};if(a.status==="destroyed"){s[i]={...d,why:a.kind==="mask"?$O:SO};continue}if(a.status!=="applied"&&(o=!1),a.kind==="mask"){s[i]={...d,masked:Object.fromEntries((c?.objects??[]).map(l=>[l.objectApiName,l.masked??0])),...c?.snapshotId!==void 0?{snapshotId:c.snapshotId}:{},why:a.status==="applied"?xy:`${Bc(a.status)}; ${xy}`};continue}if(a.kind==="users"){let l=[...a.runs].reverse().find(h=>h.takenBack!==!0),f=AO(l,n,t);"refusal"in f&&(o=!1),s[i]={...d,..."users"in f?{users:f.users}:{},why:"refusal"in f?f.refusal:a.status==="applied"?Ly:`${Bc(a.status)}; ${Ly}`};continue}if(a.status!=="applied"){s[i]={...d,why:Bc(a.status)};continue}if(c===void 0||c.takenBack===!0){o=!1,s[i]={...d,why:"it holds no run whose records are in the org"};continue}let u=await Cc(c,n,t);if("refusal"in u){o=!1,s[i]={...d,why:u.refusal};continue}s[i]={...d,records:Object.fromEntries(u.created)}}return{output:{env:e.env,org:{organizationId:e.org.organizationId,kind:e.org.kind,...e.org.alias!==void 0?{alias:e.org.alias}:{},...e.org.host!==void 0?{host:e.org.host}:{}},state:{serial:e.serial,updatedAt:e.updatedAt},resources:s},whole:o}}function My(e){let{org:t}=e,n=t.kind==="sandbox"?ke(t.host):void 0,r=[`${e.env} on ${t.alias??t.organizationId} (${t.kind}${n!==void 0?` ${n}`:""}, ${t.organizationId}): state serial ${e.state.serial}, written ${e.state.updatedAt}`];for(let[s,o]of Object.entries(e.resources)){r.push(` ${s} ${o.kind}, ${o.status}`+(o.run!==void 0?`, run ${o.run}`:""));for(let[i,a]of Object.entries(o.records))r.push(` ${i} ${a.length>0?a.join(" "):"none"}`);for(let[i,a]of Object.entries(o.masked??{}))r.push(` ${i} ${a} masked`);for(let i of o.users??[])r.push(` User ${i.username} ${i.userId}`);o.snapshotId!==void 0&&r.push(` snapshot ${o.snapshotId}, taken first`),o.why!==void 0&&r.push(` ${o.why}`)}return r}var zy={reset:"after",destroy:"before"};function Kc(e,t){let n=zy[e],r=t?.checkpoints?.[n];return r!==void 0?{step:n,checkpoint:r}:void 0}function Wc(e){let t=e.resolved.checked.file.name,{alias:n}=e.target,r=a=>({code:"NO_CHECKPOINT",message:`${a} Nothing was written.`,exit:1}),s=e.verb==="reset"?"reset":"destroy --rewind",o=e.state;if(o===void 0)return r(`This machine keeps no state of ${t} on ${n}: ${s} rewinds the org to a checkpoint its state names. Restore the journal directory of the apply, or apply first.`);if(Kc(e.verb,o)===void 0)return r(e.verb==="reset"?`The state of ${t} on ${n} names no checkpoint taken after an apply: the file asks none (checkpoint.after), or the last apply did not take it. Apply with checkpoint.after in the file, then reset.`:`The state of ${t} on ${n} names no checkpoint taken before its first apply: the file asked none (checkpoint.before: true) when it was first applied. destroy without --rewind takes back what the environment wrote.`);let i=Object.entries(o.resources).filter(([,a])=>a.kind==="mask");if(e.verb==="destroy"&&i.length>0)return{code:"MASKED",message:`The state of ${t} on ${n} names mask resources (${i.map(([a])=>a).join(", ")}): the checkpoint taken before the first apply holds the values they wrote over, and a rewind to it would put them back into the org. destroy never unmasks: destroy without --rewind takes back what the environment wrote, and leaves its maskings as they are. Nothing was written.`,exit:1};if(e.verb==="reset"){let a=Object.entries(o.resources).filter(([,c])=>c.status!=="applied"&&c.status!=="destroyed");if(a.length>0)return r(`${a.map(([c,d])=>`${c} is ${d.status}`).join(", ")}: the last apply did not end whole, and the checkpoint taken after the apply before it no longer holds the environment the state names. Apply again, then reset.`)}}async function _y(e,t,n){let r=Kc(t.verb,t.state);if(r===void 0)return{refusal:"no checkpoint to rewind to"};e.say(`checkpoint ${r.checkpoint}: reading what a rewind to it would do`);let s=await e.runner(we,pi({org:t.target.alias,store:ie(e.journalDir),checkpoint:r.checkpoint,dryRun:!0,acceptAutomation:t.acceptAutomation,acceptEmails:t.acceptEmails,acceptNoUndo:t.acceptNoUndo,acceptUnseen:t.acceptUnseen}),n);return Tu(s)}var xt=e=>e.toLocaleString("en-US");function qy(e,t){let{alias:n}=e.target,r=`it deletes ${xt(t.toDelete)} record(s) created since, gives ${xt(t.toGiveBack)} their values back and brings ${xt(t.toBringBack)} back from the recycle bin \u2014 whoever made these changes`+(Yr(t.lastChangedBy)!==""?`, last changed by ${Yr(t.lastChangedBy)}`:"");return e.verb==="reset"?`Type ${n} to reset it to '${t.checkpoint.name}', as ${e.resolved.checked.file.name} was applied: ${r}:`:`Type ${n} to rewind it to before ${e.resolved.checked.file.name} was first applied: ${r}; the environment's checkpoints are then deleted, and this is not undone:`}function jO(e){return{...e,resources:Object.fromEntries(Object.entries(e.resources).map(([t,n])=>[t,{...n,status:"destroyed",runs:n.runs.map(r=>({...r,takenBack:!0}))}]))}}async function By(e,t,n){let{target:r,resolved:s,verb:o}=t,i=s.checked.file.name,a=Kc(o,t.state),c={env:i,org:{organizationId:r.organizationId,kind:r.kind,alias:r.alias},verb:o,checkpoint:{step:zy[o],id:a?.checkpoint??"",...n!==void 0?{name:n.checkpoint.name,takenAt:new Date(n.checkpoint.takenAt).toISOString()}:{}},...n!==void 0?{preview:{toDelete:n.toDelete,toGiveBack:n.toGiveBack,toBringBack:n.toBringBack,lastChangedBy:n.lastChangedBy}}:{}},d=(w,y)=>({result:{...c,exitCode:1,status:"failure",undo:{offered:!1,why:"nothing was rewound"},refusal:w,state:{serial:y}},exitCode:1}),u=Wc(t);if(u!==void 0||a===void 0||t.state===void 0)throw new Error(u?.message??"There is no checkpoint to rewind to.");let l=t.state,f=Qe(e.locksDir,r.organizationId,{operation:o,env:i,alias:r.alias},e.lockOptions);if("busy"in f)return d(nt(f.busy).message,l.serial);let h=new AbortController,g,m=(e.onStop??Ge)(w=>{g=w,e.say(`
|
|
154
|
+
stopped by ${w}: the rewind stops before its next call to the org, and leaves its journal: run this again to take it up`),h.abort()});try{let w;try{let $=await e.store.read(r.organizationId,i);if($===void 0||$.serial!==l.serial||$.lineage!==l.lineage)return d(`The state of ${i} on ${r.alias} changed since it was read (another apply, destroy or reset ran, or a cache put back another state). Nothing was written: run this again.`,$?.serial??l.serial);w=$}catch($){if($ instanceof L)return d($.message,l.serial);throw $}e.say(`${o==="reset"?"reset":"destroy --rewind"}: rewinding ${r.alias} to checkpoint ${a.checkpoint}`);let y=await e.runner(we,pi({org:r.alias,store:ie(e.journalDir),checkpoint:a.checkpoint,dryRun:!1,acceptAutomation:t.acceptAutomation,acceptEmails:t.acceptEmails,acceptNoUndo:t.acceptNoUndo,acceptUnseen:t.acceptUnseen}),h.signal),v=Lu(y),b=g!==void 0?xe(g):v.exitCode,k=[];if(o==="destroy"&&b===0){w=await e.store.update(w,jO);for(let{step:$,checkpoint:j}of Jr(w)){let A=await Bt(e,{org:{alias:r.alias,kind:r.kind},checkpoint:j,why:"the environment it was taken of is taken back"},h.signal);k.push(A),A.exitCode===0&&(w=await e.store.update(w,P=>et(P,$,void 0)))}e.say(`every record of ${i} is taken back from ${r.alias}, with what anyone changed since its first apply: the state keeps it as destroyed, and the next apply creates it again`)}let E=Fu({verb:o,alias:r.alias,checkpoint:a.checkpoint,journalDir:e.journalDir,deleted:k.length>0&&k.every($=>$.exitCode===0)},v),S=v.refusal===void 0?void 0:v.refusal.code==="RECREATE"?`${v.refusal.message} ${o==="reset"?"reset":"destroy --rewind"} never makes records again with new Ids, which the state would no longer name: rewind with sandforge checkpoint itself, then apply again.`:v.refusal.message;return{result:{...c,exitCode:b,status:g!==void 0?"cancelled":v.status,...v.answer!==void 0?{answer:v.answer}:{},undo:E,...S!==void 0?{refusal:S.slice(0,8e3)}:{},...k.length>0?{deleted:k}:{},state:{serial:w.serial}},exitCode:b}}finally{m(),f.lock.release()}}function Uy(e){let t=e.verb==="reset"?"reset":"destroy --rewind",n=[""],r=e.answer;if(r?.deleted!==void 0){let s=(r.residual??[]).reduce((o,i)=>o+i.count,0);n.push(` rewind to ${e.checkpoint.id}: exit ${e.exitCode}, ${e.status} ${xt(r.deleted.done)} deleted, ${xt(r.givenBack?.done??0)} given back, ${xt(r.broughtBack?.done??0)} brought back`+(s>0?`, ${xt(s)} still differ`:""))}for(let s of e.deleted??[])n.push(s.exitCode===0?` checkpoint ${s.checkpoint??""} deleted`:` checkpoint ${s.checkpoint??""} kept: ${s.refusal??""}`);return e.refusal!==void 0&&n.push(`${t} refused: ${e.refusal}`),n.push(Mu(e.undo)),n.push(`${t}: ${e.status}; state serial ${e.state.serial}`),n}import{randomBytes as IO}from"node:crypto";import{existsSync as CO,readFileSync as DO,statSync as PO}from"node:fs";import{open as NO,rename as TO,rm as xO}from"node:fs/promises";import{dirname as LO,resolve as Vc}from"node:path";var Vy=1440*6e4;function Hy(e){let t={};for(let[o,i]of Object.entries(e.dryRuns))"answer"in i&&i.answer.tool===se&&(t[o]=i.answer.seed);let{host:n,...r}=e.plan.org,s=n!==void 0&&e.listedByMyDomain===!0?e.plan:{...e.plan,org:r};return Bo.parse({savedPlan:1,sandforgeVersion:e.sandforgeVersion,madeAt:e.madeAt,file:{digest:e.digest},state:e.state===void 0?{found:!1}:{found:!0,serial:e.state.serial,lineage:e.state.lineage},line:e.line,seeds:t,plan:s})}function Jy(e,t,n){let r=LO(Vc(t));if(!CO(r)||!PO(r).isDirectory())return{code:"BAD_LINE",message:`--out ${Vc(t)}: its folder ${r} is not there. Nothing was read.`,exit:2};if(n)return;let s=yn(e,t);if(s!==void 0)return{code:"PLAN_IN_REPOSITORY",message:`--out ${Vc(t)} is inside the repository ${s} that holds the file: a plan names the org by its Organization Id, its state, and the users who changed its records since, and committed with the project it would publish them. Keep it outside \u2014 in CI, in $RUNNER_TEMP, handed to the job that applies as an artifact \u2014 or give --out-in-repository for a folder of it that is never committed. Nothing was read.`,exit:2}}async function Yy(e,t){let n=`${e}.${IO(6).toString("hex")}.tmp`,r=await NO(n,"wx",si);try{await r.writeFile(`${JSON.stringify(t,null,2)}
|
|
155
|
+
`,"utf8"),await r.sync()}finally{await r.close()}try{await TO(n,e)}catch(s){throw await xO(n,{force:!0}),s}}function Gy(e){let t=o=>({refusal:{code:"PLAN_UNREAD",message:`--plan ${e} ${o}. Nothing was read or written.`,exit:2}}),n;try{n=DO(e,"utf8")}catch(o){return t(`cannot be read: ${o instanceof Error?o.message:String(o)}`)}let r;try{r=JSON.parse(n)}catch{return t("is not JSON: it is no plan plan --out kept")}let s=Bo.safeParse(r);if(!s.success){let o=s.error.issues[0],i=o?.path.map(String).join(".")||"the plan";return t(`is no plan plan --out kept (${i}: ${o?.message??"refused"})`)}return{saved:s.data}}function un(e,t){return{code:"PLAN_STALE",message:`The plan kept in ${e} ${t}. Nothing was written: plan again.`.slice(0,8e3),exit:1}}function Qy(e,t,n){if(e.plan.refusal!==void 0)return{code:"PLAN_REFUSED",message:`The plan kept in ${t} was refused when it was made: ${e.plan.refusal} Nothing was written: plan again.`.slice(0,8e3),exit:1};if(e.plan.quick===!0)return un(t,"was made with --quick, which counts nothing an apply is held to");if(e.sandforgeVersion!==n.sandforgeVersion)return un(t,`was made by SandForge ${e.sandforgeVersion}, and this one is ${n.sandforgeVersion}, which may read the file and the org otherwise`);if(n.now-Date.parse(e.madeAt)>Vy)return un(t,`was made at ${e.madeAt}, more than a day ago`)}function FO(e){return e.found?`the state at serial ${e.serial}`:"no state"}function Xy(e,t,n){let r=e.plan.org;if(!Ee(r.organizationId,n.target.organizationId))return{code:"PLAN_OTHER_ORG",message:`The plan kept in ${t} was made for ${r.alias??r.organizationId} (${r.organizationId}), and ${n.target.alias} is ${n.target.organizationId}: a plan is applied to the org it was made for. Nothing was written.`,exit:1};if(r.host!==void 0&&r.host!==n.target.host)return{code:"PLAN_OTHER_ORG",message:`The plan kept in ${t} was made for ${r.alias??r.organizationId} on ${r.host}, and ${n.target.alias} answers on ${n.target.host??"no My Domain host"}: a plan is applied to the org it was made for. Nothing was written.`,exit:1};if(e.file.digest!==n.digest)return un(t,"was made from another file: the file, or a variable or an alias it reads, changed since");let s=n.state,o=e.state;if(!(o.found===(s!==void 0)&&(!o.found||s!==void 0&&s.serial===o.serial&&s.lineage===o.lineage))){let a=s===void 0?"none":o.found&&s.lineage!==o.lineage?`at serial ${s.serial}, made again since`:`at serial ${s.serial}`;return un(t,`was made against ${FO(o)}, and the state is now ${a}: an apply or a destroy ran since, or a cache put back another state`)}}function Ky(e){return JSON.stringify([e.kind,e.action,e.objects.map(t=>[t.object,t.wouldCreate,t.atMost,t.present,t.gone,t.changed]),(e.draws??[]).map(t=>[t.lookup,t.from,t.object,t.parents])])}function Wy(e){if(e===void 0)return"nothing of it";let t=Ac(e),n=(e.draws??[]).map(s=>s.parents!==void 0?`${s.lookup} under ${s.parents} ${s.object} record(s) of ${s.from}`:`${s.lookup} under the ${s.object} records ${s.from} creates first`).join(", "),r=[t,n].filter(Boolean).join("; ");return`${e.action}${r?` (${r})`:""}`}function Po(e){let t=(e.checkpoints??[]).map(n=>`${n.step==="before"?"before the first write":"once applied"} '${n.name}'`+(n.refusal!==void 0?", refused":""));return t.length>0?t.join(", "):"none"}function No(e){let t=e.drift;return t===void 0?"not compared":t.unread!==void 0?"not read":t.differs?`differs, ${t.toDelete??0} to delete \xB7 ${t.toGiveBack??0} to give back \xB7 ${t.toBringBack??0} to bring back`:"nothing differs"}function Zy(e,t){let n=[],r=[...new Set([...e.actions,...t.actions].map(o=>o.resource))];for(let o of r){let i=e.actions.find(c=>c.resource===o),a=t.actions.find(c=>c.resource===o);i!==void 0&&a!==void 0&&Ky(i)===Ky(a)||n.push(`${o}: planned ${Wy(i)}, now ${Wy(a)}`)}let s=o=>o.actions.map(i=>i.resource).join(", ");return n.length===0&&s(e)!==s(t)&&n.push(`the order of the resources: planned ${s(e)}, now ${s(t)}`),Po(e)!==Po(t)&&n.push(`the checkpoints it takes: planned ${Po(e)}, now ${Po(t)}`),No(e)!==No(t)&&n.push(`the whole org against the checkpoint after the last apply: planned ${No(e)}, now ${No(t)}`),n}function ew(e,t){return un(e,`is not what the org holds now, read again: ${t.join("; ")}`)}function tw(e,t){let n=new Date(Date.parse(t.madeAt)+Vy).toISOString();return`plan kept in ${e}, for apply --plan until ${n}`}function nw(e,t){return`the plan kept in ${e} at ${t.madeAt} holds: the org, its state, the file and every count are as it planned them`}var BO=`sandforge env \u2014 apply a sandforge.yaml to an org: the data an environment needs, declared in
|
|
153
156
|
your repository, created, kept and taken back, without the editor.
|
|
154
157
|
|
|
155
158
|
Usage:
|
|
@@ -176,8 +179,12 @@ Commands:
|
|
|
176
179
|
files the journal directory keeps, every resource marked for the next plan to
|
|
177
180
|
replace; a damaged state is set aside, kept; reads the org's kind, writes nothing to it
|
|
178
181
|
output print what an apply created in the org: per resource, the ids of its records by
|
|
179
|
-
object, as its runs' files on this machine name them
|
|
180
|
-
applied by or the Organization Id; reaches
|
|
182
|
+
object, as its runs' files on this machine name them, and the users a users
|
|
183
|
+
resource set up; --org, the alias it was applied by or the Organization Id; reaches
|
|
184
|
+
no org
|
|
185
|
+
audit read the org, writing nothing to it: whether it delivers email, its scheduled jobs
|
|
186
|
+
against the inventory kept before its refresh, and the endpoints that still name
|
|
187
|
+
production; each part the file's audits do not turn off
|
|
181
188
|
|
|
182
189
|
Required:
|
|
183
190
|
--org <alias> sf CLI alias of the org to fill (validate and state: not needed;
|
|
@@ -194,7 +201,8 @@ plan:
|
|
|
194
201
|
--quick skip the dry runs and the removal previews: no counts, and no word
|
|
195
202
|
on what the org holds
|
|
196
203
|
--replace <resource>, --replace-drifted, --accept-automation, --accept-emails,
|
|
197
|
-
--accept-no-state
|
|
204
|
+
--accept-user-emails, --accept-no-state
|
|
205
|
+
plan what apply would do with them; --out keeps them with the plan
|
|
198
206
|
--out <file> keep the plan in <file>, for apply --plan: outside the repository
|
|
199
207
|
that holds the file, unless --out-in-repository
|
|
200
208
|
--out-in-repository keep it inside that repository all the same, in a folder of it
|
|
@@ -213,8 +221,16 @@ apply:
|
|
|
213
221
|
sends some; without it their dry runs block the plan, and
|
|
214
222
|
--accept-automation and accept: { automation: true } never stand
|
|
215
223
|
for it
|
|
224
|
+
--accept-user-emails let Salesforce email the people whose address a users resource asks
|
|
225
|
+
back: the confirmation link of each, a system email, which leaves
|
|
226
|
+
under System email only too; without it the plan refuses the
|
|
227
|
+
apply (USERS_EMAILS_NOT_ACCEPTED), and no file accepts it
|
|
216
228
|
--accept-no-state apply to a Developer Edition or a sandbox this machine has no state
|
|
217
229
|
of: records an earlier apply left there would be created twice
|
|
230
|
+
--handoff <file.md> write the handoff note there once the apply ended, outside the
|
|
231
|
+
repository that holds the file unless --out-in-repository; without
|
|
232
|
+
it, a file whose audits ask handoff: true keeps it in handoff/ of
|
|
233
|
+
the journal directory, its owner's alone
|
|
218
234
|
--yes do not ask; without it and with no terminal, stop at the question,
|
|
219
235
|
exit 2, having written nothing
|
|
220
236
|
destroy:
|
|
@@ -243,6 +259,11 @@ reset:
|
|
|
243
259
|
deletes
|
|
244
260
|
--accept-unseen as for destroy --rewind
|
|
245
261
|
--yes as for apply
|
|
262
|
+
audit:
|
|
263
|
+
--save keep the scheduled jobs read, in audits/ of the journal directory by
|
|
264
|
+
the org's host, to compare with after its next refresh
|
|
265
|
+
--fail-on-findings exit 3 on a job gone or run as a user who can no longer, an endpoint
|
|
266
|
+
that names production, or a deliverability open to all email
|
|
246
267
|
|
|
247
268
|
The file holds no secret: org credentials stay with the sf CLI. A value comes from the environment
|
|
248
269
|
only where the file writes { env: NAME }. The org to fill is never in the file. A resource's
|
|
@@ -283,6 +304,20 @@ only copy of the values masked: putting them back from a snapshot, with sandforg
|
|
|
283
304
|
your own act, before a destroy, and plan and destroy give the line. A file with a mask resource
|
|
284
305
|
takes no checkpoint.before, and destroy --rewind is refused while the state names one.
|
|
285
306
|
|
|
307
|
+
A users resource hands a sandbox back to its testers, through sandforge users: per user, by
|
|
308
|
+
its production username or the sandbox's, its address the copy put under .invalid asked back,
|
|
309
|
+
an activation, a freeze, a profile, permission sets, their groups, groups and queues. It is
|
|
310
|
+
applied before every other resource, whatever the file's order, and taken back after them all;
|
|
311
|
+
its replace converges from its last run, never everything taken back then set up again. An
|
|
312
|
+
address asked back awaits its owner's click on the link Salesforce mails to it; the plan sums
|
|
313
|
+
those emails, which the line alone accepts (--accept-user-emails). A destroy takes back what the
|
|
314
|
+
environment added and puts each user back as it was, never an address, never a user deleted.
|
|
315
|
+
|
|
316
|
+
A replay resource replays a checkpoint through sandforge checkpoint replay: by its id, the
|
|
317
|
+
newest of a name \u2014 of this sandbox before its refresh, or of the org its role from: names \u2014,
|
|
318
|
+
or an exported file whose key the variable keyEnv names. The plan resolves it to one checkpoint
|
|
319
|
+
of this machine, which the replay writes from; one it does not find blocks the apply.
|
|
320
|
+
|
|
286
321
|
A seed relation may draw its parents from the records another resource created:
|
|
287
322
|
parents: { from: <resource>.<Object> }. They are read from that resource's own run, handed to
|
|
288
323
|
the seed by their ids, at most 2,000 or the relation's limit, and counted exactly once that
|
|
@@ -303,9 +338,16 @@ then exits 3. It names what the runs kept: a record deleted since is still named
|
|
|
303
338
|
reads.
|
|
304
339
|
|
|
305
340
|
A production org is refused before anything is read, exit 1. No flag lifts it. A sandbox is
|
|
306
|
-
written to only when the file lists
|
|
307
|
-
|
|
308
|
-
|
|
341
|
+
written to only when the file lists it under targets.sandboxes, by its Organization Id or by its
|
|
342
|
+
My Domain ({ myDomain: acme--uat }, which a refresh keeps), and allows the sandbox kind; scratch
|
|
343
|
+
orgs and Developer Edition orgs need no listing. A scratch org is told apart by the Dev Hub the
|
|
344
|
+
sf CLI names for it; one it names none for is taken for a sandbox. A sandbox whose state this
|
|
345
|
+
machine kept under its Organization Id before a refresh, on the same host, is applied anew
|
|
346
|
+
without --accept-no-state: the plan says the state it sets aside, kept.
|
|
347
|
+
|
|
348
|
+
audits: in the file asks what an apply reads once it wrote, after checkpoint.after: never a
|
|
349
|
+
write, and never what the apply ends with \u2014 an audit not read is said not read, with why.
|
|
350
|
+
handoff: true has the apply write a note of what it did and what is left to do.
|
|
309
351
|
|
|
310
352
|
What apply keeps of the org is the state: ids, counts and dates, never a record's values, in
|
|
311
353
|
env/<Organization Id>/<name>/ of the folder SANDFORGE_JOURNAL_DIR names (default: ~/.sandforge),
|
|
@@ -325,7 +367,9 @@ protected org, a state of another org, no state without --accept-no-state, anoth
|
|
|
325
367
|
org under way, a removal or a frozen load refused for automation without --accept-automation,
|
|
326
368
|
more API requests, storage or emails than the org has left, emails the org delivers or would not
|
|
327
369
|
say it withholds without --accept-emails (a clone's, a seed's or a load's EMAILS_NOT_ACCEPTED, a
|
|
328
|
-
rewind's EMAILS_DELIVERED),
|
|
370
|
+
rewind's EMAILS_DELIVERED), emails to people without --accept-user-emails
|
|
371
|
+
(USERS_EMAILS_NOT_ACCEPTED), a refusal of sandforge users (USERS_*), a checkpoint a replay
|
|
372
|
+
names that this machine does not keep (REPLAY_CHECKPOINT_NOT_FOUND), a
|
|
329
373
|
checkpoint the file asks that its script refuses, a
|
|
330
374
|
production source without anonymize or accept: { realData: true }, no checkpoint to reset or
|
|
331
375
|
rewind to, a rewind refused for want of --accept-automation, --accept-no-undo or
|
|
@@ -334,22 +378,24 @@ names that no longer holds, is a day old or was refused when it was made, no sta
|
|
|
334
378
|
read, a state recover of a state that reads, of another org or of a later SandForge, of a summary
|
|
335
379
|
of another org or that does not read, of two runs of one rank, or of no run at all \u2014, or nothing
|
|
336
380
|
written; 2 a bad command line, a file that does not validate, a variable not set, the journal
|
|
337
|
-
directory or a dataset inside the file's repository, --out inside it, a file --plan
|
|
338
|
-
is no plan, a question with no terminal (give --yes); 3 partial (apply: a resource
|
|
381
|
+
directory or a dataset inside the file's repository, --out or --handoff inside it, a file --plan
|
|
382
|
+
names that is no plan, a question with no terminal (give --yes); 3 partial (apply: a resource
|
|
383
|
+
partial, or
|
|
339
384
|
failed after others wrote; destroy: records left, each with why; reset and destroy --rewind:
|
|
340
385
|
records still differ; plan with --fail-on-change or --fail-on-drift: changes or drift found;
|
|
341
|
-
output: a resource not applied whole, or whose records cannot be read
|
|
386
|
+
output: a resource not applied whole, or whose records cannot be read; audit with
|
|
387
|
+
--fail-on-findings: findings); 4 unstable (a forge run's
|
|
342
388
|
or a frozen load's verification found records still changing; reset and destroy --rewind: someone
|
|
343
389
|
changed records during it); 130, 143, 129 Ctrl-C, SIGTERM or SIGHUP stopped it \u2014 run it again: it
|
|
344
390
|
takes up from the state.
|
|
345
|
-
`,
|
|
346
|
-
`),process.exit(2)}function
|
|
347
|
-
${t.map(n=>` ${
|
|
348
|
-
`)}`,issues:t.map(
|
|
349
|
-
`).map(t=>t.trim()).filter(Boolean).at(-1)??"it said nothing"}function
|
|
350
|
-
`,{mode:384}))}}let
|
|
351
|
-
`,{mode:384}),r(`${h.name}: dry run`);let R=i[h.name],j=Vt(Qu(h,{target:l.alias,templateFile:k,runId:hr(y,h.name,en(u?.resources[h.name])),replace:w==="replace"&<(h.kind),acceptAutomation:a||c.checked.file.resources[h.name]?.accept?.automation===!0,...R!==void 0?{seed:R}:{},...b!==void 0?{storeFile:b}:{},...$!==void 0?{goneFirstFile:$}:{},...h.kind==="mask"?{store:wt(m,`${h.name}.dataops`)}:{}}),o),D=await e.runner(j.script,j.args,s);try{f[h.name]={answer:ed(h.kind,D.stdout)}}catch(N){if(!(N instanceof re))throw N;let P=WE(D.stdout,j.script);f[h.name]={failed:`exit ${D.code}: ${za(D.stderr)}`,...P?{refused:P}:{}}}}}finally{LE(m,{recursive:!0,force:!0})}return f}async function Us(e,t,n){let r=new AbortController,s,i=(e.onStop??Le)(o=>{s=o,r.abort()});try{let o=await n(r.signal);if(s!==void 0)throw new Z({refusal:{code:"STOPPED",message:`stopped by ${s} while ${t}: nothing was written`}},be(s));return o}finally{i()}}function em(e){let{resolved:t,state:n,store:r,target:s}=e,i=new Set([...t.resources.filter(o=>o.kind==="mask").map(o=>o.name),...Object.entries(n?.resources??{}).filter(([,o])=>o.kind==="mask").map(([o])=>o)]);return Object.fromEntries([...i].map(o=>[o,r.sasOf(s.organizationId,t.checked.file.name,jt(o))]))}async function Jh(e,t,n,r,s={}){let i={organizationId:e.target.organizationId,kind:e.target.kind,alias:e.target.alias},o={resolved:e.resolved,org:i,state:e.state,replace:t.replace,replaceDrifted:t.replaceDrifted,warnings:e.warnings,maskStores:em(e),...e.noState!==void 0?{refusal:e.noState.message,refusalCodes:[e.noState.code]}:{}};if(t.quick)return{plan:Ra(o),dryRuns:{}};let a=await Zh(e,{includeChanged:!1,acceptAutomation:t.acceptAutomation,refresh:!0},n,r),c=await XE(e,n,r),l=ba({...o,previews:a,...c?{drift:c}:{}}),u=new Set(l.filter(m=>m.action==="create"||m.action==="replace").map(m=>m.resource)),d=await GE(e,u),f=await QE(e,l,d,n,r,s,t.acceptEmails,t.acceptAutomation),g=await VE(e.reached.conn),y=await ZE(e,l.some(wa),n,r);return{plan:Ra({...o,previews:a,dryRuns:f,budget:g,...c?{drift:c}:{},...y?{checkpointEstimate:y}:{},draws:Object.fromEntries(Object.entries(d).map(([m,h])=>[m,{draws:h.draws,refusals:h.refusals}]))}),dryRuns:f}}async function XE(e,t,n){let r=e.state?.checkpoints?.after;if(r===void 0||n.aborted)return;t(`checkpoint ${r}: comparing the whole org with it`);let s=await e.runner(ce,Jc({org:e.target.alias,store:ye(e.journalDir),checkpoint:r}),n);return tl(r,s)}async function ZE(e,t,n,r){let s=e.resolved.checked.file;if(br(s,e.state,t).length===0||r.aborted)return;n("checkpoint: estimating what a take of the org costs");let i=await e.runner(ce,Wc({org:e.target.alias,store:ye(e.journalDir),...kr(s)}),r);return Qc(i)}function eS(e,t){let n=lc(e,"sandforge-env"),r=!1;return async()=>{try{return await n.serverTime()}catch(s){return r||(r=!0,t(`the org did not say its time (${s instanceof Error?s.message:String(s)}): the state's spans are on this machine's clock`)),new Date().toISOString()}}}function tS(e){if(e.kind==="seed"){let s=It(e).map(o=>`${o.object} ${o.count??""}`).join(", "),i=(e.draws??[]).map(o=>`${o.relation.childObject}.${o.relation.lookupField} under the ${o.relation.parentObject} records ${o.from} created`);return i.length>0?`${s}; ${i.join(", ")}`:s}if(e.kind==="frozen"){let{path:s,version:i,digest:o}=e.dataset,a=typeof s=="string"?s:`$${s.env}`;return`the Frozen dataset ${i} at ${a} (${o.slice(0,19)}\u2026), as ${e.configFile} configures its load`}if(e.kind==="mask"){let s="set"in e.source?`the rule set ${e.source.set}`:`the template ${e.source.template}`;return`masks ${e.object!==void 0?`${e.object}${e.where!==void 0?` WHERE ${e.where}`:""}`:`every object its rules mask (${It(e).map(o=>o.object).join(", ")})`} with ${s}, ${e.rules.rules.length} rule(s)`}let t=(s,i)=>i!==void 0?`${s} WHERE ${i}`:s,n=e.wholeOrg?.fit,r=e.wholeOrg?n!==void 0?`a sample of the whole org that fits the org to fill${n.withinMB!==void 0?`, within ${n.withinMB} MB`:""}`:"the whole org":e.tables!==void 0?`tables ${e.tables.map(s=>t(s.object,s.where)).join(", ")}`:e.record?.id!==void 0?`record ${e.record.id}`:`the one record of ${t(e.record?.object??"",e.record?.where)}`;return`cloned from the ${e.source} org: ${r}`}function nS(e,t){let n=Ys(e.file),r=Jn(n,Te(e.file));if("refusals"in r){t(`${e.file} does not validate:`);for(let d of r.refusals)t(` ${da(d)}`);return{answer:{file:e.file,valid:!1,issues:r.refusals.map(qa),warnings:[]},code:2}}let{file:s,order:i,runs:o,variables:a}=r.checked,c=new Set(nh(r.checked,process.env).map(d=>d.name)),l=i.flatMap(d=>{let f=o[d],g=s.resources[d];return f===void 0?[]:[{name:d,kind:f.kind,dependsOn:g!==void 0?fa(d,g):[],...f.kind==="forge"?{source:f.source}:{},objects:It(f)}]}),u=r.checked.warnings.map(qa);t(`${e.file}: valid, the environment ${s.name}`);for(let d of l){let f=o[d.name];t(` ${d.name}: ${f!==void 0?tS(f):""}`+(d.dependsOn.length>0?`, after ${d.dependsOn.join(", ")}`:""))}for(let d of a){let f=d.role!==void 0?`the ${d.role} org`:`the dataset of ${d.resource??""}`;t(` variable ${d.name} (${f}): `+(c.has(d.name)?"not set in this shell":"set"))}for(let d of u)t(`warning: ${d.path}: ${d.message}`);return{answer:{file:e.file,valid:!0,env:s.name,resources:l,variables:a.map(d=>({name:d.name,...d.role!==void 0?{role:d.role}:{},...d.resource!==void 0?{resource:d.resource}:{},set:!c.has(d.name)})),issues:[],warnings:u},code:0}}function rS(e,t,n,r){if(n===void 0&&r===void 0)return`no state kept in ${e}`;let s=n!==void 0&&r!==void 0?`${n} on ${r}`:n??r??"",i=t===0?"":`, which keeps ${t===1?"1 other state":`${t} other states`}: "${ue("env")} state" lists ${t===1?"it":"them"}`;return`no state of ${s} is kept in ${e}${i}. A state kept in another folder is read with SANDFORGE_JOURNAL_DIR set as when it was written \u2014 in a CI job, a folder its cache restores.`}async function sS(e,t,n){let r=t.journalDir??fr(),s=vr({journalDir:r,fileFolder:null});if("refusal"in s)throw ee(Ar(s.refusal,!1));let i=await s.store.sweep(),o;if(e.fileGiven){let u=Jn(Ys(e.file),Te(e.file));if("refusals"in u)throw Ws(e.file,u.refusals);o=u.checked.file.name}let a=e.org,c=await s.store.list(),l=c.filter(u=>(o===void 0||u.env===o)&&(a===void 0||u.state?.org.alias===a||u.organizationId.slice(0,15)===a.slice(0,15)));for(let u of i)n(`expired and deleted: ${u.env} on ${u.alias??u.organizationId}`);l.length===0&&n(rS(s.store.root,c.length,o,a));for(let u of l){let d=u.state;if(d===void 0){n(`${u.env} on ${u.organizationId}: not used \u2014 ${u.damaged??""}`);continue}let f=Object.entries(d.resources).map(([g,y])=>`${g} ${y.status}`).join(", ");n(`${d.env} on ${d.org.alias??d.org.organizationId} (${d.org.kind}, ${d.org.organizationId}): serial ${d.serial}, written ${d.updatedAt}`+(u.expiresAt!==void 0?`, expires ${u.expiresAt}`:"")+(f?`; ${f}`:""))}return{journalDir:r,states:l.map(u=>{let d=u.state;if(d===void 0)return{env:u.env,organizationId:u.organizationId,damaged:u.damaged??"not used"};let f=pi(d);return{env:d.env,organizationId:d.org.organizationId,...d.org.alias!==void 0?{alias:d.org.alias}:{},kind:d.org.kind,serial:d.serial,resources:Object.fromEntries(Object.entries(d.resources).map(([g,y])=>[g,y.status])),updatedAt:d.updatedAt,...f!==void 0?{expiresAt:f}:{}}}),expired:i.map(u=>({env:u.env,organizationId:u.organizationId,...u.alias!==void 0?{alias:u.alias}:{},expiresAt:u.expiresAt}))}}async function iS(e,t,n){let r=Jn(Ys(e.file),Te(e.file));if("refusals"in r)throw Ws(e.file,r.refusals);let s=t.journalDir??fr(),i=pr(Te(e.file),s),o=vr({journalDir:s,fileFolder:Te(e.file)});if("refusal"in o)throw ee(Ar(o.refusal,i!==void 0));for(let u of await o.store.sweep())n(Qh(u));let a=$h(await o.store.list(),r.checked.file.name,e.org??"");if("refusal"in a)throw ee(a.refusal);let{output:c,whole:l}=await Ah(a.state,{store:o.store,journalDir:s});return{answer:c,code:l?0:3}}async function oS(e,t,n){let r=await Qn(e,t,n),s=await kh({store:r.store,journalDir:r.journalDir,locksDir:r.locksDir,sandforgeVersion:Vs(),...t.lockOptions!==void 0?{lockOptions:t.lockOptions}:{}},{resolved:r.resolved,target:r.target});if("refusal"in s)throw ee(s.refusal);for(let i of bh(s.result))n(i);return s.result}async function Ba(e,t,n,r){return e.yes||await(t.ask??(i=>kc(i)))(n)===e.org?!0:(r("Nothing was written: the alias typed is not the org\u2019s."),!1)}function Js(e,t,n){return{runner:e.runner,store:e.store,locksDir:e.locksDir,journalDir:e.journalDir,orgNow:eS(e.reached.conn,n),say:n,sandforgeVersion:Vs(),...t.onStop!==void 0?{onStop:t.onStop}:{},...t.lockOptions!==void 0?{lockOptions:t.lockOptions}:{}}}async function Yh(e,t,n,r,s){let i=await Qn(e,t,r),o={verb:n,resolved:i.resolved,target:i.target,state:i.state,acceptAutomation:e.acceptAutomation,acceptEmails:e.acceptEmails,acceptNoUndo:e.acceptNoUndo,acceptUnseen:e.acceptUnseen},a=xa(o);if(a!==void 0)throw ee(a);for(let u of i.warnings)r(`warning: ${u}`);let c;if(!e.yes){let u=await Us(t,"reading what a rewind would do",d=>jh(Js(i,t,r),o,d));if(!("differs"in u))throw new Z({refusal:{code:"REWIND_REFUSED",message:`${u.refusal} Nothing was written.`}},1);c=u;for(let d of sl(n,i.target.alias,u))r(d);if(u.refusal!==void 0)throw new Z({refusal:{code:u.refusal.code,message:u.refusal.message}},1);if(u.differs&&!await Ba(e,t,Nh(o,u),r))throw new Z({refusal:{code:"DECLINED",message:"Nothing was written."}},1)}let l=await Ih(Js(i,t,r),o,c);for(let u of Dh(l.result))r(u);s(l.result),Fe(l.exitCode)}async function aS(e=process.argv,t={}){let n=UE(e,t.cwd),r=i=>{process[n.json?"stderr":"stdout"].write(`${i}
|
|
352
|
-
`)},s=
|
|
353
|
-
`)};try{switch(n.command){case"validate":{let{answer:
|
|
354
|
-
`),s(
|
|
355
|
-
`),process.exit(1)}));export{
|
|
391
|
+
`,UO=["validate","plan","apply","destroy","reset","state","output","audit"],KO=e=>UO.includes(e),WO={validate:{words:1,switches:["--json"],values:["--file"]},plan:{words:1,switches:["--json","--fail-on-change","--fail-on-drift","--quick","--replace-drifted","--accept-automation","--accept-emails","--accept-user-emails","--accept-no-state","--out-in-repository"],values:["--file","--org","--alias","--replace","--out"]},apply:{words:1,switches:["--json","--replace-drifted","--accept-automation","--accept-emails","--accept-user-emails","--accept-no-state","--out-in-repository","--yes"],values:["--file","--org","--alias","--replace","--plan","--handoff"]},destroy:{words:1,switches:["--json","--include-changed","--sweep","--accept-automation","--accept-emails","--rewind","--accept-no-undo","--accept-unseen","--yes"],values:["--file","--org","--alias"]},reset:{words:1,switches:["--json","--accept-automation","--accept-emails","--accept-no-undo","--accept-unseen","--yes"],values:["--file","--org","--alias"]},state:{words:1,switches:["--json"],values:["--org","--file"]},output:{words:1,switches:["--json"],values:["--org","--file"]},audit:{words:py.words,switches:["--json","--save","--fail-on-findings"],values:["--file","--org","--alias"]}},VO={words:2,switches:["--json"],values:["--file","--org","--alias"]};function dw(e,t){let n=e==="destroy"?"sandforge env":`sandforge env ${e}`;return t!==void 0&&t!==""?`${n}, relayed by ${t}`:n}function HO(e={},t="destroy"){let n=process.env[bt]?.trim();return Kd({...e,relayedBy:dw(t,n)})}function JO(e,t){return async(n,r,s)=>{let o=process.env[bt];process.env[bt]=t;try{return await e(n,r,s)}finally{o===void 0?delete process.env[bt]:process.env[bt]=o}}}function Se(e){process.stderr.write(`${e} Run with --help.
|
|
392
|
+
`),process.exit(2)}function YO(e,t=process.cwd()){let n=e.slice(2);(n.includes("--help")||n.includes("-h"))&&(process.stdout.write(BO),process.exit(0));let r=n[0];if(r===void 0||r.startsWith("-"))return Se("Name the command first: validate, plan, apply, destroy, reset, state, output or audit.");if(!KO(r))return Se(`"${r}" is not a command of sandforge env: validate, plan, apply, destroy, reset, state, output or audit. Nothing was run.`);let s=r==="state"&&n[1]==="recover";kd(n,s?VO:WO[r]);let o=m=>{let w=[];for(let y=1;y<n.length;y++)n[y]===m&&(w.push(n[y+1]??""),y++);return w},i=m=>{let w=o(m);return w.length>1&&Se(`${m} is given ${w.length} times: give it once.`),w[0]},a={};for(let m of o("--alias")){let w=m.indexOf("="),y=w>0?m.slice(0,w):"",v=w>0?m.slice(w+1):"";(y===""||v==="")&&Se(`--alias wants <role>=<alias>, as --alias uat=UAT-ORG, not "${m}".`),y in a&&Se(`--alias gives the role ${y} twice: give it once.`),a[y]=v}let c=i("--org");(r==="plan"||r==="apply"||r==="destroy"||r==="reset"||r==="output"||r==="audit"||s)&&c===void 0&&Se(`${s?"state recover":r} needs --org, the sf CLI alias of the org.`);let d=i("--out");d!==void 0&&n.includes("--quick")&&Se("--out keeps a plan for apply --plan, which a quick plan cannot be: it counts nothing an apply is held to.");let u=i("--handoff");d===void 0&&u===void 0&&n.includes("--out-in-repository")&&Se(r==="apply"?"--out-in-repository goes with --handoff: it says where the note may be kept.":"--out-in-repository goes with --out: it says where the plan may be kept.");let l=i("--plan");if(l!==void 0){let w=["--replace","--replace-drifted","--accept-automation","--accept-emails","--accept-user-emails","--accept-no-state"].filter(y=>n.includes(y));w.length>0&&Se(`${w.join(" and ")}: --plan applies the plan with the switches plan --out was given, kept in it. Give them to plan --out, then apply that plan.`)}let f=n.includes("--rewind");if(f){let m=["--include-changed","--sweep"].filter(w=>n.includes(w));m.length>0&&Se(`${m.join(" and ")} take back records by removal: --rewind takes the whole org back to the checkpoint before the first apply. Give one or the other.`)}else if(r==="destroy")for(let m of["--accept-emails","--accept-no-undo","--accept-unseen"])n.includes(m)&&Se(`${m} goes with --rewind: a destroy by removal is no rewind.`);let h=i("--file"),g=o("--replace");return{command:r,recover:s,file:To(t,h??"sandforge.yaml"),fileGiven:h!==void 0,...c!==void 0?{org:c}:{},aliases:a,json:n.includes("--json"),failOnChange:n.includes("--fail-on-change"),failOnDrift:n.includes("--fail-on-drift"),quick:n.includes("--quick"),replace:[...new Set(g)],replaceDrifted:n.includes("--replace-drifted"),acceptAutomation:n.includes("--accept-automation"),acceptEmails:n.includes("--accept-emails"),acceptUserEmails:n.includes("--accept-user-emails"),acceptNoState:n.includes("--accept-no-state"),includeChanged:n.includes("--include-changed"),sweep:n.includes("--sweep"),rewind:f,acceptNoUndo:n.includes("--accept-no-undo"),acceptUnseen:n.includes("--accept-unseen"),yes:n.includes("--yes"),...d!==void 0?{out:To(t,d)}:{},outInRepository:n.includes("--out-in-repository"),...l!==void 0?{plan:To(t,l)}:{},...u!==void 0?{handoff:To(t,u)}:{},save:n.includes("--save"),failOnFindings:n.includes("--fail-on-findings")}}function mr(){try{let e=JSON.parse(cw(Lt(__dirname,"..","package.json"),"utf8"));return typeof e.version=="string"?e.version:"0.0.0"}catch{return"0.0.0"}}var te=class extends Error{constructor(n,r){super(n.refusal.message);this.answer=n;this.code=r;this.name="Stop"}answer;code};function pe(e){return new te({refusal:{code:e.code,message:e.message}},e.exit)}function Hc(e){return{path:kn(e.path),...e.resource!==void 0?{resource:e.resource}:{},message:e.message}}function Mo(e){let t;try{t=cw(e,"utf8")}catch(r){throw new te({refusal:{code:"FILE_UNREAD",message:`${e} cannot be read: ${r instanceof Error?r.message:String(r)}`}},2)}let n=jg(t);if("refusal"in n)throw new te({refusal:{code:"INVALID_FILE",message:`${e}: ${n.refusal}`}},2);return n.document}function Lo(e,t){return new te({refusal:{code:"INVALID_FILE",message:`${e} does not validate:
|
|
393
|
+
${t.map(n=>` ${fc(n)}`).join(`
|
|
394
|
+
`)}`,issues:t.map(Hc)}},2)}async function GO(e){let t,n={request:a=>t??=e.request(a)},r=a=>({unread:a instanceof Error?a.message:String(a)}),s=await qd(n).catch(r),o="unread"in s||s.dailyApiRequests===void 0?await Bd(n).catch(r):s.dailyApiRequests,i=await Ud(n).catch(r);return{apiRequests:o,storage:"unread"in s?s:{remainingMB:s.remainingMB,maxMB:s.maxMB},emails:i}}function QO(e,t){try{return $d(JSON.parse(e),t)}catch{return}}function Jc(e){return e.trim().split(`
|
|
395
|
+
`).map(t=>t.trim()).filter(Boolean).at(-1)??"it said nothing"}function uw(e){return`the state of ${e.env} on ${e.alias??e.organizationId} expired on ${e.expiresAt}, a month after its last write, as a scratch org does: deleted`}async function ln(e,t,n){let r=Mo(e.file),s=Dg(r,Ce(e.file),process.env,{aliases:e.aliases});if("refusals"in s)throw Lo(e.file,s.refusals);let o=s.resolved,i=o.resources.map(A=>A.name);for(let A of e.replace)if(!i.includes(A))throw new te({refusal:{code:"BAD_LINE",message:`--replace ${A} names no resource of the file: it has ${i.join(", ")}.`}},2);let a=t.journalDir??Mr(),c=t.locksDir??Gd(),d=zr(Ce(e.file),a),u=Kr({journalDir:a,fileFolder:Ce(e.file)});if("refusal"in u)throw pe(Qr(u.refusal,d!==void 0));let l=u.store;for(let A of await l.sweep())n(uw(A));let f=e.org??"",h;try{h=await(t.reach??lw)(f)}catch(A){throw new te({refusal:{code:"NOT_CONNECTED",message:A instanceof Ko?A.message:`${f} could not be reached: ${A instanceof Error?A.message:String(A)}`}},1)}let g;try{g=await Sr(h.conn)}catch(A){g={unread:A instanceof Error?A.message:String(A),error:A}}let m=_u(f,g,h.session);if("refusal"in m)throw pe(m.refusal);let w=m.target,y=Uu(o.checked.file.targets,w);if(y!==void 0)throw pe(y);let v;try{v=e.recover?void 0:await l.read(w.organizationId,o.checked.file.name)}catch(A){throw A instanceof L?pe(tt(A)):A}if(v!==void 0){let A=Ku(v,o.checked.file.name,w);if(A!==void 0)throw pe(A)}let b=[],k,E,S=e.command==="plan"||e.command==="apply";if(v===void 0&&S){let A=await Do({store:l,journalDir:a},{resolved:o,target:w}),P=await l.refreshedOf(w,o.checked.file.name),D=Wu(w,o.checked.file.name,e.acceptNoState,A,P);"refusal"in D?k=D.refusal:D.refreshed!==void 0?E=D.refreshed:b.push(D.warning)}let $=gi(o.checked.file.targets,w)?.by==="myDomain";S&&$&&b.push(`${w.alias}: ${Bu(E!==void 0)}`);let j=Qd(c,w.organizationId,t.lockOptions);if(j!==void 0&&b.push(`${Zd(j)}: this plan may be out of date when it ends`),S){let A=await XO(o,w,t,n),P=await ZO(o,n),D=await e0(o,w,h,{journalDir:a,locksDir:c});if(Object.keys(A).length+Object.keys(P).length+Object.keys(D).length>0){let G=mc(o.checked,process.env,{aliases:e.aliases,sources:A,datasets:P,checkpoints:D});if("refusals"in G)throw Lo(e.file,G.refusals);o=G.resolved}}return{resolved:o,store:l,journalDir:a,locksDir:c,target:w,reached:h,state:v,warnings:b,...k!==void 0?{noState:k}:{},...E!==void 0?{refreshed:E}:{},listedByMyDomain:$,runner:t.runner!==void 0?JO(t.runner,dw(e.command,process.env[bt]?.trim())):HO({},e.command)}}async function XO(e,t,n,r){let s=new Map,o={};for(let i of e.resources){if(i.kind!=="forge")continue;let{role:a,alias:c}=i.source;r(`${i.name}: reading its source, the ${a} org (${c})`);let d;try{let l=s.get(c);l===void 0&&(l=(n.reach??lw)(c),s.set(c,l)),d=(await l).conn}catch(l){o[i.name]={refusal:l instanceof Ko?`the ${a} org: ${l.reason}`:`the ${a} org (${c}) could not be reached: ${l instanceof Error?l.message:String(l)}`};continue}let u=await Zu(d,i.run,a,c);o[i.name]="organizationId"in u&&Ee(u.organizationId,t.organizationId)?{refusal:`its source, the ${a} org (${c}), is the org to fill: a clone reads one org and writes another`}:u}return o}async function ZO(e,t){let n={};for(let r of e.resources)r.kind==="frozen"&&(t(`${r.name}: reading its dataset at ${r.dataset.dir}`),n[r.name]=await El(r.dataset.dir,r.run.dataset));return n}async function e0(e,t,n,r){let s={};for(let o of e.resources)o.kind==="replay"&&(s[o.name]=await gf(o.run,o.checkpoint,{alias:t.alias,organizationId:t.organizationId,username:n.session.username,instanceUrl:n.session.instanceUrl},{storeRoot:ie(r.journalDir),locksDir:r.locksDir}).catch(i=>({code:"STORE_REFUSED",refusal:`its checkpoint could not be read: ${i instanceof Error?i.message:String(i)}`})));return s}async function lw(e){let t=await bd(e);return{session:t,conn:Ed(t)}}async function fw(e,t,n,r){let{state:s,resolved:o,target:i}=e,a={};if(s===void 0)return a;let c={organizationId:i.organizationId,env:o.checked.file.name},d=gt(s,qe(s).map(([u])=>u));for(let u of d){let l=s.resources[u];if(l===void 0)continue;let f=t.acceptAutomation||o.checked.file.resources[u]?.accept?.automation===!0,h=[];for(let g of Pp(l.kind,l.runs)){if(r.aborted)break;let m=Pc(g,c,e,u);if(m===void 0){h.push({n:g.n,nothing:!0});continue}n(`${u}: reading what the org holds of run ${g.n}`);let w=Cp(l.kind,{target:i.alias,subject:m,includeChanged:t.includeChanged,acceptAutomation:f,checkpointStore:ie(e.journalDir),...t.sweep===!0?{sweep:!0}:{}}),y=await e.runner(w.script,w.args,r),v;try{v={n:g.n,preview:Dp(l.kind,y.stdout)}}catch(k){if(!(k instanceof de))throw k;h.push({n:g.n,failed:`exit ${y.code}: ${Jc(y.stderr)}`});continue}let b=t.refresh&&l.status==="applied"&&o.checked.file.resources[u]!==void 0?Np(l.kind,{target:i.alias,subject:m}):void 0;if(b!==void 0&&!r.aborted){n(`${u}: verifying run ${g.n}`);let k=await e.runner(b.script,b.args,r);try{v={...v,refreshed:Tp(k.stdout)}}catch(E){if(!(E instanceof de))throw E;v={...v,refreshed:{unread:`exit ${k.code}: ${Jc(k.stderr)}`}}}}h.push(v)}a[u]=h}return a}async function t0(e,t){let{resolved:n,state:r,target:s,store:o,journalDir:i}=e,a={};for(let c of n.resources)t.has(c.name)&&(c.kind!=="seed"||(c.run.draws??[]).length===0||(a[c.name]=await yo(c,r,t,{organizationId:s.organizationId,env:n.checked.file.name,target:s.alias},{store:o,journalDir:i})));return a}async function n0(e,t){let{resolved:n,state:r,target:s,store:o,journalDir:i}=e,a=new Set(qe(r).map(([d])=>d)),c=[];for(let d of t){if(!(d.action==="delete"||d.action==="replace"&&!$t(d.kind))||!a.has(d.resource))continue;let l=await Ic(r,d.resource,{organizationId:s.organizationId,env:n.checked.file.name,target:s.alias},{store:o,journalDir:i});if(!("refusal"in l))for(let f of l.created.values())c.push(...f)}return c}async function r0(e,t,n,r,s,o={},i=!1,a=!1,c=!1){let{resolved:d,target:u,state:l,store:f}=e,h={},g=new Map(t.filter(y=>y.action==="create"||y.action==="replace"||(y.kind==="mask"||y.kind==="users")&&y.action==="keep").map(y=>[y.resource,y.action]));if(g.size===0)return h;let m=d.checked.file.name;await Jd(e.journalDir,new Date).catch(()=>0);let w=MO(Lt(qO(),"sandforge-env-plan-"));try{for(let y of d.resources){let v=g.get(y.name);if(v===void 0||s.aborted)continue;if(y.kind==="forge"){let K=y.source.read;if(K===void 0||"refusal"in K)continue}if(y.kind==="frozen"){let K=y.dataset.read;if(K===void 0||"refusal"in K)continue}if(y.kind==="replay"){let K=y.checkpoint.read;if(K===void 0||"refusal"in K)continue}let b=n[y.name];if(b!==void 0&&b.refusals.length>0)continue;let k=Lt(w,`${y.name}.json`),E=y.kind==="forge"&&y.run.records!==void 0?Zr(e.journalDir,u.organizationId,m,y.name):void 0,S,$,j;if(y.kind==="frozen"){let K=f.sasOf(u.organizationId,m,rt(y.name));if($=aw(K)?K:Lt(w,`${y.name}.sas`),$===K&&(S=Lt(w,`${y.name}.cli-store.json`)),v==="replace"&&$t(y.kind)){let O=await n0(e,t);O.length>0&&(j=Lt(w,`${y.name}.gone-first.json`),rw(j,`${JSON.stringify(O)}
|
|
396
|
+
`,{mode:384}))}}let A=Jt(y,{...b!==void 0?{drawn:b.ids}:{},standIns:!0,...$!==void 0?{sasDir:$}:{}});rw(k,`${JSON.stringify(A,null,2)}
|
|
397
|
+
`,{mode:384}),r(`${y.name}: dry run`);let P=o[y.name],D=y.kind==="users"&&v!=="create"?bo(l?.resources[y.name],{organizationId:u.organizationId,env:m},e).run:void 0,x=yt(bp(y,{target:u.alias,templateFile:k,runId:_r(m,y.name,wn(l?.resources[y.name])),replace:v==="replace"&&$t(y.kind),acceptAutomation:a||d.checked.file.resources[y.name]?.accept?.automation===!0,...P!==void 0?{seed:P}:{},...S!==void 0?{storeFile:S}:{},...j!==void 0?{goneFirstFile:j}:{},...E!==void 0?{rootsPlanFile:E}:{},...y.kind==="mask"?{store:Lt(w,`${y.name}.dataops`)}:{},...D!==void 0?{replacesRun:D}:{},...c?{acceptUserEmails:!0}:{},checkpointStore:ie(e.journalDir)}),i),G=await e.runner(x.script,x.args,s);try{h[y.name]={answer:Ap(y.kind,G.stdout)}}catch(K){if(!(K instanceof de))throw K;let O=QO(G.stdout,x.script);h[y.name]={failed:`exit ${G.code}: ${Jc(G.stderr)}`,...O?{refused:O}:{}}}}}finally{zO(w,{recursive:!0,force:!0})}return h}async function xo(e,t,n){let r=new AbortController,s,o=(e.onStop??Ge)(i=>{s=i,r.abort()});try{let i=await n(r.signal);if(s!==void 0)throw new te({refusal:{code:"STOPPED",message:`stopped by ${s} while ${t}: nothing was written`}},xe(s));return i}finally{o()}}function pw(e){let{resolved:t,state:n,store:r,target:s}=e,o=new Set([...t.resources.filter(i=>i.kind==="mask").map(i=>i.name),...Object.entries(n?.resources??{}).filter(([,i])=>i.kind==="mask").map(([i])=>i)]);return Object.fromEntries([...o].map(i=>[i,r.sasOf(s.organizationId,t.checked.file.name,Kt(i))]))}async function sw(e,t,n,r,s={}){let o={organizationId:e.target.organizationId,kind:e.target.kind,alias:e.target.alias,...e.target.host!==void 0?{host:e.target.host}:{}},i=s0(e),a={resolved:e.resolved,org:o,state:e.state,replace:t.replace,replaceDrifted:t.replaceDrifted,warnings:e.warnings,maskStores:pw(e),acceptUserEmails:t.acceptUserEmails,...Object.keys(i).length>0?{usersUnknown:i}:{},...e.refreshed!==void 0?{refreshed:e.refreshed}:{},...e.noState!==void 0?{refusal:e.noState.message,refusalCodes:[e.noState.code]}:{}};if(t.quick)return{plan:Sc(a),dryRuns:{}};let c=await fw(e,{includeChanged:!1,acceptAutomation:t.acceptAutomation,refresh:!0},n,r),d=await o0(e,n,r),u=Ec({...a,previews:c,...d?{drift:d}:{}}),l=new Set(u.filter(w=>w.action==="create"||w.action==="replace").map(w=>w.resource)),f=await t0(e,l),h=await r0(e,u,f,n,r,s,t.acceptEmails,t.acceptAutomation,t.acceptUserEmails),g=await GO(e.reached.conn),m=await i0(e,u.some(vc),n,r);return{plan:Sc({...a,previews:c,dryRuns:h,budget:g,...d?{drift:d}:{},...m?{checkpointEstimate:m}:{},draws:Object.fromEntries(Object.entries(f).map(([w,y])=>[w,{draws:y.draws,refusals:y.refusals}]))}),dryRuns:h}}function s0(e){let{state:t,target:n,resolved:r}=e,s={organizationId:n.organizationId,env:r.checked.file.name},o={};for(let[i,a]of qe(t)){if(a.kind!=="users")continue;let c=bo(a,s,e).unknown;c!==void 0&&(o[i]=c)}return o}async function o0(e,t,n){let r=e.state?.checkpoints?.after;if(r===void 0||n.aborted)return;t(`checkpoint ${r}: comparing the whole org with it`);let s=await e.runner(we,Su({org:e.target.alias,store:ie(e.journalDir),checkpoint:r}),n);return Pu(r,s)}async function i0(e,t,n,r){let s=e.resolved.checked.file;if(Vr(s,e.state,t).length===0||r.aborted)return;n("checkpoint: estimating what a take of the org costs");let o=await e.runner(we,Ru({org:e.target.alias,store:ie(e.journalDir),...Wr(s)}),r);return ju(o)}function a0(e,t){let n=Id(e,"sandforge-env"),r=!1;return async()=>{try{return await n.serverTime()}catch(s){return r||(r=!0,t(`the org did not say its time (${s instanceof Error?s.message:String(s)}): the state's spans are on this machine's clock`)),new Date().toISOString()}}}function c0(e){if(e.kind==="seed"){let s=Ht(e).map(i=>`${i.object} ${i.count??""}`).join(", "),o=(e.draws??[]).map(i=>`${i.relation.childObject}.${i.relation.lookupField} under the ${i.relation.parentObject} records ${i.from} created`);return o.length>0?`${s}; ${o.join(", ")}`:s}if(e.kind==="frozen"){let{path:s,version:o,digest:i}=e.dataset,a=typeof s=="string"?s:`$${s.env}`;return`the Frozen dataset ${o} at ${a} (${i.slice(0,19)}\u2026), as ${e.configFile} configures its load`}if(e.kind==="mask"){let s="set"in e.source?`the rule set ${e.source.set}`:`the template ${e.source.template}`;return`masks ${e.object!==void 0?`${e.object}${e.where!==void 0?` WHERE ${e.where}`:""}`:`every object its rules mask (${Ht(e).map(i=>i.object).join(", ")})`} with ${s}, ${e.rules.rules.length} rule(s)`}if(e.kind==="users")return`User ${e.users.length}, applied first`;if(e.kind==="replay"){let{checkpoint:s}=e,o=s.file;return s.id!==void 0?`a replay of checkpoint ${s.id}`:s.name!==void 0?`a replay of the checkpoint named ${s.name}`+(e.from!==void 0?` of the ${e.from} org`:""):`a replay of the checkpoint file ${typeof o=="string"?o:`$${o?.env??""}`}`}let t=(s,o)=>o!==void 0?`${s} WHERE ${o}`:s,n=e.wholeOrg?.fit,r=e.wholeOrg?n!==void 0?`a sample of the whole org that fits the org to fill${n.withinMB!==void 0?`, within ${n.withinMB} MB`:""}`:"the whole org":e.tables!==void 0?`tables ${e.tables.map(s=>t(s.object,s.where)).join(", ")}`:e.records!==void 0?`the ${e.records.object} records ${Xr(e.records)} chooses, with what each reaches`:e.record?.id!==void 0?`record ${e.record.id}`:`the one record of ${t(e.record?.object??"",e.record?.where)}`;return`cloned from the ${e.source} org: ${r}`}function d0(e,t){let n=Mo(e.file),r=ur(n,Ce(e.file));if("refusals"in r){t(`${e.file} does not validate:`);for(let l of r.refusals)t(` ${fc(l)}`);return{answer:{file:e.file,valid:!1,issues:r.refusals.map(Hc),warnings:[]},code:2}}let{file:s,order:o,runs:i,variables:a}=r.checked,c=new Set(Ig(r.checked,process.env).map(l=>l.name)),d=o.flatMap(l=>{let f=i[l],h=s.resources[l];return f===void 0?[]:[{name:l,kind:f.kind,dependsOn:h!==void 0?pc(l,h):[],...f.kind==="forge"?{source:f.source}:{},objects:Ht(f)}]}),u=r.checked.warnings.map(Hc);t(`${e.file}: valid, the environment ${s.name}`);for(let l of d){let f=i[l.name];t(` ${l.name}: ${f!==void 0?c0(f):""}`+(l.dependsOn.length>0?`, after ${l.dependsOn.join(", ")}`:""))}for(let l of a){let f=l.role!==void 0?`the ${l.role} org`:l.path[2]==="checkpoint"?`the checkpoint file of ${l.resource??""}`:`the dataset of ${l.resource??""}`;t(` variable ${l.name} (${f}): `+(c.has(l.name)?"not set in this shell":"set"))}for(let l of u)t(`warning: ${l.path}: ${l.message}`);return{answer:{file:e.file,valid:!0,env:s.name,resources:d,variables:a.map(l=>({name:l.name,...l.role!==void 0?{role:l.role}:{},...l.resource!==void 0?{resource:l.resource}:{},set:!c.has(l.name)})),issues:[],warnings:u},code:0}}function u0(e,t,n,r){if(n===void 0&&r===void 0)return`no state kept in ${e}`;let s=n!==void 0&&r!==void 0?`${n} on ${r}`:n??r??"",o=t===0?"":`, which keeps ${t===1?"1 other state":`${t} other states`}: "${B("env")} state" lists ${t===1?"it":"them"}`;return`no state of ${s} is kept in ${e}${o}. A state kept in another folder is read with SANDFORGE_JOURNAL_DIR set as when it was written \u2014 in a CI job, a folder its cache restores.`}async function l0(e,t,n){let r=t.journalDir??Mr(),s=Kr({journalDir:r,fileFolder:null});if("refusal"in s)throw pe(Qr(s.refusal,!1));let o=await s.store.sweep(),i;if(e.fileGiven){let u=ur(Mo(e.file),Ce(e.file));if("refusals"in u)throw Lo(e.file,u.refusals);i=u.checked.file.name}let a=e.org,c=await s.store.list(),d=c.filter(u=>(i===void 0||u.env===i)&&(a===void 0||u.state?.org.alias===a||u.organizationId.slice(0,15)===a.slice(0,15)));for(let u of o)n(`expired and deleted: ${u.env} on ${u.alias??u.organizationId}`);d.length===0&&n(u0(s.store.root,c.length,i,a));for(let u of d){let l=u.state;if(l===void 0){n(`${u.env} on ${u.organizationId}: not used \u2014 ${u.damaged??""}`);continue}let f=Object.entries(l.resources).map(([h,g])=>`${h} ${g.status}`).join(", ");n(`${l.env} on ${l.org.alias??l.org.organizationId} (${l.org.kind}, ${l.org.organizationId}): serial ${l.serial}, written ${l.updatedAt}`+(u.expiresAt!==void 0?`, expires ${u.expiresAt}`:"")+(f?`; ${f}`:""))}return{journalDir:r,states:d.map(u=>{let l=u.state;if(l===void 0)return{env:u.env,organizationId:u.organizationId,damaged:u.damaged??"not used"};let f=ci(l);return{env:l.env,organizationId:l.org.organizationId,...l.org.alias!==void 0?{alias:l.org.alias}:{},kind:l.org.kind,serial:l.serial,resources:Object.fromEntries(Object.entries(l.resources).map(([h,g])=>[h,g.status])),updatedAt:l.updatedAt,...f!==void 0?{expiresAt:f}:{}}}),expired:o.map(u=>({env:u.env,organizationId:u.organizationId,...u.alias!==void 0?{alias:u.alias}:{},expiresAt:u.expiresAt}))}}async function f0(e,t,n){let r=ur(Mo(e.file),Ce(e.file));if("refusals"in r)throw Lo(e.file,r.refusals);let s=t.journalDir??Mr(),o=zr(Ce(e.file),s),i=Kr({journalDir:s,fileFolder:Ce(e.file)});if("refusal"in i)throw pe(Qr(i.refusal,o!==void 0));for(let u of await i.store.sweep())n(uw(u));let a=Fy(await i.store.list(),r.checked.file.name,e.org??"");if("refusal"in a)throw pe(a.refusal);let{output:c,whole:d}=await Uc(a.state,{store:i.store,journalDir:s});return{answer:c,code:d?0:3}}async function p0(e,t,n){let r=await ln(e,t,n),s=await Py({store:r.store,journalDir:r.journalDir,locksDir:r.locksDir,sandforgeVersion:mr(),...t.lockOptions!==void 0?{lockOptions:t.lockOptions}:{}},{resolved:r.resolved,target:r.target});if("refusal"in s)throw pe(s.refusal);for(let o of Ny(s.result))n(o);return s.result}function hw(e){let{target:t}=e;return{organizationId:t.organizationId,kind:t.kind,alias:t.alias,...t.host!==void 0?{host:t.host}:{}}}function ow(e){let t=e.checked.file.audits,n=jo(t,"apply"),r=t?.handoff===!0;return n!==void 0?`${hy(n)}${r?"; then the handoff note":""}`:r?"after the apply: the handoff note, written on this machine":void 0}function h0(e){if(e.handoff===void 0)return;let t=Ce(e.handoff);if(!aw(t)||!_O(t).isDirectory())return new te({refusal:{code:"BAD_LINE",message:`--handoff ${e.handoff}: its folder ${t} is not there. Nothing was read.`}},2);if(e.outInRepository)return;let n=yn(Ce(e.file),e.handoff);if(n!==void 0)return new te({refusal:{code:"HANDOFF_IN_REPOSITORY",message:`--handoff ${e.handoff} is inside the repository ${n} that holds the file: the note names the org, its users by their usernames and what is left to do, and committed with the project it would publish them. Keep it outside \u2014 in CI, in $RUNNER_TEMP, kept as an artifact a short time \u2014 or give --out-in-repository for a folder of it that is never committed. Nothing was read.`}},2)}function m0(e){let t=(e.schedules?.jobs??[]).filter(o=>o.status!=="new").length,n=e.endpoints?.found.length??0,r=[e.deliverability?.unread!==void 0?"the deliverability":"",e.schedules?.unread!==void 0?"the scheduled jobs":"",e.endpoints?.unread!==void 0?"the endpoints":""].filter(Boolean),s=[t>0?`${t} scheduled job(s) no longer run`:"",n>0?`${n} endpoint(s) still name production`:"",e.deliverability?.read==="open"?"the org delivers all email":""].filter(Boolean);return`audits: ${s.length>0?`${s.join(", ")} (below)`:"nothing found"}`+(r.length>0?`; not read: ${r.join(", ")} (below)`:"")}async function g0(e,t,n,r){let s=e.resolved.checked.file,o=hw(e),i=[],a=[],c=n,d=jo(s.audits,"apply");if(d!==void 0){r("audits: reading the org, nothing written");try{let f=await Mc({transport:e.reached.conn,journalDir:e.journalDir},{org:o,asked:d});c={...c,audits:f.result},i.push(m0(f.result)),a.push(...zc(f.result,{file:t.file,notes:f.notes}))}catch(f){i.push(`audits: not read \u2014 ${f instanceof Error?f.message:String(f)}`)}}let u=new Date().toISOString(),l=t.handoff??(s.audits?.handoff===!0?Sy(e.journalDir,{env:s.name,organizationId:e.target.organizationId,at:u}):void 0);if(l!==void 0)try{let f=await e.store.read(e.target.organizationId,s.name),h=f!==void 0?(await Uc(f,{store:e.store,journalDir:e.journalDir})).output:void 0,g=Ry({run:c,org:o,file:t.file,at:u,sandforgeVersion:mr(),...h!==void 0?{output:h}:{},resources:s.resources,...s.masking!==void 0?{masking:s.masking}:{}});await $y(l,g),c={...c,handoff:{path:l}},i.push(`handoff note: ${l}`)}catch(f){i.push(`handoff note: not written \u2014 ${f instanceof Error?f.message:String(f)}`)}return{result:c,before:i,after:a}}async function Yc(e,t,n,r){return e.yes||await(t.ask??(o=>Vd(o)))(n)===e.org?!0:(r("Nothing was written: the alias typed is not the org\u2019s."),!1)}function Fo(e,t,n){return{runner:e.runner,store:e.store,locksDir:e.locksDir,journalDir:e.journalDir,orgNow:a0(e.reached.conn,n),say:n,sandforgeVersion:mr(),...t.onStop!==void 0?{onStop:t.onStop}:{},...t.lockOptions!==void 0?{lockOptions:t.lockOptions}:{}}}async function iw(e,t,n,r,s){let o=await ln(e,t,r),i={verb:n,resolved:o.resolved,target:o.target,state:o.state,acceptAutomation:e.acceptAutomation,acceptEmails:e.acceptEmails,acceptNoUndo:e.acceptNoUndo,acceptUnseen:e.acceptUnseen},a=Wc(i);if(a!==void 0)throw pe(a);for(let u of o.warnings)r(`warning: ${u}`);let c;if(!e.yes){let u=await xo(t,"reading what a rewind would do",l=>_y(Fo(o,t,r),i,l));if(!("differs"in u))throw new te({refusal:{code:"REWIND_REFUSED",message:`${u.refusal} Nothing was written.`}},1);c=u;for(let l of xu(n,o.target.alias,u))r(l);if(u.refusal!==void 0)throw new te({refusal:{code:u.refusal.code,message:u.refusal.message}},1);if(u.differs&&!await Yc(e,t,qy(i,u),r))throw new te({refusal:{code:"DECLINED",message:"Nothing was written."}},1)}let d=await By(Fo(o,t,r),i,c);for(let u of Uy(d.result))r(u);s(d.result),Be(d.exitCode)}async function y0(e=process.argv,t={}){let n=YO(e,t.cwd),r=o=>{process[n.json?"stderr":"stdout"].write(`${o}
|
|
398
|
+
`)},s=o=>{n.json&&process.stdout.write(`${JSON.stringify(o,null,2)}
|
|
399
|
+
`)};try{switch(n.command){case"validate":{let{answer:o,code:i}=d0(n,r);s(o),Be(i);return}case"state":{s(n.recover?await p0(n,t,r):await l0(n,t,r));return}case"output":{let{answer:o,code:i}=await f0(n,t,r);for(let a of My(o))r(a);s(o),Be(i);return}case"plan":{if(n.out!==void 0){let l=Jy(Ce(n.file),n.out,n.outInRepository);if(l!==void 0)throw pe(l)}let o=await ln(n,t,r),{plan:i,dryRuns:a}=await xo(t,"planning",l=>sw(o,n,r,l)),c=ow(o.resolved);for(let l of ho(i,"apply",c!==void 0?{audits:c}:{}))r(l);if(n.out!==void 0){let l=Hy({plan:i,state:o.state,digest:o.resolved.digest,line:{replace:n.replace,replaceDrifted:n.replaceDrifted,acceptAutomation:n.acceptAutomation,...n.acceptEmails?{acceptEmails:!0}:{},acceptNoState:n.acceptNoState,...n.acceptUserEmails?{acceptUserEmails:!0}:{}},dryRuns:a,sandforgeVersion:mr(),madeAt:new Date().toISOString(),listedByMyDomain:o.listedByMyDomain});await Yy(n.out,l),r(tw(n.out,l))}s(i);let d=n.failOnChange&&$c(i),u=n.failOnDrift&&zg(i);Be(d||u?3:0);return}case"apply":{n.quick&&Se("apply makes a whole plan: --quick is for plan alone.");let o=h0(n);if(o!==void 0)throw o;let i,a=n;if(n.plan!==void 0){let w=Gy(n.plan);if("refusal"in w)throw pe(w.refusal);i=w.saved;let y=Qy(i,n.plan,{now:Date.now(),sandforgeVersion:mr()});if(y!==void 0)throw pe(y);a={...n,...i.line,acceptEmails:i.line.acceptEmails===!0,acceptUserEmails:i.line.acceptUserEmails===!0}}let c=await ln(a,t,r);if(i!==void 0&&n.plan!==void 0){let w=Xy(i,n.plan,{target:c.target,digest:c.resolved.digest,state:c.state});if(w!==void 0)throw pe(w)}let{plan:d,dryRuns:u}=await xo(t,"planning",w=>sw(c,a,r,w,i?.seeds));if(i!==void 0&&n.plan!==void 0){let w=Zy(i.plan,d);if(w.length>0)throw pe(ew(n.plan,w))}let l=ow(c.resolved);for(let w of ho(d,"apply",l!==void 0?{audits:l}:{}))r(w);if(i!==void 0&&n.plan!==void 0&&r(nw(n.plan,i)),d.refusal===void 0&&$c(d)&&!await Yc(n,t,`Type ${c.target.alias} to apply ${d.env} to it as planned:`,r))throw new te({refusal:{code:"DECLINED",message:"Nothing was written."}},1);let h=await Wg(Fo(c,t,r),{plan:d,resolved:c.resolved,target:c.target,state:c.state,dryRuns:u,acceptAutomation:a.acceptAutomation,acceptEmails:a.acceptEmails,acceptUserEmails:a.acceptUserEmails}),m=(h.exitCode===0||h.exitCode===3)&&h.result.refusal===void 0?await g0(c,n,h.result,r):{result:h.result,before:[],after:[]};for(let w of Tc(m.result,"apply",m.before))r(w);for(let w of m.after)r(w);s(m.result),Be(h.exitCode);return}case"audit":{let o=await ln(n,t,r),i=await my({transport:o.reached.conn,journalDir:o.journalDir},{org:hw(o),audits:o.resolved.checked.file.audits,file:n.file,save:n.save,failOnFindings:n.failOnFindings});if("refusal"in i)throw new te({refusal:i.refusal},i.exitCode);for(let a of i.lines)r(a);s(i.result),Be(i.exitCode);return}case"reset":{await iw(n,t,"reset",r,s);return}case"destroy":{if(n.rewind){await iw(n,t,"destroy",r,s);return}let o=await ln(n,t,r),i={organizationId:o.target.organizationId,kind:o.target.kind,alias:o.target.alias,...o.target.host!==void 0?{host:o.target.host}:{}},a=await xo(t,"reading what the org holds",u=>fw(o,{includeChanged:n.includeChanged,acceptAutomation:n.acceptAutomation,refresh:!1,sweep:n.sweep},r,u)),c=Mg({resolved:o.resolved,org:i,state:o.state,previews:a,warnings:o.warnings,maskStores:pw(o)});for(let u of ho(c,"destroy"))r(u);if(c.refusal===void 0&&c.actions.length>0&&!await Yc(n,t,`Type ${o.target.alias} to take ${c.env} back from it`+(n.includeChanged?", the records changed since included \u2014 on a shared org, others\u2019 work:":":"),r))throw new te({refusal:{code:"DECLINED",message:"Nothing was deleted."}},1);let d=await Ty(Fo(o,t,r),{plan:c,resolved:o.resolved,target:o.target,state:o.state,includeChanged:n.includeChanged,sweep:n.sweep,acceptAutomation:n.acceptAutomation});for(let u of Tc(d.result,"destroy"))r(u);s(d.result),Be(d.exitCode);return}}}catch(o){let i=o instanceof te?o:new te({refusal:{code:"FAILED",message:o instanceof Error?o.message:String(o)}},1);process.stderr.write(`${i.message}
|
|
400
|
+
`),s(i.answer),Be(i.code)}}process.argv[1]?.includes("sandforge-env")&&(eu(),y0().then(()=>process.exit(process.exitCode??0)).catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}
|
|
401
|
+
`),process.exit(1)}));export{dw as envRelayOf,HO as envStepRunner,y0 as main,YO as parseArgs,GO as readBudget,JO as relayedRunner};
|