@selvajs/selva 4.20.1-beta.4 → 4.21.0-beta.10

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 (302) hide show
  1. package/build/adapter-node.js +1 -1
  2. package/build/client/_app/immutable/assets/0.CqqJCiiV.css +2 -0
  3. package/build/client/_app/immutable/assets/0.CqqJCiiV.css.br +0 -0
  4. package/build/client/_app/immutable/assets/0.CqqJCiiV.css.gz +0 -0
  5. package/build/client/_app/immutable/chunks/{CzfnuBzq.js → BAhtiTKe.js} +1 -1
  6. package/build/client/_app/immutable/chunks/BAhtiTKe.js.br +0 -0
  7. package/build/client/_app/immutable/chunks/BAhtiTKe.js.gz +0 -0
  8. package/build/client/_app/immutable/chunks/{qi43d-TM.js → CKbHmAlc.js} +1 -1
  9. package/build/client/_app/immutable/chunks/CKbHmAlc.js.br +0 -0
  10. package/build/client/_app/immutable/chunks/CKbHmAlc.js.gz +0 -0
  11. package/build/client/_app/immutable/chunks/{C6Y_BUwr.js → CmlXAF26.js} +1 -1
  12. package/build/client/_app/immutable/chunks/CmlXAF26.js.br +0 -0
  13. package/build/client/_app/immutable/chunks/CmlXAF26.js.gz +0 -0
  14. package/build/client/_app/immutable/chunks/Cv7GBWJh.js +2 -0
  15. package/build/client/_app/immutable/chunks/Cv7GBWJh.js.br +0 -0
  16. package/build/client/_app/immutable/chunks/Cv7GBWJh.js.gz +0 -0
  17. package/build/client/_app/immutable/chunks/{BDYCH-_Q.js → D5j4-ZO1.js} +1 -1
  18. package/build/client/_app/immutable/chunks/D5j4-ZO1.js.br +0 -0
  19. package/build/client/_app/immutable/chunks/D5j4-ZO1.js.gz +0 -0
  20. package/build/client/_app/immutable/chunks/DW5EJMC7.js +1 -0
  21. package/build/client/_app/immutable/chunks/DW5EJMC7.js.br +0 -0
  22. package/build/client/_app/immutable/chunks/DW5EJMC7.js.gz +0 -0
  23. package/build/client/_app/immutable/chunks/{D-uUm_OB.js → DptnDNFA.js} +61 -56
  24. package/build/client/_app/immutable/chunks/DptnDNFA.js.br +0 -0
  25. package/build/client/_app/immutable/chunks/{D-uUm_OB.js.gz → DptnDNFA.js.gz} +0 -0
  26. package/build/client/_app/immutable/chunks/DvJo0Zn0.js +1 -0
  27. package/build/client/_app/immutable/chunks/DvJo0Zn0.js.br +1 -0
  28. package/build/client/_app/immutable/chunks/DvJo0Zn0.js.gz +0 -0
  29. package/build/client/_app/immutable/chunks/{DzxE3j6C.js → qXnHMKD9.js} +1 -1
  30. package/build/client/_app/immutable/chunks/qXnHMKD9.js.br +0 -0
  31. package/build/client/_app/immutable/chunks/qXnHMKD9.js.gz +0 -0
  32. package/build/client/_app/immutable/entry/{app.BpT6WkO1.js → app.DPbjEDd3.js} +2 -2
  33. package/build/client/_app/immutable/entry/app.DPbjEDd3.js.br +0 -0
  34. package/build/client/_app/immutable/entry/app.DPbjEDd3.js.gz +0 -0
  35. package/build/client/_app/immutable/nodes/{1.D3kiiIk_.js → 1.DWd6YbcT.js} +1 -1
  36. package/build/client/_app/immutable/nodes/1.DWd6YbcT.js.br +0 -0
  37. package/build/client/_app/immutable/nodes/1.DWd6YbcT.js.gz +0 -0
  38. package/build/client/_app/immutable/nodes/15._hpTnSzc.js +36 -0
  39. package/build/client/_app/immutable/nodes/15._hpTnSzc.js.br +0 -0
  40. package/build/client/_app/immutable/nodes/15._hpTnSzc.js.gz +0 -0
  41. package/build/client/_app/immutable/nodes/{2.CUNbzjI_.js → 2.CS32Eh9m.js} +1 -1
  42. package/build/client/_app/immutable/nodes/2.CS32Eh9m.js.br +0 -0
  43. package/build/client/_app/immutable/nodes/2.CS32Eh9m.js.gz +0 -0
  44. package/build/client/_app/immutable/nodes/{20.9OIre0ah.js → 20.CVaxGEhZ.js} +1 -1
  45. package/build/client/_app/immutable/nodes/20.CVaxGEhZ.js.br +0 -0
  46. package/build/client/_app/immutable/nodes/20.CVaxGEhZ.js.gz +0 -0
  47. package/build/client/_app/immutable/nodes/21.DpKe0-GH.js +1 -0
  48. package/build/client/_app/immutable/nodes/21.DpKe0-GH.js.br +0 -0
  49. package/build/client/_app/immutable/nodes/21.DpKe0-GH.js.gz +0 -0
  50. package/build/client/_app/immutable/nodes/24.DkL5kHzA.js +3 -0
  51. package/build/client/_app/immutable/nodes/24.DkL5kHzA.js.br +0 -0
  52. package/build/client/_app/immutable/nodes/24.DkL5kHzA.js.gz +0 -0
  53. package/build/client/_app/immutable/nodes/{25.DW1_vMxq.js → 25.DiYmTwXC.js} +2 -2
  54. package/build/client/_app/immutable/nodes/25.DiYmTwXC.js.br +0 -0
  55. package/build/client/_app/immutable/nodes/25.DiYmTwXC.js.gz +0 -0
  56. package/build/client/_app/immutable/nodes/26.7nAJpm5P.js +5 -0
  57. package/build/client/_app/immutable/nodes/26.7nAJpm5P.js.br +0 -0
  58. package/build/client/_app/immutable/nodes/26.7nAJpm5P.js.gz +0 -0
  59. package/build/client/_app/immutable/nodes/{3.3Z4QUsQQ.js → 3.Ctd9OGCk.js} +1 -1
  60. package/build/client/_app/immutable/nodes/3.Ctd9OGCk.js.br +0 -0
  61. package/build/client/_app/immutable/nodes/3.Ctd9OGCk.js.gz +0 -0
  62. package/build/client/_app/immutable/nodes/{5.DmA9lTA-.js → 5.Wh_w3RkZ.js} +1 -1
  63. package/build/client/_app/immutable/nodes/5.Wh_w3RkZ.js.br +2 -0
  64. package/build/client/_app/immutable/nodes/5.Wh_w3RkZ.js.gz +0 -0
  65. package/build/client/_app/immutable/nodes/{6.D6WLqCgl.js → 6.C-DiUI5R.js} +1 -1
  66. package/build/client/_app/immutable/nodes/6.C-DiUI5R.js.br +0 -0
  67. package/build/client/_app/immutable/nodes/6.C-DiUI5R.js.gz +0 -0
  68. package/build/client/_app/immutable/nodes/{7.CNuRjkv2.js → 7.B8yubYrv.js} +1 -1
  69. package/build/client/_app/immutable/nodes/7.B8yubYrv.js.br +0 -0
  70. package/build/client/_app/immutable/nodes/7.B8yubYrv.js.gz +0 -0
  71. package/build/client/_app/version.json +1 -1
  72. package/build/client/_app/version.json.br +0 -0
  73. package/build/client/_app/version.json.gz +0 -0
  74. package/build/runtime-meta.json +1 -1
  75. package/build/server/.vite/manifest.json +35 -45
  76. package/build/server/_app/immutable/assets/_layout.CqqJCiiV.css +2 -0
  77. package/build/server/chunks/DefinitionCard.js +3 -0
  78. package/build/server/chunks/DefinitionCard.js.map +1 -1
  79. package/build/server/chunks/access.js +15 -3
  80. package/build/server/chunks/access.js.map +1 -1
  81. package/build/server/chunks/api-errors.js +18 -3
  82. package/build/server/chunks/api-errors.js.map +1 -1
  83. package/build/server/chunks/api.js +9 -2
  84. package/build/server/chunks/api.js.map +1 -1
  85. package/build/server/chunks/auth-bootstrap.server.js +63 -39
  86. package/build/server/chunks/auth-bootstrap.server.js.map +1 -1
  87. package/build/server/chunks/boot.server.js +1 -1
  88. package/build/server/chunks/bootHealth.server.js +23 -23
  89. package/build/server/chunks/bootHealth.server.js.map +1 -1
  90. package/build/server/chunks/computeRateLimit.server.js +2 -2
  91. package/build/server/chunks/delete-with-blobs.js +1 -1
  92. package/build/server/chunks/engine.server.js +52 -5
  93. package/build/server/chunks/engine.server.js.map +1 -1
  94. package/build/server/chunks/grasshopper.js +217 -162
  95. package/build/server/chunks/grasshopper.js.map +1 -1
  96. package/build/server/chunks/handlers.js +70 -60
  97. package/build/server/chunks/handlers.js.map +1 -1
  98. package/build/server/chunks/http.js +24 -24
  99. package/build/server/chunks/http.js.map +1 -1
  100. package/build/server/chunks/http2.js +1 -1
  101. package/build/server/chunks/instance.js +3 -3
  102. package/build/server/chunks/instanceAdmins.server.js +31 -16
  103. package/build/server/chunks/instanceAdmins.server.js.map +1 -1
  104. package/build/server/chunks/internal.js +1 -1
  105. package/build/server/chunks/{abort-Bfrdupaj.js → keepalive-vtcjhAV3.js} +6 -3
  106. package/build/server/chunks/keepalive-vtcjhAV3.js.map +1 -0
  107. package/build/server/chunks/liveSolve.server.js +1 -1
  108. package/build/server/chunks/localeContext.svelte.js +14 -0
  109. package/build/server/chunks/localeContext.svelte.js.map +1 -1
  110. package/build/server/chunks/oauth.js +70 -24
  111. package/build/server/chunks/oauth.js.map +1 -1
  112. package/build/server/chunks/{outcome-DNrffAXp.js → outcome-D28FgvFK.js} +9 -6
  113. package/build/server/chunks/outcome-D28FgvFK.js.map +1 -0
  114. package/build/server/chunks/package.js +2 -1
  115. package/build/server/chunks/package.js.map +1 -1
  116. package/build/server/chunks/permissions.server.js +1 -1
  117. package/build/server/chunks/presets.server.js +1 -1
  118. package/build/server/chunks/providers.server.js +324 -121
  119. package/build/server/chunks/providers.server.js.map +1 -1
  120. package/build/server/chunks/registry.js +1 -1
  121. package/build/server/chunks/resolve-server.js +1 -1
  122. package/build/server/chunks/schema-extraction.js +75 -8
  123. package/build/server/chunks/schema-extraction.js.map +1 -1
  124. package/build/server/chunks/schema.js +1 -1
  125. package/build/server/chunks/schema.js.map +1 -1
  126. package/build/server/chunks/server-config-write.js +6 -6
  127. package/build/server/chunks/server-config-write.js.map +1 -1
  128. package/build/server/chunks/server2.js +2 -2
  129. package/build/server/chunks/server2.js.map +1 -1
  130. package/build/server/chunks/serverStats.server.js +1 -1
  131. package/build/server/chunks/signInMaxAge.server.js +1 -1
  132. package/build/server/chunks/solve.server.js +34 -8
  133. package/build/server/chunks/solve.server.js.map +1 -1
  134. package/build/server/chunks/sveltekit.js +4 -5
  135. package/build/server/chunks/sveltekit.js.map +1 -1
  136. package/build/server/chunks/update-outcome.js +11 -0
  137. package/build/server/chunks/update-outcome.js.map +1 -1
  138. package/build/server/chunks/updateCheck.server.js +24 -12
  139. package/build/server/chunks/updateCheck.server.js.map +1 -1
  140. package/build/server/entries/endpoints/.well-known/oauth-authorization-server/_server.ts.js +6 -3
  141. package/build/server/entries/endpoints/.well-known/oauth-authorization-server/_server.ts.js.map +1 -1
  142. package/build/server/entries/endpoints/.well-known/oauth-protected-resource/_server.ts.js +6 -3
  143. package/build/server/entries/endpoints/.well-known/oauth-protected-resource/_server.ts.js.map +1 -1
  144. package/build/server/entries/endpoints/.well-known/oauth-protected-resource/mcp/_server.ts.js +6 -3
  145. package/build/server/entries/endpoints/.well-known/oauth-protected-resource/mcp/_server.ts.js.map +1 -1
  146. package/build/server/entries/endpoints/api/admin/compute/_server.ts.js +1 -1
  147. package/build/server/entries/endpoints/api/admin/compute/actions/_server.ts.js +1 -1
  148. package/build/server/entries/endpoints/api/admin/compute/status/_server.ts.js +1 -1
  149. package/build/server/entries/endpoints/api/admin/orgs/_id_/_server.ts.js +1 -1
  150. package/build/server/entries/endpoints/api/admin/orgs/_server.ts.js +1 -1
  151. package/build/server/entries/endpoints/api/admin/projects/_id_/_server.ts.js +1 -1
  152. package/build/server/entries/endpoints/api/admin/projects/_id_/grants/_grantId_/_server.ts.js +1 -1
  153. package/build/server/entries/endpoints/api/admin/projects/_id_/grants/_server.ts.js +1 -1
  154. package/build/server/entries/endpoints/api/admin/projects/_server.ts.js +1 -1
  155. package/build/server/entries/endpoints/api/admin/system/health/_server.ts.js +9 -2
  156. package/build/server/entries/endpoints/api/admin/system/health/_server.ts.js.map +1 -1
  157. package/build/server/entries/endpoints/api/admin/system/update/_server.ts.js +59 -15
  158. package/build/server/entries/endpoints/api/admin/system/update/_server.ts.js.map +1 -1
  159. package/build/server/entries/endpoints/api/admin/users/_id_/_server.ts.js +42 -16
  160. package/build/server/entries/endpoints/api/admin/users/_id_/_server.ts.js.map +1 -1
  161. package/build/server/entries/endpoints/api/admin/users/_id_/disable/_server.ts.js +24 -13
  162. package/build/server/entries/endpoints/api/admin/users/_id_/disable/_server.ts.js.map +1 -1
  163. package/build/server/entries/endpoints/api/admin/users/_server.ts.js +2 -2
  164. package/build/server/entries/endpoints/api/files/_...path_/_server.ts.js +1 -1
  165. package/build/server/entries/endpoints/api/v1/compute/_server.ts.js +15 -6
  166. package/build/server/entries/endpoints/api/v1/compute/_server.ts.js.map +1 -1
  167. package/build/server/entries/endpoints/api/v1/compute/schema/_server.ts.js +3 -3
  168. package/build/server/entries/endpoints/api/v1/definitions/_guid_/_server.ts.js +1 -1
  169. package/build/server/entries/endpoints/api/v1/definitions/_guid_/image/_server.ts.js +1 -1
  170. package/build/server/entries/endpoints/api/v1/definitions/_guid_/publish/_server.ts.js +1 -1
  171. package/build/server/entries/endpoints/api/v1/definitions/_guid_/schema/_server.ts.js +1 -1
  172. package/build/server/entries/endpoints/api/v1/definitions/_guid_/share-links/_linkId_/_server.ts.js +1 -1
  173. package/build/server/entries/endpoints/api/v1/definitions/_guid_/share-links/_server.ts.js +1 -1
  174. package/build/server/entries/endpoints/api/v1/definitions/_guid_/solve/_server.ts.js +5 -4
  175. package/build/server/entries/endpoints/api/v1/definitions/_guid_/solve/_server.ts.js.map +1 -1
  176. package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_server.ts.js +1 -1
  177. package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_versionId_/_server.ts.js +1 -1
  178. package/build/server/entries/endpoints/api/v1/definitions/_guid_/versions/_versionId_/schema/_server.ts.js +1 -1
  179. package/build/server/entries/endpoints/api/v1/me/_server.ts.js +1 -1
  180. package/build/server/entries/endpoints/api/v1/me/starred/_guid_/_server.ts.js +1 -1
  181. package/build/server/entries/endpoints/api/v1/me/token/_server.ts.js +1 -1
  182. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/_server.ts.js +1 -1
  183. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/members/_server.ts.js +1 -1
  184. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/tokens/_server.ts.js +1 -1
  185. package/build/server/entries/endpoints/api/v1/orgs/_orgId_/tokens/_tokenId_/_server.ts.js +1 -1
  186. package/build/server/entries/endpoints/api/v1/projects/_id_/_server.ts.js +1 -1
  187. package/build/server/entries/endpoints/api/v1/projects/_id_/members/_server.ts.js +1 -1
  188. package/build/server/entries/endpoints/api/v1/projects/_id_/members/_userId_/_server.ts.js +1 -1
  189. package/build/server/entries/endpoints/api/v1/projects/_id_/reclaim/_server.ts.js +1 -1
  190. package/build/server/entries/endpoints/api/v1/solve/_solveId_/cancel/_server.ts.js +1 -1
  191. package/build/server/entries/endpoints/api/v1/solve-events/_server.ts.js +1 -1
  192. package/build/server/entries/endpoints/auth/email/callback/_server.ts.js +2 -2
  193. package/build/server/entries/endpoints/auth/email/callback/_server.ts.js.map +1 -1
  194. package/build/server/entries/endpoints/auth/supabase/callback/_server.ts.js +2 -2
  195. package/build/server/entries/endpoints/auth/supabase/callback/_server.ts.js.map +1 -1
  196. package/build/server/entries/endpoints/docs/api/openapi.yaml/_server.ts.js +1 -1
  197. package/build/server/entries/endpoints/mcp/_server.ts.js +43 -13
  198. package/build/server/entries/endpoints/mcp/_server.ts.js.map +1 -1
  199. package/build/server/entries/endpoints/oauth/register/_server.ts.js +1 -1
  200. package/build/server/entries/endpoints/oauth/token/_server.ts.js +1 -1
  201. package/build/server/entries/hooks.server.js +25 -6
  202. package/build/server/entries/hooks.server.js.map +1 -1
  203. package/build/server/entries/pages/admin/compute/_page.server.ts.js +1 -2
  204. package/build/server/entries/pages/admin/compute/_page.server.ts.js.map +1 -1
  205. package/build/server/entries/pages/admin/system/_page.server.ts.js +8 -3
  206. package/build/server/entries/pages/admin/system/_page.server.ts.js.map +1 -1
  207. package/build/server/entries/pages/admin/system/_page.svelte.js +18 -2
  208. package/build/server/entries/pages/admin/system/_page.svelte.js.map +1 -1
  209. package/build/server/entries/pages/library/_guid_/_page.server.ts.js +198 -99
  210. package/build/server/entries/pages/library/_guid_/_page.server.ts.js.map +1 -1
  211. package/build/server/entries/pages/library/_guid_/_page.svelte.js +693 -40
  212. package/build/server/entries/pages/library/_guid_/_page.svelte.js.map +1 -1
  213. package/build/server/entries/pages/oauth/authorize/_page.server.ts.js +3 -2
  214. package/build/server/entries/pages/oauth/authorize/_page.server.ts.js.map +1 -1
  215. package/build/server/entries/pages/oauth/authorize/_page.svelte.js +8 -1
  216. package/build/server/entries/pages/oauth/authorize/_page.svelte.js.map +1 -1
  217. package/build/server/entries/pages/projects/_page.svelte.js +2 -0
  218. package/build/server/entries/pages/projects/_page.svelte.js.map +1 -1
  219. package/build/server/entries/pages/setup/_page.server.ts.js +62 -8
  220. package/build/server/entries/pages/setup/_page.server.ts.js.map +1 -1
  221. package/build/server/entries/pages/setup/_page.svelte.js +52 -33
  222. package/build/server/entries/pages/setup/_page.svelte.js.map +1 -1
  223. package/build/server/entries/pages/team/tokens/_page.server.ts.js +1 -1
  224. package/build/server/manifest-full.js +1 -1
  225. package/build/server/manifest.js +1 -1
  226. package/build/server/nodes/0.js +2 -2
  227. package/build/server/nodes/1.js +1 -1
  228. package/build/server/nodes/15.js +1 -1
  229. package/build/server/nodes/2.js +1 -1
  230. package/build/server/nodes/20.js +1 -1
  231. package/build/server/nodes/21.js +1 -1
  232. package/build/server/nodes/24.js +1 -1
  233. package/build/server/nodes/25.js +1 -1
  234. package/build/server/nodes/26.js +1 -1
  235. package/build/server/nodes/3.js +1 -1
  236. package/build/server/nodes/5.js +1 -1
  237. package/build/server/nodes/6.js +1 -1
  238. package/build/server/nodes/7.js +1 -1
  239. package/build/server/server.js +1 -1
  240. package/package.json +16 -13
  241. package/templates/.env.example +15 -7
  242. package/build/client/_app/immutable/assets/0.2jDm0bqh.css +0 -2
  243. package/build/client/_app/immutable/assets/0.2jDm0bqh.css.br +0 -0
  244. package/build/client/_app/immutable/assets/0.2jDm0bqh.css.gz +0 -0
  245. package/build/client/_app/immutable/chunks/BDYCH-_Q.js.br +0 -0
  246. package/build/client/_app/immutable/chunks/BDYCH-_Q.js.gz +0 -0
  247. package/build/client/_app/immutable/chunks/C6Y_BUwr.js.br +0 -0
  248. package/build/client/_app/immutable/chunks/C6Y_BUwr.js.gz +0 -0
  249. package/build/client/_app/immutable/chunks/CzfnuBzq.js.br +0 -0
  250. package/build/client/_app/immutable/chunks/CzfnuBzq.js.gz +0 -0
  251. package/build/client/_app/immutable/chunks/D-uUm_OB.js.br +0 -0
  252. package/build/client/_app/immutable/chunks/D84F7w9g.js +0 -1
  253. package/build/client/_app/immutable/chunks/D84F7w9g.js.br +0 -1
  254. package/build/client/_app/immutable/chunks/D84F7w9g.js.gz +0 -0
  255. package/build/client/_app/immutable/chunks/DQsP4nZb.js +0 -1
  256. package/build/client/_app/immutable/chunks/DQsP4nZb.js.br +0 -0
  257. package/build/client/_app/immutable/chunks/DQsP4nZb.js.gz +0 -0
  258. package/build/client/_app/immutable/chunks/DzeQucGI.js +0 -2
  259. package/build/client/_app/immutable/chunks/DzeQucGI.js.br +0 -0
  260. package/build/client/_app/immutable/chunks/DzeQucGI.js.gz +0 -0
  261. package/build/client/_app/immutable/chunks/DzxE3j6C.js.br +0 -0
  262. package/build/client/_app/immutable/chunks/DzxE3j6C.js.gz +0 -0
  263. package/build/client/_app/immutable/chunks/qi43d-TM.js.br +0 -0
  264. package/build/client/_app/immutable/chunks/qi43d-TM.js.gz +0 -0
  265. package/build/client/_app/immutable/entry/app.BpT6WkO1.js.br +0 -0
  266. package/build/client/_app/immutable/entry/app.BpT6WkO1.js.gz +0 -0
  267. package/build/client/_app/immutable/nodes/1.D3kiiIk_.js.br +0 -0
  268. package/build/client/_app/immutable/nodes/1.D3kiiIk_.js.gz +0 -0
  269. package/build/client/_app/immutable/nodes/15.BXIV1QfS.js +0 -32
  270. package/build/client/_app/immutable/nodes/15.BXIV1QfS.js.br +0 -0
  271. package/build/client/_app/immutable/nodes/15.BXIV1QfS.js.gz +0 -0
  272. package/build/client/_app/immutable/nodes/2.CUNbzjI_.js.br +0 -0
  273. package/build/client/_app/immutable/nodes/2.CUNbzjI_.js.gz +0 -0
  274. package/build/client/_app/immutable/nodes/20.9OIre0ah.js.br +0 -0
  275. package/build/client/_app/immutable/nodes/20.9OIre0ah.js.gz +0 -0
  276. package/build/client/_app/immutable/nodes/21.BkNlRItr.js +0 -1
  277. package/build/client/_app/immutable/nodes/21.BkNlRItr.js.br +0 -0
  278. package/build/client/_app/immutable/nodes/21.BkNlRItr.js.gz +0 -0
  279. package/build/client/_app/immutable/nodes/24.CPSunfJJ.js +0 -3
  280. package/build/client/_app/immutable/nodes/24.CPSunfJJ.js.br +0 -0
  281. package/build/client/_app/immutable/nodes/24.CPSunfJJ.js.gz +0 -0
  282. package/build/client/_app/immutable/nodes/25.DW1_vMxq.js.br +0 -0
  283. package/build/client/_app/immutable/nodes/25.DW1_vMxq.js.gz +0 -0
  284. package/build/client/_app/immutable/nodes/26.CqaMEm_t.js +0 -6
  285. package/build/client/_app/immutable/nodes/26.CqaMEm_t.js.br +0 -0
  286. package/build/client/_app/immutable/nodes/26.CqaMEm_t.js.gz +0 -0
  287. package/build/client/_app/immutable/nodes/3.3Z4QUsQQ.js.br +0 -0
  288. package/build/client/_app/immutable/nodes/3.3Z4QUsQQ.js.gz +0 -0
  289. package/build/client/_app/immutable/nodes/5.DmA9lTA-.js.br +0 -1
  290. package/build/client/_app/immutable/nodes/5.DmA9lTA-.js.gz +0 -0
  291. package/build/client/_app/immutable/nodes/6.D6WLqCgl.js.br +0 -0
  292. package/build/client/_app/immutable/nodes/6.D6WLqCgl.js.gz +0 -0
  293. package/build/client/_app/immutable/nodes/7.CNuRjkv2.js.br +0 -0
  294. package/build/client/_app/immutable/nodes/7.CNuRjkv2.js.gz +0 -0
  295. package/build/server/_app/immutable/assets/_layout.2jDm0bqh.css +0 -2
  296. package/build/server/chunks/abort-Bfrdupaj.js.map +0 -1
  297. package/build/server/chunks/computeLimits.js +0 -33
  298. package/build/server/chunks/computeLimits.js.map +0 -1
  299. package/build/server/chunks/outcome-DNrffAXp.js.map +0 -1
  300. /package/build/client/_app/immutable/nodes/{0.CYdyv5To.js → 0.Ds0zeDAg.js} +0 -0
  301. /package/build/client/_app/immutable/nodes/{0.CYdyv5To.js.br → 0.Ds0zeDAg.js.br} +0 -0
  302. /package/build/client/_app/immutable/nodes/{0.CYdyv5To.js.gz → 0.Ds0zeDAg.js.gz} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"_server.ts.js","names":["join","readFileSync"],"sources":["../../../../../../../../src/lib/server/updateRunner.server.ts","../../../../../../../../src/routes/api/admin/system/update/+server.ts"],"sourcesContent":["/**\n * Generates the bash the self-update POST route spawns: a tiny daemonizing\n * launcher plus the runner script that actually stops/updates/starts/health-\n * checks the deployment. Split out of the route file because SvelteKit's\n * route-file validator only allows HTTP-verb exports (and `_`-prefixed ones) —\n * these are plain functions the runner-script contract tests import directly.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { findDeploymentDir } from './selfUpdate.server.js';\nimport { channelTag, type ReleaseChannel } from './releaseChannel.server.js';\n\nexport function readRuntimeVersion(dir: string): string | undefined {\n\ttry {\n\t\tconst pkg = JSON.parse(\n\t\t\treadFileSync(join(dir, 'node_modules', '@selvajs', 'selva', 'package.json'), 'utf8')\n\t\t);\n\t\treturn typeof pkg.version === 'string' ? pkg.version : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n// No caller currently passes untrusted input (plan.cwd is from\n// process.cwd(), npm package names are hardcoded), but defensive quoting is\n// cheap.\nexport function shellQuote(s: string): string {\n\treturn `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\n// Wraps the actual update commands in a tiny \"launcher\" that daemonizes them.\n//\n// THE PROBLEM: `pm2 stop selva-compute` (which the runner has to call) uses\n// tree-kill, which walks /proc parent-child relationships from\n// selva-compute's PID and SIGKILLs every descendant. Node's\n// `{ detached: true }` + `child.unref()` puts the spawned bash in a new\n// session/process group but does NOT change the parent-child relationship —\n// so tree-kill still finds and kills it, and the app never restarts.\n//\n// THE FIX: write the update commands to a tempfile and launch them via\n// `setsid bash ... &`, then have the launcher exit. The runner's PPID becomes\n// 1 (init) the moment the launcher exits, so it's no longer a descendant of\n// selva-compute and tree-kill can't reach it.\n//\n// Output: the launcher's prelude lines are echoed via tee into\n// UPDATE_LOG_PATH and through stdout (visible to SSE while the connection is\n// still up); the runner appends its output to the same log file; the\n// frontend tolerates the SSE blackout by polling the log file.\nexport function buildLauncher(\n\trunnerScript: string,\n\tlogPath: string,\n\tprelude: string[] = []\n): string {\n\tconst echoes = prelude.map((line) => `echo ${shellQuote(line)}`).join('\\n');\n\t// Note: runner script is embedded via a QUOTED heredoc so no variable\n\t// expansion happens — the runner text is written verbatim.\n\treturn `\nLOGFILE=${shellQuote(logPath)}\nRUNNER=/tmp/selva-update-runner.sh\nmkdir -p \"$(dirname \"$LOGFILE\")\"\n: > \"$LOGFILE\"\n\ncat > \"$RUNNER\" <<'__SELVA_RUNNER_EOF__'\n${runnerScript}\n__SELVA_RUNNER_EOF__\nchmod +x \"$RUNNER\"\n\ntrap '' PIPE\nexec > >(tee --output-error=warn-nopipe -a \"$LOGFILE\" 2>/dev/null) 2>&1\n${echoes}\n\n# Daemonize the runner so PM2's tree-kill of selva-compute can't reach it.\n# setsid puts it in a new session; the trailing & + disown + launcher exit\n# leaves the runner with PPID=1 once we're gone. stdin/stdout/stderr are\n# fully detached from this process (and from selva-compute's pipes).\nsetsid bash \"$RUNNER\" </dev/null >>\"$LOGFILE\" 2>&1 &\nRUNNER_PID=$!\ndisown\necho \"[INFO] Update runner started (PID $RUNNER_PID, log: $LOGFILE)\"\n\n# Small pause so the runner has time to print its first line before SSE\n# closes — otherwise the frontend's first poll might see no progress.\nsleep 1\nexit 0\n`;\n}\n\n// Bash script the daemonized runner executes. Flow:\n//\n// 1. pre-flight — query the registry; if already on latest, exit clean\n// WITHOUT touching the running app.\n// 2. pm2 sync — `pm2 update` if the daemon and CLI versions drifted.\n// 3. pm2 stop — stop selva-compute before npm overwrites build/, so\n// in-flight requests can't hit ERR_MODULE_NOT_FOUND\n// from chunk-hash churn under their feet.\n// 4. npm update — refresh @selvajs/* (--prefer-online bypasses the\n// packument cache, already baked into npmArgs).\n// 5. pm2 start — from ecosystem.config.cjs (not `pm2 start name`,\n// which requires the process to already be in pm2's\n// in-memory list — fragile after `pm2 update`).\n// 6. health probe — poll /api/health for up to 30s.\n// 7. rollback — on failure: npm install the prior version, restart.\n// 8. EXIT trap — last-resort: if anything above leaves the app\n// offline (crash, kill, network blip), unconditionally\n// try `pm2 start ecosystem.config.cjs` before exiting\n// so the customer's site doesn't stay dark.\n//\n// Embedded into the launcher via a quoted heredoc, so this whole string is\n// written verbatim — interpolated values must be shell-quoted at JS time.\nexport function buildNpmRunnerScript(\n\tnpmArgs: string[],\n\tversionBefore: string | undefined,\n\tecosystemPath: string,\n\ttag: string\n): string {\n\tconst npmCommand = ['npm', ...npmArgs].map(shellQuote).join(' ');\n\t// Empty string when versionBefore is undefined — bash sees `BEFORE=\"\"`\n\t// and skips the rollback path (you can't roll back to nothing).\n\tconst before = shellQuote(versionBefore ?? '');\n\tconst ecosystem = shellQuote(ecosystemPath);\n\t// The npm dist-tag the chosen channel resolves to (`latest` / `beta`). The\n\t// pre-flight and no-change warning query this tag, so they don't misfire on\n\t// a beta channel (where the channel's published version is a pre-release the\n\t// default `latest` query would never see) or on a revert (where the target\n\t// stable version is OLDER than the installed beta).\n\tconst distTag = shellQuote(tag);\n\n\treturn `#!/bin/bash\nset -o pipefail\nBEFORE=${before}\nECOSYSTEM=${ecosystem}\nTAG=${distTag}\n\n# Resolve the deployment-local pm2 explicitly instead of trusting PATH.\n# The runner is re-launched via \\`setsid bash\\` from a tempfile, so it inherits\n# whatever environment the spawning process had. When the update is triggered\n# from the admin UI that happens to include node_modules/.bin; from cron or a\n# bare shell it does not, and every pm2 call below — including the EXIT trap's\n# last-resort restart — fails with \"command not found\" and the app stays dark.\nPM2=\"$(dirname \"$ECOSYSTEM\")/node_modules/.bin/pm2\"\n[ -x \"$PM2\" ] || PM2=pm2\n\n# Under systemd, \\`pm2 update\\` kills and respawns the daemon. systemd sees its\n# unit's main process die and, with the default KillMode=control-group,\n# SIGTERMs everything in the cgroup — including this runner. setsid escapes\n# PM2's tree-kill but NOT the cgroup, so the runner never runs \\`pm2 update\\`\n# when this is true.\npm2_under_systemd() {\n grep -qs 'pm2.*\\\\.service' /proc/self/cgroup 2>/dev/null\n}\n\n# Waits for selva-compute to leave the transitional 'stopping' state.\n#\n# \\`pm2 stop\\` sends SIGINT and returns without waiting for the process to die.\n# The SvelteKit node adapter then drains in-flight requests before exiting, and\n# PM2 only escalates to SIGKILL after kill_timeout (10s in the scaffolded\n# ecosystem). For that whole window the process table entry has a name and an\n# id but no live pid — \\`pm2 start\\` resolves the name, converts to a restart,\n# finds nothing to restart, and pm2's own table printer crashes on\n# \\`undefined.pm2_env\\`. Polling here keeps the rest of the script out of that\n# window entirely.\n#\n# The drain reliably takes the full timeout when the update was triggered from\n# the admin UI: that page is fed by an SSE stream this very process serves, and\n# an open SSE stream never completes on its own.\n# Prints exactly one word. Callers compare it against 'online' / 'stopping', so\n# a probe that emits two tokens on failure (the inline catch AND a shell\n# fallback both firing) would silently never match either. Node's catch is the\n# single failure path; fd 0 rather than /dev/stdin because the latter isn't a\n# readable pipe everywhere.\napp_status() {\n \"$PM2\" jlist 2>/dev/null | node -e \"\n try {\n const list = JSON.parse(require('fs').readFileSync(0,'utf8'));\n const app = list.find(p => p.name === 'selva-compute');\n process.stdout.write(app ? app.pm2_env.status : 'missing');\n } catch { process.stdout.write('error'); }\n \" 2>/dev/null\n}\n\nwait_until_stopped() {\n for i in $(seq 1 20); do\n STATUS=$(app_status)\n if [ \"$STATUS\" != \"stopping\" ]; then\n return 0\n fi\n echo \"[INFO] selva-compute still draining (attempt $i/20) — waiting for SIGKILL escalation\"\n sleep 1\n done\n echo \"[WARN] selva-compute stuck in 'stopping' after 20s — continuing anyway\"\n return 1\n}\n\n# \\`pm2 start <ecosystem>\\` converts to a restart-by-id when an entry of the same\n# name is already in the table. If that entry is stale the restart fails and no\n# amount of retrying the same command helps — the name has to be dropped first\n# so the start registers a fresh process. Deleting a stopped entry is safe: the\n# ecosystem file is the source of truth for how to bring it back.\nstart_app() {\n if \"$PM2\" start \"$ECOSYSTEM\" --update-env; then\n return 0\n fi\n echo \"[WARN] pm2 start failed — dropping the stale process entry and retrying\"\n \"$PM2\" delete selva-compute >/dev/null 2>&1 || true\n \"$PM2\" start \"$ECOSYSTEM\" --update-env\n}\n\n# Last-resort safety net. If the script exits with the app NOT online for\n# any reason (crash, kill -9, network blip, npm hang past timeout), try to\n# bring it back from ecosystem.config.cjs before exiting. Leaving the app\n# down is the worst possible outcome of an update.\non_exit() {\n CODE=$?\n STATUS=$(app_status)\n # A 'stopping' entry is mid-drain, not down. Restarting it now hits the same\n # dead-id window that brought us here; wait for the entry to settle first.\n if [ \"$STATUS\" = \"stopping\" ]; then\n wait_until_stopped\n STATUS=$(app_status)\n fi\n if [ \"$STATUS\" != \"online\" ]; then\n echo \"[RECOVER] selva-compute is '$STATUS' — starting from ecosystem.config.cjs\"\n start_app >/dev/null 2>&1 || \\\\\n echo \"[RECOVER] pm2 start failed — manual intervention required: cd $(dirname \"$ECOSYSTEM\") && ./node_modules/.bin/pm2 delete selva-compute; ./node_modules/.bin/pm2 start ecosystem.config.cjs\"\n fi\n # Terminal marker: the restarted app's outcome reconciler greps this to turn\n # the run into an audit event (selfUpdate.server.ts). Keep the format stable.\n echo \"[EXIT] code=$CODE\"\n}\ntrap on_exit EXIT\n\n# A killed runner must not look like a finished one.\n#\n# \\`$?\\` inside an EXIT trap reports the last completed command, NOT the signal.\n# When systemd SIGTERMs the whole cgroup, the EXIT trap still runs and records\n# \\`code=0\\` — so deriveOutcome takes the exit-0 success branch and tells the\n# operator \"Updated X → Y. The app is back online.\" while npm never ran and\n# the deployment is unchanged. Catching the signal makes the recorded code\n# truthful; 143/130 are the conventional 128+signal values.\non_signal() {\n SIG=$1\n echo \"[FATAL] KILLED: runner received SIG$SIG before finishing.\"\n echo \"[FATAL] Nothing was installed by this run. If the app is down, recover with:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\") && pm2 start ecosystem.config.cjs --update-env\"\n echo \"[FATAL] A systemd-supervised pm2 can do this when 'pm2 update' recycles the daemon.\"\n exit $2\n}\ntrap 'on_signal TERM 143' TERM\ntrap 'on_signal INT 130' INT\ntrap 'on_signal HUP 129' HUP\n\n# ---------------------------------------------------------------------------\n# 1. Pre-flight: skip the whole cycle if there's nothing to install.\n# ---------------------------------------------------------------------------\n# Without this, clicking \"Update\" on an already-current instance triggers a\n# full stop/install/start cycle and a downtime window for no reason.\necho \"[STEP] Checking npm registry for the '$TAG' channel version\"\nLATEST=$(npm view \"@selvajs/selva@$TAG\" version --silent 2>/dev/null || echo \"\")\nif [ -z \"$LATEST\" ]; then\n echo \"[WARN] Could not query npm registry — proceeding with update attempt anyway\"\nelif [ -n \"$BEFORE\" ] && [ \"$LATEST\" = \"$BEFORE\" ]; then\n echo \"[INFO] Already on the '$TAG' channel version ($BEFORE)\"\n echo \"[DONE] Nothing to do\"\n exit 0\nelse\n # May be a forward update OR a revert (target older than installed) — either\n # way the installed version differs from what this channel publishes.\n echo \"[INFO] Target ($TAG): $BEFORE → $LATEST\"\nfi\n\n# ---------------------------------------------------------------------------\n# 1b. Node engine pre-flight — BEFORE any downtime.\n# ---------------------------------------------------------------------------\n# npm only treats an engine mismatch as fatal under engine-strict=true, which\n# no deployment sets. So a release requiring a newer Node installs\n# \"successfully\", pm2 starts, and /api/health returns 200 (it touches nothing\n# Node-version specific) — a false green that skips rollback entirely. Warn\n# here so a CLI-driven run sees it too; the admin UI blocks earlier.\nREQUIRED_NODE=$(npm view \"@selvajs/selva@$TAG\" engines.node --silent 2>/dev/null | tr -d '\"' | tr -d \"'\")\nRUNNING_NODE=$(node -p 'process.versions.node' 2>/dev/null)\nif [ -n \"$REQUIRED_NODE\" ] && [ -n \"$RUNNING_NODE\" ]; then\n # Compare majors only — the ranges we publish are all \\`>=X\\` forms.\n REQ_MAJOR=$(echo \"$REQUIRED_NODE\" | grep -o '[0-9]\\\\+' | head -1)\n RUN_MAJOR=$(echo \"$RUNNING_NODE\" | cut -d. -f1)\n if [ -n \"$REQ_MAJOR\" ] && [ \"$RUN_MAJOR\" -lt \"$REQ_MAJOR\" ] 2>/dev/null; then\n echo \"[WARN] ENGINE_MISMATCH: @selvajs/selva@$LATEST requires Node $REQUIRED_NODE but this host runs v$RUNNING_NODE\"\n echo \"[WARN] npm will install it anyway (engine-strict is off) and the health probe will pass,\"\n echo \"[WARN] but routes using newer Node APIs will fail at request time. Upgrade Node on this host.\"\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 2. Resync PM2 daemon if its in-memory version drifted from the CLI on disk.\n# ---------------------------------------------------------------------------\n# After a global pm2 upgrade the daemon keeps running its original version\n# while the CLI moves forward. Process commands then talk to a stale daemon\n# and the symptom is \"stop works, start never lands\". \\`pm2 update\\` dumps\n# processes, kills the daemon, respawns on the current CLI, restores the\n# dump. Doing it before we touch anything keeps the rest of the script\n# talking to a coherent daemon.\necho \"[STEP] Checking PM2 daemon/CLI version sync\"\nPING_OUT=$(\"$PM2\" ping 2>&1)\nif echo \"$PING_OUT\" | grep -q \"out-of-date\"; then\n # pm2 prints both versions alongside the warning. Which is newer decides\n # whether \\`pm2 update\\` can help — see the direction check below.\n DAEMON_V=$(echo \"$PING_OUT\" | sed -e 's/\\\\x1b\\\\[[0-9;]*m//g' \\\\\n | grep -i \"In memory PM2 version\" | grep -o '[0-9]\\\\+\\\\.[0-9]\\\\+\\\\.[0-9]\\\\+' | head -1)\n LOCAL_V=$(echo \"$PING_OUT\" | sed -e 's/\\\\x1b\\\\[[0-9;]*m//g' \\\\\n | grep -i \"Local PM2 version\" | grep -o '[0-9]\\\\+\\\\.[0-9]\\\\+\\\\.[0-9]\\\\+' | head -1)\n DAEMON_MAJOR=\\${DAEMON_V%%.*}\n LOCAL_MAJOR=\\${LOCAL_V%%.*}\n\n # A daemon NEWER than the deployment-local CLI means a foreign global pm2 owns\n # it. \\`pm2 update\\` would DOWNGRADE the daemon and feed it a dump it can't read,\n # losing the process table — selva-compute never gets re-registered. That is an\n # operator problem, not something this script can repair, so stop before we\n # take the app down.\n if [ -n \"$DAEMON_MAJOR\" ] && [ -n \"$LOCAL_MAJOR\" ] && [ \"$DAEMON_MAJOR\" -gt \"$LOCAL_MAJOR\" ] 2>/dev/null; then\n echo \"[FATAL] PM2_SKEW: the running daemon (v$DAEMON_V) is NEWER than this deployment's pm2 (v$LOCAL_V).\"\n echo \"[FATAL] A global pm2 owns the daemon. Running 'pm2 update' would downgrade it and drop\"\n echo \"[FATAL] the process table. Resolve manually before updating:\"\n echo \"[FATAL] which -a pm2 && pm2 -v && pm2 ping\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n exit 8\n fi\n\n if pm2_under_systemd; then\n echo \"[FATAL] SYSTEMD_PM2: this deployment's PM2 is supervised by systemd, and the daemon\"\n echo \"[FATAL] needs a resync. Running 'pm2 update' here would restart the systemd unit and\"\n echo \"[FATAL] kill this runner mid-update. Resync manually from a shell, then retry:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\") && ./node_modules/.bin/pm2 update\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n exit 9\n fi\n\n echo \"[STEP] PM2 daemon is out-of-date — running 'pm2 update' to resync\"\n if ! \"$PM2\" update; then\n echo \"[FATAL] pm2 update failed — aborting before stopping the running app\"\n exit 1\n fi\n echo \"[INFO] PM2 daemon resynced\"\nfi\n\n# ---------------------------------------------------------------------------\n# 3. Stop selva-compute BEFORE npm rewrites build/.\n# ---------------------------------------------------------------------------\n# SvelteKit's node adapter lazy-imports chunks from build/server/chunks/ on\n# every request. Letting npm rewrite build/ while the old process still\n# serves traffic means in-flight requests hit ERR_MODULE_NOT_FOUND for chunks\n# whose hash just changed under their feet. Stopping first is a brief\n# downtime window (~1-2s longer than restart-in-place) for a much smaller\n# blast radius.\n#\n# This is also where the SSE connection to the frontend dies — selva-compute\n# IS the SSE server. From here on, the user sees output via the log-file\n# polling fallback in the admin UI, not over SSE.\necho \"[STEP] Stopping selva-compute\"\nif ! \"$PM2\" stop selva-compute; then\n echo \"[WARN] pm2 stop failed — selva-compute may not be running yet. Continuing.\"\nfi\n\n# pm2 stop returns before the process is actually gone. Everything below —\n# npm rewriting build/, then the restart — must happen outside the drain window.\nwait_until_stopped\n\n# ---------------------------------------------------------------------------\n# 4. Run npm update.\n# ---------------------------------------------------------------------------\necho \"[STEP] Updating @selvajs/* packages\"\nif ! ${npmCommand}; then\n echo \"[FATAL] npm update failed — EXIT trap will restart the previous build\"\n exit 1\nfi\n\nAFTER=$(node -e \"try{console.log(require('./node_modules/@selvajs/selva/package.json').version)}catch(e){}\" 2>/dev/null)\necho \"[INFO] New @selvajs/selva: \\${AFTER:-unknown}\"\n\nif [ -n \"$BEFORE\" ] && [ \"$BEFORE\" = \"$AFTER\" ]; then\n echo \"[WARN] No version change ($BEFORE). Your npm cache may be stale.\"\n echo \"[WARN] Recover with:\"\n echo \"[WARN] npm cache clean --force\"\n echo \"[WARN] rm -rf node_modules package-lock.json\"\n echo \"[WARN] npm install --prefer-online\"\nfi\n\n# ---------------------------------------------------------------------------\n# 4b. Move pm2 onto the version the new CLI pins.\n# ---------------------------------------------------------------------------\n# Only \\`selva migrate\\` rewrites package.json, so without this a release that\n# bumps pm2 needs a manual migrate on every host. The pin is read from the CLI\n# just installed: its devDependencies.pm2 is what a fresh scaffold gets. The\n# app is stopped, so swapping the daemon here adds no downtime. A failure\n# leaves the old pm2 running the app: warn, never abort. A rollback below\n# keeps the new pm2: reinstalling the old one would leave the daemon newer\n# than the CLI, the one skew \\`pm2 update\\` cannot repair.\nPM2_DECLARED=$(node -p \"require('./package.json').dependencies?.pm2 ?? ''\" 2>/dev/null)\nPM2_PIN=$(node -p \"require('./node_modules/@selvajs/cli/package.json').devDependencies?.pm2 ?? ''\" 2>/dev/null)\nif [ -n \"$PM2_PIN\" ] && [ \"$PM2_PIN\" != \"$PM2_DECLARED\" ]; then\n echo \"[STEP] Moving pm2 \\${PM2_DECLARED:-(none)} → $PM2_PIN, the version this release pins\"\n if npm install --save --save-exact --prefer-online \"pm2@$PM2_PIN\"; then\n if pm2_under_systemd; then\n echo \"[WARN] PM2_RESYNC_NEEDED: pm2 is now $PM2_PIN, but its daemon still runs the old version.\"\n echo \"[WARN] Swapping it here would restart the systemd unit and kill this runner. From a shell:\"\n echo \"[WARN] cd $(dirname \"$ECOSYSTEM\") && npx pm2 update && npx pm2 list\"\n echo \"[WARN] Let it finish: interrupting it leaves selva-compute unregistered.\"\n elif ! \"$PM2\" update; then\n echo \"[WARN] PM2_RESYNC_NEEDED: 'pm2 update' failed — the daemon still runs the old pm2.\"\n echo \"[WARN] cd $(dirname \"$ECOSYSTEM\") && npx pm2 update && npx pm2 list\"\n fi\n else\n echo \"[WARN] PM2_PIN_FAILED: could not install pm2@$PM2_PIN — the previous pm2 still runs the app.\"\n echo \"[WARN] Retry from a shell: cd $(dirname \"$ECOSYSTEM\") && npx selva migrate\"\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 5. Start selva-compute with the new build.\n# ---------------------------------------------------------------------------\n# Start from ecosystem.config.cjs, NOT \\`pm2 start selva-compute\\` — the latter\n# requires selva-compute to already be in pm2's in-memory process list, which\n# a \\`pm2 update\\` (step 2) isn't guaranteed to preserve.\necho \"[STEP] Starting selva-compute with new build\"\nif ! start_app; then\n echo \"[FATAL] pm2 start failed — investigate with \\\\\\`pm2 logs selva-compute\\\\\\`\"\n exit 2\nfi\n\n# ---------------------------------------------------------------------------\n# 6. Health probe the new process.\n# ---------------------------------------------------------------------------\n# Read PORT from .env the same way scripts/update.sh does, so non-default\n# ports are respected.\nPORT=$(grep \"^PORT=\" .env 2>/dev/null \\\\\n | head -1 \\\\\n | cut -d'=' -f2 \\\\\n | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/^[\"'\"'\"']//' -e 's/[\"'\"'\"']$//' -e 's/[[:space:]]*#.*//')\nPORT=\\${PORT:-3000}\n\necho \"[STEP] Health-probing the new process on port $PORT\"\nHEALTHY=0\nfor i in $(seq 1 15); do\n sleep 2\n CODE=$(curl -sS -o /tmp/selva-health.$$ -w \"%{http_code}\" --max-time 5 \"http://localhost:$PORT/api/health\" 2>/dev/null || echo \"000\")\n if [ \"$CODE\" = \"200\" ]; then\n HEALTHY=1\n echo \"[INFO] Health probe passed after \\${i} attempt(s)\"\n rm -f /tmp/selva-health.$$\n break\n fi\n echo \"[INFO] Probe attempt $i/15: HTTP $CODE — retrying\"\ndone\n\nif [ \"$HEALTHY\" = \"1\" ]; then\n echo \"[DONE] Update complete\"\n exit 0\nfi\n\n# ---------------------------------------------------------------------------\n# 7. Rollback path.\n# ---------------------------------------------------------------------------\necho \"[FATAL] New process failed health check after 30s\"\nif [ -f /tmp/selva-health.$$ ]; then\n BODY=$(cat /tmp/selva-health.$$)\n echo \"[FATAL] Last response body:\"\n echo \"$BODY\"\n\n # Name the cause before rolling back. /api/health reports WHY it is degraded\n # in a structured body, but a rollback that only prints raw JSON reads to an\n # operator as \"the update just failed\" — they retry, hit the identical\n # failure, and never learn the database is the thing that needs attention.\n # Each branch below emits a stable marker deriveOutcome keys on.\n # Match on the keys unique to each report rather than a bare \\`\"ok\":false\\`,\n # which appears in whichever sub-report failed and would misattribute one\n # cause to the other. \\`expected\\` only ever appears in schemaVersion;\n # \\`plaintextFound\\`/\\`failures\\` only in atRestSecrets.\n if echo \"$BODY\" | grep -q '\"expected\":'; then\n EXPECTED=$(echo \"$BODY\" | grep -o '\"expected\":\"[^\"]*\"' | head -1 | cut -d'\"' -f4)\n ACTUAL=$(echo \"$BODY\" | grep -o '\"actual\":\"[^\"]*\"' | head -1 | cut -d'\"' -f4)\n echo \"[FATAL] SCHEMA_SKEW: @selvajs/selva@\\${AFTER:-$LATEST} expects database migration head \\${EXPECTED:-(unknown)},\"\n echo \"[FATAL] but this database is at \\${ACTUAL:-(unavailable)}. The new version is fine — its migrations\"\n echo \"[FATAL] were never applied. Retrying the update WILL fail again in exactly the same way.\"\n echo \"[FATAL] The update does not apply migrations itself: they are not reversible, so an\"\n echo \"[FATAL] auto-migrate followed by a rollback would leave code and database on different heads.\"\n echo \"[FATAL] Apply them yourself, then re-run the update:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\")\"\n echo \"[FATAL] npm install --prefer-online @selvajs/supabase-provider@$TAG\"\n echo \"[FATAL] npx selva-supabase\"\n echo \"[FATAL] npx supabase db push\"\n echo \"[FATAL] The provider install is not optional: the migration SQL ships inside that\"\n echo \"[FATAL] package, and the update only moves @selvajs/cli and @selvajs/selva — so a sync\"\n echo \"[FATAL] without it copies 0 files and the push reports 'up to date' having done nothing.\"\n echo \"[FATAL] If db push asks for credentials, see docs/self-hosting/providers/supabase.md\"\n echo \"[FATAL] — it needs a Supabase ACCOUNT credential (supabase login, or SUPABASE_ACCESS_TOKEN),\"\n echo \"[FATAL] which is not any of the three keys in .env.\"\n elif echo \"$BODY\" | grep -qE '\"plaintextFound\":true|\"failures\":\\\\[[^]]'; then\n echo \"[FATAL] AT_REST_SECRETS: stored compute server API keys could not be decrypted under the\"\n echo \"[FATAL] current SELVA_AT_REST_KEY. This is a configuration problem on this host, not a\"\n echo \"[FATAL] fault in the new version — retrying the update will fail the same way.\"\n echo \"[FATAL] Re-enter the affected keys at /admin/compute, or restore the original\"\n echo \"[FATAL] SELVA_AT_REST_KEY, then re-run the update.\"\n else\n echo \"[FATAL] The health endpoint did not report a known cause. Inspect the body above and\"\n echo \"[FATAL] \\\\\\`pm2 logs selva-compute\\\\\\` for what the new version failed on.\"\n fi\n\n rm -f /tmp/selva-health.$$\nfi\n\nif [ -z \"$BEFORE\" ]; then\n echo \"[FATAL] No prior version recorded — cannot roll back automatically.\"\n echo \"[FATAL] EXIT trap will attempt to restart the current build anyway.\"\n exit 3\nfi\n\necho \"[STEP] Rolling back @selvajs/selva to $BEFORE\"\n\"$PM2\" stop selva-compute >/dev/null 2>&1 || true\nwait_until_stopped >/dev/null 2>&1\n# Restore @selvajs/cli alongside the runtime: the forward step installs both at\n# the channel tag, so reverting only the runtime leaves a version pair that was\n# never released together.\nif ! npm install --save \"@selvajs/cli@$BEFORE\" \"@selvajs/selva@$BEFORE\"; then\n echo \"[FATAL] Rollback npm install failed — EXIT trap will retry restart.\"\n exit 4\nfi\n\nstart_app || true\nsleep 3\nROLLBACK_CODE=$(curl -sS -o /dev/null -w \"%{http_code}\" --max-time 5 \"http://localhost:$PORT/api/health\" 2>/dev/null || echo \"000\")\nif [ \"$ROLLBACK_CODE\" = \"200\" ]; then\n echo \"[DONE] Rolled back to $BEFORE — previous version is online\"\n exit 5\nfi\n\necho \"[FATAL] Rollback restart also failed health check (HTTP $ROLLBACK_CODE)\"\necho \"[FATAL] Manual recovery required. Check: pm2 logs selva-compute\"\nexit 6\n`;\n}\n\n// Selva self-updates as a CLI-scaffolded npm deployment: the deployment dir\n// holds a package.json that depends on @selvajs/selva, and update means\n// `npm install @selvajs/*@<tag>` + pm2 restart. Deployment-dir detection\n// (cwd-upward probe, `INSTALL_DIR` override) lives in `selfUpdate.server.ts`,\n// shared with the outcome reconciler and the log path.\nexport type UpdatePlan = { cwd: string; args: string[] };\n\n// Only the CLI and the runtime move. Provider code is bundled into\n// @selvajs/selva; @selvajs/supabase-provider carries just the migration SQL,\n// which the operator installs and pushes before updating.\n//\n// `npm install` pins to the channel's dist-tag rather than using `npm\n// update`, because `update` only ever moves FORWARD within the installed\n// semver range — it can't switch dist-tags or DOWNGRADE. Pinning to @latest /\n// @beta makes one command serve every transition: forward stable bumps,\n// beta→newer-beta, and the revert case (beta→stable lands on an older version).\n//\n// --save persists the resolved version into package.json so the next plain\n// install is reproducible; --prefer-online forces npm to revalidate cached\n// packuments against the registry — without it, npm's packument cache (5+\n// min TTL) can silently no-op right after publish.\nexport function npmInstallArgs(channel: ReleaseChannel): string[] {\n\tconst tag = channelTag(channel);\n\treturn ['install', '--save', '--prefer-online', `@selvajs/cli@${tag}`, `@selvajs/selva@${tag}`];\n}\n\nexport function detectUpdatePlan(\n\tenv: Record<string, string | undefined>,\n\tchannel: ReleaseChannel\n): UpdatePlan | null {\n\tconst dir = findDeploymentDir(env);\n\treturn dir ? { cwd: dir, args: npmInstallArgs(channel) } : null;\n}\n","import { spawn } from 'child_process';\nimport { join } from 'path';\nimport { readFileSync, writeFileSync } from 'fs';\nimport { env } from '#lib/server/env.js';\nimport { json } from '@sveltejs/kit';\nimport { actorFrom } from '@selvajs/platform';\nimport type { RequestHandler } from './$types';\nimport { requirePermission } from '#lib/server/access.server.js';\nimport { renderThrown } from '@selvajs/server/logging';\nimport { checkForUpdate } from '#lib/server/updateCheck.server.js';\nimport { readChannel, channelTag } from '#lib/server/releaseChannel.server.js';\nimport { getEventSink, getErrorReporter } from '#lib/server/providers.server.js';\nimport {\n\tfindDeploymentDir,\n\tstartUpdateOutcomeReconciler,\n\tupdateLogPath,\n\tupdateStatePath,\n\ttype PendingUpdateState\n} from '#lib/server/selfUpdate.server.js';\nimport {\n\treadRuntimeVersion,\n\tbuildLauncher,\n\tbuildNpmRunnerScript,\n\tdetectUpdatePlan\n} from '#lib/server/updateRunner.server.js';\n\n// Where the bash wrapper mirrors all script output (`updateLogPath` — in the\n// deployment dir so it survives reboots, audit O2). The SSE stream dies the\n// moment `pm2 stop selva-compute` succeeds (selva-compute IS the SSE server),\n// so the frontend loses visibility into everything that happens after — npm\n// update output, pm2 start result, health-probe results, rollback decisions.\n// The script keeps writing to this file regardless. Once the new selva-compute\n// process is back up, the frontend polls GET on this same route to fetch the\n// full log and reveal what happened during the blackout. One log per update —\n// the wrapper truncates at start, so we never carry stale content forward.\n// The runner's `[EXIT] code=N` marker in the same log also drives the\n// post-restart audit-event reconciliation (`selfUpdate.server.ts`).\n\n// Strip ANSI escape codes from terminal output\nfunction stripAnsi(str: string): string {\n\t// eslint-disable-next-line no-control-regex\n\treturn str.replace(/\\x1B\\[[0-9;]*[mGKHF]/g, '');\n}\n\n// POST - Run update and stream output via Server-Sent Events.\n//\n// Runs `npm update @selvajs/*` then restarts via ecosystem.config.cjs. The\n// runner script handles stop / update / start / health-probe / rollback with\n// an EXIT trap that keeps the app online no matter how it exits.\nexport const POST: RequestHandler = async ({ locals }) => {\n\trequirePermission(locals, 'instance_admin');\n\n\tconst channel = readChannel();\n\tconst plan = detectUpdatePlan(env, channel);\n\tif (!plan) {\n\t\treturn new Response(\n\t\t\tJSON.stringify({\n\t\t\t\terror:\n\t\t\t\t\t\"Couldn't determine how to update this deployment. \" +\n\t\t\t\t\t'Expected node_modules/@selvajs/selva (CLI scaffold) in the cwd ' +\n\t\t\t\t\t'or a parent directory.'\n\t\t\t}),\n\t\t\t{ status: 500, headers: { 'Content-Type': 'application/json' } }\n\t\t);\n\t}\n\n\t// Capture the runtime version BEFORE we touch anything, so we can:\n\t// (a) detect a no-op update and warn, (b) roll back to the prior version\n\t// if the new process fails to come up healthy.\n\tconst versionBefore = readRuntimeVersion(plan.cwd);\n\tconst actorId = locals.ctx ? actorFrom(locals.ctx) : 'system';\n\n\t// Audit trail (O2): `started` now; the terminal event is emitted by the\n\t// outcome reconciler after the app restarts (this process is killed\n\t// mid-update). The state file is the reconciler's emission token.\n\tconst pending: PendingUpdateState = {\n\t\tstartedAt: new Date().toISOString(),\n\t\tactorId,\n\t\tchannel,\n\t\tfromVersion: versionBefore\n\t};\n\ttry {\n\t\twriteFileSync(updateStatePath(plan.cwd), JSON.stringify(pending, null, '\\t'));\n\t} catch (err) {\n\t\tlocals.log.error('Could not persist pending-update state', {\n\t\t\tcomponent: 'selfUpdate',\n\t\t\terr: renderThrown(err)\n\t\t});\n\t}\n\tawait getEventSink().emit({\n\t\ttype: 'system.update.started',\n\t\tchannel,\n\t\tfromVersion: versionBefore,\n\t\tactorId\n\t});\n\n\tconst stream = new ReadableStream({\n\t\tstart(controller) {\n\t\t\tconst encoder = new TextEncoder();\n\n\t\t\tfunction sendEvent(type: string, data: Record<string, unknown>) {\n\t\t\t\tconst message = `data: ${JSON.stringify({ type, ...data })}\\n\\n`;\n\t\t\t\tcontroller.enqueue(encoder.encode(message));\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t// Prelude lines are passed to the bash wrapper rather than\n\t\t\t\t// sendEvent'd directly so they end up in both the SSE stream\n\t\t\t\t// (via bash stdout) AND the log file (via tee). Without this,\n\t\t\t\t// the frontend's blackout-recovery file fetch would clobber\n\t\t\t\t// these lines when it replaces its buffer with the file content.\n\t\t\t\tconst prelude = [\n\t\t\t\t\t`[INFO] Updating deployment (cwd: ${plan.cwd}, channel: ${channel})`,\n\t\t\t\t\t...(versionBefore ? [`[INFO] Current @selvajs/selva: ${versionBefore}`] : [])\n\t\t\t\t];\n\n\t\t\t\t// Spawn the launcher detached. The launcher writes the actual\n\t\t\t\t// runner script to disk, daemonizes it (setsid + & + exit),\n\t\t\t\t// and quits — leaving the runner with PPID=1 so PM2's tree-kill\n\t\t\t\t// of selva-compute can't reach it. See buildLauncher for the\n\t\t\t\t// full rationale.\n\t\t\t\t//\n\t\t\t\t// The runner is buildNpmRunnerScript — pre-flights the version\n\t\t\t\t// check, then stop / npm update / start / health probe /\n\t\t\t\t// rollback, with an EXIT trap that ensures the app is online no\n\t\t\t\t// matter how the script exits.\n\t\t\t\tconst runnerScript = buildNpmRunnerScript(\n\t\t\t\t\tplan.args,\n\t\t\t\t\tversionBefore,\n\t\t\t\t\tjoin(plan.cwd, 'ecosystem.config.cjs'),\n\t\t\t\t\tchannelTag(channel)\n\t\t\t\t);\n\t\t\t\tconst cmd = 'bash';\n\t\t\t\tconst args = ['-c', buildLauncher(runnerScript, updateLogPath(plan.cwd), prelude)];\n\n\t\t\t\t// Prepend the deployment's node_modules/.bin to PATH so the bash\n\t\t\t\t// script finds the project-local pm2 (and any other tooling\n\t\t\t\t// installed as a deployment dependency). Without this the script\n\t\t\t\t// inherits the SvelteKit process's PATH, which on most servers\n\t\t\t\t// doesn't include node_modules/.bin — so `pm2` resolves to\n\t\t\t\t// whatever's globally installed, or fails outright if no global\n\t\t\t\t// pm2 exists. Both are wrong: we want the project-local pm2 so\n\t\t\t\t// daemon and CLI stay aligned. Mirrors the local-only resolution\n\t\t\t\t// in @selvajs/cli's pm2Bin().\n\t\t\t\tconst localBin = join(plan.cwd, 'node_modules', '.bin');\n\t\t\t\tconst child = spawn(cmd, args, {\n\t\t\t\t\tcwd: plan.cwd,\n\t\t\t\t\tenv: {\n\t\t\t\t\t\tPATH: `${localBin}:${process.env.PATH ?? ''}`,\n\n\t\t\t\t\t\tHOME: process.env.HOME,\n\t\t\t\t\t\tINSTALL_DIR: plan.cwd\n\t\t\t\t\t},\n\t\t\t\t\tdetached: true,\n\t\t\t\t\tstdio: ['ignore', 'pipe', 'pipe']\n\t\t\t\t});\n\t\t\t\tchild.unref();\n\n\t\t\t\t// Covers the outcomes that DON'T restart this process (pre-flight\n\t\t\t\t// \"already up to date\", early failures): this process is still\n\t\t\t\t// alive to reconcile them. A real update kills this process; the\n\t\t\t\t// restarted one re-arms the reconciler from hooks.server.ts.\n\t\t\t\tstartUpdateOutcomeReconciler({\n\t\t\t\t\tdeploymentDir: plan.cwd,\n\t\t\t\t\temit: (e) => getEventSink().emit(e),\n\t\t\t\t\treport: (err) => getErrorReporter().capture(err, { tags: { origin: 'selfUpdate' } })\n\t\t\t\t});\n\n\t\t\t\t// Kill the process if it runs longer than 15 minutes.\n\t\t\t\t// The child is detached (its own process group), so signal the\n\t\t\t\t// whole group via negative pid — otherwise descendants (pnpm,\n\t\t\t\t// node, pm2) outlive the bash wrapper.\n\t\t\t\tconst timeout = setTimeout(\n\t\t\t\t\t() => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (child.pid) process.kill(-child.pid, 'SIGTERM');\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// group already gone — nothing to do\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsendEvent('log', { data: '[FATAL] Update timed out after 15 minutes' });\n\t\t\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t},\n\t\t\t\t\t15 * 60 * 1000\n\t\t\t\t);\n\n\t\t\t\t// Stream stdout\n\t\t\t\tlet restarting = false;\n\t\t\t\tchild.stdout.on('data', (data) => {\n\t\t\t\t\tconst lines = data.toString().split('\\n');\n\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\tconst clean = stripAnsi(line).trim();\n\t\t\t\t\t\tif (clean) {\n\t\t\t\t\t\t\t// Detect both stopProcessId (pm2 restart) and restartProcessId (pm2 reload)\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!restarting &&\n\t\t\t\t\t\t\t\t(clean.includes('Applying action stopProcessId') ||\n\t\t\t\t\t\t\t\t\tclean.includes('Applying action restartProcessId'))\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\trestarting = true;\n\t\t\t\t\t\t\t\tsendEvent('restarting', { data: clean });\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tsendEvent('log', { data: clean });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Stream stderr\n\t\t\t\tchild.stderr.on('data', (data) => {\n\t\t\t\t\tconst lines = data.toString().split('\\n');\n\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\tconst clean = stripAnsi(line).trim();\n\t\t\t\t\t\tif (clean) {\n\t\t\t\t\t\t\tsendEvent('log', { data: `[ERROR] ${clean}` });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Handle process exit\n\t\t\t\tchild.on('close', (code) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tsendEvent('exit', { code: code ?? -1 });\n\t\t\t\t\tcontroller.close();\n\t\t\t\t});\n\n\t\t\t\t// Handle errors\n\t\t\t\tchild.on('error', (err) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tsendEvent('log', { data: `[FATAL] ${err.message}` });\n\t\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\t\tcontroller.close();\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tsendEvent('log', { data: `[FATAL] Failed to spawn process: ${err}` });\n\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\tcontroller.close();\n\t\t\t}\n\t\t}\n\t});\n\n\treturn new Response(stream, {\n\t\theaders: {\n\t\t\t'Content-Type': 'text/event-stream',\n\t\t\t'Cache-Control': 'no-cache',\n\t\t\tConnection: 'keep-alive'\n\t\t}\n\t});\n};\n\n// GET — two jobs, selected by query param:\n//\n// ?check=1 → query the npm registry and report whether a newer\n// @selvajs/selva is published. JSON: { current, latest,\n// updateAvailable }. The admin page calls this on load to show\n// an \"update available\" badge. Degrades gracefully: if the\n// registry is unreachable, latest is null and updateAvailable\n// is false (we never block the page on npm).\n//\n// (default) → read the tee'd update log so the frontend can recover the\n// chunk of output that happened during the SSE blackout (between\n// `pm2 stop` killing this process and the new selva-compute\n// coming back online). Empty body if no update has run yet.\n// Polled by the admin UI during the post-restart wait.\nexport const GET: RequestHandler = async ({ locals, url, fetch }) => {\n\trequirePermission(locals, 'instance_admin');\n\n\tif (url.searchParams.get('check') !== null) {\n\t\treturn json(await checkForUpdate(fetch, readChannel()), {\n\t\t\theaders: { 'Cache-Control': 'no-store' }\n\t\t});\n\t}\n\n\tlet body = '';\n\ttry {\n\t\tbody = readFileSync(updateLogPath(findDeploymentDir(env)), 'utf8');\n\t} catch {\n\t\t// Log doesn't exist (no update has run yet). Empty body is correct —\n\t\t// the frontend treats no content as \"nothing to show yet\".\n\t}\n\treturn new Response(body, {\n\t\theaders: {\n\t\t\t'Content-Type': 'text/plain; charset=utf-8',\n\t\t\t'Cache-Control': 'no-store'\n\t\t}\n\t});\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAaA,SAAgB,mBAAmB,KAAiC;CACnE,IAAI;EACH,MAAM,MAAM,KAAK,MAChB,aAAa,KAAK,KAAK,gBAAgB,YAAY,SAAS,cAAc,GAAG,MAAM,CACpF;EACA,OAAO,OAAO,IAAI,YAAY,WAAW,IAAI,UAAU,KAAA;CACxD,QAAQ;EACP;CACD;AACD;AAKA,SAAgB,WAAW,GAAmB;CAC7C,OAAO,IAAI,EAAE,QAAQ,MAAM,OAAO,EAAE;AACrC;AAoBA,SAA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,CAAC;AACF"}
1
+ {"version":3,"file":"_server.ts.js","names":["join","readFileSync"],"sources":["../../../../../../../../src/lib/server/updateRunner.server.ts","../../../../../../../../src/routes/api/admin/system/update/+server.ts"],"sourcesContent":["/**\n * Generates the bash the self-update POST route spawns: a tiny daemonizing\n * launcher plus the runner script that actually stops/updates/starts/health-\n * checks the deployment. Split out of the route file because SvelteKit's\n * route-file validator only allows HTTP-verb exports (and `_`-prefixed ones) —\n * these are plain functions the runner-script contract tests import directly.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { findDeploymentDir } from './selfUpdate.server.js';\nimport { channelTag, type ReleaseChannel } from './releaseChannel.server.js';\n\nexport function readRuntimeVersion(dir: string): string | undefined {\n\ttry {\n\t\tconst pkg = JSON.parse(\n\t\t\treadFileSync(join(dir, 'node_modules', '@selvajs', 'selva', 'package.json'), 'utf8')\n\t\t);\n\t\treturn typeof pkg.version === 'string' ? pkg.version : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n// No caller currently passes untrusted input (plan.cwd is from\n// process.cwd(), npm package names are hardcoded), but defensive quoting is\n// cheap.\nexport function shellQuote(s: string): string {\n\treturn `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\n// Wraps the actual update commands in a tiny \"launcher\" that daemonizes them.\n//\n// THE PROBLEM: `pm2 stop selva-compute` (which the runner has to call) uses\n// tree-kill, which walks /proc parent-child relationships from\n// selva-compute's PID and SIGKILLs every descendant. Node's\n// `{ detached: true }` + `child.unref()` puts the spawned bash in a new\n// session/process group but does NOT change the parent-child relationship —\n// so tree-kill still finds and kills it, and the app never restarts.\n//\n// THE FIX: write the update commands to a tempfile and launch them via\n// `setsid bash ... &`, then have the launcher exit. The runner's PPID becomes\n// 1 (init) the moment the launcher exits, so it's no longer a descendant of\n// selva-compute and tree-kill can't reach it.\n//\n// Output: the launcher's prelude lines are echoed via tee into\n// UPDATE_LOG_PATH and through stdout (visible to SSE while the connection is\n// still up); the runner appends its output to the same log file; the\n// frontend tolerates the SSE blackout by polling the log file.\nexport function buildLauncher(\n\trunnerScript: string,\n\tlogPath: string,\n\tprelude: string[] = []\n): string {\n\tconst echoes = prelude.map((line) => `echo ${shellQuote(line)}`).join('\\n');\n\t// Note: runner script is embedded via a QUOTED heredoc so no variable\n\t// expansion happens — the runner text is written verbatim.\n\treturn `\nLOGFILE=${shellQuote(logPath)}\nmkdir -p \"$(dirname \"$LOGFILE\")\"\n: > \"$LOGFILE\"\n\n# mktemp, never a fixed name: /tmp is shared, and a file another account left at\n# a known path survives the write below and would run as the app user.\nRUNNER=$(mktemp \"\\${TMPDIR:-/tmp}/selva-update-runner.XXXXXXXX\") || {\n\techo \"[ERROR] Could not create the update runner in \\${TMPDIR:-/tmp}\"\n\texit 1\n}\ncat > \"$RUNNER\" <<'__SELVA_RUNNER_EOF__' || { echo \"[ERROR] Could not write the update runner\"; exit 1; }\nrm -f \"$0\"\nfor _ in $(seq 1 50); do\n kill -0 \"$SELVA_RUNNER_SPAWNER\" 2>/dev/null || break\n sleep 0.1\ndone\n${runnerScript}\n__SELVA_RUNNER_EOF__\n\ntrap '' PIPE\nexec > >(tee --output-error=warn-nopipe -a \"$LOGFILE\" 2>/dev/null) 2>&1\n${echoes}\n\n# Daemonize the runner so PM2's tree-kill of selva-compute can't reach it.\n# When the runner calls pm2 stop, pm2 lists the app's descendants and SIGKILLs\n# whatever on that list outlives its kill timeout. A runner still parented to this\n# launcher is on the list: it died mid-update and left the app stopped whenever the\n# registry answered inside the pause below. So it is orphaned before it runs a\n# line: the subshell forks it and exits, and the runner waits for that exit.\n# setsid gives it its own session; its stdio is detached from selva-compute's pipes.\nRUNNER_PID=$( (SELVA_RUNNER_SPAWNER=$BASHPID setsid bash \"$RUNNER\" </dev/null >>\"$LOGFILE\" 2>&1 & echo $!) )\necho \"[INFO] Update runner started (PID $RUNNER_PID, log: $LOGFILE)\"\n\n# Small pause so the runner has time to print its first line before SSE\n# closes — otherwise the frontend's first poll might see no progress.\nsleep 1\nexit 0\n`;\n}\n\n// Bash script the daemonized runner executes. Flow:\n//\n// 1. pre-flight — query the registry; if already on latest, exit clean\n// WITHOUT touching the running app. Refuse a target\n// that cannot read this deployment's data.\n// 2. pm2 sync — `pm2 update` if the daemon and CLI versions drifted.\n// 3. pm2 stop — stop selva-compute before npm overwrites build/, so\n// in-flight requests can't hit ERR_MODULE_NOT_FOUND\n// from chunk-hash churn under their feet.\n// 4. npm update — refresh @selvajs/* (--prefer-online bypasses the\n// packument cache, already baked into npmArgs).\n// 5. pm2 start — from ecosystem.config.cjs (not `pm2 start name`,\n// which requires the process to already be in pm2's\n// in-memory list — fragile after `pm2 update`).\n// 6. health probe — poll /api/health for up to 30s.\n// 7. rollback — on failure: npm install the prior version, restart.\n// 8. EXIT trap — last-resort: if anything above leaves the app\n// offline (crash, kill, network blip), unconditionally\n// try `pm2 start ecosystem.config.cjs` before exiting\n// so the customer's site doesn't stay dark.\n//\n// Embedded into the launcher via a quoted heredoc, so this whole string is\n// written verbatim — interpolated values must be shell-quoted at JS time.\nexport function buildNpmRunnerScript(\n\tnpmArgs: string[],\n\tversionBefore: string | undefined,\n\tecosystemPath: string,\n\ttag: string\n): string {\n\tconst npmCommand = ['npm', ...npmArgs].map(shellQuote).join(' ');\n\t// Empty string when versionBefore is undefined — bash sees `BEFORE=\"\"`\n\t// and skips the rollback path (you can't roll back to nothing).\n\tconst before = shellQuote(versionBefore ?? '');\n\tconst ecosystem = shellQuote(ecosystemPath);\n\t// The npm dist-tag the chosen channel resolves to (`latest` / `beta`). The\n\t// pre-flight and no-change warning query this tag, so they don't misfire on\n\t// a beta channel (where the channel's published version is a pre-release the\n\t// default `latest` query would never see) or on a revert (where the target\n\t// stable version is OLDER than the installed beta).\n\tconst distTag = shellQuote(tag);\n\n\treturn `#!/bin/bash\nset -o pipefail\nBEFORE=${before}\nECOSYSTEM=${ecosystem}\nTAG=${distTag}\n\n# Resolve the deployment-local pm2 explicitly instead of trusting PATH.\n# The runner is re-launched via \\`setsid bash\\` from a tempfile, so it inherits\n# whatever environment the spawning process had. When the update is triggered\n# from the admin UI that happens to include node_modules/.bin; from cron or a\n# bare shell it does not, and every pm2 call below — including the EXIT trap's\n# last-resort restart — fails with \"command not found\" and the app stays dark.\nPM2=\"$(dirname \"$ECOSYSTEM\")/node_modules/.bin/pm2\"\n[ -x \"$PM2\" ] || PM2=pm2\n\n# Under systemd, \\`pm2 update\\` kills and respawns the daemon. systemd sees its\n# unit's main process die and, with the default KillMode=control-group,\n# SIGTERMs everything in the cgroup — including this runner. setsid escapes\n# PM2's tree-kill but NOT the cgroup, so the runner never runs \\`pm2 update\\`\n# when this is true.\npm2_under_systemd() {\n grep -qs 'pm2.*\\\\.service' /proc/self/cgroup 2>/dev/null\n}\n\n# Waits for selva-compute to leave the transitional 'stopping' state.\n#\n# \\`pm2 stop\\` sends SIGINT and returns without waiting for the process to die.\n# The SvelteKit node adapter then drains in-flight requests before exiting, and\n# PM2 only escalates to SIGKILL after kill_timeout (10s in the scaffolded\n# ecosystem). For that whole window the process table entry has a name and an\n# id but no live pid — \\`pm2 start\\` resolves the name, converts to a restart,\n# finds nothing to restart, and pm2's own table printer crashes on\n# \\`undefined.pm2_env\\`. Polling here keeps the rest of the script out of that\n# window entirely.\n#\n# The drain reliably takes the full timeout when the update was triggered from\n# the admin UI: that page is fed by an SSE stream this very process serves, and\n# an open SSE stream never completes on its own.\n# Prints exactly one word. Callers compare it against 'online' / 'stopping', so\n# a probe that emits two tokens on failure (the inline catch AND a shell\n# fallback both firing) would silently never match either. Node's catch is the\n# single failure path; fd 0 rather than /dev/stdin because the latter isn't a\n# readable pipe everywhere.\napp_status() {\n \"$PM2\" jlist 2>/dev/null | node -e \"\n try {\n const list = JSON.parse(require('fs').readFileSync(0,'utf8'));\n const app = list.find(p => p.name === 'selva-compute');\n process.stdout.write(app ? app.pm2_env.status : 'missing');\n } catch { process.stdout.write('error'); }\n \" 2>/dev/null\n}\n\nwait_until_stopped() {\n for i in $(seq 1 20); do\n STATUS=$(app_status)\n if [ \"$STATUS\" != \"stopping\" ]; then\n return 0\n fi\n echo \"[INFO] selva-compute still draining (attempt $i/20) — waiting for SIGKILL escalation\"\n sleep 1\n done\n echo \"[WARN] selva-compute stuck in 'stopping' after 20s — continuing anyway\"\n return 1\n}\n\n# \\`pm2 start <ecosystem>\\` converts to a restart-by-id when an entry of the same\n# name is already in the table. If that entry is stale the restart fails and no\n# amount of retrying the same command helps — the name has to be dropped first\n# so the start registers a fresh process. Deleting a stopped entry is safe: the\n# ecosystem file is the source of truth for how to bring it back.\nstart_app() {\n if \"$PM2\" start \"$ECOSYSTEM\" --update-env; then\n return 0\n fi\n echo \"[WARN] pm2 start failed — dropping the stale process entry and retrying\"\n \"$PM2\" delete selva-compute >/dev/null 2>&1 || true\n \"$PM2\" start \"$ECOSYSTEM\" --update-env\n}\n\n# Last-resort safety net. If the script exits with the app NOT online for\n# any reason (crash, kill -9, network blip, npm hang past timeout), try to\n# bring it back from ecosystem.config.cjs before exiting. Leaving the app\n# down is the worst possible outcome of an update.\non_exit() {\n CODE=$?\n STATUS=$(app_status)\n # A 'stopping' entry is mid-drain, not down. Restarting it now hits the same\n # dead-id window that brought us here; wait for the entry to settle first.\n if [ \"$STATUS\" = \"stopping\" ]; then\n wait_until_stopped\n STATUS=$(app_status)\n fi\n if [ \"$STATUS\" != \"online\" ]; then\n echo \"[RECOVER] selva-compute is '$STATUS' — starting from ecosystem.config.cjs\"\n start_app >/dev/null 2>&1 || \\\\\n echo \"[RECOVER] pm2 start failed — manual intervention required: cd $(dirname \"$ECOSYSTEM\") && ./node_modules/.bin/pm2 delete selva-compute; ./node_modules/.bin/pm2 start ecosystem.config.cjs\"\n fi\n # Terminal marker: the restarted app's outcome reconciler greps this to turn\n # the run into an audit event (selfUpdate.server.ts). Keep the format stable.\n echo \"[EXIT] code=$CODE\"\n}\ntrap on_exit EXIT\n\n# A killed runner must not look like a finished one.\n#\n# \\`$?\\` inside an EXIT trap reports the last completed command, NOT the signal.\n# When systemd SIGTERMs the whole cgroup, the EXIT trap still runs and records\n# \\`code=0\\` — so deriveOutcome takes the exit-0 success branch and tells the\n# operator \"Updated X → Y. The app is back online.\" while npm never ran and\n# the deployment is unchanged. Catching the signal makes the recorded code\n# truthful; 143/130 are the conventional 128+signal values.\non_signal() {\n SIG=$1\n echo \"[FATAL] KILLED: runner received SIG$SIG before finishing.\"\n echo \"[FATAL] Nothing was installed by this run. If the app is down, recover with:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\") && pm2 start ecosystem.config.cjs --update-env\"\n echo \"[FATAL] A systemd-supervised pm2 can do this when 'pm2 update' recycles the daemon.\"\n exit $2\n}\ntrap 'on_signal TERM 143' TERM\ntrap 'on_signal INT 130' INT\ntrap 'on_signal HUP 129' HUP\n\n# ---------------------------------------------------------------------------\n# 1. Pre-flight: skip the whole cycle if there's nothing to install.\n# ---------------------------------------------------------------------------\n# Without this, clicking \"Update\" on an already-current instance triggers a\n# full stop/install/start cycle and a downtime window for no reason.\necho \"[STEP] Checking npm registry for the '$TAG' channel version\"\nLATEST=$(npm view \"@selvajs/selva@$TAG\" version --silent 2>/dev/null || echo \"\")\nif [ -z \"$LATEST\" ]; then\n echo \"[WARN] Could not query npm registry — proceeding with update attempt anyway\"\nelif [ -n \"$BEFORE\" ] && [ \"$LATEST\" = \"$BEFORE\" ]; then\n echo \"[INFO] Already on the '$TAG' channel version ($BEFORE)\"\n echo \"[DONE] Nothing to do\"\n exit 0\nelse\n # May be a forward update OR a revert (target older than installed) — either\n # way the installed version differs from what this channel publishes.\n echo \"[INFO] Target ($TAG): $BEFORE → $LATEST\"\nfi\n\n# ---------------------------------------------------------------------------\n# 1b. Node engine pre-flight — BEFORE any downtime.\n# ---------------------------------------------------------------------------\n# npm only treats an engine mismatch as fatal under engine-strict=true, which\n# no deployment sets. So a release requiring a newer Node installs\n# \"successfully\", pm2 starts, and /api/health returns 200 (it touches nothing\n# Node-version specific) — a false green that skips rollback entirely. Warn\n# here so a CLI-driven run sees it too; the admin UI blocks earlier.\nREQUIRED_NODE=$(npm view \"@selvajs/selva@$TAG\" engines.node --silent 2>/dev/null | tr -d '\"' | tr -d \"'\")\nRUNNING_NODE=$(node -p 'process.versions.node' 2>/dev/null)\nif [ -n \"$REQUIRED_NODE\" ] && [ -n \"$RUNNING_NODE\" ]; then\n # Compare majors only — the ranges we publish are all \\`>=X\\` forms.\n REQ_MAJOR=$(echo \"$REQUIRED_NODE\" | grep -o '[0-9]\\\\+' | head -1)\n RUN_MAJOR=$(echo \"$RUNNING_NODE\" | cut -d. -f1)\n if [ -n \"$REQ_MAJOR\" ] && [ \"$RUN_MAJOR\" -lt \"$REQ_MAJOR\" ] 2>/dev/null; then\n echo \"[WARN] ENGINE_MISMATCH: @selvajs/selva@$LATEST requires Node $REQUIRED_NODE but this host runs v$RUNNING_NODE\"\n echo \"[WARN] npm will install it anyway (engine-strict is off) and the health probe will pass,\"\n echo \"[WARN] but routes using newer Node APIs will fail at request time. Upgrade Node on this host.\"\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 1c. Data format pre-flight — BEFORE any downtime.\n# ---------------------------------------------------------------------------\n# A release with a lower data format than the installed one cannot read what\n# this deployment has already stored (dataFormat.server.ts). It would boot, fail\n# its health check and roll back: two outages for nothing. Installed by hand it\n# leaves stored Compute API keys unreadable. A release that declares no format\n# is format 1. Skipped when the registry gave no answer: the target is unknown.\nINSTALLED_FORMAT=$(node -p \"require('./node_modules/@selvajs/selva/package.json').selva?.dataFormat ?? 1\" 2>/dev/null)\ncase \"$INSTALLED_FORMAT\" in ''|*[!0-9]*) INSTALLED_FORMAT=1 ;; esac\nif [ -n \"$LATEST\" ] && TARGET_FORMAT=$(npm view \"@selvajs/selva@$TAG\" selva.dataFormat --silent 2>/dev/null); then\n TARGET_FORMAT=$(echo \"$TARGET_FORMAT\" | tr -d '\"' | tr -d \"'\" | tr -d '[:space:]')\n case \"$TARGET_FORMAT\" in ''|*[!0-9]*) TARGET_FORMAT=1 ;; esac\n if [ \"$TARGET_FORMAT\" -lt \"$INSTALLED_FORMAT\" ]; then\n echo \"[FATAL] DATA_FORMAT: @selvajs/selva@$LATEST reads data format $TARGET_FORMAT, but this deployment is on format $INSTALLED_FORMAT.\"\n echo \"[FATAL] It could not read what the installed version has stored, such as Compute API keys.\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n echo \"[FATAL] To go back anyway: docs/self-hosting/deployment/admin.md, 'Going back to an older release'.\"\n exit 10\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 2. Resync PM2 daemon if its in-memory version drifted from the CLI on disk.\n# ---------------------------------------------------------------------------\n# After a global pm2 upgrade the daemon keeps running its original version\n# while the CLI moves forward. Process commands then talk to a stale daemon\n# and the symptom is \"stop works, start never lands\". \\`pm2 update\\` dumps\n# processes, kills the daemon, respawns on the current CLI, restores the\n# dump. Doing it before we touch anything keeps the rest of the script\n# talking to a coherent daemon.\necho \"[STEP] Checking PM2 daemon/CLI version sync\"\nPING_OUT=$(\"$PM2\" ping 2>&1)\nif echo \"$PING_OUT\" | grep -q \"out-of-date\"; then\n # pm2 prints both versions alongside the warning. Which is newer decides\n # whether \\`pm2 update\\` can help — see the direction check below.\n DAEMON_V=$(echo \"$PING_OUT\" | sed -e 's/\\\\x1b\\\\[[0-9;]*m//g' \\\\\n | grep -i \"In memory PM2 version\" | grep -o '[0-9]\\\\+\\\\.[0-9]\\\\+\\\\.[0-9]\\\\+' | head -1)\n LOCAL_V=$(echo \"$PING_OUT\" | sed -e 's/\\\\x1b\\\\[[0-9;]*m//g' \\\\\n | grep -i \"Local PM2 version\" | grep -o '[0-9]\\\\+\\\\.[0-9]\\\\+\\\\.[0-9]\\\\+' | head -1)\n DAEMON_MAJOR=\\${DAEMON_V%%.*}\n LOCAL_MAJOR=\\${LOCAL_V%%.*}\n\n # A daemon NEWER than the deployment-local CLI means a foreign global pm2 owns\n # it. \\`pm2 update\\` would DOWNGRADE the daemon and feed it a dump it can't read,\n # losing the process table — selva-compute never gets re-registered. That is an\n # operator problem, not something this script can repair, so stop before we\n # take the app down.\n if [ -n \"$DAEMON_MAJOR\" ] && [ -n \"$LOCAL_MAJOR\" ] && [ \"$DAEMON_MAJOR\" -gt \"$LOCAL_MAJOR\" ] 2>/dev/null; then\n echo \"[FATAL] PM2_SKEW: the running daemon (v$DAEMON_V) is NEWER than this deployment's pm2 (v$LOCAL_V).\"\n echo \"[FATAL] A global pm2 owns the daemon. Running 'pm2 update' would downgrade it and drop\"\n echo \"[FATAL] the process table. Resolve manually before updating:\"\n echo \"[FATAL] which -a pm2 && pm2 -v && pm2 ping\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n exit 8\n fi\n\n if pm2_under_systemd; then\n echo \"[FATAL] SYSTEMD_PM2: this deployment's PM2 is supervised by systemd, and the daemon\"\n echo \"[FATAL] needs a resync. Running 'pm2 update' here would restart the systemd unit and\"\n echo \"[FATAL] kill this runner mid-update. Resync manually from a shell, then retry:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\") && ./node_modules/.bin/pm2 update\"\n echo \"[FATAL] Aborting WITHOUT stopping the app — it is still running.\"\n exit 9\n fi\n\n echo \"[STEP] PM2 daemon is out-of-date — running 'pm2 update' to resync\"\n if ! \"$PM2\" update; then\n echo \"[FATAL] pm2 update failed — aborting before stopping the running app\"\n exit 1\n fi\n echo \"[INFO] PM2 daemon resynced\"\nfi\n\n# ---------------------------------------------------------------------------\n# 3. Stop selva-compute BEFORE npm rewrites build/.\n# ---------------------------------------------------------------------------\n# SvelteKit's node adapter lazy-imports chunks from build/server/chunks/ on\n# every request. Letting npm rewrite build/ while the old process still\n# serves traffic means in-flight requests hit ERR_MODULE_NOT_FOUND for chunks\n# whose hash just changed under their feet. Stopping first is a brief\n# downtime window (~1-2s longer than restart-in-place) for a much smaller\n# blast radius.\n#\n# This is also where the SSE connection to the frontend dies — selva-compute\n# IS the SSE server. From here on, the user sees output via the log-file\n# polling fallback in the admin UI, not over SSE.\necho \"[STEP] Stopping selva-compute\"\nif ! \"$PM2\" stop selva-compute; then\n echo \"[WARN] pm2 stop failed — selva-compute may not be running yet. Continuing.\"\nfi\n\n# pm2 stop returns before the process is actually gone. Everything below —\n# npm rewriting build/, then the restart — must happen outside the drain window.\nwait_until_stopped\n\n# ---------------------------------------------------------------------------\n# 4. Run npm update.\n# ---------------------------------------------------------------------------\necho \"[STEP] Updating @selvajs/* packages\"\nif ! ${npmCommand}; then\n echo \"[FATAL] npm update failed — EXIT trap will restart the previous build\"\n exit 1\nfi\n\nAFTER=$(node -e \"try{console.log(require('./node_modules/@selvajs/selva/package.json').version)}catch(e){}\" 2>/dev/null)\necho \"[INFO] New @selvajs/selva: \\${AFTER:-unknown}\"\n\nif [ -n \"$BEFORE\" ] && [ \"$BEFORE\" = \"$AFTER\" ]; then\n echo \"[WARN] No version change ($BEFORE). Your npm cache may be stale.\"\n echo \"[WARN] Recover with:\"\n echo \"[WARN] npm cache clean --force\"\n echo \"[WARN] rm -rf node_modules package-lock.json\"\n echo \"[WARN] npm install --prefer-online\"\nfi\n\n# ---------------------------------------------------------------------------\n# 4b. Move pm2 onto the version the new CLI pins.\n# ---------------------------------------------------------------------------\n# Only \\`selva migrate\\` rewrites package.json, so without this a release that\n# bumps pm2 needs a manual migrate on every host. The pin is read from the CLI\n# just installed: its devDependencies.pm2 is what a fresh scaffold gets. The\n# app is stopped, so swapping the daemon here adds no downtime. A failure\n# leaves the old pm2 running the app: warn, never abort. A rollback below\n# keeps the new pm2: reinstalling the old one would leave the daemon newer\n# than the CLI, the one skew \\`pm2 update\\` cannot repair.\nPM2_DECLARED=$(node -p \"require('./package.json').dependencies?.pm2 ?? ''\" 2>/dev/null)\nPM2_PIN=$(node -p \"require('./node_modules/@selvajs/cli/package.json').devDependencies?.pm2 ?? ''\" 2>/dev/null)\nif [ -n \"$PM2_PIN\" ] && [ \"$PM2_PIN\" != \"$PM2_DECLARED\" ]; then\n echo \"[STEP] Moving pm2 \\${PM2_DECLARED:-(none)} → $PM2_PIN, the version this release pins\"\n if npm install --save --save-exact --prefer-online \"pm2@$PM2_PIN\"; then\n if pm2_under_systemd; then\n echo \"[WARN] PM2_RESYNC_NEEDED: pm2 is now $PM2_PIN, but its daemon still runs the old version.\"\n echo \"[WARN] Swapping it here would restart the systemd unit and kill this runner. From a shell:\"\n echo \"[WARN] cd $(dirname \"$ECOSYSTEM\") && npx pm2 update && npx pm2 list\"\n echo \"[WARN] Let it finish: interrupting it leaves selva-compute unregistered.\"\n elif ! \"$PM2\" update; then\n echo \"[WARN] PM2_RESYNC_NEEDED: 'pm2 update' failed — the daemon still runs the old pm2.\"\n echo \"[WARN] cd $(dirname \"$ECOSYSTEM\") && npx pm2 update && npx pm2 list\"\n fi\n else\n echo \"[WARN] PM2_PIN_FAILED: could not install pm2@$PM2_PIN — the previous pm2 still runs the app.\"\n echo \"[WARN] Retry from a shell: cd $(dirname \"$ECOSYSTEM\") && npx selva migrate\"\n fi\nfi\n\n# ---------------------------------------------------------------------------\n# 5. Start selva-compute with the new build.\n# ---------------------------------------------------------------------------\n# Start from ecosystem.config.cjs, NOT \\`pm2 start selva-compute\\` — the latter\n# requires selva-compute to already be in pm2's in-memory process list, which\n# a \\`pm2 update\\` (step 2) isn't guaranteed to preserve.\necho \"[STEP] Starting selva-compute with new build\"\nif ! start_app; then\n echo \"[FATAL] pm2 start failed — investigate with \\\\\\`pm2 logs selva-compute\\\\\\`\"\n exit 2\nfi\n\n# ---------------------------------------------------------------------------\n# 6. Health probe the new process.\n# ---------------------------------------------------------------------------\n# Read PORT from .env the same way scripts/update.sh does, so non-default\n# ports are respected.\nPORT=$(grep \"^PORT=\" .env 2>/dev/null \\\\\n | head -1 \\\\\n | cut -d'=' -f2 \\\\\n | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/^[\"'\"'\"']//' -e 's/[\"'\"'\"']$//' -e 's/[[:space:]]*#.*//')\nPORT=\\${PORT:-3000}\n\necho \"[STEP] Health-probing the new process on port $PORT\"\n# mktemp for the same reason as the runner itself: /tmp is shared. Without one\n# the probe still runs; only the rollback loses the body it names the cause from.\nHEALTH_BODY=$(mktemp \"\\${TMPDIR:-/tmp}/selva-health.XXXXXXXX\") || HEALTH_BODY=\nHEALTHY=0\nfor i in $(seq 1 15); do\n sleep 2\n CODE=$(curl -sS -o \"\\${HEALTH_BODY:-/dev/null}\" -w \"%{http_code}\" --max-time 5 \"http://localhost:$PORT/api/health\" 2>/dev/null || echo \"000\")\n if [ \"$CODE\" = \"200\" ]; then\n HEALTHY=1\n echo \"[INFO] Health probe passed after \\${i} attempt(s)\"\n [ -n \"$HEALTH_BODY\" ] && rm -f \"$HEALTH_BODY\"\n break\n fi\n echo \"[INFO] Probe attempt $i/15: HTTP $CODE — retrying\"\ndone\n\nif [ \"$HEALTHY\" = \"1\" ]; then\n echo \"[DONE] Update complete\"\n exit 0\nfi\n\n# ---------------------------------------------------------------------------\n# 7. Rollback path.\n# ---------------------------------------------------------------------------\necho \"[FATAL] New process failed health check after 30s\"\nif [ -s \"$HEALTH_BODY\" ]; then\n BODY=$(cat \"$HEALTH_BODY\")\n echo \"[FATAL] Last response body:\"\n echo \"$BODY\"\n\n # Name the cause before rolling back. /api/health reports WHY it is degraded\n # in a structured body, but a rollback that only prints raw JSON reads to an\n # operator as \"the update just failed\" — they retry, hit the identical\n # failure, and never learn the database is the thing that needs attention.\n # Each branch below emits a stable marker deriveOutcome keys on.\n # Match on the keys unique to each report rather than a bare \\`\"ok\":false\\`,\n # which appears in whichever sub-report failed and would misattribute one\n # cause to the other. \\`expected\\` only ever appears in schemaVersion;\n # \\`plaintextFound\\`/\\`failures\\` only in atRestSecrets.\n if echo \"$BODY\" | grep -q '\"expected\":'; then\n EXPECTED=$(echo \"$BODY\" | grep -o '\"expected\":\"[^\"]*\"' | head -1 | cut -d'\"' -f4)\n ACTUAL=$(echo \"$BODY\" | grep -o '\"actual\":\"[^\"]*\"' | head -1 | cut -d'\"' -f4)\n echo \"[FATAL] SCHEMA_SKEW: @selvajs/selva@\\${AFTER:-$LATEST} expects database migration head \\${EXPECTED:-(unknown)},\"\n echo \"[FATAL] but this database is at \\${ACTUAL:-(unavailable)}. The new version is fine — its migrations\"\n echo \"[FATAL] were never applied. Retrying the update WILL fail again in exactly the same way.\"\n echo \"[FATAL] The update does not apply migrations itself: they are not reversible, so an\"\n echo \"[FATAL] auto-migrate followed by a rollback would leave code and database on different heads.\"\n echo \"[FATAL] Apply them yourself, then re-run the update:\"\n echo \"[FATAL] cd $(dirname \"$ECOSYSTEM\")\"\n echo \"[FATAL] npm install --prefer-online @selvajs/supabase-provider@$TAG\"\n echo \"[FATAL] npx selva-supabase\"\n echo \"[FATAL] npx supabase db push\"\n echo \"[FATAL] The provider install is not optional: the migration SQL ships inside that\"\n echo \"[FATAL] package, and the update only moves @selvajs/cli and @selvajs/selva — so a sync\"\n echo \"[FATAL] without it copies 0 files and the push reports 'up to date' having done nothing.\"\n echo \"[FATAL] If db push asks for credentials, see docs/self-hosting/providers/supabase.md\"\n echo \"[FATAL] — it needs a Supabase ACCOUNT credential (supabase login, or SUPABASE_ACCESS_TOKEN),\"\n echo \"[FATAL] which is not any of the three keys in .env.\"\n elif echo \"$BODY\" | grep -qE '\"plaintextFound\":true|\"failures\":\\\\[[^]]'; then\n echo \"[FATAL] AT_REST_SECRETS: stored compute server API keys could not be decrypted under the\"\n echo \"[FATAL] current SELVA_AT_REST_KEY. This is a configuration problem on this host, not a\"\n echo \"[FATAL] fault in the new version — retrying the update will fail the same way.\"\n echo \"[FATAL] Re-enter the affected keys at /admin/compute, or restore the original\"\n echo \"[FATAL] SELVA_AT_REST_KEY, then re-run the update.\"\n else\n echo \"[FATAL] The health endpoint did not report a known cause. Inspect the body above and\"\n echo \"[FATAL] \\\\\\`pm2 logs selva-compute\\\\\\` for what the new version failed on.\"\n fi\n\n rm -f \"$HEALTH_BODY\"\nfi\n\nif [ -z \"$BEFORE\" ]; then\n echo \"[FATAL] No prior version recorded — cannot roll back automatically.\"\n echo \"[FATAL] EXIT trap will attempt to restart the current build anyway.\"\n exit 3\nfi\n\n# The failed version has already booted, so it may have rewritten stored data in\n# a format $BEFORE cannot read. Rolling back is still the better outcome; say so.\nAFTER_FORMAT=$(node -p \"require('./node_modules/@selvajs/selva/package.json').selva?.dataFormat ?? 1\" 2>/dev/null)\ncase \"$AFTER_FORMAT\" in ''|*[!0-9]*) AFTER_FORMAT=1 ;; esac\nif [ \"$AFTER_FORMAT\" -gt \"$INSTALLED_FORMAT\" ]; then\n echo \"[WARN] DATA_FORMAT_ROLLBACK: the failed version stores data format $AFTER_FORMAT; $BEFORE reads format $INSTALLED_FORMAT.\"\n echo \"[WARN] If Compute API keys fail to load after this rollback, re-enter them at /admin/compute.\"\nfi\n\necho \"[STEP] Rolling back @selvajs/selva to $BEFORE\"\n\"$PM2\" stop selva-compute >/dev/null 2>&1 || true\nwait_until_stopped >/dev/null 2>&1\n# Restore @selvajs/cli alongside the runtime: the forward step installs both at\n# the channel tag, so reverting only the runtime leaves a version pair that was\n# never released together.\nif ! npm install --save \"@selvajs/cli@$BEFORE\" \"@selvajs/selva@$BEFORE\"; then\n echo \"[FATAL] Rollback npm install failed — EXIT trap will retry restart.\"\n exit 4\nfi\n\nstart_app || true\nsleep 3\nROLLBACK_CODE=$(curl -sS -o /dev/null -w \"%{http_code}\" --max-time 5 \"http://localhost:$PORT/api/health\" 2>/dev/null || echo \"000\")\nif [ \"$ROLLBACK_CODE\" = \"200\" ]; then\n echo \"[DONE] Rolled back to $BEFORE — previous version is online\"\n exit 5\nfi\n\necho \"[FATAL] Rollback restart also failed health check (HTTP $ROLLBACK_CODE)\"\necho \"[FATAL] Manual recovery required. Check: pm2 logs selva-compute\"\nexit 6\n`;\n}\n\n// Selva self-updates as a CLI-scaffolded npm deployment: the deployment dir\n// holds a package.json that depends on @selvajs/selva, and update means\n// `npm install @selvajs/*@<tag>` + pm2 restart. Deployment-dir detection\n// (cwd-upward probe, `INSTALL_DIR` override) lives in `selfUpdate.server.ts`,\n// shared with the outcome reconciler and the log path.\nexport type UpdatePlan = { cwd: string; args: string[] };\n\n// Only the CLI and the runtime move. Provider code is bundled into\n// @selvajs/selva; @selvajs/supabase-provider carries just the migration SQL,\n// which the operator installs and pushes before updating.\n//\n// `npm install` pins to the channel's dist-tag rather than using `npm\n// update`, because `update` only ever moves FORWARD within the installed\n// semver range — it can't switch dist-tags or DOWNGRADE. Pinning to @latest /\n// @beta makes one command serve every transition: forward stable bumps,\n// beta→newer-beta, and the revert case (beta→stable lands on an older version).\n//\n// --save persists the resolved version into package.json so the next plain\n// install is reproducible; --prefer-online forces npm to revalidate cached\n// packuments against the registry — without it, npm's packument cache (5+\n// min TTL) can silently no-op right after publish.\nexport function npmInstallArgs(channel: ReleaseChannel): string[] {\n\tconst tag = channelTag(channel);\n\treturn ['install', '--save', '--prefer-online', `@selvajs/cli@${tag}`, `@selvajs/selva@${tag}`];\n}\n\nexport function detectUpdatePlan(\n\tenv: Record<string, string | undefined>,\n\tchannel: ReleaseChannel\n): UpdatePlan | null {\n\tconst dir = findDeploymentDir(env);\n\treturn dir ? { cwd: dir, args: npmInstallArgs(channel) } : null;\n}\n","import { spawn } from 'child_process';\nimport { join } from 'path';\nimport { readFileSync, writeFileSync } from 'fs';\nimport { env } from '#lib/server/env.js';\nimport { json } from '@sveltejs/kit';\nimport { actorFrom } from '@selvajs/platform';\nimport type { RequestHandler } from './$types';\nimport { requirePermission } from '#lib/server/access.server.js';\nimport { renderThrown } from '@selvajs/server/logging';\nimport { checkForUpdate } from '#lib/server/updateCheck.server.js';\nimport { readChannel, channelTag } from '#lib/server/releaseChannel.server.js';\nimport { getEventSink, getErrorReporter } from '#lib/server/providers.server.js';\nimport {\n\tfindDeploymentDir,\n\tstartUpdateOutcomeReconciler,\n\tupdateLogPath,\n\tupdateStatePath,\n\ttype PendingUpdateState\n} from '#lib/server/selfUpdate.server.js';\nimport {\n\treadRuntimeVersion,\n\tbuildLauncher,\n\tbuildNpmRunnerScript,\n\tdetectUpdatePlan\n} from '#lib/server/updateRunner.server.js';\n\n// Where the bash wrapper mirrors all script output (`updateLogPath` — in the\n// deployment dir so it survives reboots, audit O2). The SSE stream dies the\n// moment `pm2 stop selva-compute` succeeds (selva-compute IS the SSE server),\n// so the frontend loses visibility into everything that happens after — npm\n// update output, pm2 start result, health-probe results, rollback decisions.\n// The script keeps writing to this file regardless. Once the new selva-compute\n// process is back up, the frontend polls GET on this same route to fetch the\n// full log and reveal what happened during the blackout. One log per update —\n// the wrapper truncates at start, so we never carry stale content forward.\n// The runner's `[EXIT] code=N` marker in the same log also drives the\n// post-restart audit-event reconciliation (`selfUpdate.server.ts`).\n\n// Strip ANSI escape codes from terminal output\nfunction stripAnsi(str: string): string {\n\t// eslint-disable-next-line no-control-regex\n\treturn str.replace(/\\x1B\\[[0-9;]*[mGKHF]/g, '');\n}\n\n// POST - Run update and stream output via Server-Sent Events.\n//\n// Runs `npm update @selvajs/*` then restarts via ecosystem.config.cjs. The\n// runner script handles stop / update / start / health-probe / rollback with\n// an EXIT trap that keeps the app online no matter how it exits.\nexport const POST: RequestHandler = async ({ locals }) => {\n\trequirePermission(locals, 'instance_admin');\n\n\tconst channel = readChannel();\n\tconst plan = detectUpdatePlan(env, channel);\n\tif (!plan) {\n\t\treturn new Response(\n\t\t\tJSON.stringify({\n\t\t\t\terror:\n\t\t\t\t\t\"Couldn't determine how to update this deployment. \" +\n\t\t\t\t\t'Expected node_modules/@selvajs/selva (CLI scaffold) in the cwd ' +\n\t\t\t\t\t'or a parent directory.'\n\t\t\t}),\n\t\t\t{ status: 500, headers: { 'Content-Type': 'application/json' } }\n\t\t);\n\t}\n\n\t// Capture the runtime version BEFORE we touch anything, so we can:\n\t// (a) detect a no-op update and warn, (b) roll back to the prior version\n\t// if the new process fails to come up healthy.\n\tconst versionBefore = readRuntimeVersion(plan.cwd);\n\tconst actorId = locals.ctx ? actorFrom(locals.ctx) : 'system';\n\n\t// Audit trail (O2): `started` now; the terminal event is emitted by the\n\t// outcome reconciler after the app restarts (this process is killed\n\t// mid-update). The state file is the reconciler's emission token.\n\tconst pending: PendingUpdateState = {\n\t\tstartedAt: new Date().toISOString(),\n\t\tactorId,\n\t\tchannel,\n\t\tfromVersion: versionBefore\n\t};\n\ttry {\n\t\twriteFileSync(updateStatePath(plan.cwd), JSON.stringify(pending, null, '\\t'));\n\t} catch (err) {\n\t\tlocals.log.error('Could not persist pending-update state', {\n\t\t\tcomponent: 'selfUpdate',\n\t\t\terr: renderThrown(err)\n\t\t});\n\t}\n\tawait getEventSink().emit({\n\t\ttype: 'system.update.started',\n\t\tchannel,\n\t\tfromVersion: versionBefore,\n\t\tactorId\n\t});\n\n\tconst stream = new ReadableStream({\n\t\tstart(controller) {\n\t\t\tconst encoder = new TextEncoder();\n\n\t\t\tfunction sendEvent(type: string, data: Record<string, unknown>) {\n\t\t\t\tconst message = `data: ${JSON.stringify({ type, ...data })}\\n\\n`;\n\t\t\t\tcontroller.enqueue(encoder.encode(message));\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t// Prelude lines are passed to the bash wrapper rather than\n\t\t\t\t// sendEvent'd directly so they end up in both the SSE stream\n\t\t\t\t// (via bash stdout) AND the log file (via tee). Without this,\n\t\t\t\t// the frontend's blackout-recovery file fetch would clobber\n\t\t\t\t// these lines when it replaces its buffer with the file content.\n\t\t\t\tconst prelude = [\n\t\t\t\t\t`[INFO] Updating deployment (cwd: ${plan.cwd}, channel: ${channel})`,\n\t\t\t\t\t...(versionBefore ? [`[INFO] Current @selvajs/selva: ${versionBefore}`] : [])\n\t\t\t\t];\n\n\t\t\t\t// Spawn the launcher detached. The launcher writes the actual\n\t\t\t\t// runner script to disk, daemonizes it (setsid + & + exit),\n\t\t\t\t// and quits — leaving the runner with PPID=1 so PM2's tree-kill\n\t\t\t\t// of selva-compute can't reach it. See buildLauncher for the\n\t\t\t\t// full rationale.\n\t\t\t\t//\n\t\t\t\t// The runner is buildNpmRunnerScript — pre-flights the version\n\t\t\t\t// check, then stop / npm update / start / health probe /\n\t\t\t\t// rollback, with an EXIT trap that ensures the app is online no\n\t\t\t\t// matter how the script exits.\n\t\t\t\tconst runnerScript = buildNpmRunnerScript(\n\t\t\t\t\tplan.args,\n\t\t\t\t\tversionBefore,\n\t\t\t\t\tjoin(plan.cwd, 'ecosystem.config.cjs'),\n\t\t\t\t\tchannelTag(channel)\n\t\t\t\t);\n\t\t\t\tconst cmd = 'bash';\n\t\t\t\tconst args = ['-c', buildLauncher(runnerScript, updateLogPath(plan.cwd), prelude)];\n\n\t\t\t\t// Prepend the deployment's node_modules/.bin to PATH so the bash\n\t\t\t\t// script finds the project-local pm2 (and any other tooling\n\t\t\t\t// installed as a deployment dependency). Without this the script\n\t\t\t\t// inherits the SvelteKit process's PATH, which on most servers\n\t\t\t\t// doesn't include node_modules/.bin — so `pm2` resolves to\n\t\t\t\t// whatever's globally installed, or fails outright if no global\n\t\t\t\t// pm2 exists. Both are wrong: we want the project-local pm2 so\n\t\t\t\t// daemon and CLI stay aligned. Mirrors the local-only resolution\n\t\t\t\t// in @selvajs/cli's pm2Bin().\n\t\t\t\tconst localBin = join(plan.cwd, 'node_modules', '.bin');\n\t\t\t\tconst child = spawn(cmd, args, {\n\t\t\t\t\tcwd: plan.cwd,\n\t\t\t\t\tenv: {\n\t\t\t\t\t\tPATH: `${localBin}:${process.env.PATH ?? ''}`,\n\n\t\t\t\t\t\tHOME: process.env.HOME,\n\t\t\t\t\t\tINSTALL_DIR: plan.cwd\n\t\t\t\t\t},\n\t\t\t\t\tdetached: true,\n\t\t\t\t\tstdio: ['ignore', 'pipe', 'pipe']\n\t\t\t\t});\n\t\t\t\tchild.unref();\n\n\t\t\t\t// Covers the outcomes that DON'T restart this process (pre-flight\n\t\t\t\t// \"already up to date\", early failures): this process is still\n\t\t\t\t// alive to reconcile them. A real update kills this process; the\n\t\t\t\t// restarted one re-arms the reconciler from hooks.server.ts.\n\t\t\t\tstartUpdateOutcomeReconciler({\n\t\t\t\t\tdeploymentDir: plan.cwd,\n\t\t\t\t\temit: (e) => getEventSink().emit(e),\n\t\t\t\t\treport: (err) => getErrorReporter().capture(err, { tags: { origin: 'selfUpdate' } })\n\t\t\t\t});\n\n\t\t\t\t// Kill the process if it runs longer than 15 minutes.\n\t\t\t\t// The child is detached (its own process group), so signal the\n\t\t\t\t// whole group via negative pid — otherwise descendants (pnpm,\n\t\t\t\t// node, pm2) outlive the bash wrapper.\n\t\t\t\tconst timeout = setTimeout(\n\t\t\t\t\t() => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (child.pid) process.kill(-child.pid, 'SIGTERM');\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// group already gone — nothing to do\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsendEvent('log', { data: '[FATAL] Update timed out after 15 minutes' });\n\t\t\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t},\n\t\t\t\t\t15 * 60 * 1000\n\t\t\t\t);\n\n\t\t\t\t// Stream stdout\n\t\t\t\tlet restarting = false;\n\t\t\t\tchild.stdout.on('data', (data) => {\n\t\t\t\t\tconst lines = data.toString().split('\\n');\n\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\tconst clean = stripAnsi(line).trim();\n\t\t\t\t\t\tif (clean) {\n\t\t\t\t\t\t\t// Detect both stopProcessId (pm2 restart) and restartProcessId (pm2 reload)\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t!restarting &&\n\t\t\t\t\t\t\t\t(clean.includes('Applying action stopProcessId') ||\n\t\t\t\t\t\t\t\t\tclean.includes('Applying action restartProcessId'))\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\trestarting = true;\n\t\t\t\t\t\t\t\tsendEvent('restarting', { data: clean });\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tsendEvent('log', { data: clean });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Stream stderr\n\t\t\t\tchild.stderr.on('data', (data) => {\n\t\t\t\t\tconst lines = data.toString().split('\\n');\n\t\t\t\t\tfor (const line of lines) {\n\t\t\t\t\t\tconst clean = stripAnsi(line).trim();\n\t\t\t\t\t\tif (clean) {\n\t\t\t\t\t\t\tsendEvent('log', { data: `[ERROR] ${clean}` });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t// Handle process exit\n\t\t\t\tchild.on('close', (code) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tsendEvent('exit', { code: code ?? -1 });\n\t\t\t\t\tcontroller.close();\n\t\t\t\t});\n\n\t\t\t\t// Handle errors\n\t\t\t\tchild.on('error', (err) => {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t\tsendEvent('log', { data: `[FATAL] ${err.message}` });\n\t\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\t\tcontroller.close();\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tsendEvent('log', { data: `[FATAL] Failed to spawn process: ${err}` });\n\t\t\t\tsendEvent('exit', { code: -1 });\n\t\t\t\tcontroller.close();\n\t\t\t}\n\t\t}\n\t});\n\n\treturn new Response(stream, {\n\t\theaders: {\n\t\t\t'Content-Type': 'text/event-stream',\n\t\t\t'Cache-Control': 'no-cache',\n\t\t\tConnection: 'keep-alive'\n\t\t}\n\t});\n};\n\n// GET — two jobs, selected by query param:\n//\n// ?check=1 → query the npm registry and report whether a newer\n// @selvajs/selva is published. JSON: { current, latest,\n// updateAvailable }. The admin page calls this on load to show\n// an \"update available\" badge. Degrades gracefully: if the\n// registry is unreachable, latest is null and updateAvailable\n// is false (we never block the page on npm).\n//\n// (default) → read the tee'd update log so the frontend can recover the\n// chunk of output that happened during the SSE blackout (between\n// `pm2 stop` killing this process and the new selva-compute\n// coming back online). Empty body if no update has run yet.\n// Polled by the admin UI during the post-restart wait.\nexport const GET: RequestHandler = async ({ locals, url, fetch }) => {\n\trequirePermission(locals, 'instance_admin');\n\n\tif (url.searchParams.get('check') !== null) {\n\t\treturn json(await checkForUpdate(fetch, readChannel()), {\n\t\t\theaders: { 'Cache-Control': 'no-store' }\n\t\t});\n\t}\n\n\tlet body = '';\n\ttry {\n\t\tbody = readFileSync(updateLogPath(findDeploymentDir(env)), 'utf8');\n\t} catch {\n\t\t// Log doesn't exist (no update has run yet). Empty body is correct —\n\t\t// the frontend treats no content as \"nothing to show yet\".\n\t}\n\treturn new Response(body, {\n\t\theaders: {\n\t\t\t'Content-Type': 'text/plain; charset=utf-8',\n\t\t\t'Cache-Control': 'no-store'\n\t\t}\n\t});\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAaA,SAAgB,mBAAmB,KAAiC;CACnE,IAAI;EACH,MAAM,MAAM,KAAK,MAChB,aAAa,KAAK,KAAK,gBAAgB,YAAY,SAAS,cAAc,GAAG,MAAM,CACpF;EACA,OAAO,OAAO,IAAI,YAAY,WAAW,IAAI,UAAU,KAAA;CACxD,QAAQ;EACP;CACD;AACD;AAKA,SAAgB,WAAW,GAAmB;CAC7C,OAAO,IAAI,EAAE,QAAQ,MAAM,OAAO,EAAE;AACrC;AAoBA,SAAgB,cACf,cACA,SACA,UAAoB,CAAC,GACZ;CACT,MAAM,SAAS,QAAQ,KAAK,SAAS,QAAQ,WAAW,IAAI,GAAG,CAAC,CAAC,KAAK,IAAI;CAG1E,OAAO;UACE,WAAW,OAAO,EAAE;;;;;;;;;;;;;;;;EAgB5B,aAAa;;;;;EAKb,OAAO;;;;;;;;;;;;;;;;;AAiBT;AAyBA,SAAgB,qBACf,SACA,eACA,eACA,KACS;CACT,MAAM,aAAa,CAAC,OAAO,GAAG,OAAO,CAAC,CAAC,IAAI,UAAU,CAAC,CAAC,KAAK,GAAG;CAY/D,OAAO;;SATQ,WAAW,iBAAiB,EAWnC,EAAO;YAVG,WAAW,aAWlB,EAAU;MALL,WAA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GAGD,MAAM,GAAG,UAAU,QAAQ;IAC1B,aAAa,OAAO;IACpB,UAAU,OAAO,EAAE,MAAM,WAAW,IAAI,UAAU,CAAC;IACnD,UAAU,QAAQ,EAAE,MAAM,GAAG,CAAC;IAC9B,WAAW,MAAM;GAClB,CAAC;EACF,SAAS,KAAK;GACb,UAAU,OAAO,EAAE,MAAM,oCAAoC,MAAM,CAAC;GACpE,UAAU,QAAQ,EAAE,MAAM,GAAG,CAAC;GAC9B,WAAW,MAAM;EAClB;CACD,EACD,CAAC;CAED,OAAO,IAAI,SAAS,QAAQ,EAC3B,SAAS;EACR,gBAAgB;EAChB,iBAAiB;EACjB,YAAY;CACb,EACD,CAAC;AACF;AAgBA,IAAa,MAAsB,OAAO,EAAE,QAAQ,KAAK,YAAY;CACpE,kBAAkB,QAAQ,gBAAgB;CAE1C,IAAI,IAAI,aAAa,IAAI,OAAO,MAAM,MACrC,OAAO,KAAK,MAAM,eAAe,OAAO,YAAY,CAAC,GAAG,EACvD,SAAS,EAAE,iBAAiB,WAAW,EACxC,CAAC;CAGF,IAAI,OAAO;CACX,IAAI;EACH,OAAOC,eAAa,cAAc,kBAAkB,GAAG,CAAC,GAAG,MAAM;CAClE,QAAQ,CAGR;CACA,OAAO,IAAI,SAAS,MAAM,EACzB,SAAS;EACR,gBAAgB;EAChB,iBAAiB;CAClB,EACD,CAAC;AACF"}
@@ -1,13 +1,13 @@
1
- import { U as actorFrom, g as getPermissionStore, o as getDataProvider, r as getAuthProvider, u as getEventSink } from "../../../../../../chunks/providers.server.js";
1
+ import { K as actorFrom, g as getPermissionStore, o as getDataProvider, r as getAuthProvider, u as getEventSink } from "../../../../../../chunks/providers.server.js";
2
2
  import { b as requireManageInstanceUsers, k as ApiErrorCode, r as assertCanGrantPlatformPermissions } from "../../../../../../chunks/access.js";
3
3
  import { t as SYSTEM_CONTEXT } from "../../../../../../chunks/context.js";
4
- import { H as requireParams, R as parseBody } from "../../../../../../chunks/api.js";
4
+ import { U as requireParams, z as parseBody } from "../../../../../../chunks/api.js";
5
5
  import { r as PlatformPermissionSchema } from "../../../../../../chunks/types3.js";
6
6
  import { t as apiError } from "../../../../../../chunks/api-errors.js";
7
7
  import "../../../../../../chunks/access2.server.js";
8
8
  import { r as noContent, t as apiRoute } from "../../../../../../chunks/http2.js";
9
9
  import { t as setUserPlatformPermissions } from "../../../../../../chunks/permissions.server.js";
10
- import { n as requireEnabledToBecomeAdmin, r as requireNotSoleOrgOwner, t as requireCanRemoveInstanceAdmin } from "../../../../../../chunks/instanceAdmins.server.js";
10
+ import { n as requireEnabledToBecomeAdmin, r as withSoleOwnerGuard, t as requireCanRemoveInstanceAdmin } from "../../../../../../chunks/instanceAdmins.server.js";
11
11
  import { n as apiTokenResolutions } from "../../../../../../chunks/token2.server.js";
12
12
  import { z } from "zod";
13
13
  // src/routes/api/admin/users/[id]/+server.ts
@@ -28,23 +28,49 @@ var PATCH = apiRoute("Failed to update platform permissions", async ({ params, r
28
28
  var DELETE = apiRoute("Failed to delete user", async ({ params, locals }) => {
29
29
  requireManageInstanceUsers(locals);
30
30
  const { id } = requireParams(params, "id");
31
- const { targetIsAdmin } = await requireCanRemoveInstanceAdmin(locals.ctx, id, "delete");
32
- await requireNotSoleOrgOwner(id);
33
- const priorPermissions = await getPermissionStore().getFor(locals.ctx, id);
34
- if (targetIsAdmin) {
35
- if (await setUserPlatformPermissions(locals.ctx, id, []) === "last_admin") apiError(409, ApiErrorCode.CONFLICT, "Cannot delete the last instance admin. Promote another user to instance admin first.");
36
- }
37
- const email = (await getAuthProvider().getUser(id))?.email;
38
- const result = await getAuthProvider().deleteUser(id);
39
- if (targetIsAdmin && result !== "ok") await setUserPlatformPermissions(locals.ctx, id, priorPermissions);
40
- if (result === "not_found") apiError(404, ApiErrorCode.NOT_FOUND, "User not found");
41
- if (result === "not_supported") apiError(501, ApiErrorCode.INTERNAL, "User deletion not supported by this auth provider");
42
- await getDataProvider().onUserDeleted(SYSTEM_CONTEXT, id, { email });
31
+ const ctx = locals.ctx;
32
+ const { targetIsAdmin } = await requireCanRemoveInstanceAdmin(ctx, id, "delete");
33
+ const target = await withSoleOwnerGuard(id, async () => {
34
+ const target = await getAuthProvider().getUser(id);
35
+ if (!target) apiError(404, ApiErrorCode.NOT_FOUND, "User not found");
36
+ const priorPermissions = await getPermissionStore().getFor(ctx, id);
37
+ if (targetIsAdmin) {
38
+ if (await setUserPlatformPermissions(ctx, id, []) === "last_admin") apiError(409, ApiErrorCode.CONFLICT, "Cannot delete the last instance admin. Promote another user to instance admin first.");
39
+ }
40
+ const restoreAdmin = async () => {
41
+ if (!targetIsAdmin) return;
42
+ await getDataProvider().ensureUser(SYSTEM_CONTEXT, id);
43
+ await setUserPlatformPermissions(ctx, id, priorPermissions);
44
+ };
45
+ apiTokenResolutions.forgetUser(id);
46
+ try {
47
+ await getDataProvider().onUserDeleted(SYSTEM_CONTEXT, id, { email: target.email });
48
+ } catch (err) {
49
+ await restoreAdmin().catch(() => {});
50
+ throw err;
51
+ }
52
+ const result = await getAuthProvider().deleteUser(id).catch(async (err) => {
53
+ await restoreAdmin().catch(() => {});
54
+ throw err;
55
+ });
56
+ if (result !== "ok") await restoreAdmin().catch(() => {});
57
+ if (result === "not_found") apiError(404, ApiErrorCode.NOT_FOUND, "User not found");
58
+ if (result === "not_supported") apiError(501, ApiErrorCode.INTERNAL, "User deletion not supported by this auth provider");
59
+ return target;
60
+ });
43
61
  apiTokenResolutions.forgetUser(id);
62
+ try {
63
+ await getDataProvider().onUserDeleted(SYSTEM_CONTEXT, id, { email: target.email });
64
+ } catch (err) {
65
+ locals.log.error("User deleted, but the second erasure pass failed", {
66
+ userId: id,
67
+ error: err instanceof Error ? err.message : String(err)
68
+ });
69
+ }
44
70
  await getEventSink().emit({
45
71
  type: "user.deleted",
46
72
  userId: id,
47
- actorId: actorFrom(locals.ctx)
73
+ actorId: actorFrom(ctx)
48
74
  });
49
75
  return noContent();
50
76
  });
@@ -1 +1 @@
1
- {"version":3,"file":"_server.ts.js","names":[],"sources":["../../../../../../../../src/routes/api/admin/users/[id]/+server.ts"],"sourcesContent":["import type { RequestHandler } from './$types';\nimport { z } from 'zod';\nimport { getAuthProvider } from '#lib/server/providers.server.js';\nimport { getDataProvider, getEventSink, getPermissionStore } from '#lib/server/providers.server.js';\nimport {\n\tassertCanGrantPlatformPermissions,\n\trequireManageInstanceUsers\n} from '#lib/server/access.server.js';\nimport {\n\trequireCanRemoveInstanceAdmin,\n\trequireEnabledToBecomeAdmin,\n\trequireNotSoleOrgOwner\n} from '#lib/server/admin/instanceAdmins.server.js';\nimport { apiError, ApiErrorCode } from '#lib/server/api-errors.js';\nimport { apiRoute, noContent, parseBody, requireParams } from '#lib/server/api/http.js';\nimport {\n\tPlatformPermissionSchema,\n\tSYSTEM_CONTEXT,\n\ttype PlatformPermission,\n\tactorFrom\n} from '@selvajs/platform';\nimport { setUserPlatformPermissions } from '#lib/server/permissions.server.js';\nimport { apiTokenResolutions } from '#lib/server/apiTokens/token.server.js';\n\nconst UpdatePermissionsBody = z.object({\n\tpermissions: z.array(PlatformPermissionSchema)\n});\n\n// Platform scope only. Org role and permissions belong to\n// PATCH /api/v1/orgs/{orgId}/members/{userId}, which gates on\n// manage_org_members and enforces the sole-owner invariant — neither of which\n// this handler's manage_instance_users check can stand in for.\nexport const PATCH: RequestHandler = apiRoute(\n\t'Failed to update platform permissions',\n\tasync ({ params, request, locals }) => {\n\t\trequireManageInstanceUsers(locals);\n\t\tconst { id } = requireParams(params, 'id');\n\n\t\tconst { permissions: platform } = await parseBody(request, UpdatePermissionsBody);\n\n\t\tconst existingPlatform: PlatformPermission[] = await getPermissionStore().getFor(\n\t\t\tlocals.ctx!,\n\t\t\tid\n\t\t);\n\t\tassertCanGrantPlatformPermissions(locals.ctx!, platform, existingPlatform);\n\t\tawait requireEnabledToBecomeAdmin(id, platform, existingPlatform);\n\n\t\tconst platformResult = await setUserPlatformPermissions(locals.ctx!, id, platform);\n\t\tif (platformResult === 'not_found') apiError(404, ApiErrorCode.NOT_FOUND, 'User not found');\n\t\tif (platformResult === 'not_supported')\n\t\t\tapiError(\n\t\t\t\t501,\n\t\t\t\tApiErrorCode.INTERNAL,\n\t\t\t\t'Platform permission updates not supported by this auth provider'\n\t\t\t);\n\t\tif (platformResult === 'last_admin')\n\t\t\tapiError(\n\t\t\t\t409,\n\t\t\t\tApiErrorCode.CONFLICT,\n\t\t\t\t'Cannot remove the last instance admin. Promote another user to instance admin first.'\n\t\t\t);\n\n\t\treturn noContent();\n\t}\n);\n\n// DELETE — remove user. The §2 sole-`instance_admin` invariant and the\n// platform-scope caller check are enforced here, BEFORE the auth provider\n// deletes, by consulting the permission store (the auth provider no longer\n// owns Selva-specific authorization).\nexport const DELETE: RequestHandler = apiRoute(\n\t'Failed to delete user',\n\tasync ({ params, locals }) => {\n\t\trequireManageInstanceUsers(locals);\n\t\tconst { id } = requireParams(params, 'id');\n\n\t\tconst { targetIsAdmin } = await requireCanRemoveInstanceAdmin(locals.ctx!, id, 'delete');\n\t\tawait requireNotSoleOrgOwner(id);\n\n\t\t// The check above reads, then this writes: `set` is the atomic step, so two\n\t\t// admins deleting each other cannot both get past it.\n\t\tconst priorPermissions = await getPermissionStore().getFor(locals.ctx!, id);\n\t\tif (targetIsAdmin) {\n\t\t\tconst revoked = await setUserPlatformPermissions(locals.ctx!, id, []);\n\t\t\tif (revoked === 'last_admin') {\n\t\t\t\tapiError(\n\t\t\t\t\t409,\n\t\t\t\t\tApiErrorCode.CONFLICT,\n\t\t\t\t\t'Cannot delete the last instance admin. Promote another user to instance admin first.'\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t// Capture the email BEFORE deletion — `onUserDeleted` needs it to scrub\n\t\t// invite/audit rows keyed by email, but the auth user is gone by then.\n\t\tconst target = await getAuthProvider().getUser(id);\n\t\tconst email = target?.email;\n\n\t\tconst result = await getAuthProvider().deleteUser(id);\n\t\tif (targetIsAdmin && result !== 'ok') {\n\t\t\tawait setUserPlatformPermissions(locals.ctx!, id, priorPermissions);\n\t\t}\n\t\tif (result === 'not_found') apiError(404, ApiErrorCode.NOT_FOUND, 'User not found');\n\t\tif (result === 'not_supported')\n\t\t\tapiError(501, ApiErrorCode.INTERNAL, 'User deletion not supported by this auth provider');\n\n\t\t// Cascade + erasure: drop the user-data row and scrub personal data not\n\t\t// reachable by FK cascade (audit rows, invites-by-email, solve telemetry).\n\t\t// Supabase erases those explicitly; local removes its JSON rows + memberships.\n\t\tawait getDataProvider().onUserDeleted(SYSTEM_CONTEXT, id, { email });\n\t\tapiTokenResolutions.forgetUser(id);\n\n\t\t// Emitted after the erasure pass, which deletes audit rows this user\n\t\t// authored — emitting first would delete the row recording their deletion.\n\t\t// The actor is the admin, so the row itself survives.\n\t\tawait getEventSink().emit({\n\t\t\ttype: 'user.deleted',\n\t\t\tuserId: id,\n\t\t\tactorId: actorFrom(locals.ctx!)\n\t\t});\n\n\t\treturn noContent();\n\t}\n);\n"],"mappings":";;;;;;;;;;;;;AAwBA,IAAM,wBAAwB,EAAE,OAAO,EACtC,aAAa,EAAE,MAAM,wBAAwB,EAC9C,CAAC;AAMD,IAAa,QAAwB,SACpC,yCACA,OAAO,EAAE,QAAQ,SAAS,aAAa;CACtC,2BAA2B,MAAM;CACjC,MAAM,EAAE,OAAO,cAAc,QAAQ,IAAI;CAEzC,MAAM,EAAE,aAAa,aAAa,MAAM,UAAU,SAAS,qBAAqB;CAEhF,MAAM,mBAAyC,MAAM,mBAAmB,CAAC,CAAC,OACzE,OAAO,KACP,EACD;CACA,kCAAkC,OAAO,KAAM,UAAU,gBAAgB;CACzE,MAAM,4BAA4B,IAAI,UAAU,gBAAgB;CAEhE,MAAM,iBAAiB,MAAM,2BAA2B,OAAO,KAAM,IAAI,QAAQ;CACjF,IAAI,mBAAmB,aAAa,SAAS,KAAK,aAAa,WAAW,gBAAgB;CAC1F,IAAI,mBAAmB,iBACtB,SACC,KACA,aAAa,UACb,iEACD;CACD,IAAI,mBAAmB,cACtB,SACC,KACA,aAAa,UACb,sFACD;CAED,OAAO,UAAU;AAClB,CACD;AAMA,IAAa,SAAyB,SACrC,yBACA,OAAO,EAAE,QAAQ,aAAa;CAC7B,2BAA2B,MAAM;CACjC,MAAM,EAAE,OAAO,cAAc,QAAQ,IAAI;CAEzC,MAAM,EAAE,kBAAkB,MAAM,8BAA8B,OAAO,KAAM,IAAI,QAAQ;CACvF,MAAM,uBAAuB,EAAE;CAI/B,MAAM,mBAAmB,MAAM,mBAAmB,CAAC,CAAC,OAAO,OAAO,KAAM,EAAE;CAC1E,IAAI,eAEC;MAAA,MADkB,2BAA2B,OAAO,KAAM,IAAI,CAAC,CAAC,MACpD,cACf,SACC,KACA,aAAa,UACb,sFACD;CAAA;CAOF,MAAM,SAAQ,MADO,gBAAgB,CAAC,CAAC,QAAQ,EAAE,EAAA,EAC3B;CAEtB,MAAM,SAAS,MAAM,gBAAgB,CAAC,CAAC,WAAW,EAAE;CACpD,IAAI,iBAAiB,WAAW,MAC/B,MAAM,2BAA2B,OAAO,KAAM,IAAI,gBAAgB;CAEnE,IAAI,WAAW,aAAa,SAAS,KAAK,aAAa,WAAW,gBAAgB;CAClF,IAAI,WAAW,iBACd,SAAS,KAAK,aAAa,UAAU,mDAAmD;CAKzF,MAAM,gBAAgB,CAAC,CAAC,cAAc,gBAAgB,IAAI,EAAE,MAAM,CAAC;CACnE,oBAAoB,WAAW,EAAE;CAKjC,MAAM,aAAa,CAAC,CAAC,KAAK;EACzB,MAAM;EACN,QAAQ;EACR,SAAS,UAAU,OAAO,GAAI;CAC/B,CAAC;CAED,OAAO,UAAU;AAClB,CACD"}
1
+ {"version":3,"file":"_server.ts.js","names":[],"sources":["../../../../../../../../src/routes/api/admin/users/[id]/+server.ts"],"sourcesContent":["import type { RequestHandler } from './$types';\nimport { z } from 'zod';\nimport { getAuthProvider } from '#lib/server/providers.server.js';\nimport { getDataProvider, getEventSink, getPermissionStore } from '#lib/server/providers.server.js';\nimport {\n\tassertCanGrantPlatformPermissions,\n\trequireManageInstanceUsers\n} from '#lib/server/access.server.js';\nimport {\n\trequireCanRemoveInstanceAdmin,\n\trequireEnabledToBecomeAdmin,\n\twithSoleOwnerGuard\n} from '#lib/server/admin/instanceAdmins.server.js';\nimport { apiError, ApiErrorCode } from '#lib/server/api-errors.js';\nimport { apiRoute, noContent, parseBody, requireParams } from '#lib/server/api/http.js';\nimport {\n\tPlatformPermissionSchema,\n\tSYSTEM_CONTEXT,\n\ttype PlatformPermission,\n\tactorFrom\n} from '@selvajs/platform';\nimport { setUserPlatformPermissions } from '#lib/server/permissions.server.js';\nimport { apiTokenResolutions } from '#lib/server/apiTokens/token.server.js';\n\nconst UpdatePermissionsBody = z.object({\n\tpermissions: z.array(PlatformPermissionSchema)\n});\n\n// Platform scope only. Org role and permissions belong to\n// PATCH /api/v1/orgs/{orgId}/members/{userId}, which gates on\n// manage_org_members and enforces the sole-owner invariant — neither of which\n// this handler's manage_instance_users check can stand in for.\nexport const PATCH: RequestHandler = apiRoute(\n\t'Failed to update platform permissions',\n\tasync ({ params, request, locals }) => {\n\t\trequireManageInstanceUsers(locals);\n\t\tconst { id } = requireParams(params, 'id');\n\n\t\tconst { permissions: platform } = await parseBody(request, UpdatePermissionsBody);\n\n\t\tconst existingPlatform: PlatformPermission[] = await getPermissionStore().getFor(\n\t\t\tlocals.ctx!,\n\t\t\tid\n\t\t);\n\t\tassertCanGrantPlatformPermissions(locals.ctx!, platform, existingPlatform);\n\t\tawait requireEnabledToBecomeAdmin(id, platform, existingPlatform);\n\n\t\tconst platformResult = await setUserPlatformPermissions(locals.ctx!, id, platform);\n\t\tif (platformResult === 'not_found') apiError(404, ApiErrorCode.NOT_FOUND, 'User not found');\n\t\tif (platformResult === 'not_supported')\n\t\t\tapiError(\n\t\t\t\t501,\n\t\t\t\tApiErrorCode.INTERNAL,\n\t\t\t\t'Platform permission updates not supported by this auth provider'\n\t\t\t);\n\t\tif (platformResult === 'last_admin')\n\t\t\tapiError(\n\t\t\t\t409,\n\t\t\t\tApiErrorCode.CONFLICT,\n\t\t\t\t'Cannot remove the last instance admin. Promote another user to instance admin first.'\n\t\t\t);\n\n\t\treturn noContent();\n\t}\n);\n\n// DELETE — remove user. The §2 sole-`instance_admin` invariant and the\n// platform-scope caller check are enforced here, BEFORE the auth provider\n// deletes, by consulting the permission store (the auth provider no longer\n// owns Selva-specific authorization).\nexport const DELETE: RequestHandler = apiRoute(\n\t'Failed to delete user',\n\tasync ({ params, locals }) => {\n\t\trequireManageInstanceUsers(locals);\n\t\tconst { id } = requireParams(params, 'id');\n\n\t\tconst ctx = locals.ctx!;\n\t\tconst { targetIsAdmin } = await requireCanRemoveInstanceAdmin(ctx, id, 'delete');\n\n\t\tconst target = await withSoleOwnerGuard(id, async () => {\n\t\t\t// The email first: erasure scrubs invite and audit rows by it.\n\t\t\tconst target = await getAuthProvider().getUser(id);\n\t\t\tif (!target) apiError(404, ApiErrorCode.NOT_FOUND, 'User not found');\n\n\t\t\t// The check above reads, then this writes: `set` is the atomic step, so two\n\t\t\t// admins deleting each other cannot both get past it.\n\t\t\tconst priorPermissions = await getPermissionStore().getFor(ctx, id);\n\t\t\tif (targetIsAdmin) {\n\t\t\t\tconst revoked = await setUserPlatformPermissions(ctx, id, []);\n\t\t\t\tif (revoked === 'last_admin') {\n\t\t\t\t\tapiError(\n\t\t\t\t\t\t409,\n\t\t\t\t\t\tApiErrorCode.CONFLICT,\n\t\t\t\t\t\t'Cannot delete the last instance admin. Promote another user to instance admin first.'\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// A delete that did not happen must not cost the target their grant. The\n\t\t\t// erasure pass may already have dropped their data row, hence `ensureUser`.\n\t\t\tconst restoreAdmin = async () => {\n\t\t\t\tif (!targetIsAdmin) return;\n\t\t\t\tawait getDataProvider().ensureUser(SYSTEM_CONTEXT, id);\n\t\t\t\tawait setUserPlatformPermissions(ctx, id, priorPermissions);\n\t\t\t};\n\n\t\t\t// Erasure before the identity, so a failed store write can be retried: with\n\t\t\t// the identity gone, a retry stops at 404 and the data stays.\n\t\t\t// Supabase erases what FK cascade does not reach (audit rows, invites by\n\t\t\t// email, solve telemetry); local removes its JSON rows and memberships.\n\t\t\tapiTokenResolutions.forgetUser(id);\n\t\t\ttry {\n\t\t\t\tawait getDataProvider().onUserDeleted(SYSTEM_CONTEXT, id, { email: target.email });\n\t\t\t} catch (err) {\n\t\t\t\tawait restoreAdmin().catch(() => {});\n\t\t\t\tthrow err;\n\t\t\t}\n\n\t\t\tconst result = await getAuthProvider()\n\t\t\t\t.deleteUser(id)\n\t\t\t\t.catch(async (err: unknown) => {\n\t\t\t\t\tawait restoreAdmin().catch(() => {});\n\t\t\t\t\tthrow err;\n\t\t\t\t});\n\t\t\tif (result !== 'ok') await restoreAdmin().catch(() => {});\n\t\t\tif (result === 'not_found') apiError(404, ApiErrorCode.NOT_FOUND, 'User not found');\n\t\t\tif (result === 'not_supported')\n\t\t\t\tapiError(501, ApiErrorCode.INTERNAL, 'User deletion not supported by this auth provider');\n\t\t\treturn target;\n\t\t});\n\n\t\t// The target could still authenticate during the first pass: local's\n\t\t// `ensureUser` recreates their row, a token request re-caches its resolution,\n\t\t// and they can author audit and solve rows. This pass removes those. The\n\t\t// identity is gone, so a 500 here could not be retried; the log is the signal.\n\t\tapiTokenResolutions.forgetUser(id);\n\t\ttry {\n\t\t\tawait getDataProvider().onUserDeleted(SYSTEM_CONTEXT, id, { email: target.email });\n\t\t} catch (err) {\n\t\t\tlocals.log.error('User deleted, but the second erasure pass failed', {\n\t\t\t\tuserId: id,\n\t\t\t\terror: err instanceof Error ? err.message : String(err)\n\t\t\t});\n\t\t}\n\n\t\t// After both erasure passes, which delete audit rows this user authored.\n\t\t// The actor is the admin, so the row itself survives.\n\t\tawait getEventSink().emit({ type: 'user.deleted', userId: id, actorId: actorFrom(ctx) });\n\n\t\treturn noContent();\n\t}\n);\n"],"mappings":";;;;;;;;;;;;;AAwBA,IAAM,wBAAwB,EAAE,OAAO,EACtC,aAAa,EAAE,MAAM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C,WAAW,gBAAgB,EAAE;GACrD,MAAM,2BAA2B,KAAK,IAAI,gBAAgB;EAC3D;EAMA,oBAAoB,WAAW,EAAE;EACjC,IAAI;GACH,MAAM,gBAAgB,CAAC,CAAC,cAAc,gBAAgB,IAAI,EAAE,OAAO,OAAO,MAAM,CAAC;EAClF,SAAS,KAAK;GACb,MAAM,aAAa,CAAC,CAAC,YAAY,CAAC,CAAC;GACnC,MAAM;EACP;EAEA,MAAM,SAAS,MAAM,gBAAgB,CAAC,CACpC,WAAW,EAAE,CAAC,CACd,MAAM,OAAO,QAAiB;GAC9B,MAAM,aAAa,CAAC,CAAC,YAAY,CAAC,CAAC;GACnC,MAAM;EACP,CAAC;EACF,IAAI,WAAW,MAAM,MAAM,aAAa,CAAC,CAAC,YAAY,CAAC,CAAC;EACxD,IAAI,WAAW,aAAa,SAAS,KAAK,aAAa,WAAW,gBAAgB;EAClF,IAAI,WAAW,iBACd,SAAS,KAAK,aAAa,UAAU,mDAAmD;EACzF,OAAO;CACR,CAAC;CAMD,oBAAoB,WAAW,EAAE;CACjC,IAAI;EACH,MAAM,gBAAgB,CAAC,CAAC,cAAc,gBAAgB,IAAI,EAAE,OAAO,OAAO,MAAM,CAAC;CAClF,SAAS,KAAK;EACb,OAAO,IAAI,MAAM,oDAAoD;GACpE,QAAQ;GACR,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;EACvD,CAAC;CACF;CAIA,MAAM,aAAa,CAAC,CAAC,KAAK;EAAE,MAAM;EAAgB,QAAQ;EAAI,SAAS,UAAU,GAAG;CAAE,CAAC;CAEvF,OAAO,UAAU;AAClB,CACD"}
@@ -1,12 +1,12 @@
1
- import { T as providers, U as actorFrom, r as getAuthProvider, u as getEventSink } from "../../../../../../../chunks/providers.server.js";
1
+ import { K as actorFrom, T as providers, g as getPermissionStore, r as getAuthProvider, u as getEventSink } from "../../../../../../../chunks/providers.server.js";
2
2
  import { b as requireManageInstanceUsers, k as ApiErrorCode } from "../../../../../../../chunks/access.js";
3
- import { H as requireParams } from "../../../../../../../chunks/api.js";
4
- import { J as revokeUserApiTokens } from "../../../../../../../chunks/handlers.js";
3
+ import { U as requireParams } from "../../../../../../../chunks/api.js";
4
+ import { X as revokeUserApiTokens } from "../../../../../../../chunks/handlers.js";
5
5
  import { t as apiError } from "../../../../../../../chunks/api-errors.js";
6
6
  import "../../../../../../../chunks/access2.server.js";
7
7
  import { r as noContent, t as apiRoute } from "../../../../../../../chunks/http2.js";
8
8
  import { t as setUserPlatformPermissions } from "../../../../../../../chunks/permissions.server.js";
9
- import { t as requireCanRemoveInstanceAdmin } from "../../../../../../../chunks/instanceAdmins.server.js";
9
+ import { r as withSoleOwnerGuard, t as requireCanRemoveInstanceAdmin } from "../../../../../../../chunks/instanceAdmins.server.js";
10
10
  import { n as apiTokenResolutions } from "../../../../../../../chunks/token2.server.js";
11
11
  // src/routes/api/admin/users/[id]/disable/+server.ts
12
12
  /**
@@ -33,19 +33,30 @@ import { n as apiTokenResolutions } from "../../../../../../../chunks/token2.ser
33
33
  var POST = apiRoute("Failed to disable user", async ({ params, locals }) => {
34
34
  requireManageInstanceUsers(locals);
35
35
  const { id } = requireParams(params, "id");
36
- const { targetIsAdmin } = await requireCanRemoveInstanceAdmin(locals.ctx, id, "disable");
37
- if (targetIsAdmin) {
38
- if (await setUserPlatformPermissions(locals.ctx, id, []) === "last_admin") apiError(409, ApiErrorCode.CONFLICT, "Cannot disable the last instance admin. Promote another user to instance admin first.");
39
- }
40
- const result = await getAuthProvider().disableUser(id);
41
- if (result === "not_found") apiError(404, ApiErrorCode.NOT_FOUND, "User not found");
42
- if (result === "not_supported") apiError(501, ApiErrorCode.INTERNAL, "Disabling users is not supported by this auth provider");
36
+ const ctx = locals.ctx;
37
+ const { targetIsAdmin } = await requireCanRemoveInstanceAdmin(ctx, id, "disable");
38
+ await withSoleOwnerGuard(id, async () => {
39
+ const priorPermissions = await getPermissionStore().getFor(ctx, id);
40
+ if (targetIsAdmin) {
41
+ if (await setUserPlatformPermissions(ctx, id, []) === "last_admin") apiError(409, ApiErrorCode.CONFLICT, "Cannot disable the last instance admin. Promote another user to instance admin first.");
42
+ }
43
+ const restoreAdmin = async () => {
44
+ if (targetIsAdmin) await setUserPlatformPermissions(ctx, id, priorPermissions);
45
+ };
46
+ const result = await getAuthProvider().disableUser(id).catch(async (err) => {
47
+ await restoreAdmin().catch(() => {});
48
+ throw err;
49
+ });
50
+ if (result !== "ok") await restoreAdmin().catch(() => {});
51
+ if (result === "not_found") apiError(404, ApiErrorCode.NOT_FOUND, "User not found");
52
+ if (result === "not_supported") apiError(501, ApiErrorCode.INTERNAL, "Disabling users is not supported by this auth provider");
53
+ });
43
54
  await getEventSink().emit({
44
55
  type: "user.disabled",
45
56
  userId: id,
46
- actorId: actorFrom(locals.ctx)
57
+ actorId: actorFrom(ctx)
47
58
  });
48
- await revokeUserApiTokens(providers.data.apiTokens, locals.ctx, id, {
59
+ await revokeUserApiTokens(providers.data.apiTokens, ctx, id, {
49
60
  reason: "user_disabled",
50
61
  resolutionCache: apiTokenResolutions
51
62
  }, locals.log);
@@ -1 +1 @@
1
- {"version":3,"file":"_server.ts.js","names":[],"sources":["../../../../../../../../../src/routes/api/admin/users/[id]/disable/+server.ts"],"sourcesContent":["import type { RequestHandler } from './$types';\nimport { apiError, ApiErrorCode } from '#lib/server/api-errors.js';\nimport { apiRoute, noContent, requireParams } from '#lib/server/api/http.js';\nimport { getAuthProvider, providers } from '#lib/server/providers.server.js';\nimport { revokeUserApiTokens } from '@selvajs/server/handlers';\nimport { apiTokenResolutions } from '#lib/server/apiTokens/token.server.js';\nimport { requireManageInstanceUsers } from '#lib/server/access.server.js';\nimport { requireCanRemoveInstanceAdmin } from '#lib/server/admin/instanceAdmins.server.js';\nimport { setUserPlatformPermissions } from '#lib/server/permissions.server.js';\nimport { getEventSink } from '#lib/server/providers.server.js';\nimport { actorFrom } from '@selvajs/platform';\n\n/**\n * POST /api/admin/users/[id]/disable\n *\n * docs/contributing/permissions.md §10 — disable preserves identity and attribution. The §2\n * sole-`instance_admin` invariant is enforced here BEFORE the auth provider\n * disables, by consulting\n * `IPlatformPermissionStore.countInstanceAdminsExcluding`. Auth providers no\n * longer own Selva-specific authorization.\n *\n * Cutoff is not instant on every provider, and this route cannot make it so:\n * `sessionRefresh.revokeSession` takes the target's session token, which an\n * admin disabling someone else does not hold. Local and header-auth re-read the\n * user each request, so they cut off on the next one. Supabase keeps accepting\n * an already-issued access token until `revalidateMs` (default 60s) — but its\n * `refreshSession` rejects disabled users, so nothing new can be minted and the\n * window is bounded by the access token's own lifetime, not the 30-day refresh\n * token.\n *\n * No matching enable endpoint today — the auth interface is one-way for v1.\n * Re-enable lands when the spec defines an explicit re-onboarding flow.\n */\nexport const POST: RequestHandler = apiRoute(\n\t'Failed to disable user',\n\tasync ({ params, locals }) => {\n\t\trequireManageInstanceUsers(locals);\n\t\tconst { id } = requireParams(params, 'id');\n\n\t\tconst { targetIsAdmin } = await requireCanRemoveInstanceAdmin(locals.ctx!, id, 'disable');\n\n\t\t// Revoke before disabling. The local permission store cannot see the\n\t\t// disabled flag (it lives in the auth provider's file), so a disabled admin\n\t\t// still counts as live there — disable two admins in a row and the instance\n\t\t// reaches zero enabled admins with both checks having passed.\n\t\t//\n\t\t// Re-enabling does not restore the grant; an admin re-assigns it.\n\t\tif (targetIsAdmin) {\n\t\t\tconst revoked = await setUserPlatformPermissions(locals.ctx!, id, []);\n\t\t\tif (revoked === 'last_admin') {\n\t\t\t\tapiError(\n\t\t\t\t\t409,\n\t\t\t\t\tApiErrorCode.CONFLICT,\n\t\t\t\t\t'Cannot disable the last instance admin. Promote another user to instance admin first.'\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tconst result = await getAuthProvider().disableUser(id);\n\t\tif (result === 'not_found') apiError(404, ApiErrorCode.NOT_FOUND, 'User not found');\n\t\tif (result === 'not_supported')\n\t\t\tapiError(\n\t\t\t\t501,\n\t\t\t\tApiErrorCode.INTERNAL,\n\t\t\t\t'Disabling users is not supported by this auth provider'\n\t\t\t);\n\n\t\tawait getEventSink().emit({\n\t\t\ttype: 'user.disabled',\n\t\t\tuserId: id,\n\t\t\tactorId: actorFrom(locals.ctx!)\n\t\t});\n\n\t\tawait revokeUserApiTokens(\n\t\t\tproviders.data.apiTokens,\n\t\t\tlocals.ctx!,\n\t\t\tid,\n\t\t\t{ reason: 'user_disabled', resolutionCache: apiTokenResolutions },\n\t\t\tlocals.log\n\t\t);\n\n\t\treturn noContent();\n\t}\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,IAAa,OAAuB,SACnC,0BACA,OAAO,EAAE,QAAQ,aAAa;CAC7B,2BAA2B,MAAM;CACjC,MAAM,EAAE,OAAO,cAAc,QAAQ,IAAI;CAEzC,MAAM,EAAE,kBAAkB,MAAM,8BAA8B,OAAO,KAAM,IAAI,SAAS;CAQxF,IAAI,eAEC;MAAA,MADkB,2BAA2B,OAAO,KAAM,IAAI,CAAC,CAAC,MACpD,cACf,SACC,KACA,aAAa,UACb,uFACD;CAAA;CAIF,MAAM,SAAS,MAAM,gBAAgB,CAAC,CAAC,YAAY,EAAE;CACrD,IAAI,WAAW,aAAa,SAAS,KAAK,aAAa,WAAW,gBAAgB;CAClF,IAAI,WAAW,iBACd,SACC,KACA,aAAa,UACb,wDACD;CAED,MAAM,aAAa,CAAC,CAAC,KAAK;EACzB,MAAM;EACN,QAAQ;EACR,SAAS,UAAU,OAAO,GAAI;CAC/B,CAAC;CAED,MAAM,oBACL,UAAU,KAAK,WACf,OAAO,KACP,IACA;EAAE,QAAQ;EAAiB,iBAAiB;CAAoB,GAChE,OAAO,GACR;CAEA,OAAO,UAAU;AAClB,CACD"}
1
+ {"version":3,"file":"_server.ts.js","names":[],"sources":["../../../../../../../../../src/routes/api/admin/users/[id]/disable/+server.ts"],"sourcesContent":["import type { RequestHandler } from './$types';\nimport { apiError, ApiErrorCode } from '#lib/server/api-errors.js';\nimport { apiRoute, noContent, requireParams } from '#lib/server/api/http.js';\nimport { getAuthProvider, getPermissionStore, providers } from '#lib/server/providers.server.js';\nimport { revokeUserApiTokens } from '@selvajs/server/handlers';\nimport { apiTokenResolutions } from '#lib/server/apiTokens/token.server.js';\nimport { requireManageInstanceUsers } from '#lib/server/access.server.js';\nimport {\n\trequireCanRemoveInstanceAdmin,\n\twithSoleOwnerGuard\n} from '#lib/server/admin/instanceAdmins.server.js';\nimport { setUserPlatformPermissions } from '#lib/server/permissions.server.js';\nimport { getEventSink } from '#lib/server/providers.server.js';\nimport { actorFrom } from '@selvajs/platform';\n\n/**\n * POST /api/admin/users/[id]/disable\n *\n * docs/contributing/permissions.md §10 — disable preserves identity and attribution. The §2\n * sole-`instance_admin` invariant is enforced here BEFORE the auth provider\n * disables, by consulting\n * `IPlatformPermissionStore.countInstanceAdminsExcluding`. Auth providers no\n * longer own Selva-specific authorization.\n *\n * Cutoff is not instant on every provider, and this route cannot make it so:\n * `sessionRefresh.revokeSession` takes the target's session token, which an\n * admin disabling someone else does not hold. Local and header-auth re-read the\n * user each request, so they cut off on the next one. Supabase keeps accepting\n * an already-issued access token until `revalidateMs` (default 60s) — but its\n * `refreshSession` rejects disabled users, so nothing new can be minted and the\n * window is bounded by the access token's own lifetime, not the 30-day refresh\n * token.\n *\n * No matching enable endpoint today — the auth interface is one-way for v1.\n * Re-enable lands when the spec defines an explicit re-onboarding flow.\n */\nexport const POST: RequestHandler = apiRoute(\n\t'Failed to disable user',\n\tasync ({ params, locals }) => {\n\t\trequireManageInstanceUsers(locals);\n\t\tconst { id } = requireParams(params, 'id');\n\n\t\tconst ctx = locals.ctx!;\n\t\tconst { targetIsAdmin } = await requireCanRemoveInstanceAdmin(ctx, id, 'disable');\n\n\t\t// A disabled owner cannot sign in, and nothing re-enables a user: an org\n\t\t// whose only owner is disabled has nobody left who can name another.\n\t\tawait withSoleOwnerGuard(id, async () => {\n\t\t\t// Revoke before disabling. The local permission store cannot see the\n\t\t\t// disabled flag (it lives in the auth provider's file), so a disabled admin\n\t\t\t// still counts as live there: disable two admins in a row and the instance\n\t\t\t// reaches zero enabled admins with both checks having passed.\n\t\t\t//\n\t\t\t// Re-enabling does not restore the grant; an admin re-assigns it.\n\t\t\tconst priorPermissions = await getPermissionStore().getFor(ctx, id);\n\t\t\tif (targetIsAdmin) {\n\t\t\t\tconst revoked = await setUserPlatformPermissions(ctx, id, []);\n\t\t\t\tif (revoked === 'last_admin') {\n\t\t\t\t\tapiError(\n\t\t\t\t\t\t409,\n\t\t\t\t\t\tApiErrorCode.CONFLICT,\n\t\t\t\t\t\t'Cannot disable the last instance admin. Promote another user to instance admin first.'\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// A disable that did not happen must not cost the target their grant.\n\t\t\tconst restoreAdmin = async () => {\n\t\t\t\tif (targetIsAdmin) await setUserPlatformPermissions(ctx, id, priorPermissions);\n\t\t\t};\n\n\t\t\tconst result = await getAuthProvider()\n\t\t\t\t.disableUser(id)\n\t\t\t\t.catch(async (err: unknown) => {\n\t\t\t\t\tawait restoreAdmin().catch(() => {});\n\t\t\t\t\tthrow err;\n\t\t\t\t});\n\t\t\tif (result !== 'ok') await restoreAdmin().catch(() => {});\n\t\t\tif (result === 'not_found') apiError(404, ApiErrorCode.NOT_FOUND, 'User not found');\n\t\t\tif (result === 'not_supported')\n\t\t\t\tapiError(\n\t\t\t\t\t501,\n\t\t\t\t\tApiErrorCode.INTERNAL,\n\t\t\t\t\t'Disabling users is not supported by this auth provider'\n\t\t\t\t);\n\t\t});\n\n\t\tawait getEventSink().emit({ type: 'user.disabled', userId: id, actorId: actorFrom(ctx) });\n\n\t\tawait revokeUserApiTokens(\n\t\t\tproviders.data.apiTokens,\n\t\t\tctx,\n\t\t\tid,\n\t\t\t{ reason: 'user_disabled', resolutionCache: apiTokenResolutions },\n\t\t\tlocals.log\n\t\t);\n\n\t\treturn noContent();\n\t}\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAa,OAAuB,SACnC,0BACA,OAAO,EAAE,QAAQ,aAAa;CAC7B,2BAA2B,MAAM;CACjC,MAAM,EAAE,OAAO,cAAc,QAAQ,IAAI;CAEzC,MAAM,MAAM,OAAO;CACnB,MAAM,EAAE,kBAAkB,MAAM,8BAA8B,KAAK,IAAI,SAAS;CAIhF,MAAM,mBAAmB,IAAI,YAAY;EAOxC,MAAM,mBAAmB,MAAM,mBAAmB,CAAC,CAAC,OAAO,KAAK,EAAE;EAClE,IAAI,eAEC;OAAA,MADkB,2BAA2B,KAAK,IAAI,CAAC,CAAC,MAC5C,cACf,SACC,KACA,aAAa,UACb,uFACD;EAAA;EAIF,MAAM,eAAe,YAAY;GAChC,IAAI,eAAe,MAAM,2BAA2B,KAAK,IAAI,gBAAgB;EAC9E;EAEA,MAAM,SAAS,MAAM,gBAAgB,CAAC,CACpC,YAAY,EAAE,CAAC,CACf,MAAM,OAAO,QAAiB;GAC9B,MAAM,aAAa,CAAC,CAAC,YAAY,CAAC,CAAC;GACnC,MAAM;EACP,CAAC;EACF,IAAI,WAAW,MAAM,MAAM,aAAa,CAAC,CAAC,YAAY,CAAC,CAAC;EACxD,IAAI,WAAW,aAAa,SAAS,KAAK,aAAa,WAAW,gBAAgB;EAClF,IAAI,WAAW,iBACd,SACC,KACA,aAAa,UACb,wDACD;CACF,CAAC;CAED,MAAM,aAAa,CAAC,CAAC,KAAK;EAAE,MAAM;EAAiB,QAAQ;EAAI,SAAS,UAAU,GAAG;CAAE,CAAC;CAExF,MAAM,oBACL,UAAU,KAAK,WACf,KACA,IACA;EAAE,QAAQ;EAAiB,iBAAiB;CAAoB,GAChE,OAAO,GACR;CAEA,OAAO,UAAU;AAClB,CACD"}
@@ -1,7 +1,7 @@
1
- import { U as actorFrom, g as getPermissionStore, h as getOrganizationProvider, o as getDataProvider, r as getAuthProvider, u as getEventSink } from "../../../../../chunks/providers.server.js";
1
+ import { K as actorFrom, g as getPermissionStore, h as getOrganizationProvider, o as getDataProvider, r as getAuthProvider, u as getEventSink } from "../../../../../chunks/providers.server.js";
2
2
  import { b as requireManageInstanceUsers, k as ApiErrorCode, r as assertCanGrantPlatformPermissions } from "../../../../../chunks/access.js";
3
3
  import { t as SYSTEM_CONTEXT } from "../../../../../chunks/context.js";
4
- import { R as parseBody } from "../../../../../chunks/api.js";
4
+ import { z as parseBody } from "../../../../../chunks/api.js";
5
5
  import { r as PlatformPermissionSchema } from "../../../../../chunks/types3.js";
6
6
  import { t as apiError } from "../../../../../chunks/api-errors.js";
7
7
  import { t as listAllOrgMembers } from "../../../../../chunks/list-all-members.js";
@@ -1,4 +1,4 @@
1
- import { B as classifyAssetPath, G as definitionPaths, x as getStorageProvider } from "../../../../../chunks/providers.server.js";
1
+ import { J as definitionPaths, U as classifyAssetPath, x as getStorageProvider } from "../../../../../chunks/providers.server.js";
2
2
  import { k as ApiErrorCode, n as accessDepsFromConfig } from "../../../../../chunks/access.js";
3
3
  import { t as COVER_IMAGE_CONTENT_TYPES } from "../../../../../chunks/types2.js";
4
4
  import { r as GuidSchema } from "../../../../../chunks/schemas.js";
@@ -1,12 +1,18 @@
1
+ import { L as respondWithKeepalive, z as wantsKeepalive } from "../../../../../chunks/providers.server.js";
1
2
  import { k as ApiErrorCode } from "../../../../../chunks/access.js";
2
- import { t as apiError } from "../../../../../chunks/api-errors.js";
3
- import { n as COMPUTE_REQUEST_MAX_BYTES } from "../../../../../chunks/computeLimits.js";
3
+ import { g as SolveModeSchema } from "../../../../../chunks/api.js";
4
+ import { n as errorResponse, t as apiError } from "../../../../../chunks/api-errors.js";
5
+ import { a as computeRequestCap } from "../../../../../chunks/engine.server.js";
4
6
  import { l as requireMaxBodySize } from "../../../../../chunks/admin-auth.server.js";
5
7
  import { n as tryResolveShareToken } from "../../../../../chunks/resolve.server.js";
6
8
  import { n as runSolve, t as mapSolveError } from "../../../../../chunks/solve.server.js";
7
9
  // src/routes/api/v1/compute/+server.ts
8
- var POST = async ({ request, locals, url }) => {
9
- requireMaxBodySize(request, COMPUTE_REQUEST_MAX_BYTES);
10
+ var POST = (event) => {
11
+ if (!wantsKeepalive(event.request)) return solve(event);
12
+ return respondWithKeepalive(solve(event).catch((err) => errorResponse(err, event.locals.log)));
13
+ };
14
+ async function solve({ request, locals, url }) {
15
+ requireMaxBodySize(request, computeRequestCap());
10
16
  const loadStart = performance.now();
11
17
  const prepMarks = [];
12
18
  let prevMark = performance.now();
@@ -22,6 +28,8 @@ var POST = async ({ request, locals, url }) => {
22
28
  const channel = body.channel ?? "live";
23
29
  const explicitVersionId = body.versionId ?? null;
24
30
  if (!values || !definitionUrl) apiError(400, ApiErrorCode.VALIDATION_FAILED, "Missing required fields: values or definitionUrl");
31
+ const mode = SolveModeSchema.default("full").safeParse(body.mode);
32
+ if (!mode.success) apiError(400, ApiErrorCode.VALIDATION_FAILED, `Invalid mode: ${String(body.mode)}. Must be 'preview' or 'full'.`);
25
33
  if (channel !== "live" && channel !== "draft") apiError(400, ApiErrorCode.VALIDATION_FAILED, `Invalid channel: ${channel}. Must be 'live' or 'draft'.`);
26
34
  const isLocal = definitionUrl.startsWith("local:");
27
35
  const guid = isLocal ? definitionUrl.substring(6) : null;
@@ -49,12 +57,13 @@ var POST = async ({ request, locals, url }) => {
49
57
  locals,
50
58
  loadStart,
51
59
  prepMarks,
52
- streamId: typeof body.streamId === "string" ? body.streamId : null
60
+ streamId: typeof body.streamId === "string" ? body.streamId : null,
61
+ solveMode: mode.data
53
62
  });
54
63
  } catch (err) {
55
64
  mapSolveError(err, locals);
56
65
  }
57
- };
66
+ }
58
67
  export { POST };
59
68
 
60
69
  //# sourceMappingURL=_server.ts.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"_server.ts.js","names":[],"sources":["../../../../../../../src/routes/api/v1/compute/+server.ts"],"sourcesContent":["import type { RequestHandler } from './$types';\nimport { apiError, ApiErrorCode } from '#lib/server/api-errors.js';\nimport { COMPUTE_REQUEST_MAX_BYTES } from '#lib/server/computeLimits.js';\nimport { requireMaxBodySize } from '#lib/server/admin-auth.server.js';\nimport { tryResolveShareToken } from '#lib/server/shareLinks/resolve.server.js';\nimport { runSolve, mapSolveError, type SolveAccess } from '#lib/server/compute/solve.server.js';\n\ninterface ComputeRequest {\n\t/** Read for a remote `definitionUrl` only: a stored definition's inputs come from its schema. */\n\tinputs?: unknown;\n\tvalues: Record<string, unknown>;\n\tdefinitionUrl: string;\n\t/** Spec §6 channel selector. Defaults to 'live'. 'draft' requires editor. */\n\tchannel?: 'live' | 'draft';\n\t/**\n\t * Explicit version pick (versioning tab \"Run\"). Solves this exact version\n\t * instead of the channel pointer; editor-only, never share-token accessible.\n\t */\n\tversionId?: string;\n\t/** The caller's open live-event stream; see `SolveParams.streamId`. */\n\tstreamId?: string;\n}\n\n// The URL-addressed solve: takes an arbitrary `definitionUrl`, and is the only\n// route that accepts a share token. The solve mechanics it shares with\n// `/api/v1/definitions/{guid}/solve` live in `solve.server.ts`; what stays here\n// is the body shape and the share-token branch, which must NOT reach the\n// definition-addressed route.\n\nexport const POST: RequestHandler = async ({ request, locals, url }) => {\n\t// Reject oversized payloads before buffering.\n\trequireMaxBodySize(request, COMPUTE_REQUEST_MAX_BYTES);\n\n\t// DEBUG (SELVA_FLAG_COMPUTE_DEBUG): start of server-side work. The solve metric's\n\t// `durationMs` wraps ONLY scheduler.solve, so everything before it (auth, DB reads,\n\t// definition fetch, input tree build) and the response serialization after it are\n\t// otherwise invisible. `runSolve` continues these marks and logs the breakdown.\n\tconst loadStart = performance.now();\n\tconst prepMarks: [string, number][] = [];\n\tlet prevMark = performance.now();\n\tconst mark = (label: string) => {\n\t\tprepMarks.push([label, performance.now() - prevMark]);\n\t\tprevMark = performance.now();\n\t};\n\n\ttry {\n\t\tconst body: ComputeRequest = await request.json();\n\t\tmark('body');\n\n\t\tconst { inputs, values } = body;\n\t\tconst definitionUrl = body.definitionUrl;\n\t\tconst channel: 'live' | 'draft' = body.channel ?? 'live';\n\t\tconst explicitVersionId = body.versionId ?? null;\n\n\t\tif (!values || !definitionUrl) {\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t'Missing required fields: values or definitionUrl'\n\t\t\t);\n\t\t}\n\t\tif (channel !== 'live' && channel !== 'draft') {\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t`Invalid channel: ${channel}. Must be 'live' or 'draft'.`\n\t\t\t);\n\t\t}\n\n\t\t// Share-link tokens (spec §7); null for remote definitions or no token.\n\t\tconst isLocal = definitionUrl.startsWith('local:');\n\t\tconst guid = isLocal ? definitionUrl.substring(6) : null;\n\t\t// Explicit-version solves are editor-only, so don't resolve a share token\n\t\t// for them — force the logged-in editor gate instead.\n\t\tconst sharedAccess =\n\t\t\tisLocal && guid && !explicitVersionId\n\t\t\t\t? await tryResolveShareToken(request, url, guid, channel, { requireSolve: true })\n\t\t\t\t: null;\n\t\tmark('shareToken');\n\n\t\tif (!sharedAccess && (!locals.ctx || !locals.user)) {\n\t\t\tapiError(401, ApiErrorCode.UNAUTHORIZED, 'Unauthorized');\n\t\t}\n\n\t\t// Rate-limit bucket per caller: `share:{linkId}` for token solves so an\n\t\t// anonymous crowd on one public link can't drain the owner's budget.\n\t\tconst access: SolveAccess = sharedAccess\n\t\t\t? {\n\t\t\t\t\tkind: 'share',\n\t\t\t\t\tctx: sharedAccess.ctx,\n\t\t\t\t\tlink: sharedAccess.link,\n\t\t\t\t\trateLimitKey: `share:${sharedAccess.link.id}`\n\t\t\t\t}\n\t\t\t: { kind: 'user', ctx: locals.ctx!, rateLimitKey: `user:${locals.user!.id}` };\n\n\t\treturn await runSolve({\n\t\t\taccess,\n\t\t\tdefinitionUrl,\n\t\t\tinputs,\n\t\t\tvalues,\n\t\t\tchannel,\n\t\t\tversionId: explicitVersionId,\n\t\t\trequest,\n\t\t\tlocals,\n\t\t\tloadStart,\n\t\t\tprepMarks,\n\t\t\tstreamId: typeof body.streamId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S;GACrB;GACA;GACA;GACA;GACA;GACA,WAAW;GACX;GACA;GACA;GACA;GACA,UAAU,OAAO,KAAK,aAAa,WAAW,KAAK,WAAW;EAC/D,CAAC;CACF,SAAS,KAAK;EACb,cAAc,KAAK,MAAM;CAC1B;AACD"}
1
+ {"version":3,"file":"_server.ts.js","names":[],"sources":["../../../../../../../src/routes/api/v1/compute/+server.ts"],"sourcesContent":["import type { RequestEvent, RequestHandler } from './$types';\nimport { apiError, ApiErrorCode, errorResponse } from '#lib/server/api-errors.js';\nimport { computeRequestCap } from '#lib/server/compute/engine.server.js';\nimport { requireMaxBodySize } from '#lib/server/admin-auth.server.js';\nimport { tryResolveShareToken } from '#lib/server/shareLinks/resolve.server.js';\nimport { runSolve, mapSolveError, type SolveAccess } from '#lib/server/compute/solve.server.js';\nimport { SolveModeSchema } from '@selvajs/server/api';\nimport { respondWithKeepalive, wantsKeepalive } from '@selvajs/solve/server';\n\ninterface ComputeRequest {\n\t/** Read for a remote `definitionUrl` only: a stored definition's inputs come from its schema. */\n\tinputs?: unknown;\n\tvalues: Record<string, unknown>;\n\tdefinitionUrl: string;\n\t/** Spec §6 channel selector. Defaults to 'live'. 'draft' requires editor. */\n\tchannel?: 'live' | 'draft';\n\t/**\n\t * Explicit version pick (versioning tab \"Run\"). Solves this exact version\n\t * instead of the channel pointer; editor-only, never share-token accessible.\n\t */\n\tversionId?: string;\n\t/** The caller's open live-event stream; see `SolveParams.streamId`. */\n\tstreamId?: string;\n\t/** See `SolveBodySchema.mode`. */\n\tmode?: string;\n}\n\n// The URL-addressed solve: takes an arbitrary `definitionUrl`, and is the only\n// route that accepts a share token. The solve mechanics it shares with\n// `/api/v1/definitions/{guid}/solve` live in `solve.server.ts`; what stays here\n// is the body shape and the share-token branch, which must NOT reach the\n// definition-addressed route.\n//\n// The web app asks for keep-alive, so a solve longer than the reverse proxy's read timeout\n// still lands. Errors then travel inside the 200, which is why they become responses here.\n\nexport const POST: RequestHandler = (event) => {\n\tif (!wantsKeepalive(event.request)) return solve(event);\n\treturn respondWithKeepalive(solve(event).catch((err) => errorResponse(err, event.locals.log)));\n};\n\nasync function solve({ request, locals, url }: RequestEvent): Promise<Response> {\n\t// Reject oversized payloads before buffering.\n\trequireMaxBodySize(request, computeRequestCap());\n\n\t// DEBUG (SELVA_FLAG_COMPUTE_DEBUG): start of server-side work. The solve metric's\n\t// `durationMs` wraps ONLY scheduler.solve, so everything before it (auth, DB reads,\n\t// definition fetch, input tree build) and the response serialization after it are\n\t// otherwise invisible. `runSolve` continues these marks and logs the breakdown.\n\tconst loadStart = performance.now();\n\tconst prepMarks: [string, number][] = [];\n\tlet prevMark = performance.now();\n\tconst mark = (label: string) => {\n\t\tprepMarks.push([label, performance.now() - prevMark]);\n\t\tprevMark = performance.now();\n\t};\n\n\ttry {\n\t\tconst body: ComputeRequest = await request.json();\n\t\tmark('body');\n\n\t\tconst { inputs, values } = body;\n\t\tconst definitionUrl = body.definitionUrl;\n\t\tconst channel: 'live' | 'draft' = body.channel ?? 'live';\n\t\tconst explicitVersionId = body.versionId ?? null;\n\n\t\tif (!values || !definitionUrl) {\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t'Missing required fields: values or definitionUrl'\n\t\t\t);\n\t\t}\n\t\tconst mode = SolveModeSchema.default('full').safeParse(body.mode);\n\t\tif (!mode.success) {\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t`Invalid mode: ${String(body.mode)}. Must be 'preview' or 'full'.`\n\t\t\t);\n\t\t}\n\t\tif (channel !== 'live' && channel !== 'draft') {\n\t\t\tapiError(\n\t\t\t\t400,\n\t\t\t\tApiErrorCode.VALIDATION_FAILED,\n\t\t\t\t`Invalid channel: ${channel}. Must be 'live' or 'draft'.`\n\t\t\t);\n\t\t}\n\n\t\t// Share-link tokens (spec §7); null for remote definitions or no token.\n\t\tconst isLocal = definitionUrl.startsWith('local:');\n\t\tconst guid = isLocal ? definitionUrl.substring(6) : null;\n\t\t// Explicit-version solves are editor-only, so don't resolve a share token\n\t\t// for them — force the logged-in editor gate instead.\n\t\tconst sharedAccess =\n\t\t\tisLocal && guid && !explicitVersionId\n\t\t\t\t? await tryResolveShareToken(request, url, guid, channel, { requireSolve: true })\n\t\t\t\t: null;\n\t\tmark('shareToken');\n\n\t\tif (!sharedAccess && (!locals.ctx || !locals.user)) {\n\t\t\tapiError(401, ApiErrorCode.UNAUTHORIZED, 'Unauthorized');\n\t\t}\n\n\t\t// Rate-limit bucket per caller: `share:{linkId}` for token solves so an\n\t\t// anonymous crowd on one public link can't drain the owner's budget.\n\t\tconst access: SolveAccess = sharedAccess\n\t\t\t? {\n\t\t\t\t\tkind: 'share',\n\t\t\t\t\tctx: sharedAccess.ctx,\n\t\t\t\t\tlink: sharedAccess.link,\n\t\t\t\t\trateLimitKey: `share:${sharedAccess.link.id}`\n\t\t\t\t}\n\t\t\t: { kind: 'user', ctx: locals.ctx!, rateLimitKey: `user:${locals.user!.id}` };\n\n\t\treturn await runSolve({\n\t\t\taccess,\n\t\t\tdefinitionUrl,\n\t\t\tinputs,\n\t\t\tvalues,\n\t\t\tchannel,\n\t\t\tversionId: explicitVersionId,\n\t\t\trequest,\n\t\t\tlocals,\n\t\t\tloadStart,\n\t\t\tprepMarks,\n\t\t\tstreamId: typeof body.streamId === 'string' ? body.streamId : null,\n\t\t\tsolveMode: mode.data\n\t\t});\n\t} catch (err) {\n\t\tmapSolveError(err, locals);\n\t}\n}\n"],"mappings":";;;;;;;;;AAoCA,IAAa,QAAwB,UAAU;CAC9C,IAAI,CAAC,eAAe,MAAM,OAAO,GAAG,OAAO,MAAM,KAAK;CACtD,OAAO,qBAAqB,MAAM,KAAK,CAAC,CAAC,OAAO,QAAQ,cAAc,KAAK,MAAM,OAAO,GAAG,CAAC,CAAC;AAC9F;AAEA,eAAe,MAAM,EAAE,SAAS,QAAQ,OAAwC;CAE/E,mBAAmB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