@tinyshed/tinystore 0.1.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +262 -0
  3. package/bin/tinystore.js +50 -0
  4. package/dist/background.d.ts +30 -0
  5. package/dist/background.js +93 -0
  6. package/dist/blobs.d.ts +98 -0
  7. package/dist/blobs.js +299 -0
  8. package/dist/cancel.d.ts +14 -0
  9. package/dist/cancel.js +22 -0
  10. package/dist/clock.d.ts +21 -0
  11. package/dist/clock.js +35 -0
  12. package/dist/config.d.ts +60 -0
  13. package/dist/config.js +417 -0
  14. package/dist/connection.d.ts +78 -0
  15. package/dist/connection.js +405 -0
  16. package/dist/console.d.ts +48 -0
  17. package/dist/console.js +195 -0
  18. package/dist/errors.d.ts +103 -0
  19. package/dist/errors.js +158 -0
  20. package/dist/handles.d.ts +28 -0
  21. package/dist/handles.js +37 -0
  22. package/dist/index.d.ts +21 -0
  23. package/dist/index.js +7 -0
  24. package/dist/jobs.d.ts +304 -0
  25. package/dist/jobs.js +684 -0
  26. package/dist/kv.d.ts +283 -0
  27. package/dist/kv.js +815 -0
  28. package/dist/limiter.d.ts +45 -0
  29. package/dist/limiter.js +68 -0
  30. package/dist/logger.d.ts +96 -0
  31. package/dist/logger.js +243 -0
  32. package/dist/metrics.d.ts +249 -0
  33. package/dist/metrics.js +610 -0
  34. package/dist/once.d.ts +31 -0
  35. package/dist/once.js +116 -0
  36. package/dist/quota.d.ts +44 -0
  37. package/dist/quota.js +98 -0
  38. package/dist/records.d.ts +182 -0
  39. package/dist/records.js +346 -0
  40. package/dist/runtime/bun.d.ts +2 -0
  41. package/dist/runtime/bun.js +164 -0
  42. package/dist/runtime/node.d.ts +2 -0
  43. package/dist/runtime/node.js +157 -0
  44. package/dist/runtime/shared.d.ts +25 -0
  45. package/dist/runtime/shared.js +45 -0
  46. package/dist/runtime.d.ts +48 -0
  47. package/dist/runtime.js +4 -0
  48. package/dist/schema.d.ts +39 -0
  49. package/dist/schema.js +21 -0
  50. package/dist/session.d.ts +120 -0
  51. package/dist/session.js +546 -0
  52. package/dist/sql.d.ts +121 -0
  53. package/dist/sql.js +342 -0
  54. package/dist/store.d.ts +103 -0
  55. package/dist/store.js +153 -0
  56. package/dist/time.d.ts +35 -0
  57. package/dist/time.js +44 -0
  58. package/dist/trace.d.ts +18 -0
  59. package/dist/trace.js +22 -0
  60. package/dist/wire/codec.d.ts +90 -0
  61. package/dist/wire/codec.js +383 -0
  62. package/dist/wire/frame.d.ts +41 -0
  63. package/dist/wire/frame.js +102 -0
  64. package/dist/wire/messages.d.ts +1403 -0
  65. package/dist/wire/messages.js +472 -0
  66. package/dist/wire/msgpack.d.ts +93 -0
  67. package/dist/wire/msgpack.js +680 -0
  68. package/package.json +40 -0
  69. package/src/background.ts +108 -0
  70. package/src/blobs.ts +437 -0
  71. package/src/cancel.ts +26 -0
  72. package/src/clock.ts +45 -0
  73. package/src/config.ts +501 -0
  74. package/src/connection.ts +512 -0
  75. package/src/console.ts +228 -0
  76. package/src/errors.ts +211 -0
  77. package/src/handles.ts +68 -0
  78. package/src/index.ts +92 -0
  79. package/src/jobs.ts +963 -0
  80. package/src/kv.ts +1093 -0
  81. package/src/limiter.ts +99 -0
  82. package/src/logger.ts +326 -0
  83. package/src/metrics.ts +896 -0
  84. package/src/once.ts +142 -0
  85. package/src/quota.ts +137 -0
  86. package/src/records.ts +537 -0
  87. package/src/runtime/bun.ts +190 -0
  88. package/src/runtime/node.ts +177 -0
  89. package/src/runtime/shared.ts +61 -0
  90. package/src/runtime.ts +57 -0
  91. package/src/schema.ts +69 -0
  92. package/src/session.ts +665 -0
  93. package/src/sql.ts +478 -0
  94. package/src/store.ts +219 -0
  95. package/src/time.ts +87 -0
  96. package/src/trace.ts +32 -0
  97. package/src/wire/codec.ts +445 -0
  98. package/src/wire/frame.ts +139 -0
  99. package/src/wire/messages.ts +562 -0
  100. package/src/wire/msgpack.ts +712 -0
package/dist/kv.js ADDED
@@ -0,0 +1,815 @@
1
+ // The application's current state in kv.db, as Go's kv package keeps it:
2
+ // buckets of one value type by key, keys in branches, expiry by the store's
3
+ // clock, versions that never repeat. A handle opens with its first call.
4
+ import { Config } from './config.js';
5
+ import { ConflictError, CorruptError, InvalidError } from './errors.js';
6
+ import { checkName, handleOn, ownerText, settle } from './handles.js';
7
+ import { Limiter, limiterOpen } from './limiter.js';
8
+ import { Once } from './once.js';
9
+ import { Quota, quotaOpen } from './quota.js';
10
+ import { check, isSchema } from './schema.js';
11
+ import { dateOf, ms, unixMs } from './time.js';
12
+ import { textOf } from './wire/codec.js';
13
+ import { KvBucket, KvCall, KvCalls, KvEntry, KvPage, KvResults, methods } from './wire/messages.js';
14
+ export class Kv {
15
+ #link;
16
+ #configs = new Set();
17
+ constructor(link) {
18
+ this.#link = link;
19
+ }
20
+ /**
21
+ * The config name, shaped and typed as its defaults: then a file's values,
22
+ * then the environment, then what update kept, each over the one before.
23
+ * It resolves once the server's state is read, and follows every change
24
+ * from then on, whoever makes it, until the store closes.
25
+ *
26
+ * ```ts
27
+ * const cfg = await store.kv.config('app', { port: 8080, origins: ['localhost'] })
28
+ * cfg.value.port // PORT=3000 in .env makes it 3000
29
+ * await cfg.update({ port: 4000 }) // kept: 4000 after a restart too
30
+ * ```
31
+ */
32
+ async config(name, defaults, options = {}) {
33
+ const config = new Config(this.#link, name, defaults, options);
34
+ this.#configs.add(config);
35
+ try {
36
+ await config.start();
37
+ }
38
+ catch (err) {
39
+ this.#configs.delete(config);
40
+ throw err;
41
+ }
42
+ return config;
43
+ }
44
+ /** A limiter of requests by key: `store.kv.limiter('api', { rate: '100/s', burst: 20 })`. */
45
+ limiter(name, options) {
46
+ return new Limiter(this.#link, name, limiterOpen(name, options), []);
47
+ }
48
+ /**
49
+ * A quota of uses by key, its windows by name, each counted from a key's
50
+ * first use and all of them together or none:
51
+ * `store.kv.quota('ai', { session: '100/5h', weekly: '300/7d' })`.
52
+ */
53
+ quota(name, windows) {
54
+ return new Quota(this.#link, name, quotaOpen(name, windows), []);
55
+ }
56
+ once(name, of, options) {
57
+ checkName(name, 'once');
58
+ let values = jsonValues;
59
+ if (isSchema(of)) {
60
+ values = schemaValues(of);
61
+ }
62
+ else if (of !== undefined) {
63
+ options = of;
64
+ }
65
+ const open = KvBucket.encode({
66
+ name,
67
+ once: true,
68
+ defaultTtl: options?.defaultTtl === undefined ? undefined : ms(options.defaultTtl),
69
+ });
70
+ return new Once(this.#link, name, open, values, []);
71
+ }
72
+ /** Stops following configs, as the store does when it closes. */
73
+ stop() {
74
+ for (const config of this.#configs) {
75
+ config.stop();
76
+ }
77
+ }
78
+ bucket(name, of, options) {
79
+ checkName(name, 'bucket');
80
+ let values = jsonValues;
81
+ if (typeof of === 'string') {
82
+ values = valuesOf(of);
83
+ }
84
+ else if (isSchema(of)) {
85
+ values = schemaValues(of);
86
+ }
87
+ else if (of !== undefined) {
88
+ options = of;
89
+ }
90
+ if (options?.defaultTtl !== undefined && options.sliding !== undefined) {
91
+ throw new InvalidError(`bucket ${name}: sliding and defaultTtl are one or the other`);
92
+ }
93
+ const open = KvBucket.encode({
94
+ name,
95
+ defaultTtl: options?.defaultTtl === undefined ? undefined : ms(options.defaultTtl),
96
+ sliding: options?.sliding === undefined ? undefined : ms(options.sliding),
97
+ });
98
+ return new Bucket(this.#link, name, open, values, []);
99
+ }
100
+ counters(name, of, options) {
101
+ checkName(name, 'counters');
102
+ const big = of === 'bigint';
103
+ if (typeof of === 'object') {
104
+ options = of;
105
+ }
106
+ const open = KvBucket.encode({
107
+ name,
108
+ counters: true,
109
+ defaultTtl: options?.defaultTtl === undefined ? undefined : ms(options.defaultTtl),
110
+ loseAtMost: options?.loseAtMost === undefined ? undefined : ms(options.loseAtMost),
111
+ });
112
+ return new Counters(this.#link, name, open, big, []);
113
+ }
114
+ /**
115
+ * Runs the calls fn asks for in one transaction, all or none: the calls of
116
+ * buckets it takes through withTx, whose promises settle once the batch
117
+ * has. fn returns before anything is sent, since no transaction is held
118
+ * across the network: a call cannot wait for another's answer inside it.
119
+ * What fn returns comes back answered, an array's promises each:
120
+ *
121
+ * const [code] = await store.kv.batch(tx => [codes.withTx(tx).take(k), used.withTx(tx).set(k, 1)])
122
+ */
123
+ batch(fn) {
124
+ return runCalls(this.#link, 'batch', fn);
125
+ }
126
+ /**
127
+ * Reads the gets and hases fn asks for from one snapshot, and gives back
128
+ * what fn returns, answered as batch answers it:
129
+ *
130
+ * const [profile, prefs] = await store.kv.view(tx => [a.withTx(tx).get(id), b.withTx(tx).get(id)])
131
+ */
132
+ view(fn) {
133
+ return runCalls(this.#link, 'view', fn);
134
+ }
135
+ /**
136
+ * Runs fn as one transaction that reads before it decides what to write,
137
+ * as Go's Tx does, without holding the writer across the network: a read
138
+ * goes to the server at once, a write waits, and when fn returns the writes
139
+ * commit in one batch that first checks every key fn read is still as it
140
+ * read it. When another write changed one meanwhile, fn runs again, five
141
+ * times at most before ConflictError, so it does nothing else that must
142
+ * happen once. It gives back what fn returns.
143
+ *
144
+ * const userId = await store.kv.tx(async tx => {
145
+ * const userId = await codes.withTx(tx).take(digest(code))
146
+ * if (userId === undefined) throw new InvalidCode()
147
+ * sessions.withTx(tx).of(userId).set(digest(token), { device })
148
+ * return userId
149
+ * })
150
+ */
151
+ async tx(fn) {
152
+ for (let run = 1;; run++) {
153
+ const tx = new Tx(this.#link);
154
+ const returned = await fn(tx);
155
+ try {
156
+ await tx.commit();
157
+ return returned;
158
+ }
159
+ catch (err) {
160
+ if (run >= txRuns || !tx.stale(err)) {
161
+ throw err;
162
+ }
163
+ }
164
+ }
165
+ }
166
+ }
167
+ /** How many times tx runs its function before a key it read that keeps changing is ConflictError. */
168
+ const txRuns = 5;
169
+ /** The calls a batch or a view gathered, in their order. */
170
+ export class Batch {
171
+ kind;
172
+ calls = [];
173
+ #done = false;
174
+ #made = new WeakSet();
175
+ constructor(kind) {
176
+ this.kind = kind;
177
+ }
178
+ /** Whether the promise is one of this batch's calls', rather than an async function's. */
179
+ made(promise) {
180
+ return this.#made.has(promise);
181
+ }
182
+ record(call, settle) {
183
+ if (this.#done) {
184
+ throw new InvalidError(`a ${this.kind} takes its calls while its function runs, before it is sent`);
185
+ }
186
+ if (this.kind === 'view' && call.method !== 'kv.get' && call.method !== 'kv.has') {
187
+ throw new InvalidError(`${call.method} in a view, which reads`);
188
+ }
189
+ let resolve;
190
+ let reject;
191
+ const settled = new Promise((res, rej) => {
192
+ resolve = res;
193
+ reject = rej;
194
+ });
195
+ // a caller need not await a call it only wanted done
196
+ settled.catch(() => { });
197
+ this.#made.add(settled);
198
+ this.calls.push({
199
+ ...call,
200
+ settle: async (entry) => {
201
+ try {
202
+ resolve(await settle(entry));
203
+ }
204
+ catch (err) {
205
+ reject(err);
206
+ }
207
+ },
208
+ fail: reject,
209
+ });
210
+ return settled;
211
+ }
212
+ close() {
213
+ this.#done = true;
214
+ }
215
+ }
216
+ const absent = { found: false, value: null, version: '', expires: undefined };
217
+ /**
218
+ * A transaction of store.kv.tx: a read goes to the server at once and is
219
+ * remembered with its version, so that a key read again answers the same; a
220
+ * write waits for the commit, and a key read after it answers what it wrote.
221
+ */
222
+ export class Tx {
223
+ #link;
224
+ #reads = new Map();
225
+ #writes = new Map();
226
+ #checks = 0;
227
+ #done = false;
228
+ constructor(link) {
229
+ this.#link = link;
230
+ }
231
+ record(call, settle) {
232
+ if (this.#done) {
233
+ throw new InvalidError('a tx takes its calls while its function runs, before it commits');
234
+ }
235
+ const at = placeOf(call);
236
+ switch (call.method) {
237
+ case 'kv.get':
238
+ case 'kv.has':
239
+ return this.#read(at, call).then(settle);
240
+ case 'kv.take': {
241
+ const read = this.#read(at, call);
242
+ this.#writes.set(at, { call: { ...call, method: 'kv.delete' }, entry: absent });
243
+ return read.then(settle);
244
+ }
245
+ case 'kv.set': {
246
+ // a set's value is what the bucket encoded, which a read decodes
247
+ const value = (call.call.value ?? null);
248
+ const entry = { found: true, value, version: '', expires: undefined };
249
+ this.#writes.set(at, { call, entry });
250
+ return settle(entry);
251
+ }
252
+ case 'kv.delete':
253
+ this.#writes.set(at, { call, entry: absent });
254
+ return settle(absent);
255
+ }
256
+ throw new InvalidError(`${call.method} in a tx`);
257
+ }
258
+ #read(at, call) {
259
+ const written = this.#writes.get(at);
260
+ if (written !== undefined) {
261
+ return Promise.resolve(written.entry);
262
+ }
263
+ let reading = this.#reads.get(at);
264
+ if (reading === undefined) {
265
+ reading = this.#fetch(call);
266
+ // a read fn never awaited still fails the commit, which awaits it
267
+ reading.catch(() => { });
268
+ this.#reads.set(at, reading);
269
+ }
270
+ return reading.then(read => read.entry);
271
+ }
272
+ async #fetch(call) {
273
+ const ask = { owners: call.call.owners, key: call.call.key };
274
+ const e = await this.#link.run('read', async (connection) => {
275
+ const handle = await handleOn(connection, methods['kv.open'], call.open);
276
+ const body = await connection.session.call(methods['kv.get'], KvCall.encode({ ...ask, handle }));
277
+ return KvEntry.decode(body);
278
+ });
279
+ return {
280
+ call: { method: 'kv.get', open: call.open, call: ask },
281
+ version: e.version,
282
+ entry: entryOfWire(e),
283
+ };
284
+ }
285
+ /**
286
+ * Sends what fn wrote in one batch, after a check of each key it read: a
287
+ * key it found at the version it found, a key it found absent still
288
+ * absent. A tx that only read checks its reads from one snapshot.
289
+ */
290
+ async commit() {
291
+ this.#done = true;
292
+ const calls = [];
293
+ for (const reading of this.#reads.values()) {
294
+ const read = await reading;
295
+ const still = read.entry.found ? { ifVersion: read.version } : { ifAbsent: true };
296
+ calls.push({ ...read.call, call: { ...read.call.call, ...still } });
297
+ }
298
+ this.#checks = calls.length;
299
+ for (const write of this.#writes.values()) {
300
+ calls.push(write.call);
301
+ }
302
+ if (calls.length === 0) {
303
+ return;
304
+ }
305
+ const writes = this.#writes.size > 0;
306
+ await this.#link.run(writes ? 'write' : 'read', async (connection) => {
307
+ const encoded = [];
308
+ for (const call of calls) {
309
+ const handle = await handleOn(connection, methods['kv.open'], call.open);
310
+ encoded.push({ method: methods[call.method], ...call.call, handle });
311
+ }
312
+ const method = writes ? methods['kv.batch'] : methods['kv.view'];
313
+ await connection.session.call(method, KvCalls.encode({ calls: encoded }));
314
+ });
315
+ }
316
+ /** Whether the commit failed for a key fn read that changed since, which another run reads anew. */
317
+ stale(err) {
318
+ return err instanceof ConflictError && Number(err.what.call) < this.#checks;
319
+ }
320
+ }
321
+ /**
322
+ * A key's place as one text: its bucket's open and its owners included, an
323
+ * integer its decimal spelling, as the store keeps it.
324
+ */
325
+ function placeOf(call) {
326
+ const part = (p) => p instanceof Uint8Array ? `b${Buffer.from(p).toString('base64')}` : `t${String(p ?? '')}`;
327
+ const owners = call.call.owners ?? [];
328
+ return [Buffer.from(call.open).toString('base64'), ...owners.map(part), part(call.call.key)].join('\u0000');
329
+ }
330
+ async function runCalls(link, kind, fn) {
331
+ const tx = new Batch(kind);
332
+ const returned = fn(tx);
333
+ tx.close();
334
+ if (returned instanceof Promise && !tx.made(returned)) {
335
+ throw new InvalidError(`a ${kind}'s function returns before anything is sent; it cannot await inside`);
336
+ }
337
+ if (tx.calls.length > 0) {
338
+ await sendCalls(link, kind, tx);
339
+ }
340
+ return settle(returned);
341
+ }
342
+ async function sendCalls(link, kind, tx) {
343
+ try {
344
+ const results = await link.run(kind === 'view' ? 'read' : 'write', async (connection) => {
345
+ const calls = [];
346
+ for (const call of tx.calls) {
347
+ const handle = await handleOn(connection, methods['kv.open'], call.open);
348
+ calls.push({ method: methods[call.method], ...call.call, handle });
349
+ }
350
+ const body = await connection.session.call(methods[`kv.${kind}`], KvCalls.encode({ calls }));
351
+ return KvResults.decode(body).entries ?? [];
352
+ });
353
+ await Promise.all(tx.calls.map((call, i) => call.settle(entryOfWire(results[i] ?? {}))));
354
+ }
355
+ catch (err) {
356
+ for (const call of tx.calls) {
357
+ call.fail?.(err);
358
+ }
359
+ throw err;
360
+ }
361
+ }
362
+ function entryOfWire(e) {
363
+ return {
364
+ found: e.found ?? false,
365
+ value: e.value ?? null,
366
+ version: versionText(e.version),
367
+ expires: dateOf(e.expires),
368
+ };
369
+ }
370
+ /** A version's bytes as text, each byte a code unit, so that any bytes go back as they came. */
371
+ function versionText(version) {
372
+ return version === undefined ? '' : String.fromCharCode(...version);
373
+ }
374
+ function versionBytes(version) {
375
+ return Uint8Array.from(version, c => c.charCodeAt(0));
376
+ }
377
+ function writeFields(options) {
378
+ return {
379
+ ttl: options?.ttl === undefined ? undefined : ms(options.ttl),
380
+ expireAt: options?.expireAt === undefined ? undefined : unixMs(options.expireAt),
381
+ ifVersion: options?.ifVersion === undefined ? undefined : versionBytes(options.ifVersion),
382
+ };
383
+ }
384
+ /**
385
+ * A bucket's values under one branch of owners, the root when there are
386
+ * none: `sessions.of(user.id).get(token)`.
387
+ */
388
+ export class Bucket {
389
+ name;
390
+ #link;
391
+ #open;
392
+ #values;
393
+ #owners;
394
+ constructor(link, name, open, values, owners) {
395
+ this.#link = link;
396
+ this.name = name;
397
+ this.#open = open;
398
+ this.#values = values;
399
+ this.#owners = owners;
400
+ }
401
+ /** The branch below this one that the owners name. */
402
+ of(...owners) {
403
+ return new Bucket(this.#link, this.name, this.#open, this.#values, [
404
+ ...this.#owners,
405
+ ...owners.map(ownerText),
406
+ ]);
407
+ }
408
+ /**
409
+ * The bucket's calls inside a batch or a view, whose promises settle with
410
+ * it, or inside a tx, whose reads answer at once and writes wait for it.
411
+ */
412
+ withTx(tx) {
413
+ return new BucketTx(tx, this.#open, this.#values, this.#owners);
414
+ }
415
+ async #call(method, fields, idempotence) {
416
+ return this.#link.run(idempotence, async (connection) => {
417
+ const handle = await handleOn(connection, methods['kv.open'], this.#open);
418
+ const body = KvCall.encode({
419
+ handle,
420
+ owners: this.#owners.length > 0 ? this.#owners : undefined,
421
+ ...fields,
422
+ });
423
+ return KvEntry.decode(await connection.session.call(methods[method], body));
424
+ });
425
+ }
426
+ /** The key's value, undefined when it holds none. */
427
+ async get(key) {
428
+ const entry = await this.getEntry(key);
429
+ return entry?.value;
430
+ }
431
+ /** The key's value with its version and expiry, undefined when it holds none. */
432
+ async getEntry(key) {
433
+ const e = await this.#call('kv.get', { key }, 'read');
434
+ if (e.found !== true) {
435
+ return undefined;
436
+ }
437
+ return {
438
+ value: await this.#values.decode(e.value ?? null),
439
+ version: versionText(e.version),
440
+ expires: dateOf(e.expires),
441
+ };
442
+ }
443
+ async has(key) {
444
+ return (await this.#call('kv.has', { key }, 'read')).found === true;
445
+ }
446
+ /** Writes the value; a live key keeps its expiry unless the options give one. */
447
+ async set(key, value, options) {
448
+ await this.setEntry(key, value, options);
449
+ }
450
+ /** Writes the value and gives its new version and expiry. */
451
+ async setEntry(key, value, options) {
452
+ const raw = await this.#values.encode(value);
453
+ const e = await this.#call('kv.set', { key, value: raw, ...writeFields(options) }, 'write');
454
+ return { value, version: versionText(e.version), expires: dateOf(e.expires) };
455
+ }
456
+ /** Writes the value only where no live key is, and says whether it did. */
457
+ async setIfAbsent(key, value, options) {
458
+ return (await this.setEntryIfAbsent(key, value, options)).created;
459
+ }
460
+ /**
461
+ * Writes the value only where no live key is: created says whether it did,
462
+ * and entry is the new key's, or the live one's that was there.
463
+ */
464
+ async setEntryIfAbsent(key, value, options) {
465
+ const raw = await this.#values.encode(value);
466
+ const e = await this.#call('kv.set', { key, value: raw, ifAbsent: true, ...writeFields(options) }, 'write');
467
+ const created = e.found === true;
468
+ return {
469
+ created,
470
+ entry: {
471
+ value: created ? value : await this.#values.decode(e.value ?? null),
472
+ version: versionText(e.version),
473
+ expires: dateOf(e.expires),
474
+ },
475
+ };
476
+ }
477
+ async delete(key, options) {
478
+ await this.#call('kv.delete', { key, ...writeFields(options) }, 'write');
479
+ }
480
+ /**
481
+ * Reads the value and deletes the key in one write: a one-time code read
482
+ * and burned. A value that no longer decodes has been taken all the same.
483
+ */
484
+ async take(key, options) {
485
+ const e = await this.#call('kv.take', { key, ...writeFields(options) }, 'write');
486
+ return e.found === true ? this.#values.decode(e.value ?? null) : undefined;
487
+ }
488
+ /** Gives a live key a new expiry, keeping its value and version; false when it holds none. */
489
+ async touch(key, options) {
490
+ return (await this.#call('kv.touch', { key, ...writeFields(options) }, 'write')).found === true;
491
+ }
492
+ /** Removes this branch's keys and every branch under it, at once however many. */
493
+ async clear() {
494
+ await this.#call('kv.clear', {}, 'write');
495
+ }
496
+ /** One page of this branch's own keys, in the byte order of their text. */
497
+ async scan(options) {
498
+ const { items, page } = await this.#link.run('read', async (connection) => {
499
+ const handle = await handleOn(connection, methods['kv.open'], this.#open);
500
+ const stream = await connection.session.open(methods['kv.scan'], KvCall.encode({
501
+ handle,
502
+ owners: this.#owners.length > 0 ? this.#owners : undefined,
503
+ after: options?.after,
504
+ limit: options?.limit,
505
+ }), true);
506
+ const items = [];
507
+ for (;;) {
508
+ const event = await stream.next();
509
+ if (event.kind === 'response') {
510
+ continue;
511
+ }
512
+ stream.consumed(event.body.length);
513
+ if (event.end) {
514
+ return { items, page: KvPage.decode(event.body) };
515
+ }
516
+ items.push(KvEntry.decode(event.body));
517
+ }
518
+ });
519
+ const decoded = [];
520
+ for (const e of items) {
521
+ decoded.push({
522
+ key: e.key ?? '',
523
+ value: await this.#values.decode(e.value ?? null),
524
+ version: versionText(e.version),
525
+ expires: dateOf(e.expires),
526
+ });
527
+ }
528
+ return { items: decoded, next: page.more === true ? (page.after ?? '') : undefined };
529
+ }
530
+ /**
531
+ * Walks this branch's own keys a page at a time, holding no snapshot
532
+ * between pages: a key written during the walk may or may not be met.
533
+ */
534
+ async *all(options) {
535
+ let after;
536
+ for (;;) {
537
+ const page = await this.scan({ ...(after === undefined ? {} : { after }), ...options });
538
+ yield* page.items;
539
+ if (page.next === undefined) {
540
+ return;
541
+ }
542
+ after = page.next;
543
+ }
544
+ }
545
+ }
546
+ /** A bucket's calls inside a batch or a view. */
547
+ export class BucketTx {
548
+ #tx;
549
+ #open;
550
+ #values;
551
+ #owners;
552
+ constructor(tx, open, values, owners) {
553
+ this.#tx = tx;
554
+ this.#open = open;
555
+ this.#values = values;
556
+ this.#owners = owners;
557
+ }
558
+ of(...owners) {
559
+ return new BucketTx(this.#tx, this.#open, this.#values, [
560
+ ...this.#owners,
561
+ ...owners.map(ownerText),
562
+ ]);
563
+ }
564
+ #record(method, fields, settle) {
565
+ const owners = this.#owners.length > 0 ? this.#owners : undefined;
566
+ return this.#tx.record({ method, open: this.#open, call: { owners, ...fields } }, settle);
567
+ }
568
+ get(key) {
569
+ return this.#record('kv.get', { key }, async (e) => e.found ? this.#values.decode(e.value) : undefined);
570
+ }
571
+ has(key) {
572
+ return this.#record('kv.has', { key }, async (e) => e.found);
573
+ }
574
+ set(key, value, options) {
575
+ return this.#record('kv.set', { key, value: this.#encodeNow(value), ...writeFields(options) }, async () => { });
576
+ }
577
+ delete(key, options) {
578
+ return this.#record('kv.delete', { key, ...writeFields(options) }, async () => { });
579
+ }
580
+ take(key) {
581
+ return this.#record('kv.take', { key }, async (e) => e.found ? this.#values.decode(e.value) : undefined);
582
+ }
583
+ // a batch is sent once its function returns, so a value is encoded as it is given
584
+ #encodeNow(value) {
585
+ const raw = this.#values.encode(value);
586
+ if (raw instanceof Promise) {
587
+ throw new InvalidError('a bucket whose values encode asynchronously takes no batch');
588
+ }
589
+ return raw;
590
+ }
591
+ }
592
+ /**
593
+ * Counters under one branch: an int64 a key, 0 when absent, which add and
594
+ * max change in one write; a sum past the int64 range is refused.
595
+ */
596
+ export class Counters {
597
+ name;
598
+ #link;
599
+ #open;
600
+ #big;
601
+ #owners;
602
+ constructor(link, name, open, big, owners) {
603
+ this.#link = link;
604
+ this.name = name;
605
+ this.#open = open;
606
+ this.#big = big;
607
+ this.#owners = owners;
608
+ }
609
+ of(...owners) {
610
+ return new Counters(this.#link, this.name, this.#open, this.#big, [
611
+ ...this.#owners,
612
+ ...owners.map(ownerText),
613
+ ]);
614
+ }
615
+ async #call(method, key, n) {
616
+ const e = await this.#link.run(method === 'kv.get' ? 'read' : 'write', async (connection) => {
617
+ const handle = await handleOn(connection, methods['kv.open'], this.#open);
618
+ const body = KvCall.encode({
619
+ handle,
620
+ owners: this.#owners.length > 0 ? this.#owners : undefined,
621
+ key,
622
+ n,
623
+ });
624
+ return KvEntry.decode(await connection.session.call(methods[method], body));
625
+ });
626
+ const value = typeof e.value === 'bigint' ? e.value : 0n;
627
+ return (this.#big ? value : numberOf(value, this.name));
628
+ }
629
+ get(key) {
630
+ return this.#call('kv.get', key);
631
+ }
632
+ /** Adds n, 1 unless given, and gives the new value. */
633
+ add(key, n = 1) {
634
+ return this.#call('kv.add', key, n);
635
+ }
636
+ /** Keeps the larger of the counter and n, and gives it. */
637
+ max(key, n) {
638
+ return this.#call('kv.max', key, n);
639
+ }
640
+ async delete(key) {
641
+ await this.#call('kv.delete', key);
642
+ }
643
+ async clear() {
644
+ await this.#call('kv.clear', undefined);
645
+ }
646
+ }
647
+ function numberOf(n, bucket) {
648
+ if (n > BigInt(Number.MAX_SAFE_INTEGER) || n < BigInt(Number.MIN_SAFE_INTEGER)) {
649
+ throw new CorruptError(`${n} does not fit a number exactly: open counters ${bucket} as 'bigint'`, { bucket });
650
+ }
651
+ return Number(n);
652
+ }
653
+ const utf8 = new TextEncoder();
654
+ const jsonValues = {
655
+ encode: value => {
656
+ let text;
657
+ try {
658
+ text = JSON.stringify(value);
659
+ }
660
+ catch (err) {
661
+ throw new InvalidError(`a value JSON cannot write: ${err.message}`);
662
+ }
663
+ if (text === undefined) {
664
+ throw new InvalidError('a value JSON cannot write: undefined, a function or a symbol');
665
+ }
666
+ return utf8.encode(text);
667
+ },
668
+ decode: raw => {
669
+ if (!(raw instanceof Uint8Array)) {
670
+ throw new CorruptError(`a stored value is ${describe(raw)} where JSON was written`);
671
+ }
672
+ const text = textOf(raw);
673
+ try {
674
+ return JSON.parse(text ?? '');
675
+ }
676
+ catch (err) {
677
+ throw new CorruptError(`a stored value is not JSON any more: ${err.message}`);
678
+ }
679
+ },
680
+ };
681
+ function schemaValues(schema) {
682
+ return {
683
+ encode: jsonValues.encode,
684
+ decode: async (raw) => {
685
+ const checked = await check(schema, await jsonValues.decode(raw));
686
+ if ('issues' in checked) {
687
+ throw new CorruptError(`a stored value does not meet the bucket's schema: ${checked.issues}`);
688
+ }
689
+ return checked.value;
690
+ },
691
+ };
692
+ }
693
+ function valuesOf(kind) {
694
+ switch (kind) {
695
+ case 'json':
696
+ return jsonValues;
697
+ case 'string':
698
+ return {
699
+ encode: v => {
700
+ if (typeof v !== 'string') {
701
+ throw new InvalidError(`a ${typeof v} in a bucket of strings`);
702
+ }
703
+ return utf8.encode(v);
704
+ },
705
+ decode: raw => {
706
+ const text = raw === null ? '' : raw instanceof Uint8Array ? textOf(raw) : undefined;
707
+ if (text === undefined) {
708
+ throw new CorruptError(`a stored value is ${describe(raw)}, which is no UTF-8 string`);
709
+ }
710
+ return text;
711
+ },
712
+ };
713
+ case 'bytes':
714
+ return {
715
+ encode: v => {
716
+ if (!(v instanceof Uint8Array)) {
717
+ throw new InvalidError(`a ${typeof v} in a bucket of bytes`);
718
+ }
719
+ return v;
720
+ },
721
+ decode: raw => {
722
+ if (raw !== null && !(raw instanceof Uint8Array)) {
723
+ throw new CorruptError(`a stored value is ${describe(raw)} where bytes were written`);
724
+ }
725
+ return raw ?? new Uint8Array(0);
726
+ },
727
+ };
728
+ case 'int':
729
+ return {
730
+ encode: v => {
731
+ if (typeof v !== 'number' || !Number.isSafeInteger(v)) {
732
+ throw new InvalidError(`${String(v)} is not an integer a number holds exactly; open the bucket as 'bigint'`);
733
+ }
734
+ return BigInt(v);
735
+ },
736
+ decode: raw => {
737
+ if (typeof raw !== 'bigint') {
738
+ throw new CorruptError(`a stored value is ${describe(raw)} where an integer was written`);
739
+ }
740
+ if (raw > BigInt(Number.MAX_SAFE_INTEGER) || raw < BigInt(Number.MIN_SAFE_INTEGER)) {
741
+ throw new CorruptError(`${raw} does not fit a number exactly; open the bucket as 'bigint'`);
742
+ }
743
+ return Number(raw);
744
+ },
745
+ };
746
+ case 'bigint':
747
+ return {
748
+ encode: v => {
749
+ if (typeof v !== 'bigint' && !(typeof v === 'number' && Number.isSafeInteger(v))) {
750
+ throw new InvalidError(`${String(v)} is not an integer`);
751
+ }
752
+ return BigInt(v);
753
+ },
754
+ decode: raw => {
755
+ if (typeof raw !== 'bigint') {
756
+ throw new CorruptError(`a stored value is ${describe(raw)} where an integer was written`);
757
+ }
758
+ return raw;
759
+ },
760
+ };
761
+ case 'float':
762
+ return {
763
+ encode: v => {
764
+ if (typeof v !== 'number') {
765
+ throw new InvalidError(`a ${typeof v} in a bucket of floats`);
766
+ }
767
+ const bytes = new Uint8Array(8);
768
+ new DataView(bytes.buffer).setFloat64(0, v);
769
+ return bytes;
770
+ },
771
+ decode: raw => {
772
+ if (!(raw instanceof Uint8Array) || raw.length !== 8) {
773
+ throw new CorruptError(`a stored value is ${describe(raw)} where a float's eight bytes were written`);
774
+ }
775
+ return new DataView(raw.buffer, raw.byteOffset, 8).getFloat64(0);
776
+ },
777
+ };
778
+ case 'bool':
779
+ return {
780
+ encode: v => {
781
+ if (typeof v !== 'boolean') {
782
+ throw new InvalidError(`a ${typeof v} in a bucket of booleans`);
783
+ }
784
+ return v ? 1n : 0n;
785
+ },
786
+ decode: raw => {
787
+ if (typeof raw !== 'bigint') {
788
+ throw new CorruptError(`a stored value is ${describe(raw)} where a boolean was written`);
789
+ }
790
+ return raw !== 0n;
791
+ },
792
+ };
793
+ case 'none':
794
+ return {
795
+ encode: v => {
796
+ if (v !== null) {
797
+ throw new InvalidError('a bucket of none keeps no value: set null');
798
+ }
799
+ return null;
800
+ },
801
+ decode: raw => {
802
+ if (raw !== null) {
803
+ throw new CorruptError(`a stored value is ${describe(raw)} in a bucket that keeps none`);
804
+ }
805
+ return null;
806
+ },
807
+ };
808
+ }
809
+ }
810
+ function describe(raw) {
811
+ if (raw === null) {
812
+ return 'nothing';
813
+ }
814
+ return typeof raw === 'bigint' ? 'an integer' : `${raw.length} bytes`;
815
+ }