@objectstack/driver-sqlite-wasm 17.0.0-rc.1 → 17.0.0-rc.2
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/CHANGELOG.md +206 -0
- package/dist/index.d.mts +15 -2
- package/dist/index.d.ts +15 -2
- package/dist/index.js +44 -33
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +44 -33
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,211 @@
|
|
|
1
1
|
# @objectstack/driver-sqlite-wasm
|
|
2
2
|
|
|
3
|
+
## 17.0.0-rc.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 9b43ee2: test(drivers): the filter-logic standard now covers the backend it was counted without (#4405)
|
|
8
|
+
|
|
9
|
+
`FILTER_LOGIC_CASES` (#3774) opens by calling itself the standard "the four
|
|
10
|
+
independent FilterCondition backends are each checked against". Five backends
|
|
11
|
+
exist. `driver-mongodb`'s `translateFilter` was missed, not excluded — an
|
|
12
|
+
independent implementation whose `$and`/`$or`/`$not` translation shares no line
|
|
13
|
+
of code with the SQL compiler or the in-memory matcher, and the only one whose
|
|
14
|
+
target language cannot spell the standard directly: MongoDB has no
|
|
15
|
+
document-level `$not` at all (the server answers `unknown top level operator:
|
|
16
|
+
$not`), so a negation has to leave as `$nor`, and a branch's own keys have to
|
|
17
|
+
stay in one document while `$and`/`$or` clauses are lifted beside them. That
|
|
18
|
+
route was never checked against the shared cases. Both DEBT rows the #4363 gate
|
|
19
|
+
recorded are now cleared, and `scripts/check-driver-conformance.mjs` reports
|
|
20
|
+
`ok` for every cell of the matrix.
|
|
21
|
+
|
|
22
|
+
**`driver-mongodb` runs the table twice, and the split is deliberate.**
|
|
23
|
+
`mongodb-filter-logic-translation.test.ts` drives every shared case through
|
|
24
|
+
`translateFilter` and evaluates the emitted MongoDB _document_ over the shared
|
|
25
|
+
fixture — a pure function, no server, so it always runs. That matters here more
|
|
26
|
+
than anywhere: `mongodb-memory-server` downloads a ~123 MB binary from
|
|
27
|
+
fastdl.mongodb.org, and a defect only a downloadable binary can catch is a
|
|
28
|
+
defect nobody catches on a restricted network. Its in-process reader is strict
|
|
29
|
+
by construction — every shape it does not model throws instead of evaluating to
|
|
30
|
+
true, a document-level `$not` included — and its own discrimination is pinned by
|
|
31
|
+
cases that require a widened document to FAIL the case it widens, so "all green"
|
|
32
|
+
cannot mean "the reader says yes to everything".
|
|
33
|
+
`mongodb-filter-logic-conformance.test.ts` runs the same table against a real
|
|
34
|
+
mongod and answers the one question the first half cannot — does MongoDB agree?
|
|
35
|
+
— skipping cleanly (never silently) when the binary is unreachable.
|
|
36
|
+
|
|
37
|
+
**`driver-sqlite-wasm` runs the table through its own engine.** It inherits
|
|
38
|
+
`SqlDriver`'s filter compiler, so nothing is re-implemented; what the suite pins
|
|
39
|
+
is that a nested `(… AND …) OR (… AND …)` survives the custom sql.js dialect
|
|
40
|
+
that compiles, binds and marshals it — the same seam its temporal and pagination
|
|
41
|
+
suites cover for their clauses. Tracked as DEBT rather than EXEMPT because
|
|
42
|
+
"inherits, therefore fine" is the assumption those suites exist to disprove; the
|
|
43
|
+
suite is what disproves it.
|
|
44
|
+
|
|
45
|
+
**No divergence was found.** `translateFilter` answers all seventeen shared
|
|
46
|
+
cases correctly today, `$not`-inside-a-branch and nested `$and`-inside-`$or`
|
|
47
|
+
included, so no translation change ships here — what changes is that the next
|
|
48
|
+
edit to it cannot quietly widen a filter. Both suites were verified to be
|
|
49
|
+
discriminating rather than decorative by reintroducing the #3774 miscompile
|
|
50
|
+
(propagating `or` into a branch's own contents): 15 of the mongodb translation
|
|
51
|
+
suite's 26 tests fail, and 13 of the wasm suite's 18.
|
|
52
|
+
|
|
53
|
+
`packages/spec`'s `filter-logic-conformance.ts` header now says five and names
|
|
54
|
+
the fifth — a code comment; no schema, export or generated artifact moved.
|
|
55
|
+
|
|
56
|
+
- 24915d2: fix(driver-sqlite-wasm): a `RETURNING` write is a write — persist it (#4518)
|
|
57
|
+
|
|
58
|
+
A file-backed `sqlite-wasm` database flushed its schema at boot and then
|
|
59
|
+
recorded nothing else. Every table was on disk; every row written after schema
|
|
60
|
+
sync lived only in the WASM heap and died with the process. Reopening the file
|
|
61
|
+
found a complete, empty database.
|
|
62
|
+
|
|
63
|
+
**Cause.** The Knex dialect picked its execution branch from _"does this
|
|
64
|
+
statement return rows"_ — and then marked the database dirty only on the other,
|
|
65
|
+
row-less branch. `INSERT … RETURNING *` returns rows, so it executed on the
|
|
66
|
+
row-returning branch and never set the flag. Since the `on-disconnect` flush is
|
|
67
|
+
gated on the same flag, nothing rescued it afterwards either: **both** persist
|
|
68
|
+
strategies dropped the write. ObjectQL writes through `RETURNING *` (it hands
|
|
69
|
+
the stored row back to the caller), so this covered essentially all business
|
|
70
|
+
data, along with `knex.raw('INSERT …')` and any other mutation arriving without
|
|
71
|
+
a Knex `method`.
|
|
72
|
+
|
|
73
|
+
**Fix.** "Does this statement change the database?" is now one exported
|
|
74
|
+
predicate — `statementMutatesDatabase(sql, method)` — classifying by Knex method
|
|
75
|
+
_and_ SQL text, applied at a single funnel after execution. It is independent of
|
|
76
|
+
which branch executed the statement, so a mutation can no longer slip through by
|
|
77
|
+
returning rows, by arriving without a method, or by taking a branch that forgot
|
|
78
|
+
to say so. Transaction control still routes to `noteTransactionControl`, which
|
|
79
|
+
keeps deferring flushes until the transaction closes (#1494), and mutating
|
|
80
|
+
`PRAGMA` assignments (`auto_vacuum`, `user_version`) now count as writes too.
|
|
81
|
+
|
|
82
|
+
**What changes for you.** Nothing to author. File-backed wasm SQLite now
|
|
83
|
+
actually persists under `on-write` / `debounced:*`, and `disconnect()` is a real
|
|
84
|
+
durability boundary: when it returns, committed data is on disk. This is what
|
|
85
|
+
`bootStack({ databaseFile })` in `@objectstack/verify` needed to make `stop()` →
|
|
86
|
+
second `bootStack` a genuine cold boot — the suspended-run restart proof
|
|
87
|
+
ADR-0019 promises is now asserted end to end in the dogfood gate. Expect more
|
|
88
|
+
disk writes than before on a file-backed dev database, because previously there
|
|
89
|
+
were almost none.
|
|
90
|
+
|
|
91
|
+
**One internal signature moved.** `WasmSqliteConnection.markDirty(method?)` is
|
|
92
|
+
now `markDirty()`. It used to re-filter the caller's Knex method against its own
|
|
93
|
+
allowlist, which made "did this mutate?" a decision taken in two places that
|
|
94
|
+
could — and did — disagree. If you call it directly, drop the argument; the
|
|
95
|
+
dialect classifies, the connection obeys.
|
|
96
|
+
|
|
97
|
+
- Updated dependencies [430dcc2]
|
|
98
|
+
- Updated dependencies [e6ac4bd]
|
|
99
|
+
- Updated dependencies [80334c7]
|
|
100
|
+
- Updated dependencies [ce5242c]
|
|
101
|
+
- Updated dependencies [a7163ea]
|
|
102
|
+
- Updated dependencies [e6e9379]
|
|
103
|
+
- Updated dependencies [98877c9]
|
|
104
|
+
- Updated dependencies [98877c9]
|
|
105
|
+
- Updated dependencies [e6b1b69]
|
|
106
|
+
- Updated dependencies [ad047d2]
|
|
107
|
+
- Updated dependencies [2826d1e]
|
|
108
|
+
- Updated dependencies [5a84d41]
|
|
109
|
+
- Updated dependencies [20b1a9e]
|
|
110
|
+
- Updated dependencies [203a449]
|
|
111
|
+
- Updated dependencies [ac37fc6]
|
|
112
|
+
- Updated dependencies [4820f55]
|
|
113
|
+
- Updated dependencies [462d9c4]
|
|
114
|
+
- Updated dependencies [7d21581]
|
|
115
|
+
- Updated dependencies [f2445c9]
|
|
116
|
+
- Updated dependencies [23338c3]
|
|
117
|
+
- Updated dependencies [5b843fb]
|
|
118
|
+
- Updated dependencies [b4487aa]
|
|
119
|
+
- Updated dependencies [65ca83a]
|
|
120
|
+
- Updated dependencies [67bf2e2]
|
|
121
|
+
- Updated dependencies [c6d1cb4]
|
|
122
|
+
- Updated dependencies [36030ff]
|
|
123
|
+
- Updated dependencies [6117f7b]
|
|
124
|
+
- Updated dependencies [e533b0b]
|
|
125
|
+
- Updated dependencies [cdf4d9a]
|
|
126
|
+
- Updated dependencies [aee1806]
|
|
127
|
+
- Updated dependencies [c13350b]
|
|
128
|
+
- Updated dependencies [c13350b]
|
|
129
|
+
- Updated dependencies [9ca2d85]
|
|
130
|
+
- Updated dependencies [c13350b]
|
|
131
|
+
- Updated dependencies [891d345]
|
|
132
|
+
- Updated dependencies [a52e2ef]
|
|
133
|
+
- Updated dependencies [5293114]
|
|
134
|
+
- Updated dependencies [20bc357]
|
|
135
|
+
- Updated dependencies [5966c2a]
|
|
136
|
+
- Updated dependencies [2382580]
|
|
137
|
+
- Updated dependencies [d9fa683]
|
|
138
|
+
- Updated dependencies [3c7bcc0]
|
|
139
|
+
- Updated dependencies [4b6cac7]
|
|
140
|
+
- Updated dependencies [7631964]
|
|
141
|
+
- Updated dependencies [ac471a0]
|
|
142
|
+
- Updated dependencies [60ae58e]
|
|
143
|
+
- Updated dependencies [ce92674]
|
|
144
|
+
- Updated dependencies [9f601e8]
|
|
145
|
+
- Updated dependencies [51c5227]
|
|
146
|
+
- Updated dependencies [a4a85c8]
|
|
147
|
+
- Updated dependencies [07a4e26]
|
|
148
|
+
- Updated dependencies [ec975f1]
|
|
149
|
+
- Updated dependencies [eb4204b]
|
|
150
|
+
- Updated dependencies [4f13be2]
|
|
151
|
+
- Updated dependencies [61cc079]
|
|
152
|
+
- Updated dependencies [0e96e46]
|
|
153
|
+
- Updated dependencies [d52d4fe]
|
|
154
|
+
- Updated dependencies [742cebb]
|
|
155
|
+
- Updated dependencies [ce92674]
|
|
156
|
+
- Updated dependencies [cf2c9b7]
|
|
157
|
+
- Updated dependencies [833b512]
|
|
158
|
+
- Updated dependencies [0f9faa2]
|
|
159
|
+
- Updated dependencies [7cf42fe]
|
|
160
|
+
- Updated dependencies [5966c2a]
|
|
161
|
+
- Updated dependencies [f78dd83]
|
|
162
|
+
- Updated dependencies [a2cd18a]
|
|
163
|
+
- Updated dependencies [4638aaa]
|
|
164
|
+
- Updated dependencies [0222d3c]
|
|
165
|
+
- Updated dependencies [071d0dc]
|
|
166
|
+
- Updated dependencies [0a936ea]
|
|
167
|
+
- Updated dependencies [023c00b]
|
|
168
|
+
- Updated dependencies [155507e]
|
|
169
|
+
- Updated dependencies [7bba90b]
|
|
170
|
+
- Updated dependencies [7e05d8e]
|
|
171
|
+
- Updated dependencies [061406d]
|
|
172
|
+
- Updated dependencies [c1f344b]
|
|
173
|
+
- Updated dependencies [9c93465]
|
|
174
|
+
- Updated dependencies [ebb209c]
|
|
175
|
+
- Updated dependencies [63b33e6]
|
|
176
|
+
- Updated dependencies [2a44c1d]
|
|
177
|
+
- Updated dependencies [695cfbd]
|
|
178
|
+
- Updated dependencies [7445149]
|
|
179
|
+
- Updated dependencies [071d0dc]
|
|
180
|
+
- Updated dependencies [0848bea]
|
|
181
|
+
- Updated dependencies [d51bed2]
|
|
182
|
+
- Updated dependencies [b8b3c64]
|
|
183
|
+
- Updated dependencies [0c0fbd9]
|
|
184
|
+
- Updated dependencies [f3141d8]
|
|
185
|
+
- Updated dependencies [5a84d41]
|
|
186
|
+
- Updated dependencies [fd3013a]
|
|
187
|
+
- Updated dependencies [21676eb]
|
|
188
|
+
- Updated dependencies [e336549]
|
|
189
|
+
- Updated dependencies [d40f43a]
|
|
190
|
+
- Updated dependencies [e5e7ee0]
|
|
191
|
+
- Updated dependencies [a2ebea2]
|
|
192
|
+
- Updated dependencies [800bdb0]
|
|
193
|
+
- Updated dependencies [04f1182]
|
|
194
|
+
- Updated dependencies [5647006]
|
|
195
|
+
- Updated dependencies [38f7e4f]
|
|
196
|
+
- Updated dependencies [c57f3cf]
|
|
197
|
+
- Updated dependencies [97faca3]
|
|
198
|
+
- Updated dependencies [ad5fe25]
|
|
199
|
+
- Updated dependencies [ea90179]
|
|
200
|
+
- Updated dependencies [ce92674]
|
|
201
|
+
- Updated dependencies [5ef0b5b]
|
|
202
|
+
- Updated dependencies [48fbacb]
|
|
203
|
+
- Updated dependencies [355e951]
|
|
204
|
+
- Updated dependencies [dadb43f]
|
|
205
|
+
- @objectstack/spec@17.0.0-rc.2
|
|
206
|
+
- @objectstack/core@17.0.0-rc.2
|
|
207
|
+
- @objectstack/driver-sql@17.0.0-rc.2
|
|
208
|
+
|
|
3
209
|
## 17.0.0-rc.1
|
|
4
210
|
|
|
5
211
|
### Patch Changes
|
package/dist/index.d.mts
CHANGED
|
@@ -116,8 +116,21 @@ declare class WasmSqliteConnection {
|
|
|
116
116
|
* (which would abort it).
|
|
117
117
|
*/
|
|
118
118
|
noteTransactionControl(sql: string): void;
|
|
119
|
-
/**
|
|
120
|
-
|
|
119
|
+
/**
|
|
120
|
+
* Record that the statement just executed CHANGED the database, and schedule
|
|
121
|
+
* a flush according to {@link persist}.
|
|
122
|
+
*
|
|
123
|
+
* Deliberately takes no argument. It used to filter the caller's Knex
|
|
124
|
+
* `method` against a local write-method allowlist, which made "did this
|
|
125
|
+
* mutate?" a decision taken in TWO places — here and in the dialect's
|
|
126
|
+
* execution-path branch — and the two disagreed: an `INSERT … RETURNING`
|
|
127
|
+
* runs down the dialect's ROW-returning branch (it has rows to return), that
|
|
128
|
+
* branch never called this method at all, and so a whole class of committed
|
|
129
|
+
* writes was never marked dirty and never reached disk (#4518). One decision,
|
|
130
|
+
* one owner: {@link statementMutatesDatabase} in the dialect classifies the
|
|
131
|
+
* statement, and this method just does what it is told.
|
|
132
|
+
*/
|
|
133
|
+
markDirty(): void;
|
|
121
134
|
/**
|
|
122
135
|
* Force a write of the current database state to disk.
|
|
123
136
|
*
|
package/dist/index.d.ts
CHANGED
|
@@ -116,8 +116,21 @@ declare class WasmSqliteConnection {
|
|
|
116
116
|
* (which would abort it).
|
|
117
117
|
*/
|
|
118
118
|
noteTransactionControl(sql: string): void;
|
|
119
|
-
/**
|
|
120
|
-
|
|
119
|
+
/**
|
|
120
|
+
* Record that the statement just executed CHANGED the database, and schedule
|
|
121
|
+
* a flush according to {@link persist}.
|
|
122
|
+
*
|
|
123
|
+
* Deliberately takes no argument. It used to filter the caller's Knex
|
|
124
|
+
* `method` against a local write-method allowlist, which made "did this
|
|
125
|
+
* mutate?" a decision taken in TWO places — here and in the dialect's
|
|
126
|
+
* execution-path branch — and the two disagreed: an `INSERT … RETURNING`
|
|
127
|
+
* runs down the dialect's ROW-returning branch (it has rows to return), that
|
|
128
|
+
* branch never called this method at all, and so a whole class of committed
|
|
129
|
+
* writes was never marked dirty and never reached disk (#4518). One decision,
|
|
130
|
+
* one owner: {@link statementMutatesDatabase} in the dialect classifies the
|
|
131
|
+
* statement, and this method just does what it is told.
|
|
132
|
+
*/
|
|
133
|
+
markDirty(): void;
|
|
121
134
|
/**
|
|
122
135
|
* Force a write of the current database state to disk.
|
|
123
136
|
*
|
package/dist/index.js
CHANGED
|
@@ -45,13 +45,6 @@ var import_node_module = require("module");
|
|
|
45
45
|
|
|
46
46
|
// src/wasm-connection.ts
|
|
47
47
|
var import_meta = {};
|
|
48
|
-
var WRITE_METHODS = /* @__PURE__ */ new Set([
|
|
49
|
-
"run",
|
|
50
|
-
"insert",
|
|
51
|
-
"update",
|
|
52
|
-
"del",
|
|
53
|
-
"counter"
|
|
54
|
-
]);
|
|
55
48
|
async function tryLoadFs() {
|
|
56
49
|
try {
|
|
57
50
|
return await import("fs/promises");
|
|
@@ -262,10 +255,22 @@ var _WasmSqliteConnection = class _WasmSqliteConnection {
|
|
|
262
255
|
void this.flush();
|
|
263
256
|
}
|
|
264
257
|
}
|
|
265
|
-
/**
|
|
266
|
-
|
|
258
|
+
/**
|
|
259
|
+
* Record that the statement just executed CHANGED the database, and schedule
|
|
260
|
+
* a flush according to {@link persist}.
|
|
261
|
+
*
|
|
262
|
+
* Deliberately takes no argument. It used to filter the caller's Knex
|
|
263
|
+
* `method` against a local write-method allowlist, which made "did this
|
|
264
|
+
* mutate?" a decision taken in TWO places — here and in the dialect's
|
|
265
|
+
* execution-path branch — and the two disagreed: an `INSERT … RETURNING`
|
|
266
|
+
* runs down the dialect's ROW-returning branch (it has rows to return), that
|
|
267
|
+
* branch never called this method at all, and so a whole class of committed
|
|
268
|
+
* writes was never marked dirty and never reached disk (#4518). One decision,
|
|
269
|
+
* one owner: {@link statementMutatesDatabase} in the dialect classifies the
|
|
270
|
+
* statement, and this method just does what it is told.
|
|
271
|
+
*/
|
|
272
|
+
markDirty() {
|
|
267
273
|
if (this.isEphemeral || !this.fs) return;
|
|
268
|
-
if (method && !WRITE_METHODS.has(method)) return;
|
|
269
274
|
this.dirty = true;
|
|
270
275
|
if (this.persist === "on-write") {
|
|
271
276
|
void this.flush();
|
|
@@ -401,11 +406,23 @@ function formatBindings(bindings) {
|
|
|
401
406
|
return b;
|
|
402
407
|
});
|
|
403
408
|
}
|
|
404
|
-
function
|
|
409
|
+
function isRowReturningExecution(method, returning) {
|
|
405
410
|
if (method === "insert" || method === "update") return !!returning ? true : false;
|
|
406
411
|
if (method === "counter" || method === "del") return false;
|
|
407
412
|
return true;
|
|
408
413
|
}
|
|
414
|
+
var MUTATING_METHODS = /* @__PURE__ */ new Set(["insert", "update", "del", "counter"]);
|
|
415
|
+
var TRANSACTION_CONTROL_RE = /^\s*(BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b/i;
|
|
416
|
+
var DDL_RE = /^\s*(CREATE|ALTER|DROP|BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE|REINDEX|VACUUM|ATTACH|DETACH|TRUNCATE)\b/i;
|
|
417
|
+
var MUTATING_DML_RE = /^\s*(INSERT|UPDATE|DELETE|REPLACE|UPSERT)\b/i;
|
|
418
|
+
var MUTATING_PRAGMA_RE = /^\s*PRAGMA\b(?:[^;]*=|\s+incremental_vacuum\b)/i;
|
|
419
|
+
function statementMutatesDatabase(sql, method) {
|
|
420
|
+
if (TRANSACTION_CONTROL_RE.test(sql)) return false;
|
|
421
|
+
if (method && MUTATING_METHODS.has(method)) return true;
|
|
422
|
+
if (DDL_RE.test(sql)) return true;
|
|
423
|
+
if (MUTATING_DML_RE.test(sql)) return true;
|
|
424
|
+
return MUTATING_PRAGMA_RE.test(sql);
|
|
425
|
+
}
|
|
409
426
|
function resolveKnexSqlite3Dialect() {
|
|
410
427
|
const g = globalThis;
|
|
411
428
|
if (typeof g.require === "function") {
|
|
@@ -447,20 +464,10 @@ function getClient_WasmSqlite() {
|
|
|
447
464
|
if (!connection) throw new Error("No connection provided");
|
|
448
465
|
const db = connection.raw;
|
|
449
466
|
const bindings = formatBindings(obj.bindings);
|
|
450
|
-
|
|
451
|
-
obj.sql
|
|
452
|
-
);
|
|
453
|
-
if (isDdl) {
|
|
467
|
+
if (DDL_RE.test(obj.sql)) {
|
|
454
468
|
db.run(obj.sql, bindings);
|
|
455
469
|
obj.response = [];
|
|
456
|
-
|
|
457
|
-
connection.noteTransactionControl(obj.sql);
|
|
458
|
-
} else {
|
|
459
|
-
connection.markDirty("run");
|
|
460
|
-
}
|
|
461
|
-
return obj;
|
|
462
|
-
}
|
|
463
|
-
if (isReadMethod(obj.method, obj.returning) || /^\s*PRAGMA\b/i.test(obj.sql)) {
|
|
470
|
+
} else if (isRowReturningExecution(obj.method, obj.returning) || /^\s*PRAGMA\b/i.test(obj.sql)) {
|
|
464
471
|
const stmt = db.prepare(obj.sql);
|
|
465
472
|
try {
|
|
466
473
|
if (bindings.length) stmt.bind(bindings);
|
|
@@ -472,18 +479,22 @@ function getClient_WasmSqlite() {
|
|
|
472
479
|
} finally {
|
|
473
480
|
stmt.free();
|
|
474
481
|
}
|
|
475
|
-
|
|
482
|
+
} else {
|
|
483
|
+
db.run(obj.sql, bindings);
|
|
484
|
+
const changes = db.getRowsModified();
|
|
485
|
+
let lastID = 0;
|
|
486
|
+
if (obj.method === "insert") {
|
|
487
|
+
const r = db.exec("SELECT last_insert_rowid() AS id");
|
|
488
|
+
lastID = r?.[0]?.values?.[0]?.[0] ?? 0;
|
|
489
|
+
}
|
|
490
|
+
obj.response = [];
|
|
491
|
+
obj.context = { lastID, changes };
|
|
476
492
|
}
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
const r = db.exec("SELECT last_insert_rowid() AS id");
|
|
482
|
-
lastID = r?.[0]?.values?.[0]?.[0] ?? 0;
|
|
493
|
+
if (TRANSACTION_CONTROL_RE.test(obj.sql)) {
|
|
494
|
+
connection.noteTransactionControl(obj.sql);
|
|
495
|
+
} else if (statementMutatesDatabase(obj.sql, obj.method)) {
|
|
496
|
+
connection.markDirty();
|
|
483
497
|
}
|
|
484
|
-
obj.response = [];
|
|
485
|
-
obj.context = { lastID, changes };
|
|
486
|
-
connection.markDirty(obj.method);
|
|
487
498
|
return obj;
|
|
488
499
|
}
|
|
489
500
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/sqlite-wasm-driver.ts","../src/knex-wasm-dialect.ts","../src/wasm-connection.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { SqliteWasmDriver } from './sqlite-wasm-driver.js';\n\nexport { SqliteWasmDriver };\nexport type { SqliteWasmDriverConfig } from './sqlite-wasm-driver.js';\nexport { Client_WasmSqlite } from './knex-wasm-dialect.js';\nexport type { WasmSqliteConnectionSettings } from './knex-wasm-dialect.js';\nexport { WasmSqliteConnection } from './wasm-connection.js';\nexport type { PersistMode, WasmConnectionOptions } from './wasm-connection.js';\n\nexport default {\n id: 'com.objectstack.driver.sqlite-wasm',\n version: '1.0.0',\n\n onEnable: async (context: any) => {\n const { logger, config, drivers } = context;\n logger?.info?.('[SQLite-WASM Driver] Initializing...');\n\n if (drivers) {\n const driver = new SqliteWasmDriver(config);\n drivers.register(driver);\n logger?.info?.(`[SQLite-WASM Driver] Registered driver: ${driver.name}`);\n } else {\n logger?.warn?.('[SQLite-WASM Driver] No driver registry found in context.');\n }\n },\n};\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * SQLite-on-WASM driver for ObjectStack.\n *\n * Extends {@link SqlDriver} so all CRUD / schema / introspection / multi-tenant\n * logic is inherited as-is. Only the Knex transport is swapped to a custom\n * dialect ({@link Client_WasmSqlite}) backed by sql.js + Node `fs` persistence,\n * which lets the same `SqlDriver` codepath run inside StackBlitz WebContainer\n * (Node-in-browser) without the native `better-sqlite3` N-API binding.\n */\n\nimport type { SqlJsStatic } from 'sql.js';\nimport { SqlDriver, type SqlDriverConfig } from '@objectstack/driver-sql';\n\nimport { getClient_WasmSqlite } from './knex-wasm-dialect.js';\nimport type {\n PersistMode,\n WasmConnectionOptions,\n} from './wasm-connection.js';\n\n/** Public configuration for {@link SqliteWasmDriver}. */\nexport interface SqliteWasmDriverConfig {\n /**\n * SQLite filename. Use `:memory:` for an ephemeral database that is never\n * persisted. Any other value is treated as a Node `fs` path and the\n * sql.js database bytes are flushed back to disk according to {@link persist}.\n */\n filename: string;\n\n /**\n * Persistence strategy. Default: `'on-disconnect'`.\n *\n * - `'on-disconnect'` — flush once when the driver disconnects (and on\n * `process.beforeExit`).\n * - `'on-write'` — flush after every mutation. Safest, slowest.\n * - `` `debounced:${ms}` `` — debounce flushes by N milliseconds. Good\n * balance under bursty writes.\n */\n persist?: PersistMode;\n\n /** Pre-loaded sql.js module — skips lazy import. */\n sqlJs?: SqlJsStatic;\n\n /**\n * Override for sql.js's `locateFile`. Defaults to resolving the `.wasm`\n * file inside the installed `sql.js` package, which works in Node and\n * WebContainer.\n */\n locateFile?: (file: string) => string;\n\n /** Knex pool overrides. The dialect already defaults to `{ min: 1, max: 1 }`. */\n pool?: SqlDriverConfig['pool'];\n\n /** Optional logger. Defaults to `console`. */\n logger?: WasmConnectionOptions['logger'];\n}\n\n/**\n * SqlDriver subclass that runs Knex against sql.js (WASM SQLite).\n *\n * Behaves identically to the standard SQLite path — the dialect's\n * {@link Client_WasmSqlite._query} reports `lastID`/`changes` exactly the\n * way better-sqlite3 does, so {@link SqlDriver}'s SQL generation, returning\n * clauses, and schema introspection all keep working.\n */\nexport class SqliteWasmDriver extends SqlDriver {\n public override readonly name: string = 'com.objectstack.driver.sqlite-wasm';\n public override readonly version: string = '1.0.0';\n\n /**\n * Force the SQLite branch in {@link SqlDriver}. The base class detects\n * SQLite by string-matching `config.client`, but we pass the dialect class\n * directly so the string check would miss.\n */\n protected override get isSqlite(): boolean {\n return true;\n }\n\n /**\n * Never WAL (#3941). The base driver switches a file-backed SQLite database to\n * WAL so several processes can share one file. Nothing here is shared: the live\n * database sits in this process's WASM heap, and what reaches disk is a byte\n * image {@link flush} exports from it — another process reads that snapshot,\n * never the database. So the pragma buys this transport nothing.\n *\n * It is also not free. Journal mode is a persistent header change in the\n * operator's file, and under WAL the export path's correctness would rest on\n * sql.js checkpointing the log while `export()` closes and reopens the\n * database. Measured, it does — no row is lost today — which is why this is a\n * declined default and not a bug report. But a transport that persists by\n * serializing an image should not be one implementation detail away from\n * dropping committed rows for a concurrency benefit it cannot use.\n *\n * Declared rather than discovered: sql.js *accepts* `journal_mode = WAL`,\n * because its VFS is memory-backed, so the refusal the base class gets from\n * `:memory:` never comes — and an image whose header already says WAL (one a\n * native run left behind) reports `wal` here too.\n */\n protected override get supportsWalJournal(): boolean {\n return false;\n }\n\n private wasmConfig: SqliteWasmDriverConfig;\n private beforeExitHandler: (() => void) | null = null;\n\n constructor(config: SqliteWasmDriverConfig) {\n const knexConfig = SqliteWasmDriver.toKnexConfig(config);\n super(knexConfig);\n this.wasmConfig = config;\n if (config.logger) this.logger = config.logger as any;\n }\n\n /** Translate the public config into a Knex config that uses our dialect. */\n static toKnexConfig(config: SqliteWasmDriverConfig): SqlDriverConfig {\n return {\n // Knex accepts a Client class as `client`. The dialect's `driverName`\n // is `'wasm-sqlite'` and its `dialect` is `'sqlite3'` so the SQLite\n // query compiler is reused.\n client: getClient_WasmSqlite() as any,\n connection: {\n filename: config.filename,\n persist: config.persist,\n sqlJs: config.sqlJs,\n locateFile: config.locateFile,\n logger: config.logger,\n } as any,\n // sql.js is single-threaded WASM — a single connection per pool keeps\n // semantics consistent with the upstream SQLite dialect.\n pool: config.pool ?? { min: 1, max: 1 },\n useNullAsDefault: true,\n } as SqlDriverConfig;\n }\n\n override async connect(): Promise<void> {\n await super.connect();\n\n // Best-effort flush on process exit so `on-disconnect` mode still saves\n // user data if the host process is shut down without explicit cleanup.\n if (\n this.wasmConfig.filename !== ':memory:' &&\n !this.wasmConfig.filename.startsWith(':') &&\n typeof process !== 'undefined' &&\n typeof process.once === 'function'\n ) {\n this.beforeExitHandler = () => {\n // Fire-and-forget — beforeExit cannot await.\n void this.flush().catch(() => {\n /* ignore */\n });\n };\n process.once('beforeExit', this.beforeExitHandler);\n }\n }\n\n override async disconnect(): Promise<void> {\n if (this.beforeExitHandler && typeof process !== 'undefined') {\n try {\n process.removeListener('beforeExit', this.beforeExitHandler);\n } catch {\n /* ignore */\n }\n this.beforeExitHandler = null;\n }\n await super.disconnect();\n }\n\n /**\n * Force a flush of the in-memory database to disk. No-op for ephemeral\n * databases or when no fs is available.\n */\n async flush(): Promise<void> {\n // Reach into the Knex pool and ask every live connection to flush.\n const knex = (this as any).knex;\n const client = knex?.client;\n const pool = client?.pool;\n if (!pool || typeof pool.numUsed !== 'function') return;\n\n const acquire = client.acquireConnection?.bind(client);\n const release = client.releaseConnection?.bind(client);\n if (!acquire || !release) return;\n\n const conn = await acquire();\n try {\n if (conn && typeof conn.flush === 'function') {\n await conn.flush();\n }\n } finally {\n await release(conn);\n }\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Custom Knex SQLite dialect backed by sql.js (WASM SQLite).\n *\n * Mimics the surface that `Client_BetterSQLite3` presents to Knex so the\n * upstream SQLite3 dialect's query compiler, schema builder, and column\n * compiler all keep working unchanged. Only the transport layer —\n * `_driver` / `acquireRawConnection` / `_query` — is swapped out.\n *\n * ## Why the dialect class is built lazily\n *\n * The class `Client_WasmSqlite extends Client_SQLite3` needs the upstream\n * SQLite3 dialect at class-definition time. Resolving it at module\n * top-level breaks when this file is re-bundled by another tsup/esbuild\n * pass (e.g. `packages/runtime`), because that pass rewrites our runtime\n * `createRequire(import.meta.url)` chain back into a static `__require2`\n * Proxy stub that throws `Dynamic require of \"X\" is not supported`.\n *\n * Building the class inside a lazy factory (`getClient_WasmSqlite()`)\n * keeps the `require` call out of module-init code, so the re-bundler\n * cannot intercept it.\n */\n\nimport { createRequire } from 'node:module';\n\nimport type { SqlJsStatic } from 'sql.js';\n\nimport {\n WasmSqliteConnection,\n type PersistMode,\n type WasmConnectionOptions,\n} from './wasm-connection.js';\n\n// Built lazily — `node:module` is a Node builtin and is left untouched\n// by esbuild/tsup, so the `createRequire` import survives downstream\n// re-bundling. We defer the actual `createRequire(...)` call so that the\n// CJS build (where `import.meta.url` is empty) doesn't blow up at module\n// init; the CJS path uses `globalThis.require` directly anyway.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet cachedEsmRequire: any = null;\nfunction getEsmRequire(): any {\n if (cachedEsmRequire) return cachedEsmRequire;\n // `import.meta.url` is replaced with an empty string in CJS output;\n // fall back to the current file/cwd in that case.\n const anchor =\n typeof import.meta !== 'undefined' && (import.meta as any).url\n ? (import.meta as any).url\n : typeof __filename !== 'undefined'\n ? __filename\n : process.cwd() + '/';\n cachedEsmRequire = createRequire(anchor);\n return cachedEsmRequire;\n}\n\n/** Connection settings recognised by the WASM SQLite dialect. */\nexport interface WasmSqliteConnectionSettings {\n filename: string;\n persist?: PersistMode;\n sqlJs?: SqlJsStatic;\n locateFile?: (file: string) => string;\n logger?: WasmConnectionOptions['logger'];\n}\n\n/**\n * Coerce JS values that sql.js cannot bind directly. Mirrors\n * `Client_BetterSQLite3._formatBindings`.\n *\n * `undefined` is mapped to `null`: sql.js's binder only accepts\n * string/number/bigint/boolean/null (and array/blob) and `throw`s a *raw\n * string* — `\"Wrong API use : tried to bind a value of an unknown type\n * (undefined).\"` — for anything else. Because it throws a string rather than\n * an `Error`, it logs as a garbled char-indexed object and aborts the whole\n * write. Mapping to `null` matches the `useNullAsDefault` semantics the\n * dialect is configured with, so a missing/undefined value persists as SQL\n * `NULL` exactly as it would through better-sqlite3.\n */\nfunction formatBindings(bindings: unknown[] | undefined): unknown[] {\n if (!bindings) return [];\n return bindings.map((b) => {\n if (b === undefined) return null;\n if (b instanceof Date) return b.valueOf();\n if (typeof b === 'boolean') return Number(b);\n return b;\n });\n}\n\n/**\n * Mirrors the dispatch in upstream `Client_SQLite3._query`: only\n * `insert/update/counter/del` go through the row-less write path (and even\n * those switch to the read path when a `RETURNING` clause is requested).\n * Everything else — `select`, `first`, `pluck`, `columnInfo`, raw PRAGMA,\n * DDL with no `method` — is read with `all`/row iteration so Knex sees the\n * same response shape it would from better-sqlite3.\n */\nfunction isReadMethod(method?: string, returning?: unknown): boolean {\n if (method === 'insert' || method === 'update') return !!returning ? true : false;\n if (method === 'counter' || method === 'del') return false;\n return true;\n}\n\n/**\n * Resolve the upstream `knex/lib/dialects/sqlite3` class at runtime.\n *\n * Tries every escape hatch we have so that this works in:\n * - Plain Node ESM (use `createRequire(import.meta.url)`).\n * - Plain Node CJS (use the ambient `require` on `globalThis`).\n * - Re-bundled ESM where esbuild/tsup has stubbed `__require` — we\n * fall back to `new Function('return require')()` which evades static\n * analysis and grabs the real Node `require` at runtime.\n *\n * Wrapped in a function so the bundler cannot execute it at module init.\n */\nfunction resolveKnexSqlite3Dialect(): any {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const g = globalThis as any;\n if (typeof g.require === 'function') {\n try {\n return g.require('knex/lib/dialects/sqlite3');\n } catch {\n /* fall through */\n }\n }\n // ESM-safe path: `createRequire` was imported statically at the top of\n // this module from `node:module`. In a pure-ESM process there is no\n // ambient `require`, so this is the only reliable way to load a CJS\n // package like `knex/lib/dialects/sqlite3`.\n return getEsmRequire()('knex/lib/dialects/sqlite3');\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet cachedDialect: any = null;\n\n/**\n * Build (and cache) the `Client_WasmSqlite` class. Building lazily keeps\n * the `require('knex/lib/dialects/sqlite3')` call out of module-init\n * code so downstream re-bundlers (e.g. `packages/runtime`) cannot collapse\n * it into a Dynamic-require stub.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getClient_WasmSqlite(): any {\n if (cachedDialect) return cachedDialect;\n const Client_SQLite3 = resolveKnexSqlite3Dialect();\n\n class Client_WasmSqlite extends Client_SQLite3 {\n // sql.js has no shared \"driver module\" the way better-sqlite3 does. Knex\n // only uses `this.driver` to construct connections, and we override\n // `acquireRawConnection`, so a sentinel object is enough.\n _driver(): { name: 'sql.js' } {\n return { name: 'sql.js' };\n }\n\n async acquireRawConnection(): Promise<WasmSqliteConnection> {\n const settings = (this as any)\n .connectionSettings as WasmSqliteConnectionSettings;\n\n const conn = new WasmSqliteConnection({\n filename: settings.filename,\n persist: settings.persist,\n sqlJs: settings.sqlJs,\n locateFile: settings.locateFile,\n logger: settings.logger,\n });\n await conn.open(settings.sqlJs, settings.locateFile);\n return conn;\n }\n\n async destroyRawConnection(connection: WasmSqliteConnection): Promise<void> {\n await connection.close();\n }\n\n async _query(\n connection: WasmSqliteConnection,\n obj: any,\n ): Promise<any> {\n if (!obj.sql) throw new Error('The query is empty');\n if (!connection) throw new Error('No connection provided');\n\n const db = connection.raw;\n const bindings = formatBindings(obj.bindings);\n\n // DDL / transactional control statements have no Knex `method`. sql.js's\n // `prepare`+`step` silently no-ops on many of these (e.g. CREATE TABLE),\n // so route them through `run` which is implemented via `exec` and\n // actually mutates the database. PRAGMA is intentionally excluded — many\n // PRAGMA forms (e.g. `PRAGMA table_info(...)`, `foreign_key_list(...)`)\n // return rows used by Knex's schema introspection/columnInfo, and\n // `db.run` discards those rows.\n const isDdl =\n /^\\s*(CREATE|ALTER|DROP|BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE|REINDEX|VACUUM|ATTACH|DETACH|TRUNCATE)\\b/i.test(\n obj.sql,\n );\n if (isDdl) {\n db.run(obj.sql, bindings as any);\n obj.response = [];\n // Transaction-control statements are routed through\n // `noteTransactionControl`, which owns flushing for the transaction\n // lifecycle: it suppresses flushes while a transaction is open (sql.js\n // `export()` closes+reopens the db, which would abort the txn) and\n // performs a single flush once the transaction fully closes. Routing\n // them away from `markDirty` avoids a second, racing flush on COMMIT.\n if (/^\\s*(BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\\b/i.test(obj.sql)) {\n connection.noteTransactionControl(obj.sql);\n } else {\n connection.markDirty('run');\n }\n return obj;\n }\n\n if (isReadMethod(obj.method, obj.returning) || /^\\s*PRAGMA\\b/i.test(obj.sql)) {\n const stmt = db.prepare(obj.sql);\n try {\n if (bindings.length) stmt.bind(bindings as any);\n const rows: Record<string, unknown>[] = [];\n while (stmt.step()) {\n rows.push(stmt.getAsObject());\n }\n obj.response = rows;\n } finally {\n stmt.free();\n }\n return obj;\n }\n\n // Write path: execute via `run` (no row iteration needed) and capture\n // SQLite's per-connection lastID / changes counters.\n db.run(obj.sql, bindings as any);\n const changes = db.getRowsModified();\n let lastID: number | bigint = 0;\n if (obj.method === 'insert') {\n const r = db.exec('SELECT last_insert_rowid() AS id');\n lastID = (r?.[0]?.values?.[0]?.[0] as number) ?? 0;\n }\n obj.response = [];\n obj.context = { lastID, changes };\n connection.markDirty(obj.method);\n return obj;\n }\n }\n\n Object.assign(Client_WasmSqlite.prototype, {\n dialect: 'sqlite3',\n driverName: 'wasm-sqlite',\n });\n\n cachedDialect = Client_WasmSqlite;\n return Client_WasmSqlite;\n}\n\n/**\n * Back-compat re-export. Prefer `getClient_WasmSqlite()` so the dialect\n * is resolved lazily; the named export triggers the factory on first\n * access of any static property.\n *\n * Note: importing this binding will execute the factory at import time\n * in some bundlers, which defeats the lazy pattern. New code should call\n * `getClient_WasmSqlite()` directly.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const Client_WasmSqlite: any = new Proxy(function () {} as any, {\n get(_t, prop) {\n return (getClient_WasmSqlite() as any)[prop];\n },\n construct(_t, args) {\n const Klass = getClient_WasmSqlite();\n return new Klass(...args);\n },\n apply(_t, thisArg, args) {\n const Klass = getClient_WasmSqlite();\n return Reflect.apply(Klass, thisArg, args);\n },\n});\n\nexport default Client_WasmSqlite;\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Thin wrapper over sql.js {@link Database} that mimics the surface of\n * `better-sqlite3`'s `Database` (only the methods the Knex dialect uses).\n *\n * Persistence is handled here, not in the Knex dialect, so it can be\n * orchestrated per-connection without polluting the SQL execution path.\n */\n\nimport type { Database, SqlJsStatic } from 'sql.js';\n\n/** When to flush the in-memory WASM database to disk. */\nexport type PersistMode =\n | 'on-disconnect'\n | 'on-write'\n | `debounced:${number}`;\n\nexport interface WasmConnectionOptions {\n /**\n * On-disk file path. `:memory:` (or any value starting with `:`) skips\n * persistence entirely and the database lives only for the process.\n */\n filename: string;\n /** When to persist. Default: `on-disconnect`. */\n persist?: PersistMode;\n /** Pre-loaded sql.js module. If omitted, loaded lazily on first connect. */\n sqlJs?: SqlJsStatic;\n /**\n * Optional override for the `.wasm` locator passed to `initSqlJs()`.\n * Defaults to resolving the file from the `sql.js` package on disk\n * (works in Node and WebContainer).\n */\n locateFile?: (file: string) => string;\n /** Optional logger; defaults to `console`. */\n logger?: { warn: (msg: string, meta?: unknown) => void };\n}\n\n/** Mutation method names that should trigger a persistence cycle. */\nconst WRITE_METHODS = new Set([\n 'run',\n 'insert',\n 'update',\n 'del',\n 'counter',\n]);\n\n/**\n * Detect whether a Node-style `fs` module is available. WebContainer\n * (StackBlitz) provides Node `fs`; pure-browser environments do not.\n */\nasync function tryLoadFs(): Promise<typeof import('node:fs/promises') | null> {\n try {\n return await import('node:fs/promises');\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve a default sql.js WASM locator. We point sql.js at the `.wasm`\n * file shipped inside `sql.js`'s own `dist/` folder. This avoids requiring\n * the caller to host the WASM separately.\n */\nasync function defaultLocateFile(): Promise<((file: string) => string) | undefined> {\n try {\n const { createRequire } = await import('node:module');\n const require = createRequire(import.meta.url);\n const pkgJsonPath = require.resolve('sql.js/package.json');\n const { dirname, join } = await import('node:path');\n const dir = dirname(pkgJsonPath);\n return (file: string) => join(dir, 'dist', file);\n } catch {\n return undefined;\n }\n}\n\nlet cachedSqlJs: Promise<SqlJsStatic> | null = null;\n\nasync function loadSqlJs(\n locateFile?: (file: string) => string,\n): Promise<SqlJsStatic> {\n if (cachedSqlJs) return cachedSqlJs;\n cachedSqlJs = (async () => {\n const mod = await import('sql.js');\n const initSqlJs = (mod as any).default ?? (mod as any);\n const locator = locateFile ?? (await defaultLocateFile());\n const SQL = await initSqlJs(locator ? { locateFile: locator } : undefined);\n return SQL as SqlJsStatic;\n })();\n return cachedSqlJs;\n}\n\n/**\n * A sql.js-backed connection that exposes the `prepare`/`exec`/`close`\n * subset used by Knex's SQLite dialect. Mutations are queued through a\n * configurable persistence strategy so the on-disk file stays in sync.\n */\nexport class WasmSqliteConnection {\n /**\n * Process-wide counter making each atomic-write temp filename unique, so\n * concurrent connections (or overlapping flushes) never target the same\n * temp path. Combined with `process.pid` for cross-process uniqueness.\n */\n private static tmpSeq = 0;\n\n readonly filename: string;\n readonly persist: PersistMode;\n readonly isEphemeral: boolean;\n\n private db!: Database;\n private fs: typeof import('node:fs/promises') | null = null;\n private dirty = false;\n private debounceMs = 0;\n private debounceTimer: ReturnType<typeof setTimeout> | null = null;\n private flushChain: Promise<void> | null = null;\n private destroyed = false;\n private logger: { warn: (msg: string, meta?: unknown) => void };\n\n /**\n * Whether a `BEGIN…COMMIT/ROLLBACK` transaction is currently open. Tracked\n * because sql.js's {@link Database.export} closes and reopens the database\n * (it has no in-place serialize), and closing a connection rolls back any\n * open transaction. Flushing mid-transaction would therefore silently\n * abort it, leaving the eventual `COMMIT` to fail with\n * \"cannot commit - no transaction is active\". We defer the flush until the\n * transaction fully closes. See {@link noteTransactionControl}.\n */\n private rootTxActive = false;\n /** Open `SAVEPOINT` depth (nested transactions emitted by Knex). */\n private savepointDepth = 0;\n /** A flush was requested while a transaction was open; run it on close. */\n private flushDeferred = false;\n\n /** True while any transaction (root or savepoint) is in flight. */\n private get inTransaction(): boolean {\n return this.rootTxActive || this.savepointDepth > 0;\n }\n\n constructor(opts: WasmConnectionOptions) {\n this.filename = opts.filename;\n this.persist = opts.persist ?? 'on-disconnect';\n this.isEphemeral =\n this.filename === ':memory:' || this.filename.startsWith(':');\n this.logger = opts.logger ?? console;\n\n if (typeof this.persist === 'string' && this.persist.startsWith('debounced:')) {\n const ms = Number(this.persist.slice('debounced:'.length));\n this.debounceMs = Number.isFinite(ms) && ms > 0 ? ms : 250;\n }\n }\n\n /** Open the underlying sql.js database, loading bytes from disk if any. */\n async open(sqlJs?: SqlJsStatic, locateFile?: (file: string) => string): Promise<void> {\n const SQL = sqlJs ?? (await loadSqlJs(locateFile));\n\n if (this.isEphemeral) {\n this.db = new SQL.Database();\n return;\n }\n\n this.fs = await tryLoadFs();\n if (!this.fs) {\n this.logger.warn(\n '[driver-sqlite-wasm] No node:fs available — falling back to in-memory database. ' +\n 'Data will not be persisted across reloads.',\n );\n this.db = new SQL.Database();\n return;\n }\n\n // Ensure parent directory exists, then load bytes if the file exists.\n const { dirname } = await import('node:path');\n const dir = dirname(this.filename);\n if (dir && dir !== '.') {\n await this.fs.mkdir(dir, { recursive: true });\n }\n\n let bytes: Uint8Array | undefined;\n try {\n const buf = await this.fs.readFile(this.filename);\n bytes = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n } catch (e: any) {\n if (e?.code !== 'ENOENT') throw e;\n }\n\n if (!bytes) {\n this.db = new SQL.Database();\n return;\n }\n\n await this.quarantineOrphanedWal();\n\n // Open the on-disk bytes, but guard against a corrupt image. A torn write\n // (process killed mid-flush before atomic writes existed) or otherwise\n // damaged file makes `new SQL.Database(bytes)` either throw (\"file is not a\n // database\") or open a handle whose every query fails with \"database disk\n // image is malformed\" — which, for a background dispatcher on a tick loop,\n // means the same error spammed forever with no path to recovery. Detect it\n // once at open, quarantine the bad file, and start fresh so the dev server\n // becomes usable again instead of wedging.\n try {\n const candidate = new SQL.Database(bytes);\n this.assertReadable(candidate);\n this.db = candidate;\n } catch (err) {\n await this.quarantineCorruptFile(err);\n this.db = new SQL.Database();\n }\n }\n\n /**\n * Force sql.js to actually read a page so a malformed image surfaces now\n * rather than on the first business query. `PRAGMA quick_check` walks the\n * b-tree structure without the full-scan cost of `integrity_check`; a healthy\n * database returns a single `ok` row. Any thrown error (raw string or Error)\n * or a non-`ok` result is treated as corruption.\n */\n private assertReadable(db: Database): void {\n const res = db.exec('PRAGMA quick_check(1)');\n const first = res?.[0]?.values?.[0]?.[0];\n if (typeof first === 'string' && first.toLowerCase() !== 'ok') {\n throw new Error(`sqlite quick_check failed: ${first}`);\n }\n }\n\n /**\n * Move a corrupt database file aside so its bytes are preserved for\n * post-mortem while a fresh, empty database takes its place. Best-effort:\n * failures here must not prevent the server from booting on a clean DB.\n */\n private async quarantineCorruptFile(cause: unknown): Promise<void> {\n if (!this.fs) return;\n const reason =\n typeof cause === 'string' ? cause : (cause as Error)?.message ?? String(cause);\n const backup = `${this.filename}.corrupt-${Date.now()}`;\n try {\n await this.fs.rename(this.filename, backup);\n this.logger.warn(\n `[driver-sqlite-wasm] Database image at ${this.filename} is corrupt ` +\n `(${reason}). Quarantined to ${backup} and starting from an empty ` +\n `database so the server can boot.`,\n );\n } catch (renameErr) {\n // Could not move it aside (e.g. permissions) — overwrite is still better\n // than looping forever on a malformed image. Warn loudly and continue.\n this.logger.warn(\n `[driver-sqlite-wasm] Database image at ${this.filename} is corrupt ` +\n `(${reason}) and could not be quarantined (${String(renameErr)}). ` +\n `Starting from an empty database; the corrupt file will be overwritten ` +\n `on the next flush.`,\n );\n }\n }\n\n /**\n * Move a write-ahead log left behind by a *real* SQLite aside (#3941).\n *\n * The native driver keeps file-backed databases in WAL mode, and a clean close\n * checkpoints the log away — so a non-empty `<db>-wal` here means the last\n * process died without one. That log is a problem in both directions, and\n * neither is something wasm SQLite can fix: it cannot read the log (we load\n * only the main image, so any transaction still in there is invisible), and it\n * must not leave it in place either — the next {@link flush} rewrites the\n * image, and a real SQLite opening a fresh image beside a stale log would\n * replay frames that no longer belong to it.\n *\n * So rename it, which loses nothing recoverable (the bytes are preserved for a\n * real `sqlite3` to recover from) and disarms the mismatch. Best-effort: this\n * is a dev-only step-down path and must never prevent a boot.\n */\n private async quarantineOrphanedWal(): Promise<void> {\n if (!this.fs) return;\n const wal = `${this.filename}-wal`;\n let size: number;\n try {\n size = (await this.fs.stat(wal)).size;\n } catch {\n return; // no sidecar (the normal case) or an unreadable one\n }\n if (size <= 0) return; // checkpointed-and-truncated: nothing in it\n\n const parked = `${wal}.orphaned-${Date.now()}`;\n try {\n await this.fs.rename(wal, parked);\n this.logger.warn(\n `[driver-sqlite-wasm] ${wal} holds ${size} bytes of write-ahead log that wasm SQLite ` +\n `cannot read — this database was last used in WAL mode and closed uncleanly. Parked it ` +\n `at ${parked} and loaded the main image without it, so anything committed only to the ` +\n `log is NOT in this session. To recover it, rebuild better-sqlite3 (or use \\`sqlite3\\`), ` +\n `restore the log next to the database, and run \\`PRAGMA wal_checkpoint(TRUNCATE)\\`.`,\n );\n } catch (renameErr) {\n this.logger.warn(\n `[driver-sqlite-wasm] ${wal} holds ${size} bytes of write-ahead log that wasm SQLite ` +\n `cannot read, and it could not be moved aside (${String(renameErr)}). Data committed ` +\n `only to the log is missing from this session; checkpoint it with a real sqlite3 before ` +\n `writing further.`,\n );\n }\n }\n\n /**\n * Update transaction state from a transaction-control statement and, when a\n * transaction has just fully closed, run any flush that was deferred while\n * it was open. Called by the Knex dialect for every `BEGIN` / `COMMIT` /\n * `ROLLBACK` / `SAVEPOINT` / `RELEASE` statement.\n *\n * We bias toward \"in transaction\": an unrecognised form leaves the flag set,\n * which at worst delays a flush (safe) rather than exporting mid-transaction\n * (which would abort it).\n */\n noteTransactionControl(sql: string): void {\n const s = sql.trim().toUpperCase();\n if (/^BEGIN\\b/.test(s)) {\n this.rootTxActive = true;\n } else if (/^(COMMIT|END)\\b/.test(s)) {\n // A COMMIT/END ends the whole transaction regardless of savepoint nesting.\n this.rootTxActive = false;\n this.savepointDepth = 0;\n } else if (/^ROLLBACK\\s+TO\\b/.test(s)) {\n // Rolls back to a savepoint but keeps the (outer) transaction open.\n } else if (/^ROLLBACK\\b/.test(s)) {\n this.rootTxActive = false;\n this.savepointDepth = 0;\n } else if (/^SAVEPOINT\\b/.test(s)) {\n this.savepointDepth += 1;\n } else if (/^RELEASE\\b/.test(s)) {\n this.savepointDepth = Math.max(0, this.savepointDepth - 1);\n }\n // If the transaction just fully closed and a flush was deferred while it\n // was open, run it now. We key off `flushDeferred` (set only when\n // `markDirty` actually wanted to flush) rather than `dirty`, so persist\n // modes that don't flush per-write — e.g. `on-disconnect` — still defer to\n // close() instead of flushing on every COMMIT.\n if (!this.inTransaction && this.flushDeferred) {\n this.flushDeferred = false;\n void this.flush();\n }\n }\n\n /** Hint that a mutation just executed; schedule a flush if needed. */\n markDirty(method?: string): void {\n if (this.isEphemeral || !this.fs) return;\n if (method && !WRITE_METHODS.has(method)) return;\n this.dirty = true;\n\n if (this.persist === 'on-write') {\n void this.flush();\n return;\n }\n if (this.debounceMs > 0) {\n if (this.debounceTimer) clearTimeout(this.debounceTimer);\n this.debounceTimer = setTimeout(() => {\n this.debounceTimer = null;\n void this.flush();\n }, this.debounceMs);\n }\n // 'on-disconnect' → flush only at close()\n }\n\n /**\n * Force a write of the current database state to disk.\n *\n * Flushes are strictly serialized through a single promise chain: every call\n * appends an export+write step that runs after all previously-queued steps.\n * This matters because sql.js `export()` mutates the live connection (it\n * closes and reopens the database), so two exports must never overlap — and\n * because the returned promise must not resolve until the caller's own write\n * has hit disk (deterministic for tests and for `close()`). Each step\n * re-checks `dirty` at run time, so a no-op write collapses cheaply and a\n * write that arrived mid-flush is captured by the next queued step.\n */\n async flush(): Promise<void> {\n if (this.isEphemeral || !this.fs || this.destroyed) return;\n // Never export while a transaction is open: sql.js's `export()` closes and\n // reopens the database, which rolls back the in-flight transaction and\n // makes the subsequent COMMIT fail. Defer until the transaction closes\n // (handled in `noteTransactionControl`).\n if (this.inTransaction) {\n this.flushDeferred = true;\n return;\n }\n\n const prev = this.flushChain;\n const step = (prev ?? Promise.resolve()).then(async () => {\n if (!this.dirty || this.destroyed || this.inTransaction) return;\n // Snapshot dirty=false before export so a concurrent write re-marks us\n // and is picked up by the next queued step.\n this.dirty = false;\n try {\n const exported = this.db.export();\n // sql.js returns a Uint8Array; Buffer.from on it shares memory but\n // works fine for the atomic write below.\n await this.atomicWriteFile(Buffer.from(exported));\n } catch (err) {\n this.dirty = true; // let a later flush retry\n throw err;\n }\n });\n // Keep the chain tail alive but swallow its rejection there so one failed\n // flush doesn't poison every future flush; the awaited `step` still throws.\n this.flushChain = step.catch(() => {});\n await step;\n }\n\n /**\n * Write the database bytes to disk atomically: write to a sibling temp file,\n * fsync it, then `rename()` it over the target.\n *\n * A plain `writeFile(this.filename, …)` truncates the target and streams the\n * new bytes in place, so a process killed mid-write (a dev-server restart,\n * Ctrl-C, or crash — likely under `on-write`, where every dispatcher tick\n * flushes) leaves a half-written file. sql.js then rejects that file on the\n * next boot with \"database disk image is malformed\". `rename(2)` is atomic\n * within a filesystem, so a reader always sees either the complete old file\n * or the complete new one — never a torn image. The temp file lives in the\n * same directory as the target so the rename stays intra-filesystem.\n */\n private async atomicWriteFile(data: Buffer): Promise<void> {\n if (!this.fs) return;\n const tmp = `${this.filename}.tmp-${process.pid}-${(WasmSqliteConnection.tmpSeq += 1)}`;\n let handle: import('node:fs/promises').FileHandle | undefined;\n try {\n handle = await this.fs.open(tmp, 'w');\n await handle.writeFile(data);\n // Flush the bytes to the platter before the rename so a crash can't leave\n // a renamed-but-empty file behind on filesystems that reorder the two.\n await handle.sync();\n await handle.close();\n handle = undefined;\n await this.fs.rename(tmp, this.filename);\n } catch (err) {\n if (handle) {\n try {\n await handle.close();\n } catch {\n /* ignore */\n }\n }\n // Clean up the temp file so a failed flush doesn't litter the data dir.\n try {\n await this.fs.unlink(tmp);\n } catch {\n /* ignore */\n }\n throw err;\n }\n }\n\n /** Close the database, flushing any pending writes first. */\n async close(): Promise<void> {\n if (this.destroyed) return;\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n // Any transaction still open at close is abandoned and will be rolled back\n // by `db.close()`; clear the flag so the final flush is not deferred and\n // already-committed data is persisted.\n this.rootTxActive = false;\n this.savepointDepth = 0;\n try {\n await this.flush();\n } finally {\n this.destroyed = true;\n try {\n this.db.close();\n } catch {\n /* ignore */\n }\n }\n }\n\n /** Access the raw sql.js database (for the Knex dialect). */\n get raw(): Database {\n return this.db;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaA,wBAAgD;;;ACWhD,yBAA8B;;;ACxB9B;AAuCA,IAAM,gBAAgB,oBAAI,IAAI;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAMD,eAAe,YAA+D;AAC5E,MAAI;AACF,WAAO,MAAM,OAAO,aAAkB;AAAA,EACxC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAOA,eAAe,oBAAqE;AAClF,MAAI;AACF,UAAM,EAAE,eAAAA,eAAc,IAAI,MAAM,OAAO,QAAa;AACpD,UAAMC,WAAUD,eAAc,YAAY,GAAG;AAC7C,UAAM,cAAcC,SAAQ,QAAQ,qBAAqB;AACzD,UAAM,EAAE,SAAS,KAAK,IAAI,MAAM,OAAO,MAAW;AAClD,UAAM,MAAM,QAAQ,WAAW;AAC/B,WAAO,CAAC,SAAiB,KAAK,KAAK,QAAQ,IAAI;AAAA,EACjD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,IAAI,cAA2C;AAE/C,eAAe,UACb,YACsB;AACtB,MAAI,YAAa,QAAO;AACxB,iBAAe,YAAY;AACzB,UAAM,MAAM,MAAM,OAAO,QAAQ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YAAY,WAAY;AAEjD,UAAM,UAAU,OAAO,mBAAmB,KAAK,MAAM;AACrD,UAAM,UAAU,OAAO,mBAAmB,KAAK,MAAM;AACrD,QAAI,CAAC,WAAW,CAAC,QAAS;AAE1B,UAAM,OAAO,MAAM,QAAQ;AAC3B,QAAI;AACF,UAAI,QAAQ,OAAO,KAAK,UAAU,YAAY;AAC5C,cAAM,KAAK,MAAM;AAAA,MACnB;AAAA,IACF,UAAE;AACA,YAAM,QAAQ,IAAI;AAAA,IACpB;AAAA,EACF;AACF;;;ADpLA,IAAO,gBAAQ;AAAA,EACb,IAAI;AAAA,EACJ,SAAS;AAAA,EAET,UAAU,OAAO,YAAiB;AAChC,UAAM,EAAE,QAAQ,QAAQ,QAAQ,IAAI;AACpC,YAAQ,OAAO,sCAAsC;AAErD,QAAI,SAAS;AACX,YAAM,SAAS,IAAI,iBAAiB,MAAM;AAC1C,cAAQ,SAAS,MAAM;AACvB,cAAQ,OAAO,2CAA2C,OAAO,IAAI,EAAE;AAAA,IACzE,OAAO;AACL,cAAQ,OAAO,2DAA2D;AAAA,IAC5E;AAAA,EACF;AACF;","names":["createRequire","require","import_meta","Client_WasmSqlite"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/sqlite-wasm-driver.ts","../src/knex-wasm-dialect.ts","../src/wasm-connection.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { SqliteWasmDriver } from './sqlite-wasm-driver.js';\n\nexport { SqliteWasmDriver };\nexport type { SqliteWasmDriverConfig } from './sqlite-wasm-driver.js';\nexport { Client_WasmSqlite } from './knex-wasm-dialect.js';\nexport type { WasmSqliteConnectionSettings } from './knex-wasm-dialect.js';\nexport { WasmSqliteConnection } from './wasm-connection.js';\nexport type { PersistMode, WasmConnectionOptions } from './wasm-connection.js';\n\nexport default {\n id: 'com.objectstack.driver.sqlite-wasm',\n version: '1.0.0',\n\n onEnable: async (context: any) => {\n const { logger, config, drivers } = context;\n logger?.info?.('[SQLite-WASM Driver] Initializing...');\n\n if (drivers) {\n const driver = new SqliteWasmDriver(config);\n drivers.register(driver);\n logger?.info?.(`[SQLite-WASM Driver] Registered driver: ${driver.name}`);\n } else {\n logger?.warn?.('[SQLite-WASM Driver] No driver registry found in context.');\n }\n },\n};\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * SQLite-on-WASM driver for ObjectStack.\n *\n * Extends {@link SqlDriver} so all CRUD / schema / introspection / multi-tenant\n * logic is inherited as-is. Only the Knex transport is swapped to a custom\n * dialect ({@link Client_WasmSqlite}) backed by sql.js + Node `fs` persistence,\n * which lets the same `SqlDriver` codepath run inside StackBlitz WebContainer\n * (Node-in-browser) without the native `better-sqlite3` N-API binding.\n */\n\nimport type { SqlJsStatic } from 'sql.js';\nimport { SqlDriver, type SqlDriverConfig } from '@objectstack/driver-sql';\n\nimport { getClient_WasmSqlite } from './knex-wasm-dialect.js';\nimport type {\n PersistMode,\n WasmConnectionOptions,\n} from './wasm-connection.js';\n\n/** Public configuration for {@link SqliteWasmDriver}. */\nexport interface SqliteWasmDriverConfig {\n /**\n * SQLite filename. Use `:memory:` for an ephemeral database that is never\n * persisted. Any other value is treated as a Node `fs` path and the\n * sql.js database bytes are flushed back to disk according to {@link persist}.\n */\n filename: string;\n\n /**\n * Persistence strategy. Default: `'on-disconnect'`.\n *\n * - `'on-disconnect'` — flush once when the driver disconnects (and on\n * `process.beforeExit`).\n * - `'on-write'` — flush after every mutation. Safest, slowest.\n * - `` `debounced:${ms}` `` — debounce flushes by N milliseconds. Good\n * balance under bursty writes.\n */\n persist?: PersistMode;\n\n /** Pre-loaded sql.js module — skips lazy import. */\n sqlJs?: SqlJsStatic;\n\n /**\n * Override for sql.js's `locateFile`. Defaults to resolving the `.wasm`\n * file inside the installed `sql.js` package, which works in Node and\n * WebContainer.\n */\n locateFile?: (file: string) => string;\n\n /** Knex pool overrides. The dialect already defaults to `{ min: 1, max: 1 }`. */\n pool?: SqlDriverConfig['pool'];\n\n /** Optional logger. Defaults to `console`. */\n logger?: WasmConnectionOptions['logger'];\n}\n\n/**\n * SqlDriver subclass that runs Knex against sql.js (WASM SQLite).\n *\n * Behaves identically to the standard SQLite path — the dialect's\n * {@link Client_WasmSqlite._query} reports `lastID`/`changes` exactly the\n * way better-sqlite3 does, so {@link SqlDriver}'s SQL generation, returning\n * clauses, and schema introspection all keep working.\n */\nexport class SqliteWasmDriver extends SqlDriver {\n public override readonly name: string = 'com.objectstack.driver.sqlite-wasm';\n public override readonly version: string = '1.0.0';\n\n /**\n * Force the SQLite branch in {@link SqlDriver}. The base class detects\n * SQLite by string-matching `config.client`, but we pass the dialect class\n * directly so the string check would miss.\n */\n protected override get isSqlite(): boolean {\n return true;\n }\n\n /**\n * Never WAL (#3941). The base driver switches a file-backed SQLite database to\n * WAL so several processes can share one file. Nothing here is shared: the live\n * database sits in this process's WASM heap, and what reaches disk is a byte\n * image {@link flush} exports from it — another process reads that snapshot,\n * never the database. So the pragma buys this transport nothing.\n *\n * It is also not free. Journal mode is a persistent header change in the\n * operator's file, and under WAL the export path's correctness would rest on\n * sql.js checkpointing the log while `export()` closes and reopens the\n * database. Measured, it does — no row is lost today — which is why this is a\n * declined default and not a bug report. But a transport that persists by\n * serializing an image should not be one implementation detail away from\n * dropping committed rows for a concurrency benefit it cannot use.\n *\n * Declared rather than discovered: sql.js *accepts* `journal_mode = WAL`,\n * because its VFS is memory-backed, so the refusal the base class gets from\n * `:memory:` never comes — and an image whose header already says WAL (one a\n * native run left behind) reports `wal` here too.\n */\n protected override get supportsWalJournal(): boolean {\n return false;\n }\n\n private wasmConfig: SqliteWasmDriverConfig;\n private beforeExitHandler: (() => void) | null = null;\n\n constructor(config: SqliteWasmDriverConfig) {\n const knexConfig = SqliteWasmDriver.toKnexConfig(config);\n super(knexConfig);\n this.wasmConfig = config;\n if (config.logger) this.logger = config.logger as any;\n }\n\n /** Translate the public config into a Knex config that uses our dialect. */\n static toKnexConfig(config: SqliteWasmDriverConfig): SqlDriverConfig {\n return {\n // Knex accepts a Client class as `client`. The dialect's `driverName`\n // is `'wasm-sqlite'` and its `dialect` is `'sqlite3'` so the SQLite\n // query compiler is reused.\n client: getClient_WasmSqlite() as any,\n connection: {\n filename: config.filename,\n persist: config.persist,\n sqlJs: config.sqlJs,\n locateFile: config.locateFile,\n logger: config.logger,\n } as any,\n // sql.js is single-threaded WASM — a single connection per pool keeps\n // semantics consistent with the upstream SQLite dialect.\n pool: config.pool ?? { min: 1, max: 1 },\n useNullAsDefault: true,\n } as SqlDriverConfig;\n }\n\n override async connect(): Promise<void> {\n await super.connect();\n\n // Best-effort flush on process exit so `on-disconnect` mode still saves\n // user data if the host process is shut down without explicit cleanup.\n if (\n this.wasmConfig.filename !== ':memory:' &&\n !this.wasmConfig.filename.startsWith(':') &&\n typeof process !== 'undefined' &&\n typeof process.once === 'function'\n ) {\n this.beforeExitHandler = () => {\n // Fire-and-forget — beforeExit cannot await.\n void this.flush().catch(() => {\n /* ignore */\n });\n };\n process.once('beforeExit', this.beforeExitHandler);\n }\n }\n\n override async disconnect(): Promise<void> {\n if (this.beforeExitHandler && typeof process !== 'undefined') {\n try {\n process.removeListener('beforeExit', this.beforeExitHandler);\n } catch {\n /* ignore */\n }\n this.beforeExitHandler = null;\n }\n await super.disconnect();\n }\n\n /**\n * Force a flush of the in-memory database to disk. No-op for ephemeral\n * databases or when no fs is available.\n */\n async flush(): Promise<void> {\n // Reach into the Knex pool and ask every live connection to flush.\n const knex = (this as any).knex;\n const client = knex?.client;\n const pool = client?.pool;\n if (!pool || typeof pool.numUsed !== 'function') return;\n\n const acquire = client.acquireConnection?.bind(client);\n const release = client.releaseConnection?.bind(client);\n if (!acquire || !release) return;\n\n const conn = await acquire();\n try {\n if (conn && typeof conn.flush === 'function') {\n await conn.flush();\n }\n } finally {\n await release(conn);\n }\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Custom Knex SQLite dialect backed by sql.js (WASM SQLite).\n *\n * Mimics the surface that `Client_BetterSQLite3` presents to Knex so the\n * upstream SQLite3 dialect's query compiler, schema builder, and column\n * compiler all keep working unchanged. Only the transport layer —\n * `_driver` / `acquireRawConnection` / `_query` — is swapped out.\n *\n * ## Why the dialect class is built lazily\n *\n * The class `Client_WasmSqlite extends Client_SQLite3` needs the upstream\n * SQLite3 dialect at class-definition time. Resolving it at module\n * top-level breaks when this file is re-bundled by another tsup/esbuild\n * pass (e.g. `packages/runtime`), because that pass rewrites our runtime\n * `createRequire(import.meta.url)` chain back into a static `__require2`\n * Proxy stub that throws `Dynamic require of \"X\" is not supported`.\n *\n * Building the class inside a lazy factory (`getClient_WasmSqlite()`)\n * keeps the `require` call out of module-init code, so the re-bundler\n * cannot intercept it.\n */\n\nimport { createRequire } from 'node:module';\n\nimport type { SqlJsStatic } from 'sql.js';\n\nimport {\n WasmSqliteConnection,\n type PersistMode,\n type WasmConnectionOptions,\n} from './wasm-connection.js';\n\n// Built lazily — `node:module` is a Node builtin and is left untouched\n// by esbuild/tsup, so the `createRequire` import survives downstream\n// re-bundling. We defer the actual `createRequire(...)` call so that the\n// CJS build (where `import.meta.url` is empty) doesn't blow up at module\n// init; the CJS path uses `globalThis.require` directly anyway.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet cachedEsmRequire: any = null;\nfunction getEsmRequire(): any {\n if (cachedEsmRequire) return cachedEsmRequire;\n // `import.meta.url` is replaced with an empty string in CJS output;\n // fall back to the current file/cwd in that case.\n const anchor =\n typeof import.meta !== 'undefined' && (import.meta as any).url\n ? (import.meta as any).url\n : typeof __filename !== 'undefined'\n ? __filename\n : process.cwd() + '/';\n cachedEsmRequire = createRequire(anchor);\n return cachedEsmRequire;\n}\n\n/** Connection settings recognised by the WASM SQLite dialect. */\nexport interface WasmSqliteConnectionSettings {\n filename: string;\n persist?: PersistMode;\n sqlJs?: SqlJsStatic;\n locateFile?: (file: string) => string;\n logger?: WasmConnectionOptions['logger'];\n}\n\n/**\n * Coerce JS values that sql.js cannot bind directly. Mirrors\n * `Client_BetterSQLite3._formatBindings`.\n *\n * `undefined` is mapped to `null`: sql.js's binder only accepts\n * string/number/bigint/boolean/null (and array/blob) and `throw`s a *raw\n * string* — `\"Wrong API use : tried to bind a value of an unknown type\n * (undefined).\"` — for anything else. Because it throws a string rather than\n * an `Error`, it logs as a garbled char-indexed object and aborts the whole\n * write. Mapping to `null` matches the `useNullAsDefault` semantics the\n * dialect is configured with, so a missing/undefined value persists as SQL\n * `NULL` exactly as it would through better-sqlite3.\n */\nfunction formatBindings(bindings: unknown[] | undefined): unknown[] {\n if (!bindings) return [];\n return bindings.map((b) => {\n if (b === undefined) return null;\n if (b instanceof Date) return b.valueOf();\n if (typeof b === 'boolean') return Number(b);\n return b;\n });\n}\n\n/**\n * Mirrors the dispatch in upstream `Client_SQLite3._query`: only\n * `insert/update/counter/del` go through the row-less write path (and even\n * those switch to the read path when a `RETURNING` clause is requested).\n * Everything else — `select`, `first`, `pluck`, `columnInfo`, raw PRAGMA,\n * DDL with no `method` — is read with `all`/row iteration so Knex sees the\n * same response shape it would from better-sqlite3.\n *\n * ⚠️ This answers \"how do I EXECUTE this statement\", never \"does this statement\n * change the database\" — an `INSERT … RETURNING *` is executed down the\n * row-returning branch and mutates. Persistence is classified separately by\n * {@link statementMutatesDatabase}; conflating the two is #4518.\n */\nfunction isRowReturningExecution(method?: string, returning?: unknown): boolean {\n if (method === 'insert' || method === 'update') return !!returning ? true : false;\n if (method === 'counter' || method === 'del') return false;\n return true;\n}\n\n/** Knex `method` values that always denote a mutation. */\nconst MUTATING_METHODS = new Set(['insert', 'update', 'del', 'counter']);\n\n/** Statement-control forms whose persistence is owned by the transaction lifecycle. */\nconst TRANSACTION_CONTROL_RE = /^\\s*(BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\\b/i;\n\n/**\n * DDL / schema statements. `BEGIN…RELEASE` share this prefix set in SQLite's\n * grammar but are transaction control, so they are matched (and routed) first.\n */\nconst DDL_RE =\n /^\\s*(CREATE|ALTER|DROP|BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE|REINDEX|VACUUM|ATTACH|DETACH|TRUNCATE)\\b/i;\n\n/** DML that changes rows, whatever execution branch it happens to run down. */\nconst MUTATING_DML_RE = /^\\s*(INSERT|UPDATE|DELETE|REPLACE|UPSERT)\\b/i;\n\n/**\n * PRAGMA forms that change bytes in the database file: any assignment\n * (`PRAGMA auto_vacuum = INCREMENTAL`, `PRAGMA user_version = 3` — both\n * persistent header state) and `incremental_vacuum`, which actually moves\n * pages. Introspection PRAGMAs (`table_info`, `index_list`, …) are reads.\n */\nconst MUTATING_PRAGMA_RE = /^\\s*PRAGMA\\b(?:[^;]*=|\\s+incremental_vacuum\\b)/i;\n\n/**\n * THE single answer to \"did this statement change the database, so that the\n * in-memory image must eventually be written back to disk?\"\n *\n * It is deliberately independent of which execution branch {@link\n * isRowReturningExecution} picks, because those are different questions and\n * answering them with one predicate is what broke persistence in #4518: the\n * ObjectQL engine writes through `INSERT … RETURNING *` / `UPDATE … RETURNING *`\n * (it needs the stored row back), those run down the row-returning branch, and\n * the dirty flag was only ever set on the other branch. The result was a\n * file-backed database that flushed its schema and then silently stopped\n * recording anything — a cold boot found every table present and every row\n * gone, and `on-disconnect` did not save it either, because the final flush\n * also keys off the same flag.\n *\n * Classifying by BOTH the Knex `method` and the SQL text means a mutation\n * cannot slip through by arriving without a method (`knex.raw('INSERT …')`,\n * seed/migration SQL) or by taking an unexpected branch.\n */\nexport function statementMutatesDatabase(sql: string, method?: string): boolean {\n if (TRANSACTION_CONTROL_RE.test(sql)) return false; // owned by noteTransactionControl\n if (method && MUTATING_METHODS.has(method)) return true;\n if (DDL_RE.test(sql)) return true;\n if (MUTATING_DML_RE.test(sql)) return true;\n return MUTATING_PRAGMA_RE.test(sql);\n}\n\n/**\n * Resolve the upstream `knex/lib/dialects/sqlite3` class at runtime.\n *\n * Tries every escape hatch we have so that this works in:\n * - Plain Node ESM (use `createRequire(import.meta.url)`).\n * - Plain Node CJS (use the ambient `require` on `globalThis`).\n * - Re-bundled ESM where esbuild/tsup has stubbed `__require` — we\n * fall back to `new Function('return require')()` which evades static\n * analysis and grabs the real Node `require` at runtime.\n *\n * Wrapped in a function so the bundler cannot execute it at module init.\n */\nfunction resolveKnexSqlite3Dialect(): any {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const g = globalThis as any;\n if (typeof g.require === 'function') {\n try {\n return g.require('knex/lib/dialects/sqlite3');\n } catch {\n /* fall through */\n }\n }\n // ESM-safe path: `createRequire` was imported statically at the top of\n // this module from `node:module`. In a pure-ESM process there is no\n // ambient `require`, so this is the only reliable way to load a CJS\n // package like `knex/lib/dialects/sqlite3`.\n return getEsmRequire()('knex/lib/dialects/sqlite3');\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet cachedDialect: any = null;\n\n/**\n * Build (and cache) the `Client_WasmSqlite` class. Building lazily keeps\n * the `require('knex/lib/dialects/sqlite3')` call out of module-init\n * code so downstream re-bundlers (e.g. `packages/runtime`) cannot collapse\n * it into a Dynamic-require stub.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getClient_WasmSqlite(): any {\n if (cachedDialect) return cachedDialect;\n const Client_SQLite3 = resolveKnexSqlite3Dialect();\n\n class Client_WasmSqlite extends Client_SQLite3 {\n // sql.js has no shared \"driver module\" the way better-sqlite3 does. Knex\n // only uses `this.driver` to construct connections, and we override\n // `acquireRawConnection`, so a sentinel object is enough.\n _driver(): { name: 'sql.js' } {\n return { name: 'sql.js' };\n }\n\n async acquireRawConnection(): Promise<WasmSqliteConnection> {\n const settings = (this as any)\n .connectionSettings as WasmSqliteConnectionSettings;\n\n const conn = new WasmSqliteConnection({\n filename: settings.filename,\n persist: settings.persist,\n sqlJs: settings.sqlJs,\n locateFile: settings.locateFile,\n logger: settings.logger,\n });\n await conn.open(settings.sqlJs, settings.locateFile);\n return conn;\n }\n\n async destroyRawConnection(connection: WasmSqliteConnection): Promise<void> {\n await connection.close();\n }\n\n async _query(\n connection: WasmSqliteConnection,\n obj: any,\n ): Promise<any> {\n if (!obj.sql) throw new Error('The query is empty');\n if (!connection) throw new Error('No connection provided');\n\n const db = connection.raw;\n const bindings = formatBindings(obj.bindings);\n\n // ── 1. EXECUTE ────────────────────────────────────────────────────────\n // Three execution shapes. None of them decides persistence: that is\n // settled once, below, so a statement cannot mutate the database on a\n // branch that forgot to say so (#4518).\n\n // DDL / transaction control have no Knex `method`. sql.js's\n // `prepare`+`step` silently no-ops on many of these (e.g. CREATE TABLE),\n // so route them through `run` which is implemented via `exec` and\n // actually mutates the database. PRAGMA is intentionally excluded — many\n // PRAGMA forms (e.g. `PRAGMA table_info(...)`, `foreign_key_list(...)`)\n // return rows used by Knex's schema introspection/columnInfo, and\n // `db.run` discards those rows.\n if (DDL_RE.test(obj.sql)) {\n db.run(obj.sql, bindings as any);\n obj.response = [];\n } else if (\n isRowReturningExecution(obj.method, obj.returning) ||\n /^\\s*PRAGMA\\b/i.test(obj.sql)\n ) {\n // Row-returning branch. NOTE this is also where `INSERT … RETURNING *`\n // and `UPDATE … RETURNING *` land — statements that very much write.\n const stmt = db.prepare(obj.sql);\n try {\n if (bindings.length) stmt.bind(bindings as any);\n const rows: Record<string, unknown>[] = [];\n while (stmt.step()) {\n rows.push(stmt.getAsObject());\n }\n obj.response = rows;\n } finally {\n stmt.free();\n }\n } else {\n // Row-less write path: execute via `run` and capture SQLite's\n // per-connection lastID / changes counters.\n db.run(obj.sql, bindings as any);\n const changes = db.getRowsModified();\n let lastID: number | bigint = 0;\n if (obj.method === 'insert') {\n const r = db.exec('SELECT last_insert_rowid() AS id');\n lastID = (r?.[0]?.values?.[0]?.[0] as number) ?? 0;\n }\n obj.response = [];\n obj.context = { lastID, changes };\n }\n\n // ── 2. PERSIST ────────────────────────────────────────────────────────\n // Exactly one place decides whether the on-disk image is now stale.\n //\n // Transaction-control statements are routed to `noteTransactionControl`,\n // which owns flushing across the transaction lifecycle: it suppresses\n // flushes while a transaction is open (sql.js `export()` closes+reopens\n // the db, which would abort the txn) and performs a single flush once the\n // transaction fully closes. Routing them away from `markDirty` avoids a\n // second, racing flush on COMMIT.\n if (TRANSACTION_CONTROL_RE.test(obj.sql)) {\n connection.noteTransactionControl(obj.sql);\n } else if (statementMutatesDatabase(obj.sql, obj.method)) {\n connection.markDirty();\n }\n return obj;\n }\n }\n\n Object.assign(Client_WasmSqlite.prototype, {\n dialect: 'sqlite3',\n driverName: 'wasm-sqlite',\n });\n\n cachedDialect = Client_WasmSqlite;\n return Client_WasmSqlite;\n}\n\n/**\n * Back-compat re-export. Prefer `getClient_WasmSqlite()` so the dialect\n * is resolved lazily; the named export triggers the factory on first\n * access of any static property.\n *\n * Note: importing this binding will execute the factory at import time\n * in some bundlers, which defeats the lazy pattern. New code should call\n * `getClient_WasmSqlite()` directly.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const Client_WasmSqlite: any = new Proxy(function () {} as any, {\n get(_t, prop) {\n return (getClient_WasmSqlite() as any)[prop];\n },\n construct(_t, args) {\n const Klass = getClient_WasmSqlite();\n return new Klass(...args);\n },\n apply(_t, thisArg, args) {\n const Klass = getClient_WasmSqlite();\n return Reflect.apply(Klass, thisArg, args);\n },\n});\n\nexport default Client_WasmSqlite;\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Thin wrapper over sql.js {@link Database} that mimics the surface of\n * `better-sqlite3`'s `Database` (only the methods the Knex dialect uses).\n *\n * Persistence is handled here, not in the Knex dialect, so it can be\n * orchestrated per-connection without polluting the SQL execution path.\n */\n\nimport type { Database, SqlJsStatic } from 'sql.js';\n\n/** When to flush the in-memory WASM database to disk. */\nexport type PersistMode =\n | 'on-disconnect'\n | 'on-write'\n | `debounced:${number}`;\n\nexport interface WasmConnectionOptions {\n /**\n * On-disk file path. `:memory:` (or any value starting with `:`) skips\n * persistence entirely and the database lives only for the process.\n */\n filename: string;\n /** When to persist. Default: `on-disconnect`. */\n persist?: PersistMode;\n /** Pre-loaded sql.js module. If omitted, loaded lazily on first connect. */\n sqlJs?: SqlJsStatic;\n /**\n * Optional override for the `.wasm` locator passed to `initSqlJs()`.\n * Defaults to resolving the file from the `sql.js` package on disk\n * (works in Node and WebContainer).\n */\n locateFile?: (file: string) => string;\n /** Optional logger; defaults to `console`. */\n logger?: { warn: (msg: string, meta?: unknown) => void };\n}\n\n/**\n * Detect whether a Node-style `fs` module is available. WebContainer\n * (StackBlitz) provides Node `fs`; pure-browser environments do not.\n */\nasync function tryLoadFs(): Promise<typeof import('node:fs/promises') | null> {\n try {\n return await import('node:fs/promises');\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve a default sql.js WASM locator. We point sql.js at the `.wasm`\n * file shipped inside `sql.js`'s own `dist/` folder. This avoids requiring\n * the caller to host the WASM separately.\n */\nasync function defaultLocateFile(): Promise<((file: string) => string) | undefined> {\n try {\n const { createRequire } = await import('node:module');\n const require = createRequire(import.meta.url);\n const pkgJsonPath = require.resolve('sql.js/package.json');\n const { dirname, join } = await import('node:path');\n const dir = dirname(pkgJsonPath);\n return (file: string) => join(dir, 'dist', file);\n } catch {\n return undefined;\n }\n}\n\nlet cachedSqlJs: Promise<SqlJsStatic> | null = null;\n\nasync function loadSqlJs(\n locateFile?: (file: string) => string,\n): Promise<SqlJsStatic> {\n if (cachedSqlJs) return cachedSqlJs;\n cachedSqlJs = (async () => {\n const mod = await import('sql.js');\n const initSqlJs = (mod as any).default ?? (mod as any);\n const locator = locateFile ?? (await defaultLocateFile());\n const SQL = await initSqlJs(locator ? { locateFile: locator } : undefined);\n return SQL as SqlJsStatic;\n })();\n return cachedSqlJs;\n}\n\n/**\n * A sql.js-backed connection that exposes the `prepare`/`exec`/`close`\n * subset used by Knex's SQLite dialect. Mutations are queued through a\n * configurable persistence strategy so the on-disk file stays in sync.\n */\nexport class WasmSqliteConnection {\n /**\n * Process-wide counter making each atomic-write temp filename unique, so\n * concurrent connections (or overlapping flushes) never target the same\n * temp path. Combined with `process.pid` for cross-process uniqueness.\n */\n private static tmpSeq = 0;\n\n readonly filename: string;\n readonly persist: PersistMode;\n readonly isEphemeral: boolean;\n\n private db!: Database;\n private fs: typeof import('node:fs/promises') | null = null;\n private dirty = false;\n private debounceMs = 0;\n private debounceTimer: ReturnType<typeof setTimeout> | null = null;\n private flushChain: Promise<void> | null = null;\n private destroyed = false;\n private logger: { warn: (msg: string, meta?: unknown) => void };\n\n /**\n * Whether a `BEGIN…COMMIT/ROLLBACK` transaction is currently open. Tracked\n * because sql.js's {@link Database.export} closes and reopens the database\n * (it has no in-place serialize), and closing a connection rolls back any\n * open transaction. Flushing mid-transaction would therefore silently\n * abort it, leaving the eventual `COMMIT` to fail with\n * \"cannot commit - no transaction is active\". We defer the flush until the\n * transaction fully closes. See {@link noteTransactionControl}.\n */\n private rootTxActive = false;\n /** Open `SAVEPOINT` depth (nested transactions emitted by Knex). */\n private savepointDepth = 0;\n /** A flush was requested while a transaction was open; run it on close. */\n private flushDeferred = false;\n\n /** True while any transaction (root or savepoint) is in flight. */\n private get inTransaction(): boolean {\n return this.rootTxActive || this.savepointDepth > 0;\n }\n\n constructor(opts: WasmConnectionOptions) {\n this.filename = opts.filename;\n this.persist = opts.persist ?? 'on-disconnect';\n this.isEphemeral =\n this.filename === ':memory:' || this.filename.startsWith(':');\n this.logger = opts.logger ?? console;\n\n if (typeof this.persist === 'string' && this.persist.startsWith('debounced:')) {\n const ms = Number(this.persist.slice('debounced:'.length));\n this.debounceMs = Number.isFinite(ms) && ms > 0 ? ms : 250;\n }\n }\n\n /** Open the underlying sql.js database, loading bytes from disk if any. */\n async open(sqlJs?: SqlJsStatic, locateFile?: (file: string) => string): Promise<void> {\n const SQL = sqlJs ?? (await loadSqlJs(locateFile));\n\n if (this.isEphemeral) {\n this.db = new SQL.Database();\n return;\n }\n\n this.fs = await tryLoadFs();\n if (!this.fs) {\n this.logger.warn(\n '[driver-sqlite-wasm] No node:fs available — falling back to in-memory database. ' +\n 'Data will not be persisted across reloads.',\n );\n this.db = new SQL.Database();\n return;\n }\n\n // Ensure parent directory exists, then load bytes if the file exists.\n const { dirname } = await import('node:path');\n const dir = dirname(this.filename);\n if (dir && dir !== '.') {\n await this.fs.mkdir(dir, { recursive: true });\n }\n\n let bytes: Uint8Array | undefined;\n try {\n const buf = await this.fs.readFile(this.filename);\n bytes = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n } catch (e: any) {\n if (e?.code !== 'ENOENT') throw e;\n }\n\n if (!bytes) {\n this.db = new SQL.Database();\n return;\n }\n\n await this.quarantineOrphanedWal();\n\n // Open the on-disk bytes, but guard against a corrupt image. A torn write\n // (process killed mid-flush before atomic writes existed) or otherwise\n // damaged file makes `new SQL.Database(bytes)` either throw (\"file is not a\n // database\") or open a handle whose every query fails with \"database disk\n // image is malformed\" — which, for a background dispatcher on a tick loop,\n // means the same error spammed forever with no path to recovery. Detect it\n // once at open, quarantine the bad file, and start fresh so the dev server\n // becomes usable again instead of wedging.\n try {\n const candidate = new SQL.Database(bytes);\n this.assertReadable(candidate);\n this.db = candidate;\n } catch (err) {\n await this.quarantineCorruptFile(err);\n this.db = new SQL.Database();\n }\n }\n\n /**\n * Force sql.js to actually read a page so a malformed image surfaces now\n * rather than on the first business query. `PRAGMA quick_check` walks the\n * b-tree structure without the full-scan cost of `integrity_check`; a healthy\n * database returns a single `ok` row. Any thrown error (raw string or Error)\n * or a non-`ok` result is treated as corruption.\n */\n private assertReadable(db: Database): void {\n const res = db.exec('PRAGMA quick_check(1)');\n const first = res?.[0]?.values?.[0]?.[0];\n if (typeof first === 'string' && first.toLowerCase() !== 'ok') {\n throw new Error(`sqlite quick_check failed: ${first}`);\n }\n }\n\n /**\n * Move a corrupt database file aside so its bytes are preserved for\n * post-mortem while a fresh, empty database takes its place. Best-effort:\n * failures here must not prevent the server from booting on a clean DB.\n */\n private async quarantineCorruptFile(cause: unknown): Promise<void> {\n if (!this.fs) return;\n const reason =\n typeof cause === 'string' ? cause : (cause as Error)?.message ?? String(cause);\n const backup = `${this.filename}.corrupt-${Date.now()}`;\n try {\n await this.fs.rename(this.filename, backup);\n this.logger.warn(\n `[driver-sqlite-wasm] Database image at ${this.filename} is corrupt ` +\n `(${reason}). Quarantined to ${backup} and starting from an empty ` +\n `database so the server can boot.`,\n );\n } catch (renameErr) {\n // Could not move it aside (e.g. permissions) — overwrite is still better\n // than looping forever on a malformed image. Warn loudly and continue.\n this.logger.warn(\n `[driver-sqlite-wasm] Database image at ${this.filename} is corrupt ` +\n `(${reason}) and could not be quarantined (${String(renameErr)}). ` +\n `Starting from an empty database; the corrupt file will be overwritten ` +\n `on the next flush.`,\n );\n }\n }\n\n /**\n * Move a write-ahead log left behind by a *real* SQLite aside (#3941).\n *\n * The native driver keeps file-backed databases in WAL mode, and a clean close\n * checkpoints the log away — so a non-empty `<db>-wal` here means the last\n * process died without one. That log is a problem in both directions, and\n * neither is something wasm SQLite can fix: it cannot read the log (we load\n * only the main image, so any transaction still in there is invisible), and it\n * must not leave it in place either — the next {@link flush} rewrites the\n * image, and a real SQLite opening a fresh image beside a stale log would\n * replay frames that no longer belong to it.\n *\n * So rename it, which loses nothing recoverable (the bytes are preserved for a\n * real `sqlite3` to recover from) and disarms the mismatch. Best-effort: this\n * is a dev-only step-down path and must never prevent a boot.\n */\n private async quarantineOrphanedWal(): Promise<void> {\n if (!this.fs) return;\n const wal = `${this.filename}-wal`;\n let size: number;\n try {\n size = (await this.fs.stat(wal)).size;\n } catch {\n return; // no sidecar (the normal case) or an unreadable one\n }\n if (size <= 0) return; // checkpointed-and-truncated: nothing in it\n\n const parked = `${wal}.orphaned-${Date.now()}`;\n try {\n await this.fs.rename(wal, parked);\n this.logger.warn(\n `[driver-sqlite-wasm] ${wal} holds ${size} bytes of write-ahead log that wasm SQLite ` +\n `cannot read — this database was last used in WAL mode and closed uncleanly. Parked it ` +\n `at ${parked} and loaded the main image without it, so anything committed only to the ` +\n `log is NOT in this session. To recover it, rebuild better-sqlite3 (or use \\`sqlite3\\`), ` +\n `restore the log next to the database, and run \\`PRAGMA wal_checkpoint(TRUNCATE)\\`.`,\n );\n } catch (renameErr) {\n this.logger.warn(\n `[driver-sqlite-wasm] ${wal} holds ${size} bytes of write-ahead log that wasm SQLite ` +\n `cannot read, and it could not be moved aside (${String(renameErr)}). Data committed ` +\n `only to the log is missing from this session; checkpoint it with a real sqlite3 before ` +\n `writing further.`,\n );\n }\n }\n\n /**\n * Update transaction state from a transaction-control statement and, when a\n * transaction has just fully closed, run any flush that was deferred while\n * it was open. Called by the Knex dialect for every `BEGIN` / `COMMIT` /\n * `ROLLBACK` / `SAVEPOINT` / `RELEASE` statement.\n *\n * We bias toward \"in transaction\": an unrecognised form leaves the flag set,\n * which at worst delays a flush (safe) rather than exporting mid-transaction\n * (which would abort it).\n */\n noteTransactionControl(sql: string): void {\n const s = sql.trim().toUpperCase();\n if (/^BEGIN\\b/.test(s)) {\n this.rootTxActive = true;\n } else if (/^(COMMIT|END)\\b/.test(s)) {\n // A COMMIT/END ends the whole transaction regardless of savepoint nesting.\n this.rootTxActive = false;\n this.savepointDepth = 0;\n } else if (/^ROLLBACK\\s+TO\\b/.test(s)) {\n // Rolls back to a savepoint but keeps the (outer) transaction open.\n } else if (/^ROLLBACK\\b/.test(s)) {\n this.rootTxActive = false;\n this.savepointDepth = 0;\n } else if (/^SAVEPOINT\\b/.test(s)) {\n this.savepointDepth += 1;\n } else if (/^RELEASE\\b/.test(s)) {\n this.savepointDepth = Math.max(0, this.savepointDepth - 1);\n }\n // If the transaction just fully closed and a flush was deferred while it\n // was open, run it now. We key off `flushDeferred` (set only when\n // `markDirty` actually wanted to flush) rather than `dirty`, so persist\n // modes that don't flush per-write — e.g. `on-disconnect` — still defer to\n // close() instead of flushing on every COMMIT.\n if (!this.inTransaction && this.flushDeferred) {\n this.flushDeferred = false;\n void this.flush();\n }\n }\n\n /**\n * Record that the statement just executed CHANGED the database, and schedule\n * a flush according to {@link persist}.\n *\n * Deliberately takes no argument. It used to filter the caller's Knex\n * `method` against a local write-method allowlist, which made \"did this\n * mutate?\" a decision taken in TWO places — here and in the dialect's\n * execution-path branch — and the two disagreed: an `INSERT … RETURNING`\n * runs down the dialect's ROW-returning branch (it has rows to return), that\n * branch never called this method at all, and so a whole class of committed\n * writes was never marked dirty and never reached disk (#4518). One decision,\n * one owner: {@link statementMutatesDatabase} in the dialect classifies the\n * statement, and this method just does what it is told.\n */\n markDirty(): void {\n if (this.isEphemeral || !this.fs) return;\n this.dirty = true;\n\n if (this.persist === 'on-write') {\n void this.flush();\n return;\n }\n if (this.debounceMs > 0) {\n if (this.debounceTimer) clearTimeout(this.debounceTimer);\n this.debounceTimer = setTimeout(() => {\n this.debounceTimer = null;\n void this.flush();\n }, this.debounceMs);\n }\n // 'on-disconnect' → flush only at close()\n }\n\n /**\n * Force a write of the current database state to disk.\n *\n * Flushes are strictly serialized through a single promise chain: every call\n * appends an export+write step that runs after all previously-queued steps.\n * This matters because sql.js `export()` mutates the live connection (it\n * closes and reopens the database), so two exports must never overlap — and\n * because the returned promise must not resolve until the caller's own write\n * has hit disk (deterministic for tests and for `close()`). Each step\n * re-checks `dirty` at run time, so a no-op write collapses cheaply and a\n * write that arrived mid-flush is captured by the next queued step.\n */\n async flush(): Promise<void> {\n if (this.isEphemeral || !this.fs || this.destroyed) return;\n // Never export while a transaction is open: sql.js's `export()` closes and\n // reopens the database, which rolls back the in-flight transaction and\n // makes the subsequent COMMIT fail. Defer until the transaction closes\n // (handled in `noteTransactionControl`).\n if (this.inTransaction) {\n this.flushDeferred = true;\n return;\n }\n\n const prev = this.flushChain;\n const step = (prev ?? Promise.resolve()).then(async () => {\n if (!this.dirty || this.destroyed || this.inTransaction) return;\n // Snapshot dirty=false before export so a concurrent write re-marks us\n // and is picked up by the next queued step.\n this.dirty = false;\n try {\n const exported = this.db.export();\n // sql.js returns a Uint8Array; Buffer.from on it shares memory but\n // works fine for the atomic write below.\n await this.atomicWriteFile(Buffer.from(exported));\n } catch (err) {\n this.dirty = true; // let a later flush retry\n throw err;\n }\n });\n // Keep the chain tail alive but swallow its rejection there so one failed\n // flush doesn't poison every future flush; the awaited `step` still throws.\n this.flushChain = step.catch(() => {});\n await step;\n }\n\n /**\n * Write the database bytes to disk atomically: write to a sibling temp file,\n * fsync it, then `rename()` it over the target.\n *\n * A plain `writeFile(this.filename, …)` truncates the target and streams the\n * new bytes in place, so a process killed mid-write (a dev-server restart,\n * Ctrl-C, or crash — likely under `on-write`, where every dispatcher tick\n * flushes) leaves a half-written file. sql.js then rejects that file on the\n * next boot with \"database disk image is malformed\". `rename(2)` is atomic\n * within a filesystem, so a reader always sees either the complete old file\n * or the complete new one — never a torn image. The temp file lives in the\n * same directory as the target so the rename stays intra-filesystem.\n */\n private async atomicWriteFile(data: Buffer): Promise<void> {\n if (!this.fs) return;\n const tmp = `${this.filename}.tmp-${process.pid}-${(WasmSqliteConnection.tmpSeq += 1)}`;\n let handle: import('node:fs/promises').FileHandle | undefined;\n try {\n handle = await this.fs.open(tmp, 'w');\n await handle.writeFile(data);\n // Flush the bytes to the platter before the rename so a crash can't leave\n // a renamed-but-empty file behind on filesystems that reorder the two.\n await handle.sync();\n await handle.close();\n handle = undefined;\n await this.fs.rename(tmp, this.filename);\n } catch (err) {\n if (handle) {\n try {\n await handle.close();\n } catch {\n /* ignore */\n }\n }\n // Clean up the temp file so a failed flush doesn't litter the data dir.\n try {\n await this.fs.unlink(tmp);\n } catch {\n /* ignore */\n }\n throw err;\n }\n }\n\n /** Close the database, flushing any pending writes first. */\n async close(): Promise<void> {\n if (this.destroyed) return;\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n // Any transaction still open at close is abandoned and will be rolled back\n // by `db.close()`; clear the flag so the final flush is not deferred and\n // already-committed data is persisted.\n this.rootTxActive = false;\n this.savepointDepth = 0;\n try {\n await this.flush();\n } finally {\n this.destroyed = true;\n try {\n this.db.close();\n } catch {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AAU,OAAO,mBAAmB,KAAK,MAAM;AACrD,UAAM,UAAU,OAAO,mBAAmB,KAAK,MAAM;AACrD,QAAI,CAAC,WAAW,CAAC,QAAS;AAE1B,UAAM,OAAO,MAAM,QAAQ;AAC3B,QAAI;AACF,UAAI,QAAQ,OAAO,KAAK,UAAU,YAAY;AAC5C,cAAM,KAAK,MAAM;AAAA,MACnB;AAAA,IACF,UAAE;AACA,YAAM,QAAQ,IAAI;AAAA,IACpB;AAAA,EACF;AACF;;;ADpLA,IAAO,gBAAQ;AAAA,EACb,IAAI;AAAA,EACJ,SAAS;AAAA,EAET,UAAU,OAAO,YAAiB;AAChC,UAAM,EAAE,QAAQ,QAAQ,QAAQ,IAAI;AACpC,YAAQ,OAAO,sCAAsC;AAErD,QAAI,SAAS;AACX,YAAM,SAAS,IAAI,iBAAiB,MAAM;AAC1C,cAAQ,SAAS,MAAM;AACvB,cAAQ,OAAO,2CAA2C,OAAO,IAAI,EAAE;AAAA,IACzE,OAAO;AACL,cAAQ,OAAO,2DAA2D;AAAA,IAC5E;AAAA,EACF;AACF;","names":["createRequire","require","import_meta","Client_WasmSqlite"]}
|
package/dist/index.mjs
CHANGED
|
@@ -5,13 +5,6 @@ import { SqlDriver } from "@objectstack/driver-sql";
|
|
|
5
5
|
import { createRequire } from "module";
|
|
6
6
|
|
|
7
7
|
// src/wasm-connection.ts
|
|
8
|
-
var WRITE_METHODS = /* @__PURE__ */ new Set([
|
|
9
|
-
"run",
|
|
10
|
-
"insert",
|
|
11
|
-
"update",
|
|
12
|
-
"del",
|
|
13
|
-
"counter"
|
|
14
|
-
]);
|
|
15
8
|
async function tryLoadFs() {
|
|
16
9
|
try {
|
|
17
10
|
return await import("fs/promises");
|
|
@@ -222,10 +215,22 @@ var _WasmSqliteConnection = class _WasmSqliteConnection {
|
|
|
222
215
|
void this.flush();
|
|
223
216
|
}
|
|
224
217
|
}
|
|
225
|
-
/**
|
|
226
|
-
|
|
218
|
+
/**
|
|
219
|
+
* Record that the statement just executed CHANGED the database, and schedule
|
|
220
|
+
* a flush according to {@link persist}.
|
|
221
|
+
*
|
|
222
|
+
* Deliberately takes no argument. It used to filter the caller's Knex
|
|
223
|
+
* `method` against a local write-method allowlist, which made "did this
|
|
224
|
+
* mutate?" a decision taken in TWO places — here and in the dialect's
|
|
225
|
+
* execution-path branch — and the two disagreed: an `INSERT … RETURNING`
|
|
226
|
+
* runs down the dialect's ROW-returning branch (it has rows to return), that
|
|
227
|
+
* branch never called this method at all, and so a whole class of committed
|
|
228
|
+
* writes was never marked dirty and never reached disk (#4518). One decision,
|
|
229
|
+
* one owner: {@link statementMutatesDatabase} in the dialect classifies the
|
|
230
|
+
* statement, and this method just does what it is told.
|
|
231
|
+
*/
|
|
232
|
+
markDirty() {
|
|
227
233
|
if (this.isEphemeral || !this.fs) return;
|
|
228
|
-
if (method && !WRITE_METHODS.has(method)) return;
|
|
229
234
|
this.dirty = true;
|
|
230
235
|
if (this.persist === "on-write") {
|
|
231
236
|
void this.flush();
|
|
@@ -360,11 +365,23 @@ function formatBindings(bindings) {
|
|
|
360
365
|
return b;
|
|
361
366
|
});
|
|
362
367
|
}
|
|
363
|
-
function
|
|
368
|
+
function isRowReturningExecution(method, returning) {
|
|
364
369
|
if (method === "insert" || method === "update") return !!returning ? true : false;
|
|
365
370
|
if (method === "counter" || method === "del") return false;
|
|
366
371
|
return true;
|
|
367
372
|
}
|
|
373
|
+
var MUTATING_METHODS = /* @__PURE__ */ new Set(["insert", "update", "del", "counter"]);
|
|
374
|
+
var TRANSACTION_CONTROL_RE = /^\s*(BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b/i;
|
|
375
|
+
var DDL_RE = /^\s*(CREATE|ALTER|DROP|BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE|REINDEX|VACUUM|ATTACH|DETACH|TRUNCATE)\b/i;
|
|
376
|
+
var MUTATING_DML_RE = /^\s*(INSERT|UPDATE|DELETE|REPLACE|UPSERT)\b/i;
|
|
377
|
+
var MUTATING_PRAGMA_RE = /^\s*PRAGMA\b(?:[^;]*=|\s+incremental_vacuum\b)/i;
|
|
378
|
+
function statementMutatesDatabase(sql, method) {
|
|
379
|
+
if (TRANSACTION_CONTROL_RE.test(sql)) return false;
|
|
380
|
+
if (method && MUTATING_METHODS.has(method)) return true;
|
|
381
|
+
if (DDL_RE.test(sql)) return true;
|
|
382
|
+
if (MUTATING_DML_RE.test(sql)) return true;
|
|
383
|
+
return MUTATING_PRAGMA_RE.test(sql);
|
|
384
|
+
}
|
|
368
385
|
function resolveKnexSqlite3Dialect() {
|
|
369
386
|
const g = globalThis;
|
|
370
387
|
if (typeof g.require === "function") {
|
|
@@ -406,20 +423,10 @@ function getClient_WasmSqlite() {
|
|
|
406
423
|
if (!connection) throw new Error("No connection provided");
|
|
407
424
|
const db = connection.raw;
|
|
408
425
|
const bindings = formatBindings(obj.bindings);
|
|
409
|
-
|
|
410
|
-
obj.sql
|
|
411
|
-
);
|
|
412
|
-
if (isDdl) {
|
|
426
|
+
if (DDL_RE.test(obj.sql)) {
|
|
413
427
|
db.run(obj.sql, bindings);
|
|
414
428
|
obj.response = [];
|
|
415
|
-
|
|
416
|
-
connection.noteTransactionControl(obj.sql);
|
|
417
|
-
} else {
|
|
418
|
-
connection.markDirty("run");
|
|
419
|
-
}
|
|
420
|
-
return obj;
|
|
421
|
-
}
|
|
422
|
-
if (isReadMethod(obj.method, obj.returning) || /^\s*PRAGMA\b/i.test(obj.sql)) {
|
|
429
|
+
} else if (isRowReturningExecution(obj.method, obj.returning) || /^\s*PRAGMA\b/i.test(obj.sql)) {
|
|
423
430
|
const stmt = db.prepare(obj.sql);
|
|
424
431
|
try {
|
|
425
432
|
if (bindings.length) stmt.bind(bindings);
|
|
@@ -431,18 +438,22 @@ function getClient_WasmSqlite() {
|
|
|
431
438
|
} finally {
|
|
432
439
|
stmt.free();
|
|
433
440
|
}
|
|
434
|
-
|
|
441
|
+
} else {
|
|
442
|
+
db.run(obj.sql, bindings);
|
|
443
|
+
const changes = db.getRowsModified();
|
|
444
|
+
let lastID = 0;
|
|
445
|
+
if (obj.method === "insert") {
|
|
446
|
+
const r = db.exec("SELECT last_insert_rowid() AS id");
|
|
447
|
+
lastID = r?.[0]?.values?.[0]?.[0] ?? 0;
|
|
448
|
+
}
|
|
449
|
+
obj.response = [];
|
|
450
|
+
obj.context = { lastID, changes };
|
|
435
451
|
}
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
const r = db.exec("SELECT last_insert_rowid() AS id");
|
|
441
|
-
lastID = r?.[0]?.values?.[0]?.[0] ?? 0;
|
|
452
|
+
if (TRANSACTION_CONTROL_RE.test(obj.sql)) {
|
|
453
|
+
connection.noteTransactionControl(obj.sql);
|
|
454
|
+
} else if (statementMutatesDatabase(obj.sql, obj.method)) {
|
|
455
|
+
connection.markDirty();
|
|
442
456
|
}
|
|
443
|
-
obj.response = [];
|
|
444
|
-
obj.context = { lastID, changes };
|
|
445
|
-
connection.markDirty(obj.method);
|
|
446
457
|
return obj;
|
|
447
458
|
}
|
|
448
459
|
}
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sqlite-wasm-driver.ts","../src/knex-wasm-dialect.ts","../src/wasm-connection.ts","../src/index.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * SQLite-on-WASM driver for ObjectStack.\n *\n * Extends {@link SqlDriver} so all CRUD / schema / introspection / multi-tenant\n * logic is inherited as-is. Only the Knex transport is swapped to a custom\n * dialect ({@link Client_WasmSqlite}) backed by sql.js + Node `fs` persistence,\n * which lets the same `SqlDriver` codepath run inside StackBlitz WebContainer\n * (Node-in-browser) without the native `better-sqlite3` N-API binding.\n */\n\nimport type { SqlJsStatic } from 'sql.js';\nimport { SqlDriver, type SqlDriverConfig } from '@objectstack/driver-sql';\n\nimport { getClient_WasmSqlite } from './knex-wasm-dialect.js';\nimport type {\n PersistMode,\n WasmConnectionOptions,\n} from './wasm-connection.js';\n\n/** Public configuration for {@link SqliteWasmDriver}. */\nexport interface SqliteWasmDriverConfig {\n /**\n * SQLite filename. Use `:memory:` for an ephemeral database that is never\n * persisted. Any other value is treated as a Node `fs` path and the\n * sql.js database bytes are flushed back to disk according to {@link persist}.\n */\n filename: string;\n\n /**\n * Persistence strategy. Default: `'on-disconnect'`.\n *\n * - `'on-disconnect'` — flush once when the driver disconnects (and on\n * `process.beforeExit`).\n * - `'on-write'` — flush after every mutation. Safest, slowest.\n * - `` `debounced:${ms}` `` — debounce flushes by N milliseconds. Good\n * balance under bursty writes.\n */\n persist?: PersistMode;\n\n /** Pre-loaded sql.js module — skips lazy import. */\n sqlJs?: SqlJsStatic;\n\n /**\n * Override for sql.js's `locateFile`. Defaults to resolving the `.wasm`\n * file inside the installed `sql.js` package, which works in Node and\n * WebContainer.\n */\n locateFile?: (file: string) => string;\n\n /** Knex pool overrides. The dialect already defaults to `{ min: 1, max: 1 }`. */\n pool?: SqlDriverConfig['pool'];\n\n /** Optional logger. Defaults to `console`. */\n logger?: WasmConnectionOptions['logger'];\n}\n\n/**\n * SqlDriver subclass that runs Knex against sql.js (WASM SQLite).\n *\n * Behaves identically to the standard SQLite path — the dialect's\n * {@link Client_WasmSqlite._query} reports `lastID`/`changes` exactly the\n * way better-sqlite3 does, so {@link SqlDriver}'s SQL generation, returning\n * clauses, and schema introspection all keep working.\n */\nexport class SqliteWasmDriver extends SqlDriver {\n public override readonly name: string = 'com.objectstack.driver.sqlite-wasm';\n public override readonly version: string = '1.0.0';\n\n /**\n * Force the SQLite branch in {@link SqlDriver}. The base class detects\n * SQLite by string-matching `config.client`, but we pass the dialect class\n * directly so the string check would miss.\n */\n protected override get isSqlite(): boolean {\n return true;\n }\n\n /**\n * Never WAL (#3941). The base driver switches a file-backed SQLite database to\n * WAL so several processes can share one file. Nothing here is shared: the live\n * database sits in this process's WASM heap, and what reaches disk is a byte\n * image {@link flush} exports from it — another process reads that snapshot,\n * never the database. So the pragma buys this transport nothing.\n *\n * It is also not free. Journal mode is a persistent header change in the\n * operator's file, and under WAL the export path's correctness would rest on\n * sql.js checkpointing the log while `export()` closes and reopens the\n * database. Measured, it does — no row is lost today — which is why this is a\n * declined default and not a bug report. But a transport that persists by\n * serializing an image should not be one implementation detail away from\n * dropping committed rows for a concurrency benefit it cannot use.\n *\n * Declared rather than discovered: sql.js *accepts* `journal_mode = WAL`,\n * because its VFS is memory-backed, so the refusal the base class gets from\n * `:memory:` never comes — and an image whose header already says WAL (one a\n * native run left behind) reports `wal` here too.\n */\n protected override get supportsWalJournal(): boolean {\n return false;\n }\n\n private wasmConfig: SqliteWasmDriverConfig;\n private beforeExitHandler: (() => void) | null = null;\n\n constructor(config: SqliteWasmDriverConfig) {\n const knexConfig = SqliteWasmDriver.toKnexConfig(config);\n super(knexConfig);\n this.wasmConfig = config;\n if (config.logger) this.logger = config.logger as any;\n }\n\n /** Translate the public config into a Knex config that uses our dialect. */\n static toKnexConfig(config: SqliteWasmDriverConfig): SqlDriverConfig {\n return {\n // Knex accepts a Client class as `client`. The dialect's `driverName`\n // is `'wasm-sqlite'` and its `dialect` is `'sqlite3'` so the SQLite\n // query compiler is reused.\n client: getClient_WasmSqlite() as any,\n connection: {\n filename: config.filename,\n persist: config.persist,\n sqlJs: config.sqlJs,\n locateFile: config.locateFile,\n logger: config.logger,\n } as any,\n // sql.js is single-threaded WASM — a single connection per pool keeps\n // semantics consistent with the upstream SQLite dialect.\n pool: config.pool ?? { min: 1, max: 1 },\n useNullAsDefault: true,\n } as SqlDriverConfig;\n }\n\n override async connect(): Promise<void> {\n await super.connect();\n\n // Best-effort flush on process exit so `on-disconnect` mode still saves\n // user data if the host process is shut down without explicit cleanup.\n if (\n this.wasmConfig.filename !== ':memory:' &&\n !this.wasmConfig.filename.startsWith(':') &&\n typeof process !== 'undefined' &&\n typeof process.once === 'function'\n ) {\n this.beforeExitHandler = () => {\n // Fire-and-forget — beforeExit cannot await.\n void this.flush().catch(() => {\n /* ignore */\n });\n };\n process.once('beforeExit', this.beforeExitHandler);\n }\n }\n\n override async disconnect(): Promise<void> {\n if (this.beforeExitHandler && typeof process !== 'undefined') {\n try {\n process.removeListener('beforeExit', this.beforeExitHandler);\n } catch {\n /* ignore */\n }\n this.beforeExitHandler = null;\n }\n await super.disconnect();\n }\n\n /**\n * Force a flush of the in-memory database to disk. No-op for ephemeral\n * databases or when no fs is available.\n */\n async flush(): Promise<void> {\n // Reach into the Knex pool and ask every live connection to flush.\n const knex = (this as any).knex;\n const client = knex?.client;\n const pool = client?.pool;\n if (!pool || typeof pool.numUsed !== 'function') return;\n\n const acquire = client.acquireConnection?.bind(client);\n const release = client.releaseConnection?.bind(client);\n if (!acquire || !release) return;\n\n const conn = await acquire();\n try {\n if (conn && typeof conn.flush === 'function') {\n await conn.flush();\n }\n } finally {\n await release(conn);\n }\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Custom Knex SQLite dialect backed by sql.js (WASM SQLite).\n *\n * Mimics the surface that `Client_BetterSQLite3` presents to Knex so the\n * upstream SQLite3 dialect's query compiler, schema builder, and column\n * compiler all keep working unchanged. Only the transport layer —\n * `_driver` / `acquireRawConnection` / `_query` — is swapped out.\n *\n * ## Why the dialect class is built lazily\n *\n * The class `Client_WasmSqlite extends Client_SQLite3` needs the upstream\n * SQLite3 dialect at class-definition time. Resolving it at module\n * top-level breaks when this file is re-bundled by another tsup/esbuild\n * pass (e.g. `packages/runtime`), because that pass rewrites our runtime\n * `createRequire(import.meta.url)` chain back into a static `__require2`\n * Proxy stub that throws `Dynamic require of \"X\" is not supported`.\n *\n * Building the class inside a lazy factory (`getClient_WasmSqlite()`)\n * keeps the `require` call out of module-init code, so the re-bundler\n * cannot intercept it.\n */\n\nimport { createRequire } from 'node:module';\n\nimport type { SqlJsStatic } from 'sql.js';\n\nimport {\n WasmSqliteConnection,\n type PersistMode,\n type WasmConnectionOptions,\n} from './wasm-connection.js';\n\n// Built lazily — `node:module` is a Node builtin and is left untouched\n// by esbuild/tsup, so the `createRequire` import survives downstream\n// re-bundling. We defer the actual `createRequire(...)` call so that the\n// CJS build (where `import.meta.url` is empty) doesn't blow up at module\n// init; the CJS path uses `globalThis.require` directly anyway.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet cachedEsmRequire: any = null;\nfunction getEsmRequire(): any {\n if (cachedEsmRequire) return cachedEsmRequire;\n // `import.meta.url` is replaced with an empty string in CJS output;\n // fall back to the current file/cwd in that case.\n const anchor =\n typeof import.meta !== 'undefined' && (import.meta as any).url\n ? (import.meta as any).url\n : typeof __filename !== 'undefined'\n ? __filename\n : process.cwd() + '/';\n cachedEsmRequire = createRequire(anchor);\n return cachedEsmRequire;\n}\n\n/** Connection settings recognised by the WASM SQLite dialect. */\nexport interface WasmSqliteConnectionSettings {\n filename: string;\n persist?: PersistMode;\n sqlJs?: SqlJsStatic;\n locateFile?: (file: string) => string;\n logger?: WasmConnectionOptions['logger'];\n}\n\n/**\n * Coerce JS values that sql.js cannot bind directly. Mirrors\n * `Client_BetterSQLite3._formatBindings`.\n *\n * `undefined` is mapped to `null`: sql.js's binder only accepts\n * string/number/bigint/boolean/null (and array/blob) and `throw`s a *raw\n * string* — `\"Wrong API use : tried to bind a value of an unknown type\n * (undefined).\"` — for anything else. Because it throws a string rather than\n * an `Error`, it logs as a garbled char-indexed object and aborts the whole\n * write. Mapping to `null` matches the `useNullAsDefault` semantics the\n * dialect is configured with, so a missing/undefined value persists as SQL\n * `NULL` exactly as it would through better-sqlite3.\n */\nfunction formatBindings(bindings: unknown[] | undefined): unknown[] {\n if (!bindings) return [];\n return bindings.map((b) => {\n if (b === undefined) return null;\n if (b instanceof Date) return b.valueOf();\n if (typeof b === 'boolean') return Number(b);\n return b;\n });\n}\n\n/**\n * Mirrors the dispatch in upstream `Client_SQLite3._query`: only\n * `insert/update/counter/del` go through the row-less write path (and even\n * those switch to the read path when a `RETURNING` clause is requested).\n * Everything else — `select`, `first`, `pluck`, `columnInfo`, raw PRAGMA,\n * DDL with no `method` — is read with `all`/row iteration so Knex sees the\n * same response shape it would from better-sqlite3.\n */\nfunction isReadMethod(method?: string, returning?: unknown): boolean {\n if (method === 'insert' || method === 'update') return !!returning ? true : false;\n if (method === 'counter' || method === 'del') return false;\n return true;\n}\n\n/**\n * Resolve the upstream `knex/lib/dialects/sqlite3` class at runtime.\n *\n * Tries every escape hatch we have so that this works in:\n * - Plain Node ESM (use `createRequire(import.meta.url)`).\n * - Plain Node CJS (use the ambient `require` on `globalThis`).\n * - Re-bundled ESM where esbuild/tsup has stubbed `__require` — we\n * fall back to `new Function('return require')()` which evades static\n * analysis and grabs the real Node `require` at runtime.\n *\n * Wrapped in a function so the bundler cannot execute it at module init.\n */\nfunction resolveKnexSqlite3Dialect(): any {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const g = globalThis as any;\n if (typeof g.require === 'function') {\n try {\n return g.require('knex/lib/dialects/sqlite3');\n } catch {\n /* fall through */\n }\n }\n // ESM-safe path: `createRequire` was imported statically at the top of\n // this module from `node:module`. In a pure-ESM process there is no\n // ambient `require`, so this is the only reliable way to load a CJS\n // package like `knex/lib/dialects/sqlite3`.\n return getEsmRequire()('knex/lib/dialects/sqlite3');\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet cachedDialect: any = null;\n\n/**\n * Build (and cache) the `Client_WasmSqlite` class. Building lazily keeps\n * the `require('knex/lib/dialects/sqlite3')` call out of module-init\n * code so downstream re-bundlers (e.g. `packages/runtime`) cannot collapse\n * it into a Dynamic-require stub.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getClient_WasmSqlite(): any {\n if (cachedDialect) return cachedDialect;\n const Client_SQLite3 = resolveKnexSqlite3Dialect();\n\n class Client_WasmSqlite extends Client_SQLite3 {\n // sql.js has no shared \"driver module\" the way better-sqlite3 does. Knex\n // only uses `this.driver` to construct connections, and we override\n // `acquireRawConnection`, so a sentinel object is enough.\n _driver(): { name: 'sql.js' } {\n return { name: 'sql.js' };\n }\n\n async acquireRawConnection(): Promise<WasmSqliteConnection> {\n const settings = (this as any)\n .connectionSettings as WasmSqliteConnectionSettings;\n\n const conn = new WasmSqliteConnection({\n filename: settings.filename,\n persist: settings.persist,\n sqlJs: settings.sqlJs,\n locateFile: settings.locateFile,\n logger: settings.logger,\n });\n await conn.open(settings.sqlJs, settings.locateFile);\n return conn;\n }\n\n async destroyRawConnection(connection: WasmSqliteConnection): Promise<void> {\n await connection.close();\n }\n\n async _query(\n connection: WasmSqliteConnection,\n obj: any,\n ): Promise<any> {\n if (!obj.sql) throw new Error('The query is empty');\n if (!connection) throw new Error('No connection provided');\n\n const db = connection.raw;\n const bindings = formatBindings(obj.bindings);\n\n // DDL / transactional control statements have no Knex `method`. sql.js's\n // `prepare`+`step` silently no-ops on many of these (e.g. CREATE TABLE),\n // so route them through `run` which is implemented via `exec` and\n // actually mutates the database. PRAGMA is intentionally excluded — many\n // PRAGMA forms (e.g. `PRAGMA table_info(...)`, `foreign_key_list(...)`)\n // return rows used by Knex's schema introspection/columnInfo, and\n // `db.run` discards those rows.\n const isDdl =\n /^\\s*(CREATE|ALTER|DROP|BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE|REINDEX|VACUUM|ATTACH|DETACH|TRUNCATE)\\b/i.test(\n obj.sql,\n );\n if (isDdl) {\n db.run(obj.sql, bindings as any);\n obj.response = [];\n // Transaction-control statements are routed through\n // `noteTransactionControl`, which owns flushing for the transaction\n // lifecycle: it suppresses flushes while a transaction is open (sql.js\n // `export()` closes+reopens the db, which would abort the txn) and\n // performs a single flush once the transaction fully closes. Routing\n // them away from `markDirty` avoids a second, racing flush on COMMIT.\n if (/^\\s*(BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\\b/i.test(obj.sql)) {\n connection.noteTransactionControl(obj.sql);\n } else {\n connection.markDirty('run');\n }\n return obj;\n }\n\n if (isReadMethod(obj.method, obj.returning) || /^\\s*PRAGMA\\b/i.test(obj.sql)) {\n const stmt = db.prepare(obj.sql);\n try {\n if (bindings.length) stmt.bind(bindings as any);\n const rows: Record<string, unknown>[] = [];\n while (stmt.step()) {\n rows.push(stmt.getAsObject());\n }\n obj.response = rows;\n } finally {\n stmt.free();\n }\n return obj;\n }\n\n // Write path: execute via `run` (no row iteration needed) and capture\n // SQLite's per-connection lastID / changes counters.\n db.run(obj.sql, bindings as any);\n const changes = db.getRowsModified();\n let lastID: number | bigint = 0;\n if (obj.method === 'insert') {\n const r = db.exec('SELECT last_insert_rowid() AS id');\n lastID = (r?.[0]?.values?.[0]?.[0] as number) ?? 0;\n }\n obj.response = [];\n obj.context = { lastID, changes };\n connection.markDirty(obj.method);\n return obj;\n }\n }\n\n Object.assign(Client_WasmSqlite.prototype, {\n dialect: 'sqlite3',\n driverName: 'wasm-sqlite',\n });\n\n cachedDialect = Client_WasmSqlite;\n return Client_WasmSqlite;\n}\n\n/**\n * Back-compat re-export. Prefer `getClient_WasmSqlite()` so the dialect\n * is resolved lazily; the named export triggers the factory on first\n * access of any static property.\n *\n * Note: importing this binding will execute the factory at import time\n * in some bundlers, which defeats the lazy pattern. New code should call\n * `getClient_WasmSqlite()` directly.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const Client_WasmSqlite: any = new Proxy(function () {} as any, {\n get(_t, prop) {\n return (getClient_WasmSqlite() as any)[prop];\n },\n construct(_t, args) {\n const Klass = getClient_WasmSqlite();\n return new Klass(...args);\n },\n apply(_t, thisArg, args) {\n const Klass = getClient_WasmSqlite();\n return Reflect.apply(Klass, thisArg, args);\n },\n});\n\nexport default Client_WasmSqlite;\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Thin wrapper over sql.js {@link Database} that mimics the surface of\n * `better-sqlite3`'s `Database` (only the methods the Knex dialect uses).\n *\n * Persistence is handled here, not in the Knex dialect, so it can be\n * orchestrated per-connection without polluting the SQL execution path.\n */\n\nimport type { Database, SqlJsStatic } from 'sql.js';\n\n/** When to flush the in-memory WASM database to disk. */\nexport type PersistMode =\n | 'on-disconnect'\n | 'on-write'\n | `debounced:${number}`;\n\nexport interface WasmConnectionOptions {\n /**\n * On-disk file path. `:memory:` (or any value starting with `:`) skips\n * persistence entirely and the database lives only for the process.\n */\n filename: string;\n /** When to persist. Default: `on-disconnect`. */\n persist?: PersistMode;\n /** Pre-loaded sql.js module. If omitted, loaded lazily on first connect. */\n sqlJs?: SqlJsStatic;\n /**\n * Optional override for the `.wasm` locator passed to `initSqlJs()`.\n * Defaults to resolving the file from the `sql.js` package on disk\n * (works in Node and WebContainer).\n */\n locateFile?: (file: string) => string;\n /** Optional logger; defaults to `console`. */\n logger?: { warn: (msg: string, meta?: unknown) => void };\n}\n\n/** Mutation method names that should trigger a persistence cycle. */\nconst WRITE_METHODS = new Set([\n 'run',\n 'insert',\n 'update',\n 'del',\n 'counter',\n]);\n\n/**\n * Detect whether a Node-style `fs` module is available. WebContainer\n * (StackBlitz) provides Node `fs`; pure-browser environments do not.\n */\nasync function tryLoadFs(): Promise<typeof import('node:fs/promises') | null> {\n try {\n return await import('node:fs/promises');\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve a default sql.js WASM locator. We point sql.js at the `.wasm`\n * file shipped inside `sql.js`'s own `dist/` folder. This avoids requiring\n * the caller to host the WASM separately.\n */\nasync function defaultLocateFile(): Promise<((file: string) => string) | undefined> {\n try {\n const { createRequire } = await import('node:module');\n const require = createRequire(import.meta.url);\n const pkgJsonPath = require.resolve('sql.js/package.json');\n const { dirname, join } = await import('node:path');\n const dir = dirname(pkgJsonPath);\n return (file: string) => join(dir, 'dist', file);\n } catch {\n return undefined;\n }\n}\n\nlet cachedSqlJs: Promise<SqlJsStatic> | null = null;\n\nasync function loadSqlJs(\n locateFile?: (file: string) => string,\n): Promise<SqlJsStatic> {\n if (cachedSqlJs) return cachedSqlJs;\n cachedSqlJs = (async () => {\n const mod = await import('sql.js');\n const initSqlJs = (mod as any).default ?? (mod as any);\n const locator = locateFile ?? (await defaultLocateFile());\n const SQL = await initSqlJs(locator ? { locateFile: locator } : undefined);\n return SQL as SqlJsStatic;\n })();\n return cachedSqlJs;\n}\n\n/**\n * A sql.js-backed connection that exposes the `prepare`/`exec`/`close`\n * subset used by Knex's SQLite dialect. Mutations are queued through a\n * configurable persistence strategy so the on-disk file stays in sync.\n */\nexport class WasmSqliteConnection {\n /**\n * Process-wide counter making each atomic-write temp filename unique, so\n * concurrent connections (or overlapping flushes) never target the same\n * temp path. Combined with `process.pid` for cross-process uniqueness.\n */\n private static tmpSeq = 0;\n\n readonly filename: string;\n readonly persist: PersistMode;\n readonly isEphemeral: boolean;\n\n private db!: Database;\n private fs: typeof import('node:fs/promises') | null = null;\n private dirty = false;\n private debounceMs = 0;\n private debounceTimer: ReturnType<typeof setTimeout> | null = null;\n private flushChain: Promise<void> | null = null;\n private destroyed = false;\n private logger: { warn: (msg: string, meta?: unknown) => void };\n\n /**\n * Whether a `BEGIN…COMMIT/ROLLBACK` transaction is currently open. Tracked\n * because sql.js's {@link Database.export} closes and reopens the database\n * (it has no in-place serialize), and closing a connection rolls back any\n * open transaction. Flushing mid-transaction would therefore silently\n * abort it, leaving the eventual `COMMIT` to fail with\n * \"cannot commit - no transaction is active\". We defer the flush until the\n * transaction fully closes. See {@link noteTransactionControl}.\n */\n private rootTxActive = false;\n /** Open `SAVEPOINT` depth (nested transactions emitted by Knex). */\n private savepointDepth = 0;\n /** A flush was requested while a transaction was open; run it on close. */\n private flushDeferred = false;\n\n /** True while any transaction (root or savepoint) is in flight. */\n private get inTransaction(): boolean {\n return this.rootTxActive || this.savepointDepth > 0;\n }\n\n constructor(opts: WasmConnectionOptions) {\n this.filename = opts.filename;\n this.persist = opts.persist ?? 'on-disconnect';\n this.isEphemeral =\n this.filename === ':memory:' || this.filename.startsWith(':');\n this.logger = opts.logger ?? console;\n\n if (typeof this.persist === 'string' && this.persist.startsWith('debounced:')) {\n const ms = Number(this.persist.slice('debounced:'.length));\n this.debounceMs = Number.isFinite(ms) && ms > 0 ? ms : 250;\n }\n }\n\n /** Open the underlying sql.js database, loading bytes from disk if any. */\n async open(sqlJs?: SqlJsStatic, locateFile?: (file: string) => string): Promise<void> {\n const SQL = sqlJs ?? (await loadSqlJs(locateFile));\n\n if (this.isEphemeral) {\n this.db = new SQL.Database();\n return;\n }\n\n this.fs = await tryLoadFs();\n if (!this.fs) {\n this.logger.warn(\n '[driver-sqlite-wasm] No node:fs available — falling back to in-memory database. ' +\n 'Data will not be persisted across reloads.',\n );\n this.db = new SQL.Database();\n return;\n }\n\n // Ensure parent directory exists, then load bytes if the file exists.\n const { dirname } = await import('node:path');\n const dir = dirname(this.filename);\n if (dir && dir !== '.') {\n await this.fs.mkdir(dir, { recursive: true });\n }\n\n let bytes: Uint8Array | undefined;\n try {\n const buf = await this.fs.readFile(this.filename);\n bytes = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n } catch (e: any) {\n if (e?.code !== 'ENOENT') throw e;\n }\n\n if (!bytes) {\n this.db = new SQL.Database();\n return;\n }\n\n await this.quarantineOrphanedWal();\n\n // Open the on-disk bytes, but guard against a corrupt image. A torn write\n // (process killed mid-flush before atomic writes existed) or otherwise\n // damaged file makes `new SQL.Database(bytes)` either throw (\"file is not a\n // database\") or open a handle whose every query fails with \"database disk\n // image is malformed\" — which, for a background dispatcher on a tick loop,\n // means the same error spammed forever with no path to recovery. Detect it\n // once at open, quarantine the bad file, and start fresh so the dev server\n // becomes usable again instead of wedging.\n try {\n const candidate = new SQL.Database(bytes);\n this.assertReadable(candidate);\n this.db = candidate;\n } catch (err) {\n await this.quarantineCorruptFile(err);\n this.db = new SQL.Database();\n }\n }\n\n /**\n * Force sql.js to actually read a page so a malformed image surfaces now\n * rather than on the first business query. `PRAGMA quick_check` walks the\n * b-tree structure without the full-scan cost of `integrity_check`; a healthy\n * database returns a single `ok` row. Any thrown error (raw string or Error)\n * or a non-`ok` result is treated as corruption.\n */\n private assertReadable(db: Database): void {\n const res = db.exec('PRAGMA quick_check(1)');\n const first = res?.[0]?.values?.[0]?.[0];\n if (typeof first === 'string' && first.toLowerCase() !== 'ok') {\n throw new Error(`sqlite quick_check failed: ${first}`);\n }\n }\n\n /**\n * Move a corrupt database file aside so its bytes are preserved for\n * post-mortem while a fresh, empty database takes its place. Best-effort:\n * failures here must not prevent the server from booting on a clean DB.\n */\n private async quarantineCorruptFile(cause: unknown): Promise<void> {\n if (!this.fs) return;\n const reason =\n typeof cause === 'string' ? cause : (cause as Error)?.message ?? String(cause);\n const backup = `${this.filename}.corrupt-${Date.now()}`;\n try {\n await this.fs.rename(this.filename, backup);\n this.logger.warn(\n `[driver-sqlite-wasm] Database image at ${this.filename} is corrupt ` +\n `(${reason}). Quarantined to ${backup} and starting from an empty ` +\n `database so the server can boot.`,\n );\n } catch (renameErr) {\n // Could not move it aside (e.g. permissions) — overwrite is still better\n // than looping forever on a malformed image. Warn loudly and continue.\n this.logger.warn(\n `[driver-sqlite-wasm] Database image at ${this.filename} is corrupt ` +\n `(${reason}) and could not be quarantined (${String(renameErr)}). ` +\n `Starting from an empty database; the corrupt file will be overwritten ` +\n `on the next flush.`,\n );\n }\n }\n\n /**\n * Move a write-ahead log left behind by a *real* SQLite aside (#3941).\n *\n * The native driver keeps file-backed databases in WAL mode, and a clean close\n * checkpoints the log away — so a non-empty `<db>-wal` here means the last\n * process died without one. That log is a problem in both directions, and\n * neither is something wasm SQLite can fix: it cannot read the log (we load\n * only the main image, so any transaction still in there is invisible), and it\n * must not leave it in place either — the next {@link flush} rewrites the\n * image, and a real SQLite opening a fresh image beside a stale log would\n * replay frames that no longer belong to it.\n *\n * So rename it, which loses nothing recoverable (the bytes are preserved for a\n * real `sqlite3` to recover from) and disarms the mismatch. Best-effort: this\n * is a dev-only step-down path and must never prevent a boot.\n */\n private async quarantineOrphanedWal(): Promise<void> {\n if (!this.fs) return;\n const wal = `${this.filename}-wal`;\n let size: number;\n try {\n size = (await this.fs.stat(wal)).size;\n } catch {\n return; // no sidecar (the normal case) or an unreadable one\n }\n if (size <= 0) return; // checkpointed-and-truncated: nothing in it\n\n const parked = `${wal}.orphaned-${Date.now()}`;\n try {\n await this.fs.rename(wal, parked);\n this.logger.warn(\n `[driver-sqlite-wasm] ${wal} holds ${size} bytes of write-ahead log that wasm SQLite ` +\n `cannot read — this database was last used in WAL mode and closed uncleanly. Parked it ` +\n `at ${parked} and loaded the main image without it, so anything committed only to the ` +\n `log is NOT in this session. To recover it, rebuild better-sqlite3 (or use \\`sqlite3\\`), ` +\n `restore the log next to the database, and run \\`PRAGMA wal_checkpoint(TRUNCATE)\\`.`,\n );\n } catch (renameErr) {\n this.logger.warn(\n `[driver-sqlite-wasm] ${wal} holds ${size} bytes of write-ahead log that wasm SQLite ` +\n `cannot read, and it could not be moved aside (${String(renameErr)}). Data committed ` +\n `only to the log is missing from this session; checkpoint it with a real sqlite3 before ` +\n `writing further.`,\n );\n }\n }\n\n /**\n * Update transaction state from a transaction-control statement and, when a\n * transaction has just fully closed, run any flush that was deferred while\n * it was open. Called by the Knex dialect for every `BEGIN` / `COMMIT` /\n * `ROLLBACK` / `SAVEPOINT` / `RELEASE` statement.\n *\n * We bias toward \"in transaction\": an unrecognised form leaves the flag set,\n * which at worst delays a flush (safe) rather than exporting mid-transaction\n * (which would abort it).\n */\n noteTransactionControl(sql: string): void {\n const s = sql.trim().toUpperCase();\n if (/^BEGIN\\b/.test(s)) {\n this.rootTxActive = true;\n } else if (/^(COMMIT|END)\\b/.test(s)) {\n // A COMMIT/END ends the whole transaction regardless of savepoint nesting.\n this.rootTxActive = false;\n this.savepointDepth = 0;\n } else if (/^ROLLBACK\\s+TO\\b/.test(s)) {\n // Rolls back to a savepoint but keeps the (outer) transaction open.\n } else if (/^ROLLBACK\\b/.test(s)) {\n this.rootTxActive = false;\n this.savepointDepth = 0;\n } else if (/^SAVEPOINT\\b/.test(s)) {\n this.savepointDepth += 1;\n } else if (/^RELEASE\\b/.test(s)) {\n this.savepointDepth = Math.max(0, this.savepointDepth - 1);\n }\n // If the transaction just fully closed and a flush was deferred while it\n // was open, run it now. We key off `flushDeferred` (set only when\n // `markDirty` actually wanted to flush) rather than `dirty`, so persist\n // modes that don't flush per-write — e.g. `on-disconnect` — still defer to\n // close() instead of flushing on every COMMIT.\n if (!this.inTransaction && this.flushDeferred) {\n this.flushDeferred = false;\n void this.flush();\n }\n }\n\n /** Hint that a mutation just executed; schedule a flush if needed. */\n markDirty(method?: string): void {\n if (this.isEphemeral || !this.fs) return;\n if (method && !WRITE_METHODS.has(method)) return;\n this.dirty = true;\n\n if (this.persist === 'on-write') {\n void this.flush();\n return;\n }\n if (this.debounceMs > 0) {\n if (this.debounceTimer) clearTimeout(this.debounceTimer);\n this.debounceTimer = setTimeout(() => {\n this.debounceTimer = null;\n void this.flush();\n }, this.debounceMs);\n }\n // 'on-disconnect' → flush only at close()\n }\n\n /**\n * Force a write of the current database state to disk.\n *\n * Flushes are strictly serialized through a single promise chain: every call\n * appends an export+write step that runs after all previously-queued steps.\n * This matters because sql.js `export()` mutates the live connection (it\n * closes and reopens the database), so two exports must never overlap — and\n * because the returned promise must not resolve until the caller's own write\n * has hit disk (deterministic for tests and for `close()`). Each step\n * re-checks `dirty` at run time, so a no-op write collapses cheaply and a\n * write that arrived mid-flush is captured by the next queued step.\n */\n async flush(): Promise<void> {\n if (this.isEphemeral || !this.fs || this.destroyed) return;\n // Never export while a transaction is open: sql.js's `export()` closes and\n // reopens the database, which rolls back the in-flight transaction and\n // makes the subsequent COMMIT fail. Defer until the transaction closes\n // (handled in `noteTransactionControl`).\n if (this.inTransaction) {\n this.flushDeferred = true;\n return;\n }\n\n const prev = this.flushChain;\n const step = (prev ?? Promise.resolve()).then(async () => {\n if (!this.dirty || this.destroyed || this.inTransaction) return;\n // Snapshot dirty=false before export so a concurrent write re-marks us\n // and is picked up by the next queued step.\n this.dirty = false;\n try {\n const exported = this.db.export();\n // sql.js returns a Uint8Array; Buffer.from on it shares memory but\n // works fine for the atomic write below.\n await this.atomicWriteFile(Buffer.from(exported));\n } catch (err) {\n this.dirty = true; // let a later flush retry\n throw err;\n }\n });\n // Keep the chain tail alive but swallow its rejection there so one failed\n // flush doesn't poison every future flush; the awaited `step` still throws.\n this.flushChain = step.catch(() => {});\n await step;\n }\n\n /**\n * Write the database bytes to disk atomically: write to a sibling temp file,\n * fsync it, then `rename()` it over the target.\n *\n * A plain `writeFile(this.filename, …)` truncates the target and streams the\n * new bytes in place, so a process killed mid-write (a dev-server restart,\n * Ctrl-C, or crash — likely under `on-write`, where every dispatcher tick\n * flushes) leaves a half-written file. sql.js then rejects that file on the\n * next boot with \"database disk image is malformed\". `rename(2)` is atomic\n * within a filesystem, so a reader always sees either the complete old file\n * or the complete new one — never a torn image. The temp file lives in the\n * same directory as the target so the rename stays intra-filesystem.\n */\n private async atomicWriteFile(data: Buffer): Promise<void> {\n if (!this.fs) return;\n const tmp = `${this.filename}.tmp-${process.pid}-${(WasmSqliteConnection.tmpSeq += 1)}`;\n let handle: import('node:fs/promises').FileHandle | undefined;\n try {\n handle = await this.fs.open(tmp, 'w');\n await handle.writeFile(data);\n // Flush the bytes to the platter before the rename so a crash can't leave\n // a renamed-but-empty file behind on filesystems that reorder the two.\n await handle.sync();\n await handle.close();\n handle = undefined;\n await this.fs.rename(tmp, this.filename);\n } catch (err) {\n if (handle) {\n try {\n await handle.close();\n } catch {\n /* ignore */\n }\n }\n // Clean up the temp file so a failed flush doesn't litter the data dir.\n try {\n await this.fs.unlink(tmp);\n } catch {\n /* ignore */\n }\n throw err;\n }\n }\n\n /** Close the database, flushing any pending writes first. */\n async close(): Promise<void> {\n if (this.destroyed) return;\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n // Any transaction still open at close is abandoned and will be rolled back\n // by `db.close()`; clear the flag so the final flush is not deferred and\n // already-committed data is persisted.\n this.rootTxActive = false;\n this.savepointDepth = 0;\n try {\n await this.flush();\n } finally {\n this.destroyed = true;\n try {\n this.db.close();\n } catch {\n /* ignore */\n }\n }\n }\n\n /** Access the raw sql.js database (for the Knex dialect). */\n get raw(): Database {\n return this.db;\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { SqliteWasmDriver } from './sqlite-wasm-driver.js';\n\nexport { SqliteWasmDriver };\nexport type { SqliteWasmDriverConfig } from './sqlite-wasm-driver.js';\nexport { Client_WasmSqlite } from './knex-wasm-dialect.js';\nexport type { WasmSqliteConnectionSettings } from './knex-wasm-dialect.js';\nexport { WasmSqliteConnection } from './wasm-connection.js';\nexport type { PersistMode, WasmConnectionOptions } from './wasm-connection.js';\n\nexport default {\n id: 'com.objectstack.driver.sqlite-wasm',\n version: '1.0.0',\n\n onEnable: async (context: any) => {\n const { logger, config, drivers } = context;\n logger?.info?.('[SQLite-WASM Driver] Initializing...');\n\n if (drivers) {\n const driver = new SqliteWasmDriver(config);\n drivers.register(driver);\n logger?.info?.(`[SQLite-WASM Driver] Registered driver: ${driver.name}`);\n } else {\n logger?.warn?.('[SQLite-WASM Driver] No driver registry found in context.');\n }\n },\n};\n"],"mappings":";AAaA,SAAS,iBAAuC;;;ACWhD,SAAS,qBAAqB;;;ACe9B,IAAM,gBAAgB,oBAAI,IAAI;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAMD,eAAe,YAA+D;AAC5E,MAAI;AACF,WAAO,MAAM,OAAO,aAAkB;AAAA,EACxC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAOA,eAAe,oBAAqE;AAClF,MAAI;AACF,UAAM,EAAE,eAAAA,eAAc,IAAI,MAAM,OAAO,QAAa;AACpD,UAAMC,WAAUD,eAAc,YAAY,GAAG;AAC7C,UAAM,cAAcC,SAAQ,QAAQ,qBAAqB;AACzD,UAAM,EAAE,SAAS,KAAK,IAAI,MAAM,OAAO,MAAW;AAClD,UAAM,MAAM,QA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AC3B;AACA,UAAM,MAAM,WAAW;AAAA,EACzB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,QAAuB;AAE3B,UAAM,OAAQ,KAAa;AAC3B,UAAM,SAAS,MAAM;AACrB,UAAM,OAAO,QAAQ;AACrB,QAAI,CAAC,QAAQ,OAAO,KAAK,YAAY,WAAY;AAEjD,UAAM,UAAU,OAAO,mBAAmB,KAAK,MAAM;AACrD,UAAM,UAAU,OAAO,mBAAmB,KAAK,MAAM;AACrD,QAAI,CAAC,WAAW,CAAC,QAAS;AAE1B,UAAM,OAAO,MAAM,QAAQ;AAC3B,QAAI;AACF,UAAI,QAAQ,OAAO,KAAK,UAAU,YAAY;AAC5C,cAAM,KAAK,MAAM;AAAA,MACnB;AAAA,IACF,UAAE;AACA,YAAM,QAAQ,IAAI;AAAA,IACpB;AAAA,EACF;AACF;;;AGpLA,IAAO,gBAAQ;AAAA,EACb,IAAI;AAAA,EACJ,SAAS;AAAA,EAET,UAAU,OAAO,YAAiB;AAChC,UAAM,EAAE,QAAQ,QAAQ,QAAQ,IAAI;AACpC,YAAQ,OAAO,sCAAsC;AAErD,QAAI,SAAS;AACX,YAAM,SAAS,IAAI,iBAAiB,MAAM;AAC1C,cAAQ,SAAS,MAAM;AACvB,cAAQ,OAAO,2CAA2C,OAAO,IAAI,EAAE;AAAA,IACzE,OAAO;AACL,cAAQ,OAAO,2DAA2D;AAAA,IAC5E;AAAA,EACF;AACF;","names":["createRequire","require","Client_WasmSqlite"]}
|
|
1
|
+
{"version":3,"sources":["../src/sqlite-wasm-driver.ts","../src/knex-wasm-dialect.ts","../src/wasm-connection.ts","../src/index.ts"],"sourcesContent":["// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * SQLite-on-WASM driver for ObjectStack.\n *\n * Extends {@link SqlDriver} so all CRUD / schema / introspection / multi-tenant\n * logic is inherited as-is. Only the Knex transport is swapped to a custom\n * dialect ({@link Client_WasmSqlite}) backed by sql.js + Node `fs` persistence,\n * which lets the same `SqlDriver` codepath run inside StackBlitz WebContainer\n * (Node-in-browser) without the native `better-sqlite3` N-API binding.\n */\n\nimport type { SqlJsStatic } from 'sql.js';\nimport { SqlDriver, type SqlDriverConfig } from '@objectstack/driver-sql';\n\nimport { getClient_WasmSqlite } from './knex-wasm-dialect.js';\nimport type {\n PersistMode,\n WasmConnectionOptions,\n} from './wasm-connection.js';\n\n/** Public configuration for {@link SqliteWasmDriver}. */\nexport interface SqliteWasmDriverConfig {\n /**\n * SQLite filename. Use `:memory:` for an ephemeral database that is never\n * persisted. Any other value is treated as a Node `fs` path and the\n * sql.js database bytes are flushed back to disk according to {@link persist}.\n */\n filename: string;\n\n /**\n * Persistence strategy. Default: `'on-disconnect'`.\n *\n * - `'on-disconnect'` — flush once when the driver disconnects (and on\n * `process.beforeExit`).\n * - `'on-write'` — flush after every mutation. Safest, slowest.\n * - `` `debounced:${ms}` `` — debounce flushes by N milliseconds. Good\n * balance under bursty writes.\n */\n persist?: PersistMode;\n\n /** Pre-loaded sql.js module — skips lazy import. */\n sqlJs?: SqlJsStatic;\n\n /**\n * Override for sql.js's `locateFile`. Defaults to resolving the `.wasm`\n * file inside the installed `sql.js` package, which works in Node and\n * WebContainer.\n */\n locateFile?: (file: string) => string;\n\n /** Knex pool overrides. The dialect already defaults to `{ min: 1, max: 1 }`. */\n pool?: SqlDriverConfig['pool'];\n\n /** Optional logger. Defaults to `console`. */\n logger?: WasmConnectionOptions['logger'];\n}\n\n/**\n * SqlDriver subclass that runs Knex against sql.js (WASM SQLite).\n *\n * Behaves identically to the standard SQLite path — the dialect's\n * {@link Client_WasmSqlite._query} reports `lastID`/`changes` exactly the\n * way better-sqlite3 does, so {@link SqlDriver}'s SQL generation, returning\n * clauses, and schema introspection all keep working.\n */\nexport class SqliteWasmDriver extends SqlDriver {\n public override readonly name: string = 'com.objectstack.driver.sqlite-wasm';\n public override readonly version: string = '1.0.0';\n\n /**\n * Force the SQLite branch in {@link SqlDriver}. The base class detects\n * SQLite by string-matching `config.client`, but we pass the dialect class\n * directly so the string check would miss.\n */\n protected override get isSqlite(): boolean {\n return true;\n }\n\n /**\n * Never WAL (#3941). The base driver switches a file-backed SQLite database to\n * WAL so several processes can share one file. Nothing here is shared: the live\n * database sits in this process's WASM heap, and what reaches disk is a byte\n * image {@link flush} exports from it — another process reads that snapshot,\n * never the database. So the pragma buys this transport nothing.\n *\n * It is also not free. Journal mode is a persistent header change in the\n * operator's file, and under WAL the export path's correctness would rest on\n * sql.js checkpointing the log while `export()` closes and reopens the\n * database. Measured, it does — no row is lost today — which is why this is a\n * declined default and not a bug report. But a transport that persists by\n * serializing an image should not be one implementation detail away from\n * dropping committed rows for a concurrency benefit it cannot use.\n *\n * Declared rather than discovered: sql.js *accepts* `journal_mode = WAL`,\n * because its VFS is memory-backed, so the refusal the base class gets from\n * `:memory:` never comes — and an image whose header already says WAL (one a\n * native run left behind) reports `wal` here too.\n */\n protected override get supportsWalJournal(): boolean {\n return false;\n }\n\n private wasmConfig: SqliteWasmDriverConfig;\n private beforeExitHandler: (() => void) | null = null;\n\n constructor(config: SqliteWasmDriverConfig) {\n const knexConfig = SqliteWasmDriver.toKnexConfig(config);\n super(knexConfig);\n this.wasmConfig = config;\n if (config.logger) this.logger = config.logger as any;\n }\n\n /** Translate the public config into a Knex config that uses our dialect. */\n static toKnexConfig(config: SqliteWasmDriverConfig): SqlDriverConfig {\n return {\n // Knex accepts a Client class as `client`. The dialect's `driverName`\n // is `'wasm-sqlite'` and its `dialect` is `'sqlite3'` so the SQLite\n // query compiler is reused.\n client: getClient_WasmSqlite() as any,\n connection: {\n filename: config.filename,\n persist: config.persist,\n sqlJs: config.sqlJs,\n locateFile: config.locateFile,\n logger: config.logger,\n } as any,\n // sql.js is single-threaded WASM — a single connection per pool keeps\n // semantics consistent with the upstream SQLite dialect.\n pool: config.pool ?? { min: 1, max: 1 },\n useNullAsDefault: true,\n } as SqlDriverConfig;\n }\n\n override async connect(): Promise<void> {\n await super.connect();\n\n // Best-effort flush on process exit so `on-disconnect` mode still saves\n // user data if the host process is shut down without explicit cleanup.\n if (\n this.wasmConfig.filename !== ':memory:' &&\n !this.wasmConfig.filename.startsWith(':') &&\n typeof process !== 'undefined' &&\n typeof process.once === 'function'\n ) {\n this.beforeExitHandler = () => {\n // Fire-and-forget — beforeExit cannot await.\n void this.flush().catch(() => {\n /* ignore */\n });\n };\n process.once('beforeExit', this.beforeExitHandler);\n }\n }\n\n override async disconnect(): Promise<void> {\n if (this.beforeExitHandler && typeof process !== 'undefined') {\n try {\n process.removeListener('beforeExit', this.beforeExitHandler);\n } catch {\n /* ignore */\n }\n this.beforeExitHandler = null;\n }\n await super.disconnect();\n }\n\n /**\n * Force a flush of the in-memory database to disk. No-op for ephemeral\n * databases or when no fs is available.\n */\n async flush(): Promise<void> {\n // Reach into the Knex pool and ask every live connection to flush.\n const knex = (this as any).knex;\n const client = knex?.client;\n const pool = client?.pool;\n if (!pool || typeof pool.numUsed !== 'function') return;\n\n const acquire = client.acquireConnection?.bind(client);\n const release = client.releaseConnection?.bind(client);\n if (!acquire || !release) return;\n\n const conn = await acquire();\n try {\n if (conn && typeof conn.flush === 'function') {\n await conn.flush();\n }\n } finally {\n await release(conn);\n }\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Custom Knex SQLite dialect backed by sql.js (WASM SQLite).\n *\n * Mimics the surface that `Client_BetterSQLite3` presents to Knex so the\n * upstream SQLite3 dialect's query compiler, schema builder, and column\n * compiler all keep working unchanged. Only the transport layer —\n * `_driver` / `acquireRawConnection` / `_query` — is swapped out.\n *\n * ## Why the dialect class is built lazily\n *\n * The class `Client_WasmSqlite extends Client_SQLite3` needs the upstream\n * SQLite3 dialect at class-definition time. Resolving it at module\n * top-level breaks when this file is re-bundled by another tsup/esbuild\n * pass (e.g. `packages/runtime`), because that pass rewrites our runtime\n * `createRequire(import.meta.url)` chain back into a static `__require2`\n * Proxy stub that throws `Dynamic require of \"X\" is not supported`.\n *\n * Building the class inside a lazy factory (`getClient_WasmSqlite()`)\n * keeps the `require` call out of module-init code, so the re-bundler\n * cannot intercept it.\n */\n\nimport { createRequire } from 'node:module';\n\nimport type { SqlJsStatic } from 'sql.js';\n\nimport {\n WasmSqliteConnection,\n type PersistMode,\n type WasmConnectionOptions,\n} from './wasm-connection.js';\n\n// Built lazily — `node:module` is a Node builtin and is left untouched\n// by esbuild/tsup, so the `createRequire` import survives downstream\n// re-bundling. We defer the actual `createRequire(...)` call so that the\n// CJS build (where `import.meta.url` is empty) doesn't blow up at module\n// init; the CJS path uses `globalThis.require` directly anyway.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet cachedEsmRequire: any = null;\nfunction getEsmRequire(): any {\n if (cachedEsmRequire) return cachedEsmRequire;\n // `import.meta.url` is replaced with an empty string in CJS output;\n // fall back to the current file/cwd in that case.\n const anchor =\n typeof import.meta !== 'undefined' && (import.meta as any).url\n ? (import.meta as any).url\n : typeof __filename !== 'undefined'\n ? __filename\n : process.cwd() + '/';\n cachedEsmRequire = createRequire(anchor);\n return cachedEsmRequire;\n}\n\n/** Connection settings recognised by the WASM SQLite dialect. */\nexport interface WasmSqliteConnectionSettings {\n filename: string;\n persist?: PersistMode;\n sqlJs?: SqlJsStatic;\n locateFile?: (file: string) => string;\n logger?: WasmConnectionOptions['logger'];\n}\n\n/**\n * Coerce JS values that sql.js cannot bind directly. Mirrors\n * `Client_BetterSQLite3._formatBindings`.\n *\n * `undefined` is mapped to `null`: sql.js's binder only accepts\n * string/number/bigint/boolean/null (and array/blob) and `throw`s a *raw\n * string* — `\"Wrong API use : tried to bind a value of an unknown type\n * (undefined).\"` — for anything else. Because it throws a string rather than\n * an `Error`, it logs as a garbled char-indexed object and aborts the whole\n * write. Mapping to `null` matches the `useNullAsDefault` semantics the\n * dialect is configured with, so a missing/undefined value persists as SQL\n * `NULL` exactly as it would through better-sqlite3.\n */\nfunction formatBindings(bindings: unknown[] | undefined): unknown[] {\n if (!bindings) return [];\n return bindings.map((b) => {\n if (b === undefined) return null;\n if (b instanceof Date) return b.valueOf();\n if (typeof b === 'boolean') return Number(b);\n return b;\n });\n}\n\n/**\n * Mirrors the dispatch in upstream `Client_SQLite3._query`: only\n * `insert/update/counter/del` go through the row-less write path (and even\n * those switch to the read path when a `RETURNING` clause is requested).\n * Everything else — `select`, `first`, `pluck`, `columnInfo`, raw PRAGMA,\n * DDL with no `method` — is read with `all`/row iteration so Knex sees the\n * same response shape it would from better-sqlite3.\n *\n * ⚠️ This answers \"how do I EXECUTE this statement\", never \"does this statement\n * change the database\" — an `INSERT … RETURNING *` is executed down the\n * row-returning branch and mutates. Persistence is classified separately by\n * {@link statementMutatesDatabase}; conflating the two is #4518.\n */\nfunction isRowReturningExecution(method?: string, returning?: unknown): boolean {\n if (method === 'insert' || method === 'update') return !!returning ? true : false;\n if (method === 'counter' || method === 'del') return false;\n return true;\n}\n\n/** Knex `method` values that always denote a mutation. */\nconst MUTATING_METHODS = new Set(['insert', 'update', 'del', 'counter']);\n\n/** Statement-control forms whose persistence is owned by the transaction lifecycle. */\nconst TRANSACTION_CONTROL_RE = /^\\s*(BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\\b/i;\n\n/**\n * DDL / schema statements. `BEGIN…RELEASE` share this prefix set in SQLite's\n * grammar but are transaction control, so they are matched (and routed) first.\n */\nconst DDL_RE =\n /^\\s*(CREATE|ALTER|DROP|BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE|REINDEX|VACUUM|ATTACH|DETACH|TRUNCATE)\\b/i;\n\n/** DML that changes rows, whatever execution branch it happens to run down. */\nconst MUTATING_DML_RE = /^\\s*(INSERT|UPDATE|DELETE|REPLACE|UPSERT)\\b/i;\n\n/**\n * PRAGMA forms that change bytes in the database file: any assignment\n * (`PRAGMA auto_vacuum = INCREMENTAL`, `PRAGMA user_version = 3` — both\n * persistent header state) and `incremental_vacuum`, which actually moves\n * pages. Introspection PRAGMAs (`table_info`, `index_list`, …) are reads.\n */\nconst MUTATING_PRAGMA_RE = /^\\s*PRAGMA\\b(?:[^;]*=|\\s+incremental_vacuum\\b)/i;\n\n/**\n * THE single answer to \"did this statement change the database, so that the\n * in-memory image must eventually be written back to disk?\"\n *\n * It is deliberately independent of which execution branch {@link\n * isRowReturningExecution} picks, because those are different questions and\n * answering them with one predicate is what broke persistence in #4518: the\n * ObjectQL engine writes through `INSERT … RETURNING *` / `UPDATE … RETURNING *`\n * (it needs the stored row back), those run down the row-returning branch, and\n * the dirty flag was only ever set on the other branch. The result was a\n * file-backed database that flushed its schema and then silently stopped\n * recording anything — a cold boot found every table present and every row\n * gone, and `on-disconnect` did not save it either, because the final flush\n * also keys off the same flag.\n *\n * Classifying by BOTH the Knex `method` and the SQL text means a mutation\n * cannot slip through by arriving without a method (`knex.raw('INSERT …')`,\n * seed/migration SQL) or by taking an unexpected branch.\n */\nexport function statementMutatesDatabase(sql: string, method?: string): boolean {\n if (TRANSACTION_CONTROL_RE.test(sql)) return false; // owned by noteTransactionControl\n if (method && MUTATING_METHODS.has(method)) return true;\n if (DDL_RE.test(sql)) return true;\n if (MUTATING_DML_RE.test(sql)) return true;\n return MUTATING_PRAGMA_RE.test(sql);\n}\n\n/**\n * Resolve the upstream `knex/lib/dialects/sqlite3` class at runtime.\n *\n * Tries every escape hatch we have so that this works in:\n * - Plain Node ESM (use `createRequire(import.meta.url)`).\n * - Plain Node CJS (use the ambient `require` on `globalThis`).\n * - Re-bundled ESM where esbuild/tsup has stubbed `__require` — we\n * fall back to `new Function('return require')()` which evades static\n * analysis and grabs the real Node `require` at runtime.\n *\n * Wrapped in a function so the bundler cannot execute it at module init.\n */\nfunction resolveKnexSqlite3Dialect(): any {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const g = globalThis as any;\n if (typeof g.require === 'function') {\n try {\n return g.require('knex/lib/dialects/sqlite3');\n } catch {\n /* fall through */\n }\n }\n // ESM-safe path: `createRequire` was imported statically at the top of\n // this module from `node:module`. In a pure-ESM process there is no\n // ambient `require`, so this is the only reliable way to load a CJS\n // package like `knex/lib/dialects/sqlite3`.\n return getEsmRequire()('knex/lib/dialects/sqlite3');\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet cachedDialect: any = null;\n\n/**\n * Build (and cache) the `Client_WasmSqlite` class. Building lazily keeps\n * the `require('knex/lib/dialects/sqlite3')` call out of module-init\n * code so downstream re-bundlers (e.g. `packages/runtime`) cannot collapse\n * it into a Dynamic-require stub.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function getClient_WasmSqlite(): any {\n if (cachedDialect) return cachedDialect;\n const Client_SQLite3 = resolveKnexSqlite3Dialect();\n\n class Client_WasmSqlite extends Client_SQLite3 {\n // sql.js has no shared \"driver module\" the way better-sqlite3 does. Knex\n // only uses `this.driver` to construct connections, and we override\n // `acquireRawConnection`, so a sentinel object is enough.\n _driver(): { name: 'sql.js' } {\n return { name: 'sql.js' };\n }\n\n async acquireRawConnection(): Promise<WasmSqliteConnection> {\n const settings = (this as any)\n .connectionSettings as WasmSqliteConnectionSettings;\n\n const conn = new WasmSqliteConnection({\n filename: settings.filename,\n persist: settings.persist,\n sqlJs: settings.sqlJs,\n locateFile: settings.locateFile,\n logger: settings.logger,\n });\n await conn.open(settings.sqlJs, settings.locateFile);\n return conn;\n }\n\n async destroyRawConnection(connection: WasmSqliteConnection): Promise<void> {\n await connection.close();\n }\n\n async _query(\n connection: WasmSqliteConnection,\n obj: any,\n ): Promise<any> {\n if (!obj.sql) throw new Error('The query is empty');\n if (!connection) throw new Error('No connection provided');\n\n const db = connection.raw;\n const bindings = formatBindings(obj.bindings);\n\n // ── 1. EXECUTE ────────────────────────────────────────────────────────\n // Three execution shapes. None of them decides persistence: that is\n // settled once, below, so a statement cannot mutate the database on a\n // branch that forgot to say so (#4518).\n\n // DDL / transaction control have no Knex `method`. sql.js's\n // `prepare`+`step` silently no-ops on many of these (e.g. CREATE TABLE),\n // so route them through `run` which is implemented via `exec` and\n // actually mutates the database. PRAGMA is intentionally excluded — many\n // PRAGMA forms (e.g. `PRAGMA table_info(...)`, `foreign_key_list(...)`)\n // return rows used by Knex's schema introspection/columnInfo, and\n // `db.run` discards those rows.\n if (DDL_RE.test(obj.sql)) {\n db.run(obj.sql, bindings as any);\n obj.response = [];\n } else if (\n isRowReturningExecution(obj.method, obj.returning) ||\n /^\\s*PRAGMA\\b/i.test(obj.sql)\n ) {\n // Row-returning branch. NOTE this is also where `INSERT … RETURNING *`\n // and `UPDATE … RETURNING *` land — statements that very much write.\n const stmt = db.prepare(obj.sql);\n try {\n if (bindings.length) stmt.bind(bindings as any);\n const rows: Record<string, unknown>[] = [];\n while (stmt.step()) {\n rows.push(stmt.getAsObject());\n }\n obj.response = rows;\n } finally {\n stmt.free();\n }\n } else {\n // Row-less write path: execute via `run` and capture SQLite's\n // per-connection lastID / changes counters.\n db.run(obj.sql, bindings as any);\n const changes = db.getRowsModified();\n let lastID: number | bigint = 0;\n if (obj.method === 'insert') {\n const r = db.exec('SELECT last_insert_rowid() AS id');\n lastID = (r?.[0]?.values?.[0]?.[0] as number) ?? 0;\n }\n obj.response = [];\n obj.context = { lastID, changes };\n }\n\n // ── 2. PERSIST ────────────────────────────────────────────────────────\n // Exactly one place decides whether the on-disk image is now stale.\n //\n // Transaction-control statements are routed to `noteTransactionControl`,\n // which owns flushing across the transaction lifecycle: it suppresses\n // flushes while a transaction is open (sql.js `export()` closes+reopens\n // the db, which would abort the txn) and performs a single flush once the\n // transaction fully closes. Routing them away from `markDirty` avoids a\n // second, racing flush on COMMIT.\n if (TRANSACTION_CONTROL_RE.test(obj.sql)) {\n connection.noteTransactionControl(obj.sql);\n } else if (statementMutatesDatabase(obj.sql, obj.method)) {\n connection.markDirty();\n }\n return obj;\n }\n }\n\n Object.assign(Client_WasmSqlite.prototype, {\n dialect: 'sqlite3',\n driverName: 'wasm-sqlite',\n });\n\n cachedDialect = Client_WasmSqlite;\n return Client_WasmSqlite;\n}\n\n/**\n * Back-compat re-export. Prefer `getClient_WasmSqlite()` so the dialect\n * is resolved lazily; the named export triggers the factory on first\n * access of any static property.\n *\n * Note: importing this binding will execute the factory at import time\n * in some bundlers, which defeats the lazy pattern. New code should call\n * `getClient_WasmSqlite()` directly.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const Client_WasmSqlite: any = new Proxy(function () {} as any, {\n get(_t, prop) {\n return (getClient_WasmSqlite() as any)[prop];\n },\n construct(_t, args) {\n const Klass = getClient_WasmSqlite();\n return new Klass(...args);\n },\n apply(_t, thisArg, args) {\n const Klass = getClient_WasmSqlite();\n return Reflect.apply(Klass, thisArg, args);\n },\n});\n\nexport default Client_WasmSqlite;\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\n/**\n * Thin wrapper over sql.js {@link Database} that mimics the surface of\n * `better-sqlite3`'s `Database` (only the methods the Knex dialect uses).\n *\n * Persistence is handled here, not in the Knex dialect, so it can be\n * orchestrated per-connection without polluting the SQL execution path.\n */\n\nimport type { Database, SqlJsStatic } from 'sql.js';\n\n/** When to flush the in-memory WASM database to disk. */\nexport type PersistMode =\n | 'on-disconnect'\n | 'on-write'\n | `debounced:${number}`;\n\nexport interface WasmConnectionOptions {\n /**\n * On-disk file path. `:memory:` (or any value starting with `:`) skips\n * persistence entirely and the database lives only for the process.\n */\n filename: string;\n /** When to persist. Default: `on-disconnect`. */\n persist?: PersistMode;\n /** Pre-loaded sql.js module. If omitted, loaded lazily on first connect. */\n sqlJs?: SqlJsStatic;\n /**\n * Optional override for the `.wasm` locator passed to `initSqlJs()`.\n * Defaults to resolving the file from the `sql.js` package on disk\n * (works in Node and WebContainer).\n */\n locateFile?: (file: string) => string;\n /** Optional logger; defaults to `console`. */\n logger?: { warn: (msg: string, meta?: unknown) => void };\n}\n\n/**\n * Detect whether a Node-style `fs` module is available. WebContainer\n * (StackBlitz) provides Node `fs`; pure-browser environments do not.\n */\nasync function tryLoadFs(): Promise<typeof import('node:fs/promises') | null> {\n try {\n return await import('node:fs/promises');\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve a default sql.js WASM locator. We point sql.js at the `.wasm`\n * file shipped inside `sql.js`'s own `dist/` folder. This avoids requiring\n * the caller to host the WASM separately.\n */\nasync function defaultLocateFile(): Promise<((file: string) => string) | undefined> {\n try {\n const { createRequire } = await import('node:module');\n const require = createRequire(import.meta.url);\n const pkgJsonPath = require.resolve('sql.js/package.json');\n const { dirname, join } = await import('node:path');\n const dir = dirname(pkgJsonPath);\n return (file: string) => join(dir, 'dist', file);\n } catch {\n return undefined;\n }\n}\n\nlet cachedSqlJs: Promise<SqlJsStatic> | null = null;\n\nasync function loadSqlJs(\n locateFile?: (file: string) => string,\n): Promise<SqlJsStatic> {\n if (cachedSqlJs) return cachedSqlJs;\n cachedSqlJs = (async () => {\n const mod = await import('sql.js');\n const initSqlJs = (mod as any).default ?? (mod as any);\n const locator = locateFile ?? (await defaultLocateFile());\n const SQL = await initSqlJs(locator ? { locateFile: locator } : undefined);\n return SQL as SqlJsStatic;\n })();\n return cachedSqlJs;\n}\n\n/**\n * A sql.js-backed connection that exposes the `prepare`/`exec`/`close`\n * subset used by Knex's SQLite dialect. Mutations are queued through a\n * configurable persistence strategy so the on-disk file stays in sync.\n */\nexport class WasmSqliteConnection {\n /**\n * Process-wide counter making each atomic-write temp filename unique, so\n * concurrent connections (or overlapping flushes) never target the same\n * temp path. Combined with `process.pid` for cross-process uniqueness.\n */\n private static tmpSeq = 0;\n\n readonly filename: string;\n readonly persist: PersistMode;\n readonly isEphemeral: boolean;\n\n private db!: Database;\n private fs: typeof import('node:fs/promises') | null = null;\n private dirty = false;\n private debounceMs = 0;\n private debounceTimer: ReturnType<typeof setTimeout> | null = null;\n private flushChain: Promise<void> | null = null;\n private destroyed = false;\n private logger: { warn: (msg: string, meta?: unknown) => void };\n\n /**\n * Whether a `BEGIN…COMMIT/ROLLBACK` transaction is currently open. Tracked\n * because sql.js's {@link Database.export} closes and reopens the database\n * (it has no in-place serialize), and closing a connection rolls back any\n * open transaction. Flushing mid-transaction would therefore silently\n * abort it, leaving the eventual `COMMIT` to fail with\n * \"cannot commit - no transaction is active\". We defer the flush until the\n * transaction fully closes. See {@link noteTransactionControl}.\n */\n private rootTxActive = false;\n /** Open `SAVEPOINT` depth (nested transactions emitted by Knex). */\n private savepointDepth = 0;\n /** A flush was requested while a transaction was open; run it on close. */\n private flushDeferred = false;\n\n /** True while any transaction (root or savepoint) is in flight. */\n private get inTransaction(): boolean {\n return this.rootTxActive || this.savepointDepth > 0;\n }\n\n constructor(opts: WasmConnectionOptions) {\n this.filename = opts.filename;\n this.persist = opts.persist ?? 'on-disconnect';\n this.isEphemeral =\n this.filename === ':memory:' || this.filename.startsWith(':');\n this.logger = opts.logger ?? console;\n\n if (typeof this.persist === 'string' && this.persist.startsWith('debounced:')) {\n const ms = Number(this.persist.slice('debounced:'.length));\n this.debounceMs = Number.isFinite(ms) && ms > 0 ? ms : 250;\n }\n }\n\n /** Open the underlying sql.js database, loading bytes from disk if any. */\n async open(sqlJs?: SqlJsStatic, locateFile?: (file: string) => string): Promise<void> {\n const SQL = sqlJs ?? (await loadSqlJs(locateFile));\n\n if (this.isEphemeral) {\n this.db = new SQL.Database();\n return;\n }\n\n this.fs = await tryLoadFs();\n if (!this.fs) {\n this.logger.warn(\n '[driver-sqlite-wasm] No node:fs available — falling back to in-memory database. ' +\n 'Data will not be persisted across reloads.',\n );\n this.db = new SQL.Database();\n return;\n }\n\n // Ensure parent directory exists, then load bytes if the file exists.\n const { dirname } = await import('node:path');\n const dir = dirname(this.filename);\n if (dir && dir !== '.') {\n await this.fs.mkdir(dir, { recursive: true });\n }\n\n let bytes: Uint8Array | undefined;\n try {\n const buf = await this.fs.readFile(this.filename);\n bytes = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n } catch (e: any) {\n if (e?.code !== 'ENOENT') throw e;\n }\n\n if (!bytes) {\n this.db = new SQL.Database();\n return;\n }\n\n await this.quarantineOrphanedWal();\n\n // Open the on-disk bytes, but guard against a corrupt image. A torn write\n // (process killed mid-flush before atomic writes existed) or otherwise\n // damaged file makes `new SQL.Database(bytes)` either throw (\"file is not a\n // database\") or open a handle whose every query fails with \"database disk\n // image is malformed\" — which, for a background dispatcher on a tick loop,\n // means the same error spammed forever with no path to recovery. Detect it\n // once at open, quarantine the bad file, and start fresh so the dev server\n // becomes usable again instead of wedging.\n try {\n const candidate = new SQL.Database(bytes);\n this.assertReadable(candidate);\n this.db = candidate;\n } catch (err) {\n await this.quarantineCorruptFile(err);\n this.db = new SQL.Database();\n }\n }\n\n /**\n * Force sql.js to actually read a page so a malformed image surfaces now\n * rather than on the first business query. `PRAGMA quick_check` walks the\n * b-tree structure without the full-scan cost of `integrity_check`; a healthy\n * database returns a single `ok` row. Any thrown error (raw string or Error)\n * or a non-`ok` result is treated as corruption.\n */\n private assertReadable(db: Database): void {\n const res = db.exec('PRAGMA quick_check(1)');\n const first = res?.[0]?.values?.[0]?.[0];\n if (typeof first === 'string' && first.toLowerCase() !== 'ok') {\n throw new Error(`sqlite quick_check failed: ${first}`);\n }\n }\n\n /**\n * Move a corrupt database file aside so its bytes are preserved for\n * post-mortem while a fresh, empty database takes its place. Best-effort:\n * failures here must not prevent the server from booting on a clean DB.\n */\n private async quarantineCorruptFile(cause: unknown): Promise<void> {\n if (!this.fs) return;\n const reason =\n typeof cause === 'string' ? cause : (cause as Error)?.message ?? String(cause);\n const backup = `${this.filename}.corrupt-${Date.now()}`;\n try {\n await this.fs.rename(this.filename, backup);\n this.logger.warn(\n `[driver-sqlite-wasm] Database image at ${this.filename} is corrupt ` +\n `(${reason}). Quarantined to ${backup} and starting from an empty ` +\n `database so the server can boot.`,\n );\n } catch (renameErr) {\n // Could not move it aside (e.g. permissions) — overwrite is still better\n // than looping forever on a malformed image. Warn loudly and continue.\n this.logger.warn(\n `[driver-sqlite-wasm] Database image at ${this.filename} is corrupt ` +\n `(${reason}) and could not be quarantined (${String(renameErr)}). ` +\n `Starting from an empty database; the corrupt file will be overwritten ` +\n `on the next flush.`,\n );\n }\n }\n\n /**\n * Move a write-ahead log left behind by a *real* SQLite aside (#3941).\n *\n * The native driver keeps file-backed databases in WAL mode, and a clean close\n * checkpoints the log away — so a non-empty `<db>-wal` here means the last\n * process died without one. That log is a problem in both directions, and\n * neither is something wasm SQLite can fix: it cannot read the log (we load\n * only the main image, so any transaction still in there is invisible), and it\n * must not leave it in place either — the next {@link flush} rewrites the\n * image, and a real SQLite opening a fresh image beside a stale log would\n * replay frames that no longer belong to it.\n *\n * So rename it, which loses nothing recoverable (the bytes are preserved for a\n * real `sqlite3` to recover from) and disarms the mismatch. Best-effort: this\n * is a dev-only step-down path and must never prevent a boot.\n */\n private async quarantineOrphanedWal(): Promise<void> {\n if (!this.fs) return;\n const wal = `${this.filename}-wal`;\n let size: number;\n try {\n size = (await this.fs.stat(wal)).size;\n } catch {\n return; // no sidecar (the normal case) or an unreadable one\n }\n if (size <= 0) return; // checkpointed-and-truncated: nothing in it\n\n const parked = `${wal}.orphaned-${Date.now()}`;\n try {\n await this.fs.rename(wal, parked);\n this.logger.warn(\n `[driver-sqlite-wasm] ${wal} holds ${size} bytes of write-ahead log that wasm SQLite ` +\n `cannot read — this database was last used in WAL mode and closed uncleanly. Parked it ` +\n `at ${parked} and loaded the main image without it, so anything committed only to the ` +\n `log is NOT in this session. To recover it, rebuild better-sqlite3 (or use \\`sqlite3\\`), ` +\n `restore the log next to the database, and run \\`PRAGMA wal_checkpoint(TRUNCATE)\\`.`,\n );\n } catch (renameErr) {\n this.logger.warn(\n `[driver-sqlite-wasm] ${wal} holds ${size} bytes of write-ahead log that wasm SQLite ` +\n `cannot read, and it could not be moved aside (${String(renameErr)}). Data committed ` +\n `only to the log is missing from this session; checkpoint it with a real sqlite3 before ` +\n `writing further.`,\n );\n }\n }\n\n /**\n * Update transaction state from a transaction-control statement and, when a\n * transaction has just fully closed, run any flush that was deferred while\n * it was open. Called by the Knex dialect for every `BEGIN` / `COMMIT` /\n * `ROLLBACK` / `SAVEPOINT` / `RELEASE` statement.\n *\n * We bias toward \"in transaction\": an unrecognised form leaves the flag set,\n * which at worst delays a flush (safe) rather than exporting mid-transaction\n * (which would abort it).\n */\n noteTransactionControl(sql: string): void {\n const s = sql.trim().toUpperCase();\n if (/^BEGIN\\b/.test(s)) {\n this.rootTxActive = true;\n } else if (/^(COMMIT|END)\\b/.test(s)) {\n // A COMMIT/END ends the whole transaction regardless of savepoint nesting.\n this.rootTxActive = false;\n this.savepointDepth = 0;\n } else if (/^ROLLBACK\\s+TO\\b/.test(s)) {\n // Rolls back to a savepoint but keeps the (outer) transaction open.\n } else if (/^ROLLBACK\\b/.test(s)) {\n this.rootTxActive = false;\n this.savepointDepth = 0;\n } else if (/^SAVEPOINT\\b/.test(s)) {\n this.savepointDepth += 1;\n } else if (/^RELEASE\\b/.test(s)) {\n this.savepointDepth = Math.max(0, this.savepointDepth - 1);\n }\n // If the transaction just fully closed and a flush was deferred while it\n // was open, run it now. We key off `flushDeferred` (set only when\n // `markDirty` actually wanted to flush) rather than `dirty`, so persist\n // modes that don't flush per-write — e.g. `on-disconnect` — still defer to\n // close() instead of flushing on every COMMIT.\n if (!this.inTransaction && this.flushDeferred) {\n this.flushDeferred = false;\n void this.flush();\n }\n }\n\n /**\n * Record that the statement just executed CHANGED the database, and schedule\n * a flush according to {@link persist}.\n *\n * Deliberately takes no argument. It used to filter the caller's Knex\n * `method` against a local write-method allowlist, which made \"did this\n * mutate?\" a decision taken in TWO places — here and in the dialect's\n * execution-path branch — and the two disagreed: an `INSERT … RETURNING`\n * runs down the dialect's ROW-returning branch (it has rows to return), that\n * branch never called this method at all, and so a whole class of committed\n * writes was never marked dirty and never reached disk (#4518). One decision,\n * one owner: {@link statementMutatesDatabase} in the dialect classifies the\n * statement, and this method just does what it is told.\n */\n markDirty(): void {\n if (this.isEphemeral || !this.fs) return;\n this.dirty = true;\n\n if (this.persist === 'on-write') {\n void this.flush();\n return;\n }\n if (this.debounceMs > 0) {\n if (this.debounceTimer) clearTimeout(this.debounceTimer);\n this.debounceTimer = setTimeout(() => {\n this.debounceTimer = null;\n void this.flush();\n }, this.debounceMs);\n }\n // 'on-disconnect' → flush only at close()\n }\n\n /**\n * Force a write of the current database state to disk.\n *\n * Flushes are strictly serialized through a single promise chain: every call\n * appends an export+write step that runs after all previously-queued steps.\n * This matters because sql.js `export()` mutates the live connection (it\n * closes and reopens the database), so two exports must never overlap — and\n * because the returned promise must not resolve until the caller's own write\n * has hit disk (deterministic for tests and for `close()`). Each step\n * re-checks `dirty` at run time, so a no-op write collapses cheaply and a\n * write that arrived mid-flush is captured by the next queued step.\n */\n async flush(): Promise<void> {\n if (this.isEphemeral || !this.fs || this.destroyed) return;\n // Never export while a transaction is open: sql.js's `export()` closes and\n // reopens the database, which rolls back the in-flight transaction and\n // makes the subsequent COMMIT fail. Defer until the transaction closes\n // (handled in `noteTransactionControl`).\n if (this.inTransaction) {\n this.flushDeferred = true;\n return;\n }\n\n const prev = this.flushChain;\n const step = (prev ?? Promise.resolve()).then(async () => {\n if (!this.dirty || this.destroyed || this.inTransaction) return;\n // Snapshot dirty=false before export so a concurrent write re-marks us\n // and is picked up by the next queued step.\n this.dirty = false;\n try {\n const exported = this.db.export();\n // sql.js returns a Uint8Array; Buffer.from on it shares memory but\n // works fine for the atomic write below.\n await this.atomicWriteFile(Buffer.from(exported));\n } catch (err) {\n this.dirty = true; // let a later flush retry\n throw err;\n }\n });\n // Keep the chain tail alive but swallow its rejection there so one failed\n // flush doesn't poison every future flush; the awaited `step` still throws.\n this.flushChain = step.catch(() => {});\n await step;\n }\n\n /**\n * Write the database bytes to disk atomically: write to a sibling temp file,\n * fsync it, then `rename()` it over the target.\n *\n * A plain `writeFile(this.filename, …)` truncates the target and streams the\n * new bytes in place, so a process killed mid-write (a dev-server restart,\n * Ctrl-C, or crash — likely under `on-write`, where every dispatcher tick\n * flushes) leaves a half-written file. sql.js then rejects that file on the\n * next boot with \"database disk image is malformed\". `rename(2)` is atomic\n * within a filesystem, so a reader always sees either the complete old file\n * or the complete new one — never a torn image. The temp file lives in the\n * same directory as the target so the rename stays intra-filesystem.\n */\n private async atomicWriteFile(data: Buffer): Promise<void> {\n if (!this.fs) return;\n const tmp = `${this.filename}.tmp-${process.pid}-${(WasmSqliteConnection.tmpSeq += 1)}`;\n let handle: import('node:fs/promises').FileHandle | undefined;\n try {\n handle = await this.fs.open(tmp, 'w');\n await handle.writeFile(data);\n // Flush the bytes to the platter before the rename so a crash can't leave\n // a renamed-but-empty file behind on filesystems that reorder the two.\n await handle.sync();\n await handle.close();\n handle = undefined;\n await this.fs.rename(tmp, this.filename);\n } catch (err) {\n if (handle) {\n try {\n await handle.close();\n } catch {\n /* ignore */\n }\n }\n // Clean up the temp file so a failed flush doesn't litter the data dir.\n try {\n await this.fs.unlink(tmp);\n } catch {\n /* ignore */\n }\n throw err;\n }\n }\n\n /** Close the database, flushing any pending writes first. */\n async close(): Promise<void> {\n if (this.destroyed) return;\n if (this.debounceTimer) {\n clearTimeout(this.debounceTimer);\n this.debounceTimer = null;\n }\n // Any transaction still open at close is abandoned and will be rolled back\n // by `db.close()`; clear the flag so the final flush is not deferred and\n // already-committed data is persisted.\n this.rootTxActive = false;\n this.savepointDepth = 0;\n try {\n await this.flush();\n } finally {\n this.destroyed = true;\n try {\n this.db.close();\n } catch {\n /* ignore */\n }\n }\n }\n\n /** Access the raw sql.js database (for the Knex dialect). */\n get raw(): Database {\n return this.db;\n }\n}\n","// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.\n\nimport { SqliteWasmDriver } from './sqlite-wasm-driver.js';\n\nexport { SqliteWasmDriver };\nexport type { SqliteWasmDriverConfig } from './sqlite-wasm-driver.js';\nexport { Client_WasmSqlite } from './knex-wasm-dialect.js';\nexport type { WasmSqliteConnectionSettings } from './knex-wasm-dialect.js';\nexport { WasmSqliteConnection } from './wasm-connection.js';\nexport type { PersistMode, WasmConnectionOptions } from './wasm-connection.js';\n\nexport default {\n id: 'com.objectstack.driver.sqlite-wasm',\n version: '1.0.0',\n\n onEnable: async (context: any) => {\n const { logger, config, drivers } = context;\n logger?.info?.('[SQLite-WASM Driver] Initializing...');\n\n if (drivers) {\n const driver = new SqliteWasmDriver(config);\n drivers.register(driver);\n logger?.info?.(`[SQLite-WASM Driver] Registered driver: ${driver.name}`);\n } else {\n logger?.warn?.('[SQLite-WASM Driver] No driver registry found in context.');\n }\n },\n};\n"],"mappings":";AAaA,SAAS,iBAAuC;;;ACWhD,SAAS,qBAAqB;;;ACkB9B,eAAe,YAA+D;AAC5E,MAAI;AACF,WAAO,MAAM,OAAO,aAAkB;AAAA,EACxC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAOA,eAAe,oBAAqE;AAClF,MAAI;AACF,UAAM,EAAE,eAAAA,eAAc,IAAI,MAAM,OAAO,QAAa;AACpD,UAAMC,WAAUD,eAAc,YAAY,GAAG;AAC7C,UAAM,cAAcC,SAAQ,QAAQ,qBAAqB;AACzD,UAAM,EAAE,SAAS,KAAK,IAAI,MAAM,OAAO,MAAW;AAClD,UAAM,MAAM,QAAQ,WAAW;AAC/B,WAAO,CAAC,SAAiB,KAAK,KAAK,QAAQ,IAAI;AAAA,EACjD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,IAAI,cAA2C;AAE/C,eAAe,UACb,YACsB;AACtB,MAAI,YAAa,QAAO;AACxB,iBAAe,YAAY;AACzB,UAAM,MAAM,MAAM,OAAO,QAAQ;AACjC,UAAM,YAAa,IAAY,WAAY;AAC3C,UAAM,UAAU,cAAe,MAAM,kBAAkB;AACvD,UAAM,MAAM,MAAM,UAAU,UAAU,EAAE,YAAY,QAAQ,IAAI,MAAS;AACzE,WAAO;AAAA,EACT,GAAG;AACH,SAAO;AACT;AAOO,IAAM,wBAAN,MAAM,sBAAqB;AAAA,EAyChC,YAAY,MAA6B;AA5BzC,SAAQ,KAA+C;AACvD,SAAQ,QAAQ;AAChB,SAAQ,aAAa;AACr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M;AACrB,UAAM,OAAO,QAAQ;AACrB,QAAI,CAAC,QAAQ,OAAO,KAAK,YAAY,WAAY;AAEjD,UAAM,UAAU,OAAO,mBAAmB,KAAK,MAAM;AACrD,UAAM,UAAU,OAAO,mBAAmB,KAAK,MAAM;AACrD,QAAI,CAAC,WAAW,CAAC,QAAS;AAE1B,UAAM,OAAO,MAAM,QAAQ;AAC3B,QAAI;AACF,UAAI,QAAQ,OAAO,KAAK,UAAU,YAAY;AAC5C,cAAM,KAAK,MAAM;AAAA,MACnB;AAAA,IACF,UAAE;AACA,YAAM,QAAQ,IAAI;AAAA,IACpB;AAAA,EACF;AACF;;;AGpLA,IAAO,gBAAQ;AAAA,EACb,IAAI;AAAA,EACJ,SAAS;AAAA,EAET,UAAU,OAAO,YAAiB;AAChC,UAAM,EAAE,QAAQ,QAAQ,QAAQ,IAAI;AACpC,YAAQ,OAAO,sCAAsC;AAErD,QAAI,SAAS;AACX,YAAM,SAAS,IAAI,iBAAiB,MAAM;AAC1C,cAAQ,SAAS,MAAM;AACvB,cAAQ,OAAO,2CAA2C,OAAO,IAAI,EAAE;AAAA,IACzE,OAAO;AACL,cAAQ,OAAO,2DAA2D;AAAA,IAC5E;AAAA,EACF;AACF;","names":["createRequire","require","Client_WasmSqlite"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@objectstack/driver-sqlite-wasm",
|
|
3
|
-
"version": "17.0.0-rc.
|
|
3
|
+
"version": "17.0.0-rc.2",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"description": "WASM SQLite Driver for ObjectStack — runs in browser/WebContainer (StackBlitz) without native bindings",
|
|
6
6
|
"keywords": [
|
|
@@ -26,12 +26,12 @@
|
|
|
26
26
|
"knex": "^3.3.0",
|
|
27
27
|
"nanoid": "^6.0.0",
|
|
28
28
|
"sql.js": "^1.14.1",
|
|
29
|
-
"@objectstack/
|
|
30
|
-
"@objectstack/
|
|
31
|
-
"@objectstack/
|
|
29
|
+
"@objectstack/driver-sql": "17.0.0-rc.2",
|
|
30
|
+
"@objectstack/spec": "17.0.0-rc.2",
|
|
31
|
+
"@objectstack/core": "17.0.0-rc.2"
|
|
32
32
|
},
|
|
33
33
|
"devDependencies": {
|
|
34
|
-
"@types/node": "^26.1.
|
|
34
|
+
"@types/node": "^26.1.2",
|
|
35
35
|
"@types/sql.js": "^1.4.11",
|
|
36
36
|
"typescript": "^6.0.3",
|
|
37
37
|
"vitest": "^4.1.10"
|