Versions 89 to 318
new file, 757 lines
2+ * Indexed graph storage. Values must be copied on write and read: a caller 3+ * mutating a returned list must not silently change persisted state. Hosts 4+ * provide transactions that roll back every write when the callback throws. 5+ * The namespace belongs to one graph and must not be shared by concurrent 6+ * Graph instances. Opening a graph does not scan its stored collections. 8+export interface GraphStateStorage { 9+ read(collection: string, key: string): unknown; 10+ write(collection: string, key: string, value: unknown): void; 11+ remove(collection: string, key: string): void; 12+ entries(collection: string): Iterable<readonly [string, unknown]>; 13+ transaction<T>(body: () => T): T; 17+ * Operation-local read cache with fixed payload and entry limits. Private numeric 18+ * pages, immutable scalars and serialized objects preserve the copy contract. Discard it after an outer host 19+ * rollback or any mutation made through another storage instance. 21+type CachedValue = { bytes: number } & ( 22+ | { kind: "scalar"; value: string | number | boolean | null | undefined } 23+ | { kind: "numbers"; value: readonly number[] } 24+ | { kind: "json"; json: string } 27+export class CachedStateStorage implements GraphStateStorage { 28+ readonly #source: GraphStateStorage; 29+ readonly #cache = new Map<string, CachedValue>(); 30+ readonly #maxBytes: number; 31+ readonly #maxEntries: number; 34+ * The keys written or removed in each open transaction, innermost last (abso Capacity). A rollback drops only those: 35+ * every projection scratch scope ends in a rollback, and dropping the whole cache there read the same rows from 36+ * storage again within a call and on every call of a kept reader. 38+ readonly #touched: Set<string>[] = []; 40+ * The biggest one row may be and still be kept (abso Capacity). A few big rows read on every call (each agent with 41+ * all the news it was told: 4.3 MB for abso's 109 agents) otherwise push every small page out of the cache. 43+ readonly #maxEntryBytes: number; 44+ constructor(source: GraphStateStorage, maxBytes = 1_048_576, maxEntries = 4096, maxEntryBytes = maxBytes) { 46+ !Number.isSafeInteger(maxBytes) || 48+ !Number.isSafeInteger(maxEntries) || 50+ !Number.isSafeInteger(maxEntryBytes) || 53+ throw new Error("invalid writer cache limits"); 54+ this.#source = source; 55+ this.#maxBytes = maxBytes; 56+ this.#maxEntries = maxEntries; 57+ this.#maxEntryBytes = Math.min(maxEntryBytes, maxBytes); 59+ get retainedBytes(): number { 62+ get retainedEntries(): number { 63+ return this.#cache.size; 69+ #drop(key: string): void { 70+ const previous = this.#cache.get(key); 72+ this.#cache.delete(key); 73+ this.#bytes -= previous.bytes; 76+ read(collection: string, key: string): unknown { 77+ const cacheKey = JSON.stringify([collection, key]); 78+ const hit = this.#cache.get(cacheKey); 80+ this.#cache.delete(cacheKey); 81+ this.#cache.set(cacheKey, hit); 82+ if (hit.kind === "scalar") return hit.value; 83+ if (hit.kind === "numbers") return hit.value.slice(); 84+ return (JSON.parse(hit.json) as { value?: unknown }).value; 86+ const value = this.#source.read(collection, key); 87+ const overhead = 2 * cacheKey.length + 160; 88+ let entry: CachedValue; 90+ value === undefined || 92+ typeof value === "string" || 93+ typeof value === "boolean" || 94+ (typeof value === "number" && Number.isFinite(value)) 96+ entry = { kind: "scalar", value, bytes: overhead + (typeof value === "string" ? 2 * value.length : 16) }; 98+ Array.isArray(value) && 99+ value.length <= 256 && 100+ Object.keys(value).length === value.length && 101+ value.every(Number.isSafeInteger) 103+ // Store one private, bounded numeric page. Public reads still receive a 104+ // fresh copy; neither the source result nor a reader can mutate the cache. 105+ entry = { kind: "numbers", value: value.slice(), bytes: overhead + 32 + value.length * 8 }; 107+ const json = JSON.stringify({ value }); 108+ entry = { kind: "json", json, bytes: overhead + 2 * json.length }; 110+ this.#remember(cacheKey, entry); 111+ // A projection scope's own rows are never read again once it ends in its rollback: forget them with it. 112+ if (collection.startsWith("projection-scratch:")) this.#touched.at(-1)?.add(cacheKey); 115+ #remember(cacheKey: string, entry: CachedValue): void { 116+ this.#drop(cacheKey); 117+ // Payload accounting is bounded, not a measurement of actual isolate heap. 118+ if (entry.bytes <= this.#maxEntryBytes && this.#maxEntries > 0) { 119+ while (this.#bytes + entry.bytes > this.#maxBytes || this.#cache.size >= this.#maxEntries) 120+ this.#drop(this.#cache.keys().next().value!); 121+ this.#cache.set(cacheKey, entry); 122+ this.#bytes += entry.bytes; 125+ write(collection: string, key: string, value: unknown): void { 126+ const cacheKey = JSON.stringify([collection, key]); 127+ this.#drop(cacheKey); 128+ this.#touched.at(-1)?.add(cacheKey); 129+ this.#source.write(collection, key, value); 130+ // Allocation counters are immutable scalars. Keep successful writes within 131+ // the existing cache budget instead of immediately reading them back. 132+ if (typeof value === "number" && Number.isSafeInteger(value) && !Object.is(value, -0)) 133+ this.#remember(cacheKey, { kind: "scalar", value, bytes: 2 * cacheKey.length + 176 }); 135+ remove(collection: string, key: string): void { 136+ const cacheKey = JSON.stringify([collection, key]); 137+ this.#drop(cacheKey); 138+ this.#touched.at(-1)?.add(cacheKey); 139+ this.#source.remove(collection, key); 141+ entries(collection: string): Iterable<readonly [string, unknown]> { 142+ return this.#source.entries(collection); 144+ transaction<T>(body: () => T): T { 145+ const touched = new Set<string>(); 146+ this.#touched.push(touched); 148+ const result = this.#source.transaction(body); 149+ this.#touched.pop(); 150+ // Committed into the outer transaction, which may still roll back. 151+ const outer = this.#touched.at(-1); 152+ if (outer) for (const key of touched) outer.add(key); 155+ this.#touched.pop(); 156+ // What the transaction wrote, and anything read back after it wrote it, is gone with the rollback. 157+ for (const key of touched) this.#drop(key); 164+ * Sets known to be closed under dependencies (abso Capacity): every atom's deps are in the set. A view or a project 165+ * given one skips proving it again, which read every atom and every dependency in the history. 167+const closedSets = new WeakSet<object>(); 168+export function markClosed<S extends ReadonlySet<unknown>>(set: S): S { 169+ closedSets.add(set); 172+export function isClosedSet(set: unknown): boolean { 173+ return typeof set === "object" && set !== null && closedSets.has(set); 176+/** Immutable membership whose implementation does not retain its enumerated keys. */ 177+export abstract class StableSet<T> implements ReadonlySet<T> { 178+ abstract has(value: T): boolean; 179+ abstract values(): SetIterator<T>; 180+ /** Only resident membership data; external storage is not charged as heap. */ 181+ abstract readonly retainedBytes: number; 182+ get [Symbol.toStringTag](): string { 185+ get size(): number { 187+ for (const _ of this) count++; 190+ keys(): SetIterator<T> { 191+ return this.values(); 193+ *entries(): SetIterator<[T, T]> { 194+ for (const value of this) yield [value, value]; 196+ [Symbol.iterator](): SetIterator<T> { 197+ return this.values(); 199+ forEach(callback: (value: T, key: T, set: ReadonlySet<T>) => void, thisArg?: unknown): void { 200+ for (const value of this) callback.call(thisArg, value, value, this); 204+/** Both operands must be immutable for the lifetime of this union. */ 205+export class StableUnionSet<T> extends StableSet<T> { 206+ readonly #left: StableSet<T>; 207+ readonly #right: StableSet<T>; 208+ constructor(left: StableSet<T>, right: StableSet<T>) { 211+ this.#right = right; 213+ get retainedBytes(): number { 214+ return 32 + this.#left.retainedBytes + this.#right.retainedBytes; 216+ get left(): StableSet<T> { 219+ get right(): StableSet<T> { 222+ has(value: T): boolean { 223+ return this.#left.has(value) || this.#right.has(value); 225+ *values(): SetIterator<T> { 227+ for (const value of this.#right) if (!this.#left.has(value)) yield value; 231+/** Immutable indexed subtraction retains neither operand's enumerated values. */ 232+export class StableDifferenceSet<T> extends StableSet<T> { 233+ readonly left: StableSet<T>; 234+ readonly right: StableSet<T>; 235+ constructor(left: StableSet<T>, right: StableSet<T>) { 240+ get retainedBytes(): number { 241+ return 32 + this.left.retainedBytes + this.right.retainedBytes; 243+ has(value: T): boolean { 244+ return this.left.has(value) && !this.right.has(value); 246+ *values(): SetIterator<T> { 247+ for (const value of this.left) if (!this.right.has(value)) yield value; 251+/** Preserve indexed history; only the caller's operation-sized overlay is copied. */ 252+export function unionOverlay<T>(base: ReadonlySet<T>, overlay: Iterable<T>): ReadonlySet<T> { 253+ return base instanceof StableSet 254+ ? new StableUnionSet(base, new StableOverlaySet(overlay)) 255+ : new Set([...base, ...overlay]); 258+/** Both indexed operands must be immutable for the lifetime of the result. */ 259+export function differenceSet<T>(left: ReadonlySet<T>, right: ReadonlySet<T>): ReadonlySet<T> { 260+ return left instanceof StableSet && right instanceof StableSet 261+ ? new StableDifferenceSet(left, right) 262+ : new Set([...left].filter((value) => !right.has(value))); 265+/** An immutable snapshot for the operation's small overlay, not its history. */ 266+export class StableOverlaySet<T> extends StableSet<T> { 267+ readonly #values: Set<T>; 268+ constructor(values: Iterable<T>) { 270+ this.#values = new Set(values); 272+ get retainedBytes(): number { 273+ return 64 + this.#values.size * 32; 275+ has(value: T): boolean { 276+ return this.#values.has(value); 278+ values(): SetIterator<T> { 279+ return this.#values.values(); 283+const indexKey = (key: PropertyKey): key is string => 284+ typeof key === "string" && /^(0|[1-9][0-9]*)$/.test(key) && Number.isSafeInteger(Number(key)); 286+/** Fixed-size numeric pages; callers retain no pages outside the bounded storage cache. */ 287+export function storedNumbers(storage: GraphStateStorage, name: string) { 288+ const pageSize = 256; 289+ const meta = `${name}:meta`; 290+ const length = () => (storage.read(meta, "length") as number | undefined) ?? 0; 291+ // Older experimental writer indexes must be rebuilt from their canonical log. 292+ // Never interpret per-element rows as pages or silently lose existing history. 293+ const page = (index: number): number[] => { 294+ if (storage.read(meta, "format") !== 2) 295+ throw new Error(`writer numeric index ${name} requires canonical-log adoption`); 296+ const values = storage.read(`${name}:pages`, String(Math.floor(index / pageSize))) as number[] | undefined; 297+ if (!values) throw new Error(`missing writer numeric page in ${name}`); 304+ at(index: number): number { 305+ if (!Number.isSafeInteger(index) || index < 0 || index >= length()) 306+ throw new Error(`writer numeric index out of bounds in ${name}`); 307+ const value = page(index)[index % pageSize]; 308+ if (value === undefined) throw new Error(`incomplete writer numeric page in ${name}`); 311+ push(value: number): void { 312+ if (!Number.isSafeInteger(value)) throw new Error("writer numeric indexes require safe integers"); 313+ const index = length(); 314+ if (index > 0 && storage.read(meta, "format") !== 2) 315+ throw new Error(`writer numeric index ${name} requires canonical-log adoption`); 316+ const offset = index % pageSize; 317+ const values = offset === 0 ? [] : page(index); 318+ if (values.length !== offset) throw new Error(`invalid writer numeric page length in ${name}`); 320+ storage.write(`${name}:pages`, String(Math.floor(index / pageSize)), values); 321+ if (index === 0) storage.write(meta, "format", 2); 322+ storage.write(meta, "length", index + 1); 324+ set(index: number, value: number): void { 325+ if (!Number.isSafeInteger(value)) throw new Error("writer numeric indexes require safe integers"); 326+ if (!Number.isSafeInteger(index) || index < 0 || index >= length()) 327+ throw new Error(`writer numeric index out of bounds in ${name}`); 328+ const values = page(index); 329+ if (index % pageSize >= values.length) throw new Error(`incomplete writer numeric page in ${name}`); 330+ values[index % pageSize] = value; 331+ storage.write(`${name}:pages`, String(Math.floor(index / pageSize)), values); 336+/** Array-shaped access without retaining its historical values in memory. */ 337+export function storedArray<T>( 338+ storage: GraphStateStorage, 340+ decode?: (value: T) => T, 341+ encode?: (value: T, key: string) => unknown, 343+ const length = () => (storage.read(`${name}:meta`, "length") as number | undefined) ?? 0; 344+ const read = (key: string) => { 345+ const value = storage.read(name, key) as T; 346+ return value === undefined || !decode ? value : decode(value); 348+ return new Proxy([] as T[], { 349+ get(target, key, receiver) { 350+ if (key === "length") return length(); 351+ // No length read first (abso Capacity): set writes the row and the length together and nothing shrinks, so no 352+ // row lies past the length. Half of a cold layout's reads were this length. 353+ if (indexKey(key)) return read(key); 354+ return Reflect.get(target, key, receiver); 356+ set(_target, key, value) { 357+ if (key === "length") { 358+ if (value !== length()) throw new Error("stored graph arrays cannot be resized directly"); 361+ if (!indexKey(key)) throw new Error("invalid stored graph array property"); 362+ const index = Number(key); 363+ const size = length(); 364+ if (index > size) throw new Error("stored graph arrays cannot contain gaps"); 365+ storage.write(name, key, encode ? encode(value, key) : value); 366+ if (index === size) storage.write(`${name}:meta`, "length", size + 1); 370+ return indexKey(key) ? Number(key) < length() : Reflect.has(target, key); 373+ return [...Array.from({ length: length() }, (_, index) => String(index)), "length"]; 375+ getOwnPropertyDescriptor(target, key) { 376+ if (indexKey(key) && Number(key) < length()) 377+ return { configurable: true, enumerable: true, writable: true, value: read(key) }; 378+ return Reflect.getOwnPropertyDescriptor(target, key); 383+export interface StateMap<K, V> { 384+ keys(): IterableIterator<K>; 385+ get(key: K): V | undefined; 386+ set(key: K, value: V): StateMap<K, V>; 387+ has(key: K): boolean; 388+ delete(key: K): boolean; 389+ values(): IterableIterator<V>; 392+/** Append-only per-key lists, retaining at most one fixed-size page per iterator. */ 393+export function storedLists<V>( 394+ storage: GraphStateStorage, 396+ legacyKey = (key: string) => JSON.stringify(["string", key]), 398+ const pageSize = 256; 399+ // The previous experimental layout stored one whole historical list per key. 400+ const length = (key: string) => { 401+ const stored = storage.read(`${name}:lengths`, key) as number | undefined; 402+ if (stored === undefined && storage.read(name, legacyKey(key)) !== undefined) 403+ throw new Error(`writer list index ${name} requires canonical-log adoption`); 404+ const count = stored ?? 0; 405+ if (!Number.isSafeInteger(count) || count < 0) throw new Error(`invalid writer list count in ${name}`); 408+ const pageKey = (key: string, page: number) => JSON.stringify([key, page]); 409+ const page = (key: string, index: number): V[] => { 410+ const values = storage.read(`${name}:pages`, pageKey(key, index)) as V[] | undefined; 411+ if (!Array.isArray(values) || values.length < 1 || values.length > pageSize) 412+ throw new Error(`missing or invalid writer list page in ${name}`); 417+ *keys(): IterableIterator<string> { 418+ for (const entry of storage.entries(name)) { 420+ throw new Error(`writer list index ${name} requires canonical-log adoption`); 422+ for (const [key] of storage.entries(`${name}:lengths`)) yield key; 424+ /** Values [index * PAGE, (index + 1) * PAGE) of `key`'s list: one page, not the whole list (abso Capacity). */ 425+ pageAt(key: string, index: number): readonly V[] { 426+ const count = length(key); 427+ const values = page(key, index); 428+ if (values.length !== Math.min(pageSize, count - index * pageSize)) 429+ throw new Error(`incomplete writer list page in ${name}`); 432+ *values(key: string): IterableIterator<V> { 433+ const count = length(key); 434+ for (let start = 0; start < count; start += pageSize) { 435+ const values = page(key, start / pageSize); 436+ if (values.length !== Math.min(pageSize, count - start)) 437+ throw new Error(`incomplete writer list page in ${name}`); 441+ last(key: string): V | undefined { 442+ const count = length(key); 443+ if (count === 0) return undefined; 444+ const values = page(key, Math.floor((count - 1) / pageSize)); 445+ const expected = ((count - 1) % pageSize) + 1; 446+ if (values.length !== expected) throw new Error(`incomplete writer list page in ${name}`); 447+ return values[expected - 1]; 449+ append(key: string, value: V): void { 450+ const count = length(key); 451+ const offset = count % pageSize; 452+ const index = Math.floor(count / pageSize); 453+ const values = offset === 0 ? [] : page(key, index); 454+ if (values.length !== offset) throw new Error(`invalid writer list length in ${name}`); 456+ storage.write(`${name}:pages`, pageKey(key, index), values); 457+ storage.write(`${name}:lengths`, key, count + 1); 459+ /** Append several values, writing each page they touch once. */ 460+ appendAll(key: string, more: readonly V[]): void { 461+ if (more.length === 0) return; 462+ const count = length(key); 463+ let index = Math.floor(count / pageSize); 464+ let values = count % pageSize === 0 ? [] : page(key, index); 465+ if (values.length !== count % pageSize) throw new Error(`invalid writer list length in ${name}`); 466+ for (const value of more) { 467+ if (values.length === pageSize) { 468+ storage.write(`${name}:pages`, pageKey(key, index++), values); 473+ storage.write(`${name}:pages`, pageKey(key, index), values); 474+ storage.write(`${name}:lengths`, key, count + more.length); 479+/** Keys are tagged so numeric graph codes cannot collide with string keys. */ 480+export function storedMap<K extends string | number, V>(storage: GraphStateStorage, name: string): StateMap<K, V> { 481+ const keyOf = (key: K) => JSON.stringify([typeof key, key]); 482+ const map: StateMap<K, V> = { 484+ for (const [key] of storage.entries(name)) yield (JSON.parse(key) as [string, K])[1]; 486+ get: (key) => storage.read(name, keyOf(key)) as V | undefined, 487+ has: (key) => storage.read(name, keyOf(key)) !== undefined, 489+ storage.write(name, keyOf(key), value); 493+ const existed = map.has(key); 494+ storage.remove(name, keyOf(key)); 498+ for (const [, value] of storage.entries(name)) yield value as V; 505+ * A Map-compatible persistent index. Iteration follows insertion order and 506+ * decodes one row at a time. Returned objects are copies, so mutations need 507+ * an explicit set. Hosts wrap a logical multi-index mutation in transaction. 509+export class StoredMap<K extends string | number, V> extends Map<K, V> { 510+ readonly #storage: GraphStateStorage; 511+ readonly #name: string; 512+ readonly #encode: (value: V) => unknown; 513+ readonly #decode: (value: unknown) => V; 515+ storage: GraphStateStorage, 517+ codec?: { encode(value: V): unknown; decode(value: unknown): V }, 520+ this.#storage = storage; 522+ this.#encode = codec?.encode ?? ((value) => value); 523+ this.#decode = codec?.decode ?? ((value) => value as V); 525+ #key(key: K): string { 526+ return JSON.stringify([typeof key, key]); 528+ #row(key: K): { slot: number; value: unknown } | undefined { 529+ return this.#storage.read(this.#name, this.#key(key)) as { slot: number; value: unknown } | undefined; 531+ override get size(): number { 532+ return (this.#storage.read(`${this.#name}:meta`, "size") as number | undefined) ?? 0; 534+ override has(key: K): boolean { 535+ return this.#row(key) !== undefined; 537+ override get(key: K): V | undefined { 538+ const row = this.#row(key); 539+ return row === undefined ? undefined : this.#decode(row.value); 541+ override set(key: K, value: V): this { 542+ const row = this.#row(key); 543+ let slot = row?.slot; 544+ if (slot === undefined) { 545+ const keys = storedArray<K>(this.#storage, `${this.#name}:order`); 548+ this.#storage.write(`${this.#name}:meta`, "size", this.size + 1); 550+ this.#storage.write(this.#name, this.#key(key), { slot, value: this.#encode(value) }); 553+ override delete(key: K): boolean { 554+ if (!this.has(key)) return false; 555+ this.#storage.remove(this.#name, this.#key(key)); 556+ this.#storage.write(`${this.#name}:meta`, "size", this.size - 1); 559+ override clear(): void { 560+ for (const key of this.keys()) this.delete(key); 562+ override *entries(): MapIterator<[K, V]> { 563+ const keys = storedArray<K>(this.#storage, `${this.#name}:order`); 564+ for (let slot = 0; slot < keys.length; slot++) { 565+ const key = keys[slot]!; 566+ const row = this.#row(key); 567+ if (row?.slot === slot) yield [key, this.#decode(row.value)]; 570+ override *keys(): MapIterator<K> { 571+ const keys = storedArray<K>(this.#storage, `${this.#name}:order`); 572+ for (let slot = 0; slot < keys.length; slot++) { 573+ const key = keys[slot]!; 574+ if (this.#row(key)?.slot === slot) yield key; 577+ override *values(): MapIterator<V> { 578+ for (const [, value] of this.entries()) yield value; 580+ override [Symbol.iterator](): MapIterator<[K, V]> { 581+ return this.entries(); 583+ override forEach(callback: (value: V, key: K, map: Map<K, V>) => void, thisArg?: unknown): void { 584+ for (const [key, value] of this.entries()) callback.call(thisArg, value, key, this); 588+/** Persistent membership with streaming iteration and no in-memory key cache. */ 589+export class StoredSet<K extends string | number> extends Set<K> { 590+ readonly #map: StoredMap<K, true>; 591+ constructor(storage: GraphStateStorage, name: string) { 593+ this.#map = new StoredMap(storage, name); 595+ override get size(): number { 596+ return this.#map.size; 598+ override has(key: K): boolean { 599+ return this.#map.has(key); 601+ override add(key: K): this { 602+ this.#map.set(key, true); 605+ override delete(key: K): boolean { 606+ return this.#map.delete(key); 608+ override clear(): void { 611+ override *values(): SetIterator<K> { 612+ yield* this.#map.keys(); 614+ override keys(): SetIterator<K> { 615+ return this.values(); 617+ override *entries(): SetIterator<[K, K]> { 618+ for (const key of this.values()) yield [key, key]; 620+ override [Symbol.iterator](): SetIterator<K> { 621+ return this.values(); 623+ override forEach(callback: (value: K, key: K, set: Set<K>) => void, thisArg?: unknown): void { 624+ for (const key of this.values()) callback.call(thisArg, key, key, this); 628+/** Read-only array access to individually stored values, without copying the list. */ 629+/** How many values an atom's long list keeps to a row (readonlyPagedArray). */ 630+export const LIST_PAGE = 256; 632+/** Write a list as readonlyPagedArray reads it: its values LIST_PAGE to a row, and its length. */ 633+export function writePagedArray(storage: GraphStateStorage, name: string, values: readonly unknown[]): void { 634+ for (let start = 0; start < values.length; start += LIST_PAGE) 635+ storage.write(`${name}:pages`, String(start / LIST_PAGE), values.slice(start, start + LIST_PAGE)); 636+ storage.write(`${name}:meta`, "length", values.length); 640+ * A stored list read a page of LIST_PAGE values at a time (abso Capacity): an atom's long lists, which 641+ * readonlyStoredArray reads a row per value. Collisions read every key a draft's atoms write; a draft deleting a big 642+ * file has thousands, and that was a row each. 644+export function readonlyPagedArray<T>(storage: GraphStateStorage, name: string): readonly T[] { 645+ const length = () => { 646+ const count = storage.read(`${name}:meta`, "length"); 647+ if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid stored list length"); 648+ return count as number; 652+ let page: readonly unknown[] = []; 653+ const at = (index: number): T => { 654+ const p = Math.floor(index / LIST_PAGE); 656+ const raw = storage.read(`${name}:pages`, String(p)); 657+ if (!Array.isArray(raw)) throw Error("missing stored list page"); 661+ const value = page[index % LIST_PAGE]; 662+ if (value === undefined) throw Error("missing stored list element"); 663+ return (value && typeof value === "object" ? Object.freeze(value) : value) as T; 665+ function* inOrder(): IterableIterator<T> { 666+ const count = length(); 667+ for (let index = 0; index < count; index++) yield at(index); 669+ return new Proxy([] as T[], { 670+ get(target, key, receiver) { 671+ if (key === "length") return length(); 672+ if (key === Symbol.iterator || key === "values") return inOrder; 673+ if (indexKey(key)) return Number(key) >= length() ? undefined : at(Number(key)); 674+ return Reflect.get(target, key, receiver); 677+ return indexKey(key) ? Number(key) < length() : Reflect.has(target, key); 680+ return [...Array.from({ length: length() }, (_, index) => String(index)), "length"]; 682+ getOwnPropertyDescriptor(target, key) { 683+ if (indexKey(key) && Number(key) < length()) 684+ return { configurable: true, enumerable: true, writable: false, value: at(Number(key)) }; 685+ return Reflect.getOwnPropertyDescriptor(target, key); 688+ throw Error("stored lists are read-only"); 693+export function readonlyStoredArray<T>( 694+ storage: GraphStateStorage, 696+ decode?: (value: unknown, index: number) => T, 698+ const length = () => { 699+ const count = storage.read(`${name}:meta`, "length"); 700+ if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid stored list length"); 701+ return count as number; 704+ const at = (index: number): T => { 705+ const raw = storage.read(name, String(index)); 706+ const value = raw === undefined ? undefined : decode ? decode(raw, index) : (raw as T); 707+ if (value === undefined) throw Error("missing stored list element"); 708+ return value && typeof value === "object" ? (Object.freeze(value) as T) : value; 710+ // In order, with the length read once (abso Capacity): the array iterator reads it again before every element, a 711+ // second disk read per element of a list too long for the cache. 712+ function* inOrder(): IterableIterator<T> { 713+ const count = length(); 714+ for (let index = 0; index < count; index++) yield at(index); 716+ return new Proxy([] as T[], { 717+ get(target, key, receiver) { 718+ if (key === "length") return length(); 719+ if (key === Symbol.iterator || key === "values") return inOrder; 720+ if (indexKey(key)) return Number(key) >= length() ? undefined : at(Number(key)); 721+ return Reflect.get(target, key, receiver); 724+ return indexKey(key) ? Number(key) < length() : Reflect.has(target, key); 727+ return [...Array.from({ length: length() }, (_, index) => String(index)), "length"]; 729+ getOwnPropertyDescriptor(target, key) { 730+ if (key === "length") return { ...Reflect.getOwnPropertyDescriptor(target, key)!, value: length() }; 731+ if (indexKey(key) && Number(key) < length()) { 732+ const raw = storage.read(name, key); 733+ const value = raw === undefined ? undefined : decode ? decode(raw, Number(key)) : (raw as T); 734+ if (value === undefined) throw Error("missing stored list element"); 739+ value: value && typeof value === "object" ? Object.freeze(value) : value, 742+ return Reflect.getOwnPropertyDescriptor(target, key); 744+ preventExtensions() { 745+ throw Error("stored list is read-only"); 748+ throw Error("stored list is read-only"); 751+ throw Error("stored list is read-only"); 754+ throw Error("stored list is read-only");