@sovereignbase/explorer 0.0.0-alpha.0 → 0.0.0-alpha.2

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/dist/class.cjs ADDED
@@ -0,0 +1,760 @@
1
+ /*
2
+ * Copyright 2026 Sovereignbase
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
18
+ let _sovereignbase_storage = require("@sovereignbase/storage");
19
+ let _sovereignbase_utils = require("@sovereignbase/utils");
20
+ let _sovereignbase_bytecodec = require("@sovereignbase/bytecodec");
21
+ let _sovereignbase_dom_utils = require("@sovereignbase/dom-utils");
22
+ let _sovereignbase_hardware_bound = require("@sovereignbase/hardware-bound");
23
+ let _sovereignbase_cryptosuite = require("@sovereignbase/cryptosuite");
24
+ let _sovereignbase_sequenced = require("@sovereignbase/sequenced");
25
+ // src/.errors/class.ts
26
+ /**
27
+ * An Explorer error with a stable, machine-readable code and an optional cause.
28
+ *
29
+ * The message is prefixed with the library name. Use {@link code} rather than
30
+ * parsing the message when handling a particular failure.
31
+ */
32
+ var ExplorerError = class extends Error {
33
+ /** The machine-readable category of the failure. */
34
+ code;
35
+ /**
36
+ * Creates an error whose name is `ExplorerError`.
37
+ *
38
+ * @param code The category of the failure.
39
+ * @param message The detail to prefix with the library name; defaults to `code`.
40
+ * @param options Error options, including the original `cause`.
41
+ */
42
+ constructor(code, message, options) {
43
+ super(`{@sovereignbase/explorer} ${message ?? code}`, options);
44
+ this.code = code;
45
+ this.name = "ExplorerError";
46
+ }
47
+ };
48
+ // src/.errors/unkown.ts
49
+ /**
50
+ * Preserves an existing library error or wraps an unexpected failure once.
51
+ * @param cause The value thrown by the failed operation.
52
+ * @param operation The operation name to include in the error message.
53
+ * @returns The original library error, or an `UNKNOWN_ERROR` retaining `cause`.
54
+ */
55
+ function unknownError(cause, operation) {
56
+ return cause instanceof ExplorerError ? cause : new ExplorerError("UNKNOWN_ERROR", `${operation} failed.`, { cause });
57
+ }
58
+ // src/CredentialEntries/class.ts
59
+ /**
60
+ * Maintains the database's credential entries.
61
+ *
62
+ * Entries are identified by credential ID and synchronized through
63
+ * a sequenced array. Changes are persisted as encrypted snapshots.
64
+ */
65
+ var CredentialEntries = class {
66
+ id;
67
+ cipherKey;
68
+ sessionCredentialID;
69
+ state;
70
+ deltaBuffer = new Array();
71
+ eventTarget;
72
+ /**
73
+ * Creates a credential entries list.
74
+ *
75
+ * @param id The identifier of the persisted entries object.
76
+ * @param cipherKey The key used to encrypt the entries object.
77
+ * @param sessionCredentialID The credential ID of the current session.
78
+ * @param actorID The actor identifier used by the sequenced array.
79
+ * @param trustedSnapshot An optional snapshot used to initialize the state.
80
+ */
81
+ constructor(id, cipherKey, sessionCredentialID, actorID, trustedSnapshot) {
82
+ this.id = id;
83
+ this.cipherKey = cipherKey;
84
+ this.sessionCredentialID = sessionCredentialID;
85
+ try {
86
+ this.state = new _sovereignbase_sequenced.Sequenced.Array(actorID, trustedSnapshot);
87
+ const debouncedDispatch = (0, _sovereignbase_utils.afterIdleFor)(250, () => {
88
+ Explorer.dispatchEvent("delta", ["credentialEntries", this.deltaBuffer.splice(0)]);
89
+ });
90
+ this.state.addEventListener("delta", ({ detail }) => {
91
+ this.deltaBuffer.push(...detail);
92
+ debouncedDispatch();
93
+ });
94
+ const debouncedSave = (0, _sovereignbase_utils.afterIdleFor)(250, async (snapshot) => {
95
+ await Explorer.storeObjectByID(this.id, snapshot, this.cipherKey);
96
+ });
97
+ this.state.addEventListener("snapshot", ({ detail }) => {
98
+ debouncedSave(detail);
99
+ });
100
+ this.state.addEventListener("change", ({ detail }) => {
101
+ this.dispatchEvent("change", detail);
102
+ });
103
+ const seen = /* @__PURE__ */ new Set();
104
+ const duplicates = [];
105
+ for (let index = 0; index < this.state.length; index++) {
106
+ const entry = this.state.at(index);
107
+ if (!entry) continue;
108
+ if (seen.has(entry.id)) duplicates.push(index);
109
+ else seen.add(entry.id);
110
+ }
111
+ for (let index = duplicates.length - 1; index >= 0; index--) this.state.delete(duplicates[index]);
112
+ if (duplicates.length > 0 || this.deltaBuffer.length > 0) this.state.snapshot();
113
+ } catch (cause) {
114
+ throw unknownError(cause, "CredentialEntries.constructor()");
115
+ }
116
+ }
117
+ /**
118
+ * Creates or updates a credential entry.
119
+ *
120
+ * Updates the credential's last-used timestamp and the corresponding
121
+ * user agent's last-seen timestamp. Existing properties are preserved
122
+ * unless replacements are provided.
123
+ *
124
+ * @param credentialEvent The credential properties to apply.
125
+ * @throws {ExplorerError} If the event is invalid or setup properties are missing.
126
+ */
127
+ record(credentialEvent) {
128
+ try {
129
+ if (!credentialEvent || typeof credentialEvent !== "object") throw new ExplorerError("INVALID_CREDENTIAL_EVENT", "A credential event must be an object.");
130
+ const { id, timestamp, userAgent, name, entropy, storage } = credentialEvent;
131
+ if (typeof id !== "string" || typeof timestamp !== "number" || !Number.isFinite(timestamp) || typeof userAgent !== "string") throw new ExplorerError("INVALID_CREDENTIAL_EVENT", "A credential event requires an ID, a finite timestamp, and a user agent.");
132
+ let existing;
133
+ for (let index = this.state.length - 1; index >= 0; index--) {
134
+ const entry = this.state.at(index);
135
+ if (entry?.id === id) {
136
+ existing = entry;
137
+ break;
138
+ }
139
+ }
140
+ if (!existing && (typeof name !== "string" || !(entropy instanceof Uint8Array) || typeof storage !== "string")) throw new ExplorerError("MISSING_CREDENTIAL_SETUP_PROPERTIES", "A new credential requires a name, entropy, and binding storage.");
141
+ const userAgents = existing?.userAgents.map((agent) => ({ ...agent })) ?? [];
142
+ const agent = userAgents.find((agent) => agent.name === userAgent);
143
+ if (agent) agent.lastSeen = Math.max(agent.lastSeen, timestamp);
144
+ else userAgents.push({
145
+ name: userAgent,
146
+ lastSeen: timestamp
147
+ });
148
+ const entry = {
149
+ id,
150
+ name: name ?? existing.name,
151
+ entropy: entropy ?? existing.entropy,
152
+ storage: storage ?? existing.storage,
153
+ lastUsed: Math.max(existing?.lastUsed ?? timestamp, timestamp),
154
+ userAgents
155
+ };
156
+ for (let index = this.state.length - 1; index >= 0; index--) if (this.state.at(index)?.id === id) this.state.delete(index);
157
+ this.state.unshift(entry);
158
+ this.state.snapshot();
159
+ } catch (cause) {
160
+ throw unknownError(cause, "CredentialEntries.record()");
161
+ }
162
+ }
163
+ /**
164
+ * Revokes a credential by deleting its persisted data and list entries.
165
+ *
166
+ * The list remains unchanged if deletion of the persisted credential fails.
167
+ *
168
+ * @param credentialID The identifier of the credential to revoke.
169
+ */
170
+ async revoke(credentialID) {
171
+ try {
172
+ let exists = false;
173
+ for (let index = this.state.length - 1; index >= 0; index--) {
174
+ if (this.state.at(index)?.id !== credentialID) continue;
175
+ exists = true;
176
+ break;
177
+ }
178
+ if (!exists) return;
179
+ await Explorer.deleteObjectByID(credentialID);
180
+ for (let index = this.state.length - 1; index >= 0; index--) if (this.state.at(index)?.id === credentialID) this.state.delete(index);
181
+ this.state.snapshot();
182
+ } catch (cause) {
183
+ throw unknownError(cause, "CredentialEntries.revoke()");
184
+ }
185
+ }
186
+ /**
187
+ * Returns the credential entries ordered by most recent use.
188
+ *
189
+ * Entries with equal timestamps are ordered by identifier.
190
+ */
191
+ list() {
192
+ try {
193
+ return this.state.slice().sort((a, b) => b.lastUsed - a.lastUsed || a.id.localeCompare(b.id));
194
+ } catch (cause) {
195
+ throw unknownError(cause, "CredentialEntries.list()");
196
+ }
197
+ }
198
+ /**
199
+ * Applies a sequenced delta to the credential entries list.
200
+ *
201
+ * @param delta The delta to apply.
202
+ */
203
+ apply(delta) {
204
+ try {
205
+ this.state.apply(delta);
206
+ this.state.snapshot();
207
+ } catch (cause) {
208
+ throw unknownError(cause, "CredentialEntries.apply()");
209
+ }
210
+ }
211
+ /**
212
+ * Merges a snapshot into the credential entries list.
213
+ *
214
+ * @param snapshot The snapshot to merge.
215
+ */
216
+ merge(snapshot) {
217
+ try {
218
+ this.state.merge(snapshot);
219
+ this.state.snapshot();
220
+ } catch (cause) {
221
+ throw unknownError(cause, "CredentialEntries.merge()");
222
+ }
223
+ }
224
+ /**
225
+ * Registers an event listener for the specified event type.
226
+ *
227
+ * @param type The event type.
228
+ * @param listener The event listener, or `null`.
229
+ * @param options The event listener options.
230
+ */
231
+ addEventListener(type, listener, options) {
232
+ try {
233
+ (this.eventTarget ??= new EventTarget()).addEventListener(type, listener, options);
234
+ } catch (cause) {
235
+ throw unknownError(cause, "CredentialEntries.addEventListener()");
236
+ }
237
+ }
238
+ /**
239
+ * Removes an event listener previously registered with
240
+ * {@link addEventListener}.
241
+ *
242
+ * @param type The event type.
243
+ * @param listener The event listener to remove, or `null`.
244
+ * @param options The event listener options.
245
+ */
246
+ removeEventListener(type, listener, options) {
247
+ try {
248
+ this.eventTarget?.removeEventListener(type, listener, options);
249
+ } catch (cause) {
250
+ throw unknownError(cause, "CredentialEntries.removeEventListener()");
251
+ }
252
+ }
253
+ /**
254
+ * Dispatches an event to the registered listeners.
255
+ *
256
+ * @param type The event type.
257
+ * @param detail The value exposed through `CustomEvent.detail`.
258
+ */
259
+ dispatchEvent(type, detail) {
260
+ try {
261
+ this.eventTarget?.dispatchEvent(new CustomEvent(type, { detail }));
262
+ } catch (cause) {
263
+ throw unknownError(cause, "CredentialEntries.dispatchEvent()");
264
+ }
265
+ }
266
+ };
267
+ // src/RecentEntries/class.ts
268
+ /**
269
+ * Maintains the ordered list of recently accessed objects.
270
+ *
271
+ * Entries are ordered from most recently accessed to least recently accessed,
272
+ * deduplicated by identifier, and limited to 20 entries.
273
+ */
274
+ var RecentEntries = class {
275
+ id;
276
+ cipherKey;
277
+ state;
278
+ deltaBuffer = new Array();
279
+ eventTarget;
280
+ /**
281
+ * Creates a recent entries list.
282
+ *
283
+ * @param id The identifier of the persisted recent entries object.
284
+ * @param cipherKey The key used to encrypt the entries object.
285
+ * @param actorID The actor identifier used by the sequenced array.
286
+ * @param trustedSnapshot An optional snapshot used to initialize the state.
287
+ */
288
+ constructor(id, cipherKey, actorID, trustedSnapshot) {
289
+ this.id = id;
290
+ this.cipherKey = cipherKey;
291
+ try {
292
+ this.state = new _sovereignbase_sequenced.Sequenced.Array(actorID, trustedSnapshot);
293
+ const debouncedDispatch = (0, _sovereignbase_utils.afterIdleFor)(250, () => {
294
+ Explorer.dispatchEvent("delta", ["recentEntries", this.deltaBuffer.splice(0)]);
295
+ });
296
+ this.state.addEventListener("delta", ({ detail }) => {
297
+ this.deltaBuffer.push(...detail);
298
+ debouncedDispatch();
299
+ });
300
+ const debouncedSave = (0, _sovereignbase_utils.afterIdleFor)(250, async (snapshot) => {
301
+ await Explorer.storeObjectByID(this.id, snapshot, this.cipherKey);
302
+ });
303
+ this.state.addEventListener("snapshot", ({ detail }) => {
304
+ debouncedSave(detail);
305
+ });
306
+ this.state.addEventListener("change", ({ detail }) => {
307
+ this.dispatchEvent("change", detail);
308
+ });
309
+ const seen = /* @__PURE__ */ new Set();
310
+ const duplicates = [];
311
+ for (let index = 0; index < this.state.length; index++) {
312
+ const entry = this.state.at(index);
313
+ if (!entry) continue;
314
+ if (seen.has(entry.id) || seen.size >= 20) duplicates.push(index);
315
+ else seen.add(entry.id);
316
+ }
317
+ for (let index = duplicates.length - 1; index >= 0; index--) this.state.delete(duplicates[index]);
318
+ if (duplicates.length > 0 || this.deltaBuffer.length > 0) this.state.snapshot();
319
+ } catch (cause) {
320
+ throw unknownError(cause, "RecentEntries.constructor()");
321
+ }
322
+ }
323
+ /**
324
+ * Marks an entry as most recently accessed.
325
+ *
326
+ * Any existing entry with the same identifier is removed before the new
327
+ * entry is inserted at the beginning of the list.
328
+ *
329
+ * @param accessed The entry that was accessed.
330
+ */
331
+ update(accessed) {
332
+ try {
333
+ for (let index = this.state.length - 1; index >= 0; index--) if (this.state.at(index)?.id === accessed.id) this.state.delete(index);
334
+ this.state.unshift(accessed);
335
+ while (this.state.length > 20) this.state.pop();
336
+ this.state.snapshot();
337
+ } catch (cause) {
338
+ throw unknownError(cause, "RecentEntries.update()");
339
+ }
340
+ }
341
+ /**
342
+ * Removes an entry from the recent entries list.
343
+ *
344
+ * The referenced object is not deleted.
345
+ *
346
+ * @param id The identifier of the entry to remove.
347
+ */
348
+ delete(id) {
349
+ try {
350
+ let deleted = false;
351
+ for (let index = this.state.length - 1; index >= 0; index--) {
352
+ if (this.state.at(index)?.id !== id) continue;
353
+ this.state.delete(index);
354
+ deleted = true;
355
+ }
356
+ if (deleted) this.state.snapshot();
357
+ } catch (cause) {
358
+ throw unknownError(cause, "RecentEntries.delete()");
359
+ }
360
+ }
361
+ /**
362
+ * Returns the recent entries ordered by most recent access.
363
+ */
364
+ list() {
365
+ try {
366
+ return this.state.slice().sort((a, b) => b.dateAccessed - a.dateAccessed || a.id.localeCompare(b.id));
367
+ } catch (cause) {
368
+ throw unknownError(cause, "RecentEntries.list()");
369
+ }
370
+ }
371
+ /**
372
+ * Applies a sequenced delta to the recent entries list.
373
+ *
374
+ * @param delta The delta to apply.
375
+ */
376
+ apply(delta) {
377
+ try {
378
+ this.state.apply(delta);
379
+ this.state.snapshot();
380
+ } catch (cause) {
381
+ throw unknownError(cause, "RecentEntries.apply()");
382
+ }
383
+ }
384
+ /**
385
+ * Merges a snapshot into the recent entries list.
386
+ *
387
+ * @param snapshot The snapshot to merge.
388
+ */
389
+ merge(snapshot) {
390
+ try {
391
+ this.state.merge(snapshot);
392
+ this.state.snapshot();
393
+ } catch (cause) {
394
+ throw unknownError(cause, "RecentEntries.merge()");
395
+ }
396
+ }
397
+ /**
398
+ * Registers an event listener for the specified event type.
399
+ *
400
+ * @param type The event type.
401
+ * @param listener The event listener, or `null`.
402
+ * @param options The event listener options.
403
+ */
404
+ addEventListener(type, listener, options) {
405
+ try {
406
+ (this.eventTarget ??= new EventTarget()).addEventListener(type, listener, options);
407
+ } catch (cause) {
408
+ throw unknownError(cause, "RecentEntries.addEventListener()");
409
+ }
410
+ }
411
+ /**
412
+ * Removes an event listener previously registered with
413
+ * {@link addEventListener}.
414
+ *
415
+ * @param type The event type.
416
+ * @param listener The event listener to remove, or `null`.
417
+ * @param options The event listener options.
418
+ */
419
+ removeEventListener(type, listener, options) {
420
+ try {
421
+ this.eventTarget?.removeEventListener(type, listener, options);
422
+ } catch (cause) {
423
+ throw unknownError(cause, "RecentEntries.removeEventListener()");
424
+ }
425
+ }
426
+ /**
427
+ * Dispatches an event to the registered listeners.
428
+ *
429
+ * @param type The event type.
430
+ * @param detail The value exposed through `CustomEvent.detail`.
431
+ */
432
+ dispatchEvent(type, detail) {
433
+ try {
434
+ this.eventTarget?.dispatchEvent(new CustomEvent(type, { detail }));
435
+ } catch (cause) {
436
+ throw unknownError(cause, "RecentEntries.dispatchEvent()");
437
+ }
438
+ }
439
+ };
440
+ // src/class.ts
441
+ /**
442
+ * Provides authentication, encrypted object storage, and access to
443
+ * the database's synchronized entries.
444
+ *
445
+ * Maintains the authenticated database context and exposes static methods
446
+ * for managing stored objects, observing entries, and applying remote deltas.
447
+ */
448
+ var Explorer = class {
449
+ /** The identifier of the authenticated database. */
450
+ static databaseID;
451
+ /** Indicates whether the database has been authenticated. */
452
+ static isAuthenticated;
453
+ static storageURL;
454
+ static eventTarget;
455
+ static databaseSecret;
456
+ static sessionCredential = {};
457
+ /**
458
+ * Caches cipher keys by object identifier.
459
+ *
460
+ * Existing entries are preserved when an object is accessed with
461
+ * a cipher key.
462
+ */
463
+ static cipherKeyCache = /* @__PURE__ */ new Map();
464
+ /**
465
+ * Authenticates a database using a data PIN and device-bound entropy.
466
+ *
467
+ * Derives the credential and database identifiers from cryptographic
468
+ * secrets. When setup parameters are provided, creates and stores a
469
+ * new credential. Otherwise, loads the existing credential.
470
+ *
471
+ * Records the authenticated credential in the database's credential list.
472
+ *
473
+ * @param dataPIN The PIN used to derive the credential and database secrets.
474
+ * @param storageURL The base URL used to access persisted database objects.
475
+ * @param setupParams Optional parameters for creating a new credential.
476
+ * @returns The authentication result.
477
+ */
478
+ static async authenticate(dataPIN, storageURL, setupParams) {
479
+ try {
480
+ this.storageURL = storageURL;
481
+ const deviceEntropy = await (0, _sovereignbase_hardware_bound.deriveDeviceEntropy)();
482
+ if (!deviceEntropy) return "authenticator-error";
483
+ this.sessionCredential = {
484
+ timestamp: Date.now(),
485
+ userAgent: (0, _sovereignbase_dom_utils.readableUserAgent)()
486
+ };
487
+ const dataPINBytes = _sovereignbase_bytecodec.Bytes.utf8.decode(dataPIN);
488
+ const credentialSecret = await _sovereignbase_bytecodec.Bytes.derive(deviceEntropy, dataPINBytes, 32);
489
+ const credentialID = await _sovereignbase_cryptosuite.Cryptographic.identifier.derive(credentialSecret, _sovereignbase_bytecodec.Bytes.utf8.decode("@sovereignbase/explorer:CredentialID"), 32);
490
+ this.sessionCredential.id = credentialID;
491
+ const credentialCipherKey = await _sovereignbase_cryptosuite.Cryptographic.cipherMessage.deriveKey(credentialSecret, _sovereignbase_bytecodec.Bytes.utf8.decode("@sovereignbase/explorer:CredentialCipherKey"));
492
+ let virtualEntropy;
493
+ if ((0, _sovereignbase_utils.isRecord)(setupParams)) {
494
+ virtualEntropy = _sovereignbase_bytecodec.Bytes.generate(64);
495
+ await this.storeObjectByID(credentialID, virtualEntropy, credentialCipherKey);
496
+ this.sessionCredential.name = setupParams.credentialName;
497
+ this.sessionCredential.entropy = deviceEntropy;
498
+ this.sessionCredential.storage = setupParams.bindingStorage;
499
+ } else {
500
+ const result = await this.loadObjectByID(credentialID, credentialCipherKey);
501
+ if (!(result instanceof Uint8Array) || result.byteLength !== 64) return "invalid-data-pin";
502
+ virtualEntropy = result;
503
+ }
504
+ this.databaseSecret = await _sovereignbase_bytecodec.Bytes.derive(virtualEntropy, dataPINBytes, 64);
505
+ this.databaseID = await _sovereignbase_cryptosuite.Cryptographic.identifier.derive(this.databaseSecret, _sovereignbase_bytecodec.Bytes.utf8.decode("@sovereignbase/explorer:DatabaseID"), 32);
506
+ this.isAuthenticated = true;
507
+ (await this.loadCredentialEntries()).record(this.sessionCredential);
508
+ delete this.sessionCredential;
509
+ this.dispatchEvent("authenticated", true);
510
+ return "authenticated";
511
+ } catch (cause) {
512
+ throw unknownError(cause, "Explorer.authenticate()");
513
+ }
514
+ }
515
+ /**
516
+ * Permanently revokes a credential and deletes its persisted data.
517
+ *
518
+ * Removes the credential from the database's registered credentials.
519
+ *
520
+ * @param credentialID The identifier of the credential to revoke.
521
+ * @throws {ExplorerError} If the database is not authenticated.
522
+ */
523
+ static async permanentlyDeleteCredential(credentialID) {
524
+ try {
525
+ await (await this.loadCredentialEntries()).revoke(credentialID);
526
+ return;
527
+ } catch (cause) {
528
+ throw unknownError(cause, "Explorer.permanentlyDeleteCredential()");
529
+ }
530
+ }
531
+ /**
532
+ * Returns the registered credentials and optionally observes their changes.
533
+ *
534
+ * The returned tuple contains a cleanup function, the current credential
535
+ * entries, and the identifier of the current session's credential.
536
+ *
537
+ * The cleanup function removes the registered change listener, if any.
538
+ *
539
+ * @param onChange An optional callback invoked when the entries change.
540
+ * @returns The cleanup function, credential entries, and session credential ID.
541
+ * @throws {ExplorerError} If the database is not authenticated.
542
+ */
543
+ static async listCredentialEntries(onChange) {
544
+ try {
545
+ const credentialEntries = await this.loadCredentialEntries();
546
+ const listener = onChange ? ({ detail }) => onChange(detail) : void 0;
547
+ if (listener) credentialEntries.addEventListener("change", listener);
548
+ return [
549
+ () => {
550
+ if (listener) credentialEntries.removeEventListener("change", listener);
551
+ },
552
+ credentialEntries.list(),
553
+ credentialEntries.sessionCredentialID
554
+ ];
555
+ } catch (cause) {
556
+ throw unknownError(cause, "Explorer.listCredentialEntries()");
557
+ }
558
+ }
559
+ /**
560
+ * Returns the recently accessed objects and optionally observes their changes.
561
+ *
562
+ * The returned tuple contains a cleanup function and the current recent
563
+ * entries. The cleanup function removes the registered change listener,
564
+ * if any.
565
+ *
566
+ * @param onChange An optional callback invoked when the entries change.
567
+ * @returns The cleanup function and recent entries.
568
+ * @throws {ExplorerError} If the database is not authenticated.
569
+ */
570
+ static async listRecentEntries(onChange) {
571
+ try {
572
+ const recentEntries = await this.loadRecentEntries();
573
+ const listener = onChange ? ({ detail }) => onChange(detail) : void 0;
574
+ if (listener) recentEntries.addEventListener("change", listener);
575
+ return [() => {
576
+ if (listener) recentEntries.removeEventListener("change", listener);
577
+ }, recentEntries.list()];
578
+ } catch (cause) {
579
+ throw unknownError(cause, "Explorer.listRecentEntries()");
580
+ }
581
+ }
582
+ /**
583
+ * Loads an encrypted object using its identifier and cipher key.
584
+ *
585
+ * Caches the cipher key if the identifier has not been encountered before.
586
+ *
587
+ * @typeParam T The expected type of the loaded object.
588
+ * @param id The identifier of the object to load.
589
+ * @param cipherKey The key used to decrypt the object.
590
+ * @param onNetworkResponse An optional callback for network responses.
591
+ * @returns The loaded object, or `undefined` if no object is available.
592
+ */
593
+ static async loadObjectByID(id, cipherKey, onNetworkResponse) {
594
+ try {
595
+ if (!this.cipherKeyCache.has(id)) this.cipherKeyCache.set(id, cipherKey);
596
+ return await (0, _sovereignbase_storage.loadObject)(this.storageURL + id, cipherKey, false, onNetworkResponse);
597
+ } catch (cause) {
598
+ throw unknownError(cause, "Explorer.loadObjectByID()");
599
+ }
600
+ }
601
+ /**
602
+ * Encrypts and stores an object using its identifier and cipher key.
603
+ *
604
+ * Caches the cipher key if the identifier has not been encountered before.
605
+ *
606
+ * @typeParam T The type of the object to store.
607
+ * @param id The identifier of the object to store.
608
+ * @param object The object to encrypt and store.
609
+ * @param cipherKey The key used to encrypt the object.
610
+ */
611
+ static async storeObjectByID(id, object, cipherKey) {
612
+ try {
613
+ if (!this.cipherKeyCache.has(id)) this.cipherKeyCache.set(id, cipherKey);
614
+ await (0, _sovereignbase_storage.storeObject)(this.storageURL + id, object, cipherKey);
615
+ return;
616
+ } catch (cause) {
617
+ throw unknownError(cause, "Explorer.storeObjectByID()");
618
+ }
619
+ }
620
+ /**
621
+ * Deletes a persisted object using its identifier.
622
+ *
623
+ * @param id The identifier of the object to delete.
624
+ */
625
+ static async deleteObjectByID(id) {
626
+ try {
627
+ await (0, _sovereignbase_storage.deleteObject)(this.storageURL + id);
628
+ (await this.loadRecentEntries()).delete(id);
629
+ return;
630
+ } catch (cause) {
631
+ throw unknownError(cause, "Explorer.deleteObjectByID()");
632
+ }
633
+ }
634
+ /**
635
+ * Schedules the application of a synchronized Explorer delta.
636
+ *
637
+ * Recognized deltas are forwarded to their corresponding entries list.
638
+ * Invalid or unrecognized delta types are ignored.
639
+ *
640
+ * Processing is scheduled in a microtask and is not awaited by the caller.
641
+ *
642
+ * @param data The delta to apply.
643
+ */
644
+ static apply(data) {
645
+ queueMicrotask(async () => {
646
+ try {
647
+ if (!this.isExplorerDelta(data)) return;
648
+ switch (data[0]) {
649
+ case "recentEntries":
650
+ (await this.loadRecentEntries()).apply(data[1]);
651
+ break;
652
+ case "credentialEntries": (await this.loadCredentialEntries()).apply(data[1]);
653
+ }
654
+ return;
655
+ } catch (cause) {
656
+ throw unknownError(cause, "Explorer.apply()");
657
+ }
658
+ });
659
+ }
660
+ /**
661
+ * Registers an event listener for the specified event type.
662
+ *
663
+ * @param type The event type.
664
+ * @param listener The event listener, or `null`.
665
+ * @param options The event listener options.
666
+ */
667
+ static addEventListener(type, listener, options) {
668
+ try {
669
+ (this.eventTarget ??= new EventTarget()).addEventListener(type, listener, options);
670
+ } catch (cause) {
671
+ throw unknownError(cause, "Explorer.addEventListener()");
672
+ }
673
+ }
674
+ /**
675
+ * Removes an event listener previously registered with
676
+ * {@link addEventListener}.
677
+ *
678
+ * @param type The event type.
679
+ * @param listener The event listener to remove, or `null`.
680
+ * @param options The event listener options.
681
+ */
682
+ static removeEventListener(type, listener, options) {
683
+ try {
684
+ this.eventTarget?.removeEventListener(type, listener, options);
685
+ } catch (cause) {
686
+ throw unknownError(cause, "Explorer.removeEventListener()");
687
+ }
688
+ }
689
+ /**
690
+ * Dispatches an event to the registered listeners.
691
+ *
692
+ * @param type The event type.
693
+ * @param detail The value exposed through `CustomEvent.detail`.
694
+ */
695
+ static dispatchEvent(type, detail) {
696
+ try {
697
+ this.eventTarget?.dispatchEvent(new CustomEvent(type, { detail }));
698
+ } catch (cause) {
699
+ throw unknownError(cause, "Explorer.dispatchEvent()");
700
+ }
701
+ }
702
+ /**
703
+ * Determines whether a value has the basic structure of an Explorer delta.
704
+ *
705
+ * @param data The value to inspect.
706
+ * @returns Whether the value has a string discriminator.
707
+ */
708
+ static isExplorerDelta(data) {
709
+ return Array.isArray(data) && typeof data[0] === "string";
710
+ }
711
+ static recentEntries;
712
+ /**
713
+ * Loads or returns the cached recent entries list.
714
+ *
715
+ * Derives the list identifier and cipher key from the database secret
716
+ * and merges subsequent network responses into the loaded state.
717
+ *
718
+ * @returns The recent entries list.
719
+ * @throws {ExplorerError} If the database is not authenticated.
720
+ */
721
+ static async loadRecentEntries() {
722
+ try {
723
+ if (!this.isAuthenticated) throw new ExplorerError("NOT_AUTHENTICATED");
724
+ if (this.recentEntries) return this.recentEntries;
725
+ const id = await _sovereignbase_cryptosuite.Cryptographic.identifier.derive(this.databaseSecret, _sovereignbase_bytecodec.Bytes.utf8.decode("@sovereignbase/explorer:RecentEntriesID"), 32);
726
+ const ck = await _sovereignbase_cryptosuite.Cryptographic.cipherMessage.deriveKey(this.databaseSecret, _sovereignbase_bytecodec.Bytes.utf8.decode("@sovereignbase/explorer:RecentEntriesCipherKey"));
727
+ const trustedSnapshot = await this.loadObjectByID(id, ck, (snapshot) => void this.recentEntries.merge(snapshot));
728
+ this.recentEntries = new RecentEntries(id, ck, 0, trustedSnapshot);
729
+ return this.recentEntries;
730
+ } catch (cause) {
731
+ throw unknownError(cause, "Explorer.loadRecentEntries()");
732
+ }
733
+ }
734
+ static credentialEntries;
735
+ /**
736
+ * Loads or returns the cached credential entries list.
737
+ *
738
+ * Derives the list identifier and cipher key from the database secret
739
+ * and merges subsequent network responses into the loaded state.
740
+ *
741
+ * @returns The credential entries list.
742
+ * @throws {ExplorerError} If the database is not authenticated.
743
+ */
744
+ static async loadCredentialEntries() {
745
+ try {
746
+ if (!this.isAuthenticated) throw new ExplorerError("NOT_AUTHENTICATED");
747
+ if (this.credentialEntries) return this.credentialEntries;
748
+ const id = await _sovereignbase_cryptosuite.Cryptographic.identifier.derive(this.databaseSecret, _sovereignbase_bytecodec.Bytes.utf8.decode("@sovereignbase/explorer:CredentialEntriesID"), 32);
749
+ const ck = await _sovereignbase_cryptosuite.Cryptographic.cipherMessage.deriveKey(this.databaseSecret, _sovereignbase_bytecodec.Bytes.utf8.decode("@sovereignbase/explorer:CredentialEntriesCipherKey"));
750
+ const trustedSnapshot = await this.loadObjectByID(id, ck, (snapshot) => void this.credentialEntries.merge(snapshot));
751
+ this.credentialEntries = new CredentialEntries(id, ck, this.sessionCredential.id, 0, trustedSnapshot);
752
+ return this.credentialEntries;
753
+ } catch (cause) {
754
+ throw unknownError(cause, "Explorer.loadCredentialEntries()");
755
+ }
756
+ }
757
+ };
758
+ exports.Explorer = Explorer;
759
+
760
+ //# sourceMappingURL=class.cjs.map