Open History to see the last commit
1import { dirname, join } from 'node:path'
2import { execFile } from 'node:child_process'
3import { promisify } from 'node:util'
4import { AsyncLocalStorage } from 'node:async_hooks'
5import { copyFileSync, existsSync, mkdtempSync, rmSync } from 'node:fs'
6import { tmpdir } from 'node:os'
7import { fileURLToPath } from 'node:url'
8import { serialize } from 'node:v8'
9import { BrowserWindow, app, ipcMain } from 'electron'
10import { createSQLiteCorePersistenceAdapter } from '@tanstack/db-sqlite-persistence-core'
11import { exposeElectronSQLitePersistence } from '../../../dist/esm/main.js'
12
13const E2E_RESULT_PREFIX = `__TANSTACK_DB_E2E_RESULT__:`
14const E2E_RESULT_BASE64_PREFIX = `__TANSTACK_DB_E2E_RESULT_BASE64__:`
15const E2E_INPUT_ENV_VAR = `TANSTACK_DB_E2E_INPUT`
16const E2E_TRANSPORT_TYPE_TAG = `__tanstack_db_e2e_transport_type__`
17const E2E_TRANSPORT_VALUE_TAG = `value`
18const execFileAsync = promisify(execFile)
19
20function toSqlLiteral(value) {
21 if (value === null || value === undefined) {
22 return `NULL`
23 }
24
25 if (typeof value === `number`) {
26 return Number.isFinite(value) ? String(value) : `NULL`
27 }
28
29 if (typeof value === `boolean`) {
30 return value ? `1` : `0`
31 }
32
33 if (typeof value === `bigint`) {
34 return value.toString()
35 }
36
37 const textValue = typeof value === `string` ? value : String(value)
38 return `'${textValue.replace(/'/g, `''`)}'`
39}
40
41function interpolateSql(sql, params) {
42 let parameterIndex = 0
43 const renderedSql = sql.replace(/\?/g, () => {
44 const currentParam = params[parameterIndex]
45 parameterIndex++
46 return toSqlLiteral(currentParam)
47 })
48
49 if (parameterIndex !== params.length) {
50 throw new Error(
51 `SQL interpolation mismatch: used ${parameterIndex} params, received ${params.length}`,
52 )
53 }
54
55 return renderedSql
56}
57
58class SqliteCliDriver {
59 transactionDbPath = new AsyncLocalStorage()
60 queue = Promise.resolve()
61
62 constructor(dbPath) {
63 this.dbPath = dbPath
64 }
65
66 async exec(sql) {
67 const activeDbPath = this.transactionDbPath.getStore()
68 if (activeDbPath) {
69 await execFileAsync(`sqlite3`, [activeDbPath, sql])
70 return
71 }
72
73 await this.enqueue(async () => {
74 await execFileAsync(`sqlite3`, [this.dbPath, sql])
75 })
76 }
77
78 async query(sql, params = []) {
79 const activeDbPath = this.transactionDbPath.getStore()
80 const renderedSql = interpolateSql(sql, params)
81 const queryDbPath = activeDbPath ?? this.dbPath
82
83 const runQuery = async () => {
84 const { stdout } = await execFileAsync(`sqlite3`, [
85 `-json`,
86 queryDbPath,
87 renderedSql,
88 ])
89 const trimmedOutput = stdout.trim()
90 if (!trimmedOutput) {
91 return []
92 }
93
94 return JSON.parse(trimmedOutput)
95 }
96
97 if (activeDbPath) {
98 return runQuery()
99 }
100
101 return this.enqueue(async () => runQuery())
102 }
103
104 async run(sql, params = []) {
105 const activeDbPath = this.transactionDbPath.getStore()
106 const renderedSql = interpolateSql(sql, params)
107 const runDbPath = activeDbPath ?? this.dbPath
108
109 if (activeDbPath) {
110 await execFileAsync(`sqlite3`, [runDbPath, renderedSql])
111 return
112 }
113
114 await this.enqueue(async () => {
115 await execFileAsync(`sqlite3`, [runDbPath, renderedSql])
116 })
117 }
118
119 async transaction(fn) {
120 const activeDbPath = this.transactionDbPath.getStore()
121 if (activeDbPath) {
122 return fn(this)
123 }
124
125 return this.enqueue(async () => {
126 const txDirectory = mkdtempSync(join(tmpdir(), `db-electron-e2e-tx-`))
127 const txDbPath = join(txDirectory, `state.sqlite`)
128
129 if (existsSync(this.dbPath)) {
130 copyFileSync(this.dbPath, txDbPath)
131 }
132
133 try {
134 const txResult = await this.transactionDbPath.run(txDbPath, async () =>
135 fn(this),
136 )
137 if (existsSync(txDbPath)) {
138 copyFileSync(txDbPath, this.dbPath)
139 }
140 return txResult
141 } finally {
142 rmSync(txDirectory, { recursive: true, force: true })
143 }
144 })
145 }
146
147 enqueue(operation) {
148 const queuedOperation = this.queue.then(operation, operation)
149 this.queue = queuedOperation.then(
150 () => undefined,
151 () => undefined,
152 )
153 return queuedOperation
154 }
155}
156
157function parseInputFromEnv() {
158 const rawInput = process.env[E2E_INPUT_ENV_VAR]
159 if (!rawInput) {
160 throw new Error(`Missing ${E2E_INPUT_ENV_VAR}`)
161 }
162
163 const parsed = JSON.parse(rawInput)
164 const decoded = decodeTransportValue(parsed)
165 if (!decoded || typeof decoded !== `object`) {
166 throw new Error(`Invalid ${E2E_INPUT_ENV_VAR} payload`)
167 }
168
169 return decoded
170}
171
172function isEncodedTransportValue(value) {
173 return (
174 value &&
175 typeof value === `object` &&
176 typeof value[E2E_TRANSPORT_TYPE_TAG] === `string`
177 )
178}
179
180function decodeTransportValue(value) {
181 if (value === null) {
182 return null
183 }
184
185 if (
186 typeof value === `string` ||
187 typeof value === `number` ||
188 typeof value === `boolean`
189 ) {
190 return value
191 }
192
193 if (Array.isArray(value)) {
194 return value.map((item) => decodeTransportValue(item))
195 }
196
197 if (isEncodedTransportValue(value)) {
198 switch (value[E2E_TRANSPORT_TYPE_TAG]) {
199 case `bigint`:
200 return BigInt(value[E2E_TRANSPORT_VALUE_TAG])
201 case `date`:
202 return new Date(value[E2E_TRANSPORT_VALUE_TAG])
203 case `date_invalid`:
204 return new Date(Number.NaN)
205 case `nan`:
206 return Number.NaN
207 case `infinity`:
208 return Number.POSITIVE_INFINITY
209 case `-infinity`:
210 return Number.NEGATIVE_INFINITY
211 default:
212 break
213 }
214 }
215
216 if (typeof value === `object`) {
217 const decodedObject = {}
218 for (const [key, objectValue] of Object.entries(value)) {
219 decodedObject[key] = decodeTransportValue(objectValue)
220 }
221 return decodedObject
222 }
223
224 return value
225}
226
227function printProcessResult(result) {
228 try {
229 const serializedResult = Buffer.from(serialize(result)).toString(`base64`)
230 process.stdout.write(`${E2E_RESULT_BASE64_PREFIX}${serializedResult}\n`)
231 } catch {
232 process.stdout.write(`${E2E_RESULT_PREFIX}${JSON.stringify(result)}\n`)
233 }
234}
235
236function getPreloadPath() {
237 const currentFile = fileURLToPath(import.meta.url)
238 return join(dirname(currentFile), `renderer-preload.cjs`)
239}
240
241function getRendererPagePath() {
242 const currentFile = fileURLToPath(import.meta.url)
243 return join(dirname(currentFile), `renderer-page.html`)
244}
245
246function serializeError(error) {
247 if (error instanceof Error) {
248 return {
249 name: error.name,
250 message: error.message,
251 stack: error.stack,
252 }
253 }
254
255 return {
256 name: `Error`,
257 message: `Unknown runtime error`,
258 }
259}
260
261function createUnknownCollectionError(collectionId) {
262 const error = new Error(
263 `Unknown electron persistence collection "${collectionId}"`,
264 )
265 error.name = `UnknownElectronPersistenceCollectionError`
266 error.code = `UNKNOWN_COLLECTION`
267 return error
268}
269
270function createMainPersistence(input, driver) {
271 const adapter = createSQLiteCorePersistenceAdapter({
272 driver,
273 ...(input.adapterOptions ?? {}),
274 })
275
276 if (input.allowAnyCollectionId) {
277 return {
278 persistence: {
279 adapter,
280 },
281 cleanup: () => {},
282 }
283 }
284
285 return {
286 persistence: {
287 adapter: {
288 loadSubset: (collectionId, options, ctx) => {
289 if (collectionId !== input.collectionId) {
290 throw createUnknownCollectionError(collectionId)
291 }
292 return adapter.loadSubset(collectionId, options, ctx)
293 },
294 loadResumeSnapshot: (collectionId, ctx) => {
295 if (collectionId !== input.collectionId) {
296 throw createUnknownCollectionError(collectionId)
297 }
298 return adapter.loadResumeSnapshot(collectionId, ctx)
299 },
300 applyCommittedTx: (collectionId, tx) => {
301 if (collectionId !== input.collectionId) {
302 throw createUnknownCollectionError(collectionId)
303 }
304 return adapter.applyCommittedTx(collectionId, tx)
305 },
306 ensureIndex: (collectionId, signature, spec) => {
307 if (collectionId !== input.collectionId) {
308 throw createUnknownCollectionError(collectionId)
309 }
310 return adapter.ensureIndex(collectionId, signature, spec)
311 },
312 markIndexRemoved: (collectionId, signature) => {
313 if (collectionId !== input.collectionId) {
314 throw createUnknownCollectionError(collectionId)
315 }
316 return adapter.markIndexRemoved?.(collectionId, signature)
317 },
318 pullSince: (collectionId, fromRowVersion) => {
319 if (collectionId !== input.collectionId) {
320 throw createUnknownCollectionError(collectionId)
321 }
322 return adapter.pullSince?.(collectionId, fromRowVersion)
323 },
324 },
325 },
326 cleanup: () => {},
327 }
328}
329
330async function run() {
331 app.commandLine.appendSwitch(`disable-gpu`)
332 app.commandLine.appendSwitch(`disable-dev-shm-usage`)
333 app.commandLine.appendSwitch(`no-sandbox`)
334
335 const input = parseInputFromEnv()
336 const driver = new SqliteCliDriver(input.dbPath)
337 const mainRuntime = createMainPersistence(input, driver)
338 const disposeIpc = exposeElectronSQLitePersistence({
339 ipcMain,
340 persistence: mainRuntime.persistence,
341 channel: input.channel,
342 })
343
344 let window
345 try {
346 await app.whenReady()
347 window = new BrowserWindow({
348 show: false,
349 webPreferences: {
350 contextIsolation: true,
351 nodeIntegration: false,
352 sandbox: false,
353 preload: getPreloadPath(),
354 },
355 })
356
357 const rendererDiagnostics = []
358 window.webContents.on(
359 `console-message`,
360 (_event, level, message, line, sourceId) => {
361 rendererDiagnostics.push(
362 `[console:${String(level)}] ${sourceId}:${String(line)} ${message}`,
363 )
364 },
365 )
366 window.webContents.on(`preload-error`, (_event, path, error) => {
367 rendererDiagnostics.push(
368 `[preload-error] ${path}: ${error?.message ?? `unknown preload error`}`,
369 )
370 })
371
372 await window.loadFile(getRendererPagePath())
373
374 const scenarioInputBase64 = Buffer.from(
375 serialize({
376 collectionId: input.collectionId,
377 allowAnyCollectionId: input.allowAnyCollectionId,
378 hostKind: input.hostKind,
379 adapterOptions: input.adapterOptions,
380 channel: input.channel,
381 timeoutMs: input.timeoutMs,
382 scenario: input.scenario,
383 }),
384 ).toString(`base64`)
385
386 const hasBridgeApi = await window.webContents.executeJavaScript(
387 `typeof window.__tanstackDbRuntimeBridge__ === 'object'`,
388 true,
389 )
390 if (!hasBridgeApi) {
391 throw new Error(
392 `Renderer preload bridge is unavailable.\n${rendererDiagnostics.join(`\n`)}`,
393 )
394 }
395
396 let result
397 try {
398 result = await window.webContents.executeJavaScript(
399 `window.__tanstackDbRuntimeBridge__.runScenarioFromBase64('${scenarioInputBase64}')`,
400 true,
401 )
402 } catch (error) {
403 const message = error instanceof Error ? error.message : `Unknown error`
404 throw new Error(
405 `Renderer scenario execution failed: ${message}\n${rendererDiagnostics.join(`\n`)}`,
406 )
407 }
408
409 return {
410 ok: true,
411 result,
412 }
413 } finally {
414 if (window) {
415 window.destroy()
416 }
417 disposeIpc()
418 mainRuntime.cleanup()
419 await app.quit()
420 }
421}
422
423void run()
424 .then((result) => {
425 printProcessResult(result)
426 process.exitCode = 0
427 })
428 .catch((error) => {
429 printProcessResult({
430 ok: false,
431 error: serializeError(error),
432 })
433 process.exitCode = 1
434 })