@objectstack/driver-sqlite-wasm 17.2.0 → 17.3.0
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 +375 -0
- package/dist/index.js.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,380 @@
|
|
|
1
1
|
# @objectstack/driver-sqlite-wasm
|
|
2
2
|
|
|
3
|
+
## 17.3.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 9f4a6d5: feat(driver-sql,driver-turso,driver-sqlite-wasm): SQLite-family JSON columns declare `TEXT`; server dialects keep native JSON (#12738)
|
|
8
|
+
|
|
9
|
+
A `Field.json` column — and any field with `multiple: true` — is now declared as
|
|
10
|
+
the JSON column type the **target dialect actually has**. Postgres and MySQL are
|
|
11
|
+
untouched: their native `json`/`jsonb` and `JSON` types are correct and stay.
|
|
12
|
+
The SQLite family (plain `SqlDriver` on `sqlite3`/`better-sqlite3`, `TursoDriver`
|
|
13
|
+
in all three transport modes, and `SqliteWasmDriver`) now declares `text`.
|
|
14
|
+
|
|
15
|
+
**Why.** SQLite has no JSON type. It derives a column's *affinity* from
|
|
16
|
+
substrings of the declared type name, and `json` contains none of the markers
|
|
17
|
+
(`INT`, `CHAR`/`CLOB`/`TEXT`, `BLOB`, `REAL`/`FLOA`/`DOUB`), so it fell through
|
|
18
|
+
to **NUMERIC** and converted number-like input on the way in — measured through
|
|
19
|
+
raw SQL, a bare `'0123'` was stored as the integer `123`. `text` takes TEXT
|
|
20
|
+
affinity, converts nothing, and is what SQLite's own JSON1 functions operate on.
|
|
21
|
+
It is also what `RemoteTransport.mapFieldTypeToSQL` had spelled all along, so
|
|
22
|
+
turso's two transports now agree instead of diverging on one column.
|
|
23
|
+
|
|
24
|
+
## The migration shape
|
|
25
|
+
|
|
26
|
+
- **New columns only.** The change is to the DDL emitter. Schema sync is
|
|
27
|
+
additive, so no existing column is altered, dropped or rewritten.
|
|
28
|
+
- **Existing columns keep their declared type.** A column created before this
|
|
29
|
+
release stays `json` and keeps NUMERIC affinity — including through an
|
|
30
|
+
unrelated SQLite drift rebuild, which re-declares an introspected `json`
|
|
31
|
+
column as `json` rather than converting it.
|
|
32
|
+
- **Platform write-path behaviour is unchanged.** The `Field.json` codec stays
|
|
33
|
+
injective and stays in force: what the platform writes and reads back is
|
|
34
|
+
identical before and after, on legacy and new columns alike. Nothing on the
|
|
35
|
+
read path consults the physical column type — `isJsonField` answers from
|
|
36
|
+
metadata — so decoding is the same on both spellings.
|
|
37
|
+
- **No new schema-drift findings.** The multi-value base-type finding is gated
|
|
38
|
+
on the dialect where the column type is load-bearing (Postgres and MySQL);
|
|
39
|
+
SQLite was already excluded, and the emitter now agrees with the differ
|
|
40
|
+
instead of merely being excused by it.
|
|
41
|
+
- **The visible difference is raw-SQL-only, and in the safe direction.** A value
|
|
42
|
+
written to a JSON column by raw SQL (bypassing the driver) is preserved as
|
|
43
|
+
text on a new column where it would previously have been coerced to a number.
|
|
44
|
+
Nothing that was preserved before is coerced now.
|
|
45
|
+
|
|
46
|
+
### Patch Changes
|
|
47
|
+
|
|
48
|
+
- Updated dependencies [809d417]
|
|
49
|
+
- Updated dependencies [387e231]
|
|
50
|
+
- Updated dependencies [f794e4e]
|
|
51
|
+
- Updated dependencies [cae2169]
|
|
52
|
+
- Updated dependencies [b812a54]
|
|
53
|
+
- Updated dependencies [2d4fa75]
|
|
54
|
+
- Updated dependencies [0e4e51b]
|
|
55
|
+
- Updated dependencies [e84bbf6]
|
|
56
|
+
- Updated dependencies [effae80]
|
|
57
|
+
- Updated dependencies [efb3513]
|
|
58
|
+
- Updated dependencies [d62f990]
|
|
59
|
+
- Updated dependencies [c45d8e6]
|
|
60
|
+
- Updated dependencies [2e3e8c7]
|
|
61
|
+
- Updated dependencies [e621291]
|
|
62
|
+
- Updated dependencies [655b106]
|
|
63
|
+
- Updated dependencies [40a93b5]
|
|
64
|
+
- Updated dependencies [ef52884]
|
|
65
|
+
- Updated dependencies [d5b330d]
|
|
66
|
+
- Updated dependencies [9e1b2de]
|
|
67
|
+
- Updated dependencies [dda969c]
|
|
68
|
+
- Updated dependencies [1f45690]
|
|
69
|
+
- Updated dependencies [277948f]
|
|
70
|
+
- Updated dependencies [8bdd955]
|
|
71
|
+
- Updated dependencies [f3bbbef]
|
|
72
|
+
- Updated dependencies [4f24e9d]
|
|
73
|
+
- Updated dependencies [e27583e]
|
|
74
|
+
- Updated dependencies [4bd6faa]
|
|
75
|
+
- Updated dependencies [86cbe37]
|
|
76
|
+
- Updated dependencies [6a180e4]
|
|
77
|
+
- Updated dependencies [474242f]
|
|
78
|
+
- Updated dependencies [63cd487]
|
|
79
|
+
- Updated dependencies [bd4aa4e]
|
|
80
|
+
- Updated dependencies [803eaab]
|
|
81
|
+
- Updated dependencies [f8e8f03]
|
|
82
|
+
- Updated dependencies [983edf1]
|
|
83
|
+
- Updated dependencies [eae824e]
|
|
84
|
+
- Updated dependencies [178f90c]
|
|
85
|
+
- Updated dependencies [f6fa22c]
|
|
86
|
+
- Updated dependencies [8a483b3]
|
|
87
|
+
- Updated dependencies [84de7e3]
|
|
88
|
+
- Updated dependencies [3bc2e38]
|
|
89
|
+
- Updated dependencies [97bcd99]
|
|
90
|
+
- Updated dependencies [df59de0]
|
|
91
|
+
- Updated dependencies [96e25a8]
|
|
92
|
+
- Updated dependencies [f75a38a]
|
|
93
|
+
- Updated dependencies [7a25e7d]
|
|
94
|
+
- Updated dependencies [1fa05a6]
|
|
95
|
+
- Updated dependencies [c85a265]
|
|
96
|
+
- Updated dependencies [dcb10a5]
|
|
97
|
+
- Updated dependencies [773a999]
|
|
98
|
+
- Updated dependencies [35dffea]
|
|
99
|
+
- Updated dependencies [d8024f0]
|
|
100
|
+
- Updated dependencies [8120808]
|
|
101
|
+
- Updated dependencies [0010797]
|
|
102
|
+
- Updated dependencies [776a098]
|
|
103
|
+
- Updated dependencies [5060877]
|
|
104
|
+
- Updated dependencies [4f6325d]
|
|
105
|
+
- Updated dependencies [52954c0]
|
|
106
|
+
- Updated dependencies [2aa8456]
|
|
107
|
+
- Updated dependencies [93809a3]
|
|
108
|
+
- Updated dependencies [7c0d0c3]
|
|
109
|
+
- Updated dependencies [daae7aa]
|
|
110
|
+
- Updated dependencies [8dc22d6]
|
|
111
|
+
- Updated dependencies [279431e]
|
|
112
|
+
- Updated dependencies [948dd6b]
|
|
113
|
+
- Updated dependencies [3b4c56c]
|
|
114
|
+
- Updated dependencies [ae8edd2]
|
|
115
|
+
- Updated dependencies [e25403c]
|
|
116
|
+
- Updated dependencies [f9ffd01]
|
|
117
|
+
- Updated dependencies [64baa68]
|
|
118
|
+
- Updated dependencies [9fa70d7]
|
|
119
|
+
- Updated dependencies [09db64a]
|
|
120
|
+
- Updated dependencies [92916e7]
|
|
121
|
+
- Updated dependencies [a84f3ea]
|
|
122
|
+
- Updated dependencies [f2eaae8]
|
|
123
|
+
- Updated dependencies [09f9361]
|
|
124
|
+
- Updated dependencies [c804f0c]
|
|
125
|
+
- Updated dependencies [34d3011]
|
|
126
|
+
- Updated dependencies [c09451b]
|
|
127
|
+
- Updated dependencies [ba64877]
|
|
128
|
+
- Updated dependencies [9d3c04d]
|
|
129
|
+
- Updated dependencies [d29e42f]
|
|
130
|
+
- Updated dependencies [87ad30c]
|
|
131
|
+
- Updated dependencies [fcd0efc]
|
|
132
|
+
- Updated dependencies [d0e3a88]
|
|
133
|
+
- Updated dependencies [3f42920]
|
|
134
|
+
- Updated dependencies [dd4113e]
|
|
135
|
+
- Updated dependencies [992161b]
|
|
136
|
+
- Updated dependencies [ebcc34e]
|
|
137
|
+
- Updated dependencies [64505a5]
|
|
138
|
+
- Updated dependencies [7345308]
|
|
139
|
+
- Updated dependencies [79b6a22]
|
|
140
|
+
- Updated dependencies [30d96ab]
|
|
141
|
+
- Updated dependencies [f658793]
|
|
142
|
+
- Updated dependencies [c95ad19]
|
|
143
|
+
- Updated dependencies [e58ea8b]
|
|
144
|
+
- Updated dependencies [4a17645]
|
|
145
|
+
- Updated dependencies [3795c5f]
|
|
146
|
+
- Updated dependencies [8ab926b]
|
|
147
|
+
- Updated dependencies [7317cf2]
|
|
148
|
+
- Updated dependencies [e25e839]
|
|
149
|
+
- Updated dependencies [5997207]
|
|
150
|
+
- Updated dependencies [8b13cc8]
|
|
151
|
+
- Updated dependencies [4a4a35d]
|
|
152
|
+
- Updated dependencies [4a4a35d]
|
|
153
|
+
- Updated dependencies [86e765a]
|
|
154
|
+
- Updated dependencies [1d7e76a]
|
|
155
|
+
- Updated dependencies [53dc739]
|
|
156
|
+
- Updated dependencies [fd289be]
|
|
157
|
+
- Updated dependencies [03bf7b1]
|
|
158
|
+
- Updated dependencies [f90e820]
|
|
159
|
+
- Updated dependencies [18d816a]
|
|
160
|
+
- Updated dependencies [e8bd715]
|
|
161
|
+
- Updated dependencies [b91c351]
|
|
162
|
+
- Updated dependencies [a28a3c0]
|
|
163
|
+
- Updated dependencies [daeaaf9]
|
|
164
|
+
- Updated dependencies [c459da6]
|
|
165
|
+
- Updated dependencies [e914733]
|
|
166
|
+
- Updated dependencies [f887e52]
|
|
167
|
+
- Updated dependencies [881f8d8]
|
|
168
|
+
- Updated dependencies [3bfa1e6]
|
|
169
|
+
- Updated dependencies [0a8ebf3]
|
|
170
|
+
- Updated dependencies [901355c]
|
|
171
|
+
- Updated dependencies [107bb4b]
|
|
172
|
+
- Updated dependencies [34ce8e7]
|
|
173
|
+
- Updated dependencies [33681ea]
|
|
174
|
+
- Updated dependencies [4635f3e]
|
|
175
|
+
- Updated dependencies [fd289be]
|
|
176
|
+
- Updated dependencies [ee3595c]
|
|
177
|
+
- Updated dependencies [b2eab95]
|
|
178
|
+
- Updated dependencies [93940d4]
|
|
179
|
+
- Updated dependencies [3a04b01]
|
|
180
|
+
- Updated dependencies [45b9051]
|
|
181
|
+
- Updated dependencies [b9e9227]
|
|
182
|
+
- Updated dependencies [d395692]
|
|
183
|
+
- Updated dependencies [5894d30]
|
|
184
|
+
- Updated dependencies [a3765f6]
|
|
185
|
+
- Updated dependencies [2d5cee3]
|
|
186
|
+
- Updated dependencies [e22158f]
|
|
187
|
+
- Updated dependencies [7404925]
|
|
188
|
+
- Updated dependencies [0c2334f]
|
|
189
|
+
- Updated dependencies [778c59f]
|
|
190
|
+
- Updated dependencies [d2619fd]
|
|
191
|
+
- Updated dependencies [af56546]
|
|
192
|
+
- Updated dependencies [6acb11a]
|
|
193
|
+
- Updated dependencies [33c5fd3]
|
|
194
|
+
- Updated dependencies [20b0fdb]
|
|
195
|
+
- Updated dependencies [905019b]
|
|
196
|
+
- Updated dependencies [a286411]
|
|
197
|
+
- Updated dependencies [98c0d33]
|
|
198
|
+
- Updated dependencies [368a82e]
|
|
199
|
+
- Updated dependencies [a3d5724]
|
|
200
|
+
- Updated dependencies [93ea19b]
|
|
201
|
+
- Updated dependencies [9ee2dcf]
|
|
202
|
+
- Updated dependencies [8cb96ec]
|
|
203
|
+
- Updated dependencies [8f10a79]
|
|
204
|
+
- Updated dependencies [6269a55]
|
|
205
|
+
- Updated dependencies [a17da05]
|
|
206
|
+
- Updated dependencies [a8c00e2]
|
|
207
|
+
- Updated dependencies [0fb8760]
|
|
208
|
+
- Updated dependencies [e5ce2ed]
|
|
209
|
+
- Updated dependencies [be21955]
|
|
210
|
+
- Updated dependencies [bc56e18]
|
|
211
|
+
- Updated dependencies [be21955]
|
|
212
|
+
- Updated dependencies [a9ee989]
|
|
213
|
+
- Updated dependencies [4d0d944]
|
|
214
|
+
- Updated dependencies [15d58db]
|
|
215
|
+
- Updated dependencies [d63b014]
|
|
216
|
+
- Updated dependencies [9abe4e4]
|
|
217
|
+
- Updated dependencies [2cc7122]
|
|
218
|
+
- Updated dependencies [50d6c92]
|
|
219
|
+
- Updated dependencies [9e0ba21]
|
|
220
|
+
- Updated dependencies [311433f]
|
|
221
|
+
- Updated dependencies [0e5bea6]
|
|
222
|
+
- Updated dependencies [3e5ad08]
|
|
223
|
+
- Updated dependencies [9abe4e4]
|
|
224
|
+
- Updated dependencies [b7131f3]
|
|
225
|
+
- Updated dependencies [e5812fa]
|
|
226
|
+
- Updated dependencies [7085f90]
|
|
227
|
+
- Updated dependencies [dee4dd4]
|
|
228
|
+
- Updated dependencies [e40a28c]
|
|
229
|
+
- Updated dependencies [7e83932]
|
|
230
|
+
- Updated dependencies [ce7e497]
|
|
231
|
+
- Updated dependencies [51ecb2f]
|
|
232
|
+
- Updated dependencies [9086761]
|
|
233
|
+
- Updated dependencies [42a117b]
|
|
234
|
+
- Updated dependencies [1401ae7]
|
|
235
|
+
- Updated dependencies [4297fe7]
|
|
236
|
+
- Updated dependencies [e398863]
|
|
237
|
+
- Updated dependencies [d16df74]
|
|
238
|
+
- Updated dependencies [f11fc61]
|
|
239
|
+
- Updated dependencies [e808890]
|
|
240
|
+
- Updated dependencies [8f79379]
|
|
241
|
+
- Updated dependencies [e6ca40e]
|
|
242
|
+
- Updated dependencies [0c77ea4]
|
|
243
|
+
- Updated dependencies [52954c0]
|
|
244
|
+
- Updated dependencies [89eb997]
|
|
245
|
+
- Updated dependencies [7131f12]
|
|
246
|
+
- Updated dependencies [aa5994e]
|
|
247
|
+
- Updated dependencies [be93457]
|
|
248
|
+
- Updated dependencies [a65db76]
|
|
249
|
+
- Updated dependencies [15eb2c9]
|
|
250
|
+
- Updated dependencies [5691b07]
|
|
251
|
+
- Updated dependencies [431d2fb]
|
|
252
|
+
- Updated dependencies [2a6122b]
|
|
253
|
+
- Updated dependencies [225e769]
|
|
254
|
+
- Updated dependencies [8af88dd]
|
|
255
|
+
- Updated dependencies [fb5fbb8]
|
|
256
|
+
- Updated dependencies [c05b40b]
|
|
257
|
+
- Updated dependencies [80f1dcd]
|
|
258
|
+
- Updated dependencies [6c6157a]
|
|
259
|
+
- Updated dependencies [d7b3963]
|
|
260
|
+
- Updated dependencies [33184fd]
|
|
261
|
+
- Updated dependencies [7c41693]
|
|
262
|
+
- Updated dependencies [b72db01]
|
|
263
|
+
- Updated dependencies [dce5cd4]
|
|
264
|
+
- Updated dependencies [9688f58]
|
|
265
|
+
- Updated dependencies [556ebc1]
|
|
266
|
+
- Updated dependencies [177ebdc]
|
|
267
|
+
- Updated dependencies [8d237b4]
|
|
268
|
+
- Updated dependencies [2d2e6f0]
|
|
269
|
+
- Updated dependencies [2d8dd8d]
|
|
270
|
+
- Updated dependencies [22d573e]
|
|
271
|
+
- Updated dependencies [b5a2398]
|
|
272
|
+
- Updated dependencies [348860c]
|
|
273
|
+
- Updated dependencies [5383fa6]
|
|
274
|
+
- Updated dependencies [5b3ff63]
|
|
275
|
+
- Updated dependencies [1a6a19c]
|
|
276
|
+
- Updated dependencies [527e050]
|
|
277
|
+
- Updated dependencies [dd33bf9]
|
|
278
|
+
- Updated dependencies [4cb2a90]
|
|
279
|
+
- Updated dependencies [6757eb2]
|
|
280
|
+
- Updated dependencies [74a7804]
|
|
281
|
+
- Updated dependencies [53d3689]
|
|
282
|
+
- Updated dependencies [b3a63d3]
|
|
283
|
+
- Updated dependencies [1c66fe4]
|
|
284
|
+
- Updated dependencies [49f0dcf]
|
|
285
|
+
- Updated dependencies [033a34c]
|
|
286
|
+
- Updated dependencies [4d25d22]
|
|
287
|
+
- Updated dependencies [1ffee51]
|
|
288
|
+
- Updated dependencies [b826390]
|
|
289
|
+
- Updated dependencies [5ae4303]
|
|
290
|
+
- Updated dependencies [ece4dad]
|
|
291
|
+
- Updated dependencies [e9b377e]
|
|
292
|
+
- Updated dependencies [146f448]
|
|
293
|
+
- Updated dependencies [735f5c7]
|
|
294
|
+
- Updated dependencies [a7e18de]
|
|
295
|
+
- Updated dependencies [366f895]
|
|
296
|
+
- Updated dependencies [dc75ba8]
|
|
297
|
+
- Updated dependencies [cce0aa9]
|
|
298
|
+
- Updated dependencies [e764507]
|
|
299
|
+
- Updated dependencies [cff17af]
|
|
300
|
+
- Updated dependencies [39404f3]
|
|
301
|
+
- Updated dependencies [ca1965f]
|
|
302
|
+
- Updated dependencies [8619f95]
|
|
303
|
+
- Updated dependencies [b706af9]
|
|
304
|
+
- Updated dependencies [add4360]
|
|
305
|
+
- Updated dependencies [cd13488]
|
|
306
|
+
- Updated dependencies [df1c75c]
|
|
307
|
+
- Updated dependencies [fc9ba76]
|
|
308
|
+
- Updated dependencies [0f94cc7]
|
|
309
|
+
- Updated dependencies [a11c1a5]
|
|
310
|
+
- Updated dependencies [71f9cd1]
|
|
311
|
+
- Updated dependencies [ee17d86]
|
|
312
|
+
- Updated dependencies [cdbd920]
|
|
313
|
+
- Updated dependencies [18c432e]
|
|
314
|
+
- Updated dependencies [3c418c4]
|
|
315
|
+
- Updated dependencies [fa8715a]
|
|
316
|
+
- Updated dependencies [a933ed7]
|
|
317
|
+
- Updated dependencies [b3ca463]
|
|
318
|
+
- Updated dependencies [a933ed7]
|
|
319
|
+
- Updated dependencies [0d4a6a8]
|
|
320
|
+
- Updated dependencies [518d5e5]
|
|
321
|
+
- Updated dependencies [6643ba1]
|
|
322
|
+
- Updated dependencies [eeba2ef]
|
|
323
|
+
- Updated dependencies [ec4c4d2]
|
|
324
|
+
- Updated dependencies [424f73c]
|
|
325
|
+
- Updated dependencies [cccbe51]
|
|
326
|
+
- Updated dependencies [a8d6b1d]
|
|
327
|
+
- Updated dependencies [e4a7695]
|
|
328
|
+
- Updated dependencies [87075b1]
|
|
329
|
+
- Updated dependencies [fc58a99]
|
|
330
|
+
- Updated dependencies [14cfc00]
|
|
331
|
+
- Updated dependencies [1c6f7b4]
|
|
332
|
+
- Updated dependencies [e854a53]
|
|
333
|
+
- Updated dependencies [07cced5]
|
|
334
|
+
- Updated dependencies [3956069]
|
|
335
|
+
- Updated dependencies [dfebfc8]
|
|
336
|
+
- Updated dependencies [5dd3bc9]
|
|
337
|
+
- Updated dependencies [9f4a6d5]
|
|
338
|
+
- Updated dependencies [4045b95]
|
|
339
|
+
- Updated dependencies [7adcd07]
|
|
340
|
+
- Updated dependencies [f5a7f9c]
|
|
341
|
+
- Updated dependencies [d028b37]
|
|
342
|
+
- Updated dependencies [c49afd0]
|
|
343
|
+
- Updated dependencies [f7b25c5]
|
|
344
|
+
- Updated dependencies [122ef38]
|
|
345
|
+
- Updated dependencies [4a37870]
|
|
346
|
+
- Updated dependencies [428f9b2]
|
|
347
|
+
- Updated dependencies [aa7ff56]
|
|
348
|
+
- Updated dependencies [c41b42e]
|
|
349
|
+
- Updated dependencies [c4db311]
|
|
350
|
+
- Updated dependencies [750fff5]
|
|
351
|
+
- Updated dependencies [c19035e]
|
|
352
|
+
- Updated dependencies [ececf7a]
|
|
353
|
+
- Updated dependencies [d173125]
|
|
354
|
+
- Updated dependencies [8eeca27]
|
|
355
|
+
- Updated dependencies [8425c17]
|
|
356
|
+
- Updated dependencies [a5ef1d8]
|
|
357
|
+
- Updated dependencies [772d5de]
|
|
358
|
+
- Updated dependencies [ce80ec2]
|
|
359
|
+
- Updated dependencies [f24c90d]
|
|
360
|
+
- Updated dependencies [b372318]
|
|
361
|
+
- Updated dependencies [97a2263]
|
|
362
|
+
- Updated dependencies [29d0676]
|
|
363
|
+
- Updated dependencies [0169d49]
|
|
364
|
+
- Updated dependencies [6bd3231]
|
|
365
|
+
- Updated dependencies [1246b4c]
|
|
366
|
+
- Updated dependencies [d2b5ba8]
|
|
367
|
+
- Updated dependencies [b799ac5]
|
|
368
|
+
- Updated dependencies [8f74307]
|
|
369
|
+
- Updated dependencies [d23dc08]
|
|
370
|
+
- Updated dependencies [644ad50]
|
|
371
|
+
- Updated dependencies [0da7cd2]
|
|
372
|
+
- Updated dependencies [28a5c3e]
|
|
373
|
+
- Updated dependencies [4bc18e5]
|
|
374
|
+
- @objectstack/spec@17.3.0
|
|
375
|
+
- @objectstack/core@17.3.0
|
|
376
|
+
- @objectstack/driver-sql@17.3.0
|
|
377
|
+
|
|
3
378
|
## 17.2.0
|
|
4
379
|
|
|
5
380
|
### Patch Changes
|
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 *\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaA,wBAAgD;;;ACWhD,yBAA8B;;;ACxB9B;AA0CA,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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/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.\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 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\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 */\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 */\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaA,wBAAgD;;;ACWhD,yBAA8B;;;ACxB9B;AA0CA,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;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;AAAA,MAC7D,QAAQ;AAAA,MAER;AACA,WAAK,oBAAoB;AAAA,IAC3B;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;;;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.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 *\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,wBAA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AAA,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.\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 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\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 */\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 */\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]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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.
|
|
3
|
+
"version": "17.3.0",
|
|
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,16 +26,16 @@
|
|
|
26
26
|
"knex": "^3.3.0",
|
|
27
27
|
"nanoid": "^6.0.1",
|
|
28
28
|
"sql.js": "^1.14.1",
|
|
29
|
-
"@objectstack/
|
|
30
|
-
"@objectstack/
|
|
31
|
-
"@objectstack/spec": "17.
|
|
29
|
+
"@objectstack/driver-sql": "17.3.0",
|
|
30
|
+
"@objectstack/core": "17.3.0",
|
|
31
|
+
"@objectstack/spec": "17.3.0"
|
|
32
32
|
},
|
|
33
33
|
"devDependencies": {
|
|
34
34
|
"@types/node": "^26.2.0",
|
|
35
35
|
"@types/sql.js": "^1.4.11",
|
|
36
36
|
"typescript": "^6.0.3",
|
|
37
37
|
"vitest": "^4.1.10",
|
|
38
|
-
"@objectstack/formula": "17.
|
|
38
|
+
"@objectstack/formula": "17.3.0"
|
|
39
39
|
},
|
|
40
40
|
"author": "ObjectStack",
|
|
41
41
|
"repository": {
|
|
@@ -57,7 +57,7 @@
|
|
|
57
57
|
"node": ">=22.0.0"
|
|
58
58
|
},
|
|
59
59
|
"scripts": {
|
|
60
|
-
"build": "tsup --config ../../../tsup.config.ts",
|
|
60
|
+
"build": "tsup --config ../../../tsup.config.ts && node ../../../scripts/check-dts-emitted.mjs",
|
|
61
61
|
"dev": "tsc -w",
|
|
62
62
|
"test": "vitest run",
|
|
63
63
|
"typecheck": "tsc --noEmit"
|