@myfield/sdk 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,187 @@
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).
5
+
6
+ import { fnv1a32Bytes, utf8Encode } from "../internal/encoding.ts";
7
+ import { decryptEnvelope, encryptEnvelopeFields } from "./crypto.ts";
8
+ import type { BucketKeys } from "./keys.ts";
9
+
10
+ export type SessionCredential = { carrier: "bearer"; token: string } | { carrier: "cookie" };
11
+
12
+ export type SessionProvider = {
13
+ getSession(options?: { forceRefresh?: boolean }): Promise<SessionCredential>;
14
+ onUnauthorized?: () => void;
15
+ };
16
+
17
+ export type TransportHeadResult = { found: false } | { found: true; versionId: string };
18
+ export type TransportPayloadResult = { found: false } | { found: true; plaintext: Uint8Array };
19
+ export type TransportPullResult = { found: false } | { found: true; versionId: string; plaintext: Uint8Array };
20
+
21
+ export type TransportPushResult = { ok: true; versionId: string } | { ok: false; conflict: true; remoteVersionId: string | null };
22
+
23
+ // Thrown by sync attempts while the app is not connected. Local reads and
24
+ // writes never hit the transport, so local-first operation is unaffected;
25
+ // sync resumes once a connection is established.
26
+ export class OfflineError extends Error {
27
+ constructor() {
28
+ super("not connected to cloud sync");
29
+ this.name = "OfflineError";
30
+ }
31
+ }
32
+
33
+ export class BucketTransportError extends Error {
34
+ readonly status: number;
35
+ readonly retryable: boolean;
36
+
37
+ constructor(message: string, status: number) {
38
+ super(message);
39
+ this.status = status;
40
+ this.retryable = status === 429 || status >= 500;
41
+ }
42
+ }
43
+
44
+ export type BucketTransportOptions = {
45
+ apiBase: string;
46
+ mfid: string;
47
+ keys: BucketKeys;
48
+ sessionProvider: SessionProvider;
49
+ };
50
+
51
+ export class BucketTransport {
52
+ private readonly apiBase: string;
53
+ private readonly mfid: string;
54
+ private readonly keys: BucketKeys;
55
+ private readonly sessionProvider: SessionProvider;
56
+
57
+ constructor(options: BucketTransportOptions) {
58
+ this.apiBase = options.apiBase.replace(/\/+$/, "");
59
+ this.mfid = options.mfid;
60
+ this.keys = options.keys;
61
+ this.sessionProvider = options.sessionProvider;
62
+ }
63
+
64
+ async pullHead(wireObjectId: string): Promise<TransportHeadResult> {
65
+ const currentRes = await this.request(() => ({
66
+ url: `${this.objectUrl(wireObjectId)}/current?miss=null`,
67
+ init: { method: "GET" },
68
+ }));
69
+ if (currentRes.status === 404) return { found: false };
70
+ if (!currentRes.ok) throw new BucketTransportError(`pull current failed: ${currentRes.status}`, currentRes.status);
71
+ const body = await readJsonObject(currentRes, "pull current");
72
+ if (!("versionId" in body) || (body.versionId !== null && typeof body.versionId !== "string")) {
73
+ throw new BucketTransportError("pull current returned invalid response", currentRes.status);
74
+ }
75
+ if (!body.versionId) return { found: false };
76
+ return { found: true, versionId: body.versionId };
77
+ }
78
+
79
+ async pullPayload(wireObjectId: string, versionId: string): Promise<TransportPayloadResult> {
80
+ const payloadRes = await this.request(() => ({
81
+ url: `${this.objectUrl(wireObjectId)}/versions/${encodeURIComponent(versionId)}/payload`,
82
+ init: { method: "GET" },
83
+ }));
84
+ if (payloadRes.status === 404) return { found: false };
85
+ if (!payloadRes.ok) throw new BucketTransportError(`pull payload failed: ${payloadRes.status}`, payloadRes.status);
86
+ const envelope = new Uint8Array(await payloadRes.arrayBuffer());
87
+ const plaintext = await decryptEnvelope(this.keys, wireObjectId, envelope);
88
+ return { found: true, plaintext };
89
+ }
90
+
91
+ async pullCurrent(wireObjectId: string): Promise<TransportPullResult> {
92
+ const head = await this.pullHead(wireObjectId);
93
+ if (!head.found) return { found: false };
94
+ const payload = await this.pullPayload(wireObjectId, head.versionId);
95
+ if (!payload.found) return { found: false };
96
+ return { found: true, versionId: head.versionId, plaintext: payload.plaintext };
97
+ }
98
+
99
+ async push(wireObjectId: string, plaintext: Uint8Array, expectedHeadVersionId: string | null): Promise<TransportPushResult> {
100
+ const versionId = crypto.randomUUID();
101
+ const kind = expectedHeadVersionId == null ? "create" : "update";
102
+ const contentHash = fnv1a32Bytes(plaintext);
103
+ const cipherFields = await encryptEnvelopeFields(this.keys, wireObjectId, plaintext);
104
+ const versionPayload = utf8Encode(
105
+ JSON.stringify({
106
+ objectId: wireObjectId,
107
+ versionId,
108
+ kind,
109
+ parentVersionIds: expectedHeadVersionId ? [expectedHeadVersionId] : [],
110
+ ...cipherFields,
111
+ })
112
+ );
113
+ const versionMeta = {
114
+ objectId: wireObjectId,
115
+ versionId,
116
+ parentVersionIds: expectedHeadVersionId ? [expectedHeadVersionId] : [],
117
+ contentHash,
118
+ kind,
119
+ timestamp: Date.now(),
120
+ };
121
+ const headState = {
122
+ headVersionId: versionId,
123
+ historyMap: { [versionId]: expectedHeadVersionId ? [expectedHeadVersionId] : [] },
124
+ fieldSources: {},
125
+ };
126
+ const res = await this.request(() => {
127
+ const form = new FormData();
128
+ form.set("versionMeta", JSON.stringify(versionMeta));
129
+ form.set("headState", JSON.stringify(headState));
130
+ form.set("versionPayload", new Blob([versionPayload.buffer.slice(versionPayload.byteOffset, versionPayload.byteOffset + versionPayload.byteLength) as ArrayBuffer], { type: "application/octet-stream" }));
131
+ if (expectedHeadVersionId != null) form.set("expectedHeadVersionId", expectedHeadVersionId);
132
+ return { url: this.objectUrl(wireObjectId), init: { method: "POST", body: form } };
133
+ });
134
+ if (res.status === 409) {
135
+ const body = (await res.json().catch(() => null)) as { headVersionId?: string | null } | null;
136
+ return { ok: false, conflict: true, remoteVersionId: body?.headVersionId ?? null };
137
+ }
138
+ if (!res.ok) throw new BucketTransportError(`push failed: ${res.status}`, res.status);
139
+ return { ok: true, versionId };
140
+ }
141
+
142
+ private objectUrl(wireObjectId: string): string {
143
+ 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)}`;
145
+ }
146
+
147
+ private async request(build: () => { url: string; init: RequestInit }): Promise<Response> {
148
+ let session = await this.sessionProvider.getSession();
149
+ let res = await this.send(build(), session);
150
+ if (res.status === 401) {
151
+ session = await this.sessionProvider.getSession({ forceRefresh: true });
152
+ res = await this.send(build(), session);
153
+ if (res.status === 401) {
154
+ this.sessionProvider.onUnauthorized?.();
155
+ throw new BucketTransportError("bucket session unauthorized", 401);
156
+ }
157
+ }
158
+ return res;
159
+ }
160
+
161
+ private send(req: { url: string; init: RequestInit }, session: SessionCredential): Promise<Response> {
162
+ const headers = new Headers(req.init.headers);
163
+ headers.set("x-myfield-mfid", this.mfid);
164
+ if (session.carrier === "bearer") headers.set("Authorization", `Bearer ${session.token}`);
165
+ return fetch(req.url, {
166
+ ...req.init,
167
+ headers,
168
+ ...(session.carrier === "cookie" ? { credentials: "include" as RequestCredentials } : {}),
169
+ });
170
+ }
171
+ }
172
+
173
+ async function readJsonObject(res: Response, label: string): Promise<Record<string, unknown>> {
174
+ const contentType = res.headers.get("content-type") || "";
175
+ if (contentType && !contentType.toLowerCase().includes("application/json")) {
176
+ throw new BucketTransportError(`${label} returned non-json response`, res.status);
177
+ }
178
+ try {
179
+ const body = await res.json();
180
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
181
+ throw new Error("not an object");
182
+ }
183
+ return body as Record<string, unknown>;
184
+ } catch {
185
+ throw new BucketTransportError(`${label} returned invalid json`, res.status);
186
+ }
187
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,9 @@
1
+ // Public error classes. Exported unprefixed — the @myfield/sdk package
2
+ // scope is the namespace; `error.name` matches the class name.
3
+
4
+ export class NotConnectedError extends Error {
5
+ constructor() {
6
+ super("bucket is not connected; call connect() first");
7
+ this.name = "NotConnectedError";
8
+ }
9
+ }