orez 0.2.27 → 0.2.30

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 (157) hide show
  1. package/dist/cf-do/worker.d.ts +3 -0
  2. package/dist/cf-do/worker.d.ts.map +1 -1
  3. package/dist/cf-do/worker.js +37 -15
  4. package/dist/cf-do/worker.js.map +1 -1
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +8 -0
  7. package/dist/index.js.map +1 -1
  8. package/package.json +3 -4
  9. package/src/admin/admin-data.test.ts +0 -348
  10. package/src/admin/http-proxy.ts +0 -252
  11. package/src/admin/log-store.ts +0 -192
  12. package/src/admin/server.ts +0 -471
  13. package/src/admin/ui.ts +0 -1322
  14. package/src/bench/proxy-throughput.bench.ts +0 -343
  15. package/src/bench/serial-mutations.bench.ts +0 -270
  16. package/src/browser.ts +0 -203
  17. package/src/cf-do/.wrangler/cache/cf.json +0 -1
  18. package/src/cf-do/.wrangler/state/v3/cache/miniflare-CacheObject/metadata.sqlite +0 -0
  19. package/src/cf-do/.wrangler/state/v3/cache/miniflare-CacheObject/metadata.sqlite-shm +0 -0
  20. package/src/cf-do/.wrangler/state/v3/cache/miniflare-CacheObject/metadata.sqlite-wal +0 -0
  21. package/src/cf-do/.wrangler/state/v3/do/zero-do-ZeroDO/0ffaabee41a60e04dd0eb7db3073f0a40139e6a97ccd26823967acb652b89a7b.sqlite +0 -0
  22. package/src/cf-do/.wrangler/state/v3/do/zero-do-ZeroDO/metadata.sqlite +0 -0
  23. package/src/cf-do/.wrangler/state/v3/do/zero-do-ZeroDO/metadata.sqlite-shm +0 -0
  24. package/src/cf-do/.wrangler/state/v3/do/zero-do-ZeroDO/metadata.sqlite-wal +0 -0
  25. package/src/cf-do/.wrangler/tmp/bundle-0z4CpE/middleware-insertion-facade.js +0 -11
  26. package/src/cf-do/.wrangler/tmp/bundle-0z4CpE/middleware-loader.entry.ts +0 -134
  27. package/src/cf-do/.wrangler/tmp/bundle-vYmw0E/middleware-insertion-facade.js +0 -11
  28. package/src/cf-do/.wrangler/tmp/bundle-vYmw0E/middleware-loader.entry.ts +0 -134
  29. package/src/cf-do/.wrangler/tmp/dev-cbILNo/worker.js +0 -1059
  30. package/src/cf-do/.wrangler/tmp/dev-cbILNo/worker.js.map +0 -8
  31. package/src/cf-do/.wrangler/tmp/dev-qbho19/worker.js +0 -1059
  32. package/src/cf-do/.wrangler/tmp/dev-qbho19/worker.js.map +0 -8
  33. package/src/cf-do/ARCHITECTURE.md +0 -93
  34. package/src/cf-do/CHAT_E2E.md +0 -213
  35. package/src/cf-do/watermark.test.ts +0 -103
  36. package/src/cf-do/watermark.ts +0 -118
  37. package/src/cf-do/worker.ts +0 -1041
  38. package/src/cf-do/wrangler.toml +0 -11
  39. package/src/cf-pglite/README.md +0 -19
  40. package/src/change-tracking.ts +0 -25
  41. package/src/child-process.test.ts +0 -147
  42. package/src/child-process.ts +0 -90
  43. package/src/cli-entry.ts +0 -72
  44. package/src/cli.test.ts +0 -40
  45. package/src/cli.ts +0 -1214
  46. package/src/config.ts +0 -150
  47. package/src/do-sql-tracking.test.ts +0 -19
  48. package/src/do-sql-tracking.ts +0 -19
  49. package/src/index.ts +0 -1215
  50. package/src/integration/integration.test.ts +0 -517
  51. package/src/integration/native-binary.guard.test.ts +0 -13
  52. package/src/integration/native-startup.test.ts +0 -44
  53. package/src/integration/replication-latency.test.ts +0 -428
  54. package/src/integration/restore-live-stress.test.ts +0 -433
  55. package/src/integration/restore-reset.test.ts +0 -400
  56. package/src/integration/restore.test.ts +0 -274
  57. package/src/integration/test-permissions.ts +0 -147
  58. package/src/load-config.ts +0 -46
  59. package/src/log.ts +0 -96
  60. package/src/mutex.ts +0 -47
  61. package/src/pg-proxy-browser.singledb.test.ts +0 -233
  62. package/src/pg-proxy-browser.ts +0 -2022
  63. package/src/pg-proxy-do-backend.test.ts +0 -3890
  64. package/src/pg-proxy-do-backend.ts +0 -7191
  65. package/src/pg-proxy.ts +0 -1087
  66. package/src/pg-sqlite-compiler/README.md +0 -53
  67. package/src/pg-sqlite-compiler/catalog/seed.ts +0 -524
  68. package/src/pg-sqlite-compiler/fixtures/pgsqlite/arithmetic.json +0 -307
  69. package/src/pg-sqlite-compiler/fixtures/pgsqlite/array.json +0 -377
  70. package/src/pg-sqlite-compiler/fixtures/pgsqlite/cast.json +0 -12
  71. package/src/pg-sqlite-compiler/fixtures/pgsqlite/catalog.json +0 -447
  72. package/src/pg-sqlite-compiler/fixtures/pgsqlite/create-table.json +0 -32
  73. package/src/pg-sqlite-compiler/fixtures/pgsqlite/datetime.json +0 -397
  74. package/src/pg-sqlite-compiler/fixtures/pgsqlite/enum.json +0 -337
  75. package/src/pg-sqlite-compiler/fixtures/pgsqlite/insert.json +0 -337
  76. package/src/pg-sqlite-compiler/fixtures/pgsqlite/json.json +0 -537
  77. package/src/pg-sqlite-compiler/fixtures/pgsqlite/misc.json +0 -1837
  78. package/src/pg-sqlite-compiler/index.ts +0 -73
  79. package/src/pg-sqlite-compiler/integration.test.ts +0 -136
  80. package/src/pg-sqlite-compiler/passes/ast-utils.ts +0 -113
  81. package/src/pg-sqlite-compiler/passes/catalog.ts +0 -65
  82. package/src/pg-sqlite-compiler/passes/datetime.ts +0 -74
  83. package/src/pg-sqlite-compiler/passes/index.ts +0 -49
  84. package/src/pg-sqlite-compiler/passes/types.ts +0 -156
  85. package/src/pg-sqlite-compiler/smoke.test.ts +0 -69
  86. package/src/pg-sqlite-compiler/test/catalog.test.ts +0 -171
  87. package/src/pg-sqlite-compiler/test/corpus.test.ts +0 -161
  88. package/src/pg-sqlite-compiler/test/datetime.oracle.test.ts +0 -102
  89. package/src/pg-sqlite-compiler/test/oracle.ts +0 -237
  90. package/src/pg-sqlite-compiler/test/types.test.ts +0 -109
  91. package/src/pg-sqlite-compiler/types.ts +0 -63
  92. package/src/pglite-ipc.test.ts +0 -116
  93. package/src/pglite-ipc.ts +0 -266
  94. package/src/pglite-manager.ts +0 -557
  95. package/src/pglite-web-proxy.test.ts +0 -57
  96. package/src/pglite-web-proxy.ts +0 -221
  97. package/src/pglite-web-worker.ts +0 -152
  98. package/src/pglite-worker-thread.ts +0 -253
  99. package/src/port.ts +0 -25
  100. package/src/process-title.ts +0 -9
  101. package/src/recovery.ts +0 -155
  102. package/src/replication/change-tracker.test.ts +0 -357
  103. package/src/replication/change-tracker.ts +0 -279
  104. package/src/replication/handler.test.ts +0 -511
  105. package/src/replication/handler.ts +0 -1190
  106. package/src/replication/pgoutput-encoder.test.ts +0 -697
  107. package/src/replication/pgoutput-encoder.ts +0 -373
  108. package/src/replication/tcp-replication.test.ts +0 -876
  109. package/src/replication/zero-compat.test.ts +0 -1150
  110. package/src/restore-stress.test.ts +0 -188
  111. package/src/s3-local.ts +0 -203
  112. package/src/shim/hooks.mjs +0 -120
  113. package/src/shim/register.mjs +0 -4
  114. package/src/sqlite-mode/apply-mode.ts +0 -224
  115. package/src/sqlite-mode/index.ts +0 -15
  116. package/src/sqlite-mode/native-binary.ts +0 -89
  117. package/src/sqlite-mode/package-resolve.ts +0 -17
  118. package/src/sqlite-mode/resolve-mode.ts +0 -80
  119. package/src/sqlite-mode/shim-template.ts +0 -159
  120. package/src/sqlite-mode/sqlite-mode.test.ts +0 -427
  121. package/src/sqlite-mode/types.ts +0 -30
  122. package/src/vite-plugin.ts +0 -67
  123. package/src/wasm-sqlite.test.ts +0 -537
  124. package/src/worker/browser-admin.ts +0 -52
  125. package/src/worker/browser-build-config.test.ts +0 -71
  126. package/src/worker/browser-build-config.ts +0 -109
  127. package/src/worker/browser-embed-admin.test.ts +0 -75
  128. package/src/worker/browser-embed.ts +0 -345
  129. package/src/worker/cf-patches.ts +0 -384
  130. package/src/worker/embed-integration.test.ts +0 -321
  131. package/src/worker/index.ts +0 -138
  132. package/src/worker/shims/fastify.test.ts +0 -255
  133. package/src/worker/shims/fastify.ts +0 -306
  134. package/src/worker/shims/http-service.test.ts +0 -355
  135. package/src/worker/shims/http-service.ts +0 -293
  136. package/src/worker/shims/node-stub.ts +0 -290
  137. package/src/worker/shims/oxfmt.ts +0 -3
  138. package/src/worker/shims/postgres-browser.ts +0 -59
  139. package/src/worker/shims/postgres-socket.test.ts +0 -576
  140. package/src/worker/shims/postgres-socket.ts +0 -310
  141. package/src/worker/shims/postgres.test.ts +0 -364
  142. package/src/worker/shims/postgres.ts +0 -1454
  143. package/src/worker/shims/sqlite-browser.test.ts +0 -233
  144. package/src/worker/shims/sqlite-browser.ts +0 -175
  145. package/src/worker/shims/sqlite.test.ts +0 -786
  146. package/src/worker/shims/sqlite.ts +0 -978
  147. package/src/worker/shims/stream-browser.ts +0 -15
  148. package/src/worker/shims/ws-browser.test.ts +0 -205
  149. package/src/worker/shims/ws-browser.ts +0 -248
  150. package/src/worker/shims/ws.test.ts +0 -288
  151. package/src/worker/shims/ws.ts +0 -467
  152. package/src/worker/shims/zero-process-env.ts +0 -11
  153. package/src/worker/types.ts +0 -75
  154. package/src/worker/worker-integration.test.ts +0 -223
  155. package/src/worker/worker.test.ts +0 -136
  156. package/src/worker/zero-cache-embed-cf.ts +0 -463
  157. package/src/worker/zero-cache-embed.ts +0 -277
@@ -1,224 +0,0 @@
1
- /**
2
- * apply sqlite mode - handles shim installation with backup/restore lifecycle
3
- *
4
- * this module manages the in-place patching of @rocicorp/zero-sqlite3 with proper
5
- * backup/restore to prevent mode contamination when switching between wasm and native.
6
- */
7
-
8
- import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
9
- import { resolve } from 'node:path'
10
-
11
- import { generateCjsShim } from './shim-template.js'
12
- import { BACKUP_MARKER, type SqliteMode, type SqliteModeConfig } from './types.js'
13
-
14
- interface ApplyResult {
15
- success: boolean
16
- shimPath?: string
17
- error?: string
18
- }
19
-
20
- /**
21
- * find the index.js file to shim in @rocicorp/zero-sqlite3
22
- */
23
- function findZeroSqliteIndex(zeroSqlitePath: string): string | null {
24
- // find package root (contains package.json)
25
- let dir = zeroSqlitePath
26
- while (dir && !existsSync(resolve(dir, 'package.json'))) {
27
- const parent = resolve(dir, '..')
28
- if (parent === dir) break
29
- dir = parent
30
- }
31
-
32
- // try lib/index.js first, then root index.js
33
- const libIndex = resolve(dir, 'lib', 'index.js')
34
- if (existsSync(libIndex)) return libIndex
35
-
36
- const rootIndex = resolve(dir, 'index.js')
37
- if (existsSync(rootIndex)) return rootIndex
38
-
39
- return null
40
- }
41
-
42
- /**
43
- * get backup path for an index file
44
- */
45
- function getBackupPath(indexPath: string): string {
46
- return indexPath + BACKUP_MARKER
47
- }
48
-
49
- /**
50
- * check if a file is already shimmed by orez
51
- */
52
- function isOrezShimmed(indexPath: string): boolean {
53
- if (!existsSync(indexPath)) return false
54
- const content = readFileSync(indexPath, 'utf-8')
55
- return content.includes('orez sqlite shim')
56
- }
57
-
58
- /**
59
- * check what mode an existing shim is configured for
60
- */
61
- export function getShimMode(indexPath: string): SqliteMode | null {
62
- if (!existsSync(indexPath)) return null
63
- const content = readFileSync(indexPath, 'utf-8')
64
- if (!content.includes('orez sqlite shim')) return null
65
-
66
- // extract mode from comment: "// mode: wasm, journal_mode: delete"
67
- const match = content.match(/\/\/ mode: (native|wasm),/)
68
- return match ? (match[1] as SqliteMode) : null
69
- }
70
-
71
- /**
72
- * backup the original @rocicorp/zero-sqlite3 index.js
73
- * only backs up if not already backed up and not already shimmed
74
- */
75
- export function backupOriginal(indexPath: string): boolean {
76
- const backupPath = getBackupPath(indexPath)
77
-
78
- // already have a backup
79
- if (existsSync(backupPath)) return true
80
-
81
- // don't backup if file is already shimmed (would backup the shim)
82
- if (isOrezShimmed(indexPath)) {
83
- return false
84
- }
85
-
86
- if (!existsSync(indexPath)) return false
87
-
88
- const content = readFileSync(indexPath, 'utf-8')
89
- writeFileSync(backupPath, content)
90
- return true
91
- }
92
-
93
- /**
94
- * restore the original @rocicorp/zero-sqlite3 from backup
95
- */
96
- export function restoreOriginal(indexPath: string): boolean {
97
- const backupPath = getBackupPath(indexPath)
98
-
99
- if (!existsSync(backupPath)) {
100
- // no backup to restore from
101
- return false
102
- }
103
-
104
- const content = readFileSync(backupPath, 'utf-8')
105
- writeFileSync(indexPath, content)
106
- rmSync(backupPath)
107
- return true
108
- }
109
-
110
- /**
111
- * check if backup exists
112
- */
113
- export function hasBackup(indexPath: string): boolean {
114
- return existsSync(getBackupPath(indexPath))
115
- }
116
-
117
- /**
118
- * apply wasm mode shim to @rocicorp/zero-sqlite3
119
- * backs up original first, writes shim in place
120
- */
121
- export function applyWasmShim(config: SqliteModeConfig): ApplyResult {
122
- if (config.mode !== 'wasm') {
123
- return { success: false, error: 'applyWasmShim called with non-wasm mode' }
124
- }
125
-
126
- if (!config.zeroSqlitePath) {
127
- return { success: false, error: '@rocicorp/zero-sqlite3 not found' }
128
- }
129
-
130
- if (!config.bedrockPath) {
131
- return { success: false, error: 'bedrock-sqlite not found' }
132
- }
133
-
134
- const indexPath = findZeroSqliteIndex(config.zeroSqlitePath)
135
- if (!indexPath) {
136
- return { success: false, error: 'could not find @rocicorp/zero-sqlite3 index.js' }
137
- }
138
-
139
- // check if already shimmed for wasm mode
140
- const existingMode = getShimMode(indexPath)
141
- if (existingMode === 'wasm') {
142
- return { success: true, shimPath: indexPath }
143
- }
144
-
145
- // backup original before shimming - must succeed
146
- const backedUp = backupOriginal(indexPath)
147
- if (!backedUp && !hasBackup(indexPath)) {
148
- // file is shimmed (possibly by another mode) but no backup exists
149
- // cannot safely proceed - would lose ability to restore
150
- return {
151
- success: false,
152
- error:
153
- 'cannot apply wasm shim: file is already shimmed with no backup. reinstall @rocicorp/zero-sqlite3',
154
- }
155
- }
156
-
157
- // generate and write shim
158
- const shimCode = generateCjsShim({
159
- mode: 'wasm',
160
- bedrockPath: config.bedrockPath,
161
- includeTracing: false,
162
- })
163
-
164
- writeFileSync(indexPath, shimCode)
165
-
166
- return { success: true, shimPath: indexPath }
167
- }
168
-
169
- /**
170
- * restore native mode by removing shim and restoring original
171
- */
172
- export function restoreNativeMode(zeroSqlitePath: string): ApplyResult {
173
- const indexPath = findZeroSqliteIndex(zeroSqlitePath)
174
- if (!indexPath) {
175
- return { success: false, error: 'could not find @rocicorp/zero-sqlite3 index.js' }
176
- }
177
-
178
- // check if currently shimmed
179
- if (!isOrezShimmed(indexPath)) {
180
- // not shimmed, nothing to do
181
- return { success: true }
182
- }
183
-
184
- // restore from backup
185
- if (restoreOriginal(indexPath)) {
186
- return { success: true }
187
- }
188
-
189
- // no backup available - this is a problem
190
- return {
191
- success: false,
192
- error:
193
- 'cannot restore native mode: no backup found. reinstall @rocicorp/zero-sqlite3',
194
- }
195
- }
196
-
197
- /**
198
- * apply sqlite mode - main entry point
199
- * handles both installing wasm shim and restoring to native
200
- */
201
- export function applySqliteMode(config: SqliteModeConfig): ApplyResult {
202
- if (config.mode === 'native') {
203
- // for native mode, restore original if shimmed
204
- if (config.zeroSqlitePath) {
205
- return restoreNativeMode(config.zeroSqlitePath)
206
- }
207
- return { success: true }
208
- }
209
-
210
- return applyWasmShim(config)
211
- }
212
-
213
- /**
214
- * cleanup any shim artifacts - used during shutdown or cleanup
215
- */
216
- export function cleanupShim(zeroSqlitePath: string | undefined): void {
217
- if (!zeroSqlitePath) return
218
-
219
- const indexPath = findZeroSqliteIndex(zeroSqlitePath)
220
- if (!indexPath) return
221
-
222
- // restore original if we have a backup
223
- restoreOriginal(indexPath)
224
- }
@@ -1,15 +0,0 @@
1
- /**
2
- * sqlite-mode module - unified sqlite mode handling for orez
3
- *
4
- * this module provides:
5
- * - type definitions for sqlite modes
6
- * - mode resolution from config
7
- * - shim generation (single source of truth)
8
- * - safe mode application with backup/restore
9
- */
10
-
11
- export * from './types.js'
12
- export * from './resolve-mode.js'
13
- export * from './apply-mode.js'
14
- export * from './shim-template.js'
15
- export * from './native-binary.js'
@@ -1,89 +0,0 @@
1
- import { existsSync, readFileSync } from 'node:fs'
2
- import { dirname, resolve } from 'node:path'
3
-
4
- import { resolvePackage } from './package-resolve.js'
5
-
6
- const NATIVE_BINARY_RELATIVE_PATHS = ['build/Release/better_sqlite3.node']
7
-
8
- export interface NativeBinaryCheckResult {
9
- packageEntryPath: string
10
- packageRoot: string
11
- expectedPaths: string[]
12
- existingPaths: string[]
13
- found: boolean
14
- }
15
-
16
- function findPackageRoot(entryPath: string): string {
17
- if (!entryPath) return ''
18
-
19
- let dir = dirname(entryPath)
20
- for (let i = 0; i < 12; i++) {
21
- const pkgJson = resolve(dir, 'package.json')
22
- if (existsSync(pkgJson)) {
23
- try {
24
- const pkg = JSON.parse(readFileSync(pkgJson, 'utf-8'))
25
- if (pkg?.name === '@rocicorp/zero-sqlite3') {
26
- return dir
27
- }
28
- } catch {
29
- // ignore malformed package.json and continue searching upward
30
- }
31
- }
32
-
33
- const parent = dirname(dir)
34
- if (parent === dir) break
35
- dir = parent
36
- }
37
-
38
- return ''
39
- }
40
-
41
- export function inspectNativeSqliteBinary(): NativeBinaryCheckResult {
42
- const packageEntryPath = resolvePackage('@rocicorp/zero-sqlite3')
43
- const packageRoot = findPackageRoot(packageEntryPath)
44
- const expectedPaths = packageRoot
45
- ? NATIVE_BINARY_RELATIVE_PATHS.map((relativePath) =>
46
- resolve(packageRoot, relativePath)
47
- )
48
- : []
49
- const existingPaths = expectedPaths.filter((filePath) => existsSync(filePath))
50
-
51
- return {
52
- packageEntryPath,
53
- packageRoot,
54
- expectedPaths,
55
- existingPaths,
56
- found: existingPaths.length > 0,
57
- }
58
- }
59
-
60
- export function hasMissingNativeBinarySignature(message: string): boolean {
61
- const text = message.toLowerCase()
62
- return (
63
- text.includes('better_sqlite3.node') ||
64
- (text.includes('could not locate the bindings file') &&
65
- text.includes('zero-sqlite3')) ||
66
- (text.includes('err_dlopen_failed') && text.includes('better_sqlite3')) ||
67
- (text.includes('no native build was found') && text.includes('sqlite'))
68
- )
69
- }
70
-
71
- export function formatNativeBootstrapInstructions(
72
- result: NativeBinaryCheckResult
73
- ): string {
74
- const expectedList =
75
- result.expectedPaths.length > 0
76
- ? result.expectedPaths.map((filePath) => ` - ${filePath}`).join('\n')
77
- : ' - <unable to resolve @rocicorp/zero-sqlite3 package root>'
78
-
79
- return [
80
- 'native sqlite binary is missing.',
81
- `resolved package entry: ${result.packageEntryPath || '<not resolved>'}`,
82
- 'expected native binary path(s):',
83
- expectedList,
84
- 'fix:',
85
- ' bun i @rocicorp/zero-sqlite3',
86
- ' bun run native:bootstrap',
87
- 'manual emergency fallback (not automated): copy a known-good better_sqlite3.node into build/Release and re-run native:bootstrap.',
88
- ].join('\n')
89
- }
@@ -1,17 +0,0 @@
1
- import { createRequire } from 'node:module'
2
-
3
- /**
4
- * resolve a package entry path
5
- * import.meta.resolve doesn't work in vitest, so we fall back to require.resolve
6
- */
7
- export function resolvePackage(pkg: string): string {
8
- try {
9
- const resolved = import.meta.resolve(pkg)
10
- if (resolved) return resolved.replace('file://', '')
11
- } catch {}
12
- try {
13
- const require = createRequire(import.meta.url)
14
- return require.resolve(pkg)
15
- } catch {}
16
- return ''
17
- }
@@ -1,80 +0,0 @@
1
- /**
2
- * mode resolution - canonical place to determine sqlite mode from config/env
3
- *
4
- * priority:
5
- * 1. explicit --disable-wasm-sqlite flag → native (requires compiled binary)
6
- * 2. explicit --force-wasm-sqlite flag → wasm
7
- * 3. native binary exists → native (auto-detect, faster)
8
- * 4. fallback → wasm (works everywhere)
9
- */
10
-
11
- import { inspectNativeSqliteBinary } from './native-binary.js'
12
- import { resolvePackage } from './package-resolve.js'
13
-
14
- import type { SqliteMode, SqliteModeConfig } from './types.js'
15
- export { resolvePackage } from './package-resolve.js'
16
-
17
- /**
18
- * resolve sqlite mode from config
19
- * single source of truth for mode selection
20
- *
21
- * auto-detects native if binary exists (faster), otherwise wasm.
22
- *
23
- * @param disableWasmSqlite - explicit flag to force native mode
24
- * @param forceWasmSqlite - explicit flag to force wasm mode
25
- */
26
- export function resolveSqliteMode(
27
- disableWasmSqlite: boolean,
28
- forceWasmSqlite: boolean = false
29
- ): SqliteMode {
30
- // explicit native request
31
- if (disableWasmSqlite) return 'native'
32
-
33
- // explicit wasm request
34
- if (forceWasmSqlite) return 'wasm'
35
-
36
- // auto-detect: use native if binary is compiled
37
- const nativeCheck = inspectNativeSqliteBinary()
38
- if (nativeCheck.found) return 'native'
39
-
40
- // fallback to wasm
41
- return 'wasm'
42
- }
43
-
44
- /**
45
- * resolve full sqlite mode config including paths
46
- * returns null if required packages aren't installed
47
- */
48
- export function resolveSqliteModeConfig(
49
- disableWasmSqlite: boolean,
50
- forceWasmSqlite: boolean = false
51
- ): SqliteModeConfig | null {
52
- const mode = resolveSqliteMode(disableWasmSqlite, forceWasmSqlite)
53
- const zeroSqlitePath = resolvePackage('@rocicorp/zero-sqlite3') || undefined
54
-
55
- // native mode needs zero-sqlite3 path
56
- if (mode === 'native') {
57
- return { mode, zeroSqlitePath }
58
- }
59
-
60
- // wasm mode only needs bedrock-sqlite - we write a shim
61
- // directly into node_modules/@rocicorp/zero-sqlite3
62
- const bedrockPath = resolvePackage('bedrock-sqlite')
63
-
64
- if (!bedrockPath) {
65
- return null // bedrock-sqlite not installed
66
- }
67
-
68
- return {
69
- mode,
70
- bedrockPath,
71
- zeroSqlitePath, // optional - may not exist if using shim
72
- }
73
- }
74
-
75
- /**
76
- * get mode display string for logging
77
- */
78
- export function getModeDisplayString(mode: SqliteMode): string {
79
- return mode
80
- }
@@ -1,159 +0,0 @@
1
- /**
2
- * shim template generator - single source of truth for both cjs and esm shims.
3
- * generates the shim code that wraps bedrock-sqlite to be compatible with
4
- * @rocicorp/zero-sqlite3 (better-sqlite3 api).
5
- */
6
-
7
- import { COMMON_PRAGMAS, JOURNAL_MODE, type SqliteMode } from './types.js'
8
-
9
- export interface ShimOptions {
10
- mode: SqliteMode
11
- bedrockPath: string
12
- // include debug tracing for changeLog/replicationState writes
13
- includeTracing?: boolean
14
- }
15
-
16
- /**
17
- * generate the core shim code (shared between cjs and esm)
18
- * this is the constructor wrapper and api polyfills
19
- */
20
- function generateShimCore(opts: ShimOptions): string {
21
- const journalMode = JOURNAL_MODE[opts.mode]
22
- const { busy_timeout, synchronous } = COMMON_PRAGMAS
23
-
24
- return `
25
- var OrigDatabase = mod.Database;
26
- var SqliteError = mod.SqliteError;
27
-
28
- function Database() {
29
- var db = new OrigDatabase(...arguments);
30
- try {
31
- db.pragma('journal_mode = ${journalMode}');
32
- db.pragma('synchronous = ${synchronous}');
33
- db.pragma('temp_store = memory');
34
- db.pragma('busy_timeout = ${busy_timeout}');
35
- } catch(e) {}
36
- return db;
37
- }
38
-
39
- Database.prototype = OrigDatabase.prototype;
40
- Database.prototype.constructor = Database;
41
- Object.keys(OrigDatabase).forEach(function(k) { Database[k] = OrigDatabase[k]; });
42
-
43
- // api polyfills for better-sqlite3 compatibility
44
- Database.prototype.unsafeMode = function() { return this; };
45
- if (!Database.prototype.defaultSafeIntegers) {
46
- Database.prototype.defaultSafeIntegers = function() { return this; };
47
- }
48
- if (!Database.prototype.serialize) {
49
- Database.prototype.serialize = function() { throw new Error('not supported in wasm'); };
50
- }
51
- if (!Database.prototype.backup) {
52
- Database.prototype.backup = function() { throw new Error('not supported in wasm'); };
53
- }
54
-
55
- // wrap pragma to skip optimize (can corrupt wasm vfs) and swallow sqlite errors
56
- var origPragma = OrigDatabase.prototype.pragma;
57
- Database.prototype.pragma = function(str, opts) {
58
- if (str && str.trim().toLowerCase().startsWith('optimize')) return [];
59
- try { return origPragma.call(this, str, opts); }
60
- catch(e) { if (e && (e.code === 'SQLITE_CORRUPT' || e.code === 'SQLITE_IOERR')) return []; throw e; }
61
- };
62
-
63
- // wrap close to swallow wasm errors during shutdown
64
- var origClose = OrigDatabase.prototype.close;
65
- Database.prototype.close = function() {
66
- try { return origClose.call(this); }
67
- catch(e) { console.error('[orez-shim] close error (swallowed):', e?.message || e); }
68
- };
69
-
70
- // statement prototype polyfills
71
- var tmpDb = new OrigDatabase(':memory:');
72
- var tmpStmt = tmpDb.prepare('SELECT 1');
73
- var SP = Object.getPrototypeOf(tmpStmt);
74
- if (!SP.safeIntegers) SP.safeIntegers = function() { return this; };
75
- SP.scanStatus = function() { return undefined; };
76
- SP.scanStatusV2 = function() { return []; };
77
- SP.scanStatusReset = function() {};
78
- tmpDb.close();
79
-
80
- // scanstat constants for query planner compatibility
81
- Database.SQLITE_SCANSTAT_NLOOP = 0;
82
- Database.SQLITE_SCANSTAT_NVISIT = 1;
83
- Database.SQLITE_SCANSTAT_EST = 2;
84
- Database.SQLITE_SCANSTAT_NAME = 3;
85
- Database.SQLITE_SCANSTAT_EXPLAIN = 4;
86
- Database.SQLITE_SCANSTAT_SELECTID = 5;
87
- Database.SQLITE_SCANSTAT_PARENTID = 6;
88
- Database.SQLITE_SCANSTAT_NCYCLE = 7;
89
- Database.SQLITE_SCANSTAT_COMPLEX = 8;
90
- `.trim()
91
- }
92
-
93
- /**
94
- * generate debug tracing code for run() method
95
- */
96
- function generateTracing(): string {
97
- return `
98
- // trace writes to _zero.changeLog and _zero.replicationState for debugging
99
- var origRun = OrigDatabase.prototype.run;
100
- Database.prototype.run = function(sql) {
101
- var args = Array.prototype.slice.call(arguments, 1);
102
- if (typeof sql === 'string') {
103
- if (sql.includes('_zero.changeLog')) {
104
- console.info('[orez-shim] changeLog write:', sql.slice(0, 120), args.length ? JSON.stringify(args[0]).slice(0, 80) : '');
105
- }
106
- if (sql.includes('_zero.replicationState') && (sql.includes('UPDATE') || sql.includes('INSERT'))) {
107
- console.info('[orez-shim] replicationState update:', sql.slice(0, 120), args.length ? JSON.stringify(args[0]).slice(0, 80) : '');
108
- }
109
- }
110
- return origRun.apply(this, arguments);
111
- };
112
- `.trim()
113
- }
114
-
115
- /**
116
- * generate commonjs shim for in-place patching of @rocicorp/zero-sqlite3
117
- */
118
- export function generateCjsShim(opts: ShimOptions): string {
119
- const core = generateShimCore(opts)
120
- const tracing = opts.includeTracing ? '\n' + generateTracing() : ''
121
-
122
- return `'use strict';
123
- // orez sqlite shim - wraps bedrock-sqlite for zero-cache compatibility
124
- // mode: ${opts.mode}, journal_mode: ${JOURNAL_MODE[opts.mode]}
125
- var mod = require('${opts.bedrockPath}');
126
- ${core}
127
- ${tracing}
128
- module.exports = Database;
129
- module.exports.SqliteError = SqliteError;
130
- `
131
- }
132
-
133
- /**
134
- * generate esm shim for loader hooks
135
- */
136
- export function generateEsmShim(opts: ShimOptions): string {
137
- const core = generateShimCore(opts)
138
- const tracing = opts.includeTracing ? '\n' + generateTracing() : ''
139
-
140
- return `// orez sqlite shim - wraps bedrock-sqlite for zero-cache compatibility
141
- // mode: ${opts.mode}, journal_mode: ${JOURNAL_MODE[opts.mode]}
142
-
143
- // catch uncaught exceptions from bedrock-sqlite wasm clearly
144
- process.on('uncaughtException', (err) => {
145
- console.error('[orez-shim] UNCAUGHT EXCEPTION:', err?.message || err);
146
- console.error('[orez-shim] code:', err?.code, 'name:', err?.name);
147
- console.error('[orez-shim] stack:', err?.stack?.split('\\n').slice(0, 5).join('\\n'));
148
- process.exit(1);
149
- });
150
-
151
- import { createRequire } from 'node:module';
152
- const require = createRequire('${opts.bedrockPath}');
153
- var mod = require('${opts.bedrockPath}');
154
- ${core}
155
- ${tracing}
156
- export default Database;
157
- export { SqliteError };
158
- `
159
- }