@hiroosy/baileys-lite 0.0.4 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +658 -10
  3. package/WAProto/index.js +2 -2558
  4. package/engine-requirements.js +3 -4
  5. package/package.json +8 -3
  6. package/src/binary/wa-binary.js +3 -25
  7. package/src/constants.js +7 -15
  8. package/src/defaults.js +2 -5
  9. package/src/foundation/ai-rich.js +530 -0
  10. package/src/foundation/audio-duration.js +43 -103
  11. package/src/foundation/audio-samples.js +19 -37
  12. package/src/foundation/boom.js +0 -7
  13. package/src/foundation/cache.js +4 -26
  14. package/src/foundation/concurrency.js +1 -19
  15. package/src/foundation/curve25519.js +7 -39
  16. package/src/foundation/link-preview.js +15 -57
  17. package/src/foundation/logger.js +0 -11
  18. package/src/foundation/long.js +4 -14
  19. package/src/foundation/protobuf-minimal.js +21 -53
  20. package/src/foundation/qrcode-terminal.js +273 -0
  21. package/src/foundation/sql-database.js +716 -0
  22. package/src/foundation/wa-crypto.js +2 -31
  23. package/src/foundation/zip.js +25 -41
  24. package/src/index.js +8 -18
  25. package/src/signal/libsignal.js +23 -78
  26. package/src/signal/signal-group.js +0 -35
  27. package/src/signal/signal-repository.js +10 -29
  28. package/src/socket/business-communities.js +12 -31
  29. package/src/socket/chats.js +5 -8
  30. package/src/socket/groups-newsletter.js +18 -17
  31. package/src/socket/messages-recv.js +81 -127
  32. package/src/socket/messages-send.js +372 -139
  33. package/src/socket/socket-core.js +227 -157
  34. package/src/socket/usync.js +2 -6
  35. package/src/socket-client/native-websocket.js +344 -0
  36. package/src/socket-client/websocket-client.js +84 -38
  37. package/src/utils/auth-state-core.js +14 -56
  38. package/src/utils/auth-state-storage.js +7 -42
  39. package/src/utils/chat-sync.js +4 -26
  40. package/src/utils/media.js +15 -71
  41. package/src/utils/message-compose.js +208 -85
  42. package/src/utils/message-processing.js +10 -65
  43. package/src/utils/username.js +19 -0
  44. package/src/utils/wa-protocol-core.js +71 -127
  45. package/src/vendor/jpeg-js/decoder.js +75 -136
  46. package/src/vendor/jpeg-js/encoder.js +179 -264
  47. package/src/vendor/pngjs/bitmapper.js +5 -27
  48. package/src/vendor/pngjs/bitpacker.js +4 -12
  49. package/src/vendor/pngjs/constants.js +3 -11
  50. package/src/vendor/pngjs/crc.js +0 -6
  51. package/src/vendor/pngjs/filter-pack.js +1 -7
  52. package/src/vendor/pngjs/filter-parse-sync.js +0 -6
  53. package/src/vendor/pngjs/filter-parse.js +1 -11
  54. package/src/vendor/pngjs/format-normaliser.js +5 -11
  55. package/src/vendor/pngjs/interlace.js +7 -24
  56. package/src/vendor/pngjs/packer-sync.js +0 -11
  57. package/src/vendor/pngjs/packer.js +7 -15
  58. package/src/vendor/pngjs/paeth-predictor.js +0 -6
  59. package/src/vendor/pngjs/parser-sync.js +0 -8
  60. package/src/vendor/pngjs/parser.js +5 -29
  61. package/src/vendor/pngjs/png-sync.js +0 -7
  62. package/src/vendor/pngjs/sync-inflate.js +7 -16
  63. package/src/vendor/pngjs/sync-reader.js +4 -11
  64. package/src/voip/WaVoipCoordinator.js +158 -0
  65. package/src/voip/app-data/WaAppDataStream.js +193 -0
  66. package/src/voip/app-data/protocol.js +172 -0
  67. package/src/voip/bytes.js +63 -0
  68. package/src/voip/call/WaCallManager.js +442 -0
  69. package/src/voip/call/WaCallMediaSession.js +1705 -0
  70. package/src/voip/call/call-state.js +203 -0
  71. package/src/voip/crypto/encryption.js +13 -0
  72. package/src/voip/crypto/primitives.js +21 -0
  73. package/src/voip/crypto/rtcp.js +66 -0
  74. package/src/voip/crypto/srtp.js +180 -0
  75. package/src/voip/crypto/ssrc.js +15 -0
  76. package/src/voip/index.js +628 -0
  77. package/src/voip/media/WaAudioEngine.js +486 -0
  78. package/src/voip/media/WaVideoEngine.js +275 -0
  79. package/src/voip/media/audio-codec.js +0 -0
  80. package/src/voip/media/audio-reorder.js +107 -0
  81. package/src/voip/media/h264.js +246 -0
  82. package/src/voip/media/mlow-codec.js +465 -0
  83. package/src/voip/media/rtcp.js +68 -0
  84. package/src/voip/media/rtp.js +242 -0
  85. package/src/voip/protobuf.js +30 -0
  86. package/src/voip/relay/WaManualRelay.js +609 -0
  87. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  88. package/src/voip/relay/dtls/aead.js +46 -0
  89. package/src/voip/relay/dtls/cert-builder.js +102 -0
  90. package/src/voip/relay/dtls/der.js +98 -0
  91. package/src/voip/relay/dtls/ecdhe.js +37 -0
  92. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  93. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  94. package/src/voip/relay/dtls/handshake.js +582 -0
  95. package/src/voip/relay/dtls/prf.js +39 -0
  96. package/src/voip/relay/dtls/record.js +56 -0
  97. package/src/voip/relay/relay-ack.js +141 -0
  98. package/src/voip/relay/sctp/association.js +434 -0
  99. package/src/voip/relay/sctp/crc32c.js +21 -0
  100. package/src/voip/relay/sctp/wire.js +226 -0
  101. package/src/voip/relay/stun.js +463 -0
  102. package/src/voip/shim/baileys-resolve.js +7 -0
  103. package/src/voip/shim/core.js +66 -0
  104. package/src/voip/shim/crypto.js +6 -0
  105. package/src/voip/shim/proto.js +10 -0
  106. package/src/voip/shim/protocol.js +130 -0
  107. package/src/voip/shim/transport.js +82 -0
  108. package/src/voip/shim/util.js +207 -0
  109. package/src/voip/signaling/bridge.js +102 -0
  110. package/src/voip/signaling/screen-share.js +60 -0
  111. package/src/voip/signaling/signaling.js +491 -0
  112. package/src/voip/types.js +69 -0
  113. package/src/voip/voip-deps.js +243 -0
  114. package/src/voip/voipClient.js +314 -0
  115. package/src/wam/wam-constants.js +0 -1
  116. package/src/wam/wam.js +2 -7
@@ -0,0 +1,716 @@
1
+ import { appendFileSync, existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
2
+
3
+ const MAGIC = '{"nsql":1}'
4
+ const COMPACT_MIN_BYTES = 256 * 1024
5
+ const COMPACT_GROWTH_RATIO = 0.5
6
+ const CONTROL = new Set(['begin', 'commit', 'rollback'])
7
+ const TOKEN = /\s+|'((?:[^']|'')*)'|"([^"]*)"|`([^`]*)`|\[([^\]]*)\]|(\d+\.?\d*(?:[eE][+-]?\d+)?|\.\d+(?:[eE][+-]?\d+)?)|([A-Za-z_]\w*)|([(),;=?*.-])/y
8
+
9
+ class SqlError extends Error {
10
+ constructor(message) {
11
+ super(message)
12
+ this.name = 'SqlError'
13
+ }
14
+ }
15
+
16
+ const lower = name => name.toLowerCase()
17
+
18
+ const keyOf = (table, row) => JSON.stringify(table.pk.map(i => row[i]))
19
+
20
+ const sameRow = (a, b) => a.length === b.length && a.every((v, i) => v === b[i])
21
+
22
+ const bind = (count, params) => {
23
+ if (params.length !== count) throw new SqlError(`expected ${count} parameters, got ${params.length}`)
24
+ return params.map(value => {
25
+ if (value === null || typeof value === 'string') return value
26
+ if (typeof value === 'boolean') return Number(value)
27
+ if (typeof value === 'number' && Number.isFinite(value)) return value
28
+ throw new SqlError(`unsupported parameter type: ${typeof value}`)
29
+ })
30
+ }
31
+
32
+ const tokenize = sql => {
33
+ const tokens = []
34
+ TOKEN.lastIndex = 0
35
+ while (TOKEN.lastIndex < sql.length) {
36
+ const at = TOKEN.lastIndex
37
+ const m = TOKEN.exec(sql)
38
+ if (!m) throw new SqlError(`unexpected character at offset ${at}`)
39
+ const end = TOKEN.lastIndex
40
+ let token = null
41
+ if (m[1] !== undefined) token = { k: 'str', v: m[1].replace(/''/g, "'") }
42
+ else if (m[5] !== undefined) token = { k: 'num', v: Number(m[5]) }
43
+ else if (m[6] !== undefined) token = { k: 'id', v: m[6] }
44
+ else if (m[7] !== undefined) token = { k: 'p', v: m[7] }
45
+ else if (m[2] !== undefined || m[3] !== undefined || m[4] !== undefined) token = { k: 'id', v: m[2] ?? m[3] ?? m[4] }
46
+ if (token) tokens.push({ ...token, at, end })
47
+ }
48
+ tokens.push({ k: 'eof', at: sql.length, end: sql.length })
49
+ return tokens
50
+ }
51
+
52
+ class Parser {
53
+ constructor(tokens) {
54
+ this.tokens = tokens
55
+ this.pos = 0
56
+ this.params = 0
57
+ }
58
+
59
+ peek() {
60
+ return this.tokens[this.pos]
61
+ }
62
+
63
+ next() {
64
+ return this.tokens[this.pos++]
65
+ }
66
+
67
+ isKw(word) {
68
+ const t = this.peek()
69
+ return t.k === 'id' && t.v.toUpperCase() === word
70
+ }
71
+
72
+ eatKw(word) {
73
+ if (!this.isKw(word)) return false
74
+ this.pos++
75
+ return true
76
+ }
77
+
78
+ expectKw(word) {
79
+ if (!this.eatKw(word)) throw new SqlError(`expected ${word}`)
80
+ }
81
+
82
+ isP(ch) {
83
+ const t = this.peek()
84
+ return t.k === 'p' && t.v === ch
85
+ }
86
+
87
+ eatP(ch) {
88
+ if (!this.isP(ch)) return false
89
+ this.pos++
90
+ return true
91
+ }
92
+
93
+ expectP(ch) {
94
+ if (!this.eatP(ch)) throw new SqlError(`expected '${ch}'`)
95
+ }
96
+
97
+ ident() {
98
+ const t = this.next()
99
+ if (t.k !== 'id') throw new SqlError('expected identifier')
100
+ return t.v
101
+ }
102
+
103
+ identList() {
104
+ this.expectP('(')
105
+ const names = [this.ident()]
106
+ while (this.eatP(',')) names.push(this.ident())
107
+ this.expectP(')')
108
+ return names
109
+ }
110
+
111
+ operand() {
112
+ const t = this.next()
113
+ if (t.k === 'str' || t.k === 'num') return { kind: 'lit', value: t.v }
114
+ if (t.k === 'p' && t.v === '?') return { kind: 'param', index: this.params++ }
115
+ if (t.k === 'p' && t.v === '-' && this.peek().k === 'num') return { kind: 'lit', value: -this.next().v }
116
+ if (t.k === 'id' && t.v.toUpperCase() === 'NULL') return { kind: 'lit', value: null }
117
+ if (t.k === 'id' && t.v.toUpperCase() === 'EXCLUDED' && this.eatP('.')) return { kind: 'excluded', column: this.ident() }
118
+ throw new SqlError('unsupported expression')
119
+ }
120
+
121
+ statement() {
122
+ const t = this.peek()
123
+ const word = t.k === 'id' ? t.v.toUpperCase() : ''
124
+ switch (word) {
125
+ case 'CREATE':
126
+ return this.create()
127
+ case 'INSERT':
128
+ return this.insert()
129
+ case 'SELECT':
130
+ return this.select()
131
+ case 'DELETE':
132
+ return this.remove()
133
+ case 'PRAGMA':
134
+ return this.skip()
135
+ case 'BEGIN':
136
+ return this.control('begin')
137
+ case 'COMMIT':
138
+ case 'END':
139
+ return this.control('commit')
140
+ case 'ROLLBACK':
141
+ return this.control('rollback')
142
+ default:
143
+ throw new SqlError(`unsupported statement${word ? ` ${word}` : ''}`)
144
+ }
145
+ }
146
+
147
+ control(type) {
148
+ this.next()
149
+ this.eatKw('TRANSACTION')
150
+ return { type, write: false }
151
+ }
152
+
153
+ skip() {
154
+ this.next()
155
+ while (!this.isP(';') && this.peek().k !== 'eof') this.next()
156
+ return { type: 'noop', write: false }
157
+ }
158
+
159
+ create() {
160
+ this.next()
161
+ if (this.isKw('UNIQUE')) throw new SqlError('unique indexes are not supported')
162
+ if (this.eatKw('TABLE')) return this.createTable()
163
+ if (this.eatKw('INDEX')) return this.createIndex()
164
+ throw new SqlError('unsupported CREATE statement')
165
+ }
166
+
167
+ ifNotExists() {
168
+ if (!this.eatKw('IF')) return false
169
+ this.expectKw('NOT')
170
+ this.expectKw('EXISTS')
171
+ return true
172
+ }
173
+
174
+ createTable() {
175
+ const ifNotExists = this.ifNotExists()
176
+ const name = this.ident()
177
+ this.expectP('(')
178
+ const columns = []
179
+ let primaryKey = null
180
+ do {
181
+ if (this.eatKw('PRIMARY')) {
182
+ this.expectKw('KEY')
183
+ primaryKey = this.identList()
184
+ } else {
185
+ columns.push(this.columnDef())
186
+ }
187
+ } while (this.eatP(','))
188
+ this.expectP(')')
189
+ const key = primaryKey ?? columns.filter(c => c.primary).map(c => c.name)
190
+ if (!key.length) throw new SqlError(`table ${name} needs a PRIMARY KEY`)
191
+ return { type: 'create_table', name, ifNotExists, columns, primaryKey: key, write: true }
192
+ }
193
+
194
+ columnDef() {
195
+ const column = { name: this.ident(), notNull: false, primary: false }
196
+ if (this.peek().k === 'id' && !this.isKw('NOT') && !this.isKw('PRIMARY')) this.next()
197
+ for (;;) {
198
+ if (this.eatKw('NOT')) {
199
+ this.expectKw('NULL')
200
+ column.notNull = true
201
+ } else if (this.eatKw('PRIMARY')) {
202
+ this.expectKw('KEY')
203
+ column.primary = true
204
+ } else {
205
+ return column
206
+ }
207
+ }
208
+ }
209
+
210
+ createIndex() {
211
+ const ifNotExists = this.ifNotExists()
212
+ const name = this.ident()
213
+ this.expectKw('ON')
214
+ const table = this.ident()
215
+ const columns = this.identList()
216
+ return { type: 'create_index', name, table, columns, ifNotExists, write: true }
217
+ }
218
+
219
+ insert() {
220
+ this.next()
221
+ let replace = false
222
+ if (this.eatKw('OR')) {
223
+ this.expectKw('REPLACE')
224
+ replace = true
225
+ }
226
+ this.expectKw('INTO')
227
+ const table = this.ident()
228
+ const columns = this.isP('(') ? this.identList() : null
229
+ this.expectKw('VALUES')
230
+ this.expectP('(')
231
+ const values = [this.operand()]
232
+ while (this.eatP(',')) values.push(this.operand())
233
+ this.expectP(')')
234
+ let onConflict = null
235
+ if (this.eatKw('ON')) {
236
+ this.expectKw('CONFLICT')
237
+ const target = this.identList()
238
+ this.expectKw('DO')
239
+ if (this.eatKw('NOTHING')) {
240
+ onConflict = { target, action: 'nothing' }
241
+ } else {
242
+ this.expectKw('UPDATE')
243
+ this.expectKw('SET')
244
+ const sets = []
245
+ do {
246
+ const column = this.ident()
247
+ this.expectP('=')
248
+ sets.push({ column, operand: this.operand() })
249
+ } while (this.eatP(','))
250
+ onConflict = { target, action: 'update', sets }
251
+ }
252
+ }
253
+ return { type: 'insert', table, columns, values, replace, onConflict, write: true }
254
+ }
255
+
256
+ select() {
257
+ this.next()
258
+ let columns = '*'
259
+ if (!this.eatP('*')) {
260
+ columns = [this.ident()]
261
+ while (this.eatP(',')) columns.push(this.ident())
262
+ }
263
+ this.expectKw('FROM')
264
+ const table = this.ident()
265
+ return { type: 'select', table, columns, where: this.where(), write: false }
266
+ }
267
+
268
+ remove() {
269
+ this.next()
270
+ this.expectKw('FROM')
271
+ const table = this.ident()
272
+ return { type: 'delete', table, where: this.where(), write: true }
273
+ }
274
+
275
+ where() {
276
+ const conditions = []
277
+ if (!this.eatKw('WHERE')) return conditions
278
+ do {
279
+ const column = this.ident()
280
+ this.expectP('=')
281
+ conditions.push({ column, operand: this.operand() })
282
+ } while (this.eatKw('AND'))
283
+ return conditions
284
+ }
285
+ }
286
+
287
+ const parseStatements = sql => {
288
+ const parser = new Parser(tokenize(sql))
289
+ const statements = []
290
+ while (parser.peek().k !== 'eof') {
291
+ if (parser.eatP(';')) continue
292
+ const start = parser.peek().at
293
+ parser.params = 0
294
+ const stmt = parser.statement()
295
+ const end = parser.tokens[parser.pos - 1].end
296
+ if (!parser.eatP(';') && parser.peek().k !== 'eof') throw new SqlError('expected ;')
297
+ stmt.text = sql.slice(start, end)
298
+ stmt.paramCount = parser.params
299
+ statements.push(stmt)
300
+ }
301
+ return statements
302
+ }
303
+
304
+ export class SqlDatabase {
305
+ #tables = new Map()
306
+ #indexes = new Map()
307
+ #undo = []
308
+ #pending = []
309
+ #inTxn = false
310
+ #path = null
311
+ #logBytes = 0
312
+ #baseBytes = 0
313
+ #closed = false
314
+
315
+ constructor(path = ':memory:') {
316
+ if (path !== ':memory:') this.#open(path)
317
+ }
318
+
319
+ exec(sql) {
320
+ this.#assertOpen()
321
+ for (const stmt of parseStatements(sql)) this.#invoke(stmt, [])
322
+ }
323
+
324
+ prepare(sql) {
325
+ this.#assertOpen()
326
+ const statements = parseStatements(sql)
327
+ if (statements.length !== 1) throw new SqlError('prepare expects exactly one statement')
328
+ const [stmt] = statements
329
+ return {
330
+ run: (...params) => ({ changes: this.#invoke(stmt, params).changes }),
331
+ get: (...params) => this.#invoke(stmt, params).rows[0],
332
+ all: (...params) => this.#invoke(stmt, params).rows
333
+ }
334
+ }
335
+
336
+ transaction(fn) {
337
+ return (...args) => {
338
+ this.#assertOpen()
339
+ if (this.#inTxn) return fn(...args)
340
+ this.#control('begin')
341
+ try {
342
+ const result = fn(...args)
343
+ this.#commit()
344
+ return result
345
+ } catch (err) {
346
+ this.#rollback()
347
+ throw err
348
+ }
349
+ }
350
+ }
351
+
352
+ close() {
353
+ this.#rollback()
354
+ this.#closed = true
355
+ }
356
+
357
+ #assertOpen() {
358
+ if (this.#closed) throw new SqlError('database is closed')
359
+ }
360
+
361
+ #invoke(stmt, params) {
362
+ this.#assertOpen()
363
+ if (CONTROL.has(stmt.type)) return this.#control(stmt.type)
364
+ const values = bind(stmt.paramCount, params)
365
+ return this.#statement(() => {
366
+ const result = this.#execute(stmt, values)
367
+ if (stmt.write && result.changes && !result.noop) this.#pending.push([stmt.text, values])
368
+ return result
369
+ })
370
+ }
371
+
372
+ #control(type) {
373
+ if (type === 'begin') {
374
+ if (this.#inTxn) throw new SqlError('cannot start a transaction within a transaction')
375
+ this.#inTxn = true
376
+ } else if (!this.#inTxn) {
377
+ throw new SqlError('no transaction is active')
378
+ } else if (type === 'commit') {
379
+ this.#commit()
380
+ } else {
381
+ this.#rollback()
382
+ }
383
+ return { changes: 0, rows: [] }
384
+ }
385
+
386
+ #statement(fn) {
387
+ const auto = !this.#inTxn
388
+ if (auto) this.#inTxn = true
389
+ const mark = this.#undo.length
390
+ const pmark = this.#pending.length
391
+ let result
392
+ try {
393
+ result = fn()
394
+ } catch (err) {
395
+ this.#undoTo(mark)
396
+ this.#pending.length = pmark
397
+ if (auto) this.#end()
398
+ throw err
399
+ }
400
+ if (auto) this.#commit()
401
+ return result
402
+ }
403
+
404
+ #commit() {
405
+ try {
406
+ if (this.#path !== null && this.#pending.length) this.#append(this.#pending)
407
+ } catch (err) {
408
+ this.#rollback()
409
+ throw err
410
+ }
411
+ this.#end()
412
+ this.#maybeCompact()
413
+ }
414
+
415
+ #rollback() {
416
+ this.#undoTo(0)
417
+ this.#end()
418
+ }
419
+
420
+ #undoTo(mark) {
421
+ while (this.#undo.length > mark) this.#undo.pop()()
422
+ }
423
+
424
+ #end() {
425
+ this.#undo = []
426
+ this.#pending = []
427
+ this.#inTxn = false
428
+ }
429
+
430
+ #execute(stmt, params) {
431
+ switch (stmt.type) {
432
+ case 'create_table':
433
+ return this.#createTable(stmt)
434
+ case 'create_index':
435
+ return this.#createIndex(stmt)
436
+ case 'insert':
437
+ return this.#insert(stmt, params)
438
+ case 'delete':
439
+ return this.#deleteRows(stmt, params)
440
+ case 'select':
441
+ return this.#selectRows(stmt, params)
442
+ default:
443
+ return { changes: 0, rows: [] }
444
+ }
445
+ }
446
+
447
+ #table(name) {
448
+ const table = this.#tables.get(lower(name))
449
+ if (!table) throw new SqlError(`no such table: ${name}`)
450
+ return table
451
+ }
452
+
453
+ #column(table, name) {
454
+ const i = table.colIndex.get(lower(name))
455
+ if (i === undefined) throw new SqlError(`no such column: ${name}`)
456
+ return i
457
+ }
458
+
459
+ #isPrimaryKey(table, names) {
460
+ const cols = names.map(n => this.#column(table, n))
461
+ return cols.length === table.pk.length && cols.every(i => table.pk.includes(i))
462
+ }
463
+
464
+ #value(operand, params) {
465
+ if (operand.kind === 'param') return params[operand.index]
466
+ if (operand.kind === 'lit') return operand.value
467
+ throw new SqlError('excluded is only valid in ON CONFLICT ... DO UPDATE SET')
468
+ }
469
+
470
+ #checkNotNull(table, row) {
471
+ table.columns.forEach((c, i) => {
472
+ if (c.notNull && row[i] === null) throw new SqlError(`NOT NULL constraint failed: ${table.name}.${c.name}`)
473
+ })
474
+ }
475
+
476
+ #createTable(stmt) {
477
+ const key = lower(stmt.name)
478
+ if (this.#tables.has(key)) {
479
+ if (stmt.ifNotExists) return { changes: 0, rows: [] }
480
+ throw new SqlError(`table ${stmt.name} already exists`)
481
+ }
482
+ const pkNames = stmt.primaryKey.map(lower)
483
+ const columns = stmt.columns.map(c => ({ name: c.name, notNull: c.notNull || pkNames.includes(lower(c.name)) }))
484
+ const colIndex = new Map(columns.map((c, i) => [lower(c.name), i]))
485
+ const pk = stmt.primaryKey.map(name => {
486
+ const i = colIndex.get(lower(name))
487
+ if (i === undefined) throw new SqlError(`no such column: ${name}`)
488
+ return i
489
+ })
490
+ const table = { name: stmt.name, sql: stmt.text, columns, colIndex, pk, rows: new Map(), indexes: [] }
491
+ this.#tables.set(key, table)
492
+ this.#undo.push(() => this.#tables.delete(key))
493
+ return { changes: 1, rows: [] }
494
+ }
495
+
496
+ #createIndex(stmt) {
497
+ const key = lower(stmt.name)
498
+ if (this.#indexes.has(key)) {
499
+ if (stmt.ifNotExists) return { changes: 0, rows: [] }
500
+ throw new SqlError(`index ${stmt.name} already exists`)
501
+ }
502
+ const table = this.#table(stmt.table)
503
+ const index = {
504
+ name: stmt.name,
505
+ sql: stmt.text,
506
+ columns: stmt.columns.map(c => this.#column(table, c)),
507
+ entries: new Map()
508
+ }
509
+ for (const [rowKey, row] of table.rows) this.#addEntry(index, rowKey, row)
510
+ table.indexes.push(index)
511
+ this.#indexes.set(key, index)
512
+ this.#undo.push(() => {
513
+ table.indexes.splice(table.indexes.indexOf(index), 1)
514
+ this.#indexes.delete(key)
515
+ })
516
+ return { changes: 1, rows: [] }
517
+ }
518
+
519
+ #insert(stmt, params) {
520
+ const table = this.#table(stmt.table)
521
+ const names = stmt.columns ?? table.columns.map(c => c.name)
522
+ if (names.length !== stmt.values.length) throw new SqlError(`${names.length} columns but ${stmt.values.length} values supplied`)
523
+ if (stmt.onConflict && !this.#isPrimaryKey(table, stmt.onConflict.target)) throw new SqlError('ON CONFLICT target must be the primary key')
524
+ const row = table.columns.map(() => null)
525
+ names.forEach((name, i) => {
526
+ row[this.#column(table, name)] = this.#value(stmt.values[i], params)
527
+ })
528
+ this.#checkNotNull(table, row)
529
+ const rowKey = keyOf(table, row)
530
+ const existing = table.rows.get(rowKey)
531
+ if (!existing) {
532
+ this.#storeRow(table, rowKey, row)
533
+ return { changes: 1, rows: [] }
534
+ }
535
+ const action = stmt.onConflict?.action
536
+ if (action === 'nothing') return { changes: 0, rows: [] }
537
+ if (action === 'update') return this.#upsertConflict(table, rowKey, existing, stmt.onConflict.sets, row, params)
538
+ if (stmt.replace) {
539
+ if (sameRow(existing, row)) return { changes: 1, rows: [], noop: true }
540
+ this.#storeRow(table, rowKey, row)
541
+ return { changes: 1, rows: [] }
542
+ }
543
+ throw new SqlError(`UNIQUE constraint failed: ${table.pk.map(i => `${table.name}.${table.columns[i].name}`).join(', ')}`)
544
+ }
545
+
546
+ #upsertConflict(table, rowKey, existing, sets, incoming, params) {
547
+ const next = existing.slice()
548
+ for (const { column, operand } of sets) {
549
+ next[this.#column(table, column)] = operand.kind === 'excluded'
550
+ ? incoming[this.#column(table, operand.column)]
551
+ : this.#value(operand, params)
552
+ }
553
+ if (table.pk.some(i => next[i] !== existing[i])) throw new SqlError('primary key cannot be changed on conflict')
554
+ this.#checkNotNull(table, next)
555
+ // rewriting identical data (e.g. saveCreds with unchanged creds) must not grow the log
556
+ if (sameRow(existing, next)) return { changes: 1, rows: [], noop: true }
557
+ this.#storeRow(table, rowKey, next)
558
+ return { changes: 1, rows: [] }
559
+ }
560
+
561
+ #deleteRows(stmt, params) {
562
+ const table = this.#table(stmt.table)
563
+ let changes = 0
564
+ for (const row of this.#match(table, stmt.where, params)) {
565
+ if (this.#removeRow(table, keyOf(table, row))) changes++
566
+ }
567
+ return { changes, rows: [] }
568
+ }
569
+
570
+ #selectRows(stmt, params) {
571
+ const table = this.#table(stmt.table)
572
+ const names = stmt.columns === '*' ? table.columns.map(c => c.name) : stmt.columns
573
+ const picks = names.map(n => this.#column(table, n))
574
+ const rows = this.#match(table, stmt.where, params).map(row => Object.fromEntries(names.map((n, i) => [n, row[picks[i]]])))
575
+ return { changes: 0, rows }
576
+ }
577
+
578
+ #match(table, where, params) {
579
+ const bound = where.map(({ column, operand }) => ({ index: this.#column(table, column), value: this.#value(operand, params) }))
580
+ const wanted = new Map(bound.map(({ index, value }) => [index, value]))
581
+ return this.#candidates(table, wanted).filter(row => bound.every(({ index, value }) => value !== null && row[index] === value))
582
+ }
583
+
584
+ #candidates(table, wanted) {
585
+ if (table.pk.every(i => wanted.has(i))) {
586
+ const row = table.rows.get(JSON.stringify(table.pk.map(i => wanted.get(i))))
587
+ return row ? [row] : []
588
+ }
589
+ for (const index of table.indexes) {
590
+ if (index.columns.every(i => wanted.has(i))) {
591
+ const keys = index.entries.get(JSON.stringify(index.columns.map(i => wanted.get(i))))
592
+ return keys ? [...keys].map(k => table.rows.get(k)) : []
593
+ }
594
+ }
595
+ return [...table.rows.values()]
596
+ }
597
+
598
+ #addEntry(index, rowKey, row) {
599
+ const k = JSON.stringify(index.columns.map(i => row[i]))
600
+ let set = index.entries.get(k)
601
+ if (!set) {
602
+ set = new Set()
603
+ index.entries.set(k, set)
604
+ }
605
+ set.add(rowKey)
606
+ }
607
+
608
+ #removeEntry(index, rowKey, row) {
609
+ const k = JSON.stringify(index.columns.map(i => row[i]))
610
+ const set = index.entries.get(k)
611
+ if (!set) return
612
+ set.delete(rowKey)
613
+ if (!set.size) index.entries.delete(k)
614
+ }
615
+
616
+ #indexRow(table, rowKey, row) {
617
+ for (const index of table.indexes) this.#addEntry(index, rowKey, row)
618
+ }
619
+
620
+ #unindexRow(table, rowKey, row) {
621
+ for (const index of table.indexes) this.#removeEntry(index, rowKey, row)
622
+ }
623
+
624
+ #storeRow(table, rowKey, row) {
625
+ const prev = table.rows.get(rowKey)
626
+ if (prev) this.#unindexRow(table, rowKey, prev)
627
+ table.rows.set(rowKey, row)
628
+ this.#indexRow(table, rowKey, row)
629
+ this.#undo.push(() => this.#restoreRow(table, rowKey, prev))
630
+ }
631
+
632
+ #removeRow(table, rowKey) {
633
+ const prev = table.rows.get(rowKey)
634
+ if (!prev) return false
635
+ this.#unindexRow(table, rowKey, prev)
636
+ table.rows.delete(rowKey)
637
+ this.#undo.push(() => this.#restoreRow(table, rowKey, prev))
638
+ return true
639
+ }
640
+
641
+ #restoreRow(table, rowKey, prev) {
642
+ const current = table.rows.get(rowKey)
643
+ if (current) this.#unindexRow(table, rowKey, current)
644
+ if (prev) {
645
+ table.rows.set(rowKey, prev)
646
+ this.#indexRow(table, rowKey, prev)
647
+ } else {
648
+ table.rows.delete(rowKey)
649
+ }
650
+ }
651
+
652
+ #open(path) {
653
+ let text = existsSync(path) ? readFileSync(path, 'utf8') : ''
654
+ const fresh = text === ''
655
+ if (fresh) text = `${MAGIC}\n`
656
+ const lines = text.split('\n')
657
+ const tail = lines.pop()
658
+ if (lines[0] !== MAGIC) throw new SqlError(`${path} is not a native sql database file`)
659
+ for (const line of lines.slice(1)) this.#replay(line)
660
+ this.#path = path
661
+ this.#logBytes = this.#baseBytes = Buffer.byteLength(text)
662
+ if (fresh) {
663
+ writeFileSync(path, text)
664
+ } else if (tail !== '' || lines.length > 2) {
665
+ // torn write, or the log holds more than a single snapshot line: rewrite as a clean
666
+ // snapshot so baseBytes reflects live data and old bloated files shrink on first open
667
+ this.#compact()
668
+ }
669
+ }
670
+
671
+ #replay(line) {
672
+ if (line === '') return
673
+ let entries
674
+ try {
675
+ entries = JSON.parse(line)
676
+ } catch {
677
+ throw new SqlError('corrupted sql log entry')
678
+ }
679
+ for (const [sql, params] of entries) {
680
+ const [stmt] = parseStatements(sql)
681
+ this.#invoke(stmt, params)
682
+ }
683
+ }
684
+
685
+ #append(entries) {
686
+ const line = `${JSON.stringify(entries)}\n`
687
+ appendFileSync(this.#path, line)
688
+ this.#logBytes += Buffer.byteLength(line)
689
+ }
690
+
691
+ #maybeCompact() {
692
+ if (this.#path === null) return
693
+ // baseBytes is always the size of a clean snapshot, so garbage = logBytes - baseBytes
694
+ const garbage = this.#logBytes - this.#baseBytes
695
+ if (garbage < Math.max(COMPACT_MIN_BYTES, this.#baseBytes * COMPACT_GROWTH_RATIO)) return
696
+ try {
697
+ this.#compact()
698
+ } catch {}
699
+ }
700
+
701
+ #compact() {
702
+ const entries = []
703
+ for (const table of this.#tables.values()) entries.push([table.sql, []])
704
+ for (const index of this.#indexes.values()) entries.push([index.sql, []])
705
+ for (const table of this.#tables.values()) {
706
+ const names = table.columns.map(c => `"${c.name}"`).join(', ')
707
+ const sql = `INSERT INTO "${table.name}" (${names}) VALUES (${table.columns.map(() => '?').join(', ')})`
708
+ for (const row of table.rows.values()) entries.push([sql, row])
709
+ }
710
+ const text = `${MAGIC}\n${JSON.stringify(entries)}\n`
711
+ const tmp = `${this.#path}.tmp`
712
+ writeFileSync(tmp, text)
713
+ renameSync(tmp, this.#path)
714
+ this.#logBytes = this.#baseBytes = Buffer.byteLength(text)
715
+ }
716
+ }