get-db9 0.5.0 → 0.6.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.
package/dist/client.js CHANGED
@@ -242,6 +242,239 @@ function defaultCredentialStore() {
242
242
  return new FileCredentialStore();
243
243
  }
244
244
 
245
+ // src/ws.ts
246
+ var FsError = class extends Error {
247
+ code;
248
+ constructor(code, message) {
249
+ super(message);
250
+ this.name = "FsError";
251
+ this.code = code;
252
+ }
253
+ };
254
+ var nextId = 1;
255
+ function nextRequestId() {
256
+ return String(nextId++);
257
+ }
258
+ function toBase64(data) {
259
+ const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
260
+ if (typeof Buffer !== "undefined") {
261
+ return Buffer.from(bytes).toString("base64");
262
+ }
263
+ let binary = "";
264
+ for (let i = 0; i < bytes.length; i++) {
265
+ binary += String.fromCharCode(bytes[i]);
266
+ }
267
+ return btoa(binary);
268
+ }
269
+ function fromBase64(b64) {
270
+ if (typeof Buffer !== "undefined") {
271
+ return new Uint8Array(Buffer.from(b64, "base64"));
272
+ }
273
+ const binary = atob(b64);
274
+ const bytes = new Uint8Array(binary.length);
275
+ for (let i = 0; i < binary.length; i++) {
276
+ bytes[i] = binary.charCodeAt(i);
277
+ }
278
+ return bytes;
279
+ }
280
+ var FsClient = class _FsClient {
281
+ ws;
282
+ pending = /* @__PURE__ */ new Map();
283
+ closed = false;
284
+ constructor(ws) {
285
+ this.ws = ws;
286
+ ws.onmessage = (ev) => {
287
+ const text = typeof ev.data === "string" ? ev.data : String(ev.data);
288
+ let resp;
289
+ try {
290
+ resp = JSON.parse(text);
291
+ } catch {
292
+ return;
293
+ }
294
+ const p = this.pending.get(resp.id);
295
+ if (p) {
296
+ this.pending.delete(resp.id);
297
+ p.resolve(resp);
298
+ }
299
+ };
300
+ ws.onclose = () => {
301
+ this.closed = true;
302
+ for (const [, p] of this.pending) {
303
+ p.reject(new FsError("CONNECTION_CLOSED", "WebSocket connection closed"));
304
+ }
305
+ this.pending.clear();
306
+ };
307
+ ws.onerror = () => {
308
+ };
309
+ }
310
+ /**
311
+ * Connect to an fs9 WebSocket server.
312
+ *
313
+ * @param url WebSocket URL, e.g. `wss://host:5480`
314
+ * @param WS WebSocket constructor (native or from `ws` package)
315
+ */
316
+ static connect(url, WS) {
317
+ return new Promise((resolve, reject) => {
318
+ const ws = new WS(url);
319
+ ws.onopen = () => {
320
+ ws.onopen = null;
321
+ ws.onerror = null;
322
+ resolve(new _FsClient(ws));
323
+ };
324
+ ws.onerror = (ev) => {
325
+ ws.onopen = null;
326
+ ws.onerror = null;
327
+ const msg = ev && typeof ev === "object" && "message" in ev ? String(ev.message) : "WebSocket connection failed";
328
+ reject(new FsError("CONNECTION_ERROR", msg));
329
+ };
330
+ });
331
+ }
332
+ /** Authenticate with the server. Must be called first after connect. */
333
+ async authenticate(username, password) {
334
+ const resp = await this.sendAndRecv({
335
+ id: nextRequestId(),
336
+ op: "auth",
337
+ username,
338
+ password
339
+ });
340
+ if (!resp.ok) {
341
+ throw new FsError("AUTH_FAILED", this.errorMessage(resp));
342
+ }
343
+ const data = resp.data;
344
+ return {
345
+ user: String(data?.user ?? ""),
346
+ tenant: String(data?.tenant ?? ""),
347
+ keyspace: String(data?.keyspace ?? "")
348
+ };
349
+ }
350
+ /** Get file or directory metadata. */
351
+ async stat(path) {
352
+ const resp = await this.sendAndRecv({
353
+ id: nextRequestId(),
354
+ op: "stat",
355
+ path
356
+ });
357
+ this.expectOk(resp);
358
+ return resp.data;
359
+ }
360
+ /** List directory contents. */
361
+ async readdir(path) {
362
+ const resp = await this.sendAndRecv({
363
+ id: nextRequestId(),
364
+ op: "readdir",
365
+ path
366
+ });
367
+ this.expectOk(resp);
368
+ const data = resp.data;
369
+ return data?.entries ?? [];
370
+ }
371
+ /** Create a directory. Always recursive (mkdir -p). */
372
+ async mkdir(path, recursive = true) {
373
+ const resp = await this.sendAndRecv({
374
+ id: nextRequestId(),
375
+ op: "mkdir",
376
+ path,
377
+ recursive
378
+ });
379
+ this.expectOk(resp);
380
+ }
381
+ /** Read an entire file, returning raw bytes. */
382
+ async readFile(path) {
383
+ const resp = await this.sendAndRecv({
384
+ id: nextRequestId(),
385
+ op: "read",
386
+ path
387
+ });
388
+ this.expectOk(resp);
389
+ const data = resp.data;
390
+ const content = data?.content;
391
+ if (typeof content !== "string") {
392
+ throw new FsError("PROTOCOL", "missing content field in read response");
393
+ }
394
+ return fromBase64(content);
395
+ }
396
+ /** Write (overwrite) a file. Returns bytes written. */
397
+ async writeFile(path, data) {
398
+ const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data instanceof Uint8Array ? data : new Uint8Array(data);
399
+ const resp = await this.sendAndRecv({
400
+ id: nextRequestId(),
401
+ op: "write",
402
+ path,
403
+ content: toBase64(bytes),
404
+ encoding: "base64"
405
+ });
406
+ this.expectOk(resp);
407
+ const result = resp.data;
408
+ return result?.written ?? bytes.byteLength;
409
+ }
410
+ /** Append to a file. Returns bytes written. */
411
+ async appendFile(path, data) {
412
+ const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data instanceof Uint8Array ? data : new Uint8Array(data);
413
+ const resp = await this.sendAndRecv({
414
+ id: nextRequestId(),
415
+ op: "append",
416
+ path,
417
+ content: toBase64(bytes),
418
+ encoding: "base64"
419
+ });
420
+ this.expectOk(resp);
421
+ const result = resp.data;
422
+ return result?.written ?? bytes.byteLength;
423
+ }
424
+ /** Remove a file (non-recursive) or directory (recursive). */
425
+ async rm(path, recursive = false) {
426
+ const resp = await this.sendAndRecv(
427
+ recursive ? { id: nextRequestId(), op: "rm", path, recursive: true } : { id: nextRequestId(), op: "unlink", path }
428
+ );
429
+ this.expectOk(resp);
430
+ }
431
+ /** Rename (move) a file or directory. */
432
+ async rename(oldPath, newPath) {
433
+ const resp = await this.sendAndRecv({
434
+ id: nextRequestId(),
435
+ op: "rename",
436
+ old_path: oldPath,
437
+ new_path: newPath
438
+ });
439
+ this.expectOk(resp);
440
+ }
441
+ /** Gracefully close the WebSocket connection. */
442
+ async close() {
443
+ if (!this.closed) {
444
+ this.ws.close();
445
+ }
446
+ }
447
+ // ── internals ──────────────────────────────────────────────────
448
+ sendAndRecv(request) {
449
+ if (this.closed) {
450
+ return Promise.reject(new FsError("CONNECTION_CLOSED", "WebSocket is closed"));
451
+ }
452
+ return new Promise((resolve, reject) => {
453
+ const id = request.id;
454
+ this.pending.set(id, { resolve, reject });
455
+ try {
456
+ this.ws.send(JSON.stringify(request));
457
+ } catch (err) {
458
+ this.pending.delete(id);
459
+ reject(new FsError("CONNECTION_ERROR", String(err)));
460
+ }
461
+ });
462
+ }
463
+ expectOk(resp) {
464
+ if (!resp.ok) {
465
+ const detail = resp.error;
466
+ throw new FsError(
467
+ detail?.code ?? "UNKNOWN",
468
+ detail?.message ?? "unknown error"
469
+ );
470
+ }
471
+ }
472
+ errorMessage(resp) {
473
+ const detail = resp.error;
474
+ return detail ? `${detail.code}: ${detail.message}` : "unknown error";
475
+ }
476
+ };
477
+
245
478
  // src/client.ts
246
479
  function createDb9Client(options = {}) {
247
480
  const baseUrl = options.baseUrl ?? "https://db9.shared.aws.tidbcloud.com/api";
@@ -321,44 +554,42 @@ function createDb9Client(options = {}) {
321
554
  return operation(newClient);
322
555
  }
323
556
  }
324
- function deriveFs9Url(dbId) {
325
- const origin = baseUrl.replace(/\/api\/?$/, "");
326
- return `${origin}/fs9/${dbId}`;
327
- }
328
- function getFsClient(dbId) {
329
- const fs9Base = deriveFs9Url(dbId) + "/api/v1";
330
- return createHttpClient({
331
- baseUrl: fs9Base,
332
- fetch: options.fetch,
333
- headers: token ? { Authorization: `Bearer ${token}` } : {},
334
- timeout: options.timeout,
335
- maxRetries: options.maxRetries,
336
- retryDelay: options.retryDelay
337
- });
557
+ const fsWsPort = options.wsPort ?? 5480;
558
+ async function resolveFsConn(dbId) {
559
+ const creds = await withAuthRetry(
560
+ (client) => client.get(
561
+ `/customer/databases/${dbId}/credentials`
562
+ )
563
+ );
564
+ const connStr = creds.connection_string;
565
+ const hostMatch = connStr.match(/@([^:/?]+)/);
566
+ const host = hostMatch?.[1];
567
+ if (!host) {
568
+ throw new Error(`Cannot parse host from connection string for database '${dbId}'`);
569
+ }
570
+ const userMatch = connStr.match(/:\/\/([^:@]+)/);
571
+ const username = userMatch?.[1] ?? creds.admin_user;
572
+ const protocol = host === "localhost" || host === "127.0.0.1" ? "ws" : "wss";
573
+ return {
574
+ wsUrl: `${protocol}://${host}:${fsWsPort}`,
575
+ username,
576
+ password: creds.admin_password
577
+ };
338
578
  }
339
- async function withFsAuthRetry(dbId, operation) {
340
- if (!token && !tokenLoaded) {
341
- await getAuthClient();
579
+ async function withFsClient(dbId, operation) {
580
+ const WS = options.WebSocket ?? (typeof globalThis !== "undefined" ? globalThis.WebSocket : void 0);
581
+ if (!WS) {
582
+ throw new Error(
583
+ "WebSocket constructor not available. Pass `WebSocket` in Db9ClientOptions, or use Node 21+ / a browser environment with native WebSocket support, or install the `ws` package for Node 18\u201320."
584
+ );
342
585
  }
343
- const client = getFsClient(dbId);
586
+ const conn = await resolveFsConn(dbId);
587
+ const client = await FsClient.connect(conn.wsUrl, WS);
344
588
  try {
589
+ await client.authenticate(conn.username, conn.password);
345
590
  return await operation(client);
346
- } catch (err) {
347
- if (!(err instanceof Db9Error) || err.statusCode !== 401) {
348
- throw err;
349
- }
350
- try {
351
- if (!refreshPromise) {
352
- refreshPromise = refreshAnonymousToken();
353
- }
354
- await refreshPromise;
355
- } catch {
356
- throw err;
357
- } finally {
358
- refreshPromise = null;
359
- }
360
- const newClient = getFsClient(dbId);
361
- return operation(newClient);
591
+ } finally {
592
+ await client.close();
362
593
  }
363
594
  }
364
595
  function parseSqlError(raw) {
@@ -379,12 +610,6 @@ function createDb9Client(options = {}) {
379
610
  }
380
611
  return { message: raw };
381
612
  }
382
- async function fsStat(dbId, path) {
383
- return withFsAuthRetry(
384
- dbId,
385
- (client) => client.get("/stat", { path })
386
- );
387
- }
388
613
  async function fetchAnonymousSecret() {
389
614
  return withAuthRetry(
390
615
  (client) => client.post("/customer/anonymous-secret", {})
@@ -458,6 +683,11 @@ function createDb9Client(options = {}) {
458
683
  `/customer/databases/${databaseId}/reset-password`
459
684
  )
460
685
  ),
686
+ credentials: async (databaseId) => withAuthRetry(
687
+ (client) => client.get(
688
+ `/customer/databases/${databaseId}/credentials`
689
+ )
690
+ ),
461
691
  observability: async (databaseId) => withAuthRetry(
462
692
  (client) => client.get(
463
693
  `/customer/databases/${databaseId}/observability`
@@ -540,70 +770,84 @@ function createDb9Client(options = {}) {
540
770
  }
541
771
  },
542
772
  fs: {
543
- list: async (dbId, path, options2) => {
544
- const params = { path };
545
- if (options2?.recursive) params.recursive = "true";
546
- return withFsAuthRetry(
547
- dbId,
548
- (client) => client.get("/readdir", params)
549
- );
550
- },
551
- read: async (dbId, path) => {
552
- return withFsAuthRetry(dbId, async (client) => {
553
- const resp = await client.getRaw("/download", { path });
554
- return resp.text();
555
- });
556
- },
557
- readBinary: async (dbId, path) => {
558
- return withFsAuthRetry(dbId, async (client) => {
559
- const resp = await client.getRaw("/download", { path });
560
- return resp.arrayBuffer();
561
- });
773
+ /**
774
+ * Open a persistent WebSocket connection for multiple fs operations.
775
+ * Caller is responsible for calling `client.close()` when done.
776
+ */
777
+ connect: async (dbId) => {
778
+ const WS = options.WebSocket ?? (typeof globalThis !== "undefined" ? globalThis.WebSocket : void 0);
779
+ if (!WS) {
780
+ throw new Error(
781
+ "WebSocket constructor not available. Pass `WebSocket` in Db9ClientOptions, or use Node 21+ / a browser environment with native WebSocket support, or install the `ws` package for Node 18\u201320."
782
+ );
783
+ }
784
+ const conn = await resolveFsConn(dbId);
785
+ const client = await FsClient.connect(conn.wsUrl, WS);
786
+ await client.authenticate(conn.username, conn.password);
787
+ return client;
562
788
  },
789
+ /** List directory contents. */
790
+ list: async (dbId, path) => withFsClient(dbId, (client) => client.readdir(path)),
791
+ /** Read a file as text (UTF-8). */
792
+ read: async (dbId, path) => withFsClient(dbId, async (client) => {
793
+ const bytes = await client.readFile(path);
794
+ return new TextDecoder().decode(bytes);
795
+ }),
796
+ /** Read a file as raw bytes. */
797
+ readBinary: async (dbId, path) => withFsClient(dbId, (client) => client.readFile(path)),
798
+ /** Write (overwrite) a file. Accepts string, ArrayBuffer, or Uint8Array. */
563
799
  write: async (dbId, path, content) => {
564
- const contentType = typeof content === "string" ? "text/plain" : "application/octet-stream";
565
- await withFsAuthRetry(
566
- dbId,
567
- (client) => client.putRaw(`/upload?${new URLSearchParams({ path })}`, content, { "Content-Type": contentType })
568
- );
569
- },
570
- stat: (dbId, path) => {
571
- return fsStat(dbId, path);
800
+ await withFsClient(dbId, (client) => client.writeFile(path, content));
572
801
  },
802
+ /** Append to a file. Returns bytes written. */
803
+ append: async (dbId, path, content) => withFsClient(dbId, (client) => client.appendFile(path, content)),
804
+ /** Get file or directory metadata. */
805
+ stat: async (dbId, path) => withFsClient(dbId, (client) => client.stat(path)),
806
+ /** Check if a file or directory exists. */
573
807
  exists: async (dbId, path) => {
574
808
  try {
575
- await fsStat(dbId, path);
809
+ await withFsClient(dbId, (client) => client.stat(path));
576
810
  return true;
577
811
  } catch (err) {
578
- if (err instanceof Db9Error && err.statusCode === 404) {
812
+ if (err instanceof FsError && err.code === "ENOENT") {
579
813
  return false;
580
814
  }
581
815
  throw err;
582
816
  }
583
817
  },
818
+ /** Create a directory (recursive by default). */
584
819
  mkdir: async (dbId, path) => {
585
- await withFsAuthRetry(
586
- dbId,
587
- (client) => client.postRaw(`/mkdir?${new URLSearchParams({ path, recursive: "true" })}`)
588
- );
820
+ await withFsClient(dbId, (client) => client.mkdir(path, true));
589
821
  },
590
- remove: async (dbId, path) => {
591
- await withFsAuthRetry(
592
- dbId,
593
- (client) => client.delRaw("/remove", { path })
594
- );
822
+ /** Remove a file or directory. */
823
+ remove: async (dbId, path, opts) => {
824
+ await withFsClient(dbId, (client) => client.rm(path, opts?.recursive ?? false));
595
825
  },
596
- events: async (dbId, options2) => {
597
- const params = {};
598
- if (options2?.limit !== void 0) params.limit = String(options2.limit);
599
- if (options2?.offset !== void 0) params.offset = String(options2.offset);
600
- if (options2?.path) params.path = options2.path;
601
- if (options2?.type) params.type = options2.type;
602
- return withFsAuthRetry(
603
- dbId,
604
- (client) => client.get("/events", params)
605
- );
826
+ /** Rename (move) a file or directory. */
827
+ rename: async (dbId, oldPath, newPath) => {
828
+ await withFsClient(dbId, (client) => client.rename(oldPath, newPath));
606
829
  }
830
+ },
831
+ // ── Device Auth Flow ─────────────────────────────────────────
832
+ deviceAuth: {
833
+ /** Start device code flow. Returns codes for user to authorize. */
834
+ createDeviceCode: () => publicClient.post("/customer/device-code"),
835
+ /** Poll for device token after user authorizes. Returns token or error status. */
836
+ pollDeviceToken: async (req) => {
837
+ try {
838
+ return await publicClient.post("/customer/device-token", req);
839
+ } catch (err) {
840
+ if (err instanceof Db9Error && err.statusCode === 400) {
841
+ const errorType = err.message;
842
+ if (errorType === "authorization_pending" || errorType === "expired_token" || errorType === "access_denied") {
843
+ return { error: errorType };
844
+ }
845
+ }
846
+ throw err;
847
+ }
848
+ },
849
+ /** Submit device verification with user credentials. */
850
+ verifyDevice: (req) => publicClient.post("/customer/device-verify", req)
607
851
  }
608
852
  };
609
853
  }