@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.
@@ -6,6 +6,7 @@
6
6
  // Document body:
7
7
  // { t: "lww-map", fields: { name: { v, ts, actor } }, tombstones: { name: { ts, actor } } }
8
8
  // or { t: "opaque", data: <arbitrary JSON> } for custom merge strategies.
9
+ // Unknown top-level and entry keys are kept (BUCKET-SPEC merge steps 4-5).
9
10
  // Binary typed field values are represented in the JSON header as part references
10
11
  // and carried as raw bytes in the binary parts section.
11
12
 
@@ -23,15 +24,18 @@ const HEADER_LENGTH_BYTES = 4;
23
24
  const PART_LENGTH_BYTES = 4;
24
25
  const BINARY_PART_MARKER = "binary-part-v1";
25
26
 
26
- export type LwwFieldEntry = { v: unknown; ts: number; actor: string };
27
- export type LwwTombstone = { ts: number; actor: string };
27
+ export type LwwFieldEntry = { v: unknown; ts: number; actor: string; [extra: string]: unknown };
28
+ export type LwwTombstone = { ts: number; actor: string; [extra: string]: unknown };
28
29
 
29
30
  export type LwwMapDoc = {
30
31
  t: "lww-map";
31
32
  fields: Record<string, LwwFieldEntry>;
32
33
  tombstones: Record<string, LwwTombstone>;
34
+ ext?: Record<string, unknown>;
33
35
  };
34
36
 
37
+ const LWW_MAP_KEYS = new Set(["t", "fields", "tombstones"]);
38
+
35
39
  export type OpaqueDoc = { t: "opaque"; data: unknown };
36
40
 
37
41
  export type PayloadDoc = LwwMapDoc | OpaqueDoc;
@@ -42,7 +46,8 @@ export function emptyLwwMapDoc(): LwwMapDoc {
42
46
 
43
47
  export function encodePayloadDoc(doc: PayloadDoc): Uint8Array {
44
48
  const parts: Uint8Array[] = [];
45
- const header = utf8Encode(JSON.stringify(encodeHeaderValue(doc, parts)));
49
+ const body = doc.t === "lww-map" ? { ...(doc.ext || {}), t: doc.t, fields: doc.fields, tombstones: doc.tombstones } : doc;
50
+ const header = utf8Encode(JSON.stringify(encodeHeaderValue(body, parts)));
46
51
  let totalLength = 1 + HEADER_LENGTH_BYTES + header.byteLength;
47
52
  for (const part of parts) totalLength += PART_LENGTH_BYTES + part.byteLength;
48
53
  const out = new Uint8Array(totalLength);
@@ -93,7 +98,13 @@ function parsePayloadDoc(parsed: unknown): PayloadDoc {
93
98
  for (const entry of Object.values(doc.tombstones)) {
94
99
  if (!isLwwTombstone(entry)) throw new Error("invalid lww-map tombstone");
95
100
  }
96
- return { t: "lww-map", fields: doc.fields as Record<string, LwwFieldEntry>, tombstones: doc.tombstones as Record<string, LwwTombstone> };
101
+ const ext = Object.fromEntries(Object.entries(doc).filter(([key]) => !LWW_MAP_KEYS.has(key)));
102
+ return {
103
+ t: "lww-map",
104
+ fields: doc.fields as Record<string, LwwFieldEntry>,
105
+ tombstones: doc.tombstones as Record<string, LwwTombstone>,
106
+ ...(Object.keys(ext).length ? { ext } : {}),
107
+ };
97
108
  }
98
109
  if (docRoot?.t === "opaque") return { t: "opaque", data: (docRoot as OpaqueDoc).data };
99
110
  throw new Error("unknown payload doc type");
@@ -106,13 +117,20 @@ function wins(aTs: number, aActor: string, bTs: number, bActor: string): boolean
106
117
  return aActor > bActor;
107
118
  }
108
119
 
109
- // A well-behaved actor never issues two different values under the same
110
- // (ts, actor), but merge must stay deterministic even for malformed input:
111
- // on a full (ts, actor) tie the serialized value breaks the tie.
120
+ // Full (ts, actor) ties (malformed input, or an older SDK that dropped extra
121
+ // keys) fall back to the value, then the whole entry, to stay deterministic.
112
122
  function fieldEntryWins(a: LwwFieldEntry, b: LwwFieldEntry): boolean {
113
123
  if (a.ts !== b.ts) return a.ts > b.ts;
114
124
  if (a.actor !== b.actor) return a.actor > b.actor;
115
- return JSON.stringify(fieldValueToCanonicalJson(a.v)) > JSON.stringify(fieldValueToCanonicalJson(b.v));
125
+ const aValue = JSON.stringify(fieldValueToCanonicalJson(a.v));
126
+ const bValue = JSON.stringify(fieldValueToCanonicalJson(b.v));
127
+ if (aValue !== bValue) return aValue > bValue;
128
+ return canonicalJson(a) > canonicalJson(b);
129
+ }
130
+
131
+ function tombstoneWins(a: LwwTombstone, b: LwwTombstone): boolean {
132
+ if (a.ts !== b.ts || a.actor !== b.actor) return wins(a.ts, a.actor, b.ts, b.actor);
133
+ return canonicalJson(a) > canonicalJson(b);
116
134
  }
117
135
 
118
136
  // State-based LWW-Map merge: commutative, associative, idempotent. A field
@@ -124,38 +142,68 @@ export function mergeLwwMapDocs(a: LwwMapDoc, b: LwwMapDoc): LwwMapDoc {
124
142
  for (const source of [a.tombstones, b.tombstones]) {
125
143
  for (const [name, stone] of Object.entries(source)) {
126
144
  const existing = tombstones[name];
127
- if (!existing || wins(stone.ts, stone.actor, existing.ts, existing.actor)) tombstones[name] = { ts: stone.ts, actor: stone.actor };
145
+ if (!existing || tombstoneWins(stone, existing)) tombstones[name] = { ...stone };
128
146
  }
129
147
  }
130
148
  const fields: Record<string, LwwFieldEntry> = {};
131
149
  for (const source of [a.fields, b.fields]) {
132
150
  for (const [name, entry] of Object.entries(source)) {
133
151
  const existing = fields[name];
134
- if (!existing || fieldEntryWins(entry, existing)) fields[name] = { v: entry.v, ts: entry.ts, actor: entry.actor };
152
+ if (!existing || fieldEntryWins(entry, existing)) fields[name] = { ...entry };
135
153
  }
136
154
  }
137
155
  for (const [name, stone] of Object.entries(tombstones)) {
138
156
  const entry = fields[name];
139
157
  if (entry && !wins(entry.ts, entry.actor, stone.ts, stone.actor)) delete fields[name];
140
158
  }
141
- return { t: "lww-map", fields, tombstones };
159
+ const ext = mergeExt(a.ext, b.ext);
160
+ return { t: "lww-map", fields, tombstones, ...(ext ? { ext } : {}) };
161
+ }
162
+
163
+ function mergeExt(a: Record<string, unknown> | undefined, b: Record<string, unknown> | undefined): Record<string, unknown> | undefined {
164
+ if (!a && !b) return undefined;
165
+ const merged: Record<string, unknown> = { ...(a || {}) };
166
+ for (const [key, value] of Object.entries(b || {})) {
167
+ if (!(key in merged) || canonicalJson(value) > canonicalJson(merged[key])) merged[key] = value;
168
+ }
169
+ return Object.keys(merged).length ? merged : undefined;
170
+ }
171
+
172
+ function canonicalJson(value: unknown): string {
173
+ return stableStringify(fieldValueToCanonicalJson(value));
174
+ }
175
+
176
+ function stableStringify(value: unknown): string {
177
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
178
+ if (value && typeof value === "object") {
179
+ const entries = Object.entries(value as Record<string, unknown>)
180
+ .filter(([, item]) => item !== undefined)
181
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
182
+ return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`).join(",")}}`;
183
+ }
184
+ return JSON.stringify(value) ?? "null";
142
185
  }
143
186
 
144
187
  export function lwwMapDocsEqual(a: LwwMapDoc, b: LwwMapDoc): boolean {
145
- return JSON.stringify(canonicalLwwMapDoc(a)) === JSON.stringify(canonicalLwwMapDoc(b));
188
+ return canonicalJson(canonicalLwwMapDoc(a)) === canonicalJson(canonicalLwwMapDoc(b));
146
189
  }
147
190
 
148
191
  function canonicalLwwMapDoc(doc: LwwMapDoc): unknown {
149
192
  return {
150
- fields: Object.fromEntries(
151
- Object.entries(doc.fields)
152
- .sort(([a], [b]) => (a < b ? -1 : 1))
153
- .map(([name, entry]) => [name, { ...entry, v: fieldValueToCanonicalJson(entry.v) }])
154
- ),
155
- tombstones: Object.fromEntries(Object.entries(doc.tombstones).sort(([a], [b]) => (a < b ? -1 : 1))),
193
+ fields: Object.fromEntries(Object.entries(doc.fields).map(([name, entry]) => [name, { ...entry, v: fieldValueToCanonicalJson(entry.v) }])),
194
+ tombstones: doc.tombstones,
195
+ ext: doc.ext || {},
156
196
  };
157
197
  }
158
198
 
199
+ export function lwwMapLatestTs(doc: LwwMapDoc): number | null {
200
+ let latest: number | null = null;
201
+ for (const entry of [...Object.values(doc.fields), ...Object.values(doc.tombstones)]) {
202
+ if (latest === null || entry.ts > latest) latest = entry.ts;
203
+ }
204
+ return latest;
205
+ }
206
+
159
207
  // Plain field view with tombstones and metadata hidden.
160
208
  export function lwwMapValues(doc: LwwMapDoc): Record<string, unknown> {
161
209
  return Object.fromEntries(Object.entries(doc.fields).map(([name, entry]) => [name, hydrateFieldValue(entry.v)]));
@@ -189,6 +237,7 @@ export function applyLwwMapUpdates(doc: LwwMapDoc, updates: Record<string, unkno
189
237
  t: "lww-map",
190
238
  fields: { ...doc.fields },
191
239
  tombstones: { ...doc.tombstones },
240
+ ...(doc.ext ? { ext: { ...doc.ext } } : {}),
192
241
  };
193
242
  for (const [name, value] of Object.entries(updates)) {
194
243
  const ts = clock.next();
@@ -6,7 +6,9 @@ export type StorageAdapter = {
6
6
  get<T = unknown>(key: string): Promise<T | null>;
7
7
  set(key: string, value: unknown): Promise<void>;
8
8
  remove(key: string): Promise<void>;
9
+ removePrefix?(prefix: string): Promise<void>;
9
10
  keys(prefix: string): Promise<string[]>;
11
+ insertIfEmpty?(prefix: string, entries: { key: string; value: unknown }[]): Promise<boolean>;
10
12
  };
11
13
 
12
14
  // Per-process registry so memory-backed instances behave like persistent
@@ -29,6 +31,15 @@ export function createMemoryStorageAdapter(): StorageAdapter {
29
31
 
30
32
  function memoryAdapterOver(map: Map<string, unknown>): StorageAdapter {
31
33
  return {
34
+ async removePrefix(prefix) {
35
+ for (const key of map.keys()) if (key.startsWith(prefix)) map.delete(key);
36
+ },
37
+ async insertIfEmpty(prefix, entries) {
38
+ if ([...map.keys()].some(key => key.startsWith(prefix))) return false;
39
+ const cloned = entries.map(({ key, value }) => ({ key, value: structuredClone(value) }));
40
+ for (const { key, value } of cloned) map.set(key, value);
41
+ return true;
42
+ },
32
43
  async get<T>(key: string): Promise<T | null> {
33
44
  return map.has(key) ? (structuredClone(map.get(key)) as T) : null;
34
45
  },
@@ -51,6 +62,26 @@ export function createIndexedDbStorageAdapter(options: { dbName: string; storeNa
51
62
  const dbName = options.dbName;
52
63
  const storeName = options.storeName || "kv";
53
64
  return {
65
+ removePrefix: prefix => withIdb(dbName, storeName, db => new Promise<void>((resolve, reject) => {
66
+ const tx = db.transaction(storeName, "readwrite");
67
+ tx.objectStore(storeName).delete(IDBKeyRange.bound(prefix, `${prefix}\uffff`));
68
+ tx.oncomplete = () => resolve();
69
+ tx.onabort = tx.onerror = () => reject(tx.error || new Error("Atomic removal failed"));
70
+ })),
71
+ insertIfEmpty: (prefix, entries) => withIdb(dbName, storeName, db => new Promise((resolve, reject) => {
72
+ const tx = db.transaction(storeName, "readwrite"), store = tx.objectStore(storeName);
73
+ let inserted = false;
74
+ const count = store.count(IDBKeyRange.bound(prefix, `${prefix}\uffff`));
75
+ count.onsuccess = () => {
76
+ if (count.result) return;
77
+ try {
78
+ for (const { key, value } of entries) store.put(value, key);
79
+ inserted = true;
80
+ } catch (error) { tx.abort(); reject(error); }
81
+ };
82
+ tx.oncomplete = () => resolve(inserted);
83
+ tx.onabort = tx.onerror = () => reject(tx.error || new Error("Atomic write failed"));
84
+ })),
54
85
  get: <T>(key: string) =>
55
86
  withIdb<T | null>(dbName, storeName, (db) =>
56
87
  requestPromise<T | null>((resolve, reject) => {
@@ -1,17 +1,19 @@
1
1
  // HTTP transport for the open bucket surface: GET current, GET version
2
- // payload, and object CAS write. Session credentials come from the auth
3
- // layer; a 401 triggers one forced session refresh and retry before the
4
- // error escalates (the auth layer decides whether that means disconnected).
2
+ // payload, object CAS write, and current-head listing. Session credentials
3
+ // come from the auth layer; a 401 triggers one forced session refresh and
4
+ // retry before the error escalates (the auth layer decides whether that
5
+ // means disconnected).
5
6
 
6
7
  import { fnv1a32Bytes, utf8Encode } from "../internal/encoding.ts";
7
8
  import { decryptEnvelope, encryptEnvelopeFields } from "./crypto.ts";
8
9
  import type { BucketKeys } from "./keys.ts";
10
+ import { REVOKED_AUTHORIZATION_CODES } from "../errors.ts";
9
11
 
10
12
  export type SessionCredential = { carrier: "bearer"; token: string } | { carrier: "cookie" };
11
13
 
12
14
  export type SessionProvider = {
13
15
  getSession(options?: { forceRefresh?: boolean }): Promise<SessionCredential>;
14
- onUnauthorized?: () => void;
16
+ onUnauthorized?: () => void | Promise<void>;
15
17
  };
16
18
 
17
19
  export type TransportHeadResult = { found: false } | { found: true; versionId: string };
@@ -34,10 +36,10 @@ export class BucketTransportError extends Error {
34
36
  readonly status: number;
35
37
  readonly retryable: boolean;
36
38
 
37
- constructor(message: string, status: number) {
39
+ constructor(message: string, status: number, retryable = status === 429 || status >= 500) {
38
40
  super(message);
39
41
  this.status = status;
40
- this.retryable = status === 429 || status >= 500;
42
+ this.retryable = retryable;
41
43
  }
42
44
  }
43
45
 
@@ -46,6 +48,7 @@ export type BucketTransportOptions = {
46
48
  mfid: string;
47
49
  keys: BucketKeys;
48
50
  sessionProvider: SessionProvider;
51
+ fetch?: typeof fetch;
49
52
  };
50
53
 
51
54
  export class BucketTransport {
@@ -53,12 +56,14 @@ export class BucketTransport {
53
56
  private readonly mfid: string;
54
57
  private readonly keys: BucketKeys;
55
58
  private readonly sessionProvider: SessionProvider;
59
+ private readonly fetch: typeof fetch;
56
60
 
57
61
  constructor(options: BucketTransportOptions) {
58
62
  this.apiBase = options.apiBase.replace(/\/+$/, "");
59
63
  this.mfid = options.mfid;
60
64
  this.keys = options.keys;
61
65
  this.sessionProvider = options.sessionProvider;
66
+ this.fetch = options.fetch ?? ((...args) => globalThis.fetch(...args));
62
67
  }
63
68
 
64
69
  async pullHead(wireObjectId: string): Promise<TransportHeadResult> {
@@ -136,25 +141,72 @@ export class BucketTransport {
136
141
  return { ok: false, conflict: true, remoteVersionId: body?.headVersionId ?? null };
137
142
  }
138
143
  if (!res.ok) throw new BucketTransportError(`push failed: ${res.status}`, res.status);
139
- return { ok: true, versionId };
144
+ const result = await readJsonObject(res, "push");
145
+ if (result.ok === true) return { ok: true, versionId };
146
+ if (result.ok === false && ["version-mismatch", "conflict"].includes(String(result.reason))) {
147
+ return { ok: false, conflict: true, remoteVersionId: typeof result.headVersionId === "string" ? result.headVersionId : null };
148
+ }
149
+ if (result.ok === false && result.reason === "unauthorized") {
150
+ await this.sessionProvider.onUnauthorized?.();
151
+ throw new BucketTransportError("push was not authorized", 401, false);
152
+ }
153
+ throw new BucketTransportError(`push returned an unconfirmed acknowledgement${typeof result.reason === "string" ? `: ${result.reason}` : ""}`,
154
+ res.status, result.reason !== "invalid-input");
140
155
  }
141
156
 
142
- private objectUrl(wireObjectId: string): string {
157
+ async listHeads(): Promise<Map<string, string>> {
158
+ const heads = new Map<string, string>();
159
+ const indexRes = await this.request(() => ({ url: `${this.bucketUrl()}/objects:index`, init: { method: "GET" } }));
160
+ if (!indexRes.ok) throw new BucketTransportError(`object index failed: ${indexRes.status}`, indexRes.status);
161
+ const index = await readJsonObject(indexRes, "object index");
162
+ if (!Array.isArray(index.objects)) throw new BucketTransportError("object index returned invalid response", indexRes.status);
163
+ addHeads(heads, index.objects);
164
+ let cursor = typeof index.feedCursor === "string" ? index.feedCursor : null;
165
+ let hasMore = index.hasMoreFeed === true;
166
+ for (let page = 0; hasMore; page += 1) {
167
+ if (page >= MAX_FEED_PAGES) throw new BucketTransportError("feed did not end within page limit", 500);
168
+ const query = new URLSearchParams({ limit: String(FEED_PAGE_LIMIT) });
169
+ if (cursor) query.set("cursor", cursor);
170
+ const feedRes = await this.request(() => ({ url: `${this.bucketUrl()}/feed?${query}`, init: { method: "GET" } }));
171
+ if (!feedRes.ok) throw new BucketTransportError(`feed failed: ${feedRes.status}`, feedRes.status);
172
+ const feed = await readJsonObject(feedRes, "feed");
173
+ if (!Array.isArray(feed.entries)) throw new BucketTransportError("feed returned invalid response", feedRes.status);
174
+ addHeads(heads, feed.entries);
175
+ const next = typeof feed.cursor === "string" ? feed.cursor : null;
176
+ hasMore = feed.hasMore === true && next !== null && next !== cursor;
177
+ cursor = next;
178
+ }
179
+ return heads;
180
+ }
181
+
182
+ private bucketUrl(): string {
143
183
  const syncRoot = this.apiBase.endsWith("/v1/api/sync") ? this.apiBase : `${this.apiBase}/v1/api/sync`;
144
- return `${syncRoot}/buckets/${encodeURIComponent(this.keys.bucketId)}/objects/${encodeURIComponent(wireObjectId)}`;
184
+ return `${syncRoot}/buckets/${encodeURIComponent(this.keys.bucketId)}`;
185
+ }
186
+
187
+ private objectUrl(wireObjectId: string): string {
188
+ return `${this.bucketUrl()}/objects/${encodeURIComponent(wireObjectId)}`;
145
189
  }
146
190
 
147
191
  private async request(build: () => { url: string; init: RequestInit }): Promise<Response> {
148
192
  let session = await this.sessionProvider.getSession();
149
193
  let res = await this.send(build(), session);
150
194
  if (res.status === 401) {
195
+ void res.body?.cancel().catch(() => {});
151
196
  session = await this.sessionProvider.getSession({ forceRefresh: true });
152
197
  res = await this.send(build(), session);
153
198
  if (res.status === 401) {
154
- this.sessionProvider.onUnauthorized?.();
199
+ await this.sessionProvider.onUnauthorized?.();
155
200
  throw new BucketTransportError("bucket session unauthorized", 401);
156
201
  }
157
202
  }
203
+ if (res.status === 403) {
204
+ const body = await res.clone().json().catch(() => null) as { code?: string } | null;
205
+ if (REVOKED_AUTHORIZATION_CODES.includes(body?.code || "")) {
206
+ await this.sessionProvider.onUnauthorized?.();
207
+ throw new BucketTransportError("bucket authorization revoked", 403);
208
+ }
209
+ }
158
210
  return res;
159
211
  }
160
212
 
@@ -162,7 +214,7 @@ export class BucketTransport {
162
214
  const headers = new Headers(req.init.headers);
163
215
  headers.set("x-myfield-mfid", this.mfid);
164
216
  if (session.carrier === "bearer") headers.set("Authorization", `Bearer ${session.token}`);
165
- return fetch(req.url, {
217
+ return this.fetch(req.url, {
166
218
  ...req.init,
167
219
  headers,
168
220
  ...(session.carrier === "cookie" ? { credentials: "include" as RequestCredentials } : {}),
@@ -170,6 +222,16 @@ export class BucketTransport {
170
222
  }
171
223
  }
172
224
 
225
+ const FEED_PAGE_LIMIT = 100;
226
+ const MAX_FEED_PAGES = 10_000;
227
+
228
+ function addHeads(heads: Map<string, string>, entries: unknown[]): void {
229
+ for (const entry of entries) {
230
+ const row = entry as { objectId?: unknown; versionId?: unknown } | null;
231
+ if (typeof row?.objectId === "string" && typeof row.versionId === "string") heads.set(row.objectId, row.versionId);
232
+ }
233
+ }
234
+
173
235
  async function readJsonObject(res: Response, label: string): Promise<Record<string, unknown>> {
174
236
  const contentType = res.headers.get("content-type") || "";
175
237
  if (contentType && !contentType.toLowerCase().includes("application/json")) {
package/src/errors.ts CHANGED
@@ -7,3 +7,34 @@ export class NotConnectedError extends Error {
7
7
  this.name = "NotConnectedError";
8
8
  }
9
9
  }
10
+
11
+ export const REVOKED_AUTHORIZATION_CODES: readonly string[] = ["GRANT_REVOKED", "GRANT_NOT_FOUND", "AUTH_FAILED"];
12
+
13
+ export type ClientErrorOptions = {
14
+ status?: number;
15
+ requestId?: string;
16
+ retryable?: boolean;
17
+ retryAfterMs?: number;
18
+ maxBytes?: number;
19
+ cause?: unknown;
20
+ };
21
+
22
+ export class ClientError extends Error {
23
+ readonly code: string;
24
+ readonly status?: number;
25
+ readonly requestId?: string;
26
+ readonly retryable: boolean;
27
+ readonly retryAfterMs?: number;
28
+ readonly maxBytes?: number;
29
+
30
+ constructor(code: string, message: string, options: ClientErrorOptions = {}) {
31
+ super(message, { cause: options.cause });
32
+ this.name = "ClientError";
33
+ this.code = code;
34
+ this.status = options.status;
35
+ this.requestId = options.requestId;
36
+ this.retryable = options.retryable ?? false;
37
+ this.retryAfterMs = options.retryAfterMs;
38
+ this.maxBytes = options.maxBytes;
39
+ }
40
+ }