@backwrite/sdk 0.1.1 → 0.2.1

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,451 @@
1
+ //! High-level ergonomic service namespaces for @backwrite/sdk v0.2.0.
2
+ //! Covers SQL + fluent query builder, Auth (including terminal OTP signup),
3
+ //! CoW Branches & PITR, S3 Storage, Valkey Cache, JetStream Queues,
4
+ //! pgvector AI Search, Realtime WS tickets/broadcast, AES-256-GCM Secrets,
5
+ //! 5-Engine Backend Advisors, and Organization Quotas & Billing.
6
+
7
+ import type { BackwriteClient } from "./client.js";
8
+
9
+ export interface ScopeOptions {
10
+ projectId?: string;
11
+ branchId?: string;
12
+ }
13
+
14
+ export interface QueryResult<T = Record<string, unknown>> {
15
+ success?: boolean;
16
+ columns?: string[];
17
+ rows?: T[] | unknown[][];
18
+ summary?: string;
19
+ execution_time_ms?: number;
20
+ error?: string;
21
+ }
22
+
23
+ function requireId(val: string | undefined, label: string): string {
24
+ if (!val) throw new Error(`Backwrite SDK: ${label} is required (pass in client options or method options)`);
25
+ return encodeURIComponent(val);
26
+ }
27
+
28
+ function sqlLiteral(v: unknown): string {
29
+ if (v === null || v === undefined) return "NULL";
30
+ if (typeof v === "number" && Number.isFinite(v)) return String(v);
31
+ if (typeof v === "boolean") return v ? "TRUE" : "FALSE";
32
+ if (typeof v === "object") return `'${JSON.stringify(v).replace(/'/g, "''")}'::jsonb`;
33
+ return `'${String(v).replace(/'/g, "''")}'`;
34
+ }
35
+
36
+ function safeIdent(name: string): string {
37
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {
38
+ throw new Error(`Invalid SQL identifier: ${name}`);
39
+ }
40
+ return `"${name}"`;
41
+ }
42
+
43
+ /** Fluent table query builder backed by Backwrite's PostgreSQL 18 Data API. */
44
+ export class TableQueryBuilder<T = Record<string, unknown>> {
45
+ private cols = "*";
46
+ private wheres: string[] = [];
47
+ private orderClause = "";
48
+ private limitClause = "";
49
+ private offsetClause = "";
50
+
51
+ constructor(
52
+ private readonly db: DbService,
53
+ private readonly table: string,
54
+ private readonly scope: ScopeOptions = {},
55
+ ) {}
56
+
57
+ select(columns: string | string[] = "*"): this {
58
+ this.cols = Array.isArray(columns) ? columns.map(safeIdent).join(", ") : columns;
59
+ return this;
60
+ }
61
+
62
+ eq(column: string, value: unknown): this {
63
+ this.wheres.push(`${safeIdent(column)} = ${sqlLiteral(value)}`);
64
+ return this;
65
+ }
66
+
67
+ neq(column: string, value: unknown): this {
68
+ this.wheres.push(`${safeIdent(column)} <> ${sqlLiteral(value)}`);
69
+ return this;
70
+ }
71
+
72
+ gt(column: string, value: unknown): this {
73
+ this.wheres.push(`${safeIdent(column)} > ${sqlLiteral(value)}`);
74
+ return this;
75
+ }
76
+
77
+ lt(column: string, value: unknown): this {
78
+ this.wheres.push(`${safeIdent(column)} < ${sqlLiteral(value)}`);
79
+ return this;
80
+ }
81
+
82
+ ilike(column: string, pattern: string): this {
83
+ this.wheres.push(`${safeIdent(column)} ILIKE ${sqlLiteral(pattern)}`);
84
+ return this;
85
+ }
86
+
87
+ order(column: string, direction: "asc" | "desc" = "asc"): this {
88
+ this.orderClause = ` ORDER BY ${safeIdent(column)} ${direction.toUpperCase()}`;
89
+ return this;
90
+ }
91
+
92
+ limit(n: number): this {
93
+ this.limitClause = ` LIMIT ${Math.max(0, Math.floor(n))}`;
94
+ return this;
95
+ }
96
+
97
+ offset(n: number): this {
98
+ this.offsetClause = ` OFFSET ${Math.max(0, Math.floor(n))}`;
99
+ return this;
100
+ }
101
+
102
+ toSQL(): string {
103
+ const where = this.wheres.length ? ` WHERE ${this.wheres.join(" AND ")}` : "";
104
+ return `SELECT ${this.cols} FROM public.${safeIdent(this.table)}${where}${this.orderClause}${this.limitClause}${this.offsetClause};`;
105
+ }
106
+
107
+ async execute(): Promise<T[]> {
108
+ const res = await this.db.query<T>(this.toSQL(), this.scope);
109
+ const cols = res.columns ?? [];
110
+ const rows = res.rows ?? [];
111
+ if (!rows.length) return [];
112
+ if (!Array.isArray(rows[0])) return rows as T[];
113
+ return (rows as unknown[][]).map((arr) => {
114
+ const obj: Record<string, unknown> = {};
115
+ cols.forEach((c, idx) => { obj[c] = arr[idx]; });
116
+ return obj as T;
117
+ });
118
+ }
119
+
120
+ async insert(record: Record<string, unknown> | Record<string, unknown>[]): Promise<QueryResult<T>> {
121
+ const items = Array.isArray(record) ? record : [record];
122
+ if (!items.length) throw new Error("insert() requires at least one record");
123
+ const keys = Object.keys(items[0]);
124
+ const colList = keys.map(safeIdent).join(", ");
125
+ const values = items.map((row) => `(${keys.map((k) => sqlLiteral(row[k])).join(", ")})`).join(", ");
126
+ return this.db.query<T>(
127
+ `INSERT INTO public.${safeIdent(this.table)} (${colList}) VALUES ${values} RETURNING *;`,
128
+ this.scope,
129
+ );
130
+ }
131
+
132
+ async update(patch: Record<string, unknown>): Promise<QueryResult<T>> {
133
+ const sets = Object.entries(patch).map(([k, v]) => `${safeIdent(k)} = ${sqlLiteral(v)}`).join(", ");
134
+ const where = this.wheres.length ? ` WHERE ${this.wheres.join(" AND ")}` : "";
135
+ return this.db.query<T>(
136
+ `UPDATE public.${safeIdent(this.table)} SET ${sets}${where} RETURNING *;`,
137
+ this.scope,
138
+ );
139
+ }
140
+
141
+ async delete(): Promise<QueryResult<T>> {
142
+ if (!this.wheres.length) throw new Error("delete() requires at least one filter (.eq/.neq/...)");
143
+ return this.db.query<T>(
144
+ `DELETE FROM public.${safeIdent(this.table)} WHERE ${this.wheres.join(" AND ")} RETURNING *;`,
145
+ this.scope,
146
+ );
147
+ }
148
+ }
149
+
150
+ export class DbService {
151
+ constructor(private readonly client: BackwriteClient) {}
152
+
153
+ from<T = Record<string, unknown>>(table: string, scope?: ScopeOptions): TableQueryBuilder<T> {
154
+ return new TableQueryBuilder<T>(this, table, scope);
155
+ }
156
+
157
+ async query<T = Record<string, unknown>>(sql: string, scope: ScopeOptions = {}): Promise<QueryResult<T>> {
158
+ const pid = requireId(scope.projectId ?? this.client.projectId, "projectId");
159
+ const bid = scope.branchId ?? this.client.branchId;
160
+ const endpoint = bid
161
+ ? `/v1/projects/${pid}/branches/${encodeURIComponent(bid)}/query`
162
+ : `/v1/projects/${pid}/query`;
163
+ return this.client.request<QueryResult<T>>("POST", endpoint, { body: { sql } });
164
+ }
165
+
166
+ async schema(scope: ScopeOptions = {}): Promise<unknown> {
167
+ const pid = requireId(scope.projectId ?? this.client.projectId, "projectId");
168
+ const bid = scope.branchId ?? this.client.branchId;
169
+ const endpoint = bid
170
+ ? `/v1/projects/${pid}/branches/${encodeURIComponent(bid)}/schema`
171
+ : `/v1/projects/${pid}/schema`;
172
+ return this.client.request("GET", endpoint);
173
+ }
174
+ }
175
+
176
+ export class AuthService {
177
+ constructor(private readonly client: BackwriteClient) {}
178
+
179
+ login(email: string, password: string): Promise<Record<string, unknown>> {
180
+ return this.client.request("POST", "/v1/auth/login", { body: { email, password } });
181
+ }
182
+
183
+ cliSignup(email: string, orgName?: string): Promise<Record<string, unknown>> {
184
+ return this.client.request("POST", "/v1/auth/cli-signup", { body: { email, org_name: orgName } });
185
+ }
186
+
187
+ cliSignupVerify(email: string, code: string, orgName?: string): Promise<Record<string, unknown>> {
188
+ return this.client.request("POST", "/v1/auth/cli-signup/verify", {
189
+ body: { email, code, org_name: orgName },
190
+ });
191
+ }
192
+
193
+ me(): Promise<Record<string, unknown>> {
194
+ return this.client.request("GET", "/v1/auth/me");
195
+ }
196
+
197
+ listUsers(scope: ScopeOptions & { search?: string } = {}): Promise<unknown> {
198
+ const pid = requireId(scope.projectId ?? this.client.projectId, "projectId");
199
+ return this.client.request("GET", `/v1/projects/${pid}/auth/users`, {
200
+ query: scope.search ? { search: scope.search } : undefined,
201
+ });
202
+ }
203
+ }
204
+
205
+ export class BranchesService {
206
+ constructor(private readonly client: BackwriteClient) {}
207
+
208
+ list(projectId?: string): Promise<unknown> {
209
+ const pid = requireId(projectId ?? this.client.projectId, "projectId");
210
+ return this.client.request("GET", `/v1/projects/${pid}/branches`);
211
+ }
212
+
213
+ create(name: string, options: { projectId?: string; type?: string; mode?: string } = {}): Promise<unknown> {
214
+ const pid = requireId(options.projectId ?? this.client.projectId, "projectId");
215
+ return this.client.request("POST", `/v1/projects/${pid}/branches`, {
216
+ body: { name, branch_type: options.type ?? "preview", ...(options.mode ? { mode: options.mode } : {}) },
217
+ });
218
+ }
219
+
220
+ delete(branchId: string, projectId?: string): Promise<unknown> {
221
+ const pid = requireId(projectId ?? this.client.projectId, "projectId");
222
+ return this.client.request("DELETE", `/v1/projects/${pid}/branches/${encodeURIComponent(branchId)}`);
223
+ }
224
+
225
+ listSnapshots(scope: ScopeOptions = {}): Promise<unknown> {
226
+ const pid = requireId(scope.projectId ?? this.client.projectId, "projectId");
227
+ const bid = requireId(scope.branchId ?? this.client.branchId, "branchId");
228
+ return this.client.request("GET", `/v1/projects/${pid}/branches/${bid}/snapshots`);
229
+ }
230
+
231
+ createSnapshot(label: string, scope: ScopeOptions = {}): Promise<unknown> {
232
+ const pid = requireId(scope.projectId ?? this.client.projectId, "projectId");
233
+ const bid = requireId(scope.branchId ?? this.client.branchId, "branchId");
234
+ return this.client.request("POST", `/v1/projects/${pid}/branches/${bid}/snapshots`, {
235
+ body: { label, name: label },
236
+ });
237
+ }
238
+ }
239
+
240
+ export class StorageService {
241
+ constructor(private readonly client: BackwriteClient) {}
242
+
243
+ listBuckets(projectId?: string): Promise<unknown> {
244
+ const pid = requireId(projectId ?? this.client.projectId, "projectId");
245
+ return this.client.request("GET", `/v1/projects/${pid}/buckets`);
246
+ }
247
+
248
+ createBucket(name: string, options: { projectId?: string; isPublic?: boolean } = {}): Promise<unknown> {
249
+ const pid = requireId(options.projectId ?? this.client.projectId, "projectId");
250
+ return this.client.request("POST", `/v1/projects/${pid}/buckets`, {
251
+ body: { bucket_name: name, name, is_public: Boolean(options.isPublic) },
252
+ });
253
+ }
254
+
255
+ upload(bucket: string, key: string, data: Uint8Array | ArrayBuffer | string, branchId?: string): Promise<unknown> {
256
+ const bid = requireId(branchId ?? this.client.branchId, "branchId");
257
+ return this.client.request(
258
+ "PUT",
259
+ `/v1/storage/${bid}/${encodeURIComponent(bucket)}/${key.replace(/^\/+/, "")}`,
260
+ { body: data },
261
+ );
262
+ }
263
+
264
+ download(bucket: string, key: string, branchId?: string): Promise<unknown> {
265
+ const bid = requireId(branchId ?? this.client.branchId, "branchId");
266
+ return this.client.request(
267
+ "GET",
268
+ `/v1/storage/${bid}/${encodeURIComponent(bucket)}/${key.replace(/^\/+/, "")}`,
269
+ );
270
+ }
271
+
272
+ deleteObject(bucket: string, key: string, branchId?: string): Promise<unknown> {
273
+ const bid = requireId(branchId ?? this.client.branchId, "branchId");
274
+ return this.client.request(
275
+ "DELETE",
276
+ `/v1/storage/${bid}/${encodeURIComponent(bucket)}/${key.replace(/^\/+/, "")}`,
277
+ );
278
+ }
279
+ }
280
+
281
+ export class CacheService {
282
+ constructor(private readonly client: BackwriteClient) {}
283
+
284
+ get(key: string, branchId?: string): Promise<unknown> {
285
+ const bid = requireId(branchId ?? this.client.branchId, "branchId");
286
+ return this.client.request("GET", `/v1/cache/${bid}/kv/${encodeURIComponent(key)}`);
287
+ }
288
+
289
+ set(key: string, value: unknown, ttlSeconds?: number, branchId?: string): Promise<unknown> {
290
+ const bid = requireId(branchId ?? this.client.branchId, "branchId");
291
+ return this.client.request("PUT", `/v1/cache/${bid}/kv/${encodeURIComponent(key)}`, {
292
+ body: { value, ...(ttlSeconds !== undefined ? { ttl_seconds: ttlSeconds } : {}) },
293
+ });
294
+ }
295
+
296
+ del(key: string, branchId?: string): Promise<unknown> {
297
+ const bid = requireId(branchId ?? this.client.branchId, "branchId");
298
+ return this.client.request("DELETE", `/v1/cache/${bid}/kv/${encodeURIComponent(key)}`);
299
+ }
300
+ }
301
+
302
+ export class QueuesService {
303
+ constructor(private readonly client: BackwriteClient) {}
304
+
305
+ publish(queue: string, payload: unknown, branchId?: string): Promise<unknown> {
306
+ const bid = requireId(branchId ?? this.client.branchId, "branchId");
307
+ return this.client.request("POST", `/v1/queues/${bid}/${encodeURIComponent(queue)}/messages`, {
308
+ body: { payload },
309
+ });
310
+ }
311
+
312
+ pull(queue: string, batch = 1, branchId?: string): Promise<unknown> {
313
+ const bid = requireId(branchId ?? this.client.branchId, "branchId");
314
+ return this.client.request("POST", `/v1/queues/${bid}/${encodeURIComponent(queue)}/pull`, {
315
+ body: { batch },
316
+ });
317
+ }
318
+
319
+ ack(queue: string, ackToken: string, action: "ack" | "nack" = "ack", branchId?: string): Promise<unknown> {
320
+ const bid = requireId(branchId ?? this.client.branchId, "branchId");
321
+ return this.client.request("POST", `/v1/queues/${bid}/${encodeURIComponent(queue)}/ack`, {
322
+ body: { ack_token: ackToken, action },
323
+ });
324
+ }
325
+
326
+ stats(queue = "default", projectId?: string): Promise<unknown> {
327
+ const pid = requireId(projectId ?? this.client.projectId, "projectId");
328
+ return this.client.request("GET", `/v1/projects/${pid}/queues/${encodeURIComponent(queue)}/stats`);
329
+ }
330
+ }
331
+
332
+ export class VectorService {
333
+ constructor(private readonly client: BackwriteClient) {}
334
+
335
+ listIndexes(branchId?: string): Promise<unknown> {
336
+ const bid = requireId(branchId ?? this.client.branchId, "branchId");
337
+ return this.client.request("GET", `/v1/search/${bid}/indexes`);
338
+ }
339
+
340
+ createIndex(name: string, dimensions: number, metric: "cosine" | "l2" | "ip" = "cosine", branchId?: string): Promise<unknown> {
341
+ const bid = requireId(branchId ?? this.client.branchId, "branchId");
342
+ return this.client.request("POST", `/v1/search/${bid}/indexes`, {
343
+ body: { name, dimensions, metric },
344
+ });
345
+ }
346
+
347
+ upsert(index: string, rows: Array<{ id: string; embedding: number[]; metadata?: Record<string, unknown> }>, branchId?: string): Promise<unknown> {
348
+ const bid = requireId(branchId ?? this.client.branchId, "branchId");
349
+ return this.client.request("POST", `/v1/search/${bid}/indexes/${encodeURIComponent(index)}/upsert`, {
350
+ body: { rows },
351
+ });
352
+ }
353
+
354
+ query(index: string, embedding: number[], topK = 5, branchId?: string): Promise<unknown> {
355
+ const bid = requireId(branchId ?? this.client.branchId, "branchId");
356
+ return this.client.request("POST", `/v1/search/${bid}/indexes/${encodeURIComponent(index)}/query`, {
357
+ body: { embedding, top_k: topK },
358
+ });
359
+ }
360
+ }
361
+
362
+ export class RealtimeService {
363
+ constructor(private readonly client: BackwriteClient) {}
364
+
365
+ createTicket(branchId?: string): Promise<{ ticket: string; expires_in?: number }> {
366
+ const bid = requireId(branchId ?? this.client.branchId, "branchId");
367
+ return this.client.request("POST", `/v1/realtime/${bid}/ticket`, { body: {} });
368
+ }
369
+
370
+ broadcast(channel: string, event: string, payload: Record<string, unknown>, branchId?: string): Promise<unknown> {
371
+ const bid = requireId(branchId ?? this.client.branchId, "branchId");
372
+ return this.client.request("POST", `/v1/realtime/${bid}/broadcast`, {
373
+ body: { channel, event, payload },
374
+ });
375
+ }
376
+ }
377
+
378
+ export class SecretsService {
379
+ constructor(private readonly client: BackwriteClient) {}
380
+
381
+ list(projectId?: string): Promise<unknown> {
382
+ const pid = requireId(projectId ?? this.client.projectId, "projectId");
383
+ return this.client.request("GET", `/v1/projects/${pid}/config/secrets`);
384
+ }
385
+
386
+ set(key: string, value: string, projectId?: string): Promise<unknown> {
387
+ const pid = requireId(projectId ?? this.client.projectId, "projectId");
388
+ return this.client.request("POST", `/v1/projects/${pid}/config/secrets`, { body: { key, value } });
389
+ }
390
+
391
+ delete(key: string, projectId?: string): Promise<unknown> {
392
+ const pid = requireId(projectId ?? this.client.projectId, "projectId");
393
+ return this.client.request("DELETE", `/v1/projects/${pid}/config/secrets/${encodeURIComponent(key)}`);
394
+ }
395
+ }
396
+
397
+ export class AdvisorsService {
398
+ constructor(private readonly client: BackwriteClient) {}
399
+
400
+ list(projectId?: string): Promise<unknown> {
401
+ const pid = requireId(projectId ?? this.client.projectId, "projectId");
402
+ return this.client.request("GET", `/v1/projects/${pid}/advisors`);
403
+ }
404
+
405
+ scan(scope: ScopeOptions = {}): Promise<unknown> {
406
+ const pid = requireId(scope.projectId ?? this.client.projectId, "projectId");
407
+ return this.client.request("POST", `/v1/projects/${pid}/advisors/scan`, {
408
+ body: scope.branchId ? { branch_id: scope.branchId } : {},
409
+ });
410
+ }
411
+
412
+ simulate(advisoryId: string, projectId?: string): Promise<unknown> {
413
+ const pid = requireId(projectId ?? this.client.projectId, "projectId");
414
+ return this.client.request("POST", `/v1/projects/${pid}/advisors/${encodeURIComponent(advisoryId)}/simulate`, { body: {} });
415
+ }
416
+
417
+ apply(advisoryId: string, projectId?: string): Promise<unknown> {
418
+ const pid = requireId(projectId ?? this.client.projectId, "projectId");
419
+ return this.client.request("POST", `/v1/projects/${pid}/advisors/${encodeURIComponent(advisoryId)}/apply`, { body: {} });
420
+ }
421
+ }
422
+
423
+ export class OrgsService {
424
+ constructor(private readonly client: BackwriteClient) {}
425
+
426
+ list(): Promise<unknown> {
427
+ return this.client.request("GET", "/v1/organizations");
428
+ }
429
+
430
+ create(name: string, planTier = "free"): Promise<unknown> {
431
+ return this.client.request("POST", "/v1/organizations", {
432
+ body: { name, plan_tier: planTier, database_engine: "postgresql" },
433
+ });
434
+ }
435
+
436
+ usageLimits(orgId: string): Promise<unknown> {
437
+ return this.client.request("GET", `/v1/organizations/${encodeURIComponent(orgId)}/usage-limits`);
438
+ }
439
+
440
+ upgradePlan(orgId: string, planName: string, interval: "monthly" | "yearly" = "monthly"): Promise<unknown> {
441
+ return this.client.request("POST", `/v1/organizations/${encodeURIComponent(orgId)}/subscription`, {
442
+ body: { plan_name: planName, interval },
443
+ });
444
+ }
445
+
446
+ inviteMember(orgId: string, email: string, role = "member"): Promise<unknown> {
447
+ return this.client.request("POST", `/v1/organizations/${encodeURIComponent(orgId)}/members/invite`, {
448
+ body: { email, role },
449
+ });
450
+ }
451
+ }