@metamask-previews/wallet-cli 0.0.0-preview-8bfa290fb → 0.0.0-preview-e8a256c39

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 (264) hide show
  1. package/CHANGELOG.md +8 -4
  2. package/dist/commands/daemon/{call.d.mts → call.d.ts} +2 -2
  3. package/dist/commands/daemon/call.d.ts.map +1 -0
  4. package/dist/commands/daemon/{call.mjs → call.js} +30 -31
  5. package/dist/commands/daemon/call.js.map +1 -0
  6. package/dist/commands/daemon/{list.d.cts → list.d.ts} +2 -2
  7. package/dist/commands/daemon/list.d.ts.map +1 -0
  8. package/dist/commands/daemon/{list.mjs → list.js} +9 -10
  9. package/dist/commands/daemon/list.js.map +1 -0
  10. package/dist/commands/daemon/{purge.d.cts → purge.d.ts} +2 -2
  11. package/dist/commands/daemon/purge.d.ts.map +1 -0
  12. package/dist/commands/daemon/{purge.mjs → purge.js} +19 -20
  13. package/dist/commands/daemon/purge.js.map +1 -0
  14. package/dist/commands/daemon/{start.d.cts → start.d.ts} +2 -2
  15. package/dist/commands/daemon/start.d.ts.map +1 -0
  16. package/dist/commands/daemon/start.js +49 -0
  17. package/dist/commands/daemon/{start.cjs.map → start.js.map} +1 -1
  18. package/dist/commands/daemon/{status.d.cts → status.d.ts} +2 -2
  19. package/dist/commands/daemon/status.d.ts.map +1 -0
  20. package/dist/commands/daemon/{status.mjs → status.js} +10 -11
  21. package/dist/commands/daemon/status.js.map +1 -0
  22. package/dist/commands/daemon/{stop.d.cts → stop.d.ts} +2 -2
  23. package/dist/commands/daemon/stop.d.ts.map +1 -0
  24. package/dist/commands/daemon/{stop.mjs → stop.js} +9 -10
  25. package/dist/commands/daemon/stop.js.map +1 -0
  26. package/dist/commands/wallet/{send.d.cts → send.d.ts} +3 -3
  27. package/dist/commands/wallet/send.d.ts.map +1 -0
  28. package/dist/commands/wallet/{send.mjs → send.js} +111 -123
  29. package/dist/commands/wallet/send.js.map +1 -0
  30. package/dist/commands/wallet/{unlock.d.cts → unlock.d.ts} +2 -2
  31. package/dist/commands/wallet/unlock.d.ts.map +1 -0
  32. package/dist/commands/wallet/{unlock.mjs → unlock.js} +29 -30
  33. package/dist/commands/wallet/unlock.js.map +1 -0
  34. package/dist/daemon/{auto-approval.d.mts → auto-approval.d.ts} +3 -3
  35. package/dist/daemon/auto-approval.d.ts.map +1 -0
  36. package/dist/daemon/{auto-approval.mjs → auto-approval.js} +1 -1
  37. package/dist/daemon/auto-approval.js.map +1 -0
  38. package/dist/daemon/{daemon-client.d.mts → daemon-client.d.ts} +2 -2
  39. package/dist/daemon/daemon-client.d.ts.map +1 -0
  40. package/dist/daemon/{daemon-client.mjs → daemon-client.js} +8 -8
  41. package/dist/daemon/daemon-client.js.map +1 -0
  42. package/dist/daemon/daemon-entry.d.ts +2 -0
  43. package/dist/daemon/daemon-entry.d.ts.map +1 -0
  44. package/dist/daemon/{daemon-entry.mjs → daemon-entry.js} +12 -12
  45. package/dist/daemon/daemon-entry.js.map +1 -0
  46. package/dist/daemon/{daemon-spawn.d.mts → daemon-spawn.d.ts} +2 -2
  47. package/dist/daemon/daemon-spawn.d.ts.map +1 -0
  48. package/dist/daemon/{daemon-spawn.mjs → daemon-spawn.js} +7 -7
  49. package/dist/daemon/daemon-spawn.js.map +1 -0
  50. package/dist/daemon/{data-dir.d.cts → data-dir.d.ts} +1 -1
  51. package/dist/daemon/data-dir.d.ts.map +1 -0
  52. package/dist/daemon/{data-dir.mjs → data-dir.js} +3 -3
  53. package/dist/daemon/data-dir.js.map +1 -0
  54. package/dist/daemon/{paths.d.mts → paths.d.ts} +2 -2
  55. package/dist/daemon/paths.d.ts.map +1 -0
  56. package/dist/daemon/{paths.mjs → paths.js} +2 -2
  57. package/dist/daemon/paths.js.map +1 -0
  58. package/dist/daemon/{prompts.d.cts → prompts.d.ts} +1 -1
  59. package/dist/daemon/prompts.d.ts.map +1 -0
  60. package/dist/daemon/{prompts.mjs → prompts.js} +4 -4
  61. package/dist/daemon/prompts.js.map +1 -0
  62. package/dist/daemon/{rpc-socket-server.d.cts → rpc-socket-server.d.ts} +2 -2
  63. package/dist/daemon/rpc-socket-server.d.ts.map +1 -0
  64. package/dist/daemon/{rpc-socket-server.mjs → rpc-socket-server.js} +8 -8
  65. package/dist/daemon/rpc-socket-server.js.map +1 -0
  66. package/dist/daemon/{secrets.d.cts → secrets.d.ts} +1 -1
  67. package/dist/daemon/secrets.d.ts.map +1 -0
  68. package/dist/daemon/{secrets.mjs → secrets.js} +11 -23
  69. package/dist/daemon/secrets.js.map +1 -0
  70. package/dist/daemon/{send-transaction.d.cts → send-transaction.d.ts} +9 -9
  71. package/dist/daemon/send-transaction.d.ts.map +1 -0
  72. package/dist/daemon/{send-transaction.mjs → send-transaction.js} +3 -3
  73. package/dist/daemon/send-transaction.js.map +1 -0
  74. package/dist/daemon/{socket-line.d.cts → socket-line.d.ts} +2 -5
  75. package/dist/daemon/socket-line.d.ts.map +1 -0
  76. package/dist/daemon/{socket-line.mjs → socket-line.js} +1 -1
  77. package/dist/daemon/socket-line.js.map +1 -0
  78. package/dist/daemon/{stop-daemon.d.cts → stop-daemon.d.ts} +1 -1
  79. package/dist/daemon/stop-daemon.d.ts.map +1 -0
  80. package/dist/daemon/{stop-daemon.mjs → stop-daemon.js} +7 -7
  81. package/dist/daemon/stop-daemon.js.map +1 -0
  82. package/dist/daemon/{types.d.cts → types.d.ts} +4 -4
  83. package/dist/daemon/types.d.ts.map +1 -0
  84. package/dist/daemon/{types.mjs → types.js} +1 -1
  85. package/dist/daemon/types.js.map +1 -0
  86. package/dist/daemon/{utils.d.cts → utils.d.ts} +2 -3
  87. package/dist/daemon/utils.d.ts.map +1 -0
  88. package/dist/daemon/{utils.mjs → utils.js} +3 -3
  89. package/dist/daemon/utils.js.map +1 -0
  90. package/dist/daemon/{wallet-factory.d.cts → wallet-factory.d.ts} +4 -4
  91. package/dist/daemon/wallet-factory.d.ts.map +1 -0
  92. package/dist/daemon/{wallet-factory.mjs → wallet-factory.js} +12 -12
  93. package/dist/daemon/wallet-factory.js.map +1 -0
  94. package/dist/persistence/{KeyValueStore.d.cts → KeyValueStore.d.ts} +2 -2
  95. package/dist/persistence/KeyValueStore.d.ts.map +1 -0
  96. package/dist/persistence/KeyValueStore.js +59 -0
  97. package/dist/persistence/KeyValueStore.js.map +1 -0
  98. package/dist/persistence/{persistence.d.cts → persistence.d.ts} +5 -5
  99. package/dist/persistence/persistence.d.ts.map +1 -0
  100. package/dist/persistence/{persistence.mjs → persistence.js} +2 -2
  101. package/dist/persistence/persistence.js.map +1 -0
  102. package/dist/test/{run-command.d.cts → run-command.d.ts} +4 -4
  103. package/dist/test/run-command.d.ts.map +1 -0
  104. package/dist/test/{run-command.mjs → run-command.js} +3 -3
  105. package/dist/test/run-command.js.map +1 -0
  106. package/package.json +19 -15
  107. package/dist/commands/daemon/call.cjs +0 -79
  108. package/dist/commands/daemon/call.cjs.map +0 -1
  109. package/dist/commands/daemon/call.d.cts +0 -14
  110. package/dist/commands/daemon/call.d.cts.map +0 -1
  111. package/dist/commands/daemon/call.d.mts.map +0 -1
  112. package/dist/commands/daemon/call.mjs.map +0 -1
  113. package/dist/commands/daemon/list.cjs +0 -48
  114. package/dist/commands/daemon/list.cjs.map +0 -1
  115. package/dist/commands/daemon/list.d.cts.map +0 -1
  116. package/dist/commands/daemon/list.d.mts +0 -7
  117. package/dist/commands/daemon/list.d.mts.map +0 -1
  118. package/dist/commands/daemon/list.mjs.map +0 -1
  119. package/dist/commands/daemon/purge.cjs +0 -58
  120. package/dist/commands/daemon/purge.cjs.map +0 -1
  121. package/dist/commands/daemon/purge.d.cts.map +0 -1
  122. package/dist/commands/daemon/purge.d.mts +0 -10
  123. package/dist/commands/daemon/purge.d.mts.map +0 -1
  124. package/dist/commands/daemon/purge.mjs.map +0 -1
  125. package/dist/commands/daemon/start.cjs +0 -52
  126. package/dist/commands/daemon/start.d.cts.map +0 -1
  127. package/dist/commands/daemon/start.d.mts +0 -12
  128. package/dist/commands/daemon/start.d.mts.map +0 -1
  129. package/dist/commands/daemon/start.mjs +0 -50
  130. package/dist/commands/daemon/start.mjs.map +0 -1
  131. package/dist/commands/daemon/status.cjs +0 -59
  132. package/dist/commands/daemon/status.cjs.map +0 -1
  133. package/dist/commands/daemon/status.d.cts.map +0 -1
  134. package/dist/commands/daemon/status.d.mts +0 -7
  135. package/dist/commands/daemon/status.d.mts.map +0 -1
  136. package/dist/commands/daemon/status.mjs.map +0 -1
  137. package/dist/commands/daemon/stop.cjs +0 -26
  138. package/dist/commands/daemon/stop.cjs.map +0 -1
  139. package/dist/commands/daemon/stop.d.cts.map +0 -1
  140. package/dist/commands/daemon/stop.d.mts +0 -7
  141. package/dist/commands/daemon/stop.d.mts.map +0 -1
  142. package/dist/commands/daemon/stop.mjs.map +0 -1
  143. package/dist/commands/wallet/send.cjs +0 -332
  144. package/dist/commands/wallet/send.cjs.map +0 -1
  145. package/dist/commands/wallet/send.d.cts.map +0 -1
  146. package/dist/commands/wallet/send.d.mts +0 -42
  147. package/dist/commands/wallet/send.d.mts.map +0 -1
  148. package/dist/commands/wallet/send.mjs.map +0 -1
  149. package/dist/commands/wallet/unlock.cjs +0 -75
  150. package/dist/commands/wallet/unlock.cjs.map +0 -1
  151. package/dist/commands/wallet/unlock.d.cts.map +0 -1
  152. package/dist/commands/wallet/unlock.d.mts +0 -11
  153. package/dist/commands/wallet/unlock.d.mts.map +0 -1
  154. package/dist/commands/wallet/unlock.mjs.map +0 -1
  155. package/dist/daemon/auto-approval.cjs +0 -86
  156. package/dist/daemon/auto-approval.cjs.map +0 -1
  157. package/dist/daemon/auto-approval.d.cts +0 -22
  158. package/dist/daemon/auto-approval.d.cts.map +0 -1
  159. package/dist/daemon/auto-approval.d.mts.map +0 -1
  160. package/dist/daemon/auto-approval.mjs.map +0 -1
  161. package/dist/daemon/daemon-client.cjs +0 -149
  162. package/dist/daemon/daemon-client.cjs.map +0 -1
  163. package/dist/daemon/daemon-client.d.cts +0 -84
  164. package/dist/daemon/daemon-client.d.cts.map +0 -1
  165. package/dist/daemon/daemon-client.d.mts.map +0 -1
  166. package/dist/daemon/daemon-client.mjs.map +0 -1
  167. package/dist/daemon/daemon-entry.cjs +0 -278
  168. package/dist/daemon/daemon-entry.cjs.map +0 -1
  169. package/dist/daemon/daemon-entry.d.cts +0 -2
  170. package/dist/daemon/daemon-entry.d.cts.map +0 -1
  171. package/dist/daemon/daemon-entry.d.mts +0 -2
  172. package/dist/daemon/daemon-entry.d.mts.map +0 -1
  173. package/dist/daemon/daemon-entry.mjs.map +0 -1
  174. package/dist/daemon/daemon-spawn.cjs +0 -138
  175. package/dist/daemon/daemon-spawn.cjs.map +0 -1
  176. package/dist/daemon/daemon-spawn.d.cts +0 -28
  177. package/dist/daemon/daemon-spawn.d.cts.map +0 -1
  178. package/dist/daemon/daemon-spawn.d.mts.map +0 -1
  179. package/dist/daemon/daemon-spawn.mjs.map +0 -1
  180. package/dist/daemon/data-dir.cjs +0 -23
  181. package/dist/daemon/data-dir.cjs.map +0 -1
  182. package/dist/daemon/data-dir.d.cts.map +0 -1
  183. package/dist/daemon/data-dir.d.mts +0 -14
  184. package/dist/daemon/data-dir.d.mts.map +0 -1
  185. package/dist/daemon/data-dir.mjs.map +0 -1
  186. package/dist/daemon/paths.cjs +0 -20
  187. package/dist/daemon/paths.cjs.map +0 -1
  188. package/dist/daemon/paths.d.cts +0 -9
  189. package/dist/daemon/paths.d.cts.map +0 -1
  190. package/dist/daemon/paths.d.mts.map +0 -1
  191. package/dist/daemon/paths.mjs.map +0 -1
  192. package/dist/daemon/prompts.cjs +0 -55
  193. package/dist/daemon/prompts.cjs.map +0 -1
  194. package/dist/daemon/prompts.d.cts.map +0 -1
  195. package/dist/daemon/prompts.d.mts +0 -31
  196. package/dist/daemon/prompts.d.mts.map +0 -1
  197. package/dist/daemon/prompts.mjs.map +0 -1
  198. package/dist/daemon/rpc-socket-server.cjs +0 -284
  199. package/dist/daemon/rpc-socket-server.cjs.map +0 -1
  200. package/dist/daemon/rpc-socket-server.d.cts.map +0 -1
  201. package/dist/daemon/rpc-socket-server.d.mts +0 -44
  202. package/dist/daemon/rpc-socket-server.d.mts.map +0 -1
  203. package/dist/daemon/rpc-socket-server.mjs.map +0 -1
  204. package/dist/daemon/secrets.cjs +0 -137
  205. package/dist/daemon/secrets.cjs.map +0 -1
  206. package/dist/daemon/secrets.d.cts.map +0 -1
  207. package/dist/daemon/secrets.d.mts +0 -72
  208. package/dist/daemon/secrets.d.mts.map +0 -1
  209. package/dist/daemon/secrets.mjs.map +0 -1
  210. package/dist/daemon/send-transaction.cjs +0 -147
  211. package/dist/daemon/send-transaction.cjs.map +0 -1
  212. package/dist/daemon/send-transaction.d.cts.map +0 -1
  213. package/dist/daemon/send-transaction.d.mts +0 -102
  214. package/dist/daemon/send-transaction.d.mts.map +0 -1
  215. package/dist/daemon/send-transaction.mjs.map +0 -1
  216. package/dist/daemon/socket-line.cjs +0 -93
  217. package/dist/daemon/socket-line.cjs.map +0 -1
  218. package/dist/daemon/socket-line.d.cts.map +0 -1
  219. package/dist/daemon/socket-line.d.mts +0 -21
  220. package/dist/daemon/socket-line.d.mts.map +0 -1
  221. package/dist/daemon/socket-line.mjs.map +0 -1
  222. package/dist/daemon/stop-daemon.cjs +0 -117
  223. package/dist/daemon/stop-daemon.cjs.map +0 -1
  224. package/dist/daemon/stop-daemon.d.cts.map +0 -1
  225. package/dist/daemon/stop-daemon.d.mts +0 -28
  226. package/dist/daemon/stop-daemon.d.mts.map +0 -1
  227. package/dist/daemon/stop-daemon.mjs.map +0 -1
  228. package/dist/daemon/types.cjs +0 -20
  229. package/dist/daemon/types.cjs.map +0 -1
  230. package/dist/daemon/types.d.cts.map +0 -1
  231. package/dist/daemon/types.d.mts +0 -94
  232. package/dist/daemon/types.d.mts.map +0 -1
  233. package/dist/daemon/types.mjs.map +0 -1
  234. package/dist/daemon/utils.cjs +0 -172
  235. package/dist/daemon/utils.cjs.map +0 -1
  236. package/dist/daemon/utils.d.cts.map +0 -1
  237. package/dist/daemon/utils.d.mts +0 -87
  238. package/dist/daemon/utils.d.mts.map +0 -1
  239. package/dist/daemon/utils.mjs.map +0 -1
  240. package/dist/daemon/wallet-factory.cjs +0 -341
  241. package/dist/daemon/wallet-factory.cjs.map +0 -1
  242. package/dist/daemon/wallet-factory.d.cts.map +0 -1
  243. package/dist/daemon/wallet-factory.d.mts +0 -64
  244. package/dist/daemon/wallet-factory.d.mts.map +0 -1
  245. package/dist/daemon/wallet-factory.mjs.map +0 -1
  246. package/dist/persistence/KeyValueStore.cjs +0 -79
  247. package/dist/persistence/KeyValueStore.cjs.map +0 -1
  248. package/dist/persistence/KeyValueStore.d.cts.map +0 -1
  249. package/dist/persistence/KeyValueStore.d.mts +0 -18
  250. package/dist/persistence/KeyValueStore.d.mts.map +0 -1
  251. package/dist/persistence/KeyValueStore.mjs +0 -79
  252. package/dist/persistence/KeyValueStore.mjs.map +0 -1
  253. package/dist/persistence/persistence.cjs +0 -204
  254. package/dist/persistence/persistence.cjs.map +0 -1
  255. package/dist/persistence/persistence.d.cts.map +0 -1
  256. package/dist/persistence/persistence.d.mts +0 -45
  257. package/dist/persistence/persistence.d.mts.map +0 -1
  258. package/dist/persistence/persistence.mjs.map +0 -1
  259. package/dist/test/run-command.cjs +0 -73
  260. package/dist/test/run-command.cjs.map +0 -1
  261. package/dist/test/run-command.d.cts.map +0 -1
  262. package/dist/test/run-command.d.mts +0 -27
  263. package/dist/test/run-command.d.mts.map +0 -1
  264. package/dist/test/run-command.mjs.map +0 -1
@@ -1,6 +1,6 @@
1
- import { rm } from "node:fs/promises";
2
- import { pingDaemon, sendCommand } from "./daemon-client.mjs";
3
- import { isProcessAlive, readPidFile, sendSignal, waitFor } from "./utils.mjs";
1
+ import { rm } from 'node:fs/promises';
2
+ import { pingDaemon, sendCommand } from './daemon-client.js';
3
+ import { isProcessAlive, readPidFile, sendSignal, waitFor } from './utils.js';
4
4
  /**
5
5
  * Stop the daemon, preferring a graceful shutdown.
6
6
  *
@@ -55,7 +55,7 @@ export async function stopDaemon(socketPath, pidPath, log) {
55
55
  // pid to be gone too, so a daemon that outlived its socket falls through to
56
56
  // SIGTERM/SIGKILL rather than being orphaned.
57
57
  stopped = await waitFor(async () => (await pingDaemon(socketPath)).status !== 'responsive' &&
58
- (pid === undefined || !isProcessAlive(pid)), 5000);
58
+ (pid === undefined || !isProcessAlive(pid)), 5_000);
59
59
  }
60
60
  // Strategy 2: SIGTERM. Signal when either the socket was observed or the
61
61
  // recorded PID is alive; the absent+alive case typically means someone
@@ -66,7 +66,7 @@ export async function stopDaemon(socketPath, pidPath, log) {
66
66
  }
67
67
  try {
68
68
  if (sendSignal(pid, 'SIGTERM')) {
69
- stopped = await waitFor(() => !isProcessAlive(pid), 5000);
69
+ stopped = await waitFor(() => !isProcessAlive(pid), 5_000);
70
70
  }
71
71
  else {
72
72
  stopped = true; // Process already gone (ESRCH).
@@ -80,7 +80,7 @@ export async function stopDaemon(socketPath, pidPath, log) {
80
80
  if (!stopped && processAlive && pid !== undefined) {
81
81
  try {
82
82
  if (sendSignal(pid, 'SIGKILL')) {
83
- stopped = await waitFor(() => !isProcessAlive(pid), 2000);
83
+ stopped = await waitFor(() => !isProcessAlive(pid), 2_000);
84
84
  }
85
85
  else {
86
86
  stopped = true; // Process already gone (ESRCH).
@@ -110,4 +110,4 @@ async function cleanupFile(path, label, log) {
110
110
  log?.(`Failed to remove ${label}: ${String(error)}`);
111
111
  });
112
112
  }
113
- //# sourceMappingURL=stop-daemon.mjs.map
113
+ //# sourceMappingURL=stop-daemon.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stop-daemon.js","sourceRoot":"","sources":["../../src/daemon/stop-daemon.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AAEtC,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,WAAW,EA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,GAAG,IAAI,CAAC,CAAC,gCAAgC;YAClD,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,GAAG,EAAE,CAAC,mBAAmB,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAC5C,CAAC;IACH,CAAC;IAED,IAAI,OAAO,EAAE,CAAC;QACZ,MAAM,WAAW,CAAC,OAAO,EAAE,UAAU,EAAE,GAAG,CAAC,CAAC;QAC5C,MAAM,WAAW,CAAC,UAAU,EAAE,aAAa,EAAE,GAAG,CAAC,CAAC;QAClD,GAAG,EAAE,CAAC,iBAAiB,CAAC,CAAC;IAC3B,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;;;;;;GAOG;AACH,KAAK,UAAU,WAAW,CACxB,IAAY,EACZ,KAAa,EACb,GAA4C;IAE5C,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QACvD,GAAG,EAAE,CAAC,oBAAoB,KAAK,KAAK,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IACvD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { rm } from 'node:fs/promises';\n\nimport { pingDaemon, sendCommand } from './daemon-client.js';\nimport { isProcessAlive, readPidFile, sendSignal, waitFor } from './utils.js';\n\n/**\n * Stop the daemon, preferring a graceful shutdown.\n *\n * Resolution order when a live daemon is present:\n * 1. If the socket is responsive, request a graceful `shutdown` over it.\n * 2. If the recorded PID is still alive, escalate to SIGTERM.\n * 3. ...then SIGKILL.\n *\n * Signals (steps 2-3) are only ever sent against a PID that is observed alive.\n * The socket-absent + alive-PID branch trades a small risk of signalling a\n * recycled PID for the larger risk of leaving an orphan daemon holding the\n * SQLite database — which `daemon purge` would otherwise wipe out from under\n * it.\n *\n * When the socket is NOT responsive AND the recorded PID is dead (or there is\n * no PID file), there is no live daemon: a lingering socket or PID file is\n * stale leftovers from a daemon that already exited — typically one that\n * crashed without running its own cleanup. Those files are removed and the\n * stop is reported as successful, rather than failing on a daemon that is\n * already gone.\n *\n * @param socketPath - The daemon socket path.\n * @param pidPath - The daemon PID file path.\n * @param log - Optional logging function for status messages.\n * @returns True if the daemon was stopped (or was not running).\n */\nexport async function stopDaemon(\n socketPath: string,\n pidPath: string,\n log?: (message: string) => void,\n): Promise<boolean> {\n const pid = await readPidFile(pidPath);\n const ping = await pingDaemon(socketPath);\n const socketObserved =\n ping.status === 'responsive' || ping.status === 'unreachable';\n const processAlive = pid !== undefined && isProcessAlive(pid);\n\n // Only `absent` and `refused` prove no live daemon; `permission`/`timeout`/\n // `protocol` may be a wedged or foreign daemon, so those fall through.\n const socketProvenGone =\n ping.status === 'absent' ||\n (ping.status === 'unreachable' && ping.reason === 'refused');\n\n if (socketProvenGone && !processAlive) {\n await cleanupFile(pidPath, 'PID file', log);\n await cleanupFile(socketPath, 'socket file', log);\n return true;\n }\n\n log?.('Stopping daemon...');\n\n let stopped = false;\n\n // Strategy 1: Graceful socket-based shutdown.\n if (ping.status === 'responsive') {\n try {\n await sendCommand({ socketPath, method: 'shutdown' });\n } catch (error) {\n log?.(`Graceful shutdown request failed: ${String(error)}`);\n }\n // A quiet socket does not prove the process exited; require the recorded\n // pid to be gone too, so a daemon that outlived its socket falls through to\n // SIGTERM/SIGKILL rather than being orphaned.\n stopped = await waitFor(\n async () =>\n (await pingDaemon(socketPath)).status !== 'responsive' &&\n (pid === undefined || !isProcessAlive(pid)),\n 5_000,\n );\n }\n\n // Strategy 2: SIGTERM. Signal when either the socket was observed or the\n // recorded PID is alive; the absent+alive case typically means someone\n // removed the socket from under a live daemon.\n if (!stopped && processAlive && pid !== undefined) {\n if (!socketObserved) {\n log?.(\n `Socket at ${socketPath} is absent but recorded pid ${pid} is alive; signalling anyway.`,\n );\n }\n try {\n if (sendSignal(pid, 'SIGTERM')) {\n stopped = await waitFor(() => !isProcessAlive(pid), 5_000);\n } else {\n stopped = true; // Process already gone (ESRCH).\n }\n } catch (error) {\n log?.(`SIGTERM failed: ${String(error)}`);\n }\n }\n\n // Strategy 3: SIGKILL.\n if (!stopped && processAlive && pid !== undefined) {\n try {\n if (sendSignal(pid, 'SIGKILL')) {\n stopped = await waitFor(() => !isProcessAlive(pid), 2_000);\n } else {\n stopped = true; // Process already gone (ESRCH).\n }\n } catch (error) {\n log?.(`SIGKILL failed: ${String(error)}`);\n }\n }\n\n if (stopped) {\n await cleanupFile(pidPath, 'PID file', log);\n await cleanupFile(socketPath, 'socket file', log);\n log?.('Daemon stopped.');\n }\n\n return stopped;\n}\n\n/**\n * Remove a file best-effort, logging any failure rather than letting it\n * propagate. ENOENT is silently ignored via `force: true`.\n *\n * @param path - The file path to remove.\n * @param label - Human-readable label for log messages.\n * @param log - Optional log sink.\n */\nasync function cleanupFile(\n path: string,\n label: string,\n log: ((message: string) => void) | undefined,\n): Promise<void> {\n await rm(path, { force: true }).catch((error: unknown) => {\n log?.(`Failed to remove ${label}: ${String(error)}`);\n });\n}\n"]}
@@ -1,6 +1,6 @@
1
- import type { Struct } from "@metamask/superstruct";
2
- import type { Json } from "@metamask/utils";
3
- import type { Password, Srp } from "./secrets.cjs";
1
+ import type { Struct } from '@metamask/superstruct';
2
+ import type { Json } from '@metamask/utils';
3
+ import type { Password, Srp } from './secrets.js';
4
4
  /**
5
5
  * Sink for daemon diagnostic messages. A backgrounded daemon's stdio may be
6
6
  * discarded, so hosts supply a logger that writes somewhere durable.
@@ -91,4 +91,4 @@ export type DaemonSpawnConfig = {
91
91
  srp: Srp;
92
92
  packageRoot: string;
93
93
  };
94
- //# sourceMappingURL=types.d.cts.map
94
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/daemon/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,KAAK,EAAE,IA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;AAEF;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;;;;;;;;GASG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,eAAe,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,GAAG,EAAE,GAAG,CAAC;IACT,WAAW,EAAE,MAAM,CAAC;CACrB,CAAC"}
@@ -13,4 +13,4 @@
13
13
  export function defineHandler(paramsStruct, run) {
14
14
  return { paramsStruct, run };
15
15
  }
16
- //# sourceMappingURL=types.mjs.map
16
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/daemon/types.ts"],"names":[],"mappings":"AAiDA;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,aAAa,CAC3B,YAA6B,EAC7B,GAAiC;IAEjC,OAAO,EAAE,YAAY,EAAE,GAAG,EAGzB,CAAC;AACJ,CAAC","sourcesContent":["import type { Struct } from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\n\nimport type { Password, Srp } from './secrets.js';\n\n/**\n * Sink for daemon diagnostic messages. A backgrounded daemon's stdio may be\n * discarded, so hosts supply a logger that writes somewhere durable.\n */\nexport type Logger = (message: string) => void;\n\n/**\n * A function that handles a JSON-RPC method call after its params have been\n * validated by the corresponding {@link RpcHandlerDefinition.paramsStruct}.\n */\nexport type RpcHandler<TParams, TResult> = (\n params: TParams,\n) => Promise<TResult>;\n\n/**\n * Definition for a single JSON-RPC method: the struct that validates\n * incoming `params` plus the handler that runs once `params` is known to\n * match.\n *\n * The server (see `rpc-socket-server.ts`) validates the raw `params` against\n * `paramsStruct` before invoking `run`, so each handler body can trust the\n * shape of its input without re-checking.\n */\nexport type RpcHandlerDefinition<TParams, TResult extends Json | void> = {\n paramsStruct: Struct<TParams>;\n run: RpcHandler<TParams, TResult>;\n};\n\n/**\n * A map of RPC method names to their handler definitions.\n *\n * `TParams` is erased to `unknown` here so definitions with different narrow\n * params types (e.g. `null` vs. a tuple) can coexist in the same map. Consumers\n * therefore see each `run` as accepting `unknown` and must validate `params`\n * against the paired `paramsStruct` before invoking it — which is exactly what\n * the server (see `rpc-socket-server.ts`) does. The concrete `TParams` is\n * captured inside {@link defineHandler}, where the struct and handler are bound\n * together.\n */\nexport type RpcHandlerMap = Record<\n string,\n RpcHandlerDefinition<unknown, Json | void>\n>;\n\n/**\n * Bundle a params struct with the handler that runs once `params` is\n * validated. The server invokes `run` only after `paramsStruct` accepts the\n * value, so `run` can trust the type of its argument.\n *\n * The returned definition erases `TParams` to `unknown` so heterogeneous\n * handlers can share an {@link RpcHandlerMap}.\n *\n * @param paramsStruct - Struct that validates `params` for this method.\n * @param run - Handler invoked with the validated params.\n * @returns An {@link RpcHandlerDefinition} suitable for an {@link RpcHandlerMap}.\n */\nexport function defineHandler<TParams, TResult extends Json | void>(\n paramsStruct: Struct<TParams>,\n run: RpcHandler<TParams, TResult>,\n): RpcHandlerDefinition<unknown, TResult> {\n return { paramsStruct, run } as unknown as RpcHandlerDefinition<\n unknown,\n TResult\n >;\n}\n\n/**\n * Typed wrapper around `wallet.messenger.call` used by the `call` RPC.\n *\n * The messenger is strongly typed by action name; the daemon exposes the full\n * messenger surface over the socket and dispatches by string, so we consolidate\n * the unsafe cast into a single, documented escape hatch instead of repeating\n * it at each call site.\n */\nexport type RpcDispatcher = (action: string, ...args: Json[]) => Promise<Json>;\n\n/**\n * Resolved paths for daemon state files.\n */\nexport type DaemonPaths = {\n socketPath: string;\n pidPath: string;\n logPath: string;\n dbPath: string;\n};\n\n/**\n * Status information returned by the daemon's `getStatus` RPC method.\n */\nexport type DaemonStatusInfo = {\n pid: number;\n uptime: number;\n};\n\n/**\n * Configuration passed to the daemon spawner.\n *\n * `password` is optional: when omitted, the daemon starts without unlocking\n * the keyring, and the caller is expected to use `mm wallet unlock` before\n * any keyring-bound operation. First-run startup still requires both\n * `password` and `srp`; without `password`, the daemon will exit during\n * startup with a clear error. `srp` is always required by the type and\n * forwarded to the daemon; it is only consumed on first run.\n */\nexport type DaemonSpawnConfig = {\n dataDir: string;\n infuraProjectId: string;\n password?: Password;\n srp: Srp;\n packageRoot: string;\n};\n"]}
@@ -1,5 +1,4 @@
1
- /// <reference types="node" />
2
- import type { JsonRpcError } from "@metamask/utils";
1
+ import type { JsonRpcError } from '@metamask/utils';
3
2
  /**
4
3
  * Check whether an unknown error is a Node.js system error with the given code.
5
4
  *
@@ -84,4 +83,4 @@ export declare function sendSignal(pid: number, signal: NodeJS.Signals): boolean
84
83
  * @returns True if the condition was met, false on timeout.
85
84
  */
86
85
  export declare function waitFor(check: () => boolean | Promise<boolean>, timeoutMs: number): Promise<boolean>;
87
- //# sourceMappingURL=utils.d.cts.map
86
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/daemon/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAIpD;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAErE;AAED;;;;;;;;;GASG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAuBhE;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,YAAY,GAAG,MAAM,CAE9D;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,MAAM,GAAG,SAAS,GACxB,MAAM,GAAG,SAAS,CAEpB;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,EAAE,CAI/D;AAED;;;;;;;;GAQG;AACH,wBAAsB,WAAW,CAC/B,OAAO,EAAE,MAAM,GACd,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAa7B;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAanD;AAED;;;;;;;;GAQG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,OAAO,GAAG,OAAO,CAUvE;AAED;;;;;;GAMG;AACH,wBAAsB,OAAO,CAC3B,KAAK,EAAE,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,EACvC,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,OAAO,CAAC,CASlB"}
@@ -1,5 +1,5 @@
1
- import { isErrorWithCode as hasErrorCode } from "@metamask/utils";
2
- import { readFile } from "node:fs/promises";
1
+ import { isErrorWithCode as hasErrorCode } from '@metamask/utils';
2
+ import { readFile } from 'node:fs/promises';
3
3
  /**
4
4
  * Check whether an unknown error is a Node.js system error with the given code.
5
5
  *
@@ -157,4 +157,4 @@ export async function waitFor(check, timeoutMs) {
157
157
  }
158
158
  return false;
159
159
  }
160
- //# sourceMappingURL=utils.mjs.map
160
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/daemon/utils.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,IAAI,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAClE,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAE5C;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAAC,KAAc,EAAE,IAAY;IAC1D,OAAO,YAAY,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC;AACpD,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,yBAAyB,CAAC,KAAc;IACtD,IACE,eAAe,CAAC,KAAK,EAAE,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AAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAC3B,KAAuC,EACvC,SAAiB;IAEjB,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,SAAS,CAAC;IACxC,OAAO,IAAI,CAAC,GAAG,EAAE,GAAG,QAAQ,EAAE,CAAC;QAC7B,IAAI,MAAM,KAAK,EAAE,EAAE,CAAC;YAClB,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC;IAC3D,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import type { JsonRpcError } from '@metamask/utils';\nimport { isErrorWithCode as hasErrorCode } from '@metamask/utils';\nimport { readFile } from 'node:fs/promises';\n\n/**\n * Check whether an unknown error is a Node.js system error with the given code.\n *\n * @param error - The error to check.\n * @param code - The expected error code (e.g. 'ENOENT', 'EPERM').\n * @returns True if the error matches the code.\n */\nexport function isErrorWithCode(error: unknown, code: string): boolean {\n return hasErrorCode(error) && error.code === code;\n}\n\n/**\n * Turn an error thrown while contacting the daemon socket into a user-facing\n * message for `Command.error`, so every command reports the same failure the\n * same way. Distinguishes a stopped daemon (`ENOENT`/`ECONNREFUSED`), a\n * connection dropped mid-request (`ECONNRESET`), and a permission problem\n * (`EACCES`/`EPERM`), falling back to the raw error message.\n *\n * @param error - The value thrown while contacting the daemon.\n * @returns A human-readable explanation of the failure.\n */\nexport function makeDaemonConnectionError(error: unknown): string {\n if (\n isErrorWithCode(error, 'ENOENT') ||\n isErrorWithCode(error, 'ECONNREFUSED')\n ) {\n return 'Daemon is not running. Start it with `mm daemon start`.';\n }\n // A reset drops an already-established connection, so the daemon was running\n // — most likely it crashed mid-request. Don't tell the user to start it.\n if (isErrorWithCode(error, 'ECONNRESET')) {\n return (\n 'Lost the connection to the daemon; it may have crashed while ' +\n 'handling the request. Check `mm daemon status` and the daemon log.'\n );\n }\n if (isErrorWithCode(error, 'EACCES') || isErrorWithCode(error, 'EPERM')) {\n return (\n 'Cannot connect to the daemon socket: permission denied. ' +\n 'The socket may be owned by another user, or MM_DAEMON_DATA_DIR ' +\n 'may point to a directory you cannot access.'\n );\n }\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Format the error of a JSON-RPC failure response into a user-facing message\n * for `Command.error`, so every command reports RPC failures the same way.\n *\n * @param error - The `error` field of a JSON-RPC failure response.\n * @returns The error message annotated with its numeric code.\n */\nexport function formatJsonRpcError(error: JsonRpcError): string {\n return `${error.message} (code ${String(error.code)})`;\n}\n\n/**\n * Treat an empty string the same as `undefined` — \"no value supplied\". Used\n * to normalise `--password ''` and `MM_WALLET_PASSWORD=''` so they trigger\n * the interactive prompt rather than sending an empty string to the keyring.\n *\n * @param value - The value to normalise.\n * @returns `undefined` if `value` is `undefined` or `''`; `value` otherwise.\n */\nexport function emptyToUndefined(\n value: string | undefined,\n): string | undefined {\n return value === '' ? undefined : value;\n}\n\n/**\n * Check whether a value is an array of strings. Used to validate untyped RPC\n * results (e.g. the daemon's `listActions`) before treating them as `string[]`.\n *\n * @param value - The value to check.\n * @returns True if the value is an array whose every element is a string.\n */\nexport function isStringArray(value: unknown): value is string[] {\n return (\n Array.isArray(value) && value.every((item) => typeof item === 'string')\n );\n}\n\n/**\n * Read a PID from a file. The file may contain just the PID, or the PID on\n * the first line followed by additional metadata (e.g. start time written by\n * the daemon).\n *\n * @param pidPath - The PID file path.\n * @returns The PID, or undefined if the file is missing or its first line is\n * not a positive integer.\n */\nexport async function readPidFile(\n pidPath: string,\n): Promise<number | undefined> {\n let contents: string;\n try {\n contents = await readFile(pidPath, 'utf-8');\n } catch (error: unknown) {\n if (isErrorWithCode(error, 'ENOENT')) {\n return undefined;\n }\n throw error;\n }\n // String.prototype.split always returns at least one element, so [0] is safe.\n const pid = Number(contents.split('\\n')[0].trim());\n return Number.isInteger(pid) && pid > 0 ? pid : undefined;\n}\n\n/**\n * Check whether a process is alive by sending signal 0.\n *\n * Treats `ESRCH` as \"process is gone\", `EPERM` as \"process exists but we\n * cannot signal it\" (still alive from our perspective), and rethrows\n * anything else so the caller can surface unexpected failures rather than\n * silently assuming the process is dead.\n *\n * @param pid - The process ID to check.\n * @returns True if the process exists.\n */\nexport function isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error: unknown) {\n if (isErrorWithCode(error, 'ESRCH')) {\n return false;\n }\n if (isErrorWithCode(error, 'EPERM')) {\n return true;\n }\n throw error;\n }\n}\n\n/**\n * Send a signal to a process. Returns true if the signal was sent, false if\n * the process does not exist (ESRCH). Re-throws on permission errors and\n * other failures.\n *\n * @param pid - The process ID.\n * @param signal - The signal to send.\n * @returns True if the signal was delivered, false if the process is gone.\n */\nexport function sendSignal(pid: number, signal: NodeJS.Signals): boolean {\n try {\n process.kill(pid, signal);\n return true;\n } catch (error: unknown) {\n if (isErrorWithCode(error, 'ESRCH')) {\n return false;\n }\n throw error;\n }\n}\n\n/**\n * Poll until a condition is met or the timeout elapses.\n *\n * @param check - A function that returns true when the condition is met.\n * @param timeoutMs - Maximum time to wait in milliseconds.\n * @returns True if the condition was met, false on timeout.\n */\nexport async function waitFor(\n check: () => boolean | Promise<boolean>,\n timeoutMs: number,\n): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (await check()) {\n return true;\n }\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n return false;\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { Wallet } from "@metamask/wallet";
2
- import type { Password, Srp } from "./secrets.cjs";
3
- import type { Logger } from "./types.cjs";
1
+ import { Wallet } from '@metamask/wallet';
2
+ import type { Password, Srp } from './secrets.js';
3
+ import type { Logger } from './types.js';
4
4
  export type CreateWalletConfig = {
5
5
  databasePath: string;
6
6
  password?: Password;
@@ -61,4 +61,4 @@ export type CreateWalletResult = {
61
61
  * @returns The `Wallet` and a `dispose` handle that tears it down.
62
62
  */
63
63
  export declare function createWallet({ databasePath, password, srp, infuraProjectId, log, }: CreateWalletConfig): Promise<CreateWalletResult>;
64
- //# sourceMappingURL=wallet-factory.d.cts.map
64
+ //# sourceMappingURL=wallet-factory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wallet-factory.d.ts","sourceRoot":"","sources":["../../src/daemon/wallet-factory.ts"],"names":[],"mappings":"AAeA,OAAO,EAGL,MAAM,EACP,MAAM,kBAAkB,CAAC;AAY1B,OAAO,KAAK,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAIzC,MAAM,MAAM,kBAAkB,GAAG;IAC/B,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,GAAG,EAAE,GAAG,CAAC;IACT,eAAe,EAAE,MAAM,CAAC;IACxB,GAAG,CAAC,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG;IAC/B,MAAM,EAAE,MAAM,CAAC;IACf;;;;;;;OAOG;IACH,OAAO,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC9B,CAAC;AAmIF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,wBAAsB,YAAY,CAAC,EACjC,YAAY,EACZ,QAAQ,EACR,GAAG,EACH,eAAe,EACf,GAAG,GACJ,EAAE,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAwHlD"}
@@ -1,13 +1,13 @@
1
- import { getDefaultAnalyticsControllerState } from "@metamask/analytics-controller";
2
- import { ConfigRegistryApiEnv } from "@metamask/config-registry-controller";
3
- import { Messenger } from "@metamask/messenger";
4
- import { ClientConfigApiService, ClientType, DistributionType, EnvironmentType } from "@metamask/remote-feature-flag-controller";
5
- import { InMemoryStorageAdapter } from "@metamask/storage-service";
6
- import { AlwaysOnlineAdapter, importSecretRecoveryPhrase, Wallet } from "@metamask/wallet";
7
- import { rm } from "node:fs/promises";
8
- import { KeyValueStore } from "../persistence/KeyValueStore.mjs";
9
- import { loadState, subscribeToChanges } from "../persistence/persistence.mjs";
10
- import { subscribeToAutoApproval } from "./auto-approval.mjs";
1
+ import { getDefaultAnalyticsControllerState } from '@metamask/analytics-controller';
2
+ import { ConfigRegistryApiEnv } from '@metamask/config-registry-controller';
3
+ import { Messenger } from '@metamask/messenger';
4
+ import { ClientConfigApiService, ClientType, DistributionType, EnvironmentType, } from '@metamask/remote-feature-flag-controller';
5
+ import { InMemoryStorageAdapter } from '@metamask/storage-service';
6
+ import { AlwaysOnlineAdapter, importSecretRecoveryPhrase, Wallet, } from '@metamask/wallet';
7
+ import { rm } from 'node:fs/promises';
8
+ import { KeyValueStore } from '../persistence/KeyValueStore.js';
9
+ import { loadState, subscribeToChanges } from '../persistence/persistence.js';
10
+ import { subscribeToAutoApproval } from './auto-approval.js';
11
11
  const IN_MEMORY_DATABASE_PATH = ':memory:';
12
12
  /**
13
13
  * Build the per-instance options the daemon's `Wallet` is constructed with.
@@ -221,7 +221,7 @@ export async function createWallet({ databasePath, password, srp, infuraProjectI
221
221
  let disposePromise;
222
222
  return {
223
223
  wallet,
224
- dispose: async () => (disposePromise ?? (disposePromise = teardown(persistenceUnsubscribe, autoApprovalUnsubscribe, wallet, store, logFn))),
224
+ dispose: async () => (disposePromise ??= teardown(persistenceUnsubscribe, autoApprovalUnsubscribe, wallet, store, logFn)),
225
225
  };
226
226
  }
227
227
  catch (error) {
@@ -334,4 +334,4 @@ async function teardown(persistenceUnsubscribe, autoApprovalUnsubscribe, wallet,
334
334
  function hasPersistedKeyring(state) {
335
335
  return typeof state.KeyringController?.vault === 'string';
336
336
  }
337
- //# sourceMappingURL=wallet-factory.mjs.map
337
+ //# sourceMappingURL=wallet-factory.js.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AI,CAAC,WAAW,EAAE,CAAC;QACjB,OAAO;IACT,CAAC;IACD,IAAI,CAAC;QACH,WAAW,EAAE,CAAC;IAChB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,KAAK,CACH,GAAG,KAAK,gEAAgE;YACtE,iCAAiC,MAAM,CAAC,KAAK,CAAC,EAAE,CACnD,CAAC;IACJ,CAAC;AACH,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,KAAK,UAAU,QAAQ,CACrB,sBAAgD,EAChD,uBAAiD,EACjD,MAA0B,EAC1B,KAAoB,EACpB,KAAa;IAEb,cAAc,CAAC,sBAAsB,EAAE,aAAa,EAAE,KAAK,CAAC,CAAC;IAC7D,cAAc,CAAC,uBAAuB,EAAE,eAAe,EAAE,KAAK,CAAC,CAAC;IAChE,IAAI,MAAM,EAAE,CAAC;QACX,IAAI,CAAC;YACH,MAAM,MAAM,CAAC,OAAO,EAAE,CAAC;QACzB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,KAAK,CAAC,4CAA4C,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACrE,CAAC;IACH,CAAC;IACD,IAAI,CAAC;QACH,KAAK,CAAC,KAAK,EAAE,CAAC;IAChB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,KAAK,CAAC,yCAAyC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;IAClE,CAAC;AACH,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,mBAAmB,CAC1B,KAA8C;IAE9C,OAAO,OAAO,KAAK,CAAC,iBAAiB,EAAE,KAAK,KAAK,QAAQ,CAAC;AAC5D,CAAC","sourcesContent":["import { getDefaultAnalyticsControllerState } from '@metamask/analytics-controller';\nimport type {\n AnalyticsControllerGetStateAction,\n AnalyticsControllerTrackEventAction,\n} from '@metamask/analytics-controller';\nimport { ConfigRegistryApiEnv } from '@metamask/config-registry-controller';\nimport { Messenger } from '@metamask/messenger';\nimport {\n ClientConfigApiService,\n ClientType,\n DistributionType,\n EnvironmentType,\n} from '@metamask/remote-feature-flag-controller';\nimport { InMemoryStorageAdapter } from '@metamask/storage-service';\nimport type { Json } from '@metamask/utils';\nimport {\n AlwaysOnlineAdapter,\n importSecretRecoveryPhrase,\n Wallet,\n} from '@metamask/wallet';\nimport type {\n DefaultActions,\n DefaultEvents,\n RootMessenger,\n WalletOptions,\n} from '@metamask/wallet';\nimport { rm } from 'node:fs/promises';\n\nimport { KeyValueStore } from '../persistence/KeyValueStore.js';\nimport { loadState, subscribeToChanges } from '../persistence/persistence.js';\nimport { subscribeToAutoApproval } from './auto-approval.js';\nimport type { Password, Srp } from './secrets.js';\nimport type { Logger } from './types.js';\n\nconst IN_MEMORY_DATABASE_PATH = ':memory:';\n\nexport type CreateWalletConfig = {\n databasePath: string;\n password?: Password;\n srp: Srp;\n infuraProjectId: string;\n log?: Logger;\n};\n\nexport type CreateWalletResult = {\n wallet: Wallet;\n /**\n * Tear down everything `createWallet` set up, in the order that keeps\n * in-flight persistence writes valid: stop the state-change subscription,\n * destroy the wallet, then close the store (closing first would cause a\n * teardown-time persistence write to fail). Resilient — a failure in any\n * step is logged and the remaining steps still run — and idempotent (repeat\n * calls coalesce onto the same teardown).\n */\n dispose: () => Promise<void>;\n};\n\n/**\n * Build the per-instance options the daemon's `Wallet` is constructed with.\n *\n * Returns a fresh set on every call so the metadata probe and the real wallet\n * never share adapter/service instances (the probe is destroyed, which may\n * tear those instances down).\n *\n * Only the slots wired on `@metamask/wallet` today are populated:\n * - `storageService` — backed by an in-memory adapter. This is the wallet's\n * large-blob store (snap source, caches), distinct from the SQLite\n * `KeyValueStore` that persists controller state; no wired controller\n * offloads durable data to it yet, so in-memory suffices.\n * - `connectivityController` — the `AlwaysOnlineAdapter` exported for\n * node-like hosts that have no platform connectivity signal.\n * - `networkController` — the Infura project ID used to reach Infura RPC\n * endpoints.\n * - `remoteFeatureFlagController` — a `ClientConfigApiService` fetching real\n * flags over the network.\n * - `approvalController` — a no-op `showApprovalRequest` (the daemon is\n * headless); pending requests are accepted separately by the auto-approval\n * subscription `createWallet` installs, not by this hook.\n * - `gasFeeController` — only `clientId: 'cli'` (sent as `X-Client-Id` to the\n * gas API); the API endpoints, poll interval, and compatibility callbacks are\n * left at the wallet package's platform-agnostic defaults (the default\n * `EIP1559APIEndpoint` is already the production URL, so the daemon does not\n * re-specify it).\n * - `transactionController` — swaps processing disabled and no client hooks;\n * see the slot's inline comment for why the daemon relies on the\n * controller's defaults for everything else.\n *\n * The optional `keyringController` slot is intentionally omitted so the\n * controller's built-in defaults (e.g. the PBKDF2 encryptor) apply.\n *\n * @param infuraProjectId - The Infura project ID for the `NetworkController`.\n * @returns The `instanceOptions` for the `Wallet` constructor.\n */\nfunction buildInstanceOptions(\n infuraProjectId: string,\n): WalletOptions['instanceOptions'] {\n return {\n configRegistryApiService: {\n env: ConfigRegistryApiEnv.PRD,\n },\n approvalController: {\n // The daemon is headless, so there is no UI to open: requests are\n // resolved by the auto-approval subscription (see `subscribeToAutoApproval`)\n // rather than by this hook, which stays a no-op.\n // TODO: surface approval requests over the daemon transport.\n showApprovalRequest: (): undefined => undefined,\n },\n connectivityController: {\n connectivityAdapter: new AlwaysOnlineAdapter(),\n },\n gasFeeController: {\n // Identifies the CLI to the gas estimation API via the `X-Client-Id`\n // header.\n clientId: 'cli',\n },\n networkController: {\n infuraProjectId,\n },\n remoteFeatureFlagController: {\n clientConfigApiService: new ClientConfigApiService({\n fetch: globalThis.fetch,\n config: {\n // TODO: switch to a CLI-specific `ClientType` once one exists; until\n // then `Extension` buckets feature flags as an extension client.\n client: ClientType.Extension,\n distribution: DistributionType.Main,\n environment: EnvironmentType.Production,\n },\n }),\n getMetaMetricsId: (): string => 'cli',\n clientVersion: '0.0.0',\n },\n storageService: {\n storage: new InMemoryStorageAdapter(),\n },\n transactionController: {\n // The CLI exposes no swaps surface, so skip the swaps-specific\n // post-processing a full wallet client runs (mobile makes the same\n // choice; the extension keeps swaps enabled).\n disableSwaps: true,\n // No CLI-specific transaction hooks: the controller's built-in publish\n // path broadcasts through the wired `NetworkController` provider, and the\n // remaining hooks (metrics, notifications, gas-fee tokens) are client-UI\n // concerns the headless daemon has no equivalent for. Every other option\n // (`getPermittedAccounts`, `isSimulationEnabled`, `trace`, …) is left at\n // the controller's default.\n hooks: {},\n },\n };\n}\n\n/**\n * Register handlers for the `AnalyticsController` actions that\n * `NetworkController` calls to emit RPC service analytics. The daemon does not\n * report analytics, so these do nothing: `getState` returns an empty analytics\n * ID, which stops the controller before it tracks anything, and `trackEvent` is\n * a no-op. Registering them keeps those messenger calls from throwing.\n *\n * @param messenger - The wallet's root messenger.\n */\nfunction registerAnalyticsStubHandlers(messenger: Wallet['messenger']): void {\n // Register on an `AnalyticsController`-namespaced messenger, not the root: a\n // messenger can only register handlers for its own namespace, and doing so\n // delegates them up to the root, where `NetworkController` can reach them.\n const analyticsMessenger = new Messenger<\n 'AnalyticsController',\n AnalyticsControllerGetStateAction | AnalyticsControllerTrackEventAction,\n never,\n RootMessenger<DefaultActions, DefaultEvents>\n >({\n namespace: 'AnalyticsController',\n parent: messenger as RootMessenger<DefaultActions, DefaultEvents>,\n });\n analyticsMessenger.registerActionHandler(\n 'AnalyticsController:getState',\n () => ({\n ...getDefaultAnalyticsControllerState(),\n analyticsId: '',\n }),\n );\n analyticsMessenger.registerActionHandler(\n 'AnalyticsController:trackEvent',\n () => undefined,\n );\n}\n\n/**\n * Create a configured `Wallet` for daemon use, backed by a SQLite key-value\n * store for controller-state persistence.\n *\n * Loads any previously-persisted controller state from the store, seeds the\n * wallet with it, then subscribes the store to subsequent state changes so all\n * persist-flagged properties are written through.\n *\n * If the store does not yet contain a keyring vault (first run), the supplied\n * secret recovery phrase is imported using the supplied password. On\n * subsequent runs, the persisted vault is reused: when a password is\n * supplied, the wallet is unlocked via `KeyringController:submitPassword` so\n * keyring-bound messenger actions work immediately; when no password is\n * supplied, the wallet starts locked and the caller is expected to invoke\n * `mm wallet unlock` before any keyring-bound operation. First-run startup\n * without a password is rejected (the SRP cannot be imported without one).\n * On a subsequent run, a wrong password rejects startup with a `Failed to\n * unlock the persisted vault` error that wraps the `submitPassword` rejection.\n *\n * On any failure after the store is opened, the store is closed (and the wallet\n * destroyed, if constructed). On a first-run failure, the on-disk database is\n * also removed so a retry does not latch onto an orphaned partial vault — this\n * covers in-process failures only; a hard crash (SIGKILL/power loss) mid-import\n * can still leave a vault on disk.\n *\n * @param config - Wallet configuration.\n * @param config.databasePath - Path to the SQLite database file (or\n * `':memory:'` for ephemeral use).\n * @param config.password - The wallet password. Optional on subsequent runs;\n * when omitted, the daemon starts with a locked keyring. Required on first\n * run (to import the SRP).\n * @param config.srp - The secret recovery phrase (BIP-39 mnemonic). Used\n * only on first run.\n * @param config.infuraProjectId - The Infura project ID for the\n * `NetworkController`.\n * @param config.log - Optional logger for persistence-write and teardown\n * failures. Without it, failures fall back to `console.error` (which a detached\n * daemon's `stdio: 'ignore'` discards).\n * @returns The `Wallet` and a `dispose` handle that tears it down.\n */\nexport async function createWallet({\n databasePath,\n password,\n srp,\n infuraProjectId,\n log,\n}: CreateWalletConfig): Promise<CreateWalletResult> {\n const logFn = log ?? ((message: string): void => console.error(message));\n const store = new KeyValueStore(databasePath);\n let wallet: Wallet | undefined;\n let persistenceUnsubscribe: (() => void) | undefined;\n let autoApprovalUnsubscribe: (() => void) | undefined;\n let wasFirstRun = false;\n\n try {\n const state = await loadPersistedState(store, infuraProjectId, logFn);\n wasFirstRun = !hasPersistedKeyring(state);\n\n // Validate the first-run precondition BEFORE constructing the wallet,\n // so a doomed startup doesn't build a Wallet (and wire persistence\n // handlers) just to tear it down.\n if (wasFirstRun && password === undefined) {\n throw new Error(\n 'A password is required on first run to import the secret recovery phrase. ' +\n 'Pass `--password` (or `MM_WALLET_PASSWORD`) on `mm daemon start`.',\n );\n }\n\n wallet = new Wallet({\n state,\n instanceOptions: buildInstanceOptions(infuraProjectId),\n });\n registerAnalyticsStubHandlers(wallet.messenger);\n persistenceUnsubscribe = subscribeToChanges(\n wallet.messenger,\n wallet.controllerMetadata,\n store,\n logFn,\n );\n\n // Installed before `init` so any approval raised during initialization is covered.\n autoApprovalUnsubscribe = subscribeToAutoApproval(wallet.messenger, logFn);\n\n // Complete post-construction controller setup before serving requests —\n // e.g. `NetworkController.init` applies the selected network so a provider\n // is available. `init` settles every step independently; a rejected step\n // leaves the wallet only partially usable, so abort startup (the catch\n // below tears down and, on first run, removes the partial database) rather\n // than serving a degraded daemon.\n const initResults = await wallet.init();\n const initFailures = initResults.filter(\n (result): result is PromiseRejectedResult => result.status === 'rejected',\n );\n for (const failure of initFailures) {\n logFn(`Wallet init step failed: ${String(failure.reason)}`);\n }\n if (initFailures.length > 0) {\n const firstReason = String(initFailures[0].reason);\n throw new Error(\n `Wallet initialization failed (${initFailures.length} step(s)); refusing to serve a partially initialized wallet. First failure: ${firstReason}`,\n );\n }\n\n if (wasFirstRun) {\n // The precondition check above throws when `wasFirstRun && password ===\n // undefined`, so `password` is defined here. TS does not correlate the\n // two separate variables, so it cannot narrow `password` from\n // `wasFirstRun` alone — hence the assertion.\n await importSecretRecoveryPhrase(\n wallet,\n (password as Password).unwrap(),\n srp.unwrap(),\n );\n } else if (password !== undefined) {\n try {\n await wallet.messenger.call(\n 'KeyringController:submitPassword',\n password.unwrap(),\n );\n } catch (error) {\n throw new Error(\n `Failed to unlock the persisted vault: ${String(error)}`,\n );\n }\n }\n\n let disposePromise: Promise<void> | undefined;\n return {\n wallet,\n dispose: async () =>\n (disposePromise ??= teardown(\n persistenceUnsubscribe,\n autoApprovalUnsubscribe,\n wallet,\n store,\n logFn,\n )),\n };\n } catch (error) {\n await teardown(\n persistenceUnsubscribe,\n autoApprovalUnsubscribe,\n wallet,\n store,\n logFn,\n );\n\n if (wasFirstRun && databasePath !== IN_MEMORY_DATABASE_PATH) {\n // Best-effort cleanup of the on-disk SQLite files (main, WAL, SHM) so a\n // partially-persisted KeyringController vault cannot mislead the next run\n // into skipping SRP import. Covers in-process failures only — a crash\n // (SIGKILL/power loss) mid-import leaves the vault on disk.\n await Promise.all(\n [databasePath, `${databasePath}-wal`, `${databasePath}-shm`].map(\n (path) =>\n rm(path, { force: true }).catch((rmError: unknown) => {\n logFn(\n `Failed to remove ${path} during first-run cleanup: ${String(rmError)}`,\n );\n }),\n ),\n );\n }\n\n throw error;\n }\n}\n\n/**\n * Load persisted controller state, filtered to currently persist-flagged\n * properties.\n *\n * `loadState` filters against the live controller metadata, but that metadata\n * is only knowable from a constructed `Wallet` — and its output is what seeds\n * the real wallet. So this constructs a short-lived probe purely to read the\n * metadata, then tears it down.\n *\n * TODO: drop the probe once `@metamask/wallet` exposes controller metadata\n * without constructing a `Wallet`.\n *\n * @param store - The key-value store to read from.\n * @param infuraProjectId - The Infura project ID for the probe's\n * `NetworkController`.\n * @param logFn - Logger for a probe-teardown failure.\n * @returns The filtered persisted state, suitable for the `Wallet` `state`\n * option.\n */\nasync function loadPersistedState(\n store: KeyValueStore,\n infuraProjectId: string,\n logFn: Logger,\n): Promise<Record<string, Record<string, Json>>> {\n const probe = new Wallet({\n instanceOptions: buildInstanceOptions(infuraProjectId),\n });\n registerAnalyticsStubHandlers(probe.messenger);\n try {\n return loadState(store, probe.controllerMetadata);\n } finally {\n await probe.destroy().catch((error: unknown) => {\n logFn(`Metadata probe destroy failed: ${String(error)}`);\n });\n }\n}\n\n/**\n * Best-effort unsubscribe: run the function if present, logging (and\n * swallowing) any error so a later teardown step still runs.\n *\n * @param unsubscribe - The unsubscribe function, if one was registered.\n * @param label - Human-readable subscription name for the failure log.\n * @param logFn - Logger for a failure.\n */\nfunction runUnsubscribe(\n unsubscribe: (() => void) | undefined,\n label: string,\n logFn: Logger,\n): void {\n if (!unsubscribe) {\n return;\n }\n try {\n unsubscribe();\n } catch (error) {\n logFn(\n `${label} unsubscribe failed during teardown — subscription may remain ` +\n `live until the process exits: ${String(error)}`,\n );\n }\n}\n\n/**\n * Persistence-safe teardown of a wallet and its store; see {@link\n * CreateWalletResult.dispose} for the ordering rationale. Each step is\n * best-effort, so a failure is logged and the remaining steps still run.\n *\n * @param persistenceUnsubscribe - The persistence-subscription unsubscribe\n * function, if one was registered.\n * @param autoApprovalUnsubscribe - The auto-approval-subscription unsubscribe\n * function, if one was registered.\n * @param wallet - The wallet to destroy, if one was constructed.\n * @param store - The store to close.\n * @param logFn - Logger for step failures.\n */\nasync function teardown(\n persistenceUnsubscribe: (() => void) | undefined,\n autoApprovalUnsubscribe: (() => void) | undefined,\n wallet: Wallet | undefined,\n store: KeyValueStore,\n logFn: Logger,\n): Promise<void> {\n runUnsubscribe(persistenceUnsubscribe, 'Persistence', logFn);\n runUnsubscribe(autoApprovalUnsubscribe, 'Auto-approval', logFn);\n if (wallet) {\n try {\n await wallet.destroy();\n } catch (error) {\n logFn(`wallet.destroy() failed during teardown: ${String(error)}`);\n }\n }\n try {\n store.close();\n } catch (error) {\n logFn(`store.close() failed during teardown: ${String(error)}`);\n }\n}\n\n/**\n * Determine whether the loaded state already contains a keyring vault.\n *\n * The KeyringController persists its `vault` once an SRP has been imported, so\n * its presence indicates that first-run setup completed before.\n *\n * @param state - The state loaded from the key-value store.\n * @returns True if a KeyringController vault string is present.\n */\nfunction hasPersistedKeyring(\n state: Record<string, Record<string, unknown>>,\n): boolean {\n return typeof state.KeyringController?.vault === 'string';\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { Json } from "@metamask/utils";
1
+ import type { Json } from '@metamask/utils';
2
2
  /**
3
3
  * A synchronous key-value store backed by better-sqlite3.
4
4
  *
@@ -15,4 +15,4 @@ export declare class KeyValueStore {
15
15
  delete(key: string): void;
16
16
  close(): void;
17
17
  }
18
- //# sourceMappingURL=KeyValueStore.d.cts.map
18
+ //# sourceMappingURL=KeyValueStore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KeyValueStore.d.ts","sourceRoot":"","sources":["../../src/persistence/KeyValueStore.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAG5C;;;;;;GAMG;AACH,qBAAa,aAAa;;IAWxB,YAAY,YAAY,EAAE,MAAM,EAa/B;IAED,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAUjC;IAED,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,GAAG,IAAI,CAElC;IAED,MAAM,IAAI,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAW7B;IAED,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAExB;IAED,KAAK,IAAI,IAAI,CAEZ;CACF"}
@@ -0,0 +1,59 @@
1
+ import Sqlite from 'better-sqlite3';
2
+ /**
3
+ * A synchronous key-value store backed by better-sqlite3.
4
+ *
5
+ * Uses a single `kv` table with TEXT key (primary key) and TEXT value
6
+ * (JSON-serialized). Intended as the persistence backend for wallet
7
+ * controller state.
8
+ */
9
+ export class KeyValueStore {
10
+ #db;
11
+ #getStmt;
12
+ #setStmt;
13
+ #deleteStmt;
14
+ #getAllStmt;
15
+ constructor(databasePath) {
16
+ this.#db = new Sqlite(databasePath);
17
+ this.#db.pragma('journal_mode = WAL');
18
+ this.#db.exec('CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL)');
19
+ this.#getStmt = this.#db.prepare('SELECT value FROM kv WHERE key = ?');
20
+ this.#setStmt = this.#db.prepare('INSERT OR REPLACE INTO kv (key, value) VALUES (?, ?)');
21
+ this.#deleteStmt = this.#db.prepare('DELETE FROM kv WHERE key = ?');
22
+ this.#getAllStmt = this.#db.prepare('SELECT key, value FROM kv');
23
+ }
24
+ get(key) {
25
+ const row = this.#getStmt.get(key);
26
+ if (!row) {
27
+ return undefined;
28
+ }
29
+ try {
30
+ return JSON.parse(row.value);
31
+ }
32
+ catch {
33
+ throw new Error(`Failed to parse stored value for key '${key}'`);
34
+ }
35
+ }
36
+ set(key, value) {
37
+ this.#setStmt.run(key, JSON.stringify(value));
38
+ }
39
+ getAll() {
40
+ const rows = this.#getAllStmt.all();
41
+ const result = {};
42
+ for (const row of rows) {
43
+ try {
44
+ result[row.key] = JSON.parse(row.value);
45
+ }
46
+ catch {
47
+ throw new Error(`Failed to parse stored value for key '${row.key}'`);
48
+ }
49
+ }
50
+ return result;
51
+ }
52
+ delete(key) {
53
+ this.#deleteStmt.run(key);
54
+ }
55
+ close() {
56
+ this.#db.close();
57
+ }
58
+ }
59
+ //# sourceMappingURL=KeyValueStore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"KeyValueStore.js","sourceRoot":"","sources":["../../src/persistence/KeyValueStore.ts"],"names":[],"mappings":"AACA,OAAO,MAAM,MAAM,gBAAgB,CAAC;AAEpC;;;;;;GAMG;AACH,MAAM,OAAO,aAAa;IACf,GAAG,CAAkB;IAErB,QAAQ,CAA4D;IAEpE,QAAQ,CAA2C;IAEnD,WAAW,CAAmC;IAE9C,WAAW,CAAuD;IAE3E,YAAY,YAAoB;QAC9B,IAAI,CAAC,GAAG,GAAG,IAAI,MAAM,CAAC,YAAY,CAAC,CAAC;QACpC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,oBAAoB,CAAC,CAAC;QACtC,IAAI,CAAC,GAAG,CAAC,IAAI,CACX,2EAA2E,CAC5E,CAAC;QAEF,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,oCAAoC,CAAC,CAAC;QACvE,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAC9B,sDAAsD,CACvD,CAAC;QACF,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,8BAA8B,CAAC,CAAC;QACpE,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,2BAA2B,CAAC,CAAC;IACnE,CAAC;IAED,GAAG,CAAC,GAAW;QACb,MAAM,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACnC,IAAI,CAAC,GAAG,EAAE,CAAC;YACT,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,IAAI,CAAC;YACH,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAC/B,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,IAAI,KAAK,CAAC,yCAAyC,GAAG,GAAG,CAAC,CAAC;QACnE,CAAC;IACH,CAAC;IAED,GAAG,CAAC,GAAW,EAAE,KAAW;QAC1B,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC;IAChD,CAAC;IAED,MAAM;QACJ,MAAM,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC;QACpC,MAAM,MAAM,GAAyB,EAAE,CAAC;QACxC,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;YACvB,IAAI,CAAC;gBACH,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;YAC1C,CAAC;YAAC,MAAM,CAAC;gBACP,MAAM,IAAI,KAAK,CAAC,yCAAyC,GAAG,CAAC,GAAG,GAAG,CAAC,CAAC;YACvE,CAAC;QACH,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,MAAM,CAAC,GAAW;QAChB,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IAC5B,CAAC;IAED,KAAK;QACH,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC;IACnB,CAAC;CACF","sourcesContent":["import type { Json } from '@metamask/utils';\nimport Sqlite from 'better-sqlite3';\n\n/**\n * A synchronous key-value store backed by better-sqlite3.\n *\n * Uses a single `kv` table with TEXT key (primary key) and TEXT value\n * (JSON-serialized). Intended as the persistence backend for wallet\n * controller state.\n */\nexport class KeyValueStore {\n readonly #db: Sqlite.Database;\n\n readonly #getStmt: Sqlite.Statement<[string], { value: string } | undefined>;\n\n readonly #setStmt: Sqlite.Statement<[string, string], void>;\n\n readonly #deleteStmt: Sqlite.Statement<[string], void>;\n\n readonly #getAllStmt: Sqlite.Statement<[], { key: string; value: string }>;\n\n constructor(databasePath: string) {\n this.#db = new Sqlite(databasePath);\n this.#db.pragma('journal_mode = WAL');\n this.#db.exec(\n 'CREATE TABLE IF NOT EXISTS kv (key TEXT PRIMARY KEY, value TEXT NOT NULL)',\n );\n\n this.#getStmt = this.#db.prepare('SELECT value FROM kv WHERE key = ?');\n this.#setStmt = this.#db.prepare(\n 'INSERT OR REPLACE INTO kv (key, value) VALUES (?, ?)',\n );\n this.#deleteStmt = this.#db.prepare('DELETE FROM kv WHERE key = ?');\n this.#getAllStmt = this.#db.prepare('SELECT key, value FROM kv');\n }\n\n get(key: string): Json | undefined {\n const row = this.#getStmt.get(key);\n if (!row) {\n return undefined;\n }\n try {\n return JSON.parse(row.value);\n } catch {\n throw new Error(`Failed to parse stored value for key '${key}'`);\n }\n }\n\n set(key: string, value: Json): void {\n this.#setStmt.run(key, JSON.stringify(value));\n }\n\n getAll(): Record<string, Json> {\n const rows = this.#getAllStmt.all();\n const result: Record<string, Json> = {};\n for (const row of rows) {\n try {\n result[row.key] = JSON.parse(row.value);\n } catch {\n throw new Error(`Failed to parse stored value for key '${row.key}'`);\n }\n }\n return result;\n }\n\n delete(key: string): void {\n this.#deleteStmt.run(key);\n }\n\n close(): void {\n this.#db.close();\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
- import type { StateMetadataConstraint } from "@metamask/base-controller";
2
- import type { Json } from "@metamask/utils";
3
- import type { DefaultActions, DefaultEvents, RootMessenger } from "@metamask/wallet";
4
- import type { KeyValueStore } from "./KeyValueStore.cjs";
1
+ import type { StateMetadataConstraint } from '@metamask/base-controller';
2
+ import type { Json } from '@metamask/utils';
3
+ import type { DefaultActions, DefaultEvents, RootMessenger } from '@metamask/wallet';
4
+ import type { KeyValueStore } from './KeyValueStore.js';
5
5
  /**
6
6
  * Load persisted state from the key-value store and reconstruct it as
7
7
  * a record keyed by controller name.
@@ -42,4 +42,4 @@ export declare function loadState(store: KeyValueStore, controllerMetadata: Read
42
42
  * @returns A function that unsubscribes all persistence handlers.
43
43
  */
44
44
  export declare function subscribeToChanges(messenger: Readonly<RootMessenger<DefaultActions, DefaultEvents>>, controllerMetadata: Readonly<Record<string, Readonly<StateMetadataConstraint>>>, store: KeyValueStore, log?: (message: string) => void): () => void;
45
- //# sourceMappingURL=persistence.d.cts.map
45
+ //# sourceMappingURL=persistence.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"persistence.d.ts","sourceRoot":"","sources":["../../src/persistence/persistence.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAEzE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,KAAK,EACV,cAAc,EACd,aAAa,EACb,aAAa,EACd,MAAM,kBAAkB,CAAC;AAG1B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAsBxD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,SAAS,CACvB,KAAK,EAAE,aAAa,EACpB,kBAAkB,EAAE,QAAQ,CAC1B,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,uBAAuB,CAAC,CAAC,CAClD,GACA,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CA8BtC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,kBAAkB,CAChC,SAAS,EAAE,QAAQ,CAAC,aAAa,CAAC,cAAc,EAAE,aAAa,CAAC,CAAC,EACjE,kBAAkB,EAAE,QAAQ,CAC1B,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,uBAAuB,CAAC,CAAC,CAClD,EACD,KAAK,EAAE,aAAa,EACpB,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,GAC9B,MAAM,IAAI,CAwDZ"}
@@ -1,4 +1,4 @@
1
- import { hasProperty } from "@metamask/utils";
1
+ import { hasProperty } from '@metamask/utils';
2
2
  /**
3
3
  * Construct a store key from a controller name and property name.
4
4
  *
@@ -196,4 +196,4 @@ function getChangedProperties(patches, persistedProperties) {
196
196
  }
197
197
  return changed;
198
198
  }
199
- //# sourceMappingURL=persistence.mjs.map
199
+ //# sourceMappingURL=persistence.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"persistence.js","sourceRoot":"","sources":["../../src/persistence/persistence.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAoB9C;;;;;;GAMG;AACH,SAAS,QAAQ,CAAC,cAAsB,EAAE,YAAoB;IAC5D,OAAO,GAAG,cAAc,IAAI,YAAY,EAAE,CAAC;AAC7C,CAAC;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,UAAU,SAAS,CACvB,KAAoB,EACpB,kBAEC;IAED,MAAM,QAAQ,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC;IAChC,MAAM,KAAK,GAAyC,EAAE,CAAC;IAEvD,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC;QACpD,MAAM,QAAQ,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAClC,IAAI,QAAQ,KAAK,CAAC,CAAC,EAAE,CAAC;YACpB,MAAM,IAAI,KAAK,CACb,0BAA0B,GAAG,mDAAmD,CACjF,CAAC;QACJ,CAAC;QACD,MAAM,cAAc,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC;QAC9C,MAAM,YAAY,GAAG,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AAC;QACpB,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { StateMetadataConstraint } from '@metamask/base-controller';\nimport { hasProperty } from '@metamask/utils';\nimport type { Json } from '@metamask/utils';\nimport type {\n DefaultActions,\n DefaultEvents,\n RootMessenger,\n} from '@metamask/wallet';\nimport type { Patch } from 'immer';\n\nimport type { KeyValueStore } from './KeyValueStore.js';\n\n/**\n * Handler for a controller's `stateChanged` event: the new controller state and\n * the Immer patches describing what changed.\n */\ntype StateChangedHandler = (\n state: Record<string, Json>,\n patches: Patch[],\n) => void;\n\n/**\n * Construct a store key from a controller name and property name.\n *\n * @param controllerName - The controller name.\n * @param propertyName - The property name.\n * @returns The store key in the format `ControllerName.propertyName`.\n */\nfunction storeKey(controllerName: string, propertyName: string): string {\n return `${controllerName}.${propertyName}`;\n}\n\n/**\n * Load persisted state from the key-value store and reconstruct it as\n * a record keyed by controller name.\n *\n * Keys in the store follow the format `ControllerName.propertyName`.\n * This function groups them into `{ [controllerName]: { [propertyName]: value } }`.\n *\n * Only properties that are currently persist-flagged in `controllerMetadata`\n * are rehydrated. Rows for controllers or properties that no longer exist — or\n * whose `persist` flag has since been disabled — are ignored. This keeps\n * loading symmetric with {@link subscribeToChanges}, which only ever writes\n * persist-flagged properties: without the filter, a migration that stops\n * persisting a property would leave its stale row on disk to be resurrected\n * into the `Wallet` constructor state on the next restart.\n *\n * @param store - The key-value store to read from.\n * @param controllerMetadata - A map from controller name to its state metadata,\n * used to filter out keys that are no longer persist-flagged.\n * @returns A record of controller states, keyed by controller name, suitable\n * for the `state` option of the `Wallet` constructor.\n */\nexport function loadState(\n store: KeyValueStore,\n controllerMetadata: Readonly<\n Record<string, Readonly<StateMetadataConstraint>>\n >,\n): Record<string, Record<string, Json>> {\n const allPairs = store.getAll();\n const state: Record<string, Record<string, Json>> = {};\n\n for (const [key, value] of Object.entries(allPairs)) {\n const dotIndex = key.indexOf('.');\n if (dotIndex === -1) {\n throw new Error(\n `Invalid key in store: '${key}'. Expected format 'ControllerName.propertyName'.`,\n );\n }\n const controllerName = key.slice(0, dotIndex);\n const propertyName = key.slice(dotIndex + 1);\n\n if (!controllerName || !propertyName) {\n throw new Error(\n `Invalid key in store: '${key}'. Both controller name and property name must be non-empty.`,\n );\n }\n\n if (!isPersisted(controllerMetadata[controllerName], propertyName)) {\n continue;\n }\n\n if (!state[controllerName]) {\n state[controllerName] = {};\n }\n state[controllerName][propertyName] = value;\n }\n return state;\n}\n\n/**\n * Subscribe to all controller `stateChanged` events and persist changes\n * to the key-value store.\n *\n * For each controller's metadata, this function determines which state\n * properties are persist-flagged. When a `stateChanged` event fires, it uses\n * the Immer patches to identify which top-level properties changed, filters\n * to only persist-flagged properties, and writes them to the store.\n *\n * @param messenger - The root messenger to subscribe on.\n * @param controllerMetadata - A map from controller name to its state metadata.\n * @param store - The key-value store to write to.\n * @param log - Optional logger for persistence-write failures. Defaults to\n * `console.error` when omitted. A daemon host should supply its own logger,\n * since a backgrounded daemon's stdio may be discarded.\n * @returns A function that unsubscribes all persistence handlers.\n */\nexport function subscribeToChanges(\n messenger: Readonly<RootMessenger<DefaultActions, DefaultEvents>>,\n controllerMetadata: Readonly<\n Record<string, Readonly<StateMetadataConstraint>>\n >,\n store: KeyValueStore,\n log?: (message: string) => void,\n): () => void {\n const unsubscribers: (() => void)[] = [];\n const logFn =\n log ??\n ((message: string): void => {\n console.error(message);\n });\n\n for (const [controllerName, metadata] of Object.entries(controllerMetadata)) {\n const persistedProperties = getPersistPropertyNames(metadata);\n if (persistedProperties.size === 0) {\n continue;\n }\n\n const eventType = `${controllerName}:stateChanged`;\n\n const handler: StateChangedHandler = (state, patches) => {\n const changed = getChangedProperties(patches, persistedProperties);\n\n for (const prop of changed) {\n const key = storeKey(controllerName, prop);\n const removed = !hasProperty(state, prop);\n\n // Derive the value before the try/catch so a throwing `StateDeriver`\n // surfaces as its own error instead of a misreported write failure.\n const persistFlag = metadata[prop]?.persist;\n const value =\n !removed && typeof persistFlag === 'function'\n ? persistFlag(state[prop] as never)\n : state[prop];\n\n try {\n if (removed) {\n store.delete(key);\n } else {\n store.set(key, value);\n }\n } catch (error) {\n // TODO: Surface persistence-write failures up the stack so callers\n // can decide to halt rather than continue with diverging in-memory\n // and on-disk state. For now, log and continue.\n logFn(`Failed to persist state for ${key}: ${String(error)}`);\n }\n }\n };\n\n unsubscribers.push(subscribeToStateChanged(messenger, eventType, handler));\n }\n\n const unsubscribeAll = (): void => {\n while (unsubscribers.length > 0) {\n unsubscribers.pop()?.();\n }\n };\n\n return unsubscribeAll;\n}\n\n/**\n * Subscribe a handler to a controller's `stateChanged` event.\n *\n * The event name is built from a runtime controller name, so it widens to\n * `string` and cannot be proven to be a literal member of the messenger's event\n * union at compile time. This helper localizes that single unavoidable cast\n * behind a typed {@link StateChangedHandler}, so the `(state, patches)` payload\n * shape stays compile-checked at every call site instead of being erased by a\n * statement-level `@ts-expect-error`.\n *\n * @param messenger - The root messenger to subscribe on.\n * @param eventType - The `${controllerName}:stateChanged` event name.\n * @param handler - The state-change handler to register.\n * @returns A function that unsubscribes the handler.\n */\nfunction subscribeToStateChanged(\n messenger: Readonly<RootMessenger<DefaultActions, DefaultEvents>>,\n eventType: string,\n handler: StateChangedHandler,\n): () => void {\n const subscriber = messenger as unknown as {\n subscribe: (eventType: string, handler: StateChangedHandler) => void;\n unsubscribe: (eventType: string, handler: StateChangedHandler) => void;\n };\n subscriber.subscribe(eventType, handler);\n return () => {\n subscriber.unsubscribe(eventType, handler);\n };\n}\n\n/**\n * Determine whether a property is currently persist-flagged.\n *\n * The `persist` flag is truthy when it is `true` or a `StateDeriver` function,\n * and falsy when it is `false` or when the controller or property is absent\n * from the metadata. `loadState` and `subscribeToChanges` share this predicate\n * so the read and write paths can never disagree on what counts as persisted.\n *\n * @param metadata - The controller's state metadata, or `undefined` when the\n * controller is absent from the metadata map.\n * @param propertyName - The property name to check.\n * @returns `true` if the property should be persisted.\n */\nfunction isPersisted(\n metadata: Readonly<StateMetadataConstraint> | undefined,\n propertyName: string,\n): boolean {\n return Boolean(metadata?.[propertyName]?.persist);\n}\n\n/**\n * Get the set of property names whose `persist` metadata is truthy\n * (either `true` or a `StateDeriver` function).\n *\n * @param metadata - The controller's state metadata.\n * @returns A set of property names that should be persisted.\n */\nfunction getPersistPropertyNames(\n metadata: StateMetadataConstraint,\n): ReadonlySet<string> {\n const names = new Set<string>();\n for (const key of Object.keys(metadata)) {\n if (isPersisted(metadata, key)) {\n names.add(key);\n }\n }\n return names;\n}\n\n/**\n * Extracts the set of persist-flagged top-level property names that changed\n * from an array of Immer patches.\n *\n * If any patch has an empty path (indicating a root state replacement),\n * all persist-flagged properties are returned.\n *\n * @param patches - Immer patches from a state update.\n * @param persistedProperties - The set of persist-flagged property names.\n * @returns A set of top-level property names that were modified.\n */\nfunction getChangedProperties(\n patches: Patch[],\n persistedProperties: ReadonlySet<string>,\n): ReadonlySet<string> {\n const changed = new Set<string>();\n for (const patch of patches) {\n if (patch.path.length === 0) {\n return persistedProperties;\n }\n\n const prop = String(patch.path[0]);\n if (persistedProperties.has(prop)) {\n changed.add(prop);\n }\n }\n return changed;\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { Command } from "@oclif/core";
2
- import type { Config } from "@oclif/core";
3
- import { CLIError } from "@oclif/core/errors";
1
+ import { Command } from '@oclif/core';
2
+ import type { Config } from '@oclif/core';
3
+ import { CLIError } from '@oclif/core/errors';
4
4
  type CommandCtor = new (argv: string[], config: Config) => Command & {
5
5
  _run: () => Promise<unknown>;
6
6
  };
@@ -24,4 +24,4 @@ export declare function runCommand(CommandClass: CommandCtor, argv?: string[]):
24
24
  error: CLIError | undefined;
25
25
  }>;
26
26
  export {};
27
- //# sourceMappingURL=run-command.d.cts.map
27
+ //# sourceMappingURL=run-command.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-command.d.ts","sourceRoot":"","sources":["../../src/test/run-command.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAE9C,KAAK,WAAW,GAAG,KACjB,IAAI,EAAE,MAAM,EAAE,EACd,MAAM,EAAE,MAAM,KACX,OAAO,GAAG;IACb,IAAI,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;CAC9B,CAAC;AAKF;;;;;;;;;;;;;GAaG;AACH,wBAAsB,UAAU,CAC9B,YAAY,EAAE,WAAW,EACzB,IAAI,GAAE,MAAM,EAAO,GAClB,OAAO,CAAC;IACT,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,QAAQ,GAAG,SAAS,CAAC;CAC7B,CAAC,CAkDD"}
@@ -1,5 +1,5 @@
1
- import { Command } from "@oclif/core";
2
- import { CLIError } from "@oclif/core/errors";
1
+ import { Command } from '@oclif/core';
2
+ import { CLIError } from '@oclif/core/errors';
3
3
  const TEST_DATA_DIR = '/tmp/mm-cli-test-data';
4
4
  const TEST_PACKAGE_ROOT = '/tmp/mm-cli-test-root';
5
5
  /**
@@ -66,4 +66,4 @@ export async function runCommand(CommandClass, argv = []) {
66
66
  }
67
67
  return { stdout, stderr, error };
68
68
  }
69
- //# sourceMappingURL=run-command.mjs.map
69
+ //# sourceMappingURL=run-command.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run-command.js","sourceRoot":"","sources":["../../src/test/run-command.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAEtC,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAS9C,MAAM,aAAa,GAAG,uBAAuB,CAAC;AAC9C,MAAM,iBAAiB,GAAG,uBAAuB,CAAC;AAElD;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CA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,CAAC;QAClE,MAAM,IAAI,QAAQ,CAAC,OAAO,CAAC,CAAC;IAC9B,CAAC,CAAC,CAAC;IAEL,IAAI,CAAC;QACH,MAAM,QAAQ,GAAG,IAAI,YAAY,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;QACpD,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;IACxB,CAAC;IAAC,OAAO,MAAe,EAAE,CAAC;QACzB,IAAI,MAAM,YAAY,QAAQ,EAAE,CAAC;YAC/B,KAAK,GAAG,MAAM,CAAC;YACf,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,IAAI,CAAC;QAClC,CAAC;aAAM,CAAC;YACN,MAAM,MAAM,CAAC;QACf,CAAC;IACH,CAAC;YAAS,CAAC;QACT,MAAM,CAAC,WAAW,EAAE,CAAC;QACrB,QAAQ,CAAC,WAAW,EAAE,CAAC;IACzB,CAAC;IAED,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;AACnC,CAAC","sourcesContent":["import { Command } from '@oclif/core';\nimport type { Config } from '@oclif/core';\nimport { CLIError } from '@oclif/core/errors';\n\ntype CommandCtor = new (\n argv: string[],\n config: Config,\n) => Command & {\n _run: () => Promise<unknown>;\n};\n\nconst TEST_DATA_DIR = '/tmp/mm-cli-test-data';\nconst TEST_PACKAGE_ROOT = '/tmp/mm-cli-test-root';\n\n/**\n * Invoke an oclif command class with the given argv and return the captured\n * stdout/stderr/error so tests can assert on them.\n *\n * Bypasses `Command.run`'s static plugin-loading path (which requires a real\n * `Config.load`) by constructing the command instance directly with a\n * hand-rolled `Config` and invoking the protected `_run`. Spies on the\n * Command prototype so `this.log` and `this.error` go to local buffers\n * instead of stdout/stderr.\n *\n * @param CommandClass - The command class (a subclass of `@oclif/core` Command).\n * @param argv - Command-line tokens (flags + positional args).\n * @returns Captured stdout, stderr, and any `this.error()` payload.\n */\nexport async function runCommand(\n CommandClass: CommandCtor,\n argv: string[] = [],\n): Promise<{\n stdout: string;\n stderr: string;\n error: CLIError | undefined;\n}> {\n let stdout = '';\n let stderr = '';\n let error: CLIError | undefined;\n\n const fakeConfig = {\n dataDir: TEST_DATA_DIR,\n root: TEST_PACKAGE_ROOT,\n bin: 'mm',\n name: '@metamask/wallet-cli',\n version: '0.0.0-test',\n pjson: { name: '@metamask/wallet-cli', version: '0.0.0-test' },\n findCommand: () => undefined,\n runHook: async () => ({ successes: [], failures: [] }),\n scopedEnvVar: () => undefined,\n scopedEnvVarKey: () => '',\n scopedEnvVarKeys: () => [],\n scopedEnvVarTrue: () => false,\n plugins: new Map(),\n flexibleTaxonomy: false,\n } as unknown as Config;\n\n const logSpy = jest\n .spyOn(Command.prototype, 'log')\n .mockImplementation((message: unknown = '') => {\n stdout += `${String(message)}\\n`;\n });\n const errorSpy = jest\n .spyOn(Command.prototype, 'error')\n .mockImplementation((input: string | Error) => {\n const message = typeof input === 'string' ? input : input.message;\n throw new CLIError(message);\n });\n\n try {\n const instance = new CommandClass(argv, fakeConfig);\n await instance._run();\n } catch (caught: unknown) {\n if (caught instanceof CLIError) {\n error = caught;\n stderr += `${caught.message}\\n`;\n } else {\n throw caught;\n }\n } finally {\n logSpy.mockRestore();\n errorSpy.mockRestore();\n }\n\n return { stdout, stderr, error };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/wallet-cli",
3
- "version": "0.0.0-preview-8bfa290fb",
3
+ "version": "0.0.0-preview-e8a256c39",
4
4
  "description": "The CLI of @metamask/wallet",
5
5
  "keywords": [
6
6
  "Ethereum",
@@ -22,6 +22,7 @@
22
22
  "bin/",
23
23
  "dist/"
24
24
  ],
25
+ "type": "module",
25
26
  "sideEffects": false,
26
27
  "exports": {
27
28
  "./package.json": "./package.json"
@@ -31,8 +32,10 @@
31
32
  "registry": "https://registry.npmjs.org/"
32
33
  },
33
34
  "scripts": {
34
- "build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references",
35
- "build:all": "ts-bridge --project tsconfig.build.json --verbose --clean",
35
+ "build": "tsc --project tsconfig.build.json",
36
+ "build:all": "tsc --build tsconfig.build.json --verbose",
37
+ "build:clean": "yarn build:only-clean && yarn build",
38
+ "build:only-clean": "rimraf './dist' './tsconfig.build.tsbuildinfo'",
36
39
  "changelog:update": "../../scripts/update-changelog.sh @metamask/wallet-cli",
37
40
  "changelog:validate": "../../scripts/validate-changelog.sh @metamask/wallet-cli",
38
41
  "lint:tsconfigs": "tsx ../../scripts/lint-tsconfigs/lint-tsconfigs.mts",
@@ -40,7 +43,7 @@
40
43
  "since-latest-release": "../../scripts/since-latest-release.sh",
41
44
  "test": "yarn test:prepare && NODE_OPTIONS=--experimental-vm-modules jest --reporters=jest-silent-reporter",
42
45
  "test:clean": "NODE_OPTIONS=--experimental-vm-modules jest --clearCache",
43
- "test:e2e": "yarn test:prepare && NODE_OPTIONS=--experimental-vm-modules jest --config jest.config.e2e.js",
46
+ "test:e2e": "yarn test:prepare && NODE_OPTIONS=--experimental-vm-modules jest --config jest.config.e2e.cjs",
44
47
  "test:e2e:install-anvil": "mm-foundryup",
45
48
  "test:prepare": "./scripts/install-binaries.sh",
46
49
  "test:verbose": "NODE_OPTIONS=--experimental-vm-modules jest --verbose",
@@ -49,34 +52,35 @@
49
52
  "dependencies": {
50
53
  "@inquirer/confirm": "^6.0.11",
51
54
  "@inquirer/password": "^5.1.1",
52
- "@metamask/analytics-controller": "^2.0.0",
53
- "@metamask/base-controller": "^9.1.0",
54
- "@metamask/config-registry-controller": "^3.1.0",
55
- "@metamask/messenger": "^2.0.0",
56
- "@metamask/remote-feature-flag-controller": "^6.1.0",
55
+ "@metamask/analytics-controller": "^3.0.0",
56
+ "@metamask/base-controller": "^10.0.0",
57
+ "@metamask/config-registry-controller": "^4.0.0",
58
+ "@metamask/messenger": "^3.0.0",
59
+ "@metamask/remote-feature-flag-controller": "^7.0.0",
57
60
  "@metamask/rpc-errors": "^7.0.2",
58
61
  "@metamask/scure-bip39": "^2.1.1",
59
- "@metamask/storage-service": "^1.0.2",
62
+ "@metamask/storage-service": "^2.0.0",
60
63
  "@metamask/superstruct": "^3.4.1",
61
64
  "@metamask/utils": "^11.12.0",
62
- "@metamask/wallet": "^12.0.2",
65
+ "@metamask/wallet": "^13.0.0",
63
66
  "@oclif/core": "^4.10.5",
64
67
  "better-sqlite3": "^12.9.0",
65
68
  "immer": "^9.0.6"
66
69
  },
67
70
  "devDependencies": {
68
71
  "@metamask/auto-changelog": "^6.1.0",
69
- "@metamask/foundryup": "^1.0.1",
70
- "@ts-bridge/cli": "^0.6.4",
72
+ "@metamask/foundryup": "^2.0.0",
71
73
  "@types/better-sqlite3": "^7.6.13",
72
74
  "@types/jest": "^30.0.0",
75
+ "@typescript/native": "npm:typescript@^7.0.2",
73
76
  "deepmerge": "^4.2.2",
74
77
  "jest": "^30.4.2",
75
78
  "jest-environment-node": "^30.4.1",
76
79
  "nock": "^13.3.1",
80
+ "rimraf": "^5.0.5",
77
81
  "ts-jest": "^29.4.11",
78
82
  "tsx": "^4.20.5",
79
- "typescript": "~5.3.3"
83
+ "typescript": "npm:@typescript/typescript6@^6.0.2"
80
84
  },
81
85
  "oclif": {
82
86
  "bin": "mm",
@@ -85,6 +89,6 @@
85
89
  "topicSeparator": " "
86
90
  },
87
91
  "engines": {
88
- "node": ">=20"
92
+ "node": "^22.14.0 || ^24"
89
93
  }
90
94
  }