@tursodatabase/serverless 1.1.1 → 1.1.2-pre.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.
package/dist/index.js CHANGED
@@ -1,6 +1,1056 @@
1
- // Turso serverless driver entry point
2
- export { Connection, connect } from './connection.js';
3
- export { Statement } from './statement.js';
4
- export { Session } from './session.js';
5
- export { DatabaseError, TimeoutError } from './error.js';
6
- export { ENCRYPTION_KEY_HEADER } from './protocol.js';
1
+ // src/async-lock.ts
2
+ var AsyncLock = class {
3
+ constructor() {
4
+ this.locked = false;
5
+ this.queue = [];
6
+ }
7
+ async acquire() {
8
+ if (!this.locked) {
9
+ this.locked = true;
10
+ return;
11
+ }
12
+ return new Promise((resolve) => {
13
+ this.queue.push(resolve);
14
+ });
15
+ }
16
+ release() {
17
+ const next = this.queue.shift();
18
+ if (next) {
19
+ next();
20
+ } else {
21
+ this.locked = false;
22
+ }
23
+ }
24
+ };
25
+
26
+ // src/error.ts
27
+ var DatabaseError = class _DatabaseError extends Error {
28
+ constructor(message, code, rawCode, cause) {
29
+ super(message);
30
+ this.name = "DatabaseError";
31
+ this.code = code;
32
+ this.rawCode = rawCode;
33
+ this.cause = cause;
34
+ Object.setPrototypeOf(this, _DatabaseError.prototype);
35
+ }
36
+ };
37
+ var TimeoutError = class _TimeoutError extends DatabaseError {
38
+ constructor(message = "Query timed out", cause) {
39
+ super(message, "TIMEOUT", void 0, cause);
40
+ this.name = "TimeoutError";
41
+ Object.setPrototypeOf(this, _TimeoutError.prototype);
42
+ }
43
+ };
44
+
45
+ // src/protocol.ts
46
+ function encodeValue(value) {
47
+ if (value === null || value === void 0) {
48
+ return { type: "null" };
49
+ }
50
+ if (typeof value === "number") {
51
+ if (!Number.isFinite(value)) {
52
+ throw new Error("Only finite numbers (not Infinity or NaN) can be passed as arguments");
53
+ }
54
+ if (Number.isInteger(value)) {
55
+ return { type: "integer", value: value.toString() };
56
+ }
57
+ return { type: "float", value };
58
+ }
59
+ if (typeof value === "bigint") {
60
+ return { type: "integer", value: value.toString() };
61
+ }
62
+ if (typeof value === "boolean") {
63
+ return { type: "integer", value: value ? "1" : "0" };
64
+ }
65
+ if (typeof value === "string") {
66
+ return { type: "text", value };
67
+ }
68
+ if (value instanceof ArrayBuffer || value instanceof Uint8Array) {
69
+ const base64 = btoa(String.fromCharCode(...new Uint8Array(value)));
70
+ return { type: "blob", base64 };
71
+ }
72
+ return { type: "text", value: String(value) };
73
+ }
74
+ function decodeValue(value, safeIntegers = false) {
75
+ switch (value.type) {
76
+ case "null":
77
+ return null;
78
+ case "integer":
79
+ if (safeIntegers) {
80
+ return BigInt(value.value);
81
+ }
82
+ return parseInt(value.value, 10);
83
+ case "float":
84
+ return value.value;
85
+ case "text":
86
+ return value.value;
87
+ case "blob":
88
+ if (value.base64 !== void 0 && value.base64 !== null) {
89
+ let b64 = value.base64;
90
+ while (b64.length % 4 !== 0) {
91
+ b64 += "=";
92
+ }
93
+ const binaryString = atob(b64);
94
+ const bytes = new Uint8Array(binaryString.length);
95
+ for (let i = 0; i < binaryString.length; i++) {
96
+ bytes[i] = binaryString.charCodeAt(i);
97
+ }
98
+ return Buffer.from(bytes);
99
+ }
100
+ return Buffer.alloc(0);
101
+ default:
102
+ return null;
103
+ }
104
+ }
105
+ var ENCRYPTION_KEY_HEADER = "x-turso-encryption-key";
106
+ function wrapAbortError(error) {
107
+ if (error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError")) {
108
+ throw new TimeoutError("Query timed out");
109
+ }
110
+ throw error;
111
+ }
112
+ async function executeCursor(url, authToken, request, remoteEncryptionKey, signal) {
113
+ const headers = {
114
+ "Content-Type": "application/json"
115
+ };
116
+ if (authToken) {
117
+ headers["Authorization"] = `Bearer ${authToken}`;
118
+ }
119
+ if (remoteEncryptionKey) {
120
+ headers[ENCRYPTION_KEY_HEADER] = remoteEncryptionKey;
121
+ }
122
+ let response;
123
+ try {
124
+ response = await fetch(`${url}/v3/cursor`, {
125
+ method: "POST",
126
+ headers,
127
+ body: JSON.stringify(request),
128
+ signal
129
+ });
130
+ } catch (error) {
131
+ wrapAbortError(error);
132
+ }
133
+ if (!response.ok) {
134
+ let errorMessage = `HTTP error! status: ${response.status}`;
135
+ try {
136
+ const errorBody = await response.text();
137
+ const errorData = JSON.parse(errorBody);
138
+ if (errorData.message) {
139
+ errorMessage = errorData.message;
140
+ }
141
+ } catch {
142
+ }
143
+ throw new DatabaseError(errorMessage);
144
+ }
145
+ const reader = response.body?.getReader();
146
+ if (!reader) {
147
+ throw new DatabaseError("No response body");
148
+ }
149
+ const decoder = new TextDecoder();
150
+ let buffer = "";
151
+ let cursorResponse;
152
+ try {
153
+ while (!cursorResponse) {
154
+ const { done, value } = await reader.read();
155
+ if (done) break;
156
+ buffer += decoder.decode(value, { stream: true });
157
+ const newlineIndex = buffer.indexOf("\n");
158
+ if (newlineIndex !== -1) {
159
+ const line = buffer.slice(0, newlineIndex).trim();
160
+ buffer = buffer.slice(newlineIndex + 1);
161
+ if (line) {
162
+ cursorResponse = JSON.parse(line);
163
+ break;
164
+ }
165
+ }
166
+ }
167
+ } catch (error) {
168
+ reader.releaseLock();
169
+ wrapAbortError(error);
170
+ }
171
+ if (!cursorResponse) {
172
+ reader.releaseLock();
173
+ throw new DatabaseError("No cursor response received");
174
+ }
175
+ async function* parseEntries() {
176
+ try {
177
+ let newlineIndex;
178
+ while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
179
+ const line = buffer.slice(0, newlineIndex).trim();
180
+ buffer = buffer.slice(newlineIndex + 1);
181
+ if (line) {
182
+ yield JSON.parse(line);
183
+ }
184
+ }
185
+ while (true) {
186
+ let readResult;
187
+ try {
188
+ readResult = await reader.read();
189
+ } catch (error) {
190
+ wrapAbortError(error);
191
+ }
192
+ if (readResult.done) break;
193
+ buffer += decoder.decode(readResult.value, { stream: true });
194
+ while ((newlineIndex = buffer.indexOf("\n")) !== -1) {
195
+ const line = buffer.slice(0, newlineIndex).trim();
196
+ buffer = buffer.slice(newlineIndex + 1);
197
+ if (line) {
198
+ yield JSON.parse(line);
199
+ }
200
+ }
201
+ }
202
+ if (buffer.trim()) {
203
+ yield JSON.parse(buffer.trim());
204
+ }
205
+ } finally {
206
+ reader.releaseLock();
207
+ }
208
+ }
209
+ return { response: cursorResponse, entries: parseEntries() };
210
+ }
211
+ async function executePipeline(url, authToken, request, remoteEncryptionKey, signal) {
212
+ const headers = {
213
+ "Content-Type": "application/json"
214
+ };
215
+ if (authToken) {
216
+ headers["Authorization"] = `Bearer ${authToken}`;
217
+ }
218
+ if (remoteEncryptionKey) {
219
+ headers[ENCRYPTION_KEY_HEADER] = remoteEncryptionKey;
220
+ }
221
+ let response;
222
+ try {
223
+ response = await fetch(`${url}/v3/pipeline`, {
224
+ method: "POST",
225
+ headers,
226
+ body: JSON.stringify(request),
227
+ signal
228
+ });
229
+ } catch (error) {
230
+ wrapAbortError(error);
231
+ }
232
+ if (!response.ok) {
233
+ throw new DatabaseError(`HTTP error! status: ${response.status}`);
234
+ }
235
+ return response.json();
236
+ }
237
+
238
+ // src/session.ts
239
+ function normalizeUrl(url) {
240
+ return url.replace(/^libsql:\/\//, "https://");
241
+ }
242
+ function isValidIdentifier(str) {
243
+ return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(str);
244
+ }
245
+ var Session = class {
246
+ constructor(config) {
247
+ this.baton = null;
248
+ this.config = config;
249
+ this.baseUrl = normalizeUrl(config.url);
250
+ }
251
+ createAbortSignal(queryOptions) {
252
+ const timeout = queryOptions?.queryTimeout ?? this.config.defaultQueryTimeout;
253
+ if (timeout != null && timeout > 0) {
254
+ return AbortSignal.timeout(timeout);
255
+ }
256
+ return void 0;
257
+ }
258
+ /**
259
+ * Describe a SQL statement to get its column metadata.
260
+ *
261
+ * @param sql - The SQL statement to describe
262
+ * @returns Promise resolving to the statement description
263
+ */
264
+ async describe(sql, queryOptions) {
265
+ const request = {
266
+ baton: this.baton,
267
+ requests: [{
268
+ type: "describe",
269
+ sql
270
+ }]
271
+ };
272
+ let response;
273
+ try {
274
+ response = await executePipeline(this.baseUrl, this.config.authToken, request, this.config.remoteEncryptionKey, this.createAbortSignal(queryOptions));
275
+ } catch (e) {
276
+ this.baton = null;
277
+ throw e;
278
+ }
279
+ this.baton = response.baton;
280
+ if (response.base_url) {
281
+ this.baseUrl = response.base_url;
282
+ }
283
+ if (response.results && response.results[0]) {
284
+ const result = response.results[0];
285
+ if (result.type === "error") {
286
+ throw new DatabaseError(result.error?.message || "Describe execution failed", result.error?.code);
287
+ }
288
+ if (result.response?.type === "describe" && result.response.result) {
289
+ return result.response.result;
290
+ }
291
+ }
292
+ throw new DatabaseError("Unexpected describe response");
293
+ }
294
+ /**
295
+ * Execute a SQL statement and return all results.
296
+ *
297
+ * @param sql - The SQL statement to execute
298
+ * @param args - Optional array of parameter values or object with named parameters
299
+ * @param safeIntegers - Whether to return integers as BigInt
300
+ * @returns Promise resolving to the complete result set
301
+ */
302
+ async execute(sql, args = [], safeIntegers = false, queryOptions) {
303
+ const { response, entries } = await this.executeRaw(sql, args, queryOptions);
304
+ const result = await this.processCursorEntries(entries, safeIntegers);
305
+ return result;
306
+ }
307
+ /**
308
+ * Execute a SQL statement and return the raw response and entries.
309
+ *
310
+ * @param sql - The SQL statement to execute
311
+ * @param args - Optional array of parameter values or object with named parameters
312
+ * @returns Promise resolving to the raw response and cursor entries
313
+ */
314
+ async executeRaw(sql, args = [], queryOptions) {
315
+ let positionalArgs = [];
316
+ let namedArgs = [];
317
+ if (Array.isArray(args)) {
318
+ positionalArgs = args.map(encodeValue);
319
+ } else {
320
+ const keys = Object.keys(args);
321
+ const isNumericKeys = keys.length > 0 && keys.every((key) => /^\d+$/.test(key));
322
+ if (isNumericKeys) {
323
+ const sortedKeys = keys.sort((a, b) => parseInt(a) - parseInt(b));
324
+ const maxIndex = parseInt(sortedKeys[sortedKeys.length - 1]);
325
+ positionalArgs = new Array(maxIndex);
326
+ for (const key of sortedKeys) {
327
+ const index = parseInt(key) - 1;
328
+ positionalArgs[index] = encodeValue(args[key]);
329
+ }
330
+ for (let i = 0; i < positionalArgs.length; i++) {
331
+ if (positionalArgs[i] === void 0) {
332
+ positionalArgs[i] = { type: "null" };
333
+ }
334
+ }
335
+ } else {
336
+ namedArgs = Object.entries(args).map(([name, value]) => ({
337
+ name,
338
+ value: encodeValue(value)
339
+ }));
340
+ }
341
+ }
342
+ const request = {
343
+ baton: this.baton,
344
+ batch: {
345
+ steps: [{
346
+ stmt: {
347
+ sql,
348
+ args: positionalArgs,
349
+ named_args: namedArgs,
350
+ want_rows: true
351
+ }
352
+ }]
353
+ }
354
+ };
355
+ let result;
356
+ try {
357
+ result = await executeCursor(this.baseUrl, this.config.authToken, request, this.config.remoteEncryptionKey, this.createAbortSignal(queryOptions));
358
+ } catch (e) {
359
+ this.baton = null;
360
+ throw e;
361
+ }
362
+ const { response, entries } = result;
363
+ this.baton = response.baton;
364
+ if (response.base_url) {
365
+ this.baseUrl = response.base_url;
366
+ }
367
+ return { response, entries };
368
+ }
369
+ /**
370
+ * Process cursor entries into a structured result.
371
+ *
372
+ * @param entries - Async generator of cursor entries
373
+ * @returns Promise resolving to the processed result
374
+ */
375
+ async processCursorEntries(entries, safeIntegers = false) {
376
+ let columns = [];
377
+ let columnTypes = [];
378
+ let rows = [];
379
+ let rowsAffected = 0;
380
+ let lastInsertRowid;
381
+ for await (const entry of entries) {
382
+ switch (entry.type) {
383
+ case "step_begin":
384
+ if (entry.cols) {
385
+ columns = entry.cols.map((col) => col.name);
386
+ columnTypes = entry.cols.map((col) => col.decltype || "");
387
+ }
388
+ break;
389
+ case "row":
390
+ if (entry.row) {
391
+ const decodedRow = entry.row.map((value) => decodeValue(value, safeIntegers));
392
+ const rowObject = this.createRowObject(decodedRow, columns);
393
+ rows.push(rowObject);
394
+ }
395
+ break;
396
+ case "step_end":
397
+ if (entry.affected_row_count !== void 0) {
398
+ rowsAffected = entry.affected_row_count;
399
+ }
400
+ if (entry.last_insert_rowid !== void 0 && entry.last_insert_rowid !== null) {
401
+ lastInsertRowid = typeof entry.last_insert_rowid === "number" ? entry.last_insert_rowid : parseInt(entry.last_insert_rowid, 10);
402
+ }
403
+ break;
404
+ case "step_error":
405
+ case "error":
406
+ throw new DatabaseError(entry.error?.message || "SQL execution failed", entry.error?.code);
407
+ }
408
+ }
409
+ return {
410
+ columns,
411
+ columnTypes,
412
+ rows,
413
+ rowsAffected,
414
+ lastInsertRowid
415
+ };
416
+ }
417
+ /**
418
+ * Create a row object with both array and named property access.
419
+ *
420
+ * @param values - Array of column values
421
+ * @param columns - Array of column names
422
+ * @returns Row object with dual access patterns
423
+ */
424
+ createRowObject(values, columns) {
425
+ const row = [...values];
426
+ columns.forEach((column, index) => {
427
+ if (column && isValidIdentifier(column)) {
428
+ Object.defineProperty(row, column, {
429
+ value: values[index],
430
+ enumerable: false,
431
+ writable: false,
432
+ configurable: true
433
+ });
434
+ }
435
+ });
436
+ return row;
437
+ }
438
+ /**
439
+ * Execute multiple SQL statements in a batch.
440
+ *
441
+ * @param statements - Array of SQL statements to execute
442
+ * @returns Promise resolving to batch execution results
443
+ */
444
+ async batch(statements, queryOptions) {
445
+ const request = {
446
+ baton: this.baton,
447
+ batch: {
448
+ steps: statements.map((sql) => ({
449
+ stmt: {
450
+ sql,
451
+ args: [],
452
+ named_args: [],
453
+ want_rows: false
454
+ }
455
+ }))
456
+ }
457
+ };
458
+ let batchResult;
459
+ try {
460
+ batchResult = await executeCursor(this.baseUrl, this.config.authToken, request, this.config.remoteEncryptionKey, this.createAbortSignal(queryOptions));
461
+ } catch (e) {
462
+ this.baton = null;
463
+ throw e;
464
+ }
465
+ const { response, entries } = batchResult;
466
+ this.baton = response.baton;
467
+ if (response.base_url) {
468
+ this.baseUrl = response.base_url;
469
+ }
470
+ let totalRowsAffected = 0;
471
+ let lastInsertRowid;
472
+ for await (const entry of entries) {
473
+ switch (entry.type) {
474
+ case "step_end":
475
+ if (entry.affected_row_count !== void 0) {
476
+ totalRowsAffected += entry.affected_row_count;
477
+ }
478
+ if (entry.last_insert_rowid !== void 0 && entry.last_insert_rowid !== null) {
479
+ lastInsertRowid = typeof entry.last_insert_rowid === "number" ? entry.last_insert_rowid : parseInt(entry.last_insert_rowid, 10);
480
+ }
481
+ break;
482
+ case "step_error":
483
+ case "error":
484
+ throw new DatabaseError(entry.error?.message || "Batch execution failed", entry.error?.code);
485
+ }
486
+ }
487
+ return {
488
+ rowsAffected: totalRowsAffected,
489
+ lastInsertRowid
490
+ };
491
+ }
492
+ /**
493
+ * Execute a sequence of SQL statements separated by semicolons.
494
+ *
495
+ * @param sql - SQL string containing multiple statements separated by semicolons
496
+ * @returns Promise resolving when all statements are executed
497
+ */
498
+ async sequence(sql, queryOptions) {
499
+ const request = {
500
+ baton: this.baton,
501
+ requests: [{
502
+ type: "sequence",
503
+ sql
504
+ }]
505
+ };
506
+ let seqResponse;
507
+ try {
508
+ seqResponse = await executePipeline(this.baseUrl, this.config.authToken, request, this.config.remoteEncryptionKey, this.createAbortSignal(queryOptions));
509
+ } catch (e) {
510
+ this.baton = null;
511
+ throw e;
512
+ }
513
+ this.baton = seqResponse.baton;
514
+ if (seqResponse.base_url) {
515
+ this.baseUrl = seqResponse.base_url;
516
+ }
517
+ if (seqResponse.results && seqResponse.results[0]) {
518
+ const result = seqResponse.results[0];
519
+ if (result.type === "error") {
520
+ throw new DatabaseError(result.error?.message || "Sequence execution failed", result.error?.code);
521
+ }
522
+ }
523
+ }
524
+ /**
525
+ * Close the session.
526
+ *
527
+ * This sends a close request to the server to properly clean up the stream
528
+ * before resetting the local state.
529
+ */
530
+ async close() {
531
+ if (this.baton) {
532
+ try {
533
+ const request = {
534
+ baton: this.baton,
535
+ requests: [{
536
+ type: "close"
537
+ }]
538
+ };
539
+ await executePipeline(this.baseUrl, this.config.authToken, request, this.config.remoteEncryptionKey);
540
+ } catch {
541
+ }
542
+ }
543
+ this.baton = null;
544
+ this.baseUrl = "";
545
+ }
546
+ };
547
+
548
+ // src/statement.ts
549
+ var Statement = class _Statement {
550
+ constructor(sessionConfig, sql, columns) {
551
+ this.presentationMode = "expanded";
552
+ this.safeIntegerMode = false;
553
+ this.session = new Session(sessionConfig);
554
+ this.sql = sql;
555
+ this.columnMetadata = columns || [];
556
+ }
557
+ /**
558
+ * Create a Statement that shares an existing session and serializes execution
559
+ * through the given lock. Used by Connection.prepare() so prepared statements
560
+ * participate in the connection's transaction scope.
561
+ */
562
+ static fromSession(session, sql, columns, execLock) {
563
+ const stmt = Object.create(_Statement.prototype);
564
+ stmt.session = session;
565
+ stmt.sql = sql;
566
+ stmt.columnMetadata = columns || [];
567
+ stmt.presentationMode = "expanded";
568
+ stmt.safeIntegerMode = false;
569
+ stmt.execLock = execLock;
570
+ return stmt;
571
+ }
572
+ /**
573
+ * Whether the prepared statement returns data.
574
+ *
575
+ * This is `true` for SELECT queries and statements with RETURNING clause,
576
+ * and `false` for INSERT, UPDATE, DELETE statements without RETURNING.
577
+ *
578
+ * @example
579
+ * ```typescript
580
+ * const stmt = await conn.prepare(sql);
581
+ * if (stmt.reader) {
582
+ * return stmt.all(args); // SELECT-like query
583
+ * } else {
584
+ * return stmt.run(args); // INSERT/UPDATE/DELETE
585
+ * }
586
+ * ```
587
+ */
588
+ get reader() {
589
+ return this.columnMetadata.length > 0;
590
+ }
591
+ /**
592
+ * Enable raw mode to return arrays instead of objects.
593
+ *
594
+ * @param raw Enable or disable raw mode. If you don't pass the parameter, raw mode is enabled.
595
+ * @returns This statement instance for chaining
596
+ *
597
+ * @example
598
+ * ```typescript
599
+ * const stmt = client.prepare("SELECT * FROM users WHERE id = ?");
600
+ * const row = await stmt.raw().get([1]);
601
+ * console.log(row); // [1, "Alice", "alice@example.org"]
602
+ * ```
603
+ */
604
+ raw(raw) {
605
+ this.presentationMode = raw === false ? "expanded" : "raw";
606
+ return this;
607
+ }
608
+ /**
609
+ * Enable pluck mode to return only the first column value from each row.
610
+ *
611
+ * @param pluck Enable or disable pluck mode. If you don't pass the parameter, pluck mode is enabled.
612
+ * @returns This statement instance for chaining
613
+ *
614
+ * @example
615
+ * ```typescript
616
+ * const stmt = client.prepare("SELECT id FROM users");
617
+ * const ids = await stmt.pluck().all();
618
+ * console.log(ids); // [1, 2, 3, ...]
619
+ * ```
620
+ */
621
+ pluck(pluck) {
622
+ this.presentationMode = pluck === false ? "expanded" : "pluck";
623
+ return this;
624
+ }
625
+ /**
626
+ * Sets safe integers mode for this statement.
627
+ *
628
+ * @param toggle Whether to use safe integers. If you don't pass the parameter, safe integers mode is enabled.
629
+ * @returns This statement instance for chaining
630
+ */
631
+ safeIntegers(toggle) {
632
+ this.safeIntegerMode = toggle === false ? false : true;
633
+ return this;
634
+ }
635
+ /**
636
+ * Get column information for this statement.
637
+ *
638
+ * @returns Array of column metadata objects matching the native bindings format
639
+ *
640
+ * @example
641
+ * ```typescript
642
+ * const stmt = await client.prepare("SELECT id, name, email FROM users");
643
+ * const columns = stmt.columns();
644
+ * console.log(columns); // [{ name: 'id', type: 'INTEGER', column: null, database: null, table: null }, ...]
645
+ * ```
646
+ */
647
+ columns() {
648
+ return this.columnMetadata.map((col) => ({
649
+ name: col.name,
650
+ type: col.decltype
651
+ }));
652
+ }
653
+ async withLock(fn) {
654
+ if (!this.execLock) {
655
+ return await fn();
656
+ }
657
+ await this.execLock.acquire();
658
+ try {
659
+ return await fn();
660
+ } finally {
661
+ this.execLock.release();
662
+ }
663
+ }
664
+ /**
665
+ * Executes the prepared statement.
666
+ *
667
+ * @param args - Optional array of parameter values or object with named parameters
668
+ * @returns Promise resolving to the result of the statement
669
+ *
670
+ * @example
671
+ * ```typescript
672
+ * const stmt = client.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
673
+ * const result = await stmt.run(['John Doe', 'john.doe@example.com']);
674
+ * console.log(`Inserted user with ID ${result.lastInsertRowid}`);
675
+ * ```
676
+ */
677
+ async run(args, queryOptions) {
678
+ return await this.withLock(async () => {
679
+ const normalizedArgs = this.normalizeArgs(args);
680
+ const result = await this.session.execute(this.sql, normalizedArgs, this.safeIntegerMode, queryOptions);
681
+ return { changes: result.rowsAffected, lastInsertRowid: result.lastInsertRowid };
682
+ });
683
+ }
684
+ /**
685
+ * Execute the statement and return the first row.
686
+ *
687
+ * @param args - Optional array of parameter values or object with named parameters
688
+ * @returns Promise resolving to the first row or undefined if no results
689
+ *
690
+ * @example
691
+ * ```typescript
692
+ * const stmt = client.prepare("SELECT * FROM users WHERE id = ?");
693
+ * const user = await stmt.get([123]);
694
+ * if (user) {
695
+ * console.log(user.name);
696
+ * }
697
+ * ```
698
+ */
699
+ async get(args, queryOptions) {
700
+ return await this.withLock(async () => {
701
+ const normalizedArgs = this.normalizeArgs(args);
702
+ const result = await this.session.execute(this.sql, normalizedArgs, this.safeIntegerMode, queryOptions);
703
+ const row = result.rows[0];
704
+ if (!row) {
705
+ return void 0;
706
+ }
707
+ if (this.presentationMode === "pluck") {
708
+ return row[0];
709
+ }
710
+ if (this.presentationMode === "raw") {
711
+ return [...row];
712
+ }
713
+ const obj = {};
714
+ result.columns.forEach((col, i) => {
715
+ obj[col] = row[i];
716
+ });
717
+ return obj;
718
+ });
719
+ }
720
+ /**
721
+ * Execute the statement and return all rows.
722
+ *
723
+ * @param args - Optional array of parameter values or object with named parameters
724
+ * @returns Promise resolving to an array of all result rows
725
+ *
726
+ * @example
727
+ * ```typescript
728
+ * const stmt = client.prepare("SELECT * FROM users WHERE active = ?");
729
+ * const activeUsers = await stmt.all([true]);
730
+ * console.log(`Found ${activeUsers.length} active users`);
731
+ * ```
732
+ */
733
+ async all(args, queryOptions) {
734
+ return await this.withLock(async () => {
735
+ const normalizedArgs = this.normalizeArgs(args);
736
+ const result = await this.session.execute(this.sql, normalizedArgs, this.safeIntegerMode, queryOptions);
737
+ if (this.presentationMode === "pluck") {
738
+ return result.rows.map((row) => row[0]);
739
+ }
740
+ if (this.presentationMode === "raw") {
741
+ return result.rows.map((row) => [...row]);
742
+ }
743
+ return result.rows.map((row) => {
744
+ const obj = {};
745
+ result.columns.forEach((col, i) => {
746
+ obj[col] = row[i];
747
+ });
748
+ return obj;
749
+ });
750
+ });
751
+ }
752
+ /**
753
+ * Execute the statement and return an async iterator for streaming results.
754
+ *
755
+ * This method provides memory-efficient processing of large result sets
756
+ * by streaming rows one at a time instead of loading everything into memory.
757
+ *
758
+ * @param args - Optional array of parameter values or object with named parameters
759
+ * @returns AsyncGenerator that yields individual rows
760
+ *
761
+ * @example
762
+ * ```typescript
763
+ * const stmt = client.prepare("SELECT * FROM large_table WHERE category = ?");
764
+ * for await (const row of stmt.iterate(['electronics'])) {
765
+ * // Process each row individually
766
+ * console.log(row.id, row.name);
767
+ * }
768
+ * ```
769
+ */
770
+ async *iterate(args, queryOptions) {
771
+ if (this.execLock) {
772
+ const rows = await this.all(args, queryOptions);
773
+ for (const row of rows) {
774
+ yield row;
775
+ }
776
+ return;
777
+ }
778
+ const normalizedArgs = this.normalizeArgs(args);
779
+ const { entries } = await this.session.executeRaw(this.sql, normalizedArgs, queryOptions);
780
+ let columns = [];
781
+ for await (const entry of entries) {
782
+ switch (entry.type) {
783
+ case "step_begin":
784
+ if (entry.cols) {
785
+ columns = entry.cols.map((col) => col.name);
786
+ }
787
+ break;
788
+ case "row":
789
+ if (entry.row) {
790
+ const decodedRow = entry.row.map((value) => decodeValue(value, this.safeIntegerMode));
791
+ if (this.presentationMode === "pluck") {
792
+ yield decodedRow[0];
793
+ } else if (this.presentationMode === "raw") {
794
+ yield decodedRow;
795
+ } else {
796
+ const obj = {};
797
+ columns.forEach((col, i) => {
798
+ obj[col] = decodedRow[i];
799
+ });
800
+ yield obj;
801
+ }
802
+ }
803
+ break;
804
+ case "step_error":
805
+ case "error":
806
+ throw new DatabaseError(entry.error?.message || "SQL execution failed");
807
+ }
808
+ }
809
+ }
810
+ /**
811
+ * Normalize arguments to handle both single values and arrays.
812
+ * Matches the behavior of the native bindings.
813
+ */
814
+ normalizeArgs(args) {
815
+ if (args === void 0) {
816
+ return [];
817
+ }
818
+ if (Array.isArray(args)) {
819
+ return args;
820
+ }
821
+ if (args !== null && typeof args === "object" && args.constructor === Object) {
822
+ return args;
823
+ }
824
+ return [args];
825
+ }
826
+ };
827
+
828
+ // src/connection.ts
829
+ var Connection = class {
830
+ constructor(config) {
831
+ this.isOpen = true;
832
+ this.defaultSafeIntegerMode = false;
833
+ this._inTransaction = false;
834
+ this.execLock = new AsyncLock();
835
+ if (!config.url) {
836
+ throw new Error("invalid config: url is required");
837
+ }
838
+ this.config = config;
839
+ this.session = new Session(config);
840
+ Object.defineProperty(this, "inTransaction", {
841
+ get: () => this._inTransaction,
842
+ enumerable: true
843
+ });
844
+ }
845
+ /**
846
+ * Whether the database is currently in a transaction.
847
+ */
848
+ get inTransaction() {
849
+ return this._inTransaction;
850
+ }
851
+ /**
852
+ * Prepare a SQL statement for execution.
853
+ *
854
+ * Prepared statements created from a Connection use the same underlying session so transaction boundaries are preserved.
855
+ * This method fetches column metadata using the describe functionality.
856
+ *
857
+ * @param sql - The SQL statement to prepare
858
+ * @returns A Promise that resolves to a Statement object with column metadata
859
+ *
860
+ * @example
861
+ * ```typescript
862
+ * const stmt = await client.prepare("SELECT * FROM users WHERE id = ?");
863
+ * const columns = stmt.columns();
864
+ * const user = await stmt.get([123]);
865
+ * ```
866
+ */
867
+ async prepare(sql) {
868
+ if (!this.isOpen) {
869
+ throw new TypeError("The database connection is not open");
870
+ }
871
+ const session = new Session(this.config);
872
+ const description = await session.describe(sql);
873
+ await session.close();
874
+ const stmt = Statement.fromSession(this.session, sql, description.cols, this.execLock);
875
+ if (this.defaultSafeIntegerMode) {
876
+ stmt.safeIntegers(true);
877
+ }
878
+ return stmt;
879
+ }
880
+ /**
881
+ * Execute a SQL statement and return all results.
882
+ *
883
+ * @param sql - The SQL statement to execute
884
+ * @param args - Optional array of parameter values
885
+ * @returns Promise resolving to the complete result set
886
+ *
887
+ * @example
888
+ * ```typescript
889
+ * const result = await client.execute("SELECT * FROM users WHERE id = ?", [123]);
890
+ * console.log(result.rows);
891
+ * ```
892
+ */
893
+ async execute(sql, args, queryOptions) {
894
+ if (!this.isOpen) {
895
+ throw new TypeError("The database connection is not open");
896
+ }
897
+ await this.execLock.acquire();
898
+ try {
899
+ return await this.session.execute(sql, args || [], this.defaultSafeIntegerMode, queryOptions);
900
+ } finally {
901
+ this.execLock.release();
902
+ }
903
+ }
904
+ /**
905
+ * Execute a SQL statement and return all results.
906
+ *
907
+ * @param sql - The SQL statement to execute
908
+ * @returns Promise resolving to the complete result set
909
+ *
910
+ * @example
911
+ * ```typescript
912
+ * const result = await client.exec("SELECT * FROM users");
913
+ * console.log(result.rows);
914
+ * ```
915
+ */
916
+ async exec(sql, queryOptions) {
917
+ if (!this.isOpen) {
918
+ throw new TypeError("The database connection is not open");
919
+ }
920
+ await this.execLock.acquire();
921
+ try {
922
+ return await this.session.sequence(sql, queryOptions);
923
+ } finally {
924
+ this.execLock.release();
925
+ }
926
+ }
927
+ /**
928
+ * Execute multiple SQL statements in a batch.
929
+ *
930
+ * @param statements - Array of SQL statements to execute
931
+ * @param mode - Optional transaction mode (currently unused)
932
+ * @returns Promise resolving to batch execution results
933
+ *
934
+ * @example
935
+ * ```typescript
936
+ * await client.batch([
937
+ * "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)",
938
+ * "INSERT INTO users (name) VALUES ('Alice')",
939
+ * "INSERT INTO users (name) VALUES ('Bob')"
940
+ * ]);
941
+ * ```
942
+ */
943
+ async batch(statements, mode, queryOptions) {
944
+ if (!this.isOpen) {
945
+ throw new TypeError("The database connection is not open");
946
+ }
947
+ await this.execLock.acquire();
948
+ try {
949
+ return await this.session.batch(statements, queryOptions);
950
+ } finally {
951
+ this.execLock.release();
952
+ }
953
+ }
954
+ /**
955
+ * Execute a pragma.
956
+ *
957
+ * @param pragma - The pragma to execute
958
+ * @returns Promise resolving to the result of the pragma
959
+ */
960
+ async pragma(pragma, queryOptions) {
961
+ if (!this.isOpen) {
962
+ throw new TypeError("The database connection is not open");
963
+ }
964
+ await this.execLock.acquire();
965
+ try {
966
+ const sql = `PRAGMA ${pragma}`;
967
+ return await this.session.execute(sql, [], false, queryOptions);
968
+ } finally {
969
+ this.execLock.release();
970
+ }
971
+ }
972
+ /**
973
+ * Sets the default safe integers mode for all statements from this connection.
974
+ *
975
+ * @param toggle - Whether to use safe integers by default.
976
+ */
977
+ defaultSafeIntegers(toggle) {
978
+ this.defaultSafeIntegerMode = toggle === false ? false : true;
979
+ }
980
+ /**
981
+ * Returns a function that executes the given function in a transaction.
982
+ *
983
+ * @param fn - The function to wrap in a transaction
984
+ * @returns A function that will execute fn within a transaction
985
+ *
986
+ * @example
987
+ * ```typescript
988
+ * const insert = await client.prepare("INSERT INTO users (name) VALUES (?)");
989
+ * const insertMany = client.transaction((users) => {
990
+ * for (const user of users) {
991
+ * insert.run([user]);
992
+ * }
993
+ * });
994
+ *
995
+ * await insertMany(['Alice', 'Bob', 'Charlie']);
996
+ * ```
997
+ */
998
+ transaction(fn) {
999
+ if (typeof fn !== "function") {
1000
+ throw new TypeError("Expected first argument to be a function");
1001
+ }
1002
+ const db = this;
1003
+ const wrapTxn = (mode) => {
1004
+ return async (...bindParameters) => {
1005
+ await db.exec("BEGIN " + mode);
1006
+ db._inTransaction = true;
1007
+ try {
1008
+ const result = await fn(...bindParameters);
1009
+ await db.exec("COMMIT");
1010
+ db._inTransaction = false;
1011
+ return result;
1012
+ } catch (err) {
1013
+ await db.exec("ROLLBACK");
1014
+ db._inTransaction = false;
1015
+ throw err;
1016
+ }
1017
+ };
1018
+ };
1019
+ const properties = {
1020
+ default: { value: wrapTxn("") },
1021
+ deferred: { value: wrapTxn("DEFERRED") },
1022
+ immediate: { value: wrapTxn("IMMEDIATE") },
1023
+ exclusive: { value: wrapTxn("EXCLUSIVE") },
1024
+ database: { value: this, enumerable: true }
1025
+ };
1026
+ Object.defineProperties(properties.default.value, properties);
1027
+ Object.defineProperties(properties.deferred.value, properties);
1028
+ Object.defineProperties(properties.immediate.value, properties);
1029
+ Object.defineProperties(properties.exclusive.value, properties);
1030
+ return properties.default.value;
1031
+ }
1032
+ /**
1033
+ * Close the connection.
1034
+ *
1035
+ * This sends a close request to the server to properly clean up the stream.
1036
+ */
1037
+ async close() {
1038
+ this.isOpen = false;
1039
+ await this.session.close();
1040
+ }
1041
+ async reconnect() {
1042
+ try {
1043
+ if (this.isOpen) {
1044
+ await this.close();
1045
+ }
1046
+ } finally {
1047
+ this.session = new Session(this.config);
1048
+ this.isOpen = true;
1049
+ }
1050
+ }
1051
+ };
1052
+ function connect(config) {
1053
+ return new Connection(config);
1054
+ }
1055
+
1056
+ export { Connection, DatabaseError, ENCRYPTION_KEY_HEADER, Session, Statement, TimeoutError, connect };