@cloudbitmaps/roaring 0.25.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts", "../src/open-charging-storage.ts", "../src/reserved-namespace.ts", "../src/ts-roaring/bitmap.ts", "../src/portable/layout.ts", "../src/portable/popcount.ts", "../src/ts-roaring/containers.ts", "../src/ts-roaring/iterator.ts", "../src/ts-roaring/wire.ts", "../src/roaring-codec.ts", "../src/system-clock.ts", "../src/system-entropy.ts", "../src/option-keys.ts", "../src/lease-guards.ts", "../src/wire-store.ts", "../src/options.ts", "../src/bitmap.ts", "../src/count-route.ts"],
4
- "sourcesContent": ["/**\n * CloudRoaring \u2014 distributed, cloud-native Roaring Bitmaps, read from object storage.\n *\n * The `CloudRoaring` class is the read engine over **loaded** segments: write-once `.crbm` generations in an\n * object store, behind one registry pointer per segment. You wire storage **once**, as a single config object:\n * pass a **backend** as `storage` \u2014 `S3Storage`, `GcsStorage`, `AzureBlobStorage`, `LocalFsStorage` or\n * `MemoryStorage` \u2014 and it carries both halves, the generations and the pointer, from one bucket and one\n * prefix. Add `encryption: { keystore }` for encryption-at-rest / crypto-shred.\n *\n * Two narrower shapes are also accepted for `storage`: a bare {@link IStorageDriver}, which has no pointer and\n * so resolves generations by list-scanning storage (**cleartext and read-only**), and a {@link StorageChunkSource}\n * of your own, a read source the store uses as it is (both ports are in `@cloudbitmaps/core/driver-kit`).\n *\n * **Data gets in by loading a generation**, never by mutating one: `store.load()` streams a set of ids into one\n * immutable object and advances the segment's pointer to it. The pointer only moves forward, so a load out-raced by\n * a newer generation reports `superseded` instead of landing, and so does one that read the row when the row has\n * changed since. Every other write in the library is a load in\n * disguise \u2014 `intersectInto`/`unionInto`/`andNotInto` write a new generation of their destination, and\n * `eraseSubject` rewrites a generation without one id. Reads (`has`/`count`/`iterate`/`intersect`/`union`/`andNot`)\n * see whole, checksum-verified generations and nothing else.\n *\n * In-process lifecycle helpers \u2014 `eraseSubject`, `subjectReport`, `dropSegment`, `retireExpired`,\n * `checkConsistency`, `exportSegments` \u2014 reuse the store's own drivers, so you never re-pass them (they need the\n * store built with a backend). See the README and the getting-started guide.\n */\n\nimport {\n BoundedLru,\n PinnedStorageChunkSource,\n segmentKey,\n CrbmStorageChunkSource,\n DEFAULT_BUDGET,\n DEFAULT_RETRY_POLICY,\n withRetry,\n NOOP_METRICS,\n RetryingStorageChunkSource,\n SegmentEngine,\n LEASE_SKEW_MS,\n BudgetExceededError,\n LeaseExpiredError,\n MAX_LEASE_MS,\n NotFoundError,\n UnsupportedError,\n ValidationError,\n errorKind,\n WriteConflictError,\n checkBudget,\n collectWithinBudget,\n excludingReservedRows,\n dropSegment,\n eraseIdFromSegment,\n findIdUnderTombstone,\n judgeLoad,\n loadSegment,\n loadSegmentChunks,\n compileCombineMany,\n rebindCombineMany,\n runCombineMany,\n mapWithConcurrency,\n resolveBudget,\n resolvePerOpBudget,\n retireExpired,\n runConsistencyCheck,\n runExport,\n setSegmentRetention,\n clearSegmentRetention,\n getSegmentRetention,\n releaseLease,\n safeMetrics,\n splitId,\n takeLease,\n} from '@cloudbitmaps/core';\nimport {\n pointerIdOf,\n requireBool,\n requirePositiveInt,\n validateSegmentRef,\n} from '@cloudbitmaps/core/driver-kit';\nimport type { PinLease } from '@cloudbitmaps/core';\nimport type {\n Budget,\n BudgetOption,\n GenerationEntry,\n GenerationMetadata,\n LoadGuard,\n LoadInput,\n LoadOptions,\n LoadRefusal,\n LoadResult,\n RollbackResult,\n Clock,\n Entropy,\n CodecBitmap,\n CodecInterface,\n ConsistencyReport,\n EngineDeps,\n DropResult,\n ExportManifest,\n ExportOptions,\n ExportSink,\n IAuditSink,\n IMetricsSink,\n MetricOpName,\n RetentionPolicy,\n RetireExpiredOptions,\n RetireExpiredResult,\n RetryPolicy,\n RetryingOptions,\n Rng,\n SetRetentionResult,\n PinnedAt,\n SegmentRef,\n} from '@cloudbitmaps/core';\nimport type {\n IKeystore,\n IRegistryDriver,\n IStorageDriver,\n StorageBackend,\n StorageChunkSource,\n} from '@cloudbitmaps/core/driver-kit';\nimport { OpenChargingStorage } from './open-charging-storage';\n// This package's reason to exist: the roaring codec the facade injects into the codec-agnostic engine.\nimport { listGenerations, rollbackSegment } from '@cloudbitmaps/core';\nimport {\n destroySegment as coreDestroySegment,\n eraseNamespace as coreEraseNamespace,\n} from '@cloudbitmaps/core';\nimport type { DestroyResult, EraseDeps } from '@cloudbitmaps/core';\nimport { listSegments, refuseUnknownRefKeys, segmentExists } from '@cloudbitmaps/core';\nimport type { SegmentInfo } from '@cloudbitmaps/core';\nimport { runPreflight } from '@cloudbitmaps/core';\nimport type { PreflightResult } from '@cloudbitmaps/core';\nimport type {\n CombineManyFeed,\n CombineManyOperand,\n Expr,\n MaterializeManyFeedRecord,\n MaterializeManyStats,\n} from '@cloudbitmaps/core';\nimport { refuseReservedNamespace } from './reserved-namespace';\nimport { bitmapAsLoadInput, flagshipCodec } from './roaring-codec';\nimport { SystemClock } from './system-clock';\nimport { systemEntropy } from './system-entropy';\nimport { OPTION_KEYS, type OptionGroup } from './option-keys';\nimport { guardIdIterable, guardIds, guardItems } from './lease-guards';\nimport { wireStore } from './wire-store';\nimport { checkOptions, keysOf, kindOf, optionsError, picked } from './options';\n\n/** Default randomness for backoff jitter \u2014 lives outside `core/`, so `Math.random()` is allowed here. */\nclass SystemRng implements Rng {\n /** A float in `[0, 1)`. Jitter only \u2014 never key material, never anything a caller can observe. */\n next(): number {\n return Math.random();\n }\n}\n\n/**\n * What an erasure call waits with when its write gets no answer and it reads the row back: the caller's `clock` and\n * `rng`, else the real ones, so a call made with `{ registry }` alone waits between its reads. Deps that are not an\n * object are passed on as they are, for the call to refuse with a `ValidationError`.\n */\nfunction withWaits(deps: EraseDeps): EraseDeps {\n if (deps === null || typeof deps !== 'object') return deps;\n return { ...deps, clock: deps.clock ?? new SystemClock(), rng: deps.rng ?? new SystemRng() };\n}\n\n/**\n * Crypto-shred one segment. It cannot be undone through the library (a registry restore to a point before it can).\n * `confirmSegment` must equal `ref.segment` (a guard against an accidental destroy). A non-encrypted segment is\n * rejected unless you opt in via `allowCleartext`: it has no key to shred, its Storage bytes stay readable, and the\n * call emits a `segment.tombstone` audit event instead of `segment.erase`. A write that gets no answer is settled by\n * reading the row back, waiting between reads on `deps.clock` (the system clock by default).\n */\nexport function destroySegment(\n ref: SegmentRef,\n deps: EraseDeps,\n options: { confirmSegment: string; allowCleartext?: boolean; audit?: IAuditSink },\n): Promise<DestroyResult> {\n return coreDestroySegment(ref, withWaits(deps), options);\n}\n\n/**\n * Crypto-shred every segment in a namespace. It cannot be undone through the library. `confirmNamespace` must equal\n * `namespace`. Returns a per-segment result, in the order the registry listed the segments, which is unspecified. A\n * write that gets no answer is settled as {@link destroySegment}'s is.\n */\nexport function eraseNamespace(\n namespace: string,\n deps: EraseDeps,\n options: {\n confirmNamespace: string;\n allowCleartext?: boolean;\n audit?: IAuditSink;\n maxScanSegments?: number;\n },\n): Promise<{ destroyed: DestroyResult[] }> {\n return coreEraseNamespace(namespace, withWaits(deps), options);\n}\n\n/** Validate a segment ref a caller passes to a store method, and return its address alone; a bare name is the common slip, and the hint says so. */\nfunction validateRef(ref: SegmentRef, verb: string): SegmentRef {\n if (typeof ref !== 'object' || ref === null) {\n throw new ValidationError(\n \"a segment ref is an object such as { segment: 'name' }; store.segment() takes the bare name\",\n );\n }\n refuseUnknownRefKeys(ref, verb);\n validateSegmentRef(ref);\n // Only the address goes on: a passed-back listing row's other fields are read for nothing.\n return { segment: ref.segment, namespace: ref.namespace };\n}\n\nconst DEFAULT_CACHE_MAX_CHUNKS = 1024;\n/** Default in-flight fan-out for the admin scans (`subjectReport`/`eraseSubject`) \u2014 bounded, no thundering herd. */\nconst DEFAULT_ADMIN_CONCURRENCY = 8;\n/**\n * The row version a live version from a `CrbmStorageChunkSource` names: the version up to its last `#`, which starts\n * the opened object's fingerprint, a part with no `#` of its own, so the cut is exact for every `pointerId`. It is\n * core's `rowVersionOf` for this one caller, which is handed only that source's versions; core keeps that function\n * off its public entry.\n */\nfunction rowVersionOfLive(version: string | null): string | null {\n if (version === null) return null;\n const cut = version.lastIndexOf('#');\n return cut < 0 ? version : version.slice(0, cut);\n}\n\n/** Fail fast on a bad admin `concurrency` BEFORE the (potentially huge) registry scan, not after. */\nfunction validateConcurrency(concurrency: number | undefined): void {\n requirePositiveInt('concurrency', concurrency);\n}\n\n/**\n * Tenancy guard for the global-scope admin scans (`subjectReport`/`eraseSubject`). Ids live in ONE global\n * `[0, 2\u00B3\u00B2)` space shared across namespaces, so a namespace-less scan reaches into *every* tenant's segments.\n * Require an explicit `namespace`, or a deliberate `{ allNamespaces: true }` ack, so a fleet-wide sweep is never\n * the accidental default on a shared store.\n */\nfunction requireScope(options: { namespace?: string; allNamespaces?: boolean }, op: string): void {\n // A scope names a namespace like a ref does, and these two scans read the registry themselves rather than\n // through a core function that refuses it. `''` or a namespace that is not a string scanned nothing and read as a\n // clean erasure.\n if (options.namespace !== undefined) {\n if (typeof options.namespace !== 'string') {\n throw new ValidationError(\n `${op}: namespace must be a string; got ${kindOf(options.namespace)}`,\n );\n }\n validateSegmentRef({ segment: 'x', namespace: options.namespace });\n }\n refuseReservedNamespace(options.namespace);\n // The two are alternatives. Read as both, a call written to reach every tenant scanned one and reported it erased\n // there, while the others kept the id.\n if (options.namespace !== undefined && options.allNamespaces === true) {\n throw new ValidationError(\n `${op}: pass a namespace or { allNamespaces: true }, not both: with both, it is unclear whether to scan ` +\n `one namespace or every one`,\n );\n }\n if (options.namespace === undefined && options.allNamespaces !== true) {\n throw new ValidationError(\n `${op} scans the global id space across all namespaces \u2014 pass an explicit \\`namespace\\`, ` +\n `or \\`{ allNamespaces: true }\\` to intentionally sweep the whole fleet`,\n );\n }\n}\n\n/** The options of {@link CombineOptions} that decide what an `*Into` verb publishes: a read verb refuses them. */\ntype WriteOption = 'audit' | 'allowEmpty' | 'guard' | 'metadata' | 'keep';\n/** The range of a read: all that `iterate` and `everyNth` take. */\ntype RangeOptions = Pick<CombineOptions, 'after' | 'through'>;\n/** How a combine reads its operands: what `andNot` takes, and what the engine is handed beside the `exclude` refs. */\ntype ReadOptions = Omit<CombineOptions, 'exclude' | WriteOption>;\n/** What `intersect` and `union` take: a read that can also subtract. */\ntype StreamOptions = Omit<CombineOptions, WriteOption>;\n/** What `andNotInto` takes: every option but `exclude`, since its `excludes` argument is the subtraction. */\ntype AndNotIntoKeys = Omit<CombineOptions, 'exclude'>;\n\n/**\n * What each call that takes options takes. Each table is held in both directions to the type of what the call takes: a\n * key the type does not have, or one it has and the table leaves out, fails to compile. The combines and the reads\n * share one public options type, {@link CombineOptions}, and each takes part of it, so their tables are held to the\n * parts above; a key outside a call's part type-checks and is refused here, at run time.\n */\nconst CALL_KEYS = {\n range: keysOf<RangeOptions>()(['after', 'through']),\n andNot: keysOf<ReadOptions>()([\n 'after',\n 'through',\n 'concurrency',\n 'budget',\n 'allowAbsentOperands',\n ]),\n combine: keysOf<StreamOptions>()([\n 'after',\n 'through',\n 'concurrency',\n 'budget',\n 'allowAbsentOperands',\n 'exclude',\n ]),\n into: keysOf<CombineOptions>()([\n 'after',\n 'through',\n 'concurrency',\n 'budget',\n 'allowAbsentOperands',\n 'exclude',\n 'audit',\n 'allowEmpty',\n 'guard',\n 'metadata',\n 'keep',\n ]),\n andNotInto: keysOf<AndNotIntoKeys>()([\n 'after',\n 'through',\n 'concurrency',\n 'budget',\n 'allowAbsentOperands',\n 'audit',\n 'allowEmpty',\n 'guard',\n 'metadata',\n 'keep',\n ]),\n load: keysOf<LoadOptions>()(['allowEmpty', 'guard', 'keep', 'metadata', 'audit', 'sorted']),\n segments: keysOf<NonNullable<Parameters<CloudRoaring['segments']>[0]>>()(['namespace']),\n subjectReport: keysOf<NonNullable<Parameters<CloudRoaring['subjectReport']>[1]>>()([\n 'namespace',\n 'allNamespaces',\n 'concurrency',\n 'budget',\n ]),\n eraseSubject: keysOf<NonNullable<Parameters<CloudRoaring['eraseSubject']>[1]>>()([\n 'namespace',\n 'allNamespaces',\n 'audit',\n 'concurrency',\n 'budget',\n ]),\n rollback: keysOf<NonNullable<Parameters<CloudRoaring['rollback']>[2]>>()([\n 'audit',\n 'allowUnknown',\n ]),\n dropSegment: keysOf<Parameters<CloudRoaring['dropSegment']>[1]>()([\n 'confirmSegment',\n 'dryRun',\n 'audit',\n ]),\n retireExpired: keysOf<NonNullable<Parameters<CloudRoaring['retireExpired']>[0]>>()([\n 'namespace',\n 'now',\n 'limit',\n 'dryRun',\n 'audit',\n 'maxScanSegments',\n 'scan',\n 'shards',\n 'totalShards',\n 'lookbackBuckets',\n 'purgeTombstones',\n 'tombstoneGraceMs',\n ]),\n checkConsistency: keysOf<NonNullable<Parameters<CloudRoaring['checkConsistency']>[0]>>()([\n 'namespace',\n 'concurrency',\n 'maxScanSegments',\n 'summaries',\n 'generations',\n ]),\n exportSegments: keysOf<ExportOptions>()(['format', 'namespace', 'ndjsonBatchBytes']),\n} as const;\n\n/** The keys of `wider` that `known` does not list. */\nconst outside = (wider: readonly string[], known: readonly string[]): readonly string[] =>\n wider.filter((k) => !known.includes(k));\n\n/**\n * The fields of {@link CombineOptions} each read and combine does not take. A call reads each by name and refuses it\n * (see `optionsError`), so one inherited from a prototype or held in a getter is refused as an own key is, not dropped:\n * an `exclude` so held on `andNot` was skipped, and the stream was wider than asked. `intersectInto` and `unionInto`\n * take every field. `exportSegments` refuses `codec` the same way: the store exports with its own codec.\n */\nconst MISPLACED = {\n range: outside(CALL_KEYS.into, CALL_KEYS.range),\n andNot: outside(CALL_KEYS.into, CALL_KEYS.andNot),\n combine: outside(CALL_KEYS.into, CALL_KEYS.combine),\n andNotInto: outside(CALL_KEYS.into, CALL_KEYS.andNotInto),\n exportSegments: ['codec'],\n} as const;\n\n/**\n * Wiring for a {@link CloudRoaring} store. **Only `storage` is required** \u2014 the minimal call is\n * `new CloudRoaring({ storage: backend })`. A backend resolves generations with one strong read, reads\n * encrypted segments, and unlocks every lifecycle helper; the narrower shapes `storage` also accepts are\n * described on the option itself. Everything else is **optional\n * tuning with sensible defaults** \u2014 resilience/retries are already on, the cache is bounded, metrics are a\n * no-op \u2014 so reach for them only when you need to.\n */\nexport interface CloudRoaringOptions {\n /**\n * Where the store keeps everything. **The only required option.**\n *\n * Pass a {@link StorageBackend} \u2014 `S3Storage`, `GcsStorage`, `AzureBlobStorage`, `LocalFsStorage`,\n * `MemoryStorage` \u2014 and you are done: it carries both halves, the generations and the `currentGen` pointer,\n * configured from one bucket and one prefix. That is the whole wiring, and it is the shape to reach for.\n *\n * **Pass the backend itself, not `backend.storage`.** They differ by one property access and the mistake is\n * silent: `storage: backend` is the store, while `storage: backend.storage` hands over the *driver half*\n * alone, which constructs without complaint and gives you a cleartext, read-only store that fails later on\n * the first write or lifecycle call. `destroySegment` and `eraseNamespace` take `backend.registry`; the store takes `backend`.\n *\n * Two lower-level shapes stay accepted for wiring the facade does not cover:\n *\n * - a **raw {@link IStorageDriver}**, which the store reads through its own `.crbm` reader. There is no\n * registry in this shape, so the store resolves generations by list-scanning storage: **cleartext and\n * read-only**. Encrypted segments, the `*Into` verbs and every lifecycle helper need a backend.\n * - a {@link StorageChunkSource} of your own, a read source used as it is: read-only, like the raw driver.\n *\n * The two port types are exported by `@cloudbitmaps/core/driver-kit`, not by this package; to name the option's\n * type without importing them, write `CloudRoaringOptions['storage']`.\n */\n readonly storage: StorageBackend | IStorageDriver | StorageChunkSource;\n\n /**\n * Memory and staleness bounds for the read path. Every key is optional and every default is already sane;\n * reach for these when a deployment's shape differs from \"a long-running server with room to breathe\".\n */\n readonly cache?: CacheOptions;\n\n /**\n * Encryption at rest. Omit it entirely for a cleartext store \u2014 encryption is opt-in, and a segment's\n * encryption is decided at its **first** generation.\n */\n readonly encryption?: EncryptionOptions;\n\n /**\n * Resilience: by default every read that answers a query retries **transient** faults (throttling, 5xx, dropped\n * connections) with bounded, jittered exponential backoff (by default 4 attempts, a 50 ms base delay doubling each\n * attempt, capped at 2 s, with full jitter): `has`, `count`,\n * `iterate` and the combines, the `*Into` verbs' reads of their operands included, a pinned handle's reads and\n * `pin()` itself, and the reads a write makes along the way: a load's guard read of the current generation, and an\n * erasure's reads of the generation it rewrites, of the one it wrote and of any other that may still hold the id, and\n * the search `subjectReport` and `eraseSubject` make under a destroyed segment (its listing of the bucket included).\n * This option does not govern writes, nor the calls that read the registry or list the bucket directly (`exists`,\n * `segments`, `generations`, `getRetention`, and the registry scan `subjectReport`, `exportSegments` and\n * `checkConsistency` start from): they report a transient fault to their caller, because a conditional write that\n * lands and then loses its response would, replayed blindly, report its own write as a conflict. A write is\n * retried only where that is safe: a load's registry write that gets no answer is settled by reading the row,\n * and a throttled write-once object is sent again by the S3 and GCS drivers. Pass a partial policy to tune it \u2014 anything you leave out keeps its\n * default, except an omitted `maxDelayMs`, which is `baseDelayMs` when that is larger than 2000 ms \u2014 or `false` to turn the read retry off (e.g. if your injected client already retries). A GCS download is retried by\n * the GCS driver whatever this says.\n * Deterministic errors (`ValidationError`/`IntegrityError`/`WriteConflictError`/\u2026) are never retried by this\n * layer.\n */\n readonly retry?: RetryOptions | false;\n\n /**\n * Observability sink: receives typed metric events (storage GET/bytes, cache hit/miss, retries, intersection\n * efficiency, op latency). Defaults to a no-op \u2014 emission is skipped entirely when unused (near-zero\n * overhead). Any exception the sink throws is swallowed \u2014 metrics can never break a read.\n */\n readonly metrics?: IMetricsSink;\n\n /**\n * Per-op **denial-of-wallet** budget: the max backend requests a single\n * `count`/`iterate`/`intersect`/`union`/`andNot`/`subjectReport`/`eraseSubject` may fan out into before it's\n * refused with {@link BudgetExceededError} (`eraseSubject` reports an over-budget segment in its ledger instead,\n * see {@link CloudRoaring.eraseSubject}) \u2014 so one runaway op can't drive unbounded GET cost on a shared\n * backend. **On by default, generous** (1,000,000 requests \u2014 a normal op never hits it).\n * Tune with `{ maxRequests }`, override per op (on the combines / `subjectReport` / `eraseSubject`), or set\n * `false` to disable. The check is O(1) (before fan-out), so the hot path is untouched; per-request bytes are\n * separately size-capped, so bounding requests transitively bounds bytes.\n */\n readonly budget?: BudgetOption;\n\n /**\n * Determinism seams, for tests and replayable jobs. Production stores leave this out and get a system clock\n * and a `Math.random`-backed source.\n */\n readonly seams?: SeamOptions;\n}\n\n/** {@link CloudRoaringOptions.cache} \u2014 the memory and staleness bounds. */\nexport interface CacheOptions {\n /** Ceiling on decoded Storage chunks held in RAM (default 1024): an integer of at least 1, else `ValidationError`. */\n readonly maxChunks?: number;\n /**\n * Optional TTL on cached chunks (ms): a finite number above 0, else `ValidationError`. Omit to keep a chunk until it is\n * evicted by the count bound.\n */\n readonly ttlMs?: number;\n /**\n * How long (ms) the store trusts a segment's resolved `currentGen` before re-resolving it on the next read\n * (default 2000) \u2014 the bound on read staleness after a load publishes a new generation. Applies when\n * `storage` is a **backend**, whose registry supplies the cheap `currentGen` read the refresh needs. Lazy \u2014 no\n * timer; \u2264 one registry read per segment per window, opening a new reader only when the row's pointer was\n * renewed (a publish, a rollback, an erasure's rewrite, a status or key change); a lease or retention write does not.\n *\n * **While the registry cannot be read, the bound stretches.** A refresh that fails with a\n * {@link TransientError} keeps serving the generation of a segment still in the reader cache, and the key its reader\n * unwrapped (a read that needs the key, where none was unwrapped before it, unwraps it from that segment's row as\n * resolved before the outage), and is tried again 500 ms later (or after this TTL, if shorter), so the store converges\n * within one retry of the registry answering. A segment the reader cache has let go is not served past its resolution's TTL: once that\n * lapses, a read of it fails with the fault, as a cold read does. A refresh that fails with anything else, an access denial or a row that will not parse, is not\n * ridden out: the read that meets it throws that error, and the reader is dropped.\n *\n * `0` turns this timed refresh off, and so does wiring a bare `IStorageDriver`, which has no registry. That is\n * all it does. The store still moves a segment on to whatever generation is current when its reader cache\n * evicts the segment, when a read has to fetch from a generation a sweep deleted, and when it is invalidated,\n * as its own `load`, `rollback`, `eraseSubject` and `*Into` writes do and {@link CloudRoaring.invalidate} does.\n * A read its caches can answer touches no storage, so a sweep alone moves nothing. What `0` gives up is the bound:\n * the store notices another process's publish, erasure or drop only through one of those, whenever that happens. To read\n * one generation for as long as you need it, take a {@link Segment.pin}.\n */\n readonly genTtlMs?: number;\n /**\n * Ceiling on how many segments' `.crbm` readers (each holding a parsed index) the store keeps open at once\n * (default 1024; an integer of at least 1, else `ValidationError`) \u2014 the steady-state memory bound for a long-running\n * server that reads across many segments.\n * Past it the least-recently-used segment's reader is evicted; re-opening it later is one cheap tail GET. With a\n * timed refresh ({@link CacheOptions.genTtlMs} above 0, and a backend) the store also keeps up to 8 times this many\n * segments' resolutions (what it read of each segment's row: never an unwrapped key, though the wrapped keys are in\n * it) for `genTtlMs`, apart from their readers. An evicted segment is then reopened with no registry read, on the\n * generation it had resolved, when a read needs its index or a chunk the chunk cache does not hold: `iterate` and the\n * combines always do, and a `has()` of a cached chunk, a `count()` and a `stat()` do not, where the row has a summary\n * the store can use. A reader of a small generation, one whose whole object came with its tail read,\n * also holds its chunk bytes, so a read of it makes no chunk request until the reader is evicted or the pointer refresh\n * moves it on; a store with no timed refresh (`genTtlMs: 0`, or no registry) keeps none.\n * Applies whenever the store builds its own read path \u2014 a backend or a bare `IStorageDriver`. A pre-built\n * `StorageChunkSource` manages its own reader cache.\n */\n readonly readerMax?: number;\n /**\n * Aggregate byte ceiling on what the open readers hold: their parsed `.crbm` indices, the metadata a\n * generation carries, a fixed 3.75 KiB for the objects each open reader holds around its index, and the chunk bytes a reader keeps when its tail read returned a whole object whose chunks\n * total at most this ceiling divided by {@link CacheOptions.readerMax} (default 64 MiB) \u2014 the byte half\n * of the memory bound, complementing the {@link CacheOptions.readerMax} *count* bound. A wide/dense segment's\n * parsed index can reach about 1.3 MB, so a count-only bound could let the open readers pin over a GB and blow a small\n * heap (e.g. a 128 MB Lambda); this evicts the least-recently-used reader once the summed weight\n * would exceed the ceiling \u2014 whichever of the count/byte bounds binds first. A sixteenth of it (4 MiB by default)\n * bounds the segments' resolutions a store with a timed refresh keeps besides. Lower it for memory-tight\n * deployments that read across wide segments. An integer of at least 1, else `ValidationError`. A ceiling below two readers' weight (about 7.7 KB for tiny ones) keeps one reader open at a time. Applies whenever the store builds its own read path.\n */\n readonly readerMaxBytes?: number;\n}\n\n/** {@link CloudRoaringOptions.encryption} \u2014 encryption at rest and crypto-shred. */\nexport interface EncryptionOptions {\n /**\n * The keystore that mints and unwraps per-segment DEKs. Needs a **backend**: the wrapped DEK lives in the\n * registry, so there is nowhere to put it on a store wired with a bare driver, and that is refused at\n * construction rather than at the first read.\n */\n readonly keystore?: IKeystore;\n /**\n * Refuse to touch a **cleartext** segment \u2014 a guard against silently reading, or writing, data that should be\n * encrypted. Needs a backend, for the same reason as {@link EncryptionOptions.keystore}. Off by default. Exactly a\n * boolean: any other value, a truthy string included, throws `ValidationError`.\n *\n * It refuses **writes** as well as reads, which is easy to miss: the `*Into` verbs and `eraseSubject` both\n * carry it into their write path, so on a cleartext segment a materialisation throws and an erasure records\n * `note: 'error: KeyUnavailableError: requireEncryption: \u2026'` in its ledger rather than erasing, whatever id it erases and\n * whether or not the id is in the segment: it does not read the segment. And since a segment's encryption is\n * decided at its **first** generation, this cannot be switched on for a segment that already has one \u2014 load\n * into a new encrypted segment and drop the old one.\n */\n readonly required?: boolean;\n}\n\n/**\n * {@link CloudRoaringOptions.retry} \u2014 a partial {@link RetryPolicy} plus the retry callback.\n *\n * Partial on purpose, so tuning one field does not mean restating all five. Anything omitted here keeps its default\n * (`maxAttempts` 4, `baseDelayMs` 50, `maxDelayMs` 2000, `backoffFactor` 2, `jitter` `'full'`), except that an\n * omitted `maxDelayMs` is the `baseDelayMs` when that is larger than the default cap.\n */\nexport interface RetryOptions extends Partial<RetryPolicy> {\n /**\n * Observability: called before each transient-retry backoff wait. Best-effort: an error it throws is\n * swallowed, so it can neither stop the retry nor change the error a read fails with.\n */\n readonly onRetry?: (info: { attempt: number; delayMs: number; err: unknown }) => void;\n}\n\n/** {@link CloudRoaringOptions.seams} \u2014 injected for deterministic tests and replayable jobs. */\nexport interface SeamOptions {\n /** Defaults to a system clock. */\n readonly clock?: Clock;\n /** Defaults to `Math.random`-backed. Drives transient-retry jitter. */\n readonly rng?: Rng;\n /**\n * Defaults to the platform's Web Crypto. The source of every written generation's identity: 12 bytes a cleartext\n * generation's footer carries (an encrypted one carries its index's AEAD nonce), so two loads of the same ids are\n * two objects. Inject a deterministic one to replay a run or pin bytes in a test; never inject a constant in\n * production, since a source that repeats makes the objects it writes alike again.\n */\n readonly entropy?: Entropy;\n}\n\n/**\n * What {@link CloudRoaring.segment} takes besides the name. A handle carries no deadline: check one where you read,\n * or record it with {@link CloudRoaring.setRetention} and run {@link CloudRoaring.retireExpired}. An `expiresAt`\n * passed here is refused with {@link ValidationError}.\n */\nexport interface SegmentOptions {\n /** The segment's namespace, or `undefined` for the default one. */\n readonly namespace?: string;\n}\n\n/** A segment reference in a subject report / erasure ledger. */\nexport interface SubjectSegmentRef {\n /** The segment's name. */\n readonly segment: string;\n /** The segment's namespace, or `undefined` for the default one. */\n readonly namespace?: string;\n}\n\n/** Result of {@link CloudRoaring.subjectReport}: the segments an id is a member of, and the destroyed segments whose leftover objects hold it. */\nexport interface SubjectReport {\n /** The id the report is about. */\n readonly id: number;\n /** The registered segments the id is currently a member of. */\n readonly segments: SubjectSegmentRef[];\n /**\n * The destroyed segments whose leftover objects still hold the id in the clear: one destroyed with `allowCleartext`,\n * dropped while a load wrote an object its sweep did not catch, or crypto-shredded over an object a cleartext writer\n * left. No read resolves them, so the id is a member of none, but its bytes are in the bucket, and `eraseSubject`\n * deletes them. A crypto-shredded segment's own objects are sealed under a key no row holds and are never a holder,\n * so it is listed only when an object left under it in the clear holds the id. A destroyed segment with no\n * object left is not listed either. `[]` when none.\n */\n readonly tombstones: SubjectSegmentRef[];\n /** How many registered segments were scanned (the completeness denominator). */\n readonly scannedSegments: number;\n}\n\n/** One segment's entry in an erasure ledger (see {@link EraseSubjectResult}). */\nexport interface SubjectErasureEntry {\n /** The segment's name. */\n readonly segment: string;\n /** The segment's namespace, or `undefined` for the default one. */\n readonly namespace?: string;\n /**\n * True iff the id **was** in the segment and **no generation of it holds the id now** \u2014 not the current one, not\n * one below the pointer, and not one above it, where a rollback leaves the generations it rolled back from. The\n * current generation is one without it, every generation that held it has been deleted from the bucket, and the\n * call listed the bucket and read what was left before this entry was returned (see\n * {@link CloudRoaring.eraseSubject}).\n */\n readonly erased: boolean;\n /**\n * The generation the id was found in (present whenever the segment was read) \u2014 the newest of them, when the\n * current generation did not hold it and several others did.\n */\n readonly fromGeneration?: number;\n /** The generation written without the id (present whenever one was written). */\n readonly generation?: number;\n /**\n * Why the id was NOT erased from this segment, when `erased` is false. `'superseded'` \u2014 another writer (a load,\n * another erasure or a rollback) moved the pointer, replaced an object the call meant to delete, or left the row with\n * no pointer (a purge and re-creation, or a hand-made write), while the call was in flight, so **this call** did\n * not erase the id;\n * re-run against the new generation, which erases it if it is still there and reports nothing for the segment\n * if the racing writer already removed it. `` `error: <class>: <message>` `` \u2014 an isolated per-segment fault, named by its error's class\n * (per-segment faults are recorded so one segment can't discard the whole ledger); re-run after fixing the\n * fault. A budget refusal is one of these: the segment's generations did not fit `budget`, so it was not finished;\n * re-run with a higher `budget`. A fault that landed once part of the work was already done \u2014 a Storage `delete` fault, a collect that\n * could not prove the segment was still the same one, or a generation still holding the id when the bucket was\n * listed at the end, whether or not a rewrite was published first \u2014 also re-runs, but **read what the re-run\n * says**: it usually reports `erased: true` against the generation it found the id in, it reports\n * nothing at all if a racing collector took that generation first, or this call's own delete of it landed after a\n * fault the call could not settle (the bit is gone, but no run holds a receipt for it), and if the segment's row has since been purged it is no longer scanned at all \u2014 anything\n * left in its bucket is an orphan, which `store.generations(ref)` lists and `store.dropSegment(ref, {\n * confirmSegment })` deletes; `checkConsistency` and the collection a load runs read rows, so neither reaches it.\n * **Segments the id is not in\n * are not listed, and neither are segments that no longer have a registry row** \u2014 an empty ledger is not by\n * itself proof the id is gone.\n */\n readonly note?: string;\n}\n\n/**\n * The erasure ledger returned by {@link CloudRoaring.eraseSubject} \u2014 your proof-of-deletion artifact. It is a\n * return value only (no library-side persistence): persist it / route it to your audit sink as you see fit.\n */\nexport interface EraseSubjectResult {\n /** The id that was erased. */\n readonly id: number;\n /** Per-segment records for the segments the id was found in (absent segments are not listed). */\n readonly erasedFrom: SubjectErasureEntry[];\n /** How many registered segments were scanned. */\n readonly scannedSegments: number;\n}\n\n/**\n * Why a materialisation did not become current.\n *\n * {@link LoadRefusal} minus `'superseded'`: that one is a lost race, and the `*Into` verbs throw\n * {@link WriteConflictError} for it rather than reporting it. Narrowing the type rather than saying so only\n * in prose means the compiler enforces it, and a caller's exhaustive `switch` has no dead branch.\n */\nexport type MaterializeRefusal = Exclude<LoadRefusal, 'superseded'>;\n\n/** One output of a {@link CloudRoaring.materializeMany} call. */\nexport interface MaterializeManyOutput {\n /** The segment this output becomes a new generation of. Not an operand of the call, and named by no other output. */\n readonly dest: Segment;\n /** What to compute. */\n readonly expr: Expr;\n /** Subtracted from the result, as the entries of an `andNot` after the first are. Pinned operands it names are re-checked before the publish. */\n readonly exclude?: Expr[];\n /** As {@link CombineOptions.guard} on an `*Into` verb. */\n readonly guard?: LoadGuard;\n /** As {@link CombineOptions.allowEmpty} on an `*Into` verb. */\n readonly allowEmpty?: boolean;\n /** As {@link CombineOptions.metadata} on an `*Into` verb. */\n readonly metadata?: GenerationMetadata;\n /** As {@link CombineOptions.audit} on an `*Into` verb. */\n readonly audit?: IAuditSink;\n /** Generations to keep below the new one, as {@link CombineOptions.keep} on an `*Into` verb; overrides the call's `keep`. */\n readonly keep?: number;\n}\n\n/**\n * Operands that arrive as records in chunk-key order instead of being stored, for {@link MaterializeManyOptions.feed}.\n * Outputs name a fed operand as they name a stored one.\n */\nexport interface MaterializeManyFeed {\n /** The fed operand names, declared up front. A name is either stored or fed, never both. */\n readonly names: string[];\n /** The records, read once, in key order. */\n readonly records: AsyncIterable<MaterializeManyFeedRecord>;\n /**\n * How many ids each fed operand holds over the whole feed, **required**: an object keyed by exactly `names`, or a\n * function returning one (or a promise of one), called once after the last record and before any fed output is\n * published. A feed whose count of ids for any operand differs (one that ended early, or skipped a key) refuses every\n * fed output; so does a count that is missing, extra, thrown or rejected.\n */\n readonly counts:\n (() => Record<string, number> | Promise<Record<string, number>>) | Record<string, number>;\n}\n\n/** The options of {@link CloudRoaring.materializeMany}. */\nexport interface MaterializeManyOptions extends Pick<CombineOptions, 'after' | 'through'> {\n /**\n * The stored segments the expressions name. A set the caller holds in memory arrives as a {@link MaterializeManyOptions.feed}.\n */\n readonly operands: Record<string, Segment>;\n /** The outputs, in the order their results come back. */\n readonly outputs: ReadonlyArray<MaterializeManyOutput>;\n /**\n * Generations to keep below each new one: a non-negative integer, **required**, since a materialisation otherwise keeps\n * every generation and a call of a thousand outputs would leave a thousand uncollected destinations on every refresh.\n * An output's own `keep` overrides it.\n */\n readonly keep: number;\n /**\n * Read every stored operand at the generation it has when the call starts, for the whole call (default `true`): the call\n * pins each one that is not already pinned. It is one generation per operand, **not one instant across operands**.\n * `false` reads each live, as a combine does, which can describe two generations of one operand and break its pruning, and runs\n * **no re-check** of an operand an output subtracts: an opt-out list can move during the call and the outputs that subtract it are\n * published (`stats.operands` still reports, from one read at the end, that it moved).\n * An operand passed already pinned is used as it is whatever this says.\n */\n readonly pin?: boolean;\n /**\n * The most resident bytes the call counts at once, default 256 MiB: the buffered outputs, the operand streams, the\n * chunks being evaluated and the plan, counted as resident memory. Past it, outputs run in groups and the operands are read\n * again for each group. Process memory is more than the count (measured 1.6 to 5 times; see the guide).\n */\n readonly maxBufferedBytes?: number;\n /**\n * The most chunk reads the call may make, counted over all its groups. Default: the store's own `budget` when it was built\n * with one (a ceiling below the plan throws `BudgetExceededError` before any chunk is read), else what the plan needs,\n * with headroom. `false` lifts it. The budget used is in the result's stats.\n */\n readonly budget?: BudgetOption;\n /** Outputs published at once, default 8. */\n readonly publishConcurrency?: number;\n /** Range requests held ahead per operand, default 1. */\n readonly concurrency?: number;\n /** As on every combine. */\n readonly allowAbsentOperands?: boolean;\n /**\n * Operands fed as records in chunk-key order, beside the stored ones; an output names a fed operand as it names a stored\n * one. **A feed is read once, so a call with one runs its outputs as one group, and `maxBufferedBytes` is then required**:\n * the feed's records and the fed outputs are counted against it as they arrive, and a fed call fails as soon as the count\n * passes it. A fed output is published only after the whole feed was read and every end-of-feed check passed.\n */\n readonly feed?: MaterializeManyFeed;\n /**\n * Fed operand names allowed to hold no id. A declared fed name that appears in no record is refused at the end of the\n * feed, because an operand that is empty is usually an upstream query that failed quietly. Naming something that is not\n * a fed operand is a {@link ValidationError}.\n */\n readonly mayBeEmpty?: readonly string[];\n}\n\n/**\n * What one output of {@link CloudRoaring.materializeMany} came to: exactly what its `*Into` would have returned (a\n * {@link MaterializeResult}, published or refused with its `reason`), or `{ published: false, error }` for what it would\n * have thrown, or for what stopped it: a lost race ({@link WriteConflictError}), a publish whose outcome is unknown\n * ({@link TransientError}), a damaged operand ({@link IntegrityError}), a lapsed lease ({@link LeaseExpiredError}), a\n * pinned exclude that moved ({@link StaleOperandError}), memory ({@link BudgetExceededError}), or, for an output that names a\n * fed operand, a bad feed ({@link ValidationError}) or an erasure in this store while the call ran ({@link StaleOperandError}\n * with `reason: 'erased'`).\n */\nexport type MaterializeManyOutcome =\n MaterializeResult | { readonly published: false; readonly error: Error };\n\n/** The result of {@link CloudRoaring.materializeMany}. */\nexport interface MaterializeManyRun {\n /** One per output, in the order given: one output's refusal or error never stops another. */\n readonly outputs: MaterializeManyOutcome[];\n /**\n * What the call did: the groups it ran, its requests by class, its budget and memory, and the figures of each operand\n * and output.\n */\n readonly stats: MaterializeManyStats;\n}\n\n/**\n * {@link MaterializeManyOptions} for a **dry run**: every output is computed exactly as the call would compute it, and\n * judged against its `dest` as its publish would be, and nothing is written. See {@link CloudRoaring.materializeMany}.\n */\nexport interface MaterializeManyDryRunOptions extends MaterializeManyOptions {\n /** `true` makes the call a dry run: every output is computed and judged, and nothing is written. */\n readonly dryRun: true;\n}\n\n/**\n * What one output of a dry run would come to, with nothing written: its size, what its `dest` holds now, and the bound\n * its publish would be refused for now. `published` is always `false`, so code that branches on it never takes a dry\n * run for a publish.\n */\nexport interface MaterializeDryRunResult {\n /** Always `true`: the output was computed and judged, not published. */\n readonly dryRun: true;\n /** Always `false`: nothing was written. */\n readonly published: false;\n /** Distinct ids the output would hold. */\n readonly cardinality: number;\n /** What `dest` holds now: `null` when it has no current generation, or its object is gone. Always read. */\n readonly cardinalityBefore: number | null;\n /** The bound a publish of the output would be refused for, judged now; absent when it would publish. */\n readonly wouldRefuse?: MaterializeRefusal;\n}\n\n/**\n * What one output of a dry run came to: a {@link MaterializeDryRunResult}, or `{ published: false, error }` for what its\n * publish would have thrown or what stopped it, as on a call that publishes.\n */\nexport type MaterializeManyDryRunOutcome =\n MaterializeDryRunResult | { readonly published: false; readonly error: Error };\n\n/** The result of {@link CloudRoaring.materializeMany} with `dryRun: true`. */\nexport interface MaterializeManyDryRun {\n /** One per output, in the order given. */\n readonly outputs: MaterializeManyDryRunOutcome[];\n /**\n * What the dry run did: the groups it ran, its requests by class, its budget and memory, and the figures of each\n * operand and output.\n */\n readonly stats: MaterializeManyStats;\n}\n\n/** A dry run's value inside the call, with the requests its judgement made. */\ninterface DryRunValue extends MaterializeDryRunResult {\n readonly reads: number;\n}\n\n/** What a handle shows the store that it does not show a caller. */\ninterface HandleView {\n readonly ref: SegmentRef;\n readonly pinnedAt: PinnedAt | undefined;\n /** The lease error a read of the handle must throw now, or `undefined`. */\n readonly leaseError: () => LeaseExpiredError | undefined;\n}\n\n/**\n * Marks a segment so one from another copy of this package is recognised; `Symbol.for` is the same symbol in every\n * copy. The mark is read only to name the refusal: a store belongs to one copy, so a segment of another copy always\n * comes from another store and is refused with a message that says so. The number at the end of the key is raised\n * if the mark changes meaning.\n */\nconst SEGMENT_BRAND: unique symbol = Symbol.for('cloudbitmaps.roaring.segment/1');\n\n/** Set by the `Segment` class, whose private state it reads. */\nlet viewOf: (segment: Segment) => HandleView;\n/** The store that made a segment: one reference compare per handle per call. Set by the `Segment` class. */\nlet originOf: (segment: Segment) => object;\n\n/** What a refused handle was in the call: its role, or where it sits in a `materializeMany` call. */\ntype HandleRole = string;\n\n/**\n * Refuse, with a {@link ValidationError} and before any request, a handle that the store `origin` did not make: a\n * value that is not a segment, a segment of another store, or a segment of another installed copy of this package.\n * The messages never name the segment, the namespace or a key.\n */\nfunction assertOneStore(\n verb: string,\n role: HandleRole,\n h: unknown,\n origin: object,\n): asserts h is Segment {\n if (h instanceof Segment) {\n if (originOf(h) === origin) return;\n throw new ValidationError(\n `${verb}: ${role} belongs to another store; combine segments of one store: open each with this store's segment()`,\n );\n }\n if (\n typeof h === 'object' &&\n h !== null &&\n (h as Record<symbol, unknown>)[SEGMENT_BRAND] === true\n ) {\n throw new ValidationError(\n `${verb}: ${role} comes from another installed copy of @cloudbitmaps/roaring, so it belongs to another store; install one copy and combine segments of one store`,\n );\n }\n throw new ValidationError(`${verb}: ${role} must be a segment from this store's segment()`);\n}\n\nconst MATERIALIZE_MANY_KEYS = [\n 'operands',\n 'dryRun',\n 'outputs',\n 'keep',\n 'pin',\n 'maxBufferedBytes',\n 'budget',\n 'publishConcurrency',\n 'concurrency',\n 'allowAbsentOperands',\n 'after',\n 'through',\n 'feed',\n 'mayBeEmpty',\n] as const;\n/**\n * The fields of {@link CombineOptions} a `materializeMany` call does not take at its top level (an output takes the\n * write options), read by name as a read or combine reads its own, so one inherited or held in a getter is refused.\n */\nconst MATERIALIZE_MANY_MISPLACED = outside(CALL_KEYS.into, MATERIALIZE_MANY_KEYS);\n\n/** The keys of a `materializeMany` call's options it does not take: every own one it does not list, and the misplaced. */\nfunction unknownManyKeys(options: object): string[] {\n const unknown = Object.keys(options).filter(\n (k) => !(MATERIALIZE_MANY_KEYS as readonly string[]).includes(k),\n );\n const bag = options as Record<string, unknown>;\n for (const k of MATERIALIZE_MANY_MISPLACED) {\n if (!unknown.includes(k) && bag[k] !== undefined) unknown.push(k);\n }\n return unknown;\n}\nconst MATERIALIZE_MANY_OUTPUT_KEYS = [\n 'dest',\n 'expr',\n 'exclude',\n 'guard',\n 'allowEmpty',\n 'metadata',\n 'audit',\n 'keep',\n] as const;\n\n/** The default of `maxBufferedBytes`: 256 MiB. */\nconst DEFAULT_MAX_BUFFERED_BYTES = 256 * 1024 * 1024;\nconst DEFAULT_PUBLISH_CONCURRENCY = 8;\nconst DEFAULT_BATCH_CONCURRENCY = 1;\n/** Pins taken at once. */\nconst PIN_PARALLELISM = 16;\n\n/** What an `*Into` verb wrote: the new generation of the destination, and whether it became current. */\nexport interface MaterializeResult {\n /**\n * The generation written. Present even when refused: the refusal deleted that object, unless the destination's\n * row changed while it was writing, which leaves it in the bucket, an orphan a later load's collection takes; until\n * then a rollback onto it needs `allowUnknown`.\n */\n readonly generation: number;\n /**\n * Whether this generation is now the destination's current one.\n *\n * `false` when the guard refused the result: an empty one over a non-empty destination, or one outside\n * `guard`'s bounds. Branch on it: a refusal is reported, not thrown, so a caller that ignores it sees a\n * successful-looking result for a write that deliberately did not happen.\n */\n readonly published: boolean;\n /** Set only when `published` is false. A lost race throws {@link WriteConflictError} rather than appearing here. */\n readonly reason?: MaterializeRefusal;\n /** Ids in the generation. */\n readonly cardinality: number;\n /**\n * What the destination held when the guard judged it \u2014 `null` when it had no current generation, **or when\n * no bound needed it**. It is taken only when a bound will use it: `allowEmpty: true` with neither\n * `guard.minRetained` nor `guard.maxGrowth` skips it, and this is `null` even though `dest` was non-empty. When the destination's row\n * carries a summary of its current generation the count comes from the row and the object is not read; a row with\n * none (one a rollback left when it could not open the key, one a registry of your own stores without one, or one this store cannot use) costs\n * one object-header fetch.\n */\n readonly cardinalityBefore: number | null;\n /** Non-empty chunks in the generation. */\n readonly chunkCount: number;\n /** Bytes of the written object. */\n readonly size: number;\n /**\n * The superseded generations collected after publishing. Empty when nothing was published \u2014 and **also\n * empty on a successful publish** unless you passed `keep`, because a materialisation collects nothing by\n * default. See {@link CombineOptions.keep}.\n */\n readonly collected: readonly number[];\n}\n\n/**\n * The deps every write-side helper on the store shares: raw storage + registry + the store's codec/crypto/clock, and\n * the store's read retry for the reads a write makes along the way (undefined when the store's retry is off).\n */\ninterface LifecycleDeps {\n readonly storage: IStorageDriver;\n readonly registry: IRegistryDriver;\n readonly codec: CodecInterface;\n readonly clock: Clock;\n /** The store's random source, which spreads a publish's waits between fresh writes whether or not reads retry. */\n readonly rng: Rng;\n /** The source of each written generation's identity. */\n readonly entropy: Entropy;\n readonly keystore?: IKeystore;\n readonly requireEncryption?: boolean;\n readonly readRetry?: RetryingOptions;\n}\n\n/** How the store names a group value that is an object to `typeof` but configures nothing, by its built-in tag. */\nconst NOT_A_GROUP: Readonly<Record<string, string>> = {\n Null: 'null',\n Array: 'an array',\n Map: 'a Map',\n Set: 'a Set',\n Boolean: 'a boxed boolean',\n Number: 'a boxed number',\n String: 'a boxed string',\n};\n\n/**\n * The store: Roaring bitmap segments kept as write-once `.crbm` generations in the storage you give it, read through\n * a bounded in-memory cache. Build one per process from a backend,\n * `new CloudRoaring({ storage: new S3Storage({ bucket }) })`; building does no I/O. `store.segment(name)` is a handle\n * for `has`, `count`, `iterate` and the combines, and `store.load(ref, ids)` replaces a segment's contents with a new\n * generation.\n */\nexport class CloudRoaring {\n private readonly engine: SegmentEngine;\n /** This store's identity: every handle it makes carries this object, and a combine compares it by reference. */\n private readonly origin: object = Object.freeze({});\n private readonly cache: BoundedLru<string, CodecBitmap>;\n /** The store's retry options, for a pinned engine to read through as the store's own does; undefined when off. */\n private readonly retryOptions: RetryingOptions | undefined;\n private readonly crbmSource: CrbmStorageChunkSource | undefined;\n private readonly clock: Clock;\n private readonly rng: Rng;\n private readonly entropy: Entropy;\n private readonly metrics: IMetricsSink;\n // The store's own drivers, kept so the lifecycle helpers and the `*Into` verbs reuse them instead of making\n // you re-pass deps. `storageDriver` is set only when `storage` was a raw IStorageDriver (a pre-built StorageChunkSource has\n // no underlying driver to write through).\n private readonly storageDriver: IStorageDriver | undefined;\n private readonly registry: IRegistryDriver | undefined;\n // The backend itself, for its optional `checkLifecycle`; `undefined` for a bare driver or a source.\n private readonly backend: StorageBackend | undefined;\n private readonly keystore: IKeystore | undefined;\n private readonly requireEncryption: boolean;\n /** Resolved store-level per-op budget (null = disabled); the admin scans use it, with a per-op override. */\n private readonly budget: Budget | null;\n /**\n * Moved at the start and at the end of each `eraseSubject` this store runs. A `materializeMany` call with a feed records\n * it when it begins and is refused once it has moved: it reads caller memory, which no erasure can reach.\n */\n private erasureEpoch = 0;\n /** How many `eraseSubject` calls of this store are running: while any is, every check of the counter counts as moved. */\n private erasuresRunning = 0;\n\n /**\n * Refuse any option key the store does not take, at the top level or inside a group, naming each one.\n *\n * An option the store ignored would do nothing and look as if it had \u2014 a typo'd `cache.maxChunk`, a key from\n * another library's config spread into this one \u2014 so every key is checked against {@link OPTION_KEYS}.\n */\n private static rejectUnknownOptions(options: CloudRoaringOptions): void {\n // A nullish or non-object bag never reaches `resolveStorageSource` \u2014 the constructor reads\n // `options.seams?.clock` first and would throw a raw TypeError. Report it here, typed, instead.\n if (options === null || options === undefined || typeof options !== 'object') {\n throw new ValidationError(\n 'CloudRoaring needs an options object with a `storage` key \u2014 got ' +\n (options === null ? 'null' : typeof options),\n );\n }\n const bag = options as unknown as Record<string, unknown>;\n const unknown: Array<{ group: OptionGroup | null; key: string }> = [];\n for (const key of Object.keys(bag)) {\n if (!(OPTION_KEYS.top as readonly string[]).includes(key)) unknown.push({ group: null, key });\n }\n const groups = Object.keys(OPTION_KEYS).filter((g): g is OptionGroup => g !== 'top');\n for (const group of groups) {\n const value = bag[group];\n if (value === undefined) continue;\n const offOk = group === 'retry' || group === 'budget';\n if (value === false && offOk) continue;\n // A group that is not an object configures nothing: `encryption: true` would build a cleartext store. The\n // built-in tag, not `instanceof`, so a boxed `new Boolean(true)` and a Map from another realm are caught.\n const tag = Object.prototype.toString.call(value).slice(8, -1);\n if (typeof value !== 'object' || value === null || NOT_A_GROUP[tag] !== undefined) {\n const got = typeof value !== 'object' ? typeof value : NOT_A_GROUP[tag];\n throw new ValidationError(\n `CloudRoaring's \\`${group}\\` must be an object${offOk ? ' or `false`' : ''} \u2014 got ${got}`,\n );\n }\n const known = OPTION_KEYS[group] as readonly string[];\n for (const key of Object.keys(value)) if (!known.includes(key)) unknown.push({ group, key });\n }\n if (unknown.length === 0) return;\n const takes = (keys: readonly string[]): string => keys.map((k) => `\\`${k}\\``).join(', ');\n const named = [...new Set(unknown.map((u) => u.group))];\n throw new ValidationError(\n `CloudRoaring does not take ${takes(unknown.map((u) => (u.group === null ? u.key : `${u.group}.${u.key}`)))}. ` +\n named\n .map((g) =>\n g === null\n ? `The store takes ${takes(OPTION_KEYS.top)}.`\n : `\\`${g}\\` takes ${takes(OPTION_KEYS[g])}.`,\n )\n .join(' ') +\n ' https://github.com/cloudbitmaps/cloudbitmaps/blob/main/docs/guide/api-reference.md#build-a-store--new-cloudroaringoptions',\n );\n }\n\n /**\n * A seam the store calls through must have the methods it calls. Without this a `clock` with no `now`, an `rng` with\n * no `next` or a keystore with no `createDek` builds a store that throws a raw `TypeError` at its first load or read.\n */\n private static rejectHollowSeams(options: CloudRoaringOptions): void {\n const seams: Array<[unknown, string, readonly string[]]> = [\n [options.seams?.clock, 'seams.clock', ['now', 'sleep']],\n [options.seams?.rng, 'seams.rng', ['next']],\n [options.encryption?.keystore, 'encryption.keystore', ['createDek', 'openDek']],\n ];\n const entropy: unknown = options.seams?.entropy;\n if (entropy !== undefined && typeof entropy !== 'function') {\n throw new ValidationError(\n \"CloudRoaring's `seams.entropy` must be a function `(length) => Uint8Array` returning that many random bytes\",\n );\n }\n for (const [seam, name, needs] of seams) {\n if (seam === undefined) continue;\n const has = (m: string): boolean =>\n seam !== null && typeof (seam as Record<string, unknown>)[m] === 'function';\n if (seam === null || typeof seam !== 'object' || !needs.every(has)) {\n throw new ValidationError(\n `CloudRoaring's \\`${name}\\` must be an object with ${needs.map((m) => `\\`${m}()\\``).join(' and ')}`,\n );\n }\n }\n }\n\n /**\n * Refuse a `cache` or `encryption` value that can never be honoured, by the name the caller wrote. The sizes reach\n * the caches under their own internal names, so left to them an error would name `maxEntries` or `maxBytes`; and\n * `encryption.required` must be exactly a boolean, since the read path took a truthy string for `true` while every\n * write path did not, which refused cleartext reads and still wrote cleartext.\n */\n private static rejectBadValues(options: CloudRoaringOptions): void {\n const cache = options.cache;\n if (cache !== undefined) {\n requirePositiveInt('cache.maxChunks', cache.maxChunks);\n requirePositiveInt('cache.readerMax', cache.readerMax);\n requirePositiveInt('cache.readerMaxBytes', cache.readerMaxBytes);\n const ttl: unknown = cache.ttlMs;\n if (ttl !== undefined && (typeof ttl !== 'number' || !Number.isFinite(ttl) || ttl <= 0)) {\n throw new ValidationError(\n `cache.ttlMs must be a finite number above 0 (milliseconds); got ${typeof ttl === 'string' ? JSON.stringify(ttl) : String(ttl)}`,\n );\n }\n }\n requireBool(\"CloudRoaring's `encryption.required`\", options.encryption?.required);\n }\n\n /**\n * Builds a store. Only `storage` is required: pass a backend such as `S3Storage` or `MemoryStorage`. `cache`,\n * `encryption`, `retry`, `metrics`, `budget` and `seams` tune it. An option it does not take, a `cache` size or `ttlMs`\n * that is not a usable number, an `encryption.required` that is not a boolean, or a seam missing a method the store\n * calls, throws `ValidationError`.\n */\n constructor(options: CloudRoaringOptions) {\n CloudRoaring.rejectUnknownOptions(options);\n CloudRoaring.rejectHollowSeams(options);\n CloudRoaring.rejectBadValues(options);\n const clock = options.seams?.clock ?? new SystemClock();\n const rng = options.seams?.rng ?? new SystemRng();\n const entropy = options.seams?.entropy ?? systemEntropy;\n // Wrap the user sink so a throwing/buggy sink can never break I/O (observability is best-effort).\n const metrics = safeMetrics(options.metrics ?? NOOP_METRICS);\n const cache = new BoundedLru<string, CodecBitmap>({\n maxEntries: options.cache?.maxChunks ?? DEFAULT_CACHE_MAX_CHUNKS,\n ttlMs: options.cache?.ttlMs,\n clock,\n });\n // Resolve the storage seam, hand a backend the metrics sink, and wrap the source in the read retry: `wireStore`.\n const wired = wireStore(options, clock, rng, metrics);\n this.retryOptions = wired.retryOptions;\n // Resolve the denial-of-wallet budget once (validates; `false` \u21D2 null = disabled) and share it between the\n // engine (count/iterate/combines) and the facade's admin scans (subjectReport/eraseSubject).\n this.budget = resolveBudget(options.budget, DEFAULT_BUDGET);\n const deps: EngineDeps = {\n storage: wired.storage,\n cache,\n codec: flagshipCodec(), // the facade injects the flagship codec; core stays codec-agnostic\n clock,\n metrics,\n budget: this.budget,\n };\n this.engine = new SegmentEngine(deps);\n this.cache = cache;\n // The UNWRAPPED `.crbm` source, kept for `pin()` \u2014 the only reader that resolves a specific generation.\n // `undefined` when the caller supplied a pre-built source, which has nothing to pin.\n this.crbmSource = wired.source instanceof CrbmStorageChunkSource ? wired.source : undefined;\n this.clock = clock;\n this.rng = rng;\n this.entropy = entropy;\n this.metrics = metrics;\n // Keep the raw drivers for the lifecycle helpers (see the fields above). They use the raw drivers directly \u2014\n // a one-shot admin op surfaces a transient fault to the caller rather than retrying under the hood \u2014 except for\n // the reads a load's guard and an erasure make along the way, which take the store's read retry (`readRetry`),\n // since a read is safe to repeat and one fault there would otherwise fail the whole write.\n this.storageDriver = wired.driver;\n this.registry = wired.registry;\n if (this.registry !== undefined) REGISTRY_OF.set(this.origin, this.registry);\n this.backend = wired.backend;\n this.keystore = options.encryption?.keystore;\n this.requireEncryption = options.encryption?.required ?? false;\n }\n\n /**\n * The write-side deps, from the store's own drivers, for the lifecycle helpers and the `*Into` verbs. Requires\n * the store to have been constructed with a **backend**, which supplies both halves: an `IStorageDriver` to\n * write generations through (a pre-built `StorageChunkSource` has none) and the registry holding the pointer\n * every write publishes.\n */\n private lifecycleDeps(op: string): LifecycleDeps {\n if (this.storageDriver === undefined) {\n throw new UnsupportedError(\n `${op} needs the store built with a storage backend \u2014 S3Storage, GcsStorage, AzureBlobStorage, ` +\n `LocalFsStorage or MemoryStorage. A pre-built StorageChunkSource is read-only: it has no ` +\n `IStorageDriver underneath to write generations through. Build the store on one of those backend ` +\n `classes to write.`,\n );\n }\n if (this.registry === undefined) {\n throw new UnsupportedError(\n `${op} needs a storage backend \u2014 S3Storage, GcsStorage, AzureBlobStorage, LocalFsStorage or ` +\n `MemoryStorage. A bare IStorageDriver has no generation pointer to publish through, and there is ` +\n `no separate \\`registry\\` option: a backend carries it.`,\n );\n }\n return {\n storage: this.storageDriver,\n registry: this.registry,\n clock: this.clock,\n rng: this.rng,\n entropy: this.entropy,\n codec: flagshipCodec(), // facade injects the flagship codec\n keystore: this.keystore,\n requireEncryption: this.requireEncryption,\n readRetry: this.retryOptions,\n };\n }\n\n /**\n * Get a handle to a segment. Validates the name (non-empty, well-formed, within the encoded-length cap). The options\n * are a plain object holding `{ namespace }` and nothing else: any other own key, enumerable or not, is refused with\n * {@link ValidationError}, by name, since a misspelt `namespace` would otherwise address the default namespace, and a\n * deadline such as `expiresAt` would be left unread. A class instance, or an object built on another, is refused too,\n * since it can carry an option no scan of its own keys sees. A key whose value is `undefined` is read as absent, so a\n * spread of options keeps working.\n */\n segment(name: string, options?: SegmentOptions): Segment {\n if (typeof name === 'object' && name !== null) {\n throw new ValidationError(\n Array.isArray(name)\n ? \"segment: the name is a string, store.segment('name'), not an array\"\n : 'segment: the name is a string, not a ref: for a ref, call store.segment(ref.segment, { namespace: ref.namespace })',\n );\n }\n if (options !== undefined && options !== null) {\n if (typeof options !== 'object' || Array.isArray(options)) {\n throw new ValidationError('segment: options must be an object such as { namespace }');\n }\n // A plain object of any realm has a prototype whose own prototype is null.\n const proto = Object.getPrototypeOf(options) as object | null;\n if (proto !== null && Object.getPrototypeOf(proto) !== null) {\n throw new ValidationError(\n 'segment: options must be a plain object such as { namespace }, not a class instance or an object built on another',\n );\n }\n const unknown = Object.getOwnPropertyNames(options).filter(\n (k) => k !== 'namespace' && (options as Record<string, unknown>)[k] !== undefined,\n );\n if (unknown.length > 0) {\n throw new ValidationError(\n `segment: unknown option${unknown.length > 1 ? 's' : ''} ${unknown.map((k) => `\"${k}\"`).join(', ')}; ` +\n 'a handle takes { namespace } only',\n );\n }\n }\n const ref: SegmentRef = { segment: name, namespace: options?.namespace };\n validateSegmentRef(ref);\n refuseReservedNamespace(ref.namespace);\n return makeSegment({\n engine: this.engine,\n origin: this.origin,\n ref,\n clock: this.clock,\n metrics: this.metrics,\n materialize: (dest, ids, op, options) => this.materialize(dest, ids, op, options),\n pinned: (r, l, at) => this.pinSegment(r, l, at),\n combineEngine: (handles) => this.engineForCombine(handles),\n });\n }\n\n /**\n * Write `ids` as a **new generation of `dest`** and publish it \u2014 the shared body of the `*Into` verbs. An `*Into`\n * materialisation is a load, and publishes the same way (hard invariant 1): every load that finds a row fences its\n * publish on the row's token, and every load that finds none on that absence, guarded or not; a guarded load (the\n * default, since the empty refusal needs the size of the current generation) also fences on the pointer it judged\n * (`expectFrom`). The destination's previous generation stays readable until the publish lands (readers re-resolve\n * within `cache.genTtlMs`).\n *\n * This routes through `loadSegment` rather than writing the generation itself, and that is the whole point\n * of it. A materialisation is a load whose ids happen to come from a combine instead of from upstream, so\n * everything `load()` learned the hard way applies unchanged: the generation is written UNPUBLISHED, the\n * guard runs while the old generation is still authoritative, the publish is fenced as above, and a refused\n * object is reclaimed only when a re-read finds the row unchanged (the same token, or one that differs only in\n * its leases), `destroyed`, or gone, or finds key material on it when the load wrote cleartext; under any other\n * row it is kept (hard invariant 1: deleting it after a purge-and-recreate would put a live row over a missing\n * generation).\n *\n * Where the row is gone, or keyed over a cleartext write, the object's footer must match what the load wrote, and\n * the delete passes the version that read reported, so on a storage driver that reports `conditionalDelete` an\n * object put under the number since is kept. Where the row is unchanged or `destroyed`, the check narrows the\n * window rather than closing it: the row read and the delete are two round trips, and the delete is by number,\n * since the write reports no version of the object it made. The other deletes a load leads to are by number too: its\n * collection deletes what a listing, or the row's list of kept generations, names below the pointer, and a drop's\n * sweep and a tombstoned segment's collection delete what a listing names under a `destroyed` row. The failure the\n * checks leave when they refuse is an orphan object, which costs storage until something collects it \u2014\n * deliberately the cheaper side of the trade.\n *\n * Written and published in one step, with no guard, an empty combine \u2014 a typo'd operand, an `exclude` that\n * swallowed everything, an operand that had not loaded yet \u2014 would silently replace `dest` with an empty\n * generation: the same failure `load()`'s guard exists to prevent, on the same data, reachable without passing\n * any option at all.\n *\n * **A lost race throws.** `loadSegment` reports one as `reason: 'superseded'`; the `*Into` verbs throw\n * {@link WriteConflictError} for it, so a caller can `catch (WriteConflictError)`. That one refusal is\n * translated into the throw, and `MaterializeResult.reason` never carries it.\n *\n * **A `WriteConflictError` does not by itself mean nothing was published**, and that is worth knowing\n * before you write the retry. `'superseded'` covers five different causes \u2014 the write-once PUT collided,\n * the pointer moved, a row appeared where the load found none, the row's token changed, the row was purged \u2014\n * and only the first two are always the \"somebody beat us\" the name suggests. A row can appear, and a token can\n * change, on a write that is not a supersession at all: a `setRetention` on the destination creates its row when it\n * has none, and rewrites it when it has one. On top of that, the collection pass that runs AFTER a successful\n * publish can raise the same error. So: treat it as \"re-read the destination and decide\",\n * never as \"the write did not happen\".\n *\n * **And by default it collects nothing**, unlike `load()`. See the `keep` default below.\n */\n private async materialize(\n dest: SegmentRef,\n ids: LoadInput | CombineChunks,\n op: string,\n options?: CombineOptions,\n ): Promise<MaterializeResult> {\n // A materialisation's `keep` collects every generation below the new one beyond it, which a destination that\n // earlier materialisations kept in full needs a listing for.\n const deps = { ...this.lifecycleDeps(op), collectByListing: true };\n // Read once, here: a getter or a proxy answering twice would otherwise be checked as one value and stored as another.\n const metadata = options?.metadata;\n let result: Awaited<ReturnType<typeof loadSegment>>;\n try {\n const loadOptions = {\n ...(options?.allowEmpty === undefined ? {} : { allowEmpty: options.allowEmpty }),\n ...(options?.guard === undefined ? {} : { guard: options.guard }),\n ...(metadata === undefined ? {} : { metadata }),\n // COLLECT NOTHING by default, which `loadSegment` does not \u2014 it keeps a grace window of 1 and deletes\n // the rest. By default a materialisation collects nothing: the guide states \"**It deletes nothing**,\n // unlike `load()`. The destination's previous generations stay in the bucket until you collect them\", and\n // the ownership table\n // puts that call on the operator. Inheriting `load()`'s collection would silently delete the\n // generations an operator's recovery story depends on \u2014 `rollbackSegment` refuses a collected target \u2014\n // as a side effect of adding a guard whose entire purpose is preventing data loss. Opt in with `keep`.\n keep: options?.keep === undefined ? KEEP_EVERY_GENERATION : options.keep,\n ...(options?.audit === undefined ? {} : { audit: options.audit }),\n };\n result =\n ids instanceof CombineChunks\n ? await loadSegmentChunks(dest, ids.chunks, deps, loadOptions)\n : await loadSegment(dest, ids, deps, loadOptions);\n } finally {\n // As `load()` does: this store's view of `dest` is behind whatever just happened, and a throw can still have\n // published first. Left alone, the store read its own write's predecessor: indefinitely, with no timed refresh.\n this.engine.invalidate(dest);\n }\n // Checked on `reason` alone, not `published && reason`: the compiler narrows a const through an equality\n // test, so after this throw `reason` is provably a `MaterializeRefusal` and the return below type-checks\n // without an assertion. `'superseded'` only ever accompanies `published: false` anyway.\n const reason = result.reason;\n if (reason === 'superseded') {\n // The object is durable, but this call's write may not be the one that made it current: a concurrent writer\n // published a higher generation of `dest` between our numbering and our publish, or a write that renewed the\n // row over ours left us unable to tell it from another writer's. Ours may then be an orphan no reader will\n // resolve. Returning it here would name `generation` as \"the destination's new current generation\" \u2014 which is\n // what `MaterializeResult` documents it to be, and it could be false. The destination may hold someone else's\n // content.\n //\n // A throw rather than a flag: every other write path in the library reports a lost race loudly, and a\n // materialisation that silently did not take effect is the one outcome a caller cannot detect on its\n // own.\n // `size > 0` distinguishes the two ways a materialisation loses the race, and the operator needs them\n // apart: the object either exists (an orphan, collected by the first load that collects once a generation\n // above it is current or deleted by the refusal itself when the destination was dropped meanwhile; or current\n // but not provably this call's, when a write renewed the row's `pointerId` over it) or was never written at all,\n // because the write-once PUT itself collided. Telling someone to look for an\n // orphan that does not exist is a wasted investigation.\n // Deliberately does NOT assert which of the four causes it was. \"A newer generation was published first\"\n // is wrong for two of them: a `setRetention` on the\n // destination bumps the row's token without publishing anything, and a purge leaves no row at all.\n // Telling an operator to go looking for a newer generation that does not exist costs a real\n // investigation. `size > 0` is the one thing this path can state as fact.\n const wrote =\n result.size > 0\n ? `generation ${result.generation} was written and may not be current`\n : `nothing was written \u2014 another writer took generation ${result.generation} first`;\n throw new WriteConflictError(\n `${op}: the destination \"${dest.segment}\" changed while this materialisation was in flight, so its ` +\n `result may not be the destination's current generation: ${wrote}. The pointer may have moved, the row may have been created or rewritten ` +\n `(a retention policy does either), dropped or purged. Re-read the destination and re-run.`,\n );\n }\n return {\n generation: result.generation,\n published: result.published,\n ...(reason === undefined ? {} : { reason }),\n cardinality: result.cardinality,\n cardinalityBefore: result.cardinalityBefore,\n chunkCount: result.chunkCount,\n size: result.size,\n collected: result.collected,\n };\n }\n\n /**\n * **A dry run:** every output computed exactly as the call would compute it, and judged against its `dest` as its\n * publish would be, with nothing written: no object, no pointer, no audit event. Each output's result says how many ids\n * it would hold, what its `dest` holds now, and the bound its publish would be refused for now (`wouldRefuse`). The\n * call reads its operands as a publishing call does, takes its feed if it has one, and fails an output for what would\n * fail its publish (a `dest` whose lease has ended, a destroyed one, a moved exclude, an erasure). It reads the operands as\n * the publishing call does, and for each output the reads a publish's guard makes: one registry read for `dest`'s size,\n * or two where its row has no usable summary. It holds the memory a publish would, so it fails for memory where one\n * would, and reports to the metrics sink as the same `materializeMany` op.\n *\n * What it reports holds for now only: a publish made later reads the operands and judges each `dest` as they are then.\n * To publish what was reviewed, call again without `dryRun`, on the same pinned handles or with the same feed (the\n * guide's recipe).\n */\n materializeMany(options: MaterializeManyDryRunOptions): Promise<MaterializeManyDryRun>;\n /**\n * The call with `dryRun` a switch held in a variable, optional or not: a {@link MaterializeManyDryRun} when it is\n * `true` and a {@link MaterializeManyRun} when it is `false` or absent, so with a `boolean` (or `boolean | undefined`)\n * the result is typed as either, and the flag passed says which. A literal `true` or `false`, and a call without\n * `dryRun`, are typed exactly, as by the forms either side of this one.\n */\n materializeMany<D extends boolean | undefined = undefined>(\n options: MaterializeManyOptions & { readonly dryRun?: D },\n ): Promise<D extends true ? MaterializeManyDryRun : MaterializeManyRun>;\n /**\n * **Many outputs, each operand read once per group.** Each output is an expression over named stored operands (`and`, `or`, `andNot`, nested\n * to depth 64) published as a new generation of its own `dest`, exactly as an `*Into` would publish it, but computed\n * together: each operand's chunks are read once for all the outputs that use them, instead of once per output and\n * once more for every scratch segment a nested expression would otherwise need.\n *\n * ```ts\n * const run = await store.materializeMany({\n * operands: { us: store.segment('us'), engaged: store.segment('engaged'), optOut: store.segment('opt-out') },\n * outputs: [\n * { dest: store.segment('send-1'), expr: { and: ['us', 'engaged'] }, exclude: ['optOut'] },\n * { dest: store.segment('send-2'), expr: { andNot: ['us', 'engaged'] } },\n * ],\n * keep: 3,\n * });\n * run.outputs[0]; // a MaterializeResult, or { published: false, error }\n * ```\n *\n * **Results.** `run.outputs[i]` is index-aligned with `outputs` and is exactly what output `i`'s `*Into` would have\n * returned (a {@link MaterializeResult}: published, or refused with its `reason`), or `{ published: false, error }` for\n * what it would have thrown. One output's refusal or error never stops another. The call itself throws only for bad\n * input ({@link ValidationError} naming the output index and path, before any request), an operand that names no\n * segment (unless `allowAbsentOperands`), and a `budget` its own plan exceeds, the last two before any chunk is read.\n *\n * **One generation per operand.** By default every stored operand is pinned for the call: read at the generation it had\n * when the call started, however long the call runs and whatever loads land meanwhile. That is one generation per\n * operand, not one instant across operands (two pins are two registry reads). `pin: false` reads live, as a combine does.\n *\n * **Every pinned operand an output subtracts is re-checked.** An output subtracts an operand when it is in its `exclude`\n * or under any entry of an `andNot` after the first, at any depth. Immediately before the publishes the call re-reads the\n * registry row of each such operand and compares its generation and incarnation, and the fingerprint of the current\n * object where both reads carry one, with what was pinned (a name deleted and created again is a replacement though it\n * is generation 0 again). If one was replaced, each output that subtracts it is\n * not published and carries {@link StaleOperandError}; the others publish. It costs one registry read per such operand per\n * group, and `stats.operands` carries every operand's pinned, start and end generation and whether it moved.\n *\n * **Memory.** Everything the pass holds resident is counted against `maxBufferedBytes` (default 256 MiB): each output's\n * buffered chunks, the operand streams' ranges, the chunks being evaluated, and the plan itself, and a call whose plan alone\n * passes it is refused before any chunk is read. When the outputs do not fit, they run in groups, each reading its operands\n * once (so the operand reads grow with the total output size over the budget), and a group's buffers are released only as\n * its publishes settle. A chunk count the index understated does not grow a group past the budget: the largest buffer is\n * dropped and that output re-runs alone. An output that cannot fit alone has `BudgetExceededError` as its result. The count\n * is the pass's own: process memory is more, measured at 1.6 times the ledger's high water on Linux and 2.5 to 5 times on\n * macOS on the in-memory backend (the guide has the shapes and what is not counted).\n *\n * **Untrusted bytes.** Every operand chunk is decoded through the checks on untrusted tier data. A key an operand's index\n * lists whose bytes are missing is an error for the outputs that read the operand, never an empty chunk.\n *\n * **Handles.** A handle anywhere in the call (an operand or a `dest`) whose lease has ended or was released is refused\n * before any request, as on the `*Into` verbs. A leased operand's lease is checked before each chunk key is read: a\n * lapse fails only the outputs that read that operand, never reads empty. Each `dest`'s lease is checked again just\n * before its publish.\n *\n * **The chunk cache is bypassed:** the pass reads through the storage source and never writes the decoded-chunk cache, so\n * a batch does not evict other readers' hot chunks. Each publish still invalidates its `dest` as an `*Into` does.\n *\n * **A limit of the form.** An output cannot name another output of the same call: a `dest` that is also an operand is\n * refused. Chain two calls.\n *\n * **A feed.** `feed: { names, records, counts }` adds operands that arrive as records in chunk-key order, for conditions\n * too many to hold or store. Each record is checked before the pass sees it (see {@link MaterializeManyFeedRecord}): a bad\n * feed is refused, never read as fewer members, and **a fed output is published only after the whole feed was read and every\n * end-of-feed check passed**, so a bad feed refuses every fed output and publishes none of them; outputs that name only\n * stored operands are unaffected. At the end of the feed `counts` must equal the ids the feed held for each name, and a\n * name that appeared in no record is refused unless it is in `mayBeEmpty`. A feed is read once, so the call runs its outputs\n * as one group and **`maxBufferedBytes` is required**: each record is converted to compressed bitmaps as it arrives, the key\n * in hand and its fed outputs are counted against the budget, and the call fails as soon as the count passes it, with\n * {@link BudgetExceededError} for every fed output. **Erasure:** a fed call is refused at its next record, and before each\n * fed publish, once `eraseSubject` has started in this store ({@link StaleOperandError}, `reason: 'erased'`).\n *\n * ```ts\n * await store.materializeMany({\n * operands: { unsub: store.segment('global-unsub') },\n * feed: {\n * names: ['us', 'engaged'],\n * records: warehouseRecords(), // yields { key, operands: { us: Uint32Array, engaged: Uint32Array } } by key\n * counts: () => warehouseCounts(),\n * },\n * maxBufferedBytes: 512 * 1024 * 1024,\n * outputs: [{ dest: store.segment('send-1'), expr: { and: ['us', 'engaged'] }, exclude: ['unsub'] }],\n * keep: 12,\n * });\n * ```\n */\n materializeMany(\n options: MaterializeManyOptions & { readonly dryRun?: false },\n ): Promise<MaterializeManyRun>;\n /** The one body of the forms above. */\n async materializeMany(\n options: MaterializeManyOptions & { readonly dryRun?: boolean },\n ): Promise<MaterializeManyRun | MaterializeManyDryRun> {\n if (typeof options !== 'object' || options === null) {\n throw new ValidationError(\n 'materializeMany needs an options object with `operands`, `outputs` and `keep`',\n );\n }\n // The erasure counter as the call begins: a fed call is refused once it has moved.\n const epochAt = options.feed === undefined ? 0 : this.epochNow();\n const unknown = unknownManyKeys(options);\n if (unknown.length > 0) {\n throw new ValidationError(\n `materializeMany: unknown option${unknown.length > 1 ? 's' : ''} ${unknown.map((k) => `\"${k}\"`).join(', ')}`,\n );\n }\n // Read once, here: a getter or a proxy answering twice would be checked as one value and used as another.\n const dryRunIn: unknown = options.dryRun;\n if (dryRunIn !== undefined && typeof dryRunIn !== 'boolean') {\n throw new ValidationError('materializeMany: dryRun must be a boolean');\n }\n const dryRun = dryRunIn === true;\n const operandsIn: unknown = options.operands;\n const outputsIn: unknown = options.outputs;\n const keep = options.keep;\n const after = options.after;\n const through = options.through;\n // `null` is not the default: a switch is `true` or `false`, as on every call.\n const pinOption: unknown = options.pin === undefined ? true : options.pin;\n const feedIn: unknown = options.feed;\n const mayBeEmptyIn: unknown = options.mayBeEmpty;\n if (feedIn !== undefined && options.maxBufferedBytes === undefined) {\n throw new ValidationError(\n 'materializeMany: maxBufferedBytes is required with a feed: the feed is read once, so the call runs as one group and the budget is what bounds it',\n );\n }\n const maxBufferedBytes = options.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES;\n const publishConcurrency = options.publishConcurrency ?? DEFAULT_PUBLISH_CONCURRENCY;\n const concurrency = options.concurrency ?? DEFAULT_BATCH_CONCURRENCY;\n const budgetOption = options.budget;\n const allowAbsentOperands = options.allowAbsentOperands;\n if (typeof pinOption !== 'boolean')\n throw new ValidationError('materializeMany: pin must be a boolean');\n if (allowAbsentOperands !== undefined && typeof allowAbsentOperands !== 'boolean') {\n throw new ValidationError('materializeMany: allowAbsentOperands must be a boolean');\n }\n if (typeof operandsIn !== 'object' || operandsIn === null || Array.isArray(operandsIn)) {\n throw new ValidationError('materializeMany: operands must be an object of name to segment');\n }\n if (!Array.isArray(outputsIn) || outputsIn.length === 0) {\n throw new ValidationError('materializeMany: outputs must be a non-empty array');\n }\n const names = Object.keys(operandsIn);\n const handles = new Map<string, Segment>();\n for (const name of names) {\n const handle = (operandsIn as Record<string, unknown>)[name];\n assertOneStore('materializeMany', `operands[\"${name}\"]`, handle, this.origin);\n handles.set(name, handle);\n }\n // `mayBeEmpty` names fed operands, which the feed checks; without a feed it can name nothing.\n if (mayBeEmptyIn !== undefined && feedIn === undefined) {\n if (!Array.isArray(mayBeEmptyIn)) {\n throw new ValidationError(\n 'materializeMany: mayBeEmpty must be an array of fed operand names',\n );\n }\n if (mayBeEmptyIn.length > 0) {\n const first: unknown = mayBeEmptyIn[0];\n const what =\n typeof first !== 'string'\n ? 'something that is not a name'\n : handles.has(first)\n ? `\"${first}\", a stored operand`\n : `\"${first}\", which is not an operand of this call`;\n throw new ValidationError(\n `materializeMany: mayBeEmpty names ${what}; it names fed operands, and this call has no feed`,\n );\n }\n }\n const operandKeys = new Set([...handles.values()].map((h) => h.key()));\n const outputs: Array<{ spec: MaterializeManyOutput; dest: Segment }> = [];\n const destKeys = new Set<string>();\n (outputsIn as unknown[]).forEach((raw, i) => {\n if (typeof raw !== 'object' || raw === null) {\n throw new ValidationError(`outputs[${i}] must be an object`);\n }\n const bad = Object.keys(raw).filter(\n (k) => !(MATERIALIZE_MANY_OUTPUT_KEYS as readonly string[]).includes(k),\n );\n if (bad.length > 0) {\n throw new ValidationError(\n `outputs[${i}]: unknown option${bad.length > 1 ? 's' : ''} ${bad.map((k) => `\"${k}\"`).join(', ')}`,\n );\n }\n const spec = raw as MaterializeManyOutput;\n const dest: unknown = spec.dest;\n assertOneStore('materializeMany', `outputs[${i}].dest`, dest, this.origin);\n if (operandKeys.has(dest.key())) {\n throw new ValidationError(\n `outputs[${i}].dest is also an operand of the call: one call is one pass over operands that do not change under it, so chain two calls`,\n );\n }\n if (destKeys.has(dest.key())) {\n throw new ValidationError(\n `outputs[${i}].dest names a segment another output of the call writes`,\n );\n }\n destKeys.add(dest.key());\n outputs.push({ spec, dest });\n });\n // A ceiling the store was built with applies to a call that names none, as it does to every other operation; only a\n // store left on the library default lets the call size its own from its plan.\n const storeCeiling =\n this.budget === null || this.budget.maxRequests !== DEFAULT_BUDGET.maxRequests\n ? this.budget\n : undefined;\n const budget =\n budgetOption === undefined ? storeCeiling : resolvePerOpBudget(budgetOption, this.budget);\n // Every expression and option is checked here, with no operand pinned and no request made.\n const operandSpecs = (pins: ReadonlyMap<string, PinnedAt | undefined>): CombineManyOperand[] =>\n names.map((name) => {\n const handle = handles.get(name)!;\n const seg = viewOf(handle);\n const pinnedAt = pins.get(handle.key());\n return {\n name,\n ref: seg.ref,\n ...(handle.lease === undefined ? {} : { check: () => this.assertLease(handle) }),\n ...(pinnedAt === undefined\n ? {}\n : {\n pinnedGeneration: pinnedAt.generation,\n pinnedVersion: pinnedAt.version,\n pinnedFingerprint: pinnedAt.fingerprint,\n }),\n current: (read?: { readonly fingerprint?: boolean }) =>\n this.currentRowOf(seg.ref, read?.fingerprint === true),\n };\n });\n const request = (pins: ReadonlyMap<string, PinnedAt | undefined>) => ({\n operands: operandSpecs(pins),\n outputs: outputs.map(({ spec, dest }) => ({\n expr: spec.expr,\n ...(spec.exclude === undefined ? {} : { exclude: spec.exclude }),\n ...(spec.allowEmpty === undefined ? {} : { allowEmpty: spec.allowEmpty }),\n ...(spec.guard === undefined ? {} : { guard: spec.guard }),\n ...(spec.metadata === undefined ? {} : { metadata: spec.metadata }),\n ...(spec.keep === undefined ? {} : { keep: spec.keep }),\n beforePublish: () => this.assertLease(dest),\n // What a settled publish proves it sent: a published one wrote its object and moved the pointer, a refused one\n // wrote its object and deleted it. A dry run's judgement wrote nothing, and read the row and maybe the object.\n requestsOf: (result: MaterializeResult | DryRunValue) =>\n 'dryRun' in result\n ? { get: result.reads, put: 0 }\n : { get: 0, put: result.published ? 2 : 1 },\n publish: (\n chunks: AsyncIterable<{ readonly chunkKey: number; readonly bitmap: CodecBitmap }>,\n write: {\n readonly keep: number;\n readonly allowEmpty?: boolean;\n readonly guard?: LoadGuard;\n readonly metadata?: GenerationMetadata;\n },\n ): Promise<MaterializeResult | DryRunValue> =>\n dryRun\n ? this.judgeOutput(viewOf(dest).ref, chunks, write)\n : this.materialize(viewOf(dest).ref, new CombineChunks(chunks), 'materializeMany', {\n ...write,\n ...(spec.audit === undefined ? {} : { audit: spec.audit }),\n }),\n })),\n keep: keep as number,\n ...(after === undefined ? {} : { after }),\n ...(through === undefined ? {} : { through }),\n maxBufferedBytes,\n publishConcurrency,\n concurrency,\n ...(budget === undefined ? {} : { budget }),\n ...(allowAbsentOperands === undefined ? {} : { allowAbsentOperands }),\n ...(feedIn === undefined ? {} : { feed: this.feedOf(feedIn, mayBeEmptyIn, epochAt) }),\n ...(dryRun ? { dryRun: true } : {}),\n });\n const compiled = compileCombineMany(request(new Map()));\n // A handle anywhere whose lease has ended or was released is refused before any request, as the `*Into` verbs refuse one.\n for (const { dest } of outputs) this.assertLease(dest);\n for (const handle of handles.values()) this.assertLease(handle);\n this.lifecycleDeps('materializeMany');\n const crbm = this.crbmSource;\n if (crbm === undefined) {\n throw new UnsupportedError(\n 'materializeMany needs the `.crbm` storage source \u2014 pass a backend or a raw IStorageDriver as `storage`',\n );\n }\n // One pin per segment, shared by every name that holds it. A handle passed already pinned is used as it is.\n const held = new Map<string, { at: PinnedAt | undefined; handle: Segment }>();\n for (const [name, handle] of handles) {\n const key = handle.key();\n const at = handle.pinnedAt;\n const prior = held.get(key);\n if (prior === undefined) {\n held.set(key, { at, handle });\n } else if (prior.at !== undefined && at !== undefined) {\n if (!samePin(prior.at, at)) {\n throw new ValidationError(\n `materializeMany: operand \"${name}\" holds a segment another operand holds, ${twoPins(prior.at, at)}: one call reads a segment at one generation`,\n );\n }\n } else if (prior.at !== undefined || at !== undefined) {\n if (!pinOption) {\n throw new ValidationError(\n `materializeMany: operand \"${name}\" holds a segment another operand holds, ${twoPins(prior.at, at)}: one call reads a segment at one generation`,\n );\n }\n if (at !== undefined) held.set(key, { at, handle });\n }\n }\n const pins = new Map<string, PinnedAt | undefined>();\n const toPin: Array<[string, Segment]> = [];\n for (const [key, { at, handle }] of held) {\n if (at !== undefined) pins.set(key, at);\n else if (pinOption) toPin.push([key, handle]);\n else pins.set(key, undefined);\n }\n // Timed from the first request, the pins, to the last publish, as an `*Into` call is timed around its read and write.\n const metricsOn = this.metrics !== NOOP_METRICS;\n const work = async () => {\n const taken = await mapWithConcurrency(\n toPin,\n PIN_PARALLELISM,\n async ([key, handle]) => [key, (await handle.pin()).pinnedAt] as const,\n );\n for (const [key, at] of taken) pins.set(key, at);\n const live = new Map([...pins].filter((e): e is [string, PinnedAt] => e[1] !== undefined));\n const pinnedSource = new PinnedStorageChunkSource(crbm, live);\n const source =\n this.retryOptions === undefined\n ? pinnedSource\n : new RetryingStorageChunkSource(pinnedSource, this.retryOptions);\n const final = rebindCombineMany(compiled, operandSpecs(pins));\n return runCombineMany(final, {\n source,\n codec: flagshipCodec(),\n clock: this.clock,\n ...(metricsOn ? { metrics: this.metrics } : {}),\n });\n };\n const run = metricsOn\n ? await timeOp(this.metrics, this.clock, 'materializeMany', work)\n : await work();\n const results = run.outputs.map((o) => {\n if (!o.ok) {\n return {\n published: false as const,\n error: o.error instanceof Error ? o.error : new Error(String(o.error)),\n };\n }\n if (!('dryRun' in o.value)) return o.value;\n const v = o.value;\n const judged: MaterializeDryRunResult = {\n dryRun: true,\n published: false,\n cardinality: v.cardinality,\n cardinalityBefore: v.cardinalityBefore,\n ...(v.wouldRefuse === undefined ? {} : { wouldRefuse: v.wouldRefuse }),\n };\n return judged;\n });\n return dryRun\n ? { outputs: results as MaterializeManyDryRunOutcome[], stats: run.stats }\n : { outputs: results as MaterializeManyOutcome[], stats: run.stats };\n }\n\n /**\n * A dry run's publish of one output: count what the finished chunks hold, and judge that size against `dest` as a\n * load would, writing nothing.\n */\n private async judgeOutput(\n dest: SegmentRef,\n chunks: AsyncIterable<{ readonly chunkKey: number; readonly bitmap: CodecBitmap }>,\n write: { readonly allowEmpty?: boolean; readonly guard?: LoadGuard },\n ): Promise<DryRunValue> {\n let cardinality = 0;\n for await (const chunk of chunks) cardinality += chunk.bitmap.size;\n const judged = await judgeLoad(dest, cardinality, this.lifecycleDeps('materializeMany'), {\n ...(write.allowEmpty === undefined ? {} : { allowEmpty: write.allowEmpty }),\n ...(write.guard === undefined ? {} : { guard: write.guard }),\n });\n return {\n dryRun: true,\n published: false,\n cardinality,\n cardinalityBefore: judged.cardinalityBefore,\n ...(judged.wouldRefuse === undefined ? {} : { wouldRefuse: judged.wouldRefuse }),\n reads: judged.reads,\n };\n }\n\n private epochNow(): number {\n return this.erasureEpoch;\n }\n\n /**\n * Whether an erasure has started in this store since `at` was read, or was running when it was: one that is still\n * running is seen by the count of those running, and one that has ended since by the counter, which its end moved.\n * The one check every call that reads caller memory uses.\n */\n private epochMoved(at: number): boolean {\n return this.erasuresRunning > 0 || this.epochNow() !== at;\n }\n\n /** A call's feed with the store's erasure counter: read once here, checked by the combine before any record is read. */\n private feedOf(feed: unknown, mayBeEmpty: unknown, epochAt: number): CombineManyFeed {\n if (typeof feed !== 'object' || feed === null || Array.isArray(feed)) {\n throw new ValidationError(\n 'materializeMany: feed must be an object with names, records and counts',\n );\n }\n const f = feed as Record<string, unknown>;\n return {\n names: f.names as string[],\n records: f.records as AsyncIterable<MaterializeManyFeedRecord>,\n counts: f.counts as CombineManyFeed['counts'],\n ...(mayBeEmpty === undefined ? {} : { mayBeEmpty: mayBeEmpty as string[] }),\n epoch: { moved: () => this.epochMoved(epochAt) },\n };\n }\n\n /**\n * The registry row of `ref`, read straight from the registry, not from a snapshot: a re-check must see a move. With\n * `fingerprint`, the current generation's object is opened too (one tail read, as a pin of it makes), and its\n * fingerprint is returned beside the row: a generation's number is identified by its row and its object, since a number\n * can be taken again once its object is gone.\n */\n private async currentRowOf(\n ref: SegmentRef,\n fingerprint: boolean,\n ): Promise<{ generation: number | null; token: string; fingerprint?: string | null } | null> {\n const registry = this.requireRegistry('materializeMany');\n if (fingerprint && this.crbmSource !== undefined) {\n const crbm = this.crbmSource;\n const at = await this.withRetries(() => crbm.pinGeneration(ref));\n const colon = at?.version.indexOf(':') ?? -1;\n if (at !== null && colon >= 0) {\n return {\n generation: at.generation,\n token: at.version.slice(colon + 1),\n fingerprint: at.fingerprint,\n };\n }\n }\n const row = await this.withRetries(() => registry.get(ref));\n return row === null ? null : { generation: row.currentGen, token: pointerIdOf(row) };\n }\n\n /** Throw what a read of, or a publish to, `handle` must throw now: its lease error, if it has one. */\n private assertLease(handle: Segment): void {\n const lease = viewOf(handle).leaseError();\n if (lease !== undefined) throw lease;\n }\n\n /**\n * **Subject access (GDPR Art. 15 / CCPA right-to-know): which segments is this id a member of?**\n *\n * Enumerates the **registered** segments (via the store's own `registry`) and does a `has(id)` on each \u2014 no\n * drivers to re-pass. Complete only over registered segments (every loaded segment has a row, so build the\n * store on the backend the loads used). There is deliberately **no `id \u2192 segments` reverse index** \u2014 that would\n * tax every load for a rare request; this admin scan is `O(registered segments)` and touches no hot path. Needs\n * a storage backend (throws {@link UnsupportedError} otherwise).\n *\n * **Scope: one `namespace`, or `{ allNamespaces: true }`, never both** (both throws `ValidationError`, as does\n * neither). A segment loaded with no `namespace` is in no namespace you can name: only `{ allNamespaces: true }`\n * reaches it. `'_default'`, the label the export tool and the disaster-recovery samples print, and the bucket's\n * object keys use, for such a segment, is an ordinary namespace name here, and passing it scans a namespace of that name, not those segments.\n *\n * **Current as of the registry row, not as of the reader's cache.** Each segment's resolved generation is\n * compared with the row the scan listed, and a segment whose cached generation differs is re-resolved before the\n * read, so a load or an erasure from another process shows at once \u2014 whatever `cache.genTtlMs` is, `0` included.\n * The comparison is on the generation **and** the row's token, so a segment retired, purged and loaded again from\n * generation 0 while this store held its old generation 0 is told apart too.\n *\n * **A destroyed segment is searched as {@link CloudRoaring.eraseSubject} searches it.** No read resolves a\n * tombstone, so the id is a member of none, but a cleartext `destroySegment` (`allowCleartext`), or a `dropSegment`\n * whose sweep missed an object a load was still writing, leaves objects anyone with bucket access can read. Each\n * object left under the tombstone is opened newest first until one holds the id, and the segment is then listed in\n * `tombstones`, never in `segments`. A crypto-shredded segment's own objects are sealed under a key no row holds and are\n * never a holder: it is listed only when an object left under it in the clear holds the id. The cost is one listing per destroyed segment in scope (1 request when nothing is left), and for each\n * object opened a tail read and, where its index lists the id's chunk, a chunk read (two tail reads for an encrypted\n * object, which never holds the id): 7 requests for a cleartext destroy with 3 objects, 21 for 10. The budget is\n * charged one unit for each object opened past the one the row names, as `eraseSubject` charges. A report that runs\n * out, or whose listing or read fails after the store's retry, rejects rather than under-reporting, so one leftover\n * object that cannot be opened makes every report over its scope reject until it is removed (`generations(ref)` lists\n * what is left, `dropSegment` deletes it). A report refused for budget while it searches a destroyed segment reports\n * `spent` as `limit + 1`, a lower bound.\n */\n async subjectReport(\n id: number,\n options: { concurrency?: number; budget?: BudgetOption } & (\n { namespace: string; allNamespaces?: false } | { allNamespaces: true; namespace?: undefined }\n ),\n ): Promise<SubjectReport> {\n checkOptions(options, 'subjectReport', CALL_KEYS.subjectReport, ['allNamespaces']);\n options ??= {} as typeof options; // plain JS: no options reads as no scope, which requireScope refuses\n const registry = this.requireRegistry('subjectReport');\n requireScope(options, 'subjectReport'); // tenancy: explicit namespace, or an { allNamespaces: true } ack\n validateConcurrency(options.concurrency); // fail fast before the (possibly huge) registry scan\n const budget = resolvePerOpBudget(options.budget, this.budget); // partial override inherits the store's tightening\n splitId(id); // fail fast on a non-u32 id even when no segments are registered\n // Bounded INCREMENTALLY: draining the whole registry and only then checking the budget would refuse the\n // work after paying for the list \u2014 measured at 20,000 records buffered under `maxRequests: 2`. This is a\n // GDPR Art. 15 entry point plausibly wired to end-user traffic, so resident memory must be O(budget), not\n // O(fleet size).\n const recs = await collectWithinBudget(\n // A subject cannot be in a due-index row, and charging this request's budget for them would refuse a\n // GDPR Art. 15 report for a reason unrelated to the subject.\n excludingReservedRows(registry.list(options.namespace)),\n budget,\n 'subjectReport',\n );\n // The scan charged one unit a segment; each object opened under a tombstone past the one its row names is\n // charged too, to the same call-wide count, as `eraseSubject` charges them.\n let opens = 0;\n const charge = (): void => {\n opens += 1;\n // A refusal part-way through the search does not know what the whole search needs, so it says \"more than\"\n // and reports the bound plus one, a lower bound, as an enumeration stopped at its bound does.\n if (budget !== null && recs.length + opens > budget.maxRequests) {\n throw new BudgetExceededError(\n `subjectReport would fan out to more than ${budget.maxRequests} units, over the per-op budget: the search ` +\n `under a destroyed segment was abandoned at that point, so no exact total is available. Raise ` +\n `\\`budget.maxRequests\\`, override it per-op, or set \\`budget: false\\``,\n {\n option: 'budget.maxRequests',\n limit: budget.maxRequests,\n spent: budget.maxRequests + 1,\n },\n );\n }\n };\n // Bounded fan-out of `has()` across registered segments. Order-preserving \u21D2 deterministic result. A has()\n // fault propagates (a report that can't read a segment must fail loud, not silently under-report).\n const membership = await mapWithConcurrency(\n recs,\n options.concurrency ?? DEFAULT_ADMIN_CONCURRENCY,\n async (rec): Promise<{ tombstone: boolean; ref: SubjectSegmentRef } | null> => {\n const ref: SegmentRef = { segment: rec.segment, namespace: rec.namespace };\n if (rec.status === 'destroyed') {\n // No read resolves a destroyed row, so the id is a member of none. A cleartext destroy, or a drop whose\n // sweep left an object, leaves objects anyone with bucket access reads, which `eraseSubject` searches and\n // deletes: search them the same way, charged as it charges them.\n const deps = this.lifecycleDeps('subjectReport');\n const storage =\n budget === null\n ? deps.storage\n : new OpenChargingStorage(deps.storage, rec.currentGen, charge);\n const held = await findIdUnderTombstone(ref, id, { ...deps, storage });\n return held === null ? null : { tombstone: true, ref };\n }\n // The row this scan just listed is authoritative; the reader's snapshot may be up to `cache.genTtlMs` behind\n // it, or have no timed refresh (`genTtlMs: 0`). An access report must not lag another process's load or\n // erasure, so a segment whose snapshot is not the listed row's is forgotten before the read. The snapshot's\n // version is `<generation>:<pointerId>` (invariant 2: the number restarts at 0 once a row is purged, and is taken\n // again once its object is deleted, and every write that leads there renews the row's pointerId), so a retired\n // name loaded again is told apart too, followed by `#` and the fingerprint of the object its reader opened, which\n // is left out here. Only a segment whose resolution differs is re-resolved: one whose row has not moved, or has\n // moved only by a lease or a policy write, keeps its snapshot and costs no extra read.\n if (this.crbmSource !== undefined) {\n const held = await this.crbmSource.currentVersion(ref);\n const listed = rec.currentGen === null ? null : `${rec.currentGen}:${pointerIdOf(rec)}`;\n if (rowVersionOfLive(held) !== listed) this.engine.invalidate(ref);\n }\n return (await this.engine.has(ref, id)) ? { tombstone: false, ref } : null;\n },\n );\n const listed = membership.filter((m) => m !== null);\n const segments = listed.filter((m) => !m.tombstone).map((m) => m.ref);\n const tombstones = listed.filter((m) => m.tombstone).map((m) => m.ref);\n return { id, segments, tombstones, scannedSegments: recs.length };\n }\n\n /**\n * **Subject erasure (GDPR Art. 17): remove an id from every segment it's in, with the bit physically gone\n * from the bucket on return for each segment the ledger reports `erased: true`.** A noncurrent version, a replica\n * or a backup keeps the old object until its own lifecycle removes it.\n *\n * **Scope: one `namespace`, or `{ allNamespaces: true }`, never both** (both throws `ValidationError`, as does\n * neither). A segment loaded with no `namespace` is in no namespace you can name: only `{ allNamespaces: true }`\n * reaches it. `'_default'`, the label the export tool and the disaster-recovery samples print, and the bucket's\n * object keys use, for such a segment, is an ordinary namespace name here, and passing it scans a namespace of that name, not those segments.\n *\n * For each **registered** segment the id is a member of, `eraseIdFromSegment` rewrites the current generation\n * without the id \u2014 every chunk streamed through, one bit cleared \u2014 publishes the rewrite **fenced on the\n * generation it was derived from**, and collects the generation that held the bit. A segment whose current\n * generation does not hold the id is searched anyway, every generation in its bucket: a retained superseded one\n * can still hold it, and so can one above the pointer after a {@link CloudRoaring.rollback}, which the rollback\n * could make current again. Each holder is deleted \u2014 below the pointer by a `keep: 0` collection, above it one\n * by one, re-proved against the row first \u2014 and the generations above the pointer that never held the id stay\n * as rollback targets, but for any object no read of the segment can open, which goes whatever the id. An entry\n * says `erased: true` only once the call has listed the bucket and read what is left: **no generation of the\n * segment holds the id**. The returned per-segment record is your **erasure ledger** \u2014\n * persist it / route it to your audit sink as the proof of deletion (when you pass `audit`, an audit event is also\n * emitted per segment erased: `segment.rewrite` for a rewrite, `segment.collect` where only other generations held\n * the id and nothing was rewritten). A segment where the erasure deleted only objects no read of it can open (a first\n * load's sealed under a key no row holds) found the id in none, so the ledger does not list it; the audit sink gets\n * `segment.collect` for it with no `fromGeneration`, which is the only record of that deletion.\n *\n * Uses the backend's **own** two halves, so the membership check and the rewrite provably run\n * over the same generation. Requires the store built with a **backend** (throws\n * {@link UnsupportedError} otherwise; a pre-built `StorageChunkSource` store has no `IStorageDriver` to write\n * through; build the store on a backend instead).\n *\n * **One contract remains** (an integrator obligation the library cannot check): **do not load the segment\n * while erasing from it.** A load that lands after the rewrite carries whatever its source held, and the\n * library cannot know that source was meant to exclude the id. Quiesce loads of the affected segments for the\n * duration, or fix the source first and load after. A writer that lands *during* the rewrite is caught: the\n * rewrite's publish is refused **by the fence** \u2014 the publish lands its compare-and-swap only\n * while the pointer is still on the generation the rewrite streamed \u2014 and the entry says `note: 'superseded'`,\n * so re-run. Forward-only alone would NOT refuse it: the rewrite's number goes above everything in the bucket,\n * so the rewrite would out-rank the newer generation and then collect it.\n *\n * A racing **erasure** is caught before that, and reported the same way. It collects with `keep: 0`, taking\n * every generation below its new pointer \u2014 the one this rewrite is streaming, and the object this rewrite\n * just wrote \u2014 so the loser can find its own inputs deleted mid-flight. That surfaces as an outcome rather than\n * an error, read off the row: a moved pointer is a `'superseded'` entry, which a re-run settles, and a segment\n * that a concurrent `dropSegment` tombstoned or a retention sweep purged is left out of the ledger. A tombstoned\n * segment is still searched: a cleartext object left under it that holds the id is deleted, with everything under\n * the tombstone, and the entry reads `erased: true`. So is a segment whose row names no generation yet (a retention\n * policy set before its first load): a first load's object that holds the id is deleted, once the row's `pointerId`\n * is renewed so that the load, if still running, is refused at its publish, and the entry reads `erased: true`. An\n * encrypted first load's object there cannot be searched, so it is deleted whatever the id: on an encrypted store,\n * an erasure of any id refuses an encrypted first load in flight that has written its object onto a segment made\n * ahead of its data. Each such delete, and each of a holder above the pointer, names the object the erasure read:\n * on a storage driver that reports `conditionalDelete`, another erasure of the id that deletes it first, followed by\n * a load that takes the number freed and publishes, does not lose that load's generation to this erasure's delete,\n * which is refused, and the entry says what the row says; on one that does not, it can.\n *\n * **Read `note` on any `erased: false` entry \u2014 the two reasons mean different things.** `'superseded'` means\n * another writer (a load, another erasure, or a rollback) moved the pointer, or replaced an object the call meant to\n * delete, mid-call, so **this call** did not erase the id. Re-run: it erases the id if it is still there, and lists\n * nothing for the segment if a racing erasure of the same id already removed it. Do not read `'superseded'` as\n * \"the id is still present\" \u2014 read it as \"not done by this call, and the re-run settles it\".\n * `` `error: \u2026` `` is a per-segment fault (caught so one segment can't discard the whole ledger) and it can land\n * on either side of the publish: if the rewrite had not published, the id is still there and a re-run erases\n * it; if the publish succeeded and only the **collection** of the old generation failed, the id is already\n * absent from every read and what remains is an object in the bucket that still contains the bit. The same\n * note, after a publish, can mean a rollback moved the pointer back onto a generation that still holds the id\n * while the collection ran \u2014 then the id is served again, and the entry says so rather than `erased: true`. A\n * re-run searches every generation in the bucket, so it rewrites or collects what is left and usually reports\n * `erased: true`; {@link SubjectErasureEntry.note} says what else a re-run can report. Re-running is otherwise safe\n * and idempotent: a segment the id is no longer in is not listed. Admin-only path;\n * `O(registered segments + superseded generations)`, no hot-path cost: a segment whose current generation lacks\n * the id is searched generation by generation, one open for each other generation in its bucket, and with the\n * keep-everything default of the `*Into` verbs that is one per generation the segment ever had. The per-op\n * `budget` is charged one unit for each segment and one for each generation opened beyond the one its row names, so\n * a fleet with long histories can exhaust it where the segment count alone would not. A generation is charged at its\n * first open only: a later open of it in the call, a retry of a failed read included, costs no more units. A segment\n * that exhausts the budget is\n * reported `erased: false` with an `error:` note, before it deletes anything (the one refusal that can come after a\n * rewrite is the last check for a generation a concurrent writer left behind), and the\n * rest of the scan continues: the call itself does not throw for it. Per-subject crypto-shred is infeasible (a subject's bit is\n * co-mingled in a shared container), so this is the single-subject erasure route; whole-segment/tenant erasure\n * is `dropSegment` / the `destroySegment`/`eraseNamespace` free functions.\n */\n async eraseSubject(\n id: number,\n options: { audit?: IAuditSink; concurrency?: number; budget?: BudgetOption } & (\n { namespace: string; allNamespaces?: false } | { allNamespaces: true; namespace?: undefined }\n ),\n ): Promise<EraseSubjectResult> {\n // An erasure in progress counts as one that moved: a call feeding on caller memory is refused from the start. One refused\n // for its options still moves the counter: conservative, so an erasure is never missed.\n this.erasureEpoch++;\n checkOptions(options, 'eraseSubject', CALL_KEYS.eraseSubject, ['allNamespaces']);\n options ??= {} as typeof options; // plain JS: no options reads as no scope, which requireScope refuses\n this.erasuresRunning++;\n try {\n return await this.eraseSubjectRun(id, options);\n } finally {\n this.erasuresRunning--;\n this.erasureEpoch++;\n }\n }\n\n private async eraseSubjectRun(\n id: number,\n options: NonNullable<Parameters<CloudRoaring['eraseSubject']>[1]>,\n ): Promise<EraseSubjectResult> {\n const deps = this.lifecycleDeps('eraseSubject');\n requireScope(options, 'eraseSubject'); // tenancy: explicit namespace, or an { allNamespaces: true } ack\n validateConcurrency(options.concurrency); // fail fast before the (possibly huge) registry scan\n const budget = resolvePerOpBudget(options.budget, this.budget); // partial override inherits the store's tightening\n splitId(id); // fail fast on a non-u32 id even when nothing is registered\n // Bounded incrementally \u2014 see subjectReport above. Art. 17 erasure is likewise reachable from ordinary\n // \"delete my account\" traffic, so the enumeration itself has to respect the budget.\n const recs = await collectWithinBudget(\n excludingReservedRows(deps.registry.list(options.namespace)),\n budget,\n 'eraseSubject',\n );\n // The scan charged one unit a segment. A segment whose current generation lacks the id is searched generation by\n // generation, and each open past the current one is charged too, to the same call-wide count. With no budget\n // there is nothing to charge and the drivers are used as they are.\n let opens = 0;\n const charge = (): void => {\n opens += 1;\n checkBudget(budget, recs.length + opens, 'eraseSubject');\n };\n // Bounded fan-out. Each segment is an independent generation, so rewriting distinct segments concurrently is\n // safe. Per-segment faults stay isolated INSIDE each task \u2014 one failure never aborts the ledger \u2014 and the\n // pool preserves input order, so the ledger stays deterministic.\n const entries = await mapWithConcurrency(\n recs,\n options.concurrency ?? DEFAULT_ADMIN_CONCURRENCY,\n async (rec): Promise<SubjectErasureEntry | null> => {\n const ref: SegmentRef = { segment: rec.segment, namespace: rec.namespace };\n try {\n // The rewrite does its own membership check against the CURRENT registry generation \u2014 not the\n // engine's cached view, which may lag a load by up to `cache.genTtlMs`. An Art. 17 erasure must never\n // skip a segment because a read cache hasn't caught up yet.\n const result = await eraseIdFromSegment(\n ref,\n id,\n budget === null\n ? deps\n : { ...deps, storage: new OpenChargingStorage(deps.storage, rec.currentGen, charge) },\n { audit: options.audit },\n );\n if (result.reason === 'not-member' || result.reason === 'absent') return null;\n if (result.reason === 'no-generation') return null; // a row with no data yet holds no id\n if (result.reason === 'destroyed') return null;\n return {\n segment: rec.segment,\n namespace: rec.namespace,\n erased: result.erased,\n fromGeneration: result.fromGeneration,\n generation: result.generation,\n note: result.erased ? undefined : result.reason,\n };\n } catch (err) {\n return {\n segment: rec.segment,\n namespace: rec.namespace,\n erased: false,\n note: `error: ${errorKind(err) ?? (err instanceof Error ? err.name : 'Error')}: ${\n err instanceof Error ? err.message : String(err)\n }`, // the class lets a note be matched to the guide's table\n };\n } finally {\n // Whatever the outcome, this process's own view of the segment is now suspect: a landed rewrite\n // deleted the generation our caches were built on, and a refused one means somebody else's did.\n // Without this the erasing store keeps answering `true` for the id it just reported erased \u2014 out of\n // RAM, with no storage read for any control to intercept. `finally`, not the happy path: a rewrite\n // that published and then THREW on its collect is precisely the case where this view is stale, and\n // it is reachable from an ordinary retirement landing mid-call.\n //\n // Swallowed, because a `finally` that throws replaces the outcome above it: it would escape the\n // per-segment catch, abort the whole ledger, and discard the error it was masking \u2014 breaking the\n // isolation this fan-out promises. Dropping cache entries cannot fail today; this keeps that from\n // becoming a whole-run failure if it ever can.\n try {\n this.engine.invalidate(ref);\n } catch {\n /* best-effort: never let cache bookkeeping discard a segment's result */\n }\n }\n },\n );\n const erasedFrom = entries.filter((e): e is SubjectErasureEntry => e !== null);\n return { id, erasedFrom, scannedSegments: recs.length };\n }\n\n /**\n * Every generation still in the bucket for this segment, ascending, with the current one marked.\n *\n * What the bucket holds, not what the segment has ever been \u2014 collection deletes superseded objects, so this is\n * the grace window plus whatever has not been collected yet. It is the set {@link CloudRoaring.rollback} can\n * choose from, which is the reason to look at it. One registry read and one listing; it does not open the objects.\n * Each entry says whether the row knows the generation (`known`): a known generation needs no `allowUnknown`; an unknown\n * one does, except below a row's pointer when the row has no usable record or the target is older than a full one reaches.\n * No entry is `current` on a destroyed segment: its row keeps the pointer it had, but no read resolves through it.\n *\n * Needs a backend.\n */\n async generations(ref: SegmentRef): Promise<GenerationEntry[]> {\n ref = validateRef(ref, 'generations');\n return listGenerations(ref, this.lifecycleDeps('generations'));\n }\n\n /**\n * Whether a read of this segment would find anything \u2014 the \"do I already have this?\" question, as one\n * registry point read.\n *\n * There is no `create` in this library: {@link CloudRoaring.segment} is a validated address and does no I/O,\n * so naming a segment can never collide with an existing one. A segment starts existing when something is\n * first loaded into it, and this is how you ask whether that has happened.\n *\n * **Not the same as `count() > 0`.** A segment loaded with no ids exists and counts zero. Distinguishing\n * \"never loaded\" from \"loaded, and genuinely empty\" is the thing `count()` cannot do and the reason this\n * exists. It is `false` for a segment whose row was minted ahead of its first load (by `setRetention`) and\n * for a `destroyed` tombstone, because a read answers empty in both cases.\n *\n * One state answers `true` where a read still gives you nothing: a torn restore (a live pointer whose object\n * was deleted) makes reads of the object *throw* rather than answer empty, while a cold `count()` answers the number\n * its row records \u2014 `checkConsistency` is the call for that.\n *\n * Not a lock: the answer can change the moment it returns. If it has to hold, use the fence built for that \u2014\n * `load`'s `guard`, or `expectFrom`/`expectToken` on a publish. Needs a storage backend.\n *\n * ```ts\n * if (!(await store.exists({ segment: 'users' }))) {\n * await store.load({ segment: 'users' }, idsFromUpstream);\n * }\n * ```\n */\n async exists(ref: SegmentRef): Promise<boolean> {\n ref = validateRef(ref, 'exists');\n return segmentExists(ref, this.requireRegistry('exists'));\n }\n\n /**\n * Every segment the registry knows about, streamed \u2014 optionally scoped to one namespace.\n *\n * The registry is already the list of your segments, which is why you should not keep a second one beside it:\n * a hand-maintained list is a source of truth that drifts from this one the first time a load fails halfway.\n *\n * **An admin/discovery call, not a request-path one.** This is the registry's own enumeration \u2014 a paged\n * LIST over the `registry/` prefix \u2014 so its cost grows with the size of the fleet rather than with what you\n * are looking for.\n *\n * Scoping to a namespace narrows the LIST prefix, so it really is the difference between reading one tenant\n * and reading all of them.\n *\n * It streams, and stopping the iteration stops the scan. It reads the registry directly and is not retried: a\n * transient fault part-way through ends the loop with that error, and calling `segments()` again scans from the\n * start.\n *\n * Yields `destroyed` tombstones and rows with `currentGen: null`, because a filtered enumeration that looks\n * complete is worse than an honest one \u2014 filter on `status`/`currentGen` yourself, or ask\n * {@link CloudRoaring.exists} the narrower question. Needs a storage backend.\n *\n * ```ts\n * for await (const s of store.segments({ namespace: 'active-daily' })) {\n * console.log(s.segment, s.currentGen, s.status);\n * }\n * ```\n */\n segments(options: { namespace?: string } = {}): AsyncIterable<SegmentInfo> {\n checkOptions(options, 'segments', CALL_KEYS.segments);\n options ??= {};\n if (options.namespace !== undefined) {\n // Synchronously, at the call, where `listSegments` (an async generator, which refuses the reserved\n // namespace too for a direct caller) would only throw at the first iteration.\n validateSegmentRef({ segment: 'x', namespace: options.namespace });\n refuseReservedNamespace(options.namespace);\n }\n return listSegments(this.requireRegistry('segments'), options);\n }\n\n /**\n * Move this segment's pointer **back** to a generation still in the bucket \u2014 the one write in the library that\n * is not forward-only.\n *\n * Forward-only is right for a writer: a load whose ids came from upstream loses nothing by being out-raced, and\n * letting it regress would let a slow loader silently undo a fast one. It is wrong for an operator who has\n * looked at the segment, decided the current generation is wrong, and knows which one they want. So this is\n * reachable only by asking for it by name \u2014 no sweep, retry or reconciliation calls it \u2014 and it is audited\n * (`segment.rollback`), because every other pointer move can be reconstructed from \"a load happened\" and this\n * one cannot.\n *\n * It refuses rather than guesses. The row records, in `knownGens`, the generations its loads and rollbacks made\n * current, each with the footer checksum of its object, and a rollback moves only onto one of those: a generation the\n * row does not know (a load that wrote its object and died before the publish, a refused load's object, an object\n * sealed under a key no row holds, a load published after the point a registry was restored to) throws\n * {@link ValidationError} before any request to storage, and a known one whose object carries another checksum than\n * the recorded one throws {@link IntegrityError}, with or without a keystore, since the footer is in the clear. A\n * generation not in the bucket (collected, or never written) throws `NotFoundError` naming what *is* available, a\n * destroyed segment (crypto-shredded, destroyed in the clear or dropped) throws {@link ValidationError}, because no\n * generation resolves through a destroyed row, and a target that is cleartext under an encrypted segment, or\n * encrypted under a cleartext one, throws {@link IntegrityError} from\n * one tail read of it, because every read would refuse it. Rolling to the generation already current is a no-op that\n * reports itself, once one footer read finds its object in the bucket (and the one the row recorded); when the object is\n * gone it throws `NotFoundError` naming what is.\n *\n * The same tail read (and a range read when the target's index is longer than it) gives the target's id count and\n * metadata, which the rollback writes into the row with the pointer, so a reader that sees the target as current sees\n * what describes it. The store's keystore opens an encrypted target for this; without it, or when it cannot open the\n * key (it holds none of the key's KEKs, one it holds does not unwrap it, or it throws `TransientError` or times out\n * as `AbortSignal.timeout()` and the AWS SDK report a timeout), a rollback onto a known generation still happens,\n * opening nothing, and the row carries no summary of the target. Any other failure of the keystore is\n * thrown. A swap of the pointer that gets no answer, or that meets a conflict, is settled by reading the row: one\n * that landed, the row's pointer being at the target over a write this call sent (the write token, on a registry that\n * reports them), is checked as any is, and otherwise its `TransientError` is thrown, or a `WriteConflictError` after\n * a conflict, with no move recorded. After the swap the target's\n * footer is read once more, and the pointer put back if the object is gone or is another.\n *\n * It deletes nothing. The generations above the new pointer stay put \u2014 which is what makes this reversible \u2014\n * and are then *above* `currentGen`, where collection never looks, and still known to the row, so rolling forward onto\n * one needs no flag. They remain until loads pass them (the first load whose\n * number one of them holds numbers above them all, and collection then keeps `keep` of what is below its pointer, the\n * generation that load superseded first), {@link CloudRoaring.dropSegment}\n * deletes them, or {@link CloudRoaring.eraseSubject} does: all of those present when it rewrites, and, when the\n * current generation does not hold the id, only those holding it and any no read of the segment can open, whatever\n * the id. An operator who has just undone a bad load should not have the\n * evidence collected out from under them, while a rollback target that still holds erased data would make the\n * erasure undoable.\n *\n * `{ allowUnknown: true }` moves onto a present object the row does not vouch for, or one whose checksum differs from\n * the recorded one, as long as it is the segment's kind of object, opens, and names the generation, and records it as\n * known (over a usable record; a row with none stays without one). On an encrypted segment, outside the two cases the pointer alone decides (below), it also needs the key: with no keystore, or one that holds none of the key's KEKs or\n * one that does not unwrap it, it is refused with `KeyUnavailableError` before the target is read, since an object\n * sealed under a key no row holds passes every check that needs no key, and a key service that did not answer in\n * time is thrown as `TransientError`, to retry. Every move the row did not vouch for is audited with `unknown: true`.\n * Two cases are decided by the pointer alone: a target below it needs no flag, no key and no checksum check, and the\n * move is audited the same way. They are a row with no usable `knownGens` (a registry that drops the field, or a pointer\n * moved by hand), and a target numbered below the bound of a full record (128 entries or more, leased ones included),\n * which is its least recently current entry that no lease names (an `*Into` destination keeps every generation in the\n * bucket and names only the newest 128). A generation a publish with a smaller `keep` no longer names but that stays in\n * the bucket (a lease spared it, or its delete failed) needs `allowUnknown` until a later listing collects it.\n *\n * Needs a backend.\n */\n async rollback(\n ref: SegmentRef,\n toGeneration: number,\n options: { audit?: IAuditSink; allowUnknown?: boolean } = {},\n ): Promise<RollbackResult> {\n ref = validateRef(ref, 'rollback');\n checkOptions(options, 'rollback', CALL_KEYS.rollback, ['allowUnknown']);\n options ??= {};\n const deps = this.lifecycleDeps('rollback');\n try {\n return await rollbackSegment(ref, toGeneration, deps, options);\n } finally {\n // The pointer moved under this store's cached view \u2014 and unlike a load, it moved to content the caches may\n // still be holding from before. Drop it either way.\n this.engine.invalidate(ref);\n }\n }\n\n /**\n * **Replace this segment's contents** with `input`, as one new immutable generation, and make it current.\n *\n * `input` is ids (any sync or async iterable of integers in `[0, 2^32)`), or a whole bitmap: `{ bitmap }`, anything\n * with `serialize('portable')` such as `roaring`'s `RoaringBitmap32`, or `{ serialized }`, portable Roaring bytes.\n * A bitmap is checked (size cap, structure, safe deserializer) before the first request, written from its own\n * containers with no per-id work, and gives the generation chunk for chunk what its ids would. An\n * iterable with a `serialize` method (a `RoaringBitmap32`, another copy's bitmap, or a `RoaringBitmap`\n * of this package) passed as ids loads as `{ bitmap }` and is not iterated. A `Uint8Array` or `Buffer` passed as ids is\n * refused with `ValidationError`, since each byte would load as an id, even when it has a `serialize` of its own:\n * pass bytes as `{ serialized }`.\n *\n * Ids are held whole in memory before the object is written: the generation's bitmaps and a buffer of up to about 28\n * MB. Ids that already ascend can be loaded with `sorted: true` instead, which writes them one chunk at a time while\n * the object uploads, so the load holds one chunk and the writer's index (up to about 7 MiB, about 8 MiB for an\n * encrypted segment, derived), whatever the segment's size, and writes the same object ({@link LoadOptions.sorted}).\n *\n * The whole write path in one call: take the next generation number, write the object, check the result is\n * plausible, move the pointer, collect what the move superseded. Composed by hand those are four functions and\n * the one that gets left out is the last, so segments quietly accumulate superseded generations nobody pays\n * attention to and everybody pays for.\n *\n * ```ts\n * const r = await store.load({ segment: 'audience:active' }, idsFromWarehouse, {\n * guard: { minRetained: 0.5 }, // refuse a load that would drop more than half the segment\n * });\n * if (!r.published) console.warn(`load refused: ${r.reason}`);\n * ```\n *\n * `metadata` attaches a small record of your own to the generation: a flat object of string keys and string or finite\n * number values, at most 1,024 bytes as canonical JSON and no key over 128 bytes. A record that breaks a rule throws\n * `ValidationError` before the load makes a request. It is copied when you call, stored in the generation's object,\n * and written to the segment's row with the generation's id count by the write that moves the pointer, so a reader\n * that sees the generation as current sees its metadata. It never changes after that, a rollback puts the target's own\n * back, and an erasure carries it over without scanning it, so keep a subject's id out of it. It is sealed under the\n * segment's key on an encrypted segment.\n *\n * **A load REPLACES.** Whatever the stream contains is what the segment contains afterwards, so an upstream\n * query that returns fewer rows than usual is a shrink nobody asked for and an empty one is a wipe \u2014 both\n * reported as a successful write, because at the storage layer they are one. That is what `guard` and the\n * default empty refusal are for, and why they run **between** the write and the publish: the only moment where\n * the new content is known and the old one is still authoritative.\n *\n * **Branch on `published`.** A refusal is a normal outcome, not an exception \u2014 `published: false` with a\n * `reason`, in the same shape as a success \u2014 so a discarded result is a load that silently did nothing, and\n * with the empty guard on by default this verb refuses more readily than any other. Note the sibling `*Into`\n * verbs *throw* on the same superseded condition rather than reporting it; this one follows\n * `eraseIdFromSegment` instead, because three of its four refusals are expected guard outcomes rather than\n * faults.\n *\n * `'superseded'` means another writer got there first: another load took the same generation number, so this\n * one wrote nothing (`size: 0`), or the segment's registry row changed while the load was writing \u2014 another load\n * published, a retention change, a rollback or an erasure wrote the row, or the row was deleted.\n *\n * A refused load deletes the object it wrote before returning \u2014 it sits above `currentGen`, where generation\n * collection deliberately never looks \u2014 but only while the segment's registry row is unchanged (or differs only in\n * its leases), `destroyed` or gone, or has key material when the load wrote cleartext, which has no place in an\n * encrypted segment's bucket. Under a row that is gone or keyed, one read of the object's footer must match what the\n * load wrote first. Once another write has otherwise changed the row, the generation number it holds may name another\n * writer's object, and the row does not say whether that write took this number, so it leaves the orphan rather than risk\n * deleting live data. A publish never adds the orphan to the row's list, and a load's listing deletes it once a\n * generation above it is current, unless the row's list names it; where the row records none (after a rollback, or\n * with a `keep` above 64), that listing's window can keep it and, at a `keep` up to 64, record it, and the publishes\n * after carry it until the window pushes it out. Until it goes, a rollback onto it is refused unless `allowUnknown` is passed, since the list never names it (a list seeded\n * over a row with none can); with the override it publishes what no load published.\n *\n * **Collection is by name at any `keep` up to 64.** The segment's row records the generations a load keeps, so a load\n * that found nothing above the pointer deletes the generations its publish pushed out of the window and lists\n * nothing. It lists the segment's objects on every sixteenth generation, and on any load that met an object above the\n * pointer or whose check found the current generation's object gone, to take what the name-only passes leave, such as\n * an object a crashed load left below the pointer. A `keep` above 64 records no list and lists on every load, and so\n * does the first load of a row that records none, which then records it. {@link LoadResult.collected} then names\n * what the pass deleted by name, and one name may have been gone already.\n *\n * `input` cannot be a stream of this library (`iterate`, `everyNth`, `intersect`, `union`, `andNot`, as returned) that\n * read the segment being loaded, from this store or one built over the same registry driver: a load publishes over\n * whatever the segment is by then, so it would replace another writer's newer load with a result built from an older\n * one, and it throws {@link ValidationError}. Ids read from another store over another backend load as any ids do.\n * Two separate store instances over one bucket cannot be told apart, so this does not cover them; this release has no\n * fenced in-place update, so write the result into a new segment and point readers at it.\n *\n * What it **throws** for is a fault rather than an outcome: invalid options or ids, and a destroyed\n * segment (`ValidationError`); a key the keystore cannot provide (`KeyUnavailableError`); a current generation\n * that will not open when a guard has to read its size, which it does only when the row has no usable summary of it\n * (`IntegrityError`); a driver failure; and a fault in the collection's own reads, listing or deletes, or in the write\n * that records the window (anything but a lost race). A collection fault can be raised **after** the publish already\n * landed, so a throw does not by itself mean the load did not take effect \u2014 re-read the pointer rather than assuming.\n * A collection, by name or by listing, that finds another writer has moved the row since the publish (a load, a\n * rollback, a purge) stops and returns what it deleted in `collected`: a load that took effect does not throw for a\n * race it won.\n *\n * **A `TransientError` from the registry write can leave the publish unsettled, and deletes nothing.** The\n * generation's object is sent again after a throttle where the backend allows it (a write id tells a first send\n * that landed from another writer's object), and a driver sends each registry write once. When that write ends\n * without an answer, the load reads the row: its own landed write is `published: true`, a row that has moved on is\n * `superseded`, and a row still as the write found it gets a fresh compare-and-swap from the version just read, at\n * most three times, after a wait on the store's clock. Still unanswered, the load throws the registry's `TransientError` and keeps its object, which\n * a write may still point the row at. Re-run the load: it numbers past that object, and collection removes it once a\n * generation above it is current. A `'superseded'` refusal that follows an unanswered write sets `unanswered: true`\n * on its audit event: that write may have landed, and the generation been current for a while, first.\n *\n * Needs a backend (throws {@link UnsupportedError} otherwise).\n */\n async load(ref: SegmentRef, input: LoadInput, options: LoadOptions = {}): Promise<LoadResult> {\n ref = validateRef(ref, 'load');\n checkOptions(options, 'load', CALL_KEYS.load, ['allowEmpty', 'sorted']);\n if (typeof input === 'object' && input !== null) {\n const reads = STREAM_SOURCES.get(input);\n // The same store, or one built over the same registry driver object. Two stores over two backends copy freely;\n // two separate store instances over one bucket cannot be told apart by their registry driver and are not covered.\n const sameBackend =\n reads !== undefined &&\n (reads.origin === this.origin ||\n (this.registry !== undefined && REGISTRY_OF.get(reads.origin) === this.registry));\n if (sameBackend && reads.keys.includes(segmentKey(ref))) {\n const named = ref.namespace === undefined ? ref.segment : `${ref.namespace}/${ref.segment}`;\n throw new ValidationError(\n `load: the ids come from a read of the segment \"${named}\" that is being loaded, and a load publishes over ` +\n \"whatever the segment is by then, so another process's newer load of it can be replaced by a result built \" +\n 'from the one before, with no conflict reported. This release has no fenced in-place update: write the ' +\n 'result into a new segment and point readers at it',\n );\n }\n }\n options ??= {};\n const deps = this.lifecycleDeps('load');\n try {\n return await loadSegment(ref, bitmapAsLoadInput(input), deps, options);\n } finally {\n // This store's view of the segment is now behind whatever just happened \u2014 a published load superseded the\n // generation the caches were built on, and a throw can still have published before failing its collect.\n // `finally`, so the one path where the view is most likely stale is not the one path that skips the drop.\n this.engine.invalidate(ref);\n }\n }\n\n /**\n * **Dispose of a segment \u2014 tombstone it, then delete its storage objects.** It cannot be undone through the\n * library (a restore from the registry's and the bucket's versions or backups can).\n *\n * The operation a rolling window needs: `destroySegment` crypto-shreds (it removes the key from the segment's\n * current registry row, so the bytes are unreadable everywhere, backups included, once no retained copy of the row\n * holds the key or every KEK that wrapped it is destroyed; the objects still sit in your bucket and are still\n * billed, and it requires encryption), while this one removes the storage and works on a cleartext segment. On an\n * encrypted segment it does both.\n *\n * Pass `{ dryRun: true }` first \u2014 it reports the generations it *would* delete and changes nothing. That\n * matters more than the `confirmSegment` guard for anything automated, because in a loop the guard is the same\n * variable twice.\n *\n * ```ts\n * for (const day of expiredDays) {\n * // The family in the namespace, the date in the segment \u2014 `registry.list(namespace)` then enumerates\n * // exactly this family's buckets, which a flat `active:2026-08-01` name cannot do without string-matching.\n * const ref = { namespace: 'active-daily', segment: day };\n * await store.dropSegment(ref, { confirmSegment: ref.segment });\n * }\n * ```\n *\n * **Omitting the namespace addresses a different segment and is a silent no-op** \u2014 you get\n * `{ dropped: false, reason: 'absent' }`, not a throw, so a retention loop with that mistake deletes nothing\n * forever and quietly. Branch on `dropped`, and treat `reason: 'absent'` as the alert.\n *\n * **Inspect `generationsRemaining`.** Empty is the normal outcome; non-empty means the storage was NOT fully\n * reclaimed and the drop should be re-run. A load that had read the segment before the tombstone landed, whether it\n * was writing or still consuming its ids, can still write its object, so a single sweep can miss it \u2014 this call\n * re-sweeps and then reports whatever it still could not remove rather than returning a result that looks like a\n * clean drop. A load that writes after the last sweep deletes its own object once its publish is refused; only one\n * whose process stops in between, or whose publish fails without a definite answer (a lost response, a timeout),\n * leaves it, for a re-run of the drop.\n *\n * Reads become empty within `cache.genTtlMs` (default 2 s), not instantly: a store that had already read this\n * segment may answer from its cached generation + cached chunks until that window lapses, or, while the registry\n * cannot be read because of a transient fault, until a retry 500 ms apart reaches it again. A reader that never\n * touched it sees empty at once. **That bound needs a registry and `cache.genTtlMs > 0`.** A store with no registry\n * (a bare `IStorageDriver`), with `cache.genTtlMs: 0`, or on a `StorageChunkSource` of your own, has no timed\n * refresh. It notices the drop only when a read has to fetch\n * from a deleted generation or its reader cache evicts the segment, and until then a chunk it has cached\n * answers without reaching storage, so it can keep answering `true` for a dropped segment indefinitely. Tell\n * it with {@link invalidate}, or restart it.\n *\n * Needs the store built with a **backend** (throws {@link UnsupportedError} otherwise),\n * because it has to enumerate and delete generations \u2014 a pre-built `StorageChunkSource` only reads.\n */\n async dropSegment(\n ref: SegmentRef,\n options: { confirmSegment: string; dryRun?: boolean; audit?: IAuditSink },\n ): Promise<DropResult> {\n ref = validateRef(ref, 'dropSegment');\n if (options === undefined || options === null) {\n throw new ValidationError('dropSegment: options { confirmSegment } are required');\n }\n checkOptions(options, 'dropSegment', CALL_KEYS.dropSegment, ['dryRun']);\n const deps = this.lifecycleDeps('dropSegment');\n try {\n return await dropSegment(\n ref,\n { registry: deps.registry, storage: deps.storage, clock: deps.clock, rng: deps.rng },\n options,\n );\n } finally {\n if (options.dryRun !== true) this.engine.invalidate(ref);\n }\n }\n\n /**\n * **Record when this segment becomes eligible for retirement.** One policy write, plus a best-effort write of its\n * due-index pointer (and removal of the old pointer when the expiry day moves); no data is deleted here, and\n * nothing starts running. `retireExpired` is what acts on the policy, and **you** decide when that runs \u2014\n * an EventBridge rule, a CronJob, a queue consumer, whatever your deployment already has. This library starts\n * no background thread (it has to work identically in a Lambda, an edge isolate and a long-lived server).\n *\n * `expiresAt` is an **absolute epoch-ms you compute**, not a duration the library derives. A relative TTL would\n * have to be anchored to something the library knows \u2014 `updatedAt`, or the current generation \u2014 and every load\n * rewrites both, so \"expire 30 days after the last write\" would keep a busy daily bucket alive forever\n * precisely because it is being reloaded.\n *\n * ```ts\n * const DAY = 86_400_000;\n * const ref = { namespace: 'active-daily', segment: '2026-08-05' };\n * await store.setRetention(ref, { expiresAt: Date.now() + 30 * DAY });\n * ```\n *\n * **Works before the first load**: a segment with no registry row yet gets one (`createdRow: true` in the\n * result) with **no Storage generation**, so the policy is recorded ahead of the data and the segment is already\n * enumerable by the sweep; the first load then publishes onto that row.\n *\n * A value in the past is legal and means \"eligible on the next sweep\" \u2014 backfilling a policy onto existing\n * buckets is normal. A value below `1_000_000_000_000` (2001-09-09) is rejected: it is almost certainly epoch\n * **seconds**, which would read as long-expired and retire the segment on the next pass. Needs a storage\n * backend (throws {@link UnsupportedError} otherwise), and refuses a destroyed segment.\n */\n async setRetention(ref: SegmentRef, policy: RetentionPolicy): Promise<SetRetentionResult> {\n ref = validateRef(ref, 'setRetention');\n return setSegmentRetention(\n ref,\n { registry: this.requireRegistry('setRetention'), clock: this.clock, rng: this.rng },\n policy,\n );\n }\n\n /**\n * **The stored retention policy**, or `null` if the segment has none (or has no registry row, or is a\n * tombstone). Returns the string `'invalid'` for a row whose `expiresAt` is present but unusable \u2014 a\n * hand-edited row, or one from a restore \u2014 so a malformed policy is visible rather than silently reading as\n * \"never expires\" on a segment someone believes is expiring.\n */\n async getRetention(ref: SegmentRef): Promise<RetentionPolicy | null | 'invalid'> {\n ref = validateRef(ref, 'getRetention');\n return getSegmentRetention(ref, { registry: this.requireRegistry('getRetention') });\n }\n\n /**\n * **Cancel a segment's expiry** so no sweep retires it. Returns whether this call removed a policy (`false`\n * when there was none, and also when a write that got no answer cannot be shown to be this call's and the\n * row holds no expiry: the expiry is gone either way, and its due-index pointer is removed. A later write that set an\n * expiry is cleared too, and the answer is `true`). A separate verb from `setRetention` on purpose: \"never expire\" as a magic value passed\n * to the setter is how a typo becomes a deletion.\n */\n async clearRetention(ref: SegmentRef): Promise<boolean> {\n ref = validateRef(ref, 'clearRetention');\n return clearSegmentRetention(ref, {\n registry: this.requireRegistry('clearRetention'),\n clock: this.clock,\n rng: this.rng,\n });\n }\n\n /**\n * **Run the retention sweep: retire every segment whose `expiresAt` has passed.** This is the call that acts on\n * the policies `setRetention` records \u2014 and it is a **call, not a daemon**. Nothing schedules it; you run it from\n * whatever heartbeat your deployment already has (an EventBridge rule, a Kubernetes CronJob, a queue consumer,\n * the job that runs your loads). A library that started a timer would behave differently in a Lambda, an edge\n * isolate and a long-lived server, which is worse than not having one.\n *\n * Each retirement goes through `dropSegment`, so the registry \u2192 Storage ordering, the re-sweep for an object a\n * load was still writing, and the `generationsRemaining` report all come from one implementation rather than\n * two.\n *\n * ```ts\n * // In your scheduled handler. Start with a preview in a new deployment.\n * const preview = await store.retireExpired({ namespace: 'active-daily', dryRun: true });\n * console.log(`would retire ${preview.wouldRetire} of ${preview.scanned} (limited: ${preview.limited})`);\n *\n * const swept = await store.retireExpired({ namespace: 'active-daily' });\n * for (const e of swept.entries) {\n * // invalid-policy / policy-changed / tombstone-not-empty / failed: \u2026\n * if (e.action === 'skipped') console.warn(`${e.segment}: ${e.reason}`);\n * if (e.action === 'retired' && e.result.generationsRemaining.length > 0) {\n * console.warn(`${e.segment}: storage not fully reclaimed \u2014 re-run`);\n * }\n * }\n * if (swept.limited) scheduleAnotherPassSoon(); // more work (retirements or purges) remains\n * ```\n *\n * **Read the ledger.** A per-segment *fault* is an entry, not an exception \u2014 a throw from the middle of a fleet\n * sweep would leave the caller unable to say which segments were retired, having already retired some. (A bad\n * argument does throw, and so does a fleet larger than `maxScanSegments`.) `limited: true` means the per-cycle\n * `limit` (default 100) cut the pass short, and more work (retirements or purges) remains: `limit` caps the\n * retirements and tombstone purges one call attempts, together, and a segment it deferred gets no entry. That cap\n * is charged on **attempts**, not successes, which is what makes it a real bound: `dropSegment` writes the\n * tombstone before sweeping Storage, so a fault in the Storage phase is a segment that is already retired. Retirements are sequential, so `limit` is a\n * wall-clock knob too, and `retired` counts deletions only \u2014 a dry run reports `wouldRetire` instead, so a\n * dashboard summing `retired` can never show a phantom deletion.\n *\n * **Check `purgeFaults`.** A delete the registry refuses for a reason other than a lost race (a policy that denies\n * delete, an Azure blob with a snapshot, a raw provider error), whether of a tombstone or of a due-index pointer, is\n * counted there, with the first one's reason in `firstPurgeFault`. A refused purge is `skipped` in the ledger, is not\n * charged to `limit`, so it never holds the retirements behind it, and purging stops for the rest of the call after\n * three refused purges in a row (a purge that succeeds starts the count again).\n *\n * It also **deletes the tombstone rows its own past retirements left**, after `tombstoneGraceMs` (default 24 h; at least one hour, else `ValidationError`)\n * and only once that segment's Storage generations are provably gone \u2014 collecting a straggler generation itself\n * first, since nothing else runs that collection on its own for a tombstoned segment (an erasure collects there\n * only\n * when an object holds its id, and a re-run drop sweeps it). Attribution is a **positive marker the sweep\n * stamps on its own retirements**, not an inference from \"destroyed + an expired policy\": a crypto-shred leaves\n * `retention` untouched, so setting a policy and then honouring a right-to-erasure request mid-window produces\n * exactly that row, and deleting it would destroy the Art. 17 attestation and un-fence the name. By default a\n * segment that held nothing has its row deleted in the pass that retires it, since that row would only fence the name.\n * Pass `purgeTombstones: false` to keep every tombstone, that row included. On a backend whose registry reports\n * `conditionalDelete` (AWS S3, Azure Blob, the local filesystem and memory, by default; GCS when you set `conditionalDelete: true`)\n * the purge removes the row from the bucket for good, by a delete the store applies only to the version it judged,\n * so a full sweep reads what is live or inside its grace rather than every name a namespace ever held; elsewhere it\n * leaves a tombstone. Each retirement files a pointer in the due index\n * under the day its tombstone's grace ends, so `scan: 'index'` purges as well as retires.\n *\n * Needs the store built with a **backend** (throws {@link UnsupportedError} otherwise),\n * because retiring a segment deletes its storage objects. `now` defaults to the store's clock.\n */\n async retireExpired(\n options: Omit<RetireExpiredOptions, 'now'> & { now?: number } = {},\n ): Promise<RetireExpiredResult> {\n checkOptions(options, 'retireExpired', CALL_KEYS.retireExpired, ['dryRun', 'purgeTombstones']);\n const opts = picked(options, CALL_KEYS.retireExpired);\n const deps = this.lifecycleDeps('retireExpired');\n const result = await retireExpired(\n { registry: deps.registry, storage: deps.storage, clock: this.clock, rng: this.rng },\n { ...opts, now: opts.now === undefined ? this.clock.now() : opts.now },\n );\n // A retirement tombstones and reclaims segments this store may already have resolved. `dryRun` changes\n // nothing, so it invalidates nothing.\n if (opts.dryRun !== true) {\n for (const entry of result.entries) {\n this.engine.invalidate({ segment: entry.segment, namespace: entry.namespace });\n }\n }\n return result;\n }\n\n /**\n * **Forget everything this store has cached about a segment.** Use it after destroying or retiring a segment\n * through a path this store did not perform itself.\n *\n * A store keeps two layers of derived state \u2014 a resolved snapshot per segment (an open `.crbm` reader, plus\n * the DEK it unwrapped) and decoded chunks keyed by generation. Both are built for one event: **a publish\n * that advances `currentGen`**, which the snapshot TTL notices and the generation-keyed cache misses on.\n * Neither notices an event that *destroys* what they were derived from.\n *\n * The store's own writes handle themselves: `load`, `rollback`, `eraseSubject`, `dropSegment` and `retireExpired`\n * here, and a segment's `*Into` verbs, invalidate what they touch. This method is for the cases they cannot see:\n *\n * - **`destroySegment` / `eraseNamespace`**, which are free functions over raw drivers rather than methods\n * here, so a crypto-shred performed beside this store invalidates nothing in it. It keeps its open reader and\n * the unwrapped DEK, and decrypts with them, chunks it had never fetched before the shred included, until its\n * snapshot re-resolves: within `cache.genTtlMs` when the store has a registry and a `genTtlMs` above 0, and\n * otherwise only when its caches let the segment go or a read has to fetch from a generation a sweep collected.\n * A pin answers with no timed bound, until it is told or both caches let it go.\n * - **Another process.** Erasing on one box invalidates nothing on the others; each store bounds its own\n * staleness by `cache.genTtlMs`, and a store with no registry (a bare `IStorageDriver`), with\n * `cache.genTtlMs: 0`, or on a `StorageChunkSource` of your own has no bound at all: it converges only when a read happens to miss its caches. If a compliance deadline depends on every\n * reader converging, you need to signal them \u2014 this is the call to make when your own fan-out delivers.\n *\n * It also forgets any replacement this store found of a pin's object, so once it is called after a restore puts that\n * object back, the pin reads it again. A read of the segment already running on this store, a pin's and a combine's\n * with a pinned operand included, caches nothing more of what it began reading before the call, and a pinned one\n * opens its object again before its next chunk, failing with `NotFoundError` if the object is gone or replaced, or\n * its row is gone or destroyed.\n *\n * Synchronous, best-effort, and safe to call for a segment this store has never read.\n *\n * ```ts\n * await destroySegment(ref, { registry: backend.registry }, { confirmSegment: ref.segment });\n * store.invalidate(ref); // this process\n * await bus.publish('cloudbitmaps.invalidate', ref); // and every other one\n * ```\n */\n invalidate(ref: SegmentRef): void {\n ref = validateRef(ref, 'invalidate');\n refuseReservedNamespace(ref.namespace);\n this.engine.invalidate(ref);\n }\n\n /**\n * Build a handle held at the generation `ref` resolves to right now. See {@link Segment.pin}.\n *\n * The pinned handle gets its own engine but **shares the store's chunk cache**, under keys of its own: the\n * pinned view reports the version captured at pin time, marked as a pin's, so its decoded chunks are never\n * those of a live read that fetched across a publish (see {@link PinnedStorageChunkSource.currentVersion}). It\n * shares the store engine's invalidations too, so the store's writes reach a pinned read already running.\n */\n private async pinSegment(ref: SegmentRef, leaseUntil?: number, named?: PinAt): Promise<Segment> {\n const crbm = this.crbmSource;\n if (crbm === undefined) {\n throw new UnsupportedError(\n 'pin() needs the `.crbm` storage source \u2014 pass a backend or a raw IStorageDriver as `storage` (the store ' +\n 'cannot pin a StorageChunkSource of your own)',\n );\n }\n // A lease is taken between the pin's row read and its open (see `pinGeneration`). The holder is drawn once, here,\n // outside the retries, so a write that landed unseen is found by its holder when the pin is run again.\n let hold: LeaseHold | undefined;\n let take: PinLease | undefined;\n if (leaseUntil !== undefined) {\n const registry = this.requireRegistry('pin({ leaseUntil })');\n if (registry.capabilities().canWrite === false) {\n throw new UnsupportedError(\n \"pin({ leaseUntil }) needs a registry that can write a row, and this store's cannot in this runtime\",\n );\n }\n const holder = this.mintHolder();\n const deps = { registry, clock: this.clock, rng: this.rng };\n // A pin takes the generation current when its row is read, which must still be current when the write lands; a\n // `pinAt` takes the one it names, which only has to be published.\n const generationOf = (row: { currentGen: number | null }): number =>\n named?.generation ?? (row.currentGen as number);\n hold = {\n holder,\n until: leaseUntil,\n released: false,\n done: false,\n release: () => releaseLease(ref, deps, holder),\n };\n take = {\n take: (row) =>\n takeLease(ref, deps, {\n holder,\n generation: generationOf(row),\n until: leaseUntil,\n row,\n current: named === undefined,\n }),\n };\n }\n let at: Awaited<ReturnType<CrbmStorageChunkSource['pinGeneration']>>;\n try {\n // Under the store's retries, as its reads are: a transient fault resolving the pin must not fail pin().\n at = await this.withRetries(() =>\n named === undefined\n ? crbm.pinGeneration(ref, take)\n : crbm.pinGenerationAt(ref, named, take),\n );\n if (hold !== undefined && at === null) {\n throw new NotFoundError(`segment \"${ref.segment}\" has no generation to lease`);\n }\n } catch (err) {\n // A lease that landed and was not handed to a caller is released, so it holds nothing for its whole length.\n if (hold !== undefined) await hold.release().catch(() => undefined);\n throw err;\n }\n const pinnedAt: PinnedAt =\n at === null\n ? { generation: null, version: null, fingerprint: null }\n : { generation: at.generation, version: at.version, fingerprint: at.fingerprint };\n const pins = new Map([[segmentKey(ref), pinnedAt]]);\n return makeSegment({\n engine: this.engineWithPins(pins),\n origin: this.origin,\n ref,\n clock: this.clock,\n metrics: this.metrics,\n materialize: (dest, ids, op, options) => this.materialize(dest, ids, op, options),\n pinned: (r, l, at) => this.pinSegment(r, l, at),\n combineEngine: (handles) => this.engineForCombine(handles),\n pinnedAt,\n lease: hold,\n });\n }\n\n /** 16 hex digits from the store's `Rng`, which names the holder of one lease: unique, not secret. */\n private mintHolder(): string {\n let id = '';\n for (let i = 0; i < 4; i++)\n id += Math.floor(this.rng.next() * 0x10000)\n .toString(16)\n .padStart(4, '0');\n return id;\n }\n\n /**\n * An engine reading every segment in `pins` at its pinned generation and everything else live, with the store's\n * retries, so a transient fault on a pinned read is retried as it would be on a live one.\n *\n * It **shares the store's chunk cache and its memory bound**, under keys of its own for each pinned segment, and the\n * store engine's invalidations, so an invalidation of a pinned segment reaches a read of the pin already running.\n */\n private engineWithPins(pins: ReadonlyMap<string, PinnedAt>): SegmentEngine {\n const crbm = this.crbmSource;\n if (crbm === undefined) {\n throw new UnsupportedError(\n 'pin() needs the `.crbm` storage source \u2014 pass a backend or a raw IStorageDriver as `storage` (the store ' +\n 'cannot pin a StorageChunkSource of your own)',\n );\n }\n const pinned = new PinnedStorageChunkSource(crbm, pins);\n return new SegmentEngine({\n storage:\n this.retryOptions === undefined\n ? pinned\n : new RetryingStorageChunkSource(pinned, this.retryOptions),\n cache: this.cache,\n codec: flagshipCodec(),\n clock: this.clock,\n metrics: this.metrics,\n budget: this.budget,\n sharesInvalidationsWith: this.engine,\n });\n }\n\n /**\n * The engine a combine should run on, given the handles involved.\n *\n * A pinned handle passed as an **operand** must still be read at its pin. Routing by \"which handle the call\n * was made on\" reads it live instead \u2014 `snap.intersect([other])` honours the pin while\n * `other.intersect([snap])` silently does not, and the two are the same question. So the combine collects\n * every pin in play and runs on an engine that honours all of them. With no pins anywhere this is the\n * store's own engine and costs nothing.\n *\n * One engine reads a segment at one generation, so a combine that holds the same segment at two \u2014 two pins of\n * it, or a pin and a live handle \u2014 is refused. Keeping one of them would answer the question for the wrong\n * instant, and say nothing: diffing two snapshots of a segment returned no ids at all.\n */\n private engineForCombine(handles: readonly Segment[]): SegmentEngine | undefined {\n // A combine that pins nothing \u2014 nearly every one \u2014 cannot hold a segment twice at two generations, so it pays\n // one pass over its handles and nothing more.\n if (!handles.some((h) => h.pinnedAt !== undefined)) return undefined;\n const pins = new Map<string, PinnedAt>();\n const held = new Map<string, PinnedAt | undefined>();\n for (const h of handles) {\n const key = h.key();\n const at = h.pinnedAt;\n if (held.has(key)) {\n const before = held.get(key);\n if (!samePin(before, at)) {\n throw new ValidationError(\n `the same segment is in this combine twice, ${twoPins(before, at)}: one call reads a segment at one ` +\n 'generation, so materialise one of them into a segment of its own first, with ' +\n \"`materializeMany({ operands: { src: seg }, outputs: [{ dest, expr: { or: ['src'] } }], keep })`\",\n );\n }\n } else {\n held.set(key, at);\n }\n if (at !== undefined) pins.set(key, at);\n }\n return this.engineWithPins(pins);\n }\n\n /** `op` under the store's retries, as the store's own reads run; bare when the store has retries off. */\n private withRetries<T>(op: () => Promise<T>): Promise<T> {\n const r = this.retryOptions;\n return r === undefined ? op() : withRetry(op, r.policy ?? DEFAULT_RETRY_POLICY, r);\n }\n\n /** The store's registry, or a typed error naming the operation that needs one. */\n private requireRegistry(op: string): IRegistryDriver {\n if (this.registry === undefined) {\n throw new UnsupportedError(\n `${op} needs a storage backend \u2014 S3Storage, GcsStorage, AzureBlobStorage, LocalFsStorage or ` +\n `MemoryStorage. A bare IStorageDriver has no generation pointer to publish through, and there is ` +\n `no separate \\`registry\\` option: a backend carries it.`,\n );\n }\n return this.registry;\n }\n\n /**\n * **Cross-tier DR consistency check.** After a restore/failover, verify every registered segment's `currentGen`\n * actually has its `.crbm` present in Storage \u2014 catching a **torn restore** where the registry (`currentGen`) came\n * back ahead of the object store, so a pointer references a generation that isn't there (reads would then\n * throw). Read-only, bounded fan-out; run it at startup after a restore. Returns `{ checked, inconsistent,\n * errored }` \u2014 `inconsistent` empty \u21D2 coherent; otherwise it names the segments to recover (restore the object\n * store, or roll the registry back to a coherent point). Needs the store built with a **backend**\n * (throws {@link UnsupportedError} otherwise). `destroyed` segments (crypto-shredded, destroyed in the clear or\n * dropped) are skipped. Pair\n * it with the DR runbook (docs/guide/disaster-recovery.md).\n *\n * A segment whose pointer names a missing object is the torn restore this reports; a cold `count()` of it still\n * answers the number its row records, while a read of the object throws, so the count alone never shows it. With\n * `summaries: true` it also opens each segment's current object (one tail read each) and reports a segment whose\n * row's summary names another object by its fingerprint, or says another id count or metadata than the object holds,\n * as `summary-mismatch`, which is what a\n * restore of the registry from another point than the bucket leaves a count to answer. A sealed summary is held\n * against its object when this store has the key, and counted in `summariesUnchecked` when it does not.\n *\n * With `generations: true` it also holds every generation a row's ledger of known generations names, the current one\n * included, against its object: one footer read each (104 bytes, no key, not retried), reporting\n * `known-generation-mismatch` with the `generation` where the object under that number is not the one the row\n * recorded. A named generation that is not in the bucket is not reported. A row with a pointer whose ledger cannot\n * be used is counted in `generationsUnchecked`, and none of its objects is read.\n *\n * It holds the registry rows it enumerates resident, at most 250,000 of them, and throws\n * `BudgetExceededError` (`option: 'maxScanSegments'`) past that rather than report a partial scan as a whole one.\n * Narrow the scan with `namespace`, or raise `maxScanSegments` when the fleet really is that large and the memory\n * is there.\n */\n async checkConsistency(\n options: {\n namespace?: string;\n concurrency?: number;\n /** The most registry rows the scan holds resident (default 250,000); past it the call throws `BudgetExceededError`. */\n maxScanSegments?: number;\n summaries?: boolean;\n generations?: boolean;\n } = {},\n ): Promise<ConsistencyReport> {\n checkOptions(options, 'checkConsistency', CALL_KEYS.checkConsistency, [\n 'summaries',\n 'generations',\n ]);\n options ??= {};\n const deps = this.lifecycleDeps('checkConsistency');\n return runConsistencyCheck(\n { storage: deps.storage, registry: deps.registry, keystore: deps.keystore },\n options,\n );\n }\n\n /**\n * **First-run check of the store's storage and registry.** Call it once at deploy time, or on a first run, before\n * the first load: it finds a missing permission, a storage that does not refuse a second write to a key, a listing\n * that lags, or a lifecycle rule that would delete the store's objects, while nothing depends on them yet.\n *\n * It runs seven checks and always lists all seven, in this order: `registry` (one read of a row that must be\n * absent, and the registry able to write), `write` (a new object), `write-once` (a second write to the same key must\n * be refused), `read` (the object reads back as written), `list` (the listing names it), `delete` (this run's own\n * object is removed, with the version the read gave where the driver applies one) and `lifecycle` (the backend's\n * lifecycle check). The probe is one small object at `cbm.due.preflight/segments/probe.<number>.crbm` under the\n * store's prefix; no registry row is written, and no segment of yours can share the name. A probe left by a run that\n * was cut off is named in the `list` detail and never deleted, since it could be a run in progress.\n *\n * It **never throws over a finding**. A failed step, a transient fault included, is a `problem` whose `detail`\n * says to run again when the fault was transient, and the checks that cannot run without it are `unchecked`. The\n * exception is the `lifecycle` step, whose failures, its timeout included, are `unchecked`. `ok` is true when no\n * check is a `problem`: read an `unchecked` check yourself, as `ok` does not vouch for it. The `lifecycle` check is\n * `unchecked` for a backend whose check says so (Azure Blob always), for a backend that has no such method (a\n * third-party backend, a `brandAsBackend` wrapper that does not forward it), when the identity lacks the optional\n * permission to read the lifecycle rules (`s3:GetLifecycleConfiguration`, `storage.buckets.get`), and when the check\n * takes longer than 30 seconds of the store's clock. The other steps are the store's ordinary calls and keep their\n * timing.\n *\n * **Not checked:** read-after-delete, the registry's `If-Match` on compare-and-swap, multipart abort permission,\n * versioning, backups, the keystore's backup and an S3 SDK from 3.641.0 to 3.699.0 (an older SDK shows as a\n * `write-once` problem; these drop `If-Match`, which only a registry write refuses). It makes no kind of request that a\n * load does not, though the lifecycle read needs its own optional permission. A run costs about seven requests (a\n * first run on GCS makes eight, the eighth a second listing that checks the bucket exists, and Azure Blob always\n * eight): two writes and a delete, the rest reads and one listing.\n *\n * Throws {@link UnsupportedError}, and only that, for a store with no backend, since there is nothing to check.\n */\n async preflight(): Promise<PreflightResult> {\n const deps = this.lifecycleDeps('preflight');\n const backend = this.backend;\n let checkLifecycle: NonNullable<StorageBackend['checkLifecycle']> | undefined;\n try {\n // A wrapper may carry anything under the name; only a function is a check.\n const method: unknown = backend?.checkLifecycle;\n if (typeof method === 'function')\n checkLifecycle = method.bind(backend) as typeof checkLifecycle;\n } catch {\n // a getter that throws offers no check\n }\n return runPreflight({\n storage: deps.storage,\n registry: deps.registry,\n clock: this.clock,\n entropy: this.entropy,\n checkLifecycle,\n });\n }\n\n /**\n * **Export (\"eject\") every registered segment's current generation** through the injected `sink`, using only\n * public read APIs \u2014 so your data is readable **without CloudRoaring** (the exit path; see the README's \"Your\n * data stays yours\"). `format: 'roaring'` (default) writes one **portable Roaring bitmap** per segment\n * (loadable by any roaring library); `'ndjson'` writes newline-delimited ids (zero-dependency, streaming).\n * Enumerates via the store's **own** registry (needs one \u2014 throws {@link UnsupportedError} otherwise) so the\n * enumeration and the read path provably share one registry. Encrypted segments are decrypted transparently\n * **iff** this store was wired with their keystore \u2014 the export is therefore **cleartext**; protect it.\n * Destroyed segments (crypto-shredded, destroyed in the clear or dropped) are skipped. A segment that can't be read\n * is isolated into the manifest's `failed[]` (the run continues), so \"a manifest exists\" means the run finished \u2014\n * check `failed`. The `export-segments`\n * CLI wraps this with a filesystem sink. The `'roaring'` format's bitmaps are built by the store's own codec.\n */\n async exportSegments(sink: ExportSink, options: ExportOptions = {}): Promise<ExportManifest> {\n checkOptions(options, 'exportSegments', CALL_KEYS.exportSegments, [], MISPLACED.exportSegments);\n const opts = picked(options, CALL_KEYS.exportSegments);\n const registry = this.requireRegistry('exportSegments');\n // The store's own codec builds the `'roaring'` format's bitmap: core's `runExport` is codec-agnostic and needs one.\n return runExport(this, registry, sink, { ...opts, codec: flagshipCodec() });\n }\n}\n\n/**\n * The options of a read or a combine on a {@link Segment}: one type for all of them, and each verb takes the fields that\n * apply to it.\n *\n * | verb | takes |\n * |---|---|\n * | `iterate`, `everyNth` | `after`, `through` |\n * | `intersect`, `union` | the range, `concurrency`, `budget`, `allowAbsentOperands`, `exclude` |\n * | `andNot` | the same but `exclude`: its `excludes` argument is the subtraction |\n * | `intersectInto`, `unionInto` | every field |\n * | `andNotInto` | every field but `exclude` |\n *\n * `audit`, `allowEmpty`, `guard`, `metadata` and `keep` decide what an `*Into` verb publishes, and a read publishes\n * nothing. A field a verb does not take is refused with a {@link ValidationError} that names it, before any request,\n * whether the object holds it as an own key, inherits it or holds it in a getter: a streaming read fails when it is first\n * read, and an `*Into` verb rejects. The compiler catches one only in an object\n * literal given to `iterate` or `everyNth`, which take the range alone: `Pick<CombineOptions, 'after' | 'through'>`,\n * the part {@link MaterializeManyOptions} extends.\n *\n * **The range**, `after` and `through`, is the ids greater than `after` and no greater than `through`, `(after,\n * through]`, built for keyset paging: `after` is the last id the caller already has, `through` the end of its window.\n * Each is optional: left out, the read starts at the first id or runs to the last. Each is an integer in\n * `0..4294967295`, or the read throws {@link ValidationError} when it is first read. `after >= through` is an empty range,\n * not an error, because a cursor that has reached the end of its window is normal; an empty range reads nothing, not even\n * whether a combine's operands exist. On a combine the range applies to every operand and every `exclude`, and a read\n * with a range fetches only the chunks it overlaps. The per-op budget is charged before the first fetch, for every chunk\n * in the range, so with `after` alone it is charged to the end of the segment however early the caller stops; pass\n * `through` to bound it. A read that lists its keys again after a move is charged again, with the chunks it has already\n * taken.\n */\nexport interface CombineOptions {\n /** Exclusive lower bound: the read yields only ids greater than this. */\n readonly after?: number | undefined;\n /** Inclusive upper bound: the read yields only ids up to and including this. */\n readonly through?: number | undefined;\n /**\n * How far ahead each operand is read: a positive integer, default 32. The library's own stores read each operand as\n * one stream of coalesced ranges (chunks that sit near each other are one request), and `concurrency` is how many\n * range requests a stream holds ahead of the read, in flight or landed and not yet used. So about\n * `concurrency \u00D7 operands` requests are in flight at most, and, since a range is at most 1 MiB (one chunk, when a chunk\n * is larger), about `concurrency \u00D7 operands` MiB are held, whatever the segment's size. The stream opens 4 ranges wide\n * (or `concurrency`, if lower) and widens as ranges are taken, so a read that stops early has asked for little past\n * where it stopped, and a read that fits one range makes one request however many chunks it needs. A source that\n * reads chunk by chunk (a custom one) is read `concurrency` chunk keys at once, opening 8 wide. A running\n * stream holds its operand's reader outside the reader cache's bounds until it ends or the segment moves on.\n */\n readonly concurrency?: number;\n /** Override the store's per-op denial-of-wallet budget for this call (`false` lifts it). */\n readonly budget?: BudgetOption;\n /**\n * Allow an operand naming a segment that does not exist. Default `false`: a combine **refuses** one, because\n * a misspelled or mis-namespaced operand is indistinguishable from a correct one in the result.\n *\n * Reading a segment that does not exist answers empty, and that is right \u2014 but passing one as an operand is\n * different. A suppression list with nobody on it correctly suppresses nothing; one whose `namespace` you\n * omitted *silently* suppresses nothing, and the result is not obviously-empty, it is the full audience and\n * plausibly right. The failure mode is mailing the people who opted out.\n *\n * ```ts\n * // `global-opt-out` lives in the `suppression` namespace. This addresses a DIFFERENT segment:\n * audience.andNot([store.segment('global-opt-out')]); // throws ValidationError\n * audience.andNot([store.segment('global-opt-out', { namespace: 'suppression' })]); // correct\n * ```\n *\n * Set `true` when you genuinely intend to combine against a name that may not exist yet. Checked only for an\n * operand that resolved to no chunks at all, so a normal combine pays nothing for it.\n */\n readonly allowAbsentOperands?: boolean;\n /**\n * Segments whose ids are subtracted from the result, on `intersect`, `union`, `intersectInto` and `unionInto`.\n *\n * `exclude` is why suppression does not need an intermediate segment: applied here it folds into the same\n * chunk-aligned pass, and each exclude is read **only at the keys that survived** \u2014 so a large global opt-out\n * list costs reads proportional to the audience, not to itself. `andNot` and `andNotInto` refuse it: their `excludes`\n * argument is the subtraction, and a second one in the options would be two spellings of one thing.\n */\n readonly exclude?: Segment[];\n /**\n * Audit sink, for the `*Into` verbs. A materialisation publishes a generation, and a publish is an auditable event\n * (`segment.publish`, exactly as a load emits) \u2014 as is a refusal (`segment.load-refused`).\n *\n * It is on the call rather than on the store because that is where every other auditable operation takes it\n * (`eraseSubject`, `dropSegment`, `retireExpired`): the caller who performs the act decides where the record\n * goes. Without it a `*Into` would be the one write path in the library that could make a generation current\n * and leave no trace in the compliance trail. A read verb writes nothing and emits nothing, so it refuses one.\n */\n readonly audit?: IAuditSink;\n /**\n * For the `*Into` verbs: publish an empty result over a non-empty destination. Off by default, exactly as on\n * {@link CloudRoaring.load}: an empty combine is far more often a mistake upstream \u2014 a typo'd operand, a segment that\n * has not loaded yet, an `exclude` that swallowed everything \u2014 than an intent, and once it lands it is\n * indistinguishable from a correct run.\n */\n readonly allowEmpty?: boolean;\n /**\n * For the `*Into` verbs: refuse an implausible result rather than publish it. Same bounds, and same meaning, as on\n * `load()`.\n */\n readonly guard?: LoadGuard;\n /**\n * For the `*Into` verbs: metadata for the generation the call publishes, under the rules and with the meaning of\n * {@link LoadOptions.metadata}: small, immutable, published with the pointer, never a subject's id. A value that\n * breaks a rule throws {@link ValidationError} before any request is made.\n */\n readonly metadata?: GenerationMetadata;\n /**\n * For the `*Into` verbs: generations to keep below the new pointer \u2014 see {@link LoadOptions.keep}. A value that is\n * not a non-negative integer throws `ValidationError`.\n *\n * **Defaults to keeping everything**, unlike `load()`, which keeps 1 and collects what it supersedes. An operator's\n * recovery story can depend on a materialisation collecting nothing: `rollbackSegment` refuses a target that\n * has been collected. Pass a number to collect on the way through; `0` keeps only the\n * generation this call publishes. It collects by listing the destination, so it clears every generation below the\n * new one beyond `keep`, however many earlier calls kept, where a `load()` deletes by name the generations its\n * publish pushes out of the window.\n */\n readonly keep?: number;\n}\n\n/**\n * An id stream as an iterator: the ids ascending, driven by `for await` or by hand with `next()`, `return()` and\n * `throw()`, as a generator is, on a handle that holds a lease as on one that does not. It is its own iterator and\n * single-use. {@link Segment.everyNth} returns this; the streams of {@link IdStream} add `batches()`.\n */\nexport interface IdIterator extends AsyncIterableIterator<number> {\n /** Ends the read, as a generator's `return` does, and resolves done with `value`. */\n return(value?: unknown): Promise<IteratorResult<number, unknown>>;\n /** Throws `err` into the read, as a generator's `throw` does: it rejects with `err` unless the read handles it. */\n throw(err: unknown): Promise<IteratorResult<number, unknown>>;\n}\n\n/**\n * What a streaming read returns: the ids, ascending, one at a time under `for await`, or one chunk at a time from\n * {@link IdStream.batches}.\n *\n * It is an `AsyncIterable<number>`, so every consumer of an id stream takes it as an async iterable, and an\n * {@link IdIterator}, so `next()`, `return()` and `throw()` are typed. A live read is the\n * engine's async generator itself, with `batches` attached: `for await` it, or drive it with `next()`, `return()` and\n * `throw()`, and it is single-use (a second `for await` over it yields nothing). A handle that holds a lease returns a\n * stream of the same shape, which checks the lease as it reads. `batches()` is a\n * separate, new read: it starts when called, fetches its chunks afresh and charges the per-op budget again, whether or\n * not the per-id stream was read, and reading both is two reads (invariant 3 applies to each separately). Nothing is\n * fetched until a read is first pulled. A stream pulled with `next()` and dropped without `return()` is held by nothing\n * in the store, so it is garbage once the caller lets it go.\n */\nexport interface IdStream extends IdIterator {\n /**\n * The same ids as the per-id stream, in the same order, one `Uint32Array` per chunk: each array ascending, holding\n * every id of one chunk the read yields (a range trimmed at its edges exactly as the per-id stream trims it), and\n * no array is empty. Chunks arrive in ascending order, so the concatenation is the per-id stream.\n *\n * One `await` per chunk instead of one per id: measured locally, an in-memory read goes several times faster, and\n * a large scan stops being bound by the event loop. The reads, the budget and the read-ahead window are the per-id\n * stream's, and so is stopping early: leaving a `for await` over it (`break`, `return`, a throw) ends the read.\n *\n * **Memory:** one array per chunk, at most 65,536 ids (256 KiB), allocated for that chunk alone and yours to\n * keep, change or hand on; the read holds no reference to it after yielding it.\n *\n * ```ts\n * for await (const ids of seg.andNot([optOut]).batches()) await send(ids);\n * ```\n */\n batches(): AsyncIterable<Uint32Array>;\n}\n\n/** A generator the engine just made, with the batch read that goes with it attached. Adds nothing per id. */\nconst withBatches = (\n gen: AsyncGenerator<number>,\n batches: () => AsyncIterable<Uint32Array>,\n): IdStream => Object.assign(gen, { batches });\n\n/** A generator function whose generator throws `err` on its first pull: what a refused read is, so its caller can drive it as any other. */\nconst refusing = (err: unknown) =>\n // eslint-disable-next-line require-yield\n async function* (): AsyncGenerator<never> {\n throw err;\n };\n\n/**\n * A stream that fails when it is first read, either way, and has the shape of one that does not: a generator, with\n * `batches` attached. A combine refuses its arguments this way, as the engine's own checks do, so a caller's try/catch\n * around the iteration catches it.\n */\nconst failing = (err: unknown): IdStream => withBatches(refusing(err)(), refusing(err));\n\n/** Whether two handles of one segment read it at one generation: both live, or both pinned to one object. */\nconst samePin = (a: PinnedAt | undefined, b: PinnedAt | undefined): boolean =>\n a === undefined || b === undefined\n ? a === b\n : a.generation === b.generation && a.fingerprint === b.fingerprint;\n\n/** How a refusal names two handles of one segment that read it at two generations. */\nconst twoPins = (a: PinnedAt | undefined, b: PinnedAt | undefined): string => {\n const one = (p: PinnedAt | undefined): string =>\n p === undefined ? 'live' : `pinned at generation ${p.generation ?? 'none'}`;\n return a !== undefined && b !== undefined && a.generation === b.generation\n ? `pinned twice at generation ${a.generation ?? 'none'}, as two different objects`\n : `${one(a)} and ${one(b)}`;\n};\n\n/** Every key of `T`, each possibly `undefined`: a copy typed this way fails to compile until it names every field. */\ntype EveryField<T> = { [K in keyof Required<T>]: T[K] | undefined };\n\n/** A read's range, read once, now, from whatever object holds it: a getter or an inherited bound included. */\nconst rangeOf = (options: RangeOptions): EveryField<RangeOptions> => ({\n after: options.after,\n through: options.through,\n});\n\n/**\n * How a combine reads its operands, read once, now, field by field, for the same reason as {@link rangeOf}. Typed to\n * name every field, so a read option added to {@link CombineOptions} and not listed here fails to compile instead of\n * being dropped.\n */\nconst readOptions = (options: ReadOptions): EveryField<ReadOptions> => ({\n ...rangeOf(options),\n concurrency: options.concurrency,\n budget: options.budget,\n allowAbsentOperands: options.allowAbsentOperands,\n});\n\nconst NO_SEGMENTS: readonly Segment[] = [];\n\n/**\n * `list` when it is an array, else a {@link ValidationError} naming `what`. A combine takes its operands and its\n * `exclude` as arrays: a `Set` or a lone segment from plain JavaScript would otherwise fail with a raw `TypeError`, or,\n * as an `exclude`, be read as no exclusion at all.\n */\nfunction segmentList(list: unknown, what: string): readonly Segment[] {\n if (!Array.isArray(list)) throw new ValidationError(`${what} must be an array of segments`);\n return list as readonly Segment[];\n}\n\ntype CombineVerb = 'intersect' | 'union' | 'andNot';\n\n/**\n * The segments a stream of this library reads, by key, held by the stream object. `store.load` consults it so that ids\n * read from a segment are not loaded back into that segment: the load publishes forward over whatever the segment is\n * by then, so another process's newer load of it would be replaced by a result built from the one before. Only a\n * stream handed over as it was returned is known; one wrapped in a generator of the caller's is not.\n */\nconst STREAM_SOURCES = new WeakMap<object, { origin: object; keys: readonly string[] }>();\n\n/** The registry driver each store was built over, by the store's origin: two stores over one backend instance share one. */\nconst REGISTRY_OF = new WeakMap<object, object>();\n\n/** `stream`, remembered as reading the segments `keys` of the store `origin`. */\nfunction readsFrom<T extends object>(stream: T, origin: object, keys: readonly string[]): T {\n STREAM_SOURCES.set(stream, { origin, keys });\n return stream;\n}\n\n/** How a refused operand list is named: `andNot` takes `excludes`, the others take `others`. */\nfunction operandsLabel(verb: CombineVerb): string {\n return verb === 'andNot' ? 'andNot: `excludes`' : `${verb}: \\`others\\``;\n}\n\n/**\n * The refusal of an empty operand list on `intersect` and `intersectInto`: an intersection over nothing has no meaning,\n * and a list built in a loop that came out empty would otherwise turn a filter into no filter. `union`, `andNot` and\n * their `*Into` forms read an empty list as the receiver itself. `verb` begins the message; the `*Into` form points a\n * caller who wanted a copy at the batch call, which reads a segment once at one instant.\n */\nfunction refuseNoOperands(verb: 'intersect' | 'intersectInto'): never {\n throw new ValidationError(\n verb === 'intersect'\n ? 'intersect requires at least one segment to intersect with; to read every id of one segment, use iterate()'\n : 'intersectInto requires at least one segment to intersect with; to copy this segment into dest, call ' +\n \"materializeMany({ operands: { src: thisSegment }, outputs: [{ dest, expr: { or: ['src'] } }], keep })\",\n );\n}\n\ntype EngineCombine = Parameters<SegmentEngine['intersect']>[1];\ntype EngineAndNot = Parameters<SegmentEngine['andNot']>[2];\n\n/**\n * What a combine is read as: the ids a caller streams, or the chunks an `*Into` writes. The three verbs make the\n * same decisions about `exclude`, the engine and the options whichever it is, so each is written once over this, and\n * only the last step differs.\n */\ninterface CombineOutput<T> {\n /** A combine that fails when first read, as the engine's own refusals do. */\n readonly failing: (err: unknown) => T;\n /** The same combine, checking a lease each time it reads a chunk. */\n readonly guard: (result: T, check: () => void) => T;\n readonly intersect: (engine: SegmentEngine, refs: SegmentRef[], opts: EngineCombine) => T;\n readonly union: (engine: SegmentEngine, refs: SegmentRef[], opts: EngineCombine) => T;\n readonly andNot: (\n engine: SegmentEngine,\n base: SegmentRef,\n refs: SegmentRef[],\n opts: EngineAndNot,\n ) => T;\n}\n\n/** Combines read as ids: what `intersect`, `union` and `andNot` return. */\nconst AS_IDS: CombineOutput<IdStream> = {\n failing,\n guard: guardIds,\n intersect: (engine, refs, opts) =>\n withBatches(engine.intersect(refs, opts), () => engine.intersectBatches(refs, opts)),\n union: (engine, refs, opts) =>\n withBatches(engine.union(refs, opts), () => engine.unionBatches(refs, opts)),\n andNot: (engine, base, refs, opts) =>\n withBatches(engine.andNot(base, refs, opts), () => engine.andNotBatches(base, refs, opts)),\n};\n\n/** A combine's result as the chunks it is made of. */\ntype ChunkStream = AsyncIterable<{ chunkKey: number; bitmap: CodecBitmap }>;\n\n/** A combine's chunks on their way to a load, which writes them as they are. */\nclass CombineChunks {\n constructor(readonly chunks: ChunkStream) {}\n}\n\n/** Combines read as chunks: what the `*Into` verbs write into the new generation, with no id built on the way. */\nconst AS_CHUNKS: CombineOutput<ChunkStream> = {\n guard: guardItems,\n failing: (err) => refusing(err)(),\n intersect: (engine, refs, opts) => engine.intersectChunks(refs, opts, 'intersectInto'),\n union: (engine, refs, opts) => engine.unionChunks(refs, opts, 'unionInto'),\n andNot: (engine, base, refs, opts) => engine.andNotChunks(base, refs, opts, 'andNotInto'),\n};\n\n/**\n * The `keep` a materialisation passes when the caller does not: a grace window wide enough to collect nothing.\n *\n * The collection keeps `keep` generations below the pointer and deletes the rest, so an\n * integer at the top of the range keeps all of them. It has to be an integer \u2014 `loadSegment` validates that,\n * and `Infinity` is rejected \u2014 which is why this is `MAX_SAFE_INTEGER` and not the value that reads more\n * naturally.\n */\nconst KEEP_EVERY_GENERATION = Number.MAX_SAFE_INTEGER;\n\n/** Build a pinned twin of a handle \u2014 injected into `Segment` so it stays free of store wiring. */\ntype Pin = (ref: SegmentRef, leaseUntil?: number, at?: PinAt) => Promise<Segment>;\n\n/**\n * The engine a combine should run on, given every handle involved \u2014 `undefined` when none is pinned and the\n * store's own engine will do. Injected so `Segment` stays free of store wiring.\n */\ntype CombineEngine = (handles: readonly Segment[]) => SegmentEngine | undefined;\n\n/** How a `Segment` hands a result stream back to its store to become a new generation of `dest`. */\ntype Materialize = (\n dest: SegmentRef,\n ids: LoadInput | CombineChunks,\n op: string,\n options?: CombineOptions,\n) => Promise<MaterializeResult>;\n\n/** What a {@link Segment} is built from: the store's own wiring, which is why a handle is not constructible. */\ninterface SegmentParts {\n engine: SegmentEngine;\n /** The store's identity token, shared by every handle the store makes. */\n origin: object;\n ref: SegmentRef;\n clock: Clock;\n metrics: IMetricsSink;\n materialize: Materialize;\n /** Build a pinned twin of this handle \u2014 injected so `Segment` stays free of store wiring. */\n pinned: Pin;\n combineEngine: CombineEngine;\n pinnedAt?: PinnedAt;\n /** The lease this handle holds, when it came from `pin({ leaseUntil })`. */\n lease?: LeaseHold;\n}\n\n/**\n * The state of the lease a handle holds. `released` is set first by `release()`, so a read racing it already fails; `done`\n * once the registry write has landed, so a second `release()` makes no request.\n */\ninterface LeaseHold {\n readonly holder: string;\n readonly until: number;\n released: boolean;\n done: boolean;\n readonly release: () => Promise<void>;\n}\n\n/** What {@link Segment.pin} and {@link Segment.pinAt} take besides the generation. */\nexport interface PinOptions {\n /**\n * Hold the pinned generation until this instant: epoch-**milliseconds**, after now and at most\n * 14 days (1,209,600,000 ms) from it. A load's collection leaves a leased generation in the bucket until the lease\n * ends, and a read of the handle after it throws {@link LeaseExpiredError}, never empty.\n */\n readonly leaseUntil?: number;\n}\n\n/** The lease a pinned handle holds, as {@link Segment.lease} reports it. */\nexport interface Lease {\n /** 16 hex digits naming this lease in the segment's registry row. */\n readonly holder: string;\n /** Epoch-ms the lease runs to on this store's clock. */\n readonly until: number;\n}\n\n/**\n * The generation {@link Segment.pinAt} reopens: what an earlier pin recorded in {@link Segment.pinnedAt}. The\n * fingerprint is required, since a generation number is taken again after a purge and re-create.\n */\nexport interface PinAt {\n /** The generation number an earlier pin held. */\n readonly generation: number;\n /** The fingerprint of that generation's object, from the earlier pin's `pinnedAt.fingerprint`. */\n readonly fingerprint: string;\n}\n\n/**\n * What {@link Segment.stat} answers: the generation a handle reads, its id count, its metadata and the size of its\n * object.\n */\nexport interface SegmentStat {\n /** The generation read, or `null` when the segment has none. */\n readonly generation: number | null;\n /** The number of ids in the generation read, or `0` when the segment has none. */\n readonly cardinality: number;\n /** The metadata the generation was loaded with; absent when it has none. */\n readonly metadata?: GenerationMetadata;\n /**\n * The generation's object in storage, in bytes: what the segment stores. From the registry row's summary, which\n * records the object's size with its checksum, or from the object's footer when the row has no summary to use.\n * `null` when the segment has no generation, or when the store's source cannot report a size.\n */\n readonly sizeBytes: number | null;\n}\n\n/**\n * Time `fn` with `clock` and emit an `op` metric to `metrics` when it settles, on success or throw: the store's timing,\n * as a segment's `timed` does its own inline, which keeps a promise off the path of `has` and `count`.\n */\nasync function timeOp<T>(\n metrics: IMetricsSink,\n clock: Clock,\n name: MetricOpName,\n fn: () => Promise<T>,\n): Promise<T> {\n const startedAt = clock.now();\n try {\n return await fn();\n } finally {\n metrics.onEvent({ kind: 'op', name, ms: Math.max(0, clock.now() - startedAt) });\n }\n}\n\n/** The store's one way to mint a {@link Segment}, bound by the class's static block. */\nlet makeSegment: (parts: SegmentParts) => Segment;\n/** True only while {@link makeSegment} is constructing, so a `new Segment(...)` from plain JS is refused. */\nlet minting = false;\n\n/**\n * A handle bound to one segment \u2014 the read verbs, plus the three `*Into` verbs that write a **new generation**\n * of another segment.\n *\n * **IDs must be integers in `[0, 2^32)`** (dense 32-bit). A non-integer / negative / out-of-range id\n * throws {@link ValidationError}.\n *\n * A handle has no per-id write: data enters a segment as a whole generation (`store.load()`, or one of the\n * `*Into` verbs), and leaves it the same way (`eraseSubject`, `dropSegment`).\n */\nexport class Segment {\n private readonly metricsOn: boolean;\n private readonly engine: SegmentEngine;\n /** The store that made this handle, by reference; a combine takes only handles of its own store. */\n private readonly origin: object;\n private readonly ref: SegmentRef;\n private readonly clock: Clock;\n private readonly metrics: IMetricsSink;\n private readonly materialize: Materialize;\n private readonly pinned: Pin;\n private readonly combineEngine: CombineEngine;\n /**\n * The generation this handle is held at, when it came from {@link Segment.pin}. Read by the store so a\n * pinned handle passed as an **operand** is still read at its pin rather than live.\n */\n readonly pinnedAt?: PinnedAt;\n /**\n * The lease this handle holds, when it came from `pin({ leaseUntil })`; `undefined` otherwise. It reports what was\n * taken and does not change when the lease ends: a read after `lease.until` (or after {@link Segment.release}) throws\n * {@link LeaseExpiredError}.\n */\n readonly lease?: Lease;\n private readonly leaseHold?: LeaseHold;\n\n static {\n Object.defineProperty(Segment.prototype, SEGMENT_BRAND, { value: true });\n makeSegment = (parts) => {\n minting = true;\n try {\n return new Segment(parts);\n } finally {\n minting = false;\n }\n };\n viewOf = (segment) => ({\n ref: segment.ref,\n pinnedAt: segment.pinnedAt,\n leaseError: () => segment.leaseError(),\n });\n originOf = (segment) => segment.origin;\n }\n\n /**\n * Not constructible: a handle comes from {@link CloudRoaring.segment}, which wires it to the store's engine,\n * caches and write path. The constructor takes those internals, so it is not part of the surface.\n */\n private constructor(parts: SegmentParts) {\n if (!minting) {\n throw new ValidationError(\n 'a Segment is not constructed directly; call `store.segment(name)`',\n );\n }\n this.engine = parts.engine;\n this.origin = parts.origin;\n this.ref = parts.ref;\n this.clock = parts.clock;\n this.metrics = parts.metrics;\n this.materialize = parts.materialize;\n this.pinned = parts.pinned;\n this.combineEngine = parts.combineEngine;\n this.pinnedAt = parts.pinnedAt;\n this.leaseHold = parts.lease;\n if (parts.lease !== undefined) {\n this.lease = Object.freeze({ holder: parts.lease.holder, until: parts.lease.until });\n }\n this.metricsOn = parts.metrics !== NOOP_METRICS;\n }\n\n /**\n * **Hold this segment at the generation that is current right now**, for as long as you keep the handle.\n *\n * An ordinary handle re-resolves on `cache.genTtlMs`, so a publish part-way through a long job means its second\n * half describes a different instant than its first \u2014 every chunk whole and verified, but the answer covering\n * two moments, with nothing in the result saying so. That is fine for a dashboard and wrong for an export, a\n * reconciliation, or a send that has to match the count you reported. A pin is how you get one instant.\n *\n * ```ts\n * const snap = await store.segment('active-30d').pin();\n * const total = await snap.count(); // the number you report\n * for await (const id of snap.iterate()) { \u2026 } // \u2026and the ids it counted, however long this takes\n * ```\n *\n * **Only this segment is pinned.** `snap.intersect([other])` reads `snap` at its pinned generation and\n * `other` at whatever is current \u2014 pin each segment if you want the whole query held. And a pinned handle\n * used as an *operand* is still read at its pin, never live.\n *\n * **One call reads a segment at one generation**, so a combine that holds this segment at two \u2014\n * `snap0.andNot([snap1])`, or `live.intersect([snap])` \u2014 throws {@link ValidationError} when it is read, and an\n * `*Into` of one throws before it reads anything. Materialise one side first, with `materializeMany({ operands: { src: seg }, outputs: [{ dest, expr: { or: ['src'] } }], keep })`.\n *\n * **A pin knows its object, not only its number.** A name purged and loaded again starts again at generation\n * 0, so a pin of the old segment never reads the new one: what it has already read still answers, as the\n * instant it pinned, and anything it would have to fetch fails with `NotFoundError`, as a swept pin's does.\n *\n * **It is a hold, and `pin({ leaseUntil })` makes it a bounded one.** Without a lease nothing stops a collection\n * deleting the generation underneath you: a pinned read deliberately does **not** heal forward, because silently\n * serving a different generation is the one thing a pin exists to prevent, so it fails instead. Size `keep` to cover\n * your longest pinned job \u2014 see [Generations and `keep`](https://github.com/cloudbitmaps/cloudbitmaps/blob/main/docs/guide/loading.md#generations-and-keep) \u2014 take the pin on a segment\n * you are not collecting, or lease it.\n *\n * **A lease** (`leaseUntil`: epoch **milliseconds**, after now and at most 14 days out) keeps the generation out of\n * a load's collection until then, from any process, and the pin is taken with it: the lease is written to the segment's\n * row before the object is opened. A read of the handle after the lease, or after {@link Segment.release}, throws\n * {@link LeaseExpiredError} at every read site, including when the handle is an operand or an `exclude` of a combine\n * or the target of an `*Into`, and never reads empty. A stream checks the lease each time it reads a chunk. A segment\n * holds at most 64 live leases ({@link LeaseLimitError}). A collector holds a lease 60 seconds past its end, which covers\n * clocks that differ by that much. Erasure, shred, drop and retention expiry ignore a lease. See\n * [Hold a generation for a job](https://github.com/cloudbitmaps/cloudbitmaps/blob/main/docs/guide/reading.md#hold-a-generation-for-a-job-a-lease).\n *\n * A segment with no current generation pins nothing and reads empty, exactly as it would unpinned. A pinned\n * segment whose row is later dropped or destroyed fails once it must open its object again, rather than go empty\n * part-way through a call. **A pin\n * keeps the key its reader unwrapped for as long as that reader stays open, and answers from the chunks it\n * decoded for as long as they stay cached.** This store invalidates a pin:\n *\n * - a `load`, a `rollback` or an `*Into` invalidates a pin of the segment it writes;\n * - `dropSegment` invalidates a pin of the segment it drops, and `retireExpired` a pin of each segment its ledger\n * lists, retired or not, neither on a dry run;\n * - `eraseSubject` invalidates a pin of each segment it scans that is not already destroyed.\n *\n * An invalidated pin opens its object again, and fails if that object is gone or replaced, or its row is gone or\n * destroyed. A read of the pin already running when the invalidation comes, a combine on this store with the pin as\n * an operand included, looks the pin up again before it hands out its next chunk: it carries on with what it holds\n * where the object is still there, and fails with `NotFoundError` where it is gone. It caches nothing more of what it\n * began reading before the invalidation, so the pin's next read opens the object again too.\n * Anything else leaves the pin as it is: after a `destroySegment` beside this store, or an erasure, a drop or a\n * retirement through another store, in this process or another, the pin answers from what it holds until this\n * store's reader cache evicts the pin's reader and its chunk cache evicts the chunks the pin decoded, or\n * {@link CloudRoaring.invalidate} is called on this store. A combine on another store refuses the pin. Where the\n * object the pin reads has been deleted, by an erasure, a drop or a sweep, a chunk the pin has not cached fails at\n * once. No timed refresh bounds any of that, as none bounds anything else a pin holds.\n *\n * A replacement a pin has found is remembered, so its later chunk reads fail with no request, until the store\n * forgets it: an invalidation of the segment does, as does a later `pin()` of the same version that opens the object\n * again, and the store remembers at most `cache.readerMax` of them. So once a restore puts the pinned object back,\n * call {@link CloudRoaring.invalidate} on this store: the pin then reads the object again.\n *\n * `pin()` reads the registry row and opens the generation at once, so the pin knows its object before its first\n * read. With a registry, pins of one generation taken while its row is unchanged share one reader while the store\n * keeps it open, pins taken at the same moment included: the first costs a tail read, and a key unwrap for an\n * encrypted segment, whether or not it is read, and the rest cost the row read alone. Without a registry every\n * `pin()` lists the segment's objects and makes the tail read, since only the object can tell two incarnations of\n * a name apart there. It retries a\n * transient fault as the store's reads do, and heals a generation swept between the two, but it fails where the\n * generation cannot be opened: `NotFoundError` for a pointer at a missing object, `IntegrityError` for a damaged\n * or misfiled one.\n *\n * Needs a store built on the `.crbm` storage source (the default when you pass a backend or a raw driver). Throws\n * {@link UnsupportedError} on a store wired with a `StorageChunkSource` of your own, which it cannot pin.\n */\n async pin(options?: PinOptions): Promise<Segment> {\n // A leased handle pins nothing once its lease is over. The pin it makes is an ordinary one: it takes the generation\n // that is current now, which is not the leased one, and holds no lease of its own unless asked.\n this.assertLease();\n const leaseUntil = this.leaseUntilOf('pin', options);\n return this.pinned(this.ref, leaseUntil);\n }\n\n /**\n * Hold what this pin names until `leaseUntil`, or `undefined` for a pin with no lease. Refuses an option it does not\n * know, a value that is not epoch-milliseconds in the future, and one past the longest lease, before any request is\n * made.\n */\n private leaseUntilOf(op: string, options: PinOptions | null | undefined): number | undefined {\n if (options === undefined || options === null) return undefined;\n if (typeof options !== 'object' || Array.isArray(options)) {\n throw new ValidationError(`${op}: options must be an object such as { leaseUntil }`);\n }\n // Own enumerable string keys only, as `pinAt` reads its argument.\n const unknown = Object.keys(options).filter((k) => k !== 'leaseUntil');\n if (unknown.length > 0) {\n throw new ValidationError(\n `${op}: unknown option${unknown.length > 1 ? 's' : ''} ${unknown.map((k) => `\"${k}\"`).join(', ')}; ` +\n 'this version takes { leaseUntil } only',\n );\n }\n const until = options.leaseUntil;\n if (until === undefined) return undefined;\n const now = this.clock.now();\n if (typeof until !== 'number' || !Number.isSafeInteger(until)) {\n throw new ValidationError(\n `${op}: leaseUntil must be an integer epoch-MILLISECONDS; got ${String(until)}`,\n );\n }\n if (until <= now) {\n throw new ValidationError(\n `${op}: leaseUntil (${until}) is not after now (${now}); it is epoch MILLISECONDS, so a value in seconds ` +\n 'reads as long past. Use `Date.now() + hours * 3_600_000`',\n );\n }\n if (until > now + MAX_LEASE_MS) {\n throw new ValidationError(\n `${op}: leaseUntil is more than 14 days away; the longest lease is ${MAX_LEASE_MS} ms. Take a new lease when a job outlasts it`,\n );\n }\n return until;\n }\n\n /**\n * End this handle's lease now, so a load's collection may take its generation. Idempotent: a handle with no lease, or\n * one already released, does nothing and makes no request. Every read of the handle after it throws\n * {@link LeaseExpiredError} (reason `'released'`), including one already under way at its next chunk. A lease that has\n * ended by its own time needs no release: this then makes no request either, and the registry row's entry is pruned\n * by a later write. Otherwise it is one registry read and one write; a failure of either is thrown as the registry's own\n * typed error, and the entry then holds until its time ends, `release()` being safe to call again.\n */\n async release(): Promise<void> {\n const hold = this.leaseHold;\n if (hold === undefined) return;\n hold.released = true;\n if (hold.done) return;\n if (this.clock.now() >= hold.until + LEASE_SKEW_MS) {\n hold.done = true;\n return;\n }\n await hold.release();\n hold.done = true;\n }\n\n /**\n * The error a read of this handle must throw, or `undefined` when it holds no lease or the lease is live. One property\n * read on a handle with no lease. A read past a lease throws; it never reads empty.\n */\n private leaseError(): LeaseExpiredError | undefined {\n const hold = this.leaseHold;\n if (hold === undefined) return undefined;\n const name = this.ref.namespace\n ? `${this.ref.namespace}/${this.ref.segment}`\n : this.ref.segment;\n if (hold.released) {\n return new LeaseExpiredError(\n `the lease on segment \"${name}\" was released`,\n hold.until,\n 'released',\n );\n }\n if (this.clock.now() >= hold.until) {\n return new LeaseExpiredError(\n `the lease on segment \"${name}\" ended; a read of a handle past its lease throws, never reads empty`,\n hold.until,\n 'expired',\n );\n }\n return undefined;\n }\n\n /**\n * Refuse with a {@link ValidationError} any of `handles` that this store did not make: a value that is not a segment,\n * a segment of another store (even one over the same backend) and a segment of another installed copy of the\n * package. It runs first in every combine, before the lease check reads the handles and before any request.\n */\n private assertSegments(verb: string, role: HandleRole, handles: readonly unknown[]): void {\n for (const h of handles) assertOneStore(verb, role, h, this.origin);\n }\n\n /**\n * Throw the first lease error among `handles`: this handle and every operand and exclude of a call. It runs before\n * the engine, so no operand, exclude or cached reader can answer past a lease.\n */\n private assertLeases(handles: readonly Segment[]): void {\n for (const h of handles) {\n const err = h.leaseError();\n if (err !== undefined) throw err;\n }\n }\n\n /** Throw this handle's lease error, if it has one. The calls that return a value instead of throwing use {@link leaseError}. */\n private assertLease(): void {\n const err = this.leaseError();\n if (err !== undefined) throw err;\n }\n\n /**\n * Reopen a generation a pin named earlier, as a pinned handle like the one {@link Segment.pin} returns, held at\n * `at.generation` instead of the current one. Pass what the earlier pin recorded, `{ generation, fingerprint }`\n * from its {@link Segment.pinnedAt}. A generation number alone is not an identity, since a purged and re-created\n * name starts again at 0, so the fingerprint is required: a bare number, a malformed fingerprint or a key other\n * than `generation`, `fingerprint` and `version` is a {@link ValidationError}. Identify a pin by its `generation` and\n * `fingerprint`: the handle's `pinnedAt.version` can differ from the earlier pin's.\n *\n * Throws {@link NotFoundError} when the generation is gone (collected, purged, or on a destroyed segment),\n * is above the row's pointer, or is another object than the fingerprint names, and never reads empty. A rollback\n * deletes nothing, so once a later load moves the pointer past a generation it rolled back from, that one can be\n * reopened while its object is stored. Nothing keeps a generation alive unless you lease it: a later load's\n * collection can delete it, which is sized by `keep` on every writer, or held by `options.leaseUntil` (see\n * {@link PinOptions} and {@link Segment.pin}). A leased `pinAt` writes the lease before it verifies the object, and\n * releases it if the verify fails; for a generation below the pointer, a collector that read the row before the lease\n * landed can still delete the generation inside its own round trip, and the handle then fails with `NotFoundError`\n * like any swept pin. A leased handle is checked at every read site as a leased `pin()` is. With a registry it costs one row read and one tail read,\n * and a leased `pinAt` one conditional write to the row besides; the handle\n * then reads as one from `pin()` does, including its failure on a chunk it has not cached once the generation is\n * swept. Works for an encrypted segment. The first argument is an object so that fields can join it later; the lease\n * is in `options`, the second.\n *\n * It takes what {@link Segment.pinnedAt} holds: once `generation` is not `null`, the record passes as it is (its\n * `version` is not read), and `{ generation, fingerprint }` does as well. A pin of a segment that had no generation\n * has nothing to reopen and throws {@link ValidationError}.\n */\n async pinAt(at: PinAt, options?: PinOptions): Promise<Segment> {\n // A leased handle past its lease pins nothing, as for `pin()`.\n this.assertLease();\n // A pin's `pinnedAt` is handed back whole, so its `version` is a key `pinAt` knows: the fingerprint is what\n // identifies the object, and the version is not read.\n const { generation, fingerprint, version } = (at ?? {}) as Partial<PinAt> & {\n version?: unknown;\n };\n // Own enumerable string keys only: a symbol, non-enumerable or inherited key is not seen.\n const unknown =\n typeof at === 'object' && at !== null\n ? Object.keys(at).filter((k) => !['generation', 'fingerprint', 'version'].includes(k))\n : [];\n if (unknown.length > 0) {\n throw new ValidationError(\n `pinAt: unknown option${unknown.length > 1 ? 's' : ''} ${unknown.map((k) => `\"${k}\"`).join(', ')}; ` +\n \"pinAt takes { generation, fingerprint } and a pin's `version`, which it does not read\",\n );\n }\n if ((generation as unknown) === null) {\n throw new ValidationError(\n 'pinAt: the pin named no generation (the segment had none when it was pinned), so there is nothing to reopen',\n );\n }\n if (version !== undefined && typeof version !== 'string') {\n throw new ValidationError(\n 'pinAt: `version`, when given, is the string a pin recorded in its pinnedAt; pinAt does not read it, so leave it out if you have none',\n );\n }\n if (\n typeof generation !== 'number' ||\n !Number.isSafeInteger(generation) ||\n generation < 0 ||\n typeof fingerprint !== 'string' ||\n !/^\\d+:\\d+$/.test(fingerprint)\n ) {\n throw new ValidationError(\n 'pinAt: pass { generation, fingerprint } as recorded by an earlier pin (its pinnedAt); a generation number ' +\n 'without the fingerprint of its object does not identify it',\n );\n }\n // `at` takes `{ generation, fingerprint }` and a pin's `version`; the lease goes in the options, the second argument.\n const leaseUntil = this.leaseUntilOf('pinAt', options);\n return this.pinned(this.ref, leaseUntil, { generation, fingerprint });\n }\n\n /**\n * An opaque string that names this handle's segment, namespace included: two handles of one segment have the\n * same key, a live handle and its pins among them. Use it as a `Map` key or a log field when you track handles\n * and have not kept the name you made them with. The format is not specified and is not a storage key, so\n * compare keys, never parse one.\n */\n key(): string {\n return segmentKey(this.ref);\n }\n\n /**\n * Refuse an `*Into` that cannot run, before any request, in this order: anything that is not a segment or is a\n * segment of another store, an empty operand list for `intersectInto`, and a `dest` that is also a source (all\n * {@link ValidationError}); then a handle (this one, `dest`, an operand or an exclude) whose lease has ended or was\n * released ({@link LeaseExpiredError}). A call with both a lapsed lease and one of the first three refusals throws the\n * first. Called by the three `*Into` verbs only.\n *\n * The verbs are `async` so this surfaces as a **rejected promise**, like every other validation in the facade \u2014\n * a synchronous throw out of a promise-returning method escapes a caller who attached `.catch()` instead of\n * awaiting.\n */\n private assertIntoHandles(\n verb: `${CombineVerb}Into`,\n dest: Segment,\n operands: readonly Segment[],\n excludes: readonly Segment[],\n ): void {\n this.assertSegments(verb, 'the destination', [dest]);\n this.assertSegments(verb, verb === 'andNotInto' ? 'an exclude' : 'an operand', operands);\n this.assertSegments(verb, 'an exclude', excludes);\n const base = verb.slice(0, -'Into'.length) as CombineVerb;\n if (base === 'intersect' && operands.length === 0) refuseNoOperands('intersectInto');\n this.refuseSourceDestination(verb, dest, operands, excludes);\n this.assertLeases([this, dest, ...operands, ...excludes]);\n }\n\n /**\n * Refuse an `*Into` whose destination is also one of its sources (this segment, an operand or an exclude, by the key\n * a handle gives, so a pin of the source and a ref spelled with the default namespace count), before any request, as\n * `materializeMany` refuses it. The combine would read the destination at the generation this store last resolved,\n * up to `cache.genTtlMs` old, while the publish is fenced on the row as it stands: another process's newer load of\n * the destination would be overwritten by a result built from the one before it, with no conflict to report.\n */\n private refuseSourceDestination(\n verb: `${CombineVerb}Into`,\n dest: Segment,\n operands: readonly Segment[],\n excludes: readonly Segment[],\n ): void {\n const key = dest.key();\n const role =\n this.key() === key\n ? 'this segment'\n : operands.some((o) => o.key() === key)\n ? verb === 'andNotInto'\n ? 'an exclude'\n : 'an operand'\n : excludes.some((o) => o.key() === key)\n ? 'an exclude'\n : undefined;\n if (role === undefined) return;\n const { namespace, segment } = dest.ref;\n const named = namespace === undefined ? segment : `${namespace}/${segment}`;\n throw new ValidationError(\n `${verb}: the destination \"${named}\" is also ${role} of the call, and a call that reads a segment while it ` +\n 'publishes to it can replace a newer load of it with a result built from an older one, with no conflict ' +\n 'reported. This release has no fenced in-place update: combine into a new segment and point readers at it',\n );\n }\n\n /** `result` as is, or, when a handle of the call holds a lease, checking that lease each time it reads a chunk. */\n private guarded<T>(out: CombineOutput<T>, handles: readonly Segment[], result: T): T {\n return handles.some((h) => h.leaseHold !== undefined)\n ? out.guard(result, () => this.assertLeases(handles))\n : result;\n }\n\n /**\n * Time an op with the injected clock and emit an `op` metric on completion (success or throw). With no sink wired it\n * reads no clock and emits nothing, but a call still passes through this async frame; `has()` and `count()` return the\n * engine's promise directly instead.\n */\n private async timed<T>(name: MetricOpName, fn: () => Promise<T>): Promise<T> {\n if (!this.metricsOn) return fn();\n const startedAt = this.clock.now();\n try {\n return await fn();\n } finally {\n this.metrics.onEvent({ kind: 'op', name, ms: Math.max(0, this.clock.now() - startedAt) });\n }\n }\n\n /**\n * Membership: one chunk. A cold resolution of the segment is one registry read and a warm one none; then a cached\n * chunk answers with no request, and an uncached one is one range read, after a tail read when no reader of the\n * generation is open, unless that tail carried the chunk. Throws {@link ValidationError} on a bad id.\n */\n has(id: number): Promise<boolean> {\n const lease = this.leaseError();\n if (lease !== undefined) return Promise.reject(lease);\n if (!this.metricsOn) return this.engine.has(this.ref, id);\n return this.timed('has', () => this.engine.has(this.ref, id));\n }\n /**\n * Cardinality of the generation this handle reads: **one registry read when cold, none when warm, and no read of the\n * object**, with **zero payload reads**. The registry row records the id count of the generation it names, written\n * by the write that made it current, and a count answers from that. A row with no summary it can use (one written\n * without it, as a registry of your own may, one that names another generation, a sealed one that does not open)\n * sends the count to the `.crbm` index, summed with a tail read of the object. A segment whose pointer names a missing object (a torn\n * restore) still counts the row's number, while a read of the object throws; `checkConsistency` is what finds it.\n *\n * What this trusts: the row's summary, or the index's sum, and no payload is decoded to confirm it. The summary is\n * used only for the generation it names, on an active row, and a sealed one only if it opens under the segment's\n * key; it is held against the object whenever the object is opened anyway (a `has`, an `iterate`, a combine, a\n * `pin()`), at no extra request, and a disagreement stops this store using it, and fails nothing. It is not\n * confirmed on the cold path, so a party who can write the registry row can make a count wrong. The index is checked for internal consistency when the object is opened (each key in\n * range and ascending, each cardinality in `1..65536`, each payload inside the payload region, and, on an\n * unencrypted object, the footer's chunk count and total agreeing with the index), and a corrupt index that is\n * still internally consistent yields a wrong count. `iterate()` and the combines decode the payloads, whose\n * structure is checked.\n */\n count(): Promise<number> {\n const lease = this.leaseError();\n if (lease !== undefined) return Promise.reject(lease);\n if (!this.metricsOn) return this.engine.count(this.ref);\n return this.timed('count', () => this.engine.count(this.ref));\n }\n /**\n * What the generation this handle reads is, from one resolution: its number, its id count, the metadata it was\n * loaded with (absent when it has none), and `sizeBytes`, its object's bytes in storage. All four come from the\n * registry row when it has a summary this store can use, as `count()`'s do: the summary records the object's\n * fingerprint, its size with its checksum. That is **one registry read when cold, none when warm, and no read of the\n * object**. With no summary it can use, they come from the generation's object, opened once: its footer and index,\n * with no payload read, which is a tail read of the object more when cold (and a range read for an index longer than\n * the tail) and keeps the generation in the reader cache as a read does. On a pinned handle it answers for the\n * generation it pinned, from the pinned object. A segment with no generation answers\n * `{ generation: null, cardinality: 0, sizeBytes: null }`, and a store whose source cannot report a size answers\n * `sizeBytes: null`. A pointer that names a missing object (a torn restore) still answers from the row's summary, as\n * `count()` does, while a read of the object throws `NotFoundError`; with no summary to use, `stat()` throws it too.\n * `checkConsistency` is what finds such a row.\n *\n * Trust is as for `count()`: what the row's summary says is believed until the object is next opened. Every open of\n * the generation holds the object to the fingerprint the summary records, so another object under the number is\n * refused when it is opened, and holds its count against the summary's; a disagreement in count makes this process\n * stop using that summary, so `stat()` then answers from the object, whose index is checked for internal consistency\n * and whose count is the index's sum. A reader already open is not checked again until the row changes, it is\n * evicted or it is invalidated.\n *\n * `sizeBytes` is what `groundedReport` in `@cloudbitmaps/tools` prices storage from.\n *\n * ```ts\n * const { generation, cardinality, metadata, sizeBytes } = await store.segment('active-30d').stat();\n * ```\n */\n async stat(): Promise<SegmentStat> {\n this.assertLease();\n return this.engine.stat(this.ref);\n }\n /**\n * Every id, ascending, streamed one chunk at a time. Pass a range to read part of the segment: the ids in\n * `(after, through]`, fetching only the chunks the range overlaps. The per-op budget is charged for every chunk in\n * the range, so give a page `through` as well as `after`. On a pinned handle it reads the pinned generation, as a\n * full read does.\n *\n * ```ts\n * // Keyset paging: each page resumes where the one before ended, and stops at its window's end.\n * for await (const id of seg.iterate({ after: previousEnd, through: windowEnd })) await send(id);\n * ```\n *\n * Each bound is optional and an integer in `0..4294967295`; a bad one throws {@link ValidationError} when the\n * stream is first read. `after >= through` is an empty range, which reads nothing.\n */\n iterate(options?: Pick<CombineOptions, 'after' | 'through'>): IdStream {\n const lease = this.leaseError();\n if (lease !== undefined) return failing(lease);\n const bad = optionsError(options, 'iterate', CALL_KEYS.range, [], MISPLACED.range);\n if (bad !== undefined) return failing(bad);\n // Neither bound set is no range at all, which the engine reads on its full-read path.\n const range = options == null ? undefined : rangeOf(options);\n const none = range === undefined || (range.after === undefined && range.through === undefined);\n const { engine, ref } = this;\n const bounds = none ? undefined : range;\n const stream = withBatches(engine.iterate(ref, bounds), () =>\n engine.iterateBatches(ref, bounds),\n );\n return readsFrom(\n this.leaseHold === undefined ? stream : guardIds(stream, () => this.assertLease()),\n this.origin,\n [this.key()],\n );\n }\n\n /**\n * **Pinned handles only.** The ids at 1-based ranks `n`, `2n`, `3n` \u2026, counted over the ids in `(after, through]`\n * when a range is given, ascending: `everyNth(1000)` yields the 1,000th id, then the 2,000th, and so on. A last\n * partial window yields nothing, so a caller cutting a send into windows of `n` appends its own final end.\n *\n * It places each boundary from the per-chunk counts the pin already holds and reads only the chunks that hold one,\n * each once however many boundaries it holds, so it reads at most one chunk per boundary and never more chunks\n * than the object has. A range with `after` inside a chunk reads that chunk too, to count the ids at or below\n * `after`, even when fewer than `n` ids remain above it; when the chunks in range hold fewer than `n` ids in all,\n * nothing is fetched. `through` stops the read and no chunk past it is read, though a `through` inside a chunk may read that last chunk and\n * yield nothing from it. The reads and the read-ahead window are\n * those of {@link Segment.iterate}, and the per-op budget is charged before the first fetch, with an upper bound on\n * the chunks the read can take. A pinned read after the generation is swept throws {@link NotFoundError}.\n *\n * The ranks come from the index's counts, which are trusted as {@link Segment.count} trusts them. A chunk that is\n * read must hold the number of ids its index says, or the read throws {@link IntegrityError}; a chunk that is not\n * read is not checked, so an index that is wrong about one, and, on an unencrypted object, still adds up to the footer's\n * total, moves the ids after it to the wrong ranks. An encrypted object's index is authenticated and bound to the\n * object, so a wrong count there needs the key.\n *\n * A live handle is refused with {@link UnsupportedError} at the first read, because its counts and its chunks could\n * come from two generations and name the wrong id. `n` that is not a positive integer throws\n * {@link ValidationError} at the first read, as does a bad bound.\n *\n * ```ts\n * const audience = await store.segment('audience').pin();\n * const ends: number[] = [];\n * for await (const id of audience.everyNth(1_000)) ends.push(id); // the end of each window of 1,000\n * ```\n */\n everyNth(n: number, options?: Pick<CombineOptions, 'after' | 'through'>): IdIterator {\n // The lease first: a leased handle past its lease throws, never reads empty.\n const lease = this.leaseError();\n if (lease !== undefined) return refusing(lease)();\n const bad = optionsError(options, 'everyNth', CALL_KEYS.range, [], MISPLACED.range);\n if (bad !== undefined) return refusing(bad)();\n if (this.pinnedAt === undefined) {\n return refusing(\n new UnsupportedError(\n 'everyNth needs a pinned handle: a live handle can place a rank by one generation ' +\n 'and read it from another. Call `pin()` first.',\n ),\n )();\n }\n const stream = this.engine.everyNth(\n this.ref,\n n,\n options == null ? undefined : rangeOf(options),\n );\n // A stream with no `.batches()`: guarded before its first pull, so a stream built live and pulled after the lease\n // ended throws even when no rank falls in its range, and at each chunk after that.\n return readsFrom(\n this.leaseHold === undefined ? stream : guardIdIterable(stream, () => this.assertLease()),\n this.origin,\n [this.key()],\n );\n }\n\n /**\n * The options a combine hands the engine, read once, when it is called ({@link readOptions}), with the `exclude`\n * it was given ({@link excludesOf}) and mapped down to the plain refs\n * `core` takes. A method rather than a module function because `ref` is class-private \u2014 the encapsulation is\n * worth more than the free function.\n *\n * Each field is named rather than copied with a rest spread: a rest copy takes only own enumerable properties, so\n * a bound held in a getter or inherited from a prototype was dropped, and the read silently widened to the whole\n * segment.\n */\n private refsIn(\n options: CombineOptions | null | undefined,\n exclude: readonly Segment[],\n ): (ReadOptions & { exclude?: SegmentRef[] }) | undefined {\n if (options == null) return undefined;\n return {\n ...readOptions(options),\n exclude: exclude.length > 0 ? exclude.map((o) => o.ref) : undefined,\n };\n }\n\n /**\n * The handles in `options.exclude`, read once so a getter sees one call. With none this is one property read and\n * a shared empty list; otherwise it is the caller's own array, so the common case allocates nothing.\n */\n private excludesOf(options: CombineOptions | null | undefined): readonly Segment[] {\n const exclude = options?.exclude;\n if (exclude == null) return NO_SEGMENTS;\n return segmentList(exclude, '`exclude`').length === 0 ? NO_SEGMENTS : exclude;\n }\n\n /**\n * Chunk-skipping intersection: stream the ids in **this** segment AND every segment in `others`, ascending.\n * Fetches only the Storage chunks present in *all* operands (a key absent from any operand contributes nothing\n * and is never downloaded), reading each operand's as coalesced ranges under a bounded in-flight window \u2014 so the Storage\n * footprint stays small (Lambda-friendly) regardless of segment size. Pass `concurrency` to tune that window (the range\n * requests held ahead per operand: a positive integer, 32 by default).\n * AND is commutative, so `a.intersect([b])` and `b.intersect([a])` yield the same ids. Pass `budget` to\n * override the store's per-op denial-of-wallet budget for this call (or `false` to lift it).\n *\n * Of {@link CombineOptions} it takes the range, `concurrency`, `budget`, `allowAbsentOperands` and `exclude`; a write\n * option (`audit`, `allowEmpty`, `guard`, `metadata`, `keep`) fails the stream with {@link ValidationError} when it is\n * first read, before any request. So does an empty `others`: an intersection over nothing has no meaning, and\n * to read every id of one segment, use {@link iterate}. (`union` and `andNot` read an empty list as `this`.)\n */\n intersect(others: Segment[], options?: CombineOptions): IdStream {\n const bad = optionsError(\n options,\n 'intersect',\n CALL_KEYS.combine,\n ['allowAbsentOperands'],\n MISPLACED.combine,\n );\n if (bad !== undefined) return failing(bad);\n return this.combineAs(AS_IDS, 'intersect', others, options ?? undefined);\n }\n\n /**\n * Materialize `this \u2229 others\u2026` (minus `exclude`) as a **new generation of `dest`** \u2014 `dest`'s previous contents\n * are superseded, not added to. Streaming + bounded-memory; the result is one immutable object published\n * as a load is (the pointer advances to it, fenced on the row), so readers of `dest` see either the old generation\n * or the new one, never a partial. Needs the\n * store built with a backend (throws {@link UnsupportedError} otherwise).\n *\n * **An empty result does NOT overwrite a non-empty destination.** A combine that comes out empty is far more\n * often a mistake upstream \u2014 a typo'd operand, an `exclude` that swallowed everything, an operand that has\n * not loaded yet \u2014 than an intent, and once it publishes it is indistinguishable from a correct run. So the\n * write is **refused and reported**: `published: false`, `reason: 'empty'`, and `dest` keeps what it had.\n * Pass `allowEmpty: true` when emptying the destination is the point.\n *\n * `guard` adds the same plausibility bounds `load()` takes \u2014 `minCardinality`, `minRetained` and `maxGrowth` \u2014 judged\n * against what `dest` held before. A refusal is **reported, not thrown**, exactly as on `load()`; branch on\n * `published`. A lost race is the one outcome that still throws ({@link WriteConflictError}), because a\n * materialisation that silently did not take effect is the one thing a caller cannot detect on its own.\n *\n * A call involving a handle whose lease has ended, or anything that is not a segment, is refused before any of this.\n * So is a `dest` that is also `this`, an operand or an exclude (the same segment by name and namespace, however the\n * handle was made), and, for `intersectInto` alone, an empty `others` (`unionInto` and `andNotInto` publish `this` for an\n * empty list): each throws {@link ValidationError} before any request. A destination that\n * is also a source would publish a result built from the generation this store last resolved over a newer load by\n * another process, with no conflict to report. This release has no fenced in-place update: write the result into a\n * new segment and point readers at it; a single writer that knows nothing else writes the segment may load the result\n * back, unfenced. To copy `src` into `dest`, call\n * `materializeMany({ operands: { src }, outputs: [{ dest, expr: { or: ['src'] } }], keep })`, which reads each chunk\n * once, at one instant.\n * It takes every field of {@link CombineOptions}, as `unionInto` does.\n */\n async intersectInto(\n dest: Segment,\n others: Segment[],\n options?: CombineOptions,\n ): Promise<MaterializeResult> {\n checkOptions(options, 'intersectInto', CALL_KEYS.into, ['allowEmpty', 'allowAbsentOperands']);\n return this.combineInto('intersectInto', dest, others, options);\n }\n\n /**\n * `this \u222A others\u2026`, minus `options.exclude` \u2014 streamed ascending.\n *\n * **The one composite read with no chunk-skipping,** and that is inherent to union rather than a limitation\n * here: an id in *any* operand belongs to the result, so every chunk of every operand must be read.\n * `intersect` prunes any key missing from any operand; union has nothing to prune. It is charged against the\n * same per-op budget, so a wide union is refused rather than quietly billed \u2014 pass `budget` to raise it\n * deliberately. If you find yourself unioning the same segments on every read, materializing the combined\n * segment once (`unionInto`, or a load) is the cheaper shape. It takes the options {@link intersect} takes, and an\n * empty `others` reads `this` itself.\n */\n union(others: Segment[], options?: CombineOptions): IdStream {\n const bad = optionsError(\n options,\n 'union',\n CALL_KEYS.combine,\n ['allowAbsentOperands'],\n MISPLACED.combine,\n );\n if (bad !== undefined) return failing(bad);\n return this.combineAs(AS_IDS, 'union', others, options ?? undefined);\n }\n\n /** Materialize `this \u222A others\u2026` (minus `exclude`) as a **new generation of `dest`** \u2014 see {@link intersectInto}. */\n async unionInto(\n dest: Segment,\n others: Segment[],\n options?: CombineOptions,\n ): Promise<MaterializeResult> {\n checkOptions(options, 'unionInto', CALL_KEYS.into, ['allowEmpty', 'allowAbsentOperands']);\n return this.combineInto('unionInto', dest, others, options);\n }\n\n /**\n * `this \\ (excludes\u2026)` \u2014 streamed ascending. Suppression on its own.\n *\n * Reads every chunk of `this` (any of them may survive the subtraction) but each exclude **only where it\n * overlaps this segment**, so the cost tracks the segment being filtered rather than the size of the\n * suppression list: at most one read per surviving key of `this`, so subtracting a 61,000-chunk global\n * opt-out list from a 40-chunk audience costs at most 40 reads, not 61,000.\n *\n * To filter the *result of an intersection*, do not chain \u2014 pass `exclude` to {@link intersect} instead, so\n * the suppression folds into the same pass rather than materializing an intermediate segment first.\n *\n * It takes the options {@link intersect} takes but `exclude`, since `excludes` is its subtraction: `exclude` or a write\n * option fails the stream with {@link ValidationError} when it is first read, before any request.\n */\n andNot(excludes: Segment[], options?: CombineOptions): IdStream {\n const bad = optionsError(\n options,\n 'andNot',\n CALL_KEYS.andNot,\n ['allowAbsentOperands'],\n MISPLACED.andNot,\n );\n if (bad !== undefined) return failing(bad);\n return this.combineAs(AS_IDS, 'andNot', excludes, options ?? undefined);\n }\n\n /**\n * Materialize `this \\ (excludes\u2026)` as a **new generation of `dest`** \u2014 see {@link intersectInto}. It takes every field\n * of {@link CombineOptions} but `exclude`, since `excludes` is its subtraction: `exclude` is refused with\n * {@link ValidationError} before any request.\n */\n async andNotInto(\n dest: Segment,\n excludes: Segment[],\n options?: CombineOptions,\n ): Promise<MaterializeResult> {\n checkOptions(\n options,\n 'andNotInto',\n CALL_KEYS.andNotInto,\n ['allowEmpty', 'allowAbsentOperands'],\n MISPLACED.andNotInto,\n );\n return this.combineInto('andNotInto', dest, excludes, options);\n }\n /**\n * The one body of the three combines, read as ids or as chunks. `operands` is `others` for `intersect` and\n * `union`, and `excludes` for `andNot`, which takes no `exclude` option.\n */\n private combineAs<T>(\n out: CombineOutput<T>,\n verb: CombineVerb,\n operands: Segment[],\n options?: CombineOptions,\n ): T {\n // Order of the checks: the lists are arrays, every handle is a segment, then no handle's lease has ended, all before\n // the engine is asked for anything, so a handle past its lease throws `LeaseExpiredError` and never reads empty.\n let exclude: readonly Segment[];\n let handles: readonly Segment[];\n try {\n exclude = verb === 'andNot' ? NO_SEGMENTS : this.excludesOf(options);\n const others = segmentList(operands, operandsLabel(verb));\n if (verb === 'intersect' && others.length === 0) refuseNoOperands('intersect');\n handles = [this, ...others, ...exclude];\n this.assertSegments(verb, verb === 'andNot' ? 'an exclude' : 'an operand', others);\n this.assertSegments(verb, 'an exclude', exclude);\n this.assertLeases(handles);\n } catch (err) {\n return out.failing(err);\n }\n let engine: SegmentEngine;\n try {\n engine = this.combineEngine([this, ...operands, ...exclude]) ?? this.engine;\n } catch (err) {\n return out.failing(err);\n }\n // A stream of ids remembers what it reads, for `store.load` ({@link STREAM_SOURCES}); a stream of chunks is not one.\n const keys = handles.map((h) => h.key());\n const known = (result: T): T =>\n (out as unknown) === AS_IDS ? (readsFrom(result as object, this.origin, keys) as T) : result;\n if (verb === 'andNot') {\n const refs = operands.map((o) => o.ref);\n const opts = options == null ? undefined : readOptions(options);\n return known(this.guarded(out, handles, out.andNot(engine, this.ref, refs, opts)));\n }\n const refs = [this.ref, ...operands.map((o) => o.ref)];\n const opts = this.refsIn(options, exclude);\n return known(\n this.guarded(\n out,\n handles,\n verb === 'union' ? out.union(engine, refs, opts) : out.intersect(engine, refs, opts),\n ),\n );\n }\n\n /** The one body of the three `*Into` verbs, after each has checked its own options. */\n private combineInto(\n name: `${CombineVerb}Into`,\n dest: Segment,\n operands: Segment[],\n options: CombineOptions | undefined,\n ): Promise<MaterializeResult> {\n const verb = name.slice(0, -'Into'.length) as CombineVerb;\n const listed = segmentList(\n operands,\n verb === 'andNot' ? `${name}: \\`excludes\\`` : `${name}: \\`others\\``,\n );\n const excludes = verb === 'andNot' ? NO_SEGMENTS : this.excludesOf(options);\n const all = excludes.length > 0 ? [...listed, ...excludes] : listed;\n this.assertIntoHandles(name, dest, listed, excludes);\n // Refused here, before `materialize` reads anything of `dest`, rather than when the load reads the combine: a\n // broken destination would otherwise answer first, and hide the refusal behind its own error.\n this.combineEngine([this, ...all]);\n return this.timed(name, () =>\n this.materialize(\n dest.ref,\n new CombineChunks(this.combineAs(AS_CHUNKS, verb, operands, options)),\n name,\n options,\n ),\n );\n }\n}\n\n// ---------------------------------------------------------------------------------------------------\n// What `@cloudbitmaps/roaring` re-exports from `@cloudbitmaps/core` and `@cloudbitmaps/core/node`, by name: the\n// types the store's signatures name, the backends, the errors and their classifier, and the helpers an\n// application calls. An application installs this package and imports from it alone. Nothing else of core's is\n// re-exported: its main entry is internal. The driver\n// contracts the store's signatures stop at (`IStorageDriver`, `IRegistryDriver`, `StorageBackend`,\n// `StorageChunkSource`, `IKeystore` and the registry's record types) are exported by `@cloudbitmaps/core/driver-kit`,\n// their one home, and not here: an application that has to name one imports it from there, or derives it\n// (`CloudRoaringOptions['storage']`, `NonNullable<EncryptionOptions['keystore']>`). A name added here is a public name\n// of this package, so add one on purpose: `tests/docs/api-reference-sync.test.ts` fails until the API reference lists\n// it.\n// ---------------------------------------------------------------------------------------------------\n// The backends and the keystore that need a Node builtin, which core exports from `@cloudbitmaps/core/node`.\nexport { MemoryStorage, LocalFsStorage, InProcessKeystore } from '@cloudbitmaps/core/node';\nexport type {\n InProcessKeystoreOptions,\n LocalFsStorageOptions,\n MemoryStorageOptions,\n} from '@cloudbitmaps/core/node';\n// The public bitmap class, also the one door that decodes portable bytes you hold. It is defined in `./bitmap`.\nexport { RoaringBitmap } from './bitmap';\nexport type { RoaringBitmapDeserializeOptions } from './bitmap';\nexport {\n // The retention policy helpers\n excludingReservedRows,\n readRetentionPolicy,\n // Errors and their copy-safe classifier\n CloudRoaringError,\n ValidationError,\n WriteConflictError,\n IntegrityError,\n NotFoundError,\n UnsupportedError,\n CapabilityError,\n TransientError,\n KeyUnavailableError,\n BudgetExceededError,\n LeaseExpiredError,\n LeaseLimitError,\n StaleOperandError,\n errorKind,\n // Metrics and audit\n CountingMetricsSink,\n RecordingAuditSink,\n} from '@cloudbitmaps/core';\nexport type {\n AuditEvent,\n Budget,\n BudgetOption,\n Clock,\n ConsistencyErrorEntry,\n ConsistencyIssue,\n ConsistencyReport,\n DestroyResult,\n DropResult,\n Entropy,\n EraseDeps,\n ErrorKind,\n ExportFailure,\n ExportFormat,\n ExportManifest,\n ExportOptions,\n ExportSink,\n ExportSkipped,\n ExportWriter,\n ExportedSegment,\n Expr,\n GenerationEntry,\n GenerationMetadata,\n IAuditSink,\n IMetricsSink,\n LoadGuard,\n LoadInput,\n LoadOptions,\n LoadRefusal,\n LoadResult,\n MaterializeManyFeedRecord,\n MaterializeManyOperandStats,\n MaterializeManyOutputStats,\n MaterializeManyStats,\n MetricEvent,\n MetricOpName,\n MetricsSnapshot,\n PinnedAt,\n PortableBitmap,\n PreflightCheck,\n PreflightResult,\n RetentionPolicy,\n RetireEntry,\n RetireExpiredOptions,\n RetireExpiredResult,\n RetryPolicy,\n Rng,\n RollbackResult,\n SegmentInfo,\n SegmentRef,\n SetRetentionResult,\n} from '@cloudbitmaps/core';\n", "/**\n * A storage driver that charges every **generation open** to a per-op budget, for `eraseSubject`.\n *\n * The budget counts fan-out in units of one backend read. `eraseSubject`'s scan charges one unit per registered\n * segment, but a segment whose current generation lacks the id is searched anyway: every other generation in its\n * bucket is opened, one tail read each, and with the keep-everything default of the `*Into` verbs that is one per\n * generation the segment ever had. Those opens are the work the scan's own count leaves out. They are counted here,\n * at the storage port where they happen, so an open added to the erasure later is charged without anyone\n * remembering to charge it, and no option of the public erasure call had to grow.\n *\n * Two opens are never charged, because the segment's unit already pays for them: the generation the row named when\n * the scan listed it, which every erasure must read to decide membership, and an object this call wrote itself,\n * which it reads back to verify. Every other generation is charged once, at its first open: a later open of the same\n * number in the same call is paid for by that unit. The look for a holder left once the call has deleted opens again\n * each generation it found clean, and an object whose open failed has its footer read on its own; neither costs a unit\n * more. A refusal here comes from a read. Most of an erasure's reads that can be refused come before its deletes; two\n * kinds come after one: the look for a holder left, when it opens a generation the call never opened before, and the\n * zero-byte read of a generation the call deleted that the row then names. A refusal of either is thrown in place of\n * the call's answer, so the call reports the budget, not what it deleted.\n */\nimport type {\n GenKey,\n IStorageDriver,\n SegmentRef,\n StorageDeleteOptions,\n} from '@cloudbitmaps/core/driver-kit';\n\nexport class OpenChargingStorage implements IStorageDriver {\n /** Generations an open of costs nothing more: the scan's current one, this call's writes, and each one charged. */\n private readonly free = new Set<number>();\n\n /**\n * @param inner the driver the erasure would otherwise use\n * @param current the generation the segment's row named when it was listed, or `null` when it named none\n * @param charge called once per charged open; it throws to refuse\n */\n constructor(\n private readonly inner: IStorageDriver,\n current: number | null,\n private readonly charge: () => void,\n ) {\n if (current !== null) this.free.add(current);\n }\n\n capabilities(): ReturnType<IStorageDriver['capabilities']> {\n return this.inner.capabilities();\n }\n\n async putImmutable(\n key: GenKey,\n write: Parameters<IStorageDriver['putImmutable']>[1],\n ): ReturnType<IStorageDriver['putImmutable']> {\n const written = await this.inner.putImmutable(key, write);\n this.free.add(key.generation);\n return written;\n }\n\n getRange(key: GenKey, offset: number, length: number): Promise<Uint8Array> {\n return this.inner.getRange(key, offset, length);\n }\n\n /**\n * One `getTail` is one open: a reader takes the footer and the index from it, and reads chunks with `getRange`. A\n * generation is charged at its first open only.\n */\n async getTail(key: GenKey, maxBytes: number): ReturnType<IStorageDriver['getTail']> {\n if (!this.free.has(key.generation)) {\n this.charge();\n this.free.add(key.generation);\n }\n return this.inner.getTail(key, maxBytes);\n }\n\n /** Handed through whole: the erasure's delete of a holder is conditioned on the object it searched. */\n delete(key: GenKey, options?: StorageDeleteOptions): Promise<void> {\n return this.inner.delete(key, options);\n }\n\n list(ref: SegmentRef): AsyncIterable<GenKey> {\n return this.inner.list(ref);\n }\n}\n", "/**\n * The facade's refusal of the namespace the library keeps for its own rows.\n *\n * `cbm.due.` is where the due index stores its pointers, and every fleet-wide scan skips a row there as\n * bookkeeping, so a segment in it would be invisible to an erasure, a consistency check, an export and a retention\n * sweep. `@cloudbitmaps/core` refuses the prefix in every call that takes a ref or a `namespace` option; this is a\n * copy of that one constant, for the checks the facade makes itself before anything reaches core (`segment()`,\n * `invalidate()` and the scope of the two subject scans, which read the registry directly). A test holds the copy\n * equal to core's, so the two cannot drift.\n *\n * Internal: not exported from the package entry.\n */\nimport { ValidationError } from '@cloudbitmaps/core';\n\nexport const RESERVED_NAMESPACE_PREFIX = 'cbm.due.';\n\n/** Throw `ValidationError` for a namespace in the reserved prefix; `undefined` and every look-alike pass. */\nexport function refuseReservedNamespace(namespace: string | undefined): void {\n if (namespace !== undefined && namespace.startsWith(RESERVED_NAMESPACE_PREFIX)) {\n throw new ValidationError(\n `namespace \"${namespace}\" is reserved: names starting with \"${RESERVED_NAMESPACE_PREFIX}\" hold the ` +\n `library's own bookkeeping rows, which every fleet-wide scan skips, so a segment there would be ` +\n `invisible to an erasure, a consistency check, an export and a retention sweep. Choose another namespace.`,\n );\n }\n}\n", "/**\n * A Roaring bitmap of unsigned 32-bit ids in TypeScript, behind the codec seam: {@link tsRoaringCodec} is a\n * `CodecInterface` that stores the same portable Roaring bytes as CRoaring (through `roaring`, the reference the tests compare it\n * against), with no native addon.\n *\n * It implements the data structure of Chambi, Lemire, Kaser and Godin, \"Better bitmap performance with Roaring bitmaps\"\n * (2016), with the run containers of Lemire, Ssi-Yan-Kai and Kaser, \"Consistently faster and smaller compressed bitmaps\n * with Roaring\" (2016), and the implementation notes of Lemire et al., \"Roaring Bitmaps: Implementation of an Optimized\n * Software Library\" (2018); the links are in the package README's credits. An id is split into a 16-bit key and a 16-bit\n * remainder; the remainders of one key sit in a container (an array, a bitset or runs: `containers.ts`), and the\n * containers sit in ascending key order beside their keys. The portable bytes are `wire.ts`.\n *\n * TsBitmap\n * keys: [ 0 3 40000 ] ascending 16-bit keys\n * conts: [ ARRAY RUN BITSET ] one container each, with its cardinality kept\n * size: total cardinality, kept as containers change\n *\n * What it keeps to, which the oracle suite holds it to against CRoaring and against the stored-byte rule:\n *\n * - `serialize()` writes the containers as they are: one made from ids is an array or a bitset by cardinality, one\n * decoded from run bytes stays a run until it changes;\n * - `optimize()` re-encodes each container canonically (a run only when strictly smaller than the plain body), so\n * `serialize()` afterwards depends on the set alone;\n * - `safeDeserialize` runs the layout check first (`portable/layout.ts`), so the structure every operation assumes is\n * proven before a container is built, and refuses what CRoaring's validator refuses, with `IntegrityError`;\n * - a combine never changes its operand. A key only this bitmap holds keeps its container by reference (it can be a\n * run), an unshared bitset's words are reused in place, and a key only the operand holds is copied in for a union or\n * an exclusive-or; a pair of containers combines into an array or a bitset, except that two run containers (for\n * and, or, andNot and xor) and a run with an array (for or alone) keep a run result while it is the smaller form\n * (the written rule is in `containers.ts`).\n * - `clone` shares every container with the original and flags it, so the first write on either side copies it.\n *\n * `andCardinality` (and the or, xor and andNot counts derived from it), `intersects`, `isSubset` and `isEqual` answer from\n * the containers without building a result: they change neither bitmap and allocate nothing per call.\n *\n * Writing an id that is not an integer from 0 to 4,294,967,295 throws `ValidationError`; reading one (`has`) says no\n * and removing one does nothing. A combine works on each pair of containers by their kinds (`containers.ts` has the\n * table), `addMany` and `removeMany` group sorted ids by key and touch each container once, and iteration is a class\n * that walks the containers where they are (`iterator.ts`; a bitmap must not be mutated while it is iterated).\n *\n * `encodeChunks` takes a snapshot of the containers and marks each shared, so the bitmap may change while the chunks\n * are read: a change copies a shared container first, and the chunks stay what they were when it was called. It\n * optimizes and serializes one container per step, so a writer can yield between steps. Membership and bytes are\n * unchanged, but every container is now flagged shared, so the next write to each copies it once.\n *\n * @see https://github.com/RoaringBitmap/RoaringFormatSpec\n */\nimport type { CodecBitmap, CodecInterface, EncodedChunk } from '@cloudbitmaps/core';\nimport { IntegrityError, ValidationError, refusalOfId } from '@cloudbitmaps/core';\nimport {\n Container,\n appendIds,\n arrayContainer,\n cloneContainer,\n containerAdd,\n containerAddSorted,\n containerAnd,\n containerAndCard,\n containerAndNot,\n containerHas,\n containerMax,\n containerMin,\n containerOr,\n containerRemove,\n containerXor,\n containersEqual,\n containersIntersect,\n containersSubset,\n fromSortedIds,\n optimize,\n orManyContainers,\n orRunIdsWalk,\n RUN,\n walksRunIds,\n} from './containers';\nimport { BitmapIterator } from './iterator';\nimport { decodeContainers, serializeContainers, trailingBytes } from './wire';\n\nconst MAX_ID = 0xffff_ffff;\n\nfunction isId(value: number): boolean {\n return Number.isInteger(value) && value >= 0 && value <= MAX_ID;\n}\n\nfunction checkedId(value: number): number {\n if (!isId(value)) throw refusalOfId(value);\n return value;\n}\n\n/**\n * The ids of `values`, checked, as a `Uint32Array`: `values` itself when it is one (every element of it is an id), else\n * a new one the caller may sort. An array is read once; another iterable is read once into a buffer that doubles, so no\n * intermediate array of the ids is built.\n */\nexport function collect(values: Iterable<number>): Uint32Array {\n if (values instanceof Uint32Array) return values;\n if (Array.isArray(values)) {\n const list = values as number[];\n const out = new Uint32Array(list.length);\n let i = 0;\n try {\n for (; i < list.length; i++) {\n const v = list[i] as number;\n // `v >>> 0 === v` is an integer from 0 to 2^32 - 1 and nothing else (NaN, fractions, strings and null fail it).\n if (v >>> 0 !== v) throw refusalOfId(v);\n out[i] = v;\n }\n } catch (error) {\n // `>>>` coerces a value that is not a number, and the coercion can throw (a BigInt, a Symbol, an object with no\n // primitive form, a `valueOf` that throws): whatever fails on a value that is not a number is that value's\n // refusal, and a check per value to tell it apart in the loop would cost every build. A failure on a number\n // (its own refusal, or a getter that throws) is rethrown as it is.\n const v: unknown = list[i];\n if (typeof v !== 'number') throw refusalOfId(v);\n throw error;\n }\n return out;\n }\n let out = new Uint32Array(1_024);\n let n = 0;\n for (const v of values) {\n if (n === out.length) {\n const grown = new Uint32Array(2 * n);\n grown.set(out);\n out = grown;\n }\n out[n++] = checkedId(v);\n }\n return out.subarray(0, n);\n}\n\n/** The ids of `values` that are ids, in a new `Uint32Array`: what a removal acts on, which ignores the rest. */\nfunction collectLenient(values: Iterable<number>): Uint32Array {\n if (values instanceof Uint32Array) return values.slice();\n const list = Array.isArray(values) ? (values as number[]) : Array.from(values);\n const out = new Uint32Array(list.length);\n let n = 0;\n for (let i = 0; i < list.length; i++) {\n const v = list[i] as number;\n if (v >>> 0 === v) out[n++] = v;\n }\n return out.subarray(0, n);\n}\n\n/** The most ids one key's group of an `addMany` can hold and still go into its container one id at a time. */\nconst FEW_IDS = 4;\n\n/**\n * How `addMany` writes a group of `count` ids into the container `before` that its key already holds: `few` (each id put\n * into it), `walk` (a run container merged with the ids where they are) or `merge` (a container built for the group,\n * then merged).\n */\nexport function groupPath(before: Container, count: number): 'few' | 'walk' | 'merge' {\n if (count <= FEW_IDS) return 'few';\n return walksRunIds(before, count) ? 'walk' : 'merge';\n}\n\n/**\n * `ids` ascending: itself when it already is, else sorted, in place when `owned` (a new array that is the caller's own)\n * and in a copy when it is the caller's.\n */\nfunction sortedIds(ids: Uint32Array, owned: boolean): Uint32Array {\n for (let i = 1; i < ids.length; i++) {\n if ((ids[i - 1] as number) > (ids[i] as number)) return (owned ? ids : ids.slice()).sort();\n }\n return ids;\n}\n\n/** The index of the first of the ascending `keys`, from index `from`, that is `>= key`. */\nfunction lowerBound(keys: readonly number[], key: number, from = 0): number {\n let lo = from;\n let hi = keys.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if ((keys[mid] as number) < key) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n}\n\n/** Like {@link lowerBound}, but by doubling steps from `from`, so it costs the log of the distance, not of the length. */\nfunction gallopKeys(keys: readonly number[], key: number, from: number): number {\n let step = 1;\n let lo = from;\n let hi = from;\n while (hi < keys.length && (keys[hi] as number) < key) {\n lo = hi + 1;\n hi += step;\n step *= 2;\n }\n return lowerBoundIn(keys, key, lo, Math.min(hi, keys.length));\n}\n\nfunction lowerBoundIn(keys: readonly number[], key: number, from: number, to: number): number {\n let lo = from;\n let hi = to;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if ((keys[mid] as number) < key) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n}\n\nconst OR = 0;\nconst AND = 1;\nconst AND_NOT = 2;\nconst XOR = 3;\ntype Combine = typeof OR | typeof AND | typeof AND_NOT | typeof XOR;\n\nfunction combineContainers(op: Combine, a: Container, b: Container): Container | null {\n if (op === OR) return containerOr(a, b, !a.shared || a.kind === RUN);\n if (op === AND) return containerAnd(a, b, !a.shared);\n if (op === XOR) return containerXor(a, b, !a.shared);\n return containerAndNot(a, b, !a.shared);\n}\n\nexport class TsBitmap implements CodecBitmap {\n #keys: number[];\n #conts: Container[];\n #size: number;\n\n private constructor(keys: number[], conts: Container[], size: number) {\n this.#keys = keys;\n this.#conts = conts;\n this.#size = size;\n }\n\n static empty(): TsBitmap {\n return new TsBitmap([], [], 0);\n }\n\n static fromValues(values: Iterable<number>): TsBitmap {\n const bitmap = TsBitmap.empty();\n bitmap.addMany(values);\n return bitmap;\n }\n\n /**\n * Cap the size, check the structure, then build the containers. With `whole`, bytes after the last container are\n * refused too; without it they are ignored. With `detached`, every container gets storage of its own, copied out of\n * the input, so nothing the result holds is a view of one shared buffer: a bitmap that is kept and then reduced\n * does not keep the whole input alive.\n *\n * @throws {IntegrityError} if the input exceeds `maxBytes`, is not a well-formed portable bitmap, or (with `whole`)\n * has bytes after it.\n */\n static safeDeserialize(\n bytes: Uint8Array,\n maxBytes: number,\n options: { readonly whole?: boolean; readonly detached?: boolean } = {},\n ): TsBitmap {\n if (bytes.length > maxBytes) {\n throw new IntegrityError(`serialized bitmap is ${bytes.length}B, exceeds cap ${maxBytes}B`);\n }\n const { keys, conts, end } = decodeContainers(bytes, options.detached === true);\n if (options.whole === true && end !== bytes.byteLength) {\n throw trailingBytes(bytes.byteLength, end);\n }\n let size = 0;\n for (let i = 0; i < conts.length; i++) size += (conts[i] as Container).card;\n return new TsBitmap(keys, conts, size);\n }\n\n serialize(): Uint8Array {\n return serializeContainers(this.#keys, this.#conts);\n }\n\n /** Re-encode each container canonically; membership is untouched. */\n optimize(): void {\n const conts = this.#conts;\n for (let i = 0; i < conts.length; i++) conts[i] = optimize(conts[i] as Container);\n }\n\n /** Whether at least one container is held as runs. */\n hasRunContainer(): boolean {\n for (let i = 0; i < this.#conts.length; i++)\n if ((this.#conts[i] as Container).kind === RUN) return true;\n return false;\n }\n\n /**\n * The set as storage chunks: each payload is the portable bytes of a one-container bitmap holding that chunk's low 16\n * bits, optimized the way {@link optimize} does. Nothing is built until a chunk is asked for, so a writer that yields\n * between chunks runs this in slices. The call snapshots the containers and marks each shared, so a change to the\n * bitmap while the chunks are read copies a container instead of altering what the chunks will say. The bitmap's own\n * containers are not optimized by it.\n */\n encodeChunks(): Iterable<EncodedChunk> {\n const keys = this.#keys.slice();\n const conts = this.#conts.slice();\n for (let i = 0; i < conts.length; i++) (conts[i] as Container).shared = true;\n return {\n *[Symbol.iterator](): Iterator<EncodedChunk> {\n for (let i = 0; i < conts.length; i++) {\n const c = optimize(conts[i] as Container);\n yield {\n chunkKey: keys[i] as number,\n payload: serializeContainers([0], [c]),\n cardinality: c.card,\n };\n }\n },\n };\n }\n\n /** The smallest id, or `undefined` when the bitmap is empty. */\n minimum(): number | undefined {\n if (this.#conts.length === 0) return undefined;\n return (this.#keys[0] as number) * 65_536 + containerMin(this.#conts[0] as Container);\n }\n\n maximum(): number | undefined {\n const last = this.#conts.length - 1;\n if (last < 0) return undefined;\n return (this.#keys[last] as number) * 65_536 + containerMax(this.#conts[last] as Container);\n }\n\n add(value: number): void {\n checkedId(value);\n const key = value >>> 16;\n const low = value & 0xffff;\n const at = lowerBound(this.#keys, key);\n const found = this.#keys[at] === key;\n if (!found) {\n this.#insert(at, key, arrayContainer(Uint16Array.of(low), 1));\n this.#size++;\n return;\n }\n const before = this.#conts[at] as Container;\n const after = containerAdd(before, low);\n this.#conts[at] = after;\n this.#size += after.card - before.card;\n }\n\n /**\n * Add the ids. They are grouped by key in ascending order, so each container is touched once, a key already held is\n * merged where it is, and the new keys are put in with one pass over the key list however many there are.\n */\n addMany(values: Iterable<number>): void {\n const ids = sortedIds(collect(values), !(values instanceof Uint32Array));\n const fresh: Array<{ key: number; group: Container }> = [];\n let at = 0;\n for (let i = 0; i < ids.length;) {\n const key = (ids[i] as number) >>> 16;\n let end = i + 1;\n while (end < ids.length && (ids[end] as number) >>> 16 === key) end++;\n const first = i;\n i = end;\n at = gallopKeys(this.#keys, key, at);\n if (this.#keys[at] === key) {\n const before = this.#conts[at] as Container;\n // A group of a few goes into the container it meets without a container of its own. A run container is never\n // written in place, so the result may be it when the ids add nothing.\n // A larger group into a run container is walked from the ids, again with no container for the group.\n const path = groupPath(before, end - first);\n const after =\n path === 'few'\n ? containerAddSorted(before, ids, first, end)\n : path === 'walk'\n ? orRunIdsWalk(before, ids, first, end)\n : containerOr(\n before,\n fromSortedIds(ids, first, end),\n !before.shared || before.kind === RUN,\n );\n this.#conts[at] = after;\n this.#size += after.card - before.card;\n } else {\n const group = fromSortedIds(ids, first, end);\n fresh.push({ key, group });\n this.#size += group.card;\n }\n }\n if (fresh.length > 0) this.#insertAll(fresh);\n }\n\n /** Remove the id (anything that is not an id is ignored); whether it was there. */\n remove(value: number): boolean {\n if (!isId(value)) return false;\n const key = value >>> 16;\n const at = lowerBound(this.#keys, key);\n if (this.#keys[at] !== key) return false;\n const before = this.#conts[at] as Container;\n const after = containerRemove(before, value & 0xffff);\n if (after === null) {\n this.#keys.splice(at, 1);\n this.#conts.splice(at, 1);\n this.#size -= before.card;\n return true;\n }\n this.#conts[at] = after;\n this.#size += after.card - before.card;\n return after.card !== before.card;\n }\n\n /** Remove every id. Containers a clone shares are left to it. */\n clear(): void {\n this.#keys = [];\n this.#conts = [];\n this.#size = 0;\n }\n\n /** Remove the ids (anything that is not an id is ignored), grouped by key; the keys left empty go in one pass. */\n removeMany(values: Iterable<number>): void {\n const ids = sortedIds(collectLenient(values), true);\n const keys = this.#keys;\n const conts = this.#conts;\n let at = 0;\n let emptied = 0;\n for (let i = 0; i < ids.length;) {\n const key = (ids[i] as number) >>> 16;\n let end = i + 1;\n while (end < ids.length && (ids[end] as number) >>> 16 === key) end++;\n const from = i;\n i = end;\n at = gallopKeys(keys, key, at);\n if (keys[at] !== key) continue;\n const before = conts[at] as Container;\n if (before.card === 0) continue;\n const after = containerAndNot(before, fromSortedIds(ids, from, end), !before.shared);\n this.#size -= before.card - (after === null ? 0 : after.card);\n if (after === null) {\n conts[at] = EMPTIED;\n emptied++;\n } else {\n conts[at] = after;\n }\n }\n if (emptied > 0) this.#dropEmptied();\n }\n\n has(value: number): boolean {\n if (!isId(value)) return false;\n const key = value >>> 16;\n const at = lowerBound(this.#keys, key);\n return this.#keys[at] === key && containerHas(this.#conts[at] as Container, value & 0xffff);\n }\n\n get size(): number {\n return this.#size;\n }\n\n get isEmpty(): boolean {\n return this.#size === 0;\n }\n\n clone(): TsBitmap {\n const conts = new Array<Container>(this.#conts.length);\n // The copy shares each container with this bitmap and both mark it shared, so the first write on either side copies\n // it; a clone that is only read, or combined into fresh containers, never pays for a copy.\n for (let i = 0; i < conts.length; i++) {\n const c = this.#conts[i] as Container;\n c.shared = true;\n conts[i] = c;\n }\n return new TsBitmap(this.#keys.slice(), conts, this.#size);\n }\n\n orInPlace(other: CodecBitmap): void {\n this.#combine(TsBitmap.#of(other), OR);\n }\n\n andInPlace(other: CodecBitmap): void {\n this.#combine(TsBitmap.#of(other), AND);\n }\n\n andNotInPlace(other: CodecBitmap): void {\n this.#combine(TsBitmap.#of(other), AND_NOT);\n }\n\n /** Flip the ids `other` holds, in one pass over the pair of each key. */\n xorInPlace(other: CodecBitmap): void {\n this.#combine(TsBitmap.#of(other), XOR);\n }\n\n /** How many ids both bitmaps hold, counted without building the intersection. */\n andCardinality(other: CodecBitmap): number {\n const that = TsBitmap.#of(other);\n const a = this.#keys;\n const b = that.#keys;\n let n = 0;\n let i = 0;\n let j = 0;\n while (i < a.length && j < b.length) {\n const ka = a[i] as number;\n const kb = b[j] as number;\n if (ka === kb) {\n n += containerAndCard(this.#conts[i++] as Container, that.#conts[j++] as Container);\n } else if (ka < kb) {\n i = gallopKeys(a, kb, i + 1);\n } else {\n j = gallopKeys(b, ka, j + 1);\n }\n }\n return n;\n }\n\n /** How many ids either bitmap holds. */\n orCardinality(other: CodecBitmap): number {\n return this.#size + TsBitmap.#of(other).#size - this.andCardinality(other);\n }\n\n /** How many ids exactly one of the bitmaps holds. */\n xorCardinality(other: CodecBitmap): number {\n return this.#size + TsBitmap.#of(other).#size - 2 * this.andCardinality(other);\n }\n\n /** How many ids this bitmap holds that `other` lacks. */\n andNotCardinality(other: CodecBitmap): number {\n return this.#size - this.andCardinality(other);\n }\n\n /** Whether the bitmaps share an id; stops at the first one found. */\n intersects(other: CodecBitmap): boolean {\n const that = TsBitmap.#of(other);\n const a = this.#keys;\n const b = that.#keys;\n let i = 0;\n let j = 0;\n while (i < a.length && j < b.length) {\n const ka = a[i] as number;\n const kb = b[j] as number;\n if (ka === kb) {\n if (containersIntersect(this.#conts[i++] as Container, that.#conts[j++] as Container)) {\n return true;\n }\n } else if (ka < kb) {\n i = gallopKeys(a, kb, i + 1);\n } else {\n j = gallopKeys(b, ka, j + 1);\n }\n }\n return false;\n }\n\n /** Whether every id of this bitmap is in `other`; stops at the first container that is not inside its partner. */\n isSubset(other: CodecBitmap): boolean {\n const that = TsBitmap.#of(other);\n if (this.#size > that.#size) return false;\n const a = this.#keys;\n const b = that.#keys;\n let j = 0;\n for (let i = 0; i < a.length; i++) {\n j = gallopKeys(b, a[i] as number, j);\n if (j === b.length || b[j] !== a[i]) return false;\n const c = this.#conts[i] as Container;\n if (!containersSubset(c, that.#conts[j++] as Container)) return false;\n }\n return true;\n }\n\n /** Whether both hold the same ids, whatever the kinds of their containers. */\n isEqual(other: CodecBitmap): boolean {\n const that = TsBitmap.#of(other);\n if (this.#size !== that.#size || this.#keys.length !== that.#keys.length) return false;\n for (let i = 0; i < this.#keys.length; i++) {\n if (this.#keys[i] !== that.#keys[i]) return false;\n if (!containersEqual(this.#conts[i] as Container, that.#conts[i] as Container)) return false;\n }\n return true;\n }\n\n [Symbol.iterator](): IterableIterator<number> {\n return new BitmapIterator(this.#keys, this.#conts);\n }\n\n toArray(): number[] {\n return Array.from(this.toUint32Array());\n }\n\n /** The ids as a new ascending `Uint32Array`. */\n toUint32Array(): Uint32Array {\n const out = new Uint32Array(this.#size);\n let at = 0;\n for (let i = 0; i < this.#conts.length; i++) {\n at = appendIds(this.#conts[i] as Container, out, at, (this.#keys[i] as number) * 65_536);\n }\n return out;\n }\n\n static #of(other: CodecBitmap): TsBitmap {\n if (!(other instanceof TsBitmap)) {\n throw new ValidationError('a TypeScript roaring bitmap combines only with another one');\n }\n return other;\n }\n\n #insert(at: number, key: number, container: Container): void {\n if (at === this.#keys.length) {\n this.#keys.push(key);\n this.#conts.push(container);\n } else {\n this.#keys.splice(at, 0, key);\n this.#conts.splice(at, 0, container);\n }\n }\n\n /** Put the new keys, ascending and none held, in: after the last key by pushing, else in one merge pass. */\n #insertAll(fresh: ReadonlyArray<{ key: number; group: Container }>): void {\n const keys = this.#keys;\n const conts = this.#conts;\n if (\n keys.length === 0 ||\n (keys[keys.length - 1] as number) < (fresh[0] as { key: number }).key\n ) {\n for (const { key, group } of fresh) {\n keys.push(key);\n conts.push(group);\n }\n return;\n }\n const outKeys: number[] = [];\n const outConts: Container[] = [];\n let i = 0;\n let j = 0;\n while (i < keys.length || j < fresh.length) {\n if (\n j === fresh.length ||\n (i < keys.length && (keys[i] as number) < (fresh[j] as { key: number }).key)\n ) {\n outKeys.push(keys[i] as number);\n outConts.push(conts[i++] as Container);\n } else {\n const next = fresh[j++] as { key: number; group: Container };\n outKeys.push(next.key);\n outConts.push(next.group);\n }\n }\n this.#keys = outKeys;\n this.#conts = outConts;\n }\n\n /** Remove the keys whose container was emptied by {@link removeMany}, in one pass. */\n #dropEmptied(): void {\n let kept = 0;\n for (let i = 0; i < this.#conts.length; i++) {\n if (this.#conts[i] === EMPTIED) continue;\n this.#keys[kept] = this.#keys[i] as number;\n this.#conts[kept++] = this.#conts[i] as Container;\n }\n this.#keys.length = kept;\n this.#conts.length = kept;\n }\n\n /**\n * Walk both key lists and rebuild this one: where both hold a key, the combine of the two containers; where only this\n * does, its container, unless the operation is an intersection; where only `that` does, a copy of its container for a\n * union and nothing otherwise. A combine that leaves no value drops the key. An intersection jumps over a stretch of\n * keys the other side lacks by doubling steps, so a few keys against many cost the few.\n */\n #combine(that: TsBitmap, op: Combine): void {\n const a = this.#keys;\n const b = that.#keys;\n const ca = this.#conts;\n const cb = that.#conts;\n const keys: number[] = [];\n const conts: Container[] = [];\n let size = 0;\n let i = 0;\n let j = 0;\n while (i < a.length && j < b.length) {\n const ka = a[i] as number;\n const kb = b[j] as number;\n if (ka === kb) {\n const c = combineContainers(op, ca[i++] as Container, cb[j++] as Container);\n if (c !== null) {\n keys.push(ka);\n conts.push(c);\n size += c.card;\n }\n } else if (ka < kb) {\n if (op === AND) {\n i = gallopKeys(a, kb, i + 1);\n } else {\n keys.push(ka);\n conts.push(ca[i] as Container);\n size += (ca[i++] as Container).card;\n }\n } else if (op === AND) {\n j = gallopKeys(b, ka, j + 1);\n } else {\n if (op === OR || op === XOR) {\n keys.push(kb);\n conts.push(cloneContainer(cb[j] as Container));\n size += (cb[j] as Container).card;\n }\n j++;\n }\n }\n if (op !== AND) {\n for (; i < a.length; i++) {\n keys.push(a[i] as number);\n conts.push(ca[i] as Container);\n size += (ca[i] as Container).card;\n }\n }\n if (op === OR || op === XOR) {\n for (; j < b.length; j++) {\n keys.push(b[j] as number);\n conts.push(cloneContainer(cb[j] as Container));\n size += (cb[j] as Container).card;\n }\n }\n this.#keys = keys;\n this.#conts = conts;\n this.#size = size;\n }\n\n /** The ids both bitmaps hold, as a new bitmap; neither operand changes and no container of either is kept. */\n static and(a: CodecBitmap, b: CodecBitmap): TsBitmap {\n return TsBitmap.#fresh(TsBitmap.#of(a), TsBitmap.#of(b), AND);\n }\n\n /** The ids either holds, as a new bitmap; neither operand changes. */\n static or(a: CodecBitmap, b: CodecBitmap): TsBitmap {\n return TsBitmap.#fresh(TsBitmap.#of(a), TsBitmap.#of(b), OR);\n }\n\n /**\n * The ids any of `bitmaps` holds, as a new bitmap that owns all its storage; no operand changes and none is flagged.\n * The containers of each key are gathered across the inputs and united in one pass (see {@link orManyContainers}),\n * counted once. A key only one input holds is copied as it is, a run included.\n */\n static orMany(bitmaps: readonly CodecBitmap[]): TsBitmap {\n const byKey = new Map<number, Container[]>();\n for (const input of bitmaps) {\n const that = TsBitmap.#of(input);\n for (let i = 0; i < that.#keys.length; i++) {\n const key = that.#keys[i] as number;\n const held = byKey.get(key);\n if (held === undefined) byKey.set(key, [that.#conts[i] as Container]);\n else held.push(that.#conts[i] as Container);\n }\n }\n const keys = Array.from(byKey.keys()).sort((x, y) => x - y);\n const conts: Container[] = [];\n let size = 0;\n for (const key of keys) {\n const held = byKey.get(key) as Container[];\n const c = held.length === 1 ? cloneContainer(held[0] as Container) : orManyContainers(held);\n conts.push(c);\n size += c.card;\n }\n return new TsBitmap(keys, conts, size);\n }\n\n /** The ids exactly one holds, as a new bitmap; neither operand changes. */\n static xor(a: CodecBitmap, b: CodecBitmap): TsBitmap {\n return TsBitmap.#fresh(TsBitmap.#of(a), TsBitmap.#of(b), XOR);\n }\n\n /** The ids of `a` that `b` lacks, as a new bitmap; neither operand changes. */\n static andNot(a: CodecBitmap, b: CodecBitmap): TsBitmap {\n return TsBitmap.#fresh(TsBitmap.#of(a), TsBitmap.#of(b), AND_NOT);\n }\n\n /**\n * The same walk as {@link TsBitmap.#combine}, building a new bitmap and leaving both operands whole. Where both hold\n * a key, the pair combines into a fresh container (the in-place form is never taken, so no storage of either operand\n * is written). A container only `x` holds is kept by reference and flagged shared, so a later write to `x` or to the\n * result copies it once; for an intersection nothing of `x` is kept, so nothing is flagged. A container only `y`\n * holds is copied in for a union or a symmetric difference.\n */\n static #fresh(x: TsBitmap, y: TsBitmap, op: Combine): TsBitmap {\n const a = x.#keys;\n const b = y.#keys;\n const ca = x.#conts;\n const cb = y.#conts;\n const keys: number[] = [];\n const conts: Container[] = [];\n let size = 0;\n let i = 0;\n let j = 0;\n while (i < a.length && j < b.length) {\n const ka = a[i] as number;\n const kb = b[j] as number;\n if (ka === kb) {\n const c = freshPair(op, ca[i++] as Container, cb[j++] as Container);\n if (c !== null) {\n keys.push(ka);\n conts.push(c);\n size += c.card;\n }\n } else if (ka < kb) {\n if (op === AND) {\n i = gallopKeys(a, kb, i + 1);\n } else {\n const c = ca[i++] as Container;\n c.shared = true;\n keys.push(ka);\n conts.push(c);\n size += c.card;\n }\n } else if (op === AND) {\n j = gallopKeys(b, ka, j + 1);\n } else {\n if (op === OR || op === XOR) {\n keys.push(kb);\n conts.push(cloneContainer(cb[j] as Container));\n size += (cb[j] as Container).card;\n }\n j++;\n }\n }\n if (op !== AND) {\n for (; i < a.length; i++) {\n const c = ca[i] as Container;\n c.shared = true;\n keys.push(a[i] as number);\n conts.push(c);\n size += c.card;\n }\n }\n if (op === OR || op === XOR) {\n for (; j < b.length; j++) {\n keys.push(b[j] as number);\n conts.push(cloneContainer(cb[j] as Container));\n size += (cb[j] as Container).card;\n }\n }\n return new TsBitmap(keys, conts, size);\n }\n}\n\n/** A pair of containers combined into a container of its own (`null` when nothing is left); neither is written. */\nfunction freshPair(op: Combine, a: Container, b: Container): Container | null {\n if (op === OR) return containerOr(a, b, false);\n if (op === AND) return containerAnd(a, b, false);\n if (op === AND_NOT) return containerAndNot(a, b, false);\n return containerXor(a, b, false);\n}\n\n/** Stands for a container {@link TsBitmap.removeMany} emptied, until the keys left empty are dropped. */\nconst EMPTIED = arrayContainer(new Uint16Array(0), 0);\n\n/** The TypeScript Roaring codec: the same portable bytes as CRoaring, with no native addon. */\nexport const tsRoaringCodec: CodecInterface = {\n empty: () => TsBitmap.empty(),\n fromValues: (values) => TsBitmap.fromValues(values),\n safeDeserialize: (bytes, maxBytes, options) => TsBitmap.safeDeserialize(bytes, maxBytes, options),\n owns: (bitmap) => bitmap instanceof TsBitmap,\n intersectSmallestFirst: true,\n};\n", "/**\n * The layout of a portable-roaring bitmap: parsed, and checked for the structure every reader of it assumes.\n *\n * WHY THIS EXISTS. A decoder that only promises never to read past the buffer (CRoaring's safe deserialize, which\n * the `roaring` package calls, is one) takes every other invariant of the format on trust from bytes that come off a\n * storage tier, which hard invariant 5 says are hostile until proven otherwise. This check is what the TypeScript\n * decoder runs before it builds a bitmap, and the tests hold it to CRoaring's. What `roaring` 2.7.0, the native\n * reference, does with such bytes when nothing checks them first:\n *\n * - **Containers out of order.** `maximum()` reads the last container, so a chunk payload listing container 1\n * before container 0 passes the engine's 16-bit range check, and a read then yields container 1's values masked\n * into the chunk: ids the segment does not hold, which `has()` denies.\n * - **Values or runs out of order, duplicated or overlapping.** `has()` binary-searches, so it denies values that\n * iteration yields, `size` counts duplicates, and a range read stops early.\n * - **A run past the end of its container.** `maximum()` wraps to a small value, so the range check passes, and\n * iteration yields values from the next container's id space.\n * - **A run container with no runs.** Iterating it, or intersecting or unioning with it, crashes the process.\n * - **A bitset whose header cardinality disagrees with its bits.** `size` answers the header. Where the header\n * says fewer values than the bits hold, `remove()` converts the container into an array sized by the header and\n * writes every bit into it: a heap overflow in the native library, and then a crash.\n *\n * None of those is caught by a CRC, which proves only that the bytes are the bytes that were written. Anyone who\n * can write the bucket writes those.\n *\n * WHAT IT CHECKS, which is what CRoaring's `roaring_bitmap_internal_validate` checks, stated on the serialized form: container\n * keys strictly ascend; array values strictly ascend; runs ascend, stay inside their container, and neither overlap\n * nor touch (a writer merges touching runs); a run container has at least one run; a bitset's popcount is the\n * cardinality its header states. And two things CRoaring's deserializer ignores and this library's readers use: every\n * offset in the offset header is where its container really starts, and a run container's header cardinality is\n * the number of values its runs cover. Anything a real writer produces passes, because a real writer produces\n * exactly this structure.\n *\n * HOW IT READS. A bitset body is counted in place through a `Uint32Array` (copied to a scratch first when its offset is not\n * a multiple of 4); every array and run list goes through the `DataView`, which costs less to compile on a first call.\n * Each path refuses the same bytes with the same message.\n *\n * WHAT IT COSTS. One pass over the bytes the decode is about to copy anyway, once per decode: never per id, and\n * never on a cache hit.\n *\n * The codec's bitmap decoder in `ts-roaring/` runs it before it builds a container. The membership-only reader in\n * `decode.ts`, which the tests use as a second reader of the same bytes, builds on the layout it returns. One check in\n * one place is what keeps the two decoders from disagreeing about which bytes are a bitmap.\n *\n * @see https://github.com/RoaringBitmap/RoaringFormatSpec\n */\nimport { IntegrityError } from '@cloudbitmaps/core';\nimport type { EncodedChunk } from '@cloudbitmaps/core';\nimport { BITSET_WORDS, popcountWords } from './popcount';\n\n/** Whether this machine stores a typed array's elements little-endian, as the wire does (so a body is a plain copy). */\nexport const LITTLE_ENDIAN = new Uint8Array(Uint16Array.of(1).buffer)[0] === 1;\n\n/** Cookie for a bitmap with no run containers. Followed by a u32 container count. */\nexport const SERIAL_COOKIE_NO_RUNCONTAINER = 12_346;\n/** Cookie (low 16 bits) for a bitmap that may contain run containers; the high 16 bits hold `count - 1`. */\nexport const SERIAL_COOKIE = 12_347;\n/**\n * Below this many containers, a run-cookie bitmap omits the offset header and containers must be located by\n * walking their sizes. At or above it the header is present. (A `NO_RUNCONTAINER` bitmap always has it.)\n */\nexport const NO_OFFSET_THRESHOLD = 4;\n/** A container holding more than this many values is stored as a flat 8 KiB bitset rather than a u16 array. */\nexport const ARRAY_MAX_CARDINALITY = 4_096;\n/** 65,536 bits, flat. */\nconst BITMAP_CONTAINER_BYTES = 8_192;\n/** The largest value a container holds: its low 16 bits. */\nconst MAX_LOW = 0xffff;\n\n/** A container of sorted `u16` values. */\nexport const ARRAY = 0;\n/** A container of 65,536 bits. */\nexport const BITMAP = 1;\n/** A container of `(start, length)` runs. */\nconst RUN = 2;\ntype ContainerKind = typeof ARRAY | typeof BITMAP | typeof RUN;\n\nexport interface PortableContainer {\n /** High 16 bits of every value in this container. */\n readonly key: number;\n /** Number of values. Stored as `cardinality - 1` on the wire, normalized here. */\n readonly cardinality: number;\n readonly kind: ContainerKind;\n /** Absolute byte offset of this container's payload within the source buffer; a run container's run count. */\n readonly offset: number;\n}\n\n/**\n * The error for a field that runs past the buffer. Callers test the bound inline and call this only when it\n * fails, so a well-formed bitmap never builds the message: the test runs once per container, and a string built\n * on every pass would cost a bitmap of many small containers more than the check itself does.\n */\nfunction overrun(bytes: Uint8Array, offset: number, length: number, what: string): IntegrityError {\n return new IntegrityError(\n `portable roaring: ${what} needs bytes [${offset}, ${offset + length}) of a ${bytes.byteLength}-byte buffer`,\n );\n}\n\n/**\n * Parse the portable-format bitmap in `bytes`, and check its structure.\n *\n * An empty buffer is the empty bitmap, as it is to CRoaring, which returns one without reading a byte.\n *\n * @throws {IntegrityError} if the cookie is unrecognized, any field runs past the buffer, or the structure is not\n * one a writer produces (see the module header for the list).\n */\nexport function parsePortableLayout(bytes: Uint8Array): PortableContainer[] {\n const containers: PortableContainer[] = [];\n walk(bytes, containers);\n return containers;\n}\n\n/**\n * {@link parsePortableLayout}'s check alone, for a caller that hands the bytes to another decoder afterwards and\n * so has no use for the layout: it allocates nothing per container.\n *\n * @returns where the bitmap ends: the offset one past its last container's last byte (0 for an empty buffer). A\n * caller that needs the buffer to be exactly one bitmap compares it with the buffer's length.\n * @throws {IntegrityError} exactly where {@link parsePortableLayout} does.\n */\nexport function checkPortableLayout(bytes: Uint8Array): number {\n return walk(bytes, null);\n}\n\n/** A one-container payload's header without run containers: cookie, count, `(key, cardinality - 1)`, offset. */\nconst SINGLE_HEADER_BYTES = 16;\n/** A one-container payload's header under the run cookie: cookie holding `count - 1`, one flag byte, the pair. */\nconst SINGLE_RUN_HEADER_BYTES = 9;\n\n/**\n * Each container of the portable bitmap in `bytes`, as the one-container portable bitmap a `.crbm` chunk stores:\n * its key moved to 0, its cardinality and kind kept, its body copied unchanged. These are exactly the bytes the\n * serializer writes for a bitmap holding only that container's low 16 bits, so a chunk cut from a whole\n * bitmap is the chunk built from its ids, provided the whole bitmap was encoded canonically first.\n *\n * Lazy, one container per step, and each container checked as it is copied, by the same rules as\n * {@link checkPortableLayout} (keys in order, and each body holding what its header says), so a stored chunk is\n * never one a reader refuses. The bytes are the serializer's, of a bitmap decoded from bytes that passed the\n * check, so on every honest input this finds nothing. It is what stands between a store and a bitmap decoded from a\n * buffer another thread was still writing during the load's call: the check saw the bytes as they were, the decode\n * as they became.\n *\n * @throws {IntegrityError} at the first container that runs past the buffer or does not hold what its header says.\n */\nexport function* containerPayloads(bytes: Uint8Array): Generator<EncodedChunk> {\n if (bytes.byteLength === 0) return;\n const { view, count, runFlagsAt, descriptiveAt, bodiesAt } = header(bytes);\n let pos = bodiesAt;\n let previousKey = -1;\n for (let i = 0; i < count; i++) {\n const key = view.getUint16(descriptiveAt + i * 4, true);\n if (key <= previousKey) {\n throw new IntegrityError(\n `portable roaring: container keys are not strictly ascending at index ${i}`,\n );\n }\n previousKey = key;\n const cardinality = view.getUint16(descriptiveAt + i * 4 + 2, true) + 1;\n const isRun =\n runFlagsAt >= 0 && ((bytes[runFlagsAt + (i >>> 3)] as number) & (1 << (i & 7))) !== 0;\n const kind: ContainerKind = isRun ? RUN : cardinality > ARRAY_MAX_CARDINALITY ? BITMAP : ARRAY;\n const size = checkContainer(bytes, view, pos, kind, cardinality, i);\n const headerBytes = isRun ? SINGLE_RUN_HEADER_BYTES : SINGLE_HEADER_BYTES;\n const payload = new Uint8Array(headerBytes + size);\n const out = new DataView(payload.buffer);\n if (isRun) {\n out.setUint32(0, SERIAL_COOKIE, true); // count - 1 = 0 in the high half\n payload[4] = 1; // container 0 is a run container\n out.setUint16(7, cardinality - 1, true); // after key 0 at byte 5\n } else {\n out.setUint32(0, SERIAL_COOKIE_NO_RUNCONTAINER, true);\n out.setUint32(4, 1, true);\n out.setUint16(10, cardinality - 1, true); // after key 0 at byte 8\n out.setUint32(12, SINGLE_HEADER_BYTES, true);\n }\n payload.set(bytes.subarray(pos, pos + size), headerBytes);\n pos += size;\n yield { chunkKey: key, payload, cardinality };\n }\n}\n\n/** Where each part of a non-empty portable bitmap's header is, checked against the buffer's length. */\ninterface Header {\n readonly view: DataView;\n readonly count: number;\n /** Where the run-container flag bits start, or -1 under the cookie that has none. */\n readonly runFlagsAt: number;\n /** The descriptive header: `(key, cardinality - 1)` per container. */\n readonly descriptiveAt: number;\n /** The offset header, or -1 where this layout has none. */\n readonly offsetsAt: number;\n /** Where the first container's body starts. */\n readonly bodiesAt: number;\n}\n\nfunction header(bytes: Uint8Array): Header {\n const length = bytes.byteLength;\n const view = new DataView(bytes.buffer, bytes.byteOffset, length);\n if (length < 4) throw overrun(bytes, 0, 4, 'the cookie');\n const cookie = view.getUint32(0, true);\n let count: number;\n let runFlagsAt = -1;\n let pos: number;\n if (cookie === SERIAL_COOKIE_NO_RUNCONTAINER) {\n if (length < 8) throw overrun(bytes, 4, 4, 'the container count');\n count = view.getUint32(4, true);\n pos = 8;\n } else if ((cookie & 0xffff) === SERIAL_COOKIE) {\n // The count is packed into the cookie's high half as `count - 1`, so it can never be zero here.\n count = (cookie >>> 16) + 1;\n runFlagsAt = 4;\n const flagBytes = (count + 7) >>> 3;\n if (runFlagsAt + flagBytes > length) {\n throw overrun(bytes, runFlagsAt, flagBytes, 'the run-container bitmap');\n }\n pos = runFlagsAt + flagBytes;\n } else {\n throw new IntegrityError(\n `portable roaring: unrecognized cookie 0x${cookie.toString(16)}, not a portable-format bitmap`,\n );\n }\n const descriptiveAt = pos;\n if (pos + count * 4 > length) throw overrun(bytes, pos, count * 4, 'the descriptive header');\n pos += count * 4;\n let offsetsAt = -1;\n if (runFlagsAt < 0 || count >= NO_OFFSET_THRESHOLD) {\n if (pos + count * 4 > length) throw overrun(bytes, pos, count * 4, 'the offset header');\n offsetsAt = pos;\n pos += count * 4;\n }\n return { view, count, runFlagsAt, descriptiveAt, offsetsAt, bodiesAt: pos };\n}\n\n/**\n * Check every container of `bytes`, appending each one's layout to `out` when there is one to append to. Returns\n * where the bitmap ends.\n */\nfunction walk(bytes: Uint8Array, out: PortableContainer[] | null): number {\n if (bytes.byteLength === 0) return 0;\n const { view, count, runFlagsAt, descriptiveAt, offsetsAt, bodiesAt } = header(bytes);\n let pos = bodiesAt;\n\n let previousKey = -1;\n // Containers lie back to back from here. That is how CRoaring's deserializer finds them (it never reads the\n // offset header), so the offsets are checked against it rather than followed.\n for (let i = 0; i < count; i++) {\n const key = view.getUint16(descriptiveAt + i * 4, true);\n if (key <= previousKey) {\n throw new IntegrityError(\n `portable roaring: container keys are not strictly ascending at index ${i}`,\n );\n }\n previousKey = key;\n const cardinality = view.getUint16(descriptiveAt + i * 4 + 2, true) + 1;\n const isRun =\n runFlagsAt >= 0 && ((bytes[runFlagsAt + (i >>> 3)] as number) & (1 << (i & 7))) !== 0;\n const kind: ContainerKind = isRun ? RUN : cardinality > ARRAY_MAX_CARDINALITY ? BITMAP : ARRAY;\n if (offsetsAt >= 0) {\n const stated = view.getUint32(offsetsAt + i * 4, true);\n if (stated !== pos) {\n throw new IntegrityError(\n `portable roaring: the offset header puts container ${i} at byte ${stated}, but it starts at ${pos}`,\n );\n }\n }\n\n const size = checkContainer(bytes, view, pos, kind, cardinality, i);\n out?.push({ key, cardinality, kind, offset: pos });\n pos += size;\n }\n return pos;\n}\n\n/**\n * Check one container's body at `pos`: that it fits the buffer and holds what its header says (see the module\n * header for the rules). Returns the body's size.\n */\nfunction checkContainer(\n bytes: Uint8Array,\n view: DataView,\n pos: number,\n kind: ContainerKind,\n cardinality: number,\n i: number,\n): number {\n const length = bytes.byteLength;\n if (kind === ARRAY) {\n const size = cardinality * 2;\n if (pos + size > length) throw overrun(bytes, pos, size, `container ${i} (array)`);\n checkArray(view, pos, cardinality, i);\n return size;\n }\n if (kind === BITMAP) {\n if (pos + BITMAP_CONTAINER_BYTES > length) {\n throw overrun(bytes, pos, BITMAP_CONTAINER_BYTES, `container ${i} (bitmap)`);\n }\n const bits = bitsetBits(bytes, pos);\n if (bits !== cardinality) {\n throw new IntegrityError(\n `portable roaring: container ${i} (bitmap) holds ${bits} values, but its header says ${cardinality}`,\n );\n }\n return BITMAP_CONTAINER_BYTES;\n }\n if (pos + 2 > length) throw overrun(bytes, pos, 2, `container ${i} (run count)`);\n const runs = view.getUint16(pos, true);\n const size = 2 + runs * 4;\n if (pos + size > length) throw overrun(bytes, pos, size, `container ${i} (run)`);\n const covered = checkRuns(view, pos + 2, runs, i);\n // A header cannot state zero values, so this is also what refuses a run container with no runs, the shape\n // that crashes CRoaring when anything iterates it.\n if (covered !== cardinality) {\n throw new IntegrityError(\n `portable roaring: container ${i} (run) covers ${covered} values, but its header says ${cardinality}`,\n );\n }\n return size;\n}\n\n/**\n * An array container's values must strictly ascend: `has` binary-searches them and iteration yields them in order.\n *\n * Read two values per `u32` (little-endian, so the first value is the low half): half the loads and half the loop\n * trips of reading them one at a time, which measured about twice as fast (probe, indicative).\n */\nfunction checkArray(view: DataView, at: number, cardinality: number, index: number): void {\n let previous = -1;\n let p = at;\n const end = at + cardinality * 2;\n for (; p + 4 <= end; p += 4) {\n const pair = view.getUint32(p, true);\n const first = pair & 0xffff;\n const second = pair >>> 16;\n if (first <= previous || second <= first) throw unordered(index, (p - at) / 2);\n previous = second;\n }\n if (p < end && view.getUint16(p, true) <= previous) throw unordered(index, (p - at) / 2);\n}\n\nfunction unordered(index: number, element: number): IntegrityError {\n return new IntegrityError(\n `portable roaring: container ${index} (array) is not strictly ascending at or after element ${element}`,\n );\n}\n\n/**\n * Runs must ascend, stay inside the container, and leave at least one value between each other: overlapping runs\n * count their shared values twice, and touching ones are two runs a writer would have merged into one. Returns the\n * number of values the runs cover. Each run is one `u32`: its start in the low half, its length in the high.\n */\nfunction checkRuns(view: DataView, at: number, runs: number, index: number): number {\n let covered = 0;\n /** The lowest start the next run may have: one past the value after the previous run's last. */\n let lowest = 0;\n for (let r = 0; r < runs; r++) {\n const run = view.getUint32(at + r * 4, true);\n const start = run & 0xffff;\n const last = start + (run >>> 16);\n if (start < lowest) {\n throw new IntegrityError(\n `portable roaring: container ${index} (run) has run ${r} out of order, overlapping or touching the one before`,\n );\n }\n if (last > MAX_LOW) {\n throw new IntegrityError(\n `portable roaring: container ${index} (run) has run ${r} running past the end of the container`,\n );\n }\n covered += last - start + 1;\n lowest = last + 2;\n }\n return covered;\n}\n\n/**\n * Set bits in the bitset container's 2,048 words at `at`. A body at a 4-byte-aligned offset is counted in place through\n * a `Uint32Array`; any other is copied into a scratch of its own first. Counting is the same on either byte order, so\n * the words need not be read as little-endian.\n */\nfunction bitsetBits(bytes: Uint8Array, at: number): number {\n const offset = bytes.byteOffset + at;\n if ((offset & 3) === 0) return popcountWords(new Uint32Array(bytes.buffer, offset, BITSET_WORDS));\n scratchBytes.set(bytes.subarray(at, at + BITMAP_CONTAINER_BYTES));\n return popcountWords(scratchWords);\n}\n\n/** Where a bitset body that is not 4-byte aligned is copied to be counted. */\nconst scratchWords = new Uint32Array(BITSET_WORDS);\nconst scratchBytes = new Uint8Array(scratchWords.buffer);\n", "/**\n * Bit counting over 32-bit words, shared by the layout check (which counts a stored bitset before it is decoded) and by\n * the containers (which count a bitset they have just built), so both count one way.\n */\n\n/** The 32-bit words of a bitset container: 65,536 bits. */\nexport const BITSET_WORDS = 2_048;\n\n/** Set bits in one 32-bit word. */\nexport function popcount32(word: number): number {\n let w = word - ((word >>> 1) & 0x5555_5555);\n w = (w & 0x3333_3333) + ((w >>> 2) & 0x3333_3333);\n return Math.imul((w + (w >>> 4)) & 0x0f0f_0f0f, 0x0101_0101) >>> 24;\n}\n\n/**\n * Set bits in the {@link BITSET_WORDS} words of a bitset: Harley-Seal, which adds sixteen words through a tree of carry-save\n * adders and counts the bits of one word in sixteen instead of every word. Plain 32-bit integer arithmetic, no `BigInt`.\n */\nexport function popcountWords(d: Uint32Array): number {\n let total = 0;\n let ones = 0;\n let twos = 0;\n let fours = 0;\n let eights = 0;\n for (let i = 0; i < BITSET_WORDS; i += 16) {\n let u: number;\n let twosA: number;\n let twosB: number;\n let foursA: number;\n let foursB: number;\n let x = d[i] as number;\n let y = d[i + 1] as number;\n u = ones ^ x;\n twosA = (ones & x) | (u & y);\n ones = u ^ y;\n x = d[i + 2] as number;\n y = d[i + 3] as number;\n u = ones ^ x;\n twosB = (ones & x) | (u & y);\n ones = u ^ y;\n u = twos ^ twosA;\n foursA = (twos & twosA) | (u & twosB);\n twos = u ^ twosB;\n x = d[i + 4] as number;\n y = d[i + 5] as number;\n u = ones ^ x;\n twosA = (ones & x) | (u & y);\n ones = u ^ y;\n x = d[i + 6] as number;\n y = d[i + 7] as number;\n u = ones ^ x;\n twosB = (ones & x) | (u & y);\n ones = u ^ y;\n u = twos ^ twosA;\n foursB = (twos & twosA) | (u & twosB);\n twos = u ^ twosB;\n u = fours ^ foursA;\n const eightsA = (fours & foursA) | (u & foursB);\n fours = u ^ foursB;\n x = d[i + 8] as number;\n y = d[i + 9] as number;\n u = ones ^ x;\n twosA = (ones & x) | (u & y);\n ones = u ^ y;\n x = d[i + 10] as number;\n y = d[i + 11] as number;\n u = ones ^ x;\n twosB = (ones & x) | (u & y);\n ones = u ^ y;\n u = twos ^ twosA;\n foursA = (twos & twosA) | (u & twosB);\n twos = u ^ twosB;\n x = d[i + 12] as number;\n y = d[i + 13] as number;\n u = ones ^ x;\n twosA = (ones & x) | (u & y);\n ones = u ^ y;\n x = d[i + 14] as number;\n y = d[i + 15] as number;\n u = ones ^ x;\n twosB = (ones & x) | (u & y);\n ones = u ^ y;\n u = twos ^ twosA;\n foursB = (twos & twosA) | (u & twosB);\n twos = u ^ twosB;\n u = fours ^ foursA;\n const eightsB = (fours & foursA) | (u & foursB);\n fours = u ^ foursB;\n u = eights ^ eightsA;\n const sixteens = (eights & eightsA) | (u & eightsB);\n eights = u ^ eightsB;\n total += popcount32(sixteens);\n }\n return (\n 16 * total +\n 8 * popcount32(eights) +\n 4 * popcount32(fours) +\n 2 * popcount32(twos) +\n popcount32(ones)\n );\n}\n", "/**\n * The three Roaring containers on typed arrays, and the operations on one container or a pair of them.\n *\n * A Roaring bitmap splits a 32-bit id into a 16-bit key and a 16-bit remainder and keeps the remainders of one key in a\n * container, whose kind is chosen for its content (Chambi, Lemire, Kaser and Godin, 2016; Lemire et al., 2016 and 2018,\n * the papers credited in the package README):\n *\n * - ARRAY: the sorted remainders, a `Uint16Array`, for up to 4,096 values;\n * - BITSET: 65,536 bits, a `Uint32Array` of 2,048 words, for more than 4,096 values;\n * - RUN: `(start, length - 1)` pairs of maximal runs of consecutive remainders, a `Uint16Array`.\n *\n * A container keeps its cardinality; nothing recounts it per call. A container is a RUN because it was decoded from\n * one, because {@link optimize} chose it, because a write into a run container edited its run list, or because a\n * combine of two runs left a run, in each case while the run form is the smaller one (see {@link optimize}); removing\n * an id turns it back into an array or a bitset. A run container's storage is never written in place: a write builds a\n * new list.\n *\n * STORAGE. An ARRAY or RUN container reads its values from `data[off, off + len)` (`len` values, or `len` run pairs\n * at `off + 2 * i`), so the small containers of one decoded bitmap can sit side by side in a single `Uint16Array` (a\n * slab) instead of each holding a typed array of its own, which for a run of a few bytes costs many times its payload.\n * A BITSET always owns its 2,048 words. A container whose storage another holder can see (a slab neighbour, or a\n * snapshot taken for `encodeChunks`, or a `clone`) has `shared` set, and a write copies it first; nothing writes to\n * shared storage. A write that may go in place returns a new container object over the same storage with `shared`\n * clear; that is safe because a clone or snapshot flags the container its bitmap holds at that moment, so a flagged\n * object never sits beside an unflagged one over the same storage.\n *\n * COMBINES, by the kinds of the pair (the result kind of a pair is a written rule: an array up to 4,096 values or a\n * bitset above, except that an `or` of a run with an array stays a run while the run form is smaller (an and, andNot\n * or xor of a run with an array gives an array or a bitset), and two run containers keep\n * a run result, for every one of the four combines, while its body, `2 + 4 * runs` bytes, is strictly smaller than that array or bitset, so a combine of\n * two runs of a few long intervals does not expand them to 8 KB of words and every later operation on the result stays\n * a walk of the intervals; every run a combine writes is maximal, its runs ascending with at least one value between\n * them, as the decoder requires; a container that has no partner in the other bitmap is not combined, and `TsBitmap`\n * keeps it by reference, so a result bitmap can hold a run; `optimize` picks runs before anything is stored, so\n * stored bytes depend on the set alone):\n *\n * and or andNot\n * A A merge, or gallop when merge while the union scratch bitset from 32 values,\n * one side is 16x longer fits an array, else bits gallop when the second side is\n * (scratch bitset from 32) 16x longer, else merge\n * A B probe each value copy the bitset, set bits keep values whose bit is clear\n * B B word loop word loop word loop\n * R R interval intersection interval union interval difference\n * A R probe / range copy merge into the run list through bitset words\n * B R probe / range copy through bitset words through bitset words\n *\n * XOR is one pass per pair, not the union less the intersection: two arrays merge once, two bitsets are one word loop and\n * one count, two run lists are one walk over their boundaries, and any pair with a bitset flips the other side's bits in\n * the bitset's words (`containerXor`).\n *\n * A combine takes `inPlace` when its first operand is a bitset nothing else can see: the words are written, not copied.\n *\n * COUNTS. `containerAndCard` says how many values a pair shares, `containersIntersect` whether it shares any (stopping\n * at the first) and `containersSubset` whether every value of one is in the other (stopping at the first that is not), each\n * by the kinds of the pair and each building nothing: the answers the bitmap's counting operations are made from. The\n * last two never count.\n */\nimport { ARRAY_MAX_CARDINALITY, LITTLE_ENDIAN } from '../portable/layout';\nimport { BITSET_WORDS, popcount32, popcountWords } from '../portable/popcount';\n\n/** A container of sorted `u16` values. */\nexport const ARRAY = 0;\n/** A container of 65,536 bits. */\nexport const BITSET = 1;\n/** A container of `(start, length - 1)` pairs. */\nexport const RUN = 2;\ntype Kind = typeof ARRAY | typeof BITSET | typeof RUN;\n\n/** 32-bit words in a bitset container. */\nexport const WORDS = BITSET_WORDS;\n/** Bytes of a bitset container's body. */\nexport const BITSET_BYTES = 8_192;\n\n/** How many times longer one array must be than the other for the shorter to gallop over it instead of a linear merge (a larger factor gallops less often, which suits similar sizes better and skewed ones worse). */\nconst GALLOP_SKEW = 16;\n\nexport { LITTLE_ENDIAN };\n\n/**\n * One container. `data` is a `Uint16Array` for an array or a run container and a `Uint32Array` of {@link WORDS} words\n * for a bitset. An array's values are `data[off, off + len)` (`len` is its cardinality), a run container's pairs are\n * `data[off, off + 2 * len)` (`len` is the number of runs), and `card` is the number of values in every kind. `shared`\n * says another holder can see `data`: it is set once and a write copies instead.\n */\nexport class Container {\n constructor(\n readonly kind: Kind,\n readonly data: Uint16Array | Uint32Array,\n readonly off: number,\n readonly len: number,\n readonly card: number,\n public shared: boolean,\n ) {}\n}\n\n/** The 16-bit storage of an array or run container. */\nfunction lows16(c: Container): Uint16Array {\n return c.data as Uint16Array;\n}\n\n/** The words of a bitset container. */\nfunction words32(c: Container): Uint32Array {\n return c.data as Uint32Array;\n}\n\nexport function arrayContainer(values: Uint16Array, card: number): Container {\n return new Container(ARRAY, values, 0, card, card, false);\n}\n\nexport function bitsetContainer(words: Uint32Array, card: number): Container {\n return new Container(BITSET, words, 0, 0, card, false);\n}\n\nfunction runContainer(pairs: Uint16Array, runs: number, card: number): Container {\n return new Container(RUN, pairs, 0, runs, card, false);\n}\n\n// Scratch for results whose size is known only after they are built: a combine writes into it and copies out exactly\n// what it wrote. Single-threaded and never held across a call that could run other code, so one of each is enough.\nlet valueScratch = new Uint16Array(8_192);\nlet pairScratch = new Uint16Array(8_192);\n// The most a scratch keeps for the life of the process: one container's worth of 16-bit values. A request above it\n// gets a fresh array that is not kept.\nconst SCRATCH_KEEP = 65_536;\n\nfunction values16(n: number): Uint16Array {\n if (valueScratch.length >= n) return valueScratch;\n if (n > SCRATCH_KEEP) return new Uint16Array(n);\n valueScratch = new Uint16Array(Math.max(n, Math.min(2 * valueScratch.length, SCRATCH_KEEP)));\n return valueScratch;\n}\n\nfunction pairs16(n: number): Uint16Array {\n if (pairScratch.length >= n) return pairScratch;\n if (n > SCRATCH_KEEP) return new Uint16Array(n);\n pairScratch = new Uint16Array(Math.max(n, Math.min(2 * pairScratch.length, SCRATCH_KEEP)));\n return pairScratch;\n}\n\n/** An array container of the first `n` values of `scratch` (copied out), or `null` when there are none. */\nfunction arrayOfScratch(scratch: Uint16Array, n: number): Container | null {\n return n === 0 ? null : arrayContainer(scratch.slice(0, n), n);\n}\n\n/**\n * Set bits in the AND of two bitsets, counted as the words are read: {@link popcountWords}'s tree with each word taken\n * as `d[i] & e[i]`, so the AND is never written to memory and read back.\n */\nfunction popcountAnd(d: Uint32Array, e: Uint32Array): number {\n let total = 0;\n let ones = 0;\n let twos = 0;\n let fours = 0;\n let eights = 0;\n for (let i = 0; i < WORDS; i += 16) {\n let u: number;\n let twosA: number;\n let twosB: number;\n let foursA: number;\n let foursB: number;\n let x = (d[i] as number) & (e[i] as number);\n let y = (d[i + 1] as number) & (e[i + 1] as number);\n u = ones ^ x;\n twosA = (ones & x) | (u & y);\n ones = u ^ y;\n x = (d[i + 2] as number) & (e[i + 2] as number);\n y = (d[i + 3] as number) & (e[i + 3] as number);\n u = ones ^ x;\n twosB = (ones & x) | (u & y);\n ones = u ^ y;\n u = twos ^ twosA;\n foursA = (twos & twosA) | (u & twosB);\n twos = u ^ twosB;\n x = (d[i + 4] as number) & (e[i + 4] as number);\n y = (d[i + 5] as number) & (e[i + 5] as number);\n u = ones ^ x;\n twosA = (ones & x) | (u & y);\n ones = u ^ y;\n x = (d[i + 6] as number) & (e[i + 6] as number);\n y = (d[i + 7] as number) & (e[i + 7] as number);\n u = ones ^ x;\n twosB = (ones & x) | (u & y);\n ones = u ^ y;\n u = twos ^ twosA;\n foursB = (twos & twosA) | (u & twosB);\n twos = u ^ twosB;\n u = fours ^ foursA;\n const eightsA = (fours & foursA) | (u & foursB);\n fours = u ^ foursB;\n x = (d[i + 8] as number) & (e[i + 8] as number);\n y = (d[i + 9] as number) & (e[i + 9] as number);\n u = ones ^ x;\n twosA = (ones & x) | (u & y);\n ones = u ^ y;\n x = (d[i + 10] as number) & (e[i + 10] as number);\n y = (d[i + 11] as number) & (e[i + 11] as number);\n u = ones ^ x;\n twosB = (ones & x) | (u & y);\n ones = u ^ y;\n u = twos ^ twosA;\n foursA = (twos & twosA) | (u & twosB);\n twos = u ^ twosB;\n x = (d[i + 12] as number) & (e[i + 12] as number);\n y = (d[i + 13] as number) & (e[i + 13] as number);\n u = ones ^ x;\n twosA = (ones & x) | (u & y);\n ones = u ^ y;\n x = (d[i + 14] as number) & (e[i + 14] as number);\n y = (d[i + 15] as number) & (e[i + 15] as number);\n u = ones ^ x;\n twosB = (ones & x) | (u & y);\n ones = u ^ y;\n u = twos ^ twosA;\n foursB = (twos & twosA) | (u & twosB);\n twos = u ^ twosB;\n u = fours ^ foursA;\n const eightsB = (fours & foursA) | (u & foursB);\n fours = u ^ foursB;\n u = eights ^ eightsA;\n const sixteens = (eights & eightsA) | (u & eightsB);\n eights = u ^ eightsB;\n total += popcount32(sixteens);\n }\n return (\n 16 * total +\n 8 * popcount32(eights) +\n 4 * popcount32(fours) +\n 2 * popcount32(twos) +\n popcount32(ones)\n );\n}\n\n/** Set the bits `start` to `end`, both inclusive, in `words`. */\nfunction setRange(words: Uint32Array, start: number, end: number): void {\n const first = start >>> 5;\n const last = end >>> 5;\n const head = (0xffff_ffff << (start & 31)) >>> 0;\n const tail = 0xffff_ffff >>> (31 - (end & 31));\n if (first === last) {\n words[first] = (words[first] as number) | (head & tail);\n return;\n }\n words[first] = (words[first] as number) | head;\n for (let i = first + 1; i < last; i++) words[i] = 0xffff_ffff;\n words[last] = (words[last] as number) | tail;\n}\n\n/** Clear the bits `start` to `end`, both inclusive, in `words`. */\nfunction clearRange(words: Uint32Array, start: number, end: number): void {\n const first = start >>> 5;\n const last = end >>> 5;\n const head = (0xffff_ffff << (start & 31)) >>> 0;\n const tail = 0xffff_ffff >>> (31 - (end & 31));\n if (first === last) {\n words[first] = (words[first] as number) & ~(head & tail);\n return;\n }\n words[first] = (words[first] as number) & ~head;\n for (let i = first + 1; i < last; i++) words[i] = 0;\n words[last] = (words[last] as number) & ~tail;\n}\n\n/** Flip the bits `start` to `end`, both inclusive, in `words`. */\nfunction flipRange(words: Uint32Array, start: number, end: number): void {\n const first = start >>> 5;\n const last = end >>> 5;\n const head = (0xffff_ffff << (start & 31)) >>> 0;\n const tail = 0xffff_ffff >>> (31 - (end & 31));\n if (first === last) {\n words[first] = (words[first] as number) ^ (head & tail);\n return;\n }\n words[first] = (words[first] as number) ^ head;\n for (let i = first + 1; i < last; i++) words[i] = ~(words[i] as number);\n words[last] = (words[last] as number) ^ tail;\n}\n\n/**\n * The container holding the ascending ids `ids[from, to)`, all of one key (only the low 16 bits are kept), duplicates\n * allowed: an array up to 4,096 distinct values and a bitset above.\n */\nexport function fromSortedIds(ids: Uint32Array, from: number, to: number): Container {\n const n = to - from;\n if (n <= ARRAY_MAX_CARDINALITY) {\n const lows = new Uint16Array(n);\n let count = 0;\n let previous = -1;\n for (let i = from; i < to; i++) {\n const low = (ids[i] as number) & 0xffff;\n if (low !== previous) lows[count++] = low;\n previous = low;\n }\n return arrayContainer(count === n ? lows : lows.slice(0, count), count);\n }\n const words = new Uint32Array(WORDS);\n for (let i = from; i < to; i++) {\n const v = (ids[i] as number) & 0xffff;\n words[v >>> 5] = (words[v >>> 5] as number) | (1 << (v & 31));\n }\n return fromWordsCard(words, popcountWords(words)) as Container;\n}\n\n/** The container holding `words` (kept as the bitset's storage when it becomes one) given its cardinality, or `null` when it is 0. */\nfunction fromWordsCard(words: Uint32Array, card: number): Container | null {\n if (card === 0) return null;\n if (card > ARRAY_MAX_CARDINALITY) return bitsetContainer(words, card);\n const out = new Uint16Array(card);\n wordsToLows(words, out);\n return arrayContainer(out, card);\n}\n\n/** Write the positions of the set bits of `words`, ascending, to `out`; returns how many. */\nfunction wordsToLows(words: Uint32Array, out: Uint16Array): number {\n let k = 0;\n for (let i = 0; i < WORDS; i++) {\n let w = words[i] as number;\n const base = i * 32 + 31;\n while (w !== 0) {\n const lowest = w & -w;\n out[k++] = base - Math.clz32(lowest);\n w ^= lowest;\n }\n }\n return k;\n}\n\n/** Write the container's remainders, ascending, to `out` (which holds at least `card` of them). */\nfunction writeLows(c: Container, out: Uint16Array): void {\n if (c.kind === ARRAY) {\n out.set(lows16(c).subarray(c.off, c.off + c.len));\n } else if (c.kind === BITSET) {\n wordsToLows(words32(c), out);\n } else {\n const u16 = lows16(c);\n let k = 0;\n for (let r = 0; r < c.len; r++) {\n const start = u16[c.off + 2 * r] as number;\n const end = start + (u16[c.off + 2 * r + 1] as number);\n for (let v = start; v <= end; v++) out[k++] = v;\n }\n }\n}\n\n/** An array with fewer values than this is written out by a loop, not by a view and a copy. */\nconst SMALL_IDS = 32;\n\n/**\n * Write the container's ids, each plus `base`, ascending, to `out` from index `at`; returns the index after the last.\n * The one step a `toUint32Array` takes per container.\n */\nexport function appendIds(c: Container, out: Uint32Array, at: number, base: number): number {\n if (c.kind === ARRAY) {\n const u16 = lows16(c);\n const end = c.off + c.len;\n if (base === 0 && c.len >= SMALL_IDS) {\n // One widening copy (a short array is counted out instead: a view over it costs more than its ids).\n out.set(u16.subarray(c.off, end), at);\n return at + c.len;\n }\n for (let i = c.off; i < end; i++) out[at++] = base + (u16[i] as number);\n return at;\n }\n if (c.kind === BITSET) {\n const words = words32(c);\n for (let i = 0; i < WORDS; i++) {\n let w = words[i] as number;\n const top = base + i * 32 + 31;\n while (w !== 0) {\n const lowest = w & -w;\n out[at++] = top - Math.clz32(lowest);\n w ^= lowest;\n }\n }\n return at;\n }\n // Runs: a short run is counted out, each id written once with `base` added as it goes; a long one is one widening copy.\n const u16 = lows16(c);\n for (let r = 0; r < c.len; r++) {\n const start = u16[c.off + 2 * r] as number;\n const length = u16[c.off + 2 * r + 1] as number;\n if (length < LONG_RUN) {\n const last = base + start + length;\n for (let v = base + start; v <= last; v++) out[at++] = v;\n continue;\n }\n // `start..start + length` out of a table of 0..65,535, then `base` added where it is not 0.\n const from = at;\n out.set(iota().subarray(start, start + length + 1), at);\n at += length + 1;\n if (base !== 0) for (let i = from; i < at; i++) out[i] = (out[i] as number) + base;\n }\n return at;\n}\n\n/** A run of at least this many values (less one) is copied out of {@link iota} rather than counted out. */\nconst LONG_RUN = 48;\n\nlet iotaTable: Uint16Array | undefined;\n\n/** The numbers 0 to 65,535 as `u16`s, built when the first long run is expanded and kept. */\nfunction iota(): Uint16Array {\n if (iotaTable === undefined) {\n iotaTable = new Uint16Array(65_536);\n for (let i = 0; i < 65_536; i++) iotaTable[i] = i;\n }\n return iotaTable;\n}\n\n/**\n * The container's bits as words. A bitset's own words are returned, not a copy: a caller reads them and never writes.\n * Any other kind is expanded into a new array.\n */\nfunction toWords(c: Container): Uint32Array {\n if (c.kind === BITSET) return words32(c);\n const words = new Uint32Array(WORDS);\n const u16 = lows16(c);\n if (c.kind === ARRAY) {\n for (let i = c.off; i < c.off + c.len; i++) {\n const v = u16[i] as number;\n words[v >>> 5] = (words[v >>> 5] as number) | (1 << (v & 31));\n }\n } else {\n for (let r = 0; r < c.len; r++) {\n const start = u16[c.off + 2 * r] as number;\n setRange(words, start, start + (u16[c.off + 2 * r + 1] as number));\n }\n }\n return words;\n}\n\n/** An array or a bitset (by cardinality) with a run container's values; any other container as it is. */\nfunction demote(c: Container): Container {\n if (c.kind !== RUN) return c;\n if (c.card > ARRAY_MAX_CARDINALITY) return bitsetContainer(toWords(c), c.card);\n const out = new Uint16Array(c.card);\n writeLows(c, out);\n return arrayContainer(out, c.card);\n}\n\n/** A copy that shares nothing with `c`. */\nexport function cloneContainer(c: Container): Container {\n if (c.kind === BITSET) return bitsetContainer(words32(c).slice(), c.card);\n const copy = lows16(c).slice(c.off, c.off + (c.kind === ARRAY ? c.len : 2 * c.len));\n return new Container(c.kind, copy, 0, c.len, c.card, false);\n}\n\n/** The words `c` may write to: its own, or a copy when another holder can see them. */\nfunction writableWords(c: Container): Uint32Array {\n return c.shared ? words32(c).slice() : words32(c);\n}\n\n/** The index of the first of the `len` values at `data[off + i * stride]` that is `>= low`. */\nfunction lowerBound(\n data: Uint16Array,\n off: number,\n len: number,\n low: number,\n stride: number,\n): number {\n let lo = 0;\n let hi = len;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if ((data[off + mid * stride] as number) < low) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n}\n\n/** The index in `[from, end)` of the first of `data[off + i]` that is `>= target`, by doubling steps then a binary search; `end` if none. */\nfunction gallop(data: Uint16Array, off: number, from: number, end: number, target: number): number {\n let step = 1;\n let lo = from;\n let hi = from;\n while (hi < end && (data[off + hi] as number) < target) {\n lo = hi + 1;\n hi += step;\n step *= 2;\n }\n if (hi > end) hi = end;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if ((data[off + mid] as number) < target) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n}\n\nexport function containerHas(c: Container, low: number): boolean {\n if (c.kind === BITSET)\n return ((((c.data as Uint32Array)[low >>> 5] as number) >>> (low & 31)) & 1) === 1;\n const u16 = c.data as Uint16Array;\n if (c.kind === ARRAY) {\n const at = lowerBound(u16, c.off, c.len, low, 1);\n return at < c.len && u16[c.off + at] === low;\n }\n // The last run starting at or before `low`.\n const after = lowerBound(u16, c.off, c.len, low + 1, 2);\n if (after === 0) return false;\n const r = c.off + 2 * (after - 1);\n return low <= (u16[r] as number) + (u16[r + 1] as number);\n}\n\n/** The index of the first of the `len` runs at `data[off + 2 * i]`, from index `from`, that starts after `value`; `len` if none. */\nfunction runsAfter(\n data: Uint16Array,\n off: number,\n from: number,\n len: number,\n value: number,\n): number {\n let step = 1;\n let lo = from;\n let hi = from;\n while (hi < len && (data[off + 2 * hi] as number) <= value) {\n lo = hi + 1;\n hi += step;\n step *= 2;\n }\n if (hi > len) hi = len;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if ((data[off + 2 * mid] as number) <= value) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n}\n\n/**\n * The container for the first `runs` pairs of `pairs`, whose values number `card`: a run container (over a copy when\n * `copy`, else over `pairs` itself) while its body is strictly smaller than the plain one, the rule {@link optimize}\n * applies, and an array or a bitset otherwise.\n */\nfunction runsOrPlain(pairs: Uint16Array, runs: number, card: number, copy: boolean): Container {\n const plain = card <= ARRAY_MAX_CARDINALITY ? 2 * card : BITSET_BYTES;\n if (2 + 4 * runs < plain) {\n return runContainer(copy ? pairs.slice(0, 2 * runs) : pairs, runs, card);\n }\n return fromRunPairs(pairs, runs, card) as Container;\n}\n\n/** The run container `c` with the value `low` (which it lacks) added: the run list edited, never expanded to words. */\nfunction addToRuns(c: Container, low: number): Container {\n const u16 = lows16(c);\n // `next` is the first run that starts after `low`; the run before it, if any, ends before `low`.\n const next = runsAfter(u16, c.off, 0, c.len, low);\n const prev = next - 1;\n const joinPrev =\n prev >= 0 &&\n (u16[c.off + 2 * prev] as number) + (u16[c.off + 2 * prev + 1] as number) + 1 === low;\n const joinNext = next < c.len && (u16[c.off + 2 * next] as number) === low + 1;\n const runs = c.len + 1 - (joinPrev ? 1 : 0) - (joinNext ? 1 : 0);\n const out = new Uint16Array(2 * runs);\n const head = joinPrev ? prev : next;\n out.set(u16.subarray(c.off, c.off + 2 * head));\n let at = 2 * head;\n if (joinPrev && joinNext) {\n out[at++] = u16[c.off + 2 * prev] as number;\n out[at++] =\n (u16[c.off + 2 * next] as number) +\n (u16[c.off + 2 * next + 1] as number) -\n (u16[c.off + 2 * prev] as number);\n } else if (joinPrev) {\n out[at++] = u16[c.off + 2 * prev] as number;\n out[at++] = (u16[c.off + 2 * prev + 1] as number) + 1;\n } else if (joinNext) {\n out[at++] = low;\n out[at++] = (u16[c.off + 2 * next + 1] as number) + 1;\n } else {\n out[at++] = low;\n out[at++] = 0;\n }\n const rest = joinNext ? next + 1 : next;\n out.set(u16.subarray(c.off + 2 * rest, c.off + 2 * c.len), at);\n return runsOrPlain(out, runs, c.card + 1, false);\n}\n\n/**\n * Add `low`; returns the container that now holds it, which is `c` itself unless the kind changed or the storage had to\n * be copied. `c.card` of the result is the new cardinality either way.\n */\nexport function containerAdd(c: Container, low: number): Container {\n if (containerHas(c, low)) return c;\n if (c.kind === RUN) return addToRuns(c, low);\n if (c.kind === BITSET) {\n const words = writableWords(c);\n words[low >>> 5] = (words[low >>> 5] as number) | (1 << (low & 31));\n return bitsetContainer(words, c.card + 1);\n }\n if (c.card === ARRAY_MAX_CARDINALITY) {\n const words = toWords(c);\n words[low >>> 5] = (words[low >>> 5] as number) | (1 << (low & 31));\n return bitsetContainer(words, c.card + 1);\n }\n const old = lows16(c);\n const at = lowerBound(old, c.off, c.len, low, 1);\n let u16 = old;\n if (!c.shared && c.off === 0 && old.length > c.len) {\n u16.copyWithin(at + 1, at, c.len);\n } else {\n u16 = new Uint16Array(Math.min(ARRAY_MAX_CARDINALITY, Math.max(8, c.len * 2)));\n u16.set(old.subarray(c.off, c.off + at));\n u16.set(old.subarray(c.off + at, c.off + c.len), at + 1);\n }\n u16[at] = low;\n return arrayContainer(u16, c.card + 1);\n}\n\n/**\n * A run container with the ids `ids[from, to)` (ascending, all of one key, duplicates allowed, only the low 16 bits\n * kept) added, for a group of a few: each id is found in the run list by a gallop search and written into one working\n * copy of the list (the tail moved by a block copy), so the cost is a few searches and moves, not a walk of every run.\n * The result is the same container {@link orRunArrayWalk} gives for the same values: a run container while that is the\n * smaller form, and `c` itself when no id adds anything.\n */\nfunction addFewToRuns(c: Container, ids: Uint32Array, from: number, to: number): Container {\n const x = lows16(c);\n let data = x;\n let base = c.off;\n let out: Uint16Array | null = null;\n let n = c.len;\n let added = 0;\n for (let k = from; k < to; k++) {\n const low = (ids[k] as number) & 0xffff;\n const next = runsAfter(data, base, 0, n, low);\n const prev = next - 1;\n const prevEnd =\n prev >= 0 ? (data[base + 2 * prev] as number) + (data[base + 2 * prev + 1] as number) : -2;\n if (prevEnd >= low) continue;\n if (out === null) {\n out = new Uint16Array(2 * (c.len + to - from));\n out.set(x.subarray(c.off, c.off + 2 * c.len));\n data = out;\n base = 0;\n }\n const joinPrev = prevEnd + 1 === low;\n const joinNext = next < n && (out[2 * next] as number) === low + 1;\n if (joinPrev && joinNext) {\n out[2 * prev + 1] =\n (out[2 * next] as number) + (out[2 * next + 1] as number) - (out[2 * prev] as number);\n out.copyWithin(2 * next, 2 * next + 2, 2 * n);\n n--;\n } else if (joinPrev) {\n out[2 * prev + 1] = (out[2 * prev + 1] as number) + 1;\n } else if (joinNext) {\n out[2 * next] = low;\n out[2 * next + 1] = (out[2 * next + 1] as number) + 1;\n } else {\n out.copyWithin(2 * next + 2, 2 * next, 2 * n);\n out[2 * next] = low;\n out[2 * next + 1] = 0;\n n++;\n }\n added++;\n }\n if (out === null) return c;\n return runsOrPlain(out, n, c.card + added, true);\n}\n\n/**\n * The ids `ids[from, to)` (ascending, all of one key, duplicates allowed, only the low 16 bits kept) added to `c`; the\n * container that holds them, `c` itself when they add nothing. For a group of a few, where building a container for the\n * group and merging two containers costs more than putting each id in: a run container is edited by one search per id,\n * a bitset has its bits set (in place unless `c` is shared), an array has each id inserted. `c.card` of the result is the\n * new cardinality.\n */\nexport function containerAddSorted(\n c: Container,\n ids: Uint32Array,\n from: number,\n to: number,\n): Container {\n if (c.kind === RUN) return addFewToRuns(c, ids, from, to);\n let cur = c;\n for (let k = from; k < to; k++) cur = containerAdd(cur, (ids[k] as number) & 0xffff);\n return cur;\n}\n\n/**\n * Remove `low`; returns the container that now holds the rest, `c` itself unless the kind changed or the storage had\n * to be copied, or `null` when nothing is left.\n */\nexport function containerRemove(c: Container, low: number): Container | null {\n if (!containerHas(c, low)) return c;\n if (c.card === 1) return null;\n const plain = demote(c);\n if (plain.kind === BITSET) {\n const words = writableWords(plain);\n words[low >>> 5] = (words[low >>> 5] as number) & ~(1 << (low & 31));\n return fromWordsCard(words, plain.card - 1);\n }\n const old = lows16(plain);\n const at = lowerBound(old, plain.off, plain.len, low, 1);\n if (!plain.shared && plain.off === 0) {\n old.copyWithin(at, at + 1, plain.len);\n return arrayContainer(old, plain.card - 1);\n }\n const u16 = new Uint16Array(plain.len - 1);\n u16.set(old.subarray(plain.off, plain.off + at));\n u16.set(old.subarray(plain.off + at + 1, plain.off + plain.len), at);\n return arrayContainer(u16, plain.card - 1);\n}\n\n/** The smallest remainder in the container. */\nexport function containerMin(c: Container): number {\n if (c.kind === ARRAY || c.kind === RUN) return (c.data as Uint16Array)[c.off] as number;\n const words = words32(c);\n for (let i = 0; i < WORDS; i++) {\n const w = words[i] as number;\n if (w !== 0) return i * 32 + 31 - Math.clz32(w & -w);\n }\n throw new RangeError('a bitset container holds no bits');\n}\n\n/** The largest remainder in the container. */\nexport function containerMax(c: Container): number {\n if (c.kind === ARRAY) return (c.data as Uint16Array)[c.off + c.len - 1] as number;\n if (c.kind === RUN) {\n const u16 = c.data as Uint16Array;\n return (u16[c.off + 2 * c.len - 2] as number) + (u16[c.off + 2 * c.len - 1] as number);\n }\n const words = words32(c);\n for (let i = WORDS - 1; i >= 0; i--) {\n const w = words[i] as number;\n if (w !== 0) return i * 32 + 31 - Math.clz32(w);\n }\n throw new RangeError('a bitset container holds no bits');\n}\n\n/**\n * The number of maximal runs of consecutive values the container's values form, or any count at or above `stop` when\n * it has that many (the caller only needs to know whether runs are few enough to be worth storing).\n */\nfunction runCount(c: Container, stop: number): number {\n if (c.kind === RUN) return c.len;\n let runs = 0;\n if (c.kind === ARRAY) {\n const u16 = lows16(c);\n let previous = -2;\n for (let i = c.off; i < c.off + c.len; i++) {\n const v = u16[i] as number;\n if (v !== previous + 1 && ++runs >= stop) return runs;\n previous = v;\n }\n return runs;\n }\n // A run starts at each set bit whose lower neighbour (the previous word's top bit, for bit 0) is clear.\n const words = words32(c);\n let carry = 0;\n for (let i = 0; i < WORDS; i++) {\n const w = words[i] as number;\n const starts = w & ~((w << 1) | carry);\n // Words of all ones or none, most of a run-shaped set's, have no start: no count to take.\n if (starts !== 0) {\n runs += popcount32(starts >>> 0);\n if (runs >= stop) return runs;\n }\n carry = w >>> 31;\n }\n return runs;\n}\n\n/** `c` as a run container: the pairs of its maximal runs, `runs` of them. */\nfunction toRun(c: Container, runs: number): Container {\n const pairs = new Uint16Array(2 * runs);\n let r = 0;\n if (c.kind === ARRAY) {\n const u16 = lows16(c);\n const end = c.off + c.len;\n let i = c.off;\n while (i < end) {\n let j = i;\n while (j + 1 < end && (u16[j + 1] as number) === (u16[j] as number) + 1) j++;\n pairs[2 * r] = u16[i] as number;\n pairs[2 * r + 1] = j - i;\n r++;\n i = j + 1;\n }\n return runContainer(pairs, runs, c.card);\n }\n // A start is a set bit with a clear lower neighbour and an end a set bit with a clear upper one; read in order, the\n // two alternate across words, and a run of one value is both at once.\n const words = words32(c);\n let start = 0;\n let carry = 0;\n for (let i = 0; i < WORDS; i++) {\n const w = words[i] as number;\n const next = i + 1 < WORDS ? (words[i + 1] as number) : 0;\n let starts = (w & ~((w << 1) | carry)) >>> 0;\n let ends = (w & ~((w >>> 1) | (next << 31))) >>> 0;\n carry = w >>> 31;\n let both = starts | ends;\n while (both !== 0) {\n const bit = both & -both;\n both ^= bit;\n const at = i * 32 + 31 - Math.clz32(bit);\n if ((starts & bit) !== 0) {\n starts ^= bit;\n start = at;\n }\n if ((ends & bit) !== 0) {\n ends ^= bit;\n pairs[2 * r] = start;\n pairs[2 * r + 1] = at - start;\n r++;\n }\n }\n }\n return runContainer(pairs, runs, c.card);\n}\n\n/**\n * The canonical container for these values: a run container only when its body (`2 + 4 * runs` bytes) is strictly\n * smaller than the plain one (`2 * card` bytes for an array, 8,192 for a bitset), so a tie is an array (or bitset),\n * whatever kind the container had. It depends on the values alone, which is what makes stored bytes a function of the set.\n */\nexport function optimize(c: Container): Container {\n const plain = c.card <= ARRAY_MAX_CARDINALITY ? 2 * c.card : BITSET_BYTES;\n // Smaller than the plain body needs `2 + 4 * runs < plain`, so a count at `stop` already settles it.\n const runs = runCount(c, (plain - 2) / 4);\n if (2 + 4 * runs < plain) return c.kind === RUN ? c : toRun(c, runs);\n return demote(c);\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Combines\n// ---------------------------------------------------------------------------------------------------------------\n\n/** Whether an array of `longer` values is at least {@link GALLOP_SKEW} times as long as one of `shorter`. */\nfunction skewed(shorter: number, longer: number): boolean {\n return longer >= GALLOP_SKEW * shorter;\n}\n\n// Arrays shorter than this are merged; from here a similar-sized pair is intersected through a scratch bitset, which\n// reads both arrays once, in order, with no unpredictable branch. A lower value pays the bitset's set-and-clear for\n// pairs the merge finishes sooner; a higher one leaves mid-sized pairs on the slower merge.\nconst PROBE_MIN = 32;\n\n// How many merge steps `intersectsArrays` takes before it falls back to the scratch bitset. The value is chosen, not measured to\n// be the best: a pair that shares a value inside the first steps answers without setting a bit, and a pair that shares nothing\n// there pays the steps and then the scratch bitset. Two random sets of a thousand values in one chunk share about 15 values\n// (derived), so most such pairs share none in 64 steps and reach the bitset; probes of 320 steps made the overlapping pair\n// about four times faster and the disjoint pair about 30 percent slower (indicative), and neither is kept.\nexport const MERGE_FIRST = 64;\n\n// Scratch bitset for the array probe: all zero between calls (each call clears what it set).\nconst probeWords = new Uint32Array(WORDS);\n\n/** Values both arrays hold. */\nfunction andArrays(a: Container, b: Container): Container | null {\n const small = a.len <= b.len ? a : b;\n const big = small === a ? b : a;\n const s = lows16(small);\n const l = lows16(big);\n const out = values16(small.len);\n let n = 0;\n if (small.len >= PROBE_MIN && !skewed(small.len, big.len)) {\n const se = small.off + small.len;\n const first = s[small.off] as number;\n const last = s[se - 1] as number;\n // Only the span of `big` between the shorter array's ends can hold a match.\n const le = big.off + big.len;\n if (last < (l[big.off] as number) || first > (l[le - 1] as number)) return null;\n const from = gallop(l, 0, big.off, le, first);\n const to = gallop(l, 0, from, le, last + 1);\n const words = probeWords;\n for (let i = small.off; i < se; i++) {\n const v = s[i] as number;\n words[v >>> 5] = (words[v >>> 5] as number) | (1 << (v & 31));\n }\n for (let j = from; j < to; j++) {\n const v = l[j] as number;\n // The slot is written whether or not `v` is in the set; only a hit moves `n` past it.\n out[n] = v;\n n += ((words[v >>> 5] as number) >>> (v & 31)) & 1;\n }\n for (let i = small.off; i < se; i++) words[(s[i] as number) >>> 5] = 0;\n return arrayOfScratch(out, n);\n }\n if (skewed(small.len, big.len)) {\n let at = 0;\n const end = big.off + big.len;\n for (let i = small.off; i < small.off + small.len; i++) {\n const v = s[i] as number;\n at = gallop(l, 0, Math.max(at, big.off), end, v);\n if (at === end) break;\n if (l[at] === v) out[n++] = v;\n }\n return arrayOfScratch(out, n);\n }\n let i = small.off;\n let j = big.off;\n const ie = small.off + small.len;\n const je = big.off + big.len;\n while (i < ie && j < je) {\n const x = s[i] as number;\n const y = l[j] as number;\n // No branch on the comparison: it is unpredictable on random data, and a misprediction costs more than the\n // three adds. The slot is written whether or not the values match; only a match moves `n` past it.\n out[n] = x;\n n += x === y ? 1 : 0;\n i += x <= y ? 1 : 0;\n j += x >= y ? 1 : 0;\n }\n return arrayOfScratch(out, n);\n}\n\n/** The values of array `a` whose membership in `b` (a bitset) is `keep`. */\nfunction filterByBits(a: Container, b: Container, keep: boolean): Container | null {\n const u16 = lows16(a);\n const words = words32(b);\n const out = values16(a.len);\n const flip = keep ? 0 : 1;\n let n = 0;\n for (let i = a.off; i < a.off + a.len; i++) {\n const v = u16[i] as number;\n // Written whether or not `v` is kept; only a kept value moves `n` past its slot (no unpredictable branch).\n out[n] = v;\n n += (((words[v >>> 5] as number) >>> (v & 31)) & 1) ^ flip;\n }\n return arrayOfScratch(out, n);\n}\n\n/** The values of array `a` whose membership in the runs of `b` is `keep`. */\nfunction filterByRuns(a: Container, b: Container, keep: boolean): Container | null {\n const u16 = lows16(a);\n const pairs = lows16(b);\n const out = values16(a.len);\n let n = 0;\n // Walking the runs costs one step per run and per value, so it wins once values are at least as many as runs; with\n // fewer values the per-value walk skips the runs it does not need to visit.\n if (keep && a.len >= b.len) {\n // At least as many values as runs: walk the runs, skipping the values below each and copying those inside it.\n const ae = a.off + a.len;\n let i = a.off;\n for (let r = 0; r < b.len && i < ae; r++) {\n const start = pairs[b.off + 2 * r] as number;\n const end = start + (pairs[b.off + 2 * r + 1] as number);\n while (i < ae && (u16[i] as number) < start) i++;\n while (i < ae && (u16[i] as number) <= end) out[n++] = u16[i++] as number;\n }\n return arrayOfScratch(out, n);\n }\n let r = 0;\n for (let i = a.off; i < a.off + a.len; i++) {\n const v = u16[i] as number;\n // The first run that ends at or after `v`.\n while (\n r < b.len &&\n (pairs[b.off + 2 * r] as number) + (pairs[b.off + 2 * r + 1] as number) < v\n ) {\n r++;\n }\n const inside = r < b.len && (pairs[b.off + 2 * r] as number) <= v;\n if (inside === keep) out[n++] = v;\n }\n return arrayOfScratch(out, n);\n}\n\n/** The values of `a` that `b` lacks, both arrays. */\nfunction andNotArrays(a: Container, b: Container): Container | null {\n const x = lows16(a);\n const y = lows16(b);\n const out = values16(a.len);\n let n = 0;\n const je = b.off + b.len;\n if (skewed(a.len, b.len)) {\n let at = b.off;\n for (let i = a.off; i < a.off + a.len; i++) {\n const v = x[i] as number;\n at = gallop(y, 0, at, je, v);\n if (at === je || y[at] !== v) out[n++] = v;\n }\n return arrayOfScratch(out, n);\n }\n if (b.len >= PROBE_MIN) {\n // Similar sizes: mark the part of `b` inside `a`'s span in the scratch bitset, then keep each value of `a` whose bit\n // is clear. Both arrays are read once, in order, with no unpredictable branch.\n const ae = a.off + a.len;\n const first = x[a.off] as number;\n const last = x[ae - 1] as number;\n const from = gallop(y, 0, b.off, je, first);\n const to = gallop(y, 0, from, je, last + 1);\n const words = probeWords;\n for (let j = from; j < to; j++) {\n const v = y[j] as number;\n words[v >>> 5] = (words[v >>> 5] as number) | (1 << (v & 31));\n }\n for (let i = a.off; i < ae; i++) {\n const v = x[i] as number;\n // Written whether or not `v` is kept; only a kept value moves `n` past its slot.\n out[n] = v;\n n += (((words[v >>> 5] as number) >>> (v & 31)) & 1) ^ 1;\n }\n for (let j = from; j < to; j++) words[(y[j] as number) >>> 5] = 0;\n return arrayOfScratch(out, n);\n }\n let i = a.off;\n let j = b.off;\n const ie = a.off + a.len;\n while (i < ie && j < je) {\n const p = x[i] as number;\n const q = y[j] as number;\n out[n] = p;\n n += p < q ? 1 : 0;\n i += p <= q ? 1 : 0;\n j += p >= q ? 1 : 0;\n }\n while (i < ie) out[n++] = x[i++] as number;\n return arrayOfScratch(out, n);\n}\n\n/** The values either array holds. */\nfunction orArrays(a: Container, b: Container): Container {\n const x = lows16(a);\n const y = lows16(b);\n const ie = a.off + a.len;\n const je = b.off + b.len;\n if (a.len + b.len > ARRAY_MAX_CARDINALITY) {\n const words = new Uint32Array(WORDS);\n for (let i = a.off; i < ie; i++) {\n const v = x[i] as number;\n words[v >>> 5] = (words[v >>> 5] as number) | (1 << (v & 31));\n }\n for (let j = b.off; j < je; j++) {\n const v = y[j] as number;\n words[v >>> 5] = (words[v >>> 5] as number) | (1 << (v & 31));\n }\n return fromWordsCard(words, popcountWords(words)) as Container;\n }\n const out = values16(a.len + b.len);\n let n = 0;\n let i = a.off;\n let j = b.off;\n while (i < ie && j < je) {\n const p = x[i] as number;\n const q = y[j] as number;\n out[n++] = p < q ? p : q;\n i += p <= q ? 1 : 0;\n j += p >= q ? 1 : 0;\n }\n while (i < ie) out[n++] = x[i++] as number;\n while (j < je) out[n++] = y[j++] as number;\n return arrayOfScratch(out, n) as Container;\n}\n\n/** `out` = `x` AND `y` over WORDS words, four a step; `out` may be `x` or `y`. */\nfunction andWords(out: Uint32Array, x: Uint32Array, y: Uint32Array): void {\n for (let i = 0; i < WORDS; i += 4) {\n const X0 = x[i] as number;\n const Y0 = y[i] as number;\n const X1 = x[i + 1] as number;\n const Y1 = y[i + 1] as number;\n const X2 = x[i + 2] as number;\n const Y2 = y[i + 2] as number;\n const X3 = x[i + 3] as number;\n const Y3 = y[i + 3] as number;\n out[i] = X0 & Y0;\n out[i + 1] = X1 & Y1;\n out[i + 2] = X2 & Y2;\n out[i + 3] = X3 & Y3;\n }\n}\n\n/** `out` = `x` OR `y` over WORDS words, four a step; `out` may be `x` or `y`. */\nfunction orWords(out: Uint32Array, x: Uint32Array, y: Uint32Array): void {\n for (let i = 0; i < WORDS; i += 4) {\n const X0 = x[i] as number;\n const Y0 = y[i] as number;\n const X1 = x[i + 1] as number;\n const Y1 = y[i + 1] as number;\n const X2 = x[i + 2] as number;\n const Y2 = y[i + 2] as number;\n const X3 = x[i + 3] as number;\n const Y3 = y[i + 3] as number;\n out[i] = X0 | Y0;\n out[i + 1] = X1 | Y1;\n out[i + 2] = X2 | Y2;\n out[i + 3] = X3 | Y3;\n }\n}\n\n/** `out` = `x` XOR `y` over WORDS words, four a step; `out` may be `x` or `y`. */\nfunction xorWords(out: Uint32Array, x: Uint32Array, y: Uint32Array): void {\n for (let i = 0; i < WORDS; i += 4) {\n const X0 = x[i] as number;\n const Y0 = y[i] as number;\n const X1 = x[i + 1] as number;\n const Y1 = y[i + 1] as number;\n const X2 = x[i + 2] as number;\n const Y2 = y[i + 2] as number;\n const X3 = x[i + 3] as number;\n const Y3 = y[i + 3] as number;\n out[i] = X0 ^ Y0;\n out[i + 1] = X1 ^ Y1;\n out[i + 2] = X2 ^ Y2;\n out[i + 3] = X3 ^ Y3;\n }\n}\n\n/** `out` = `x` AND NOT `y` over WORDS words, four a step; `out` may be `x` or `y`. */\nfunction andNotWords(out: Uint32Array, x: Uint32Array, y: Uint32Array): void {\n for (let i = 0; i < WORDS; i += 4) {\n const X0 = x[i] as number;\n const Y0 = y[i] as number;\n const X1 = x[i + 1] as number;\n const Y1 = y[i + 1] as number;\n const X2 = x[i + 2] as number;\n const Y2 = y[i + 2] as number;\n const X3 = x[i + 3] as number;\n const Y3 = y[i + 3] as number;\n out[i] = X0 & ~Y0;\n out[i + 1] = X1 & ~Y1;\n out[i + 2] = X2 & ~Y2;\n out[i + 3] = X3 & ~Y3;\n }\n}\n\n/** `dest` (a bitset) or `other`, into words: `dest`'s own words when `inPlace`, else a copy. */\nfunction orIntoBitset(dest: Container, other: Container, inPlace: boolean): Container {\n const words = inPlace ? words32(dest) : words32(dest).slice();\n if (other.kind === ARRAY) {\n const u16 = lows16(other);\n let card = dest.card;\n for (let i = other.off; i < other.off + other.len; i++) {\n const v = u16[i] as number;\n const w = words[v >>> 5] as number;\n const bit = 1 << (v & 31);\n if ((w & bit) === 0) {\n words[v >>> 5] = w | bit;\n card++;\n }\n }\n return bitsetContainer(words, card);\n }\n if (other.kind === BITSET) {\n orWords(words, words, words32(other));\n } else {\n const pairs = lows16(other);\n for (let r = 0; r < other.len; r++) {\n const start = pairs[other.off + 2 * r] as number;\n setRange(words, start, start + (pairs[other.off + 2 * r + 1] as number));\n }\n }\n return bitsetContainer(words, popcountWords(words));\n}\n\n/**\n * A new accumulator holding the OR of the bitset containers of `list` (all zero when there is none), four sources a\n * step: each word is loaded from the accumulator once per four sources, not once per source, and the first group writes\n * the accumulator, so no source is copied. Fewer than four sources, and the tail of any more, go one at a time.\n */\nfunction orBitsetWords(list: readonly Container[]): Uint32Array {\n const bits: Uint32Array[] = [];\n for (const c of list) if (c.kind === BITSET) bits.push(words32(c));\n const n = bits.length;\n if (n === 0) return new Uint32Array(WORDS);\n let k: number;\n let words: Uint32Array;\n if (n >= 4) {\n const a = bits[0] as Uint32Array;\n const b = bits[1] as Uint32Array;\n const c = bits[2] as Uint32Array;\n const d = bits[3] as Uint32Array;\n words = new Uint32Array(WORDS);\n for (let i = 0; i < WORDS; i++)\n words[i] = (a[i] as number) | (b[i] as number) | (c[i] as number) | (d[i] as number);\n k = 4;\n } else {\n words = (bits[0] as Uint32Array).slice();\n k = 1;\n }\n for (; k + 4 <= n; k += 4) {\n const a = bits[k] as Uint32Array;\n const b = bits[k + 1] as Uint32Array;\n const c = bits[k + 2] as Uint32Array;\n const d = bits[k + 3] as Uint32Array;\n for (let i = 0; i < WORDS; i++) {\n words[i] =\n (words[i] as number) |\n (a[i] as number) |\n (b[i] as number) |\n (c[i] as number) |\n (d[i] as number);\n }\n }\n for (; k < n; k++) {\n const o = bits[k] as Uint32Array;\n for (let i = 0; i < WORDS; i++) words[i] = (words[i] as number) | (o[i] as number);\n }\n return words;\n}\n\n/**\n * The values of every container of `list` (two or more, all of one key), as a container of its own: an array up to\n * 4,096 values, a bitset above, never a run. No input is written and none is kept. Arrays whose total fits an array are\n * sorted together; anything else is OR-ed into one accumulator of words (a bitset's words, an array's values set\n * bit by bit, a run's range filled) whose bits are counted once at the end, where a pairwise fold would count the\n * whole accumulator after every input.\n */\nexport function orManyContainers(list: readonly Container[]): Container {\n let total = 0;\n let allArrays = true;\n for (const c of list) {\n total += c.card;\n if (c.kind !== ARRAY) allArrays = false;\n }\n if (allArrays && total <= ARRAY_MAX_CARDINALITY) {\n const out = values16(total);\n let n = 0;\n for (const c of list) {\n out.set(lows16(c).subarray(c.off, c.off + c.len), n);\n n += c.len;\n }\n const sorted = out.subarray(0, n).sort();\n let distinct = 0;\n for (let i = 0; i < n; i++) {\n const v = sorted[i] as number;\n if (i === 0 || v !== (sorted[distinct - 1] as number)) sorted[distinct++] = v;\n }\n return arrayContainer(sorted.slice(0, distinct), distinct);\n }\n const words = orBitsetWords(list);\n for (const c of list) {\n if (c.kind === ARRAY) {\n const u16 = lows16(c);\n for (let i = c.off; i < c.off + c.len; i++) {\n const v = u16[i] as number;\n words[v >>> 5] = (words[v >>> 5] as number) | (1 << (v & 31));\n }\n } else if (c.kind === RUN) {\n const pairs = lows16(c);\n for (let r = 0; r < c.len; r++) {\n const start = pairs[c.off + 2 * r] as number;\n setRange(words, start, start + (pairs[c.off + 2 * r + 1] as number));\n }\n }\n }\n return fromWordsCard(words, popcountWords(words)) as Container;\n}\n\n/** A result built from the first `runs` pairs of `pairs`, whose values number `card`: an array up to 4,096 values, else a bitset. */\nfunction fromRunPairs(pairs: Uint16Array, runs: number, card: number): Container | null {\n if (card === 0) return null;\n if (card <= ARRAY_MAX_CARDINALITY) {\n const out = new Uint16Array(card);\n let k = 0;\n for (let r = 0; r < runs; r++) {\n const start = pairs[2 * r] as number;\n const end = start + (pairs[2 * r + 1] as number);\n for (let v = start; v <= end; v++) out[k++] = v;\n }\n return arrayContainer(out, card);\n }\n const words = new Uint32Array(WORDS);\n for (let r = 0; r < runs; r++) {\n const start = pairs[2 * r] as number;\n setRange(words, start, start + (pairs[2 * r + 1] as number));\n }\n return bitsetContainer(words, card);\n}\n\n/** The values both run containers hold. */\nfunction andRuns(a: Container, b: Container): Container | null {\n const x = lows16(a);\n const y = lows16(b);\n const out = pairs16(2 * (a.len + b.len));\n let runs = 0;\n let card = 0;\n let i = 0;\n let j = 0;\n while (i < a.len && j < b.len) {\n const as = x[a.off + 2 * i] as number;\n const ae = as + (x[a.off + 2 * i + 1] as number);\n const bs = y[b.off + 2 * j] as number;\n const be = bs + (y[b.off + 2 * j + 1] as number);\n const lo = as > bs ? as : bs;\n const hi = ae < be ? ae : be;\n if (lo <= hi) {\n out[2 * runs] = lo;\n out[2 * runs + 1] = hi - lo;\n runs++;\n card += hi - lo + 1;\n }\n if (ae < be) i++;\n else j++;\n }\n return card === 0 ? null : runsOrPlain(out, runs, card, true);\n}\n\n/** The values either run container holds. */\nfunction orRuns(a: Container, b: Container): Container {\n const x = lows16(a);\n const y = lows16(b);\n const out = pairs16(2 * (a.len + b.len));\n let runs = 0;\n let card = 0;\n let i = 0;\n let j = 0;\n let start = -1;\n let end = -1;\n const flush = (): void => {\n if (start < 0) return;\n out[2 * runs] = start;\n out[2 * runs + 1] = end - start;\n runs++;\n card += end - start + 1;\n };\n while (i < a.len || j < b.len) {\n let s: number;\n let e: number;\n if (j >= b.len || (i < a.len && (x[a.off + 2 * i] as number) <= (y[b.off + 2 * j] as number))) {\n s = x[a.off + 2 * i] as number;\n e = s + (x[a.off + 2 * i + 1] as number);\n i++;\n } else {\n s = y[b.off + 2 * j] as number;\n e = s + (y[b.off + 2 * j + 1] as number);\n j++;\n }\n if (start >= 0 && s <= end + 1) {\n if (e > end) end = e;\n } else {\n flush();\n start = s;\n end = e;\n }\n }\n flush();\n return runsOrPlain(out, runs, card, true);\n}\n\n/** The values of `a` that `b` lacks, both run containers. */\nfunction andNotRuns(a: Container, b: Container): Container | null {\n const x = lows16(a);\n const y = lows16(b);\n const out = pairs16(2 * (a.len + b.len + 1));\n let runs = 0;\n let card = 0;\n let j = 0;\n for (let i = 0; i < a.len; i++) {\n let s = x[a.off + 2 * i] as number;\n const e = s + (x[a.off + 2 * i + 1] as number);\n while (j < b.len && (y[b.off + 2 * j] as number) + (y[b.off + 2 * j + 1] as number) < s) j++;\n let k = j;\n while (s <= e) {\n if (k >= b.len || (y[b.off + 2 * k] as number) > e) {\n out[2 * runs] = s;\n out[2 * runs + 1] = e - s;\n runs++;\n card += e - s + 1;\n break;\n }\n const bs = y[b.off + 2 * k] as number;\n const be = bs + (y[b.off + 2 * k + 1] as number);\n if (bs > s) {\n out[2 * runs] = s;\n out[2 * runs + 1] = bs - 1 - s;\n runs++;\n card += bs - s;\n }\n s = be + 1;\n k++;\n }\n }\n return card === 0 ? null : runsOrPlain(out, runs, card, true);\n}\n\n/**\n * The values of bitset `a` inside the runs of `b`. Only the words a run covers are read, each masked to the run's ends.\n * A run container of at most 4,096 values cannot produce more than an array holds, so its result is written straight to\n * an array (no 8 KiB bitset, no popcount); a larger one is built as words and counted once, with Harley-Seal, which\n * beats counting each covered word when the runs cover many of them.\n */\nfunction bitsetInRuns(a: Container, b: Container): Container | null {\n const words = words32(a);\n const pairs = lows16(b);\n if (b.card <= ARRAY_MAX_CARDINALITY) {\n const out = values16(b.card);\n let n = 0;\n for (let r = 0; r < b.len; r++) {\n const start = pairs[b.off + 2 * r] as number;\n const end = start + (pairs[b.off + 2 * r + 1] as number);\n const first = start >>> 5;\n const last = end >>> 5;\n const head = (0xffff_ffff << (start & 31)) >>> 0;\n const tail = 0xffff_ffff >>> (31 - (end & 31));\n for (let i = first; i <= last; i++) {\n let w = words[i] as number;\n if (i === first) w &= head;\n if (i === last) w &= tail;\n const top = i * 32 + 31;\n while (w !== 0) {\n const lowest = w & -w;\n out[n++] = top - Math.clz32(lowest);\n w ^= lowest;\n }\n }\n }\n return arrayOfScratch(out, n);\n }\n const out = new Uint32Array(WORDS);\n for (let r = 0; r < b.len; r++) {\n const start = pairs[b.off + 2 * r] as number;\n const end = start + (pairs[b.off + 2 * r + 1] as number);\n const first = start >>> 5;\n const last = end >>> 5;\n const head = (0xffff_ffff << (start & 31)) >>> 0;\n const tail = 0xffff_ffff >>> (31 - (end & 31));\n if (first === last) {\n out[first] = (out[first] as number) | ((words[first] as number) & head & tail);\n } else {\n out[first] = (out[first] as number) | ((words[first] as number) & head);\n for (let i = first + 1; i < last; i++) out[i] = words[i] as number;\n out[last] = (out[last] as number) | ((words[last] as number) & tail);\n }\n }\n return fromWordsCard(out, popcountWords(out));\n}\n\n/** The values both hold, or `null` when there are none. Neither operand is changed unless `inPlace` and `a` is a bitset (see the module comment). */\nexport function containerAnd(a: Container, b: Container, inPlace = false): Container | null {\n if (a.kind === BITSET && b.kind === BITSET) {\n const x = words32(a);\n const y = words32(b);\n const out = inPlace ? x : new Uint32Array(WORDS);\n andWords(out, x, y);\n return fromWordsCard(out, popcountWords(out));\n }\n // Commutative: put the lower kind first (array, bitset, run).\n if (a.kind > b.kind) return containerAnd(b, a);\n if (a.kind === ARRAY) {\n if (b.kind === ARRAY) return andArrays(a, b);\n return b.kind === BITSET ? filterByBits(a, b, true) : filterByRuns(a, b, true);\n }\n return b.kind === RUN && a.kind === RUN ? andRuns(a, b) : bitsetInRuns(a, b);\n}\n\n/** The values either holds. */\nexport function containerOr(a: Container, b: Container, inPlace = false): Container {\n if (a.kind === BITSET) return orIntoBitset(a, b, inPlace);\n if (b.kind === BITSET) return orIntoBitset(b, a, false);\n if (a.kind === ARRAY && b.kind === ARRAY) return orArrays(a, b);\n if (a.kind === RUN && b.kind === RUN) return orRuns(a, b);\n return a.kind === RUN ? orRunArray(a, b, inPlace) : orRunArray(b, a, false);\n}\n\n/**\n * How many steps of the merge walk (the runs plus the values) a run container and an array take before expanding the run\n * container to words is the cheaper way to write the array into it: the walk costs a few nanoseconds a step, the\n * expansion a fixed 8 KB of words (zeroed, one range set per run, one pass to count the runs of the result).\n */\nexport const EXPAND_MIN_STEPS = 1024;\n\n/**\n * Whether {@link orRunArray} writes the array into the run container through words instead of the merge walk: from\n * {@link EXPAND_MIN_STEPS} steps up, and when the result is likely not to be a run container. The result has at most\n * `runs.len + array.len` runs, so when that many runs already fail the size rule against the plain body of the largest\n * result, the walk would probably build a run list only to expand it again; the result can have far fewer runs than that\n * bound (values that fall inside runs add none), so this is a heuristic about speed. A pure function of the two containers' lengths and\n * cardinalities, so it costs one comparison on the hot path; either choice returns the same container.\n */\nexport function expandsRunArray(runs: Container, array: Container): boolean {\n return expandsRunSteps(runs, array.len);\n}\n\n/**\n * {@link expandsRunArray} for a run container and `values` values to write into it: the one size rule, on numbers, so a\n * walk that reads its values from an id list and one that reads an array container choose alike.\n */\nexport function expandsRunSteps(runs: Container, values: number): boolean {\n const steps = runs.len + values;\n if (steps < EXPAND_MIN_STEPS) return false;\n const cardMax = runs.card + values;\n const plainMax = cardMax <= ARRAY_MAX_CARDINALITY ? 2 * cardMax : BITSET_BYTES;\n return 2 + 4 * steps >= plainMax;\n}\n\n/**\n * Whether a group of `count` ids goes into the run container `runs` by {@link orRunIdsWalk}: the size rule sends it to\n * the merge walk. The rule refuses from 2,048 steps (the runs plus the ids) up, since `2 + 4 * steps >= 8192` first holds there (2,047\n * steps still walk), so the walk takes at most 2,046 ids for one run, fewer for more runs, and fewer\n * again when the result is small enough for the plain body to be an array. Every other group takes the container merge.\n */\nexport function walksRunIds(runs: Container, count: number): boolean {\n return runs.kind === RUN && !expandsRunSteps(runs, count);\n}\n\n/**\n * A run container with an array's values written through words: the runs are set in a new bitset, then each value, and\n * the container of the result is the canonical one for its values (a run container only when its body is the smaller\n * one: {@link optimize}). When the array adds nothing and `keep` allows, the run container itself is the result.\n */\nexport function orRunArrayExpand(runs: Container, array: Container, keep: boolean): Container {\n const words = toWords(runs);\n const v = lows16(array);\n let added = 0;\n for (let i = array.off; i < array.off + array.len; i++) {\n const value = v[i] as number;\n const word = words[value >>> 5] as number;\n const bit = 1 << (value & 31);\n if ((word & bit) === 0) {\n words[value >>> 5] = word | bit;\n added++;\n }\n }\n if (added === 0 && keep) return runs;\n return optimize(fromWordsCard(words, runs.card + added) as Container);\n}\n\n/** A run container with an array's values: by the merge walk, or through words when that is cheaper (see {@link expandsRunArray}). */\nfunction orRunArray(runs: Container, array: Container, keep: boolean): Container {\n return expandsRunArray(runs, array)\n ? orRunArrayExpand(runs, array, keep)\n : orRunArrayWalk(runs, array, keep);\n}\n\n/**\n * A run container with an array's values, merged in one walk over both lists: each step takes whichever of the next run\n * and the next value starts first and appends it to the result, joining it to the pair being built when they touch or\n * overlap. Cost is the runs plus the values, with no search or view per value, and no expansion to 8 KB of words. The\n * result is a run container while that is the smaller form (see {@link runsOrPlain}). When the array adds nothing and\n * `keep` allows, the run container itself is the result: runs are never written in place, so aliasing it is safe.\n */\nexport function orRunArrayWalk(runs: Container, array: Container, keep: boolean): Container {\n const x = lows16(runs);\n const v = lows16(array);\n const out = pairs16(2 * (runs.len + array.len));\n const runEnd = runs.off + 2 * runs.len;\n const valueEnd = array.off + array.len;\n let r = runs.off;\n let vi = array.off;\n let at = 0;\n // The pair being built, `[from, to]`; `to` is -2 before there is one, so nothing is next to it.\n let from = 0;\n let to = -2;\n let added = 0;\n while (vi < valueEnd) {\n const value = v[vi++] as number;\n // Every run that starts at or before the value comes first; one that reaches it holds it.\n while (r < runEnd && (x[r] as number) <= value) {\n const start = x[r] as number;\n const end = start + (x[r + 1] as number);\n r += 2;\n if (start <= to + 1) {\n if (end > to) to = end;\n } else {\n if (to >= 0) {\n out[at++] = from;\n out[at++] = to - from;\n }\n from = start;\n to = end;\n }\n }\n if (value <= to) continue;\n added++;\n if (value === to + 1) {\n to = value;\n } else {\n if (to >= 0) {\n out[at++] = from;\n out[at++] = to - from;\n }\n from = value;\n to = value;\n }\n }\n while (r < runEnd) {\n const start = x[r] as number;\n const end = start + (x[r + 1] as number);\n r += 2;\n if (start <= to + 1) {\n if (end > to) to = end;\n } else {\n if (to >= 0) {\n out[at++] = from;\n out[at++] = to - from;\n }\n from = start;\n to = end;\n }\n }\n out[at++] = from;\n out[at++] = to - from;\n if (added === 0 && keep) return runs;\n return runsOrPlain(out, at >>> 1, runs.card + added, true);\n}\n\n/**\n * The ids `ids[from, to)` (ascending, all of one key, duplicates allowed, only the low 16 bits kept) written into a run\n * container by the merge walk of {@link orRunArrayWalk}, reading the ids where they are instead of from a container\n * built for them. The same walk, so the result is the same container for the same values; `runs` itself when the ids add\n * nothing. A copy of the walk, not a shared one: each walk reads one kind of array (16-bit values here, 32-bit ids\n * there), so its element reads stay of one kind for the engine, where a shared walk would see both. A test holds the\n * two to the same container for the same values.\n */\nexport function orRunIdsWalk(\n runs: Container,\n ids: Uint32Array,\n from: number,\n to: number,\n): Container {\n const x = lows16(runs);\n const out = pairs16(2 * (runs.len + to - from));\n const runEnd = runs.off + 2 * runs.len;\n let r = runs.off;\n let vi = from;\n let at = 0;\n // The pair being built, `[start, last]`; `last` is -2 before there is one, so nothing is next to it.\n let start = 0;\n let last = -2;\n let added = 0;\n while (vi < to) {\n const value = (ids[vi++] as number) & 0xffff;\n while (r < runEnd && (x[r] as number) <= value) {\n const s = x[r] as number;\n const end = s + (x[r + 1] as number);\n r += 2;\n if (s <= last + 1) {\n if (end > last) last = end;\n } else {\n if (last >= 0) {\n out[at++] = start;\n out[at++] = last - start;\n }\n start = s;\n last = end;\n }\n }\n if (value <= last) continue;\n added++;\n if (value === last + 1) {\n last = value;\n } else {\n if (last >= 0) {\n out[at++] = start;\n out[at++] = last - start;\n }\n start = value;\n last = value;\n }\n }\n while (r < runEnd) {\n const s = x[r] as number;\n const end = s + (x[r + 1] as number);\n r += 2;\n if (s <= last + 1) {\n if (end > last) last = end;\n } else {\n if (last >= 0) {\n out[at++] = start;\n out[at++] = last - start;\n }\n start = s;\n last = end;\n }\n }\n out[at++] = start;\n out[at++] = last - start;\n if (added === 0) return runs;\n return runsOrPlain(out, at >>> 1, runs.card + added, true);\n}\n\n/** The values of `a` that `b` lacks, or `null` when there are none. */\nexport function containerAndNot(a: Container, b: Container, inPlace = false): Container | null {\n if (a.kind === ARRAY) {\n if (b.kind === ARRAY) return andNotArrays(a, b);\n return b.kind === BITSET ? filterByBits(a, b, false) : filterByRuns(a, b, false);\n }\n if (a.kind === RUN && b.kind === RUN) return andNotRuns(a, b);\n // A bitset, or a run container expanded to words (which it owns).\n const words = a.kind === BITSET ? (inPlace ? words32(a) : words32(a).slice()) : toWords(a);\n if (b.kind === ARRAY) {\n const u16 = lows16(b);\n for (let i = b.off; i < b.off + b.len; i++) {\n const v = u16[i] as number;\n words[v >>> 5] = (words[v >>> 5] as number) & ~(1 << (v & 31));\n }\n } else if (b.kind === BITSET) {\n andNotWords(words, words, words32(b));\n } else {\n const pairs = lows16(b);\n for (let r = 0; r < b.len; r++) {\n const start = pairs[b.off + 2 * r] as number;\n clearRange(words, start, start + (pairs[b.off + 2 * r + 1] as number));\n }\n }\n return fromWordsCard(words, popcountWords(words));\n}\n\n/** The values exactly one array holds: one merge that drops a value both hold. */\nfunction xorArrays(a: Container, b: Container): Container | null {\n const x = lows16(a);\n const y = lows16(b);\n const ie = a.off + a.len;\n const je = b.off + b.len;\n const out = values16(a.len + b.len);\n let n = 0;\n let i = a.off;\n let j = b.off;\n while (i < ie && j < je) {\n const p = x[i] as number;\n const q = y[j] as number;\n out[n] = p < q ? p : q;\n // A value both hold is written over by the next one.\n n += p === q ? 0 : 1;\n i += p <= q ? 1 : 0;\n j += p >= q ? 1 : 0;\n }\n while (i < ie) out[n++] = x[i++] as number;\n while (j < je) out[n++] = y[j++] as number;\n if (n <= ARRAY_MAX_CARDINALITY) return arrayOfScratch(out, n);\n const words = new Uint32Array(WORDS);\n for (let k = 0; k < n; k++) {\n const v = out[k] as number;\n words[v >>> 5] = (words[v >>> 5] as number) | (1 << (v & 31));\n }\n return bitsetContainer(words, n);\n}\n\n/**\n * The values exactly one run container holds, as one walk over the run boundaries of both. A run `(start, length - 1)`\n * opens at `start` and closes at `start + length`; the boundaries of one list ascend strictly (its runs neither touch\n * nor overlap), and a boundary both lists have cancels, so what is left alternates open, close and any two pieces that\n * touch have already joined.\n */\nfunction xorRuns(a: Container, b: Container): Container | null {\n const x = lows16(a);\n const y = lows16(b);\n const na = 2 * a.len;\n const nb = 2 * b.len;\n const out = pairs16(2 * (a.len + b.len));\n const NONE = 0x7fff_ffff;\n let i = 0;\n let j = 0;\n let pa = na > 0 ? boundary(x, a.off, 0) : NONE;\n let pb = nb > 0 ? boundary(y, b.off, 0) : NONE;\n let open = -1;\n let runs = 0;\n let card = 0;\n while (i < na || j < nb) {\n let p: number;\n if (pa === pb) {\n // The boundary is in both lists: it cancels.\n i++;\n j++;\n pa = i < na ? boundary(x, a.off, i) : NONE;\n pb = j < nb ? boundary(y, b.off, j) : NONE;\n continue;\n }\n if (pa < pb) {\n p = pa;\n i++;\n pa = i < na ? boundary(x, a.off, i) : NONE;\n } else {\n p = pb;\n j++;\n pb = j < nb ? boundary(y, b.off, j) : NONE;\n }\n if (open < 0) {\n open = p;\n } else {\n out[2 * runs] = open;\n out[2 * runs + 1] = p - 1 - open;\n runs++;\n card += p - open;\n open = -1;\n }\n }\n return card === 0 ? null : runsOrPlain(out, runs, card, true);\n}\n\n/** Boundary `k` of a run list at `off`: pair `k >> 1`'s start when `k` is even and one past its last value when odd. */\nfunction boundary(u16: Uint16Array, off: number, k: number): number {\n const at = off + (k & ~1);\n return (u16[at] as number) + ((k & 1) === 0 ? 0 : (u16[at + 1] as number) + 1);\n}\n\n/**\n * The values exactly one of the two holds, or `null` when there are none, built in one pass over the pair by their\n * kinds: one word loop and one count for two bitsets, one merge for two arrays, one walk for two run containers, and\n * for any pair with a bitset the bitset's words (a copy, or its own when `inPlace` and `a` is the bitset) with the\n * other side's values flipped in. Array against run goes through words. Neither operand is changed unless `inPlace`\n * and `a` is a bitset (see the module comment).\n */\nexport function containerXor(a: Container, b: Container, inPlace = false): Container | null {\n if (a.kind === BITSET || b.kind === BITSET) {\n const base = a.kind === BITSET ? a : b;\n const other = base === a ? b : a;\n if (other.kind === BITSET) {\n const x = words32(a);\n const y = words32(b);\n const out = inPlace ? x : new Uint32Array(WORDS);\n xorWords(out, x, y);\n return fromWordsCard(out, popcountWords(out));\n }\n const words = inPlace && base === a ? words32(base) : words32(base).slice();\n if (other.kind === ARRAY) {\n return fromWordsCard(words, flipValues(words, other, base.card));\n }\n const pairs = lows16(other);\n for (let r = 0; r < other.len; r++) {\n const start = pairs[other.off + 2 * r] as number;\n flipRange(words, start, start + (pairs[other.off + 2 * r + 1] as number));\n }\n return fromWordsCard(words, popcountWords(words));\n }\n if (a.kind === ARRAY && b.kind === ARRAY) return xorArrays(a, b);\n if (a.kind === RUN && b.kind === RUN) return xorRuns(a, b);\n const runs = a.kind === RUN ? a : b;\n const array = runs === a ? b : a;\n const words = toWords(runs);\n return fromWordsCard(words, flipValues(words, array, runs.card));\n}\n\n/** Flip the bits of `array`'s values in `words`, which hold `card` set bits; returns the count after. */\nfunction flipValues(words: Uint32Array, array: Container, card: number): number {\n const u16 = lows16(array);\n let n = card;\n for (let i = array.off; i < array.off + array.len; i++) {\n const v = u16[i] as number;\n const w = words[v >>> 5] as number;\n words[v >>> 5] = w ^ (1 << (v & 31));\n n += 1 - 2 * ((w >>> (v & 31)) & 1);\n }\n return n;\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Counting a combine without building it\n// ---------------------------------------------------------------------------------------------------------------\n\n/** Set bits of `words` from bit `start` to bit `end`, both inclusive. */\nfunction bitsInRange(words: Uint32Array, start: number, end: number): number {\n const first = start >>> 5;\n const last = end >>> 5;\n const head = (0xffff_ffff << (start & 31)) >>> 0;\n const tail = 0xffff_ffff >>> (31 - (end & 31));\n if (first === last) return popcount32((words[first] as number) & head & tail);\n let n = popcount32((words[first] as number) & head) + popcount32((words[last] as number) & tail);\n for (let i = first + 1; i < last; i++) n += popcount32(words[i] as number);\n return n;\n}\n\n/** Values both arrays hold: a merge that writes nothing, or a gallop of the shorter over the longer when one is much longer. */\nfunction andCountArrays(a: Container, b: Container): number {\n const small = a.len <= b.len ? a : b;\n const big = small === a ? b : a;\n const s = lows16(small);\n const l = lows16(big);\n const se = small.off + small.len;\n const le = big.off + big.len;\n let n = 0;\n if (skewed(small.len, big.len)) {\n let at = big.off;\n for (let i = small.off; i < se; i++) {\n const v = s[i] as number;\n at = gallop(l, 0, at, le, v);\n if (at === le) break;\n if (l[at] === v) n++;\n }\n return n;\n }\n if (small.len >= PROBE_MIN) {\n // As the building intersection does: the shorter array as bits, the longer one tested against them in order, only\n // the span of the longer between the shorter's ends. Nothing is written but the scratch bits, cleared again.\n const first = s[small.off] as number;\n const last = s[se - 1] as number;\n if (last < (l[big.off] as number) || first > (l[le - 1] as number)) return 0;\n const from = gallop(l, 0, big.off, le, first);\n const to = gallop(l, 0, from, le, last + 1);\n const words = probeWords;\n for (let i = small.off; i < se; i++) {\n const v = s[i] as number;\n words[v >>> 5] = (words[v >>> 5] as number) | (1 << (v & 31));\n }\n for (let j = from; j < to; j++) {\n const v = l[j] as number;\n n += ((words[v >>> 5] as number) >>> (v & 31)) & 1;\n }\n for (let i = small.off; i < se; i++) words[(s[i] as number) >>> 5] = 0;\n return n;\n }\n let i = small.off;\n let j = big.off;\n while (i < se && j < le) {\n const x = s[i] as number;\n const y = l[j] as number;\n // No branch on the comparison, as in the building merge.\n n += x === y ? 1 : 0;\n i += x <= y ? 1 : 0;\n j += x >= y ? 1 : 0;\n }\n return n;\n}\n\n/** Values of array `a` that bitset `b` holds. */\nfunction andCountArrayBitset(a: Container, b: Container): number {\n const u16 = lows16(a);\n const words = words32(b);\n let n = 0;\n for (let i = a.off; i < a.off + a.len; i++) {\n const v = u16[i] as number;\n n += ((words[v >>> 5] as number) >>> (v & 31)) & 1;\n }\n return n;\n}\n\n/** Values of array `a` that the runs of `b` cover: a walk of both, or a search of the runs per value when the runs are far more. */\nfunction andCountArrayRuns(a: Container, b: Container): number {\n const u16 = lows16(a);\n const pairs = lows16(b);\n const ae = a.off + a.len;\n let n = 0;\n if (skewed(a.len, b.len)) {\n for (let i = a.off; i < ae; i++) {\n const v = u16[i] as number;\n // The last run starting at or before `v`.\n const after = lowerBound(pairs, b.off, b.len, v + 1, 2);\n if (after === 0) continue;\n const r = b.off + 2 * (after - 1);\n if (v <= (pairs[r] as number) + (pairs[r + 1] as number)) n++;\n }\n return n;\n }\n let i = a.off;\n for (let r = 0; r < b.len && i < ae; r++) {\n const start = pairs[b.off + 2 * r] as number;\n const end = start + (pairs[b.off + 2 * r + 1] as number);\n while (i < ae && (u16[i] as number) < start) i++;\n while (i < ae && (u16[i] as number) <= end) {\n n++;\n i++;\n }\n }\n return n;\n}\n\n/** Values bitset `a` holds inside the runs of `b`. */\nfunction andCountBitsetRuns(a: Container, b: Container): number {\n const words = words32(a);\n const pairs = lows16(b);\n let n = 0;\n for (let r = 0; r < b.len; r++) {\n const start = pairs[b.off + 2 * r] as number;\n n += bitsInRange(words, start, start + (pairs[b.off + 2 * r + 1] as number));\n }\n return n;\n}\n\n/** Values both run containers hold: the summed overlap of the runs. */\nfunction andCountRuns(a: Container, b: Container): number {\n const x = lows16(a);\n const y = lows16(b);\n let n = 0;\n let i = 0;\n let j = 0;\n while (i < a.len && j < b.len) {\n const as = x[a.off + 2 * i] as number;\n const ae = as + (x[a.off + 2 * i + 1] as number);\n const bs = y[b.off + 2 * j] as number;\n const be = bs + (y[b.off + 2 * j + 1] as number);\n const lo = as > bs ? as : bs;\n const hi = ae < be ? ae : be;\n if (lo <= hi) n += hi - lo + 1;\n if (ae < be) i++;\n else j++;\n }\n return n;\n}\n\n/** How many values both containers hold; builds nothing and changes neither operand. */\nexport function containerAndCard(a: Container, b: Container): number {\n if (a.kind === BITSET && b.kind === BITSET) {\n return popcountAnd(words32(a), words32(b));\n }\n // Commutative: put the lower kind first (array, bitset, run).\n if (a.kind > b.kind) return containerAndCard(b, a);\n if (a.kind === ARRAY) {\n if (b.kind === ARRAY) return andCountArrays(a, b);\n return b.kind === BITSET ? andCountArrayBitset(a, b) : andCountArrayRuns(a, b);\n }\n return b.kind === RUN && a.kind === RUN ? andCountRuns(a, b) : andCountBitsetRuns(a, b);\n}\n\n/** Whether any bit from `start` to `end`, both inclusive, is set in `words`; stops at the first word that has one. */\nfunction anyBitInRange(words: Uint32Array, start: number, end: number): boolean {\n const first = start >>> 5;\n const last = end >>> 5;\n const head = (0xffff_ffff << (start & 31)) >>> 0;\n const tail = 0xffff_ffff >>> (31 - (end & 31));\n if (first === last) return ((words[first] as number) & head & tail) !== 0;\n if (((words[first] as number) & head) !== 0 || ((words[last] as number) & tail) !== 0)\n return true;\n for (let i = first + 1; i < last; i++) if (words[i] !== 0) return true;\n return false;\n}\n\n/** Whether every bit from `start` to `end`, both inclusive, is set in `words`; stops at the first word that lacks one. */\nfunction allBitsInRange(words: Uint32Array, start: number, end: number): boolean {\n const first = start >>> 5;\n const last = end >>> 5;\n const head = (0xffff_ffff << (start & 31)) >>> 0;\n const tail = 0xffff_ffff >>> (31 - (end & 31));\n if (first === last) return (~(words[first] as number) & head & tail) === 0;\n if ((~(words[first] as number) & head) !== 0 || (~(words[last] as number) & tail) !== 0)\n return false;\n for (let i = first + 1; i < last; i++) if (words[i] !== 0xffff_ffff) return false;\n return true;\n}\n\n/** Whether every value of array `a` is in array `b`: a merge or a gallop that stops at the first value `b` lacks. */\nfunction subsetArrays(a: Container, b: Container): boolean {\n const x = lows16(a);\n const y = lows16(b);\n const ie = a.off + a.len;\n const je = b.off + b.len;\n let j = b.off;\n if (skewed(a.len, b.len)) {\n for (let i = a.off; i < ie; i++) {\n const v = x[i] as number;\n j = gallop(y, 0, j, je, v);\n if (j === je || y[j] !== v) return false;\n }\n return true;\n }\n let i = a.off;\n while (i < ie && j < je) {\n const p = x[i] as number;\n const q = y[j] as number;\n if (p < q) return false;\n i += p === q ? 1 : 0;\n j++;\n }\n return i === ie;\n}\n\n/** Whether every value of array `a` is covered by a run of `b`: one walk of the runs, stopping at the first value outside them. */\nfunction subsetArrayRuns(a: Container, b: Container): boolean {\n const u16 = lows16(a);\n const pairs = lows16(b);\n let r = 0;\n for (let i = a.off; i < a.off + a.len; i++) {\n const v = u16[i] as number;\n while (r < b.len && (pairs[b.off + 2 * r] as number) + (pairs[b.off + 2 * r + 1] as number) < v)\n r++;\n if (r === b.len || (pairs[b.off + 2 * r] as number) > v) return false;\n }\n return true;\n}\n\n/** Whether every value of the runs of `a` is in the array `b`: each run is `length` consecutive entries of `b`, since both ascend without repeats. */\nfunction subsetRunsArray(a: Container, b: Container): boolean {\n const pairs = lows16(a);\n const y = lows16(b);\n const je = b.off + b.len;\n let j = b.off;\n for (let r = 0; r < a.len; r++) {\n const start = pairs[a.off + 2 * r] as number;\n const last = start + (pairs[a.off + 2 * r + 1] as number);\n j = gallop(y, 0, j, je, start);\n const end = j + (last - start);\n if (end >= je || y[j] !== start || y[end] !== last) return false;\n j = end + 1;\n }\n return true;\n}\n\n/** Whether every value of the run containers `a` lies inside a run of `b` (whose runs are maximal, so inside one run). */\nfunction subsetRuns(a: Container, b: Container): boolean {\n const x = lows16(a);\n const y = lows16(b);\n let j = 0;\n for (let i = 0; i < a.len; i++) {\n const start = x[a.off + 2 * i] as number;\n const last = start + (x[a.off + 2 * i + 1] as number);\n while (j < b.len && (y[b.off + 2 * j] as number) + (y[b.off + 2 * j + 1] as number) < start)\n j++;\n if (j === b.len || (y[b.off + 2 * j] as number) > start) return false;\n if ((y[b.off + 2 * j] as number) + (y[b.off + 2 * j + 1] as number) < last) return false;\n }\n return true;\n}\n\n/** Whether every set bit of the bitset `a` lies in a run of `b`: no set bit before the first run, between two, or after the last. */\nfunction subsetBitsetRuns(a: Container, b: Container): boolean {\n const words = words32(a);\n const pairs = lows16(b);\n let from = 0;\n for (let r = 0; r < b.len; r++) {\n const start = pairs[b.off + 2 * r] as number;\n if (start > from && anyBitInRange(words, from, start - 1)) return false;\n from = start + (pairs[b.off + 2 * r + 1] as number) + 1;\n }\n return from > 65_535 || !anyBitInRange(words, from, 65_535);\n}\n\n/**\n * Whether every value of `a` is in `b`, by the kinds of the pair, stopping at the first value that is not and counting\n * nothing: no scratch and no popcount, where `containerAndCard(a, b) === a.card` reads both operands whole. A bitset in\n * an array is the one pair that falls back to that count (it only arises for a bitset of 4,096 values or fewer, which\n * the codec's own results never are).\n */\nexport function containersSubset(a: Container, b: Container): boolean {\n if (a.card > b.card) return false;\n if (a.kind === ARRAY) {\n if (b.kind === ARRAY) return subsetArrays(a, b);\n if (b.kind === RUN) return subsetArrayRuns(a, b);\n const u16 = lows16(a);\n const words = words32(b);\n for (let i = a.off; i < a.off + a.len; i++) {\n const v = u16[i] as number;\n if ((((words[v >>> 5] as number) >>> (v & 31)) & 1) === 0) return false;\n }\n return true;\n }\n if (a.kind === BITSET) {\n if (b.kind === BITSET) {\n const x = words32(a);\n const y = words32(b);\n for (let i = 0; i < WORDS; i += 8) {\n const lack =\n ((x[i] as number) & ~(y[i] as number)) |\n ((x[i + 1] as number) & ~(y[i + 1] as number)) |\n ((x[i + 2] as number) & ~(y[i + 2] as number)) |\n ((x[i + 3] as number) & ~(y[i + 3] as number)) |\n ((x[i + 4] as number) & ~(y[i + 4] as number)) |\n ((x[i + 5] as number) & ~(y[i + 5] as number)) |\n ((x[i + 6] as number) & ~(y[i + 6] as number)) |\n ((x[i + 7] as number) & ~(y[i + 7] as number));\n if (lack !== 0) return false;\n }\n return true;\n }\n if (b.kind === RUN) return subsetBitsetRuns(a, b);\n return containerAndCard(a, b) === a.card;\n }\n if (b.kind === ARRAY) return subsetRunsArray(a, b);\n if (b.kind === RUN) return subsetRuns(a, b);\n const words = words32(b);\n const pairs = lows16(a);\n for (let r = 0; r < a.len; r++) {\n const start = pairs[a.off + 2 * r] as number;\n if (!allBitsInRange(words, start, start + (pairs[a.off + 2 * r + 1] as number))) return false;\n }\n return true;\n}\n\n/**\n * Whether two containers hold the same values. Two containers of one kind compare their storage and stop at the first\n * difference: bitset words, array values, run pairs. That is exact for runs because every run container is canonical:\n * the decoder refuses runs that touch or overlap, and every writer of a run container ({@link optimize}, a write into\n * a run, the union of a run with an array, the run results of `and`, `or`, `andNot` and `xor`) leaves the runs\n * maximal and the container in its smallest kind, so one set has one list of pairs. Containers of different kinds can hold the same set (a run against an array), so they fall back to the\n * count of the values they share.\n */\nexport function containersEqual(a: Container, b: Container): boolean {\n if (a.card !== b.card) return false;\n if (a.kind !== b.kind) return containerAndCard(a, b) === a.card;\n if (a.kind === BITSET) return equalWords(words32(a), 0, words32(b), 0, WORDS);\n if (a.len !== b.len) return false;\n const x = lows16(a);\n const y = lows16(b);\n const n = a.kind === ARRAY ? a.len : 2 * a.len;\n if (n < EQUAL_VIEW_MIN) {\n // Short lists that both start at the front of their storage (every container of a detached decode) pass constant\n // start offsets and skip the view test; a separate function for them measured slower on a bitmap that mixes kinds\n // (indicative, probe).\n if (a.off === 0 && b.off === 0) return equalU16(x, 0, y, 0, n);\n return equalU16(x, a.off, y, b.off, n);\n }\n const xb = x.byteOffset + 2 * a.off;\n const yb = y.byteOffset + 2 * b.off;\n if (usesEqualView(n, xb, yb)) {\n // Two values a step through a 32-bit view over the same bytes.\n const m = n >>> 1;\n if (!equalWords(new Uint32Array(x.buffer, xb, m), 0, new Uint32Array(y.buffer, yb, m), 0, m))\n return false;\n return (n & 1) === 0 || x[a.off + n - 1] === y[b.off + n - 1];\n }\n return equalU16(x, a.off, y, b.off, n);\n}\n\n/** The fewest 16-bit values (an array's values, twice a run container's pairs) from which a compare goes through a 32-bit view: a view costs about as much as a few hundred compares. */\nexport const EQUAL_VIEW_MIN = 512;\n\n/** Whether a compare of `n` 16-bit values, whose two lists start at byte offsets `xb` and `yb`, goes through a 32-bit view: from {@link EQUAL_VIEW_MIN} values, when both starts fall on a 4-byte boundary. */\nexport function usesEqualView(n: number, xb: number, yb: number): boolean {\n return n >= EQUAL_VIEW_MIN && (xb & 3) === 0 && (yb & 3) === 0;\n}\n\n/** Whether `n` words of `x` from `xo` equal those of `y` from `yo`: eight a step, the differences OR-ed and tested once per group. */\nfunction equalWords(x: Uint32Array, xo: number, y: Uint32Array, yo: number, n: number): boolean {\n let i = 0;\n for (const end = n - 7; i < end; i += 8) {\n const d =\n ((x[xo + i] as number) ^ (y[yo + i] as number)) |\n ((x[xo + i + 1] as number) ^ (y[yo + i + 1] as number)) |\n ((x[xo + i + 2] as number) ^ (y[yo + i + 2] as number)) |\n ((x[xo + i + 3] as number) ^ (y[yo + i + 3] as number)) |\n ((x[xo + i + 4] as number) ^ (y[yo + i + 4] as number)) |\n ((x[xo + i + 5] as number) ^ (y[yo + i + 5] as number)) |\n ((x[xo + i + 6] as number) ^ (y[yo + i + 6] as number)) |\n ((x[xo + i + 7] as number) ^ (y[yo + i + 7] as number));\n if (d !== 0) return false;\n }\n for (; i < n; i++) if (x[xo + i] !== y[yo + i]) return false;\n return true;\n}\n\n/** {@link equalWords} over 16-bit values. */\nfunction equalU16(x: Uint16Array, xo: number, y: Uint16Array, yo: number, n: number): boolean {\n let i = 0;\n for (const end = n - 7; i < end; i += 8) {\n const d =\n ((x[xo + i] as number) ^ (y[yo + i] as number)) |\n ((x[xo + i + 1] as number) ^ (y[yo + i + 1] as number)) |\n ((x[xo + i + 2] as number) ^ (y[yo + i + 2] as number)) |\n ((x[xo + i + 3] as number) ^ (y[yo + i + 3] as number)) |\n ((x[xo + i + 4] as number) ^ (y[yo + i + 4] as number)) |\n ((x[xo + i + 5] as number) ^ (y[yo + i + 5] as number)) |\n ((x[xo + i + 6] as number) ^ (y[yo + i + 6] as number)) |\n ((x[xo + i + 7] as number) ^ (y[yo + i + 7] as number));\n if (d !== 0) return false;\n }\n for (; i < n; i++) if (x[xo + i] !== y[yo + i]) return false;\n return true;\n}\n\n/** Whether two arrays share a value; stops at the first. */\nfunction intersectsArrays(a: Container, b: Container): boolean {\n const small = a.len <= b.len ? a : b;\n const big = small === a ? b : a;\n const s = lows16(small);\n const l = lows16(big);\n const se = small.off + small.len;\n const le = big.off + big.len;\n // Disjoint ranges answer at once.\n if (\n (s[se - 1] as number) < (l[big.off] as number) ||\n (s[small.off] as number) > (l[le - 1] as number)\n ) {\n return false;\n }\n if (skewed(small.len, big.len)) {\n let at = big.off;\n for (let i = small.off; i < se; i++) {\n const v = s[i] as number;\n at = gallop(l, 0, at, le, v);\n if (at === le) return false;\n if (l[at] === v) return true;\n }\n return false;\n }\n let i = small.off;\n let j = big.off;\n if (small.len >= PROBE_MIN) {\n // A pair that shares a value early is answered by the merge without setting any bits: take a bounded number of merge\n // steps first and set up the scratch bits only for a pair that shares nothing that soon (most random pairs of this\n // size still reach them; see MERGE_FIRST).\n for (let step = 0; step < MERGE_FIRST && i < se && j < le; step++) {\n const x = s[i] as number;\n const y = l[j] as number;\n if (x === y) return true;\n if (x < y) i++;\n else j++;\n }\n if (i === se || j === le) return false;\n // As the counting kernel does: the shorter array as bits and the span of the longer between its ends tested against\n // them, but stopping at the first hit. The scratch bits are cleared on both exits.\n const left = i;\n const from = gallop(l, 0, j, le, s[left] as number);\n const to = gallop(l, 0, from, le, (s[se - 1] as number) + 1);\n const words = probeWords;\n for (let k = left; k < se; k++) {\n const v = s[k] as number;\n words[v >>> 5] = (words[v >>> 5] as number) | (1 << (v & 31));\n }\n let hit = false;\n for (let k = from; k < to; k++) {\n const v = l[k] as number;\n if ((((words[v >>> 5] as number) >>> (v & 31)) & 1) === 1) {\n hit = true;\n break;\n }\n }\n for (let k = left; k < se; k++) words[(s[k] as number) >>> 5] = 0;\n return hit;\n }\n while (i < se && j < le) {\n const x = s[i] as number;\n const y = l[j] as number;\n if (x === y) return true;\n if (x < y) i++;\n else j++;\n }\n return false;\n}\n\n/** Whether the array `a` has a value the runs of `b` cover; stops at the first. */\nfunction intersectsArrayRuns(a: Container, b: Container): boolean {\n const u16 = lows16(a);\n const pairs = lows16(b);\n let r = 0;\n for (let i = a.off; i < a.off + a.len; i++) {\n const v = u16[i] as number;\n // The first run that ends at or after `v`.\n while (\n r < b.len &&\n (pairs[b.off + 2 * r] as number) + (pairs[b.off + 2 * r + 1] as number) < v\n ) {\n r++;\n }\n if (r === b.len) return false;\n if ((pairs[b.off + 2 * r] as number) <= v) return true;\n }\n return false;\n}\n\n/** Whether the two containers share a value; stops at the first one it finds. */\nexport function containersIntersect(a: Container, b: Container): boolean {\n if (a.kind > b.kind) return containersIntersect(b, a);\n if (a.kind === ARRAY) {\n if (b.kind === ARRAY) return intersectsArrays(a, b);\n if (b.kind === RUN) return intersectsArrayRuns(a, b);\n const u16 = lows16(a);\n const words = words32(b);\n for (let i = a.off; i < a.off + a.len; i++) {\n const v = u16[i] as number;\n if ((((words[v >>> 5] as number) >>> (v & 31)) & 1) === 1) return true;\n }\n return false;\n }\n if (a.kind === BITSET) {\n const x = words32(a);\n if (b.kind === BITSET) {\n const y = words32(b);\n for (let i = 0; i < WORDS; i += 8) {\n const both =\n ((x[i] as number) & (y[i] as number)) |\n ((x[i + 1] as number) & (y[i + 1] as number)) |\n ((x[i + 2] as number) & (y[i + 2] as number)) |\n ((x[i + 3] as number) & (y[i + 3] as number)) |\n ((x[i + 4] as number) & (y[i + 4] as number)) |\n ((x[i + 5] as number) & (y[i + 5] as number)) |\n ((x[i + 6] as number) & (y[i + 6] as number)) |\n ((x[i + 7] as number) & (y[i + 7] as number));\n if (both !== 0) return true;\n }\n return false;\n }\n const pairs = lows16(b);\n for (let r = 0; r < b.len; r++) {\n const start = pairs[b.off + 2 * r] as number;\n if (anyBitInRange(x, start, start + (pairs[b.off + 2 * r + 1] as number))) return true;\n }\n return false;\n }\n // Two run containers share a value when any two runs overlap.\n const x = lows16(a);\n const y = lows16(b);\n let i = 0;\n let j = 0;\n while (i < a.len && j < b.len) {\n const as = x[a.off + 2 * i] as number;\n const ae = as + (x[a.off + 2 * i + 1] as number);\n const bs = y[b.off + 2 * j] as number;\n const be = bs + (y[b.off + 2 * j + 1] as number);\n if ((as > bs ? as : bs) <= (ae < be ? ae : be)) return true;\n if (ae < be) i++;\n else j++;\n }\n return false;\n}\n", "/**\n * The ascending iterator over a Roaring bitmap's ids: a class with its own state, not a generator, so a step is one\n * method call and a result object, with no suspended frame and no scratch buffer of 65,536 entries per iterator. It\n * walks one container at a time in place: an array by index, a run container by run and value, a bitset by word and the\n * lowest set bit of what is left of it.\n *\n * It reads the bitmap's live storage and takes no snapshot, so mutating the bitmap while iterating it is not supported.\n * Over a bitmap nothing changes it yields every id once, ascending, then ends. After a change it neither throws nor\n * reads outside the storage it holds, but what it yields is unspecified: an id may be missed, repeated or out of order,\n * and an id added or removed meanwhile may or may not appear. Collect the ids first (`toUint32Array`) or iterate a\n * `clone()` to change a bitmap while walking it.\n */\nimport { ARRAY, BITSET, WORDS, type Container } from './containers';\n\nconst DONE: IteratorReturnResult<undefined> = { done: true, value: undefined };\n\nexport class BitmapIterator implements IterableIterator<number> {\n readonly #keys: readonly number[];\n readonly #conts: readonly Container[];\n /** The container being walked, as an index into `#conts`, and its kind, storage and offset. */\n #at = -1;\n #kind: number = ARRAY;\n #u16: Uint16Array = new Uint16Array(0);\n #words: Uint32Array = new Uint32Array(0);\n #off = 0;\n /** Added to every remainder: the container's key times 65,536. */\n #base = 0;\n /** An array: the next index and one past the last. A run container: the next run's index and the run count. A bitset: the word index. */\n #pos = 0;\n #end = 0;\n /** A run container: the next value and the last of the current run. A bitset: what is left of the current word. */\n #next = 0;\n #last = -1;\n\n constructor(keys: readonly number[], conts: readonly Container[]) {\n this.#keys = keys;\n this.#conts = conts;\n }\n\n [Symbol.iterator](): this {\n return this;\n }\n\n next(): IteratorResult<number, undefined> {\n for (;;) {\n if (this.#kind === ARRAY) {\n if (this.#pos < this.#end) {\n return { done: false, value: this.#base + (this.#u16[this.#pos++] as number) };\n }\n } else if (this.#kind === BITSET) {\n let w = this.#next;\n while (w === 0 && ++this.#pos < WORDS) w = this.#words[this.#pos] as number;\n if (w !== 0) {\n const lowest = w & -w;\n this.#next = w ^ lowest;\n return {\n done: false,\n value: this.#base + this.#pos * 32 + 31 - Math.clz32(lowest),\n };\n }\n } else {\n if (this.#next <= this.#last) return { done: false, value: this.#base + this.#next++ };\n if (this.#pos < this.#end) {\n const r = this.#off + 2 * this.#pos++;\n this.#next = this.#u16[r] as number;\n this.#last = this.#next + (this.#u16[r + 1] as number);\n continue;\n }\n }\n if (!this.#advance()) return DONE;\n }\n }\n\n /** Move to the next container; `false` when there is none. */\n #advance(): boolean {\n if (++this.#at >= this.#conts.length) {\n this.#at = this.#conts.length;\n this.#kind = ARRAY;\n this.#pos = 0;\n this.#end = 0;\n return false;\n }\n const c = this.#conts[this.#at] as Container;\n this.#kind = c.kind;\n this.#base = (this.#keys[this.#at] as number) * 65_536;\n this.#off = c.off;\n if (c.kind === ARRAY) {\n this.#u16 = c.data as Uint16Array;\n this.#pos = c.off;\n this.#end = c.off + c.len;\n } else if (c.kind === BITSET) {\n this.#words = c.data as Uint32Array;\n this.#pos = 0;\n this.#next = this.#words[0] as number;\n } else {\n this.#u16 = c.data as Uint16Array;\n this.#pos = 0;\n this.#end = c.len;\n this.#next = 0;\n this.#last = -1;\n }\n return true;\n }\n}\n", "/**\n * The portable Roaring bytes of a set of containers: written from them, and read back into them.\n *\n * The layout is the RoaringFormatSpec's, as this repo's format page states it. A bitmap with no run container starts\n * with the cookie 12,346 and a `u32` container count; one with a run container starts with the cookie 12,347 whose high\n * half holds `count - 1`, then one bit per container (a run container's) in `ceil(count / 8)` bytes. Then come a\n * `(key, cardinality - 1)` pair of `u16`s per container, an offset per container (always without runs; with runs only\n * from four containers up) and the bodies back to back: an array's values as `u16`s, a bitset's 2,048 words, a run\n * container's run count and `(start, length - 1)` pairs. All integers are little-endian.\n *\n * Reading goes through {@link parsePortableLayout}, which holds every rule a reader refuses on (bounds, ordering, runs,\n * cardinalities, offsets), so there is one code path for what is a bitmap and this module only copies bytes the layout\n * has already vouched for, on a private copy of the input.\n */\nimport { IntegrityError } from '@cloudbitmaps/core';\nimport {\n NO_OFFSET_THRESHOLD,\n SERIAL_COOKIE,\n SERIAL_COOKIE_NO_RUNCONTAINER,\n parsePortableLayout,\n ARRAY as LAYOUT_ARRAY,\n BITMAP as LAYOUT_BITMAP,\n} from '../portable/layout';\nimport {\n ARRAY,\n BITSET,\n BITSET_BYTES,\n RUN,\n LITTLE_ENDIAN,\n WORDS,\n bitsetContainer,\n Container,\n} from './containers';\n\n/** The size of a container's body on the wire. */\nfunction bodySize(c: Container): number {\n if (c.kind === ARRAY) return 2 * c.len;\n if (c.kind === BITSET) return BITSET_BYTES;\n return 2 + 4 * c.len;\n}\n\n/** A body of fewer `u16`s than this is written with a loop, not a view and a copy. */\nconst SMALL_BODY = 64;\n\n/** Write `count` `u16`s of `src` from index `from` at byte `at` of `out`, little-endian. */\nfunction putU16s(out: Uint8Array, at: number, src: Uint16Array, from: number, count: number): void {\n if (count < SMALL_BODY) {\n // A short body is written by a loop: a view over it costs more than its bytes. Byte by byte is little-endian on any machine.\n for (let i = 0; i < count; i++) {\n const v = src[from + i] as number;\n out[at++] = v & 255;\n out[at++] = v >>> 8;\n }\n return;\n }\n if (LITTLE_ENDIAN) {\n out.set(new Uint8Array(src.buffer, src.byteOffset + 2 * from, 2 * count), at);\n return;\n }\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n for (let i = 0; i < count; i++) view.setUint16(at + 2 * i, src[from + i] as number, true);\n}\n\nfunction writeBody(c: Container, out: Uint8Array, view: DataView, at: number): void {\n if (c.kind === ARRAY) {\n putU16s(out, at, c.data as Uint16Array, c.off, c.len);\n } else if (c.kind === BITSET) {\n const words = c.data as Uint32Array;\n if (LITTLE_ENDIAN) out.set(new Uint8Array(words.buffer, words.byteOffset, BITSET_BYTES), at);\n else for (let i = 0; i < WORDS; i++) view.setUint32(at + 4 * i, words[i] as number, true);\n } else {\n view.setUint16(at, c.len, true);\n putU16s(out, at + 2, c.data as Uint16Array, c.off, 2 * c.len);\n }\n}\n\n/** The portable bytes of the bitmap holding `conts`, under the ascending 16-bit `keys`. Empty input is the 8-byte empty bitmap. */\nexport function serializeContainers(\n keys: readonly number[],\n conts: readonly Container[],\n): Uint8Array {\n const n = conts.length;\n let hasRun = false;\n for (let i = 0; i < n; i++) if ((conts[i] as Container).kind === RUN) hasRun = true;\n const offsets = !hasRun || n >= NO_OFFSET_THRESHOLD;\n let at = hasRun ? 4 + ((n + 7) >>> 3) : 8;\n const describeAt = at;\n at += 4 * n;\n const offsetsAt = at;\n if (offsets) at += 4 * n;\n let total = at;\n for (let i = 0; i < n; i++) total += bodySize(conts[i] as Container);\n\n const out = new Uint8Array(total);\n const view = new DataView(out.buffer);\n if (hasRun) {\n view.setUint32(0, SERIAL_COOKIE | ((n - 1) << 16), true);\n for (let i = 0; i < n; i++) {\n if ((conts[i] as Container).kind === RUN) {\n out[4 + (i >>> 3)] = (out[4 + (i >>> 3)] as number) | (1 << (i & 7));\n }\n }\n } else {\n view.setUint32(0, SERIAL_COOKIE_NO_RUNCONTAINER, true);\n view.setUint32(4, n, true);\n }\n for (let i = 0; i < n; i++) {\n const c = conts[i] as Container;\n view.setUint16(describeAt + 4 * i, keys[i] as number, true);\n view.setUint16(describeAt + 4 * i + 2, c.card - 1, true);\n if (offsets) view.setUint32(offsetsAt + 4 * i, at, true);\n writeBody(c, out, view, at);\n at += bodySize(c);\n }\n return out;\n}\n\n/** What {@link decodeContainers} found: the containers in key order, and where the bitmap ends in the buffer. */\ninterface Decoded {\n readonly keys: number[];\n readonly conts: Container[];\n /** One past the last byte of the last container (0 for an empty buffer). */\n readonly end: number;\n}\n\n/**\n * Read the portable bitmap in `bytes`. An empty buffer is the empty bitmap. With `detached`, each container is copied\n * into storage of its own, so the result holds no view of the input's copy and no slab shared between containers.\n *\n * @throws {IntegrityError} for every shape {@link parsePortableLayout} refuses.\n */\nexport function decodeContainers(input: Uint8Array, detached = false): Decoded {\n // The bytes are copied before they are checked, and the checked copy is the one read (Uint8Array's own slice, which\n // always copies; a Node Buffer's slice is a view of the same memory): a buffer another thread is\n // still writing (a shared one) could otherwise pass the check and then hold different bytes when they are copied\n // into containers, leaving an unsorted array or a bitset whose cardinality is not its bit count.\n const bytes = Uint8Array.prototype.slice.call(input) as Uint8Array;\n const layout = parsePortableLayout(bytes);\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n // Sized to the container count, not grown by pushes: a pushed-to array reserves room for sixteen more, which for the\n // one-container bitmaps a store decodes is most of what the two lists hold.\n const keys = new Array<number>(layout.length);\n const conts = new Array<Container>(layout.length);\n let n = 0;\n // A bitmap of no containers is its 8-byte header (the run cookie cannot state a count of zero).\n let end = bytes.byteLength === 0 ? 0 : 8;\n // The arrays and run containers of one bitmap share a single `Uint16Array`, each reading its own stretch of it, so a\n // run container of a few bytes costs its bytes and one small object, not a typed array of its own. When the bitmap\n // has only one of them it is the whole slab and owns it.\n // A detached decode gives every container storage of its own, so it has no slab to size and no lone container to\n // find: the pass over the layout that measures them is skipped.\n let slabLength = 0;\n let small = 0;\n if (!detached) {\n for (const { cardinality, kind, offset } of layout) {\n if (kind === LAYOUT_ARRAY) {\n slabLength += cardinality;\n small++;\n } else if (kind !== LAYOUT_BITMAP) {\n slabLength += 2 * view.getUint16(offset, true);\n small++;\n }\n }\n }\n // The private copy's memory is its own when the copy starts at its buffer's first byte and fills it, which a copy made\n // by `Uint8Array.prototype.slice` does. A body that sits at a suitably aligned offset of it can then be read in place,\n // as a typed array over the copy, with no second copy of it: the one bitset of a chunk, or its one array or run container.\n const own =\n LITTLE_ENDIAN &&\n bytes.byteOffset === 0 &&\n bytes.buffer instanceof ArrayBuffer &&\n bytes.buffer.byteLength === bytes.byteLength;\n const alias = !detached && own && small === 1;\n // A container with storage of its own: the one a detached decode gives every container, and the lone array or run\n // container of a bitmap that cannot be read in place.\n const solo = alias || detached;\n const slab = solo ? NO_U16 : new Uint16Array(slabLength);\n let used = 0;\n for (const { key, cardinality, kind, offset } of layout) {\n keys[n] = key;\n if (kind === LAYOUT_ARRAY) {\n if (alias && offset % 2 === 0) {\n const values = new Uint16Array(bytes.buffer, offset, cardinality);\n conts[n++] = new Container(ARRAY, values, 0, cardinality, cardinality, false);\n } else {\n const into = solo ? new Uint16Array(cardinality) : slab;\n getU16s(bytes, view, offset, into, solo ? 0 : used, cardinality);\n conts[n++] = new Container(\n ARRAY,\n into,\n solo ? 0 : used,\n cardinality,\n cardinality,\n !solo && small > 1,\n );\n used += cardinality;\n }\n end = offset + 2 * cardinality;\n } else if (kind === LAYOUT_BITMAP) {\n let words: Uint32Array;\n if (!detached && own && offset % 4 === 0) {\n words = new Uint32Array(bytes.buffer, offset, WORDS);\n } else {\n words = new Uint32Array(WORDS);\n if (LITTLE_ENDIAN) {\n new Uint8Array(words.buffer).set(bytes.subarray(offset, offset + BITSET_BYTES));\n } else {\n for (let i = 0; i < WORDS; i++) words[i] = view.getUint32(offset + 4 * i, true);\n }\n }\n conts[n++] = bitsetContainer(words, cardinality);\n end = offset + BITSET_BYTES;\n } else {\n const runs = view.getUint16(offset, true);\n if (alias && (offset + 2) % 2 === 0) {\n const pairs = new Uint16Array(bytes.buffer, offset + 2, 2 * runs);\n conts[n++] = new Container(RUN, pairs, 0, runs, cardinality, false);\n } else {\n const into = solo ? new Uint16Array(2 * runs) : slab;\n getU16s(bytes, view, offset + 2, into, solo ? 0 : used, 2 * runs);\n conts[n++] = new Container(\n RUN,\n into,\n solo ? 0 : used,\n runs,\n cardinality,\n !solo && small > 1,\n );\n used += 2 * runs;\n }\n end = offset + 2 + 4 * runs;\n }\n }\n return { keys, conts, end };\n}\n\nconst NO_U16 = new Uint16Array(0);\n\n/** Copy `count` little-endian `u16`s from byte `at` of `bytes` into `slab` from index `to`. */\nfunction getU16s(\n bytes: Uint8Array,\n view: DataView,\n at: number,\n slab: Uint16Array,\n to: number,\n count: number,\n): void {\n if (LITTLE_ENDIAN) {\n new Uint8Array(slab.buffer, 2 * to, 2 * count).set(bytes.subarray(at, at + 2 * count));\n return;\n }\n for (let i = 0; i < count; i++) slab[to + i] = view.getUint16(at + 2 * i, true);\n}\n\n/** The refusal for bytes that follow the bitmap's last container when the buffer must be exactly one bitmap. */\nexport function trailingBytes(length: number, end: number): IntegrityError {\n return new IntegrityError(\n `portable roaring: ${length - end} bytes follow the bitmap's last container, which ends at byte ${end}. ` +\n `One buffer holds one bitmap: to load several as one segment, combine them first and serialize the result.`,\n );\n}\n", "/**\n * The codec selection point and the load-input and decode helpers the `CloudRoaring` facade builds on.\n *\n * The store's codec is the TypeScript Roaring codec (`ts-roaring/bitmap.ts`): the portable format, read and written in\n * JavaScript with no native addon. Every deserialize is preceded by a hard size cap and a structural check\n * (`portable/layout.ts`). The `unsafe_frozen_*` formats are never used.\n */\nimport type { CodecInterface, LoadInput, PortableBitmap } from '@cloudbitmaps/core';\nimport { tsRoaringCodec } from './ts-roaring/bitmap';\n\n/**\n * An iterable that serializes itself to portable Roaring (an object with `Symbol.iterator` and a `serialize` method: a\n * caller's `RoaringBitmap32` from the `roaring` package, another copy's bitmap, or a `RoaringBitmap` of this\n * package), passed where ids go, loads as `{ bitmap }`: from its containers, through the same check as any bytes,\n * never id by id. Its `serialize` decides, even where it disagrees with what it iterates. Any other input passes\n * through unchanged, so the core's own rules apply to it: a byte array (`Uint8Array`, `Buffer`) is refused as ids even\n * with a `serialize` of its own, and an object that is not iterable is read as `{ serialized }` or `{ bitmap }` or\n * refused, whatever else it has.\n */\nexport function bitmapAsLoadInput(input: LoadInput): LoadInput {\n if (typeof input !== 'object' || input === null) return input;\n const tag = Object.prototype.toString.call(input).slice(8, -1);\n if (tag === 'Uint8Array' || tag === 'Uint8ClampedArray') return input;\n return Symbol.iterator in input &&\n typeof (input as { serialize?: unknown }).serialize === 'function'\n ? { bitmap: input as unknown as PortableBitmap }\n : input;\n}\n\nlet activeCodec: CodecInterface = tsRoaringCodec;\n\n/**\n * The codec the store hands to the engine at every site that injects one (`CloudRoaring`, a load, a pin and an export): the TypeScript codec unless a harness has flipped it with {@link setFlagshipCodec}.\n * Internal: no public entry exports it, and a store cannot be configured with a codec.\n */\nexport function flagshipCodec(): CodecInterface {\n return activeCodec;\n}\n\n/** Flip the codec the store uses, for the whole process. Test and bench harnesses only; returns the previous one. */\nexport function setFlagshipCodec(codec: CodecInterface): CodecInterface {\n const previous = activeCodec;\n activeCodec = codec;\n return previous;\n}\n", "/**\n * The default real-time {@link Clock} \u2014 the production half of the determinism seam.\n *\n * It lives outside `core/`, so `Date.now()`, `setTimeout` and `setImmediate` are allowed here; that separation is\n * the whole point of the seam, and it is lint-enforced on the other side.\n *\n * It sits in its own module rather than in `index.ts` so the facade, the tests and anything else that needs a real\n * clock can import it without importing the whole barrel.\n */\nimport type { Clock } from '@cloudbitmaps/core';\n\n/** Default real-time clock \u2014 lives outside `core/`, so `Date.now()` + timers are allowed here. */\nexport class SystemClock implements Clock {\n now(): number {\n return Date.now();\n }\n\n sleep(ms: number): Promise<void> {\n if (ms <= 0) return Promise.resolve();\n // A *ref'd* timer, deliberately. Every `sleep` on this clock backs a caller-awaited, bounded retry \u2014 today\n // the transient-retry loop (`withRetry`) that wraps the chunk source. A pending backoff therefore always means unfinished\n // awaited work, so the timer MUST keep the event loop alive until it resolves. An unref'd timer lets a\n // short-lived process \u2014 CLI, Lambda, a bare script \u2014 whose only remaining handle is the backoff timer exit 0\n // mid-retry, silently dropping the awaited operation with neither a result nor a thrown error. When a\n // transient fault repeats (a backend throttling a hot key, say), the backoff timer can be the last handle\n // standing.\n // Retries are bounded (`maxAttempts`/`maxRetries` + `maxDelayMs`), so a ref'd timer can only\n // extend a process by the small remaining backoff budget of work that is genuinely still in flight.\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n }\n\n /**\n * `setImmediate`, and it has to be \u2014 this is the one place where the choice of primitive is the whole feature.\n *\n * A long CPU-bound loop in `core/` (bulk-load is the one that matters) periodically hands the loop back so a\n * co-resident HTTP server keeps answering. Measured on the **synthetic yield-primitive benchmark** \u2014 a\n * 61,035-iteration loop yielding every 1,024, isolating the primitive rather than timing a real load (the\n * end-to-end figures are 519 ms \u2192 24 ms; see `cooperative.ts`, which lists all three experiments):\n *\n * ```text\n * no yield 568 ms wall 568.0 ms worst event-loop gap\n * sleep(0) 555 ms wall 555.2 ms \u2190 a microtask. Yields NOTHING.\n * setImmediate 569 ms wall 13.8 ms \u2190 free, and 41x less starvation\n * setTimeout(1) 625 ms wall 15.0 ms \u2190 +10% wall for no extra relief\n * ```\n *\n * `sleep(0)` resolving on a microtask is correct for its own contract and useless for this: microtasks drain\n * before the loop ever advances a phase, so `await sleep(0)` in a tight loop never lets a single pending I/O\n * callback run. `setImmediate` fires in the check phase *after* pending I/O, which is exactly the ordering a\n * server wants \u2014 inbound requests are serviced before the loop resumes chewing.\n *\n * A timer is not ref'd here (unlike {@link sleep}): a yield expresses \"someone else may go first\", never\n * \"there is outstanding work\" \u2014 and `setImmediate` cannot outlive the turn that scheduled it anyway.\n */\n yieldNow(): Promise<void> {\n return new Promise((resolve) => {\n setImmediate(resolve);\n });\n }\n}\n", "/**\n * The default {@link Entropy}: the platform's Web Crypto, the production half of the seam a generation's write\n * identity is drawn through.\n *\n * It lives outside `core/`, which may reach no global, and it draws on use, not at construction, so a process that\n * only reads runs on a runtime without Web Crypto. `Math.random` is never a fallback: an identity that two writers\n * could draw alike is no identity.\n */\nimport { UnsupportedError } from '@cloudbitmaps/core';\nimport type { Entropy } from '@cloudbitmaps/core';\n\n/** `length` random bytes from `crypto.getRandomValues`; {@link UnsupportedError} on a runtime that has none. */\nexport const systemEntropy: Entropy = (length) => {\n const c = (globalThis as { crypto?: { getRandomValues?: (a: Uint8Array) => Uint8Array } }).crypto;\n if (c === undefined || typeof c.getRandomValues !== 'function') {\n throw new UnsupportedError(\n \"this runtime has no Web Crypto (crypto.getRandomValues), which every load needs for its generation's \" +\n 'write identity: run on a runtime that has it, or pass `seams.entropy`',\n );\n }\n return c.getRandomValues(new Uint8Array(length));\n};\n", "/**\n * The keys `new CloudRoaring(options)` takes: at the top level, and inside each group whose value is an object. The\n * constructor refuses any other key by name, because an option it ignored would do nothing and look as if it had,\n * and the gates that read the docs' samples and the harnesses' option bags hold them to the same table. A test\n * holds the table to the option interfaces, in both directions.\n *\n * NOT part of the public API. It is its own module, rather than an `export` from the barrel, so the constructor\n * and those gates read one copy.\n */\nexport const OPTION_KEYS = {\n top: ['storage', 'cache', 'encryption', 'retry', 'metrics', 'budget', 'seams'],\n cache: ['maxChunks', 'ttlMs', 'genTtlMs', 'readerMax', 'readerMaxBytes'],\n encryption: ['keystore', 'required'],\n retry: ['maxAttempts', 'baseDelayMs', 'maxDelayMs', 'backoffFactor', 'jitter', 'onRetry'],\n budget: ['maxRequests'],\n seams: ['clock', 'rng', 'entropy'],\n} as const satisfies Record<string, readonly string[]>;\n\n/** The groups: the top-level keys whose value, when it is an object, has keys of its own. */\nexport type OptionGroup = Exclude<keyof typeof OPTION_KEYS, 'top'>;\n", "/**\n * The checks a stream makes of a lease: before its first pull, and each time it reads a chunk. Kept apart from the store\n * so each can be held on its own, and so a stream of another shape (a rank read, a plain iterable of ids) is wrapped by\n * the same function.\n *\n * ```\n * caller \u2500\u2500 next() \u2500\u2500> guarded stream \u2500\u2500 next() \u2500\u2500> engine's stream\n * \u2502 check before the first pull\n * \u2502 check again at each chunk (or each item)\n * \u2514\u2500 a throwing check ends the engine's stream, then rejects\n * return() / throw() \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500> engine's stream (ended / thrown into)\n * ```\n *\n * A guarded stream is its own iterator and single-use, as the engine's generator it wraps is: it answers `next`,\n * `return` and `throw`, and iterating it gives it back.\n */\n\n/** An async iterator that is also its own iterable, with `return` and `throw` always present, as a generator's are. */\ninterface GuardedStream<T> extends AsyncIterableIterator<T> {\n return(value?: unknown): Promise<IteratorResult<T, unknown>>;\n throw(err: unknown): Promise<IteratorResult<T, unknown>>;\n}\n\n/** What an id stream is, as far as a guard is concerned: ids, and the same ids a chunk at a time. */\ninterface IdStream extends AsyncIterable<number> {\n batches(): AsyncIterable<Uint32Array>;\n}\n\n/** An id stream that is guarded: the per-id stream is an iterator of its own, and `batches()` is guarded too. */\ntype GuardedIds = GuardedStream<number> & { batches(): GuardedStream<Uint32Array> };\n\n/** A finished result, new each time: a caller may keep or change what it is handed. */\nconst done = (value?: unknown): IteratorReturnResult<unknown> => ({ done: true, value });\n\n/**\n * The one guard: `check` runs before the first pull, then once an item is pulled and before it is handed on. Every\n * item is checked, or, when `keyOf` is given, the first item of each run of items with one key (the ids of one chunk).\n * A check that throws ends the inner stream and rejects with its error, and the guarded stream is over: a pull that\n * settles after that is done, whatever the source had already pulled for it. A key is remembered only once its check\n * has passed.\n */\nconst guard = <T>(\n inner: AsyncIterable<T>,\n check: () => void,\n keyOf?: (item: T) => number,\n): GuardedStream<T> => {\n const it = inner[Symbol.asyncIterator]();\n let first = true;\n let over = false;\n let last = -1;\n const end = async (value?: unknown): Promise<unknown> => {\n over = true;\n await it.return?.(value);\n return value;\n };\n const stop = async (err: unknown): Promise<never> => {\n await end();\n throw err;\n };\n /** What a pull hands on: nothing once the stream is over, and an item only after its check passes. */\n const deliver = (\n r: IteratorResult<T, unknown>,\n ): Promise<IteratorResult<T, unknown>> | IteratorResult<T, unknown> => {\n if (over) return done();\n if (r.done === true) return r;\n const key = keyOf?.(r.value);\n if (key === undefined || key !== last) {\n try {\n check();\n } catch (err) {\n return stop(err);\n }\n if (key !== undefined) last = key;\n }\n return r;\n };\n return {\n [Symbol.asyncIterator]() {\n return this;\n },\n async next() {\n if (over) return done();\n if (first) {\n first = false;\n try {\n check();\n } catch (err) {\n return stop(err);\n }\n }\n return deliver(await it.next());\n },\n async return(value?: unknown) {\n return done(await end(value));\n },\n async throw(err: unknown) {\n first = false;\n if (it.throw === undefined) return stop(err);\n let r: IteratorResult<T, unknown>;\n try {\n r = await it.throw(err);\n } catch (thrown) {\n over = true;\n throw thrown;\n }\n return deliver(r);\n },\n };\n};\n\n/**\n * A stream of ascending ids that checks a lease before it first pulls, and each time it reads a chunk after that: once\n * the engine has the next chunk and before an id of it is yielded, so nothing of a chunk fetched past the lease is\n * served. Ids ascend, so a chunk is entered when `id >>> 16` changes. The check before the first pull is what stops a\n * stream built while the lease was live, and pulled after it ended, ending empty without ever checking. A throw ends the\n * engine's reads. Used only when a handle in the call holds a lease: a call with none returns the engine's stream\n * untouched. It takes any async iterable of ids, so a stream with no `.batches()` (a rank read) is wrapped the same way.\n */\nexport const guardIdIterable = (\n inner: AsyncIterable<number>,\n check: () => void,\n): GuardedStream<number> => guard(inner, check, (id) => id >>> 16);\n\n/** {@link guardIdIterable} for an `IdStream`, whose `.batches()` is guarded too. */\nexport const guardIds = (inner: IdStream, check: () => void): GuardedIds =>\n Object.assign(guardIdIterable(inner, check), {\n batches: () => guardItems(inner.batches(), check),\n });\n\n/**\n * A stream of chunks that checks a lease before the first pull and before each item is handed on: an item is one\n * chunk (a batch of ids, or a chunk an `*Into` writes).\n */\nexport const guardItems = <T>(inner: AsyncIterable<T>, check: () => void): GuardedStream<T> =>\n guard(inner, check);\n", "/**\n * How a store's storage and read retry are wired from its options:\n *\n * ```\n * options.storage \u2500\u2500> resolveStorageSource \u2500\u2500> source (what the engine reads), driver, registry\n * \u2502 backend: CrbmStorageChunkSource over its storage half, pinned to its registry\n * \u2502 driver: CrbmStorageChunkSource, no registry (list-scan, cleartext, read-only)\n * \u2514 source: used as-is\n * source \u2500\u2500> retry on (default) \u2500\u2500> RetryingStorageChunkSource(source, policy) = storage\n * \u2514\u2500> retry: false \u2500\u2500\u2500\u2500\u2500\u2500\u2500> storage = source\n * ```\n *\n * The constructor keeps what it builds itself (cache, engine, budget); this file owns only the storage half.\n */\nimport {\n CrbmStorageChunkSource,\n DEFAULT_RETRY_POLICY,\n NOOP_METRICS,\n RetryingStorageChunkSource,\n ValidationError,\n isStorageBackend,\n} from '@cloudbitmaps/core';\nimport type { Clock, IMetricsSink, RetryPolicy, RetryingOptions, Rng } from '@cloudbitmaps/core';\nimport type {\n IKeystore,\n IRegistryDriver,\n IStorageDriver,\n StorageBackend,\n StorageChunkSource,\n} from '@cloudbitmaps/core/driver-kit';\n\n/** The slice of a store's options the wiring reads; `CloudRoaringOptions` satisfies it. */\ninterface StoreWiring {\n readonly storage: unknown;\n readonly encryption?: { readonly keystore?: IKeystore; readonly required?: boolean };\n readonly cache?: {\n readonly genTtlMs?: number;\n readonly readerMax?: number;\n readonly readerMaxBytes?: number;\n };\n readonly retry?:\n | (Partial<RetryPolicy> & {\n readonly onRetry?: (info: { attempt: number; delayMs: number; err: unknown }) => void;\n })\n | false;\n}\n\n/** What {@link wireStore} builds for the constructor. */\ninterface WiredStore {\n /** What the engine reads through: the source, wrapped in the read retry unless it is off. */\n readonly storage: StorageChunkSource;\n /** The resolved source before the retry wrapper. */\n readonly source: StorageChunkSource;\n readonly driver: IStorageDriver | undefined;\n readonly registry: IRegistryDriver | undefined;\n /** The backend the store was given, for its optional lifecycle check; `undefined` for a bare driver or a source. */\n readonly backend: StorageBackend | undefined;\n /** The read retry the store shares with its lifecycle reads; `undefined` when retry is off. */\n readonly retryOptions: RetryingOptions | undefined;\n}\n\n/**\n * A caller's partial policy, completed from {@link DEFAULT_RETRY_POLICY}, so tuning one field does not mean restating\n * all five.\n *\n * Each field is read for `undefined`, not by spreading over the default: a key that is present with the value\n * `undefined` (the ordinary shape of a value read from env or JSON, which `exactOptionalPropertyTypes`\n * being off lets through) must fall back to the default. A spread would let it replace the default with\n * `undefined`, giving `NaN` delays that `SystemClock.sleep` turns into a ~1 ms hot retry loop, with the\n * backoff bound and the herd protection gone and no error to show it.\n *\n * An omitted `maxDelayMs` is the default cap, or the `baseDelayMs` given when that is larger, so tuning only the\n * base delay never leaves a cap below it. A `maxDelayMs` given below the `baseDelayMs` is refused when the retrying\n * source checks the policy.\n */\nfunction resolveRetryPolicy(partial: Partial<RetryPolicy>): RetryPolicy {\n // Only an absent value is the default: a `null` is kept, and refused when the retrying source checks the policy.\n const orDefault = <K extends keyof RetryPolicy>(field: K): RetryPolicy[K] =>\n partial[field] === undefined ? DEFAULT_RETRY_POLICY[field] : (partial[field] as RetryPolicy[K]);\n const baseDelayMs = orDefault('baseDelayMs');\n return {\n maxAttempts: orDefault('maxAttempts'),\n baseDelayMs,\n maxDelayMs:\n partial.maxDelayMs === undefined\n ? typeof baseDelayMs === 'number' && baseDelayMs > DEFAULT_RETRY_POLICY.maxDelayMs\n ? baseDelayMs\n : DEFAULT_RETRY_POLICY.maxDelayMs\n : partial.maxDelayMs,\n backoffFactor: orDefault('backoffFactor'),\n jitter: orDefault('jitter'),\n };\n}\n\n/**\n * Resolve the storage seam, hand a backend the metrics sink, and wrap the source in the read retry. Refusals come in\n * that order: a bad `storage` first, then a bad `retry`.\n */\nexport function wireStore(\n options: StoreWiring,\n clock: Clock,\n rng: Rng,\n metrics: IMetricsSink,\n): WiredStore {\n // Resolve the Storage seam to a StorageChunkSource: a raw IStorageDriver is wrapped into the `.crbm` storage source\n // here (with the store's registry/keystore) so drivers are wired once; a pre-built source is used as-is.\n const resolved = resolveStorageSource(options, clock);\n // A backend that can say something about its own setup is handed the sink, never a no-op one.\n if (metrics !== NOOP_METRICS && isStorageBackend(options.storage)) {\n options.storage.attachMetrics?.(metrics);\n }\n let storage: StorageChunkSource = resolved.source;\n let retryOptions: RetryingOptions | undefined;\n // Resilience on by default: wrap the source so transient faults retry with jittered backoff. `false` opts\n // out (e.g. the injected client already retries); a RetryPolicy tunes it.\n if (options.retry !== false) {\n const { onRetry: userOnRetry, ...ov } = options.retry ?? {};\n if (userOnRetry !== undefined && typeof userOnRetry !== 'function') {\n throw new ValidationError('retry.onRetry must be a function');\n }\n retryOptions = {\n clock,\n rng,\n policy: resolveRetryPolicy(ov),\n // Bridge transient-fault retries into the metrics stream, then call the user's own hook.\n onRetry: (info) => {\n metrics.onEvent({\n kind: 'retry',\n reason: 'transient',\n attempt: info.attempt,\n delayMs: info.delayMs,\n });\n userOnRetry?.(info);\n },\n };\n storage = new RetryingStorageChunkSource(storage, retryOptions);\n }\n return {\n storage,\n source: resolved.source,\n driver: resolved.driver,\n registry: resolved.registry,\n backend: isStorageBackend(options.storage) ? options.storage : undefined,\n retryOptions,\n };\n}\n\n/**\n * Resolve the `storage` option to a {@link StorageChunkSource} at construction (wiring-time only \u2014 no hot-path cost).\n *\n * `storage` is discriminated by a **brand** for the backend arm and structurally for the other two, never by\n * `instanceof`, so a backend or driver from a different copy of the package still works (the same reason the error\n * predicates are brand-based): a raw {@link IStorageDriver} exposes `putImmutable`\n * (the byte-mover seam); a pre-built {@link StorageChunkSource} exposes `getChunk` (the engine's read seam). The\n * two interfaces are deliberately **disjoint** on these methods (an invariant the driver SDK maintains, pinned\n * by a test) \u2014 an object exposing *both* is ambiguous and rejected, as is one exposing *neither* (incl. a\n * nullish/non-object value from a JS caller): fail fast with a typed error rather than crash on a probe.\n *\n * A backend is wrapped into a {@link CrbmStorageChunkSource} over its storage half, pinned to its registry,\n * with the config's `encryption` group; a bare driver is wrapped the same way but without a\n * registry; a pre-built source is used as-is. `keystore`/`requireEncryption` are meaningful **only** where the\n * store builds the source itself \u2014 pairing either with a pre-built source is a wiring mistake, so reject it\n * rather than silently ignore it. The `CrbmStorageChunkSource` constructor enforces the rest (a keystore /\n * `requireEncryption` needs a registry, so they need a backend; the driver needs range reads).\n *\n * Returns the resolved `source` (what the engine reads through) **and** the raw `driver` when one was passed \u2014\n * the store keeps the raw driver so its lifecycle helpers and the `*Into` verbs can write generations without\n * you re-passing drivers. `driver` is `undefined` for a pre-built source (there's no underlying `IStorageDriver` to\n * write through, so its writes throw {@link UnsupportedError}).\n */\nfunction resolveStorageSource(\n options: StoreWiring,\n clock: Pick<Clock, 'now'>,\n): {\n source: StorageChunkSource;\n driver: IStorageDriver | undefined;\n registry: IRegistryDriver | undefined;\n} {\n const storage: unknown = options.storage;\n if (storage === null || typeof storage !== 'object') {\n throw new ValidationError(\n '`storage` must be a StorageBackend, an IStorageDriver, or a StorageChunkSource',\n );\n }\n const asBackend = storage as Partial<StorageBackend>;\n const isObject = (v: unknown): v is Record<string, unknown> =>\n v !== null && typeof v === 'object';\n const hasGetChunk = typeof (storage as Partial<StorageChunkSource>).getChunk === 'function';\n const hasPutImmutable = typeof (storage as Partial<IStorageDriver>).putImmutable === 'function';\n\n // The BRAND decides, not the shape. `{ storage, registry }` is also the shape of core's free-function deps\n // object, so before the brand any literal satisfied it \u2014 including one holding halves from two unrelated\n // stores, which the store accepted and then answered empty for a segment that holds data.\n const isBackend = isStorageBackend(storage);\n\n // A branded backend that ALSO quacks like a driver or a source is genuinely ambiguous. Unreachable for the\n // five classes, kept because the alternative to refusing is guessing.\n if (isBackend && (hasGetChunk || hasPutImmutable)) {\n throw new ValidationError(\n '`storage` is a StorageBackend that also exposes ' +\n `${hasGetChunk ? '`getChunk`' : '`putImmutable`'} \u2014 ambiguous. A backend must not also be a driver ` +\n 'or a source; pass whichever one you mean.',\n );\n }\n\n // Unbranded, but carrying both halves. Three sub-cases, and they want different things said.\n const hasStorageHalf = isObject(asBackend.storage);\n const hasRegistryHalf = isObject(asBackend.registry);\n\n // (a) A DRIVER that also carries a registry \u2014 the audit/metrics/tenant-scoping wrapper. Without this it\n // falls through to the bare-driver path, where there is no pointer at all: generations resolve by\n // list-scan, so the store answers from the HIGHEST object in the bucket rather than the published one, and\n // a load that wrote an object but never published it is served as if it had been. Silently, and with the\n // wrapper's registry sitting right there unused.\n if (!isBackend && hasPutImmutable && hasRegistryHalf) {\n throw new ValidationError(\n '`storage` looks like a driver that also carries a `registry`. Passed as a bare driver it would have ' +\n 'no pointer at all \u2014 generations would resolve by list-scan, so reads could serve a generation that ' +\n 'was written but never published. If you meant a backend, use a backend class \u2014 S3Storage, GcsStorage, ' +\n 'AzureBlobStorage, LocalFsStorage or MemoryStorage \u2014 or, to pair a driver of your own with a registry, ' +\n 'brand the pair with `brandAsBackend` from `@cloudbitmaps/core/driver-kit`.',\n );\n }\n\n // (b) Both halves, neither of them a driver or a source: the hand-assembled literal, or a spread of a real\n // backend with one half swapped. Name the classes AND the door \u2014 the five classes cannot express an\n // instrumented half or a foreign registry, which is exactly the case that lands here.\n if (!isBackend && !hasGetChunk && !hasPutImmutable && hasStorageHalf && hasRegistryHalf) {\n const storageOk =\n typeof (asBackend.storage as Partial<IStorageDriver>).putImmutable === 'function';\n const registryOk =\n typeof (asBackend.registry as Partial<IRegistryDriver>).compareAndSwap === 'function';\n // (c) \u2026and if a half is not actually a driver, say THAT rather than lecturing about buckets.\n if (!storageOk || !registryOk) {\n const bad = !storageOk\n ? '`storage` half is not an IStorageDriver (no `putImmutable`)'\n : '`registry` half is not an IRegistryDriver (no `compareAndSwap`)';\n throw new ValidationError(\n '`storage` looks like a backend but its ' +\n bad +\n ' \u2014 use a backend class, or brand a pair of drivers with `brandAsBackend` from ' +\n '`@cloudbitmaps/core/driver-kit`.',\n );\n }\n throw new ValidationError(\n '`storage` must be a backend \u2014 S3Storage, GcsStorage, AzureBlobStorage, LocalFsStorage or ' +\n 'MemoryStorage. An object with `.storage` and `.registry` is not one: a backend builds both halves ' +\n 'from a single bucket and prefix, so they cannot disagree, and hand-assembling them re-opens exactly ' +\n 'that mismatch \u2014 a store whose pointer and generations live in different places reads as empty ' +\n 'rather than failing. A driver author who genuinely wants halves of their own \u2014 an instrumented driver, ' +\n 'a registry in a database you already run \u2014 brands the pair with `brandAsBackend` from ' +\n '`@cloudbitmaps/core/driver-kit`, which is taking on that they agree.',\n );\n }\n\n if (isBackend) {\n const backend = storage as StorageBackend;\n return {\n source: new CrbmStorageChunkSource(backend.storage, {\n registry: backend.registry,\n keystore: options.encryption?.keystore,\n requireEncryption: options.encryption?.required,\n clock,\n currentGenTtlMs: options.cache?.genTtlMs,\n maxOpenSegments: options.cache?.readerMax,\n maxOpenIndexBytes: options.cache?.readerMaxBytes,\n }),\n driver: backend.storage,\n registry: backend.registry,\n };\n }\n\n if (hasGetChunk && hasPutImmutable) {\n throw new ValidationError(\n '`storage` exposes both `getChunk` and `putImmutable` \u2014 ambiguous; pass a StorageBackend, an IStorageDriver, or a StorageChunkSource, not a hybrid',\n );\n }\n if (!hasGetChunk && !hasPutImmutable) {\n throw new ValidationError(\n '`storage` must be a StorageBackend, an IStorageDriver, or a StorageChunkSource',\n );\n }\n if (hasGetChunk) {\n // Already a StorageChunkSource \u2014 used as-is. `keystore`/`requireEncryption` only apply when the store\n // builds the source itself; with a source of the caller's own they are inert, so reject them rather than mislead.\n if (options.encryption?.keystore !== undefined || options.encryption?.required === true) {\n throw new ValidationError(\n 'keystore/requireEncryption apply only when the store builds its own read path: a StorageChunkSource of ' +\n 'your own reads an encrypted segment by itself, if it must; to have the store decrypt, pass a backend',\n );\n }\n return { source: storage as StorageChunkSource, driver: undefined, registry: undefined };\n }\n // A bare IStorageDriver: no pointer, so generations resolve by list-scan. Cleartext, read-only.\n const driver = storage as IStorageDriver;\n return {\n source: new CrbmStorageChunkSource(driver, {\n keystore: options.encryption?.keystore,\n requireEncryption: options.encryption?.required,\n clock,\n currentGenTtlMs: options.cache?.genTtlMs,\n maxOpenSegments: options.cache?.readerMax,\n maxOpenIndexBytes: options.cache?.readerMaxBytes,\n }),\n driver,\n registry: undefined,\n };\n}\n", "/**\n * The shape checks every call that takes an options bag makes before it reads or writes anything: the bag is an\n * object, it names only keys the call takes, and each switch is a boolean. The per-call key tables stay with the\n * facade, because each is held to the options type it describes.\n */\nimport { ValidationError } from '@cloudbitmaps/core';\n\n/** A key of `T` that `K` does not list: a key table missing one fails to compile. */\ntype Unlisted<T, K extends readonly PropertyKey[]> = Exclude<keyof T, K[number]>;\n\n/** The keys of `T`, every one of them, as a table the options check below reads. */\nexport const keysOf =\n <T>() =>\n <const K extends readonly (keyof T & string)[]>(\n keys: K & ([Unlisted<T, K>] extends [never] ? unknown : never),\n ): readonly string[] =>\n keys;\n\n/** How a value of the wrong kind is named in a message: by its kind, never by its content. */\nexport const kindOf = (v: unknown): string =>\n v === null ? 'null' : Array.isArray(v) ? 'an array' : `a ${typeof v}`;\n\n/**\n * Why `options` cannot be a call's options, or `undefined` when it can. `undefined` and `null` read as none; anything\n * but an object is refused, and so is a key `known` does not list, unless its value is `undefined`, so a spread of\n * options keeps working; and each of `booleans` present must be a boolean, `null` included. A bag of the wrong shape, a misspelt key or\n * a switch given as a string would otherwise read as no option at all, and silently widen what the call does: a scope\n * passed as a string swept every namespace, and `dryRun: 'true'` deleted.\n *\n * `misplaced` names the keys of a wider options type that the call does not take, such as `exclude` on `andNot`, which\n * shares its options type with the combines that do. Each is read by name, so one inherited from a prototype or held\n * in a getter, which `Object.keys` does not list, is refused as an own key is, rather than dropped without a word.\n */\nexport function optionsError(\n options: unknown,\n op: string,\n known: readonly string[],\n booleans: readonly string[] = [],\n misplaced: readonly string[] = [],\n): ValidationError | undefined {\n if (options === undefined || options === null) return undefined;\n if (typeof options !== 'object' || Array.isArray(options)) {\n return new ValidationError(`${op}: options must be an object; got ${kindOf(options)}`);\n }\n const bag = options as Record<string, unknown>;\n const unknown = Object.keys(bag).filter((k) => !known.includes(k) && bag[k] !== undefined);\n for (const k of misplaced) if (!unknown.includes(k) && bag[k] !== undefined) unknown.push(k);\n if (unknown.length > 0) {\n return new ValidationError(\n `${op}: unknown option${unknown.length > 1 ? 's' : ''} ${unknown.map((k) => `\"${k}\"`).join(', ')}; ` +\n `it takes { ${known.join(', ')} }`,\n );\n }\n // An `audit` that is not a sink would receive nothing and say nothing: refused here, before the call reads or scans\n // anything, as the core entries refuse it before they write.\n const audit = bag.audit;\n if (\n audit !== undefined &&\n audit !== null &&\n typeof (audit as { onEvent?: unknown }).onEvent !== 'function'\n ) {\n return new ValidationError(\n `${op}: audit must be a sink with an onEvent(event) method, such as a RecordingAuditSink`,\n );\n }\n // A switch is `true` or `false`. `null` is refused with the rest: read as absent, `dryRun: null` dropped for real.\n for (const name of booleans) {\n const v = bag[name];\n if (v !== undefined && typeof v !== 'boolean') {\n return new ValidationError(`${op}: \\`${name}\\` must be a boolean; got ${kindOf(v)}`);\n }\n }\n return undefined;\n}\n\n/**\n * The keys of `options` a call takes, each read by name. A spread copies only own enumerable properties, so an option\n * held in a getter or inherited from a prototype, which TypeScript accepts and {@link optionsError} reads, would pass\n * the checks and then be dropped: a `dryRun` so held ran a real sweep, and a `namespace` exported every tenant. The\n * call then reads the copy only, so it runs with exactly what was checked.\n */\nexport function picked<T extends object>(\n options: T | null | undefined,\n keys: readonly string[],\n): Partial<T> {\n const out: Record<string, unknown> = {};\n if (options === undefined || options === null) return out as Partial<T>;\n for (const key of keys) {\n const value = (options as Record<string, unknown>)[key];\n if (value !== undefined) out[key] = value;\n }\n return out as Partial<T>;\n}\n\n/** {@link optionsError}, thrown: for a call that rejects, rather than one that returns a stream. */\nexport function checkOptions(\n options: unknown,\n op: string,\n known: readonly string[],\n booleans?: readonly string[],\n misplaced?: readonly string[],\n): void {\n const err = optionsError(options, op, known, booleans, misplaced);\n if (err !== undefined) throw err;\n}\n", "/**\n * `RoaringBitmap`: a mutable set of unsigned 32-bit ids, in TypeScript on typed arrays, with no native addon. It is a\n * thin public shell around the codec's own bitmap (`ts-roaring/bitmap.ts`): the shell checks every argument (an id is\n * an integer from 0 to 4,294,967,295, and a refusal never repeats the value), and the codec does the work.\n *\n * ```ts\n * import { RoaringBitmap } from '@cloudbitmaps/roaring';\n *\n * const a = new RoaringBitmap([1, 5, 70_000]);\n * a.add(9).has(9); // true\n * const bytes = a.serialize();\n * RoaringBitmap.deserialize(bytes).size; // 4\n * ```\n *\n * The portable bytes are the codec's, so what `serialize()` writes a store loads and what a store holds,\n * `RoaringBitmap.deserialize` reads. Bytes you did not write go through `deserialize` only: it caps their size,\n * checks their structure and builds one whole bitmap whose storage is its own, so keeping it keeps no copy of the\n * input alive.\n */\nimport {\n MAX_SERIALIZED_LOAD_BYTES,\n ValidationError,\n decodeSerialized,\n refusalOfId,\n} from '@cloudbitmaps/core';\nimport type { CodecInterface } from '@cloudbitmaps/core';\nimport { COUNT_BY_KERNELS } from './count-route';\nimport { checkOptions, kindOf, picked } from './options';\nimport { TsBitmap, collect, tsRoaringCodec } from './ts-roaring/bitmap';\n\n/** What {@link RoaringBitmap.deserialize} takes as its second argument. */\nexport interface RoaringBitmapDeserializeOptions {\n /**\n * A cap on the input's size in bytes, lower than the one every decode has (537,403,396, the most any canonical\n * 32-bit bitmap serializes to). Bytes over it are refused before any is read. It can only lower the cap: a value\n * above it, or one that is not a non-negative integer, is a `ValidationError`.\n */\n readonly maxBytes?: number;\n}\n\n/** `Object.prototype.toString`'s tag, which names a typed array's kind across realms and for `Buffer` too. */\nfunction tagOf(value: unknown): string {\n return Object.prototype.toString.call(value).slice(8, -1);\n}\n\nconst VIEW = Object.getPrototypeOf(Uint8Array.prototype) as object;\nconst viewGetter = (name: 'buffer'): ((this: unknown) => unknown) =>\n Object.getOwnPropertyDescriptor(VIEW, name)?.get as (this: unknown) => unknown;\nconst bufferOf = viewGetter('buffer');\n\nconst plainByteLength = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'byteLength')\n ?.get as (this: unknown) => unknown;\nconst hasSharedMemory = typeof SharedArrayBuffer === 'function';\n\n/**\n * Whether the typed array's memory may be a `SharedArrayBuffer`'s, by brand: another thread may write it while it is\n * read. `ArrayBuffer`'s own `byteLength` getter returns for a genuine `ArrayBuffer` (so ordinary memory costs no throw)\n * and throws for anything else, which is then treated as shared and copied; a `Symbol.toStringTag` can be given any\n * value, the brand cannot. False on a runtime without a `SharedArrayBuffer`.\n */\nfunction inSharedMemory(ids: Uint32Array): boolean {\n if (!hasSharedMemory) return false;\n try {\n plainByteLength.call(bufferOf.call(ids));\n return false;\n } catch {\n return true;\n }\n}\n\n/** An id, or the refusal that names what is wrong with it and never repeats it. */\nfunction checkedId(id: unknown): number {\n if (typeof id !== 'number' || id >>> 0 !== id) throw refusalOfId(id);\n return id;\n}\n\nfunction oneIdOnly(method: string, bulk: string): ValidationError {\n return new ValidationError(`${method} takes one id; use ${bulk} for several`);\n}\n\n/**\n * The ids to act on, as something the codec reads once and never keeps: a typed array that is, or may be, in shared memory is copied first\n * (it is read twice, to see whether it ascends and then to build, and another thread could write between the reads).\n *\n * @throws {ValidationError} for anything that is not an iterable of ids, and for bytes, which would read as ids.\n */\nfunction idsOf(values: unknown): Iterable<number> {\n if (typeof values !== 'object' || values === null || !(Symbol.iterator in values)) {\n throw new ValidationError('values must be an iterable of ids');\n }\n const tag = tagOf(values);\n if (tag === 'Uint8Array' || tag === 'Uint8ClampedArray') {\n throw new ValidationError(\n `values are ids, and this is a ${tag === 'Uint8Array' ? 'Uint8Array or Buffer' : tag}: each byte would be ` +\n `read as an id. To read portable bytes, call RoaringBitmap.deserialize(bytes).`,\n );\n }\n if (values instanceof Uint32Array && inSharedMemory(values)) return new Uint32Array(values);\n return values as Iterable<number>;\n}\n\n/** The codec with its decode detached: each container of a decoded bitmap owns its storage. */\nconst detachedCodec: CodecInterface = {\n ...tsRoaringCodec,\n safeDeserialize: (bytes, maxBytes, options) =>\n TsBitmap.safeDeserialize(bytes, maxBytes, { ...options, detached: true }),\n};\n\nfunction maxBytesOf(options: unknown): number {\n if (options === undefined) return MAX_SERIALIZED_LOAD_BYTES;\n if (typeof options !== 'object' || options === null) {\n throw new ValidationError(\n `deserialize takes no format argument, the format is always portable; its second argument is ` +\n `{ maxBytes } or nothing, not ${kindOf(options)}`,\n );\n }\n checkOptions(options, 'RoaringBitmap.deserialize', ['maxBytes']);\n const { maxBytes } = picked(options as RoaringBitmapDeserializeOptions | undefined, ['maxBytes']);\n if (maxBytes === undefined) return MAX_SERIALIZED_LOAD_BYTES;\n if (!Number.isInteger(maxBytes) || maxBytes < 0 || maxBytes > MAX_SERIALIZED_LOAD_BYTES) {\n throw new ValidationError(\n `maxBytes must be an integer from 0 to ${MAX_SERIALIZED_LOAD_BYTES}, the size no canonical bitmap exceeds`,\n );\n }\n return maxBytes;\n}\n\n/**\n * A mutable set of integers from 0 to 4,294,967,295 (unsigned 32-bit ids) with set algebra and the portable Roaring\n * serialization. It is not designed for subclassing, and `JSON.stringify` of one gives `\"{}\"`: write\n * `JSON.stringify([...bitmap])` or `bitmap.toArray()`. Passed to a method of the `roaring` package from npm in place of a\n * `RoaringBitmap32`, it answers wrongly without throwing in JavaScript (TypeScript refuses the call): decode its\n * `serialize()` bytes with that package instead.\n *\n * Every id argument is checked: a value that is not an integer in range (a fraction, `NaN`, a string, `null`, a\n * negative, one too large) throws `ValidationError`, whose message never repeats it, and the bitmap is unchanged.\n * Iterating while changing the bitmap is unsupported: collect first with `toUint32Array()`, or iterate a `clone()`.\n * Everything is synchronous.\n */\nexport class RoaringBitmap implements Iterable<number> {\n #bitmap: TsBitmap;\n\n /**\n * A bitmap of `values`: an array or another iterable of ids, a `Uint32Array` (read in place when it already ascends,\n * else sorted on a copy; it is never changed or kept), or another `RoaringBitmap` (a copy-on-write `clone()`).\n * With no argument it is empty.\n *\n * @throws {ValidationError} for an id that is not an integer from 0 to 4294967295; for a value that is not an\n * iterable (`null`, a number, a string, an object, an `ArrayBuffer`); and for a `Uint8Array`, `Uint8ClampedArray` or\n * `Buffer`, which would read each byte as an id: call {@link RoaringBitmap.deserialize} for bytes.\n */\n constructor(values?: Iterable<number>) {\n if (values === undefined) {\n this.#bitmap = TsBitmap.empty();\n } else if (RoaringBitmap.#is(values)) {\n this.#bitmap = values.#bitmap.clone();\n } else {\n this.#bitmap = TsBitmap.fromValues(idsOf(values));\n }\n }\n\n /**\n * Decode portable Roaring bytes you hold, through the check a `{ serialized }` load makes first: a size cap, a\n * structural check and one whole bitmap, and only then the decoder. The result owns its storage: it keeps nothing\n * of `bytes`, so a large input that is decoded and then reduced can be freed.\n *\n * @param bytes a `Uint8Array`, which a Node `Buffer` is.\n * @param options `{ maxBytes }` lowers the size cap below the default of 537,403,396 bytes.\n * @throws {ValidationError} for something that is not a `Uint8Array`; an empty or detached one (an empty buffer is\n * not a bitmap: `new RoaringBitmap()` is the empty set); one over the cap or `maxBytes`; bytes that are not exactly\n * one well-formed portable bitmap, including bytes after its last container; a second argument that is not\n * `undefined` or an object whose only key is `maxBytes` (a format argument such as `'portable'` is one); and a\n * `maxBytes` that is not an integer from 0 to the cap.\n */\n static deserialize(bytes: Uint8Array, options?: RoaringBitmapDeserializeOptions): RoaringBitmap {\n const maxBytes = maxBytesOf(options);\n return RoaringBitmap.#wrap(\n decodeSerialized(bytes, detachedCodec, 'the buffer', {\n maxBytes,\n refuseEmpty: true,\n }) as TsBitmap,\n );\n }\n\n /** Whether `value` is a `RoaringBitmap` of this copy of the package. */\n static #is(value: unknown): value is RoaringBitmap {\n return typeof value === 'object' && value !== null && #bitmap in value;\n }\n\n static #wrap(bitmap: TsBitmap): RoaringBitmap {\n const out = new RoaringBitmap();\n out.#bitmap = bitmap;\n return out;\n }\n\n /** The codec bitmap of an operand, or a refusal that says what combines with what. */\n static #operand(other: unknown): TsBitmap {\n if (!RoaringBitmap.#is(other)) {\n throw new ValidationError(\n 'a RoaringBitmap combines only with another RoaringBitmap of this copy of the package',\n );\n }\n return other.#bitmap;\n }\n\n /** How many ids it holds. */\n get size(): number {\n return this.#bitmap.size;\n }\n\n /** Whether it holds no id. */\n get isEmpty(): boolean {\n return this.#bitmap.isEmpty;\n }\n\n /**\n * Whether it holds `id`.\n *\n * @throws {ValidationError} for a value that is not an integer from 0 to 4294967295.\n */\n has(id: number): boolean {\n return this.#bitmap.has(checkedId(id));\n }\n\n /** The smallest id, or `undefined` when it is empty. */\n minimum(): number | undefined {\n return this.#bitmap.minimum();\n }\n\n /** The largest id, or `undefined` when it is empty. */\n maximum(): number | undefined {\n return this.#bitmap.maximum();\n }\n\n /**\n * Add one id; returns this bitmap, for chaining.\n *\n * @throws {ValidationError} for a value that is not an integer from 0 to 4294967295, and for a second argument:\n * use {@link RoaringBitmap.addMany} to add several.\n */\n add(id: number): this {\n if (arguments.length !== 1) throw oneIdOnly('add', 'addMany');\n this.#bitmap.add(checkedId(id));\n return this;\n }\n\n /**\n * Add every id of `values` (an iterable of ids, or a `Uint32Array`); returns this bitmap. Nothing is added if any\n * of them is refused.\n *\n * @throws {ValidationError} as the constructor does.\n */\n addMany(values: Iterable<number>): this {\n if (RoaringBitmap.#is(values)) this.#bitmap.orInPlace(values.#bitmap);\n else this.#bitmap.addMany(idsOf(values));\n return this;\n }\n\n /**\n * Remove one id; whether it was there.\n *\n * @throws {ValidationError} for a value that is not an integer from 0 to 4294967295, and for a second argument:\n * use {@link RoaringBitmap.removeMany} to remove several.\n */\n remove(id: number): boolean {\n if (arguments.length !== 1) throw oneIdOnly('remove', 'removeMany');\n return this.#bitmap.remove(checkedId(id));\n }\n\n /**\n * Remove every id of `values` (an iterable of ids, or a `Uint32Array`); returns this bitmap. Nothing is removed if\n * any of them is refused.\n *\n * @throws {ValidationError} as the constructor does.\n */\n removeMany(values: Iterable<number>): this {\n if (RoaringBitmap.#is(values)) this.#bitmap.andNotInPlace(values.#bitmap);\n else this.#bitmap.removeMany(collect(idsOf(values)));\n return this;\n }\n\n /** Remove every id. */\n clear(): void {\n this.#bitmap.clear();\n }\n\n /**\n * A copy. It is copy-on-write: the copy costs the key list and one flag per container, not the ids, and the first\n * write to a container on either side copies that container once.\n */\n clone(): RoaringBitmap {\n return RoaringBitmap.#wrap(this.#bitmap.clone());\n }\n\n /**\n * Keep only the ids `other` also holds; returns this bitmap. `other` is not changed, and may be this bitmap.\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n andInPlace(other: RoaringBitmap): this {\n this.#bitmap.andInPlace(RoaringBitmap.#operand(other));\n return this;\n }\n\n /**\n * Add the ids `other` holds; returns this bitmap. `other` is not changed, and may be this bitmap.\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n orInPlace(other: RoaringBitmap): this {\n this.#bitmap.orInPlace(RoaringBitmap.#operand(other));\n return this;\n }\n\n /**\n * Remove the ids `other` holds; returns this bitmap. `other` is not changed, and may be this bitmap.\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n andNotInPlace(other: RoaringBitmap): this {\n this.#bitmap.andNotInPlace(RoaringBitmap.#operand(other));\n return this;\n }\n\n /**\n * Flip the ids `other` holds: keep those only this bitmap holds, add those only `other` holds; returns this bitmap.\n * `other` is not changed, and may be this bitmap (the result is then empty).\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n xorInPlace(other: RoaringBitmap): this {\n this.#bitmap.xorInPlace(RoaringBitmap.#operand(other));\n return this;\n }\n\n /**\n * How many ids both bitmaps hold, without building the intersection. Neither bitmap changes; `other` may be this one.\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n andCardinality(other: RoaringBitmap): number {\n const that = RoaringBitmap.#operand(other);\n return COUNT_BY_KERNELS\n ? this.#bitmap.andCardinality(that)\n : TsBitmap.and(this.#bitmap, that).size;\n }\n\n /**\n * How many ids either bitmap holds. Neither bitmap changes; `other` may be this one.\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n orCardinality(other: RoaringBitmap): number {\n const that = RoaringBitmap.#operand(other);\n return COUNT_BY_KERNELS\n ? this.#bitmap.orCardinality(that)\n : TsBitmap.or(this.#bitmap, that).size;\n }\n\n /**\n * How many ids exactly one of the bitmaps holds. Neither bitmap changes; `other` may be this one.\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n xorCardinality(other: RoaringBitmap): number {\n const that = RoaringBitmap.#operand(other);\n return COUNT_BY_KERNELS\n ? this.#bitmap.xorCardinality(that)\n : TsBitmap.xor(this.#bitmap, that).size;\n }\n\n /**\n * How many ids this bitmap holds that `other` lacks. Neither bitmap changes; `other` may be this one.\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n andNotCardinality(other: RoaringBitmap): number {\n const that = RoaringBitmap.#operand(other);\n return COUNT_BY_KERNELS\n ? this.#bitmap.andNotCardinality(that)\n : TsBitmap.andNot(this.#bitmap, that).size;\n }\n\n /**\n * Whether the bitmaps share an id. Neither bitmap changes; `other` may be this one.\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n intersects(other: RoaringBitmap): boolean {\n const that = RoaringBitmap.#operand(other);\n return COUNT_BY_KERNELS\n ? this.#bitmap.intersects(that)\n : !TsBitmap.and(this.#bitmap, that).isEmpty;\n }\n\n /**\n * Whether every id of this bitmap is in `other` (an empty bitmap is a subset of every bitmap, itself included). Neither\n * bitmap changes. Unlike the `roaring` package, which answers `false`, a value that is not a bitmap is refused.\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n isSubset(other: RoaringBitmap): boolean {\n return this.#bitmap.isSubset(RoaringBitmap.#operand(other));\n }\n\n /**\n * Whether both bitmaps hold exactly the same ids, whatever the kinds of their containers or the bytes they would\n * serialize to. Neither bitmap changes.\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n isEqual(other: RoaringBitmap): boolean {\n return this.#bitmap.isEqual(RoaringBitmap.#operand(other));\n }\n\n /**\n * The ids both bitmaps hold, as a new bitmap. Neither operand changes, and the result holds storage of its own.\n *\n * @throws {ValidationError} if an operand is not a `RoaringBitmap` of this copy of the package.\n */\n static and(a: RoaringBitmap, b: RoaringBitmap): RoaringBitmap {\n return RoaringBitmap.#wrap(TsBitmap.and(RoaringBitmap.#operand(a), RoaringBitmap.#operand(b)));\n }\n\n /**\n * The ids either bitmap holds, as a new bitmap. Neither operand changes. A container only `a` holds is shared with\n * the result copy-on-write, so the next write to it, on either side, copies it once.\n *\n * @throws {ValidationError} if an operand is not a `RoaringBitmap` of this copy of the package.\n */\n static or(a: RoaringBitmap, b: RoaringBitmap): RoaringBitmap {\n return RoaringBitmap.#wrap(TsBitmap.or(RoaringBitmap.#operand(a), RoaringBitmap.#operand(b)));\n }\n\n /**\n * The ids exactly one of the bitmaps holds, as a new bitmap. Neither operand changes (see {@link RoaringBitmap.or}\n * for what is shared).\n *\n * @throws {ValidationError} if an operand is not a `RoaringBitmap` of this copy of the package.\n */\n static xor(a: RoaringBitmap, b: RoaringBitmap): RoaringBitmap {\n return RoaringBitmap.#wrap(TsBitmap.xor(RoaringBitmap.#operand(a), RoaringBitmap.#operand(b)));\n }\n\n /**\n * The ids of `a` that `b` lacks, as a new bitmap. Neither operand changes (see {@link RoaringBitmap.or} for what is\n * shared).\n *\n * @throws {ValidationError} if an operand is not a `RoaringBitmap` of this copy of the package.\n */\n static andNot(a: RoaringBitmap, b: RoaringBitmap): RoaringBitmap {\n return RoaringBitmap.#wrap(\n TsBitmap.andNot(RoaringBitmap.#operand(a), RoaringBitmap.#operand(b)),\n );\n }\n\n /**\n * The union of every bitmap of `bitmaps`, as a new bitmap that owns its storage (an empty list gives the empty set).\n * No operand changes, and none is flagged: the result accumulates in containers of its own.\n *\n * @throws {ValidationError} if `bitmaps` is not an iterable, or holds anything that is not a `RoaringBitmap` of this\n * copy of the package; nothing is combined then.\n */\n static orMany(bitmaps: Iterable<RoaringBitmap>): RoaringBitmap {\n if (typeof bitmaps !== 'object' || bitmaps === null || !(Symbol.iterator in bitmaps)) {\n throw new ValidationError('orMany takes an iterable of RoaringBitmap');\n }\n const parts = Array.from(bitmaps, (b) => RoaringBitmap.#operand(b));\n return RoaringBitmap.#wrap(TsBitmap.orMany(parts));\n }\n\n /** The ids in ascending order, each once. A bitmap that changes during the walk gives unspecified ids, and no error. */\n [Symbol.iterator](): IterableIterator<number> {\n return this.#bitmap[Symbol.iterator]();\n }\n\n /** The ids as a new ascending array. A bitmap too large to allocate as one throws the runtime's `RangeError`. */\n toArray(): number[] {\n return this.#bitmap.toArray();\n }\n\n /** The ids as a new ascending `Uint32Array` the caller owns, never a view of the bitmap's storage. */\n toUint32Array(): Uint32Array {\n return this.#bitmap.toUint32Array();\n }\n\n /**\n * The portable Roaring bytes, in a new `Uint8Array`. Call {@link RoaringBitmap.runOptimize} first when the bitmap was\n * decoded from bytes another writer made: its run containers stay as they were, and a bitmap that serializes over\n * the size cap is refused by a load.\n *\n * @param format `'portable'`, the only format there is, or nothing.\n * @throws {ValidationError} for any other argument.\n */\n serialize(format?: 'portable'): Uint8Array {\n if (format !== undefined && format !== 'portable') {\n throw new ValidationError(\n `a bitmap serializes only as serialize() or serialize('portable'); got ${kindOf(format)}`,\n );\n }\n return this.#bitmap.serialize();\n }\n\n /**\n * Re-encode every container in the smallest form (a run container only where it is strictly smaller than the plain\n * one), so `serialize()` afterwards depends on the set alone. Membership is unchanged.\n *\n * @returns whether the bitmap holds at least one run container afterwards, not whether anything changed.\n */\n runOptimize(): boolean {\n this.#bitmap.optimize();\n return this.#bitmap.hasRunContainer();\n }\n}\n", "/**\n * How the four cardinalities and `intersects` of `RoaringBitmap` are answered: from the containers, with the count\n * kernels (`true`), or by building the combination and counting it (`false`). Both routes give the same answers and\n * change no operand; only the cost differs. `isSubset` and `isEqual` always use their kernels.\n *\n * `true` because the count bench's record (`bench/count-kernels-results.json`) has the count's median below the build's\n * on every data set it judges. One switch, so a measurement that finds the build-then-count route cheaper changes this\n * line and nothing else.\n */\nexport const COUNT_BY_KERNELS = true;\n"],
5
- "mappings": ";AA0BA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA,0BAAAA;AAAA,EACA;AAAA,EACA,wBAAAC;AAAA,EACA;AAAA,EACA,gBAAAC;AAAA,EACA,8BAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,oBAAAC;AAAA,EACA,mBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;AClDA,IAAM,sBAAN,MAAoD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASzD,YACmB,OACjB,SACiB,QACjB;AAHiB;AAEA;AAEjB,QAAI,YAAY,KAAM,MAAK,KAAK,IAAI,OAAO;AAAA,EAC7C;AAAA,EALmB;AAAA,EAEA;AAAA;AAAA,EAVF,OAAO,oBAAI,IAAY;AAAA,EAexC,eAA2D;AACzD,WAAO,KAAK,MAAM,aAAa;AAAA,EACjC;AAAA,EAEA,MAAM,aACJ,KACA,OAC4C;AAC5C,UAAM,UAAU,MAAM,KAAK,MAAM,aAAa,KAAK,KAAK;AACxD,SAAK,KAAK,IAA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9D,aAAO,MAAM,KAAK,QAAQ,KAAK,SAAS,IAAI,OAAO,QAAQ,KAAK,KAAKD,OAAMC,KAAI,CAAC,CAAC;AAAA,IACnF;AACA,UAAM,OAAO,CAAC,KAAK,KAAK,GAAG,SAAS,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC;AACrD,UAAM,OAAO,KAAK,OAAO,SAAS,OAAO;AACzC,WAAO;AAAA,MACL,KAAK;AAAA,QACH;AAAA,QACA;AAAA,QACA,SAAS,UAAU,IAAI,MAAM,QAAQ,MAAM,IAAI,IAAI,IAAI,UAAU,QAAQ,MAAM,IAAI;AAAA,MACrF;AAAA,IACF;AAAA,EACF;AAAA;AAAA,EAGQ,YACN,MACA,MACA,UACA,SAC4B;AAC5B,UAAM,OAAO,KAAK,MAAM,GAAG,CAAC,OAAO,MAAM;AACzC,UAAM,SAAS;AAAA,MACb;AAAA,MACA,SAAS,WAAW,GAAG,IAAI,mBAAmB,GAAG,IAAI;AAAA,IACvD;AACA,UAAM,WAAW,SAAS,WAAW,cAAc,KAAK,WAAW,OAAO;AAC1E,UAAM,MAAM,SAAS,SAAS,IAAI,CAAC,GAAG,QAAQ,GAAG,QAAQ,IAAI;AAC7D,SAAK,kBAAkB,MAAM,MAAM,QAAQ,QAAQ;AAGnD,SAAK,cAAc,CAAC,MAAM,GAAG,GAAG,CAAC;AACjC,WAAO,KAAK;AAAA,MAAM;AAAA,MAAM,MACtB,KAAK;AAAA,QACH,KAAK;AAAA,QACL,IAAI,cAAc,KAAK,UAAU,WAAW,MAAM,UAAU,OAAO,CAAC;AAAA,QACpE;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
6
- "names": ["CrbmStorageChunkSource", "DEFAULT_RETRY_POLICY", "NOOP_METRICS", "RetryingStorageChunkSource", "UnsupportedError", "ValidationError", "IntegrityError", "ValidationError", "size", "ARRAY", "RUN", "ARRAY", "RUN", "u16", "i", "j", "r", "out", "words", "x", "y", "ARRAY", "IntegrityError", "ARRAY", "RUN", "IntegrityError", "out", "lowerBound", "RUN", "IntegrityError", "ValidationError", "ValidationError", "ValidationError", "ValidationError", "refusalOfId", "checkedId", "refusalOfId", "ValidationError", "excludingReservedRows", "ValidationError", "WriteConflictError", "IntegrityError", "NotFoundError", "UnsupportedError", "BudgetExceededError", "LeaseExpiredError", "errorKind", "NOOP_METRICS", "CrbmStorageChunkSource", "options", "pins", "RetryingStorageChunkSource", "listed", "at", "DEFAULT_RETRY_POLICY", "refs", "opts"]
4
+ "sourcesContent": ["/**\n * CloudRoaring \u2014 distributed, cloud-native Roaring Bitmaps, read from object storage.\n *\n * The `CloudRoaring` class is the read engine over **loaded** segments: write-once `.crbm` generations in an\n * object store, behind one registry pointer per segment. You wire storage **once**, as a single config object:\n * pass a **backend** as `storage` \u2014 `S3Storage`, `GcsStorage`, `AzureBlobStorage`, `LocalFsStorage` or\n * `MemoryStorage` \u2014 and it carries both halves, the generations and the pointer, from one bucket and one\n * prefix. Add `encryption: { keystore }` for encryption-at-rest / crypto-shred.\n *\n * Two narrower shapes are also accepted for `storage`: a bare {@link IStorageDriver}, which has no pointer and\n * so resolves generations by list-scanning storage (**cleartext and read-only**), and a {@link StorageChunkSource}\n * of your own, a read source the store uses as it is (both ports are in `@cloudbitmaps/core/driver-kit`).\n *\n * **Data gets in by loading a generation**, never by mutating one: `store.load()` streams a set of ids into one\n * immutable object and advances the segment's pointer to it. The pointer only moves forward, so a load out-raced by\n * a newer generation reports `superseded` instead of landing, and so does one that read the row when the row has\n * changed since. Every other write in the library is a load in\n * disguise \u2014 `intersectInto`/`unionInto`/`andNotInto` write a new generation of their destination, and\n * `eraseSubject` rewrites a generation without one id. Reads (`has`/`count`/`iterate`/`intersect`/`union`/`andNot`)\n * see whole, checksum-verified generations and nothing else.\n *\n * In-process lifecycle helpers \u2014 `eraseSubject`, `subjectReport`, `dropSegment`, `retireExpired`,\n * `checkConsistency`, `exportSegments` \u2014 reuse the store's own drivers, so you never re-pass them (they need the\n * store built with a backend). See the README and the getting-started guide.\n */\n\nimport {\n BoundedLru,\n PinnedStorageChunkSource,\n segmentKey,\n CrbmStorageChunkSource,\n DEFAULT_BUDGET,\n DEFAULT_RETRY_POLICY,\n withRetry,\n NOOP_METRICS,\n RetryingStorageChunkSource,\n SegmentEngine,\n LEASE_SKEW_MS,\n BudgetExceededError,\n LeaseExpiredError,\n MAX_LEASE_MS,\n NotFoundError,\n UnsupportedError,\n ValidationError,\n errorKind,\n WriteConflictError,\n checkBudget,\n collectWithinBudget,\n excludingReservedRows,\n dropSegment,\n eraseIdFromSegment,\n findIdUnderTombstone,\n judgeLoad,\n loadSegment,\n loadSegmentChunks,\n compileCombineMany,\n rebindCombineMany,\n runCombineMany,\n mapWithConcurrency,\n resolveBudget,\n resolvePerOpBudget,\n retireExpired,\n runConsistencyCheck,\n runExport,\n setSegmentRetention,\n clearSegmentRetention,\n getSegmentRetention,\n releaseLease,\n safeMetrics,\n splitId,\n takeLease,\n} from '@cloudbitmaps/core';\nimport {\n pointerIdOf,\n requireBool,\n requirePositiveInt,\n validateSegmentRef,\n} from '@cloudbitmaps/core/driver-kit';\nimport type { PinLease } from '@cloudbitmaps/core';\nimport type {\n Budget,\n BudgetOption,\n GenerationEntry,\n GenerationMetadata,\n LoadGuard,\n LoadInput,\n LoadOptions,\n LoadRefusal,\n LoadResult,\n RollbackResult,\n Clock,\n Entropy,\n CodecBitmap,\n CodecInterface,\n ConsistencyReport,\n EngineDeps,\n DropResult,\n ExportManifest,\n ExportOptions,\n ExportSink,\n IAuditSink,\n IMetricsSink,\n MetricOpName,\n RetentionPolicy,\n RetireExpiredOptions,\n RetireExpiredResult,\n RetryPolicy,\n RetryingOptions,\n Rng,\n SetRetentionResult,\n PinnedAt,\n SegmentRef,\n} from '@cloudbitmaps/core';\nimport type {\n IKeystore,\n IRegistryDriver,\n IStorageDriver,\n StorageBackend,\n StorageChunkSource,\n} from '@cloudbitmaps/core/driver-kit';\nimport { OpenChargingStorage } from './open-charging-storage';\n// This package's reason to exist: the roaring codec the facade injects into the codec-agnostic engine.\nimport { listGenerations, rollbackSegment } from '@cloudbitmaps/core';\nimport {\n destroySegment as coreDestroySegment,\n eraseNamespace as coreEraseNamespace,\n} from '@cloudbitmaps/core';\nimport type { DestroyResult, EraseDeps } from '@cloudbitmaps/core';\nimport { listSegments, refuseUnknownRefKeys, segmentExists } from '@cloudbitmaps/core';\nimport type { SegmentInfo } from '@cloudbitmaps/core';\nimport { runPreflight } from '@cloudbitmaps/core';\nimport type { PreflightResult } from '@cloudbitmaps/core';\nimport type {\n CombineManyFeed,\n CombineManyOperand,\n Expr,\n MaterializeManyFeedRecord,\n MaterializeManyStats,\n} from '@cloudbitmaps/core';\nimport { refuseReservedNamespace } from './reserved-namespace';\nimport { bitmapAsLoadInput, flagshipCodec } from './roaring-codec';\nimport { SystemClock } from './system-clock';\nimport { systemEntropy } from './system-entropy';\nimport { OPTION_KEYS, type OptionGroup } from './option-keys';\nimport { guardIdIterable, guardIds, guardItems } from './lease-guards';\nimport { wireStore } from './wire-store';\nimport { checkOptions, keysOf, kindOf, optionsError, picked } from './options';\n\n/** Default randomness for backoff jitter \u2014 lives outside `core/`, so `Math.random()` is allowed here. */\nclass SystemRng implements Rng {\n /** A float in `[0, 1)`. Jitter only \u2014 never key material, never anything a caller can observe. */\n next(): number {\n return Math.random();\n }\n}\n\n/**\n * What an erasure call waits with when its write gets no answer and it reads the row back: the caller's `clock` and\n * `rng`, else the real ones, so a call made with `{ registry }` alone waits between its reads. Deps that are not an\n * object are passed on as they are, for the call to refuse with a `ValidationError`.\n */\nfunction withWaits(deps: EraseDeps): EraseDeps {\n if (deps === null || typeof deps !== 'object') return deps;\n return { ...deps, clock: deps.clock ?? new SystemClock(), rng: deps.rng ?? new SystemRng() };\n}\n\n/**\n * Crypto-shred one segment. It cannot be undone through the library (a registry restore to a point before it can).\n * `confirmSegment` must equal `ref.segment` (a guard against an accidental destroy). A non-encrypted segment is\n * rejected unless you opt in via `allowCleartext`: it has no key to shred, its Storage bytes stay readable, and the\n * call emits a `segment.tombstone` audit event instead of `segment.erase`. A write that gets no answer is settled by\n * reading the row back, waiting between reads on `deps.clock` (the system clock by default).\n */\nexport function destroySegment(\n ref: SegmentRef,\n deps: EraseDeps,\n options: { confirmSegment: string; allowCleartext?: boolean; audit?: IAuditSink },\n): Promise<DestroyResult> {\n return coreDestroySegment(ref, withWaits(deps), options);\n}\n\n/**\n * Crypto-shred every segment in a namespace. It cannot be undone through the library. `confirmNamespace` must equal\n * `namespace`. Returns a per-segment result, in the order the registry listed the segments, which is unspecified. A\n * write that gets no answer is settled as {@link destroySegment}'s is.\n */\nexport function eraseNamespace(\n namespace: string,\n deps: EraseDeps,\n options: {\n confirmNamespace: string;\n allowCleartext?: boolean;\n audit?: IAuditSink;\n maxScanSegments?: number;\n },\n): Promise<{ destroyed: DestroyResult[] }> {\n return coreEraseNamespace(namespace, withWaits(deps), options);\n}\n\n/** Validate a segment ref a caller passes to a store method, and return its address alone; a bare name is the common slip, and the hint says so. */\nfunction validateRef(ref: SegmentRef, verb: string): SegmentRef {\n if (typeof ref !== 'object' || ref === null) {\n throw new ValidationError(\n \"a segment ref is an object such as { segment: 'name' }; store.segment() takes the bare name\",\n );\n }\n refuseUnknownRefKeys(ref, verb);\n validateSegmentRef(ref);\n // Only the address goes on: a passed-back listing row's other fields are read for nothing.\n return { segment: ref.segment, namespace: ref.namespace };\n}\n\nconst DEFAULT_CACHE_MAX_CHUNKS = 1024;\n/** Default in-flight fan-out for the admin scans (`subjectReport`/`eraseSubject`) \u2014 bounded, no thundering herd. */\nconst DEFAULT_ADMIN_CONCURRENCY = 8;\n/**\n * The row version a live version from a `CrbmStorageChunkSource` names: the version up to its last `#`, which starts\n * the opened object's fingerprint, a part with no `#` of its own, so the cut is exact for every `pointerId`. It is\n * core's `rowVersionOf` for this one caller, which is handed only that source's versions; core keeps that function\n * off its public entry.\n */\nfunction rowVersionOfLive(version: string | null): string | null {\n if (version === null) return null;\n const cut = version.lastIndexOf('#');\n return cut < 0 ? version : version.slice(0, cut);\n}\n\n/** Fail fast on a bad admin `concurrency` BEFORE the (potentially huge) registry scan, not after. */\nfunction validateConcurrency(concurrency: number | undefined): void {\n requirePositiveInt('concurrency', concurrency);\n}\n\n/**\n * Tenancy guard for the global-scope admin scans (`subjectReport`/`eraseSubject`). Ids live in ONE global\n * `[0, 2\u00B3\u00B2)` space shared across namespaces, so a namespace-less scan reaches into *every* tenant's segments.\n * Require an explicit `namespace`, or a deliberate `{ allNamespaces: true }` ack, so a fleet-wide sweep is never\n * the accidental default on a shared store.\n */\nfunction requireScope(options: { namespace?: string; allNamespaces?: boolean }, op: string): void {\n // A scope names a namespace like a ref does, and these two scans read the registry themselves rather than\n // through a core function that refuses it. `''` or a namespace that is not a string scanned nothing and read as a\n // clean erasure.\n if (options.namespace !== undefined) {\n if (typeof options.namespace !== 'string') {\n throw new ValidationError(\n `${op}: namespace must be a string; got ${kindOf(options.namespace)}`,\n );\n }\n validateSegmentRef({ segment: 'x', namespace: options.namespace });\n }\n refuseReservedNamespace(options.namespace);\n // The two are alternatives. Read as both, a call written to reach every tenant scanned one and reported it erased\n // there, while the others kept the id.\n if (options.namespace !== undefined && options.allNamespaces === true) {\n throw new ValidationError(\n `${op}: pass a namespace or { allNamespaces: true }, not both: with both, it is unclear whether to scan ` +\n `one namespace or every one`,\n );\n }\n if (options.namespace === undefined && options.allNamespaces !== true) {\n throw new ValidationError(\n `${op} scans the global id space across all namespaces \u2014 pass an explicit \\`namespace\\`, ` +\n `or \\`{ allNamespaces: true }\\` to intentionally sweep the whole fleet`,\n );\n }\n}\n\n/** The options of {@link CombineOptions} that decide what an `*Into` verb publishes: a read verb refuses them. */\ntype WriteOption = 'audit' | 'allowEmpty' | 'guard' | 'metadata' | 'keep';\n/** The range of a read: all that `iterate` and `everyNth` take. */\ntype RangeOptions = Pick<CombineOptions, 'after' | 'through'>;\n/** How a combine reads its operands: what `andNot` takes, and what the engine is handed beside the `exclude` refs. */\ntype ReadOptions = Omit<CombineOptions, 'exclude' | WriteOption>;\n/** What `intersect` and `union` take: a read that can also subtract. */\ntype StreamOptions = Omit<CombineOptions, WriteOption>;\n/** What `andNotInto` takes: every option but `exclude`, since its `excludes` argument is the subtraction. */\ntype AndNotIntoKeys = Omit<CombineOptions, 'exclude'>;\n\n/**\n * What each call that takes options takes. Each table is held in both directions to the type of what the call takes: a\n * key the type does not have, or one it has and the table leaves out, fails to compile. The combines and the reads\n * share one public options type, {@link CombineOptions}, and each takes part of it, so their tables are held to the\n * parts above; a key outside a call's part type-checks and is refused here, at run time.\n */\nconst CALL_KEYS = {\n range: keysOf<RangeOptions>()(['after', 'through']),\n andNot: keysOf<ReadOptions>()([\n 'after',\n 'through',\n 'concurrency',\n 'budget',\n 'allowAbsentOperands',\n ]),\n combine: keysOf<StreamOptions>()([\n 'after',\n 'through',\n 'concurrency',\n 'budget',\n 'allowAbsentOperands',\n 'exclude',\n ]),\n intersectCount: keysOf<StreamOptions>()([\n 'after',\n 'through',\n 'concurrency',\n 'budget',\n 'allowAbsentOperands',\n 'exclude',\n ]),\n unionCount: keysOf<StreamOptions>()([\n 'after',\n 'through',\n 'concurrency',\n 'budget',\n 'allowAbsentOperands',\n 'exclude',\n ]),\n andNotCount: keysOf<ReadOptions>()([\n 'after',\n 'through',\n 'concurrency',\n 'budget',\n 'allowAbsentOperands',\n ]),\n into: keysOf<CombineOptions>()([\n 'after',\n 'through',\n 'concurrency',\n 'budget',\n 'allowAbsentOperands',\n 'exclude',\n 'audit',\n 'allowEmpty',\n 'guard',\n 'metadata',\n 'keep',\n ]),\n andNotInto: keysOf<AndNotIntoKeys>()([\n 'after',\n 'through',\n 'concurrency',\n 'budget',\n 'allowAbsentOperands',\n 'audit',\n 'allowEmpty',\n 'guard',\n 'metadata',\n 'keep',\n ]),\n load: keysOf<LoadOptions>()(['allowEmpty', 'guard', 'keep', 'metadata', 'audit', 'sorted']),\n segments: keysOf<NonNullable<Parameters<CloudRoaring['segments']>[0]>>()(['namespace']),\n subjectReport: keysOf<NonNullable<Parameters<CloudRoaring['subjectReport']>[1]>>()([\n 'namespace',\n 'allNamespaces',\n 'concurrency',\n 'budget',\n ]),\n eraseSubject: keysOf<NonNullable<Parameters<CloudRoaring['eraseSubject']>[1]>>()([\n 'namespace',\n 'allNamespaces',\n 'audit',\n 'concurrency',\n 'budget',\n ]),\n rollback: keysOf<NonNullable<Parameters<CloudRoaring['rollback']>[2]>>()([\n 'audit',\n 'allowUnknown',\n ]),\n dropSegment: keysOf<Parameters<CloudRoaring['dropSegment']>[1]>()([\n 'confirmSegment',\n 'dryRun',\n 'audit',\n ]),\n retireExpired: keysOf<NonNullable<Parameters<CloudRoaring['retireExpired']>[0]>>()([\n 'namespace',\n 'now',\n 'limit',\n 'dryRun',\n 'audit',\n 'maxScanSegments',\n 'scan',\n 'shards',\n 'totalShards',\n 'lookbackBuckets',\n 'purgeTombstones',\n 'tombstoneGraceMs',\n ]),\n checkConsistency: keysOf<NonNullable<Parameters<CloudRoaring['checkConsistency']>[0]>>()([\n 'namespace',\n 'concurrency',\n 'maxScanSegments',\n 'summaries',\n 'generations',\n ]),\n exportSegments: keysOf<ExportOptions>()(['format', 'namespace', 'ndjsonBatchBytes']),\n} as const;\n\n/** The keys of `wider` that `known` does not list. */\nconst outside = (wider: readonly string[], known: readonly string[]): readonly string[] =>\n wider.filter((k) => !known.includes(k));\n\n/**\n * The fields of {@link CombineOptions} each read and combine does not take. A call reads each by name and refuses it\n * (see `optionsError`), so one inherited from a prototype or held in a getter is refused as an own key is, not dropped:\n * an `exclude` so held on `andNot` was skipped, and the stream was wider than asked. `intersectInto` and `unionInto`\n * take every field. `exportSegments` refuses `codec` the same way: the store exports with its own codec.\n */\nconst MISPLACED = {\n range: outside(CALL_KEYS.into, CALL_KEYS.range),\n andNot: outside(CALL_KEYS.into, CALL_KEYS.andNot),\n combine: outside(CALL_KEYS.into, CALL_KEYS.combine),\n intersectCount: outside(CALL_KEYS.into, CALL_KEYS.intersectCount),\n unionCount: outside(CALL_KEYS.into, CALL_KEYS.unionCount),\n andNotCount: outside(CALL_KEYS.into, CALL_KEYS.andNotCount),\n andNotInto: outside(CALL_KEYS.into, CALL_KEYS.andNotInto),\n exportSegments: ['codec'],\n} as const;\n\n/**\n * Wiring for a {@link CloudRoaring} store. **Only `storage` is required** \u2014 the minimal call is\n * `new CloudRoaring({ storage: backend })`. A backend resolves generations with one strong read, reads\n * encrypted segments, and unlocks every lifecycle helper; the narrower shapes `storage` also accepts are\n * described on the option itself. Everything else is **optional\n * tuning with sensible defaults** \u2014 resilience/retries are already on, the cache is bounded, metrics are a\n * no-op \u2014 so reach for them only when you need to.\n */\nexport interface CloudRoaringOptions {\n /**\n * Where the store keeps everything. **The only required option.**\n *\n * Pass a {@link StorageBackend} \u2014 `S3Storage`, `GcsStorage`, `AzureBlobStorage`, `LocalFsStorage`,\n * `MemoryStorage` \u2014 and you are done: it carries both halves, the generations and the `currentGen` pointer,\n * configured from one bucket and one prefix. That is the whole wiring, and it is the shape to reach for.\n *\n * **Pass the backend itself, not `backend.storage`.** They differ by one property access and the mistake is\n * silent: `storage: backend` is the store, while `storage: backend.storage` hands over the *driver half*\n * alone, which constructs without complaint and gives you a cleartext, read-only store that fails later on\n * the first write or lifecycle call. `destroySegment` and `eraseNamespace` take `backend.registry`; the store takes `backend`.\n *\n * Two lower-level shapes stay accepted for wiring the facade does not cover:\n *\n * - a **raw {@link IStorageDriver}**, which the store reads through its own `.crbm` reader. There is no\n * registry in this shape, so the store resolves generations by list-scanning storage: **cleartext and\n * read-only**. Encrypted segments, the `*Into` verbs and every lifecycle helper need a backend.\n * - a {@link StorageChunkSource} of your own, a read source used as it is: read-only, like the raw driver.\n *\n * The two port types are exported by `@cloudbitmaps/core/driver-kit`, not by this package; to name the option's\n * type without importing them, write `CloudRoaringOptions['storage']`.\n */\n readonly storage: StorageBackend | IStorageDriver | StorageChunkSource;\n\n /**\n * Memory and staleness bounds for the read path. Every key is optional and every default is already sane;\n * reach for these when a deployment's shape differs from \"a long-running server with room to breathe\".\n */\n readonly cache?: CacheOptions;\n\n /**\n * Encryption at rest. Omit it entirely for a cleartext store \u2014 encryption is opt-in, and a segment's\n * encryption is decided at its **first** generation.\n */\n readonly encryption?: EncryptionOptions;\n\n /**\n * Resilience: by default every read that answers a query retries **transient** faults (throttling, 5xx, dropped\n * connections) with bounded, jittered exponential backoff (by default 4 attempts, a 50 ms base delay doubling each\n * attempt, capped at 2 s, with full jitter): `has`, `count`,\n * `iterate` and the combines, the `*Into` verbs' reads of their operands included, a pinned handle's reads and\n * `pin()` itself, and the reads a write makes along the way: a load's guard read of the current generation, and an\n * erasure's reads of the generation it rewrites, of the one it wrote and of any other that may still hold the id, and\n * the search `subjectReport` and `eraseSubject` make under a destroyed segment (its listing of the bucket included).\n * This option does not govern writes, nor the calls that read the registry or list the bucket directly (`exists`,\n * `segments`, `generations`, `getRetention`, and the registry scan `subjectReport`, `exportSegments` and\n * `checkConsistency` start from): they report a transient fault to their caller, because a conditional write that\n * lands and then loses its response would, replayed blindly, report its own write as a conflict. A write is\n * retried only where that is safe: a load's registry write that gets no answer is settled by reading the row,\n * and a throttled write-once object is sent again by the S3 and GCS drivers. Pass a partial policy to tune it \u2014 anything you leave out keeps its\n * default, except an omitted `maxDelayMs`, which is `baseDelayMs` when that is larger than 2000 ms \u2014 or `false` to turn the read retry off (e.g. if your injected client already retries). A GCS download is retried by\n * the GCS driver whatever this says.\n * Deterministic errors (`ValidationError`/`IntegrityError`/`WriteConflictError`/\u2026) are never retried by this\n * layer.\n */\n readonly retry?: RetryOptions | false;\n\n /**\n * Observability sink: receives typed metric events (storage GET/bytes, cache hit/miss, retries, intersection\n * efficiency, op latency). Defaults to a no-op \u2014 emission is skipped entirely when unused (near-zero\n * overhead). Any exception the sink throws is swallowed \u2014 metrics can never break a read.\n */\n readonly metrics?: IMetricsSink;\n\n /**\n * Per-op **denial-of-wallet** budget: the max backend requests a single\n * `count`/`iterate`/`intersect`/`union`/`andNot`/`subjectReport`/`eraseSubject` may fan out into before it's\n * refused with {@link BudgetExceededError} (`eraseSubject` reports an over-budget segment in its ledger instead,\n * see {@link CloudRoaring.eraseSubject}) \u2014 so one runaway op can't drive unbounded GET cost on a shared\n * backend. **On by default, generous** (1,000,000 requests \u2014 a normal op never hits it).\n * Tune with `{ maxRequests }`, override per op (on the combines / `subjectReport` / `eraseSubject`), or set\n * `false` to disable. The check is O(1) (before fan-out), so the hot path is untouched; per-request bytes are\n * separately size-capped, so bounding requests transitively bounds bytes.\n */\n readonly budget?: BudgetOption;\n\n /**\n * Determinism seams, for tests and replayable jobs. Production stores leave this out and get a system clock\n * and a `Math.random`-backed source.\n */\n readonly seams?: SeamOptions;\n}\n\n/** {@link CloudRoaringOptions.cache} \u2014 the memory and staleness bounds. */\nexport interface CacheOptions {\n /** Ceiling on decoded Storage chunks held in RAM (default 1024): an integer of at least 1, else `ValidationError`. */\n readonly maxChunks?: number;\n /**\n * Optional TTL on cached chunks (ms): a finite number above 0, else `ValidationError`. Omit to keep a chunk until it is\n * evicted by the count bound.\n */\n readonly ttlMs?: number;\n /**\n * How long (ms) the store trusts a segment's resolved `currentGen` before re-resolving it on the next read\n * (default 2000) \u2014 the bound on read staleness after a load publishes a new generation. Applies when\n * `storage` is a **backend**, whose registry supplies the cheap `currentGen` read the refresh needs. Lazy \u2014 no\n * timer; \u2264 one registry read per segment per window, opening a new reader only when the row's pointer was\n * renewed (a publish, a rollback, an erasure's rewrite, a status or key change); a lease or retention write does not.\n *\n * **While the registry cannot be read, the bound stretches.** A refresh that fails with a\n * {@link TransientError} keeps serving the generation of a segment still in the reader cache, and the key its reader\n * unwrapped (a read that needs the key, where none was unwrapped before it, unwraps it from that segment's row as\n * resolved before the outage), and is tried again 500 ms later (or after this TTL, if shorter), so the store converges\n * within one retry of the registry answering. A segment the reader cache has let go is not served past its resolution's TTL: once that\n * lapses, a read of it fails with the fault, as a cold read does. A refresh that fails with anything else, an access denial or a row that will not parse, is not\n * ridden out: the read that meets it throws that error, and the reader is dropped.\n *\n * **A pinned handle is checked on the same interval.** It never moves to another generation, but at most every\n * `genTtlMs` (counted on access) its segment's row is read, one read shared by every pin of the segment, and the\n * pin fails with `NotFoundError` once the segment is destroyed, gone or re-created, or its generation erased or\n * collected, or recorded by its row as another object, even when its reader and chunks are still cached. A transient\n * fault of the registry, or of the footer read an erasure's check makes, keeps it serving.\n *\n * `0` turns this timed refresh off, and the pinned handles' check with it, and so does wiring a bare `IStorageDriver`, which has no registry. That is\n * all it does. The store still moves a segment on to whatever generation is current when its reader cache\n * evicts the segment, when a read has to fetch from a generation a sweep deleted, and when it is invalidated,\n * as its own `load`, `rollback`, `eraseSubject` and `*Into` writes do and {@link CloudRoaring.invalidate} does.\n * A read its caches can answer touches no storage, so a sweep alone moves nothing. What `0` gives up is the bound:\n * the store notices another process's publish, erasure or drop only through one of those, whenever that happens. To read\n * one generation for as long as you need it, take a {@link Segment.pin}.\n */\n readonly genTtlMs?: number;\n /**\n * Ceiling on how many segments' `.crbm` readers (each holding a parsed index) the store keeps open at once\n * (default 1024; an integer of at least 1, else `ValidationError`) \u2014 the steady-state memory bound for a long-running\n * server that reads across many segments.\n * Past it the least-recently-used segment's reader is evicted; re-opening it later is one cheap tail GET. With a\n * timed refresh ({@link CacheOptions.genTtlMs} above 0, and a backend) the store also keeps up to 8 times this many\n * segments' resolutions (what it read of each segment's row: never an unwrapped key, though the wrapped keys are in\n * it) for `genTtlMs`, apart from their readers. An evicted segment is then reopened with no registry read, on the\n * generation it had resolved, when a read needs its index or a chunk the chunk cache does not hold: `iterate` and the\n * combines always do, and a `has()` of a cached chunk, a `count()` and a `stat()` do not, where the row has a summary\n * the store can use. A reader of a small generation, one whose whole object came with its tail read,\n * also holds its chunk bytes, so a read of it makes no chunk request until the reader is evicted or the pointer refresh\n * moves it on; a store with no timed refresh (`genTtlMs: 0`, or no registry) keeps none.\n * Applies whenever the store builds its own read path \u2014 a backend or a bare `IStorageDriver`. A pre-built\n * `StorageChunkSource` manages its own reader cache.\n */\n readonly readerMax?: number;\n /**\n * Aggregate byte ceiling on what the open readers hold: their parsed `.crbm` indices, the metadata a\n * generation carries, a fixed 3.75 KiB for the objects each open reader holds around its index, and the chunk bytes a reader keeps when its tail read returned a whole object whose chunks\n * total at most this ceiling divided by {@link CacheOptions.readerMax} (default 64 MiB) \u2014 the byte half\n * of the memory bound, complementing the {@link CacheOptions.readerMax} *count* bound. A wide/dense segment's\n * parsed index can reach about 1.3 MB, so a count-only bound could let the open readers pin over a GB and blow a small\n * heap (e.g. a 128 MB Lambda); this evicts the least-recently-used reader once the summed weight\n * would exceed the ceiling \u2014 whichever of the count/byte bounds binds first. A sixteenth of it (4 MiB by default)\n * bounds the segments' resolutions a store with a timed refresh keeps besides. Lower it for memory-tight\n * deployments that read across wide segments. An integer of at least 1, else `ValidationError`. A ceiling below two readers' weight (about 7.7 KB for tiny ones) keeps one reader open at a time. Applies whenever the store builds its own read path.\n */\n readonly readerMaxBytes?: number;\n}\n\n/** {@link CloudRoaringOptions.encryption} \u2014 encryption at rest and crypto-shred. */\nexport interface EncryptionOptions {\n /**\n * The keystore that mints and unwraps per-segment DEKs. Needs a **backend**: the wrapped DEK lives in the\n * registry, so there is nowhere to put it on a store wired with a bare driver, and that is refused at\n * construction rather than at the first read.\n */\n readonly keystore?: IKeystore;\n /**\n * Refuse to touch a **cleartext** segment \u2014 a guard against silently reading, or writing, data that should be\n * encrypted. Needs a backend, for the same reason as {@link EncryptionOptions.keystore}. Off by default. Exactly a\n * boolean: any other value, a truthy string included, throws `ValidationError`.\n *\n * It refuses **writes** as well as reads, which is easy to miss: the `*Into` verbs and `eraseSubject` both\n * carry it into their write path, so on a cleartext segment a materialisation throws and an erasure records\n * `note: 'error: KeyUnavailableError: requireEncryption: \u2026'` in its ledger rather than erasing, whatever id it erases and\n * whether or not the id is in the segment: it does not read the segment. And since a segment's encryption is\n * decided at its **first** generation, this cannot be switched on for a segment that already has one \u2014 load\n * into a new encrypted segment and drop the old one.\n */\n readonly required?: boolean;\n}\n\n/**\n * {@link CloudRoaringOptions.retry} \u2014 a partial {@link RetryPolicy} plus the retry callback.\n *\n * Partial on purpose, so tuning one field does not mean restating all five. Anything omitted here keeps its default\n * (`maxAttempts` 4, `baseDelayMs` 50, `maxDelayMs` 2000, `backoffFactor` 2, `jitter` `'full'`), except that an\n * omitted `maxDelayMs` is the `baseDelayMs` when that is larger than the default cap.\n */\nexport interface RetryOptions extends Partial<RetryPolicy> {\n /**\n * Observability: called before each transient-retry backoff wait. Best-effort: an error it throws is\n * swallowed, so it can neither stop the retry nor change the error a read fails with.\n */\n readonly onRetry?: (info: { attempt: number; delayMs: number; err: unknown }) => void;\n}\n\n/** {@link CloudRoaringOptions.seams} \u2014 injected for deterministic tests and replayable jobs. */\nexport interface SeamOptions {\n /** Defaults to a system clock. */\n readonly clock?: Clock;\n /** Defaults to `Math.random`-backed. Drives transient-retry jitter. */\n readonly rng?: Rng;\n /**\n * Defaults to the platform's Web Crypto. The source of every written generation's identity: 12 bytes a cleartext\n * generation's footer carries (an encrypted one carries its index's AEAD nonce), so two loads of the same ids are\n * two objects. Inject a deterministic one to replay a run or pin bytes in a test; never inject a constant in\n * production, since a source that repeats makes the objects it writes alike again.\n */\n readonly entropy?: Entropy;\n}\n\n/**\n * What {@link CloudRoaring.segment} takes besides the name. A handle carries no deadline: check one where you read,\n * or record it with {@link CloudRoaring.setRetention} and run {@link CloudRoaring.retireExpired}. An `expiresAt`\n * passed here is refused with {@link ValidationError}.\n */\nexport interface SegmentOptions {\n /** The segment's namespace, or `undefined` for the default one. */\n readonly namespace?: string;\n}\n\n/** A segment reference in a subject report / erasure ledger. */\nexport interface SubjectSegmentRef {\n /** The segment's name. */\n readonly segment: string;\n /** The segment's namespace, or `undefined` for the default one. */\n readonly namespace?: string;\n}\n\n/** Result of {@link CloudRoaring.subjectReport}: the segments an id is a member of, and the destroyed segments whose leftover objects hold it. */\nexport interface SubjectReport {\n /** The id the report is about. */\n readonly id: number;\n /** The registered segments the id is currently a member of. */\n readonly segments: SubjectSegmentRef[];\n /**\n * The destroyed segments whose leftover objects still hold the id in the clear: one destroyed with `allowCleartext`,\n * dropped while a load wrote an object its sweep did not catch, or crypto-shredded over an object a cleartext writer\n * left. No read resolves them, so the id is a member of none, but its bytes are in the bucket, and `eraseSubject`\n * deletes them. A crypto-shredded segment's own objects are sealed under a key no row holds and are never a holder,\n * so it is listed only when an object left under it in the clear holds the id. A destroyed segment with no\n * object left is not listed either. `[]` when none.\n */\n readonly tombstones: SubjectSegmentRef[];\n /** How many registered segments were scanned (the completeness denominator). */\n readonly scannedSegments: number;\n}\n\n/** One segment's entry in an erasure ledger (see {@link EraseSubjectResult}). */\nexport interface SubjectErasureEntry {\n /** The segment's name. */\n readonly segment: string;\n /** The segment's namespace, or `undefined` for the default one. */\n readonly namespace?: string;\n /**\n * True iff the id **was** in the segment and **no generation of it holds the id now** \u2014 not the current one, not\n * one below the pointer, and not one above it, where a rollback leaves the generations it rolled back from. The\n * current generation is one without it, every generation that held it has been deleted from the bucket, and the\n * call listed the bucket and read what was left before this entry was returned (see\n * {@link CloudRoaring.eraseSubject}).\n */\n readonly erased: boolean;\n /**\n * The generation the id was found in (present whenever the segment was read) \u2014 the newest of them, when the\n * current generation did not hold it and several others did.\n */\n readonly fromGeneration?: number;\n /** The generation written without the id (present whenever one was written). */\n readonly generation?: number;\n /**\n * Why the id was NOT erased from this segment, when `erased` is false. `'superseded'` \u2014 another writer (a load,\n * another erasure or a rollback) moved the pointer, replaced an object the call meant to delete, or left the row with\n * no pointer (a purge and re-creation, or a hand-made write), while the call was in flight, so **this call** did\n * not erase the id;\n * re-run against the new generation, which erases it if it is still there and reports nothing for the segment\n * if the racing writer already removed it. `` `error: <class>: <message>` `` \u2014 an isolated per-segment fault, named by its error's class\n * (per-segment faults are recorded so one segment can't discard the whole ledger); re-run after fixing the\n * fault. A budget refusal is one of these: the segment's generations did not fit `budget`, so it was not finished;\n * re-run with a higher `budget`. A fault that landed once part of the work was already done \u2014 a Storage `delete` fault, a collect that\n * could not prove the segment was still the same one, or a generation still holding the id when the bucket was\n * listed at the end, whether or not a rewrite was published first \u2014 also re-runs, but **read what the re-run\n * says**: it usually reports `erased: true` against the generation it found the id in, it reports\n * nothing at all if a racing collector took that generation first, or this call's own delete of it landed after a\n * fault the call could not settle (the bit is gone, but no run holds a receipt for it), and if the segment's row has since been purged it is no longer scanned at all \u2014 anything\n * left in its bucket is an orphan, which `store.generations(ref)` lists and `store.dropSegment(ref, {\n * confirmSegment })` deletes; `checkConsistency` and the collection a load runs read rows, so neither reaches it.\n * **Segments the id is not in\n * are not listed, and neither are segments that no longer have a registry row** \u2014 an empty ledger is not by\n * itself proof the id is gone.\n */\n readonly note?: string;\n}\n\n/**\n * The erasure ledger returned by {@link CloudRoaring.eraseSubject} \u2014 your proof-of-deletion artifact. It is a\n * return value only (no library-side persistence): persist it / route it to your audit sink as you see fit.\n */\nexport interface EraseSubjectResult {\n /** The id that was erased. */\n readonly id: number;\n /** Per-segment records for the segments the id was found in (absent segments are not listed). */\n readonly erasedFrom: SubjectErasureEntry[];\n /** How many registered segments were scanned. */\n readonly scannedSegments: number;\n}\n\n/**\n * Why a materialisation did not become current.\n *\n * {@link LoadRefusal} minus `'superseded'`: that one is a lost race, and the `*Into` verbs throw\n * {@link WriteConflictError} for it rather than reporting it. Narrowing the type rather than saying so only\n * in prose means the compiler enforces it, and a caller's exhaustive `switch` has no dead branch.\n */\nexport type MaterializeRefusal = Exclude<LoadRefusal, 'superseded'>;\n\n/** One output of a {@link CloudRoaring.materializeMany} call. */\nexport interface MaterializeManyOutput {\n /** The segment this output becomes a new generation of. Not an operand of the call, and named by no other output. */\n readonly dest: Segment;\n /** What to compute. */\n readonly expr: Expr;\n /** Subtracted from the result, as the entries of an `andNot` after the first are. Pinned operands it names are re-checked before the publish. */\n readonly exclude?: Expr[];\n /** As {@link CombineOptions.guard} on an `*Into` verb. */\n readonly guard?: LoadGuard;\n /** As {@link CombineOptions.allowEmpty} on an `*Into` verb. */\n readonly allowEmpty?: boolean;\n /** As {@link CombineOptions.metadata} on an `*Into` verb. */\n readonly metadata?: GenerationMetadata;\n /** As {@link CombineOptions.audit} on an `*Into` verb. */\n readonly audit?: IAuditSink;\n /** Generations to keep below the new one, as {@link CombineOptions.keep} on an `*Into` verb; overrides the call's `keep`. */\n readonly keep?: number;\n}\n\n/**\n * Operands that arrive as records in chunk-key order instead of being stored, for {@link MaterializeManyOptions.feed}.\n * Outputs name a fed operand as they name a stored one.\n */\nexport interface MaterializeManyFeed {\n /** The fed operand names, declared up front. A name is either stored or fed, never both. */\n readonly names: string[];\n /** The records, read once, in key order. */\n readonly records: AsyncIterable<MaterializeManyFeedRecord>;\n /**\n * How many ids each fed operand holds over the whole feed, **required**: an object keyed by exactly `names`, or a\n * function returning one (or a promise of one), called once after the last record and before any fed output is\n * published. A feed whose count of ids for any operand differs (one that ended early, or skipped a key) refuses every\n * fed output; so does a count that is missing, extra, thrown or rejected.\n */\n readonly counts:\n (() => Record<string, number> | Promise<Record<string, number>>) | Record<string, number>;\n}\n\n/** The options of {@link CloudRoaring.materializeMany}. */\nexport interface MaterializeManyOptions extends Pick<CombineOptions, 'after' | 'through'> {\n /**\n * The stored segments the expressions name. A set the caller holds in memory arrives as a {@link MaterializeManyOptions.feed}.\n */\n readonly operands: Record<string, Segment>;\n /** The outputs, in the order their results come back. */\n readonly outputs: ReadonlyArray<MaterializeManyOutput>;\n /**\n * Generations to keep below each new one: a non-negative integer, **required**, since a materialisation otherwise keeps\n * every generation and a call of a thousand outputs would leave a thousand uncollected destinations on every refresh.\n * An output's own `keep` overrides it.\n */\n readonly keep: number;\n /**\n * Read every stored operand at the generation it has when the call starts, for the whole call (default `true`): the call\n * pins each one that is not already pinned. It is one generation per operand, **not one instant across operands**.\n * `false` reads each live, as a combine does, which can describe two generations of one operand and break its pruning, and runs\n * **no re-check** of an operand an output subtracts: an opt-out list can move during the call and the outputs that subtract it are\n * published (`stats.operands` still reports, from one read at the end, that it moved).\n * An operand passed already pinned is used as it is whatever this says.\n */\n readonly pin?: boolean;\n /**\n * The most resident bytes the call counts at once, default 256 MiB: the buffered outputs, the operand streams, the\n * chunks being evaluated and the plan, counted as resident memory. Past it, outputs run in groups and the operands are read\n * again for each group. Process memory is more than the count (measured 1.6 to 5 times; see the guide).\n */\n readonly maxBufferedBytes?: number;\n /**\n * The most chunk reads the call may make, counted over all its groups. Default: the store's own `budget` when it was built\n * with one (a ceiling below the plan throws `BudgetExceededError` before any chunk is read), else what the plan needs,\n * with headroom. `false` lifts it. The budget used is in the result's stats.\n */\n readonly budget?: BudgetOption;\n /** Outputs published at once, default 8. */\n readonly publishConcurrency?: number;\n /** Range requests held ahead per operand, default 1. */\n readonly concurrency?: number;\n /** As on every combine. */\n readonly allowAbsentOperands?: boolean;\n /**\n * Operands fed as records in chunk-key order, beside the stored ones; an output names a fed operand as it names a stored\n * one. **A feed is read once, so a call with one runs its outputs as one group, and `maxBufferedBytes` is then required**:\n * the feed's records and the fed outputs are counted against it as they arrive, and a fed call fails as soon as the count\n * passes it. A fed output is published only after the whole feed was read and every end-of-feed check passed.\n */\n readonly feed?: MaterializeManyFeed;\n /**\n * Fed operand names allowed to hold no id. A declared fed name that appears in no record is refused at the end of the\n * feed, because an operand that is empty is usually an upstream query that failed quietly. Naming something that is not\n * a fed operand is a {@link ValidationError}.\n */\n readonly mayBeEmpty?: readonly string[];\n}\n\n/**\n * What one output of {@link CloudRoaring.materializeMany} came to: exactly what its `*Into` would have returned (a\n * {@link MaterializeResult}, published or refused with its `reason`), or `{ published: false, error }` for what it would\n * have thrown, or for what stopped it: a lost race ({@link WriteConflictError}), a publish whose outcome is unknown\n * ({@link TransientError}), a damaged operand ({@link IntegrityError}), a lapsed lease ({@link LeaseExpiredError}), a\n * pinned exclude that moved ({@link StaleOperandError}), memory ({@link BudgetExceededError}), or, for an output that names a\n * fed operand, a bad feed ({@link ValidationError}) or an erasure in this store while the call ran ({@link StaleOperandError}\n * with `reason: 'erased'`).\n */\nexport type MaterializeManyOutcome =\n MaterializeResult | { readonly published: false; readonly error: Error };\n\n/** The result of {@link CloudRoaring.materializeMany}. */\nexport interface MaterializeManyRun {\n /** One per output, in the order given: one output's refusal or error never stops another. */\n readonly outputs: MaterializeManyOutcome[];\n /**\n * What the call did: the groups it ran, its requests by class, its budget and memory, and the figures of each operand\n * and output.\n */\n readonly stats: MaterializeManyStats;\n}\n\n/**\n * {@link MaterializeManyOptions} for a **dry run**: every output is computed exactly as the call would compute it, and\n * judged against its `dest` as its publish would be, and nothing is written. See {@link CloudRoaring.materializeMany}.\n */\nexport interface MaterializeManyDryRunOptions extends MaterializeManyOptions {\n /** `true` makes the call a dry run: every output is computed and judged, and nothing is written. */\n readonly dryRun: true;\n}\n\n/**\n * What one output of a dry run would come to, with nothing written: its size, what its `dest` holds now, and the bound\n * its publish would be refused for now. `published` is always `false`, so code that branches on it never takes a dry\n * run for a publish.\n */\nexport interface MaterializeDryRunResult {\n /** Always `true`: the output was computed and judged, not published. */\n readonly dryRun: true;\n /** Always `false`: nothing was written. */\n readonly published: false;\n /** Distinct ids the output would hold. */\n readonly cardinality: number;\n /** What `dest` holds now: `null` when it has no current generation, or its object is gone. Always read. */\n readonly cardinalityBefore: number | null;\n /** The bound a publish of the output would be refused for, judged now; absent when it would publish. */\n readonly wouldRefuse?: MaterializeRefusal;\n}\n\n/**\n * What one output of a dry run came to: a {@link MaterializeDryRunResult}, or `{ published: false, error }` for what its\n * publish would have thrown or what stopped it, as on a call that publishes.\n */\nexport type MaterializeManyDryRunOutcome =\n MaterializeDryRunResult | { readonly published: false; readonly error: Error };\n\n/** The result of {@link CloudRoaring.materializeMany} with `dryRun: true`. */\nexport interface MaterializeManyDryRun {\n /** One per output, in the order given. */\n readonly outputs: MaterializeManyDryRunOutcome[];\n /**\n * What the dry run did: the groups it ran, its requests by class, its budget and memory, and the figures of each\n * operand and output.\n */\n readonly stats: MaterializeManyStats;\n}\n\n/** A dry run's value inside the call, with the requests its judgement made. */\ninterface DryRunValue extends MaterializeDryRunResult {\n readonly reads: number;\n}\n\n/** What a handle shows the store that it does not show a caller. */\ninterface HandleView {\n readonly ref: SegmentRef;\n readonly pinnedAt: PinnedAt | undefined;\n /** The lease error a read of the handle must throw now, or `undefined`. */\n readonly leaseError: () => LeaseExpiredError | undefined;\n}\n\n/**\n * Marks a segment so one from another copy of this package is recognised; `Symbol.for` is the same symbol in every\n * copy. The mark is read only to name the refusal: a store belongs to one copy, so a segment of another copy always\n * comes from another store and is refused with a message that says so. The number at the end of the key is raised\n * if the mark changes meaning.\n */\nconst SEGMENT_BRAND: unique symbol = Symbol.for('cloudbitmaps.roaring.segment/1');\n\n/** Set by the `Segment` class, whose private state it reads. */\nlet viewOf: (segment: Segment) => HandleView;\n/** The store that made a segment: one reference compare per handle per call. Set by the `Segment` class. */\nlet originOf: (segment: Segment) => object;\n\n/** What a refused handle was in the call: its role, or where it sits in a `materializeMany` call. */\ntype HandleRole = string;\n\n/**\n * Refuse, with a {@link ValidationError} and before any request, a handle that the store `origin` did not make: a\n * value that is not a segment, a segment of another store, or a segment of another installed copy of this package.\n * The messages never name the segment, the namespace or a key.\n */\nfunction assertOneStore(\n verb: string,\n role: HandleRole,\n h: unknown,\n origin: object,\n): asserts h is Segment {\n if (h instanceof Segment) {\n if (originOf(h) === origin) return;\n throw new ValidationError(\n `${verb}: ${role} belongs to another store; combine segments of one store: open each with this store's segment()`,\n );\n }\n if (\n typeof h === 'object' &&\n h !== null &&\n (h as Record<symbol, unknown>)[SEGMENT_BRAND] === true\n ) {\n throw new ValidationError(\n `${verb}: ${role} comes from another installed copy of @cloudbitmaps/roaring, so it belongs to another store; install one copy and combine segments of one store`,\n );\n }\n throw new ValidationError(`${verb}: ${role} must be a segment from this store's segment()`);\n}\n\nconst MATERIALIZE_MANY_KEYS = [\n 'operands',\n 'dryRun',\n 'outputs',\n 'keep',\n 'pin',\n 'maxBufferedBytes',\n 'budget',\n 'publishConcurrency',\n 'concurrency',\n 'allowAbsentOperands',\n 'after',\n 'through',\n 'feed',\n 'mayBeEmpty',\n] as const;\n/**\n * The fields of {@link CombineOptions} a `materializeMany` call does not take at its top level (an output takes the\n * write options), read by name as a read or combine reads its own, so one inherited or held in a getter is refused.\n */\nconst MATERIALIZE_MANY_MISPLACED = outside(CALL_KEYS.into, MATERIALIZE_MANY_KEYS);\n\n/** The keys of a `materializeMany` call's options it does not take: every own one it does not list, and the misplaced. */\nfunction unknownManyKeys(options: object): string[] {\n const unknown = Object.keys(options).filter(\n (k) => !(MATERIALIZE_MANY_KEYS as readonly string[]).includes(k),\n );\n const bag = options as Record<string, unknown>;\n for (const k of MATERIALIZE_MANY_MISPLACED) {\n if (!unknown.includes(k) && bag[k] !== undefined) unknown.push(k);\n }\n return unknown;\n}\nconst MATERIALIZE_MANY_OUTPUT_KEYS = [\n 'dest',\n 'expr',\n 'exclude',\n 'guard',\n 'allowEmpty',\n 'metadata',\n 'audit',\n 'keep',\n] as const;\n\n/** The default of `maxBufferedBytes`: 256 MiB. */\nconst DEFAULT_MAX_BUFFERED_BYTES = 256 * 1024 * 1024;\nconst DEFAULT_PUBLISH_CONCURRENCY = 8;\nconst DEFAULT_BATCH_CONCURRENCY = 1;\n/** Pins taken at once. */\nconst PIN_PARALLELISM = 16;\n\n/** What an `*Into` verb wrote: the new generation of the destination, and whether it became current. */\nexport interface MaterializeResult {\n /**\n * The generation written. Present even when refused: the refusal deleted that object, unless the destination's\n * row changed while it was writing, which leaves it in the bucket, an orphan a later load's collection takes; until\n * then a rollback onto it needs `allowUnknown`.\n */\n readonly generation: number;\n /**\n * Whether this generation is now the destination's current one.\n *\n * `false` when the guard refused the result: an empty one over a non-empty destination, or one outside\n * `guard`'s bounds. Branch on it: a refusal is reported, not thrown, so a caller that ignores it sees a\n * successful-looking result for a write that deliberately did not happen.\n */\n readonly published: boolean;\n /** Set only when `published` is false. A lost race throws {@link WriteConflictError} rather than appearing here. */\n readonly reason?: MaterializeRefusal;\n /** Ids in the generation. */\n readonly cardinality: number;\n /**\n * What the destination held when the guard judged it \u2014 `null` when it had no current generation, **or when\n * no bound needed it**. It is taken only when a bound will use it: `allowEmpty: true` with neither\n * `guard.minRetained` nor `guard.maxGrowth` skips it, and this is `null` even though `dest` was non-empty. When the destination's row\n * carries a summary of its current generation the count comes from the row and the object is not read; a row with\n * none (one a rollback left when it could not open the key, one a registry of your own stores without one, or one this store cannot use) costs\n * one object-header fetch.\n */\n readonly cardinalityBefore: number | null;\n /** Non-empty chunks in the generation. */\n readonly chunkCount: number;\n /** Bytes of the written object. */\n readonly size: number;\n /**\n * The superseded generations collected after publishing. Empty when nothing was published \u2014 and **also\n * empty on a successful publish** unless you passed `keep`, because a materialisation collects nothing by\n * default. See {@link CombineOptions.keep}.\n */\n readonly collected: readonly number[];\n}\n\n/**\n * The deps every write-side helper on the store shares: raw storage + registry + the store's codec/crypto/clock, and\n * the store's read retry for the reads a write makes along the way (undefined when the store's retry is off).\n */\ninterface LifecycleDeps {\n readonly storage: IStorageDriver;\n readonly registry: IRegistryDriver;\n readonly codec: CodecInterface;\n readonly clock: Clock;\n /** The store's random source, which spreads a publish's waits between fresh writes whether or not reads retry. */\n readonly rng: Rng;\n /** The source of each written generation's identity. */\n readonly entropy: Entropy;\n readonly keystore?: IKeystore;\n readonly requireEncryption?: boolean;\n readonly readRetry?: RetryingOptions;\n}\n\n/** How the store names a group value that is an object to `typeof` but configures nothing, by its built-in tag. */\nconst NOT_A_GROUP: Readonly<Record<string, string>> = {\n Null: 'null',\n Array: 'an array',\n Map: 'a Map',\n Set: 'a Set',\n Boolean: 'a boxed boolean',\n Number: 'a boxed number',\n String: 'a boxed string',\n};\n\n/**\n * The store: Roaring bitmap segments kept as write-once `.crbm` generations in the storage you give it, read through\n * a bounded in-memory cache. Build one per process from a backend,\n * `new CloudRoaring({ storage: new S3Storage({ bucket }) })`; building does no I/O. `store.segment(name)` is a handle\n * for `has`, `count`, `iterate` and the combines, and `store.load(ref, ids)` replaces a segment's contents with a new\n * generation.\n */\nexport class CloudRoaring {\n private readonly engine: SegmentEngine;\n /** This store's identity: every handle it makes carries this object, and a combine compares it by reference. */\n private readonly origin: object = Object.freeze({});\n private readonly cache: BoundedLru<string, CodecBitmap>;\n /** The store's retry options, for a pinned engine to read through as the store's own does; undefined when off. */\n private readonly retryOptions: RetryingOptions | undefined;\n private readonly crbmSource: CrbmStorageChunkSource | undefined;\n private readonly clock: Clock;\n private readonly rng: Rng;\n private readonly entropy: Entropy;\n private readonly metrics: IMetricsSink;\n // The store's own drivers, kept so the lifecycle helpers and the `*Into` verbs reuse them instead of making\n // you re-pass deps. `storageDriver` is set only when `storage` was a raw IStorageDriver (a pre-built StorageChunkSource has\n // no underlying driver to write through).\n private readonly storageDriver: IStorageDriver | undefined;\n private readonly registry: IRegistryDriver | undefined;\n // The backend itself, for its optional `checkLifecycle`; `undefined` for a bare driver or a source.\n private readonly backend: StorageBackend | undefined;\n private readonly keystore: IKeystore | undefined;\n private readonly requireEncryption: boolean;\n /** Resolved store-level per-op budget (null = disabled); the admin scans use it, with a per-op override. */\n private readonly budget: Budget | null;\n /**\n * Moved at the start and at the end of each `eraseSubject` this store runs. A `materializeMany` call with a feed records\n * it when it begins and is refused once it has moved: it reads caller memory, which no erasure can reach.\n */\n private erasureEpoch = 0;\n /** How many `eraseSubject` calls of this store are running: while any is, every check of the counter counts as moved. */\n private erasuresRunning = 0;\n\n /**\n * Refuse any option key the store does not take, at the top level or inside a group, naming each one.\n *\n * An option the store ignored would do nothing and look as if it had \u2014 a typo'd `cache.maxChunk`, a key from\n * another library's config spread into this one \u2014 so every key is checked against {@link OPTION_KEYS}.\n */\n private static rejectUnknownOptions(options: CloudRoaringOptions): void {\n // A nullish or non-object bag never reaches `resolveStorageSource` \u2014 the constructor reads\n // `options.seams?.clock` first and would throw a raw TypeError. Report it here, typed, instead.\n if (options === null || options === undefined || typeof options !== 'object') {\n throw new ValidationError(\n 'CloudRoaring needs an options object with a `storage` key \u2014 got ' +\n (options === null ? 'null' : typeof options),\n );\n }\n const bag = options as unknown as Record<string, unknown>;\n const unknown: Array<{ group: OptionGroup | null; key: string }> = [];\n for (const key of Object.keys(bag)) {\n if (!(OPTION_KEYS.top as readonly string[]).includes(key)) unknown.push({ group: null, key });\n }\n const groups = Object.keys(OPTION_KEYS).filter((g): g is OptionGroup => g !== 'top');\n for (const group of groups) {\n const value = bag[group];\n if (value === undefined) continue;\n const offOk = group === 'retry' || group === 'budget';\n if (value === false && offOk) continue;\n // A group that is not an object configures nothing: `encryption: true` would build a cleartext store. The\n // built-in tag, not `instanceof`, so a boxed `new Boolean(true)` and a Map from another realm are caught.\n const tag = Object.prototype.toString.call(value).slice(8, -1);\n if (typeof value !== 'object' || value === null || NOT_A_GROUP[tag] !== undefined) {\n const got = typeof value !== 'object' ? typeof value : NOT_A_GROUP[tag];\n throw new ValidationError(\n `CloudRoaring's \\`${group}\\` must be an object${offOk ? ' or `false`' : ''} \u2014 got ${got}`,\n );\n }\n const known = OPTION_KEYS[group] as readonly string[];\n for (const key of Object.keys(value)) if (!known.includes(key)) unknown.push({ group, key });\n }\n if (unknown.length === 0) return;\n const takes = (keys: readonly string[]): string => keys.map((k) => `\\`${k}\\``).join(', ');\n const named = [...new Set(unknown.map((u) => u.group))];\n throw new ValidationError(\n `CloudRoaring does not take ${takes(unknown.map((u) => (u.group === null ? u.key : `${u.group}.${u.key}`)))}. ` +\n named\n .map((g) =>\n g === null\n ? `The store takes ${takes(OPTION_KEYS.top)}.`\n : `\\`${g}\\` takes ${takes(OPTION_KEYS[g])}.`,\n )\n .join(' ') +\n ' https://github.com/cloudbitmaps/cloudbitmaps/blob/main/docs/guide/api-reference.md#build-a-store--new-cloudroaringoptions',\n );\n }\n\n /**\n * A seam the store calls through must have the methods it calls. Without this a `clock` with no `now`, an `rng` with\n * no `next` or a keystore with no `createDek` builds a store that throws a raw `TypeError` at its first load or read.\n */\n private static rejectHollowSeams(options: CloudRoaringOptions): void {\n const seams: Array<[unknown, string, readonly string[]]> = [\n [options.seams?.clock, 'seams.clock', ['now', 'sleep']],\n [options.seams?.rng, 'seams.rng', ['next']],\n [options.encryption?.keystore, 'encryption.keystore', ['createDek', 'openDek']],\n ];\n const entropy: unknown = options.seams?.entropy;\n if (entropy !== undefined && typeof entropy !== 'function') {\n throw new ValidationError(\n \"CloudRoaring's `seams.entropy` must be a function `(length) => Uint8Array` returning that many random bytes\",\n );\n }\n for (const [seam, name, needs] of seams) {\n if (seam === undefined) continue;\n const has = (m: string): boolean =>\n seam !== null && typeof (seam as Record<string, unknown>)[m] === 'function';\n if (seam === null || typeof seam !== 'object' || !needs.every(has)) {\n throw new ValidationError(\n `CloudRoaring's \\`${name}\\` must be an object with ${needs.map((m) => `\\`${m}()\\``).join(' and ')}`,\n );\n }\n }\n }\n\n /**\n * Refuse a `cache` or `encryption` value that can never be honoured, by the name the caller wrote. The sizes reach\n * the caches under their own internal names, so left to them an error would name `maxEntries` or `maxBytes`; and\n * `encryption.required` must be exactly a boolean, since the read path took a truthy string for `true` while every\n * write path did not, which refused cleartext reads and still wrote cleartext.\n */\n private static rejectBadValues(options: CloudRoaringOptions): void {\n const cache = options.cache;\n if (cache !== undefined) {\n requirePositiveInt('cache.maxChunks', cache.maxChunks);\n requirePositiveInt('cache.readerMax', cache.readerMax);\n requirePositiveInt('cache.readerMaxBytes', cache.readerMaxBytes);\n const ttl: unknown = cache.ttlMs;\n if (ttl !== undefined && (typeof ttl !== 'number' || !Number.isFinite(ttl) || ttl <= 0)) {\n throw new ValidationError(\n `cache.ttlMs must be a finite number above 0 (milliseconds); got ${typeof ttl === 'string' ? JSON.stringify(ttl) : String(ttl)}`,\n );\n }\n }\n requireBool(\"CloudRoaring's `encryption.required`\", options.encryption?.required);\n }\n\n /**\n * Builds a store. Only `storage` is required: pass a backend such as `S3Storage` or `MemoryStorage`. `cache`,\n * `encryption`, `retry`, `metrics`, `budget` and `seams` tune it. An option it does not take, a `cache` size or `ttlMs`\n * that is not a usable number, an `encryption.required` that is not a boolean, or a seam missing a method the store\n * calls, throws `ValidationError`.\n */\n constructor(options: CloudRoaringOptions) {\n CloudRoaring.rejectUnknownOptions(options);\n CloudRoaring.rejectHollowSeams(options);\n CloudRoaring.rejectBadValues(options);\n const clock = options.seams?.clock ?? new SystemClock();\n const rng = options.seams?.rng ?? new SystemRng();\n const entropy = options.seams?.entropy ?? systemEntropy;\n // Wrap the user sink so a throwing/buggy sink can never break I/O (observability is best-effort).\n const metrics = safeMetrics(options.metrics ?? NOOP_METRICS);\n const cache = new BoundedLru<string, CodecBitmap>({\n maxEntries: options.cache?.maxChunks ?? DEFAULT_CACHE_MAX_CHUNKS,\n ttlMs: options.cache?.ttlMs,\n clock,\n });\n // Resolve the storage seam, hand a backend the metrics sink, and wrap the source in the read retry: `wireStore`.\n const wired = wireStore(options, clock, rng, metrics);\n this.retryOptions = wired.retryOptions;\n // Resolve the denial-of-wallet budget once (validates; `false` \u21D2 null = disabled) and share it between the\n // engine (count/iterate/combines) and the facade's admin scans (subjectReport/eraseSubject).\n this.budget = resolveBudget(options.budget, DEFAULT_BUDGET);\n const deps: EngineDeps = {\n storage: wired.storage,\n cache,\n codec: flagshipCodec(), // the facade injects the flagship codec; core stays codec-agnostic\n clock,\n metrics,\n budget: this.budget,\n };\n this.engine = new SegmentEngine(deps);\n this.cache = cache;\n // The UNWRAPPED `.crbm` source, kept for `pin()` \u2014 the only reader that resolves a specific generation.\n // `undefined` when the caller supplied a pre-built source, which has nothing to pin.\n this.crbmSource = wired.source instanceof CrbmStorageChunkSource ? wired.source : undefined;\n this.clock = clock;\n this.rng = rng;\n this.entropy = entropy;\n this.metrics = metrics;\n // Keep the raw drivers for the lifecycle helpers (see the fields above). They use the raw drivers directly \u2014\n // a one-shot admin op surfaces a transient fault to the caller rather than retrying under the hood \u2014 except for\n // the reads a load's guard and an erasure make along the way, which take the store's read retry (`readRetry`),\n // since a read is safe to repeat and one fault there would otherwise fail the whole write.\n this.storageDriver = wired.driver;\n this.registry = wired.registry;\n if (this.registry !== undefined) REGISTRY_OF.set(this.origin, this.registry);\n this.backend = wired.backend;\n this.keystore = options.encryption?.keystore;\n this.requireEncryption = options.encryption?.required ?? false;\n }\n\n /**\n * The write-side deps, from the store's own drivers, for the lifecycle helpers and the `*Into` verbs. Requires\n * the store to have been constructed with a **backend**, which supplies both halves: an `IStorageDriver` to\n * write generations through (a pre-built `StorageChunkSource` has none) and the registry holding the pointer\n * every write publishes.\n */\n private lifecycleDeps(op: string): LifecycleDeps {\n if (this.storageDriver === undefined) {\n throw new UnsupportedError(\n `${op} needs the store built with a storage backend \u2014 S3Storage, GcsStorage, AzureBlobStorage, ` +\n `LocalFsStorage or MemoryStorage. A pre-built StorageChunkSource is read-only: it has no ` +\n `IStorageDriver underneath to write generations through. Build the store on one of those backend ` +\n `classes to write.`,\n );\n }\n if (this.registry === undefined) {\n throw new UnsupportedError(\n `${op} needs a storage backend \u2014 S3Storage, GcsStorage, AzureBlobStorage, LocalFsStorage or ` +\n `MemoryStorage. A bare IStorageDriver has no generation pointer to publish through, and there is ` +\n `no separate \\`registry\\` option: a backend carries it.`,\n );\n }\n return {\n storage: this.storageDriver,\n registry: this.registry,\n clock: this.clock,\n rng: this.rng,\n entropy: this.entropy,\n codec: flagshipCodec(), // facade injects the flagship codec\n keystore: this.keystore,\n requireEncryption: this.requireEncryption,\n readRetry: this.retryOptions,\n };\n }\n\n /**\n * Get a handle to a segment. Validates the name (non-empty, well-formed, within the encoded-length cap). The options\n * are a plain object holding `{ namespace }` and nothing else: any other own key, enumerable or not, is refused with\n * {@link ValidationError}, by name, since a misspelt `namespace` would otherwise address the default namespace, and a\n * deadline such as `expiresAt` would be left unread. A class instance, or an object built on another, is refused too,\n * since it can carry an option no scan of its own keys sees. A key whose value is `undefined` is read as absent, so a\n * spread of options keeps working.\n */\n segment(name: string, options?: SegmentOptions): Segment {\n if (typeof name === 'object' && name !== null) {\n throw new ValidationError(\n Array.isArray(name)\n ? \"segment: the name is a string, store.segment('name'), not an array\"\n : 'segment: the name is a string, not a ref: for a ref, call store.segment(ref.segment, { namespace: ref.namespace })',\n );\n }\n if (options !== undefined && options !== null) {\n if (typeof options !== 'object' || Array.isArray(options)) {\n throw new ValidationError('segment: options must be an object such as { namespace }');\n }\n // A plain object of any realm has a prototype whose own prototype is null.\n const proto = Object.getPrototypeOf(options) as object | null;\n if (proto !== null && Object.getPrototypeOf(proto) !== null) {\n throw new ValidationError(\n 'segment: options must be a plain object such as { namespace }, not a class instance or an object built on another',\n );\n }\n const unknown = Object.getOwnPropertyNames(options).filter(\n (k) => k !== 'namespace' && (options as Record<string, unknown>)[k] !== undefined,\n );\n if (unknown.length > 0) {\n throw new ValidationError(\n `segment: unknown option${unknown.length > 1 ? 's' : ''} ${unknown.map((k) => `\"${k}\"`).join(', ')}; ` +\n 'a handle takes { namespace } only',\n );\n }\n }\n const ref: SegmentRef = { segment: name, namespace: options?.namespace };\n validateSegmentRef(ref);\n refuseReservedNamespace(ref.namespace);\n return makeSegment({\n engine: this.engine,\n origin: this.origin,\n ref,\n clock: this.clock,\n metrics: this.metrics,\n materialize: (dest, ids, op, options) => this.materialize(dest, ids, op, options),\n pinned: (r, l, at) => this.pinSegment(r, l, at),\n combineEngine: (handles) => this.engineForCombine(handles),\n });\n }\n\n /**\n * Write `ids` as a **new generation of `dest`** and publish it \u2014 the shared body of the `*Into` verbs. An `*Into`\n * materialisation is a load, and publishes the same way (hard invariant 1): every load that finds a row fences its\n * publish on the row's token, and every load that finds none on that absence, guarded or not; a guarded load (the\n * default, since the empty refusal needs the size of the current generation) also fences on the pointer it judged\n * (`expectFrom`). The destination's previous generation stays readable until the publish lands (readers re-resolve\n * within `cache.genTtlMs`).\n *\n * This routes through `loadSegment` rather than writing the generation itself, and that is the whole point\n * of it. A materialisation is a load whose ids happen to come from a combine instead of from upstream, so\n * everything `load()` learned the hard way applies unchanged: the generation is written UNPUBLISHED, the\n * guard runs while the old generation is still authoritative, the publish is fenced as above, and a refused\n * object is reclaimed only when a re-read finds the row unchanged (the same token, or one that differs only in\n * its leases), `destroyed`, or gone, or finds key material on it when the load wrote cleartext; under any other\n * row it is kept (hard invariant 1: deleting it after a purge-and-recreate would put a live row over a missing\n * generation).\n *\n * Where the row is gone, or keyed over a cleartext write, the object's footer must match what the load wrote, and\n * the delete passes the version that read reported, so on a storage driver that reports `conditionalDelete` an\n * object put under the number since is kept. Where the row is unchanged or `destroyed`, the check narrows the\n * window rather than closing it: the row read and the delete are two round trips, and the delete is by number,\n * since the write reports no version of the object it made. The other deletes a load leads to are by number too: its\n * collection deletes what a listing, or the row's list of kept generations, names below the pointer, and a drop's\n * sweep and a tombstoned segment's collection delete what a listing names under a `destroyed` row. The failure the\n * checks leave when they refuse is an orphan object, which costs storage until something collects it \u2014\n * deliberately the cheaper side of the trade.\n *\n * Written and published in one step, with no guard, an empty combine \u2014 a typo'd operand, an `exclude` that\n * swallowed everything, an operand that had not loaded yet \u2014 would silently replace `dest` with an empty\n * generation: the same failure `load()`'s guard exists to prevent, on the same data, reachable without passing\n * any option at all.\n *\n * **A lost race throws.** `loadSegment` reports one as `reason: 'superseded'`; the `*Into` verbs throw\n * {@link WriteConflictError} for it, so a caller can `catch (WriteConflictError)`. That one refusal is\n * translated into the throw, and `MaterializeResult.reason` never carries it.\n *\n * **A `WriteConflictError` does not by itself mean nothing was published**, and that is worth knowing\n * before you write the retry. `'superseded'` covers five different causes \u2014 the write-once PUT collided,\n * the pointer moved, a row appeared where the load found none, the row's token changed, the row was purged \u2014\n * and only the first two are always the \"somebody beat us\" the name suggests. A row can appear, and a token can\n * change, on a write that is not a supersession at all: a `setRetention` on the destination creates its row when it\n * has none, and rewrites it when it has one. On top of that, the collection pass that runs AFTER a successful\n * publish can raise the same error. So: treat it as \"re-read the destination and decide\",\n * never as \"the write did not happen\".\n *\n * **And by default it collects nothing**, unlike `load()`. See the `keep` default below.\n */\n private async materialize(\n dest: SegmentRef,\n ids: LoadInput | CombineChunks,\n op: string,\n options?: CombineOptions,\n ): Promise<MaterializeResult> {\n // A materialisation's `keep` collects every generation below the new one beyond it, which a destination that\n // earlier materialisations kept in full needs a listing for.\n const deps = { ...this.lifecycleDeps(op), collectByListing: true };\n // Read once, here: a getter or a proxy answering twice would otherwise be checked as one value and stored as another.\n const metadata = options?.metadata;\n let result: Awaited<ReturnType<typeof loadSegment>>;\n try {\n const loadOptions = {\n ...(options?.allowEmpty === undefined ? {} : { allowEmpty: options.allowEmpty }),\n ...(options?.guard === undefined ? {} : { guard: options.guard }),\n ...(metadata === undefined ? {} : { metadata }),\n // COLLECT NOTHING by default, which `loadSegment` does not \u2014 it keeps a grace window of 1 and deletes\n // the rest. By default a materialisation collects nothing: the guide states \"**It deletes nothing**,\n // unlike `load()`. The destination's previous generations stay in the bucket until you collect them\", and\n // the ownership table\n // puts that call on the operator. Inheriting `load()`'s collection would silently delete the\n // generations an operator's recovery story depends on \u2014 `rollbackSegment` refuses a collected target \u2014\n // as a side effect of adding a guard whose entire purpose is preventing data loss. Opt in with `keep`.\n keep: options?.keep === undefined ? KEEP_EVERY_GENERATION : options.keep,\n ...(options?.audit === undefined ? {} : { audit: options.audit }),\n };\n result =\n ids instanceof CombineChunks\n ? await loadSegmentChunks(dest, ids.chunks, deps, loadOptions)\n : await loadSegment(dest, ids, deps, loadOptions);\n } finally {\n // As `load()` does: this store's view of `dest` is behind whatever just happened, and a throw can still have\n // published first. Left alone, the store read its own write's predecessor: indefinitely, with no timed refresh.\n this.engine.invalidate(dest);\n }\n // Checked on `reason` alone, not `published && reason`: the compiler narrows a const through an equality\n // test, so after this throw `reason` is provably a `MaterializeRefusal` and the return below type-checks\n // without an assertion. `'superseded'` only ever accompanies `published: false` anyway.\n const reason = result.reason;\n if (reason === 'superseded') {\n // The object is durable, but this call's write may not be the one that made it current: a concurrent writer\n // published a higher generation of `dest` between our numbering and our publish, or a write that renewed the\n // row over ours left us unable to tell it from another writer's. Ours may then be an orphan no reader will\n // resolve. Returning it here would name `generation` as \"the destination's new current generation\" \u2014 which is\n // what `MaterializeResult` documents it to be, and it could be false. The destination may hold someone else's\n // content.\n //\n // A throw rather than a flag: every other write path in the library reports a lost race loudly, and a\n // materialisation that silently did not take effect is the one outcome a caller cannot detect on its\n // own.\n // `size > 0` distinguishes the two ways a materialisation loses the race, and the operator needs them\n // apart: the object either exists (an orphan, collected by the first load that collects once a generation\n // above it is current or deleted by the refusal itself when the destination was dropped meanwhile; or current\n // but not provably this call's, when a write renewed the row's `pointerId` over it) or was never written at all,\n // because the write-once PUT itself collided. Telling someone to look for an\n // orphan that does not exist is a wasted investigation.\n // Deliberately does NOT assert which of the four causes it was. \"A newer generation was published first\"\n // is wrong for two of them: a `setRetention` on the\n // destination bumps the row's token without publishing anything, and a purge leaves no row at all.\n // Telling an operator to go looking for a newer generation that does not exist costs a real\n // investigation. `size > 0` is the one thing this path can state as fact.\n const wrote =\n result.size > 0\n ? `generation ${result.generation} was written and may not be current`\n : `nothing was written \u2014 another writer took generation ${result.generation} first`;\n throw new WriteConflictError(\n `${op}: the destination \"${dest.segment}\" changed while this materialisation was in flight, so its ` +\n `result may not be the destination's current generation: ${wrote}. The pointer may have moved, the row may have been created or rewritten ` +\n `(a retention policy does either), dropped or purged. Re-read the destination and re-run.`,\n );\n }\n return {\n generation: result.generation,\n published: result.published,\n ...(reason === undefined ? {} : { reason }),\n cardinality: result.cardinality,\n cardinalityBefore: result.cardinalityBefore,\n chunkCount: result.chunkCount,\n size: result.size,\n collected: result.collected,\n };\n }\n\n /**\n * **A dry run:** every output computed exactly as the call would compute it, and judged against its `dest` as its\n * publish would be, with nothing written: no object, no pointer, no audit event. Each output's result says how many ids\n * it would hold, what its `dest` holds now, and the bound its publish would be refused for now (`wouldRefuse`). The\n * call reads its operands as a publishing call does, takes its feed if it has one, and fails an output for what would\n * fail its publish (a `dest` whose lease has ended, a destroyed one, a moved exclude, an erasure). It reads the operands as\n * the publishing call does, and for each output the reads a publish's guard makes: one registry read for `dest`'s size,\n * or two where its row has no usable summary. It holds the memory a publish would, so it fails for memory where one\n * would, and reports to the metrics sink as the same `materializeMany` op.\n *\n * What it reports holds for now only: a publish made later reads the operands and judges each `dest` as they are then.\n * To publish what was reviewed, call again without `dryRun`, on the same pinned handles or with the same feed (the\n * guide's recipe).\n */\n materializeMany(options: MaterializeManyDryRunOptions): Promise<MaterializeManyDryRun>;\n /**\n * The call with `dryRun` a switch held in a variable, optional or not: a {@link MaterializeManyDryRun} when it is\n * `true` and a {@link MaterializeManyRun} when it is `false` or absent, so with a `boolean` (or `boolean | undefined`)\n * the result is typed as either, and the flag passed says which. A literal `true` or `false`, and a call without\n * `dryRun`, are typed exactly, as by the forms either side of this one.\n */\n materializeMany<D extends boolean | undefined = undefined>(\n options: MaterializeManyOptions & { readonly dryRun?: D },\n ): Promise<D extends true ? MaterializeManyDryRun : MaterializeManyRun>;\n /**\n * **Many outputs, each operand read once per group.** Each output is an expression over named stored operands (`and`, `or`, `andNot`, nested\n * to depth 64) published as a new generation of its own `dest`, exactly as an `*Into` would publish it, but computed\n * together: each operand's chunks are read once for all the outputs that use them, instead of once per output and\n * once more for every scratch segment a nested expression would otherwise need.\n *\n * ```ts\n * const run = await store.materializeMany({\n * operands: { us: store.segment('us'), engaged: store.segment('engaged'), optOut: store.segment('opt-out') },\n * outputs: [\n * { dest: store.segment('send-1'), expr: { and: ['us', 'engaged'] }, exclude: ['optOut'] },\n * { dest: store.segment('send-2'), expr: { andNot: ['us', 'engaged'] } },\n * ],\n * keep: 3,\n * });\n * run.outputs[0]; // a MaterializeResult, or { published: false, error }\n * ```\n *\n * **Results.** `run.outputs[i]` is index-aligned with `outputs` and is exactly what output `i`'s `*Into` would have\n * returned (a {@link MaterializeResult}: published, or refused with its `reason`), or `{ published: false, error }` for\n * what it would have thrown. One output's refusal or error never stops another. The call itself throws only for bad\n * input ({@link ValidationError} naming the output index and path, before any request), an operand that names no\n * segment (unless `allowAbsentOperands`), and a `budget` its own plan exceeds, the last two before any chunk is read.\n *\n * **One generation per operand.** By default every stored operand is pinned for the call: read at the generation it had\n * when the call started, however long the call runs and whatever loads land meanwhile. That is one generation per\n * operand, not one instant across operands (two pins are two registry reads). `pin: false` reads live, as a combine does.\n *\n * **Every pinned operand an output subtracts is re-checked.** An output subtracts an operand when it is in its `exclude`\n * or under any entry of an `andNot` after the first, at any depth. Immediately before the publishes the call re-reads the\n * registry row of each such operand and compares its generation and incarnation, and the fingerprint of the current\n * object where both reads carry one, with what was pinned (a name deleted and created again is a replacement though it\n * is generation 0 again). If one was replaced, each output that subtracts it is\n * not published and carries {@link StaleOperandError}; the others publish. It costs one registry read per such operand per\n * group, and `stats.operands` carries every operand's pinned, start and end generation and whether it moved.\n *\n * **Memory.** Everything the pass holds resident is counted against `maxBufferedBytes` (default 256 MiB): each output's\n * buffered chunks, the operand streams' ranges, the chunks being evaluated, and the plan itself, and a call whose plan alone\n * passes it is refused before any chunk is read. When the outputs do not fit, they run in groups, each reading its operands\n * once (so the operand reads grow with the total output size over the budget), and a group's buffers are released only as\n * its publishes settle. A chunk count the index understated does not grow a group past the budget: the largest buffer is\n * dropped and that output re-runs alone. An output that cannot fit alone has `BudgetExceededError` as its result. The count\n * is the pass's own: process memory is more, measured at 1.6 times the ledger's high water on Linux and 2.5 to 5 times on\n * macOS on the in-memory backend (the guide has the shapes and what is not counted).\n *\n * **Untrusted bytes.** Every operand chunk is decoded through the checks on untrusted tier data. A key an operand's index\n * lists whose bytes are missing is an error for the outputs that read the operand, never an empty chunk.\n *\n * **Handles.** A handle anywhere in the call (an operand or a `dest`) whose lease has ended or was released is refused\n * before any request, as on the `*Into` verbs. A leased operand's lease is checked before each chunk key is read: a\n * lapse fails only the outputs that read that operand, never reads empty. Each `dest`'s lease is checked again just\n * before its publish.\n *\n * **The chunk cache is bypassed:** the pass reads through the storage source and never writes the decoded-chunk cache, so\n * a batch does not evict other readers' hot chunks. Each publish still invalidates its `dest` as an `*Into` does.\n *\n * **A limit of the form.** An output cannot name another output of the same call: a `dest` that is also an operand is\n * refused. Chain two calls.\n *\n * **A feed.** `feed: { names, records, counts }` adds operands that arrive as records in chunk-key order, for conditions\n * too many to hold or store. Each record is checked before the pass sees it (see {@link MaterializeManyFeedRecord}): a bad\n * feed is refused, never read as fewer members, and **a fed output is published only after the whole feed was read and every\n * end-of-feed check passed**, so a bad feed refuses every fed output and publishes none of them; outputs that name only\n * stored operands are unaffected. At the end of the feed `counts` must equal the ids the feed held for each name, and a\n * name that appeared in no record is refused unless it is in `mayBeEmpty`. A feed is read once, so the call runs its outputs\n * as one group and **`maxBufferedBytes` is required**: each record is converted to compressed bitmaps as it arrives, the key\n * in hand and its fed outputs are counted against the budget, and the call fails as soon as the count passes it, with\n * {@link BudgetExceededError} for every fed output. **Erasure:** a fed call is refused at its next record, and before each\n * fed publish, once `eraseSubject` has started in this store ({@link StaleOperandError}, `reason: 'erased'`).\n *\n * ```ts\n * await store.materializeMany({\n * operands: { unsub: store.segment('global-unsub') },\n * feed: {\n * names: ['us', 'engaged'],\n * records: warehouseRecords(), // yields { key, operands: { us: Uint32Array, engaged: Uint32Array } } by key\n * counts: () => warehouseCounts(),\n * },\n * maxBufferedBytes: 512 * 1024 * 1024,\n * outputs: [{ dest: store.segment('send-1'), expr: { and: ['us', 'engaged'] }, exclude: ['unsub'] }],\n * keep: 12,\n * });\n * ```\n */\n materializeMany(\n options: MaterializeManyOptions & { readonly dryRun?: false },\n ): Promise<MaterializeManyRun>;\n /** The one body of the forms above. */\n async materializeMany(\n options: MaterializeManyOptions & { readonly dryRun?: boolean },\n ): Promise<MaterializeManyRun | MaterializeManyDryRun> {\n if (typeof options !== 'object' || options === null) {\n throw new ValidationError(\n 'materializeMany needs an options object with `operands`, `outputs` and `keep`',\n );\n }\n // The erasure counter as the call begins: a fed call is refused once it has moved.\n const epochAt = options.feed === undefined ? 0 : this.epochNow();\n const unknown = unknownManyKeys(options);\n if (unknown.length > 0) {\n throw new ValidationError(\n `materializeMany: unknown option${unknown.length > 1 ? 's' : ''} ${unknown.map((k) => `\"${k}\"`).join(', ')}`,\n );\n }\n // Read once, here: a getter or a proxy answering twice would be checked as one value and used as another.\n const dryRunIn: unknown = options.dryRun;\n if (dryRunIn !== undefined && typeof dryRunIn !== 'boolean') {\n throw new ValidationError('materializeMany: dryRun must be a boolean');\n }\n const dryRun = dryRunIn === true;\n const operandsIn: unknown = options.operands;\n const outputsIn: unknown = options.outputs;\n const keep = options.keep;\n const after = options.after;\n const through = options.through;\n // `null` is not the default: a switch is `true` or `false`, as on every call.\n const pinOption: unknown = options.pin === undefined ? true : options.pin;\n const feedIn: unknown = options.feed;\n const mayBeEmptyIn: unknown = options.mayBeEmpty;\n if (feedIn !== undefined && options.maxBufferedBytes === undefined) {\n throw new ValidationError(\n 'materializeMany: maxBufferedBytes is required with a feed: the feed is read once, so the call runs as one group and the budget is what bounds it',\n );\n }\n const maxBufferedBytes = options.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES;\n const publishConcurrency = options.publishConcurrency ?? DEFAULT_PUBLISH_CONCURRENCY;\n const concurrency = options.concurrency ?? DEFAULT_BATCH_CONCURRENCY;\n const budgetOption = options.budget;\n const allowAbsentOperands = options.allowAbsentOperands;\n if (typeof pinOption !== 'boolean')\n throw new ValidationError('materializeMany: pin must be a boolean');\n if (allowAbsentOperands !== undefined && typeof allowAbsentOperands !== 'boolean') {\n throw new ValidationError('materializeMany: allowAbsentOperands must be a boolean');\n }\n if (typeof operandsIn !== 'object' || operandsIn === null || Array.isArray(operandsIn)) {\n throw new ValidationError('materializeMany: operands must be an object of name to segment');\n }\n if (!Array.isArray(outputsIn) || outputsIn.length === 0) {\n throw new ValidationError('materializeMany: outputs must be a non-empty array');\n }\n const names = Object.keys(operandsIn);\n const handles = new Map<string, Segment>();\n for (const name of names) {\n const handle = (operandsIn as Record<string, unknown>)[name];\n assertOneStore('materializeMany', `operands[\"${name}\"]`, handle, this.origin);\n handles.set(name, handle);\n }\n // `mayBeEmpty` names fed operands, which the feed checks; without a feed it can name nothing.\n if (mayBeEmptyIn !== undefined && feedIn === undefined) {\n if (!Array.isArray(mayBeEmptyIn)) {\n throw new ValidationError(\n 'materializeMany: mayBeEmpty must be an array of fed operand names',\n );\n }\n if (mayBeEmptyIn.length > 0) {\n const first: unknown = mayBeEmptyIn[0];\n const what =\n typeof first !== 'string'\n ? 'something that is not a name'\n : handles.has(first)\n ? `\"${first}\", a stored operand`\n : `\"${first}\", which is not an operand of this call`;\n throw new ValidationError(\n `materializeMany: mayBeEmpty names ${what}; it names fed operands, and this call has no feed`,\n );\n }\n }\n const operandKeys = new Set([...handles.values()].map((h) => h.key()));\n const outputs: Array<{ spec: MaterializeManyOutput; dest: Segment }> = [];\n const destKeys = new Set<string>();\n (outputsIn as unknown[]).forEach((raw, i) => {\n if (typeof raw !== 'object' || raw === null) {\n throw new ValidationError(`outputs[${i}] must be an object`);\n }\n const bad = Object.keys(raw).filter(\n (k) => !(MATERIALIZE_MANY_OUTPUT_KEYS as readonly string[]).includes(k),\n );\n if (bad.length > 0) {\n throw new ValidationError(\n `outputs[${i}]: unknown option${bad.length > 1 ? 's' : ''} ${bad.map((k) => `\"${k}\"`).join(', ')}`,\n );\n }\n const spec = raw as MaterializeManyOutput;\n const dest: unknown = spec.dest;\n assertOneStore('materializeMany', `outputs[${i}].dest`, dest, this.origin);\n if (operandKeys.has(dest.key())) {\n throw new ValidationError(\n `outputs[${i}].dest is also an operand of the call: one call is one pass over operands that do not change under it, so chain two calls`,\n );\n }\n if (destKeys.has(dest.key())) {\n throw new ValidationError(\n `outputs[${i}].dest names a segment another output of the call writes`,\n );\n }\n destKeys.add(dest.key());\n outputs.push({ spec, dest });\n });\n // A ceiling the store was built with applies to a call that names none, as it does to every other operation; only a\n // store left on the library default lets the call size its own from its plan.\n const storeCeiling =\n this.budget === null || this.budget.maxRequests !== DEFAULT_BUDGET.maxRequests\n ? this.budget\n : undefined;\n const budget =\n budgetOption === undefined ? storeCeiling : resolvePerOpBudget(budgetOption, this.budget);\n // Every expression and option is checked here, with no operand pinned and no request made.\n const operandSpecs = (pins: ReadonlyMap<string, PinnedAt | undefined>): CombineManyOperand[] =>\n names.map((name) => {\n const handle = handles.get(name)!;\n const seg = viewOf(handle);\n const pinnedAt = pins.get(handle.key());\n return {\n name,\n ref: seg.ref,\n ...(handle.lease === undefined ? {} : { check: () => this.assertLease(handle) }),\n ...(pinnedAt === undefined\n ? {}\n : {\n pinnedGeneration: pinnedAt.generation,\n pinnedVersion: pinnedAt.version,\n pinnedFingerprint: pinnedAt.fingerprint,\n }),\n current: (read?: { readonly fingerprint?: boolean }) =>\n this.currentRowOf(seg.ref, read?.fingerprint === true),\n };\n });\n const request = (pins: ReadonlyMap<string, PinnedAt | undefined>) => ({\n operands: operandSpecs(pins),\n outputs: outputs.map(({ spec, dest }) => ({\n expr: spec.expr,\n ...(spec.exclude === undefined ? {} : { exclude: spec.exclude }),\n ...(spec.allowEmpty === undefined ? {} : { allowEmpty: spec.allowEmpty }),\n ...(spec.guard === undefined ? {} : { guard: spec.guard }),\n ...(spec.metadata === undefined ? {} : { metadata: spec.metadata }),\n ...(spec.keep === undefined ? {} : { keep: spec.keep }),\n beforePublish: () => this.assertLease(dest),\n // What a settled publish proves it sent: a published one wrote its object and moved the pointer, a refused one\n // wrote its object and deleted it. A dry run's judgement wrote nothing, and read the row and maybe the object.\n requestsOf: (result: MaterializeResult | DryRunValue) =>\n 'dryRun' in result\n ? { get: result.reads, put: 0 }\n : { get: 0, put: result.published ? 2 : 1 },\n publish: (\n chunks: AsyncIterable<{ readonly chunkKey: number; readonly bitmap: CodecBitmap }>,\n write: {\n readonly keep: number;\n readonly allowEmpty?: boolean;\n readonly guard?: LoadGuard;\n readonly metadata?: GenerationMetadata;\n },\n ): Promise<MaterializeResult | DryRunValue> =>\n dryRun\n ? this.judgeOutput(viewOf(dest).ref, chunks, write)\n : this.materialize(viewOf(dest).ref, new CombineChunks(chunks), 'materializeMany', {\n ...write,\n ...(spec.audit === undefined ? {} : { audit: spec.audit }),\n }),\n })),\n keep: keep as number,\n ...(after === undefined ? {} : { after }),\n ...(through === undefined ? {} : { through }),\n maxBufferedBytes,\n publishConcurrency,\n concurrency,\n ...(budget === undefined ? {} : { budget }),\n ...(allowAbsentOperands === undefined ? {} : { allowAbsentOperands }),\n ...(feedIn === undefined ? {} : { feed: this.feedOf(feedIn, mayBeEmptyIn, epochAt) }),\n ...(dryRun ? { dryRun: true } : {}),\n });\n const compiled = compileCombineMany(request(new Map()));\n // A handle anywhere whose lease has ended or was released is refused before any request, as the `*Into` verbs refuse one.\n for (const { dest } of outputs) this.assertLease(dest);\n for (const handle of handles.values()) this.assertLease(handle);\n this.lifecycleDeps('materializeMany');\n const crbm = this.crbmSource;\n if (crbm === undefined) {\n throw new UnsupportedError(\n 'materializeMany needs the `.crbm` storage source \u2014 pass a backend or a raw IStorageDriver as `storage`',\n );\n }\n // One pin per segment, shared by every name that holds it. A handle passed already pinned is used as it is.\n const held = new Map<string, { at: PinnedAt | undefined; handle: Segment }>();\n for (const [name, handle] of handles) {\n const key = handle.key();\n const at = handle.pinnedAt;\n const prior = held.get(key);\n if (prior === undefined) {\n held.set(key, { at, handle });\n } else if (prior.at !== undefined && at !== undefined) {\n if (!samePin(prior.at, at)) {\n throw new ValidationError(\n `materializeMany: operand \"${name}\" holds a segment another operand holds, ${twoPins(prior.at, at)}: one call reads a segment at one generation`,\n );\n }\n } else if (prior.at !== undefined || at !== undefined) {\n if (!pinOption) {\n throw new ValidationError(\n `materializeMany: operand \"${name}\" holds a segment another operand holds, ${twoPins(prior.at, at)}: one call reads a segment at one generation`,\n );\n }\n if (at !== undefined) held.set(key, { at, handle });\n }\n }\n const pins = new Map<string, PinnedAt | undefined>();\n const toPin: Array<[string, Segment]> = [];\n for (const [key, { at, handle }] of held) {\n if (at !== undefined) pins.set(key, at);\n else if (pinOption) toPin.push([key, handle]);\n else pins.set(key, undefined);\n }\n // Timed from the first request, the pins, to the last publish, as an `*Into` call is timed around its read and write.\n const metricsOn = this.metrics !== NOOP_METRICS;\n const work = async () => {\n const taken = await mapWithConcurrency(\n toPin,\n PIN_PARALLELISM,\n async ([key, handle]) => [key, (await handle.pin()).pinnedAt] as const,\n );\n for (const [key, at] of taken) pins.set(key, at);\n const live = new Map([...pins].filter((e): e is [string, PinnedAt] => e[1] !== undefined));\n const pinnedSource = new PinnedStorageChunkSource(crbm, live);\n const source =\n this.retryOptions === undefined\n ? pinnedSource\n : new RetryingStorageChunkSource(pinnedSource, this.retryOptions);\n const final = rebindCombineMany(compiled, operandSpecs(pins));\n return runCombineMany(final, {\n source,\n codec: flagshipCodec(),\n clock: this.clock,\n ...(metricsOn ? { metrics: this.metrics } : {}),\n });\n };\n const run = metricsOn\n ? await timeOp(this.metrics, this.clock, 'materializeMany', work)\n : await work();\n const results = run.outputs.map((o) => {\n if (!o.ok) {\n return {\n published: false as const,\n error: o.error instanceof Error ? o.error : new Error(String(o.error)),\n };\n }\n if (!('dryRun' in o.value)) return o.value;\n const v = o.value;\n const judged: MaterializeDryRunResult = {\n dryRun: true,\n published: false,\n cardinality: v.cardinality,\n cardinalityBefore: v.cardinalityBefore,\n ...(v.wouldRefuse === undefined ? {} : { wouldRefuse: v.wouldRefuse }),\n };\n return judged;\n });\n return dryRun\n ? { outputs: results as MaterializeManyDryRunOutcome[], stats: run.stats }\n : { outputs: results as MaterializeManyOutcome[], stats: run.stats };\n }\n\n /**\n * A dry run's publish of one output: count what the finished chunks hold, and judge that size against `dest` as a\n * load would, writing nothing.\n */\n private async judgeOutput(\n dest: SegmentRef,\n chunks: AsyncIterable<{ readonly chunkKey: number; readonly bitmap: CodecBitmap }>,\n write: { readonly allowEmpty?: boolean; readonly guard?: LoadGuard },\n ): Promise<DryRunValue> {\n let cardinality = 0;\n for await (const chunk of chunks) cardinality += chunk.bitmap.size;\n const judged = await judgeLoad(dest, cardinality, this.lifecycleDeps('materializeMany'), {\n ...(write.allowEmpty === undefined ? {} : { allowEmpty: write.allowEmpty }),\n ...(write.guard === undefined ? {} : { guard: write.guard }),\n });\n return {\n dryRun: true,\n published: false,\n cardinality,\n cardinalityBefore: judged.cardinalityBefore,\n ...(judged.wouldRefuse === undefined ? {} : { wouldRefuse: judged.wouldRefuse }),\n reads: judged.reads,\n };\n }\n\n private epochNow(): number {\n return this.erasureEpoch;\n }\n\n /**\n * Whether an erasure has started in this store since `at` was read, or was running when it was: one that is still\n * running is seen by the count of those running, and one that has ended since by the counter, which its end moved.\n * The one check every call that reads caller memory uses.\n */\n private epochMoved(at: number): boolean {\n return this.erasuresRunning > 0 || this.epochNow() !== at;\n }\n\n /** A call's feed with the store's erasure counter: read once here, checked by the combine before any record is read. */\n private feedOf(feed: unknown, mayBeEmpty: unknown, epochAt: number): CombineManyFeed {\n if (typeof feed !== 'object' || feed === null || Array.isArray(feed)) {\n throw new ValidationError(\n 'materializeMany: feed must be an object with names, records and counts',\n );\n }\n const f = feed as Record<string, unknown>;\n return {\n names: f.names as string[],\n records: f.records as AsyncIterable<MaterializeManyFeedRecord>,\n counts: f.counts as CombineManyFeed['counts'],\n ...(mayBeEmpty === undefined ? {} : { mayBeEmpty: mayBeEmpty as string[] }),\n epoch: { moved: () => this.epochMoved(epochAt) },\n };\n }\n\n /**\n * The registry row of `ref`, read straight from the registry, not from a snapshot: a re-check must see a move. With\n * `fingerprint`, the current generation's object is opened too (one tail read, as a pin of it makes), and its\n * fingerprint is returned beside the row: a generation's number is identified by its row and its object, since a number\n * can be taken again once its object is gone.\n */\n private async currentRowOf(\n ref: SegmentRef,\n fingerprint: boolean,\n ): Promise<{ generation: number | null; token: string; fingerprint?: string | null } | null> {\n const registry = this.requireRegistry('materializeMany');\n if (fingerprint && this.crbmSource !== undefined) {\n const crbm = this.crbmSource;\n const at = await this.withRetries(() => crbm.pinGeneration(ref));\n const colon = at?.version.indexOf(':') ?? -1;\n if (at !== null && colon >= 0) {\n return {\n generation: at.generation,\n token: at.version.slice(colon + 1),\n fingerprint: at.fingerprint,\n };\n }\n }\n const row = await this.withRetries(() => registry.get(ref));\n return row === null ? null : { generation: row.currentGen, token: pointerIdOf(row) };\n }\n\n /** Throw what a read of, or a publish to, `handle` must throw now: its lease error, if it has one. */\n private assertLease(handle: Segment): void {\n const lease = viewOf(handle).leaseError();\n if (lease !== undefined) throw lease;\n }\n\n /**\n * **Subject access (GDPR Art. 15 / CCPA right-to-know): which segments is this id a member of?**\n *\n * Enumerates the **registered** segments (via the store's own `registry`) and does a `has(id)` on each \u2014 no\n * drivers to re-pass. Complete only over registered segments (every loaded segment has a row, so build the\n * store on the backend the loads used). There is deliberately **no `id \u2192 segments` reverse index** \u2014 that would\n * tax every load for a rare request; this admin scan is `O(registered segments)` and touches no hot path. Needs\n * a storage backend (throws {@link UnsupportedError} otherwise).\n *\n * **Scope: one `namespace`, or `{ allNamespaces: true }`, never both** (both throws `ValidationError`, as does\n * neither). A segment loaded with no `namespace` is in no namespace you can name: only `{ allNamespaces: true }`\n * reaches it. `'_default'`, the label the export tool and the disaster-recovery samples print, and the bucket's\n * object keys use, for such a segment, is an ordinary namespace name here, and passing it scans a namespace of that name, not those segments.\n *\n * **Current as of the registry row, not as of the reader's cache.** Each segment's resolved generation is\n * compared with the row the scan listed, and a segment whose cached generation differs is re-resolved before the\n * read, so a load or an erasure from another process shows at once \u2014 whatever `cache.genTtlMs` is, `0` included.\n * The comparison is on the generation **and** the row's token, so a segment retired, purged and loaded again from\n * generation 0 while this store held its old generation 0 is told apart too.\n *\n * **A destroyed segment is searched as {@link CloudRoaring.eraseSubject} searches it.** No read resolves a\n * tombstone, so the id is a member of none, but a cleartext `destroySegment` (`allowCleartext`), or a `dropSegment`\n * whose sweep missed an object a load was still writing, leaves objects anyone with bucket access can read. Each\n * object left under the tombstone is opened newest first until one holds the id, and the segment is then listed in\n * `tombstones`, never in `segments`. A crypto-shredded segment's own objects are sealed under a key no row holds and are\n * never a holder: it is listed only when an object left under it in the clear holds the id. The cost is one listing per destroyed segment in scope (1 request when nothing is left), and for each\n * object opened a tail read and, where its index lists the id's chunk, a chunk read (two tail reads for an encrypted\n * object, which never holds the id): 7 requests for a cleartext destroy with 3 objects, 21 for 10. The budget is\n * charged one unit for each object opened past the one the row names, as `eraseSubject` charges. A report that runs\n * out, or whose listing or read fails after the store's retry, rejects rather than under-reporting, so one leftover\n * object that cannot be opened makes every report over its scope reject until it is removed (`generations(ref)` lists\n * what is left, `dropSegment` deletes it). A report refused for budget while it searches a destroyed segment reports\n * `spent` as `limit + 1`, a lower bound.\n */\n async subjectReport(\n id: number,\n options: { concurrency?: number; budget?: BudgetOption } & (\n { namespace: string; allNamespaces?: false } | { allNamespaces: true; namespace?: undefined }\n ),\n ): Promise<SubjectReport> {\n checkOptions(options, 'subjectReport', CALL_KEYS.subjectReport, ['allNamespaces']);\n options ??= {} as typeof options; // plain JS: no options reads as no scope, which requireScope refuses\n const registry = this.requireRegistry('subjectReport');\n requireScope(options, 'subjectReport'); // tenancy: explicit namespace, or an { allNamespaces: true } ack\n validateConcurrency(options.concurrency); // fail fast before the (possibly huge) registry scan\n const budget = resolvePerOpBudget(options.budget, this.budget); // partial override inherits the store's tightening\n splitId(id); // fail fast on a non-u32 id even when no segments are registered\n // Bounded INCREMENTALLY: draining the whole registry and only then checking the budget would refuse the\n // work after paying for the list \u2014 measured at 20,000 records buffered under `maxRequests: 2`. This is a\n // GDPR Art. 15 entry point plausibly wired to end-user traffic, so resident memory must be O(budget), not\n // O(fleet size).\n const recs = await collectWithinBudget(\n // A subject cannot be in a due-index row, and charging this request's budget for them would refuse a\n // GDPR Art. 15 report for a reason unrelated to the subject.\n excludingReservedRows(registry.list(options.namespace)),\n budget,\n 'subjectReport',\n );\n // The scan charged one unit a segment; each object opened under a tombstone past the one its row names is\n // charged too, to the same call-wide count, as `eraseSubject` charges them.\n let opens = 0;\n const charge = (): void => {\n opens += 1;\n // A refusal part-way through the search does not know what the whole search needs, so it says \"more than\"\n // and reports the bound plus one, a lower bound, as an enumeration stopped at its bound does.\n if (budget !== null && recs.length + opens > budget.maxRequests) {\n throw new BudgetExceededError(\n `subjectReport would fan out to more than ${budget.maxRequests} units, over the per-op budget: the search ` +\n `under a destroyed segment was abandoned at that point, so no exact total is available. Raise ` +\n `\\`budget.maxRequests\\`, override it per-op, or set \\`budget: false\\``,\n {\n option: 'budget.maxRequests',\n limit: budget.maxRequests,\n spent: budget.maxRequests + 1,\n },\n );\n }\n };\n // Bounded fan-out of `has()` across registered segments. Order-preserving \u21D2 deterministic result. A has()\n // fault propagates (a report that can't read a segment must fail loud, not silently under-report).\n const membership = await mapWithConcurrency(\n recs,\n options.concurrency ?? DEFAULT_ADMIN_CONCURRENCY,\n async (rec): Promise<{ tombstone: boolean; ref: SubjectSegmentRef } | null> => {\n const ref: SegmentRef = { segment: rec.segment, namespace: rec.namespace };\n if (rec.status === 'destroyed') {\n // No read resolves a destroyed row, so the id is a member of none. A cleartext destroy, or a drop whose\n // sweep left an object, leaves objects anyone with bucket access reads, which `eraseSubject` searches and\n // deletes: search them the same way, charged as it charges them.\n const deps = this.lifecycleDeps('subjectReport');\n const storage =\n budget === null\n ? deps.storage\n : new OpenChargingStorage(deps.storage, rec.currentGen, charge);\n const held = await findIdUnderTombstone(ref, id, { ...deps, storage });\n return held === null ? null : { tombstone: true, ref };\n }\n // The row this scan just listed is authoritative; the reader's snapshot may be up to `cache.genTtlMs` behind\n // it, or have no timed refresh (`genTtlMs: 0`). An access report must not lag another process's load or\n // erasure, so a segment whose snapshot is not the listed row's is forgotten before the read. The snapshot's\n // version is `<generation>:<pointerId>` (invariant 2: the number restarts at 0 once a row is purged, and is taken\n // again once its object is deleted, and every write that leads there renews the row's pointerId), so a retired\n // name loaded again is told apart too, followed by `#` and the fingerprint of the object its reader opened, which\n // is left out here. Only a segment whose resolution differs is re-resolved: one whose row has not moved, or has\n // moved only by a lease or a policy write, keeps its snapshot and costs no extra read.\n if (this.crbmSource !== undefined) {\n const held = await this.crbmSource.currentVersion(ref);\n const listed = rec.currentGen === null ? null : `${rec.currentGen}:${pointerIdOf(rec)}`;\n if (rowVersionOfLive(held) !== listed) this.engine.invalidate(ref);\n }\n return (await this.engine.has(ref, id)) ? { tombstone: false, ref } : null;\n },\n );\n const listed = membership.filter((m) => m !== null);\n const segments = listed.filter((m) => !m.tombstone).map((m) => m.ref);\n const tombstones = listed.filter((m) => m.tombstone).map((m) => m.ref);\n return { id, segments, tombstones, scannedSegments: recs.length };\n }\n\n /**\n * **Subject erasure (GDPR Art. 17): remove an id from every segment it's in, with the bit physically gone\n * from the bucket on return for each segment the ledger reports `erased: true`.** A noncurrent version, a replica\n * or a backup keeps the old object until its own lifecycle removes it.\n *\n * **Scope: one `namespace`, or `{ allNamespaces: true }`, never both** (both throws `ValidationError`, as does\n * neither). A segment loaded with no `namespace` is in no namespace you can name: only `{ allNamespaces: true }`\n * reaches it. `'_default'`, the label the export tool and the disaster-recovery samples print, and the bucket's\n * object keys use, for such a segment, is an ordinary namespace name here, and passing it scans a namespace of that name, not those segments.\n *\n * For each **registered** segment the id is a member of, `eraseIdFromSegment` rewrites the current generation\n * without the id \u2014 every chunk streamed through, one bit cleared \u2014 publishes the rewrite **fenced on the\n * generation it was derived from**, and collects the generation that held the bit. A segment whose current\n * generation does not hold the id is searched anyway, every generation in its bucket: a retained superseded one\n * can still hold it, and so can one above the pointer after a {@link CloudRoaring.rollback}, which the rollback\n * could make current again. Each holder is deleted \u2014 below the pointer by a `keep: 0` collection, above it one\n * by one, re-proved against the row first \u2014 and the generations above the pointer that never held the id stay\n * as rollback targets, but for any object no read of the segment can open, which goes whatever the id. An entry\n * says `erased: true` only once the call has listed the bucket and read what is left: **no generation of the\n * segment holds the id**. The returned per-segment record is your **erasure ledger** \u2014\n * persist it / route it to your audit sink as the proof of deletion (when you pass `audit`, an audit event is also\n * emitted per segment erased: `segment.rewrite` for a rewrite, `segment.collect` where only other generations held\n * the id and nothing was rewritten). A segment where the erasure deleted only objects no read of it can open (a first\n * load's sealed under a key no row holds) found the id in none, so the ledger does not list it; the audit sink gets\n * `segment.collect` for it with no `fromGeneration`, which is the only record of that deletion.\n *\n * Uses the backend's **own** two halves, so the membership check and the rewrite provably run\n * over the same generation. Requires the store built with a **backend** (throws\n * {@link UnsupportedError} otherwise; a pre-built `StorageChunkSource` store has no `IStorageDriver` to write\n * through; build the store on a backend instead).\n *\n * **One contract remains** (an integrator obligation the library cannot check): **do not load the segment\n * while erasing from it.** A load that lands after the rewrite carries whatever its source held, and the\n * library cannot know that source was meant to exclude the id. Quiesce loads of the affected segments for the\n * duration, or fix the source first and load after. A writer that lands *during* the rewrite is caught: the\n * rewrite's publish is refused **by the fence** \u2014 the publish lands its compare-and-swap only\n * while the pointer is still on the generation the rewrite streamed \u2014 and the entry says `note: 'superseded'`,\n * so re-run. Forward-only alone would NOT refuse it: the rewrite's number goes above everything listed near the row's own numbers,\n * so the rewrite would out-rank the newer generation and then collect it.\n *\n * A racing **erasure** is caught before that, and reported the same way. It collects with `keep: 0`, taking\n * every generation below its new pointer \u2014 the one this rewrite is streaming, and the object this rewrite\n * just wrote \u2014 so the loser can find its own inputs deleted mid-flight. That surfaces as an outcome rather than\n * an error, read off the row: a moved pointer is a `'superseded'` entry, which a re-run settles, and a segment\n * that a concurrent `dropSegment` tombstoned or a retention sweep purged is left out of the ledger. A tombstoned\n * segment is still searched: a cleartext object left under it that holds the id is deleted, with everything under\n * the tombstone, and the entry reads `erased: true`. So is a segment whose row names no generation yet (a retention\n * policy set before its first load): a first load's object that holds the id is deleted, once the row's `pointerId`\n * is renewed so that the load, if still running, is refused at its publish, and the entry reads `erased: true`. An\n * encrypted first load's object there cannot be searched, so it is deleted whatever the id: on an encrypted store,\n * an erasure of any id refuses an encrypted first load in flight that has written its object onto a segment made\n * ahead of its data. Each such delete, and each of a holder above the pointer, names the object the erasure read:\n * on a storage driver that reports `conditionalDelete`, another erasure of the id that deletes it first, followed by\n * a load that takes the number freed and publishes, does not lose that load's generation to this erasure's delete,\n * which is refused, and the entry says what the row says; on one that does not, it can.\n *\n * **Read `note` on any `erased: false` entry \u2014 the two reasons mean different things.** `'superseded'` means\n * another writer (a load, another erasure, or a rollback) moved the pointer, or replaced an object the call meant to\n * delete, mid-call, so **this call** did not erase the id. Re-run: it erases the id if it is still there, and lists\n * nothing for the segment if a racing erasure of the same id already removed it. Do not read `'superseded'` as\n * \"the id is still present\" \u2014 read it as \"not done by this call, and the re-run settles it\".\n * `` `error: \u2026` `` is a per-segment fault (caught so one segment can't discard the whole ledger) and it can land\n * on either side of the publish: if the rewrite had not published, the id is still there and a re-run erases\n * it; if the publish succeeded and only the **collection** of the old generation failed, the id is already\n * absent from every read and what remains is an object in the bucket that still contains the bit. The same\n * note, after a publish, can mean a rollback moved the pointer back onto a generation that still holds the id\n * while the collection ran \u2014 then the id is served again, and the entry says so rather than `erased: true`. A\n * re-run searches every generation in the bucket, so it rewrites or collects what is left and usually reports\n * `erased: true`; {@link SubjectErasureEntry.note} says what else a re-run can report. Re-running is otherwise safe\n * and idempotent: a segment the id is no longer in is not listed. Admin-only path;\n * `O(registered segments + superseded generations)`, no hot-path cost: a segment whose current generation lacks\n * the id is searched generation by generation, one open for each other generation in its bucket, and with the\n * keep-everything default of the `*Into` verbs that is one per generation the segment ever had. The per-op\n * `budget` is charged one unit for each segment and one for each generation opened beyond the one its row names, so\n * a fleet with long histories can exhaust it where the segment count alone would not. A generation is charged at its\n * first open only: a later open of it in the call, a retry of a failed read included, costs no more units. A segment\n * that exhausts the budget is\n * reported `erased: false` with an `error:` note, before it deletes anything (the one refusal that can come after a\n * rewrite is the last check for a generation a concurrent writer left behind), and the\n * rest of the scan continues: the call itself does not throw for it. Per-subject crypto-shred is infeasible (a subject's bit is\n * co-mingled in a shared container), so this is the single-subject erasure route; whole-segment/tenant erasure\n * is `dropSegment` / the `destroySegment`/`eraseNamespace` free functions.\n */\n async eraseSubject(\n id: number,\n options: { audit?: IAuditSink; concurrency?: number; budget?: BudgetOption } & (\n { namespace: string; allNamespaces?: false } | { allNamespaces: true; namespace?: undefined }\n ),\n ): Promise<EraseSubjectResult> {\n // An erasure in progress counts as one that moved: a call feeding on caller memory is refused from the start. One refused\n // for its options still moves the counter: conservative, so an erasure is never missed.\n this.erasureEpoch++;\n checkOptions(options, 'eraseSubject', CALL_KEYS.eraseSubject, ['allNamespaces']);\n options ??= {} as typeof options; // plain JS: no options reads as no scope, which requireScope refuses\n this.erasuresRunning++;\n try {\n return await this.eraseSubjectRun(id, options);\n } finally {\n this.erasuresRunning--;\n this.erasureEpoch++;\n }\n }\n\n private async eraseSubjectRun(\n id: number,\n options: NonNullable<Parameters<CloudRoaring['eraseSubject']>[1]>,\n ): Promise<EraseSubjectResult> {\n const deps = this.lifecycleDeps('eraseSubject');\n requireScope(options, 'eraseSubject'); // tenancy: explicit namespace, or an { allNamespaces: true } ack\n validateConcurrency(options.concurrency); // fail fast before the (possibly huge) registry scan\n const budget = resolvePerOpBudget(options.budget, this.budget); // partial override inherits the store's tightening\n splitId(id); // fail fast on a non-u32 id even when nothing is registered\n // Bounded incrementally \u2014 see subjectReport above. Art. 17 erasure is likewise reachable from ordinary\n // \"delete my account\" traffic, so the enumeration itself has to respect the budget.\n const recs = await collectWithinBudget(\n excludingReservedRows(deps.registry.list(options.namespace)),\n budget,\n 'eraseSubject',\n );\n // The scan charged one unit a segment. A segment whose current generation lacks the id is searched generation by\n // generation, and each open past the current one is charged too, to the same call-wide count. With no budget\n // there is nothing to charge and the drivers are used as they are.\n let opens = 0;\n const charge = (): void => {\n opens += 1;\n checkBudget(budget, recs.length + opens, 'eraseSubject');\n };\n // Bounded fan-out. Each segment is an independent generation, so rewriting distinct segments concurrently is\n // safe. Per-segment faults stay isolated INSIDE each task \u2014 one failure never aborts the ledger \u2014 and the\n // pool preserves input order, so the ledger stays deterministic.\n const entries = await mapWithConcurrency(\n recs,\n options.concurrency ?? DEFAULT_ADMIN_CONCURRENCY,\n async (rec): Promise<SubjectErasureEntry | null> => {\n const ref: SegmentRef = { segment: rec.segment, namespace: rec.namespace };\n try {\n // The rewrite does its own membership check against the CURRENT registry generation \u2014 not the\n // engine's cached view, which may lag a load by up to `cache.genTtlMs`. An Art. 17 erasure must never\n // skip a segment because a read cache hasn't caught up yet.\n const result = await eraseIdFromSegment(\n ref,\n id,\n budget === null\n ? deps\n : { ...deps, storage: new OpenChargingStorage(deps.storage, rec.currentGen, charge) },\n { audit: options.audit },\n );\n if (result.reason === 'not-member' || result.reason === 'absent') return null;\n if (result.reason === 'no-generation') return null; // a row with no data yet holds no id\n if (result.reason === 'destroyed') return null;\n return {\n segment: rec.segment,\n namespace: rec.namespace,\n erased: result.erased,\n fromGeneration: result.fromGeneration,\n generation: result.generation,\n note: result.erased ? undefined : result.reason,\n };\n } catch (err) {\n return {\n segment: rec.segment,\n namespace: rec.namespace,\n erased: false,\n note: `error: ${errorKind(err) ?? (err instanceof Error ? err.name : 'Error')}: ${\n err instanceof Error ? err.message : String(err)\n }`, // the class lets a note be matched to the guide's table\n };\n } finally {\n // Whatever the outcome, this process's own view of the segment is now suspect: a landed rewrite\n // deleted the generation our caches were built on, and a refused one means somebody else's did.\n // Without this the erasing store keeps answering `true` for the id it just reported erased \u2014 out of\n // RAM, with no storage read for any control to intercept. `finally`, not the happy path: a rewrite\n // that published and then THREW on its collect is precisely the case where this view is stale, and\n // it is reachable from an ordinary retirement landing mid-call.\n //\n // Swallowed, because a `finally` that throws replaces the outcome above it: it would escape the\n // per-segment catch, abort the whole ledger, and discard the error it was masking \u2014 breaking the\n // isolation this fan-out promises. Dropping cache entries cannot fail today; this keeps that from\n // becoming a whole-run failure if it ever can.\n try {\n this.engine.invalidate(ref);\n } catch {\n /* best-effort: never let cache bookkeeping discard a segment's result */\n }\n }\n },\n );\n const erasedFrom = entries.filter((e): e is SubjectErasureEntry => e !== null);\n return { id, erasedFrom, scannedSegments: recs.length };\n }\n\n /**\n * Every generation still in the bucket for this segment, ascending, with the current one marked.\n *\n * What the bucket holds, not what the segment has ever been \u2014 collection deletes superseded objects, so this is\n * the grace window plus whatever has not been collected yet. It is the set {@link CloudRoaring.rollback} can\n * choose from, which is the reason to look at it. One registry read and one listing; it does not open the objects.\n * Each entry says whether the row knows the generation (`known`): a known generation needs no `allowUnknown`; an unknown\n * one does, except below a row's pointer when the row has no usable record or the target is older than a full one reaches.\n * No entry is `current` on a destroyed segment: its row keeps the pointer it had, but no read resolves through it.\n *\n * Needs a backend.\n */\n async generations(ref: SegmentRef): Promise<GenerationEntry[]> {\n ref = validateRef(ref, 'generations');\n return listGenerations(ref, this.lifecycleDeps('generations'));\n }\n\n /**\n * Whether a read of this segment would find anything \u2014 the \"do I already have this?\" question, as one\n * registry point read.\n *\n * There is no `create` in this library: {@link CloudRoaring.segment} is a validated address and does no I/O,\n * so naming a segment can never collide with an existing one. A segment starts existing when something is\n * first loaded into it, and this is how you ask whether that has happened.\n *\n * **Not the same as `count() > 0`.** A segment loaded with no ids exists and counts zero. Distinguishing\n * \"never loaded\" from \"loaded, and genuinely empty\" is the thing `count()` cannot do and the reason this\n * exists. It is `false` for a segment whose row was minted ahead of its first load (by `setRetention`) and\n * for a `destroyed` tombstone, because a read answers empty in both cases.\n *\n * One state answers `true` where a read still gives you nothing: a torn restore (a live pointer whose object\n * was deleted) makes reads of the object *throw* rather than answer empty, while a cold `count()` answers the number\n * its row records \u2014 `checkConsistency` is the call for that.\n *\n * Not a lock: the answer can change the moment it returns. If it has to hold, use the fence built for that \u2014\n * `load`'s `guard`, or `expectFrom`/`expectToken` on a publish. Needs a storage backend.\n *\n * ```ts\n * if (!(await store.exists({ segment: 'users' }))) {\n * await store.load({ segment: 'users' }, idsFromUpstream);\n * }\n * ```\n */\n async exists(ref: SegmentRef): Promise<boolean> {\n ref = validateRef(ref, 'exists');\n return segmentExists(ref, this.requireRegistry('exists'));\n }\n\n /**\n * Every segment the registry knows about, streamed \u2014 optionally scoped to one namespace.\n *\n * The registry is already the list of your segments, which is why you should not keep a second one beside it:\n * a hand-maintained list is a source of truth that drifts from this one the first time a load fails halfway.\n *\n * **An admin/discovery call, not a request-path one.** This is the registry's own enumeration \u2014 a paged\n * LIST over the `registry/` prefix \u2014 so its cost grows with the size of the fleet rather than with what you\n * are looking for.\n *\n * Scoping to a namespace narrows the LIST prefix, so it really is the difference between reading one tenant\n * and reading all of them.\n *\n * It streams, and stopping the iteration stops the scan. It reads the registry directly and is not retried: a\n * transient fault part-way through ends the loop with that error, and calling `segments()` again scans from the\n * start.\n *\n * Yields `destroyed` tombstones and rows with `currentGen: null`, because a filtered enumeration that looks\n * complete is worse than an honest one \u2014 filter on `status`/`currentGen` yourself, or ask\n * {@link CloudRoaring.exists} the narrower question. Needs a storage backend.\n *\n * ```ts\n * for await (const s of store.segments({ namespace: 'active-daily' })) {\n * console.log(s.segment, s.currentGen, s.status);\n * }\n * ```\n */\n segments(options: { namespace?: string } = {}): AsyncIterable<SegmentInfo> {\n checkOptions(options, 'segments', CALL_KEYS.segments);\n options ??= {};\n if (options.namespace !== undefined) {\n // Synchronously, at the call, where `listSegments` (an async generator, which refuses the reserved\n // namespace too for a direct caller) would only throw at the first iteration.\n validateSegmentRef({ segment: 'x', namespace: options.namespace });\n refuseReservedNamespace(options.namespace);\n }\n return listSegments(this.requireRegistry('segments'), options);\n }\n\n /**\n * Move this segment's pointer **back** to a generation still in the bucket \u2014 the one write in the library that\n * is not forward-only.\n *\n * Forward-only is right for a writer: a load whose ids came from upstream loses nothing by being out-raced, and\n * letting it regress would let a slow loader silently undo a fast one. It is wrong for an operator who has\n * looked at the segment, decided the current generation is wrong, and knows which one they want. So this is\n * reachable only by asking for it by name \u2014 no sweep, retry or reconciliation calls it \u2014 and it is audited\n * (`segment.rollback`), because every other pointer move can be reconstructed from \"a load happened\" and this\n * one cannot.\n *\n * It refuses rather than guesses. The row records, in `knownGens`, the generations its loads and rollbacks made\n * current, each with the footer checksum of its object, and a rollback moves only onto one of those: a generation the\n * row does not know (a load that wrote its object and died before the publish, a refused load's object, an object\n * sealed under a key no row holds, a load published after the point a registry was restored to) throws\n * {@link ValidationError} before any request to storage, and a known one whose object carries another checksum than\n * the recorded one throws {@link IntegrityError}, with or without a keystore, since the footer is in the clear. A\n * generation not in the bucket (collected, or never written) throws `NotFoundError` naming what *is* available, a\n * destroyed segment (crypto-shredded, destroyed in the clear or dropped) throws {@link ValidationError}, because no\n * generation resolves through a destroyed row, and a target that is cleartext under an encrypted segment, or\n * encrypted under a cleartext one, throws {@link IntegrityError} from\n * one tail read of it, because every read would refuse it. Rolling to the generation already current is a no-op that\n * reports itself, once one footer read finds its object in the bucket (and the one the row recorded); when the object is\n * gone it throws `NotFoundError` naming what is.\n *\n * The same tail read (and a range read when the target's index is longer than it) gives the target's id count and\n * metadata, which the rollback writes into the row with the pointer, so a reader that sees the target as current sees\n * what describes it. The store's keystore opens an encrypted target for this; without it, or when it cannot open the\n * key (it holds none of the key's KEKs, one it holds does not unwrap it, or it throws `TransientError` or times out\n * as `AbortSignal.timeout()` and the AWS SDK report a timeout), a rollback onto a known generation still happens,\n * opening nothing, and the row carries no summary of the target. Any other failure of the keystore is\n * thrown. A swap of the pointer that gets no answer, or that meets a conflict, is settled by reading the row: one\n * that landed, the row's pointer being at the target over a write this call sent (the write token, on a registry that\n * reports them), is checked as any is, and otherwise its `TransientError` is thrown, or a `WriteConflictError` after\n * a conflict, with no move recorded. After the swap the target's\n * footer is read once more, and the pointer put back if the object is gone or is another.\n *\n * It deletes nothing. The generations above the new pointer stay put \u2014 which is what makes this reversible \u2014\n * and are then *above* `currentGen`, where collection never looks, and still known to the row, so rolling forward onto\n * one needs no flag. They remain until loads pass them (the first load whose\n * number one of them holds numbers above them all, those within 1,024 of what the row names and any contiguous run\n * touching them, and collection then keeps `keep` of what is below its pointer, the\n * generation that load superseded first), {@link CloudRoaring.dropSegment}\n * deletes them, or {@link CloudRoaring.eraseSubject} does: all of those present when it rewrites, and, when the\n * current generation does not hold the id, only those holding it and any no read of the segment can open, whatever\n * the id. An operator who has just undone a bad load should not have the\n * evidence collected out from under them, while a rollback target that still holds erased data would make the\n * erasure undoable.\n *\n * `{ allowUnknown: true }` moves onto a present object the row does not vouch for, or one whose checksum differs from\n * the recorded one, as long as it is the segment's kind of object, opens, and names the generation, and records it as\n * known (over a usable record; a row with none stays without one). On an encrypted segment, outside the two cases the pointer alone decides (below), it also needs the key: with no keystore, or one that holds none of the key's KEKs or\n * one that does not unwrap it, it is refused with `KeyUnavailableError` before the target is read, since an object\n * sealed under a key no row holds passes every check that needs no key, and a key service that did not answer in\n * time is thrown as `TransientError`, to retry. Every move the row did not vouch for is audited with `unknown: true`.\n * Two cases are decided by the pointer alone: a target below it needs no flag, no key and no checksum check, and the\n * move is audited the same way. They are a row with no usable `knownGens` (a registry that drops the field, or a pointer\n * moved by hand), and a target numbered below the bound of a full record (128 entries or more, leased ones included),\n * which is its least recently current entry that no lease names (an `*Into` destination keeps every generation in the\n * bucket and names only the newest 128). A generation a publish with a smaller `keep` no longer names but that stays in\n * the bucket (a lease spared it, or its delete failed) needs `allowUnknown` until a later listing collects it.\n *\n * Needs a backend.\n */\n async rollback(\n ref: SegmentRef,\n toGeneration: number,\n options: { audit?: IAuditSink; allowUnknown?: boolean } = {},\n ): Promise<RollbackResult> {\n ref = validateRef(ref, 'rollback');\n checkOptions(options, 'rollback', CALL_KEYS.rollback, ['allowUnknown']);\n options ??= {};\n const deps = this.lifecycleDeps('rollback');\n try {\n return await rollbackSegment(ref, toGeneration, deps, options);\n } finally {\n // The pointer moved under this store's cached view \u2014 and unlike a load, it moved to content the caches may\n // still be holding from before. Drop it either way.\n this.engine.invalidate(ref);\n }\n }\n\n /**\n * **Replace this segment's contents** with `input`, as one new immutable generation, and make it current.\n *\n * `input` is ids (any sync or async iterable of integers in `[0, 2^32)`), or a whole bitmap: `{ bitmap }`, anything\n * with `serialize('portable')` such as `roaring`'s `RoaringBitmap32`, or `{ serialized }`, portable Roaring bytes.\n * A bitmap is checked (size cap, structure, safe deserializer) before the first request, written from its own\n * containers with no per-id work, and gives the generation chunk for chunk what its ids would. An\n * iterable with a `serialize` method (a `RoaringBitmap32`, another copy's bitmap, or a `RoaringBitmap`\n * of this package) passed as ids loads as `{ bitmap }` and is not iterated. A `Uint8Array` or `Buffer` passed as ids is\n * refused with `ValidationError`, since each byte would load as an id, even when it has a `serialize` of its own:\n * pass bytes as `{ serialized }`.\n *\n * Ids are held whole in memory before the object is written: the generation's bitmaps and a buffer of up to about 28\n * MB. Ids that already ascend can be loaded with `sorted: true` instead, which writes them one chunk at a time while\n * the object uploads, so the load holds one chunk and the writer's index (up to about 7 MiB, about 8 MiB for an\n * encrypted segment, derived), whatever the segment's size, and writes the same object ({@link LoadOptions.sorted}).\n *\n * The whole write path in one call: take the next generation number, write the object, check the result is\n * plausible, move the pointer, collect what the move superseded. Composed by hand those are four functions and\n * the one that gets left out is the last, so segments quietly accumulate superseded generations nobody pays\n * attention to and everybody pays for.\n *\n * ```ts\n * const r = await store.load({ segment: 'audience:active' }, idsFromWarehouse, {\n * guard: { minRetained: 0.5 }, // refuse a load that would drop more than half the segment\n * });\n * if (!r.published) console.warn(`load refused: ${r.reason}`);\n * ```\n *\n * `metadata` attaches a small record of your own to the generation: a flat object of string keys and string or finite\n * number values, at most 1,024 bytes as canonical JSON and no key over 128 bytes. A record that breaks a rule throws\n * `ValidationError` before the load makes a request. It is copied when you call, stored in the generation's object,\n * and written to the segment's row with the generation's id count by the write that moves the pointer, so a reader\n * that sees the generation as current sees its metadata. It never changes after that, a rollback puts the target's own\n * back, and an erasure carries it over without scanning it, so keep a subject's id out of it. It is sealed under the\n * segment's key on an encrypted segment.\n *\n * **A load REPLACES.** Whatever the stream contains is what the segment contains afterwards, so an upstream\n * query that returns fewer rows than usual is a shrink nobody asked for and an empty one is a wipe \u2014 both\n * reported as a successful write, because at the storage layer they are one. That is what `guard` and the\n * default empty refusal are for, and why they run **between** the write and the publish: the only moment where\n * the new content is known and the old one is still authoritative.\n *\n * **Branch on `published`.** A refusal is a normal outcome, not an exception \u2014 `published: false` with a\n * `reason`, in the same shape as a success \u2014 so a discarded result is a load that silently did nothing, and\n * with the empty guard on by default this verb refuses more readily than any other. Note the sibling `*Into`\n * verbs *throw* on the same superseded condition rather than reporting it; this one follows\n * `eraseIdFromSegment` instead, because three of its four refusals are expected guard outcomes rather than\n * faults.\n *\n * `'superseded'` means another writer got there first: another load took the same generation number, so this\n * one wrote nothing (`size: 0`), or the segment's registry row changed while the load was writing \u2014 another load\n * published, a retention change, a rollback or an erasure wrote the row, or the row was deleted.\n *\n * A refused load deletes the object it wrote before returning \u2014 it sits above `currentGen`, where generation\n * collection deliberately never looks \u2014 but only while the segment's registry row is unchanged (or differs only in\n * its leases), `destroyed` or gone, or has key material when the load wrote cleartext, which has no place in an\n * encrypted segment's bucket. Under a row that is gone or keyed, one read of the object's footer must match what the\n * load wrote first. Once another write has otherwise changed the row, the generation number it holds may name another\n * writer's object, and the row does not say whether that write took this number, so it leaves the orphan rather than risk\n * deleting live data. A publish never adds the orphan to the row's list, and a load's listing deletes it once a\n * generation above it is current, unless the row's list names it; where the row records none (after a rollback, or\n * with a `keep` above 64), that listing's window can keep it and, at a `keep` up to 64, record it, and the publishes\n * after carry it until the window pushes it out. Until it goes, a rollback onto it is refused unless `allowUnknown` is passed, since the list never names it (a list seeded\n * over a row with none can); with the override it publishes what no load published.\n *\n * **Collection is by name at any `keep` up to 64.** The segment's row records the generations a load keeps, so a load\n * that found nothing above the pointer deletes the generations its publish pushed out of the window and lists\n * nothing. It lists the segment's objects on every sixteenth generation, and on any load that met an object above the\n * pointer or whose check found the current generation's object gone, to take what the name-only passes leave, such as\n * an object a crashed load left below the pointer. A `keep` above 64 records no list and lists on every load, and so\n * does the first load of a row that records none, which then records it. {@link LoadResult.collected} then names\n * what the pass deleted by name, and one name may have been gone already.\n *\n * `input` cannot be a stream of this library (`iterate`, `everyNth`, `intersect`, `union`, `andNot`, as returned) that\n * read the segment being loaded, from this store or one built over the same registry driver: a load publishes over\n * whatever the segment is by then, so it would replace another writer's newer load with a result built from an older\n * one, and it throws {@link ValidationError}. Ids read from another store over another backend load as any ids do.\n * Two separate store instances over one bucket cannot be told apart, so this does not cover them; this release has no\n * fenced in-place update, so write the result into a new segment and point readers at it.\n *\n * What it **throws** for is a fault rather than an outcome: invalid options or ids, and a destroyed\n * segment (`ValidationError`); a key the keystore cannot provide (`KeyUnavailableError`); a current generation\n * that will not open when a guard has to read its size, which it does only when the row has no usable summary of it\n * (`IntegrityError`); a driver failure; and a fault in the collection's own reads, listing or deletes, or in the write\n * that records the window (anything but a lost race). A collection fault can be raised **after** the publish already\n * landed, so a throw does not by itself mean the load did not take effect \u2014 re-read the pointer rather than assuming.\n * A collection, by name or by listing, that finds another writer has moved the row since the publish (a load, a\n * rollback, a purge) stops and returns what it deleted in `collected`: a load that took effect does not throw for a\n * race it won.\n *\n * **A `TransientError` from the registry write can leave the publish unsettled, and deletes nothing.** The\n * generation's object is sent again after a throttle where the backend allows it (a write id tells a first send\n * that landed from another writer's object), and a driver sends each registry write once. When that write ends\n * without an answer, the load reads the row: its own landed write is `published: true`, a row that has moved on is\n * `superseded`, and a row still as the write found it gets a fresh compare-and-swap from the version just read, at\n * most three times, after a wait on the store's clock. Still unanswered, the load throws the registry's `TransientError` and keeps its object, which\n * a write may still point the row at. Re-run the load: it numbers past that object, and collection removes it once a\n * generation above it is current. A `'superseded'` refusal that follows an unanswered write sets `unanswered: true`\n * on its audit event: that write may have landed, and the generation been current for a while, first.\n *\n * Needs a backend (throws {@link UnsupportedError} otherwise).\n */\n async load(ref: SegmentRef, input: LoadInput, options: LoadOptions = {}): Promise<LoadResult> {\n ref = validateRef(ref, 'load');\n checkOptions(options, 'load', CALL_KEYS.load, ['allowEmpty', 'sorted']);\n if (typeof input === 'object' && input !== null) {\n const reads = STREAM_SOURCES.get(input);\n // The same store, or one built over the same registry driver object. Two stores over two backends copy freely;\n // two separate store instances over one bucket cannot be told apart by their registry driver and are not covered.\n const sameBackend =\n reads !== undefined &&\n (reads.origin === this.origin ||\n (this.registry !== undefined && REGISTRY_OF.get(reads.origin) === this.registry));\n if (sameBackend && reads.keys.includes(segmentKey(ref))) {\n const named = ref.namespace === undefined ? ref.segment : `${ref.namespace}/${ref.segment}`;\n throw new ValidationError(\n `load: the ids come from a read of the segment \"${named}\" that is being loaded, and a load publishes over ` +\n \"whatever the segment is by then, so another process's newer load of it can be replaced by a result built \" +\n 'from the one before, with no conflict reported. This release has no fenced in-place update: write the ' +\n 'result into a new segment and point readers at it',\n );\n }\n }\n options ??= {};\n const deps = this.lifecycleDeps('load');\n try {\n return await loadSegment(ref, bitmapAsLoadInput(input), deps, options);\n } finally {\n // This store's view of the segment is now behind whatever just happened \u2014 a published load superseded the\n // generation the caches were built on, and a throw can still have published before failing its collect.\n // `finally`, so the one path where the view is most likely stale is not the one path that skips the drop.\n this.engine.invalidate(ref);\n }\n }\n\n /**\n * **Dispose of a segment \u2014 tombstone it, then delete its storage objects.** It cannot be undone through the\n * library (a restore from the registry's and the bucket's versions or backups can).\n *\n * The operation a rolling window needs: `destroySegment` crypto-shreds (it removes the key from the segment's\n * current registry row, so the bytes are unreadable everywhere, backups included, once no retained copy of the row\n * holds the key or every KEK that wrapped it is destroyed; the objects still sit in your bucket and are still\n * billed, and it requires encryption), while this one removes the storage and works on a cleartext segment. On an\n * encrypted segment it does both.\n *\n * Pass `{ dryRun: true }` first \u2014 it reports the generations it *would* delete and changes nothing. That\n * matters more than the `confirmSegment` guard for anything automated, because in a loop the guard is the same\n * variable twice.\n *\n * ```ts\n * for (const day of expiredDays) {\n * // The family in the namespace, the date in the segment \u2014 `registry.list(namespace)` then enumerates\n * // exactly this family's buckets, which a flat `active:2026-08-01` name cannot do without string-matching.\n * const ref = { namespace: 'active-daily', segment: day };\n * await store.dropSegment(ref, { confirmSegment: ref.segment });\n * }\n * ```\n *\n * **Omitting the namespace addresses a different segment and is a silent no-op** \u2014 you get\n * `{ dropped: false, reason: 'absent' }`, not a throw, so a retention loop with that mistake deletes nothing\n * forever and quietly. Branch on `dropped`, and treat `reason: 'absent'` as the alert.\n *\n * **Inspect `generationsRemaining`.** Empty is the normal outcome; non-empty means the storage was NOT fully\n * reclaimed and the drop should be re-run. A load that had read the segment before the tombstone landed, whether it\n * was writing or still consuming its ids, can still write its object, so a single sweep can miss it \u2014 this call\n * re-sweeps and then reports whatever it still could not remove rather than returning a result that looks like a\n * clean drop. A load that writes after the last sweep deletes its own object once its publish is refused; only one\n * whose process stops in between, or whose publish fails without a definite answer (a lost response, a timeout),\n * leaves it, for a re-run of the drop.\n *\n * Reads become empty within `cache.genTtlMs` (default 2 s), not instantly: a store that had already read this\n * segment may answer from its cached generation + cached chunks until that window lapses, or, while the registry\n * cannot be read because of a transient fault, until a retry 500 ms apart reaches it again. A reader that never\n * touched it sees empty at once. **That bound needs a registry and `cache.genTtlMs > 0`.** A store with no registry\n * (a bare `IStorageDriver`), with `cache.genTtlMs: 0`, or on a `StorageChunkSource` of your own, has no timed\n * refresh. It notices the drop only when a read has to fetch\n * from a deleted generation or its reader cache evicts the segment, and until then a chunk it has cached\n * answers without reaching storage, so it can keep answering `true` for a dropped segment indefinitely. Tell\n * it with {@link invalidate}, or restart it.\n *\n * Needs the store built with a **backend** (throws {@link UnsupportedError} otherwise),\n * because it has to enumerate and delete generations \u2014 a pre-built `StorageChunkSource` only reads.\n */\n async dropSegment(\n ref: SegmentRef,\n options: { confirmSegment: string; dryRun?: boolean; audit?: IAuditSink },\n ): Promise<DropResult> {\n ref = validateRef(ref, 'dropSegment');\n if (options === undefined || options === null) {\n throw new ValidationError('dropSegment: options { confirmSegment } are required');\n }\n checkOptions(options, 'dropSegment', CALL_KEYS.dropSegment, ['dryRun']);\n const deps = this.lifecycleDeps('dropSegment');\n try {\n return await dropSegment(\n ref,\n { registry: deps.registry, storage: deps.storage, clock: deps.clock, rng: deps.rng },\n options,\n );\n } finally {\n if (options.dryRun !== true) this.engine.invalidate(ref);\n }\n }\n\n /**\n * **Record when this segment becomes eligible for retirement.** One policy write, plus a best-effort write of its\n * due-index pointer (and removal of the old pointer when the expiry day moves); no data is deleted here, and\n * nothing starts running. `retireExpired` is what acts on the policy, and **you** decide when that runs \u2014\n * an EventBridge rule, a CronJob, a queue consumer, whatever your deployment already has. This library starts\n * no background thread (it has to work identically in a Lambda, an edge isolate and a long-lived server).\n *\n * `expiresAt` is an **absolute epoch-ms you compute**, not a duration the library derives. A relative TTL would\n * have to be anchored to something the library knows \u2014 `updatedAt`, or the current generation \u2014 and every load\n * rewrites both, so \"expire 30 days after the last write\" would keep a busy daily bucket alive forever\n * precisely because it is being reloaded.\n *\n * ```ts\n * const DAY = 86_400_000;\n * const ref = { namespace: 'active-daily', segment: '2026-08-05' };\n * await store.setRetention(ref, { expiresAt: Date.now() + 30 * DAY });\n * ```\n *\n * **Works before the first load**: a segment with no registry row yet gets one (`createdRow: true` in the\n * result) with **no Storage generation**, so the policy is recorded ahead of the data and the segment is already\n * enumerable by the sweep; the first load then publishes onto that row.\n *\n * A value in the past is legal and means \"eligible on the next sweep\" \u2014 backfilling a policy onto existing\n * buckets is normal. A value below `1_000_000_000_000` (2001-09-09) is rejected: it is almost certainly epoch\n * **seconds**, which would read as long-expired and retire the segment on the next pass. Needs a storage\n * backend (throws {@link UnsupportedError} otherwise), and refuses a destroyed segment.\n */\n async setRetention(ref: SegmentRef, policy: RetentionPolicy): Promise<SetRetentionResult> {\n ref = validateRef(ref, 'setRetention');\n return setSegmentRetention(\n ref,\n { registry: this.requireRegistry('setRetention'), clock: this.clock, rng: this.rng },\n policy,\n );\n }\n\n /**\n * **The stored retention policy**, or `null` if the segment has none (or has no registry row, or is a\n * tombstone). Returns the string `'invalid'` for a row whose `expiresAt` is present but unusable \u2014 a\n * hand-edited row, or one from a restore \u2014 so a malformed policy is visible rather than silently reading as\n * \"never expires\" on a segment someone believes is expiring.\n */\n async getRetention(ref: SegmentRef): Promise<RetentionPolicy | null | 'invalid'> {\n ref = validateRef(ref, 'getRetention');\n return getSegmentRetention(ref, { registry: this.requireRegistry('getRetention') });\n }\n\n /**\n * **Cancel a segment's expiry** so no sweep retires it. Returns whether this call removed a policy (`false`\n * when there was none, and also when a write that got no answer cannot be shown to be this call's and the\n * row holds no expiry: the expiry is gone either way, and its due-index pointer is removed. A later write that set an\n * expiry is cleared too, and the answer is `true`). A separate verb from `setRetention` on purpose: \"never expire\" as a magic value passed\n * to the setter is how a typo becomes a deletion.\n */\n async clearRetention(ref: SegmentRef): Promise<boolean> {\n ref = validateRef(ref, 'clearRetention');\n return clearSegmentRetention(ref, {\n registry: this.requireRegistry('clearRetention'),\n clock: this.clock,\n rng: this.rng,\n });\n }\n\n /**\n * **Run the retention sweep: retire every segment whose `expiresAt` has passed.** This is the call that acts on\n * the policies `setRetention` records \u2014 and it is a **call, not a daemon**. Nothing schedules it; you run it from\n * whatever heartbeat your deployment already has (an EventBridge rule, a Kubernetes CronJob, a queue consumer,\n * the job that runs your loads). A library that started a timer would behave differently in a Lambda, an edge\n * isolate and a long-lived server, which is worse than not having one.\n *\n * Each retirement goes through `dropSegment`, so the registry \u2192 Storage ordering, the re-sweep for an object a\n * load was still writing, and the `generationsRemaining` report all come from one implementation rather than\n * two.\n *\n * ```ts\n * // In your scheduled handler. Start with a preview in a new deployment.\n * const preview = await store.retireExpired({ namespace: 'active-daily', dryRun: true });\n * console.log(`would retire ${preview.wouldRetire} of ${preview.scanned} (limited: ${preview.limited})`);\n *\n * const swept = await store.retireExpired({ namespace: 'active-daily' });\n * for (const e of swept.entries) {\n * // invalid-policy / policy-changed / tombstone-not-empty / failed: \u2026\n * if (e.action === 'skipped') console.warn(`${e.segment}: ${e.reason}`);\n * if (e.action === 'retired' && e.result.generationsRemaining.length > 0) {\n * console.warn(`${e.segment}: storage not fully reclaimed \u2014 re-run`);\n * }\n * }\n * if (swept.limited) scheduleAnotherPassSoon(); // more work (retirements or purges) remains\n * ```\n *\n * **Read the ledger.** A per-segment *fault* is an entry, not an exception \u2014 a throw from the middle of a fleet\n * sweep would leave the caller unable to say which segments were retired, having already retired some. (A bad\n * argument does throw, and so does a fleet larger than `maxScanSegments`.) `limited: true` means the per-cycle\n * `limit` (default 100) cut the pass short, and more work (retirements or purges) remains: `limit` caps the\n * retirements and tombstone purges one call attempts, together, and a segment it deferred gets no entry. That cap\n * is charged on **attempts**, not successes, which is what makes it a real bound: `dropSegment` writes the\n * tombstone before sweeping Storage, so a fault in the Storage phase is a segment that is already retired. Retirements are sequential, so `limit` is a\n * wall-clock knob too, and `retired` counts deletions only \u2014 a dry run reports `wouldRetire` instead, so a\n * dashboard summing `retired` can never show a phantom deletion.\n *\n * **Check `purgeFaults`.** A delete the registry refuses for a reason other than a lost race (a policy that denies\n * delete, an Azure blob with a snapshot, a raw provider error), whether of a tombstone or of a due-index pointer, is\n * counted there, with the first one's reason in `firstPurgeFault`. A refused purge is `skipped` in the ledger, is not\n * charged to `limit`, so it never holds the retirements behind it, and purging stops for the rest of the call after\n * three refused purges in a row (a purge that succeeds starts the count again).\n *\n * It also **deletes the tombstone rows its own past retirements left**, after `tombstoneGraceMs` (default 24 h; at least one hour, else `ValidationError`)\n * and only once that segment's Storage generations are provably gone \u2014 collecting a straggler generation itself\n * first, since nothing else runs that collection on its own for a tombstoned segment (an erasure collects there\n * only\n * when an object holds its id, and a re-run drop sweeps it). Attribution is a **positive marker the sweep\n * stamps on its own retirements**, not an inference from \"destroyed + an expired policy\": a crypto-shred leaves\n * `retention` untouched, so setting a policy and then honouring a right-to-erasure request mid-window produces\n * exactly that row, and deleting it would destroy the Art. 17 attestation and un-fence the name. By default a\n * segment that held nothing has its row deleted in the pass that retires it, since that row would only fence the name.\n * Pass `purgeTombstones: false` to keep every tombstone, that row included. On a backend whose registry reports\n * `conditionalDelete` (AWS S3, Azure Blob, the local filesystem and memory, by default; GCS when you set `conditionalDelete: true`)\n * the purge removes the row from the bucket for good, by a delete the store applies only to the version it judged,\n * so a full sweep reads what is live or inside its grace rather than every name a namespace ever held; elsewhere it\n * leaves a tombstone. Each retirement files a pointer in the due index\n * under the day its tombstone's grace ends, so `scan: 'index'` purges as well as retires.\n *\n * Needs the store built with a **backend** (throws {@link UnsupportedError} otherwise),\n * because retiring a segment deletes its storage objects. `now` defaults to the store's clock.\n */\n async retireExpired(\n options: Omit<RetireExpiredOptions, 'now'> & { now?: number } = {},\n ): Promise<RetireExpiredResult> {\n checkOptions(options, 'retireExpired', CALL_KEYS.retireExpired, ['dryRun', 'purgeTombstones']);\n const opts = picked(options, CALL_KEYS.retireExpired);\n const deps = this.lifecycleDeps('retireExpired');\n const result = await retireExpired(\n { registry: deps.registry, storage: deps.storage, clock: this.clock, rng: this.rng },\n { ...opts, now: opts.now === undefined ? this.clock.now() : opts.now },\n );\n // A retirement tombstones and reclaims segments this store may already have resolved. `dryRun` changes\n // nothing, so it invalidates nothing.\n if (opts.dryRun !== true) {\n for (const entry of result.entries) {\n this.engine.invalidate({ segment: entry.segment, namespace: entry.namespace });\n }\n }\n return result;\n }\n\n /**\n * **Forget everything this store has cached about a segment.** Use it after destroying or retiring a segment\n * through a path this store did not perform itself.\n *\n * A store keeps two layers of derived state \u2014 a resolved snapshot per segment (an open `.crbm` reader, plus\n * the DEK it unwrapped) and decoded chunks keyed by generation. Both are built for one event: **a publish\n * that advances `currentGen`**, which the snapshot TTL notices and the generation-keyed cache misses on.\n * Neither notices an event that *destroys* what they were derived from.\n *\n * The store's own writes handle themselves: `load`, `rollback`, `eraseSubject`, `dropSegment` and `retireExpired`\n * here, and a segment's `*Into` verbs, invalidate what they touch. This method is for the cases they cannot see:\n *\n * - **`destroySegment` / `eraseNamespace`**, which are free functions over raw drivers rather than methods\n * here, so a crypto-shred performed beside this store invalidates nothing in it. It keeps its open reader and\n * the unwrapped DEK, and decrypts with them, chunks it had never fetched before the shred included, until its\n * snapshot re-resolves: within `cache.genTtlMs` when the store has a registry and a `genTtlMs` above 0, and\n * otherwise only when its caches let the segment go or a read has to fetch from a generation a sweep collected.\n * A pin on a store with a timed refresh fails within `cache.genTtlMs` once its segment is destroyed or its\n * generation erased; on a store with none it answers until it is told or both caches let it go.\n * - **Another process.** Erasing on one box invalidates nothing on the others; each store bounds its own\n * staleness by `cache.genTtlMs`, and a store with no registry (a bare `IStorageDriver`), with\n * `cache.genTtlMs: 0`, or on a `StorageChunkSource` of your own has no bound at all: it converges only when a read happens to miss its caches. If a compliance deadline depends on every\n * reader converging, you need to signal them \u2014 this is the call to make when your own fan-out delivers.\n *\n * It also forgets any replacement this store found of a pin's object, so once it is called after a restore puts that\n * object back, the pin reads it again. A read of the segment already running on this store, a pin's and a combine's\n * with a pinned operand included, caches nothing more of what it began reading before the call, and a pinned one\n * opens its object again before its next chunk, failing with `NotFoundError` if the object is gone or replaced, or\n * its row is gone or destroyed.\n *\n * Synchronous, best-effort, and safe to call for a segment this store has never read.\n *\n * ```ts\n * await destroySegment(ref, { registry: backend.registry }, { confirmSegment: ref.segment });\n * store.invalidate(ref); // this process\n * await bus.publish('cloudbitmaps.invalidate', ref); // and every other one\n * ```\n */\n invalidate(ref: SegmentRef): void {\n ref = validateRef(ref, 'invalidate');\n refuseReservedNamespace(ref.namespace);\n this.engine.invalidate(ref);\n }\n\n /**\n * Build a handle held at the generation `ref` resolves to right now. See {@link Segment.pin}.\n *\n * The pinned handle gets its own engine but **shares the store's chunk cache**, under keys of its own: the\n * pinned view reports the version captured at pin time, marked as a pin's, so its decoded chunks are never\n * those of a live read that fetched across a publish (see {@link PinnedStorageChunkSource.currentVersion}). It\n * shares the store engine's invalidations too, so the store's writes reach a pinned read already running.\n */\n private async pinSegment(ref: SegmentRef, leaseUntil?: number, named?: PinAt): Promise<Segment> {\n const crbm = this.crbmSource;\n if (crbm === undefined) {\n throw new UnsupportedError(\n 'pin() needs the `.crbm` storage source \u2014 pass a backend or a raw IStorageDriver as `storage` (the store ' +\n 'cannot pin a StorageChunkSource of your own)',\n );\n }\n // A lease is taken between the pin's row read and its open (see `pinGeneration`). The holder is drawn once, here,\n // outside the retries, so a write that landed unseen is found by its holder when the pin is run again.\n let hold: LeaseHold | undefined;\n let take: PinLease | undefined;\n if (leaseUntil !== undefined) {\n const registry = this.requireRegistry('pin({ leaseUntil })');\n if (registry.capabilities().canWrite === false) {\n throw new UnsupportedError(\n \"pin({ leaseUntil }) needs a registry that can write a row, and this store's cannot in this runtime\",\n );\n }\n const holder = this.mintHolder();\n const deps = { registry, clock: this.clock, rng: this.rng };\n // A pin takes the generation current when its row is read, which must still be current when the write lands; a\n // `pinAt` takes the one it names, which only has to be published.\n const generationOf = (row: { currentGen: number | null }): number =>\n named?.generation ?? (row.currentGen as number);\n hold = {\n holder,\n until: leaseUntil,\n released: false,\n done: false,\n release: () => releaseLease(ref, deps, holder),\n };\n take = {\n take: (row) =>\n takeLease(ref, deps, {\n holder,\n generation: generationOf(row),\n until: leaseUntil,\n row,\n current: named === undefined,\n }),\n };\n }\n let at: Awaited<ReturnType<CrbmStorageChunkSource['pinGeneration']>>;\n try {\n // Under the store's retries, as its reads are: a transient fault resolving the pin must not fail pin().\n at = await this.withRetries(() =>\n named === undefined\n ? crbm.pinGeneration(ref, take)\n : crbm.pinGenerationAt(ref, named, take),\n );\n if (hold !== undefined && at === null) {\n throw new NotFoundError(`segment \"${ref.segment}\" has no generation to lease`);\n }\n } catch (err) {\n // A lease that landed and was not handed to a caller is released, so it holds nothing for its whole length.\n if (hold !== undefined) await hold.release().catch(() => undefined);\n throw err;\n }\n const pinnedAt: PinnedAt =\n at === null\n ? { generation: null, version: null, fingerprint: null }\n : { generation: at.generation, version: at.version, fingerprint: at.fingerprint };\n if (at !== null) crbm.startPinChecks(pinnedAt, at.checkedAtMs);\n const pins = new Map([[segmentKey(ref), pinnedAt]]);\n return makeSegment({\n engine: this.engineWithPins(pins),\n origin: this.origin,\n ref,\n clock: this.clock,\n metrics: this.metrics,\n materialize: (dest, ids, op, options) => this.materialize(dest, ids, op, options),\n pinned: (r, l, at) => this.pinSegment(r, l, at),\n combineEngine: (handles) => this.engineForCombine(handles),\n pinnedAt,\n lease: hold,\n });\n }\n\n /** 16 hex digits from the store's `Rng`, which names the holder of one lease: unique, not secret. */\n private mintHolder(): string {\n let id = '';\n for (let i = 0; i < 4; i++)\n id += Math.floor(this.rng.next() * 0x10000)\n .toString(16)\n .padStart(4, '0');\n return id;\n }\n\n /**\n * An engine reading every segment in `pins` at its pinned generation and everything else live, with the store's\n * retries, so a transient fault on a pinned read is retried as it would be on a live one.\n *\n * It **shares the store's chunk cache and its memory bound**, under keys of its own for each pinned segment, and the\n * store engine's invalidations, so an invalidation of a pinned segment reaches a read of the pin already running.\n */\n private engineWithPins(pins: ReadonlyMap<string, PinnedAt>): SegmentEngine {\n const crbm = this.crbmSource;\n if (crbm === undefined) {\n throw new UnsupportedError(\n 'pin() needs the `.crbm` storage source \u2014 pass a backend or a raw IStorageDriver as `storage` (the store ' +\n 'cannot pin a StorageChunkSource of your own)',\n );\n }\n const pinned = new PinnedStorageChunkSource(crbm, pins);\n return new SegmentEngine({\n storage:\n this.retryOptions === undefined\n ? pinned\n : new RetryingStorageChunkSource(pinned, this.retryOptions),\n cache: this.cache,\n codec: flagshipCodec(),\n clock: this.clock,\n metrics: this.metrics,\n budget: this.budget,\n sharesInvalidationsWith: this.engine,\n });\n }\n\n /**\n * The engine a combine should run on, given the handles involved.\n *\n * A pinned handle passed as an **operand** must still be read at its pin. Routing by \"which handle the call\n * was made on\" reads it live instead \u2014 `snap.intersect([other])` honours the pin while\n * `other.intersect([snap])` silently does not, and the two are the same question. So the combine collects\n * every pin in play and runs on an engine that honours all of them. With no pins anywhere this is the\n * store's own engine and costs nothing.\n *\n * One engine reads a segment at one generation, so a combine that holds the same segment at two \u2014 two pins of\n * it, or a pin and a live handle \u2014 is refused. Keeping one of them would answer the question for the wrong\n * instant, and say nothing: diffing two snapshots of a segment returned no ids at all.\n */\n private engineForCombine(handles: readonly Segment[]): SegmentEngine | undefined {\n // A combine that pins nothing \u2014 nearly every one \u2014 cannot hold a segment twice at two generations, so it pays\n // one pass over its handles and nothing more.\n if (!handles.some((h) => h.pinnedAt !== undefined)) return undefined;\n const pins = new Map<string, PinnedAt>();\n const held = new Map<string, PinnedAt | undefined>();\n for (const h of handles) {\n const key = h.key();\n const at = h.pinnedAt;\n if (held.has(key)) {\n const before = held.get(key);\n if (!samePin(before, at)) {\n throw new ValidationError(\n `the same segment is in this combine twice, ${twoPins(before, at)}: one call reads a segment at one ` +\n 'generation, so materialise one of them into a segment of its own first, with ' +\n \"`materializeMany({ operands: { src: seg }, outputs: [{ dest, expr: { or: ['src'] } }], keep })`\",\n );\n }\n } else {\n held.set(key, at);\n }\n if (at !== undefined) pins.set(key, at);\n }\n return this.engineWithPins(pins);\n }\n\n /** `op` under the store's retries, as the store's own reads run; bare when the store has retries off. */\n private withRetries<T>(op: () => Promise<T>): Promise<T> {\n const r = this.retryOptions;\n return r === undefined ? op() : withRetry(op, r.policy ?? DEFAULT_RETRY_POLICY, r);\n }\n\n /** The store's registry, or a typed error naming the operation that needs one. */\n private requireRegistry(op: string): IRegistryDriver {\n if (this.registry === undefined) {\n throw new UnsupportedError(\n `${op} needs a storage backend \u2014 S3Storage, GcsStorage, AzureBlobStorage, LocalFsStorage or ` +\n `MemoryStorage. A bare IStorageDriver has no generation pointer to publish through, and there is ` +\n `no separate \\`registry\\` option: a backend carries it.`,\n );\n }\n return this.registry;\n }\n\n /**\n * **Cross-tier DR consistency check.** After a restore/failover, verify every registered segment's `currentGen`\n * actually has its `.crbm` present in Storage \u2014 catching a **torn restore** where the registry (`currentGen`) came\n * back ahead of the object store, so a pointer references a generation that isn't there (reads would then\n * throw). Read-only, bounded fan-out; run it at startup after a restore. Returns `{ checked, inconsistent,\n * errored }` \u2014 `inconsistent` empty \u21D2 coherent; otherwise it names the segments to recover (restore the object\n * store, or roll the registry back to a coherent point). Needs the store built with a **backend**\n * (throws {@link UnsupportedError} otherwise). `destroyed` segments (crypto-shredded, destroyed in the clear or\n * dropped) are skipped. Pair\n * it with the DR runbook (docs/guide/disaster-recovery.md).\n *\n * A segment whose pointer names a missing object is the torn restore this reports; a cold `count()` of it still\n * answers the number its row records, while a read of the object throws, so the count alone never shows it. With\n * `summaries: true` it also opens each segment's current object (one tail read each) and reports a segment whose\n * row's summary names another object by its fingerprint, or says another id count or metadata than the object holds,\n * as `summary-mismatch`, which is what a\n * restore of the registry from another point than the bucket leaves a count to answer. A sealed summary is held\n * against its object when this store has the key, and counted in `summariesUnchecked` when it does not.\n *\n * With `generations: true` it also holds every generation a row's ledger of known generations names, the current one\n * included, against its object: one footer read each (104 bytes, no key, not retried), reporting\n * `known-generation-mismatch` with the `generation` where the object under that number is not the one the row\n * recorded. A named generation that is not in the bucket is not reported. A row with a pointer whose ledger cannot\n * be used is counted in `generationsUnchecked`, and none of its objects is read.\n *\n * It holds the registry rows it enumerates resident, at most 250,000 of them, and throws\n * `BudgetExceededError` (`option: 'maxScanSegments'`) past that rather than report a partial scan as a whole one.\n * Narrow the scan with `namespace`, or raise `maxScanSegments` when the fleet really is that large and the memory\n * is there.\n */\n async checkConsistency(\n options: {\n namespace?: string;\n concurrency?: number;\n /** The most registry rows the scan holds resident (default 250,000); past it the call throws `BudgetExceededError`. */\n maxScanSegments?: number;\n summaries?: boolean;\n generations?: boolean;\n } = {},\n ): Promise<ConsistencyReport> {\n checkOptions(options, 'checkConsistency', CALL_KEYS.checkConsistency, [\n 'summaries',\n 'generations',\n ]);\n options ??= {};\n const deps = this.lifecycleDeps('checkConsistency');\n return runConsistencyCheck(\n { storage: deps.storage, registry: deps.registry, keystore: deps.keystore },\n options,\n );\n }\n\n /**\n * **First-run check of the store's storage and registry.** Call it once at deploy time, or on a first run, before\n * the first load: it finds a missing permission, a storage that does not refuse a second write to a key, a listing\n * that lags, or a lifecycle rule that would delete the store's objects, while nothing depends on them yet.\n *\n * It runs seven checks and always lists all seven, in this order: `registry` (one read of a row that must be\n * absent, and the registry able to write), `write` (a new object), `write-once` (a second write to the same key must\n * be refused), `read` (the object reads back as written), `list` (the listing names it), `delete` (this run's own\n * object is removed, with the version the read gave where the driver applies one) and `lifecycle` (the backend's\n * lifecycle check). The probe is one small object at `cbm.due.preflight/segments/probe.<number>.crbm` under the\n * store's prefix; no registry row is written, and no segment of yours can share the name. A probe left by a run that\n * was cut off is named in the `list` detail and never deleted, since it could be a run in progress.\n *\n * It **never throws over a finding**. A failed step, a transient fault included, is a `problem` whose `detail`\n * says to run again when the fault was transient, and the checks that cannot run without it are `unchecked`. The\n * exception is the `lifecycle` step, whose failures, its timeout included, are `unchecked`. `ok` is true when no\n * check is a `problem`: read an `unchecked` check yourself, as `ok` does not vouch for it. The `lifecycle` check is\n * `unchecked` for a backend whose check says so (Azure Blob always), for a backend that has no such method (a\n * third-party backend, a `brandAsBackend` wrapper that does not forward it), when the identity lacks the optional\n * permission to read the lifecycle rules (`s3:GetLifecycleConfiguration`, `storage.buckets.get`), and when the check\n * takes longer than 30 seconds of the store's clock. The other steps are the store's ordinary calls and keep their\n * timing.\n *\n * **Not checked:** read-after-delete, the registry's `If-Match` on compare-and-swap, multipart abort permission,\n * versioning, backups, the keystore's backup and an S3 SDK from 3.641.0 to 3.699.0 (an older SDK shows as a\n * `write-once` problem; these drop `If-Match`, which only a registry write refuses). It makes no kind of request that a\n * load does not, though the lifecycle read needs its own optional permission. A run costs about seven requests (a\n * first run on GCS makes eight, the eighth a second listing that checks the bucket exists, and Azure Blob always\n * eight): two writes and a delete, the rest reads and one listing.\n *\n * Throws {@link UnsupportedError}, and only that, for a store with no backend, since there is nothing to check.\n */\n async preflight(): Promise<PreflightResult> {\n const deps = this.lifecycleDeps('preflight');\n const backend = this.backend;\n let checkLifecycle: NonNullable<StorageBackend['checkLifecycle']> | undefined;\n try {\n // A wrapper may carry anything under the name; only a function is a check.\n const method: unknown = backend?.checkLifecycle;\n if (typeof method === 'function')\n checkLifecycle = method.bind(backend) as typeof checkLifecycle;\n } catch {\n // a getter that throws offers no check\n }\n return runPreflight({\n storage: deps.storage,\n registry: deps.registry,\n clock: this.clock,\n entropy: this.entropy,\n checkLifecycle,\n });\n }\n\n /**\n * **Export (\"eject\") every registered segment's current generation** through the injected `sink`, using only\n * public read APIs \u2014 so your data is readable **without CloudRoaring** (the exit path; see the README's \"Your\n * data stays yours\"). `format: 'roaring'` (default) writes one **portable Roaring bitmap** per segment\n * (loadable by any roaring library); `'ndjson'` writes newline-delimited ids (zero-dependency, streaming).\n * Enumerates via the store's **own** registry (needs one \u2014 throws {@link UnsupportedError} otherwise) so the\n * enumeration and the read path provably share one registry. Encrypted segments are decrypted transparently\n * **iff** this store was wired with their keystore \u2014 the export is therefore **cleartext**; protect it.\n * Destroyed segments (crypto-shredded, destroyed in the clear or dropped) are skipped. A segment that can't be read\n * is isolated into the manifest's `failed[]` (the run continues), so \"a manifest exists\" means the run finished \u2014\n * check `failed`. The `export-segments`\n * CLI wraps this with a filesystem sink. The `'roaring'` format's bitmaps are built by the store's own codec.\n */\n async exportSegments(sink: ExportSink, options: ExportOptions = {}): Promise<ExportManifest> {\n checkOptions(options, 'exportSegments', CALL_KEYS.exportSegments, [], MISPLACED.exportSegments);\n const opts = picked(options, CALL_KEYS.exportSegments);\n const registry = this.requireRegistry('exportSegments');\n // The store's own codec builds the `'roaring'` format's bitmap: core's `runExport` is codec-agnostic and needs one.\n return runExport(this, registry, sink, { ...opts, codec: flagshipCodec() });\n }\n}\n\n/**\n * The options of a read or a combine on a {@link Segment}: one type for all of them, and each verb takes the fields that\n * apply to it.\n *\n * | verb | takes |\n * |---|---|\n * | `iterate`, `everyNth` | `after`, `through` |\n * | `intersect`, `union` | the range, `concurrency`, `budget`, `allowAbsentOperands`, `exclude` |\n * | `andNot` | the same but `exclude`: its `excludes` argument is the subtraction |\n * | `intersectInto`, `unionInto` | every field |\n * | `andNotInto` | every field but `exclude` |\n *\n * `audit`, `allowEmpty`, `guard`, `metadata` and `keep` decide what an `*Into` verb publishes, and a read publishes\n * nothing. A field a verb does not take is refused with a {@link ValidationError} that names it, before any request,\n * whether the object holds it as an own key, inherits it or holds it in a getter: a streaming read fails when it is first\n * read, and an `*Into` verb rejects. The compiler catches one only in an object\n * literal given to `iterate` or `everyNth`, which take the range alone: `Pick<CombineOptions, 'after' | 'through'>`,\n * the part {@link MaterializeManyOptions} extends.\n *\n * **The range**, `after` and `through`, is the ids greater than `after` and no greater than `through`, `(after,\n * through]`, built for keyset paging: `after` is the last id the caller already has, `through` the end of its window.\n * Each is optional: left out, the read starts at the first id or runs to the last. Each is an integer in\n * `0..4294967295`, or the read throws {@link ValidationError} when it is first read. `after >= through` is an empty range,\n * not an error, because a cursor that has reached the end of its window is normal; an empty range reads nothing, not even\n * whether a combine's operands exist. On a combine the range applies to every operand and every `exclude`, and a read\n * with a range fetches only the chunks it overlaps. The per-op budget is charged before the first fetch, for every chunk\n * in the range, so with `after` alone it is charged to the end of the segment however early the caller stops; pass\n * `through` to bound it. A read that lists its keys again after a move is charged again, with the chunks it has already\n * taken.\n */\nexport interface CombineOptions {\n /** Exclusive lower bound: the read yields only ids greater than this. */\n readonly after?: number | undefined;\n /** Inclusive upper bound: the read yields only ids up to and including this. */\n readonly through?: number | undefined;\n /**\n * How far ahead each operand is read: a positive integer, default 32. The library's own stores read each operand as\n * one stream of coalesced ranges (chunks that sit near each other are one request), and `concurrency` is how many\n * range requests a stream holds ahead of the read, in flight or landed and not yet used. So about\n * `concurrency \u00D7 operands` requests are in flight at most, and, since a range is at most 1 MiB (one chunk, when a chunk\n * is larger), about `concurrency \u00D7 operands` MiB are held, whatever the segment's size. The stream opens 4 ranges wide\n * (or `concurrency`, if lower) and widens as ranges are taken, so a read that stops early has asked for little past\n * where it stopped, and a read that fits one range makes one request however many chunks it needs. A source that\n * reads chunk by chunk (a custom one) is read `concurrency` chunk keys at once, opening 8 wide. A running\n * stream holds its operand's reader outside the reader cache's bounds until it ends or the segment moves on.\n */\n readonly concurrency?: number;\n /** Override the store's per-op denial-of-wallet budget for this call (`false` lifts it). */\n readonly budget?: BudgetOption;\n /**\n * Allow an operand naming a segment that does not exist. Default `false`: a combine **refuses** one, because\n * a misspelled or mis-namespaced operand is indistinguishable from a correct one in the result.\n *\n * Reading a segment that does not exist answers empty, and that is right \u2014 but passing one as an operand is\n * different. A suppression list with nobody on it correctly suppresses nothing; one whose `namespace` you\n * omitted *silently* suppresses nothing, and the result is not obviously-empty, it is the full audience and\n * plausibly right. The failure mode is mailing the people who opted out.\n *\n * ```ts\n * // `global-opt-out` lives in the `suppression` namespace. This addresses a DIFFERENT segment:\n * audience.andNot([store.segment('global-opt-out')]); // throws ValidationError\n * audience.andNot([store.segment('global-opt-out', { namespace: 'suppression' })]); // correct\n * ```\n *\n * Set `true` when you genuinely intend to combine against a name that may not exist yet. Checked only for an\n * operand that resolved to no chunks at all, so a normal combine pays nothing for it.\n */\n readonly allowAbsentOperands?: boolean;\n /**\n * Segments whose ids are subtracted from the result, on `intersect`, `union`, `intersectInto` and `unionInto`.\n *\n * `exclude` is why suppression does not need an intermediate segment: applied here it folds into the same\n * chunk-aligned pass, and each exclude is read **only at the keys that survived** \u2014 so a large global opt-out\n * list costs reads proportional to the audience, not to itself. `andNot` and `andNotInto` refuse it: their `excludes`\n * argument is the subtraction, and a second one in the options would be two spellings of one thing.\n */\n readonly exclude?: Segment[];\n /**\n * Audit sink, for the `*Into` verbs. A materialisation publishes a generation, and a publish is an auditable event\n * (`segment.publish`, exactly as a load emits) \u2014 as is a refusal (`segment.load-refused`).\n *\n * It is on the call rather than on the store because that is where every other auditable operation takes it\n * (`eraseSubject`, `dropSegment`, `retireExpired`): the caller who performs the act decides where the record\n * goes. Without it a `*Into` would be the one write path in the library that could make a generation current\n * and leave no trace in the compliance trail. A read verb writes nothing and emits nothing, so it refuses one.\n */\n readonly audit?: IAuditSink;\n /**\n * For the `*Into` verbs: publish an empty result over a non-empty destination. Off by default, exactly as on\n * {@link CloudRoaring.load}: an empty combine is far more often a mistake upstream \u2014 a typo'd operand, a segment that\n * has not loaded yet, an `exclude` that swallowed everything \u2014 than an intent, and once it lands it is\n * indistinguishable from a correct run.\n */\n readonly allowEmpty?: boolean;\n /**\n * For the `*Into` verbs: refuse an implausible result rather than publish it. Same bounds, and same meaning, as on\n * `load()`.\n */\n readonly guard?: LoadGuard;\n /**\n * For the `*Into` verbs: metadata for the generation the call publishes, under the rules and with the meaning of\n * {@link LoadOptions.metadata}: small, immutable, published with the pointer, never a subject's id. A value that\n * breaks a rule throws {@link ValidationError} before any request is made.\n */\n readonly metadata?: GenerationMetadata;\n /**\n * For the `*Into` verbs: generations to keep below the new pointer \u2014 see {@link LoadOptions.keep}. A value that is\n * not a non-negative integer throws `ValidationError`.\n *\n * **Defaults to keeping everything**, unlike `load()`, which keeps 1 and collects what it supersedes. An operator's\n * recovery story can depend on a materialisation collecting nothing: `rollbackSegment` refuses a target that\n * has been collected. Pass a number to collect on the way through; `0` keeps only the\n * generation this call publishes. It collects by listing the destination, so it clears every generation below the\n * new one beyond `keep`, however many earlier calls kept, where a `load()` deletes by name the generations its\n * publish pushes out of the window.\n */\n readonly keep?: number;\n}\n\n/**\n * An id stream as an iterator: the ids ascending, driven by `for await` or by hand with `next()`, `return()` and\n * `throw()`, as a generator is, on a handle that holds a lease as on one that does not. It is its own iterator and\n * single-use. {@link Segment.everyNth} returns this; the streams of {@link IdStream} add `batches()`.\n */\nexport interface IdIterator extends AsyncIterableIterator<number> {\n /** Ends the read, as a generator's `return` does, and resolves done with `value`. */\n return(value?: unknown): Promise<IteratorResult<number, unknown>>;\n /** Throws `err` into the read, as a generator's `throw` does: it rejects with `err` unless the read handles it. */\n throw(err: unknown): Promise<IteratorResult<number, unknown>>;\n}\n\n/**\n * What a streaming read returns: the ids, ascending, one at a time under `for await`, or one chunk at a time from\n * {@link IdStream.batches}.\n *\n * It is an `AsyncIterable<number>`, so every consumer of an id stream takes it as an async iterable, and an\n * {@link IdIterator}, so `next()`, `return()` and `throw()` are typed. A live read is the\n * engine's async generator itself, with `batches` attached: `for await` it, or drive it with `next()`, `return()` and\n * `throw()`, and it is single-use (a second `for await` over it yields nothing). A handle that holds a lease returns a\n * stream of the same shape, which checks the lease as it reads. `batches()` is a\n * separate, new read: it starts when called, fetches its chunks afresh and charges the per-op budget again, whether or\n * not the per-id stream was read, and reading both is two reads (invariant 3 applies to each separately). Nothing is\n * fetched until a read is first pulled. A stream pulled with `next()` and dropped without `return()` is held by nothing\n * in the store, so it is garbage once the caller lets it go.\n */\nexport interface IdStream extends IdIterator {\n /**\n * The same ids as the per-id stream, in the same order, one `Uint32Array` per chunk: each array ascending, holding\n * every id of one chunk the read yields (a range trimmed at its edges exactly as the per-id stream trims it), and\n * no array is empty. Chunks arrive in ascending order, so the concatenation is the per-id stream.\n *\n * One `await` per chunk instead of one per id: measured locally, an in-memory read goes several times faster, and\n * a large scan stops being bound by the event loop. The reads, the budget and the read-ahead window are the per-id\n * stream's, and so is stopping early: leaving a `for await` over it (`break`, `return`, a throw) ends the read.\n *\n * **Memory:** one array per chunk, at most 65,536 ids (256 KiB), allocated for that chunk alone and yours to\n * keep, change or hand on; the read holds no reference to it after yielding it.\n *\n * ```ts\n * for await (const ids of seg.andNot([optOut]).batches()) await send(ids);\n * ```\n */\n batches(): AsyncIterable<Uint32Array>;\n}\n\n/** A generator the engine just made, with the batch read that goes with it attached. Adds nothing per id. */\nconst withBatches = (\n gen: AsyncGenerator<number>,\n batches: () => AsyncIterable<Uint32Array>,\n): IdStream => Object.assign(gen, { batches });\n\n/** A generator function whose generator throws `err` on its first pull: what a refused read is, so its caller can drive it as any other. */\nconst refusing = (err: unknown) =>\n // eslint-disable-next-line require-yield\n async function* (): AsyncGenerator<never> {\n throw err;\n };\n\n/**\n * A stream that fails when it is first read, either way, and has the shape of one that does not: a generator, with\n * `batches` attached. A combine refuses its arguments this way, as the engine's own checks do, so a caller's try/catch\n * around the iteration catches it.\n */\nconst failing = (err: unknown): IdStream => withBatches(refusing(err)(), refusing(err));\n\n/** Whether two handles of one segment read it at one generation: both live, or both pinned to one object. */\nconst samePin = (a: PinnedAt | undefined, b: PinnedAt | undefined): boolean =>\n a === undefined || b === undefined\n ? a === b\n : a.generation === b.generation && a.fingerprint === b.fingerprint;\n\n/** How a refusal names two handles of one segment that read it at two generations. */\nconst twoPins = (a: PinnedAt | undefined, b: PinnedAt | undefined): string => {\n const one = (p: PinnedAt | undefined): string =>\n p === undefined ? 'live' : `pinned at generation ${p.generation ?? 'none'}`;\n return a !== undefined && b !== undefined && a.generation === b.generation\n ? `pinned twice at generation ${a.generation ?? 'none'}, as two different objects`\n : `${one(a)} and ${one(b)}`;\n};\n\n/** Every key of `T`, each possibly `undefined`: a copy typed this way fails to compile until it names every field. */\ntype EveryField<T> = { [K in keyof Required<T>]: T[K] | undefined };\n\n/** A read's range, read once, now, from whatever object holds it: a getter or an inherited bound included. */\nconst rangeOf = (options: RangeOptions): EveryField<RangeOptions> => ({\n after: options.after,\n through: options.through,\n});\n\n/**\n * How a combine reads its operands, read once, now, field by field, for the same reason as {@link rangeOf}. Typed to\n * name every field, so a read option added to {@link CombineOptions} and not listed here fails to compile instead of\n * being dropped.\n */\nconst readOptions = (options: ReadOptions): EveryField<ReadOptions> => ({\n ...rangeOf(options),\n concurrency: options.concurrency,\n budget: options.budget,\n allowAbsentOperands: options.allowAbsentOperands,\n});\n\nconst NO_SEGMENTS: readonly Segment[] = [];\n\n/**\n * `list` when it is an array, else a {@link ValidationError} naming `what`. A combine takes its operands and its\n * `exclude` as arrays: a `Set` or a lone segment from plain JavaScript would otherwise fail with a raw `TypeError`, or,\n * as an `exclude`, be read as no exclusion at all.\n */\nfunction segmentList(list: unknown, what: string): readonly Segment[] {\n if (!Array.isArray(list)) throw new ValidationError(`${what} must be an array of segments`);\n return list as readonly Segment[];\n}\n\ntype CombineVerb = 'intersect' | 'union' | 'andNot';\n\n/**\n * The segments a stream of this library reads, by key, held by the stream object. `store.load` consults it so that ids\n * read from a segment are not loaded back into that segment: the load publishes forward over whatever the segment is\n * by then, so another process's newer load of it would be replaced by a result built from the one before. Only a\n * stream handed over as it was returned is known; one wrapped in a generator of the caller's is not.\n */\nconst STREAM_SOURCES = new WeakMap<object, { origin: object; keys: readonly string[] }>();\n\n/** The registry driver each store was built over, by the store's origin: two stores over one backend instance share one. */\nconst REGISTRY_OF = new WeakMap<object, object>();\n\n/** `stream`, remembered as reading the segments `keys` of the store `origin`. */\nfunction readsFrom<T extends object>(stream: T, origin: object, keys: readonly string[]): T {\n STREAM_SOURCES.set(stream, { origin, keys });\n return stream;\n}\n\n/** How a refused operand list is named: `andNot` takes `excludes`, the others take `others`. */\nfunction operandsLabel(verb: CombineVerb): string {\n return verb === 'andNot' ? 'andNot: `excludes`' : `${verb}: \\`others\\``;\n}\n\n/**\n * The refusal of an empty operand list on `intersect` and `intersectInto`: an intersection over nothing has no meaning,\n * and a list built in a loop that came out empty would otherwise turn a filter into no filter. `union`, `andNot` and\n * their `*Into` forms read an empty list as the receiver itself. `verb` begins the message; the `*Into` form points a\n * caller who wanted a copy at the batch call, which reads a segment once at one instant.\n */\nfunction refuseNoOperands(verb: 'intersect' | 'intersectInto' | 'intersectCount'): never {\n throw new ValidationError(\n verb === 'intersect'\n ? 'intersect requires at least one segment to intersect with; to read every id of one segment, use iterate()'\n : verb === 'intersectCount'\n ? 'intersectCount requires at least one segment to intersect with; to count one segment, use count()'\n : 'intersectInto requires at least one segment to intersect with; to copy this segment into dest, call ' +\n \"materializeMany({ operands: { src: thisSegment }, outputs: [{ dest, expr: { or: ['src'] } }], keep })\",\n );\n}\n\ntype EngineCombine = Parameters<SegmentEngine['intersect']>[1];\ntype EngineAndNot = Parameters<SegmentEngine['andNot']>[2];\n\n/**\n * What a combine is read as: the ids a caller streams, or the chunks an `*Into` writes. The three verbs make the\n * same decisions about `exclude`, the engine and the options whichever it is, so each is written once over this, and\n * only the last step differs.\n */\ninterface CombineOutput<T> {\n /** A combine that fails when first read, as the engine's own refusals do. */\n readonly failing: (err: unknown) => T;\n /** The same combine, checking a lease each time it reads a chunk. */\n readonly guard: (result: T, check: () => void) => T;\n readonly intersect: (engine: SegmentEngine, refs: SegmentRef[], opts: EngineCombine) => T;\n readonly union: (engine: SegmentEngine, refs: SegmentRef[], opts: EngineCombine) => T;\n readonly andNot: (\n engine: SegmentEngine,\n base: SegmentRef,\n refs: SegmentRef[],\n opts: EngineAndNot,\n ) => T;\n}\n\n/** Combines read as ids: what `intersect`, `union` and `andNot` return. */\nconst AS_IDS: CombineOutput<IdStream> = {\n failing,\n guard: guardIds,\n intersect: (engine, refs, opts) =>\n withBatches(engine.intersect(refs, opts), () => engine.intersectBatches(refs, opts)),\n union: (engine, refs, opts) =>\n withBatches(engine.union(refs, opts), () => engine.unionBatches(refs, opts)),\n andNot: (engine, base, refs, opts) =>\n withBatches(engine.andNot(base, refs, opts), () => engine.andNotBatches(base, refs, opts)),\n};\n\n/** A combine's result as the chunks it is made of. */\ntype ChunkStream = AsyncIterable<{ chunkKey: number; bitmap: CodecBitmap }>;\n\n/** A combine's chunks on their way to a load, which writes them as they are. */\nclass CombineChunks {\n constructor(readonly chunks: ChunkStream) {}\n}\n\n/** Combines read as chunks: what the `*Into` verbs write into the new generation, with no id built on the way. */\nconst AS_CHUNKS: CombineOutput<ChunkStream> = {\n guard: guardItems,\n failing: (err) => refusing(err)(),\n intersect: (engine, refs, opts) => engine.intersectChunks(refs, opts, 'intersectInto'),\n union: (engine, refs, opts) => engine.unionChunks(refs, opts, 'unionInto'),\n andNot: (engine, base, refs, opts) => engine.andNotChunks(base, refs, opts, 'andNotInto'),\n};\n\n/**\n * The `keep` a materialisation passes when the caller does not: a grace window wide enough to collect nothing.\n *\n * The collection keeps `keep` generations below the pointer and deletes the rest, so an\n * integer at the top of the range keeps all of them. It has to be an integer \u2014 `loadSegment` validates that,\n * and `Infinity` is rejected \u2014 which is why this is `MAX_SAFE_INTEGER` and not the value that reads more\n * naturally.\n */\nconst KEEP_EVERY_GENERATION = Number.MAX_SAFE_INTEGER;\n\n/** Build a pinned twin of a handle \u2014 injected into `Segment` so it stays free of store wiring. */\ntype Pin = (ref: SegmentRef, leaseUntil?: number, at?: PinAt) => Promise<Segment>;\n\n/**\n * The engine a combine should run on, given every handle involved \u2014 `undefined` when none is pinned and the\n * store's own engine will do. Injected so `Segment` stays free of store wiring.\n */\ntype CombineEngine = (handles: readonly Segment[]) => SegmentEngine | undefined;\n\n/** How a `Segment` hands a result stream back to its store to become a new generation of `dest`. */\ntype Materialize = (\n dest: SegmentRef,\n ids: LoadInput | CombineChunks,\n op: string,\n options?: CombineOptions,\n) => Promise<MaterializeResult>;\n\n/** What a {@link Segment} is built from: the store's own wiring, which is why a handle is not constructible. */\ninterface SegmentParts {\n engine: SegmentEngine;\n /** The store's identity token, shared by every handle the store makes. */\n origin: object;\n ref: SegmentRef;\n clock: Clock;\n metrics: IMetricsSink;\n materialize: Materialize;\n /** Build a pinned twin of this handle \u2014 injected so `Segment` stays free of store wiring. */\n pinned: Pin;\n combineEngine: CombineEngine;\n pinnedAt?: PinnedAt;\n /** The lease this handle holds, when it came from `pin({ leaseUntil })`. */\n lease?: LeaseHold;\n}\n\n/**\n * The state of the lease a handle holds. `released` is set first by `release()`, so a read racing it already fails; `done`\n * once the registry write has landed, so a second `release()` makes no request.\n */\ninterface LeaseHold {\n readonly holder: string;\n readonly until: number;\n released: boolean;\n done: boolean;\n readonly release: () => Promise<void>;\n}\n\n/** What {@link Segment.pin} and {@link Segment.pinAt} take besides the generation. */\nexport interface PinOptions {\n /**\n * Hold the pinned generation until this instant: epoch-**milliseconds**, after now and at most\n * 14 days (1,209,600,000 ms) from it. A load's collection leaves a leased generation in the bucket until the lease\n * ends, and a read of the handle after it throws {@link LeaseExpiredError}, never empty.\n */\n readonly leaseUntil?: number;\n}\n\n/** The lease a pinned handle holds, as {@link Segment.lease} reports it. */\nexport interface Lease {\n /** 16 hex digits naming this lease in the segment's registry row. */\n readonly holder: string;\n /** Epoch-ms the lease runs to on this store's clock. */\n readonly until: number;\n}\n\n/**\n * The generation {@link Segment.pinAt} reopens: what an earlier pin recorded in {@link Segment.pinnedAt}. The\n * fingerprint is required, since a generation number is taken again after a purge and re-create.\n */\nexport interface PinAt {\n /** The generation number an earlier pin held. */\n readonly generation: number;\n /** The fingerprint of that generation's object, from the earlier pin's `pinnedAt.fingerprint`. */\n readonly fingerprint: string;\n}\n\n/**\n * What {@link Segment.stat} answers: the generation a handle reads, its id count, its metadata and the size of its\n * object.\n */\nexport interface SegmentStat {\n /** The generation read, or `null` when the segment has none. */\n readonly generation: number | null;\n /** The number of ids in the generation read, or `0` when the segment has none. */\n readonly cardinality: number;\n /** The metadata the generation was loaded with; absent when it has none. */\n readonly metadata?: GenerationMetadata;\n /**\n * The generation's object in storage, in bytes: what the segment stores. From the registry row's summary, which\n * records the object's size with its checksum, or from the object's footer when the row has no summary to use.\n * `null` when the segment has no generation, or when the store's source cannot report a size.\n */\n readonly sizeBytes: number | null;\n}\n\n/**\n * Time `fn` with `clock` and emit an `op` metric to `metrics` when it settles, on success or throw: the store's timing,\n * as a segment's `timed` does its own inline, which keeps a promise off the path of `has` and `count`.\n */\nasync function timeOp<T>(\n metrics: IMetricsSink,\n clock: Clock,\n name: MetricOpName,\n fn: () => Promise<T>,\n): Promise<T> {\n const startedAt = clock.now();\n try {\n return await fn();\n } finally {\n metrics.onEvent({ kind: 'op', name, ms: Math.max(0, clock.now() - startedAt) });\n }\n}\n\n/** The store's one way to mint a {@link Segment}, bound by the class's static block. */\nlet makeSegment: (parts: SegmentParts) => Segment;\n/** True only while {@link makeSegment} is constructing, so a `new Segment(...)` from plain JS is refused. */\nlet minting = false;\n\n/**\n * A handle bound to one segment \u2014 the read verbs, plus the three `*Into` verbs that write a **new generation**\n * of another segment.\n *\n * **IDs must be integers in `[0, 2^32)`** (dense 32-bit). A non-integer / negative / out-of-range id\n * throws {@link ValidationError}.\n *\n * A handle has no per-id write: data enters a segment as a whole generation (`store.load()`, or one of the\n * `*Into` verbs), and leaves it the same way (`eraseSubject`, `dropSegment`).\n */\nexport class Segment {\n private readonly metricsOn: boolean;\n private readonly engine: SegmentEngine;\n /** The store that made this handle, by reference; a combine takes only handles of its own store. */\n private readonly origin: object;\n private readonly ref: SegmentRef;\n private readonly clock: Clock;\n private readonly metrics: IMetricsSink;\n private readonly materialize: Materialize;\n private readonly pinned: Pin;\n private readonly combineEngine: CombineEngine;\n /**\n * The generation this handle is held at, when it came from {@link Segment.pin}. Read by the store so a\n * pinned handle passed as an **operand** is still read at its pin rather than live.\n */\n readonly pinnedAt?: PinnedAt;\n /**\n * The lease this handle holds, when it came from `pin({ leaseUntil })`; `undefined` otherwise. It reports what was\n * taken and does not change when the lease ends: a read after `lease.until` (or after {@link Segment.release}) throws\n * {@link LeaseExpiredError}.\n */\n readonly lease?: Lease;\n private readonly leaseHold?: LeaseHold;\n\n static {\n Object.defineProperty(Segment.prototype, SEGMENT_BRAND, { value: true });\n makeSegment = (parts) => {\n minting = true;\n try {\n return new Segment(parts);\n } finally {\n minting = false;\n }\n };\n viewOf = (segment) => ({\n ref: segment.ref,\n pinnedAt: segment.pinnedAt,\n leaseError: () => segment.leaseError(),\n });\n originOf = (segment) => segment.origin;\n }\n\n /**\n * Not constructible: a handle comes from {@link CloudRoaring.segment}, which wires it to the store's engine,\n * caches and write path. The constructor takes those internals, so it is not part of the surface.\n */\n private constructor(parts: SegmentParts) {\n if (!minting) {\n throw new ValidationError(\n 'a Segment is not constructed directly; call `store.segment(name)`',\n );\n }\n this.engine = parts.engine;\n this.origin = parts.origin;\n this.ref = parts.ref;\n this.clock = parts.clock;\n this.metrics = parts.metrics;\n this.materialize = parts.materialize;\n this.pinned = parts.pinned;\n this.combineEngine = parts.combineEngine;\n this.pinnedAt = parts.pinnedAt;\n this.leaseHold = parts.lease;\n if (parts.lease !== undefined) {\n this.lease = Object.freeze({ holder: parts.lease.holder, until: parts.lease.until });\n }\n this.metricsOn = parts.metrics !== NOOP_METRICS;\n }\n\n /**\n * **Hold this segment at the generation that is current right now**, for as long as you keep the handle.\n *\n * An ordinary handle re-resolves on `cache.genTtlMs`, so a publish part-way through a long job means its second\n * half describes a different instant than its first \u2014 every chunk whole and verified, but the answer covering\n * two moments, with nothing in the result saying so. That is fine for a dashboard and wrong for an export, a\n * reconciliation, or a send that has to match the count you reported. A pin is how you get one instant.\n *\n * ```ts\n * const snap = await store.segment('active-30d').pin();\n * const total = await snap.count(); // the number you report\n * for await (const id of snap.iterate()) { \u2026 } // \u2026and the ids it counted, however long this takes\n * ```\n *\n * **Only this segment is pinned.** `snap.intersect([other])` reads `snap` at its pinned generation and\n * `other` at whatever is current \u2014 pin each segment if you want the whole query held. And a pinned handle\n * used as an *operand* is still read at its pin, never live.\n *\n * **One call reads a segment at one generation**, so a combine that holds this segment at two \u2014\n * `snap0.andNot([snap1])`, or `live.intersect([snap])` \u2014 throws {@link ValidationError} when it is read, and an\n * `*Into` of one throws before it reads anything. Materialise one side first, with `materializeMany({ operands: { src: seg }, outputs: [{ dest, expr: { or: ['src'] } }], keep })`.\n *\n * **A pin knows its object, not only its number.** A name purged and loaded again starts again at generation\n * 0, so a pin of the old segment never reads the new one. On a store with a timed refresh the pin fails with\n * `NotFoundError` at its next check, within `cache.genTtlMs`, what it had already read included, and `invalidate`\n * does not bring it back: take a new pin. On a store with none, what it has already read still answers, as the\n * instant it pinned, and anything it would have to fetch fails with `NotFoundError`, as a swept pin's does.\n *\n * **It is a hold, and `pin({ leaseUntil })` makes it a bounded one.** Without a lease nothing stops a collection\n * deleting the generation underneath you: a pinned read deliberately does **not** heal forward, because silently\n * serving a different generation is the one thing a pin exists to prevent, so it fails instead. Size `keep` to cover\n * your longest pinned job \u2014 see [Generations and `keep`](https://github.com/cloudbitmaps/cloudbitmaps/blob/main/docs/guide/loading.md#generations-and-keep) \u2014 take the pin on a segment\n * you are not collecting, or lease it.\n *\n * **A lease** (`leaseUntil`: epoch **milliseconds**, after now and at most 14 days out) keeps the generation out of\n * a load's collection until then, from any process, and the pin is taken with it: the lease is written to the segment's\n * row before the object is opened. A read of the handle after the lease, or after {@link Segment.release}, throws\n * {@link LeaseExpiredError} at every read site, including when the handle is an operand or an `exclude` of a combine\n * or the target of an `*Into`, and never reads empty. A stream checks the lease each time it reads a chunk. A segment\n * holds at most 64 live leases ({@link LeaseLimitError}). A collector holds a lease 60 seconds past its end, which covers\n * clocks that differ by that much. Erasure, shred, drop and retention expiry ignore a lease. See\n * [Hold a generation for a job](https://github.com/cloudbitmaps/cloudbitmaps/blob/main/docs/guide/reading.md#hold-a-generation-for-a-job-a-lease).\n *\n * A segment with no current generation pins nothing and reads empty, exactly as it would unpinned. A pinned\n * segment whose row is later dropped or destroyed fails once it must open its object again, rather than go empty\n * part-way through a call. **A pin\n * keeps the key its reader unwrapped for as long as that reader stays open, and answers from the chunks it\n * decoded for as long as they stay cached, until its next check.** On a store with a timed refresh a pin checks its\n * segment's row every `cache.genTtlMs` (from the moment it was taken, whether or not it was read) and fails with\n * `NotFoundError` once the segment is destroyed, is another incarnation, or its generation is collected or recorded by its row as another object (an object lost or replaced out of band\n * under a row that still names it is found only when the pin must fetch). This\n * store invalidates a pin:\n *\n * - a `load`, a `rollback` or an `*Into` invalidates a pin of the segment it writes;\n * - `dropSegment` invalidates a pin of the segment it drops, and `retireExpired` a pin of each segment its ledger\n * lists, retired or not, neither on a dry run;\n * - `eraseSubject` invalidates a pin of each segment it scans that is not already destroyed.\n *\n * An invalidated pin opens its object again, and fails if that object is gone or replaced, or its row is gone or\n * destroyed. A read of the pin already running when the invalidation comes, a combine on this store with the pin as\n * an operand included, looks the pin up again before it hands out its next chunk: it carries on with what it holds\n * where the object is still there, and fails with `NotFoundError` where it is gone. It caches nothing more of what it\n * began reading before the invalidation, so the pin's next read opens the object again too.\n * Anything else leaves the pin as it is: after a `destroySegment` beside this store, or an erasure, a drop or a\n * retirement through another store, in this process or another, the pin answers from what it holds for at most\n * `cache.genTtlMs` on a store with a timed refresh, and then fails. On a store with none it answers until this\n * store's reader cache evicts the pin's reader and its chunk cache evicts the chunks the pin decoded, or\n * {@link CloudRoaring.invalidate} is called on this store. A combine on another store refuses the pin. Where the\n * object the pin reads has been deleted, by an erasure, a drop or a sweep, a chunk the pin has not cached fails at\n * once. With no timed refresh nothing bounds any of that, as nothing bounds anything else a pin holds.\n *\n * A replacement a read of the pin found is remembered, so its later chunk reads fail with no request, until the store\n * forgets it: an invalidation of the segment does, as does a later `pin()` of the same version that opens the object\n * again; a replacement the pin's own check found is forgotten only by an invalidation. The store remembers at most `cache.readerMax` of them. So once a restore puts the pinned object back\n * into the same row, call {@link CloudRoaring.invalidate} on this store: the pin then reads the object again. A\n * restore into a purged and re-created row does not revive a pin on a store with a timed refresh: take a new pin.\n *\n * `pin()` reads the registry row and opens the generation at once, so the pin knows its object before its first\n * read. With a registry, pins of one generation taken while its row is unchanged share one reader while the store\n * keeps it open, pins taken at the same moment included: the first costs a tail read, and a key unwrap for an\n * encrypted segment, whether or not it is read, and the rest cost the row read alone. Without a registry every\n * `pin()` lists the segment's objects and makes the tail read, since only the object can tell two incarnations of\n * a name apart there. It retries a\n * transient fault as the store's reads do, and heals a generation swept between the two, but it fails where the\n * generation cannot be opened: `NotFoundError` for a pointer at a missing object, `IntegrityError` for a damaged\n * or misfiled one.\n *\n * Needs a store built on the `.crbm` storage source (the default when you pass a backend or a raw driver). Throws\n * {@link UnsupportedError} on a store wired with a `StorageChunkSource` of your own, which it cannot pin.\n */\n async pin(options?: PinOptions): Promise<Segment> {\n // A leased handle pins nothing once its lease is over. The pin it makes is an ordinary one: it takes the generation\n // that is current now, which is not the leased one, and holds no lease of its own unless asked.\n this.assertLease();\n const leaseUntil = this.leaseUntilOf('pin', options);\n return this.pinned(this.ref, leaseUntil);\n }\n\n /**\n * Hold what this pin names until `leaseUntil`, or `undefined` for a pin with no lease. Refuses an option it does not\n * know, a value that is not epoch-milliseconds in the future, and one past the longest lease, before any request is\n * made.\n */\n private leaseUntilOf(op: string, options: PinOptions | null | undefined): number | undefined {\n if (options === undefined || options === null) return undefined;\n if (typeof options !== 'object' || Array.isArray(options)) {\n throw new ValidationError(`${op}: options must be an object such as { leaseUntil }`);\n }\n // Own enumerable string keys only, as `pinAt` reads its argument.\n const unknown = Object.keys(options).filter((k) => k !== 'leaseUntil');\n if (unknown.length > 0) {\n throw new ValidationError(\n `${op}: unknown option${unknown.length > 1 ? 's' : ''} ${unknown.map((k) => `\"${k}\"`).join(', ')}; ` +\n 'this version takes { leaseUntil } only',\n );\n }\n const until = options.leaseUntil;\n if (until === undefined) return undefined;\n const now = this.clock.now();\n if (typeof until !== 'number' || !Number.isSafeInteger(until)) {\n throw new ValidationError(\n `${op}: leaseUntil must be an integer epoch-MILLISECONDS; got ${String(until)}`,\n );\n }\n if (until <= now) {\n throw new ValidationError(\n `${op}: leaseUntil (${until}) is not after now (${now}); it is epoch MILLISECONDS, so a value in seconds ` +\n 'reads as long past. Use `Date.now() + hours * 3_600_000`',\n );\n }\n if (until > now + MAX_LEASE_MS) {\n throw new ValidationError(\n `${op}: leaseUntil is more than 14 days away; the longest lease is ${MAX_LEASE_MS} ms. Take a new lease when a job outlasts it`,\n );\n }\n return until;\n }\n\n /**\n * End this handle's lease now, so a load's collection may take its generation. Idempotent: a handle with no lease, or\n * one already released, does nothing and makes no request. Every read of the handle after it throws\n * {@link LeaseExpiredError} (reason `'released'`), including one already under way at its next chunk. A lease that has\n * ended by its own time needs no release: this then makes no request either, and the registry row's entry is pruned\n * by a later write. Otherwise it is one registry read and one write; a failure of either is thrown as the registry's own\n * typed error, and the entry then holds until its time ends, `release()` being safe to call again.\n */\n async release(): Promise<void> {\n const hold = this.leaseHold;\n if (hold === undefined) return;\n hold.released = true;\n if (hold.done) return;\n if (this.clock.now() >= hold.until + LEASE_SKEW_MS) {\n hold.done = true;\n return;\n }\n await hold.release();\n hold.done = true;\n }\n\n /**\n * The error a read of this handle must throw, or `undefined` when it holds no lease or the lease is live. One property\n * read on a handle with no lease. A read past a lease throws; it never reads empty.\n */\n private leaseError(): LeaseExpiredError | undefined {\n const hold = this.leaseHold;\n if (hold === undefined) return undefined;\n const name = this.ref.namespace\n ? `${this.ref.namespace}/${this.ref.segment}`\n : this.ref.segment;\n if (hold.released) {\n return new LeaseExpiredError(\n `the lease on segment \"${name}\" was released`,\n hold.until,\n 'released',\n );\n }\n if (this.clock.now() >= hold.until) {\n return new LeaseExpiredError(\n `the lease on segment \"${name}\" ended; a read of a handle past its lease throws, never reads empty`,\n hold.until,\n 'expired',\n );\n }\n return undefined;\n }\n\n /**\n * Refuse with a {@link ValidationError} any of `handles` that this store did not make: a value that is not a segment,\n * a segment of another store (even one over the same backend) and a segment of another installed copy of the\n * package. It runs first in every combine, before the lease check reads the handles and before any request.\n */\n private assertSegments(verb: string, role: HandleRole, handles: readonly unknown[]): void {\n for (const h of handles) assertOneStore(verb, role, h, this.origin);\n }\n\n /**\n * Throw the first lease error among `handles`: this handle and every operand and exclude of a call. It runs before\n * the engine, so no operand, exclude or cached reader can answer past a lease.\n */\n private assertLeases(handles: readonly Segment[]): void {\n for (const h of handles) {\n const err = h.leaseError();\n if (err !== undefined) throw err;\n }\n }\n\n /** Throw this handle's lease error, if it has one. The calls that return a value instead of throwing use {@link leaseError}. */\n private assertLease(): void {\n const err = this.leaseError();\n if (err !== undefined) throw err;\n }\n\n /**\n * Reopen a generation a pin named earlier, as a pinned handle like the one {@link Segment.pin} returns, held at\n * `at.generation` instead of the current one. Pass what the earlier pin recorded, `{ generation, fingerprint }`\n * from its {@link Segment.pinnedAt}. A generation number alone is not an identity, since a purged and re-created\n * name starts again at 0, so the fingerprint is required: a bare number, a malformed fingerprint or a key other\n * than `generation`, `fingerprint` and `version` is a {@link ValidationError}. Identify a pin by its `generation` and\n * `fingerprint`: the handle's `pinnedAt.version` can differ from the earlier pin's.\n *\n * Throws {@link NotFoundError} when the generation is gone (collected, purged, or on a destroyed segment),\n * is above the row's pointer, or is another object than the fingerprint names, and never reads empty. A rollback\n * deletes nothing, so once a later load moves the pointer past a generation it rolled back from, that one can be\n * reopened while its object is stored. Nothing keeps a generation alive unless you lease it: a later load's\n * collection can delete it, which is sized by `keep` on every writer, or held by `options.leaseUntil` (see\n * {@link PinOptions} and {@link Segment.pin}). A leased `pinAt` writes the lease before it verifies the object, and\n * releases it if the verify fails; for a generation below the pointer, a collector that read the row before the lease\n * landed can still delete the generation inside its own round trip, and the handle then fails with `NotFoundError`\n * like any swept pin. A leased handle is checked at every read site as a leased `pin()` is. With a registry it costs one row read and one tail read,\n * and a leased `pinAt` one conditional write to the row besides; the handle\n * then reads as one from `pin()` does, including its failure on a chunk it has not cached once the generation is\n * swept. Works for an encrypted segment. The first argument is an object so that fields can join it later; the lease\n * is in `options`, the second.\n *\n * It takes what {@link Segment.pinnedAt} holds: once `generation` is not `null`, the record passes as it is (its\n * `version` is not read), and `{ generation, fingerprint }` does as well. A pin of a segment that had no generation\n * has nothing to reopen and throws {@link ValidationError}.\n */\n async pinAt(at: PinAt, options?: PinOptions): Promise<Segment> {\n // A leased handle past its lease pins nothing, as for `pin()`.\n this.assertLease();\n // A pin's `pinnedAt` is handed back whole, so its `version` is a key `pinAt` knows: the fingerprint is what\n // identifies the object, and the version is not read.\n const { generation, fingerprint, version } = (at ?? {}) as Partial<PinAt> & {\n version?: unknown;\n };\n // Own enumerable string keys only: a symbol, non-enumerable or inherited key is not seen.\n const unknown =\n typeof at === 'object' && at !== null\n ? Object.keys(at).filter((k) => !['generation', 'fingerprint', 'version'].includes(k))\n : [];\n if (unknown.length > 0) {\n throw new ValidationError(\n `pinAt: unknown option${unknown.length > 1 ? 's' : ''} ${unknown.map((k) => `\"${k}\"`).join(', ')}; ` +\n \"pinAt takes { generation, fingerprint } and a pin's `version`, which it does not read\",\n );\n }\n if ((generation as unknown) === null) {\n throw new ValidationError(\n 'pinAt: the pin named no generation (the segment had none when it was pinned), so there is nothing to reopen',\n );\n }\n if (version !== undefined && typeof version !== 'string') {\n throw new ValidationError(\n 'pinAt: `version`, when given, is the string a pin recorded in its pinnedAt; pinAt does not read it, so leave it out if you have none',\n );\n }\n if (\n typeof generation !== 'number' ||\n !Number.isSafeInteger(generation) ||\n generation < 0 ||\n typeof fingerprint !== 'string' ||\n !/^\\d+:\\d+$/.test(fingerprint)\n ) {\n throw new ValidationError(\n 'pinAt: pass { generation, fingerprint } as recorded by an earlier pin (its pinnedAt); a generation number ' +\n 'without the fingerprint of its object does not identify it',\n );\n }\n // `at` takes `{ generation, fingerprint }` and a pin's `version`; the lease goes in the options, the second argument.\n const leaseUntil = this.leaseUntilOf('pinAt', options);\n return this.pinned(this.ref, leaseUntil, { generation, fingerprint });\n }\n\n /**\n * An opaque string that names this handle's segment, namespace included: two handles of one segment have the\n * same key, a live handle and its pins among them. Use it as a `Map` key or a log field when you track handles\n * and have not kept the name you made them with. The format is not specified and is not a storage key, so\n * compare keys, never parse one.\n */\n key(): string {\n return segmentKey(this.ref);\n }\n\n /**\n * Refuse an `*Into` that cannot run, before any request, in this order: anything that is not a segment or is a\n * segment of another store, an empty operand list for `intersectInto`, and a `dest` that is also a source (all\n * {@link ValidationError}); then a handle (this one, `dest`, an operand or an exclude) whose lease has ended or was\n * released ({@link LeaseExpiredError}). A call with both a lapsed lease and one of the first three refusals throws the\n * first. Called by the three `*Into` verbs only.\n *\n * The verbs are `async` so this surfaces as a **rejected promise**, like every other validation in the facade \u2014\n * a synchronous throw out of a promise-returning method escapes a caller who attached `.catch()` instead of\n * awaiting.\n */\n private assertIntoHandles(\n verb: `${CombineVerb}Into`,\n dest: Segment,\n operands: readonly Segment[],\n excludes: readonly Segment[],\n ): void {\n this.assertSegments(verb, 'the destination', [dest]);\n this.assertSegments(verb, verb === 'andNotInto' ? 'an exclude' : 'an operand', operands);\n this.assertSegments(verb, 'an exclude', excludes);\n const base = verb.slice(0, -'Into'.length) as CombineVerb;\n if (base === 'intersect' && operands.length === 0) refuseNoOperands('intersectInto');\n this.refuseSourceDestination(verb, dest, operands, excludes);\n this.assertLeases([this, dest, ...operands, ...excludes]);\n }\n\n /**\n * Refuse an `*Into` whose destination is also one of its sources (this segment, an operand or an exclude, by the key\n * a handle gives, so a pin of the source and a ref spelled with the default namespace count), before any request, as\n * `materializeMany` refuses it. The combine would read the destination at the generation this store last resolved,\n * up to `cache.genTtlMs` old, while the publish is fenced on the row as it stands: another process's newer load of\n * the destination would be overwritten by a result built from the one before it, with no conflict to report.\n */\n private refuseSourceDestination(\n verb: `${CombineVerb}Into`,\n dest: Segment,\n operands: readonly Segment[],\n excludes: readonly Segment[],\n ): void {\n const key = dest.key();\n const role =\n this.key() === key\n ? 'this segment'\n : operands.some((o) => o.key() === key)\n ? verb === 'andNotInto'\n ? 'an exclude'\n : 'an operand'\n : excludes.some((o) => o.key() === key)\n ? 'an exclude'\n : undefined;\n if (role === undefined) return;\n const { namespace, segment } = dest.ref;\n const named = namespace === undefined ? segment : `${namespace}/${segment}`;\n throw new ValidationError(\n `${verb}: the destination \"${named}\" is also ${role} of the call, and a call that reads a segment while it ` +\n 'publishes to it can replace a newer load of it with a result built from an older one, with no conflict ' +\n 'reported. This release has no fenced in-place update: combine into a new segment and point readers at it',\n );\n }\n\n /** `result` as is, or, when a handle of the call holds a lease, checking that lease each time it reads a chunk. */\n private guarded<T>(out: CombineOutput<T>, handles: readonly Segment[], result: T): T {\n return handles.some((h) => h.leaseHold !== undefined)\n ? out.guard(result, () => this.assertLeases(handles))\n : result;\n }\n\n /**\n * Time an op with the injected clock and emit an `op` metric on completion (success or throw). With no sink wired it\n * reads no clock and emits nothing, but a call still passes through this async frame; `has()` and `count()` return the\n * engine's promise directly instead.\n */\n private async timed<T>(name: MetricOpName, fn: () => Promise<T>): Promise<T> {\n if (!this.metricsOn) return fn();\n const startedAt = this.clock.now();\n try {\n return await fn();\n } finally {\n this.metrics.onEvent({ kind: 'op', name, ms: Math.max(0, this.clock.now() - startedAt) });\n }\n }\n\n /**\n * Membership: one chunk. A cold resolution of the segment is one registry read and a warm one none; then a cached\n * chunk answers with no request, and an uncached one is one range read, after a tail read when no reader of the\n * generation is open, unless that tail carried the chunk. Throws {@link ValidationError} on a bad id.\n */\n has(id: number): Promise<boolean> {\n const lease = this.leaseError();\n if (lease !== undefined) return Promise.reject(lease);\n if (!this.metricsOn) return this.engine.has(this.ref, id);\n return this.timed('has', () => this.engine.has(this.ref, id));\n }\n /**\n * Cardinality of the generation this handle reads: **one registry read when cold, none when warm, and no read of the\n * object**, with **zero payload reads**. The registry row records the id count of the generation it names, written\n * by the write that made it current, and a count answers from that. A row with no summary it can use (one written\n * without it, as a registry of your own may, one that names another generation, a sealed one that does not open)\n * sends the count to the `.crbm` index, summed with a tail read of the object. A segment whose pointer names a missing object (a torn\n * restore) still counts the row's number, while a read of the object throws; `checkConsistency` is what finds it.\n *\n * What this trusts: the row's summary, or the index's sum, and no payload is decoded to confirm it. The summary is\n * used only for the generation it names, on an active row, and a sealed one only if it opens under the segment's\n * key; it is held against the object whenever the object is opened anyway (a `has`, an `iterate`, a combine, a\n * `pin()`), at no extra request, and a disagreement stops this store using it, and fails nothing. It is not\n * confirmed on the cold path, so a party who can write the registry row can make a count wrong. The index is checked for internal consistency when the object is opened (each key in\n * range and ascending, each cardinality in `1..65536`, each payload inside the payload region, and, on an\n * unencrypted object, the footer's chunk count and total agreeing with the index), and a corrupt index that is\n * still internally consistent yields a wrong count. `iterate()` and the combines decode the payloads, whose\n * structure is checked.\n */\n count(): Promise<number> {\n const lease = this.leaseError();\n if (lease !== undefined) return Promise.reject(lease);\n if (!this.metricsOn) return this.engine.count(this.ref);\n return this.timed('count', () => this.engine.count(this.ref));\n }\n /**\n * What the generation this handle reads is, from one resolution: its number, its id count, the metadata it was\n * loaded with (absent when it has none), and `sizeBytes`, its object's bytes in storage. All four come from the\n * registry row when it has a summary this store can use, as `count()`'s do: the summary records the object's\n * fingerprint, its size with its checksum. That is **one registry read when cold, none when warm, and no read of the\n * object**. With no summary it can use, they come from the generation's object, opened once: its footer and index,\n * with no payload read, which is a tail read of the object more when cold (and a range read for an index longer than\n * the tail) and keeps the generation in the reader cache as a read does. On a pinned handle it answers for the\n * generation it pinned, from the pinned object. A segment with no generation answers\n * `{ generation: null, cardinality: 0, sizeBytes: null }`, and a store whose source cannot report a size answers\n * `sizeBytes: null`. A pointer that names a missing object (a torn restore) still answers from the row's summary, as\n * `count()` does, while a read of the object throws `NotFoundError`; with no summary to use, `stat()` throws it too.\n * `checkConsistency` is what finds such a row.\n *\n * Trust is as for `count()`: what the row's summary says is believed until the object is next opened. Every open of\n * the generation holds the object to the fingerprint the summary records, so another object under the number is\n * refused when it is opened, and holds its count against the summary's; a disagreement in count makes this process\n * stop using that summary, so `stat()` then answers from the object, whose index is checked for internal consistency\n * and whose count is the index's sum. A reader already open is not checked again until the row changes, it is\n * evicted or it is invalidated.\n *\n * `sizeBytes` is what `groundedReport` in `@cloudbitmaps/tools` prices storage from.\n *\n * ```ts\n * const { generation, cardinality, metadata, sizeBytes } = await store.segment('active-30d').stat();\n * ```\n */\n async stat(): Promise<SegmentStat> {\n this.assertLease();\n return this.engine.stat(this.ref);\n }\n /**\n * Every id, ascending, streamed one chunk at a time. Pass a range to read part of the segment: the ids in\n * `(after, through]`, fetching only the chunks the range overlaps. The per-op budget is charged for every chunk in\n * the range, so give a page `through` as well as `after`. On a pinned handle it reads the pinned generation, as a\n * full read does.\n *\n * ```ts\n * // Keyset paging: each page resumes where the one before ended, and stops at its window's end.\n * for await (const id of seg.iterate({ after: previousEnd, through: windowEnd })) await send(id);\n * ```\n *\n * Each bound is optional and an integer in `0..4294967295`; a bad one throws {@link ValidationError} when the\n * stream is first read. `after >= through` is an empty range, which reads nothing.\n */\n iterate(options?: Pick<CombineOptions, 'after' | 'through'>): IdStream {\n const lease = this.leaseError();\n if (lease !== undefined) return failing(lease);\n const bad = optionsError(options, 'iterate', CALL_KEYS.range, [], MISPLACED.range);\n if (bad !== undefined) return failing(bad);\n // Neither bound set is no range at all, which the engine reads on its full-read path.\n const range = options == null ? undefined : rangeOf(options);\n const none = range === undefined || (range.after === undefined && range.through === undefined);\n const { engine, ref } = this;\n const bounds = none ? undefined : range;\n const stream = withBatches(engine.iterate(ref, bounds), () =>\n engine.iterateBatches(ref, bounds),\n );\n return readsFrom(\n this.leaseHold === undefined ? stream : guardIds(stream, () => this.assertLease()),\n this.origin,\n [this.key()],\n );\n }\n\n /**\n * **Pinned handles only.** The ids at 1-based ranks `n`, `2n`, `3n` \u2026, counted over the ids in `(after, through]`\n * when a range is given, ascending: `everyNth(1000)` yields the 1,000th id, then the 2,000th, and so on. A last\n * partial window yields nothing, so a caller cutting a send into windows of `n` appends its own final end.\n *\n * It places each boundary from the per-chunk counts the pin already holds and reads only the chunks that hold one,\n * each once however many boundaries it holds, so it reads at most one chunk per boundary and never more chunks\n * than the object has. A range with `after` inside a chunk reads that chunk too, to count the ids at or below\n * `after`, even when fewer than `n` ids remain above it; when the chunks in range hold fewer than `n` ids in all,\n * nothing is fetched. `through` stops the read and no chunk past it is read, though a `through` inside a chunk may read that last chunk and\n * yield nothing from it. The reads and the read-ahead window are\n * those of {@link Segment.iterate}, and the per-op budget is charged before the first fetch, with an upper bound on\n * the chunks the read can take. A pinned read after the generation is swept throws {@link NotFoundError}.\n *\n * The ranks come from the index's counts, which are trusted as {@link Segment.count} trusts them. A chunk that is\n * read must hold the number of ids its index says, or the read throws {@link IntegrityError}; a chunk that is not\n * read is not checked, so an index that is wrong about one, and, on an unencrypted object, still adds up to the footer's\n * total, moves the ids after it to the wrong ranks. An encrypted object's index is authenticated and bound to the\n * object, so a wrong count there needs the key.\n *\n * A live handle is refused with {@link UnsupportedError} at the first read, because its counts and its chunks could\n * come from two generations and name the wrong id. `n` that is not a positive integer throws\n * {@link ValidationError} at the first read, as does a bad bound.\n *\n * ```ts\n * const audience = await store.segment('audience').pin();\n * const ends: number[] = [];\n * for await (const id of audience.everyNth(1_000)) ends.push(id); // the end of each window of 1,000\n * ```\n */\n everyNth(n: number, options?: Pick<CombineOptions, 'after' | 'through'>): IdIterator {\n // The lease first: a leased handle past its lease throws, never reads empty.\n const lease = this.leaseError();\n if (lease !== undefined) return refusing(lease)();\n const bad = optionsError(options, 'everyNth', CALL_KEYS.range, [], MISPLACED.range);\n if (bad !== undefined) return refusing(bad)();\n if (this.pinnedAt === undefined) {\n return refusing(\n new UnsupportedError(\n 'everyNth needs a pinned handle: a live handle can place a rank by one generation ' +\n 'and read it from another. Call `pin()` first.',\n ),\n )();\n }\n const stream = this.engine.everyNth(\n this.ref,\n n,\n options == null ? undefined : rangeOf(options),\n );\n // A stream with no `.batches()`: guarded before its first pull, so a stream built live and pulled after the lease\n // ended throws even when no rank falls in its range, and at each chunk after that.\n return readsFrom(\n this.leaseHold === undefined ? stream : guardIdIterable(stream, () => this.assertLease()),\n this.origin,\n [this.key()],\n );\n }\n\n /**\n * The options a combine hands the engine, read once, when it is called ({@link readOptions}), with the `exclude`\n * it was given ({@link excludesOf}) and mapped down to the plain refs\n * `core` takes. A method rather than a module function because `ref` is class-private \u2014 the encapsulation is\n * worth more than the free function.\n *\n * Each field is named rather than copied with a rest spread: a rest copy takes only own enumerable properties, so\n * a bound held in a getter or inherited from a prototype was dropped, and the read silently widened to the whole\n * segment.\n */\n private refsIn(\n options: CombineOptions | null | undefined,\n exclude: readonly Segment[],\n ): (ReadOptions & { exclude?: SegmentRef[] }) | undefined {\n if (options == null) return undefined;\n return {\n ...readOptions(options),\n exclude: exclude.length > 0 ? exclude.map((o) => o.ref) : undefined,\n };\n }\n\n /**\n * The handles in `options.exclude`, read once so a getter sees one call. With none this is one property read and\n * a shared empty list; otherwise it is the caller's own array, so the common case allocates nothing.\n */\n private excludesOf(options: CombineOptions | null | undefined): readonly Segment[] {\n const exclude = options?.exclude;\n if (exclude == null) return NO_SEGMENTS;\n return segmentList(exclude, '`exclude`').length === 0 ? NO_SEGMENTS : exclude;\n }\n\n /**\n * Chunk-skipping intersection: stream the ids in **this** segment AND every segment in `others`, ascending.\n * Fetches only the Storage chunks present in *all* operands (a key absent from any operand contributes nothing\n * and is never downloaded), reading each operand's as coalesced ranges under a bounded in-flight window \u2014 so the Storage\n * footprint stays small (Lambda-friendly) regardless of segment size. Pass `concurrency` to tune that window (the range\n * requests held ahead per operand: a positive integer, 32 by default).\n * AND is commutative, so `a.intersect([b])` and `b.intersect([a])` yield the same ids. Pass `budget` to\n * override the store's per-op denial-of-wallet budget for this call (or `false` to lift it).\n *\n * Of {@link CombineOptions} it takes the range, `concurrency`, `budget`, `allowAbsentOperands` and `exclude`; a write\n * option (`audit`, `allowEmpty`, `guard`, `metadata`, `keep`) fails the stream with {@link ValidationError} when it is\n * first read, before any request. So does an empty `others`: an intersection over nothing has no meaning, and\n * to read every id of one segment, use {@link iterate}. (`union` and `andNot` read an empty list as `this`.)\n */\n intersect(others: Segment[], options?: CombineOptions): IdStream {\n const bad = optionsError(\n options,\n 'intersect',\n CALL_KEYS.combine,\n ['allowAbsentOperands'],\n MISPLACED.combine,\n );\n if (bad !== undefined) return failing(bad);\n return this.combineAs(AS_IDS, 'intersect', others, options ?? undefined);\n }\n\n /**\n * Materialize `this \u2229 others\u2026` (minus `exclude`) as a **new generation of `dest`** \u2014 `dest`'s previous contents\n * are superseded, not added to. Streaming + bounded-memory; the result is one immutable object published\n * as a load is (the pointer advances to it, fenced on the row), so readers of `dest` see either the old generation\n * or the new one, never a partial. Needs the\n * store built with a backend (throws {@link UnsupportedError} otherwise).\n *\n * **An empty result does NOT overwrite a non-empty destination.** A combine that comes out empty is far more\n * often a mistake upstream \u2014 a typo'd operand, an `exclude` that swallowed everything, an operand that has\n * not loaded yet \u2014 than an intent, and once it publishes it is indistinguishable from a correct run. So the\n * write is **refused and reported**: `published: false`, `reason: 'empty'`, and `dest` keeps what it had.\n * Pass `allowEmpty: true` when emptying the destination is the point.\n *\n * `guard` adds the same plausibility bounds `load()` takes \u2014 `minCardinality`, `minRetained` and `maxGrowth` \u2014 judged\n * against what `dest` held before. A refusal is **reported, not thrown**, exactly as on `load()`; branch on\n * `published`. A lost race is the one outcome that still throws ({@link WriteConflictError}), because a\n * materialisation that silently did not take effect is the one thing a caller cannot detect on its own.\n *\n * A call involving a handle whose lease has ended, or anything that is not a segment, is refused before any of this.\n * So is a `dest` that is also `this`, an operand or an exclude (the same segment by name and namespace, however the\n * handle was made), and, for `intersectInto` alone, an empty `others` (`unionInto` and `andNotInto` publish `this` for an\n * empty list): each throws {@link ValidationError} before any request. A destination that\n * is also a source would publish a result built from the generation this store last resolved over a newer load by\n * another process, with no conflict to report. This release has no fenced in-place update: write the result into a\n * new segment and point readers at it; a single writer that knows nothing else writes the segment may load the result\n * back, unfenced. To copy `src` into `dest`, call\n * `materializeMany({ operands: { src }, outputs: [{ dest, expr: { or: ['src'] } }], keep })`, which reads each chunk\n * once, at one instant.\n * It takes every field of {@link CombineOptions}, as `unionInto` does.\n */\n async intersectInto(\n dest: Segment,\n others: Segment[],\n options?: CombineOptions,\n ): Promise<MaterializeResult> {\n checkOptions(options, 'intersectInto', CALL_KEYS.into, ['allowEmpty', 'allowAbsentOperands']);\n return this.combineInto('intersectInto', dest, others, options);\n }\n\n /**\n * `this \u222A others\u2026`, minus `options.exclude` \u2014 streamed ascending.\n *\n * **The one composite read with no chunk-skipping,** and that is inherent to union rather than a limitation\n * here: an id in *any* operand belongs to the result, so every chunk of every operand must be read.\n * `intersect` prunes any key missing from any operand; union has nothing to prune. It is charged against the\n * same per-op budget, so a wide union is refused rather than quietly billed \u2014 pass `budget` to raise it\n * deliberately. If you find yourself unioning the same segments on every read, materializing the combined\n * segment once (`unionInto`, or a load) is the cheaper shape. It takes the options {@link intersect} takes, and an\n * empty `others` reads `this` itself.\n */\n union(others: Segment[], options?: CombineOptions): IdStream {\n const bad = optionsError(\n options,\n 'union',\n CALL_KEYS.combine,\n ['allowAbsentOperands'],\n MISPLACED.combine,\n );\n if (bad !== undefined) return failing(bad);\n return this.combineAs(AS_IDS, 'union', others, options ?? undefined);\n }\n\n /** Materialize `this \u222A others\u2026` (minus `exclude`) as a **new generation of `dest`** \u2014 see {@link intersectInto}. */\n async unionInto(\n dest: Segment,\n others: Segment[],\n options?: CombineOptions,\n ): Promise<MaterializeResult> {\n checkOptions(options, 'unionInto', CALL_KEYS.into, ['allowEmpty', 'allowAbsentOperands']);\n return this.combineInto('unionInto', dest, others, options);\n }\n\n /**\n * `this \\ (excludes\u2026)` \u2014 streamed ascending. Suppression on its own.\n *\n * Reads every chunk of `this` (any of them may survive the subtraction) but each exclude **only where it\n * overlaps this segment**, so the cost tracks the segment being filtered rather than the size of the\n * suppression list: at most one read per surviving key of `this`, so subtracting a 61,000-chunk global\n * opt-out list from a 40-chunk audience costs at most 40 reads, not 61,000.\n *\n * To filter the *result of an intersection*, do not chain \u2014 pass `exclude` to {@link intersect} instead, so\n * the suppression folds into the same pass rather than materializing an intermediate segment first.\n *\n * It takes the options {@link intersect} takes but `exclude`, since `excludes` is its subtraction: `exclude` or a write\n * option fails the stream with {@link ValidationError} when it is first read, before any request.\n */\n andNot(excludes: Segment[], options?: CombineOptions): IdStream {\n const bad = optionsError(\n options,\n 'andNot',\n CALL_KEYS.andNot,\n ['allowAbsentOperands'],\n MISPLACED.andNot,\n );\n if (bad !== undefined) return failing(bad);\n return this.combineAs(AS_IDS, 'andNot', excludes, options ?? undefined);\n }\n\n /**\n * Materialize `this \\ (excludes\u2026)` as a **new generation of `dest`** \u2014 see {@link intersectInto}. It takes every field\n * of {@link CombineOptions} but `exclude`, since `excludes` is its subtraction: `exclude` is refused with\n * {@link ValidationError} before any request.\n */\n async andNotInto(\n dest: Segment,\n excludes: Segment[],\n options?: CombineOptions,\n ): Promise<MaterializeResult> {\n checkOptions(\n options,\n 'andNotInto',\n CALL_KEYS.andNotInto,\n ['allowEmpty', 'allowAbsentOperands'],\n MISPLACED.andNotInto,\n );\n return this.combineInto('andNotInto', dest, excludes, options);\n }\n\n /**\n * How many ids `this \u2229 others\u2026` holds (minus `exclude`): the length of what {@link intersect} streams, without\n * streaming it. Every key all the operands hold is decoded and counted as the stream reads it, and a key only some\n * operands hold is not read, so the call makes the requests {@link intersect} makes and returns a number instead of\n * the ids. It is exact: it never answers a key from an index, so it trusts nothing {@link count} trusts.\n *\n * The range, `concurrency`, `budget`, `allowAbsentOperands` and `exclude` are {@link intersect}'s; a write option fails\n * the call with {@link ValidationError} before any request, and so does an empty `others` (to count one segment, use\n * {@link count}).\n *\n * Like a stream, a count that runs while a segment is erased or reloaded can describe two instants, within the bound\n * the streams state. A union or a difference, and an intersection with an `exclude`, looks at its operands'\n * generations every `concurrency` keys; an intersection with no `exclude` makes no such look, since it decodes every\n * key and so shows a move in the chunks it decodes, as its stream does. Either way it plans again above the last key\n * it took when one moved. A pinned handle counts the generation it pinned, and each pinned operand's object is\n * looked up once before the first key (one footer read each, which `budget` does not charge, and which the stream\n * does not make), and again at each look where there is one, so an erasure of what it pinned fails the count with\n * {@link NotFoundError}; a\n * fault the look meets other than a transient one, which is retried, is raised as it is. A call that involves a\n * handle whose lease has ended, or has ended by the next look, throws {@link LeaseExpiredError}.\n */\n async intersectCount(others: Segment[], options?: CombineOptions): Promise<number> {\n checkOptions(\n options,\n 'intersectCount',\n CALL_KEYS.intersectCount,\n ['allowAbsentOperands'],\n MISPLACED.intersectCount,\n );\n return this.countCombine('intersect', others, options ?? undefined);\n }\n\n /**\n * How many ids `this \u222A others\u2026` holds (minus `exclude`): the length of what {@link union} streams, without streaming\n * it. A chunk key only one operand holds, that no `exclude` holds and the range does not cut, is answered from that\n * operand's index, so a union of segments that mostly do not overlap reads little of them; every other key is\n * decoded and counted. On handles that are not pinned it makes no more requests than {@link union} does, and reads\n * fewer bytes when the shared keys are few. An empty `others`, with no `exclude` and no range, is {@link count} of\n * `this`, answered from the registry row when it can be; when that figure is 0 it adds one registry read, to refuse\n * a segment that does not exist as the stream does.\n *\n * What it trusts: the index, for each key it answers without decoding, as {@link count} does, so a party who can write\n * an object's index can make that key's figure wrong; a decoded key is exact. A source with no per-chunk counts\n * decodes every key. It takes the options {@link intersectCount} takes; the erasure bound, the lease checks and the\n * pinned handles are as for {@link intersectCount}, a pinned operand adding a footer read before the first key and at\n * each look. An empty `others` on a pinned handle is {@link count} of the pin, with no look.\n */\n async unionCount(others: Segment[], options?: CombineOptions): Promise<number> {\n checkOptions(\n options,\n 'unionCount',\n CALL_KEYS.unionCount,\n ['allowAbsentOperands'],\n MISPLACED.unionCount,\n );\n return this.countCombine('union', others, options ?? undefined);\n }\n\n /**\n * How many ids `this \\ (excludes\u2026)` holds: the length of what {@link andNot} streams, without streaming it. A chunk\n * key of `this` that no exclude holds and the range does not cut is answered from its index and not read; a key an\n * exclude shares is decoded and counted. On handles that are not pinned it makes no more requests than {@link andNot}\n * does, and reads fewer bytes when the excludes overlap little of `this`. An empty `excludes`, with no range, is\n * {@link count} of `this` (the stream of it is the whole of `this`), answered from the registry row when it can be,\n * with one registry read added when that figure is 0.\n *\n * It takes the options {@link andNot} takes (every one of {@link intersectCount}'s but `exclude`, which a count of a\n * difference has no use for, since `excludes` is its subtraction) and trusts what {@link unionCount} trusts. The\n * erasure bound, the lease checks and the pinned handles are as for {@link intersectCount}.\n */\n async andNotCount(excludes: Segment[], options?: CombineOptions): Promise<number> {\n checkOptions(\n options,\n 'andNotCount',\n CALL_KEYS.andNotCount,\n ['allowAbsentOperands'],\n MISPLACED.andNotCount,\n );\n return this.countCombine('andNot', excludes, options ?? undefined);\n }\n\n /** The one body of the three count methods, after each has checked its own options. */\n private async countCombine(\n verb: CombineVerb,\n operands: Segment[],\n options?: CombineOptions,\n ): Promise<number> {\n const name = `${verb}Count`;\n const exclude = verb === 'andNot' ? NO_SEGMENTS : this.excludesOf(options);\n const others = segmentList(\n operands,\n verb === 'andNot' ? `${name}: \\`excludes\\`` : `${name}: \\`others\\``,\n );\n if (verb === 'intersect' && others.length === 0) refuseNoOperands('intersectCount');\n const handles = [this, ...others, ...exclude];\n this.assertSegments(name, verb === 'andNot' ? 'an exclude' : 'an operand', others);\n this.assertSegments(name, 'an exclude', exclude);\n this.assertLeases(handles);\n const engine = this.combineEngine(handles) ?? this.engine;\n const read = options == null ? undefined : readOptions(options);\n const guard = handles.some((h) => h.leaseHold !== undefined)\n ? () => this.assertLeases(handles)\n : undefined;\n const opts = guard === undefined ? read : { ...read, guard };\n const refs = others.map((o) => o.ref);\n if (verb === 'andNot') return engine.combineCount([this.ref], refs, 'all', verb, opts);\n return engine.combineCount(\n [this.ref, ...refs],\n exclude.map((o) => o.ref),\n verb === 'union' ? 'any' : 'all',\n verb,\n opts,\n );\n }\n /**\n * The one body of the three combines, read as ids or as chunks. `operands` is `others` for `intersect` and\n * `union`, and `excludes` for `andNot`, which takes no `exclude` option.\n */\n private combineAs<T>(\n out: CombineOutput<T>,\n verb: CombineVerb,\n operands: Segment[],\n options?: CombineOptions,\n ): T {\n // Order of the checks: the lists are arrays, every handle is a segment, then no handle's lease has ended, all before\n // the engine is asked for anything, so a handle past its lease throws `LeaseExpiredError` and never reads empty.\n let exclude: readonly Segment[];\n let handles: readonly Segment[];\n try {\n exclude = verb === 'andNot' ? NO_SEGMENTS : this.excludesOf(options);\n const others = segmentList(operands, operandsLabel(verb));\n if (verb === 'intersect' && others.length === 0) refuseNoOperands('intersect');\n handles = [this, ...others, ...exclude];\n this.assertSegments(verb, verb === 'andNot' ? 'an exclude' : 'an operand', others);\n this.assertSegments(verb, 'an exclude', exclude);\n this.assertLeases(handles);\n } catch (err) {\n return out.failing(err);\n }\n let engine: SegmentEngine;\n try {\n engine = this.combineEngine([this, ...operands, ...exclude]) ?? this.engine;\n } catch (err) {\n return out.failing(err);\n }\n // A stream of ids remembers what it reads, for `store.load` ({@link STREAM_SOURCES}); a stream of chunks is not one.\n const keys = handles.map((h) => h.key());\n const known = (result: T): T =>\n (out as unknown) === AS_IDS ? (readsFrom(result as object, this.origin, keys) as T) : result;\n if (verb === 'andNot') {\n const refs = operands.map((o) => o.ref);\n const opts = options == null ? undefined : readOptions(options);\n return known(this.guarded(out, handles, out.andNot(engine, this.ref, refs, opts)));\n }\n const refs = [this.ref, ...operands.map((o) => o.ref)];\n const opts = this.refsIn(options, exclude);\n return known(\n this.guarded(\n out,\n handles,\n verb === 'union' ? out.union(engine, refs, opts) : out.intersect(engine, refs, opts),\n ),\n );\n }\n\n /** The one body of the three `*Into` verbs, after each has checked its own options. */\n private combineInto(\n name: `${CombineVerb}Into`,\n dest: Segment,\n operands: Segment[],\n options: CombineOptions | undefined,\n ): Promise<MaterializeResult> {\n const verb = name.slice(0, -'Into'.length) as CombineVerb;\n const listed = segmentList(\n operands,\n verb === 'andNot' ? `${name}: \\`excludes\\`` : `${name}: \\`others\\``,\n );\n const excludes = verb === 'andNot' ? NO_SEGMENTS : this.excludesOf(options);\n const all = excludes.length > 0 ? [...listed, ...excludes] : listed;\n this.assertIntoHandles(name, dest, listed, excludes);\n // Refused here, before `materialize` reads anything of `dest`, rather than when the load reads the combine: a\n // broken destination would otherwise answer first, and hide the refusal behind its own error.\n this.combineEngine([this, ...all]);\n return this.timed(name, () =>\n this.materialize(\n dest.ref,\n new CombineChunks(this.combineAs(AS_CHUNKS, verb, operands, options)),\n name,\n options,\n ),\n );\n }\n}\n\n// ---------------------------------------------------------------------------------------------------\n// What `@cloudbitmaps/roaring` re-exports from `@cloudbitmaps/core` and `@cloudbitmaps/core/node`, by name: the\n// types the store's signatures name, the backends, the errors and their classifier, and the helpers an\n// application calls. An application installs this package and imports from it alone. Nothing else of core's is\n// re-exported: its main entry is internal. The driver\n// contracts the store's signatures stop at (`IStorageDriver`, `IRegistryDriver`, `StorageBackend`,\n// `StorageChunkSource`, `IKeystore` and the registry's record types) are exported by `@cloudbitmaps/core/driver-kit`,\n// their one home, and not here: an application that has to name one imports it from there, or derives it\n// (`CloudRoaringOptions['storage']`, `NonNullable<EncryptionOptions['keystore']>`). A name added here is a public name\n// of this package, so add one on purpose: `tests/docs/api-reference-sync.test.ts` fails until the API reference lists\n// it.\n// ---------------------------------------------------------------------------------------------------\n// The backends and the keystore that need a Node builtin, which core exports from `@cloudbitmaps/core/node`.\nexport { MemoryStorage, LocalFsStorage, InProcessKeystore } from '@cloudbitmaps/core/node';\nexport type {\n InProcessKeystoreOptions,\n LocalFsStorageOptions,\n MemoryStorageOptions,\n} from '@cloudbitmaps/core/node';\n// The public bitmap class, also the one door that decodes portable bytes you hold. It is defined in `./bitmap`.\nexport { RoaringBitmap } from './bitmap';\nexport type { RoaringBitmapDeserializeOptions } from './bitmap';\nexport {\n // The retention policy helpers\n excludingReservedRows,\n readRetentionPolicy,\n // Errors and their copy-safe classifier\n CloudRoaringError,\n ValidationError,\n WriteConflictError,\n IntegrityError,\n NotFoundError,\n UnsupportedError,\n CapabilityError,\n TransientError,\n KeyUnavailableError,\n BudgetExceededError,\n LeaseExpiredError,\n LeaseLimitError,\n StaleOperandError,\n errorKind,\n // Metrics and audit\n CountingMetricsSink,\n RecordingAuditSink,\n} from '@cloudbitmaps/core';\nexport type {\n AuditEvent,\n Budget,\n BudgetOption,\n Clock,\n ConsistencyErrorEntry,\n ConsistencyIssue,\n ConsistencyReport,\n DestroyResult,\n DropResult,\n Entropy,\n EraseDeps,\n ErrorKind,\n ExportFailure,\n ExportFormat,\n ExportManifest,\n ExportOptions,\n ExportSink,\n ExportSkipped,\n ExportWriter,\n ExportedSegment,\n Expr,\n GenerationEntry,\n GenerationMetadata,\n IAuditSink,\n IMetricsSink,\n LoadGuard,\n LoadInput,\n LoadOptions,\n LoadRefusal,\n LoadResult,\n MaterializeManyFeedRecord,\n MaterializeManyOperandStats,\n MaterializeManyOutputStats,\n MaterializeManyStats,\n MetricEvent,\n MetricOpName,\n MetricsSnapshot,\n PinnedAt,\n PortableBitmap,\n PreflightCheck,\n PreflightResult,\n RetentionPolicy,\n RetireEntry,\n RetireExpiredOptions,\n RetireExpiredResult,\n RetryPolicy,\n Rng,\n RollbackResult,\n SegmentInfo,\n SegmentRef,\n SetRetentionResult,\n} from '@cloudbitmaps/core';\n", "/**\n * A storage driver that charges every **generation open** to a per-op budget, for `eraseSubject`.\n *\n * The budget counts fan-out in units of one backend read. `eraseSubject`'s scan charges one unit per registered\n * segment, but a segment whose current generation lacks the id is searched anyway: every other generation in its\n * bucket is opened, one tail read each, and with the keep-everything default of the `*Into` verbs that is one per\n * generation the segment ever had. Those opens are the work the scan's own count leaves out. They are counted here,\n * at the storage port where they happen, so an open added to the erasure later is charged without anyone\n * remembering to charge it, and no option of the public erasure call had to grow.\n *\n * Two opens are never charged, because the segment's unit already pays for them: the generation the row named when\n * the scan listed it, which every erasure must read to decide membership, and an object this call wrote itself,\n * which it reads back to verify. Every other generation is charged once, at its first open: a later open of the same\n * number in the same call is paid for by that unit. The look for a holder left once the call has deleted opens again\n * each generation it found clean, and an object whose open failed has its footer read on its own; neither costs a unit\n * more. A refusal here comes from a read. Most of an erasure's reads that can be refused come before its deletes; two\n * kinds come after one: the look for a holder left, when it opens a generation the call never opened before, and the\n * zero-byte read of a generation the call deleted that the row then names. A refusal of either is thrown in place of\n * the call's answer, so the call reports the budget, not what it deleted.\n */\nimport type {\n GenKey,\n IStorageDriver,\n SegmentRef,\n StorageDeleteOptions,\n} from '@cloudbitmaps/core/driver-kit';\n\nexport class OpenChargingStorage implements IStorageDriver {\n /** Generations an open of costs nothing more: the scan's current one, this call's writes, and each one charged. */\n private readonly free = new Set<number>();\n\n /**\n * @param inner the driver the erasure would otherwise use\n * @param current the generation the segment's row named when it was listed, or `null` when it named none\n * @param charge called once per charged open; it throws to refuse\n */\n constructor(\n private readonly inner: IStorageDriver,\n current: number | null,\n private readonly charge: () => void,\n ) {\n if (current !== null) this.free.add(current);\n }\n\n capabilities(): ReturnType<IStorageDriver['capabilities']> {\n return this.inner.capabilities();\n }\n\n async putImmutable(\n key: GenKey,\n write: Parameters<IStorageDriver['putImmutable']>[1],\n ): ReturnType<IStorageDriver['putImmutable']> {\n const written = await this.inner.putImmutable(key, write);\n this.free.add(key.generation);\n return written;\n }\n\n getRange(key: GenKey, offset: number, length: number): Promise<Uint8Array> {\n return this.inner.getRange(key, offset, length);\n }\n\n /**\n * One `getTail` is one open: a reader takes the footer and the index from it, and reads chunks with `getRange`. A\n * generation is charged at its first open only.\n */\n async getTail(key: GenKey, maxBytes: number): ReturnType<IStorageDriver['getTail']> {\n if (!this.free.has(key.generation)) {\n this.charge();\n this.free.add(key.generation);\n }\n return this.inner.getTail(key, maxBytes);\n }\n\n /** Handed through whole: the erasure's delete of a holder is conditioned on the object it searched. */\n delete(key: GenKey, options?: StorageDeleteOptions): Promise<void> {\n return this.inner.delete(key, options);\n }\n\n list(ref: SegmentRef): AsyncIterable<GenKey> {\n return this.inner.list(ref);\n }\n}\n", "/**\n * The facade's refusal of the namespace the library keeps for its own rows.\n *\n * `cbm.due.` is where the due index stores its pointers, and every fleet-wide scan skips a row there as\n * bookkeeping, so a segment in it would be invisible to an erasure, a consistency check, an export and a retention\n * sweep. `@cloudbitmaps/core` refuses the prefix in every call that takes a ref or a `namespace` option; this is a\n * copy of that one constant, for the checks the facade makes itself before anything reaches core (`segment()`,\n * `invalidate()` and the scope of the two subject scans, which read the registry directly). A test holds the copy\n * equal to core's, so the two cannot drift.\n *\n * Internal: not exported from the package entry.\n */\nimport { ValidationError } from '@cloudbitmaps/core';\n\nexport const RESERVED_NAMESPACE_PREFIX = 'cbm.due.';\n\n/** Throw `ValidationError` for a namespace in the reserved prefix; `undefined` and every look-alike pass. */\nexport function refuseReservedNamespace(namespace: string | undefined): void {\n if (namespace !== undefined && namespace.startsWith(RESERVED_NAMESPACE_PREFIX)) {\n throw new ValidationError(\n `namespace \"${namespace}\" is reserved: names starting with \"${RESERVED_NAMESPACE_PREFIX}\" hold the ` +\n `library's own bookkeeping rows, which every fleet-wide scan skips, so a segment there would be ` +\n `invisible to an erasure, a consistency check, an export and a retention sweep. Choose another namespace.`,\n );\n }\n}\n", "/**\n * A Roaring bitmap of unsigned 32-bit ids in TypeScript, behind the codec seam: {@link tsRoaringCodec} is a\n * `CodecInterface` that stores the same portable Roaring bytes as CRoaring (through `roaring`, the reference the tests compare it\n * against), with no native addon.\n *\n * It implements the data structure of Chambi, Lemire, Kaser and Godin, \"Better bitmap performance with Roaring bitmaps\"\n * (2016), with the run containers of Lemire, Ssi-Yan-Kai and Kaser, \"Consistently faster and smaller compressed bitmaps\n * with Roaring\" (2016), and the implementation notes of Lemire et al., \"Roaring Bitmaps: Implementation of an Optimized\n * Software Library\" (2018); the links are in the package README's credits. An id is split into a 16-bit key and a 16-bit\n * remainder; the remainders of one key sit in a container (an array, a bitset or runs: `containers.ts`), and the\n * containers sit in ascending key order beside their keys. The portable bytes are `wire.ts`.\n *\n * TsBitmap\n * keys: [ 0 3 40000 ] ascending 16-bit keys\n * conts: [ ARRAY RUN BITSET ] one container each, with its cardinality kept\n * size: total cardinality, kept as containers change\n *\n * What it keeps to, which the oracle suite holds it to against CRoaring and against the stored-byte rule:\n *\n * - `serialize()` writes the containers as they are: one made from ids is an array or a bitset by cardinality, one\n * decoded from run bytes stays a run until it changes;\n * - `optimize()` re-encodes each container canonically (a run only when strictly smaller than the plain body), so\n * `serialize()` afterwards depends on the set alone;\n * - `safeDeserialize` runs the layout check first (`portable/layout.ts`), so the structure every operation assumes is\n * proven before a container is built, and refuses what CRoaring's validator refuses, with `IntegrityError`;\n * - a combine never changes its operand. A key only this bitmap holds keeps its container by reference (it can be a\n * run), an unshared bitset's words are reused in place, and a key only the operand holds is copied in for a union or\n * an exclusive-or; a pair of containers combines into an array or a bitset, except that two run containers (for\n * and, or, andNot and xor) and a run with an array (for or alone) keep a run result while it is the smaller form\n * (the written rule is in `containers.ts`).\n * - `clone` shares every container with the original and flags it, so the first write on either side copies it.\n *\n * `andCardinality` (and the or, xor and andNot counts derived from it), `intersects`, `isSubset` and `isEqual` answer from\n * the containers without building a result: they change neither bitmap and allocate nothing per call.\n *\n * Writing an id that is not an integer from 0 to 4,294,967,295 throws `ValidationError`; reading one (`has`) says no\n * and removing one does nothing. A combine works on each pair of containers by their kinds (`containers.ts` has the\n * table), `addMany` and `removeMany` group sorted ids by key and touch each container once, and iteration is a class\n * that walks the containers where they are (`iterator.ts`; a bitmap must not be mutated while it is iterated).\n *\n * `encodeChunks` takes a snapshot of the containers and marks each shared, so the bitmap may change while the chunks\n * are read: a change copies a shared container first, and the chunks stay what they were when it was called. It\n * optimizes and serializes one container per step, so a writer can yield between steps. Membership and bytes are\n * unchanged, but every container is now flagged shared, so the next write to each copies it once.\n *\n * @see https://github.com/RoaringBitmap/RoaringFormatSpec\n */\nimport type { CodecBitmap, CodecInterface, EncodedChunk } from '@cloudbitmaps/core';\nimport { IntegrityError, ValidationError, refusalOfId } from '@cloudbitmaps/core';\nimport {\n Container,\n appendIds,\n arrayContainer,\n cloneContainer,\n containerAdd,\n containerAddSorted,\n containerAnd,\n containerAndCard,\n containerAndNot,\n containerHas,\n containerMax,\n containerMin,\n containerOr,\n containerRemove,\n containerXor,\n containersEqual,\n containersIntersect,\n containersSubset,\n fromSortedIds,\n optimize,\n orManyContainers,\n orRunIdsWalk,\n RUN,\n walksRunIds,\n} from './containers';\nimport { BitmapIterator } from './iterator';\nimport { decodeContainers, serializeContainers, trailingBytes } from './wire';\n\nconst MAX_ID = 0xffff_ffff;\n\nfunction isId(value: number): boolean {\n return Number.isInteger(value) && value >= 0 && value <= MAX_ID;\n}\n\nfunction checkedId(value: number): number {\n if (!isId(value)) throw refusalOfId(value);\n return value;\n}\n\n/**\n * The ids of `values`, checked, as a `Uint32Array`: `values` itself when it is one (every element of it is an id), else\n * a new one the caller may sort. An array is read once; another iterable is read once into a buffer that doubles, so no\n * intermediate array of the ids is built.\n */\nexport function collect(values: Iterable<number>): Uint32Array {\n if (values instanceof Uint32Array) return values;\n if (Array.isArray(values)) {\n const list = values as number[];\n const out = new Uint32Array(list.length);\n let i = 0;\n try {\n for (; i < list.length; i++) {\n const v = list[i] as number;\n // `v >>> 0 === v` is an integer from 0 to 2^32 - 1 and nothing else (NaN, fractions, strings and null fail it).\n if (v >>> 0 !== v) throw refusalOfId(v);\n out[i] = v;\n }\n } catch (error) {\n // `>>>` coerces a value that is not a number, and the coercion can throw (a BigInt, a Symbol, an object with no\n // primitive form, a `valueOf` that throws): whatever fails on a value that is not a number is that value's\n // refusal, and a check per value to tell it apart in the loop would cost every build. A failure on a number\n // (its own refusal, or a getter that throws) is rethrown as it is.\n const v: unknown = list[i];\n if (typeof v !== 'number') throw refusalOfId(v);\n throw error;\n }\n return out;\n }\n let out = new Uint32Array(1_024);\n let n = 0;\n for (const v of values) {\n if (n === out.length) {\n const grown = new Uint32Array(2 * n);\n grown.set(out);\n out = grown;\n }\n out[n++] = checkedId(v);\n }\n return out.subarray(0, n);\n}\n\n/** The ids of `values` that are ids, in a new `Uint32Array`: what a removal acts on, which ignores the rest. */\nfunction collectLenient(values: Iterable<number>): Uint32Array {\n if (values instanceof Uint32Array) return values.slice();\n const list = Array.isArray(values) ? (values as number[]) : Array.from(values);\n const out = new Uint32Array(list.length);\n let n = 0;\n for (let i = 0; i < list.length; i++) {\n const v = list[i] as number;\n if (v >>> 0 === v) out[n++] = v;\n }\n return out.subarray(0, n);\n}\n\n/** The most ids one key's group of an `addMany` can hold and still go into its container one id at a time. */\nconst FEW_IDS = 4;\n\n/**\n * How `addMany` writes a group of `count` ids into the container `before` that its key already holds: `few` (each id put\n * into it), `walk` (a run container merged with the ids where they are) or `merge` (a container built for the group,\n * then merged).\n */\nexport function groupPath(before: Container, count: number): 'few' | 'walk' | 'merge' {\n if (count <= FEW_IDS) return 'few';\n return walksRunIds(before, count) ? 'walk' : 'merge';\n}\n\n/**\n * `ids` ascending: itself when it already is, else sorted, in place when `owned` (a new array that is the caller's own)\n * and in a copy when it is the caller's.\n */\nfunction sortedIds(ids: Uint32Array, owned: boolean): Uint32Array {\n for (let i = 1; i < ids.length; i++) {\n if ((ids[i - 1] as number) > (ids[i] as number)) return (owned ? ids : ids.slice()).sort();\n }\n return ids;\n}\n\n/** The index of the first of the ascending `keys`, from index `from`, that is `>= key`. */\nfunction lowerBound(keys: readonly number[], key: number, from = 0): number {\n let lo = from;\n let hi = keys.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if ((keys[mid] as number) < key) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n}\n\n/** Like {@link lowerBound}, but by doubling steps from `from`, so it costs the log of the distance, not of the length. */\nfunction gallopKeys(keys: readonly number[], key: number, from: number): number {\n let step = 1;\n let lo = from;\n let hi = from;\n while (hi < keys.length && (keys[hi] as number) < key) {\n lo = hi + 1;\n hi += step;\n step *= 2;\n }\n return lowerBoundIn(keys, key, lo, Math.min(hi, keys.length));\n}\n\nfunction lowerBoundIn(keys: readonly number[], key: number, from: number, to: number): number {\n let lo = from;\n let hi = to;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if ((keys[mid] as number) < key) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n}\n\nconst OR = 0;\nconst AND = 1;\nconst AND_NOT = 2;\nconst XOR = 3;\ntype Combine = typeof OR | typeof AND | typeof AND_NOT | typeof XOR;\n\nfunction combineContainers(op: Combine, a: Container, b: Container): Container | null {\n if (op === OR) return containerOr(a, b, !a.shared || a.kind === RUN);\n if (op === AND) return containerAnd(a, b, !a.shared);\n if (op === XOR) return containerXor(a, b, !a.shared);\n return containerAndNot(a, b, !a.shared);\n}\n\nexport class TsBitmap implements CodecBitmap {\n #keys: number[];\n #conts: Container[];\n #size: number;\n\n private constructor(keys: number[], conts: Container[], size: number) {\n this.#keys = keys;\n this.#conts = conts;\n this.#size = size;\n }\n\n static empty(): TsBitmap {\n return new TsBitmap([], [], 0);\n }\n\n static fromValues(values: Iterable<number>): TsBitmap {\n const bitmap = TsBitmap.empty();\n bitmap.addMany(values);\n return bitmap;\n }\n\n /**\n * Cap the size, check the structure, then build the containers. With `whole`, bytes after the last container are\n * refused too; without it they are ignored. With `detached`, every container gets storage of its own, copied out of\n * the input, so nothing the result holds is a view of one shared buffer: a bitmap that is kept and then reduced\n * does not keep the whole input alive.\n *\n * @throws {IntegrityError} if the input exceeds `maxBytes`, is not a well-formed portable bitmap, or (with `whole`)\n * has bytes after it.\n */\n static safeDeserialize(\n bytes: Uint8Array,\n maxBytes: number,\n options: { readonly whole?: boolean; readonly detached?: boolean } = {},\n ): TsBitmap {\n if (bytes.length > maxBytes) {\n throw new IntegrityError(`serialized bitmap is ${bytes.length}B, exceeds cap ${maxBytes}B`);\n }\n const { keys, conts, end } = decodeContainers(bytes, options.detached === true);\n if (options.whole === true && end !== bytes.byteLength) {\n throw trailingBytes(bytes.byteLength, end);\n }\n let size = 0;\n for (let i = 0; i < conts.length; i++) size += (conts[i] as Container).card;\n return new TsBitmap(keys, conts, size);\n }\n\n serialize(): Uint8Array {\n return serializeContainers(this.#keys, this.#conts);\n }\n\n /** Re-encode each container canonically; membership is untouched. */\n optimize(): void {\n const conts = this.#conts;\n for (let i = 0; i < conts.length; i++) conts[i] = optimize(conts[i] as Container);\n }\n\n /** Whether at least one container is held as runs. */\n hasRunContainer(): boolean {\n for (let i = 0; i < this.#conts.length; i++)\n if ((this.#conts[i] as Container).kind === RUN) return true;\n return false;\n }\n\n /**\n * The set as storage chunks: each payload is the portable bytes of a one-container bitmap holding that chunk's low 16\n * bits, optimized the way {@link optimize} does. Nothing is built until a chunk is asked for, so a writer that yields\n * between chunks runs this in slices. The call snapshots the containers and marks each shared, so a change to the\n * bitmap while the chunks are read copies a container instead of altering what the chunks will say. The bitmap's own\n * containers are not optimized by it.\n */\n encodeChunks(): Iterable<EncodedChunk> {\n const keys = this.#keys.slice();\n const conts = this.#conts.slice();\n for (let i = 0; i < conts.length; i++) (conts[i] as Container).shared = true;\n return {\n *[Symbol.iterator](): Iterator<EncodedChunk> {\n for (let i = 0; i < conts.length; i++) {\n const c = optimize(conts[i] as Container);\n yield {\n chunkKey: keys[i] as number,\n payload: serializeContainers([0], [c]),\n cardinality: c.card,\n };\n }\n },\n };\n }\n\n /** The smallest id, or `undefined` when the bitmap is empty. */\n minimum(): number | undefined {\n if (this.#conts.length === 0) return undefined;\n return (this.#keys[0] as number) * 65_536 + containerMin(this.#conts[0] as Container);\n }\n\n maximum(): number | undefined {\n const last = this.#conts.length - 1;\n if (last < 0) return undefined;\n return (this.#keys[last] as number) * 65_536 + containerMax(this.#conts[last] as Container);\n }\n\n add(value: number): void {\n checkedId(value);\n const key = value >>> 16;\n const low = value & 0xffff;\n const at = lowerBound(this.#keys, key);\n const found = this.#keys[at] === key;\n if (!found) {\n this.#insert(at, key, arrayContainer(Uint16Array.of(low), 1));\n this.#size++;\n return;\n }\n const before = this.#conts[at] as Container;\n const after = containerAdd(before, low);\n this.#conts[at] = after;\n this.#size += after.card - before.card;\n }\n\n /**\n * Add the ids. They are grouped by key in ascending order, so each container is touched once, a key already held is\n * merged where it is, and the new keys are put in with one pass over the key list however many there are.\n */\n addMany(values: Iterable<number>): void {\n const ids = sortedIds(collect(values), !(values instanceof Uint32Array));\n const fresh: Array<{ key: number; group: Container }> = [];\n let at = 0;\n for (let i = 0; i < ids.length;) {\n const key = (ids[i] as number) >>> 16;\n let end = i + 1;\n while (end < ids.length && (ids[end] as number) >>> 16 === key) end++;\n const first = i;\n i = end;\n at = gallopKeys(this.#keys, key, at);\n if (this.#keys[at] === key) {\n const before = this.#conts[at] as Container;\n // A group of a few goes into the container it meets without a container of its own. A run container is never\n // written in place, so the result may be it when the ids add nothing.\n // A larger group into a run container is walked from the ids, again with no container for the group.\n const path = groupPath(before, end - first);\n const after =\n path === 'few'\n ? containerAddSorted(before, ids, first, end)\n : path === 'walk'\n ? orRunIdsWalk(before, ids, first, end)\n : containerOr(\n before,\n fromSortedIds(ids, first, end),\n !before.shared || before.kind === RUN,\n );\n this.#conts[at] = after;\n this.#size += after.card - before.card;\n } else {\n const group = fromSortedIds(ids, first, end);\n fresh.push({ key, group });\n this.#size += group.card;\n }\n }\n if (fresh.length > 0) this.#insertAll(fresh);\n }\n\n /** Remove the id (anything that is not an id is ignored); whether it was there. */\n remove(value: number): boolean {\n if (!isId(value)) return false;\n const key = value >>> 16;\n const at = lowerBound(this.#keys, key);\n if (this.#keys[at] !== key) return false;\n const before = this.#conts[at] as Container;\n const after = containerRemove(before, value & 0xffff);\n if (after === null) {\n this.#keys.splice(at, 1);\n this.#conts.splice(at, 1);\n this.#size -= before.card;\n return true;\n }\n this.#conts[at] = after;\n this.#size += after.card - before.card;\n return after.card !== before.card;\n }\n\n /** Remove every id. Containers a clone shares are left to it. */\n clear(): void {\n this.#keys = [];\n this.#conts = [];\n this.#size = 0;\n }\n\n /** Remove the ids (anything that is not an id is ignored), grouped by key; the keys left empty go in one pass. */\n removeMany(values: Iterable<number>): void {\n const ids = sortedIds(collectLenient(values), true);\n const keys = this.#keys;\n const conts = this.#conts;\n let at = 0;\n let emptied = 0;\n for (let i = 0; i < ids.length;) {\n const key = (ids[i] as number) >>> 16;\n let end = i + 1;\n while (end < ids.length && (ids[end] as number) >>> 16 === key) end++;\n const from = i;\n i = end;\n at = gallopKeys(keys, key, at);\n if (keys[at] !== key) continue;\n const before = conts[at] as Container;\n if (before.card === 0) continue;\n const after = containerAndNot(before, fromSortedIds(ids, from, end), !before.shared);\n this.#size -= before.card - (after === null ? 0 : after.card);\n if (after === null) {\n conts[at] = EMPTIED;\n emptied++;\n } else {\n conts[at] = after;\n }\n }\n if (emptied > 0) this.#dropEmptied();\n }\n\n has(value: number): boolean {\n if (!isId(value)) return false;\n const key = value >>> 16;\n const at = lowerBound(this.#keys, key);\n return this.#keys[at] === key && containerHas(this.#conts[at] as Container, value & 0xffff);\n }\n\n get size(): number {\n return this.#size;\n }\n\n get isEmpty(): boolean {\n return this.#size === 0;\n }\n\n clone(): TsBitmap {\n const conts = new Array<Container>(this.#conts.length);\n // The copy shares each container with this bitmap and both mark it shared, so the first write on either side copies\n // it; a clone that is only read, or combined into fresh containers, never pays for a copy.\n for (let i = 0; i < conts.length; i++) {\n const c = this.#conts[i] as Container;\n c.shared = true;\n conts[i] = c;\n }\n return new TsBitmap(this.#keys.slice(), conts, this.#size);\n }\n\n orInPlace(other: CodecBitmap): void {\n this.#combine(TsBitmap.#of(other), OR);\n }\n\n andInPlace(other: CodecBitmap): void {\n this.#combine(TsBitmap.#of(other), AND);\n }\n\n andNotInPlace(other: CodecBitmap): void {\n this.#combine(TsBitmap.#of(other), AND_NOT);\n }\n\n /** Flip the ids `other` holds, in one pass over the pair of each key. */\n xorInPlace(other: CodecBitmap): void {\n this.#combine(TsBitmap.#of(other), XOR);\n }\n\n /** How many ids both bitmaps hold, counted without building the intersection. */\n andCardinality(other: CodecBitmap): number {\n const that = TsBitmap.#of(other);\n const a = this.#keys;\n const b = that.#keys;\n let n = 0;\n let i = 0;\n let j = 0;\n while (i < a.length && j < b.length) {\n const ka = a[i] as number;\n const kb = b[j] as number;\n if (ka === kb) {\n n += containerAndCard(this.#conts[i++] as Container, that.#conts[j++] as Container);\n } else if (ka < kb) {\n i = gallopKeys(a, kb, i + 1);\n } else {\n j = gallopKeys(b, ka, j + 1);\n }\n }\n return n;\n }\n\n /** How many ids either bitmap holds. */\n orCardinality(other: CodecBitmap): number {\n return this.#size + TsBitmap.#of(other).#size - this.andCardinality(other);\n }\n\n /** How many ids exactly one of the bitmaps holds. */\n xorCardinality(other: CodecBitmap): number {\n return this.#size + TsBitmap.#of(other).#size - 2 * this.andCardinality(other);\n }\n\n /** How many ids this bitmap holds that `other` lacks. */\n andNotCardinality(other: CodecBitmap): number {\n return this.#size - this.andCardinality(other);\n }\n\n /** Whether the bitmaps share an id; stops at the first one found. */\n intersects(other: CodecBitmap): boolean {\n const that = TsBitmap.#of(other);\n const a = this.#keys;\n const b = that.#keys;\n let i = 0;\n let j = 0;\n while (i < a.length && j < b.length) {\n const ka = a[i] as number;\n const kb = b[j] as number;\n if (ka === kb) {\n if (containersIntersect(this.#conts[i++] as Container, that.#conts[j++] as Container)) {\n return true;\n }\n } else if (ka < kb) {\n i = gallopKeys(a, kb, i + 1);\n } else {\n j = gallopKeys(b, ka, j + 1);\n }\n }\n return false;\n }\n\n /** Whether every id of this bitmap is in `other`; stops at the first container that is not inside its partner. */\n isSubset(other: CodecBitmap): boolean {\n const that = TsBitmap.#of(other);\n if (this.#size > that.#size) return false;\n const a = this.#keys;\n const b = that.#keys;\n let j = 0;\n for (let i = 0; i < a.length; i++) {\n j = gallopKeys(b, a[i] as number, j);\n if (j === b.length || b[j] !== a[i]) return false;\n const c = this.#conts[i] as Container;\n if (!containersSubset(c, that.#conts[j++] as Container)) return false;\n }\n return true;\n }\n\n /** Whether both hold the same ids, whatever the kinds of their containers. */\n isEqual(other: CodecBitmap): boolean {\n const that = TsBitmap.#of(other);\n if (this.#size !== that.#size || this.#keys.length !== that.#keys.length) return false;\n for (let i = 0; i < this.#keys.length; i++) {\n if (this.#keys[i] !== that.#keys[i]) return false;\n if (!containersEqual(this.#conts[i] as Container, that.#conts[i] as Container)) return false;\n }\n return true;\n }\n\n [Symbol.iterator](): IterableIterator<number> {\n return new BitmapIterator(this.#keys, this.#conts);\n }\n\n toArray(): number[] {\n return Array.from(this.toUint32Array());\n }\n\n /** The ids as a new ascending `Uint32Array`. */\n toUint32Array(): Uint32Array {\n const out = new Uint32Array(this.#size);\n let at = 0;\n for (let i = 0; i < this.#conts.length; i++) {\n at = appendIds(this.#conts[i] as Container, out, at, (this.#keys[i] as number) * 65_536);\n }\n return out;\n }\n\n static #of(other: CodecBitmap): TsBitmap {\n if (!(other instanceof TsBitmap)) {\n throw new ValidationError('a TypeScript roaring bitmap combines only with another one');\n }\n return other;\n }\n\n #insert(at: number, key: number, container: Container): void {\n if (at === this.#keys.length) {\n this.#keys.push(key);\n this.#conts.push(container);\n } else {\n this.#keys.splice(at, 0, key);\n this.#conts.splice(at, 0, container);\n }\n }\n\n /** Put the new keys, ascending and none held, in: after the last key by pushing, else in one merge pass. */\n #insertAll(fresh: ReadonlyArray<{ key: number; group: Container }>): void {\n const keys = this.#keys;\n const conts = this.#conts;\n if (\n keys.length === 0 ||\n (keys[keys.length - 1] as number) < (fresh[0] as { key: number }).key\n ) {\n for (const { key, group } of fresh) {\n keys.push(key);\n conts.push(group);\n }\n return;\n }\n const outKeys: number[] = [];\n const outConts: Container[] = [];\n let i = 0;\n let j = 0;\n while (i < keys.length || j < fresh.length) {\n if (\n j === fresh.length ||\n (i < keys.length && (keys[i] as number) < (fresh[j] as { key: number }).key)\n ) {\n outKeys.push(keys[i] as number);\n outConts.push(conts[i++] as Container);\n } else {\n const next = fresh[j++] as { key: number; group: Container };\n outKeys.push(next.key);\n outConts.push(next.group);\n }\n }\n this.#keys = outKeys;\n this.#conts = outConts;\n }\n\n /** Remove the keys whose container was emptied by {@link removeMany}, in one pass. */\n #dropEmptied(): void {\n let kept = 0;\n for (let i = 0; i < this.#conts.length; i++) {\n if (this.#conts[i] === EMPTIED) continue;\n this.#keys[kept] = this.#keys[i] as number;\n this.#conts[kept++] = this.#conts[i] as Container;\n }\n this.#keys.length = kept;\n this.#conts.length = kept;\n }\n\n /**\n * Walk both key lists and rebuild this one: where both hold a key, the combine of the two containers; where only this\n * does, its container, unless the operation is an intersection; where only `that` does, a copy of its container for a\n * union and nothing otherwise. A combine that leaves no value drops the key. An intersection jumps over a stretch of\n * keys the other side lacks by doubling steps, so a few keys against many cost the few.\n */\n #combine(that: TsBitmap, op: Combine): void {\n const a = this.#keys;\n const b = that.#keys;\n const ca = this.#conts;\n const cb = that.#conts;\n const keys: number[] = [];\n const conts: Container[] = [];\n let size = 0;\n let i = 0;\n let j = 0;\n while (i < a.length && j < b.length) {\n const ka = a[i] as number;\n const kb = b[j] as number;\n if (ka === kb) {\n const c = combineContainers(op, ca[i++] as Container, cb[j++] as Container);\n if (c !== null) {\n keys.push(ka);\n conts.push(c);\n size += c.card;\n }\n } else if (ka < kb) {\n if (op === AND) {\n i = gallopKeys(a, kb, i + 1);\n } else {\n keys.push(ka);\n conts.push(ca[i] as Container);\n size += (ca[i++] as Container).card;\n }\n } else if (op === AND) {\n j = gallopKeys(b, ka, j + 1);\n } else {\n if (op === OR || op === XOR) {\n keys.push(kb);\n conts.push(cloneContainer(cb[j] as Container));\n size += (cb[j] as Container).card;\n }\n j++;\n }\n }\n if (op !== AND) {\n for (; i < a.length; i++) {\n keys.push(a[i] as number);\n conts.push(ca[i] as Container);\n size += (ca[i] as Container).card;\n }\n }\n if (op === OR || op === XOR) {\n for (; j < b.length; j++) {\n keys.push(b[j] as number);\n conts.push(cloneContainer(cb[j] as Container));\n size += (cb[j] as Container).card;\n }\n }\n this.#keys = keys;\n this.#conts = conts;\n this.#size = size;\n }\n\n /** The ids both bitmaps hold, as a new bitmap; neither operand changes and no container of either is kept. */\n static and(a: CodecBitmap, b: CodecBitmap): TsBitmap {\n return TsBitmap.#fresh(TsBitmap.#of(a), TsBitmap.#of(b), AND);\n }\n\n /** The ids either holds, as a new bitmap; neither operand changes. */\n static or(a: CodecBitmap, b: CodecBitmap): TsBitmap {\n return TsBitmap.#fresh(TsBitmap.#of(a), TsBitmap.#of(b), OR);\n }\n\n /**\n * The ids any of `bitmaps` holds, as a new bitmap that owns all its storage; no operand changes and none is flagged.\n * The containers of each key are gathered across the inputs and united in one pass (see {@link orManyContainers}),\n * counted once. A key only one input holds is copied as it is, a run included.\n */\n static orMany(bitmaps: readonly CodecBitmap[]): TsBitmap {\n const byKey = new Map<number, Container[]>();\n for (const input of bitmaps) {\n const that = TsBitmap.#of(input);\n for (let i = 0; i < that.#keys.length; i++) {\n const key = that.#keys[i] as number;\n const held = byKey.get(key);\n if (held === undefined) byKey.set(key, [that.#conts[i] as Container]);\n else held.push(that.#conts[i] as Container);\n }\n }\n const keys = Array.from(byKey.keys()).sort((x, y) => x - y);\n const conts: Container[] = [];\n let size = 0;\n for (const key of keys) {\n const held = byKey.get(key) as Container[];\n const c = held.length === 1 ? cloneContainer(held[0] as Container) : orManyContainers(held);\n conts.push(c);\n size += c.card;\n }\n return new TsBitmap(keys, conts, size);\n }\n\n /** The ids exactly one holds, as a new bitmap; neither operand changes. */\n static xor(a: CodecBitmap, b: CodecBitmap): TsBitmap {\n return TsBitmap.#fresh(TsBitmap.#of(a), TsBitmap.#of(b), XOR);\n }\n\n /** The ids of `a` that `b` lacks, as a new bitmap; neither operand changes. */\n static andNot(a: CodecBitmap, b: CodecBitmap): TsBitmap {\n return TsBitmap.#fresh(TsBitmap.#of(a), TsBitmap.#of(b), AND_NOT);\n }\n\n /**\n * The same walk as {@link TsBitmap.#combine}, building a new bitmap and leaving both operands whole. Where both hold\n * a key, the pair combines into a fresh container (the in-place form is never taken, so no storage of either operand\n * is written). A container only `x` holds is kept by reference and flagged shared, so a later write to `x` or to the\n * result copies it once; for an intersection nothing of `x` is kept, so nothing is flagged. A container only `y`\n * holds is copied in for a union or a symmetric difference.\n */\n static #fresh(x: TsBitmap, y: TsBitmap, op: Combine): TsBitmap {\n const a = x.#keys;\n const b = y.#keys;\n const ca = x.#conts;\n const cb = y.#conts;\n const keys: number[] = [];\n const conts: Container[] = [];\n let size = 0;\n let i = 0;\n let j = 0;\n while (i < a.length && j < b.length) {\n const ka = a[i] as number;\n const kb = b[j] as number;\n if (ka === kb) {\n const c = freshPair(op, ca[i++] as Container, cb[j++] as Container);\n if (c !== null) {\n keys.push(ka);\n conts.push(c);\n size += c.card;\n }\n } else if (ka < kb) {\n if (op === AND) {\n i = gallopKeys(a, kb, i + 1);\n } else {\n const c = ca[i++] as Container;\n c.shared = true;\n keys.push(ka);\n conts.push(c);\n size += c.card;\n }\n } else if (op === AND) {\n j = gallopKeys(b, ka, j + 1);\n } else {\n if (op === OR || op === XOR) {\n keys.push(kb);\n conts.push(cloneContainer(cb[j] as Container));\n size += (cb[j] as Container).card;\n }\n j++;\n }\n }\n if (op !== AND) {\n for (; i < a.length; i++) {\n const c = ca[i] as Container;\n c.shared = true;\n keys.push(a[i] as number);\n conts.push(c);\n size += c.card;\n }\n }\n if (op === OR || op === XOR) {\n for (; j < b.length; j++) {\n keys.push(b[j] as number);\n conts.push(cloneContainer(cb[j] as Container));\n size += (cb[j] as Container).card;\n }\n }\n return new TsBitmap(keys, conts, size);\n }\n}\n\n/** A pair of containers combined into a container of its own (`null` when nothing is left); neither is written. */\nfunction freshPair(op: Combine, a: Container, b: Container): Container | null {\n if (op === OR) return containerOr(a, b, false);\n if (op === AND) return containerAnd(a, b, false);\n if (op === AND_NOT) return containerAndNot(a, b, false);\n return containerXor(a, b, false);\n}\n\n/** Stands for a container {@link TsBitmap.removeMany} emptied, until the keys left empty are dropped. */\nconst EMPTIED = arrayContainer(new Uint16Array(0), 0);\n\n/** The TypeScript Roaring codec: the same portable bytes as CRoaring, with no native addon. */\nexport const tsRoaringCodec: CodecInterface = {\n empty: () => TsBitmap.empty(),\n fromValues: (values) => TsBitmap.fromValues(values),\n safeDeserialize: (bytes, maxBytes, options) => TsBitmap.safeDeserialize(bytes, maxBytes, options),\n owns: (bitmap) => bitmap instanceof TsBitmap,\n intersectSmallestFirst: true,\n};\n", "/**\n * The layout of a portable-roaring bitmap: parsed, and checked for the structure every reader of it assumes.\n *\n * WHY THIS EXISTS. A decoder that only promises never to read past the buffer (CRoaring's safe deserialize, which\n * the `roaring` package calls, is one) takes every other invariant of the format on trust from bytes that come off a\n * storage tier, which hard invariant 5 says are hostile until proven otherwise. This check is what the TypeScript\n * decoder runs before it builds a bitmap, and the tests hold it to CRoaring's. What `roaring` 2.7.0, the native\n * reference, does with such bytes when nothing checks them first:\n *\n * - **Containers out of order.** `maximum()` reads the last container, so a chunk payload listing container 1\n * before container 0 passes the engine's 16-bit range check, and a read then yields container 1's values masked\n * into the chunk: ids the segment does not hold, which `has()` denies.\n * - **Values or runs out of order, duplicated or overlapping.** `has()` binary-searches, so it denies values that\n * iteration yields, `size` counts duplicates, and a range read stops early.\n * - **A run past the end of its container.** `maximum()` wraps to a small value, so the range check passes, and\n * iteration yields values from the next container's id space.\n * - **A run container with no runs.** Iterating it, or intersecting or unioning with it, crashes the process.\n * - **A bitset whose header cardinality disagrees with its bits.** `size` answers the header. Where the header\n * says fewer values than the bits hold, `remove()` converts the container into an array sized by the header and\n * writes every bit into it: a heap overflow in the native library, and then a crash.\n *\n * None of those is caught by a CRC, which proves only that the bytes are the bytes that were written. Anyone who\n * can write the bucket writes those.\n *\n * WHAT IT CHECKS, which is what CRoaring's `roaring_bitmap_internal_validate` checks, stated on the serialized form: container\n * keys strictly ascend; array values strictly ascend; runs ascend, stay inside their container, and neither overlap\n * nor touch (a writer merges touching runs); a run container has at least one run; a bitset's popcount is the\n * cardinality its header states. And two things CRoaring's deserializer ignores and this library's readers use: every\n * offset in the offset header is where its container really starts, and a run container's header cardinality is\n * the number of values its runs cover. Anything a real writer produces passes, because a real writer produces\n * exactly this structure.\n *\n * HOW IT READS. A bitset body is counted in place through a `Uint32Array` (copied to a scratch first when its offset is not\n * a multiple of 4); every array and run list goes through the `DataView`, which costs less to compile on a first call.\n * Each path refuses the same bytes with the same message.\n *\n * WHAT IT COSTS. One pass over the bytes the decode is about to copy anyway, once per decode: never per id, and\n * never on a cache hit.\n *\n * The codec's bitmap decoder in `ts-roaring/` runs it before it builds a container. The membership-only reader in\n * `decode.ts`, which the tests use as a second reader of the same bytes, builds on the layout it returns. One check in\n * one place is what keeps the two decoders from disagreeing about which bytes are a bitmap.\n *\n * @see https://github.com/RoaringBitmap/RoaringFormatSpec\n */\nimport { IntegrityError } from '@cloudbitmaps/core';\nimport type { EncodedChunk } from '@cloudbitmaps/core';\nimport { BITSET_WORDS, popcountWords } from './popcount';\n\n/** Whether this machine stores a typed array's elements little-endian, as the wire does (so a body is a plain copy). */\nexport const LITTLE_ENDIAN = new Uint8Array(Uint16Array.of(1).buffer)[0] === 1;\n\n/** Cookie for a bitmap with no run containers. Followed by a u32 container count. */\nexport const SERIAL_COOKIE_NO_RUNCONTAINER = 12_346;\n/** Cookie (low 16 bits) for a bitmap that may contain run containers; the high 16 bits hold `count - 1`. */\nexport const SERIAL_COOKIE = 12_347;\n/**\n * Below this many containers, a run-cookie bitmap omits the offset header and containers must be located by\n * walking their sizes. At or above it the header is present. (A `NO_RUNCONTAINER` bitmap always has it.)\n */\nexport const NO_OFFSET_THRESHOLD = 4;\n/** A container holding more than this many values is stored as a flat 8 KiB bitset rather than a u16 array. */\nexport const ARRAY_MAX_CARDINALITY = 4_096;\n/** 65,536 bits, flat. */\nconst BITMAP_CONTAINER_BYTES = 8_192;\n/** The largest value a container holds: its low 16 bits. */\nconst MAX_LOW = 0xffff;\n\n/** A container of sorted `u16` values. */\nexport const ARRAY = 0;\n/** A container of 65,536 bits. */\nexport const BITMAP = 1;\n/** A container of `(start, length)` runs. */\nconst RUN = 2;\ntype ContainerKind = typeof ARRAY | typeof BITMAP | typeof RUN;\n\nexport interface PortableContainer {\n /** High 16 bits of every value in this container. */\n readonly key: number;\n /** Number of values. Stored as `cardinality - 1` on the wire, normalized here. */\n readonly cardinality: number;\n readonly kind: ContainerKind;\n /** Absolute byte offset of this container's payload within the source buffer; a run container's run count. */\n readonly offset: number;\n}\n\n/**\n * The error for a field that runs past the buffer. Callers test the bound inline and call this only when it\n * fails, so a well-formed bitmap never builds the message: the test runs once per container, and a string built\n * on every pass would cost a bitmap of many small containers more than the check itself does.\n */\nfunction overrun(bytes: Uint8Array, offset: number, length: number, what: string): IntegrityError {\n return new IntegrityError(\n `portable roaring: ${what} needs bytes [${offset}, ${offset + length}) of a ${bytes.byteLength}-byte buffer`,\n );\n}\n\n/**\n * Parse the portable-format bitmap in `bytes`, and check its structure.\n *\n * An empty buffer is the empty bitmap, as it is to CRoaring, which returns one without reading a byte.\n *\n * @throws {IntegrityError} if the cookie is unrecognized, any field runs past the buffer, or the structure is not\n * one a writer produces (see the module header for the list).\n */\nexport function parsePortableLayout(bytes: Uint8Array): PortableContainer[] {\n const containers: PortableContainer[] = [];\n walk(bytes, containers);\n return containers;\n}\n\n/**\n * {@link parsePortableLayout}'s check alone, for a caller that hands the bytes to another decoder afterwards and\n * so has no use for the layout: it allocates nothing per container.\n *\n * @returns where the bitmap ends: the offset one past its last container's last byte (0 for an empty buffer). A\n * caller that needs the buffer to be exactly one bitmap compares it with the buffer's length.\n * @throws {IntegrityError} exactly where {@link parsePortableLayout} does.\n */\nexport function checkPortableLayout(bytes: Uint8Array): number {\n return walk(bytes, null);\n}\n\n/** A one-container payload's header without run containers: cookie, count, `(key, cardinality - 1)`, offset. */\nconst SINGLE_HEADER_BYTES = 16;\n/** A one-container payload's header under the run cookie: cookie holding `count - 1`, one flag byte, the pair. */\nconst SINGLE_RUN_HEADER_BYTES = 9;\n\n/**\n * Each container of the portable bitmap in `bytes`, as the one-container portable bitmap a `.crbm` chunk stores:\n * its key moved to 0, its cardinality and kind kept, its body copied unchanged. These are exactly the bytes the\n * serializer writes for a bitmap holding only that container's low 16 bits, so a chunk cut from a whole\n * bitmap is the chunk built from its ids, provided the whole bitmap was encoded canonically first.\n *\n * Lazy, one container per step, and each container checked as it is copied, by the same rules as\n * {@link checkPortableLayout} (keys in order, and each body holding what its header says), so a stored chunk is\n * never one a reader refuses. The bytes are the serializer's, of a bitmap decoded from bytes that passed the\n * check, so on every honest input this finds nothing. It is what stands between a store and a bitmap decoded from a\n * buffer another thread was still writing during the load's call: the check saw the bytes as they were, the decode\n * as they became.\n *\n * @throws {IntegrityError} at the first container that runs past the buffer or does not hold what its header says.\n */\nexport function* containerPayloads(bytes: Uint8Array): Generator<EncodedChunk> {\n if (bytes.byteLength === 0) return;\n const { view, count, runFlagsAt, descriptiveAt, bodiesAt } = header(bytes);\n let pos = bodiesAt;\n let previousKey = -1;\n for (let i = 0; i < count; i++) {\n const key = view.getUint16(descriptiveAt + i * 4, true);\n if (key <= previousKey) {\n throw new IntegrityError(\n `portable roaring: container keys are not strictly ascending at index ${i}`,\n );\n }\n previousKey = key;\n const cardinality = view.getUint16(descriptiveAt + i * 4 + 2, true) + 1;\n const isRun =\n runFlagsAt >= 0 && ((bytes[runFlagsAt + (i >>> 3)] as number) & (1 << (i & 7))) !== 0;\n const kind: ContainerKind = isRun ? RUN : cardinality > ARRAY_MAX_CARDINALITY ? BITMAP : ARRAY;\n const size = checkContainer(bytes, view, pos, kind, cardinality, i);\n const headerBytes = isRun ? SINGLE_RUN_HEADER_BYTES : SINGLE_HEADER_BYTES;\n const payload = new Uint8Array(headerBytes + size);\n const out = new DataView(payload.buffer);\n if (isRun) {\n out.setUint32(0, SERIAL_COOKIE, true); // count - 1 = 0 in the high half\n payload[4] = 1; // container 0 is a run container\n out.setUint16(7, cardinality - 1, true); // after key 0 at byte 5\n } else {\n out.setUint32(0, SERIAL_COOKIE_NO_RUNCONTAINER, true);\n out.setUint32(4, 1, true);\n out.setUint16(10, cardinality - 1, true); // after key 0 at byte 8\n out.setUint32(12, SINGLE_HEADER_BYTES, true);\n }\n payload.set(bytes.subarray(pos, pos + size), headerBytes);\n pos += size;\n yield { chunkKey: key, payload, cardinality };\n }\n}\n\n/** Where each part of a non-empty portable bitmap's header is, checked against the buffer's length. */\ninterface Header {\n readonly view: DataView;\n readonly count: number;\n /** Where the run-container flag bits start, or -1 under the cookie that has none. */\n readonly runFlagsAt: number;\n /** The descriptive header: `(key, cardinality - 1)` per container. */\n readonly descriptiveAt: number;\n /** The offset header, or -1 where this layout has none. */\n readonly offsetsAt: number;\n /** Where the first container's body starts. */\n readonly bodiesAt: number;\n}\n\nfunction header(bytes: Uint8Array): Header {\n const length = bytes.byteLength;\n const view = new DataView(bytes.buffer, bytes.byteOffset, length);\n if (length < 4) throw overrun(bytes, 0, 4, 'the cookie');\n const cookie = view.getUint32(0, true);\n let count: number;\n let runFlagsAt = -1;\n let pos: number;\n if (cookie === SERIAL_COOKIE_NO_RUNCONTAINER) {\n if (length < 8) throw overrun(bytes, 4, 4, 'the container count');\n count = view.getUint32(4, true);\n pos = 8;\n } else if ((cookie & 0xffff) === SERIAL_COOKIE) {\n // The count is packed into the cookie's high half as `count - 1`, so it can never be zero here.\n count = (cookie >>> 16) + 1;\n runFlagsAt = 4;\n const flagBytes = (count + 7) >>> 3;\n if (runFlagsAt + flagBytes > length) {\n throw overrun(bytes, runFlagsAt, flagBytes, 'the run-container bitmap');\n }\n pos = runFlagsAt + flagBytes;\n } else {\n throw new IntegrityError(\n `portable roaring: unrecognized cookie 0x${cookie.toString(16)}, not a portable-format bitmap`,\n );\n }\n const descriptiveAt = pos;\n if (pos + count * 4 > length) throw overrun(bytes, pos, count * 4, 'the descriptive header');\n pos += count * 4;\n let offsetsAt = -1;\n if (runFlagsAt < 0 || count >= NO_OFFSET_THRESHOLD) {\n if (pos + count * 4 > length) throw overrun(bytes, pos, count * 4, 'the offset header');\n offsetsAt = pos;\n pos += count * 4;\n }\n return { view, count, runFlagsAt, descriptiveAt, offsetsAt, bodiesAt: pos };\n}\n\n/**\n * Check every container of `bytes`, appending each one's layout to `out` when there is one to append to. Returns\n * where the bitmap ends.\n */\nfunction walk(bytes: Uint8Array, out: PortableContainer[] | null): number {\n if (bytes.byteLength === 0) return 0;\n const { view, count, runFlagsAt, descriptiveAt, offsetsAt, bodiesAt } = header(bytes);\n let pos = bodiesAt;\n\n let previousKey = -1;\n // Containers lie back to back from here. That is how CRoaring's deserializer finds them (it never reads the\n // offset header), so the offsets are checked against it rather than followed.\n for (let i = 0; i < count; i++) {\n const key = view.getUint16(descriptiveAt + i * 4, true);\n if (key <= previousKey) {\n throw new IntegrityError(\n `portable roaring: container keys are not strictly ascending at index ${i}`,\n );\n }\n previousKey = key;\n const cardinality = view.getUint16(descriptiveAt + i * 4 + 2, true) + 1;\n const isRun =\n runFlagsAt >= 0 && ((bytes[runFlagsAt + (i >>> 3)] as number) & (1 << (i & 7))) !== 0;\n const kind: ContainerKind = isRun ? RUN : cardinality > ARRAY_MAX_CARDINALITY ? BITMAP : ARRAY;\n if (offsetsAt >= 0) {\n const stated = view.getUint32(offsetsAt + i * 4, true);\n if (stated !== pos) {\n throw new IntegrityError(\n `portable roaring: the offset header puts container ${i} at byte ${stated}, but it starts at ${pos}`,\n );\n }\n }\n\n const size = checkContainer(bytes, view, pos, kind, cardinality, i);\n out?.push({ key, cardinality, kind, offset: pos });\n pos += size;\n }\n return pos;\n}\n\n/**\n * Check one container's body at `pos`: that it fits the buffer and holds what its header says (see the module\n * header for the rules). Returns the body's size.\n */\nfunction checkContainer(\n bytes: Uint8Array,\n view: DataView,\n pos: number,\n kind: ContainerKind,\n cardinality: number,\n i: number,\n): number {\n const length = bytes.byteLength;\n if (kind === ARRAY) {\n const size = cardinality * 2;\n if (pos + size > length) throw overrun(bytes, pos, size, `container ${i} (array)`);\n checkArray(view, pos, cardinality, i);\n return size;\n }\n if (kind === BITMAP) {\n if (pos + BITMAP_CONTAINER_BYTES > length) {\n throw overrun(bytes, pos, BITMAP_CONTAINER_BYTES, `container ${i} (bitmap)`);\n }\n const bits = bitsetBits(bytes, pos);\n if (bits !== cardinality) {\n throw new IntegrityError(\n `portable roaring: container ${i} (bitmap) holds ${bits} values, but its header says ${cardinality}`,\n );\n }\n return BITMAP_CONTAINER_BYTES;\n }\n if (pos + 2 > length) throw overrun(bytes, pos, 2, `container ${i} (run count)`);\n const runs = view.getUint16(pos, true);\n const size = 2 + runs * 4;\n if (pos + size > length) throw overrun(bytes, pos, size, `container ${i} (run)`);\n const covered = checkRuns(view, pos + 2, runs, i);\n // A header cannot state zero values, so this is also what refuses a run container with no runs, the shape\n // that crashes CRoaring when anything iterates it.\n if (covered !== cardinality) {\n throw new IntegrityError(\n `portable roaring: container ${i} (run) covers ${covered} values, but its header says ${cardinality}`,\n );\n }\n return size;\n}\n\n/**\n * An array container's values must strictly ascend: `has` binary-searches them and iteration yields them in order.\n *\n * Read two values per `u32` (little-endian, so the first value is the low half): half the loads and half the loop\n * trips of reading them one at a time, which measured about twice as fast (probe, indicative).\n */\nfunction checkArray(view: DataView, at: number, cardinality: number, index: number): void {\n let previous = -1;\n let p = at;\n const end = at + cardinality * 2;\n for (; p + 4 <= end; p += 4) {\n const pair = view.getUint32(p, true);\n const first = pair & 0xffff;\n const second = pair >>> 16;\n if (first <= previous || second <= first) throw unordered(index, (p - at) / 2);\n previous = second;\n }\n if (p < end && view.getUint16(p, true) <= previous) throw unordered(index, (p - at) / 2);\n}\n\nfunction unordered(index: number, element: number): IntegrityError {\n return new IntegrityError(\n `portable roaring: container ${index} (array) is not strictly ascending at or after element ${element}`,\n );\n}\n\n/**\n * Runs must ascend, stay inside the container, and leave at least one value between each other: overlapping runs\n * count their shared values twice, and touching ones are two runs a writer would have merged into one. Returns the\n * number of values the runs cover. Each run is one `u32`: its start in the low half, its length in the high.\n */\nfunction checkRuns(view: DataView, at: number, runs: number, index: number): number {\n let covered = 0;\n /** The lowest start the next run may have: one past the value after the previous run's last. */\n let lowest = 0;\n for (let r = 0; r < runs; r++) {\n const run = view.getUint32(at + r * 4, true);\n const start = run & 0xffff;\n const last = start + (run >>> 16);\n if (start < lowest) {\n throw new IntegrityError(\n `portable roaring: container ${index} (run) has run ${r} out of order, overlapping or touching the one before`,\n );\n }\n if (last > MAX_LOW) {\n throw new IntegrityError(\n `portable roaring: container ${index} (run) has run ${r} running past the end of the container`,\n );\n }\n covered += last - start + 1;\n lowest = last + 2;\n }\n return covered;\n}\n\n/**\n * Set bits in the bitset container's 2,048 words at `at`. A body at a 4-byte-aligned offset is counted in place through\n * a `Uint32Array`; any other is copied into a scratch of its own first. Counting is the same on either byte order, so\n * the words need not be read as little-endian.\n */\nfunction bitsetBits(bytes: Uint8Array, at: number): number {\n const offset = bytes.byteOffset + at;\n if ((offset & 3) === 0) return popcountWords(new Uint32Array(bytes.buffer, offset, BITSET_WORDS));\n scratchBytes.set(bytes.subarray(at, at + BITMAP_CONTAINER_BYTES));\n return popcountWords(scratchWords);\n}\n\n/** Where a bitset body that is not 4-byte aligned is copied to be counted. */\nconst scratchWords = new Uint32Array(BITSET_WORDS);\nconst scratchBytes = new Uint8Array(scratchWords.buffer);\n", "/**\n * Bit counting over 32-bit words, shared by the layout check (which counts a stored bitset before it is decoded) and by\n * the containers (which count a bitset they have just built), so both count one way.\n */\n\n/** The 32-bit words of a bitset container: 65,536 bits. */\nexport const BITSET_WORDS = 2_048;\n\n/** Set bits in one 32-bit word. */\nexport function popcount32(word: number): number {\n let w = word - ((word >>> 1) & 0x5555_5555);\n w = (w & 0x3333_3333) + ((w >>> 2) & 0x3333_3333);\n return Math.imul((w + (w >>> 4)) & 0x0f0f_0f0f, 0x0101_0101) >>> 24;\n}\n\n/**\n * Set bits in the {@link BITSET_WORDS} words of a bitset: Harley-Seal, which adds sixteen words through a tree of carry-save\n * adders and counts the bits of one word in sixteen instead of every word. Plain 32-bit integer arithmetic, no `BigInt`.\n */\nexport function popcountWords(d: Uint32Array): number {\n let total = 0;\n let ones = 0;\n let twos = 0;\n let fours = 0;\n let eights = 0;\n for (let i = 0; i < BITSET_WORDS; i += 16) {\n let u: number;\n let twosA: number;\n let twosB: number;\n let foursA: number;\n let foursB: number;\n let x = d[i] as number;\n let y = d[i + 1] as number;\n u = ones ^ x;\n twosA = (ones & x) | (u & y);\n ones = u ^ y;\n x = d[i + 2] as number;\n y = d[i + 3] as number;\n u = ones ^ x;\n twosB = (ones & x) | (u & y);\n ones = u ^ y;\n u = twos ^ twosA;\n foursA = (twos & twosA) | (u & twosB);\n twos = u ^ twosB;\n x = d[i + 4] as number;\n y = d[i + 5] as number;\n u = ones ^ x;\n twosA = (ones & x) | (u & y);\n ones = u ^ y;\n x = d[i + 6] as number;\n y = d[i + 7] as number;\n u = ones ^ x;\n twosB = (ones & x) | (u & y);\n ones = u ^ y;\n u = twos ^ twosA;\n foursB = (twos & twosA) | (u & twosB);\n twos = u ^ twosB;\n u = fours ^ foursA;\n const eightsA = (fours & foursA) | (u & foursB);\n fours = u ^ foursB;\n x = d[i + 8] as number;\n y = d[i + 9] as number;\n u = ones ^ x;\n twosA = (ones & x) | (u & y);\n ones = u ^ y;\n x = d[i + 10] as number;\n y = d[i + 11] as number;\n u = ones ^ x;\n twosB = (ones & x) | (u & y);\n ones = u ^ y;\n u = twos ^ twosA;\n foursA = (twos & twosA) | (u & twosB);\n twos = u ^ twosB;\n x = d[i + 12] as number;\n y = d[i + 13] as number;\n u = ones ^ x;\n twosA = (ones & x) | (u & y);\n ones = u ^ y;\n x = d[i + 14] as number;\n y = d[i + 15] as number;\n u = ones ^ x;\n twosB = (ones & x) | (u & y);\n ones = u ^ y;\n u = twos ^ twosA;\n foursB = (twos & twosA) | (u & twosB);\n twos = u ^ twosB;\n u = fours ^ foursA;\n const eightsB = (fours & foursA) | (u & foursB);\n fours = u ^ foursB;\n u = eights ^ eightsA;\n const sixteens = (eights & eightsA) | (u & eightsB);\n eights = u ^ eightsB;\n total += popcount32(sixteens);\n }\n return (\n 16 * total +\n 8 * popcount32(eights) +\n 4 * popcount32(fours) +\n 2 * popcount32(twos) +\n popcount32(ones)\n );\n}\n", "/**\n * The three Roaring containers on typed arrays, and the operations on one container or a pair of them.\n *\n * A Roaring bitmap splits a 32-bit id into a 16-bit key and a 16-bit remainder and keeps the remainders of one key in a\n * container, whose kind is chosen for its content (Chambi, Lemire, Kaser and Godin, 2016; Lemire et al., 2016 and 2018,\n * the papers credited in the package README):\n *\n * - ARRAY: the sorted remainders, a `Uint16Array`, for up to 4,096 values;\n * - BITSET: 65,536 bits, a `Uint32Array` of 2,048 words, for more than 4,096 values;\n * - RUN: `(start, length - 1)` pairs of maximal runs of consecutive remainders, a `Uint16Array`.\n *\n * A container keeps its cardinality; nothing recounts it per call. A container is a RUN because it was decoded from\n * one, because {@link optimize} chose it, because a write into a run container edited its run list, or because a\n * combine of two runs left a run, in each case while the run form is the smaller one (see {@link optimize}); removing\n * an id turns it back into an array or a bitset. A run container's storage is never written in place: a write builds a\n * new list.\n *\n * STORAGE. An ARRAY or RUN container reads its values from `data[off, off + len)` (`len` values, or `len` run pairs\n * at `off + 2 * i`), so the small containers of one decoded bitmap can sit side by side in a single `Uint16Array` (a\n * slab) instead of each holding a typed array of its own, which for a run of a few bytes costs many times its payload.\n * A BITSET always owns its 2,048 words. A container whose storage another holder can see (a slab neighbour, or a\n * snapshot taken for `encodeChunks`, or a `clone`) has `shared` set, and a write copies it first; nothing writes to\n * shared storage. A write that may go in place returns a new container object over the same storage with `shared`\n * clear; that is safe because a clone or snapshot flags the container its bitmap holds at that moment, so a flagged\n * object never sits beside an unflagged one over the same storage.\n *\n * COMBINES, by the kinds of the pair (the result kind of a pair is a written rule: an array up to 4,096 values or a\n * bitset above, except that an `or` of a run with an array stays a run while the run form is smaller (an and, andNot\n * or xor of a run with an array gives an array or a bitset), and two run containers keep\n * a run result, for every one of the four combines, while its body, `2 + 4 * runs` bytes, is strictly smaller than that array or bitset, so a combine of\n * two runs of a few long intervals does not expand them to 8 KB of words and every later operation on the result stays\n * a walk of the intervals; every run a combine writes is maximal, its runs ascending with at least one value between\n * them, as the decoder requires; a container that has no partner in the other bitmap is not combined, and `TsBitmap`\n * keeps it by reference, so a result bitmap can hold a run; `optimize` picks runs before anything is stored, so\n * stored bytes depend on the set alone):\n *\n * and or andNot\n * A A merge, or gallop when merge while the union scratch bitset from 32 values,\n * one side is 16x longer fits an array, else bits gallop when the second side is\n * (scratch bitset from 32) 16x longer, else merge\n * A B probe each value copy the bitset, set bits keep values whose bit is clear\n * B B word loop word loop word loop\n * R R interval intersection interval union interval difference\n * A R probe / range copy merge into the run list through bitset words\n * B R probe / range copy through bitset words through bitset words\n *\n * XOR is one pass per pair, not the union less the intersection: two arrays merge once, two bitsets are one word loop and\n * one count, two run lists are one walk over their boundaries, and any pair with a bitset flips the other side's bits in\n * the bitset's words (`containerXor`).\n *\n * A combine takes `inPlace` when its first operand is a bitset nothing else can see: the words are written, not copied.\n *\n * COUNTS. `containerAndCard` says how many values a pair shares, `containersIntersect` whether it shares any (stopping\n * at the first) and `containersSubset` whether every value of one is in the other (stopping at the first that is not), each\n * by the kinds of the pair and each building nothing: the answers the bitmap's counting operations are made from. The\n * last two never count.\n */\nimport { ARRAY_MAX_CARDINALITY, LITTLE_ENDIAN } from '../portable/layout';\nimport { BITSET_WORDS, popcount32, popcountWords } from '../portable/popcount';\n\n/** A container of sorted `u16` values. */\nexport const ARRAY = 0;\n/** A container of 65,536 bits. */\nexport const BITSET = 1;\n/** A container of `(start, length - 1)` pairs. */\nexport const RUN = 2;\ntype Kind = typeof ARRAY | typeof BITSET | typeof RUN;\n\n/** 32-bit words in a bitset container. */\nexport const WORDS = BITSET_WORDS;\n/** Bytes of a bitset container's body. */\nexport const BITSET_BYTES = 8_192;\n\n/** How many times longer one array must be than the other for the shorter to gallop over it instead of a linear merge (a larger factor gallops less often, which suits similar sizes better and skewed ones worse). */\nconst GALLOP_SKEW = 16;\n\nexport { LITTLE_ENDIAN };\n\n/**\n * One container. `data` is a `Uint16Array` for an array or a run container and a `Uint32Array` of {@link WORDS} words\n * for a bitset. An array's values are `data[off, off + len)` (`len` is its cardinality), a run container's pairs are\n * `data[off, off + 2 * len)` (`len` is the number of runs), and `card` is the number of values in every kind. `shared`\n * says another holder can see `data`: it is set once and a write copies instead.\n */\nexport class Container {\n constructor(\n readonly kind: Kind,\n readonly data: Uint16Array | Uint32Array,\n readonly off: number,\n readonly len: number,\n readonly card: number,\n public shared: boolean,\n ) {}\n}\n\n/** The 16-bit storage of an array or run container. */\nfunction lows16(c: Container): Uint16Array {\n return c.data as Uint16Array;\n}\n\n/** The words of a bitset container. */\nfunction words32(c: Container): Uint32Array {\n return c.data as Uint32Array;\n}\n\nexport function arrayContainer(values: Uint16Array, card: number): Container {\n return new Container(ARRAY, values, 0, card, card, false);\n}\n\nexport function bitsetContainer(words: Uint32Array, card: number): Container {\n return new Container(BITSET, words, 0, 0, card, false);\n}\n\nfunction runContainer(pairs: Uint16Array, runs: number, card: number): Container {\n return new Container(RUN, pairs, 0, runs, card, false);\n}\n\n// Scratch for results whose size is known only after they are built: a combine writes into it and copies out exactly\n// what it wrote. Single-threaded and never held across a call that could run other code, so one of each is enough.\nlet valueScratch = new Uint16Array(8_192);\nlet pairScratch = new Uint16Array(8_192);\n// The most a scratch keeps for the life of the process: one container's worth of 16-bit values. A request above it\n// gets a fresh array that is not kept.\nconst SCRATCH_KEEP = 65_536;\n\nfunction values16(n: number): Uint16Array {\n if (valueScratch.length >= n) return valueScratch;\n if (n > SCRATCH_KEEP) return new Uint16Array(n);\n valueScratch = new Uint16Array(Math.max(n, Math.min(2 * valueScratch.length, SCRATCH_KEEP)));\n return valueScratch;\n}\n\nfunction pairs16(n: number): Uint16Array {\n if (pairScratch.length >= n) return pairScratch;\n if (n > SCRATCH_KEEP) return new Uint16Array(n);\n pairScratch = new Uint16Array(Math.max(n, Math.min(2 * pairScratch.length, SCRATCH_KEEP)));\n return pairScratch;\n}\n\n/** An array container of the first `n` values of `scratch` (copied out), or `null` when there are none. */\nfunction arrayOfScratch(scratch: Uint16Array, n: number): Container | null {\n return n === 0 ? null : arrayContainer(scratch.slice(0, n), n);\n}\n\n/**\n * Set bits in the AND of two bitsets, counted as the words are read: {@link popcountWords}'s tree with each word taken\n * as `d[i] & e[i]`, so the AND is never written to memory and read back.\n */\nfunction popcountAnd(d: Uint32Array, e: Uint32Array): number {\n let total = 0;\n let ones = 0;\n let twos = 0;\n let fours = 0;\n let eights = 0;\n for (let i = 0; i < WORDS; i += 16) {\n let u: number;\n let twosA: number;\n let twosB: number;\n let foursA: number;\n let foursB: number;\n let x = (d[i] as number) & (e[i] as number);\n let y = (d[i + 1] as number) & (e[i + 1] as number);\n u = ones ^ x;\n twosA = (ones & x) | (u & y);\n ones = u ^ y;\n x = (d[i + 2] as number) & (e[i + 2] as number);\n y = (d[i + 3] as number) & (e[i + 3] as number);\n u = ones ^ x;\n twosB = (ones & x) | (u & y);\n ones = u ^ y;\n u = twos ^ twosA;\n foursA = (twos & twosA) | (u & twosB);\n twos = u ^ twosB;\n x = (d[i + 4] as number) & (e[i + 4] as number);\n y = (d[i + 5] as number) & (e[i + 5] as number);\n u = ones ^ x;\n twosA = (ones & x) | (u & y);\n ones = u ^ y;\n x = (d[i + 6] as number) & (e[i + 6] as number);\n y = (d[i + 7] as number) & (e[i + 7] as number);\n u = ones ^ x;\n twosB = (ones & x) | (u & y);\n ones = u ^ y;\n u = twos ^ twosA;\n foursB = (twos & twosA) | (u & twosB);\n twos = u ^ twosB;\n u = fours ^ foursA;\n const eightsA = (fours & foursA) | (u & foursB);\n fours = u ^ foursB;\n x = (d[i + 8] as number) & (e[i + 8] as number);\n y = (d[i + 9] as number) & (e[i + 9] as number);\n u = ones ^ x;\n twosA = (ones & x) | (u & y);\n ones = u ^ y;\n x = (d[i + 10] as number) & (e[i + 10] as number);\n y = (d[i + 11] as number) & (e[i + 11] as number);\n u = ones ^ x;\n twosB = (ones & x) | (u & y);\n ones = u ^ y;\n u = twos ^ twosA;\n foursA = (twos & twosA) | (u & twosB);\n twos = u ^ twosB;\n x = (d[i + 12] as number) & (e[i + 12] as number);\n y = (d[i + 13] as number) & (e[i + 13] as number);\n u = ones ^ x;\n twosA = (ones & x) | (u & y);\n ones = u ^ y;\n x = (d[i + 14] as number) & (e[i + 14] as number);\n y = (d[i + 15] as number) & (e[i + 15] as number);\n u = ones ^ x;\n twosB = (ones & x) | (u & y);\n ones = u ^ y;\n u = twos ^ twosA;\n foursB = (twos & twosA) | (u & twosB);\n twos = u ^ twosB;\n u = fours ^ foursA;\n const eightsB = (fours & foursA) | (u & foursB);\n fours = u ^ foursB;\n u = eights ^ eightsA;\n const sixteens = (eights & eightsA) | (u & eightsB);\n eights = u ^ eightsB;\n total += popcount32(sixteens);\n }\n return (\n 16 * total +\n 8 * popcount32(eights) +\n 4 * popcount32(fours) +\n 2 * popcount32(twos) +\n popcount32(ones)\n );\n}\n\n/** Set the bits `start` to `end`, both inclusive, in `words`. */\nfunction setRange(words: Uint32Array, start: number, end: number): void {\n const first = start >>> 5;\n const last = end >>> 5;\n const head = (0xffff_ffff << (start & 31)) >>> 0;\n const tail = 0xffff_ffff >>> (31 - (end & 31));\n if (first === last) {\n words[first] = (words[first] as number) | (head & tail);\n return;\n }\n words[first] = (words[first] as number) | head;\n for (let i = first + 1; i < last; i++) words[i] = 0xffff_ffff;\n words[last] = (words[last] as number) | tail;\n}\n\n/** Clear the bits `start` to `end`, both inclusive, in `words`. */\nfunction clearRange(words: Uint32Array, start: number, end: number): void {\n const first = start >>> 5;\n const last = end >>> 5;\n const head = (0xffff_ffff << (start & 31)) >>> 0;\n const tail = 0xffff_ffff >>> (31 - (end & 31));\n if (first === last) {\n words[first] = (words[first] as number) & ~(head & tail);\n return;\n }\n words[first] = (words[first] as number) & ~head;\n for (let i = first + 1; i < last; i++) words[i] = 0;\n words[last] = (words[last] as number) & ~tail;\n}\n\n/** Flip the bits `start` to `end`, both inclusive, in `words`. */\nfunction flipRange(words: Uint32Array, start: number, end: number): void {\n const first = start >>> 5;\n const last = end >>> 5;\n const head = (0xffff_ffff << (start & 31)) >>> 0;\n const tail = 0xffff_ffff >>> (31 - (end & 31));\n if (first === last) {\n words[first] = (words[first] as number) ^ (head & tail);\n return;\n }\n words[first] = (words[first] as number) ^ head;\n for (let i = first + 1; i < last; i++) words[i] = ~(words[i] as number);\n words[last] = (words[last] as number) ^ tail;\n}\n\n/**\n * The container holding the ascending ids `ids[from, to)`, all of one key (only the low 16 bits are kept), duplicates\n * allowed: an array up to 4,096 distinct values and a bitset above.\n */\nexport function fromSortedIds(ids: Uint32Array, from: number, to: number): Container {\n const n = to - from;\n if (n <= ARRAY_MAX_CARDINALITY) {\n const lows = new Uint16Array(n);\n let count = 0;\n let previous = -1;\n for (let i = from; i < to; i++) {\n const low = (ids[i] as number) & 0xffff;\n if (low !== previous) lows[count++] = low;\n previous = low;\n }\n return arrayContainer(count === n ? lows : lows.slice(0, count), count);\n }\n const words = new Uint32Array(WORDS);\n for (let i = from; i < to; i++) {\n const v = (ids[i] as number) & 0xffff;\n words[v >>> 5] = (words[v >>> 5] as number) | (1 << (v & 31));\n }\n return fromWordsCard(words, popcountWords(words)) as Container;\n}\n\n/** The container holding `words` (kept as the bitset's storage when it becomes one) given its cardinality, or `null` when it is 0. */\nfunction fromWordsCard(words: Uint32Array, card: number): Container | null {\n if (card === 0) return null;\n if (card > ARRAY_MAX_CARDINALITY) return bitsetContainer(words, card);\n const out = new Uint16Array(card);\n wordsToLows(words, out);\n return arrayContainer(out, card);\n}\n\n/** Write the positions of the set bits of `words`, ascending, to `out`; returns how many. */\nfunction wordsToLows(words: Uint32Array, out: Uint16Array): number {\n let k = 0;\n for (let i = 0; i < WORDS; i++) {\n let w = words[i] as number;\n const base = i * 32 + 31;\n while (w !== 0) {\n const lowest = w & -w;\n out[k++] = base - Math.clz32(lowest);\n w ^= lowest;\n }\n }\n return k;\n}\n\n/** Write the container's remainders, ascending, to `out` (which holds at least `card` of them). */\nfunction writeLows(c: Container, out: Uint16Array): void {\n if (c.kind === ARRAY) {\n out.set(lows16(c).subarray(c.off, c.off + c.len));\n } else if (c.kind === BITSET) {\n wordsToLows(words32(c), out);\n } else {\n const u16 = lows16(c);\n let k = 0;\n for (let r = 0; r < c.len; r++) {\n const start = u16[c.off + 2 * r] as number;\n const end = start + (u16[c.off + 2 * r + 1] as number);\n for (let v = start; v <= end; v++) out[k++] = v;\n }\n }\n}\n\n/** An array with fewer values than this is written out by a loop, not by a view and a copy. */\nconst SMALL_IDS = 32;\n\n/**\n * Write the container's ids, each plus `base`, ascending, to `out` from index `at`; returns the index after the last.\n * The one step a `toUint32Array` takes per container.\n */\nexport function appendIds(c: Container, out: Uint32Array, at: number, base: number): number {\n if (c.kind === ARRAY) {\n const u16 = lows16(c);\n const end = c.off + c.len;\n if (base === 0 && c.len >= SMALL_IDS) {\n // One widening copy (a short array is counted out instead: a view over it costs more than its ids).\n out.set(u16.subarray(c.off, end), at);\n return at + c.len;\n }\n for (let i = c.off; i < end; i++) out[at++] = base + (u16[i] as number);\n return at;\n }\n if (c.kind === BITSET) {\n const words = words32(c);\n for (let i = 0; i < WORDS; i++) {\n let w = words[i] as number;\n const top = base + i * 32 + 31;\n while (w !== 0) {\n const lowest = w & -w;\n out[at++] = top - Math.clz32(lowest);\n w ^= lowest;\n }\n }\n return at;\n }\n // Runs: a short run is counted out, each id written once with `base` added as it goes; a long one is one widening copy.\n const u16 = lows16(c);\n for (let r = 0; r < c.len; r++) {\n const start = u16[c.off + 2 * r] as number;\n const length = u16[c.off + 2 * r + 1] as number;\n if (length < LONG_RUN) {\n const last = base + start + length;\n for (let v = base + start; v <= last; v++) out[at++] = v;\n continue;\n }\n // `start..start + length` out of a table of 0..65,535, then `base` added where it is not 0.\n const from = at;\n out.set(iota().subarray(start, start + length + 1), at);\n at += length + 1;\n if (base !== 0) for (let i = from; i < at; i++) out[i] = (out[i] as number) + base;\n }\n return at;\n}\n\n/** A run of at least this many values (less one) is copied out of {@link iota} rather than counted out. */\nconst LONG_RUN = 48;\n\nlet iotaTable: Uint16Array | undefined;\n\n/** The numbers 0 to 65,535 as `u16`s, built when the first long run is expanded and kept. */\nfunction iota(): Uint16Array {\n if (iotaTable === undefined) {\n iotaTable = new Uint16Array(65_536);\n for (let i = 0; i < 65_536; i++) iotaTable[i] = i;\n }\n return iotaTable;\n}\n\n/**\n * The container's bits as words. A bitset's own words are returned, not a copy: a caller reads them and never writes.\n * Any other kind is expanded into a new array.\n */\nfunction toWords(c: Container): Uint32Array {\n if (c.kind === BITSET) return words32(c);\n const words = new Uint32Array(WORDS);\n const u16 = lows16(c);\n if (c.kind === ARRAY) {\n for (let i = c.off; i < c.off + c.len; i++) {\n const v = u16[i] as number;\n words[v >>> 5] = (words[v >>> 5] as number) | (1 << (v & 31));\n }\n } else {\n for (let r = 0; r < c.len; r++) {\n const start = u16[c.off + 2 * r] as number;\n setRange(words, start, start + (u16[c.off + 2 * r + 1] as number));\n }\n }\n return words;\n}\n\n/** An array or a bitset (by cardinality) with a run container's values; any other container as it is. */\nfunction demote(c: Container): Container {\n if (c.kind !== RUN) return c;\n if (c.card > ARRAY_MAX_CARDINALITY) return bitsetContainer(toWords(c), c.card);\n const out = new Uint16Array(c.card);\n writeLows(c, out);\n return arrayContainer(out, c.card);\n}\n\n/** A copy that shares nothing with `c`. */\nexport function cloneContainer(c: Container): Container {\n if (c.kind === BITSET) return bitsetContainer(words32(c).slice(), c.card);\n const copy = lows16(c).slice(c.off, c.off + (c.kind === ARRAY ? c.len : 2 * c.len));\n return new Container(c.kind, copy, 0, c.len, c.card, false);\n}\n\n/** The words `c` may write to: its own, or a copy when another holder can see them. */\nfunction writableWords(c: Container): Uint32Array {\n return c.shared ? words32(c).slice() : words32(c);\n}\n\n/** The index of the first of the `len` values at `data[off + i * stride]` that is `>= low`. */\nfunction lowerBound(\n data: Uint16Array,\n off: number,\n len: number,\n low: number,\n stride: number,\n): number {\n let lo = 0;\n let hi = len;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if ((data[off + mid * stride] as number) < low) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n}\n\n/** The index in `[from, end)` of the first of `data[off + i]` that is `>= target`, by doubling steps then a binary search; `end` if none. */\nfunction gallop(data: Uint16Array, off: number, from: number, end: number, target: number): number {\n let step = 1;\n let lo = from;\n let hi = from;\n while (hi < end && (data[off + hi] as number) < target) {\n lo = hi + 1;\n hi += step;\n step *= 2;\n }\n if (hi > end) hi = end;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if ((data[off + mid] as number) < target) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n}\n\nexport function containerHas(c: Container, low: number): boolean {\n if (c.kind === BITSET)\n return ((((c.data as Uint32Array)[low >>> 5] as number) >>> (low & 31)) & 1) === 1;\n const u16 = c.data as Uint16Array;\n if (c.kind === ARRAY) {\n const at = lowerBound(u16, c.off, c.len, low, 1);\n return at < c.len && u16[c.off + at] === low;\n }\n // The last run starting at or before `low`.\n const after = lowerBound(u16, c.off, c.len, low + 1, 2);\n if (after === 0) return false;\n const r = c.off + 2 * (after - 1);\n return low <= (u16[r] as number) + (u16[r + 1] as number);\n}\n\n/** The index of the first of the `len` runs at `data[off + 2 * i]`, from index `from`, that starts after `value`; `len` if none. */\nfunction runsAfter(\n data: Uint16Array,\n off: number,\n from: number,\n len: number,\n value: number,\n): number {\n let step = 1;\n let lo = from;\n let hi = from;\n while (hi < len && (data[off + 2 * hi] as number) <= value) {\n lo = hi + 1;\n hi += step;\n step *= 2;\n }\n if (hi > len) hi = len;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if ((data[off + 2 * mid] as number) <= value) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n}\n\n/**\n * The container for the first `runs` pairs of `pairs`, whose values number `card`: a run container (over a copy when\n * `copy`, else over `pairs` itself) while its body is strictly smaller than the plain one, the rule {@link optimize}\n * applies, and an array or a bitset otherwise.\n */\nfunction runsOrPlain(pairs: Uint16Array, runs: number, card: number, copy: boolean): Container {\n const plain = card <= ARRAY_MAX_CARDINALITY ? 2 * card : BITSET_BYTES;\n if (2 + 4 * runs < plain) {\n return runContainer(copy ? pairs.slice(0, 2 * runs) : pairs, runs, card);\n }\n return fromRunPairs(pairs, runs, card) as Container;\n}\n\n/** The run container `c` with the value `low` (which it lacks) added: the run list edited, never expanded to words. */\nfunction addToRuns(c: Container, low: number): Container {\n const u16 = lows16(c);\n // `next` is the first run that starts after `low`; the run before it, if any, ends before `low`.\n const next = runsAfter(u16, c.off, 0, c.len, low);\n const prev = next - 1;\n const joinPrev =\n prev >= 0 &&\n (u16[c.off + 2 * prev] as number) + (u16[c.off + 2 * prev + 1] as number) + 1 === low;\n const joinNext = next < c.len && (u16[c.off + 2 * next] as number) === low + 1;\n const runs = c.len + 1 - (joinPrev ? 1 : 0) - (joinNext ? 1 : 0);\n const out = new Uint16Array(2 * runs);\n const head = joinPrev ? prev : next;\n out.set(u16.subarray(c.off, c.off + 2 * head));\n let at = 2 * head;\n if (joinPrev && joinNext) {\n out[at++] = u16[c.off + 2 * prev] as number;\n out[at++] =\n (u16[c.off + 2 * next] as number) +\n (u16[c.off + 2 * next + 1] as number) -\n (u16[c.off + 2 * prev] as number);\n } else if (joinPrev) {\n out[at++] = u16[c.off + 2 * prev] as number;\n out[at++] = (u16[c.off + 2 * prev + 1] as number) + 1;\n } else if (joinNext) {\n out[at++] = low;\n out[at++] = (u16[c.off + 2 * next + 1] as number) + 1;\n } else {\n out[at++] = low;\n out[at++] = 0;\n }\n const rest = joinNext ? next + 1 : next;\n out.set(u16.subarray(c.off + 2 * rest, c.off + 2 * c.len), at);\n return runsOrPlain(out, runs, c.card + 1, false);\n}\n\n/**\n * Add `low`; returns the container that now holds it, which is `c` itself unless the kind changed or the storage had to\n * be copied. `c.card` of the result is the new cardinality either way.\n */\nexport function containerAdd(c: Container, low: number): Container {\n if (containerHas(c, low)) return c;\n if (c.kind === RUN) return addToRuns(c, low);\n if (c.kind === BITSET) {\n const words = writableWords(c);\n words[low >>> 5] = (words[low >>> 5] as number) | (1 << (low & 31));\n return bitsetContainer(words, c.card + 1);\n }\n if (c.card === ARRAY_MAX_CARDINALITY) {\n const words = toWords(c);\n words[low >>> 5] = (words[low >>> 5] as number) | (1 << (low & 31));\n return bitsetContainer(words, c.card + 1);\n }\n const old = lows16(c);\n const at = lowerBound(old, c.off, c.len, low, 1);\n let u16 = old;\n if (!c.shared && c.off === 0 && old.length > c.len) {\n u16.copyWithin(at + 1, at, c.len);\n } else {\n u16 = new Uint16Array(Math.min(ARRAY_MAX_CARDINALITY, Math.max(8, c.len * 2)));\n u16.set(old.subarray(c.off, c.off + at));\n u16.set(old.subarray(c.off + at, c.off + c.len), at + 1);\n }\n u16[at] = low;\n return arrayContainer(u16, c.card + 1);\n}\n\n/**\n * A run container with the ids `ids[from, to)` (ascending, all of one key, duplicates allowed, only the low 16 bits\n * kept) added, for a group of a few: each id is found in the run list by a gallop search and written into one working\n * copy of the list (the tail moved by a block copy), so the cost is a few searches and moves, not a walk of every run.\n * The result is the same container {@link orRunArrayWalk} gives for the same values: a run container while that is the\n * smaller form, and `c` itself when no id adds anything.\n */\nfunction addFewToRuns(c: Container, ids: Uint32Array, from: number, to: number): Container {\n const x = lows16(c);\n let data = x;\n let base = c.off;\n let out: Uint16Array | null = null;\n let n = c.len;\n let added = 0;\n for (let k = from; k < to; k++) {\n const low = (ids[k] as number) & 0xffff;\n const next = runsAfter(data, base, 0, n, low);\n const prev = next - 1;\n const prevEnd =\n prev >= 0 ? (data[base + 2 * prev] as number) + (data[base + 2 * prev + 1] as number) : -2;\n if (prevEnd >= low) continue;\n if (out === null) {\n out = new Uint16Array(2 * (c.len + to - from));\n out.set(x.subarray(c.off, c.off + 2 * c.len));\n data = out;\n base = 0;\n }\n const joinPrev = prevEnd + 1 === low;\n const joinNext = next < n && (out[2 * next] as number) === low + 1;\n if (joinPrev && joinNext) {\n out[2 * prev + 1] =\n (out[2 * next] as number) + (out[2 * next + 1] as number) - (out[2 * prev] as number);\n out.copyWithin(2 * next, 2 * next + 2, 2 * n);\n n--;\n } else if (joinPrev) {\n out[2 * prev + 1] = (out[2 * prev + 1] as number) + 1;\n } else if (joinNext) {\n out[2 * next] = low;\n out[2 * next + 1] = (out[2 * next + 1] as number) + 1;\n } else {\n out.copyWithin(2 * next + 2, 2 * next, 2 * n);\n out[2 * next] = low;\n out[2 * next + 1] = 0;\n n++;\n }\n added++;\n }\n if (out === null) return c;\n return runsOrPlain(out, n, c.card + added, true);\n}\n\n/**\n * The ids `ids[from, to)` (ascending, all of one key, duplicates allowed, only the low 16 bits kept) added to `c`; the\n * container that holds them, `c` itself when they add nothing. For a group of a few, where building a container for the\n * group and merging two containers costs more than putting each id in: a run container is edited by one search per id,\n * a bitset has its bits set (in place unless `c` is shared), an array has each id inserted. `c.card` of the result is the\n * new cardinality.\n */\nexport function containerAddSorted(\n c: Container,\n ids: Uint32Array,\n from: number,\n to: number,\n): Container {\n if (c.kind === RUN) return addFewToRuns(c, ids, from, to);\n let cur = c;\n for (let k = from; k < to; k++) cur = containerAdd(cur, (ids[k] as number) & 0xffff);\n return cur;\n}\n\n/**\n * Remove `low`; returns the container that now holds the rest, `c` itself unless the kind changed or the storage had\n * to be copied, or `null` when nothing is left.\n */\nexport function containerRemove(c: Container, low: number): Container | null {\n if (!containerHas(c, low)) return c;\n if (c.card === 1) return null;\n const plain = demote(c);\n if (plain.kind === BITSET) {\n const words = writableWords(plain);\n words[low >>> 5] = (words[low >>> 5] as number) & ~(1 << (low & 31));\n return fromWordsCard(words, plain.card - 1);\n }\n const old = lows16(plain);\n const at = lowerBound(old, plain.off, plain.len, low, 1);\n if (!plain.shared && plain.off === 0) {\n old.copyWithin(at, at + 1, plain.len);\n return arrayContainer(old, plain.card - 1);\n }\n const u16 = new Uint16Array(plain.len - 1);\n u16.set(old.subarray(plain.off, plain.off + at));\n u16.set(old.subarray(plain.off + at + 1, plain.off + plain.len), at);\n return arrayContainer(u16, plain.card - 1);\n}\n\n/** The smallest remainder in the container. */\nexport function containerMin(c: Container): number {\n if (c.kind === ARRAY || c.kind === RUN) return (c.data as Uint16Array)[c.off] as number;\n const words = words32(c);\n for (let i = 0; i < WORDS; i++) {\n const w = words[i] as number;\n if (w !== 0) return i * 32 + 31 - Math.clz32(w & -w);\n }\n throw new RangeError('a bitset container holds no bits');\n}\n\n/** The largest remainder in the container. */\nexport function containerMax(c: Container): number {\n if (c.kind === ARRAY) return (c.data as Uint16Array)[c.off + c.len - 1] as number;\n if (c.kind === RUN) {\n const u16 = c.data as Uint16Array;\n return (u16[c.off + 2 * c.len - 2] as number) + (u16[c.off + 2 * c.len - 1] as number);\n }\n const words = words32(c);\n for (let i = WORDS - 1; i >= 0; i--) {\n const w = words[i] as number;\n if (w !== 0) return i * 32 + 31 - Math.clz32(w);\n }\n throw new RangeError('a bitset container holds no bits');\n}\n\n/**\n * The number of maximal runs of consecutive values the container's values form, or any count at or above `stop` when\n * it has that many (the caller only needs to know whether runs are few enough to be worth storing).\n */\nfunction runCount(c: Container, stop: number): number {\n if (c.kind === RUN) return c.len;\n let runs = 0;\n if (c.kind === ARRAY) {\n const u16 = lows16(c);\n let previous = -2;\n for (let i = c.off; i < c.off + c.len; i++) {\n const v = u16[i] as number;\n if (v !== previous + 1 && ++runs >= stop) return runs;\n previous = v;\n }\n return runs;\n }\n // A run starts at each set bit whose lower neighbour (the previous word's top bit, for bit 0) is clear.\n const words = words32(c);\n let carry = 0;\n for (let i = 0; i < WORDS; i++) {\n const w = words[i] as number;\n const starts = w & ~((w << 1) | carry);\n // Words of all ones or none, most of a run-shaped set's, have no start: no count to take.\n if (starts !== 0) {\n runs += popcount32(starts >>> 0);\n if (runs >= stop) return runs;\n }\n carry = w >>> 31;\n }\n return runs;\n}\n\n/** `c` as a run container: the pairs of its maximal runs, `runs` of them. */\nfunction toRun(c: Container, runs: number): Container {\n const pairs = new Uint16Array(2 * runs);\n let r = 0;\n if (c.kind === ARRAY) {\n const u16 = lows16(c);\n const end = c.off + c.len;\n let i = c.off;\n while (i < end) {\n let j = i;\n while (j + 1 < end && (u16[j + 1] as number) === (u16[j] as number) + 1) j++;\n pairs[2 * r] = u16[i] as number;\n pairs[2 * r + 1] = j - i;\n r++;\n i = j + 1;\n }\n return runContainer(pairs, runs, c.card);\n }\n // A start is a set bit with a clear lower neighbour and an end a set bit with a clear upper one; read in order, the\n // two alternate across words, and a run of one value is both at once.\n const words = words32(c);\n let start = 0;\n let carry = 0;\n for (let i = 0; i < WORDS; i++) {\n const w = words[i] as number;\n const next = i + 1 < WORDS ? (words[i + 1] as number) : 0;\n let starts = (w & ~((w << 1) | carry)) >>> 0;\n let ends = (w & ~((w >>> 1) | (next << 31))) >>> 0;\n carry = w >>> 31;\n let both = starts | ends;\n while (both !== 0) {\n const bit = both & -both;\n both ^= bit;\n const at = i * 32 + 31 - Math.clz32(bit);\n if ((starts & bit) !== 0) {\n starts ^= bit;\n start = at;\n }\n if ((ends & bit) !== 0) {\n ends ^= bit;\n pairs[2 * r] = start;\n pairs[2 * r + 1] = at - start;\n r++;\n }\n }\n }\n return runContainer(pairs, runs, c.card);\n}\n\n/**\n * The canonical container for these values: a run container only when its body (`2 + 4 * runs` bytes) is strictly\n * smaller than the plain one (`2 * card` bytes for an array, 8,192 for a bitset), so a tie is an array (or bitset),\n * whatever kind the container had. It depends on the values alone, which is what makes stored bytes a function of the set.\n */\nexport function optimize(c: Container): Container {\n const plain = c.card <= ARRAY_MAX_CARDINALITY ? 2 * c.card : BITSET_BYTES;\n // Smaller than the plain body needs `2 + 4 * runs < plain`, so a count at `stop` already settles it.\n const runs = runCount(c, (plain - 2) / 4);\n if (2 + 4 * runs < plain) return c.kind === RUN ? c : toRun(c, runs);\n return demote(c);\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Combines\n// ---------------------------------------------------------------------------------------------------------------\n\n/** Whether an array of `longer` values is at least {@link GALLOP_SKEW} times as long as one of `shorter`. */\nfunction skewed(shorter: number, longer: number): boolean {\n return longer >= GALLOP_SKEW * shorter;\n}\n\n// Arrays shorter than this are merged; from here a similar-sized pair is intersected through a scratch bitset, which\n// reads both arrays once, in order, with no unpredictable branch. A lower value pays the bitset's set-and-clear for\n// pairs the merge finishes sooner; a higher one leaves mid-sized pairs on the slower merge.\nconst PROBE_MIN = 32;\n\n// How many merge steps `intersectsArrays` takes before it falls back to the scratch bitset. The value is chosen, not measured to\n// be the best: a pair that shares a value inside the first steps answers without setting a bit, and a pair that shares nothing\n// there pays the steps and then the scratch bitset. Two random sets of a thousand values in one chunk share about 15 values\n// (derived), so most such pairs share none in 64 steps and reach the bitset; probes of 320 steps made the overlapping pair\n// about four times faster and the disjoint pair about 30 percent slower (indicative), and neither is kept.\nexport const MERGE_FIRST = 64;\n\n// Scratch bitset for the array probe: all zero between calls (each call clears what it set).\nconst probeWords = new Uint32Array(WORDS);\n\n/** Values both arrays hold. */\nfunction andArrays(a: Container, b: Container): Container | null {\n const small = a.len <= b.len ? a : b;\n const big = small === a ? b : a;\n const s = lows16(small);\n const l = lows16(big);\n const out = values16(small.len);\n let n = 0;\n if (small.len >= PROBE_MIN && !skewed(small.len, big.len)) {\n const se = small.off + small.len;\n const first = s[small.off] as number;\n const last = s[se - 1] as number;\n // Only the span of `big` between the shorter array's ends can hold a match.\n const le = big.off + big.len;\n if (last < (l[big.off] as number) || first > (l[le - 1] as number)) return null;\n const from = gallop(l, 0, big.off, le, first);\n const to = gallop(l, 0, from, le, last + 1);\n const words = probeWords;\n for (let i = small.off; i < se; i++) {\n const v = s[i] as number;\n words[v >>> 5] = (words[v >>> 5] as number) | (1 << (v & 31));\n }\n for (let j = from; j < to; j++) {\n const v = l[j] as number;\n // The slot is written whether or not `v` is in the set; only a hit moves `n` past it.\n out[n] = v;\n n += ((words[v >>> 5] as number) >>> (v & 31)) & 1;\n }\n for (let i = small.off; i < se; i++) words[(s[i] as number) >>> 5] = 0;\n return arrayOfScratch(out, n);\n }\n if (skewed(small.len, big.len)) {\n let at = 0;\n const end = big.off + big.len;\n for (let i = small.off; i < small.off + small.len; i++) {\n const v = s[i] as number;\n at = gallop(l, 0, Math.max(at, big.off), end, v);\n if (at === end) break;\n if (l[at] === v) out[n++] = v;\n }\n return arrayOfScratch(out, n);\n }\n let i = small.off;\n let j = big.off;\n const ie = small.off + small.len;\n const je = big.off + big.len;\n while (i < ie && j < je) {\n const x = s[i] as number;\n const y = l[j] as number;\n // No branch on the comparison: it is unpredictable on random data, and a misprediction costs more than the\n // three adds. The slot is written whether or not the values match; only a match moves `n` past it.\n out[n] = x;\n n += x === y ? 1 : 0;\n i += x <= y ? 1 : 0;\n j += x >= y ? 1 : 0;\n }\n return arrayOfScratch(out, n);\n}\n\n/** The values of array `a` whose membership in `b` (a bitset) is `keep`. */\nfunction filterByBits(a: Container, b: Container, keep: boolean): Container | null {\n const u16 = lows16(a);\n const words = words32(b);\n const out = values16(a.len);\n const flip = keep ? 0 : 1;\n let n = 0;\n for (let i = a.off; i < a.off + a.len; i++) {\n const v = u16[i] as number;\n // Written whether or not `v` is kept; only a kept value moves `n` past its slot (no unpredictable branch).\n out[n] = v;\n n += (((words[v >>> 5] as number) >>> (v & 31)) & 1) ^ flip;\n }\n return arrayOfScratch(out, n);\n}\n\n/** The values of array `a` whose membership in the runs of `b` is `keep`. */\nfunction filterByRuns(a: Container, b: Container, keep: boolean): Container | null {\n const u16 = lows16(a);\n const pairs = lows16(b);\n const out = values16(a.len);\n let n = 0;\n // Walking the runs costs one step per run and per value, so it wins once values are at least as many as runs; with\n // fewer values the per-value walk skips the runs it does not need to visit.\n if (keep && a.len >= b.len) {\n // At least as many values as runs: walk the runs, skipping the values below each and copying those inside it.\n const ae = a.off + a.len;\n let i = a.off;\n for (let r = 0; r < b.len && i < ae; r++) {\n const start = pairs[b.off + 2 * r] as number;\n const end = start + (pairs[b.off + 2 * r + 1] as number);\n while (i < ae && (u16[i] as number) < start) i++;\n while (i < ae && (u16[i] as number) <= end) out[n++] = u16[i++] as number;\n }\n return arrayOfScratch(out, n);\n }\n let r = 0;\n for (let i = a.off; i < a.off + a.len; i++) {\n const v = u16[i] as number;\n // The first run that ends at or after `v`.\n while (\n r < b.len &&\n (pairs[b.off + 2 * r] as number) + (pairs[b.off + 2 * r + 1] as number) < v\n ) {\n r++;\n }\n const inside = r < b.len && (pairs[b.off + 2 * r] as number) <= v;\n if (inside === keep) out[n++] = v;\n }\n return arrayOfScratch(out, n);\n}\n\n/** The values of `a` that `b` lacks, both arrays. */\nfunction andNotArrays(a: Container, b: Container): Container | null {\n const x = lows16(a);\n const y = lows16(b);\n const out = values16(a.len);\n let n = 0;\n const je = b.off + b.len;\n if (skewed(a.len, b.len)) {\n let at = b.off;\n for (let i = a.off; i < a.off + a.len; i++) {\n const v = x[i] as number;\n at = gallop(y, 0, at, je, v);\n if (at === je || y[at] !== v) out[n++] = v;\n }\n return arrayOfScratch(out, n);\n }\n if (b.len >= PROBE_MIN) {\n // Similar sizes: mark the part of `b` inside `a`'s span in the scratch bitset, then keep each value of `a` whose bit\n // is clear. Both arrays are read once, in order, with no unpredictable branch.\n const ae = a.off + a.len;\n const first = x[a.off] as number;\n const last = x[ae - 1] as number;\n const from = gallop(y, 0, b.off, je, first);\n const to = gallop(y, 0, from, je, last + 1);\n const words = probeWords;\n for (let j = from; j < to; j++) {\n const v = y[j] as number;\n words[v >>> 5] = (words[v >>> 5] as number) | (1 << (v & 31));\n }\n for (let i = a.off; i < ae; i++) {\n const v = x[i] as number;\n // Written whether or not `v` is kept; only a kept value moves `n` past its slot.\n out[n] = v;\n n += (((words[v >>> 5] as number) >>> (v & 31)) & 1) ^ 1;\n }\n for (let j = from; j < to; j++) words[(y[j] as number) >>> 5] = 0;\n return arrayOfScratch(out, n);\n }\n let i = a.off;\n let j = b.off;\n const ie = a.off + a.len;\n while (i < ie && j < je) {\n const p = x[i] as number;\n const q = y[j] as number;\n out[n] = p;\n n += p < q ? 1 : 0;\n i += p <= q ? 1 : 0;\n j += p >= q ? 1 : 0;\n }\n while (i < ie) out[n++] = x[i++] as number;\n return arrayOfScratch(out, n);\n}\n\n/** The values either array holds. */\nfunction orArrays(a: Container, b: Container): Container {\n const x = lows16(a);\n const y = lows16(b);\n const ie = a.off + a.len;\n const je = b.off + b.len;\n if (a.len + b.len > ARRAY_MAX_CARDINALITY) {\n const words = new Uint32Array(WORDS);\n for (let i = a.off; i < ie; i++) {\n const v = x[i] as number;\n words[v >>> 5] = (words[v >>> 5] as number) | (1 << (v & 31));\n }\n for (let j = b.off; j < je; j++) {\n const v = y[j] as number;\n words[v >>> 5] = (words[v >>> 5] as number) | (1 << (v & 31));\n }\n return fromWordsCard(words, popcountWords(words)) as Container;\n }\n const out = values16(a.len + b.len);\n let n = 0;\n let i = a.off;\n let j = b.off;\n while (i < ie && j < je) {\n const p = x[i] as number;\n const q = y[j] as number;\n out[n++] = p < q ? p : q;\n i += p <= q ? 1 : 0;\n j += p >= q ? 1 : 0;\n }\n while (i < ie) out[n++] = x[i++] as number;\n while (j < je) out[n++] = y[j++] as number;\n return arrayOfScratch(out, n) as Container;\n}\n\n/** `out` = `x` AND `y` over WORDS words, four a step; `out` may be `x` or `y`. */\nfunction andWords(out: Uint32Array, x: Uint32Array, y: Uint32Array): void {\n for (let i = 0; i < WORDS; i += 4) {\n const X0 = x[i] as number;\n const Y0 = y[i] as number;\n const X1 = x[i + 1] as number;\n const Y1 = y[i + 1] as number;\n const X2 = x[i + 2] as number;\n const Y2 = y[i + 2] as number;\n const X3 = x[i + 3] as number;\n const Y3 = y[i + 3] as number;\n out[i] = X0 & Y0;\n out[i + 1] = X1 & Y1;\n out[i + 2] = X2 & Y2;\n out[i + 3] = X3 & Y3;\n }\n}\n\n/** `out` = `x` OR `y` over WORDS words, four a step; `out` may be `x` or `y`. */\nfunction orWords(out: Uint32Array, x: Uint32Array, y: Uint32Array): void {\n for (let i = 0; i < WORDS; i += 4) {\n const X0 = x[i] as number;\n const Y0 = y[i] as number;\n const X1 = x[i + 1] as number;\n const Y1 = y[i + 1] as number;\n const X2 = x[i + 2] as number;\n const Y2 = y[i + 2] as number;\n const X3 = x[i + 3] as number;\n const Y3 = y[i + 3] as number;\n out[i] = X0 | Y0;\n out[i + 1] = X1 | Y1;\n out[i + 2] = X2 | Y2;\n out[i + 3] = X3 | Y3;\n }\n}\n\n/** `out` = `x` XOR `y` over WORDS words, four a step; `out` may be `x` or `y`. */\nfunction xorWords(out: Uint32Array, x: Uint32Array, y: Uint32Array): void {\n for (let i = 0; i < WORDS; i += 4) {\n const X0 = x[i] as number;\n const Y0 = y[i] as number;\n const X1 = x[i + 1] as number;\n const Y1 = y[i + 1] as number;\n const X2 = x[i + 2] as number;\n const Y2 = y[i + 2] as number;\n const X3 = x[i + 3] as number;\n const Y3 = y[i + 3] as number;\n out[i] = X0 ^ Y0;\n out[i + 1] = X1 ^ Y1;\n out[i + 2] = X2 ^ Y2;\n out[i + 3] = X3 ^ Y3;\n }\n}\n\n/** `out` = `x` AND NOT `y` over WORDS words, four a step; `out` may be `x` or `y`. */\nfunction andNotWords(out: Uint32Array, x: Uint32Array, y: Uint32Array): void {\n for (let i = 0; i < WORDS; i += 4) {\n const X0 = x[i] as number;\n const Y0 = y[i] as number;\n const X1 = x[i + 1] as number;\n const Y1 = y[i + 1] as number;\n const X2 = x[i + 2] as number;\n const Y2 = y[i + 2] as number;\n const X3 = x[i + 3] as number;\n const Y3 = y[i + 3] as number;\n out[i] = X0 & ~Y0;\n out[i + 1] = X1 & ~Y1;\n out[i + 2] = X2 & ~Y2;\n out[i + 3] = X3 & ~Y3;\n }\n}\n\n/** `dest` (a bitset) or `other`, into words: `dest`'s own words when `inPlace`, else a copy. */\nfunction orIntoBitset(dest: Container, other: Container, inPlace: boolean): Container {\n const words = inPlace ? words32(dest) : words32(dest).slice();\n if (other.kind === ARRAY) {\n const u16 = lows16(other);\n let card = dest.card;\n for (let i = other.off; i < other.off + other.len; i++) {\n const v = u16[i] as number;\n const w = words[v >>> 5] as number;\n const bit = 1 << (v & 31);\n if ((w & bit) === 0) {\n words[v >>> 5] = w | bit;\n card++;\n }\n }\n return bitsetContainer(words, card);\n }\n if (other.kind === BITSET) {\n orWords(words, words, words32(other));\n } else {\n const pairs = lows16(other);\n for (let r = 0; r < other.len; r++) {\n const start = pairs[other.off + 2 * r] as number;\n setRange(words, start, start + (pairs[other.off + 2 * r + 1] as number));\n }\n }\n return bitsetContainer(words, popcountWords(words));\n}\n\n/**\n * A new accumulator holding the OR of the bitset containers of `list` (all zero when there is none), four sources a\n * step: each word is loaded from the accumulator once per four sources, not once per source, and the first group writes\n * the accumulator, so no source is copied. Fewer than four sources, and the tail of any more, go one at a time.\n */\nfunction orBitsetWords(list: readonly Container[]): Uint32Array {\n const bits: Uint32Array[] = [];\n for (const c of list) if (c.kind === BITSET) bits.push(words32(c));\n const n = bits.length;\n if (n === 0) return new Uint32Array(WORDS);\n let k: number;\n let words: Uint32Array;\n if (n >= 4) {\n const a = bits[0] as Uint32Array;\n const b = bits[1] as Uint32Array;\n const c = bits[2] as Uint32Array;\n const d = bits[3] as Uint32Array;\n words = new Uint32Array(WORDS);\n for (let i = 0; i < WORDS; i++)\n words[i] = (a[i] as number) | (b[i] as number) | (c[i] as number) | (d[i] as number);\n k = 4;\n } else {\n words = (bits[0] as Uint32Array).slice();\n k = 1;\n }\n for (; k + 4 <= n; k += 4) {\n const a = bits[k] as Uint32Array;\n const b = bits[k + 1] as Uint32Array;\n const c = bits[k + 2] as Uint32Array;\n const d = bits[k + 3] as Uint32Array;\n for (let i = 0; i < WORDS; i++) {\n words[i] =\n (words[i] as number) |\n (a[i] as number) |\n (b[i] as number) |\n (c[i] as number) |\n (d[i] as number);\n }\n }\n for (; k < n; k++) {\n const o = bits[k] as Uint32Array;\n for (let i = 0; i < WORDS; i++) words[i] = (words[i] as number) | (o[i] as number);\n }\n return words;\n}\n\n/**\n * The values of every container of `list` (two or more, all of one key), as a container of its own: an array up to\n * 4,096 values, a bitset above, never a run. No input is written and none is kept. Arrays whose total fits an array are\n * sorted together; anything else is OR-ed into one accumulator of words (a bitset's words, an array's values set\n * bit by bit, a run's range filled) whose bits are counted once at the end, where a pairwise fold would count the\n * whole accumulator after every input.\n */\nexport function orManyContainers(list: readonly Container[]): Container {\n let total = 0;\n let allArrays = true;\n for (const c of list) {\n total += c.card;\n if (c.kind !== ARRAY) allArrays = false;\n }\n if (allArrays && total <= ARRAY_MAX_CARDINALITY) {\n const out = values16(total);\n let n = 0;\n for (const c of list) {\n out.set(lows16(c).subarray(c.off, c.off + c.len), n);\n n += c.len;\n }\n const sorted = out.subarray(0, n).sort();\n let distinct = 0;\n for (let i = 0; i < n; i++) {\n const v = sorted[i] as number;\n if (i === 0 || v !== (sorted[distinct - 1] as number)) sorted[distinct++] = v;\n }\n return arrayContainer(sorted.slice(0, distinct), distinct);\n }\n const words = orBitsetWords(list);\n for (const c of list) {\n if (c.kind === ARRAY) {\n const u16 = lows16(c);\n for (let i = c.off; i < c.off + c.len; i++) {\n const v = u16[i] as number;\n words[v >>> 5] = (words[v >>> 5] as number) | (1 << (v & 31));\n }\n } else if (c.kind === RUN) {\n const pairs = lows16(c);\n for (let r = 0; r < c.len; r++) {\n const start = pairs[c.off + 2 * r] as number;\n setRange(words, start, start + (pairs[c.off + 2 * r + 1] as number));\n }\n }\n }\n return fromWordsCard(words, popcountWords(words)) as Container;\n}\n\n/** A result built from the first `runs` pairs of `pairs`, whose values number `card`: an array up to 4,096 values, else a bitset. */\nfunction fromRunPairs(pairs: Uint16Array, runs: number, card: number): Container | null {\n if (card === 0) return null;\n if (card <= ARRAY_MAX_CARDINALITY) {\n const out = new Uint16Array(card);\n let k = 0;\n for (let r = 0; r < runs; r++) {\n const start = pairs[2 * r] as number;\n const end = start + (pairs[2 * r + 1] as number);\n for (let v = start; v <= end; v++) out[k++] = v;\n }\n return arrayContainer(out, card);\n }\n const words = new Uint32Array(WORDS);\n for (let r = 0; r < runs; r++) {\n const start = pairs[2 * r] as number;\n setRange(words, start, start + (pairs[2 * r + 1] as number));\n }\n return bitsetContainer(words, card);\n}\n\n/** The values both run containers hold. */\nfunction andRuns(a: Container, b: Container): Container | null {\n const x = lows16(a);\n const y = lows16(b);\n const out = pairs16(2 * (a.len + b.len));\n let runs = 0;\n let card = 0;\n let i = 0;\n let j = 0;\n while (i < a.len && j < b.len) {\n const as = x[a.off + 2 * i] as number;\n const ae = as + (x[a.off + 2 * i + 1] as number);\n const bs = y[b.off + 2 * j] as number;\n const be = bs + (y[b.off + 2 * j + 1] as number);\n const lo = as > bs ? as : bs;\n const hi = ae < be ? ae : be;\n if (lo <= hi) {\n out[2 * runs] = lo;\n out[2 * runs + 1] = hi - lo;\n runs++;\n card += hi - lo + 1;\n }\n if (ae < be) i++;\n else j++;\n }\n return card === 0 ? null : runsOrPlain(out, runs, card, true);\n}\n\n/** The values either run container holds. */\nfunction orRuns(a: Container, b: Container): Container {\n const x = lows16(a);\n const y = lows16(b);\n const out = pairs16(2 * (a.len + b.len));\n let runs = 0;\n let card = 0;\n let i = 0;\n let j = 0;\n let start = -1;\n let end = -1;\n const flush = (): void => {\n if (start < 0) return;\n out[2 * runs] = start;\n out[2 * runs + 1] = end - start;\n runs++;\n card += end - start + 1;\n };\n while (i < a.len || j < b.len) {\n let s: number;\n let e: number;\n if (j >= b.len || (i < a.len && (x[a.off + 2 * i] as number) <= (y[b.off + 2 * j] as number))) {\n s = x[a.off + 2 * i] as number;\n e = s + (x[a.off + 2 * i + 1] as number);\n i++;\n } else {\n s = y[b.off + 2 * j] as number;\n e = s + (y[b.off + 2 * j + 1] as number);\n j++;\n }\n if (start >= 0 && s <= end + 1) {\n if (e > end) end = e;\n } else {\n flush();\n start = s;\n end = e;\n }\n }\n flush();\n return runsOrPlain(out, runs, card, true);\n}\n\n/** The values of `a` that `b` lacks, both run containers. */\nfunction andNotRuns(a: Container, b: Container): Container | null {\n const x = lows16(a);\n const y = lows16(b);\n const out = pairs16(2 * (a.len + b.len + 1));\n let runs = 0;\n let card = 0;\n let j = 0;\n for (let i = 0; i < a.len; i++) {\n let s = x[a.off + 2 * i] as number;\n const e = s + (x[a.off + 2 * i + 1] as number);\n while (j < b.len && (y[b.off + 2 * j] as number) + (y[b.off + 2 * j + 1] as number) < s) j++;\n let k = j;\n while (s <= e) {\n if (k >= b.len || (y[b.off + 2 * k] as number) > e) {\n out[2 * runs] = s;\n out[2 * runs + 1] = e - s;\n runs++;\n card += e - s + 1;\n break;\n }\n const bs = y[b.off + 2 * k] as number;\n const be = bs + (y[b.off + 2 * k + 1] as number);\n if (bs > s) {\n out[2 * runs] = s;\n out[2 * runs + 1] = bs - 1 - s;\n runs++;\n card += bs - s;\n }\n s = be + 1;\n k++;\n }\n }\n return card === 0 ? null : runsOrPlain(out, runs, card, true);\n}\n\n/**\n * The values of bitset `a` inside the runs of `b`. Only the words a run covers are read, each masked to the run's ends.\n * A run container of at most 4,096 values cannot produce more than an array holds, so its result is written straight to\n * an array (no 8 KiB bitset, no popcount); a larger one is built as words and counted once, with Harley-Seal, which\n * beats counting each covered word when the runs cover many of them.\n */\nfunction bitsetInRuns(a: Container, b: Container): Container | null {\n const words = words32(a);\n const pairs = lows16(b);\n if (b.card <= ARRAY_MAX_CARDINALITY) {\n const out = values16(b.card);\n let n = 0;\n for (let r = 0; r < b.len; r++) {\n const start = pairs[b.off + 2 * r] as number;\n const end = start + (pairs[b.off + 2 * r + 1] as number);\n const first = start >>> 5;\n const last = end >>> 5;\n const head = (0xffff_ffff << (start & 31)) >>> 0;\n const tail = 0xffff_ffff >>> (31 - (end & 31));\n for (let i = first; i <= last; i++) {\n let w = words[i] as number;\n if (i === first) w &= head;\n if (i === last) w &= tail;\n const top = i * 32 + 31;\n while (w !== 0) {\n const lowest = w & -w;\n out[n++] = top - Math.clz32(lowest);\n w ^= lowest;\n }\n }\n }\n return arrayOfScratch(out, n);\n }\n const out = new Uint32Array(WORDS);\n for (let r = 0; r < b.len; r++) {\n const start = pairs[b.off + 2 * r] as number;\n const end = start + (pairs[b.off + 2 * r + 1] as number);\n const first = start >>> 5;\n const last = end >>> 5;\n const head = (0xffff_ffff << (start & 31)) >>> 0;\n const tail = 0xffff_ffff >>> (31 - (end & 31));\n if (first === last) {\n out[first] = (out[first] as number) | ((words[first] as number) & head & tail);\n } else {\n out[first] = (out[first] as number) | ((words[first] as number) & head);\n for (let i = first + 1; i < last; i++) out[i] = words[i] as number;\n out[last] = (out[last] as number) | ((words[last] as number) & tail);\n }\n }\n return fromWordsCard(out, popcountWords(out));\n}\n\n/** The values both hold, or `null` when there are none. Neither operand is changed unless `inPlace` and `a` is a bitset (see the module comment). */\nexport function containerAnd(a: Container, b: Container, inPlace = false): Container | null {\n if (a.kind === BITSET && b.kind === BITSET) {\n const x = words32(a);\n const y = words32(b);\n const out = inPlace ? x : new Uint32Array(WORDS);\n andWords(out, x, y);\n return fromWordsCard(out, popcountWords(out));\n }\n // Commutative: put the lower kind first (array, bitset, run).\n if (a.kind > b.kind) return containerAnd(b, a);\n if (a.kind === ARRAY) {\n if (b.kind === ARRAY) return andArrays(a, b);\n return b.kind === BITSET ? filterByBits(a, b, true) : filterByRuns(a, b, true);\n }\n return b.kind === RUN && a.kind === RUN ? andRuns(a, b) : bitsetInRuns(a, b);\n}\n\n/** The values either holds. */\nexport function containerOr(a: Container, b: Container, inPlace = false): Container {\n if (a.kind === BITSET) return orIntoBitset(a, b, inPlace);\n if (b.kind === BITSET) return orIntoBitset(b, a, false);\n if (a.kind === ARRAY && b.kind === ARRAY) return orArrays(a, b);\n if (a.kind === RUN && b.kind === RUN) return orRuns(a, b);\n return a.kind === RUN ? orRunArray(a, b, inPlace) : orRunArray(b, a, false);\n}\n\n/**\n * How many steps of the merge walk (the runs plus the values) a run container and an array take before expanding the run\n * container to words is the cheaper way to write the array into it: the walk costs a few nanoseconds a step, the\n * expansion a fixed 8 KB of words (zeroed, one range set per run, one pass to count the runs of the result).\n */\nexport const EXPAND_MIN_STEPS = 1024;\n\n/**\n * Whether {@link orRunArray} writes the array into the run container through words instead of the merge walk: from\n * {@link EXPAND_MIN_STEPS} steps up, and when the result is likely not to be a run container. The result has at most\n * `runs.len + array.len` runs, so when that many runs already fail the size rule against the plain body of the largest\n * result, the walk would probably build a run list only to expand it again; the result can have far fewer runs than that\n * bound (values that fall inside runs add none), so this is a heuristic about speed. A pure function of the two containers' lengths and\n * cardinalities, so it costs one comparison on the hot path; either choice returns the same container.\n */\nexport function expandsRunArray(runs: Container, array: Container): boolean {\n return expandsRunSteps(runs, array.len);\n}\n\n/**\n * {@link expandsRunArray} for a run container and `values` values to write into it: the one size rule, on numbers, so a\n * walk that reads its values from an id list and one that reads an array container choose alike.\n */\nexport function expandsRunSteps(runs: Container, values: number): boolean {\n const steps = runs.len + values;\n if (steps < EXPAND_MIN_STEPS) return false;\n const cardMax = runs.card + values;\n const plainMax = cardMax <= ARRAY_MAX_CARDINALITY ? 2 * cardMax : BITSET_BYTES;\n return 2 + 4 * steps >= plainMax;\n}\n\n/**\n * Whether a group of `count` ids goes into the run container `runs` by {@link orRunIdsWalk}: the size rule sends it to\n * the merge walk. The rule refuses from 2,048 steps (the runs plus the ids) up, since `2 + 4 * steps >= 8192` first holds there (2,047\n * steps still walk), so the walk takes at most 2,046 ids for one run, fewer for more runs, and fewer\n * again when the result is small enough for the plain body to be an array. Every other group takes the container merge.\n */\nexport function walksRunIds(runs: Container, count: number): boolean {\n return runs.kind === RUN && !expandsRunSteps(runs, count);\n}\n\n/**\n * A run container with an array's values written through words: the runs are set in a new bitset, then each value, and\n * the container of the result is the canonical one for its values (a run container only when its body is the smaller\n * one: {@link optimize}). When the array adds nothing and `keep` allows, the run container itself is the result.\n */\nexport function orRunArrayExpand(runs: Container, array: Container, keep: boolean): Container {\n const words = toWords(runs);\n const v = lows16(array);\n let added = 0;\n for (let i = array.off; i < array.off + array.len; i++) {\n const value = v[i] as number;\n const word = words[value >>> 5] as number;\n const bit = 1 << (value & 31);\n if ((word & bit) === 0) {\n words[value >>> 5] = word | bit;\n added++;\n }\n }\n if (added === 0 && keep) return runs;\n return optimize(fromWordsCard(words, runs.card + added) as Container);\n}\n\n/** A run container with an array's values: by the merge walk, or through words when that is cheaper (see {@link expandsRunArray}). */\nfunction orRunArray(runs: Container, array: Container, keep: boolean): Container {\n return expandsRunArray(runs, array)\n ? orRunArrayExpand(runs, array, keep)\n : orRunArrayWalk(runs, array, keep);\n}\n\n/**\n * A run container with an array's values, merged in one walk over both lists: each step takes whichever of the next run\n * and the next value starts first and appends it to the result, joining it to the pair being built when they touch or\n * overlap. Cost is the runs plus the values, with no search or view per value, and no expansion to 8 KB of words. The\n * result is a run container while that is the smaller form (see {@link runsOrPlain}). When the array adds nothing and\n * `keep` allows, the run container itself is the result: runs are never written in place, so aliasing it is safe.\n */\nexport function orRunArrayWalk(runs: Container, array: Container, keep: boolean): Container {\n const x = lows16(runs);\n const v = lows16(array);\n const out = pairs16(2 * (runs.len + array.len));\n const runEnd = runs.off + 2 * runs.len;\n const valueEnd = array.off + array.len;\n let r = runs.off;\n let vi = array.off;\n let at = 0;\n // The pair being built, `[from, to]`; `to` is -2 before there is one, so nothing is next to it.\n let from = 0;\n let to = -2;\n let added = 0;\n while (vi < valueEnd) {\n const value = v[vi++] as number;\n // Every run that starts at or before the value comes first; one that reaches it holds it.\n while (r < runEnd && (x[r] as number) <= value) {\n const start = x[r] as number;\n const end = start + (x[r + 1] as number);\n r += 2;\n if (start <= to + 1) {\n if (end > to) to = end;\n } else {\n if (to >= 0) {\n out[at++] = from;\n out[at++] = to - from;\n }\n from = start;\n to = end;\n }\n }\n if (value <= to) continue;\n added++;\n if (value === to + 1) {\n to = value;\n } else {\n if (to >= 0) {\n out[at++] = from;\n out[at++] = to - from;\n }\n from = value;\n to = value;\n }\n }\n while (r < runEnd) {\n const start = x[r] as number;\n const end = start + (x[r + 1] as number);\n r += 2;\n if (start <= to + 1) {\n if (end > to) to = end;\n } else {\n if (to >= 0) {\n out[at++] = from;\n out[at++] = to - from;\n }\n from = start;\n to = end;\n }\n }\n out[at++] = from;\n out[at++] = to - from;\n if (added === 0 && keep) return runs;\n return runsOrPlain(out, at >>> 1, runs.card + added, true);\n}\n\n/**\n * The ids `ids[from, to)` (ascending, all of one key, duplicates allowed, only the low 16 bits kept) written into a run\n * container by the merge walk of {@link orRunArrayWalk}, reading the ids where they are instead of from a container\n * built for them. The same walk, so the result is the same container for the same values; `runs` itself when the ids add\n * nothing. A copy of the walk, not a shared one: each walk reads one kind of array (16-bit values here, 32-bit ids\n * there), so its element reads stay of one kind for the engine, where a shared walk would see both. A test holds the\n * two to the same container for the same values.\n */\nexport function orRunIdsWalk(\n runs: Container,\n ids: Uint32Array,\n from: number,\n to: number,\n): Container {\n const x = lows16(runs);\n const out = pairs16(2 * (runs.len + to - from));\n const runEnd = runs.off + 2 * runs.len;\n let r = runs.off;\n let vi = from;\n let at = 0;\n // The pair being built, `[start, last]`; `last` is -2 before there is one, so nothing is next to it.\n let start = 0;\n let last = -2;\n let added = 0;\n while (vi < to) {\n const value = (ids[vi++] as number) & 0xffff;\n while (r < runEnd && (x[r] as number) <= value) {\n const s = x[r] as number;\n const end = s + (x[r + 1] as number);\n r += 2;\n if (s <= last + 1) {\n if (end > last) last = end;\n } else {\n if (last >= 0) {\n out[at++] = start;\n out[at++] = last - start;\n }\n start = s;\n last = end;\n }\n }\n if (value <= last) continue;\n added++;\n if (value === last + 1) {\n last = value;\n } else {\n if (last >= 0) {\n out[at++] = start;\n out[at++] = last - start;\n }\n start = value;\n last = value;\n }\n }\n while (r < runEnd) {\n const s = x[r] as number;\n const end = s + (x[r + 1] as number);\n r += 2;\n if (s <= last + 1) {\n if (end > last) last = end;\n } else {\n if (last >= 0) {\n out[at++] = start;\n out[at++] = last - start;\n }\n start = s;\n last = end;\n }\n }\n out[at++] = start;\n out[at++] = last - start;\n if (added === 0) return runs;\n return runsOrPlain(out, at >>> 1, runs.card + added, true);\n}\n\n/** The values of `a` that `b` lacks, or `null` when there are none. */\nexport function containerAndNot(a: Container, b: Container, inPlace = false): Container | null {\n if (a.kind === ARRAY) {\n if (b.kind === ARRAY) return andNotArrays(a, b);\n return b.kind === BITSET ? filterByBits(a, b, false) : filterByRuns(a, b, false);\n }\n if (a.kind === RUN && b.kind === RUN) return andNotRuns(a, b);\n // A bitset, or a run container expanded to words (which it owns).\n const words = a.kind === BITSET ? (inPlace ? words32(a) : words32(a).slice()) : toWords(a);\n if (b.kind === ARRAY) {\n const u16 = lows16(b);\n for (let i = b.off; i < b.off + b.len; i++) {\n const v = u16[i] as number;\n words[v >>> 5] = (words[v >>> 5] as number) & ~(1 << (v & 31));\n }\n } else if (b.kind === BITSET) {\n andNotWords(words, words, words32(b));\n } else {\n const pairs = lows16(b);\n for (let r = 0; r < b.len; r++) {\n const start = pairs[b.off + 2 * r] as number;\n clearRange(words, start, start + (pairs[b.off + 2 * r + 1] as number));\n }\n }\n return fromWordsCard(words, popcountWords(words));\n}\n\n/** The values exactly one array holds: one merge that drops a value both hold. */\nfunction xorArrays(a: Container, b: Container): Container | null {\n const x = lows16(a);\n const y = lows16(b);\n const ie = a.off + a.len;\n const je = b.off + b.len;\n const out = values16(a.len + b.len);\n let n = 0;\n let i = a.off;\n let j = b.off;\n while (i < ie && j < je) {\n const p = x[i] as number;\n const q = y[j] as number;\n out[n] = p < q ? p : q;\n // A value both hold is written over by the next one.\n n += p === q ? 0 : 1;\n i += p <= q ? 1 : 0;\n j += p >= q ? 1 : 0;\n }\n while (i < ie) out[n++] = x[i++] as number;\n while (j < je) out[n++] = y[j++] as number;\n if (n <= ARRAY_MAX_CARDINALITY) return arrayOfScratch(out, n);\n const words = new Uint32Array(WORDS);\n for (let k = 0; k < n; k++) {\n const v = out[k] as number;\n words[v >>> 5] = (words[v >>> 5] as number) | (1 << (v & 31));\n }\n return bitsetContainer(words, n);\n}\n\n/**\n * The values exactly one run container holds, as one walk over the run boundaries of both. A run `(start, length - 1)`\n * opens at `start` and closes at `start + length`; the boundaries of one list ascend strictly (its runs neither touch\n * nor overlap), and a boundary both lists have cancels, so what is left alternates open, close and any two pieces that\n * touch have already joined.\n */\nfunction xorRuns(a: Container, b: Container): Container | null {\n const x = lows16(a);\n const y = lows16(b);\n const na = 2 * a.len;\n const nb = 2 * b.len;\n const out = pairs16(2 * (a.len + b.len));\n const NONE = 0x7fff_ffff;\n let i = 0;\n let j = 0;\n let pa = na > 0 ? boundary(x, a.off, 0) : NONE;\n let pb = nb > 0 ? boundary(y, b.off, 0) : NONE;\n let open = -1;\n let runs = 0;\n let card = 0;\n while (i < na || j < nb) {\n let p: number;\n if (pa === pb) {\n // The boundary is in both lists: it cancels.\n i++;\n j++;\n pa = i < na ? boundary(x, a.off, i) : NONE;\n pb = j < nb ? boundary(y, b.off, j) : NONE;\n continue;\n }\n if (pa < pb) {\n p = pa;\n i++;\n pa = i < na ? boundary(x, a.off, i) : NONE;\n } else {\n p = pb;\n j++;\n pb = j < nb ? boundary(y, b.off, j) : NONE;\n }\n if (open < 0) {\n open = p;\n } else {\n out[2 * runs] = open;\n out[2 * runs + 1] = p - 1 - open;\n runs++;\n card += p - open;\n open = -1;\n }\n }\n return card === 0 ? null : runsOrPlain(out, runs, card, true);\n}\n\n/** Boundary `k` of a run list at `off`: pair `k >> 1`'s start when `k` is even and one past its last value when odd. */\nfunction boundary(u16: Uint16Array, off: number, k: number): number {\n const at = off + (k & ~1);\n return (u16[at] as number) + ((k & 1) === 0 ? 0 : (u16[at + 1] as number) + 1);\n}\n\n/**\n * The values exactly one of the two holds, or `null` when there are none, built in one pass over the pair by their\n * kinds: one word loop and one count for two bitsets, one merge for two arrays, one walk for two run containers, and\n * for any pair with a bitset the bitset's words (a copy, or its own when `inPlace` and `a` is the bitset) with the\n * other side's values flipped in. Array against run goes through words. Neither operand is changed unless `inPlace`\n * and `a` is a bitset (see the module comment).\n */\nexport function containerXor(a: Container, b: Container, inPlace = false): Container | null {\n if (a.kind === BITSET || b.kind === BITSET) {\n const base = a.kind === BITSET ? a : b;\n const other = base === a ? b : a;\n if (other.kind === BITSET) {\n const x = words32(a);\n const y = words32(b);\n const out = inPlace ? x : new Uint32Array(WORDS);\n xorWords(out, x, y);\n return fromWordsCard(out, popcountWords(out));\n }\n const words = inPlace && base === a ? words32(base) : words32(base).slice();\n if (other.kind === ARRAY) {\n return fromWordsCard(words, flipValues(words, other, base.card));\n }\n const pairs = lows16(other);\n for (let r = 0; r < other.len; r++) {\n const start = pairs[other.off + 2 * r] as number;\n flipRange(words, start, start + (pairs[other.off + 2 * r + 1] as number));\n }\n return fromWordsCard(words, popcountWords(words));\n }\n if (a.kind === ARRAY && b.kind === ARRAY) return xorArrays(a, b);\n if (a.kind === RUN && b.kind === RUN) return xorRuns(a, b);\n const runs = a.kind === RUN ? a : b;\n const array = runs === a ? b : a;\n const words = toWords(runs);\n return fromWordsCard(words, flipValues(words, array, runs.card));\n}\n\n/** Flip the bits of `array`'s values in `words`, which hold `card` set bits; returns the count after. */\nfunction flipValues(words: Uint32Array, array: Container, card: number): number {\n const u16 = lows16(array);\n let n = card;\n for (let i = array.off; i < array.off + array.len; i++) {\n const v = u16[i] as number;\n const w = words[v >>> 5] as number;\n words[v >>> 5] = w ^ (1 << (v & 31));\n n += 1 - 2 * ((w >>> (v & 31)) & 1);\n }\n return n;\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Counting a combine without building it\n// ---------------------------------------------------------------------------------------------------------------\n\n/** Set bits of `words` from bit `start` to bit `end`, both inclusive. */\nfunction bitsInRange(words: Uint32Array, start: number, end: number): number {\n const first = start >>> 5;\n const last = end >>> 5;\n const head = (0xffff_ffff << (start & 31)) >>> 0;\n const tail = 0xffff_ffff >>> (31 - (end & 31));\n if (first === last) return popcount32((words[first] as number) & head & tail);\n let n = popcount32((words[first] as number) & head) + popcount32((words[last] as number) & tail);\n for (let i = first + 1; i < last; i++) n += popcount32(words[i] as number);\n return n;\n}\n\n/** Values both arrays hold: a merge that writes nothing, or a gallop of the shorter over the longer when one is much longer. */\nfunction andCountArrays(a: Container, b: Container): number {\n const small = a.len <= b.len ? a : b;\n const big = small === a ? b : a;\n const s = lows16(small);\n const l = lows16(big);\n const se = small.off + small.len;\n const le = big.off + big.len;\n let n = 0;\n if (skewed(small.len, big.len)) {\n let at = big.off;\n for (let i = small.off; i < se; i++) {\n const v = s[i] as number;\n at = gallop(l, 0, at, le, v);\n if (at === le) break;\n if (l[at] === v) n++;\n }\n return n;\n }\n if (small.len >= PROBE_MIN) {\n // As the building intersection does: the shorter array as bits, the longer one tested against them in order, only\n // the span of the longer between the shorter's ends. Nothing is written but the scratch bits, cleared again.\n const first = s[small.off] as number;\n const last = s[se - 1] as number;\n if (last < (l[big.off] as number) || first > (l[le - 1] as number)) return 0;\n const from = gallop(l, 0, big.off, le, first);\n const to = gallop(l, 0, from, le, last + 1);\n const words = probeWords;\n for (let i = small.off; i < se; i++) {\n const v = s[i] as number;\n words[v >>> 5] = (words[v >>> 5] as number) | (1 << (v & 31));\n }\n for (let j = from; j < to; j++) {\n const v = l[j] as number;\n n += ((words[v >>> 5] as number) >>> (v & 31)) & 1;\n }\n for (let i = small.off; i < se; i++) words[(s[i] as number) >>> 5] = 0;\n return n;\n }\n let i = small.off;\n let j = big.off;\n while (i < se && j < le) {\n const x = s[i] as number;\n const y = l[j] as number;\n // No branch on the comparison, as in the building merge.\n n += x === y ? 1 : 0;\n i += x <= y ? 1 : 0;\n j += x >= y ? 1 : 0;\n }\n return n;\n}\n\n/** Values of array `a` that bitset `b` holds. */\nfunction andCountArrayBitset(a: Container, b: Container): number {\n const u16 = lows16(a);\n const words = words32(b);\n let n = 0;\n for (let i = a.off; i < a.off + a.len; i++) {\n const v = u16[i] as number;\n n += ((words[v >>> 5] as number) >>> (v & 31)) & 1;\n }\n return n;\n}\n\n/** Values of array `a` that the runs of `b` cover: a walk of both, or a search of the runs per value when the runs are far more. */\nfunction andCountArrayRuns(a: Container, b: Container): number {\n const u16 = lows16(a);\n const pairs = lows16(b);\n const ae = a.off + a.len;\n let n = 0;\n if (skewed(a.len, b.len)) {\n for (let i = a.off; i < ae; i++) {\n const v = u16[i] as number;\n // The last run starting at or before `v`.\n const after = lowerBound(pairs, b.off, b.len, v + 1, 2);\n if (after === 0) continue;\n const r = b.off + 2 * (after - 1);\n if (v <= (pairs[r] as number) + (pairs[r + 1] as number)) n++;\n }\n return n;\n }\n let i = a.off;\n for (let r = 0; r < b.len && i < ae; r++) {\n const start = pairs[b.off + 2 * r] as number;\n const end = start + (pairs[b.off + 2 * r + 1] as number);\n while (i < ae && (u16[i] as number) < start) i++;\n while (i < ae && (u16[i] as number) <= end) {\n n++;\n i++;\n }\n }\n return n;\n}\n\n/** Values bitset `a` holds inside the runs of `b`. */\nfunction andCountBitsetRuns(a: Container, b: Container): number {\n const words = words32(a);\n const pairs = lows16(b);\n let n = 0;\n for (let r = 0; r < b.len; r++) {\n const start = pairs[b.off + 2 * r] as number;\n n += bitsInRange(words, start, start + (pairs[b.off + 2 * r + 1] as number));\n }\n return n;\n}\n\n/** Values both run containers hold: the summed overlap of the runs. */\nfunction andCountRuns(a: Container, b: Container): number {\n const x = lows16(a);\n const y = lows16(b);\n let n = 0;\n let i = 0;\n let j = 0;\n while (i < a.len && j < b.len) {\n const as = x[a.off + 2 * i] as number;\n const ae = as + (x[a.off + 2 * i + 1] as number);\n const bs = y[b.off + 2 * j] as number;\n const be = bs + (y[b.off + 2 * j + 1] as number);\n const lo = as > bs ? as : bs;\n const hi = ae < be ? ae : be;\n if (lo <= hi) n += hi - lo + 1;\n if (ae < be) i++;\n else j++;\n }\n return n;\n}\n\n/** How many values both containers hold; builds nothing and changes neither operand. */\nexport function containerAndCard(a: Container, b: Container): number {\n if (a.kind === BITSET && b.kind === BITSET) {\n return popcountAnd(words32(a), words32(b));\n }\n // Commutative: put the lower kind first (array, bitset, run).\n if (a.kind > b.kind) return containerAndCard(b, a);\n if (a.kind === ARRAY) {\n if (b.kind === ARRAY) return andCountArrays(a, b);\n return b.kind === BITSET ? andCountArrayBitset(a, b) : andCountArrayRuns(a, b);\n }\n return b.kind === RUN && a.kind === RUN ? andCountRuns(a, b) : andCountBitsetRuns(a, b);\n}\n\n/** Whether any bit from `start` to `end`, both inclusive, is set in `words`; stops at the first word that has one. */\nfunction anyBitInRange(words: Uint32Array, start: number, end: number): boolean {\n const first = start >>> 5;\n const last = end >>> 5;\n const head = (0xffff_ffff << (start & 31)) >>> 0;\n const tail = 0xffff_ffff >>> (31 - (end & 31));\n if (first === last) return ((words[first] as number) & head & tail) !== 0;\n if (((words[first] as number) & head) !== 0 || ((words[last] as number) & tail) !== 0)\n return true;\n for (let i = first + 1; i < last; i++) if (words[i] !== 0) return true;\n return false;\n}\n\n/** Whether every bit from `start` to `end`, both inclusive, is set in `words`; stops at the first word that lacks one. */\nfunction allBitsInRange(words: Uint32Array, start: number, end: number): boolean {\n const first = start >>> 5;\n const last = end >>> 5;\n const head = (0xffff_ffff << (start & 31)) >>> 0;\n const tail = 0xffff_ffff >>> (31 - (end & 31));\n if (first === last) return (~(words[first] as number) & head & tail) === 0;\n if ((~(words[first] as number) & head) !== 0 || (~(words[last] as number) & tail) !== 0)\n return false;\n for (let i = first + 1; i < last; i++) if (words[i] !== 0xffff_ffff) return false;\n return true;\n}\n\n/** Whether every value of array `a` is in array `b`: a merge or a gallop that stops at the first value `b` lacks. */\nfunction subsetArrays(a: Container, b: Container): boolean {\n const x = lows16(a);\n const y = lows16(b);\n const ie = a.off + a.len;\n const je = b.off + b.len;\n let j = b.off;\n if (skewed(a.len, b.len)) {\n for (let i = a.off; i < ie; i++) {\n const v = x[i] as number;\n j = gallop(y, 0, j, je, v);\n if (j === je || y[j] !== v) return false;\n }\n return true;\n }\n let i = a.off;\n while (i < ie && j < je) {\n const p = x[i] as number;\n const q = y[j] as number;\n if (p < q) return false;\n i += p === q ? 1 : 0;\n j++;\n }\n return i === ie;\n}\n\n/** Whether every value of array `a` is covered by a run of `b`: one walk of the runs, stopping at the first value outside them. */\nfunction subsetArrayRuns(a: Container, b: Container): boolean {\n const u16 = lows16(a);\n const pairs = lows16(b);\n let r = 0;\n for (let i = a.off; i < a.off + a.len; i++) {\n const v = u16[i] as number;\n while (r < b.len && (pairs[b.off + 2 * r] as number) + (pairs[b.off + 2 * r + 1] as number) < v)\n r++;\n if (r === b.len || (pairs[b.off + 2 * r] as number) > v) return false;\n }\n return true;\n}\n\n/** Whether every value of the runs of `a` is in the array `b`: each run is `length` consecutive entries of `b`, since both ascend without repeats. */\nfunction subsetRunsArray(a: Container, b: Container): boolean {\n const pairs = lows16(a);\n const y = lows16(b);\n const je = b.off + b.len;\n let j = b.off;\n for (let r = 0; r < a.len; r++) {\n const start = pairs[a.off + 2 * r] as number;\n const last = start + (pairs[a.off + 2 * r + 1] as number);\n j = gallop(y, 0, j, je, start);\n const end = j + (last - start);\n if (end >= je || y[j] !== start || y[end] !== last) return false;\n j = end + 1;\n }\n return true;\n}\n\n/** Whether every value of the run containers `a` lies inside a run of `b` (whose runs are maximal, so inside one run). */\nfunction subsetRuns(a: Container, b: Container): boolean {\n const x = lows16(a);\n const y = lows16(b);\n let j = 0;\n for (let i = 0; i < a.len; i++) {\n const start = x[a.off + 2 * i] as number;\n const last = start + (x[a.off + 2 * i + 1] as number);\n while (j < b.len && (y[b.off + 2 * j] as number) + (y[b.off + 2 * j + 1] as number) < start)\n j++;\n if (j === b.len || (y[b.off + 2 * j] as number) > start) return false;\n if ((y[b.off + 2 * j] as number) + (y[b.off + 2 * j + 1] as number) < last) return false;\n }\n return true;\n}\n\n/** Whether every set bit of the bitset `a` lies in a run of `b`: no set bit before the first run, between two, or after the last. */\nfunction subsetBitsetRuns(a: Container, b: Container): boolean {\n const words = words32(a);\n const pairs = lows16(b);\n let from = 0;\n for (let r = 0; r < b.len; r++) {\n const start = pairs[b.off + 2 * r] as number;\n if (start > from && anyBitInRange(words, from, start - 1)) return false;\n from = start + (pairs[b.off + 2 * r + 1] as number) + 1;\n }\n return from > 65_535 || !anyBitInRange(words, from, 65_535);\n}\n\n/**\n * Whether every value of `a` is in `b`, by the kinds of the pair, stopping at the first value that is not and counting\n * nothing: no scratch and no popcount, where `containerAndCard(a, b) === a.card` reads both operands whole. A bitset in\n * an array is the one pair that falls back to that count (it only arises for a bitset of 4,096 values or fewer, which\n * the codec's own results never are).\n */\nexport function containersSubset(a: Container, b: Container): boolean {\n if (a.card > b.card) return false;\n if (a.kind === ARRAY) {\n if (b.kind === ARRAY) return subsetArrays(a, b);\n if (b.kind === RUN) return subsetArrayRuns(a, b);\n const u16 = lows16(a);\n const words = words32(b);\n for (let i = a.off; i < a.off + a.len; i++) {\n const v = u16[i] as number;\n if ((((words[v >>> 5] as number) >>> (v & 31)) & 1) === 0) return false;\n }\n return true;\n }\n if (a.kind === BITSET) {\n if (b.kind === BITSET) {\n const x = words32(a);\n const y = words32(b);\n for (let i = 0; i < WORDS; i += 8) {\n const lack =\n ((x[i] as number) & ~(y[i] as number)) |\n ((x[i + 1] as number) & ~(y[i + 1] as number)) |\n ((x[i + 2] as number) & ~(y[i + 2] as number)) |\n ((x[i + 3] as number) & ~(y[i + 3] as number)) |\n ((x[i + 4] as number) & ~(y[i + 4] as number)) |\n ((x[i + 5] as number) & ~(y[i + 5] as number)) |\n ((x[i + 6] as number) & ~(y[i + 6] as number)) |\n ((x[i + 7] as number) & ~(y[i + 7] as number));\n if (lack !== 0) return false;\n }\n return true;\n }\n if (b.kind === RUN) return subsetBitsetRuns(a, b);\n return containerAndCard(a, b) === a.card;\n }\n if (b.kind === ARRAY) return subsetRunsArray(a, b);\n if (b.kind === RUN) return subsetRuns(a, b);\n const words = words32(b);\n const pairs = lows16(a);\n for (let r = 0; r < a.len; r++) {\n const start = pairs[a.off + 2 * r] as number;\n if (!allBitsInRange(words, start, start + (pairs[a.off + 2 * r + 1] as number))) return false;\n }\n return true;\n}\n\n/**\n * Whether two containers hold the same values. Two containers of one kind compare their storage and stop at the first\n * difference: bitset words, array values, run pairs. That is exact for runs because every run container is canonical:\n * the decoder refuses runs that touch or overlap, and every writer of a run container ({@link optimize}, a write into\n * a run, the union of a run with an array, the run results of `and`, `or`, `andNot` and `xor`) leaves the runs\n * maximal and the container in its smallest kind, so one set has one list of pairs. Containers of different kinds can hold the same set (a run against an array), so they fall back to the\n * count of the values they share.\n */\nexport function containersEqual(a: Container, b: Container): boolean {\n if (a.card !== b.card) return false;\n if (a.kind !== b.kind) return containerAndCard(a, b) === a.card;\n if (a.kind === BITSET) return equalWords(words32(a), 0, words32(b), 0, WORDS);\n if (a.len !== b.len) return false;\n const x = lows16(a);\n const y = lows16(b);\n const n = a.kind === ARRAY ? a.len : 2 * a.len;\n if (n < EQUAL_VIEW_MIN) {\n // Short lists that both start at the front of their storage (every container of a detached decode) pass constant\n // start offsets and skip the view test; a separate function for them measured slower on a bitmap that mixes kinds\n // (indicative, probe).\n if (a.off === 0 && b.off === 0) return equalU16(x, 0, y, 0, n);\n return equalU16(x, a.off, y, b.off, n);\n }\n const xb = x.byteOffset + 2 * a.off;\n const yb = y.byteOffset + 2 * b.off;\n if (usesEqualView(n, xb, yb)) {\n // Two values a step through a 32-bit view over the same bytes.\n const m = n >>> 1;\n if (!equalWords(new Uint32Array(x.buffer, xb, m), 0, new Uint32Array(y.buffer, yb, m), 0, m))\n return false;\n return (n & 1) === 0 || x[a.off + n - 1] === y[b.off + n - 1];\n }\n return equalU16(x, a.off, y, b.off, n);\n}\n\n/** The fewest 16-bit values (an array's values, twice a run container's pairs) from which a compare goes through a 32-bit view: a view costs about as much as a few hundred compares. */\nexport const EQUAL_VIEW_MIN = 512;\n\n/** Whether a compare of `n` 16-bit values, whose two lists start at byte offsets `xb` and `yb`, goes through a 32-bit view: from {@link EQUAL_VIEW_MIN} values, when both starts fall on a 4-byte boundary. */\nexport function usesEqualView(n: number, xb: number, yb: number): boolean {\n return n >= EQUAL_VIEW_MIN && (xb & 3) === 0 && (yb & 3) === 0;\n}\n\n/** Whether `n` words of `x` from `xo` equal those of `y` from `yo`: eight a step, the differences OR-ed and tested once per group. */\nfunction equalWords(x: Uint32Array, xo: number, y: Uint32Array, yo: number, n: number): boolean {\n let i = 0;\n for (const end = n - 7; i < end; i += 8) {\n const d =\n ((x[xo + i] as number) ^ (y[yo + i] as number)) |\n ((x[xo + i + 1] as number) ^ (y[yo + i + 1] as number)) |\n ((x[xo + i + 2] as number) ^ (y[yo + i + 2] as number)) |\n ((x[xo + i + 3] as number) ^ (y[yo + i + 3] as number)) |\n ((x[xo + i + 4] as number) ^ (y[yo + i + 4] as number)) |\n ((x[xo + i + 5] as number) ^ (y[yo + i + 5] as number)) |\n ((x[xo + i + 6] as number) ^ (y[yo + i + 6] as number)) |\n ((x[xo + i + 7] as number) ^ (y[yo + i + 7] as number));\n if (d !== 0) return false;\n }\n for (; i < n; i++) if (x[xo + i] !== y[yo + i]) return false;\n return true;\n}\n\n/** {@link equalWords} over 16-bit values. */\nfunction equalU16(x: Uint16Array, xo: number, y: Uint16Array, yo: number, n: number): boolean {\n let i = 0;\n for (const end = n - 7; i < end; i += 8) {\n const d =\n ((x[xo + i] as number) ^ (y[yo + i] as number)) |\n ((x[xo + i + 1] as number) ^ (y[yo + i + 1] as number)) |\n ((x[xo + i + 2] as number) ^ (y[yo + i + 2] as number)) |\n ((x[xo + i + 3] as number) ^ (y[yo + i + 3] as number)) |\n ((x[xo + i + 4] as number) ^ (y[yo + i + 4] as number)) |\n ((x[xo + i + 5] as number) ^ (y[yo + i + 5] as number)) |\n ((x[xo + i + 6] as number) ^ (y[yo + i + 6] as number)) |\n ((x[xo + i + 7] as number) ^ (y[yo + i + 7] as number));\n if (d !== 0) return false;\n }\n for (; i < n; i++) if (x[xo + i] !== y[yo + i]) return false;\n return true;\n}\n\n/** Whether two arrays share a value; stops at the first. */\nfunction intersectsArrays(a: Container, b: Container): boolean {\n const small = a.len <= b.len ? a : b;\n const big = small === a ? b : a;\n const s = lows16(small);\n const l = lows16(big);\n const se = small.off + small.len;\n const le = big.off + big.len;\n // Disjoint ranges answer at once.\n if (\n (s[se - 1] as number) < (l[big.off] as number) ||\n (s[small.off] as number) > (l[le - 1] as number)\n ) {\n return false;\n }\n if (skewed(small.len, big.len)) {\n let at = big.off;\n for (let i = small.off; i < se; i++) {\n const v = s[i] as number;\n at = gallop(l, 0, at, le, v);\n if (at === le) return false;\n if (l[at] === v) return true;\n }\n return false;\n }\n let i = small.off;\n let j = big.off;\n if (small.len >= PROBE_MIN) {\n // A pair that shares a value early is answered by the merge without setting any bits: take a bounded number of merge\n // steps first and set up the scratch bits only for a pair that shares nothing that soon (most random pairs of this\n // size still reach them; see MERGE_FIRST).\n for (let step = 0; step < MERGE_FIRST && i < se && j < le; step++) {\n const x = s[i] as number;\n const y = l[j] as number;\n if (x === y) return true;\n if (x < y) i++;\n else j++;\n }\n if (i === se || j === le) return false;\n // As the counting kernel does: the shorter array as bits and the span of the longer between its ends tested against\n // them, but stopping at the first hit. The scratch bits are cleared on both exits.\n const left = i;\n const from = gallop(l, 0, j, le, s[left] as number);\n const to = gallop(l, 0, from, le, (s[se - 1] as number) + 1);\n const words = probeWords;\n for (let k = left; k < se; k++) {\n const v = s[k] as number;\n words[v >>> 5] = (words[v >>> 5] as number) | (1 << (v & 31));\n }\n let hit = false;\n for (let k = from; k < to; k++) {\n const v = l[k] as number;\n if ((((words[v >>> 5] as number) >>> (v & 31)) & 1) === 1) {\n hit = true;\n break;\n }\n }\n for (let k = left; k < se; k++) words[(s[k] as number) >>> 5] = 0;\n return hit;\n }\n while (i < se && j < le) {\n const x = s[i] as number;\n const y = l[j] as number;\n if (x === y) return true;\n if (x < y) i++;\n else j++;\n }\n return false;\n}\n\n/** Whether the array `a` has a value the runs of `b` cover; stops at the first. */\nfunction intersectsArrayRuns(a: Container, b: Container): boolean {\n const u16 = lows16(a);\n const pairs = lows16(b);\n let r = 0;\n for (let i = a.off; i < a.off + a.len; i++) {\n const v = u16[i] as number;\n // The first run that ends at or after `v`.\n while (\n r < b.len &&\n (pairs[b.off + 2 * r] as number) + (pairs[b.off + 2 * r + 1] as number) < v\n ) {\n r++;\n }\n if (r === b.len) return false;\n if ((pairs[b.off + 2 * r] as number) <= v) return true;\n }\n return false;\n}\n\n/** Whether the two containers share a value; stops at the first one it finds. */\nexport function containersIntersect(a: Container, b: Container): boolean {\n if (a.kind > b.kind) return containersIntersect(b, a);\n if (a.kind === ARRAY) {\n if (b.kind === ARRAY) return intersectsArrays(a, b);\n if (b.kind === RUN) return intersectsArrayRuns(a, b);\n const u16 = lows16(a);\n const words = words32(b);\n for (let i = a.off; i < a.off + a.len; i++) {\n const v = u16[i] as number;\n if ((((words[v >>> 5] as number) >>> (v & 31)) & 1) === 1) return true;\n }\n return false;\n }\n if (a.kind === BITSET) {\n const x = words32(a);\n if (b.kind === BITSET) {\n const y = words32(b);\n for (let i = 0; i < WORDS; i += 8) {\n const both =\n ((x[i] as number) & (y[i] as number)) |\n ((x[i + 1] as number) & (y[i + 1] as number)) |\n ((x[i + 2] as number) & (y[i + 2] as number)) |\n ((x[i + 3] as number) & (y[i + 3] as number)) |\n ((x[i + 4] as number) & (y[i + 4] as number)) |\n ((x[i + 5] as number) & (y[i + 5] as number)) |\n ((x[i + 6] as number) & (y[i + 6] as number)) |\n ((x[i + 7] as number) & (y[i + 7] as number));\n if (both !== 0) return true;\n }\n return false;\n }\n const pairs = lows16(b);\n for (let r = 0; r < b.len; r++) {\n const start = pairs[b.off + 2 * r] as number;\n if (anyBitInRange(x, start, start + (pairs[b.off + 2 * r + 1] as number))) return true;\n }\n return false;\n }\n // Two run containers share a value when any two runs overlap.\n const x = lows16(a);\n const y = lows16(b);\n let i = 0;\n let j = 0;\n while (i < a.len && j < b.len) {\n const as = x[a.off + 2 * i] as number;\n const ae = as + (x[a.off + 2 * i + 1] as number);\n const bs = y[b.off + 2 * j] as number;\n const be = bs + (y[b.off + 2 * j + 1] as number);\n if ((as > bs ? as : bs) <= (ae < be ? ae : be)) return true;\n if (ae < be) i++;\n else j++;\n }\n return false;\n}\n", "/**\n * The ascending iterator over a Roaring bitmap's ids: a class with its own state, not a generator, so a step is one\n * method call and a result object, with no suspended frame and no scratch buffer of 65,536 entries per iterator. It\n * walks one container at a time in place: an array by index, a run container by run and value, a bitset by word and the\n * lowest set bit of what is left of it.\n *\n * It reads the bitmap's live storage and takes no snapshot, so mutating the bitmap while iterating it is not supported.\n * Over a bitmap nothing changes it yields every id once, ascending, then ends. After a change it neither throws nor\n * reads outside the storage it holds, but what it yields is unspecified: an id may be missed, repeated or out of order,\n * and an id added or removed meanwhile may or may not appear. Collect the ids first (`toUint32Array`) or iterate a\n * `clone()` to change a bitmap while walking it.\n */\nimport { ARRAY, BITSET, WORDS, type Container } from './containers';\n\nconst DONE: IteratorReturnResult<undefined> = { done: true, value: undefined };\n\nexport class BitmapIterator implements IterableIterator<number> {\n readonly #keys: readonly number[];\n readonly #conts: readonly Container[];\n /** The container being walked, as an index into `#conts`, and its kind, storage and offset. */\n #at = -1;\n #kind: number = ARRAY;\n #u16: Uint16Array = new Uint16Array(0);\n #words: Uint32Array = new Uint32Array(0);\n #off = 0;\n /** Added to every remainder: the container's key times 65,536. */\n #base = 0;\n /** An array: the next index and one past the last. A run container: the next run's index and the run count. A bitset: the word index. */\n #pos = 0;\n #end = 0;\n /** A run container: the next value and the last of the current run. A bitset: what is left of the current word. */\n #next = 0;\n #last = -1;\n\n constructor(keys: readonly number[], conts: readonly Container[]) {\n this.#keys = keys;\n this.#conts = conts;\n }\n\n [Symbol.iterator](): this {\n return this;\n }\n\n next(): IteratorResult<number, undefined> {\n for (;;) {\n if (this.#kind === ARRAY) {\n if (this.#pos < this.#end) {\n return { done: false, value: this.#base + (this.#u16[this.#pos++] as number) };\n }\n } else if (this.#kind === BITSET) {\n let w = this.#next;\n while (w === 0 && ++this.#pos < WORDS) w = this.#words[this.#pos] as number;\n if (w !== 0) {\n const lowest = w & -w;\n this.#next = w ^ lowest;\n return {\n done: false,\n value: this.#base + this.#pos * 32 + 31 - Math.clz32(lowest),\n };\n }\n } else {\n if (this.#next <= this.#last) return { done: false, value: this.#base + this.#next++ };\n if (this.#pos < this.#end) {\n const r = this.#off + 2 * this.#pos++;\n this.#next = this.#u16[r] as number;\n this.#last = this.#next + (this.#u16[r + 1] as number);\n continue;\n }\n }\n if (!this.#advance()) return DONE;\n }\n }\n\n /** Move to the next container; `false` when there is none. */\n #advance(): boolean {\n if (++this.#at >= this.#conts.length) {\n this.#at = this.#conts.length;\n this.#kind = ARRAY;\n this.#pos = 0;\n this.#end = 0;\n return false;\n }\n const c = this.#conts[this.#at] as Container;\n this.#kind = c.kind;\n this.#base = (this.#keys[this.#at] as number) * 65_536;\n this.#off = c.off;\n if (c.kind === ARRAY) {\n this.#u16 = c.data as Uint16Array;\n this.#pos = c.off;\n this.#end = c.off + c.len;\n } else if (c.kind === BITSET) {\n this.#words = c.data as Uint32Array;\n this.#pos = 0;\n this.#next = this.#words[0] as number;\n } else {\n this.#u16 = c.data as Uint16Array;\n this.#pos = 0;\n this.#end = c.len;\n this.#next = 0;\n this.#last = -1;\n }\n return true;\n }\n}\n", "/**\n * The portable Roaring bytes of a set of containers: written from them, and read back into them.\n *\n * The layout is the RoaringFormatSpec's, as this repo's format page states it. A bitmap with no run container starts\n * with the cookie 12,346 and a `u32` container count; one with a run container starts with the cookie 12,347 whose high\n * half holds `count - 1`, then one bit per container (a run container's) in `ceil(count / 8)` bytes. Then come a\n * `(key, cardinality - 1)` pair of `u16`s per container, an offset per container (always without runs; with runs only\n * from four containers up) and the bodies back to back: an array's values as `u16`s, a bitset's 2,048 words, a run\n * container's run count and `(start, length - 1)` pairs. All integers are little-endian.\n *\n * Reading goes through {@link parsePortableLayout}, which holds every rule a reader refuses on (bounds, ordering, runs,\n * cardinalities, offsets), so there is one code path for what is a bitmap and this module only copies bytes the layout\n * has already vouched for, on a private copy of the input.\n */\nimport { IntegrityError } from '@cloudbitmaps/core';\nimport {\n NO_OFFSET_THRESHOLD,\n SERIAL_COOKIE,\n SERIAL_COOKIE_NO_RUNCONTAINER,\n parsePortableLayout,\n ARRAY as LAYOUT_ARRAY,\n BITMAP as LAYOUT_BITMAP,\n} from '../portable/layout';\nimport {\n ARRAY,\n BITSET,\n BITSET_BYTES,\n RUN,\n LITTLE_ENDIAN,\n WORDS,\n bitsetContainer,\n Container,\n} from './containers';\n\n/** The size of a container's body on the wire. */\nfunction bodySize(c: Container): number {\n if (c.kind === ARRAY) return 2 * c.len;\n if (c.kind === BITSET) return BITSET_BYTES;\n return 2 + 4 * c.len;\n}\n\n/** A body of fewer `u16`s than this is written with a loop, not a view and a copy. */\nconst SMALL_BODY = 64;\n\n/** Write `count` `u16`s of `src` from index `from` at byte `at` of `out`, little-endian. */\nfunction putU16s(out: Uint8Array, at: number, src: Uint16Array, from: number, count: number): void {\n if (count < SMALL_BODY) {\n // A short body is written by a loop: a view over it costs more than its bytes. Byte by byte is little-endian on any machine.\n for (let i = 0; i < count; i++) {\n const v = src[from + i] as number;\n out[at++] = v & 255;\n out[at++] = v >>> 8;\n }\n return;\n }\n if (LITTLE_ENDIAN) {\n out.set(new Uint8Array(src.buffer, src.byteOffset + 2 * from, 2 * count), at);\n return;\n }\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n for (let i = 0; i < count; i++) view.setUint16(at + 2 * i, src[from + i] as number, true);\n}\n\nfunction writeBody(c: Container, out: Uint8Array, view: DataView, at: number): void {\n if (c.kind === ARRAY) {\n putU16s(out, at, c.data as Uint16Array, c.off, c.len);\n } else if (c.kind === BITSET) {\n const words = c.data as Uint32Array;\n if (LITTLE_ENDIAN) out.set(new Uint8Array(words.buffer, words.byteOffset, BITSET_BYTES), at);\n else for (let i = 0; i < WORDS; i++) view.setUint32(at + 4 * i, words[i] as number, true);\n } else {\n view.setUint16(at, c.len, true);\n putU16s(out, at + 2, c.data as Uint16Array, c.off, 2 * c.len);\n }\n}\n\n/** The portable bytes of the bitmap holding `conts`, under the ascending 16-bit `keys`. Empty input is the 8-byte empty bitmap. */\nexport function serializeContainers(\n keys: readonly number[],\n conts: readonly Container[],\n): Uint8Array {\n const n = conts.length;\n let hasRun = false;\n for (let i = 0; i < n; i++) if ((conts[i] as Container).kind === RUN) hasRun = true;\n const offsets = !hasRun || n >= NO_OFFSET_THRESHOLD;\n let at = hasRun ? 4 + ((n + 7) >>> 3) : 8;\n const describeAt = at;\n at += 4 * n;\n const offsetsAt = at;\n if (offsets) at += 4 * n;\n let total = at;\n for (let i = 0; i < n; i++) total += bodySize(conts[i] as Container);\n\n const out = new Uint8Array(total);\n const view = new DataView(out.buffer);\n if (hasRun) {\n view.setUint32(0, SERIAL_COOKIE | ((n - 1) << 16), true);\n for (let i = 0; i < n; i++) {\n if ((conts[i] as Container).kind === RUN) {\n out[4 + (i >>> 3)] = (out[4 + (i >>> 3)] as number) | (1 << (i & 7));\n }\n }\n } else {\n view.setUint32(0, SERIAL_COOKIE_NO_RUNCONTAINER, true);\n view.setUint32(4, n, true);\n }\n for (let i = 0; i < n; i++) {\n const c = conts[i] as Container;\n view.setUint16(describeAt + 4 * i, keys[i] as number, true);\n view.setUint16(describeAt + 4 * i + 2, c.card - 1, true);\n if (offsets) view.setUint32(offsetsAt + 4 * i, at, true);\n writeBody(c, out, view, at);\n at += bodySize(c);\n }\n return out;\n}\n\n/** What {@link decodeContainers} found: the containers in key order, and where the bitmap ends in the buffer. */\ninterface Decoded {\n readonly keys: number[];\n readonly conts: Container[];\n /** One past the last byte of the last container (0 for an empty buffer). */\n readonly end: number;\n}\n\n/**\n * Read the portable bitmap in `bytes`. An empty buffer is the empty bitmap. With `detached`, each container is copied\n * into storage of its own, so the result holds no view of the input's copy and no slab shared between containers.\n *\n * @throws {IntegrityError} for every shape {@link parsePortableLayout} refuses.\n */\nexport function decodeContainers(input: Uint8Array, detached = false): Decoded {\n // The bytes are copied before they are checked, and the checked copy is the one read (Uint8Array's own slice, which\n // always copies; a Node Buffer's slice is a view of the same memory): a buffer another thread is\n // still writing (a shared one) could otherwise pass the check and then hold different bytes when they are copied\n // into containers, leaving an unsorted array or a bitset whose cardinality is not its bit count.\n const bytes = Uint8Array.prototype.slice.call(input) as Uint8Array;\n const layout = parsePortableLayout(bytes);\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n // Sized to the container count, not grown by pushes: a pushed-to array reserves room for sixteen more, which for the\n // one-container bitmaps a store decodes is most of what the two lists hold.\n const keys = new Array<number>(layout.length);\n const conts = new Array<Container>(layout.length);\n let n = 0;\n // A bitmap of no containers is its 8-byte header (the run cookie cannot state a count of zero).\n let end = bytes.byteLength === 0 ? 0 : 8;\n // The arrays and run containers of one bitmap share a single `Uint16Array`, each reading its own stretch of it, so a\n // run container of a few bytes costs its bytes and one small object, not a typed array of its own. When the bitmap\n // has only one of them it is the whole slab and owns it.\n // A detached decode gives every container storage of its own, so it has no slab to size and no lone container to\n // find: the pass over the layout that measures them is skipped.\n let slabLength = 0;\n let small = 0;\n if (!detached) {\n for (const { cardinality, kind, offset } of layout) {\n if (kind === LAYOUT_ARRAY) {\n slabLength += cardinality;\n small++;\n } else if (kind !== LAYOUT_BITMAP) {\n slabLength += 2 * view.getUint16(offset, true);\n small++;\n }\n }\n }\n // The private copy's memory is its own when the copy starts at its buffer's first byte and fills it, which a copy made\n // by `Uint8Array.prototype.slice` does. A body that sits at a suitably aligned offset of it can then be read in place,\n // as a typed array over the copy, with no second copy of it: the one bitset of a chunk, or its one array or run container.\n const own =\n LITTLE_ENDIAN &&\n bytes.byteOffset === 0 &&\n bytes.buffer instanceof ArrayBuffer &&\n bytes.buffer.byteLength === bytes.byteLength;\n const alias = !detached && own && small === 1;\n // A container with storage of its own: the one a detached decode gives every container, and the lone array or run\n // container of a bitmap that cannot be read in place.\n const solo = alias || detached;\n const slab = solo ? NO_U16 : new Uint16Array(slabLength);\n let used = 0;\n for (const { key, cardinality, kind, offset } of layout) {\n keys[n] = key;\n if (kind === LAYOUT_ARRAY) {\n if (alias && offset % 2 === 0) {\n const values = new Uint16Array(bytes.buffer, offset, cardinality);\n conts[n++] = new Container(ARRAY, values, 0, cardinality, cardinality, false);\n } else {\n const into = solo ? new Uint16Array(cardinality) : slab;\n getU16s(bytes, view, offset, into, solo ? 0 : used, cardinality);\n conts[n++] = new Container(\n ARRAY,\n into,\n solo ? 0 : used,\n cardinality,\n cardinality,\n !solo && small > 1,\n );\n used += cardinality;\n }\n end = offset + 2 * cardinality;\n } else if (kind === LAYOUT_BITMAP) {\n let words: Uint32Array;\n if (!detached && own && offset % 4 === 0) {\n words = new Uint32Array(bytes.buffer, offset, WORDS);\n } else {\n words = new Uint32Array(WORDS);\n if (LITTLE_ENDIAN) {\n new Uint8Array(words.buffer).set(bytes.subarray(offset, offset + BITSET_BYTES));\n } else {\n for (let i = 0; i < WORDS; i++) words[i] = view.getUint32(offset + 4 * i, true);\n }\n }\n conts[n++] = bitsetContainer(words, cardinality);\n end = offset + BITSET_BYTES;\n } else {\n const runs = view.getUint16(offset, true);\n if (alias && (offset + 2) % 2 === 0) {\n const pairs = new Uint16Array(bytes.buffer, offset + 2, 2 * runs);\n conts[n++] = new Container(RUN, pairs, 0, runs, cardinality, false);\n } else {\n const into = solo ? new Uint16Array(2 * runs) : slab;\n getU16s(bytes, view, offset + 2, into, solo ? 0 : used, 2 * runs);\n conts[n++] = new Container(\n RUN,\n into,\n solo ? 0 : used,\n runs,\n cardinality,\n !solo && small > 1,\n );\n used += 2 * runs;\n }\n end = offset + 2 + 4 * runs;\n }\n }\n return { keys, conts, end };\n}\n\nconst NO_U16 = new Uint16Array(0);\n\n/** Copy `count` little-endian `u16`s from byte `at` of `bytes` into `slab` from index `to`. */\nfunction getU16s(\n bytes: Uint8Array,\n view: DataView,\n at: number,\n slab: Uint16Array,\n to: number,\n count: number,\n): void {\n if (LITTLE_ENDIAN) {\n new Uint8Array(slab.buffer, 2 * to, 2 * count).set(bytes.subarray(at, at + 2 * count));\n return;\n }\n for (let i = 0; i < count; i++) slab[to + i] = view.getUint16(at + 2 * i, true);\n}\n\n/** The refusal for bytes that follow the bitmap's last container when the buffer must be exactly one bitmap. */\nexport function trailingBytes(length: number, end: number): IntegrityError {\n return new IntegrityError(\n `portable roaring: ${length - end} bytes follow the bitmap's last container, which ends at byte ${end}. ` +\n `One buffer holds one bitmap: to load several as one segment, combine them first and serialize the result.`,\n );\n}\n", "/**\n * The codec selection point and the load-input and decode helpers the `CloudRoaring` facade builds on.\n *\n * The store's codec is the TypeScript Roaring codec (`ts-roaring/bitmap.ts`): the portable format, read and written in\n * JavaScript with no native addon. Every deserialize is preceded by a hard size cap and a structural check\n * (`portable/layout.ts`). The `unsafe_frozen_*` formats are never used.\n */\nimport type { CodecInterface, LoadInput, PortableBitmap } from '@cloudbitmaps/core';\nimport { tsRoaringCodec } from './ts-roaring/bitmap';\n\n/**\n * An iterable that serializes itself to portable Roaring (an object with `Symbol.iterator` and a `serialize` method: a\n * caller's `RoaringBitmap32` from the `roaring` package, another copy's bitmap, or a `RoaringBitmap` of this\n * package), passed where ids go, loads as `{ bitmap }`: from its containers, through the same check as any bytes,\n * never id by id. Its `serialize` decides, even where it disagrees with what it iterates. Any other input passes\n * through unchanged, so the core's own rules apply to it: a byte array (`Uint8Array`, `Buffer`) is refused as ids even\n * with a `serialize` of its own, and an object that is not iterable is read as `{ serialized }` or `{ bitmap }` or\n * refused, whatever else it has.\n */\nexport function bitmapAsLoadInput(input: LoadInput): LoadInput {\n if (typeof input !== 'object' || input === null) return input;\n const tag = Object.prototype.toString.call(input).slice(8, -1);\n if (tag === 'Uint8Array' || tag === 'Uint8ClampedArray') return input;\n return Symbol.iterator in input &&\n typeof (input as { serialize?: unknown }).serialize === 'function'\n ? { bitmap: input as unknown as PortableBitmap }\n : input;\n}\n\nlet activeCodec: CodecInterface = tsRoaringCodec;\n\n/**\n * The codec the store hands to the engine at every site that injects one (`CloudRoaring`, a load, a pin and an export): the TypeScript codec unless a harness has flipped it with {@link setFlagshipCodec}.\n * Internal: no public entry exports it, and a store cannot be configured with a codec.\n */\nexport function flagshipCodec(): CodecInterface {\n return activeCodec;\n}\n\n/** Flip the codec the store uses, for the whole process. Test and bench harnesses only; returns the previous one. */\nexport function setFlagshipCodec(codec: CodecInterface): CodecInterface {\n const previous = activeCodec;\n activeCodec = codec;\n return previous;\n}\n", "/**\n * The default real-time {@link Clock} \u2014 the production half of the determinism seam.\n *\n * It lives outside `core/`, so `Date.now()`, `setTimeout` and `setImmediate` are allowed here; that separation is\n * the whole point of the seam, and it is lint-enforced on the other side.\n *\n * It sits in its own module rather than in `index.ts` so the facade, the tests and anything else that needs a real\n * clock can import it without importing the whole barrel.\n */\nimport type { Clock } from '@cloudbitmaps/core';\n\n/** Default real-time clock \u2014 lives outside `core/`, so `Date.now()` + timers are allowed here. */\nexport class SystemClock implements Clock {\n now(): number {\n return Date.now();\n }\n\n sleep(ms: number): Promise<void> {\n if (ms <= 0) return Promise.resolve();\n // A *ref'd* timer, deliberately. Every `sleep` on this clock backs a caller-awaited, bounded retry \u2014 today\n // the transient-retry loop (`withRetry`) that wraps the chunk source. A pending backoff therefore always means unfinished\n // awaited work, so the timer MUST keep the event loop alive until it resolves. An unref'd timer lets a\n // short-lived process \u2014 CLI, Lambda, a bare script \u2014 whose only remaining handle is the backoff timer exit 0\n // mid-retry, silently dropping the awaited operation with neither a result nor a thrown error. When a\n // transient fault repeats (a backend throttling a hot key, say), the backoff timer can be the last handle\n // standing.\n // Retries are bounded (`maxAttempts`/`maxRetries` + `maxDelayMs`), so a ref'd timer can only\n // extend a process by the small remaining backoff budget of work that is genuinely still in flight.\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n }\n\n /**\n * `setImmediate`, and it has to be \u2014 this is the one place where the choice of primitive is the whole feature.\n *\n * A long CPU-bound loop in `core/` (bulk-load is the one that matters) periodically hands the loop back so a\n * co-resident HTTP server keeps answering. Measured on the **synthetic yield-primitive benchmark** \u2014 a\n * 61,035-iteration loop yielding every 1,024, isolating the primitive rather than timing a real load (the\n * end-to-end figures are 519 ms \u2192 24 ms; see `cooperative.ts`, which lists all three experiments):\n *\n * ```text\n * no yield 568 ms wall 568.0 ms worst event-loop gap\n * sleep(0) 555 ms wall 555.2 ms \u2190 a microtask. Yields NOTHING.\n * setImmediate 569 ms wall 13.8 ms \u2190 free, and 41x less starvation\n * setTimeout(1) 625 ms wall 15.0 ms \u2190 +10% wall for no extra relief\n * ```\n *\n * `sleep(0)` resolving on a microtask is correct for its own contract and useless for this: microtasks drain\n * before the loop ever advances a phase, so `await sleep(0)` in a tight loop never lets a single pending I/O\n * callback run. `setImmediate` fires in the check phase *after* pending I/O, which is exactly the ordering a\n * server wants \u2014 inbound requests are serviced before the loop resumes chewing.\n *\n * A timer is not ref'd here (unlike {@link sleep}): a yield expresses \"someone else may go first\", never\n * \"there is outstanding work\" \u2014 and `setImmediate` cannot outlive the turn that scheduled it anyway.\n */\n yieldNow(): Promise<void> {\n return new Promise((resolve) => {\n setImmediate(resolve);\n });\n }\n}\n", "/**\n * The default {@link Entropy}: the platform's Web Crypto, the production half of the seam a generation's write\n * identity is drawn through.\n *\n * It lives outside `core/`, which may reach no global, and it draws on use, not at construction, so a process that\n * only reads runs on a runtime without Web Crypto. `Math.random` is never a fallback: an identity that two writers\n * could draw alike is no identity.\n */\nimport { UnsupportedError } from '@cloudbitmaps/core';\nimport type { Entropy } from '@cloudbitmaps/core';\n\n/** `length` random bytes from `crypto.getRandomValues`; {@link UnsupportedError} on a runtime that has none. */\nexport const systemEntropy: Entropy = (length) => {\n const c = (globalThis as { crypto?: { getRandomValues?: (a: Uint8Array) => Uint8Array } }).crypto;\n if (c === undefined || typeof c.getRandomValues !== 'function') {\n throw new UnsupportedError(\n \"this runtime has no Web Crypto (crypto.getRandomValues), which every load needs for its generation's \" +\n 'write identity: run on a runtime that has it, or pass `seams.entropy`',\n );\n }\n return c.getRandomValues(new Uint8Array(length));\n};\n", "/**\n * The keys `new CloudRoaring(options)` takes: at the top level, and inside each group whose value is an object. The\n * constructor refuses any other key by name, because an option it ignored would do nothing and look as if it had,\n * and the gates that read the docs' samples and the harnesses' option bags hold them to the same table. A test\n * holds the table to the option interfaces, in both directions.\n *\n * NOT part of the public API. It is its own module, rather than an `export` from the barrel, so the constructor\n * and those gates read one copy.\n */\nexport const OPTION_KEYS = {\n top: ['storage', 'cache', 'encryption', 'retry', 'metrics', 'budget', 'seams'],\n cache: ['maxChunks', 'ttlMs', 'genTtlMs', 'readerMax', 'readerMaxBytes'],\n encryption: ['keystore', 'required'],\n retry: ['maxAttempts', 'baseDelayMs', 'maxDelayMs', 'backoffFactor', 'jitter', 'onRetry'],\n budget: ['maxRequests'],\n seams: ['clock', 'rng', 'entropy'],\n} as const satisfies Record<string, readonly string[]>;\n\n/** The groups: the top-level keys whose value, when it is an object, has keys of its own. */\nexport type OptionGroup = Exclude<keyof typeof OPTION_KEYS, 'top'>;\n", "/**\n * The checks a stream makes of a lease: before its first pull, and each time it reads a chunk. Kept apart from the store\n * so each can be held on its own, and so a stream of another shape (a rank read, a plain iterable of ids) is wrapped by\n * the same function.\n *\n * ```\n * caller \u2500\u2500 next() \u2500\u2500> guarded stream \u2500\u2500 next() \u2500\u2500> engine's stream\n * \u2502 check before the first pull\n * \u2502 check again at each chunk (or each item)\n * \u2514\u2500 a throwing check ends the engine's stream, then rejects\n * return() / throw() \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500> engine's stream (ended / thrown into)\n * ```\n *\n * A guarded stream is its own iterator and single-use, as the engine's generator it wraps is: it answers `next`,\n * `return` and `throw`, and iterating it gives it back.\n */\n\n/** An async iterator that is also its own iterable, with `return` and `throw` always present, as a generator's are. */\ninterface GuardedStream<T> extends AsyncIterableIterator<T> {\n return(value?: unknown): Promise<IteratorResult<T, unknown>>;\n throw(err: unknown): Promise<IteratorResult<T, unknown>>;\n}\n\n/** What an id stream is, as far as a guard is concerned: ids, and the same ids a chunk at a time. */\ninterface IdStream extends AsyncIterable<number> {\n batches(): AsyncIterable<Uint32Array>;\n}\n\n/** An id stream that is guarded: the per-id stream is an iterator of its own, and `batches()` is guarded too. */\ntype GuardedIds = GuardedStream<number> & { batches(): GuardedStream<Uint32Array> };\n\n/** A finished result, new each time: a caller may keep or change what it is handed. */\nconst done = (value?: unknown): IteratorReturnResult<unknown> => ({ done: true, value });\n\n/**\n * The one guard: `check` runs before the first pull, then once an item is pulled and before it is handed on. Every\n * item is checked, or, when `keyOf` is given, the first item of each run of items with one key (the ids of one chunk).\n * A check that throws ends the inner stream and rejects with its error, and the guarded stream is over: a pull that\n * settles after that is done, whatever the source had already pulled for it. A key is remembered only once its check\n * has passed.\n */\nconst guard = <T>(\n inner: AsyncIterable<T>,\n check: () => void,\n keyOf?: (item: T) => number,\n): GuardedStream<T> => {\n const it = inner[Symbol.asyncIterator]();\n let first = true;\n let over = false;\n let last = -1;\n const end = async (value?: unknown): Promise<unknown> => {\n over = true;\n await it.return?.(value);\n return value;\n };\n const stop = async (err: unknown): Promise<never> => {\n await end();\n throw err;\n };\n /** What a pull hands on: nothing once the stream is over, and an item only after its check passes. */\n const deliver = (\n r: IteratorResult<T, unknown>,\n ): Promise<IteratorResult<T, unknown>> | IteratorResult<T, unknown> => {\n if (over) return done();\n if (r.done === true) return r;\n const key = keyOf?.(r.value);\n if (key === undefined || key !== last) {\n try {\n check();\n } catch (err) {\n return stop(err);\n }\n if (key !== undefined) last = key;\n }\n return r;\n };\n return {\n [Symbol.asyncIterator]() {\n return this;\n },\n async next() {\n if (over) return done();\n if (first) {\n first = false;\n try {\n check();\n } catch (err) {\n return stop(err);\n }\n }\n return deliver(await it.next());\n },\n async return(value?: unknown) {\n return done(await end(value));\n },\n async throw(err: unknown) {\n first = false;\n if (it.throw === undefined) return stop(err);\n let r: IteratorResult<T, unknown>;\n try {\n r = await it.throw(err);\n } catch (thrown) {\n over = true;\n throw thrown;\n }\n return deliver(r);\n },\n };\n};\n\n/**\n * A stream of ascending ids that checks a lease before it first pulls, and each time it reads a chunk after that: once\n * the engine has the next chunk and before an id of it is yielded, so nothing of a chunk fetched past the lease is\n * served. Ids ascend, so a chunk is entered when `id >>> 16` changes. The check before the first pull is what stops a\n * stream built while the lease was live, and pulled after it ended, ending empty without ever checking. A throw ends the\n * engine's reads. Used only when a handle in the call holds a lease: a call with none returns the engine's stream\n * untouched. It takes any async iterable of ids, so a stream with no `.batches()` (a rank read) is wrapped the same way.\n */\nexport const guardIdIterable = (\n inner: AsyncIterable<number>,\n check: () => void,\n): GuardedStream<number> => guard(inner, check, (id) => id >>> 16);\n\n/** {@link guardIdIterable} for an `IdStream`, whose `.batches()` is guarded too. */\nexport const guardIds = (inner: IdStream, check: () => void): GuardedIds =>\n Object.assign(guardIdIterable(inner, check), {\n batches: () => guardItems(inner.batches(), check),\n });\n\n/**\n * A stream of chunks that checks a lease before the first pull and before each item is handed on: an item is one\n * chunk (a batch of ids, or a chunk an `*Into` writes).\n */\nexport const guardItems = <T>(inner: AsyncIterable<T>, check: () => void): GuardedStream<T> =>\n guard(inner, check);\n", "/**\n * How a store's storage and read retry are wired from its options:\n *\n * ```\n * options.storage \u2500\u2500> resolveStorageSource \u2500\u2500> source (what the engine reads), driver, registry\n * \u2502 backend: CrbmStorageChunkSource over its storage half, pinned to its registry\n * \u2502 driver: CrbmStorageChunkSource, no registry (list-scan, cleartext, read-only)\n * \u2514 source: used as-is\n * source \u2500\u2500> retry on (default) \u2500\u2500> RetryingStorageChunkSource(source, policy) = storage\n * \u2514\u2500> retry: false \u2500\u2500\u2500\u2500\u2500\u2500\u2500> storage = source\n * ```\n *\n * The constructor keeps what it builds itself (cache, engine, budget); this file owns only the storage half.\n */\nimport {\n CrbmStorageChunkSource,\n DEFAULT_RETRY_POLICY,\n NOOP_METRICS,\n RetryingStorageChunkSource,\n ValidationError,\n isStorageBackend,\n} from '@cloudbitmaps/core';\nimport type { Clock, IMetricsSink, RetryPolicy, RetryingOptions, Rng } from '@cloudbitmaps/core';\nimport type {\n IKeystore,\n IRegistryDriver,\n IStorageDriver,\n StorageBackend,\n StorageChunkSource,\n} from '@cloudbitmaps/core/driver-kit';\n\n/** The slice of a store's options the wiring reads; `CloudRoaringOptions` satisfies it. */\ninterface StoreWiring {\n readonly storage: unknown;\n readonly encryption?: { readonly keystore?: IKeystore; readonly required?: boolean };\n readonly cache?: {\n readonly genTtlMs?: number;\n readonly readerMax?: number;\n readonly readerMaxBytes?: number;\n };\n readonly retry?:\n | (Partial<RetryPolicy> & {\n readonly onRetry?: (info: { attempt: number; delayMs: number; err: unknown }) => void;\n })\n | false;\n}\n\n/** What {@link wireStore} builds for the constructor. */\ninterface WiredStore {\n /** What the engine reads through: the source, wrapped in the read retry unless it is off. */\n readonly storage: StorageChunkSource;\n /** The resolved source before the retry wrapper. */\n readonly source: StorageChunkSource;\n readonly driver: IStorageDriver | undefined;\n readonly registry: IRegistryDriver | undefined;\n /** The backend the store was given, for its optional lifecycle check; `undefined` for a bare driver or a source. */\n readonly backend: StorageBackend | undefined;\n /** The read retry the store shares with its lifecycle reads; `undefined` when retry is off. */\n readonly retryOptions: RetryingOptions | undefined;\n}\n\n/**\n * A caller's partial policy, completed from {@link DEFAULT_RETRY_POLICY}, so tuning one field does not mean restating\n * all five.\n *\n * Each field is read for `undefined`, not by spreading over the default: a key that is present with the value\n * `undefined` (the ordinary shape of a value read from env or JSON, which `exactOptionalPropertyTypes`\n * being off lets through) must fall back to the default. A spread would let it replace the default with\n * `undefined`, giving `NaN` delays that `SystemClock.sleep` turns into a ~1 ms hot retry loop, with the\n * backoff bound and the herd protection gone and no error to show it.\n *\n * An omitted `maxDelayMs` is the default cap, or the `baseDelayMs` given when that is larger, so tuning only the\n * base delay never leaves a cap below it. A `maxDelayMs` given below the `baseDelayMs` is refused when the retrying\n * source checks the policy.\n */\nfunction resolveRetryPolicy(partial: Partial<RetryPolicy>): RetryPolicy {\n // Only an absent value is the default: a `null` is kept, and refused when the retrying source checks the policy.\n const orDefault = <K extends keyof RetryPolicy>(field: K): RetryPolicy[K] =>\n partial[field] === undefined ? DEFAULT_RETRY_POLICY[field] : (partial[field] as RetryPolicy[K]);\n const baseDelayMs = orDefault('baseDelayMs');\n return {\n maxAttempts: orDefault('maxAttempts'),\n baseDelayMs,\n maxDelayMs:\n partial.maxDelayMs === undefined\n ? typeof baseDelayMs === 'number' && baseDelayMs > DEFAULT_RETRY_POLICY.maxDelayMs\n ? baseDelayMs\n : DEFAULT_RETRY_POLICY.maxDelayMs\n : partial.maxDelayMs,\n backoffFactor: orDefault('backoffFactor'),\n jitter: orDefault('jitter'),\n };\n}\n\n/**\n * Resolve the storage seam, hand a backend the metrics sink, and wrap the source in the read retry. Refusals come in\n * that order: a bad `storage` first, then a bad `retry`.\n */\nexport function wireStore(\n options: StoreWiring,\n clock: Clock,\n rng: Rng,\n metrics: IMetricsSink,\n): WiredStore {\n // Resolve the Storage seam to a StorageChunkSource: a raw IStorageDriver is wrapped into the `.crbm` storage source\n // here (with the store's registry/keystore) so drivers are wired once; a pre-built source is used as-is.\n const resolved = resolveStorageSource(options, clock);\n // A backend that can say something about its own setup is handed the sink, never a no-op one.\n if (metrics !== NOOP_METRICS && isStorageBackend(options.storage)) {\n options.storage.attachMetrics?.(metrics);\n }\n let storage: StorageChunkSource = resolved.source;\n let retryOptions: RetryingOptions | undefined;\n // Resilience on by default: wrap the source so transient faults retry with jittered backoff. `false` opts\n // out (e.g. the injected client already retries); a RetryPolicy tunes it.\n if (options.retry !== false) {\n const { onRetry: userOnRetry, ...ov } = options.retry ?? {};\n if (userOnRetry !== undefined && typeof userOnRetry !== 'function') {\n throw new ValidationError('retry.onRetry must be a function');\n }\n retryOptions = {\n clock,\n rng,\n policy: resolveRetryPolicy(ov),\n // Bridge transient-fault retries into the metrics stream, then call the user's own hook.\n onRetry: (info) => {\n metrics.onEvent({\n kind: 'retry',\n reason: 'transient',\n attempt: info.attempt,\n delayMs: info.delayMs,\n });\n userOnRetry?.(info);\n },\n };\n storage = new RetryingStorageChunkSource(storage, retryOptions);\n }\n return {\n storage,\n source: resolved.source,\n driver: resolved.driver,\n registry: resolved.registry,\n backend: isStorageBackend(options.storage) ? options.storage : undefined,\n retryOptions,\n };\n}\n\n/**\n * Resolve the `storage` option to a {@link StorageChunkSource} at construction (wiring-time only \u2014 no hot-path cost).\n *\n * `storage` is discriminated by a **brand** for the backend arm and structurally for the other two, never by\n * `instanceof`, so a backend or driver from a different copy of the package still works (the same reason the error\n * predicates are brand-based): a raw {@link IStorageDriver} exposes `putImmutable`\n * (the byte-mover seam); a pre-built {@link StorageChunkSource} exposes `getChunk` (the engine's read seam). The\n * two interfaces are deliberately **disjoint** on these methods (an invariant the driver SDK maintains, pinned\n * by a test) \u2014 an object exposing *both* is ambiguous and rejected, as is one exposing *neither* (incl. a\n * nullish/non-object value from a JS caller): fail fast with a typed error rather than crash on a probe.\n *\n * A backend is wrapped into a {@link CrbmStorageChunkSource} over its storage half, pinned to its registry,\n * with the config's `encryption` group; a bare driver is wrapped the same way but without a\n * registry; a pre-built source is used as-is. `keystore`/`requireEncryption` are meaningful **only** where the\n * store builds the source itself \u2014 pairing either with a pre-built source is a wiring mistake, so reject it\n * rather than silently ignore it. The `CrbmStorageChunkSource` constructor enforces the rest (a keystore /\n * `requireEncryption` needs a registry, so they need a backend; the driver needs range reads).\n *\n * Returns the resolved `source` (what the engine reads through) **and** the raw `driver` when one was passed \u2014\n * the store keeps the raw driver so its lifecycle helpers and the `*Into` verbs can write generations without\n * you re-passing drivers. `driver` is `undefined` for a pre-built source (there's no underlying `IStorageDriver` to\n * write through, so its writes throw {@link UnsupportedError}).\n */\nfunction resolveStorageSource(\n options: StoreWiring,\n clock: Pick<Clock, 'now'>,\n): {\n source: StorageChunkSource;\n driver: IStorageDriver | undefined;\n registry: IRegistryDriver | undefined;\n} {\n const storage: unknown = options.storage;\n if (storage === null || typeof storage !== 'object') {\n throw new ValidationError(\n '`storage` must be a StorageBackend, an IStorageDriver, or a StorageChunkSource',\n );\n }\n const asBackend = storage as Partial<StorageBackend>;\n const isObject = (v: unknown): v is Record<string, unknown> =>\n v !== null && typeof v === 'object';\n const hasGetChunk = typeof (storage as Partial<StorageChunkSource>).getChunk === 'function';\n const hasPutImmutable = typeof (storage as Partial<IStorageDriver>).putImmutable === 'function';\n\n // The BRAND decides, not the shape. `{ storage, registry }` is also the shape of core's free-function deps\n // object, so before the brand any literal satisfied it \u2014 including one holding halves from two unrelated\n // stores, which the store accepted and then answered empty for a segment that holds data.\n const isBackend = isStorageBackend(storage);\n\n // A branded backend that ALSO quacks like a driver or a source is genuinely ambiguous. Unreachable for the\n // five classes, kept because the alternative to refusing is guessing.\n if (isBackend && (hasGetChunk || hasPutImmutable)) {\n throw new ValidationError(\n '`storage` is a StorageBackend that also exposes ' +\n `${hasGetChunk ? '`getChunk`' : '`putImmutable`'} \u2014 ambiguous. A backend must not also be a driver ` +\n 'or a source; pass whichever one you mean.',\n );\n }\n\n // Unbranded, but carrying both halves. Three sub-cases, and they want different things said.\n const hasStorageHalf = isObject(asBackend.storage);\n const hasRegistryHalf = isObject(asBackend.registry);\n\n // (a) A DRIVER that also carries a registry \u2014 the audit/metrics/tenant-scoping wrapper. Without this it\n // falls through to the bare-driver path, where there is no pointer at all: generations resolve by\n // list-scan, so the store answers from the HIGHEST object in the bucket rather than the published one, and\n // a load that wrote an object but never published it is served as if it had been. Silently, and with the\n // wrapper's registry sitting right there unused.\n if (!isBackend && hasPutImmutable && hasRegistryHalf) {\n throw new ValidationError(\n '`storage` looks like a driver that also carries a `registry`. Passed as a bare driver it would have ' +\n 'no pointer at all \u2014 generations would resolve by list-scan, so reads could serve a generation that ' +\n 'was written but never published. If you meant a backend, use a backend class \u2014 S3Storage, GcsStorage, ' +\n 'AzureBlobStorage, LocalFsStorage or MemoryStorage \u2014 or, to pair a driver of your own with a registry, ' +\n 'brand the pair with `brandAsBackend` from `@cloudbitmaps/core/driver-kit`.',\n );\n }\n\n // (b) Both halves, neither of them a driver or a source: the hand-assembled literal, or a spread of a real\n // backend with one half swapped. Name the classes AND the door \u2014 the five classes cannot express an\n // instrumented half or a foreign registry, which is exactly the case that lands here.\n if (!isBackend && !hasGetChunk && !hasPutImmutable && hasStorageHalf && hasRegistryHalf) {\n const storageOk =\n typeof (asBackend.storage as Partial<IStorageDriver>).putImmutable === 'function';\n const registryOk =\n typeof (asBackend.registry as Partial<IRegistryDriver>).compareAndSwap === 'function';\n // (c) \u2026and if a half is not actually a driver, say THAT rather than lecturing about buckets.\n if (!storageOk || !registryOk) {\n const bad = !storageOk\n ? '`storage` half is not an IStorageDriver (no `putImmutable`)'\n : '`registry` half is not an IRegistryDriver (no `compareAndSwap`)';\n throw new ValidationError(\n '`storage` looks like a backend but its ' +\n bad +\n ' \u2014 use a backend class, or brand a pair of drivers with `brandAsBackend` from ' +\n '`@cloudbitmaps/core/driver-kit`.',\n );\n }\n throw new ValidationError(\n '`storage` must be a backend \u2014 S3Storage, GcsStorage, AzureBlobStorage, LocalFsStorage or ' +\n 'MemoryStorage. An object with `.storage` and `.registry` is not one: a backend builds both halves ' +\n 'from a single bucket and prefix, so they cannot disagree, and hand-assembling them re-opens exactly ' +\n 'that mismatch \u2014 a store whose pointer and generations live in different places reads as empty ' +\n 'rather than failing. A driver author who genuinely wants halves of their own \u2014 an instrumented driver, ' +\n 'a registry in a database you already run \u2014 brands the pair with `brandAsBackend` from ' +\n '`@cloudbitmaps/core/driver-kit`, which is taking on that they agree.',\n );\n }\n\n if (isBackend) {\n const backend = storage as StorageBackend;\n return {\n source: new CrbmStorageChunkSource(backend.storage, {\n registry: backend.registry,\n keystore: options.encryption?.keystore,\n requireEncryption: options.encryption?.required,\n clock,\n currentGenTtlMs: options.cache?.genTtlMs,\n maxOpenSegments: options.cache?.readerMax,\n maxOpenIndexBytes: options.cache?.readerMaxBytes,\n }),\n driver: backend.storage,\n registry: backend.registry,\n };\n }\n\n if (hasGetChunk && hasPutImmutable) {\n throw new ValidationError(\n '`storage` exposes both `getChunk` and `putImmutable` \u2014 ambiguous; pass a StorageBackend, an IStorageDriver, or a StorageChunkSource, not a hybrid',\n );\n }\n if (!hasGetChunk && !hasPutImmutable) {\n throw new ValidationError(\n '`storage` must be a StorageBackend, an IStorageDriver, or a StorageChunkSource',\n );\n }\n if (hasGetChunk) {\n // Already a StorageChunkSource \u2014 used as-is. `keystore`/`requireEncryption` only apply when the store\n // builds the source itself; with a source of the caller's own they are inert, so reject them rather than mislead.\n if (options.encryption?.keystore !== undefined || options.encryption?.required === true) {\n throw new ValidationError(\n 'keystore/requireEncryption apply only when the store builds its own read path: a StorageChunkSource of ' +\n 'your own reads an encrypted segment by itself, if it must; to have the store decrypt, pass a backend',\n );\n }\n return { source: storage as StorageChunkSource, driver: undefined, registry: undefined };\n }\n // A bare IStorageDriver: no pointer, so generations resolve by list-scan. Cleartext, read-only.\n const driver = storage as IStorageDriver;\n return {\n source: new CrbmStorageChunkSource(driver, {\n keystore: options.encryption?.keystore,\n requireEncryption: options.encryption?.required,\n clock,\n currentGenTtlMs: options.cache?.genTtlMs,\n maxOpenSegments: options.cache?.readerMax,\n maxOpenIndexBytes: options.cache?.readerMaxBytes,\n }),\n driver,\n registry: undefined,\n };\n}\n", "/**\n * The shape checks every call that takes an options bag makes before it reads or writes anything: the bag is an\n * object, it names only keys the call takes, and each switch is a boolean. The per-call key tables stay with the\n * facade, because each is held to the options type it describes.\n */\nimport { ValidationError } from '@cloudbitmaps/core';\n\n/** A key of `T` that `K` does not list: a key table missing one fails to compile. */\ntype Unlisted<T, K extends readonly PropertyKey[]> = Exclude<keyof T, K[number]>;\n\n/** The keys of `T`, every one of them, as a table the options check below reads. */\nexport const keysOf =\n <T>() =>\n <const K extends readonly (keyof T & string)[]>(\n keys: K & ([Unlisted<T, K>] extends [never] ? unknown : never),\n ): readonly string[] =>\n keys;\n\n/** How a value of the wrong kind is named in a message: by its kind, never by its content. */\nexport const kindOf = (v: unknown): string =>\n v === null ? 'null' : Array.isArray(v) ? 'an array' : `a ${typeof v}`;\n\n/**\n * Why `options` cannot be a call's options, or `undefined` when it can. `undefined` and `null` read as none; anything\n * but an object is refused, and so is a key `known` does not list, unless its value is `undefined`, so a spread of\n * options keeps working; and each of `booleans` present must be a boolean, `null` included. A bag of the wrong shape, a misspelt key or\n * a switch given as a string would otherwise read as no option at all, and silently widen what the call does: a scope\n * passed as a string swept every namespace, and `dryRun: 'true'` deleted.\n *\n * `misplaced` names the keys of a wider options type that the call does not take, such as `exclude` on `andNot`, which\n * shares its options type with the combines that do. Each is read by name, so one inherited from a prototype or held\n * in a getter, which `Object.keys` does not list, is refused as an own key is, rather than dropped without a word.\n */\nexport function optionsError(\n options: unknown,\n op: string,\n known: readonly string[],\n booleans: readonly string[] = [],\n misplaced: readonly string[] = [],\n): ValidationError | undefined {\n if (options === undefined || options === null) return undefined;\n if (typeof options !== 'object' || Array.isArray(options)) {\n return new ValidationError(`${op}: options must be an object; got ${kindOf(options)}`);\n }\n const bag = options as Record<string, unknown>;\n const unknown = Object.keys(bag).filter((k) => !known.includes(k) && bag[k] !== undefined);\n for (const k of misplaced) if (!unknown.includes(k) && bag[k] !== undefined) unknown.push(k);\n if (unknown.length > 0) {\n return new ValidationError(\n `${op}: unknown option${unknown.length > 1 ? 's' : ''} ${unknown.map((k) => `\"${k}\"`).join(', ')}; ` +\n `it takes { ${known.join(', ')} }`,\n );\n }\n // An `audit` that is not a sink would receive nothing and say nothing: refused here, before the call reads or scans\n // anything, as the core entries refuse it before they write.\n const audit = bag.audit;\n if (\n audit !== undefined &&\n audit !== null &&\n typeof (audit as { onEvent?: unknown }).onEvent !== 'function'\n ) {\n return new ValidationError(\n `${op}: audit must be a sink with an onEvent(event) method, such as a RecordingAuditSink`,\n );\n }\n // A switch is `true` or `false`. `null` is refused with the rest: read as absent, `dryRun: null` dropped for real.\n for (const name of booleans) {\n const v = bag[name];\n if (v !== undefined && typeof v !== 'boolean') {\n return new ValidationError(`${op}: \\`${name}\\` must be a boolean; got ${kindOf(v)}`);\n }\n }\n return undefined;\n}\n\n/**\n * The keys of `options` a call takes, each read by name. A spread copies only own enumerable properties, so an option\n * held in a getter or inherited from a prototype, which TypeScript accepts and {@link optionsError} reads, would pass\n * the checks and then be dropped: a `dryRun` so held ran a real sweep, and a `namespace` exported every tenant. The\n * call then reads the copy only, so it runs with exactly what was checked.\n */\nexport function picked<T extends object>(\n options: T | null | undefined,\n keys: readonly string[],\n): Partial<T> {\n const out: Record<string, unknown> = {};\n if (options === undefined || options === null) return out as Partial<T>;\n for (const key of keys) {\n const value = (options as Record<string, unknown>)[key];\n if (value !== undefined) out[key] = value;\n }\n return out as Partial<T>;\n}\n\n/** {@link optionsError}, thrown: for a call that rejects, rather than one that returns a stream. */\nexport function checkOptions(\n options: unknown,\n op: string,\n known: readonly string[],\n booleans?: readonly string[],\n misplaced?: readonly string[],\n): void {\n const err = optionsError(options, op, known, booleans, misplaced);\n if (err !== undefined) throw err;\n}\n", "/**\n * `RoaringBitmap`: a mutable set of unsigned 32-bit ids, in TypeScript on typed arrays, with no native addon. It is a\n * thin public shell around the codec's own bitmap (`ts-roaring/bitmap.ts`): the shell checks every argument (an id is\n * an integer from 0 to 4,294,967,295, and a refusal never repeats the value), and the codec does the work.\n *\n * ```ts\n * import { RoaringBitmap } from '@cloudbitmaps/roaring';\n *\n * const a = new RoaringBitmap([1, 5, 70_000]);\n * a.add(9).has(9); // true\n * const bytes = a.serialize();\n * RoaringBitmap.deserialize(bytes).size; // 4\n * ```\n *\n * The portable bytes are the codec's, so what `serialize()` writes a store loads and what a store holds,\n * `RoaringBitmap.deserialize` reads. Bytes you did not write go through `deserialize` only: it caps their size,\n * checks their structure and builds one whole bitmap whose storage is its own, so keeping it keeps no copy of the\n * input alive.\n */\nimport {\n MAX_SERIALIZED_LOAD_BYTES,\n ValidationError,\n decodeSerialized,\n refusalOfId,\n} from '@cloudbitmaps/core';\nimport type { CodecInterface } from '@cloudbitmaps/core';\nimport { COUNT_BY_KERNELS } from './count-route';\nimport { checkOptions, kindOf, picked } from './options';\nimport { TsBitmap, collect, tsRoaringCodec } from './ts-roaring/bitmap';\n\n/** What {@link RoaringBitmap.deserialize} takes as its second argument. */\nexport interface RoaringBitmapDeserializeOptions {\n /**\n * A cap on the input's size in bytes, lower than the one every decode has (537,403,396, the most any canonical\n * 32-bit bitmap serializes to). Bytes over it are refused before any is read. It can only lower the cap: a value\n * above it, or one that is not a non-negative integer, is a `ValidationError`.\n */\n readonly maxBytes?: number;\n}\n\n/** `Object.prototype.toString`'s tag, which names a typed array's kind across realms and for `Buffer` too. */\nfunction tagOf(value: unknown): string {\n return Object.prototype.toString.call(value).slice(8, -1);\n}\n\nconst VIEW = Object.getPrototypeOf(Uint8Array.prototype) as object;\nconst viewGetter = (name: 'buffer'): ((this: unknown) => unknown) =>\n Object.getOwnPropertyDescriptor(VIEW, name)?.get as (this: unknown) => unknown;\nconst bufferOf = viewGetter('buffer');\n\nconst plainByteLength = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'byteLength')\n ?.get as (this: unknown) => unknown;\nconst hasSharedMemory = typeof SharedArrayBuffer === 'function';\n\n/**\n * Whether the typed array's memory may be a `SharedArrayBuffer`'s, by brand: another thread may write it while it is\n * read. `ArrayBuffer`'s own `byteLength` getter returns for a genuine `ArrayBuffer` (so ordinary memory costs no throw)\n * and throws for anything else, which is then treated as shared and copied; a `Symbol.toStringTag` can be given any\n * value, the brand cannot. False on a runtime without a `SharedArrayBuffer`.\n */\nfunction inSharedMemory(ids: Uint32Array): boolean {\n if (!hasSharedMemory) return false;\n try {\n plainByteLength.call(bufferOf.call(ids));\n return false;\n } catch {\n return true;\n }\n}\n\n/** An id, or the refusal that names what is wrong with it and never repeats it. */\nfunction checkedId(id: unknown): number {\n if (typeof id !== 'number' || id >>> 0 !== id) throw refusalOfId(id);\n return id;\n}\n\nfunction oneIdOnly(method: string, bulk: string): ValidationError {\n return new ValidationError(`${method} takes one id; use ${bulk} for several`);\n}\n\n/**\n * The ids to act on, as something the codec reads once and never keeps: a typed array that is, or may be, in shared memory is copied first\n * (it is read twice, to see whether it ascends and then to build, and another thread could write between the reads).\n *\n * @throws {ValidationError} for anything that is not an iterable of ids, and for bytes, which would read as ids.\n */\nfunction idsOf(values: unknown): Iterable<number> {\n if (typeof values !== 'object' || values === null || !(Symbol.iterator in values)) {\n throw new ValidationError('values must be an iterable of ids');\n }\n const tag = tagOf(values);\n if (tag === 'Uint8Array' || tag === 'Uint8ClampedArray') {\n throw new ValidationError(\n `values are ids, and this is a ${tag === 'Uint8Array' ? 'Uint8Array or Buffer' : tag}: each byte would be ` +\n `read as an id. To read portable bytes, call RoaringBitmap.deserialize(bytes).`,\n );\n }\n if (values instanceof Uint32Array && inSharedMemory(values)) return new Uint32Array(values);\n return values as Iterable<number>;\n}\n\n/** The codec with its decode detached: each container of a decoded bitmap owns its storage. */\nconst detachedCodec: CodecInterface = {\n ...tsRoaringCodec,\n safeDeserialize: (bytes, maxBytes, options) =>\n TsBitmap.safeDeserialize(bytes, maxBytes, { ...options, detached: true }),\n};\n\nfunction maxBytesOf(options: unknown): number {\n if (options === undefined) return MAX_SERIALIZED_LOAD_BYTES;\n if (typeof options !== 'object' || options === null) {\n throw new ValidationError(\n `deserialize takes no format argument, the format is always portable; its second argument is ` +\n `{ maxBytes } or nothing, not ${kindOf(options)}`,\n );\n }\n checkOptions(options, 'RoaringBitmap.deserialize', ['maxBytes']);\n const { maxBytes } = picked(options as RoaringBitmapDeserializeOptions | undefined, ['maxBytes']);\n if (maxBytes === undefined) return MAX_SERIALIZED_LOAD_BYTES;\n if (!Number.isInteger(maxBytes) || maxBytes < 0 || maxBytes > MAX_SERIALIZED_LOAD_BYTES) {\n throw new ValidationError(\n `maxBytes must be an integer from 0 to ${MAX_SERIALIZED_LOAD_BYTES}, the size no canonical bitmap exceeds`,\n );\n }\n return maxBytes;\n}\n\n/**\n * A mutable set of integers from 0 to 4,294,967,295 (unsigned 32-bit ids) with set algebra and the portable Roaring\n * serialization. It is not designed for subclassing, and `JSON.stringify` of one gives `\"{}\"`: write\n * `JSON.stringify([...bitmap])` or `bitmap.toArray()`. Passed to a method of the `roaring` package from npm in place of a\n * `RoaringBitmap32`, it answers wrongly without throwing in JavaScript (TypeScript refuses the call): decode its\n * `serialize()` bytes with that package instead.\n *\n * Every id argument is checked: a value that is not an integer in range (a fraction, `NaN`, a string, `null`, a\n * negative, one too large) throws `ValidationError`, whose message never repeats it, and the bitmap is unchanged.\n * Iterating while changing the bitmap is unsupported: collect first with `toUint32Array()`, or iterate a `clone()`.\n * Everything is synchronous.\n */\nexport class RoaringBitmap implements Iterable<number> {\n #bitmap: TsBitmap;\n\n /**\n * A bitmap of `values`: an array or another iterable of ids, a `Uint32Array` (read in place when it already ascends,\n * else sorted on a copy; it is never changed or kept), or another `RoaringBitmap` (a copy-on-write `clone()`).\n * With no argument it is empty.\n *\n * @throws {ValidationError} for an id that is not an integer from 0 to 4294967295; for a value that is not an\n * iterable (`null`, a number, a string, an object, an `ArrayBuffer`); and for a `Uint8Array`, `Uint8ClampedArray` or\n * `Buffer`, which would read each byte as an id: call {@link RoaringBitmap.deserialize} for bytes.\n */\n constructor(values?: Iterable<number>) {\n if (values === undefined) {\n this.#bitmap = TsBitmap.empty();\n } else if (RoaringBitmap.#is(values)) {\n this.#bitmap = values.#bitmap.clone();\n } else {\n this.#bitmap = TsBitmap.fromValues(idsOf(values));\n }\n }\n\n /**\n * Decode portable Roaring bytes you hold, through the check a `{ serialized }` load makes first: a size cap, a\n * structural check and one whole bitmap, and only then the decoder. The result owns its storage: it keeps nothing\n * of `bytes`, so a large input that is decoded and then reduced can be freed.\n *\n * @param bytes a `Uint8Array`, which a Node `Buffer` is.\n * @param options `{ maxBytes }` lowers the size cap below the default of 537,403,396 bytes.\n * @throws {ValidationError} for something that is not a `Uint8Array`; an empty or detached one (an empty buffer is\n * not a bitmap: `new RoaringBitmap()` is the empty set); one over the cap or `maxBytes`; bytes that are not exactly\n * one well-formed portable bitmap, including bytes after its last container; a second argument that is not\n * `undefined` or an object whose only key is `maxBytes` (a format argument such as `'portable'` is one); and a\n * `maxBytes` that is not an integer from 0 to the cap.\n */\n static deserialize(bytes: Uint8Array, options?: RoaringBitmapDeserializeOptions): RoaringBitmap {\n const maxBytes = maxBytesOf(options);\n return RoaringBitmap.#wrap(\n decodeSerialized(bytes, detachedCodec, 'the buffer', {\n maxBytes,\n refuseEmpty: true,\n }) as TsBitmap,\n );\n }\n\n /** Whether `value` is a `RoaringBitmap` of this copy of the package. */\n static #is(value: unknown): value is RoaringBitmap {\n return typeof value === 'object' && value !== null && #bitmap in value;\n }\n\n static #wrap(bitmap: TsBitmap): RoaringBitmap {\n const out = new RoaringBitmap();\n out.#bitmap = bitmap;\n return out;\n }\n\n /** The codec bitmap of an operand, or a refusal that says what combines with what. */\n static #operand(other: unknown): TsBitmap {\n if (!RoaringBitmap.#is(other)) {\n throw new ValidationError(\n 'a RoaringBitmap combines only with another RoaringBitmap of this copy of the package',\n );\n }\n return other.#bitmap;\n }\n\n /** How many ids it holds. */\n get size(): number {\n return this.#bitmap.size;\n }\n\n /** Whether it holds no id. */\n get isEmpty(): boolean {\n return this.#bitmap.isEmpty;\n }\n\n /**\n * Whether it holds `id`.\n *\n * @throws {ValidationError} for a value that is not an integer from 0 to 4294967295.\n */\n has(id: number): boolean {\n return this.#bitmap.has(checkedId(id));\n }\n\n /** The smallest id, or `undefined` when it is empty. */\n minimum(): number | undefined {\n return this.#bitmap.minimum();\n }\n\n /** The largest id, or `undefined` when it is empty. */\n maximum(): number | undefined {\n return this.#bitmap.maximum();\n }\n\n /**\n * Add one id; returns this bitmap, for chaining.\n *\n * @throws {ValidationError} for a value that is not an integer from 0 to 4294967295, and for a second argument:\n * use {@link RoaringBitmap.addMany} to add several.\n */\n add(id: number): this {\n if (arguments.length !== 1) throw oneIdOnly('add', 'addMany');\n this.#bitmap.add(checkedId(id));\n return this;\n }\n\n /**\n * Add every id of `values` (an iterable of ids, or a `Uint32Array`); returns this bitmap. Nothing is added if any\n * of them is refused.\n *\n * @throws {ValidationError} as the constructor does.\n */\n addMany(values: Iterable<number>): this {\n if (RoaringBitmap.#is(values)) this.#bitmap.orInPlace(values.#bitmap);\n else this.#bitmap.addMany(idsOf(values));\n return this;\n }\n\n /**\n * Remove one id; whether it was there.\n *\n * @throws {ValidationError} for a value that is not an integer from 0 to 4294967295, and for a second argument:\n * use {@link RoaringBitmap.removeMany} to remove several.\n */\n remove(id: number): boolean {\n if (arguments.length !== 1) throw oneIdOnly('remove', 'removeMany');\n return this.#bitmap.remove(checkedId(id));\n }\n\n /**\n * Remove every id of `values` (an iterable of ids, or a `Uint32Array`); returns this bitmap. Nothing is removed if\n * any of them is refused.\n *\n * @throws {ValidationError} as the constructor does.\n */\n removeMany(values: Iterable<number>): this {\n if (RoaringBitmap.#is(values)) this.#bitmap.andNotInPlace(values.#bitmap);\n else this.#bitmap.removeMany(collect(idsOf(values)));\n return this;\n }\n\n /** Remove every id. */\n clear(): void {\n this.#bitmap.clear();\n }\n\n /**\n * A copy. It is copy-on-write: the copy costs the key list and one flag per container, not the ids, and the first\n * write to a container on either side copies that container once.\n */\n clone(): RoaringBitmap {\n return RoaringBitmap.#wrap(this.#bitmap.clone());\n }\n\n /**\n * Keep only the ids `other` also holds; returns this bitmap. `other` is not changed, and may be this bitmap.\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n andInPlace(other: RoaringBitmap): this {\n this.#bitmap.andInPlace(RoaringBitmap.#operand(other));\n return this;\n }\n\n /**\n * Add the ids `other` holds; returns this bitmap. `other` is not changed, and may be this bitmap.\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n orInPlace(other: RoaringBitmap): this {\n this.#bitmap.orInPlace(RoaringBitmap.#operand(other));\n return this;\n }\n\n /**\n * Remove the ids `other` holds; returns this bitmap. `other` is not changed, and may be this bitmap.\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n andNotInPlace(other: RoaringBitmap): this {\n this.#bitmap.andNotInPlace(RoaringBitmap.#operand(other));\n return this;\n }\n\n /**\n * Flip the ids `other` holds: keep those only this bitmap holds, add those only `other` holds; returns this bitmap.\n * `other` is not changed, and may be this bitmap (the result is then empty).\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n xorInPlace(other: RoaringBitmap): this {\n this.#bitmap.xorInPlace(RoaringBitmap.#operand(other));\n return this;\n }\n\n /**\n * How many ids both bitmaps hold, without building the intersection. Neither bitmap changes; `other` may be this one.\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n andCardinality(other: RoaringBitmap): number {\n const that = RoaringBitmap.#operand(other);\n return COUNT_BY_KERNELS\n ? this.#bitmap.andCardinality(that)\n : TsBitmap.and(this.#bitmap, that).size;\n }\n\n /**\n * How many ids either bitmap holds. Neither bitmap changes; `other` may be this one.\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n orCardinality(other: RoaringBitmap): number {\n const that = RoaringBitmap.#operand(other);\n return COUNT_BY_KERNELS\n ? this.#bitmap.orCardinality(that)\n : TsBitmap.or(this.#bitmap, that).size;\n }\n\n /**\n * How many ids exactly one of the bitmaps holds. Neither bitmap changes; `other` may be this one.\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n xorCardinality(other: RoaringBitmap): number {\n const that = RoaringBitmap.#operand(other);\n return COUNT_BY_KERNELS\n ? this.#bitmap.xorCardinality(that)\n : TsBitmap.xor(this.#bitmap, that).size;\n }\n\n /**\n * How many ids this bitmap holds that `other` lacks. Neither bitmap changes; `other` may be this one.\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n andNotCardinality(other: RoaringBitmap): number {\n const that = RoaringBitmap.#operand(other);\n return COUNT_BY_KERNELS\n ? this.#bitmap.andNotCardinality(that)\n : TsBitmap.andNot(this.#bitmap, that).size;\n }\n\n /**\n * Whether the bitmaps share an id. Neither bitmap changes; `other` may be this one.\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n intersects(other: RoaringBitmap): boolean {\n const that = RoaringBitmap.#operand(other);\n return COUNT_BY_KERNELS\n ? this.#bitmap.intersects(that)\n : !TsBitmap.and(this.#bitmap, that).isEmpty;\n }\n\n /**\n * Whether every id of this bitmap is in `other` (an empty bitmap is a subset of every bitmap, itself included). Neither\n * bitmap changes. Unlike the `roaring` package, which answers `false`, a value that is not a bitmap is refused.\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n isSubset(other: RoaringBitmap): boolean {\n return this.#bitmap.isSubset(RoaringBitmap.#operand(other));\n }\n\n /**\n * Whether both bitmaps hold exactly the same ids, whatever the kinds of their containers or the bytes they would\n * serialize to. Neither bitmap changes.\n *\n * @throws {ValidationError} if `other` is not a `RoaringBitmap` of this copy of the package.\n */\n isEqual(other: RoaringBitmap): boolean {\n return this.#bitmap.isEqual(RoaringBitmap.#operand(other));\n }\n\n /**\n * The ids both bitmaps hold, as a new bitmap. Neither operand changes, and the result holds storage of its own.\n *\n * @throws {ValidationError} if an operand is not a `RoaringBitmap` of this copy of the package.\n */\n static and(a: RoaringBitmap, b: RoaringBitmap): RoaringBitmap {\n return RoaringBitmap.#wrap(TsBitmap.and(RoaringBitmap.#operand(a), RoaringBitmap.#operand(b)));\n }\n\n /**\n * The ids either bitmap holds, as a new bitmap. Neither operand changes. A container only `a` holds is shared with\n * the result copy-on-write, so the next write to it, on either side, copies it once.\n *\n * @throws {ValidationError} if an operand is not a `RoaringBitmap` of this copy of the package.\n */\n static or(a: RoaringBitmap, b: RoaringBitmap): RoaringBitmap {\n return RoaringBitmap.#wrap(TsBitmap.or(RoaringBitmap.#operand(a), RoaringBitmap.#operand(b)));\n }\n\n /**\n * The ids exactly one of the bitmaps holds, as a new bitmap. Neither operand changes (see {@link RoaringBitmap.or}\n * for what is shared).\n *\n * @throws {ValidationError} if an operand is not a `RoaringBitmap` of this copy of the package.\n */\n static xor(a: RoaringBitmap, b: RoaringBitmap): RoaringBitmap {\n return RoaringBitmap.#wrap(TsBitmap.xor(RoaringBitmap.#operand(a), RoaringBitmap.#operand(b)));\n }\n\n /**\n * The ids of `a` that `b` lacks, as a new bitmap. Neither operand changes (see {@link RoaringBitmap.or} for what is\n * shared).\n *\n * @throws {ValidationError} if an operand is not a `RoaringBitmap` of this copy of the package.\n */\n static andNot(a: RoaringBitmap, b: RoaringBitmap): RoaringBitmap {\n return RoaringBitmap.#wrap(\n TsBitmap.andNot(RoaringBitmap.#operand(a), RoaringBitmap.#operand(b)),\n );\n }\n\n /**\n * The union of every bitmap of `bitmaps`, as a new bitmap that owns its storage (an empty list gives the empty set).\n * No operand changes, and none is flagged: the result accumulates in containers of its own.\n *\n * @throws {ValidationError} if `bitmaps` is not an iterable, or holds anything that is not a `RoaringBitmap` of this\n * copy of the package; nothing is combined then.\n */\n static orMany(bitmaps: Iterable<RoaringBitmap>): RoaringBitmap {\n if (typeof bitmaps !== 'object' || bitmaps === null || !(Symbol.iterator in bitmaps)) {\n throw new ValidationError('orMany takes an iterable of RoaringBitmap');\n }\n const parts = Array.from(bitmaps, (b) => RoaringBitmap.#operand(b));\n return RoaringBitmap.#wrap(TsBitmap.orMany(parts));\n }\n\n /** The ids in ascending order, each once. A bitmap that changes during the walk gives unspecified ids, and no error. */\n [Symbol.iterator](): IterableIterator<number> {\n return this.#bitmap[Symbol.iterator]();\n }\n\n /** The ids as a new ascending array. A bitmap too large to allocate as one throws the runtime's `RangeError`. */\n toArray(): number[] {\n return this.#bitmap.toArray();\n }\n\n /** The ids as a new ascending `Uint32Array` the caller owns, never a view of the bitmap's storage. */\n toUint32Array(): Uint32Array {\n return this.#bitmap.toUint32Array();\n }\n\n /**\n * The portable Roaring bytes, in a new `Uint8Array`. Call {@link RoaringBitmap.runOptimize} first when the bitmap was\n * decoded from bytes another writer made: its run containers stay as they were, and a bitmap that serializes over\n * the size cap is refused by a load.\n *\n * @param format `'portable'`, the only format there is, or nothing.\n * @throws {ValidationError} for any other argument.\n */\n serialize(format?: 'portable'): Uint8Array {\n if (format !== undefined && format !== 'portable') {\n throw new ValidationError(\n `a bitmap serializes only as serialize() or serialize('portable'); got ${kindOf(format)}`,\n );\n }\n return this.#bitmap.serialize();\n }\n\n /**\n * Re-encode every container in the smallest form (a run container only where it is strictly smaller than the plain\n * one), so `serialize()` afterwards depends on the set alone. Membership is unchanged.\n *\n * @returns whether the bitmap holds at least one run container afterwards, not whether anything changed.\n */\n runOptimize(): boolean {\n this.#bitmap.optimize();\n return this.#bitmap.hasRunContainer();\n }\n}\n", "/**\n * How the four cardinalities and `intersects` of `RoaringBitmap` are answered: from the containers, with the count\n * kernels (`true`), or by building the combination and counting it (`false`). Both routes give the same answers and\n * change no operand; only the cost differs. `isSubset` and `isEqual` always use their kernels.\n *\n * `true` because the count bench's record (`bench/count-kernels-results.json`) has the count's median below the build's\n * on every data set it judges. One switch, so a measurement that finds the build-then-count route cheaper changes this\n * line and nothing else.\n */\nexport const COUNT_BY_KERNELS = true;\n"],
5
+ "mappings": ";AA0BA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA,0BAAAA;AAAA,EACA;AAAA,EACA,wBAAAC;AAAA,EACA;AAAA,EACA,gBAAAC;AAAA,EACA,8BAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,oBAAAC;AAAA,EACA,mBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;AClDA,IAAM,sBAAN,MAAoD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASzD,YACmB,OACjB,SACiB,QACjB;AAHiB;AAEA;AAEjB,QAAI,YAAY,KAAM,MAAK,KAAK,IAAI,OAAO;AAAA,EAC7C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AK;AAAA,QACL,IAAI,cAAc,KAAK,UAAU,WAAW,MAAM,UAAU,OAAO,CAAC;AAAA,QACpE;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
6
+ "names": ["CrbmStorageChunkSource", "DEFAULT_RETRY_POLICY", "NOOP_METRICS", "RetryingStorageChunkSource", "UnsupportedError", "ValidationError", "IntegrityError", "ValidationError", "size", "ARRAY", "RUN", "ARRAY", "RUN", "u16", "i", "j", "r", "out", "words", "x", "y", "ARRAY", "IntegrityError", "ARRAY", "RUN", "IntegrityError", "out", "lowerBound", "RUN", "IntegrityError", "ValidationError", "ValidationError", "ValidationError", "ValidationError", "refusalOfId", "checkedId", "refusalOfId", "ValidationError", "excludingReservedRows", "ValidationError", "WriteConflictError", "IntegrityError", "NotFoundError", "UnsupportedError", "BudgetExceededError", "LeaseExpiredError", "errorKind", "NOOP_METRICS", "CrbmStorageChunkSource", "options", "pins", "RetryingStorageChunkSource", "listed", "at", "DEFAULT_RETRY_POLICY", "guard", "refs", "opts"]
7
7
  }