@kernlize/core 0.0.0-stage → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +17 -2
- package/dist/cache/index.d.ts +314 -0
- package/dist/cache/index.js +25 -0
- package/dist/cache/index.js.map +1 -0
- package/dist/chunk-42OMIYEO.js +288 -0
- package/dist/chunk-42OMIYEO.js.map +1 -0
- package/dist/chunk-E7SNLTN2.js +283 -0
- package/dist/chunk-E7SNLTN2.js.map +1 -0
- package/dist/chunk-SX5I2XY6.js +468 -0
- package/dist/chunk-SX5I2XY6.js.map +1 -0
- package/dist/crypto/index.d.ts +78 -0
- package/dist/crypto/index.js +13 -0
- package/dist/crypto/index.js.map +1 -0
- package/dist/index.d.ts +3326 -0
- package/dist/index.js +4050 -0
- package/dist/index.js.map +1 -0
- package/dist/sqlite-worker.d.ts +2 -0
- package/dist/sqlite-worker.js +61 -0
- package/dist/sqlite-worker.js.map +1 -0
- package/dist/wm/index.d.ts +246 -0
- package/dist/wm/index.js +19 -0
- package/dist/wm/index.js.map +1 -0
- package/package.json +91 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 kernl contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,18 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @kernlize/core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Opinionated shell composition over kehto and applesauce.
|
|
4
|
+
|
|
5
|
+
| Registry | Package |
|
|
6
|
+
| --- | --- |
|
|
7
|
+
| npm | `@kernlize/core` |
|
|
8
|
+
| JSR | `@kernl/core` |
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
npm install @kernlize/core
|
|
12
|
+
# or, with Deno
|
|
13
|
+
deno add jsr:@kernl/core
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
[Package reference](https://kernl.run/docs/packages/core) · [API reference](https://kernl.run/docs/reference/api) · [Source](https://github.com/kernlize/web/tree/main/packages/core)
|
|
17
|
+
|
|
18
|
+
ESM only. MIT licensed.
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import { Filter, NostrEvent } from 'applesauce-core/helpers';
|
|
2
|
+
import { IAsyncEventDatabase, IEventDatabase, IEventStoreStreams } from 'applesauce-core/event-store';
|
|
3
|
+
import { IEventStoreStreams as IEventStoreStreams$1 } from 'applesauce-core';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A place events are kept between visits. Every backend keeps the same rules: for a replaceable or addressable
|
|
7
|
+
* event only the newest version is kept, a deletion by the same author removes its targets and keeps them out,
|
|
8
|
+
* and ephemeral events are never stored (D-030).
|
|
9
|
+
*/
|
|
10
|
+
interface EventCache {
|
|
11
|
+
/** Which backend this is: `sqlite-opfs`, `indexeddb`, `memory`, or a custom name. */
|
|
12
|
+
readonly name: string;
|
|
13
|
+
/** Store events. Duplicates, older replaceable versions and deleted events are dropped. */
|
|
14
|
+
add(events: readonly NostrEvent[]): Promise<void>;
|
|
15
|
+
/** Events matching any of the filters, newest first, each filter's `limit` applied to that filter. */
|
|
16
|
+
query(filters: readonly Filter[]): Promise<NostrEvent[]>;
|
|
17
|
+
/** Remove the events matching any of the filters; resolves how many were removed. */
|
|
18
|
+
removeByFilters(filters: readonly Filter[]): Promise<number>;
|
|
19
|
+
/** Remove every event. */
|
|
20
|
+
clear(): Promise<void>;
|
|
21
|
+
/** Release the backend. The cache is not used after this. */
|
|
22
|
+
close(): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
/** Opens one kind of {@link EventCache}. */
|
|
25
|
+
interface EventCacheAdapter {
|
|
26
|
+
/** The name the opened cache will carry. */
|
|
27
|
+
readonly name: string;
|
|
28
|
+
/** Open the cache; rejects with `unavailable:<reason>` when this context cannot support it. */
|
|
29
|
+
open(): Promise<EventCache>;
|
|
30
|
+
}
|
|
31
|
+
/** Options for {@link openEventCache}. */
|
|
32
|
+
interface OpenEventCacheOptions {
|
|
33
|
+
/** Called for every adapter that did not open, with its name and the reason it gave. */
|
|
34
|
+
onFallback?(name: string, reason: string): void;
|
|
35
|
+
}
|
|
36
|
+
/** Options for the IndexedDB adapter. */
|
|
37
|
+
interface IndexedDbCacheOptions {
|
|
38
|
+
/** The database name. Default `kernl-events`. */
|
|
39
|
+
readonly name?: string;
|
|
40
|
+
/** The factory to open it with. Default `globalThis.indexedDB`. */
|
|
41
|
+
readonly indexedDB?: IDBFactory;
|
|
42
|
+
}
|
|
43
|
+
/** Options for {@link attachEventCache}, passed to applesauce's `persistEventsToCache`. */
|
|
44
|
+
interface AttachEventCacheOptions {
|
|
45
|
+
/** Milliseconds to collect new events before writing them. Default 5000. */
|
|
46
|
+
readonly batchTime?: number;
|
|
47
|
+
/** Write early once this many events are waiting. */
|
|
48
|
+
readonly maxBatchSize?: number;
|
|
49
|
+
}
|
|
50
|
+
/** A cache wired to an event store: new events are written to it, and loaders read from it. */
|
|
51
|
+
interface AttachedEventCache {
|
|
52
|
+
/** A loader `cacheRequest`: matching events marked as from the cache, or none when the cache cannot answer. */
|
|
53
|
+
readonly cacheRequest: (filters: Filter[]) => Promise<NostrEvent[]>;
|
|
54
|
+
/** Stop writing new events to the cache. */
|
|
55
|
+
stop(): void;
|
|
56
|
+
}
|
|
57
|
+
/** What the sqlite cache did about a damaged database. */
|
|
58
|
+
interface CacheRecoveryEvent {
|
|
59
|
+
/** `wiped`: the file was removed and opened fresh. `rotated`: a new file was used. `disabled`: the cache gave up. */
|
|
60
|
+
readonly action: 'wiped' | 'rotated' | 'disabled';
|
|
61
|
+
/** The error that showed the damage. */
|
|
62
|
+
readonly reason: string;
|
|
63
|
+
}
|
|
64
|
+
/** A value bound to a SQL parameter. */
|
|
65
|
+
type SqlValue = string | number | null;
|
|
66
|
+
/** One SQL statement and its parameters. */
|
|
67
|
+
interface SqlStatement {
|
|
68
|
+
readonly sql: string;
|
|
69
|
+
readonly params?: readonly SqlValue[];
|
|
70
|
+
}
|
|
71
|
+
/** One open sqlite database, as the sqlite cache needs it. */
|
|
72
|
+
interface SqliteDriver {
|
|
73
|
+
/** Run the statements in one transaction. */
|
|
74
|
+
exec(statements: readonly SqlStatement[]): Promise<void>;
|
|
75
|
+
/** Run one statement and resolve its rows as objects. */
|
|
76
|
+
query(statement: SqlStatement): Promise<Record<string, unknown>[]>;
|
|
77
|
+
/** Close the database. */
|
|
78
|
+
close(): Promise<void>;
|
|
79
|
+
}
|
|
80
|
+
/** Where the sqlite cache's database files live: the SAH pool in a worker, or a fake in tests. */
|
|
81
|
+
interface SqliteFiles {
|
|
82
|
+
/** Open, creating when absent, the database at `filename`. */
|
|
83
|
+
open(filename: string): Promise<SqliteDriver>;
|
|
84
|
+
/** Remove the database at `filename` and its journal. Rejects when it cannot. */
|
|
85
|
+
wipe(filename: string): Promise<void>;
|
|
86
|
+
/** Release every file and whatever runs them. */
|
|
87
|
+
close(): Promise<void>;
|
|
88
|
+
}
|
|
89
|
+
/** The part of the Web Locks API the sqlite cache uses. */
|
|
90
|
+
interface LockManagerLike {
|
|
91
|
+
request(name: string, options: {
|
|
92
|
+
ifAvailable: true;
|
|
93
|
+
}, callback: (lock: unknown) => Promise<void> | void): Promise<unknown>;
|
|
94
|
+
}
|
|
95
|
+
/** The part of `Storage` the sqlite cache keeps its current filename in. */
|
|
96
|
+
interface FilenameStorage {
|
|
97
|
+
getItem(key: string): string | null;
|
|
98
|
+
setItem(key: string, value: string): void;
|
|
99
|
+
}
|
|
100
|
+
/** Options for the sqlite-over-OPFS adapter. */
|
|
101
|
+
interface SqliteOpfsOptions {
|
|
102
|
+
/** The database file in the SAH pool. Default `/kernl-events.sqlite3`. */
|
|
103
|
+
readonly filename?: string;
|
|
104
|
+
/** Keeps the filename after a rotation. Default `globalThis.localStorage` when there is one. */
|
|
105
|
+
readonly storage?: FilenameStorage;
|
|
106
|
+
/** Guards the database against a second tab. Default `navigator.locks` when there is one. */
|
|
107
|
+
readonly locks?: LockManagerLike;
|
|
108
|
+
/** Opens the database files. Default: a dedicated worker running sqlite-wasm over the OPFS SAH pool. */
|
|
109
|
+
readonly connect?: () => Promise<SqliteFiles>;
|
|
110
|
+
/** Told whenever a damaged database was wiped or rotated, or the cache gave up. */
|
|
111
|
+
onRecover?(event: CacheRecoveryEvent): void;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The storage a backend provides. It only keeps rows; every rule about which event wins lives in
|
|
116
|
+
* {@link createEventCache}, so all backends behave the same.
|
|
117
|
+
*/
|
|
118
|
+
interface EventRecords {
|
|
119
|
+
/** Insert events, ignoring ids already present. */
|
|
120
|
+
put(events: readonly NostrEvent[]): Promise<void>;
|
|
121
|
+
/** Events matching one filter. Honouring `limit` is an optimisation; the caller applies it again. */
|
|
122
|
+
query(filter: Filter): Promise<NostrEvent[]>;
|
|
123
|
+
/** Remove events by id. */
|
|
124
|
+
remove(ids: readonly string[]): Promise<void>;
|
|
125
|
+
clear(): Promise<void>;
|
|
126
|
+
close(): Promise<void>;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Give a backend kernl's cache rules: replaceable and addressable events keep only their newest version,
|
|
130
|
+
* kind 5 deletions by the same author remove their targets and keep them out, ephemeral events are not
|
|
131
|
+
* stored, and writes run one after another so two batches never race on the same address.
|
|
132
|
+
*
|
|
133
|
+
* @param name - The cache's name.
|
|
134
|
+
* @param records - The backend's storage.
|
|
135
|
+
* @returns An {@link EventCache} over `records`.
|
|
136
|
+
* @example
|
|
137
|
+
* ```ts
|
|
138
|
+
* import { createEventCache, type EventRecords } from '@kernlize/core/cache';
|
|
139
|
+
*
|
|
140
|
+
* declare const records: EventRecords;
|
|
141
|
+
* const cache = createEventCache('custom', records);
|
|
142
|
+
* await cache.query([{ kinds: [0], limit: 1 }]);
|
|
143
|
+
* ```
|
|
144
|
+
*/
|
|
145
|
+
declare function createEventCache(name: string, records: EventRecords): EventCache;
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Turn any applesauce event database into a kernl cache: applesauce-sqlite's better-sqlite3, libsql or turso
|
|
149
|
+
* databases, the in-memory `EventMemory`, or a database of your own. kernl's cache rules are applied on top,
|
|
150
|
+
* so the database only has to store rows.
|
|
151
|
+
*
|
|
152
|
+
* @param name - The cache's name.
|
|
153
|
+
* @param database - A synchronous or asynchronous applesauce event database.
|
|
154
|
+
* @param close - Called once when the cache is closed, to release the database.
|
|
155
|
+
* @returns An {@link EventCache} over `database`.
|
|
156
|
+
* @example
|
|
157
|
+
* ```ts
|
|
158
|
+
* import { EventMemory } from 'applesauce-core/event-store';
|
|
159
|
+
* import { fromEventDatabase } from '@kernlize/core/cache';
|
|
160
|
+
*
|
|
161
|
+
* const cache = fromEventDatabase('memory', new EventMemory());
|
|
162
|
+
* await cache.add([]);
|
|
163
|
+
* ```
|
|
164
|
+
*/
|
|
165
|
+
declare function fromEventDatabase(name: string, database: IAsyncEventDatabase | IEventDatabase, close?: () => Promise<void> | void): EventCache;
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* An adapter whose cache lives in memory and is gone when the page closes. It always opens, which makes it
|
|
169
|
+
* the last resort of {@link openEventCache}.
|
|
170
|
+
*
|
|
171
|
+
* @returns The `memory` adapter.
|
|
172
|
+
* @example
|
|
173
|
+
* ```ts
|
|
174
|
+
* import { createMemoryCacheAdapter } from '@kernlize/core/cache';
|
|
175
|
+
*
|
|
176
|
+
* const cache = await createMemoryCacheAdapter().open();
|
|
177
|
+
* cache.name; // 'memory'
|
|
178
|
+
* ```
|
|
179
|
+
*/
|
|
180
|
+
declare function createMemoryCacheAdapter(): EventCacheAdapter;
|
|
181
|
+
/**
|
|
182
|
+
* Open the first adapter that can open in this context. An adapter that rejects is reported through
|
|
183
|
+
* `onFallback` and the next one is tried; when none opens, the cache is kept in memory. It never rejects:
|
|
184
|
+
* the cache is an accelerator, and the shell runs without one (D-030).
|
|
185
|
+
*
|
|
186
|
+
* @param adapters - Adapters in order of preference.
|
|
187
|
+
* @param options - `onFallback`, told the name and reason of every adapter that did not open.
|
|
188
|
+
* @returns The opened cache.
|
|
189
|
+
* @example
|
|
190
|
+
* ```ts
|
|
191
|
+
* import { defaultWebCacheAdapters, openEventCache } from '@kernlize/core/cache';
|
|
192
|
+
*
|
|
193
|
+
* const cache = await openEventCache(defaultWebCacheAdapters(), {
|
|
194
|
+
* onFallback: (name, reason) => console.info(`${name} cache skipped: ${reason}`),
|
|
195
|
+
* });
|
|
196
|
+
* ```
|
|
197
|
+
*/
|
|
198
|
+
declare function openEventCache(adapters: readonly EventCacheAdapter[], options?: OpenEventCacheOptions): Promise<EventCache>;
|
|
199
|
+
/**
|
|
200
|
+
* The adapters a browser shell tries, in order: sqlite over OPFS in a worker, then IndexedDB, then memory.
|
|
201
|
+
*
|
|
202
|
+
* @returns `[sqlite-opfs, indexeddb, memory]` with their default options.
|
|
203
|
+
* @example
|
|
204
|
+
* ```ts
|
|
205
|
+
* import { defaultWebCacheAdapters, openEventCache } from '@kernlize/core/cache';
|
|
206
|
+
*
|
|
207
|
+
* const cache = await openEventCache(defaultWebCacheAdapters());
|
|
208
|
+
* ```
|
|
209
|
+
*/
|
|
210
|
+
declare function defaultWebCacheAdapters(): readonly EventCacheAdapter[];
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* An adapter for a cache in IndexedDB: one object store keyed by id, with indexes on kind, author, time and
|
|
214
|
+
* single-letter tags. It needs no worker and no extra library, which makes it the fallback when sqlite over
|
|
215
|
+
* OPFS is unavailable.
|
|
216
|
+
*
|
|
217
|
+
* @param options - The database `name` (default `kernl-events`) and the `indexedDB` factory to use.
|
|
218
|
+
* @returns The `indexeddb` adapter. Its `open` rejects `unavailable:indexeddb` when there is no factory or it refuses.
|
|
219
|
+
* @example
|
|
220
|
+
* ```ts
|
|
221
|
+
* import { createIndexedDbCacheAdapter, openEventCache } from '@kernlize/core/cache';
|
|
222
|
+
*
|
|
223
|
+
* const cache = await openEventCache([createIndexedDbCacheAdapter({ name: 'my-shell-events' })]);
|
|
224
|
+
* ```
|
|
225
|
+
*/
|
|
226
|
+
declare function createIndexedDbCacheAdapter(options?: IndexedDbCacheOptions): EventCacheAdapter;
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* An adapter for a cache in sqlite-wasm over the origin-private file system. sqlite runs in a dedicated
|
|
230
|
+
* worker on the SAH pool VFS, so the page needs no cross-origin isolation; sqlite-wasm is loaded only
|
|
231
|
+
* inside that worker. The database is checked with `PRAGMA quick_check` on open, and damage found then or
|
|
232
|
+
* later is repaired by wiping or rotating the file. A Web Lock keeps a second tab out; that tab falls back
|
|
233
|
+
* to the next adapter.
|
|
234
|
+
*
|
|
235
|
+
* @param options - Filename, storage for the rotated filename, lock manager, connection and `onRecover`.
|
|
236
|
+
* @returns The `sqlite-opfs` adapter. Its `open` rejects `unavailable:opfs`, `unavailable:locked`,
|
|
237
|
+
* `unavailable:corrupt` or `unavailable:sqlite (…)`.
|
|
238
|
+
* @example
|
|
239
|
+
* ```ts
|
|
240
|
+
* import { createSqliteOpfsCacheAdapter, openEventCache } from '@kernlize/core/cache';
|
|
241
|
+
*
|
|
242
|
+
* const cache = await openEventCache([
|
|
243
|
+
* createSqliteOpfsCacheAdapter({ onRecover: ({ action, reason }) => console.warn(`event cache ${action}: ${reason}`) }),
|
|
244
|
+
* ]);
|
|
245
|
+
* ```
|
|
246
|
+
*/
|
|
247
|
+
declare function createSqliteOpfsCacheAdapter(options?: SqliteOpfsOptions): EventCacheAdapter;
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Whether an error means the database file is damaged, rather than busy, full or misused.
|
|
251
|
+
*
|
|
252
|
+
* @param error - Whatever a sqlite call threw.
|
|
253
|
+
* @returns True for `SQLITE_CORRUPT`, `SQLITE_NOTADB` and their messages.
|
|
254
|
+
* @example
|
|
255
|
+
* ```ts
|
|
256
|
+
* import { isCorruptionError } from '@kernlize/core/cache';
|
|
257
|
+
*
|
|
258
|
+
* isCorruptionError(new Error('SQLITE_CORRUPT: database disk image is malformed')); // true
|
|
259
|
+
* isCorruptionError(new Error('SQLITE_BUSY: database is locked')); // false
|
|
260
|
+
* ```
|
|
261
|
+
*/
|
|
262
|
+
declare function isCorruptionError(error: unknown): boolean;
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Wire a cache to an event store. New events the store receives are written in batches through applesauce's
|
|
266
|
+
* `persistEventsToCache`, which skips events that came from the cache. `cacheRequest` is what applesauce
|
|
267
|
+
* loaders take as their `cacheRequest`: it marks every event it returns as from the cache, and resolves
|
|
268
|
+
* nothing when the cache cannot answer, because a cache is an accelerator, never identity.
|
|
269
|
+
*
|
|
270
|
+
* @param store - An event store, or anything with its `insert$` stream.
|
|
271
|
+
* @param cache - The cache to write to and read from.
|
|
272
|
+
* @param options - `batchTime` and `maxBatchSize` for the writes.
|
|
273
|
+
* @returns `cacheRequest` and `stop`, which ends the writes.
|
|
274
|
+
* @example
|
|
275
|
+
* ```ts
|
|
276
|
+
* import { EventStore } from 'applesauce-core';
|
|
277
|
+
* import { attachEventCache, createMemoryCacheAdapter } from '@kernlize/core/cache';
|
|
278
|
+
*
|
|
279
|
+
* const store = new EventStore();
|
|
280
|
+
* const attached = attachEventCache(store, await createMemoryCacheAdapter().open());
|
|
281
|
+
* await attached.cacheRequest([{ kinds: [0], limit: 1 }]);
|
|
282
|
+
* attached.stop();
|
|
283
|
+
* ```
|
|
284
|
+
*/
|
|
285
|
+
declare function attachEventCache(store: Pick<IEventStoreStreams, 'insert$'>, cache: EventCache, options?: AttachEventCacheOptions): AttachedEventCache;
|
|
286
|
+
|
|
287
|
+
/** An event cache the shell opens itself, once, on start. */
|
|
288
|
+
type EventCacheOpener = () => Promise<EventCache | undefined>;
|
|
289
|
+
/** The shell's side of its event cache: what loaders ask, and how it is let go. */
|
|
290
|
+
interface ConnectedEventCache {
|
|
291
|
+
/** Loader `cacheRequest`: cached matches marked as from the cache; none while the cache opens or when there is none. */
|
|
292
|
+
readonly cacheRequest: (filters: Filter[]) => Promise<NostrEvent[]>;
|
|
293
|
+
/** Stop writing, then close the cache. */
|
|
294
|
+
close(): Promise<void>;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Open the shell's event cache in the background and attach it to the store.
|
|
298
|
+
*
|
|
299
|
+
* The shell starts at once: a request that comes before the cache is open
|
|
300
|
+
* waits for it, and a cache that fails to open leaves the shell without one,
|
|
301
|
+
* because the cache is an accelerator (D-030).
|
|
302
|
+
*
|
|
303
|
+
* @param store - The shell's event store; its new events are written to the cache.
|
|
304
|
+
* @param open - Opens the cache, such as `() => openEventCache(defaultWebCacheAdapters())`; none when absent.
|
|
305
|
+
* @returns The loader hook and the release.
|
|
306
|
+
* @example
|
|
307
|
+
* ```ts
|
|
308
|
+
* const cache = connectEventCache(eventStore, () => openEventCache(defaultWebCacheAdapters()));
|
|
309
|
+
* createAddressLoader(pool, { cacheRequest: cache.cacheRequest });
|
|
310
|
+
* ```
|
|
311
|
+
*/
|
|
312
|
+
declare function connectEventCache(store: Pick<IEventStoreStreams$1, 'insert$'>, open?: EventCacheOpener): ConnectedEventCache;
|
|
313
|
+
|
|
314
|
+
export { type AttachEventCacheOptions, type AttachedEventCache, type CacheRecoveryEvent, type ConnectedEventCache, type EventCache, type EventCacheAdapter, type EventCacheOpener, type EventRecords, type FilenameStorage, type IndexedDbCacheOptions, type LockManagerLike, type OpenEventCacheOptions, type SqlStatement, type SqlValue, type SqliteDriver, type SqliteFiles, type SqliteOpfsOptions, attachEventCache, connectEventCache, createEventCache, createIndexedDbCacheAdapter, createMemoryCacheAdapter, createSqliteOpfsCacheAdapter, defaultWebCacheAdapters, fromEventDatabase, isCorruptionError, openEventCache };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import {
|
|
2
|
+
attachEventCache,
|
|
3
|
+
connectEventCache,
|
|
4
|
+
createEventCache,
|
|
5
|
+
createIndexedDbCacheAdapter,
|
|
6
|
+
createMemoryCacheAdapter,
|
|
7
|
+
createSqliteOpfsCacheAdapter,
|
|
8
|
+
defaultWebCacheAdapters,
|
|
9
|
+
fromEventDatabase,
|
|
10
|
+
isCorruptionError,
|
|
11
|
+
openEventCache
|
|
12
|
+
} from "../chunk-SX5I2XY6.js";
|
|
13
|
+
export {
|
|
14
|
+
attachEventCache,
|
|
15
|
+
connectEventCache,
|
|
16
|
+
createEventCache,
|
|
17
|
+
createIndexedDbCacheAdapter,
|
|
18
|
+
createMemoryCacheAdapter,
|
|
19
|
+
createSqliteOpfsCacheAdapter,
|
|
20
|
+
defaultWebCacheAdapters,
|
|
21
|
+
fromEventDatabase,
|
|
22
|
+
isCorruptionError,
|
|
23
|
+
openEventCache
|
|
24
|
+
};
|
|
25
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
// src/crypto/subtle-fallback.ts
|
|
2
|
+
import { cbc, gcm } from "@noble/ciphers/aes.js";
|
|
3
|
+
import { ed25519, x25519 } from "@noble/curves/ed25519.js";
|
|
4
|
+
import { hkdf } from "@noble/hashes/hkdf.js";
|
|
5
|
+
import { hmac } from "@noble/hashes/hmac.js";
|
|
6
|
+
import { sha1 } from "@noble/hashes/legacy.js";
|
|
7
|
+
import { sha256, sha384, sha512 } from "@noble/hashes/sha2.js";
|
|
8
|
+
var HASHES = {
|
|
9
|
+
"SHA-1": sha1,
|
|
10
|
+
"SHA-256": sha256,
|
|
11
|
+
"SHA-384": sha384,
|
|
12
|
+
"SHA-512": sha512
|
|
13
|
+
};
|
|
14
|
+
var PKCS8_PREFIX = {
|
|
15
|
+
Ed25519: Uint8Array.from([48, 46, 2, 1, 0, 48, 5, 6, 3, 43, 101, 112, 4, 34, 4, 32]),
|
|
16
|
+
X25519: Uint8Array.from([48, 46, 2, 1, 0, 48, 5, 6, 3, 43, 101, 110, 4, 34, 4, 32])
|
|
17
|
+
};
|
|
18
|
+
var materials = /* @__PURE__ */ new WeakMap();
|
|
19
|
+
function fail(name, message) {
|
|
20
|
+
throw new DOMException(message, name);
|
|
21
|
+
}
|
|
22
|
+
function nameOf(alg) {
|
|
23
|
+
return (typeof alg === "string" ? alg : alg.name).toUpperCase();
|
|
24
|
+
}
|
|
25
|
+
function param(alg, field) {
|
|
26
|
+
return typeof alg === "string" ? void 0 : Reflect.get(alg, field);
|
|
27
|
+
}
|
|
28
|
+
function canonical(name) {
|
|
29
|
+
const upper = name.toUpperCase();
|
|
30
|
+
if (upper === "ED25519") return "Ed25519";
|
|
31
|
+
if (upper === "X25519") return "X25519";
|
|
32
|
+
return upper;
|
|
33
|
+
}
|
|
34
|
+
function hashOf(input) {
|
|
35
|
+
const name = (typeof input === "string" ? input : String(Reflect.get(Object(input), "name") ?? "")).toUpperCase();
|
|
36
|
+
if (name in HASHES) return name;
|
|
37
|
+
return fail("NotSupportedError", `Unsupported hash: ${name || "none"}`);
|
|
38
|
+
}
|
|
39
|
+
function bytesOf(data) {
|
|
40
|
+
if (data instanceof ArrayBuffer) return new Uint8Array(data.slice(0));
|
|
41
|
+
if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength));
|
|
42
|
+
return fail("DataError", "Expected a BufferSource");
|
|
43
|
+
}
|
|
44
|
+
function bufferOf(bytes) {
|
|
45
|
+
return bytes.slice().buffer;
|
|
46
|
+
}
|
|
47
|
+
function toBase64Url(bytes) {
|
|
48
|
+
let binary = "";
|
|
49
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
50
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
51
|
+
}
|
|
52
|
+
function fromBase64Url(text) {
|
|
53
|
+
const base64 = text.replace(/-/g, "+").replace(/_/g, "/");
|
|
54
|
+
return Uint8Array.from(atob(base64 + "=".repeat((4 - base64.length % 4) % 4)), (char) => char.charCodeAt(0));
|
|
55
|
+
}
|
|
56
|
+
var FallbackKey = class {
|
|
57
|
+
constructor(type, algorithm, extractable, usages) {
|
|
58
|
+
this.type = type;
|
|
59
|
+
this.extractable = extractable;
|
|
60
|
+
this.algorithm = Object.freeze(algorithm);
|
|
61
|
+
this.usages = [...usages];
|
|
62
|
+
Object.freeze(this);
|
|
63
|
+
}
|
|
64
|
+
type;
|
|
65
|
+
extractable;
|
|
66
|
+
algorithm;
|
|
67
|
+
usages;
|
|
68
|
+
};
|
|
69
|
+
function makeKey(type, algorithm, extractable, usages, material) {
|
|
70
|
+
const key = new FallbackKey(type, algorithm, extractable, usages);
|
|
71
|
+
materials.set(key, material);
|
|
72
|
+
return key;
|
|
73
|
+
}
|
|
74
|
+
function materialOf(key, alg) {
|
|
75
|
+
const material = materials.get(key);
|
|
76
|
+
if (material === void 0) return fail("InvalidAccessError", "The key was not made by this fallback");
|
|
77
|
+
if (canonical(key.algorithm.name) !== canonical(alg)) return fail("InvalidAccessError", `Key is ${key.algorithm.name}, not ${alg}`);
|
|
78
|
+
return material;
|
|
79
|
+
}
|
|
80
|
+
function publicOf(curve, secret) {
|
|
81
|
+
return curve === "Ed25519" ? ed25519.getPublicKey(secret) : x25519.getPublicKey(secret);
|
|
82
|
+
}
|
|
83
|
+
function curveKey(curve, isPrivate, bytes, extractable, usages) {
|
|
84
|
+
if (bytes.length !== 32) return fail("DataError", `${curve} keys are 32 bytes`);
|
|
85
|
+
return makeKey(isPrivate ? "private" : "public", { name: curve }, extractable, usages, { bytes });
|
|
86
|
+
}
|
|
87
|
+
function importCurve(format, data, curve, extractable, usages) {
|
|
88
|
+
if (format === "raw") return curveKey(curve, false, bytesOf(data), extractable, usages);
|
|
89
|
+
if (format === "pkcs8") {
|
|
90
|
+
const der = bytesOf(data);
|
|
91
|
+
const prefix = PKCS8_PREFIX[curve];
|
|
92
|
+
if (der.length !== prefix.length + 32 || prefix.some((byte, at) => der[at] !== byte)) return fail("DataError", `Unsupported ${curve} PKCS#8 encoding`);
|
|
93
|
+
return curveKey(curve, true, der.slice(prefix.length), extractable, usages);
|
|
94
|
+
}
|
|
95
|
+
if (format === "jwk") {
|
|
96
|
+
const jwk = data;
|
|
97
|
+
if (jwk.kty !== "OKP" || jwk.crv !== curve) return fail("DataError", `Expected an OKP ${curve} JWK`);
|
|
98
|
+
if (jwk.d !== void 0) return curveKey(curve, true, fromBase64Url(jwk.d), extractable, usages);
|
|
99
|
+
if (jwk.x !== void 0) return curveKey(curve, false, fromBase64Url(jwk.x), extractable, usages);
|
|
100
|
+
return fail("DataError", "JWK has neither x nor d");
|
|
101
|
+
}
|
|
102
|
+
return fail("NotSupportedError", `Unsupported ${curve} key format: ${format}`);
|
|
103
|
+
}
|
|
104
|
+
function secretAlgorithm(alg, bytes, hash) {
|
|
105
|
+
if (alg === "HMAC") return { name: alg, hash: { name: hash }, length: bytes.length * 8 };
|
|
106
|
+
if (alg === "HKDF") return { name: alg };
|
|
107
|
+
return { name: alg, length: bytes.length * 8 };
|
|
108
|
+
}
|
|
109
|
+
function importSecret(format, data, algorithm, extractable, usages) {
|
|
110
|
+
const alg = nameOf(algorithm);
|
|
111
|
+
const bytes = format === "raw" ? bytesOf(data) : format === "jwk" && data.kty === "oct" ? fromBase64Url(data.k ?? "") : fail("NotSupportedError", `Unsupported ${alg} key format: ${format}`);
|
|
112
|
+
if (alg !== "HMAC" && alg !== "HKDF" && ![16, 24, 32].includes(bytes.length)) return fail("DataError", "AES keys are 128, 192 or 256 bits");
|
|
113
|
+
const hash = alg === "HMAC" ? hashOf(param(algorithm, "hash")) : void 0;
|
|
114
|
+
const material = hash === void 0 ? { bytes } : { bytes, hash };
|
|
115
|
+
return makeKey("secret", secretAlgorithm(alg, bytes, hash), alg !== "HKDF" && extractable, usages, material);
|
|
116
|
+
}
|
|
117
|
+
async function importKey(format, data, algorithm, extractable, usages) {
|
|
118
|
+
const name = canonical(nameOf(algorithm));
|
|
119
|
+
if (name === "Ed25519" || name === "X25519") return importCurve(format, data, name, extractable, usages);
|
|
120
|
+
if (["AES-GCM", "AES-CBC", "HMAC", "HKDF"].includes(name)) return importSecret(format, data, algorithm, extractable, usages);
|
|
121
|
+
return fail("NotSupportedError", `Unsupported algorithm: ${name}`);
|
|
122
|
+
}
|
|
123
|
+
function exportCurve(format, key, bytes) {
|
|
124
|
+
const curve = canonical(key.algorithm.name);
|
|
125
|
+
const isPrivate = key.type === "private";
|
|
126
|
+
if (format === "raw" && !isPrivate) return bufferOf(bytes);
|
|
127
|
+
if (format === "pkcs8" && isPrivate) {
|
|
128
|
+
const der = new Uint8Array(PKCS8_PREFIX[curve].length + 32);
|
|
129
|
+
der.set(PKCS8_PREFIX[curve]);
|
|
130
|
+
der.set(bytes, PKCS8_PREFIX[curve].length);
|
|
131
|
+
return der.buffer;
|
|
132
|
+
}
|
|
133
|
+
if (format === "jwk") {
|
|
134
|
+
const jwk = { kty: "OKP", crv: curve, x: toBase64Url(isPrivate ? publicOf(curve, bytes) : bytes), key_ops: [...key.usages], ext: true };
|
|
135
|
+
if (isPrivate) jwk.d = toBase64Url(bytes);
|
|
136
|
+
return jwk;
|
|
137
|
+
}
|
|
138
|
+
return fail("InvalidAccessError", `Cannot export a ${key.type} ${curve} key as ${format}`);
|
|
139
|
+
}
|
|
140
|
+
async function exportKey(format, key) {
|
|
141
|
+
const { bytes } = materialOf(key, key.algorithm.name);
|
|
142
|
+
if (!key.extractable) return fail("InvalidAccessError", "The key is not extractable");
|
|
143
|
+
if (key.type !== "secret") return exportCurve(format, key, bytes);
|
|
144
|
+
if (format === "raw") return bufferOf(bytes);
|
|
145
|
+
if (format === "jwk") return { kty: "oct", k: toBase64Url(bytes), key_ops: [...key.usages], ext: true };
|
|
146
|
+
return fail("NotSupportedError", `Cannot export a secret key as ${format}`);
|
|
147
|
+
}
|
|
148
|
+
function randomBytes(length) {
|
|
149
|
+
return globalThis.crypto.getRandomValues(new Uint8Array(length));
|
|
150
|
+
}
|
|
151
|
+
async function generateKey(algorithm, extractable, usages) {
|
|
152
|
+
const name = canonical(nameOf(algorithm));
|
|
153
|
+
if (name === "Ed25519" || name === "X25519") {
|
|
154
|
+
const secret = randomBytes(32);
|
|
155
|
+
const publicUsages = usages.filter((usage) => usage === "verify");
|
|
156
|
+
const privateUsages = usages.filter((usage) => usage !== "verify");
|
|
157
|
+
return {
|
|
158
|
+
publicKey: curveKey(name, false, publicOf(name, secret), true, publicUsages),
|
|
159
|
+
privateKey: curveKey(name, true, secret, extractable, privateUsages)
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
if (name === "AES-GCM" || name === "AES-CBC" || name === "HMAC") {
|
|
163
|
+
const length = param(algorithm, "length");
|
|
164
|
+
const bits = length ?? (name === "HMAC" ? HASHES[hashOf(param(algorithm, "hash"))].outputLen * 8 : 256);
|
|
165
|
+
return importSecret("raw", randomBytes(bits / 8), algorithm, extractable, usages);
|
|
166
|
+
}
|
|
167
|
+
return fail("NotSupportedError", `Unsupported algorithm: ${name}`);
|
|
168
|
+
}
|
|
169
|
+
async function sign(algorithm, key, data) {
|
|
170
|
+
const name = canonical(nameOf(algorithm));
|
|
171
|
+
const material = materialOf(key, name);
|
|
172
|
+
if (name === "HMAC") return bufferOf(hmac(HASHES[material.hash], material.bytes, bytesOf(data)));
|
|
173
|
+
if (name === "Ed25519" && key.type === "private") return bufferOf(ed25519.sign(bytesOf(data), material.bytes));
|
|
174
|
+
return fail("NotSupportedError", `Cannot sign with ${name}`);
|
|
175
|
+
}
|
|
176
|
+
async function verify(algorithm, key, signature, data) {
|
|
177
|
+
const name = canonical(nameOf(algorithm));
|
|
178
|
+
const material = materialOf(key, name);
|
|
179
|
+
if (name === "HMAC") {
|
|
180
|
+
const expected = hmac(HASHES[material.hash], material.bytes, bytesOf(data));
|
|
181
|
+
const given = bytesOf(signature);
|
|
182
|
+
return given.length === expected.length && given.reduce((diff, byte, at) => diff | byte ^ expected[at], 0) === 0;
|
|
183
|
+
}
|
|
184
|
+
if (name === "Ed25519" && key.type === "public") {
|
|
185
|
+
try {
|
|
186
|
+
return ed25519.verify(bytesOf(signature), bytesOf(data), material.bytes);
|
|
187
|
+
} catch {
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return fail("NotSupportedError", `Cannot verify with ${name}`);
|
|
192
|
+
}
|
|
193
|
+
function aesCipher(algorithm, key) {
|
|
194
|
+
const name = nameOf(algorithm);
|
|
195
|
+
if (name !== "AES-CBC" && name !== "AES-GCM") return fail("NotSupportedError", `Unsupported cipher: ${name}`);
|
|
196
|
+
const { bytes } = materialOf(key, name);
|
|
197
|
+
const iv = param(algorithm, "iv");
|
|
198
|
+
if (iv === void 0) return fail("DataError", `${name} needs an iv`);
|
|
199
|
+
const nonce = bytesOf(iv);
|
|
200
|
+
if (name === "AES-CBC") return cbc(bytes, nonce);
|
|
201
|
+
const tagLength = param(algorithm, "tagLength") ?? 128;
|
|
202
|
+
if (tagLength !== 128) return fail("NotSupportedError", "Only 128-bit AES-GCM tags are supported");
|
|
203
|
+
const aad = param(algorithm, "additionalData");
|
|
204
|
+
return gcm(bytes, nonce, aad === void 0 ? void 0 : bytesOf(aad));
|
|
205
|
+
}
|
|
206
|
+
async function encrypt(algorithm, key, data) {
|
|
207
|
+
return bufferOf(aesCipher(algorithm, key).encrypt(bytesOf(data)));
|
|
208
|
+
}
|
|
209
|
+
async function decrypt(algorithm, key, data) {
|
|
210
|
+
const cipher = aesCipher(algorithm, key);
|
|
211
|
+
try {
|
|
212
|
+
return bufferOf(cipher.decrypt(bytesOf(data)));
|
|
213
|
+
} catch {
|
|
214
|
+
return fail("OperationError", "Decryption failed");
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
async function deriveBits(algorithm, baseKey, length) {
|
|
218
|
+
const name = canonical(nameOf(algorithm));
|
|
219
|
+
const material = materialOf(baseKey, name);
|
|
220
|
+
if (typeof algorithm === "string") return fail("NotSupportedError", `${name} needs parameters`);
|
|
221
|
+
if (name === "X25519") {
|
|
222
|
+
const peer = materialOf(param(algorithm, "public"), "X25519");
|
|
223
|
+
const shared = x25519.getSharedSecret(material.bytes, peer.bytes);
|
|
224
|
+
return bufferOf(length === void 0 || length === null ? shared : shared.slice(0, length / 8));
|
|
225
|
+
}
|
|
226
|
+
if (name === "HKDF" && typeof length === "number") {
|
|
227
|
+
const salt = bytesOf(param(algorithm, "salt"));
|
|
228
|
+
const info = bytesOf(param(algorithm, "info"));
|
|
229
|
+
return bufferOf(hkdf(HASHES[hashOf(param(algorithm, "hash"))], material.bytes, salt, info, length / 8));
|
|
230
|
+
}
|
|
231
|
+
return fail("NotSupportedError", `Cannot derive bits with ${name}`);
|
|
232
|
+
}
|
|
233
|
+
async function digest(algorithm, data) {
|
|
234
|
+
return bufferOf(HASHES[hashOf(nameOf(algorithm))](bytesOf(data)));
|
|
235
|
+
}
|
|
236
|
+
async function unsupported() {
|
|
237
|
+
return fail("NotSupportedError", "Not available in this fallback");
|
|
238
|
+
}
|
|
239
|
+
function createFallbackSubtle() {
|
|
240
|
+
return {
|
|
241
|
+
decrypt,
|
|
242
|
+
deriveBits,
|
|
243
|
+
deriveKey: unsupported,
|
|
244
|
+
digest,
|
|
245
|
+
encrypt,
|
|
246
|
+
exportKey,
|
|
247
|
+
generateKey,
|
|
248
|
+
importKey,
|
|
249
|
+
sign,
|
|
250
|
+
unwrapKey: unsupported,
|
|
251
|
+
verify,
|
|
252
|
+
wrapKey: unsupported
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// src/crypto/install.ts
|
|
257
|
+
function randomUuidFallback(scope) {
|
|
258
|
+
const provider = scope.crypto;
|
|
259
|
+
if (provider === void 0 || typeof provider.randomUUID === "function" || typeof provider.getRandomValues !== "function") return false;
|
|
260
|
+
const getRandomValues = provider.getRandomValues.bind(provider);
|
|
261
|
+
const randomUUID = () => {
|
|
262
|
+
const bytes = getRandomValues(new Uint8Array(16));
|
|
263
|
+
bytes[6] = bytes[6] & 15 | 64;
|
|
264
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
265
|
+
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
266
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
267
|
+
};
|
|
268
|
+
Object.defineProperty(provider, "randomUUID", { value: randomUUID, configurable: true, writable: true });
|
|
269
|
+
return true;
|
|
270
|
+
}
|
|
271
|
+
function installCryptoFallback(scope = globalThis) {
|
|
272
|
+
const randomUUID = randomUuidFallback(scope);
|
|
273
|
+
const provider = scope.crypto;
|
|
274
|
+
const subtle = provider !== void 0 && provider.subtle === void 0 && typeof provider.getRandomValues === "function";
|
|
275
|
+
if (subtle) Object.defineProperty(provider, "subtle", { value: createFallbackSubtle(), configurable: true });
|
|
276
|
+
return { randomUUID, subtle };
|
|
277
|
+
}
|
|
278
|
+
function renderRandomUuidFallbackScript() {
|
|
279
|
+
return `<script data-kernl-crypto-fallback>(${randomUuidFallback.toString()})(window);</script>`;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
export {
|
|
283
|
+
createFallbackSubtle,
|
|
284
|
+
randomUuidFallback,
|
|
285
|
+
installCryptoFallback,
|
|
286
|
+
renderRandomUuidFallbackScript
|
|
287
|
+
};
|
|
288
|
+
//# sourceMappingURL=chunk-42OMIYEO.js.map
|