@bastani/atomic 0.10.1 → 0.10.2-alpha.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 (295) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +6 -0
  3. package/dist/builtin/intercom/broker/watchdog.ts +4 -0
  4. package/dist/builtin/intercom/package.json +1 -1
  5. package/dist/builtin/mcp/package.json +1 -1
  6. package/dist/builtin/subagents/CHANGELOG.md +16 -0
  7. package/dist/builtin/subagents/README.md +2 -0
  8. package/dist/builtin/subagents/package.json +1 -1
  9. package/dist/builtin/subagents/skills/subagent/SKILL.md +3 -3
  10. package/dist/builtin/subagents/src/extension/index.bundle.mjs +269 -144
  11. package/dist/builtin/web-access/CHANGELOG.md +7 -0
  12. package/dist/builtin/web-access/index.bundle.mjs +9 -5
  13. package/dist/builtin/web-access/package.json +1 -1
  14. package/dist/cli/list-models.d.ts.map +1 -1
  15. package/dist/cli/list-models.js +1 -14
  16. package/dist/cli/list-models.js.map +1 -1
  17. package/dist/core/agent-session-export.d.ts.map +1 -1
  18. package/dist/core/agent-session-export.js +13 -9
  19. package/dist/core/agent-session-export.js.map +1 -1
  20. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  21. package/dist/core/agent-session-message-queue.js +6 -3
  22. package/dist/core/agent-session-message-queue.js.map +1 -1
  23. package/dist/core/agent-session-methods.d.ts +3 -0
  24. package/dist/core/agent-session-methods.d.ts.map +1 -1
  25. package/dist/core/agent-session-methods.js.map +1 -1
  26. package/dist/core/agent-session-nested-tools.d.ts.map +1 -1
  27. package/dist/core/agent-session-nested-tools.js +2 -1
  28. package/dist/core/agent-session-nested-tools.js.map +1 -1
  29. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  30. package/dist/core/agent-session-prompt.js +12 -0
  31. package/dist/core/agent-session-prompt.js.map +1 -1
  32. package/dist/core/agent-session-state.d.ts +6 -0
  33. package/dist/core/agent-session-state.d.ts.map +1 -1
  34. package/dist/core/agent-session-state.js +71 -4
  35. package/dist/core/agent-session-state.js.map +1 -1
  36. package/dist/core/agent-session-tool-hooks.d.ts.map +1 -1
  37. package/dist/core/agent-session-tool-hooks.js +9 -1
  38. package/dist/core/agent-session-tool-hooks.js.map +1 -1
  39. package/dist/core/agent-session-types.d.ts +2 -0
  40. package/dist/core/agent-session-types.d.ts.map +1 -1
  41. package/dist/core/agent-session-types.js.map +1 -1
  42. package/dist/core/agent-session.d.ts +3 -0
  43. package/dist/core/agent-session.d.ts.map +1 -1
  44. package/dist/core/agent-session.js +7 -0
  45. package/dist/core/agent-session.js.map +1 -1
  46. package/dist/core/cache-stats.d.ts +15 -0
  47. package/dist/core/cache-stats.d.ts.map +1 -1
  48. package/dist/core/cache-stats.js +40 -2
  49. package/dist/core/cache-stats.js.map +1 -1
  50. package/dist/core/diagnostic-writer.d.ts.map +1 -1
  51. package/dist/core/diagnostic-writer.js +2 -1
  52. package/dist/core/diagnostic-writer.js.map +1 -1
  53. package/dist/core/export-html/template.js +14 -4
  54. package/dist/core/extensions/context-types.d.ts +6 -0
  55. package/dist/core/extensions/context-types.d.ts.map +1 -1
  56. package/dist/core/extensions/context-types.js.map +1 -1
  57. package/dist/core/extensions/loader-api.d.ts.map +1 -1
  58. package/dist/core/extensions/loader-api.js +5 -2
  59. package/dist/core/extensions/loader-api.js.map +1 -1
  60. package/dist/core/queued-message-delivery.d.ts +100 -7
  61. package/dist/core/queued-message-delivery.d.ts.map +1 -1
  62. package/dist/core/queued-message-delivery.js +194 -4
  63. package/dist/core/queued-message-delivery.js.map +1 -1
  64. package/dist/core/resume-cache-checkpoint.d.ts +32 -0
  65. package/dist/core/resume-cache-checkpoint.d.ts.map +1 -0
  66. package/dist/core/resume-cache-checkpoint.js +67 -0
  67. package/dist/core/resume-cache-checkpoint.js.map +1 -0
  68. package/dist/core/sdk-types.d.ts +37 -0
  69. package/dist/core/sdk-types.d.ts.map +1 -1
  70. package/dist/core/sdk-types.js.map +1 -1
  71. package/dist/core/sdk.d.ts.map +1 -1
  72. package/dist/core/sdk.js +57 -28
  73. package/dist/core/sdk.js.map +1 -1
  74. package/dist/core/session-manager-core.d.ts.map +1 -1
  75. package/dist/core/session-manager-core.js +12 -3
  76. package/dist/core/session-manager-core.js.map +1 -1
  77. package/dist/core/session-manager-entries.d.ts +13 -0
  78. package/dist/core/session-manager-entries.d.ts.map +1 -1
  79. package/dist/core/session-manager-entries.js +38 -6
  80. package/dist/core/session-manager-entries.js.map +1 -1
  81. package/dist/core/settings-lock-directory.d.ts.map +1 -1
  82. package/dist/core/settings-lock-directory.js +2 -1
  83. package/dist/core/settings-lock-directory.js.map +1 -1
  84. package/dist/core/storage/node-sqlite-file-gate.d.ts +173 -0
  85. package/dist/core/storage/node-sqlite-file-gate.d.ts.map +1 -0
  86. package/dist/core/storage/node-sqlite-file-gate.js +1033 -0
  87. package/dist/core/storage/node-sqlite-file-gate.js.map +1 -0
  88. package/dist/core/storage/node-sqlite-thread.d.ts +33 -6
  89. package/dist/core/storage/node-sqlite-thread.d.ts.map +1 -1
  90. package/dist/core/storage/node-sqlite-thread.js +72 -2
  91. package/dist/core/storage/node-sqlite-thread.js.map +1 -1
  92. package/dist/core/storage/node-sqlite.d.ts.map +1 -1
  93. package/dist/core/storage/node-sqlite.js +216 -15
  94. package/dist/core/storage/node-sqlite.js.map +1 -1
  95. package/dist/core/storage/session/entry-structure.d.ts.map +1 -1
  96. package/dist/core/storage/session/entry-structure.js +39 -2
  97. package/dist/core/storage/session/entry-structure.js.map +1 -1
  98. package/dist/core/storage/session/session-resume.d.ts.map +1 -1
  99. package/dist/core/storage/session/session-resume.js +1 -0
  100. package/dist/core/storage/session/session-resume.js.map +1 -1
  101. package/dist/core/storage/session/session-search-index.d.ts.map +1 -1
  102. package/dist/core/storage/session/session-search-index.js +56 -9
  103. package/dist/core/storage/session/session-search-index.js.map +1 -1
  104. package/dist/core/storage/statement-sequence.d.ts +36 -0
  105. package/dist/core/storage/statement-sequence.d.ts.map +1 -0
  106. package/dist/core/storage/statement-sequence.js +22 -0
  107. package/dist/core/storage/statement-sequence.js.map +1 -0
  108. package/dist/core/system-prompt.d.ts.map +1 -1
  109. package/dist/core/system-prompt.js +13 -4
  110. package/dist/core/system-prompt.js.map +1 -1
  111. package/dist/core/tasks/heartbeat-notice.d.ts.map +1 -1
  112. package/dist/core/tasks/heartbeat-notice.js +2 -1
  113. package/dist/core/tasks/heartbeat-notice.js.map +1 -1
  114. package/dist/core/tool-loadout.d.ts +4 -2
  115. package/dist/core/tool-loadout.d.ts.map +1 -1
  116. package/dist/core/tool-loadout.js +27 -5
  117. package/dist/core/tool-loadout.js.map +1 -1
  118. package/dist/core/tools/history-regex-worker.d.ts.map +1 -1
  119. package/dist/core/tools/history-regex-worker.js +2 -1
  120. package/dist/core/tools/history-regex-worker.js.map +1 -1
  121. package/dist/core/tools/powershell.d.ts +22 -22
  122. package/dist/core/tools/sqlite-selector-connection.d.ts.map +1 -1
  123. package/dist/core/tools/sqlite-selector-connection.js +7 -0
  124. package/dist/core/tools/sqlite-selector-connection.js.map +1 -1
  125. package/dist/core/transformed-system-prompt.d.ts +92 -0
  126. package/dist/core/transformed-system-prompt.d.ts.map +1 -0
  127. package/dist/core/transformed-system-prompt.js +240 -0
  128. package/dist/core/transformed-system-prompt.js.map +1 -0
  129. package/dist/extensions/codemode/execute.js +1 -1
  130. package/dist/extensions/codemode/execute.js.map +1 -1
  131. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  132. package/dist/extensions/codemode/tool.js +16 -3
  133. package/dist/extensions/codemode/tool.js.map +1 -1
  134. package/dist/extensions/llama/ui.d.ts.map +1 -1
  135. package/dist/extensions/llama/ui.js +13 -8
  136. package/dist/extensions/llama/ui.js.map +1 -1
  137. package/dist/extensions/mcp/config.d.ts +2 -0
  138. package/dist/extensions/mcp/config.d.ts.map +1 -1
  139. package/dist/extensions/mcp/config.js +5 -0
  140. package/dist/extensions/mcp/config.js.map +1 -1
  141. package/dist/extensions/mcp/index.d.ts +4 -0
  142. package/dist/extensions/mcp/index.d.ts.map +1 -1
  143. package/dist/extensions/mcp/index.js +289 -64
  144. package/dist/extensions/mcp/index.js.map +1 -1
  145. package/dist/extensions/mcp/runtime.d.ts +1 -1
  146. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  147. package/dist/extensions/mcp/runtime.js +2 -2
  148. package/dist/extensions/mcp/runtime.js.map +1 -1
  149. package/dist/extensions/mcp/tool-records.d.ts +58 -0
  150. package/dist/extensions/mcp/tool-records.d.ts.map +1 -0
  151. package/dist/extensions/mcp/tool-records.js +129 -0
  152. package/dist/extensions/mcp/tool-records.js.map +1 -0
  153. package/dist/index.d.ts +1 -0
  154. package/dist/index.d.ts.map +1 -1
  155. package/dist/index.js +1 -0
  156. package/dist/index.js.map +1 -1
  157. package/dist/modes/interactive/components/agent-panel.d.ts +2 -4
  158. package/dist/modes/interactive/components/agent-panel.d.ts.map +1 -1
  159. package/dist/modes/interactive/components/agent-panel.js +65 -80
  160. package/dist/modes/interactive/components/agent-panel.js.map +1 -1
  161. package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
  162. package/dist/modes/interactive/components/compaction-boundary-message.js +3 -3
  163. package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
  164. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  165. package/dist/modes/interactive/components/footer.js +35 -28
  166. package/dist/modes/interactive/components/footer.js.map +1 -1
  167. package/dist/modes/interactive/components/notice-line.d.ts +16 -0
  168. package/dist/modes/interactive/components/notice-line.d.ts.map +1 -1
  169. package/dist/modes/interactive/components/notice-line.js +7 -0
  170. package/dist/modes/interactive/components/notice-line.js.map +1 -1
  171. package/dist/modes/interactive/components/prompt-slot.d.ts +1 -0
  172. package/dist/modes/interactive/components/prompt-slot.d.ts.map +1 -1
  173. package/dist/modes/interactive/components/prompt-slot.js +8 -4
  174. package/dist/modes/interactive/components/prompt-slot.js.map +1 -1
  175. package/dist/modes/interactive/components/task-board.d.ts +0 -1
  176. package/dist/modes/interactive/components/task-board.d.ts.map +1 -1
  177. package/dist/modes/interactive/components/task-board.js +6 -14
  178. package/dist/modes/interactive/components/task-board.js.map +1 -1
  179. package/dist/modes/interactive/components/task-row.d.ts.map +1 -1
  180. package/dist/modes/interactive/components/task-row.js +7 -6
  181. package/dist/modes/interactive/components/task-row.js.map +1 -1
  182. package/dist/modes/interactive/components/token-segment.d.ts +2 -1
  183. package/dist/modes/interactive/components/token-segment.d.ts.map +1 -1
  184. package/dist/modes/interactive/components/token-segment.js +2 -4
  185. package/dist/modes/interactive/components/token-segment.js.map +1 -1
  186. package/dist/modes/interactive/components/tree-selector-content.d.ts.map +1 -1
  187. package/dist/modes/interactive/components/tree-selector-content.js +2 -2
  188. package/dist/modes/interactive/components/tree-selector-content.js.map +1 -1
  189. package/dist/modes/interactive/components/working-run-meter.d.ts +0 -1
  190. package/dist/modes/interactive/components/working-run-meter.d.ts.map +1 -1
  191. package/dist/modes/interactive/components/working-run-meter.js +0 -9
  192. package/dist/modes/interactive/components/working-run-meter.js.map +1 -1
  193. package/dist/modes/interactive/extension-command-hold.d.ts +25 -0
  194. package/dist/modes/interactive/extension-command-hold.d.ts.map +1 -0
  195. package/dist/modes/interactive/extension-command-hold.js +45 -0
  196. package/dist/modes/interactive/extension-command-hold.js.map +1 -0
  197. package/dist/modes/interactive/interactive-agent-events.js +2 -1
  198. package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
  199. package/dist/modes/interactive/interactive-extension-context.js +18 -10
  200. package/dist/modes/interactive/interactive-extension-context.js.map +1 -1
  201. package/dist/modes/interactive/interactive-extension-custom-ui.js +3 -0
  202. package/dist/modes/interactive/interactive-extension-custom-ui.js.map +1 -1
  203. package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
  204. package/dist/modes/interactive/interactive-input-handling.js +54 -13
  205. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  206. package/dist/modes/interactive/interactive-model-routing.d.ts +6 -0
  207. package/dist/modes/interactive/interactive-model-routing.d.ts.map +1 -1
  208. package/dist/modes/interactive/interactive-model-routing.js +15 -9
  209. package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
  210. package/dist/modes/interactive/interactive-prompt-turn.js +4 -0
  211. package/dist/modes/interactive/interactive-prompt-turn.js.map +1 -1
  212. package/dist/modes/interactive/interactive-queueing.d.ts +7 -0
  213. package/dist/modes/interactive/interactive-queueing.d.ts.map +1 -1
  214. package/dist/modes/interactive/interactive-queueing.js +47 -1
  215. package/dist/modes/interactive/interactive-queueing.js.map +1 -1
  216. package/dist/modes/interactive/interactive-session-routing.js +6 -0
  217. package/dist/modes/interactive/interactive-session-routing.js.map +1 -1
  218. package/dist/modes/interactive/interactive-slash-commands.js +165 -65
  219. package/dist/modes/interactive/interactive-slash-commands.js.map +1 -1
  220. package/dist/modes/interactive/screen-hold.d.ts +3 -0
  221. package/dist/modes/interactive/screen-hold.d.ts.map +1 -1
  222. package/dist/modes/interactive/screen-hold.js +9 -1
  223. package/dist/modes/interactive/screen-hold.js.map +1 -1
  224. package/dist/modes/interactive-engine/engine-health.d.ts +11 -3
  225. package/dist/modes/interactive-engine/engine-health.d.ts.map +1 -1
  226. package/dist/modes/interactive-engine/engine-health.js +5 -4
  227. package/dist/modes/interactive-engine/engine-health.js.map +1 -1
  228. package/dist/modes/interactive-engine/engine-quit-intent.d.ts +7 -0
  229. package/dist/modes/interactive-engine/engine-quit-intent.d.ts.map +1 -1
  230. package/dist/modes/interactive-engine/engine-quit-intent.js +19 -0
  231. package/dist/modes/interactive-engine/engine-quit-intent.js.map +1 -1
  232. package/dist/modes/interactive-engine/isolated-runtime.d.ts +18 -0
  233. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  234. package/dist/modes/interactive-engine/isolated-runtime.js +56 -4
  235. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  236. package/dist/modes/interactive-engine/protocol.d.ts +7 -0
  237. package/dist/modes/interactive-engine/protocol.d.ts.map +1 -1
  238. package/dist/modes/interactive-engine/protocol.js +1 -0
  239. package/dist/modes/interactive-engine/protocol.js.map +1 -1
  240. package/dist/modes/rpc/agent-panel-bridge.d.ts.map +1 -1
  241. package/dist/modes/rpc/agent-panel-bridge.js +0 -13
  242. package/dist/modes/rpc/agent-panel-bridge.js.map +1 -1
  243. package/dist/modes/rpc/rpc-client-process.d.ts +14 -1
  244. package/dist/modes/rpc/rpc-client-process.d.ts.map +1 -1
  245. package/dist/modes/rpc/rpc-client-process.js +74 -10
  246. package/dist/modes/rpc/rpc-client-process.js.map +1 -1
  247. package/dist/modes/rpc/rpc-client.d.ts +27 -1
  248. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  249. package/dist/modes/rpc/rpc-client.js +81 -5
  250. package/dist/modes/rpc/rpc-client.js.map +1 -1
  251. package/dist/modes/rpc/rpc-event-buffer.d.ts +2 -0
  252. package/dist/modes/rpc/rpc-event-buffer.d.ts.map +1 -1
  253. package/dist/modes/rpc/rpc-event-buffer.js +9 -0
  254. package/dist/modes/rpc/rpc-event-buffer.js.map +1 -1
  255. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  256. package/dist/modes/rpc/rpc-mode.js +16 -3
  257. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  258. package/dist/modes/rpc/rpc-session-binding.d.ts +7 -1
  259. package/dist/modes/rpc/rpc-session-binding.d.ts.map +1 -1
  260. package/dist/modes/rpc/rpc-session-binding.js +10 -2
  261. package/dist/modes/rpc/rpc-session-binding.js.map +1 -1
  262. package/dist/utils/image-resize.d.ts.map +1 -1
  263. package/dist/utils/image-resize.js +2 -1
  264. package/dist/utils/image-resize.js.map +1 -1
  265. package/dist/utils/interactive-engine-bootstrap.d.ts +2 -0
  266. package/dist/utils/interactive-engine-bootstrap.d.ts.map +1 -1
  267. package/dist/utils/interactive-engine-bootstrap.js +1 -0
  268. package/dist/utils/interactive-engine-bootstrap.js.map +1 -1
  269. package/dist/utils/interactive-engine-env.d.ts +2 -0
  270. package/dist/utils/interactive-engine-env.d.ts.map +1 -1
  271. package/dist/utils/interactive-engine-env.js +1 -0
  272. package/dist/utils/interactive-engine-env.js.map +1 -1
  273. package/dist/utils/shell.d.ts.map +1 -1
  274. package/dist/utils/shell.js +2 -0
  275. package/dist/utils/shell.js.map +1 -1
  276. package/dist/utils/token-count.d.ts +8 -0
  277. package/dist/utils/token-count.d.ts.map +1 -0
  278. package/dist/utils/token-count.js +25 -0
  279. package/dist/utils/token-count.js.map +1 -0
  280. package/dist/utils/worker-threads.d.ts +18 -0
  281. package/dist/utils/worker-threads.d.ts.map +1 -0
  282. package/dist/utils/worker-threads.js +28 -0
  283. package/dist/utils/worker-threads.js.map +1 -0
  284. package/docs/background-tasks.md +13 -12
  285. package/docs/compaction.md +2 -2
  286. package/docs/development.md +1 -1
  287. package/docs/extensions/api-reference.md +5 -3
  288. package/docs/extensions/events.md +2 -0
  289. package/docs/mcp-servers.md +1 -1
  290. package/docs/settings.md +2 -0
  291. package/docs/storage.md +3 -1
  292. package/docs/subagents.md +6 -2
  293. package/docs/usage.md +1 -1
  294. package/npm-shrinkwrap.json +49 -49
  295. package/package.json +6 -6
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-sqlite-file-gate.js","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite-file-gate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAuB5C;;;;;;;GAOG;AACH,MAAM,IAAI,GAAG,CAAC,CAAC;AACf,MAAM,MAAM,GAAG,CAAC,CAAC;AAuBjB,+FAA+F;AAC/F,SAAS,eAAe,CAAC,UAAwB;IAChD,OAAO;QACN,QAAQ,EAAE,MAAM,CAAC,iBAAiB;QAClC,KAAK,EAAE,SAAS;QAChB,UAAU;QACV,MAAM,EAAE,GAAG,EAAE,CAAC,KAAK;QACnB,IAAI,EAAE,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E,CAAC;IAC3B,MAAM,KAAK,GAAG,MAAM,CAAC,cAAc,CAAC,IAAI,KAAK,CAAC,oBAAoB,CAAC,EAAE,KAAK,CAAC,SAAS,CAAU,CAAC;IAC/F,MAAM,MAAM,GAA4B,EAAE,OAAO,EAAE,CAAC,EAAE,MAAM,EAAE,oBAAoB,EAAE,CAAC;IACrF,OAAO,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,kBAAkB,EAAE,GAAG,MAAM,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;AAC/F,CAAC","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { createRequire } from \"node:module\";\nimport type { DatabaseSync, SQLInputValue, StatementSync } from \"node:sqlite\";\n\n/**\n * A connection on a thread of its own taking or holding a file's write lock: open from the moment it sends\n * `BEGIN IMMEDIATE` until it learns that the attempt was refused or failed, or until its transaction let go of the\n * lock. Only a `scoped` hold, one opened while the process had a wrapped connection to the file, makes wrapped calls\n * wait: its transaction's callback runs in its asynchronous context (`runInHold`), so calls made inside it are told\n * apart. A process that wraps no connection to the file never enters that context, and wrapped calls made while an\n * unscoped hold is open run at once, as they always have.\n */\nexport interface FileHold {\n\treadonly file: string;\n\treadonly scoped: boolean;\n\topen: boolean;\n}\n\n/** The holds whose transaction callbacks an asynchronous context runs in, innermost first. */\nexport interface HoldScope {\n\treadonly hold: FileHold;\n\treadonly outer: HoldScope | undefined;\n}\n\n/**\n * What the process's connections to one file are doing with its write lock, in one `Int32` they all share: `FREE`, a\n * statement of the calling thread running (`CALLER`), or a connection on a thread of its own taking it (`tag * 4 + 2`)\n * or holding it (`tag * 4 + 3`), by its `tag`. That thread moves it with compare-and-exchange as SQLite takes and lets\n * go of the lock: it takes the word before `BEGIN IMMEDIATE`, and gives it back once its transaction ended, before it\n * answers. A statement of the calling thread runs only while it has the word itself (`runAdmitted`), so neither can\n * take the lock from under the other.\n */\nconst FREE = 0;\nconst CALLER = 1;\n\n/** A threaded connection's share of its file's word: the word, its tag, and how to stop using it. */\nexport interface FileLock {\n\treadonly buffer: SharedArrayBuffer;\n\treadonly tag: number;\n\t/** Gives the word back if this connection still takes or holds it, as when its thread exited. */\n\tclear(): void;\n\t/** This connection no longer uses the word; the file's word goes once no connection does. */\n\trelease(): void;\n}\n\n/** A call waiting for its turn; one decided only at its turn (see `runDeferred`) is armed then. */\ninterface Waiter {\n\tdeadline: number;\n\ttimer: ReturnType<typeof setTimeout> | undefined;\n\t/** The connection the call runs on: later calls on it wait behind this one (see `runDeferred`). */\n\treadonly connection: DatabaseSync;\n\t/** Runs the call if it can run now; whether it did. */\n\ttryRun: () => boolean;\n\tfail: () => void;\n}\n\n/** A waiter for a call on `connection` that is decided at its turn: no deadline until then. */\nfunction undecidedWaiter(connection: DatabaseSync): Waiter {\n\treturn {\n\t\tdeadline: Number.POSITIVE_INFINITY,\n\t\ttimer: undefined,\n\t\tconnection,\n\t\ttryRun: () => false,\n\t\tfail: () => {},\n\t};\n}\n\n/** Statements a calling-thread connection prepared to decide how its calls run while the file is held; see `modeOf`. */\ninterface Plans {\n\treadonly explained: Map<string, StatementSync>;\n\tbusyTimeout?: StatementSync;\n\t/** Whether the file is in WAL mode; see `inWriteAheadLog`. */\n\twriteAheadLog?: boolean;\n\t/** Whether the connection lets its busy timeout be set; see `triesAllowed`. */\n\ttimeoutSettable?: boolean;\n}\n\n/**\n * One file's open holds, the calls waiting to run, and what those calls' connections prepared meanwhile, by the\n * object that owns each connection (not the connection, which its own statements keep alive), so they are kept no\n * longer than it is.\n */\nexport interface FileGate {\n\treadonly holds: Set<FileHold>;\n\treadonly waiters: Waiter[];\n\treadonly plans: WeakMap<object, Plans>;\n\twatching: boolean;\n\t/** A call ran on this file in the current turn of the event loop; the next one waits for the next turn. */\n\tpaced: boolean;\n\tpumping: boolean;\n\tpolling: boolean;\n}\n\ninterface Registry {\n\treadonly files: Map<string, FileGate>;\n\treadonly words: Map<string, FileWord>;\n\treadonly scopes: AsyncLocalStorage<HoldScope | undefined>;\n\t/** Wrapped connections to each file that are open: closed ones, and ones collected unclosed, no longer count. */\n\treadonly wrapped: Map<string, number>;\n\treadonly collected: FinalizationRegistry<{ readonly release: () => void }>;\n\t/** Connections that refused their busy timeout back after a try: never tried first again (see `attemptOnce`). */\n\treadonly untried: WeakSet<DatabaseSync>;\n}\n\n/** One file's word and the tags of the connections that use it. */\ninterface FileWord {\n\treadonly state: Int32Array;\n\treadonly tags: Set<number>;\n\tlastTag: number;\n}\n\n/** Tags stay below this, so a mark (`tag * 4 + 3`) is a positive `Int32`. */\nconst TAG_LIMIT = 2 ** 28;\n\n// Shared across module copies, as the transaction gates are: a copy that runs a transaction's callback and a copy whose\n// wrapped connection is called from it must see the same holds, words and asynchronous context.\nconst REGISTRY = Symbol.for(\"atomic-storage/node-sqlite-file-holds@1\");\nconst registryBag = globalThis as typeof globalThis & Record<symbol, Registry | undefined>;\nconst registry: Registry = registryBag[REGISTRY] ?? {\n\tfiles: new Map(),\n\twords: new Map(),\n\tscopes: new AsyncLocalStorage(),\n\twrapped: new Map(),\n\tcollected: new FinalizationRegistry((use) => use.release()),\n\tuntried: new WeakSet(),\n};\nregistryBag[REGISTRY] = registry;\n\n/** A threaded connection to `file` starts using the file's word (see `FREE`). */\nexport function useFileLock(file: string): FileLock {\n\tlet word = registry.words.get(file);\n\tif (word === undefined) {\n\t\tword = {\n\t\t\tstate: new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)),\n\t\t\ttags: new Set(),\n\t\t\tlastTag: 0,\n\t\t};\n\t\tregistry.words.set(file, word);\n\t}\n\t// The next tag no connection to the file uses, from 1 up, wrapping before the marks would leave the Int32 range.\n\tlet tag = word.lastTag;\n\tdo tag = (tag % (TAG_LIMIT - 1)) + 1;\n\twhile (word.tags.has(tag));\n\tword.lastTag = tag;\n\tword.tags.add(tag);\n\tconst { state, tags } = word;\n\tlet released = false;\n\treturn {\n\t\tbuffer: state.buffer as SharedArrayBuffer,\n\t\ttag,\n\t\tclear: () => {\n\t\t\tif (\n\t\t\t\tAtomics.compareExchange(state, 0, tag * 4 + 3, FREE) === tag * 4 + 3 ||\n\t\t\t\tAtomics.compareExchange(state, 0, tag * 4 + 2, FREE) === tag * 4 + 2\n\t\t\t)\n\t\t\t\tAtomics.notify(state, 0);\n\t\t},\n\t\trelease: () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\ttags.delete(tag);\n\t\t\tif (tags.size === 0 && registry.words.get(file)?.tags === tags) registry.words.delete(file);\n\t\t},\n\t};\n}\n\n/**\n * Runs `call`, a statement of the calling thread, if the file's word is free, holding the word while it runs, which is\n * synchronous; undefined, running nothing, if a threaded connection takes or holds the lock.\n */\nfunction runAdmitted<T>(state: Int32Array, call: () => Promise<T>): Promise<T> | undefined {\n\tif (Atomics.compareExchange(state, 0, FREE, CALLER) !== FREE) return undefined;\n\ttry {\n\t\treturn call();\n\t} finally {\n\t\tAtomics.store(state, 0, FREE);\n\t\tAtomics.notify(state, 0);\n\t}\n}\n\n/**\n * A wrapped connection, `owner`, to `file` counts as open until `release` or until `owner` is collected, whichever\n * comes first; see `FileHold`.\n */\nexport function useWrappedFile(file: string, owner: object): { release(): void } {\n\tregistry.wrapped.set(file, (registry.wrapped.get(file) ?? 0) + 1);\n\tlet released = false;\n\tconst use = {\n\t\trelease: () => {\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\tconst count = (registry.wrapped.get(file) ?? 1) - 1;\n\t\t\tif (count > 0) registry.wrapped.set(file, count);\n\t\t\telse registry.wrapped.delete(file);\n\t\t\tleaveScopesIfUnused();\n\t\t},\n\t};\n\tregistry.collected.register(owner, use, use);\n\treturn {\n\t\trelease: () => {\n\t\t\tregistry.collected.unregister(use);\n\t\t\tuse.release();\n\t\t},\n\t};\n}\n\n/** Opens a hold on `file`, identified as `fileIdentity` identifies it, scoped if a wrapped connection to it is open. */\nexport function holdFile(file: string): FileHold {\n\tlet gate = registry.files.get(file);\n\tif (gate === undefined) {\n\t\tgate = {\n\t\t\tholds: new Set(),\n\t\t\twaiters: [],\n\t\t\tplans: new WeakMap(),\n\t\t\twatching: false,\n\t\t\tpaced: false,\n\t\t\tpumping: false,\n\t\t\tpolling: false,\n\t\t};\n\t\tregistry.files.set(file, gate);\n\t}\n\tconst hold: FileHold = { file, scoped: registry.wrapped.has(file), open: true };\n\tgate.holds.add(hold);\n\treturn hold;\n}\n\n/** Whether a scoped hold of the gate's file is open. */\nfunction scopedHoldOpen(gate: FileGate): boolean {\n\tfor (const hold of gate.holds) if (hold.scoped) return true;\n\treturn false;\n}\n\n/**\n * Leaves the asynchronous context once no wrapped connection is open and no scoped hold is: nothing reads it then, and\n * on Node 22 an entered context keeps promise hooks on for every later await. It is entered again when needed.\n */\nfunction leaveScopesIfUnused(): void {\n\tif (registry.wrapped.size > 0) return;\n\tfor (const gate of registry.files.values()) if (scopedHoldOpen(gate)) return;\n\tregistry.scopes.disable();\n}\n\n/**\n * Closes `hold`, once. When it was the file's last, the oldest call waiting for the file runs now, if the word is free\n * and no call ran in this turn; the others follow one per turn (see `runNextWaiter`).\n */\nexport function releaseHold(hold: FileHold | undefined): void {\n\tif (hold === undefined || !hold.open) return;\n\thold.open = false;\n\tconst gate = registry.files.get(hold.file);\n\tif (gate === undefined) return;\n\tgate.holds.delete(hold);\n\tif (!scopedHoldOpen(gate)) runNextWaiter(hold.file, gate);\n\tforgetIfIdle(hold.file, gate);\n\tif (hold.scoped) leaveScopesIfUnused();\n}\n\n/**\n * Runs the oldest waiting call if the word is free and no call ran on the file in this turn of the event loop, and\n * schedules the next one for the next turn: calls that queued up behind a long transaction run one per turn, so none\n * of them holds the event loop for the time of all of them. A call that finds the word taken waits again, still under\n * its own deadline.\n */\nfunction runNextWaiter(file: string, gate: FileGate): void {\n\tif (gate.paced || gate.waiters.length === 0) return;\n\tconst waiter = gate.waiters[0]!;\n\tif (!waiter.tryRun()) {\n\t\tfailOverdue(file, gate);\n\t\treturn;\n\t}\n\tgate.waiters.shift();\n\tclearTimeout(waiter.timer);\n\tranThisTurn(file, gate);\n}\n\n/**\n * The oldest call could not run: calls waiting past their deadline fail now, having run nothing (or refused, see\n * `runTryingFirst`); the others keep their place.\n */\nfunction failOverdue(file: string, gate: FileGate): void {\n\tconst now = performance.now();\n\tconst overdue = gate.waiters.filter((waiting) => now >= waiting.deadline);\n\tfor (const waiter of overdue) {\n\t\tgate.waiters.splice(gate.waiters.indexOf(waiter), 1);\n\t\tclearTimeout(waiter.timer);\n\t\twaiter.fail();\n\t}\n\t// The calls behind them get their turn.\n\tif (overdue.length > 0) ranThisTurn(file, gate);\n}\n\n/** Notes that a call ran on the file in this turn; the next waiting one gets the next turn. */\nfunction ranThisTurn(file: string, gate: FileGate): void {\n\tgate.paced = true;\n\tif (gate.pumping) return;\n\tgate.pumping = true;\n\tsetImmediate(() => {\n\t\tgate.pumping = false;\n\t\tgate.paced = false;\n\t\tconst state = registry.words.get(file)?.state;\n\t\trunNextWaiter(file, gate);\n\t\tif (state !== undefined) watchWord(file, gate, state);\n\t\tforgetIfIdle(file, gate);\n\t});\n}\n\nfunction forgetIfIdle(file: string, gate: FileGate): void {\n\tif (\n\t\tgate.holds.size === 0 &&\n\t\tgate.waiters.length === 0 &&\n\t\t!gate.pumping &&\n\t\t!gate.polling &&\n\t\tregistry.files.get(file) === gate\n\t)\n\t\tregistry.files.delete(file);\n}\n\n/**\n * Runs a transaction's callback inside the transaction callbacks it was requested in (`scope`, captured when it was\n * requested, since a group commit runs it from another's request) and inside its own hold, so calls it makes can be\n * told apart.\n */\nexport function runInHold<T>(hold: FileHold | undefined, scope: HoldScope | undefined, callback: () => T): T {\n\tconst store = hold?.scoped === true ? { hold, outer: scope } : scope;\n\t// Nothing to change, as always for a process that wraps no connection to a file: no context is entered.\n\tif (store === registry.scopes.getStore()) return callback();\n\treturn registry.scopes.run(store, callback);\n}\n\n/** The holds whose callbacks the caller runs in; captured when a call is made, not when it runs. */\nexport function currentHoldScope(): HoldScope | undefined {\n\treturn registry.scopes.getStore();\n}\n\n/**\n * Whether a call made now on a wrapped connection to `file` comes in behind a transaction: a scoped hold is open or\n * calls wait for their turn. Read when the call is made; one made once that is over runs as it always has, however\n * busy the file was before.\n */\nexport function inBacklog(file: string): boolean {\n\tconst gate = registry.files.get(file);\n\treturn gate !== undefined && (scopedHoldOpen(gate) || gate.waiters.length > 0);\n}\n\n/**\n * The gate of `file` when another context holds it open: some hold is open, and none of the callbacks `scope` runs in\n * belongs to an open hold of it. A call made inside an open hold's own callback cannot wait for it, since the\n * transaction waits for the call: it runs at once, as it always has. A call made in the backlog of a transaction\n * (`backlog`, see `inBacklog`) also takes its turn behind the calls queued before it, one per turn.\n */\nexport function heldElsewhere(file: string, scope: HoldScope | undefined, backlog: boolean): FileGate | undefined {\n\tconst gate = registry.files.get(file);\n\tif (gate === undefined || (!scopedHoldOpen(gate) && gate.waiters.length === 0 && !(gate.paced && backlog)))\n\t\treturn undefined;\n\tfor (let inner = scope; inner !== undefined; inner = inner.outer) {\n\t\tif (inner.hold.open && inner.hold.file === file) return undefined;\n\t}\n\treturn gate;\n}\n\n/**\n * Runs `run` as soon as the file's word is free: at once if it is, as SQLite's busy handler would find the lock free;\n * otherwise once a threaded connection gives the word back, or the file's last hold closes. Fails it with `busy()`,\n * having run nothing, if the word is still taken at the end of the busy timeout of `database`, which `owner` owns\n * (read only when the call has to wait). When that cannot be read, `run` runs at once, as it always has.\n */\nexport function runWhenFree<T>(\n\tfile: string,\n\tgate: FileGate,\n\towner: object,\n\tdatabase: DatabaseSync,\n\trun: () => Promise<T>,\n\tbusy: () => Error,\n): Promise<T> {\n\tconst state = registry.words.get(file)?.state;\n\tif (state === undefined) return run();\n\t// Calls already waiting go first, and one runs per turn.\n\trunNextWaiter(file, gate);\n\tconst now = gate.waiters.length === 0 && !gate.paced ? runAdmitted(state, run) : undefined;\n\tif (now !== undefined) {\n\t\tranThisTurn(file, gate);\n\t\treturn now;\n\t}\n\tconst timeoutMs = busyTimeoutOf(gate, owner, database);\n\tif (timeoutMs === undefined) return run();\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst waiter = undecidedWaiter(database);\n\t\tgate.waiters.push(waiter);\n\t\tarmWhenFree(file, gate, waiter, state, timeoutMs, run, resolve, reject, busy);\n\t});\n}\n\n/** Makes `waiter` run `run` once the word is free, for `runWhenFree`. */\nfunction armWhenFree<T>(\n\tfile: string,\n\tgate: FileGate,\n\twaiter: Waiter,\n\tstate: Int32Array,\n\ttimeoutMs: number,\n\trun: () => Promise<T>,\n\tresolve: (value: T | PromiseLike<T>) => void,\n\treject: (error: unknown) => void,\n\tbusy: () => Error,\n): void {\n\twaiter.deadline = performance.now() + timeoutMs;\n\t// Decided once the event loop handled what it already received, such as the exit of a connection's thread, which\n\t// a timer runs ahead of. At its deadline it fails if the word is taken. While the word is free it keeps its place:\n\t// a free lock is never reported busy, and its turn comes (see `runNextWaiter`), so its busy timeout bounds how long\n\t// it waits for the lock, not for its turn.\n\twaiter.timer = setTimeout(\n\t\t() =>\n\t\t\tsetImmediate(() => {\n\t\t\t\tconst index = gate.waiters.indexOf(waiter);\n\t\t\t\tif (index === -1 || Atomics.load(state, 0) === FREE) return;\n\t\t\t\tgate.waiters.splice(index, 1);\n\t\t\t\twaiter.fail();\n\t\t\t\tranThisTurn(file, gate);\n\t\t\t\tforgetIfIdle(file, gate);\n\t\t\t}),\n\t\ttimeoutMs,\n\t);\n\twaiter.tryRun = () => {\n\t\tconst ran = runAdmitted(state, run);\n\t\tif (ran === undefined) return false;\n\t\tresolve(ran);\n\t\treturn true;\n\t};\n\twaiter.fail = () => reject(busy());\n\twatchWord(file, gate, state);\n}\n\n/**\n * Wakes the gate's waiting calls whenever the file's word changes, so a call runs the moment a threaded connection\n * gives the lock back, before its answer reaches this thread. One watch per gate, for as long as calls wait.\n */\nfunction watchWord(file: string, gate: FileGate, state: Int32Array): void {\n\tfor (;;) {\n\t\tif (gate.watching || gate.waiters.length === 0) return;\n\t\tconst observed = Atomics.load(state, 0);\n\t\t// Freed since the caller found it taken: run what waits now rather than wait for a change that already came.\n\t\tif (observed === FREE) {\n\t\t\t// Free: the oldest runs now or at the next turn (see `runNextWaiter`); nothing to watch for until then.\n\t\t\trunNextWaiter(file, gate);\n\t\t\tforgetIfIdle(file, gate);\n\t\t\t// Ran, or was refused a lock the word does not announce (another process's), which `pollWaiters` tries again.\n\t\t\tif (gate.paced || Atomics.load(state, 0) === FREE) return;\n\t\t\tcontinue;\n\t\t}\n\t\t// Until the last deadline: each waiter's own timer decides at its deadline, so a watch never runs past it.\n\t\t// Calls not decided yet (see `runDeferred`) need no watch: they are decided in their turn, whatever the word.\n\t\tconst deadlines = gate.waiters.map((waiter) => waiter.deadline).filter(Number.isFinite);\n\t\tconst untilMs = Math.max(...deadlines) - performance.now();\n\t\tif (deadlines.length === 0 || untilMs <= 0) return;\n\t\tconst result = Atomics.waitAsync(state, 0, observed, untilMs);\n\t\tif (!result.async) {\n\t\t\tif (result.value === \"not-equal\") continue;\n\t\t\treturn;\n\t\t}\n\t\tgate.watching = true;\n\t\tvoid result.value.then(() => {\n\t\t\tgate.watching = false;\n\t\t\trunNextWaiter(file, gate);\n\t\t\tforgetIfIdle(file, gate);\n\t\t\twatchWord(file, gate, state);\n\t\t});\n\t\treturn;\n\t}\n}\n\n/** Most plans one connection keeps while a file is held. */\nconst MAX_PLANS = 32;\n\nfunction plansOf(gate: FileGate, owner: object): Plans {\n\tlet plans = gate.plans.get(owner);\n\tif (plans === undefined) {\n\t\tplans = { explained: new Map() };\n\t\tgate.plans.set(owner, plans);\n\t}\n\treturn plans;\n}\n\n/** Drops what the connection of `owner` prepared while `file` was held, as it closes. */\nexport function forgetPlans(file: string, owner: object): void {\n\tregistry.files.get(file)?.plans.delete(owner);\n}\n\n/** The busy timeout `database` waits for a lock now, in milliseconds; undefined when it cannot be read. */\nfunction busyTimeoutOf(gate: FileGate, owner: object, database: DatabaseSync): number | undefined {\n\tconst plans = plansOf(gate, owner);\n\ttry {\n\t\tplans.busyTimeout ??= database.prepare(\"PRAGMA busy_timeout\");\n\t\tconst timeout = Number(plans.busyTimeout.get()?.timeout);\n\t\treturn Number.isFinite(timeout) && timeout >= 0 ? timeout : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** A blank or a comment, which SQLite skips between words. */\nconst GAP = String.raw`(?:\\s|--[^\\n]*(?:\\n|$)|\\/\\*[\\s\\S]*?\\*\\/)`;\n/** What SQLite skips before a statement's first word: blanks, comments and empty statements. */\nconst LEADING = new RegExp(`^(?:${GAP}|;)*`);\n/**\n * A PRAGMA, alone or under EXPLAIN or EXPLAIN QUERY PLAN (on text without what `LEADING` matches): SQLite may carry it\n * out while it prepares it, so it is never prepared ahead.\n */\nconst PRAGMA_STATEMENT = new RegExp(`^(?:EXPLAIN${GAP}+(?:QUERY${GAP}+PLAN${GAP}+)?)?PRAGMA\\\\b`, \"i\");\n/** A name as SQLite reads it, bare or quoted, with its quotes. */\nconst NAME = String.raw`(?:\\w+|\"(?:[^\"]|\"\")*\"|'(?:[^']|'')*'|\\[[^\\]]*\\]|` + \"`(?:[^`]|``)*`)\";\n/**\n * A PRAGMA's name, past an optional EXPLAIN or EXPLAIN QUERY PLAN, `PRAGMA` and an optional schema (`schema.`), on text\n * without what `LEADING` matches.\n */\nconst PRAGMA_NAME = new RegExp(\n\t`^(EXPLAIN${GAP}+(?:QUERY${GAP}+PLAN${GAP}+)?)?PRAGMA${GAP}+(?:(${NAME})${GAP}*\\\\.${GAP}*)?(${NAME})`,\n\t\"i\",\n);\n/** A name without its quotes, in lower case. */\nfunction unquoted(name: string): string {\n\tconst quote = name[0];\n\tif (quote === '\"' || quote === \"'\" || quote === \"`\")\n\t\treturn name.slice(1, -1).replaceAll(`${quote}${quote}`, quote).toLowerCase();\n\tif (quote === \"[\") return name.slice(1, -1).toLowerCase();\n\treturn name.toLowerCase();\n}\n\n/**\n * PRAGMAs that write the file and are tried first: SQLite refuses each in its opening steps, before it changed\n * anything. Every other PRAGMA runs as it always has: one that reads or sets a setting of the connection or another\n * database needs no lock of the file in WAL mode, and runs at once anyway; and ones a try would change are among them:\n * those of the busy timeout, which the try sets, also under EXPLAIN, since SQLite sets it while it prepares the\n * statement; setters that change something before they meet the lock (`journal_mode`, `default_cache_size`,\n * `auto_vacuum`, and the ones that apply to every attached database when no schema is named); checks that run the\n * application's functions in the schema's constraints (`integrity_check`, `quick_check`); and ones that answer\n * differently when refused the lock at once (a checkpoint that waits, `optimize`).\n */\nconst TRIED_PRAGMAS = new Set([\"user_version\", \"application_id\", \"schema_version\", \"incremental_vacuum\"]);\n\n/** Whether a PRAGMA (on text without what `LEADING` matches) is tried first; see `TRIED_PRAGMAS`. */\nfunction pragmaTriedFirst(statement: string): boolean {\n\tconst match = PRAGMA_NAME.exec(statement);\n\tif (match === null) return false;\n\tconst [, explain, schema, name = \"\"] = match;\n\treturn (\n\t\texplain === undefined &&\n\t\t(schema === undefined || unquoted(schema) === \"main\") &&\n\t\tTRIED_PRAGMAS.has(unquoted(name))\n\t);\n}\n\n/**\n * Built-in functions a try cannot run safely: ones that read the connection's change counters, which a refused try\n * changes; `load_extension`, which runs an extension's code; and `sqlite_attach` (ATTACH), which reads another file\n * with its own locks.\n */\nconst UNSAFE_FUNCTIONS = new Set([\"changes\", \"total_changes\", \"last_insert_rowid\", \"load_extension\", \"sqlite_attach\"]);\n/** Steps of a plan that call a function or an aggregate, named in their P4 as `name(arguments)`. */\nconst FUNCTION_STEPS = new Set([\n\t\"Function\",\n\t\"Function0\",\n\t\"PureFunc\",\n\t\"PureFunc0\",\n\t\"AggStep\",\n\t\"AggStep0\",\n\t\"AggStep1\",\n\t\"AggFinal\",\n\t\"AggValue\",\n\t\"AggInverse\",\n]);\n/** The collating sequences SQLite builds in; `B` is how a plan's key lists `BINARY`. */\nconst BUILT_IN_COLLATIONS = new Set([\"\", \"B\", \"BINARY\", \"NOCASE\", \"RTRIM\"]);\n/** Steps of a plan that compare with a collating sequence named in their P4 as `name-encoding`. */\nconst COLLATING_STEPS = new Set([\"CollSeq\", \"Eq\", \"Ne\", \"Lt\", \"Le\", \"Gt\", \"Ge\"]);\nconst COLLATION = /^(.*)-(?:8|16le|16be|16)$/;\n/** A plan's key, `k(fields,collation,…)`, each collation after its `-` (descending) and `N.` (nulls last) marks. */\nconst KEY = /^k\\(\\d+((?:,[^,)]*)*)\\)$/;\n\n/** Whether a step of a plan compares with a collating sequence SQLite does not build in, an extension's code. */\nfunction usesOtherCollation(opcode: string, p4: string): boolean {\n\tconst key = KEY.exec(p4);\n\tif (key !== null)\n\t\treturn key[1]!\n\t\t\t.split(\",\")\n\t\t\t.slice(1)\n\t\t\t.some((field) => !BUILT_IN_COLLATIONS.has(field.replace(/^-?(?:N\\.)?/, \"\")));\n\tif (!COLLATING_STEPS.has(opcode)) return false;\n\tconst name = COLLATION.exec(p4)?.[1];\n\treturn name !== undefined && !BUILT_IN_COLLATIONS.has(name);\n}\n\n/** A VACUUM, which may create the file it writes into before it is refused. */\nconst VACUUM_STATEMENT = /^VACUUM\\b/i;\n/** `UNSAFE_FUNCTIONS` but `sqlite_attach`, whose statement, ATTACH, names it otherwise. */\nconst UNSAFE_NAMES = [\"changes\", \"total_changes\", \"last_insert_rowid\", \"load_extension\"];\n/** An INSERT, UPDATE or DELETE, possibly after a WITH clause: listing its plan resets `changes()`. */\nconst CHANGING_STATEMENT = /^(?:INSERT|REPLACE|UPDATE|DELETE|WITH)\\b/i;\n/**\n * A string literal or a comment, which names nothing; or a name, bare (SQLite reads any character past ASCII as part of\n * one) or quoted.\n */\nconst WORD =\n\t/'(?:[^']|'')*'|--[^\\n]*|\\/\\*[\\s\\S]*?(?:\\*\\/|$)|\"((?:[^\"]|\"\")*)\"|\\[([^\\]]*)\\]|`((?:[^`]|``)*)`|([A-Za-z_\\u0080-\\u{10FFFF}][\\w$\\u0080-\\u{10FFFF}]*)/gu;\n\n/** The names `sql` uses, bare or quoted, in lower case: outside its string literals and comments. */\nfunction namesIn(sql: string): Set<string> {\n\tconst names = new Set<string>();\n\tfor (const [, double, bracket, backtick, bare] of sql.matchAll(WORD)) {\n\t\tconst name = double?.replaceAll('\"\"', '\"') ?? bracket ?? backtick?.replaceAll(\"``\", \"`\") ?? bare;\n\t\tif (name !== undefined) names.add(name.toLowerCase());\n\t}\n\treturn names;\n}\n\n/**\n * Whether `statement` names a function whose result a listing of its plan could change, which resets `changes()`\n * for an INSERT, UPDATE or DELETE: one of `UNSAFE_NAMES`, or, for such a statement, a function SQLite does not build\n * in, which could read the counters itself. When the connection cannot list its functions, every INSERT, UPDATE or\n * DELETE counts.\n */\nfunction namesUnsafeFunction(statement: string, database: DatabaseSync): boolean {\n\tconst names = namesIn(statement);\n\tif (UNSAFE_NAMES.some((name) => names.has(name))) return true;\n\tif (!CHANGING_STATEMENT.test(statement)) return false;\n\tconst userFunctions = functionsNotBuiltIn(database);\n\tif (userFunctions === undefined) return true;\n\tfor (const name of userFunctions) if (names.has(name)) return true;\n\treturn false;\n}\n\n/** The database numbers of a connection's main database, the file itself, and of its temporary database. */\nconst MAIN_DATABASE = 0;\nconst TEMP_DATABASE = 1;\n\n/**\n * How a wrapped call runs while a threaded transaction of this thread holds its file:\n *\n * - `try first`: once at once with a busy timeout of 0 (see `runTryingFirst`), refused the lock, tried again. Only a\n * statement whose plan proves that a refusal comes from its opening steps, before it did anything: the only\n * databases it writes are the file and the temporary one, and the file is in WAL mode, where a commit needs no\n * further lock; it calls no code but SQLite's own (no function or collating sequence SQLite does not build in, no\n * virtual table, no `UNSAFE_FUNCTIONS`); it is no VACUUM, which may create the file it writes into before it is\n * refused. A PRAGMA, which is never prepared ahead since SQLite may carry one out while preparing it, is tried first\n * only if it is one of `TRIED_PRAGMAS`.\n * - `as before`: every other single statement, an `exec` of no statement, and every call while the connection is\n * inside a transaction of its own or the file is not in WAL mode. It runs exactly as it always has, with the\n * connection's own busy timeout.\n * - `script`: an `exec` of more than one statement (see `splitStatements`). It waits until no transaction of this\n * thread holds the lock (see `runWhenFree`), so no part of it runs while the lock is held. An `exec` of exactly one\n * statement runs as that statement.\n *\n * At a busy timeout of 0 every single statement runs as before: it never waits for the lock, and setting the timeout,\n * as a try does, would remove a busy handler an extension installed, which reads as a timeout of 0. A script still\n * waits (for no time), which sets no timeout.\n *\n * The plan of a statement is made once while the file is held and listed again for later calls. Listing the plan of\n * an INSERT, UPDATE or DELETE resets the connection's `changes()`, which the statement's own run sets again; so a\n * statement that names a function that reads the change counters or may (see `namesUnsafeFunction`) runs as before\n * without its plan being listed.\n */\nexport function modeOf(\n\tgate: FileGate,\n\towner: object,\n\tdatabase: DatabaseSync,\n\tsql: string,\n\tparams: readonly SQLInputValue[],\n\tsingle: boolean,\n): \"try first\" | \"as before\" | \"script\" {\n\tif (!single) {\n\t\tconst statements = splitStatements(sql);\n\t\tif (statements.length > 1) return \"script\";\n\t\t// Nothing to run, nor to wait for.\n\t\tif (statements.length === 0) return \"as before\";\n\t\treturn modeOf(gate, owner, database, statements[0]!, params, true);\n\t}\n\tif (busyTimeoutOf(gate, owner, database) === 0) return \"as before\";\n\t// Inside a transaction of its own, a write's upgrade of the connection's read is refused at once, with no busy\n\t// handler, and a try again could succeed or be refused otherwise.\n\tif (\n\t\tdatabase.isTransaction !== false ||\n\t\t!inWriteAheadLog(gate, owner, database) ||\n\t\t!triesAllowed(gate, owner, database)\n\t)\n\t\treturn \"as before\";\n\t// Decided on the text SQLite reads, past the blanks, comments and empty statements it skips.\n\tconst statement = sql.replace(LEADING, \"\");\n\tif (PRAGMA_STATEMENT.test(statement)) return pragmaTriedFirst(statement) ? \"try first\" : \"as before\";\n\t// Decided without its plan: listing the plan of an INSERT, UPDATE or DELETE resets the connection's changes().\n\tif (VACUUM_STATEMENT.test(statement) || namesUnsafeFunction(statement, database)) return \"as before\";\n\tconst steps = planSteps(gate, owner, database, statement, params);\n\treturn steps !== undefined && triesSafely(steps, database) ? \"try first\" : \"as before\";\n}\n\n/**\n * Whether calls on `database`, which `owner` owns, may be tried first: it never refused its busy timeout back after a\n * try, and, checked once while the file is held, before anything is tried, the timeout can be read and set to the\n * value it has. An authorizer you set can refuse either; then every call runs as before, and the timeout is never set.\n */\nfunction triesAllowed(gate: FileGate, owner: object, database: DatabaseSync): boolean {\n\tif (registry.untried.has(database)) return false;\n\tconst plans = plansOf(gate, owner);\n\tif (plans.timeoutSettable === undefined) {\n\t\tconst timeoutMs = busyTimeoutOf(gate, owner, database);\n\t\ttry {\n\t\t\tif (timeoutMs !== undefined) setBusyTimeout(database, timeoutMs);\n\t\t\tplans.timeoutSettable = timeoutMs !== undefined;\n\t\t} catch {\n\t\t\tplans.timeoutSettable = false;\n\t\t}\n\t}\n\treturn plans.timeoutSettable;\n}\n\n/**\n * Whether the file of `database`, which `owner` owns, is in WAL mode, read once while the file is held. A connection\n * of this process on a thread of its own is open on the file, so it stays in WAL mode meanwhile.\n */\nfunction inWriteAheadLog(gate: FileGate, owner: object, database: DatabaseSync): boolean {\n\tconst plans = plansOf(gate, owner);\n\tif (plans.writeAheadLog === undefined) {\n\t\ttry {\n\t\t\tplans.writeAheadLog = String(database.prepare(\"PRAGMA main.journal_mode\").get()?.journal_mode) === \"wal\";\n\t\t} catch {\n\t\t\tplans.writeAheadLog = false;\n\t\t}\n\t}\n\treturn plans.writeAheadLog;\n}\n\n/**\n * Whether a plan, with the programs of the triggers it fires, can be refused the lock only in its opening steps, before\n * it did anything (see `modeOf`). When the connection cannot list its functions, every function counts as one SQLite\n * does not build in.\n */\nfunction triesSafely(steps: ReturnType<StatementSync[\"all\"]>, database: DatabaseSync): boolean {\n\tlet userFunctions: Set<string> | undefined | null = null;\n\tfor (const step of steps) {\n\t\tconst opcode = String(step.opcode);\n\t\tif (opcode === \"Transaction\") {\n\t\t\tconst written = Number(step.p1);\n\t\t\tif (Number(step.p2) !== 0 && written !== MAIN_DATABASE && written !== TEMP_DATABASE) return false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (opcode === \"Vacuum\" || /^V[A-Z]/.test(opcode)) return false;\n\t\tif (typeof step.p4 === \"string\" && usesOtherCollation(opcode, step.p4)) return false;\n\t\tif (!FUNCTION_STEPS.has(opcode)) continue;\n\t\tconst name = /^([^(]+)\\(/.exec(String(step.p4 ?? \"\"))?.[1]?.toLowerCase();\n\t\tif (name === undefined || UNSAFE_FUNCTIONS.has(name)) return false;\n\t\tif (userFunctions === null) userFunctions = functionsNotBuiltIn(database);\n\t\tif (userFunctions === undefined || userFunctions.has(name)) return false;\n\t}\n\treturn true;\n}\n\n/** The names of the functions `database` has that SQLite does not build in; undefined when it cannot list them. */\nfunction functionsNotBuiltIn(database: DatabaseSync): Set<string> | undefined {\n\ttry {\n\t\tconst names = new Set<string>();\n\t\tlet listed = 0;\n\t\tfor (const row of database.prepare(\"PRAGMA function_list\").all()) {\n\t\t\tlisted++;\n\t\t\tif (Number(row.builtin) === 0) names.add(String(row.name).toLowerCase());\n\t\t}\n\t\treturn listed === 0 ? undefined : names;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Whether `error` is SQLITE_BUSY itself (not one of its extended codes, such as SQLITE_BUSY_SNAPSHOT). */\nfunction plainBusy(error: unknown): boolean {\n\tfor (let cause = error; typeof cause === \"object\" && cause !== null; ) {\n\t\tconst { errcode } = cause as { errcode?: unknown };\n\t\tif (typeof errcode === \"number\") return errcode === 5;\n\t\tcause = (cause as { cause?: unknown }).cause;\n\t}\n\treturn false;\n}\n\n/** One attempt: done, with a value or an error of its own, or refused the lock (SQLITE_BUSY), having done nothing. */\ntype Attempt<T> =\n\t| { readonly kind: \"done\"; readonly value: T }\n\t| { readonly kind: \"failed\"; readonly error: unknown }\n\t| { readonly kind: \"busy\"; readonly error: unknown };\n\n/**\n * Runs `attempt`, a call that runs synchronously on `database`, once with a busy timeout of 0, then gives the\n * connection back `timeoutMs`. Undefined, having run nothing, when the connection no longer tries calls first or does\n * not take the busy timeout of 0, as read back (an authorizer you set can refuse or ignore it, though it allowed the\n * value it had; see `triesAllowed`): the call is to run as before, and the connection is not tried first again. When\n * the connection does not take the value back after the try, twice, the try's outcome is final, a refusal of the lock\n * included, and the connection is never tried first again: its busy timeout can stay 0.\n */\nfunction attemptOnce<T>(database: DatabaseSync, timeoutMs: number, attempt: () => T): Attempt<T> | undefined {\n\tif (registry.untried.has(database)) return undefined;\n\tlet zero = false;\n\ttry {\n\t\tsetBusyTimeout(database, 0);\n\t\tzero = readBusyTimeout(database) === 0;\n\t} catch {\n\t\t// Refused: the timeout is unchanged.\n\t}\n\tif (!zero) {\n\t\tregistry.untried.add(database);\n\t\ttimeoutRestored(database, timeoutMs);\n\t\treturn undefined;\n\t}\n\tlet outcome: Attempt<T>;\n\ttry {\n\t\toutcome = { kind: \"done\", value: attempt() };\n\t} catch (error) {\n\t\toutcome = plainBusy(error) ? { kind: \"busy\", error } : { kind: \"failed\", error };\n\t}\n\tif (!timeoutRestored(database, timeoutMs)) {\n\t\tregistry.untried.add(database);\n\t\tif (outcome.kind === \"busy\") return { kind: \"failed\", error: outcome.error };\n\t}\n\treturn outcome;\n}\n\n/** Gives `database` back its busy timeout after a try, trying twice; whether it took it, as read back. */\nfunction timeoutRestored(database: DatabaseSync, timeoutMs: number): boolean {\n\tfor (let tries = 0; tries < 2; tries++) {\n\t\ttry {\n\t\t\tsetBusyTimeout(database, timeoutMs);\n\t\t\tif (readBusyTimeout(database) === timeoutMs) return true;\n\t\t} catch {\n\t\t\t// Tried again once, then given up.\n\t\t}\n\t}\n\treturn false;\n}\n\n/** The busy timeout of `database` as it reads it now; undefined when it cannot be read. */\nfunction readBusyTimeout(database: DatabaseSync): number | undefined {\n\ttry {\n\t\tconst timeout = Number(database.prepare(\"PRAGMA busy_timeout\").get()?.timeout);\n\t\treturn Number.isFinite(timeout) ? timeout : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/** Sets the connection's busy timeout: a setting of the connection, which touches no file. */\nfunction setBusyTimeout(database: DatabaseSync, timeoutMs: number): void {\n\tdatabase.exec(`PRAGMA busy_timeout=${timeoutMs}`);\n}\n\n/**\n * Runs a single statement, `attempt` (synchronous on `database`, the connection `owner` owns), the way SQLite's busy\n * handler would, without holding this thread: once at once with a busy timeout of 0; refused the lock, it waits off\n * this thread and is tried again once a threaded transaction gives the lock back, or on a short poll for a lock another\n * process holds, oldest first and one call per turn of the event loop; still refused at the end of the connection's\n * busy timeout, it fails with that SQLITE_BUSY. Calls already waiting go first. When the busy timeout cannot be read,\n * `asBefore` runs it as it always has.\n */\nexport function runTryingFirst<T>(\n\tfile: string,\n\tgate: FileGate,\n\towner: object,\n\tdatabase: DatabaseSync,\n\tattempt: () => T,\n\tasBefore: () => Promise<T>,\n\tbusy: () => Error,\n): Promise<T> {\n\tconst timeoutMs = busyTimeoutOf(gate, owner, database);\n\tif (timeoutMs === undefined) return asBefore();\n\trunNextWaiter(file, gate);\n\tlet refusal: unknown;\n\tif (gate.waiters.length === 0 && !gate.paced) {\n\t\tconst first = attemptOnce(database, timeoutMs, attempt);\n\t\tif (first === undefined) return asBefore();\n\t\tif (first.kind !== \"busy\") {\n\t\t\tranThisTurn(file, gate);\n\t\t\treturn first.kind === \"done\" ? Promise.resolve(first.value) : Promise.reject(first.error);\n\t\t}\n\t\trefusal = first.error;\n\t}\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst waiter = undecidedWaiter(database);\n\t\tgate.waiters.push(waiter);\n\t\tarmTry(file, gate, waiter, database, timeoutMs, attempt, asBefore, refusal, resolve, reject, busy);\n\t});\n}\n\n/**\n * Makes `waiter` try `attempt` again on each wake until its deadline, `timeoutMs` from now, for `runTryingFirst`;\n * `refusal` is the SQLITE_BUSY of its last try, if any.\n */\nfunction armTry<T>(\n\tfile: string,\n\tgate: FileGate,\n\twaiter: Waiter,\n\tdatabase: DatabaseSync,\n\ttimeoutMs: number,\n\tattempt: () => T,\n\tasBefore: () => Promise<T>,\n\trefusal: unknown,\n\tresolve: (value: T | PromiseLike<T>) => void,\n\treject: (error: unknown) => void,\n\tbusy: () => Error,\n): void {\n\tlet lastRefusal = refusal;\n\t// A try the connection does not allow runs the call as before (see `attemptOnce`).\n\tconst settle = (outcome: Attempt<T> | undefined): boolean => {\n\t\tif (outcome === undefined) {\n\t\t\tresolve(asBefore());\n\t\t\treturn true;\n\t\t}\n\t\tif (outcome.kind === \"busy\") {\n\t\t\tlastRefusal = outcome.error;\n\t\t\treturn false;\n\t\t}\n\t\tif (outcome.kind === \"done\") resolve(outcome.value);\n\t\telse reject(outcome.error);\n\t\treturn true;\n\t};\n\twaiter.deadline = performance.now() + timeoutMs;\n\t// At its deadline it is tried once more if it is the oldest; refused, or behind others while the lock is taken, it\n\t// fails with the refusal. Behind others while the lock is free, it keeps its place.\n\twaiter.timer = setTimeout(\n\t\t() =>\n\t\t\tsetImmediate(() => {\n\t\t\t\tconst index = gate.waiters.indexOf(waiter);\n\t\t\t\tif (index === -1) return;\n\t\t\t\tif (index === 0 && settle(attemptOnce(database, timeoutMs, attempt))) {\n\t\t\t\t\tgate.waiters.shift();\n\t\t\t\t\tranThisTurn(file, gate);\n\t\t\t\t} else if (index === 0 || wordTaken(file)) {\n\t\t\t\t\tgate.waiters.splice(index, 1);\n\t\t\t\t\twaiter.fail();\n\t\t\t\t\tranThisTurn(file, gate);\n\t\t\t\t}\n\t\t\t\tforgetIfIdle(file, gate);\n\t\t\t}),\n\t\ttimeoutMs,\n\t);\n\twaiter.tryRun = () => settle(attemptOnce(database, timeoutMs, attempt));\n\t// Refused at its last try, it fails with that refusal; never tried, with SQLITE_BUSY as the runtime reports it.\n\twaiter.fail = () => reject(lastRefusal ?? busy());\n\tconst state = registry.words.get(file)?.state;\n\tif (state !== undefined) watchWord(file, gate, state);\n\tpollWaiters(file, gate);\n}\n\n/** Whether a call on `database` waits for its turn. */\nexport function connectionWaits(gate: FileGate, database: DatabaseSync): boolean {\n\treturn gate.waiters.some((waiter) => waiter.connection === database);\n}\n\n/**\n * Runs a call on `database`, which `owner` owns, behind an earlier call on the same connection that waits, from this\n * or another wrapped handle, so no call runs on a connection between a refused try of an earlier call and the try that\n * follows, as none could while SQLite's busy handler waited. It is decided (see `modeOf`) only at its turn,\n * since listing the plan of an INSERT, UPDATE or DELETE resets the connection's `changes()`, which a call before it\n * could read; then it runs as `runTryingFirst` or `runWhenFree` would, or as before, with `call`. Once no threaded\n * transaction holds the file, it runs as before.\n */\nexport function runDeferred<T>(\n\tfile: string,\n\tgate: FileGate,\n\towner: object,\n\tdatabase: DatabaseSync,\n\tstatement: { readonly sql: string; readonly params: readonly SQLInputValue[]; readonly single: boolean },\n\tattempt: () => T,\n\tcall: () => Promise<T>,\n\tbusy: () => Error,\n): Promise<T> {\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst waiter = undecidedWaiter(database);\n\t\twaiter.tryRun = () => {\n\t\t\tconst mode = scopedHoldOpen(gate)\n\t\t\t\t? modeOf(gate, owner, database, statement.sql, statement.params, statement.single)\n\t\t\t\t: \"as before\";\n\t\t\tconst state = registry.words.get(file)?.state;\n\t\t\tconst timeoutMs = mode === \"as before\" ? undefined : busyTimeoutOf(gate, owner, database);\n\t\t\tif (timeoutMs === undefined || (mode === \"script\" && state === undefined)) {\n\t\t\t\tresolve(call());\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (mode === \"script\") {\n\t\t\t\tconst ran = runAdmitted(state!, call);\n\t\t\t\tif (ran !== undefined) {\n\t\t\t\t\tresolve(ran);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tarmWhenFree(file, gate, waiter, state!, timeoutMs, call, resolve, reject, busy);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tconst first = attemptOnce(database, timeoutMs, attempt);\n\t\t\tif (first === undefined) resolve(call());\n\t\t\telse if (first.kind === \"done\") resolve(first.value);\n\t\t\telse if (first.kind === \"failed\") reject(first.error);\n\t\t\telse {\n\t\t\t\tarmTry(file, gate, waiter, database, timeoutMs, attempt, call, first.error, resolve, reject, busy);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn true;\n\t\t};\n\t\tgate.waiters.push(waiter);\n\t});\n}\n\n/** Whether a threaded transaction of this thread takes or holds the file's lock now, as its word says. */\nfunction wordTaken(file: string): boolean {\n\tconst state = registry.words.get(file)?.state;\n\treturn state !== undefined && Atomics.load(state, 0) !== FREE;\n}\n\n/** How often calls refused a lock that no transaction of this thread holds (another process's) are tried again. */\nconst POLL_MS = 20;\n\n/**\n * Tries the oldest waiting call again every `POLL_MS` while calls wait, for locks no word announces. While the word is\n * taken, the watch on it (`watchWord`) wakes the calls instead.\n */\nfunction pollWaiters(file: string, gate: FileGate): void {\n\tif (gate.polling || gate.waiters.length === 0) return;\n\tgate.polling = true;\n\tsetTimeout(() => {\n\t\tgate.polling = false;\n\t\tif (!wordTaken(file)) runNextWaiter(file, gate);\n\t\tforgetIfIdle(file, gate);\n\t\tpollWaiters(file, gate);\n\t}, POLL_MS);\n}\n\n/**\n * The statements of an `exec` text, split as SQLite reads them: past quoted strings and names (`'…'`, `\"…\"`, `` `…` ``,\n * `[…]`) and comments, with a trigger's body (`CREATE TRIGGER … BEGIN … END`) kept in its statement. Empty statements\n * are dropped. A comment left open runs to the end of the text; past a quote left open, or in a trigger's body without\n * its END, the rest of the text is one statement, which SQLite fails.\n */\nexport function splitStatements(sql: string): string[] {\n\tconst statements: string[] = [];\n\tlet start = 0;\n\tlet words: string[] = [];\n\tlet lastWord = \"\";\n\tlet tokens = false;\n\tconst trigger = () =>\n\t\twords[0] === \"CREATE\" &&\n\t\t(words[1] === \"TRIGGER\" || ((words[1] === \"TEMP\" || words[1] === \"TEMPORARY\") && words[2] === \"TRIGGER\"));\n\tfor (let index = 0; index < sql.length; ) {\n\t\tconst char = sql[index]!;\n\t\tif (char === \"'\" || char === '\"' || char === \"`\" || char === \"[\") {\n\t\t\tconst close = char === \"[\" ? \"]\" : char;\n\t\t\tlet end = sql.indexOf(close, index + 1);\n\t\t\t// A doubled quote stands for the quote itself, except in a bracketed name.\n\t\t\twhile (end !== -1 && close !== \"]\" && sql[end + 1] === close) end = sql.indexOf(close, end + 2);\n\t\t\ttokens = true;\n\t\t\t// Unterminated: SQLite fails the statement there, after the ones before it ran.\n\t\t\tif (end === -1) break;\n\t\t\tindex = end + 1;\n\t\t\tlastWord = \"\";\n\t\t} else if (char === \"-\" && sql[index + 1] === \"-\") {\n\t\t\tconst end = sql.indexOf(\"\\n\", index + 2);\n\t\t\tindex = end === -1 ? sql.length : end + 1;\n\t\t} else if (char === \"/\" && sql[index + 1] === \"*\") {\n\t\t\t// Unterminated, the comment runs to the end of the text.\n\t\t\tconst end = sql.indexOf(\"*/\", index + 2);\n\t\t\tindex = end === -1 ? sql.length : end + 2;\n\t\t} else if (char === \";\") {\n\t\t\tindex += 1;\n\t\t\t// Inside a trigger's body, only the semicolon after its END ends the statement.\n\t\t\tif (trigger() && lastWord !== \"END\") continue;\n\t\t\tif (tokens) statements.push(sql.slice(start, index - 1));\n\t\t\tstart = index;\n\t\t\twords = [];\n\t\t\tlastWord = \"\";\n\t\t\ttokens = false;\n\t\t} else if (/[A-Za-z_]/.test(char)) {\n\t\t\tlet end = index + 1;\n\t\t\twhile (end < sql.length && /[\\w$]/.test(sql[end]!)) end += 1;\n\t\t\tconst word = sql.slice(index, end).toUpperCase();\n\t\t\tif (words.length < 3) words.push(word);\n\t\t\tlastWord = word;\n\t\t\ttokens = true;\n\t\t\tindex = end;\n\t\t} else {\n\t\t\tif (!/\\s/.test(char)) {\n\t\t\t\ttokens = true;\n\t\t\t\tlastWord = \"\";\n\t\t\t}\n\t\t\tindex += 1;\n\t\t}\n\t}\n\t// Past an unterminated quote, or in a trigger's body without its END, SQLite fails the rest as one statement.\n\tif (tokens) statements.push(sql.slice(start));\n\treturn statements;\n}\n\n/**\n * The steps of the plan of `sql`, listed now from the plan kept for it (SQLite prepares a kept plan again when this\n * connection changed its schema since, and fails it if the statement no longer prepares), or from a new one; undefined\n * when SQLite cannot make one. The plan is bound to the call's `params` first, so parameters the statement cannot\n * bind fail before the plan is listed, which resets `changes()` (see `modeOf`), as the statement fails before it runs.\n */\nfunction planSteps(\n\tgate: FileGate,\n\towner: object,\n\tdatabase: DatabaseSync,\n\tsql: string,\n\tparams: readonly SQLInputValue[],\n): ReturnType<StatementSync[\"all\"]> | undefined {\n\tconst plans = plansOf(gate, owner);\n\tconst kept = plans.explained.get(sql);\n\tif (kept !== undefined) {\n\t\ttry {\n\t\t\treturn kept.all(...params);\n\t\t} catch {\n\t\t\tplans.explained.delete(sql);\n\t\t}\n\t}\n\ttry {\n\t\tconst explained = database.prepare(`EXPLAIN ${sql}`);\n\t\tconst steps = explained.all(...params);\n\t\tif (plans.explained.size >= MAX_PLANS) plans.explained.delete(plans.explained.keys().next().value!);\n\t\tplans.explained.set(sql, explained);\n\t\treturn steps;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nlet sqliteErrorShape: { readonly prototype: object; readonly ownCode: boolean } | undefined;\n\n/**\n * How the runtime's node:sqlite builds its errors: their class (Bun has one of its own) and whether `code` is a field\n * of each error, read once from a failure of a connection of this module's own. Plain `Error` fields when it cannot\n * be read.\n */\nfunction errorShape(): { readonly prototype: object; readonly ownCode: boolean } {\n\tif (sqliteErrorShape !== undefined) return sqliteErrorShape;\n\tsqliteErrorShape = { prototype: Error.prototype, ownCode: true };\n\ttry {\n\t\tconst { DatabaseSync: Database } = createRequire(import.meta.url)(\"node:sqlite\") as typeof import(\"node:sqlite\");\n\t\tconst probe = new Database(\":memory:\");\n\t\ttry {\n\t\t\tprobe.exec(\"SELECT\");\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error)\n\t\t\t\tsqliteErrorShape = {\n\t\t\t\t\tprototype: Object.getPrototypeOf(error) as object,\n\t\t\t\t\townCode: Object.hasOwn(error, \"code\"),\n\t\t\t\t};\n\t\t} finally {\n\t\t\tprobe.close();\n\t\t}\n\t} catch {\n\t\t// The plain shape stands.\n\t}\n\treturn sqliteErrorShape;\n}\n\n/**\n * SQLITE_BUSY as the runtime's node:sqlite reports it, for a call that waited out its busy timeout without running:\n * the runtime's own error class with the fields a refused statement carries.\n */\nexport function sqliteBusyError(): Error {\n\tconst shape = errorShape();\n\tconst error = Object.setPrototypeOf(new Error(\"database is locked\"), shape.prototype) as Error;\n\tconst fields: Record<string, unknown> = { errcode: 5, errstr: \"database is locked\" };\n\treturn Object.assign(error, shape.ownCode ? { code: \"ERR_SQLITE_ERROR\", ...fields } : fields);\n}\n"]}
@@ -1,4 +1,24 @@
1
- import type { SqliteRow, SqliteValue } from "./database.js";
1
+ import type { SqliteRow, SqliteStatement, SqliteValue } from "./database.js";
2
+ import type { SqliteSequence } from "./statement-sequence.js";
3
+ /**
4
+ * Statements sent as one request (see `SqliteSequence`). `abort` holds one `Int32` the caller sets to non-zero when its
5
+ * signal aborts: the thread reads it before each run of `repeat` and before each statement.
6
+ */
7
+ export interface SequenceRequest {
8
+ readonly kind: "sequence";
9
+ readonly repeat?: SqliteSequence["repeat"];
10
+ readonly statements: readonly SqliteStatement[];
11
+ readonly abort?: SharedArrayBuffer;
12
+ }
13
+ /**
14
+ * What a sequence request is answered with: how many runs of `repeat` changed `minChanges` rows or more, or that it
15
+ * stopped because the caller's signal aborted.
16
+ */
17
+ export type SequenceAnswer = {
18
+ readonly repeated: number;
19
+ } | {
20
+ readonly aborted: true;
21
+ };
2
22
  /** What a connection's thread is asked to do; each request is answered once, in the order it was sent. */
3
23
  export type ConnectionRequest = {
4
24
  readonly kind: "open";
@@ -12,15 +32,20 @@ export type ConnectionRequest = {
12
32
  readonly sql: string;
13
33
  readonly params: readonly SqliteValue[];
14
34
  } | {
15
- readonly kind: "begin" | "dataVersion" | "now" | "jsonbExtract" | "close";
16
- };
35
+ readonly kind: "begin";
36
+ readonly lockState?: SharedArrayBuffer;
37
+ readonly lockTag?: number;
38
+ } | {
39
+ readonly kind: "dataVersion" | "now" | "jsonbExtract" | "close";
40
+ } | SequenceRequest;
17
41
  /**
18
- * What a request is answered with: `get` a row or undefined, `all` rows, `run` the changes, `open` the location,
19
- * `dataVersion` and `now` a number, `jsonbExtract` a boolean, the others undefined.
42
+ * What a request is answered with: `get` a row or undefined, `all` rows, `run` the changes, `sequence` a
43
+ * `SequenceAnswer`, `open` the location, `dataVersion` and `now` a number, `jsonbExtract` a boolean, the others
44
+ * undefined.
20
45
  */
21
46
  export type ConnectionAnswer = SqliteRow | SqliteRow[] | {
22
47
  readonly changes: number;
23
- } | string | number | boolean | null | undefined;
48
+ } | SequenceAnswer | string | number | boolean | null | undefined;
24
49
  /** Thrown for a request to a connection whose thread is gone: closed, or lost to an error or an exit. */
25
50
  export declare class ConnectionThreadEndedError extends Error {
26
51
  constructor(message: string);
@@ -60,5 +85,7 @@ export declare class ThreadConnection {
60
85
  /** Rejects every request still waiting, oldest first, and every later one. Ending again does nothing. */
61
86
  private end;
62
87
  private stop;
88
+ /** Calls `listener` once the connection's thread has exited, whether closed or lost. */
89
+ onExit(listener: () => void): void;
63
90
  }
64
91
  //# sourceMappingURL=node-sqlite-thread.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"node-sqlite-thread.d.ts","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite-thread.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AA4I5D,0GAA0G;AAC1G,MAAM,MAAM,iBAAiB,GAC1B;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAA;CAAE,GAC5E;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAC/C;IAAE,QAAQ,CAAC,IAAI,EAAE,KAAK,GAAG,KAAK,GAAG,KAAK,CAAC;IAAC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,SAAS,WAAW,EAAE,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AAQ,EAAE,MAAM,IAAI,GAAG,IAAI,CAEjC;CACD"}
@@ -95,7 +95,22 @@ const handlers = {
95
95
  },
96
96
  all: (request) => table(statement(request.sql).all(...bind(request.params))),
97
97
  // One non-blocking BEGIN IMMEDIATE, the connection's busy timeout restored before answering.
98
- begin: () => {
98
+ begin: (request) => {
99
+ // The file's lock word (see FREE in node-sqlite-file-gate.ts): taken before BEGIN, after waiting here for a
100
+ // statement the calling thread runs meanwhile; settleLock gives it back once the transaction ended.
101
+ if (request.lockState !== undefined) {
102
+ const state = new Int32Array(request.lockState);
103
+ for (;;) {
104
+ const found = Atomics.compareExchange(state, 0, 0, request.lockTag * 4 + 2);
105
+ if (found === 0) break;
106
+ // Anything but a statement of the calling thread (1) is another holder: a lock taken, as BEGIN would find.
107
+ if (found !== 1)
108
+ throw Object.assign(new Error("database is locked"), { code: "ERR_SQLITE_ERROR", errcode: 5, errstr: "database is locked" });
109
+ Atomics.wait(state, 0, 1, 50);
110
+ }
111
+ Atomics.notify(state, 0);
112
+ lockState = { state, held: request.lockTag * 4 + 3 };
113
+ }
99
114
  const configured = Number(database.prepare("PRAGMA busy_timeout").get()?.timeout ?? 0);
100
115
  database.exec("PRAGMA busy_timeout=0");
101
116
  let began = false;
@@ -111,6 +126,29 @@ const handlers = {
111
126
  }
112
127
  }
113
128
  },
129
+ // \`repeat\`, then each statement, in one request: the statements the caller would send one at a time, in the same
130
+ // order, each prepared when it is reached. The caller's abort flag is read where the caller would check its signal.
131
+ sequence: (request) => {
132
+ const abort = request.abort === undefined ? undefined : new Int32Array(request.abort);
133
+ const aborted = () => abort !== undefined && Atomics.load(abort, 0) !== 0;
134
+ let repeated = 0;
135
+ if (request.repeat !== undefined) {
136
+ const { statement: repeat, times, minChanges } = request.repeat;
137
+ while (repeated < times) {
138
+ if (aborted()) return { aborted: true };
139
+ const before = Number(statement("SELECT total_changes() AS changes").get().changes);
140
+ statement(repeat.sql).run(...bind(repeat.params));
141
+ const after = Number(statement("SELECT total_changes() AS changes").get().changes);
142
+ if (after - before < minChanges) break;
143
+ repeated++;
144
+ }
145
+ }
146
+ for (const { sql, params } of request.statements) {
147
+ if (aborted()) return { aborted: true };
148
+ statement(sql).run(...bind(params));
149
+ }
150
+ return { repeated };
151
+ },
114
152
  dataVersion: () => Number(database.prepare("PRAGMA data_version").get()?.data_version ?? 0),
115
153
  now: () => Number(database.prepare(workerData.nowSql).get().now),
116
154
  jsonbExtract: () => {
@@ -128,9 +166,37 @@ const handlers = {
128
166
  },
129
167
  };
130
168
 
169
+ // The file's lock word while this connection takes or holds the lock: held while a transaction is open on it, given
170
+ // back (and the waiting threads woken) once none is, before the request that ended it is answered.
171
+ let lockState;
172
+
173
+ function settleLock() {
174
+ if (lockState === undefined) return;
175
+ const { state, held } = lockState;
176
+ let open = false;
177
+ try {
178
+ open = database?.isTransaction === true;
179
+ } catch {}
180
+ if (open) {
181
+ if (Atomics.compareExchange(state, 0, held - 1, held) === held - 1) Atomics.notify(state, 0);
182
+ return;
183
+ }
184
+ lockState = undefined;
185
+ if (Atomics.compareExchange(state, 0, held, 0) === held || Atomics.compareExchange(state, 0, held - 1, 0) === held - 1)
186
+ Atomics.notify(state, 0);
187
+ }
188
+
189
+ function handle(request) {
190
+ try {
191
+ return handlers[request.kind](request);
192
+ } finally {
193
+ settleLock();
194
+ }
195
+ }
196
+
131
197
  parentPort.on("message", (request) => {
132
198
  try {
133
- parentPort.postMessage({ id: request.id, value: handlers[request.kind](request) });
199
+ parentPort.postMessage({ id: request.id, value: handle(request) });
134
200
  } catch (error) {
135
201
  parentPort.postMessage({ id: request.id, failure: failure(error) });
136
202
  }
@@ -322,5 +388,9 @@ export class ThreadConnection {
322
388
  this.end(new ConnectionThreadEndedError("SQLite connection closed"));
323
389
  await this.worker.terminate();
324
390
  }
391
+ /** Calls `listener` once the connection's thread has exited, whether closed or lost. */
392
+ onExit(listener) {
393
+ this.worker.once("exit", listener);
394
+ }
325
395
  }
326
396
  //# sourceMappingURL=node-sqlite-th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EAAE,CAAC;IAC/B,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport type { SqliteRow, SqliteValue } from \"./database.js\";\nimport { sqliteDialect } from \"./dialect.js\";\n\n/**\n * A node:sqlite connection that runs on a worker thread of its own (#5376). The thread owns the `DatabaseSync`; the\n * calling thread sends it one request at a time and receives each answer as a message, so no statement, lock wait or\n * synced commit runs on the caller's event loop. SQLite's busy handler waits on the connection's own thread, so a\n * statement waiting for a lock that another connection of the same process holds never stops that connection from\n * finishing.\n */\nconst CONNECTION_SOURCE = `\nconst { parentPort, workerData } = require(\"node:worker_threads\");\nprocess.emitWarning = () => {};\nconst { DatabaseSync } = require(\"node:sqlite\");\nlet database;\n\nconst STANDARD_ERRORS = [Error, TypeError, RangeError, SyntaxError, ReferenceError, EvalError, URIError];\n// Bun stamps every error with where it was thrown; the caller's copy gets its own.\nconst LOCATION_FIELDS = new Set([\"stack\", \"message\", \"line\", \"column\", \"originalLine\", \"originalColumn\", \"sourceURL\"]);\n\n// An object's own fields that hold plain values, with their enumerability.\nfunction fieldsOf(object, skip) {\n\tconst fields = [];\n\tfor (const key of Object.getOwnPropertyNames(object)) {\n\t\tif (skip.has(key)) continue;\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(object, key);\n\t\tconst value = descriptor?.value;\n\t\tif (value === null || (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\" && typeof value !== \"bigint\")) continue;\n\t\tfields.push([key, value, descriptor.enumerable === true]);\n\t}\n\treturn fields;\n}\n\n// A thrown error as it crosses to the caller: the standard constructor it descends from, its message, and its own\n// fields with their enumerability. A runtime's error class of its own between the error and that constructor (Bun's\n// node:sqlite errors have one holding name, code and toString) is described by its fields and whether it has a\n// toString of its own, and how it shows.\nfunction failure(error) {\n\tif (!(error instanceof Error)) return { constructor: \"Error\", message: String(error), fields: [] };\n\tlet standard = Object.getPrototypeOf(error);\n\tlet between;\n\twhile (standard !== null && !STANDARD_ERRORS.some((each) => each.prototype === standard)) {\n\t\tif (between === undefined) {\n\t\t\tconst toString = Object.getOwnPropertyDescriptor(standard, \"toString\");\n\t\t\tbetween = {\n\t\t\t\tfields: fieldsOf(standard, new Set([\"constructor\", \"message\"])),\n\t\t\t\t...(typeof toString?.value === \"function\" ? { toString: { enumerable: toString.enumerable === true } } : {}),\n\t\t\t};\n\t\t}\n\t\tstandard = Object.getPrototypeOf(standard);\n\t}\n\treturn {\n\t\tconstructor: standard === null ? \"Error\" : standard.constructor.name,\n\t\tmessage: String(error.message),\n\t\tfields: fieldsOf(error, LOCATION_FIELDS),\n\t\t...(between === undefined ? {} : { between }),\n\t};\n}\n\nfunction statement(sql) {\n\tconst prepared = database.prepare(sql);\n\tprepared.setReadBigInts(true);\n\treturn prepared;\n}\n\n// Node 22 binds an empty Uint8Array that arrived in a message as NULL; a new empty one binds as a zero-length blob.\nfunction bind(params) {\n\treturn params.map((value) => (value instanceof Uint8Array && value.byteLength === 0 ? new Uint8Array(0) : value));\n}\n\nfunction value(each) {\n\tif (typeof each === \"bigint\") return each >= -BigInt(Number.MAX_SAFE_INTEGER) && each <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(each) : each;\n\t// A copy of its own: a view of a larger buffer would send the whole buffer.\n\treturn each instanceof Uint8Array ? new Uint8Array(each) : each;\n}\n\n// Rows cross as their column names and one array of values each, in the order the driver gives a row's fields.\nfunction table(rows) {\n\tif (rows.length === 0) return { columns: [], values: [] };\n\tconst columns = Object.keys(rows[0]);\n\treturn { columns, values: rows.map((row) => columns.map((column) => value(row[column]))) };\n}\n\nconst handlers = {\n\topen: (request) => {\n\t\tdatabase = new DatabaseSync(request.path, { readOnly: request.readOnly });\n\t\treturn database.location();\n\t},\n\texec: (request) => {\n\t\tdatabase.exec(request.sql);\n\t},\n\trun: (request) => ({ changes: Number(statement(request.sql).run(...bind(request.params)).changes) }),\n\tget: (request) => {\n\t\tconst row = statement(request.sql).get(...bind(request.params));\n\t\treturn row === undefined ? undefined : table([row]);\n\t},\n\tall: (request) => table(statement(request.sql).all(...bind(request.params))),\n\t// One non-blocking BEGIN IMMEDIATE, the connection's busy timeout restored before answering.\n\tbegin: () => {\n\t\tconst configured = Number(database.prepare(\"PRAGMA busy_timeout\").get()?.timeout ?? 0);\n\t\tdatabase.exec(\"PRAGMA busy_timeout=0\");\n\t\tlet began = false;\n\t\ttry {\n\t\t\tdatabase.exec(\"BEGIN IMMEDIATE\");\n\t\t\tbegan = true;\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tdatabase.exec(\"PRAGMA busy_timeout=\" + configured);\n\t\t\t} catch (restoreFailure) {\n\t\t\t\tif (began) database.exec(\"ROLLBACK\");\n\t\t\t\tthrow restoreFailure;\n\t\t\t}\n\t\t}\n\t},\n\tdataVersion: () => Number(database.prepare(\"PRAGMA data_version\").get()?.data_version ?? 0),\n\tnow: () => Number(database.prepare(workerData.nowSql).get().now),\n\tjsonbExtract: () => {\n\t\ttry {\n\t\t\tstatement(\"SELECT jsonb_extract('[]', '$')\");\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"no such function: jsonb_extract\") return false;\n\t\t\tthrow error;\n\t\t}\n\t},\n\tclose: () => {\n\t\tdatabase?.close();\n\t\tglobalThis.Bun?.gc?.(true);\n\t},\n};\n\nparentPort.on(\"message\", (request) => {\n\ttry {\n\t\tparentPort.postMessage({ id: request.id, value: handlers[request.kind](request) });\n\t} catch (error) {\n\t\tparentPort.postMessage({ id: request.id, failure: failure(error) });\n\t}\n});\n`;\n\n/** What a connection's thread is asked to do; each request is answered once, in the order it was sent. */\nexport type ConnectionRequest =\n\t| { readonly kind: \"open\"; readonly path: string; readonly readOnly: boolean }\n\t| { readonly kind: \"exec\"; readonly sql: string }\n\t| { readonly kind: \"run\" | \"get\" | \"all\"; readonly sql: string; readonly params: readonly SqliteValue[] }\n\t| { readonly kind: \"begin\" | \"dataVersion\" | \"now\" | \"jsonbExtract\" | \"close\" };\n\n/** Rows as they cross from a connection's thread: the column names, then each row's values in their order. */\ninterface RowTable {\n\treadonly columns: readonly string[];\n\treadonly values: readonly (readonly SqliteValue[])[];\n}\n\n/** What a request's answer carries as it crosses, before rows are rebuilt. */\ntype ConnectionValue = RowTable | { readonly changes: number } | string | number | boolean | null | undefined;\n\n/**\n * What a request is answered with: `get` a row or undefined, `all` rows, `run` the changes, `open` the location,\n * `dataVersion` and `now` a number, `jsonbExtract` a boolean, the others undefined.\n */\nexport type ConnectionAnswer =\n\t| SqliteRow\n\t| SqliteRow[]\n\t| { readonly changes: number }\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| undefined;\n\n/** An own field that holds a plain value: its key, value and enumerability. */\ntype ConnectionField = readonly [string, string | number | boolean | bigint, boolean];\n\n/** A failure as it crosses from a connection's thread; see `failure` in the thread's source. */\ninterface ConnectionFailure {\n\treadonly constructor: string;\n\treadonly message: string;\n\treadonly fields: readonly ConnectionField[];\n\treadonly between?: {\n\t\treadonly fields: readonly ConnectionField[];\n\t\treadonly toString?: { readonly enumerable: boolean };\n\t};\n}\n\ninterface ConnectionReply {\n\treadonly id: number;\n\treadonly value?: ConnectionValue;\n\treadonly failure?: ConnectionFailure;\n}\n\nconst STANDARD_ERRORS: Readonly<Record<string, ErrorConstructor>> = {\n\tError,\n\tTypeError,\n\tRangeError,\n\tSyntaxError,\n\tReferenceError,\n\tEvalError,\n\tURIError,\n};\n\n/** One prototype per runtime error class seen, by what it holds: see `connectionError`. */\nconst betweenPrototypes = new Map<string, object>();\n\n/** How a runtime's error class of its own shows an error, as Bun's do: `TypeError [ERR_INVALID_ARG_VALUE]: …`. */\nfunction showWithCode(this: Error & { readonly code?: unknown }): string {\n\treturn `${this.name} [${String(this.code)}]: ${this.message}`;\n}\n\nfunction betweenPrototype(base: ErrorConstructor, between: NonNullable<ConnectionFailure[\"between\"]>): object {\n\tconst key = JSON.stringify([\n\t\tbase.name,\n\t\tbetween.fields.map(([field, value, enumerable]) => [field, String(value), enumerable]),\n\t\tbetween.toString,\n\t]);\n\tlet prototype = betweenPrototypes.get(key);\n\tif (prototype === undefined) {\n\t\tconst created: object = Object.create(base.prototype);\n\t\tfor (const [field, value, enumerable] of between.fields)\n\t\t\tObject.defineProperty(created, field, { value, enumerable, writable: true, configurable: true });\n\t\tif (between.toString !== undefined)\n\t\t\tObject.defineProperty(created, \"toString\", {\n\t\t\t\tvalue: showWithCode,\n\t\t\t\tenumerable: between.toString.enumerable,\n\t\t\t\twritable: true,\n\t\t\t\tconfigurable: true,\n\t\t\t});\n\t\tbetweenPrototypes.set(key, created);\n\t\tprototype = created;\n\t}\n\treturn prototype;\n}\n\n/**\n * The driver's error, rebuilt on the calling thread as the driver threw it: an instance of the same standard error\n * class with the same message, and the same own fields (`code`, `errcode`, `errstr` for SQLite's errors) with the same\n * enumerability. A runtime's own error class between them is stood in for by a prototype that holds the same fields and\n * shows the error the same way.\n */\nfunction connectionError(failure: ConnectionFailure): Error {\n\tconst base = STANDARD_ERRORS[failure.constructor] ?? Error;\n\tconst error = new base(failure.message);\n\tif (failure.between !== undefined) Object.setPrototypeOf(error, betweenPrototype(base, failure.between));\n\tfor (const [key, value, enumerable] of failure.fields)\n\t\tObject.defineProperty(error, key, { value, enumerable, writable: true, configurable: true });\n\treturn error;\n}\n\n/** The rows of `table`, each a plain object built the way the calling-thread connection builds them. */\nfunction rowsOf(table: RowTable): SqliteRow[] {\n\tconst { columns, values } = table;\n\treturn values.map((row) => Object.fromEntries(columns.map((column, index) => [column, row[index] as SqliteValue])));\n}\n\ninterface Waiter {\n\treadonly resolve: (value: ConnectionValue) => void;\n\treadonly reject: (error: unknown) => void;\n}\n\n/** Thrown for a request to a connection whose thread is gone: closed, or lost to an error or an exit. */\nexport class ConnectionThreadEndedError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"ConnectionThreadEndedError\";\n\t}\n}\n\n/** A node:sqlite connection running on its own worker thread. */\nexport class ThreadConnection {\n\tprivate readonly worker: Worker;\n\tprivate readonly waiting = new Map<number, Waiter>();\n\tprivate nextId = 1;\n\tprivate ended?: Error;\n\tprivate closing?: Promise<undefined>;\n\n\tprivate constructor() {\n\t\t// None of the process's own flags: an `--input-type=module` would make this CommonJS source a module, and the\n\t\t// caller's preloads would run again for every connection. Whether node:sqlite is available was settled by the\n\t\t// open before it started the thread.\n\t\tthis.worker = new Worker(CONNECTION_SOURCE, {\n\t\t\teval: true,\n\t\t\texecArgv: [],\n\t\t\tworkerData: { nowSql: `SELECT ${sqliteDialect.nowMs} AS now` },\n\t\t});\n\t\tthis.worker.on(\"message\", (reply: ConnectionReply) => this.receive(reply));\n\t\tthis.worker.on(\"error\", (error: Error) => this.end(error));\n\t\tthis.worker.on(\"exit\", (code: number) =>\n\t\t\tthis.end(new ConnectionThreadEndedError(`SQLite connection thread exited with code ${code}`)),\n\t\t);\n\t}\n\n\t/**\n\t * Opens `openAs` (or `path`) on a thread of its own and resolves with the location SQLite reports for it. A failure\n\t * to start the thread or to open the database rejects with its cause; the thread is gone then.\n\t */\n\tstatic async open(\n\t\tpath: string,\n\t\toptions: { readonly readOnly: boolean; readonly openAs?: string },\n\t): Promise<{ readonly connection: ThreadConnection; readonly location: string | null }> {\n\t\tconst connection = new ThreadConnection();\n\t\ttry {\n\t\t\tconst location = await connection.request({\n\t\t\t\tkind: \"open\",\n\t\t\t\tpath: options.openAs ?? path,\n\t\t\t\treadOnly: options.readOnly,\n\t\t\t});\n\t\t\treturn { connection, location: typeof location === \"string\" ? location : null };\n\t\t} catch (error) {\n\t\t\tawait connection.stop();\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Sends one request; resolves with the thread's answer or rejects with the driver's error, rebuilt. While a request\n\t * waits for its answer the thread keeps the process alive; an idle connection does not, as a connection on the\n\t * calling thread would not.\n\t */\n\trequest(request: ConnectionRequest): Promise<ConnectionAnswer> {\n\t\tif (request.kind === \"close\") return this.close();\n\t\tconst answer = this.send(request);\n\t\tif (request.kind === \"get\")\n\t\t\treturn answer.then((value) => (value === undefined ? undefined : rowsOf(value as RowTable)[0]));\n\t\tif (request.kind === \"all\") return answer.then((value) => rowsOf(value as RowTable));\n\t\treturn answer as Promise<ConnectionAnswer>;\n\t}\n\n\tprivate send(request: ConnectionRequest): Promise<ConnectionValue> {\n\t\treturn new Promise<ConnectionValue>((resolve, reject) => {\n\t\t\tif (this.ended !== undefined) {\n\t\t\t\treject(this.ended);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst id = this.nextId++;\n\t\t\ttry {\n\t\t\t\tthis.worker.postMessage({ id, ...request });\n\t\t\t} catch (error) {\n\t\t\t\t// A value the thread cannot receive.\n\t\t\t\treject(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.waiting.set(id, { resolve, reject });\n\t\t\tif (this.waiting.size === 1) this.worker.ref();\n\t\t});\n\t}\n\n\t/**\n\t * Closes the database on its thread, then ends the thread: a `close` request. Requests sent after it are rejected. A\n\t * thread already lost has nothing to close.\n\t */\n\tprivate close(): Promise<undefined> {\n\t\tthis.closing ??= (async () => {\n\t\t\ttry {\n\t\t\t\tif (this.ended === undefined) await this.send({ kind: \"close\" });\n\t\t\t} finally {\n\t\t\t\tawait this.stop();\n\t\t\t}\n\t\t\treturn undefined;\n\t\t})();\n\t\treturn this.closing;\n\t}\n\n\tprivate receive(reply: ConnectionReply): void {\n\t\tconst waiter = this.waiting.get(reply.id);\n\t\tif (waiter === undefined) return;\n\t\tthis.waiting.delete(reply.id);\n\t\tif (this.waiting.size === 0) this.worker.unref();\n\t\tif (reply.failure === undefined) waiter.resolve(reply.value);\n\t\telse waiter.reject(connectionError(reply.failure));\n\t}\n\n\t/** Rejects every request still waiting, oldest first, and every later one. Ending again does nothing. */\n\tprivate end(cause: Error): void {\n\t\tif (this.ended !== undefined) return;\n\t\t// Kept for as long as the connection is: an error's stack, until formatted, keeps the functions of the frames it\n\t\t// names, and so whatever they hold, such as a session that closed its store.\n\t\tvoid cause.stack;\n\t\tthis.ended = cause;\n\t\tconst waiting = [...this.waiting.values()];\n\t\tthis.waiting.clear();\n\t\tthis.worker.unref();\n\t\tfor (const waiter of waiting) waiter.reject(cause);\n\t}\n\n\tprivate async stop(): Promise<void> {\n\t\tthis.end(new ConnectionThreadEndedError(\"SQLite connection closed\"));\n\t\tawait this.worker.terminate();\n\t}\n}\n"]}
1
+ {"version":3,"file":"node-sqlite-thread.js","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite-thread.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAE7C,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAG7C;;;;;;GAMG;AACH,MAAM,iBAAiB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAkMzB,CAAC;AAiFF,MAAM,eAAe,GAA+C;IACnE,KAAK;IACL,SAAS;IACT,UAAU;IACV,WAAW;IACX,cAAc;IACd,SAAS;IACT,QAAQ;CACR,CAAC;AAEF,2FAA2F;AAC3F,MAAM,iBAAiB,GAAG,IAAI,GAAG,EAAkB,CAAC;AAEpD,kHAAkH;AAClH,SAAS,YAAY;IACpB,OAAO,GAAG,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,OAAO,EAAE,CAAC;AAC/D,CAAC;AAED,SAAS,gBAAgB,CAAC,IAAsB,EAAE,OAAkD;IACnG,MAAM,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC;QAC1B,IAAI,CAAC,IAAI;QACT,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,UAAU,CAAC,EA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AAK,EAAE,CAAC;QACpB,KAAK,MAAM,MAAM,IAAI,OAAO;YAAE,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACpD,CAAC;IAEO,KAAK,CAAC,IAAI;QACjB,IAAI,CAAC,GAAG,CAAC,IAAI,0BAA0B,CAAC,0BAA0B,CAAC,CAAC,CAAC;QACrE,MAAM,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC;IAC/B,CAAC;IAED,wFAAwF;IACxF,MAAM,CAAC,QAAoB;QAC1B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IACpC,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport type { SqliteRow, SqliteStatement, SqliteValue } from \"./database.js\";\nimport { sqliteDialect } from \"./dialect.js\";\nimport type { SqliteSequence } from \"./statement-sequence.js\";\n\n/**\n * A node:sqlite connection that runs on a worker thread of its own (#5376). The thread owns the `DatabaseSync`; the\n * calling thread sends it one request at a time and receives each answer as a message, so no statement, lock wait or\n * synced commit runs on the caller's event loop. SQLite's busy handler waits on the connection's own thread, so a\n * statement waiting for a lock that another connection of the same process holds never stops that connection from\n * finishing.\n */\nconst CONNECTION_SOURCE = `\nconst { parentPort, workerData } = require(\"node:worker_threads\");\nprocess.emitWarning = () => {};\nconst { DatabaseSync } = require(\"node:sqlite\");\nlet database;\n\nconst STANDARD_ERRORS = [Error, TypeError, RangeError, SyntaxError, ReferenceError, EvalError, URIError];\n// Bun stamps every error with where it was thrown; the caller's copy gets its own.\nconst LOCATION_FIELDS = new Set([\"stack\", \"message\", \"line\", \"column\", \"originalLine\", \"originalColumn\", \"sourceURL\"]);\n\n// An object's own fields that hold plain values, with their enumerability.\nfunction fieldsOf(object, skip) {\n\tconst fields = [];\n\tfor (const key of Object.getOwnPropertyNames(object)) {\n\t\tif (skip.has(key)) continue;\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(object, key);\n\t\tconst value = descriptor?.value;\n\t\tif (value === null || (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\" && typeof value !== \"bigint\")) continue;\n\t\tfields.push([key, value, descriptor.enumerable === true]);\n\t}\n\treturn fields;\n}\n\n// A thrown error as it crosses to the caller: the standard constructor it descends from, its message, and its own\n// fields with their enumerability. A runtime's error class of its own between the error and that constructor (Bun's\n// node:sqlite errors have one holding name, code and toString) is described by its fields and whether it has a\n// toString of its own, and how it shows.\nfunction failure(error) {\n\tif (!(error instanceof Error)) return { constructor: \"Error\", message: String(error), fields: [] };\n\tlet standard = Object.getPrototypeOf(error);\n\tlet between;\n\twhile (standard !== null && !STANDARD_ERRORS.some((each) => each.prototype === standard)) {\n\t\tif (between === undefined) {\n\t\t\tconst toString = Object.getOwnPropertyDescriptor(standard, \"toString\");\n\t\t\tbetween = {\n\t\t\t\tfields: fieldsOf(standard, new Set([\"constructor\", \"message\"])),\n\t\t\t\t...(typeof toString?.value === \"function\" ? { toString: { enumerable: toString.enumerable === true } } : {}),\n\t\t\t};\n\t\t}\n\t\tstandard = Object.getPrototypeOf(standard);\n\t}\n\treturn {\n\t\tconstructor: standard === null ? \"Error\" : standard.constructor.name,\n\t\tmessage: String(error.message),\n\t\tfields: fieldsOf(error, LOCATION_FIELDS),\n\t\t...(between === undefined ? {} : { between }),\n\t};\n}\n\nfunction statement(sql) {\n\tconst prepared = database.prepare(sql);\n\tprepared.setReadBigInts(true);\n\treturn prepared;\n}\n\n// Node 22 binds an empty Uint8Array that arrived in a message as NULL; a new empty one binds as a zero-length blob.\nfunction bind(params) {\n\treturn params.map((value) => (value instanceof Uint8Array && value.byteLength === 0 ? new Uint8Array(0) : value));\n}\n\nfunction value(each) {\n\tif (typeof each === \"bigint\") return each >= -BigInt(Number.MAX_SAFE_INTEGER) && each <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(each) : each;\n\t// A copy of its own: a view of a larger buffer would send the whole buffer.\n\treturn each instanceof Uint8Array ? new Uint8Array(each) : each;\n}\n\n// Rows cross as their column names and one array of values each, in the order the driver gives a row's fields.\nfunction table(rows) {\n\tif (rows.length === 0) return { columns: [], values: [] };\n\tconst columns = Object.keys(rows[0]);\n\treturn { columns, values: rows.map((row) => columns.map((column) => value(row[column]))) };\n}\n\nconst handlers = {\n\topen: (request) => {\n\t\tdatabase = new DatabaseSync(request.path, { readOnly: request.readOnly });\n\t\treturn database.location();\n\t},\n\texec: (request) => {\n\t\tdatabase.exec(request.sql);\n\t},\n\trun: (request) => ({ changes: Number(statement(request.sql).run(...bind(request.params)).changes) }),\n\tget: (request) => {\n\t\tconst row = statement(request.sql).get(...bind(request.params));\n\t\treturn row === undefined ? undefined : table([row]);\n\t},\n\tall: (request) => table(statement(request.sql).all(...bind(request.params))),\n\t// One non-blocking BEGIN IMMEDIATE, the connection's busy timeout restored before answering.\n\tbegin: (request) => {\n\t\t// The file's lock word (see FREE in node-sqlite-file-gate.ts): taken before BEGIN, after waiting here for a\n\t\t// statement the calling thread runs meanwhile; settleLock gives it back once the transaction ended.\n\t\tif (request.lockState !== undefined) {\n\t\t\tconst state = new Int32Array(request.lockState);\n\t\t\tfor (;;) {\n\t\t\t\tconst found = Atomics.compareExchange(state, 0, 0, request.lockTag * 4 + 2);\n\t\t\t\tif (found === 0) break;\n\t\t\t\t// Anything but a statement of the calling thread (1) is another holder: a lock taken, as BEGIN would find.\n\t\t\t\tif (found !== 1)\n\t\t\t\t\tthrow Object.assign(new Error(\"database is locked\"), { code: \"ERR_SQLITE_ERROR\", errcode: 5, errstr: \"database is locked\" });\n\t\t\t\tAtomics.wait(state, 0, 1, 50);\n\t\t\t}\n\t\t\tAtomics.notify(state, 0);\n\t\t\tlockState = { state, held: request.lockTag * 4 + 3 };\n\t\t}\n\t\tconst configured = Number(database.prepare(\"PRAGMA busy_timeout\").get()?.timeout ?? 0);\n\t\tdatabase.exec(\"PRAGMA busy_timeout=0\");\n\t\tlet began = false;\n\t\ttry {\n\t\t\tdatabase.exec(\"BEGIN IMMEDIATE\");\n\t\t\tbegan = true;\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tdatabase.exec(\"PRAGMA busy_timeout=\" + configured);\n\t\t\t} catch (restoreFailure) {\n\t\t\t\tif (began) database.exec(\"ROLLBACK\");\n\t\t\t\tthrow restoreFailure;\n\t\t\t}\n\t\t}\n\t},\n\t// \\`repeat\\`, then each statement, in one request: the statements the caller would send one at a time, in the same\n\t// order, each prepared when it is reached. The caller's abort flag is read where the caller would check its signal.\n\tsequence: (request) => {\n\t\tconst abort = request.abort === undefined ? undefined : new Int32Array(request.abort);\n\t\tconst aborted = () => abort !== undefined && Atomics.load(abort, 0) !== 0;\n\t\tlet repeated = 0;\n\t\tif (request.repeat !== undefined) {\n\t\t\tconst { statement: repeat, times, minChanges } = request.repeat;\n\t\t\twhile (repeated < times) {\n\t\t\t\tif (aborted()) return { aborted: true };\n\t\t\t\tconst before = Number(statement(\"SELECT total_changes() AS changes\").get().changes);\n\t\t\t\tstatement(repeat.sql).run(...bind(repeat.params));\n\t\t\t\tconst after = Number(statement(\"SELECT total_changes() AS changes\").get().changes);\n\t\t\t\tif (after - before < minChanges) break;\n\t\t\t\trepeated++;\n\t\t\t}\n\t\t}\n\t\tfor (const { sql, params } of request.statements) {\n\t\t\tif (aborted()) return { aborted: true };\n\t\t\tstatement(sql).run(...bind(params));\n\t\t}\n\t\treturn { repeated };\n\t},\n\tdataVersion: () => Number(database.prepare(\"PRAGMA data_version\").get()?.data_version ?? 0),\n\tnow: () => Number(database.prepare(workerData.nowSql).get().now),\n\tjsonbExtract: () => {\n\t\ttry {\n\t\t\tstatement(\"SELECT jsonb_extract('[]', '$')\");\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"no such function: jsonb_extract\") return false;\n\t\t\tthrow error;\n\t\t}\n\t},\n\tclose: () => {\n\t\tdatabase?.close();\n\t\tglobalThis.Bun?.gc?.(true);\n\t},\n};\n\n// The file's lock word while this connection takes or holds the lock: held while a transaction is open on it, given\n// back (and the waiting threads woken) once none is, before the request that ended it is answered.\nlet lockState;\n\nfunction settleLock() {\n\tif (lockState === undefined) return;\n\tconst { state, held } = lockState;\n\tlet open = false;\n\ttry {\n\t\topen = database?.isTransaction === true;\n\t} catch {}\n\tif (open) {\n\t\tif (Atomics.compareExchange(state, 0, held - 1, held) === held - 1) Atomics.notify(state, 0);\n\t\treturn;\n\t}\n\tlockState = undefined;\n\tif (Atomics.compareExchange(state, 0, held, 0) === held || Atomics.compareExchange(state, 0, held - 1, 0) === held - 1)\n\t\tAtomics.notify(state, 0);\n}\n\nfunction handle(request) {\n\ttry {\n\t\treturn handlers[request.kind](request);\n\t} finally {\n\t\tsettleLock();\n\t}\n}\n\nparentPort.on(\"message\", (request) => {\n\ttry {\n\t\tparentPort.postMessage({ id: request.id, value: handle(request) });\n\t} catch (error) {\n\t\tparentPort.postMessage({ id: request.id, failure: failure(error) });\n\t}\n});\n`;\n\n/**\n * Statements sent as one request (see `SqliteSequence`). `abort` holds one `Int32` the caller sets to non-zero when its\n * signal aborts: the thread reads it before each run of `repeat` and before each statement.\n */\nexport interface SequenceRequest {\n\treadonly kind: \"sequence\";\n\treadonly repeat?: SqliteSequence[\"repeat\"];\n\treadonly statements: readonly SqliteStatement[];\n\treadonly abort?: SharedArrayBuffer;\n}\n\n/**\n * What a sequence request is answered with: how many runs of `repeat` changed `minChanges` rows or more, or that it\n * stopped because the caller's signal aborted.\n */\nexport type SequenceAnswer = { readonly repeated: number } | { readonly aborted: true };\n\n/** What a connection's thread is asked to do; each request is answered once, in the order it was sent. */\nexport type ConnectionRequest =\n\t| { readonly kind: \"open\"; readonly path: string; readonly readOnly: boolean }\n\t| { readonly kind: \"exec\"; readonly sql: string }\n\t| { readonly kind: \"run\" | \"get\" | \"all\"; readonly sql: string; readonly params: readonly SqliteValue[] }\n\t| { readonly kind: \"begin\"; readonly lockState?: SharedArrayBuffer; readonly lockTag?: number }\n\t| { readonly kind: \"dataVersion\" | \"now\" | \"jsonbExtract\" | \"close\" }\n\t| SequenceRequest;\n\n/** Rows as they cross from a connection's thread: the column names, then each row's values in their order. */\ninterface RowTable {\n\treadonly columns: readonly string[];\n\treadonly values: readonly (readonly SqliteValue[])[];\n}\n\n/** What a request's answer carries as it crosses, before rows are rebuilt. */\ntype ConnectionValue =\n\t| RowTable\n\t| { readonly changes: number }\n\t| SequenceAnswer\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| undefined;\n\n/**\n * What a request is answered with: `get` a row or undefined, `all` rows, `run` the changes, `sequence` a\n * `SequenceAnswer`, `open` the location, `dataVersion` and `now` a number, `jsonbExtract` a boolean, the others\n * undefined.\n */\nexport type ConnectionAnswer =\n\t| SqliteRow\n\t| SqliteRow[]\n\t| { readonly changes: number }\n\t| SequenceAnswer\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| undefined;\n\n/** An own field that holds a plain value: its key, value and enumerability. */\ntype ConnectionField = readonly [string, string | number | boolean | bigint, boolean];\n\n/** A failure as it crosses from a connection's thread; see `failure` in the thread's source. */\ninterface ConnectionFailure {\n\treadonly constructor: string;\n\treadonly message: string;\n\treadonly fields: readonly ConnectionField[];\n\treadonly between?: {\n\t\treadonly fields: readonly ConnectionField[];\n\t\treadonly toString?: { readonly enumerable: boolean };\n\t};\n}\n\ninterface ConnectionReply {\n\treadonly id: number;\n\treadonly value?: ConnectionValue;\n\treadonly failure?: ConnectionFailure;\n}\n\nconst STANDARD_ERRORS: Readonly<Record<string, ErrorConstructor>> = {\n\tError,\n\tTypeError,\n\tRangeError,\n\tSyntaxError,\n\tReferenceError,\n\tEvalError,\n\tURIError,\n};\n\n/** One prototype per runtime error class seen, by what it holds: see `connectionError`. */\nconst betweenPrototypes = new Map<string, object>();\n\n/** How a runtime's error class of its own shows an error, as Bun's do: `TypeError [ERR_INVALID_ARG_VALUE]: …`. */\nfunction showWithCode(this: Error & { readonly code?: unknown }): string {\n\treturn `${this.name} [${String(this.code)}]: ${this.message}`;\n}\n\nfunction betweenPrototype(base: ErrorConstructor, between: NonNullable<ConnectionFailure[\"between\"]>): object {\n\tconst key = JSON.stringify([\n\t\tbase.name,\n\t\tbetween.fields.map(([field, value, enumerable]) => [field, String(value), enumerable]),\n\t\tbetween.toString,\n\t]);\n\tlet prototype = betweenPrototypes.get(key);\n\tif (prototype === undefined) {\n\t\tconst created: object = Object.create(base.prototype);\n\t\tfor (const [field, value, enumerable] of between.fields)\n\t\t\tObject.defineProperty(created, field, { value, enumerable, writable: true, configurable: true });\n\t\tif (between.toString !== undefined)\n\t\t\tObject.defineProperty(created, \"toString\", {\n\t\t\t\tvalue: showWithCode,\n\t\t\t\tenumerable: between.toString.enumerable,\n\t\t\t\twritable: true,\n\t\t\t\tconfigurable: true,\n\t\t\t});\n\t\tbetweenPrototypes.set(key, created);\n\t\tprototype = created;\n\t}\n\treturn prototype;\n}\n\n/**\n * The driver's error, rebuilt on the calling thread as the driver threw it: an instance of the same standard error\n * class with the same message, and the same own fields (`code`, `errcode`, `errstr` for SQLite's errors) with the same\n * enumerability. A runtime's own error class between them is stood in for by a prototype that holds the same fields and\n * shows the error the same way.\n */\nfunction connectionError(failure: ConnectionFailure): Error {\n\tconst base = STANDARD_ERRORS[failure.constructor] ?? Error;\n\tconst error = new base(failure.message);\n\tif (failure.between !== undefined) Object.setPrototypeOf(error, betweenPrototype(base, failure.between));\n\tfor (const [key, value, enumerable] of failure.fields)\n\t\tObject.defineProperty(error, key, { value, enumerable, writable: true, configurable: true });\n\treturn error;\n}\n\n/** The rows of `table`, each a plain object built the way the calling-thread connection builds them. */\nfunction rowsOf(table: RowTable): SqliteRow[] {\n\tconst { columns, values } = table;\n\treturn values.map((row) => Object.fromEntries(columns.map((column, index) => [column, row[index] as SqliteValue])));\n}\n\ninterface Waiter {\n\treadonly resolve: (value: ConnectionValue) => void;\n\treadonly reject: (error: unknown) => void;\n}\n\n/** Thrown for a request to a connection whose thread is gone: closed, or lost to an error or an exit. */\nexport class ConnectionThreadEndedError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"ConnectionThreadEndedError\";\n\t}\n}\n\n/** A node:sqlite connection running on its own worker thread. */\nexport class ThreadConnection {\n\tprivate readonly worker: Worker;\n\tprivate readonly waiting = new Map<number, Waiter>();\n\tprivate nextId = 1;\n\tprivate ended?: Error;\n\tprivate closing?: Promise<undefined>;\n\n\tprivate constructor() {\n\t\t// None of the process's own flags: an `--input-type=module` would make this CommonJS source a module, and the\n\t\t// caller's preloads would run again for every connection. Whether node:sqlite is available was settled by the\n\t\t// open before it started the thread.\n\t\tthis.worker = new Worker(CONNECTION_SOURCE, {\n\t\t\teval: true,\n\t\t\texecArgv: [],\n\t\t\tworkerData: { nowSql: `SELECT ${sqliteDialect.nowMs} AS now` },\n\t\t});\n\t\tthis.worker.on(\"message\", (reply: ConnectionReply) => this.receive(reply));\n\t\tthis.worker.on(\"error\", (error: Error) => this.end(error));\n\t\tthis.worker.on(\"exit\", (code: number) =>\n\t\t\tthis.end(new ConnectionThreadEndedError(`SQLite connection thread exited with code ${code}`)),\n\t\t);\n\t}\n\n\t/**\n\t * Opens `openAs` (or `path`) on a thread of its own and resolves with the location SQLite reports for it. A failure\n\t * to start the thread or to open the database rejects with its cause; the thread is gone then.\n\t */\n\tstatic async open(\n\t\tpath: string,\n\t\toptions: { readonly readOnly: boolean; readonly openAs?: string },\n\t): Promise<{ readonly connection: ThreadConnection; readonly location: string | null }> {\n\t\tconst connection = new ThreadConnection();\n\t\ttry {\n\t\t\tconst location = await connection.request({\n\t\t\t\tkind: \"open\",\n\t\t\t\tpath: options.openAs ?? path,\n\t\t\t\treadOnly: options.readOnly,\n\t\t\t});\n\t\t\treturn { connection, location: typeof location === \"string\" ? location : null };\n\t\t} catch (error) {\n\t\t\tawait connection.stop();\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Sends one request; resolves with the thread's answer or rejects with the driver's error, rebuilt. While a request\n\t * waits for its answer the thread keeps the process alive; an idle connection does not, as a connection on the\n\t * calling thread would not.\n\t */\n\trequest(request: ConnectionRequest): Promise<ConnectionAnswer> {\n\t\tif (request.kind === \"close\") return this.close();\n\t\tconst answer = this.send(request);\n\t\tif (request.kind === \"get\")\n\t\t\treturn answer.then((value) => (value === undefined ? undefined : rowsOf(value as RowTable)[0]));\n\t\tif (request.kind === \"all\") return answer.then((value) => rowsOf(value as RowTable));\n\t\treturn answer as Promise<ConnectionAnswer>;\n\t}\n\n\tprivate send(request: ConnectionRequest): Promise<ConnectionValue> {\n\t\treturn new Promise<ConnectionValue>((resolve, reject) => {\n\t\t\tif (this.ended !== undefined) {\n\t\t\t\treject(this.ended);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst id = this.nextId++;\n\t\t\ttry {\n\t\t\t\tthis.worker.postMessage({ id, ...request });\n\t\t\t} catch (error) {\n\t\t\t\t// A value the thread cannot receive.\n\t\t\t\treject(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.waiting.set(id, { resolve, reject });\n\t\t\tif (this.waiting.size === 1) this.worker.ref();\n\t\t});\n\t}\n\n\t/**\n\t * Closes the database on its thread, then ends the thread: a `close` request. Requests sent after it are rejected. A\n\t * thread already lost has nothing to close.\n\t */\n\tprivate close(): Promise<undefined> {\n\t\tthis.closing ??= (async () => {\n\t\t\ttry {\n\t\t\t\tif (this.ended === undefined) await this.send({ kind: \"close\" });\n\t\t\t} finally {\n\t\t\t\tawait this.stop();\n\t\t\t}\n\t\t\treturn undefined;\n\t\t})();\n\t\treturn this.closing;\n\t}\n\n\tprivate receive(reply: ConnectionReply): void {\n\t\tconst waiter = this.waiting.get(reply.id);\n\t\tif (waiter === undefined) return;\n\t\tthis.waiting.delete(reply.id);\n\t\tif (this.waiting.size === 0) this.worker.unref();\n\t\tif (reply.failure === undefined) waiter.resolve(reply.value);\n\t\telse waiter.reject(connectionError(reply.failure));\n\t}\n\n\t/** Rejects every request still waiting, oldest first, and every later one. Ending again does nothing. */\n\tprivate end(cause: Error): void {\n\t\tif (this.ended !== undefined) return;\n\t\t// Kept for as long as the connection is: an error's stack, until formatted, keeps the functions of the frames it\n\t\t// names, and so whatever they hold, such as a session that closed its store.\n\t\tvoid cause.stack;\n\t\tthis.ended = cause;\n\t\tconst waiting = [...this.waiting.values()];\n\t\tthis.waiting.clear();\n\t\tthis.worker.unref();\n\t\tfor (const waiter of waiting) waiter.reject(cause);\n\t}\n\n\tprivate async stop(): Promise<void> {\n\t\tthis.end(new ConnectionThreadEndedError(\"SQLite connection closed\"));\n\t\tawait this.worker.terminate();\n\t}\n\n\t/** Calls `listener` once the connection's thread has exited, whether closed or lost. */\n\tonExit(listener: () => void): void {\n\t\tthis.worker.once(\"exit\", listener);\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"node-sqlite.d.ts","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite.ts"],"names":[],"mappings":"AA4BA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAKhD,OAAO,KAAK,EACX,cAAc,EAMd,MAAM,eAAe,CAAC;AAEvB,OAAO,EAaN,+BAA+B,EAI/B,MAAM,aAAa,CAAC;AAumBrB,wBAAgB,kBAAkB,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAE/D;AAmYD;;;;GAIG;AACH,eAAO,MAAM,4BAA4B,MAAM,CAAC;AA0BhD,mHAAmH;AACnH,MAAM,WAAW,gBAAgB;IAChC,sHAAsH;IACtH,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,oHAAoH;IACpH,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,wGAAwG;IACxG,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,0FAA0F;IAC1F,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,6DAA6D;IAC7D,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;CAClC;AAg3BD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,Q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