@noy-db/hub 0.2.0-pre.30 → 0.2.0-pre.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/dist/adapter/index.d.ts +9 -0
  2. package/dist/adapter/index.js +14 -0
  3. package/dist/attestation/index.d.ts +1 -1
  4. package/dist/attestation/index.js +3 -3
  5. package/dist/blobs/index.d.ts +3 -3
  6. package/dist/bundle/index.d.ts +3 -3
  7. package/dist/bundle/index.js +1 -1
  8. package/dist/{chunk-Y6YUWZTS.js → chunk-L5HHBOMS.js} +2 -2
  9. package/dist/{chunk-BVKLJBJJ.js → chunk-W5NVNJDX.js} +2 -1
  10. package/dist/{chunk-BVKLJBJJ.js.map → chunk-W5NVNJDX.js.map} +1 -1
  11. package/dist/consent/index.d.ts +2 -2
  12. package/dist/{decrypt-partition-Mhjh6nnG.d.ts → decrypt-partition-CXS5KopB.d.ts} +1 -1
  13. package/dist/derivations/index.d.ts +3 -3
  14. package/dist/{dev-unlock-DJ3IhgY9.d.ts → dev-unlock-CnHTTVea.d.ts} +1 -1
  15. package/dist/guards/index.d.ts +3 -3
  16. package/dist/{hash-DLwkYf1d.d.ts → hash-oc5paYl0.d.ts} +1 -1
  17. package/dist/history/index.d.ts +3 -3
  18. package/dist/i18n/index.d.ts +2 -2
  19. package/dist/{index-CMRIx_zx.d.ts → index-BmhGztUi.d.ts} +1 -1
  20. package/dist/index.d.ts +11 -11
  21. package/dist/index.js +2 -2
  22. package/dist/kernel/index.d.ts +2 -2
  23. package/dist/materialized-views/index.d.ts +3 -3
  24. package/dist/{mime-magic-CacDBwYp.d.ts → mime-magic-JeLKHRng.d.ts} +1 -1
  25. package/dist/{noydb-5MIBD77B.js → noydb-NAU2DTFP.js} +2 -2
  26. package/dist/noydb-NAU2DTFP.js.map +1 -0
  27. package/dist/overlay-views/index.d.ts +3 -3
  28. package/dist/periods/index.d.ts +2 -2
  29. package/dist/session/index.d.ts +3 -3
  30. package/dist/shadow/index.d.ts +2 -2
  31. package/dist/snapshots/index.d.ts +2 -2
  32. package/dist/store/index.d.ts +2 -2
  33. package/dist/sync/index.d.ts +1 -1
  34. package/dist/team/index.d.ts +2 -2
  35. package/dist/{transition-guard-J04-jime.d.ts → transition-guard-Dy3NioQr.d.ts} +1 -1
  36. package/dist/tx/index.d.ts +2 -2
  37. package/dist/{with-materialized-view-DNfzC5lH.d.ts → with-materialized-view-DIVeez0W.d.ts} +1 -1
  38. package/dist/{with-overlayed-view-qk3lbhOd.d.ts → with-overlayed-view-DVZrc5Hb.d.ts} +1 -1
  39. package/dist/{with-rollup-Dd3_ZG4b.d.ts → with-rollup-CbU-O4wP.d.ts} +1 -1
  40. package/package.json +62 -221
  41. package/dist/aggregate/index.cjs +0 -1144
  42. package/dist/aggregate/index.cjs.map +0 -1
  43. package/dist/aggregate/index.d.cts +0 -39
  44. package/dist/attestation/index.cjs +0 -305
  45. package/dist/attestation/index.cjs.map +0 -1
  46. package/dist/attestation/index.d.cts +0 -54
  47. package/dist/blobs/index.cjs +0 -1967
  48. package/dist/blobs/index.cjs.map +0 -1
  49. package/dist/blobs/index.d.cts +0 -48
  50. package/dist/bundle/index.cjs +0 -41045
  51. package/dist/bundle/index.cjs.map +0 -1
  52. package/dist/bundle/index.d.cts +0 -187
  53. package/dist/consent/index.cjs +0 -204
  54. package/dist/consent/index.cjs.map +0 -1
  55. package/dist/consent/index.d.cts +0 -27
  56. package/dist/crdt/index.cjs +0 -152
  57. package/dist/crdt/index.cjs.map +0 -1
  58. package/dist/crdt/index.d.cts +0 -30
  59. package/dist/decrypt-partition-C0iDpbSd.d.cts +0 -558
  60. package/dist/derivations/index.cjs +0 -469
  61. package/dist/derivations/index.cjs.map +0 -1
  62. package/dist/derivations/index.d.cts +0 -74
  63. package/dist/dev-unlock-0Z6yxfS7.d.cts +0 -263
  64. package/dist/discriminant-BN9REW3o.d.cts +0 -60
  65. package/dist/errors-BAWO5Z5a.d.cts +0 -1500
  66. package/dist/forget/index.cjs +0 -43
  67. package/dist/forget/index.cjs.map +0 -1
  68. package/dist/forget/index.d.cts +0 -1
  69. package/dist/guards/index.cjs +0 -455
  70. package/dist/guards/index.cjs.map +0 -1
  71. package/dist/guards/index.d.cts +0 -39
  72. package/dist/hash-Db8ncXGr.d.cts +0 -63
  73. package/dist/history/index.cjs +0 -1245
  74. package/dist/history/index.cjs.map +0 -1
  75. package/dist/history/index.d.cts +0 -65
  76. package/dist/i18n/index.cjs +0 -1280
  77. package/dist/i18n/index.cjs.map +0 -1
  78. package/dist/i18n/index.d.cts +0 -41
  79. package/dist/index-BMmajblo.d.cts +0 -362
  80. package/dist/index-C1SC1EPe.d.cts +0 -1325
  81. package/dist/index-xJEPkvMb.d.cts +0 -93
  82. package/dist/index.cjs +0 -48100
  83. package/dist/index.cjs.map +0 -1
  84. package/dist/index.d.cts +0 -1050
  85. package/dist/indexing/index.cjs +0 -803
  86. package/dist/indexing/index.cjs.map +0 -1
  87. package/dist/indexing/index.d.cts +0 -36
  88. package/dist/kernel/index.cjs +0 -751
  89. package/dist/kernel/index.cjs.map +0 -1
  90. package/dist/kernel/index.d.cts +0 -11
  91. package/dist/lazy-builder-eYZzLEL1.d.cts +0 -304
  92. package/dist/materialized-views/index.cjs +0 -1518
  93. package/dist/materialized-views/index.cjs.map +0 -1
  94. package/dist/materialized-views/index.d.cts +0 -187
  95. package/dist/mime-magic-sdMzsfVK.d.cts +0 -103
  96. package/dist/overlay-views/index.cjs +0 -399
  97. package/dist/overlay-views/index.cjs.map +0 -1
  98. package/dist/overlay-views/index.d.cts +0 -102
  99. package/dist/periods/index.cjs +0 -1041
  100. package/dist/periods/index.cjs.map +0 -1
  101. package/dist/periods/index.d.cts +0 -24
  102. package/dist/predicate-BmhBSPCH.d.cts +0 -267
  103. package/dist/query/index.cjs +0 -3480
  104. package/dist/query/index.cjs.map +0 -1
  105. package/dist/query/index.d.cts +0 -4
  106. package/dist/sealed-record/index.cjs +0 -139
  107. package/dist/sealed-record/index.cjs.map +0 -1
  108. package/dist/sealed-record/index.d.cts +0 -123
  109. package/dist/session/index.cjs +0 -495
  110. package/dist/session/index.cjs.map +0 -1
  111. package/dist/session/index.d.cts +0 -48
  112. package/dist/shadow/index.cjs +0 -133
  113. package/dist/shadow/index.cjs.map +0 -1
  114. package/dist/shadow/index.d.cts +0 -19
  115. package/dist/snapshots/index.cjs +0 -937
  116. package/dist/snapshots/index.cjs.map +0 -1
  117. package/dist/snapshots/index.d.cts +0 -30
  118. package/dist/store/index.cjs +0 -1091
  119. package/dist/store/index.cjs.map +0 -1
  120. package/dist/store/index.d.cts +0 -501
  121. package/dist/strategy-BSxFXGzb.d.cts +0 -110
  122. package/dist/strategy-mJExw4LQ.d.cts +0 -1069
  123. package/dist/sync/index.cjs +0 -1062
  124. package/dist/sync/index.cjs.map +0 -1
  125. package/dist/sync/index.d.cts +0 -45
  126. package/dist/team/index.cjs +0 -2805
  127. package/dist/team/index.cjs.map +0 -1
  128. package/dist/team/index.d.cts +0 -120
  129. package/dist/transition-guard-tWZIsaXe.d.cts +0 -165
  130. package/dist/tx/index.cjs +0 -614
  131. package/dist/tx/index.cjs.map +0 -1
  132. package/dist/tx/index.d.cts +0 -39
  133. package/dist/types-CdVfiQgt.d.cts +0 -15275
  134. package/dist/ulid-DRH25k3y.d.cts +0 -66
  135. package/dist/util/index.cjs +0 -237
  136. package/dist/util/index.cjs.map +0 -1
  137. package/dist/util/index.d.cts +0 -79
  138. package/dist/with-materialized-view-DfgPcvi9.d.cts +0 -27
  139. package/dist/with-overlayed-view-Cvfkx1lg.d.cts +0 -13
  140. package/dist/with-rollup-nIxo7h9z.d.cts +0 -47
  141. /package/dist/{noydb-5MIBD77B.js.map → adapter/index.js.map} +0 -0
  142. /package/dist/{chunk-Y6YUWZTS.js.map → chunk-L5HHBOMS.js.map} +0 -0
  143. /package/dist/{types-DHn9lEP0.d.ts → index-DHn9lEP0.d.ts} +0 -0
package/dist/index.d.cts DELETED
@@ -1,1050 +0,0 @@
1
- import { aW as NoydbStore, bs as UserEnvelope, bc as PublicEnvelope, bt as GateName, bu as GatePolicy, bv as VaultPolicy, bw as ActiveTier, bx as FactorProof, aY as EncryptedEnvelope, by as SchemaUpdateStrategy, bz as TransformFn, bA as PersistedSchemaEnvelope, bB as UpdateDecision, bd as SealingKeyProvider, aU as UnlockedKeyring, bC as DirectoryConfig, bD as UserVisibility, bh as Vault, b1 as DiffEntry } from './types-CdVfiQgt.cjs';
2
- export { bE as AccessibleVault, bF as AffectedDocument, a_ as AppendInput, bG as ApproveWithdrawalOptions, bH as ArchivePolicy, bI as ArchiveResult, bJ as ArchiveRunOptions, bK as ArchiveStrategy, aE as ArrayOutputSpec, o as BLOB_CHUNKS_COLLECTION, p as BLOB_COLLECTION, r as BLOB_INDEX_COLLECTION, t as BLOB_SLOTS_PREFIX, u as BLOB_VERSIONS_PREFIX, bL as BUNDLE_STORE_POLICY, z as BlobObject, A as BlobPutOptions, C as BlobResponseOptions, E as BlobSet, bM as BuiltInGateName, be as BundleRecipient, a4 as CONSENT_AUDIT_COLLECTION, bN as CacheOptions, bO as CacheStats, bP as ChangeEvent, a$ as ChangeType, ad as ClosePeriodOptions, aN as Collection, bQ as CollectionChangeEvent, bR as CollectionConfig, bS as CollectionConflictResolver, bT as CollectionDescription, bU as CollectionDescriptor, au as CollectionFrame, b0 as CollectionInstant, bV as CollectionMeta, bW as CollectionStats, bX as ComputedFieldError, bY as ComputedFields, bZ as ComputedFn, b_ as Conflict, b$ as ConflictPolicy, c0 as ConflictStrategy, a5 as ConsentAuditEntry, a6 as ConsentAuditFilter, a7 as ConsentContext, a8 as ConsentOp, c1 as CrossTierAccessEvent, c2 as CustodyApi, K as DEFAULT_CHUNK_SIZE, c3 as DEFAULT_PUBLIC_ENVELOPE_SCHEMA, c4 as DELEGATIONS_COLLECTION, D as DICT_COLLECTION_PREFIX, c5 as DeepPartial, c6 as DeepPartialOrNull, c7 as DeferredNumberingConfig, c8 as DelegationToken, c9 as DeleteManyResult, ca as DerivationDescriptor, aC as DerivationStrategy, aG as DerivationStrategyHandle, aH as DerivedFromMeta, cb as DescribeOptions, cc as DescribedField, a as DictEntry, b as DictKeyDescriptor, c as DictionaryHandle, d as DictionaryOptions, cd as DirtyEntry, ce as DryRunResult, cf as DumpSchemaOptions, cg as ELEVATION_AUDIT_COLLECTION, ch as ElevatedHandle, ci as EmbeddingDescriptor, cj as EnrollAuthenticatorOptions, ck as EnrollAuthenticatorWrappingDEKsOptions, cl as EnrollAuthenticatorWrappingKEKOptions, cm as EnrollRecoveryResult, cn as ExportAccessibleOptions, co as ExportCapability, cp as ExportChunk, cq as ExportFormat, cr as ExportStreamOptions, cs as FactorKind, ct as FactorProofBundle, cu as FactorRequirement, cv as FenceDoc, cw as FenceState, cx as FieldChange, cy as FieldDescriptor, cz as FieldMeta, cA as FieldSource, cB as FormattedSequenceHandle, cC as FrozenSnapshotRef, cD as GhostRecord, cE as GrantCustodianOptions, cF as GrantOptions, ao as GuardChange, ap as GuardContext, an as GuardStrategy, ar as GuardStrategyHandle, cG as GuardViolation, cH as HistoryConfig, cI as HistoryEntry, aX as HistoryOptions, cJ as INDEXED_STORE_POLICY, cK as ImportCapability, cL as InferOutput, cM as InternalCollectionStats, cN as IssueDelegationOptions, cO as IssueMagicLinkGrantOptions, b2 as JsonPatch, b3 as JsonPatchOp, cP as KeyringAuthenticator, cQ as KeyringAuthenticatorWrappingDEKs, cR as KeyringAuthenticatorWrappingKEK, cS as KeyringFile, b4 as LedgerStore, cT as LiberateOptions, cU as LiberateResult, cV as LinkEndpointError, cW as LinkIntegrityError, cX as LinkOnDelete, cY as LinkRow, cZ as LinkSetHandle, c_ as LinkSpec, c$ as ListAccessibleVaultsOptions, d0 as ListPageResult, d1 as ListUsersOptions, d2 as LiveUserEnvelope, d3 as LocaleReadOptions, d4 as Lru, d5 as LruOptions, d6 as LruStats, d7 as MAGIC_LINK_CONTENT_INFO_PREFIX, d8 as MAGIC_LINK_GRANTS_COLLECTION, d9 as MAGIC_LINK_KEK_INFO_PREFIX, da as MagicLinkGrantPayload, db as MagicLinkGrantRecord, bo as MaterializedFromMeta, dc as MaterializedViewDescriptor, bp as MaterializedViewOutput, aK as MaterializedViewStrategy, aL as MaterializedViewStrategyHandle, dd as MemoryRecipientSealer, de as MemorySealingKeyProvider, df as NOYDB_BACKUP_VERSION, dg as NOYDB_FORMAT_VERSION, dh as NOYDB_KEYRING_VERSION, di as NOYDB_SYNC_VERSION, dj as NextOptions, dk as Noydb, aw as NoydbBundleStore, dl as NoydbEventMap, dm as NoydbOptions, dn as NumberingAssignment, T as ObjectListEntry, U as ObjectMeta, V as ObjectProjection, W as ObjectUrlOptions, ae as OpenPeriodOptions, aI as OutputSpec, aO as OverlayFieldMergeMode, aP as OverlayFieldMergeRule, dp as OverlayViewDescriptor, aM as OverlayedViewStrategy, aR as OverlayedViewStrategyHandle, af as PERIODS_COLLECTION, dq as PUBLIC_ENVELOPE_FIELDS, dr as PaperRecoveryDoc, ds as PaperRecoveryEntry, dt as PassphrasePolicy, du as PassphraseValidationResult, ag as PeriodRecord, dv as Permission, dw as Permissions, dx as PersistedSchemaKind, dy as PlaintextTranslatorContext, dz as PlaintextTranslatorFn, P as PolicyEnforcer, dA as PresenceHandle, dB as PresencePeer, aZ as PruneOptions, dC as PublicEnvelopeField, dD as PublicEnvelopeSchema, dE as PublicEnvelopeText, dF as PullMode, dG as PullOptions, dH as PullPolicy, dI as PullResult, dJ as PushMode, dK as PushOptions, dL as PushPolicy, dM as PushResult, dN as PutManyItemOptions, dO as PutManyOptions, dP as PutManyResult, X as PutObjectOptions, Y as PutUrlOptions, dQ as QueryAcrossOptions, dR as QueryAcrossResult, dS as QuickUnlockState, dT as QuickUnlockStore, dU as ReAuthOperation, bg as RecipientHint, bf as RecipientSealer, aJ as RecordOutputSpec, dV as RecoverPassphraseInput, dW as RecoverPassphraseResult, dX as RecoverUserOptions, dY as RecoveryProof, dZ as RejectWithdrawalOptions, d_ as RequestWithdrawalOptions, d$ as RequestWithdrawalResult, e0 as ResolvedPublicEnvelopeSchema, ax as RetentionPolicy, e1 as RetrieveHit, e2 as RetrieveOptions, e3 as RevokeOptions, aT as Role, e4 as RotatePassphraseInput, e5 as RotateRecoveryOptions, e6 as RotateRecoveryResult, e7 as SEALED_PASSPHRASE_RECORD_ID, e8 as SchemaDelta, e9 as SchemaIntrospection, S as ScriptWarning, ea as SealedEnvelope, eb as SealedPassphrase, ec as SearchEntry, ed as SearchOptions, ee as SearchResult, ef as SemanticType, eg as SequenceHandle, eh as SequenceOptions, ei as SequenceStore, ej as SessionPolicy, ek as SetPublicEnvelopeInput, el as ShamirRecoveryDoc, em as ShamirRecoveryEntry, bj as ShamirRecoveryProvider, Z as SlotInfo, _ as SlotRecord, en as SlotRewrapCeremony, eo as SlotRewrapContext, aA as SnapshotMeta, ep as StandardSchemaV1, eq as StandardSchemaV1Issue, er as StandardSchemaV1SyncResult, e as StaticDictDescriptor, es as StoreAuth, et as StoreAuthKind, eu as StoreCapabilities, ev as StoreTime, ew as SyncEngine, ex as SyncMetadata, ey as SyncPolicy, ez as SyncScheduler, eA as SyncSchedulerStatus, eB as SyncStatus, eC as SyncTarget, eD as SyncTargetRole, eE as SyncTransaction, eF as SyncTransactionResult, eG as TabChannel, eH as TabCoordinationOptions, eI as TabLockManager, eJ as TabPresence, eK as TabRole, eL as TierMode, eM as TransactionInvariant, eN as TranslatorAuditEntry, eO as TxCollection, bk as TxContext, eP as TxOp, eQ as TxVault, eR as USER_ENVELOPE_COLLECTION, eS as USER_ENVELOPE_MAX_BYTES, bq as UnionArmJoin, br as UnionSource, eT as Unsubscribe, eU as UpdateAuthenticatorOptions, eV as UpdateContext, eW as UpdateUserOptions, eX as UserApi, eY as UserEnvelopeCheckGate, eZ as UserEnvelopeOversizedError, e_ as UserEnvelopePresented, e$ as UserInfo, f0 as VaultBackup, b5 as VaultEngine, av as VaultFrame, b6 as VaultInstant, f1 as VaultMeta, f2 as VaultPolicyOnDisk, f3 as VaultSchemaSnapshot, f4 as VaultSnapshot, b7 as VerifyResult, $ as VersionRecord, f5 as WarningRules, f6 as WeakPassphraseError, f7 as WeakPassphraseReason, f8 as WithArchiveOptions, f9 as WithdrawAccessibleOptions, fa as WithdrawResult, fb as WithdrawalRequest, fc as WithdrawalRequestError, fd as WithdrawalRequestStatus, fe as WrappedDeksBlob, ff as WriteConflict, fg as WriteEvent, fh as WriteHook, fi as WriteQueue, fj as aesGcmOpen, b8 as applyPatch, fk as approveWithdrawal, fl as assertStrongPassphrase, fm as buildRecipientKeyringFile, fn as burnPaperRecoveryEntry, fo as compileSequenceFormat, b9 as computePatch, n as createEnforcer, fp as createNoydb, fq as createStore, fr as deriveMagicLinkContentKey, f as dictCollectionName, g as dictKey, ba as diff, h as enforceScript, fs as enrollAuthenticator, ft as estimateEntropy, fu as evalComputedFields, fv as evaluateExportCapability, fw as evaluateImportCapability, fx as exportAccessibleData, fy as findAuthenticator, bb as formatDiff, fz as hasExportCapability, fA as hasImportCapability, fB as hasRecoveryEnrolled, i as inferScripts, j as isDictCollectionName, k as isDictKeyDescriptor, fC as isLinkCollectionName, fD as isMagicLinkGrantExpired, fE as isPublicEnvelope, l as isStaticDictDescriptor, fF as issueDelegation, fG as keyringRecoverPassphrase, fH as keyringRotatePassphrase, fI as liberateVault, fJ as listMagicLinkGrants, fK as listUsers, fL as listUsersWithEnvelopes, fM as listWithdrawalRequests, fN as loadActiveDelegations, fO as loadPaperRecoveryEntries, fP as loadSealedPassphrase, fQ as loadShamirRecoveryEntries, fR as magicLinkGrantRecordId, a1 as memoryObjectProjection, fS as mintPaperRecoveryEntry, fT as mintShamirRecoveryEntry, fU as mintWrappedDeksBlob, fV as parseRsaOaepTlv, fW as parseSealedEnvelope, fX as readMagicLinkGrantRecord, fY as recoverUser, fZ as rejectWithdrawal, f_ as removeAuthenticator, f$ as requestWithdrawal, g0 as resolvePublicEnvelopeSchema, g1 as resolveSequenceKey, g2 as revokeDelegation, g3 as revokeMagicLinkGrant, g4 as runTransaction, g5 as savePaperRecoveryEntries, g6 as saveSealedPassphrase, g7 as saveShamirRecoveryEntries, g8 as sealRsaOaepTlv, s as staticDict, g9 as unwrapDeksFromBlob, ga as unwrapDeksFromPaperEntry, gb as unwrapDeksFromShamirEntry, gc as unwrapMagicLinkGrant, gd as validatePassphrase, ge as validatePublicEnvelopeInput, gf as validateSchemaInput, gg as validateSchemaOutput, v as validateSessionPolicy, gh as withArchive, gi as withDeferredNumbering, gj as withdrawAccessibleData, gk as writeMagicLinkGrant } from './types-CdVfiQgt.cjs';
3
- export { I as ImportExternalOptions, a as ImportExternalResult, b as ImportableCollection, d as detectMagic, c as detectMimeType, i as importExternalObjects, e as isPreCompressed } from './mime-magic-sdMzsfVK.cjs';
4
- export { AgeRoute, BlobLifecyclePolicy, BlobStoreRoute, CircuitBreakerOptions, HealthCheckOptions, LogLevel, LoggingOptions, MetricsOptions, OverrideOptions, OverrideTarget, RetryOptions, RouteStatus, RouteStoreOptions, RoutedNoydbStore, StoreCacheOptions, StoreMiddleware, StoreOperation, SuspendOptions, WrapBundleStoreOptions, WrappedBundleNoydbStore, createBundleStore, routeStore, withCache, withCircuitBreaker, withHealthCheck, withLogging, withMetrics, withRetry, wrapBundleStore, wrapStore } from './store/index.cjs';
5
- import { N as NoydbError } from './errors-BAWO5Z5a.cjs';
6
- export { H as AlreadyElevatedError, A as AmendmentForbiddenError, s as AttestationError, B as BackupCorruptedError, u as BackupLedgerError, v as BundleIntegrityError, w as BundleSealMismatchError, x as BundleVersionConflictError, J as ConflictError, K as CrossJoinSourceUnknownError, Q as CrossJoinTooLargeError, V as DanglingReferenceError, W as DataResidencyError, X as DebugPlaintextError, Y as DebugReservedFieldError, Z as DecryptionError, _ as DelegationTargetMissingError, i as DerivationCapExceededError, j as DerivationCycleError, k as DerivationDepthError, l as DerivationOutputShapeError, m as DerivationOutputUnknownError, D as DictKeyInUseError, a as DictKeyMissingError, $ as DirectoryDisabledError, a0 as ElevationExpiredError, a1 as EmbeddingDimMismatchError, a2 as EmbeddingModelMismatchError, a3 as ExportCapabilityError, F as FieldFrozenError, a4 as FilenameSanitizationError, a5 as ForgetStrategyNotConfiguredError, a6 as GroupCardinalityError, I as IllegalTransitionError, a7 as ImportCapabilityError, a8 as IndexRequiredError, a9 as IndexWriteFailureError, aa as InvalidKeyError, f as InvariantError, ab as JoinTooLargeError, ac as KeyringCorruptError, ad as KeyringExpiredError, ae as LedgerContentionError, L as LocaleNotSpecifiedError, z as MaterializedViewConfigError, C as MaterializedViewCycleError, E as MaterializedViewSourceUnknownError, G as MaterializedViewTooLargeError, af as MigrationRequiredError, M as MissingTranslationError, ag as NetworkError, ah as NoAccessError, ai as NonAdditiveSchemaChangeError, aj as NotFoundError, ak as NumberingUncertaintyError, O as OverlayBaseIsVirtualError, n as OverlayCollectionUnavailableError, o as OverlayIdMismatchError, p as OverlayNameCollisionError, al as PathEscapeError, am as PeriodClosedError, an as PermissionDeniedError, ao as PrivilegeEscalationError, ap as QuiesceTimeoutError, aq as ReadOnlyAtInstantError, ar as ReadOnlyError, as as ReadOnlyFrameError, at as RecordCekNotFoundError, g as RecordLockedError, R as ReservedCollectionNameError, au as ReservedVaultNameError, av as SchemaFenceError, aw as SchemaLockedError, ax as SchemaUpdateError, ay as SchemaValidationError, S as ScriptViolationError, q as SealedRecordExpiredError, r as SealedRecordMismatchError, az as SequenceContentionError, aA as SequenceOfflineError, c as SessionExpiredError, d as SessionNotFoundError, e as SessionPolicyError, aB as ShardProvisioningError, h as SnapshotNotFoundError, b as StaticDictReadonlyError, aC as StoreCapabilityError, aD as TamperedError, aE as TierDemoteDeniedError, aF as TierNotGrantedError, T as TranslatorNotConfiguredError, aG as UniqueConstraintError, U as UnknownDictCodeError, aH as UnknownShardError, aI as UnsupportedIndexOptionError, aJ as ValidationError, aK as VaultTemplateNotFoundError } from './errors-BAWO5Z5a.cjs';
7
- export { A as AutoCredential, m as AutoCredentialKind, c as CompressionAlgo, D as DecryptedRecord, N as NOYDB_BUNDLE_FORMAT_VERSION, e as NOYDB_BUNDLE_MAGIC, f as NOYDB_BUNDLE_PREFIX_BYTES, g as NoydbBundleHeader, h as NoydbBundleReadResult, R as ReadNoydbBundleOptions, W as WriteNoydbBundleOptions, i as decryptExtractedPartition, n as hasNoydbBundleMagic, r as readNoydbBundle, k as readNoydbBundleHeader, o as readNoydbBundlePublicEnvelope, l as resetBrotliSupportCache, w as writeNoydbBundle } from './decrypt-partition-C0iDpbSd.cjs';
8
- export { g as generateULID, i as isULID } from './ulid-DRH25k3y.cjs';
9
- export { D as DEFAULT_CROSS_JOIN_MAX_ROWS, a as DEFAULT_JOIN_MAX_ROWS, J as JoinContext, b as JoinLeg, c as JoinStrategy, d as JoinableSource, L as LiveQuery, e as LiveUpstream, O as OrderBy, Q as Query, f as QueryPlan, g as QuerySource, R as RefDescriptor, h as RefIntegrityError, i as RefMode, j as RefRegistry, k as RefScopeError, l as RefViolation, S as ScanBuilder, m as ScanPageProvider, n as applyJoins, o as buildLiveQuery, p as executePlan, q as isRefArray, r as ref, s as refArray, t as resetJoinWarnings } from './index-C1SC1EPe.cjs';
10
- export { L as LedgerEntry, c as canonicalJson, h as hashEntry, p as paddedIndex, a as parseIndex, s as sha256Hex } from './index-BMmajblo.cjs';
11
- export { a as CrdtMode, b as CrdtState, L as LwwMapState, R as RgaState, Y as YjsState, m as mergeCrdtStates, r as resolveCrdtSnapshot } from './strategy-BSxFXGzb.cjs';
12
- export { F as FuseOptions, b as base64ToBuffer, a as bufferToBase64, d as decryptBytes, c as decryptDeterministic, e as derivePresenceKey, f as encryptBytes, g as encryptDeterministic, h as fuseRetrieval } from './index-xJEPkvMb.cjs';
13
- export { TransactionStrategyOptions } from './tx/index.cjs';
14
- export { I as ImmutableGuardConfig, T as TransitionGuardConfig, i as immutableGuard, t as transitionGuard, w as withGuard } from './transition-guard-tWZIsaXe.cjs';
15
- import { M as RoundingMode } from './strategy-mJExw4LQ.cjs';
16
- export { j as AggregateResult, k as AggregateSpec, l as Aggregation, m as AggregationUpstream, G as GROUPBY_MAX_CARDINALITY, n as GROUPBY_WARN_CARDINALITY, o as GroupedAggregation, p as GroupedQuery, q as GroupedQueryN, t as GroupedRow, u as GroupedRowN, I as I18nMap, a as I18nTextDescriptor, b as I18nTextOptions, L as Layer, w as LiveAggregation, N as MoneyCurrencyError, P as MoneyDescriptor, Q as MoneyOptions, S as MoneyOptionsFixed, T as MoneyOptionsMulti, U as MoneyPrecisionError, V as MoneyUnsupportedError, O as OnMissing, c as OnMissingPolicy, x as Reducer, y as ReducerOptions, R as ResolveI18nOptions, d as applyI18nLocale, z as avg, C as count, D as groupAndReduce, i as i18nText, e as isI18nTextDescriptor, W as isMoneyDescriptor, E as max, F as min, X as money, H as reduceRecords, r as resolveI18nText, f as resolvePolicy, K as sum, v as validateI18nTextValue } from './strategy-mJExw4LQ.cjs';
17
- export { w as withDerivation, a as withRollup } from './with-rollup-nIxo7h9z.cjs';
18
- export { w as withMaterializedView } from './with-materialized-view-DfgPcvi9.cjs';
19
- export { a as Clause, C as CollectionIndexes, F as FieldClause, b as FilterClause, G as GroupClause, H as HashIndex, I as IndexDef, O as Operator, e as evaluateClause, c as evaluateFieldClause, r as readPath } from './predicate-BmhBSPCH.cjs';
20
- export { w as withOverlayedView } from './with-overlayed-view-Cvfkx1lg.cjs';
21
- export { SYNC_CREDENTIALS_COLLECTION, SyncCredential, credentialStatus, deleteCredential, getCredential, listCredentials, putCredential } from './team/index.cjs';
22
- export { C as CreateSessionOptions, a as CreateSessionResult, D as DevUnlockOptions, S as SessionToken, b as activeSessionCount, c as clearDevUnlock, d as createSession, e as enableDevUnlock, i as isDevUnlockActive, f as isSessionAlive, l as loadDevUnlock, r as resolveSession, g as revokeAllSessions, h as revokeSession } from './dev-unlock-0Z6yxfS7.cjs';
23
- export { i as isDiscriminant } from './discriminant-BN9REW3o.cjs';
24
- export { L as LEDGER_COLLECTION, a as LEDGER_DELTAS_COLLECTION, e as envelopePayloadHash } from './hash-Db8ncXGr.cjs';
25
- import './lazy-builder-eYZzLEL1.cjs';
26
- import '@noy-db/attestation';
27
-
28
- /**
29
- * Persistence helpers for per-principal user envelopes stored at
30
- * `_users/<keyringId>` (logically: `_meta/user/<keyringId>`).
31
- *
32
- * Unlike `_meta/policy` and `_meta/handle` which are plaintext, user
33
- * envelopes carry user data and are encrypted with a dedicated
34
- * {@link USER_ENVELOPE_COLLECTION} DEK (provisioned at vault open and
35
- * propagated to every keyring via the system-collection DEK path in
36
- * `team/keyring.ts`).
37
- *
38
- * This module is the **storage primitive** layer. The public API
39
- * (`vault.user.*`) sits on top of this; permission gates, own-only
40
- * write enforcement, and presence-channel propagation live there.
41
- *
42
- * @see docs/superpowers/specs/2026-05-05-user-envelope-design.md
43
- *
44
- * @module
45
- */
46
-
47
- /**
48
- * Read and decrypt the user envelope for `keyringId`. Returns `null`
49
- * when no envelope has been persisted (either the principal has never
50
- * called `updateMe`, or the keyring predates this feature).
51
- *
52
- * Decryption errors propagate — a tampered or wrong-keyed envelope
53
- * surfaces as the underlying crypto error rather than masquerading as
54
- * "not found".
55
- */
56
- declare function loadUserEnvelope<T = unknown>(store: NoydbStore, vault: string, keyringId: string, dek: CryptoKey): Promise<UserEnvelope<T> | null>;
57
- /**
58
- * Encrypt and persist the user envelope for `keyringId`. The new
59
- * version is `(prior._v ?? 0) + 1`. Pass `expectedVersion` to enable
60
- * optimistic-concurrency checks: a mismatch with the stored version
61
- * throws {@link ConflictError} with the actual stored version.
62
- *
63
- * `expectedVersion: 0` means "expect no prior envelope"; the write
64
- * succeeds only if no envelope exists yet.
65
- *
66
- * Soft-caps the JSON-serialized payload at {@link USER_ENVELOPE_MAX_BYTES};
67
- * larger payloads throw {@link UserEnvelopeOversizedError}.
68
- */
69
- declare function saveUserEnvelope<T>(store: NoydbStore, vault: string, keyringId: string, payload: T, dek: CryptoKey, expectedVersion?: number): Promise<UserEnvelope<T>>;
70
- /**
71
- * Delete the user envelope for `keyringId`. Idempotent — no error if
72
- * the envelope is already absent. Called from the keyring revoke path
73
- * (cascade-delete) and is a no-op for keyrings that never wrote.
74
- */
75
- declare function deleteUserEnvelope(store: NoydbStore, vault: string, keyringId: string): Promise<void>;
76
- /**
77
- * List the keyring ids that have a user envelope persisted in `vault`.
78
- * Order is store-defined — callers that need a stable order should sort.
79
- */
80
- declare function listUserEnvelopeIds(store: NoydbStore, vault: string): Promise<string[]>;
81
-
82
- /**
83
- * Default text tokenizer for scan-mode search (#308).
84
- *
85
- * NFKC-normalize → lowercase → split on Unicode letter/number runs. This is a
86
- * word-boundary tokenizer: it does **not** segment scripts written without
87
- * inter-word spaces (Thai, Lao, Khmer, CJK) — those collapse to one token per
88
- * run. For such data, a dictionary/ICU segmenter is the right `tokenizer`
89
- * (the engine takes one as a parameter); substring/`contains` matching is the
90
- * pragmatic fallback until then. See the #308 design note.
91
- */
92
- type Tokenizer = (text: string) => string[];
93
- declare const tokenize: Tokenizer;
94
-
95
- /**
96
- * Cache policy helpers — parse human-friendly byte budgets into raw numbers.
97
- *
98
- * Accepted shapes (case-insensitive on suffix):
99
- * number — interpreted as raw bytes
100
- * '1024' — string of digits, raw bytes
101
- * '50KB' — kilobytes (×1024)
102
- * '50MB' — megabytes (×1024²)
103
- * '1GB' — gigabytes (×1024³)
104
- *
105
- * Decimals are accepted (`'1.5GB'` → 1610612736 bytes).
106
- *
107
- * Anything else throws — better to fail loud at construction time than
108
- * to silently treat a typo as 0 bytes (which would evict everything).
109
- */
110
- /** Parse a byte budget into a positive integer number of bytes. */
111
- declare function parseBytes(input: number | string): number;
112
- /**
113
- * Estimate the in-memory byte size of a decrypted record.
114
- *
115
- * Uses `JSON.stringify().length` as a stand-in for actual heap usage.
116
- * It's a deliberate approximation: real V8 heap size includes pointer
117
- * overhead, hidden classes, and string interning that we can't measure
118
- * from JavaScript. The JSON length is a stable, monotonic proxy that
119
- * costs O(record size) per insert — fine when records are typically
120
- * < 1 KB and the cache eviction is the slow path anyway.
121
- *
122
- * Returns `0` (and the caller must treat it as 1 for accounting) if
123
- * stringification throws on circular references; this is documented
124
- * but in practice records always come from JSON-decoded envelopes.
125
- */
126
- declare function estimateRecordBytes(record: unknown): number;
127
-
128
- /**
129
- * Persistence helpers for `_meta/public-envelope`. Mirrors the
130
- * bypass-AES pattern used by `_meta/handle` and `_meta/policy` —
131
- * the document is plaintext JSON, the envelope's `_iv` field is
132
- * left empty.
133
- *
134
- * @module
135
- */
136
-
137
- /** Reserved id for the vault-level public envelope record. */
138
- declare const PUBLIC_ENVELOPE_RECORD_ID = "public-envelope";
139
- /**
140
- * Read the public envelope from `_meta/public-envelope`. Returns
141
- * `undefined` when no envelope has been persisted (fresh vault, or
142
- * a vault written before the feature was enabled). Tolerates
143
- * corrupted documents — a JSON parse failure surfaces as `undefined`,
144
- * not a thrown error, mirroring `_meta/handle`'s contract.
145
- */
146
- declare function loadPublicEnvelope(store: NoydbStore, vault: string): Promise<PublicEnvelope | undefined>;
147
- /** Persist the public envelope. Idempotent — overwrites any prior write. */
148
- declare function savePublicEnvelope(store: NoydbStore, vault: string, envelope: PublicEnvelope): Promise<void>;
149
- /**
150
- * Public, no-key reader. Plain function, not a method on `Noydb` —
151
- * the whole point is it works without an authenticated session, so
152
- * a UI can show "Acme 2026 Tax Records" before unlocking.
153
- *
154
- * Resolves any `name` / `description` locale map through the supplied
155
- * `locale` (when provided). Omitting `locale` returns the raw
156
- * envelope, which a multilingual picker can render as it pleases.
157
- */
158
- declare function readPublicEnvelope(store: NoydbStore, vault: string, opts?: {
159
- readonly locale?: string;
160
- }): Promise<PublicEnvelope | undefined>;
161
-
162
- /**
163
- * Why a gate denied a request. Stable across hub versions so consumers
164
- * can switch on the value in error UIs.
165
- */
166
- type PolicyDenyReason = 'insufficient-tier' | 'missing-factor' | 'stale-proof' | 'disabled' | 'shared-device-blocked';
167
- /**
168
- * Thrown by {@link checkGate} when the active session does not meet
169
- * the gate's requirements. Carries the gate name, the reason, and the
170
- * full required {@link GatePolicy} so error UIs can prompt the user
171
- * for the missing factor without re-reading the policy document.
172
- */
173
- declare class PolicyDeniedError extends NoydbError {
174
- readonly gate: GateName;
175
- readonly reason: PolicyDenyReason;
176
- readonly required: GatePolicy;
177
- constructor(gate: GateName, reason: PolicyDenyReason, required: GatePolicy, message?: string);
178
- }
179
- /**
180
- * Raised by `createNoydb({ ... })` when the developer omits a recovery
181
- * profile and `recover-passphrase` is not explicitly disabled. Vaults
182
- * MUST have at least one recovery path enrolled before being
183
- * production-ready (paper, shamir, multi-channel, or admin-mediated).
184
- *
185
- * The error message carries a pointer to the recovery design docs.
186
- */
187
- declare class RecoveryNotEnrolledError extends NoydbError {
188
- constructor(message?: string);
189
- }
190
- /**
191
- * Raised by `openVault` when a managed-passphrase-mode vault has no
192
- * STRONG recovery profile enrolled.
193
- *
194
- * Managed mode means the user never types a passphrase — the unlock
195
- * material lives in a `SealingKeyProvider` (`at-*` package). If that
196
- * provider's key is lost AND no strong recovery is enrolled, the
197
- * vault is irrecoverable. To prevent that footgun, managed-mode vaults
198
- * require at least one strong recovery profile (Shamir today;
199
- * multi-channel / admin-mediated when those ship).
200
- *
201
- * Paper recovery alone is NOT strong under managed mode: the user has
202
- * no memorized passphrase to fall back on, so losing the paper sheet =
203
- * losing every record permanently.
204
- *
205
- * Bootstrap with `db.openVaultAndEnrollRecovery(vault, { recovery: [{ profile: "shamir", k, n }] })`
206
- * to atomically create-and-enroll, or call `db.enrollRecovery(vault, { profile: "shamir", ... })`
207
- * separately before re-attempting `openVault`.
208
- */
209
- declare class ManagedRecoveryNotEnrolledError extends NoydbError {
210
- readonly vault: string;
211
- constructor(vault: string);
212
- }
213
- /**
214
- * Raised by `db.recoverPassphrase` / `db.enrollRecovery` /
215
- * `db.rotateRecovery` when the developer requests a recovery profile
216
- * not yet wired in this hub release.
217
- *
218
- * Implemented: `paper` and `shamir`.
219
- * Pending: `multi-channel` and `admin-mediated` (follow-up slices).
220
- *
221
- * The carried `profile` and `tracking` fields let consumers steer the
222
- * UI ("multi-channel recovery is not yet wired up — open issue #N to follow").
223
- */
224
- declare class RecoveryProfileNotImplementedError extends NoydbError {
225
- readonly profile: string;
226
- readonly tracking: string;
227
- constructor(profile: string, tracking: string);
228
- }
229
-
230
- /**
231
- * Default policy for personal vaults and SMB deployments — the gates
232
- * that need an off-device factor get one (TOTP / email-OTP / paper
233
- * recovery), the rest take a tier-1 unlock alone. Tier-3 (PIN) is the
234
- * floor only for `rotate-unlock` because that's the
235
- * "change my PIN" flow.
236
- *
237
- * The unspecified gates (e.g. `view-user-auth`) inherit the engine
238
- * default of `{ enabled: false, minTier: 1 }` — they fail closed.
239
- *
240
- * @see docs/subsystems/session-tiers.md → Built-in gates
241
- */
242
- declare const PERSONAL_POLICY: VaultPolicy;
243
- /**
244
- * Strict policy for regulated deployments and shared workstations —
245
- * raises the phrase floor to 8 words, demands two distinct factors for
246
- * exports, and blocks export-on-shared-device. Use as a base for
247
- * `policy: { ...STRICT_POLICY, gates: { ...STRICT_POLICY.gates, ... } }`
248
- * tweaks.
249
- */
250
- declare const STRICT_POLICY: VaultPolicy;
251
- /**
252
- * Merge a developer override onto a preset. Unspecified gates inherit;
253
- * specified gates fully replace the preset's entry for that gate.
254
- *
255
- * Example:
256
- *
257
- * ```ts
258
- * mergePolicy(PERSONAL_POLICY, {
259
- * gates: {
260
- * 'app:approve-large-payment': { minTier: 2, factors: [{ anyOf: ['totp'] }] },
261
- * },
262
- * })
263
- * // → PERSONAL_POLICY plus the new app gate; existing gates intact.
264
- * ```
265
- */
266
- declare function mergePolicy(base: VaultPolicy, override?: Partial<VaultPolicy>): VaultPolicy;
267
-
268
- /**
269
- * Policy gate engine — the {@link checkGate} entry point.
270
- *
271
- * Given a configured {@link VaultPolicy}, an active session tier, and
272
- * the factor proofs an actor is presenting, decide whether the gate
273
- * permits the action. On denial, throws {@link PolicyDeniedError} with
274
- * a stable {@link PolicyDenyReason} so consumers can branch in error
275
- * UIs.
276
- *
277
- * @see docs/subsystems/session-tiers.md → checkGate() API
278
- *
279
- * @module
280
- */
281
-
282
- /** Default freshness window — 5 minutes. */
283
- declare const DEFAULT_FRESHNESS_MS: number;
284
- /** Caller-supplied context for one `checkGate` invocation. */
285
- interface CheckGateContext {
286
- /** Tier the active session currently holds. */
287
- readonly activeTier: ActiveTier;
288
- /** Proofs the actor is presenting for this gate. */
289
- readonly factors?: ReadonlyArray<FactorProof>;
290
- /**
291
- * If the host knows the actor is on a shared device, set this to
292
- * `true` so the engine can apply `warn.sharedDevice` rules. Defaults
293
- * to `false`.
294
- */
295
- readonly sharedDevice?: boolean;
296
- /**
297
- * Override `now()` for tests. Defaults to `Date.now()`.
298
- * @internal
299
- */
300
- readonly now?: number;
301
- }
302
- /**
303
- * Decide whether `gate` permits the action under `context`. Throws
304
- * {@link PolicyDeniedError} on denial; resolves with `void` on success.
305
- *
306
- * Lookup rules:
307
- * - **Built-in gates** without a configured policy fail closed
308
- * (`enabled: false`).
309
- * - **App-defined gates** (`app:*`) without a configured policy are
310
- * treated as no-op (allow). The developer registered the policy if
311
- * they wanted enforcement; absence means the gate is informational.
312
- */
313
- declare function checkGate(policy: VaultPolicy, gate: GateName, context: CheckGateContext): Promise<void>;
314
- /**
315
- * Same as {@link checkGate} but returns a structured verdict instead
316
- * of throwing. Useful when an error UI wants to show the user
317
- * "you'll need TOTP plus a recovery code to do that" without first
318
- * triggering the action.
319
- */
320
- declare function describeGate(policy: VaultPolicy, gate: GateName, context: CheckGateContext): Promise<{
321
- ok: true;
322
- } | {
323
- ok: false;
324
- reason: PolicyDenyReason;
325
- required: GatePolicy;
326
- }>;
327
-
328
- /**
329
- * Persistence helpers for the vault-level policy document
330
- * (`_meta/policy`). Mirrors the bypass-AES pattern used by
331
- * `_meta/handle` — the policy document is plain JSON, the envelope's
332
- * `_iv` field is left empty.
333
- *
334
- * @see docs/subsystems/session-tiers.md → Storage location
335
- *
336
- * @module
337
- */
338
-
339
- /** Reserved collection name for vault-level metadata documents. */
340
- declare const META_COLLECTION = "_meta";
341
- /** Reserved id for the vault-level policy document. */
342
- declare const POLICY_RECORD_ID = "policy";
343
- /**
344
- * Read the vault-level policy from `_meta/policy`. Returns `undefined`
345
- * when no policy has been persisted (fresh vault, or a vault written
346
- * before the policy module landed). The caller falls back to the
347
- * default preset.
348
- *
349
- * Tolerates corrupted documents the same way `_meta/handle` does: a
350
- * JSON parse failure surfaces as `undefined`, not a thrown error, so
351
- * a bad write never permanently locks a vault.
352
- */
353
- declare function loadVaultPolicy(store: NoydbStore, vault: string): Promise<VaultPolicy | undefined>;
354
- /**
355
- * Persist the vault-level policy at `_meta/policy`. Idempotent — call
356
- * once at vault creation and again on `db.updatePolicy()` invocations.
357
- */
358
- declare function saveVaultPolicy(store: NoydbStore, vault: string, policy: VaultPolicy): Promise<void>;
359
-
360
- /**
361
- * Helpers for reading records out of a *plaintext* store (`encrypt: false`)
362
- * with native tooling — the programmatic core of a `noydb cat`-style unwrap.
363
- * See the plaintext/debug-store-mode design.
364
- */
365
-
366
- /**
367
- * Extract the record from a plaintext stored envelope, handling both layouts:
368
- *
369
- * - **classic plaintext** (`encrypt: false`): the record is JSON in `_data`.
370
- * - **debugPlaintext**: the record's fields are inlined beside the
371
- * `_`-prefixed metadata (marked by `_debug`).
372
- *
373
- * Returns `null` for an empty/absent body. Throws if handed an **encrypted**
374
- * envelope (non-empty `_iv`) — there is no key here; decrypt through the vault
375
- * instead. Intended for record envelopes, not blob chunks.
376
- *
377
- * @example
378
- * ```ts
379
- * // node script over a to-file store, no vault needed:
380
- * const env = JSON.parse(readFileSync('data/acme/invoices/inv-1.json', 'utf8'))
381
- * console.log(readPlaintextRecord(env)) // → { id: 'inv-1', total: '120.00', … }
382
- * ```
383
- */
384
- declare function readPlaintextRecord<T = Record<string, unknown>>(envelope: EncryptedEnvelope): T | null;
385
-
386
- /** Allow any schema change. Explicit blind / back-compat. */
387
- declare function blindUpdate(): SchemaUpdateStrategy;
388
- /** Allow additive changes; reject non-additive ones. The safety backstop. */
389
- declare function additiveOnly(): SchemaUpdateStrategy;
390
- /**
391
- * Reject schema changes. With `fields`, reject only when one of those
392
- * fields is added/removed/changed; otherwise reject any non-`none` delta.
393
- */
394
- declare function lockSchema(opts?: {
395
- readonly fields?: readonly string[];
396
- }): SchemaUpdateStrategy;
397
-
398
- /** The coordinatedCutover update strategy (single-step — no from/to). */
399
-
400
- declare function coordinatedCutover(opts: {
401
- readonly transform: TransformFn;
402
- }): SchemaUpdateStrategy;
403
-
404
- /**
405
- * Hub-core constants that must be referenceable without pulling any
406
- * subsystem chunk. Kept import-free.
407
- */
408
- /** Reserved fleet-wide control-plane vault name. Hub reserves it for an outward orchestration framework's state/control-plane vault. */
409
- declare const STATE_VAULT_NAME = "__noydb_state__";
410
-
411
- /**
412
- * Derive a {@link PersistedSchemaEnvelope} from a Standard Schema v1
413
- * validator. Supports zod 3 (via the optional `zod-to-json-schema` peer-dep)
414
- * and zod 4 (via its native `z.toJSONSchema()`); both are loaded lazily so
415
- * hub never statically imports zod. Other validator families write a stub
416
- * envelope flagging the kind.
417
- *
418
- * @see docs/superpowers/specs/2026-05-22-schema-dump-design.md
419
- *
420
- * @module
421
- */
422
-
423
- /**
424
- * Heuristic Zod detection — uses the Standard Schema v1 `~standard.vendor`
425
- * property (present in Zod v3.23+ and Zod v4+). Falls back to the
426
- * `_def.typeName` heuristic for older Zod v3 builds that predate Standard
427
- * Schema support.
428
- */
429
- declare function isZodSchema(value: unknown): boolean;
430
- declare function derivePersistedSchema(validator: unknown): Promise<PersistedSchemaEnvelope>;
431
-
432
- /**
433
- * Read / write the per-collection persisted-schema envelope. Mirrors the
434
- * standard noy-db record envelope shape and is **AES-GCM encrypted with
435
- * the collection's DEK** — the schema body (field names, enum values,
436
- * constraints) is sensitive metadata, so it gets the same encryption
437
- * envelope as the records it describes.
438
- *
439
- * Storage layout:
440
- *
441
- * <vault>/_schemas/<collection> → EncryptedEnvelope
442
- *
443
- * The DEK passed to {@link savePersistedSchema} / {@link loadPersistedSchema}
444
- * is the same key the collection uses for its records.
445
- *
446
- * @module
447
- */
448
-
449
- /** Reserved collection name where persisted schemas live. */
450
- declare const SCHEMAS_COLLECTION: "_schemas";
451
- /**
452
- * Read and decrypt the persisted-schema envelope for one collection.
453
- * Returns `undefined` when no envelope has been written or when decryption
454
- * fails (e.g. wrong DEK passed). Tolerates corrupted records — JSON parse
455
- * failures surface as `undefined`, mirroring `_meta/handle`'s contract.
456
- */
457
- declare function loadPersistedSchema(store: NoydbStore, vault: string, collection: string, dek: CryptoKey): Promise<PersistedSchemaEnvelope | undefined>;
458
- /**
459
- * Encrypt and persist a schema envelope for one collection. Always
460
- * overwrites any prior write (callers gate on hash equality before calling
461
- * to avoid no-op writes).
462
- */
463
- declare function savePersistedSchema(store: NoydbStore, vault: string, collection: string, dek: CryptoKey, payload: PersistedSchemaEnvelope): Promise<void>;
464
-
465
- /**
466
- * Orchestrate the derive → hash → skip-or-write cycle for a collection's
467
- * persisted JSON Schema. Called by the Vault at collection-registration
468
- * time when the developer opts in via `collection({ persistJsonSchema:
469
- * true })`.
470
- *
471
- * Skip semantics:
472
- *
473
- * - Zod validators: skip when the new hash equals the stored hash.
474
- * - Non-Zod (stub envelopes have hash=null): skip when the stored
475
- * envelope's `kind` matches the freshly-detected kind (since there's
476
- * no body to compare yet — a kind change is the only signal).
477
- *
478
- * @module
479
- */
480
-
481
- interface PersistSchemaResult {
482
- /** True when a fresh envelope was written to storage. */
483
- readonly written: boolean;
484
- /** True when an existing envelope matched and the write was skipped. */
485
- readonly skipped: boolean;
486
- /** The envelope that was either written or matched. */
487
- readonly envelope: PersistedSchemaEnvelope;
488
- /** The update-strategy decision, present when strategies ran. */
489
- readonly decision?: UpdateDecision;
490
- }
491
- declare function persistSchemaIfNeeded(opts: {
492
- readonly store: NoydbStore;
493
- readonly vault: string;
494
- readonly collectionName: string;
495
- readonly validator: unknown;
496
- readonly dek: CryptoKey;
497
- readonly strategies?: readonly SchemaUpdateStrategy[];
498
- }): Promise<PersistSchemaResult>;
499
-
500
- /**
501
- * FR-6 — Deed: sealed / hidden-owner provisioning.
502
- *
503
- * A **Deed** is a vault owned by a *latent* principal who never
504
- * authenticates. The owner credential (the random passphrase that
505
- * derives `KEK_owner`) is minted machine-side and sealed under a
506
- * **non-firm** {@link SealingKeyProvider} — that sealing boundary is
507
- * the cryptographic *inalienability anchor*: whoever holds the
508
- * provider (the client / their KMS) is the only party that can ever
509
- * re-derive `KEK_owner`. A firm-side custodian operates the vault
510
- * fully but can never reach the owner key — there is deliberately NO
511
- * firm-controlled fallback.
512
- *
513
- * Provisioning reuses the managed-mode seam:
514
- * - {@link resolveManagedSecret} mints + seals + persists the random
515
- * passphrase at `_meta/sealed-passphrase` (and unseals it on every
516
- * subsequent open through the same provider).
517
- * - {@link createOwnerKeyring} derives `KEK_owner` from that
518
- * passphrase and writes the `_keyring/<ownerUserId>` file.
519
- *
520
- * On top of that, a Deed writes a `_meta/deed` **marker**. The marker
521
- * is PLAINTEXT metadata — it records WHO the latent owner is and WHICH
522
- * sealing boundary protects them, so it must be readable without
523
- * unlocking the vault (a custodian or auditor inspecting the vault must
524
- * be able to see "this is a Deed vault, owner = X, sealed under Y"
525
- * without any key). The marker itself is therefore never sealed; only
526
- * the owner *credential* is.
527
- *
528
- * @module
529
- */
530
-
531
- /** Reserved id for the Deed marker under `_meta`. */
532
- declare const DEED_RECORD_ID: "deed";
533
- /**
534
- * Plaintext metadata recording a vault's latent-owner Deed. Persisted
535
- * at `_meta/deed`. Readable without unlocking the vault by design — it
536
- * carries no secret material, only the identity of the latent owner
537
- * and the sealing boundary that anchors inalienability.
538
- */
539
- interface DeedMarker {
540
- /** The latent owner principal — the user id of the `_keyring/<id>` owner file. */
541
- readonly ownerUserId: string;
542
- /**
543
- * The `SealingKeyProvider.id` the owner credential is sealed under.
544
- * The inalienability anchor: only the holder of this (non-firm)
545
- * provider can re-derive `KEK_owner`. Audit metadata — never secret.
546
- */
547
- readonly sealedUnder: string;
548
- /** Always `true` for a Deed — the owner never authenticates interactively. */
549
- readonly latent: true;
550
- /** ISO-8601 timestamp the Deed was issued. */
551
- readonly issuedAt: string;
552
- /**
553
- * ISO-8601 timestamp the vault was liberated (a new owner claimed it
554
- * via the audited Liberate ceremony), if any. Absent until liberation.
555
- */
556
- readonly liberatedAt?: string;
557
- }
558
- /**
559
- * Provision a Deed: a latent owner whose credential is sealed under
560
- * `sealing` (a NON-firm provider). Mints + seals the owner passphrase
561
- * via {@link resolveManagedSecret}, derives the owner keyring via
562
- * {@link createOwnerKeyring}, then writes the plaintext `_meta/deed`
563
- * marker. Returns the unlocked owner keyring.
564
- *
565
- * The returned keyring is the only in-memory window onto `KEK_owner`
566
- * for this call; the persistent re-entry point is the sealing provider
567
- * (re-run {@link resolveManagedSecret} with the same provider to
568
- * re-resolve the passphrase, then {@link createOwnerKeyring}/load to
569
- * unlock — no interactive passphrase is ever required).
570
- *
571
- * There is deliberately no firm-controlled fallback: the marker's
572
- * `sealedUnder` is the single cryptographic anchor of ownership.
573
- */
574
- declare function createDeedOwner(store: NoydbStore, vault: string, ownerUserId: string, sealing: SealingKeyProvider): Promise<UnlockedKeyring>;
575
- /**
576
- * Read the {@link DeedMarker} from `_meta/deed`, or `null` if the vault
577
- * has no Deed marker (i.e. it is not a Deed vault). Plaintext read — no
578
- * unlocking required.
579
- */
580
- declare function loadDeedMarker(store: NoydbStore, vault: string): Promise<DeedMarker | null>;
581
- /** Whether `vault` carries a Deed marker (a sealed/latent owner). */
582
- declare function isDeedVault(store: NoydbStore, vault: string): Promise<boolean>;
583
-
584
- /**
585
- * Authentication introspection.
586
- *
587
- * Three surfaces over the configured tier model and the actual
588
- * per-user enrollment state:
589
- *
590
- * 1. **Vault-wide English summary** — {@link describeAuthConfig}.
591
- * 2. **Vault-wide Mermaid diagram** — {@link diagramAuthConfig}.
592
- * 3. **Per-user introspection** — {@link describeUserAuth}, gated by
593
- * the `view-user-auth` policy gate (off by default).
594
- *
595
- * The per-user surface is held to a strict allowlist — fields not on
596
- * the allowlist are dropped, never rendered. The negative test in
597
- * `auth-introspection.test.ts` exercises the allowlist by feeding a
598
- * contrived keyring with fake "secret" fields and asserting that none
599
- * of them appear in the output.
600
- *
601
- * @module
602
- */
603
-
604
- /** Vault-wide English summary of the configured authentication graph. */
605
- declare function describeAuthConfig(store: NoydbStore, vault: string): Promise<string>;
606
- /**
607
- * Render the vault's auth graph as Mermaid `flowchart TB` source. The
608
- * caller pipes this through Mermaid (CLI or browser) to get an SVG.
609
- */
610
- declare function diagramAuthConfig(store: NoydbStore, vault: string): Promise<string>;
611
- /**
612
- * Render the per-user enrollment summary. Returns an empty
613
- * (non-throwing) string when the user has no keyring file — never
614
- * confirms or denies the existence of the user from the document
615
- * alone.
616
- *
617
- * Sanitization is strict: only the slot list, enrollment dates, and
618
- * recovery-profile counts are rendered. WebAuthn cred ids, OIDC
619
- * subject ids, password hashes, recovery codes, TOTP secrets — all
620
- * dropped at the allowlist boundary, not redacted.
621
- */
622
- declare function describeUserAuth(store: NoydbStore, vault: string, userId: string): Promise<string>;
623
- /** Bulk variant for owner dashboards. */
624
- declare function describeAllUsersAuth(store: NoydbStore, vault: string): Promise<Array<{
625
- userId: string;
626
- description: string;
627
- }>>;
628
-
629
- /**
630
- * Persistence helpers for the vault-level user-directory toggle
631
- * (`_meta/directory`). Mirrors the bypass-AES pattern used by
632
- * `_meta/policy` — the directory document is plain JSON, the
633
- * envelope's `_iv` field is left empty.
634
- *
635
- * @see docs/subsystems/user-envelope.md → Directory visibility
636
- * @see docs/subsystems/plaintext-bypass.md — every `_iv: ''` write site
637
- *
638
- * @module
639
- */
640
-
641
- /** Reserved id for the vault-level directory document. */
642
- declare const DIRECTORY_RECORD_ID = "directory";
643
- /**
644
- * Read the directory toggle from `_meta/directory`. Returns `undefined`
645
- * when no document has been persisted — callers treat that as the
646
- * default-on case (`{ enabled: true }`).
647
- *
648
- * Tolerates corrupted documents the same way `_meta/policy` does: a
649
- * JSON parse failure surfaces as `undefined`, not a thrown error, so a
650
- * bad write never permanently breaks team enumeration.
651
- */
652
- declare function readDirectoryConfig(store: NoydbStore, vault: string): Promise<DirectoryConfig | undefined>;
653
- /**
654
- * Persist the directory toggle at `_meta/directory`. Idempotent — call
655
- * on every `db.setDirectoryEnabled()` invocation. Owner-only at the
656
- * caller site; this primitive does not check roles.
657
- */
658
- declare function persistDirectoryConfig(store: NoydbStore, vault: string, config: DirectoryConfig): Promise<void>;
659
-
660
- /**
661
- * Persistence helpers for the per-user visibility flag
662
- * (`_meta/visibility/<keyringId>`). Mirrors the bypass-AES pattern used
663
- * by `_meta/policy` — the visibility document is plain JSON, the
664
- * envelope's `_iv` field is left empty.
665
- *
666
- * Stored alongside the keyring file rather than inside the encrypted
667
- * user envelope (`_users/<keyringId>`) because:
668
- *
669
- * - `UserEnvelope<T>.data` is opaque-to-hub by contract — hub does not
670
- * introspect or reserve any keys inside it. Adding `hidden` there
671
- * would violate that contract.
672
- * - `listUsersWithEnvelopes` filters by the flag, and the filter must
673
- * work even when decryption fails (legacy keyrings predating the
674
- * envelope feature, or a corrupted envelope).
675
- *
676
- * @see docs/subsystems/user-envelope.md → Directory visibility
677
- * @see docs/subsystems/plaintext-bypass.md — every `_iv: ''` write site
678
- *
679
- * @module
680
- */
681
-
682
- /** Prefix for per-user visibility records inside `_meta`. */
683
- declare const VISIBILITY_RECORD_PREFIX = "visibility/";
684
- /** Compose the `_meta` record id for a keyring's visibility doc. */
685
- declare function visibilityRecordId(keyringId: string): string;
686
- /**
687
- * Read the visibility flag for `keyringId`. Returns `undefined` when no
688
- * document has been persisted — callers treat that as the default-visible
689
- * case (`{ hidden: false }`).
690
- */
691
- declare function readUserVisibility(store: NoydbStore, vault: string, keyringId: string): Promise<UserVisibility | undefined>;
692
- /**
693
- * Persist the visibility flag for `keyringId` at
694
- * `_meta/visibility/<keyringId>`. Idempotent — call on every
695
- * `vault.user.setMyVisibility()` invocation. Own-only at the caller
696
- * site; this primitive does not enforce keyring ownership.
697
- */
698
- declare function persistUserVisibility(store: NoydbStore, vault: string, keyringId: string, visibility: UserVisibility): Promise<void>;
699
- /**
700
- * Delete the visibility flag for `keyringId`. Called from `revoke()`
701
- * alongside `deleteUserEnvelope` so the sidecar does not leak to a
702
- * re-granted principal with the same `userId`. Idempotent — the store's
703
- * `delete()` is already a no-op when the record is absent.
704
- */
705
- declare function deleteUserVisibility(store: NoydbStore, vault: string, keyringId: string): Promise<void>;
706
-
707
- /**
708
- * Return the ISO-4217 minor-unit scale for a currency code, or `null`
709
- * when the code is not in the known set (caller must supply an explicit
710
- * scale).
711
- */
712
- declare function scaleForCurrency(code: string): number | null;
713
-
714
- /**
715
- * Money-aware aggregation: exact `sum` / `min` / `max` over money
716
- * fields.
717
- *
718
- * The generic reducers (`aggregate/reducers.ts`) read a field via
719
- * `readNumber`, which coerces a string (the stored scaled-integer form
720
- * of money, e.g. `'12345'`) to `0` — so an un-wrapped money `sum` would
721
- * silently return zero. {@link wrapMoneyReducers} rewrites any `sum` /
722
- * `min` / `max` over a declared money field into a reducer that
723
- * accumulates per-currency `BigInt` totals of the stored integers, so
724
- * the result is exact for any magnitude (past `Number.MAX_SAFE_INTEGER`
725
- * included).
726
- *
727
- * Results are currency-aware and never silently mix currencies:
728
- * - **fixed** mode → a single exact decimal string.
729
- * - **multi** mode → an exact `Record<currency, string>` map.
730
- * - **`sum` with `convertTo` + `fx`** → a single exact string, with
731
- * each currency converted via BigInt arithmetic (no float).
732
- *
733
- * `remove()` is implemented for every money reducer so they participate
734
- * in incremental live-aggregation and materialized-view maintenance
735
- * exactly like the generic reducers they replace.
736
- */
737
-
738
- type FxRates = Record<string, number | string>;
739
-
740
- /**
741
- * Exact money arithmetic helpers (#337) — `mulRate` and `allocate`.
742
- *
743
- * Both operate on the canonical decoded string form that `get()`
744
- * returns (`'10000.00'`), entirely in scaled-`BigInt` space — no
745
- * floating-point step anywhere, exact past 2^53. They are pure
746
- * functions with no vault or descriptor dependency: the working scale
747
- * is inferred from the amount's fractional digits (a canonical money
748
- * string always carries exactly the field's scale) or pinned with
749
- * `opts.scale`.
750
- *
751
- * Why these two: app-side invariants of the form
752
- * `Σ parts === whole` (receipt totals, net-zero WHT pairs, proration)
753
- * carry ±0.01 tolerances ONLY because the math is major-unit floats +
754
- * round2. `mulRate` (VAT-style rate application with explicit
755
- * rounding) and `allocate` (largest-remainder split — parts sum to the
756
- * input EXACTLY, by construction) make those tolerances zero.
757
- */
758
-
759
- interface MulRateOptions {
760
- /**
761
- * Output scale (fraction digits). Defaults to the amount's own
762
- * fractional digits — for a canonical money string that IS the
763
- * field's scale.
764
- */
765
- readonly scale?: number;
766
- /** Rounding for the final re-scale. Default `'half-up'`. */
767
- readonly rounding?: RoundingMode;
768
- }
769
- interface AllocateOptions {
770
- /** Working scale. Defaults to the amount's own fractional digits. */
771
- readonly scale?: number;
772
- }
773
- /**
774
- * Multiply a money amount by a decimal rate, exactly.
775
- *
776
- * The rate is parsed at its OWN full precision (`0.07` → `7` at scale
777
- * 2), the product computed in `BigInt` at `amountScale + rateScale`,
778
- * then re-scaled back to the output scale with the requested rounding —
779
- * one rounding step, at the very end.
780
- *
781
- * ```ts
782
- * mulRate('10000.00', 0.07) // '700.00' (VAT)
783
- * mulRate('33.33', '0.07') // '2.33' (half-up)
784
- * mulRate('33.33', 0.07, { rounding: 'floor' }) // '2.33'
785
- * mulRate(100, 0.07, { scale: 2 }) // '7.00'
786
- * ```
787
- */
788
- declare function mulRate(amount: number | string, rate: number | string, opts?: MulRateOptions): string;
789
- /**
790
- * Split a money amount across weighted buckets with ZERO drift: the
791
- * returned parts sum to the input exactly, by construction
792
- * (largest-remainder method).
793
- *
794
- * Each bucket gets `floor(amount × weightᵢ / Σweights)`; the leftover
795
- * minor units (always fewer than the bucket count) go one each to the
796
- * buckets with the largest truncated remainders — ties broken by
797
- * position, earlier bucket first. Weights are parsed as exact decimals
798
- * (no float division anywhere); they must be non-negative with a
799
- * positive sum.
800
- *
801
- * ```ts
802
- * allocate('100.00', [1, 1, 1]) // ['33.34', '33.33', '33.33']
803
- * allocate('0.05', [3, 7]) // ['0.02', '0.03']
804
- * allocate('-100.00', [1, 1, 1]) // ['-33.34', '-33.33', '-33.33']
805
- * ```
806
- */
807
- declare function allocate(amount: number | string, weights: ReadonlyArray<number | string>, opts?: AllocateOptions): string[];
808
-
809
- /**
810
- * Branded money output type (#338).
811
- *
812
- * The decoded read shape of a money field is an exact decimal STRING
813
- * (`'10000.00'`) — but a hand-written schema types it `string | number`,
814
- * which is honest about the input side and unhelpful on the output
815
- * side: every read site hand-coerces, and a missed coercion passes
816
- * typecheck silently (then surfaces as a runtime template warning, or
817
- * worse, as `'10000.00' * 100` arithmetic).
818
- *
819
- * {@link MoneyString} is the output-side brand: a `string` that has
820
- * been through noy-db's decode (or {@link asMoney}'s guard). Branding
821
- * is type-level only — zero runtime cost on the read path.
822
- *
823
- * ## Wiring the brand through a validator (the input/output asymmetry)
824
- *
825
- * Keep the permissive `string | number` on the INPUT side so write
826
- * sites are untouched, and brand the OUTPUT side. With Zod:
827
- *
828
- * ```ts
829
- * import type { MoneyString } from '@noy-db/hub'
830
- *
831
- * const moneyValue = z.union([z.number(), z.string()]) as unknown as
832
- * z.ZodType<MoneyString, z.ZodTypeDef, string | number>
833
- *
834
- * const Invoice = z.object({ id: z.string(), total: moneyValue })
835
- * type InvoiceOut = z.output<typeof Invoice> // total: MoneyString
836
- * type InvoiceIn = z.input<typeof Invoice> // total: string | number
837
- * ```
838
- *
839
- * The cast is sound for fields declared in `moneyFields`: reads pass
840
- * through `decodeMoneyFields`, which always produces the canonical
841
- * decimal string.
842
- */
843
- declare const MONEY_BRAND: unique symbol;
844
- /**
845
- * An exact decimal string produced by noy-db's money decode
846
- * (`'10000.00'`). The brand exists only at the type level — at runtime
847
- * a `MoneyString` is a plain string.
848
- */
849
- type MoneyString = string & {
850
- readonly [MONEY_BRAND]: true;
851
- };
852
- /**
853
- * Runtime-guarded cast to {@link MoneyString}. Accepts a decimal string
854
- * or a number, returns the canonical decimal string branded — throws
855
- * `MoneyUnsupportedError` on anything non-finite / non-decimal. Use at
856
- * trust boundaries (deserialized JSON, route params); values read
857
- * through `get()`/`list()` are already canonical.
858
- */
859
- declare function asMoney(value: string | number): MoneyString;
860
- /** Type guard: is `value` a decimal string acceptable as money? */
861
- declare function isMoneyString(value: unknown): value is MoneyString;
862
- /**
863
- * The ONE sanctioned escape hatch to a JS `number` — explicit because
864
- * the conversion is lossy past 2^53. For display math and chart axes;
865
- * never feed the result back into stored amounts (use `mulRate` /
866
- * `allocate` for exact arithmetic).
867
- */
868
- declare function moneyNumber(value: MoneyString | string | number): number;
869
-
870
- /**
871
- * Hierarchical access — tier-aware keyring helpers.
872
- *
873
- * The keyring's existing `deks: Map<string, CryptoKey>` is keyed by
874
- * collection name. extends the key space:
875
- *
876
- * `'invoices'` — tier-0 DEK (unchanged from v0.x)
877
- * `'invoices#1'` — tier-1 DEK
878
- * `'invoices#2'` — tier-2 DEK
879
- *
880
- * Tier 0 keeps the bare collection name so any keyring written
881
- * before tiers existed loads without migration. Tiers ≥ 1 use `#N`
882
- * suffixes that
883
- * would be invalid as user-supplied collection names (see
884
- * `ReservedCollectionNameError` — `#` is reserved).
885
- *
886
- * @module
887
- */
888
-
889
- /** Canonical DEK key for a given collection + tier. Tier 0 → bare name. */
890
- declare function dekKey(collection: string, tier: number): string;
891
- /**
892
- * Returns the user's effective clearance for a given collection: the
893
- * maximum tier for which their keyring holds a DEK. Falls back to 0
894
- * when the user has only the tier-0 DEK (or none — the getDEK caller
895
- * will raise separately).
896
- */
897
- declare function effectiveClearance(keyring: UnlockedKeyring, collection: string): number;
898
- /**
899
- * Assert the caller is cleared for the requested tier. Owners and
900
- * admins always pass (they can mint any new tier DEK on demand);
901
- * other roles must already hold the tier DEK — via a prior grant or
902
- * an active delegation — otherwise this throws `TierNotGrantedError`.
903
- *
904
- * This gate runs BEFORE `getDEK()` on the mutation path so a
905
- * non-cleared operator never has the opportunity to silently
906
- * auto-create a tier DEK they shouldn't have.
907
- */
908
- declare function assertTierAccess(keyring: UnlockedKeyring, collection: string, tier: number): void;
909
-
910
- /**
911
- * Vault-level diff orchestrator.
912
- *
913
- * Compares a live `Vault`'s plaintext state against a candidate state
914
- * (another vault, a plain `{ collection: records[] }` map, or a vault
915
- * dump JSON) and returns a structured `VaultDiff` plan listing the
916
- * records that would be added, modified, or deleted to bring the live
917
- * vault into the candidate's shape.
918
- *
919
- * Builds on two existing record-level helpers:
920
- *
921
- * 1. `diff(a, b)` from `./history/diff.ts` — emits dot-pathed
922
- * `DiffEntry[]` with `type: 'added' | 'removed' | 'changed'` for
923
- * each changed field of two records. Used here for the
924
- * `fieldDiffs` of every `modified` entry, and (with empty result)
925
- * as the default deep-equal check.
926
- *
927
- * 2. `Vault.exportStream()` from `./vault.ts` — the canonical
928
- * decrypt-and-stream-records iterator. Used to walk both sides
929
- * when the candidate is itself a `Vault`. ACL-scoped: collections
930
- * the caller can't read silently drop out, the same way every
931
- * other plaintext-emitting export pipeline filters them.
932
- *
933
- * The new orchestration is the **vault-level** enumeration: bucket
934
- * each record id into added (only in candidate), deleted (only in
935
- * vault), or modified (in both with field changes); leave the
936
- * field-level granularity to the existing `diff()`.
937
- *
938
- * Use cases:
939
- *
940
- * - Import preview (`@noy-db/as-*` `fromString` returns a plan
941
- * whose body is a `VaultDiff`).
942
- * - Backup verification ("does this `.noydb` bundle from yesterday
943
- * match the current vault?").
944
- * - Two-vault reconciliation ("what's different between Office A
945
- * and Office B before we sync?").
946
- * - Test assertions (golden-file testing with one-liner
947
- * `expect(plan.summary).toEqual(...)`).
948
- *
949
- * @module
950
- */
951
-
952
- /** Per-record entry shape — added and deleted records carry only the record value. */
953
- interface VaultDiffEntry<T = unknown> {
954
- readonly collection: string;
955
- readonly id: string;
956
- readonly record: T;
957
- /**
958
- * Unencrypted envelope metadata for the RECEIVER-side record.
959
- * Populated only when `diffVault` is called with `{includeMetadata: true}`.
960
- * Default: `undefined` (zero extra reads, no behavior change).
961
- *
962
- * Populated for `modified` (the CURRENT receiver state, before the candidate
963
- * is applied) and `deleted` (the receiver envelope of the record being
964
- * removed). `added` entries have no receiver envelope at diff time, so their
965
- * `metadata` is always absent.
966
- */
967
- readonly metadata?: {
968
- readonly version: number;
969
- readonly timestamp: string;
970
- readonly by?: string;
971
- readonly source?: string;
972
- readonly sourceTs?: string;
973
- };
974
- }
975
- /** Modified records carry both halves of the diff plus the field-level breakdown. */
976
- interface VaultDiffModifiedEntry<T = unknown> extends VaultDiffEntry<T> {
977
- /** The record as it stands in the live vault. */
978
- readonly before: T;
979
- /** Top-level keys whose values differ between `before` and `record`. */
980
- readonly fieldsChanged: readonly string[];
981
- /**
982
- * Field-level diff entries from `diff(before, record)`. Reuses the
983
- * existing per-record diff helper so consumers can render git-style
984
- * `path: from → to` rows without re-walking the records.
985
- */
986
- readonly fieldDiffs: readonly DiffEntry[];
987
- }
988
- interface VaultDiff<T = unknown> {
989
- readonly added: readonly VaultDiffEntry<T>[];
990
- readonly modified: readonly VaultDiffModifiedEntry<T>[];
991
- readonly deleted: readonly VaultDiffEntry<T>[];
992
- /** Only populated when `options.includeUnchanged: true`. */
993
- readonly unchanged: readonly VaultDiffEntry<T>[] | undefined;
994
- readonly summary: {
995
- readonly add: number;
996
- readonly modify: number;
997
- readonly delete: number;
998
- readonly total: number;
999
- };
1000
- /**
1001
- * Format the diff as a human-readable string.
1002
- *
1003
- * - `'count'` — one line, just the numbers (`12 added · 3 modified · 0 deleted`)
1004
- * - `'one-line'` — count plus a single overview line
1005
- * - `'full'` — count + one row per added/modified/deleted record (default)
1006
- */
1007
- format(opts?: {
1008
- detail?: 'count' | 'one-line' | 'full';
1009
- }): string;
1010
- }
1011
- interface DiffOptions {
1012
- /** Restrict the diff to a subset of collections. */
1013
- readonly collections?: readonly string[];
1014
- /** Field on each record that carries its id. Defaults to `'id'`. */
1015
- readonly idKey?: string;
1016
- /** Override the default deep-equal check for "modified vs unchanged". */
1017
- readonly compareFn?: (a: unknown, b: unknown) => boolean;
1018
- /** If true, include unchanged records in the diff (off by default to save memory). */
1019
- readonly includeUnchanged?: boolean;
1020
- /**
1021
- * When `true`, each entry in `added`, `modified`, and `deleted` will carry a
1022
- * `metadata` field with the RECEIVER-side envelope metadata
1023
- * (`version`, `timestamp`, `by?`, `source?`, `sourceTs?`).
1024
- *
1025
- * Off by default — no extra adapter reads, no behavior change for existing callers.
1026
- * (FR-5 read surface, #445)
1027
- */
1028
- readonly includeMetadata?: boolean;
1029
- }
1030
- /**
1031
- * Candidate state to diff the vault against:
1032
- *
1033
- * - A `Vault` instance — both sides are walked via `exportStream()`.
1034
- * - A `Record<collection, records[]>` map — same shape `as-json.toObject()`
1035
- * produces. Useful for diffing parsed file content against the live vault.
1036
- * - A `VaultDump` (output of `vault.dump()`) — a JSON string carrying the
1037
- * full vault state. Parsed and reduced to the map shape above.
1038
- */
1039
- type DiffCandidate<T = unknown> = Vault | Record<string, readonly T[]> | string;
1040
- /**
1041
- * Compute the diff between a live vault and a candidate state.
1042
- *
1043
- * Returns a fully buffered `VaultDiff` — no streaming. Memory cost is
1044
- * O(n + m) in the row count of vault + candidate. For documented
1045
- * 1K-50K-record vaults this is fine; a streaming variant lands as a
1046
- * follow-up if a > 100K-record consumer arrives.
1047
- */
1048
- declare function diffVault<T = unknown>(vault: Vault, candidate: DiffCandidate<T>, options?: DiffOptions): Promise<VaultDiff<T>>;
1049
-
1050
- export { ActiveTier, type AllocateOptions, type CheckGateContext, DEED_RECORD_ID, DEFAULT_FRESHNESS_MS, DIRECTORY_RECORD_ID, type DeedMarker, type DiffCandidate, DiffEntry, type DiffOptions, DirectoryConfig, EncryptedEnvelope, FactorProof, type FxRates, GateName, GatePolicy, META_COLLECTION, ManagedRecoveryNotEnrolledError, type MoneyString, type MulRateOptions, NoydbError, NoydbStore, PERSONAL_POLICY, POLICY_RECORD_ID, PUBLIC_ENVELOPE_RECORD_ID, type PersistSchemaResult, PersistedSchemaEnvelope, PolicyDeniedError, type PolicyDenyReason, PublicEnvelope, RecoveryNotEnrolledError, RecoveryProfileNotImplementedError, RoundingMode, SCHEMAS_COLLECTION, STATE_VAULT_NAME, STRICT_POLICY, SchemaUpdateStrategy, SealingKeyProvider, type Tokenizer, UnlockedKeyring, UpdateDecision, UserEnvelope, UserVisibility, VISIBILITY_RECORD_PREFIX, Vault, type VaultDiff, type VaultDiffEntry, type VaultDiffModifiedEntry, VaultPolicy, additiveOnly, allocate, asMoney, assertTierAccess, blindUpdate, checkGate, coordinatedCutover, createDeedOwner, dekKey, deleteUserEnvelope, deleteUserVisibility, derivePersistedSchema, describeAllUsersAuth, describeAuthConfig, describeGate, describeUserAuth, diagramAuthConfig, diffVault, effectiveClearance, estimateRecordBytes, isDeedVault, isMoneyString, isZodSchema, listUserEnvelopeIds, loadDeedMarker, loadPersistedSchema, loadPublicEnvelope, loadUserEnvelope, loadVaultPolicy, lockSchema, mergePolicy, moneyNumber, mulRate, parseBytes, persistDirectoryConfig, persistSchemaIfNeeded, persistUserVisibility, readDirectoryConfig, readPlaintextRecord, readPublicEnvelope, readUserVisibility, savePersistedSchema, savePublicEnvelope, saveUserEnvelope, saveVaultPolicy, scaleForCurrency, tokenize, visibilityRecordId };