@dreaminhex/hexdb 2.3.2 → 2.3.3
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/README.md +8 -1
- package/dist/index.d.ts +16 -3
- package/dist/index.js +50 -5
- package/dist/uri.d.ts +17 -0
- package/dist/uri.js +135 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -17,4 +17,11 @@ await orders.insert({ customer: "ada", total: 12 })
|
|
|
17
17
|
const page = await orders.query({ filter: { total: { $gt: 10 } }, sort: "-total" })
|
|
18
18
|
```
|
|
19
19
|
|
|
20
|
-
Create an API key on the admin UI's Account page.
|
|
20
|
+
Create an API key on the admin UI's Account page. A connection URI works too, the same one the other HexDB drivers take:
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
const db = new HexDB(process.env.HEXDB_URI!) // e.g. hexdbs://db.example.com?apiKey=hxk_...
|
|
24
|
+
const db2 = await HexDB.connect("hexdbs://ada:pw@db.example.com") // signs in now; new HexDB(uri) signs in on first use
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
`parseConnectionUri` and `redactConnectionUri` are exported for tools that store URIs. The [driver documentation](https://github.com/dreaminhex/hexdb/tree/main/drivers) and the [manual](https://github.com/dreaminhex/hexdb/blob/main/MANUAL.md) cover the rest. Licensed under the Apache License 2.0.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
|
+
export { isConnectionUri, parseConnectionUri, redactConnectionUri, type ConnectionUri } from "./uri.js";
|
|
1
2
|
export interface Options {
|
|
2
|
-
/**
|
|
3
|
+
/**
|
|
4
|
+
* Base URL of any hex, e.g. http://127.0.0.1:7700 (replicas forward writes to the Overseer),
|
|
5
|
+
* or a connection URI (hexdb://, hexdbs://; see the manual's "Connection URIs").
|
|
6
|
+
*/
|
|
3
7
|
url: string;
|
|
4
|
-
/** An API key (hxk_...) or a session token. */
|
|
8
|
+
/** An API key (hxk_...) or a session token. Wins over a connection URI's apiKey. */
|
|
5
9
|
apiKey?: string;
|
|
6
10
|
/** Retries for 429 and 503 answers (honoring Retry-After). Default 3. */
|
|
7
11
|
retries?: number;
|
|
@@ -76,7 +80,16 @@ export declare class HexDB {
|
|
|
76
80
|
private readonly retries;
|
|
77
81
|
private readonly timeoutMs;
|
|
78
82
|
private readonly fetcher;
|
|
79
|
-
|
|
83
|
+
/** A connection URI's login, signed in with before the first request. */
|
|
84
|
+
private pendingLogin?;
|
|
85
|
+
private signingIn?;
|
|
86
|
+
/** Options, or a URL or connection URI (a URI's login signs in before the first request). */
|
|
87
|
+
constructor(options: Options | string);
|
|
88
|
+
/** Connect with a URL or connection URI and sign in now if it has a login (so bad credentials fail here). */
|
|
89
|
+
static connect(options: Options | string): Promise<HexDB>;
|
|
90
|
+
/** The base URL requests go to. */
|
|
91
|
+
get url(): string;
|
|
92
|
+
private signInIfPending;
|
|
80
93
|
/** Send any request to the REST API and return the parsed JSON (undefined for 204). */
|
|
81
94
|
request<T = unknown>(method: Method, path: string, body?: unknown, headers?: Record<string, string>, timeoutMs?: number): Promise<T>;
|
|
82
95
|
/** Send raw bytes (or nothing) and get the raw response; throws HexDBError on an error answer. */
|
package/dist/index.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
//
|
|
4
4
|
// import { HexDB } from "@dreaminhex/hexdb"
|
|
5
5
|
// const db = new HexDB({ url: "http://127.0.0.1:7700", apiKey: process.env.HEXDB_API_KEY })
|
|
6
|
+
// const db = new HexDB("hexdbs://db.example.com?apiKey=hxk_...") // or a connection URI
|
|
6
7
|
// const orders = db.tessellation("orders")
|
|
7
8
|
// const { id } = await orders.insert({ customer: "ada", total: 12 })
|
|
8
9
|
// const page = await orders.query({ filter: { total: { $gt: 10 } }, sort: "-total" })
|
|
@@ -10,6 +11,8 @@
|
|
|
10
11
|
// const media = db.files("media") // a files tessellation
|
|
11
12
|
// await media.upload("photos/IMG_1.jpg", bytes)
|
|
12
13
|
// const hits = await media.search("glacier") // names, tags and extracted metadata
|
|
14
|
+
import { isConnectionUri, parseConnectionUri } from "./uri.js";
|
|
15
|
+
export { isConnectionUri, parseConnectionUri, redactConnectionUri } from "./uri.js";
|
|
13
16
|
/** An error answer from HexDB: `status` is the HTTP status, `code` HexDB's error code. */
|
|
14
17
|
export class HexDBError extends Error {
|
|
15
18
|
status;
|
|
@@ -31,15 +34,53 @@ export class HexDB {
|
|
|
31
34
|
retries;
|
|
32
35
|
timeoutMs;
|
|
33
36
|
fetcher;
|
|
37
|
+
/** A connection URI's login, signed in with before the first request. */
|
|
38
|
+
pendingLogin;
|
|
39
|
+
signingIn;
|
|
40
|
+
/** Options, or a URL or connection URI (a URI's login signs in before the first request). */
|
|
34
41
|
constructor(options) {
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
42
|
+
const opts = typeof options === "string" ? { url: options } : options;
|
|
43
|
+
let url = opts.url;
|
|
44
|
+
let apiKey = opts.apiKey;
|
|
45
|
+
let timeoutMs = opts.timeoutMs;
|
|
46
|
+
if (isConnectionUri(url)) {
|
|
47
|
+
const uri = parseConnectionUri(url);
|
|
48
|
+
url = uri.url;
|
|
49
|
+
apiKey ??= uri.apiKey ?? undefined;
|
|
50
|
+
timeoutMs ??= uri.timeoutSeconds === null ? undefined : uri.timeoutSeconds * 1000;
|
|
51
|
+
if (uri.login !== null && opts.apiKey === undefined) {
|
|
52
|
+
if (uri.password === null)
|
|
53
|
+
throw new Error("The connection URI has a login but no password; use an API key for accounts without one");
|
|
54
|
+
this.pendingLogin = { login: uri.login, password: uri.password };
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
this.base = url.replace(/\/+$/, "");
|
|
58
|
+
this.token = apiKey;
|
|
59
|
+
this.retries = opts.retries ?? 3;
|
|
60
|
+
this.timeoutMs = timeoutMs ?? 30_000;
|
|
61
|
+
this.fetcher = opts.fetch ?? globalThis.fetch.bind(globalThis);
|
|
62
|
+
}
|
|
63
|
+
/** Connect with a URL or connection URI and sign in now if it has a login (so bad credentials fail here). */
|
|
64
|
+
static async connect(options) {
|
|
65
|
+
const db = new HexDB(options);
|
|
66
|
+
await db.signInIfPending();
|
|
67
|
+
return db;
|
|
68
|
+
}
|
|
69
|
+
/** The base URL requests go to. */
|
|
70
|
+
get url() {
|
|
71
|
+
return this.base;
|
|
72
|
+
}
|
|
73
|
+
async signInIfPending() {
|
|
74
|
+
const pending = this.pendingLogin;
|
|
75
|
+
if (!pending)
|
|
76
|
+
return;
|
|
77
|
+
this.signingIn ??= this.login(pending.login, pending.password).finally(() => (this.signingIn = undefined));
|
|
78
|
+
await this.signingIn;
|
|
40
79
|
}
|
|
41
80
|
/** Send any request to the REST API and return the parsed JSON (undefined for 204). */
|
|
42
81
|
async request(method, path, body, headers = {}, timeoutMs = this.timeoutMs) {
|
|
82
|
+
if (this.pendingLogin && path !== "/auth/login")
|
|
83
|
+
await this.signInIfPending();
|
|
43
84
|
for (let attempt = 0;; attempt++) {
|
|
44
85
|
const controller = new AbortController();
|
|
45
86
|
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
@@ -82,6 +123,8 @@ export class HexDB {
|
|
|
82
123
|
}
|
|
83
124
|
/** Send raw bytes (or nothing) and get the raw response; throws HexDBError on an error answer. */
|
|
84
125
|
async requestRaw(method, path, body, headers = {}, timeoutMs = 600_000) {
|
|
126
|
+
if (this.pendingLogin)
|
|
127
|
+
await this.signInIfPending();
|
|
85
128
|
const controller = new AbortController();
|
|
86
129
|
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
87
130
|
let response;
|
|
@@ -114,12 +157,14 @@ export class HexDB {
|
|
|
114
157
|
async login(login, password, code) {
|
|
115
158
|
const result = await this.request("POST", "/auth/login", { login, password, code, return_token: true });
|
|
116
159
|
this.token = result.token;
|
|
160
|
+
this.pendingLogin = undefined;
|
|
117
161
|
return { user: result.user, expires_at: result.expires_at };
|
|
118
162
|
}
|
|
119
163
|
/** End the session (a no-op for API keys). */
|
|
120
164
|
async logout() {
|
|
121
165
|
await this.request("POST", "/auth/logout");
|
|
122
166
|
this.token = undefined;
|
|
167
|
+
this.pendingLogin = undefined;
|
|
123
168
|
}
|
|
124
169
|
/** Whether the server is up (and, signed in, which hex answered). */
|
|
125
170
|
health() {
|
package/dist/uri.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** A parsed connection URI. Absent parts are null. */
|
|
2
|
+
export interface ConnectionUri {
|
|
3
|
+
/** The base URL requests go to, e.g. https://db.example.com/hexdb (no trailing slash). */
|
|
4
|
+
url: string;
|
|
5
|
+
login: string | null;
|
|
6
|
+
password: string | null;
|
|
7
|
+
apiKey: string | null;
|
|
8
|
+
timeoutSeconds: number | null;
|
|
9
|
+
pageSize: number | null;
|
|
10
|
+
caFile: string | null;
|
|
11
|
+
}
|
|
12
|
+
/** Whether `text` is a hexdb:// or hexdbs:// URI (as opposed to a plain http(s) URL). */
|
|
13
|
+
export declare function isConnectionUri(text: string): boolean;
|
|
14
|
+
/** Parse a hexdb:// or hexdbs:// URI; throws an Error naming the problem if it isn't valid. */
|
|
15
|
+
export declare function parseConnectionUri(uri: string): ConnectionUri;
|
|
16
|
+
/** The URI with its password and apiKey replaced by `***`, safe to show or log. */
|
|
17
|
+
export declare function redactConnectionUri(uri: string): string;
|
package/dist/uri.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// HexDB connection URIs (MANUAL.md, "Connection URIs"):
|
|
2
|
+
//
|
|
3
|
+
// hexdb://[login[:password]@]host[:port][/path][?option=value&...] HTTP, port 7700 by default
|
|
4
|
+
// hexdbs://... HTTPS, port 443 by default
|
|
5
|
+
/** Whether `text` is a hexdb:// or hexdbs:// URI (as opposed to a plain http(s) URL). */
|
|
6
|
+
export function isConnectionUri(text) {
|
|
7
|
+
return /^hexdbs?:/i.test(text.trim());
|
|
8
|
+
}
|
|
9
|
+
/** Parse a hexdb:// or hexdbs:// URI; throws an Error naming the problem if it isn't valid. */
|
|
10
|
+
export function parseConnectionUri(uri) {
|
|
11
|
+
const text = uri.trim();
|
|
12
|
+
const scheme = /^(hexdbs?):\/\//i.exec(text);
|
|
13
|
+
if (!scheme) {
|
|
14
|
+
throw new Error(/^hexdbs?:/i.test(text) ? "A HexDB URI needs // after the scheme: hexdb://host" : "A HexDB URI starts with hexdb:// or hexdbs://");
|
|
15
|
+
}
|
|
16
|
+
const tls = scheme[1].toLowerCase() === "hexdbs";
|
|
17
|
+
let rest = text.slice(scheme[0].length);
|
|
18
|
+
if (rest.includes("#"))
|
|
19
|
+
throw new Error("A HexDB URI can't have a fragment (#)");
|
|
20
|
+
let query = "";
|
|
21
|
+
const q = rest.indexOf("?");
|
|
22
|
+
if (q >= 0) {
|
|
23
|
+
query = rest.slice(q + 1);
|
|
24
|
+
rest = rest.slice(0, q);
|
|
25
|
+
}
|
|
26
|
+
const slash = rest.indexOf("/");
|
|
27
|
+
let authority = slash >= 0 ? rest.slice(0, slash) : rest;
|
|
28
|
+
const path = slash >= 0 ? rest.slice(slash).replace(/\/+$/, "") : "";
|
|
29
|
+
let login = null;
|
|
30
|
+
let password = null;
|
|
31
|
+
const at = authority.lastIndexOf("@");
|
|
32
|
+
if (at >= 0) {
|
|
33
|
+
const userinfo = authority.slice(0, at);
|
|
34
|
+
authority = authority.slice(at + 1);
|
|
35
|
+
const colon = userinfo.indexOf(":");
|
|
36
|
+
login = decode(colon >= 0 ? userinfo.slice(0, colon) : userinfo, "login");
|
|
37
|
+
password = colon >= 0 ? decode(userinfo.slice(colon + 1), "password") : null;
|
|
38
|
+
if (!login)
|
|
39
|
+
throw new Error("The URI's login is empty");
|
|
40
|
+
}
|
|
41
|
+
if (authority.includes(","))
|
|
42
|
+
throw new Error("A HexDB URI names one host; any hex of a lattice serves the whole lattice");
|
|
43
|
+
let host;
|
|
44
|
+
let portText = null;
|
|
45
|
+
if (authority.startsWith("[")) {
|
|
46
|
+
const close = authority.indexOf("]");
|
|
47
|
+
if (close < 0)
|
|
48
|
+
throw new Error("An IPv6 address needs a closing ]");
|
|
49
|
+
host = authority.slice(0, close + 1);
|
|
50
|
+
const after = authority.slice(close + 1);
|
|
51
|
+
if (after) {
|
|
52
|
+
if (!after.startsWith(":"))
|
|
53
|
+
throw new Error(`Unexpected text after the IPv6 address: ${after}`);
|
|
54
|
+
portText = after.slice(1);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
const colon = authority.lastIndexOf(":");
|
|
59
|
+
host = colon >= 0 ? authority.slice(0, colon) : authority;
|
|
60
|
+
portText = colon >= 0 ? authority.slice(colon + 1) : null;
|
|
61
|
+
}
|
|
62
|
+
host = host.toLowerCase();
|
|
63
|
+
if (!host || host === "[]")
|
|
64
|
+
throw new Error("The URI has no host");
|
|
65
|
+
const defaultPort = tls ? 443 : 7700;
|
|
66
|
+
let port = defaultPort;
|
|
67
|
+
if (portText !== null) {
|
|
68
|
+
if (!/^\d+$/.test(portText))
|
|
69
|
+
throw new Error(`The port isn't a number: ${portText}`);
|
|
70
|
+
port = Number(portText);
|
|
71
|
+
if (port < 1 || port > 65535)
|
|
72
|
+
throw new Error(`The port must be 1 to 65535: ${portText}`);
|
|
73
|
+
}
|
|
74
|
+
const result = {
|
|
75
|
+
url: `${tls ? "https" : "http"}://${host}${port === 443 && tls ? "" : `:${port}`}${path}`,
|
|
76
|
+
login,
|
|
77
|
+
password,
|
|
78
|
+
apiKey: null,
|
|
79
|
+
timeoutSeconds: null,
|
|
80
|
+
pageSize: null,
|
|
81
|
+
caFile: null,
|
|
82
|
+
};
|
|
83
|
+
for (const pair of query.split("&")) {
|
|
84
|
+
if (!pair)
|
|
85
|
+
continue;
|
|
86
|
+
const eq = pair.indexOf("=");
|
|
87
|
+
const name = decode(eq >= 0 ? pair.slice(0, eq) : pair, "option name").toLowerCase();
|
|
88
|
+
const value = decode(eq >= 0 ? pair.slice(eq + 1) : "", name);
|
|
89
|
+
switch (name) {
|
|
90
|
+
case "apikey":
|
|
91
|
+
if (!value)
|
|
92
|
+
throw new Error("apiKey is empty");
|
|
93
|
+
result.apiKey = value;
|
|
94
|
+
break;
|
|
95
|
+
case "timeout":
|
|
96
|
+
result.timeoutSeconds = integer(value, "timeout", 1, Number.MAX_SAFE_INTEGER, "a positive number of seconds");
|
|
97
|
+
break;
|
|
98
|
+
case "pagesize":
|
|
99
|
+
result.pageSize = integer(value, "pageSize", 1, 10_000, "1 to 10,000");
|
|
100
|
+
break;
|
|
101
|
+
case "cafile":
|
|
102
|
+
if (!value)
|
|
103
|
+
throw new Error("caFile is empty");
|
|
104
|
+
result.caFile = value;
|
|
105
|
+
break;
|
|
106
|
+
default:
|
|
107
|
+
// Options other drivers use are ignored, so one URI works everywhere.
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (result.login !== null && result.apiKey !== null)
|
|
111
|
+
throw new Error("Give a login or an apiKey, not both");
|
|
112
|
+
return result;
|
|
113
|
+
}
|
|
114
|
+
/** The URI with its password and apiKey replaced by `***`, safe to show or log. */
|
|
115
|
+
export function redactConnectionUri(uri) {
|
|
116
|
+
return uri
|
|
117
|
+
.replace(/^(hexdbs?:\/\/[^:@/?#]*:)[^@/?#]*@/i, "$1***@")
|
|
118
|
+
.replace(/([?&]apikey=)[^&#]*/gi, "$1***");
|
|
119
|
+
}
|
|
120
|
+
function decode(text, what) {
|
|
121
|
+
try {
|
|
122
|
+
return decodeURIComponent(text.replace(/\+/g, "%2B"));
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
throw new Error(`The ${what} has a malformed %-escape`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function integer(value, name, min, max, expected) {
|
|
129
|
+
if (!/^\d+$/.test(value))
|
|
130
|
+
throw new Error(`${name} must be ${expected}: ${value || "(empty)"}`);
|
|
131
|
+
const n = Number(value);
|
|
132
|
+
if (n < min || n > max)
|
|
133
|
+
throw new Error(`${name} must be ${expected}: ${value}`);
|
|
134
|
+
return n;
|
|
135
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dreaminhex/hexdb",
|
|
3
|
-
"version": "2.3.
|
|
3
|
+
"version": "2.3.3",
|
|
4
4
|
"description": "Client for HexDB, the hexagonal document database.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Dream In Hex",
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
},
|
|
40
40
|
"scripts": {
|
|
41
41
|
"build": "tsc -p tsconfig.json",
|
|
42
|
-
"test": "npm run build && node --test test/client.test.mjs"
|
|
42
|
+
"test": "npm run build && node --test test/uri.test.mjs test/client.test.mjs"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
45
|
"@types/node": "^26.6.5",
|