@rfc0/patty 0.0.0-stage → 1.0.0

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 (465) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +214 -2
  3. package/dist/adapters/access-tokens.js +7 -0
  4. package/dist/adapters/accounts.js +37 -0
  5. package/dist/adapters/auth.js +11 -0
  6. package/dist/adapters/bills.js +32 -0
  7. package/dist/adapters/budgets.js +29 -0
  8. package/dist/adapters/categories.js +32 -0
  9. package/dist/adapters/client-grants.js +7 -0
  10. package/dist/adapters/credit-cards.js +33 -0
  11. package/dist/adapters/currencies.js +2 -0
  12. package/dist/adapters/currency-rates.js +18 -0
  13. package/dist/adapters/dashboards.js +43 -0
  14. package/dist/adapters/demo.js +13 -0
  15. package/dist/adapters/instance-settings.js +7 -0
  16. package/dist/adapters/invites.js +7 -0
  17. package/dist/adapters/recurring.js +55 -0
  18. package/dist/adapters/sessions.js +7 -0
  19. package/dist/adapters/settings.js +4 -0
  20. package/dist/adapters/setup-codes.js +7 -0
  21. package/dist/adapters/tags.js +9 -0
  22. package/dist/adapters/transactions.js +95 -0
  23. package/dist/adapters/users.js +7 -0
  24. package/dist/common/build-version.js +5 -0
  25. package/dist/common/errors.js +118 -0
  26. package/dist/common/net.js +71 -0
  27. package/dist/common/result.js +7 -0
  28. package/dist/composition/auth.js +106 -0
  29. package/dist/composition/boot.js +27 -0
  30. package/dist/composition/cli.js +86 -0
  31. package/dist/composition/demo/seed.js +92 -0
  32. package/dist/composition/demo/shell.js +107 -0
  33. package/dist/composition/export.js +89 -0
  34. package/dist/composition/http.js +110 -0
  35. package/dist/composition/import.js +55 -0
  36. package/dist/composition/lazy-modules.js +2 -0
  37. package/dist/composition/runtime.js +115 -0
  38. package/dist/composition/sign-in/interpreter.js +154 -0
  39. package/dist/composition/sign-in/server.js +36 -0
  40. package/dist/composition/sign-in/wiring.js +23 -0
  41. package/dist/composition/stdio.js +69 -0
  42. package/dist/config.js +136 -0
  43. package/dist/controllers/account/account.js +88 -0
  44. package/dist/controllers/account/transaction.js +119 -0
  45. package/dist/controllers/account/transfer.js +34 -0
  46. package/dist/controllers/aggregate.js +40 -0
  47. package/dist/controllers/auth/access-tokens.js +61 -0
  48. package/dist/controllers/auth/grants.js +136 -0
  49. package/dist/controllers/auth/key-export.js +20 -0
  50. package/dist/controllers/auth/owner.js +80 -0
  51. package/dist/controllers/auth/password.js +35 -0
  52. package/dist/controllers/auth/session.js +50 -0
  53. package/dist/controllers/auth/step-up.js +8 -0
  54. package/dist/controllers/auth/users.js +183 -0
  55. package/dist/controllers/budgets.js +87 -0
  56. package/dist/controllers/categories.js +67 -0
  57. package/dist/controllers/correlations.js +112 -0
  58. package/dist/controllers/credit-card/bill.js +105 -0
  59. package/dist/controllers/credit-card/credit-card.js +129 -0
  60. package/dist/controllers/credit-card/transaction.js +181 -0
  61. package/dist/controllers/currencies.js +1 -0
  62. package/dist/controllers/currency-rates.js +40 -0
  63. package/dist/controllers/dashboards.js +68 -0
  64. package/dist/controllers/demo/seed.js +31 -0
  65. package/dist/controllers/demo/tour.js +12 -0
  66. package/dist/controllers/deps.js +6 -0
  67. package/dist/controllers/instance.js +6 -0
  68. package/dist/controllers/merchants.js +12 -0
  69. package/dist/controllers/recurring.js +70 -0
  70. package/dist/controllers/resolve.js +37 -0
  71. package/dist/controllers/settings.js +47 -0
  72. package/dist/controllers/status.js +19 -0
  73. package/dist/controllers/summary.js +21 -0
  74. package/dist/controllers/tags.js +19 -0
  75. package/dist/controllers/transaction/bulk.js +6 -0
  76. package/dist/controllers/transaction/core.js +49 -0
  77. package/dist/controllers/transaction/read.js +28 -0
  78. package/dist/diplomat/auth/credentials.js +58 -0
  79. package/dist/diplomat/auth/sign-in-store.js +18 -0
  80. package/dist/diplomat/cli/commands/auth.js +100 -0
  81. package/dist/diplomat/cli/commands/db.js +72 -0
  82. package/dist/diplomat/cli/commands/demo.js +68 -0
  83. package/dist/diplomat/cli/commands/key.js +119 -0
  84. package/dist/diplomat/cli/commands/login.js +151 -0
  85. package/dist/diplomat/cli/commands/setup.js +132 -0
  86. package/dist/diplomat/cli/commands/users.js +123 -0
  87. package/dist/diplomat/cli/commands.js +61 -0
  88. package/dist/diplomat/cli/export-file.js +37 -0
  89. package/dist/diplomat/cli/import-file.js +44 -0
  90. package/dist/diplomat/cli/io.js +61 -0
  91. package/dist/diplomat/cli/key-export-approval.js +37 -0
  92. package/dist/diplomat/cli/messages.js +96 -0
  93. package/dist/diplomat/cli/prompt.js +74 -0
  94. package/dist/diplomat/cli/terminal.js +81 -0
  95. package/dist/diplomat/client-config/clients.js +150 -0
  96. package/dist/diplomat/client-config/merge.js +41 -0
  97. package/dist/diplomat/db/bootstrap.js +98 -0
  98. package/dist/diplomat/db/database-files.js +147 -0
  99. package/dist/diplomat/db/driver.js +167 -0
  100. package/dist/diplomat/db/effects.js +101 -0
  101. package/dist/diplomat/db/engine.js +9 -0
  102. package/dist/diplomat/db/export.js +22 -0
  103. package/dist/diplomat/db/file-lock.js +82 -0
  104. package/dist/diplomat/db/key-lock.js +14 -0
  105. package/dist/diplomat/db/locale-cache.js +23 -0
  106. package/dist/diplomat/db/migration-barrier.js +57 -0
  107. package/dist/diplomat/db/migration-journal.js +18 -0
  108. package/dist/diplomat/db/migration-lock.js +15 -0
  109. package/dist/diplomat/db/migrations.js +11 -0
  110. package/dist/diplomat/db/present.js +17 -0
  111. package/dist/diplomat/db/queries/aggregate-whitelist.js +35 -0
  112. package/dist/diplomat/db/queries/filters.js +59 -0
  113. package/dist/diplomat/db/queries/fts.js +18 -0
  114. package/dist/diplomat/db/queries/scope.js +8 -0
  115. package/dist/diplomat/db/queries/transaction-select.js +26 -0
  116. package/dist/diplomat/db/queries/tx-predicates.js +13 -0
  117. package/dist/diplomat/db/repos/access-tokens.js +27 -0
  118. package/dist/diplomat/db/repos/accounts.js +91 -0
  119. package/dist/diplomat/db/repos/bills.js +93 -0
  120. package/dist/diplomat/db/repos/budgets.js +72 -0
  121. package/dist/diplomat/db/repos/categories.js +53 -0
  122. package/dist/diplomat/db/repos/client-grants.js +67 -0
  123. package/dist/diplomat/db/repos/correlations.js +66 -0
  124. package/dist/diplomat/db/repos/credit-cards.js +67 -0
  125. package/dist/diplomat/db/repos/currencies.js +8 -0
  126. package/dist/diplomat/db/repos/currency-rates.js +40 -0
  127. package/dist/diplomat/db/repos/dashboards.js +123 -0
  128. package/dist/diplomat/db/repos/health.js +12 -0
  129. package/dist/diplomat/db/repos/instance-settings.js +14 -0
  130. package/dist/diplomat/db/repos/instance.js +58 -0
  131. package/dist/diplomat/db/repos/invites.js +43 -0
  132. package/dist/diplomat/db/repos/merchants.js +121 -0
  133. package/dist/diplomat/db/repos/recurring.js +29 -0
  134. package/dist/diplomat/db/repos/sessions.js +19 -0
  135. package/dist/diplomat/db/repos/settings.js +41 -0
  136. package/dist/diplomat/db/repos/setup-codes.js +28 -0
  137. package/dist/diplomat/db/repos/sub-categories.js +67 -0
  138. package/dist/diplomat/db/repos/tags.js +51 -0
  139. package/dist/diplomat/db/repos/transaction-tags.js +57 -0
  140. package/dist/diplomat/db/repos/transactions.js +163 -0
  141. package/dist/diplomat/db/repos/users.js +47 -0
  142. package/dist/diplomat/db/safety-copy.js +87 -0
  143. package/dist/diplomat/db/schema.js +348 -0
  144. package/dist/diplomat/db/seed/categories.js +112 -0
  145. package/dist/diplomat/db/seed/currencies.js +9 -0
  146. package/dist/diplomat/db/seed/demo/br.js +98 -0
  147. package/dist/diplomat/db/seed/demo/co.js +89 -0
  148. package/dist/diplomat/db/seed/demo/index.js +12 -0
  149. package/dist/diplomat/db/seed/demo/mx.js +90 -0
  150. package/dist/diplomat/db/seed/demo/shared.js +39 -0
  151. package/dist/diplomat/db/seed/demo/us.js +90 -0
  152. package/dist/diplomat/db/seed/merchant-rules.js +188 -0
  153. package/dist/diplomat/db/sqlite-errors.js +40 -0
  154. package/dist/diplomat/db/tenancy-integrity.js +45 -0
  155. package/dist/diplomat/db/version-guard.js +16 -0
  156. package/dist/diplomat/http/auth-pages.js +41 -0
  157. package/dist/diplomat/http/auth-paths.js +46 -0
  158. package/dist/diplomat/http/bearer.js +15 -0
  159. package/dist/diplomat/http/connect-pages.js +51 -0
  160. package/dist/diplomat/http/context.js +17 -0
  161. package/dist/diplomat/http/cookies.js +27 -0
  162. package/dist/diplomat/http/form-pages.js +38 -0
  163. package/dist/diplomat/http/hooks/auth.js +106 -0
  164. package/dist/diplomat/http/hooks/demo-marker.js +59 -0
  165. package/dist/diplomat/http/openapi.js +73 -0
  166. package/dist/diplomat/http/principal.js +1 -0
  167. package/dist/diplomat/http/rate-limiter.js +78 -0
  168. package/dist/diplomat/http/remedy.js +26 -0
  169. package/dist/diplomat/http/respond.js +50 -0
  170. package/dist/diplomat/http/routes/account.js +226 -0
  171. package/dist/diplomat/http/routes/aggregate.js +28 -0
  172. package/dist/diplomat/http/routes/auth.js +105 -0
  173. package/dist/diplomat/http/routes/budget.js +34 -0
  174. package/dist/diplomat/http/routes/category.js +109 -0
  175. package/dist/diplomat/http/routes/connect.js +124 -0
  176. package/dist/diplomat/http/routes/credit-card.js +263 -0
  177. package/dist/diplomat/http/routes/currency-rates.js +60 -0
  178. package/dist/diplomat/http/routes/currency.js +16 -0
  179. package/dist/diplomat/http/routes/dashboard.js +93 -0
  180. package/dist/diplomat/http/routes/invite.js +63 -0
  181. package/dist/diplomat/http/routes/recurring.js +65 -0
  182. package/dist/diplomat/http/routes/settings.js +38 -0
  183. package/dist/diplomat/http/routes/summary.js +23 -0
  184. package/dist/diplomat/http/routes/system.js +29 -0
  185. package/dist/diplomat/http/routes/tag.js +51 -0
  186. package/dist/diplomat/http/routes/tokens.js +72 -0
  187. package/dist/diplomat/http/routes/transaction.js +55 -0
  188. package/dist/diplomat/http/routes/transfer.js +35 -0
  189. package/dist/diplomat/http/routes/ui.js +110 -0
  190. package/dist/diplomat/http/routes/users.js +156 -0
  191. package/dist/diplomat/http/routes/well-known.js +26 -0
  192. package/dist/diplomat/http/routes.js +85 -0
  193. package/dist/diplomat/http/session.js +34 -0
  194. package/dist/diplomat/http/token-pages.js +75 -0
  195. package/dist/diplomat/http/ui-files.js +21 -0
  196. package/dist/diplomat/http/user-pages.js +93 -0
  197. package/dist/diplomat/mcp/annotations.js +8 -0
  198. package/dist/diplomat/mcp/auth-info.js +20 -0
  199. package/dist/diplomat/mcp/context.js +14 -0
  200. package/dist/diplomat/mcp/definition.js +3 -0
  201. package/dist/diplomat/mcp/gate.js +15 -0
  202. package/dist/diplomat/mcp/instructions.js +19 -0
  203. package/dist/diplomat/mcp/prompts.js +125 -0
  204. package/dist/diplomat/mcp/register.js +12 -0
  205. package/dist/diplomat/mcp/remedy.js +17 -0
  206. package/dist/diplomat/mcp/resources.js +93 -0
  207. package/dist/diplomat/mcp/respond.js +20 -0
  208. package/dist/diplomat/mcp/route.js +62 -0
  209. package/dist/diplomat/mcp/scopes.js +53 -0
  210. package/dist/diplomat/mcp/server.js +26 -0
  211. package/dist/diplomat/mcp/shared.js +5 -0
  212. package/dist/diplomat/mcp/stdio-session.js +94 -0
  213. package/dist/diplomat/mcp/stdio.js +23 -0
  214. package/dist/diplomat/mcp/tool-name.js +59 -0
  215. package/dist/diplomat/mcp/tools/account.js +218 -0
  216. package/dist/diplomat/mcp/tools/aggregate.js +32 -0
  217. package/dist/diplomat/mcp/tools/budget.js +99 -0
  218. package/dist/diplomat/mcp/tools/category.js +103 -0
  219. package/dist/diplomat/mcp/tools/correlations.js +70 -0
  220. package/dist/diplomat/mcp/tools/credit-card.js +239 -0
  221. package/dist/diplomat/mcp/tools/currency-rates.js +62 -0
  222. package/dist/diplomat/mcp/tools/dashboard.js +75 -0
  223. package/dist/diplomat/mcp/tools/index.js +31 -0
  224. package/dist/diplomat/mcp/tools/recurring.js +62 -0
  225. package/dist/diplomat/mcp/tools/summary.js +30 -0
  226. package/dist/diplomat/mcp/tools/system.js +83 -0
  227. package/dist/diplomat/mcp/tools/tag.js +48 -0
  228. package/dist/diplomat/mcp/tools/transaction.js +53 -0
  229. package/dist/diplomat/mcp/tools/transfer.js +28 -0
  230. package/dist/diplomat/mcp/tour.js +87 -0
  231. package/dist/logic/account.js +79 -0
  232. package/dist/logic/aggregate.js +37 -0
  233. package/dist/logic/auth/bearer.js +35 -0
  234. package/dist/logic/auth/grant.js +126 -0
  235. package/dist/logic/auth/key-export.js +10 -0
  236. package/dist/logic/auth/keychain.js +3 -0
  237. package/dist/logic/auth/message.js +22 -0
  238. package/dist/logic/auth/origin.js +57 -0
  239. package/dist/logic/auth/owner.js +22 -0
  240. package/dist/logic/auth/password.js +3 -0
  241. package/dist/logic/auth/redact.js +25 -0
  242. package/dist/logic/auth/revoke.js +28 -0
  243. package/dist/logic/auth/scope.js +17 -0
  244. package/dist/logic/auth/session.js +30 -0
  245. package/dist/logic/auth/sign-in-flow.js +305 -0
  246. package/dist/logic/auth/time.js +2 -0
  247. package/dist/logic/auth/token.js +74 -0
  248. package/dist/logic/auth/user-plans.js +84 -0
  249. package/dist/logic/auth/users.js +78 -0
  250. package/dist/logic/balance.js +2 -0
  251. package/dist/logic/bill.js +74 -0
  252. package/dist/logic/budget.js +78 -0
  253. package/dist/logic/category.js +37 -0
  254. package/dist/logic/classify.js +21 -0
  255. package/dist/logic/correlations.js +147 -0
  256. package/dist/logic/credit-card.js +2 -0
  257. package/dist/logic/currency-rate.js +69 -0
  258. package/dist/logic/dashboard.js +40 -0
  259. package/dist/logic/demo/database.js +30 -0
  260. package/dist/logic/demo/plan.js +308 -0
  261. package/dist/logic/demo/tour.js +33 -0
  262. package/dist/logic/export-destination.js +12 -0
  263. package/dist/logic/key-import.js +15 -0
  264. package/dist/logic/locale.js +5 -0
  265. package/dist/logic/localize.js +12 -0
  266. package/dist/logic/merchant.js +31 -0
  267. package/dist/logic/migration.js +1 -0
  268. package/dist/logic/money.js +12 -0
  269. package/dist/logic/period.js +45 -0
  270. package/dist/logic/persistence.js +48 -0
  271. package/dist/logic/recurring.js +51 -0
  272. package/dist/logic/resolve.js +44 -0
  273. package/dist/logic/summary.js +29 -0
  274. package/dist/logic/tag.js +13 -0
  275. package/dist/logic/transaction.js +197 -0
  276. package/dist/main.js +42 -0
  277. package/dist/models/account.js +197 -0
  278. package/dist/models/aggregate.js +61 -0
  279. package/dist/models/auth/bearer.js +11 -0
  280. package/dist/models/auth/entity.js +17 -0
  281. package/dist/models/auth/errors.js +42 -0
  282. package/dist/models/auth/grant.js +58 -0
  283. package/dist/models/auth/key-export.js +11 -0
  284. package/dist/models/auth/message.js +50 -0
  285. package/dist/models/auth/mode.js +7 -0
  286. package/dist/models/auth/origin.js +16 -0
  287. package/dist/models/auth/owner.js +36 -0
  288. package/dist/models/auth/password.js +24 -0
  289. package/dist/models/auth/principal.js +26 -0
  290. package/dist/models/auth/redact.js +4 -0
  291. package/dist/models/auth/scope.js +9 -0
  292. package/dist/models/auth/session.js +19 -0
  293. package/dist/models/auth/sign-in-flow.js +102 -0
  294. package/dist/models/auth/sign-in.js +41 -0
  295. package/dist/models/auth/time.js +5 -0
  296. package/dist/models/auth/token.js +50 -0
  297. package/dist/models/auth/users.js +52 -0
  298. package/dist/models/bill.js +55 -0
  299. package/dist/models/budget.js +106 -0
  300. package/dist/models/category.js +52 -0
  301. package/dist/models/client-config.js +18 -0
  302. package/dist/models/correlations.js +215 -0
  303. package/dist/models/credit-card.js +156 -0
  304. package/dist/models/currency-rate.js +83 -0
  305. package/dist/models/dashboard.js +54 -0
  306. package/dist/models/database.js +16 -0
  307. package/dist/models/date.js +8 -0
  308. package/dist/models/demo/core.js +58 -0
  309. package/dist/models/demo/tour.js +41 -0
  310. package/dist/models/encryption-key.js +2 -0
  311. package/dist/models/error.js +13 -0
  312. package/dist/models/export.js +9 -0
  313. package/dist/models/id.js +2 -0
  314. package/dist/models/instance.js +7 -0
  315. package/dist/models/key-import.js +6 -0
  316. package/dist/models/locale.js +25 -0
  317. package/dist/models/merchant.js +12 -0
  318. package/dist/models/money.js +14 -0
  319. package/dist/models/package.js +12 -0
  320. package/dist/models/page.js +56 -0
  321. package/dist/models/persistence.js +1 -0
  322. package/dist/models/prompts.js +5 -0
  323. package/dist/models/recurring.js +54 -0
  324. package/dist/models/remedy.js +17 -0
  325. package/dist/models/resolution.js +1 -0
  326. package/dist/models/startup.js +7 -0
  327. package/dist/models/summary.js +24 -0
  328. package/dist/models/tag.js +14 -0
  329. package/dist/models/tenancy.js +10 -0
  330. package/dist/models/transaction-tag.js +6 -0
  331. package/dist/models/transaction.js +275 -0
  332. package/dist/wire/db/access-tokens.js +1 -0
  333. package/dist/wire/db/accounts.js +7 -0
  334. package/dist/wire/db/aggregate.js +16 -0
  335. package/dist/wire/db/bills.js +14 -0
  336. package/dist/wire/db/budgets.js +33 -0
  337. package/dist/wire/db/categories.js +14 -0
  338. package/dist/wire/db/client-grants.js +1 -0
  339. package/dist/wire/db/correlations.js +49 -0
  340. package/dist/wire/db/credit-cards.js +1 -0
  341. package/dist/wire/db/currencies.js +1 -0
  342. package/dist/wire/db/currency-rates.js +1 -0
  343. package/dist/wire/db/dashboards.js +1 -0
  344. package/dist/wire/db/instance-settings.js +1 -0
  345. package/dist/wire/db/invites.js +1 -0
  346. package/dist/wire/db/merchants.js +18 -0
  347. package/dist/wire/db/recurring.js +19 -0
  348. package/dist/wire/db/sessions.js +1 -0
  349. package/dist/wire/db/settings.js +1 -0
  350. package/dist/wire/db/setup-codes.js +1 -0
  351. package/dist/wire/db/tags.js +1 -0
  352. package/dist/wire/db/tenancy.js +1 -0
  353. package/dist/wire/db/transactions.js +89 -0
  354. package/dist/wire/db/users.js +1 -0
  355. package/dist/wire/in/accounts.js +26 -0
  356. package/dist/wire/in/aggregate.js +10 -0
  357. package/dist/wire/in/auth.js +107 -0
  358. package/dist/wire/in/bills.js +11 -0
  359. package/dist/wire/in/budgets.js +11 -0
  360. package/dist/wire/in/categories.js +9 -0
  361. package/dist/wire/in/cli.js +106 -0
  362. package/dist/wire/in/coerce.js +6 -0
  363. package/dist/wire/in/common.js +17 -0
  364. package/dist/wire/in/credit-cards.js +16 -0
  365. package/dist/wire/in/currency-rates.js +8 -0
  366. package/dist/wire/in/period.js +7 -0
  367. package/dist/wire/in/recurring.js +6 -0
  368. package/dist/wire/in/settings.js +5 -0
  369. package/dist/wire/in/summary.js +5 -0
  370. package/dist/wire/in/tags.js +2 -0
  371. package/dist/wire/in/transactions.js +31 -0
  372. package/dist/wire/out/bills.js +9 -0
  373. package/dist/wire/out/budgets.js +10 -0
  374. package/dist/wire/out/client-config.js +2 -0
  375. package/dist/wire/out/common.js +4 -0
  376. package/dist/wire/out/credit-cards.js +15 -0
  377. package/dist/wire/out/currency-rates.js +11 -0
  378. package/dist/wire/out/errors.js +58 -0
  379. package/dist/wire/out/recurring.js +6 -0
  380. package/dist/wire/out/status.js +10 -0
  381. package/dist/wire/out/summary.js +9 -0
  382. package/dist/wire/out/transactions.js +52 -0
  383. package/drizzle/0000_futuristic_umar.sql +124 -0
  384. package/drizzle/0001_fts5_search.sql +23 -0
  385. package/drizzle/0002_rename_graph_to_history.sql +7 -0
  386. package/drizzle/0003_lyrical_hairball.sql +2 -0
  387. package/drizzle/0004_misty_ikaris.sql +7 -0
  388. package/drizzle/0005_credit-liability-accounts.sql +14 -0
  389. package/drizzle/0006_smart_aqueduct.sql +1 -0
  390. package/drizzle/0007_add_dashboards.sql +5 -0
  391. package/drizzle/0008_yummy_madripoor.sql +1 -0
  392. package/drizzle/0009_version_groundwork.sql +9 -0
  393. package/drizzle/0010_category_merchant_association_cascade.sql +16 -0
  394. package/drizzle/0011_dashboard_id_normalization.sql +16 -0
  395. package/drizzle/0012_hot_the_spike.sql +12 -0
  396. package/drizzle/0013_recurring_rules_merchant.sql +1 -0
  397. package/drizzle/0014_dashboard_source_discriminator.sql +17 -0
  398. package/drizzle/0015_currencies_decimals.sql +1 -0
  399. package/drizzle/0016_unusual_zaran.sql +13 -0
  400. package/drizzle/0017_premium_blur.sql +1 -0
  401. package/drizzle/0018_auth_identity.sql +39 -0
  402. package/drizzle/0019_access_tokens.sql +16 -0
  403. package/drizzle/0020_stdio_sign_in.sql +27 -0
  404. package/drizzle/0021_tenancy_data.sql +289 -0
  405. package/drizzle/0022_user_management.sql +17 -0
  406. package/drizzle/0023_instance_settings_row.sql +2 -0
  407. package/drizzle/0024_credentials_changed_at.sql +2 -0
  408. package/drizzle/0025_instance_kind.sql +2 -0
  409. package/drizzle/0026_demo_seeded_at.sql +2 -0
  410. package/drizzle/0027_demo_country.sql +2 -0
  411. package/drizzle/0028_reset_sign_ins.sql +2 -0
  412. package/drizzle/meta/0000_snapshot.json +894 -0
  413. package/drizzle/meta/0003_snapshot.json +910 -0
  414. package/drizzle/meta/0004_snapshot.json +951 -0
  415. package/drizzle/meta/0005_snapshot.json +991 -0
  416. package/drizzle/meta/0006_snapshot.json +998 -0
  417. package/drizzle/meta/0007_snapshot.json +1029 -0
  418. package/drizzle/meta/0008_snapshot.json +1049 -0
  419. package/drizzle/meta/0009_snapshot.json +1121 -0
  420. package/drizzle/meta/0010_snapshot.json +1121 -0
  421. package/drizzle/meta/0011_snapshot.json +1136 -0
  422. package/drizzle/meta/0012_snapshot.json +1227 -0
  423. package/drizzle/meta/0013_snapshot.json +1247 -0
  424. package/drizzle/meta/0014_snapshot.json +1267 -0
  425. package/drizzle/meta/0015_snapshot.json +1275 -0
  426. package/drizzle/meta/0016_snapshot.json +1371 -0
  427. package/drizzle/meta/0017_snapshot.json +1392 -0
  428. package/drizzle/meta/0018_snapshot.json +1603 -0
  429. package/drizzle/meta/0019_snapshot.json +1713 -0
  430. package/drizzle/meta/0020_snapshot.json +1904 -0
  431. package/drizzle/meta/0021_snapshot.json +2186 -0
  432. package/drizzle/meta/0022_snapshot.json +2311 -0
  433. package/drizzle/meta/0023_snapshot.json +2311 -0
  434. package/drizzle/meta/0024_snapshot.json +2318 -0
  435. package/drizzle/meta/0025_snapshot.json +2326 -0
  436. package/drizzle/meta/0026_snapshot.json +2333 -0
  437. package/drizzle/meta/0027_snapshot.json +2340 -0
  438. package/drizzle/meta/0028_snapshot.json +2340 -0
  439. package/drizzle/meta/_journal.json +209 -0
  440. package/package.json +106 -4
  441. package/skills/dashboard-building/SKILL.md +201 -0
  442. package/skills/patty-tour/SKILL.md +34 -0
  443. package/ui/app.css +758 -0
  444. package/ui/app.js +493 -0
  445. package/ui/connect-result.html +16 -0
  446. package/ui/connect.html +53 -0
  447. package/ui/dashboards/accounts.html +3189 -0
  448. package/ui/dashboards/budget.html +1716 -0
  449. package/ui/dashboards/cards.html +4032 -0
  450. package/ui/dashboards/categories.html +4694 -0
  451. package/ui/dashboards/comparative.html +2464 -0
  452. package/ui/dashboards/dashboards.html +839 -0
  453. package/ui/dashboards/overview.html +2405 -0
  454. package/ui/dashboards/pending.html +2973 -0
  455. package/ui/dashboards/projections.html +2517 -0
  456. package/ui/dashboards/tags.html +1365 -0
  457. package/ui/invite.html +44 -0
  458. package/ui/login.html +26 -0
  459. package/ui/money.js +175 -0
  460. package/ui/setup.html +29 -0
  461. package/ui/shell.html +96 -0
  462. package/ui/token-created.html +24 -0
  463. package/ui/tokens.html +58 -0
  464. package/ui/user-invited.html +27 -0
  465. package/ui/users.html +60 -0
@@ -0,0 +1,74 @@
1
+ import { err, errAsync, ok, safeTry } from 'neverthrow';
2
+ import { PASSWORD_STDIN_FLAG } from '../../wire/in/cli.js';
3
+ import { isExportConfirmation } from '../../logic/auth/key-export.js';
4
+ import { KEY_EXPORT_CONFIRMATION_ANSWER } from '../../models/auth/key-export.js';
5
+ import { normalizeUsername, PasswordSchema, UsernameSchema } from '../../models/auth/password.js';
6
+ import { invalidAnswer, PromptFailureCode } from './terminal.js';
7
+ export const MAX_PROMPT_ATTEMPTS = 3;
8
+ export const PROMPT_MESSAGES = {
9
+ username: 'Username: ',
10
+ password: 'Password: ',
11
+ confirmation: 'Confirm password: ',
12
+ exportConfirmation: `Write the key file? Type ${KEY_EXPORT_CONFIRMATION_ANSWER} to confirm: `,
13
+ passwordsDiffer: 'The two passwords differ.',
14
+ invalidAnswer: 'That is not valid.',
15
+ usernameRequiredWithStdin: `--${PASSWORD_STDIN_FLAG} needs --username <name>: stdin carries only the password.`,
16
+ noTerminal: 'There is no terminal to ask for a password. Run this command in a terminal, or pipe the password in on ' +
17
+ `stdin with --${PASSWORD_STDIN_FLAG} (choosing the owner's login also needs --username <name>).`,
18
+ };
19
+ export const isPromptEnded = (failure) => failure.code === PromptFailureCode.enum.prompt_ended;
20
+ const decode = (schema) => (raw) => {
21
+ const parsed = schema.safeParse(raw);
22
+ return parsed.success
23
+ ? ok(parsed.data)
24
+ : err(invalidAnswer(parsed.error.issues[0]?.message ?? PROMPT_MESSAGES.invalidAnswer));
25
+ };
26
+ const decodeUsername = decode(UsernameSchema);
27
+ const decodePassword = decode(PasswordSchema);
28
+ /** An invalid answer is asked again (and told why) until the attempts run out; an ended prompt is never retried. */
29
+ const withRetries = (terminal, attempt, attemptsLeft = MAX_PROMPT_ATTEMPTS) => attempt().orElse((failure) => {
30
+ if (isPromptEnded(failure) || attemptsLeft <= 1)
31
+ return errAsync(failure);
32
+ terminal.tell(failure.message);
33
+ return withRetries(terminal, attempt, attemptsLeft - 1);
34
+ });
35
+ const askUsername = (terminal) => withRetries(terminal, () => terminal.ask(PROMPT_MESSAGES.username).andThen(decodeUsername));
36
+ /** An existing administrator's login. Neither answer is format-checked, so a refusal costs and says the same whatever
37
+ * was typed (a stored username may predate today's policy); the password is never echoed. */
38
+ export const askAdminCredentials = (terminal) => safeTry(async function* () {
39
+ const username = yield* terminal.ask(PROMPT_MESSAGES.username).map(normalizeUsername);
40
+ const password = yield* terminal.askSecret(PROMPT_MESSAGES.password);
41
+ return ok({ username, password });
42
+ });
43
+ /** Whether the person typed the one confirming answer; anything else is a no. */
44
+ export const askExportConfirmation = (terminal) => terminal.ask(PROMPT_MESSAGES.exportConfirmation).map(isExportConfirmation);
45
+ const askNewPassword = (terminal) => withRetries(terminal, () => safeTry(async function* () {
46
+ const password = yield* terminal.askSecret(PROMPT_MESSAGES.password).andThen(decodePassword);
47
+ const confirmation = yield* terminal.askSecret(PROMPT_MESSAGES.confirmation);
48
+ return confirmation === password ? ok(password) : err(invalidAnswer(PROMPT_MESSAGES.passwordsDiffer));
49
+ }));
50
+ const piped = async (io) => decodePassword(await io.readPasswordFromStdin());
51
+ const canAskPassword = (io, options) => options.passwordStdin || io.terminal !== null;
52
+ /** Never hangs: with no pipe and no terminal it fails with instructions. */
53
+ export const collectNewPassword = async (io, options) => {
54
+ if (options.passwordStdin)
55
+ return piped(io);
56
+ return io.terminal ? askNewPassword(io.terminal) : err(invalidAnswer(PROMPT_MESSAGES.noTerminal));
57
+ };
58
+ const collectUsername = async (io, options) => {
59
+ if (options.username !== undefined)
60
+ return decodeUsername(options.username);
61
+ return io.terminal ? askUsername(io.terminal) : err(invalidAnswer(PROMPT_MESSAGES.noTerminal));
62
+ };
63
+ /** With `--password-stdin` stdin is only the password, so the username must come from `--username`. */
64
+ export const collectNewCredentials = async (io, options) => {
65
+ if (options.passwordStdin && options.username === undefined)
66
+ return err(invalidAnswer(PROMPT_MESSAGES.usernameRequiredWithStdin));
67
+ if (!canAskPassword(io, options))
68
+ return err(invalidAnswer(PROMPT_MESSAGES.noTerminal));
69
+ const username = await collectUsername(io, options);
70
+ if (username.isErr())
71
+ return err(username.error);
72
+ const password = await collectNewPassword(io, options);
73
+ return password.map((value) => ({ username: username.value, password: value }));
74
+ };
@@ -0,0 +1,81 @@
1
+ import { err, ok, ResultAsync } from 'neverthrow';
2
+ import { z } from 'zod';
3
+ import { createInterface } from 'node:readline/promises';
4
+ import { Writable } from 'node:stream';
5
+ import { PASSWORD_STDIN_FLAG } from '../../wire/in/cli.js';
6
+ import { text } from 'node:stream/consumers';
7
+ /** How a prompt ended without an answer: Ctrl-C, or the input closing (Ctrl-D). */
8
+ export const PromptEnd = z.enum(['interrupted', 'cancelled']);
9
+ /** Why asking a person failed: the prompt ended before an answer came, or the answer is not valid. */
10
+ export const PromptFailureCode = z.enum(['prompt_ended', 'invalid_answer']);
11
+ export const promptEnded = (how) => ({ code: PromptFailureCode.enum.prompt_ended, how });
12
+ export const invalidAnswer = (message) => ({
13
+ code: PromptFailureCode.enum.invalid_answer,
14
+ message,
15
+ });
16
+ export const PROMPT_ABORTED_MESSAGE = 'cancelled';
17
+ export const STDIN_IS_A_TERMINAL_MESSAGE = `--${PASSWORD_STDIN_FLAG} expects the password piped or redirected in, but stdin is a terminal`;
18
+ /** Readline remembers every answer, secret ones included, and Up would print them back: remember none. */
19
+ const NO_HISTORY = 0;
20
+ const TRAILING_NEWLINE = /\r?\n$/;
21
+ export const printResult = (line) => {
22
+ process.stdout.write(`${line}\n`);
23
+ };
24
+ export const printDiagnostic = (line) => {
25
+ process.stderr.write(`${line}\n`);
26
+ };
27
+ export const isInteractive = () => process.stdin.isTTY === true;
28
+ /** Races a question against the prompt ending. A question on a closed interface rejects: that is the prompt having
29
+ * ended (Ctrl-C between prompts), not a crash. */
30
+ const answer = (ended, question) => {
31
+ const stopped = ended.then((end) => err(end));
32
+ // `question` runs now, not on a later tick: the prompt text is written before a secret answer mutes the output.
33
+ const pending = new Promise((resolve, reject) => {
34
+ question().then(resolve, reject);
35
+ }).then((line) => ok(line), () => stopped);
36
+ return new ResultAsync(Promise.race([pending, stopped]));
37
+ };
38
+ /**
39
+ * Prompts on stderr; a secret answer is swallowed by a muted stream. Ctrl-C ends the prompt as `interrupted`, Ctrl-D
40
+ * as `cancelled`; both are answers, not exceptions. Ctrl-C between prompts takes effect at the next prompt: a step
41
+ * already running (hashing, a claim) finishes — deliberately, so no write is cut in half.
42
+ */
43
+ export const open = (streams = { input: process.stdin, output: process.stderr }) => {
44
+ let muted = false;
45
+ let interrupted = false;
46
+ const output = new Writable({
47
+ write: (chunk, encoding, callback) => {
48
+ if (!muted)
49
+ streams.output.write(chunk, encoding);
50
+ callback();
51
+ },
52
+ });
53
+ const lines = createInterface({ input: streams.input, output, terminal: true, historySize: NO_HISTORY });
54
+ const ended = new Promise((resolve) => {
55
+ lines.once('close', () => resolve(promptEnded(interrupted ? PromptEnd.enum.interrupted : PromptEnd.enum.cancelled)));
56
+ });
57
+ lines.once('SIGINT', () => {
58
+ interrupted = true;
59
+ lines.close();
60
+ streams.output.write('\n');
61
+ });
62
+ return {
63
+ ask: (question) => answer(ended, () => lines.question(question)),
64
+ askSecret: (question) => {
65
+ const secret = answer(ended, () => lines.question(question));
66
+ muted = true; // after the prompt text is written, before anything is typed
67
+ return new ResultAsync(Promise.resolve(secret).finally(() => {
68
+ muted = false;
69
+ if (!interrupted)
70
+ streams.output.write('\n');
71
+ }));
72
+ },
73
+ tell: printDiagnostic,
74
+ close: () => lines.close(),
75
+ };
76
+ };
77
+ export const readPasswordFromStdin = async () => {
78
+ if (isInteractive())
79
+ throw new Error(STDIN_IS_A_TERMINAL_MESSAGE);
80
+ return (await text(process.stdin)).replace(TRAILING_NEWLINE, '');
81
+ };
@@ -0,0 +1,150 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, join } from 'node:path';
4
+ import { err, ok, Result } from 'neverthrow';
5
+ import * as R from 'remeda';
6
+ import { DEFAULT_PROFILE, PROFILE_ENV_VAR } from '../../models/auth/sign-in.js';
7
+ import { clientConfigFailures } from '../../models/client-config.js';
8
+ import { DEMO_SERVER_NAME } from '../../models/demo/core.js';
9
+ import { PACKAGE_SPEC } from '../../models/package.js';
10
+ import { ServersKey } from '../../wire/out/client-config.js';
11
+ import { mergeMcpServersKey, mergeServersKey, resolveConfigObject, SERVER_NAME, STDIO_ENTRY, VSCODE_ENTRY, withDemo, withoutServer, withProfile, } from './merge.js';
12
+ // ---------------------------------------------------------------------------
13
+ // FS helpers
14
+ // ---------------------------------------------------------------------------
15
+ const INVALID_ROOT_MESSAGE = 'does not contain a JSON object at the root';
16
+ const invalidConfigWarning = (path) => `patty setup: ${path} ${INVALID_ROOT_MESSAGE} — replacing it during setup.`;
17
+ // The throwing system calls, wrapped once: everything below this block is Results.
18
+ const readText = Result.fromThrowable((path) => readFileSync(path, 'utf8'), R.identity());
19
+ const writeText = Result.fromThrowable((path, text) => {
20
+ mkdirSync(dirname(path), { recursive: true });
21
+ writeFileSync(path, text, 'utf8');
22
+ }, R.identity());
23
+ const parseJson = Result.fromThrowable((text) => JSON.parse(text), R.identity());
24
+ const replaceUnusable = (path) => ok({ config: {}, warnings: [invalidConfigWarning(path)] });
25
+ const refuseUnusable = (path) => err(clientConfigFailures.readFailed(path, `${INVALID_ROOT_MESSAGE}, or is not plain JSON — left unchanged`));
26
+ /** The demo entry refuses an unusable file instead of replacing it. */
27
+ export const readJsonOrEmpty = (path, whenUnusable = replaceUnusable) => {
28
+ if (!existsSync(path))
29
+ return ok({ config: {}, warnings: [] });
30
+ return readText(path)
31
+ .mapErr((cause) => clientConfigFailures.readFailed(path, cause))
32
+ .andThen((content) => {
33
+ const trimmed = content.trim();
34
+ if (!trimmed)
35
+ return ok({ config: {}, warnings: [] });
36
+ const config = parseJson(trimmed).map(resolveConfigObject).unwrapOr(null);
37
+ return config ? ok({ config, warnings: [] }) : whenUnusable(path);
38
+ });
39
+ };
40
+ const writeJson = (path, data) => writeText(path, JSON.stringify(data, null, 2) + '\n').mapErr((cause) => clientConfigFailures.writeFailed(path, cause));
41
+ // ---------------------------------------------------------------------------
42
+ // Platform-aware config path helpers
43
+ // ---------------------------------------------------------------------------
44
+ const home = homedir();
45
+ const claudeDesktopConfigPath = () => {
46
+ if (process.platform === 'win32') {
47
+ const appData = process.env['APPDATA'] ?? join(home, 'AppData', 'Roaming');
48
+ return join(appData, 'Claude', 'claude_desktop_config.json');
49
+ }
50
+ if (process.platform === 'darwin') {
51
+ return join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json');
52
+ }
53
+ return join(home, '.config', 'Claude', 'claude_desktop_config.json');
54
+ };
55
+ /** Reads the client's file, merges the PATTY entry in, writes it back, and reports. */
56
+ const writeEntry = (configPath, merge, entry, next, whenUnusable = replaceUnusable) => readJsonOrEmpty(configPath, whenUnusable).andThen(({ config, warnings }) => writeJson(configPath, merge(config, entry))
57
+ .map(() => ({ warnings, lines: [` Updated: ${configPath}`, next] }))
58
+ // What was raised while reading is still owed to the person, ahead of the failure.
59
+ .mapErr((failure) => ({ ...failure, warnings })));
60
+ const nothingToRemove = (reason) => ok({ warnings: [], lines: [` ${reason}`] });
61
+ const removeDemoEntry = (configPath, key, next) => {
62
+ if (!existsSync(configPath))
63
+ return nothingToRemove(`No demo entry to remove: ${configPath} does not exist`);
64
+ return readJsonOrEmpty(configPath, refuseUnusable).andThen(({ config, warnings }) => {
65
+ const without = withoutServer(config, key, DEMO_SERVER_NAME);
66
+ if (without === null)
67
+ return nothingToRemove(`No ${DEMO_SERVER_NAME} entry in ${configPath}`);
68
+ return writeJson(configPath, without)
69
+ .map(() => ({ warnings, lines: [` Removed ${DEMO_SERVER_NAME} from ${configPath}`, next] }))
70
+ .mapErr((failure) => ({ ...failure, warnings }));
71
+ });
72
+ };
73
+ const MERGE_BY_KEY = {
74
+ [ServersKey.enum.mcpServers]: mergeMcpServersKey,
75
+ [ServersKey.enum.servers]: mergeServersKey,
76
+ };
77
+ const fileClient = ({ label, path, key, entry, next }) => ({
78
+ label,
79
+ run: (profile) => writeEntry(path(), MERGE_BY_KEY[key], withProfile(entry, profile), next),
80
+ addDemo: (databasePath) => writeEntry(path(), (existing, demoEntry) => MERGE_BY_KEY[key](existing, demoEntry, DEMO_SERVER_NAME), withDemo(entry, databasePath), next, refuseUnusable),
81
+ removeDemo: () => removeDemoEntry(path(), key, next),
82
+ });
83
+ // Codex CLI MCP configuration path and format is not yet stable: describe the snippet and let the user place it.
84
+ /** JSON-escaped: a path may hold backslashes or quotes. */
85
+ const inlineObject = (env) => `{ ${Object.entries(env)
86
+ .map(([name, value]) => `${JSON.stringify(name)}: ${JSON.stringify(value)}`)
87
+ .join(', ')} }`;
88
+ const codexSnippet = (name, env) => ` Codex CLI: add the following to your MCP config file:
89
+
90
+ {
91
+ "mcpServers": {
92
+ "${name}": {
93
+ "command": "npx",
94
+ "args": ["-y", "${PACKAGE_SPEC}"]${env === null ? '' : `,\n "env": ${inlineObject(env)}`}
95
+ }
96
+ }
97
+ }
98
+
99
+ Refer to the Codex CLI docs for the exact config file location.`;
100
+ const setupCodex = (profile) => ok({
101
+ warnings: [],
102
+ lines: [codexSnippet(SERVER_NAME, profile === DEFAULT_PROFILE ? null : { [PROFILE_ENV_VAR]: profile })],
103
+ });
104
+ const codex = {
105
+ label: 'OpenAI Codex',
106
+ run: setupCodex,
107
+ addDemo: (databasePath) => ok({ warnings: [], lines: [codexSnippet(DEMO_SERVER_NAME, withDemo(STDIO_ENTRY, databasePath).env)] }),
108
+ removeDemo: () => ok({ warnings: [], lines: [` Codex CLI: remove the "${DEMO_SERVER_NAME}" entry from your MCP config file.`] }),
109
+ };
110
+ // ---------------------------------------------------------------------------
111
+ // Client registry
112
+ // ---------------------------------------------------------------------------
113
+ const claudeCode = fileClient({
114
+ label: 'Claude Code (CLI)',
115
+ path: () => join(home, '.claude', 'mcp.json'),
116
+ key: ServersKey.enum.mcpServers,
117
+ entry: STDIO_ENTRY,
118
+ next: ' Verify with: claude mcp list',
119
+ });
120
+ const claudeDesktop = fileClient({
121
+ label: 'Claude Desktop',
122
+ path: claudeDesktopConfigPath,
123
+ key: ServersKey.enum.mcpServers,
124
+ entry: STDIO_ENTRY,
125
+ next: ' Fully quit and reopen Claude Desktop to apply.',
126
+ });
127
+ const copilot = fileClient({
128
+ label: 'VS Code / GitHub Copilot',
129
+ path: () => join(process.cwd(), '.vscode', 'mcp.json'),
130
+ key: ServersKey.enum.servers,
131
+ entry: VSCODE_ENTRY,
132
+ next: ' Reload VS Code window (Cmd/Ctrl+Shift+P → "Developer: Reload Window") to apply.',
133
+ });
134
+ const antigravity = fileClient({
135
+ label: 'Google Antigravity',
136
+ path: () => join(home, '.gemini', 'config', 'mcp_config.json'),
137
+ key: ServersKey.enum.mcpServers,
138
+ entry: STDIO_ENTRY,
139
+ next: ' Reopen Antigravity or type /mcp in the CLI to refresh.',
140
+ });
141
+ const TOOLS = {
142
+ 'claude-code': claudeCode,
143
+ 'claude-desktop': claudeDesktop,
144
+ copilot,
145
+ vscode: copilot,
146
+ antigravity,
147
+ codex,
148
+ };
149
+ const findClient = (tool) => TOOLS[tool.trim().toLowerCase()];
150
+ export const clientConfigs = { find: findClient };
@@ -0,0 +1,41 @@
1
+ import { DEFAULT_PROFILE, PROFILE_ENV_VAR } from '../../models/auth/sign-in.js';
2
+ import { DEMO_ENV_ON, DEMO_ENV_VAR, DEMO_PORT } from '../../models/demo/core.js';
3
+ import { PACKAGE_SPEC } from '../../models/package.js';
4
+ import { ServersKey } from '../../wire/out/client-config.js';
5
+ // ---------------------------------------------------------------------------
6
+ // Shared MCP entry shapes
7
+ // ---------------------------------------------------------------------------
8
+ export const resolveConfigObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value) ? value : null;
9
+ export const STDIO_ENTRY = {
10
+ command: 'npx',
11
+ args: ['-y', PACKAGE_SPEC],
12
+ };
13
+ export const VSCODE_ENTRY = {
14
+ type: 'stdio',
15
+ command: 'npx',
16
+ args: ['-y', PACKAGE_SPEC],
17
+ };
18
+ /** A client config entry that signs in as `profile`: `PATTY_PROFILE` is added to its `env` only when the profile
19
+ * is not the default, so an ordinary install writes exactly the entry it always did (ADR-034 §5.2). */
20
+ export const withProfile = (entry, profile) => profile === DEFAULT_PROFILE ? entry : { ...entry, env: { [PROFILE_ENV_VAR]: profile } };
21
+ export const withDemo = (entry, databasePath) => ({
22
+ ...entry,
23
+ env: { DB_PATH: databasePath, PORT: String(DEMO_PORT), [DEMO_ENV_VAR]: DEMO_ENV_ON },
24
+ });
25
+ // ---------------------------------------------------------------------------
26
+ // Pure config merge helpers (testable without FS)
27
+ // ---------------------------------------------------------------------------
28
+ export const SERVER_NAME = 'patty';
29
+ const mergeServer = (key, existing, entry, name) => {
30
+ const servers = resolveConfigObject(existing[key]) ?? {};
31
+ return { ...existing, [key]: { ...servers, [name]: entry } };
32
+ };
33
+ export const mergeMcpServersKey = (existing, entry, name = SERVER_NAME) => mergeServer(ServersKey.enum.mcpServers, existing, entry, name);
34
+ export const mergeServersKey = (existing, entry, name = SERVER_NAME) => mergeServer(ServersKey.enum.servers, existing, entry, name);
35
+ export const withoutServer = (existing, key, name) => {
36
+ const servers = resolveConfigObject(existing[key]);
37
+ if (servers === null || !(name in servers))
38
+ return null;
39
+ const { [name]: _removed, ...rest } = servers;
40
+ return { ...existing, [key]: rest };
41
+ };
@@ -0,0 +1,98 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { migrate } from 'drizzle-orm/libsql/migrator';
4
+ import { ResultAsync } from 'neverthrow';
5
+ import * as R from 'remeda';
6
+ import { DashboardSource } from '../../models/dashboard.js';
7
+ import { ClassificationMethod } from '../../models/transaction.js';
8
+ import { normalizeMerchant } from '../../logic/merchant.js';
9
+ import { HTML_FILE_EXTENSION, listDefaultDashboardFiles } from './repos/dashboards.js';
10
+ import { categories, currencies, dashboards, merchantCategory, merchants } from './schema.js';
11
+ import { migrateWithSafetyCopy } from './safety-copy.js';
12
+ import { assertOwnedRowsHaveKnownUsers } from './tenancy-integrity.js';
13
+ import { checkDatabaseNotAhead } from './version-guard.js';
14
+ import { CURRENCIES } from './seed/currencies.js';
15
+ import { CATEGORIES } from './seed/categories.js';
16
+ import { DEFAULT_MERCHANT_RULES } from './seed/merchant-rules.js';
17
+ // Resolve the migrations folder relative to this module (../../../drizzle), so it
18
+ // works under both `tsx src/...` (dev) and `node dist/...` (prod/npx) regardless of cwd.
19
+ const DEFAULT_MIGRATIONS_FOLDER = fileURLToPath(new URL('../../../drizzle', import.meta.url));
20
+ // ---------------------------------------------------------------------------
21
+ // Seed helpers
22
+ // ---------------------------------------------------------------------------
23
+ /** Seeded-rule weight (≈ 0.8 confidence). Named so the value isn't a bare literal. */
24
+ const SEED_RULE_WEIGHT = 3;
25
+ const seedRules = () => R.pipe(DEFAULT_MERCHANT_RULES, R.map(({ key, category }) => ({ key: normalizeMerchant(key), categoryId: category })), R.filter(({ key }) => key.length > 0), R.uniqueBy(({ key, categoryId }) => `${key} ${categoryId}`));
26
+ const seedCurrencies = async (db) => {
27
+ await db
28
+ .insert(currencies)
29
+ .values([...CURRENCIES])
30
+ .onConflictDoNothing();
31
+ };
32
+ const seedCategories = async (db) => {
33
+ await db
34
+ .insert(categories)
35
+ .values([...CATEGORIES])
36
+ .onConflictDoNothing();
37
+ };
38
+ // Reconciles rows to the default dashboard files actually present under ui/dashboards/ (ADR-027
39
+ // Phase 2) — every *.html file there becomes a source: 'file' row, named after its own filename,
40
+ // on every boot; dropping a new default in that folder needs no code change here. Seeded once per
41
+ // name (onConflictDoNothing on the `name` UNIQUE constraint): a later save_dashboard upsert
42
+ // detaches that name into a custom, inline row and survives future boots — bootstrap never
43
+ // re-seeds over a dashboard that already exists, file-backed or not. The minted id is discarded on
44
+ // that conflict path, same as any other insert.
45
+ const seedDashboards = async (db) => {
46
+ const files = await listDefaultDashboardFiles();
47
+ if (files.length === 0)
48
+ return;
49
+ const now = new Date().toISOString();
50
+ await db
51
+ .insert(dashboards)
52
+ .values(files.map((filename) => ({
53
+ id: randomUUID(),
54
+ name: filename.slice(0, -HTML_FILE_EXTENSION.length),
55
+ html: null,
56
+ source: DashboardSource.enum.file,
57
+ path: filename,
58
+ updatedAt: now,
59
+ })))
60
+ .onConflictDoNothing();
61
+ };
62
+ const seedMerchantRules = async (db) => {
63
+ const currentYear = new Date().getFullYear();
64
+ const rules = seedRules();
65
+ const distinctKeys = [...new Set(rules.map(({ key }) => key))];
66
+ await db
67
+ .insert(merchants)
68
+ .values(distinctKeys.map((key) => ({ key })))
69
+ .onConflictDoNothing();
70
+ await db
71
+ .insert(merchantCategory)
72
+ .values(rules.map(({ key, categoryId }) => ({
73
+ merchantKey: key,
74
+ categoryId,
75
+ weight: SEED_RULE_WEIGHT,
76
+ origin: ClassificationMethod.enum.rule,
77
+ lastSeen: currentYear,
78
+ })))
79
+ .onConflictDoNothing();
80
+ };
81
+ // ---------------------------------------------------------------------------
82
+ // Bootstrap
83
+ // ---------------------------------------------------------------------------
84
+ /** Idempotent: refuses a database a newer build has migrated, then applies pending migrations (after a safety copy,
85
+ * if one rewrites existing data) and upserts seed data. Safe on every boot. The guard comes first — before the
86
+ * copy, the migrations and the seeding — so an older build writes nothing to a database it does not understand. */
87
+ export const bootstrap = (db, migrationsFolder = DEFAULT_MIGRATIONS_FOLDER) => checkDatabaseNotAhead(db, migrationsFolder)
88
+ .andThen(() => ResultAsync.fromSafePromise(migrateWithSafetyCopy(db, migrationsFolder, () => migrate(db, { migrationsFolder }), assertOwnedRowsHaveKnownUsers)))
89
+ // A newer build may have migrated between the first check and now (both starting at once): look again right before
90
+ // the first seed write, so an older build never seeds into a schema it does not know.
91
+ .andThen(() => checkDatabaseNotAhead(db, migrationsFolder))
92
+ .andThen(() => ResultAsync.fromSafePromise(seed(db)));
93
+ const seed = async (db) => {
94
+ await seedCurrencies(db);
95
+ await seedCategories(db);
96
+ await seedMerchantRules(db);
97
+ await seedDashboards(db);
98
+ };
@@ -0,0 +1,147 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { tmpdir } from 'node:os';
3
+ import { link, open } from 'node:fs/promises';
4
+ import { pipeline } from 'node:stream/promises';
5
+ import { copyFileSync, createReadStream, existsSync, lstatSync, mkdirSync, mkdtempSync, readlinkSync, rmdirSync, realpathSync, rmSync, } from 'node:fs';
6
+ import { basename, dirname, join, resolve } from 'node:path';
7
+ import { DEMO_DB_KEY, DemoProbeAbsence } from '../../models/demo/core.js';
8
+ import { DATA_BEARING_SUFFIXES, DATABASE_COMPANION_SUFFIXES, EXCLUSIVE_CREATE_FLAG, PRIVATE_DIRECTORY_MODE, PRIVATE_FILE_MODE, } from '../../models/export.js';
9
+ import { closeDatabase, openDatabaseWithKey } from './driver.js';
10
+ import { countSnapshotRows } from './export.js';
11
+ import { tryExclusiveLock } from './file-lock.js';
12
+ import { instanceRepo } from './repos/instance.js';
13
+ const DATABASE_FILE_SUFFIXES = ['', ...DATABASE_COMPANION_SUFFIXES];
14
+ export const databaseExists = (databasePath) => existsSync(databasePath);
15
+ export const removeDatabaseFiles = (databasePath) => DATABASE_FILE_SUFFIXES.forEach((suffix) => rmSync(`${databasePath}${suffix}`, { force: true }));
16
+ export const isSymlink = (path) => {
17
+ try {
18
+ return lstatSync(path).isSymbolicLink();
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ };
24
+ const realPathOfMissing = (path) => {
25
+ const absolute = resolve(path);
26
+ if (existsSync(absolute))
27
+ return realpathSync(absolute);
28
+ if (isSymlink(absolute))
29
+ return null;
30
+ const parent = dirname(absolute);
31
+ if (parent === absolute)
32
+ return absolute;
33
+ const resolvedParent = realPathOfMissing(parent);
34
+ return resolvedParent === null ? null : join(resolvedParent, basename(absolute));
35
+ };
36
+ /** Null when the path cannot be resolved (a link loop, a chain of dangling links). */
37
+ export const canonicalPath = (path) => {
38
+ if (existsSync(path))
39
+ return realpathSync(path);
40
+ if (!isSymlink(path))
41
+ return realPathOfMissing(path);
42
+ const target = resolve(dirname(path), readlinkSync(path));
43
+ if (existsSync(target))
44
+ return realpathSync(target);
45
+ return isSymlink(target) ? null : realPathOfMissing(target);
46
+ };
47
+ const MISSING = { probe: DemoProbeAbsence.enum.missing, holdsData: false };
48
+ const UNREADABLE = { probe: DemoProbeAbsence.enum.unreadable, holdsData: false };
49
+ /** Includes the hot rollback journal: without it, a crashed transaction's pages would read as committed. */
50
+ const PROBE_FILE_SUFFIXES = ['', '-wal', '-journal'];
51
+ /** libSQL has no read-only open and closing can checkpoint a log: probe a copy, never the original. */
52
+ const onCopyOf = async (databasePath, look) => {
53
+ const directory = mkdtempSync(join(tmpdir(), 'patty-probe-'));
54
+ const source = canonicalPath(databasePath) ?? databasePath;
55
+ try {
56
+ PROBE_FILE_SUFFIXES.forEach((suffix) => {
57
+ if (existsSync(`${source}${suffix}`)) {
58
+ copyFileSync(`${source}${suffix}`, join(directory, `probe.db${suffix}`));
59
+ }
60
+ });
61
+ return await look(join(directory, 'probe.db'));
62
+ }
63
+ finally {
64
+ rmSync(directory, { recursive: true, force: true });
65
+ }
66
+ };
67
+ export const countRowsOnCopy = (databasePath, key) => onCopyOf(databasePath, (copyPath) => countSnapshotRows(copyPath, key));
68
+ const lookAtOpenable = async (path) => {
69
+ const db = await openDatabaseWithKey({ DB_PATH: path }, DEMO_DB_KEY, { initializeJournal: false });
70
+ try {
71
+ const repo = instanceRepo(db);
72
+ return { probe: await repo.kind(), holdsData: await repo.hasUserData() };
73
+ }
74
+ finally {
75
+ closeDatabase(db);
76
+ }
77
+ };
78
+ export const probeDatabase = async (databasePath) => {
79
+ if (!existsSync(databasePath))
80
+ return MISSING;
81
+ try {
82
+ return await onCopyOf(databasePath, lookAtOpenable);
83
+ }
84
+ catch {
85
+ return UNREADABLE;
86
+ }
87
+ };
88
+ const IMPORT_STAGING_INFIX = '.import-';
89
+ const copyToStaging = async (from, staging) => {
90
+ const destination = await open(staging, EXCLUSIVE_CREATE_FLAG, PRIVATE_FILE_MODE);
91
+ await pipeline(createReadStream(from), destination.createWriteStream());
92
+ };
93
+ const removeEmptyDirectories = (leaf, top) => {
94
+ try {
95
+ rmdirSync(leaf);
96
+ }
97
+ catch {
98
+ return;
99
+ }
100
+ if (leaf !== top)
101
+ removeEmptyDirectories(dirname(leaf), top);
102
+ };
103
+ export const discardStaged = ({ path, createdDirectory }) => {
104
+ rmSync(path, { force: true });
105
+ if (createdDirectory !== null)
106
+ removeEmptyDirectories(dirname(path), createdDirectory);
107
+ };
108
+ export const stagePrivateCopy = async (from, to) => {
109
+ const createdDirectory = mkdirSync(dirname(to), { recursive: true, mode: PRIVATE_DIRECTORY_MODE }) ?? null;
110
+ const staged = { path: `${to}${IMPORT_STAGING_INFIX}${randomUUID()}`, source: from, createdDirectory };
111
+ try {
112
+ await copyToStaging(from, staged.path);
113
+ }
114
+ catch (cause) {
115
+ discardStaged(staged);
116
+ throw cause;
117
+ }
118
+ return staged;
119
+ };
120
+ // Hard link, not rename: link refuses an existing target.
121
+ export const publishStaged = async (staged, to) => {
122
+ try {
123
+ await link(staged.path, to);
124
+ }
125
+ catch (cause) {
126
+ discardStaged(staged);
127
+ throw cause;
128
+ }
129
+ rmSync(staged.path, { force: true });
130
+ };
131
+ const existsAsLink = (path) => {
132
+ try {
133
+ lstatSync(path);
134
+ return true;
135
+ }
136
+ catch {
137
+ return false;
138
+ }
139
+ };
140
+ export const hasDataBearingCompanion = (databasePath) => DATA_BEARING_SUFFIXES.some((suffix) => existsAsLink(`${databasePath}${suffix}`));
141
+ const LOCK_SUFFIX = '.lock';
142
+ /** Held by the OS, so a dead process releases it; the lock file is never deleted, or waiters would lock another. */
143
+ export const acquireDatabaseLock = (databasePath) => {
144
+ const lockPath = `${databasePath}${LOCK_SUFFIX}`;
145
+ mkdirSync(dirname(lockPath), { recursive: true, mode: PRIVATE_DIRECTORY_MODE });
146
+ return tryExclusiveLock(lockPath);
147
+ };