@the-w1zard/singularity 1.0.11 → 1.0.13

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.
@@ -0,0 +1,590 @@
1
+ // #region ══════════════════════════════════════════════════════════════════════════════════════════════════════
2
+ //
3
+ // Design pillars:
4
+ // 1. Structured clone in/out — no JSON round-trip. Map/Set/Date/Blob native.
5
+ // 2. Transaction batching — all ops in a tick share one transaction.
6
+ // 3. SWR memory cache + in-flight dedup + write coalescing.
7
+ // 4. Cross-tab sync via BroadcastChannel + HLC (no LWW-by-luck).
8
+ // 5. Pub/sub that returns Teardown and bridges to onFlush.
9
+ // 6. Explicit versioning — defineMigration(v, upgrade) once.
10
+ // 7. Cursor-as-async-iterator — `for await (const [k,v] of db.entries())`.
11
+ // 8. Zero deps. Browser + Bun + Node (via fake-indexeddb).
12
+ // ─────────────────────────────────────────────────────────────────────────────
13
+ import { HYBRID_LOGICAL_CLOCK_CRDT } from '#hlc';
14
+ const isBrowser = typeof window !== 'undefined';
15
+ export function runTeardown(t) {
16
+ if (t == null)
17
+ return;
18
+ if (typeof t === 'function')
19
+ return void t();
20
+ if (Array.isArray(t)) {
21
+ for (const x of t)
22
+ runTeardown(x);
23
+ return;
24
+ }
25
+ const a = t;
26
+ if (typeof a.unsubscribe === 'function')
27
+ return void a.unsubscribe();
28
+ if (typeof a[Symbol.dispose] === 'function')
29
+ return void a[Symbol.dispose]();
30
+ }
31
+ export function reportError(e) {
32
+ const g = globalThis;
33
+ if (typeof g.reportError === 'function')
34
+ return void g.reportError(e);
35
+ queueMicrotask(() => { throw e; });
36
+ }
37
+ export class INDEXED_DB {
38
+ dbName;
39
+ storeName;
40
+ _version;
41
+ _migrations = new Map();
42
+ _nodeId;
43
+ _hlc;
44
+ _onFlush;
45
+ _onError;
46
+ // ── connection ──────────────────────────────────────────────────────────
47
+ _db = null;
48
+ _opening = null;
49
+ // ── memory cache (SWR) ──────────────────────────────────────────────────
50
+ memory = new O2();
51
+ inflight = new O2();
52
+ ttlMs;
53
+ memoryTimer;
54
+ // ── transaction batching ────────────────────────────────────────────────
55
+ pending = [];
56
+ flushScheduled = false;
57
+ _closed = false;
58
+ // ── subscribers ─────────────────────────────────────────────────────────
59
+ subscribers = new Map();
60
+ // ── cross-tab ───────────────────────────────────────────────────────────
61
+ _channel;
62
+ _localChange = false;
63
+ constructor(opts = {}) {
64
+ this.dbName = opts.dbName ?? 'the_wizard';
65
+ this.storeName = opts.storeName ?? 'the_wizards_tardis';
66
+ this._version = opts.version ?? 1;
67
+ this._nodeId = opts.nodeId ?? Math.random().toString(36).slice(2, 10);
68
+ this.ttlMs = opts.ttlMs ?? 30 * 60 * 1000;
69
+ this._onFlush = opts.onFlush ?? ((fn) => queueMicrotask(fn));
70
+ this._onError = opts.onError ?? reportError;
71
+ if (typeof BroadcastChannel !== 'undefined') {
72
+ this._channel = new BroadcastChannel(`sauron_idb_sync:${this.dbName}:${this.storeName}`);
73
+ this._channel.onmessage = (e) => this._onRemote(e.data);
74
+ }
75
+ this._hlc = new HYBRID_LOGICAL_CLOCK_CRDT(this._nodeId);
76
+ }
77
+ // ───────────────────────────────────────────────────────────────────────
78
+ // Migrations — call before first open. Each version gets one upgrader.
79
+ // ───────────────────────────────────────────────────────────────────────
80
+ defineMigration(version, fn) {
81
+ this._migrations.set(version, fn);
82
+ if (version > this._version)
83
+ this._version = version;
84
+ return this;
85
+ }
86
+ // ───────────────────────────────────────────────────────────────────────
87
+ // Open — idempotent, single in-flight promise, runs all pending migrations
88
+ // ───────────────────────────────────────────────────────────────────────
89
+ open() {
90
+ if (this._db)
91
+ return Promise.resolve(this._db);
92
+ if (this._opening)
93
+ return this._opening;
94
+ if (typeof indexedDB === 'undefined') {
95
+ return Promise.reject(new Error('[INDEXED_DB] indexedDB is not defined in this environment'));
96
+ }
97
+ this._opening = new Promise((resolve, reject) => {
98
+ const req = indexedDB.open(this.dbName, this._version);
99
+ req.onupgradeneeded = (ev) => {
100
+ const db = req.result;
101
+ const oldVersion = ev.oldVersion;
102
+ if (!db.objectStoreNames.contains(this.storeName)) {
103
+ db.createObjectStore(this.storeName);
104
+ }
105
+ // run migrations from oldVersion+1 .. this._version
106
+ for (let v = oldVersion + 1; v <= this._version; v++) {
107
+ const fn = this._migrations.get(v);
108
+ if (fn) {
109
+ try {
110
+ fn(db, oldVersion);
111
+ }
112
+ catch (err) {
113
+ this._onError(err);
114
+ reject(err);
115
+ return;
116
+ }
117
+ }
118
+ }
119
+ };
120
+ req.onsuccess = () => {
121
+ this._db = req.result;
122
+ this._opening = null;
123
+ this._db.onclose = () => { this._db = null; };
124
+ this._db.onversionchange = () => { this._db?.close(); this._db = null; };
125
+ resolve(this._db);
126
+ };
127
+ req.onerror = () => { this._opening = null; reject(req.error); };
128
+ req.onblocked = () => { };
129
+ });
130
+ return this._opening;
131
+ }
132
+ // ───────────────────────────────────────────────────────────────────────
133
+ // Transaction batching
134
+ //
135
+ // All ops queued within a microtask get executed in a single IDB
136
+ // transaction. This is the biggest perf win vs. the old per-op tx().
137
+ //
138
+ // We serialize ALL ops through one readwrite transaction. IDB will
139
+ // upgrade readonly ops to readwrite anyway when mixed, and the cost of
140
+ // a readwrite tx over readonly is tiny compared to the setup cost.
141
+ // ───────────────────────────────────────────────────────────────────────
142
+ scheduleFlush() {
143
+ if (this.flushScheduled)
144
+ return;
145
+ this.flushScheduled = true;
146
+ this._onFlush(() => this.flush());
147
+ }
148
+ async flush() {
149
+ this.flushScheduled = false;
150
+ if (this.pending.length === 0 || this._closed)
151
+ return;
152
+ const ops = this.pending;
153
+ this.pending = [];
154
+ let db;
155
+ try {
156
+ db = await this.open();
157
+ }
158
+ catch (err) {
159
+ for (const op of ops)
160
+ ('reject' in op && op.reject(err));
161
+ return;
162
+ }
163
+ let tx;
164
+ try {
165
+ tx = db.transaction(this.storeName, 'readwrite');
166
+ }
167
+ catch (err) {
168
+ for (const op of ops)
169
+ ('reject' in op && op.reject(err));
170
+ return;
171
+ }
172
+ const store = tx.objectStore(this.storeName);
173
+ // Wire up all requests inside one tx. IDB keeps the tx alive as long
174
+ // as there's at least one pending request, so scheduling them all
175
+ // before returning is safe.
176
+ for (const op of ops) {
177
+ try {
178
+ switch (op.kind) {
179
+ case 'get': {
180
+ const r = store.get(op.key);
181
+ r.onsuccess = () => {
182
+ const rec = r.result;
183
+ if (rec) {
184
+ this.memory.set(op.key, rec);
185
+ op.resolve(rec.value);
186
+ }
187
+ else
188
+ op.resolve(undefined);
189
+ };
190
+ r.onerror = () => op.reject(r.error);
191
+ break;
192
+ }
193
+ case 'put': {
194
+ const rec = {
195
+ value: op.value,
196
+ hlc: this._hlc.tick(),
197
+ nodeId: this._nodeId,
198
+ ts: Date.now(),
199
+ };
200
+ const r = store.put(rec, op.key);
201
+ r.onsuccess = () => {
202
+ this.memory.set(op.key, rec);
203
+ this._broadcastPut(op.key, rec);
204
+ this._emit(op.key, rec.value);
205
+ op.resolve();
206
+ };
207
+ r.onerror = () => op.reject(r.error);
208
+ break;
209
+ }
210
+ case 'del': {
211
+ const r = store.delete(op.key);
212
+ r.onsuccess = () => {
213
+ this.memory.delete(op.key);
214
+ this._broadcastDel(op.key);
215
+ this._emit(op.key, undefined);
216
+ op.resolve();
217
+ };
218
+ r.onerror = () => op.reject(r.error);
219
+ break;
220
+ }
221
+ case 'has': {
222
+ const r = store.getKey(op.key);
223
+ r.onsuccess = () => op.resolve(r.result !== undefined);
224
+ r.onerror = () => op.reject(r.error);
225
+ break;
226
+ }
227
+ case 'keys': {
228
+ const r = store.getAllKeys();
229
+ r.onsuccess = () => op.resolve(r.result);
230
+ r.onerror = () => op.reject(r.error);
231
+ break;
232
+ }
233
+ case 'clear': {
234
+ const r = store.clear();
235
+ r.onsuccess = () => {
236
+ this.memory.clear();
237
+ this._broadcastClear();
238
+ op.resolve();
239
+ };
240
+ r.onerror = () => op.reject(r.error);
241
+ break;
242
+ }
243
+ case 'cursor': {
244
+ const out = [];
245
+ const r = store.openCursor(op.range);
246
+ r.onsuccess = () => {
247
+ const c = r.result;
248
+ if (c) {
249
+ const rec = c.value;
250
+ out.push([c.key, rec.value]);
251
+ c.continue();
252
+ }
253
+ else {
254
+ op.resolve(out);
255
+ }
256
+ };
257
+ r.onerror = () => op.reject(r.error);
258
+ break;
259
+ }
260
+ }
261
+ }
262
+ catch (err) {
263
+ 'reject' in op && op.reject(err);
264
+ }
265
+ }
266
+ }
267
+ // ───────────────────────────────────────────────────────────────────────
268
+ // Core CRUD — all batched through the pending queue
269
+ // ───────────────────────────────────────────────────────────────────────
270
+ get(key) {
271
+ const cached = this.memory.get(key);
272
+ if (cached) {
273
+ return MaybePromise(cached.value);
274
+ }
275
+ else {
276
+ return MaybePromise(this._enqueueGet(key));
277
+ }
278
+ }
279
+ getOrThrow(key) {
280
+ const v = this.get(key);
281
+ if (v === undefined)
282
+ throw new Error(`[INDEXED_DB] key not found: ${key}`);
283
+ else
284
+ return MaybePromise(v);
285
+ }
286
+ has(key) {
287
+ if (this.memory.has(key))
288
+ return MaybePromise(true);
289
+ else
290
+ return MaybePromise(this._enqueueHas(key));
291
+ }
292
+ set(key, value) {
293
+ // write-through memory so subsequent gets in the same tick see it
294
+ const rec = {
295
+ value,
296
+ hlc: this._hlc.tick(),
297
+ nodeId: this._nodeId,
298
+ ts: Date.now(),
299
+ };
300
+ this.memory.set(key, rec);
301
+ return MaybePromise(this._enqueuePut(key, value));
302
+ }
303
+ async setMany(entries) {
304
+ await Promise.all(Object.entries(entries).map(([k, v]) => this.set(k, v)));
305
+ }
306
+ async update(key, updater) {
307
+ const prev = await this.get(key);
308
+ const next = updater(prev);
309
+ await this.set(key, next);
310
+ return MaybePromise(next);
311
+ }
312
+ delete(key) {
313
+ this.memory.delete(key);
314
+ return MaybePromise(this._enqueueDel(key));
315
+ }
316
+ async deleteMany(keys) {
317
+ await Promise.all(keys.map((k) => this.delete(k)));
318
+ }
319
+ async clear(chain) {
320
+ this.memory.clear();
321
+ return MaybePromise(this._enqueueClear());
322
+ }
323
+ async keys(chain) {
324
+ return MaybePromise(this._enqueueKeys());
325
+ }
326
+ // ───────────────────────────────────────────────────────────────────────
327
+ // In-flight dedup: same key requested twice in a tick → one IDB get
328
+ // ───────────────────────────────────────────────────────────────────────
329
+ _enqueueGet(key) {
330
+ const existing = this.inflight.get(key);
331
+ if (existing)
332
+ return existing;
333
+ const p = new Promise((resolve, reject) => {
334
+ this.pending.push({ kind: 'get', key, resolve: resolve, reject });
335
+ this.scheduleFlush();
336
+ }).finally(() => { this.inflight.delete(key); });
337
+ this.inflight.set(key, p);
338
+ return p;
339
+ }
340
+ _enqueuePut(key, value) {
341
+ return new Promise((resolve, reject) => {
342
+ this.pending.push({ kind: 'put', key, value, resolve, reject });
343
+ this.scheduleFlush();
344
+ });
345
+ }
346
+ _enqueueDel(key) {
347
+ return new Promise((resolve, reject) => {
348
+ this.pending.push({ kind: 'del', key, resolve, reject });
349
+ this.scheduleFlush();
350
+ });
351
+ }
352
+ _enqueueHas(key) {
353
+ return new Promise((resolve, reject) => {
354
+ this.pending.push({ kind: 'has', key, resolve, reject });
355
+ this.scheduleFlush();
356
+ });
357
+ }
358
+ _enqueueKeys() {
359
+ return new Promise((resolve, reject) => {
360
+ this.pending.push({ kind: 'keys', resolve, reject });
361
+ this.scheduleFlush();
362
+ });
363
+ }
364
+ _enqueueClear() {
365
+ return new Promise((resolve, reject) => {
366
+ this.pending.push({ kind: 'clear', resolve, reject });
367
+ this.scheduleFlush();
368
+ });
369
+ }
370
+ _enqueueCursor(range) {
371
+ return new Promise((resolve, reject) => {
372
+ this.pending.push({ kind: 'cursor', range, resolve, reject });
373
+ this.scheduleFlush();
374
+ });
375
+ }
376
+ // ───────────────────────────────────────────────────────────────────────
377
+ // Pub/sub
378
+ // ───────────────────────────────────────────────────────────────────────
379
+ subscribe(key, cb, chain) {
380
+ let set = this.subscribers.get(key);
381
+ if (!set) {
382
+ set = new Set();
383
+ this.subscribers.set(key, set);
384
+ }
385
+ set.add(cb);
386
+ const cached = this.memory.get(key);
387
+ if (cached) {
388
+ try {
389
+ cb(cached.value);
390
+ }
391
+ catch (e) {
392
+ this._onError(e);
393
+ }
394
+ }
395
+ return () => {
396
+ const s = this.subscribers.get(key);
397
+ if (!s)
398
+ return;
399
+ s.delete(cb);
400
+ if (s.size === 0)
401
+ this.subscribers.delete(key);
402
+ };
403
+ }
404
+ /** Selector-based subscription — only fires when the selected slice changes. */
405
+ select(key, selector, cb, chain) {
406
+ let last;
407
+ let first = true;
408
+ return this.subscribe(key, (v) => {
409
+ const next = selector(v);
410
+ if (first || !Object.is(last, next)) {
411
+ first = false;
412
+ last = next;
413
+ cb(next);
414
+ }
415
+ });
416
+ }
417
+ _emit(key, value) {
418
+ const set = this.subscribers.get(key);
419
+ if (!set)
420
+ return;
421
+ for (const cb of set) {
422
+ try {
423
+ cb(value);
424
+ }
425
+ catch (e) {
426
+ this._onError(e);
427
+ }
428
+ }
429
+ }
430
+ // ───────────────────────────────────────────────────────────────────────
431
+ // waitFor — with waiter cleanup (no leak)
432
+ // ───────────────────────────────────────────────────────────────────────
433
+ waitFor(key, opts = {}) {
434
+ const existing = this.memory.get(key);
435
+ if (existing)
436
+ return Promise.resolve(existing.value);
437
+ return new Promise((resolve, reject) => {
438
+ let timer;
439
+ const unsub = this.subscribe(key, (v) => {
440
+ if (v === undefined)
441
+ return;
442
+ runTeardown(unsub);
443
+ if (timer)
444
+ clearTimeout(timer);
445
+ resolve(v);
446
+ });
447
+ if (opts.timeoutMs && opts.timeoutMs > 0) {
448
+ timer = setTimeout(() => {
449
+ runTeardown(unsub);
450
+ reject(new Error(`[INDEXED_DB] waitFor(${key}) timed out after ${opts.timeoutMs}ms`));
451
+ }, opts.timeoutMs);
452
+ }
453
+ });
454
+ }
455
+ // ───────────────────────────────────────────────────────────────────────
456
+ // Cursor as async iterator — `for await (const [k, v] of db.entries())`
457
+ // ───────────────────────────────────────────────────────────────────────
458
+ entries(range) {
459
+ let buf = null;
460
+ let idx = 0;
461
+ const self = this;
462
+ return {
463
+ [Symbol.asyncIterator]() { return this; },
464
+ async next() {
465
+ if (!buf) {
466
+ buf = await self._enqueueCursor(range);
467
+ }
468
+ if (idx >= buf.length)
469
+ return { done: true, value: undefined };
470
+ return { done: false, value: buf[idx++] };
471
+ },
472
+ };
473
+ }
474
+ // ───────────────────────────────────────────────────────────────────────
475
+ // Cross-tab sync via BroadcastChannel + HLC
476
+ // ───────────────────────────────────────────────────────────────────────
477
+ _broadcastPut(key, rec) {
478
+ this._localChange = true;
479
+ this._channel?.postMessage({ type: 'put', key, rec });
480
+ }
481
+ _broadcastDel(key) {
482
+ this._localChange = true;
483
+ this._channel?.postMessage({ type: 'del', key });
484
+ }
485
+ _broadcastClear() {
486
+ this._localChange = true;
487
+ this._channel?.postMessage({ type: 'clear' });
488
+ }
489
+ _onRemote(msg) {
490
+ if (!msg || typeof msg !== 'object')
491
+ return;
492
+ switch (msg.type) {
493
+ case 'put': {
494
+ const remote = msg.rec;
495
+ if (!remote?.hlc)
496
+ return;
497
+ this._hlc.update(remote.hlc);
498
+ const local = this.memory.get(msg.key);
499
+ if (local && this._hlc.compare(local.hlc, remote.hlc) >= 0)
500
+ return; // local wins
501
+ this.memory.set(msg.key, remote);
502
+ this._emit(msg.key, remote.value);
503
+ break;
504
+ }
505
+ case 'del': {
506
+ this.memory.delete(msg.key);
507
+ this._emit(msg.key, undefined);
508
+ break;
509
+ }
510
+ case 'clear': {
511
+ this.memory.clear();
512
+ // don't re-emit every key; consumers should listen for clear
513
+ this._emit('__clear__', undefined);
514
+ break;
515
+ }
516
+ }
517
+ }
518
+ // ───────────────────────────────────────────────────────────────────────
519
+ // Conflict policy — optional, mirrors your ConflictPolicy shape
520
+ // ───────────────────────────────────────────────────────────────────────
521
+ async merge(key, incoming, policy) {
522
+ const local = await this.get(key);
523
+ if (local === undefined)
524
+ return this.set(key, incoming);
525
+ const localRec = this.memory.get(key);
526
+ const remoteHlc = this._hlc.tick();
527
+ const resolved = policy(local, incoming, {
528
+ key,
529
+ localHlc: localRec.hlc,
530
+ remoteHlc,
531
+ nodeId: this._nodeId,
532
+ });
533
+ return this.set(key, resolved);
534
+ }
535
+ // ───────────────────────────────────────────────────────────────────────
536
+ // Memory cache control
537
+ // ───────────────────────────────────────────────────────────────────────
538
+ touchMemory() {
539
+ if (this.memoryTimer)
540
+ clearTimeout(this.memoryTimer);
541
+ this.memoryTimer = setTimeout(() => {
542
+ this.memory.clear();
543
+ this.memoryTimer = undefined;
544
+ }, this.ttlMs);
545
+ }
546
+ /** Force memory to rehydrate from IDB on next read. */
547
+ invalidateMemory(key) {
548
+ if (key)
549
+ this.memory.delete(key);
550
+ else
551
+ this.memory.clear();
552
+ }
553
+ _withLock(key, fn) {
554
+ if (typeof navigator !== 'undefined' && navigator.locks) {
555
+ return navigator.locks.request('mem_write_' + key, fn);
556
+ }
557
+ return fn();
558
+ }
559
+ // ───────────────────────────────────────────────────────────────────────
560
+ // Lifecycle
561
+ // ───────────────────────────────────────────────────────────────────────
562
+ async close() {
563
+ this._closed = true;
564
+ if (this.memoryTimer)
565
+ clearTimeout(this.memoryTimer);
566
+ this._channel?.close();
567
+ if (this._db) {
568
+ this._db.close();
569
+ this._db = null;
570
+ }
571
+ }
572
+ isOpen() { return !!this._db; }
573
+ async info() {
574
+ if (!this._db)
575
+ await this.open();
576
+ const tx = this._db.transaction(this.storeName, 'readonly');
577
+ const count = await new Promise((resolve, reject) => {
578
+ const r = tx.objectStore(this.storeName).count();
579
+ r.onsuccess = () => resolve(r.result);
580
+ r.onerror = () => reject(r.error);
581
+ });
582
+ return {
583
+ isOpen: !!this._db,
584
+ dbName: this.dbName,
585
+ storeName: this.storeName,
586
+ version: this._version,
587
+ count,
588
+ };
589
+ }
590
+ }
@@ -0,0 +1,28 @@
1
+ import { SERVER_KVDB } from "./db";
2
+ const db = new SERVER_KVDB("__SAURON__", "SAURON_SLAVE_REG", "SAURON_MASTER_REG", "THE_WIZARD_ROOT_REG", {
3
+ directory: "./bench-data",
4
+ durability: "group",
5
+ walBatchBytes: 1024 * 1024,
6
+ walBatchRecords: 8192,
7
+ walFlushIntervalMs: 1,
8
+ walHighWaterBytes: 64 * 1024 * 1024,
9
+ checkpointIntervalMs: 10_000
10
+ });
11
+ await db.open();
12
+ const value = new Uint8Array(128).fill(65);
13
+ const operations = 10_000_000;
14
+ const started = process.hrtime.bigint();
15
+ await db.set(`key`, value);
16
+ for (let index = 0; index < operations; index++) {
17
+ db.hot(`key`);
18
+ }
19
+ const elapsedNs = Number(process.hrtime.bigint() - started);
20
+ const operationsPerSecond = operations / (elapsedNs / 1e9);
21
+ console.log({
22
+ operations,
23
+ elapsedSeconds: elapsedNs / 1e9,
24
+ operationsPerSecond,
25
+ millionOperationsPerSecond: operationsPerSecond / 1e6,
26
+ stats: db.stats
27
+ });
28
+ await db.close();
@@ -0,0 +1,43 @@
1
+ export function encodeUtf8(value) {
2
+ return new TextEncoder().encode(value);
3
+ }
4
+ export function decodeUtf8(bytes) {
5
+ return new TextDecoder().decode(bytes);
6
+ }
7
+ export function concatBytes(parts) {
8
+ let length = 0;
9
+ for (const part of parts) {
10
+ length += part.length;
11
+ }
12
+ const output = new Uint8Array(length);
13
+ let offset = 0;
14
+ for (const part of parts) {
15
+ output.set(part, offset);
16
+ offset += part.length;
17
+ }
18
+ return output;
19
+ }
20
+ export function readUint32(bytes, offset) {
21
+ return (bytes[offset] |
22
+ (bytes[offset + 1] << 8) |
23
+ (bytes[offset + 2] << 16) |
24
+ (bytes[offset + 3] << 24)) >>> 0;
25
+ }
26
+ export function writeUint32(bytes, offset, value) {
27
+ bytes[offset] = value & 0xff;
28
+ bytes[offset + 1] = (value >>> 8) & 0xff;
29
+ bytes[offset + 2] = (value >>> 16) & 0xff;
30
+ bytes[offset + 3] = (value >>> 24) & 0xff;
31
+ }
32
+ export function readBigUint64(bytes, offset) {
33
+ let value = 0n;
34
+ for (let i = 7; i >= 0; i--) {
35
+ value = (value << 8n) | BigInt(bytes[offset + i]);
36
+ }
37
+ return value;
38
+ }
39
+ export function writeBigUint64(bytes, offset, value) {
40
+ for (let i = 0; i < 8; i++) {
41
+ bytes[offset + i] = Number((value >> BigInt(i * 8)) & 0xffn);
42
+ }
43
+ }
@@ -0,0 +1,8 @@
1
+ // src/constants.ts
2
+ export const PAGE_SIZE = 4096;
3
+ export const RECORD_HEADER_SIZE = 16;
4
+ export const MAX_INLINE_VALUE_SIZE = PAGE_SIZE - RECORD_HEADER_SIZE - 1024;
5
+ export const RECORD_ACTIVE = 1;
6
+ export const RECORD_FREE = 0;
7
+ export const OP_PUT = 1;
8
+ export const OP_DELETE = 2;
@@ -0,0 +1,15 @@
1
+ const CRC_TABLE = new Uint32Array(256);
2
+ for (let i = 0; i < 256; i++) {
3
+ let value = i;
4
+ for (let bit = 0; bit < 8; bit++) {
5
+ value = value & 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
6
+ }
7
+ CRC_TABLE[i] = value >>> 0;
8
+ }
9
+ export function crc32(bytes, start = 0, end = bytes.length) {
10
+ let crc = 0xffffffff;
11
+ for (let i = start; i < end; i++) {
12
+ crc = CRC_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
13
+ }
14
+ return (crc ^ 0xffffffff) >>> 0;
15
+ }