@ohos-ports/libsql-client 0.18.0-beta.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/lib-esm/web.js ADDED
@@ -0,0 +1,22 @@
1
+ import { LibsqlError } from "@libsql/core/api";
2
+ import { expandConfig } from "@libsql/core/config";
3
+ import { supportedUrlLink } from "@libsql/core/util";
4
+ import { _createClient as _createWsClient } from "./ws.js";
5
+ import { _createClient as _createHttpClient } from "./http.js";
6
+ export * from "@libsql/core/api";
7
+ export function createClient(config) {
8
+ return _createClient(expandConfig(config, true));
9
+ }
10
+ /** @private */
11
+ export function _createClient(config) {
12
+ if (config.scheme === "ws" || config.scheme === "wss") {
13
+ return _createWsClient(config);
14
+ }
15
+ else if (config.scheme === "http" || config.scheme === "https") {
16
+ return _createHttpClient(config);
17
+ }
18
+ else {
19
+ throw new LibsqlError('The client that uses Web standard APIs supports only "libsql:", "wss:", "ws:", "https:" and "http:" URLs, ' +
20
+ `got ${JSON.stringify(config.scheme + ":")}. For more information, please read ${supportedUrlLink}`, "URL_SCHEME_NOT_SUPPORTED");
21
+ }
22
+ }
@@ -0,0 +1,50 @@
1
+ /// <reference types="node" />
2
+ import * as hrana from "@libsql/hrana-client";
3
+ import type { Config, IntMode, Client, Transaction, ResultSet, InStatement, InArgs, Replicated } from "@libsql/core/api";
4
+ import { TransactionMode } from "@libsql/core/api";
5
+ import type { ExpandedConfig } from "@libsql/core/config";
6
+ import { HranaTransaction } from "./hrana.js";
7
+ import { SqlCache } from "./sql_cache.js";
8
+ export * from "@libsql/core/api";
9
+ export declare function createClient(config: Config): WsClient;
10
+ /** @private */
11
+ export declare function _createClient(config: ExpandedConfig): WsClient;
12
+ interface ConnState {
13
+ client: hrana.WsClient;
14
+ useSqlCache: boolean | undefined;
15
+ sqlCache: SqlCache;
16
+ openTime: Date;
17
+ streamStates: Set<StreamState>;
18
+ }
19
+ interface StreamState {
20
+ conn: ConnState;
21
+ stream: hrana.WsStream;
22
+ }
23
+ export declare class WsClient implements Client {
24
+ #private;
25
+ closed: boolean;
26
+ protocol: "ws";
27
+ /** @private */
28
+ constructor(client: hrana.WsClient, url: URL, authToken: string | undefined, intMode: IntMode, concurrency: number | undefined);
29
+ private limit;
30
+ execute(stmtOrSql: InStatement | string, args?: InArgs): Promise<ResultSet>;
31
+ batch(stmts: Array<InStatement | [string, InArgs?]>, mode?: TransactionMode): Promise<Array<ResultSet>>;
32
+ migrate(stmts: Array<InStatement>): Promise<Array<ResultSet>>;
33
+ transaction(mode?: TransactionMode): Promise<WsTransaction>;
34
+ executeMultiple(sql: string): Promise<void>;
35
+ sync(): Promise<Replicated>;
36
+ reconnect(): Promise<void>;
37
+ _closeStream(streamState: StreamState): void;
38
+ close(): void;
39
+ }
40
+ export declare class WsTransaction extends HranaTransaction implements Transaction {
41
+ #private;
42
+ /** @private */
43
+ constructor(client: WsClient, state: StreamState, mode: TransactionMode, version: hrana.ProtocolVersion);
44
+ /** @private */
45
+ _getStream(): hrana.Stream;
46
+ /** @private */
47
+ _getSqlCache(): SqlCache;
48
+ close(): void;
49
+ get closed(): boolean;
50
+ }
package/lib-esm/ws.js ADDED
@@ -0,0 +1,359 @@
1
+ import * as hrana from "@libsql/hrana-client";
2
+ import { LibsqlError } from "@libsql/core/api";
3
+ import { expandConfig } from "@libsql/core/config";
4
+ import { HranaTransaction, executeHranaBatch, stmtToHrana, resultSetFromHrana, mapHranaError, } from "./hrana.js";
5
+ import { SqlCache } from "./sql_cache.js";
6
+ import { encodeBaseUrl } from "@libsql/core/uri";
7
+ import { supportedUrlLink } from "@libsql/core/util";
8
+ import promiseLimit from "promise-limit";
9
+ export * from "@libsql/core/api";
10
+ export function createClient(config) {
11
+ return _createClient(expandConfig(config, false));
12
+ }
13
+ /** @private */
14
+ export function _createClient(config) {
15
+ if (config.scheme !== "wss" && config.scheme !== "ws") {
16
+ throw new LibsqlError('The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, ' +
17
+ `got ${JSON.stringify(config.scheme + ":")}. For more information, please read ${supportedUrlLink}`, "URL_SCHEME_NOT_SUPPORTED");
18
+ }
19
+ if (config.encryptionKey !== undefined) {
20
+ throw new LibsqlError("Encryption key is not supported by the remote client.", "ENCRYPTION_KEY_NOT_SUPPORTED");
21
+ }
22
+ if (config.scheme === "ws" && config.tls) {
23
+ throw new LibsqlError(`A "ws:" URL cannot opt into TLS by using ?tls=1`, "URL_INVALID");
24
+ }
25
+ else if (config.scheme === "wss" && !config.tls) {
26
+ throw new LibsqlError(`A "wss:" URL cannot opt out of TLS by using ?tls=0`, "URL_INVALID");
27
+ }
28
+ const url = encodeBaseUrl(config.scheme, config.authority, config.path);
29
+ let client;
30
+ try {
31
+ client = hrana.openWs(url, config.authToken);
32
+ }
33
+ catch (e) {
34
+ if (e instanceof hrana.WebSocketUnsupportedError) {
35
+ const suggestedScheme = config.scheme === "wss" ? "https" : "http";
36
+ const suggestedUrl = encodeBaseUrl(suggestedScheme, config.authority, config.path);
37
+ throw new LibsqlError("This environment does not support WebSockets, please switch to the HTTP client by using " +
38
+ `a "${suggestedScheme}:" URL (${JSON.stringify(suggestedUrl)}). ` +
39
+ `For more information, please read ${supportedUrlLink}`, "WEBSOCKETS_NOT_SUPPORTED");
40
+ }
41
+ throw mapHranaError(e);
42
+ }
43
+ return new WsClient(client, url, config.authToken, config.intMode, config.concurrency);
44
+ }
45
+ const maxConnAgeMillis = 60 * 1000;
46
+ const sqlCacheCapacity = 100;
47
+ export class WsClient {
48
+ #url;
49
+ #authToken;
50
+ #intMode;
51
+ // State of the current connection. The `hrana.WsClient` inside may be closed at any moment due to an
52
+ // asynchronous error.
53
+ #connState;
54
+ // If defined, this is a connection that will be used in the future, once it is ready.
55
+ #futureConnState;
56
+ closed;
57
+ protocol;
58
+ #isSchemaDatabase;
59
+ #promiseLimitFunction;
60
+ /** @private */
61
+ constructor(client, url, authToken, intMode, concurrency) {
62
+ this.#url = url;
63
+ this.#authToken = authToken;
64
+ this.#intMode = intMode;
65
+ this.#connState = this.#openConn(client);
66
+ this.#futureConnState = undefined;
67
+ this.closed = false;
68
+ this.protocol = "ws";
69
+ this.#promiseLimitFunction = promiseLimit(concurrency);
70
+ }
71
+ async limit(fn) {
72
+ return this.#promiseLimitFunction(fn);
73
+ }
74
+ async execute(stmtOrSql, args) {
75
+ let stmt;
76
+ if (typeof stmtOrSql === "string") {
77
+ stmt = {
78
+ sql: stmtOrSql,
79
+ args: args || [],
80
+ };
81
+ }
82
+ else {
83
+ stmt = stmtOrSql;
84
+ }
85
+ return this.limit(async () => {
86
+ const streamState = await this.#openStream();
87
+ try {
88
+ const hranaStmt = stmtToHrana(stmt);
89
+ // Schedule all operations synchronously, so they will be pipelined and executed in a single
90
+ // network roundtrip.
91
+ streamState.conn.sqlCache.apply([hranaStmt]);
92
+ const hranaRowsPromise = streamState.stream.query(hranaStmt);
93
+ streamState.stream.closeGracefully();
94
+ const hranaRowsResult = await hranaRowsPromise;
95
+ return resultSetFromHrana(hranaRowsResult);
96
+ }
97
+ catch (e) {
98
+ throw mapHranaError(e);
99
+ }
100
+ finally {
101
+ this._closeStream(streamState);
102
+ }
103
+ });
104
+ }
105
+ async batch(stmts, mode = "deferred") {
106
+ return this.limit(async () => {
107
+ const streamState = await this.#openStream();
108
+ try {
109
+ const normalizedStmts = stmts.map((stmt) => {
110
+ if (Array.isArray(stmt)) {
111
+ return {
112
+ sql: stmt[0],
113
+ args: stmt[1] || [],
114
+ };
115
+ }
116
+ return stmt;
117
+ });
118
+ const hranaStmts = normalizedStmts.map(stmtToHrana);
119
+ const version = await streamState.conn.client.getVersion();
120
+ // Schedule all operations synchronously, so they will be pipelined and executed in a single
121
+ // network roundtrip.
122
+ streamState.conn.sqlCache.apply(hranaStmts);
123
+ const batch = streamState.stream.batch(version >= 3);
124
+ const resultsPromise = executeHranaBatch(mode, version, batch, hranaStmts);
125
+ const results = await resultsPromise;
126
+ return results;
127
+ }
128
+ catch (e) {
129
+ throw mapHranaError(e);
130
+ }
131
+ finally {
132
+ this._closeStream(streamState);
133
+ }
134
+ });
135
+ }
136
+ async migrate(stmts) {
137
+ return this.limit(async () => {
138
+ const streamState = await this.#openStream();
139
+ try {
140
+ const hranaStmts = stmts.map(stmtToHrana);
141
+ const version = await streamState.conn.client.getVersion();
142
+ // Schedule all operations synchronously, so they will be pipelined and executed in a single
143
+ // network roundtrip.
144
+ const batch = streamState.stream.batch(version >= 3);
145
+ const resultsPromise = executeHranaBatch("deferred", version, batch, hranaStmts, true);
146
+ const results = await resultsPromise;
147
+ return results;
148
+ }
149
+ catch (e) {
150
+ throw mapHranaError(e);
151
+ }
152
+ finally {
153
+ this._closeStream(streamState);
154
+ }
155
+ });
156
+ }
157
+ async transaction(mode = "write") {
158
+ return this.limit(async () => {
159
+ const streamState = await this.#openStream();
160
+ try {
161
+ const version = await streamState.conn.client.getVersion();
162
+ // the BEGIN statement will be batched with the first statement on the transaction to save a
163
+ // network roundtrip
164
+ return new WsTransaction(this, streamState, mode, version);
165
+ }
166
+ catch (e) {
167
+ this._closeStream(streamState);
168
+ throw mapHranaError(e);
169
+ }
170
+ });
171
+ }
172
+ async executeMultiple(sql) {
173
+ return this.limit(async () => {
174
+ const streamState = await this.#openStream();
175
+ try {
176
+ // Schedule all operations synchronously, so they will be pipelined and executed in a single
177
+ // network roundtrip.
178
+ const promise = streamState.stream.sequence(sql);
179
+ streamState.stream.closeGracefully();
180
+ await promise;
181
+ }
182
+ catch (e) {
183
+ throw mapHranaError(e);
184
+ }
185
+ finally {
186
+ this._closeStream(streamState);
187
+ }
188
+ });
189
+ }
190
+ sync() {
191
+ throw new LibsqlError("sync not supported in ws mode", "SYNC_NOT_SUPPORTED");
192
+ }
193
+ async #openStream() {
194
+ if (this.closed) {
195
+ throw new LibsqlError("The client is closed", "CLIENT_CLOSED");
196
+ }
197
+ const now = new Date();
198
+ const ageMillis = now.valueOf() - this.#connState.openTime.valueOf();
199
+ if (ageMillis > maxConnAgeMillis &&
200
+ this.#futureConnState === undefined) {
201
+ // The existing connection is too old, let's open a new one.
202
+ const futureConnState = this.#openConn();
203
+ this.#futureConnState = futureConnState;
204
+ // However, if we used `futureConnState` immediately, we would introduce additional latency,
205
+ // because we would have to wait for the WebSocket handshake to complete, even though we may a
206
+ // have perfectly good existing connection in `this.#connState`!
207
+ //
208
+ // So we wait until the `hrana.Client.getVersion()` operation completes (which happens when the
209
+ // WebSocket hanshake completes), and only then we replace `this.#connState` with
210
+ // `futureConnState`, which is stored in `this.#futureConnState` in the meantime.
211
+ futureConnState.client.getVersion().then((_version) => {
212
+ if (this.#connState !== futureConnState) {
213
+ // We need to close `this.#connState` before we replace it. However, it is possible
214
+ // that `this.#connState` has already been replaced: see the code below.
215
+ if (this.#connState.streamStates.size === 0) {
216
+ this.#connState.client.close();
217
+ }
218
+ else {
219
+ // If there are existing streams on the connection, we must not close it, because
220
+ // these streams would be broken. The last stream to be closed will also close the
221
+ // connection in `_closeStream()`.
222
+ }
223
+ }
224
+ this.#connState = futureConnState;
225
+ this.#futureConnState = undefined;
226
+ }, (_e) => {
227
+ // If the new connection could not be established, let's just ignore the error and keep
228
+ // using the existing connection.
229
+ this.#futureConnState = undefined;
230
+ });
231
+ }
232
+ if (this.#connState.client.closed) {
233
+ // An error happened on this connection and it has been closed. Let's try to seamlessly reconnect.
234
+ try {
235
+ if (this.#futureConnState !== undefined) {
236
+ // We are already in the process of opening a new connection, so let's just use it
237
+ // immediately.
238
+ this.#connState = this.#futureConnState;
239
+ }
240
+ else {
241
+ this.#connState = this.#openConn();
242
+ }
243
+ }
244
+ catch (e) {
245
+ throw mapHranaError(e);
246
+ }
247
+ }
248
+ const connState = this.#connState;
249
+ try {
250
+ // Now we wait for the WebSocket handshake to complete (if it hasn't completed yet). Note that
251
+ // this does not increase latency, because any messages that we would send on the WebSocket before
252
+ // the handshake would be queued until the handshake is completed anyway.
253
+ if (connState.useSqlCache === undefined) {
254
+ connState.useSqlCache =
255
+ (await connState.client.getVersion()) >= 2;
256
+ if (connState.useSqlCache) {
257
+ connState.sqlCache.capacity = sqlCacheCapacity;
258
+ }
259
+ }
260
+ const stream = connState.client.openStream();
261
+ stream.intMode = this.#intMode;
262
+ const streamState = { conn: connState, stream };
263
+ connState.streamStates.add(streamState);
264
+ return streamState;
265
+ }
266
+ catch (e) {
267
+ throw mapHranaError(e);
268
+ }
269
+ }
270
+ #openConn(client) {
271
+ try {
272
+ client ??= hrana.openWs(this.#url, this.#authToken);
273
+ return {
274
+ client,
275
+ useSqlCache: undefined,
276
+ sqlCache: new SqlCache(client, 0),
277
+ openTime: new Date(),
278
+ streamStates: new Set(),
279
+ };
280
+ }
281
+ catch (e) {
282
+ throw mapHranaError(e);
283
+ }
284
+ }
285
+ async reconnect() {
286
+ try {
287
+ for (const st of Array.from(this.#connState.streamStates)) {
288
+ try {
289
+ st.stream.close();
290
+ }
291
+ catch { }
292
+ }
293
+ this.#connState.client.close();
294
+ }
295
+ catch { }
296
+ if (this.#futureConnState) {
297
+ try {
298
+ this.#futureConnState.client.close();
299
+ }
300
+ catch { }
301
+ this.#futureConnState = undefined;
302
+ }
303
+ const next = this.#openConn();
304
+ const version = await next.client.getVersion();
305
+ next.useSqlCache = version >= 2;
306
+ if (next.useSqlCache) {
307
+ next.sqlCache.capacity = sqlCacheCapacity;
308
+ }
309
+ this.#connState = next;
310
+ this.closed = false;
311
+ }
312
+ _closeStream(streamState) {
313
+ streamState.stream.close();
314
+ const connState = streamState.conn;
315
+ connState.streamStates.delete(streamState);
316
+ if (connState.streamStates.size === 0 &&
317
+ connState !== this.#connState) {
318
+ // We are not using this connection anymore and this is the last stream that was using it, so we
319
+ // must close it now.
320
+ connState.client.close();
321
+ }
322
+ }
323
+ close() {
324
+ this.#connState.client.close();
325
+ this.closed = true;
326
+ if (this.#futureConnState) {
327
+ try {
328
+ this.#futureConnState.client.close();
329
+ }
330
+ catch { }
331
+ this.#futureConnState = undefined;
332
+ }
333
+ this.closed = true;
334
+ }
335
+ }
336
+ export class WsTransaction extends HranaTransaction {
337
+ #client;
338
+ #streamState;
339
+ /** @private */
340
+ constructor(client, state, mode, version) {
341
+ super(mode, version);
342
+ this.#client = client;
343
+ this.#streamState = state;
344
+ }
345
+ /** @private */
346
+ _getStream() {
347
+ return this.#streamState.stream;
348
+ }
349
+ /** @private */
350
+ _getSqlCache() {
351
+ return this.#streamState.conn.sqlCache;
352
+ }
353
+ close() {
354
+ this.#client._closeStream(this.#streamState);
355
+ }
356
+ get closed() {
357
+ return this.#streamState.stream.closed;
358
+ }
359
+ }
package/package.json ADDED
@@ -0,0 +1,123 @@
1
+ {
2
+ "name": "@ohos-ports/libsql-client",
3
+ "version": "0.18.0-beta.0",
4
+ "keywords": [
5
+ "libsql",
6
+ "database",
7
+ "sqlite",
8
+ "serverless",
9
+ "vercel",
10
+ "netlify",
11
+ "lambda"
12
+ ],
13
+ "description": "libSQL driver for TypeScript and JavaScript",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://github.com/ohos-ports/ohos-ports.git",
17
+ "directory": "ports/libsql-client/0.18.0"
18
+ },
19
+ "authors": [
20
+ "Jan Špaček <honza@chiselstrike.com>",
21
+ "Pekka Enberg <penberg@chiselstrike.com>",
22
+ "Jan Plhak <jp@chiselstrike.com>"
23
+ ],
24
+ "license": "MIT",
25
+ "type": "module",
26
+ "main": "lib-cjs/node.js",
27
+ "types": "lib-esm/node.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./lib-esm/node.d.ts",
31
+ "import": {
32
+ "workerd": "./lib-esm/web.js",
33
+ "deno": "./lib-esm/node.js",
34
+ "edge-light": "./lib-esm/web.js",
35
+ "netlify": "./lib-esm/web.js",
36
+ "node": "./lib-esm/node.js",
37
+ "browser": "./lib-esm/web.js",
38
+ "default": "./lib-esm/node.js"
39
+ },
40
+ "require": "./lib-cjs/node.js"
41
+ },
42
+ "./node": {
43
+ "types": "./lib-esm/node.d.ts",
44
+ "import": "./lib-esm/node.js",
45
+ "require": "./lib-cjs/node.js"
46
+ },
47
+ "./http": {
48
+ "types": "./lib-esm/http.d.ts",
49
+ "import": "./lib-esm/http.js",
50
+ "require": "./lib-cjs/http.js"
51
+ },
52
+ "./ws": {
53
+ "types": "./lib-esm/ws.d.ts",
54
+ "import": "./lib-esm/ws.js",
55
+ "require": "./lib-cjs/ws.js"
56
+ },
57
+ "./sqlite3": {
58
+ "types": "./lib-esm/sqlite3.d.ts",
59
+ "import": "./lib-esm/sqlite3.js",
60
+ "require": "./lib-cjs/sqlite3.js"
61
+ },
62
+ "./web": {
63
+ "types": "./lib-esm/web.d.ts",
64
+ "import": "./lib-esm/web.js",
65
+ "require": "./lib-cjs/web.js"
66
+ }
67
+ },
68
+ "typesVersions": {
69
+ "*": {
70
+ ".": [
71
+ "./lib-esm/node.d.ts"
72
+ ],
73
+ "http": [
74
+ "./lib-esm/http.d.ts"
75
+ ],
76
+ "hrana": [
77
+ "./lib-esm/hrana.d.ts"
78
+ ],
79
+ "sqlite3": [
80
+ "./lib-esm/sqlite3.d.ts"
81
+ ],
82
+ "web": [
83
+ "./lib-esm/web.d.ts"
84
+ ]
85
+ }
86
+ },
87
+ "files": [
88
+ "lib-cjs/**",
89
+ "lib-esm/**",
90
+ "README.md"
91
+ ],
92
+ "scripts": {
93
+ "build": "npm run build:cjs && npm run build:esm",
94
+ "build:cjs": "tsc -p tsconfig.build-cjs.json",
95
+ "build:esm": "tsc -p tsconfig.build-esm.json",
96
+ "format:check": "prettier --check .",
97
+ "test": "jest --runInBand",
98
+ "typecheck": "tsc --noEmit",
99
+ "typedoc": "rm -rf ./docs && typedoc",
100
+ "lint-staged": "lint-staged"
101
+ },
102
+ "dependencies": {
103
+ "@libsql/core": "^0.18.0",
104
+ "@libsql/hrana-client": "^0.10.0",
105
+ "js-base64": "^3.7.5",
106
+ "@ohos-ports/libsql": "^0.5.29",
107
+ "promise-limit": "^2.7.0"
108
+ },
109
+ "devDependencies": {
110
+ "@types/jest": "^29.2.5",
111
+ "@types/node": "^18.15.5",
112
+ "jest": "^29.3.1",
113
+ "lint-staged": "^15.2.2",
114
+ "msw": "^2.3.0",
115
+ "prettier": "3.2.5",
116
+ "ts-jest": "^29.0.5",
117
+ "typedoc": "^0.23.28",
118
+ "typescript": "^4.9.4"
119
+ },
120
+ "bugs": {
121
+ "url": "https://github.com/ohos-ports/ohos-ports/issues"
122
+ }
123
+ }