@noy-db/hub 0.7.0-pre.8 → 0.7.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/CHANGELOG.md +1379 -0
- package/README.md +7 -6
- package/dist/api-TXFOVOXX.js +19 -0
- package/dist/as/index.js +14 -14
- package/dist/at/index.js +9 -10
- package/dist/attestation/index.js +18 -19
- package/dist/attestation/index.js.map +1 -1
- package/dist/{backup-SZBDQQSL.js → backup-IJTB4S4M.js} +14 -15
- package/dist/{backup-SZBDQQSL.js.map → backup-IJTB4S4M.js.map} +1 -1
- package/dist/blobs/index.js +13 -14
- package/dist/blobs/index.js.map +1 -1
- package/dist/broker/index.js +12 -13
- package/dist/broker/index.js.map +1 -1
- package/dist/by/index.js +2 -3
- package/dist/cargo/index.js +33 -34
- package/dist/{chunk-X6TBQKHW.js → chunk-2577DKXB.js} +2 -2
- package/dist/chunk-2C3AQB46.js +1652 -0
- package/dist/chunk-2C3AQB46.js.map +1 -0
- package/dist/{chunk-L3FHEWA3.js → chunk-2N4GY74U.js} +6 -6
- package/dist/{chunk-626TSARM.js → chunk-2Y4IMKA6.js} +4 -4
- package/dist/{chunk-7CWII4BL.js → chunk-3RCJJBNR.js} +10 -10
- package/dist/{chunk-M7UC2QPT.js → chunk-453F654R.js} +2 -2
- package/dist/{chunk-2QNKXGUS.js → chunk-4GVM6QZA.js} +2 -2
- package/dist/{chunk-AB5P32RE.js → chunk-4OZNXTO4.js} +2 -2
- package/dist/{chunk-L3HDEHGM.js → chunk-5VCRVKOZ.js} +4 -4
- package/dist/{chunk-6AQIFBSP.js → chunk-5WDXHNSW.js} +5 -5
- package/dist/chunk-66TQOPFM.js +37 -0
- package/dist/chunk-66TQOPFM.js.map +1 -0
- package/dist/{chunk-BOFRKAUS.js → chunk-6GMZ7HEE.js} +6 -6
- package/dist/{chunk-PRHCMEUK.js → chunk-6GOE5PGN.js} +168 -1328
- package/dist/chunk-6GOE5PGN.js.map +1 -0
- package/dist/{chunk-XBFEKTIY.js → chunk-6I2RQCET.js} +4 -4
- package/dist/{chunk-PUJTKLPL.js → chunk-6X6SEMEE.js} +6 -4
- package/dist/{chunk-PUJTKLPL.js.map → chunk-6X6SEMEE.js.map} +1 -1
- package/dist/{chunk-UCUALOSM.js → chunk-6YXCPL4T.js} +2 -2
- package/dist/{chunk-BYBB4ABD.js → chunk-77K4PG6P.js} +8 -8
- package/dist/{chunk-S2VG3ABP.js → chunk-7MG2LHO5.js} +3 -3
- package/dist/{chunk-GU3LQYW2.js → chunk-7MG7SJT7.js} +1 -1
- package/dist/chunk-7MG7SJT7.js.map +1 -0
- package/dist/{chunk-JBIV4FLR.js → chunk-7O3Y4PPD.js} +5 -1
- package/dist/chunk-7O3Y4PPD.js.map +1 -0
- package/dist/{chunk-EO2KGKEJ.js → chunk-7V4TP3AF.js} +4 -4
- package/dist/{chunk-LFDMKZIP.js → chunk-ANATMFIO.js} +5 -5
- package/dist/{chunk-T3PHCEN4.js → chunk-ANSIZYEG.js} +3 -3
- package/dist/{chunk-ZKRRBRSZ.js → chunk-AO42KJO6.js} +7 -7
- package/dist/{chunk-VFIWDPXZ.js → chunk-BLN54W3L.js} +3 -3
- package/dist/{chunk-ZQ2UUHSL.js → chunk-BM5TWITZ.js} +7 -7
- package/dist/{chunk-WLFABTZ6.js → chunk-BOET4NA4.js} +3 -3
- package/dist/{chunk-FOG7YEJP.js → chunk-BOWNCWZT.js} +3 -3
- package/dist/{chunk-7XODKGTW.js → chunk-BSFNRLK2.js} +5 -5
- package/dist/{chunk-YPSOHDNC.js → chunk-BUE2D7PX.js} +26 -3
- package/dist/chunk-BUE2D7PX.js.map +1 -0
- package/dist/{chunk-J4MN6XIU.js → chunk-BZ3534YM.js} +2 -2
- package/dist/chunk-CARABLSQ.js +176 -0
- package/dist/chunk-CARABLSQ.js.map +1 -0
- package/dist/{chunk-4MZEZ37W.js → chunk-CHJBLCOG.js} +10 -8
- package/dist/{chunk-4MZEZ37W.js.map → chunk-CHJBLCOG.js.map} +1 -1
- package/dist/{chunk-IF56DYJK.js → chunk-CPWQB3N5.js} +7 -7
- package/dist/{chunk-SHILAQH5.js → chunk-DGOZ4UZD.js} +2 -2
- package/dist/{chunk-BWWUXE3L.js → chunk-ELNXJMGB.js} +6 -6
- package/dist/{chunk-44C2URL7.js → chunk-EQEYOJBM.js} +3 -3
- package/dist/{chunk-Y3XWRDAM.js → chunk-EYBQEIUY.js} +3 -3
- package/dist/{chunk-Z7ZXZL6Y.js → chunk-FAHMLERK.js} +2 -2
- package/dist/chunk-FFWI7UH7.js +53 -0
- package/dist/chunk-FFWI7UH7.js.map +1 -0
- package/dist/{chunk-EXDIHWFO.js → chunk-FMZY5Q6L.js} +3 -3
- package/dist/{chunk-H6WXKZL7.js → chunk-FXBIP2WD.js} +6 -6
- package/dist/{chunk-ZTYG36DH.js → chunk-G56KBWFY.js} +67 -22
- package/dist/chunk-G56KBWFY.js.map +1 -0
- package/dist/{chunk-672U6STZ.js → chunk-GPEQUXHL.js} +4 -4
- package/dist/{chunk-Z2PWOSCJ.js → chunk-GY4WYNNG.js} +2 -2
- package/dist/{chunk-RDHUZ674.js → chunk-HDOU6I2Y.js} +80 -8
- package/dist/chunk-HDOU6I2Y.js.map +1 -0
- package/dist/{chunk-OMHHGOG4.js → chunk-J6FXAEUG.js} +15 -13
- package/dist/chunk-J6FXAEUG.js.map +1 -0
- package/dist/{chunk-4A4TYISP.js → chunk-JBDFMYKQ.js} +2 -2
- package/dist/{chunk-POS53FG6.js → chunk-JMGDHKQF.js} +2 -2
- package/dist/{chunk-Q7GEDVHC.js → chunk-K6LHRFBL.js} +7 -7
- package/dist/{chunk-4JDIRUTT.js → chunk-K7NTTA6P.js} +2 -2
- package/dist/{chunk-26W5VETY.js → chunk-KG7TZKZG.js} +5 -5
- package/dist/{chunk-RJ7RIIX6.js → chunk-KJIMGIWO.js} +8 -8
- package/dist/{chunk-F7ZFRPGQ.js → chunk-KTFRCC5C.js} +2 -2
- package/dist/{chunk-HSGEIMJS.js → chunk-KUJDV5QH.js} +5 -5
- package/dist/{chunk-XWNLKG6R.js → chunk-KUX3OB6D.js} +7 -5
- package/dist/{chunk-XWNLKG6R.js.map → chunk-KUX3OB6D.js.map} +1 -1
- package/dist/{chunk-UPJMBMCR.js → chunk-L742JPKZ.js} +6 -6
- package/dist/{chunk-4TZUFNXL.js → chunk-L7CIOOBW.js} +2 -2
- package/dist/{chunk-7LYUJNU3.js → chunk-LWBCUYZW.js} +2 -2
- package/dist/{chunk-JHLJQUXU.js → chunk-MUM7IANK.js} +3 -3
- package/dist/{chunk-2GXEQUEX.js → chunk-MVMXZYXT.js} +2 -2
- package/dist/{chunk-XLPXGN66.js → chunk-NA2NIJZI.js} +8 -8
- package/dist/{chunk-S6YB5ZRP.js → chunk-NKHRDYOR.js} +4 -4
- package/dist/{chunk-XJ3FEKEY.js → chunk-NQKIUNW5.js} +2 -2
- package/dist/{chunk-6NRVFD55.js → chunk-PT43Y56J.js} +6 -6
- package/dist/{chunk-5ACAVJUI.js → chunk-Q2PU57HC.js} +2 -2
- package/dist/{chunk-E6YA6UAP.js → chunk-Q7HZX3IF.js} +2 -2
- package/dist/{chunk-4ZPE6SKS.js → chunk-QIBVIOXO.js} +3 -3
- package/dist/{chunk-WLLUM35R.js → chunk-QIZPZMUI.js} +2 -2
- package/dist/{chunk-P6ASQOZR.js → chunk-REDOOY2Q.js} +3 -3
- package/dist/chunk-REDOOY2Q.js.map +1 -0
- package/dist/{chunk-LKFKXS5K.js → chunk-RMF67KCG.js} +2 -2
- package/dist/{chunk-YCSM3GZU.js → chunk-RMS3NEA3.js} +2 -2
- package/dist/{chunk-4FPEWQKF.js → chunk-RRNRNANG.js} +27 -17
- package/dist/chunk-RRNRNANG.js.map +1 -0
- package/dist/chunk-RTBJ5IOO.js +87 -0
- package/dist/chunk-RTBJ5IOO.js.map +1 -0
- package/dist/chunk-RXLYKVTF.js +17 -0
- package/dist/chunk-RXLYKVTF.js.map +1 -0
- package/dist/{chunk-OPXR4PB2.js → chunk-SFAWCTEM.js} +2 -2
- package/dist/{chunk-3QARDAYW.js → chunk-SKGMN35F.js} +2 -2
- package/dist/{chunk-W5LHQXZU.js → chunk-SL3JAAKN.js} +2 -2
- package/dist/chunk-SMH6SRX7.js +87 -0
- package/dist/chunk-SMH6SRX7.js.map +1 -0
- package/dist/{chunk-JJZIIJSA.js → chunk-SPXXX5E4.js} +12 -82
- package/dist/chunk-SPXXX5E4.js.map +1 -0
- package/dist/{chunk-UALOYGCP.js → chunk-SPYWXKJN.js} +3 -3
- package/dist/{chunk-QU3YUP2X.js → chunk-SZJ3DLZA.js} +2 -2
- package/dist/chunk-TFMM5DBB.js +20 -0
- package/dist/chunk-TFMM5DBB.js.map +1 -0
- package/dist/{chunk-225O5CXQ.js → chunk-TFR7DSOV.js} +2 -2
- package/dist/{chunk-X67FCULK.js → chunk-TRGTKX5E.js} +3 -3
- package/dist/{chunk-JVLSU7S2.js → chunk-TUFM4UZP.js} +2 -2
- package/dist/{chunk-VVAVTSTR.js → chunk-U4FOQDY4.js} +5 -172
- package/dist/chunk-U4FOQDY4.js.map +1 -0
- package/dist/{chunk-HTGRQZFB.js → chunk-UGTBXF5U.js} +3 -3
- package/dist/{chunk-THNJ3IKU.js → chunk-ULUMAZ5S.js} +2 -2
- package/dist/{chunk-XDVVBETV.js → chunk-UXVWEX5L.js} +2 -2
- package/dist/{chunk-FKFIEEY6.js → chunk-UXWB3FPF.js} +10 -10
- package/dist/{chunk-NO272T7Q.js → chunk-V4PXLYWM.js} +2 -31
- package/dist/chunk-V4PXLYWM.js.map +1 -0
- package/dist/{chunk-CBRS2NEK.js → chunk-VTFVLCUH.js} +2 -2
- package/dist/{chunk-TOV6VMHF.js → chunk-VXANTWBJ.js} +3 -3
- package/dist/{chunk-VSLUSXVK.js → chunk-VXGSWL6L.js} +6 -6
- package/dist/{chunk-KHKKD62N.js → chunk-VYYM3MEN.js} +2 -16
- package/dist/chunk-VYYM3MEN.js.map +1 -0
- package/dist/{chunk-HQINBNHM.js → chunk-WEQEYLCS.js} +7 -7
- package/dist/{chunk-U6GCYG2T.js → chunk-X2DLENDQ.js} +3 -3
- package/dist/{chunk-XVU7J43V.js → chunk-XLMEZIAJ.js} +2 -2
- package/dist/{chunk-ILSR22WM.js → chunk-XTXOCYOJ.js} +5 -5
- package/dist/{chunk-KDJGJR7F.js → chunk-YSRUYAVU.js} +2 -2
- package/dist/{chunk-NLKLXXTO.js → chunk-YYP7WSEB.js} +2 -2
- package/dist/{chunk-4G25SDQL.js → chunk-ZN4FD4PE.js} +4 -4
- package/dist/{chunk-XSN63FUS.js → chunk-ZORTV6NH.js} +2 -2
- package/dist/{chunk-S3I7VKID.js → chunk-ZVO4QVPD.js} +5 -5
- package/dist/classified/index.js +5 -6
- package/dist/{classified-marker-KL4YXUXD.js → classified-marker-LI2SF2E4.js} +3 -5
- package/dist/{classified-marker-KL4YXUXD.js.map → classified-marker-LI2SF2E4.js.map} +1 -1
- package/dist/collection-facade-4GRREZ6C.js +45 -0
- package/dist/computed-VPOKQK4N.js +10 -0
- package/dist/consent/index.js +9 -10
- package/dist/consent/index.js.map +1 -1
- package/dist/cover/index.js +9 -10
- package/dist/crdt/index.js +0 -1
- package/dist/crdt/index.js.map +1 -1
- package/dist/custody/index.js +12 -13
- package/dist/{dead-filter-ZGRFZKYE.js → dead-filter-TSWZQRR5.js} +2 -3
- package/dist/{dead-filter-ZGRFZKYE.js.map → dead-filter-TSWZQRR5.js.map} +1 -1
- package/dist/debug/index.js +1 -2
- package/dist/debug/index.js.map +1 -1
- package/dist/{delegation-2DO3VI5E.js → delegation-OVIFFPG4.js} +11 -12
- package/dist/{delegation-2DO3VI5E.js.map → delegation-OVIFFPG4.js.map} +1 -1
- package/dist/derivations/index.js +30 -16
- package/dist/derive-6O5SWQKN.js +21 -0
- package/dist/directory/index.js +10 -11
- package/dist/dispatch-S73TK3IY.js +302 -0
- package/dist/dispatch-S73TK3IY.js.map +1 -0
- package/dist/{dispatch-M62IAL2S.js → dispatch-WC6X2M6C.js} +5 -7
- package/dist/{dispatch-M62IAL2S.js.map → dispatch-WC6X2M6C.js.map} +1 -1
- package/dist/{enclave-4P4KH5ZW.js → enclave-KJOTOH7X.js} +9 -10
- package/dist/executor-5NIMLSKZ.js +8 -0
- package/dist/executor-AQVXV5GZ.js +8 -0
- package/dist/executor-PUAO6AKJ.js +29 -0
- package/dist/export-accessible-72EQNBMR.js +22 -0
- package/dist/extract-partition-PUYNU3UF.js +37 -0
- package/dist/{fanout-sidecar-BRQHWTZQ.js → fanout-sidecar-WUFXNYP4.js} +9 -10
- package/dist/{fanout-sidecar-BRQHWTZQ.js.map → fanout-sidecar-WUFXNYP4.js.map} +1 -1
- package/dist/{fence-watcher-ZVSMLKQD.js → fence-watcher-U2PW6JU5.js} +1 -3
- package/dist/{fence-watcher-ZVSMLKQD.js.map → fence-watcher-U2PW6JU5.js.map} +1 -1
- package/dist/find-2ABFCZX4.js +10 -0
- package/dist/forget/index.js +9 -10
- package/dist/forget/index.js.map +1 -1
- package/dist/guards/index.js +4 -5
- package/dist/history/index.js +13 -14
- package/dist/history/index.js.map +1 -1
- package/dist/i18n/index.js +14 -15
- package/dist/i18n/index.js.map +1 -1
- package/dist/index.d.ts +20 -4
- package/dist/index.js +122 -115
- package/dist/index.js.map +1 -1
- package/dist/indexing/index.js +2 -3
- package/dist/indexing/index.js.map +1 -1
- package/dist/introspection/index.js +13 -13
- package/dist/issue-SIDORTSZ.js +18 -0
- package/dist/{json-schema-I22JCYCG.js → json-schema-V3M5MUCM.js} +1 -3
- package/dist/{json-schema-I22JCYCG.js.map → json-schema-V3M5MUCM.js.map} +1 -1
- package/dist/kernel/collection-config.d.ts +34 -0
- package/dist/kernel/collection.d.ts +11 -6
- package/dist/kernel/errors.d.ts +45 -0
- package/dist/kernel/match-pairs.d.ts +30 -0
- package/dist/kernel/types.d.ts +66 -0
- package/dist/lazy/index.js +3 -3
- package/dist/{ledger-4X5ZH43X.js → ledger-F33ZVMTK.js} +11 -12
- package/dist/liberate-LCDPNAG2.js +24 -0
- package/dist/link-set-FKNWAYKS.js +30 -0
- package/dist/{managed-secret-CXALLEUB.js → managed-secret-PQYKSR6T.js} +10 -11
- package/dist/materialized-views/index.js +21 -21
- package/dist/{migrate-cek-LBRKYUZZ.js → migrate-cek-5ENH64AA.js} +2 -3
- package/dist/{migrate-cek-LBRKYUZZ.js.map → migrate-cek-5ENH64AA.js.map} +1 -1
- package/dist/money/index.js +4 -5
- package/dist/noydb-DUXZPKSN.js +90 -0
- package/dist/overlay-views/index.js +4 -5
- package/dist/periods/index.js +12 -13
- package/dist/pod/index.js +64 -60
- package/dist/{pod-handle-DHEYBTJ2.js → pod-handle-Q736KYON.js} +10 -11
- package/dist/{pod-handle-DHEYBTJ2.js.map → pod-handle-Q736KYON.js.map} +1 -1
- package/dist/policy/index.js +10 -11
- package/dist/port/to/index.d.ts +40 -0
- package/dist/portability/index.js +8 -9
- package/dist/portability/index.js.map +1 -1
- package/dist/{post-register-4DXRYGTU.js → post-register-LNE2FE2A.js} +6 -7
- package/dist/{post-register-4DXRYGTU.js.map → post-register-LNE2FE2A.js.map} +1 -1
- package/dist/{purge-scope-FGNNLWHD.js → purge-scope-4HEFPDOW.js} +1 -3
- package/dist/{purge-scope-FGNNLWHD.js.map → purge-scope-4HEFPDOW.js.map} +1 -1
- package/dist/query/index.js +3 -4
- package/dist/{read-only-facade-CHCKSEPD.js → read-only-facade-BIGO37U3.js} +1 -2
- package/dist/reduce/index.js +4 -5
- package/dist/reduce/index.js.map +1 -1
- package/dist/register-I2DZXGAR.js +31 -0
- package/dist/registry-23WF3TGH.js +8 -0
- package/dist/registry-4AYVUNXK.js +8 -0
- package/dist/registry-VSSQPIGF.js +18 -0
- package/dist/registry-YLEWMGAC.js +32 -0
- package/dist/request-withdrawal-KFQHEZ25.js +30 -0
- package/dist/{reveal-X2QMWOVX.js → reveal-67RDQRIN.js} +6 -7
- package/dist/{reveal-X2QMWOVX.js.map → reveal-67RDQRIN.js.map} +1 -1
- package/dist/revoke-DQDZAZZM.js +23 -0
- package/dist/satellites/index.js +1 -2
- package/dist/schema-update/index.js +2 -3
- package/dist/sealed-record/index.js +12 -13
- package/dist/sealed-record/index.js.map +1 -1
- package/dist/search/index.js +4 -5
- package/dist/{seed-IX5NFSH5.js → seed-G42JYN56.js} +12 -13
- package/dist/{seed-IX5NFSH5.js.map → seed-G42JYN56.js.map} +1 -1
- package/dist/sequence/index.js +9 -10
- package/dist/session/index.js +9 -10
- package/dist/session/index.js.map +1 -1
- package/dist/shadow/index.js +2 -3
- package/dist/shadow/index.js.map +1 -1
- package/dist/share-link/index.js +0 -1
- package/dist/share-link/index.js.map +1 -1
- package/dist/signer-WAMDZHEN.js +24 -0
- package/dist/snapshots/index.js +10 -11
- package/dist/snapshots/index.js.map +1 -1
- package/dist/{stale-5I36LPVK.js → stale-DDL7WQEZ.js} +10 -11
- package/dist/storage-FLR73HHF.js +22 -0
- package/dist/store/index.js +0 -1
- package/dist/{store-coordination-provider-OLPNRMFO.js → store-coordination-provider-MEQ2MJQG.js} +10 -11
- package/dist/{store-coordination-provider-OLPNRMFO.js.map → store-coordination-provider-MEQ2MJQG.js.map} +1 -1
- package/dist/sync/index.js +10 -11
- package/dist/sync/index.js.map +1 -1
- package/dist/team/index.js +15 -16
- package/dist/tiers/index.js +11 -12
- package/dist/to/index.js +2 -3
- package/dist/to/index.js.map +1 -1
- package/dist/transactions/index.js +3 -4
- package/dist/transactions/index.js.map +1 -1
- package/dist/{ulid-VQW6ERQN.js → ulid-4MKXG325.js} +1 -2
- package/dist/util/index.js +1 -2
- package/dist/util/index.js.map +1 -1
- package/dist/{vault-diff-FE5J35NJ.js → vault-diff-C6WUJFNP.js} +1 -2
- package/dist/vault-head/index.js +8 -9
- package/dist/vault-head/index.js.map +1 -1
- package/dist/{verify-WYOFLSNA.js → verify-KOV2G5D6.js} +5 -6
- package/dist/{verify-WYOFLSNA.js.map → verify-KOV2G5D6.js.map} +1 -1
- package/dist/walk-3UQBRMDV.js +21 -0
- package/dist/with-formula/derivations/dispatch.d.ts +16 -1
- package/dist/with-formula/derivations/registry.d.ts +20 -0
- package/dist/with-formula/derivations/trigger-match.d.ts +104 -0
- package/dist/with-formula/derivations/types.d.ts +61 -0
- package/dist/with-party/team/roster-epoch.d.ts +71 -0
- package/dist/with-party/team/roster-tag.d.ts +1 -1
- package/dist/with-shape/introspection/behaviors.d.ts +7 -0
- package/dist/with-shape/introspection/describe.d.ts +10 -1
- package/dist/with-shape/introspection/field-meta.d.ts +86 -0
- package/dist/withdraw-accessible-EL5GXZBS.js +27 -0
- package/package.json +8 -3
- package/dist/api-OAZLPNVV.js +0 -20
- package/dist/chunk-4FPEWQKF.js.map +0 -1
- package/dist/chunk-5263OEM3.js +0 -344
- package/dist/chunk-5263OEM3.js.map +0 -1
- package/dist/chunk-GU3LQYW2.js.map +0 -1
- package/dist/chunk-JBIV4FLR.js.map +0 -1
- package/dist/chunk-JJZIIJSA.js.map +0 -1
- package/dist/chunk-KHKKD62N.js.map +0 -1
- package/dist/chunk-NO272T7Q.js.map +0 -1
- package/dist/chunk-OMHHGOG4.js.map +0 -1
- package/dist/chunk-P6ASQOZR.js.map +0 -1
- package/dist/chunk-PRHCMEUK.js.map +0 -1
- package/dist/chunk-PZ5AY32C.js +0 -10
- package/dist/chunk-RDHUZ674.js.map +0 -1
- package/dist/chunk-VAG47QHV.js +0 -81
- package/dist/chunk-VAG47QHV.js.map +0 -1
- package/dist/chunk-VVAVTSTR.js.map +0 -1
- package/dist/chunk-YPSOHDNC.js.map +0 -1
- package/dist/chunk-ZTYG36DH.js.map +0 -1
- package/dist/collection-facade-6IY2LW6W.js +0 -45
- package/dist/computed-ASBNTLOK.js +0 -11
- package/dist/derive-TCTS7ULE.js +0 -22
- package/dist/dispatch-FNCCONFK.js +0 -194
- package/dist/dispatch-FNCCONFK.js.map +0 -1
- package/dist/executor-AFHQYRAU.js +0 -9
- package/dist/executor-CDIMJVE2.js +0 -29
- package/dist/executor-YYDW6XQI.js +0 -9
- package/dist/export-accessible-WADNWX35.js +0 -23
- package/dist/extract-partition-SHQYQSWE.js +0 -38
- package/dist/find-SZBL2HPB.js +0 -11
- package/dist/issue-2DGG7NKE.js +0 -19
- package/dist/liberate-7NEPRE52.js +0 -25
- package/dist/link-set-WHTYVTOV.js +0 -31
- package/dist/noydb-BQ3ZTN2Z.js +0 -86
- package/dist/register-GLCOH73C.js +0 -32
- package/dist/registry-GWGHZWGP.js +0 -19
- package/dist/registry-IWFMXCHX.js +0 -9
- package/dist/registry-Q3FG3OAX.js +0 -9
- package/dist/registry-T346IZCF.js +0 -18
- package/dist/request-withdrawal-2RERJECX.js +0 -31
- package/dist/revoke-4NRSCPNW.js +0 -24
- package/dist/signer-HJHTGX7X.js +0 -25
- package/dist/storage-ZYYAB3J3.js +0 -23
- package/dist/walk-LTV7LOCN.js +0 -21
- package/dist/withdraw-accessible-V4XCPH7U.js +0 -28
- package/dist/withdraw-accessible-V4XCPH7U.js.map +0 -1
- package/dist/zod-HAJM7LMS.js +0 -14763
- package/dist/zod-HAJM7LMS.js.map +0 -1
- /package/dist/{api-OAZLPNVV.js.map → api-TXFOVOXX.js.map} +0 -0
- /package/dist/{chunk-X6TBQKHW.js.map → chunk-2577DKXB.js.map} +0 -0
- /package/dist/{chunk-L3FHEWA3.js.map → chunk-2N4GY74U.js.map} +0 -0
- /package/dist/{chunk-626TSARM.js.map → chunk-2Y4IMKA6.js.map} +0 -0
- /package/dist/{chunk-7CWII4BL.js.map → chunk-3RCJJBNR.js.map} +0 -0
- /package/dist/{chunk-M7UC2QPT.js.map → chunk-453F654R.js.map} +0 -0
- /package/dist/{chunk-2QNKXGUS.js.map → chunk-4GVM6QZA.js.map} +0 -0
- /package/dist/{chunk-AB5P32RE.js.map → chunk-4OZNXTO4.js.map} +0 -0
- /package/dist/{chunk-L3HDEHGM.js.map → chunk-5VCRVKOZ.js.map} +0 -0
- /package/dist/{chunk-6AQIFBSP.js.map → chunk-5WDXHNSW.js.map} +0 -0
- /package/dist/{chunk-BOFRKAUS.js.map → chunk-6GMZ7HEE.js.map} +0 -0
- /package/dist/{chunk-XBFEKTIY.js.map → chunk-6I2RQCET.js.map} +0 -0
- /package/dist/{chunk-UCUALOSM.js.map → chunk-6YXCPL4T.js.map} +0 -0
- /package/dist/{chunk-BYBB4ABD.js.map → chunk-77K4PG6P.js.map} +0 -0
- /package/dist/{chunk-S2VG3ABP.js.map → chunk-7MG2LHO5.js.map} +0 -0
- /package/dist/{chunk-EO2KGKEJ.js.map → chunk-7V4TP3AF.js.map} +0 -0
- /package/dist/{chunk-LFDMKZIP.js.map → chunk-ANATMFIO.js.map} +0 -0
- /package/dist/{chunk-T3PHCEN4.js.map → chunk-ANSIZYEG.js.map} +0 -0
- /package/dist/{chunk-ZKRRBRSZ.js.map → chunk-AO42KJO6.js.map} +0 -0
- /package/dist/{chunk-VFIWDPXZ.js.map → chunk-BLN54W3L.js.map} +0 -0
- /package/dist/{chunk-ZQ2UUHSL.js.map → chunk-BM5TWITZ.js.map} +0 -0
- /package/dist/{chunk-WLFABTZ6.js.map → chunk-BOET4NA4.js.map} +0 -0
- /package/dist/{chunk-FOG7YEJP.js.map → chunk-BOWNCWZT.js.map} +0 -0
- /package/dist/{chunk-7XODKGTW.js.map → chunk-BSFNRLK2.js.map} +0 -0
- /package/dist/{chunk-J4MN6XIU.js.map → chunk-BZ3534YM.js.map} +0 -0
- /package/dist/{chunk-IF56DYJK.js.map → chunk-CPWQB3N5.js.map} +0 -0
- /package/dist/{chunk-SHILAQH5.js.map → chunk-DGOZ4UZD.js.map} +0 -0
- /package/dist/{chunk-BWWUXE3L.js.map → chunk-ELNXJMGB.js.map} +0 -0
- /package/dist/{chunk-44C2URL7.js.map → chunk-EQEYOJBM.js.map} +0 -0
- /package/dist/{chunk-Y3XWRDAM.js.map → chunk-EYBQEIUY.js.map} +0 -0
- /package/dist/{chunk-Z7ZXZL6Y.js.map → chunk-FAHMLERK.js.map} +0 -0
- /package/dist/{chunk-EXDIHWFO.js.map → chunk-FMZY5Q6L.js.map} +0 -0
- /package/dist/{chunk-H6WXKZL7.js.map → chunk-FXBIP2WD.js.map} +0 -0
- /package/dist/{chunk-672U6STZ.js.map → chunk-GPEQUXHL.js.map} +0 -0
- /package/dist/{chunk-Z2PWOSCJ.js.map → chunk-GY4WYNNG.js.map} +0 -0
- /package/dist/{chunk-4A4TYISP.js.map → chunk-JBDFMYKQ.js.map} +0 -0
- /package/dist/{chunk-POS53FG6.js.map → chunk-JMGDHKQF.js.map} +0 -0
- /package/dist/{chunk-Q7GEDVHC.js.map → chunk-K6LHRFBL.js.map} +0 -0
- /package/dist/{chunk-4JDIRUTT.js.map → chunk-K7NTTA6P.js.map} +0 -0
- /package/dist/{chunk-26W5VETY.js.map → chunk-KG7TZKZG.js.map} +0 -0
- /package/dist/{chunk-RJ7RIIX6.js.map → chunk-KJIMGIWO.js.map} +0 -0
- /package/dist/{chunk-F7ZFRPGQ.js.map → chunk-KTFRCC5C.js.map} +0 -0
- /package/dist/{chunk-HSGEIMJS.js.map → chunk-KUJDV5QH.js.map} +0 -0
- /package/dist/{chunk-UPJMBMCR.js.map → chunk-L742JPKZ.js.map} +0 -0
- /package/dist/{chunk-4TZUFNXL.js.map → chunk-L7CIOOBW.js.map} +0 -0
- /package/dist/{chunk-7LYUJNU3.js.map → chunk-LWBCUYZW.js.map} +0 -0
- /package/dist/{chunk-JHLJQUXU.js.map → chunk-MUM7IANK.js.map} +0 -0
- /package/dist/{chunk-2GXEQUEX.js.map → chunk-MVMXZYXT.js.map} +0 -0
- /package/dist/{chunk-XLPXGN66.js.map → chunk-NA2NIJZI.js.map} +0 -0
- /package/dist/{chunk-S6YB5ZRP.js.map → chunk-NKHRDYOR.js.map} +0 -0
- /package/dist/{chunk-XJ3FEKEY.js.map → chunk-NQKIUNW5.js.map} +0 -0
- /package/dist/{chunk-6NRVFD55.js.map → chunk-PT43Y56J.js.map} +0 -0
- /package/dist/{chunk-5ACAVJUI.js.map → chunk-Q2PU57HC.js.map} +0 -0
- /package/dist/{chunk-E6YA6UAP.js.map → chunk-Q7HZX3IF.js.map} +0 -0
- /package/dist/{chunk-4ZPE6SKS.js.map → chunk-QIBVIOXO.js.map} +0 -0
- /package/dist/{chunk-WLLUM35R.js.map → chunk-QIZPZMUI.js.map} +0 -0
- /package/dist/{chunk-LKFKXS5K.js.map → chunk-RMF67KCG.js.map} +0 -0
- /package/dist/{chunk-YCSM3GZU.js.map → chunk-RMS3NEA3.js.map} +0 -0
- /package/dist/{chunk-OPXR4PB2.js.map → chunk-SFAWCTEM.js.map} +0 -0
- /package/dist/{chunk-3QARDAYW.js.map → chunk-SKGMN35F.js.map} +0 -0
- /package/dist/{chunk-W5LHQXZU.js.map → chunk-SL3JAAKN.js.map} +0 -0
- /package/dist/{chunk-UALOYGCP.js.map → chunk-SPYWXKJN.js.map} +0 -0
- /package/dist/{chunk-QU3YUP2X.js.map → chunk-SZJ3DLZA.js.map} +0 -0
- /package/dist/{chunk-225O5CXQ.js.map → chunk-TFR7DSOV.js.map} +0 -0
- /package/dist/{chunk-X67FCULK.js.map → chunk-TRGTKX5E.js.map} +0 -0
- /package/dist/{chunk-JVLSU7S2.js.map → chunk-TUFM4UZP.js.map} +0 -0
- /package/dist/{chunk-HTGRQZFB.js.map → chunk-UGTBXF5U.js.map} +0 -0
- /package/dist/{chunk-THNJ3IKU.js.map → chunk-ULUMAZ5S.js.map} +0 -0
- /package/dist/{chunk-XDVVBETV.js.map → chunk-UXVWEX5L.js.map} +0 -0
- /package/dist/{chunk-FKFIEEY6.js.map → chunk-UXWB3FPF.js.map} +0 -0
- /package/dist/{chunk-CBRS2NEK.js.map → chunk-VTFVLCUH.js.map} +0 -0
- /package/dist/{chunk-TOV6VMHF.js.map → chunk-VXANTWBJ.js.map} +0 -0
- /package/dist/{chunk-VSLUSXVK.js.map → chunk-VXGSWL6L.js.map} +0 -0
- /package/dist/{chunk-HQINBNHM.js.map → chunk-WEQEYLCS.js.map} +0 -0
- /package/dist/{chunk-U6GCYG2T.js.map → chunk-X2DLENDQ.js.map} +0 -0
- /package/dist/{chunk-XVU7J43V.js.map → chunk-XLMEZIAJ.js.map} +0 -0
- /package/dist/{chunk-ILSR22WM.js.map → chunk-XTXOCYOJ.js.map} +0 -0
- /package/dist/{chunk-KDJGJR7F.js.map → chunk-YSRUYAVU.js.map} +0 -0
- /package/dist/{chunk-NLKLXXTO.js.map → chunk-YYP7WSEB.js.map} +0 -0
- /package/dist/{chunk-4G25SDQL.js.map → chunk-ZN4FD4PE.js.map} +0 -0
- /package/dist/{chunk-XSN63FUS.js.map → chunk-ZORTV6NH.js.map} +0 -0
- /package/dist/{chunk-S3I7VKID.js.map → chunk-ZVO4QVPD.js.map} +0 -0
- /package/dist/{chunk-PZ5AY32C.js.map → collection-facade-4GRREZ6C.js.map} +0 -0
- /package/dist/{collection-facade-6IY2LW6W.js.map → computed-VPOKQK4N.js.map} +0 -0
- /package/dist/{computed-ASBNTLOK.js.map → derive-6O5SWQKN.js.map} +0 -0
- /package/dist/{derive-TCTS7ULE.js.map → enclave-KJOTOH7X.js.map} +0 -0
- /package/dist/{enclave-4P4KH5ZW.js.map → executor-5NIMLSKZ.js.map} +0 -0
- /package/dist/{executor-AFHQYRAU.js.map → executor-AQVXV5GZ.js.map} +0 -0
- /package/dist/{executor-CDIMJVE2.js.map → executor-PUAO6AKJ.js.map} +0 -0
- /package/dist/{executor-YYDW6XQI.js.map → export-accessible-72EQNBMR.js.map} +0 -0
- /package/dist/{export-accessible-WADNWX35.js.map → extract-partition-PUYNU3UF.js.map} +0 -0
- /package/dist/{extract-partition-SHQYQSWE.js.map → find-2ABFCZX4.js.map} +0 -0
- /package/dist/{find-SZBL2HPB.js.map → issue-SIDORTSZ.js.map} +0 -0
- /package/dist/{issue-2DGG7NKE.js.map → ledger-F33ZVMTK.js.map} +0 -0
- /package/dist/{ledger-4X5ZH43X.js.map → liberate-LCDPNAG2.js.map} +0 -0
- /package/dist/{liberate-7NEPRE52.js.map → link-set-FKNWAYKS.js.map} +0 -0
- /package/dist/{link-set-WHTYVTOV.js.map → managed-secret-PQYKSR6T.js.map} +0 -0
- /package/dist/{managed-secret-CXALLEUB.js.map → noydb-DUXZPKSN.js.map} +0 -0
- /package/dist/{noydb-BQ3ZTN2Z.js.map → read-only-facade-BIGO37U3.js.map} +0 -0
- /package/dist/{read-only-facade-CHCKSEPD.js.map → register-I2DZXGAR.js.map} +0 -0
- /package/dist/{register-GLCOH73C.js.map → registry-23WF3TGH.js.map} +0 -0
- /package/dist/{registry-GWGHZWGP.js.map → registry-4AYVUNXK.js.map} +0 -0
- /package/dist/{registry-IWFMXCHX.js.map → registry-VSSQPIGF.js.map} +0 -0
- /package/dist/{registry-Q3FG3OAX.js.map → registry-YLEWMGAC.js.map} +0 -0
- /package/dist/{registry-T346IZCF.js.map → request-withdrawal-KFQHEZ25.js.map} +0 -0
- /package/dist/{request-withdrawal-2RERJECX.js.map → revoke-DQDZAZZM.js.map} +0 -0
- /package/dist/{revoke-4NRSCPNW.js.map → signer-WAMDZHEN.js.map} +0 -0
- /package/dist/{signer-HJHTGX7X.js.map → stale-DDL7WQEZ.js.map} +0 -0
- /package/dist/{stale-5I36LPVK.js.map → storage-FLR73HHF.js.map} +0 -0
- /package/dist/{storage-ZYYAB3J3.js.map → ulid-4MKXG325.js.map} +0 -0
- /package/dist/{ulid-VQW6ERQN.js.map → vault-diff-C6WUJFNP.js.map} +0 -0
- /package/dist/{vault-diff-FE5J35NJ.js.map → walk-3UQBRMDV.js.map} +0 -0
- /package/dist/{walk-LTV7LOCN.js.map → withdraw-accessible-EL5GXZBS.js.map} +0 -0
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
import {
|
|
2
2
|
assertTierAccess
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-UGTBXF5U.js";
|
|
4
4
|
import {
|
|
5
5
|
dekKey,
|
|
6
6
|
liveRecordIsElevated,
|
|
7
7
|
liveRecordTier
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-JMGDHKQF.js";
|
|
9
9
|
import {
|
|
10
10
|
buildRecordAad,
|
|
11
11
|
openEnvelopeJson,
|
|
12
12
|
writeEnvelopeBody
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-77K4PG6P.js";
|
|
14
14
|
import {
|
|
15
15
|
buildRecordEnvelope,
|
|
16
16
|
buildSealedRecordEnvelope
|
|
17
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-SZJ3DLZA.js";
|
|
18
18
|
import {
|
|
19
19
|
base64ToBuffer,
|
|
20
20
|
bufferToBase64,
|
|
@@ -27,7 +27,7 @@ import {
|
|
|
27
27
|
sha256Hex,
|
|
28
28
|
unwrapCek,
|
|
29
29
|
wrapCek
|
|
30
|
-
} from "./chunk-
|
|
30
|
+
} from "./chunk-SL3JAAKN.js";
|
|
31
31
|
import {
|
|
32
32
|
BLOB_ADDRESS_KEY_ID,
|
|
33
33
|
BlobIntentPendingError,
|
|
@@ -39,7 +39,7 @@ import {
|
|
|
39
39
|
UnsupportedTierCompositionError,
|
|
40
40
|
ValidationError,
|
|
41
41
|
isConflictError
|
|
42
|
-
} from "./chunk-
|
|
42
|
+
} from "./chunk-7O3Y4PPD.js";
|
|
43
43
|
|
|
44
44
|
// src/with-shape/blobs/blob-pinning.ts
|
|
45
45
|
function memoryBlobPinStore() {
|
|
@@ -3137,4 +3137,4 @@ export {
|
|
|
3137
3137
|
DEFAULT_CHUNK_SIZE,
|
|
3138
3138
|
BlobSet
|
|
3139
3139
|
};
|
|
3140
|
-
//# sourceMappingURL=chunk-
|
|
3140
|
+
//# sourceMappingURL=chunk-BM5TWITZ.js.map
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
envelopeBodyForHash
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-77K4PG6P.js";
|
|
4
4
|
import {
|
|
5
5
|
sha256Hex
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-SL3JAAKN.js";
|
|
7
7
|
|
|
8
8
|
// src/with-commit/history/ledger/entry.ts
|
|
9
9
|
function canonicalJson(value) {
|
|
@@ -67,4 +67,4 @@ export {
|
|
|
67
67
|
parseIndex,
|
|
68
68
|
envelopePayloadHash
|
|
69
69
|
};
|
|
70
|
-
//# sourceMappingURL=chunk-
|
|
70
|
+
//# sourceMappingURL=chunk-BOET4NA4.js.map
|
|
@@ -2,10 +2,10 @@ import {
|
|
|
2
2
|
base64ToBuffer,
|
|
3
3
|
decryptBytesWithAAD,
|
|
4
4
|
encryptBytesWithAAD
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-SL3JAAKN.js";
|
|
6
6
|
import {
|
|
7
7
|
TamperedError
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-7O3Y4PPD.js";
|
|
9
9
|
|
|
10
10
|
// src/kernel/enclave/classify/compare.ts
|
|
11
11
|
var subtle = globalThis.crypto.subtle;
|
|
@@ -92,4 +92,4 @@ export {
|
|
|
92
92
|
openVdigPayload,
|
|
93
93
|
evaluateKofN
|
|
94
94
|
};
|
|
95
|
-
//# sourceMappingURL=chunk-
|
|
95
|
+
//# sourceMappingURL=chunk-BOWNCWZT.js.map
|
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import {
|
|
2
2
|
buildAccessibleBundle,
|
|
3
3
|
resolveAccessibleCollections
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-L7CIOOBW.js";
|
|
5
5
|
import {
|
|
6
6
|
buildRecordEnvelope
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-SZJ3DLZA.js";
|
|
8
8
|
import {
|
|
9
9
|
sha256Hex
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-SL3JAAKN.js";
|
|
11
11
|
import {
|
|
12
12
|
ReadOnlyError
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-7O3Y4PPD.js";
|
|
14
14
|
|
|
15
15
|
// src/with-audit/portability/withdraw-accessible.ts
|
|
16
16
|
var FROZEN_SNAPSHOTS_COLLECTION = "_frozen_snapshots";
|
|
@@ -117,4 +117,4 @@ export {
|
|
|
117
117
|
freezeAndDeleteClosure,
|
|
118
118
|
withdrawAccessibleData
|
|
119
119
|
};
|
|
120
|
-
//# sourceMappingURL=chunk-
|
|
120
|
+
//# sourceMappingURL=chunk-BSFNRLK2.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
ValidationError
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-7O3Y4PPD.js";
|
|
4
4
|
|
|
5
5
|
// src/with-formula/derivations/with-derivation.ts
|
|
6
6
|
function withDerivation(spec) {
|
|
@@ -38,11 +38,34 @@ function withDerivation(spec) {
|
|
|
38
38
|
`withDerivation: triggerBy.collection must not equal the source "${spec.source}" (use sources[] for same-id triggers)`
|
|
39
39
|
);
|
|
40
40
|
}
|
|
41
|
-
|
|
41
|
+
const hasOn = typeof t.on === "string";
|
|
42
|
+
const hasMatch = Array.isArray(t.match);
|
|
43
|
+
if (hasOn === hasMatch) {
|
|
44
|
+
throw new ValidationError(
|
|
45
|
+
`withDerivation: triggerBy on "${t.collection}" needs exactly one of \`on\` or \`match\``
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
if (hasOn && t.on.length === 0) {
|
|
42
49
|
throw new ValidationError(
|
|
43
50
|
`withDerivation: triggerBy on "${t.collection}" needs a non-empty \`on\` (the FK field on the source)`
|
|
44
51
|
);
|
|
45
52
|
}
|
|
53
|
+
if (hasMatch) {
|
|
54
|
+
const match = t.match;
|
|
55
|
+
if (match.length === 0) {
|
|
56
|
+
throw new ValidationError(`withDerivation: triggerBy match on "${t.collection}" must be non-empty`);
|
|
57
|
+
}
|
|
58
|
+
const seen = /* @__PURE__ */ new Set();
|
|
59
|
+
for (const p of match) {
|
|
60
|
+
if (typeof p?.from !== "string" || p.from.length === 0 || typeof p?.to !== "string" || p.to.length === 0) {
|
|
61
|
+
throw new ValidationError(`withDerivation: triggerBy match on "${t.collection}" needs non-empty \`from\` and \`to\` in every pair`);
|
|
62
|
+
}
|
|
63
|
+
if (seen.has(p.to)) {
|
|
64
|
+
throw new ValidationError(`withDerivation: triggerBy match on "${t.collection}" repeats \`to: "${p.to}"\` \u2014 two pairs constraining one source field is a contradiction, not a wider match`);
|
|
65
|
+
}
|
|
66
|
+
seen.add(p.to);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
46
69
|
if (t.maxFanout !== void 0 && (!Number.isInteger(t.maxFanout) || t.maxFanout < 1)) {
|
|
47
70
|
throw new ValidationError(
|
|
48
71
|
`withDerivation: triggerBy maxFanout on "${t.collection}" must be a positive integer (got ${String(t.maxFanout)}).`
|
|
@@ -126,4 +149,4 @@ export {
|
|
|
126
149
|
withDerivation,
|
|
127
150
|
withRollup
|
|
128
151
|
};
|
|
129
|
-
//# sourceMappingURL=chunk-
|
|
152
|
+
//# sourceMappingURL=chunk-BUE2D7PX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/with-formula/derivations/with-derivation.ts","../src/with-formula/derivations/with-rollup.ts"],"sourcesContent":["import { ValidationError } from '../../kernel/errors.js'\nimport type { DerivationSpec, DerivationStrategy } from './types.js'\n\n/**\n * Register a deterministic derivation: one source collection → one or\n * more typed outputs, computed by the user's `derive` function on\n * plaintext after DEK unwrap. Outputs are encrypted with the same DEK\n * as the source and written via the standard `Collection.put` path.\n *\n * See design-history/2026-05-01-dim14-derivation-v1-design.md.\n */\nexport function withDerivation<\n TSource extends Record<string, unknown>,\n TOutputs extends Record<string, Record<string, unknown> | ReadonlyArray<Record<string, unknown>>>,\n>(spec: DerivationSpec<TSource, TOutputs>): DerivationStrategy {\n if (!spec.source || spec.source.length === 0) {\n throw new ValidationError('withDerivation: source collection name is required')\n }\n if (!spec.outputs || Object.keys(spec.outputs).length === 0) {\n throw new ValidationError('withDerivation: outputs map must declare at least one output')\n }\n if (spec.deterministic !== true) {\n throw new ValidationError('withDerivation: v1 only supports deterministic derivations')\n }\n if (typeof spec.derive !== 'function') {\n throw new ValidationError('withDerivation: derive must be a function')\n }\n\n // Validate declared sibling sources. Each must be a non-empty\n // string and must differ from the primary source — a self-reference\n // would double-register the strategy under the same `_bySource` key.\n if (spec.sources !== undefined) {\n for (const extra of spec.sources) {\n if (typeof extra !== 'string' || extra.length === 0) {\n throw new ValidationError('withDerivation: each entry in sources[] must be a non-empty string')\n }\n if (extra === spec.source) {\n throw new ValidationError(\n `withDerivation: sources[] must not contain the primary source \"${spec.source}\"`,\n )\n }\n }\n }\n\n // Validate FK triggers. Each `collection` must be a non-empty\n // string differing from the primary source, and `on` a non-empty field.\n if (spec.triggerBy !== undefined) {\n for (const t of spec.triggerBy) {\n if (typeof t?.collection !== 'string' || t.collection.length === 0) {\n throw new ValidationError('withDerivation: each triggerBy entry needs a non-empty `collection`')\n }\n if (t.collection === spec.source) {\n throw new ValidationError(\n `withDerivation: triggerBy.collection must not equal the source \"${spec.source}\" (use sources[] for same-id triggers)`,\n )\n }\n const hasOn = typeof (t as { on?: unknown }).on === 'string'\n const hasMatch = Array.isArray((t as { match?: unknown }).match)\n if (hasOn === hasMatch) {\n throw new ValidationError(\n `withDerivation: triggerBy on \"${t.collection}\" needs exactly one of \\`on\\` or \\`match\\``,\n )\n }\n if (hasOn && (t as { on: string }).on.length === 0) {\n throw new ValidationError(\n `withDerivation: triggerBy on \"${t.collection}\" needs a non-empty \\`on\\` (the FK field on the source)`,\n )\n }\n if (hasMatch) {\n const match = (t as { match: ReadonlyArray<{ from: string; to: string }> }).match\n if (match.length === 0) {\n throw new ValidationError(`withDerivation: triggerBy match on \"${t.collection}\" must be non-empty`)\n }\n const seen = new Set<string>()\n for (const p of match) {\n if (typeof p?.from !== 'string' || p.from.length === 0 || typeof p?.to !== 'string' || p.to.length === 0) {\n throw new ValidationError(`withDerivation: triggerBy match on \"${t.collection}\" needs non-empty \\`from\\` and \\`to\\` in every pair`)\n }\n if (seen.has(p.to)) {\n throw new ValidationError(`withDerivation: triggerBy match on \"${t.collection}\" repeats \\`to: \"${p.to}\"\\` — two pairs constraining one source field is a contradiction, not a wider match`)\n }\n seen.add(p.to)\n }\n }\n if (t.maxFanout !== undefined && (!Number.isInteger(t.maxFanout) || t.maxFanout < 1)) {\n throw new ValidationError(\n `withDerivation: triggerBy maxFanout on \"${t.collection}\" must be a positive integer (got ${String(t.maxFanout)}).`,\n )\n }\n }\n }\n\n // Validate array-shape outputs.\n const lifecycleMode = typeof spec.lifecycle === 'string' ? spec.lifecycle : spec.lifecycle.mode\n for (const [outputKey, outputSpec] of Object.entries(spec.outputs)) {\n // Self-write output (collection === source): reverse-denorm must declare\n // `denorm` (the fields it owns) — field-level provenance.\n if (outputSpec.shape === 'record' && outputSpec.collection === spec.source) {\n if (!outputSpec.denorm || outputSpec.denorm.length === 0) {\n throw new ValidationError(\n `withDerivation: self-write output \"${outputKey}\" (collection === source \"${spec.source}\") `\n + 'must declare `denorm: [...]` naming the fields it maintains.',\n )\n }\n }\n if (outputSpec.shape === 'array') {\n if (lifecycleMode !== 'eager') {\n throw new ValidationError(\n `withDerivation: shape 'array' supports lifecycle 'eager' only in this release `\n + `Output \"${outputKey}\" declared lifecycle '${lifecycleMode}'. `\n + 'Switch to `lifecycle: \"eager\"` or use shape: \"record\".',\n )\n }\n if (typeof outputSpec.key !== 'function') {\n throw new ValidationError(\n `withDerivation: shape 'array' output \"${outputKey}\" requires \\`key: (out) => string\\`.`,\n )\n }\n if (outputSpec.maxFanout !== undefined) {\n if (!Number.isInteger(outputSpec.maxFanout) || outputSpec.maxFanout < 1) {\n throw new ValidationError(\n `withDerivation: maxFanout for output \"${outputKey}\" must be a positive integer `\n + `(got ${String(outputSpec.maxFanout)}).`,\n )\n }\n }\n }\n }\n\n return {\n __noydb_strategy: 'derivation',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n spec: spec as DerivationSpec<any, any>,\n }\n}\n","import { ValidationError } from '../../kernel/errors.js'\nimport type { DerivationSpec, DerivationStrategy } from './types.js'\n\n/** Options for {@link withRollup} (#844b — was an inline literal, so unnameable). */\nexport interface WithRollupOptions<\n TChild extends Record<string, unknown> = Record<string, unknown>,\n TParent extends Record<string, unknown> = Record<string, unknown>,\n> {\n /** Child collection — the trigger. */\n readonly from: string\n /** FK field on the child pointing at the parent id. */\n readonly key: keyof TChild & string\n /** Parent collection carrying the maintained summary. */\n readonly into: string\n /** Field on the parent to maintain. */\n readonly field: keyof TParent & string\n /** Reduces the matching children to the value written at `field`. */\n readonly compute: (children: TChild[]) => unknown\n}\n\n/**\n * `withRollup` — aggregate many child records onto a single field of their\n * parent. The reverse of a join: instead of reading children\n * on demand, the parent carries a maintained summary.\n *\n * ```ts\n * withRollup<Sale, Buyer>({\n * from: 'sales', // child collection (the trigger)\n * key: 'buyerId', // FK on the child → parent id\n * into: 'buyers', // parent collection\n * field: 'revenueByYear', // field on the parent to maintain\n * compute: (sales) => groupSumByYear(sales, 'total'),\n * })\n * ```\n *\n * On every write OR delete of a `from` record, the parent at id `child[key]`\n * is recomputed: `compute(allChildren where child[key] === parentId)` is\n * patched onto `parent[field]`. A parent write also recomputes its own\n * aggregate (so a parent created after its children still fills in). Only the\n * `field` is touched — the rest of the parent record is never clobbered — and\n * a value-equality guard suppresses no-op writes. The aggregate is gap-free\n * with respect to child inserts, updates, and deletes.\n *\n * Desugars to a `withDerivation` strategy carrying a `rollup` marker; dispatch\n * handles it without invoking the executor. Eager-only in this slice.\n */\nexport function withRollup<\n TChild extends Record<string, unknown> = Record<string, unknown>,\n TParent extends Record<string, unknown> = Record<string, unknown>,\n>(opts: WithRollupOptions<TChild, TParent>): DerivationStrategy {\n const { from, key, into, field, compute } = opts\n if (!from || from.length === 0) {\n throw new ValidationError('withRollup: `from` (child collection) is required')\n }\n if (!into || into.length === 0) {\n throw new ValidationError('withRollup: `into` (parent collection) is required')\n }\n if (from === into) {\n throw new ValidationError('withRollup: `from` and `into` must be different collections')\n }\n if (!key || key.length === 0) {\n throw new ValidationError('withRollup: `key` (FK field on the child) is required')\n }\n if (!field || field.length === 0) {\n throw new ValidationError('withRollup: `field` (target field on the parent) is required')\n }\n if (typeof compute !== 'function') {\n throw new ValidationError('withRollup: `compute` must be a function')\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const spec: DerivationSpec<any, any> = {\n source: into, // the parent record is what carries the rolled-up field\n deterministic: true,\n rollup: { from, key, field, compute: compute as (children: unknown[]) => unknown },\n // Synthetic self-write output for registry / cycle bookkeeping. Dispatch\n // patches `field` directly (value-equality guarded); the executor is not run.\n outputs: { value: { shape: 'record', collection: into, denorm: [field] } },\n derive: () => ({ value: {} }), // never invoked for a rollup strategy\n lifecycle: 'eager',\n }\n\n return { __noydb_strategy: 'derivation', spec }\n}\n"],"mappings":";;;;;AAWO,SAAS,eAGd,MAA6D;AAC7D,MAAI,CAAC,KAAK,UAAU,KAAK,OAAO,WAAW,GAAG;AAC5C,UAAM,IAAI,gBAAgB,oDAAoD;AAAA,EAChF;AACA,MAAI,CAAC,KAAK,WAAW,OAAO,KAAK,KAAK,OAAO,EAAE,WAAW,GAAG;AAC3D,UAAM,IAAI,gBAAgB,8DAA8D;AAAA,EAC1F;AACA,MAAI,KAAK,kBAAkB,MAAM;AAC/B,UAAM,IAAI,gBAAgB,4DAA4D;AAAA,EACxF;AACA,MAAI,OAAO,KAAK,WAAW,YAAY;AACrC,UAAM,IAAI,gBAAgB,2CAA2C;AAAA,EACvE;AAKA,MAAI,KAAK,YAAY,QAAW;AAC9B,eAAW,SAAS,KAAK,SAAS;AAChC,UAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAAG;AACnD,cAAM,IAAI,gBAAgB,oEAAoE;AAAA,MAChG;AACA,UAAI,UAAU,KAAK,QAAQ;AACzB,cAAM,IAAI;AAAA,UACR,kEAAkE,KAAK,MAAM;AAAA,QAC/E;AAAA,MACF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9B,UAAM,IAAI,gBAAgB,oDAAoD;AAAA,EAChF;AACA,MAAI,SAAS,MAAM;AACjB,UAAM,IAAI,gBAAgB,6DAA6D;AAAA,EACzF;AACA,MAAI,CAAC,OAAO,IAAI,WAAW,GAAG;AAC5B,UAAM,IAAI,gBAAgB,uDAAuD;AAAA,EACnF;AACA,MAAI,CAAC,SAAS,MAAM,WAAW,GAAG;AAChC,UAAM,IAAI,gBAAgB,8DAA8D;AAAA,EAC1F;AACA,MAAI,OAAO,YAAY,YAAY;AACjC,UAAM,IAAI,gBAAgB,0CAA0C;AAAA,EACtE;AAGA,QAAM,OAAiC;AAAA,IACrC,QAAQ;AAAA;AAAA,IACR,eAAe;AAAA,IACf,QAAQ,EAAE,MAAM,KAAK,OAAO,QAAqD;AAAA;AAAA;AAAA,IAGjF,SAAS,EAAE,OAAO,EAAE,OAAO,UAAU,YAAY,MAAM,QAAQ,CAAC,KAAK,EAAE,EAAE;AAAA,IACzE,QAAQ,OAAO,EAAE,OAAO,CAAC,EAAE;AAAA;AAAA,IAC3B,WAAW;AAAA,EACb;AAEA,SAAO,EAAE,kBAAkB,cAAc,KAAK;AAChD;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
PortabilityNotEnabledError
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-7O3Y4PPD.js";
|
|
4
4
|
|
|
5
5
|
// src/with-audit/portability/strategy.ts
|
|
6
6
|
var NO_PORTABILITY = {
|
|
@@ -27,4 +27,4 @@ var NO_PORTABILITY = {
|
|
|
27
27
|
export {
|
|
28
28
|
NO_PORTABILITY
|
|
29
29
|
};
|
|
30
|
-
//# sourceMappingURL=chunk-
|
|
30
|
+
//# sourceMappingURL=chunk-BZ3534YM.js.map
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import {
|
|
2
|
+
matchesReferencingValue
|
|
3
|
+
} from "./chunk-U4FOQDY4.js";
|
|
4
|
+
import {
|
|
5
|
+
PeriodClosedError
|
|
6
|
+
} from "./chunk-7O3Y4PPD.js";
|
|
7
|
+
|
|
8
|
+
// src/kernel/via/dispatch.ts
|
|
9
|
+
function touchFor(batch, collection) {
|
|
10
|
+
let t = batch.get(collection);
|
|
11
|
+
if (!t) {
|
|
12
|
+
t = { puts: /* @__PURE__ */ new Set(), deletes: /* @__PURE__ */ new Map() };
|
|
13
|
+
batch.set(collection, t);
|
|
14
|
+
}
|
|
15
|
+
return t;
|
|
16
|
+
}
|
|
17
|
+
function resolveRollupDeleteIntents(registry, collectionName, deleted) {
|
|
18
|
+
if (!registry) return [];
|
|
19
|
+
const intents = [];
|
|
20
|
+
for (const { spec } of registry.strategiesForSource(collectionName)) {
|
|
21
|
+
if (!spec.rollup || spec.rollup.from !== collectionName) continue;
|
|
22
|
+
const kv = deleted[spec.rollup.key];
|
|
23
|
+
if (typeof kv === "string" || typeof kv === "number") intents.push({ into: spec.source, parentId: String(kv), field: spec.rollup.field });
|
|
24
|
+
}
|
|
25
|
+
return intents;
|
|
26
|
+
}
|
|
27
|
+
function findRollupSpecForIntent(registry, collectionName, intent) {
|
|
28
|
+
return registry?.strategiesForSource(collectionName).find((s) => s.spec.source === intent.into && s.spec.rollup?.field === intent.field && s.spec.rollup?.from === collectionName)?.spec;
|
|
29
|
+
}
|
|
30
|
+
var WaveContext = class {
|
|
31
|
+
_seen = /* @__PURE__ */ new Set();
|
|
32
|
+
seen(targetKey) {
|
|
33
|
+
if (this._seen.has(targetKey)) return true;
|
|
34
|
+
this._seen.add(targetKey);
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
async function runGraphDispatchWave(vault, batch) {
|
|
39
|
+
const wave = new WaveContext();
|
|
40
|
+
for (const [collectionName, touch] of batch) {
|
|
41
|
+
if (vault.graph.dependentsOf(collectionName).length === 0) continue;
|
|
42
|
+
const coll = vault._getCollection(collectionName);
|
|
43
|
+
if (!coll) continue;
|
|
44
|
+
for (const id of touch.puts) {
|
|
45
|
+
try {
|
|
46
|
+
const stored = await coll._getStoredRecordForDispatch(id);
|
|
47
|
+
if (!stored) continue;
|
|
48
|
+
await coll.dispatchDerivations(id, stored.record, stored.version, wave);
|
|
49
|
+
await coll.dispatchMaterializedViews(id, stored.record, wave);
|
|
50
|
+
} catch (err) {
|
|
51
|
+
console.warn(`[via-dispatch] wave recompute failed for ${collectionName}/${id}:`, err);
|
|
52
|
+
vault._emit("derivation:wave-error", { collection: collectionName, id, error: err });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
for (const [id, intents] of touch.deletes) {
|
|
56
|
+
try {
|
|
57
|
+
await coll._recomputeDeletedRollups(intents, wave);
|
|
58
|
+
await coll.dispatchMaterializedViewsOnDelete(id);
|
|
59
|
+
await coll.dispatchArrayDerivationsOnDelete(id);
|
|
60
|
+
} catch (err) {
|
|
61
|
+
console.warn(`[via-dispatch] wave delete-recompute failed for ${collectionName}/${id}:`, err);
|
|
62
|
+
vault._emit("derivation:wave-error", { collection: collectionName, id, error: err });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
async function putDerivedOutput(outColl, id, value, ctx, options) {
|
|
68
|
+
try {
|
|
69
|
+
await outColl.put(id, value, options);
|
|
70
|
+
return "written";
|
|
71
|
+
} catch (err) {
|
|
72
|
+
if (!(err instanceof PeriodClosedError)) throw err;
|
|
73
|
+
const targetCollection = outColl.name;
|
|
74
|
+
const event = {
|
|
75
|
+
source: ctx.source,
|
|
76
|
+
target: { collection: targetCollection, id },
|
|
77
|
+
period: err.periodName,
|
|
78
|
+
endDate: err.endDate
|
|
79
|
+
};
|
|
80
|
+
ctx.emit("derivation:skipped-frozen", event);
|
|
81
|
+
if (ctx.audit) await ctx.audit(event);
|
|
82
|
+
return "skipped-frozen";
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function ledgerAuditHook(ledger, actor) {
|
|
86
|
+
if (!ledger) return void 0;
|
|
87
|
+
return async (e) => {
|
|
88
|
+
await ledger.append({
|
|
89
|
+
op: "lifecycle",
|
|
90
|
+
collection: e.target.collection,
|
|
91
|
+
id: e.target.id,
|
|
92
|
+
version: 0,
|
|
93
|
+
actor,
|
|
94
|
+
payloadHash: "",
|
|
95
|
+
reason: JSON.stringify({ event: "derivation-skipped-frozen", ...e })
|
|
96
|
+
});
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
async function forgetDerivedFanout(vault, ref, envelope, stats, lookupCompareKeys) {
|
|
100
|
+
const coll = vault._getCollection(ref.collection);
|
|
101
|
+
if (coll) {
|
|
102
|
+
const mv = await coll.dispatchMaterializedViewsOnDelete(ref.id);
|
|
103
|
+
stats.recordsErased += mv.deleted;
|
|
104
|
+
stats.derivedResidueUndecodable.push(...mv.residueUndecodable);
|
|
105
|
+
stats.derivedResidueDeclined.push(...mv.residueDeclined);
|
|
106
|
+
}
|
|
107
|
+
const edges = vault.graph.derivedArtifactsOf(ref.collection);
|
|
108
|
+
if (edges.length === 0 || !coll) return;
|
|
109
|
+
if (edges.some((e) => e.kind === "ref")) {
|
|
110
|
+
const { cascaded, nullified, residue } = await applyLookupRefsFanout(vault, ref.collection, ref.id, lookupCompareKeys);
|
|
111
|
+
stats.lookupReferencesCascaded += cascaded;
|
|
112
|
+
stats.lookupReferencesNullified += nullified;
|
|
113
|
+
stats.lookupReferencesResidue.push(...residue);
|
|
114
|
+
}
|
|
115
|
+
if (edges.some((e) => e.kind === "derivation")) {
|
|
116
|
+
stats.recordsErased += await coll.dispatchArrayDerivationsOnDelete(ref.id, true);
|
|
117
|
+
}
|
|
118
|
+
if (envelope && edges.some((e) => e.kind === "rollup")) {
|
|
119
|
+
const priorRecord = await coll._decodeEnvelope(envelope, ref.id);
|
|
120
|
+
if (priorRecord) {
|
|
121
|
+
for (const r of await coll.dispatchRollupsOnDelete(ref.id, priorRecord)) {
|
|
122
|
+
if (r.outcome === "written") stats.aggregatesRecomputed += 1;
|
|
123
|
+
else if (r.outcome === "skipped-frozen") stats.residueFrozen.push(`${r.into}:${r.parentId}`);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
async function applyLookupRefsFanout(vault, backing, key, compareKeys) {
|
|
129
|
+
let cascaded = 0;
|
|
130
|
+
let nullified = 0;
|
|
131
|
+
const residue = [];
|
|
132
|
+
for (const { referencing, onDelete, keyField } of vault.graph.referencingEdgesOf(backing)) {
|
|
133
|
+
if (onDelete === "restrict") continue;
|
|
134
|
+
const compareKey = keyField === "id" ? key : compareKeys.get(keyField);
|
|
135
|
+
if (compareKey === void 0) {
|
|
136
|
+
residue.push(`${backing}:${key}:${referencing.collection}.${referencing.field}`);
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
const coll = vault._getCollection(referencing.collection);
|
|
140
|
+
if (!coll) continue;
|
|
141
|
+
const matches = (await coll.list()).filter((rec) => matchesReferencingValue(rec, referencing.field, compareKey));
|
|
142
|
+
for (const rec of matches) {
|
|
143
|
+
const id = rec["id"];
|
|
144
|
+
if (id === void 0) continue;
|
|
145
|
+
if (onDelete === "cascade") {
|
|
146
|
+
await coll.delete(id);
|
|
147
|
+
cascaded++;
|
|
148
|
+
} else if (onDelete === "nullify") {
|
|
149
|
+
await coll.put(id, { ...rec, [referencing.field]: null });
|
|
150
|
+
nullified++;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return { cascaded, nullified, residue };
|
|
155
|
+
}
|
|
156
|
+
function selfWriteFieldEqual(a, b) {
|
|
157
|
+
if (a === b) return true;
|
|
158
|
+
if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
|
|
159
|
+
try {
|
|
160
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
161
|
+
} catch {
|
|
162
|
+
return false;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export {
|
|
167
|
+
touchFor,
|
|
168
|
+
resolveRollupDeleteIntents,
|
|
169
|
+
findRollupSpecForIntent,
|
|
170
|
+
runGraphDispatchWave,
|
|
171
|
+
putDerivedOutput,
|
|
172
|
+
ledgerAuditHook,
|
|
173
|
+
forgetDerivedFanout,
|
|
174
|
+
selfWriteFieldEqual
|
|
175
|
+
};
|
|
176
|
+
//# sourceMappingURL=chunk-CARABLSQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/kernel/via/dispatch.ts"],"sourcesContent":["// kernel/via/dispatch.ts — the batched, origin-aware sync/cutover/restore dispatch wave\n// (Via port phase C, #638 Task 4, fixes #621).\n//\n// `Collection._onRecordMutated`'s `sync-apply`/`cutover`/`restore` cases feed touched\n// (collection, id) pairs into a per-session `GraphBatch` (owned by `Vault._collectGraphTouch`)\n// instead of dispatching inline — the `local-write` path keeps its own byte-identical inline\n// dispatch (`wave` stays `undefined` there, per the spec's behavior lock). At batch-flush time\n// `runGraphDispatchWave` decrypts each touched record (id threaded into the decrypt, matching\n// the phase-B at-rest contract) and re-runs the SAME `dispatchDerivations`/\n// `dispatchMaterializedViews` the local-write path uses, sharing one `WaveContext` so N touched\n// records feeding the SAME rollup/MV target recompute exactly once (per-target dedup).\n// See design-history/2026-07-11-via-phase-c-design.md §3.\n\nimport type { ViaGraph } from './graph.js'\nimport type { Collection } from '../collection.js'\nimport type { EncryptedEnvelope } from '../types.js'\nimport { PeriodClosedError } from '../errors.js'\nimport { matchesReferencingValue } from '../../port/with/lookup-strategy.js'\n\n/** One deleted child's resolved rollup PARENT intent (#640) — ids + a field name only. A\n * resolved `parentId` is an id, same class as any touched record id — never a stored value. */\nexport interface RollupDeleteIntent {\n readonly into: string\n readonly parentId: string\n readonly field: string\n}\n\n/** One collection's batched touches this session (#640 widens the #638 `Set<string>` shape):\n * `puts` — the original semantics, unchanged; `deletes` — a deleted record's id mapped to its\n * resolved rollup-parent intents, captured PRE-invalidation by `Collection._onRecordMutated`'s\n * sync-apply delete case (the FK is only readable there — see `kernel/collection.ts\n * #_rollupDeleteIntents`). */\nexport interface GraphTouch {\n readonly puts: Set<string>\n readonly deletes: Map<string, readonly RollupDeleteIntent[]>\n}\n\n/** Per-session touched set — collection → its `GraphTouch`. Metadata only — ids (collection\n * names, record ids INCLUDING resolved rollup parent ids) and field names; NEVER record payload\n * or key material. A resolved parentId is an id, same class as the touched ids — not a stored\n * value. */\nexport type GraphBatch = Map<string, GraphTouch>\n\n/** Get-or-create `batch`'s `GraphTouch` entry for `collection` (#640) — shared by\n * `Vault._collectGraphTouch`/`_collectGraphDelete` so each stays a one-line call. */\nexport function touchFor(batch: GraphBatch, collection: string): GraphTouch {\n let t = batch.get(collection)\n if (!t) {\n t = { puts: new Set(), deletes: new Map() }\n batch.set(collection, t)\n }\n return t\n}\n\n/** #640 — sync, I/O-free: `deleted`'s resolved rollup PARENT intents (the FK is only readable\n * NOW, before the record is gone) — a pure function so `Collection._rollupDeleteIntents` stays\n * a one-line delegator under the kernel-surface ceiling. `registry` is `this.derivationSource\n * ?.registry()`; `collectionName` is `this.name` (the CHILD/`rollup.from` side). Generic over\n * the registry's own spec shape so this file never imports a `with-formula` type (port-layering\n * — via/dispatch.ts must not gain a with-* import). */\nexport function resolveRollupDeleteIntents<S extends { source: string; rollup?: { from: string; key: string; field: string } }>(\n registry: { strategiesForSource(name: string): ReadonlyArray<{ spec: S }> } | undefined,\n collectionName: string,\n deleted: Record<string, unknown>,\n): RollupDeleteIntent[] {\n if (!registry) return []\n const intents: RollupDeleteIntent[] = []\n for (const { spec } of registry.strategiesForSource(collectionName)) {\n if (!spec.rollup || spec.rollup.from !== collectionName) continue\n const kv = deleted[spec.rollup.key]\n if (typeof kv === 'string' || typeof kv === 'number') intents.push({ into: spec.source, parentId: String(kv), field: spec.rollup.field })\n }\n return intents\n}\n\n/** #640 — resolve a `RollupDeleteIntent` back to its registry `spec`. The wave's per-intent\n * driver needs `spec.rollup.compute`, which `GraphBatch`'s metadata-only pin forbids batching —\n * so it's re-resolved here, post-boundary, instead of carried across it. `undefined` if the\n * intent's originating strategy was unregistered between collect time and wave time (residual\n * gap, freshness-only). */\nexport function findRollupSpecForIntent<S extends { source: string; rollup?: { from: string; field: string } }>(\n registry: { strategiesForSource(name: string): ReadonlyArray<{ spec: S }> } | undefined,\n collectionName: string,\n intent: RollupDeleteIntent,\n): S | undefined {\n return registry?.strategiesForSource(collectionName).find((s) => s.spec.source === intent.into && s.spec.rollup?.field === intent.field && s.spec.rollup?.from === collectionName)?.spec\n}\n\n/** One dedup ledger for a single wave — a target is recomputed at most once (mark-on-check). */\nexport class WaveContext {\n private readonly _seen = new Set<string>()\n seen(targetKey: string): boolean {\n if (this._seen.has(targetKey)) return true\n this._seen.add(targetKey)\n return false\n }\n}\n\n/** The slice of `Vault` the wave needs: the shared graph (the #553 zero-cost skip) and cached-\n * collection lookup — never constructs, since a touched collection is, by construction,\n * already open (it just fired `_onRecordMutated`). */\nexport interface VaultLike {\n readonly graph: ViaGraph\n _getCollection(name: string): Collection<Record<string, unknown>> | undefined\n /** #640 (#644 item 3) — structured wave-error surfacing, additive to the existing console.warn. */\n _emit(event: string, payload: unknown): void\n}\n\n/**\n * Run ONE dispatch wave for a completed batch: for each touched (collection, id), decrypt the\n * applied envelope (id threaded), then run the SAME `dispatchDerivations` +\n * `dispatchMaterializedViews` the local-write path uses — with a shared `WaveContext` so N\n * touched records feeding the SAME target recompute once. #553: a collection with no graph\n * out-edges (e.g. money-only) is skipped before any decrypt/dispatch async work.\n */\nexport async function runGraphDispatchWave(vault: VaultLike, batch: GraphBatch): Promise<void> {\n const wave = new WaveContext()\n for (const [collectionName, touch] of batch) {\n if (vault.graph.dependentsOf(collectionName).length === 0) continue\n const coll = vault._getCollection(collectionName)\n if (!coll) continue\n for (const id of touch.puts) {\n try {\n // Decrypt is INSIDE the per-id isolation boundary (whole-branch review Important\n // finding, #638): an undecryptable synced envelope (`TamperedError`) must not\n // escape `_getStoredRecordForDispatch` and abort the wave — that would propagate\n // through `_flushGraphBatch` and reject the surrounding `SyncEngine.pull`/`push`\n // AFTER records were already applied + meta persisted, starving every other\n // touched target in the same batch.\n const stored = await coll._getStoredRecordForDispatch(id)\n if (!stored) continue\n await coll.dispatchDerivations(id, stored.record, stored.version, wave)\n await coll.dispatchMaterializedViews(id, stored.record, wave)\n } catch (err) {\n // #638 Task 5 review mandate: one touched record's recompute must not abort the\n // whole wave (starving co-batched healthy targets) or the pull/push it's nested\n // inside. `PeriodClosedError` never reaches here — `putDerivedOutput` already\n // intercepts it at every output-write call site and turns it into a skip+event.\n // Anything else (a genuine decrypt failure, a derive()/executor bug, a schema\n // violation on the output, ...) is surfaced — not silently swallowed — via the\n // SAME console.warn channel `dispatchDerivations`/the MV executor already use for\n // their own non-strict-mode output failures, then isolated to just this one id.\n // #644 item 3: ADDITIVELY (never in place of the warn) emit a structured event too,\n // so a listener doesn't have to scrape console output to react to a wave failure.\n console.warn(`[via-dispatch] wave recompute failed for ${collectionName}/${id}:`, err)\n vault._emit('derivation:wave-error', { collection: collectionName, id, error: err })\n }\n }\n // #640 — delete-kind touches: the deleted child's rollup-parent intents, resolved (sync,\n // pre-invalidation) at collect time by `Collection._rollupDeleteIntents`. Same per-id\n // isolation as the puts loop above. #658: the wave now ALSO heals MV rows and array-shape\n // derivation output rows for the deleted child — parity with the local-delete boundary\n // (`Collection._doDelete`'s `!internal` block, which already calls all three). Still never\n // routed through `dispatchDerivations` (the mutation-choke-point.test.ts:85-99 pin — sync-\n // applied deletes never RE-DERIVE); `dispatchMaterializedViewsOnDelete`/\n // `dispatchArrayDerivationsOnDelete` only need `id` (MV refresh recomputes+diffs; array-\n // derivation reads its per-source sidecar) and never call `derive()`, so the pin holds.\n for (const [id, intents] of touch.deletes) {\n try {\n await coll._recomputeDeletedRollups(intents, wave)\n // #658: record-shape same-id outputs are left untouched (eraseRecordShapeToo defaults\n // false), matching local delete — the user deletes those directly if wanted.\n // #658: TODO dedup MV refresh per wave — `dispatchMaterializedViewsOnDelete` doesn't\n // accept a `WaveContext` (unlike the put-path `dispatchMaterializedViews`), so N deleted\n // children of one eager MV in a batch each trigger a full refresh pass. Threading `wave`\n // through would touch collection.ts's zero-slack kernel-surface ceiling for a perf-only\n // win; correctness doesn't depend on it (idempotent per source-id) — left as a follow-up.\n await coll.dispatchMaterializedViewsOnDelete(id)\n await coll.dispatchArrayDerivationsOnDelete(id)\n } catch (err) {\n console.warn(`[via-dispatch] wave delete-recompute failed for ${collectionName}/${id}:`, err)\n vault._emit('derivation:wave-error', { collection: collectionName, id, error: err })\n }\n }\n }\n}\n\n/** A record's post-freeze source mutation, for the `'derivation:skipped-frozen'` event\n * and the optional audit-trail entry. See {@link putDerivedOutput}. */\nexport interface DerivationSkippedFrozen {\n readonly source: { readonly collection: string; readonly id: string }\n readonly target: { readonly collection: string; readonly id: string }\n readonly period: string\n readonly endDate: string\n}\n\n/** The minimal put-capable shape `putDerivedOutput` needs. Any `Collection<T>` structurally\n * satisfies this — its real `options` type is a superset of what's declared here. */\nexport interface CollectionLike {\n put(id: string, value: unknown, options?: { readonly source?: string }): Promise<void>\n}\n\nexport interface PutDerivedOutputCtx {\n readonly emit: (ev: string, p: unknown) => void\n readonly source: { readonly collection: string; readonly id: string }\n readonly audit?: ((e: DerivationSkippedFrozen) => Promise<void>) | undefined\n}\n\n/**\n * Attempt a dispatch-driven output write. On `PeriodClosedError` (the closed-period\n * `beforePut` gate — `freezePeriod`/`archivePeriod` add no separate gate, per seam map\n * Part 7): SKIP (no `_ts` stamped — the gate throws before any write happens), emit\n * `'derivation:skipped-frozen'` on the event bus (ALWAYS), and append an audit-trail entry\n * when the with-history ledger is active. Returns `'written' | 'skipped-frozen'`. Any OTHER\n * error propagates unchanged — this helper narrows exactly one error class. The SOURCE\n * write is never wrapped through this helper — only derived-output writes are (§7).\n */\nexport async function putDerivedOutput(\n outColl: CollectionLike, id: string, value: unknown,\n ctx: PutDerivedOutputCtx,\n options?: { readonly source?: string },\n): Promise<'written' | 'skipped-frozen'> {\n try {\n await outColl.put(id, value, options)\n return 'written'\n } catch (err) {\n if (!(err instanceof PeriodClosedError)) throw err\n // Reach-around for the target collection's private `name` — the SAME pattern\n // `with-formula/materialized-views/executor.ts`'s `listOutputIds` already uses to\n // read a `Collection`'s private `adapter`/`vault`/`name` fields from outside the class.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const targetCollection = (outColl as any).name as string\n const event: DerivationSkippedFrozen = {\n source: ctx.source,\n target: { collection: targetCollection, id },\n period: err.periodName,\n endDate: err.endDate,\n }\n ctx.emit('derivation:skipped-frozen', event)\n if (ctx.audit) await ctx.audit(event)\n return 'skipped-frozen'\n }\n}\n\n/** Structural (no static import — kernel spine may not statically reach a with-* service,\n * the S4 gate recipe `check-architecture.mjs`'s port-layering check enforces) shape of the\n * with-history `LedgerStore.append` seam this helper needs. */\ninterface AuditLedgerLike {\n append(input: {\n readonly op: 'lifecycle'\n readonly collection: string\n readonly id: string\n readonly version: number\n readonly actor: string\n readonly payloadHash: string\n readonly reason?: string\n }): Promise<unknown>\n}\n\n/** @internal — the optional with-history ledger audit hook for `putDerivedOutput`, present\n * only when the ledger is active (mirrors every other kernel event's `if (this.ledger)`\n * gate). Encoded as a `'lifecycle'` entry — the existing \"non-data audit event\" op (the\n * same convention `forget`'s JSON-summary-in-`reason` entry uses; `ledger/entry.ts:88-104`). */\nexport function ledgerAuditHook(\n ledger: AuditLedgerLike | undefined, actor: string,\n): ((e: DerivationSkippedFrozen) => Promise<void>) | undefined {\n if (!ledger) return undefined\n return async (e) => {\n await ledger.append({\n op: 'lifecycle', collection: e.target.collection, id: e.target.id, version: 0, actor, payloadHash: '',\n reason: JSON.stringify({ event: 'derivation-skipped-frozen', ...e }),\n })\n }\n}\n\n/** `recomputeRollup`/`dispatchRollupsOnDelete`'s per-target write outcome (#638 Task 6):\n * `'written'`/`'skipped-frozen'` mirror {@link putDerivedOutput}'s result; `'noop'` covers\n * no-parent/no-change/deduped-by-wave — nothing to report either way. */\nexport type RollupOutcome = 'written' | 'skipped-frozen' | 'noop'\n\n/** Mutable accumulator `forgetDerivedFanout` writes into, one per `Vault.forget()` call — keeps\n * the per-ref loop's call site to a single line under vault.ts's tight kernel-surface ceiling.\n * Maps 1:1 onto `ForgetResult`'s additive fields (`with-audit/forget/strategy.ts`). */\nexport interface ForgetFanoutStats {\n recordsErased: number\n aggregatesRecomputed: number\n readonly residueFrozen: string[]\n /** #650 Task 5 (#648) — referencing records tombstoned via a `'ref'` edge's `cascade` policy. */\n lookupReferencesCascaded: number\n /** #650 Task 5 (#648) — referencing fields cleared via a `'ref'` edge's `nullify` policy. */\n lookupReferencesNullified: number\n /** #650 Task 5 review (Important fix) — `'ref'` edges whose compare-key could NOT be resolved,\n * even from the LIVE pre-shred row (the backing row itself is unreadable) — propagation was\n * skipped for these, reported here so the skip is never silent. `backing:key:collection.field`\n * entries, one per un-propagated edge. */\n readonly lookupReferencesResidue: string[]\n /** #776/#782/#785 — `outputCollection:id` MV-output rows that survived erasure invalidation\n * (eager tombstone leg AND lazy/manual `invalidateMVAtRest`) despite belonging to the\n * forgotten subject, because the ownership stamp could not be decoded (undecodable under\n * the default DEK — e.g. elevated above tier 0 on a tiered output collection). Ownership\n * UNCONFIRMED. Never erased, but surfaced here rather than silently skipped. */\n readonly derivedResidueUndecodable: string[]\n /** #782/#785 — `outputCollection:id` MV-output rows that decoded and stamp-matched but whose\n * `_internalDelete` declined (the #718 tier-elevation gate). Ownership CONFIRMED, erasure\n * declined — a real silent survival, surfaced here rather than silently skipped. */\n readonly derivedResidueDeclined: string[]\n}\n\n/**\n * #622 — after `_writeTombstone(ref.id, actor)` erases the forgotten subject's own record, fan\n * out to its derived residue via the graph (spec §5): record-grain artifacts (MV rows,\n * array-shape derivation rows, same-id record-shape derivation copies) are ERASED through the\n * SAME `!internal` housekeeping-bypass machinery the ordinary delete path uses (no user\n * `onDelete` re-fires — the shred-is-not-a-domain-delete property `_writeTombstone` protects);\n * aggregate-grain rollups are RECOMPUTED without the forgotten contribution in open periods, or\n * skip+audit (via `putDerivedOutput`, already wired into the rollup/MV output paths) in frozen\n * ones. Mutates `stats` in place. `envelope` is `ref`'s PRE-tombstone envelope, decoded only if\n * a rollup edge is actually present — the #553 zero-cost-skip discipline: no decrypt for the\n * common case of a forgotten record with no aggregate-grain consumer, and no work at all when\n * `ref.collection` has no graph out-edges. `lookupCompareKeys` is the `'ref'` edges' compare-key\n * map, resolved from the LIVE row BEFORE any shred (`VaultLinks.checkLookupRefsRestrict`'s return\n * value — `Vault.forget()`'s pre-shred restrict check doubles as the live-resolve pass) — see\n * {@link applyLookupRefsFanout}.\n */\nexport async function forgetDerivedFanout(\n vault: VaultLike,\n ref: { readonly collection: string; readonly id: string },\n envelope: EncryptedEnvelope | null,\n stats: ForgetFanoutStats,\n lookupCompareKeys: ReadonlyMap<string, string | undefined>,\n): Promise<void> {\n const coll = vault._getCollection(ref.collection)\n\n // #761 item 4 — drive the MV arm off `dispatchMaterializedViewsOnDelete` UNCONDITIONALLY,\n // ABOVE the `edges` check below: `registry.edges()` drops the same-collection\n // partition-disjoint MV edge (registry.ts's `sources.length === 0 → continue`), so a\n // same-collection MV's source collection never appears in `vault.graph`'s derived-artifact\n // edges even though the MV IS registered — forget() would otherwise never reach it.\n // `dispatchMaterializedViewsOnDelete` self-guards O(1) via `mvsForSource` (a no-op when\n // this collection isn't an MV source), so this is safe to call unconditionally. Safe to\n // route through the eager executor's tombstone leg ONLY because that leg is now\n // stamp-scoped (#762) — before that fix this would have opened a NEW forget-time\n // data-loss path into the unscoped tombstone diff.\n if (coll) {\n const mv = await coll.dispatchMaterializedViewsOnDelete(ref.id)\n stats.recordsErased += mv.deleted\n stats.derivedResidueUndecodable.push(...mv.residueUndecodable)\n stats.derivedResidueDeclined.push(...mv.residueDeclined)\n }\n\n const edges = vault.graph.derivedArtifactsOf(ref.collection)\n if (edges.length === 0 || !coll) return\n\n // #650 Task 5 (#648) — 'ref' cascade/nullify propagate ADDITIVELY, here, AFTER the shred\n // (restrict already refused BEFORE any shred — the caller's pre-tombstone check, spec §4).\n // The I/O shell (loop shape, collection accessor) is duplicated, not imported, from\n // `VaultLinks.applyLookupRefsPropagation`/`checkLookupRefsRestrict` (with-shape/links/\n // vault-facade.ts) — the kernel spine may not statically import a with-* service\n // (port-layering, the #638 Task 5 via/dispatch.ts precedent); `vault._getCollection` is\n // cached-only while `VaultLinks`' accessor constructs. The pure match predicate itself is\n // shared through the port seam (#651 Task 3 — `matchesReferencingValue`, `port/with/\n // lookup-strategy.ts`), so only the shell, not the coercion logic, stays duplicated. A\n // referencing edge whose dimension uses a non-default `key` (matrix tier only) needs the\n // backing row's OWN value at that field, not its PUT-id — the row is ALREADY tombstoned by\n // now, so it's read from `lookupCompareKeys`, resolved by the caller from the LIVE row\n // BEFORE the shred (#650 Task 5 review, Important fix — eliminates the post-shred\n // envelope-decode dependency this used to have, which silently skipped propagation whenever\n // that decode failed).\n if (edges.some((e) => e.kind === 'ref')) {\n const { cascaded, nullified, residue } = await applyLookupRefsFanout(vault, ref.collection, ref.id, lookupCompareKeys)\n stats.lookupReferencesCascaded += cascaded\n stats.lookupReferencesNullified += nullified\n stats.lookupReferencesResidue.push(...residue)\n }\n\n if (edges.some((e) => e.kind === 'derivation')) {\n // #622 review Finding 1: count REAL erasures (dispatchArrayDerivationsOnDelete's own\n // `_internalDelete`-backed tally), not the derivation EDGE count — an edge exists whenever\n // this collection is ANY trigger (source/sources[]/triggerBy), but the same-id record-shape\n // guard only erases for `spec.source === this.name`, and `derive()` may never have produced\n // an output row (optional-skip) in the first place. Both cases must contribute 0, not +1.\n stats.recordsErased += await coll.dispatchArrayDerivationsOnDelete(ref.id, true)\n }\n\n if (envelope && edges.some((e) => e.kind === 'rollup')) {\n const priorRecord = await coll._decodeEnvelope(envelope, ref.id)\n if (priorRecord) {\n for (const r of await coll.dispatchRollupsOnDelete(ref.id, priorRecord)) {\n if (r.outcome === 'written') stats.aggregatesRecomputed += 1\n else if (r.outcome === 'skipped-frozen') stats.residueFrozen.push(`${r.into}:${r.parentId}`)\n }\n }\n }\n}\n\n/**\n * Apply `cascade`/`nullify` propagation for `backing`'s non-restrict `'ref'` edges — the\n * forget-path counterpart of `VaultLinks.applyLookupRefsPropagation` (I/O shell duplicated, not\n * imported, match predicate shared via the port — see {@link forgetDerivedFanout}'s call site\n * comment). `restrict` edges are skipped here: the\n * forget loop's `checkLookupRefsRestrict`-equivalent call already refused (or the reference no\n * longer existed) BEFORE `_writeTombstone` ran, so by the time this runs only cascade/nullify\n * remain to propagate. `compareKeys` is the non-`'id'`-`keyField` compare-value map, resolved by\n * the caller from the LIVE row BEFORE the shred (#650 Task 5 review, Important fix) — the live row\n * is already shredded by the time THIS function runs, so it can no longer resolve one itself. A\n * `keyField` absent from (or `undefined` in) the map means that live resolve failed too — the edge\n * is reported as residue instead of silently skipped (never a bare `continue` with no trace).\n */\nasync function applyLookupRefsFanout(\n vault: VaultLike,\n backing: string,\n key: string,\n compareKeys: ReadonlyMap<string, string | undefined>,\n): Promise<{ cascaded: number; nullified: number; residue: string[] }> {\n let cascaded = 0\n let nullified = 0\n const residue: string[] = []\n for (const { referencing, onDelete, keyField } of vault.graph.referencingEdgesOf(backing)) {\n if (onDelete === 'restrict') continue\n const compareKey = keyField === 'id' ? key : compareKeys.get(keyField)\n if (compareKey === undefined) {\n residue.push(`${backing}:${key}:${referencing.collection}.${referencing.field}`)\n continue\n }\n const coll = vault._getCollection(referencing.collection)\n if (!coll) continue\n const matches = (await coll.list()).filter((rec) => matchesReferencingValue(rec, referencing.field, compareKey))\n for (const rec of matches) {\n const id = rec['id'] as string | undefined\n if (id === undefined) continue\n if (onDelete === 'cascade') {\n await coll.delete(id)\n cascaded++\n } else if (onDelete === 'nullify') {\n await coll.put(id, { ...rec, [referencing.field]: null })\n nullified++\n }\n }\n }\n return { cascaded, nullified, residue }\n}\n\n/**\n * Value-equality for a single self-write reverse-denorm field. Scalars\n * compare by identity; objects by canonical JSON (denorm values should be\n * deterministically shaped). Used as the cycle guard — when every denorm\n * field already matches, no write is issued and the self-write recursion ends.\n */\nexport function selfWriteFieldEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true\n if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false\n try {\n return JSON.stringify(a) === JSON.stringify(b)\n } catch {\n return false\n }\n}\n"],"mappings":";;;;;;;;AA6CO,SAAS,SAAS,OAAmB,YAAgC;AAC1E,MAAI,IAAI,MAAM,IAAI,UAAU;AAC5B,MAAI,CAAC,GAAG;AACN,QAAI,EAAE,MAAM,oBAAI,IAAI,GAAG,SAAS,oBAAI,IAAI,EAAE;AAC1C,UAAM,IAAI,YAAY,CAAC;AAAA,EACzB;AACA,SAAO;AACT;AAQO,SAAS,2BACd,UACA,gBACA,SACsB;AACtB,MAAI,CAAC,SAAU,QAAO,CAAC;AACvB,QAAM,UAAgC,CAAC;AACvC,aAAW,EAAE,KAAK,KAAK,SAAS,oBAAoB,cAAc,GAAG;AACnE,QAAI,CAAC,KAAK,UAAU,KAAK,OAAO,SAAS,eAAgB;AACzD,UAAM,KAAK,QAAQ,KAAK,OAAO,GAAG;AAClC,QAAI,OAAO,OAAO,YAAY,OAAO,OAAO,SAAU,SAAQ,KAAK,EAAE,MAAM,KAAK,QAAQ,UAAU,OAAO,EAAE,GAAG,OAAO,KAAK,OAAO,MAAM,CAAC;AAAA,EAC1I;AACA,SAAO;AACT;AAOO,SAAS,wBACd,UACA,gBACA,QACe;AACf,SAAO,UAAU,oBAAoB,cAAc,EAAE,KAAK,CAAC,MAAM,EAAE,KAAK,WAAW,OAAO,QAAQ,EAAE,KAAK,QAAQ,UAAU,OAAO,SAAS,EAAE,KAAK,QAAQ,SAAS,cAAc,GAAG;AACtL;AAGO,IAAM,cAAN,MAAkB;AAAA,EACN,QAAQ,oBAAI,IAAY;AAAA,EACzC,KAAK,WAA4B;AAC/B,QAAI,KAAK,MAAM,IAAI,SAAS,EAAG,QAAO;AACtC,SAAK,MAAM,IAAI,SAAS;AACxB,WAAO;AAAA,EACT;AACF;AAmBA,eAAsB,qBAAq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AG,KAAK,CAAC,YAAY,KAAK,GAAG,KAAK,CAAC;AACxD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,SAAO,EAAE,UAAU,WAAW,QAAQ;AACxC;AAQO,SAAS,oBAAoB,GAAY,GAAqB;AACnE,MAAI,MAAM,EAAG,QAAO;AACpB,MAAI,MAAM,QAAQ,MAAM,QAAQ,OAAO,MAAM,YAAY,OAAO,MAAM,SAAU,QAAO;AACvF,MAAI;AACF,WAAO,KAAK,UAAU,CAAC,MAAM,KAAK,UAAU,CAAC;AAAA,EAC/C,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
@@ -1,24 +1,25 @@
|
|
|
1
1
|
import {
|
|
2
2
|
freezeSnapshotOnly
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-BSFNRLK2.js";
|
|
4
4
|
import {
|
|
5
5
|
resolveManagedSecret
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-4GVM6QZA.js";
|
|
7
7
|
import {
|
|
8
8
|
assertRosterTagValid,
|
|
9
9
|
createOwnerKeyring,
|
|
10
10
|
mintRosterTag,
|
|
11
|
+
nextRosterEpoch,
|
|
11
12
|
requireRosterKey
|
|
12
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-G56KBWFY.js";
|
|
13
14
|
import {
|
|
14
15
|
buildRecordEnvelope
|
|
15
|
-
} from "./chunk-
|
|
16
|
+
} from "./chunk-SZJ3DLZA.js";
|
|
16
17
|
import {
|
|
17
18
|
wrapKey
|
|
18
|
-
} from "./chunk-
|
|
19
|
+
} from "./chunk-SL3JAAKN.js";
|
|
19
20
|
import {
|
|
20
21
|
PermissionDeniedError
|
|
21
|
-
} from "./chunk-
|
|
22
|
+
} from "./chunk-7O3Y4PPD.js";
|
|
22
23
|
|
|
23
24
|
// src/with-party/team/deed.ts
|
|
24
25
|
var DEED_RECORD_ID = "deed";
|
|
@@ -107,7 +108,8 @@ async function liberateVault(vault, opts) {
|
|
|
107
108
|
}
|
|
108
109
|
const rosterKey = requireRosterKey(keyring, "liberateVault");
|
|
109
110
|
const merged = { ...keyringFile, deks: mergedDeks };
|
|
110
|
-
const
|
|
111
|
+
const withEpoch = { ...merged, roster_epoch: nextRosterEpoch(keyringFile.roster_epoch) };
|
|
112
|
+
const mergedFile = { ...withEpoch, roster_tag: await mintRosterTag(withEpoch, rosterKey) };
|
|
111
113
|
await adapter.put(vaultName, "_keyring", opts.newOwnerId, { ...env, _data: JSON.stringify(mergedFile) });
|
|
112
114
|
await vault._getLedgerOrNull()?.append({
|
|
113
115
|
op: "lifecycle",
|
|
@@ -135,4 +137,4 @@ export {
|
|
|
135
137
|
isDeedVault,
|
|
136
138
|
liberateVault
|
|
137
139
|
};
|
|
138
|
-
//# sourceMappingURL=chunk-
|
|
140
|
+
//# sourceMappingURL=chunk-CHJBLCOG.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/with-party/team/deed.ts","../src/with-party/custody/liberate.ts"],"sourcesContent":["/**\n * FR-6 — Deed: sealed / hidden-owner provisioning.\n *\n * A **Deed** is a vault owned by a *latent* principal who never\n * authenticates. The owner credential (the random secret that\n * derives `KEK_owner`) is minted machine-side and sealed under a\n * **non-firm** {@link NoydbSealer} — that sealing boundary is\n * the cryptographic *inalienability anchor*: whoever holds the\n * provider (the client / their KMS) is the only party that can ever\n * re-derive `KEK_owner`. A firm-side custodian operates the vault\n * fully but can never reach the owner key — there is deliberately NO\n * firm-controlled fallback.\n *\n * Provisioning reuses the managed-mode seam:\n * - {@link resolveManagedSecret} mints + seals + persists the random\n * secret at `_meta/sealed-secret` (and unseals it on every\n * subsequent open through the same provider).\n * - {@link createOwnerKeyring} derives `KEK_owner` from that\n * secret and writes the `_keyring/<ownerUserId>` file.\n *\n * On top of that, a Deed writes a `_meta/deed` **marker**. The marker\n * is PLAINTEXT metadata — it records WHO the latent owner is and WHICH\n * sealing boundary protects them, so it must be readable without\n * unlocking the vault (a custodian or auditor inspecting the vault must\n * be able to see \"this is a Deed vault, owner = X, sealed under Y\"\n * without any key). The marker itself is therefore never sealed; only\n * the owner *credential* is.\n *\n * @module\n */\n\nimport { buildRecordEnvelope } from '../../kernel/enclave/index.js'\nimport type { NoydbStore } from '../../kernel/types.js'\nimport type { UnlockedKeyring } from './keyring.js'\nimport { createOwnerKeyring } from './keyring.js'\nimport type { NoydbSealer } from './managed-secret.js'\nimport { resolveManagedSecret } from './managed-secret.js'\n\n/** Reserved id for the Deed marker under `_meta`. */\nexport const DEED_RECORD_ID = 'deed' as const\n\n/**\n * Plaintext metadata recording a vault's latent-owner Deed. Persisted\n * at `_meta/deed`. Readable without unlocking the vault by design — it\n * carries no secret material, only the identity of the latent owner\n * and the sealing boundary that anchors inalienability.\n */\nexport interface DeedMarker {\n /** The latent owner principal — the user id of the `_keyring/<id>` owner file. */\n readonly ownerUserId: string\n /**\n * The `NoydbSealer.id` the owner credential is sealed under.\n * The inalienability anchor: only the holder of this (non-firm)\n * provider can re-derive `KEK_owner`. Audit metadata — never secret.\n */\n readonly sealedUnder: string\n /** Always `true` for a Deed — the owner never authenticates interactively. */\n readonly latent: true\n /** ISO-8601 timestamp the Deed was issued. */\n readonly issuedAt: string\n /**\n * ISO-8601 timestamp the vault was liberated (a new owner claimed it\n * via the audited Liberate ceremony), if any. Absent until liberation.\n */\n readonly liberatedAt?: string\n}\n\n/**\n * Wire-format payload stored inside the `_meta/deed` envelope. Carries\n * a magic marker for forensics + the {@link DeedMarker} fields. JSON,\n * AES-GCM bypassed (the marker is plaintext metadata by design).\n */\ninterface DeedEnvelopePayload extends DeedMarker {\n readonly _noydb_deed: 1\n}\n\n/**\n * Provision a Deed: a latent owner whose credential is sealed under\n * `sealing` (a NON-firm provider). Mints + seals the owner secret\n * via {@link resolveManagedSecret}, derives the owner keyring via\n * {@link createOwnerKeyring}, then writes the plaintext `_meta/deed`\n * marker. Returns the unlocked owner keyring.\n *\n * The returned keyring is the only in-memory window onto `KEK_owner`\n * for this call; the persistent re-entry point is the sealing provider\n * (re-run {@link resolveManagedSecret} with the same provider to\n * re-resolve the secret, then {@link createOwnerKeyring}/load to\n * unlock — no interactive secret is ever required).\n *\n * There is deliberately no firm-controlled fallback: the marker's\n * `sealedUnder` is the single cryptographic anchor of ownership.\n */\nexport async function createDeedOwner(\n store: NoydbStore,\n vault: string,\n ownerUserId: string,\n sealing: NoydbSealer,\n): Promise<UnlockedKeyring> {\n // 1. Mint + seal + persist the random owner secret under the\n // non-firm provider (writes _meta/sealed-secret).\n const secret = await resolveManagedSecret(store, vault, sealing)\n\n // 2. Derive KEK_owner from the (never-human-seen) secret and\n // write the owner keyring file.\n const keyring = await createOwnerKeyring(store, vault, { userId: ownerUserId, secret: secret })\n\n // 3. Write the plaintext Deed marker. NOT sealed — it is audit\n // metadata that must be readable without unlocking.\n await saveDeedMarker(store, vault, {\n ownerUserId,\n sealedUnder: sealing.id,\n latent: true,\n issuedAt: new Date().toISOString(),\n })\n\n return keyring\n}\n\n/**\n * Read the {@link DeedMarker} from `_meta/deed`, or `null` if the vault\n * has no Deed marker (i.e. it is not a Deed vault). Plaintext read — no\n * unlocking required.\n */\nexport async function loadDeedMarker(\n store: NoydbStore,\n vault: string,\n): Promise<DeedMarker | null> {\n const envelope = await store.get(vault, '_meta', DEED_RECORD_ID)\n if (!envelope) return null\n let payload: unknown\n try {\n payload = JSON.parse(envelope._data)\n } catch {\n return null\n }\n if (typeof payload !== 'object' || payload === null) return null\n const r = payload as Record<string, unknown>\n if (r._noydb_deed !== 1) return null\n if (\n typeof r.ownerUserId !== 'string'\n || typeof r.sealedUnder !== 'string'\n || r.latent !== true\n || typeof r.issuedAt !== 'string'\n ) {\n return null\n }\n const marker: DeedMarker = {\n ownerUserId: r.ownerUserId,\n sealedUnder: r.sealedUnder,\n latent: true,\n issuedAt: r.issuedAt,\n ...(typeof r.liberatedAt === 'string' ? { liberatedAt: r.liberatedAt } : {}),\n }\n return marker\n}\n\n/** Whether `vault` carries a Deed marker (a sealed/latent owner). */\nexport async function isDeedVault(\n store: NoydbStore,\n vault: string,\n): Promise<boolean> {\n return (await loadDeedMarker(store, vault)) !== null\n}\n\n/**\n * Persist a {@link DeedMarker} at `_meta/deed`. Mirrors\n * `saveSealedSecret`'s envelope shape: a standard\n * {@link EncryptedEnvelope} with AES-GCM bypassed (`_iv: ''`), the\n * payload stored as plaintext JSON in `_data`. The marker is metadata,\n * not a secret — sealing it would defeat its purpose (auditors /\n * custodians must read it without a key).\n *\n * @internal — used by `createDeedOwner` and (later) the Liberate\n * ceremony to stamp `liberatedAt`.\n */\nexport async function saveDeedMarker(\n store: NoydbStore,\n vault: string,\n marker: DeedMarker,\n): Promise<void> {\n const persisted: DeedEnvelopePayload = { _noydb_deed: 1, ...marker }\n const prior = await store.get(vault, '_meta', DEED_RECORD_ID)\n const env = buildRecordEnvelope(\n { collection: '_meta', id: DEED_RECORD_ID, version: (prior?._v ?? 0) + 1 },\n // AES-GCM bypassed — the marker is plaintext audit metadata.\n { iv: '', data: JSON.stringify(persisted) },\n )\n await store.put(vault, '_meta', DEED_RECORD_ID, env)\n}\n","/**\n * `liberateVault` — the audited claim of ownership over a\n * sealed-owner (Deed) vault. The inverse of withdrawal.\n *\n * A **Deed** vault's owner credential is sealed under a non-firm provider, so\n * the firm-side **custodian** (which holds every collection DEK and operates\n * the vault fully) can never reach `KEK_owner`. Liberation is the ONLY route\n * by which a custodian assumes ownership, and it is deliberately a manual,\n * audited ceremony:\n *\n * 1. gate `'liberate-vault'` (fail-closed)\n * 2. caller MUST be the `custodian` (the de-facto authority holding the DEKs)\n * 3. freeze a PRE-liberation EVIDENCE snapshot (hash-pinned in the ledger) —\n * but PRESERVE the live data for the new owner (see the freeze decision\n * below)\n * 4. mint a NEW owner keyring re-wrapping the incumbent DEKs under the new\n * owner's KEK\n * 5. lifecycle ledger `liberation-claimed:<newOwnerId>:<legalBasis>`\n * 6. stamp the `_meta/deed` marker with `liberatedAt`\n *\n * ## Security: the inalienability floor\n *\n * Liberation **mints a new owner from the custodian's DEKs** — it does NOT\n * unseal the original sealed owner. The old sealed-owner credential is left\n * untouched and ORPHANED (its `_keyring/<id>` file remains, its KEK is still\n * sealed under the non-firm provider), never impersonated. The new owner is a\n * DISTINCT principal under a fresh KEK derived from `newOwnerSecret`. This\n * preserves the inalienability floor: the act of claiming ownership is itself\n * auditable and produces a different principal, rather than silently assuming\n * the latent owner's identity.\n *\n * ## Freeze decision: snapshot-only, not freeze-and-delete\n *\n * `freezeAndDeleteClosure` (withdraw-accessible.ts) writes a hash-pinned\n * snapshot and THEN delete-closures the live records — correct for a\n * destructive withdrawal, WRONG for liberation. Liberation transfers\n * operational continuity; it must leave the live data intact for the new\n * owner. We therefore call the snapshot-only core `freezeSnapshotOnly`\n * (factored out of that module; the freeze-AND-delete withdrawal path is\n * unchanged) to pin the evidence snapshot while preserving the records.\n *\n * @module\n */\n\nimport type { Vault } from '../../kernel/vault.js'\nimport type { FactorProofBundle, KeyringFile } from '../../kernel/types.js'\nimport { PermissionDeniedError } from '../../kernel/errors.js'\nimport { wrapKey } from '../../kernel/enclave/index.js'\nimport { createOwnerKeyring, requireRosterKey } from '../team/keyring.js'\nimport { mintRosterTag, assertRosterTagValid } from '../team/roster-tag.js'\nimport type { FrozenSnapshotRef } from '../../with-audit/portability/withdraw-accessible.js'\nimport { freezeSnapshotOnly } from '../../with-audit/portability/withdraw-accessible.js'\nimport { loadDeedMarker, saveDeedMarker } from '../team/deed.js'\n\nexport interface LiberateOptions {\n /** The id of the new owner principal the custodian mints by claiming ownership. */\n readonly newOwnerId: string\n /** The secret that derives the new owner's KEK (the DEKs are re-wrapped under it). */\n readonly newOwnerSecret: string\n /** Legal/contractual basis recorded in the audit (e.g. 'contractual-handover'). */\n readonly legalBasis: string\n readonly factors?: FactorProofBundle\n}\n\nexport interface LiberateResult {\n /** The hash-pinned pre-liberation evidence snapshot. */\n readonly snapshot: FrozenSnapshotRef\n}\n\n/**\n * Audited claim of ownership over a sealed-owner vault by its custodian. See\n * the module doc for the full ceremony + security rationale.\n */\nexport async function liberateVault(\n vault: Vault,\n opts: LiberateOptions,\n): Promise<LiberateResult> {\n // 1. gate — fail-closed `liberate-vault`.\n await vault.noydb.checkGate(vault.name, 'liberate-vault', opts.factors)\n\n // 2. caller must be the custodian (the de-facto authority holding the DEKs).\n const { name: vaultName, adapter, keyring } = vault._introspectState()\n if (keyring.role !== 'custodian') {\n throw new PermissionDeniedError(\n 'liberation is claimed only by the custodian (the de-facto authority holding the DEKs)',\n )\n }\n\n // Refuse to clobber an existing principal: the new owner must be a FRESH id.\n // (Checked before any side effect so a colliding id never leaves a half-run\n // ceremony — no orphan snapshot, no partial keyring overwrite.)\n const existing = await adapter.get(vaultName, '_keyring', opts.newOwnerId)\n if (existing) {\n throw new PermissionDeniedError(\n `liberateVault: newOwnerId \"${opts.newOwnerId}\" already exists as a principal; choose a fresh id (liberation mints a distinct owner, it never overwrites an existing keyring)`,\n )\n }\n\n // 3. Pre-liberation EVIDENCE snapshot of every operational collection —\n // snapshot-only (live data preserved for the new owner; liberation\n // transfers operational continuity, it does not erase).\n const collections = await listOperationalCollections(vault)\n const snapshot = await freezeSnapshotOnly(vault, collections, { actorUserId: keyring.userId })\n\n // 4. Mint a NEW owner keyring, re-wrapping the incumbent DEKs under the new\n // owner's fresh KEK. The old sealed owner is NOT unsealed — a DISTINCT\n // principal is minted and the original owner credential is left orphaned\n // (inalienability floor). Mirrors adopt-partition.ts's DEK re-wrap.\n const newOwner = await createOwnerKeyring(adapter, vaultName, { userId: opts.newOwnerId, secret: opts.newOwnerSecret })\n if (!newOwner.kek) {\n throw new PermissionDeniedError(\n `new owner keyring for \"${opts.newOwnerId}\" has no KEK to re-wrap the incumbent DEKs under`,\n )\n }\n const env = await adapter.get(vaultName, '_keyring', opts.newOwnerId)\n if (!env) {\n throw new PermissionDeniedError(`new owner keyring for \"${opts.newOwnerId}\" did not persist`)\n }\n const keyringFile = JSON.parse(env._data) as KeyringFile\n // #1096 — this is a read-BACK of the file `createOwnerKeyring` just wrote, and\n // it is about to be edited and restamped, so the store gets a window to alter\n // it in between. Verified against the NEW owner's own roster key, not the\n // incumbent's: at this instant the file is still stamped under the fresh key\n // minted above (the swap to the incumbent key happens below).\n const mintedRosterKey = requireRosterKey(newOwner, 'liberateVault')\n await assertRosterTagValid(keyringFile, mintedRosterKey, opts.newOwnerId)\n const mergedDeks: Record<string, string> = { ...keyringFile.deks }\n for (const [collection, dek] of keyring.deks) {\n mergedDeks[collection] = await wrapKey(dek, newOwner.kek)\n }\n // #1096 — liberation joins a new owner to an EXISTING vault, so the vault's\n // roster key must stay the incumbent one. `createOwnerKeyring` above minted a\n // fresh roster key (correct for a new vault, wrong here), and the merge loop\n // has just overwritten `_roster` with the incumbent's — so the tag it stamped\n // no longer matches the key in the file. Restamp under the key that actually\n // ends up persisted, or the new owner cannot open the vault they just claimed.\n //\n // Keeping the incumbent key is the substantive half: a fresh one would leave\n // the new owner unable to verify any co-member's roster, and every co-member\n // unable to verify theirs.\n const rosterKey = requireRosterKey(keyring, 'liberateVault')\n const merged: KeyringFile = { ...keyringFile, deks: mergedDeks }\n const mergedFile: KeyringFile = { ...merged, roster_tag: await mintRosterTag(merged, rosterKey) }\n await adapter.put(vaultName, '_keyring', opts.newOwnerId, { ...env, _data: JSON.stringify(mergedFile) })\n\n // 5. Lifecycle ledger audit (no-op if the history strategy is absent).\n await vault._getLedgerOrNull()?.append({\n op: 'lifecycle', collection: '', id: '', version: 0, actor: opts.newOwnerId, payloadHash: '',\n reason: `liberation-claimed:${opts.newOwnerId}:${opts.legalBasis}`,\n })\n\n // 6. Stamp the Deed marker with `liberatedAt` (if a marker exists).\n const marker = await loadDeedMarker(adapter, vaultName)\n if (marker) {\n await saveDeedMarker(adapter, vaultName, { ...marker, liberatedAt: new Date().toISOString() })\n }\n\n return { snapshot }\n}\n\n/**\n * Enumerate the vault's operational (user-facing) collections — those carried\n * by the caller's keyring DEK map, minus the reserved internal collections\n * (`_*`). These are the collections frozen into the evidence snapshot.\n */\nasync function listOperationalCollections(vault: Vault): Promise<readonly string[]> {\n const { keyring } = vault._introspectState()\n return [...keyring.deks.keys()].filter((c) => !c.startsWith('_'))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuCO,IAAM,iBAAiB;AAqD9B,eAAsB,gBACpB,OACA,OACA,aACA,SAC0B;AAG1B,QAAM,SAAS,MAAM,qBAAqB,OAAO,OAAO,OAAO;AAI/D,QAAM,UAAU,MAAM,mBAAmB,OAAO,OAAO,EAAE,QAAQ,aAAa,OAAe,CAAC;AAI9F,QAAM,eAAe,OAAO,OAAO;AAAA,IACjC;AAAA,IACA,aAAa,QAAQ;AAAA,IACrB,QAAQ;AAAA,IACR,WAAU,oBAAI,KAAK,GAAE,YAAY;AAAA,EACnC,CAAC;AAED,SAAO;AACT;AAOA,eAAsB,eACpB,OACA,OAC4B;AAC5B,QAAM,WAAW,MAAM,MAAM,IAAI,OAAO,SAAS,cAAc;AAC/D,MAAI,CAAC,SAAU,QAAO;AACtB,MAAI;AACJ,MAAI;AACF,cAAU,KAAK,MAAM,SAAS,KAAK;AAAA,EACrC,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,OAAO,YAAY,YAAY,YAAY,KAAM,QAAO;AAC5D,QAAM,IAAI;AACV,MAAI,EAAE,gBAAgB,EAAG,QAAO;AAChC,MACE,OAAO,EAAE,gBAAgB,YACtB,OAAO,EAAE,gBAAgB,YACzB,EAAE,WAAW,QACb,OAAO,EAAE,aAAa,UACzB;AACA,WAAO;AAAA,EACT;AACA,QAAM,SAAqB;AAAA,IACzB,aAAa,EAAE;AAAA,IACf,aAAa,EAAE;AAAA,IACf,QAAQ;AAAA,IACR,UAAU,EAAE;AAAA,IACZ,GAAI,OAAO,EAAE,gBAAgB,WAAW,EAAE,aAAa,EAAE,YAAY,IAAI,CAAC;AAAA,EAC5E;AACA,SAAO;AACT;AAGA,eAAsB,YACpB,OACA,OACkB;AAClB,SAAQ,MAAM,eAAe,OAA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/team/deed.ts","../src/with-party/custody/liberate.ts"],"sourcesContent":["/**\n * FR-6 — Deed: sealed / hidden-owner provisioning.\n *\n * A **Deed** is a vault owned by a *latent* principal who never\n * authenticates. The owner credential (the random secret that\n * derives `KEK_owner`) is minted machine-side and sealed under a\n * **non-firm** {@link NoydbSealer} — that sealing boundary is\n * the cryptographic *inalienability anchor*: whoever holds the\n * provider (the client / their KMS) is the only party that can ever\n * re-derive `KEK_owner`. A firm-side custodian operates the vault\n * fully but can never reach the owner key — there is deliberately NO\n * firm-controlled fallback.\n *\n * Provisioning reuses the managed-mode seam:\n * - {@link resolveManagedSecret} mints + seals + persists the random\n * secret at `_meta/sealed-secret` (and unseals it on every\n * subsequent open through the same provider).\n * - {@link createOwnerKeyring} derives `KEK_owner` from that\n * secret and writes the `_keyring/<ownerUserId>` file.\n *\n * On top of that, a Deed writes a `_meta/deed` **marker**. The marker\n * is PLAINTEXT metadata — it records WHO the latent owner is and WHICH\n * sealing boundary protects them, so it must be readable without\n * unlocking the vault (a custodian or auditor inspecting the vault must\n * be able to see \"this is a Deed vault, owner = X, sealed under Y\"\n * without any key). The marker itself is therefore never sealed; only\n * the owner *credential* is.\n *\n * @module\n */\n\nimport { buildRecordEnvelope } from '../../kernel/enclave/index.js'\nimport type { NoydbStore } from '../../kernel/types.js'\nimport type { UnlockedKeyring } from './keyring.js'\nimport { createOwnerKeyring } from './keyring.js'\nimport type { NoydbSealer } from './managed-secret.js'\nimport { resolveManagedSecret } from './managed-secret.js'\n\n/** Reserved id for the Deed marker under `_meta`. */\nexport const DEED_RECORD_ID = 'deed' as const\n\n/**\n * Plaintext metadata recording a vault's latent-owner Deed. Persisted\n * at `_meta/deed`. Readable without unlocking the vault by design — it\n * carries no secret material, only the identity of the latent owner\n * and the sealing boundary that anchors inalienability.\n */\nexport interface DeedMarker {\n /** The latent owner principal — the user id of the `_keyring/<id>` owner file. */\n readonly ownerUserId: string\n /**\n * The `NoydbSealer.id` the owner credential is sealed under.\n * The inalienability anchor: only the holder of this (non-firm)\n * provider can re-derive `KEK_owner`. Audit metadata — never secret.\n */\n readonly sealedUnder: string\n /** Always `true` for a Deed — the owner never authenticates interactively. */\n readonly latent: true\n /** ISO-8601 timestamp the Deed was issued. */\n readonly issuedAt: string\n /**\n * ISO-8601 timestamp the vault was liberated (a new owner claimed it\n * via the audited Liberate ceremony), if any. Absent until liberation.\n */\n readonly liberatedAt?: string\n}\n\n/**\n * Wire-format payload stored inside the `_meta/deed` envelope. Carries\n * a magic marker for forensics + the {@link DeedMarker} fields. JSON,\n * AES-GCM bypassed (the marker is plaintext metadata by design).\n */\ninterface DeedEnvelopePayload extends DeedMarker {\n readonly _noydb_deed: 1\n}\n\n/**\n * Provision a Deed: a latent owner whose credential is sealed under\n * `sealing` (a NON-firm provider). Mints + seals the owner secret\n * via {@link resolveManagedSecret}, derives the owner keyring via\n * {@link createOwnerKeyring}, then writes the plaintext `_meta/deed`\n * marker. Returns the unlocked owner keyring.\n *\n * The returned keyring is the only in-memory window onto `KEK_owner`\n * for this call; the persistent re-entry point is the sealing provider\n * (re-run {@link resolveManagedSecret} with the same provider to\n * re-resolve the secret, then {@link createOwnerKeyring}/load to\n * unlock — no interactive secret is ever required).\n *\n * There is deliberately no firm-controlled fallback: the marker's\n * `sealedUnder` is the single cryptographic anchor of ownership.\n */\nexport async function createDeedOwner(\n store: NoydbStore,\n vault: string,\n ownerUserId: string,\n sealing: NoydbSealer,\n): Promise<UnlockedKeyring> {\n // 1. Mint + seal + persist the random owner secret under the\n // non-firm provider (writes _meta/sealed-secret).\n const secret = await resolveManagedSecret(store, vault, sealing)\n\n // 2. Derive KEK_owner from the (never-human-seen) secret and\n // write the owner keyring file.\n const keyring = await createOwnerKeyring(store, vault, { userId: ownerUserId, secret: secret })\n\n // 3. Write the plaintext Deed marker. NOT sealed — it is audit\n // metadata that must be readable without unlocking.\n await saveDeedMarker(store, vault, {\n ownerUserId,\n sealedUnder: sealing.id,\n latent: true,\n issuedAt: new Date().toISOString(),\n })\n\n return keyring\n}\n\n/**\n * Read the {@link DeedMarker} from `_meta/deed`, or `null` if the vault\n * has no Deed marker (i.e. it is not a Deed vault). Plaintext read — no\n * unlocking required.\n */\nexport async function loadDeedMarker(\n store: NoydbStore,\n vault: string,\n): Promise<DeedMarker | null> {\n const envelope = await store.get(vault, '_meta', DEED_RECORD_ID)\n if (!envelope) return null\n let payload: unknown\n try {\n payload = JSON.parse(envelope._data)\n } catch {\n return null\n }\n if (typeof payload !== 'object' || payload === null) return null\n const r = payload as Record<string, unknown>\n if (r._noydb_deed !== 1) return null\n if (\n typeof r.ownerUserId !== 'string'\n || typeof r.sealedUnder !== 'string'\n || r.latent !== true\n || typeof r.issuedAt !== 'string'\n ) {\n return null\n }\n const marker: DeedMarker = {\n ownerUserId: r.ownerUserId,\n sealedUnder: r.sealedUnder,\n latent: true,\n issuedAt: r.issuedAt,\n ...(typeof r.liberatedAt === 'string' ? { liberatedAt: r.liberatedAt } : {}),\n }\n return marker\n}\n\n/** Whether `vault` carries a Deed marker (a sealed/latent owner). */\nexport async function isDeedVault(\n store: NoydbStore,\n vault: string,\n): Promise<boolean> {\n return (await loadDeedMarker(store, vault)) !== null\n}\n\n/**\n * Persist a {@link DeedMarker} at `_meta/deed`. Mirrors\n * `saveSealedSecret`'s envelope shape: a standard\n * {@link EncryptedEnvelope} with AES-GCM bypassed (`_iv: ''`), the\n * payload stored as plaintext JSON in `_data`. The marker is metadata,\n * not a secret — sealing it would defeat its purpose (auditors /\n * custodians must read it without a key).\n *\n * @internal — used by `createDeedOwner` and (later) the Liberate\n * ceremony to stamp `liberatedAt`.\n */\nexport async function saveDeedMarker(\n store: NoydbStore,\n vault: string,\n marker: DeedMarker,\n): Promise<void> {\n const persisted: DeedEnvelopePayload = { _noydb_deed: 1, ...marker }\n const prior = await store.get(vault, '_meta', DEED_RECORD_ID)\n const env = buildRecordEnvelope(\n { collection: '_meta', id: DEED_RECORD_ID, version: (prior?._v ?? 0) + 1 },\n // AES-GCM bypassed — the marker is plaintext audit metadata.\n { iv: '', data: JSON.stringify(persisted) },\n )\n await store.put(vault, '_meta', DEED_RECORD_ID, env)\n}\n","/**\n * `liberateVault` — the audited claim of ownership over a\n * sealed-owner (Deed) vault. The inverse of withdrawal.\n *\n * A **Deed** vault's owner credential is sealed under a non-firm provider, so\n * the firm-side **custodian** (which holds every collection DEK and operates\n * the vault fully) can never reach `KEK_owner`. Liberation is the ONLY route\n * by which a custodian assumes ownership, and it is deliberately a manual,\n * audited ceremony:\n *\n * 1. gate `'liberate-vault'` (fail-closed)\n * 2. caller MUST be the `custodian` (the de-facto authority holding the DEKs)\n * 3. freeze a PRE-liberation EVIDENCE snapshot (hash-pinned in the ledger) —\n * but PRESERVE the live data for the new owner (see the freeze decision\n * below)\n * 4. mint a NEW owner keyring re-wrapping the incumbent DEKs under the new\n * owner's KEK\n * 5. lifecycle ledger `liberation-claimed:<newOwnerId>:<legalBasis>`\n * 6. stamp the `_meta/deed` marker with `liberatedAt`\n *\n * ## Security: the inalienability floor\n *\n * Liberation **mints a new owner from the custodian's DEKs** — it does NOT\n * unseal the original sealed owner. The old sealed-owner credential is left\n * untouched and ORPHANED (its `_keyring/<id>` file remains, its KEK is still\n * sealed under the non-firm provider), never impersonated. The new owner is a\n * DISTINCT principal under a fresh KEK derived from `newOwnerSecret`. This\n * preserves the inalienability floor: the act of claiming ownership is itself\n * auditable and produces a different principal, rather than silently assuming\n * the latent owner's identity.\n *\n * ## Freeze decision: snapshot-only, not freeze-and-delete\n *\n * `freezeAndDeleteClosure` (withdraw-accessible.ts) writes a hash-pinned\n * snapshot and THEN delete-closures the live records — correct for a\n * destructive withdrawal, WRONG for liberation. Liberation transfers\n * operational continuity; it must leave the live data intact for the new\n * owner. We therefore call the snapshot-only core `freezeSnapshotOnly`\n * (factored out of that module; the freeze-AND-delete withdrawal path is\n * unchanged) to pin the evidence snapshot while preserving the records.\n *\n * @module\n */\n\nimport type { Vault } from '../../kernel/vault.js'\nimport type { FactorProofBundle, KeyringFile } from '../../kernel/types.js'\nimport { PermissionDeniedError } from '../../kernel/errors.js'\nimport { wrapKey } from '../../kernel/enclave/index.js'\nimport { createOwnerKeyring, requireRosterKey } from '../team/keyring.js'\nimport { mintRosterTag, assertRosterTagValid } from '../team/roster-tag.js'\nimport { nextRosterEpoch } from '../team/roster-epoch.js'\nimport type { FrozenSnapshotRef } from '../../with-audit/portability/withdraw-accessible.js'\nimport { freezeSnapshotOnly } from '../../with-audit/portability/withdraw-accessible.js'\nimport { loadDeedMarker, saveDeedMarker } from '../team/deed.js'\n\nexport interface LiberateOptions {\n /** The id of the new owner principal the custodian mints by claiming ownership. */\n readonly newOwnerId: string\n /** The secret that derives the new owner's KEK (the DEKs are re-wrapped under it). */\n readonly newOwnerSecret: string\n /** Legal/contractual basis recorded in the audit (e.g. 'contractual-handover'). */\n readonly legalBasis: string\n readonly factors?: FactorProofBundle\n}\n\nexport interface LiberateResult {\n /** The hash-pinned pre-liberation evidence snapshot. */\n readonly snapshot: FrozenSnapshotRef\n}\n\n/**\n * Audited claim of ownership over a sealed-owner vault by its custodian. See\n * the module doc for the full ceremony + security rationale.\n */\nexport async function liberateVault(\n vault: Vault,\n opts: LiberateOptions,\n): Promise<LiberateResult> {\n // 1. gate — fail-closed `liberate-vault`.\n await vault.noydb.checkGate(vault.name, 'liberate-vault', opts.factors)\n\n // 2. caller must be the custodian (the de-facto authority holding the DEKs).\n const { name: vaultName, adapter, keyring } = vault._introspectState()\n if (keyring.role !== 'custodian') {\n throw new PermissionDeniedError(\n 'liberation is claimed only by the custodian (the de-facto authority holding the DEKs)',\n )\n }\n\n // Refuse to clobber an existing principal: the new owner must be a FRESH id.\n // (Checked before any side effect so a colliding id never leaves a half-run\n // ceremony — no orphan snapshot, no partial keyring overwrite.)\n const existing = await adapter.get(vaultName, '_keyring', opts.newOwnerId)\n if (existing) {\n throw new PermissionDeniedError(\n `liberateVault: newOwnerId \"${opts.newOwnerId}\" already exists as a principal; choose a fresh id (liberation mints a distinct owner, it never overwrites an existing keyring)`,\n )\n }\n\n // 3. Pre-liberation EVIDENCE snapshot of every operational collection —\n // snapshot-only (live data preserved for the new owner; liberation\n // transfers operational continuity, it does not erase).\n const collections = await listOperationalCollections(vault)\n const snapshot = await freezeSnapshotOnly(vault, collections, { actorUserId: keyring.userId })\n\n // 4. Mint a NEW owner keyring, re-wrapping the incumbent DEKs under the new\n // owner's fresh KEK. The old sealed owner is NOT unsealed — a DISTINCT\n // principal is minted and the original owner credential is left orphaned\n // (inalienability floor). Mirrors adopt-partition.ts's DEK re-wrap.\n const newOwner = await createOwnerKeyring(adapter, vaultName, { userId: opts.newOwnerId, secret: opts.newOwnerSecret })\n if (!newOwner.kek) {\n throw new PermissionDeniedError(\n `new owner keyring for \"${opts.newOwnerId}\" has no KEK to re-wrap the incumbent DEKs under`,\n )\n }\n const env = await adapter.get(vaultName, '_keyring', opts.newOwnerId)\n if (!env) {\n throw new PermissionDeniedError(`new owner keyring for \"${opts.newOwnerId}\" did not persist`)\n }\n const keyringFile = JSON.parse(env._data) as KeyringFile\n // #1096 — this is a read-BACK of the file `createOwnerKeyring` just wrote, and\n // it is about to be edited and restamped, so the store gets a window to alter\n // it in between. Verified against the NEW owner's own roster key, not the\n // incumbent's: at this instant the file is still stamped under the fresh key\n // minted above (the swap to the incumbent key happens below).\n const mintedRosterKey = requireRosterKey(newOwner, 'liberateVault')\n await assertRosterTagValid(keyringFile, mintedRosterKey, opts.newOwnerId)\n const mergedDeks: Record<string, string> = { ...keyringFile.deks }\n for (const [collection, dek] of keyring.deks) {\n mergedDeks[collection] = await wrapKey(dek, newOwner.kek)\n }\n // #1096 — liberation joins a new owner to an EXISTING vault, so the vault's\n // roster key must stay the incumbent one. `createOwnerKeyring` above minted a\n // fresh roster key (correct for a new vault, wrong here), and the merge loop\n // has just overwritten `_roster` with the incumbent's — so the tag it stamped\n // no longer matches the key in the file. Restamp under the key that actually\n // ends up persisted, or the new owner cannot open the vault they just claimed.\n //\n // Keeping the incumbent key is the substantive half: a fresh one would leave\n // the new owner unable to verify any co-member's roster, and every co-member\n // unable to verify theirs.\n const rosterKey = requireRosterKey(keyring, 'liberateVault')\n const merged: KeyringFile = { ...keyringFile, deks: mergedDeks }\n // #1097 — stamped BEFORE the tag is minted, so it lands inside the\n // authenticated canonical and a store can neither edit nor strip it.\n const withEpoch = { ...merged, roster_epoch: nextRosterEpoch(keyringFile.roster_epoch) }\n const mergedFile: KeyringFile = { ...withEpoch, roster_tag: await mintRosterTag(withEpoch, rosterKey) }\n await adapter.put(vaultName, '_keyring', opts.newOwnerId, { ...env, _data: JSON.stringify(mergedFile) })\n\n // 5. Lifecycle ledger audit (no-op if the history strategy is absent).\n await vault._getLedgerOrNull()?.append({\n op: 'lifecycle', collection: '', id: '', version: 0, actor: opts.newOwnerId, payloadHash: '',\n reason: `liberation-claimed:${opts.newOwnerId}:${opts.legalBasis}`,\n })\n\n // 6. Stamp the Deed marker with `liberatedAt` (if a marker exists).\n const marker = await loadDeedMarker(adapter, vaultName)\n if (marker) {\n await saveDeedMarker(adapter, vaultName, { ...marker, liberatedAt: new Date().toISOString() })\n }\n\n return { snapshot }\n}\n\n/**\n * Enumerate the vault's operational (user-facing) collections — those carried\n * by the caller's keyring DEK map, minus the reserved internal collections\n * (`_*`). These are the collections frozen into the evidence snapshot.\n */\nasync function listOperationalCollections(vault: Vault): Promise<readonly string[]> {\n const { keyring } = vault._introspectState()\n return [...keyring.deks.keys()].filter((c) => !c.startsWith('_'))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAuCO,IAAM,iBAAiB;AAqD9B,eAAsB,gBACpB,OACA,OACA,aACA,SAC0B;AAG1B,QAAM,SAAS,MAAM,qBAAqB,OAAO,OAAO,OAAO;AAI/D,QAAM,UAAU,MAAM,mBAAmB,OAAO,OAAO,EAAE,QAAQ,aAAa,OAAe,CAAC;AAI9F,QAAM,eAAe,OAAO,OAAO;AAAA,IACjC;AAAA,IACA,aAAa,QAAQ;AAAA,IACrB,Q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