crispy-recall 0.1.6 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -105,1414 +105,826 @@ var init_log = __esm({
105
105
  }
106
106
  });
107
107
 
108
- // node_modules/node-sqlite3-wasm/dist/node-sqlite3-wasm.js
109
- var require_node_sqlite3_wasm = __commonJS({
110
- "node_modules/node-sqlite3-wasm/dist/node-sqlite3-wasm.js"(exports2, module2) {
111
- var Module = typeof Module != "undefined" ? Module : {};
112
- var ENVIRONMENT_IS_NODE = true;
113
- var INT32_MIN = -2147483648;
114
- var INT32_MAX = 2147483647;
115
- var NULL = 0;
116
- var SQLITE_OK = 0;
117
- var SQLITE_ROW = 100;
118
- var SQLITE_DONE = 101;
119
- var SQLITE_INTEGER = 1;
120
- var SQLITE_FLOAT = 2;
121
- var SQLITE_TEXT = 3;
122
- var SQLITE_BLOB = 4;
123
- var SQLITE_NULL = 5;
124
- var SQLITE_UTF8 = 1;
125
- var SQLITE_TRANSIENT = -1;
126
- var SQLITE_DETERMINISTIC = 2048;
127
- var temp;
128
- var sqlite3 = {};
129
- Module.onRuntimeInitialized = () => {
130
- temp = stackAlloc(4);
131
- const v = null;
132
- const n = "number";
133
- const s = "string";
134
- const n1 = [n];
135
- const n2 = [n, ...n1];
136
- const n3 = [n, ...n2];
137
- const n4 = [n, ...n3];
138
- const n5 = [n, ...n4];
139
- const signatures = { open_v2: [n, [s, n, n, s]], exec: [n, n5], errmsg: [s, n1], prepare_v2: [n, n5], close_v2: [n, n1], finalize: [n, n1], reset: [n, n1], clear_bindings: [n, n1], bind_int: [n, n3], bind_int64: [n, n3], bind_double: [n, n3], bind_text: [n, n5], bind_blob: [n, n5], bind_blob64: [n, n5], bind_null: [n, n2], bind_parameter_index: [n, [n, s]], step: [n, n1], column_int64: [n, n2], column_double: [n, n2], column_text: [s, n2], column_blob: [n, n2], column_type: [n, n2], column_name: [s, n2], column_count: [n, n1], column_bytes: [n, n2], last_insert_rowid: [n, n1], changes: [n, n1], create_function_v2: [n, [n, s, n, n, n, n, n, n, n]], value_type: [n, n1], value_text: [s, n1], value_blob: [n, n1], value_int64: [n, n1], value_double: [n, n1], value_bytes: [n, n1], result_double: [v, n2], result_null: [v, n1], result_text: [v, n4], result_blob: [v, n4], result_blob64: [v, n4], result_int: [v, n2], result_int64: [v, n2], result_error: [v, n3], column_table_name: [s, n2], get_autocommit: [n, n1] };
140
- for (const [name, sig] of Object.entries(signatures)) {
141
- sqlite3[name] = cwrap(`sqlite3_${name}`, sig[0], sig[1]);
108
+ // node_modules/better-sqlite3/lib/util.js
109
+ var require_util = __commonJS({
110
+ "node_modules/better-sqlite3/lib/util.js"(exports2) {
111
+ "use strict";
112
+ exports2.getBooleanOption = (options, key) => {
113
+ let value = false;
114
+ if (key in options && typeof (value = options[key]) !== "boolean") {
115
+ throw new TypeError(`Expected the "${key}" option to be a boolean`);
142
116
  }
117
+ return value;
143
118
  };
144
- var SQLite3Error = class extends Error {
145
- constructor(message) {
146
- super(message);
147
- this.name = "SQLite3Error";
119
+ exports2.cppdb = Symbol();
120
+ exports2.inspect = Symbol.for("nodejs.util.inspect.custom");
121
+ }
122
+ });
123
+
124
+ // node_modules/better-sqlite3/lib/sqlite-error.js
125
+ var require_sqlite_error = __commonJS({
126
+ "node_modules/better-sqlite3/lib/sqlite-error.js"(exports2, module2) {
127
+ "use strict";
128
+ var descriptor = { value: "SqliteError", writable: true, enumerable: false, configurable: true };
129
+ function SqliteError(message, code) {
130
+ if (new.target !== SqliteError) {
131
+ return new SqliteError(message, code);
148
132
  }
149
- };
150
- function arrayToHeap(array) {
151
- const ptr = _malloc(array.byteLength);
152
- HEAPU8.set(array, ptr);
153
- return ptr;
154
- }
155
- function stringToHeap(str) {
156
- const size = lengthBytesUTF8(str) + 1;
157
- const ptr = _malloc(size);
158
- stringToUTF8(str, ptr, size);
159
- return ptr;
160
- }
161
- function toNumberOrNot(bigInt) {
162
- if (bigInt >= Number.MIN_SAFE_INTEGER && bigInt <= Number.MAX_SAFE_INTEGER) {
163
- return Number(bigInt);
164
- }
165
- return bigInt;
166
- }
167
- function parseFunctionArguments(argc, argv) {
168
- const args = [];
169
- for (let i = 0; i < argc; i++) {
170
- const ptr = getValue(argv + 4 * i, "i32");
171
- const type = sqlite3.value_type(ptr);
172
- let arg;
173
- switch (type) {
174
- case SQLITE_INTEGER:
175
- arg = toNumberOrNot(sqlite3.value_int64(ptr));
176
- break;
177
- case SQLITE_FLOAT:
178
- arg = sqlite3.value_double(ptr);
179
- break;
180
- case SQLITE_TEXT:
181
- arg = sqlite3.value_text(ptr);
182
- break;
183
- case SQLITE_BLOB:
184
- const p = sqlite3.value_blob(ptr);
185
- if (p != NULL) {
186
- arg = HEAPU8.slice(p, p + sqlite3.value_bytes(ptr));
187
- } else {
188
- arg = new Uint8Array();
189
- }
190
- break;
191
- case SQLITE_NULL:
192
- arg = null;
193
- break;
194
- }
195
- args.push(arg);
133
+ if (typeof code !== "string") {
134
+ throw new TypeError("Expected second argument to be a string");
196
135
  }
197
- return args;
136
+ Error.call(this, message);
137
+ descriptor.value = "" + message;
138
+ Object.defineProperty(this, "message", descriptor);
139
+ Error.captureStackTrace(this, SqliteError);
140
+ this.code = code;
198
141
  }
199
- function setFunctionResult(cx, result) {
200
- switch (typeof result) {
201
- case "boolean":
202
- sqlite3.result_int(cx, result ? 1 : 0);
203
- break;
204
- case "number":
205
- if (Number.isSafeInteger(result)) {
206
- if (result >= INT32_MIN && result <= INT32_MAX) {
207
- sqlite3.result_int(cx, result);
208
- } else {
209
- sqlite3.result_int64(cx, BigInt(result));
210
- }
211
- } else {
212
- sqlite3.result_double(cx, result);
213
- }
214
- break;
215
- case "bigint":
216
- sqlite3.result_int64(cx, result);
217
- break;
218
- case "string":
219
- const tempPtr = stringToHeap(result);
220
- sqlite3.result_text(cx, tempPtr, -1, SQLITE_TRANSIENT);
221
- _free(tempPtr);
222
- break;
223
- case "object":
224
- if (result === null) {
225
- sqlite3.result_null(cx);
226
- } else if (result instanceof Uint8Array) {
227
- const tempPtr2 = arrayToHeap(result);
228
- if (result.byteLength <= INT32_MAX) {
229
- sqlite3.result_blob(cx, tempPtr2, result.byteLength, SQLITE_TRANSIENT);
230
- } else {
231
- sqlite3.result_blob64(cx, tempPtr2, BigInt(result.byteLength), SQLITE_TRANSIENT);
232
- }
233
- _free(tempPtr2);
234
- } else {
235
- throw new SQLite3Error(`Unsupported type for function result: "${typeof result}"`);
236
- }
237
- break;
238
- default:
239
- throw new SQLite3Error(`Unsupported type for function result: "${typeof result}"`);
142
+ Object.setPrototypeOf(SqliteError, Error);
143
+ Object.setPrototypeOf(SqliteError.prototype, Error.prototype);
144
+ Object.defineProperty(SqliteError.prototype, "name", descriptor);
145
+ module2.exports = SqliteError;
146
+ }
147
+ });
148
+
149
+ // node_modules/file-uri-to-path/index.js
150
+ var require_file_uri_to_path = __commonJS({
151
+ "node_modules/file-uri-to-path/index.js"(exports2, module2) {
152
+ var sep2 = require("path").sep || "/";
153
+ module2.exports = fileUriToPath;
154
+ function fileUriToPath(uri) {
155
+ if ("string" != typeof uri || uri.length <= 7 || "file://" != uri.substring(0, 7)) {
156
+ throw new TypeError("must pass in a file:// URI to convert to a file path");
157
+ }
158
+ var rest = decodeURI(uri.substring(7));
159
+ var firstSlash = rest.indexOf("/");
160
+ var host = rest.substring(0, firstSlash);
161
+ var path3 = rest.substring(firstSlash + 1);
162
+ if ("localhost" == host)
163
+ host = "";
164
+ if (host) {
165
+ host = sep2 + sep2 + host;
166
+ }
167
+ path3 = path3.replace(/^(.+)\|/, "$1:");
168
+ if (sep2 == "\\") {
169
+ path3 = path3.replace(/\//g, "\\");
170
+ }
171
+ if (/^.+\:/.test(path3)) {
172
+ } else {
173
+ path3 = sep2 + path3;
240
174
  }
175
+ return host + path3;
241
176
  }
242
- var Database = class {
243
- constructor(filename, { fileMustExist = false, readOnly = false } = {}) {
244
- let flags;
245
- if (readOnly) {
246
- flags = SQLITE_OPEN_READONLY;
247
- } else {
248
- flags = SQLITE_OPEN_READWRITE;
249
- if (!fileMustExist)
250
- flags |= SQLITE_OPEN_CREATE;
251
- }
252
- const rc = sqlite3.open_v2(filename, temp, flags, NULL);
253
- this._ptr = getValue(temp, "i32");
254
- if (rc !== SQLITE_OK) {
255
- if (this._ptr !== NULL)
256
- sqlite3.close_v2(this._ptr);
257
- throw new SQLite3Error(`Could not open the database "${filename}"`);
258
- }
259
- this._functions = /* @__PURE__ */ new Map();
260
- }
261
- get isOpen() {
262
- return this._ptr !== null;
263
- }
264
- get inTransaction() {
265
- this._assertOpen();
266
- return sqlite3.get_autocommit(this._ptr) === 0;
267
- }
268
- close() {
269
- this._assertOpen();
270
- for (const func of this._functions.values())
271
- removeFunction(func);
272
- this._functions.clear();
273
- this._handleError(sqlite3.close_v2(this._ptr));
274
- this._ptr = null;
275
- }
276
- function(name, func, { deterministic = false } = {}) {
277
- this._assertOpen();
278
- function wrappedFunc(cx, argc, argv) {
279
- const args = parseFunctionArguments(argc, argv);
280
- let result;
281
- try {
282
- result = func.apply(null, args);
283
- } catch (err2) {
284
- const tempPtr = stringToHeap(err2.toString());
285
- sqlite3.result_error(cx, tempPtr, -1);
286
- _free(tempPtr);
287
- return;
288
- }
289
- setFunctionResult(cx, result);
290
- }
291
- if (this._functions.has(name)) {
292
- removeFunction(this._functions.get(name));
293
- this._functions.delete(name);
294
- }
295
- const funcPtr = addFunction(wrappedFunc, "viii");
296
- this._functions.set(name, funcPtr);
297
- let eTextRep = SQLITE_UTF8;
298
- if (deterministic)
299
- eTextRep |= SQLITE_DETERMINISTIC;
300
- this._handleError(sqlite3.create_function_v2(this._ptr, name, func.length, eTextRep, NULL, funcPtr, NULL, NULL, NULL));
301
- return this;
302
- }
303
- exec(sql) {
304
- this._assertOpen();
305
- const tempPtr = stringToHeap(sql);
306
- try {
307
- this._handleError(sqlite3.exec(this._ptr, tempPtr, NULL, NULL, NULL));
308
- } finally {
309
- _free(tempPtr);
310
- }
311
- }
312
- prepare(sql) {
313
- this._assertOpen();
314
- return new Statement(this, sql);
315
- }
316
- run(sql, values) {
317
- const stmt = this.prepare(sql);
318
- try {
319
- return stmt.run(values);
320
- } finally {
321
- stmt.finalize();
322
- }
323
- }
324
- all(sql, values, { expand: expand2 = false } = {}) {
325
- return this._query(sql, values, false, expand2);
177
+ }
178
+ });
179
+
180
+ // node_modules/bindings/bindings.js
181
+ var require_bindings = __commonJS({
182
+ "node_modules/bindings/bindings.js"(exports2, module2) {
183
+ var fs3 = require("fs");
184
+ var path3 = require("path");
185
+ var fileURLToPath3 = require_file_uri_to_path();
186
+ var join8 = path3.join;
187
+ var dirname3 = path3.dirname;
188
+ var exists = fs3.accessSync && function(path4) {
189
+ try {
190
+ fs3.accessSync(path4);
191
+ } catch (e) {
192
+ return false;
326
193
  }
327
- get(sql, values, { expand: expand2 = false } = {}) {
328
- return this._query(sql, values, true, expand2);
194
+ return true;
195
+ } || fs3.existsSync || path3.existsSync;
196
+ var defaults2 = {
197
+ arrow: process.env.NODE_BINDINGS_ARROW || " \u2192 ",
198
+ compiled: process.env.NODE_BINDINGS_COMPILED_DIR || "compiled",
199
+ platform: process.platform,
200
+ arch: process.arch,
201
+ nodePreGyp: "node-v" + process.versions.modules + "-" + process.platform + "-" + process.arch,
202
+ version: process.versions.node,
203
+ bindings: "bindings.node",
204
+ try: [
205
+ // node-gyp's linked version in the "build" dir
206
+ ["module_root", "build", "bindings"],
207
+ // node-waf and gyp_addon (a.k.a node-gyp)
208
+ ["module_root", "build", "Debug", "bindings"],
209
+ ["module_root", "build", "Release", "bindings"],
210
+ // Debug files, for development (legacy behavior, remove for node v0.9)
211
+ ["module_root", "out", "Debug", "bindings"],
212
+ ["module_root", "Debug", "bindings"],
213
+ // Release files, but manually compiled (legacy behavior, remove for node v0.9)
214
+ ["module_root", "out", "Release", "bindings"],
215
+ ["module_root", "Release", "bindings"],
216
+ // Legacy from node-waf, node <= 0.4.x
217
+ ["module_root", "build", "default", "bindings"],
218
+ // Production "Release" buildtype binary (meh...)
219
+ ["module_root", "compiled", "version", "platform", "arch", "bindings"],
220
+ // node-qbs builds
221
+ ["module_root", "addon-build", "release", "install-root", "bindings"],
222
+ ["module_root", "addon-build", "debug", "install-root", "bindings"],
223
+ ["module_root", "addon-build", "default", "install-root", "bindings"],
224
+ // node-pre-gyp path ./lib/binding/{node_abi}-{platform}-{arch}
225
+ ["module_root", "lib", "binding", "nodePreGyp", "bindings"]
226
+ ]
227
+ };
228
+ function bindings(opts) {
229
+ if (typeof opts == "string") {
230
+ opts = { bindings: opts };
231
+ } else if (!opts) {
232
+ opts = {};
329
233
  }
330
- _query(sql, values, single, expand2) {
331
- const stmt = this.prepare(sql);
234
+ Object.keys(defaults2).map(function(i2) {
235
+ if (!(i2 in opts))
236
+ opts[i2] = defaults2[i2];
237
+ });
238
+ if (!opts.module_root) {
239
+ opts.module_root = exports2.getRoot(exports2.getFileName());
240
+ }
241
+ if (path3.extname(opts.bindings) != ".node") {
242
+ opts.bindings += ".node";
243
+ }
244
+ var requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
245
+ var tries = [], i = 0, l = opts.try.length, n, b, err;
246
+ for (; i < l; i++) {
247
+ n = join8.apply(
248
+ null,
249
+ opts.try[i].map(function(p) {
250
+ return opts[p] || p;
251
+ })
252
+ );
253
+ tries.push(n);
332
254
  try {
333
- if (single) {
334
- return stmt.get(values, { expand: expand2 });
335
- } else {
336
- return stmt.all(values, { expand: expand2 });
255
+ b = opts.path ? requireFunc.resolve(n) : requireFunc(n);
256
+ if (!opts.path) {
257
+ b.path = n;
258
+ }
259
+ return b;
260
+ } catch (e) {
261
+ if (e.code !== "MODULE_NOT_FOUND" && e.code !== "QUALIFIED_PATH_RESOLUTION_FAILED" && !/not find/i.test(e.message)) {
262
+ throw e;
337
263
  }
338
- } finally {
339
- stmt.finalize();
340
- }
341
- }
342
- _assertOpen() {
343
- if (!this.isOpen)
344
- throw new SQLite3Error("Database already closed");
345
- }
346
- _handleError(returnCode) {
347
- if (returnCode !== SQLITE_OK)
348
- throw new SQLite3Error(sqlite3.errmsg(this._ptr));
349
- }
350
- };
351
- var Statement = class {
352
- constructor(db3, sql) {
353
- const tempPtr = stringToHeap(sql);
354
- try {
355
- db3._handleError(sqlite3.prepare_v2(db3._ptr, tempPtr, -1, temp, NULL));
356
- } finally {
357
- _free(tempPtr);
358
- }
359
- this._ptr = getValue(temp, "i32");
360
- if (this._ptr === NULL)
361
- throw new SQLite3Error("Nothing to prepare");
362
- this._db = db3;
363
- }
364
- get database() {
365
- return this._db;
366
- }
367
- get isFinalized() {
368
- return this._ptr === null;
369
- }
370
- run(values) {
371
- this._assertReady();
372
- this._bind(values);
373
- this._step();
374
- return { changes: sqlite3.changes(this._db._ptr), lastInsertRowid: toNumberOrNot(sqlite3.last_insert_rowid(this._db._ptr)) };
375
- }
376
- iterate(values, { expand: expand2 = false } = {}) {
377
- return this._queryRows(values, expand2);
378
- }
379
- all(values, { expand: expand2 = false } = {}) {
380
- return Array.from(this.iterate(values, { expand: expand2 }));
381
- }
382
- get(values, { expand: expand2 = false } = {}) {
383
- const result = this._queryRows(values, expand2).next();
384
- return result.done ? null : result.value;
385
- }
386
- finalize() {
387
- if (this.isFinalized)
388
- throw new SQLite3Error("Statement already finalized");
389
- try {
390
- this._db._handleError(sqlite3.finalize(this._ptr));
391
- } finally {
392
- this._ptr = null;
393
- }
394
- }
395
- _reset() {
396
- return sqlite3.clear_bindings(this._ptr) === SQLITE_OK && sqlite3.reset(this._ptr) === SQLITE_OK;
397
- }
398
- *_queryRows(values, expand2) {
399
- this._assertReady();
400
- this._bind(values);
401
- const columns = this._getColumnNames();
402
- while (this._step())
403
- yield this._getRow(columns, expand2);
404
- }
405
- _bind(values) {
406
- if (!this._reset()) {
407
- throw new SQLite3Error("Could not reset statement prior to binding new values");
408
- }
409
- if (Array.isArray(values)) {
410
- this._bindArray(values);
411
- } else if (values != null && typeof values === "object") {
412
- this._bindObject(values);
413
- } else if (typeof values !== "undefined") {
414
- this._bindValue(values, 1);
415
264
  }
416
265
  }
417
- _step() {
418
- const ret = sqlite3.step(this._ptr);
419
- switch (ret) {
420
- case SQLITE_ROW:
421
- return true;
422
- case SQLITE_DONE:
423
- return false;
424
- default:
425
- this._db._handleError(ret);
426
- }
427
- }
428
- _getRow(columns, expand2) {
429
- const row = {};
430
- for (let i = 0; i < columns.length; i++) {
431
- let v;
432
- const colType = sqlite3.column_type(this._ptr, i);
433
- switch (colType) {
434
- case SQLITE_INTEGER:
435
- v = toNumberOrNot(sqlite3.column_int64(this._ptr, i));
436
- break;
437
- case SQLITE_FLOAT:
438
- v = sqlite3.column_double(this._ptr, i);
439
- break;
440
- case SQLITE_TEXT:
441
- v = sqlite3.column_text(this._ptr, i);
442
- break;
443
- case SQLITE_BLOB:
444
- const p = sqlite3.column_blob(this._ptr, i);
445
- if (p != NULL) {
446
- v = HEAPU8.slice(p, p + sqlite3.column_bytes(this._ptr, i));
447
- } else {
448
- v = new Uint8Array();
266
+ err = new Error(
267
+ "Could not locate the bindings file. Tried:\n" + tries.map(function(a) {
268
+ return opts.arrow + a;
269
+ }).join("\n")
270
+ );
271
+ err.tries = tries;
272
+ throw err;
273
+ }
274
+ module2.exports = exports2 = bindings;
275
+ exports2.getFileName = function getFileName(calling_file) {
276
+ var origPST = Error.prepareStackTrace, origSTL = Error.stackTraceLimit, dummy = {}, fileName;
277
+ Error.stackTraceLimit = 10;
278
+ Error.prepareStackTrace = function(e, st) {
279
+ for (var i = 0, l = st.length; i < l; i++) {
280
+ fileName = st[i].getFileName();
281
+ if (fileName !== __filename) {
282
+ if (calling_file) {
283
+ if (fileName !== calling_file) {
284
+ return;
449
285
  }
450
- break;
451
- case SQLITE_NULL:
452
- v = null;
453
- break;
454
- }
455
- const column = columns[i];
456
- if (expand2) {
457
- let table = sqlite3.column_table_name(this._ptr, i);
458
- table = table === "" ? "$" : table;
459
- if (Object.hasOwn(row, table)) {
460
- row[table][column] = v;
461
286
  } else {
462
- row[table] = { [column]: v };
287
+ return;
463
288
  }
464
- } else {
465
- row[column] = v;
466
289
  }
467
290
  }
468
- return row;
469
- }
470
- _getColumnNames() {
471
- const names = [];
472
- const columns = sqlite3.column_count(this._ptr);
473
- for (let i = 0; i < columns; i++)
474
- names.push(sqlite3.column_name(this._ptr, i));
475
- return names;
476
- }
477
- _bindArray(values) {
478
- for (let i = 0; i < values.length; i++)
479
- this._bindValue(values[i], i + 1);
480
- }
481
- _bindObject(values) {
482
- for (const [param, value] of Object.entries(values)) {
483
- const i = sqlite3.bind_parameter_index(this._ptr, param);
484
- if (i === 0)
485
- throw new SQLite3Error(`Unknown binding parameter: "${param}"`);
486
- this._bindValue(value, i);
487
- }
488
- }
489
- _bindValue(value, position) {
490
- let ret;
491
- switch (typeof value) {
492
- case "string":
493
- const tempPtr = stringToHeap(value);
494
- ret = sqlite3.bind_text(this._ptr, position, tempPtr, -1, SQLITE_TRANSIENT);
495
- _free(tempPtr);
496
- break;
497
- case "number":
498
- if (Number.isSafeInteger(value)) {
499
- if (value >= INT32_MIN && value <= INT32_MAX) {
500
- ret = sqlite3.bind_int(this._ptr, position, value);
501
- } else {
502
- ret = sqlite3.bind_int64(this._ptr, position, BigInt(value));
503
- }
504
- } else {
505
- ret = sqlite3.bind_double(this._ptr, position, value);
506
- }
507
- break;
508
- case "bigint":
509
- ret = sqlite3.bind_int64(this._ptr, position, value);
510
- break;
511
- case "boolean":
512
- ret = sqlite3.bind_int(this._ptr, position, value ? 1 : 0);
513
- break;
514
- case "object":
515
- if (value === null) {
516
- ret = sqlite3.bind_null(this._ptr, position);
517
- } else if (value instanceof Uint8Array) {
518
- const tempPtr2 = arrayToHeap(value);
519
- if (value.byteLength <= INT32_MAX) {
520
- ret = sqlite3.bind_blob(this._ptr, position, tempPtr2, value.byteLength, SQLITE_TRANSIENT);
521
- } else {
522
- ret = sqlite3.bind_blob64(this._ptr, position, tempPtr2, BigInt(value.byteLength), SQLITE_TRANSIENT);
523
- }
524
- _free(tempPtr2);
525
- } else {
526
- throw new SQLite3Error(`Unsupported type for binding: "${typeof value}"`);
527
- }
528
- break;
529
- default:
530
- throw new SQLite3Error(`Unsupported type for binding: "${typeof value}"`);
291
+ };
292
+ Error.captureStackTrace(dummy);
293
+ dummy.stack;
294
+ Error.prepareStackTrace = origPST;
295
+ Error.stackTraceLimit = origSTL;
296
+ var fileSchema = "file://";
297
+ if (fileName.indexOf(fileSchema) === 0) {
298
+ fileName = fileURLToPath3(fileName);
299
+ }
300
+ return fileName;
301
+ };
302
+ exports2.getRoot = function getRoot(file) {
303
+ var dir = dirname3(file), prev;
304
+ while (true) {
305
+ if (dir === ".") {
306
+ dir = process.cwd();
531
307
  }
532
- if (ret !== SQLITE_OK)
533
- this._db._handleError(ret);
534
- }
535
- _assertReady() {
536
- if (this.isFinalized)
537
- throw new SQLite3Error("Statement already finalized");
538
- if (!this._db.isOpen)
539
- throw new SQLite3Error("Database is closed");
308
+ if (exists(join8(dir, "package.json")) || exists(join8(dir, "node_modules"))) {
309
+ return dir;
310
+ }
311
+ if (prev === dir) {
312
+ throw new Error(
313
+ 'Could not find module root given file: "' + file + '". Do you have a `package.json` file? '
314
+ );
315
+ }
316
+ prev = dir;
317
+ dir = join8(dir, "..");
540
318
  }
541
319
  };
542
- Module.Database = Database;
543
- Module.SQLite3Error = SQLite3Error;
544
- var path3 = require("node:path");
545
- var crypto = require("node:crypto");
546
- var SQLITE_CANTOPEN = 14;
547
- var SQLITE_IOERR_READ = 266;
548
- var SQLITE_IOERR_SHORT_READ = 522;
549
- var SQLITE_IOERR_FSYNC = 1034;
550
- var SQLITE_IOERR_WRITE = 778;
551
- var SQLITE_IOERR_DELETE = 2570;
552
- var SQLITE_IOERR_CLOSE = 4106;
553
- var SQLITE_IOERR_TRUNCATE = 1546;
554
- var SQLITE_IOERR_FSTAT = 1802;
555
- var SQLITE_IOERR_LOCK = 3850;
556
- var SQLITE_IOERR_UNLOCK = 2058;
557
- var SQLITE_OPEN_READONLY = 1;
558
- var SQLITE_OPEN_READWRITE = 2;
559
- var SQLITE_OPEN_CREATE = 4;
560
- var SQLITE_OPEN_EXCLUSIVE = 16;
561
- var SQLITE_ACCESS_READWRITE = 1;
562
- var SQLITE_ACCESS_READ = 2;
563
- var SQLITE_LOCK_NONE = 0;
564
- var SQLITE_BUSY = 5;
565
- function _fd(fileInfo) {
566
- return getValue(fileInfo + 4, "i32");
567
- }
568
- function _isLocked(fileInfo) {
569
- return getValue(fileInfo + 8, "i32") != 0;
570
- }
571
- function _setLocked(fileInfo, locked) {
572
- setValue(fileInfo + 8, locked ? 1 : 0, "i32");
573
- }
574
- function _path(fileInfo) {
575
- return UTF8ToString(getValue(fileInfo + 12, "i32"));
576
- }
577
- function _safeInt(bigInt) {
578
- if (bigInt < Number.MIN_SAFE_INTEGER || bigInt > Number.MAX_SAFE_INTEGER)
579
- throw 0;
580
- return Number(bigInt);
581
- }
582
- var arguments_ = [];
583
- var thisProgram = "./this.program";
584
- var quit_ = (status, toThrow) => {
585
- throw toThrow;
586
- };
587
- var _scriptName;
588
- if (typeof __filename != "undefined") {
589
- _scriptName = __filename;
590
- } else {
591
- }
592
- var scriptDirectory = "";
593
- function locateFile(path4) {
594
- if (Module["locateFile"]) {
595
- return Module["locateFile"](path4, scriptDirectory);
596
- }
597
- return scriptDirectory + path4;
598
- }
599
- var readAsync;
600
- var readBinary;
601
- if (ENVIRONMENT_IS_NODE) {
602
- fs3 = require("node:fs");
603
- scriptDirectory = __dirname + "/";
604
- readBinary = (filename) => {
605
- filename = isFileURI(filename) ? new URL(filename) : filename;
606
- var ret = fs3.readFileSync(filename);
607
- return ret;
608
- };
609
- readAsync = async (filename, binary = true) => {
610
- filename = isFileURI(filename) ? new URL(filename) : filename;
611
- var ret = fs3.readFileSync(filename, binary ? void 0 : "utf8");
612
- return ret;
613
- };
614
- if (process.argv.length > 1) {
615
- thisProgram = process.argv[1].replace(/\\/g, "/");
616
- }
617
- arguments_ = process.argv.slice(2);
618
- if (typeof module2 != "undefined") {
619
- module2["exports"] = Module;
620
- }
621
- quit_ = (status, toThrow) => {
622
- process.exitCode = status;
623
- throw toThrow;
624
- };
625
- } else {
626
- }
627
- var fs3;
628
- var out = console.log.bind(console);
629
- var err = console.error.bind(console);
630
- var wasmBinary;
631
- var ABORT2 = false;
632
- var EXITSTATUS;
633
- var isFileURI = (filename) => filename.startsWith("file://");
634
- var runtimeInitialized = false;
635
- function updateMemoryViews() {
636
- var b = wasmMemory.buffer;
637
- HEAP8 = new Int8Array(b);
638
- HEAP16 = new Int16Array(b);
639
- HEAPU8 = new Uint8Array(b);
640
- HEAPU16 = new Uint16Array(b);
641
- HEAP32 = new Int32Array(b);
642
- HEAPU32 = new Uint32Array(b);
643
- HEAPF32 = new Float32Array(b);
644
- HEAPF64 = new Float64Array(b);
645
- HEAP64 = new BigInt64Array(b);
646
- HEAPU64 = new BigUint64Array(b);
647
- }
648
- function preRun() {
649
- if (Module["preRun"]) {
650
- if (typeof Module["preRun"] == "function")
651
- Module["preRun"] = [Module["preRun"]];
652
- while (Module["preRun"].length) {
653
- addOnPreRun(Module["preRun"].shift());
654
- }
655
- }
656
- callRuntimeCallbacks(onPreRuns);
657
- }
658
- function initRuntime() {
659
- runtimeInitialized = true;
660
- wasmExports["z"]();
661
- }
662
- function postRun() {
663
- if (Module["postRun"]) {
664
- if (typeof Module["postRun"] == "function")
665
- Module["postRun"] = [Module["postRun"]];
666
- while (Module["postRun"].length) {
667
- addOnPostRun(Module["postRun"].shift());
668
- }
669
- }
670
- callRuntimeCallbacks(onPostRuns);
671
- }
672
- function abort(what) {
673
- Module["onAbort"]?.(what);
674
- what = `Aborted(${what})`;
675
- err(what);
676
- ABORT2 = true;
677
- what += ". Build with -sASSERTIONS for more info.";
678
- var e = new WebAssembly.RuntimeError(what);
679
- throw e;
680
- }
681
- var wasmBinaryFile;
682
- function findWasmBinary() {
683
- return locateFile("node-sqlite3-wasm.wasm");
684
- }
685
- function getBinarySync(file) {
686
- if (file == wasmBinaryFile && wasmBinary) {
687
- return new Uint8Array(wasmBinary);
688
- }
689
- if (readBinary) {
690
- return readBinary(file);
691
- }
692
- throw 'sync fetching of the wasm failed: you can preload it to Module["wasmBinary"] manually, or emcc.py will do that for you when generating HTML (but not JS)';
693
- }
694
- function instantiateSync(file, info) {
695
- var module3;
696
- var binary = getBinarySync(file);
697
- module3 = new WebAssembly.Module(binary);
698
- var instance = new WebAssembly.Instance(module3, info);
699
- return [instance, module3];
700
- }
701
- function getWasmImports() {
702
- var imports = { a: wasmImports };
703
- return imports;
704
- }
705
- function createWasm() {
706
- function receiveInstance(instance, module3) {
707
- wasmExports = instance.exports;
708
- assignWasmExports(wasmExports);
709
- updateMemoryViews();
710
- return wasmExports;
711
- }
712
- var info = getWasmImports();
713
- if (Module["instantiateWasm"]) {
714
- return new Promise((resolve, reject) => {
715
- Module["instantiateWasm"](info, (inst, mod) => {
716
- resolve(receiveInstance(inst, mod));
717
- });
718
- });
719
- }
720
- wasmBinaryFile ??= findWasmBinary();
721
- var result = instantiateSync(wasmBinaryFile, info);
722
- return receiveInstance(result[0]);
723
- }
724
- var ExitStatus = class {
725
- name = "ExitStatus";
726
- constructor(status) {
727
- this.message = `Program terminated with exit(${status})`;
728
- this.status = status;
729
- }
320
+ }
321
+ });
322
+
323
+ // node_modules/better-sqlite3/lib/methods/wrappers.js
324
+ var require_wrappers = __commonJS({
325
+ "node_modules/better-sqlite3/lib/methods/wrappers.js"(exports2) {
326
+ "use strict";
327
+ var { cppdb } = require_util();
328
+ exports2.prepare = function prepare(sql) {
329
+ return this[cppdb].prepare(sql, this, false);
730
330
  };
731
- var HEAP16;
732
- var HEAP32;
733
- var HEAP64;
734
- var HEAP8;
735
- var HEAPF32;
736
- var HEAPF64;
737
- var HEAPU16;
738
- var HEAPU32;
739
- var HEAPU64;
740
- var HEAPU8;
741
- var callRuntimeCallbacks = (callbacks) => {
742
- while (callbacks.length > 0) {
743
- callbacks.shift()(Module);
744
- }
331
+ exports2.exec = function exec(sql) {
332
+ this[cppdb].exec(sql);
333
+ return this;
745
334
  };
746
- var onPostRuns = [];
747
- var addOnPostRun = (cb) => onPostRuns.push(cb);
748
- var onPreRuns = [];
749
- var addOnPreRun = (cb) => onPreRuns.push(cb);
750
- function getValue(ptr, type = "i8") {
751
- if (type.endsWith("*"))
752
- type = "*";
753
- switch (type) {
754
- case "i1":
755
- return HEAP8[ptr];
756
- case "i8":
757
- return HEAP8[ptr];
758
- case "i16":
759
- return HEAP16[ptr >> 1];
760
- case "i32":
761
- return HEAP32[ptr >> 2];
762
- case "i64":
763
- return HEAP64[ptr >> 3];
764
- case "float":
765
- return HEAPF32[ptr >> 2];
766
- case "double":
767
- return HEAPF64[ptr >> 3];
768
- case "*":
769
- return HEAPU32[ptr >> 2];
770
- default:
771
- abort(`invalid type for getValue: ${type}`);
772
- }
773
- }
774
- var noExitRuntime = true;
775
- function setValue(ptr, value, type = "i8") {
776
- if (type.endsWith("*"))
777
- type = "*";
778
- switch (type) {
779
- case "i1":
780
- HEAP8[ptr] = value;
781
- break;
782
- case "i8":
783
- HEAP8[ptr] = value;
784
- break;
785
- case "i16":
786
- HEAP16[ptr >> 1] = value;
787
- break;
788
- case "i32":
789
- HEAP32[ptr >> 2] = value;
790
- break;
791
- case "i64":
792
- HEAP64[ptr >> 3] = BigInt(value);
793
- break;
794
- case "float":
795
- HEAPF32[ptr >> 2] = value;
796
- break;
797
- case "double":
798
- HEAPF64[ptr >> 3] = value;
799
- break;
800
- case "*":
801
- HEAPU32[ptr >> 2] = value;
802
- break;
803
- default:
804
- abort(`invalid type for setValue: ${type}`);
805
- }
806
- }
807
- var stackRestore = (val) => __emscripten_stack_restore(val);
808
- var stackSave = () => _emscripten_stack_get_current();
809
- var __abort_js = () => abort("");
810
- var runtimeKeepaliveCounter = 0;
811
- var __emscripten_runtime_keepalive_clear = () => {
812
- noExitRuntime = false;
813
- runtimeKeepaliveCounter = 0;
335
+ exports2.close = function close() {
336
+ this[cppdb].close();
337
+ return this;
814
338
  };
815
- var isLeapYear = (year) => year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
816
- var MONTH_DAYS_LEAP_CUMULATIVE = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335];
817
- var MONTH_DAYS_REGULAR_CUMULATIVE = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
818
- var ydayFromDate = (date) => {
819
- var leap = isLeapYear(date.getFullYear());
820
- var monthDaysCumulative = leap ? MONTH_DAYS_LEAP_CUMULATIVE : MONTH_DAYS_REGULAR_CUMULATIVE;
821
- var yday = monthDaysCumulative[date.getMonth()] + date.getDate() - 1;
822
- return yday;
339
+ exports2.loadExtension = function loadExtension(...args) {
340
+ this[cppdb].loadExtension(...args);
341
+ return this;
823
342
  };
824
- var INT53_MAX = 9007199254740992;
825
- var INT53_MIN = -9007199254740992;
826
- var bigintToI53Checked = (num) => num < INT53_MIN || num > INT53_MAX ? NaN : Number(num);
827
- function __localtime_js(time, tmPtr) {
828
- time = bigintToI53Checked(time);
829
- var date = new Date(time * 1e3);
830
- HEAP32[tmPtr >> 2] = date.getSeconds();
831
- HEAP32[tmPtr + 4 >> 2] = date.getMinutes();
832
- HEAP32[tmPtr + 8 >> 2] = date.getHours();
833
- HEAP32[tmPtr + 12 >> 2] = date.getDate();
834
- HEAP32[tmPtr + 16 >> 2] = date.getMonth();
835
- HEAP32[tmPtr + 20 >> 2] = date.getFullYear() - 1900;
836
- HEAP32[tmPtr + 24 >> 2] = date.getDay();
837
- var yday = ydayFromDate(date) | 0;
838
- HEAP32[tmPtr + 28 >> 2] = yday;
839
- HEAP32[tmPtr + 36 >> 2] = -(date.getTimezoneOffset() * 60);
840
- var start = new Date(date.getFullYear(), 0, 1);
841
- var summerOffset = new Date(date.getFullYear(), 6, 1).getTimezoneOffset();
842
- var winterOffset = start.getTimezoneOffset();
843
- var dst = (summerOffset != winterOffset && date.getTimezoneOffset() == Math.min(winterOffset, summerOffset)) | 0;
844
- HEAP32[tmPtr + 32 >> 2] = dst;
845
- }
846
- var timers = {};
847
- var handleException = (e) => {
848
- if (e instanceof ExitStatus || e == "unwind") {
849
- return EXITSTATUS;
850
- }
851
- quit_(1, e);
343
+ exports2.defaultSafeIntegers = function defaultSafeIntegers(...args) {
344
+ this[cppdb].defaultSafeIntegers(...args);
345
+ return this;
852
346
  };
853
- var keepRuntimeAlive = () => noExitRuntime || runtimeKeepaliveCounter > 0;
854
- var _proc_exit = (code) => {
855
- EXITSTATUS = code;
856
- if (!keepRuntimeAlive()) {
857
- Module["onExit"]?.(code);
858
- ABORT2 = true;
859
- }
860
- quit_(code, new ExitStatus(code));
347
+ exports2.unsafeMode = function unsafeMode(...args) {
348
+ this[cppdb].unsafeMode(...args);
349
+ return this;
861
350
  };
862
- var exitJS = (status, implicit) => {
863
- EXITSTATUS = status;
864
- _proc_exit(status);
351
+ exports2.getters = {
352
+ name: {
353
+ get: function name() {
354
+ return this[cppdb].name;
355
+ },
356
+ enumerable: true
357
+ },
358
+ open: {
359
+ get: function open() {
360
+ return this[cppdb].open;
361
+ },
362
+ enumerable: true
363
+ },
364
+ inTransaction: {
365
+ get: function inTransaction() {
366
+ return this[cppdb].inTransaction;
367
+ },
368
+ enumerable: true
369
+ },
370
+ readonly: {
371
+ get: function readonly() {
372
+ return this[cppdb].readonly;
373
+ },
374
+ enumerable: true
375
+ },
376
+ memory: {
377
+ get: function memory() {
378
+ return this[cppdb].memory;
379
+ },
380
+ enumerable: true
381
+ }
865
382
  };
866
- var _exit = exitJS;
867
- var maybeExit = () => {
868
- if (!keepRuntimeAlive()) {
869
- try {
870
- _exit(EXITSTATUS);
871
- } catch (e) {
872
- handleException(e);
873
- }
383
+ }
384
+ });
385
+
386
+ // node_modules/better-sqlite3/lib/methods/transaction.js
387
+ var require_transaction = __commonJS({
388
+ "node_modules/better-sqlite3/lib/methods/transaction.js"(exports2, module2) {
389
+ "use strict";
390
+ var { cppdb } = require_util();
391
+ var controllers = /* @__PURE__ */ new WeakMap();
392
+ module2.exports = function transaction(fn) {
393
+ if (typeof fn !== "function")
394
+ throw new TypeError("Expected first argument to be a function");
395
+ const db3 = this[cppdb];
396
+ const controller = getController(db3, this);
397
+ const { apply } = Function.prototype;
398
+ const properties = {
399
+ default: { value: wrapTransaction(apply, fn, db3, controller.default) },
400
+ deferred: { value: wrapTransaction(apply, fn, db3, controller.deferred) },
401
+ immediate: { value: wrapTransaction(apply, fn, db3, controller.immediate) },
402
+ exclusive: { value: wrapTransaction(apply, fn, db3, controller.exclusive) },
403
+ database: { value: this, enumerable: true }
404
+ };
405
+ Object.defineProperties(properties.default.value, properties);
406
+ Object.defineProperties(properties.deferred.value, properties);
407
+ Object.defineProperties(properties.immediate.value, properties);
408
+ Object.defineProperties(properties.exclusive.value, properties);
409
+ return properties.default.value;
410
+ };
411
+ var getController = (db3, self) => {
412
+ let controller = controllers.get(db3);
413
+ if (!controller) {
414
+ const shared = {
415
+ commit: db3.prepare("COMMIT", self, false),
416
+ rollback: db3.prepare("ROLLBACK", self, false),
417
+ savepoint: db3.prepare("SAVEPOINT ` _bs3. `", self, false),
418
+ release: db3.prepare("RELEASE ` _bs3. `", self, false),
419
+ rollbackTo: db3.prepare("ROLLBACK TO ` _bs3. `", self, false)
420
+ };
421
+ controllers.set(db3, controller = {
422
+ default: Object.assign({ begin: db3.prepare("BEGIN", self, false) }, shared),
423
+ deferred: Object.assign({ begin: db3.prepare("BEGIN DEFERRED", self, false) }, shared),
424
+ immediate: Object.assign({ begin: db3.prepare("BEGIN IMMEDIATE", self, false) }, shared),
425
+ exclusive: Object.assign({ begin: db3.prepare("BEGIN EXCLUSIVE", self, false) }, shared)
426
+ });
874
427
  }
428
+ return controller;
875
429
  };
876
- var callUserCallback = (func) => {
877
- if (ABORT2) {
878
- return;
430
+ var wrapTransaction = (apply, fn, db3, { begin, commit, rollback, savepoint, release, rollbackTo }) => function sqliteTransaction() {
431
+ let before, after, undo;
432
+ if (db3.inTransaction) {
433
+ before = savepoint;
434
+ after = release;
435
+ undo = rollbackTo;
436
+ } else {
437
+ before = begin;
438
+ after = commit;
439
+ undo = rollback;
879
440
  }
441
+ before.run();
880
442
  try {
881
- return func();
882
- } catch (e) {
883
- handleException(e);
884
- } finally {
885
- maybeExit();
443
+ const result = apply.call(fn, this, arguments);
444
+ if (result && typeof result.then === "function") {
445
+ throw new TypeError("Transaction function cannot return a promise");
446
+ }
447
+ after.run();
448
+ return result;
449
+ } catch (ex) {
450
+ if (db3.inTransaction) {
451
+ undo.run();
452
+ if (undo !== rollback)
453
+ after.run();
454
+ }
455
+ throw ex;
886
456
  }
887
457
  };
888
- var _emscripten_get_now = () => performance.now();
889
- var __setitimer_js = (which, timeout_ms) => {
890
- if (timers[which]) {
891
- clearTimeout(timers[which].id);
892
- delete timers[which];
893
- }
894
- if (!timeout_ms)
895
- return 0;
896
- var id = setTimeout(() => {
897
- delete timers[which];
898
- callUserCallback(() => __emscripten_timeout(which, _emscripten_get_now()));
899
- }, timeout_ms);
900
- timers[which] = { id, timeout_ms };
901
- return 0;
458
+ }
459
+ });
460
+
461
+ // node_modules/better-sqlite3/lib/methods/pragma.js
462
+ var require_pragma = __commonJS({
463
+ "node_modules/better-sqlite3/lib/methods/pragma.js"(exports2, module2) {
464
+ "use strict";
465
+ var { getBooleanOption, cppdb } = require_util();
466
+ module2.exports = function pragma(source, options) {
467
+ if (options == null)
468
+ options = {};
469
+ if (typeof source !== "string")
470
+ throw new TypeError("Expected first argument to be a string");
471
+ if (typeof options !== "object")
472
+ throw new TypeError("Expected second argument to be an options object");
473
+ const simple = getBooleanOption(options, "simple");
474
+ const stmt = this[cppdb].prepare(`PRAGMA ${source}`, this, true);
475
+ return simple ? stmt.pluck().get() : stmt.all();
902
476
  };
903
- var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {
904
- if (!(maxBytesToWrite > 0))
905
- return 0;
906
- var startIdx = outIdx;
907
- var endIdx = outIdx + maxBytesToWrite - 1;
908
- for (var i = 0; i < str.length; ++i) {
909
- var u = str.codePointAt(i);
910
- if (u <= 127) {
911
- if (outIdx >= endIdx)
912
- break;
913
- heap[outIdx++] = u;
914
- } else if (u <= 2047) {
915
- if (outIdx + 1 >= endIdx)
916
- break;
917
- heap[outIdx++] = 192 | u >> 6;
918
- heap[outIdx++] = 128 | u & 63;
919
- } else if (u <= 65535) {
920
- if (outIdx + 2 >= endIdx)
921
- break;
922
- heap[outIdx++] = 224 | u >> 12;
923
- heap[outIdx++] = 128 | u >> 6 & 63;
924
- heap[outIdx++] = 128 | u & 63;
925
- } else {
926
- if (outIdx + 3 >= endIdx)
927
- break;
928
- heap[outIdx++] = 240 | u >> 18;
929
- heap[outIdx++] = 128 | u >> 12 & 63;
930
- heap[outIdx++] = 128 | u >> 6 & 63;
931
- heap[outIdx++] = 128 | u & 63;
932
- i++;
933
- }
934
- }
935
- heap[outIdx] = 0;
936
- return outIdx - startIdx;
477
+ }
478
+ });
479
+
480
+ // node_modules/better-sqlite3/lib/methods/backup.js
481
+ var require_backup = __commonJS({
482
+ "node_modules/better-sqlite3/lib/methods/backup.js"(exports2, module2) {
483
+ "use strict";
484
+ var fs3 = require("fs");
485
+ var path3 = require("path");
486
+ var { promisify: promisify2 } = require("util");
487
+ var { cppdb } = require_util();
488
+ var fsAccess = promisify2(fs3.access);
489
+ module2.exports = async function backup(filename, options) {
490
+ if (options == null)
491
+ options = {};
492
+ if (typeof filename !== "string")
493
+ throw new TypeError("Expected first argument to be a string");
494
+ if (typeof options !== "object")
495
+ throw new TypeError("Expected second argument to be an options object");
496
+ filename = filename.trim();
497
+ const attachedName = "attached" in options ? options.attached : "main";
498
+ const handler = "progress" in options ? options.progress : null;
499
+ if (!filename)
500
+ throw new TypeError("Backup filename cannot be an empty string");
501
+ if (filename === ":memory:")
502
+ throw new TypeError('Invalid backup filename ":memory:"');
503
+ if (typeof attachedName !== "string")
504
+ throw new TypeError('Expected the "attached" option to be a string');
505
+ if (!attachedName)
506
+ throw new TypeError('The "attached" option cannot be an empty string');
507
+ if (handler != null && typeof handler !== "function")
508
+ throw new TypeError('Expected the "progress" option to be a function');
509
+ await fsAccess(path3.dirname(filename)).catch(() => {
510
+ throw new TypeError("Cannot save backup because the directory does not exist");
511
+ });
512
+ const isNewFile = await fsAccess(filename).then(() => false, () => true);
513
+ return runBackup(this[cppdb].backup(this, attachedName, filename, isNewFile), handler || null);
514
+ };
515
+ var runBackup = (backup, handler) => {
516
+ let rate = 0;
517
+ let useDefault = true;
518
+ return new Promise((resolve, reject) => {
519
+ setImmediate(function step() {
520
+ try {
521
+ const progress = backup.transfer(rate);
522
+ if (!progress.remainingPages) {
523
+ backup.close();
524
+ resolve(progress);
525
+ return;
526
+ }
527
+ if (useDefault) {
528
+ useDefault = false;
529
+ rate = 100;
530
+ }
531
+ if (handler) {
532
+ const ret = handler(progress);
533
+ if (ret !== void 0) {
534
+ if (typeof ret === "number" && ret === ret)
535
+ rate = Math.max(0, Math.min(2147483647, Math.round(ret)));
536
+ else
537
+ throw new TypeError("Expected progress callback to return a number or undefined");
538
+ }
539
+ }
540
+ setImmediate(step);
541
+ } catch (err) {
542
+ backup.close();
543
+ reject(err);
544
+ }
545
+ });
546
+ });
937
547
  };
938
- var stringToUTF8 = (str, outPtr, maxBytesToWrite) => stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);
939
- var __tzset_js = (timezone, daylight, std_name, dst_name) => {
940
- var currentYear = (/* @__PURE__ */ new Date()).getFullYear();
941
- var winter = new Date(currentYear, 0, 1);
942
- var summer = new Date(currentYear, 6, 1);
943
- var winterOffset = winter.getTimezoneOffset();
944
- var summerOffset = summer.getTimezoneOffset();
945
- var stdTimezoneOffset = Math.max(winterOffset, summerOffset);
946
- HEAPU32[timezone >> 2] = stdTimezoneOffset * 60;
947
- HEAP32[daylight >> 2] = Number(winterOffset != summerOffset);
948
- var extractZone = (timezoneOffset) => {
949
- var sign = timezoneOffset >= 0 ? "-" : "+";
950
- var absOffset = Math.abs(timezoneOffset);
951
- var hours = String(Math.floor(absOffset / 60)).padStart(2, "0");
952
- var minutes = String(absOffset % 60).padStart(2, "0");
953
- return `UTC${sign}${hours}${minutes}`;
954
- };
955
- var winterName = extractZone(winterOffset);
956
- var summerName = extractZone(summerOffset);
957
- if (summerOffset < winterOffset) {
958
- stringToUTF8(winterName, std_name, 17);
959
- stringToUTF8(summerName, dst_name, 17);
960
- } else {
961
- stringToUTF8(winterName, dst_name, 17);
962
- stringToUTF8(summerName, std_name, 17);
963
- }
548
+ }
549
+ });
550
+
551
+ // node_modules/better-sqlite3/lib/methods/serialize.js
552
+ var require_serialize = __commonJS({
553
+ "node_modules/better-sqlite3/lib/methods/serialize.js"(exports2, module2) {
554
+ "use strict";
555
+ var { cppdb } = require_util();
556
+ module2.exports = function serialize(options) {
557
+ if (options == null)
558
+ options = {};
559
+ if (typeof options !== "object")
560
+ throw new TypeError("Expected first argument to be an options object");
561
+ const attachedName = "attached" in options ? options.attached : "main";
562
+ if (typeof attachedName !== "string")
563
+ throw new TypeError('Expected the "attached" option to be a string');
564
+ if (!attachedName)
565
+ throw new TypeError('The "attached" option cannot be an empty string');
566
+ return this[cppdb].serialize(attachedName);
964
567
  };
965
- var _emscripten_date_now = () => Date.now();
966
- var getHeapMax = () => 2147483648;
967
- var alignMemory = (size, alignment) => Math.ceil(size / alignment) * alignment;
968
- var growMemory = (size) => {
969
- var oldHeapSize = wasmMemory.buffer.byteLength;
970
- var pages = (size - oldHeapSize + 65535) / 65536 | 0;
971
- try {
972
- wasmMemory.grow(pages);
973
- updateMemoryViews();
974
- return 1;
975
- } catch (e) {
568
+ }
569
+ });
570
+
571
+ // node_modules/better-sqlite3/lib/methods/function.js
572
+ var require_function = __commonJS({
573
+ "node_modules/better-sqlite3/lib/methods/function.js"(exports2, module2) {
574
+ "use strict";
575
+ var { getBooleanOption, cppdb } = require_util();
576
+ module2.exports = function defineFunction(name, options, fn) {
577
+ if (options == null)
578
+ options = {};
579
+ if (typeof options === "function") {
580
+ fn = options;
581
+ options = {};
976
582
  }
583
+ if (typeof name !== "string")
584
+ throw new TypeError("Expected first argument to be a string");
585
+ if (typeof fn !== "function")
586
+ throw new TypeError("Expected last argument to be a function");
587
+ if (typeof options !== "object")
588
+ throw new TypeError("Expected second argument to be an options object");
589
+ if (!name)
590
+ throw new TypeError("User-defined function name cannot be an empty string");
591
+ const safeIntegers = "safeIntegers" in options ? +getBooleanOption(options, "safeIntegers") : 2;
592
+ const deterministic = getBooleanOption(options, "deterministic");
593
+ const directOnly = getBooleanOption(options, "directOnly");
594
+ const varargs = getBooleanOption(options, "varargs");
595
+ let argCount = -1;
596
+ if (!varargs) {
597
+ argCount = fn.length;
598
+ if (!Number.isInteger(argCount) || argCount < 0)
599
+ throw new TypeError("Expected function.length to be a positive integer");
600
+ if (argCount > 100)
601
+ throw new RangeError("User-defined functions cannot have more than 100 arguments");
602
+ }
603
+ this[cppdb].function(fn, name, argCount, safeIntegers, deterministic, directOnly);
604
+ return this;
977
605
  };
978
- var _emscripten_resize_heap = (requestedSize) => {
979
- var oldSize = HEAPU8.length;
980
- requestedSize >>>= 0;
981
- var maxHeapSize = getHeapMax();
982
- if (requestedSize > maxHeapSize) {
983
- return false;
984
- }
985
- for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
986
- var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);
987
- overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);
988
- var newSize = Math.min(maxHeapSize, alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536));
989
- var replacement = growMemory(newSize);
990
- if (replacement) {
991
- return true;
992
- }
993
- }
994
- return false;
606
+ }
607
+ });
608
+
609
+ // node_modules/better-sqlite3/lib/methods/aggregate.js
610
+ var require_aggregate = __commonJS({
611
+ "node_modules/better-sqlite3/lib/methods/aggregate.js"(exports2, module2) {
612
+ "use strict";
613
+ var { getBooleanOption, cppdb } = require_util();
614
+ module2.exports = function defineAggregate(name, options) {
615
+ if (typeof name !== "string")
616
+ throw new TypeError("Expected first argument to be a string");
617
+ if (typeof options !== "object" || options === null)
618
+ throw new TypeError("Expected second argument to be an options object");
619
+ if (!name)
620
+ throw new TypeError("User-defined function name cannot be an empty string");
621
+ const start = "start" in options ? options.start : null;
622
+ const step = getFunctionOption(options, "step", true);
623
+ const inverse = getFunctionOption(options, "inverse", false);
624
+ const result = getFunctionOption(options, "result", false);
625
+ const safeIntegers = "safeIntegers" in options ? +getBooleanOption(options, "safeIntegers") : 2;
626
+ const deterministic = getBooleanOption(options, "deterministic");
627
+ const directOnly = getBooleanOption(options, "directOnly");
628
+ const varargs = getBooleanOption(options, "varargs");
629
+ let argCount = -1;
630
+ if (!varargs) {
631
+ argCount = Math.max(getLength(step), inverse ? getLength(inverse) : 0);
632
+ if (argCount > 0)
633
+ argCount -= 1;
634
+ if (argCount > 100)
635
+ throw new RangeError("User-defined functions cannot have more than 100 arguments");
636
+ }
637
+ this[cppdb].aggregate(start, step, inverse, result, name, argCount, safeIntegers, deterministic, directOnly);
638
+ return this;
995
639
  };
996
- var UTF8Decoder = globalThis.TextDecoder && new TextDecoder();
997
- var findStringEnd = (heapOrArray, idx, maxBytesToRead, ignoreNul) => {
998
- var maxIdx = idx + maxBytesToRead;
999
- if (ignoreNul)
1000
- return maxIdx;
1001
- while (heapOrArray[idx] && !(idx >= maxIdx))
1002
- ++idx;
1003
- return idx;
640
+ var getFunctionOption = (options, key, required) => {
641
+ const value = key in options ? options[key] : null;
642
+ if (typeof value === "function")
643
+ return value;
644
+ if (value != null)
645
+ throw new TypeError(`Expected the "${key}" option to be a function`);
646
+ if (required)
647
+ throw new TypeError(`Missing required option "${key}"`);
648
+ return null;
1004
649
  };
1005
- var UTF8ArrayToString = (heapOrArray, idx = 0, maxBytesToRead, ignoreNul) => {
1006
- var endPtr = findStringEnd(heapOrArray, idx, maxBytesToRead, ignoreNul);
1007
- if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
1008
- return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));
1009
- }
1010
- var str = "";
1011
- while (idx < endPtr) {
1012
- var u0 = heapOrArray[idx++];
1013
- if (!(u0 & 128)) {
1014
- str += String.fromCharCode(u0);
1015
- continue;
1016
- }
1017
- var u1 = heapOrArray[idx++] & 63;
1018
- if ((u0 & 224) == 192) {
1019
- str += String.fromCharCode((u0 & 31) << 6 | u1);
1020
- continue;
1021
- }
1022
- var u2 = heapOrArray[idx++] & 63;
1023
- if ((u0 & 240) == 224) {
1024
- u0 = (u0 & 15) << 12 | u1 << 6 | u2;
1025
- } else {
1026
- u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heapOrArray[idx++] & 63;
1027
- }
1028
- if (u0 < 65536) {
1029
- str += String.fromCharCode(u0);
1030
- } else {
1031
- var ch = u0 - 65536;
1032
- str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);
1033
- }
1034
- }
1035
- return str;
650
+ var getLength = ({ length }) => {
651
+ if (Number.isInteger(length) && length >= 0)
652
+ return length;
653
+ throw new TypeError("Expected function.length to be a positive integer");
1036
654
  };
1037
- var UTF8ToString = (ptr, maxBytesToRead, ignoreNul) => ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead, ignoreNul) : "";
1038
- function _nodejsAccess(vfs, filePath, flags, outResult) {
1039
- let aflags = fs3.constants.F_OK;
1040
- if (flags == SQLITE_ACCESS_READWRITE)
1041
- aflags = fs3.constants.R_OK | fs3.constants.W_OK;
1042
- if (flags == SQLITE_ACCESS_READ)
1043
- aflags = fs3.constants.R_OK;
1044
- try {
1045
- fs3.accessSync(UTF8ToString(filePath), aflags);
1046
- setValue(outResult, 1, "i32");
1047
- } catch {
1048
- setValue(outResult, 0, "i32");
655
+ }
656
+ });
657
+
658
+ // node_modules/better-sqlite3/lib/methods/table.js
659
+ var require_table = __commonJS({
660
+ "node_modules/better-sqlite3/lib/methods/table.js"(exports2, module2) {
661
+ "use strict";
662
+ var { cppdb } = require_util();
663
+ module2.exports = function defineTable(name, factory) {
664
+ if (typeof name !== "string")
665
+ throw new TypeError("Expected first argument to be a string");
666
+ if (!name)
667
+ throw new TypeError("Virtual table module name cannot be an empty string");
668
+ let eponymous = false;
669
+ if (typeof factory === "object" && factory !== null) {
670
+ eponymous = true;
671
+ factory = defer2(parseTableDefinition(factory, "used", name));
672
+ } else {
673
+ if (typeof factory !== "function")
674
+ throw new TypeError("Expected second argument to be a function or a table definition object");
675
+ factory = wrapFactory(factory);
1049
676
  }
1050
- return SQLITE_OK;
677
+ this[cppdb].table(factory, name, eponymous);
678
+ return this;
679
+ };
680
+ function wrapFactory(factory) {
681
+ return function virtualTableFactory(moduleName, databaseName, tableName, ...args) {
682
+ const thisObject = {
683
+ module: moduleName,
684
+ database: databaseName,
685
+ table: tableName
686
+ };
687
+ const def = apply.call(factory, thisObject, args);
688
+ if (typeof def !== "object" || def === null) {
689
+ throw new TypeError(`Virtual table module "${moduleName}" did not return a table definition object`);
690
+ }
691
+ return parseTableDefinition(def, "returned", moduleName);
692
+ };
1051
693
  }
1052
- function _nodejsCheckReservedLock(fi, outResult) {
1053
- try {
1054
- fs3.accessSync(`${_path(fi)}.lock`, fs3.constants.F_OK);
1055
- setValue(outResult, 1, "i32");
1056
- } catch {
1057
- setValue(outResult, 0, "i32");
694
+ function parseTableDefinition(def, verb, moduleName) {
695
+ if (!hasOwnProperty.call(def, "rows")) {
696
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition without a "rows" property`);
1058
697
  }
1059
- return SQLITE_OK;
1060
- }
1061
- function _nodejsClose(fi) {
1062
- _nodejsUnlock(fi, SQLITE_LOCK_NONE);
1063
- try {
1064
- fs3.closeSync(_fd(fi));
1065
- } catch {
1066
- return SQLITE_IOERR_CLOSE;
698
+ if (!hasOwnProperty.call(def, "columns")) {
699
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition without a "columns" property`);
1067
700
  }
1068
- return SQLITE_OK;
1069
- }
1070
- function _nodejsDelete(vfs, filePath, dirSync) {
1071
- const pathStr = UTF8ToString(filePath);
1072
- try {
1073
- fs3.unlinkSync(pathStr);
1074
- } catch (err2) {
1075
- if (err2.code != "ENOENT")
1076
- return SQLITE_IOERR_DELETE;
701
+ const rows = def.rows;
702
+ if (typeof rows !== "function" || Object.getPrototypeOf(rows) !== GeneratorFunctionPrototype) {
703
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "rows" property (should be a generator function)`);
1077
704
  }
1078
- if (dirSync) {
1079
- let fd = -1;
1080
- try {
1081
- fd = fs3.openSync(path3.dirname(pathStr), "r");
1082
- fs3.fsyncSync(fd);
1083
- } catch {
1084
- return SQLITE_IOERR_FSYNC;
1085
- } finally {
1086
- try {
1087
- fs3.closeSync(fd);
1088
- } catch {
1089
- return SQLITE_IOERR_FSYNC;
1090
- }
1091
- }
705
+ let columns = def.columns;
706
+ if (!Array.isArray(columns) || !(columns = [...columns]).every((x) => typeof x === "string")) {
707
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "columns" property (should be an array of strings)`);
1092
708
  }
1093
- return SQLITE_OK;
1094
- }
1095
- function _nodejsFileSize(fi, outSize) {
1096
- try {
1097
- setValue(outSize, fs3.fstatSync(_fd(fi)).size, "i64");
1098
- } catch {
1099
- return SQLITE_IOERR_FSTAT;
709
+ if (columns.length !== new Set(columns).size) {
710
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with duplicate column names`);
1100
711
  }
1101
- return SQLITE_OK;
1102
- }
1103
- function _nodejsFullPathname(vfs, relPath, sizeFullPath, outFullPath) {
1104
- const full = path3.resolve(UTF8ToString(relPath));
1105
- stringToUTF8(full, outFullPath, sizeFullPath);
1106
- return full.length < sizeFullPath ? SQLITE_OK : SQLITE_CANTOPEN;
1107
- }
1108
- function _nodejsLock(fi, level) {
1109
- if (!_isLocked(fi)) {
1110
- try {
1111
- fs3.mkdirSync(`${_path(fi)}.lock`);
1112
- } catch (err2) {
1113
- return err2.code == "EEXIST" ? SQLITE_BUSY : SQLITE_IOERR_LOCK;
1114
- }
1115
- _setLocked(fi, true);
712
+ if (!columns.length) {
713
+ throw new RangeError(`Virtual table module "${moduleName}" ${verb} a table definition with zero columns`);
1116
714
  }
1117
- return SQLITE_OK;
1118
- }
1119
- function _nodejsRandomness(vfs, bytes, outBuffer) {
1120
- const buf = HEAPU8.subarray(outBuffer, outBuffer + bytes);
1121
- crypto.randomFillSync(buf);
1122
- return bytes;
1123
- }
1124
- function _nodejsRead(fi, outBuffer, bytes, offset) {
1125
- const buf = HEAPU8.subarray(outBuffer, outBuffer + bytes);
1126
- let bytesRead;
1127
- try {
1128
- bytesRead = fs3.readSync(_fd(fi), buf, 0, bytes, offset);
1129
- } catch {
1130
- return SQLITE_IOERR_READ;
1131
- }
1132
- if (bytesRead == bytes) {
1133
- return SQLITE_OK;
1134
- } else if (bytesRead >= 0) {
1135
- if (bytesRead < bytes) {
1136
- try {
1137
- buf.fill(0, bytesRead);
1138
- } catch {
1139
- return SQLITE_IOERR_READ;
1140
- }
715
+ let parameters;
716
+ if (hasOwnProperty.call(def, "parameters")) {
717
+ parameters = def.parameters;
718
+ if (!Array.isArray(parameters) || !(parameters = [...parameters]).every((x) => typeof x === "string")) {
719
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "parameters" property (should be an array of strings)`);
1141
720
  }
1142
- return SQLITE_IOERR_SHORT_READ;
721
+ } else {
722
+ parameters = inferParameters(rows);
1143
723
  }
1144
- return SQLITE_IOERR_READ;
1145
- }
1146
- function _nodejsSync(fi, flags) {
1147
- try {
1148
- fs3.fsyncSync(_fd(fi));
1149
- } catch {
1150
- return SQLITE_IOERR_FSYNC;
724
+ if (parameters.length !== new Set(parameters).size) {
725
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with duplicate parameter names`);
1151
726
  }
1152
- return SQLITE_OK;
1153
- }
1154
- function _nodejsTruncate(fi, size) {
1155
- try {
1156
- fs3.ftruncateSync(_fd(fi), _safeInt(size));
1157
- } catch {
1158
- return SQLITE_IOERR_TRUNCATE;
727
+ if (parameters.length > 32) {
728
+ throw new RangeError(`Virtual table module "${moduleName}" ${verb} a table definition with more than the maximum number of 32 parameters`);
1159
729
  }
1160
- return SQLITE_OK;
1161
- }
1162
- function _nodejsUnlock(fi, level) {
1163
- if (level == SQLITE_LOCK_NONE && _isLocked(fi)) {
1164
- try {
1165
- fs3.rmdirSync(`${_path(fi)}.lock`);
1166
- } catch (err2) {
1167
- if (err2.code != "ENOENT")
1168
- return SQLITE_IOERR_UNLOCK;
730
+ for (const parameter of parameters) {
731
+ if (columns.includes(parameter)) {
732
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with column "${parameter}" which was ambiguously defined as both a column and parameter`);
1169
733
  }
1170
- _setLocked(fi, false);
1171
734
  }
1172
- return SQLITE_OK;
1173
- }
1174
- function _nodejsWrite(fi, buffer, bytes, offset) {
1175
- try {
1176
- const bytesWritten = fs3.writeSync(_fd(fi), HEAPU8.subarray(buffer, buffer + bytes), 0, bytes, _safeInt(offset));
1177
- return bytesWritten != bytes ? SQLITE_IOERR_WRITE : SQLITE_OK;
1178
- } catch {
1179
- return SQLITE_IOERR_WRITE;
1180
- }
1181
- }
1182
- function _nodejs_max_path_length() {
1183
- return process.platform == "win32" ? 260 : 4096;
1184
- }
1185
- function _nodejs_open(filePath, flags, mode) {
1186
- let oflags = 0;
1187
- if (flags & SQLITE_OPEN_EXCLUSIVE)
1188
- oflags |= fs3.constants.O_EXCL;
1189
- if (flags & SQLITE_OPEN_CREATE)
1190
- oflags |= fs3.constants.O_CREAT;
1191
- if (flags & SQLITE_OPEN_READONLY)
1192
- oflags |= fs3.constants.O_RDONLY;
1193
- if (flags & SQLITE_OPEN_READWRITE)
1194
- oflags |= fs3.constants.O_RDWR;
1195
- try {
1196
- return fs3.openSync(UTF8ToString(filePath), oflags, mode);
1197
- } catch {
1198
- return -1;
735
+ let safeIntegers = 2;
736
+ if (hasOwnProperty.call(def, "safeIntegers")) {
737
+ const bool = def.safeIntegers;
738
+ if (typeof bool !== "boolean") {
739
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "safeIntegers" property (should be a boolean)`);
740
+ }
741
+ safeIntegers = +bool;
1199
742
  }
1200
- }
1201
- var getCFunc = (ident) => {
1202
- var func = Module["_" + ident];
1203
- return func;
1204
- };
1205
- var writeArrayToMemory = (array, buffer) => {
1206
- HEAP8.set(array, buffer);
1207
- };
1208
- var lengthBytesUTF8 = (str) => {
1209
- var len = 0;
1210
- for (var i = 0; i < str.length; ++i) {
1211
- var c = str.charCodeAt(i);
1212
- if (c <= 127) {
1213
- len++;
1214
- } else if (c <= 2047) {
1215
- len += 2;
1216
- } else if (c >= 55296 && c <= 57343) {
1217
- len += 4;
1218
- ++i;
1219
- } else {
1220
- len += 3;
743
+ let directOnly = false;
744
+ if (hasOwnProperty.call(def, "directOnly")) {
745
+ directOnly = def.directOnly;
746
+ if (typeof directOnly !== "boolean") {
747
+ throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "directOnly" property (should be a boolean)`);
1221
748
  }
1222
749
  }
1223
- return len;
1224
- };
1225
- var stackAlloc = (sz) => __emscripten_stack_alloc(sz);
1226
- var stringToUTF8OnStack = (str) => {
1227
- var size = lengthBytesUTF8(str) + 1;
1228
- var ret = stackAlloc(size);
1229
- stringToUTF8(str, ret, size);
1230
- return ret;
1231
- };
1232
- var ccall = (ident, returnType, argTypes, args, opts) => {
1233
- var toC = { string: (str) => {
1234
- var ret2 = 0;
1235
- if (str !== null && str !== void 0 && str !== 0) {
1236
- ret2 = stringToUTF8OnStack(str);
1237
- }
1238
- return ret2;
1239
- }, array: (arr) => {
1240
- var ret2 = stackAlloc(arr.length);
1241
- writeArrayToMemory(arr, ret2);
1242
- return ret2;
1243
- } };
1244
- function convertReturnValue(ret2) {
1245
- if (returnType === "string") {
1246
- return UTF8ToString(ret2);
1247
- }
1248
- if (returnType === "boolean")
1249
- return Boolean(ret2);
1250
- return ret2;
1251
- }
1252
- var func = getCFunc(ident);
1253
- var cArgs = [];
1254
- var stack = 0;
1255
- if (args) {
1256
- for (var i = 0; i < args.length; i++) {
1257
- var converter = toC[argTypes[i]];
1258
- if (converter) {
1259
- if (stack === 0)
1260
- stack = stackSave();
1261
- cArgs[i] = converter(args[i]);
750
+ const columnDefinitions = [
751
+ ...parameters.map(identifier).map((str) => `${str} HIDDEN`),
752
+ ...columns.map(identifier)
753
+ ];
754
+ return [
755
+ `CREATE TABLE x(${columnDefinitions.join(", ")});`,
756
+ wrapGenerator(rows, new Map(columns.map((x, i) => [x, parameters.length + i])), moduleName),
757
+ parameters,
758
+ safeIntegers,
759
+ directOnly
760
+ ];
761
+ }
762
+ function wrapGenerator(generator, columnMap, moduleName) {
763
+ return function* virtualTable(...args) {
764
+ const output = args.map((x) => Buffer.isBuffer(x) ? Buffer.from(x) : x);
765
+ for (let i = 0; i < columnMap.size; ++i) {
766
+ output.push(null);
767
+ }
768
+ for (const row of generator(...args)) {
769
+ if (Array.isArray(row)) {
770
+ extractRowArray(row, output, columnMap.size, moduleName);
771
+ yield output;
772
+ } else if (typeof row === "object" && row !== null) {
773
+ extractRowObject(row, output, columnMap, moduleName);
774
+ yield output;
1262
775
  } else {
1263
- cArgs[i] = args[i];
776
+ throw new TypeError(`Virtual table module "${moduleName}" yielded something that isn't a valid row object`);
1264
777
  }
1265
778
  }
779
+ };
780
+ }
781
+ function extractRowArray(row, output, columnCount, moduleName) {
782
+ if (row.length !== columnCount) {
783
+ throw new TypeError(`Virtual table module "${moduleName}" yielded a row with an incorrect number of columns`);
1266
784
  }
1267
- var ret = func(...cArgs);
1268
- function onDone(ret2) {
1269
- if (stack !== 0)
1270
- stackRestore(stack);
1271
- return convertReturnValue(ret2);
1272
- }
1273
- ret = onDone(ret);
1274
- return ret;
1275
- };
1276
- var cwrap = (ident, returnType, argTypes, opts) => {
1277
- var numericArgs = !argTypes || argTypes.every((type) => type === "number" || type === "boolean");
1278
- var numericRet = returnType !== "string";
1279
- if (numericRet && numericArgs && !opts) {
1280
- return getCFunc(ident);
1281
- }
1282
- return (...args) => ccall(ident, returnType, argTypes, args, opts);
1283
- };
1284
- var wasmTableMirror = [];
1285
- var getWasmTableEntry = (funcPtr) => {
1286
- var func = wasmTableMirror[funcPtr];
1287
- if (!func) {
1288
- wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr);
785
+ const offset = output.length - columnCount;
786
+ for (let i = 0; i < columnCount; ++i) {
787
+ output[i + offset] = row[i];
1289
788
  }
1290
- return func;
1291
- };
1292
- var updateTableMap = (offset, count) => {
1293
- if (functionsInTableMap) {
1294
- for (var i = offset; i < offset + count; i++) {
1295
- var item = getWasmTableEntry(i);
1296
- if (item) {
1297
- functionsInTableMap.set(item, i);
1298
- }
789
+ }
790
+ function extractRowObject(row, output, columnMap, moduleName) {
791
+ let count = 0;
792
+ for (const key of Object.keys(row)) {
793
+ const index = columnMap.get(key);
794
+ if (index === void 0) {
795
+ throw new TypeError(`Virtual table module "${moduleName}" yielded a row with an undeclared column "${key}"`);
1299
796
  }
797
+ output[index] = row[key];
798
+ count += 1;
1300
799
  }
1301
- };
1302
- var functionsInTableMap;
1303
- var getFunctionAddress = (func) => {
1304
- if (!functionsInTableMap) {
1305
- functionsInTableMap = /* @__PURE__ */ new WeakMap();
1306
- updateTableMap(0, wasmTable.length);
800
+ if (count !== columnMap.size) {
801
+ throw new TypeError(`Virtual table module "${moduleName}" yielded a row with missing columns`);
1307
802
  }
1308
- return functionsInTableMap.get(func) || 0;
1309
- };
1310
- var freeTableIndexes = [];
1311
- var getEmptyTableSlot = () => {
1312
- if (freeTableIndexes.length) {
1313
- return freeTableIndexes.pop();
803
+ }
804
+ function inferParameters({ length }) {
805
+ if (!Number.isInteger(length) || length < 0) {
806
+ throw new TypeError("Expected function.length to be a positive integer");
1314
807
  }
1315
- return wasmTable["grow"](1);
1316
- };
1317
- var setWasmTableEntry = (idx, func) => {
1318
- wasmTable.set(idx, func);
1319
- wasmTableMirror[idx] = wasmTable.get(idx);
1320
- };
1321
- var uleb128EncodeWithLen = (arr) => {
1322
- const n = arr.length;
1323
- return [n % 128 | 128, n >> 7, ...arr];
1324
- };
1325
- var wasmTypeCodes = { i: 127, p: 127, j: 126, f: 125, d: 124, e: 111 };
1326
- var generateTypePack = (types2) => uleb128EncodeWithLen(Array.from(types2, (type) => {
1327
- var code = wasmTypeCodes[type];
1328
- return code;
1329
- }));
1330
- var convertJsFunctionToWasm = (func, sig) => {
1331
- var bytes = Uint8Array.of(0, 97, 115, 109, 1, 0, 0, 0, 1, ...uleb128EncodeWithLen([1, 96, ...generateTypePack(sig.slice(1)), ...generateTypePack(sig[0] === "v" ? "" : sig[0])]), 2, 7, 1, 1, 101, 1, 102, 0, 0, 7, 5, 1, 1, 102, 0, 0);
1332
- var module3 = new WebAssembly.Module(bytes);
1333
- var instance = new WebAssembly.Instance(module3, { e: { f: func } });
1334
- var wrappedFunc = instance.exports["f"];
1335
- return wrappedFunc;
1336
- };
1337
- var addFunction = (func, sig) => {
1338
- var rtn = getFunctionAddress(func);
1339
- if (rtn) {
1340
- return rtn;
808
+ const params = [];
809
+ for (let i = 0; i < length; ++i) {
810
+ params.push(`$${i + 1}`);
1341
811
  }
1342
- var ret = getEmptyTableSlot();
1343
- try {
1344
- setWasmTableEntry(ret, func);
1345
- } catch (err2) {
1346
- if (!(err2 instanceof TypeError)) {
1347
- throw err2;
1348
- }
1349
- var wrapped = convertJsFunctionToWasm(func, sig);
1350
- setWasmTableEntry(ret, wrapped);
1351
- }
1352
- functionsInTableMap.set(func, ret);
1353
- return ret;
812
+ return params;
813
+ }
814
+ var { hasOwnProperty } = Object.prototype;
815
+ var { apply } = Function.prototype;
816
+ var GeneratorFunctionPrototype = Object.getPrototypeOf(function* () {
817
+ });
818
+ var identifier = (str) => `"${str.replace(/"/g, '""')}"`;
819
+ var defer2 = (x) => () => x;
820
+ }
821
+ });
822
+
823
+ // node_modules/better-sqlite3/lib/methods/inspect.js
824
+ var require_inspect = __commonJS({
825
+ "node_modules/better-sqlite3/lib/methods/inspect.js"(exports2, module2) {
826
+ "use strict";
827
+ var DatabaseInspection = function Database2() {
1354
828
  };
1355
- var removeFunction = (index) => {
1356
- functionsInTableMap.delete(getWasmTableEntry(index));
1357
- setWasmTableEntry(index, null);
1358
- freeTableIndexes.push(index);
829
+ module2.exports = function inspect(depth, opts) {
830
+ return Object.assign(new DatabaseInspection(), this);
1359
831
  };
1360
- {
1361
- if (Module["noExitRuntime"])
1362
- noExitRuntime = Module["noExitRuntime"];
1363
- if (Module["print"])
1364
- out = Module["print"];
1365
- if (Module["printErr"])
1366
- err = Module["printErr"];
1367
- if (Module["wasmBinary"])
1368
- wasmBinary = Module["wasmBinary"];
1369
- if (Module["arguments"])
1370
- arguments_ = Module["arguments"];
1371
- if (Module["thisProgram"])
1372
- thisProgram = Module["thisProgram"];
1373
- if (Module["preInit"]) {
1374
- if (typeof Module["preInit"] == "function")
1375
- Module["preInit"] = [Module["preInit"]];
1376
- while (Module["preInit"].length > 0) {
1377
- Module["preInit"].shift()();
1378
- }
1379
- }
1380
- }
1381
- Module["cwrap"] = cwrap;
1382
- Module["addFunction"] = addFunction;
1383
- Module["removeFunction"] = removeFunction;
1384
- var _sqlite3_finalize;
1385
- var _sqlite3_reset;
1386
- var _sqlite3_clear_bindings;
1387
- var _sqlite3_value_blob;
1388
- var _sqlite3_value_text;
1389
- var _sqlite3_value_bytes;
1390
- var _sqlite3_value_double;
1391
- var _sqlite3_value_int64;
1392
- var _sqlite3_value_type;
1393
- var _sqlite3_result_blob;
1394
- var _sqlite3_result_blob64;
1395
- var _sqlite3_result_double;
1396
- var _sqlite3_result_error;
1397
- var _sqlite3_result_int;
1398
- var _sqlite3_result_int64;
1399
- var _sqlite3_result_null;
1400
- var _sqlite3_result_text;
1401
- var _sqlite3_step;
1402
- var _sqlite3_column_count;
1403
- var _sqlite3_column_blob;
1404
- var _sqlite3_column_bytes;
1405
- var _sqlite3_column_double;
1406
- var _sqlite3_column_int64;
1407
- var _sqlite3_column_text;
1408
- var _sqlite3_column_type;
1409
- var _sqlite3_column_name;
1410
- var _sqlite3_column_table_name;
1411
- var _sqlite3_bind_blob;
1412
- var _sqlite3_bind_blob64;
1413
- var _sqlite3_bind_double;
1414
- var _sqlite3_bind_int;
1415
- var _sqlite3_bind_int64;
1416
- var _sqlite3_bind_null;
1417
- var _sqlite3_bind_text;
1418
- var _sqlite3_bind_parameter_index;
1419
- var _sqlite3_exec;
1420
- var _sqlite3_prepare_v2;
1421
- var _sqlite3_errmsg;
1422
- var _sqlite3_last_insert_rowid;
1423
- var _sqlite3_changes;
1424
- var _sqlite3_close_v2;
1425
- var _sqlite3_create_function_v2;
1426
- var _sqlite3_open_v2;
1427
- var _sqlite3_get_autocommit;
1428
- var _malloc;
1429
- var _free;
1430
- var __emscripten_timeout;
1431
- var __emscripten_stack_restore;
1432
- var __emscripten_stack_alloc;
1433
- var _emscripten_stack_get_current;
1434
- var memory;
1435
- var __indirect_function_table;
1436
- var wasmMemory;
1437
- var wasmTable;
1438
- function assignWasmExports(wasmExports2) {
1439
- _sqlite3_finalize = Module["_sqlite3_finalize"] = wasmExports2["A"];
1440
- _sqlite3_reset = Module["_sqlite3_reset"] = wasmExports2["B"];
1441
- _sqlite3_clear_bindings = Module["_sqlite3_clear_bindings"] = wasmExports2["C"];
1442
- _sqlite3_value_blob = Module["_sqlite3_value_blob"] = wasmExports2["D"];
1443
- _sqlite3_value_text = Module["_sqlite3_value_text"] = wasmExports2["E"];
1444
- _sqlite3_value_bytes = Module["_sqlite3_value_bytes"] = wasmExports2["F"];
1445
- _sqlite3_value_double = Module["_sqlite3_value_double"] = wasmExports2["G"];
1446
- _sqlite3_value_int64 = Module["_sqlite3_value_int64"] = wasmExports2["H"];
1447
- _sqlite3_value_type = Module["_sqlite3_value_type"] = wasmExports2["I"];
1448
- _sqlite3_result_blob = Module["_sqlite3_result_blob"] = wasmExports2["J"];
1449
- _sqlite3_result_blob64 = Module["_sqlite3_result_blob64"] = wasmExports2["K"];
1450
- _sqlite3_result_double = Module["_sqlite3_result_double"] = wasmExports2["L"];
1451
- _sqlite3_result_error = Module["_sqlite3_result_error"] = wasmExports2["M"];
1452
- _sqlite3_result_int = Module["_sqlite3_result_int"] = wasmExports2["N"];
1453
- _sqlite3_result_int64 = Module["_sqlite3_result_int64"] = wasmExports2["O"];
1454
- _sqlite3_result_null = Module["_sqlite3_result_null"] = wasmExports2["P"];
1455
- _sqlite3_result_text = Module["_sqlite3_result_text"] = wasmExports2["Q"];
1456
- _sqlite3_step = Module["_sqlite3_step"] = wasmExports2["R"];
1457
- _sqlite3_column_count = Module["_sqlite3_column_count"] = wasmExports2["S"];
1458
- _sqlite3_column_blob = Module["_sqlite3_column_blob"] = wasmExports2["T"];
1459
- _sqlite3_column_bytes = Module["_sqlite3_column_bytes"] = wasmExports2["U"];
1460
- _sqlite3_column_double = Module["_sqlite3_column_double"] = wasmExports2["V"];
1461
- _sqlite3_column_int64 = Module["_sqlite3_column_int64"] = wasmExports2["W"];
1462
- _sqlite3_column_text = Module["_sqlite3_column_text"] = wasmExports2["X"];
1463
- _sqlite3_column_type = Module["_sqlite3_column_type"] = wasmExports2["Y"];
1464
- _sqlite3_column_name = Module["_sqlite3_column_name"] = wasmExports2["Z"];
1465
- _sqlite3_column_table_name = Module["_sqlite3_column_table_name"] = wasmExports2["_"];
1466
- _sqlite3_bind_blob = Module["_sqlite3_bind_blob"] = wasmExports2["$"];
1467
- _sqlite3_bind_blob64 = Module["_sqlite3_bind_blob64"] = wasmExports2["aa"];
1468
- _sqlite3_bind_double = Module["_sqlite3_bind_double"] = wasmExports2["ba"];
1469
- _sqlite3_bind_int = Module["_sqlite3_bind_int"] = wasmExports2["ca"];
1470
- _sqlite3_bind_int64 = Module["_sqlite3_bind_int64"] = wasmExports2["da"];
1471
- _sqlite3_bind_null = Module["_sqlite3_bind_null"] = wasmExports2["ea"];
1472
- _sqlite3_bind_text = Module["_sqlite3_bind_text"] = wasmExports2["fa"];
1473
- _sqlite3_bind_parameter_index = Module["_sqlite3_bind_parameter_index"] = wasmExports2["ga"];
1474
- _sqlite3_exec = Module["_sqlite3_exec"] = wasmExports2["ha"];
1475
- _sqlite3_prepare_v2 = Module["_sqlite3_prepare_v2"] = wasmExports2["ia"];
1476
- _sqlite3_errmsg = Module["_sqlite3_errmsg"] = wasmExports2["ja"];
1477
- _sqlite3_last_insert_rowid = Module["_sqlite3_last_insert_rowid"] = wasmExports2["ka"];
1478
- _sqlite3_changes = Module["_sqlite3_changes"] = wasmExports2["la"];
1479
- _sqlite3_close_v2 = Module["_sqlite3_close_v2"] = wasmExports2["ma"];
1480
- _sqlite3_create_function_v2 = Module["_sqlite3_create_function_v2"] = wasmExports2["na"];
1481
- _sqlite3_open_v2 = Module["_sqlite3_open_v2"] = wasmExports2["oa"];
1482
- _sqlite3_get_autocommit = Module["_sqlite3_get_autocommit"] = wasmExports2["pa"];
1483
- _malloc = Module["_malloc"] = wasmExports2["qa"];
1484
- _free = Module["_free"] = wasmExports2["ra"];
1485
- __emscripten_timeout = wasmExports2["ta"];
1486
- __emscripten_stack_restore = wasmExports2["ua"];
1487
- __emscripten_stack_alloc = wasmExports2["va"];
1488
- _emscripten_stack_get_current = wasmExports2["wa"];
1489
- memory = wasmMemory = wasmExports2["y"];
1490
- __indirect_function_table = wasmTable = wasmExports2["sa"];
1491
- }
1492
- var wasmImports = { n: __abort_js, l: __emscripten_runtime_keepalive_clear, o: __localtime_js, i: __setitimer_js, p: __tzset_js, q: _emscripten_date_now, a: _emscripten_get_now, j: _emscripten_resize_heap, w: _nodejsAccess, s: _nodejsCheckReservedLock, f: _nodejsClose, x: _nodejsDelete, v: _nodejsFileSize, m: _nodejsFullPathname, u: _nodejsLock, h: _nodejsRandomness, e: _nodejsRead, b: _nodejsSync, c: _nodejsTruncate, t: _nodejsUnlock, d: _nodejsWrite, g: _nodejs_max_path_length, r: _nodejs_open, k: _proc_exit };
1493
- function run() {
1494
- preRun();
1495
- function doRun() {
1496
- Module["calledRun"] = true;
1497
- if (ABORT2)
1498
- return;
1499
- initRuntime();
1500
- Module["onRuntimeInitialized"]?.();
1501
- postRun();
1502
- }
1503
- if (Module["setStatus"]) {
1504
- Module["setStatus"]("Running...");
1505
- setTimeout(() => {
1506
- setTimeout(() => Module["setStatus"](""), 1);
1507
- doRun();
1508
- }, 1);
832
+ }
833
+ });
834
+
835
+ // node_modules/better-sqlite3/lib/database.js
836
+ var require_database = __commonJS({
837
+ "node_modules/better-sqlite3/lib/database.js"(exports2, module2) {
838
+ "use strict";
839
+ var fs3 = require("fs");
840
+ var path3 = require("path");
841
+ var util = require_util();
842
+ var SqliteError = require_sqlite_error();
843
+ var DEFAULT_ADDON;
844
+ function Database2(filenameGiven, options) {
845
+ if (new.target == null) {
846
+ return new Database2(filenameGiven, options);
847
+ }
848
+ let buffer;
849
+ if (Buffer.isBuffer(filenameGiven)) {
850
+ buffer = filenameGiven;
851
+ filenameGiven = ":memory:";
852
+ }
853
+ if (filenameGiven == null)
854
+ filenameGiven = "";
855
+ if (options == null)
856
+ options = {};
857
+ if (typeof filenameGiven !== "string")
858
+ throw new TypeError("Expected first argument to be a string");
859
+ if (typeof options !== "object")
860
+ throw new TypeError("Expected second argument to be an options object");
861
+ if ("readOnly" in options)
862
+ throw new TypeError('Misspelled option "readOnly" should be "readonly"');
863
+ if ("memory" in options)
864
+ throw new TypeError('Option "memory" was removed in v7.0.0 (use ":memory:" filename instead)');
865
+ const filename = filenameGiven.trim();
866
+ const anonymous = filename === "" || filename === ":memory:";
867
+ const readonly = util.getBooleanOption(options, "readonly");
868
+ const fileMustExist = util.getBooleanOption(options, "fileMustExist");
869
+ const timeout = "timeout" in options ? options.timeout : 5e3;
870
+ const verbose = "verbose" in options ? options.verbose : null;
871
+ const nativeBinding = "nativeBinding" in options ? options.nativeBinding : null;
872
+ if (readonly && anonymous && !buffer)
873
+ throw new TypeError("In-memory/temporary databases cannot be readonly");
874
+ if (!Number.isInteger(timeout) || timeout < 0)
875
+ throw new TypeError('Expected the "timeout" option to be a positive integer');
876
+ if (timeout > 2147483647)
877
+ throw new RangeError('Option "timeout" cannot be greater than 2147483647');
878
+ if (verbose != null && typeof verbose !== "function")
879
+ throw new TypeError('Expected the "verbose" option to be a function');
880
+ if (nativeBinding != null && typeof nativeBinding !== "string" && typeof nativeBinding !== "object")
881
+ throw new TypeError('Expected the "nativeBinding" option to be a string or addon object');
882
+ let addon;
883
+ if (nativeBinding == null) {
884
+ addon = DEFAULT_ADDON || (DEFAULT_ADDON = require_bindings()("better_sqlite3.node"));
885
+ } else if (typeof nativeBinding === "string") {
886
+ const requireFunc = typeof __non_webpack_require__ === "function" ? __non_webpack_require__ : require;
887
+ addon = requireFunc(path3.resolve(nativeBinding).replace(/(\.node)?$/, ".node"));
1509
888
  } else {
1510
- doRun();
889
+ addon = nativeBinding;
1511
890
  }
891
+ if (!addon.isInitialized) {
892
+ addon.setErrorConstructor(SqliteError);
893
+ addon.isInitialized = true;
894
+ }
895
+ if (!anonymous && !filename.startsWith("file:") && !fs3.existsSync(path3.dirname(filename))) {
896
+ throw new TypeError("Cannot open database because the directory does not exist");
897
+ }
898
+ Object.defineProperties(this, {
899
+ [util.cppdb]: { value: new addon.Database(filename, filenameGiven, anonymous, readonly, fileMustExist, timeout, verbose || null, buffer || null) },
900
+ ...wrappers.getters
901
+ });
1512
902
  }
1513
- var wasmExports;
1514
- wasmExports = createWasm();
1515
- run();
903
+ var wrappers = require_wrappers();
904
+ Database2.prototype.prepare = wrappers.prepare;
905
+ Database2.prototype.transaction = require_transaction();
906
+ Database2.prototype.pragma = require_pragma();
907
+ Database2.prototype.backup = require_backup();
908
+ Database2.prototype.serialize = require_serialize();
909
+ Database2.prototype.function = require_function();
910
+ Database2.prototype.aggregate = require_aggregate();
911
+ Database2.prototype.table = require_table();
912
+ Database2.prototype.loadExtension = wrappers.loadExtension;
913
+ Database2.prototype.exec = wrappers.exec;
914
+ Database2.prototype.close = wrappers.close;
915
+ Database2.prototype.defaultSafeIntegers = wrappers.defaultSafeIntegers;
916
+ Database2.prototype.unsafeMode = wrappers.unsafeMode;
917
+ Database2.prototype[util.inspect] = require_inspect();
918
+ module2.exports = Database2;
919
+ }
920
+ });
921
+
922
+ // node_modules/better-sqlite3/lib/index.js
923
+ var require_lib = __commonJS({
924
+ "node_modules/better-sqlite3/lib/index.js"(exports2, module2) {
925
+ "use strict";
926
+ module2.exports = require_database();
927
+ module2.exports.SqliteError = require_sqlite_error();
1516
928
  }
1517
929
  });
1518
930
 
@@ -4054,10 +3466,18 @@ var require_extract_zip = __commonJS({
4054
3466
  }
4055
3467
  });
4056
3468
 
3469
+ // src/installer/stable-node.ts
3470
+ var init_stable_node = __esm({
3471
+ "src/installer/stable-node.ts"() {
3472
+ "use strict";
3473
+ }
3474
+ });
3475
+
4057
3476
  // src/installer/settings-merge.ts
4058
3477
  var init_settings_merge = __esm({
4059
3478
  "src/installer/settings-merge.ts"() {
4060
3479
  "use strict";
3480
+ init_stable_node();
4061
3481
  }
4062
3482
  });
4063
3483
 
@@ -4101,15 +3521,21 @@ var init_config = __esm({
4101
3521
  // src/recall/embedder.ts
4102
3522
  var embedder_exports = {};
4103
3523
  __export(embedder_exports, {
3524
+ LLAMA_RELEASE_TAG: () => LLAMA_RELEASE_TAG,
3525
+ MACOS_MIN_VERSION: () => MACOS_MIN_VERSION,
3526
+ buildUnzipInvocations: () => buildUnzipInvocations,
4104
3527
  disposeEmbedder: () => disposeEmbedder,
4105
3528
  embed: () => embed,
4106
3529
  embedBatch: () => embedBatch,
4107
3530
  ensureBinary: () => ensureBinary,
4108
3531
  ensureModel: () => ensureModel,
3532
+ extractArchive: () => extractArchive,
4109
3533
  getBinaryPath: () => getBinaryPath,
4110
3534
  getModelPath: () => getModelPath,
4111
3535
  hasNvidiaGpu: () => hasNvidiaGpu,
4112
- initEmbedder: () => initEmbedder
3536
+ initEmbedder: () => initEmbedder,
3537
+ installExtractedBinaries: () => installExtractedBinaries,
3538
+ withTimeout: () => withTimeout
4113
3539
  });
4114
3540
  function gpuRuntime() {
4115
3541
  if (_gpuRuntime === void 0) {
@@ -4283,6 +3709,82 @@ async function performBinaryDownload(binPath) {
4283
3709
  }
4284
3710
  throw new Error("No suitable llama-embedding binary found");
4285
3711
  }
3712
+ function withTimeout(promise, ms, label) {
3713
+ let timer;
3714
+ const timeout = new Promise((_, reject) => {
3715
+ timer = setTimeout(
3716
+ () => reject(new Error(`${label} timed out after ${Math.round(ms / 1e3)}s`)),
3717
+ ms
3718
+ );
3719
+ });
3720
+ promise.catch(() => {
3721
+ });
3722
+ return Promise.race([promise, timeout]).finally(() => {
3723
+ if (timer)
3724
+ clearTimeout(timer);
3725
+ });
3726
+ }
3727
+ function psQuote(p) {
3728
+ return p.replace(/'/g, "''");
3729
+ }
3730
+ function buildUnzipInvocations(plat, archivePath, dir) {
3731
+ if (plat === "win32") {
3732
+ return [{
3733
+ cmd: "powershell",
3734
+ args: [
3735
+ "-NoProfile",
3736
+ "-NonInteractive",
3737
+ "-Command",
3738
+ `Expand-Archive -LiteralPath '${psQuote(archivePath)}' -DestinationPath '${psQuote(dir)}' -Force`
3739
+ ]
3740
+ }];
3741
+ }
3742
+ const unzip = { cmd: "unzip", args: ["-o", "-q", archivePath, "-d", dir] };
3743
+ return plat === "darwin" ? [unzip, { cmd: "ditto", args: ["-x", "-k", archivePath, dir] }] : [unzip];
3744
+ }
3745
+ async function osUnzip(archivePath, dir) {
3746
+ (0, import_node_fs4.mkdirSync)(dir, { recursive: true });
3747
+ const invocations = buildUnzipInvocations((0, import_node_os2.platform)(), archivePath, dir);
3748
+ let lastErr;
3749
+ for (const { cmd, args } of invocations) {
3750
+ try {
3751
+ await execFileAsync(cmd, args, { timeout: EXTRACT_TIMEOUT_MS, windowsHide: true });
3752
+ return;
3753
+ } catch (err) {
3754
+ lastErr = err;
3755
+ }
3756
+ }
3757
+ throw lastErr instanceof Error ? lastErr : new Error(`Native unzip failed for ${archivePath}`);
3758
+ }
3759
+ async function extractArchive(archivePath, baseDir, assetName, timeoutMs = EXTRACT_TIMEOUT_MS) {
3760
+ try {
3761
+ await withTimeout((0, import_extract_zip.default)(archivePath, { dir: baseDir }), timeoutMs, `Extracting ${assetName}`);
3762
+ return baseDir;
3763
+ } catch (err) {
3764
+ const msg = err instanceof Error ? err.message : String(err);
3765
+ log({
3766
+ source: "recall-catchup",
3767
+ level: "warn",
3768
+ summary: `Bundled unzip failed for ${assetName} (${msg}); falling back to system unzip`
3769
+ });
3770
+ const fallbackDir = (0, import_node_path4.join)(baseDir, "__os_unzip__");
3771
+ await osUnzip(archivePath, fallbackDir);
3772
+ return fallbackDir;
3773
+ }
3774
+ }
3775
+ async function installExtractedBinaries(extractedDir, destDir = binDir()) {
3776
+ const buildBinDir = (0, import_node_path4.join)(extractedDir, "build", "bin");
3777
+ const sourceDir = (0, import_node_fs4.existsSync)(buildBinDir) ? buildBinDir : extractedDir;
3778
+ (0, import_node_fs4.mkdirSync)(destDir, { recursive: true });
3779
+ let copiedCount = 0;
3780
+ for (const file of await (0, import_promises.readdir)(sourceDir)) {
3781
+ if (!isWantedFile(file))
3782
+ continue;
3783
+ await (0, import_promises.cp)((0, import_node_path4.join)(sourceDir, file), (0, import_node_path4.join)(destDir, file), { force: true });
3784
+ copiedCount++;
3785
+ }
3786
+ return copiedCount;
3787
+ }
4286
3788
  async function downloadAndExtract(assetName, binPath) {
4287
3789
  const url = `https://github.com/ggml-org/llama.cpp/releases/download/${LLAMA_RELEASE_TAG}/${assetName}`;
4288
3790
  const isGpu = assetName.includes("cuda") || assetName.includes("vulkan");
@@ -4303,18 +3805,8 @@ async function downloadAndExtract(assetName, binPath) {
4303
3805
  const tmpExtractDir = (0, import_node_path4.join)((0, import_node_os2.tmpdir)(), `llama-extract-${Date.now()}`);
4304
3806
  (0, import_node_fs4.mkdirSync)(tmpExtractDir, { recursive: true });
4305
3807
  try {
4306
- await (0, import_extract_zip.default)(archivePath, { dir: tmpExtractDir });
4307
- const buildBinDir = (0, import_node_path4.join)(tmpExtractDir, "build", "bin");
4308
- const sourceDir = (0, import_node_fs4.existsSync)(buildBinDir) ? buildBinDir : tmpExtractDir;
4309
- let copiedCount = 0;
4310
- for (const file of await (0, import_promises.readdir)(sourceDir)) {
4311
- if (!isWantedFile(file))
4312
- continue;
4313
- const src = (0, import_node_path4.join)(sourceDir, file);
4314
- const dest = (0, import_node_path4.join)(binDir(), file);
4315
- await (0, import_promises.cp)(src, dest, { force: true });
4316
- copiedCount++;
4317
- }
3808
+ const extractedDir = await extractArchive(archivePath, tmpExtractDir, assetName);
3809
+ const copiedCount = await installExtractedBinaries(extractedDir);
4318
3810
  if (copiedCount === 0) {
4319
3811
  throw new Error(`No binaries found in archive ${assetName}`);
4320
3812
  }
@@ -4469,7 +3961,7 @@ async function downloadFile(url, destPath) {
4469
3961
  });
4470
3962
  });
4471
3963
  }
4472
- function isProcessAlive2(pid) {
3964
+ function isProcessAlive(pid) {
4473
3965
  try {
4474
3966
  process.kill(pid, 0);
4475
3967
  return true;
@@ -4509,8 +4001,8 @@ function cleanupStalePidFiles() {
4509
4001
  try {
4510
4002
  const data = JSON.parse((0, import_node_fs4.readFileSync)(pidFile, "utf-8"));
4511
4003
  const ownerPid = data.ownerPid ?? data.pid;
4512
- if (!isProcessAlive2(ownerPid)) {
4513
- if (data.pid && isProcessAlive2(data.pid)) {
4004
+ if (!isProcessAlive(ownerPid)) {
4005
+ if (data.pid && isProcessAlive(data.pid)) {
4514
4006
  try {
4515
4007
  process.kill(data.pid, "SIGTERM");
4516
4008
  } catch {
@@ -4938,7 +4430,7 @@ async function embedBatchInner(texts) {
4938
4430
  async function disposeEmbedder() {
4939
4431
  await killServer();
4940
4432
  }
4941
- var import_node_child_process, import_node_fs4, import_promises, import_node_http, import_node_path4, import_node_os2, import_node_util, import_extract_zip, execFileAsync, _gpuRuntime, MODEL_FILENAME, MODEL_URL, EXPECTED_DIMS, BATCH_SEPARATOR, MAX_ARG_BYTES, LLAMA_RELEASE_TAG, BIN_NAME, SERVER_BIN_NAME, SERVER_SUPPORTED, SERVER_THRESHOLD, IDLE_TIMEOUT_MS, HEALTH_POLL_INTERVAL_MS, HEALTH_POLL_TIMEOUT_MS, HTTP_REQUEST_TIMEOUT_MS, SERVER_KILL_TIMEOUT_MS, SERVER_COOLDOWN_MS, embedQueue, embedRunning, binaryPath, downloadPromise, binaryDownloadPromise, serverProcess, activeSocketPath, idleTimer, serverStartPromise, serverCooldownUntil, serverRetryPromise, activeServerRequests, WANTED_FILES, WANTED_LIB_PATTERNS;
4433
+ var import_node_child_process, import_node_fs4, import_promises, import_node_http, import_node_path4, import_node_os2, import_node_util, import_extract_zip, execFileAsync, _gpuRuntime, MODEL_FILENAME, MODEL_URL, EXPECTED_DIMS, BATCH_SEPARATOR, MAX_ARG_BYTES, LLAMA_RELEASE_TAG, MACOS_MIN_VERSION, BIN_NAME, SERVER_BIN_NAME, SERVER_SUPPORTED, SERVER_THRESHOLD, IDLE_TIMEOUT_MS, HEALTH_POLL_INTERVAL_MS, HEALTH_POLL_TIMEOUT_MS, HTTP_REQUEST_TIMEOUT_MS, SERVER_KILL_TIMEOUT_MS, SERVER_COOLDOWN_MS, EXTRACT_TIMEOUT_MS, embedQueue, embedRunning, binaryPath, downloadPromise, binaryDownloadPromise, serverProcess, activeSocketPath, idleTimer, serverStartPromise, serverCooldownUntil, serverRetryPromise, activeServerRequests, WANTED_FILES, WANTED_LIB_PATTERNS;
4942
4434
  var init_embedder = __esm({
4943
4435
  "src/recall/embedder.ts"() {
4944
4436
  "use strict";
@@ -4960,6 +4452,7 @@ var init_embedder = __esm({
4960
4452
  BATCH_SEPARATOR = "<#sep#>";
4961
4453
  MAX_ARG_BYTES = (0, import_node_os2.platform)() === "win32" ? 0 : 1e5;
4962
4454
  LLAMA_RELEASE_TAG = "b5300";
4455
+ MACOS_MIN_VERSION = { arm64: "14.0", x64: "13.7" };
4963
4456
  BIN_NAME = (0, import_node_os2.platform)() === "win32" ? "llama-embedding.exe" : "llama-embedding";
4964
4457
  SERVER_BIN_NAME = (0, import_node_os2.platform)() === "win32" ? "llama-server.exe" : "llama-server";
4965
4458
  SERVER_SUPPORTED = (0, import_node_os2.platform)() !== "win32";
@@ -4970,6 +4463,7 @@ var init_embedder = __esm({
4970
4463
  HTTP_REQUEST_TIMEOUT_MS = 12e4;
4971
4464
  SERVER_KILL_TIMEOUT_MS = 5e3;
4972
4465
  SERVER_COOLDOWN_MS = 6e4;
4466
+ EXTRACT_TIMEOUT_MS = 12e4;
4973
4467
  embedQueue = [];
4974
4468
  embedRunning = false;
4975
4469
  binaryPath = null;
@@ -5261,8 +4755,36 @@ function stripToolContent(entries) {
5261
4755
  // src/db.ts
5262
4756
  var import_node_fs2 = require("node:fs");
5263
4757
  var import_node_path2 = require("node:path");
4758
+ var import_node_module = require("node:module");
5264
4759
  init_log();
5265
- var import_node_sqlite3_wasm = __toESM(require_node_sqlite3_wasm());
4760
+ init_paths();
4761
+ var import_better_sqlite3 = __toESM(require_lib());
4762
+ var BindingLoadError = class extends Error {
4763
+ constructor(dbPath2, cause) {
4764
+ super(
4765
+ `recall: failed to load the better-sqlite3 native binding while opening ${dbPath2}: ${cause.message}
4766
+ The native SQLite binding is ABI-locked to the Node it was built for. This is usually one of:
4767
+ \u2022 recall is running under a different Node than the one npm installed it with (e.g. Homebrew node vs nvm) \u2014 reinstall with \`npm install -g crispy-recall\` using the node on your PATH, then \`recall install\`.
4768
+ \u2022 no prebuilt binary matched your Node version and it could not compile \u2014 use Node 22 LTS or 24+ (Node 23 has no prebuilt SQLite binding), and on macOS make sure Xcode Command Line Tools are installed (\`xcode-select --install\`).
4769
+ Run \`recall doctor\` for details.`
4770
+ );
4771
+ this.dbPath = dbPath2;
4772
+ this.cause = cause;
4773
+ this.name = "BindingLoadError";
4774
+ }
4775
+ };
4776
+ function isBindingLoadError(e) {
4777
+ if (!e || typeof e !== "object")
4778
+ return false;
4779
+ const err = e;
4780
+ const code = typeof err.code === "string" ? err.code : "";
4781
+ if (code === "ERR_DLOPEN_FAILED" || code === "MODULE_NOT_FOUND")
4782
+ return true;
4783
+ const msg = typeof err.message === "string" ? err.message : "";
4784
+ return /NODE_MODULE_VERSION|different Node\.?js version|dlopen|invalid ELF|not a valid Win32 application|better_sqlite3\.node|Could not locate the bindings|was compiled against/i.test(
4785
+ msg
4786
+ );
4787
+ }
5266
4788
  var db = null;
5267
4789
  var currentDbPath = null;
5268
4790
  function getDb(dbPath2) {
@@ -5272,15 +4794,16 @@ function getDb(dbPath2) {
5272
4794
  closeDb();
5273
4795
  }
5274
4796
  (0, import_node_fs2.mkdirSync)((0, import_node_path2.dirname)(dbPath2), { recursive: true });
5275
- clearStaleLock(dbPath2);
5276
- writeOwnerFile(dbPath2);
5277
- db = new import_node_sqlite3_wasm.Database(dbPath2);
4797
+ cleanupWasmArtifacts(dbPath2);
4798
+ const raw = openDatabase(dbPath2);
4799
+ try {
4800
+ configurePragmas(raw, dbPath2);
4801
+ } catch (e) {
4802
+ raw.close();
4803
+ throw e;
4804
+ }
4805
+ db = createAdapter(raw);
5278
4806
  currentDbPath = dbPath2;
5279
- db.exec("PRAGMA busy_timeout = 5000");
5280
- db.exec("PRAGMA journal_mode = WAL");
5281
- db.exec("PRAGMA synchronous = NORMAL");
5282
- db.exec("PRAGMA wal_autocheckpoint = 1000");
5283
- db.exec("PRAGMA foreign_keys = ON");
5284
4807
  ensureSchema(db);
5285
4808
  log({ source: "db", level: "info", summary: `DB: initialized at ${dbPath2}` });
5286
4809
  return db;
@@ -5288,84 +4811,111 @@ function getDb(dbPath2) {
5288
4811
  function closeDb() {
5289
4812
  if (db) {
5290
4813
  db.close();
5291
- if (currentDbPath)
5292
- removeOwnerFile(currentDbPath);
5293
4814
  db = null;
5294
4815
  currentDbPath = null;
5295
4816
  }
5296
4817
  }
5297
- function ownerFilePath(dbPath2) {
5298
- return `${dbPath2}.owner`;
5299
- }
5300
- function processStartToken(pid) {
5301
- if (process.platform !== "linux")
5302
- return "";
4818
+ function openDatabase(dbPath2) {
4819
+ const nativeBinding = resolveNativeBinding();
5303
4820
  try {
5304
- const stat = (0, import_node_fs2.readFileSync)(`/proc/${pid}/stat`, "utf-8");
5305
- const close = stat.lastIndexOf(")");
5306
- if (close === -1)
5307
- return "";
5308
- const rest = stat.slice(close + 2).trim().split(/\s+/);
5309
- const starttime = rest[19];
5310
- return starttime ?? "";
5311
- } catch {
5312
- return "";
4821
+ return nativeBinding ? new import_better_sqlite3.default(dbPath2, { nativeBinding }) : new import_better_sqlite3.default(dbPath2);
4822
+ } catch (e) {
4823
+ if (isBindingLoadError(e))
4824
+ throw new BindingLoadError(dbPath2, e);
4825
+ throw e;
5313
4826
  }
5314
4827
  }
5315
- function writeOwnerFile(dbPath2) {
5316
- try {
5317
- const token = processStartToken(process.pid);
5318
- (0, import_node_fs2.writeFileSync)(ownerFilePath(dbPath2), `${process.pid}:${token}`, "utf-8");
5319
- } catch {
5320
- }
4828
+ function resolveNativeBinding() {
4829
+ const sibling = (0, import_node_path2.join)(__dirname, "better_sqlite3.node");
4830
+ if ((0, import_node_fs2.existsSync)(sibling))
4831
+ return sibling;
4832
+ const resolved = resolveInstalledBinding();
4833
+ if (resolved)
4834
+ return resolved;
4835
+ const staged = (0, import_node_path2.join)(binDir(), "better_sqlite3.node");
4836
+ if ((0, import_node_fs2.existsSync)(staged))
4837
+ return staged;
4838
+ return null;
5321
4839
  }
5322
- function removeOwnerFile(dbPath2) {
4840
+ function resolveInstalledBinding() {
5323
4841
  try {
5324
- (0, import_node_fs2.unlinkSync)(ownerFilePath(dbPath2));
4842
+ const pkgJson = (0, import_node_module.createRequire)(__filename).resolve("better-sqlite3/package.json");
4843
+ return findNativeBinding((0, import_node_path2.dirname)(pkgJson));
5325
4844
  } catch {
4845
+ return null;
5326
4846
  }
5327
4847
  }
5328
- function isProcessAlive(pid) {
5329
- try {
5330
- process.kill(pid, 0);
5331
- return true;
5332
- } catch {
5333
- return false;
4848
+ function findNativeBinding(baseDir) {
4849
+ for (const c of [
4850
+ (0, import_node_path2.join)(baseDir, "build", "Release", "better_sqlite3.node"),
4851
+ (0, import_node_path2.join)(baseDir, "build", "Debug", "better_sqlite3.node")
4852
+ ]) {
4853
+ try {
4854
+ if ((0, import_node_fs2.statSync)(c).isFile())
4855
+ return c;
4856
+ } catch {
4857
+ }
5334
4858
  }
5335
- }
5336
- function clearStaleLock(dbPath2) {
5337
- const lockDir = `${dbPath2}.lock`;
5338
- if (!(0, import_node_fs2.existsSync)(lockDir))
5339
- return;
5340
- const ownerFile = ownerFilePath(dbPath2);
5341
- if ((0, import_node_fs2.existsSync)(ownerFile)) {
4859
+ const stack = [baseDir];
4860
+ while (stack.length) {
4861
+ const dir = stack.pop();
4862
+ let entries;
5342
4863
  try {
5343
- const raw = (0, import_node_fs2.readFileSync)(ownerFile, "utf-8").trim();
5344
- const sep2 = raw.indexOf(":");
5345
- const pidStr = sep2 === -1 ? raw : raw.slice(0, sep2);
5346
- const storedToken = sep2 === -1 ? "" : raw.slice(sep2 + 1);
5347
- const pid = parseInt(pidStr, 10);
5348
- if (!isNaN(pid) && isProcessAlive(pid)) {
5349
- if (storedToken === "" || storedToken === processStartToken(pid)) {
5350
- return;
5351
- }
5352
- }
4864
+ entries = (0, import_node_fs2.readdirSync)(dir, { withFileTypes: true });
5353
4865
  } catch {
4866
+ continue;
5354
4867
  }
4868
+ for (const e of entries) {
4869
+ const p = (0, import_node_path2.join)(dir, e.name);
4870
+ if (e.isDirectory())
4871
+ stack.push(p);
4872
+ else if (e.name.endsWith(".node"))
4873
+ return p;
4874
+ }
4875
+ }
4876
+ return null;
4877
+ }
4878
+ function createAdapter(raw) {
4879
+ return {
4880
+ all: (sql, params) => raw.prepare(sql).all(...params ?? []),
4881
+ get: (sql, params) => raw.prepare(sql).get(...params ?? []),
4882
+ run: (sql, params) => raw.prepare(sql).run(...params ?? []),
4883
+ exec: (sql) => {
4884
+ raw.exec(sql);
4885
+ },
4886
+ prepare: (sql) => {
4887
+ const st = raw.prepare(sql);
4888
+ return {
4889
+ run: (p) => st.run(...p ?? []),
4890
+ all: (p) => st.all(...p ?? []),
4891
+ get: (p) => st.get(...p ?? [])
4892
+ };
4893
+ },
4894
+ close: () => raw.close()
4895
+ };
4896
+ }
4897
+ function configurePragmas(raw, dbPath2) {
4898
+ const isMemory = dbPath2 === ":memory:" || dbPath2.includes(":memory:") || dbPath2.startsWith("file::memory:");
4899
+ raw.pragma("busy_timeout = 5000");
4900
+ const mode = raw.pragma("journal_mode = WAL", { simple: true });
4901
+ if (!isMemory && mode !== "wal") {
4902
+ throw new Error(
4903
+ `recall: expected WAL journal_mode, got '${String(mode)}' \u2014 refusing to run on a non-WAL DB (${dbPath2}). A native build on a delete-mode DB is drift; run \`recall doctor\`.`
4904
+ );
4905
+ }
4906
+ raw.pragma("synchronous = NORMAL");
4907
+ raw.pragma("wal_autocheckpoint = 1000");
4908
+ raw.pragma("foreign_keys = ON");
4909
+ }
4910
+ function cleanupWasmArtifacts(dbPath2) {
4911
+ try {
4912
+ (0, import_node_fs2.rmSync)(`${dbPath2}.lock`, { recursive: true, force: true });
4913
+ } catch {
5355
4914
  }
5356
4915
  try {
5357
- (0, import_node_fs2.rmSync)(lockDir, { recursive: true, force: true });
5358
- log({
5359
- source: "db",
5360
- level: "warn",
5361
- summary: `DB: removed stale lock directory (${lockDir}) \u2014 owning process is dead`
5362
- });
5363
- } catch (err) {
5364
- log({
5365
- source: "db",
5366
- level: "error",
5367
- summary: `DB: failed to remove stale lock directory: ${err}`
5368
- });
4916
+ if ((0, import_node_fs2.existsSync)(`${dbPath2}.owner`))
4917
+ (0, import_node_fs2.unlinkSync)(`${dbPath2}.owner`);
4918
+ } catch {
5369
4919
  }
5370
4920
  }
5371
4921
  function ensureSchema(db3) {
@@ -5383,6 +4933,12 @@ function ensureSchema(db3) {
5383
4933
 
5384
4934
  CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id, created_at);
5385
4935
  CREATE INDEX IF NOT EXISTS idx_messages_project ON messages(project_id);
4936
+ -- getUnembeddedMessages() orders the whole table by created_at DESC (LIMIT N).
4937
+ -- Without a standalone created_at index SQLite full-scans messages and builds
4938
+ -- a TEMP B-TREE to sort on every call \u2014 a ~4s/batch cost that dominates the
4939
+ -- embed drain and every Stop-hook catch-up. This index serves the ORDER BY so
4940
+ -- the planner walks it and early-terminates at LIMIT instead.
4941
+ CREATE INDEX IF NOT EXISTS idx_messages_created_at ON messages(created_at);
5386
4942
  `);
5387
4943
  db3.exec(`
5388
4944
  CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(
@@ -5423,9 +4979,19 @@ function ensureSchema(db3) {
5423
4979
  message_id TEXT PRIMARY KEY REFERENCES messages(message_id) ON DELETE CASCADE,
5424
4980
  embedding_q8 BLOB NOT NULL,
5425
4981
  norm REAL NOT NULL,
5426
- quant_scale REAL NOT NULL
4982
+ quant_scale REAL NOT NULL,
4983
+ embed_version INTEGER NOT NULL DEFAULT 1
5427
4984
  );
5428
4985
  `);
4986
+ const hasEmbedVersion = () => db3.all(`PRAGMA table_info(message_vectors)`).some((c) => c.name === "embed_version");
4987
+ if (!hasEmbedVersion()) {
4988
+ try {
4989
+ db3.exec(`ALTER TABLE message_vectors ADD COLUMN embed_version INTEGER NOT NULL DEFAULT 1`);
4990
+ } catch (e) {
4991
+ if (!hasEmbedVersion())
4992
+ throw e;
4993
+ }
4994
+ }
5429
4995
  db3.exec(`
5430
4996
  CREATE TABLE IF NOT EXISTS ingest_watermark (
5431
4997
  transcript_path TEXT PRIMARY KEY,
@@ -5446,6 +5012,20 @@ init_log();
5446
5012
 
5447
5013
  // src/recall/message-store.ts
5448
5014
  init_quantize();
5015
+
5016
+ // src/recall/embed-config.ts
5017
+ var DOC_PREFIX = "search_document: ";
5018
+ var EMBED_VERSION = 3;
5019
+ var ENRICH_MAX_CHARS = 200;
5020
+ var ENRICH_PREV_CHARS = 512;
5021
+ var ENRICH_SEP = "\n";
5022
+ function buildEmbedText(messageText, prevText) {
5023
+ if (messageText.length >= ENRICH_MAX_CHARS || !prevText)
5024
+ return messageText;
5025
+ return prevText.slice(-ENRICH_PREV_CHARS) + ENRICH_SEP + messageText;
5026
+ }
5027
+
5028
+ // src/recall/message-store.ts
5449
5029
  var dirEnsured = false;
5450
5030
  function db2() {
5451
5031
  return getDb(dbPath());
@@ -5461,7 +5041,7 @@ function insertMessages(messages, opts) {
5461
5041
  return;
5462
5042
  ensureDir2();
5463
5043
  const d = db2();
5464
- d.exec("BEGIN");
5044
+ d.exec("BEGIN IMMEDIATE");
5465
5045
  try {
5466
5046
  if (opts?.replaceSessionId) {
5467
5047
  d.run(
@@ -5476,20 +5056,16 @@ function insertMessages(messages, opts) {
5476
5056
  (message_id, session_id, message_seq, message_text, project_id, created_at, message_role)
5477
5057
  VALUES (?, ?, ?, ?, ?, ?, ?)`
5478
5058
  );
5479
- try {
5480
- for (const m of messages) {
5481
- stmt.run([
5482
- m.message_id,
5483
- m.session_id,
5484
- m.message_seq,
5485
- m.message_text,
5486
- m.project_id,
5487
- m.created_at,
5488
- m.message_role
5489
- ]);
5490
- }
5491
- } finally {
5492
- stmt.finalize();
5059
+ for (const m of messages) {
5060
+ stmt.run([
5061
+ m.message_id,
5062
+ m.session_id,
5063
+ m.message_seq,
5064
+ m.message_text,
5065
+ m.project_id,
5066
+ m.created_at,
5067
+ m.message_role
5068
+ ]);
5493
5069
  }
5494
5070
  d.exec("COMMIT");
5495
5071
  } catch (e) {
@@ -5502,24 +5078,21 @@ function insertMessageVectors(records) {
5502
5078
  return;
5503
5079
  ensureDir2();
5504
5080
  const d = db2();
5505
- d.exec("BEGIN");
5081
+ d.exec("BEGIN IMMEDIATE");
5506
5082
  try {
5507
5083
  const stmt = d.prepare(
5508
5084
  `INSERT OR REPLACE INTO message_vectors
5509
- (message_id, embedding_q8, norm, quant_scale)
5510
- VALUES (?, ?, ?, ?)`
5085
+ (message_id, embedding_q8, norm, quant_scale, embed_version)
5086
+ VALUES (?, ?, ?, ?, ?)`
5511
5087
  );
5512
- try {
5513
- for (const r of records) {
5514
- stmt.run([
5515
- r.messageId,
5516
- Buffer.from(r.embeddingQ8.buffer, r.embeddingQ8.byteOffset, r.embeddingQ8.byteLength),
5517
- r.norm,
5518
- r.quantScale
5519
- ]);
5520
- }
5521
- } finally {
5522
- stmt.finalize();
5088
+ for (const r of records) {
5089
+ stmt.run([
5090
+ r.messageId,
5091
+ Buffer.from(r.embeddingQ8.buffer, r.embeddingQ8.byteOffset, r.embeddingQ8.byteLength),
5092
+ r.norm,
5093
+ r.quantScale,
5094
+ EMBED_VERSION
5095
+ ]);
5523
5096
  }
5524
5097
  d.exec("COMMIT");
5525
5098
  } catch (e) {
@@ -5531,19 +5104,29 @@ var MIN_EMBED_CHARS = 50;
5531
5104
  function getUnembeddedMessages(limit) {
5532
5105
  try {
5533
5106
  const rows = db2().all(
5534
- `SELECT m.message_id, m.session_id, m.message_text FROM messages m
5107
+ `SELECT m.message_id, m.session_id, m.message_text,
5108
+ (SELECT p.message_text FROM messages p
5109
+ WHERE p.session_id = m.session_id AND p.message_seq < m.message_seq
5110
+ ORDER BY p.message_seq DESC LIMIT 1) AS prev_text
5111
+ FROM messages m
5535
5112
  WHERE m.message_text != ''
5536
- AND LENGTH(m.message_text) >= ${MIN_EMBED_CHARS}
5537
- AND NOT EXISTS (SELECT 1 FROM message_vectors mv WHERE mv.message_id = m.message_id)
5113
+ AND (LENGTH(m.message_text) >= ${MIN_EMBED_CHARS}
5114
+ OR EXISTS (SELECT 1 FROM messages p2 WHERE p2.session_id = m.session_id AND p2.message_seq < m.message_seq))
5115
+ AND NOT EXISTS (SELECT 1 FROM message_vectors mv WHERE mv.message_id = m.message_id AND mv.embed_version = ?)
5538
5116
  ORDER BY m.created_at DESC
5539
5117
  LIMIT ?`,
5540
- [limit]
5118
+ [EMBED_VERSION, limit]
5541
5119
  );
5542
- return rows.map((r) => ({
5543
- message_id: r.message_id,
5544
- session_id: r.session_id,
5545
- message_text: r.message_text
5546
- }));
5120
+ return rows.map((r) => {
5121
+ const message_text = r.message_text;
5122
+ const prev_text = r.prev_text ?? null;
5123
+ return {
5124
+ message_id: r.message_id,
5125
+ session_id: r.session_id,
5126
+ message_text,
5127
+ embed_text: buildEmbedText(message_text, prev_text)
5128
+ };
5129
+ });
5547
5130
  } catch {
5548
5131
  return [];
5549
5132
  }
@@ -6495,6 +6078,7 @@ var SAFE_EMBED_CHARS = 6e3;
6495
6078
  async function embedRowsResilient(rows) {
6496
6079
  const { embedBatch: embedBatch2 } = await Promise.resolve().then(() => (init_embedder(), embedder_exports));
6497
6080
  const { quantizeToQ8: quantizeToQ82, computeNorm: computeNorm2 } = await Promise.resolve().then(() => (init_quantize(), quantize_exports));
6081
+ rows = rows.map((r) => ({ messageId: r.messageId, text: DOC_PREFIX + r.text }));
6498
6082
  const toRecord = (messageId, f32) => {
6499
6083
  const { q8, scale } = quantizeToQ82(f32);
6500
6084
  return { messageId, embeddingQ8: q8, norm: computeNorm2(f32), quantScale: scale };
@@ -6527,20 +6111,30 @@ async function embedRowsResilient(rows) {
6527
6111
  async function embedSessionMessages(sessionId, force) {
6528
6112
  const d = getDb(dbPath());
6529
6113
  const rows = d.all(
6530
- force ? `SELECT message_id, message_text FROM messages WHERE session_id = ? ORDER BY message_seq ASC` : `SELECT m.message_id, m.message_text FROM messages m
6114
+ force ? `SELECT m.message_id, m.message_text,
6115
+ (SELECT p.message_text FROM messages p
6116
+ WHERE p.session_id = m.session_id AND p.message_seq < m.message_seq
6117
+ ORDER BY p.message_seq DESC LIMIT 1) AS prev_text
6118
+ FROM messages m WHERE m.session_id = ? ORDER BY m.message_seq ASC` : `SELECT m.message_id, m.message_text,
6119
+ (SELECT p.message_text FROM messages p
6120
+ WHERE p.session_id = m.session_id AND p.message_seq < m.message_seq
6121
+ ORDER BY p.message_seq DESC LIMIT 1) AS prev_text
6122
+ FROM messages m
6531
6123
  WHERE m.session_id = ?
6532
- AND NOT EXISTS (SELECT 1 FROM message_vectors mv WHERE mv.message_id = m.message_id)
6124
+ AND NOT EXISTS (SELECT 1 FROM message_vectors mv WHERE mv.message_id = m.message_id AND mv.embed_version = ?)
6533
6125
  ORDER BY m.message_seq ASC`,
6534
- [sessionId]
6126
+ force ? [sessionId] : [sessionId, EMBED_VERSION]
6535
6127
  );
6536
6128
  const validRows = [];
6537
6129
  for (const r of rows) {
6538
- const text = r.message_text.trim();
6539
- if (!text)
6130
+ const messageText = r.message_text.trim();
6131
+ if (!messageText)
6540
6132
  continue;
6133
+ const prevText = r.prev_text ?? null;
6134
+ const embedText = buildEmbedText(messageText, prevText);
6541
6135
  validRows.push({
6542
6136
  messageId: r.message_id,
6543
- text: text.length > MAX_EMBED_CHARS ? text.slice(0, MAX_EMBED_CHARS) : text
6137
+ text: embedText.length > MAX_EMBED_CHARS ? embedText.slice(0, MAX_EMBED_CHARS) : embedText
6544
6138
  });
6545
6139
  }
6546
6140
  if (validRows.length === 0)
@@ -6557,7 +6151,7 @@ async function embedMessageBatch(messages) {
6557
6151
  return 0;
6558
6152
  const truncated = [];
6559
6153
  for (const m of messages) {
6560
- const text = m.message_text.trim();
6154
+ const text = (m.embed_text ?? m.message_text).trim();
6561
6155
  if (!text)
6562
6156
  continue;
6563
6157
  truncated.push({