@myfield/sdk 0.9.0 → 0.9.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/src/facade.ts CHANGED
@@ -5,9 +5,11 @@
5
5
  // boundary. `namespace` scopes ALL local persistence (instance keys, auth
6
6
  // context, sessions, objects, the internal index) and never reaches the
7
7
  // wire; bucket `id` is the app-local authorization label, while sync uses
8
- // the remote bucket id returned in the grant envelope.
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).
9
10
 
10
- import { BucketClient, type BucketTransportLike } from "./bucket/client.ts";
11
+ import { BucketClient, type BucketTransportLike, type ChangeSource } from "./bucket/client.ts";
12
+ import type { PayloadDoc } from "./bucket/format.ts";
11
13
  import {
12
14
  canonicalizeFieldValue,
13
15
  createBucketBinaryValue,
@@ -21,20 +23,26 @@ import {
21
23
  createNamespacedMemoryStorageAdapter,
22
24
  type StorageAdapter,
23
25
  } from "./bucket/store.ts";
24
- import { BucketTransport, OfflineError } from "./bucket/transport.ts";
25
- import { createInstanceAuthClient, isValidBucketId, type AuthCallbackResult, type InstanceAuthClient } from "./auth/instance.ts";
26
- import { NotConnectedError } from "./errors.ts";
26
+ import { BucketTransport, BucketTransportError, OfflineError } from "./bucket/transport.ts";
27
+ import { isValidBucketId } from "./auth/identifiers.ts";
28
+ import { ClientError, NotConnectedError } from "./errors.ts";
27
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";
28
35
 
29
- const DEFAULT_AUTH_BASE = "https://myfield.one/auth/";
30
- const DEFAULT_API_BASE = "https://api.myfield.one";
31
36
  const INDEX_OBJECT_ID = "~index";
37
+ const ID_FIELD = "~id";
32
38
  const DELETED_FIELD = "~deleted";
33
39
  const RESERVED_PREFIX = "~";
34
40
 
35
41
  export type CreateInstanceOptions = {
36
42
  namespace?: string;
37
43
  storage?: "indexeddb" | "memory";
44
+ appId?: string;
45
+ authUrl?: string;
38
46
  };
39
47
 
40
48
  export type BucketState = "disconnected" | "connecting" | "connected";
@@ -42,7 +50,6 @@ export type BucketState = "disconnected" | "connecting" | "connected";
42
50
  export type ListEntry = { id: string; updatedAt: string; deleted?: true };
43
51
 
44
52
  export type ConnectOptions = {
45
- authBase?: string;
46
53
  autoSync?: boolean;
47
54
  };
48
55
 
@@ -52,6 +59,7 @@ export type Bucket = {
52
59
  readonly id: string;
53
60
  readonly state: BucketState;
54
61
  binary(input: BinaryInput | BucketBinaryValue, options?: BinaryOptions): BucketBinaryValue;
62
+ /** @deprecated No-op kept for compatibility; operations initialize storage lazily. */
55
63
  ready(): Promise<void>;
56
64
  put(objectId: string, object: Record<string, unknown>): Promise<void>;
57
65
  get(objectId: string): Promise<Record<string, unknown> | null>;
@@ -73,11 +81,34 @@ export type Bucket = {
73
81
 
74
82
  export type Instance = {
75
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;
76
95
  createBucket(options: { id: string }): Bucket;
77
96
  };
78
97
 
79
- export function createInstance(options: CreateInstanceOptions = {}): Instance {
80
- const namespace = normalizeNamespace(options.namespace);
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());
81
112
  const storageKind = options.storage || "indexeddb";
82
113
 
83
114
  const baseAdapter =
@@ -86,40 +117,95 @@ export function createInstance(options: CreateInstanceOptions = {}): Instance {
86
117
  : createIndexedDbStorageAdapter({ dbName: `myfield-sdk:${namespace}` });
87
118
  const authAdapter = prefixedAdapter(baseAdapter, "auth:");
88
119
 
89
- // One handle per bucket id: separate facades over the same storage would
90
- // split event listeners and duplicate clients/clocks/debounce timers.
91
- const buckets = new Map<string, Bucket>();
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;
92
127
 
93
- return {
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 = {
94
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,
95
178
  createBucket(bucketOptions) {
96
179
  const bucketId = String(bucketOptions?.id || "").trim();
97
180
  if (!bucketId) throw new Error("bucket id is required");
98
181
  if (!isValidBucketId(bucketId)) throw new Error("invalid bucketId");
99
- const existing = buckets.get(bucketId);
100
- if (existing) return existing;
101
- const bucket = createBucketFacade({ namespace, bucketId, dataAdapter: baseAdapter, authAdapter });
102
- buckets.set(bucketId, bucket);
103
- return bucket;
182
+ return getLocalBucket(bucketId).bucket;
104
183
  },
105
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;
106
193
  }
107
194
 
108
195
  // ---------------------------------------------------------------------------
109
196
 
110
197
  type BucketDeps = {
111
- namespace: string;
112
198
  bucketId: string;
113
199
  dataAdapter: StorageAdapter;
114
- authAdapter: StorageAdapter;
200
+ connection: ReturnType<typeof createInstanceConnection>;
201
+ onDispose?: () => void;
115
202
  };
116
203
 
117
- function createBucketFacade(deps: BucketDeps): Bucket {
118
- const { bucketId, dataAdapter, authAdapter } = deps;
119
- const endpointsKey = `meta:${bucketId}:endpoints`;
204
+ function createBucketFacade(deps: BucketDeps) {
205
+ const { bucketId, dataAdapter, connection } = deps;
120
206
  const actorKey = `meta:actor`;
121
207
 
122
- let state: BucketState = "disconnected";
208
+ let state: BucketState = connection.state;
123
209
  let client: BucketClient | null = null;
124
210
  let clientInit: Promise<BucketClient> | null = null;
125
211
  let liveTransport: BucketTransportLike | null = null;
@@ -128,15 +214,11 @@ function createBucketFacade(deps: BucketDeps): Bucket {
128
214
  let syncIntervalMs: number | undefined;
129
215
  let disposed = false;
130
216
 
131
- // Browser auth machinery (lazy; never touched by the test seam path).
132
- let authClient: InstanceAuthClient | null = null;
133
- let popupAuthClient: InstanceAuthClient | null = null;
134
- let authPageOrigin = "";
135
- let authPopupWindow: Window | null = null;
136
- let authPopupPollTimer: ReturnType<typeof setInterval> | null = null;
137
- let pendingConnect: { resolve: (state: BucketState) => void } | null = null;
138
- let pendingConnectDone: Promise<BucketState> | null = null;
139
- let popupMessageListener: ((event: MessageEvent<unknown>) => void) | null = null;
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;
140
222
 
141
223
  const listeners = { state: new Set<(s: BucketState, d?: string) => void>(), change: new Set<(id: string) => void>() };
142
224
 
@@ -154,13 +236,6 @@ function createBucketFacade(deps: BucketDeps): Bucket {
154
236
  for (const handler of listeners.change) handler(objectId);
155
237
  }
156
238
 
157
- function settlePendingConnect(): void {
158
- if (!pendingConnect) return;
159
- const settle = pendingConnect;
160
- pendingConnect = null;
161
- settle.resolve(state);
162
- }
163
-
164
239
  function ensureClient(): Promise<BucketClient> {
165
240
  if (clientInit) return clientInit;
166
241
  clientInit = (async () => {
@@ -183,20 +258,29 @@ function createBucketFacade(deps: BucketDeps): Bucket {
183
258
  if (!liveTransport) return Promise.reject(new OfflineError());
184
259
  return liveTransport.push(wireObjectId, plaintext, expectedHeadVersionId);
185
260
  },
261
+ listHeads() {
262
+ if (!liveTransport?.listHeads) return Promise.reject(new OfflineError());
263
+ return liveTransport.listHeads();
264
+ },
186
265
  },
187
266
  storage: dataAdapter,
267
+ autoSync: autoSync && Boolean(liveTransport),
188
268
  actorId,
269
+ localOnlyObjectIds: [INDEX_OBJECT_ID],
270
+ validateRemote: assertRemoteObjectId,
189
271
  wireObjectId: (appObjectId) => {
190
272
  if (!liveWireId) return Promise.reject(new OfflineError());
191
273
  return liveWireId(appObjectId);
192
274
  },
193
275
  storagePrefix: `data:${bucketId}`,
194
- onChange: emitChange,
276
+ onChange: onClientChange,
195
277
  onSyncError: (objectId, error) => {
196
278
  if (error instanceof OfflineError) return;
197
279
  // Retryable sync failures surface as state detail without a state
198
280
  // change; local data is never affected.
199
- emitState(state, `sync error${objectId ? ` (${objectId})` : ""}: ${formatError(error)}`);
281
+ const detail = `sync error${objectId ? ` (${objectId})` : ""}: ${formatError(error)}`;
282
+ if (connection.state === "connected") connection.report(localError(error, detail));
283
+ else emitState(state, detail);
200
284
  },
201
285
  });
202
286
  return client;
@@ -204,6 +288,36 @@ function createBucketFacade(deps: BucketDeps): Bucket {
204
288
  return clientInit;
205
289
  }
206
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
+
207
321
  // ---- local object API ---------------------------------------------------
208
322
 
209
323
  function assertObjectId(objectId: string): void {
@@ -218,10 +332,17 @@ function createBucketFacade(deps: BucketDeps): Bucket {
218
332
  }
219
333
  }
220
334
 
221
- async function upsertIndexEntry(objectId: string, deleted: boolean): Promise<void> {
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> {
222
338
  const c = await ensureClient();
339
+ lastIndexRev = Math.max(lastIndexRev + 1, Date.now());
223
340
  await c.setFields(INDEX_OBJECT_ID, {
224
- [objectId]: { updatedAt: new Date().toISOString(), ...(deleted ? { deleted: true } : {}) },
341
+ [objectId]: {
342
+ updatedAt: new Date(updatedAtMs).toISOString(),
343
+ rev: lastIndexRev,
344
+ ...(deleted ? { deleted: true } : {}),
345
+ },
225
346
  });
226
347
  }
227
348
 
@@ -247,6 +368,10 @@ function createBucketFacade(deps: BucketDeps): Bucket {
247
368
  return changed;
248
369
  }
249
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
+
250
375
  async function put(objectId: string, object: Record<string, unknown>): Promise<void> {
251
376
  assertObjectId(objectId);
252
377
  assertFieldNames(object);
@@ -254,11 +379,11 @@ function createBucketFacade(deps: BucketDeps): Bucket {
254
379
  const known = (await c.getFields(objectId)) || {};
255
380
  const updates: Record<string, unknown> = { ...object };
256
381
  for (const name of Object.keys(known)) {
257
- if (!(name in object)) updates[name] = undefined; // deletes locally known omitted fields (incl. a live ~deleted marker)
382
+ if (!(name in object) && name !== ID_FIELD) updates[name] = undefined; // deletes locally known omitted fields (incl. a live ~deleted marker)
258
383
  }
259
384
  const changed = await dropUnchanged(updates, known);
260
385
  if (Object.keys(changed).length === 0) return; // full no-op: do not advance LWW state or the index entry
261
- await c.setFields(objectId, changed);
386
+ await c.setFields(objectId, withObjectId(changed, objectId, known));
262
387
  await upsertIndexEntry(objectId, false);
263
388
  }
264
389
 
@@ -271,7 +396,7 @@ function createBucketFacade(deps: BucketDeps): Bucket {
271
396
  if (DELETED_FIELD in known) updates[DELETED_FIELD] = undefined; // update recreates a deleted object
272
397
  const changed = await dropUnchanged(updates, known);
273
398
  if (Object.keys(changed).length === 0) return;
274
- await c.setFields(objectId, changed);
399
+ await c.setFields(objectId, withObjectId(changed, objectId, known));
275
400
  await upsertIndexEntry(objectId, false);
276
401
  }
277
402
 
@@ -299,7 +424,7 @@ function createBucketFacade(deps: BucketDeps): Bucket {
299
424
  for (const name of Object.keys(known)) {
300
425
  if (!name.startsWith(RESERVED_PREFIX)) updates[name] = undefined;
301
426
  }
302
- await c.setFields(objectId, updates);
427
+ await c.setFields(objectId, withObjectId(updates, objectId, known));
303
428
  await upsertIndexEntry(objectId, true);
304
429
  }
305
430
 
@@ -324,207 +449,163 @@ function createBucketFacade(deps: BucketDeps): Bucket {
324
449
 
325
450
  async function sync(): Promise<void> {
326
451
  if (!liveTransport) throw new NotConnectedError();
327
- const c = await ensureClient();
328
- const dirtyObjectIds = (await c.dirtyObjectIds()).filter((id) => id !== INDEX_OBJECT_ID && !id.startsWith(RESERVED_PREFIX));
329
- await c.syncAuto({ indexObjectId: INDEX_OBJECT_ID });
330
- for (const id of dirtyObjectIds) {
331
- const raw = await c.getFields(id);
332
- await upsertIndexEntry(id, raw?.[DELETED_FIELD] === true);
333
- }
334
- if (dirtyObjectIds.length > 0) await c.syncObject(INDEX_OBJECT_ID);
452
+ await runSyncPass();
335
453
  }
336
454
 
337
- function startAutoSync(): void {
338
- if (!autoSync || !client) return;
339
- client.watch([INDEX_OBJECT_ID]);
340
- client.start({ indexObjectId: INDEX_OBJECT_ID, ...(syncIntervalMs !== undefined ? { intervalMs: syncIntervalMs } : {}) });
341
- }
342
-
343
- // ---- connection (browser) ----------------------------------------------
344
-
345
- async function readStoredEndpoints(): Promise<{ authBase: string; apiBase: string }> {
346
- const stored = await dataAdapter.get<{ authBase?: string; apiBase?: string }>(endpointsKey);
347
- const authBase = stored?.authBase || DEFAULT_AUTH_BASE;
348
- return {
349
- authBase,
350
- apiBase: stored?.apiBase || apiBaseForAuthBase(authBase),
351
- };
352
- }
353
-
354
- async function ensureAuthClients(endpoints: { authBase: string; apiBase: string }): Promise<InstanceAuthClient> {
355
- if (authClient) return authClient;
356
- if (typeof window === "undefined") throw new Error("connect()/resume() require a browser environment");
357
- const origin = window.location.origin;
358
- const authPageUrl = normalizeAuthBase(endpoints.authBase);
359
- authPageOrigin = new URL(authPageUrl, window.location.href).origin;
360
- const baseOptions = {
361
- appId: new URL(origin).hostname,
362
- apiBase: endpoints.apiBase,
363
- redirectUri: origin + window.location.pathname,
364
- origin,
365
- storage: authAdapter,
366
- };
367
- authClient = createInstanceAuthClient({
368
- ...baseOptions,
369
- authPageUrl: addCallbackTransport(authPageUrl, "same-tab"),
370
- });
371
- popupAuthClient = createInstanceAuthClient({
372
- ...baseOptions,
373
- authPageUrl: addCallbackTransport(authPageUrl, "popup"),
374
- openAuthUrl: (url) => openAuthPopupUrl(url),
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
+ },
375
477
  });
376
- popupMessageListener = (event: MessageEvent<unknown>) => void onPopupMessage(event);
377
- window.addEventListener("message", popupMessageListener);
378
- return authClient;
478
+ await writeMissingObjectIds(c);
479
+ await Promise.all(pendingIndexRefreshes);
379
480
  }
380
481
 
381
- function clearPopupMonitor(): void {
382
- if (authPopupPollTimer != null) {
383
- clearInterval(authPopupPollTimer);
384
- authPopupPollTimer = null;
385
- }
386
- }
387
-
388
- function tryOpenPopupShell(): boolean {
389
- clearPopupMonitor();
390
- authPopupWindow?.close();
391
- const width = 520;
392
- const height = 720;
393
- const left = Math.max(0, Math.floor(window.screenX + (window.outerWidth - width) / 2));
394
- const top = Math.max(0, Math.floor(window.screenY + (window.outerHeight - height) / 2));
395
- authPopupWindow = window.open(
396
- "about:blank",
397
- "myfield-sdk-auth",
398
- `popup=yes,width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`
399
- );
400
- if (!authPopupWindow || authPopupWindow.closed) {
401
- authPopupWindow = null;
402
- return false;
403
- }
404
- try {
405
- authPopupWindow.document.title = "Opening Myfield...";
406
- authPopupWindow.document.body.textContent = "Opening Myfield authorization...";
407
- } catch {
408
- // Same-origin about:blank in normal browsers; ignore if blocked.
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);
409
491
  }
410
- authPopupWindow.focus();
411
- authPopupPollTimer = setInterval(() => {
412
- if (!authPopupWindow?.closed) return;
413
- clearPopupMonitor();
414
- if (state === "connecting") {
415
- emitState("disconnected", "authorization window closed");
416
- settlePendingConnect();
417
- }
418
- }, 500);
419
- return true;
492
+ for (const id of upgraded) await c.flush(id);
420
493
  }
421
494
 
422
- function openAuthPopupUrl(url: string): void {
423
- if (!authPopupWindow || authPopupWindow.closed) {
424
- if (!tryOpenPopupShell()) throw new Error("authorization popup was blocked");
425
- }
426
- try {
427
- authPopupWindow!.location.href = url;
428
- authPopupWindow!.focus();
429
- } catch {
430
- authPopupWindow = window.open(url, "myfield-sdk-auth");
431
- if (!authPopupWindow) throw new Error("authorization popup was blocked");
432
- }
495
+ function startAutoSync(): void {
496
+ if (!autoSync || !client) return;
497
+ client.start({ run: runSyncPass, ...(syncIntervalMs !== undefined ? { intervalMs: syncIntervalMs } : {}) });
433
498
  }
434
499
 
435
- async function onPopupMessage(event: MessageEvent<unknown>): Promise<void> {
436
- if (event.origin !== authPageOrigin) return;
437
- const message = event.data as { type?: unknown; callbackUrl?: unknown } | null;
438
- if (!message || message.type !== "myfield.auth.callback" || typeof message.callbackUrl !== "string") return;
439
- clearPopupMonitor();
440
- authPopupWindow?.close();
441
- authPopupWindow = null;
442
- await handleCallbackUrl(message.callbackUrl);
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;
443
509
  }
444
510
 
445
- async function handleCallbackUrl(callbackUrl: string): Promise<AuthCallbackResult | null> {
446
- try {
447
- const auth = await ensureAuthClients(await readStoredEndpoints());
448
- const callback = await auth.handleCallback(callbackUrl);
449
- if (!callback) return null;
450
- if (callback.result === "approved") {
451
- await establish({ forceRefresh: true });
452
- } else {
453
- emitState("disconnected", callback.errorDescription || callback.error || callback.result);
454
- settlePendingConnect();
455
- }
456
- return callback;
457
- } catch (error) {
458
- emitState("disconnected", formatError(error));
459
- settlePendingConnect();
460
- return null;
461
- }
511
+ function stopLocal() {
512
+ liveTransport = null;
513
+ liveWireId = null;
514
+ connectedAccess = null;
515
+ verifiedAccess = null;
516
+ activating = null;
517
+ client?.stop();
462
518
  }
463
519
 
464
- async function establish(sessionOptions: { forceRefresh?: boolean } = {}): Promise<void> {
465
- emitState("connecting");
466
- try {
467
- const endpoints = await readStoredEndpoints();
468
- const auth = await ensureAuthClients(endpoints);
469
- const c = await ensureClient();
470
- await auth.getSession(bucketId, sessionOptions);
471
- const access = await auth.getBucketAccess(bucketId);
472
- if (!access.resourceApiUrl) throw new Error("auth callback missing resourceApiUrl; reconnect through the current Myfield auth page");
473
- const transport = new BucketTransport({
474
- apiBase: access.resourceApiUrl,
475
- mfid: access.mfid,
476
- keys: access.keys,
477
- sessionProvider: {
478
- getSession: (sessionOpts) => auth.getSession(bucketId, sessionOpts),
479
- onUnauthorized: () => {
480
- // Grant revoked: drop back to local-first; reconnecting needs a
481
- // user gesture through connect() again.
482
- liveTransport = null;
483
- liveWireId = null;
484
- c.stop();
485
- emitState("disconnected", "unauthorized");
486
- },
487
- },
488
- });
489
- await verifyConnectedTransport(transport, access.keys.wireObjectId);
490
- liveTransport = transport;
491
- liveWireId = access.keys.wireObjectId;
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) {
492
536
  startAutoSync();
493
- emitState("connected");
494
- } catch (error) {
495
- client?.stop();
496
- emitState("disconnected", formatError(error));
497
- } finally {
498
- settlePendingConnect();
537
+ return Promise.resolve();
499
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;
500
564
  }
501
565
 
502
- async function verifyConnectedTransport(transport: BucketTransport, wireObjectId: (appObjectId: string) => Promise<string>): Promise<void> {
503
- await transport.pullHead(await wireObjectId(INDEX_OBJECT_ID));
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();
504
571
  }
505
572
 
506
- async function handleStartupCallback(): Promise<boolean> {
507
- const href = window.location.href;
508
- if (!href.includes("mf_auth_result") && !new URL(href).searchParams.get("mf_request_id")) return false;
509
- const callback = await handleCallbackUrl(href);
510
- if (callback) stripCallbackFromUrl();
511
- return !!callback;
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;
512
583
  }
513
584
 
514
- function stripCallbackFromUrl(): void {
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;
515
595
  try {
516
- const url = new URL(window.location.href);
517
- url.hash = "";
518
- for (const param of ["state", "error", "error_description", "error_uri", "mf_request_id", "mf_result"]) url.searchParams.delete(param);
519
- window.history.replaceState(null, "", url.toString());
520
- } catch {
521
- // Cosmetic only.
596
+ next = await (prompt ? connection.connect() : connection.resume());
597
+ } catch (error) {
598
+ if (error === lastFailure || isAbortError(error)) return "disconnected";
599
+ throw error;
522
600
  }
601
+ if (next !== "connected") return next;
602
+ try { await reconcile(); } catch { return "disconnected"; }
603
+ return next;
523
604
  }
524
605
 
525
606
  // ---- public object ------------------------------------------------------
526
607
 
527
- return {
608
+ const bucket: Bucket = {
528
609
  id: bucketId,
529
610
  get state() {
530
611
  return state;
@@ -532,92 +613,27 @@ function createBucketFacade(deps: BucketDeps): Bucket {
532
613
  binary(input, options) {
533
614
  return createBucketBinaryValue(input, options);
534
615
  },
535
- async ready() {
536
- await ensureClient();
537
- },
616
+ async ready() {},
538
617
  put,
539
618
  get: getObject,
540
619
  update,
541
620
  delete: deleteObject,
542
621
  list,
543
- async resume() {
544
- if (disposed) throw new Error("disposed");
545
- await ensureClient();
546
- if (typeof window === "undefined") return state;
547
- if (state !== "disconnected") return state;
548
- const auth = await ensureAuthClients(await readStoredEndpoints());
549
- if (await handleStartupCallback()) return state;
550
- const context = await auth.getContext(bucketId);
551
- if (context) await establish();
552
- return state;
553
- },
554
- async connect(options) {
555
- if (disposed) throw new Error("disposed");
556
- if (options?.autoSync !== undefined) autoSync = options.autoSync;
557
- if (options?.authBase) {
558
- const endpoints = await readStoredEndpoints();
559
- const authBase = normalizeAuthBase(options.authBase);
560
- await dataAdapter.set(endpointsKey, {
561
- authBase,
562
- apiBase: apiBaseForAuthBase(authBase) || endpoints.apiBase,
563
- });
564
- // Endpoints changed: force fresh auth clients bound to them.
565
- if (popupMessageListener && typeof window !== "undefined") {
566
- window.removeEventListener("message", popupMessageListener);
567
- popupMessageListener = null;
568
- }
569
- authClient = null;
570
- popupAuthClient = null;
571
- }
572
- if (state === "connected") return state;
573
- // Re-entrant connect (e.g. a double-clicked button) joins the pending
574
- // flow instead of orphaning the first caller's promise.
575
- if (pendingConnectDone) return pendingConnectDone;
576
- const resumed = await this.resume();
577
- if (resumed !== "disconnected") return resumed;
578
- if (pendingConnectDone) return pendingConnectDone;
579
- const auth = await ensureAuthClients(await readStoredEndpoints());
580
- emitState("connecting");
581
- const done = new Promise<BucketState>((resolve) => {
582
- pendingConnect = { resolve };
583
- }).finally(() => {
584
- if (pendingConnectDone === done) pendingConnectDone = null;
585
- });
586
- pendingConnectDone = done;
587
- try {
588
- if (shouldUseSameTabAuth() || !tryOpenPopupShell()) {
589
- clearPopupMonitor();
590
- authPopupWindow = null;
591
- await auth.authorize({ bucketId });
592
- // Same-tab navigates away; resolution happens on reload via resume().
593
- } else {
594
- await popupAuthClient!.authorize({ bucketId });
595
- }
596
- } catch (error) {
597
- authPopupWindow?.close();
598
- authPopupWindow = null;
599
- clearPopupMonitor();
600
- emitState("disconnected", formatError(error));
601
- settlePendingConnect();
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 })"));
602
626
  }
603
- return done;
604
- },
605
- async disconnect() {
606
- liveTransport = null;
607
- liveWireId = null;
608
- client?.stop();
609
- if (authClient) await authClient.clearContext(bucketId);
610
- emitState("disconnected");
611
- settlePendingConnect();
627
+ if (options?.autoSync !== undefined) this.setAutoSync(options.autoSync);
628
+ return connectLegacy(true);
612
629
  },
630
+ disconnect: () => connection.disconnect(),
613
631
  async sync() {
614
632
  await sync();
615
633
  },
616
634
  setAutoSync(enabled) {
617
635
  autoSync = enabled;
618
- if (!client) return;
619
- if (enabled && liveTransport) startAutoSync();
620
- if (!enabled) client.stop();
636
+ void reconcile().catch(() => {});
621
637
  },
622
638
  on(event: "state" | "change", handler: (...args: never[]) => void): () => void {
623
639
  const set = listeners[event] as Set<(...args: unknown[]) => void>;
@@ -625,10 +641,12 @@ function createBucketFacade(deps: BucketDeps): Bucket {
625
641
  return () => set.delete(handler as (...args: unknown[]) => void);
626
642
  },
627
643
  dispose() {
644
+ if (disposed) return;
628
645
  disposed = true;
629
646
  client?.dispose();
630
- clearPopupMonitor();
631
- if (popupMessageListener && typeof window !== "undefined") window.removeEventListener("message", popupMessageListener);
647
+ stopState();
648
+ stopLocal();
649
+ deps.onDispose?.();
632
650
  },
633
651
  __bindTestTransport(transport) {
634
652
  liveTransport = transport;
@@ -636,19 +654,22 @@ function createBucketFacade(deps: BucketDeps): Bucket {
636
654
  emitState("connected");
637
655
  },
638
656
  };
657
+ return { bucket, connectInstance };
639
658
  }
640
659
 
641
660
  function normalizeNamespace(value: string | undefined): string {
642
- const namespace = value === undefined ? "default" : String(value).trim();
643
- if (!namespace) throw new Error("namespace is required");
644
- if (!/^[a-z0-9]{1,32}$/.test(namespace)) {
645
- throw new Error("namespace must use lowercase letters and digits only (a-z0-9, max 32)");
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");
646
664
  }
647
665
  return namespace;
648
666
  }
649
667
 
650
668
  function prefixedAdapter(adapter: StorageAdapter, prefix: string): StorageAdapter {
651
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}` }))) } : {}),
652
673
  get: (key) => adapter.get(`${prefix}${key}`),
653
674
  set: (key, value) => adapter.set(`${prefix}${key}`, value),
654
675
  remove: (key) => adapter.remove(`${prefix}${key}`),
@@ -656,36 +677,22 @@ function prefixedAdapter(adapter: StorageAdapter, prefix: string): StorageAdapte
656
677
  };
657
678
  }
658
679
 
659
- function addCallbackTransport(url: string, transport: "same-tab" | "popup"): string {
660
- const parsed = new URL(url, typeof window === "undefined" ? "https://localhost/" : window.location.href);
661
- parsed.searchParams.set("callbackTransport", transport);
662
- return parsed.toString();
663
- }
664
-
665
- function normalizeAuthBase(value: string): string {
666
- const parsed = new URL(String(value || DEFAULT_AUTH_BASE), typeof window === "undefined" ? DEFAULT_AUTH_BASE : window.location.href);
667
- const pathname = parsed.pathname.replace(/\/+$/, "");
668
- parsed.pathname = pathname.endsWith("/auth") ? `${pathname}/` : `${pathname}/auth/`;
669
- parsed.search = "";
670
- parsed.hash = "";
671
- return parsed.toString();
672
- }
673
-
674
- function apiBaseForAuthBase(authBase: string): string {
675
- const parsed = new URL(authBase);
676
- if (parsed.hostname === "myfield.one") return DEFAULT_API_BASE;
677
- if (parsed.hostname === "dev.myfield.space") return "https://api-dev.myfield.space";
678
- if (parsed.hostname === "staging.myfield.space") return "https://api-staging.myfield.space";
679
- return `${parsed.protocol}//api.${parsed.host}`;
680
- }
681
-
682
- function shouldUseSameTabAuth(): boolean {
683
- if (typeof navigator === "undefined") return false;
684
- const platform = navigator.platform || "";
685
- const userAgent = navigator.userAgent || "";
686
- return /iPad|iPhone|iPod/.test(userAgent) || (platform === "MacIntel" && navigator.maxTouchPoints > 1);
680
+ function isAbortError(error: unknown): boolean {
681
+ return error instanceof Error && error.name === "AbortError";
687
682
  }
688
683
 
689
684
  function formatError(error: unknown): string {
690
685
  return error instanceof Error ? error.message : String(error);
691
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
+ }