@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.d.ts ADDED
@@ -0,0 +1,283 @@
1
+ import { Config, type ConfigOptions } from './config.ts';
2
+ import type { Link } from './connection.ts';
3
+ import { type Page, type Settled } from './handles.ts';
4
+ import { Limiter, type LimiterOptions, type Rate } from './limiter.ts';
5
+ import { Once, type OnceOptions } from './once.ts';
6
+ import { Quota } from './quota.ts';
7
+ import { type StandardSchemaV1 } from './schema.ts';
8
+ import { type Duration, type Time } from './time.ts';
9
+ import { type Key, type Raw } from './wire/codec.ts';
10
+ import { KvCall, methods } from './wire/messages.ts';
11
+ /**
12
+ * How a bucket keeps its values in a row, as Go's codecFor keeps a type's,
13
+ * so that Go, Python and this SDK read each other's buckets:
14
+ *
15
+ * 'json' JSON text, the default a Go struct, a Python dataclass
16
+ * 'string' its UTF-8 bytes string, str
17
+ * 'bytes' the bytes []byte, bytes
18
+ * 'int' an integer, a number exactly int64, int
19
+ * 'bigint' an integer int64, int
20
+ * 'float' its eight bytes, big-endian float64, float
21
+ * 'bool' 1 or 0 bool, bool
22
+ * 'none' nothing: a bucket of them is a set struct{}, None
23
+ */
24
+ export type Kind = 'json' | 'string' | 'bytes' | 'int' | 'bigint' | 'float' | 'bool' | 'none';
25
+ interface KindValue {
26
+ json: unknown;
27
+ string: string;
28
+ bytes: Uint8Array;
29
+ int: number;
30
+ bigint: bigint;
31
+ float: number;
32
+ bool: boolean;
33
+ none: null;
34
+ }
35
+ export interface BucketOptions {
36
+ /** the expiry a key gets when it is written without its own */
37
+ defaultTtl?: Duration;
38
+ /** keeps a key this long from its last read; beside defaultTtl it is refused */
39
+ sliding?: Duration;
40
+ }
41
+ export interface CounterOptions {
42
+ defaultTtl?: Duration;
43
+ /**
44
+ * keeps changes in the server's memory between flushes this far apart, so
45
+ * a crash may lose them: attempts and rates, not money
46
+ */
47
+ loseAtMost?: Duration;
48
+ }
49
+ export interface WriteOptions {
50
+ ttl?: Duration;
51
+ expireAt?: Time;
52
+ /** writes only while the key is live at this version: ConflictError otherwise */
53
+ ifVersion?: string;
54
+ }
55
+ export interface Entry<V> {
56
+ value: V;
57
+ /** compared only for equality: give it back to ifVersion */
58
+ version: string;
59
+ /** when the key expires; undefined for one that never does */
60
+ expires: Date | undefined;
61
+ }
62
+ export interface Scanned<V> extends Entry<V> {
63
+ /** the key's text; bytes when it is not UTF-8 */
64
+ key: string | Uint8Array;
65
+ }
66
+ /** Encodes a bucket's values into what a row keeps, and back. */
67
+ export interface Values<V> {
68
+ encode(value: V): Raw | Promise<Raw>;
69
+ decode(raw: Raw): V | Promise<V>;
70
+ }
71
+ export declare class Kv {
72
+ #private;
73
+ constructor(link: Link);
74
+ /**
75
+ * The config name, shaped and typed as its defaults: then a file's values,
76
+ * then the environment, then what update kept, each over the one before.
77
+ * It resolves once the server's state is read, and follows every change
78
+ * from then on, whoever makes it, until the store closes.
79
+ *
80
+ * ```ts
81
+ * const cfg = await store.kv.config('app', { port: 8080, origins: ['localhost'] })
82
+ * cfg.value.port // PORT=3000 in .env makes it 3000
83
+ * await cfg.update({ port: 4000 }) // kept: 4000 after a restart too
84
+ * ```
85
+ */
86
+ config<T extends object>(name: string, defaults: T, options?: ConfigOptions<T>): Promise<Config<T>>;
87
+ /** A limiter of requests by key: `store.kv.limiter('api', { rate: '100/s', burst: 20 })`. */
88
+ limiter(name: string, options: LimiterOptions): Limiter;
89
+ /**
90
+ * A quota of uses by key, its windows by name, each counted from a key's
91
+ * first use and all of them together or none:
92
+ * `store.kv.quota('ai', { session: '100/5h', weekly: '300/7d' })`.
93
+ */
94
+ quota<W extends string>(name: string, windows: Record<W, Rate>): Quota<W>;
95
+ /**
96
+ * The answers a function gives once a key, JSON values of type T kept a
97
+ * day unless defaultTtl says: `store.kv.once<Receipt>('charges')`.
98
+ */
99
+ once<T = unknown>(name: string, options?: OnceOptions): Once<T>;
100
+ /** Answers each read is checked by, zod's, valibot's or another Standard Schema. */
101
+ once<S extends StandardSchemaV1>(name: string, schema: S, options?: OnceOptions): Once<StandardSchemaV1.InferOutput<S>>;
102
+ /** Stops following configs, as the store does when it closes. */
103
+ stop(): void;
104
+ /** A bucket of JSON values of type T. */
105
+ bucket<T = unknown>(name: string, options?: BucketOptions): Bucket<T>;
106
+ /** A bucket of values kept as their kind says. */
107
+ bucket<K extends Kind>(name: string, kind: K, options?: BucketOptions): Bucket<KindValue[K]>;
108
+ /** A bucket of JSON values each read is checked by, zod's, valibot's or another Standard Schema. */
109
+ bucket<S extends StandardSchemaV1>(name: string, schema: S, options?: BucketOptions): Bucket<StandardSchemaV1.InferOutput<S>>;
110
+ /** Counters, an int64 a key read as a number, 0 when absent. */
111
+ counters(name: string, options?: CounterOptions): Counters<number>;
112
+ /** Counters read as bigints, for values past 2^53. */
113
+ counters(name: string, kind: 'bigint', options?: CounterOptions): Counters<bigint>;
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<const T = void>(fn: (tx: Batch) => T): Promise<Settled<T>>;
124
+ /**
125
+ * Reads the gets and hases fn asks for from one snapshot, and gives back
126
+ * what fn returns, answered as batch answers it:
127
+ *
128
+ * const [profile, prefs] = await store.kv.view(tx => [a.withTx(tx).get(id), b.withTx(tx).get(id)])
129
+ */
130
+ view<const T = void>(fn: (tx: Batch) => T): Promise<Settled<T>>;
131
+ /**
132
+ * Runs fn as one transaction that reads before it decides what to write,
133
+ * as Go's Tx does, without holding the writer across the network: a read
134
+ * goes to the server at once, a write waits, and when fn returns the writes
135
+ * commit in one batch that first checks every key fn read is still as it
136
+ * read it. When another write changed one meanwhile, fn runs again, five
137
+ * times at most before ConflictError, so it does nothing else that must
138
+ * happen once. It gives back what fn returns.
139
+ *
140
+ * const userId = await store.kv.tx(async tx => {
141
+ * const userId = await codes.withTx(tx).take(digest(code))
142
+ * if (userId === undefined) throw new InvalidCode()
143
+ * sessions.withTx(tx).of(userId).set(digest(token), { device })
144
+ * return userId
145
+ * })
146
+ */
147
+ tx<T>(fn: (tx: Tx) => T | Promise<T>): Promise<T>;
148
+ }
149
+ /** The calls a batch or a view gathered, in their order. */
150
+ export declare class Batch {
151
+ #private;
152
+ readonly kind: 'batch' | 'view';
153
+ readonly calls: Recorded[];
154
+ constructor(kind: 'batch' | 'view');
155
+ /** Whether the promise is one of this batch's calls', rather than an async function's. */
156
+ made(promise: Promise<unknown>): boolean;
157
+ record<T>(call: Omit<Recorded, 'settle'>, settle: (entry: Entry<Raw> & {
158
+ found: boolean;
159
+ }) => Promise<T>): Promise<T>;
160
+ close(): void;
161
+ }
162
+ interface Recorded {
163
+ method: keyof typeof methods;
164
+ open: Uint8Array;
165
+ call: Parameters<typeof KvCall.encode>[0];
166
+ settle: (entry: Entry<Raw> & {
167
+ found: boolean;
168
+ }) => Promise<void>;
169
+ fail?: (err: unknown) => void;
170
+ }
171
+ /** What a bucket's calls inside a batch, a view or a tx go through. */
172
+ interface Recorder {
173
+ record<T>(call: Omit<Recorded, 'settle'>, settle: (entry: Entry<Raw> & {
174
+ found: boolean;
175
+ }) => Promise<T>): Promise<T>;
176
+ }
177
+ type Found = Entry<Raw> & {
178
+ found: boolean;
179
+ };
180
+ /**
181
+ * A transaction of store.kv.tx: a read goes to the server at once and is
182
+ * remembered with its version, so that a key read again answers the same; a
183
+ * write waits for the commit, and a key read after it answers what it wrote.
184
+ */
185
+ export declare class Tx implements Recorder {
186
+ #private;
187
+ constructor(link: Link);
188
+ record<T>(call: Omit<Recorded, 'settle'>, settle: (entry: Found) => Promise<T>): Promise<T>;
189
+ /**
190
+ * Sends what fn wrote in one batch, after a check of each key it read: a
191
+ * key it found at the version it found, a key it found absent still
192
+ * absent. A tx that only read checks its reads from one snapshot.
193
+ */
194
+ commit(): Promise<void>;
195
+ /** Whether the commit failed for a key fn read that changed since, which another run reads anew. */
196
+ stale(err: unknown): boolean;
197
+ }
198
+ /**
199
+ * A bucket's values under one branch of owners, the root when there are
200
+ * none: `sessions.of(user.id).get(token)`.
201
+ */
202
+ export declare class Bucket<V> {
203
+ #private;
204
+ readonly name: string;
205
+ constructor(link: Link, name: string, open: Uint8Array, values: Values<V>, owners: (string | Uint8Array)[]);
206
+ /** The branch below this one that the owners name. */
207
+ of(...owners: Key[]): Bucket<V>;
208
+ /**
209
+ * The bucket's calls inside a batch or a view, whose promises settle with
210
+ * it, or inside a tx, whose reads answer at once and writes wait for it.
211
+ */
212
+ withTx(tx: Batch | Tx): BucketTx<V>;
213
+ /** The key's value, undefined when it holds none. */
214
+ get(key: Key): Promise<V | undefined>;
215
+ /** The key's value with its version and expiry, undefined when it holds none. */
216
+ getEntry(key: Key): Promise<Entry<V> | undefined>;
217
+ has(key: Key): Promise<boolean>;
218
+ /** Writes the value; a live key keeps its expiry unless the options give one. */
219
+ set(key: Key, value: V, options?: WriteOptions): Promise<void>;
220
+ /** Writes the value and gives its new version and expiry. */
221
+ setEntry(key: Key, value: V, options?: WriteOptions): Promise<Entry<V>>;
222
+ /** Writes the value only where no live key is, and says whether it did. */
223
+ setIfAbsent(key: Key, value: V, options?: Omit<WriteOptions, 'ifVersion'>): Promise<boolean>;
224
+ /**
225
+ * Writes the value only where no live key is: created says whether it did,
226
+ * and entry is the new key's, or the live one's that was there.
227
+ */
228
+ setEntryIfAbsent(key: Key, value: V, options?: Omit<WriteOptions, 'ifVersion'>): Promise<{
229
+ created: boolean;
230
+ entry: Entry<V>;
231
+ }>;
232
+ delete(key: Key, options?: Pick<WriteOptions, 'ifVersion'>): Promise<void>;
233
+ /**
234
+ * Reads the value and deletes the key in one write: a one-time code read
235
+ * and burned. A value that no longer decodes has been taken all the same.
236
+ */
237
+ take(key: Key, options?: Pick<WriteOptions, 'ifVersion'>): Promise<V | undefined>;
238
+ /** Gives a live key a new expiry, keeping its value and version; false when it holds none. */
239
+ touch(key: Key, options: WriteOptions): Promise<boolean>;
240
+ /** Removes this branch's keys and every branch under it, at once however many. */
241
+ clear(): Promise<void>;
242
+ /** One page of this branch's own keys, in the byte order of their text. */
243
+ scan(options?: {
244
+ after?: Key;
245
+ limit?: number;
246
+ }): Promise<Page<Scanned<V>, string | Uint8Array>>;
247
+ /**
248
+ * Walks this branch's own keys a page at a time, holding no snapshot
249
+ * between pages: a key written during the walk may or may not be met.
250
+ */
251
+ all(options?: {
252
+ limit?: number;
253
+ }): AsyncGenerator<Scanned<V>>;
254
+ }
255
+ /** A bucket's calls inside a batch or a view. */
256
+ export declare class BucketTx<V> {
257
+ #private;
258
+ constructor(tx: Recorder, open: Uint8Array, values: Values<V>, owners: (string | Uint8Array)[]);
259
+ of(...owners: Key[]): BucketTx<V>;
260
+ get(key: Key): Promise<V | undefined>;
261
+ has(key: Key): Promise<boolean>;
262
+ set(key: Key, value: V, options?: WriteOptions): Promise<void>;
263
+ delete(key: Key, options?: Pick<WriteOptions, 'ifVersion'>): Promise<void>;
264
+ take(key: Key): Promise<V | undefined>;
265
+ }
266
+ /**
267
+ * Counters under one branch: an int64 a key, 0 when absent, which add and
268
+ * max change in one write; a sum past the int64 range is refused.
269
+ */
270
+ export declare class Counters<N extends number | bigint> {
271
+ #private;
272
+ readonly name: string;
273
+ constructor(link: Link, name: string, open: Uint8Array, big: boolean, owners: (string | Uint8Array)[]);
274
+ of(...owners: Key[]): Counters<N>;
275
+ get(key: Key): Promise<N>;
276
+ /** Adds n, 1 unless given, and gives the new value. */
277
+ add(key: Key, n?: number | bigint): Promise<N>;
278
+ /** Keeps the larger of the counter and n, and gives it. */
279
+ max(key: Key, n: number | bigint): Promise<N>;
280
+ delete(key: Key): Promise<void>;
281
+ clear(): Promise<void>;
282
+ }
283
+ export {};