@nojaja/sqlite-vec1-embeddinggemma2-wasm 0.0.0-stage → 0.0.1-build2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +90 -2
- package/dist/image/jpeg.wasm +0 -0
- package/dist/image/png.wasm +0 -0
- package/dist/image/resize.wasm +0 -0
- package/dist/index-browser.d.ts +3 -0
- package/dist/index-browser.mjs +16459 -0
- package/dist/index.bundle.js +2165 -0
- package/dist/index.d.mts +3 -0
- package/dist/index.d.ts +3 -0
- package/dist/node/index.js +2165 -0
- package/dist/node/index.mjs +2130 -0
- package/dist/official/types.d.ts +177 -0
- package/dist/ort/ort-wasm-simd-threaded.jsep.mjs +108 -0
- package/dist/ort/ort-wasm-simd-threaded.jsep.wasm +0 -0
- package/dist/ort/ort-wasm-simd-threaded.jspi.mjs +120 -0
- package/dist/ort/ort-wasm-simd-threaded.jspi.wasm +0 -0
- package/dist/reports/build-content.json +190 -0
- package/dist/reports/esbuild-metafile.json +2339 -0
- package/dist/reports/sbom.cdx.json +384 -0
- package/dist/runtime-lock.json +96 -0
- package/dist/samples/browser/index.mjs +48 -0
- package/dist/samples/browser/owner.mjs +16235 -0
- package/dist/samples/browser/server.js +69 -0
- package/dist/samples/node/index.js +2384 -0
- package/dist/sqlite3-bundler-friendly.mjs +21851 -0
- package/dist/sqlite3-node.mjs +16572 -0
- package/dist/sqlite3-opfs-async-proxy.js +1105 -0
- package/dist/sqlite3-worker1-bundler-friendly.mjs +35 -0
- package/dist/sqlite3-worker1-promiser.mjs +320 -0
- package/dist/sqlite3-worker1.mjs +35 -0
- package/dist/sqlite3.mjs +21940 -0
- package/dist/sqlite3.wasm +0 -0
- package/dist/vendor/transformers-directml-node.js +37007 -0
- package/dist/vendor/transformers-portable-node.js +36983 -0
- package/dist/vendor/transformers-portable.mjs +37001 -0
- package/dist/workers/db-browser.mjs +16496 -0
- package/dist/workers/inference-browser.mjs +1379 -0
- package/dist/workers/inference-node.js +7344 -0
- package/manifests/embeddinggemma2-q4.json +127 -0
- package/manifests/runtime-lock.json +96 -0
- package/package.json +143 -4
- package/samples/browser/index.ts +80 -0
- package/samples/browser/owner.ts +50 -0
- package/samples/browser/server.ts +50 -0
- package/samples/cli-demo.ts +58 -0
- package/samples/node/index.ts +144 -0
- package/samples/official-scenario.ts +117 -0
|
@@ -0,0 +1,2130 @@
|
|
|
1
|
+
// src/official/node.ts
|
|
2
|
+
import * as fs2 from "node:fs";
|
|
3
|
+
import * as path3 from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
|
|
6
|
+
// src/errors.ts
|
|
7
|
+
var VectorError = class extends Error {
|
|
8
|
+
code;
|
|
9
|
+
/**
|
|
10
|
+
* 処理名: VectorErrorコンストラクタ
|
|
11
|
+
* 処理概要: エラーコードを受け取り、nameをVectorError、messageをcodeに設定して初期化する。
|
|
12
|
+
* 実装理由: 仕様に定められたエラーコード形式(messageとcodeが同一)を厳格に保持するため。
|
|
13
|
+
* @param code - 設定するエラーコード。
|
|
14
|
+
*/
|
|
15
|
+
constructor(code) {
|
|
16
|
+
super(code);
|
|
17
|
+
this.name = "VectorError";
|
|
18
|
+
this.code = code;
|
|
19
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
// src/official/options.ts
|
|
24
|
+
function validateEmbeddingOptions(options, env) {
|
|
25
|
+
if (options === void 0) {
|
|
26
|
+
return void 0;
|
|
27
|
+
}
|
|
28
|
+
if (env.runtime === "node") {
|
|
29
|
+
if (env.platform !== "win32" && env.platform !== "linux") {
|
|
30
|
+
throw new VectorError("E_ENVIRONMENT");
|
|
31
|
+
}
|
|
32
|
+
if (env.architecture !== "x64") {
|
|
33
|
+
throw new VectorError("E_ENVIRONMENT");
|
|
34
|
+
}
|
|
35
|
+
if (env.nodeMajor !== void 0) {
|
|
36
|
+
if (env.nodeMajor % 2 !== 0 || env.nodeMajor < 20 || env.nodeMajor > 24) {
|
|
37
|
+
throw new VectorError("E_ENVIRONMENT");
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const model = options.model ?? { network: "offline" };
|
|
42
|
+
if (model.network !== "allow" && model.network !== "offline") {
|
|
43
|
+
throw new VectorError("E_INPUT");
|
|
44
|
+
}
|
|
45
|
+
const rawBackend = options.backend;
|
|
46
|
+
if (rawBackend !== void 0 && rawBackend !== "wasm" && rawBackend !== "webgpu" && rawBackend !== "directml") {
|
|
47
|
+
throw new VectorError("E_INPUT");
|
|
48
|
+
}
|
|
49
|
+
const backend = options.backend ?? "wasm";
|
|
50
|
+
if (env.runtime === "node") {
|
|
51
|
+
if (backend === "webgpu") {
|
|
52
|
+
throw new VectorError("E_ENVIRONMENT");
|
|
53
|
+
}
|
|
54
|
+
if (backend === "directml") {
|
|
55
|
+
if (env.platform !== "win32" || env.architecture !== "x64") {
|
|
56
|
+
throw new VectorError("E_ENVIRONMENT");
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
} else if (env.runtime === "browser") {
|
|
60
|
+
if (!env.worker) {
|
|
61
|
+
console.warn(
|
|
62
|
+
"SQLite synchronous embedding UDFs require Atomics.wait and cannot run on the browser main thread. Run initialize({ embedding }) inside a Dedicated Worker or use sqlite3EmbeddingWorkerPromiser()."
|
|
63
|
+
);
|
|
64
|
+
throw new VectorError("E_ENVIRONMENT");
|
|
65
|
+
}
|
|
66
|
+
if (backend === "directml") {
|
|
67
|
+
throw new VectorError("E_ENVIRONMENT");
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function validateTimeout(val, defaultVal) {
|
|
71
|
+
if (val === void 0) return defaultVal;
|
|
72
|
+
if (typeof val !== "number" || !Number.isFinite(val) || Number.isNaN(val) || val < 1 || val > 18e5) {
|
|
73
|
+
throw new VectorError("E_INPUT");
|
|
74
|
+
}
|
|
75
|
+
return val;
|
|
76
|
+
}
|
|
77
|
+
const initTimeoutMs = validateTimeout(options.initTimeoutMs, 6e5);
|
|
78
|
+
const sqlTimeoutMs = validateTimeout(options.sqlTimeoutMs, 12e4);
|
|
79
|
+
if (options.workerUrl !== void 0 && (typeof options.workerUrl !== "string" || options.workerUrl.trim().length === 0)) {
|
|
80
|
+
throw new VectorError("E_INPUT");
|
|
81
|
+
}
|
|
82
|
+
if (options.manifestUrl !== void 0 && (typeof options.manifestUrl !== "string" || options.manifestUrl.trim().length === 0)) {
|
|
83
|
+
throw new VectorError("E_INPUT");
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
model,
|
|
87
|
+
backend,
|
|
88
|
+
workerUrl: options.workerUrl,
|
|
89
|
+
manifestUrl: options.manifestUrl,
|
|
90
|
+
initTimeoutMs,
|
|
91
|
+
sqlTimeoutMs,
|
|
92
|
+
models: options.models,
|
|
93
|
+
defaultModel: options.defaultModel
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// src/official/metadata.ts
|
|
98
|
+
var OFFICIAL_METADATA_DDL = "CREATE TABLE _svw_meta(id INTEGER PRIMARY KEY CHECK(id=1), metadata TEXT NOT NULL) STRICT";
|
|
99
|
+
function officialMetadataRecord(identity) {
|
|
100
|
+
return {
|
|
101
|
+
productVersion: "0.0.3",
|
|
102
|
+
modelId: identity.modelId,
|
|
103
|
+
revision: identity.revision,
|
|
104
|
+
fingerprint: identity.fingerprint,
|
|
105
|
+
profile: identity.profile,
|
|
106
|
+
dimension: 768,
|
|
107
|
+
dtype: "q4"
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
function validateOfficialMetadata(actual, identity) {
|
|
111
|
+
if (!actual || typeof actual !== "object") {
|
|
112
|
+
throw new VectorError("E_MODEL_MISMATCH");
|
|
113
|
+
}
|
|
114
|
+
const rec = actual;
|
|
115
|
+
const keys = Object.keys(rec);
|
|
116
|
+
if (keys.length !== 7) {
|
|
117
|
+
throw new VectorError("E_MODEL_MISMATCH");
|
|
118
|
+
}
|
|
119
|
+
if (rec.productVersion !== "0.0.3" || rec.modelId !== identity.modelId || rec.revision !== identity.revision || rec.fingerprint !== identity.fingerprint || rec.profile !== identity.profile || rec.dimension !== 768 || rec.dtype !== "q4") {
|
|
120
|
+
throw new VectorError("E_MODEL_MISMATCH");
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function initializeOfficialMetadata(sqlite3, db, identity) {
|
|
124
|
+
const metaTableCount = db.selectValue("SELECT count(*) FROM sqlite_schema WHERE type='table' AND name='_svw_meta'");
|
|
125
|
+
if (metaTableCount === 0) {
|
|
126
|
+
const userTableCount = db.selectValue("SELECT count(*) FROM sqlite_schema WHERE type='table' AND name NOT LIKE 'sqlite_%'");
|
|
127
|
+
if (userTableCount > 0) {
|
|
128
|
+
throw new VectorError("E_MODEL_UNBOUND");
|
|
129
|
+
}
|
|
130
|
+
db.exec("BEGIN IMMEDIATE");
|
|
131
|
+
try {
|
|
132
|
+
db.exec(OFFICIAL_METADATA_DDL);
|
|
133
|
+
const recordJson = JSON.stringify(officialMetadataRecord(identity));
|
|
134
|
+
const stmt = db.prepare("INSERT INTO _svw_meta(id, metadata) VALUES(1, ?)");
|
|
135
|
+
try {
|
|
136
|
+
stmt.bind(1, recordJson);
|
|
137
|
+
stmt.step();
|
|
138
|
+
} finally {
|
|
139
|
+
stmt.finalize();
|
|
140
|
+
}
|
|
141
|
+
db.exec("COMMIT");
|
|
142
|
+
} catch (err) {
|
|
143
|
+
try {
|
|
144
|
+
db.exec("ROLLBACK");
|
|
145
|
+
} catch {
|
|
146
|
+
}
|
|
147
|
+
throw err;
|
|
148
|
+
}
|
|
149
|
+
} else {
|
|
150
|
+
const schemaSql = db.selectValue("SELECT sql FROM sqlite_schema WHERE type='table' AND name='_svw_meta'");
|
|
151
|
+
if (schemaSql !== OFFICIAL_METADATA_DDL) {
|
|
152
|
+
throw new VectorError("E_MODEL_MISMATCH");
|
|
153
|
+
}
|
|
154
|
+
const rowCount = db.selectValue("SELECT count(*) FROM _svw_meta");
|
|
155
|
+
if (rowCount !== 1) {
|
|
156
|
+
throw new VectorError("E_MODEL_MISMATCH");
|
|
157
|
+
}
|
|
158
|
+
const metaJson = db.selectValue("SELECT metadata FROM _svw_meta WHERE id=1");
|
|
159
|
+
if (typeof metaJson !== "string") {
|
|
160
|
+
throw new VectorError("E_MODEL_MISMATCH");
|
|
161
|
+
}
|
|
162
|
+
let parsed;
|
|
163
|
+
try {
|
|
164
|
+
parsed = JSON.parse(metaJson);
|
|
165
|
+
} catch {
|
|
166
|
+
throw new VectorError("E_MODEL_MISMATCH");
|
|
167
|
+
}
|
|
168
|
+
validateOfficialMetadata(parsed, identity);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
var OfficialMetadataProtection = class {
|
|
172
|
+
sqlite3;
|
|
173
|
+
origSetAuthorizer;
|
|
174
|
+
userAuthorizers = /* @__PURE__ */ new WeakMap();
|
|
175
|
+
isDisposed = false;
|
|
176
|
+
constructor(sqlite3) {
|
|
177
|
+
this.sqlite3 = sqlite3;
|
|
178
|
+
const capi = sqlite3.capi;
|
|
179
|
+
this.origSetAuthorizer = capi.sqlite3_set_authorizer;
|
|
180
|
+
const self = this;
|
|
181
|
+
capi.sqlite3_set_authorizer = (pDb, xAuth, pUserData) => {
|
|
182
|
+
const dbObj = pDb && typeof pDb === "object" && pDb.pointer ? pDb : null;
|
|
183
|
+
if (dbObj) {
|
|
184
|
+
self.userAuthorizers.set(dbObj, { auth: xAuth, pUser: pUserData });
|
|
185
|
+
return self.origSetAuthorizer.call(capi, dbObj.pointer, self.createCompositeAuthorizer(xAuth, pUserData), 0);
|
|
186
|
+
}
|
|
187
|
+
return self.origSetAuthorizer.call(capi, pDb, self.createCompositeAuthorizer(xAuth, pUserData), pUserData);
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
createCompositeAuthorizer(userAuth, pUser) {
|
|
191
|
+
const capi = this.sqlite3.capi;
|
|
192
|
+
return (pUserData, actionCode, p1, p2, dbName, triggerName) => {
|
|
193
|
+
const target = typeof p1 === "string" ? p1 : p1 ? this.sqlite3.wasm.cstrToJs(p1) : "";
|
|
194
|
+
if (typeof target === "string" && target.startsWith("_svw_")) {
|
|
195
|
+
if (actionCode === 23 || actionCode === 9 || actionCode === 11 || actionCode === 18 || actionCode === 26 || actionCode === capi.SQLITE_UPDATE || actionCode === capi.SQLITE_DELETE || actionCode === capi.SQLITE_DROP_TABLE || actionCode === capi.SQLITE_INSERT || actionCode === capi.SQLITE_ALTER_TABLE) {
|
|
196
|
+
return capi.SQLITE_DENY;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
if ((actionCode === 19 || actionCode === capi.SQLITE_PRAGMA) && typeof target === "string" && target.toLowerCase() === "writable_schema") {
|
|
200
|
+
return capi.SQLITE_DENY;
|
|
201
|
+
}
|
|
202
|
+
if (typeof userAuth === "function") {
|
|
203
|
+
return userAuth(pUser ?? pUserData, actionCode, p1, p2, dbName, triggerName);
|
|
204
|
+
}
|
|
205
|
+
return capi.SQLITE_OK;
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
observe(db) {
|
|
209
|
+
const pDb = db.pointer ?? db;
|
|
210
|
+
const auth = this.createCompositeAuthorizer(null, 0);
|
|
211
|
+
this.origSetAuthorizer.call(this.sqlite3.capi, pDb, auth, 0);
|
|
212
|
+
}
|
|
213
|
+
close(db) {
|
|
214
|
+
this.userAuthorizers.delete(db);
|
|
215
|
+
}
|
|
216
|
+
dispose() {
|
|
217
|
+
if (this.isDisposed) return;
|
|
218
|
+
this.isDisposed = true;
|
|
219
|
+
this.sqlite3.capi.sqlite3_set_authorizer = this.origSetAuthorizer;
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
// src/official/vector-metadata.ts
|
|
224
|
+
function calculateCosineDistance(a, b) {
|
|
225
|
+
if (a === null || b === null) {
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
if (!(a instanceof Uint8Array) || !(b instanceof Uint8Array)) {
|
|
229
|
+
throw new VectorError("E_INPUT");
|
|
230
|
+
}
|
|
231
|
+
if (a.byteLength % 4 !== 0 || b.byteLength % 4 !== 0) {
|
|
232
|
+
throw new VectorError("E_INPUT");
|
|
233
|
+
}
|
|
234
|
+
if (a.byteLength !== b.byteLength || a.byteLength === 0) {
|
|
235
|
+
throw new VectorError("E_INPUT");
|
|
236
|
+
}
|
|
237
|
+
const len = a.byteLength / 4;
|
|
238
|
+
const viewA = new DataView(a.buffer, a.byteOffset, a.byteLength);
|
|
239
|
+
const viewB = new DataView(b.buffer, b.byteOffset, b.byteLength);
|
|
240
|
+
let dot = 0;
|
|
241
|
+
let normASq = 0;
|
|
242
|
+
let normBSq = 0;
|
|
243
|
+
for (let i = 0; i < len; i++) {
|
|
244
|
+
const valA = viewA.getFloat32(i * 4, true);
|
|
245
|
+
const valB = viewB.getFloat32(i * 4, true);
|
|
246
|
+
if (!Number.isFinite(valA) || !Number.isFinite(valB) || Number.isNaN(valA) || Number.isNaN(valB)) {
|
|
247
|
+
throw new VectorError("E_INPUT");
|
|
248
|
+
}
|
|
249
|
+
dot += valA * valB;
|
|
250
|
+
normASq += valA * valA;
|
|
251
|
+
normBSq += valB * valB;
|
|
252
|
+
}
|
|
253
|
+
if (normASq <= 0 || normBSq <= 0) {
|
|
254
|
+
throw new VectorError("E_INPUT");
|
|
255
|
+
}
|
|
256
|
+
const normA = Math.sqrt(normASq);
|
|
257
|
+
const normB = Math.sqrt(normBSq);
|
|
258
|
+
let cosSim = dot / (normA * normB);
|
|
259
|
+
if (cosSim > 1) cosSim = 1;
|
|
260
|
+
if (cosSim < -1) cosSim = -1;
|
|
261
|
+
return 1 - cosSim;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// src/bridge/inference-health.ts
|
|
265
|
+
var HEALTH_READY = 1;
|
|
266
|
+
function assertInferenceReady(buffer) {
|
|
267
|
+
const view = new Int32Array(buffer, 0, 1);
|
|
268
|
+
const val = Atomics.load(view, 0);
|
|
269
|
+
if (val !== HEALTH_READY) {
|
|
270
|
+
throw new VectorError("E_INFERENCE");
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// src/inference/statement-embedding-cache.ts
|
|
275
|
+
function validateEmbeddingBlob(value) {
|
|
276
|
+
if (!(value instanceof Uint8Array) || value.byteLength !== 3072) {
|
|
277
|
+
throw new VectorError("E_EMBEDDING_VALUE");
|
|
278
|
+
}
|
|
279
|
+
const view = new DataView(value.buffer, value.byteOffset, value.byteLength);
|
|
280
|
+
let sumSquares = 0;
|
|
281
|
+
for (let i = 0; i < 768; i++) {
|
|
282
|
+
const floatVal = view.getFloat32(i * 4, true);
|
|
283
|
+
if (!Number.isFinite(floatVal)) {
|
|
284
|
+
throw new VectorError("E_EMBEDDING_VALUE");
|
|
285
|
+
}
|
|
286
|
+
sumSquares += floatVal * floatVal;
|
|
287
|
+
}
|
|
288
|
+
const norm = Math.sqrt(sumSquares);
|
|
289
|
+
if (!Number.isFinite(norm) || norm < 1e-12) {
|
|
290
|
+
throw new VectorError("E_EMBEDDING_VALUE");
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
var StatementEmbeddingCache = class {
|
|
294
|
+
identityStr;
|
|
295
|
+
capacity;
|
|
296
|
+
check;
|
|
297
|
+
entriesList = [];
|
|
298
|
+
currentBytes = 0;
|
|
299
|
+
isDisposed = false;
|
|
300
|
+
hitCount = 0;
|
|
301
|
+
missCount = 0;
|
|
302
|
+
evictionCount = 0;
|
|
303
|
+
actualInferenceCount = 0;
|
|
304
|
+
/**
|
|
305
|
+
* 処理名: StatementEmbeddingCache コンストラクタ
|
|
306
|
+
* 処理概要: アイデンティティと容量、ヘルス/デッドライン検査コールバックを初期化する。
|
|
307
|
+
* 実装理由: ステートメント実行単位で独立したキャッシュインスタンスを構築するため。
|
|
308
|
+
* @param identity - モデル・ランタイムアイデンティティ。
|
|
309
|
+
* @param capacity - 最大バイト容量 (1..33554432)。
|
|
310
|
+
* @param check - ヘルスおよび期限検査コールバック。
|
|
311
|
+
*/
|
|
312
|
+
constructor(identity, capacity = 33554432, check = () => {
|
|
313
|
+
}) {
|
|
314
|
+
if (!Number.isSafeInteger(capacity) || capacity < 1 || capacity > 33554432) {
|
|
315
|
+
throw new VectorError("E_INPUT");
|
|
316
|
+
}
|
|
317
|
+
this.identityStr = JSON.stringify([
|
|
318
|
+
identity.modelId,
|
|
319
|
+
identity.revision,
|
|
320
|
+
identity.fingerprint,
|
|
321
|
+
identity.profile,
|
|
322
|
+
identity.backend,
|
|
323
|
+
identity.runtimeGeneration
|
|
324
|
+
]);
|
|
325
|
+
this.capacity = capacity;
|
|
326
|
+
this.check = check;
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* 処理名: 画像バイト配列完全一致比較
|
|
330
|
+
* 処理概要: 2つの Uint8Array の長さと全バイトを比較する。
|
|
331
|
+
* 実装理由: 画像ハッシュ衝突のリスクを排除し全バイトで同一性を保証するため。
|
|
332
|
+
* @param a - 比較対象 A。
|
|
333
|
+
* @param b - 比較対象 B。
|
|
334
|
+
* @returns 完全一致時 true。
|
|
335
|
+
*/
|
|
336
|
+
compareBytes(a, b) {
|
|
337
|
+
if (a.byteLength !== b.byteLength) {
|
|
338
|
+
return false;
|
|
339
|
+
}
|
|
340
|
+
for (let i = 0; i < a.byteLength; i++) {
|
|
341
|
+
if (a[i] !== b[i]) {
|
|
342
|
+
return false;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return true;
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* 処理名: キャッシュ解決
|
|
349
|
+
* 処理概要: キャッシュを探索し、ヒット時は複製を返し、ミス時は推論を実行してLRUキャッシュへ追加する。
|
|
350
|
+
* 実装理由: 同一ステートメント内の重複推論を抑制し、安全にキャッシュを更新するため。
|
|
351
|
+
* @param request - 埋め込み呼び出し要求。
|
|
352
|
+
* @param infer - 推論実行コールバック。
|
|
353
|
+
* @returns 3072 バイトの独立した Float32 ベクトル BLOB、または NULL。
|
|
354
|
+
*/
|
|
355
|
+
resolve(request, infer) {
|
|
356
|
+
if (this.isDisposed) {
|
|
357
|
+
throw new VectorError("E_PROTOCOL");
|
|
358
|
+
}
|
|
359
|
+
this.check();
|
|
360
|
+
let key;
|
|
361
|
+
let entrySize;
|
|
362
|
+
let reqImageCopy;
|
|
363
|
+
const getStrBytes = (s) => typeof Buffer !== "undefined" ? Buffer.byteLength(s, "utf8") : new TextEncoder().encode(s).length;
|
|
364
|
+
if (request.operation === "image") {
|
|
365
|
+
key = JSON.stringify([this.identityStr, "image", request.mime, request.bytes.length]);
|
|
366
|
+
entrySize = getStrBytes(key) + 3072 + request.bytes.length;
|
|
367
|
+
reqImageCopy = new Uint8Array(request.bytes);
|
|
368
|
+
} else {
|
|
369
|
+
const normalizedTitle = request.title ?? "";
|
|
370
|
+
key = JSON.stringify([this.identityStr, request.operation, request.body, normalizedTitle]);
|
|
371
|
+
entrySize = getStrBytes(key) + 3072;
|
|
372
|
+
}
|
|
373
|
+
const hitIdx = this.entriesList.findIndex((e) => {
|
|
374
|
+
if (e.key !== key) return false;
|
|
375
|
+
if (request.operation === "image") {
|
|
376
|
+
return e.imageBytes && this.compareBytes(e.imageBytes, request.bytes);
|
|
377
|
+
}
|
|
378
|
+
return true;
|
|
379
|
+
});
|
|
380
|
+
if (hitIdx !== -1) {
|
|
381
|
+
this.check();
|
|
382
|
+
const [hitEntry] = this.entriesList.splice(hitIdx, 1);
|
|
383
|
+
this.entriesList.push(hitEntry);
|
|
384
|
+
this.hitCount++;
|
|
385
|
+
return new Uint8Array(hitEntry.blob);
|
|
386
|
+
}
|
|
387
|
+
this.missCount++;
|
|
388
|
+
this.actualInferenceCount++;
|
|
389
|
+
const result = infer(request);
|
|
390
|
+
if (result === null) {
|
|
391
|
+
return null;
|
|
392
|
+
}
|
|
393
|
+
validateEmbeddingBlob(result);
|
|
394
|
+
if (entrySize > this.capacity) {
|
|
395
|
+
return new Uint8Array(result);
|
|
396
|
+
}
|
|
397
|
+
while (this.entriesList.length >= 10 || this.currentBytes + entrySize > this.capacity && this.entriesList.length > 0) {
|
|
398
|
+
const evicted = this.entriesList.shift();
|
|
399
|
+
this.currentBytes -= evicted.size;
|
|
400
|
+
this.evictionCount++;
|
|
401
|
+
}
|
|
402
|
+
const blobCopy = new Uint8Array(result);
|
|
403
|
+
this.entriesList.push({
|
|
404
|
+
key,
|
|
405
|
+
operation: request.operation,
|
|
406
|
+
imageBytes: reqImageCopy,
|
|
407
|
+
blob: blobCopy,
|
|
408
|
+
size: entrySize
|
|
409
|
+
});
|
|
410
|
+
this.currentBytes += entrySize;
|
|
411
|
+
return new Uint8Array(result);
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* 処理名: キャッシュ破棄
|
|
415
|
+
* 処理概要: 全エントリと内部バッファ参照を解放し、再利用を不可にする。
|
|
416
|
+
* 実装理由: ステートメント終了時のメモリ解放および再利用拒否プロトコルを遵守するため。
|
|
417
|
+
*/
|
|
418
|
+
dispose() {
|
|
419
|
+
this.isDisposed = true;
|
|
420
|
+
this.entriesList = [];
|
|
421
|
+
this.currentBytes = 0;
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* 処理名: 統計カウンタ取得
|
|
425
|
+
* 処理概要: ヒット、ミス、追い出し、実推論、エントリ数、保持バイト数を返す。
|
|
426
|
+
* 実装理由: キャッシュ動作の検証および gemma_model_info 診断のため。
|
|
427
|
+
* @returns 統計カウンタ情報。
|
|
428
|
+
*/
|
|
429
|
+
statistics() {
|
|
430
|
+
return {
|
|
431
|
+
hit: this.hitCount,
|
|
432
|
+
miss: this.missCount,
|
|
433
|
+
eviction: this.evictionCount,
|
|
434
|
+
actualInference: this.actualInferenceCount,
|
|
435
|
+
entries: this.entriesList.length,
|
|
436
|
+
bytes: this.currentBytes
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
|
|
441
|
+
// src/sqlite/statement-lifecycle.ts
|
|
442
|
+
var StatementLifecycle = class {
|
|
443
|
+
identity;
|
|
444
|
+
timeoutMs;
|
|
445
|
+
clock;
|
|
446
|
+
health;
|
|
447
|
+
activeExecution = null;
|
|
448
|
+
stmtMap = /* @__PURE__ */ new Map();
|
|
449
|
+
dbMap = /* @__PURE__ */ new Map();
|
|
450
|
+
generationSeq = 0;
|
|
451
|
+
accumulatedHit = 0;
|
|
452
|
+
accumulatedMiss = 0;
|
|
453
|
+
accumulatedEviction = 0;
|
|
454
|
+
accumulatedActualInference = 0;
|
|
455
|
+
/**
|
|
456
|
+
* 処理名: StatementLifecycle コンストラクタ
|
|
457
|
+
* 処理概要: キャッシュアイデンティティ、タイムアウト時間、クロック関数、ヘルスバッファを初期化する。
|
|
458
|
+
* 実装理由: ステートメント実行ごとの期限計算およびヘルス監視を設定するため。
|
|
459
|
+
* @param identity - モデル・ランタイムアイデンティティ。
|
|
460
|
+
* @param timeoutMs - ステートメント実行タイムアウト (ミリ秒)。
|
|
461
|
+
* @param clock - 単調時刻クロック関数 (既定: performance.now)。
|
|
462
|
+
* @param health - 推論セッションヘルス共有バッファ (任意)。
|
|
463
|
+
*/
|
|
464
|
+
constructor(identity, timeoutMs, clock = () => performance.now(), health) {
|
|
465
|
+
this.identity = identity;
|
|
466
|
+
this.timeoutMs = timeoutMs;
|
|
467
|
+
this.clock = clock;
|
|
468
|
+
this.health = health;
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* 処理名: アクティブステップ存在確認
|
|
472
|
+
* 処理概要: 現在 step 実行中のステートメントコンテキストが存在するか判定する。
|
|
473
|
+
* 実装理由: 再入防止および実行状態確認のため。
|
|
474
|
+
* @returns アクティブステップ実行中なら true。
|
|
475
|
+
*/
|
|
476
|
+
hasActiveStep() {
|
|
477
|
+
return this.activeExecution !== null;
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* 処理名: ステップ開始 (enter)
|
|
481
|
+
* 処理概要: ステートメント実行を開始し、ROW継続時は既存キャッシュ、新規時は新世代コンテキストを割り当てる。
|
|
482
|
+
* 実装理由: ステートメント間・接続間のキャッシュ混同を排除し、期限切れを検査するため。
|
|
483
|
+
* @param database - データベースポインタ。
|
|
484
|
+
* @param statement - ステートメントポインタ。
|
|
485
|
+
* @returns 有効な StatementExecution。
|
|
486
|
+
*/
|
|
487
|
+
enter(database, statement) {
|
|
488
|
+
if (this.activeExecution !== null && this.activeExecution.statement !== statement) {
|
|
489
|
+
throw new VectorError("E_PROTOCOL");
|
|
490
|
+
}
|
|
491
|
+
const existing = this.stmtMap.get(statement);
|
|
492
|
+
if (existing) {
|
|
493
|
+
if (this.health) {
|
|
494
|
+
assertInferenceReady(this.health);
|
|
495
|
+
}
|
|
496
|
+
if (existing.cancelled) {
|
|
497
|
+
throw new VectorError("E_CANCELLED");
|
|
498
|
+
}
|
|
499
|
+
if (this.clock() >= existing.deadline) {
|
|
500
|
+
this.reset(statement);
|
|
501
|
+
throw new VectorError("E_TIMEOUT");
|
|
502
|
+
}
|
|
503
|
+
this.activeExecution = existing;
|
|
504
|
+
return existing;
|
|
505
|
+
}
|
|
506
|
+
this.generationSeq++;
|
|
507
|
+
const generation = this.generationSeq;
|
|
508
|
+
const now = this.clock();
|
|
509
|
+
const deadline = now + this.timeoutMs;
|
|
510
|
+
if (now >= deadline) {
|
|
511
|
+
throw new VectorError("E_TIMEOUT");
|
|
512
|
+
}
|
|
513
|
+
if (this.health) {
|
|
514
|
+
assertInferenceReady(this.health);
|
|
515
|
+
}
|
|
516
|
+
const cancellationBuffer = new SharedArrayBuffer(4);
|
|
517
|
+
const checkCallback = () => {
|
|
518
|
+
if (this.health) {
|
|
519
|
+
assertInferenceReady(this.health);
|
|
520
|
+
}
|
|
521
|
+
const currentExec = this.stmtMap.get(statement);
|
|
522
|
+
if (currentExec?.cancelled) {
|
|
523
|
+
throw new VectorError("E_CANCELLED");
|
|
524
|
+
}
|
|
525
|
+
if (this.clock() >= deadline) {
|
|
526
|
+
throw new VectorError("E_TIMEOUT");
|
|
527
|
+
}
|
|
528
|
+
};
|
|
529
|
+
const cache = new StatementEmbeddingCache(this.identity, 33554432, checkCallback);
|
|
530
|
+
const execution = {
|
|
531
|
+
database,
|
|
532
|
+
statement,
|
|
533
|
+
generation,
|
|
534
|
+
deadline,
|
|
535
|
+
cancelled: false,
|
|
536
|
+
cancellationBuffer,
|
|
537
|
+
cache
|
|
538
|
+
};
|
|
539
|
+
this.stmtMap.set(statement, execution);
|
|
540
|
+
let stmts = this.dbMap.get(database);
|
|
541
|
+
if (!stmts) {
|
|
542
|
+
stmts = /* @__PURE__ */ new Set();
|
|
543
|
+
this.dbMap.set(database, stmts);
|
|
544
|
+
}
|
|
545
|
+
stmts.add(statement);
|
|
546
|
+
this.activeExecution = execution;
|
|
547
|
+
return execution;
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* 処理名: 現在実行コンテキスト取得
|
|
551
|
+
* 処理概要: 現在アクティブなステップの StatementExecution を取得し、ヘルス・キャンセル・期限を検査する。
|
|
552
|
+
* 実装理由: UDF 評価時に実行文脈の健全性を保証するため。
|
|
553
|
+
* @returns 現在の StatementExecution。
|
|
554
|
+
*/
|
|
555
|
+
current() {
|
|
556
|
+
if (!this.activeExecution) {
|
|
557
|
+
throw new VectorError("E_PROTOCOL");
|
|
558
|
+
}
|
|
559
|
+
if (this.health) {
|
|
560
|
+
assertInferenceReady(this.health);
|
|
561
|
+
}
|
|
562
|
+
if (this.activeExecution.cancelled) {
|
|
563
|
+
throw new VectorError("E_CANCELLED");
|
|
564
|
+
}
|
|
565
|
+
if (this.clock() >= this.activeExecution.deadline) {
|
|
566
|
+
throw new VectorError("E_TIMEOUT");
|
|
567
|
+
}
|
|
568
|
+
return this.activeExecution;
|
|
569
|
+
}
|
|
570
|
+
/**
|
|
571
|
+
* 処理名: ステップ終了 (leave)
|
|
572
|
+
* 処理概要: ステップ実行を完了し、SQLITE_ROW(100)以外の場合はキャッシュを破棄して統計を加算する。
|
|
573
|
+
* 実装理由: ROW行間のみキャッシュを維持し、DONEやエラー時に確実にメモリを解放するため。
|
|
574
|
+
* @param statement - ステートメントポインタ。
|
|
575
|
+
* @param result - sqlite3_step の戻り値コード (100=SQLITE_ROW, 101=SQLITE_DONE 等)。
|
|
576
|
+
*/
|
|
577
|
+
leave(statement, result) {
|
|
578
|
+
if (this.activeExecution && this.activeExecution.statement === statement) {
|
|
579
|
+
this.activeExecution = null;
|
|
580
|
+
}
|
|
581
|
+
const execution = this.stmtMap.get(statement);
|
|
582
|
+
if (!execution) {
|
|
583
|
+
return;
|
|
584
|
+
}
|
|
585
|
+
if (result === 100) {
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
this.reset(statement);
|
|
589
|
+
}
|
|
590
|
+
/**
|
|
591
|
+
* 処理名: ステートメントリセット
|
|
592
|
+
* 処理概要: 対象ステートメントのキャッシュを破棄し、統計カウンタを累積してマップから除去する。
|
|
593
|
+
* 実装理由: sqlite3_reset / finalize 時のキャッシュ破棄プロトコルを遵守するため。
|
|
594
|
+
* @param statement - ステートメントポインタ。
|
|
595
|
+
*/
|
|
596
|
+
reset(statement) {
|
|
597
|
+
const execution = this.stmtMap.get(statement);
|
|
598
|
+
if (execution) {
|
|
599
|
+
const stats = execution.cache.statistics();
|
|
600
|
+
this.accumulatedHit += stats.hit;
|
|
601
|
+
this.accumulatedMiss += stats.miss;
|
|
602
|
+
this.accumulatedEviction += stats.eviction;
|
|
603
|
+
this.accumulatedActualInference += stats.actualInference;
|
|
604
|
+
execution.cache.dispose();
|
|
605
|
+
this.stmtMap.delete(statement);
|
|
606
|
+
const stmts = this.dbMap.get(execution.database);
|
|
607
|
+
if (stmts) {
|
|
608
|
+
stmts.delete(statement);
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
if (this.activeExecution && this.activeExecution.statement === statement) {
|
|
612
|
+
this.activeExecution = null;
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
/**
|
|
616
|
+
* 処理名: データベースクローズ
|
|
617
|
+
* 処理概要: 指定データベースに関連付けられた全ステートメントのコンテキストを破棄する。
|
|
618
|
+
* 実装理由: DB close 時のリソース完全回収のため。
|
|
619
|
+
* @param database - データベースポインタ。
|
|
620
|
+
*/
|
|
621
|
+
close(database) {
|
|
622
|
+
const stmts = this.dbMap.get(database);
|
|
623
|
+
if (stmts) {
|
|
624
|
+
for (const statement of Array.from(stmts)) {
|
|
625
|
+
this.reset(statement);
|
|
626
|
+
}
|
|
627
|
+
this.dbMap.delete(database);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
/**
|
|
631
|
+
* 処理名: 実行キャンセル
|
|
632
|
+
* 処理概要: 指定データベースまたは全ステートメントのキャンセルフラグを立て、キャッシュを破棄する。
|
|
633
|
+
* 実装理由: キャンセルシグナルを同期的かつ即座に反映させるため。
|
|
634
|
+
* @param database - 対象データベースポインタ (省略時は全DB)。
|
|
635
|
+
*/
|
|
636
|
+
cancel(database) {
|
|
637
|
+
const targets = [];
|
|
638
|
+
if (database !== void 0) {
|
|
639
|
+
const stmts = this.dbMap.get(database);
|
|
640
|
+
if (stmts) {
|
|
641
|
+
for (const s of stmts) {
|
|
642
|
+
const exec = this.stmtMap.get(s);
|
|
643
|
+
if (exec) targets.push(exec);
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
} else {
|
|
647
|
+
targets.push(...Array.from(this.stmtMap.values()));
|
|
648
|
+
}
|
|
649
|
+
for (const execution of targets) {
|
|
650
|
+
execution.cancelled = true;
|
|
651
|
+
Atomics.store(new Int32Array(execution.cancellationBuffer, 0, 1), 0, 1);
|
|
652
|
+
execution.cache.dispose();
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* 処理名: 累積統計取得
|
|
657
|
+
* 処理概要: これまでに実行・終了した全ステートメントのキャッシュ統計を合算して返す。
|
|
658
|
+
* 実装理由: gemma_model_info におけるキャッシュ効率診断のため。
|
|
659
|
+
* @returns 累積 CacheCounters。
|
|
660
|
+
*/
|
|
661
|
+
statistics() {
|
|
662
|
+
let currentEntries = 0;
|
|
663
|
+
let currentBytes = 0;
|
|
664
|
+
for (const exec of this.stmtMap.values()) {
|
|
665
|
+
const s = exec.cache.statistics();
|
|
666
|
+
currentEntries += s.entries;
|
|
667
|
+
currentBytes += s.bytes;
|
|
668
|
+
}
|
|
669
|
+
return {
|
|
670
|
+
hit: this.accumulatedHit,
|
|
671
|
+
miss: this.accumulatedMiss,
|
|
672
|
+
eviction: this.accumulatedEviction,
|
|
673
|
+
actualInference: this.accumulatedActualInference,
|
|
674
|
+
entries: currentEntries,
|
|
675
|
+
bytes: currentBytes
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
};
|
|
679
|
+
|
|
680
|
+
// src/official/lifecycle-adapter.ts
|
|
681
|
+
var OfficialLifecycleAdapter = class {
|
|
682
|
+
sqlite3;
|
|
683
|
+
openDatabases = /* @__PURE__ */ new Set();
|
|
684
|
+
lifecycle;
|
|
685
|
+
onCloseCallbacks = [];
|
|
686
|
+
// 元の CAPI 関数の退避
|
|
687
|
+
origStep;
|
|
688
|
+
origReset;
|
|
689
|
+
origFinalize;
|
|
690
|
+
origSetAuthorizer;
|
|
691
|
+
origProgressHandler;
|
|
692
|
+
origTraceV2;
|
|
693
|
+
// ユーザー定義の authorizer および progress handler マップ (db ハンドル別)
|
|
694
|
+
userAuthorizers = /* @__PURE__ */ new Map();
|
|
695
|
+
userProgressHandlers = /* @__PURE__ */ new Map();
|
|
696
|
+
lastInterruptReason = /* @__PURE__ */ new Map();
|
|
697
|
+
disposed = false;
|
|
698
|
+
/**
|
|
699
|
+
* 処理名: OfficialLifecycleAdapter コンストラクタ
|
|
700
|
+
* 処理概要: SQLite 静的オブジェクトとライフサイクル管理を受け取り、CAPI をフックする。
|
|
701
|
+
* 実装理由: ステートメント境界と権限保護を CAPI レベルで透過的に管理するため。
|
|
702
|
+
* @param sqlite3 - 公式 SQLite3 静的インターフェース。
|
|
703
|
+
* @param lifecycle - ステートメントライフサイクルマネージャー。
|
|
704
|
+
* @param onClose - DB クローズ時コールバック。
|
|
705
|
+
*/
|
|
706
|
+
constructor(sqlite3, lifecycle, onClose) {
|
|
707
|
+
this.sqlite3 = sqlite3;
|
|
708
|
+
this.lifecycle = lifecycle ?? {};
|
|
709
|
+
if (onClose) {
|
|
710
|
+
this.onCloseCallbacks.push(onClose);
|
|
711
|
+
}
|
|
712
|
+
const capi = sqlite3.capi;
|
|
713
|
+
this.origStep = capi.sqlite3_step;
|
|
714
|
+
this.origReset = capi.sqlite3_reset;
|
|
715
|
+
this.origFinalize = capi.sqlite3_finalize;
|
|
716
|
+
this.origSetAuthorizer = capi.sqlite3_set_authorizer;
|
|
717
|
+
this.origProgressHandler = capi.sqlite3_progress_handler;
|
|
718
|
+
this.origTraceV2 = capi.sqlite3_trace_v2;
|
|
719
|
+
this.installCapiHooks();
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* 処理名: CAPI フックのインストール
|
|
723
|
+
* 処理概要: step, reset, finalize, authorizer, progress_handler, trace_v2 をインターセプトする。
|
|
724
|
+
* 実装理由: ステートメントキャッシュ境界の維持と _svw_ メタデータ保護、および引数互換性を保証するため。
|
|
725
|
+
*/
|
|
726
|
+
installCapiHooks() {
|
|
727
|
+
const capi = this.sqlite3.capi;
|
|
728
|
+
const adapter = this;
|
|
729
|
+
capi.sqlite3_step = function(pStmt) {
|
|
730
|
+
const pDb = capi.sqlite3_db_handle(pStmt);
|
|
731
|
+
const dbPtr = typeof pDb === "number" ? pDb : pDb?.pointer ?? pDb;
|
|
732
|
+
adapter.lastInterruptReason.delete(dbPtr);
|
|
733
|
+
if (typeof adapter.lifecycle.enter === "function") {
|
|
734
|
+
adapter.lifecycle.enter(pDb, pStmt);
|
|
735
|
+
}
|
|
736
|
+
try {
|
|
737
|
+
const res = adapter.origStep.call(capi, pStmt);
|
|
738
|
+
if (typeof adapter.lifecycle.leave === "function") {
|
|
739
|
+
adapter.lifecycle.leave(pStmt, res);
|
|
740
|
+
}
|
|
741
|
+
if (res === 9 || res === capi.SQLITE_INTERRUPT) {
|
|
742
|
+
const reason = adapter.lastInterruptReason.get(dbPtr);
|
|
743
|
+
if (reason) {
|
|
744
|
+
adapter.lastInterruptReason.delete(dbPtr);
|
|
745
|
+
if (typeof adapter.lifecycle.reset === "function") {
|
|
746
|
+
adapter.lifecycle.reset(pStmt);
|
|
747
|
+
}
|
|
748
|
+
throw reason;
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
return res;
|
|
752
|
+
} catch (err) {
|
|
753
|
+
if (typeof adapter.lifecycle.reset === "function") {
|
|
754
|
+
adapter.lifecycle.reset(pStmt);
|
|
755
|
+
}
|
|
756
|
+
throw err;
|
|
757
|
+
}
|
|
758
|
+
};
|
|
759
|
+
capi.sqlite3_reset = function(pStmt) {
|
|
760
|
+
if (typeof adapter.lifecycle.reset === "function") {
|
|
761
|
+
adapter.lifecycle.reset(pStmt);
|
|
762
|
+
}
|
|
763
|
+
return adapter.origReset.call(capi, pStmt);
|
|
764
|
+
};
|
|
765
|
+
capi.sqlite3_finalize = function(pStmt) {
|
|
766
|
+
if (typeof adapter.lifecycle.reset === "function") {
|
|
767
|
+
adapter.lifecycle.reset(pStmt);
|
|
768
|
+
}
|
|
769
|
+
return adapter.origFinalize.call(capi, pStmt);
|
|
770
|
+
};
|
|
771
|
+
capi.sqlite3_set_authorizer = function(pDb, xAuth, pUserData) {
|
|
772
|
+
const dbPtr = typeof pDb === "number" ? pDb : pDb?.pointer ?? pDb;
|
|
773
|
+
if (xAuth) {
|
|
774
|
+
adapter.userAuthorizers.set(dbPtr, { fn: xAuth, arg: pUserData });
|
|
775
|
+
} else {
|
|
776
|
+
adapter.userAuthorizers.delete(dbPtr);
|
|
777
|
+
}
|
|
778
|
+
return adapter.applyAuthorizer(pDb);
|
|
779
|
+
};
|
|
780
|
+
capi.sqlite3_progress_handler = function(pDb, nOps, xHandler, pUserData) {
|
|
781
|
+
const dbPtr = typeof pDb === "number" ? pDb : pDb?.pointer ?? pDb;
|
|
782
|
+
if (xHandler && nOps > 0) {
|
|
783
|
+
adapter.userProgressHandlers.set(dbPtr, { nOps, fn: xHandler, arg: pUserData });
|
|
784
|
+
} else {
|
|
785
|
+
adapter.userProgressHandlers.delete(dbPtr);
|
|
786
|
+
}
|
|
787
|
+
return adapter.applyProgressHandler(pDb);
|
|
788
|
+
};
|
|
789
|
+
if (typeof this.origTraceV2 === "function") {
|
|
790
|
+
capi.sqlite3_trace_v2 = function(pDb, uMask, xCallback, pCtx = 0) {
|
|
791
|
+
const dbPtr = typeof pDb === "number" ? pDb : pDb?.pointer ?? pDb;
|
|
792
|
+
return adapter.origTraceV2.call(capi, dbPtr, uMask, xCallback, pCtx ?? 0);
|
|
793
|
+
};
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
/**
|
|
797
|
+
* 処理名: 合成 authorizer の適用
|
|
798
|
+
* 処理概要: _svw_ メタデータ保護とユーザー定義 authorizer を合成して設定する。
|
|
799
|
+
* 実装理由: 内部メタデータの改変を拒絶しつつユーザー側のセキュリティポリシーを両立するため。
|
|
800
|
+
* @param db - 対象データベース。
|
|
801
|
+
*/
|
|
802
|
+
applyAuthorizer(db) {
|
|
803
|
+
const capi = this.sqlite3.capi;
|
|
804
|
+
const dbPtr = typeof db === "number" ? db : db?.pointer ?? db;
|
|
805
|
+
const userAuth = this.userAuthorizers.get(dbPtr);
|
|
806
|
+
const SQLITE_OK = capi.SQLITE_OK ?? 0;
|
|
807
|
+
const SQLITE_DENY = capi.SQLITE_DENY ?? 1;
|
|
808
|
+
const SQLITE_READ = capi.SQLITE_READ ?? 20;
|
|
809
|
+
const compositeAuth = (arg, action, p3, p4, p5, p6) => {
|
|
810
|
+
const targetName = typeof p3 === "string" ? p3 : typeof p4 === "string" ? p4 : "";
|
|
811
|
+
const isInternal = targetName.startsWith("_svw_");
|
|
812
|
+
if (isInternal) {
|
|
813
|
+
if (action === SQLITE_READ) {
|
|
814
|
+
if (userAuth) {
|
|
815
|
+
return userAuth.fn(userAuth.arg, action, p3, p4, p5, p6);
|
|
816
|
+
}
|
|
817
|
+
return SQLITE_OK;
|
|
818
|
+
}
|
|
819
|
+
return SQLITE_DENY;
|
|
820
|
+
}
|
|
821
|
+
if (userAuth) {
|
|
822
|
+
return userAuth.fn(userAuth.arg, action, p3, p4, p5, p6);
|
|
823
|
+
}
|
|
824
|
+
return SQLITE_OK;
|
|
825
|
+
};
|
|
826
|
+
return this.origSetAuthorizer.call(capi, db, compositeAuth, 0);
|
|
827
|
+
}
|
|
828
|
+
/**
|
|
829
|
+
* 処理名: 合成 progress handler の適用
|
|
830
|
+
* 処理概要: 100 命令周期の内部ライフサイクル期限検査とユーザー進捗ハンドラを合成する。
|
|
831
|
+
* 実装理由: 長時間実行やキャンセルの安全な中断とユーザー通知を両立するため。
|
|
832
|
+
* @param db - 対象データベース。
|
|
833
|
+
*/
|
|
834
|
+
applyProgressHandler(db) {
|
|
835
|
+
const capi = this.sqlite3.capi;
|
|
836
|
+
const dbPtr = typeof db === "number" ? db : db?.pointer ?? db;
|
|
837
|
+
const userHandler = this.userProgressHandlers.get(dbPtr);
|
|
838
|
+
const nOps = userHandler ? Math.min(userHandler.nOps, 100) : 100;
|
|
839
|
+
const compositeProgress = (arg) => {
|
|
840
|
+
if (typeof this.lifecycle.current === "function") {
|
|
841
|
+
try {
|
|
842
|
+
this.lifecycle.current();
|
|
843
|
+
} catch (err) {
|
|
844
|
+
this.lastInterruptReason.set(dbPtr, err);
|
|
845
|
+
return 1;
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
if (userHandler) {
|
|
849
|
+
const userRes = userHandler.fn(userHandler.arg);
|
|
850
|
+
if (userRes !== 0) {
|
|
851
|
+
this.lastInterruptReason.set(dbPtr, new VectorError("E_CANCELLED"));
|
|
852
|
+
return 1;
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
return 0;
|
|
856
|
+
};
|
|
857
|
+
return this.origProgressHandler.call(capi, db, nOps, compositeProgress, 0);
|
|
858
|
+
}
|
|
859
|
+
/**
|
|
860
|
+
* 処理名: データベース接続監視開始
|
|
861
|
+
* 処理概要: DB インスタンスの close メソッドをフックし、接続のオープン・クローズ状態を追跡する。
|
|
862
|
+
* @param db - 対象データベース接続。
|
|
863
|
+
*/
|
|
864
|
+
observe(db) {
|
|
865
|
+
if (this.disposed) return;
|
|
866
|
+
this.openDatabases.add(db);
|
|
867
|
+
this.applyAuthorizer(db);
|
|
868
|
+
this.applyProgressHandler(db);
|
|
869
|
+
const originalClose = db.close.bind(db);
|
|
870
|
+
db.close = () => {
|
|
871
|
+
this.openDatabases.delete(db);
|
|
872
|
+
for (const cb of this.onCloseCallbacks) {
|
|
873
|
+
try {
|
|
874
|
+
cb(db);
|
|
875
|
+
} catch {
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
return originalClose();
|
|
879
|
+
};
|
|
880
|
+
}
|
|
881
|
+
/**
|
|
882
|
+
* 処理名: クローズ状態アサート
|
|
883
|
+
* 処理概要: まだオープン中のデータベース接続が存在する場合は E_DB_IN_USE エラーを投げる。
|
|
884
|
+
*/
|
|
885
|
+
assertClosed() {
|
|
886
|
+
if (this.openDatabases.size > 0) {
|
|
887
|
+
throw new VectorError("E_DB_IN_USE");
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
/**
|
|
891
|
+
* 処理名: 追跡中のデータベース数取得
|
|
892
|
+
*/
|
|
893
|
+
get activeCount() {
|
|
894
|
+
return this.openDatabases.size;
|
|
895
|
+
}
|
|
896
|
+
/**
|
|
897
|
+
* 処理名: ライフサイクルアダプター破棄
|
|
898
|
+
* 処理概要: フックした CAPI を元通りに復元し、追跡状態をリセットする。
|
|
899
|
+
*/
|
|
900
|
+
dispose() {
|
|
901
|
+
if (this.disposed) return;
|
|
902
|
+
this.disposed = true;
|
|
903
|
+
const capi = this.sqlite3.capi;
|
|
904
|
+
capi.sqlite3_step = this.origStep;
|
|
905
|
+
capi.sqlite3_reset = this.origReset;
|
|
906
|
+
capi.sqlite3_finalize = this.origFinalize;
|
|
907
|
+
capi.sqlite3_set_authorizer = this.origSetAuthorizer;
|
|
908
|
+
capi.sqlite3_progress_handler = this.origProgressHandler;
|
|
909
|
+
if (typeof this.origTraceV2 === "function") {
|
|
910
|
+
capi.sqlite3_trace_v2 = this.origTraceV2;
|
|
911
|
+
}
|
|
912
|
+
this.openDatabases.clear();
|
|
913
|
+
this.userAuthorizers.clear();
|
|
914
|
+
this.userProgressHandlers.clear();
|
|
915
|
+
}
|
|
916
|
+
};
|
|
917
|
+
|
|
918
|
+
// src/official/functions.ts
|
|
919
|
+
function embeddingSqlValue(name, args, infer) {
|
|
920
|
+
if (args.length < 1) {
|
|
921
|
+
throw new VectorError("E_INPUT");
|
|
922
|
+
}
|
|
923
|
+
if (args.length >= 2) {
|
|
924
|
+
const model = args[1];
|
|
925
|
+
if (typeof model !== "string" || model !== "embeddinggemma-2") {
|
|
926
|
+
throw new VectorError("E_INPUT");
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
const rawBody = args[0];
|
|
930
|
+
if (rawBody === null) {
|
|
931
|
+
return null;
|
|
932
|
+
}
|
|
933
|
+
if (typeof rawBody !== "string") {
|
|
934
|
+
throw new VectorError("E_INPUT");
|
|
935
|
+
}
|
|
936
|
+
if (rawBody.trim().length === 0 || rawBody.includes("\0")) {
|
|
937
|
+
throw new VectorError("E_INPUT");
|
|
938
|
+
}
|
|
939
|
+
if (!infer) {
|
|
940
|
+
throw new VectorError("E_EMBEDDING_NOT_READY");
|
|
941
|
+
}
|
|
942
|
+
const operation = name === "embedding_query" ? "query" : "document";
|
|
943
|
+
return infer({
|
|
944
|
+
operation,
|
|
945
|
+
body: rawBody,
|
|
946
|
+
title: void 0
|
|
947
|
+
});
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
// src/official/registration.ts
|
|
951
|
+
function registerEmbeddingExtension(sqlite3, infer, options) {
|
|
952
|
+
const cacheIdentity = {
|
|
953
|
+
modelId: options?.identity?.modelId ?? "default-model",
|
|
954
|
+
revision: options?.identity?.revision ?? "0.0.1",
|
|
955
|
+
fingerprint: options?.identity?.fingerprint ?? "default-fingerprint",
|
|
956
|
+
profile: options?.identity?.profile ?? "default-profile",
|
|
957
|
+
backend: options?.identity?.backend ?? "wasm",
|
|
958
|
+
runtimeGeneration: 1
|
|
959
|
+
};
|
|
960
|
+
const timeoutMs = options?.timeoutMs ?? 3e4;
|
|
961
|
+
const lifecycle = new StatementLifecycle(cacheIdentity, timeoutMs);
|
|
962
|
+
const adapter = new OfficialLifecycleAdapter(sqlite3, lifecycle);
|
|
963
|
+
const protection = new OfficialMetadataProtection(sqlite3);
|
|
964
|
+
let functionCalls = 0;
|
|
965
|
+
let closed = false;
|
|
966
|
+
const originalDB = sqlite3.oo1.DB;
|
|
967
|
+
const setupUDFsForDb = (db) => {
|
|
968
|
+
try {
|
|
969
|
+
db.createFunction({
|
|
970
|
+
name: "gemma_model_info",
|
|
971
|
+
arity: 0,
|
|
972
|
+
xFunc: () => {
|
|
973
|
+
if (!infer) {
|
|
974
|
+
return JSON.stringify({ ready: false });
|
|
975
|
+
}
|
|
976
|
+
return JSON.stringify({
|
|
977
|
+
ready: true,
|
|
978
|
+
...options?.information,
|
|
979
|
+
functionCalls,
|
|
980
|
+
cache: lifecycle.statistics()
|
|
981
|
+
});
|
|
982
|
+
}
|
|
983
|
+
});
|
|
984
|
+
db.createFunction({
|
|
985
|
+
name: "DISTANCE",
|
|
986
|
+
arity: 2,
|
|
987
|
+
xFunc: (_ctx, a, b) => {
|
|
988
|
+
return calculateCosineDistance(a, b);
|
|
989
|
+
}
|
|
990
|
+
});
|
|
991
|
+
const inferWrapper = (req) => {
|
|
992
|
+
functionCalls++;
|
|
993
|
+
let current;
|
|
994
|
+
try {
|
|
995
|
+
if (typeof lifecycle.current === "function") {
|
|
996
|
+
current = lifecycle.current();
|
|
997
|
+
}
|
|
998
|
+
} catch {
|
|
999
|
+
}
|
|
1000
|
+
const cache = current?.cache;
|
|
1001
|
+
const doInfer = (r) => {
|
|
1002
|
+
try {
|
|
1003
|
+
const res = infer({
|
|
1004
|
+
operation: r.operation,
|
|
1005
|
+
body: r.body,
|
|
1006
|
+
title: r.title,
|
|
1007
|
+
bytes: r.bytes,
|
|
1008
|
+
mime: r.mime,
|
|
1009
|
+
model: void 0
|
|
1010
|
+
});
|
|
1011
|
+
if (res instanceof Uint8Array) {
|
|
1012
|
+
return res;
|
|
1013
|
+
}
|
|
1014
|
+
return null;
|
|
1015
|
+
} catch (err) {
|
|
1016
|
+
console.warn("Embedding error:", err);
|
|
1017
|
+
throw err;
|
|
1018
|
+
}
|
|
1019
|
+
};
|
|
1020
|
+
if (cache && typeof cache.resolve === "function") {
|
|
1021
|
+
return cache.resolve(req, doInfer);
|
|
1022
|
+
}
|
|
1023
|
+
return doInfer(req);
|
|
1024
|
+
};
|
|
1025
|
+
if (!infer) {
|
|
1026
|
+
return;
|
|
1027
|
+
}
|
|
1028
|
+
const embeddingFunc = (_ctx, ...args) => {
|
|
1029
|
+
return embeddingSqlValue("embedding", args, inferWrapper);
|
|
1030
|
+
};
|
|
1031
|
+
db.createFunction({
|
|
1032
|
+
name: "embedding",
|
|
1033
|
+
arity: 1,
|
|
1034
|
+
directOnly: true,
|
|
1035
|
+
xFunc: embeddingFunc
|
|
1036
|
+
});
|
|
1037
|
+
db.createFunction({
|
|
1038
|
+
name: "embedding",
|
|
1039
|
+
arity: 2,
|
|
1040
|
+
directOnly: true,
|
|
1041
|
+
xFunc: embeddingFunc
|
|
1042
|
+
});
|
|
1043
|
+
const embeddingQueryFunc = (_ctx, ...args) => {
|
|
1044
|
+
return embeddingSqlValue("embedding_query", args, inferWrapper);
|
|
1045
|
+
};
|
|
1046
|
+
db.createFunction({
|
|
1047
|
+
name: "embedding_query",
|
|
1048
|
+
arity: 1,
|
|
1049
|
+
directOnly: true,
|
|
1050
|
+
xFunc: embeddingQueryFunc
|
|
1051
|
+
});
|
|
1052
|
+
db.createFunction({
|
|
1053
|
+
name: "embedding_query",
|
|
1054
|
+
arity: 2,
|
|
1055
|
+
directOnly: true,
|
|
1056
|
+
xFunc: embeddingQueryFunc
|
|
1057
|
+
});
|
|
1058
|
+
} catch {
|
|
1059
|
+
}
|
|
1060
|
+
};
|
|
1061
|
+
function WrappedDB(...args) {
|
|
1062
|
+
const instance = Reflect.construct(originalDB, args, WrappedDB);
|
|
1063
|
+
try {
|
|
1064
|
+
const metaTableCount = instance.selectValue("SELECT count(*) FROM sqlite_schema WHERE type='table' AND name='_svw_meta'");
|
|
1065
|
+
if (metaTableCount === 0) {
|
|
1066
|
+
const userTableCount = instance.selectValue("SELECT count(*) FROM sqlite_schema WHERE type='table' AND name NOT LIKE 'sqlite_%'");
|
|
1067
|
+
if (userTableCount > 0) {
|
|
1068
|
+
try {
|
|
1069
|
+
instance.close();
|
|
1070
|
+
} catch {
|
|
1071
|
+
}
|
|
1072
|
+
throw new VectorError("E_MODEL_UNBOUND");
|
|
1073
|
+
}
|
|
1074
|
+
if (options?.identity) {
|
|
1075
|
+
initializeOfficialMetadata(sqlite3, instance, options.identity);
|
|
1076
|
+
}
|
|
1077
|
+
} else {
|
|
1078
|
+
if (options?.identity) {
|
|
1079
|
+
initializeOfficialMetadata(sqlite3, instance, options.identity);
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
} catch (err) {
|
|
1083
|
+
if (err instanceof VectorError) {
|
|
1084
|
+
throw err;
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
setupUDFsForDb(instance);
|
|
1088
|
+
adapter.observe(instance);
|
|
1089
|
+
protection.observe(instance);
|
|
1090
|
+
return instance;
|
|
1091
|
+
}
|
|
1092
|
+
Object.setPrototypeOf(WrappedDB.prototype, originalDB.prototype);
|
|
1093
|
+
Object.setPrototypeOf(WrappedDB, originalDB);
|
|
1094
|
+
sqlite3.oo1.DB = WrappedDB;
|
|
1095
|
+
return {
|
|
1096
|
+
async close() {
|
|
1097
|
+
if (closed) {
|
|
1098
|
+
return;
|
|
1099
|
+
}
|
|
1100
|
+
adapter.assertClosed();
|
|
1101
|
+
closed = true;
|
|
1102
|
+
sqlite3.oo1.DB = originalDB;
|
|
1103
|
+
adapter.dispose();
|
|
1104
|
+
protection.dispose();
|
|
1105
|
+
}
|
|
1106
|
+
};
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
// src/official/initialize.ts
|
|
1110
|
+
async function initializeOfficialRuntime(factory, options = {}, env, prepareInference) {
|
|
1111
|
+
const { embedding: embeddingOpt, ...officialOptions } = options;
|
|
1112
|
+
const sqlite3 = await factory(officialOptions);
|
|
1113
|
+
const validated = validateEmbeddingOptions(embeddingOpt, env);
|
|
1114
|
+
let session = null;
|
|
1115
|
+
if (validated && prepareInference) {
|
|
1116
|
+
session = await prepareInference(validated);
|
|
1117
|
+
}
|
|
1118
|
+
const extensionControl = registerEmbeddingExtension(sqlite3, session?.infer, {
|
|
1119
|
+
identity: session?.identity,
|
|
1120
|
+
timeoutMs: validated?.sqlTimeoutMs ?? 12e4,
|
|
1121
|
+
information: session?.information,
|
|
1122
|
+
models: validated?.models,
|
|
1123
|
+
defaultModel: validated?.defaultModel
|
|
1124
|
+
});
|
|
1125
|
+
const trackedPools = [];
|
|
1126
|
+
if (typeof sqlite3.installOpfsSAHPoolVfs === "function") {
|
|
1127
|
+
const originalInstall = sqlite3.installOpfsSAHPoolVfs.bind(sqlite3);
|
|
1128
|
+
sqlite3.installOpfsSAHPoolVfs = async (poolOpts) => {
|
|
1129
|
+
const pool = await originalInstall(poolOpts);
|
|
1130
|
+
if (pool && typeof pool.pauseVfs === "function") {
|
|
1131
|
+
trackedPools.push(pool);
|
|
1132
|
+
}
|
|
1133
|
+
return pool;
|
|
1134
|
+
};
|
|
1135
|
+
}
|
|
1136
|
+
let isClosed = false;
|
|
1137
|
+
sqlite3.embedding = {
|
|
1138
|
+
async close() {
|
|
1139
|
+
if (isClosed) return;
|
|
1140
|
+
await extensionControl.close();
|
|
1141
|
+
if (session) {
|
|
1142
|
+
await session.close();
|
|
1143
|
+
}
|
|
1144
|
+
for (const p of trackedPools) {
|
|
1145
|
+
try {
|
|
1146
|
+
p.pauseVfs();
|
|
1147
|
+
} catch {
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
isClosed = true;
|
|
1151
|
+
}
|
|
1152
|
+
};
|
|
1153
|
+
return sqlite3;
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
// src/official/node-inference.ts
|
|
1157
|
+
import { Worker } from "node:worker_threads";
|
|
1158
|
+
import { resolve } from "node:path";
|
|
1159
|
+
import { readFile } from "node:fs/promises";
|
|
1160
|
+
|
|
1161
|
+
// src/bridge/protocol.ts
|
|
1162
|
+
var BUFFER_BYTE_LENGTH = 8192;
|
|
1163
|
+
var HEADER_INT32_COUNT = 8;
|
|
1164
|
+
var HEADER_BYTE_LENGTH = 32;
|
|
1165
|
+
var PROTOCOL_VERSION = 1;
|
|
1166
|
+
var STATE_PENDING = 0;
|
|
1167
|
+
var STATE_WRITING = 1;
|
|
1168
|
+
var STATE_OK = 2;
|
|
1169
|
+
var STATE_ERROR = 3;
|
|
1170
|
+
var STATE_ABANDONED = 4;
|
|
1171
|
+
function createResponseBuffer() {
|
|
1172
|
+
const sab = new SharedArrayBuffer(BUFFER_BYTE_LENGTH);
|
|
1173
|
+
const header = new Int32Array(sab, 0, HEADER_INT32_COUNT);
|
|
1174
|
+
Atomics.store(header, 0, STATE_PENDING);
|
|
1175
|
+
Atomics.store(header, 4, PROTOCOL_VERSION);
|
|
1176
|
+
return sab;
|
|
1177
|
+
}
|
|
1178
|
+
function readResponse(buffer) {
|
|
1179
|
+
if (buffer.byteLength !== BUFFER_BYTE_LENGTH) {
|
|
1180
|
+
throw new VectorError("E_PROTOCOL");
|
|
1181
|
+
}
|
|
1182
|
+
const header = new Int32Array(buffer, 0, HEADER_INT32_COUNT);
|
|
1183
|
+
const state = Atomics.load(header, 0);
|
|
1184
|
+
if (state !== STATE_OK && state !== STATE_ERROR) {
|
|
1185
|
+
throw new VectorError("E_PROTOCOL");
|
|
1186
|
+
}
|
|
1187
|
+
const payloadLen = header[1];
|
|
1188
|
+
const errorId = header[2];
|
|
1189
|
+
const dim = header[3];
|
|
1190
|
+
const version = header[4];
|
|
1191
|
+
if (version !== PROTOCOL_VERSION || header[5] !== 0 || header[6] !== 0 || header[7] !== 0) {
|
|
1192
|
+
throw new VectorError("E_PROTOCOL");
|
|
1193
|
+
}
|
|
1194
|
+
if (state === STATE_OK) {
|
|
1195
|
+
if (payloadLen !== 3072 || errorId !== 0 || dim !== 768) {
|
|
1196
|
+
throw new VectorError("E_PROTOCOL");
|
|
1197
|
+
}
|
|
1198
|
+
} else {
|
|
1199
|
+
if (payloadLen < 0 || payloadLen > 4096 || errorId < 1 || errorId > 10 || dim !== 0) {
|
|
1200
|
+
throw new VectorError("E_PROTOCOL");
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
const payloadBytes = new Uint8Array(buffer, HEADER_BYTE_LENGTH, payloadLen);
|
|
1204
|
+
const payloadCopy = new Uint8Array(payloadLen);
|
|
1205
|
+
payloadCopy.set(payloadBytes);
|
|
1206
|
+
return { payload: payloadCopy, errorId };
|
|
1207
|
+
}
|
|
1208
|
+
function abandonResponse(buffer) {
|
|
1209
|
+
if (buffer.byteLength !== BUFFER_BYTE_LENGTH) {
|
|
1210
|
+
throw new VectorError("E_PROTOCOL");
|
|
1211
|
+
}
|
|
1212
|
+
const header = new Int32Array(buffer, 0, HEADER_INT32_COUNT);
|
|
1213
|
+
while (true) {
|
|
1214
|
+
const current = Atomics.load(header, 0);
|
|
1215
|
+
if (current === STATE_OK || current === STATE_ERROR) {
|
|
1216
|
+
return false;
|
|
1217
|
+
}
|
|
1218
|
+
if (current === STATE_ABANDONED) {
|
|
1219
|
+
return true;
|
|
1220
|
+
}
|
|
1221
|
+
if (current === STATE_PENDING || current === STATE_WRITING) {
|
|
1222
|
+
const prev = Atomics.compareExchange(header, 0, current, STATE_ABANDONED);
|
|
1223
|
+
if (prev === current) {
|
|
1224
|
+
return true;
|
|
1225
|
+
}
|
|
1226
|
+
} else {
|
|
1227
|
+
throw new VectorError("E_PROTOCOL");
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
function waitResponse(buffer, cancellation, deadline) {
|
|
1232
|
+
if (buffer.byteLength !== BUFFER_BYTE_LENGTH) {
|
|
1233
|
+
throw new VectorError("E_PROTOCOL");
|
|
1234
|
+
}
|
|
1235
|
+
if (!(cancellation instanceof SharedArrayBuffer) || cancellation.byteLength !== 4) {
|
|
1236
|
+
throw new VectorError("E_PROTOCOL");
|
|
1237
|
+
}
|
|
1238
|
+
if (typeof deadline !== "number" || !Number.isFinite(deadline)) {
|
|
1239
|
+
throw new VectorError("E_PROTOCOL");
|
|
1240
|
+
}
|
|
1241
|
+
const header = new Int32Array(buffer, 0, HEADER_INT32_COUNT);
|
|
1242
|
+
const cancelView = new Int32Array(cancellation, 0, 1);
|
|
1243
|
+
while (true) {
|
|
1244
|
+
if (Atomics.load(cancelView, 0) === 1) {
|
|
1245
|
+
abandonResponse(buffer);
|
|
1246
|
+
throw new VectorError("E_CANCELLED");
|
|
1247
|
+
}
|
|
1248
|
+
const state = Atomics.load(header, 0);
|
|
1249
|
+
if (state === STATE_ABANDONED) {
|
|
1250
|
+
throw new VectorError("E_CANCELLED");
|
|
1251
|
+
}
|
|
1252
|
+
if (state === STATE_OK || state === STATE_ERROR) {
|
|
1253
|
+
return readResponse(buffer);
|
|
1254
|
+
}
|
|
1255
|
+
const now = performance.now();
|
|
1256
|
+
if (now >= deadline) {
|
|
1257
|
+
abandonResponse(buffer);
|
|
1258
|
+
throw new VectorError("E_TIMEOUT");
|
|
1259
|
+
}
|
|
1260
|
+
const remaining = Math.min(50, Math.max(1, Math.ceil(deadline - now)));
|
|
1261
|
+
Atomics.wait(header, 0, state, remaining);
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
// src/workers/db.ts
|
|
1266
|
+
var ERROR_ID_MAP = {
|
|
1267
|
+
1: "E_INPUT",
|
|
1268
|
+
2: "E_TOKEN_LIMIT",
|
|
1269
|
+
3: "E_IMAGE_FORMAT",
|
|
1270
|
+
4: "E_IMAGE_LIMIT",
|
|
1271
|
+
5: "E_EMBEDDING_VALUE",
|
|
1272
|
+
6: "E_INFERENCE",
|
|
1273
|
+
7: "E_TIMEOUT",
|
|
1274
|
+
8: "E_CANCELLED",
|
|
1275
|
+
9: "E_MEMORY",
|
|
1276
|
+
10: "E_PROTOCOL"
|
|
1277
|
+
};
|
|
1278
|
+
function requestEmbedding(port, request, cancellationBuffer, timeoutMs) {
|
|
1279
|
+
if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs < 0) {
|
|
1280
|
+
throw new VectorError("E_PROTOCOL");
|
|
1281
|
+
}
|
|
1282
|
+
if (!(cancellationBuffer instanceof SharedArrayBuffer) || cancellationBuffer.byteLength !== 4) {
|
|
1283
|
+
throw new VectorError("E_PROTOCOL");
|
|
1284
|
+
}
|
|
1285
|
+
if (typeof request.jobId !== "string" || request.jobId.length === 0) {
|
|
1286
|
+
throw new VectorError("E_PROTOCOL");
|
|
1287
|
+
}
|
|
1288
|
+
if (!Number.isSafeInteger(request.requestId) || request.requestId < 1) {
|
|
1289
|
+
throw new VectorError("E_PROTOCOL");
|
|
1290
|
+
}
|
|
1291
|
+
if (!Number.isSafeInteger(request.generation) || request.generation < 0) {
|
|
1292
|
+
throw new VectorError("E_PROTOCOL");
|
|
1293
|
+
}
|
|
1294
|
+
if (request.operation !== "image" && request.body === null) {
|
|
1295
|
+
return null;
|
|
1296
|
+
}
|
|
1297
|
+
let input;
|
|
1298
|
+
if (request.operation === "image") {
|
|
1299
|
+
if (!(request.bytes instanceof Uint8Array)) {
|
|
1300
|
+
throw new VectorError("E_INPUT");
|
|
1301
|
+
}
|
|
1302
|
+
input = {
|
|
1303
|
+
bytes: new Uint8Array(request.bytes),
|
|
1304
|
+
mime: request.mime
|
|
1305
|
+
};
|
|
1306
|
+
} else {
|
|
1307
|
+
input = {
|
|
1308
|
+
text: request.body,
|
|
1309
|
+
title: request.title
|
|
1310
|
+
};
|
|
1311
|
+
}
|
|
1312
|
+
const responseBuffer = createResponseBuffer();
|
|
1313
|
+
const message = {
|
|
1314
|
+
protocolVersion: 1,
|
|
1315
|
+
jobId: request.jobId,
|
|
1316
|
+
requestId: request.requestId,
|
|
1317
|
+
generation: request.generation,
|
|
1318
|
+
operation: request.operation,
|
|
1319
|
+
input,
|
|
1320
|
+
responseBuffer
|
|
1321
|
+
};
|
|
1322
|
+
try {
|
|
1323
|
+
port.postMessage(message);
|
|
1324
|
+
} catch {
|
|
1325
|
+
throw new VectorError("E_INFERENCE");
|
|
1326
|
+
}
|
|
1327
|
+
const deadline = performance.now() + timeoutMs;
|
|
1328
|
+
const bridgeRes = waitResponse(responseBuffer, cancellationBuffer, deadline);
|
|
1329
|
+
if (bridgeRes.errorId !== 0) {
|
|
1330
|
+
const code = ERROR_ID_MAP[bridgeRes.errorId] ?? "E_PROTOCOL";
|
|
1331
|
+
throw new VectorError(code);
|
|
1332
|
+
}
|
|
1333
|
+
return new Uint8Array(bridgeRes.payload);
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
// src/runtime-assets/model-contract.ts
|
|
1337
|
+
var MODEL_REVISION = "daa72c51243991dfcaf9f9137d2c573d8f7790c0";
|
|
1338
|
+
var MODEL_ASSET_FILES = [
|
|
1339
|
+
{ path: "onnx/model_q4.onnx", source: "model_q4.onnx", mime: "application/octet-stream" },
|
|
1340
|
+
{ path: "onnx/model_q4.onnx_data", source: "model_q4.onnx_data", mime: "application/octet-stream" },
|
|
1341
|
+
{ path: "onnx/vision_encoder_q4.onnx", source: "vision_encoder_q4.onnx", mime: "application/octet-stream" },
|
|
1342
|
+
{ path: "onnx/vision_encoder_q4.onnx_data", source: "vision_encoder_q4.onnx_data", mime: "application/octet-stream" },
|
|
1343
|
+
{ path: "config.json", source: "config.json", mime: "application/json" },
|
|
1344
|
+
{ path: "processor_config.json", source: "processor_config.json", mime: "application/json" },
|
|
1345
|
+
{ path: "preprocessor_config.json", source: "preprocessor_config.json", mime: "application/json" },
|
|
1346
|
+
{ path: "tokenizer.json", source: "tokenizer.json", mime: "application/json" },
|
|
1347
|
+
{ path: "tokenizer_config.json", source: "tokenizer_config.json", mime: "application/json" },
|
|
1348
|
+
{ path: "config_sentence_transformers.json", source: "config_sentence_transformers.json", mime: "application/json" },
|
|
1349
|
+
{ path: "chat_template.jinja", source: "chat_template.jinja", mime: "text/plain" }
|
|
1350
|
+
];
|
|
1351
|
+
var ALLOWED_PATH_SET = new Set(MODEL_ASSET_FILES.map((a) => a.path));
|
|
1352
|
+
|
|
1353
|
+
// src/official/node-inference.ts
|
|
1354
|
+
async function createNodeInferenceSession(options, packageRoot2) {
|
|
1355
|
+
const workerPath = resolve(packageRoot2, "dist/workers/inference-node.js");
|
|
1356
|
+
const manifestPath = resolve(packageRoot2, "manifests/embeddinggemma2-q4.json");
|
|
1357
|
+
let manifest;
|
|
1358
|
+
try {
|
|
1359
|
+
manifest = JSON.parse(await readFile(manifestPath, "utf8"));
|
|
1360
|
+
} catch {
|
|
1361
|
+
manifest = {
|
|
1362
|
+
modelId: "google/embeddinggemma-2",
|
|
1363
|
+
fingerprint: "5e730f96377d880c7ca94c9ddc9cd5f600e5237e106f5e4dc7d9448140026ac7"
|
|
1364
|
+
};
|
|
1365
|
+
}
|
|
1366
|
+
const healthBuffer = new SharedArrayBuffer(4);
|
|
1367
|
+
const worker = new Worker(workerPath, {
|
|
1368
|
+
workerData: {
|
|
1369
|
+
kind: "initialize",
|
|
1370
|
+
backend: options.backend,
|
|
1371
|
+
network: options.model.network,
|
|
1372
|
+
modelBaseUrl: options.model.baseUrl,
|
|
1373
|
+
generation: 1,
|
|
1374
|
+
healthBuffer,
|
|
1375
|
+
cacheDirectory: options.model.cacheDirectory
|
|
1376
|
+
}
|
|
1377
|
+
});
|
|
1378
|
+
await new Promise((res, rej) => {
|
|
1379
|
+
const timer = setTimeout(() => {
|
|
1380
|
+
worker.terminate();
|
|
1381
|
+
rej(new VectorError("E_TIMEOUT"));
|
|
1382
|
+
}, options.initTimeoutMs);
|
|
1383
|
+
const onMessage = (msg) => {
|
|
1384
|
+
const data = msg;
|
|
1385
|
+
if (data?.kind === "ready") {
|
|
1386
|
+
clearTimeout(timer);
|
|
1387
|
+
worker.off("message", onMessage);
|
|
1388
|
+
worker.off("error", onError);
|
|
1389
|
+
res();
|
|
1390
|
+
} else if (data?.kind === "failed") {
|
|
1391
|
+
clearTimeout(timer);
|
|
1392
|
+
console.error("Worker reported failed:", data.error || data.code);
|
|
1393
|
+
worker.terminate();
|
|
1394
|
+
rej(new VectorError("E_INFERENCE"));
|
|
1395
|
+
}
|
|
1396
|
+
};
|
|
1397
|
+
const onError = (err) => {
|
|
1398
|
+
clearTimeout(timer);
|
|
1399
|
+
worker.terminate();
|
|
1400
|
+
rej(err instanceof VectorError ? err : new VectorError("E_INFERENCE"));
|
|
1401
|
+
};
|
|
1402
|
+
worker.on("message", onMessage);
|
|
1403
|
+
worker.on("error", onError);
|
|
1404
|
+
});
|
|
1405
|
+
let closed = false;
|
|
1406
|
+
const cancellationBuffer = new SharedArrayBuffer(4);
|
|
1407
|
+
let requestIdCounter = 1;
|
|
1408
|
+
return {
|
|
1409
|
+
infer: (req) => {
|
|
1410
|
+
if (closed) throw new VectorError("E_INFERENCE");
|
|
1411
|
+
const res = requestEmbedding(
|
|
1412
|
+
worker,
|
|
1413
|
+
{
|
|
1414
|
+
jobId: `node-${Date.now()}`,
|
|
1415
|
+
requestId: requestIdCounter++,
|
|
1416
|
+
generation: 1,
|
|
1417
|
+
operation: req.operation,
|
|
1418
|
+
body: req.body,
|
|
1419
|
+
title: req.title,
|
|
1420
|
+
bytes: req.bytes,
|
|
1421
|
+
mime: req.mime
|
|
1422
|
+
},
|
|
1423
|
+
cancellationBuffer,
|
|
1424
|
+
options.sqlTimeoutMs
|
|
1425
|
+
);
|
|
1426
|
+
return res;
|
|
1427
|
+
},
|
|
1428
|
+
close: async () => {
|
|
1429
|
+
if (closed) return;
|
|
1430
|
+
closed = true;
|
|
1431
|
+
try {
|
|
1432
|
+
worker.postMessage({ kind: "close" });
|
|
1433
|
+
await worker.terminate();
|
|
1434
|
+
} catch {
|
|
1435
|
+
}
|
|
1436
|
+
},
|
|
1437
|
+
identity: {
|
|
1438
|
+
modelId: "embeddinggemma-2",
|
|
1439
|
+
revision: MODEL_REVISION,
|
|
1440
|
+
fingerprint: manifest.fingerprint,
|
|
1441
|
+
profile: "embeddinggemma-2/q4/768",
|
|
1442
|
+
backend: options.backend,
|
|
1443
|
+
runtimeGeneration: 1
|
|
1444
|
+
},
|
|
1445
|
+
information: {
|
|
1446
|
+
ready: true,
|
|
1447
|
+
modelId: manifest.modelId,
|
|
1448
|
+
dtype: "q4",
|
|
1449
|
+
dimension: 768,
|
|
1450
|
+
backend: options.backend,
|
|
1451
|
+
fingerprint: manifest.fingerprint
|
|
1452
|
+
}
|
|
1453
|
+
};
|
|
1454
|
+
}
|
|
1455
|
+
|
|
1456
|
+
// src/official/node-vfs.ts
|
|
1457
|
+
import * as crypto2 from "node:crypto";
|
|
1458
|
+
|
|
1459
|
+
// src/official/node-files.ts
|
|
1460
|
+
import fs from "node:fs";
|
|
1461
|
+
import path from "node:path";
|
|
1462
|
+
import os from "node:os";
|
|
1463
|
+
function canonicalNodeSqlitePath(filename) {
|
|
1464
|
+
if (filename.includes("\0")) {
|
|
1465
|
+
throw new VectorError("E_STORAGE");
|
|
1466
|
+
}
|
|
1467
|
+
const resolved = path.resolve(filename);
|
|
1468
|
+
const dir = path.dirname(resolved);
|
|
1469
|
+
const base = path.basename(resolved);
|
|
1470
|
+
if (!fs.existsSync(dir)) {
|
|
1471
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
1472
|
+
}
|
|
1473
|
+
let realDir;
|
|
1474
|
+
try {
|
|
1475
|
+
realDir = fs.realpathSync.native(dir);
|
|
1476
|
+
} catch {
|
|
1477
|
+
throw new VectorError("E_STORAGE");
|
|
1478
|
+
}
|
|
1479
|
+
return path.join(realDir, base);
|
|
1480
|
+
}
|
|
1481
|
+
var NodeSqliteFiles = class {
|
|
1482
|
+
files = /* @__PURE__ */ new Map();
|
|
1483
|
+
mainLocks = /* @__PURE__ */ new Map();
|
|
1484
|
+
/**
|
|
1485
|
+
* 処理名: ファイルオープン
|
|
1486
|
+
* 処理概要: オプションに従ってファイルを開き、メイン DB の重複ロック検査およびシンボリックリンク検証を行う。
|
|
1487
|
+
* @param identifier - VFS が割り当てるファイル識別子。
|
|
1488
|
+
* @param filename - ファイルパス (null の場合は一時ファイル)。
|
|
1489
|
+
* @param options - オープンオプション。
|
|
1490
|
+
*/
|
|
1491
|
+
open(identifier, filename, options) {
|
|
1492
|
+
let canonicalPath;
|
|
1493
|
+
let removeOnClose = options.removeOnClose;
|
|
1494
|
+
if (filename === null) {
|
|
1495
|
+
const tempName = `sqlite-temp-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`;
|
|
1496
|
+
canonicalPath = path.join(os.tmpdir(), tempName);
|
|
1497
|
+
removeOnClose = true;
|
|
1498
|
+
} else {
|
|
1499
|
+
canonicalPath = canonicalNodeSqlitePath(filename);
|
|
1500
|
+
if (options.main) {
|
|
1501
|
+
const existingHolder = this.mainLocks.get(canonicalPath);
|
|
1502
|
+
if (existingHolder !== void 0 && existingHolder !== identifier) {
|
|
1503
|
+
throw new VectorError("E_DATABASE_LOCKED");
|
|
1504
|
+
}
|
|
1505
|
+
if (fs.existsSync(canonicalPath)) {
|
|
1506
|
+
const lstat = fs.lstatSync(canonicalPath);
|
|
1507
|
+
if (lstat.isSymbolicLink()) {
|
|
1508
|
+
throw new VectorError("E_STORAGE");
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1512
|
+
}
|
|
1513
|
+
let flags = fs.constants.O_RDWR;
|
|
1514
|
+
if (options.readonly) {
|
|
1515
|
+
flags = fs.constants.O_RDONLY;
|
|
1516
|
+
} else if (options.create) {
|
|
1517
|
+
flags = fs.constants.O_RDWR | fs.constants.O_CREAT;
|
|
1518
|
+
}
|
|
1519
|
+
let fd;
|
|
1520
|
+
try {
|
|
1521
|
+
fd = fs.openSync(canonicalPath, flags, 384);
|
|
1522
|
+
const stat = fs.fstatSync(fd);
|
|
1523
|
+
if (!stat.isFile()) {
|
|
1524
|
+
fs.closeSync(fd);
|
|
1525
|
+
throw new VectorError("E_STORAGE");
|
|
1526
|
+
}
|
|
1527
|
+
} catch (err) {
|
|
1528
|
+
if (err instanceof VectorError) throw err;
|
|
1529
|
+
throw new VectorError("E_STORAGE");
|
|
1530
|
+
}
|
|
1531
|
+
if (options.main) {
|
|
1532
|
+
this.mainLocks.set(canonicalPath, identifier);
|
|
1533
|
+
}
|
|
1534
|
+
this.files.set(identifier, {
|
|
1535
|
+
fd,
|
|
1536
|
+
canonicalPath,
|
|
1537
|
+
removeOnClose,
|
|
1538
|
+
main: options.main
|
|
1539
|
+
});
|
|
1540
|
+
}
|
|
1541
|
+
/**
|
|
1542
|
+
* 処理名: ファイル読み取り
|
|
1543
|
+
* 処理概要: 指定オフセットからバッファへ読み出し、ファイル末尾以降はゼロ埋めを行う。
|
|
1544
|
+
* @param identifier - ファイル識別子。
|
|
1545
|
+
* @param buffer - 読み込み先バッファ。
|
|
1546
|
+
* @param offset - 読み取り開始ファイルオフセット。
|
|
1547
|
+
* @returns 実際に読み取られた有効バイト数。
|
|
1548
|
+
*/
|
|
1549
|
+
read(identifier, buffer, offset) {
|
|
1550
|
+
const file = this.files.get(identifier);
|
|
1551
|
+
if (!file) throw new VectorError("E_STORAGE");
|
|
1552
|
+
let bytesRead = 0;
|
|
1553
|
+
try {
|
|
1554
|
+
bytesRead = fs.readSync(file.fd, buffer, 0, buffer.byteLength, offset);
|
|
1555
|
+
} catch {
|
|
1556
|
+
throw new VectorError("E_STORAGE");
|
|
1557
|
+
}
|
|
1558
|
+
if (bytesRead < buffer.byteLength) {
|
|
1559
|
+
buffer.fill(0, bytesRead);
|
|
1560
|
+
}
|
|
1561
|
+
return bytesRead;
|
|
1562
|
+
}
|
|
1563
|
+
/**
|
|
1564
|
+
* 処理名: ファイル書き込み
|
|
1565
|
+
* 処理概要: バッファの内容を指定オフセットへ書き込む。
|
|
1566
|
+
* @param identifier - ファイル識別子。
|
|
1567
|
+
* @param buffer - 書き込み元バッファ。
|
|
1568
|
+
* @param offset - 書き込み開始ファイルオフセット。
|
|
1569
|
+
*/
|
|
1570
|
+
write(identifier, buffer, offset) {
|
|
1571
|
+
const file = this.files.get(identifier);
|
|
1572
|
+
if (!file) throw new VectorError("E_STORAGE");
|
|
1573
|
+
try {
|
|
1574
|
+
fs.writeSync(file.fd, buffer, 0, buffer.byteLength, offset);
|
|
1575
|
+
} catch {
|
|
1576
|
+
throw new VectorError("E_STORAGE");
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
/**
|
|
1580
|
+
* 処理名: ファイルディスク同期
|
|
1581
|
+
* 処理概要: ファイルの変更内容をディスクへフラッシュする。
|
|
1582
|
+
* @param identifier - ファイル識別子。
|
|
1583
|
+
*/
|
|
1584
|
+
sync(identifier) {
|
|
1585
|
+
const file = this.files.get(identifier);
|
|
1586
|
+
if (!file) throw new VectorError("E_STORAGE");
|
|
1587
|
+
try {
|
|
1588
|
+
fs.fsyncSync(file.fd);
|
|
1589
|
+
} catch {
|
|
1590
|
+
throw new VectorError("E_STORAGE");
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
/**
|
|
1594
|
+
* 処理名: ファイルサイズ切り捨て
|
|
1595
|
+
* 処理概要: ファイルサイズを指定バイト数へ切り詰める。
|
|
1596
|
+
* @param identifier - ファイル識別子。
|
|
1597
|
+
* @param size - 切り詰め後サイズ。
|
|
1598
|
+
*/
|
|
1599
|
+
truncate(identifier, size) {
|
|
1600
|
+
const file = this.files.get(identifier);
|
|
1601
|
+
if (!file) throw new VectorError("E_STORAGE");
|
|
1602
|
+
try {
|
|
1603
|
+
fs.ftruncateSync(file.fd, size);
|
|
1604
|
+
} catch {
|
|
1605
|
+
throw new VectorError("E_STORAGE");
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
/**
|
|
1609
|
+
* 処理名: ファイルサイズ取得
|
|
1610
|
+
* 処理概要: 現在のファイルサイズをバイト単位で返す。
|
|
1611
|
+
* @param identifier - ファイル識別子。
|
|
1612
|
+
* @returns ファイルサイズ。
|
|
1613
|
+
*/
|
|
1614
|
+
size(identifier) {
|
|
1615
|
+
const file = this.files.get(identifier);
|
|
1616
|
+
if (!file) throw new VectorError("E_STORAGE");
|
|
1617
|
+
try {
|
|
1618
|
+
return fs.fstatSync(file.fd).size;
|
|
1619
|
+
} catch {
|
|
1620
|
+
throw new VectorError("E_STORAGE");
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
/**
|
|
1624
|
+
* 処理名: ファイルアクセス確認
|
|
1625
|
+
* 処理概要: ファイルの存在および読み書き権限を確認する。
|
|
1626
|
+
* @param filename - ファイルパス。
|
|
1627
|
+
* @param writable - 書き込み権限が必要かどうか。
|
|
1628
|
+
* @returns アクセス可能なら true。
|
|
1629
|
+
*/
|
|
1630
|
+
accessible(filename, writable) {
|
|
1631
|
+
try {
|
|
1632
|
+
const mode = writable ? fs.constants.W_OK : fs.constants.R_OK;
|
|
1633
|
+
fs.accessSync(filename, mode);
|
|
1634
|
+
return true;
|
|
1635
|
+
} catch {
|
|
1636
|
+
return false;
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
/**
|
|
1640
|
+
* 処理名: ファイル削除
|
|
1641
|
+
* 処理概要: 指定されたファイルをディスクから削除する。
|
|
1642
|
+
* @param filename - ファイルパス。
|
|
1643
|
+
*/
|
|
1644
|
+
delete(filename) {
|
|
1645
|
+
try {
|
|
1646
|
+
const canonical = canonicalNodeSqlitePath(filename);
|
|
1647
|
+
fs.unlinkSync(canonical);
|
|
1648
|
+
} catch {
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
/**
|
|
1652
|
+
* 処理名: ファイルクローズ
|
|
1653
|
+
* 処理概要: ファイル記述子を閉じ、ロックを解放し、一時ファイルであれば削除する。
|
|
1654
|
+
* @param identifier - ファイル識別子。
|
|
1655
|
+
*/
|
|
1656
|
+
close(identifier) {
|
|
1657
|
+
const file = this.files.get(identifier);
|
|
1658
|
+
if (!file) throw new VectorError("E_STORAGE");
|
|
1659
|
+
try {
|
|
1660
|
+
fs.closeSync(file.fd);
|
|
1661
|
+
} catch {
|
|
1662
|
+
}
|
|
1663
|
+
if (file.main) {
|
|
1664
|
+
this.mainLocks.delete(file.canonicalPath);
|
|
1665
|
+
}
|
|
1666
|
+
if (file.removeOnClose) {
|
|
1667
|
+
try {
|
|
1668
|
+
fs.unlinkSync(file.canonicalPath);
|
|
1669
|
+
} catch {
|
|
1670
|
+
}
|
|
1671
|
+
}
|
|
1672
|
+
this.files.delete(identifier);
|
|
1673
|
+
}
|
|
1674
|
+
/**
|
|
1675
|
+
* 処理名: 全ファイル破棄
|
|
1676
|
+
* 処理概要: 残存するすべてのオープンファイルをクローズし、一時ファイルを削除する。
|
|
1677
|
+
*/
|
|
1678
|
+
dispose() {
|
|
1679
|
+
for (const id of Array.from(this.files.keys())) {
|
|
1680
|
+
try {
|
|
1681
|
+
this.close(id);
|
|
1682
|
+
} catch {
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
}
|
|
1686
|
+
};
|
|
1687
|
+
|
|
1688
|
+
// src/official/node-file-ownership.ts
|
|
1689
|
+
import * as crypto from "node:crypto";
|
|
1690
|
+
import * as os2 from "node:os";
|
|
1691
|
+
import * as path2 from "node:path";
|
|
1692
|
+
import { Worker as Worker2 } from "node:worker_threads";
|
|
1693
|
+
function getOwnershipPipePath(canonicalPath) {
|
|
1694
|
+
const norm = process.platform === "win32" ? canonicalPath.toLowerCase() : canonicalPath;
|
|
1695
|
+
const hash = crypto.createHash("sha256").update(norm).digest("hex");
|
|
1696
|
+
if (process.platform === "win32") {
|
|
1697
|
+
return `\\\\.\\pipe\\svw-sqlite-${hash}`;
|
|
1698
|
+
}
|
|
1699
|
+
return path2.join(os2.tmpdir(), `svw-sqlite-${hash}.sock`);
|
|
1700
|
+
}
|
|
1701
|
+
var HELPER_WORKER_CODE = `
|
|
1702
|
+
const { workerData, parentPort } = require("node:worker_threads");
|
|
1703
|
+
const net = require("node:net");
|
|
1704
|
+
const fs = require("node:fs");
|
|
1705
|
+
|
|
1706
|
+
const { pipePath, sab } = workerData;
|
|
1707
|
+
const int32 = new Int32Array(sab);
|
|
1708
|
+
|
|
1709
|
+
const server = net.createServer();
|
|
1710
|
+
|
|
1711
|
+
server.once("error", (err) => {
|
|
1712
|
+
if (err.code === "EADDRINUSE") {
|
|
1713
|
+
Atomics.store(int32, 0, 2);
|
|
1714
|
+
} else {
|
|
1715
|
+
Atomics.store(int32, 0, 3);
|
|
1716
|
+
}
|
|
1717
|
+
Atomics.notify(int32, 0);
|
|
1718
|
+
});
|
|
1719
|
+
|
|
1720
|
+
server.listen(pipePath, () => {
|
|
1721
|
+
Atomics.store(int32, 0, 1);
|
|
1722
|
+
Atomics.notify(int32, 0);
|
|
1723
|
+
});
|
|
1724
|
+
|
|
1725
|
+
if (parentPort) {
|
|
1726
|
+
parentPort.on("message", (msg) => {
|
|
1727
|
+
if (msg && msg.kind === "release") {
|
|
1728
|
+
server.close(() => {
|
|
1729
|
+
if (process.platform !== "win32") {
|
|
1730
|
+
try { fs.unlinkSync(pipePath); } catch {}
|
|
1731
|
+
}
|
|
1732
|
+
Atomics.store(int32, 0, 4);
|
|
1733
|
+
Atomics.notify(int32, 0);
|
|
1734
|
+
});
|
|
1735
|
+
}
|
|
1736
|
+
});
|
|
1737
|
+
}
|
|
1738
|
+
`;
|
|
1739
|
+
var NodeFileOwnership = class {
|
|
1740
|
+
pipePath;
|
|
1741
|
+
worker;
|
|
1742
|
+
sab;
|
|
1743
|
+
int32;
|
|
1744
|
+
released = false;
|
|
1745
|
+
/**
|
|
1746
|
+
* 処理名: NodeFileOwnership コンストラクタ
|
|
1747
|
+
* 処理概要: ヘルパー Worker を起動し、最大 10000ms で排他リスナーの取得を待機する。
|
|
1748
|
+
* @param canonicalPath - 排他対象ファイルの正規化絶対パス。
|
|
1749
|
+
*/
|
|
1750
|
+
constructor(canonicalPath) {
|
|
1751
|
+
this.pipePath = getOwnershipPipePath(canonicalPath);
|
|
1752
|
+
this.sab = new SharedArrayBuffer(4);
|
|
1753
|
+
this.int32 = new Int32Array(this.sab);
|
|
1754
|
+
try {
|
|
1755
|
+
this.worker = new Worker2(HELPER_WORKER_CODE, {
|
|
1756
|
+
eval: true,
|
|
1757
|
+
execArgv: [],
|
|
1758
|
+
workerData: {
|
|
1759
|
+
pipePath: this.pipePath,
|
|
1760
|
+
sab: this.sab
|
|
1761
|
+
}
|
|
1762
|
+
});
|
|
1763
|
+
} catch {
|
|
1764
|
+
throw new VectorError("E_STORAGE");
|
|
1765
|
+
}
|
|
1766
|
+
const waitRes = Atomics.wait(this.int32, 0, 0, 1e4);
|
|
1767
|
+
const status = Atomics.load(this.int32, 0);
|
|
1768
|
+
if (waitRes === "timed-out" || status === 0) {
|
|
1769
|
+
this.worker.terminate();
|
|
1770
|
+
throw new VectorError("E_STORAGE");
|
|
1771
|
+
}
|
|
1772
|
+
if (status === 2) {
|
|
1773
|
+
this.worker.terminate();
|
|
1774
|
+
throw new VectorError("E_DATABASE_LOCKED");
|
|
1775
|
+
}
|
|
1776
|
+
if (status !== 1) {
|
|
1777
|
+
this.worker.terminate();
|
|
1778
|
+
throw new VectorError("E_STORAGE");
|
|
1779
|
+
}
|
|
1780
|
+
}
|
|
1781
|
+
/**
|
|
1782
|
+
* 処理名: 排他所有権解放
|
|
1783
|
+
* 処理概要: ヘルパー Worker へ終了を通知し、リスナーのクローズを最大 10000ms 待機して Worker を終了する。
|
|
1784
|
+
* 実装理由: 正常クローズ時にカーネル資源を即座に解放し、後続接続を可能にするため。
|
|
1785
|
+
*/
|
|
1786
|
+
release() {
|
|
1787
|
+
if (this.released) return;
|
|
1788
|
+
this.released = true;
|
|
1789
|
+
try {
|
|
1790
|
+
this.worker.postMessage({ kind: "release" });
|
|
1791
|
+
const waitRes = Atomics.wait(this.int32, 0, 1, 1e4);
|
|
1792
|
+
const status = Atomics.load(this.int32, 0);
|
|
1793
|
+
if (waitRes === "timed-out" || status !== 4) {
|
|
1794
|
+
this.worker.terminate();
|
|
1795
|
+
throw new VectorError("E_STORAGE");
|
|
1796
|
+
}
|
|
1797
|
+
} finally {
|
|
1798
|
+
this.worker.terminate();
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1801
|
+
};
|
|
1802
|
+
|
|
1803
|
+
// src/official/node-vfs.ts
|
|
1804
|
+
var VFS_NAME = "node-file";
|
|
1805
|
+
function installNodeFileVfs(sqlite3) {
|
|
1806
|
+
const wasm = sqlite3.wasm;
|
|
1807
|
+
const capi = sqlite3.capi;
|
|
1808
|
+
const files = new NodeSqliteFiles();
|
|
1809
|
+
let idCounter = 1;
|
|
1810
|
+
const pFileToEntry = /* @__PURE__ */ new Map();
|
|
1811
|
+
const ioMethods = {
|
|
1812
|
+
xClose: (pFile) => {
|
|
1813
|
+
const entry = pFileToEntry.get(pFile);
|
|
1814
|
+
if (!entry) return capi.SQLITE_OK;
|
|
1815
|
+
pFileToEntry.delete(pFile);
|
|
1816
|
+
try {
|
|
1817
|
+
files.close(entry.identifier);
|
|
1818
|
+
} catch {
|
|
1819
|
+
}
|
|
1820
|
+
if (entry.ownership) {
|
|
1821
|
+
try {
|
|
1822
|
+
entry.ownership.release();
|
|
1823
|
+
} catch {
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1826
|
+
return capi.SQLITE_OK;
|
|
1827
|
+
},
|
|
1828
|
+
xRead: (pFile, pDest, n, offset64) => {
|
|
1829
|
+
const entry = pFileToEntry.get(pFile);
|
|
1830
|
+
if (!entry) return capi.SQLITE_IOERR;
|
|
1831
|
+
const offset = Number(offset64);
|
|
1832
|
+
const buf = new Uint8Array(n);
|
|
1833
|
+
try {
|
|
1834
|
+
const bytesRead = files.read(entry.identifier, buf, offset);
|
|
1835
|
+
const heap = wasm.heap8u();
|
|
1836
|
+
heap.set(buf, Number(pDest));
|
|
1837
|
+
if (bytesRead < n) {
|
|
1838
|
+
return capi.SQLITE_IOERR_SHORT_READ;
|
|
1839
|
+
}
|
|
1840
|
+
return capi.SQLITE_OK;
|
|
1841
|
+
} catch {
|
|
1842
|
+
return capi.SQLITE_IOERR_READ;
|
|
1843
|
+
}
|
|
1844
|
+
},
|
|
1845
|
+
xWrite: (pFile, pSrc, n, offset64) => {
|
|
1846
|
+
const entry = pFileToEntry.get(pFile);
|
|
1847
|
+
if (!entry) return capi.SQLITE_IOERR;
|
|
1848
|
+
const offset = Number(offset64);
|
|
1849
|
+
try {
|
|
1850
|
+
const heap = wasm.heap8u();
|
|
1851
|
+
const slice = heap.subarray(Number(pSrc), Number(pSrc) + n);
|
|
1852
|
+
files.write(entry.identifier, slice, offset);
|
|
1853
|
+
return capi.SQLITE_OK;
|
|
1854
|
+
} catch {
|
|
1855
|
+
return capi.SQLITE_IOERR_WRITE;
|
|
1856
|
+
}
|
|
1857
|
+
},
|
|
1858
|
+
xTruncate: (pFile, size64) => {
|
|
1859
|
+
const entry = pFileToEntry.get(pFile);
|
|
1860
|
+
if (!entry) return capi.SQLITE_IOERR;
|
|
1861
|
+
const size = Number(size64);
|
|
1862
|
+
try {
|
|
1863
|
+
files.truncate(entry.identifier, size);
|
|
1864
|
+
return capi.SQLITE_OK;
|
|
1865
|
+
} catch {
|
|
1866
|
+
return capi.SQLITE_IOERR_TRUNCATE;
|
|
1867
|
+
}
|
|
1868
|
+
},
|
|
1869
|
+
xSync: (pFile, _flags) => {
|
|
1870
|
+
const entry = pFileToEntry.get(pFile);
|
|
1871
|
+
if (!entry) return capi.SQLITE_IOERR;
|
|
1872
|
+
try {
|
|
1873
|
+
files.sync(entry.identifier);
|
|
1874
|
+
return capi.SQLITE_OK;
|
|
1875
|
+
} catch {
|
|
1876
|
+
return capi.SQLITE_IOERR_FSYNC;
|
|
1877
|
+
}
|
|
1878
|
+
},
|
|
1879
|
+
xFileSize: (pFile, pSize64) => {
|
|
1880
|
+
const entry = pFileToEntry.get(pFile);
|
|
1881
|
+
if (!entry) return capi.SQLITE_IOERR;
|
|
1882
|
+
try {
|
|
1883
|
+
const sz = files.size(entry.identifier);
|
|
1884
|
+
wasm.poke(pSize64, sz, "i64");
|
|
1885
|
+
return capi.SQLITE_OK;
|
|
1886
|
+
} catch {
|
|
1887
|
+
return capi.SQLITE_IOERR_FSTAT;
|
|
1888
|
+
}
|
|
1889
|
+
},
|
|
1890
|
+
xLock: (pFile, lockType) => {
|
|
1891
|
+
const entry = pFileToEntry.get(pFile);
|
|
1892
|
+
if (!entry) return capi.SQLITE_IOERR;
|
|
1893
|
+
entry.lockType = lockType;
|
|
1894
|
+
return capi.SQLITE_OK;
|
|
1895
|
+
},
|
|
1896
|
+
xUnlock: (pFile, lockType) => {
|
|
1897
|
+
const entry = pFileToEntry.get(pFile);
|
|
1898
|
+
if (!entry) return capi.SQLITE_IOERR;
|
|
1899
|
+
entry.lockType = lockType;
|
|
1900
|
+
return capi.SQLITE_OK;
|
|
1901
|
+
},
|
|
1902
|
+
xCheckReservedLock: (pFile, pOut) => {
|
|
1903
|
+
const entry = pFileToEntry.get(pFile);
|
|
1904
|
+
if (!entry) return capi.SQLITE_IOERR;
|
|
1905
|
+
wasm.poke32(pOut, entry.lockType > capi.SQLITE_LOCK_SHARED ? 1 : 0);
|
|
1906
|
+
return capi.SQLITE_OK;
|
|
1907
|
+
},
|
|
1908
|
+
xFileControl: (_pFile, _op, _pArg) => {
|
|
1909
|
+
return capi.SQLITE_NOTFOUND;
|
|
1910
|
+
},
|
|
1911
|
+
xSectorSize: (_pFile) => {
|
|
1912
|
+
return 4096;
|
|
1913
|
+
},
|
|
1914
|
+
xDeviceCharacteristics: (_pFile) => {
|
|
1915
|
+
return 0;
|
|
1916
|
+
}
|
|
1917
|
+
};
|
|
1918
|
+
const nodeIoMethods = new capi.sqlite3_io_methods();
|
|
1919
|
+
nodeIoMethods.$iVersion = 1;
|
|
1920
|
+
sqlite3.vfs.installVfs({
|
|
1921
|
+
io: { struct: nodeIoMethods, methods: ioMethods }
|
|
1922
|
+
});
|
|
1923
|
+
const vfsMethods = {
|
|
1924
|
+
xOpen: (pVfs, zName, pFile, flags, pOutFlags) => {
|
|
1925
|
+
const filename = zName ? wasm.cstrToJs(zName) : null;
|
|
1926
|
+
const isMainDb = (flags & capi.SQLITE_OPEN_MAIN_DB) !== 0;
|
|
1927
|
+
const isCreate = (flags & capi.SQLITE_OPEN_CREATE) !== 0;
|
|
1928
|
+
const isReadonly = (flags & capi.SQLITE_OPEN_READONLY) !== 0;
|
|
1929
|
+
const isDeleteOnClose = (flags & capi.SQLITE_OPEN_DELETEONCLOSE) !== 0;
|
|
1930
|
+
let ownership;
|
|
1931
|
+
if (isMainDb && filename) {
|
|
1932
|
+
try {
|
|
1933
|
+
const canonical = canonicalNodeSqlitePath(filename);
|
|
1934
|
+
ownership = new NodeFileOwnership(canonical);
|
|
1935
|
+
} catch (err) {
|
|
1936
|
+
if (err instanceof VectorError && err.code === "E_DATABASE_LOCKED") {
|
|
1937
|
+
return capi.SQLITE_BUSY;
|
|
1938
|
+
}
|
|
1939
|
+
return capi.SQLITE_CANTOPEN;
|
|
1940
|
+
}
|
|
1941
|
+
}
|
|
1942
|
+
const identifier = idCounter++;
|
|
1943
|
+
try {
|
|
1944
|
+
files.open(identifier, filename, {
|
|
1945
|
+
create: isCreate,
|
|
1946
|
+
readonly: isReadonly,
|
|
1947
|
+
main: isMainDb,
|
|
1948
|
+
removeOnClose: isDeleteOnClose || filename === null
|
|
1949
|
+
});
|
|
1950
|
+
} catch (err) {
|
|
1951
|
+
ownership?.release();
|
|
1952
|
+
if (err instanceof VectorError && err.code === "E_DATABASE_LOCKED") {
|
|
1953
|
+
return capi.SQLITE_BUSY;
|
|
1954
|
+
}
|
|
1955
|
+
return capi.SQLITE_CANTOPEN;
|
|
1956
|
+
}
|
|
1957
|
+
const sq3File = new capi.sqlite3_file(pFile);
|
|
1958
|
+
sq3File.$pMethods = nodeIoMethods.pointer;
|
|
1959
|
+
sq3File.dispose();
|
|
1960
|
+
pFileToEntry.set(pFile, {
|
|
1961
|
+
pFile,
|
|
1962
|
+
identifier,
|
|
1963
|
+
path: filename,
|
|
1964
|
+
flags,
|
|
1965
|
+
ownership,
|
|
1966
|
+
lockType: capi.SQLITE_LOCK_NONE
|
|
1967
|
+
});
|
|
1968
|
+
if (pOutFlags) {
|
|
1969
|
+
wasm.poke32(pOutFlags, flags);
|
|
1970
|
+
}
|
|
1971
|
+
return capi.SQLITE_OK;
|
|
1972
|
+
},
|
|
1973
|
+
xDelete: (_pVfs, zName, _syncDir) => {
|
|
1974
|
+
const filename = wasm.cstrToJs(zName);
|
|
1975
|
+
try {
|
|
1976
|
+
files.delete(filename);
|
|
1977
|
+
return capi.SQLITE_OK;
|
|
1978
|
+
} catch {
|
|
1979
|
+
return capi.SQLITE_IOERR_DELETE;
|
|
1980
|
+
}
|
|
1981
|
+
},
|
|
1982
|
+
xAccess: (_pVfs, zName, flags, pOut) => {
|
|
1983
|
+
const filename = wasm.cstrToJs(zName);
|
|
1984
|
+
const writable = (flags & capi.SQLITE_ACCESS_READWRITE) !== 0;
|
|
1985
|
+
const ok = files.accessible(filename, writable);
|
|
1986
|
+
wasm.poke32(pOut, ok ? 1 : 0);
|
|
1987
|
+
return capi.SQLITE_OK;
|
|
1988
|
+
},
|
|
1989
|
+
xFullPathname: (_pVfs, zName, nOut, pOut) => {
|
|
1990
|
+
const filename = wasm.cstrToJs(zName);
|
|
1991
|
+
try {
|
|
1992
|
+
const canonical = canonicalNodeSqlitePath(filename);
|
|
1993
|
+
const encoded = new TextEncoder().encode(canonical);
|
|
1994
|
+
if (encoded.length >= nOut) {
|
|
1995
|
+
return capi.SQLITE_CANTOPEN;
|
|
1996
|
+
}
|
|
1997
|
+
const heap = wasm.heap8u();
|
|
1998
|
+
heap.set(encoded, Number(pOut));
|
|
1999
|
+
heap[Number(pOut) + encoded.length] = 0;
|
|
2000
|
+
return capi.SQLITE_OK;
|
|
2001
|
+
} catch {
|
|
2002
|
+
return capi.SQLITE_CANTOPEN;
|
|
2003
|
+
}
|
|
2004
|
+
},
|
|
2005
|
+
xRandomness: (_pVfs, nOut, pOut) => {
|
|
2006
|
+
const heap = wasm.heap8u();
|
|
2007
|
+
const randomBuf = crypto2.randomBytes(nOut);
|
|
2008
|
+
heap.set(randomBuf, Number(pOut));
|
|
2009
|
+
return nOut;
|
|
2010
|
+
},
|
|
2011
|
+
xSleep: (_pVfs, microseconds) => {
|
|
2012
|
+
const ms = Math.ceil(microseconds / 1e3);
|
|
2013
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
2014
|
+
return capi.SQLITE_OK;
|
|
2015
|
+
},
|
|
2016
|
+
xCurrentTime: (_pVfs, pOut) => {
|
|
2017
|
+
wasm.poke(pOut, 24405875e-1 + Date.now() / 864e5, "double");
|
|
2018
|
+
return capi.SQLITE_OK;
|
|
2019
|
+
},
|
|
2020
|
+
xGetLastError: (_pVfs, _nOut, _pOut) => {
|
|
2021
|
+
return 0;
|
|
2022
|
+
}
|
|
2023
|
+
};
|
|
2024
|
+
const nodeVfs = new capi.sqlite3_vfs();
|
|
2025
|
+
nodeVfs.$iVersion = 1;
|
|
2026
|
+
nodeVfs.$szOsFile = capi.sqlite3_file.structInfo.sizeof;
|
|
2027
|
+
nodeVfs.$mxPathname = 1024;
|
|
2028
|
+
nodeVfs.addOnDispose(
|
|
2029
|
+
nodeVfs.$zName = wasm.allocCString(VFS_NAME)
|
|
2030
|
+
);
|
|
2031
|
+
sqlite3.vfs.installVfs({
|
|
2032
|
+
vfs: { struct: nodeVfs, methods: vfsMethods, asDefault: false }
|
|
2033
|
+
});
|
|
2034
|
+
let isClosed = false;
|
|
2035
|
+
return {
|
|
2036
|
+
close: () => {
|
|
2037
|
+
if (isClosed) return;
|
|
2038
|
+
isClosed = true;
|
|
2039
|
+
for (const entry of Array.from(pFileToEntry.values())) {
|
|
2040
|
+
try {
|
|
2041
|
+
files.close(entry.identifier);
|
|
2042
|
+
} catch {
|
|
2043
|
+
}
|
|
2044
|
+
try {
|
|
2045
|
+
entry.ownership?.release();
|
|
2046
|
+
} catch {
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
pFileToEntry.clear();
|
|
2050
|
+
files.dispose();
|
|
2051
|
+
try {
|
|
2052
|
+
capi.sqlite3_vfs_unregister(nodeVfs);
|
|
2053
|
+
nodeVfs.dispose();
|
|
2054
|
+
nodeIoMethods.dispose();
|
|
2055
|
+
} catch {
|
|
2056
|
+
}
|
|
2057
|
+
}
|
|
2058
|
+
};
|
|
2059
|
+
}
|
|
2060
|
+
|
|
2061
|
+
// src/official/node.ts
|
|
2062
|
+
function findPackageRoot(startDir) {
|
|
2063
|
+
let cur = path3.resolve(startDir);
|
|
2064
|
+
while (cur !== path3.dirname(cur)) {
|
|
2065
|
+
if (fs2.existsSync(path3.join(cur, "package.json"))) {
|
|
2066
|
+
return cur;
|
|
2067
|
+
}
|
|
2068
|
+
cur = path3.dirname(cur);
|
|
2069
|
+
}
|
|
2070
|
+
return path3.resolve(startDir, "../..");
|
|
2071
|
+
}
|
|
2072
|
+
var packageRoot = findPackageRoot(__dirname);
|
|
2073
|
+
function locateSqliteWasm(file) {
|
|
2074
|
+
if (file === "sqlite3.wasm") {
|
|
2075
|
+
const distPath = path3.resolve(packageRoot, "dist/sqlite3.wasm");
|
|
2076
|
+
if (fs2.existsSync(distPath)) {
|
|
2077
|
+
return distPath;
|
|
2078
|
+
}
|
|
2079
|
+
const downloadsPath = path3.resolve(packageRoot, "downloads/sqlite-official/sqlite3.wasm");
|
|
2080
|
+
if (fs2.existsSync(downloadsPath)) {
|
|
2081
|
+
return downloadsPath;
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
2084
|
+
return file;
|
|
2085
|
+
}
|
|
2086
|
+
var nodeOfficialFactory = async (options = {}) => {
|
|
2087
|
+
const customLocate = options.locateFile ?? locateSqliteWasm;
|
|
2088
|
+
const loaderPath = path3.resolve(packageRoot, "dist/sqlite3-node.mjs");
|
|
2089
|
+
const targetPath = fs2.existsSync(loaderPath) ? loaderPath : path3.resolve(packageRoot, "downloads/sqlite-official/sqlite3-node.mjs");
|
|
2090
|
+
const targetUrl = pathToFileURL(targetPath).href;
|
|
2091
|
+
const initFn = (await import(targetUrl)).default;
|
|
2092
|
+
const mergedOpts = {
|
|
2093
|
+
locateFile: customLocate,
|
|
2094
|
+
...options
|
|
2095
|
+
};
|
|
2096
|
+
return initFn(mergedOpts);
|
|
2097
|
+
};
|
|
2098
|
+
async function initialize(options) {
|
|
2099
|
+
const environment = {
|
|
2100
|
+
worker: false,
|
|
2101
|
+
runtime: "node",
|
|
2102
|
+
platform: process.platform,
|
|
2103
|
+
architecture: process.arch,
|
|
2104
|
+
nodeMajor: parseInt(process.versions.node.split(".")[0] || "24", 10)
|
|
2105
|
+
};
|
|
2106
|
+
const sqlite3 = await initializeOfficialRuntime(
|
|
2107
|
+
nodeOfficialFactory,
|
|
2108
|
+
options,
|
|
2109
|
+
environment,
|
|
2110
|
+
(opt) => createNodeInferenceSession(opt, packageRoot)
|
|
2111
|
+
);
|
|
2112
|
+
if (sqlite3.capi) {
|
|
2113
|
+
const vfsControl = installNodeFileVfs(sqlite3);
|
|
2114
|
+
const origClose = sqlite3.embedding.close.bind(sqlite3.embedding);
|
|
2115
|
+
sqlite3.embedding.close = async () => {
|
|
2116
|
+
try {
|
|
2117
|
+
await origClose();
|
|
2118
|
+
} finally {
|
|
2119
|
+
vfsControl.close();
|
|
2120
|
+
}
|
|
2121
|
+
};
|
|
2122
|
+
}
|
|
2123
|
+
return sqlite3;
|
|
2124
|
+
}
|
|
2125
|
+
|
|
2126
|
+
// src/index.ts
|
|
2127
|
+
var index_default = initialize;
|
|
2128
|
+
export {
|
|
2129
|
+
index_default as default
|
|
2130
|
+
};
|