@myfield/sdk 0.9.2 → 0.9.3

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/src/facade.ts DELETED
@@ -1,698 +0,0 @@
1
- // Public facade (docs/API.md): createInstance / Instance / Bucket.
2
- //
3
- // A bucket is a local-first end-to-end-encrypted object KV. Local CRUD works
4
- // with no account and no network; connect() is the single network/identity
5
- // boundary. `namespace` scopes ALL local persistence (instance keys, auth
6
- // context, sessions, objects, the internal index) and never reaches the
7
- // wire; bucket `id` is the app-local authorization label, while sync uses
8
- // the remote bucket id returned in the grant envelope. `~index` is local
9
- // only; objects carry their app id in `~id` (docs/BUCKET-SPEC.md).
10
-
11
- import { BucketClient, type BucketTransportLike, type ChangeSource } from "./bucket/client.ts";
12
- import type { PayloadDoc } from "./bucket/format.ts";
13
- import {
14
- canonicalizeFieldValue,
15
- createBucketBinaryValue,
16
- fieldValueToCanonicalJson,
17
- type BinaryInput,
18
- type BinaryOptions,
19
- type BucketBinaryValue,
20
- } from "./bucket/binary.ts";
21
- import {
22
- createIndexedDbStorageAdapter,
23
- createNamespacedMemoryStorageAdapter,
24
- type StorageAdapter,
25
- } from "./bucket/store.ts";
26
- import { BucketTransport, BucketTransportError, OfflineError } from "./bucket/transport.ts";
27
- import { isValidBucketId } from "./auth/identifiers.ts";
28
- import { ClientError, NotConnectedError } from "./errors.ts";
29
- import { randomId } from "./internal/encoding.ts";
30
- import { resolveAppId } from "./auth/identifiers.ts";
31
- import type { InstanceKey } from "./auth/keys.ts";
32
-
33
- import { createInstanceConnection, normalizeAuthUrl } from "./remote/connection.ts";
34
- import type { RemoteBucket } from "./remote/bucket.ts";
35
-
36
- const INDEX_OBJECT_ID = "~index";
37
- const ID_FIELD = "~id";
38
- const DELETED_FIELD = "~deleted";
39
- const RESERVED_PREFIX = "~";
40
-
41
- export type CreateInstanceOptions = {
42
- namespace?: string;
43
- storage?: "indexeddb" | "memory";
44
- appId?: string;
45
- authUrl?: string;
46
- };
47
-
48
- export type BucketState = "disconnected" | "connecting" | "connected";
49
-
50
- export type ListEntry = { id: string; updatedAt: string; deleted?: true };
51
-
52
- export type ConnectOptions = {
53
- autoSync?: boolean;
54
- };
55
-
56
- export type { BinaryInput, BinaryOptions, BucketBinaryValue };
57
-
58
- export type Bucket = {
59
- readonly id: string;
60
- readonly state: BucketState;
61
- binary(input: BinaryInput | BucketBinaryValue, options?: BinaryOptions): BucketBinaryValue;
62
- /** @deprecated No-op kept for compatibility; operations initialize storage lazily. */
63
- ready(): Promise<void>;
64
- put(objectId: string, object: Record<string, unknown>): Promise<void>;
65
- get(objectId: string): Promise<Record<string, unknown> | null>;
66
- update(objectId: string, fields: Record<string, unknown>): Promise<void>;
67
- delete(objectId: string): Promise<void>;
68
- list(options?: { prefix?: string; includeDeleted?: boolean }): Promise<ListEntry[]>;
69
- resume(): Promise<BucketState>;
70
- connect(options?: ConnectOptions): Promise<BucketState>;
71
- disconnect(): Promise<void>;
72
- sync(): Promise<void>;
73
- setAutoSync(enabled: boolean): void;
74
- on(event: "state", handler: (state: BucketState, detail?: string) => void): () => void;
75
- on(event: "change", handler: (objectId: string) => void): () => void;
76
- dispose(): void;
77
- // Internal test seam: binds a transport as if connect() succeeded, with
78
- // identity wire ids (blinding has its own unit tests). Not public API.
79
- __bindTestTransport(transport: BucketTransportLike): void;
80
- };
81
-
82
- export type Instance = {
83
- readonly namespace: string;
84
- readonly remote: { getBucket(): RemoteBucket };
85
- readonly state: BucketState;
86
- getBucket(): Bucket;
87
- getKey(): Promise<InstanceKey | null>;
88
- createKey(): Promise<InstanceKey>;
89
- importKey(key: InstanceKey): Promise<void>;
90
- removeKey(): Promise<void>;
91
- resume(options?: { autoSync?: boolean }): Promise<BucketState>;
92
- connect(options?: { autoSync?: boolean }): Promise<BucketState>;
93
- disconnect(): Promise<void>;
94
- on(event: "state", handler: (state: BucketState, error?: ClientError) => void): () => void;
95
- createBucket(options: { id: string }): Bucket;
96
- };
97
-
98
- export const instanceTestCleanup = new WeakMap<Instance, () => void>();
99
-
100
- export function createInstance(appId: string): Instance;
101
- export function createInstance(options?: CreateInstanceOptions): Instance;
102
- export function createInstance(input: string | CreateInstanceOptions = {}, ...extra: unknown[]): Instance {
103
- if (typeof input === "string" && extra.length) throw new ClientError("INVALID_INPUT", "createInstance accepts an appId or an options object, without additional arguments");
104
- const options: CreateInstanceOptions = typeof input === "string" ? { appId: input } : input;
105
- if (!options || typeof options !== "object" || Array.isArray(options)) throw new ClientError("INVALID_INPUT", "Instance options are required");
106
- if (["authStorage", "dbName", "storeName"].some(key => key in options)) throw new ClientError("INVALID_INPUT", "Custom database configuration is not supported");
107
- const authUrl = options.authUrl === undefined ? undefined : normalizeAuthUrl(options.authUrl);
108
- const explicitAppId = options.appId === undefined ? undefined : resolveAppId(options.appId);
109
- let resolvedAppId = explicitAppId;
110
- const getAppId = () => resolvedAppId ??= resolveAppId();
111
- const namespace = normalizeNamespace(options.namespace === undefined ? explicitAppId : String(options.namespace).trim());
112
- const storageKind = options.storage || "indexeddb";
113
-
114
- const baseAdapter =
115
- storageKind === "memory"
116
- ? createNamespacedMemoryStorageAdapter(`myfield-sdk:${namespace}`)
117
- : createIndexedDbStorageAdapter({ dbName: `myfield-sdk:${namespace}` });
118
- const authAdapter = prefixedAdapter(baseAdapter, "auth:");
119
-
120
- const buckets = new Map<string, ReturnType<typeof createBucketFacade>>();
121
- const connections = new Map<string, ReturnType<typeof createInstanceConnection>>();
122
- const connectionDeps = { getAppId, data: baseAdapter, auth: authAdapter,
123
- hasActiveConnection: () => connection.active || [...connections.values()].some(value => value.active),
124
- persistent: storageKind !== "memory", authUrl };
125
- const connection = createInstanceConnection(connectionDeps);
126
- let disposed = false;
127
-
128
- function getLocalBucket(bucketId: string) {
129
- if (disposed) throw new ClientError("INVALID_STATE", "Instance runtime has stopped");
130
- const existing = buckets.get(bucketId);
131
- if (existing) return existing;
132
- let isDefault = false;
133
- try { isDefault = bucketId === getAppId(); } catch {}
134
- let resource = isDefault ? connection : connections.get(bucketId);
135
- if (!resource) {
136
- resource = createInstanceConnection({ ...connectionDeps, getBucketId: () => bucketId });
137
- connections.set(bucketId, resource);
138
- }
139
- const owned = resource;
140
- const runtime = createBucketFacade({ bucketId, dataAdapter: baseAdapter, connection: owned, onDispose: () => {
141
- if (buckets.get(bucketId) === runtime) buckets.delete(bucketId);
142
- if (owned !== connection && connections.get(bucketId) === owned) {
143
- connections.delete(bucketId);
144
- owned.dispose();
145
- }
146
- } });
147
- buckets.set(bucketId, runtime);
148
- return runtime;
149
- }
150
-
151
- function startLocal(prompt: boolean, args: unknown[]): Promise<BucketState> {
152
- try {
153
- if (args.length > 1) throw new ClientError("INVALID_INPUT", "Connection accepts one options object");
154
- const options = args[0];
155
- if (options !== undefined && (!options || typeof options !== "object" || Array.isArray(options)
156
- || Object.keys(options).some(key => key !== "autoSync")
157
- || ("autoSync" in options && options.autoSync !== undefined && typeof options.autoSync !== "boolean"))) {
158
- throw new ClientError("INVALID_INPUT", "Only autoSync is supported");
159
- }
160
- const runtime = getLocalBucket(getAppId());
161
- return runtime.connectInstance(prompt, (options as { autoSync?: boolean } | undefined)?.autoSync);
162
- } catch (error) { return Promise.reject(error); }
163
- }
164
-
165
- const instance: Instance = {
166
- namespace,
167
- remote: connection.remote,
168
- get state() { return connection.state; },
169
- getBucket: () => getLocalBucket(getAppId()).bucket,
170
- resume: (...args: unknown[]) => startLocal(false, args),
171
- on: connection.on,
172
- connect: (...args: unknown[]) => startLocal(true, args),
173
- getKey: connection.getKey,
174
- createKey: connection.createKey,
175
- importKey: connection.importKey,
176
- removeKey: connection.removeKey,
177
- disconnect: connection.disconnect,
178
- createBucket(bucketOptions) {
179
- const bucketId = String(bucketOptions?.id || "").trim();
180
- if (!bucketId) throw new Error("bucket id is required");
181
- if (!isValidBucketId(bucketId)) throw new Error("invalid bucketId");
182
- return getLocalBucket(bucketId).bucket;
183
- },
184
- };
185
- if (explicitAppId) getLocalBucket(explicitAppId);
186
- instanceTestCleanup.set(instance, () => {
187
- disposed = true;
188
- for (const runtime of buckets.values()) runtime.bucket.dispose();
189
- for (const resource of connections.values()) resource.dispose();
190
- connection.dispose();
191
- });
192
- return instance;
193
- }
194
-
195
- // ---------------------------------------------------------------------------
196
-
197
- type BucketDeps = {
198
- bucketId: string;
199
- dataAdapter: StorageAdapter;
200
- connection: ReturnType<typeof createInstanceConnection>;
201
- onDispose?: () => void;
202
- };
203
-
204
- function createBucketFacade(deps: BucketDeps) {
205
- const { bucketId, dataAdapter, connection } = deps;
206
- const actorKey = `meta:actor`;
207
-
208
- let state: BucketState = connection.state;
209
- let client: BucketClient | null = null;
210
- let clientInit: Promise<BucketClient> | null = null;
211
- let liveTransport: BucketTransportLike | null = null;
212
- let liveWireId: ((appObjectId: string) => Promise<string>) | null = null;
213
- let autoSync = true;
214
- let syncIntervalMs: number | undefined;
215
- let disposed = false;
216
-
217
- let connectedAccess: ReturnType<typeof connection.getLocalAccess> | null = null;
218
- let activating: Promise<void> | null = null;
219
- let verifiedAccess: ReturnType<typeof connection.getLocalAccess> | null = null;
220
- let connecting: { operation: Promise<BucketState>; result: Promise<BucketState> } | null = null;
221
- let lastFailure: unknown = null;
222
-
223
- const listeners = { state: new Set<(s: BucketState, d?: string) => void>(), change: new Set<(id: string) => void>() };
224
-
225
- function emitState(next: BucketState, detail?: string): void {
226
- if (state !== next) {
227
- state = next;
228
- for (const handler of listeners.state) handler(next, detail);
229
- } else if (detail) {
230
- for (const handler of listeners.state) handler(next, detail);
231
- }
232
- }
233
-
234
- function emitChange(objectId: string): void {
235
- if (objectId.startsWith(RESERVED_PREFIX)) return;
236
- for (const handler of listeners.change) handler(objectId);
237
- }
238
-
239
- function ensureClient(): Promise<BucketClient> {
240
- if (clientInit) return clientInit;
241
- clientInit = (async () => {
242
- let actorId = await dataAdapter.get<string>(actorKey);
243
- if (typeof actorId !== "string" || !actorId) {
244
- actorId = randomId("actor");
245
- await dataAdapter.set(actorKey, actorId);
246
- }
247
- client = new BucketClient({
248
- transport: {
249
- pullHead(wireObjectId) {
250
- if (!liveTransport) return Promise.reject(new OfflineError());
251
- return liveTransport.pullHead(wireObjectId);
252
- },
253
- pullPayload(wireObjectId, versionId) {
254
- if (!liveTransport) return Promise.reject(new OfflineError());
255
- return liveTransport.pullPayload(wireObjectId, versionId);
256
- },
257
- push(wireObjectId, plaintext, expectedHeadVersionId) {
258
- if (!liveTransport) return Promise.reject(new OfflineError());
259
- return liveTransport.push(wireObjectId, plaintext, expectedHeadVersionId);
260
- },
261
- listHeads() {
262
- if (!liveTransport?.listHeads) return Promise.reject(new OfflineError());
263
- return liveTransport.listHeads();
264
- },
265
- },
266
- storage: dataAdapter,
267
- autoSync: autoSync && Boolean(liveTransport),
268
- actorId,
269
- localOnlyObjectIds: [INDEX_OBJECT_ID],
270
- validateRemote: assertRemoteObjectId,
271
- wireObjectId: (appObjectId) => {
272
- if (!liveWireId) return Promise.reject(new OfflineError());
273
- return liveWireId(appObjectId);
274
- },
275
- storagePrefix: `data:${bucketId}`,
276
- onChange: onClientChange,
277
- onSyncError: (objectId, error) => {
278
- if (error instanceof OfflineError) return;
279
- // Retryable sync failures surface as state detail without a state
280
- // change; local data is never affected.
281
- const detail = `sync error${objectId ? ` (${objectId})` : ""}: ${formatError(error)}`;
282
- if (connection.state === "connected") connection.report(localError(error, detail));
283
- else emitState(state, detail);
284
- },
285
- });
286
- return client;
287
- })();
288
- return clientInit;
289
- }
290
-
291
- function assertRemoteObjectId(objectId: string, doc: PayloadDoc): void {
292
- if (objectId.startsWith(RESERVED_PREFIX) || doc.t !== "lww-map") return;
293
- const remoteId = doc.fields[ID_FIELD]?.v;
294
- if (remoteId !== undefined && remoteId !== objectId) throw new Error(`object id mismatch for ${objectId}`);
295
- }
296
-
297
- // Refresh the index before emitting, so a change handler's list() sees it.
298
- const pendingIndexRefreshes = new Set<Promise<void>>();
299
- function onClientChange(objectId: string, source: ChangeSource): void {
300
- if (objectId.startsWith(RESERVED_PREFIX)) return;
301
- if (source === "local") {
302
- emitChange(objectId);
303
- return;
304
- }
305
- const refresh = refreshIndexEntry(objectId)
306
- .catch((error) => emitState(state, `index update failed (${objectId}): ${formatError(error)}`))
307
- .finally(() => {
308
- pendingIndexRefreshes.delete(refresh);
309
- emitChange(objectId);
310
- });
311
- pendingIndexRefreshes.add(refresh);
312
- }
313
-
314
- async function refreshIndexEntry(objectId: string): Promise<void> {
315
- const c = await ensureClient();
316
- const raw = await c.getFields(objectId);
317
- const latest = await c.lastModified(objectId);
318
- await upsertIndexEntry(objectId, raw?.[DELETED_FIELD] === true, latest ?? Date.now());
319
- }
320
-
321
- // ---- local object API ---------------------------------------------------
322
-
323
- function assertObjectId(objectId: string): void {
324
- if (typeof objectId !== "string" || !objectId) throw new Error("objectId must be a non-empty string");
325
- if (objectId.startsWith(RESERVED_PREFIX)) throw new Error(`object ids starting with "${RESERVED_PREFIX}" are reserved`);
326
- }
327
-
328
- function assertFieldNames(fields: Record<string, unknown>): void {
329
- if (!fields || typeof fields !== "object" || Array.isArray(fields)) throw new Error("fields must be a plain object");
330
- for (const name of Object.keys(fields)) {
331
- if (name.startsWith(RESERVED_PREFIX)) throw new Error(`field names starting with "${RESERVED_PREFIX}" are reserved`);
332
- }
333
- }
334
-
335
- // `rev` keeps two writes in one millisecond distinct.
336
- let lastIndexRev = 0;
337
- async function upsertIndexEntry(objectId: string, deleted: boolean, updatedAtMs = Date.now()): Promise<void> {
338
- const c = await ensureClient();
339
- lastIndexRev = Math.max(lastIndexRev + 1, Date.now());
340
- await c.setFields(INDEX_OBJECT_ID, {
341
- [objectId]: {
342
- updatedAt: new Date(updatedAtMs).toISOString(),
343
- rev: lastIndexRev,
344
- ...(deleted ? { deleted: true } : {}),
345
- },
346
- });
347
- }
348
-
349
- function publicView(raw: Record<string, unknown>): Record<string, unknown> {
350
- return Object.fromEntries(Object.entries(raw).filter(([name]) => !name.startsWith(RESERVED_PREFIX)));
351
- }
352
-
353
- // Fields whose JSON value is unchanged keep their existing LWW
354
- // timestamp/source (API.md): re-stamping unchanged fields would let a
355
- // device that re-saves whole objects steamroll other devices' concurrent
356
- // field edits.
357
- async function dropUnchanged(updates: Record<string, unknown>, known: Record<string, unknown>): Promise<Record<string, unknown>> {
358
- const changed: Record<string, unknown> = {};
359
- for (const [name, value] of Object.entries(updates)) {
360
- if (value === undefined) {
361
- if (name in known) changed[name] = undefined;
362
- continue;
363
- }
364
- const canonicalValue = await canonicalizeFieldValue(value);
365
- if (name in known && JSON.stringify(fieldValueToCanonicalJson(await canonicalizeFieldValue(known[name]))) === JSON.stringify(fieldValueToCanonicalJson(canonicalValue))) continue;
366
- changed[name] = value;
367
- }
368
- return changed;
369
- }
370
-
371
- function withObjectId(updates: Record<string, unknown>, objectId: string, known: Record<string, unknown>): Record<string, unknown> {
372
- return known[ID_FIELD] === objectId ? updates : { ...updates, [ID_FIELD]: objectId };
373
- }
374
-
375
- async function put(objectId: string, object: Record<string, unknown>): Promise<void> {
376
- assertObjectId(objectId);
377
- assertFieldNames(object);
378
- const c = await ensureClient();
379
- const known = (await c.getFields(objectId)) || {};
380
- const updates: Record<string, unknown> = { ...object };
381
- for (const name of Object.keys(known)) {
382
- if (!(name in object) && name !== ID_FIELD) updates[name] = undefined; // deletes locally known omitted fields (incl. a live ~deleted marker)
383
- }
384
- const changed = await dropUnchanged(updates, known);
385
- if (Object.keys(changed).length === 0) return; // full no-op: do not advance LWW state or the index entry
386
- await c.setFields(objectId, withObjectId(changed, objectId, known));
387
- await upsertIndexEntry(objectId, false);
388
- }
389
-
390
- async function update(objectId: string, fields: Record<string, unknown>): Promise<void> {
391
- assertObjectId(objectId);
392
- assertFieldNames(fields);
393
- const c = await ensureClient();
394
- const known = (await c.getFields(objectId)) || {};
395
- const updates: Record<string, unknown> = { ...fields };
396
- if (DELETED_FIELD in known) updates[DELETED_FIELD] = undefined; // update recreates a deleted object
397
- const changed = await dropUnchanged(updates, known);
398
- if (Object.keys(changed).length === 0) return;
399
- await c.setFields(objectId, withObjectId(changed, objectId, known));
400
- await upsertIndexEntry(objectId, false);
401
- }
402
-
403
- async function getObject(objectId: string): Promise<Record<string, unknown> | null> {
404
- assertObjectId(objectId);
405
- const c = await ensureClient();
406
- const raw = await c.getFields(objectId);
407
- if (!raw) return null;
408
- if (raw[DELETED_FIELD]) return null;
409
- const view = publicView(raw);
410
- return Object.keys(view).length === 0 && !(await hasIndexEntry(objectId)) ? null : view;
411
- }
412
-
413
- async function hasIndexEntry(objectId: string): Promise<boolean> {
414
- const c = await ensureClient();
415
- const index = (await c.getFields(INDEX_OBJECT_ID)) || {};
416
- return objectId in index;
417
- }
418
-
419
- async function deleteObject(objectId: string): Promise<void> {
420
- assertObjectId(objectId);
421
- const c = await ensureClient();
422
- const known = (await c.getFields(objectId)) || {};
423
- const updates: Record<string, unknown> = { [DELETED_FIELD]: true };
424
- for (const name of Object.keys(known)) {
425
- if (!name.startsWith(RESERVED_PREFIX)) updates[name] = undefined;
426
- }
427
- await c.setFields(objectId, withObjectId(updates, objectId, known));
428
- await upsertIndexEntry(objectId, true);
429
- }
430
-
431
- async function list(options?: { prefix?: string; includeDeleted?: boolean }): Promise<ListEntry[]> {
432
- const c = await ensureClient();
433
- const index = (await c.getFields(INDEX_OBJECT_ID)) || {};
434
- const rows: ListEntry[] = [];
435
- for (const [objectId, value] of Object.entries(index)) {
436
- if (objectId.startsWith(RESERVED_PREFIX)) continue;
437
- if (options?.prefix && !objectId.startsWith(options.prefix)) continue;
438
- const entry = value as { updatedAt?: unknown; deleted?: unknown } | null;
439
- if (!entry || typeof entry.updatedAt !== "string") continue;
440
- const deleted = entry.deleted === true;
441
- if (deleted && !options?.includeDeleted) continue;
442
- rows.push({ id: objectId, updatedAt: entry.updatedAt, ...(deleted ? { deleted: true as const } : {}) });
443
- }
444
- rows.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1));
445
- return rows;
446
- }
447
-
448
- // ---- sync ---------------------------------------------------------------
449
-
450
- async function sync(): Promise<void> {
451
- if (!liveTransport) throw new NotConnectedError();
452
- await runSyncPass();
453
- }
454
-
455
- async function runSyncPass(): Promise<void> {
456
- const c = await ensureClient();
457
- const wireId = liveWireId;
458
- if (!wireId) throw new OfflineError();
459
- // 0.9.0 compatibility: skip the remote ~index, but use it to resolve objects without ~id.
460
- let legacyIndex: Record<string, unknown> | null | undefined;
461
- await c.syncPass({
462
- skipWireIds: [await wireId(INDEX_OBJECT_ID)],
463
- resolveUnknown: async (wireObjectId, versionId) => {
464
- const doc = await c.pullDoc(wireObjectId, versionId);
465
- if (!doc || doc.t !== "lww-map") return null;
466
- const id = doc.fields[ID_FIELD]?.v;
467
- if (typeof id === "string") return id;
468
- if (legacyIndex === undefined) {
469
- const legacy = await c.pullRemoteDoc(INDEX_OBJECT_ID);
470
- legacyIndex = legacy?.t === "lww-map" ? legacy.fields : null;
471
- }
472
- for (const candidate of Object.keys(legacyIndex || {})) {
473
- if (!candidate.startsWith(RESERVED_PREFIX) && (await wireId(candidate)) === wireObjectId) return candidate;
474
- }
475
- return null;
476
- },
477
- });
478
- await writeMissingObjectIds(c);
479
- await Promise.all(pendingIndexRefreshes);
480
- }
481
-
482
- // 0.9.0 compatibility: add ~id to objects written without it.
483
- async function writeMissingObjectIds(c: BucketClient): Promise<void> {
484
- const upgraded: string[] = [];
485
- for (const id of await c.knownObjectIds()) {
486
- if (id.startsWith(RESERVED_PREFIX)) continue;
487
- const raw = await c.getFields(id);
488
- if (!raw || raw[ID_FIELD] === id) continue;
489
- await c.setFields(id, { [ID_FIELD]: id });
490
- upgraded.push(id);
491
- }
492
- for (const id of upgraded) await c.flush(id);
493
- }
494
-
495
- function startAutoSync(): void {
496
- if (!autoSync || !client) return;
497
- client.start({ run: runSyncPass, ...(syncIntervalMs !== undefined ? { intervalMs: syncIntervalMs } : {}) });
498
- }
499
-
500
- function bindTransport() {
501
- const current = connection.getLocalAccess();
502
- if (current === connectedAccess) return current;
503
- connectedAccess = current;
504
- liveTransport = new BucketTransport({ apiBase: current.access.resourceApiUrl!,
505
- mfid: current.access.mfid, keys: current.access.keys,
506
- sessionProvider: current.sessionProvider, fetch: current.fetch });
507
- liveWireId = current.access.keys.wireObjectId;
508
- return current;
509
- }
510
-
511
- function stopLocal() {
512
- liveTransport = null;
513
- liveWireId = null;
514
- connectedAccess = null;
515
- verifiedAccess = null;
516
- activating = null;
517
- client?.stop();
518
- }
519
-
520
- let connectionState = connection.state;
521
- const stopState = connection.on("state", (next, error) => {
522
- if (disposed) return;
523
- const entered = next === "connected" && connectionState !== "connected";
524
- connectionState = next;
525
- if (next === "disconnected" && error) lastFailure = error;
526
- if (next === "connected") bindTransport(); else stopLocal();
527
- emitState(next, error ? formatError(error) : undefined);
528
- // Error reports re-emit "connected"; only a new connection starts sync.
529
- if (entered) void reconcile().catch(() => {});
530
- });
531
- if (state === "connected") bindTransport();
532
-
533
- function activate(): Promise<void> {
534
- const current = bindTransport();
535
- if (verifiedAccess === current) {
536
- startAutoSync();
537
- return Promise.resolve();
538
- }
539
- if (activating) return activating;
540
- const operation = (async () => {
541
- const transport = liveTransport!;
542
- await ensureClient();
543
- current.signal.throwIfAborted();
544
- await transport.pullHead(await current.access.keys.wireObjectId(INDEX_OBJECT_ID));
545
- current.signal.throwIfAborted();
546
- if (disposed) return;
547
- verifiedAccess = current;
548
- startAutoSync();
549
- })().catch(async error => {
550
- current.signal.throwIfAborted();
551
- if (disposed) return;
552
- const failure = localError(error);
553
- if (failure.retryable) {
554
- // Keep shared access; automatic sync retries and reports later failures.
555
- connection.report(failure);
556
- startAutoSync();
557
- return;
558
- }
559
- await connection.fail(failure, current.signal);
560
- throw failure;
561
- }).finally(() => { if (activating === operation) activating = null; });
562
- activating = operation;
563
- return operation;
564
- }
565
-
566
- // Automatic sync runs exactly while the connection is up and autoSync is on.
567
- function reconcile(): Promise<void> {
568
- if (disposed) return Promise.resolve();
569
- if (!autoSync || !liveTransport) { client?.stop(); return Promise.resolve(); }
570
- return activate();
571
- }
572
-
573
- function connectInstance(prompt: boolean, enabled?: boolean): Promise<BucketState> {
574
- if (enabled !== undefined) bucket.setAutoSync(enabled);
575
- const operation = prompt ? connection.connect() : connection.resume();
576
- if (connecting?.operation === operation) return connecting.result;
577
- const done = operation.then(async next => {
578
- if (next === "connected") await reconcile();
579
- return next;
580
- }).finally(() => { if (connecting?.result === done) connecting = null; });
581
- connecting = { operation, result: done };
582
- return done;
583
- }
584
-
585
- // 0.9.1 semantics: invalid calls reject; authorization-flow failures resolve
586
- // "disconnected" after the state event carries the error.
587
- async function connectLegacy(prompt: boolean): Promise<BucketState> {
588
- if (disposed) throw new Error("disposed");
589
- await ensureClient();
590
- if (typeof window === "undefined") {
591
- if (!prompt) return state;
592
- throw new ClientError("INVALID_STATE", "Connecting requires a browser");
593
- }
594
- let next: BucketState;
595
- try {
596
- next = await (prompt ? connection.connect() : connection.resume());
597
- } catch (error) {
598
- if (error === lastFailure || isAbortError(error)) return "disconnected";
599
- throw error;
600
- }
601
- if (next !== "connected") return next;
602
- try { await reconcile(); } catch { return "disconnected"; }
603
- return next;
604
- }
605
-
606
- // ---- public object ------------------------------------------------------
607
-
608
- const bucket: Bucket = {
609
- id: bucketId,
610
- get state() {
611
- return state;
612
- },
613
- binary(input, options) {
614
- return createBucketBinaryValue(input, options);
615
- },
616
- async ready() {},
617
- put,
618
- get: getObject,
619
- update,
620
- delete: deleteObject,
621
- list,
622
- resume: () => connectLegacy(false),
623
- connect(options) {
624
- if (options && typeof options === "object" && (options as { authBase?: unknown }).authBase !== undefined) {
625
- return Promise.reject(new ClientError("INVALID_INPUT", "Pass the authorization page as createInstance({ authUrl })"));
626
- }
627
- if (options?.autoSync !== undefined) this.setAutoSync(options.autoSync);
628
- return connectLegacy(true);
629
- },
630
- disconnect: () => connection.disconnect(),
631
- async sync() {
632
- await sync();
633
- },
634
- setAutoSync(enabled) {
635
- autoSync = enabled;
636
- void reconcile().catch(() => {});
637
- },
638
- on(event: "state" | "change", handler: (...args: never[]) => void): () => void {
639
- const set = listeners[event] as Set<(...args: unknown[]) => void>;
640
- set.add(handler as (...args: unknown[]) => void);
641
- return () => set.delete(handler as (...args: unknown[]) => void);
642
- },
643
- dispose() {
644
- if (disposed) return;
645
- disposed = true;
646
- client?.dispose();
647
- stopState();
648
- stopLocal();
649
- deps.onDispose?.();
650
- },
651
- __bindTestTransport(transport) {
652
- liveTransport = transport;
653
- liveWireId = async (appObjectId) => appObjectId;
654
- emitState("connected");
655
- },
656
- };
657
- return { bucket, connectInstance };
658
- }
659
-
660
- function normalizeNamespace(value: string | undefined): string {
661
- const namespace = value === undefined ? "default" : value;
662
- if (typeof namespace !== "string" || namespace.length > 63 || !namespace.split(".").every(label => /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label))) {
663
- throw new ClientError("INVALID_INPUT", "namespace must be a lowercase domain-form name of 1–63 characters");
664
- }
665
- return namespace;
666
- }
667
-
668
- function prefixedAdapter(adapter: StorageAdapter, prefix: string): StorageAdapter {
669
- return {
670
- ...(adapter.removePrefix ? { removePrefix: (keyPrefix: string) => adapter.removePrefix!(`${prefix}${keyPrefix}`) } : {}),
671
- ...(adapter.insertIfEmpty ? { insertIfEmpty: (keyPrefix: string, entries: { key: string; value: unknown }[]) =>
672
- adapter.insertIfEmpty!(`${prefix}${keyPrefix}`, entries.map(entry => ({ ...entry, key: `${prefix}${entry.key}` }))) } : {}),
673
- get: (key) => adapter.get(`${prefix}${key}`),
674
- set: (key, value) => adapter.set(`${prefix}${key}`, value),
675
- remove: (key) => adapter.remove(`${prefix}${key}`),
676
- keys: async (keyPrefix) => (await adapter.keys(`${prefix}${keyPrefix}`)).map((key) => key.slice(prefix.length)),
677
- };
678
- }
679
-
680
- function isAbortError(error: unknown): boolean {
681
- return error instanceof Error && error.name === "AbortError";
682
- }
683
-
684
- function formatError(error: unknown): string {
685
- return error instanceof Error ? error.message : String(error);
686
- }
687
-
688
- function localError(error: unknown, message = formatError(error)): ClientError {
689
- if (error instanceof ClientError) {
690
- if (message === error.message) return error;
691
- return new ClientError(error.code, message, { cause: error, retryable: error.retryable, status: error.status,
692
- requestId: error.requestId, retryAfterMs: error.retryAfterMs, maxBytes: error.maxBytes });
693
- }
694
- const retryable = error instanceof BucketTransportError ? error.retryable : error instanceof TypeError;
695
- return new ClientError(retryable ? "NETWORK_ERROR" : "SYNC_FAILED", message, {
696
- cause: error, retryable, status: error instanceof BucketTransportError ? error.status : undefined,
697
- });
698
- }