@haybarn/haybarn-wasm 2.0.0-rc6 → 2.0.0-rc7

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../web-worker/cjs/browser.js", "../src/targets/duckdb.ts", "../src/bindings/config.ts", "../src/bindings/tokens.ts", "../src/log.ts", "../src/status.ts", "../src/parallel/async_connection.ts", "../src/parallel/worker_request.ts", "../src/bindings/interrupt.ts", "../src/json_typedef.ts", "../src/utils/opfs_util.ts", "../src/parallel/async_bindings.ts", "../src/bindings/runtime.ts", "../src/parallel/extension_prefetch.ts", "../src/parallel/worker_dispatcher.ts", "../../wasm-feature-detect/dist/esm/index.js", "../package.json", "../src/version.ts", "../src/platform.ts", "../src/worker.ts"],
4
- "sourcesContent": ["/**\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nmodule.exports = Worker;", "export * from '../bindings/config';\nexport * from '../bindings/tokens';\nexport * from '../log';\nexport * from '../status';\nexport * from '../parallel';\nexport * from '../platform';\nexport * from '../version';\nexport * from '../worker';\n\nexport { InstantiationProgress, InstantiationProgressHandler, DuckDBDataProtocol, WebFile } from '../bindings';\n", "export interface DuckDBQueryConfig {\n /**\n * The polling interval for queries\n */\n queryPollingInterval?: number;\n /**\n * Cast BigInt to Double?\n */\n castBigIntToDouble?: boolean;\n /**\n * Cast Timestamp to Date64?\n */\n castTimestampToDate?: boolean;\n /**\n * Cast Timestamp to Date64?\n */\n castDurationToTime64?: boolean;\n /**\n * Cast Decimal to Double?\n */\n castDecimalToDouble?: boolean;\n}\n\nexport interface DuckDBFilesystemConfig {\n reliableHeadRequests?: boolean;\n /**\n * Allow falling back to full HTTP reads if the server does not support range requests.\n */\n allowFullHTTPReads?: boolean;\n /**\n * Force use of full HTTP reads, suppressing range requests.\n */\n forceFullHTTPReads?: boolean;\n}\n\nexport interface DuckDBOPFSConfig {\n /**\n * Defines how `opfs://` files are handled during SQL execution.\n * - \"auto\": Automatically register `opfs://` files and drop them after execution.\n * - \"manual\": Files must be manually registered and dropped.\n */\n fileHandling?: \"auto\" | \"manual\";\n}\n\nexport enum DuckDBAccessMode {\n UNDEFINED = 0,\n AUTOMATIC = 1,\n READ_ONLY = 2,\n READ_WRITE = 3,\n}\n\nexport interface DuckDBConfig {\n /**\n * The database path\n */\n path?: string;\n /**\n * The access mode\n */\n accessMode?: DuckDBAccessMode;\n /**\n * Spill data that does not fit in memory to the temporary directory, js_buffer://tmp by default:\n * buffers held by the runtime outside the WASM heap. Enabled unless set to false.\n */\n spill?: boolean;\n /**\n * The temporary directory of DuckDB, overrides the default of the runtime\n */\n temporaryDirectory?: string;\n /**\n * The home directory of DuckDB, opfs://home where the browser has an origin private file system: what DuckDB\n * stores next to the user (persistent secrets) persists across sessions\n */\n homeDirectory?: string;\n /**\n * The repository extensions are loaded from (custom_extension_repository), the Haybarn core repository\n * (haybarn-extensions.query.farm/core) by default\n */\n extensionRepository?: string;\n /**\n * The maximum number of threads.\n * Note that this will only work with cross-origin isolated sites since it requires SharedArrayBuffers.\n */\n maximumThreads?: number;\n /**\n * The direct io flag\n */\n useDirectIO?: boolean;\n /**\n * The query config\n */\n query?: DuckDBQueryConfig;\n /**\n * The filesystem config\n */\n filesystem?: DuckDBFilesystemConfig;\n /**\n * Whether to allow unsigned extensions\n */\n allowUnsignedExtensions?: boolean;\n /**\n * Whether to use alternate Arrow conversion that preserves full range and precision of data.\n */\n arrowLosslessConversion?: boolean;\n /**\n * Custom user agent string\n */\n customUserAgent?: string;\n /**\n * opfs string\n */\n opfs?: DuckDBOPFSConfig;\n /**\n * Haybarn: run extension `LOAD`/`INSTALL` statements with the task scheduler pinned to a single thread.\n *\n * When enabled, the bindings bracket each statement that starts with `LOAD`/`INSTALL` with `SET threads=1` ...\n * `SET threads=<previous>`. It was the workaround for an intermittent deadlock of extension loads on the threads\n * bundle: the query thread spun while a scheduler thread ran the load, so it never synced the side module the\n * main thread opened. The engine now waits instead of spinning (`wait_for_tasks_instead_of_spinning.patch`), and\n * loads, autoloads inside queries included, no longer need the bracket.\n *\n * Defaults to disabled. A no-op on the base bundle and whenever `threads` is already 1.\n */\n singleThreadedExtensionLoad?: boolean;\n}\n", "export enum TokenType {\n IDENTIFIER = 0,\n NUMERIC_CONSTANT = 1,\n STRING_CONSTANT = 2,\n OPERATOR = 3,\n KEYWORD = 4,\n COMMENT = 5,\n}\n\nexport interface ScriptTokens {\n offsets: number[];\n types: TokenType[];\n}\n", "export enum LogLevel {\n NONE = 0,\n DEBUG = 1,\n INFO = 2,\n WARNING = 3,\n ERROR = 4,\n}\n\nexport enum LogTopic {\n NONE = 0,\n CONNECT = 1,\n DISCONNECT = 2,\n OPEN = 3,\n QUERY = 4,\n INSTANTIATE = 5,\n FILESYSTEM = 6,\n}\n\nexport enum LogEvent {\n NONE = 0,\n OK = 1,\n ERROR = 2,\n START = 3,\n RUN = 4,\n CAPTURE = 5,\n}\n\nexport enum LogOrigin {\n NONE = 0,\n WEB_WORKER = 1,\n NODE_WORKER = 2,\n BINDINGS = 3,\n ASYNC_DUCKDB = 4,\n}\n\nexport type LogEntry<O, T, E, V> = {\n readonly timestamp: Date;\n readonly level: LogLevel;\n readonly origin: O;\n readonly topic: T;\n readonly event: E;\n readonly value: V;\n};\n\nexport type ProgressEntry = {\n readonly status: string;\n readonly percentage: string;\n readonly repetitions: string;\n};\n\n/** An execution progress handler */\nexport type ExecutionProgressHandler = (p: ProgressEntry) => void;\n\nexport type LogEntryVariant =\n | LogEntry<LogOrigin.BINDINGS, LogTopic.INSTANTIATE, LogEvent.ERROR, string>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.FILESYSTEM, LogEvent.RUN, string>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.QUERY, LogEvent.START, void>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.QUERY, LogEvent.OK, void>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.QUERY, LogEvent.ERROR, void>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.CONNECT, LogEvent.OK, void>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.CONNECT, LogEvent.ERROR, void>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.DISCONNECT, LogEvent.OK, void>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.DISCONNECT, LogEvent.ERROR, void>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.OPEN, LogEvent.START, void>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.OPEN, LogEvent.OK, void>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.OPEN, LogEvent.ERROR, void>\n | LogEntry<LogOrigin.ASYNC_DUCKDB, LogTopic.QUERY, LogEvent.RUN, string>;\n\nexport interface Logger {\n log(entry: LogEntryVariant): void;\n}\n\nexport class VoidLogger implements Logger {\n public log(_entry: LogEntryVariant): void {}\n}\n\nexport class ConsoleLogger implements Logger {\n constructor(protected level: LogLevel = LogLevel.INFO) {}\n public log(entry: LogEntryVariant): void {\n if (entry.level >= this.level) {\n console.log(entry);\n }\n }\n}\n\nexport function getLogLevelLabel(level: LogLevel): string {\n switch (level) {\n case LogLevel.NONE:\n return 'NONE';\n case LogLevel.DEBUG:\n return 'DEBUG';\n case LogLevel.INFO:\n return 'INFO';\n case LogLevel.WARNING:\n return 'WARNING';\n case LogLevel.ERROR:\n return 'ERROR';\n default:\n return '?';\n }\n}\n\nexport function getLogEventLabel(event: LogEvent): string {\n switch (event) {\n case LogEvent.NONE:\n return 'NONE';\n case LogEvent.OK:\n return 'OK';\n case LogEvent.ERROR:\n return 'ERROR';\n case LogEvent.START:\n return 'START';\n case LogEvent.RUN:\n return 'RUN';\n case LogEvent.CAPTURE:\n return 'CAPTURE';\n default:\n return '?';\n }\n}\n\nexport function getLogTopicLabel(topic: LogTopic): string {\n switch (topic) {\n case LogTopic.CONNECT:\n return 'CONNECT';\n case LogTopic.DISCONNECT:\n return 'DISCONNECT';\n case LogTopic.INSTANTIATE:\n return 'INSTANTIATE';\n case LogTopic.OPEN:\n return 'OPEN';\n case LogTopic.QUERY:\n return 'QUERY';\n case LogTopic.FILESYSTEM:\n return 'FILESYSTEM';\n default:\n return '?';\n }\n}\n\nexport function getLogOriginLabel(origin: LogOrigin): string {\n switch (origin) {\n case LogOrigin.NONE:\n return 'NONE';\n case LogOrigin.WEB_WORKER:\n return 'WEB WORKER';\n case LogOrigin.NODE_WORKER:\n return 'NODE WORKER';\n case LogOrigin.BINDINGS:\n return 'DUCKDB BINDINGS';\n case LogOrigin.ASYNC_DUCKDB:\n return 'DUCKDB';\n default:\n return '?';\n }\n}\n", "export enum StatusCode {\n SUCCESS = 0,\n MAX_ARROW_ERROR = 255,\n DUCKDB_WASM_RETRY = 256,\n}\n\nexport function IsArrowBuffer(status: StatusCode): boolean {\n return status <= StatusCode.MAX_ARROW_ERROR;\n}\n\nexport function IsDuckDBWasmRetry(status: StatusCode): boolean {\n return status === StatusCode.DUCKDB_WASM_RETRY;\n}\n", "import * as arrow from 'apache-arrow';\nimport { AsyncDuckDB } from './async_bindings';\nimport { LogLevel, LogTopic, LogOrigin, LogEvent } from '../log';\nimport { ArrowInsertOptions, CSVInsertOptions, JSONInsertOptions } from '../bindings/insert_options';\n\n/** A thin helper to memoize the connection id */\nexport class AsyncDuckDBConnection {\n /** The async duckdb */\n protected readonly _bindings: AsyncDuckDB;\n /** The conn handle */\n protected readonly _conn: number;\n\n constructor(bindings: AsyncDuckDB, conn: number) {\n this._bindings = bindings;\n this._conn = conn;\n }\n\n /** Access the database bindings */\n public get bindings(): AsyncDuckDB {\n return this._bindings;\n }\n\n /** Disconnect from the database */\n public async close(): Promise<void> {\n return this._bindings.disconnect(this._conn);\n }\n\n /** Brave souls may use this function to consume the underlying connection id */\n public useUnsafe<R>(callback: (bindings: AsyncDuckDB, conn: number) => R) {\n return callback(this._bindings, this._conn);\n }\n\n /** Run a query */\n public async query<T extends { [key: string]: arrow.DataType } = any>(text: string): Promise<arrow.Table<T>> {\n this._bindings.logger.log({\n timestamp: new Date(),\n level: LogLevel.INFO,\n origin: LogOrigin.ASYNC_DUCKDB,\n topic: LogTopic.QUERY,\n event: LogEvent.RUN,\n value: text,\n });\n const buffer = await this._bindings.runQuery(this._conn, text);\n const reader = arrow.RecordBatchReader.from<T>(buffer);\n console.assert(reader.isSync(), 'Reader is not sync');\n return new arrow.Table(reader as arrow.RecordBatchFileReader);\n }\n\n /** Send a query */\n public async send<T extends { [key: string]: arrow.DataType } = any>(\n text: string,\n allowStreamResult: boolean = false,\n ): Promise<arrow.AsyncRecordBatchStreamReader<T>> {\n this._bindings.logger.log({\n timestamp: new Date(),\n level: LogLevel.INFO,\n origin: LogOrigin.ASYNC_DUCKDB,\n topic: LogTopic.QUERY,\n event: LogEvent.RUN,\n value: text,\n });\n let header = await this._bindings.startPendingQuery(this._conn, text, allowStreamResult);\n while (header == null) {\n // Avoid infinite loop on detached state\n if (this._bindings.isDetached()) {\n console.error('cannot send a message since the worker is not set!');\n return undefined as any;\n }\n header = await this._bindings.pollPendingQuery(this._conn);\n }\n const iter = new AsyncResultStreamIterator(this._bindings, this._conn, header);\n const reader = await arrow.RecordBatchReader.from<T>(iter);\n console.assert(reader.isAsync());\n console.assert(reader.isStream());\n return reader as unknown as arrow.AsyncRecordBatchStreamReader<T>; // XXX\n }\n\n /** Cancel a query that was sent earlier */\n public async cancelSent(): Promise<boolean> {\n return await this._bindings.cancelPendingQuery(this._conn);\n }\n\n /** Get table names */\n public async getTableNames(query: string): Promise<string[]> {\n return await this._bindings.getTableNames(this._conn, query);\n }\n\n /** Create a prepared statement */\n public async prepare<T extends { [key: string]: arrow.DataType } = any>(\n text: string,\n ): Promise<AsyncPreparedStatement<T>> {\n const stmt = await this._bindings.createPrepared(this._conn, text);\n return new AsyncPreparedStatement<T>(this._bindings, this._conn, stmt);\n }\n\n /** Insert an arrow table */\n public async insertArrowTable(table: arrow.Table, options: ArrowInsertOptions): Promise<void> {\n const buffer = arrow.tableToIPC(table, 'stream');\n await this.insertArrowFromIPCStream(buffer, options);\n }\n /** Insert an arrow table from an ipc stream */\n public async insertArrowFromIPCStream(buffer: Uint8Array, options: ArrowInsertOptions): Promise<void> {\n await this._bindings.insertArrowFromIPCStream(this._conn, buffer, options);\n }\n /** Insert csv file from path */\n public async insertCSVFromPath(text: string, options: CSVInsertOptions): Promise<void> {\n await this._bindings.insertCSVFromPath(this._conn, text, options);\n }\n /** Insert json file from path */\n public async insertJSONFromPath(text: string, options: JSONInsertOptions): Promise<void> {\n await this._bindings.insertJSONFromPath(this._conn, text, options);\n }\n}\n\n/** An async result stream iterator */\nexport class AsyncResultStreamIterator implements AsyncIterable<Uint8Array> {\n /** First chunk? */\n protected _first: boolean;\n /** Reached end of stream? */\n protected _depleted: boolean;\n /** In-flight */\n protected _inFlight: Promise<Uint8Array | null> | null;\n\n constructor(\n protected readonly db: AsyncDuckDB,\n protected readonly conn: number,\n protected readonly header: Uint8Array,\n ) {\n this._first = true;\n this._depleted = false;\n this._inFlight = null;\n }\n\n async next(): Promise<IteratorResult<Uint8Array>> {\n if (this._first) {\n this._first = false;\n return { done: false, value: this.header };\n }\n if (this._depleted) {\n return { done: true, value: null };\n }\n let buffer: Uint8Array | null = null;\n if (this._inFlight != null) {\n buffer = await this._inFlight;\n this._inFlight = null;\n }\n\n while (buffer == null) {\n buffer = await this.db.fetchQueryResults(this.conn);\n }\n\n this._depleted = buffer.length == 0;\n if (!this._depleted) {\n this._inFlight = this.db.fetchQueryResults(this.conn);\n }\n\n return {\n done: this._depleted,\n value: buffer,\n };\n }\n\n [Symbol.asyncIterator]() {\n return this;\n }\n}\n\n/** A thin helper to bind the prepared statement id */\nexport class AsyncPreparedStatement<T extends { [key: string]: arrow.DataType } = any> {\n /** The bindings */\n protected readonly bindings: AsyncDuckDB;\n /** The connection id */\n protected readonly connectionId: number;\n /** The statement id */\n protected readonly statementId: number;\n\n /** Constructor */\n constructor(bindings: AsyncDuckDB, connectionId: number, statementId: number) {\n this.bindings = bindings;\n this.connectionId = connectionId;\n this.statementId = statementId;\n }\n\n /** Close a prepared statement */\n public async close() {\n await this.bindings.closePrepared(this.connectionId, this.statementId);\n }\n\n /** Run a prepared statement */\n public async query(...params: any[]): Promise<arrow.Table<T>> {\n const buffer = await this.bindings.runPrepared(this.connectionId, this.statementId, params);\n const reader = arrow.RecordBatchReader.from<T>(buffer);\n console.assert(reader.isSync());\n return new arrow.Table(reader as arrow.RecordBatchFileReader);\n }\n\n /** Send a prepared statement */\n public async send(...params: any[]): Promise<arrow.AsyncRecordBatchStreamReader<T>> {\n const header = await this.bindings.sendPrepared(this.connectionId, this.statementId, params);\n const iter = new AsyncResultStreamIterator(this.bindings, this.connectionId, header);\n const reader = await arrow.RecordBatchReader.from<T>(iter);\n console.assert(reader.isAsync());\n console.assert(reader.isStream());\n return reader as unknown as arrow.AsyncRecordBatchStreamReader<T>; // XXX\n }\n}\n", "import { CSVInsertOptions, JSONInsertOptions, ArrowInsertOptions } from '../bindings/insert_options';\nimport { OPFSAccessMode } from '../bindings/opfs_scratch';\nimport { LogEntryVariant, ProgressEntry } from '../log';\nimport { ScriptTokens } from '../bindings/tokens';\nimport { FileStatistics } from '../bindings/file_stats';\nimport { DuckDBConfig } from '../bindings/config';\nimport { WebFile } from '../bindings/web_file';\nimport { InstantiationProgress, QueryProgress, QueryProgressHandle } from '../bindings/progress';\nimport { InterruptHandle } from '../bindings/interrupt';\nimport { DuckDBDataProtocol } from '../bindings';\n\nexport type ConnectionID = number;\nexport type StatementID = number;\n\nexport enum WorkerRequestType {\n CANCEL_PENDING_QUERY = 'CANCEL_PENDING_QUERY',\n CLOSE_PREPARED = 'CLOSE_PREPARED',\n COLLECT_FILE_STATISTICS = 'COLLECT_FILE_STATISTICS',\n REGISTER_OPFS_FILE_NAME = 'REGISTER_OPFS_FILE_NAME',\n CONNECT = 'CONNECT',\n COPY_FILE_TO_BUFFER = 'COPY_FILE_TO_BUFFER',\n COPY_FILE_TO_PATH = 'COPY_FILE_TO_PATH',\n CREATE_PREPARED = 'CREATE_PREPARED',\n DISCONNECT = 'DISCONNECT',\n DROP_FILE = 'DROP_FILE',\n DROP_FILES = 'DROP_FILES',\n EXPORT_FILE_STATISTICS = 'EXPORT_FILE_STATISTICS',\n FETCH_QUERY_RESULTS = 'FETCH_QUERY_RESULTS',\n FLUSH_FILES = 'FLUSH_FILES',\n GET_FEATURE_FLAGS = 'GET_FEATURE_FLAGS',\n GET_INTERRUPT_HANDLE = 'GET_INTERRUPT_HANDLE',\n GET_PROGRESS_HANDLE = 'GET_PROGRESS_HANDLE',\n GET_QUERY_PROGRESS = 'GET_QUERY_PROGRESS',\n GET_TABLE_NAMES = 'GET_TABLE_NAMES',\n GET_VERSION = 'GET_VERSION',\n GLOB_FILE_INFOS = 'GLOB_FILE_INFOS',\n INSERT_ARROW_FROM_IPC_STREAM = 'INSERT_ARROW_FROM_IPC_STREAM',\n INSERT_CSV_FROM_PATH = 'IMPORT_CSV_FROM_PATH',\n INSERT_JSON_FROM_PATH = 'IMPORT_JSON_FROM_PATH',\n INSTANTIATE = 'INSTANTIATE',\n OPEN = 'OPEN',\n PING = 'PING',\n PREFETCH_EXTENSIONS = 'PREFETCH_EXTENSIONS',\n POLL_PENDING_QUERY = 'POLL_PENDING_QUERY',\n REGISTER_FILE_BUFFER = 'REGISTER_FILE_BUFFER',\n REGISTER_FILE_HANDLE = 'REGISTER_FILE_HANDLE',\n REGISTER_FILE_URL = 'REGISTER_FILE_URL',\n RESET = 'RESET',\n RUN_PREPARED = 'RUN_PREPARED',\n RUN_QUERY = 'RUN_QUERY',\n SEND_PREPARED = 'SEND_PREPARED',\n START_PENDING_QUERY = 'START_PENDING_QUERY',\n TOKENIZE = 'TOKENIZE',\n}\n\nexport enum WorkerResponseType {\n CONNECTION_INFO = 'CONNECTION_INFO',\n ERROR = 'ERROR',\n EXTENSIONS_PREFETCHED = 'EXTENSIONS_PREFETCHED',\n FEATURE_FLAGS = 'FEATURE_FLAGS',\n FILE_BUFFER = 'FILE_BUFFER',\n FILE_INFOS = 'FILE_INFOS',\n FILE_SIZE = 'FILE_SIZE',\n FILE_STATISTICS = 'FILE_STATISTICS',\n INSTANTIATE_PROGRESS = 'INSTANTIATE_PROGRESS',\n INTERRUPT_HANDLE = 'INTERRUPT_HANDLE',\n LOG = 'LOG',\n PROGRESS_HANDLE = 'PROGRESS_HANDLE',\n PROGRESS_UPDATE = 'PROGRESS_UPDATE',\n OK = 'OK',\n PREPARED_STATEMENT_ID = 'PREPARED_STATEMENT_ID',\n QUERY_PLAN = 'QUERY_PLAN',\n QUERY_PROGRESS = 'QUERY_PROGRESS',\n QUERY_RESULT = 'QUERY_RESULT',\n QUERY_RESULT_CHUNK = 'QUERY_RESULT_CHUNK',\n QUERY_RESULT_HEADER = 'QUERY_RESULT_HEADER',\n QUERY_RESULT_HEADER_OR_NULL = 'QUERY_RESULT_HEADER_OR_NULL',\n REGISTERED_FILE = 'REGISTERED_FILE',\n SCRIPT_TOKENS = 'SCRIPT_TOKENS',\n SUCCESS = 'SUCCESS',\n TABLE_NAMES = 'TABLE_NAMES',\n OPFS_FILE_NAMES = 'OPFS_FILE_NAMES',\n VERSION_STRING = 'VERSION_STRING',\n}\n\nexport type WorkerRequest<T, P> = {\n readonly messageId: number;\n readonly type: T;\n readonly data: P;\n};\n\nexport type WorkerResponse<T, P> = {\n readonly messageId: number;\n readonly requestId: number;\n readonly type: T;\n readonly data: P;\n};\n\nexport type WorkerTaskReturnType<T extends WorkerTaskVariant> = T extends WorkerTask<any, any, infer P> ? P : never;\n\nexport class WorkerTask<T, D, P> {\n readonly type: T;\n readonly data: D;\n promise: Promise<P>;\n promiseResolver: (value: P | PromiseLike<P>) => void = () => {};\n promiseRejecter: (value: any) => void = () => {};\n\n constructor(type: T, data: D) {\n this.type = type;\n this.data = data;\n this.promise = new Promise<P>(\n (resolve: (value: P | PromiseLike<P>) => void, reject: (reason?: void) => void) => {\n this.promiseResolver = resolve;\n this.promiseRejecter = reject;\n },\n );\n }\n}\n\nexport type WorkerRequestVariant =\n | WorkerRequest<WorkerRequestType.CLOSE_PREPARED, [ConnectionID, StatementID]>\n | WorkerRequest<WorkerRequestType.CANCEL_PENDING_QUERY, number>\n | WorkerRequest<WorkerRequestType.COLLECT_FILE_STATISTICS, [string, boolean]>\n | WorkerRequest<WorkerRequestType.REGISTER_OPFS_FILE_NAME, [string, OPFSAccessMode]>\n | WorkerRequest<WorkerRequestType.CONNECT, null>\n | WorkerRequest<WorkerRequestType.COPY_FILE_TO_BUFFER, string>\n | WorkerRequest<WorkerRequestType.COPY_FILE_TO_PATH, [string, string]>\n | WorkerRequest<WorkerRequestType.CREATE_PREPARED, [ConnectionID, string]>\n | WorkerRequest<WorkerRequestType.DISCONNECT, number>\n | WorkerRequest<WorkerRequestType.DROP_FILE, string>\n | WorkerRequest<WorkerRequestType.DROP_FILES, string[] | undefined>\n | WorkerRequest<WorkerRequestType.EXPORT_FILE_STATISTICS, string>\n | WorkerRequest<WorkerRequestType.FETCH_QUERY_RESULTS, number>\n | WorkerRequest<WorkerRequestType.FLUSH_FILES, null>\n | WorkerRequest<WorkerRequestType.GET_FEATURE_FLAGS, null>\n | WorkerRequest<WorkerRequestType.GET_INTERRUPT_HANDLE, number>\n | WorkerRequest<WorkerRequestType.GET_PROGRESS_HANDLE, number>\n | WorkerRequest<WorkerRequestType.GET_QUERY_PROGRESS, number>\n | WorkerRequest<WorkerRequestType.GET_TABLE_NAMES, [number, string]>\n | WorkerRequest<WorkerRequestType.GET_VERSION, null>\n | WorkerRequest<WorkerRequestType.GLOB_FILE_INFOS, string>\n | WorkerRequest<\n WorkerRequestType.INSERT_ARROW_FROM_IPC_STREAM,\n [number, Uint8Array, ArrowInsertOptions | undefined]\n >\n | WorkerRequest<WorkerRequestType.INSERT_CSV_FROM_PATH, [number, string, CSVInsertOptions]>\n | WorkerRequest<WorkerRequestType.INSERT_JSON_FROM_PATH, [number, string, JSONInsertOptions]>\n | WorkerRequest<WorkerRequestType.INSTANTIATE, [string, string | null, boolean?]>\n | WorkerRequest<WorkerRequestType.OPEN, DuckDBConfig>\n | WorkerRequest<WorkerRequestType.PING, null>\n | WorkerRequest<WorkerRequestType.PREFETCH_EXTENSIONS, [string[], number | undefined]>\n | WorkerRequest<WorkerRequestType.POLL_PENDING_QUERY, number>\n | WorkerRequest<WorkerRequestType.REGISTER_FILE_BUFFER, [string, Uint8Array]>\n | WorkerRequest<WorkerRequestType.REGISTER_FILE_HANDLE, [string, any, DuckDBDataProtocol, boolean]>\n | WorkerRequest<WorkerRequestType.REGISTER_FILE_URL, [string, string, DuckDBDataProtocol, boolean]>\n | WorkerRequest<WorkerRequestType.RESET, null>\n | WorkerRequest<WorkerRequestType.RUN_PREPARED, [number, number, any[]]>\n | WorkerRequest<WorkerRequestType.RUN_QUERY, [number, string]>\n | WorkerRequest<WorkerRequestType.SEND_PREPARED, [number, number, any[]]>\n | WorkerRequest<WorkerRequestType.START_PENDING_QUERY, [number, string, boolean]>\n | WorkerRequest<WorkerRequestType.TOKENIZE, string>;\n\nexport type WorkerResponseVariant =\n | WorkerResponse<WorkerResponseType.CONNECTION_INFO, number>\n | WorkerResponse<WorkerResponseType.ERROR, any>\n | WorkerResponse<WorkerResponseType.EXTENSIONS_PREFETCHED, string[]>\n | WorkerResponse<WorkerResponseType.FEATURE_FLAGS, number>\n | WorkerResponse<WorkerResponseType.FILE_BUFFER, Uint8Array>\n | WorkerResponse<WorkerResponseType.FILE_INFOS, WebFile[]>\n | WorkerResponse<WorkerResponseType.FILE_SIZE, number>\n | WorkerResponse<WorkerResponseType.FILE_STATISTICS, FileStatistics>\n | WorkerResponse<WorkerResponseType.INSTANTIATE_PROGRESS, InstantiationProgress>\n | WorkerResponse<WorkerResponseType.INTERRUPT_HANDLE, InterruptHandle | null>\n | WorkerResponse<WorkerResponseType.LOG, LogEntryVariant>\n | WorkerResponse<WorkerResponseType.PROGRESS_HANDLE, QueryProgressHandle | null>\n | WorkerResponse<WorkerResponseType.PROGRESS_UPDATE, ProgressEntry>\n | WorkerResponse<WorkerResponseType.OK, null>\n | WorkerResponse<WorkerResponseType.PREPARED_STATEMENT_ID, number>\n | WorkerResponse<WorkerResponseType.QUERY_PLAN, Uint8Array>\n | WorkerResponse<WorkerResponseType.QUERY_PROGRESS, QueryProgress | null>\n | WorkerResponse<WorkerResponseType.QUERY_RESULT, Uint8Array>\n | WorkerResponse<WorkerResponseType.QUERY_RESULT_CHUNK, Uint8Array | null>\n | WorkerResponse<WorkerResponseType.QUERY_RESULT_HEADER, Uint8Array>\n | WorkerResponse<WorkerResponseType.QUERY_RESULT_HEADER_OR_NULL, Uint8Array | null>\n | WorkerResponse<WorkerResponseType.SCRIPT_TOKENS, ScriptTokens>\n | WorkerResponse<WorkerResponseType.SUCCESS, boolean>\n | WorkerResponse<WorkerResponseType.TABLE_NAMES, string[]>\n | WorkerResponse<WorkerResponseType.OPFS_FILE_NAMES, string[]>\n | WorkerResponse<WorkerResponseType.VERSION_STRING, string>;\n\nexport type WorkerTaskVariant =\n | WorkerTask<WorkerRequestType.COLLECT_FILE_STATISTICS, [string, boolean], null>\n | WorkerTask<WorkerRequestType.REGISTER_OPFS_FILE_NAME, [string, OPFSAccessMode], string[]>\n | WorkerTask<WorkerRequestType.CLOSE_PREPARED, [number, number], null>\n | WorkerTask<WorkerRequestType.CONNECT, null, ConnectionID>\n | WorkerTask<WorkerRequestType.COPY_FILE_TO_BUFFER, string, Uint8Array>\n | WorkerTask<WorkerRequestType.COPY_FILE_TO_PATH, [string, string], null>\n | WorkerTask<WorkerRequestType.CREATE_PREPARED, [number, string], number>\n | WorkerTask<WorkerRequestType.DISCONNECT, ConnectionID, null>\n | WorkerTask<WorkerRequestType.DROP_FILE, string, null>\n | WorkerTask<WorkerRequestType.DROP_FILES, string[] | undefined, null>\n | WorkerTask<WorkerRequestType.EXPORT_FILE_STATISTICS, string, FileStatistics>\n | WorkerTask<WorkerRequestType.FETCH_QUERY_RESULTS, ConnectionID, Uint8Array | null>\n | WorkerTask<WorkerRequestType.FLUSH_FILES, null, null>\n | WorkerTask<WorkerRequestType.GET_FEATURE_FLAGS, null, number>\n | WorkerTask<WorkerRequestType.GET_INTERRUPT_HANDLE, ConnectionID, InterruptHandle | null>\n | WorkerTask<WorkerRequestType.GET_PROGRESS_HANDLE, ConnectionID, QueryProgressHandle | null>\n | WorkerTask<WorkerRequestType.GET_QUERY_PROGRESS, ConnectionID, QueryProgress | null>\n | WorkerTask<WorkerRequestType.GET_TABLE_NAMES, [number, string], string[]>\n | WorkerTask<WorkerRequestType.GET_VERSION, null, string>\n | WorkerTask<\n WorkerRequestType.INSERT_ARROW_FROM_IPC_STREAM,\n [number, Uint8Array, ArrowInsertOptions | undefined],\n null\n >\n | WorkerTask<WorkerRequestType.INSERT_CSV_FROM_PATH, [number, string, CSVInsertOptions], null>\n | WorkerTask<WorkerRequestType.INSERT_JSON_FROM_PATH, [number, string, JSONInsertOptions], null>\n | WorkerTask<WorkerRequestType.INSTANTIATE, [string, string | null, boolean?], null>\n | WorkerTask<WorkerRequestType.OPEN, DuckDBConfig, null>\n | WorkerTask<WorkerRequestType.PING, null, null>\n | WorkerTask<WorkerRequestType.PREFETCH_EXTENSIONS, [string[], number | undefined], string[]>\n | WorkerTask<WorkerRequestType.REGISTER_FILE_BUFFER, [string, Uint8Array], null>\n | WorkerTask<WorkerRequestType.REGISTER_FILE_HANDLE, [string, any, DuckDBDataProtocol, boolean], null>\n | WorkerTask<WorkerRequestType.REGISTER_FILE_URL, [string, string, DuckDBDataProtocol, boolean], null>\n | WorkerTask<WorkerRequestType.GLOB_FILE_INFOS, string, WebFile[]>\n | WorkerTask<WorkerRequestType.RESET, null, null>\n | WorkerTask<WorkerRequestType.RUN_PREPARED, [number, number, any[]], Uint8Array>\n | WorkerTask<WorkerRequestType.RUN_QUERY, [ConnectionID, string], Uint8Array>\n | WorkerTask<WorkerRequestType.SEND_PREPARED, [number, number, any[]], Uint8Array>\n | WorkerTask<WorkerRequestType.START_PENDING_QUERY, [ConnectionID, string, boolean], Uint8Array | null>\n | WorkerTask<WorkerRequestType.POLL_PENDING_QUERY, ConnectionID, Uint8Array | null>\n | WorkerTask<WorkerRequestType.CANCEL_PENDING_QUERY, ConnectionID, boolean>\n | WorkerTask<WorkerRequestType.TOKENIZE, string, ScriptTokens>;\n", "/**\n * A connection's interrupt flag, reachable from any thread.\n *\n * On the threads bundle the worker is inside the call that runs a query (a blocking `runQuery`, or one\n * `pollPendingQuery`, which can process many chunks) until that call returns, so a message asking to cancel the\n * query (`cancelPendingQuery`) is read only afterwards. The wasm memory of that bundle is a SharedArrayBuffer, so\n * the caller can set the engine's own flag (`ClientContext::interrupt_state`) in place. The engine checks it between\n * chunks on every thread and in the HTTP client, and the statement fails with an interrupt error, as with a native\n * `Connection::Interrupt()`.\n *\n * The flag belongs to the connection, not to a query: whatever runs on the connection when it is set is\n * interrupted. A statement in autocommit mode clears it before it starts, so a store made between statements has\n * no effect there.\n */\nexport interface InterruptHandle {\n /** The engine's wasm memory */\n memory: SharedArrayBuffer;\n /** Byte offset of the connection's one-byte interrupt flag in `memory` */\n offset: number;\n}\n\n/** ClientInterruptState::NOT_INTERRUPTED */\nconst NOT_INTERRUPTED = 0;\n/** ClientInterruptState::INTERRUPTED */\nconst INTERRUPTED = 1;\n\n/**\n * Interrupt whatever runs on the handle's connection. Callable from any thread.\n *\n * Moves the flag from not interrupted to interrupted only, as `ClientContext::Interrupt()` does: a statement that\n * suppressed interrupts (after an irreversible step such as a COMMIT) stays unaffected.\n */\nexport function interruptConnection(handle: InterruptHandle): void {\n Atomics.compareExchange(new Uint8Array(handle.memory, handle.offset, 1), 0, NOT_INTERRUPTED, INTERRUPTED);\n}\n", "import * as arrow from 'apache-arrow';\n\nexport interface SQLType {\n /// The sql type\n sqlType: string;\n /// Is nullable?\n nullable?: boolean;\n /// Decimal precision\n precision?: number;\n /// Decimal scaling\n scale?: number;\n /// Timezone\n timezone?: string;\n /// Byte width (FixedSizeBinary)\n byteWidth?: number;\n /// Key type\n keyType?: SQLType;\n /// Value type\n valueType?: SQLType;\n /// Fields\n fields?: SQLField[];\n}\n\nexport function arrowToSQLType(type: arrow.DataType): SQLType {\n switch (type.typeId) {\n case arrow.Type.Binary:\n return { sqlType: 'binary' };\n case arrow.Type.Bool:\n return { sqlType: 'bool' };\n case arrow.Type.Date:\n return { sqlType: 'date' };\n case arrow.Type.DateDay:\n return { sqlType: 'date32[d]' };\n case arrow.Type.DateMillisecond:\n return { sqlType: 'date64[ms]' };\n case arrow.Type.Decimal: {\n const dec = type as arrow.Decimal;\n return { sqlType: 'decimal', precision: dec.precision, scale: dec.scale };\n }\n case arrow.Type.Float:\n return { sqlType: 'float' };\n case arrow.Type.Float16:\n return { sqlType: 'float16' };\n case arrow.Type.Float32:\n return { sqlType: 'float32' };\n case arrow.Type.Float64:\n return { sqlType: 'float64' };\n case arrow.Type.Int:\n return { sqlType: 'int32' };\n case arrow.Type.Int16:\n return { sqlType: 'int16' };\n case arrow.Type.Int32:\n return { sqlType: 'int32' };\n case arrow.Type.Int64:\n return { sqlType: 'int64' };\n case arrow.Type.Uint16:\n return { sqlType: 'uint16' };\n case arrow.Type.Uint32:\n return { sqlType: 'uint32' };\n case arrow.Type.Uint64:\n return { sqlType: 'uint64' };\n case arrow.Type.Uint8:\n return { sqlType: 'uint8' };\n case arrow.Type.IntervalDayTime:\n return { sqlType: 'interval[dt]' };\n case arrow.Type.IntervalYearMonth:\n return { sqlType: 'interval[m]' };\n case arrow.Type.List: {\n const list = type as arrow.List;\n return {\n sqlType: 'list',\n valueType: arrowToSQLType(list.valueType),\n };\n }\n case arrow.Type.FixedSizeBinary: {\n const bin = type as arrow.FixedSizeBinary;\n return { sqlType: 'fixedsizebinary', byteWidth: bin.byteWidth };\n }\n case arrow.Type.Null:\n return { sqlType: 'null' };\n case arrow.Type.Utf8:\n return { sqlType: 'utf8' };\n case arrow.Type.Struct: {\n const struct_ = type as arrow.Struct;\n return {\n sqlType: 'struct',\n fields: struct_.children.map(c => arrowToSQLField(c.name, c.type)),\n };\n }\n case arrow.Type.Map: {\n const map_ = type as arrow.Map_;\n return {\n sqlType: 'map',\n keyType: arrowToSQLType(map_.keyType),\n valueType: arrowToSQLType(map_.valueType),\n };\n }\n case arrow.Type.Time:\n return { sqlType: 'time[s]' };\n case arrow.Type.TimeMicrosecond:\n return { sqlType: 'time[us]' };\n case arrow.Type.TimeMillisecond:\n return { sqlType: 'time[ms]' };\n case arrow.Type.TimeNanosecond:\n return { sqlType: 'time[ns]' };\n case arrow.Type.TimeSecond:\n return { sqlType: 'time[s]' };\n case arrow.Type.Timestamp: {\n const ts = type as arrow.Timestamp;\n return { sqlType: 'timestamp', timezone: ts.timezone || undefined };\n }\n case arrow.Type.TimestampSecond: {\n const ts = type as arrow.TimestampSecond;\n return { sqlType: 'timestamp[s]', timezone: ts.timezone || undefined };\n }\n case arrow.Type.TimestampMicrosecond: {\n const ts = type as arrow.TimestampMicrosecond;\n return { sqlType: 'timestamp[us]', timezone: ts.timezone || undefined };\n }\n case arrow.Type.TimestampNanosecond: {\n const ts = type as arrow.TimestampNanosecond;\n return { sqlType: 'timestamp[ns]', timezone: ts.timezone || undefined };\n }\n case arrow.Type.TimestampMillisecond: {\n const ts = type as arrow.TimestampMillisecond;\n return { sqlType: 'timestamp[ms]', timezone: ts.timezone || undefined };\n }\n }\n throw new Error(`unsupported arrow type: ${type.toString()}`);\n}\n\nexport type SQLField = SQLType & { name: string };\n\nexport function arrowToSQLField(name: string, type: arrow.DataType): SQLField {\n const t = arrowToSQLType(type) as SQLField;\n t.name = name;\n return t;\n}\n", "export const REGEX_OPFS_FILE = /'(opfs:\\/\\/\\S*?)'/g;\nexport const REGEX_OPFS_PROTOCOL = /(opfs:\\/\\/\\S*?)/g;\n\nexport function isOPFSProtocol(path: string): boolean {\n return path.search(REGEX_OPFS_PROTOCOL) > -1;\n}\n\nexport function searchOPFSFiles(text: string) {\n return [...text.matchAll(REGEX_OPFS_FILE)].map(match => match[1]);\n}", "import { OPFSAccessMode } from '../bindings/opfs_scratch';\nimport {\n WorkerRequestType,\n WorkerResponseType,\n WorkerResponseVariant,\n WorkerTaskVariant,\n WorkerTask,\n ConnectionID,\n WorkerTaskReturnType,\n} from './worker_request';\nimport { AsyncDuckDBBindings } from './async_bindings_interface';\nimport { Logger } from '../log';\nimport { AsyncDuckDBConnection } from './async_connection';\nimport { CSVInsertOptions, JSONInsertOptions, ArrowInsertOptions } from '../bindings/insert_options';\nimport { ScriptTokens } from '../bindings/tokens';\nimport { FileStatistics } from '../bindings/file_stats';\nimport { DuckDBConfig } from '../bindings/config';\nimport { InstantiationProgress, QueryProgress, QueryProgressHandle } from '../bindings/progress';\nimport { InterruptHandle, interruptConnection } from '../bindings/interrupt';\nimport { arrowToSQLField } from '../json_typedef';\nimport { WebFile } from '../bindings/web_file';\nimport { DuckDBDataProtocol } from '../bindings';\nimport { searchOPFSFiles } from \"../utils/opfs_util\";\nimport { ProgressEntry } from '../log';\n\nconst TEXT_ENCODER = new TextEncoder();\n\n/**\n * How often the flag of `registerCancelSAB` is checked while a pending query runs. A check costs one atomic load, so\n * the interval only bounds the latency of a cancel that arrives while the page waits for a poll.\n */\nconst CANCEL_SAB_POLL_MS = 50;\n\n/** The default time a worker gets to answer its first message (see AsyncDuckDBOptions.workerStartTimeout) */\nexport const DEFAULT_WORKER_START_TIMEOUT_MS = 30000;\n\n/** Options for the async DuckDB */\nexport interface AsyncDuckDBOptions {\n /**\n * Milliseconds the worker gets to answer its first message before all pending\n * requests are rejected with \"worker did not start\". Only a cheap PING is timed,\n * and only until the worker's first response arrives, so slow instantiation or\n * long-running queries are never cut short. 0 disables the check.\n * Defaults to DEFAULT_WORKER_START_TIMEOUT_MS (30 s).\n */\n workerStartTimeout?: number;\n}\n\nexport class AsyncDuckDB implements AsyncDuckDBBindings {\n /** The message handler */\n protected readonly _onMessageHandler: (event: MessageEvent) => void;\n /** The error handler */\n protected readonly _onErrorHandler: (event: ErrorEvent) => void;\n /** The close handler */\n protected readonly _onCloseHandler: () => void;\n /** The message error handler */\n protected readonly _onMessageErrorHandler: (event: MessageEvent) => void;\n\n /** Instantiate the module */\n protected _onInstantiationProgress: ((p: InstantiationProgress) => void)[] = [];\n\n /** Progress callbacks */\n protected _onExecutionProgress: ((p: ProgressEntry) => void)[] = [];\n\n /** The logger */\n protected readonly _logger: Logger;\n /** The worker */\n protected _worker: Worker | null = null;\n /** The promise for the worker shutdown */\n protected _workerShutdownPromise: Promise<null> | null = null;\n /** Make the worker as terminated */\n protected _workerShutdownResolver: (value: PromiseLike<null> | null) => void = () => {};\n\n /** The next message id */\n protected _nextMessageId = 0;\n /** The pending requests */\n protected _pendingRequests: Map<number, WorkerTaskVariant> = new Map();\n /** The DuckDBConfig */\n protected _config: DuckDBConfig = {};\n /** The interrupt flags of the connections, fetched when they connect (threads bundle only) */\n protected _interruptHandles: Map<ConnectionID, InterruptHandle> = new Map();\n /** The connections with a pending query, in the order the queries started */\n protected _pendingQueries: Set<ConnectionID> = new Set();\n /** The flag of registerCancelSAB */\n protected _cancelFlag: Int32Array | null = null;\n /** The interval that checks the flag of registerCancelSAB while a pending query runs */\n protected _cancelWatcher: ReturnType<typeof setInterval> | null = null;\n\n /** Milliseconds the worker gets to answer its first message, 0 disables the check */\n protected readonly _workerStartTimeout: number;\n /** Did the attached worker send anything yet? */\n protected _workerStarted = false;\n /** The armed worker start timer, if any */\n protected _workerStartTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(logger: Logger, worker: Worker | null = null, options: AsyncDuckDBOptions = {}) {\n this._logger = logger;\n this._workerStartTimeout = options.workerStartTimeout ?? DEFAULT_WORKER_START_TIMEOUT_MS;\n this._onMessageHandler = this.onMessage.bind(this);\n this._onErrorHandler = this.onError.bind(this);\n this._onCloseHandler = this.onClose.bind(this);\n this._onMessageErrorHandler = this.onMessageError.bind(this);\n if (worker != null) this.attach(worker);\n }\n\n /** Get the logger */\n public get logger(): Logger {\n return this._logger;\n }\n\n /** Get the logger */\n public get config(): DuckDBConfig {\n return this._config;\n }\n\n /** Attach to worker */\n protected attach(worker: Worker): void {\n this._worker = worker;\n this._workerStarted = false;\n this._worker.addEventListener('message', this._onMessageHandler);\n this._worker.addEventListener('error', this._onErrorHandler);\n this._worker.addEventListener('close', this._onCloseHandler);\n this._worker.addEventListener('messageerror', this._onMessageErrorHandler);\n this._workerShutdownPromise = new Promise<null>(\n (resolve: (value: PromiseLike<null> | null) => void, _reject: (reason?: void) => void) => {\n this._workerShutdownResolver = resolve;\n },\n );\n }\n\n /** Detach from worker */\n public detach(): void {\n if (!this._worker) return;\n this._worker.removeEventListener('message', this._onMessageHandler);\n this._worker.removeEventListener('error', this._onErrorHandler);\n this._worker.removeEventListener('close', this._onCloseHandler);\n this._worker.removeEventListener('messageerror', this._onMessageErrorHandler);\n this._worker = null;\n this.clearWorkerStartTimer();\n this.rejectPendingRequests(new Error('duckdb worker was detached before the request completed'));\n this._workerShutdownResolver(null);\n this._workerShutdownPromise = null;\n this._workerShutdownResolver = () => {};\n }\n\n /** Kill the worker */\n public async terminate(): Promise<void> {\n if (!this._worker) return;\n this.forgetConnections();\n this._worker.terminate();\n //await this._workerShutdownPromise; TODO deadlocking in karma?\n this._worker = null;\n this.clearWorkerStartTimer();\n this.rejectPendingRequests(new Error('duckdb worker was terminated before the request completed'));\n this._workerShutdownPromise = null;\n this._workerShutdownResolver = () => {};\n }\n\n /** Reject all pending requests with an error and forget them */\n protected rejectPendingRequests(error: Error): void {\n const pending = [...this._pendingRequests.values()];\n this._pendingRequests.clear();\n for (const task of pending) {\n task.promiseRejecter(error);\n }\n }\n\n /** Stop waiting for the worker to start */\n protected clearWorkerStartTimer(): void {\n if (this._workerStartTimer !== null) {\n clearTimeout(this._workerStartTimer);\n this._workerStartTimer = null;\n }\n }\n\n /**\n * Make sure a worker that never starts fails instead of hanging.\n *\n * A worker can fail to load without ever emitting 'error' (e.g. a script error swallowed by\n * a Worker polyfill), in which case every request would wait forever. Before the first\n * request goes out we send a PING, which the dispatcher answers immediately, ahead of the\n * request itself. Any message from the worker disarms the timer. If none arrives in time,\n * all pending requests are rejected. Long-running requests are never timed.\n */\n protected armWorkerStartTimer(): void {\n if (!this._worker || this._workerStarted || this._workerStartTimer !== null) return;\n if (!(this._workerStartTimeout > 0)) return;\n const ping = new WorkerTask<WorkerRequestType.PING, null, null>(WorkerRequestType.PING, null);\n ping.promise.catch(() => {});\n const mid = this._nextMessageId++;\n this._pendingRequests.set(mid, ping);\n this._worker.postMessage({ messageId: mid, type: ping.type, data: ping.data });\n const timeout = this._workerStartTimeout;\n this._workerStartTimer = setTimeout(() => {\n this._workerStartTimer = null;\n if (this._workerStarted) return;\n const error = new Error(\n `duckdb worker did not start: no response within ${timeout} ms. ` +\n 'The worker script probably failed to load or threw during startup; check the worker console ' +\n 'output. In Node.js, also check the `web-worker` package version. ' +\n 'The timeout can be changed with the `workerStartTimeout` option of AsyncDuckDB.',\n );\n console.error(error.message);\n this.rejectPendingRequests(error);\n }, timeout);\n }\n\n /** Post a task */\n protected async postTask<W extends WorkerTaskVariant>(\n task: W,\n transfer: ArrayBuffer[] = [],\n ): Promise<WorkerTaskReturnType<W>> {\n if (!this._worker) {\n console.error('cannot send a message since the worker is not set!:' + task.type+\",\" + task.data);\n return undefined as any;\n }\n this.armWorkerStartTimer();\n const mid = this._nextMessageId++;\n this._pendingRequests.set(mid, task);\n this._worker.postMessage(\n {\n messageId: mid,\n type: task.type,\n data: task.data,\n },\n transfer,\n );\n return (await task.promise) as WorkerTaskReturnType<W>;\n }\n\n /** Received a message */\n protected onMessage(event: MessageEvent): void {\n // Any message proves the worker is running\n if (!this._workerStarted) {\n this._workerStarted = true;\n this.clearWorkerStartTimer();\n }\n\n // Unassociated responses?\n const response = event.data as WorkerResponseVariant;\n switch (response.type) {\n // Request failed?\n case WorkerResponseType.PROGRESS_UPDATE: {\n for (const p of this._onExecutionProgress) {\n p(response.data);\n }\n return;\n }\n case WorkerResponseType.LOG: {\n this._logger.log(response.data);\n return;\n }\n // Call progress callback\n case WorkerResponseType.INSTANTIATE_PROGRESS: {\n for (const p of this._onInstantiationProgress) {\n p(response.data);\n }\n return;\n }\n }\n\n // Haybarn: a message of the engine's platform functions (open-auth-url, vgi-ensure-worker), for the page\n // bridges that listen on the same Worker\n if (typeof response.requestId !== 'number') {\n return;\n }\n // Get associated task\n const task = this._pendingRequests.get(response.requestId);\n if (!task) {\n console.warn(`unassociated response: [${response.requestId}, ${response.type.toString()}]`);\n return;\n }\n this._pendingRequests.delete(response.requestId);\n\n // Request failed?\n if (response.type == WorkerResponseType.ERROR) {\n // Workaround for Firefox not being able to perform structured-clone on Native Errors\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1556604\n const e = new Error(response.data.message);\n e.name = response.data.name;\n if (Object.getOwnPropertyDescriptor(e, 'stack')?.writable) {\n e.stack = response.data.stack;\n }\n task.promiseRejecter(e);\n return;\n }\n\n // Otherwise differentiate between the tasks first\n switch (task.type) {\n case WorkerRequestType.CLOSE_PREPARED:\n case WorkerRequestType.COLLECT_FILE_STATISTICS:\n case WorkerRequestType.COPY_FILE_TO_PATH:\n case WorkerRequestType.DISCONNECT:\n case WorkerRequestType.DROP_FILE:\n case WorkerRequestType.DROP_FILES:\n case WorkerRequestType.FLUSH_FILES:\n case WorkerRequestType.INSERT_ARROW_FROM_IPC_STREAM:\n case WorkerRequestType.INSERT_CSV_FROM_PATH:\n case WorkerRequestType.INSERT_JSON_FROM_PATH:\n case WorkerRequestType.OPEN:\n case WorkerRequestType.PING:\n case WorkerRequestType.REGISTER_FILE_BUFFER:\n case WorkerRequestType.REGISTER_FILE_HANDLE:\n case WorkerRequestType.REGISTER_FILE_URL:\n case WorkerRequestType.RESET:\n if (response.type == WorkerResponseType.OK) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.INSTANTIATE:\n this._onInstantiationProgress = [];\n if (response.type == WorkerResponseType.OK) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.GLOB_FILE_INFOS:\n if (response.type == WorkerResponseType.FILE_INFOS) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.GET_VERSION:\n if (response.type == WorkerResponseType.VERSION_STRING) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.GET_FEATURE_FLAGS:\n if (response.type == WorkerResponseType.FEATURE_FLAGS) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.GET_TABLE_NAMES:\n if (response.type == WorkerResponseType.TABLE_NAMES) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.REGISTER_OPFS_FILE_NAME:\n if (response.type == WorkerResponseType.OPFS_FILE_NAMES) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.PREFETCH_EXTENSIONS:\n if (response.type == WorkerResponseType.EXTENSIONS_PREFETCHED) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.TOKENIZE:\n if (response.type == WorkerResponseType.SCRIPT_TOKENS) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.COPY_FILE_TO_BUFFER:\n if (response.type == WorkerResponseType.FILE_BUFFER) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.EXPORT_FILE_STATISTICS:\n if (response.type == WorkerResponseType.FILE_STATISTICS) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.CONNECT:\n if (response.type == WorkerResponseType.CONNECTION_INFO) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.RUN_PREPARED:\n case WorkerRequestType.RUN_QUERY:\n if (response.type == WorkerResponseType.QUERY_RESULT) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.SEND_PREPARED:\n if (response.type == WorkerResponseType.QUERY_RESULT_HEADER) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.START_PENDING_QUERY:\n if (response.type == WorkerResponseType.QUERY_RESULT_HEADER_OR_NULL) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.POLL_PENDING_QUERY:\n if (response.type == WorkerResponseType.QUERY_RESULT_HEADER_OR_NULL) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.CANCEL_PENDING_QUERY:\n this._onInstantiationProgress = [];\n if (response.type == WorkerResponseType.SUCCESS) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.GET_INTERRUPT_HANDLE:\n if (response.type == WorkerResponseType.INTERRUPT_HANDLE) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.GET_PROGRESS_HANDLE:\n if (response.type == WorkerResponseType.PROGRESS_HANDLE) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.GET_QUERY_PROGRESS:\n if (response.type == WorkerResponseType.QUERY_PROGRESS) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.FETCH_QUERY_RESULTS:\n if (response.type == WorkerResponseType.QUERY_RESULT_CHUNK) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.CREATE_PREPARED:\n if (response.type == WorkerResponseType.PREPARED_STATEMENT_ID) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n }\n task.promiseRejecter(new Error(`unexpected response type: ${response.type.toString()}`));\n }\n\n /** Received an error */\n protected onError(event: ErrorEvent): void {\n console.error(event);\n console.error(`error in duckdb worker: ${event.message} (${event.filename}:${event.lineno})`);\n this.clearWorkerStartTimer();\n this.rejectPendingRequests(new Error(`error in duckdb worker: ${event.message ?? 'unknown error'}`));\n }\n\n /** A message from the worker could not be deserialized */\n protected onMessageError(_event: MessageEvent): void {\n // We cannot tell which request the lost response belonged to, so fail them all rather than hang.\n console.error('duckdb worker sent a message that could not be deserialized');\n this.rejectPendingRequests(new Error('duckdb worker sent a message that could not be deserialized'));\n }\n\n /** The worker was closed */\n protected onClose(): void {\n this._workerShutdownResolver(null);\n this.clearWorkerStartTimer();\n if (this._pendingRequests.size != 0) {\n console.warn(`worker terminated with ${this._pendingRequests.size} pending requests`);\n }\n this.rejectPendingRequests(new Error('duckdb worker closed before the request completed'));\n }\n\n /** Is in detached state, no worker defined */\n public isDetached(): boolean {\n return !this._worker;\n }\n\n /** Reset the duckdb */\n public async reset(): Promise<null> {\n this.forgetConnections();\n const task = new WorkerTask<WorkerRequestType.RESET, null, null>(WorkerRequestType.RESET, null);\n return await this.postTask(task);\n }\n\n /** Ping the worker thread */\n public async ping(): Promise<any> {\n const task = new WorkerTask<WorkerRequestType.PING, null, null>(WorkerRequestType.PING, null);\n await this.postTask(task);\n }\n /** Try to drop a file */\n public async dropFile(name: string): Promise<null> {\n const task = new WorkerTask<WorkerRequestType.DROP_FILE, string, null>(WorkerRequestType.DROP_FILE, name);\n return await this.postTask(task);\n }\n /** Try to drop files */\n public async dropFiles(names?: string[]): Promise<null> {\n const task = new WorkerTask<WorkerRequestType.DROP_FILES, string[] | undefined, null>(WorkerRequestType.DROP_FILES, names);\n return await this.postTask(task);\n }\n /** Flush all files */\n public async flushFiles(): Promise<null> {\n const task = new WorkerTask<WorkerRequestType.FLUSH_FILES, null, null>(WorkerRequestType.FLUSH_FILES, null);\n return await this.postTask(task);\n }\n\n /** Open the database */\n public async instantiate(\n mainModuleURL: string,\n pthreadWorkerURL: string | null = null,\n progress?: (progress: InstantiationProgress) => void,\n ): Promise<null> {\n if (progress) {\n this._onInstantiationProgress.push(progress);\n }\n // Haybarn: the worker only counts download progress when someone listens (third element)\n const task = new WorkerTask<WorkerRequestType.INSTANTIATE, [string, string | null, boolean?], null>(\n WorkerRequestType.INSTANTIATE,\n [mainModuleURL, pthreadWorkerURL, this._onInstantiationProgress.length > 0],\n );\n return await this.postTask(task);\n }\n\n /** Get the version */\n public async getVersion(): Promise<string> {\n const task = new WorkerTask<WorkerRequestType.GET_VERSION, null, string>(WorkerRequestType.GET_VERSION, null);\n const version = await this.postTask(task);\n return version;\n }\n\n /** Get the feature flags */\n public async getFeatureFlags(): Promise<number> {\n const task = new WorkerTask<WorkerRequestType.GET_FEATURE_FLAGS, null, number>(\n WorkerRequestType.GET_FEATURE_FLAGS,\n null,\n );\n const feature = await this.postTask(task);\n return feature;\n }\n\n /** Open a new database */\n public async open(config: DuckDBConfig): Promise<void> {\n this._config = config;\n this.forgetConnections();\n const task = new WorkerTask<WorkerRequestType.OPEN, DuckDBConfig, null>(WorkerRequestType.OPEN, config);\n await this.postTask(task);\n }\n\n /**\n * Haybarn: download, hash and compile extensions ahead of LOAD.\n *\n * In browsers, LOAD downloads each extension synchronously and hashes it with SHA-256 compiled to wasm before\n * checking its signature, then compiles it. This does that work in the worker ahead of time: the downloads run in\n * parallel, the hash is computed with WebCrypto and the module is compiled with `WebAssembly.compileStreaming`. A\n * later `LOAD <name>` that resolves to the same URL then only checks the signature, against that hash, and\n * dlopen uses the compiled module once the check has passed. Settings that change the URL (such as\n * `custom_extension_repository`, or `INSTALL <name> FROM <repository>` / `VERSION`) must come first.\n *\n * Call it while setting up the session, before running queries. Requests sent while a prefetch runs wait for it.\n *\n * Resolves to the names that are held for LOAD, once every download has finished, failed or timed out (after\n * `timeoutMs`, 30 seconds by default). A name that can't be resolved or downloaded is skipped, leaving the\n * download to LOAD, which reports any error; so are extensions that are already loaded. Each prefetched extension\n * serves one LOAD, at most 256 MiB is held for LOADs that haven't run yet, and `reset()` or `open()` drops what no\n * LOAD took. Does nothing in Node.js.\n */\n public async prefetchExtensions(names: string[], timeoutMs?: number): Promise<string[]> {\n const task = new WorkerTask<WorkerRequestType.PREFETCH_EXTENSIONS, [string[], number | undefined], string[]>(\n WorkerRequestType.PREFETCH_EXTENSIONS,\n [names, timeoutMs],\n );\n return await this.postTask(task);\n }\n\n /** Tokenize a script text */\n public async tokenize(text: string): Promise<ScriptTokens> {\n const task = new WorkerTask<WorkerRequestType.TOKENIZE, string, ScriptTokens>(WorkerRequestType.TOKENIZE, text);\n const tokens = await this.postTask(task);\n return tokens;\n }\n\n /** Connect to the database */\n public async connectInternal(): Promise<number> {\n const task = new WorkerTask<WorkerRequestType.CONNECT, null, ConnectionID>(WorkerRequestType.CONNECT, null);\n return await this.postTask(task);\n }\n\n /** Connect to the database */\n public async connect(): Promise<AsyncDuckDBConnection> {\n const cid = await this.connectInternal();\n // A cancel must reach a query that runs inside a worker call, which no message does: keep the flag at hand\n if (typeof SharedArrayBuffer !== 'undefined') {\n const handle = await this.getInterruptHandle(cid);\n if (handle !== null) this._interruptHandles.set(cid, handle);\n }\n return new AsyncDuckDBConnection(this, cid);\n }\n\n /** Disconnect from the database */\n public async disconnect(conn: ConnectionID): Promise<void> {\n this._interruptHandles.delete(conn);\n this.endPendingQuery(conn);\n const task = new WorkerTask<WorkerRequestType.DISCONNECT, ConnectionID, null>(\n WorkerRequestType.DISCONNECT,\n conn,\n );\n await this.postTask(task);\n }\n\n /** Run a query */\n public async runQuery(conn: ConnectionID, text: string): Promise<Uint8Array> {\n if( this.shouldOPFSFileHandling() ){\n const files = await this.registerOPFSFileFromSQL(text);\n try {\n return await this._runQueryAsync(conn, text);\n } finally {\n if( files.length > 0 ){\n await this.dropFiles(files);\n }\n }\n } else {\n return await this._runQueryAsync(conn, text);\n }\n }\n\n private async _runQueryAsync(conn: ConnectionID, text: string): Promise<Uint8Array> {\n const task = new WorkerTask<WorkerRequestType.RUN_QUERY, [ConnectionID, string], Uint8Array>(\n WorkerRequestType.RUN_QUERY,\n [conn, text],\n );\n return await this.postTask(task);\n }\n\n /** Start a pending query */\n public async startPendingQuery(\n conn: ConnectionID,\n text: string,\n allowStreamResult: boolean = false,\n ): Promise<Uint8Array | null> {\n if( this.shouldOPFSFileHandling() ){\n const files = await this.registerOPFSFileFromSQL(text);\n try {\n return await this._startPendingQueryAsync(conn, text, allowStreamResult);\n } finally {\n if( files.length > 0 ){\n await this.dropFiles(files);\n }\n }\n } else {\n return await this._startPendingQueryAsync(conn, text, allowStreamResult);\n }\n }\n\n private async _startPendingQueryAsync(\n conn: ConnectionID,\n text: string,\n allowStreamResult: boolean = false,\n ): Promise<Uint8Array | null> {\n const task = new WorkerTask<\n WorkerRequestType.START_PENDING_QUERY,\n [ConnectionID, string, boolean],\n Uint8Array | null\n >(WorkerRequestType.START_PENDING_QUERY, [conn, text, allowStreamResult]);\n this.beginPendingQuery(conn);\n return await this.trackPendingQuery(conn, this.postTask(task));\n }\n\n /** Poll a pending query */\n public async pollPendingQuery(conn: ConnectionID): Promise<Uint8Array | null> {\n if (this.takeCancelFlag() && this._pendingQueries.has(conn)) {\n // Cancelled through registerCancelSAB before this poll was sent: the poll reports the cancel\n await this.cancelPendingQuery(conn);\n }\n const task = new WorkerTask<WorkerRequestType.POLL_PENDING_QUERY, ConnectionID, Uint8Array | null>(\n WorkerRequestType.POLL_PENDING_QUERY,\n conn,\n );\n return await this.trackPendingQuery(conn, this.postTask(task));\n }\n /**\n * Cancel a pending query.\n *\n * On the threads bundle the worker runs a poll to its end before it reads another message, so the query is\n * interrupted through shared memory first (getInterruptHandle): a running poll stops at the engine's next check\n * and fails with an interrupt error, and in-flight HTTP requests of the query are abandoned. The cancel message\n * then ends the query in the worker, if the poll has not already ended it.\n */\n public async cancelPendingQuery(conn: ConnectionID): Promise<boolean> {\n const handle = this._interruptHandles.get(conn);\n const interrupted = handle !== undefined && this._pendingQueries.has(conn);\n if (interrupted) {\n interruptConnection(handle);\n }\n this.endPendingQuery(conn);\n const task = new WorkerTask<WorkerRequestType.CANCEL_PENDING_QUERY, ConnectionID, boolean>(\n WorkerRequestType.CANCEL_PENDING_QUERY,\n conn,\n );\n const cancelled = await this.postTask(task);\n return cancelled || interrupted;\n }\n\n /**\n * The connection's interrupt flag, or null when the wasm memory is not shared (the base bundle). Then\n * `interruptConnection(handle)` interrupts what runs on the connection from any thread, also while the worker is\n * inside the call that runs it and no message reaches it.\n */\n public async getInterruptHandle(conn: ConnectionID): Promise<InterruptHandle | null> {\n const cached = this._interruptHandles.get(conn);\n if (cached) return cached;\n const task = new WorkerTask<WorkerRequestType.GET_INTERRUPT_HANDLE, ConnectionID, InterruptHandle | null>(\n WorkerRequestType.GET_INTERRUPT_HANDLE,\n conn,\n );\n return await this.postTask(task);\n }\n\n /**\n * The connection's query progress slot, or null when the wasm memory is not shared (the base bundle). Read it\n * with `readQueryProgress(handle)`, also while a query runs. The engine reports progress only with\n * `SET enable_progress_bar = true`.\n */\n public async getProgressHandle(conn: ConnectionID): Promise<QueryProgressHandle | null> {\n const task = new WorkerTask<WorkerRequestType.GET_PROGRESS_HANDLE, ConnectionID, QueryProgressHandle | null>(\n WorkerRequestType.GET_PROGRESS_HANDLE,\n conn,\n );\n return await this.postTask(task);\n }\n\n /**\n * The progress of the connection's query as the engine last reported it, on every bundle. The worker answers\n * between two calls only: on the threads bundle, read a running query's progress with getProgressHandle.\n */\n public async getQueryProgress(conn: ConnectionID): Promise<QueryProgress | null> {\n const task = new WorkerTask<WorkerRequestType.GET_QUERY_PROGRESS, ConnectionID, QueryProgress | null>(\n WorkerRequestType.GET_QUERY_PROGRESS,\n conn,\n );\n return await this.postTask(task);\n }\n\n /**\n * Register a SharedArrayBuffer of at least 4 bytes through which any thread can cancel the most recently started\n * pending query: `Atomics.store(new Int32Array(sab), 0, 1)`. The flag is checked before each poll and every\n * 50 ms while a pending query runs; a cancel resets it to 0 and goes through `cancelPendingQuery`, so on the\n * threads bundle it also interrupts a poll that is running. For a specific connection use `cancelSent()` or\n * `getInterruptHandle`. Registering again replaces the buffer.\n */\n public registerCancelSAB(sab: SharedArrayBuffer): void {\n if (typeof SharedArrayBuffer === 'undefined') {\n throw new TypeError(\n 'registerCancelSAB requires SharedArrayBuffer support (cross-origin isolation must be enabled)',\n );\n }\n if (!(sab instanceof SharedArrayBuffer)) {\n throw new TypeError('registerCancelSAB requires a SharedArrayBuffer (got a non-shared buffer)');\n }\n if (sab.byteLength < 4) {\n throw new RangeError(`registerCancelSAB requires at least 4 bytes for the Int32 flag (got ${sab.byteLength})`);\n }\n this._cancelFlag = new Int32Array(sab, 0, 1);\n this.updateCancelWatcher();\n }\n\n /** A pending query starts on the connection */\n protected beginPendingQuery(conn: ConnectionID): void {\n // Re-added at the end: the most recently started query is the one registerCancelSAB cancels\n this._pendingQueries.delete(conn);\n this._pendingQueries.add(conn);\n this.updateCancelWatcher();\n }\n /** The connection's pending query ended (it has a result, failed, or was cancelled) */\n protected endPendingQuery(conn: ConnectionID): void {\n this._pendingQueries.delete(conn);\n this.updateCancelWatcher();\n }\n /** Track the end of a pending query through the response to its start or a poll */\n protected async trackPendingQuery(\n conn: ConnectionID,\n response: Promise<Uint8Array | null>,\n ): Promise<Uint8Array | null> {\n try {\n const header = await response;\n if (header !== null) this.endPendingQuery(conn);\n return header;\n } catch (e) {\n this.endPendingQuery(conn);\n throw e;\n }\n }\n /** Forget all connections, the database they belonged to is gone */\n protected forgetConnections(): void {\n this._interruptHandles.clear();\n this._pendingQueries.clear();\n this.updateCancelWatcher();\n }\n /** Consume a cancel requested through registerCancelSAB */\n protected takeCancelFlag(): boolean {\n if (this._cancelFlag === null) return false;\n return Atomics.compareExchange(this._cancelFlag, 0, 1, 0) === 1;\n }\n /** Watch the flag of registerCancelSAB while a pending query runs */\n protected updateCancelWatcher(): void {\n const watch = this._cancelFlag !== null && this._pendingQueries.size > 0;\n if (watch && this._cancelWatcher === null) {\n this._cancelWatcher = setInterval(() => {\n let latest: ConnectionID | undefined;\n for (const conn of this._pendingQueries) latest = conn;\n if (latest === undefined || !this.takeCancelFlag()) return;\n this.cancelPendingQuery(latest).catch(e => console.error('[cancel-sab] cancelPendingQuery failed:', e));\n }, CANCEL_SAB_POLL_MS);\n } else if (!watch && this._cancelWatcher !== null) {\n clearInterval(this._cancelWatcher);\n this._cancelWatcher = null;\n }\n }\n\n /** Fetch query results */\n public async fetchQueryResults(conn: ConnectionID): Promise<Uint8Array | null> {\n const task = new WorkerTask<WorkerRequestType.FETCH_QUERY_RESULTS, ConnectionID, Uint8Array | null>(\n WorkerRequestType.FETCH_QUERY_RESULTS,\n conn,\n );\n return await this.postTask(task);\n }\n\n /** Get table names */\n public async getTableNames(conn: number, text: string): Promise<string[]> {\n const task = new WorkerTask<WorkerRequestType.GET_TABLE_NAMES, [number, string], string[]>(\n WorkerRequestType.GET_TABLE_NAMES,\n [conn, text],\n );\n return await this.postTask(task);\n }\n\n /** Prepare a statement and return its identifier */\n public async createPrepared(conn: number, text: string): Promise<number> {\n const task = new WorkerTask<WorkerRequestType.CREATE_PREPARED, [number, string], number>(\n WorkerRequestType.CREATE_PREPARED,\n [conn, text],\n );\n return await this.postTask(task);\n }\n /** Close a prepared statement */\n public async closePrepared(conn: number, statement: number): Promise<void> {\n const task = new WorkerTask<WorkerRequestType.CLOSE_PREPARED, [number, number], null>(\n WorkerRequestType.CLOSE_PREPARED,\n [conn, statement],\n );\n await this.postTask(task);\n }\n /** Execute a prepared statement and return the full result */\n public async runPrepared(conn: number, statement: number, params: any[]): Promise<Uint8Array> {\n const task = new WorkerTask<WorkerRequestType.RUN_PREPARED, [ConnectionID, number, any[]], Uint8Array>(\n WorkerRequestType.RUN_PREPARED,\n [conn, statement, params],\n );\n return await this.postTask(task);\n }\n /** Execute a prepared statement and stream the result */\n public async sendPrepared(conn: number, statement: number, params: any[]): Promise<Uint8Array> {\n const task = new WorkerTask<WorkerRequestType.SEND_PREPARED, [ConnectionID, number, any[]], Uint8Array>(\n WorkerRequestType.SEND_PREPARED,\n [conn, statement, params],\n );\n return await this.postTask(task);\n }\n /** Glob file infos */\n public async globFiles(path: string): Promise<WebFile[]> {\n const task = new WorkerTask<WorkerRequestType.GLOB_FILE_INFOS, string, WebFile[]>(\n WorkerRequestType.GLOB_FILE_INFOS,\n path,\n );\n return await this.postTask(task);\n }\n /** Register file text */\n public async registerFileText(name: string, text: string): Promise<void> {\n const buffer = TEXT_ENCODER.encode(text);\n await this.registerFileBuffer(name, buffer);\n }\n /** Register a file path. */\n public async registerFileURL(\n name: string,\n url: string,\n proto: DuckDBDataProtocol,\n directIO: boolean,\n ): Promise<void> {\n if (url === undefined) {\n url = name;\n }\n const task = new WorkerTask<\n WorkerRequestType.REGISTER_FILE_URL,\n [string, string, DuckDBDataProtocol, boolean],\n null\n >(WorkerRequestType.REGISTER_FILE_URL, [name, url, proto, directIO]);\n await this.postTask(task);\n }\n\n /** Register an empty file buffer. */\n public async registerEmptyFileBuffer(name: string): Promise<void> {\n /*\n const task = new WorkerTask<WorkerRequestType.REGISTER_FILE_BUFFER, [string, Uint8Array], null>(\n WorkerRequestType.REGISTER_FILE_BUFFER,\n [name, new Uint8Array()],\n );\n await this.postTask(task);\n*/\n }\n\n /** Register a file buffer. */\n public async registerFileBuffer(name: string, buffer: Uint8Array): Promise<void> {\n const task = new WorkerTask<WorkerRequestType.REGISTER_FILE_BUFFER, [string, Uint8Array], null>(\n WorkerRequestType.REGISTER_FILE_BUFFER,\n [name, buffer],\n );\n await this.postTask(task, [buffer.buffer]);\n }\n\n /** Register a file handle. */\n public async registerFileHandle<HandleType>(\n name: string,\n handle: HandleType,\n protocol: DuckDBDataProtocol,\n directIO: boolean,\n ): Promise<void> {\n const task = new WorkerTask<\n WorkerRequestType.REGISTER_FILE_HANDLE,\n [string, any, DuckDBDataProtocol, boolean],\n null\n >(WorkerRequestType.REGISTER_FILE_HANDLE, [name, handle, protocol, directIO]);\n await this.postTask(task, []);\n }\n\n /** Prepare an opfs:// file (or the files a glob pattern matches) for the next queries, returns their names.\n * Registered files are held open until they are dropped, for writing unless `mode` is 'read' */\n public async registerOPFSFileName(name: string, mode: OPFSAccessMode = 'write'): Promise<string[]> {\n const task = new WorkerTask<WorkerRequestType.REGISTER_OPFS_FILE_NAME, [string, OPFSAccessMode], string[]>(\n WorkerRequestType.REGISTER_OPFS_FILE_NAME,\n [name, mode],\n );\n return await this.postTask(task, []);\n }\n\n /** Enable file statistics */\n public async collectFileStatistics(name: string, enable: boolean): Promise<void> {\n const task = new WorkerTask<WorkerRequestType.COLLECT_FILE_STATISTICS, [string, boolean], null>(\n WorkerRequestType.COLLECT_FILE_STATISTICS,\n [name, enable],\n );\n await this.postTask(task, []);\n }\n\n /** Export file statistics */\n public async exportFileStatistics(name: string): Promise<FileStatistics> {\n const task = new WorkerTask<WorkerRequestType.EXPORT_FILE_STATISTICS, string, FileStatistics>(\n WorkerRequestType.EXPORT_FILE_STATISTICS,\n name,\n );\n return await this.postTask(task, []);\n }\n\n /** Copy a file to a buffer. */\n public async copyFileToBuffer(name: string): Promise<Uint8Array> {\n const task = new WorkerTask<WorkerRequestType.COPY_FILE_TO_BUFFER, string, Uint8Array>(\n WorkerRequestType.COPY_FILE_TO_BUFFER,\n name,\n );\n return await this.postTask(task);\n }\n\n /** Copy a file to a path. */\n public async copyFileToPath(name: string, path: string): Promise<void> {\n const task = new WorkerTask<WorkerRequestType.COPY_FILE_TO_PATH, [string, string], null>(\n WorkerRequestType.COPY_FILE_TO_PATH,\n [name, path],\n );\n await this.postTask(task);\n }\n\n /** Insert arrow from an ipc stream */\n public async insertArrowFromIPCStream(\n conn: ConnectionID,\n buffer: Uint8Array,\n options?: ArrowInsertOptions,\n ): Promise<void> {\n if (buffer.length == 0) return;\n // Pass to the worker\n const task = new WorkerTask<\n WorkerRequestType.INSERT_ARROW_FROM_IPC_STREAM,\n [number, Uint8Array, ArrowInsertOptions | undefined],\n null\n >(WorkerRequestType.INSERT_ARROW_FROM_IPC_STREAM, [conn, buffer, options]);\n await this.postTask(task, [buffer.buffer]);\n }\n /** Insert a csv file */\n public async insertCSVFromPath(conn: ConnectionID, path: string, options: CSVInsertOptions): Promise<void> {\n // Flatten the table options\n if (options.columns !== undefined) {\n const out = [];\n for (const k in options.columns) {\n const type = options.columns[k];\n out.push(arrowToSQLField(k, type));\n }\n options.columnsFlat = out;\n delete options.columns;\n }\n\n // Pass to the worker\n const task = new WorkerTask<WorkerRequestType.INSERT_CSV_FROM_PATH, [number, string, CSVInsertOptions], null>(\n WorkerRequestType.INSERT_CSV_FROM_PATH,\n [conn, path, options],\n );\n await this.postTask(task);\n }\n /** Insert a json file */\n public async insertJSONFromPath(conn: ConnectionID, path: string, options: JSONInsertOptions): Promise<void> {\n // Flatten the table options\n if (options.columns !== undefined) {\n const out = [];\n for (const k in options.columns) {\n const type = options.columns[k];\n out.push(arrowToSQLField(k, type));\n }\n options.columnsFlat = out;\n delete options.columns;\n }\n\n // Pass to the worker\n const task = new WorkerTask<WorkerRequestType.INSERT_JSON_FROM_PATH, [number, string, JSONInsertOptions], null>(\n WorkerRequestType.INSERT_JSON_FROM_PATH,\n [conn, path, options],\n );\n await this.postTask(task);\n }\n\n /** opfs:// files named in SQL are prepared ahead of the query when the config asks for it, whether the\n * database itself lives in OPFS or not */\n private shouldOPFSFileHandling(): boolean {\n return this.config.opfs?.fileHandling == 'auto';\n }\n\n private async registerOPFSFileFromSQL(text: string) {\n const files = searchOPFSFiles(text);\n // A database that is attached is written to, everything else is read\n const mode: OPFSAccessMode = /\\bATTACH\\b/i.test(text) ? 'write' : 'read';\n const result: string[] = [];\n for (const file of files) {\n try {\n result.push(...(await this.registerOPFSFileName(file, mode)));\n } catch (e) {\n console.error(e);\n throw new Error('File Not found:' + file);\n }\n }\n return result;\n }\n}\n", "import { DuckDBModule } from './duckdb_module';\nimport { Logger } from '../log';\nimport { OPFSAccessMode } from './opfs_scratch';\nimport { UDFFunction } from './udf_function';\nimport * as udf_rt from './udf_runtime';\n\n/** Wrapper for TextDecoder to support shared array buffers */\nfunction TextDecoderWrapper(): (input?: BufferSource) => string {\n const decoder = new TextDecoder();\n return (data: any) => {\n if (typeof SharedArrayBuffer !== 'undefined' && data.buffer instanceof SharedArrayBuffer) {\n data = new Uint8Array(data);\n }\n return decoder.decode(data);\n };\n}\n/** Helper to decode text */\nexport const decodeText = TextDecoderWrapper();\n\n/** Copy a buffer */\nexport function failWith(mod: DuckDBModule, msg: string): void {\n console.error(`FAIL WITH: ${msg}`);\n mod.ccall('duckdb_web_fail_with', null, ['string'], [msg]);\n}\n\n/** Copy a buffer */\nexport function copyBuffer(mod: DuckDBModule, begin: number, length: number): Uint8Array {\n const buffer = mod.HEAPU8.subarray(begin, begin + length);\n const copy = new Uint8Array(new ArrayBuffer(buffer.byteLength));\n copy.set(buffer);\n return copy;\n}\n\n/** Decode a string */\nexport function readString(mod: DuckDBModule, begin: number, length: number): string {\n return decodeText(mod.HEAPU8.subarray(begin, begin + length));\n}\n\n/** The data protocol */\nexport enum DuckDBDataProtocol {\n BUFFER = 0,\n NODE_FS = 1,\n BROWSER_FILEREADER = 2,\n BROWSER_FSACCESS = 3,\n HTTP = 4,\n S3 = 5,\n /** Files held by the runtime outside the WASM heap (js_buffer://) */\n JS_BUFFER = 6,\n}\n\n/** File flags for opening files*/\nexport enum FileFlags {\n //! Open file with read access\n FILE_FLAGS_READ = 1 << 0,\n //! Open file with write access\n FILE_FLAGS_WRITE = 1 << 1,\n //! Use direct IO when reading/writing to the file\n FILE_FLAGS_DIRECT_IO = 1 << 2,\n //! Create file if not exists, can only be used together with WRITE\n FILE_FLAGS_FILE_CREATE = 1 << 3,\n //! Always create a new file. If a file exists, the file is truncated. Cannot be used together with CREATE.\n FILE_FLAGS_FILE_CREATE_NEW = 1 << 4,\n //! Open file in append mode\n FILE_FLAGS_APPEND = 1 << 5,\n FILE_FLAGS_PRIVATE = 1 << 6,\n FILE_FLAGS_NULL_IF_NOT_EXISTS = 1 << 7,\n FILE_FLAGS_PARALLEL_ACCESS = 1 << 8,\n FILE_FLAGS_EXCLUSIVE_CREATE = 1 << 9,\n FILE_FLAGS_NULL_IF_EXISTS = 1 << 10\n}\n\n/** Configuration for the AWS S3 Filesystem */\nexport interface S3Config {\n region?: string;\n endpoint?: string;\n accessKeyId?: string;\n secretAccessKey?: string;\n sessionToken?: string;\n}\n\n/** An info for a file registered with DuckDB */\nexport interface DuckDBFileInfo {\n cacheEpoch: number;\n fileId: number;\n fileName: string;\n dataProtocol: DuckDBDataProtocol;\n dataUrl: string | null;\n reliableHeadRequests?: boolean;\n allowFullHttpReads?: boolean;\n forceFullHttpReads?: boolean;\n s3Config?: S3Config;\n}\n\n/** Global info for all files registered with DuckDB */\nexport interface DuckDBGlobalFileInfo {\n cacheEpoch: number;\n reliableHeadRequests?: boolean;\n allowFullHttpReads?: boolean;\n forceFullHttpReads?: boolean;\n s3Config?: S3Config;\n}\n\nexport interface PreparedDBFileHandle {\n path: string;\n handle: any;\n fromCached: boolean;\n}\n\n/** Call a function with packed response buffer */\nexport function callSRet(\n mod: DuckDBModule,\n funcName: string,\n argTypes: Array<Emscripten.JSType>,\n args: Array<any>,\n): [number, number, number] {\n const stackPointer = mod.stackSave();\n\n // Allocate the packed response buffer\n const response = mod.stackAlloc(3 * 8);\n argTypes.unshift('number');\n args.unshift(response);\n\n // Do the call\n mod.ccall(funcName, null, argTypes, args);\n\n // Read the response\n const status = mod.HEAPF64[(response >>> 3) + 0];\n const data = mod.HEAPF64[(response >>> 3) + 1];\n const dataSize = mod.HEAPF64[(response >>> 3) + 2];\n\n // Restore the stack\n mod.stackRestore(stackPointer);\n return [status, data, dataSize];\n}\n\n/** Drop response buffers */\nexport function dropResponseBuffers(mod: DuckDBModule): void {\n mod.ccall('duckdb_web_clear_response', null, [], []);\n}\n\n/** The duckdb runtime */\nexport interface DuckDBRuntime {\n _files?: Map<string, any>;\n _udfFunctions: Map<number, UDFFunction>;\n\n // Receive the logger of the bindings, file operations are logged at debug level\n setLogger?(logger: Logger): void;\n\n // Test a platform feature\n testPlatformFeature(mod: DuckDBModule, feature: number): boolean;\n\n // File APIs with dedicated file identifier\n getDefaultDataProtocol(mod: DuckDBModule): number;\n openFile(mod: DuckDBModule, fileId: number, flags: FileFlags): void;\n syncFile(mod: DuckDBModule, fileId: number): void;\n closeFile(mod: DuckDBModule, fileId: number): void;\n dropFile(mod: DuckDBModule, fileNamePtr: number, fileNameLen: number): void;\n getLastFileModificationTime(mod: DuckDBModule, fileId: number): number;\n truncateFile(mod: DuckDBModule, fileId: number, newSize: number): void;\n readFile(mod: DuckDBModule, fileId: number, buffer: number, bytes: number, location: number): number;\n writeFile(mod: DuckDBModule, fileId: number, buffer: number, bytes: number, location: number): number;\n\n // File APIs with path parameter\n removeDirectory(mod: DuckDBModule, pathPtr: number, pathLen: number): void;\n checkDirectory(mod: DuckDBModule, pathPtr: number, pathLen: number): boolean;\n createDirectory(mod: DuckDBModule, pathPtr: number, pathLen: number): void;\n listDirectoryEntries(mod: DuckDBModule, pathPtr: number, pathLen: number): boolean;\n glob(mod: DuckDBModule, pathPtr: number, pathLen: number): void;\n moveFile(mod: DuckDBModule, fromPtr: number, fromLen: number, toPtr: number, toLen: number): void;\n checkFile(mod: DuckDBModule, pathPtr: number, pathLen: number): boolean;\n removeFile(mod: DuckDBModule, pathPtr: number, pathLen: number): void;\n\n // Prepare a file handle that could only be acquired aschronously\n prepareFileHandle?: (path: string, protocol: DuckDBDataProtocol) => Promise<PreparedDBFileHandle[]>;\n prepareFileHandles?: (\n path: string[],\n protocol: DuckDBDataProtocol,\n mode?: OPFSAccessMode,\n ) => Promise<PreparedDBFileHandle[]>;\n prepareDBFileHandle?: (path: string, protocol: DuckDBDataProtocol) => Promise<PreparedDBFileHandle[]>;\n /** Finish file operations that could only be completed asynchronously, called between queries */\n checkpointFiles?: () => Promise<void>;\n /** Mount the origin private file system, a no-op where there is none */\n mountOPFS?: () => Promise<void>;\n\n // Internal API - experimental\n progressUpdate(final: number, percentage: number, iteration: number): void;\n\n // Call a scalar UDF function\n callScalarUDF(\n mod: DuckDBModule,\n response: number,\n funcId: number,\n descPtr: number,\n descSize: number,\n ptrsPtr: number,\n ptrsSize: number,\n ): void;\n}\n\nexport const DEFAULT_RUNTIME: DuckDBRuntime = {\n _udfFunctions: new Map(),\n\n testPlatformFeature: (_mod: DuckDBModule, _feature: number): boolean => false,\n getDefaultDataProtocol: (_mod: DuckDBModule): number => DuckDBDataProtocol.BUFFER,\n openFile: (_mod: DuckDBModule, _fileId: number, flags: FileFlags): void => {},\n syncFile: (_mod: DuckDBModule, _fileId: number): void => {},\n closeFile: (_mod: DuckDBModule, _fileId: number): void => {},\n dropFile: (_mod: DuckDBModule, _fileNamePtr: number, _fileNameLen: number): void => {},\n getLastFileModificationTime: (_mod: DuckDBModule, _fileId: number): number => {\n return 0;\n },\n progressUpdate: (_final: number, _percentage: number, _iteration: number): void => {\n return;\n },\n truncateFile: (_mod: DuckDBModule, _fileId: number, _newSize: number): void => {},\n readFile: (_mod: DuckDBModule, _fileId: number, _buffer: number, _bytes: number, _location: number): number => {\n return 0;\n },\n writeFile: (_mod: DuckDBModule, _fileId: number, _buffer: number, _bytes: number, _location: number): number => {\n return 0;\n },\n\n removeDirectory: (_mod: DuckDBModule, _pathPtr: number, _pathLen: number): void => {},\n checkDirectory: (_mod: DuckDBModule, _pathPtr: number, _pathLen: number): boolean => {\n return false;\n },\n createDirectory: (_mod: DuckDBModule, _pathPtr: number, _pathLen: number): void => {},\n listDirectoryEntries: (_mod: DuckDBModule, _pathPtr: number, _pathLen: number): boolean => {\n return false;\n },\n glob: (_mod: DuckDBModule, _pathPtr: number, _pathLen: number): void => {},\n moveFile: (_mod: DuckDBModule, _fromPtr: number, _fromLen: number, _toPtr: number, _toLen: number): void => {},\n checkFile: (_mod: DuckDBModule, _pathPtr: number, _pathLen: number): boolean => {\n return false;\n },\n removeFile: (_mod: DuckDBModule, _pathPtr: number, _pathLen: number): void => {},\n callScalarUDF: (\n mod: DuckDBModule,\n response: number,\n funcId: number,\n descPtr: number,\n descSize: number,\n ptrsPtr: number,\n ptrsSize: number,\n ): void => {\n udf_rt.callScalarUDF(DEFAULT_RUNTIME, mod, response, funcId, descPtr, descSize, ptrsPtr, ptrsSize);\n },\n};\n", "// Haybarn: prefetching of wasm extensions inside the worker.\n//\n// LOAD runs synchronously inside the engine: the extension provider (lib/src/extension_provider.cc) downloads the\n// extension with a synchronous XHR and hashes it with SHA-256 compiled to wasm before checking its signature.\n// Prefetching does that work ahead of time and asynchronously: all downloads run in parallel, the signature hash is\n// computed with WebCrypto, and the module is compiled with WebAssembly.compileStreaming (which also lets Chrome cache\n// the compiled code). The provider takes the entry for its URL, so it only has to check the RSA signature against the\n// hash, and dlopen instantiates the compiled module once that check has passed (scripts/patch_dylink_glue.cjs).\n//\n// The hash is computed here over exactly the bytes the provider is given, and neither ever leaves this worker, so\n// this trusts nothing the synchronous path didn't already trust. The signature check itself stays in the engine.\n//\n// This runs in the worker's event loop, between requests: the dispatcher processes requests in order, so a request\n// sent while a prefetch runs waits for it. On the threads bundle the provider fetches on the main runtime thread,\n// which is this one, so the entries are where it looks for them.\n\n/** The size of the signature at the end of an extension file */\nconst SIGNATURE_SIZE = 256;\n/** The chunk size of the two-level hash. Must match the engine's verifier (extension_load.cpp). */\nconst HASH_CHUNK_SIZE = 1024 * 1024;\n/** The most bytes held for LOADs that haven't taken them; prefetches beyond it are left to LOAD */\nconst MAX_HELD_BYTES = 256 * 1024 * 1024;\n/** How long a download may take before it is left to LOAD. Requests wait for prefetches, so one must never hang. */\nexport const PREFETCH_TIMEOUT_MS = 30_000;\n\n/** A prefetched extension */\nexport interface PrefetchedExtension {\n /** The file, as LOAD would have downloaded it */\n bytes: Uint8Array;\n /** SHA-256 over the SHA-256 hashes of each 1 MiB chunk of the file without its signature */\n hash: Uint8Array | null;\n /** The module compiled from the same download, or null */\n module: WebAssembly.Module | null;\n}\n\n/** Prefetched extensions by URL, until a LOAD takes them */\nconst prefetched = new Map<string, PrefetchedExtension>();\n/** Prefetches that are still running, by URL */\nconst running = new Map<string, Promise<boolean>>();\n/** The bytes held in `prefetched` */\nlet heldBytes = 0;\n/** Bumped by clearPrefetchedExtensions, so prefetches still running then don't add their entries after it */\nlet generation = 0;\n\n/** Compute the engine's two-level signature hash of an extension file */\nexport async function computeExtensionHash(bytes: Uint8Array): Promise<Uint8Array | null> {\n if (bytes.byteLength < SIGNATURE_SIZE || typeof crypto === 'undefined' || !crypto.subtle) {\n return null;\n }\n const end = bytes.byteLength - SIGNATURE_SIZE;\n const chunks: Promise<ArrayBuffer>[] = [];\n for (let offset = 0; offset < end; offset += HASH_CHUNK_SIZE) {\n chunks.push(crypto.subtle.digest('SHA-256', bytes.subarray(offset, Math.min(end, offset + HASH_CHUNK_SIZE))));\n }\n const hashes = await Promise.all(chunks);\n const concatenated = new Uint8Array(hashes.length * 32);\n hashes.forEach((h, i) => concatenated.set(new Uint8Array(h), i * 32));\n return new Uint8Array(await crypto.subtle.digest('SHA-256', concatenated));\n}\n\n/**\n * Download, hash and compile one extension. Resolves to whether it is now held for LOAD. Failures are dropped: LOAD\n * then downloads it itself and reports the error.\n */\nasync function prefetchOne(url: string, timeoutMs: number): Promise<boolean> {\n const startedIn = generation;\n try {\n // The signal also aborts reading the body, and with it the compile\n const signal = typeof AbortSignal.timeout === 'function' ? AbortSignal.timeout(timeoutMs) : undefined;\n const response = await fetch(url, { signal });\n // LOAD's XHR only accepts 200\n if (response.status !== 200) {\n return false;\n }\n // Compile from the response itself and read the bytes from a clone, so both come from one download. Without a\n // module, dlopen compiles the bytes as before.\n let compiling: Promise<WebAssembly.Module | null> = Promise.resolve(null);\n let body = response;\n if (typeof WebAssembly.compileStreaming === 'function') {\n body = response.clone();\n compiling = WebAssembly.compileStreaming(response).catch(() => null);\n }\n const bytes = new Uint8Array(await body.arrayBuffer());\n // Without a hash the provider hashes the file itself\n const [hash, module] = await Promise.all([computeExtensionHash(bytes).catch(() => null), compiling]);\n if (generation !== startedIn || heldBytes + bytes.byteLength > MAX_HELD_BYTES) {\n return false;\n }\n prefetched.set(url, { bytes, hash, module });\n heldBytes += bytes.byteLength;\n return true;\n } catch (e) {\n // Network error or timeout: leave it to LOAD\n return false;\n } finally {\n running.delete(url);\n }\n}\n\n/**\n * Prefetch extensions by URL. Resolves to the URLs that are held for LOAD once every download has finished, failed\n * or timed out; never rejects.\n */\nexport async function prefetchExtensions(urls: string[], timeoutMs: number = PREFETCH_TIMEOUT_MS): Promise<string[]> {\n installPrefetchHook();\n const work: Promise<boolean>[] = [];\n for (const url of urls) {\n if (prefetched.has(url)) {\n work.push(Promise.resolve(true));\n continue;\n }\n let p = running.get(url);\n if (!p) {\n p = prefetchOne(url, timeoutMs);\n running.set(url, p);\n }\n work.push(p);\n }\n const held = await Promise.all(work);\n return urls.filter((_, i) => held[i]);\n}\n\n/** Take the prefetched entry for a URL. Called by the provider's LOAD; each entry serves one LOAD. */\nexport function takePrefetchedExtension(url: string): PrefetchedExtension | null {\n const entry = prefetched.get(url);\n if (!entry) {\n return null;\n }\n prefetched.delete(url);\n heldBytes -= entry.bytes.byteLength;\n return entry;\n}\n\n/** Drop prefetched extensions that no LOAD took, including those still downloading */\nexport function clearPrefetchedExtensions(): void {\n prefetched.clear();\n heldBytes = 0;\n ++generation;\n}\n\n/** Make the prefetched entries reachable from the provider's LOAD */\nexport function installPrefetchHook(): void {\n (globalThis as any).__haybarnTakePrefetchedExtension = takePrefetchedExtension;\n}\n", "import { DuckDBBindings, DuckDBDataProtocol } from '../bindings';\nimport { WorkerResponseVariant, WorkerRequestVariant, WorkerRequestType, WorkerResponseType } from './worker_request';\nimport { Logger, LogEntryVariant } from '../log';\nimport { InstantiationProgress } from '../bindings/progress';\nimport { clearPrefetchedExtensions, prefetchExtensions } from './extension_prefetch';\n\nexport abstract class AsyncDuckDBDispatcher implements Logger {\n /** The bindings */\n protected _bindings: DuckDBBindings | null = null;\n /** The next message id */\n protected _nextMessageId = 0;\n\n /** Instantiate the wasm module */\n protected abstract instantiate(\n mainModule: string,\n pthreadWorker: string | null,\n progress?: (p: InstantiationProgress) => void,\n ): Promise<DuckDBBindings>;\n /** Post a response to the main thread */\n protected abstract postMessage(response: WorkerResponseVariant, transfer: ArrayBuffer[]): void;\n\n /** Send log entry to the main thread */\n public log(entry: LogEntryVariant): void {\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: 0,\n type: WorkerResponseType.LOG,\n data: entry,\n },\n [],\n );\n }\n\n /** Send plain OK without further data */\n protected sendOK(request: WorkerRequestVariant): void {\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.OK,\n data: null,\n },\n [],\n );\n }\n\n /** Fail with an error */\n protected failWith(request: WorkerRequestVariant, e: Error): void {\n // Workaround for Firefox not being able to perform structured-clone on Native Errors\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1556604\n const obj: any = {\n name: e.name,\n message: e.message,\n stack: e.stack || undefined,\n };\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.ERROR,\n data: obj,\n },\n [],\n );\n return;\n }\n\n /** The requests are processed in the order they arrive, even if a request has to wait for asynchronous work */\n private _requests: Promise<void> = Promise.resolve();\n /** Checkpoint files, unless a query is still executing: a pending query that was not polled to its end or a\n * result stream that was not fetched to its end keeps DuckDB's worker threads busy between requests */\n private async checkpointFiles(): Promise<void> {\n if (this._bindings!.queriesInFlight()) return;\n await this._bindings!.checkpointFiles();\n }\n\n /** Process a request from the main thread */\n public onMessage(request: WorkerRequestVariant): Promise<void> {\n const run = this._requests.then(() => this.processRequest(request));\n this._requests = run.catch(() => {});\n return run;\n }\n\n /** Process a single request */\n private async processRequest(request: WorkerRequestVariant): Promise<void> {\n // First process those requests that don't need bindings\n switch (request.type) {\n case WorkerRequestType.PING:\n this.sendOK(request);\n return;\n case WorkerRequestType.INSTANTIATE:\n if (this._bindings != null) {\n this.failWith(request, new Error('duckdb already initialized'));\n }\n try {\n // Only forward progress if the caller asked for it (older clients don't say).\n const forwardProgress =\n request.data[2] === false\n ? undefined\n : (p: InstantiationProgress) => {\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.INSTANTIATE_PROGRESS,\n data: p,\n },\n [],\n );\n };\n this._bindings = await this.instantiate(request.data[0], request.data[1], forwardProgress);\n this.sendOK(request);\n } catch (e: any) {\n console.log(e);\n this._bindings = null;\n this.failWith(request, e);\n }\n return;\n default:\n break;\n }\n\n // Bindings not initialized?\n if (!this._bindings) {\n return this.failWith(request, new Error('duckdb is not initialized'));\n }\n\n // Catch every exception and forward it as error message to the main thread\n try {\n // Files created by the previous request are moved into place before the next one runs\n await this.checkpointFiles();\n switch (request.type) {\n case WorkerRequestType.GET_VERSION:\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.VERSION_STRING,\n data: this._bindings.getVersion(),\n },\n [],\n );\n break;\n case WorkerRequestType.GET_FEATURE_FLAGS:\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.FEATURE_FLAGS,\n data: this._bindings.getFeatureFlags(),\n },\n [],\n );\n break;\n case WorkerRequestType.RESET:\n clearPrefetchedExtensions();\n this._bindings.reset();\n // Files written by this request are in place when it is acknowledged\n await this.checkpointFiles();\n this.sendOK(request);\n break;\n\n case WorkerRequestType.OPEN: {\n const path = request.data.path;\n if (path?.startsWith('opfs://')) {\n await this._bindings.prepareDBFileHandle(path, DuckDBDataProtocol.BROWSER_FSACCESS);\n request.data.useDirectIO = true;\n }\n // DuckDB's home directory is opfs://home where OPFS exists, it is in use from the start\n this.log({ timestamp: new Date(), level: 1, origin: 3, topic: 3, event: 3, value: 'mount' } as any);\n await this._bindings.mountOPFS();\n this.log({ timestamp: new Date(), level: 1, origin: 3, topic: 3, event: 3, value: 'open' } as any);\n // The new database may resolve extensions to other URLs\n clearPrefetchedExtensions();\n this._bindings.open(request.data);\n this.log({ timestamp: new Date(), level: 1, origin: 3, topic: 3, event: 3, value: 'opened' } as any);\n this.sendOK(request);\n break;\n }\n case WorkerRequestType.DROP_FILE:\n this._bindings.dropFile(request.data);\n // Files written by this request are in place when it is acknowledged\n await this.checkpointFiles();\n this.sendOK(request);\n break;\n case WorkerRequestType.DROP_FILES:\n this._bindings.dropFiles(request.data);\n // Files written by this request are in place when it is acknowledged\n await this.checkpointFiles();\n this.sendOK(request);\n break;\n case WorkerRequestType.FLUSH_FILES:\n this._bindings.flushFiles();\n // Files written by this request are in place when it is acknowledged\n await this.checkpointFiles();\n this.sendOK(request);\n break;\n case WorkerRequestType.PREFETCH_EXTENSIONS: {\n // Haybarn: only browsers gain. Node's LOAD reads files or downloads in a child process.\n const [names, timeoutMs] = request.data;\n const held: string[] = [];\n if (typeof XMLHttpRequest !== 'undefined') {\n const urls = new Map<string, string>();\n for (const name of names) {\n try {\n // Empty when the extension is already loaded\n const url = this._bindings.getExtensionUrl(name);\n if (url) {\n urls.set(name, url);\n }\n } catch (e) {\n // Not resolvable (e.g. no loadable extensions in this build): LOAD reports it\n }\n }\n const ready = new Set(await prefetchExtensions([...new Set(urls.values())], timeoutMs));\n for (const [name, url] of urls) {\n if (ready.has(url)) {\n held.push(name);\n }\n }\n }\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.EXTENSIONS_PREFETCHED,\n data: held,\n },\n [],\n );\n break;\n }\n case WorkerRequestType.CONNECT: {\n const conn = this._bindings.connect();\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.CONNECTION_INFO,\n data: conn.useUnsafe((_, c) => c),\n },\n [],\n );\n break;\n }\n case WorkerRequestType.DISCONNECT:\n this._bindings.disconnect(request.data);\n this.sendOK(request);\n break;\n case WorkerRequestType.CREATE_PREPARED: {\n const result = this._bindings.createPrepared(request.data[0], request.data[1]);\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.PREPARED_STATEMENT_ID,\n data: result,\n },\n [],\n );\n break;\n }\n case WorkerRequestType.CLOSE_PREPARED: {\n this._bindings.closePrepared(request.data[0], request.data[1]);\n this.sendOK(request);\n break;\n }\n case WorkerRequestType.RUN_PREPARED: {\n const result = this._bindings.runPrepared(request.data[0], request.data[1], request.data[2]);\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.QUERY_RESULT,\n data: result,\n },\n [result.buffer],\n );\n break;\n }\n case WorkerRequestType.RUN_QUERY: {\n const result = this._bindings.runQuery(request.data[0], request.data[1]);\n // Files the query wrote are in place when its result is acknowledged\n await this.checkpointFiles();\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.QUERY_RESULT,\n data: result,\n },\n [result.buffer],\n );\n break;\n }\n case WorkerRequestType.SEND_PREPARED: {\n const result = this._bindings.sendPrepared(request.data[0], request.data[1], request.data[2]);\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.QUERY_RESULT_HEADER,\n data: result,\n },\n [result.buffer],\n );\n break;\n }\n case WorkerRequestType.START_PENDING_QUERY: {\n const result = this._bindings.startPendingQuery(request.data[0], request.data[1], request.data[2]);\n await this.checkpointFiles();\n const transfer = [];\n if (result) {\n transfer.push(result.buffer);\n }\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.QUERY_RESULT_HEADER_OR_NULL,\n data: result,\n },\n transfer,\n );\n break;\n }\n case WorkerRequestType.POLL_PENDING_QUERY: {\n const result = this._bindings.pollPendingQuery(request.data);\n await this.checkpointFiles();\n const transfer = [];\n if (result) {\n transfer.push(result.buffer);\n }\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.QUERY_RESULT_HEADER_OR_NULL,\n data: result,\n },\n transfer,\n );\n break;\n }\n case WorkerRequestType.CANCEL_PENDING_QUERY: {\n const result = this._bindings.cancelPendingQuery(request.data);\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.SUCCESS,\n data: result,\n },\n [],\n );\n break;\n }\n // The SharedArrayBuffer of a handle is shared by postMessage, not copied\n case WorkerRequestType.GET_INTERRUPT_HANDLE:\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.INTERRUPT_HANDLE,\n data: this._bindings.getInterruptHandle(request.data),\n },\n [],\n );\n break;\n case WorkerRequestType.GET_PROGRESS_HANDLE:\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.PROGRESS_HANDLE,\n data: this._bindings.getProgressHandle(request.data),\n },\n [],\n );\n break;\n case WorkerRequestType.GET_QUERY_PROGRESS:\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.QUERY_PROGRESS,\n data: this._bindings.getQueryProgress(request.data),\n },\n [],\n );\n break;\n case WorkerRequestType.FETCH_QUERY_RESULTS: {\n const result = this._bindings.fetchQueryResults(request.data);\n // An empty batch ends the stream\n if (!result || result.length == 0) {\n await this.checkpointFiles();\n }\n const transfer = result ? [result.buffer] : [];\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.QUERY_RESULT_CHUNK,\n data: result,\n },\n transfer,\n );\n break;\n }\n case WorkerRequestType.GET_TABLE_NAMES: {\n const result = this._bindings.getTableNames(request.data[0], request.data[1]);\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.TABLE_NAMES,\n data: result,\n },\n [],\n );\n break;\n }\n case WorkerRequestType.GLOB_FILE_INFOS: {\n const infos = this._bindings.globFiles(request.data);\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.FILE_INFOS,\n data: infos,\n },\n [],\n );\n break;\n }\n\n case WorkerRequestType.REGISTER_FILE_URL:\n this._bindings.registerFileURL(request.data[0], request.data[1], request.data[2], request.data[3]);\n this.sendOK(request);\n break;\n\n case WorkerRequestType.REGISTER_FILE_BUFFER:\n this._bindings.registerFileBuffer(request.data[0], request.data[1]);\n this.sendOK(request);\n break;\n\n case WorkerRequestType.REGISTER_FILE_HANDLE:\n await this._bindings.registerFileHandleAsync(\n request.data[0],\n request.data[1],\n request.data[2],\n request.data[3],\n );\n this.sendOK(request);\n break;\n\n case WorkerRequestType.COPY_FILE_TO_PATH:\n this._bindings.copyFileToPath(request.data[0], request.data[1]);\n this.sendOK(request);\n break;\n\n case WorkerRequestType.COPY_FILE_TO_BUFFER: {\n const buffer = this._bindings.copyFileToBuffer(request.data);\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.FILE_BUFFER,\n data: buffer,\n },\n [],\n );\n break;\n }\n case WorkerRequestType.COLLECT_FILE_STATISTICS:\n this._bindings.collectFileStatistics(request.data[0], request.data[1]);\n this.sendOK(request);\n break;\n\n case WorkerRequestType.REGISTER_OPFS_FILE_NAME: {\n const files = await this._bindings.registerOPFSFileName(request.data[0], request.data[1]);\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.OPFS_FILE_NAMES,\n data: files,\n },\n [],\n );\n break;\n }\n\n case WorkerRequestType.EXPORT_FILE_STATISTICS: {\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.FILE_STATISTICS,\n data: this._bindings.exportFileStatistics(request.data),\n },\n [],\n );\n break;\n }\n case WorkerRequestType.INSERT_ARROW_FROM_IPC_STREAM: {\n this._bindings.insertArrowFromIPCStream(request.data[0], request.data[1], request.data[2]);\n this.sendOK(request);\n break;\n }\n case WorkerRequestType.INSERT_CSV_FROM_PATH: {\n this._bindings.insertCSVFromPath(request.data[0], request.data[1], request.data[2]);\n this.sendOK(request);\n break;\n }\n case WorkerRequestType.INSERT_JSON_FROM_PATH: {\n this._bindings.insertJSONFromPath(request.data[0], request.data[1], request.data[2]);\n this.sendOK(request);\n break;\n }\n case WorkerRequestType.TOKENIZE: {\n const result = this._bindings.tokenize(request.data);\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.SCRIPT_TOKENS,\n data: result,\n },\n [],\n );\n break;\n }\n }\n } catch (e: any) {\n console.log(e);\n return this.failWith(request, e);\n }\n }\n}\n", "export const bigInt=()=>(async e=>{try{return(await WebAssembly.instantiate(e)).instance.exports.b(BigInt(0))===BigInt(0)}catch(e){return!1}})(new Uint8Array([0,97,115,109,1,0,0,0,1,6,1,96,1,126,1,126,3,2,1,0,7,5,1,1,98,0,0,10,6,1,4,0,32,0,11])),bulkMemory=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,3,1,0,1,10,14,1,12,0,65,0,65,0,65,0,252,10,0,0,11])),exceptions=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,8,1,6,0,6,64,25,11,11])),extendedConst=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,5,3,1,0,1,11,9,1,0,65,1,65,2,106,11,0])),gc=()=>(async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,95,1,120,0])))(),jspi=()=>(async()=>\"Suspender\"in WebAssembly)(),memory64=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,5,3,1,4,1])),multiMemory=()=>(async()=>{try{return new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,5,5,2,0,0,0,0])),!0}catch(e){return!1}})(),multiValue=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,6,1,96,0,2,127,127,3,2,1,0,10,8,1,6,0,65,0,65,0,11])),mutableGlobals=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,2,8,1,1,97,1,98,3,127,1,6,6,1,127,1,65,0,11,7,5,1,1,97,3,1])),referenceTypes=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,7,1,5,0,208,112,26,11])),relaxedSimd=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,15,1,13,0,65,1,253,15,65,2,253,15,253,128,2,11])),saturatedFloatToInt=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,12,1,10,0,67,0,0,0,0,252,0,26,11])),signExtensions=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,8,1,6,0,65,0,192,26,11])),simd=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])),streamingCompilation=()=>(async()=>\"compileStreaming\"in WebAssembly)(),tailCall=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,6,1,4,0,18,0,11])),threads=()=>(async e=>{try{return\"undefined\"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(e)}catch(e){return!1}})(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])),typeReflection=()=>(async()=>\"Function\"in WebAssembly)();\n", "{\n \"name\": \"@haybarn/haybarn-wasm\",\n \"version\": \"2.0.0-rc6\",\n \"description\": \"Haybarn for WebAssembly \u2014 Query Farm's derived distribution of DuckDB-Wasm. Haybarn, powered by DuckDB.\",\n \"license\": \"MIT\",\n \"homepage\": \"https://query.farm/products/haybarn/\",\n \"bugs\": {\n \"url\": \"https://github.com/Query-farm-haybarn/haybarn-wasm/issues\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/Query-farm-haybarn/haybarn-wasm.git\"\n },\n \"keywords\": [\n \"sql\",\n \"haybarn\",\n \"duckdb\",\n \"relational\",\n \"database\",\n \"data\",\n \"query\",\n \"wasm\",\n \"analytics\",\n \"olap\",\n \"arrow\",\n \"parquet\",\n \"json\",\n \"csv\"\n ],\n \"dependencies\": {\n \"apache-arrow\": \"^17.0.0\",\n \"qs\": \"^6.14.1\"\n },\n \"devDependencies\": {\n \"@types/emscripten\": \"^1.39.10\",\n \"@types/jasmine\": \"^5.1.13\",\n \"@typescript-eslint/eslint-plugin\": \"^6.21.0\",\n \"@typescript-eslint/parser\": \"^6.21.0\",\n \"esbuild\": \"^0.20.2\",\n \"eslint\": \"^8.57.0\",\n \"eslint-plugin-jasmine\": \"^4.1.3\",\n \"eslint-plugin-react\": \"^7.37.5\",\n \"fast-glob\": \"^3.3.2\",\n \"jasmine\": \"^5.13.0\",\n \"jasmine-core\": \"^5.1.2\",\n \"jasmine-spec-reporter\": \"^7.0.0\",\n \"js-sha256\": \"^0.11.1\",\n \"karma\": \"^6.4.2\",\n \"karma-chrome-launcher\": \"^3.2.0\",\n \"karma-coverage\": \"^2.2.1\",\n \"karma-firefox-launcher\": \"^2.1.3\",\n \"karma-jasmine\": \"^5.1.0\",\n \"karma-jasmine-html-reporter\": \"^2.1.0\",\n \"karma-sourcemap-loader\": \"^0.4.0\",\n \"karma-spec-reporter\": \"^0.0.36\",\n \"make-dir\": \"^4.0.0\",\n \"nyc\": \"^15.1.0\",\n \"prettier\": \"^3.2.5\",\n \"puppeteer\": \"^22.8.0\",\n \"rimraf\": \"^5.0.5\",\n \"s3rver\": \"^3.7.1\",\n \"typedoc\": \"^0.28.15\",\n \"typescript\": \"^5.3.3\",\n \"wasm-feature-detect\": \"^1.6.1\",\n \"web-worker\": \"^1.2.0\"\n },\n \"scripts\": {\n \"build:debug\": \"node bundle.mjs debug && tsc --emitDeclarationOnly\",\n \"build:release\": \"node bundle.mjs release && tsc --emitDeclarationOnly\",\n \"docs\": \"typedoc\",\n \"format\": \"prettier --write \\\"**/*.+(js|ts)\\\"\",\n \"report\": \"node ./coverage.mjs\",\n \"test:node\": \"node --enable-source-maps ../jasmine/bin/jasmine ./dist/tests-node.cjs\",\n \"test:node:debug\": \"node --inspect-brk --enable-source-maps ../jasmine/bin/jasmine ./dist/tests-node.cjs\",\n \"test:node:coverage\": \"nyc -r json --report-dir ./coverage/node node ../jasmine/bin/jasmine ./dist/tests-node.cjs\",\n \"test:firefox\": \"karma start ./karma/tests-firefox.cjs\",\n \"test:chrome\": \"karma start ./karma/tests-chrome.cjs\",\n \"test:chrome:threads\": \"karma start ./karma/tests-chrome-threads.cjs\",\n \"test:chrome:threads:smoke\": \"karma start ./karma/threads-smoke-chrome.cjs\",\n \"test:chrome:httpfs\": \"karma start ./karma/httpfs-chrome.cjs\",\n \"test:chrome:haybarn-repository\": \"karma start ./karma/haybarn-repository-chrome.cjs\",\n \"test:chrome:threads-pool\": \"karma start ./karma/threads-pool-chrome.cjs\",\n \"test:chrome:interrupt\": \"karma start ./karma/interrupt-chrome.cjs\",\n \"test:chrome:platform\": \"karma start ./karma/platform-chrome.cjs\",\n \"test:chrome:prefetch\": \"karma start ./karma/prefetch-chrome.cjs\",\n \"test:chrome:coverage\": \"karma start ./karma/tests-chrome-coverage.cjs\",\n \"test:browser\": \"karma start ./karma/tests-all.cjs\",\n \"test:browser:debug\": \"karma start ./karma/tests-debug.cjs\",\n \"test\": \"npm run test:chrome && npm run test:node\",\n \"test:coverage\": \"npm run test:chrome:coverage && npm run test:node:coverage && npm run report\",\n \"lint\": \"eslint src test\"\n },\n \"files\": [\n \"dist\",\n \"!dist/tests-*\",\n \"!dist/duckdb-browser-base.worker.js.map\",\n \"!dist/types/test\"\n ],\n \"main\": \"dist/duckdb-browser.cjs\",\n \"module\": \"dist/duckdb-browser.mjs\",\n \"types\": \"dist/duckdb-browser.d.ts\",\n \"jsdelivr\": \"dist/duckdb-browser.cjs\",\n \"unpkg\": \"dist/duckdb-browser.mjs\",\n \"sideEffects\": false,\n \"browser\": {\n \"fs\": false,\n \"path\": false,\n \"perf_hooks\": false,\n \"os\": false,\n \"worker_threads\": false\n },\n \"exports\": {\n \"./dist/duckdb-base.wasm\": \"./dist/duckdb-base.wasm\",\n \"./dist/duckdb-threads.wasm\": \"./dist/duckdb-threads.wasm\",\n \"./dist/duckdb-browser\": \"./dist/duckdb-browser.mjs\",\n \"./dist/duckdb-browser.cjs\": \"./dist/duckdb-browser.cjs\",\n \"./dist/duckdb-browser.mjs\": \"./dist/duckdb-browser.mjs\",\n \"./dist/duckdb-browser-threads.pthread.worker.js\": \"./dist/duckdb-browser-threads.pthread.worker.js\",\n \"./dist/duckdb-browser-threads.worker.js\": \"./dist/duckdb-browser-threads.worker.js\",\n \"./dist/duckdb-browser-base.worker.js\": \"./dist/duckdb-browser-base.worker.js\",\n \"./dist/duckdb-browser-vgi.mjs\": \"./dist/duckdb-browser-vgi.mjs\",\n \"./dist/duckdb-browser-vgi.cjs\": \"./dist/duckdb-browser-vgi.cjs\",\n \"./vgi\": {\n \"types\": \"./dist/duckdb-browser-vgi.d.ts\",\n \"import\": \"./dist/duckdb-browser-vgi.mjs\",\n \"require\": \"./dist/duckdb-browser-vgi.cjs\"\n },\n \"./dist/duckdb-node\": \"./dist/duckdb-node.cjs\",\n \"./dist/duckdb-node.cjs\": \"./dist/duckdb-node.cjs\",\n \"./dist/duckdb-node-blocking\": \"./dist/duckdb-node-blocking.cjs\",\n \"./dist/duckdb-node-blocking.cjs\": \"./dist/duckdb-node-blocking.cjs\",\n \"./dist/duckdb-node-base.worker.cjs\": \"./dist/duckdb-node-base.worker.cjs\",\n \"./blocking\": {\n \"node\": {\n \"types\": \"./dist/duckdb-node-blocking.d.ts\",\n \"require\": \"./dist/duckdb-node-blocking.cjs\",\n \"import\": \"./dist/duckdb-node-blocking.cjs\"\n },\n \"types\": \"./dist/duckdb-node-blocking.d.ts\",\n \"import\": \"./dist/duckdb-node-blocking.mjs\",\n \"require\": \"./dist/duckdb-node-blocking.cjs\"\n },\n \".\": {\n \"browser\": {\n \"types\": \"./dist/duckdb-browser.d.ts\",\n \"import\": \"./dist/duckdb-browser.mjs\",\n \"require\": \"./dist/duckdb-browser.cjs\"\n },\n \"node\": {\n \"types\": \"./dist/duckdb-node.d.ts\",\n \"import\": \"./dist/duckdb-node.cjs\",\n \"require\": \"./dist/duckdb-node.cjs\"\n },\n \"types\": \"./dist/duckdb-browser.d.ts\",\n \"import\": \"./dist/duckdb-browser.mjs\",\n \"require\": \"./dist/duckdb-browser.cjs\"\n }\n }\n}\n", "import config from '../package.json';\n\nexport const PACKAGE_NAME = config.name;\nexport const PACKAGE_VERSION = config.version;\n\nconst VERSION_PARTS = config.version.split('.');\nexport const PACKAGE_VERSION_MAJOR = VERSION_PARTS[0];\nexport const PACKAGE_VERSION_MINOR = VERSION_PARTS[1];\nexport const PACKAGE_VERSION_PATCH = VERSION_PARTS[2];\n", "import * as check from 'wasm-feature-detect';\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\n\n// Platform check taken from here:\n// https://github.com/xtermjs/xterm.js/blob/master/src/common/Platform.ts#L21\n\ninterface INavigator {\n userAgent: string;\n language: string;\n platform: string;\n}\n\n// We're declaring a navigator global here as we expect it in all runtimes (node and browser), but\n// we want this module to live in common.\ndeclare const navigator: INavigator;\n\nexport const isNode = () => (typeof navigator === 'undefined' ? true : false);\nconst userAgent = () => (isNode() ? 'node' : navigator.userAgent);\nexport const isFirefox = () => userAgent().includes('Firefox');\nexport const isSafari = () => /^((?!chrome|android).)*safari/i.test(userAgent());\n\n/** Bundles have different characteristics:\n * - base: single-threaded, requires WebAssembly exception handling\n * - threads: multi-threaded, additionally requires SIMD, threads and cross origin isolation\n */\nexport interface DuckDBBundles {\n base: {\n mainModule: string;\n mainWorker: string;\n };\n threads?: {\n mainModule: string;\n mainWorker: string;\n pthreadWorker: string;\n };\n}\n\nexport function getJsDelivrBundles(): DuckDBBundles {\n const jsdelivr_dist_url = `https://cdn.jsdelivr.net/npm/${PACKAGE_NAME}@${PACKAGE_VERSION}/dist/`;\n return {\n base: {\n mainModule: `${jsdelivr_dist_url}duckdb-base.wasm`,\n mainWorker: `${jsdelivr_dist_url}duckdb-browser-base.worker.js`,\n },\n // threads is still experimental, let the user opt in explicitly\n };\n}\n\nexport interface DuckDBBundle {\n mainModule: string;\n mainWorker: string | null;\n pthreadWorker: string | null;\n}\n\nexport interface PlatformFeatures {\n bigInt64Array: boolean;\n crossOriginIsolated: boolean;\n wasmExceptions: boolean;\n wasmSIMD: boolean;\n wasmBulkMemory: boolean;\n wasmThreads: boolean;\n}\n\nlet bigInt64Array: boolean | null = null;\nlet wasmExceptions: boolean | null = null;\nlet wasmThreads: boolean | null = null;\nlet wasmSIMD: boolean | null = null;\nlet wasmBulkMemory: boolean | null = null;\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\ndeclare namespace globalThis {\n let crossOriginIsolated: boolean;\n}\n\nexport async function getPlatformFeatures(): Promise<PlatformFeatures> {\n if (bigInt64Array == null) {\n bigInt64Array = typeof BigInt64Array != 'undefined';\n }\n if (wasmExceptions == null) {\n wasmExceptions = await check.exceptions();\n }\n if (wasmThreads == null) {\n wasmThreads = await check.threads();\n }\n if (wasmSIMD == null) {\n wasmSIMD = await check.simd();\n }\n if (wasmBulkMemory == null) {\n wasmBulkMemory = await check.bulkMemory();\n }\n return {\n bigInt64Array: bigInt64Array!,\n crossOriginIsolated: isNode() || globalThis.crossOriginIsolated || false,\n wasmExceptions: wasmExceptions!,\n wasmSIMD: wasmSIMD!,\n wasmThreads: wasmThreads!,\n wasmBulkMemory: wasmBulkMemory!,\n };\n}\n\n/** Every bundle requires WebAssembly exception handling, throws if the platform does not support it */\nexport async function checkPlatformSupport(): Promise<PlatformFeatures> {\n const platform = await getPlatformFeatures();\n if (!platform.wasmExceptions) {\n throw new Error('DuckDB-Wasm requires WebAssembly exception handling, which this platform does not support');\n }\n return platform;\n}\n\nexport async function selectBundle(bundles: DuckDBBundles): Promise<DuckDBBundle> {\n const platform = await checkPlatformSupport();\n if (platform.wasmSIMD && platform.wasmThreads && platform.crossOriginIsolated && bundles.threads) {\n return {\n mainModule: bundles.threads.mainModule,\n mainWorker: bundles.threads.mainWorker,\n pthreadWorker: bundles.threads.pthreadWorker,\n };\n }\n return {\n mainModule: bundles.base.mainModule,\n mainWorker: bundles.base.mainWorker,\n pthreadWorker: null,\n };\n}\n", "import Worker from 'web-worker';\n\nexport async function createWorker(url: string) {\n const request = new Request(url);\n const workerScript = await fetch(request);\n const workerURL = URL.createObjectURL(await workerScript.blob());\n return new Worker(workerURL);\n}\n"],
4
+ "sourcesContent": ["/**\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nmodule.exports = Worker;", "export * from '../bindings/config';\nexport * from '../bindings/tokens';\nexport * from '../log';\nexport * from '../status';\nexport * from '../parallel';\nexport * from '../platform';\nexport * from '../version';\nexport * from '../worker';\n\nexport { InstantiationProgress, InstantiationProgressHandler, DuckDBDataProtocol, WebFile } from '../bindings';\n", "export interface DuckDBQueryConfig {\n /**\n * The polling interval for queries\n */\n queryPollingInterval?: number;\n /**\n * Cast BigInt to Double?\n */\n castBigIntToDouble?: boolean;\n /**\n * Cast Timestamp to Date64?\n */\n castTimestampToDate?: boolean;\n /**\n * Cast Timestamp to Date64?\n */\n castDurationToTime64?: boolean;\n /**\n * Cast Decimal to Double?\n */\n castDecimalToDouble?: boolean;\n}\n\nexport interface DuckDBFilesystemConfig {\n reliableHeadRequests?: boolean;\n /**\n * Allow falling back to full HTTP reads if the server does not support range requests.\n */\n allowFullHTTPReads?: boolean;\n /**\n * Force use of full HTTP reads, suppressing range requests.\n */\n forceFullHTTPReads?: boolean;\n}\n\nexport interface DuckDBOPFSConfig {\n /**\n * Defines how `opfs://` files are handled during SQL execution.\n * - \"auto\": Automatically register `opfs://` files and drop them after execution.\n * - \"manual\": Files must be manually registered and dropped.\n */\n fileHandling?: \"auto\" | \"manual\";\n}\n\nexport enum DuckDBAccessMode {\n UNDEFINED = 0,\n AUTOMATIC = 1,\n READ_ONLY = 2,\n READ_WRITE = 3,\n}\n\nexport interface DuckDBConfig {\n /**\n * The database path\n */\n path?: string;\n /**\n * The access mode\n */\n accessMode?: DuckDBAccessMode;\n /**\n * Spill data that does not fit in memory to the temporary directory, js_buffer://tmp by default:\n * buffers held by the runtime outside the WASM heap. Enabled unless set to false.\n */\n spill?: boolean;\n /**\n * The temporary directory of DuckDB, overrides the default of the runtime\n */\n temporaryDirectory?: string;\n /**\n * The home directory of DuckDB, opfs://home where the browser has an origin private file system: what DuckDB\n * stores next to the user (persistent secrets) persists across sessions\n */\n homeDirectory?: string;\n /**\n * The repository extensions are loaded from (custom_extension_repository), the Haybarn core repository\n * (haybarn-extensions.query.farm/core) by default\n */\n extensionRepository?: string;\n /**\n * The maximum number of threads.\n * Note that this will only work with cross-origin isolated sites since it requires SharedArrayBuffers.\n */\n maximumThreads?: number;\n /**\n * The direct io flag\n */\n useDirectIO?: boolean;\n /**\n * The query config\n */\n query?: DuckDBQueryConfig;\n /**\n * The filesystem config\n */\n filesystem?: DuckDBFilesystemConfig;\n /**\n * Whether to allow unsigned extensions\n */\n allowUnsignedExtensions?: boolean;\n /**\n * Whether to use alternate Arrow conversion that preserves full range and precision of data.\n */\n arrowLosslessConversion?: boolean;\n /**\n * Custom user agent string\n */\n customUserAgent?: string;\n /**\n * opfs string\n */\n opfs?: DuckDBOPFSConfig;\n /**\n * Haybarn: run extension `LOAD`/`INSTALL` statements with the task scheduler pinned to a single thread.\n *\n * When enabled, the bindings bracket each statement that starts with `LOAD`/`INSTALL` with `SET threads=1` ...\n * `SET threads=<previous>`. It was the workaround for an intermittent deadlock of extension loads on the threads\n * bundle: the query thread spun while a scheduler thread ran the load, so it never synced the side module the\n * main thread opened. The engine now waits instead of spinning (`wait_for_tasks_instead_of_spinning.patch`), and\n * loads, autoloads inside queries included, no longer need the bracket.\n *\n * Defaults to disabled. A no-op on the base bundle and whenever `threads` is already 1.\n */\n singleThreadedExtensionLoad?: boolean;\n}\n", "export enum TokenType {\n IDENTIFIER = 0,\n NUMERIC_CONSTANT = 1,\n STRING_CONSTANT = 2,\n OPERATOR = 3,\n KEYWORD = 4,\n COMMENT = 5,\n}\n\nexport interface ScriptTokens {\n offsets: number[];\n types: TokenType[];\n}\n", "export enum LogLevel {\n NONE = 0,\n DEBUG = 1,\n INFO = 2,\n WARNING = 3,\n ERROR = 4,\n}\n\nexport enum LogTopic {\n NONE = 0,\n CONNECT = 1,\n DISCONNECT = 2,\n OPEN = 3,\n QUERY = 4,\n INSTANTIATE = 5,\n FILESYSTEM = 6,\n}\n\nexport enum LogEvent {\n NONE = 0,\n OK = 1,\n ERROR = 2,\n START = 3,\n RUN = 4,\n CAPTURE = 5,\n}\n\nexport enum LogOrigin {\n NONE = 0,\n WEB_WORKER = 1,\n NODE_WORKER = 2,\n BINDINGS = 3,\n ASYNC_DUCKDB = 4,\n}\n\nexport type LogEntry<O, T, E, V> = {\n readonly timestamp: Date;\n readonly level: LogLevel;\n readonly origin: O;\n readonly topic: T;\n readonly event: E;\n readonly value: V;\n};\n\nexport type ProgressEntry = {\n readonly status: string;\n readonly percentage: string;\n readonly repetitions: string;\n};\n\n/** An execution progress handler */\nexport type ExecutionProgressHandler = (p: ProgressEntry) => void;\n\nexport type LogEntryVariant =\n | LogEntry<LogOrigin.BINDINGS, LogTopic.INSTANTIATE, LogEvent.ERROR, string>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.FILESYSTEM, LogEvent.RUN, string>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.QUERY, LogEvent.START, void>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.QUERY, LogEvent.OK, void>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.QUERY, LogEvent.ERROR, void>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.CONNECT, LogEvent.OK, void>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.CONNECT, LogEvent.ERROR, void>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.DISCONNECT, LogEvent.OK, void>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.DISCONNECT, LogEvent.ERROR, void>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.OPEN, LogEvent.START, void>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.OPEN, LogEvent.OK, void>\n | LogEntry<LogOrigin.BINDINGS, LogTopic.OPEN, LogEvent.ERROR, void>\n | LogEntry<LogOrigin.ASYNC_DUCKDB, LogTopic.QUERY, LogEvent.RUN, string>;\n\nexport interface Logger {\n log(entry: LogEntryVariant): void;\n}\n\nexport class VoidLogger implements Logger {\n public log(_entry: LogEntryVariant): void {}\n}\n\nexport class ConsoleLogger implements Logger {\n constructor(protected level: LogLevel = LogLevel.INFO) {}\n public log(entry: LogEntryVariant): void {\n if (entry.level >= this.level) {\n console.log(entry);\n }\n }\n}\n\nexport function getLogLevelLabel(level: LogLevel): string {\n switch (level) {\n case LogLevel.NONE:\n return 'NONE';\n case LogLevel.DEBUG:\n return 'DEBUG';\n case LogLevel.INFO:\n return 'INFO';\n case LogLevel.WARNING:\n return 'WARNING';\n case LogLevel.ERROR:\n return 'ERROR';\n default:\n return '?';\n }\n}\n\nexport function getLogEventLabel(event: LogEvent): string {\n switch (event) {\n case LogEvent.NONE:\n return 'NONE';\n case LogEvent.OK:\n return 'OK';\n case LogEvent.ERROR:\n return 'ERROR';\n case LogEvent.START:\n return 'START';\n case LogEvent.RUN:\n return 'RUN';\n case LogEvent.CAPTURE:\n return 'CAPTURE';\n default:\n return '?';\n }\n}\n\nexport function getLogTopicLabel(topic: LogTopic): string {\n switch (topic) {\n case LogTopic.CONNECT:\n return 'CONNECT';\n case LogTopic.DISCONNECT:\n return 'DISCONNECT';\n case LogTopic.INSTANTIATE:\n return 'INSTANTIATE';\n case LogTopic.OPEN:\n return 'OPEN';\n case LogTopic.QUERY:\n return 'QUERY';\n case LogTopic.FILESYSTEM:\n return 'FILESYSTEM';\n default:\n return '?';\n }\n}\n\nexport function getLogOriginLabel(origin: LogOrigin): string {\n switch (origin) {\n case LogOrigin.NONE:\n return 'NONE';\n case LogOrigin.WEB_WORKER:\n return 'WEB WORKER';\n case LogOrigin.NODE_WORKER:\n return 'NODE WORKER';\n case LogOrigin.BINDINGS:\n return 'DUCKDB BINDINGS';\n case LogOrigin.ASYNC_DUCKDB:\n return 'DUCKDB';\n default:\n return '?';\n }\n}\n", "export enum StatusCode {\n SUCCESS = 0,\n MAX_ARROW_ERROR = 255,\n DUCKDB_WASM_RETRY = 256,\n}\n\nexport function IsArrowBuffer(status: StatusCode): boolean {\n return status <= StatusCode.MAX_ARROW_ERROR;\n}\n\nexport function IsDuckDBWasmRetry(status: StatusCode): boolean {\n return status === StatusCode.DUCKDB_WASM_RETRY;\n}\n", "import * as arrow from 'apache-arrow';\nimport { AsyncDuckDB } from './async_bindings';\nimport { LogLevel, LogTopic, LogOrigin, LogEvent } from '../log';\nimport { ArrowInsertOptions, CSVInsertOptions, JSONInsertOptions } from '../bindings/insert_options';\n\n/** A thin helper to memoize the connection id */\nexport class AsyncDuckDBConnection {\n /** The async duckdb */\n protected readonly _bindings: AsyncDuckDB;\n /** The conn handle */\n protected readonly _conn: number;\n\n constructor(bindings: AsyncDuckDB, conn: number) {\n this._bindings = bindings;\n this._conn = conn;\n }\n\n /** Access the database bindings */\n public get bindings(): AsyncDuckDB {\n return this._bindings;\n }\n\n /** Disconnect from the database */\n public async close(): Promise<void> {\n return this._bindings.disconnect(this._conn);\n }\n\n /** Brave souls may use this function to consume the underlying connection id */\n public useUnsafe<R>(callback: (bindings: AsyncDuckDB, conn: number) => R) {\n return callback(this._bindings, this._conn);\n }\n\n /** Run a query */\n public async query<T extends { [key: string]: arrow.DataType } = any>(text: string): Promise<arrow.Table<T>> {\n this._bindings.logger.log({\n timestamp: new Date(),\n level: LogLevel.INFO,\n origin: LogOrigin.ASYNC_DUCKDB,\n topic: LogTopic.QUERY,\n event: LogEvent.RUN,\n value: text,\n });\n const buffer = await this._bindings.runQuery(this._conn, text);\n const reader = arrow.RecordBatchReader.from<T>(buffer);\n console.assert(reader.isSync(), 'Reader is not sync');\n return new arrow.Table(reader as arrow.RecordBatchFileReader);\n }\n\n /** Send a query */\n public async send<T extends { [key: string]: arrow.DataType } = any>(\n text: string,\n allowStreamResult: boolean = false,\n ): Promise<arrow.AsyncRecordBatchStreamReader<T>> {\n this._bindings.logger.log({\n timestamp: new Date(),\n level: LogLevel.INFO,\n origin: LogOrigin.ASYNC_DUCKDB,\n topic: LogTopic.QUERY,\n event: LogEvent.RUN,\n value: text,\n });\n let header = await this._bindings.startPendingQuery(this._conn, text, allowStreamResult);\n while (header == null) {\n // Avoid infinite loop on detached state\n if (this._bindings.isDetached()) {\n console.error('cannot send a message since the worker is not set!');\n return undefined as any;\n }\n header = await this._bindings.pollPendingQuery(this._conn);\n }\n const iter = new AsyncResultStreamIterator(this._bindings, this._conn, header);\n const reader = await arrow.RecordBatchReader.from<T>(iter);\n console.assert(reader.isAsync());\n console.assert(reader.isStream());\n return reader as unknown as arrow.AsyncRecordBatchStreamReader<T>; // XXX\n }\n\n /** Cancel a query that was sent earlier */\n public async cancelSent(): Promise<boolean> {\n return await this._bindings.cancelPendingQuery(this._conn);\n }\n\n /** Get table names */\n public async getTableNames(query: string): Promise<string[]> {\n return await this._bindings.getTableNames(this._conn, query);\n }\n\n /** Create a prepared statement */\n public async prepare<T extends { [key: string]: arrow.DataType } = any>(\n text: string,\n ): Promise<AsyncPreparedStatement<T>> {\n const stmt = await this._bindings.createPrepared(this._conn, text);\n return new AsyncPreparedStatement<T>(this._bindings, this._conn, stmt);\n }\n\n /** Insert an arrow table */\n public async insertArrowTable(table: arrow.Table, options: ArrowInsertOptions): Promise<void> {\n const buffer = arrow.tableToIPC(table, 'stream');\n await this.insertArrowFromIPCStream(buffer, options);\n }\n /** Insert an arrow table from an ipc stream */\n public async insertArrowFromIPCStream(buffer: Uint8Array, options: ArrowInsertOptions): Promise<void> {\n await this._bindings.insertArrowFromIPCStream(this._conn, buffer, options);\n }\n /** Insert csv file from path */\n public async insertCSVFromPath(text: string, options: CSVInsertOptions): Promise<void> {\n await this._bindings.insertCSVFromPath(this._conn, text, options);\n }\n /** Insert json file from path */\n public async insertJSONFromPath(text: string, options: JSONInsertOptions): Promise<void> {\n await this._bindings.insertJSONFromPath(this._conn, text, options);\n }\n}\n\n/** An async result stream iterator */\nexport class AsyncResultStreamIterator implements AsyncIterable<Uint8Array> {\n /** First chunk? */\n protected _first: boolean;\n /** Reached end of stream? */\n protected _depleted: boolean;\n /** In-flight */\n protected _inFlight: Promise<Uint8Array | null> | null;\n\n constructor(\n protected readonly db: AsyncDuckDB,\n protected readonly conn: number,\n protected readonly header: Uint8Array,\n ) {\n this._first = true;\n this._depleted = false;\n this._inFlight = null;\n }\n\n async next(): Promise<IteratorResult<Uint8Array>> {\n if (this._first) {\n this._first = false;\n return { done: false, value: this.header };\n }\n if (this._depleted) {\n return { done: true, value: null };\n }\n let buffer: Uint8Array | null = null;\n if (this._inFlight != null) {\n buffer = await this._inFlight;\n this._inFlight = null;\n }\n\n while (buffer == null) {\n buffer = await this.db.fetchQueryResults(this.conn);\n }\n\n this._depleted = buffer.length == 0;\n if (!this._depleted) {\n this._inFlight = this.db.fetchQueryResults(this.conn);\n }\n\n return {\n done: this._depleted,\n value: buffer,\n };\n }\n\n [Symbol.asyncIterator]() {\n return this;\n }\n}\n\n/** A thin helper to bind the prepared statement id */\nexport class AsyncPreparedStatement<T extends { [key: string]: arrow.DataType } = any> {\n /** The bindings */\n protected readonly bindings: AsyncDuckDB;\n /** The connection id */\n protected readonly connectionId: number;\n /** The statement id */\n protected readonly statementId: number;\n\n /** Constructor */\n constructor(bindings: AsyncDuckDB, connectionId: number, statementId: number) {\n this.bindings = bindings;\n this.connectionId = connectionId;\n this.statementId = statementId;\n }\n\n /** Close a prepared statement */\n public async close() {\n await this.bindings.closePrepared(this.connectionId, this.statementId);\n }\n\n /** Run a prepared statement */\n public async query(...params: any[]): Promise<arrow.Table<T>> {\n const buffer = await this.bindings.runPrepared(this.connectionId, this.statementId, params);\n const reader = arrow.RecordBatchReader.from<T>(buffer);\n console.assert(reader.isSync());\n return new arrow.Table(reader as arrow.RecordBatchFileReader);\n }\n\n /** Send a prepared statement */\n public async send(...params: any[]): Promise<arrow.AsyncRecordBatchStreamReader<T>> {\n const header = await this.bindings.sendPrepared(this.connectionId, this.statementId, params);\n const iter = new AsyncResultStreamIterator(this.bindings, this.connectionId, header);\n const reader = await arrow.RecordBatchReader.from<T>(iter);\n console.assert(reader.isAsync());\n console.assert(reader.isStream());\n return reader as unknown as arrow.AsyncRecordBatchStreamReader<T>; // XXX\n }\n}\n", "import { CSVInsertOptions, JSONInsertOptions, ArrowInsertOptions } from '../bindings/insert_options';\nimport { OPFSAccessMode } from '../bindings/opfs_scratch';\nimport { LogEntryVariant, ProgressEntry } from '../log';\nimport { ScriptTokens } from '../bindings/tokens';\nimport { FileStatistics } from '../bindings/file_stats';\nimport { DuckDBConfig } from '../bindings/config';\nimport { WebFile } from '../bindings/web_file';\nimport { InstantiationProgress, QueryProgress, QueryProgressHandle } from '../bindings/progress';\nimport { InterruptHandle } from '../bindings/interrupt';\nimport { DuckDBDataProtocol } from '../bindings';\n\nexport type ConnectionID = number;\nexport type StatementID = number;\n\nexport enum WorkerRequestType {\n CANCEL_PENDING_QUERY = 'CANCEL_PENDING_QUERY',\n CLOSE_PREPARED = 'CLOSE_PREPARED',\n COLLECT_FILE_STATISTICS = 'COLLECT_FILE_STATISTICS',\n REGISTER_OPFS_FILE_NAME = 'REGISTER_OPFS_FILE_NAME',\n CONNECT = 'CONNECT',\n COPY_FILE_TO_BUFFER = 'COPY_FILE_TO_BUFFER',\n COPY_FILE_TO_PATH = 'COPY_FILE_TO_PATH',\n CREATE_PREPARED = 'CREATE_PREPARED',\n DISCONNECT = 'DISCONNECT',\n DROP_FILE = 'DROP_FILE',\n DROP_FILES = 'DROP_FILES',\n EXPORT_FILE_STATISTICS = 'EXPORT_FILE_STATISTICS',\n FETCH_QUERY_RESULTS = 'FETCH_QUERY_RESULTS',\n FLUSH_FILES = 'FLUSH_FILES',\n GET_FEATURE_FLAGS = 'GET_FEATURE_FLAGS',\n GET_INTERRUPT_HANDLE = 'GET_INTERRUPT_HANDLE',\n GET_PROGRESS_HANDLE = 'GET_PROGRESS_HANDLE',\n GET_QUERY_PROGRESS = 'GET_QUERY_PROGRESS',\n GET_TABLE_NAMES = 'GET_TABLE_NAMES',\n GET_VERSION = 'GET_VERSION',\n GLOB_FILE_INFOS = 'GLOB_FILE_INFOS',\n INSERT_ARROW_FROM_IPC_STREAM = 'INSERT_ARROW_FROM_IPC_STREAM',\n INSERT_CSV_FROM_PATH = 'IMPORT_CSV_FROM_PATH',\n INSERT_JSON_FROM_PATH = 'IMPORT_JSON_FROM_PATH',\n INSTANTIATE = 'INSTANTIATE',\n OPEN = 'OPEN',\n PING = 'PING',\n PREFETCH_EXTENSIONS = 'PREFETCH_EXTENSIONS',\n POLL_PENDING_QUERY = 'POLL_PENDING_QUERY',\n REGISTER_FILE_BUFFER = 'REGISTER_FILE_BUFFER',\n REGISTER_FILE_HANDLE = 'REGISTER_FILE_HANDLE',\n REGISTER_FILE_URL = 'REGISTER_FILE_URL',\n RESET = 'RESET',\n RUN_PREPARED = 'RUN_PREPARED',\n RUN_QUERY = 'RUN_QUERY',\n SEND_PREPARED = 'SEND_PREPARED',\n START_PENDING_QUERY = 'START_PENDING_QUERY',\n TOKENIZE = 'TOKENIZE',\n}\n\nexport enum WorkerResponseType {\n CONNECTION_INFO = 'CONNECTION_INFO',\n ERROR = 'ERROR',\n EXTENSIONS_PREFETCHED = 'EXTENSIONS_PREFETCHED',\n FEATURE_FLAGS = 'FEATURE_FLAGS',\n FILE_BUFFER = 'FILE_BUFFER',\n FILE_INFOS = 'FILE_INFOS',\n FILE_SIZE = 'FILE_SIZE',\n FILE_STATISTICS = 'FILE_STATISTICS',\n INSTANTIATE_PROGRESS = 'INSTANTIATE_PROGRESS',\n INTERRUPT_HANDLE = 'INTERRUPT_HANDLE',\n LOG = 'LOG',\n PROGRESS_HANDLE = 'PROGRESS_HANDLE',\n PROGRESS_UPDATE = 'PROGRESS_UPDATE',\n OK = 'OK',\n PREPARED_STATEMENT_ID = 'PREPARED_STATEMENT_ID',\n QUERY_PLAN = 'QUERY_PLAN',\n QUERY_PROGRESS = 'QUERY_PROGRESS',\n QUERY_RESULT = 'QUERY_RESULT',\n QUERY_RESULT_CHUNK = 'QUERY_RESULT_CHUNK',\n QUERY_RESULT_HEADER = 'QUERY_RESULT_HEADER',\n QUERY_RESULT_HEADER_OR_NULL = 'QUERY_RESULT_HEADER_OR_NULL',\n REGISTERED_FILE = 'REGISTERED_FILE',\n SCRIPT_TOKENS = 'SCRIPT_TOKENS',\n SUCCESS = 'SUCCESS',\n TABLE_NAMES = 'TABLE_NAMES',\n OPFS_FILE_NAMES = 'OPFS_FILE_NAMES',\n VERSION_STRING = 'VERSION_STRING',\n}\n\nexport type WorkerRequest<T, P> = {\n readonly messageId: number;\n readonly type: T;\n readonly data: P;\n};\n\nexport type WorkerResponse<T, P> = {\n readonly messageId: number;\n readonly requestId: number;\n readonly type: T;\n readonly data: P;\n};\n\nexport type WorkerTaskReturnType<T extends WorkerTaskVariant> = T extends WorkerTask<any, any, infer P> ? P : never;\n\nexport class WorkerTask<T, D, P> {\n readonly type: T;\n readonly data: D;\n promise: Promise<P>;\n promiseResolver: (value: P | PromiseLike<P>) => void = () => {};\n promiseRejecter: (value: any) => void = () => {};\n\n constructor(type: T, data: D) {\n this.type = type;\n this.data = data;\n this.promise = new Promise<P>(\n (resolve: (value: P | PromiseLike<P>) => void, reject: (reason?: void) => void) => {\n this.promiseResolver = resolve;\n this.promiseRejecter = reject;\n },\n );\n }\n}\n\nexport type WorkerRequestVariant =\n | WorkerRequest<WorkerRequestType.CLOSE_PREPARED, [ConnectionID, StatementID]>\n | WorkerRequest<WorkerRequestType.CANCEL_PENDING_QUERY, number>\n | WorkerRequest<WorkerRequestType.COLLECT_FILE_STATISTICS, [string, boolean]>\n | WorkerRequest<WorkerRequestType.REGISTER_OPFS_FILE_NAME, [string, OPFSAccessMode]>\n | WorkerRequest<WorkerRequestType.CONNECT, null>\n | WorkerRequest<WorkerRequestType.COPY_FILE_TO_BUFFER, string>\n | WorkerRequest<WorkerRequestType.COPY_FILE_TO_PATH, [string, string]>\n | WorkerRequest<WorkerRequestType.CREATE_PREPARED, [ConnectionID, string]>\n | WorkerRequest<WorkerRequestType.DISCONNECT, number>\n | WorkerRequest<WorkerRequestType.DROP_FILE, string>\n | WorkerRequest<WorkerRequestType.DROP_FILES, string[] | undefined>\n | WorkerRequest<WorkerRequestType.EXPORT_FILE_STATISTICS, string>\n | WorkerRequest<WorkerRequestType.FETCH_QUERY_RESULTS, number>\n | WorkerRequest<WorkerRequestType.FLUSH_FILES, null>\n | WorkerRequest<WorkerRequestType.GET_FEATURE_FLAGS, null>\n | WorkerRequest<WorkerRequestType.GET_INTERRUPT_HANDLE, number>\n | WorkerRequest<WorkerRequestType.GET_PROGRESS_HANDLE, number>\n | WorkerRequest<WorkerRequestType.GET_QUERY_PROGRESS, number>\n | WorkerRequest<WorkerRequestType.GET_TABLE_NAMES, [number, string]>\n | WorkerRequest<WorkerRequestType.GET_VERSION, null>\n | WorkerRequest<WorkerRequestType.GLOB_FILE_INFOS, string>\n | WorkerRequest<\n WorkerRequestType.INSERT_ARROW_FROM_IPC_STREAM,\n [number, Uint8Array, ArrowInsertOptions | undefined]\n >\n | WorkerRequest<WorkerRequestType.INSERT_CSV_FROM_PATH, [number, string, CSVInsertOptions]>\n | WorkerRequest<WorkerRequestType.INSERT_JSON_FROM_PATH, [number, string, JSONInsertOptions]>\n | WorkerRequest<WorkerRequestType.INSTANTIATE, [string, string | null, boolean?]>\n | WorkerRequest<WorkerRequestType.OPEN, DuckDBConfig>\n | WorkerRequest<WorkerRequestType.PING, null>\n | WorkerRequest<WorkerRequestType.PREFETCH_EXTENSIONS, [string[], number | undefined]>\n | WorkerRequest<WorkerRequestType.POLL_PENDING_QUERY, number>\n | WorkerRequest<WorkerRequestType.REGISTER_FILE_BUFFER, [string, Uint8Array]>\n | WorkerRequest<WorkerRequestType.REGISTER_FILE_HANDLE, [string, any, DuckDBDataProtocol, boolean]>\n | WorkerRequest<WorkerRequestType.REGISTER_FILE_URL, [string, string, DuckDBDataProtocol, boolean]>\n | WorkerRequest<WorkerRequestType.RESET, null>\n | WorkerRequest<WorkerRequestType.RUN_PREPARED, [number, number, any[]]>\n | WorkerRequest<WorkerRequestType.RUN_QUERY, [number, string]>\n | WorkerRequest<WorkerRequestType.SEND_PREPARED, [number, number, any[]]>\n | WorkerRequest<WorkerRequestType.START_PENDING_QUERY, [number, string, boolean]>\n | WorkerRequest<WorkerRequestType.TOKENIZE, string>;\n\nexport type WorkerResponseVariant =\n | WorkerResponse<WorkerResponseType.CONNECTION_INFO, number>\n | WorkerResponse<WorkerResponseType.ERROR, any>\n | WorkerResponse<WorkerResponseType.EXTENSIONS_PREFETCHED, string[]>\n | WorkerResponse<WorkerResponseType.FEATURE_FLAGS, number>\n | WorkerResponse<WorkerResponseType.FILE_BUFFER, Uint8Array>\n | WorkerResponse<WorkerResponseType.FILE_INFOS, WebFile[]>\n | WorkerResponse<WorkerResponseType.FILE_SIZE, number>\n | WorkerResponse<WorkerResponseType.FILE_STATISTICS, FileStatistics>\n | WorkerResponse<WorkerResponseType.INSTANTIATE_PROGRESS, InstantiationProgress>\n | WorkerResponse<WorkerResponseType.INTERRUPT_HANDLE, InterruptHandle | null>\n | WorkerResponse<WorkerResponseType.LOG, LogEntryVariant>\n | WorkerResponse<WorkerResponseType.PROGRESS_HANDLE, QueryProgressHandle | null>\n | WorkerResponse<WorkerResponseType.PROGRESS_UPDATE, ProgressEntry>\n | WorkerResponse<WorkerResponseType.OK, null>\n | WorkerResponse<WorkerResponseType.PREPARED_STATEMENT_ID, number>\n | WorkerResponse<WorkerResponseType.QUERY_PLAN, Uint8Array>\n | WorkerResponse<WorkerResponseType.QUERY_PROGRESS, QueryProgress | null>\n | WorkerResponse<WorkerResponseType.QUERY_RESULT, Uint8Array>\n | WorkerResponse<WorkerResponseType.QUERY_RESULT_CHUNK, Uint8Array | null>\n | WorkerResponse<WorkerResponseType.QUERY_RESULT_HEADER, Uint8Array>\n | WorkerResponse<WorkerResponseType.QUERY_RESULT_HEADER_OR_NULL, Uint8Array | null>\n | WorkerResponse<WorkerResponseType.SCRIPT_TOKENS, ScriptTokens>\n | WorkerResponse<WorkerResponseType.SUCCESS, boolean>\n | WorkerResponse<WorkerResponseType.TABLE_NAMES, string[]>\n | WorkerResponse<WorkerResponseType.OPFS_FILE_NAMES, string[]>\n | WorkerResponse<WorkerResponseType.VERSION_STRING, string>;\n\nexport type WorkerTaskVariant =\n | WorkerTask<WorkerRequestType.COLLECT_FILE_STATISTICS, [string, boolean], null>\n | WorkerTask<WorkerRequestType.REGISTER_OPFS_FILE_NAME, [string, OPFSAccessMode], string[]>\n | WorkerTask<WorkerRequestType.CLOSE_PREPARED, [number, number], null>\n | WorkerTask<WorkerRequestType.CONNECT, null, ConnectionID>\n | WorkerTask<WorkerRequestType.COPY_FILE_TO_BUFFER, string, Uint8Array>\n | WorkerTask<WorkerRequestType.COPY_FILE_TO_PATH, [string, string], null>\n | WorkerTask<WorkerRequestType.CREATE_PREPARED, [number, string], number>\n | WorkerTask<WorkerRequestType.DISCONNECT, ConnectionID, null>\n | WorkerTask<WorkerRequestType.DROP_FILE, string, null>\n | WorkerTask<WorkerRequestType.DROP_FILES, string[] | undefined, null>\n | WorkerTask<WorkerRequestType.EXPORT_FILE_STATISTICS, string, FileStatistics>\n | WorkerTask<WorkerRequestType.FETCH_QUERY_RESULTS, ConnectionID, Uint8Array | null>\n | WorkerTask<WorkerRequestType.FLUSH_FILES, null, null>\n | WorkerTask<WorkerRequestType.GET_FEATURE_FLAGS, null, number>\n | WorkerTask<WorkerRequestType.GET_INTERRUPT_HANDLE, ConnectionID, InterruptHandle | null>\n | WorkerTask<WorkerRequestType.GET_PROGRESS_HANDLE, ConnectionID, QueryProgressHandle | null>\n | WorkerTask<WorkerRequestType.GET_QUERY_PROGRESS, ConnectionID, QueryProgress | null>\n | WorkerTask<WorkerRequestType.GET_TABLE_NAMES, [number, string], string[]>\n | WorkerTask<WorkerRequestType.GET_VERSION, null, string>\n | WorkerTask<\n WorkerRequestType.INSERT_ARROW_FROM_IPC_STREAM,\n [number, Uint8Array, ArrowInsertOptions | undefined],\n null\n >\n | WorkerTask<WorkerRequestType.INSERT_CSV_FROM_PATH, [number, string, CSVInsertOptions], null>\n | WorkerTask<WorkerRequestType.INSERT_JSON_FROM_PATH, [number, string, JSONInsertOptions], null>\n | WorkerTask<WorkerRequestType.INSTANTIATE, [string, string | null, boolean?], null>\n | WorkerTask<WorkerRequestType.OPEN, DuckDBConfig, null>\n | WorkerTask<WorkerRequestType.PING, null, null>\n | WorkerTask<WorkerRequestType.PREFETCH_EXTENSIONS, [string[], number | undefined], string[]>\n | WorkerTask<WorkerRequestType.REGISTER_FILE_BUFFER, [string, Uint8Array], null>\n | WorkerTask<WorkerRequestType.REGISTER_FILE_HANDLE, [string, any, DuckDBDataProtocol, boolean], null>\n | WorkerTask<WorkerRequestType.REGISTER_FILE_URL, [string, string, DuckDBDataProtocol, boolean], null>\n | WorkerTask<WorkerRequestType.GLOB_FILE_INFOS, string, WebFile[]>\n | WorkerTask<WorkerRequestType.RESET, null, null>\n | WorkerTask<WorkerRequestType.RUN_PREPARED, [number, number, any[]], Uint8Array>\n | WorkerTask<WorkerRequestType.RUN_QUERY, [ConnectionID, string], Uint8Array>\n | WorkerTask<WorkerRequestType.SEND_PREPARED, [number, number, any[]], Uint8Array>\n | WorkerTask<WorkerRequestType.START_PENDING_QUERY, [ConnectionID, string, boolean], Uint8Array | null>\n | WorkerTask<WorkerRequestType.POLL_PENDING_QUERY, ConnectionID, Uint8Array | null>\n | WorkerTask<WorkerRequestType.CANCEL_PENDING_QUERY, ConnectionID, boolean>\n | WorkerTask<WorkerRequestType.TOKENIZE, string, ScriptTokens>;\n", "/**\n * A connection's interrupt flag, reachable from any thread.\n *\n * On the threads bundle the worker is inside the call that runs a query (a blocking `runQuery`, or one\n * `pollPendingQuery`, which can process many chunks) until that call returns, so a message asking to cancel the\n * query (`cancelPendingQuery`) is read only afterwards. The wasm memory of that bundle is a SharedArrayBuffer, so\n * the caller can set the engine's own flag (`ClientContext::interrupt_state`) in place. The engine checks it between\n * chunks on every thread and in the HTTP client, and the statement fails with an interrupt error, as with a native\n * `Connection::Interrupt()`.\n *\n * The flag belongs to the connection, not to a query: whatever runs on the connection when it is set is\n * interrupted. A statement in autocommit mode clears it before it starts, so a store made between statements has\n * no effect there.\n */\nexport interface InterruptHandle {\n /** The engine's wasm memory */\n memory: SharedArrayBuffer;\n /** Byte offset of the connection's one-byte interrupt flag in `memory` */\n offset: number;\n}\n\n/** ClientInterruptState::NOT_INTERRUPTED */\nconst NOT_INTERRUPTED = 0;\n/** ClientInterruptState::INTERRUPTED */\nconst INTERRUPTED = 1;\n\n/**\n * Interrupt whatever runs on the handle's connection. Callable from any thread.\n *\n * Moves the flag from not interrupted to interrupted only, as `ClientContext::Interrupt()` does: a statement that\n * suppressed interrupts (after an irreversible step such as a COMMIT) stays unaffected.\n */\nexport function interruptConnection(handle: InterruptHandle): void {\n Atomics.compareExchange(new Uint8Array(handle.memory, handle.offset, 1), 0, NOT_INTERRUPTED, INTERRUPTED);\n}\n", "import * as arrow from 'apache-arrow';\n\nexport interface SQLType {\n /// The sql type\n sqlType: string;\n /// Is nullable?\n nullable?: boolean;\n /// Decimal precision\n precision?: number;\n /// Decimal scaling\n scale?: number;\n /// Timezone\n timezone?: string;\n /// Byte width (FixedSizeBinary)\n byteWidth?: number;\n /// Key type\n keyType?: SQLType;\n /// Value type\n valueType?: SQLType;\n /// Fields\n fields?: SQLField[];\n}\n\nexport function arrowToSQLType(type: arrow.DataType): SQLType {\n switch (type.typeId) {\n case arrow.Type.Binary:\n return { sqlType: 'binary' };\n case arrow.Type.Bool:\n return { sqlType: 'bool' };\n case arrow.Type.Date:\n return { sqlType: 'date' };\n case arrow.Type.DateDay:\n return { sqlType: 'date32[d]' };\n case arrow.Type.DateMillisecond:\n return { sqlType: 'date64[ms]' };\n case arrow.Type.Decimal: {\n const dec = type as arrow.Decimal;\n return { sqlType: 'decimal', precision: dec.precision, scale: dec.scale };\n }\n case arrow.Type.Float:\n return { sqlType: 'float' };\n case arrow.Type.Float16:\n return { sqlType: 'float16' };\n case arrow.Type.Float32:\n return { sqlType: 'float32' };\n case arrow.Type.Float64:\n return { sqlType: 'float64' };\n case arrow.Type.Int:\n return { sqlType: 'int32' };\n case arrow.Type.Int16:\n return { sqlType: 'int16' };\n case arrow.Type.Int32:\n return { sqlType: 'int32' };\n case arrow.Type.Int64:\n return { sqlType: 'int64' };\n case arrow.Type.Uint16:\n return { sqlType: 'uint16' };\n case arrow.Type.Uint32:\n return { sqlType: 'uint32' };\n case arrow.Type.Uint64:\n return { sqlType: 'uint64' };\n case arrow.Type.Uint8:\n return { sqlType: 'uint8' };\n case arrow.Type.IntervalDayTime:\n return { sqlType: 'interval[dt]' };\n case arrow.Type.IntervalYearMonth:\n return { sqlType: 'interval[m]' };\n case arrow.Type.List: {\n const list = type as arrow.List;\n return {\n sqlType: 'list',\n valueType: arrowToSQLType(list.valueType),\n };\n }\n case arrow.Type.FixedSizeBinary: {\n const bin = type as arrow.FixedSizeBinary;\n return { sqlType: 'fixedsizebinary', byteWidth: bin.byteWidth };\n }\n case arrow.Type.Null:\n return { sqlType: 'null' };\n case arrow.Type.Utf8:\n return { sqlType: 'utf8' };\n case arrow.Type.Struct: {\n const struct_ = type as arrow.Struct;\n return {\n sqlType: 'struct',\n fields: struct_.children.map(c => arrowToSQLField(c.name, c.type)),\n };\n }\n case arrow.Type.Map: {\n const map_ = type as arrow.Map_;\n return {\n sqlType: 'map',\n keyType: arrowToSQLType(map_.keyType),\n valueType: arrowToSQLType(map_.valueType),\n };\n }\n case arrow.Type.Time:\n return { sqlType: 'time[s]' };\n case arrow.Type.TimeMicrosecond:\n return { sqlType: 'time[us]' };\n case arrow.Type.TimeMillisecond:\n return { sqlType: 'time[ms]' };\n case arrow.Type.TimeNanosecond:\n return { sqlType: 'time[ns]' };\n case arrow.Type.TimeSecond:\n return { sqlType: 'time[s]' };\n case arrow.Type.Timestamp: {\n const ts = type as arrow.Timestamp;\n return { sqlType: 'timestamp', timezone: ts.timezone || undefined };\n }\n case arrow.Type.TimestampSecond: {\n const ts = type as arrow.TimestampSecond;\n return { sqlType: 'timestamp[s]', timezone: ts.timezone || undefined };\n }\n case arrow.Type.TimestampMicrosecond: {\n const ts = type as arrow.TimestampMicrosecond;\n return { sqlType: 'timestamp[us]', timezone: ts.timezone || undefined };\n }\n case arrow.Type.TimestampNanosecond: {\n const ts = type as arrow.TimestampNanosecond;\n return { sqlType: 'timestamp[ns]', timezone: ts.timezone || undefined };\n }\n case arrow.Type.TimestampMillisecond: {\n const ts = type as arrow.TimestampMillisecond;\n return { sqlType: 'timestamp[ms]', timezone: ts.timezone || undefined };\n }\n }\n throw new Error(`unsupported arrow type: ${type.toString()}`);\n}\n\nexport type SQLField = SQLType & { name: string };\n\nexport function arrowToSQLField(name: string, type: arrow.DataType): SQLField {\n const t = arrowToSQLType(type) as SQLField;\n t.name = name;\n return t;\n}\n", "export const REGEX_OPFS_FILE = /'(opfs:\\/\\/\\S*?)'/g;\nexport const REGEX_OPFS_PROTOCOL = /(opfs:\\/\\/\\S*?)/g;\n\nexport function isOPFSProtocol(path: string): boolean {\n return path.search(REGEX_OPFS_PROTOCOL) > -1;\n}\n\nexport function searchOPFSFiles(text: string) {\n return [...text.matchAll(REGEX_OPFS_FILE)].map(match => match[1]);\n}", "import { OPFSAccessMode } from '../bindings/opfs_scratch';\nimport {\n WorkerRequestType,\n WorkerResponseType,\n WorkerResponseVariant,\n WorkerTaskVariant,\n WorkerTask,\n ConnectionID,\n WorkerTaskReturnType,\n} from './worker_request';\nimport { AsyncDuckDBBindings } from './async_bindings_interface';\nimport { Logger } from '../log';\nimport { AsyncDuckDBConnection } from './async_connection';\nimport { CSVInsertOptions, JSONInsertOptions, ArrowInsertOptions } from '../bindings/insert_options';\nimport { ScriptTokens } from '../bindings/tokens';\nimport { FileStatistics } from '../bindings/file_stats';\nimport { DuckDBConfig } from '../bindings/config';\nimport { InstantiationProgress, QueryProgress, QueryProgressHandle } from '../bindings/progress';\nimport { InterruptHandle, interruptConnection } from '../bindings/interrupt';\nimport { arrowToSQLField } from '../json_typedef';\nimport { WebFile } from '../bindings/web_file';\nimport { DuckDBDataProtocol } from '../bindings';\nimport { searchOPFSFiles } from \"../utils/opfs_util\";\nimport { ProgressEntry } from '../log';\n\nconst TEXT_ENCODER = new TextEncoder();\n\n/**\n * How often the flag of `registerCancelSAB` is checked while a pending query runs. A check costs one atomic load, so\n * the interval only bounds the latency of a cancel that arrives while the page waits for a poll.\n */\nconst CANCEL_SAB_POLL_MS = 50;\n\n/** The default time a worker gets to answer its first message (see AsyncDuckDBOptions.workerStartTimeout) */\nexport const DEFAULT_WORKER_START_TIMEOUT_MS = 30000;\n\n/** Options for the async DuckDB */\nexport interface AsyncDuckDBOptions {\n /**\n * Milliseconds the worker gets to answer its first message before all pending\n * requests are rejected with \"worker did not start\". Only a cheap PING is timed,\n * and only until the worker's first response arrives, so slow instantiation or\n * long-running queries are never cut short. 0 disables the check.\n * Defaults to DEFAULT_WORKER_START_TIMEOUT_MS (30 s).\n */\n workerStartTimeout?: number;\n}\n\nexport class AsyncDuckDB implements AsyncDuckDBBindings {\n /** The message handler */\n protected readonly _onMessageHandler: (event: MessageEvent) => void;\n /** The error handler */\n protected readonly _onErrorHandler: (event: ErrorEvent) => void;\n /** The close handler */\n protected readonly _onCloseHandler: () => void;\n /** The message error handler */\n protected readonly _onMessageErrorHandler: (event: MessageEvent) => void;\n\n /** Instantiate the module */\n protected _onInstantiationProgress: ((p: InstantiationProgress) => void)[] = [];\n\n /** Progress callbacks */\n protected _onExecutionProgress: ((p: ProgressEntry) => void)[] = [];\n\n /** The logger */\n protected readonly _logger: Logger;\n /** The worker */\n protected _worker: Worker | null = null;\n /** The promise for the worker shutdown */\n protected _workerShutdownPromise: Promise<null> | null = null;\n /** Make the worker as terminated */\n protected _workerShutdownResolver: (value: PromiseLike<null> | null) => void = () => {};\n\n /** The next message id */\n protected _nextMessageId = 0;\n /** The pending requests */\n protected _pendingRequests: Map<number, WorkerTaskVariant> = new Map();\n /** The DuckDBConfig */\n protected _config: DuckDBConfig = {};\n /** The interrupt flags of the connections, fetched when they connect (threads bundle only) */\n protected _interruptHandles: Map<ConnectionID, InterruptHandle> = new Map();\n /** The connections with a pending query, in the order the queries started */\n protected _pendingQueries: Set<ConnectionID> = new Set();\n /** The flag of registerCancelSAB */\n protected _cancelFlag: Int32Array | null = null;\n /** The interval that checks the flag of registerCancelSAB while a pending query runs */\n protected _cancelWatcher: ReturnType<typeof setInterval> | null = null;\n\n /** Milliseconds the worker gets to answer its first message, 0 disables the check */\n protected readonly _workerStartTimeout: number;\n /** Did the attached worker send anything yet? */\n protected _workerStarted = false;\n /** The armed worker start timer, if any */\n protected _workerStartTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(logger: Logger, worker: Worker | null = null, options: AsyncDuckDBOptions = {}) {\n this._logger = logger;\n this._workerStartTimeout = options.workerStartTimeout ?? DEFAULT_WORKER_START_TIMEOUT_MS;\n this._onMessageHandler = this.onMessage.bind(this);\n this._onErrorHandler = this.onError.bind(this);\n this._onCloseHandler = this.onClose.bind(this);\n this._onMessageErrorHandler = this.onMessageError.bind(this);\n if (worker != null) this.attach(worker);\n }\n\n /** Get the logger */\n public get logger(): Logger {\n return this._logger;\n }\n\n /** Get the logger */\n public get config(): DuckDBConfig {\n return this._config;\n }\n\n /** Attach to worker */\n protected attach(worker: Worker): void {\n this._worker = worker;\n this._workerStarted = false;\n this._worker.addEventListener('message', this._onMessageHandler);\n this._worker.addEventListener('error', this._onErrorHandler);\n this._worker.addEventListener('close', this._onCloseHandler);\n this._worker.addEventListener('messageerror', this._onMessageErrorHandler);\n this._workerShutdownPromise = new Promise<null>(\n (resolve: (value: PromiseLike<null> | null) => void, _reject: (reason?: void) => void) => {\n this._workerShutdownResolver = resolve;\n },\n );\n }\n\n /** Detach from worker */\n public detach(): void {\n if (!this._worker) return;\n this._worker.removeEventListener('message', this._onMessageHandler);\n this._worker.removeEventListener('error', this._onErrorHandler);\n this._worker.removeEventListener('close', this._onCloseHandler);\n this._worker.removeEventListener('messageerror', this._onMessageErrorHandler);\n this._worker = null;\n this.clearWorkerStartTimer();\n this.rejectPendingRequests(new Error('duckdb worker was detached before the request completed'));\n this._workerShutdownResolver(null);\n this._workerShutdownPromise = null;\n this._workerShutdownResolver = () => {};\n }\n\n /** Kill the worker */\n public async terminate(): Promise<void> {\n if (!this._worker) return;\n this.forgetConnections();\n this._worker.terminate();\n //await this._workerShutdownPromise; TODO deadlocking in karma?\n this._worker = null;\n this.clearWorkerStartTimer();\n this.rejectPendingRequests(new Error('duckdb worker was terminated before the request completed'));\n this._workerShutdownPromise = null;\n this._workerShutdownResolver = () => {};\n }\n\n /** Reject all pending requests with an error and forget them */\n protected rejectPendingRequests(error: Error): void {\n const pending = [...this._pendingRequests.values()];\n this._pendingRequests.clear();\n for (const task of pending) {\n task.promiseRejecter(error);\n }\n }\n\n /** Stop waiting for the worker to start */\n protected clearWorkerStartTimer(): void {\n if (this._workerStartTimer !== null) {\n clearTimeout(this._workerStartTimer);\n this._workerStartTimer = null;\n }\n }\n\n /**\n * Make sure a worker that never starts fails instead of hanging.\n *\n * A worker can fail to load without ever emitting 'error' (e.g. a script error swallowed by\n * a Worker polyfill), in which case every request would wait forever. Before the first\n * request goes out we send a PING, which the dispatcher answers immediately, ahead of the\n * request itself. Any message from the worker disarms the timer. If none arrives in time,\n * all pending requests are rejected. Long-running requests are never timed.\n */\n protected armWorkerStartTimer(): void {\n if (!this._worker || this._workerStarted || this._workerStartTimer !== null) return;\n if (!(this._workerStartTimeout > 0)) return;\n const ping = new WorkerTask<WorkerRequestType.PING, null, null>(WorkerRequestType.PING, null);\n ping.promise.catch(() => {});\n const mid = this._nextMessageId++;\n this._pendingRequests.set(mid, ping);\n this._worker.postMessage({ messageId: mid, type: ping.type, data: ping.data });\n const timeout = this._workerStartTimeout;\n this._workerStartTimer = setTimeout(() => {\n this._workerStartTimer = null;\n if (this._workerStarted) return;\n const error = new Error(\n `duckdb worker did not start: no response within ${timeout} ms. ` +\n 'The worker script probably failed to load or threw during startup; check the worker console ' +\n 'output. In Node.js, also check the `web-worker` package version. ' +\n 'The timeout can be changed with the `workerStartTimeout` option of AsyncDuckDB.',\n );\n console.error(error.message);\n this.rejectPendingRequests(error);\n }, timeout);\n }\n\n /** Post a task */\n protected async postTask<W extends WorkerTaskVariant>(\n task: W,\n transfer: ArrayBuffer[] = [],\n ): Promise<WorkerTaskReturnType<W>> {\n if (!this._worker) {\n console.error('cannot send a message since the worker is not set!:' + task.type+\",\" + task.data);\n return undefined as any;\n }\n this.armWorkerStartTimer();\n const mid = this._nextMessageId++;\n this._pendingRequests.set(mid, task);\n this._worker.postMessage(\n {\n messageId: mid,\n type: task.type,\n data: task.data,\n },\n transfer,\n );\n return (await task.promise) as WorkerTaskReturnType<W>;\n }\n\n /** Received a message */\n protected onMessage(event: MessageEvent): void {\n // Any message proves the worker is running\n if (!this._workerStarted) {\n this._workerStarted = true;\n this.clearWorkerStartTimer();\n }\n\n // Unassociated responses?\n const response = event.data as WorkerResponseVariant;\n switch (response.type) {\n // Request failed?\n case WorkerResponseType.PROGRESS_UPDATE: {\n for (const p of this._onExecutionProgress) {\n p(response.data);\n }\n return;\n }\n case WorkerResponseType.LOG: {\n this._logger.log(response.data);\n return;\n }\n // Call progress callback\n case WorkerResponseType.INSTANTIATE_PROGRESS: {\n for (const p of this._onInstantiationProgress) {\n p(response.data);\n }\n return;\n }\n }\n\n // Haybarn: a message of the engine's platform functions (open-auth-url, vgi-ensure-worker), for the page\n // bridges that listen on the same Worker\n if (typeof response.requestId !== 'number') {\n return;\n }\n // Get associated task\n const task = this._pendingRequests.get(response.requestId);\n if (!task) {\n console.warn(`unassociated response: [${response.requestId}, ${response.type.toString()}]`);\n return;\n }\n this._pendingRequests.delete(response.requestId);\n\n // Request failed?\n if (response.type == WorkerResponseType.ERROR) {\n // Workaround for Firefox not being able to perform structured-clone on Native Errors\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1556604\n const e = new Error(response.data.message);\n e.name = response.data.name;\n if (Object.getOwnPropertyDescriptor(e, 'stack')?.writable) {\n e.stack = response.data.stack;\n }\n task.promiseRejecter(e);\n return;\n }\n\n // Otherwise differentiate between the tasks first\n switch (task.type) {\n case WorkerRequestType.CLOSE_PREPARED:\n case WorkerRequestType.COLLECT_FILE_STATISTICS:\n case WorkerRequestType.COPY_FILE_TO_PATH:\n case WorkerRequestType.DISCONNECT:\n case WorkerRequestType.DROP_FILE:\n case WorkerRequestType.DROP_FILES:\n case WorkerRequestType.FLUSH_FILES:\n case WorkerRequestType.INSERT_ARROW_FROM_IPC_STREAM:\n case WorkerRequestType.INSERT_CSV_FROM_PATH:\n case WorkerRequestType.INSERT_JSON_FROM_PATH:\n case WorkerRequestType.OPEN:\n case WorkerRequestType.PING:\n case WorkerRequestType.REGISTER_FILE_BUFFER:\n case WorkerRequestType.REGISTER_FILE_HANDLE:\n case WorkerRequestType.REGISTER_FILE_URL:\n case WorkerRequestType.RESET:\n if (response.type == WorkerResponseType.OK) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.INSTANTIATE:\n this._onInstantiationProgress = [];\n if (response.type == WorkerResponseType.OK) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.GLOB_FILE_INFOS:\n if (response.type == WorkerResponseType.FILE_INFOS) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.GET_VERSION:\n if (response.type == WorkerResponseType.VERSION_STRING) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.GET_FEATURE_FLAGS:\n if (response.type == WorkerResponseType.FEATURE_FLAGS) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.GET_TABLE_NAMES:\n if (response.type == WorkerResponseType.TABLE_NAMES) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.REGISTER_OPFS_FILE_NAME:\n if (response.type == WorkerResponseType.OPFS_FILE_NAMES) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.PREFETCH_EXTENSIONS:\n if (response.type == WorkerResponseType.EXTENSIONS_PREFETCHED) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.TOKENIZE:\n if (response.type == WorkerResponseType.SCRIPT_TOKENS) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.COPY_FILE_TO_BUFFER:\n if (response.type == WorkerResponseType.FILE_BUFFER) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.EXPORT_FILE_STATISTICS:\n if (response.type == WorkerResponseType.FILE_STATISTICS) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.CONNECT:\n if (response.type == WorkerResponseType.CONNECTION_INFO) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.RUN_PREPARED:\n case WorkerRequestType.RUN_QUERY:\n if (response.type == WorkerResponseType.QUERY_RESULT) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.SEND_PREPARED:\n if (response.type == WorkerResponseType.QUERY_RESULT_HEADER) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.START_PENDING_QUERY:\n if (response.type == WorkerResponseType.QUERY_RESULT_HEADER_OR_NULL) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.POLL_PENDING_QUERY:\n if (response.type == WorkerResponseType.QUERY_RESULT_HEADER_OR_NULL) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.CANCEL_PENDING_QUERY:\n this._onInstantiationProgress = [];\n if (response.type == WorkerResponseType.SUCCESS) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.GET_INTERRUPT_HANDLE:\n if (response.type == WorkerResponseType.INTERRUPT_HANDLE) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.GET_PROGRESS_HANDLE:\n if (response.type == WorkerResponseType.PROGRESS_HANDLE) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.GET_QUERY_PROGRESS:\n if (response.type == WorkerResponseType.QUERY_PROGRESS) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.FETCH_QUERY_RESULTS:\n if (response.type == WorkerResponseType.QUERY_RESULT_CHUNK) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n case WorkerRequestType.CREATE_PREPARED:\n if (response.type == WorkerResponseType.PREPARED_STATEMENT_ID) {\n task.promiseResolver(response.data);\n return;\n }\n break;\n }\n task.promiseRejecter(new Error(`unexpected response type: ${response.type.toString()}`));\n }\n\n /** Received an error */\n protected onError(event: ErrorEvent): void {\n console.error(event);\n console.error(`error in duckdb worker: ${event.message} (${event.filename}:${event.lineno})`);\n this.clearWorkerStartTimer();\n this.rejectPendingRequests(new Error(`error in duckdb worker: ${event.message ?? 'unknown error'}`));\n }\n\n /** A message from the worker could not be deserialized */\n protected onMessageError(_event: MessageEvent): void {\n // We cannot tell which request the lost response belonged to, so fail them all rather than hang.\n console.error('duckdb worker sent a message that could not be deserialized');\n this.rejectPendingRequests(new Error('duckdb worker sent a message that could not be deserialized'));\n }\n\n /** The worker was closed */\n protected onClose(): void {\n this._workerShutdownResolver(null);\n this.clearWorkerStartTimer();\n if (this._pendingRequests.size != 0) {\n console.warn(`worker terminated with ${this._pendingRequests.size} pending requests`);\n }\n this.rejectPendingRequests(new Error('duckdb worker closed before the request completed'));\n }\n\n /** Is in detached state, no worker defined */\n public isDetached(): boolean {\n return !this._worker;\n }\n\n /** Reset the duckdb */\n public async reset(): Promise<null> {\n this.forgetConnections();\n const task = new WorkerTask<WorkerRequestType.RESET, null, null>(WorkerRequestType.RESET, null);\n return await this.postTask(task);\n }\n\n /** Ping the worker thread */\n public async ping(): Promise<any> {\n const task = new WorkerTask<WorkerRequestType.PING, null, null>(WorkerRequestType.PING, null);\n await this.postTask(task);\n }\n /** Try to drop a file */\n public async dropFile(name: string): Promise<null> {\n const task = new WorkerTask<WorkerRequestType.DROP_FILE, string, null>(WorkerRequestType.DROP_FILE, name);\n return await this.postTask(task);\n }\n /** Try to drop files */\n public async dropFiles(names?: string[]): Promise<null> {\n const task = new WorkerTask<WorkerRequestType.DROP_FILES, string[] | undefined, null>(WorkerRequestType.DROP_FILES, names);\n return await this.postTask(task);\n }\n /** Flush all files */\n public async flushFiles(): Promise<null> {\n const task = new WorkerTask<WorkerRequestType.FLUSH_FILES, null, null>(WorkerRequestType.FLUSH_FILES, null);\n return await this.postTask(task);\n }\n\n /** Open the database */\n public async instantiate(\n mainModuleURL: string,\n pthreadWorkerURL: string | null = null,\n progress?: (progress: InstantiationProgress) => void,\n ): Promise<null> {\n if (progress) {\n this._onInstantiationProgress.push(progress);\n }\n // Haybarn: the worker only counts download progress when someone listens (third element)\n const task = new WorkerTask<WorkerRequestType.INSTANTIATE, [string, string | null, boolean?], null>(\n WorkerRequestType.INSTANTIATE,\n [mainModuleURL, pthreadWorkerURL, this._onInstantiationProgress.length > 0],\n );\n return await this.postTask(task);\n }\n\n /** Get the version */\n public async getVersion(): Promise<string> {\n const task = new WorkerTask<WorkerRequestType.GET_VERSION, null, string>(WorkerRequestType.GET_VERSION, null);\n const version = await this.postTask(task);\n return version;\n }\n\n /** Get the feature flags */\n public async getFeatureFlags(): Promise<number> {\n const task = new WorkerTask<WorkerRequestType.GET_FEATURE_FLAGS, null, number>(\n WorkerRequestType.GET_FEATURE_FLAGS,\n null,\n );\n const feature = await this.postTask(task);\n return feature;\n }\n\n /** Open a new database */\n public async open(config: DuckDBConfig): Promise<void> {\n this._config = config;\n this.forgetConnections();\n const task = new WorkerTask<WorkerRequestType.OPEN, DuckDBConfig, null>(WorkerRequestType.OPEN, config);\n await this.postTask(task);\n }\n\n /**\n * Haybarn: download, hash and compile extensions ahead of LOAD.\n *\n * In browsers, LOAD downloads each extension synchronously and hashes it with SHA-256 compiled to wasm before\n * checking its signature, then compiles it. This does that work in the worker ahead of time: the downloads run in\n * parallel, the hash is computed with WebCrypto and the module is compiled with `WebAssembly.compileStreaming`. A\n * later `LOAD <name>` that resolves to the same URL then only checks the signature, against that hash, and\n * dlopen uses the compiled module once the check has passed. Settings that change the URL (such as\n * `custom_extension_repository`, or `INSTALL <name> FROM <repository>` / `VERSION`) must come first.\n *\n * Call it while setting up the session, before running queries. Requests sent while a prefetch runs wait for it.\n *\n * Resolves to the names that are held for LOAD, once every download has finished, failed or timed out (after\n * `timeoutMs`, 30 seconds by default). A name that can't be resolved or downloaded is skipped, leaving the\n * download to LOAD, which reports any error; so are extensions that are already loaded. Each prefetched extension\n * serves one LOAD, at most 256 MiB is held for LOADs that haven't run yet, and `reset()` or `open()` drops what no\n * LOAD took. Does nothing in Node.js.\n */\n public async prefetchExtensions(names: string[], timeoutMs?: number): Promise<string[]> {\n const task = new WorkerTask<WorkerRequestType.PREFETCH_EXTENSIONS, [string[], number | undefined], string[]>(\n WorkerRequestType.PREFETCH_EXTENSIONS,\n [names, timeoutMs],\n );\n return await this.postTask(task);\n }\n\n /** Tokenize a script text */\n public async tokenize(text: string): Promise<ScriptTokens> {\n const task = new WorkerTask<WorkerRequestType.TOKENIZE, string, ScriptTokens>(WorkerRequestType.TOKENIZE, text);\n const tokens = await this.postTask(task);\n return tokens;\n }\n\n /** Connect to the database */\n public async connectInternal(): Promise<number> {\n const task = new WorkerTask<WorkerRequestType.CONNECT, null, ConnectionID>(WorkerRequestType.CONNECT, null);\n return await this.postTask(task);\n }\n\n /** Connect to the database */\n public async connect(): Promise<AsyncDuckDBConnection> {\n const cid = await this.connectInternal();\n // A cancel must reach a query that runs inside a worker call, which no message does: keep the flag at hand\n if (typeof SharedArrayBuffer !== 'undefined') {\n const handle = await this.getInterruptHandle(cid);\n if (handle !== null) this._interruptHandles.set(cid, handle);\n }\n return new AsyncDuckDBConnection(this, cid);\n }\n\n /** Disconnect from the database */\n public async disconnect(conn: ConnectionID): Promise<void> {\n this._interruptHandles.delete(conn);\n this.endPendingQuery(conn);\n const task = new WorkerTask<WorkerRequestType.DISCONNECT, ConnectionID, null>(\n WorkerRequestType.DISCONNECT,\n conn,\n );\n await this.postTask(task);\n }\n\n /** Run a query */\n public async runQuery(conn: ConnectionID, text: string): Promise<Uint8Array> {\n if( this.shouldOPFSFileHandling() ){\n const files = await this.registerOPFSFileFromSQL(text);\n try {\n return await this._runQueryAsync(conn, text);\n } finally {\n if( files.length > 0 ){\n await this.dropFiles(files);\n }\n }\n } else {\n return await this._runQueryAsync(conn, text);\n }\n }\n\n private async _runQueryAsync(conn: ConnectionID, text: string): Promise<Uint8Array> {\n const task = new WorkerTask<WorkerRequestType.RUN_QUERY, [ConnectionID, string], Uint8Array>(\n WorkerRequestType.RUN_QUERY,\n [conn, text],\n );\n return await this.postTask(task);\n }\n\n /** Start a pending query */\n public async startPendingQuery(\n conn: ConnectionID,\n text: string,\n allowStreamResult: boolean = false,\n ): Promise<Uint8Array | null> {\n if( this.shouldOPFSFileHandling() ){\n const files = await this.registerOPFSFileFromSQL(text);\n try {\n return await this._startPendingQueryAsync(conn, text, allowStreamResult);\n } finally {\n if( files.length > 0 ){\n await this.dropFiles(files);\n }\n }\n } else {\n return await this._startPendingQueryAsync(conn, text, allowStreamResult);\n }\n }\n\n private async _startPendingQueryAsync(\n conn: ConnectionID,\n text: string,\n allowStreamResult: boolean = false,\n ): Promise<Uint8Array | null> {\n const task = new WorkerTask<\n WorkerRequestType.START_PENDING_QUERY,\n [ConnectionID, string, boolean],\n Uint8Array | null\n >(WorkerRequestType.START_PENDING_QUERY, [conn, text, allowStreamResult]);\n this.beginPendingQuery(conn);\n return await this.trackPendingQuery(conn, this.postTask(task));\n }\n\n /** Poll a pending query */\n public async pollPendingQuery(conn: ConnectionID): Promise<Uint8Array | null> {\n if (this.takeCancelFlag() && this._pendingQueries.has(conn)) {\n // Cancelled through registerCancelSAB before this poll was sent: the poll reports the cancel\n await this.cancelPendingQuery(conn);\n }\n const task = new WorkerTask<WorkerRequestType.POLL_PENDING_QUERY, ConnectionID, Uint8Array | null>(\n WorkerRequestType.POLL_PENDING_QUERY,\n conn,\n );\n return await this.trackPendingQuery(conn, this.postTask(task));\n }\n /**\n * Cancel a pending query.\n *\n * On the threads bundle the worker runs a poll to its end before it reads another message, so the query is\n * interrupted through shared memory first (getInterruptHandle): a running poll stops at the engine's next check\n * and fails with an interrupt error, and in-flight HTTP requests of the query are abandoned. The cancel message\n * then ends the query in the worker, if the poll has not already ended it.\n */\n public async cancelPendingQuery(conn: ConnectionID): Promise<boolean> {\n const handle = this._interruptHandles.get(conn);\n const interrupted = handle !== undefined && this._pendingQueries.has(conn);\n if (interrupted) {\n interruptConnection(handle);\n }\n this.endPendingQuery(conn);\n const task = new WorkerTask<WorkerRequestType.CANCEL_PENDING_QUERY, ConnectionID, boolean>(\n WorkerRequestType.CANCEL_PENDING_QUERY,\n conn,\n );\n const cancelled = await this.postTask(task);\n return cancelled || interrupted;\n }\n\n /**\n * The connection's interrupt flag, or null when the wasm memory is not shared (the base bundle). Then\n * `interruptConnection(handle)` interrupts what runs on the connection from any thread, also while the worker is\n * inside the call that runs it and no message reaches it.\n */\n public async getInterruptHandle(conn: ConnectionID): Promise<InterruptHandle | null> {\n const cached = this._interruptHandles.get(conn);\n if (cached) return cached;\n const task = new WorkerTask<WorkerRequestType.GET_INTERRUPT_HANDLE, ConnectionID, InterruptHandle | null>(\n WorkerRequestType.GET_INTERRUPT_HANDLE,\n conn,\n );\n return await this.postTask(task);\n }\n\n /**\n * The connection's query progress slot, or null when the wasm memory is not shared (the base bundle). Read it\n * with `readQueryProgress(handle)`, also while a query runs. The engine reports progress only with\n * `SET enable_progress_bar = true`.\n */\n public async getProgressHandle(conn: ConnectionID): Promise<QueryProgressHandle | null> {\n const task = new WorkerTask<WorkerRequestType.GET_PROGRESS_HANDLE, ConnectionID, QueryProgressHandle | null>(\n WorkerRequestType.GET_PROGRESS_HANDLE,\n conn,\n );\n return await this.postTask(task);\n }\n\n /**\n * The progress of the connection's query as the engine last reported it, on every bundle. The worker answers\n * between two calls only: on the threads bundle, read a running query's progress with getProgressHandle.\n */\n public async getQueryProgress(conn: ConnectionID): Promise<QueryProgress | null> {\n const task = new WorkerTask<WorkerRequestType.GET_QUERY_PROGRESS, ConnectionID, QueryProgress | null>(\n WorkerRequestType.GET_QUERY_PROGRESS,\n conn,\n );\n return await this.postTask(task);\n }\n\n /**\n * Register a SharedArrayBuffer of at least 4 bytes through which any thread can cancel the most recently started\n * pending query: `Atomics.store(new Int32Array(sab), 0, 1)`. The flag is checked before each poll and every\n * 50 ms while a pending query runs; a cancel resets it to 0 and goes through `cancelPendingQuery`, so on the\n * threads bundle it also interrupts a poll that is running. For a specific connection use `cancelSent()` or\n * `getInterruptHandle`. Registering again replaces the buffer.\n */\n public registerCancelSAB(sab: SharedArrayBuffer): void {\n if (typeof SharedArrayBuffer === 'undefined') {\n throw new TypeError(\n 'registerCancelSAB requires SharedArrayBuffer support (cross-origin isolation must be enabled)',\n );\n }\n if (!(sab instanceof SharedArrayBuffer)) {\n throw new TypeError('registerCancelSAB requires a SharedArrayBuffer (got a non-shared buffer)');\n }\n if (sab.byteLength < 4) {\n throw new RangeError(`registerCancelSAB requires at least 4 bytes for the Int32 flag (got ${sab.byteLength})`);\n }\n this._cancelFlag = new Int32Array(sab, 0, 1);\n this.updateCancelWatcher();\n }\n\n /** A pending query starts on the connection */\n protected beginPendingQuery(conn: ConnectionID): void {\n // Re-added at the end: the most recently started query is the one registerCancelSAB cancels\n this._pendingQueries.delete(conn);\n this._pendingQueries.add(conn);\n this.updateCancelWatcher();\n }\n /** The connection's pending query ended (it has a result, failed, or was cancelled) */\n protected endPendingQuery(conn: ConnectionID): void {\n this._pendingQueries.delete(conn);\n this.updateCancelWatcher();\n }\n /** Track the end of a pending query through the response to its start or a poll */\n protected async trackPendingQuery(\n conn: ConnectionID,\n response: Promise<Uint8Array | null>,\n ): Promise<Uint8Array | null> {\n try {\n const header = await response;\n if (header !== null) this.endPendingQuery(conn);\n return header;\n } catch (e) {\n this.endPendingQuery(conn);\n throw e;\n }\n }\n /** Forget all connections, the database they belonged to is gone */\n protected forgetConnections(): void {\n this._interruptHandles.clear();\n this._pendingQueries.clear();\n this.updateCancelWatcher();\n }\n /** Consume a cancel requested through registerCancelSAB */\n protected takeCancelFlag(): boolean {\n if (this._cancelFlag === null) return false;\n return Atomics.compareExchange(this._cancelFlag, 0, 1, 0) === 1;\n }\n /** Watch the flag of registerCancelSAB while a pending query runs */\n protected updateCancelWatcher(): void {\n const watch = this._cancelFlag !== null && this._pendingQueries.size > 0;\n if (watch && this._cancelWatcher === null) {\n this._cancelWatcher = setInterval(() => {\n let latest: ConnectionID | undefined;\n for (const conn of this._pendingQueries) latest = conn;\n if (latest === undefined || !this.takeCancelFlag()) return;\n this.cancelPendingQuery(latest).catch(e => console.error('[cancel-sab] cancelPendingQuery failed:', e));\n }, CANCEL_SAB_POLL_MS);\n } else if (!watch && this._cancelWatcher !== null) {\n clearInterval(this._cancelWatcher);\n this._cancelWatcher = null;\n }\n }\n\n /** Fetch query results */\n public async fetchQueryResults(conn: ConnectionID): Promise<Uint8Array | null> {\n const task = new WorkerTask<WorkerRequestType.FETCH_QUERY_RESULTS, ConnectionID, Uint8Array | null>(\n WorkerRequestType.FETCH_QUERY_RESULTS,\n conn,\n );\n return await this.postTask(task);\n }\n\n /** Get table names */\n public async getTableNames(conn: number, text: string): Promise<string[]> {\n const task = new WorkerTask<WorkerRequestType.GET_TABLE_NAMES, [number, string], string[]>(\n WorkerRequestType.GET_TABLE_NAMES,\n [conn, text],\n );\n return await this.postTask(task);\n }\n\n /** Prepare a statement and return its identifier */\n public async createPrepared(conn: number, text: string): Promise<number> {\n const task = new WorkerTask<WorkerRequestType.CREATE_PREPARED, [number, string], number>(\n WorkerRequestType.CREATE_PREPARED,\n [conn, text],\n );\n return await this.postTask(task);\n }\n /** Close a prepared statement */\n public async closePrepared(conn: number, statement: number): Promise<void> {\n const task = new WorkerTask<WorkerRequestType.CLOSE_PREPARED, [number, number], null>(\n WorkerRequestType.CLOSE_PREPARED,\n [conn, statement],\n );\n await this.postTask(task);\n }\n /** Execute a prepared statement and return the full result */\n public async runPrepared(conn: number, statement: number, params: any[]): Promise<Uint8Array> {\n const task = new WorkerTask<WorkerRequestType.RUN_PREPARED, [ConnectionID, number, any[]], Uint8Array>(\n WorkerRequestType.RUN_PREPARED,\n [conn, statement, params],\n );\n return await this.postTask(task);\n }\n /** Execute a prepared statement and stream the result */\n public async sendPrepared(conn: number, statement: number, params: any[]): Promise<Uint8Array> {\n const task = new WorkerTask<WorkerRequestType.SEND_PREPARED, [ConnectionID, number, any[]], Uint8Array>(\n WorkerRequestType.SEND_PREPARED,\n [conn, statement, params],\n );\n return await this.postTask(task);\n }\n /** Glob file infos */\n public async globFiles(path: string): Promise<WebFile[]> {\n const task = new WorkerTask<WorkerRequestType.GLOB_FILE_INFOS, string, WebFile[]>(\n WorkerRequestType.GLOB_FILE_INFOS,\n path,\n );\n return await this.postTask(task);\n }\n /** Register file text */\n public async registerFileText(name: string, text: string): Promise<void> {\n const buffer = TEXT_ENCODER.encode(text);\n await this.registerFileBuffer(name, buffer);\n }\n /** Register a file path. */\n public async registerFileURL(\n name: string,\n url: string,\n proto: DuckDBDataProtocol,\n directIO: boolean,\n ): Promise<void> {\n if (url === undefined) {\n url = name;\n }\n const task = new WorkerTask<\n WorkerRequestType.REGISTER_FILE_URL,\n [string, string, DuckDBDataProtocol, boolean],\n null\n >(WorkerRequestType.REGISTER_FILE_URL, [name, url, proto, directIO]);\n await this.postTask(task);\n }\n\n /** Register an empty file buffer. */\n public async registerEmptyFileBuffer(name: string): Promise<void> {\n /*\n const task = new WorkerTask<WorkerRequestType.REGISTER_FILE_BUFFER, [string, Uint8Array], null>(\n WorkerRequestType.REGISTER_FILE_BUFFER,\n [name, new Uint8Array()],\n );\n await this.postTask(task);\n*/\n }\n\n /** Register a file buffer. */\n public async registerFileBuffer(name: string, buffer: Uint8Array): Promise<void> {\n const task = new WorkerTask<WorkerRequestType.REGISTER_FILE_BUFFER, [string, Uint8Array], null>(\n WorkerRequestType.REGISTER_FILE_BUFFER,\n [name, buffer],\n );\n await this.postTask(task, [buffer.buffer]);\n }\n\n /** Register a file handle. */\n public async registerFileHandle<HandleType>(\n name: string,\n handle: HandleType,\n protocol: DuckDBDataProtocol,\n directIO: boolean,\n ): Promise<void> {\n const task = new WorkerTask<\n WorkerRequestType.REGISTER_FILE_HANDLE,\n [string, any, DuckDBDataProtocol, boolean],\n null\n >(WorkerRequestType.REGISTER_FILE_HANDLE, [name, handle, protocol, directIO]);\n await this.postTask(task, []);\n }\n\n /** Prepare an opfs:// file (or the files a glob pattern matches) for the next queries, returns their names.\n * Registered files are held open until they are dropped, for writing unless `mode` is 'read' */\n public async registerOPFSFileName(name: string, mode: OPFSAccessMode = 'write'): Promise<string[]> {\n const task = new WorkerTask<WorkerRequestType.REGISTER_OPFS_FILE_NAME, [string, OPFSAccessMode], string[]>(\n WorkerRequestType.REGISTER_OPFS_FILE_NAME,\n [name, mode],\n );\n return await this.postTask(task, []);\n }\n\n /** Enable file statistics */\n public async collectFileStatistics(name: string, enable: boolean): Promise<void> {\n const task = new WorkerTask<WorkerRequestType.COLLECT_FILE_STATISTICS, [string, boolean], null>(\n WorkerRequestType.COLLECT_FILE_STATISTICS,\n [name, enable],\n );\n await this.postTask(task, []);\n }\n\n /** Export file statistics */\n public async exportFileStatistics(name: string): Promise<FileStatistics> {\n const task = new WorkerTask<WorkerRequestType.EXPORT_FILE_STATISTICS, string, FileStatistics>(\n WorkerRequestType.EXPORT_FILE_STATISTICS,\n name,\n );\n return await this.postTask(task, []);\n }\n\n /** Copy a file to a buffer. */\n public async copyFileToBuffer(name: string): Promise<Uint8Array> {\n const task = new WorkerTask<WorkerRequestType.COPY_FILE_TO_BUFFER, string, Uint8Array>(\n WorkerRequestType.COPY_FILE_TO_BUFFER,\n name,\n );\n return await this.postTask(task);\n }\n\n /** Copy a file to a path. */\n public async copyFileToPath(name: string, path: string): Promise<void> {\n const task = new WorkerTask<WorkerRequestType.COPY_FILE_TO_PATH, [string, string], null>(\n WorkerRequestType.COPY_FILE_TO_PATH,\n [name, path],\n );\n await this.postTask(task);\n }\n\n /** Insert arrow from an ipc stream */\n public async insertArrowFromIPCStream(\n conn: ConnectionID,\n buffer: Uint8Array,\n options?: ArrowInsertOptions,\n ): Promise<void> {\n if (buffer.length == 0) return;\n // Pass to the worker\n const task = new WorkerTask<\n WorkerRequestType.INSERT_ARROW_FROM_IPC_STREAM,\n [number, Uint8Array, ArrowInsertOptions | undefined],\n null\n >(WorkerRequestType.INSERT_ARROW_FROM_IPC_STREAM, [conn, buffer, options]);\n await this.postTask(task, [buffer.buffer]);\n }\n /** Insert a csv file */\n public async insertCSVFromPath(conn: ConnectionID, path: string, options: CSVInsertOptions): Promise<void> {\n // Flatten the table options\n if (options.columns !== undefined) {\n const out = [];\n for (const k in options.columns) {\n const type = options.columns[k];\n out.push(arrowToSQLField(k, type));\n }\n options.columnsFlat = out;\n delete options.columns;\n }\n\n // Pass to the worker\n const task = new WorkerTask<WorkerRequestType.INSERT_CSV_FROM_PATH, [number, string, CSVInsertOptions], null>(\n WorkerRequestType.INSERT_CSV_FROM_PATH,\n [conn, path, options],\n );\n await this.postTask(task);\n }\n /** Insert a json file */\n public async insertJSONFromPath(conn: ConnectionID, path: string, options: JSONInsertOptions): Promise<void> {\n // Flatten the table options\n if (options.columns !== undefined) {\n const out = [];\n for (const k in options.columns) {\n const type = options.columns[k];\n out.push(arrowToSQLField(k, type));\n }\n options.columnsFlat = out;\n delete options.columns;\n }\n\n // Pass to the worker\n const task = new WorkerTask<WorkerRequestType.INSERT_JSON_FROM_PATH, [number, string, JSONInsertOptions], null>(\n WorkerRequestType.INSERT_JSON_FROM_PATH,\n [conn, path, options],\n );\n await this.postTask(task);\n }\n\n /** opfs:// files named in SQL are prepared ahead of the query when the config asks for it, whether the\n * database itself lives in OPFS or not */\n private shouldOPFSFileHandling(): boolean {\n return this.config.opfs?.fileHandling == 'auto';\n }\n\n private async registerOPFSFileFromSQL(text: string) {\n const files = searchOPFSFiles(text);\n // A database that is attached is written to, everything else is read\n const mode: OPFSAccessMode = /\\bATTACH\\b/i.test(text) ? 'write' : 'read';\n const result: string[] = [];\n for (const file of files) {\n try {\n result.push(...(await this.registerOPFSFileName(file, mode)));\n } catch (e) {\n console.error(e);\n throw new Error('File Not found:' + file);\n }\n }\n return result;\n }\n}\n", "import { DuckDBModule } from './duckdb_module';\nimport { Logger } from '../log';\nimport { OPFSAccessMode } from './opfs_scratch';\nimport { UDFFunction } from './udf_function';\nimport * as udf_rt from './udf_runtime';\n\n/** Wrapper for TextDecoder to support shared array buffers */\nfunction TextDecoderWrapper(): (input?: BufferSource) => string {\n const decoder = new TextDecoder();\n return (data: any) => {\n if (typeof SharedArrayBuffer !== 'undefined' && data.buffer instanceof SharedArrayBuffer) {\n data = new Uint8Array(data);\n }\n return decoder.decode(data);\n };\n}\n/** Helper to decode text */\nexport const decodeText = TextDecoderWrapper();\n\n/** Copy a buffer */\nexport function failWith(mod: DuckDBModule, msg: string): void {\n console.error(`FAIL WITH: ${msg}`);\n mod.ccall('duckdb_web_fail_with', null, ['string'], [msg]);\n}\n\n/** Copy a buffer */\nexport function copyBuffer(mod: DuckDBModule, begin: number, length: number): Uint8Array {\n const buffer = mod.HEAPU8.subarray(begin, begin + length);\n const copy = new Uint8Array(new ArrayBuffer(buffer.byteLength));\n copy.set(buffer);\n return copy;\n}\n\n/** Decode a string */\nexport function readString(mod: DuckDBModule, begin: number, length: number): string {\n return decodeText(mod.HEAPU8.subarray(begin, begin + length));\n}\n\n/** The data protocol */\nexport enum DuckDBDataProtocol {\n BUFFER = 0,\n NODE_FS = 1,\n BROWSER_FILEREADER = 2,\n BROWSER_FSACCESS = 3,\n HTTP = 4,\n S3 = 5,\n /** Files held by the runtime outside the WASM heap (js_buffer://) */\n JS_BUFFER = 6,\n}\n\n/** File flags for opening files*/\nexport enum FileFlags {\n //! Open file with read access\n FILE_FLAGS_READ = 1 << 0,\n //! Open file with write access\n FILE_FLAGS_WRITE = 1 << 1,\n //! Use direct IO when reading/writing to the file\n FILE_FLAGS_DIRECT_IO = 1 << 2,\n //! Create file if not exists, can only be used together with WRITE\n FILE_FLAGS_FILE_CREATE = 1 << 3,\n //! Always create a new file. If a file exists, the file is truncated. Cannot be used together with CREATE.\n FILE_FLAGS_FILE_CREATE_NEW = 1 << 4,\n //! Open file in append mode\n FILE_FLAGS_APPEND = 1 << 5,\n FILE_FLAGS_PRIVATE = 1 << 6,\n FILE_FLAGS_NULL_IF_NOT_EXISTS = 1 << 7,\n FILE_FLAGS_PARALLEL_ACCESS = 1 << 8,\n FILE_FLAGS_EXCLUSIVE_CREATE = 1 << 9,\n FILE_FLAGS_NULL_IF_EXISTS = 1 << 10\n}\n\n/** Configuration for the AWS S3 Filesystem */\nexport interface S3Config {\n region?: string;\n endpoint?: string;\n accessKeyId?: string;\n secretAccessKey?: string;\n sessionToken?: string;\n}\n\n/** An info for a file registered with DuckDB */\nexport interface DuckDBFileInfo {\n cacheEpoch: number;\n fileId: number;\n fileName: string;\n dataProtocol: DuckDBDataProtocol;\n dataUrl: string | null;\n reliableHeadRequests?: boolean;\n allowFullHttpReads?: boolean;\n forceFullHttpReads?: boolean;\n s3Config?: S3Config;\n}\n\n/** Global info for all files registered with DuckDB */\nexport interface DuckDBGlobalFileInfo {\n cacheEpoch: number;\n reliableHeadRequests?: boolean;\n allowFullHttpReads?: boolean;\n forceFullHttpReads?: boolean;\n s3Config?: S3Config;\n}\n\nexport interface PreparedDBFileHandle {\n path: string;\n handle: any;\n fromCached: boolean;\n}\n\n/** Call a function with packed response buffer */\nexport function callSRet(\n mod: DuckDBModule,\n funcName: string,\n argTypes: Array<Emscripten.JSType>,\n args: Array<any>,\n): [number, number, number] {\n const stackPointer = mod.stackSave();\n\n // Allocate the packed response buffer\n const response = mod.stackAlloc(3 * 8);\n argTypes.unshift('number');\n args.unshift(response);\n\n // Do the call\n mod.ccall(funcName, null, argTypes, args);\n\n // Read the response\n const status = mod.HEAPF64[(response >>> 3) + 0];\n const data = mod.HEAPF64[(response >>> 3) + 1];\n const dataSize = mod.HEAPF64[(response >>> 3) + 2];\n\n // Restore the stack\n mod.stackRestore(stackPointer);\n return [status, data, dataSize];\n}\n\n/** Drop response buffers */\nexport function dropResponseBuffers(mod: DuckDBModule): void {\n mod.ccall('duckdb_web_clear_response', null, [], []);\n}\n\n/** The duckdb runtime */\nexport interface DuckDBRuntime {\n _files?: Map<string, any>;\n _udfFunctions: Map<number, UDFFunction>;\n\n // Receive the logger of the bindings, file operations are logged at debug level\n setLogger?(logger: Logger): void;\n\n // Test a platform feature\n testPlatformFeature(mod: DuckDBModule, feature: number): boolean;\n\n // File APIs with dedicated file identifier\n getDefaultDataProtocol(mod: DuckDBModule): number;\n openFile(mod: DuckDBModule, fileId: number, flags: FileFlags): void;\n syncFile(mod: DuckDBModule, fileId: number): void;\n closeFile(mod: DuckDBModule, fileId: number): void;\n dropFile(mod: DuckDBModule, fileNamePtr: number, fileNameLen: number): void;\n getLastFileModificationTime(mod: DuckDBModule, fileId: number): number;\n truncateFile(mod: DuckDBModule, fileId: number, newSize: number): void;\n readFile(mod: DuckDBModule, fileId: number, buffer: number, bytes: number, location: number): number;\n writeFile(mod: DuckDBModule, fileId: number, buffer: number, bytes: number, location: number): number;\n\n // File APIs with path parameter\n removeDirectory(mod: DuckDBModule, pathPtr: number, pathLen: number): void;\n checkDirectory(mod: DuckDBModule, pathPtr: number, pathLen: number): boolean;\n createDirectory(mod: DuckDBModule, pathPtr: number, pathLen: number): void;\n listDirectoryEntries(mod: DuckDBModule, pathPtr: number, pathLen: number): boolean;\n glob(mod: DuckDBModule, pathPtr: number, pathLen: number): void;\n moveFile(mod: DuckDBModule, fromPtr: number, fromLen: number, toPtr: number, toLen: number): void;\n checkFile(mod: DuckDBModule, pathPtr: number, pathLen: number): boolean;\n removeFile(mod: DuckDBModule, pathPtr: number, pathLen: number): void;\n\n // Prepare a file handle that could only be acquired aschronously\n prepareFileHandle?: (path: string, protocol: DuckDBDataProtocol) => Promise<PreparedDBFileHandle[]>;\n prepareFileHandles?: (\n path: string[],\n protocol: DuckDBDataProtocol,\n mode?: OPFSAccessMode,\n ) => Promise<PreparedDBFileHandle[]>;\n prepareDBFileHandle?: (path: string, protocol: DuckDBDataProtocol) => Promise<PreparedDBFileHandle[]>;\n /** Finish file operations that could only be completed asynchronously, called between queries */\n checkpointFiles?: () => Promise<void>;\n /** Mount the origin private file system, a no-op where there is none */\n mountOPFS?: () => Promise<void>;\n\n // Internal API - experimental\n progressUpdate(final: number, percentage: number, iteration: number): void;\n\n // Call a scalar UDF function\n callScalarUDF(\n mod: DuckDBModule,\n response: number,\n funcId: number,\n descPtr: number,\n descSize: number,\n ptrsPtr: number,\n ptrsSize: number,\n ): void;\n}\n\nexport const DEFAULT_RUNTIME: DuckDBRuntime = {\n _udfFunctions: new Map(),\n\n testPlatformFeature: (_mod: DuckDBModule, _feature: number): boolean => false,\n getDefaultDataProtocol: (_mod: DuckDBModule): number => DuckDBDataProtocol.BUFFER,\n openFile: (_mod: DuckDBModule, _fileId: number, flags: FileFlags): void => {},\n syncFile: (_mod: DuckDBModule, _fileId: number): void => {},\n closeFile: (_mod: DuckDBModule, _fileId: number): void => {},\n dropFile: (_mod: DuckDBModule, _fileNamePtr: number, _fileNameLen: number): void => {},\n getLastFileModificationTime: (_mod: DuckDBModule, _fileId: number): number => {\n return 0;\n },\n progressUpdate: (_final: number, _percentage: number, _iteration: number): void => {\n return;\n },\n truncateFile: (_mod: DuckDBModule, _fileId: number, _newSize: number): void => {},\n readFile: (_mod: DuckDBModule, _fileId: number, _buffer: number, _bytes: number, _location: number): number => {\n return 0;\n },\n writeFile: (_mod: DuckDBModule, _fileId: number, _buffer: number, _bytes: number, _location: number): number => {\n return 0;\n },\n\n removeDirectory: (_mod: DuckDBModule, _pathPtr: number, _pathLen: number): void => {},\n checkDirectory: (_mod: DuckDBModule, _pathPtr: number, _pathLen: number): boolean => {\n return false;\n },\n createDirectory: (_mod: DuckDBModule, _pathPtr: number, _pathLen: number): void => {},\n listDirectoryEntries: (_mod: DuckDBModule, _pathPtr: number, _pathLen: number): boolean => {\n return false;\n },\n glob: (_mod: DuckDBModule, _pathPtr: number, _pathLen: number): void => {},\n moveFile: (_mod: DuckDBModule, _fromPtr: number, _fromLen: number, _toPtr: number, _toLen: number): void => {},\n checkFile: (_mod: DuckDBModule, _pathPtr: number, _pathLen: number): boolean => {\n return false;\n },\n removeFile: (_mod: DuckDBModule, _pathPtr: number, _pathLen: number): void => {},\n callScalarUDF: (\n mod: DuckDBModule,\n response: number,\n funcId: number,\n descPtr: number,\n descSize: number,\n ptrsPtr: number,\n ptrsSize: number,\n ): void => {\n udf_rt.callScalarUDF(DEFAULT_RUNTIME, mod, response, funcId, descPtr, descSize, ptrsPtr, ptrsSize);\n },\n};\n", "// Haybarn: prefetching of wasm extensions inside the worker.\n//\n// LOAD runs synchronously inside the engine: the extension provider (lib/src/extension_provider.cc) downloads the\n// extension with a synchronous XHR and hashes it with SHA-256 compiled to wasm before checking its signature.\n// Prefetching does that work ahead of time and asynchronously: all downloads run in parallel, the signature hash is\n// computed with WebCrypto, and the module is compiled with WebAssembly.compileStreaming (which also lets Chrome cache\n// the compiled code). The provider takes the entry for its URL, so it only has to check the RSA signature against the\n// hash, and dlopen instantiates the compiled module once that check has passed (scripts/patch_dylink_glue.cjs).\n//\n// The hash is computed here over exactly the bytes the provider is given, and neither ever leaves this worker, so\n// this trusts nothing the synchronous path didn't already trust. The signature check itself stays in the engine.\n//\n// This runs in the worker's event loop, between requests: the dispatcher processes requests in order, so a request\n// sent while a prefetch runs waits for it. On the threads bundle the provider fetches on the main runtime thread,\n// which is this one, so the entries are where it looks for them.\n\n/** The size of the signature at the end of an extension file */\nconst SIGNATURE_SIZE = 256;\n/** The chunk size of the two-level hash. Must match the engine's verifier (extension_load.cpp). */\nconst HASH_CHUNK_SIZE = 1024 * 1024;\n/** The most bytes held for LOADs that haven't taken them; prefetches beyond it are left to LOAD */\nconst MAX_HELD_BYTES = 256 * 1024 * 1024;\n/** How long a download may take before it is left to LOAD. Requests wait for prefetches, so one must never hang. */\nexport const PREFETCH_TIMEOUT_MS = 30_000;\n\n/** A prefetched extension */\nexport interface PrefetchedExtension {\n /** The file, as LOAD would have downloaded it */\n bytes: Uint8Array;\n /** SHA-256 over the SHA-256 hashes of each 1 MiB chunk of the file without its signature */\n hash: Uint8Array | null;\n /** The module compiled from the same download, or null */\n module: WebAssembly.Module | null;\n}\n\n/** Prefetched extensions by URL, until a LOAD takes them */\nconst prefetched = new Map<string, PrefetchedExtension>();\n/** Prefetches that are still running, by URL */\nconst running = new Map<string, Promise<boolean>>();\n/** The bytes held in `prefetched` */\nlet heldBytes = 0;\n/** Bumped by clearPrefetchedExtensions, so prefetches still running then don't add their entries after it */\nlet generation = 0;\n\n/** Compute the engine's two-level signature hash of an extension file */\nexport async function computeExtensionHash(bytes: Uint8Array): Promise<Uint8Array | null> {\n if (bytes.byteLength < SIGNATURE_SIZE || typeof crypto === 'undefined' || !crypto.subtle) {\n return null;\n }\n const end = bytes.byteLength - SIGNATURE_SIZE;\n const chunks: Promise<ArrayBuffer>[] = [];\n for (let offset = 0; offset < end; offset += HASH_CHUNK_SIZE) {\n chunks.push(crypto.subtle.digest('SHA-256', bytes.subarray(offset, Math.min(end, offset + HASH_CHUNK_SIZE))));\n }\n const hashes = await Promise.all(chunks);\n const concatenated = new Uint8Array(hashes.length * 32);\n hashes.forEach((h, i) => concatenated.set(new Uint8Array(h), i * 32));\n return new Uint8Array(await crypto.subtle.digest('SHA-256', concatenated));\n}\n\n/**\n * Download, hash and compile one extension. Resolves to whether it is now held for LOAD. Failures are dropped: LOAD\n * then downloads it itself and reports the error.\n */\nasync function prefetchOne(url: string, timeoutMs: number): Promise<boolean> {\n const startedIn = generation;\n try {\n // The signal also aborts reading the body, and with it the compile\n const signal = typeof AbortSignal.timeout === 'function' ? AbortSignal.timeout(timeoutMs) : undefined;\n const response = await fetch(url, { signal });\n // LOAD's XHR only accepts 200\n if (response.status !== 200) {\n return false;\n }\n // Compile from the response itself and read the bytes from a clone, so both come from one download. Without a\n // module, dlopen compiles the bytes as before.\n let compiling: Promise<WebAssembly.Module | null> = Promise.resolve(null);\n let body = response;\n if (typeof WebAssembly.compileStreaming === 'function') {\n body = response.clone();\n compiling = WebAssembly.compileStreaming(response).catch(() => null);\n }\n const bytes = new Uint8Array(await body.arrayBuffer());\n // Without a hash the provider hashes the file itself\n const [hash, module] = await Promise.all([computeExtensionHash(bytes).catch(() => null), compiling]);\n if (generation !== startedIn || heldBytes + bytes.byteLength > MAX_HELD_BYTES) {\n return false;\n }\n prefetched.set(url, { bytes, hash, module });\n heldBytes += bytes.byteLength;\n return true;\n } catch (e) {\n // Network error or timeout: leave it to LOAD\n return false;\n } finally {\n running.delete(url);\n }\n}\n\n/**\n * Prefetch extensions by URL. Resolves to the URLs that are held for LOAD once every download has finished, failed\n * or timed out; never rejects.\n */\nexport async function prefetchExtensions(urls: string[], timeoutMs: number = PREFETCH_TIMEOUT_MS): Promise<string[]> {\n installPrefetchHook();\n const work: Promise<boolean>[] = [];\n for (const url of urls) {\n if (prefetched.has(url)) {\n work.push(Promise.resolve(true));\n continue;\n }\n let p = running.get(url);\n if (!p) {\n p = prefetchOne(url, timeoutMs);\n running.set(url, p);\n }\n work.push(p);\n }\n const held = await Promise.all(work);\n return urls.filter((_, i) => held[i]);\n}\n\n/** Take the prefetched entry for a URL. Called by the provider's LOAD; each entry serves one LOAD. */\nexport function takePrefetchedExtension(url: string): PrefetchedExtension | null {\n const entry = prefetched.get(url);\n if (!entry) {\n return null;\n }\n prefetched.delete(url);\n heldBytes -= entry.bytes.byteLength;\n return entry;\n}\n\n/** Drop prefetched extensions that no LOAD took, including those still downloading */\nexport function clearPrefetchedExtensions(): void {\n prefetched.clear();\n heldBytes = 0;\n ++generation;\n}\n\n/** Make the prefetched entries reachable from the provider's LOAD */\nexport function installPrefetchHook(): void {\n (globalThis as any).__haybarnTakePrefetchedExtension = takePrefetchedExtension;\n}\n", "import { DuckDBBindings, DuckDBDataProtocol } from '../bindings';\nimport { WorkerResponseVariant, WorkerRequestVariant, WorkerRequestType, WorkerResponseType } from './worker_request';\nimport { Logger, LogEntryVariant } from '../log';\nimport { InstantiationProgress } from '../bindings/progress';\nimport { clearPrefetchedExtensions, prefetchExtensions } from './extension_prefetch';\n\nexport abstract class AsyncDuckDBDispatcher implements Logger {\n /** The bindings */\n protected _bindings: DuckDBBindings | null = null;\n /** The next message id */\n protected _nextMessageId = 0;\n\n /** Instantiate the wasm module */\n protected abstract instantiate(\n mainModule: string,\n pthreadWorker: string | null,\n progress?: (p: InstantiationProgress) => void,\n ): Promise<DuckDBBindings>;\n /** Post a response to the main thread */\n protected abstract postMessage(response: WorkerResponseVariant, transfer: ArrayBuffer[]): void;\n\n /** Send log entry to the main thread */\n public log(entry: LogEntryVariant): void {\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: 0,\n type: WorkerResponseType.LOG,\n data: entry,\n },\n [],\n );\n }\n\n /** Send plain OK without further data */\n protected sendOK(request: WorkerRequestVariant): void {\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.OK,\n data: null,\n },\n [],\n );\n }\n\n /** Fail with an error */\n protected failWith(request: WorkerRequestVariant, e: Error): void {\n // Workaround for Firefox not being able to perform structured-clone on Native Errors\n // https://bugzilla.mozilla.org/show_bug.cgi?id=1556604\n const obj: any = {\n name: e.name,\n message: e.message,\n stack: e.stack || undefined,\n };\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.ERROR,\n data: obj,\n },\n [],\n );\n return;\n }\n\n /** The requests are processed in the order they arrive, even if a request has to wait for asynchronous work */\n private _requests: Promise<void> = Promise.resolve();\n /** Checkpoint files, unless a query is still executing: a pending query that was not polled to its end or a\n * result stream that was not fetched to its end keeps DuckDB's worker threads busy between requests */\n private async checkpointFiles(): Promise<void> {\n if (this._bindings!.queriesInFlight()) return;\n await this._bindings!.checkpointFiles();\n }\n\n /** Process a request from the main thread */\n public onMessage(request: WorkerRequestVariant): Promise<void> {\n const run = this._requests.then(() => this.processRequest(request));\n this._requests = run.catch(() => {});\n return run;\n }\n\n /** Process a single request */\n private async processRequest(request: WorkerRequestVariant): Promise<void> {\n // First process those requests that don't need bindings\n switch (request.type) {\n case WorkerRequestType.PING:\n this.sendOK(request);\n return;\n case WorkerRequestType.INSTANTIATE:\n if (this._bindings != null) {\n this.failWith(request, new Error('duckdb already initialized'));\n }\n try {\n // Only forward progress if the caller asked for it (older clients don't say).\n const forwardProgress =\n request.data[2] === false\n ? undefined\n : (p: InstantiationProgress) => {\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.INSTANTIATE_PROGRESS,\n data: p,\n },\n [],\n );\n };\n this._bindings = await this.instantiate(request.data[0], request.data[1], forwardProgress);\n this.sendOK(request);\n } catch (e: any) {\n console.log(e);\n this._bindings = null;\n this.failWith(request, e);\n }\n return;\n default:\n break;\n }\n\n // Bindings not initialized?\n if (!this._bindings) {\n return this.failWith(request, new Error('duckdb is not initialized'));\n }\n\n // Catch every exception and forward it as error message to the main thread\n try {\n // Files created by the previous request are moved into place before the next one runs\n await this.checkpointFiles();\n switch (request.type) {\n case WorkerRequestType.GET_VERSION:\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.VERSION_STRING,\n data: this._bindings.getVersion(),\n },\n [],\n );\n break;\n case WorkerRequestType.GET_FEATURE_FLAGS:\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.FEATURE_FLAGS,\n data: this._bindings.getFeatureFlags(),\n },\n [],\n );\n break;\n case WorkerRequestType.RESET:\n clearPrefetchedExtensions();\n this._bindings.reset();\n // Files written by this request are in place when it is acknowledged\n await this.checkpointFiles();\n this.sendOK(request);\n break;\n\n case WorkerRequestType.OPEN: {\n const path = request.data.path;\n if (path?.startsWith('opfs://')) {\n await this._bindings.prepareDBFileHandle(path, DuckDBDataProtocol.BROWSER_FSACCESS);\n request.data.useDirectIO = true;\n }\n // DuckDB's home directory is opfs://home where OPFS exists, it is in use from the start\n this.log({ timestamp: new Date(), level: 1, origin: 3, topic: 3, event: 3, value: 'mount' } as any);\n await this._bindings.mountOPFS();\n this.log({ timestamp: new Date(), level: 1, origin: 3, topic: 3, event: 3, value: 'open' } as any);\n // The new database may resolve extensions to other URLs\n clearPrefetchedExtensions();\n this._bindings.open(request.data);\n this.log({ timestamp: new Date(), level: 1, origin: 3, topic: 3, event: 3, value: 'opened' } as any);\n this.sendOK(request);\n break;\n }\n case WorkerRequestType.DROP_FILE:\n this._bindings.dropFile(request.data);\n // Files written by this request are in place when it is acknowledged\n await this.checkpointFiles();\n this.sendOK(request);\n break;\n case WorkerRequestType.DROP_FILES:\n this._bindings.dropFiles(request.data);\n // Files written by this request are in place when it is acknowledged\n await this.checkpointFiles();\n this.sendOK(request);\n break;\n case WorkerRequestType.FLUSH_FILES:\n this._bindings.flushFiles();\n // Files written by this request are in place when it is acknowledged\n await this.checkpointFiles();\n this.sendOK(request);\n break;\n case WorkerRequestType.PREFETCH_EXTENSIONS: {\n // Haybarn: only browsers gain. Node's LOAD reads files or downloads in a child process.\n const [names, timeoutMs] = request.data;\n const held: string[] = [];\n if (typeof XMLHttpRequest !== 'undefined') {\n const urls = new Map<string, string>();\n for (const name of names) {\n try {\n // Empty when the extension is already loaded\n const url = this._bindings.getExtensionUrl(name);\n if (url) {\n urls.set(name, url);\n }\n } catch (e) {\n // Not resolvable (e.g. no loadable extensions in this build): LOAD reports it\n }\n }\n const ready = new Set(await prefetchExtensions([...new Set(urls.values())], timeoutMs));\n for (const [name, url] of urls) {\n if (ready.has(url)) {\n held.push(name);\n }\n }\n }\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.EXTENSIONS_PREFETCHED,\n data: held,\n },\n [],\n );\n break;\n }\n case WorkerRequestType.CONNECT: {\n const conn = this._bindings.connect();\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.CONNECTION_INFO,\n data: conn.useUnsafe((_, c) => c),\n },\n [],\n );\n break;\n }\n case WorkerRequestType.DISCONNECT:\n this._bindings.disconnect(request.data);\n this.sendOK(request);\n break;\n case WorkerRequestType.CREATE_PREPARED: {\n const result = this._bindings.createPrepared(request.data[0], request.data[1]);\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.PREPARED_STATEMENT_ID,\n data: result,\n },\n [],\n );\n break;\n }\n case WorkerRequestType.CLOSE_PREPARED: {\n this._bindings.closePrepared(request.data[0], request.data[1]);\n this.sendOK(request);\n break;\n }\n case WorkerRequestType.RUN_PREPARED: {\n const result = this._bindings.runPrepared(request.data[0], request.data[1], request.data[2]);\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.QUERY_RESULT,\n data: result,\n },\n [result.buffer],\n );\n break;\n }\n case WorkerRequestType.RUN_QUERY: {\n const result = this._bindings.runQuery(request.data[0], request.data[1]);\n // Files the query wrote are in place when its result is acknowledged\n await this.checkpointFiles();\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.QUERY_RESULT,\n data: result,\n },\n [result.buffer],\n );\n break;\n }\n case WorkerRequestType.SEND_PREPARED: {\n const result = this._bindings.sendPrepared(request.data[0], request.data[1], request.data[2]);\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.QUERY_RESULT_HEADER,\n data: result,\n },\n [result.buffer],\n );\n break;\n }\n case WorkerRequestType.START_PENDING_QUERY: {\n const result = this._bindings.startPendingQuery(request.data[0], request.data[1], request.data[2]);\n await this.checkpointFiles();\n const transfer = [];\n if (result) {\n transfer.push(result.buffer);\n }\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.QUERY_RESULT_HEADER_OR_NULL,\n data: result,\n },\n transfer,\n );\n break;\n }\n case WorkerRequestType.POLL_PENDING_QUERY: {\n const result = this._bindings.pollPendingQuery(request.data);\n await this.checkpointFiles();\n const transfer = [];\n if (result) {\n transfer.push(result.buffer);\n }\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.QUERY_RESULT_HEADER_OR_NULL,\n data: result,\n },\n transfer,\n );\n break;\n }\n case WorkerRequestType.CANCEL_PENDING_QUERY: {\n const result = this._bindings.cancelPendingQuery(request.data);\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.SUCCESS,\n data: result,\n },\n [],\n );\n break;\n }\n // The SharedArrayBuffer of a handle is shared by postMessage, not copied\n case WorkerRequestType.GET_INTERRUPT_HANDLE:\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.INTERRUPT_HANDLE,\n data: this._bindings.getInterruptHandle(request.data),\n },\n [],\n );\n break;\n case WorkerRequestType.GET_PROGRESS_HANDLE:\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.PROGRESS_HANDLE,\n data: this._bindings.getProgressHandle(request.data),\n },\n [],\n );\n break;\n case WorkerRequestType.GET_QUERY_PROGRESS:\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.QUERY_PROGRESS,\n data: this._bindings.getQueryProgress(request.data),\n },\n [],\n );\n break;\n case WorkerRequestType.FETCH_QUERY_RESULTS: {\n const result = this._bindings.fetchQueryResults(request.data);\n // An empty batch ends the stream\n if (!result || result.length == 0) {\n await this.checkpointFiles();\n }\n const transfer = result ? [result.buffer] : [];\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.QUERY_RESULT_CHUNK,\n data: result,\n },\n transfer,\n );\n break;\n }\n case WorkerRequestType.GET_TABLE_NAMES: {\n const result = this._bindings.getTableNames(request.data[0], request.data[1]);\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.TABLE_NAMES,\n data: result,\n },\n [],\n );\n break;\n }\n case WorkerRequestType.GLOB_FILE_INFOS: {\n const infos = this._bindings.globFiles(request.data);\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.FILE_INFOS,\n data: infos,\n },\n [],\n );\n break;\n }\n\n case WorkerRequestType.REGISTER_FILE_URL:\n this._bindings.registerFileURL(request.data[0], request.data[1], request.data[2], request.data[3]);\n this.sendOK(request);\n break;\n\n case WorkerRequestType.REGISTER_FILE_BUFFER:\n this._bindings.registerFileBuffer(request.data[0], request.data[1]);\n this.sendOK(request);\n break;\n\n case WorkerRequestType.REGISTER_FILE_HANDLE:\n await this._bindings.registerFileHandleAsync(\n request.data[0],\n request.data[1],\n request.data[2],\n request.data[3],\n );\n this.sendOK(request);\n break;\n\n case WorkerRequestType.COPY_FILE_TO_PATH:\n this._bindings.copyFileToPath(request.data[0], request.data[1]);\n this.sendOK(request);\n break;\n\n case WorkerRequestType.COPY_FILE_TO_BUFFER: {\n const buffer = this._bindings.copyFileToBuffer(request.data);\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.FILE_BUFFER,\n data: buffer,\n },\n [],\n );\n break;\n }\n case WorkerRequestType.COLLECT_FILE_STATISTICS:\n this._bindings.collectFileStatistics(request.data[0], request.data[1]);\n this.sendOK(request);\n break;\n\n case WorkerRequestType.REGISTER_OPFS_FILE_NAME: {\n const files = await this._bindings.registerOPFSFileName(request.data[0], request.data[1]);\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.OPFS_FILE_NAMES,\n data: files,\n },\n [],\n );\n break;\n }\n\n case WorkerRequestType.EXPORT_FILE_STATISTICS: {\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.FILE_STATISTICS,\n data: this._bindings.exportFileStatistics(request.data),\n },\n [],\n );\n break;\n }\n case WorkerRequestType.INSERT_ARROW_FROM_IPC_STREAM: {\n this._bindings.insertArrowFromIPCStream(request.data[0], request.data[1], request.data[2]);\n this.sendOK(request);\n break;\n }\n case WorkerRequestType.INSERT_CSV_FROM_PATH: {\n this._bindings.insertCSVFromPath(request.data[0], request.data[1], request.data[2]);\n this.sendOK(request);\n break;\n }\n case WorkerRequestType.INSERT_JSON_FROM_PATH: {\n this._bindings.insertJSONFromPath(request.data[0], request.data[1], request.data[2]);\n this.sendOK(request);\n break;\n }\n case WorkerRequestType.TOKENIZE: {\n const result = this._bindings.tokenize(request.data);\n this.postMessage(\n {\n messageId: this._nextMessageId++,\n requestId: request.messageId,\n type: WorkerResponseType.SCRIPT_TOKENS,\n data: result,\n },\n [],\n );\n break;\n }\n }\n } catch (e: any) {\n console.log(e);\n return this.failWith(request, e);\n }\n }\n}\n", "export const bigInt=()=>(async e=>{try{return(await WebAssembly.instantiate(e)).instance.exports.b(BigInt(0))===BigInt(0)}catch(e){return!1}})(new Uint8Array([0,97,115,109,1,0,0,0,1,6,1,96,1,126,1,126,3,2,1,0,7,5,1,1,98,0,0,10,6,1,4,0,32,0,11])),bulkMemory=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,3,1,0,1,10,14,1,12,0,65,0,65,0,65,0,252,10,0,0,11])),exceptions=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,8,1,6,0,6,64,25,11,11])),extendedConst=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,5,3,1,0,1,11,9,1,0,65,1,65,2,106,11,0])),gc=()=>(async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,95,1,120,0])))(),jspi=()=>(async()=>\"Suspender\"in WebAssembly)(),memory64=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,5,3,1,4,1])),multiMemory=()=>(async()=>{try{return new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,5,5,2,0,0,0,0])),!0}catch(e){return!1}})(),multiValue=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,6,1,96,0,2,127,127,3,2,1,0,10,8,1,6,0,65,0,65,0,11])),mutableGlobals=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,2,8,1,1,97,1,98,3,127,1,6,6,1,127,1,65,0,11,7,5,1,1,97,3,1])),referenceTypes=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,7,1,5,0,208,112,26,11])),relaxedSimd=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,15,1,13,0,65,1,253,15,65,2,253,15,253,128,2,11])),saturatedFloatToInt=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,12,1,10,0,67,0,0,0,0,252,0,26,11])),signExtensions=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,8,1,6,0,65,0,192,26,11])),simd=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11])),streamingCompilation=()=>(async()=>\"compileStreaming\"in WebAssembly)(),tailCall=async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,6,1,4,0,18,0,11])),threads=()=>(async e=>{try{return\"undefined\"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(e)}catch(e){return!1}})(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])),typeReflection=()=>(async()=>\"Function\"in WebAssembly)();\n", "{\n \"name\": \"@haybarn/haybarn-wasm\",\n \"version\": \"2.0.0-rc7\",\n \"description\": \"Haybarn for WebAssembly \u2014 Query Farm's derived distribution of DuckDB-Wasm. Haybarn, powered by DuckDB.\",\n \"license\": \"MIT\",\n \"homepage\": \"https://query.farm/products/haybarn/\",\n \"bugs\": {\n \"url\": \"https://github.com/Query-farm-haybarn/haybarn-wasm/issues\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/Query-farm-haybarn/haybarn-wasm.git\"\n },\n \"keywords\": [\n \"sql\",\n \"haybarn\",\n \"duckdb\",\n \"relational\",\n \"database\",\n \"data\",\n \"query\",\n \"wasm\",\n \"analytics\",\n \"olap\",\n \"arrow\",\n \"parquet\",\n \"json\",\n \"csv\"\n ],\n \"dependencies\": {\n \"apache-arrow\": \"^17.0.0\",\n \"qs\": \"^6.14.1\"\n },\n \"devDependencies\": {\n \"@types/emscripten\": \"^1.39.10\",\n \"@types/jasmine\": \"^5.1.13\",\n \"@typescript-eslint/eslint-plugin\": \"^6.21.0\",\n \"@typescript-eslint/parser\": \"^6.21.0\",\n \"esbuild\": \"^0.20.2\",\n \"eslint\": \"^8.57.0\",\n \"eslint-plugin-jasmine\": \"^4.1.3\",\n \"eslint-plugin-react\": \"^7.37.5\",\n \"fast-glob\": \"^3.3.2\",\n \"jasmine\": \"^5.13.0\",\n \"jasmine-core\": \"^5.1.2\",\n \"jasmine-spec-reporter\": \"^7.0.0\",\n \"js-sha256\": \"^0.11.1\",\n \"karma\": \"^6.4.2\",\n \"karma-chrome-launcher\": \"^3.2.0\",\n \"karma-coverage\": \"^2.2.1\",\n \"karma-firefox-launcher\": \"^2.1.3\",\n \"karma-jasmine\": \"^5.1.0\",\n \"karma-jasmine-html-reporter\": \"^2.1.0\",\n \"karma-sourcemap-loader\": \"^0.4.0\",\n \"karma-spec-reporter\": \"^0.0.36\",\n \"make-dir\": \"^4.0.0\",\n \"nyc\": \"^15.1.0\",\n \"prettier\": \"^3.2.5\",\n \"puppeteer\": \"^22.8.0\",\n \"rimraf\": \"^5.0.5\",\n \"s3rver\": \"^3.7.1\",\n \"typedoc\": \"^0.28.15\",\n \"typescript\": \"^5.3.3\",\n \"wasm-feature-detect\": \"^1.6.1\",\n \"web-worker\": \"^1.2.0\"\n },\n \"scripts\": {\n \"build:debug\": \"node bundle.mjs debug && tsc --emitDeclarationOnly\",\n \"build:release\": \"node bundle.mjs release && tsc --emitDeclarationOnly\",\n \"docs\": \"typedoc\",\n \"format\": \"prettier --write \\\"**/*.+(js|ts)\\\"\",\n \"report\": \"node ./coverage.mjs\",\n \"test:node\": \"node --enable-source-maps ../jasmine/bin/jasmine ./dist/tests-node.cjs\",\n \"test:node:debug\": \"node --inspect-brk --enable-source-maps ../jasmine/bin/jasmine ./dist/tests-node.cjs\",\n \"test:node:coverage\": \"nyc -r json --report-dir ./coverage/node node ../jasmine/bin/jasmine ./dist/tests-node.cjs\",\n \"test:firefox\": \"karma start ./karma/tests-firefox.cjs\",\n \"test:chrome\": \"karma start ./karma/tests-chrome.cjs\",\n \"test:chrome:threads\": \"karma start ./karma/tests-chrome-threads.cjs\",\n \"test:chrome:threads:smoke\": \"karma start ./karma/threads-smoke-chrome.cjs\",\n \"test:chrome:httpfs\": \"karma start ./karma/httpfs-chrome.cjs\",\n \"test:chrome:haybarn-repository\": \"karma start ./karma/haybarn-repository-chrome.cjs\",\n \"test:chrome:threads-pool\": \"karma start ./karma/threads-pool-chrome.cjs\",\n \"test:chrome:interrupt\": \"karma start ./karma/interrupt-chrome.cjs\",\n \"test:chrome:platform\": \"karma start ./karma/platform-chrome.cjs\",\n \"test:chrome:prefetch\": \"karma start ./karma/prefetch-chrome.cjs\",\n \"test:chrome:coverage\": \"karma start ./karma/tests-chrome-coverage.cjs\",\n \"test:browser\": \"karma start ./karma/tests-all.cjs\",\n \"test:browser:debug\": \"karma start ./karma/tests-debug.cjs\",\n \"test\": \"npm run test:chrome && npm run test:node\",\n \"test:coverage\": \"npm run test:chrome:coverage && npm run test:node:coverage && npm run report\",\n \"lint\": \"eslint src test\"\n },\n \"files\": [\n \"dist\",\n \"!dist/tests-*\",\n \"!dist/duckdb-browser-base.worker.js.map\",\n \"!dist/types/test\"\n ],\n \"main\": \"dist/duckdb-browser.cjs\",\n \"module\": \"dist/duckdb-browser.mjs\",\n \"types\": \"dist/duckdb-browser.d.ts\",\n \"jsdelivr\": \"dist/duckdb-browser.cjs\",\n \"unpkg\": \"dist/duckdb-browser.mjs\",\n \"sideEffects\": false,\n \"browser\": {\n \"fs\": false,\n \"path\": false,\n \"perf_hooks\": false,\n \"os\": false,\n \"worker_threads\": false\n },\n \"exports\": {\n \"./dist/duckdb-base.wasm\": \"./dist/duckdb-base.wasm\",\n \"./dist/duckdb-threads.wasm\": \"./dist/duckdb-threads.wasm\",\n \"./dist/duckdb-browser\": \"./dist/duckdb-browser.mjs\",\n \"./dist/duckdb-browser.cjs\": \"./dist/duckdb-browser.cjs\",\n \"./dist/duckdb-browser.mjs\": \"./dist/duckdb-browser.mjs\",\n \"./dist/duckdb-browser-threads.pthread.worker.js\": \"./dist/duckdb-browser-threads.pthread.worker.js\",\n \"./dist/duckdb-browser-threads.worker.js\": \"./dist/duckdb-browser-threads.worker.js\",\n \"./dist/duckdb-browser-base.worker.js\": \"./dist/duckdb-browser-base.worker.js\",\n \"./dist/duckdb-browser-vgi.mjs\": \"./dist/duckdb-browser-vgi.mjs\",\n \"./dist/duckdb-browser-vgi.cjs\": \"./dist/duckdb-browser-vgi.cjs\",\n \"./vgi\": {\n \"types\": \"./dist/duckdb-browser-vgi.d.ts\",\n \"import\": \"./dist/duckdb-browser-vgi.mjs\",\n \"require\": \"./dist/duckdb-browser-vgi.cjs\"\n },\n \"./dist/duckdb-node\": \"./dist/duckdb-node.cjs\",\n \"./dist/duckdb-node.cjs\": \"./dist/duckdb-node.cjs\",\n \"./dist/duckdb-node-blocking\": \"./dist/duckdb-node-blocking.cjs\",\n \"./dist/duckdb-node-blocking.cjs\": \"./dist/duckdb-node-blocking.cjs\",\n \"./dist/duckdb-node-base.worker.cjs\": \"./dist/duckdb-node-base.worker.cjs\",\n \"./blocking\": {\n \"node\": {\n \"types\": \"./dist/duckdb-node-blocking.d.ts\",\n \"require\": \"./dist/duckdb-node-blocking.cjs\",\n \"import\": \"./dist/duckdb-node-blocking.cjs\"\n },\n \"types\": \"./dist/duckdb-node-blocking.d.ts\",\n \"import\": \"./dist/duckdb-node-blocking.mjs\",\n \"require\": \"./dist/duckdb-node-blocking.cjs\"\n },\n \".\": {\n \"browser\": {\n \"types\": \"./dist/duckdb-browser.d.ts\",\n \"import\": \"./dist/duckdb-browser.mjs\",\n \"require\": \"./dist/duckdb-browser.cjs\"\n },\n \"node\": {\n \"types\": \"./dist/duckdb-node.d.ts\",\n \"import\": \"./dist/duckdb-node.cjs\",\n \"require\": \"./dist/duckdb-node.cjs\"\n },\n \"types\": \"./dist/duckdb-browser.d.ts\",\n \"import\": \"./dist/duckdb-browser.mjs\",\n \"require\": \"./dist/duckdb-browser.cjs\"\n }\n }\n}\n", "import config from '../package.json';\n\nexport const PACKAGE_NAME = config.name;\nexport const PACKAGE_VERSION = config.version;\n\nconst VERSION_PARTS = config.version.split('.');\nexport const PACKAGE_VERSION_MAJOR = VERSION_PARTS[0];\nexport const PACKAGE_VERSION_MINOR = VERSION_PARTS[1];\nexport const PACKAGE_VERSION_PATCH = VERSION_PARTS[2];\n", "import * as check from 'wasm-feature-detect';\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\n\n// Platform check taken from here:\n// https://github.com/xtermjs/xterm.js/blob/master/src/common/Platform.ts#L21\n\ninterface INavigator {\n userAgent: string;\n language: string;\n platform: string;\n}\n\n// We're declaring a navigator global here as we expect it in all runtimes (node and browser), but\n// we want this module to live in common.\ndeclare const navigator: INavigator;\n\nexport const isNode = () => (typeof navigator === 'undefined' ? true : false);\nconst userAgent = () => (isNode() ? 'node' : navigator.userAgent);\nexport const isFirefox = () => userAgent().includes('Firefox');\nexport const isSafari = () => /^((?!chrome|android).)*safari/i.test(userAgent());\n\n/** Bundles have different characteristics:\n * - base: single-threaded, requires WebAssembly exception handling\n * - threads: multi-threaded, additionally requires SIMD, threads and cross origin isolation\n */\nexport interface DuckDBBundles {\n base: {\n mainModule: string;\n mainWorker: string;\n };\n threads?: {\n mainModule: string;\n mainWorker: string;\n pthreadWorker: string;\n };\n}\n\nexport function getJsDelivrBundles(): DuckDBBundles {\n const jsdelivr_dist_url = `https://cdn.jsdelivr.net/npm/${PACKAGE_NAME}@${PACKAGE_VERSION}/dist/`;\n return {\n base: {\n mainModule: `${jsdelivr_dist_url}duckdb-base.wasm`,\n mainWorker: `${jsdelivr_dist_url}duckdb-browser-base.worker.js`,\n },\n // threads is still experimental, let the user opt in explicitly\n };\n}\n\nexport interface DuckDBBundle {\n mainModule: string;\n mainWorker: string | null;\n pthreadWorker: string | null;\n}\n\nexport interface PlatformFeatures {\n bigInt64Array: boolean;\n crossOriginIsolated: boolean;\n wasmExceptions: boolean;\n wasmSIMD: boolean;\n wasmBulkMemory: boolean;\n wasmThreads: boolean;\n}\n\nlet bigInt64Array: boolean | null = null;\nlet wasmExceptions: boolean | null = null;\nlet wasmThreads: boolean | null = null;\nlet wasmSIMD: boolean | null = null;\nlet wasmBulkMemory: boolean | null = null;\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\ndeclare namespace globalThis {\n let crossOriginIsolated: boolean;\n}\n\nexport async function getPlatformFeatures(): Promise<PlatformFeatures> {\n if (bigInt64Array == null) {\n bigInt64Array = typeof BigInt64Array != 'undefined';\n }\n if (wasmExceptions == null) {\n wasmExceptions = await check.exceptions();\n }\n if (wasmThreads == null) {\n wasmThreads = await check.threads();\n }\n if (wasmSIMD == null) {\n wasmSIMD = await check.simd();\n }\n if (wasmBulkMemory == null) {\n wasmBulkMemory = await check.bulkMemory();\n }\n return {\n bigInt64Array: bigInt64Array!,\n crossOriginIsolated: isNode() || globalThis.crossOriginIsolated || false,\n wasmExceptions: wasmExceptions!,\n wasmSIMD: wasmSIMD!,\n wasmThreads: wasmThreads!,\n wasmBulkMemory: wasmBulkMemory!,\n };\n}\n\n/** Every bundle requires WebAssembly exception handling, throws if the platform does not support it */\nexport async function checkPlatformSupport(): Promise<PlatformFeatures> {\n const platform = await getPlatformFeatures();\n if (!platform.wasmExceptions) {\n throw new Error('DuckDB-Wasm requires WebAssembly exception handling, which this platform does not support');\n }\n return platform;\n}\n\nexport async function selectBundle(bundles: DuckDBBundles): Promise<DuckDBBundle> {\n const platform = await checkPlatformSupport();\n if (platform.wasmSIMD && platform.wasmThreads && platform.crossOriginIsolated && bundles.threads) {\n return {\n mainModule: bundles.threads.mainModule,\n mainWorker: bundles.threads.mainWorker,\n pthreadWorker: bundles.threads.pthreadWorker,\n };\n }\n return {\n mainModule: bundles.base.mainModule,\n mainWorker: bundles.base.mainWorker,\n pthreadWorker: null,\n };\n}\n", "import Worker from 'web-worker';\n\nexport async function createWorker(url: string) {\n const request = new Request(url);\n const workerScript = await fetch(request);\n const workerURL = URL.createObjectURL(await workerScript.blob());\n return new Worker(workerURL);\n}\n"],
5
5
  "mappings": "ioBAAA,IAAAA,GAAAC,GAAA,CAAAC,GAAAC,KAAA,CAeAA,GAAO,QAAU,SCfjB,IAAAC,GAAA,GAAAC,GAAAD,GAAA,iBAAAE,EAAA,0BAAAC,EAAA,0BAAAC,EAAA,2BAAAC,EAAA,8BAAAC,EAAA,kBAAAC,EAAA,oCAAAC,EAAA,qBAAAC,EAAA,uBAAAC,EAAA,kBAAAC,GAAA,sBAAAC,GAAA,aAAAC,EAAA,aAAAC,EAAA,cAAAC,EAAA,aAAAC,EAAA,iBAAAC,EAAA,oBAAAC,EAAA,0BAAAC,GAAA,0BAAAC,GAAA,0BAAAC,GAAA,eAAAC,EAAA,cAAAC,EAAA,eAAAC,EAAA,sBAAAC,EAAA,uBAAAC,EAAA,eAAAC,EAAA,yBAAAC,GAAA,iBAAAC,GAAA,uBAAAC,GAAA,qBAAAC,GAAA,qBAAAC,GAAA,sBAAAC,GAAA,qBAAAC,GAAA,wBAAAC,GAAA,cAAAC,GAAA,WAAAC,EAAA,aAAAC,GAAA,iBAAAC,KAAA,eAAAC,GAAAxC,IC4CO,IAAKyC,OACRA,IAAA,UAAY,GAAZ,YACAA,IAAA,UAAY,GAAZ,YACAA,IAAA,UAAY,GAAZ,YACAA,IAAA,WAAa,GAAb,aAJQA,OAAA,IC5CL,IAAKC,OACRA,IAAA,WAAa,GAAb,aACAA,IAAA,iBAAmB,GAAnB,mBACAA,IAAA,gBAAkB,GAAlB,kBACAA,IAAA,SAAW,GAAX,WACAA,IAAA,QAAU,GAAV,UACAA,IAAA,QAAU,GAAV,UANQA,OAAA,ICAL,IAAKC,OACRA,IAAA,KAAO,GAAP,OACAA,IAAA,MAAQ,GAAR,QACAA,IAAA,KAAO,GAAP,OACAA,IAAA,QAAU,GAAV,UACAA,IAAA,MAAQ,GAAR,QALQA,OAAA,IAQAC,OACRA,IAAA,KAAO,G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K,WACzB,WAAYA,EAAQ,KAAK,WACzB,cAAe,IACnB,CACJ,CC3HA,IAAAC,GAAmB,QAEnB,eAAsBC,GAAaC,EAAa,CAC5C,IAAMC,EAAU,IAAI,QAAQD,CAAG,EACzBE,EAAe,MAAM,MAAMD,CAAO,EAClCE,EAAY,IAAI,gBAAgB,MAAMD,EAAa,KAAK,CAAC,EAC/D,OAAO,IAAI,GAAAE,QAAOD,CAAS,CAC/B",
6
6
  "names": ["require_browser", "__commonJSMin", "exports", "module", "duckdb_exports", "__export", "AsyncDuckDB", "AsyncDuckDBConnection", "AsyncDuckDBDispatcher", "AsyncPreparedStatement", "AsyncResultStreamIterator", "ConsoleLogger", "DEFAULT_WORKER_START_TIMEOUT_MS", "DuckDBAccessMode", "DuckDBDataProtocol", "IsArrowBuffer", "IsDuckDBWasmRetry", "LogEvent", "LogLevel", "LogOrigin", "LogTopic", "PACKAGE_NAME", "PACKAGE_VERSION", "PACKAGE_VERSION_MAJOR", "PACKAGE_VERSION_MINOR", "PACKAGE_VERSION_PATCH", "StatusCode", "TokenType", "VoidLogger", "WorkerRequestType", "WorkerResponseType", "WorkerTask", "checkPlatformSupport", "createWorker", "getJsDelivrBundles", "getLogEventLabel", "getLogLevelLabel", "getLogOriginLabel", "getLogTopicLabel", "getPlatformFeatures", "isFirefox", "isNode", "isSafari", "selectBundle", "__toCommonJS", "DuckDBAccessMode", "TokenType", "LogLevel", "LogTopic", "LogEvent", "LogOrigin", "VoidLogger", "_entry", "ConsoleLogger", "level", "entry", "getLogLevelLabel", "getLogEventLabel", "event", "getLogTopicLabel", "topic", "getLogOriginLabel", "origin", "StatusCode", "IsArrowBuffer", "status", "IsDuckDBWasmRetry", "arrow", "AsyncDuckDBConnection", "bindings", "conn", "callback", "text", "buffer", "reader", "allowStreamResult", "header", "iter", "AsyncResultStreamIterator", "query", "stmt", "AsyncPreparedStatement", "table", "options", "db", "connectionId", "statementId", "params", "WorkerRequestType", "WorkerResponseType", "WorkerTask", "type", "data", "resolve", "reject", "interruptConnection", "handle", "arrow", "arrowToSQLType", "type", "dec", "c", "arrowToSQLField", "map_", "name", "t", "REGEX_OPFS_FILE", "searchOPFSFiles", "text", "REGEX_OPFS_FILE", "match", "TEXT_ENCODER", "CANCEL_SAB_POLL_MS", "DEFAULT_WORKER_START_TIMEOUT_MS", "AsyncDuckDB", "logger", "worker", "options", "_a", "resolve", "_reject", "error", "pending", "task", "ping", "WorkerTask", "mid", "timeout", "transfer", "event", "response", "p", "e", "_event", "name", "names", "mainModuleURL", "pthreadWorkerURL", "progress", "config", "timeoutMs", "text", "cid", "handle", "AsyncDuckDBConnection", "conn", "files", "allowStreamResult", "interrupted", "interruptConnection", "cached", "sab", "header", "watch", "latest", "statement", "params", "path", "buffer", "url", "proto", "directIO", "protocol", "mode", "enable", "out", "k", "type", "arrowToSQLField", "searchOPFSFiles", "result", "file", "TextDecoderWrapper", "decoder", "data", "decodeText", "DuckDBDataProtocol", "prefetched", "running", "heldBytes", "generation", "computeExtensionHash", "bytes", "end", "chunks", "offset", "hashes", "concatenated", "h", "i", "prefetchOne", "url", "timeoutMs", "startedIn", "signal", "response", "compiling", "body", "hash", "module", "prefetchExtensions", "urls", "installPrefetchHook", "work", "p", "held", "_", "takePrefetchedExtension", "entry", "clearPrefetchedExtensions", "AsyncDuckDBDispatcher", "entry", "request", "e", "obj", "run", "forwardProgress", "p", "clearPrefetchedExtensions", "path", "names", "timeoutMs", "held", "urls", "name", "url", "ready", "prefetchExtensions", "conn", "_", "c", "result", "transfer", "infos", "buffer", "files", "bulkMemory", "exceptions", "simd", "threads", "e", "package_default", "PACKAGE_NAME", "package_default", "PACKAGE_VERSION", "VERSION_PARTS", "PACKAGE_VERSION_MAJOR", "PACKAGE_VERSION_MINOR", "PACKAGE_VERSION_PATCH", "isNode", "userAgent", "isFirefox", "isSafari", "getJsDelivrBundles", "jsdelivr_dist_url", "PACKAGE_NAME", "PACKAGE_VERSION", "bigInt64Array", "wasmExceptions", "wasmThreads", "wasmSIMD", "wasmBulkMemory", "getPlatformFeatures", "exceptions", "threads", "simd", "bulkMemory", "checkPlatformSupport", "platform", "selectBundle", "bundles", "import_web_worker", "createWorker", "url", "request", "workerScript", "workerURL", "Worker"]
7
7
  }