@ducklings/browser 1.4.3-dev.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.
@@ -0,0 +1,1177 @@
1
+ import { Table } from '@uwdata/flechette';
2
+ export { Table } from '@uwdata/flechette';
3
+
4
+ /**
5
+ * Shared type definitions for Ducklings
6
+ * @packageDocumentation
7
+ */
8
+ /**
9
+ * DuckDB type constants mapping to the C API type IDs.
10
+ * @category Types
11
+ */
12
+ declare const DuckDBType: {
13
+ readonly INVALID: 0;
14
+ readonly BOOLEAN: 1;
15
+ readonly TINYINT: 2;
16
+ readonly SMALLINT: 3;
17
+ readonly INTEGER: 4;
18
+ readonly BIGINT: 5;
19
+ readonly UTINYINT: 6;
20
+ readonly USMALLINT: 7;
21
+ readonly UINTEGER: 8;
22
+ readonly UBIGINT: 9;
23
+ readonly FLOAT: 10;
24
+ readonly DOUBLE: 11;
25
+ readonly TIMESTAMP: 12;
26
+ readonly DATE: 13;
27
+ readonly TIME: 14;
28
+ readonly INTERVAL: 15;
29
+ readonly HUGEINT: 16;
30
+ readonly UHUGEINT: 32;
31
+ readonly VARCHAR: 17;
32
+ readonly BLOB: 18;
33
+ readonly DECIMAL: 19;
34
+ readonly TIMESTAMP_S: 20;
35
+ readonly TIMESTAMP_MS: 21;
36
+ readonly TIMESTAMP_NS: 22;
37
+ readonly ENUM: 23;
38
+ readonly LIST: 24;
39
+ readonly STRUCT: 25;
40
+ readonly MAP: 26;
41
+ readonly ARRAY: 33;
42
+ readonly UUID: 27;
43
+ readonly UNION: 28;
44
+ readonly BIT: 29;
45
+ readonly TIME_TZ: 30;
46
+ readonly TIMESTAMP_TZ: 31;
47
+ };
48
+ /**
49
+ * Type ID from DuckDB type constants.
50
+ * @category Types
51
+ */
52
+ type DuckDBTypeId = (typeof DuckDBType)[keyof typeof DuckDBType];
53
+ /**
54
+ * Database access mode.
55
+ * @category Configuration
56
+ */
57
+ declare enum AccessMode {
58
+ /** DuckDB determines mode based on context (resolves to READ_WRITE for in-memory) */
59
+ AUTOMATIC = "automatic",
60
+ /** Read-only mode - all write operations are blocked */
61
+ READ_ONLY = "read_only",
62
+ /** Read-write mode - allows both reads and writes */
63
+ READ_WRITE = "read_write"
64
+ }
65
+ /**
66
+ * DuckDB configuration options.
67
+ * @category Configuration
68
+ */
69
+ interface DuckDBConfig {
70
+ /**
71
+ * Database access mode.
72
+ * Use READ_ONLY to prevent any data modification.
73
+ * @default AccessMode.AUTOMATIC
74
+ */
75
+ accessMode?: AccessMode;
76
+ /**
77
+ * Enable external access (file I/O, httpfs, etc.).
78
+ * Set to false to prevent all external data access.
79
+ * WARNING: Setting to false will disable httpfs functionality.
80
+ * @default true
81
+ */
82
+ enableExternalAccess?: boolean;
83
+ /**
84
+ * Lock configuration after startup.
85
+ * Prevents runtime configuration changes via SQL SET commands.
86
+ * @default true (secure default)
87
+ */
88
+ lockConfiguration?: boolean;
89
+ /**
90
+ * Custom configuration options.
91
+ * Key-value pairs passed directly to duckdb_set_config.
92
+ * @see https://duckdb.org/docs/configuration/overview
93
+ */
94
+ customConfig?: Record<string, string>;
95
+ }
96
+ /**
97
+ * Column metadata for query results.
98
+ * @category Types
99
+ */
100
+ interface ColumnInfo {
101
+ /** Column name */
102
+ name: string;
103
+ /** DuckDB type ID */
104
+ type: DuckDBTypeId;
105
+ /** Type alias (e.g., "JSON" for aliased types) */
106
+ alias?: string;
107
+ }
108
+ /**
109
+ * Options for initializing the DuckDB WASM module.
110
+ * @category Types
111
+ */
112
+ interface InitOptions {
113
+ /**
114
+ * URL to the WASM file (for browser environments).
115
+ * If not provided, uses the default bundled WASM location.
116
+ */
117
+ wasmUrl?: string;
118
+ /**
119
+ * URL to the Emscripten JS file (duckdb.js).
120
+ * Required for proper bundler support.
121
+ */
122
+ wasmJsUrl?: string;
123
+ /**
124
+ * URL to the worker script (for browser environments).
125
+ * If not provided, uses the default bundled worker location.
126
+ */
127
+ workerUrl?: string;
128
+ /**
129
+ * Pre-created Worker instance.
130
+ * Use {@link createWorker} for CDN loading to work around cross-origin restrictions.
131
+ *
132
+ * @example
133
+ * ```typescript
134
+ * import { createWorker, getJsDelivrBundle, init } from '@ducklings/browser';
135
+ *
136
+ * const bundle = getJsDelivrBundle();
137
+ * const worker = await createWorker(bundle.mainWorker);
138
+ * await init({ worker, wasmUrl: bundle.wasmModule, wasmJsUrl: bundle.wasmJs });
139
+ * ```
140
+ */
141
+ worker?: Worker;
142
+ /**
143
+ * Pre-compiled WebAssembly.Module (for Cloudflare Workers).
144
+ * In Workers, import the WASM file directly and pass it here.
145
+ */
146
+ wasmModule?: WebAssembly.Module;
147
+ /**
148
+ * Whether to use the main thread instead of a Web Worker.
149
+ * Defaults to false (use Web Worker).
150
+ * Note: Main thread mode blocks the UI during operations.
151
+ */
152
+ useMainThread?: boolean;
153
+ /**
154
+ * DuckDB configuration options.
155
+ * Controls access mode, security settings, and custom configuration.
156
+ */
157
+ config?: DuckDBConfig;
158
+ }
159
+ /**
160
+ * File information returned by globFiles.
161
+ * @category Types
162
+ */
163
+ interface FileInfo {
164
+ /** File name/path */
165
+ name: string;
166
+ /** File size in bytes */
167
+ size: number;
168
+ }
169
+ /**
170
+ * Options for CSV insertion.
171
+ * @category Types
172
+ */
173
+ interface CSVInsertOptions {
174
+ /** Whether the CSV has a header row */
175
+ header?: boolean;
176
+ /** Column delimiter */
177
+ delimiter?: string;
178
+ /** Quote character */
179
+ quote?: string;
180
+ /** Escape character */
181
+ escape?: string;
182
+ /** Skip rows at start */
183
+ skip?: number;
184
+ /** Column names (if no header) */
185
+ columns?: string[];
186
+ }
187
+ /**
188
+ * Options for JSON insertion.
189
+ * @category Types
190
+ */
191
+ interface JSONInsertOptions {
192
+ /** JSON format: 'auto', 'records', 'values', or 'newline_delimited' */
193
+ format?: 'auto' | 'records' | 'values' | 'newline_delimited';
194
+ /** Column names */
195
+ columns?: string[];
196
+ }
197
+
198
+ /**
199
+ * Worker message protocol for Ducklings
200
+ * @packageDocumentation
201
+ */
202
+
203
+ /**
204
+ * Request types sent from main thread to worker.
205
+ */
206
+ declare enum WorkerRequestType {
207
+ PING = "PING",
208
+ INSTANTIATE = "INSTANTIATE",
209
+ GET_VERSION = "GET_VERSION",
210
+ OPEN = "OPEN",
211
+ CLOSE = "CLOSE",
212
+ CONNECT = "CONNECT",
213
+ DISCONNECT = "DISCONNECT",
214
+ QUERY = "QUERY",
215
+ QUERY_ARROW = "QUERY_ARROW",
216
+ QUERY_STREAMING = "QUERY_STREAMING",
217
+ EXECUTE = "EXECUTE",
218
+ FETCH_CHUNK = "FETCH_CHUNK",
219
+ CLOSE_STREAMING_RESULT = "CLOSE_STREAMING_RESULT",
220
+ RESET_STREAMING_RESULT = "RESET_STREAMING_RESULT",
221
+ PREPARE = "PREPARE",
222
+ RUN_PREPARED = "RUN_PREPARED",
223
+ EXECUTE_PREPARED = "EXECUTE_PREPARED",
224
+ CLOSE_PREPARED = "CLOSE_PREPARED",
225
+ BEGIN_TRANSACTION = "BEGIN_TRANSACTION",
226
+ COMMIT = "COMMIT",
227
+ ROLLBACK = "ROLLBACK",
228
+ REGISTER_FILE_URL = "REGISTER_FILE_URL",
229
+ REGISTER_FILE_BUFFER = "REGISTER_FILE_BUFFER",
230
+ REGISTER_FILE_HANDLE = "REGISTER_FILE_HANDLE",
231
+ REGISTER_FILE_TEXT = "REGISTER_FILE_TEXT",
232
+ DROP_FILE = "DROP_FILE",
233
+ DROP_FILES = "DROP_FILES",
234
+ FLUSH_FILES = "FLUSH_FILES",
235
+ COPY_FILE_TO_BUFFER = "COPY_FILE_TO_BUFFER",
236
+ COPY_FILE_TO_PATH = "COPY_FILE_TO_PATH",
237
+ GLOB_FILES = "GLOB_FILES",
238
+ INSERT_ARROW_FROM_IPC = "INSERT_ARROW_FROM_IPC",
239
+ INSERT_CSV_FROM_PATH = "INSERT_CSV_FROM_PATH",
240
+ INSERT_JSON_FROM_PATH = "INSERT_JSON_FROM_PATH"
241
+ }
242
+
243
+ /**
244
+ * Async Prepared Statement class
245
+ *
246
+ * @packageDocumentation
247
+ */
248
+
249
+ /**
250
+ * A prepared SQL statement with parameter binding.
251
+ *
252
+ * Prepared statements are more secure (prevent SQL injection) and can be
253
+ * more efficient when executing the same query multiple times with different parameters.
254
+ *
255
+ * Bind methods are synchronous (store locally), while run() and execute() are async
256
+ * (send to worker).
257
+ *
258
+ * @category Query Results
259
+ * @example
260
+ * ```typescript
261
+ * const stmt = await conn.prepare('SELECT * FROM users WHERE id = ? AND active = ?');
262
+ * stmt.bindInt32(1, userId);
263
+ * stmt.bindBoolean(2, true);
264
+ * const result = await stmt.run();
265
+ * await stmt.close();
266
+ * ```
267
+ */
268
+ declare class PreparedStatement {
269
+ private db;
270
+ private connectionId;
271
+ private preparedStatementId;
272
+ private closed;
273
+ private bindings;
274
+ /**
275
+ * @internal
276
+ */
277
+ constructor(db: DuckDB, connectionId: number, preparedStatementId: number, _sql: string);
278
+ private checkClosed;
279
+ /**
280
+ * Clear all parameter bindings.
281
+ */
282
+ clearBindings(): void;
283
+ /**
284
+ * Bind a NULL value to a parameter.
285
+ *
286
+ * @param index - 1-based parameter index
287
+ */
288
+ bindNull(index: number): void;
289
+ /**
290
+ * Bind a boolean value to a parameter.
291
+ *
292
+ * @param index - 1-based parameter index
293
+ * @param value - The boolean value
294
+ */
295
+ bindBoolean(index: number, value: boolean): void;
296
+ /**
297
+ * Bind an 8-bit signed integer to a parameter.
298
+ *
299
+ * @param index - 1-based parameter index
300
+ * @param value - The integer value (-128 to 127)
301
+ */
302
+ bindInt8(index: number, value: number): void;
303
+ /**
304
+ * Bind a 16-bit signed integer to a parameter.
305
+ *
306
+ * @param index - 1-based parameter index
307
+ * @param value - The integer value (-32768 to 32767)
308
+ */
309
+ bindInt16(index: number, value: number): void;
310
+ /**
311
+ * Bind a 32-bit signed integer to a parameter.
312
+ *
313
+ * @param index - 1-based parameter index
314
+ * @param value - The integer value
315
+ */
316
+ bindInt32(index: number, value: number): void;
317
+ /**
318
+ * Bind a 64-bit signed integer to a parameter.
319
+ *
320
+ * @param index - 1-based parameter index
321
+ * @param value - The integer value (BigInt or number)
322
+ */
323
+ bindInt64(index: number, value: bigint | number): void;
324
+ /**
325
+ * Bind an 8-bit unsigned integer to a parameter.
326
+ *
327
+ * @param index - 1-based parameter index
328
+ * @param value - The integer value (0 to 255)
329
+ */
330
+ bindUInt8(index: number, value: number): void;
331
+ /**
332
+ * Bind a 16-bit unsigned integer to a parameter.
333
+ *
334
+ * @param index - 1-based parameter index
335
+ * @param value - The integer value (0 to 65535)
336
+ */
337
+ bindUInt16(index: number, value: number): void;
338
+ /**
339
+ * Bind a 32-bit unsigned integer to a parameter.
340
+ *
341
+ * @param index - 1-based parameter index
342
+ * @param value - The integer value
343
+ */
344
+ bindUInt32(index: number, value: number): void;
345
+ /**
346
+ * Bind a 64-bit unsigned integer to a parameter.
347
+ *
348
+ * @param index - 1-based parameter index
349
+ * @param value - The integer value (BigInt or number)
350
+ */
351
+ bindUInt64(index: number, value: bigint | number): void;
352
+ /**
353
+ * Bind a 32-bit float to a parameter.
354
+ *
355
+ * @param index - 1-based parameter index
356
+ * @param value - The float value
357
+ */
358
+ bindFloat(index: number, value: number): void;
359
+ /**
360
+ * Bind a 64-bit double to a parameter.
361
+ *
362
+ * @param index - 1-based parameter index
363
+ * @param value - The double value
364
+ */
365
+ bindDouble(index: number, value: number): void;
366
+ /**
367
+ * Bind a string value to a parameter.
368
+ *
369
+ * @param index - 1-based parameter index
370
+ * @param value - The string value
371
+ */
372
+ bindVarchar(index: number, value: string): void;
373
+ /**
374
+ * Bind a blob (binary) value to a parameter.
375
+ *
376
+ * @param index - 1-based parameter index
377
+ * @param value - The binary data
378
+ */
379
+ bindBlob(index: number, value: Uint8Array): void;
380
+ /**
381
+ * Execute the prepared statement and return results.
382
+ *
383
+ * @returns Promise resolving to array of result rows as objects
384
+ *
385
+ * @example
386
+ * ```typescript
387
+ * const stmt = await conn.prepare('SELECT * FROM users WHERE id = ?');
388
+ * stmt.bindInt32(1, 42);
389
+ * const rows = await stmt.run();
390
+ * ```
391
+ */
392
+ run<T = Record<string, unknown>>(): Promise<T[]>;
393
+ /**
394
+ * Execute the prepared statement and return the number of affected rows.
395
+ *
396
+ * Use this for INSERT, UPDATE, DELETE statements.
397
+ *
398
+ * @returns Promise resolving to the number of rows affected
399
+ *
400
+ * @example
401
+ * ```typescript
402
+ * const stmt = await conn.prepare('DELETE FROM users WHERE id = ?');
403
+ * stmt.bindInt32(1, 42);
404
+ * const deleted = await stmt.execute();
405
+ * ```
406
+ */
407
+ execute(): Promise<number>;
408
+ /**
409
+ * Close the prepared statement and release resources.
410
+ */
411
+ close(): Promise<void>;
412
+ }
413
+
414
+ /**
415
+ * Data Chunk class
416
+ *
417
+ * @packageDocumentation
418
+ */
419
+
420
+ /**
421
+ * A chunk of data from a streaming query result.
422
+ *
423
+ * DataChunks contain a fixed number of rows and provide methods to
424
+ * access the data in various formats.
425
+ *
426
+ * @category Query Results
427
+ * @example
428
+ * ```typescript
429
+ * for await (const chunk of stream) {
430
+ * console.log(`Chunk has ${chunk.rowCount} rows`);
431
+ *
432
+ * // Get as array of objects
433
+ * for (const row of chunk.toArray()) {
434
+ * console.log(row);
435
+ * }
436
+ *
437
+ * // Or access raw columnar data
438
+ * const column = chunk.getColumn(0);
439
+ * console.log(column);
440
+ * }
441
+ * ```
442
+ */
443
+ declare class DataChunk {
444
+ private columns;
445
+ private rows;
446
+ private _rowCount;
447
+ /**
448
+ * @internal
449
+ */
450
+ constructor(columns: ColumnInfo[], rows: unknown[][], rowCount: number);
451
+ /**
452
+ * Get the number of rows in this chunk.
453
+ */
454
+ get rowCount(): number;
455
+ /**
456
+ * Get the number of columns.
457
+ */
458
+ get columnCount(): number;
459
+ /**
460
+ * Get the column information.
461
+ */
462
+ getColumns(): ColumnInfo[];
463
+ /**
464
+ * Get the raw row data.
465
+ *
466
+ * Each row is an array of values in column order.
467
+ */
468
+ getRows(): unknown[][];
469
+ /**
470
+ * Get a single column's values.
471
+ *
472
+ * @param index - The 0-based column index
473
+ * @returns Array of values for that column
474
+ */
475
+ getColumn(index: number): unknown[];
476
+ /**
477
+ * Get a single column's values by name.
478
+ *
479
+ * @param name - The column name
480
+ * @returns Array of values for that column
481
+ */
482
+ getColumnByName(name: string): unknown[];
483
+ /**
484
+ * Get a single row.
485
+ *
486
+ * @param index - The 0-based row index
487
+ * @returns The row as an array of values
488
+ */
489
+ getRow(index: number): unknown[];
490
+ /**
491
+ * Get a single row as an object.
492
+ *
493
+ * @param index - The 0-based row index
494
+ * @returns The row as an object with column names as keys
495
+ */
496
+ getRowObject<T = Record<string, unknown>>(index: number): T;
497
+ /**
498
+ * Convert all rows to an array of objects.
499
+ *
500
+ * @returns Array of row objects with column names as keys
501
+ */
502
+ toArray<T = Record<string, unknown>>(): T[];
503
+ /**
504
+ * Iterate over rows as objects.
505
+ */
506
+ [Symbol.iterator](): Iterator<Record<string, unknown>>;
507
+ }
508
+
509
+ /**
510
+ * Async Streaming Result class
511
+ *
512
+ * @packageDocumentation
513
+ */
514
+
515
+ /**
516
+ * An async streaming query result.
517
+ *
518
+ * This class allows you to process large result sets in chunks,
519
+ * which is more memory-efficient than loading everything at once.
520
+ *
521
+ * Implements AsyncIterable for use with `for await...of`.
522
+ *
523
+ * @category Query Results
524
+ * @example
525
+ * ```typescript
526
+ * const stream = await conn.queryStreaming('SELECT * FROM large_table');
527
+ *
528
+ * // Using for await...of
529
+ * for await (const chunk of stream) {
530
+ * console.log(`Processing ${chunk.rowCount} rows`);
531
+ * for (const row of chunk.toArray()) {
532
+ * processRow(row);
533
+ * }
534
+ * }
535
+ *
536
+ * // Or manually
537
+ * let chunk;
538
+ * while ((chunk = await stream.nextChunk()) !== null) {
539
+ * console.log(chunk.rowCount);
540
+ * }
541
+ *
542
+ * await stream.close();
543
+ * ```
544
+ */
545
+ declare class AsyncStreamingResult implements AsyncIterable<DataChunk> {
546
+ private db;
547
+ private connectionId;
548
+ private streamingResultId;
549
+ private columns;
550
+ private closed;
551
+ private done;
552
+ /**
553
+ * @internal
554
+ */
555
+ constructor(db: DuckDB, connectionId: number, streamingResultId: number, columns: ColumnInfo[]);
556
+ /**
557
+ * Get the column information for this result.
558
+ */
559
+ getColumns(): ColumnInfo[];
560
+ /**
561
+ * Check if the result has been fully consumed.
562
+ */
563
+ isDone(): boolean;
564
+ /**
565
+ * Check if the result is closed.
566
+ */
567
+ isClosed(): boolean;
568
+ private checkClosed;
569
+ /**
570
+ * Fetch the next chunk of data.
571
+ *
572
+ * @returns Promise resolving to the next DataChunk, or null if no more data
573
+ */
574
+ nextChunk(): Promise<DataChunk | null>;
575
+ /**
576
+ * Collect all remaining chunks into an array of objects.
577
+ *
578
+ * Warning: This loads all data into memory. Use nextChunk() or
579
+ * for await...of for large result sets.
580
+ *
581
+ * @returns Promise resolving to array of all result rows
582
+ */
583
+ toArray<T = Record<string, unknown>>(): Promise<T[]>;
584
+ /**
585
+ * Collect all remaining chunks into an Arrow Table.
586
+ *
587
+ * Warning: This loads all data into memory.
588
+ *
589
+ * @returns Promise resolving to Arrow Table with all results
590
+ */
591
+ toArrowTable(): Promise<Table>;
592
+ /**
593
+ * Close the streaming result and release resources.
594
+ */
595
+ close(): Promise<void>;
596
+ /**
597
+ * Returns an async iterator for this streaming result.
598
+ */
599
+ [Symbol.asyncIterator](): AsyncIterator<DataChunk>;
600
+ }
601
+
602
+ /**
603
+ * Async Connection class
604
+ *
605
+ * @packageDocumentation
606
+ */
607
+
608
+ /**
609
+ * A connection to a DuckDB database.
610
+ *
611
+ * Connections are used to execute queries and manage transactions.
612
+ * All operations are async as they communicate with a Web Worker.
613
+ *
614
+ * @category Connection
615
+ * @example
616
+ * ```typescript
617
+ * const conn = await db.connect();
618
+ *
619
+ * // Query returns array of objects
620
+ * const rows = await conn.query('SELECT * FROM range(10)');
621
+ *
622
+ * // Query returns Arrow Table
623
+ * const table = await conn.queryArrow('SELECT * FROM range(1000)');
624
+ *
625
+ * // Streaming for large results
626
+ * const stream = await conn.queryStreaming('SELECT * FROM large_table');
627
+ * for await (const chunk of stream) {
628
+ * console.log(chunk.rowCount);
629
+ * }
630
+ *
631
+ * await conn.close();
632
+ * ```
633
+ */
634
+ declare class Connection {
635
+ private db;
636
+ private connectionId;
637
+ private closed;
638
+ /**
639
+ * @internal
640
+ */
641
+ constructor(db: DuckDB, connectionId: number);
642
+ /**
643
+ * Get the connection ID.
644
+ * @internal
645
+ */
646
+ getConnectionId(): number;
647
+ /**
648
+ * Get the database instance.
649
+ * @internal
650
+ */
651
+ getDB(): DuckDB;
652
+ private checkClosed;
653
+ /**
654
+ * Executes a SQL query and returns the results as an array of objects.
655
+ *
656
+ * @param sql - The SQL query to execute
657
+ * @returns Promise resolving to array of result rows as objects
658
+ *
659
+ * @example
660
+ * ```typescript
661
+ * const rows = await conn.query<{ id: number; name: string }>(
662
+ * 'SELECT * FROM users WHERE active = true'
663
+ * );
664
+ * for (const row of rows) {
665
+ * console.log(row.id, row.name);
666
+ * }
667
+ * ```
668
+ */
669
+ query<T = Record<string, unknown>>(sql: string): Promise<T[]>;
670
+ /**
671
+ * Executes a SQL query and returns results as a Flechette Arrow Table.
672
+ *
673
+ * This method is more efficient for large result sets and provides
674
+ * proper Arrow/columnar data representation.
675
+ *
676
+ * @param sql - The SQL query to execute
677
+ * @returns Promise resolving to Arrow Table with query results
678
+ *
679
+ * @example
680
+ * ```typescript
681
+ * const table = await conn.queryArrow('SELECT * FROM range(1000000)');
682
+ * console.log(table.numRows);
683
+ * ```
684
+ */
685
+ queryArrow(sql: string): Promise<Table>;
686
+ /**
687
+ * Executes a SQL query and returns a streaming result.
688
+ *
689
+ * This method is more memory-efficient for large result sets as it
690
+ * processes data in chunks rather than loading everything at once.
691
+ *
692
+ * @param sql - The SQL query to execute
693
+ * @returns Promise resolving to AsyncStreamingResult that can be iterated over
694
+ *
695
+ * @example
696
+ * ```typescript
697
+ * const stream = await conn.queryStreaming('SELECT * FROM large_table');
698
+ * for await (const chunk of stream) {
699
+ * console.log(`Processing ${chunk.rowCount} rows`);
700
+ * for (const row of chunk.toArray()) {
701
+ * processRow(row);
702
+ * }
703
+ * }
704
+ * await stream.close();
705
+ * ```
706
+ */
707
+ queryStreaming(sql: string): Promise<AsyncStreamingResult>;
708
+ /**
709
+ * Executes a SQL statement and returns the number of affected rows.
710
+ *
711
+ * Use this for INSERT, UPDATE, DELETE, or other statements where you
712
+ * don't need to read result rows.
713
+ *
714
+ * @param sql - The SQL statement to execute
715
+ * @returns Promise resolving to the number of rows affected
716
+ *
717
+ * @example
718
+ * ```typescript
719
+ * const deleted = await conn.execute('DELETE FROM users WHERE inactive = true');
720
+ * console.log(`Deleted ${deleted} users`);
721
+ * ```
722
+ */
723
+ execute(sql: string): Promise<number>;
724
+ /**
725
+ * Prepares a SQL statement for execution.
726
+ *
727
+ * Prepared statements are more secure (prevent SQL injection) and can be
728
+ * more efficient when executing the same query multiple times with different parameters.
729
+ *
730
+ * @param sql - The SQL statement with parameter placeholders (?)
731
+ * @returns Promise resolving to a PreparedStatement instance
732
+ *
733
+ * @example
734
+ * ```typescript
735
+ * const stmt = await conn.prepare('SELECT * FROM users WHERE id = ?');
736
+ * stmt.bindInt32(1, 42);
737
+ * const rows = await stmt.run();
738
+ * await stmt.close();
739
+ * ```
740
+ */
741
+ prepare(sql: string): Promise<PreparedStatement>;
742
+ /**
743
+ * Begins a new transaction.
744
+ *
745
+ * @example
746
+ * ```typescript
747
+ * await conn.beginTransaction();
748
+ * try {
749
+ * await conn.execute('INSERT INTO users (name) VALUES ($1)', ['Alice']);
750
+ * await conn.execute('UPDATE balances SET amount = amount - 100 WHERE user = $1', ['Alice']);
751
+ * await conn.commit();
752
+ * } catch (e) {
753
+ * await conn.rollback();
754
+ * throw e;
755
+ * }
756
+ * ```
757
+ */
758
+ beginTransaction(): Promise<void>;
759
+ /**
760
+ * Commits the current transaction.
761
+ */
762
+ commit(): Promise<void>;
763
+ /**
764
+ * Rolls back the current transaction.
765
+ */
766
+ rollback(): Promise<void>;
767
+ /**
768
+ * Execute a function within a transaction.
769
+ *
770
+ * The transaction is automatically committed on success or rolled back on error.
771
+ *
772
+ * @param fn - The function to execute within the transaction
773
+ * @returns Promise resolving to the function's return value
774
+ *
775
+ * @example
776
+ * ```typescript
777
+ * const result = await conn.transaction(async () => {
778
+ * await conn.execute('INSERT INTO users (name) VALUES ($1)', ['Alice']);
779
+ * return await conn.query('SELECT * FROM users WHERE name = $1', ['Alice']);
780
+ * });
781
+ * ```
782
+ */
783
+ transaction<T>(fn: () => Promise<T>): Promise<T>;
784
+ /**
785
+ * Insert data from an Arrow IPC buffer.
786
+ *
787
+ * @param tableName - The name of the table to insert into
788
+ * @param ipcBuffer - The Arrow IPC buffer containing the data
789
+ *
790
+ * @example
791
+ * ```typescript
792
+ * import { tableToIPC } from '@uwdata/flechette';
793
+ * const ipcBuffer = tableToIPC(myArrowTable);
794
+ * await conn.insertArrowFromIPCStream('my_table', ipcBuffer);
795
+ * ```
796
+ */
797
+ insertArrowFromIPCStream(tableName: string, ipcBuffer: Uint8Array): Promise<void>;
798
+ /**
799
+ * Insert data from a CSV file.
800
+ *
801
+ * @param tableName - The name of the table to insert into
802
+ * @param path - The virtual file path of the CSV
803
+ * @param options - Optional CSV parsing options
804
+ *
805
+ * @example
806
+ * ```typescript
807
+ * await db.registerFileBuffer('data.csv', csvData);
808
+ * await conn.insertCSVFromPath('my_table', 'data.csv', { header: true });
809
+ * ```
810
+ */
811
+ insertCSVFromPath(tableName: string, path: string, options?: CSVInsertOptions): Promise<void>;
812
+ /**
813
+ * Insert data from a JSON file.
814
+ *
815
+ * @param tableName - The name of the table to insert into
816
+ * @param path - The virtual file path of the JSON
817
+ * @param options - Optional JSON parsing options
818
+ *
819
+ * @example
820
+ * ```typescript
821
+ * await db.registerFileBuffer('data.json', jsonData);
822
+ * await conn.insertJSONFromPath('my_table', 'data.json');
823
+ * ```
824
+ */
825
+ insertJSONFromPath(tableName: string, path: string, options?: JSONInsertOptions): Promise<void>;
826
+ /**
827
+ * Closes the connection and releases resources.
828
+ */
829
+ close(): Promise<void>;
830
+ }
831
+
832
+ /**
833
+ * Async DuckDB bindings for the main thread
834
+ *
835
+ * @packageDocumentation
836
+ */
837
+
838
+ /**
839
+ * Initialize the DuckDB WASM module.
840
+ *
841
+ * This function must be called before creating any DuckDB instances.
842
+ * It spawns a Web Worker and initializes the WebAssembly module inside it.
843
+ *
844
+ * URLs for worker, WASM, and JS files are automatically resolved from the
845
+ * library location. You can override them if needed.
846
+ *
847
+ * @category Database
848
+ * @param options - Optional initialization options
849
+ * @returns Promise that resolves when initialization is complete
850
+ *
851
+ * @example
852
+ * ```typescript
853
+ * import { init, DuckDB } from '@ducklings/browser';
854
+ *
855
+ * await init();
856
+ * const db = new DuckDB();
857
+ * const conn = await db.connect();
858
+ *
859
+ * const rows = await conn.query('SELECT 42 as answer');
860
+ * console.log(rows);
861
+ *
862
+ * await conn.close();
863
+ * await db.close();
864
+ * ```
865
+ */
866
+ declare function init(options?: string | InitOptions): Promise<void>;
867
+ /**
868
+ * Returns the DuckDB library version.
869
+ *
870
+ * @category Database
871
+ * @returns Promise resolving to version string
872
+ * @throws DuckDBError if WASM module is not initialized
873
+ */
874
+ declare function version(): Promise<string>;
875
+ /**
876
+ * Get the global DuckDB instance.
877
+ *
878
+ * @category Database
879
+ * @returns The global DuckDB instance
880
+ * @throws DuckDBError if not initialized
881
+ */
882
+ declare function getDB(): DuckDB;
883
+ /**
884
+ * DuckDB database instance.
885
+ *
886
+ * This is the main entry point for using DuckDB in WASM.
887
+ * Create a database instance, then create connections to execute queries.
888
+ *
889
+ * @category Database
890
+ * @example
891
+ * ```typescript
892
+ * import { init, DuckDB } from '@ducklings/browser';
893
+ *
894
+ * await init();
895
+ *
896
+ * const db = new DuckDB();
897
+ * const conn = await db.connect();
898
+ *
899
+ * const result = await conn.query('SELECT 42 as answer');
900
+ * console.log(result);
901
+ *
902
+ * await conn.close();
903
+ * await db.close();
904
+ * ```
905
+ */
906
+ declare class DuckDB {
907
+ private worker;
908
+ private pendingRequests;
909
+ private nextMessageId;
910
+ private closed;
911
+ /**
912
+ * Creates a new DuckDB instance.
913
+ *
914
+ * @param worker - The Web Worker to use for DuckDB operations
915
+ * @internal Use init() instead of creating directly
916
+ */
917
+ constructor(worker?: Worker);
918
+ private setupMessageHandler;
919
+ /**
920
+ * Post a request to the worker and return a promise for the response.
921
+ *
922
+ * @internal
923
+ */
924
+ postTask<T>(type: WorkerRequestType, data?: unknown, transfer?: Transferable[]): Promise<T>;
925
+ /**
926
+ * Instantiate the WASM module in the worker.
927
+ *
928
+ * @internal
929
+ */
930
+ instantiate(wasmUrl?: string, wasmJsUrl?: string): Promise<void>;
931
+ /**
932
+ * Open the database.
933
+ *
934
+ * @param config - Optional configuration options
935
+ * @internal
936
+ */
937
+ open(config?: DuckDBConfig): Promise<void>;
938
+ /**
939
+ * Get the DuckDB library version.
940
+ */
941
+ getVersion(): Promise<string>;
942
+ /**
943
+ * Creates a new connection to this database.
944
+ *
945
+ * Multiple connections can be created to the same database.
946
+ * Each connection maintains its own transaction state.
947
+ *
948
+ * @returns Promise resolving to a new Connection instance
949
+ */
950
+ connect(): Promise<Connection>;
951
+ /**
952
+ * Creates a new DuckDB database and initializes the WASM module if needed.
953
+ *
954
+ * This is a convenience method that combines init() and connect().
955
+ *
956
+ * @returns Promise that resolves to a new Connection instance
957
+ *
958
+ * @example
959
+ * ```typescript
960
+ * const conn = await DuckDB.createConnection();
961
+ * const rows = await conn.query('SELECT 42 as answer');
962
+ * ```
963
+ */
964
+ static createConnection(): Promise<Connection>;
965
+ /**
966
+ * Register a remote file by URL.
967
+ *
968
+ * @param name - The virtual file name to use
969
+ * @param url - The URL to fetch the file from
970
+ * @param protocol - Optional protocol hint ('HTTP' or 'HTTPS')
971
+ * @param directIO - Whether to use direct I/O
972
+ *
973
+ * @example
974
+ * ```typescript
975
+ * await db.registerFileURL('data.parquet', 'https://example.com/data.parquet');
976
+ * const rows = await conn.query("SELECT * FROM 'data.parquet'");
977
+ * ```
978
+ */
979
+ registerFileURL(name: string, url: string, protocol?: string, directIO?: boolean): Promise<void>;
980
+ /**
981
+ * Register an in-memory buffer as a virtual file.
982
+ *
983
+ * @param name - The virtual file name to use
984
+ * @param buffer - The file contents
985
+ *
986
+ * @example
987
+ * ```typescript
988
+ * const csvData = new TextEncoder().encode('id,name\n1,Alice\n2,Bob');
989
+ * await db.registerFileBuffer('data.csv', csvData);
990
+ * const rows = await conn.query("SELECT * FROM read_csv('/data.csv')");
991
+ * ```
992
+ */
993
+ registerFileBuffer(name: string, buffer: Uint8Array): Promise<void>;
994
+ /**
995
+ * Register a text string as a virtual file.
996
+ *
997
+ * @param name - The virtual file name to use
998
+ * @param text - The file contents as a string
999
+ */
1000
+ registerFileText(name: string, text: string): Promise<void>;
1001
+ /**
1002
+ * Remove a registered file.
1003
+ *
1004
+ * @param name - The virtual file name to remove
1005
+ */
1006
+ dropFile(name: string): Promise<void>;
1007
+ /**
1008
+ * Remove all registered files.
1009
+ */
1010
+ dropFiles(): Promise<void>;
1011
+ /**
1012
+ * Flush all file buffers.
1013
+ */
1014
+ flushFiles(): Promise<void>;
1015
+ /**
1016
+ * Export a file to a buffer.
1017
+ *
1018
+ * @param name - The virtual file name to export
1019
+ * @returns The file contents
1020
+ */
1021
+ copyFileToBuffer(name: string): Promise<Uint8Array>;
1022
+ /**
1023
+ * Copy a file to another path.
1024
+ *
1025
+ * @param srcName - The source file name
1026
+ * @param dstPath - The destination path
1027
+ */
1028
+ copyFileToPath(srcName: string, dstPath: string): Promise<void>;
1029
+ /**
1030
+ * List files matching a glob pattern.
1031
+ *
1032
+ * @param pattern - The glob pattern to match
1033
+ * @returns List of matching files
1034
+ */
1035
+ globFiles(pattern: string): Promise<FileInfo[]>;
1036
+ /**
1037
+ * Closes the database and releases all resources.
1038
+ */
1039
+ close(): Promise<void>;
1040
+ }
1041
+
1042
+ /**
1043
+ * CDN utilities for loading DuckDB from CDNs like jsDelivr
1044
+ *
1045
+ * When loading the library from a CDN, browsers block cross-origin Worker creation.
1046
+ * Use {@link createWorker} to work around this limitation.
1047
+ *
1048
+ * @packageDocumentation
1049
+ */
1050
+ /**
1051
+ * Bundle URLs for loading from CDN
1052
+ *
1053
+ * @category CDN
1054
+ */
1055
+ interface DuckDBBundle {
1056
+ /** URL to the main library entry point */
1057
+ mainModule: string;
1058
+ /** URL to the worker script */
1059
+ mainWorker: string;
1060
+ /** URL to the WASM binary */
1061
+ wasmModule: string;
1062
+ /** URL to the Emscripten JS glue */
1063
+ wasmJs: string;
1064
+ }
1065
+ /**
1066
+ * Get pre-configured bundle URLs for loading from jsDelivr CDN
1067
+ *
1068
+ * @category CDN
1069
+ * @param version - Optional version to use (defaults to current package version)
1070
+ * @returns Bundle URLs for jsDelivr
1071
+ *
1072
+ * @example
1073
+ * ```typescript
1074
+ * import { getJsDelivrBundle, createWorker, init } from '@ducklings/browser';
1075
+ *
1076
+ * const bundle = getJsDelivrBundle();
1077
+ * const worker = await createWorker(bundle.mainWorker);
1078
+ *
1079
+ * await init({
1080
+ * worker,
1081
+ * wasmUrl: bundle.wasmModule,
1082
+ * wasmJsUrl: bundle.wasmJs,
1083
+ * });
1084
+ * ```
1085
+ */
1086
+ declare function getJsDelivrBundle(version?: string): DuckDBBundle;
1087
+ /**
1088
+ * Get pre-configured bundle URLs for loading from unpkg CDN
1089
+ *
1090
+ * @category CDN
1091
+ * @param version - Optional version to use (defaults to current package version)
1092
+ * @returns Bundle URLs for unpkg
1093
+ */
1094
+ declare function getUnpkgBundle(version?: string): DuckDBBundle;
1095
+ /**
1096
+ * Create a Worker from a cross-origin URL using Blob URL workaround.
1097
+ *
1098
+ * Browsers block creating Workers from cross-origin scripts (like those served from CDNs).
1099
+ * This function fetches the worker script and creates a same-origin Blob URL from it.
1100
+ *
1101
+ * @category CDN
1102
+ * @param url - URL to the worker script (can be cross-origin)
1103
+ * @returns Promise resolving to a same-origin Worker
1104
+ *
1105
+ * @example
1106
+ * ```typescript
1107
+ * import { createWorker, getJsDelivrBundle, init } from '@ducklings/browser';
1108
+ *
1109
+ * const bundle = getJsDelivrBundle();
1110
+ * const worker = await createWorker(bundle.mainWorker);
1111
+ *
1112
+ * await init({ worker });
1113
+ * ```
1114
+ */
1115
+ declare function createWorker(url: string): Promise<Worker>;
1116
+
1117
+ /**
1118
+ * Error handling for Ducklings
1119
+ * @packageDocumentation
1120
+ */
1121
+ /**
1122
+ * Error thrown by DuckDB operations.
1123
+ *
1124
+ * This error is thrown when DuckDB encounters an error during query execution,
1125
+ * connection management, or other database operations.
1126
+ *
1127
+ * @example
1128
+ * ```typescript
1129
+ * try {
1130
+ * await conn.query('SELECT * FROM nonexistent_table');
1131
+ * } catch (e) {
1132
+ * if (e instanceof DuckDBError) {
1133
+ * console.error('DuckDB error:', e.message);
1134
+ * console.error('Query:', e.query);
1135
+ * }
1136
+ * }
1137
+ * ```
1138
+ */
1139
+ declare class DuckDBError extends Error {
1140
+ /** Error code if available */
1141
+ readonly code?: string;
1142
+ /** The SQL query that caused the error */
1143
+ readonly query?: string;
1144
+ constructor(message: string, code?: string, query?: string);
1145
+ /**
1146
+ * Create a DuckDBError from a plain object (for worker message deserialization).
1147
+ * @internal
1148
+ */
1149
+ static fromObject(obj: {
1150
+ message: string;
1151
+ code?: string;
1152
+ query?: string;
1153
+ }): DuckDBError;
1154
+ /**
1155
+ * Convert to a plain object for worker message serialization.
1156
+ * @internal
1157
+ */
1158
+ toObject(): {
1159
+ message: string;
1160
+ code?: string;
1161
+ query?: string;
1162
+ };
1163
+ }
1164
+
1165
+ /**
1166
+ * Package version constants
1167
+ *
1168
+ * These are injected at build time via tsup's define option.
1169
+ *
1170
+ * @packageDocumentation
1171
+ */
1172
+ /** Package name for CDN URL generation */
1173
+ declare const PACKAGE_NAME: string;
1174
+ /** Package version for CDN URL generation */
1175
+ declare const PACKAGE_VERSION: string;
1176
+
1177
+ export { AccessMode, type CSVInsertOptions, type ColumnInfo, Connection, DataChunk, DuckDB, type DuckDBBundle, type DuckDBConfig, DuckDBError, DuckDBType, type DuckDBTypeId, type FileInfo, type InitOptions, type JSONInsertOptions, PACKAGE_NAME, PACKAGE_VERSION, PreparedStatement, AsyncStreamingResult as StreamingResult, createWorker, getDB, getJsDelivrBundle, getUnpkgBundle, init, version };