@noy-db/hub 0.6.0-pre.2 → 0.6.0-pre.21
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 +5234 -0
- package/codemods/0.4.0-pre.json +699 -0
- package/codemods/0.6.0-pre.json +211 -0
- package/dist/api-EYNT6KGS.js +20 -0
- package/dist/attestation/index.js +19 -19
- package/dist/{backup-YYBE5RPC.js → backup-FSC36VWC.js} +36 -18
- package/dist/backup-FSC36VWC.js.map +1 -0
- package/dist/blobs/index.js +13 -13
- package/dist/broker/index.js +12 -12
- package/dist/cargo/index.js +33 -33
- package/dist/{chunk-35EBKWQU.js → chunk-2LFOMUEA.js} +4 -4
- package/dist/{chunk-OF3L2SD6.js → chunk-32B7VCKU.js} +2 -2
- package/dist/{chunk-MSWYQLMQ.js → chunk-3B6S6RSI.js} +2 -2
- package/dist/{chunk-PJNTR2NV.js → chunk-3ENNPCIW.js} +7 -10
- package/dist/chunk-3ENNPCIW.js.map +1 -0
- package/dist/{chunk-7F4DBNSP.js → chunk-3O72ZD2E.js} +3 -3
- package/dist/{chunk-FNSMZQS4.js → chunk-3PMFMUFX.js} +2 -2
- package/dist/{chunk-WQDTCJ6W.js → chunk-45YHJ3GV.js} +11 -3
- package/dist/{chunk-WQDTCJ6W.js.map → chunk-45YHJ3GV.js.map} +1 -1
- package/dist/{chunk-NIVEDYJZ.js → chunk-4A34KWOU.js} +31 -49
- package/dist/chunk-4A34KWOU.js.map +1 -0
- package/dist/{chunk-ZJADGNYF.js → chunk-4AOERLTV.js} +1 -1
- package/dist/chunk-4AOERLTV.js.map +1 -0
- package/dist/{chunk-EDXAQ6JI.js → chunk-4N5Q23KV.js} +87 -34
- package/dist/chunk-4N5Q23KV.js.map +1 -0
- package/dist/{chunk-VV4NSB7P.js → chunk-4OQZNXQG.js} +15 -24
- package/dist/chunk-4OQZNXQG.js.map +1 -0
- package/dist/{chunk-FAXZQ5UF.js → chunk-4RAS6HN6.js} +2 -2
- package/dist/{chunk-C2OOEM57.js → chunk-4YL2LMXK.js} +92 -35
- package/dist/chunk-4YL2LMXK.js.map +1 -0
- package/dist/{chunk-EP7VPR7Y.js → chunk-5Q7AJ7DN.js} +11 -8
- package/dist/chunk-5Q7AJ7DN.js.map +1 -0
- package/dist/{chunk-VMCCGUQB.js → chunk-6JPGVL7X.js} +2 -2
- package/dist/{chunk-PRDRGL73.js → chunk-6KTVJ5ZZ.js} +17 -14
- package/dist/chunk-6KTVJ5ZZ.js.map +1 -0
- package/dist/{chunk-4MC5JRRX.js → chunk-6WO62AJW.js} +14 -15
- package/dist/chunk-6WO62AJW.js.map +1 -0
- package/dist/{chunk-WLYIROCJ.js → chunk-6YD5SYQS.js} +2 -2
- package/dist/{chunk-YAWK6AWF.js → chunk-7KAE7CQ2.js} +2 -2
- package/dist/{chunk-MWKDOHEF.js → chunk-7LNE2N2V.js} +17 -10
- package/dist/chunk-7LNE2N2V.js.map +1 -0
- package/dist/{chunk-5PR33AC4.js → chunk-7PJ3BKHS.js} +20 -17
- package/dist/chunk-7PJ3BKHS.js.map +1 -0
- package/dist/{chunk-JXIDGFKS.js → chunk-A4TOGAUW.js} +4 -2
- package/dist/chunk-A4TOGAUW.js.map +1 -0
- package/dist/{chunk-VCETL77O.js → chunk-AU3AUJIZ.js} +27 -7
- package/dist/chunk-AU3AUJIZ.js.map +1 -0
- package/dist/{chunk-NKH7GSIH.js → chunk-AUPSEJ7O.js} +4 -4
- package/dist/{chunk-CCZJJ4I2.js → chunk-B6IYATME.js} +4 -4
- package/dist/{chunk-WYZ5MYUA.js → chunk-BAHOV5I5.js} +44 -42
- package/dist/chunk-BAHOV5I5.js.map +1 -0
- package/dist/{chunk-G5APARUV.js → chunk-BEZDLIDG.js} +13 -15
- package/dist/chunk-BEZDLIDG.js.map +1 -0
- package/dist/{chunk-ERB6NDDW.js → chunk-CAGI4LLJ.js} +427 -72
- package/dist/chunk-CAGI4LLJ.js.map +1 -0
- package/dist/{chunk-4UVDI4XE.js → chunk-CLAHBPOI.js} +4 -4
- package/dist/{chunk-HNGSV2YC.js → chunk-CWM4GQD2.js} +39 -10
- package/dist/chunk-CWM4GQD2.js.map +1 -0
- package/dist/{chunk-HVQGCKY4.js → chunk-D3R7Q4QK.js} +2 -2
- package/dist/{chunk-I4F6PKUK.js → chunk-DIZ6HM7Q.js} +16 -17
- package/dist/chunk-DIZ6HM7Q.js.map +1 -0
- package/dist/{chunk-ZNACADFG.js → chunk-DVRZYAGT.js} +4 -4
- package/dist/chunk-DVRZYAGT.js.map +1 -0
- package/dist/{chunk-P7OG2ETF.js → chunk-DXKLLKME.js} +3 -3
- package/dist/{chunk-TDJPS3T2.js → chunk-E5SC6ENM.js} +24 -19
- package/dist/chunk-E5SC6ENM.js.map +1 -0
- package/dist/{chunk-26JMGSSC.js → chunk-EES37S2V.js} +4 -4
- package/dist/chunk-EES37S2V.js.map +1 -0
- package/dist/{chunk-JIUVJ4M7.js → chunk-EKEIEJL6.js} +2 -2
- package/dist/{chunk-GASWQ3XG.js → chunk-ESKIAXO2.js} +15 -16
- package/dist/chunk-ESKIAXO2.js.map +1 -0
- package/dist/{chunk-TOAIYQJR.js → chunk-FFSQFH6D.js} +7 -10
- package/dist/chunk-FFSQFH6D.js.map +1 -0
- package/dist/{chunk-DG27IUVI.js → chunk-FS7NTGCJ.js} +2 -2
- package/dist/{chunk-V5KYPBUR.js → chunk-FW7NGYLT.js} +11 -14
- package/dist/chunk-FW7NGYLT.js.map +1 -0
- package/dist/{chunk-52QYGZHH.js → chunk-GBBDFE6C.js} +2 -2
- package/dist/chunk-GBBDFE6C.js.map +1 -0
- package/dist/{chunk-HXGUIPQB.js → chunk-GQXFOAYZ.js} +3 -3
- package/dist/{chunk-BTVYJWSN.js → chunk-GTHVPVAR.js} +10 -10
- package/dist/{chunk-DMQCLZ4Z.js → chunk-GWO2IDAB.js} +2 -2
- package/dist/{chunk-6HFM7EIT.js → chunk-H3G4I3PN.js} +2 -2
- package/dist/chunk-HK67PX4J.js +27 -0
- package/dist/chunk-HK67PX4J.js.map +1 -0
- package/dist/{chunk-E7OBCBXS.js → chunk-HQSPF5IY.js} +22 -18
- package/dist/chunk-HQSPF5IY.js.map +1 -0
- package/dist/{chunk-VJFMXYKP.js → chunk-HR5R5JOM.js} +2 -2
- package/dist/{chunk-FDX7OWWI.js → chunk-HYYVT2KZ.js} +2 -2
- package/dist/{chunk-JRCYZEHU.js → chunk-I6QKB7MT.js} +2 -2
- package/dist/{chunk-MZ5ZFO2D.js → chunk-ICDHUUMQ.js} +84 -112
- package/dist/chunk-ICDHUUMQ.js.map +1 -0
- package/dist/{chunk-W5W6KHN2.js → chunk-IGNJOJEP.js} +1 -1
- package/dist/chunk-IGNJOJEP.js.map +1 -0
- package/dist/{chunk-KUDZVJKQ.js → chunk-IJ46VCWD.js} +2 -2
- package/dist/{chunk-4HDYQL3J.js → chunk-INMHEMXX.js} +2 -2
- package/dist/{chunk-66W5OOCX.js → chunk-JLYQQNY4.js} +52 -65
- package/dist/chunk-JLYQQNY4.js.map +1 -0
- package/dist/{chunk-UHXCLPGC.js → chunk-JNMTN5D5.js} +2 -2
- package/dist/chunk-JNMTN5D5.js.map +1 -0
- package/dist/{chunk-I4ZAO7F7.js → chunk-JWMBG5S3.js} +7 -11
- package/dist/chunk-JWMBG5S3.js.map +1 -0
- package/dist/chunk-KRVS7YWY.js +123 -0
- package/dist/chunk-KRVS7YWY.js.map +1 -0
- package/dist/{chunk-AR2JDFAE.js → chunk-KV6JM2IA.js} +2 -2
- package/dist/{chunk-PVU7LW5L.js → chunk-KX57HODD.js} +6 -6
- package/dist/{chunk-PY7CI6L5.js → chunk-LGFTOU27.js} +553 -275
- package/dist/chunk-LGFTOU27.js.map +1 -0
- package/dist/chunk-LN7P6MZB.js +190 -0
- package/dist/chunk-LN7P6MZB.js.map +1 -0
- package/dist/{chunk-UIBGXRDD.js → chunk-LX46B56Q.js} +25 -31
- package/dist/chunk-LX46B56Q.js.map +1 -0
- package/dist/{chunk-CEJWMBXO.js → chunk-LXECF2ZR.js} +2 -2
- package/dist/{chunk-7VHY5E3X.js → chunk-MSLPDFK2.js} +7 -7
- package/dist/{chunk-I6SDX7WX.js → chunk-MZTUTEHP.js} +16 -22
- package/dist/chunk-MZTUTEHP.js.map +1 -0
- package/dist/{chunk-VRA4Q7DA.js → chunk-NCCEDL2K.js} +55 -48
- package/dist/chunk-NCCEDL2K.js.map +1 -0
- package/dist/{chunk-HNHCQ556.js → chunk-NR2SUJ3H.js} +2 -2
- package/dist/{chunk-AHLJSVRL.js → chunk-NW4TY6VC.js} +5 -7
- package/dist/chunk-NW4TY6VC.js.map +1 -0
- package/dist/{chunk-RKKORO4M.js → chunk-O742QBZZ.js} +10 -10
- package/dist/chunk-O742QBZZ.js.map +1 -0
- package/dist/{chunk-VN45YLWM.js → chunk-OHOKBMTM.js} +343 -132
- package/dist/chunk-OHOKBMTM.js.map +1 -0
- package/dist/{chunk-W3TVWF6N.js → chunk-OIBEJN5H.js} +2 -2
- package/dist/{chunk-QD724WDJ.js → chunk-OMYCSTXL.js} +4 -4
- package/dist/{chunk-Z45YRGFO.js → chunk-ONVD6GBY.js} +2 -2
- package/dist/{chunk-TAGFGKHP.js → chunk-OTHHO3KI.js} +7 -10
- package/dist/chunk-OTHHO3KI.js.map +1 -0
- package/dist/{chunk-3737A6EA.js → chunk-P2MR5UNE.js} +75 -18
- package/dist/chunk-P2MR5UNE.js.map +1 -0
- package/dist/chunk-PENPHA45.js +66 -0
- package/dist/chunk-PENPHA45.js.map +1 -0
- package/dist/{chunk-3FSX6LDG.js → chunk-PPCOKVFA.js} +8 -3
- package/dist/{chunk-3FSX6LDG.js.map → chunk-PPCOKVFA.js.map} +1 -1
- package/dist/{chunk-VOQW5LAM.js → chunk-QSIEL6TL.js} +102 -71
- package/dist/chunk-QSIEL6TL.js.map +1 -0
- package/dist/chunk-RFO4UXKQ.js +201 -0
- package/dist/chunk-RFO4UXKQ.js.map +1 -0
- package/dist/{chunk-KCQX65FU.js → chunk-RKCRPPNB.js} +3 -3
- package/dist/{chunk-7TSYBD3E.js → chunk-RSXQNFGO.js} +2 -2
- package/dist/{chunk-SZ2K3MHL.js → chunk-S56VYR4Q.js} +8 -11
- package/dist/{chunk-SZ2K3MHL.js.map → chunk-S56VYR4Q.js.map} +1 -1
- package/dist/{chunk-7NXHMW6Y.js → chunk-SYS46BL7.js} +2 -2
- package/dist/{chunk-55LKVALY.js → chunk-T7IR4N2S.js} +1 -3
- package/dist/chunk-T7IR4N2S.js.map +1 -0
- package/dist/{chunk-A67356IR.js → chunk-T7JGWTES.js} +33 -8
- package/dist/chunk-T7JGWTES.js.map +1 -0
- package/dist/{chunk-WHJKIZS7.js → chunk-TDSN2O2V.js} +27 -149
- package/dist/chunk-TDSN2O2V.js.map +1 -0
- package/dist/{chunk-747LRSOO.js → chunk-TMBSPLUG.js} +2 -2
- package/dist/{chunk-LWSJG3LI.js → chunk-TQPASLY4.js} +7 -3
- package/dist/chunk-TQPASLY4.js.map +1 -0
- package/dist/{chunk-WKPJXWKR.js → chunk-TX5MKAHA.js} +3 -3
- package/dist/{chunk-HFQ6LGIO.js → chunk-U27Y4DJZ.js} +12 -10
- package/dist/{chunk-HFQ6LGIO.js.map → chunk-U27Y4DJZ.js.map} +1 -1
- package/dist/{chunk-E6427JU2.js → chunk-VVSOPRUE.js} +18 -2
- package/dist/chunk-VVSOPRUE.js.map +1 -0
- package/dist/{chunk-7G6VDWXB.js → chunk-WVE6YKMX.js} +3 -3
- package/dist/chunk-WVE6YKMX.js.map +1 -0
- package/dist/{chunk-GLKDWWNO.js → chunk-YALD3SST.js} +16 -14
- package/dist/chunk-YALD3SST.js.map +1 -0
- package/dist/{chunk-NJDQ4YSV.js → chunk-YKXZHUOW.js} +4 -4
- package/dist/{chunk-VW6ZZGCG.js → chunk-ZLHHE5XZ.js} +3 -3
- package/dist/{chunk-FUHKW252.js → chunk-ZZXLB6AS.js} +2 -2
- package/dist/classified/index.js +5 -5
- package/dist/{classified-marker-FTOX7Q5L.js → classified-marker-NA6HUV33.js} +3 -3
- package/dist/collection-facade-VBM35WAH.js +45 -0
- package/dist/{computed-6G5M3UPH.js → computed-GSTLWSY5.js} +3 -3
- package/dist/consent/index.js +10 -10
- package/dist/cover/index.js +10 -3
- package/dist/custody/index.js +11 -11
- package/dist/{dead-filter-ENRIOQIE.js → dead-filter-UALP5DJX.js} +2 -2
- package/dist/debug/index.js +1 -1
- package/dist/{delegation-SSEPLXXO.js → delegation-JLNXM7KH.js} +24 -23
- package/dist/delegation-JLNXM7KH.js.map +1 -0
- package/dist/derivations/index.js +12 -12
- package/dist/derive-YUO3TQYN.js +22 -0
- package/dist/directory/index.js +10 -10
- package/dist/{dispatch-RE74SH6L.js → dispatch-4ZHLSFZQ.js} +5 -5
- package/dist/{dispatch-BDVGYC6X.js → dispatch-77CB75KB.js} +18 -18
- package/dist/{enclave-52VUXNRL.js → enclave-O4NOROCJ.js} +27 -9
- package/dist/executor-CZDXBXKE.js +29 -0
- package/dist/executor-DVJAWN3B.js +9 -0
- package/dist/executor-VRLG4TQJ.js +9 -0
- package/dist/export-accessible-UXSMG7AB.js +23 -0
- package/dist/extract-partition-TVY7AMKH.js +38 -0
- package/dist/{fanout-sidecar-DTBIDOWF.js → fanout-sidecar-NLQ7QAYW.js} +18 -27
- package/dist/fanout-sidecar-NLQ7QAYW.js.map +1 -0
- package/dist/find-WSARMJBW.js +11 -0
- package/dist/forget/index.js +9 -9
- package/dist/guards/index.js +7 -7
- package/dist/history/index.js +23 -20
- package/dist/history/index.js.map +1 -1
- package/dist/i18n/index.js +14 -14
- package/dist/index.d.ts +33 -15
- package/dist/index.js +187 -191
- package/dist/index.js.map +1 -1
- package/dist/indexing/index.js +2 -2
- package/dist/introspection/index.js +11 -11
- package/dist/issue-3JNJNPT3.js +19 -0
- package/dist/kernel/constants.d.ts +18 -0
- package/dist/kernel/enclave/crypto.d.ts +24 -4
- package/dist/kernel/enclave/index.d.ts +9 -2
- package/dist/kernel/enclave/record-aad.d.ts +131 -0
- package/dist/kernel/enclave/record-envelope.d.ts +76 -0
- package/dist/kernel/enclave/record-keys/envelope-body.d.ts +34 -2
- package/dist/kernel/enclave/record-keys/lifecycle.d.ts +22 -5
- package/dist/kernel/enclave/record-keys/record-codec.d.ts +47 -14
- package/dist/kernel/enclave/record-keys/rekey-blob.d.ts +88 -0
- package/dist/kernel/enclave/record-keys/rekey.d.ts +68 -0
- package/dist/kernel/enclave/record-keys/tombstone.d.ts +3 -2
- package/dist/kernel/errors.d.ts +71 -12
- package/dist/kernel/merge-authority.d.ts +25 -0
- package/dist/kernel/noydb.d.ts +27 -4
- package/dist/kernel/query/builder.d.ts +15 -2
- package/dist/kernel/query/join.d.ts +27 -0
- package/dist/kernel/sync-policy.d.ts +0 -2
- package/dist/kernel/tier-visibility.d.ts +15 -0
- package/dist/kernel/types.d.ts +145 -12
- package/dist/kernel/vault.d.ts +22 -18
- package/dist/kernel/via/index.d.ts +11 -2
- package/dist/{ledger-4WJL66BW.js → ledger-MVPNG5OS.js} +11 -11
- package/dist/liberate-4LOJOLDT.js +24 -0
- package/dist/{link-set-N4ZPV6E6.js → link-set-3POMQR3I.js} +11 -11
- package/dist/{managed-secret-OTHS64IF.js → managed-secret-IARIJJ7Q.js} +11 -3
- package/dist/materialized-views/index.js +22 -21
- package/dist/migrate-cek-XM2ETTZW.js +19 -0
- package/dist/migrate-cek-XM2ETTZW.js.map +1 -0
- package/dist/money/index.js +12 -8
- package/dist/noydb-IRILUDED.js +84 -0
- package/dist/overlay-views/index.js +4 -4
- package/dist/periods/index.js +22 -12
- package/dist/pod/index.js +75 -86
- package/dist/pod-handle-MELERCKU.js +41 -0
- package/dist/pod-handle-MELERCKU.js.map +1 -0
- package/dist/policy/index.js +11 -4
- package/dist/port/to/index.d.ts +4 -4
- package/dist/port/to/locator.d.ts +54 -8
- package/dist/port/with/i18n-strategy.d.ts +4 -1
- package/dist/port/with/lookup-strategy.d.ts +4 -1
- package/dist/port/with/merge-authority.d.ts +52 -0
- package/dist/port/with/service-bus.d.ts +0 -4
- package/dist/port/with/strategies.d.ts +2 -0
- package/dist/port/with/team-strategy.d.ts +5 -1
- package/dist/portability/index.js +8 -8
- package/dist/{post-register-ZAG2CAIY.js → post-register-Z5T7FY45.js} +6 -6
- package/dist/query/index.js +3 -3
- package/dist/reduce/index.js +4 -4
- package/dist/register-UZ37QPDB.js +32 -0
- package/dist/registry-ETJNA7PO.js +9 -0
- package/dist/registry-F7U6KSLX.js +9 -0
- package/dist/registry-L4ELKX6C.js +18 -0
- package/dist/registry-SDT5LIGO.js +19 -0
- package/dist/request-withdrawal-PVFEYX57.js +31 -0
- package/dist/{reveal-CMOJY4VO.js → reveal-DQ2E3QAZ.js} +6 -6
- package/dist/revoke-YXY6SHUH.js +24 -0
- package/dist/satellites/index.js +1 -1
- package/dist/schema-update/index.js +2 -2
- package/dist/sealed-record/index.js +20 -13
- package/dist/sealed-record/index.js.map +1 -1
- package/dist/search/index.js +4 -4
- package/dist/{seed-UK4QRIUN.js → seed-DZ4ORU5N.js} +19 -22
- package/dist/seed-DZ4ORU5N.js.map +1 -0
- package/dist/sequence/index.js +9 -9
- package/dist/session/index.js +10 -10
- package/dist/shadow/index.js +2 -2
- package/dist/share-link/index.js +1 -1
- package/dist/signer-Q7XQBMPA.js +25 -0
- package/dist/snapshots/index.js +10 -10
- package/dist/snapshots/index.js.map +1 -1
- package/dist/{stale-ZWXSOWJI.js → stale-NI7SAXAZ.js} +10 -10
- package/dist/storage-3VNGSHXS.js +23 -0
- package/dist/{store-coordination-provider-PB6QZ57W.js → store-coordination-provider-TYKNR3OU.js} +18 -12
- package/dist/store-coordination-provider-TYKNR3OU.js.map +1 -0
- package/dist/sync/index.js +11 -11
- package/dist/team/index.js +15 -14
- package/dist/tiers/index.js +11 -10
- package/dist/to/index.js +17 -9
- package/dist/to/index.js.map +1 -1
- package/dist/transactions/index.js +4 -4
- package/dist/{ulid-PTAIMDG4.js → ulid-VQW6ERQN.js} +2 -2
- package/dist/util/index.js +1 -1
- package/dist/vault-head/index.js +115 -0
- package/dist/vault-head/index.js.map +1 -0
- package/dist/{verify-RO5RTZOJ.js → verify-6J2YLKSO.js} +5 -5
- package/dist/via/lookup/handle.d.ts +4 -1
- package/dist/via/money/exact.d.ts +44 -0
- package/dist/via/money/index.d.ts +2 -0
- package/dist/via/money/normalize.d.ts +20 -0
- package/dist/walk-WRA7RAPY.js +21 -0
- package/dist/with-audit/guards/immutable-guard.d.ts +14 -0
- package/dist/with-audit/periods/active.d.ts +28 -1
- package/dist/with-audit/periods/index.d.ts +4 -2
- package/dist/with-audit/periods/periods.d.ts +161 -6
- package/dist/with-audit/periods/strategy.d.ts +14 -5
- package/dist/with-audit/periods/vault-facade.d.ts +89 -10
- package/dist/with-audit/periods/window.d.ts +10 -0
- package/dist/with-audit/sealed-record/index.d.ts +13 -0
- package/dist/with-audit/tiers/index.d.ts +17 -2
- package/dist/with-cargo/adopt-partition.d.ts +1 -1
- package/dist/with-cargo/extract-partition.d.ts +1 -1
- package/dist/with-cargo/index.d.ts +2 -2
- package/dist/with-commit/history/history.d.ts +26 -0
- package/dist/with-commit/history/index.d.ts +2 -1
- package/dist/with-commit/history/ledger/store.d.ts +7 -1
- package/dist/with-commit/history/strategy.d.ts +11 -1
- package/dist/with-commit/numbering/index.d.ts +0 -5
- package/dist/with-commit/vault-head/active.d.ts +2 -0
- package/dist/with-commit/vault-head/head.d.ts +28 -0
- package/dist/with-commit/vault-head/index.d.ts +10 -0
- package/dist/with-commit/vault-head/strategy.d.ts +127 -0
- package/dist/with-commit/vault-head/verify.d.ts +90 -0
- package/dist/with-formula/materialized-views/types.d.ts +52 -0
- package/dist/with-party/directory/cover/storage.d.ts +0 -8
- package/dist/with-party/directory/storage.d.ts +0 -11
- package/dist/with-party/directory/visibility.d.ts +0 -21
- package/dist/with-party/policy/storage.d.ts +0 -10
- package/dist/with-party/team/index.d.ts +1 -1
- package/dist/with-party/team/keyring.d.ts +149 -3
- package/dist/with-party/team/noydb-facade.d.ts +5 -1
- package/dist/with-party/team/roster-tag.d.ts +101 -0
- package/dist/with-party/team/tiers.d.ts +2 -1
- package/dist/with-pod/format.d.ts +10 -12
- package/dist/with-pod/index.d.ts +10 -10
- package/dist/with-pod/open.d.ts +2 -2
- package/dist/with-pod/pod-handle.d.ts +19 -0
- package/dist/with-pod/pod-store.d.ts +0 -8
- package/dist/with-pod/{bundle.d.ts → pod.d.ts} +26 -19
- package/dist/with-pod/ulid.d.ts +1 -1
- package/dist/with-shape/blobs/blob-set.d.ts +2 -2
- package/dist/with-shape/introspection/index.d.ts +1 -0
- package/dist/with-sync/engine.d.ts +54 -5
- package/dist/with-sync/strategy.d.ts +3 -0
- package/dist/withdraw-accessible-4JTDFRFZ.js +28 -0
- package/package.json +13 -5
- package/dist/api-WVY3H3YH.js +0 -20
- package/dist/backup-YYBE5RPC.js.map +0 -1
- package/dist/bundle-handle-JEUWU2SJ.js +0 -36
- package/dist/bundle-handle-JEUWU2SJ.js.map +0 -1
- package/dist/chunk-26JMGSSC.js.map +0 -1
- package/dist/chunk-3737A6EA.js.map +0 -1
- package/dist/chunk-4MC5JRRX.js.map +0 -1
- package/dist/chunk-52QYGZHH.js.map +0 -1
- package/dist/chunk-55LKVALY.js.map +0 -1
- package/dist/chunk-5PR33AC4.js.map +0 -1
- package/dist/chunk-66W5OOCX.js.map +0 -1
- package/dist/chunk-7G6VDWXB.js.map +0 -1
- package/dist/chunk-A67356IR.js.map +0 -1
- package/dist/chunk-AFHQATY4.js +0 -47
- package/dist/chunk-AFHQATY4.js.map +0 -1
- package/dist/chunk-AHLJSVRL.js.map +0 -1
- package/dist/chunk-C2OOEM57.js.map +0 -1
- package/dist/chunk-DIMKRG2E.js +0 -131
- package/dist/chunk-DIMKRG2E.js.map +0 -1
- package/dist/chunk-E6427JU2.js.map +0 -1
- package/dist/chunk-E7OBCBXS.js.map +0 -1
- package/dist/chunk-EDXAQ6JI.js.map +0 -1
- package/dist/chunk-EP7VPR7Y.js.map +0 -1
- package/dist/chunk-ERB6NDDW.js.map +0 -1
- package/dist/chunk-G5APARUV.js.map +0 -1
- package/dist/chunk-GASWQ3XG.js.map +0 -1
- package/dist/chunk-GLKDWWNO.js.map +0 -1
- package/dist/chunk-HNGSV2YC.js.map +0 -1
- package/dist/chunk-I4F6PKUK.js.map +0 -1
- package/dist/chunk-I4ZAO7F7.js.map +0 -1
- package/dist/chunk-I6SDX7WX.js.map +0 -1
- package/dist/chunk-JXIDGFKS.js.map +0 -1
- package/dist/chunk-LWSJG3LI.js.map +0 -1
- package/dist/chunk-MWKDOHEF.js.map +0 -1
- package/dist/chunk-MZ5ZFO2D.js.map +0 -1
- package/dist/chunk-NIVEDYJZ.js.map +0 -1
- package/dist/chunk-NWCGDAV6.js +0 -45
- package/dist/chunk-NWCGDAV6.js.map +0 -1
- package/dist/chunk-PJNTR2NV.js.map +0 -1
- package/dist/chunk-PRDRGL73.js.map +0 -1
- package/dist/chunk-PY7CI6L5.js.map +0 -1
- package/dist/chunk-RKKORO4M.js.map +0 -1
- package/dist/chunk-TAGFGKHP.js.map +0 -1
- package/dist/chunk-TDJPS3T2.js.map +0 -1
- package/dist/chunk-TOAIYQJR.js.map +0 -1
- package/dist/chunk-UHXCLPGC.js.map +0 -1
- package/dist/chunk-UIBGXRDD.js.map +0 -1
- package/dist/chunk-V5KYPBUR.js.map +0 -1
- package/dist/chunk-VCETL77O.js.map +0 -1
- package/dist/chunk-VN45YLWM.js.map +0 -1
- package/dist/chunk-VOQW5LAM.js.map +0 -1
- package/dist/chunk-VRA4Q7DA.js.map +0 -1
- package/dist/chunk-VV4NSB7P.js.map +0 -1
- package/dist/chunk-W5W6KHN2.js.map +0 -1
- package/dist/chunk-WHJKIZS7.js.map +0 -1
- package/dist/chunk-WYZ5MYUA.js.map +0 -1
- package/dist/chunk-ZJADGNYF.js.map +0 -1
- package/dist/chunk-ZNACADFG.js.map +0 -1
- package/dist/collection-facade-QN5ULWYC.js +0 -45
- package/dist/delegation-SSEPLXXO.js.map +0 -1
- package/dist/derive-6V3PIZF7.js +0 -22
- package/dist/executor-CYJQLKKI.js +0 -9
- package/dist/executor-FHHLXO4Y.js +0 -28
- package/dist/executor-S4QIKEHW.js +0 -9
- package/dist/export-accessible-PE5AYKZR.js +0 -23
- package/dist/extract-partition-X2L26O6A.js +0 -38
- package/dist/fanout-sidecar-DTBIDOWF.js.map +0 -1
- package/dist/find-RBBYKXI7.js +0 -11
- package/dist/issue-RNU55YOF.js +0 -19
- package/dist/liberate-PX4CAT5V.js +0 -24
- package/dist/noydb-YPSEGK32.js +0 -83
- package/dist/register-TMD6YRCX.js +0 -32
- package/dist/registry-CZVINVQH.js +0 -9
- package/dist/registry-FVLDWQKT.js +0 -18
- package/dist/registry-IKUR2MXD.js +0 -9
- package/dist/registry-JET4HBLY.js +0 -19
- package/dist/request-withdrawal-RH55LNZL.js +0 -31
- package/dist/revoke-R5TBYVA6.js +0 -24
- package/dist/seed-UK4QRIUN.js.map +0 -1
- package/dist/signer-AGALOXOO.js +0 -25
- package/dist/storage-N7LB275C.js +0 -23
- package/dist/store-coordination-provider-PB6QZ57W.js.map +0 -1
- package/dist/walk-OCUHCYJ6.js +0 -21
- package/dist/with-pod/bundle-handle.d.ts +0 -9
- package/dist/withdraw-accessible-QQNWM5BO.js +0 -28
- /package/dist/{api-WVY3H3YH.js.map → api-EYNT6KGS.js.map} +0 -0
- /package/dist/{chunk-35EBKWQU.js.map → chunk-2LFOMUEA.js.map} +0 -0
- /package/dist/{chunk-OF3L2SD6.js.map → chunk-32B7VCKU.js.map} +0 -0
- /package/dist/{chunk-MSWYQLMQ.js.map → chunk-3B6S6RSI.js.map} +0 -0
- /package/dist/{chunk-7F4DBNSP.js.map → chunk-3O72ZD2E.js.map} +0 -0
- /package/dist/{chunk-FNSMZQS4.js.map → chunk-3PMFMUFX.js.map} +0 -0
- /package/dist/{chunk-FAXZQ5UF.js.map → chunk-4RAS6HN6.js.map} +0 -0
- /package/dist/{chunk-VMCCGUQB.js.map → chunk-6JPGVL7X.js.map} +0 -0
- /package/dist/{chunk-WLYIROCJ.js.map → chunk-6YD5SYQS.js.map} +0 -0
- /package/dist/{chunk-YAWK6AWF.js.map → chunk-7KAE7CQ2.js.map} +0 -0
- /package/dist/{chunk-NKH7GSIH.js.map → chunk-AUPSEJ7O.js.map} +0 -0
- /package/dist/{chunk-CCZJJ4I2.js.map → chunk-B6IYATME.js.map} +0 -0
- /package/dist/{chunk-4UVDI4XE.js.map → chunk-CLAHBPOI.js.map} +0 -0
- /package/dist/{chunk-HVQGCKY4.js.map → chunk-D3R7Q4QK.js.map} +0 -0
- /package/dist/{chunk-P7OG2ETF.js.map → chunk-DXKLLKME.js.map} +0 -0
- /package/dist/{chunk-JIUVJ4M7.js.map → chunk-EKEIEJL6.js.map} +0 -0
- /package/dist/{chunk-DG27IUVI.js.map → chunk-FS7NTGCJ.js.map} +0 -0
- /package/dist/{chunk-HXGUIPQB.js.map → chunk-GQXFOAYZ.js.map} +0 -0
- /package/dist/{chunk-BTVYJWSN.js.map → chunk-GTHVPVAR.js.map} +0 -0
- /package/dist/{chunk-DMQCLZ4Z.js.map → chunk-GWO2IDAB.js.map} +0 -0
- /package/dist/{chunk-6HFM7EIT.js.map → chunk-H3G4I3PN.js.map} +0 -0
- /package/dist/{chunk-VJFMXYKP.js.map → chunk-HR5R5JOM.js.map} +0 -0
- /package/dist/{chunk-FDX7OWWI.js.map → chunk-HYYVT2KZ.js.map} +0 -0
- /package/dist/{chunk-JRCYZEHU.js.map → chunk-I6QKB7MT.js.map} +0 -0
- /package/dist/{chunk-KUDZVJKQ.js.map → chunk-IJ46VCWD.js.map} +0 -0
- /package/dist/{chunk-4HDYQL3J.js.map → chunk-INMHEMXX.js.map} +0 -0
- /package/dist/{chunk-AR2JDFAE.js.map → chunk-KV6JM2IA.js.map} +0 -0
- /package/dist/{chunk-PVU7LW5L.js.map → chunk-KX57HODD.js.map} +0 -0
- /package/dist/{chunk-CEJWMBXO.js.map → chunk-LXECF2ZR.js.map} +0 -0
- /package/dist/{chunk-7VHY5E3X.js.map → chunk-MSLPDFK2.js.map} +0 -0
- /package/dist/{chunk-HNHCQ556.js.map → chunk-NR2SUJ3H.js.map} +0 -0
- /package/dist/{chunk-W3TVWF6N.js.map → chunk-OIBEJN5H.js.map} +0 -0
- /package/dist/{chunk-QD724WDJ.js.map → chunk-OMYCSTXL.js.map} +0 -0
- /package/dist/{chunk-Z45YRGFO.js.map → chunk-ONVD6GBY.js.map} +0 -0
- /package/dist/{chunk-KCQX65FU.js.map → chunk-RKCRPPNB.js.map} +0 -0
- /package/dist/{chunk-7TSYBD3E.js.map → chunk-RSXQNFGO.js.map} +0 -0
- /package/dist/{chunk-7NXHMW6Y.js.map → chunk-SYS46BL7.js.map} +0 -0
- /package/dist/{chunk-747LRSOO.js.map → chunk-TMBSPLUG.js.map} +0 -0
- /package/dist/{chunk-WKPJXWKR.js.map → chunk-TX5MKAHA.js.map} +0 -0
- /package/dist/{chunk-NJDQ4YSV.js.map → chunk-YKXZHUOW.js.map} +0 -0
- /package/dist/{chunk-VW6ZZGCG.js.map → chunk-ZLHHE5XZ.js.map} +0 -0
- /package/dist/{chunk-FUHKW252.js.map → chunk-ZZXLB6AS.js.map} +0 -0
- /package/dist/{classified-marker-FTOX7Q5L.js.map → classified-marker-NA6HUV33.js.map} +0 -0
- /package/dist/{collection-facade-QN5ULWYC.js.map → collection-facade-VBM35WAH.js.map} +0 -0
- /package/dist/{computed-6G5M3UPH.js.map → computed-GSTLWSY5.js.map} +0 -0
- /package/dist/{dead-filter-ENRIOQIE.js.map → dead-filter-UALP5DJX.js.map} +0 -0
- /package/dist/{derive-6V3PIZF7.js.map → derive-YUO3TQYN.js.map} +0 -0
- /package/dist/{dispatch-RE74SH6L.js.map → dispatch-4ZHLSFZQ.js.map} +0 -0
- /package/dist/{dispatch-BDVGYC6X.js.map → dispatch-77CB75KB.js.map} +0 -0
- /package/dist/{enclave-52VUXNRL.js.map → enclave-O4NOROCJ.js.map} +0 -0
- /package/dist/{executor-CYJQLKKI.js.map → executor-CZDXBXKE.js.map} +0 -0
- /package/dist/{executor-FHHLXO4Y.js.map → executor-DVJAWN3B.js.map} +0 -0
- /package/dist/{executor-S4QIKEHW.js.map → executor-VRLG4TQJ.js.map} +0 -0
- /package/dist/{export-accessible-PE5AYKZR.js.map → export-accessible-UXSMG7AB.js.map} +0 -0
- /package/dist/{extract-partition-X2L26O6A.js.map → extract-partition-TVY7AMKH.js.map} +0 -0
- /package/dist/{find-RBBYKXI7.js.map → find-WSARMJBW.js.map} +0 -0
- /package/dist/{issue-RNU55YOF.js.map → issue-3JNJNPT3.js.map} +0 -0
- /package/dist/{ledger-4WJL66BW.js.map → ledger-MVPNG5OS.js.map} +0 -0
- /package/dist/{liberate-PX4CAT5V.js.map → liberate-4LOJOLDT.js.map} +0 -0
- /package/dist/{link-set-N4ZPV6E6.js.map → link-set-3POMQR3I.js.map} +0 -0
- /package/dist/{managed-secret-OTHS64IF.js.map → managed-secret-IARIJJ7Q.js.map} +0 -0
- /package/dist/{noydb-YPSEGK32.js.map → noydb-IRILUDED.js.map} +0 -0
- /package/dist/{post-register-ZAG2CAIY.js.map → post-register-Z5T7FY45.js.map} +0 -0
- /package/dist/{register-TMD6YRCX.js.map → register-UZ37QPDB.js.map} +0 -0
- /package/dist/{registry-CZVINVQH.js.map → registry-ETJNA7PO.js.map} +0 -0
- /package/dist/{registry-FVLDWQKT.js.map → registry-F7U6KSLX.js.map} +0 -0
- /package/dist/{registry-IKUR2MXD.js.map → registry-L4ELKX6C.js.map} +0 -0
- /package/dist/{registry-JET4HBLY.js.map → registry-SDT5LIGO.js.map} +0 -0
- /package/dist/{request-withdrawal-RH55LNZL.js.map → request-withdrawal-PVFEYX57.js.map} +0 -0
- /package/dist/{reveal-CMOJY4VO.js.map → reveal-DQ2E3QAZ.js.map} +0 -0
- /package/dist/{revoke-R5TBYVA6.js.map → revoke-YXY6SHUH.js.map} +0 -0
- /package/dist/{signer-AGALOXOO.js.map → signer-Q7XQBMPA.js.map} +0 -0
- /package/dist/{stale-ZWXSOWJI.js.map → stale-NI7SAXAZ.js.map} +0 -0
- /package/dist/{storage-N7LB275C.js.map → storage-3VNGSHXS.js.map} +0 -0
- /package/dist/{ulid-PTAIMDG4.js.map → ulid-VQW6ERQN.js.map} +0 -0
- /package/dist/{verify-RO5RTZOJ.js.map → verify-6J2YLKSO.js.map} +0 -0
- /package/dist/{walk-OCUHCYJ6.js.map → walk-WRA7RAPY.js.map} +0 -0
- /package/dist/{withdraw-accessible-QQNWM5BO.js.map → withdraw-accessible-4JTDFRFZ.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/with-pod/ulid.ts"],"sourcesContent":["/**\n * Minimal ULID generator — zero dependencies, Web Crypto API only.\n *\n *. Used by the bundle writer to generate stable opaque\n * handles for `.noydb` containers.\n *\n * **What's a ULID?** A 128-bit identifier encoded as 26 Crockford\n * base32 characters. Layout:\n *\n * ```\n * 01HYABCDEFGHJKMNPQRSTVWXYZ\n * |--------||---------------|\n * 48-bit 80-bit\n * timestamp randomness\n * ```\n *\n * The first 10 chars encode a millisecond Unix timestamp (so ULIDs\n * sort lexicographically by creation time), and the remaining 16\n * chars are random. Crockford base32 omits I/L/O/U to avoid\n * ambiguity in handwriting and URLs.\n *\n * **Why hand-roll instead of pulling in `ulid`?** The package adds\n * a dep, the implementation is ~30 lines, and the bundle module\n * is the only consumer. Adding `ulid` would also drag in its own\n * crypto polyfill that we don't need on Node 18+ or modern\n * browsers.\n *\n * **Privacy consideration:** the timestamp prefix is observable in\n * the bundle header. This is a deliberate trade-off:\n * - Pro: lexicographic sortability lets bundle adapters list\n * newest-first without an extra index.\n * - Con: a casual observer can read the bundle's creation time\n * from the handle. They cannot read it from any OTHER field\n * (the header explicitly forbids `_exported_at`), and a\n * creation timestamp is the same kind of metadata that\n * filesystem mtime would already expose for a downloaded\n * bundle. The leak is therefore equivalent to what's already\n * visible from the file's mtime — not a new exposure.\n *\n * If a future use case needs timestamp-free handles, a v2 of the\n * format could specify \"use the random portion only\" without a\n * format break — `validatePodHeaderFields` only checks the regex\n * shape, not the encoded timestamp.\n */\n\n/**\n * Crockford base32 alphabet — omits I, L, O, U to avoid handwriting\n * and URL-encoding ambiguity. 32 characters covering 5 bits each.\n */\nconst CROCKFORD_ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\n/**\n * Encode a non-negative integer as a fixed-width Crockford base32\n * string. The width is fixed (not the natural log32 length) so\n * leading zeros are preserved — that's required for the timestamp\n * prefix to remain lexicographically sortable.\n *\n * Used twice: once for the 48-bit timestamp portion (10 chars) and\n * once for each 40-bit half of the randomness (8 chars × 2).\n */\nfunction encodeBase32(value: number, length: number): string {\n let out = ''\n let v = value\n for (let i = 0; i < length; i++) {\n out = CROCKFORD_ALPHABET[v % 32]! + out\n v = Math.floor(v / 32)\n }\n return out\n}\n\n/**\n * Generate a fresh ULID. Uses `crypto.getRandomValues` for the\n * randomness portion — same Web Crypto API the rest of the\n * codebase uses for IVs and salt.\n *\n * Returns a 26-character string. Calling twice in the same\n * millisecond produces two distinct ULIDs (the random portion\n * differs); ULIDs from the same millisecond are NOT guaranteed\n * to be monotonically ordered relative to each other, only\n * relative to ULIDs from a different millisecond. The bundle\n * format never relies on intra-millisecond ordering.\n */\nexport function generateULID(): string {\n const now = Date.now()\n\n // 48-bit timestamp → 10 Crockford base32 characters.\n // JavaScript's max safe integer is 2^53 - 1; Date.now() is well\n // within that range until the year ~285,000 AD. Splitting into\n // high and low 24-bit halves keeps every intermediate value\n // inside the safe-integer range and avoids any ambiguity in the\n // base32 encoder above.\n const timestampHigh = Math.floor(now / 0x1000000) // top 24 bits\n const timestampLow = now & 0xffffff // bottom 24 bits\n const tsPart =\n encodeBase32(timestampHigh, 5) + encodeBase32(timestampLow, 5)\n\n // 80-bit randomness → 16 Crockford base32 characters. Split into\n // two 40-bit halves so each fits in JavaScript's safe-integer\n // range (53 bits) and the base32 encoder doesn't have to deal\n // with bigints.\n const randBytes = new Uint8Array(10)\n crypto.getRandomValues(randBytes)\n\n // First 5 bytes (40 bits) → 8 Crockford base32 characters.\n // Reconstruct the 40-bit integer from bytes in big-endian order.\n // Multiplication by 2^32 (instead of bit-shift) avoids JavaScript's\n // 32-bit integer cast on the high byte.\n const rand1 =\n randBytes[0]! * 2 ** 32 +\n (randBytes[1]! << 24 >>> 0) +\n (randBytes[2]! << 16) +\n (randBytes[3]! << 8) +\n randBytes[4]!\n // Same for the second 5 bytes.\n const rand2 =\n randBytes[5]! * 2 ** 32 +\n (randBytes[6]! << 24 >>> 0) +\n (randBytes[7]! << 16) +\n (randBytes[8]! << 8) +\n randBytes[9]!\n const randPart = encodeBase32(rand1, 8) + encodeBase32(rand2, 8)\n\n return tsPart + randPart\n}\n\n/**\n * Validate that a string is a syntactically well-formed ULID. Used\n * by the bundle header validator. Does NOT verify that the\n * timestamp portion decodes to a sensible date — the format only\n * cares about the encoding shape.\n */\nexport function isULID(value: string): boolean {\n return /^[0-9A-HJKMNP-TV-Z]{26}$/.test(value)\n}\n"],"mappings":";AAiDA,IAAM,qBAAqB;AAW3B,SAAS,aAAa,OAAe,QAAwB;AAC3D,MAAI,MAAM;AACV,MAAI,IAAI;AACR,WAAS,IAAI,GAAG,IAAI,QAAQ,KAAK;AAC/B,UAAM,mBAAmB,IAAI,EAAE,IAAK;AACpC,QAAI,KAAK,MAAM,IAAI,EAAE;AAAA,EACvB;AACA,SAAO;AACT;AAcO,SAAS,eAAuB;AACrC,QAAM,MAAM,KAAK,IAAI;AAQrB,QAAM,gBAAgB,KAAK,MAAM,MAAM,QAAS;AAChD,QAAM,eAAe,MAAM;AAC3B,QAAM,SACJ,aAAa,eAAe,CAAC,IAAI,aAAa,cAAc,CAAC;AAM/D,QAAM,YAAY,IAAI,WAAW,EAAE;AACnC,SAAO,gBAAgB,SAAS;AAMhC,QAAM,QACJ,UAAU,CAAC,IAAK,KAAK,MACpB,UAAU,CAAC,KAAM,OAAO,MACxB,UAAU,CAAC,KAAM,OACjB,UAAU,CAAC,KAAM,KAClB,UAAU,CAAC;AAEb,QAAM,QACJ,UAAU,CAAC,IAAK,KAAK,MACpB,UAAU,CAAC,KAAM,OAAO,MACxB,UAAU,CAAC,KAAM,OACjB,UAAU,CAAC,KAAM,KAClB,UAAU,CAAC;AACb,QAAM,WAAW,aAAa,OAAO,CAAC,IAAI,aAAa,OAAO,CAAC;AAE/D,SAAO,SAAS;AAClB;AAQO,SAAS,OAAO,OAAwB;AAC7C,SAAO,2BAA2B,KAAK,KAAK;AAC9C;","names":[]}
|
|
@@ -1,32 +1,33 @@
|
|
|
1
1
|
import {
|
|
2
2
|
SyncScheduler
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-T7IR4N2S.js";
|
|
4
4
|
import {
|
|
5
5
|
PERIODS_COLLECTION,
|
|
6
6
|
PERIOD_ARCHIVES_COLLECTION,
|
|
7
7
|
PERIOD_FREEZES_COLLECTION,
|
|
8
8
|
PERIOD_TARGET_PURGES_COLLECTION,
|
|
9
9
|
periodExclusiveUpperBound
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-A4TOGAUW.js";
|
|
11
11
|
import {
|
|
12
12
|
envelopeBodySize
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-OHOKBMTM.js";
|
|
14
14
|
import {
|
|
15
|
+
buildRecordEnvelope,
|
|
15
16
|
isDeleteMarker,
|
|
16
17
|
isTombstoneShape
|
|
17
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-PENPHA45.js";
|
|
18
19
|
import {
|
|
19
20
|
decrypt,
|
|
20
21
|
derivePresenceKey,
|
|
21
22
|
encrypt
|
|
22
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-AU3AUJIZ.js";
|
|
23
24
|
import {
|
|
24
25
|
NOYDB_SYNC_VERSION
|
|
25
|
-
} from "./chunk-
|
|
26
|
+
} from "./chunk-IGNJOJEP.js";
|
|
26
27
|
import {
|
|
27
28
|
ValidationError,
|
|
28
29
|
isConflictError
|
|
29
|
-
} from "./chunk-
|
|
30
|
+
} from "./chunk-CWM4GQD2.js";
|
|
30
31
|
|
|
31
32
|
// src/with-sync/presence.ts
|
|
32
33
|
var subtle = globalThis.crypto.subtle;
|
|
@@ -233,13 +234,10 @@ var PresenceHandle = class {
|
|
|
233
234
|
const record = { lastSeen: now, iv, data };
|
|
234
235
|
const json = JSON.stringify(record);
|
|
235
236
|
const storeAdapter = this.syncAdapter ?? this.adapter;
|
|
236
|
-
const envelope =
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
_iv: "",
|
|
241
|
-
_data: json
|
|
242
|
-
};
|
|
237
|
+
const envelope = buildRecordEnvelope(
|
|
238
|
+
{ collection: this.storageCollection, id: recordId, version: 1 },
|
|
239
|
+
{ ts: now, iv: "", data: json }
|
|
240
|
+
);
|
|
243
241
|
try {
|
|
244
242
|
await storeAdapter.put(
|
|
245
243
|
this.vault,
|
|
@@ -337,6 +335,7 @@ function buildPeriodScope(option, records) {
|
|
|
337
335
|
|
|
338
336
|
// src/with-sync/engine.ts
|
|
339
337
|
var SyncEngine = class {
|
|
338
|
+
mergeAuthority;
|
|
340
339
|
local;
|
|
341
340
|
remote;
|
|
342
341
|
strategy;
|
|
@@ -349,8 +348,17 @@ var SyncEngine = class {
|
|
|
349
348
|
* into the scheduler below. */
|
|
350
349
|
policy;
|
|
351
350
|
dirty = [];
|
|
351
|
+
/** #1036 — last SUCCESSFUL push/pull. Never advanced by a failed attempt. */
|
|
352
352
|
lastPush = null;
|
|
353
353
|
lastPull = null;
|
|
354
|
+
/**
|
|
355
|
+
* #1036 — the failure that ended the most recent attempt, cleared by the next
|
|
356
|
+
* success. Live state only: deliberately NOT persisted in `_sync/meta`, since a
|
|
357
|
+
* reload cannot know whether the target is still failing. It exists so a poller
|
|
358
|
+
* can separate "never synced" (both null) from "synced a while ago, failing
|
|
359
|
+
* since" (`lastPush` set, `lastError` set).
|
|
360
|
+
*/
|
|
361
|
+
lastError = null;
|
|
354
362
|
loaded = false;
|
|
355
363
|
autoSyncInterval = null;
|
|
356
364
|
isOnline = true;
|
|
@@ -424,6 +432,7 @@ var SyncEngine = class {
|
|
|
424
432
|
this.role = opts.role ?? "sync-peer";
|
|
425
433
|
this.label = opts.label;
|
|
426
434
|
this.policy = opts.syncPolicy;
|
|
435
|
+
this.mergeAuthority = opts.mergeAuthority;
|
|
427
436
|
const policy = opts.syncPolicy;
|
|
428
437
|
if (policy && (policy.push.mode !== "manual" || policy.pull.mode !== "manual")) {
|
|
429
438
|
this.scheduler = new SyncScheduler(policy, {
|
|
@@ -586,7 +595,7 @@ var SyncEngine = class {
|
|
|
586
595
|
);
|
|
587
596
|
conflicts.push(conflict);
|
|
588
597
|
if (handled === "local") {
|
|
589
|
-
const winner = this.advancePastRemote(conflict.local, remoteEnvelope);
|
|
598
|
+
const winner = await this.advancePastRemote(conflict.local, entry.collection, entry.id, remoteEnvelope);
|
|
590
599
|
await this.remote.put(this.vault, entry.collection, entry.id, winner);
|
|
591
600
|
if (winner !== conflict.local) await this.applyRemote(entry.collection, entry.id, winner);
|
|
592
601
|
completed.push(i);
|
|
@@ -615,7 +624,7 @@ var SyncEngine = class {
|
|
|
615
624
|
for (const i of completed.sort((a, b) => b - a)) {
|
|
616
625
|
this.dirty.splice(i, 1);
|
|
617
626
|
}
|
|
618
|
-
this.
|
|
627
|
+
this.recordOutcome("push", errors);
|
|
619
628
|
try {
|
|
620
629
|
await this.persistMeta();
|
|
621
630
|
} finally {
|
|
@@ -787,7 +796,7 @@ var SyncEngine = class {
|
|
|
787
796
|
} catch (err) {
|
|
788
797
|
errors.push(err instanceof Error ? err : new Error(String(err)));
|
|
789
798
|
}
|
|
790
|
-
this.
|
|
799
|
+
this.recordOutcome("pull", errors);
|
|
791
800
|
try {
|
|
792
801
|
await this.persistMeta();
|
|
793
802
|
} finally {
|
|
@@ -873,7 +882,7 @@ var SyncEngine = class {
|
|
|
873
882
|
);
|
|
874
883
|
conflicts.push(conflict);
|
|
875
884
|
if (handled === "local") {
|
|
876
|
-
const winner = this.advancePastRemote(conflict.local, remoteEnvelope);
|
|
885
|
+
const winner = await this.advancePastRemote(conflict.local, entry.collection, entry.id, remoteEnvelope);
|
|
877
886
|
await this.remote.put(this.vault, entry.collection, entry.id, winner);
|
|
878
887
|
if (winner !== conflict.local) await this.applyRemote(entry.collection, entry.id, winner);
|
|
879
888
|
completed.push(i);
|
|
@@ -902,12 +911,33 @@ var SyncEngine = class {
|
|
|
902
911
|
for (const i of completed.sort((a, b) => b - a)) {
|
|
903
912
|
this.dirty.splice(i, 1);
|
|
904
913
|
}
|
|
905
|
-
this.
|
|
914
|
+
this.recordOutcome("push", errors);
|
|
906
915
|
await this.persistMeta();
|
|
907
916
|
const result = { pushed, conflicts, errors, erasures };
|
|
908
917
|
this.emitter.emit("sync:push", result);
|
|
909
918
|
return result;
|
|
910
919
|
}
|
|
920
|
+
/**
|
|
921
|
+
* #1036 — close out a push/pull. `push()` and `pull()` collect per-record
|
|
922
|
+
* failures into their result's `errors` rather than throwing, and the clock used
|
|
923
|
+
* to be stamped regardless — so an unreachable store still reported a fresh
|
|
924
|
+
* `lastPush`, and a UI rendered "Last synced: just now" over a sync that moved
|
|
925
|
+
* nothing. An attempt only advances the clock when it had no errors.
|
|
926
|
+
*
|
|
927
|
+
* An empty dirty log is a success, not a failure: nothing to send is not the
|
|
928
|
+
* same as failing to send, and treating it otherwise would leave a quiet vault
|
|
929
|
+
* looking permanently unsynced.
|
|
930
|
+
*/
|
|
931
|
+
recordOutcome(op, errors) {
|
|
932
|
+
const at = (/* @__PURE__ */ new Date()).toISOString();
|
|
933
|
+
if (errors.length > 0) {
|
|
934
|
+
this.lastError = { at, op, message: errors[0].message };
|
|
935
|
+
return;
|
|
936
|
+
}
|
|
937
|
+
this.lastError = null;
|
|
938
|
+
if (op === "push") this.lastPush = at;
|
|
939
|
+
else this.lastPull = at;
|
|
940
|
+
}
|
|
911
941
|
/** Get current sync status. */
|
|
912
942
|
status() {
|
|
913
943
|
const scheduled = this.scheduler?.status;
|
|
@@ -916,6 +946,7 @@ var SyncEngine = class {
|
|
|
916
946
|
lastPush: this.lastPush,
|
|
917
947
|
lastPull: this.lastPull,
|
|
918
948
|
online: this.isOnline,
|
|
949
|
+
...this.lastError ? { lastError: this.lastError } : {},
|
|
919
950
|
...scheduled && scheduled.readiness.size > 0 ? { readiness: scheduled.readiness, phase: scheduled.phase } : {}
|
|
920
951
|
};
|
|
921
952
|
}
|
|
@@ -967,16 +998,41 @@ var SyncEngine = class {
|
|
|
967
998
|
* the remote's (the same-`_v` push tie), re-stamp it at `remote._v + 1`.
|
|
968
999
|
* Without this the loser's next pull sees no delta (`_v`-based
|
|
969
1000
|
* detection) and the peers stay silently diverged at the same version.
|
|
970
|
-
*
|
|
971
|
-
*
|
|
972
|
-
*
|
|
973
|
-
*
|
|
974
|
-
*
|
|
1001
|
+
* ## Why this is async, and why it goes through `MergeAuthority` (#1093)
|
|
1002
|
+
*
|
|
1003
|
+
* It used to be `{ ...winner, _v: remote._v + 1 }` — a metadata restamp on
|
|
1004
|
+
* ciphertext the engine cannot decrypt. That spread was the SOLE reason `_v`
|
|
1005
|
+
* could not be bound into the AAD: a version rewritten onto a body sealed at
|
|
1006
|
+
* a different one produces a record no reader can open.
|
|
1007
|
+
*
|
|
1008
|
+
* `with-sync` is DEK-free by design and `check:architecture` enforces it, so
|
|
1009
|
+
* the re-seal cannot happen here. It happens in the injected authority, which
|
|
1010
|
+
* holds the keys. The engine still decides WHICH version to advance to; it
|
|
1011
|
+
* simply no longer pretends it can rewrite a sealed body.
|
|
1012
|
+
*
|
|
1013
|
+
* The authority is ALWAYS present in the product — `kernel/noydb.ts` builds
|
|
1014
|
+
* one from the keyring and passes it at both engine-construction sites, and
|
|
1015
|
+
* `with-sync/active.ts` is the only place an engine is constructed. The
|
|
1016
|
+
* fallback below is reachable only by constructing `SyncEngine` directly,
|
|
1017
|
+
* which tests do. It restamps, as before — and would produce an unreadable
|
|
1018
|
+
* record if such a test ever held AEAD-sealed envelopes. None do; the
|
|
1019
|
+
* fixtures that reach it build their own plaintext ones.
|
|
1020
|
+
*
|
|
1021
|
+
* The 'merged' branch needs none of this: resolver output is already stamped
|
|
1022
|
+
* `max(local, remote) + 1` by whoever built it.
|
|
975
1023
|
*/
|
|
976
|
-
advancePastRemote(winner, remote) {
|
|
977
|
-
|
|
1024
|
+
async advancePastRemote(winner, collection, id, remote) {
|
|
1025
|
+
if (winner._v > remote._v) return winner;
|
|
1026
|
+
const toVersion = remote._v + 1;
|
|
1027
|
+
if (!this.mergeAuthority) return { ...winner, _v: toVersion };
|
|
1028
|
+
return this.mergeAuthority.advance(collection, id, winner, toVersion);
|
|
978
1029
|
}
|
|
979
1030
|
async applyRemote(collection, id, envelope) {
|
|
1031
|
+
if (this.mergeAuthority && !await this.mergeAuthority.verify(collection, id, envelope)) {
|
|
1032
|
+
throw new ValidationError(
|
|
1033
|
+
`sync: refusing remote envelope for "${collection}/${id}" \u2014 it does not authenticate at the identity and version it claims. The local copy is unchanged.`
|
|
1034
|
+
);
|
|
1035
|
+
}
|
|
980
1036
|
await this.local.put(this.vault, collection, id, envelope);
|
|
981
1037
|
if (this.pullByteSink !== null) {
|
|
982
1038
|
this.pullByteSink.records++;
|
|
@@ -1086,13 +1142,10 @@ var SyncEngine = class {
|
|
|
1086
1142
|
last_pull: this.lastPull,
|
|
1087
1143
|
dirty: this.dirty
|
|
1088
1144
|
};
|
|
1089
|
-
const envelope =
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
_iv: "",
|
|
1094
|
-
_data: JSON.stringify(meta)
|
|
1095
|
-
};
|
|
1145
|
+
const envelope = buildRecordEnvelope(
|
|
1146
|
+
{ collection: "_sync", id: "meta", version: 1 },
|
|
1147
|
+
{ iv: "", data: JSON.stringify(meta) }
|
|
1148
|
+
);
|
|
1096
1149
|
await this.local.put(this.vault, "_sync", "meta", envelope);
|
|
1097
1150
|
}
|
|
1098
1151
|
};
|
|
@@ -1160,4 +1213,4 @@ export {
|
|
|
1160
1213
|
SyncEngine,
|
|
1161
1214
|
SyncTransaction
|
|
1162
1215
|
};
|
|
1163
|
-
//# sourceMappingURL=chunk-
|
|
1216
|
+
//# sourceMappingURL=chunk-4N5Q23KV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/with-sync/presence.ts","../src/with-sync/period-scope.ts","../src/with-sync/engine.ts","../src/with-sync/transaction.ts"],"sourcesContent":["/**\n * Presence handle — real-time awareness of who is viewing/editing a collection.\n * encrypted ephemeral channel keyed by collection DEK via HKDF.\n *\n * The presence key is derived from the collection DEK so:\n * - The adapter never learns user identities from presence payloads.\n * - Presence rotates automatically when the DEK rotates (revoked users\n * can no longer participate after a DEK rotation).\n *\n * Two transport strategies:\n * 1. **Pub/sub** (real-time): used when the adapter implements\n * `presencePublish` and `presenceSubscribe`.\n * 2. **Storage-poll** (fallback): presence records are written to a\n * reserved `_presence_<collection>` collection on the sync adapter\n * (if available) or local adapter, and polled periodically.\n */\n\nimport { buildRecordEnvelope } from '../kernel/enclave/index.js'\nimport type { NoydbStore, PresencePeer } from '../kernel/types.js'\nimport { encrypt, decrypt, derivePresenceKey, type EnclaveKey } from '../kernel/enclave/index.js'\n\nconst subtle = globalThis.crypto.subtle\n\n/**\n * HKDF salt domain for the presence-tag key — the adapter-opaque record-id\n * tag used by the storage-poll fallback. Domain-separated from the presence\n * PAYLOAD key (`'noydb-presence'`, in `derivePresenceKey`) so the tag key\n * and the payload encryption key are cryptographically independent even\n * though both derive from the same collection DEK.\n */\nconst PRESENCE_TAG_KEY_DOMAIN = 'noydb.presence.tag.v1'\n\n/** Options for constructing a PresenceHandle. @internal */\nexport interface PresenceHandleOpts {\n /** Local adapter for storage-poll fallback. */\n adapter: NoydbStore\n /** Remote (sync) adapter — preferred for broadcasting presence if available. */\n syncAdapter?: NoydbStore\n /** Vault name — used as part of the channel and storage key. */\n vault: string\n /** Collection name — used as HKDF `info` and channel suffix. */\n collectionName: string\n /**\n * Calling user's ID. In encrypted mode it is encrypted inside the\n * storage-poll record's `data` field — the record id is an\n * adapter-opaque HMAC tag, not the userId, so the adapter never learns\n * peer identities. Unencrypted vaults have no key to tag or encrypt\n * with, so the userId is used as the record id in cleartext (dev posture\n * only — identity privacy requires encryption).\n */\n userId: string\n /** Whether encryption is active. When false, presence payloads are stored as JSON. */\n encrypted: boolean\n /** Callback that resolves the collection DEK (used to derive the presence key). */\n getDEK: (collectionName: string) => Promise<EnclaveKey>\n /** How long (ms) before a peer's presence is considered stale. Default: 30_000. */\n staleMs?: number\n /** Poll interval (ms) for the storage-poll fallback. Default: 5_000. */\n pollIntervalMs?: number\n}\n\n/**\n * Internal storage envelope for the storage-poll fallback.\n * Written to `_presence_<collection>` as `{ lastSeen, iv, data }`.\n *\n * In encrypted mode `data` is ciphertext of `{ userId, payload }` — the\n * userId rides inside the encrypted payload, never as a top-level field, and\n * the record's storage id is a separate HMAC tag (see `presenceTag`), not\n * the userId. In unencrypted mode `data` is `JSON.stringify(payload)` and\n * the record id IS the (cleartext) userId — there is no key to tag with.\n */\ninterface StoragePresenceRecord {\n lastSeen: string\n iv: string // base64 AES-GCM IV (empty when not encrypted)\n data: string // base64 ciphertext or JSON string when not encrypted\n}\n\n/** Presence handle for a single collection. */\nexport class PresenceHandle<P> {\n private readonly adapter: NoydbStore\n private readonly syncAdapter: NoydbStore | undefined\n private readonly vault: string\n private readonly collectionName: string\n private readonly userId: string\n private readonly encrypted: boolean\n private readonly getDEK: (collectionName: string) => Promise<EnclaveKey>\n private readonly staleMs: number\n private readonly pollIntervalMs: number\n private readonly channel: string\n private readonly storageCollection: string\n\n private presenceKey: EnclaveKey | null = null\n private presenceTagKey: EnclaveKey | null = null\n private subscribers: Array<(peers: PresencePeer<P>[]) => void> = []\n private unsubscribePubSub: (() => void) | null = null\n private pollTimer: ReturnType<typeof setInterval> | null = null\n private stopped = false\n\n constructor(opts: PresenceHandleOpts) {\n this.adapter = opts.adapter\n this.syncAdapter = opts.syncAdapter\n this.vault = opts.vault\n this.collectionName = opts.collectionName\n this.userId = opts.userId\n this.encrypted = opts.encrypted\n this.getDEK = opts.getDEK\n this.staleMs = opts.staleMs ?? 30_000\n this.pollIntervalMs = opts.pollIntervalMs ?? 5_000\n // Channel used by pub/sub adapters — vault-scoped so two collections\n // in the same vault don't bleed into each other's presence channels.\n this.channel = `${opts.vault}:${opts.collectionName}:presence`\n // Reserved collection name for the storage-poll fallback.\n this.storageCollection = `_presence_${opts.collectionName}`\n }\n\n /**\n * Announce yourself (or update your cursor/status).\n * Encrypts `payload` with the presence key and publishes it.\n */\n async update(payload: P): Promise<void> {\n if (this.stopped) return\n\n const key = await this.getPresenceKey()\n const now = new Date().toISOString()\n const plaintext = JSON.stringify({ userId: this.userId, lastSeen: now, payload })\n let encryptedPayload: string\n\n if (this.encrypted && key) {\n const { iv, data } = await encrypt(plaintext, key)\n encryptedPayload = JSON.stringify({ iv, data })\n } else {\n encryptedPayload = plaintext\n }\n\n // Pub/sub path — publish to any adapter that supports it\n const pubAdapter = this.getPubSubAdapter()\n if (pubAdapter?.presencePublish) {\n await pubAdapter.presencePublish(this.channel, encryptedPayload)\n }\n\n // Storage-poll path — write a record to the storage adapter\n await this.writeStorageRecord(payload, now)\n }\n\n /**\n * Subscribe to presence updates. The callback receives a filtered, decrypted\n * list of all currently-active peers (excluding yourself, excluding stale).\n *\n * Returns an unsubscribe function. Also call `stop()` to release all resources.\n */\n subscribe(cb: (peers: PresencePeer<P>[]) => void): () => void {\n if (this.stopped) return () => {}\n\n this.subscribers.push(cb)\n\n // Start pub/sub listener on first subscriber\n if (this.subscribers.length === 1) {\n this.startListening()\n }\n\n return () => {\n this.subscribers = this.subscribers.filter(s => s !== cb)\n if (this.subscribers.length === 0) this.stopListening()\n }\n }\n\n /** Stop all listening and clear resources. */\n stop(): void {\n this.stopped = true\n this.stopListening()\n this.subscribers = []\n }\n\n // ─── Private ────────────────────────────────────────────────────────\n\n private async getPresenceKey(): Promise<EnclaveKey | null> {\n if (!this.encrypted) return null\n if (!this.presenceKey) {\n try {\n const dek = await this.getDEK(this.collectionName)\n this.presenceKey = await derivePresenceKey(dek, this.collectionName)\n } catch {\n // no-op — presence degrades gracefully if crypto fails\n }\n }\n return this.presenceKey\n }\n\n /**\n * Derive (and cache) the presence-tag key — a non-extractable, sign-only\n * HMAC-SHA256 key HKDF-derived from the collection DEK, domain-separated\n * from the presence payload key by {@link PRESENCE_TAG_KEY_DOMAIN}.\n * Mirrors `deriveClassifyIndexKey` (kernel/enclave/classify/bidx.ts). No\n * PBKDF2 stretch — the adapter never holds this key, so a plain keyed HMAC\n * tag is sufficient and deterministic. Returns `null` when unencrypted\n * (no DEK to derive from).\n */\n private async getPresenceTagKey(): Promise<EnclaveKey | null> {\n if (!this.encrypted) return null\n if (!this.presenceTagKey) {\n try {\n const dek = await this.getDEK(this.collectionName)\n const rawDek = await subtle.exportKey('raw', dek)\n const hkdfKey = await subtle.importKey('raw', rawDek, 'HKDF', false, ['deriveBits'])\n const salt = new TextEncoder().encode(PRESENCE_TAG_KEY_DOMAIN)\n const info = new TextEncoder().encode(this.collectionName)\n const bits = await subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt, info }, hkdfKey, 256)\n this.presenceTagKey = await subtle.importKey('raw', bits, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])\n } catch {\n // no-op — presence degrades gracefully if crypto fails\n }\n }\n return this.presenceTagKey\n }\n\n /**\n * Deterministic, adapter-opaque tag for `userId` — used as the\n * storage-poll record id in encrypted mode so the adapter never sees the\n * userId. Falls back to the raw `userId` when unencrypted (no key exists\n * to tag with — see {@link PresenceHandleOpts.userId}).\n *\n * Signs directly via `subtle.sign` (like `bidx.ts`'s `mintAt`) rather than\n * the barrel's `hmacSha256Hex` helper: that helper re-exports its key\n * argument's raw bytes internally, which only works for extractable keys\n * (e.g. an AES-GCM DEK) — `presenceTagKey` is deliberately non-extractable.\n */\n private async presenceTag(userId: string): Promise<string> {\n const tagKey = await this.getPresenceTagKey()\n if (!tagKey) return userId\n const mac = await subtle.sign('HMAC', tagKey, new TextEncoder().encode(userId) as BufferSource)\n return Array.from(new Uint8Array(mac)).map((b) => b.toString(16).padStart(2, '0')).join('')\n }\n\n private getPubSubAdapter(): NoydbStore | undefined {\n // Prefer the sync adapter (it broadcasts to other devices)\n if (this.syncAdapter?.presencePublish) return this.syncAdapter\n if (this.adapter.presencePublish) return this.adapter\n return undefined\n }\n\n private startListening(): void {\n const pubAdapter = this.getPubSubAdapter()\n\n if (pubAdapter?.presenceSubscribe) {\n // Real-time pub/sub path\n this.unsubscribePubSub = pubAdapter.presenceSubscribe(\n this.channel,\n (encryptedPayload) => { void this.handlePubSubMessage(encryptedPayload) },\n )\n } else {\n // Storage-poll fallback\n this.pollTimer = setInterval(\n () => { void this.pollStoragePresence() },\n this.pollIntervalMs,\n )\n // Kick off an immediate poll\n void this.pollStoragePresence()\n }\n }\n\n private stopListening(): void {\n if (this.unsubscribePubSub) {\n this.unsubscribePubSub()\n this.unsubscribePubSub = null\n }\n if (this.pollTimer) {\n clearInterval(this.pollTimer)\n this.pollTimer = null\n }\n }\n\n private async handlePubSubMessage(encryptedPayload: string): Promise<void> {\n try {\n const peer = await this.decryptPresencePayload(encryptedPayload)\n if (!peer || peer.userId === this.userId) return\n\n const cutoff = new Date(Date.now() - this.staleMs).toISOString()\n if (peer.lastSeen < cutoff) return\n\n // Deliver only this new peer to subscribers; a full snapshot poll follows\n // on next interval. For pub/sub, we could maintain a map of active peers,\n // but for simplicity: emit a snapshot read from storage.\n await this.pollStoragePresence()\n } catch {\n // Decrypt failure — stale key or tampered payload, ignore\n }\n }\n\n private async decryptPresencePayload(\n encryptedPayload: string,\n ): Promise<{ userId: string; lastSeen: string; payload: P } | null> {\n const key = await this.getPresenceKey()\n\n if (!this.encrypted || !key) {\n return JSON.parse(encryptedPayload) as { userId: string; lastSeen: string; payload: P }\n }\n\n const { iv: ivB64, data } = JSON.parse(encryptedPayload) as { iv: string; data: string }\n const plaintext = await decrypt(ivB64, data, key)\n return JSON.parse(plaintext) as { userId: string; lastSeen: string; payload: P }\n }\n\n private async writeStorageRecord(payload: P, now: string): Promise<void> {\n const key = await this.getPresenceKey()\n let iv = ''\n let data: string\n let recordId: string\n\n if (this.encrypted && key) {\n // userId rides INSIDE the ciphertext, like the pub/sub path — the\n // adapter never sees it. The record id is a separate deterministic\n // tag, also opaque to the adapter.\n const plaintext = JSON.stringify({ userId: this.userId, payload })\n const result = await encrypt(plaintext, key)\n iv = result.iv\n data = result.data\n recordId = await this.presenceTag(this.userId)\n } else {\n // Unencrypted vault — no key exists to tag or encrypt with.\n data = JSON.stringify(payload)\n recordId = this.userId\n }\n\n const record: StoragePresenceRecord = { lastSeen: now, iv, data }\n const json = JSON.stringify(record)\n\n // Use the sync adapter if available (so other devices can read it);\n // fall back to local adapter.\n const storeAdapter = this.syncAdapter ?? this.adapter\n const envelope = buildRecordEnvelope(\n { collection: this.storageCollection, id: recordId, version: 1 },\n { ts: now, iv: '', data: json },\n )\n try {\n await storeAdapter.put(\n this.vault,\n this.storageCollection,\n recordId,\n envelope,\n )\n } catch {\n // Presence write failure is non-fatal — the user is still present locally\n }\n }\n\n private async pollStoragePresence(): Promise<void> {\n if (this.stopped || this.subscribers.length === 0) return\n\n try {\n const key = await this.getPresenceKey()\n const storeAdapter = this.syncAdapter ?? this.adapter\n const ids = await storeAdapter.list(this.vault, this.storageCollection)\n const cutoff = new Date(Date.now() - this.staleMs).toISOString()\n const peers: PresencePeer<P>[] = []\n const myTag = await this.presenceTag(this.userId)\n\n for (const id of ids) {\n if (id === myTag) continue // skip ourselves\n const envelope = await storeAdapter.get(this.vault, this.storageCollection, id)\n if (!envelope) continue\n\n try {\n const record = JSON.parse(envelope._data) as StoragePresenceRecord\n if (record.lastSeen < cutoff) continue\n\n let peerUserId: string\n let peerPayload: P\n if (this.encrypted && key && record.iv) {\n const plaintext = await decrypt(record.iv, record.data, key)\n const decoded = JSON.parse(plaintext) as { userId: string; payload: P }\n peerUserId = decoded.userId\n peerPayload = decoded.payload\n } else {\n // Unencrypted mode: the record id IS the userId (see writeStorageRecord).\n peerUserId = id\n peerPayload = JSON.parse(record.data) as P\n }\n\n peers.push({ userId: peerUserId, payload: peerPayload, lastSeen: record.lastSeen })\n } catch {\n // One bad record (e.g. a pre-fix record that fails to decrypt\n // under a new reader) shouldn't blank the whole snapshot — skip\n // just this record.\n continue\n }\n }\n\n for (const cb of this.subscribers) {\n cb(peers)\n }\n } catch {\n // Poll failure is non-fatal\n }\n }\n}\n","/**\n * #807 — period-scoped pull support for the `SyncEngine` (thin-client\n * bootstrap: first sync pulls the current period + the period summaries;\n * historical periods backfill on demand via `pull({ periods: ['<name>'] })`).\n *\n * ## Membership law\n *\n * The engine only ever sees ciphertext envelopes, so period membership at\n * the sync tier is by write-time `_ts` against the closed periods' windows\n * (`periodExclusiveUpperBound`) — the SAME store-tier law freeze (#604) and\n * archive (#613) use, NOT the business-date (`dateField`) seal the write\n * guard applies inside the trust boundary. A late-booked record (in-period\n * business date, current write-time) therefore syncs with the current\n * period — mirroring how it archives at the NEXT period's archive.\n *\n * Closed periods partition the timeline by their exclusive upper bounds:\n * the earliest closed period's window is unbounded below (a close seals\n * everything at-or-before its `endDate`), each later one starts at its\n * predecessor's bound, and the CURRENT window is everything at-or-after\n * the latest closed bound (everything, when no period was ever closed).\n *\n * ## What a period filter can never drop\n *\n * - **Period summaries** (`_periods` + freeze/archive/target-purge\n * companions) — the navigation index; always pulled in full, exempt from\n * every filter (`collections`, `periods`, `modifiedSince`).\n * - **Delete markers and tombstones** — an erasure or delete must never be\n * skipped by partial sync (the #589/#590 law, mirroring the\n * `modifiedSince` exemption). This is what makes a device that never\n * pulled period P converge instead of resurrecting P's deleted records\n * when it later backfills.\n * - **Reserved lookups** (`_dict_*`/`_lookup_*`) — vocabulary/config rows\n * are not period-partitioned data; their explicit pull loop is exempt.\n *\n * Push is NEVER period-filtered — `PushOptions` has no `periods` member at\n * all; a thin client's writes always flow up in full.\n */\nimport type { EncryptedEnvelope } from '../kernel/types.js'\nimport { ValidationError } from '../kernel/errors.js'\nimport { isTombstoneShape, isDeleteMarker } from '../kernel/enclave/index.js'\nimport {\n PERIODS_COLLECTION,\n PERIOD_FREEZES_COLLECTION,\n PERIOD_ARCHIVES_COLLECTION,\n PERIOD_TARGET_PURGES_COLLECTION,\n periodExclusiveUpperBound,\n} from '../with-audit/periods/window.js'\n\nexport { PERIODS_COLLECTION }\n\n/**\n * The reserved period-metadata collections a period-scoped pull always\n * fetches first (phase 1, \"summaries\"): the hash-chained `_periods` index\n * plus its freeze/archive/target-purge companions.\n */\nexport const PERIOD_SUMMARY_COLLECTIONS: readonly string[] = [\n PERIODS_COLLECTION,\n PERIOD_FREEZES_COLLECTION,\n PERIOD_ARCHIVES_COLLECTION,\n PERIOD_TARGET_PURGES_COLLECTION,\n]\n\n/** The subset of a decrypted `PeriodRecord` the window computation needs. */\nexport interface PeriodSyncRecord {\n readonly name: string\n readonly kind: 'closed' | 'opened'\n readonly endDate: string\n}\n\n/**\n * Vault-injected source of decrypted period records, wired via\n * `SyncEngine.setPeriodPullSource` (same injection pattern as\n * `setReservedLookupSource`). MUST re-read from the local store on every\n * call — the engine invokes it right after the summaries phase applied\n * freshly pulled `_periods` envelopes.\n */\nexport interface PeriodPullSource {\n periods(): Promise<readonly PeriodSyncRecord[]>\n}\n\nconst SHAPE_MSG =\n 'pull: `periods` must be an array of closed-period names, or `{ current: true }`.'\n\n/** Validate the raw `PullOptions.periods` value (runtime shape only). */\nexport function validatePeriodsOption(\n periods: unknown,\n): asserts periods is readonly string[] | { readonly current: true } {\n if (Array.isArray(periods)) {\n for (const p of periods) {\n if (typeof p !== 'string' || p.length === 0) throw new ValidationError(SHAPE_MSG)\n }\n return\n }\n if (\n typeof periods === 'object' && periods !== null &&\n (periods as { current?: unknown }).current === true &&\n Object.keys(periods).length === 1\n ) {\n return\n }\n throw new ValidationError(SHAPE_MSG)\n}\n\n/**\n * Resolve the selected `_ts` windows and return the pull-scope predicate:\n * `true` = the envelope is in scope for this pull. Tombstones and delete\n * markers are unconditionally in scope (see module doc).\n *\n * Throws `ValidationError` for a name that is not a closed period in the\n * (freshly synced) `_periods` index — a typo'd backfill must fail loudly,\n * never silently pull nothing.\n */\nexport function buildPeriodScope(\n option: readonly string[] | { readonly current: true },\n records: readonly PeriodSyncRecord[],\n): (envelope: EncryptedEnvelope) => boolean {\n const closed = records\n .filter((r) => r.kind === 'closed')\n .map((r) => ({ name: r.name, bound: periodExclusiveUpperBound(r.endDate) }))\n .sort((a, b) => a.bound.localeCompare(b.bound))\n\n let windows: ReadonlyArray<{ lower: string | null; upper: string | null }>\n if (Array.isArray(option)) {\n windows = (option as readonly string[]).map((name) => {\n const idx = closed.findIndex((c) => c.name === name)\n if (idx < 0) {\n const other = records.find((r) => r.name === name)\n throw new ValidationError(\n other\n ? `pull: period \"${name}\" is \"${other.kind}\" — only closed periods have a backfill window; use \\`{ current: true }\\` for the open period.`\n : `pull: no closed period named \"${name}\" in this vault's _periods index.`,\n )\n }\n return { lower: idx > 0 ? closed[idx - 1]!.bound : null, upper: closed[idx]!.bound }\n })\n } else {\n // { current: true } — everything at-or-after the latest closed bound\n // (everything, when no period was ever closed: with no closed periods\n // there is nothing historical to exclude, so nothing is silently dropped).\n windows = [{ lower: closed.length > 0 ? closed[closed.length - 1]!.bound : null, upper: null }]\n }\n\n return (envelope: EncryptedEnvelope): boolean => {\n if (isTombstoneShape(envelope) || isDeleteMarker(envelope)) return true\n return windows.some(\n (w) =>\n (w.lower === null || envelope._ts >= w.lower) &&\n (w.upper === null || envelope._ts < w.upper),\n )\n }\n}\n","import { buildRecordEnvelope } from '../kernel/enclave/index.js'\nimport type {\n NoydbStore,\n DirtyEntry,\n Conflict,\n ConflictStrategy,\n CollectionConflictResolver,\n PushOptions,\n PullOptions,\n PushResult,\n PullResult,\n SyncStatus,\n EncryptedEnvelope,\n SyncMetadata,\n SyncTargetRole,\n ErasureEnforcement,\n} from '../kernel/types.js'\nimport { NOYDB_SYNC_VERSION } from '../kernel/types.js'\nimport { isConflictError, ValidationError } from '../kernel/errors.js'\nimport type { MergeAuthority } from '../port/with/merge-authority.js'\nimport {\n PERIOD_SUMMARY_COLLECTIONS,\n PERIODS_COLLECTION,\n buildPeriodScope,\n validatePeriodsOption,\n type PeriodPullSource,\n} from './period-scope.js'\nimport type { NoydbEventEmitter } from '../kernel/events.js'\nimport type { SyncPolicy } from '../kernel/sync-policy.js'\nimport { SyncScheduler } from '../kernel/sync-policy.js'\nimport { isTombstoneShape, isDeleteMarker, envelopeBodySize } from '../kernel/enclave/index.js'\n\n/** #650 Task 4 (#647) — the declared reserved-lookup (`_dict_*`/`_lookup_*`) collection-name\n * registry a `SyncEngine` enumerates on pull. Explicit, not a blanket underscore-glob — other\n * `_`-prefixed namespaces keep their `loadAll`-skip semantics untouched. */\nexport interface ReservedLookupSource {\n /** Declared reserved-lookup collection names to enumerate on pull. */\n collections(): readonly string[]\n}\n\n/** Sync engine: dirty tracking, push, pull, conflict resolution, scheduling. */\nexport class SyncEngine {\n private readonly mergeAuthority: MergeAuthority | undefined\n private readonly local: NoydbStore\n private readonly remote: NoydbStore\n private readonly strategy: ConflictStrategy\n private readonly emitter: NoydbEventEmitter\n private readonly vault: string\n readonly role: SyncTargetRole\n readonly label: string | undefined\n /** #948: the resolved policy this engine was constructed with, retained for\n * introspection (`Noydb.listSyncTargets()`) — otherwise lost once consumed\n * into the scheduler below. */\n readonly policy: SyncPolicy | undefined\n\n private dirty: DirtyEntry[] = []\n /** #1036 — last SUCCESSFUL push/pull. Never advanced by a failed attempt. */\n private lastPush: string | null = null\n private lastPull: string | null = null\n /**\n * #1036 — the failure that ended the most recent attempt, cleared by the next\n * success. Live state only: deliberately NOT persisted in `_sync/meta`, since a\n * reload cannot know whether the target is still failing. It exists so a poller\n * can separate \"never synced\" (both null) from \"synced a while ago, failing\n * since\" (`lastPush` set, `lastError` set).\n */\n private lastError: { readonly at: string; readonly op: 'push' | 'pull'; readonly message: string } | null = null\n private loaded = false\n private autoSyncInterval: ReturnType<typeof setInterval> | null = null\n private isOnline = true\n\n /** Sync scheduler. Manages push/pull timing. */\n readonly scheduler: SyncScheduler | null\n\n /** Per-collection conflict resolvers registered by Collection instances. */\n private readonly conflictResolvers = new Map<string, CollectionConflictResolver>()\n\n /**\n * Expands a collection-name filter to include its satellite pair partner(s)\n * (spec #591 convergence rule 5b) — wired from vault satellite declaration\n * via `setPairExpander`. `undefined` when no satellite has ever been\n * declared for this vault: identity behavior, zero change for non-satellite\n * users.\n */\n private pairExpander?: (names: readonly string[]) => readonly string[]\n\n /** #598: refreshes Collection in-memory views after a sync-applied local write. Wired by the\n * vault at open. `action` (#640): `'delete'` for a pulled tombstone/delete-marker, `'put'`\n * otherwise — classified at `applyRemote`, the one choke point that holds the envelope. */\n private cacheInvalidator?: (collection: string, id: string, action: 'put' | 'delete') => Promise<void>\n\n /** Wire the Collection-cache invalidation hook (#598). Same injection pattern as `setPairExpander`. */\n setCacheInvalidator(fn: (collection: string, id: string, action: 'put' | 'delete') => Promise<void>): void {\n this.cacheInvalidator = fn\n }\n\n /** #638 Task 4: opens/flushes the vault's graph-dispatch touch batch around a whole `pull()`/\n * `push()` call, so N `applyRemote`d records feeding the same derivation/rollup/MV target\n * recompute once. Wired by the vault at open, mirroring `cacheInvalidator`. */\n private graphBatchController?: { begin(): void; flush(): Promise<void> }\n\n /** Wire the graph-dispatch batch controller (#638 Task 4). Same injection pattern as `setCacheInvalidator`. */\n setGraphBatchController(controller: { begin(): void; flush(): Promise<void> }): void {\n this.graphBatchController = controller\n }\n\n /** #650 Task 4 (#647): declared reserved-lookup collections `pull()` enumerates explicitly (the\n * store's `list()` does not skip `_`-prefixed names, unlike `loadAll()`). Wired by the vault at\n * open, same injection pattern as `setCacheInvalidator`/`setGraphBatchController`. */\n private reservedLookup?: ReservedLookupSource\n\n /** Wire the reserved-lookup source (#650 Task 4). */\n setReservedLookupSource(source: ReservedLookupSource): void {\n this.reservedLookup = source\n }\n\n /** #653: expands a (pair-expanded) collection-name filter to include the reserved `_dict_*`\n * collections those names depend on via their lookup fields — mirrors `pairExpander` so a\n * partial `push`/`pull({collections:[...]})` never drops the dictionary a named collection's\n * labels/membership rely on. Wired unconditionally from the vault's `dictKeyFieldRegistry` via\n * `setReservedDictExpander` (returns `[]` when the vault has no dict-backed collections); only\n * `undefined` on a standalone engine that was never vault-attached. */\n private reservedDictExpander?: (names: readonly string[]) => readonly string[]\n\n /** Wire the reserved-dict expansion function (#653). Same injection pattern as `setPairExpander`. */\n setReservedDictExpander(expander: (names: readonly string[]) => readonly string[]): void {\n this.reservedDictExpander = expander\n }\n\n /** #807: vault-injected source of decrypted period records — resolves the `_ts` windows a\n * `pull({ periods })` scopes to. Re-read AFTER the summaries phase, so a fresh device's\n * freshly pulled `_periods` index is what the windows are computed from. `undefined` on a\n * standalone engine that was never vault-attached (period-scoped pull then throws). */\n private periodPullSource?: PeriodPullSource\n\n /** Wire the period-window source (#807). Same injection pattern as `setReservedLookupSource`. */\n setPeriodPullSource(source: PeriodPullSource): void {\n this.periodPullSource = source\n }\n\n /** #807: KPI accumulator `applyRemote` feeds during a period-scoped `pull()` — pointed at the\n * active phase's counters (summaries → records) and cleared before pull returns. Approximate\n * by design: a push interleaved mid-pull on the same engine would attribute its converge\n * applies to the open phase; the counters are a download-budget KPI, not an audit source. */\n private pullByteSink: { records: number; bytes: number } | null = null\n\n constructor(opts: {\n local: NoydbStore\n remote: NoydbStore\n vault: string\n strategy: ConflictStrategy\n emitter: NoydbEventEmitter\n syncPolicy?: SyncPolicy\n role?: SyncTargetRole\n label?: string\n /**\n * #1042 — the merge's verify/re-stamp capability. Optional so an engine\n * built without one behaves exactly as before; the Vault supplies it.\n *\n * A closure, not an import: `with-sync` is DEK-free and\n * `check:architecture` enforces that, so the capability arrives already\n * bound to the keys rather than the engine reaching for them.\n */\n mergeAuthority?: MergeAuthority\n }) {\n this.local = opts.local\n this.remote = opts.remote\n this.vault = opts.vault\n this.strategy = opts.strategy\n this.emitter = opts.emitter\n this.role = opts.role ?? 'sync-peer'\n this.label = opts.label\n this.policy = opts.syncPolicy\n this.mergeAuthority = opts.mergeAuthority\n\n // Create a scheduler when the policy asks for ANY automatic behaviour.\n // #897: this used to test `push.mode !== 'manual'` alone, so a policy of\n // `{ push: manual, pull: interval }` silently got no scheduler and its pull\n // mode was ignored.\n const policy = opts.syncPolicy\n if (policy && (policy.push.mode !== 'manual' || policy.pull.mode !== 'manual')) {\n this.scheduler = new SyncScheduler(policy, {\n push: () => this.push().then(() => {}),\n // #618 — role-gate the SCHEDULER-INITIATED pull. The Noydb layer gates\n // pull-from-sink for explicit calls, but the scheduler calls the engine\n // directly and would bypass it: a backup/archive-only primary with an\n // `interval`/`on-focus` pull policy would pull ungated, reintroducing\n // #616. This guards the engine self-initiating on a timer; an explicit\n // `engine.pull()` still pulls for every role.\n // `collections` is set by a 'phased' sequence — one collection per phase.\n // A role-gated skip reports 'incomplete': nothing was pulled, so the\n // phase must not mark its collection ready.\n pull: (collections) =>\n this.role === 'sync-peer'\n ? this.pull(collections ? { collections: [...collections] } : undefined)\n // PullResult.errors accumulates WITHOUT throwing, so a partial\n // failure is only visible here — not via a rejected promise.\n .then(r => (r.errors.length === 0 ? 'complete' : 'incomplete'))\n : Promise.resolve('incomplete'),\n getDirtyCount: () => this.dirty.length,\n })\n } else {\n this.scheduler = null\n }\n }\n\n /** Start the sync scheduler. Called after vault is fully opened. */\n startScheduler(): void {\n this.scheduler?.start()\n }\n\n /** Stop the sync scheduler. Called on close. */\n stopScheduler(): void {\n this.scheduler?.stop()\n }\n\n /**\n * Register a per-collection conflict resolver.\n * Called by Collection when `conflictPolicy` is set.\n *\n * Pair-coupled (#591 rule 5b): registering for one satellite-pair member\n * registers the same resolver for both — the pair converges under one\n * resolution policy. Expands with whatever the pair-expander knows *at this\n * call*; resolvers registered before their pair existed are covered by\n * `remirrorPairResolvers` at pair-registration time.\n */\n registerConflictResolver(collection: string, resolver: CollectionConflictResolver): void {\n for (const n of this.pairExpander?.([collection]) ?? [collection]) this.conflictResolvers.set(n, resolver)\n }\n\n /**\n * Wire a satellite pair-expansion function (vault registration, #591 Task 11).\n * The closure re-reads the live `SatelliteRegistry` on every call, so pairs\n * declared after this is set are still picked up by `push`/`pull` filters.\n */\n setPairExpander(expander: (names: readonly string[]) => readonly string[]): void {\n this.pairExpander = expander\n }\n\n /**\n * Retroactively mirror per-collection conflict resolvers across a newly\n * registered satellite pair (#591 rule 5b) — covers the NORMAL declaration\n * order, where the base's `conflictPolicy` resolver was registered before\n * the satellite was declared (so the call-time expansion in\n * `registerConflictResolver` saw no pair yet). Tie-break: when BOTH members\n * already carry (different) resolvers, the FIRST name in `names` wins —\n * callers pass `[base, satellite]`, so the base's resolver is canonical.\n * Idempotent; a later explicit registration on either member still\n * overwrites both (last-wins, via the call-time expansion above).\n */\n remirrorPairResolvers(names: readonly string[]): void {\n const canonical = names.map(n => this.conflictResolvers.get(n)).find(r => r !== undefined)\n if (!canonical) return\n for (const n of names) this.conflictResolvers.set(n, canonical)\n }\n\n /** Record a local change for later push. */\n async trackChange(collection: string, id: string, action: 'put' | 'delete', version: number): Promise<void> {\n await this.ensureLoaded()\n\n // Deduplicate: if same collection+id already in dirty, update it\n const idx = this.dirty.findIndex(d => d.collection === collection && d.id === id)\n const entry: DirtyEntry = {\n vault: this.vault,\n collection,\n id,\n action,\n version,\n timestamp: new Date().toISOString(),\n }\n\n if (idx >= 0) {\n this.dirty[idx] = entry\n } else {\n this.dirty.push(entry)\n }\n\n await this.persistMeta()\n\n // Notify scheduler of the write (triggers on-change or debounce)\n this.scheduler?.notifyChange()\n }\n\n /** Remove a dirty entry (satellite fan-out revert cleanup — spec #591). */\n async removeDirty(collection: string, id: string): Promise<void> {\n const before = this.dirty.length\n this.dirty = this.dirty.filter(d => !(d.collection === collection && d.id === id))\n if (this.dirty.length !== before) await this.persistMeta()\n }\n\n /** Push dirty records to remote adapter. Accepts optional `PushOptions` for partial sync. */\n async push(options?: PushOptions): Promise<PushResult> {\n await this.ensureLoaded()\n this.graphBatchController?.begin() // #638 Task 4\n\n let pushed = 0\n const conflicts: Conflict[] = []\n const erasures: ErasureEnforcement[] = []\n const errors: Error[] = []\n const completed: number[] = []\n\n // Partial sync: expand the filter to cover satellite pair partners (#591 rule 5b), then the\n // reserved `_dict_*` collections those (expanded) names depend on (#653) — a locally-dirty\n // dict edit pushes alongside push({collections:['orders']}), symmetric with pull below.\n const expanded = options?.collections ? (this.pairExpander?.(options.collections) ?? options.collections) : null\n const filter = expanded ? new Set([...expanded, ...(this.reservedDictExpander?.(expanded) ?? [])]) : null\n\n for (let i = 0; i < this.dirty.length; i++) {\n const entry = this.dirty[i]!\n\n // Partial sync: skip collections not in the filter\n if (filter && !filter.has(entry.collection)) {\n continue\n }\n\n try {\n if (entry.action === 'delete') {\n await this.remote.delete(this.vault, entry.collection, entry.id)\n completed.push(i)\n pushed++\n } else {\n const envelope = await this.local.get(this.vault, entry.collection, entry.id)\n if (!envelope) {\n // Record was deleted locally after being marked dirty\n completed.push(i)\n continue\n }\n\n if (isTombstoneShape(envelope)) {\n // #590: a tombstone push is an erasure assertion — unconditional,\n // no CAS, no conflict resolution. Erasure always wins.\n await this.remote.put(this.vault, entry.collection, entry.id, envelope)\n completed.push(i)\n pushed++\n continue\n }\n\n try {\n await this.remote.put(\n this.vault,\n entry.collection,\n entry.id,\n envelope,\n entry.version - 1,\n )\n completed.push(i)\n pushed++\n } catch (err) {\n if (isConflictError(err)) {\n const remoteEnvelope = await this.remote.get(this.vault, entry.collection, entry.id)\n if (remoteEnvelope) {\n if (isTombstoneShape(remoteEnvelope)) {\n // #590: remote already shredded this record — enforce locally,\n // never resolve. Resolvers must not overrule an erasure.\n await this.applyRemote(entry.collection, entry.id, remoteEnvelope)\n erasures.push(this.reportErasure(entry.collection, entry.id, remoteEnvelope, envelope, 'push'))\n completed.push(i)\n } else if (\n remoteEnvelope._v === envelope._v &&\n isDeleteMarker(remoteEnvelope) !== isDeleteMarker(envelope) &&\n !this.conflictResolvers.get(entry.collection)\n ) {\n // #589: a same-_v delete-vs-edit tie on the push channel. handleConflict's db-level\n // 'version' default would resolve it to local-wins; the tie rule consults ONLY the\n // per-collection resolver, else delete-wins. (When a per-collection resolver IS set,\n // fall through to handleConflict, which already honors it — incl. the merged case.)\n if (isDeleteMarker(remoteEnvelope)) {\n // remote already deleted → converge locally, drop our (edit) push\n await this.applyRemote(entry.collection, entry.id, remoteEnvelope)\n completed.push(i)\n } else {\n // our local is the marker → force the delete onto the remote (unconditional put)\n await this.remote.put(this.vault, entry.collection, entry.id, envelope)\n completed.push(i)\n pushed++\n }\n } else {\n const { handled, conflict } = await this.handleConflict(\n entry.collection,\n entry.id,\n envelope,\n remoteEnvelope,\n 'push',\n )\n conflicts.push(conflict)\n if (handled === 'local') {\n // #936: supersede, don't overwrite in place — see advancePastRemote.\n const winner = await this.advancePastRemote(conflict.local, entry.collection, entry.id, remoteEnvelope)\n await this.remote.put(this.vault, entry.collection, entry.id, winner)\n if (winner !== conflict.local) await this.applyRemote(entry.collection, entry.id, winner)\n completed.push(i)\n pushed++\n } else if (handled === 'remote') {\n await this.applyRemote(entry.collection, entry.id, conflict.remote)\n completed.push(i)\n } else if (handled === 'merged' && conflict.local !== envelope) {\n // Merged envelope is stored in conflict.local (the winner)\n const merged = conflict.local\n await this.remote.put(this.vault, entry.collection, entry.id, merged)\n await this.applyRemote(entry.collection, entry.id, merged)\n completed.push(i)\n pushed++\n }\n // handled === 'deferred': leave in dirty log\n }\n }\n } else {\n throw err\n }\n }\n }\n } catch (err) {\n errors.push(err instanceof Error ? err : new Error(String(err)))\n }\n }\n\n // Remove completed entries from dirty log (reverse order to preserve indices)\n for (const i of completed.sort((a, b) => b - a)) {\n this.dirty.splice(i, 1)\n }\n\n this.recordOutcome('push', errors)\n try {\n await this.persistMeta()\n } finally {\n // #644 item 1: flush (which clears `_graphBatch` unconditionally, vault.ts:1316-1320) must\n // run even if `persistMeta()` throws — else a throw here leaves the batch open, corrupting\n // the NEXT pull()/push() call's wave with THIS call's stale touches.\n await this.graphBatchController?.flush() // #638 Task 4\n }\n\n const result: PushResult = { pushed, conflicts, errors, erasures }\n this.emitter.emit('sync:push', result)\n return result\n }\n\n /** Pull remote records to local adapter. Accepts optional `PullOptions` for partial sync. */\n async pull(options?: PullOptions): Promise<PullResult> {\n await this.ensureLoaded()\n\n let pulled = 0\n const conflicts: Conflict[] = []\n const erasures: ErasureEnforcement[] = []\n const errors: Error[] = []\n\n // ── #807 period-scoped pull: validate the option, sync the period summaries\n // (`_periods` + companions — the navigation index, ALWAYS pulled in full,\n // exempt from every filter), then resolve the selected `_ts` windows from the\n // freshly synced index. All BEFORE the graph batch opens, so an invalid\n // option throws without leaving a batch dangling; summary applies route\n // through `applyRemote` like any pull (reserved names have no Collection\n // instance, so the invalidator/graph seams are no-ops for them). ──\n let periodScope: ((envelope: EncryptedEnvelope) => boolean) | null = null\n let phases: { summaries: { records: number; bytes: number }; records: { records: number; bytes: number } } | null = null\n if (options?.periods !== undefined) {\n validatePeriodsOption(options.periods)\n if (!this.periodPullSource) {\n throw new ValidationError(\n 'period-scoped pull requires a vault-attached sync engine (open the vault via createNoydb + openVault).',\n )\n }\n phases = { summaries: { records: 0, bytes: 0 }, records: { records: 0, bytes: 0 } }\n let remotePeriodCount = 0\n this.pullByteSink = phases.summaries\n try {\n for (const collName of PERIOD_SUMMARY_COLLECTIONS) {\n for (const id of await this.remote.list(this.vault, collName)) {\n if (collName === PERIODS_COLLECTION) remotePeriodCount++\n try {\n const remoteEnvelope = await this.remote.get(this.vault, collName, id)\n if (!remoteEnvelope) continue\n const localEnvelope = await this.local.get(this.vault, collName, id)\n if (!localEnvelope || remoteEnvelope._v > localEnvelope._v) {\n await this.applyRemote(collName, id, remoteEnvelope)\n pulled++\n }\n } catch (err) {\n errors.push(err instanceof Error ? err : new Error(String(err)))\n }\n }\n }\n } finally {\n this.pullByteSink = null\n }\n const periodRecords = await this.periodPullSource.periods()\n if (remotePeriodCount > 0 && periodRecords.length === 0) {\n throw new ValidationError(\n 'period-scoped pull: the vault holds _periods records but none are readable — enable the ' +\n 'periods service (`periodsStrategy: withPeriods()`) so pull can resolve the period windows.',\n )\n }\n periodScope = buildPeriodScope(options.periods, periodRecords)\n }\n\n this.graphBatchController?.begin() // #638 Task 4\n if (phases) this.pullByteSink = phases.records\n\n // Partial sync: expand the filter to cover satellite pair partners (#591 rule 5b), then the\n // reserved `_dict_*` collections those (expanded) names depend on (#653) — adopters never\n // name `_dict_*` in a `collections` filter, so a named collection's lookup-field dependency\n // must be pulled alongside it or its labels/membership go stale.\n const expanded = options?.collections ? (this.pairExpander?.(options.collections) ?? options.collections) : null\n const filter = expanded ? new Set([...expanded, ...(this.reservedDictExpander?.(expanded) ?? [])]) : null\n\n try {\n const remoteSnapshot = await this.remote.loadAll(this.vault)\n\n for (const [collName, records] of Object.entries(remoteSnapshot)) {\n // Partial sync: skip collections not in the filter\n if (filter && !filter.has(collName)) {\n continue\n }\n\n for (const [id, remoteEnvelope] of Object.entries(records)) {\n // Partial sync: modifiedSince filter — arriving tombstones are exempt (#590):\n // an erasure must never be skipped by partial sync.\n if (\n options?.modifiedSince &&\n remoteEnvelope._ts <= options.modifiedSince &&\n !isTombstoneShape(remoteEnvelope) &&\n !isDeleteMarker(remoteEnvelope)\n ) {\n continue\n }\n\n // #807: period scope — a record whose `_ts` falls outside every selected\n // window is skipped. Tombstones and delete markers are ALWAYS in scope\n // (built into the predicate): an erasure or delete must never be skipped\n // by partial sync, mirroring the modifiedSince exemption above — that is\n // what lets a device that never pulled a period backfill it later without\n // resurrecting its deleted records.\n if (periodScope !== null && !periodScope(remoteEnvelope)) {\n continue\n }\n\n try {\n const localEnvelope = await this.local.get(this.vault, collName, id)\n const remoteIsTombstone = isTombstoneShape(remoteEnvelope)\n\n if (!localEnvelope) {\n // New record from remote (tombstones included — durable erasure evidence)\n await this.applyRemote(collName, id, remoteEnvelope)\n pulled++\n } else if (isTombstoneShape(localEnvelope)) {\n if (remoteIsTombstone) {\n // Both shredded — keep the higher version counter\n if (remoteEnvelope._v > localEnvelope._v) await this.applyRemote(collName, id, remoteEnvelope)\n } else {\n // Terminal rule (#590): a tombstone is never overwritten by a live\n // envelope, regardless of _v. Re-assert the shred outward instead.\n erasures.push(await this.reassertTombstone(collName, id, localEnvelope, remoteEnvelope))\n }\n } else if (remoteIsTombstone) {\n // Terminal rule (#590): an arriving tombstone wins over any local live\n // envelope — even a newer, dirty one. Resolvers are never consulted.\n const wasDirty = this.dirty.some(d => d.collection === collName && d.id === id)\n await this.applyRemote(collName, id, remoteEnvelope)\n this.dirty = this.dirty.filter(d => !(d.collection === collName && d.id === id))\n pulled++\n if (wasDirty) erasures.push(this.reportErasure(collName, id, remoteEnvelope, localEnvelope, 'pull'))\n } else if (\n remoteEnvelope._v === localEnvelope._v &&\n isDeleteMarker(remoteEnvelope) !== isDeleteMarker(localEnvelope)\n ) {\n // #589: true concurrent delete-vs-edit at the SAME version. Version order\n // can't break the tie. A per-collection resolver decides if one is set;\n // otherwise DELETE wins (the db-level 'version' default is deliberately NOT\n // consulted — it would resolve a tie to local-wins).\n const resolver = this.conflictResolvers.get(collName)\n if (resolver) {\n const winner = await resolver(id, localEnvelope, remoteEnvelope)\n if (winner !== localEnvelope && winner !== null) {\n // #589 (review): a novel/merged winner (neither side verbatim) must also be\n // pushed to remote — mirrors handleConflict's 'merged' handling — so both\n // sides converge instead of local applying it while remote keeps its old copy.\n if (winner !== remoteEnvelope) {\n await this.remote.put(this.vault, collName, id, winner)\n }\n await this.applyRemote(collName, id, winner)\n this.dirty = this.dirty.filter(d => !(d.collection === collName && d.id === id))\n pulled++\n }\n // winner === localEnvelope or null → keep local (its dirty entry, if any, pushes out)\n } else if (isDeleteMarker(remoteEnvelope)) {\n // no resolver → delete wins; the incoming marker is the delete\n await this.applyRemote(collName, id, remoteEnvelope)\n this.dirty = this.dirty.filter(d => !(d.collection === collName && d.id === id))\n pulled++\n }\n // no resolver and LOCAL is the marker → keep local marker; its dirty 'put' pushes it outward\n } else if (remoteEnvelope._v > localEnvelope._v) {\n // Remote is newer — check if we have a dirty entry for this\n const isDirty = this.dirty.some(d => d.collection === collName && d.id === id)\n if (isDirty) {\n // Both changed — conflict\n const { handled, conflict } = await this.handleConflict(\n collName,\n id,\n localEnvelope,\n remoteEnvelope,\n 'pull',\n )\n conflicts.push(conflict)\n if (handled === 'remote') {\n await this.applyRemote(collName, id, conflict.remote)\n this.dirty = this.dirty.filter(d => !(d.collection === collName && d.id === id))\n pulled++\n } else if (handled === 'merged' && conflict.local !== localEnvelope) {\n const merged = conflict.local\n await this.applyRemote(collName, id, merged)\n this.dirty = this.dirty.filter(d => !(d.collection === collName && d.id === id))\n pulled++\n }\n // 'local' or 'deferred': push handles it\n } else {\n // Remote is newer, no local changes — update\n await this.applyRemote(collName, id, remoteEnvelope)\n pulled++\n }\n }\n // Same version or local is newer — skip (push will handle)\n } catch (err) {\n errors.push(err instanceof Error ? err : new Error(String(err)))\n }\n }\n }\n\n // #650 Task 4 (#647) — reserved lookup collections (`_dict_*`/`_lookup_*`) are invisible to\n // `remote.loadAll()` above (the store contract skips `_`-prefixed names) but DO sync via\n // this EXPLICIT, declared registry — not a blanket underscore-glob; other `_` namespaces\n // keep their `loadAll`-skip semantics untouched. Applied through the SAME `applyRemote` path,\n // still inside this try block, BEFORE `persistMeta`/`flush` below — so a pulled vocabulary\n // row lands before the wave (flushed at the end of `pull()`) recomputes any dependent.\n //\n // #647 fix wave 1: `LookupHandle.delete()`/`rename()` now write a version-ordered\n // delete-marker row (mirroring #589) instead of a raw adapter delete, so a removed key is\n // a normal row here too — reachable via `remote.list()` like any other id, applied by\n // version like any other write. The only reserved-tier-specific rule is the same-version\n // tie-break below: reserved lookups have no per-collection conflict-resolver concept\n // (dictionaries are admin-edited, not multi-actor-negotiated), so a converging delete\n // unconditionally wins over a same-version live edit.\n //\n // #807: the period scope deliberately does NOT apply here — vocabularies/config rows are\n // not period-partitioned data (a thin client's lookups must be complete regardless of\n // which periods it pulled), the same always-pull rule as the `_periods` summaries phase.\n for (const collName of this.reservedLookup?.collections() ?? []) {\n if (filter && !filter.has(collName)) continue\n for (const id of await this.remote.list(this.vault, collName)) {\n try {\n const remoteEnvelope = await this.remote.get(this.vault, collName, id)\n if (!remoteEnvelope) continue\n\n // Partial sync: modifiedSince filter — a delete marker is exempt, mirroring the\n // main loop's tombstone/marker exemption above: a deletion must never be silently\n // skipped by a time-window partial pull.\n if (\n options?.modifiedSince &&\n remoteEnvelope._ts <= options.modifiedSince &&\n !isDeleteMarker(remoteEnvelope)\n ) {\n continue\n }\n\n const localEnvelope = await this.local.get(this.vault, collName, id)\n if (!localEnvelope) {\n await this.applyRemote(collName, id, remoteEnvelope)\n pulled++\n } else if (\n remoteEnvelope._v === localEnvelope._v &&\n isDeleteMarker(remoteEnvelope) !== isDeleteMarker(localEnvelope)\n ) {\n // Same-version delete-vs-edit tie (#589's rule, reserved-tier default: no\n // resolver concept here, so delete always wins).\n if (isDeleteMarker(remoteEnvelope)) {\n await this.applyRemote(collName, id, remoteEnvelope)\n this.dirty = this.dirty.filter(d => !(d.collection === collName && d.id === id))\n pulled++\n }\n // else: local already holds the marker (a local delete not yet observed\n // remotely) — keep it; push re-asserts it.\n } else if (remoteEnvelope._v > localEnvelope._v) {\n await this.applyRemote(collName, id, remoteEnvelope)\n // Drop any now-superseded local dirty entry so a subsequent push doesn't\n // redundantly re-fight a CAS conflict over content pull just overwrote.\n this.dirty = this.dirty.filter(d => !(d.collection === collName && d.id === id))\n pulled++\n }\n } catch (err) {\n errors.push(err instanceof Error ? err : new Error(String(err)))\n }\n }\n }\n } catch (err) {\n errors.push(err instanceof Error ? err : new Error(String(err)))\n }\n\n this.recordOutcome('pull', errors)\n try {\n await this.persistMeta()\n } finally {\n this.pullByteSink = null // #807: stop attributing applies to this pull's KPI counters\n // #644 item 1: flush must run even if `persistMeta()` throws (see push()'s identical guard).\n await this.graphBatchController?.flush() // #638 Task 4\n }\n\n const result: PullResult = { pulled, conflicts, errors, erasures, ...(phases !== null ? { phases } : {}) }\n this.emitter.emit('sync:pull', result)\n return result\n }\n\n /** Bidirectional sync: pull then push. */\n async sync(options?: { push?: PushOptions; pull?: PullOptions }): Promise<{ pull: PullResult; push: PushResult }> {\n const pullResult = await this.pull(options?.pull)\n const pushResult = await this.push(options?.push)\n return { pull: pullResult, push: pushResult }\n }\n\n /**\n * Push a specific subset of dirty entries (for sync transactions, ).\n * Entries are matched by collection+id from the dirty log; matched entries\n * are removed from the dirty log on success.\n */\n async pushFiltered(predicate: (entry: DirtyEntry) => boolean): Promise<PushResult> {\n await this.ensureLoaded()\n\n let pushed = 0\n const conflicts: Conflict[] = []\n const erasures: ErasureEnforcement[] = []\n const errors: Error[] = []\n const completed: number[] = []\n\n for (let i = 0; i < this.dirty.length; i++) {\n const entry = this.dirty[i]!\n if (!predicate(entry)) continue\n\n try {\n if (entry.action === 'delete') {\n await this.remote.delete(this.vault, entry.collection, entry.id)\n completed.push(i)\n pushed++\n } else {\n const envelope = await this.local.get(this.vault, entry.collection, entry.id)\n if (!envelope) {\n completed.push(i)\n continue\n }\n\n if (isTombstoneShape(envelope)) {\n // #590: a tombstone push is an erasure assertion — unconditional,\n // no CAS, no conflict resolution. Erasure always wins.\n await this.remote.put(this.vault, entry.collection, entry.id, envelope)\n completed.push(i)\n pushed++\n continue\n }\n\n try {\n await this.remote.put(\n this.vault,\n entry.collection,\n entry.id,\n envelope,\n entry.version - 1,\n )\n completed.push(i)\n pushed++\n } catch (err) {\n if (isConflictError(err)) {\n const remoteEnvelope = await this.remote.get(this.vault, entry.collection, entry.id)\n if (remoteEnvelope) {\n if (isTombstoneShape(remoteEnvelope)) {\n // #590: remote already shredded this record — enforce locally,\n // never resolve. Resolvers must not overrule an erasure.\n await this.applyRemote(entry.collection, entry.id, remoteEnvelope)\n erasures.push(this.reportErasure(entry.collection, entry.id, remoteEnvelope, envelope, 'push'))\n completed.push(i)\n } else if (\n remoteEnvelope._v === envelope._v &&\n isDeleteMarker(remoteEnvelope) !== isDeleteMarker(envelope) &&\n !this.conflictResolvers.get(entry.collection)\n ) {\n // #589: a same-_v delete-vs-edit tie on the push channel. handleConflict's db-level\n // 'version' default would resolve it to local-wins; the tie rule consults ONLY the\n // per-collection resolver, else delete-wins. (When a per-collection resolver IS set,\n // fall through to handleConflict, which already honors it — incl. the merged case.)\n if (isDeleteMarker(remoteEnvelope)) {\n // remote already deleted → converge locally, drop our (edit) push\n await this.applyRemote(entry.collection, entry.id, remoteEnvelope)\n completed.push(i)\n } else {\n // our local is the marker → force the delete onto the remote (unconditional put)\n await this.remote.put(this.vault, entry.collection, entry.id, envelope)\n completed.push(i)\n pushed++\n }\n } else {\n const { handled, conflict } = await this.handleConflict(\n entry.collection,\n entry.id,\n envelope,\n remoteEnvelope,\n 'push',\n )\n conflicts.push(conflict)\n if (handled === 'local') {\n // #936: supersede, don't overwrite in place — see advancePastRemote.\n const winner = await this.advancePastRemote(conflict.local, entry.collection, entry.id, remoteEnvelope)\n await this.remote.put(this.vault, entry.collection, entry.id, winner)\n if (winner !== conflict.local) await this.applyRemote(entry.collection, entry.id, winner)\n completed.push(i)\n pushed++\n } else if (handled === 'remote') {\n await this.applyRemote(entry.collection, entry.id, conflict.remote)\n completed.push(i)\n } else if (handled === 'merged' && conflict.local !== envelope) {\n const merged = conflict.local\n await this.remote.put(this.vault, entry.collection, entry.id, merged)\n await this.applyRemote(entry.collection, entry.id, merged)\n completed.push(i)\n pushed++\n }\n }\n }\n } else {\n throw err\n }\n }\n }\n } catch (err) {\n errors.push(err instanceof Error ? err : new Error(String(err)))\n }\n }\n\n for (const i of completed.sort((a, b) => b - a)) {\n this.dirty.splice(i, 1)\n }\n\n this.recordOutcome('push', errors)\n await this.persistMeta()\n\n const result: PushResult = { pushed, conflicts, errors, erasures }\n this.emitter.emit('sync:push', result)\n return result\n }\n\n /**\n * #1036 — close out a push/pull. `push()` and `pull()` collect per-record\n * failures into their result's `errors` rather than throwing, and the clock used\n * to be stamped regardless — so an unreachable store still reported a fresh\n * `lastPush`, and a UI rendered \"Last synced: just now\" over a sync that moved\n * nothing. An attempt only advances the clock when it had no errors.\n *\n * An empty dirty log is a success, not a failure: nothing to send is not the\n * same as failing to send, and treating it otherwise would leave a quiet vault\n * looking permanently unsynced.\n */\n private recordOutcome(op: 'push' | 'pull', errors: readonly Error[]): void {\n const at = new Date().toISOString()\n if (errors.length > 0) {\n this.lastError = { at, op, message: errors[0]!.message }\n return\n }\n this.lastError = null\n if (op === 'push') this.lastPush = at\n else this.lastPull = at\n }\n\n /** Get current sync status. */\n status(): SyncStatus {\n // #809 — readiness rides the status surface that already exists rather than\n // a second accessor, so an app asks one question to learn everything about\n // this vault's sync. Absent entirely unless a phased policy is running.\n const scheduled = this.scheduler?.status\n return {\n dirty: this.dirty.length,\n lastPush: this.lastPush,\n lastPull: this.lastPull,\n online: this.isOnline,\n ...(this.lastError ? { lastError: this.lastError } : {}),\n ...(scheduled && scheduled.readiness.size > 0\n ? { readiness: scheduled.readiness, phase: scheduled.phase }\n : {}),\n }\n }\n\n // ─── Auto-Sync ───────────────────────────────────────────────────\n\n /** Start auto-sync: listen for online/offline events, optional periodic sync. */\n startAutoSync(intervalMs?: number): void {\n // Online/offline detection\n if (typeof globalThis.addEventListener === 'function') {\n globalThis.addEventListener('online', this.handleOnline)\n globalThis.addEventListener('offline', this.handleOffline)\n }\n\n // Periodic sync\n if (intervalMs && intervalMs > 0) {\n this.autoSyncInterval = setInterval(() => {\n if (this.isOnline) {\n void this.sync()\n }\n }, intervalMs)\n }\n }\n\n /** Stop auto-sync and scheduler. */\n stopAutoSync(): void {\n this.stopScheduler()\n if (typeof globalThis.removeEventListener === 'function') {\n globalThis.removeEventListener('online', this.handleOnline)\n globalThis.removeEventListener('offline', this.handleOffline)\n }\n if (this.autoSyncInterval) {\n clearInterval(this.autoSyncInterval)\n this.autoSyncInterval = null\n }\n }\n\n private handleOnline = (): void => {\n this.isOnline = true\n this.emitter.emit('sync:online', undefined as never)\n void this.sync()\n }\n\n private handleOffline = (): void => {\n this.isOnline = false\n this.emitter.emit('sync:offline', undefined as never)\n }\n\n /** Apply an envelope to the local store and refresh in-memory views (#598). `action` (#640):\n * classified HERE — the one choke point that still holds the envelope — so the\n * cacheInvalidator seam (and, downstream, the dispatch wave) can tell a pulled delete from an\n * ordinary put. `isTombstoneShape` covers a forgotten-elsewhere record arriving as a shred;\n * `isDeleteMarker` covers an ordinary (#589) delete — both route to the SAME 'delete' action\n * (sync delete ≠ forget: freshness only, no shred/residue channel on the receiving side). */\n /**\n * #936 — a local-wins resolution write must SUPERSEDE the remote, never\n * overwrite it in place: when the winner's `_v` does not already exceed\n * the remote's (the same-`_v` push tie), re-stamp it at `remote._v + 1`.\n * Without this the loser's next pull sees no delta (`_v`-based\n * detection) and the peers stay silently diverged at the same version.\n * ## Why this is async, and why it goes through `MergeAuthority` (#1093)\n *\n * It used to be `{ ...winner, _v: remote._v + 1 }` — a metadata restamp on\n * ciphertext the engine cannot decrypt. That spread was the SOLE reason `_v`\n * could not be bound into the AAD: a version rewritten onto a body sealed at\n * a different one produces a record no reader can open.\n *\n * `with-sync` is DEK-free by design and `check:architecture` enforces it, so\n * the re-seal cannot happen here. It happens in the injected authority, which\n * holds the keys. The engine still decides WHICH version to advance to; it\n * simply no longer pretends it can rewrite a sealed body.\n *\n * The authority is ALWAYS present in the product — `kernel/noydb.ts` builds\n * one from the keyring and passes it at both engine-construction sites, and\n * `with-sync/active.ts` is the only place an engine is constructed. The\n * fallback below is reachable only by constructing `SyncEngine` directly,\n * which tests do. It restamps, as before — and would produce an unreadable\n * record if such a test ever held AEAD-sealed envelopes. None do; the\n * fixtures that reach it build their own plaintext ones.\n *\n * The 'merged' branch needs none of this: resolver output is already stamped\n * `max(local, remote) + 1` by whoever built it.\n */\n private async advancePastRemote(winner: EncryptedEnvelope, collection: string, id: string, remote: EncryptedEnvelope): Promise<EncryptedEnvelope> {\n if (winner._v > remote._v) return winner\n const toVersion = remote._v + 1\n if (!this.mergeAuthority) return { ...winner, _v: toVersion }\n return this.mergeAuthority.advance(collection, id, winner, toVersion)\n }\n\n private async applyRemote(collection: string, id: string, envelope: EncryptedEnvelope): Promise<void> {\n // #1042 — FAIL CLOSED, and do it HERE rather than at the 14 call sites.\n // Every path that commits store-supplied ciphertext goes through this\n // function, so gating it once covers them all by construction instead of by\n // remembering. A gate added per-caller is a gate someone forgets.\n //\n // Throwing is the correct shape, not a shortcut: each pull entry is wrapped\n // in its own try/catch that records the error and moves on, so a poisoned\n // record becomes one `PullResult.errors` entry rather than a halted sync —\n // which is exactly what a hostile store would want.\n //\n // Ordering is the whole point: this runs BEFORE `local.put`, so a rejection\n // costs the client nothing. Its existing copy is untouched.\n if (this.mergeAuthority && !(await this.mergeAuthority.verify(collection, id, envelope))) {\n throw new ValidationError(\n `sync: refusing remote envelope for \"${collection}/${id}\" — it does not authenticate at the ` +\n 'identity and version it claims. The local copy is unchanged.',\n )\n }\n await this.local.put(this.vault, collection, id, envelope)\n if (this.pullByteSink !== null) {\n // #807: KPI — one applied envelope; bytes ≈ ciphertext payload size.\n this.pullByteSink.records++\n this.pullByteSink.bytes += envelopeBodySize(envelope)\n }\n const action: 'put' | 'delete' = isTombstoneShape(envelope) || isDeleteMarker(envelope) ? 'delete' : 'put'\n await this.cacheInvalidator?.(collection, id, action)\n }\n\n /** Record + emit a tombstone enforcement (#590). */\n private reportErasure(\n collection: string, id: string,\n tombstone: EncryptedEnvelope, suppressed: EncryptedEnvelope,\n direction: 'pull' | 'push',\n ): ErasureEnforcement {\n const enforcement: ErasureEnforcement = { vault: this.vault, collection, id, tombstone, suppressed, direction }\n this.emitter.emit('sync:erasure', enforcement)\n return enforcement\n }\n\n /**\n * Re-assert a local tombstone over a live remote envelope (#590): the shred\n * wins in both directions, regardless of `_v`. Bumps the tombstone to the\n * suppressed envelope's `_v` when higher so per-key version counters stay\n * monotonic on every store; `_by` (the shredding actor) is preserved.\n */\n private async reassertTombstone(\n collection: string, id: string,\n tombstone: EncryptedEnvelope, suppressedRemote: EncryptedEnvelope,\n ): Promise<ErasureEnforcement> {\n let winner = tombstone\n if (suppressedRemote._v > tombstone._v) {\n winner = { ...tombstone, _v: suppressedRemote._v, _ts: new Date().toISOString() }\n await this.applyRemote(collection, id, winner)\n }\n await this.remote.put(this.vault, collection, id, winner)\n // The re-assert already delivered the tombstone remotely — drop any dirty\n // entry so the following push doesn't redundantly re-put it.\n this.dirty = this.dirty.filter(d => !(d.collection === collection && d.id === id))\n return this.reportErasure(collection, id, winner, suppressedRemote, 'pull')\n }\n\n /**\n * Resolve a conflict, checking per-collection resolvers first,\n * then falling back to the db-level `ConflictStrategy`.\n *\n * Returns the resolved `Conflict` object (possibly with `resolve` set for\n * manual mode) and a `handled` discriminant:\n * - `'local'` — keep the local envelope; push it to remote.\n * - `'remote'` — keep the remote envelope; update local.\n * - `'merged'` — a custom merge fn produced a new envelope stored as `conflict.local`.\n * - `'deferred'` — manual mode, resolve was not called synchronously.\n */\n private async handleConflict(\n collection: string,\n id: string,\n local: EncryptedEnvelope,\n remote: EncryptedEnvelope,\n _phase: 'push' | 'pull',\n ): Promise<{ handled: 'local' | 'remote' | 'merged' | 'deferred'; conflict: Conflict }> {\n const resolver = this.conflictResolvers.get(collection)\n\n if (resolver) {\n // Per-collection resolver is responsible for emitting sync:conflict\n // (manual policy emits with a resolve callback; LWW/FWW/custom are silent).\n const winner = await resolver(id, local, remote)\n const base: Conflict = {\n vault: this.vault,\n collection,\n id,\n local,\n remote,\n localVersion: local._v,\n remoteVersion: remote._v,\n }\n if (winner === null) return { handled: 'deferred', conflict: base }\n if (winner === local) return { handled: 'local', conflict: base }\n if (winner === remote) return { handled: 'remote', conflict: base }\n // Custom merge fn produced a new envelope — store as conflict.local for the caller\n return {\n handled: 'merged',\n conflict: { ...base, local: winner, localVersion: winner._v },\n }\n }\n\n // Fall back to db-level strategy — emit once\n const baseConflict: Conflict = {\n vault: this.vault,\n collection,\n id,\n local,\n remote,\n localVersion: local._v,\n remoteVersion: remote._v,\n }\n this.emitter.emit('sync:conflict', baseConflict)\n const side = this.legacyResolve(baseConflict)\n return { handled: side, conflict: baseConflict }\n }\n\n /** DB-level ConflictStrategy resolution (legacy, kept for backward compat). */\n private legacyResolve(conflict: Conflict): 'local' | 'remote' {\n if (typeof this.strategy === 'function') {\n return this.strategy(conflict)\n }\n switch (this.strategy) {\n case 'local-wins': return 'local'\n case 'remote-wins': return 'remote'\n case 'version':\n default:\n return conflict.localVersion >= conflict.remoteVersion ? 'local' : 'remote'\n }\n }\n\n // ─── Persistence ─────────────────────────────────────────────────\n\n private async ensureLoaded(): Promise<void> {\n if (this.loaded) return\n\n const envelope = await this.local.get(this.vault, '_sync', 'meta')\n if (envelope) {\n const meta = JSON.parse(envelope._data) as SyncMetadata\n this.dirty = [...meta.dirty]\n this.lastPush = meta.last_push\n this.lastPull = meta.last_pull\n }\n\n this.loaded = true\n }\n\n private async persistMeta(): Promise<void> {\n const meta: SyncMetadata = {\n _noydb_sync: NOYDB_SYNC_VERSION,\n last_push: this.lastPush,\n last_pull: this.lastPull,\n dirty: this.dirty,\n }\n\n const envelope: EncryptedEnvelope = buildRecordEnvelope(\n { collection: '_sync', id: 'meta', version: 1 },\n { iv: '', data: JSON.stringify(meta) },\n )\n\n await this.local.put(this.vault, '_sync', 'meta', envelope)\n }\n}\n","import type { SyncTransactionResult } from '../kernel/types.js'\nimport type { SyncEngine } from './engine.js'\nimport type { Vault } from '../kernel/vault.js'\n\ninterface TxOp {\n readonly type: 'put' | 'delete'\n readonly collection: string\n readonly id: string\n readonly record?: unknown\n}\n\n/**\n * Sync transaction.\n *\n * Stages local writes and then pushes only those records to remote in a\n * single batch. If any record conflicts during the push, the result\n * carries `status: 'conflict'` — no automatic rollback is performed;\n * the caller handles conflict resolution.\n *\n * Obtain via `db.transaction(compartmentName)`.\n */\nexport class SyncTransaction {\n private readonly comp: Vault\n private readonly engine: SyncEngine\n private readonly ops: TxOp[] = []\n\n /** @internal — constructed by `Noydb.transaction()` */\n constructor(comp: Vault, engine: SyncEngine) {\n this.comp = comp\n this.engine = engine\n }\n\n /** Stage a record write. Does not write to any adapter until `commit()`. */\n put(collection: string, id: string, record: unknown): this {\n this.ops.push({ type: 'put', collection, id, record })\n return this\n }\n\n /** Stage a record delete. Does not write to any adapter until `commit()`. */\n delete(collection: string, id: string): this {\n this.ops.push({ type: 'delete', collection, id })\n return this\n }\n\n /**\n * Commit the transaction.\n *\n * Phase 1 — writes all staged operations to the local adapter via the\n * collection layer (encryption + dirty-log tracking).\n *\n * Phase 2 — pushes only the records that were written in this\n * transaction to the remote adapter. Existing dirty entries from\n * outside this transaction are not affected.\n *\n * If any record conflicts during the push, `status` is `'conflict'`\n * and `conflicts` lists the affected records. No automatic rollback is\n * performed.\n */\n async commit(): Promise<SyncTransactionResult> {\n // Phase 1: write all staged ops to local via collection layer\n for (const op of this.ops) {\n if (op.type === 'put') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await (this.comp.collection<any>(op.collection)).put(op.id, op.record as any)\n } else {\n await this.comp.collection(op.collection).delete(op.id)\n }\n }\n\n // Phase 2: push only the records from this transaction\n const opSet = new Set<string>()\n for (const op of this.ops) {\n opSet.add(`${op.collection}::${op.id}`)\n }\n\n const pushResult = await this.engine.pushFiltered(\n (entry) => opSet.has(`${entry.collection}::${entry.id}`),\n )\n\n return {\n status: pushResult.conflicts.length > 0 ? 'conflict' : 'committed',\n pushed: pushResult.pushed,\n conflicts: pushResult.conflicts,\n ...(pushResult.erasures?.length ? { erasures: pushResult.erasures } : {}),\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBA,IAAM,SAAS,WAAW,OAAO;AASjC,IAAM,0BAA0B;AAgDzB,IAAM,iBAAN,MAAwB;AAAA,EACZ;AAAA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,aAAa,MAAM,KAAK,OAAO;AAAA,MACnC,CAAC,UAAU,MAAM,IAAI,GAAG,MAAM,UAAU,KAAK,MAAM,EAAE,EAAE;AAAA,IACzD;AAEA,WAAO;AAAA,MACL,QAAQ,WAAW,UAAU,SAAS,IAAI,aAAa;AAAA,MACvD,QAAQ,WAAW;AAAA,MACnB,WAAW,WAAW;AAAA,MACtB,GAAI,WAAW,UAAU,SAAS,EAAE,UAAU,WAAW,SAAS,IAAI,CAAC;AAAA,IACzE;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
import {
|
|
2
2
|
installViaBinder
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-JNMTN5D5.js";
|
|
4
4
|
import {
|
|
5
|
-
|
|
6
|
-
} from "./chunk-
|
|
5
|
+
buildRecordAad
|
|
6
|
+
} from "./chunk-OHOKBMTM.js";
|
|
7
|
+
import {
|
|
8
|
+
buildRecordEnvelope
|
|
9
|
+
} from "./chunk-PENPHA45.js";
|
|
7
10
|
import {
|
|
8
|
-
|
|
9
|
-
} from "./chunk-
|
|
11
|
+
encrypt
|
|
12
|
+
} from "./chunk-AU3AUJIZ.js";
|
|
10
13
|
import {
|
|
11
14
|
ValidationError
|
|
12
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-CWM4GQD2.js";
|
|
13
16
|
|
|
14
17
|
// src/via/blob/binding.ts
|
|
15
18
|
async function eraseBlobs(ctx, cfg) {
|
|
@@ -367,27 +370,15 @@ function generateEvictionId(collection, recordId, slotName) {
|
|
|
367
370
|
}
|
|
368
371
|
async function writeAuditEntry(ctx, entry) {
|
|
369
372
|
const json = JSON.stringify(entry);
|
|
373
|
+
const identity = { collection: BLOB_EVICTION_AUDIT_COLLECTION, id: entry.id, by: entry.actor, version: 1 };
|
|
374
|
+
const body = { ts: entry.evictedAt };
|
|
370
375
|
let envelope;
|
|
371
376
|
if (ctx.encrypted) {
|
|
372
377
|
const dek = await ctx.getDEK(BLOB_EVICTION_AUDIT_COLLECTION);
|
|
373
|
-
const { iv, data } = await encrypt(json, dek);
|
|
374
|
-
envelope = {
|
|
375
|
-
_noydb: NOYDB_FORMAT_VERSION,
|
|
376
|
-
_v: 1,
|
|
377
|
-
_ts: entry.evictedAt,
|
|
378
|
-
_iv: iv,
|
|
379
|
-
_data: data,
|
|
380
|
-
_by: entry.actor
|
|
381
|
-
};
|
|
378
|
+
const { iv, data } = await encrypt(json, dek, buildRecordAad(identity));
|
|
379
|
+
envelope = buildRecordEnvelope(identity, { ...body, iv, data });
|
|
382
380
|
} else {
|
|
383
|
-
envelope = {
|
|
384
|
-
_noydb: NOYDB_FORMAT_VERSION,
|
|
385
|
-
_v: 1,
|
|
386
|
-
_ts: entry.evictedAt,
|
|
387
|
-
_iv: "",
|
|
388
|
-
_data: json,
|
|
389
|
-
_by: entry.actor
|
|
390
|
-
};
|
|
381
|
+
envelope = buildRecordEnvelope(identity, { ...body, iv: "", data: json });
|
|
391
382
|
}
|
|
392
383
|
await ctx.adapter.put(ctx.vault, BLOB_EVICTION_AUDIT_COLLECTION, entry.id, envelope);
|
|
393
384
|
}
|
|
@@ -400,4 +391,4 @@ export {
|
|
|
400
391
|
BLOB_EVICTION_AUDIT_COLLECTION,
|
|
401
392
|
runCompaction
|
|
402
393
|
};
|
|
403
|
-
//# sourceMappingURL=chunk-
|
|
394
|
+
//# sourceMappingURL=chunk-4OQZNXQG.js.map
|