@archildata/sqlite 0.0.0 → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js DELETED
@@ -1,430 +0,0 @@
1
- // src/index.ts
2
- import { exec as archilExec } from "disk";
3
-
4
- // src/adapter.ts
5
- import { Buffer } from "buffer";
6
- var DEFAULT_TIMEOUT_MS = 5e3;
7
- var WRITE_MOUNT_QUEUE_MS = 5e3;
8
- var RESULT_PREFIX = "ARCHIL_SQLITE_RESULT:";
9
- var DISK_EXEC_MOUNT_PATH = "/mnt/archil/disk";
10
- var REMOTE_RUNNER = `
11
- const { Buffer } = require("node:buffer");
12
- const { DatabaseSync } = require("node:sqlite");
13
- const fs = require("node:fs");
14
-
15
- const RESULT_PREFIX = ${JSON.stringify(RESULT_PREFIX)};
16
-
17
- function emit(payload) {
18
- const encoded = Buffer.from(JSON.stringify(payload), "utf8").toString("base64");
19
- console.log(RESULT_PREFIX + encoded);
20
- }
21
-
22
- function decodeValue(value) {
23
- switch (value.type) {
24
- case "null":
25
- return null;
26
- case "number":
27
- case "string":
28
- return value.value;
29
- case "bigint":
30
- return BigInt(value.value);
31
- case "bytes":
32
- return Buffer.from(value.value, "base64");
33
- default:
34
- throw new TypeError("unsupported SQLite parameter type: " + value.type);
35
- }
36
- }
37
-
38
- function encodeValue(value) {
39
- if (value === undefined) return { type: "undefined" };
40
- if (value === null) return { type: "null" };
41
- if (typeof value === "number") return { type: "number", value };
42
- if (typeof value === "string") return { type: "string", value };
43
- if (typeof value === "bigint") return { type: "bigint", value: value.toString() };
44
- if (value instanceof Uint8Array) {
45
- return { type: "bytes", value: Buffer.from(value.buffer, value.byteOffset, value.byteLength).toString("base64") };
46
- }
47
- if (Array.isArray(value)) return { type: "array", value: value.map(encodeValue) };
48
- if (typeof value === "object") {
49
- return {
50
- type: "object",
51
- value: Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, encodeValue(entry)])),
52
- };
53
- }
54
- throw new TypeError("unsupported SQLite result type: " + typeof value);
55
- }
56
-
57
- function executeOperation(db, operation) {
58
- const statement = db.prepare(operation.sql);
59
- const params = operation.params.map(decodeValue);
60
- switch (operation.method) {
61
- case "get":
62
- return statement.get(...params);
63
- case "all":
64
- return statement.all(...params);
65
- case "run":
66
- return statement.run(...params);
67
- }
68
- }
69
-
70
- function run(payload) {
71
- if (!fs.existsSync(payload.databasePath)) {
72
- const err = new Error("SQLite database does not exist at " + payload.displayPath);
73
- err.code = "SQLITE_DATABASE_NOT_FOUND";
74
- throw err;
75
- }
76
-
77
- const db = new DatabaseSync(payload.databasePath, {
78
- readOnly: payload.readOnly,
79
- timeout: payload.timeoutMs,
80
- readBigInts: payload.readBigInts,
81
- returnArrays: payload.returnArrays,
82
- });
83
-
84
- try {
85
- if (!payload.transaction) {
86
- return executeOperation(db, payload.operations[0]);
87
- }
88
-
89
- db.exec(payload.readOnly ? "BEGIN" : "BEGIN IMMEDIATE");
90
- try {
91
- const results = payload.operations.map((operation) => executeOperation(db, operation));
92
- db.exec("COMMIT");
93
- return results;
94
- } catch (err) {
95
- try {
96
- db.exec("ROLLBACK");
97
- } catch {}
98
- throw err;
99
- }
100
- } finally {
101
- db.close();
102
- }
103
- }
104
-
105
- try {
106
- const payload = JSON.parse(Buffer.from(process.argv[1], "base64").toString("utf8"));
107
- emit({ ok: true, result: encodeValue(run(payload)) });
108
- } catch (err) {
109
- emit({
110
- ok: false,
111
- error: {
112
- name: err && err.name,
113
- message: err && err.message,
114
- stack: err && err.stack,
115
- code: err && err.code,
116
- },
117
- });
118
- }
119
- `;
120
- var ArchilSQLiteError = class extends Error {
121
- code;
122
- remoteStack;
123
- constructor(message, opts = {}) {
124
- super(message);
125
- this.name = "ArchilSQLiteError";
126
- this.code = opts.code;
127
- this.remoteStack = opts.remoteStack;
128
- }
129
- };
130
- var operationStates = /* @__PURE__ */ new WeakMap();
131
- function deferredPromise() {
132
- let resolve;
133
- let reject;
134
- const promise = new Promise((promiseResolve, promiseReject) => {
135
- resolve = promiseResolve;
136
- reject = promiseReject;
137
- });
138
- promise.catch(() => {
139
- });
140
- return { promise, resolve, reject };
141
- }
142
- var SQLiteOperationImpl = class {
143
- constructor(executeRequest, request) {
144
- this.executeRequest = executeRequest;
145
- operationStates.set(this, {
146
- executeRequest,
147
- request
148
- });
149
- }
150
- executeRequest;
151
- execute() {
152
- const state = operationStates.get(this);
153
- if (!state) {
154
- throw new TypeError("unknown SQLite operation");
155
- }
156
- state.promise ??= this.executeRequest(state.request);
157
- return state.promise;
158
- }
159
- then(onfulfilled, onrejected) {
160
- return this.execute().then(onfulfilled, onrejected);
161
- }
162
- };
163
- var SQLiteQueryImpl = class {
164
- constructor(executeRequest, request) {
165
- this.executeRequest = executeRequest;
166
- this.request = request;
167
- }
168
- executeRequest;
169
- request;
170
- get() {
171
- return new SQLiteOperationImpl(this.executeRequest, {
172
- ...this.request,
173
- method: "get"
174
- });
175
- }
176
- all() {
177
- return new SQLiteOperationImpl(this.executeRequest, {
178
- ...this.request,
179
- method: "all"
180
- });
181
- }
182
- run() {
183
- return new SQLiteOperationImpl(this.executeRequest, {
184
- ...this.request,
185
- method: "run"
186
- });
187
- }
188
- };
189
- var SQLiteAdapter = class {
190
- constructor(exec, disk, database, options = {}) {
191
- this.exec = exec;
192
- this.disk = disk;
193
- this.database = database;
194
- this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
195
- this.readBigInts = options.readBigInts ?? false;
196
- this.returnArrays = options.returnArrays ?? false;
197
- }
198
- exec;
199
- disk;
200
- database;
201
- timeoutMs;
202
- readBigInts;
203
- returnArrays;
204
- read(strings, ...values) {
205
- return new SQLiteQueryImpl((request) => this.executeSingle(request), {
206
- kind: "read",
207
- sql: templateToSql(strings),
208
- params: values.map(encodeParameter)
209
- });
210
- }
211
- write(strings, ...values) {
212
- return new SQLiteQueryImpl((request) => this.executeSingle(request), {
213
- kind: "write",
214
- sql: templateToSql(strings),
215
- params: values.map(encodeParameter)
216
- });
217
- }
218
- async transaction(operations) {
219
- const states = operations.map((operation) => {
220
- const state = operationStates.get(operation);
221
- if (!state) {
222
- throw new TypeError("unknown SQLite operation");
223
- }
224
- return state;
225
- });
226
- const seen = /* @__PURE__ */ new Set();
227
- for (const state of states) {
228
- if (state.promise) {
229
- throw new TypeError("SQLite operation has already started");
230
- }
231
- if (seen.has(state)) {
232
- throw new TypeError("SQLite operation cannot be used more than once in a transaction");
233
- }
234
- seen.add(state);
235
- }
236
- const requests = states.map((state) => state.request);
237
- const readOnly = requests.every((request) => request.kind === "read");
238
- const deferreds = states.map(() => deferredPromise());
239
- states.forEach((state, index) => {
240
- state.promise = deferreds[index].promise;
241
- });
242
- try {
243
- const results = await this.executeRemote(requests, { transaction: true, readOnly });
244
- results.forEach((result, index) => {
245
- deferreds[index].resolve(result);
246
- });
247
- return results;
248
- } catch (err) {
249
- deferreds.forEach((deferred) => {
250
- deferred.reject(err);
251
- });
252
- throw err;
253
- }
254
- }
255
- executeSingle(request) {
256
- return this.executeRemote([request], {
257
- transaction: false,
258
- readOnly: request.kind === "read"
259
- }).then((results) => results[0]);
260
- }
261
- async executeRemote(operations, opts) {
262
- const payload = {
263
- databasePath: `${DISK_EXEC_MOUNT_PATH}/${this.database.path}`,
264
- displayPath: this.database.path,
265
- timeoutMs: this.timeoutMs,
266
- readBigInts: this.readBigInts,
267
- returnArrays: this.returnArrays,
268
- readOnly: opts.readOnly,
269
- transaction: opts.transaction,
270
- operations
271
- };
272
- const checkoutPaths = opts.readOnly || !this.database.directory ? void 0 : [this.database.directory];
273
- const queueMs = opts.readOnly ? void 0 : WRITE_MOUNT_QUEUE_MS;
274
- const mount = {
275
- disk: this.disk.id,
276
- readOnly: opts.readOnly,
277
- checkoutPaths,
278
- queueMs
279
- };
280
- const command = buildCommand(payload);
281
- const result = await this.exec({
282
- command,
283
- disks: { disk: mount }
284
- });
285
- const decoded = parseExecResult(result);
286
- return opts.transaction ? decoded : [decoded];
287
- }
288
- };
289
- function createSQLiteAdapter(exec) {
290
- return {
291
- async createDatabase(disk, databasePath, options = {}) {
292
- const database = normalizeDatabasePath(databasePath);
293
- const rootDirectory = database.directory ? `${DISK_EXEC_MOUNT_PATH}/${database.directory}` : DISK_EXEC_MOUNT_PATH;
294
- const mountedDatabasePath = `${rootDirectory}/${database.filename}`;
295
- const command = `mkdir -p ${shellQuote(rootDirectory)} && node --no-warnings -e ${shellQuote(CREATE_DATABASE_RUNNER)} ${shellQuote(mountedDatabasePath)}`;
296
- const result = await exec({
297
- command,
298
- disks: {
299
- disk: {
300
- disk: disk.id,
301
- readOnly: false,
302
- queueMs: WRITE_MOUNT_QUEUE_MS
303
- }
304
- }
305
- });
306
- if (result.exitCode !== 0) {
307
- throw new ArchilSQLiteError(
308
- `SQLite database creation failed with exit code ${result.exitCode}: ${result.stderr || result.stdout}`
309
- );
310
- }
311
- return new SQLiteAdapter(exec, disk, database, options);
312
- },
313
- async getDatabase(disk, databasePath, options = {}) {
314
- const database = normalizeDatabasePath(databasePath);
315
- return new SQLiteAdapter(exec, disk, database, options);
316
- }
317
- };
318
- }
319
- function templateToSql(strings) {
320
- let sql = strings[0] ?? "";
321
- for (let i = 1; i < strings.length; i++) {
322
- sql += "?" + strings[i];
323
- }
324
- return sql;
325
- }
326
- function normalizeDatabasePath(path) {
327
- if (path.endsWith("/")) {
328
- throw new TypeError("database path must include a file name and not end with '/'");
329
- }
330
- const segments = path.split("/").filter((segment) => segment.length > 0 && segment !== ".");
331
- if (segments.length === 0 || segments.some((segment) => segment === "..")) {
332
- throw new TypeError("database path must be a non-empty relative file path without '..'");
333
- }
334
- const filename = segments[segments.length - 1];
335
- const directorySegments = segments.slice(0, -1);
336
- return {
337
- path: segments.join("/"),
338
- directory: directorySegments.length > 0 ? directorySegments.join("/") : void 0,
339
- filename
340
- };
341
- }
342
- var CREATE_DATABASE_RUNNER = `
343
- const { DatabaseSync } = require("node:sqlite");
344
- const db = new DatabaseSync(process.argv[1]);
345
- db.close();
346
- `;
347
- function encodeParameter(value) {
348
- if (value === null) return { type: "null" };
349
- if (typeof value === "number") return { type: "number", value };
350
- if (typeof value === "string") return { type: "string", value };
351
- if (typeof value === "bigint") return { type: "bigint", value: value.toString() };
352
- if (value instanceof Uint8Array) {
353
- return {
354
- type: "bytes",
355
- value: Buffer.from(value.buffer, value.byteOffset, value.byteLength).toString("base64")
356
- };
357
- }
358
- if (value instanceof ArrayBuffer) {
359
- return { type: "bytes", value: Buffer.from(value).toString("base64") };
360
- }
361
- throw new TypeError(`unsupported SQLite parameter type: ${typeof value}`);
362
- }
363
- function decodeWireValue(value) {
364
- switch (value.type) {
365
- case "undefined":
366
- return void 0;
367
- case "null":
368
- return null;
369
- case "number":
370
- case "string":
371
- return value.value;
372
- case "bigint":
373
- return BigInt(value.value);
374
- case "bytes":
375
- return Uint8Array.from(Buffer.from(value.value, "base64"));
376
- case "array":
377
- return value.value.map(decodeWireValue);
378
- case "object":
379
- return Object.fromEntries(
380
- Object.entries(value.value).map(([key, entry]) => [key, decodeWireValue(entry)])
381
- );
382
- }
383
- }
384
- function buildCommand(payload) {
385
- const encodedPayload = Buffer.from(JSON.stringify(payload), "utf8").toString("base64");
386
- return `node --no-warnings -e ${shellQuote(REMOTE_RUNNER)} ${shellQuote(encodedPayload)}`;
387
- }
388
- function shellQuote(value) {
389
- return `'${value.replace(/'/g, "'\\''")}'`;
390
- }
391
- function parseExecResult(result) {
392
- if (result.exitCode !== 0) {
393
- throw new ArchilSQLiteError(
394
- `SQLite serverless execution failed with exit code ${result.exitCode}: ${result.stderr || result.stdout}`
395
- );
396
- }
397
- const line = result.stdout.split(/\r?\n/).reverse().find((entry) => entry.startsWith(RESULT_PREFIX));
398
- if (!line) {
399
- throw new ArchilSQLiteError("SQLite serverless execution did not return a result payload");
400
- }
401
- let parsed;
402
- try {
403
- parsed = JSON.parse(
404
- Buffer.from(line.slice(RESULT_PREFIX.length), "base64").toString("utf8")
405
- );
406
- } catch (err) {
407
- throw new ArchilSQLiteError(`SQLite serverless execution returned invalid JSON: ${err}`);
408
- }
409
- if (!parsed.ok) {
410
- throw new ArchilSQLiteError(parsed.error.message ?? "SQLite serverless execution failed", {
411
- code: parsed.error.code,
412
- remoteStack: parsed.error.stack
413
- });
414
- }
415
- return decodeWireValue(parsed.result);
416
- }
417
-
418
- // src/index.ts
419
- var sqlite = createSQLiteAdapter((opts) => archilExec(opts));
420
- function createDatabase(disk, databasePath, options) {
421
- return sqlite.createDatabase(disk, databasePath, options);
422
- }
423
- function getDatabase(disk, databasePath, options) {
424
- return sqlite.getDatabase(disk, databasePath, options);
425
- }
426
- export {
427
- ArchilSQLiteError,
428
- createDatabase,
429
- getDatabase
430
- };