@trysqless/node 0.1.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/README.md ADDED
@@ -0,0 +1,206 @@
1
+ # SQLess Node.js SDK
2
+
3
+ `@trysqless/node` provides a method-based API for SQLess on Node.js 22 or later.
4
+ Applications do not handle WebSocket events, protocol messages, framing, or
5
+ authentication headers. JavaScript (ESM) and TypeScript declarations are included.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @trysqless/node
11
+ ```
12
+
13
+ For installations in mainland China, use the npm mirror:
14
+
15
+ ```sh
16
+ npm install @trysqless/node --registry=https://registry.npmmirror.com
17
+ ```
18
+
19
+ Include the installed runtime dependencies in your deployment package. Package
20
+ installation is a build step, not part of a cloud function's cold start.
21
+
22
+ ## Develop from this repository
23
+
24
+ Releases use `sdks/node/VERSION` as their version source. Changing that file on
25
+ `main` triggers `.github/workflows/publish-node-sdk.yml`, which tests the SDK,
26
+ publishes to npm, requests npmmirror synchronization, and verifies installation
27
+ from the mirror. A failed mirror synchronization can be retried without
28
+ republishing the same version; changed package contents require a new version.
29
+
30
+ After the first npm publication, configure a GitHub Actions trusted publisher for
31
+ `cloudcarver/sqless`, workflow `publish-node-sdk.yml`, with direct publishing
32
+ allowed. The workflow uses OIDC and does not need an npm token. Run
33
+ `node scripts/publish.mjs --dry-run` in this directory to validate packaging
34
+ without publishing.
35
+
36
+ In your application directory, install the SDK from a SQLess checkout:
37
+
38
+ ```sh
39
+ pnpm add /path/to/sqless/sdks/node
40
+ ```
41
+
42
+ For a monorepo, a relative `file:` dependency also works:
43
+
44
+ ```json
45
+ {
46
+ "dependencies": {
47
+ "@trysqless/node": "file:../sqless/sdks/node"
48
+ }
49
+ }
50
+ ```
51
+
52
+ ## Connect and execute SQL
53
+
54
+ ```js
55
+ import { SQLessClient } from '@trysqless/node';
56
+
57
+ const db = await SQLessClient.connect(process.env.DATABASE_CONNECTION_STRING);
58
+ try {
59
+ await db.execute([
60
+ { sql: 'CREATE TABLE IF NOT EXISTS notes(id INTEGER PRIMARY KEY, message TEXT)', parameters: [] },
61
+ { sql: 'INSERT INTO notes(message) VALUES (?)', parameters: ['hello'] },
62
+ ], { write: true });
63
+
64
+ const { results } = await db.execute([
65
+ { sql: 'SELECT id, message FROM notes WHERE message = ?', parameters: ['hello'] },
66
+ ]);
67
+ console.log(results[0].columns, results[0].rows);
68
+ } finally {
69
+ db.close();
70
+ }
71
+ ```
72
+
73
+ Keep one client at process scope in an HTTP server and close it during shutdown.
74
+ Concurrent `execute()` calls share one authenticated WebSocket and a bounded
75
+ session pool. An idle connection does not issue SQL probes or keep database
76
+ compute running. `isClosed()` reports connection loss; reconnect explicitly for
77
+ future operations. Failed SQL is never replayed by the SDK.
78
+
79
+ The connection string format is:
80
+
81
+ ```text
82
+ ws[s]://token:<percent-encoded-token>@host/path/api/v1/ws?database_id=<uuid>
83
+ ```
84
+
85
+ The SDK removes URL credentials and `database_id` before connecting. It sends the
86
+ token in the upgrade's Authorization header and binds sessions to the database
87
+ UUID. Keep the string in server-side configuration; never log it or ship it to
88
+ browser code. Authentication happens once at upgrade. Administrative token
89
+ changes do not revoke an already established connection.
90
+
91
+ Separate connection fields are also supported:
92
+
93
+ ```js
94
+ const db = await SQLessClient.connect({
95
+ url: 'ws://notes.sqless.internal/api/v1/ws',
96
+ databaseId: process.env.DATABASE_ID,
97
+ token: process.env.DATABASE_TOKEN,
98
+ sessions: 16,
99
+ maxQueued: 2048,
100
+ timeout: 60000,
101
+ });
102
+ ```
103
+
104
+ Pool options can also accompany `{ connectionString }`. `sessions` is between
105
+ 1 and 16 (default 16), `maxQueued` is the number of waiting callers (default 2048),
106
+ and `timeout` is the request/queue timeout in milliseconds (default 60000).
107
+ Optional `headers` configure the handshake; the SDK supplies Authorization.
108
+ Explicit sessions and automatic requests share this same pool limit.
109
+
110
+ ## Methods
111
+
112
+ | Object | Method | Result |
113
+ | --- | --- | --- |
114
+ | Client | `execute(statements, options?)` | `{ results, transaction? }` for a complete batch |
115
+ | Client | `executeScript(script, parameterSets?, options?)` | The same result for a SQL script |
116
+ | Client | `openSession()` | A reserved session for sequential, interactive work |
117
+ | Client or session | `getTransaction(transactionId)` | A transaction receipt |
118
+ | Client or session | `isClosed()` | Whether the connection/session has closed |
119
+ | Client or session | `close()` | Release the connection/session; safe to call twice |
120
+ | Session | `execute(statements, options?)` | Execute statements on the reserved session |
121
+ | Session | `executeScript(script, parameterSets?, options?)` | Execute a script on the reserved session |
122
+ | Session | `begin({ transactionId }?)` | Begin a write transaction and return its receipt |
123
+ | Session | `commit()` | Commit and return the receipt |
124
+ | Session | `rollback()` | Roll back and return the receipt |
125
+
126
+ A statement contains `sql`, `parameters`, and optional `maxRows`. Each result
127
+ contains `columns`, array-valued `rows`, `rowsAffected`, `truncated`, and optional
128
+ `lastInsertId`. `parameterSets`, when provided for a script, must contain one
129
+ parameter array per SQL statement, including empty arrays for statements without
130
+ parameters.
131
+
132
+ Client execution options accept `write: true` to generate a transaction UUID, or
133
+ an explicit `transactionId`. SQLess determines read/write behavior from SQL;
134
+ `write` does not change server-side permissions. Supply your own UUID when you
135
+ need to look up a write whose response might be lost. Session execution options
136
+ accept `transactionId`; inside an active transaction, normally omit it and use
137
+ the ID returned by `begin()`.
138
+
139
+ Integers outside JavaScript's safe range are returned as `bigint`. Pass `bigint`
140
+ for large integer parameters to preserve their exact value. Inputs support
141
+ `null`, boolean, number, bigint, and string. BLOB results use base64 strings, as
142
+ defined by the SQLess value contract.
143
+
144
+ ## Interactive transactions
145
+
146
+ Await each operation on a reserved session before starting the next one:
147
+
148
+ ```js
149
+ const session = await db.openSession();
150
+ try {
151
+ const transaction = await session.begin();
152
+ await session.execute([
153
+ { sql: 'INSERT INTO notes(message) VALUES (?)', parameters: ['transactional'] },
154
+ ]);
155
+ const receipt = await session.commit();
156
+ console.log(transaction.id, receipt.state);
157
+ } finally {
158
+ session.close();
159
+ }
160
+ ```
161
+
162
+ Use `session.rollback()` to explicitly abort an active transaction. Closing a
163
+ session aborts uncommitted work and releases its pool slot. Once the server has
164
+ accepted COMMIT, closing the session cannot undo it. The pooled client methods
165
+ reject an unfinished interactive transaction and close that session instead of
166
+ lending it to another caller.
167
+
168
+ For an uncertain write, retain its UUID before sending SQL:
169
+
170
+ ```js
171
+ import { randomUUID } from 'node:crypto';
172
+
173
+ const transactionId = randomUUID();
174
+ await db.execute([
175
+ { sql: 'INSERT INTO notes(message) VALUES (?)', parameters: ['receipt example'] },
176
+ ], { transactionId });
177
+
178
+ // This may also be queried on a newly connected client after transport loss.
179
+ const receipt = await db.getTransaction(transactionId);
180
+ console.log(receipt.state);
181
+ ```
182
+
183
+ Connection loss or a timeout is not proof that a write failed. Inspect the
184
+ transaction receipt instead of blindly retrying SQL. Receipt states are
185
+ `active`, `committing`, `committed`, `rolled_back`, and `unknown`.
186
+
187
+ Server errors reject with `SQLessError`, exposing `code`, optional
188
+ `statementIndex`, and optional `transaction`. Connection, timeout, and queue
189
+ errors reject with `Error`. Requests are limited to 4 MiB and responses to 9 MiB.
190
+
191
+ ## Tests
192
+
193
+ From the SQLess repository root:
194
+
195
+ ```sh
196
+ pnpm install --dir sdks/node --frozen-lockfile
197
+ pnpm --dir sdks/node test
198
+ CGO_ENABLED=1 go test -race -tags vfs ./pkg/handler ./pkg/service/database \
199
+ -run 'TestNode(Client|SDK)' -v
200
+ ```
201
+
202
+ The Go tests run the JavaScript scenarios in `test/` against real WebSocket/smux
203
+ handlers. They cover authentication, database binding, large messages, BigInt,
204
+ 160 concurrent calls, no replay after disconnect, and method-based transactions
205
+ against real SQLite/VFS. The database fixture substitutes control and object
206
+ storage, so this is not a cloud durability or capacity test.
package/errors.js ADDED
@@ -0,0 +1,9 @@
1
+ export class SQLessError extends Error {
2
+ constructor(response) {
3
+ super(`${response.error.code}: ${response.error.message}`);
4
+ this.name = 'SQLessError';
5
+ this.code = response.error.code;
6
+ this.statementIndex = response.error.statementIndex;
7
+ this.transaction = response.transaction;
8
+ }
9
+ }
package/index.d.ts ADDED
@@ -0,0 +1,76 @@
1
+ export type SQLValue = null | boolean | number | bigint | string;
2
+
3
+ export interface Statement {
4
+ sql: string;
5
+ parameters: SQLValue[];
6
+ maxRows?: number;
7
+ }
8
+
9
+ export interface StatementResult {
10
+ columns: string[];
11
+ rows: SQLValue[][];
12
+ rowsAffected: number | bigint;
13
+ lastInsertId?: number | bigint;
14
+ truncated: boolean;
15
+ }
16
+
17
+ export interface Transaction {
18
+ id: string;
19
+ databaseId: string;
20
+ createdAt: string;
21
+ state: 'active' | 'committing' | 'committed' | 'rolled_back' | 'unknown';
22
+ remoteTxid?: string;
23
+ reason?: string;
24
+ }
25
+
26
+ export interface SQLResult {
27
+ results: StatementResult[];
28
+ transaction?: Transaction;
29
+ }
30
+
31
+ export interface ExecuteOptions {
32
+ /** Generate a transaction UUID before sending a complete write batch. */
33
+ write?: boolean;
34
+ /** Supply your own UUID to query the receipt after an uncertain outcome. */
35
+ transactionId?: string;
36
+ }
37
+
38
+ export type ConnectOptions = {
39
+ sessions?: number;
40
+ maxQueued?: number;
41
+ /** Request and queue timeout in milliseconds. Default: 60000. */
42
+ timeout?: number;
43
+ headers?: Record<string, string>;
44
+ } & ({ connectionString: string; token?: string; databaseId?: string }
45
+ | { url: string; token: string; databaseId: string });
46
+
47
+ export class SQLessError extends Error {
48
+ private constructor();
49
+ readonly code: string;
50
+ readonly statementIndex?: number;
51
+ readonly transaction?: Transaction;
52
+ }
53
+
54
+ export class SQLessClient {
55
+ private constructor();
56
+ static connect(options: string | ConnectOptions): Promise<SQLessClient>;
57
+ execute(statements: Statement[], options?: ExecuteOptions): Promise<SQLResult>;
58
+ executeScript(script: string, parameterSets?: SQLValue[][], options?: ExecuteOptions): Promise<SQLResult>;
59
+ getTransaction(transactionId: string): Promise<Transaction>;
60
+ openSession(): Promise<SQLessSession>;
61
+ isClosed(): boolean;
62
+ close(): void;
63
+ }
64
+
65
+ /** A reserved pool slot. Calls on a session must be awaited sequentially. */
66
+ export interface SQLessSession {
67
+ execute(statements: Statement[], options?: Pick<ExecuteOptions, 'transactionId'>): Promise<SQLResult>;
68
+ executeScript(script: string, parameterSets?: SQLValue[][], options?: Pick<ExecuteOptions, 'transactionId'>): Promise<SQLResult>;
69
+ begin(options?: Pick<ExecuteOptions, 'transactionId'>): Promise<Transaction>;
70
+ commit(): Promise<Transaction>;
71
+ rollback(): Promise<Transaction>;
72
+ getTransaction(transactionId: string): Promise<Transaction>;
73
+ isClosed(): boolean;
74
+ /** Releases the slot and aborts uncommitted work; cannot undo an accepted COMMIT. */
75
+ close(): void;
76
+ }
package/index.js ADDED
@@ -0,0 +1,77 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { Connection } from './transport.js';
3
+
4
+ export { SQLessError } from './errors.js';
5
+
6
+ const result = response => ({ results: response.results ?? [], ...(response.transaction ? { transaction: response.transaction } : {}) });
7
+ const receipt = ({ write = false, transactionId } = {}) => ({ transactionId: transactionId ?? (write ? randomUUID() : undefined) });
8
+
9
+ // Transport objects never leave this module. Clients and leased sessions share
10
+ // the same bounded pool; opening an interactive session reserves one pool slot.
11
+ export class SQLessClient {
12
+ #connection;
13
+
14
+ static async connect(options) {
15
+ return new SQLessClient(await Connection.connect(options));
16
+ }
17
+
18
+ constructor(connection) { this.#connection = connection; }
19
+
20
+ async execute(statements, options) {
21
+ return result(await this.#connection.request({ op: 'execute', statements, ...receipt(options) }));
22
+ }
23
+
24
+ async executeScript(script, parameterSets, options) {
25
+ return result(await this.#connection.request({ op: 'execute', script, parameterSets, ...receipt(options) }));
26
+ }
27
+
28
+ async getTransaction(transactionId) {
29
+ return (await this.#connection.request({ op: 'status', transactionId })).transaction;
30
+ }
31
+
32
+ async openSession() {
33
+ return new SQLessSession(this.#connection, await this.#connection.acquire());
34
+ }
35
+
36
+ isClosed() { return this.#connection.closed; }
37
+ close() { this.#connection.close(); }
38
+ }
39
+
40
+ class SQLessSession {
41
+ #connection;
42
+ #session;
43
+ #closed = false;
44
+
45
+ constructor(connection, session) {
46
+ this.#connection = connection;
47
+ this.#session = session;
48
+ }
49
+
50
+ async execute(statements, { transactionId } = {}) {
51
+ return result(await this.#session.call({ op: 'execute', statements, transactionId }));
52
+ }
53
+
54
+ async executeScript(script, parameterSets, { transactionId } = {}) {
55
+ return result(await this.#session.call({ op: 'execute', script, parameterSets, transactionId }));
56
+ }
57
+
58
+ async begin({ transactionId = randomUUID() } = {}) {
59
+ return (await this.executeScript('BEGIN IMMEDIATE', undefined, { transactionId })).transaction;
60
+ }
61
+
62
+ async commit() { return (await this.executeScript('COMMIT')).transaction; }
63
+ async rollback() { return (await this.executeScript('ROLLBACK')).transaction; }
64
+
65
+ async getTransaction(transactionId) {
66
+ return (await this.#session.call({ op: 'status', transactionId })).transaction;
67
+ }
68
+
69
+ isClosed() { return this.#session.closed; }
70
+
71
+ close() {
72
+ if (this.#closed) return;
73
+ this.#closed = true;
74
+ this.#session.close();
75
+ this.#connection.release(this.#session);
76
+ }
77
+ }
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@trysqless/node",
3
+ "version": "0.1.0",
4
+ "description": "Method-based Node.js SDK for SQLess over authenticated WebSocket",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/cloudcarver/sqless.git",
8
+ "directory": "sdks/node"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public",
12
+ "registry": "https://registry.npmjs.org"
13
+ },
14
+ "type": "module",
15
+ "main": "index.js",
16
+ "exports": "./index.js",
17
+ "files": [
18
+ "index.js",
19
+ "transport.js",
20
+ "errors.js",
21
+ "index.d.ts",
22
+ "README.md"
23
+ ],
24
+ "types": "index.d.ts",
25
+ "scripts": {
26
+ "test": "node --test *.test.js && tsc --noEmit --strict --target ES2022 --module NodeNext test/types.mts"
27
+ },
28
+ "engines": {
29
+ "node": ">=22"
30
+ },
31
+ "dependencies": {
32
+ "ws": "8.18.3"
33
+ },
34
+ "devDependencies": {
35
+ "typescript": "5.9.3"
36
+ }
37
+ }
package/transport.js ADDED
@@ -0,0 +1,202 @@
1
+ import WebSocket from 'ws';
2
+ import { SQLessError } from './errors.js';
3
+
4
+ const WINDOW = 256 * 1024, FRAME = 32 * 1024, MAX_REQUEST = 4 << 20, MAX_RESPONSE = 9 << 20;
5
+ const SYN = 0, FIN = 1, PSH = 2, NOP = 3, UPD = 4;
6
+ const stringify = value => JSON.stringify(value, (_, v) => typeof v === 'bigint' ? JSON.rawJSON(v.toString()) : v);
7
+ const parse = text => JSON.parse(text, (_, value, context) =>
8
+ typeof value === 'number' && !Number.isSafeInteger(value) && /^-?\d+$/.test(context.source) ? BigInt(context.source) : value);
9
+
10
+ class Session {
11
+ constructor(client, id) {
12
+ this.client = client; this.id = id; this.seq = 0; this.closed = false;
13
+ this.written = 0; this.consumed = 0; this.window = WINDOW;
14
+ this.received = 0; this.ack = 0; this.chunks = []; this.bytes = 0; this.header = Buffer.alloc(0);
15
+ this.expected = null; this.pending = null; this.outgoing = null;
16
+ this.state = 'idle';
17
+ client.streams.set(id, this); client.frame(SYN, id);
18
+ }
19
+ call(request) {
20
+ if (this.closed) return Promise.reject(new Error('SQLess session closed; SQL is never replayed'));
21
+ if (this.pending) return Promise.reject(new Error('Only one request may be in flight per session'));
22
+ const id = String(++this.seq);
23
+ const body = Buffer.from(stringify({ ...request, version: 1, id }));
24
+ if (!body.length || body.length > MAX_REQUEST) return Promise.reject(new Error('SQLess request exceeds 4 MiB'));
25
+ const payload = Buffer.allocUnsafe(body.length + 4); payload.writeUInt32BE(body.length); body.copy(payload, 4);
26
+ return new Promise((resolve, reject) => {
27
+ const timer = setTimeout(() => this.close(new Error('SQLess request timed out; transaction outcome may be unknown')), this.client.timeout);
28
+ this.pending = { id, op: request.op, resolve, reject, timer }; this.outgoing = { payload, offset: 0 }; this.pump();
29
+ });
30
+ }
31
+ pump() {
32
+ const o = this.outgoing;
33
+ if (!o || this.closed) return;
34
+ while (o.offset < o.payload.length && this.client.ws.bufferedAmount < 1 << 20) {
35
+ const available = this.window - ((this.written - this.consumed) >>> 0);
36
+ if (available <= 0) break;
37
+ const n = Math.min(FRAME, available, o.payload.length - o.offset);
38
+ const data = o.payload.subarray(o.offset, o.offset + n);
39
+ o.offset += n; this.written = (this.written + n) >>> 0;
40
+ this.client.frame(PSH, this.id, data);
41
+ }
42
+ if (o.offset === o.payload.length) this.outgoing = null;
43
+ }
44
+ update(data) {
45
+ if (data.length !== 8) throw new Error('Invalid smux window update');
46
+ const consumed = data.readUInt32LE(0), window = data.readUInt32LE(4);
47
+ if (((this.written - consumed) >>> 0) > 0x7fffffff || window > 0x7fffffff) throw new Error('Invalid smux acknowledgement');
48
+ this.consumed = consumed; this.window = window; this.pump();
49
+ }
50
+ receive(data) {
51
+ this.received = (this.received + data.length) >>> 0;
52
+ this.ack += data.length;
53
+ while (data.length) {
54
+ if (!this.pending) throw new Error('Unsolicited SQLess response');
55
+ if (this.expected === null) {
56
+ const n = Math.min(4 - this.header.length, data.length);
57
+ this.header = Buffer.concat([this.header, data.subarray(0, n)]); data = data.subarray(n);
58
+ if (this.header.length < 4) break;
59
+ this.expected = this.header.readUInt32BE(0); this.header = Buffer.alloc(0);
60
+ if (!this.expected || this.expected > MAX_RESPONSE) throw new Error('SQLess response exceeds 9 MiB');
61
+ }
62
+ const n = Math.min(this.expected - this.bytes, data.length);
63
+ this.chunks.push(data.subarray(0, n)); this.bytes += n; data = data.subarray(n);
64
+ if (this.bytes === this.expected) {
65
+ const response = parse(Buffer.concat(this.chunks, this.bytes).toString('utf8'));
66
+ this.chunks = []; this.bytes = 0; this.expected = null;
67
+ const pending = this.pending;
68
+ if (response.version !== 1 || response.id !== pending.id) throw new Error('SQLess response identity mismatch');
69
+ // A status lookup's receipt belongs to the requested transaction, not
70
+ // necessarily the transaction currently running on this session.
71
+ if (pending.op === 'execute' || response.sessionState === 'closed') this.state = response.sessionState;
72
+ this.pending = null; clearTimeout(pending.timer);
73
+ if (response.error) pending.reject(new SQLessError(response)); else pending.resolve(response);
74
+ if (response.sessionState === 'closed') this.close(new Error('SQLess session closed'));
75
+ }
76
+ }
77
+ if (!this.closed && (this.ack >= WINDOW / 2 || this.received === this.ack)) {
78
+ const ack = Buffer.allocUnsafe(8); ack.writeUInt32LE(this.received); ack.writeUInt32LE(WINDOW, 4);
79
+ this.ack = 0; this.client.frame(UPD, this.id, ack);
80
+ }
81
+ }
82
+ close(error = new Error('SQLess session closed; transaction outcome may be unknown')) {
83
+ if (this.closed) return;
84
+ this.closed = true;
85
+ if (this.pending) { clearTimeout(this.pending.timer); this.pending.reject(error); this.pending = null; }
86
+ this.chunks = []; this.outgoing = null;
87
+ this.client.streams.delete(this.id); this.client.frame(FIN, this.id);
88
+ }
89
+ }
90
+
91
+ // One authenticated WebSocket multiplexes up to 16 sequential SQL sessions.
92
+ // Queueing is bounded. No SQL, transaction or failed OPEN is automatically replayed.
93
+ export class Connection {
94
+ static async connect(options) {
95
+ const { url, connectionString, sessions = 16, maxQueued = 2048, timeout = 60000, headers = {} } = typeof options === 'string' ? { connectionString: options } : options;
96
+ let { token, databaseId } = typeof options === 'string' ? {} : options;
97
+ if (!Number.isInteger(sessions) || sessions < 1 || sessions > 16) throw new Error('sessions must be between 1 and 16');
98
+ if (!Number.isInteger(maxQueued) || maxQueued < 0 || !Number.isFinite(timeout) || timeout <= 0) throw new Error('Invalid queue or timeout');
99
+ const client = new Connection();
100
+ const endpoint = new URL(connectionString ?? url);
101
+ if (!['http:', 'https:', 'ws:', 'wss:'].includes(endpoint.protocol)) throw new Error('SQLess requires an HTTP or WebSocket URL');
102
+ if (connectionString) {
103
+ token ??= decodeURIComponent(endpoint.password);
104
+ databaseId ??= endpoint.searchParams.get('database_id');
105
+ }
106
+ if (!token || !databaseId) throw new Error('SQLess requires a database token and ID');
107
+ endpoint.username = ''; endpoint.password = ''; endpoint.searchParams.delete('database_id');
108
+ Object.assign(client, { databaseId, limit: sessions, maxQueued, timeout });
109
+ endpoint.protocol = endpoint.protocol === 'https:' || endpoint.protocol === 'wss:' ? 'wss:' : 'ws:';
110
+ if (!endpoint.pathname.endsWith('/api/v1/ws')) endpoint.pathname = endpoint.pathname.replace(/\/$/, '') + '/api/v1/ws';
111
+ client.ws = new WebSocket(endpoint, 'sqless.v1', { headers: { ...headers, Authorization: `Bearer ${token}` }, maxPayload: 64 << 10, handshakeTimeout: 10000, perMessageDeflate: false, followRedirects: false });
112
+ const ready = new Promise((resolve, reject) => {
113
+ client.ws.once('open', () => { if (client.ws.protocol !== 'sqless.v1') { reject(new Error('Missing sqless.v1 protocol')); client.close(); } else resolve(); });
114
+ client.ws.once('error', reject);
115
+ client.ws.once('close', () => reject(new Error('SQLess handshake closed')));
116
+ });
117
+ client.ws.on('error', error => client.fail(error));
118
+ client.ws.on('close', () => client.fail(new Error('SQLess connection closed; transaction outcome may be unknown')));
119
+ client.ws.on('message', (data, binary) => {
120
+ try { if (!binary) throw new Error('Binary sqless.v1 message required'); client.receive(data); }
121
+ catch (error) { client.fail(error); }
122
+ });
123
+ await ready; return client;
124
+ }
125
+ constructor() {
126
+ this.streams = new Map(); this.next = 1; this.buffer = Buffer.alloc(0);
127
+ this.idle = []; this.queue = []; this.allocated = 0; this.closed = false;
128
+ }
129
+ frame(cmd, id, data = Buffer.alloc(0)) {
130
+ if (this.closed || this.ws.readyState !== WebSocket.OPEN) return;
131
+ const frame = Buffer.allocUnsafe(data.length + 8);
132
+ frame[0] = 2; frame[1] = cmd; frame.writeUInt16LE(data.length, 2); frame.writeUInt32LE(id, 4); data.copy(frame, 8);
133
+ this.ws.send(frame, error => { if (error) this.fail(error); else for (const s of this.streams.values()) s.pump(); });
134
+ }
135
+ receive(data) {
136
+ this.buffer = this.buffer.length ? Buffer.concat([this.buffer, data]) : data;
137
+ while (this.buffer.length >= 8) {
138
+ const b = this.buffer, length = b.readUInt16LE(2);
139
+ if (b[0] !== 2) throw new Error('Unsupported smux version');
140
+ if (b.length < length + 8) return;
141
+ const cmd = b[1], id = b.readUInt32LE(4), body = b.subarray(8, length + 8);
142
+ this.buffer = b.subarray(length + 8);
143
+ const stream = this.streams.get(id);
144
+ if (cmd === NOP) continue;
145
+ if (cmd === SYN || cmd > UPD) throw new Error('Unexpected smux command');
146
+ // A FIN or in-flight PSH may arrive after a locally closed stream.
147
+ if (!stream) continue;
148
+ if (cmd === PSH) stream.receive(body);
149
+ else if (cmd === UPD) stream.update(body);
150
+ else if (cmd === FIN) stream.close();
151
+ }
152
+ }
153
+ async openSession(databaseId = this.databaseId) {
154
+ if (this.closed) throw new Error('SQLess client closed');
155
+ if (this.next > 0xffffffff) throw new Error('SQLess stream IDs exhausted');
156
+ const s = new Session(this, this.next); this.next += 2;
157
+ try { await s.call({ op: 'open', databaseId }); return s; }
158
+ catch (error) { s.close(error); throw error; }
159
+ }
160
+ async acquire() {
161
+ if (this.closed) throw new Error('SQLess client closed');
162
+ while (this.idle.length) { const s = this.idle.pop(); if (!s.closed) return s; this.allocated--; }
163
+ if (this.allocated < this.limit) {
164
+ this.allocated++;
165
+ try { return await this.openSession(); }
166
+ catch (error) { this.allocated--; this.wake(); throw error; }
167
+ }
168
+ if (this.queue.length >= this.maxQueued) throw new Error('SQLess session queue is full');
169
+ return new Promise((resolve, reject) => {
170
+ const waiter = { resolve, reject };
171
+ waiter.timer = setTimeout(() => { const i = this.queue.indexOf(waiter); if (i >= 0) this.queue.splice(i, 1); reject(new Error('SQLess session queue timed out; SQL was not sent')); }, this.timeout);
172
+ this.queue.push(waiter);
173
+ });
174
+ }
175
+ wake() {
176
+ if (!this.queue.length || this.closed) return;
177
+ const waiter = this.queue.shift(); clearTimeout(waiter.timer);
178
+ this.acquire().then(waiter.resolve, waiter.reject);
179
+ }
180
+ release(s) { if (s.closed) this.allocated--; else this.idle.push(s); this.wake(); }
181
+ async request(request) {
182
+ const s = await this.acquire();
183
+ try {
184
+ const response = await s.call(request);
185
+ if (s.state === 'transaction') throw new Error('Use openSession() for an interactive transaction; this session was closed');
186
+ return response;
187
+ } finally {
188
+ // Error responses may also leave a transaction active. Never hand that
189
+ // transaction to the next caller borrowing a pooled session.
190
+ if (s.state === 'transaction') s.close();
191
+ this.release(s);
192
+ }
193
+ }
194
+ fail(error) {
195
+ if (this.closed) return;
196
+ this.closed = true;
197
+ for (const s of this.streams.values()) s.close(error);
198
+ for (const w of this.queue) { clearTimeout(w.timer); w.reject(error); }
199
+ this.queue = []; this.idle = []; this.ws.terminate();
200
+ }
201
+ close() { this.fail(new Error('SQLess client closed')); }
202
+ }