gemi 0.119.2 → 0.120.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai/index.js.map +1 -1
  3. package/dist/app/index.js +2 -2
  4. package/dist/app/index.js.map +1 -1
  5. package/dist/bin/gemi.js +32 -5
  6. package/dist/bin/gemi.js.map +6 -5
  7. package/dist/bun/plugin.js +1 -1
  8. package/dist/bun/preload.js +1 -1
  9. package/dist/{chunk-x5m12vkw.js → chunk-0ejjgzwc.js} +2 -2
  10. package/dist/{chunk-x5m12vkw.js.map → chunk-0ejjgzwc.js.map} +1 -1
  11. package/dist/{chunk-7rffbkmg.js → chunk-0k02tza1.js} +1 -1
  12. package/dist/{chunk-14xk8kq0.js → chunk-0yj0s1pn.js} +2 -2
  13. package/dist/{chunk-14xk8kq0.js.map → chunk-0yj0s1pn.js.map} +1 -1
  14. package/dist/{chunk-6pqbsc5y.js → chunk-19dpzp4y.js} +3 -3
  15. package/dist/{chunk-6pqbsc5y.js.map → chunk-19dpzp4y.js.map} +1 -1
  16. package/dist/{chunk-3vt172y7.js → chunk-1wnnkde0.js} +3 -3
  17. package/dist/{chunk-3vt172y7.js.map → chunk-1wnnkde0.js.map} +1 -1
  18. package/dist/{chunk-ct1vwaw7.js → chunk-1xdrs2hx.js} +3 -3
  19. package/dist/{chunk-ct1vwaw7.js.map → chunk-1xdrs2hx.js.map} +1 -1
  20. package/dist/{chunk-ty8gxbgj.js → chunk-231a9920.js} +3 -3
  21. package/dist/{chunk-ty8gxbgj.js.map → chunk-231a9920.js.map} +3 -3
  22. package/dist/{chunk-79rtpahn.js → chunk-2c0s0561.js} +2 -2
  23. package/dist/{chunk-79rtpahn.js.map → chunk-2c0s0561.js.map} +1 -1
  24. package/dist/{chunk-nfq127pg.js → chunk-2n3pgfnb.js} +2 -2
  25. package/dist/{chunk-nfq127pg.js.map → chunk-2n3pgfnb.js.map} +1 -1
  26. package/dist/{chunk-s2h85rbf.js → chunk-32n8t8x6.js} +2 -2
  27. package/dist/{chunk-s2h85rbf.js.map → chunk-32n8t8x6.js.map} +1 -1
  28. package/dist/{chunk-6gfsjgra.js → chunk-3gsv1vv1.js} +2 -2
  29. package/dist/{chunk-6gfsjgra.js.map → chunk-3gsv1vv1.js.map} +1 -1
  30. package/dist/{chunk-862jeyz0.js → chunk-3wnghdsx.js} +2 -2
  31. package/dist/{chunk-862jeyz0.js.map → chunk-3wnghdsx.js.map} +1 -1
  32. package/dist/{chunk-yn4x9wxc.js → chunk-471htqmz.js} +2 -2
  33. package/dist/{chunk-yn4x9wxc.js.map → chunk-471htqmz.js.map} +1 -1
  34. package/dist/{chunk-w1zqg54r.js → chunk-48gmyaxc.js} +2 -2
  35. package/dist/{chunk-w1zqg54r.js.map → chunk-48gmyaxc.js.map} +1 -1
  36. package/dist/{chunk-299zx9dv.js → chunk-4acpw92g.js} +3 -3
  37. package/dist/{chunk-299zx9dv.js.map → chunk-4acpw92g.js.map} +1 -1
  38. package/dist/{chunk-9c5s06gc.js → chunk-4fx8p02c.js} +2 -2
  39. package/dist/{chunk-9c5s06gc.js.map → chunk-4fx8p02c.js.map} +1 -1
  40. package/dist/{chunk-xpz1bp50.js → chunk-51w5ktv2.js} +3 -3
  41. package/dist/{chunk-xpz1bp50.js.map → chunk-51w5ktv2.js.map} +1 -1
  42. package/dist/{chunk-9qkjkse0.js → chunk-5nj94s66.js} +4 -4
  43. package/dist/{chunk-9qkjkse0.js.map → chunk-5nj94s66.js.map} +1 -1
  44. package/dist/{chunk-j632p533.js → chunk-5tdxbwzg.js} +3 -3
  45. package/dist/{chunk-j632p533.js.map → chunk-5tdxbwzg.js.map} +1 -1
  46. package/dist/{chunk-zq1bhsdg.js → chunk-65beps2q.js} +3 -3
  47. package/dist/{chunk-zq1bhsdg.js.map → chunk-65beps2q.js.map} +1 -1
  48. package/dist/{chunk-xeh1mw1d.js → chunk-6yhpprzs.js} +3 -3
  49. package/dist/{chunk-xeh1mw1d.js.map → chunk-6yhpprzs.js.map} +1 -1
  50. package/dist/{chunk-620yeafr.js → chunk-7ftj43vp.js} +2 -2
  51. package/dist/{chunk-620yeafr.js.map → chunk-7ftj43vp.js.map} +1 -1
  52. package/dist/{chunk-4kj4e22e.js → chunk-7g649j8h.js} +2 -2
  53. package/dist/{chunk-4kj4e22e.js.map → chunk-7g649j8h.js.map} +1 -1
  54. package/dist/{chunk-675kzd7z.js → chunk-7mmw0jr2.js} +2 -2
  55. package/dist/{chunk-675kzd7z.js.map → chunk-7mmw0jr2.js.map} +1 -1
  56. package/dist/{chunk-k1ncgq7p.js → chunk-9d2d08qm.js} +2 -2
  57. package/dist/{chunk-k1ncgq7p.js.map → chunk-9d2d08qm.js.map} +1 -1
  58. package/dist/{chunk-wdg83tgd.js → chunk-9rr5h818.js} +3 -3
  59. package/dist/{chunk-wdg83tgd.js.map → chunk-9rr5h818.js.map} +1 -1
  60. package/dist/{chunk-30xxc6r7.js → chunk-9xyxbxgk.js} +2 -2
  61. package/dist/{chunk-30xxc6r7.js.map → chunk-9xyxbxgk.js.map} +1 -1
  62. package/dist/{chunk-6ggmk2eg.js → chunk-c0v61fp5.js} +2 -2
  63. package/dist/{chunk-6ggmk2eg.js.map → chunk-c0v61fp5.js.map} +1 -1
  64. package/dist/{chunk-bw2pfaz3.js → chunk-c7qs1xp3.js} +2 -2
  65. package/dist/{chunk-bw2pfaz3.js.map → chunk-c7qs1xp3.js.map} +1 -1
  66. package/dist/{chunk-2kegxt0s.js → chunk-cca0grq3.js} +2 -2
  67. package/dist/{chunk-2kegxt0s.js.map → chunk-cca0grq3.js.map} +1 -1
  68. package/dist/{chunk-b336h3hj.js → chunk-cskqet01.js} +2 -2
  69. package/dist/{chunk-b336h3hj.js.map → chunk-cskqet01.js.map} +1 -1
  70. package/dist/{chunk-pzk2a5sr.js → chunk-cvr5624r.js} +1 -1
  71. package/dist/{chunk-8507ez1g.js → chunk-d2c3947c.js} +2 -2
  72. package/dist/{chunk-8507ez1g.js.map → chunk-d2c3947c.js.map} +1 -1
  73. package/dist/{chunk-q0djcyj2.js → chunk-d5f1m3d2.js} +2 -2
  74. package/dist/{chunk-q0djcyj2.js.map → chunk-d5f1m3d2.js.map} +1 -1
  75. package/dist/{chunk-qm6j85fq.js → chunk-dbx3g5ck.js} +2 -2
  76. package/dist/{chunk-qm6j85fq.js.map → chunk-dbx3g5ck.js.map} +1 -1
  77. package/dist/chunk-dc8gyybt.js +24 -0
  78. package/dist/{chunk-w8d37mcq.js.map → chunk-dc8gyybt.js.map} +3 -3
  79. package/dist/{chunk-f9tfpn3w.js → chunk-dedqr5wb.js} +2 -2
  80. package/dist/{chunk-f9tfpn3w.js.map → chunk-dedqr5wb.js.map} +1 -1
  81. package/dist/{chunk-h02kyxgg.js → chunk-dhbgrv58.js} +1 -1
  82. package/dist/{chunk-d4dd7jde.js → chunk-dwedx1jb.js} +3 -3
  83. package/dist/{chunk-d4dd7jde.js.map → chunk-dwedx1jb.js.map} +1 -1
  84. package/dist/{chunk-5crtgt1y.js → chunk-ep0baa9g.js} +2 -2
  85. package/dist/{chunk-5crtgt1y.js.map → chunk-ep0baa9g.js.map} +1 -1
  86. package/dist/{chunk-kk77x2v4.js → chunk-er8acmch.js} +7 -7
  87. package/dist/{chunk-kk77x2v4.js.map → chunk-er8acmch.js.map} +3 -3
  88. package/dist/{chunk-thz75w6e.js → chunk-fcqx2t0p.js} +2 -2
  89. package/dist/{chunk-thz75w6e.js.map → chunk-fcqx2t0p.js.map} +1 -1
  90. package/dist/{chunk-1p87gdd2.js → chunk-fenc5tpv.js} +2 -2
  91. package/dist/{chunk-1p87gdd2.js.map → chunk-fenc5tpv.js.map} +1 -1
  92. package/dist/{chunk-fmea4sak.js → chunk-gc2dz11k.js} +2 -2
  93. package/dist/{chunk-fmea4sak.js.map → chunk-gc2dz11k.js.map} +1 -1
  94. package/dist/{chunk-qxxbp3nn.js → chunk-gemzbw7f.js} +2 -2
  95. package/dist/{chunk-qxxbp3nn.js.map → chunk-gemzbw7f.js.map} +1 -1
  96. package/dist/{chunk-qpy25jj9.js → chunk-gy81nd9a.js} +2 -2
  97. package/dist/{chunk-qpy25jj9.js.map → chunk-gy81nd9a.js.map} +1 -1
  98. package/dist/{chunk-c8vttyem.js → chunk-h43jp8ws.js} +2 -2
  99. package/dist/{chunk-c8vttyem.js.map → chunk-h43jp8ws.js.map} +1 -1
  100. package/dist/chunk-hhymaj0m.js +57 -0
  101. package/dist/{chunk-bz5gda3b.js.map → chunk-hhymaj0m.js.map} +7 -6
  102. package/dist/chunk-htgmy3x7.js +5 -0
  103. package/dist/{chunk-15v719sq.js.map → chunk-htgmy3x7.js.map} +1 -1
  104. package/dist/{chunk-xqd3zde5.js → chunk-jaa6xkeh.js} +2 -2
  105. package/dist/{chunk-xqd3zde5.js.map → chunk-jaa6xkeh.js.map} +1 -1
  106. package/dist/{chunk-2bja99cq.js → chunk-kk18xqgc.js} +2 -2
  107. package/dist/{chunk-2bja99cq.js.map → chunk-kk18xqgc.js.map} +1 -1
  108. package/dist/{chunk-mcjbck8e.js → chunk-krk7mcgm.js} +3 -3
  109. package/dist/{chunk-mcjbck8e.js.map → chunk-krk7mcgm.js.map} +1 -1
  110. package/dist/{chunk-hd5ztshp.js → chunk-krtybgz1.js} +2 -2
  111. package/dist/{chunk-hd5ztshp.js.map → chunk-krtybgz1.js.map} +1 -1
  112. package/dist/{chunk-fjhnn3de.js → chunk-m53fgf20.js} +3 -3
  113. package/dist/{chunk-fjhnn3de.js.map → chunk-m53fgf20.js.map} +1 -1
  114. package/dist/{chunk-4c1npv8k.js → chunk-m83zm86m.js} +2 -2
  115. package/dist/{chunk-4c1npv8k.js.map → chunk-m83zm86m.js.map} +1 -1
  116. package/dist/{chunk-q6a30w8w.js → chunk-meg8rtr6.js} +2 -2
  117. package/dist/{chunk-q6a30w8w.js.map → chunk-meg8rtr6.js.map} +1 -1
  118. package/dist/{chunk-vy0tnx2s.js → chunk-mr94nfp1.js} +3 -3
  119. package/dist/{chunk-vy0tnx2s.js.map → chunk-mr94nfp1.js.map} +1 -1
  120. package/dist/{chunk-zb8zzf5x.js → chunk-nz8z8jr1.js} +3 -3
  121. package/dist/{chunk-zb8zzf5x.js.map → chunk-nz8z8jr1.js.map} +1 -1
  122. package/dist/{chunk-d38x71xy.js → chunk-pemhmjzp.js} +3 -3
  123. package/dist/{chunk-d38x71xy.js.map → chunk-pemhmjzp.js.map} +1 -1
  124. package/dist/{chunk-d2v78b77.js → chunk-pn2x59ge.js} +3 -3
  125. package/dist/{chunk-d2v78b77.js.map → chunk-pn2x59ge.js.map} +1 -1
  126. package/dist/{chunk-p5xy9cn8.js → chunk-qsz9241c.js} +2 -2
  127. package/dist/{chunk-p5xy9cn8.js.map → chunk-qsz9241c.js.map} +1 -1
  128. package/dist/{chunk-d6nhcqvt.js → chunk-qy8c0gzr.js} +2 -2
  129. package/dist/{chunk-d6nhcqvt.js.map → chunk-qy8c0gzr.js.map} +1 -1
  130. package/dist/{chunk-7ns5506p.js → chunk-r01aqf0q.js} +2 -2
  131. package/dist/{chunk-7ns5506p.js.map → chunk-r01aqf0q.js.map} +1 -1
  132. package/dist/{chunk-0p6mdba6.js → chunk-rhvc1axc.js} +2 -2
  133. package/dist/{chunk-0p6mdba6.js.map → chunk-rhvc1axc.js.map} +1 -1
  134. package/dist/{chunk-pjz79c2c.js → chunk-s07v65x6.js} +3 -3
  135. package/dist/{chunk-pjz79c2c.js.map → chunk-s07v65x6.js.map} +1 -1
  136. package/dist/{chunk-q00f25na.js → chunk-s5k3yq6t.js} +2 -2
  137. package/dist/{chunk-q00f25na.js.map → chunk-s5k3yq6t.js.map} +1 -1
  138. package/dist/{chunk-2854taf5.js → chunk-sx340k85.js} +2 -2
  139. package/dist/{chunk-2854taf5.js.map → chunk-sx340k85.js.map} +1 -1
  140. package/dist/{chunk-j5q5ysng.js → chunk-tewhms9w.js} +2 -2
  141. package/dist/{chunk-j5q5ysng.js.map → chunk-tewhms9w.js.map} +1 -1
  142. package/dist/{chunk-7pxdvvrz.js → chunk-tk135gmj.js} +3 -3
  143. package/dist/{chunk-7pxdvvrz.js.map → chunk-tk135gmj.js.map} +1 -1
  144. package/dist/{chunk-yvd4pgd9.js → chunk-vx7hvyvq.js} +2 -2
  145. package/dist/{chunk-yvd4pgd9.js.map → chunk-vx7hvyvq.js.map} +1 -1
  146. package/dist/{chunk-xecnc8zv.js → chunk-wjkh2gem.js} +1 -1
  147. package/dist/{chunk-khd9ft0s.js → chunk-wnj7q0th.js} +3 -3
  148. package/dist/{chunk-khd9ft0s.js.map → chunk-wnj7q0th.js.map} +1 -1
  149. package/dist/{chunk-511zqetr.js → chunk-wqe47c0j.js} +2 -2
  150. package/dist/{chunk-511zqetr.js.map → chunk-wqe47c0j.js.map} +1 -1
  151. package/dist/{chunk-2y0r4b7g.js → chunk-y6wt5b6t.js} +1 -1
  152. package/dist/{chunk-kkx8a35r.js → chunk-yds7zwc3.js} +2 -2
  153. package/dist/{chunk-kkx8a35r.js.map → chunk-yds7zwc3.js.map} +1 -1
  154. package/dist/{chunk-w7am9q0q.js → chunk-zefs2b6h.js} +2 -2
  155. package/dist/{chunk-w7am9q0q.js.map → chunk-zefs2b6h.js.map} +1 -1
  156. package/dist/{chunk-de4t48j9.js → chunk-zg6hmc48.js} +1 -1
  157. package/dist/{chunk-svn6zvzd.js → chunk-zrcd9hxr.js} +2 -2
  158. package/dist/{chunk-svn6zvzd.js.map → chunk-zrcd9hxr.js.map} +1 -1
  159. package/dist/client/index.d.ts +1 -0
  160. package/dist/client/index.d.ts.map +1 -1
  161. package/dist/client/index.js +26 -1
  162. package/dist/client/index.js.map +1 -1
  163. package/dist/client/staticNavigation.d.ts +26 -0
  164. package/dist/client/staticNavigation.d.ts.map +1 -0
  165. package/dist/config/index.js +1 -1
  166. package/dist/console/run.js +2 -2
  167. package/dist/console/run.js.map +1 -1
  168. package/dist/container/index.js +2 -2
  169. package/dist/container/index.js.map +1 -1
  170. package/dist/database/index.js +2 -2
  171. package/dist/database/index.js.map +1 -1
  172. package/dist/email/index.js +2 -2
  173. package/dist/email/index.js.map +1 -1
  174. package/dist/facades/index.js +2 -2
  175. package/dist/facades/index.js.map +1 -1
  176. package/dist/foundation/index.js +2 -2
  177. package/dist/foundation/index.js.map +1 -1
  178. package/dist/http/ViewRouter.d.ts +36 -2
  179. package/dist/http/ViewRouter.d.ts.map +1 -1
  180. package/dist/http/index.d.ts +1 -1
  181. package/dist/http/index.d.ts.map +1 -1
  182. package/dist/http/index.js +2 -2
  183. package/dist/http/index.js.map +1 -1
  184. package/dist/i18n/dictionaryRuntime.js +2 -2
  185. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  186. package/dist/i18n/index.js +2 -2
  187. package/dist/i18n/index.js.map +2 -2
  188. package/dist/internal/islandRuntime.d.ts +16 -0
  189. package/dist/internal/islandRuntime.d.ts.map +1 -1
  190. package/dist/internal/staticNavigationRuntime.d.ts +8 -0
  191. package/dist/internal/staticNavigationRuntime.d.ts.map +1 -0
  192. package/dist/kernel/index.js +2 -2
  193. package/dist/kernel/index.js.map +2 -2
  194. package/dist/orm/index.js +2 -2
  195. package/dist/orm/index.js.map +1 -1
  196. package/dist/server/devFetch.d.ts.map +1 -1
  197. package/dist/server/httpProd.d.ts.map +1 -1
  198. package/dist/server/index.js +2 -2
  199. package/dist/server/index.js.map +1 -1
  200. package/dist/services/index.d.ts +1 -1
  201. package/dist/services/index.d.ts.map +1 -1
  202. package/dist/services/index.js +3 -3
  203. package/dist/services/index.js.map +2 -2
  204. package/dist/services/queue/work.js +2 -2
  205. package/dist/services/queue/work.js.map +1 -1
  206. package/dist/services/router/ViewRouteDispatcher.d.ts +5 -0
  207. package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
  208. package/dist/services/router/staticDocument.d.ts +30 -21
  209. package/dist/services/router/staticDocument.d.ts.map +1 -1
  210. package/dist/stats/bundleStats.d.ts +6 -2
  211. package/dist/stats/bundleStats.d.ts.map +1 -1
  212. package/dist/stats/route-table.js +2 -2
  213. package/dist/stats/route-table.js.map +3 -3
  214. package/dist/stats/routeTable.d.ts +5 -1
  215. package/dist/stats/routeTable.d.ts.map +1 -1
  216. package/dist/support/index.js +2 -2
  217. package/dist/support/index.js.map +1 -1
  218. package/dist/testing/index.d.ts +2 -0
  219. package/dist/testing/index.d.ts.map +1 -1
  220. package/dist/testing/index.js +185 -2
  221. package/dist/testing/index.js.map +1 -1
  222. package/dist/testing/staticDocument.d.ts +80 -0
  223. package/dist/testing/staticDocument.d.ts.map +1 -0
  224. package/dist/vitest/index.js +1 -1
  225. package/package.json +1 -1
  226. package/dist/chunk-15v719sq.js +0 -5
  227. package/dist/chunk-bz5gda3b.js +0 -57
  228. package/dist/chunk-w8d37mcq.js +0 -24
  229. /package/dist/{chunk-7rffbkmg.js.map → chunk-0k02tza1.js.map} +0 -0
  230. /package/dist/{chunk-pzk2a5sr.js.map → chunk-cvr5624r.js.map} +0 -0
  231. /package/dist/{chunk-h02kyxgg.js.map → chunk-dhbgrv58.js.map} +0 -0
  232. /package/dist/{chunk-xecnc8zv.js.map → chunk-wjkh2gem.js.map} +0 -0
  233. /package/dist/{chunk-2y0r4b7g.js.map → chunk-y6wt5b6t.js.map} +0 -0
  234. /package/dist/{chunk-de4t48j9.js.map → chunk-zg6hmc48.js.map} +0 -0
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Jh as k,oh as g,ph as m}from"./chunk-kkx8a35r.js";import{Ti as p}from"./chunk-zb8zzf5x.js";import{ij as n}from"./chunk-j5q5ysng.js";var b={};n(b,{registeredNames:()=>x,register:()=>i,has:()=>S,get:()=>_,clearRegistry:()=>a});var M=new Map;function i(q,z){M.set(q,z)}function S(q){return M.has(q)}function _(q){let z=M.get(q);if(z===void 0)throw new k(q,[...M.keys()]);return z}function x(){return[...M.keys()]}function a(){M.clear()}import{createCipheriv as r,createDecipheriv as e,randomBytes as qq}from"crypto";class Y{static token="encrypter";keys=new Map;currentId;constructor(q={}){for(let[z,J]of Object.entries(q.keys??{})){if(!u.test(z))throw new U(`Encryption key id "${z}" is not valid. Use 1-32 letters, digits, "_" or "-": the id is written into every encrypted value.`);this.keys.set(z,zq(z,J))}if(q.current!==void 0){if(!this.keys.has(q.current))throw new U(`encryption.current is "${q.current}", but encryption.keys has no key by that id (${I(this.keys)}).`);this.currentId=q.current}else if(this.keys.size===1)this.currentId=[...this.keys.keys()][0];else if(this.keys.size>1)throw new U(`encryption.keys has ${this.keys.size} keys (${I(this.keys)}) and no encryption.current to say which one encrypts new values.`)}get configured(){return this.currentId!==void 0}get currentKeyId(){return this.requireCurrent()}encrypt(q){if(typeof q!=="string")throw TypeError(`Encrypter.encrypt takes a string, got ${Jq(q)}. Serialise other values first (JSON.stringify).`);let z=this.requireCurrent(),J=this.keys.get(z),Q=`${j}:${z}`,Z=qq(y),$=r(E,J,Z);$.setAAD(Buffer.from(Q));let X=Buffer.concat([$.update(q,"utf8"),$.final(),$.getAuthTag()]);return`${Q}:${Z.toString("base64url")}:${X.toString("base64url")}`}decrypt(q){let z=D(q);if(!z)throw new N("malformed","The value is not an encrypted envelope.");if(!this.configured)this.requireCurrent();let J=this.keys.get(z.keyId);if(!J)throw new N("unknown_key",`The value was encrypted with key "${z.keyId}", which is not in encryption.keys (${I(this.keys)}). Keep a key configured until encryption:rotate has re-encrypted the values written with it.`);try{let Q=e(E,J,z.iv);return Q.setAAD(Buffer.from(`${j}:${z.keyId}`)),Q.setAuthTag(z.tag),Buffer.concat([Q.update(z.ciphertext),Q.final()]).toString("utf8")}catch{throw new N("invalid",`The value did not authenticate under key "${z.keyId}": it was altered, or encrypted with a different key under the same id.`)}}isEncrypted(q){return D(q)!==null}keyIdOf(q){return D(q)?.keyId??null}needsReencryption(q){return this.keyIdOf(q)!==this.requireCurrent()}requireCurrent(){if(this.currentId===void 0)throw new U("No encryption key is configured. Add app/config/encryption.ts (defineEncryptionConfig({ keys: { k1: process.env.APP_ENCRYPTION_KEY } })) and list it as `encryption` in your Kernel's config. Generate a key with `openssl rand -base64 32`.");return this.currentId}}class U extends Error{constructor(q){super(q);this.name="EncryptionKeyError"}}class N extends Error{reason;column;constructor(q,z){super(z);this.reason=q;this.name="DecryptionError"}}var j="v1",E="aes-256-gcm",f=32,y=12,A=16,u=/^[A-Za-z0-9_-]{1,32}$/,v=/^[A-Za-z0-9_-]+$/;function zq(q,z){if(typeof z!=="string"||z.trim()==="")throw new U(`Encryption key "${q}" is empty. Is the environment variable it reads set?`);let J=z.trim().replace(/^base64:/,""),Q=/^[A-Za-z0-9+/=_-]+$/.test(J)?Buffer.from(J,"base64"):Buffer.alloc(0);if(Q.length!==f)throw new U(`Encryption key "${q}" is not ${f} bytes of base64 (it decodes to ${Q.length}). Generate one with \`openssl rand -base64 32\`.`);return Q}function D(q){if(typeof q!=="string")return null;let z=q.split(":");if(z.length!==4||z[0]!==j)return null;let[,J,Q,Z]=z;if(!u.test(J)||!v.test(Q)||!v.test(Z))return null;let $=Buffer.from(Q,"base64url"),X=Buffer.from(Z,"base64url");if($.length!==y||X.length<A)return null;return{keyId:J,iv:$,ciphertext:X.subarray(0,X.length-A),tag:X.subarray(X.length-A)}}function I(q){return q.size===0?"none configured":[...q.keys()].map((z)=>`"${z}"`).join(", ")}function Jq(q){return q===null?"null":Array.isArray(q)?"an array":`a ${typeof q}`}var h=new WeakMap;function T(q){let z=h.get(q);if(z===void 0)z=Object.values(q.fields).filter((J)=>J.encrypted===!0).map((J)=>J.name),h.set(q,z);return z}function Mq(){let q=new Set,z=[];for(let J of x()){let Q=O(J);if(!Q||q.has(Q.name))continue;q.add(Q.name);for(let Z of T(Q))z.push(`${Q.name}.${Z}`)}return z}function c(){let q=p();if(!q.bound(Y))throw new U("Encrypted columns need an Encrypter, and none is bound in this application. A booted Kernel binds one from the `encryption` config slice; a hand-built Application can bind its own: `application.instance(Encrypter, new Encrypter({ keys: { k1: key } }))`.");return q.make(Y)}var l=Symbol("gemi.orm.encryptedColumnsRaw");function Nq(q){return{...q,[l]:!0}}function Vq(q){return typeof q==="object"&&q!==null&&q[l]===!0}function Lq(q,z,J){if(!P(J))return;let Q={model:q.name,operation:z};d(q,J,Q,0);for(let Z of["by","_min","_max","_avg","_sum"])if(J[Z]!==void 0)o(q,J[Z],Z,Q);if(J.having!==void 0)B(q,J.having,Q)}var w=64;function d(q,z,J,Q){if(Q>w)return;if(z.where!==void 0)W(q,z.where,"where",J,Q);if(z.cursor!==void 0)W(q,z.cursor,"cursor",J,Q);if(z.orderBy!==void 0)K(q,z.orderBy,J,Q);if(z.distinct!==void 0)o(q,z.distinct,"distinct",J);for(let Z of[z.include,z.select]){if(!P(Z))continue;for(let[$,X]of Object.entries(Z)){if(!P(X))continue;if($==="_count"){if(!P(X.select))continue;for(let[G,F]of Object.entries(X.select)){let H=R(q,G);if(H&&P(F)&&F.where!==void 0)W(H,F.where,"where",J,Q+1)}continue}let C=R(q,$);if(C)d(C,X,J,Q+1)}}}var Qq=["some","every","none","is","isNot"];function W(q,z,J,Q,Z){if(Z>w)return;if(Array.isArray(z)){for(let $ of z)W(q,$,J,Q,Z);return}if(!P(z))return;for(let[$,X]of Object.entries(z)){if(X===void 0)continue;if($==="AND"||$==="OR"||$==="NOT"){W(q,X,J,Q,Z);continue}let C=q.fields[$];if(C){if(C.encrypted===!0&&!t(X))L(q,$,J,Q);continue}let G=R(q,$);if(G){if(!P(X))continue;let F=Object.keys(X).filter((H)=>Qq.includes(H));if(F.length>0)for(let H of F)W(G,X[H],J,Q,Z+1);else W(G,X,J,Q,Z+1);continue}if(P(X)){for(let F of Object.keys(X))if(q.fields[F]?.encrypted===!0)L(q,F,J,Q)}}}function K(q,z,J,Q){if(Q>w)return;if(Array.isArray(z)){for(let Z of z)K(q,Z,J,Q);return}if(!P(z))return;for(let[Z,$]of Object.entries(z)){if(q.fields[Z]?.encrypted===!0)L(q,Z,"orderBy",J);let X=R(q,Z);if(X&&P($)&&!("_count"in $))K(X,$,J,Q+1)}}function o(q,z,J,Q){let Z=typeof z==="string"?[z]:Array.isArray(z)?z.filter(($)=>typeof $==="string"):P(z)?Object.keys(z).filter(($)=>z[$]):[];for(let $ of Z)if(q.fields[$]?.encrypted===!0)L(q,$,J,Q)}function B(q,z,J){if(Array.isArray(z)){for(let Q of z)B(q,Q,J);return}if(!P(z))return;for(let[Q,Z]of Object.entries(z)){if(Q==="AND"||Q==="OR"||Q==="NOT"){B(q,Z,J);continue}if(q.fields[Q]?.encrypted===!0&&!t(Z))L(q,Q,"having",J)}}function t(q){if(q===null)return!0;if(!P(q))return!1;let z=Object.entries(q).filter(([,J])=>J!==void 0);return z.length>0&&z.every(([J,Q])=>(J==="equals"||J==="not")&&Q===null)}function L(q,z,J,Q){throw new m(J,Q.model,Q.operation,`${q.name}.${z} is an encrypted column: each write stores a different random ciphertext, so the database cannot compare, sort or group by it. Only null checks work on it ({ ${z}: null } or { ${z}: { not: null } }). To look a row up by a secret, store a keyed hash of it in a separate column and filter on that.`)}function Yq(q,z,J){let Q=T(q);if(Q.length===0||!P(J))return J;let Z={model:q.name,operation:z},$,X=(F)=>($??=c()).encrypt(F),C=J,G=(F,H)=>{if(H===C[F])return;if(C===J)C={...J};C[F]=H};switch(z){case"create":case"update":case"updateMany":G("data",V(Q,J.data,X,Z));break;case"createMany":G("data",Array.isArray(J.data)?Zq(J.data,(F)=>V(Q,F,X,Z)):V(Q,J.data,X,Z));break;case"upsert":G("create",V(Q,J.create,X,Z)),G("update",V(Q,J.update,X,Z));break}return C}function V(q,z,J,Q){if(!P(z))return z;let Z;for(let $ of q){if(!($ in z))continue;let X=z[$],C=s($,X,J,Q);if(C!==X)(Z??={...z})[$]=C}return Z??z}function s(q,z,J,Q){if(z===void 0||z===null)return z;if(typeof z==="string")return J(z);if(P(z)&&Object.keys(z).length===1&&"set"in z){let Z=z.set;return Z===null||Z===void 0?z:{set:s(q,Z,J,Q)}}throw new g("data",Q.model,Q.operation,`${Q.model}.${q} is an encrypted column and takes a string or null (or { set: string | null }); got ${Cq(z)}.`)}function Zq(q,z){let J;return q.forEach((Q,Z)=>{let $=z(Q);if($!==Q)(J??=[...q])[Z]=$}),J??q}function $q(q,z){let J=T(q);if(J.length===0||z.length===0)return;let Q;for(let Z of z){if(!P(Z))continue;for(let $ of J){let X=Z[$];if(typeof X!=="string")continue;Q??=c();try{Z[$]=Q.decrypt(X)}catch(C){if(C instanceof N)C.column={model:q.name,field:$},C.message=`Could not decrypt ${q.name}.${$}: ${C.message}`;throw C}}}}function Xq(q,z){let J=O(q.model),Q=[];for(let Z of z){if(!P(Z))continue;let $=Z[q.as];if(Array.isArray($))Q.push(...$);else if(P($))Q.push($)}if(Q.length===0)return;if(J)$q(J,Q);for(let Z of q.folded??[])Xq(Z,Q)}function O(q){if(!S(q))return;return _(q).$schema}function R(q,z){let J=q.relations[z];return J?O(J.model):void 0}function P(q){return typeof q==="object"&&q!==null&&!Array.isArray(q)&&!(q instanceof Date)}function Cq(q){if(Array.isArray(q))return"an array";if(q instanceof Date)return"a Date";return`a ${typeof q}`}
3
- export{i as Yg,S as Zg,_ as _g,x as $g,b as ah,Y as bh,U as ch,N as dh,T as eh,Mq as fh,c as gh,Nq as hh,Vq as ih,Lq as jh,Yq as kh,$q as lh,Xq as mh};
2
+ import{Fh as k,kh as g,lh as m}from"./chunk-yds7zwc3.js";import{Pi as p}from"./chunk-nz8z8jr1.js";import{kj as n}from"./chunk-tewhms9w.js";var b={};n(b,{registeredNames:()=>x,register:()=>i,has:()=>S,get:()=>_,clearRegistry:()=>a});var M=new Map;function i(q,z){M.set(q,z)}function S(q){return M.has(q)}function _(q){let z=M.get(q);if(z===void 0)throw new k(q,[...M.keys()]);return z}function x(){return[...M.keys()]}function a(){M.clear()}import{createCipheriv as r,createDecipheriv as e,randomBytes as qq}from"crypto";class Y{static token="encrypter";keys=new Map;currentId;constructor(q={}){for(let[z,J]of Object.entries(q.keys??{})){if(!u.test(z))throw new U(`Encryption key id "${z}" is not valid. Use 1-32 letters, digits, "_" or "-": the id is written into every encrypted value.`);this.keys.set(z,zq(z,J))}if(q.current!==void 0){if(!this.keys.has(q.current))throw new U(`encryption.current is "${q.current}", but encryption.keys has no key by that id (${I(this.keys)}).`);this.currentId=q.current}else if(this.keys.size===1)this.currentId=[...this.keys.keys()][0];else if(this.keys.size>1)throw new U(`encryption.keys has ${this.keys.size} keys (${I(this.keys)}) and no encryption.current to say which one encrypts new values.`)}get configured(){return this.currentId!==void 0}get currentKeyId(){return this.requireCurrent()}encrypt(q){if(typeof q!=="string")throw TypeError(`Encrypter.encrypt takes a string, got ${Jq(q)}. Serialise other values first (JSON.stringify).`);let z=this.requireCurrent(),J=this.keys.get(z),Q=`${j}:${z}`,Z=qq(y),$=r(E,J,Z);$.setAAD(Buffer.from(Q));let X=Buffer.concat([$.update(q,"utf8"),$.final(),$.getAuthTag()]);return`${Q}:${Z.toString("base64url")}:${X.toString("base64url")}`}decrypt(q){let z=D(q);if(!z)throw new N("malformed","The value is not an encrypted envelope.");if(!this.configured)this.requireCurrent();let J=this.keys.get(z.keyId);if(!J)throw new N("unknown_key",`The value was encrypted with key "${z.keyId}", which is not in encryption.keys (${I(this.keys)}). Keep a key configured until encryption:rotate has re-encrypted the values written with it.`);try{let Q=e(E,J,z.iv);return Q.setAAD(Buffer.from(`${j}:${z.keyId}`)),Q.setAuthTag(z.tag),Buffer.concat([Q.update(z.ciphertext),Q.final()]).toString("utf8")}catch{throw new N("invalid",`The value did not authenticate under key "${z.keyId}": it was altered, or encrypted with a different key under the same id.`)}}isEncrypted(q){return D(q)!==null}keyIdOf(q){return D(q)?.keyId??null}needsReencryption(q){return this.keyIdOf(q)!==this.requireCurrent()}requireCurrent(){if(this.currentId===void 0)throw new U("No encryption key is configured. Add app/config/encryption.ts (defineEncryptionConfig({ keys: { k1: process.env.APP_ENCRYPTION_KEY } })) and list it as `encryption` in your Kernel's config. Generate a key with `openssl rand -base64 32`.");return this.currentId}}class U extends Error{constructor(q){super(q);this.name="EncryptionKeyError"}}class N extends Error{reason;column;constructor(q,z){super(z);this.reason=q;this.name="DecryptionError"}}var j="v1",E="aes-256-gcm",f=32,y=12,A=16,u=/^[A-Za-z0-9_-]{1,32}$/,v=/^[A-Za-z0-9_-]+$/;function zq(q,z){if(typeof z!=="string"||z.trim()==="")throw new U(`Encryption key "${q}" is empty. Is the environment variable it reads set?`);let J=z.trim().replace(/^base64:/,""),Q=/^[A-Za-z0-9+/=_-]+$/.test(J)?Buffer.from(J,"base64"):Buffer.alloc(0);if(Q.length!==f)throw new U(`Encryption key "${q}" is not ${f} bytes of base64 (it decodes to ${Q.length}). Generate one with \`openssl rand -base64 32\`.`);return Q}function D(q){if(typeof q!=="string")return null;let z=q.split(":");if(z.length!==4||z[0]!==j)return null;let[,J,Q,Z]=z;if(!u.test(J)||!v.test(Q)||!v.test(Z))return null;let $=Buffer.from(Q,"base64url"),X=Buffer.from(Z,"base64url");if($.length!==y||X.length<A)return null;return{keyId:J,iv:$,ciphertext:X.subarray(0,X.length-A),tag:X.subarray(X.length-A)}}function I(q){return q.size===0?"none configured":[...q.keys()].map((z)=>`"${z}"`).join(", ")}function Jq(q){return q===null?"null":Array.isArray(q)?"an array":`a ${typeof q}`}var h=new WeakMap;function T(q){let z=h.get(q);if(z===void 0)z=Object.values(q.fields).filter((J)=>J.encrypted===!0).map((J)=>J.name),h.set(q,z);return z}function Mq(){let q=new Set,z=[];for(let J of x()){let Q=O(J);if(!Q||q.has(Q.name))continue;q.add(Q.name);for(let Z of T(Q))z.push(`${Q.name}.${Z}`)}return z}function c(){let q=p();if(!q.bound(Y))throw new U("Encrypted columns need an Encrypter, and none is bound in this application. A booted Kernel binds one from the `encryption` config slice; a hand-built Application can bind its own: `application.instance(Encrypter, new Encrypter({ keys: { k1: key } }))`.");return q.make(Y)}var l=Symbol("gemi.orm.encryptedColumnsRaw");function Nq(q){return{...q,[l]:!0}}function Vq(q){return typeof q==="object"&&q!==null&&q[l]===!0}function Lq(q,z,J){if(!P(J))return;let Q={model:q.name,operation:z};d(q,J,Q,0);for(let Z of["by","_min","_max","_avg","_sum"])if(J[Z]!==void 0)o(q,J[Z],Z,Q);if(J.having!==void 0)B(q,J.having,Q)}var w=64;function d(q,z,J,Q){if(Q>w)return;if(z.where!==void 0)W(q,z.where,"where",J,Q);if(z.cursor!==void 0)W(q,z.cursor,"cursor",J,Q);if(z.orderBy!==void 0)K(q,z.orderBy,J,Q);if(z.distinct!==void 0)o(q,z.distinct,"distinct",J);for(let Z of[z.include,z.select]){if(!P(Z))continue;for(let[$,X]of Object.entries(Z)){if(!P(X))continue;if($==="_count"){if(!P(X.select))continue;for(let[G,F]of Object.entries(X.select)){let H=R(q,G);if(H&&P(F)&&F.where!==void 0)W(H,F.where,"where",J,Q+1)}continue}let C=R(q,$);if(C)d(C,X,J,Q+1)}}}var Qq=["some","every","none","is","isNot"];function W(q,z,J,Q,Z){if(Z>w)return;if(Array.isArray(z)){for(let $ of z)W(q,$,J,Q,Z);return}if(!P(z))return;for(let[$,X]of Object.entries(z)){if(X===void 0)continue;if($==="AND"||$==="OR"||$==="NOT"){W(q,X,J,Q,Z);continue}let C=q.fields[$];if(C){if(C.encrypted===!0&&!t(X))L(q,$,J,Q);continue}let G=R(q,$);if(G){if(!P(X))continue;let F=Object.keys(X).filter((H)=>Qq.includes(H));if(F.length>0)for(let H of F)W(G,X[H],J,Q,Z+1);else W(G,X,J,Q,Z+1);continue}if(P(X)){for(let F of Object.keys(X))if(q.fields[F]?.encrypted===!0)L(q,F,J,Q)}}}function K(q,z,J,Q){if(Q>w)return;if(Array.isArray(z)){for(let Z of z)K(q,Z,J,Q);return}if(!P(z))return;for(let[Z,$]of Object.entries(z)){if(q.fields[Z]?.encrypted===!0)L(q,Z,"orderBy",J);let X=R(q,Z);if(X&&P($)&&!("_count"in $))K(X,$,J,Q+1)}}function o(q,z,J,Q){let Z=typeof z==="string"?[z]:Array.isArray(z)?z.filter(($)=>typeof $==="string"):P(z)?Object.keys(z).filter(($)=>z[$]):[];for(let $ of Z)if(q.fields[$]?.encrypted===!0)L(q,$,J,Q)}function B(q,z,J){if(Array.isArray(z)){for(let Q of z)B(q,Q,J);return}if(!P(z))return;for(let[Q,Z]of Object.entries(z)){if(Q==="AND"||Q==="OR"||Q==="NOT"){B(q,Z,J);continue}if(q.fields[Q]?.encrypted===!0&&!t(Z))L(q,Q,"having",J)}}function t(q){if(q===null)return!0;if(!P(q))return!1;let z=Object.entries(q).filter(([,J])=>J!==void 0);return z.length>0&&z.every(([J,Q])=>(J==="equals"||J==="not")&&Q===null)}function L(q,z,J,Q){throw new m(J,Q.model,Q.operation,`${q.name}.${z} is an encrypted column: each write stores a different random ciphertext, so the database cannot compare, sort or group by it. Only null checks work on it ({ ${z}: null } or { ${z}: { not: null } }). To look a row up by a secret, store a keyed hash of it in a separate column and filter on that.`)}function Yq(q,z,J){let Q=T(q);if(Q.length===0||!P(J))return J;let Z={model:q.name,operation:z},$,X=(F)=>($??=c()).encrypt(F),C=J,G=(F,H)=>{if(H===C[F])return;if(C===J)C={...J};C[F]=H};switch(z){case"create":case"update":case"updateMany":G("data",V(Q,J.data,X,Z));break;case"createMany":G("data",Array.isArray(J.data)?Zq(J.data,(F)=>V(Q,F,X,Z)):V(Q,J.data,X,Z));break;case"upsert":G("create",V(Q,J.create,X,Z)),G("update",V(Q,J.update,X,Z));break}return C}function V(q,z,J,Q){if(!P(z))return z;let Z;for(let $ of q){if(!($ in z))continue;let X=z[$],C=s($,X,J,Q);if(C!==X)(Z??={...z})[$]=C}return Z??z}function s(q,z,J,Q){if(z===void 0||z===null)return z;if(typeof z==="string")return J(z);if(P(z)&&Object.keys(z).length===1&&"set"in z){let Z=z.set;return Z===null||Z===void 0?z:{set:s(q,Z,J,Q)}}throw new g("data",Q.model,Q.operation,`${Q.model}.${q} is an encrypted column and takes a string or null (or { set: string | null }); got ${Cq(z)}.`)}function Zq(q,z){let J;return q.forEach((Q,Z)=>{let $=z(Q);if($!==Q)(J??=[...q])[Z]=$}),J??q}function $q(q,z){let J=T(q);if(J.length===0||z.length===0)return;let Q;for(let Z of z){if(!P(Z))continue;for(let $ of J){let X=Z[$];if(typeof X!=="string")continue;Q??=c();try{Z[$]=Q.decrypt(X)}catch(C){if(C instanceof N)C.column={model:q.name,field:$},C.message=`Could not decrypt ${q.name}.${$}: ${C.message}`;throw C}}}}function Xq(q,z){let J=O(q.model),Q=[];for(let Z of z){if(!P(Z))continue;let $=Z[q.as];if(Array.isArray($))Q.push(...$);else if(P($))Q.push($)}if(Q.length===0)return;if(J)$q(J,Q);for(let Z of q.folded??[])Xq(Z,Q)}function O(q){if(!S(q))return;return _(q).$schema}function R(q,z){let J=q.relations[z];return J?O(J.model):void 0}function P(q){return typeof q==="object"&&q!==null&&!Array.isArray(q)&&!(q instanceof Date)}function Cq(q){if(Array.isArray(q))return"an array";if(q instanceof Date)return"a Date";return`a ${typeof q}`}
3
+ export{i as Ug,S as Vg,_ as Wg,x as Xg,b as Yg,Y as Zg,U as _g,N as $g,T as ah,Mq as bh,c as ch,Nq as dh,Vq as eh,Lq as fh,Yq as gh,$q as hh,Xq as ih};
4
4
 
5
- //# debugId=CC9B8AE61D6011C264756E2164756E21
5
+ //# debugId=2F03E14C3C283B2A64756E2164756E21
@@ -7,6 +7,6 @@
7
7
  "import { app } from \"../foundation/app\";\nimport {\n DecryptionError,\n Encrypter,\n EncryptionKeyError,\n} from \"../services/encryption/Encrypter\";\nimport { InvalidArgumentError, UnsupportedByDesignError } from \"./errors\";\nimport * as registry from \"./registry\";\nimport type { ModelSchema } from \"./schema\";\n\n/**\n * Encrypted columns: a `String` field marked `/// @gemi.encrypted` in the\n * Prisma schema is stored as an `Encrypter` envelope and read back as the\n * plaintext.\n *\n * Applied in `Model.$exec`, per model, at the two places a value crosses the\n * boundary:\n *\n * - **Writes** encrypt the model's *own* columns in `data` (and an upsert's\n * `create` / `update`). A nested write into a related model is not touched\n * here: every nested write runs through the related model's own `$exec`,\n * which encrypts its own columns, so encrypting it here as well would\n * encrypt it twice.\n * - **Reads** decrypt the model's own rows after shaping. A batched `include`\n * comes back through the child's `$exec` and is already decrypted; a folded\n * (lateral) one never enters it, so the parent decrypts those rows on the\n * child's behalf (`decryptFolded`) — the same split `redactFolded` handles\n * for policies.\n *\n * The schema, not the model class, says which columns are encrypted. That is\n * deliberate: a column that is encrypted when written through `FigmaConnection`\n * and plaintext when written through `FigmaConnectionModel` is not encrypted\n * at rest. The generated base, the subclass and every `Model.on(...)` variant\n * share one `$schema`, so none of them can write the column in the clear.\n *\n * A filter, sort or grouping on an encrypted column is refused: every write\n * stores a different random ciphertext, so the database cannot compare it to\n * anything. A null check is the exception, because a NULL column is stored as\n * NULL.\n */\n\nconst fieldsBySchema = new WeakMap<ModelSchema, readonly string[]>();\n\n/** The schema's encrypted fields, in declaration order. Empty for most models. */\nexport function encryptedFields(schema: ModelSchema): readonly string[] {\n let fields = fieldsBySchema.get(schema);\n if (fields === undefined) {\n fields = Object.values(schema.fields)\n .filter((field) => field.encrypted === true)\n .map((field) => field.name);\n fieldsBySchema.set(schema, fields);\n }\n return fields;\n}\n\n/** `Model.field` for every encrypted column of every registered model. */\nexport function encryptedColumnsInRegistry(): string[] {\n const seen = new Set<string>();\n const columns: string[] = [];\n for (const name of registry.registeredNames()) {\n const schema = schemaOf(name);\n if (!schema || seen.has(schema.name)) continue;\n seen.add(schema.name);\n for (const field of encryptedFields(schema)) columns.push(`${schema.name}.${field}`);\n }\n return columns;\n}\n\n/**\n * The application's `Encrypter`. An application booted without the\n * framework's providers (a test harness that binds only the database) gets a\n * typed error naming the fix rather than a container error.\n */\nexport function currentEncrypter(): Encrypter {\n const application = app();\n if (!application.bound(Encrypter)) {\n throw new EncryptionKeyError(\n \"Encrypted columns need an Encrypter, and none is bound in this \" +\n \"application. A booted Kernel binds one from the `encryption` config \" +\n \"slice; a hand-built Application can bind its own: \" +\n \"`application.instance(Encrypter, new Encrypter({ keys: { k1: key } }))`.\",\n );\n }\n return application.make(Encrypter);\n}\n\n// --- the internal raw mode ---------------------------------------------------\n\n/**\n * Marks an `$exec` call as reading and writing encrypted columns *as stored*:\n * no decryption of results, no encryption of `data`, and filters on encrypted\n * columns allowed (compared against the envelope). Used by `encryption:rotate`\n * to compare-and-swap one envelope for another. A module-private symbol, like\n * the other `$exec` markers, so an application cannot set it.\n */\nconst RAW = Symbol(\"gemi.orm.encryptedColumnsRaw\");\n\nexport function markEncryptionRaw<T extends object>(options: T): T {\n return { ...options, [RAW]: true };\n}\n\nexport function isEncryptionRaw(options: unknown): boolean {\n return (\n typeof options === \"object\" &&\n options !== null &&\n (options as Record<symbol, unknown>)[RAW] === true\n );\n}\n\n// --- refusing filters --------------------------------------------------------\n\ninterface Origin {\n model: string;\n operation: string;\n}\n\n/**\n * Refuses any argument that would make the database compare, sort or group an\n * encrypted column: `where` (including relation filters into other models),\n * `orderBy`, `distinct`, `cursor`, `groupBy`'s `by` and `having`, the\n * `_min` / `_max` aggregates, and the same arguments nested inside an\n * `include` or `select`.\n *\n * Walked whether or not this model has encrypted columns, because a relation\n * filter or an include reaches other models'.\n */\nexport function assertNoEncryptedFilters(schema: ModelSchema, op: string, args: unknown): void {\n if (!isObject(args)) return;\n const origin: Origin = { model: schema.name, operation: op };\n readArgs(schema, args, origin, 0);\n for (const key of [\"by\", \"_min\", \"_max\", \"_avg\", \"_sum\"]) {\n if (args[key] !== undefined) fieldList(schema, args[key], key, origin);\n }\n if (args.having !== undefined) having(schema, args.having, origin);\n}\n\n/** Generous: relation depth is bounded by `MAX_RELATION_DEPTH` long before this. */\nconst MAX_WALK_DEPTH = 64;\n\nfunction readArgs(schema: ModelSchema, args: Record<string, any>, origin: Origin, depth: number) {\n if (depth > MAX_WALK_DEPTH) return;\n if (args.where !== undefined) where(schema, args.where, \"where\", origin, depth);\n if (args.cursor !== undefined) where(schema, args.cursor, \"cursor\", origin, depth);\n if (args.orderBy !== undefined) orderBy(schema, args.orderBy, origin, depth);\n if (args.distinct !== undefined) fieldList(schema, args.distinct, \"distinct\", origin);\n\n for (const projection of [args.include, args.select]) {\n if (!isObject(projection)) continue;\n for (const [key, value] of Object.entries(projection)) {\n if (!isObject(value)) continue;\n if (key === \"_count\") {\n if (!isObject(value.select)) continue;\n for (const [name, count] of Object.entries(value.select)) {\n const target = relationTarget(schema, name);\n if (target && isObject(count) && count.where !== undefined) {\n where(target, count.where, \"where\", origin, depth + 1);\n }\n }\n continue;\n }\n const target = relationTarget(schema, key);\n if (target) readArgs(target, value, origin, depth + 1);\n }\n }\n}\n\nconst RELATION_FILTERS = [\"some\", \"every\", \"none\", \"is\", \"isNot\"];\n\nfunction where(\n schema: ModelSchema,\n node: unknown,\n argument: string,\n origin: Origin,\n depth: number,\n): void {\n if (depth > MAX_WALK_DEPTH) return;\n if (Array.isArray(node)) {\n for (const item of node) where(schema, item, argument, origin, depth);\n return;\n }\n if (!isObject(node)) return;\n\n for (const [key, value] of Object.entries(node)) {\n if (value === undefined) continue;\n\n if (key === \"AND\" || key === \"OR\" || key === \"NOT\") {\n where(schema, value, argument, origin, depth);\n continue;\n }\n\n const field = schema.fields[key];\n if (field) {\n if (field.encrypted === true && !isNullCheck(value)) {\n refuse(schema, key, argument, origin);\n }\n continue;\n }\n\n const target = relationTarget(schema, key);\n if (target) {\n if (!isObject(value)) continue;\n const filters = Object.keys(value).filter((name) => RELATION_FILTERS.includes(name));\n if (filters.length > 0) {\n for (const name of filters) where(target, value[name], argument, origin, depth + 1);\n } else {\n where(target, value, argument, origin, depth + 1);\n }\n continue;\n }\n\n // A compound unique key — `provider_providerId: { provider, providerId }`.\n if (isObject(value)) {\n for (const name of Object.keys(value)) {\n if (schema.fields[name]?.encrypted === true) refuse(schema, name, argument, origin);\n }\n }\n }\n}\n\nfunction orderBy(schema: ModelSchema, node: unknown, origin: Origin, depth: number): void {\n if (depth > MAX_WALK_DEPTH) return;\n if (Array.isArray(node)) {\n for (const item of node) orderBy(schema, item, origin, depth);\n return;\n }\n if (!isObject(node)) return;\n for (const [key, value] of Object.entries(node)) {\n if (schema.fields[key]?.encrypted === true) refuse(schema, key, \"orderBy\", origin);\n const target = relationTarget(schema, key);\n if (target && isObject(value) && !(\"_count\" in value)) {\n orderBy(target, value, origin, depth + 1);\n }\n }\n}\n\n/** `distinct`, `by`, and the `_min` / `_max` / `_avg` / `_sum` selections. */\nfunction fieldList(schema: ModelSchema, node: unknown, argument: string, origin: Origin): void {\n const names =\n typeof node === \"string\"\n ? [node]\n : Array.isArray(node)\n ? node.filter((name): name is string => typeof name === \"string\")\n : isObject(node)\n ? Object.keys(node).filter((name) => node[name])\n : [];\n for (const name of names) {\n if (schema.fields[name]?.encrypted === true) refuse(schema, name, argument, origin);\n }\n}\n\nfunction having(schema: ModelSchema, node: unknown, origin: Origin): void {\n if (Array.isArray(node)) {\n for (const item of node) having(schema, item, origin);\n return;\n }\n if (!isObject(node)) return;\n for (const [key, value] of Object.entries(node)) {\n if (key === \"AND\" || key === \"OR\" || key === \"NOT\") {\n having(schema, value, origin);\n continue;\n }\n if (schema.fields[key]?.encrypted === true && !isNullCheck(value)) {\n refuse(schema, key, \"having\", origin);\n }\n }\n}\n\n/** `null`, `{ equals: null }`, `{ not: null }` — the only comparisons a ciphertext supports. */\nfunction isNullCheck(value: unknown): boolean {\n if (value === null) return true;\n if (!isObject(value)) return false;\n const entries = Object.entries(value).filter(([, operand]) => operand !== undefined);\n return (\n entries.length > 0 &&\n entries.every(([operator, operand]) => (operator === \"equals\" || operator === \"not\") && operand === null)\n );\n}\n\nfunction refuse(schema: ModelSchema, field: string, argument: string, origin: Origin): never {\n throw new UnsupportedByDesignError(\n argument,\n origin.model,\n origin.operation,\n `${schema.name}.${field} is an encrypted column: each write stores a ` +\n `different random ciphertext, so the database cannot compare, sort or ` +\n `group by it. Only null checks work on it ({ ${field}: null } or ` +\n `{ ${field}: { not: null } }). To look a row up by a secret, store a ` +\n `keyed hash of it in a separate column and filter on that.`,\n );\n}\n\n// --- writes ------------------------------------------------------------------\n\n/**\n * `args` with this model's encrypted columns encrypted, or `args` itself when\n * there is nothing to encrypt. Never mutates the caller's objects: the same\n * `data` may be reused for a second call.\n *\n * Only `data` (and an upsert's `create` / `update`) at this level. Nested\n * relation writes are left as they are; see the note at the top of the file.\n */\nexport function encryptWriteArgs(schema: ModelSchema, op: string, args: any): any {\n const fields = encryptedFields(schema);\n if (fields.length === 0 || !isObject(args)) return args;\n\n const origin: Origin = { model: schema.name, operation: op };\n let encrypter: Encrypter | undefined;\n const encrypt = (value: string) => (encrypter ??= currentEncrypter()).encrypt(value);\n\n let next = args;\n const replace = (key: string, value: unknown) => {\n if (value === next[key]) return;\n if (next === args) next = { ...args };\n next[key] = value;\n };\n\n switch (op) {\n case \"create\":\n case \"update\":\n case \"updateMany\":\n replace(\"data\", encryptData(fields, args.data, encrypt, origin));\n break;\n case \"createMany\":\n replace(\n \"data\",\n Array.isArray(args.data)\n ? mapIfChanged(args.data, (row) => encryptData(fields, row, encrypt, origin))\n : encryptData(fields, args.data, encrypt, origin),\n );\n break;\n case \"upsert\":\n replace(\"create\", encryptData(fields, args.create, encrypt, origin));\n replace(\"update\", encryptData(fields, args.update, encrypt, origin));\n break;\n }\n return next;\n}\n\nfunction encryptData(\n fields: readonly string[],\n data: unknown,\n encrypt: (value: string) => string,\n origin: Origin,\n): unknown {\n if (!isObject(data)) return data;\n let copy: Record<string, unknown> | undefined;\n for (const name of fields) {\n if (!(name in data)) continue;\n const value = data[name];\n const next = encryptValue(name, value, encrypt, origin);\n if (next !== value) (copy ??= { ...data })[name] = next;\n }\n return copy ?? data;\n}\n\nfunction encryptValue(\n field: string,\n value: unknown,\n encrypt: (value: string) => string,\n origin: Origin,\n): unknown {\n if (value === undefined || value === null) return value;\n if (typeof value === \"string\") return encrypt(value);\n // Prisma's `{ set: value }` spelling of a scalar update.\n if (isObject(value) && Object.keys(value).length === 1 && \"set\" in value) {\n const set = value.set;\n return set === null || set === undefined ? value : { set: encryptValue(field, set, encrypt, origin) };\n }\n throw new InvalidArgumentError(\n \"data\",\n origin.model,\n origin.operation,\n `${origin.model}.${field} is an encrypted column and takes a string or ` +\n `null (or { set: string | null }); got ${describe(value)}.`,\n );\n}\n\nfunction mapIfChanged<T>(items: T[], fn: (item: T) => T): T[] {\n let copy: T[] | undefined;\n items.forEach((item, index) => {\n const next = fn(item);\n if (next !== item) (copy ??= [...items])[index] = next;\n });\n return copy ?? items;\n}\n\n// --- reads -------------------------------------------------------------------\n\n/**\n * Decrypts this model's encrypted columns on `rows`, in place. A value that\n * does not decrypt raises `DecryptionError` naming the column — a ciphertext\n * is never handed back as if it were the value.\n */\nexport function decryptRows(schema: ModelSchema, rows: readonly unknown[]): void {\n const fields = encryptedFields(schema);\n if (fields.length === 0 || rows.length === 0) return;\n\n let encrypter: Encrypter | undefined;\n for (const row of rows) {\n if (!isObject(row)) continue;\n for (const field of fields) {\n const value = row[field];\n if (typeof value !== \"string\") continue;\n encrypter ??= currentEncrypter();\n try {\n row[field] = encrypter.decrypt(value);\n } catch (error) {\n if (error instanceof DecryptionError) {\n error.column = { model: schema.name, field };\n error.message = `Could not decrypt ${schema.name}.${field}: ${error.message}`;\n }\n throw error;\n }\n }\n }\n}\n\n/**\n * Decrypts the rows a strategy folded into the parent's statement, which never\n * passed through their own model's `$exec`. Recursive, because the fold is.\n */\nexport function decryptFolded(\n relation: { as: string; model: string; folded?: readonly { as: string; model: string; folded?: readonly unknown[] }[] },\n parents: readonly unknown[],\n): void {\n const schema = schemaOf(relation.model);\n const rows: unknown[] = [];\n for (const parent of parents) {\n if (!isObject(parent)) continue;\n const value = parent[relation.as];\n if (Array.isArray(value)) rows.push(...value);\n else if (isObject(value)) rows.push(value);\n }\n if (rows.length === 0) return;\n if (schema) decryptRows(schema, rows);\n for (const child of relation.folded ?? []) {\n decryptFolded(child as Parameters<typeof decryptFolded>[0], rows);\n }\n}\n\n// --- helpers -----------------------------------------------------------------\n\nfunction schemaOf(model: string): ModelSchema | undefined {\n if (!registry.has(model)) return undefined;\n return registry.get<{ $schema?: ModelSchema }>(model).$schema;\n}\n\nfunction relationTarget(schema: ModelSchema, name: string): ModelSchema | undefined {\n const relation = schema.relations[name];\n return relation ? schemaOf(relation.model) : undefined;\n}\n\nfunction isObject(value: unknown): value is Record<string, any> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value) && !(value instanceof Date);\n}\n\nfunction describe(value: unknown): string {\n if (Array.isArray(value)) return \"an array\";\n if (value instanceof Date) return \"a Date\";\n return `a ${typeof value}`;\n}\n"
8
8
  ],
9
9
  "mappings": ";oPAeA,FAAM,JAAS,IAAI,IAEZ,SAAS,CAAQ,CAAC,EAAc,EAAsB,CAC3D,EAAO,IAAI,EAAM,CAAK,EAGjB,SAAS,CAAG,CAAC,EAAuB,CACzC,OAAO,EAAO,IAAI,CAAI,EAGjB,SAAS,CAAgB,CAAC,EAAiB,CAChD,IAAM,EAAQ,EAAO,IAAI,CAAI,EAC7B,GAAI,IAAU,OACZ,MAAM,IAAI,EAAwB,EAAM,CAAC,GAAG,EAAO,KAAK,CAAC,CAAC,EAE5D,OAAO,EAGF,SAAS,CAAe,EAAa,CAC1C,MAAO,CAAC,GAAG,EAAO,KAAK,CAAC,EAGnB,SAAS,CAAa,EAAS,CACpC,EAAO,MAAM,ECtCf,yBAAS,sBAAgB,iBAAkB,gBA2BpC,MAAM,CAAU,OACd,OAAQ,YAEE,KAAO,IAAI,IACX,UAOjB,WAAW,CAAC,EAA2B,CAAC,EAAG,CACzC,QAAY,EAAI,KAAU,OAAO,QAAQ,EAAO,MAAQ,CAAC,CAAC,EAAG,CAC3D,GAAI,CAAC,EAAO,KAAK,CAAE,EACjB,MAAM,IAAI,EACR,sBAAsB,sGAExB,EAEF,KAAK,KAAK,IAAI,EAAI,GAAS,EAAI,CAAK,CAAC,EAGvC,GAAI,EAAO,UAAY,OAAW,CAChC,GAAI,CAAC,KAAK,KAAK,IAAI,EAAO,OAAO,EAC/B,MAAM,IAAI,EACR,0BAA0B,EAAO,wDACT,EAAY,KAAK,IAAI,KAC/C,EAEF,KAAK,UAAY,EAAO,QACnB,QAAI,KAAK,KAAK,OAAS,EA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,aAAiB,MAGpG,SAAS,EAAQ,CAAC,EAAwB,CACxC,GAAI,MAAM,QAAQ,CAAK,EAAG,MAAO,WACjC,GAAI,aAAiB,KAAM,MAAO,SAClC,MAAO,KAAK,OAAO",
10
- "debugId": "CC9B8AE61D6011C264756E2164756E21",
10
+ "debugId": "2F03E14C3C283B2A64756E2164756E21",
11
11
  "names": []
12
12
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{kj as P}from"./chunk-j5q5ysng.js";class F{provider="custom";supportsIdempotencyKey=!1;async deliver(j){let x=await this.send(j);return{ok:Boolean(x),id:null}}}class G extends F{apiKey;provider="resend";supportsIdempotencyKey=!0;constructor(j=process.env.RESEND_API_KEY){super();this.apiKey=j}async send(j){return(await this.deliver(j)).ok}async deliver(j){let{Resend:x}=await import("./chunk-14xk8kq0.js"),A=new x(this.apiKey),{idempotencyKey:z,...N}=j,{data:H,error:B}=await A.emails.send(N,z?{idempotencyKey:z}:void 0);if(B)return console.error(B),{ok:!1,id:null,error:B};if(H)return{ok:!0,id:H.id??null};return{ok:!1,id:null}}}function Z(j){return j}function J(){return{driver:new G,headers:{},filterRecipients:(j)=>j}}function Q(j){for(let x=j;x;x=Object.getPrototypeOf(x)){let A=Object.prototype.hasOwnProperty.call(x,"deliver"),z=Object.prototype.hasOwnProperty.call(x,"send");if(A)return!1;if(z)return!0}return!0}async function M(j,x){if(typeof j.deliver==="function"&&!Q(j))return j.deliver(x);return{ok:Boolean(await j.send(x)),id:null}}class U{static token="mail";driver;headers;recipientFilter;constructor(j={}){let x=J();this.driver=j.driver??x.driver,this.headers=j.headers??x.headers,this.recipientFilter=j.filterRecipients??x.filterRecipients}filterRecipients(j){return this.recipientFilter(j)}send(j){return this.driver.send(j)}async deliver(j){return M(this.driver,j)}}
3
- export{F as Ei,G as Fi,Z as Gi,J as Hi,M as Ii,U as Ji};
2
+ import{mj as P}from"./chunk-tewhms9w.js";class F{provider="custom";supportsIdempotencyKey=!1;async deliver(j){let x=await this.send(j);return{ok:Boolean(x),id:null}}}class G extends F{apiKey;provider="resend";supportsIdempotencyKey=!0;constructor(j=process.env.RESEND_API_KEY){super();this.apiKey=j}async send(j){return(await this.deliver(j)).ok}async deliver(j){let{Resend:x}=await import("./chunk-0yj0s1pn.js"),A=new x(this.apiKey),{idempotencyKey:z,...N}=j,{data:H,error:B}=await A.emails.send(N,z?{idempotencyKey:z}:void 0);if(B)return console.error(B),{ok:!1,id:null,error:B};if(H)return{ok:!0,id:H.id??null};return{ok:!1,id:null}}}function Z(j){return j}function J(){return{driver:new G,headers:{},filterRecipients:(j)=>j}}function Q(j){for(let x=j;x;x=Object.getPrototypeOf(x)){let A=Object.prototype.hasOwnProperty.call(x,"deliver"),z=Object.prototype.hasOwnProperty.call(x,"send");if(A)return!1;if(z)return!0}return!0}async function M(j,x){if(typeof j.deliver==="function"&&!Q(j))return j.deliver(x);return{ok:Boolean(await j.send(x)),id:null}}class U{static token="mail";driver;headers;recipientFilter;constructor(j={}){let x=J();this.driver=j.driver??x.driver,this.headers=j.headers??x.headers,this.recipientFilter=j.filterRecipients??x.filterRecipients}filterRecipients(j){return this.recipientFilter(j)}send(j){return this.driver.send(j)}async deliver(j){return M(this.driver,j)}}
3
+ export{F as Ai,G as Bi,Z as Ci,J as Di,M as Ei,U as Fi};
4
4
 
5
- //# debugId=C1FA984869FC252964756E2164756E21
5
+ //# debugId=45A5C471AE26169A64756E2164756E21
@@ -9,6 +9,6 @@
9
9
  "import { mailConfigDefaults, type MailConfig } from \"./config\";\nimport { deliverThrough } from \"./deliver\";\nimport type { EmailDriver } from \"./drivers/EmailDriver\";\nimport type { EmailDeliveryResult, SendEmailParams } from \"./drivers/types\";\n\nexport class MailManager {\n static token = \"mail\";\n\n readonly driver: EmailDriver;\n readonly headers: Record<string, string>;\n\n private readonly recipientFilter: NonNullable<MailConfig[\"filterRecipients\"]>;\n\n constructor(config: MailConfig = {}) {\n const defaults = mailConfigDefaults();\n\n this.driver = config.driver ?? defaults.driver;\n this.headers = config.headers ?? defaults.headers;\n this.recipientFilter = config.filterRecipients ?? defaults.filterRecipients;\n }\n\n filterRecipients(emails: string[]): Promise<Array<string>> | Array<string> {\n return this.recipientFilter(emails);\n }\n\n send(params: SendEmailParams) {\n return this.driver.send(params);\n }\n\n /** Like `send`, but reports the outcome and the provider's message id. */\n async deliver(params: SendEmailParams): Promise<EmailDeliveryResult> {\n // A driver that doesn't extend `EmailDriver`, or a subclass that only\n // overrides `send`, is called through `send`.\n return deliverThrough(this.driver, params);\n }\n}\n"
10
10
  ],
11
11
  "mappings": ";yCAEO,MAAe,CAAY,CAKvB,SAAmB,SAMnB,uBAAkC,QASrC,QAAO,CAAC,EAAuD,CACnE,IAAM,EAAK,MAAM,KAAK,KAAK,CAAM,EACjC,MAAO,CAAE,GAAI,QAAQ,CAAE,EAAG,GAAI,IAAK,EAEvC,CCvBO,MAAM,UAAqB,CAAY,CAIxB,OAHF,SAAW,SACX,uBAAyB,GAE3C,WAAW,CAAS,EAAS,QAAQ,IAAI,eAAgB,CACvD,MAAM,EADY,mBAId,KAAI,CAAC,EAAyB,CAClC,OAAQ,MAAM,KAAK,QAAQ,CAAM,GAAG,QAGvB,QAAO,CAAC,EAAuD,CAO5E,IAAQ,UAAW,KAAa,+BAC1B,EAAS,IAAI,EAAO,KAAK,MAAM,GAG7B,oBAAmB,GAAY,GAC/B,OAAM,SAAU,MAAM,EAAO,OAAO,KAC1C,EACA,EAAiB,CAAE,gBAAe,EAAI,MACxC,EAEA,GAAI,EAEF,OADA,QAAQ,MAAM,CAAK,EACZ,CAAE,GAAI,GAAO,GAAI,KAAM,OAAM,EAGtC,GAAI,EACF,MAAO,CAAE,GAAI,GAAM,GAAI,EAAK,IAAM,IAAK,EAGzC,MAAO,CAAE,GAAI,GAAO,GAAI,IAAK,EAEjC,CC7BO,SAAS,CAAgB,CAAC,EAAgC,CAC/D,OAAO,EAGF,SAAS,CAAkB,EAAyB,CACzD,MAAO,CACL,OAAQ,IAAI,EACZ,QAAS,CAAC,EACV,iBAAkB,CAAC,IAAW,CAChC,ECVF,SAAS,CAAgB,CAAC,EAAgB,CACxC,QAAS,EAAQ,EAAQ,EAAO,EAAQ,OAAO,eAAe,CAAK,EAAG,CACpE,IAAM,EAAa,OAAO,UAAU,eAAe,KAAK,EAAO,SAAS,EAClE,EAAU,OAAO,UAAU,eAAe,KAAK,EAAO,MAAM,EAClE,GAAI,EAAY,MAAO,GACvB,GAAI,EAAS,MAAO,GAEtB,MAAO,GAOT,eAAsB,CAAc,CAClC,EACA,EAC8B,CAC9B,GAAI,OAAO,EAAO,UAAY,YAAc,CAAC,EAAiB,CAAM,EAClE,OAAO,EAAO,QAAQ,CAAM,EAE9B,MAAO,CAAE,GAAI,QAAQ,MAAM,EAAO,KAAK,CAAM,CAAC,EAAG,GAAI,IAAK,EC7BrD,MAAM,CAAY,OAChB,OAAQ,OAEN,OACA,QAEQ,gBAEjB,WAAW,CAAC,EAAqB,CAAC,EAAG,CACnC,IAAM,EAAW,EAAmB,EAEpC,KAAK,OAAS,EAAO,QAAU,EAAS,OACxC,KAAK,QAAU,EAAO,SAAW,EAAS,QAC1C,KAAK,gBAAkB,EAAO,kBAAoB,EAAS,iBAG7D,gBAAgB,CAAC,EAA0D,CACzE,OAAO,KAAK,gBAAgB,CAAM,EAGpC,IAAI,CAAC,EAAyB,CAC5B,OAAO,KAAK,OAAO,KAAK,CAAM,OAI1B,QAAO,CAAC,EAAuD,CAGnE,OAAO,EAAe,KAAK,OAAQ,CAAM,EAE7C",
12
- "debugId": "C1FA984869FC252964756E2164756E21",
12
+ "debugId": "45A5C471AE26169A64756E2164756E21",
13
13
  "names": []
14
14
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{gh as R}from"./chunk-6pqbsc5y.js";import{Oh as L}from"./chunk-q6a30w8w.js";import{ti as T}from"./chunk-fmea4sak.js";import{Ti as F}from"./chunk-zb8zzf5x.js";class N{rows=new Map;async find(j,B){for(let G of this.rows.values())if(G.userId===j&&G.provider===B)return{...G};return null}async list(j){return[...this.rows.values()].filter((B)=>B.userId===j).map((B)=>({...B}))}async save(j,B,G){let Q=await this.find(j,B),K=new Date,V={id:Q?.id??Bun.randomUUIDv7(),userId:j,provider:B,...S(G),needsReconnect:!1,revision:(Q?.revision??0)+1,createdAt:Q?.createdAt??K,updatedAt:K};return this.rows.set(V.id,V),{...V}}async updateTokens(j,B,G){let Q=this.rows.get(j);if(!Q||Q.revision!==B)return null;let K={...Q,...S(G),needsReconnect:!1,revision:B+1,updatedAt:new Date};return this.rows.set(j,K),{...K}}async markNeedsReconnect(j){let B=this.rows.get(j);if(B)this.rows.set(j,{...B,needsReconnect:!0,updatedAt:new Date})}async delete(j){this.rows.delete(j)}}class H{encrypter;table;sql;dialect;constructor(j,B,G={}){this.encrypter=B;let Q=G.table??"gemi_oauth_connections";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The connections table name "${Q}" is not a plain identifier.`);this.table=Q,this.sql=j.sql,this.dialect=j.dialect}async createTable(){for(let j of A(this.dialect,this.table))await this.sql.unsafe(j)}async find(j,B){let G=this.sql,Q=await G`
2
+ import{ch as R}from"./chunk-19dpzp4y.js";import{Kh as L}from"./chunk-meg8rtr6.js";import{pi as T}from"./chunk-gc2dz11k.js";import{Pi as F}from"./chunk-nz8z8jr1.js";class N{rows=new Map;async find(j,B){for(let G of this.rows.values())if(G.userId===j&&G.provider===B)return{...G};return null}async list(j){return[...this.rows.values()].filter((B)=>B.userId===j).map((B)=>({...B}))}async save(j,B,G){let Q=await this.find(j,B),K=new Date,V={id:Q?.id??Bun.randomUUIDv7(),userId:j,provider:B,...S(G),needsReconnect:!1,revision:(Q?.revision??0)+1,createdAt:Q?.createdAt??K,updatedAt:K};return this.rows.set(V.id,V),{...V}}async updateTokens(j,B,G){let Q=this.rows.get(j);if(!Q||Q.revision!==B)return null;let K={...Q,...S(G),needsReconnect:!1,revision:B+1,updatedAt:new Date};return this.rows.set(j,K),{...K}}async markNeedsReconnect(j){let B=this.rows.get(j);if(B)this.rows.set(j,{...B,needsReconnect:!0,updatedAt:new Date})}async delete(j){this.rows.delete(j)}}class H{encrypter;table;sql;dialect;constructor(j,B,G={}){this.encrypter=B;let Q=G.table??"gemi_oauth_connections";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The connections table name "${Q}" is not a plain identifier.`);this.table=Q,this.sql=j.sql,this.dialect=j.dialect}async createTable(){for(let j of A(this.dialect,this.table))await this.sql.unsafe(j)}async find(j,B){let G=this.sql,Q=await G`
3
3
  SELECT * FROM ${this.name(G)} WHERE user_id = ${j} AND provider = ${B}
4
4
  `;return Q[0]?this.decode(Q[0]):null}async list(j){let B=this.sql;return(await B`
5
5
  SELECT * FROM ${this.name(B)} WHERE user_id = ${j} ORDER BY provider
@@ -66,6 +66,6 @@ import{gh as R}from"./chunk-6pqbsc5y.js";import{Oh as L}from"./chunk-q6a30w8w.js
66
66
  "created_at" BIGINT NOT NULL,
67
67
  "updated_at" BIGINT NOT NULL${Q}
68
68
  )`,`CREATE UNIQUE INDEX IF NOT EXISTS "${B}_user_id_provider_key" ON "${B}"("user_id", "provider")`]}class Z extends Error{code;status;providerError;constructor(j,B,G={}){super(B,G.cause!==void 0?{cause:G.cause}:void 0);this.code=j;this.name="OAuthConnectionError",this.status=G.status,this.providerError=G.providerError}}class $ extends Z{provider;constructor(j,B={}){super("reconnect_required",`The ${j} connection needs to be reconnected: its tokens were refused and could not be refreshed.`,B);this.provider=j;this.name="OAuthReconnectRequiredError"}}class O{config;constructor(j){for(let B of["authorizeUrl","tokenUrl"])U(B,j[B]);if(j.revokeUrl!==void 0)U("revokeUrl",j.revokeUrl);if(j.apiBaseUrl===void 0||j.apiBaseUrl===null||j.apiBaseUrl==="")throw Error(`OAuthConnectionProvider: apiBaseUrl is required. Set it to the provider's API origin (e.g. apiBaseUrl: "https://api.figma.com"); connection.fetch only sends the token there.`);U("apiBaseUrl",j.apiBaseUrl),this.config={scopeSeparator:" ",clientAuth:"body",pkce:!0,authorizationParams:{},refreshLeewaySeconds:60,...j}}authorizationUrl(j){let B=new URL(this.config.authorizeUrl),G={...this.config.authorizationParams,response_type:"code",client_id:this.config.clientId,redirect_uri:j.redirectUri,scope:this.config.scopes.join(this.config.scopeSeparator),state:j.state};if(this.config.pkce)G.code_challenge=j.codeChallenge,G.code_challenge_method="S256";for(let[Q,K]of Object.entries(G))B.searchParams.set(Q,K);return B.toString()}exchangeCode(j){let B=new URLSearchParams({grant_type:"authorization_code",code:j.code,redirect_uri:j.redirectUri});if(this.config.pkce)B.set("code_verifier",j.codeVerifier);return this.tokenRequest(B,{scopes:this.config.scopes,refreshToken:null,phase:"exchange"})}refresh(j,B){let G=new URLSearchParams({grant_type:"refresh_token",refresh_token:j});return this.tokenRequest(G,{scopes:B,refreshToken:j,phase:"refresh"})}async revoke(j,B){if(!this.config.revokeUrl)throw new Z("revoke_unsupported","This provider has no revokeUrl configured. Use disconnect() to forget the tokens locally.");let G=new URLSearchParams({token:j,token_type_hint:B}),Q;try{Q=await fetch(this.config.revokeUrl,this.post(G))}catch(K){throw new Z("revoke_failed","The revocation request failed.",{cause:K})}if(!Q.ok)throw new Z("revoke_failed",`The provider refused the revocation (HTTP ${Q.status}).`,{status:Q.status})}post(j){let B={"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"};if(this.config.clientAuth==="basic"){let G=`${encodeURIComponent(this.config.clientId)}:${encodeURIComponent(this.config.clientSecret)}`;B.Authorization=`Basic ${Buffer.from(G).toString("base64")}`}else j.set("client_id",this.config.clientId),j.set("client_secret",this.config.clientSecret);return{method:"POST",headers:B,body:j.toString(),redirect:"error"}}async tokenRequest(j,B){let G=B.phase==="exchange"?"exchange_failed":"refresh_failed",Q;try{Q=await fetch(this.config.tokenUrl,this.post(j))}catch(Y){throw new Z(G,"The token request failed.",{cause:Y})}let K=await Q.json().catch(()=>({}));if(!Q.ok||typeof K.access_token!=="string"||K.access_token===""){let Y=typeof K.error==="string"&&/^[a-z0-9_]{1,64}$/.test(K.error)?K.error:void 0;throw new Z(G,`The token endpoint refused the ${B.phase==="exchange"?"code":"refresh token"} (HTTP ${Q.status}${Y?`, ${Y}`:""}).`,{status:Q.status,providerError:Y})}let V=Number(K.expires_in),W=typeof K.scope==="string"?K.scope:void 0,_=K.user_id_string??K.user_id??K.account_id;return{accessToken:K.access_token,refreshToken:typeof K.refresh_token==="string"&&K.refresh_token!==""?K.refresh_token:B.refreshToken,tokenType:typeof K.token_type==="string"?K.token_type:null,expiresAt:Number.isFinite(V)&&V>0?new Date(Date.now()+V*1000):null,scopes:W!==void 0?W.split(/[\s,]+/).filter(Boolean):B.scopes,providerAccountId:typeof _==="string"||typeof _==="number"?String(_):null}}}function U(j,B){let G;try{G=new URL(String(B))}catch{G=void 0}if(!G||G.protocol!=="https:"&&!(G.protocol==="http:"&&z(G.hostname)))throw Error(`OAuthConnectionProvider: ${j} must be an https URL (http only for localhost), got ${JSON.stringify(B)}.`)}function z(j){return j==="localhost"||j==="127.0.0.1"||j==="[::1]"||j==="::1"}class E{options;static token="auth.connections";resolvedStore;refreshing=new Map;fakes;fakeStore;fakeRequests=[];constructor(j){this.options=j}get providers(){return this.options.providers}get store(){if(this.fakeStore)return this.fakeStore;if(!this.resolvedStore){let j=this.options.store;this.resolvedStore=typeof j==="function"?j():j??new H(F(T).connection(),()=>R())}return this.resolvedStore}provider(j){let B=this.options.providers[j];if(!B){let G=Object.keys(this.options.providers);throw new Z("unknown_provider",`No OAuth connection provider "${j}" in auth.connections`+(G.length>0?` (configured: ${G.join(", ")}).`:" (none are configured)."))}return B}async for(j,B){this.provider(B);let G=await this.store.find(D(j),B);return G?new X(this,G):null}async list(j){return(await this.store.list(D(j))).filter((G)=>(G.provider in this.options.providers)).map((G)=>new X(this,G))}async save(j,B,G){let Q=this.provider(B),K=await this.store.save(D(j),B,{refreshToken:null,tokenType:null,expiresAt:null,providerAccountId:null,scopes:Q.config.scopes,...G});return new X(this,K)}fake(j={}){return this.fakes=new Map(Object.entries(j)),this.fakeStore=new N,this.fakeRequests.length=0,this}restore(){this.fakes=void 0,this.fakeStore=void 0,this.fakeRequests.length=0}get faked(){return this.fakes!==void 0}async send(j,B){if(!this.fakes)return fetch(B);this.fakeRequests.push(B.clone());let G=this.fakes.get(j);if(!G)throw Error(`Connections.fake() has no handler for "${j}". Pass one: Connections.fake({ ${j}: (req) => ... }).`);return G(B)}refresh(j){let B=this.refreshing.get(j.id);if(B)return B;let G=this.withLock(j.id,()=>this.refreshOnce(j)).finally(()=>this.refreshing.delete(j.id));return this.refreshing.set(j.id,G),G}async refreshOnce(j){let B=await this.store.find(j.userId,j.provider);if(!B||B.id!==j.id)throw new $(j.provider);if(B.revision!==j.revision&&!B.needsReconnect)return B;if(B.needsReconnect)throw new $(j.provider);let G=this.provider(B.provider);if(this.faked||B.refreshToken===null){if(this.faked)return B;throw await this.store.markNeedsReconnect(B.id),new $(B.provider)}let Q;try{Q=await G.refresh(B.refreshToken,B.scopes)}catch(W){if(W instanceof Z&&W.status!==void 0&&W.status>=400&&W.status<500)throw await this.store.markNeedsReconnect(B.id),new $(B.provider,{cause:W,status:W.status,providerError:W.providerError});throw W}let K=await this.store.updateTokens(B.id,B.revision,Q);if(K)return K;let V=await this.store.find(B.userId,B.provider);if(!V)throw new $(B.provider);return V}async withLock(j,B){let G=F();if(this.faked||!G.bound(L))return B();let Q=await G.make(L).run(`gemi:oauth-connection:${j}`,{ttl:30000,wait:20000},()=>B());if(!Q.acquired)throw new Z("refresh_failed","Timed out waiting for another refresh of this connection to finish.");return Q.value}}class X{manager;record;constructor(j,B){this.manager=j;this.record=B}get provider(){return this.record.provider}get userId(){return this.record.userId}get providerAccountId(){return this.record.providerAccountId}get scopes(){return this.record.scopes}get expiresAt(){return this.record.expiresAt}get needsReconnect(){return this.record.needsReconnect}get connectedAt(){return this.record.createdAt}hasScopes(...j){return j.every((B)=>this.record.scopes.includes(B))}async fetch(j,B={}){let G=this.resolveUrl(j),Q=await this.current(),K=await this.send(G,B,Q.accessToken);if(K.response.status!==401||!K.authorized||B.body instanceof ReadableStream)return K.response;await K.response.body?.cancel().catch(()=>{});let V=await this.refreshFrom(Q);return(await this.send(G,B,V.accessToken)).response}async accessToken(){return(await this.current()).accessToken}async refresh(){await this.refreshFrom(this.record)}async revoke(){if(!this.manager.faked){let j=this.manager.provider(this.record.provider);if(this.record.refreshToken!==null)await j.revoke(this.record.refreshToken,"refresh_token");else await j.revoke(this.record.accessToken,"access_token")}await this.manager.store.delete(this.record.id)}async disconnect(){await this.manager.store.delete(this.record.id)}toJSON(){return{provider:this.provider,providerAccountId:this.providerAccountId,scopes:[...this.scopes],expiresAt:this.expiresAt,needsReconnect:this.needsReconnect,connectedAt:this.connectedAt}}[Symbol.for("nodejs.util.inspect.custom")](){return{ProviderConnection:this.toJSON()}}async current(){if(this.record.needsReconnect)throw new $(this.record.provider);let j=this.manager.provider(this.record.provider).config.refreshLeewaySeconds*1000,B=this.record.expiresAt?.getTime();if(B!==void 0&&B-Date.now()<=j)return this.refreshFrom(this.record);return this.record}async refreshFrom(j){try{this.record=await this.manager.refresh(j)}catch(B){if(B instanceof $)this.record={...this.record,needsReconnect:!0};throw B}return this.record}resolveUrl(j){let B=this.manager.provider(this.record.provider).config.apiBaseUrl,G;try{G=new URL(String(j),B)}catch{throw new Z("forbidden_url",`connection.fetch was given ${JSON.stringify(String(j))}, which is not a URL.`)}if(G.origin!==new URL(B).origin)throw new Z("forbidden_url",`connection.fetch only sends the ${this.record.provider} token to ${new URL(B).origin} (apiBaseUrl), not to ${G.origin}.`);if(G.protocol!=="https:"&&!(G.protocol==="http:"&&z(G.hostname)))throw new Z("forbidden_url",`connection.fetch only sends a token over https, not to ${G.origin}.`);return G}async send(j,B,G){let Q=j,K=(B.method??"GET").toUpperCase(),V=B.body,W=!0;if(B.redirect==="manual"||B.redirect==="error")return{response:await this.manager.send(this.record.provider,this.request(Q,B,K,V,G)),authorized:W};for(let _=0;;_++){let Y=this.request(Q,{...B,redirect:"manual"},K,V,W?G:null),J=await this.manager.send(this.record.provider,Y),M=J.headers.get("location");if(!C.has(J.status)||M===null||_>=5)return{response:J,authorized:W};await J.body?.cancel().catch(()=>{});let P=new URL(M,Q);if(P.origin!==Q.origin)W=!1;if(J.status===303||(J.status===301||J.status===302)&&K==="POST")K="GET",V=void 0;Q=P}}request(j,B,G,Q,K){let V=new Headers(B.headers);if(K===null)V.delete("authorization");else V.set("Authorization",`Bearer ${K}`);return new Request(j,{...B,method:G,body:Q,headers:V})}}var C=new Set([301,302,303,307,308]);function D(j){let B=typeof j==="object"&&j!==null?j.id:j;if(B===void 0||B===null||B==="")throw TypeError("An OAuth connection belongs to a user: pass the user (or its id).");return String(B)}
69
- export{N as Rg,H as Sg,Z as Tg,$ as Ug,O as Vg,E as Wg,X as Xg};
69
+ export{N as Ng,H as Og,Z as Pg,$ as Qg,O as Rg,E as Sg,X as Tg};
70
70
 
71
- //# debugId=8235325ABF40DA7464756E2164756E21
71
+ //# debugId=7E331063F684CCE764756E2164756E21
@@ -8,6 +8,6 @@
8
8
  "import { DatabaseManager } from \"../../database/DatabaseManager\";\nimport { app } from \"../../foundation/app\";\nimport { currentEncrypter } from \"../../orm/encryption\";\nimport { LockManager } from \"../../services/lock/LockManager\";\nimport {\n type ConnectionRecord,\n type ConnectionStore,\n DatabaseConnectionStore,\n MemoryConnectionStore,\n} from \"./ConnectionStore\";\nimport { OAuthConnectionError, OAuthReconnectRequiredError } from \"./errors\";\nimport { type OAuthConnectionProvider, type OAuthTokenSet, isLoopback } from \"./OAuthConnectionProvider\";\n\n/** A user, as far as a connection is concerned: anything with an `id`. */\nexport type ConnectionOwner = { id: string | number } | string | number;\n\n/** What `Connections.fake` answers an API request with. */\nexport type FakeConnectionHandler = (request: Request) => Response | Promise<Response>;\n\nexport interface ConnectionManagerOptions {\n providers: Record<string, OAuthConnectionProvider>;\n /** Default: a `DatabaseConnectionStore` on the default database connection. */\n store?: ConnectionStore | (() => ConnectionStore);\n}\n\n/**\n * The OAuth connections a user has made, and the one place their tokens are\n * read, refreshed and spent. Reached through the `Connections` facade.\n */\nexport class ConnectionManager {\n static token = \"auth.connections\";\n\n private resolvedStore: ConnectionStore | undefined;\n private readonly refreshing = new Map<string, Promise<ConnectionRecord>>();\n private fakes: Map<string, FakeConnectionHandler> | undefined;\n private fakeStore: MemoryConnectionStore | undefined;\n readonly fakeRequests: Request[] = [];\n\n constructor(private readonly options: ConnectionManagerOptions) {}\n\n get providers(): Record<string, OAuthConnectionProvider> {\n return this.options.providers;\n }\n\n /** The store connections are kept in. */\n get store(): ConnectionStore {\n if (this.fakeStore) return this.fakeStore;\n if (!this.resolvedStore) {\n const configured = this.options.store;\n this.resolvedStore =\n typeof configured === \"function\"\n ? configured()\n : (configured ??\n new DatabaseConnectionStore(app(DatabaseManager).connection(), () => currentEncrypter()));\n }\n return this.resolvedStore;\n }\n\n provider(name: string): OAuthConnectionProvider {\n const provider = this.options.providers[name];\n if (!provider) {\n const known = Object.keys(this.options.providers);\n throw new OAuthConnectionError(\n \"unknown_provider\",\n `No OAuth connection provider \"${name}\" in auth.connections` +\n (known.length > 0 ? ` (configured: ${known.join(\", \")}).` : \" (none are configured).\"),\n );\n }\n return provider;\n }\n\n /** The user's connection to `provider`, or `null` when they have not connected it. */\n async for(user: ConnectionOwner, provider: string): Promise<ProviderConnection | null> {\n this.provider(provider);\n const record = await this.store.find(ownerId(user), provider);\n return record ? new ProviderConnection(this, record) : null;\n }\n\n /** Every connection the user has. */\n async list(user: ConnectionOwner): Promise<ProviderConnection[]> {\n const records = await this.store.list(ownerId(user));\n return records\n .filter((record) => record.provider in this.options.providers)\n .map((record) => new ProviderConnection(this, record));\n }\n\n /**\n * Stores tokens for the user, replacing any earlier connection to the same\n * provider. The connect callback calls this; call it yourself for tokens\n * obtained some other way.\n */\n async save(\n user: ConnectionOwner,\n provider: string,\n tokens: Partial<OAuthTokenSet> & { accessToken: string },\n ): Promise<ProviderConnection> {\n const config = this.provider(provider);\n const record = await this.store.save(ownerId(user), provider, {\n refreshToken: null,\n tokenType: null,\n expiresAt: null,\n providerAccountId: null,\n scopes: config.config.scopes,\n ...tokens,\n });\n return new ProviderConnection(this, record);\n }\n\n // --- testing ---------------------------------------------------------------\n\n /**\n * Fakes every provider's API: connections live in memory, `fetch` answers\n * through `handlers[provider]` (recorded in `fakeRequests`), and nothing\n * reaches a token or revocation endpoint. Returns `this` so a test can\n * `save` a connection to start from.\n */\n fake(handlers: Record<string, FakeConnectionHandler> = {}): this {\n this.fakes = new Map(Object.entries(handlers));\n this.fakeStore = new MemoryConnectionStore();\n this.fakeRequests.length = 0;\n return this;\n }\n\n /** Undoes `fake`. */\n restore(): void {\n this.fakes = undefined;\n this.fakeStore = undefined;\n this.fakeRequests.length = 0;\n }\n\n get faked(): boolean {\n return this.fakes !== undefined;\n }\n\n // --- internals, for ProviderConnection ---------------------------------------\n\n /** @internal */\n async send(provider: string, request: Request): Promise<Response> {\n if (!this.fakes) return fetch(request);\n this.fakeRequests.push(request.clone());\n const handler = this.fakes.get(provider);\n if (!handler) {\n throw new Error(`Connections.fake() has no handler for \"${provider}\". Pass one: Connections.fake({ ${provider}: (req) => ... }).`);\n }\n return handler(request);\n }\n\n /**\n * A record whose access token is not the one at `staleRevision`: refreshed\n * by this call, or by whoever refreshed it first. Serialised per connection\n * in this process (concurrent callers share one refresh) and, through the\n * app's lock store, across processes — a rotating refresh token must be\n * spent exactly once.\n *\n * @internal\n */\n refresh(record: ConnectionRecord): Promise<ConnectionRecord> {\n const inFlight = this.refreshing.get(record.id);\n if (inFlight) return inFlight;\n const task = this.withLock(record.id, () => this.refreshOnce(record)).finally(() =>\n this.refreshing.delete(record.id),\n );\n this.refreshing.set(record.id, task);\n return task;\n }\n\n private async refreshOnce(seen: ConnectionRecord): Promise<ConnectionRecord> {\n // Re-read under the lock: another process may have refreshed already.\n const current = await this.store.find(seen.userId, seen.provider);\n if (!current || current.id !== seen.id) {\n throw new OAuthReconnectRequiredError(seen.provider);\n }\n if (current.revision !== seen.revision && !current.needsReconnect) return current;\n if (current.needsReconnect) throw new OAuthReconnectRequiredError(seen.provider);\n\n const provider = this.provider(current.provider);\n if (this.faked || current.refreshToken === null) {\n if (this.faked) return current;\n await this.store.markNeedsReconnect(current.id);\n throw new OAuthReconnectRequiredError(current.provider);\n }\n\n let tokens: OAuthTokenSet;\n try {\n tokens = await provider.refresh(current.refreshToken, current.scopes);\n } catch (error) {\n // A refusal from the token endpoint is final: the grant is gone. A\n // network error or a 5xx is not, and leaves the connection alone.\n if (error instanceof OAuthConnectionError && error.status !== undefined && error.status >= 400 && error.status < 500) {\n await this.store.markNeedsReconnect(current.id);\n throw new OAuthReconnectRequiredError(current.provider, {\n cause: error,\n status: error.status,\n providerError: error.providerError,\n });\n }\n throw error;\n }\n\n const updated = await this.store.updateTokens(current.id, current.revision, tokens);\n if (updated) return updated;\n // Someone else wrote first (only possible without a shared lock store).\n const winner = await this.store.find(current.userId, current.provider);\n if (!winner) throw new OAuthReconnectRequiredError(current.provider);\n return winner;\n }\n\n private async withLock<T>(id: string, fn: () => Promise<T>): Promise<T> {\n const application = app();\n if (this.faked || !application.bound(LockManager)) return fn();\n const result = await application\n .make(LockManager)\n .run(`gemi:oauth-connection:${id}`, { ttl: 30_000, wait: 20_000 }, () => fn());\n if (!result.acquired) {\n throw new OAuthConnectionError(\n \"refresh_failed\",\n \"Timed out waiting for another refresh of this connection to finish.\",\n );\n }\n return result.value as T;\n }\n}\n\n/**\n * One user's connection to one provider. Never exposes a token as a property,\n * and serialises (`toJSON`, `console.log`) without them.\n */\nexport class ProviderConnection {\n constructor(\n private readonly manager: ConnectionManager,\n private record: ConnectionRecord,\n ) {}\n\n get provider(): string {\n return this.record.provider;\n }\n get userId(): string {\n return this.record.userId;\n }\n get providerAccountId(): string | null {\n return this.record.providerAccountId;\n }\n /** The scopes the provider granted. */\n get scopes(): readonly string[] {\n return this.record.scopes;\n }\n get expiresAt(): Date | null {\n return this.record.expiresAt;\n }\n /** A refresh was refused: the user has to connect again. */\n get needsReconnect(): boolean {\n return this.record.needsReconnect;\n }\n get connectedAt(): Date {\n return this.record.createdAt;\n }\n\n /** Whether every one of `scopes` was granted. */\n hasScopes(...scopes: string[]): boolean {\n return scopes.every((scope) => this.record.scopes.includes(scope));\n }\n\n /**\n * `fetch`, as the user: adds `Authorization: Bearer <token>`, refreshes the\n * token first when it is about to expire, and after a 401 refreshes and\n * retries once. A refresh the provider refuses marks the connection and\n * throws `OAuthReconnectRequiredError`.\n *\n * A path is resolved against the provider's `apiBaseUrl`, and a URL on any\n * other origin is refused (`OAuthConnectionError`,\n * `forbidden_url`), so the token only ever goes to the provider. Redirects\n * are followed by hand: the token is dropped on one that leaves the origin.\n * A streamed request body cannot be sent twice, so a 401 for one is\n * returned rather than retried.\n */\n async fetch(input: string | URL, init: RequestInit = {}): Promise<Response> {\n const url = this.resolveUrl(input);\n const record = await this.current();\n const first = await this.send(url, init, record.accessToken);\n // Retry only a 401 for the token itself, not one from where a redirect\n // led after the token was dropped.\n if (first.response.status !== 401 || !first.authorized || init.body instanceof ReadableStream) {\n return first.response;\n }\n\n await first.response.body?.cancel().catch(() => {});\n const refreshed = await this.refreshFrom(record);\n return (await this.send(url, init, refreshed.accessToken)).response;\n }\n\n /**\n * A valid access token, refreshed first if it is about to expire — for an\n * SDK that wants the token itself. Prefer `fetch`, which also retries a 401.\n */\n async accessToken(): Promise<string> {\n return (await this.current()).accessToken;\n }\n\n /** Refreshes now, whatever the expiry says. */\n async refresh(): Promise<void> {\n await this.refreshFrom(this.record);\n }\n\n /**\n * Revokes the grant at the provider (the refresh token when there is one,\n * which ends the whole grant, else the access token) and deletes the\n * connection. If the provider refuses, nothing is deleted and\n * `OAuthConnectionError` (`revoke_failed`) is thrown — call `disconnect()`\n * to forget the tokens anyway. A provider without a `revokeUrl` throws\n * `revoke_unsupported`; use `disconnect()`.\n */\n async revoke(): Promise<void> {\n if (!this.manager.faked) {\n const provider = this.manager.provider(this.record.provider);\n if (this.record.refreshToken !== null) {\n await provider.revoke(this.record.refreshToken, \"refresh_token\");\n } else {\n await provider.revoke(this.record.accessToken, \"access_token\");\n }\n }\n await this.manager.store.delete(this.record.id);\n }\n\n /** Forgets the tokens locally without telling the provider. */\n async disconnect(): Promise<void> {\n await this.manager.store.delete(this.record.id);\n }\n\n toJSON() {\n return {\n provider: this.provider,\n providerAccountId: this.providerAccountId,\n scopes: [...this.scopes],\n expiresAt: this.expiresAt,\n needsReconnect: this.needsReconnect,\n connectedAt: this.connectedAt,\n };\n }\n\n [Symbol.for(\"nodejs.util.inspect.custom\")]() {\n return { ProviderConnection: this.toJSON() };\n }\n\n private async current(): Promise<ConnectionRecord> {\n if (this.record.needsReconnect) throw new OAuthReconnectRequiredError(this.record.provider);\n const leeway = this.manager.provider(this.record.provider).config.refreshLeewaySeconds * 1000;\n const expiresAt = this.record.expiresAt?.getTime();\n if (expiresAt !== undefined && expiresAt - Date.now() <= leeway) {\n return this.refreshFrom(this.record);\n }\n return this.record;\n }\n\n private async refreshFrom(record: ConnectionRecord): Promise<ConnectionRecord> {\n try {\n this.record = await this.manager.refresh(record);\n } catch (error) {\n if (error instanceof OAuthReconnectRequiredError) {\n this.record = { ...this.record, needsReconnect: true };\n }\n throw error;\n }\n return this.record;\n }\n\n private resolveUrl(input: string | URL): URL {\n const base = this.manager.provider(this.record.provider).config.apiBaseUrl;\n let url: URL;\n try {\n url = new URL(String(input), base);\n } catch {\n throw new OAuthConnectionError(\n \"forbidden_url\",\n `connection.fetch was given ${JSON.stringify(String(input))}, which is not a URL.`,\n );\n }\n if (url.origin !== new URL(base).origin) {\n throw new OAuthConnectionError(\n \"forbidden_url\",\n `connection.fetch only sends the ${this.record.provider} token to ${new URL(base).origin} ` +\n `(apiBaseUrl), not to ${url.origin}.`,\n );\n }\n if (url.protocol !== \"https:\" && !(url.protocol === \"http:\" && isLoopback(url.hostname))) {\n throw new OAuthConnectionError(\n \"forbidden_url\",\n `connection.fetch only sends a token over https, not to ${url.origin}.`,\n );\n }\n return url;\n }\n\n private async send(url: URL, init: RequestInit, token: string): Promise<{ response: Response; authorized: boolean }> {\n let target = url;\n let method = (init.method ?? \"GET\").toUpperCase();\n let body = init.body;\n let authorized = true;\n\n // Followed by hand (unless the caller asked for \"manual\" or \"error\"), so\n // the token never follows a redirect to another origin.\n if (init.redirect === \"manual\" || init.redirect === \"error\") {\n const response = await this.manager.send(this.record.provider, this.request(target, init, method, body, token));\n return { response, authorized };\n }\n\n for (let hop = 0; ; hop++) {\n const request = this.request(target, { ...init, redirect: \"manual\" }, method, body, authorized ? token : null);\n const response = await this.manager.send(this.record.provider, request);\n const location = response.headers.get(\"location\");\n if (!REDIRECTS.has(response.status) || location === null || hop >= 5) return { response, authorized };\n\n await response.body?.cancel().catch(() => {});\n const next = new URL(location, target);\n if (next.origin !== target.origin) authorized = false;\n if (response.status === 303 || ((response.status === 301 || response.status === 302) && method === \"POST\")) {\n method = \"GET\";\n body = undefined;\n }\n target = next;\n }\n }\n\n private request(url: URL, init: RequestInit, method: string, body: RequestInit[\"body\"], token: string | null): Request {\n const headers = new Headers(init.headers);\n if (token === null) headers.delete(\"authorization\");\n else headers.set(\"Authorization\", `Bearer ${token}`);\n return new Request(url, { ...init, method, body, headers });\n }\n}\n\nconst REDIRECTS = new Set([301, 302, 303, 307, 308]);\n\nfunction ownerId(user: ConnectionOwner): string {\n const id = typeof user === \"object\" && user !== null ? user.id : user;\n if (id === undefined || id === null || id === \"\") {\n throw new TypeError(\"An OAuth connection belongs to a user: pass the user (or its id).\");\n }\n return String(id);\n}\n"
9
9
  ],
10
10
  "mappings": ";sLAwCO,AAAM,LAAiD,LAC3C,KAAO,IAAI,SAEtB,KAAI,CAAC,EAAgB,EAAkB,CAC3C,QAAW,KAAO,KAAK,KAAK,OAAO,EACjC,GAAI,EAAI,SAAW,GAAU,EAAI,WAAa,EAAU,MAAO,IAAK,CAAI,EAE1E,OAAO,UAGH,KAAI,CAAC,EAAgB,CACzB,MAAO,CAAC,GAAG,KAAK,KAAK,OA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,IAAM,EAAK,OAAO,IAAS,UAAY,IAAS,KAAO,EAAK,GAAK,EACjE,GAAI,IAAO,QAAa,IAAO,MAAQ,IAAO,GAC5C,MAAU,UAAU,mEAAmE,EAEzF,OAAO,OAAO,CAAE",
11
- "debugId": "8235325ABF40DA7464756E2164756E21",
11
+ "debugId": "7E331063F684CCE764756E2164756E21",
12
12
  "names": []
13
13
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{R as C,T as h,U as m}from"./chunk-qm6j85fq.js";import{ma as w,na as q}from"./chunk-de4t48j9.js";import"./chunk-a22h5cby.js";import"./chunk-epvpmakp.js";import"./chunk-r3v2cnrj.js";import"./chunk-6ggmk2eg.js";import{Da as N}from"./chunk-kk77x2v4.js";import"./chunk-2bja99cq.js";import"./chunk-hd5ztshp.js";import{Ng as _}from"./chunk-2kegxt0s.js";import{ej as y}from"./chunk-0p6mdba6.js";import"./chunk-j5q5ysng.js";import{join as $J}from"path";import{createServer as zJ}from"vite";import{join as l}from"path";import{IncomingMessage as d,ServerResponse as p}from"http";import{Socket as i}from"net";function v(J){return J.replace(/\x1b\[[0-9;]*m/g,"").replace(/\[[0-9;]*m/g,"").replace(/\n\s*\n/g,`
2
+ import{R as C,T as h,U as m}from"./chunk-dbx3g5ck.js";import{ma as w,na as q}from"./chunk-zg6hmc48.js";import"./chunk-a22h5cby.js";import"./chunk-epvpmakp.js";import"./chunk-r3v2cnrj.js";import"./chunk-c0v61fp5.js";import"./chunk-kk18xqgc.js";import"./chunk-krtybgz1.js";import{Jg as _}from"./chunk-cca0grq3.js";import{Ui as y}from"./chunk-er8acmch.js";import{gj as N}from"./chunk-rhvc1axc.js";import"./chunk-tewhms9w.js";import{join as $J}from"path";import{createServer as zJ}from"vite";import{join as l}from"path";import{IncomingMessage as d,ServerResponse as p}from"http";import{Socket as i}from"net";function v(J){return J.replace(/\x1b\[[0-9;]*m/g,"").replace(/\[[0-9;]*m/g,"").replace(/\n\s*\n/g,`
3
3
  `).split(`
4
4
  `).map((W)=>W.trim()).filter((W)=>W.length>0).join(`
5
5
  `).trim()}function D(J){return`
@@ -53,6 +53,6 @@ RefreshRuntime.injectIntoGlobalHook(window);
53
53
  window.$RefreshReg$ = () => {};
54
54
  window.$RefreshSig$ = () => (type) => type;
55
55
  window.__vite_plugin_react_preamble_installed__ = true;
56
- `;function t(J){let{pathname:W}=new URL(J.url),Z=($)=>new Response($,{headers:{"Content-Type":"application/javascript"}});if(W===S)return Z(s);if(W.startsWith("/render-error.js"))return Z("window.render_error = true");if(W.startsWith("/refresh.js"))return Z(a);return null}function k(J,W,Z){let $=l(process.cwd(),"app");return async(Q)=>{let{pathname:X}=new URL(Q.url),Y=(z)=>{if(console.error(z),Z.ssrFixStacktrace?.(z),O(z),y(X))return new Response(JSON.stringify({error:_("server_error",z?.message??String(z),500)}),{status:500,headers:{"Content-Type":"application/json"}});return globalThis.__gemiErrorPageServed=!0,new Response(D(H(z)),{status:500,headers:{"Content-Type":"text/html"}})},G=async(z)=>{let U=t(z);if(U)return U;try{let B=J.fetch.bind(J),K=await n(Z,z)??await B(z);if(K instanceof Response)return K;let j={},b={},M={},c=(L,A)=>`"${L}": () => import("${A}")`,F=[];for(let L of["404",...J.getFlatComponentTree.call(J)]){if(Bun.env.NODE_ENV==="test")break;let A=`${process.env.APP_DIR}`,x=await I(Z).import(`${A}/views/${L}.tsx`);j[L]=x.default,b[L]=x?.OpenGraph,M[L]=x,F.push(c(L,`/app/views/${L}.tsx`))}let u=`{${F.join(",")}}`;return await K({getStyles:async(L,A)=>await C($,Z,L,A?.layout),resolveIsland:(L)=>({src:`/${L}${N}`,preload:[]}),bootstrapModules:[S],viewImportMap:j,viewModules:M,ogMap:b,loaders:u,cssManifest:{}})}catch(B){return Y(B)}};return await W(Q,(z)=>J.withGlobalMiddleware(z,G,Y))}}function r(J){try{return Bun.listen({hostname:"0.0.0.0",port:J,socket:{data(){}}}).stop(!0),!0}catch(W){return W?.code!=="EADDRINUSE"}}function T(J,W=r){let Z=24678+(J-5173);if(Z>65471)Z=24678;for(let $=Z;$<Z+64;$++)if(W($))return $;throw Error(`Could not find a free port for Vite's HMR websocket: tried ${Z}-${Z+64-1}. Set one explicitly in gemi.config.ts as \`vite: { server: { ws: { port } } }\`.`)}import{createServer as e}from"http";var JJ=new Set(["vite-hmr","vite-ping"]);async function P(J){let W=e((Z,$)=>{$.writeHead(426,{"Content-Type":"text/plain"}),$.end("Upgrade Required")});return await new Promise((Z,$)=>{W.once("error",$),W.listen(J,"127.0.0.1",()=>{W.off("error",$),Z()})}),W}function f(J){if(!J||typeof J!=="object")return null;let Z=J.server?.address?.();if(Z&&typeof Z==="object"&&"port"in Z)return Number(Z.port)||null;return null}function R(J){if(J.headers.get("upgrade")?.toLowerCase()!=="websocket")return!1;return JJ.has(J.headers.get("sec-websocket-protocol")??"")}var WJ=(J)=>typeof J==="string"?J:new Uint8Array(J);async function g(J,W,Z){let $=new URL(J.url),Q=J.headers.get("sec-websocket-protocol")??"vite-hmr",X={host:J.headers.get("host")??$.host},Y=J.headers.get("origin");if(Y)X.origin=Y;let G=new WebSocket(`ws://127.0.0.1:${Z}${$.pathname}${$.search}`,{protocols:[Q],headers:X});G.binaryType="arraybuffer";let z={upstream:G,early:[]};if(G.onmessage=(K)=>{let j=WJ(K.data);if(z.browser)z.browser.send(j);else z.early.push(j)},G.onclose=(K)=>{z.browser?.close(ZJ(K.code),K.reason)},G.onerror=()=>{},!await new Promise((K)=>{G.addEventListener("open",()=>K(!0),{once:!0}),G.addEventListener("close",()=>K(!1),{once:!0})}))return new Response("Vite refused the HMR websocket",{status:403});if(!W.upgrade(J,{headers:{"Sec-WebSocket-Protocol":Q},data:z}))return G.close(),new Response("WebSocket upgrade failed",{status:400});return}function ZJ(J){if(J===1000||J>=1001&&J<=1003||J>=1007&&J<=1014)return J;if(J>=3000&&J<=4999)return J;return 1000}var E={open(J){let W=J.data;for(let Z of W.early)J.send(Z);if(W.early=[],W.browser=J,W.upstream.readyState!==WebSocket.OPEN)J.close(1000)},message(J,W){if(J.data.upstream.readyState===WebSocket.OPEN)J.data.upstream.send(W)},close(J){let{upstream:W}=J.data;if(W.readyState<=WebSocket.OPEN)W.close()}};var V=process.cwd(),GJ=$J(V,"app");if(!globalThis.__gemiErrorHooked)globalThis.__gemiErrorHooked=!0,process.on("unhandledRejection",(J)=>{console.error(J),O(J)}),process.on("uncaughtException",(J)=>{console.error(J),O(J)});async function SJ(J,W){let Z=Number(process.env.PORT)||5173,$=m(),Q=Boolean(globalThis.__gemiVite),X=globalThis.__gemiVite??=await zJ({configFile:!1,plugins:[q()],server:{middlewareMode:!0,port:Z,ws:{server:await P(T(Z))},allowedHosts:J.devAllowedHosts.call(J),watch:{ignored:(U)=>{let B=U.split(/[/\\]/).pop()??"";return B===".env"||B.startsWith(".env.")}}},appType:"custom",resolve:{dedupe:["react","react-dom"]},optimizeDeps:{include:["react","react-dom","react-dom/client"]},ssr:{external:[...w]}});process.env.ROOT_DIR=V,process.env.APP_DIR=GJ;let Y=k(J,W,X),G=f(X.config?.server?.ws),z=Bun.serve({port:Z,idleTimeout:$,fetch:(U,B)=>{if(G!==null&&R(U))return g(U,B,G);return Y(U)},websocket:E});if(Q)I(X).clearCache();if(Q)if(globalThis.__gemiErrorActive&&globalThis.__gemiErrorPageServed)globalThis.__gemiErrorActive=!1,globalThis.__gemiErrorPageServed=!1,X.ws.send({type:"full-reload"});else globalThis.__gemiErrorActive=!1,X.ws.send({type:"custom",event:"http-reload"});else h({port:z.port,rootDir:V});return z}export{H as viteErrorPayload,SJ as httpDev};
56
+ `;function t(J){let{pathname:W}=new URL(J.url),Z=($)=>new Response($,{headers:{"Content-Type":"application/javascript"}});if(W===S)return Z(s);if(W.startsWith("/render-error.js"))return Z("window.render_error = true");if(W.startsWith("/refresh.js"))return Z(a);return null}function k(J,W,Z){let $=l(process.cwd(),"app");return async(Q)=>{let{pathname:X}=new URL(Q.url),Y=(z)=>{if(console.error(z),Z.ssrFixStacktrace?.(z),O(z),N(X))return new Response(JSON.stringify({error:_("server_error",z?.message??String(z),500)}),{status:500,headers:{"Content-Type":"application/json"}});return globalThis.__gemiErrorPageServed=!0,new Response(D(H(z)),{status:500,headers:{"Content-Type":"text/html"}})},G=async(z)=>{let U=t(z);if(U)return U;try{let B=J.fetch.bind(J),K=await n(Z,z)??await B(z);if(K instanceof Response)return K;let j={},b={},M={},c=(L,A)=>`"${L}": () => import("${A}")`,F=[];for(let L of["404",...J.getFlatComponentTree.call(J)]){if(Bun.env.NODE_ENV==="test")break;let A=`${process.env.APP_DIR}`,x=await I(Z).import(`${A}/views/${L}.tsx`);j[L]=x.default,b[L]=x?.OpenGraph,M[L]=x,F.push(c(L,`/app/views/${L}.tsx`))}let u=`{${F.join(",")}}`;return await K({getStyles:async(L,A)=>await C($,Z,L,A?.layout),resolveIsland:(L)=>({src:`/${L}${y}`,preload:[]}),buildId:"dev",bootstrapModules:[S],viewImportMap:j,viewModules:M,ogMap:b,loaders:u,cssManifest:{}})}catch(B){return Y(B)}};return await W(Q,(z)=>J.withGlobalMiddleware(z,G,Y))}}function r(J){try{return Bun.listen({hostname:"0.0.0.0",port:J,socket:{data(){}}}).stop(!0),!0}catch(W){return W?.code!=="EADDRINUSE"}}function T(J,W=r){let Z=24678+(J-5173);if(Z>65471)Z=24678;for(let $=Z;$<Z+64;$++)if(W($))return $;throw Error(`Could not find a free port for Vite's HMR websocket: tried ${Z}-${Z+64-1}. Set one explicitly in gemi.config.ts as \`vite: { server: { ws: { port } } }\`.`)}import{createServer as e}from"http";var JJ=new Set(["vite-hmr","vite-ping"]);async function P(J){let W=e((Z,$)=>{$.writeHead(426,{"Content-Type":"text/plain"}),$.end("Upgrade Required")});return await new Promise((Z,$)=>{W.once("error",$),W.listen(J,"127.0.0.1",()=>{W.off("error",$),Z()})}),W}function f(J){if(!J||typeof J!=="object")return null;let Z=J.server?.address?.();if(Z&&typeof Z==="object"&&"port"in Z)return Number(Z.port)||null;return null}function R(J){if(J.headers.get("upgrade")?.toLowerCase()!=="websocket")return!1;return JJ.has(J.headers.get("sec-websocket-protocol")??"")}var WJ=(J)=>typeof J==="string"?J:new Uint8Array(J);async function g(J,W,Z){let $=new URL(J.url),Q=J.headers.get("sec-websocket-protocol")??"vite-hmr",X={host:J.headers.get("host")??$.host},Y=J.headers.get("origin");if(Y)X.origin=Y;let G=new WebSocket(`ws://127.0.0.1:${Z}${$.pathname}${$.search}`,{protocols:[Q],headers:X});G.binaryType="arraybuffer";let z={upstream:G,early:[]};if(G.onmessage=(K)=>{let j=WJ(K.data);if(z.browser)z.browser.send(j);else z.early.push(j)},G.onclose=(K)=>{z.browser?.close(ZJ(K.code),K.reason)},G.onerror=()=>{},!await new Promise((K)=>{G.addEventListener("open",()=>K(!0),{once:!0}),G.addEventListener("close",()=>K(!1),{once:!0})}))return new Response("Vite refused the HMR websocket",{status:403});if(!W.upgrade(J,{headers:{"Sec-WebSocket-Protocol":Q},data:z}))return G.close(),new Response("WebSocket upgrade failed",{status:400});return}function ZJ(J){if(J===1000||J>=1001&&J<=1003||J>=1007&&J<=1014)return J;if(J>=3000&&J<=4999)return J;return 1000}var E={open(J){let W=J.data;for(let Z of W.early)J.send(Z);if(W.early=[],W.browser=J,W.upstream.readyState!==WebSocket.OPEN)J.close(1000)},message(J,W){if(J.data.upstream.readyState===WebSocket.OPEN)J.data.upstream.send(W)},close(J){let{upstream:W}=J.data;if(W.readyState<=WebSocket.OPEN)W.close()}};var V=process.cwd(),GJ=$J(V,"app");if(!globalThis.__gemiErrorHooked)globalThis.__gemiErrorHooked=!0,process.on("unhandledRejection",(J)=>{console.error(J),O(J)}),process.on("uncaughtException",(J)=>{console.error(J),O(J)});async function SJ(J,W){let Z=Number(process.env.PORT)||5173,$=m(),Q=Boolean(globalThis.__gemiVite),X=globalThis.__gemiVite??=await zJ({configFile:!1,plugins:[q()],server:{middlewareMode:!0,port:Z,ws:{server:await P(T(Z))},allowedHosts:J.devAllowedHosts.call(J),watch:{ignored:(U)=>{let B=U.split(/[/\\]/).pop()??"";return B===".env"||B.startsWith(".env.")}}},appType:"custom",resolve:{dedupe:["react","react-dom"]},optimizeDeps:{include:["react","react-dom","react-dom/client"]},ssr:{external:[...w]}});process.env.ROOT_DIR=V,process.env.APP_DIR=GJ;let Y=k(J,W,X),G=f(X.config?.server?.ws),z=Bun.serve({port:Z,idleTimeout:$,fetch:(U,B)=>{if(G!==null&&R(U))return g(U,B,G);return Y(U)},websocket:E});if(Q)I(X).clearCache();if(Q)if(globalThis.__gemiErrorActive&&globalThis.__gemiErrorPageServed)globalThis.__gemiErrorActive=!1,globalThis.__gemiErrorPageServed=!1,X.ws.send({type:"full-reload"});else globalThis.__gemiErrorActive=!1,X.ws.send({type:"custom",event:"http-reload"});else h({port:z.port,rootDir:V});return z}export{H as viteErrorPayload,SJ as httpDev};
57
57
 
58
- //# debugId=C68D33BAD4255DC364756E2164756E21
58
+ //# debugId=DD235AA05CAC380F64756E2164756E21
@@ -3,12 +3,12 @@
3
3
  "sources": ["../server/httpDev.ts", "../server/devFetch.ts", "../server/renderErrorPage.ts", "../server/hmrPort.ts", "../server/hmrRelay.ts"],
4
4
  "sourcesContent": [
5
5
  "import { join } from \"node:path\";\n\nimport { createServer } from \"vite\";\n\nimport { App } from \"../app\";\nimport gemiVite from \"../vite\";\nimport { Instrumentation } from \"./types\";\nimport { printStartupBanner } from \"./banner\";\nimport { GEMI_EXTERNAL_SPECIFIERS } from \"../internal/gemiExternals\";\nimport { createDevFetch, sendErrorToClient, ssrRunner } from \"./devFetch\";\nimport { resolveHmrPort } from \"./hmrPort\";\nimport { serverIdleTimeout } from \"./idleTimeout\";\nimport {\n type HmrRelayData,\n hmrRelayHandler,\n hmrRelayPort,\n isHmrUpgrade,\n listenHmrServer,\n upgradeHmr,\n} from \"./hmrRelay\";\n\nexport { viteErrorPayload } from \"./devFetch\";\n\nconst rootDir = process.cwd();\nconst appDir = join(rootDir, \"app\");\n\n// `bun --hot` re-evaluates the module graph on every server-code change. A\n// syntax error or top-level throw in app code therefore fails during *module\n// load* — outside any request, and before `httpDev` re-runs — so Bun only\n// prints it to the console. Bun surfaces these as `unhandledRejection` (the\n// reload re-imports the entry and the failing dynamic import rejects), so hook\n// that here and forward it to the client. Registered once; process listeners\n// persist across reloads.\nif (!globalThis.__gemiErrorHooked) {\n globalThis.__gemiErrorHooked = true;\n process.on(\"unhandledRejection\", (reason) => {\n console.error(reason);\n sendErrorToClient(reason);\n });\n process.on(\"uncaughtException\", (err) => {\n console.error(err);\n sendErrorToClient(err);\n });\n}\n\nexport async function httpDev(app: App, instrumentation: Instrumentation) {\n // Same override the prod server honors (`httpProd.ts`). Read here rather than\n // inline at `Bun.serve` because the HMR port is derived from it.\n const httpPort = Number(process.env.PORT) || 5173;\n // The same `SERVER_IDLE_TIMEOUT` `gemi start` honours (#787), so a long-poll\n // that works in production is not cut at Bun's 10s here. Read before Vite\n // starts so a bad value fails the boot first. Upgraded sockets, the HMR relay\n // among them, are not subject to it.\n const idleTimeout = serverIdleTimeout();\n\n // `bun --hot` re-runs this module on every server-code change, so keep a\n // single Vite server on `globalThis` instead of spawning a new one (and a new\n // HMR socket) on each reload.\n const isReload = Boolean(globalThis.__gemiVite);\n const vite = (globalThis.__gemiVite ??= await createServer({\n // gemi owns the Vite setup — the app has no `vite.config.mjs` to discover.\n // Register the gemi plugin explicitly instead; it loads `gemi.config.ts` and\n // appends the app's Vite plugins (e.g. `@vitejs/plugin-react`, which serves\n // `/@react-refresh` and the HMR preamble referenced below).\n configFile: false,\n plugins: [gemiVite()],\n server: {\n middlewareMode: true,\n // The page's own port, so the HMR client's fallback (\"direct\") socket\n // also targets this server rather than Vite's default 5173.\n port: httpPort,\n // In middleware mode Vite would stand up a second HTTP server for the HMR\n // websocket on a fixed port — so two `gemi dev` processes fought over one\n // socket, and a proxy or tunnel, which carries only the page's port,\n // could not reach it at all. Hand Vite a loopback server instead, on a\n // port of this process's own (see `hmrPort.ts` for how it is chosen):\n // given a server, Vite tells the browser to connect to the page's origin,\n // and `Bun.serve` below relays that socket to it (see `hmrRelay.ts`).\n // `ws` and not the older `hmr`: `server.hmr.{port,host,…}` is\n // deprecated in Vite 8 and warns. An app overriding either one in\n // `gemi.config.ts` still wins — plugin config (where `gemi.config.ts`'s\n // `vite` block is applied) is merged over this inline config, and Vite's\n // own `hmr`→`ws` compat shim forwards the deprecated spelling here.\n ws: { server: await listenHmrServer(resolveHmrPort(httpPort)) },\n // Vite answers any host other than `localhost` and `*.localhost` with a\n // 403, which would block a `route.domains` root such as `lvh.me` and\n // every custom domain pointed here from `/etc/hosts`.\n allowedHosts: app.devAllowedHosts.call(app),\n // gemi reloads `.env` into process.env itself (see `watchEnv`). Stop Vite\n // from *also* watching env files: Vite's env-change handler restarts the\n // dev server, which closes the SSR module runner — but gemi keeps a single\n // Vite instance across `bun --hot` reloads, so an in-flight view import\n // hits the closed runner (\"Vite module runner has been closed\"). Ignoring\n // env files here only disables the restart; env *loading* at startup (and\n // `import.meta.env`) is unaffected.\n watch: {\n ignored: (file: string) => {\n const base = file.split(/[/\\\\]/).pop() ?? \"\";\n return base === \".env\" || base.startsWith(\".env.\");\n },\n },\n },\n appType: \"custom\",\n // Views are loaded through this SSR graph while the renderer\n // (react-dom/server in ViewRouteDispatcher) is imported by Bun.\n // Dedupe so Vite can never resolve a second React copy — a mismatch makes\n // the SSR dispatcher null (\"Invalid hook call\") after an HMR reload.\n resolve: { dedupe: [\"react\", \"react-dom\"] },\n // Pre-bundle the whole React surface the client uses in one pass. The client\n // imports `react-dom/client` (`init.tsx`) and `react-dom` (`createPortal` in\n // `HttpReload.tsx`); if only the first is discovered at startup, the first\n // request to a module using the second triggers a *second* optimize pass,\n // and the already-served page ends up importing a now-stale dep — surfacing\n // as \"does not provide an export named 't'\". Listing them up front bundles\n // them together so no re-optimization (and no version skew) happens.\n optimizeDeps: { include: [\"react\", \"react-dom\", \"react-dom/client\"] },\n // `gemi` is a linked package, so Vite would otherwise compile its own copy\n // into this graph — giving views a *different* `RouteStateContext` (and\n // other module-level singletons) than the Bun-loaded renderer's `Root`\n // provider, so `useRouteData()` reads the empty default (`i18n` undefined).\n // Externalizing makes view imports of `gemi/*` resolve to the one Bun\n // instance. Vite's `ssr.external` matches exact specifiers (subpaths are NOT\n // covered by the bare name, and regexes are ignored here), so every subpath\n // a view might import must be listed — see `internal/gemiExternals`, the\n // shared source of truth this and the SSR build (`vite/index.ts`) both use.\n ssr: {\n external: [...GEMI_EXTERNAL_SPECIFIERS],\n },\n }));\n\n process.env.ROOT_DIR = rootDir;\n process.env.APP_DIR = appDir;\n\n const devFetch = createDevFetch(app, instrumentation, vite);\n // `null` when an app's own `server.ws` in `gemi.config.ts` sent Vite's\n // websocket elsewhere; the browser then connects there directly.\n const relayPort = hmrRelayPort(vite.config?.server?.ws);\n const server = Bun.serve<HmrRelayData>({\n port: httpPort,\n idleTimeout,\n fetch: (req, server) => {\n if (relayPort !== null && isHmrUpgrade(req)) {\n return upgradeHmr(req, server, relayPort);\n }\n return devFetch(req);\n },\n websocket: hmrRelayHandler,\n });\n\n // `bun --hot` re-evaluates its *whole* module graph on a server-code change —\n // node_modules included — so after a reload `react`, `react-dom/server` and the\n // Bun-loaded `gemi` are all fresh instances. This Vite server is not reloaded\n // with them (it is deliberately kept on `globalThis` above), and its SSR runner\n // still holds every view module it has evaluated — each bound, through the\n // externalized `gemi/*` imports, to the *previous* `gemi` and therefore the\n // previous `react`. The next render then sets the dispatcher on the new React\n // while a cached view calls hooks on the old one: \"Invalid hook call\", a null\n // `dispatcher.useContext` thrown from `useRouteData` inside a view nobody\n // touched. Editing a *view* never showed it — Vite's own watcher invalidates\n // that module, so it re-evaluates against the new instances. Editing a\n // server-only file (`app/config/*`, a feature declaration, a controller) is\n // the case with nothing to invalidate the views, so drop the evaluated\n // modules here, once per reload.\n //\n // Here and not before `Bun.serve`, with nothing awaited in between, because\n // both sides of the swap have to see a consistent pair. Until that call\n // returns the *previous* fetch handler is still serving — old dispatcher, old\n // `react-dom/server` — and a request landing there after an early clear would\n // re-evaluate its views against the *new* `gemi`: the same mismatch, reversed.\n // After it, the new handler is live and must not be given the stale ones. The\n // two statements are synchronous neighbours, so no request can be dispatched\n // between them.\n //\n // Only the *evaluated* modules go: the server-side transform cache is\n // untouched, so this costs a re-evaluation and not a re-transform. Clearing\n // the module graph as well would not have been enough anyway — externalized\n // deps (`gemi`, and React through it) are cached in the runner by URL and\n // carry no invalidation flag, which is exactly where the stale React hides.\n if (isReload) {\n ssrRunner(vite).clearCache();\n }\n\n // On a reload `app` has already been rebuilt with the new code and Bun.serve\n // above has swapped in the new fetch handler, so the updated controllers are\n // live *now*. Tell the client to re-run its queries only at this point —\n // firing it from Vite's file watcher instead races Bun's reload and leaves\n // the UI one change behind.\n if (isReload) {\n // We got here, so the reload succeeded. Recover from any error that was\n // showing: a standalone error page must be fully reloaded to get the app\n // back, whereas an overlay pushed onto a live page is cleared by the\n // client's `http-reload` handler (no jarring full-page reload). A normal\n // reload just re-runs client queries against the now-live controllers.\n if (globalThis.__gemiErrorActive && globalThis.__gemiErrorPageServed) {\n globalThis.__gemiErrorActive = false;\n globalThis.__gemiErrorPageServed = false;\n vite.ws.send({ type: \"full-reload\" });\n } else {\n globalThis.__gemiErrorActive = false;\n vite.ws.send({ type: \"custom\", event: \"http-reload\" });\n }\n } else {\n // First start (not a `bun --hot` reload) — print the startup banner once.\n printStartupBanner({ port: server.port, rootDir });\n }\n\n return server;\n}\n",
6
- "import { stringEraRefusal } from \"../http/Error\";\nimport { join } from \"node:path\";\nimport { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Socket } from \"node:net\";\n\nimport type { RunnableDevEnvironment, ViteDevServer } from \"vite\";\n\nimport type { App } from \"../app\";\nimport { isApiPath } from \"../services/router/apiPath\";\nimport { renderErrorPage } from \"./renderErrorPage\";\nimport { createDevStyles } from \"./styles\";\nimport type { Instrumentation } from \"./types\";\nimport { ISLAND_ENTRY_QUERY } from \"../internal/islandRuntime\";\n\n// Run a Web `Request` through Vite's Connect middleware.\n// Resolves to a `Response` when Vite handles the request (module transforms,\n// assets, the HMR client, ...), or `null` when it calls `next()` — which, with\n// `appType: \"custom\"`, it does for everything it doesn't own.\nfunction viteMiddleware(vite: ViteDevServer, request: Request): Promise<Response | null> {\n const url = new URL(request.url);\n\n const req = new IncomingMessage(new Socket());\n req.url = url.pathname + url.search;\n req.method = request.method;\n req.headers = Object.fromEntries(request.headers);\n\n const res = new ServerResponse(req);\n const chunks: Buffer[] = [];\n\n return new Promise((resolve) => {\n res.write = ((chunk: any) => {\n if (chunk) chunks.push(Buffer.from(chunk));\n return true;\n }) as typeof res.write;\n\n res.end = ((chunk?: any) => {\n if (chunk && typeof chunk !== \"function\") chunks.push(Buffer.from(chunk));\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(res.getHeaders())) {\n if (value == null) continue;\n for (const v of Array.isArray(value) ? value : [value]) {\n headers.append(key, String(v));\n }\n }\n\n resolve(\n new Response(chunks.length ? Buffer.concat(chunks) : null, {\n status: res.statusCode,\n headers,\n }),\n );\n return res;\n }) as typeof res.end;\n\n vite.middlewares(req, res, () => resolve(null));\n });\n}\n\ndeclare global {\n // Created once and reused across `bun --hot` reloads (see below).\n var __gemiVite: ViteDevServer | undefined;\n // Guards one-time registration of the process error hooks across reloads.\n var __gemiErrorHooked: boolean | undefined;\n // An error overlay is currently showing on the client (clear it on recovery).\n var __gemiErrorActive: boolean | undefined;\n // We served a standalone error *page* (not just a pushed overlay), so the\n // visible document has no live app — recovery needs a full page reload.\n var __gemiErrorPageServed: boolean | undefined;\n}\n\n// Build the `> 1 | ...\\n | ^` codeframe Vite's overlay renders — must\n// match its `codeframeRE` (a `<line> | <text>` line followed by a `| ^` line,\n// each ending in a newline).\nfunction codeFrame(lineText: string, line: number, column: number) {\n const gutter = String(line);\n const pad = \" \".repeat(gutter.length);\n const caret = \" \".repeat(Math.max(0, column - 1)) + \"^\";\n return `${gutter} | ${lineText}\\n${pad} | ${caret}\\n`;\n}\n\n// Normalize whatever Bun/JS throws into the { message, stack, frame, loc }\n// shape Vite's error overlay consumes. Two cases matter:\n// - a real `Error` (runtime top-level throw) carries a proper `.stack`;\n// - a Bun `BuildMessage` (syntax error) has NO `.stack`, only a `.position`\n// ({ file, line, column, lineText }) — so synthesize a codeframe + loc from\n// it, otherwise the overlay shows a bare message with no location.\n// (An `Error` instance also JSON-stringifies to `{}`, so fields are copied by\n// hand either way.)\nexport function viteErrorPayload(err: any) {\n if (err && typeof err === \"object\") {\n const pos = err.position;\n if (pos && typeof pos === \"object\" && typeof pos.file === \"string\") {\n return {\n message: typeof err.message === \"string\" ? err.message : String(err),\n stack: \"\",\n frame:\n typeof pos.lineText === \"string\"\n ? codeFrame(pos.lineText, pos.line, pos.column)\n : undefined,\n loc: { file: pos.file, line: pos.line, column: pos.column },\n };\n }\n return {\n message: typeof err.message === \"string\" ? err.message : String(err),\n stack: typeof err.stack === \"string\" ? err.stack : \"\",\n };\n }\n return { message: String(err), stack: \"\" };\n}\n\n// Push an error into the browser via Vite's HMR socket. `__gemiVite` persists\n// across `bun --hot` reloads, so this works even when the reload that produced\n// the error never got far enough to (re)run `httpDev`.\nexport function sendErrorToClient(err: any) {\n const vite = globalThis.__gemiVite;\n if (!vite) return;\n vite.ws.send({ type: \"error\", err: viteErrorPayload(err) as any });\n globalThis.__gemiErrorActive = true;\n}\n\n/**\n * The SSR environment's module runner — what `vite.ssrLoadModule` is a thin\n * (and, in Vite 8, deprecated) wrapper over. Going through it directly is what\n * gives `httpDev` a handle on the evaluated-module cache it has to drop after a\n * `bun --hot` reload; `ssrLoadModule` keeps its own runner private.\n *\n * Duck-typed rather than `isRunnableDevEnvironment(environment)`: this server\n * outlives the module instance that created it, and after a reload the freshly\n * evaluated `vite` brings a *new* `RunnableDevEnvironment` class object, so the\n * `instanceof` that predicate performs is false for a perfectly runnable\n * environment. (The same one-copy-per-reload rule this whole dance is about.)\n */\nexport function ssrRunner(vite: ViteDevServer) {\n const environment = vite.environments.ssr as RunnableDevEnvironment;\n if (typeof environment?.runner?.import !== \"function\") {\n throw new Error(\"gemi dev requires a runnable Vite SSR environment.\");\n }\n return environment.runner;\n}\n\n/**\n * The dev document's single bootstrap module. It loads, in this order:\n *\n * 1. `/refresh.js` — the React Refresh preamble;\n * 2. `/@vite/client` — the HMR client;\n * 3. `/app/client.tsx` — the app.\n *\n * One module, because React emits every `bootstrapModules` entry as\n * `<script type=\"module\" async>`, and async module scripts run in whatever\n * order they finish loading. The preamble has to have installed\n * `window.$RefreshReg$` before any component module evaluates, or\n * `@vitejs/plugin-react`'s transform throws \"can't detect preamble\" and the\n * app never hydrates. Awaiting each `import()` is what makes the order a\n * guarantee rather than a race.\n *\n * The preamble and the HMR client are each caught: an app without\n * `@vitejs/plugin-react` has no `/@react-refresh` and needs no preamble, and a\n * broken HMR client must not stop the app from booting. The app's own import\n * is not caught, so its errors surface as they would from a script tag.\n */\nexport const DEV_ENTRY_PATH = \"/@gemi/dev-entry.js\";\n\nexport const DEV_ENTRY_SOURCE = `const report = (error) => console.error(error);\nawait import(\"/refresh.js\").catch(report);\nawait import(\"/@vite/client\").catch(report);\nawait import(\"/app/client.tsx\");\n`;\n\n/**\n * Installs the React Refresh preamble, as `@vitejs/plugin-react`'s own\n * `index.html` transform would.\n *\n * The runtime is imported by an origin-relative URL. An absolute one, built\n * from the request URL the server sees, breaks behind a TLS-terminating proxy\n * or tunnel: the browser is on `https://<tunnel>` while the server sees\n * `http://localhost:5173`, so the import is blocked as mixed content or points\n * at a host the browser cannot reach.\n */\nexport const REFRESH_PREAMBLE_SOURCE = `import RefreshRuntime from \"/@react-refresh\";\nRefreshRuntime.injectIntoGlobalHook(window);\nwindow.$RefreshReg$ = () => {};\nwindow.$RefreshSig$ = () => (type) => type;\nwindow.__vite_plugin_react_preamble_installed__ = true;\n`;\n\n/**\n * The scripts the dev document loads that nothing on disk backs: the\n * bootstrap entry above, `/refresh.js` with the React Refresh preamble, and\n * `/render-error.js`, which the dev error page loads. `null` for any other\n * path.\n *\n * Answered inside the global middleware, not in front of it as they were. They\n * have no production counterpart, but a gate that must hold in dev as well,\n * one that refuses traffic without a header, is only complete if nothing the\n * dev server answers goes around it.\n */\nfunction devScript(req: Request): Response | null {\n const { pathname } = new URL(req.url);\n const script = (source: string) =>\n new Response(source, {\n headers: {\n \"Content-Type\": \"application/javascript\",\n },\n });\n if (pathname === DEV_ENTRY_PATH) {\n return script(DEV_ENTRY_SOURCE);\n }\n if (pathname.startsWith(\"/render-error.js\")) {\n return script(\"window.render_error = true\");\n }\n if (pathname.startsWith(\"/refresh.js\")) {\n return script(REFRESH_PREAMBLE_SOURCE);\n }\n return null;\n}\n\n/**\n * The dev server's `fetch` handler, apart from `Bun.serve` and from creating\n * Vite, so a test can hand it a stub Vite server and drive it with plain\n * `Request`s. `httpDev` is the only other caller. This module has no import\n * side effects, unlike `httpDev.ts`, which installs process-wide error hooks.\n */\nexport function createDevFetch(\n app: App,\n instrumentation: Instrumentation,\n vite: ViteDevServer,\n): (req: Request) => Promise<Response> {\n const appDir = join(process.cwd(), \"app\");\n\n return async (req) => {\n const { pathname } = new URL(req.url);\n const errorResponse = (err: any): Response => {\n // Errors thrown *while handling a request* (a controller throwing, a\n // failing view import, ...) never hit `httpDev`'s module-load hooks,\n // so surface them here: forward to the overlay for any already-open\n // page, and render an error page for this response so a fresh load\n // (which has no live HMR socket yet) still shows the failure.\n console.error(err);\n vite.ssrFixStacktrace?.(err);\n sendErrorToClient(err);\n\n if (isApiPath(pathname)) {\n return new Response(\n JSON.stringify({\n error: stringEraRefusal(\"server_error\", err?.message ?? String(err), 500),\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n // This document has no live app (so no HttpReload listener to clear the\n // overlay) — remember that, so recovery forces a full page reload.\n globalThis.__gemiErrorPageServed = true;\n return new Response(renderErrorPage(viteErrorPayload(err)), {\n status: 500,\n headers: { \"Content-Type\": \"text/html\" },\n });\n };\n const requestHandler = async (req: Request): Promise<Response> => {\n const script = devScript(req);\n if (script) {\n return script;\n }\n try {\n const handler = app.fetch.bind(app);\n const result = (await viteMiddleware(vite, req)) ?? (await handler(req));\n if (result instanceof Response) {\n return result;\n }\n\n const viewImportMap = {};\n const ogMap = {};\n const viewModules = {};\n const template = (viewName: string, path: string) =>\n `\"${viewName}\": () => import(\"${path}\")`;\n const templates = [];\n\n for (const fileName of [\"404\", ...app.getFlatComponentTree.call(app)]) {\n if (process.env.NODE_ENV === \"test\") {\n break;\n }\n const appDir = `${process.env.APP_DIR}`;\n const mod = await ssrRunner(vite).import(`${appDir}/views/${fileName}.tsx`);\n\n viewImportMap[fileName] = mod.default;\n ogMap[fileName] = mod?.OpenGraph;\n // The whole module, so a streaming render can put the view's\n // `Loading`/`Error` exports into the shell it sends.\n viewModules[fileName] = mod;\n // Emit a root-relative URL (`/app/views/Foo.tsx`), NOT the absolute\n // filesystem path the runner import above uses. The browser's\n // `window.loaders` preload and `client.tsx`'s `import.meta.glob` map\n // must import the exact same URL — otherwise Vite serves the module\n // under two URLs (`/app/views/Foo.tsx` vs `/Users/.../app/views/Foo.tsx`)\n // and loads/instantiates the view twice.\n templates.push(template(fileName, `/app/views/${fileName}.tsx`));\n }\n\n const loaders = `{${templates.join(\",\")}}`;\n\n return await result({\n getStyles: async (currentViews: string[], options?: { static?: boolean; layout?: string }) =>\n await createDevStyles(appDir, vite, currentViews, options?.layout),\n // Vite serves app files by their root-relative path; the island\n // entry is that path plus the plugin's query.\n resolveIsland: (moduleKey: string) => ({\n src: `/${moduleKey}${ISLAND_ENTRY_QUERY}`,\n preload: [],\n }),\n bootstrapModules: [DEV_ENTRY_PATH],\n viewImportMap,\n viewModules,\n ogMap,\n loaders,\n cssManifest: {},\n });\n } catch (err: any) {\n return errorResponse(err);\n }\n };\n\n // In front of Vite's middleware, the dev scripts and the app, as\n // `httpProd` puts the global middleware in front of its static files, so a\n // check that passes here passes there. A throw from it is answered like\n // one from a route. Vite's HMR websocket is the one thing it cannot cover:\n // its upgrade is relayed to Vite by `Bun.serve` (see `hmrRelay.ts`) before\n // this handler runs, and Vite checks the token and host itself.\n return await instrumentation(req, (req) =>\n app.withGlobalMiddleware(req, requestHandler, errorResponse),\n );\n };\n}\n",
6
+ "import { stringEraRefusal } from \"../http/Error\";\nimport { join } from \"node:path\";\nimport { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Socket } from \"node:net\";\n\nimport type { RunnableDevEnvironment, ViteDevServer } from \"vite\";\n\nimport type { App } from \"../app\";\nimport { isApiPath } from \"../services/router/apiPath\";\nimport { renderErrorPage } from \"./renderErrorPage\";\nimport { createDevStyles } from \"./styles\";\nimport type { Instrumentation } from \"./types\";\nimport { ISLAND_ENTRY_QUERY } from \"../internal/islandRuntime\";\n\n// Run a Web `Request` through Vite's Connect middleware.\n// Resolves to a `Response` when Vite handles the request (module transforms,\n// assets, the HMR client, ...), or `null` when it calls `next()` — which, with\n// `appType: \"custom\"`, it does for everything it doesn't own.\nfunction viteMiddleware(vite: ViteDevServer, request: Request): Promise<Response | null> {\n const url = new URL(request.url);\n\n const req = new IncomingMessage(new Socket());\n req.url = url.pathname + url.search;\n req.method = request.method;\n req.headers = Object.fromEntries(request.headers);\n\n const res = new ServerResponse(req);\n const chunks: Buffer[] = [];\n\n return new Promise((resolve) => {\n res.write = ((chunk: any) => {\n if (chunk) chunks.push(Buffer.from(chunk));\n return true;\n }) as typeof res.write;\n\n res.end = ((chunk?: any) => {\n if (chunk && typeof chunk !== \"function\") chunks.push(Buffer.from(chunk));\n\n const headers = new Headers();\n for (const [key, value] of Object.entries(res.getHeaders())) {\n if (value == null) continue;\n for (const v of Array.isArray(value) ? value : [value]) {\n headers.append(key, String(v));\n }\n }\n\n resolve(\n new Response(chunks.length ? Buffer.concat(chunks) : null, {\n status: res.statusCode,\n headers,\n }),\n );\n return res;\n }) as typeof res.end;\n\n vite.middlewares(req, res, () => resolve(null));\n });\n}\n\ndeclare global {\n // Created once and reused across `bun --hot` reloads (see below).\n var __gemiVite: ViteDevServer | undefined;\n // Guards one-time registration of the process error hooks across reloads.\n var __gemiErrorHooked: boolean | undefined;\n // An error overlay is currently showing on the client (clear it on recovery).\n var __gemiErrorActive: boolean | undefined;\n // We served a standalone error *page* (not just a pushed overlay), so the\n // visible document has no live app — recovery needs a full page reload.\n var __gemiErrorPageServed: boolean | undefined;\n}\n\n// Build the `> 1 | ...\\n | ^` codeframe Vite's overlay renders — must\n// match its `codeframeRE` (a `<line> | <text>` line followed by a `| ^` line,\n// each ending in a newline).\nfunction codeFrame(lineText: string, line: number, column: number) {\n const gutter = String(line);\n const pad = \" \".repeat(gutter.length);\n const caret = \" \".repeat(Math.max(0, column - 1)) + \"^\";\n return `${gutter} | ${lineText}\\n${pad} | ${caret}\\n`;\n}\n\n// Normalize whatever Bun/JS throws into the { message, stack, frame, loc }\n// shape Vite's error overlay consumes. Two cases matter:\n// - a real `Error` (runtime top-level throw) carries a proper `.stack`;\n// - a Bun `BuildMessage` (syntax error) has NO `.stack`, only a `.position`\n// ({ file, line, column, lineText }) — so synthesize a codeframe + loc from\n// it, otherwise the overlay shows a bare message with no location.\n// (An `Error` instance also JSON-stringifies to `{}`, so fields are copied by\n// hand either way.)\nexport function viteErrorPayload(err: any) {\n if (err && typeof err === \"object\") {\n const pos = err.position;\n if (pos && typeof pos === \"object\" && typeof pos.file === \"string\") {\n return {\n message: typeof err.message === \"string\" ? err.message : String(err),\n stack: \"\",\n frame:\n typeof pos.lineText === \"string\"\n ? codeFrame(pos.lineText, pos.line, pos.column)\n : undefined,\n loc: { file: pos.file, line: pos.line, column: pos.column },\n };\n }\n return {\n message: typeof err.message === \"string\" ? err.message : String(err),\n stack: typeof err.stack === \"string\" ? err.stack : \"\",\n };\n }\n return { message: String(err), stack: \"\" };\n}\n\n// Push an error into the browser via Vite's HMR socket. `__gemiVite` persists\n// across `bun --hot` reloads, so this works even when the reload that produced\n// the error never got far enough to (re)run `httpDev`.\nexport function sendErrorToClient(err: any) {\n const vite = globalThis.__gemiVite;\n if (!vite) return;\n vite.ws.send({ type: \"error\", err: viteErrorPayload(err) as any });\n globalThis.__gemiErrorActive = true;\n}\n\n/**\n * The SSR environment's module runner — what `vite.ssrLoadModule` is a thin\n * (and, in Vite 8, deprecated) wrapper over. Going through it directly is what\n * gives `httpDev` a handle on the evaluated-module cache it has to drop after a\n * `bun --hot` reload; `ssrLoadModule` keeps its own runner private.\n *\n * Duck-typed rather than `isRunnableDevEnvironment(environment)`: this server\n * outlives the module instance that created it, and after a reload the freshly\n * evaluated `vite` brings a *new* `RunnableDevEnvironment` class object, so the\n * `instanceof` that predicate performs is false for a perfectly runnable\n * environment. (The same one-copy-per-reload rule this whole dance is about.)\n */\nexport function ssrRunner(vite: ViteDevServer) {\n const environment = vite.environments.ssr as RunnableDevEnvironment;\n if (typeof environment?.runner?.import !== \"function\") {\n throw new Error(\"gemi dev requires a runnable Vite SSR environment.\");\n }\n return environment.runner;\n}\n\n/**\n * The dev document's single bootstrap module. It loads, in this order:\n *\n * 1. `/refresh.js` — the React Refresh preamble;\n * 2. `/@vite/client` — the HMR client;\n * 3. `/app/client.tsx` — the app.\n *\n * One module, because React emits every `bootstrapModules` entry as\n * `<script type=\"module\" async>`, and async module scripts run in whatever\n * order they finish loading. The preamble has to have installed\n * `window.$RefreshReg$` before any component module evaluates, or\n * `@vitejs/plugin-react`'s transform throws \"can't detect preamble\" and the\n * app never hydrates. Awaiting each `import()` is what makes the order a\n * guarantee rather than a race.\n *\n * The preamble and the HMR client are each caught: an app without\n * `@vitejs/plugin-react` has no `/@react-refresh` and needs no preamble, and a\n * broken HMR client must not stop the app from booting. The app's own import\n * is not caught, so its errors surface as they would from a script tag.\n */\nexport const DEV_ENTRY_PATH = \"/@gemi/dev-entry.js\";\n\nexport const DEV_ENTRY_SOURCE = `const report = (error) => console.error(error);\nawait import(\"/refresh.js\").catch(report);\nawait import(\"/@vite/client\").catch(report);\nawait import(\"/app/client.tsx\");\n`;\n\n/**\n * Installs the React Refresh preamble, as `@vitejs/plugin-react`'s own\n * `index.html` transform would.\n *\n * The runtime is imported by an origin-relative URL. An absolute one, built\n * from the request URL the server sees, breaks behind a TLS-terminating proxy\n * or tunnel: the browser is on `https://<tunnel>` while the server sees\n * `http://localhost:5173`, so the import is blocked as mixed content or points\n * at a host the browser cannot reach.\n */\nexport const REFRESH_PREAMBLE_SOURCE = `import RefreshRuntime from \"/@react-refresh\";\nRefreshRuntime.injectIntoGlobalHook(window);\nwindow.$RefreshReg$ = () => {};\nwindow.$RefreshSig$ = () => (type) => type;\nwindow.__vite_plugin_react_preamble_installed__ = true;\n`;\n\n/**\n * The scripts the dev document loads that nothing on disk backs: the\n * bootstrap entry above, `/refresh.js` with the React Refresh preamble, and\n * `/render-error.js`, which the dev error page loads. `null` for any other\n * path.\n *\n * Answered inside the global middleware, not in front of it as they were. They\n * have no production counterpart, but a gate that must hold in dev as well,\n * one that refuses traffic without a header, is only complete if nothing the\n * dev server answers goes around it.\n */\nfunction devScript(req: Request): Response | null {\n const { pathname } = new URL(req.url);\n const script = (source: string) =>\n new Response(source, {\n headers: {\n \"Content-Type\": \"application/javascript\",\n },\n });\n if (pathname === DEV_ENTRY_PATH) {\n return script(DEV_ENTRY_SOURCE);\n }\n if (pathname.startsWith(\"/render-error.js\")) {\n return script(\"window.render_error = true\");\n }\n if (pathname.startsWith(\"/refresh.js\")) {\n return script(REFRESH_PREAMBLE_SOURCE);\n }\n return null;\n}\n\n/**\n * The dev server's `fetch` handler, apart from `Bun.serve` and from creating\n * Vite, so a test can hand it a stub Vite server and drive it with plain\n * `Request`s. `httpDev` is the only other caller. This module has no import\n * side effects, unlike `httpDev.ts`, which installs process-wide error hooks.\n */\nexport function createDevFetch(\n app: App,\n instrumentation: Instrumentation,\n vite: ViteDevServer,\n): (req: Request) => Promise<Response> {\n const appDir = join(process.cwd(), \"app\");\n\n return async (req) => {\n const { pathname } = new URL(req.url);\n const errorResponse = (err: any): Response => {\n // Errors thrown *while handling a request* (a controller throwing, a\n // failing view import, ...) never hit `httpDev`'s module-load hooks,\n // so surface them here: forward to the overlay for any already-open\n // page, and render an error page for this response so a fresh load\n // (which has no live HMR socket yet) still shows the failure.\n console.error(err);\n vite.ssrFixStacktrace?.(err);\n sendErrorToClient(err);\n\n if (isApiPath(pathname)) {\n return new Response(\n JSON.stringify({\n error: stringEraRefusal(\"server_error\", err?.message ?? String(err), 500),\n }),\n {\n status: 500,\n headers: { \"Content-Type\": \"application/json\" },\n },\n );\n }\n\n // This document has no live app (so no HttpReload listener to clear the\n // overlay) — remember that, so recovery forces a full page reload.\n globalThis.__gemiErrorPageServed = true;\n return new Response(renderErrorPage(viteErrorPayload(err)), {\n status: 500,\n headers: { \"Content-Type\": \"text/html\" },\n });\n };\n const requestHandler = async (req: Request): Promise<Response> => {\n const script = devScript(req);\n if (script) {\n return script;\n }\n try {\n const handler = app.fetch.bind(app);\n const result = (await viteMiddleware(vite, req)) ?? (await handler(req));\n if (result instanceof Response) {\n return result;\n }\n\n const viewImportMap = {};\n const ogMap = {};\n const viewModules = {};\n const template = (viewName: string, path: string) =>\n `\"${viewName}\": () => import(\"${path}\")`;\n const templates = [];\n\n for (const fileName of [\"404\", ...app.getFlatComponentTree.call(app)]) {\n if (process.env.NODE_ENV === \"test\") {\n break;\n }\n const appDir = `${process.env.APP_DIR}`;\n const mod = await ssrRunner(vite).import(`${appDir}/views/${fileName}.tsx`);\n\n viewImportMap[fileName] = mod.default;\n ogMap[fileName] = mod?.OpenGraph;\n // The whole module, so a streaming render can put the view's\n // `Loading`/`Error` exports into the shell it sends.\n viewModules[fileName] = mod;\n // Emit a root-relative URL (`/app/views/Foo.tsx`), NOT the absolute\n // filesystem path the runner import above uses. The browser's\n // `window.loaders` preload and `client.tsx`'s `import.meta.glob` map\n // must import the exact same URL — otherwise Vite serves the module\n // under two URLs (`/app/views/Foo.tsx` vs `/Users/.../app/views/Foo.tsx`)\n // and loads/instantiates the view twice.\n templates.push(template(fileName, `/app/views/${fileName}.tsx`));\n }\n\n const loaders = `{${templates.join(\",\")}}`;\n\n return await result({\n getStyles: async (currentViews: string[], options?: { static?: boolean; layout?: string }) =>\n await createDevStyles(appDir, vite, currentViews, options?.layout),\n // Vite serves app files by their root-relative path; the island\n // entry is that path plus the plugin's query.\n resolveIsland: (moduleKey: string) => ({\n src: `/${moduleKey}${ISLAND_ENTRY_QUERY}`,\n preload: [],\n }),\n // Vite serves modules fresh, so dev has one build.\n buildId: \"dev\",\n bootstrapModules: [DEV_ENTRY_PATH],\n viewImportMap,\n viewModules,\n ogMap,\n loaders,\n cssManifest: {},\n });\n } catch (err: any) {\n return errorResponse(err);\n }\n };\n\n // In front of Vite's middleware, the dev scripts and the app, as\n // `httpProd` puts the global middleware in front of its static files, so a\n // check that passes here passes there. A throw from it is answered like\n // one from a route. Vite's HMR websocket is the one thing it cannot cover:\n // its upgrade is relayed to Vite by `Bun.serve` (see `hmrRelay.ts`) before\n // this handler runs, and Vite checks the token and host itself.\n return await instrumentation(req, (req) =>\n app.withGlobalMiddleware(req, requestHandler, errorResponse),\n );\n };\n}\n",
7
7
  "function cleanupTerminalText(text) {\n return (\n text\n // Remove ANSI escape sequences (colors, formatting)\n .replace(/\\x1b\\[[0-9;]*m/g, \"\")\n // Remove ANSI escape sequences with different format\n .replace(/\\[[0-9;]*m/g, \"\")\n // Remove excessive whitespace and normalize line breaks\n .replace(/\\n\\s*\\n/g, \"\\n\")\n // Trim each line\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .join(\"\\n\")\n .trim()\n );\n}\n\nexport function renderErrorPage(err: any) {\n return `\n<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta\n name=\"viewport\"\n content=\"width=device-width, initial-scale=1.0\"\n />\n\n <title>Error</title>\n <style>\n body {\n font-family: Arial, sans-serif;\n padding: 20px;\n }\n h1 {\n color: red;\n }\n </style>\n </head>\n <body>\n <div id=\"overlay\"></div>\n <script type=\"module\" src=\"/refresh.js\"></script>\n <script type=\"module\" src=\"/@vite/client\"></script>\n <script>\n ${cleanupTerminalText.toString()}\n const err = ${JSON.stringify(err, Object.getOwnPropertyNames(err), 2)}\n\n window.addEventListener('load', () => {\n const container = document.getElementById('overlay')\n const ErrorOverlay = customElements.get('vite-error-overlay')\n if (ErrorOverlay) {\n const overlay = new ErrorOverlay({ ...err, message: cleanupTerminalText(err.message) });\n container.appendChild(overlay)\n }\n })\n </script>\n </body>\n</html>\n`;\n}\n",
8
8
  "// Vite's HMR websocket needs a port of its own, and in middleware mode Vite\n// always picks the same one.\n//\n// `httpDev` runs Vite with `middlewareMode: true`, so Vite has no HTTP server of\n// its own to hang the websocket off — it stands up a second HTTP server just for\n// the upgrade. When nothing names a port, that server binds Vite's default 24678\n// in *every* `gemi dev` process. `PORT` moves the Bun server and nothing else, so\n// a second dev server logs\n//\n// WebSocket server error: Port undefined is already in use\n//\n// and carries on with a dead socket. (Vite logs that failure rather than throwing\n// — which is why the symptom is not a crash but pages that hot-reload on the\n// *other* checkout's edits: their `/@vite/client` was told 24678, and 24678 is\n// the first server's.) So gemi names the port instead of letting Vite default it.\n//\n// Why derive from the HTTP port rather than just scan for a free one: two dev\n// servers must already differ in `PORT` to run at all, so deriving makes their\n// HMR ports differ *before* either one binds anything. A scan alone would hand\n// both the same port when they start at the same moment, each having probed\n// before the other bound. The scan is still here, for the port being taken by\n// something that is not a gemi dev server.\n\nconst VITE_DEFAULT_HTTP_PORT = 5173;\nconst VITE_DEFAULT_HMR_PORT = 24678;\n\n// A port is 16 bits.\nconst MAX_PORT = 65535;\n\n// How far to walk up from the derived port before giving up. Large enough that\n// only a pathological machine exhausts it, small enough to fail in well under a\n// second rather than appearing to hang.\nconst SEARCH_WINDOW = 64;\n\n/**\n * Bind-test a port the same way Vite will.\n *\n * Vite calls `wsHttpServer.listen(port, host)` with no host unless one is\n * configured, so its websocket server takes the wildcard address — which is what\n * this binds too. The match matters: a wildcard bind collides with a wildcard\n * *or* a loopback holder, while a loopback bind only collides with loopback. A\n * process holding `127.0.0.1:P` alone therefore reads as free here, correctly —\n * Vite would fail to bind `*:P` against it, but nothing in gemi makes Vite bind\n * loopback-only, so that case cannot arise from a second `gemi dev`.\n *\n * Only `EADDRINUSE` counts as taken. Any other failure — a permission error, an\n * unroutable address — is not something a different port would fix, so it is\n * reported free and left for Vite to surface.\n */\nfunction isPortFree(port: number): boolean {\n try {\n const listener = Bun.listen({\n hostname: \"0.0.0.0\",\n port,\n socket: { data() {} },\n });\n // `true` closes active connections too. There are none — nothing has been\n // told this port exists yet — but it also makes the close synchronous, so\n // the port is released before the next probe or before Vite binds it.\n listener.stop(true);\n return true;\n } catch (error) {\n return (error as { code?: string })?.code !== \"EADDRINUSE\";\n }\n}\n\n/**\n * Pick the port for Vite's HMR websocket, given the port the dev server's HTTP\n * side is on.\n *\n * `5173` returns `24678` — Vite's two defaults stay paired, so a single dev\n * server behaves exactly as it did before, and anything pointed at 24678 (a\n * firewall rule, a container port mapping, a note in a README) keeps working.\n * Every other HTTP port is offset by the same distance, so distinct `PORT`s\n * always yield distinct HMR ports.\n *\n * @param isFree Injected for tests. Production callers use the bind test above.\n */\nexport function resolveHmrPort(\n httpPort: number,\n isFree: (port: number) => boolean = isPortFree,\n): number {\n let start = VITE_DEFAULT_HMR_PORT + (httpPort - VITE_DEFAULT_HTTP_PORT);\n\n // A high `PORT` can push the derived port past the top of the range — or so\n // close to it that the walk would run off the end. Fall back to the default\n // and let the scan sort it out; being *adjacent* to another server's port is\n // fine, landing *on* it is what has to be avoided, and the scan does that.\n //\n // There is deliberately no matching floor. The offset is only -5173, so the\n // lowest a real HTTP port can derive is 19505 (from `PORT=0`) — a guard for\n // the bottom of the range would be a branch no input can take.\n if (start > MAX_PORT - SEARCH_WINDOW) {\n start = VITE_DEFAULT_HMR_PORT;\n }\n\n for (let port = start; port < start + SEARCH_WINDOW; port++) {\n if (isFree(port)) return port;\n }\n\n throw new Error(\n `Could not find a free port for Vite's HMR websocket: tried ${start}-${\n start + SEARCH_WINDOW - 1\n }. Set one explicitly in gemi.config.ts as \\`vite: { server: { ws: { port } } }\\`.`,\n );\n}\n",
9
9
  "import { createServer, type Server as NodeServer } from \"node:http\";\n\nimport type { Server, ServerWebSocket, WebSocketHandler } from \"bun\";\n\n// Vite's HMR websocket, carried on the dev server's own port.\n//\n// In middleware mode Vite has no HTTP server of its own, so by default it\n// stands up a second one for the websocket, on a second port (see\n// `hmrPort.ts`), and tells the browser to connect to `<page host>:<that port>`.\n// A reverse proxy or tunnel (ngrok, a container port mapping, a phone on the\n// LAN through https) only carries the port the page came from, so HMR could\n// not connect there, and the client logged connection failures forever.\n//\n// Vite can attach its websocket to a server it is handed (`server.ws.server`)\n// instead, and then tells the browser to connect to the page's own origin. That\n// server has to be a Node `http.Server`; the dev server is `Bun.serve`. So:\n//\n// - the Node server Vite is handed listens on loopback only, on the port\n// `resolveHmrPort` picked, and answers nothing but websocket upgrades;\n// - `Bun.serve` accepts the browser's upgrade on the page's origin and relays\n// frames both ways to that loopback server.\n//\n// The relay forwards the browser's `Host` and `Origin` and the request's query\n// (the `token`), so Vite still runs its own host and token checks against what\n// the browser actually sent.\n\n/** The subprotocols Vite's client opens its sockets with. */\nconst VITE_PROTOCOLS = new Set([\"vite-hmr\", \"vite-ping\"]);\n\n/**\n * Start the loopback Node server Vite attaches its HMR websocket to.\n * Everything but an upgrade gets `426 Upgrade Required`, as Vite's own\n * websocket server answers.\n */\nexport async function listenHmrServer(port: number): Promise<NodeServer> {\n const server = createServer((_req, res) => {\n res.writeHead(426, { \"Content-Type\": \"text/plain\" });\n res.end(\"Upgrade Required\");\n });\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(port, \"127.0.0.1\", () => {\n server.off(\"error\", reject);\n resolve();\n });\n });\n return server;\n}\n\n/**\n * The loopback port to relay to, read from the config Vite actually resolved,\n * so an app that set its own `server.ws` in `gemi.config.ts` is relayed to\n * where Vite really is, or not relayed at all. `null` when Vite was not given\n * a server (its websocket is then on a port of its own, and the client goes\n * there directly) or when HMR is off.\n */\nexport function hmrRelayPort(wsConfig: unknown): number | null {\n if (!wsConfig || typeof wsConfig !== \"object\") return null;\n const server = (wsConfig as { server?: { address?: () => unknown } }).server;\n const address = server?.address?.();\n if (address && typeof address === \"object\" && \"port\" in address) {\n return Number((address as { port: number }).port) || null;\n }\n return null;\n}\n\n/** Whether a request is the Vite client opening its HMR (or ping) socket. */\nexport function isHmrUpgrade(req: Request): boolean {\n if (req.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\") return false;\n return VITE_PROTOCOLS.has(req.headers.get(\"sec-websocket-protocol\") ?? \"\");\n}\n\nexport type HmrRelayData = {\n /** The socket to Vite, already open when the browser's is accepted. */\n upstream: WebSocket;\n /** Frames Vite sent before the browser's socket opened (its `connected`). */\n early: (string | Uint8Array)[];\n browser?: ServerWebSocket<HmrRelayData>;\n};\n\ntype Frame = string | Uint8Array;\n\nconst frameOf = (data: unknown): Frame =>\n typeof data === \"string\" ? data : new Uint8Array(data as ArrayBuffer);\n\n/**\n * Open the socket to Vite first, and accept the browser's upgrade only once\n * Vite has accepted it. Returns `undefined` once Bun has taken the request\n * over, or a refusal.\n *\n * The order matters. Vite refuses a socket whose host is not in\n * `allowedHosts`, or a cross-origin one without its token. Had the browser's\n * socket been accepted first and closed when Vite refused, the client would\n * read that as \"server connection lost\", ping (which Vite always answers),\n * and reload the page, forever. Refused before it opens, the client logs one\n * \"failed to connect to websocket\" and the page keeps working.\n */\nexport async function upgradeHmr(\n req: Request,\n server: Server<HmrRelayData>,\n port: number,\n): Promise<Response | undefined> {\n const url = new URL(req.url);\n const protocol = req.headers.get(\"sec-websocket-protocol\") ?? \"vite-hmr\";\n // `Host` is what Vite's `allowedHosts` check reads; the URL's host is the\n // same value `Bun.serve` derived it from.\n const headers: Record<string, string> = {\n host: req.headers.get(\"host\") ?? url.host,\n };\n const origin = req.headers.get(\"origin\");\n if (origin) headers.origin = origin;\n\n const upstream = new WebSocket(\n `ws://127.0.0.1:${port}${url.pathname}${url.search}`,\n {\n protocols: [protocol],\n headers,\n } as any,\n );\n upstream.binaryType = \"arraybuffer\";\n const data: HmrRelayData = { upstream, early: [] };\n\n upstream.onmessage = (event) => {\n const frame = frameOf(event.data);\n if (data.browser) data.browser.send(frame);\n else data.early.push(frame);\n };\n upstream.onclose = (event) => {\n data.browser?.close(sendableCloseCode(event.code), event.reason);\n };\n upstream.onerror = () => {\n // A `close` follows; it ends the browser's socket if there is one.\n };\n\n const opened = await new Promise<boolean>((resolve) => {\n upstream.addEventListener(\"open\", () => resolve(true), { once: true });\n upstream.addEventListener(\"close\", () => resolve(false), { once: true });\n });\n if (!opened) {\n return new Response(\"Vite refused the HMR websocket\", { status: 403 });\n }\n\n const upgraded = server.upgrade(req, {\n // The browser fails a connection whose response does not echo the\n // subprotocol it asked for.\n headers: { \"Sec-WebSocket-Protocol\": protocol },\n data,\n });\n if (!upgraded) {\n upstream.close();\n return new Response(\"WebSocket upgrade failed\", { status: 400 });\n }\n return undefined;\n}\n\n// A close code that may be sent in a close frame. 1005, 1006 and 1015 are\n// reported locally and never sent.\nfunction sendableCloseCode(code: number): number {\n if (\n code === 1000 ||\n (code >= 1001 && code <= 1003) ||\n (code >= 1007 && code <= 1014)\n ) {\n return code;\n }\n if (code >= 3000 && code <= 4999) return code;\n return 1000;\n}\n\n/** `Bun.serve`'s `websocket` option: relays frames to and from Vite. */\nexport const hmrRelayHandler: WebSocketHandler<HmrRelayData> = {\n open(ws: ServerWebSocket<HmrRelayData>) {\n const data = ws.data;\n for (const frame of data.early) ws.send(frame);\n data.early = [];\n data.browser = ws;\n // Vite may have hung up while the upgrade was in flight.\n if (data.upstream.readyState !== WebSocket.OPEN) ws.close(1000);\n },\n message(ws: ServerWebSocket<HmrRelayData>, message) {\n if (ws.data.upstream.readyState === WebSocket.OPEN) {\n ws.data.upstream.send(message);\n }\n },\n close(ws: ServerWebSocket<HmrRelayData>) {\n const { upstream } = ws.data;\n if (upstream.readyState <= WebSocket.OPEN) upstream.close();\n },\n};\n"
10
10
  ],
11
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,EAQ1C,aAAc,CAAE,QAAS,CAAC,QAAS,YAAa,kBAAkB,CAAE,EAUpE,IAAK,CACH,SAAU,CAAC,GAAG,CAAwB,CACxC,CACF,CAAC,EAED,QAAQ,IAAI,SAAW,EACvB,QAAQ,IAAI,QAAU,GAEtB,IAAM,EAAW,EAAe,EAAK,EAAiB,CAAI,EAGpD,EAAY,EAAa,EAAK,QAAQ,QAAQ,EAAE,EAChD,EAAS,IAAI,MAAoB,CACrC,KAAM,EACN,cACA,MAAO,CAAC,EAAK,IAAW,CACtB,GAAI,IAAc,MAAQ,EAAa,CAAG,EACxC,OAAO,EAAW,EAAK,EAAQ,CAAS,EAE1C,OAAO,EAAS,CAAG,GAErB,UAAW,CACb,CAAC,EA+BD,GAAI,EACF,EAAU,CAAI,EAAE,WAAW,EAQ7B,GAAI,EAMF,GAAI,WAAW,mBAAqB,WAAW,sBAC7C,WAAW,kBAAoB,GAC/B,WAAW,sBAAwB,GACnC,EAAK,GAAG,KAAK,CAAE,KAAM,aAAc,CAAC,EAEpC,gBAAW,kBAAoB,GAC/B,EAAK,GAAG,KAAK,CAAE,KAAM,SAAU,MAAO,aAAc,CAAC,EAIvD,OAAmB,CAAE,KAAM,EAAO,KAAM,SAAQ,CAAC,EAGnD,OAAO",
12
+ "debugId": "DD235AA05CAC380F64756E2164756E21",
13
13
  "names": []
14
14
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Y as r}from"./chunk-bw2pfaz3.js";import{Z as mc}from"./chunk-qpy25jj9.js";import"./chunk-svn6zvzd.js";import"./chunk-q00f25na.js";import{aa as _}from"./chunk-s2h85rbf.js";import{gj as u,jj as O}from"./chunk-j5q5ysng.js";import{Buffer as hc}from"buffer";import{request as Yc}from"http";function E(c){return new Promise((I,x)=>{let N=Yc({method:"GET",...c,hostname:c.hostname?.replace(/^\[(.+)\]$/,"$1")});N.on("error",(T)=>{x(Object.assign(new K.ProviderError("Unable to connect to instance metadata service"),T)),N.destroy()}),N.on("timeout",()=>{x(new K.ProviderError("TimeoutError from instance metadata service")),N.destroy()}),N.on("response",(T)=>{let{statusCode:y=400}=T;if(y<200||300<=y)x(Object.assign(new K.ProviderError("Error response received from instance metadata service"),{statusCode:y})),N.destroy();let $=[];T.on("data",(w)=>{$.push(w)}),T.on("end",()=>{I(hc.concat($)),N.destroy()})}),N.end()})}var K;var D=O(()=>{K=u(_(),1)});var G=(c)=>Boolean(c)&&typeof c==="object"&&typeof c.AccessKeyId==="string"&&typeof c.SecretAccessKey==="string"&&typeof c.Token==="string"&&typeof c.Expiration==="string",L=(c)=>({accessKeyId:c.AccessKeyId,secretAccessKey:c.SecretAccessKey,sessionToken:c.Token,expiration:new Date(c.Expiration),...c.AccountId&&{accountId:c.AccountId}});var W=()=>{};var Hc=1000,qc=0,Q=({maxRetries:c=0,timeout:I=1000})=>({maxRetries:c,timeout:I});var X=()=>{};var v=(c,I)=>{let x=c();for(let N=0;N<I;N++)x=x.catch(c);return x};var b=()=>{};import{parse as Sc}from"url";var z,H="AWS_CONTAINER_CREDENTIALS_FULL_URI",q="AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",M="AWS_CONTAINER_AUTHORIZATION_TOKEN",kc=(c={})=>{let{timeout:I,maxRetries:x}=Q(c);return()=>v(async()=>{let N=await jc({logger:c.logger}),T=JSON.parse(await fc(I,N));if(!G(T))throw new z.CredentialsProviderError("Invalid response received from instance metadata service.",{logger:c.logger});return L(T)},x)},fc=async(c,I)=>{if(process.env[M])I.headers={...I.headers,Authorization:process.env[M]};return(await E({...I,timeout:c})).toString()},uc="169.254.170.2",Ec,$c,jc=async({logger:c})=>{if(process.env[q])return{hostname:uc,path:process.env[q]};if(process.env[H]){let I=Sc(process.env[H]);if(!I.hostname||!(I.hostname in Ec))throw new z.CredentialsProviderError(`${I.hostname} is not a valid container metadata service hostname`,{tryNextLink:!1,logger:c});if(!I.protocol||!(I.protocol in $c))throw new z.CredentialsProviderError(`${I.protocol} is not a valid container metadata service protocol`,{tryNextLink:!1,logger:c});return{...I,port:I.port?parseInt(I.port,10):void 0}}throw new z.CredentialsProviderError(`The container metadata credential provider cannot be used unless the ${q} or ${H} environment variable is set`,{tryNextLink:!1,logger:c})};var p=O(()=>{D();W();X();b();z=u(_(),1),Ec={localhost:!0,"127.0.0.1":!0},$c={"http:":!0,"https:":!0}});var C,Z;var a=O(()=>{C=u(_(),1);Z=class Z extends C.CredentialsProviderError{tryNextLink;name="InstanceMetadataV1FallbackError";constructor(c,I=!0){super(c,I);this.tryNextLink=I,Object.setPrototypeOf(this,Z.prototype)}}});var J;var B=O(()=>{(function(c){c.IPv4="http://169.254.169.254",c.IPv6="http://[fd00:ec2::254]"})(J||(J={}))});var n;var o=O(()=>{n={environmentVariableSelector:(c)=>c.AWS_EC2_METADATA_SERVICE_ENDPOINT,configFileSelector:(c)=>c.ec2_metadata_service_endpoint,default:void 0}});var f;var t=O(()=>{(function(c){c.IPv4="IPv4",c.IPv6="IPv6"})(f||(f={}))});var Ac="AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE",Jc="ec2_metadata_service_endpoint_mode",s;var g=O(()=>{t();s={environmentVariableSelector:(c)=>c[Ac],configFileSelector:(c)=>c[Jc],default:f.IPv4}});var U,l,F=async()=>l.parseUrl(await vc()||await zc()),vc=async()=>U.loadConfig(n)(),zc=async()=>{let c=await U.loadConfig(s)();switch(c){case f.IPv4:return J.IPv4;case f.IPv6:return J.IPv6;default:throw Error(`Unsupported endpoint mode: ${c}. Select from ${Object.values(f)}`)}};var P=O(()=>{B();o();t();g();U=u(r(),1),l=u(mc(),1)});var V=(c,I)=>{let x=300+Math.floor(Math.random()*300),N=new Date(Date.now()+x*1000);I.warn(`Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(N)}.
2
+ import{Y as r}from"./chunk-c7qs1xp3.js";import{Z as mc}from"./chunk-gy81nd9a.js";import"./chunk-zrcd9hxr.js";import"./chunk-s5k3yq6t.js";import{aa as _}from"./chunk-32n8t8x6.js";import{ij as u,lj as O}from"./chunk-tewhms9w.js";import{Buffer as hc}from"buffer";import{request as Yc}from"http";function E(c){return new Promise((I,x)=>{let N=Yc({method:"GET",...c,hostname:c.hostname?.replace(/^\[(.+)\]$/,"$1")});N.on("error",(T)=>{x(Object.assign(new K.ProviderError("Unable to connect to instance metadata service"),T)),N.destroy()}),N.on("timeout",()=>{x(new K.ProviderError("TimeoutError from instance metadata service")),N.destroy()}),N.on("response",(T)=>{let{statusCode:y=400}=T;if(y<200||300<=y)x(Object.assign(new K.ProviderError("Error response received from instance metadata service"),{statusCode:y})),N.destroy();let $=[];T.on("data",(w)=>{$.push(w)}),T.on("end",()=>{I(hc.concat($)),N.destroy()})}),N.end()})}var K;var D=O(()=>{K=u(_(),1)});var G=(c)=>Boolean(c)&&typeof c==="object"&&typeof c.AccessKeyId==="string"&&typeof c.SecretAccessKey==="string"&&typeof c.Token==="string"&&typeof c.Expiration==="string",L=(c)=>({accessKeyId:c.AccessKeyId,secretAccessKey:c.SecretAccessKey,sessionToken:c.Token,expiration:new Date(c.Expiration),...c.AccountId&&{accountId:c.AccountId}});var W=()=>{};var Hc=1000,qc=0,Q=({maxRetries:c=0,timeout:I=1000})=>({maxRetries:c,timeout:I});var X=()=>{};var v=(c,I)=>{let x=c();for(let N=0;N<I;N++)x=x.catch(c);return x};var b=()=>{};import{parse as Sc}from"url";var z,H="AWS_CONTAINER_CREDENTIALS_FULL_URI",q="AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",M="AWS_CONTAINER_AUTHORIZATION_TOKEN",kc=(c={})=>{let{timeout:I,maxRetries:x}=Q(c);return()=>v(async()=>{let N=await jc({logger:c.logger}),T=JSON.parse(await fc(I,N));if(!G(T))throw new z.CredentialsProviderError("Invalid response received from instance metadata service.",{logger:c.logger});return L(T)},x)},fc=async(c,I)=>{if(process.env[M])I.headers={...I.headers,Authorization:process.env[M]};return(await E({...I,timeout:c})).toString()},uc="169.254.170.2",Ec,$c,jc=async({logger:c})=>{if(process.env[q])return{hostname:uc,path:process.env[q]};if(process.env[H]){let I=Sc(process.env[H]);if(!I.hostname||!(I.hostname in Ec))throw new z.CredentialsProviderError(`${I.hostname} is not a valid container metadata service hostname`,{tryNextLink:!1,logger:c});if(!I.protocol||!(I.protocol in $c))throw new z.CredentialsProviderError(`${I.protocol} is not a valid container metadata service protocol`,{tryNextLink:!1,logger:c});return{...I,port:I.port?parseInt(I.port,10):void 0}}throw new z.CredentialsProviderError(`The container metadata credential provider cannot be used unless the ${q} or ${H} environment variable is set`,{tryNextLink:!1,logger:c})};var p=O(()=>{D();W();X();b();z=u(_(),1),Ec={localhost:!0,"127.0.0.1":!0},$c={"http:":!0,"https:":!0}});var C,Z;var a=O(()=>{C=u(_(),1);Z=class Z extends C.CredentialsProviderError{tryNextLink;name="InstanceMetadataV1FallbackError";constructor(c,I=!0){super(c,I);this.tryNextLink=I,Object.setPrototypeOf(this,Z.prototype)}}});var J;var B=O(()=>{(function(c){c.IPv4="http://169.254.169.254",c.IPv6="http://[fd00:ec2::254]"})(J||(J={}))});var n;var o=O(()=>{n={environmentVariableSelector:(c)=>c.AWS_EC2_METADATA_SERVICE_ENDPOINT,configFileSelector:(c)=>c.ec2_metadata_service_endpoint,default:void 0}});var f;var t=O(()=>{(function(c){c.IPv4="IPv4",c.IPv6="IPv6"})(f||(f={}))});var Ac="AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE",Jc="ec2_metadata_service_endpoint_mode",s;var g=O(()=>{t();s={environmentVariableSelector:(c)=>c[Ac],configFileSelector:(c)=>c[Jc],default:f.IPv4}});var U,l,F=async()=>l.parseUrl(await vc()||await zc()),vc=async()=>U.loadConfig(n)(),zc=async()=>{let c=await U.loadConfig(s)();switch(c){case f.IPv4:return J.IPv4;case f.IPv6:return J.IPv6;default:throw Error(`Unsupported endpoint mode: ${c}. Select from ${Object.values(f)}`)}};var P=O(()=>{B();o();t();g();U=u(r(),1),l=u(mc(),1)});var V=(c,I)=>{let x=300+Math.floor(Math.random()*300),N=new Date(Date.now()+x*1000);I.warn(`Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(N)}.
3
3
  For more information, please visit: https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html`);let T=c.originalExpiration??c.expiration;return{...c,...T?{originalExpiration:T}:{},expiration:N}};var d=()=>{};var e=(c,I={})=>{let x=I?.logger||console,N;return async()=>{let T;try{if(T=await c(),T.expiration&&T.expiration.getTime()<Date.now())T=V(T,x)}catch(y){if(N)x.warn("Credential renew failed: ",y),T=V(N,x);else throw y}return N=T,T}};var i=O(()=>{d()});var Nc,k,Tc="/latest/meta-data/iam/security-credentials/",Kc="/latest/api/token",R="AWS_EC2_METADATA_V1_DISABLED",cc="ec2_metadata_v1_disabled",Ic="x-aws-ec2-metadata-token",YI=(c={})=>e(_c(c),{logger:c.logger}),_c=(c={})=>{let I=!1,{logger:x,profile:N}=c,{timeout:T,maxRetries:y}=Q(c),$=async(w,j)=>{if(I||j.headers?.[Ic]==null){let h=!1,Y=!1,wc=await Nc.loadConfig({environmentVariableSelector:(S)=>{let A=S[R];if(Y=!!A&&A!=="false",A===void 0)throw new k.CredentialsProviderError(`${R} not set in env, checking config file next.`,{logger:c.logger});return Y},configFileSelector:(S)=>{let A=S[cc];return h=!!A&&A!=="false",h},default:!1},{profile:N})();if(c.ec2MetadataV1Disabled||wc){let S=[];if(c.ec2MetadataV1Disabled)S.push("credential provider initialization (runtime option ec2MetadataV1Disabled)");if(h)S.push(`config file profile (${cc})`);if(Y)S.push(`process environment variable (${R})`);throw new Z(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${S.join(", ")}].`)}}let yc=(await v(async()=>{let h;try{h=await Gc(j)}catch(Y){if(Y.statusCode===401)I=!1;throw Y}return h},w)).trim();return v(async()=>{let h;try{h=await Lc(yc,j,c)}catch(Y){if(Y.statusCode===401)I=!1;throw Y}return h},w)};return async()=>{let w=await F();if(I)return x?.debug("AWS SDK Instance Metadata","using v1 fallback (no token fetch)"),$(y,{...w,timeout:T});else{let j;try{j=(await Dc({...w,timeout:T})).toString()}catch(m){if(m?.statusCode===400)throw Object.assign(m,{message:"EC2 Metadata token request returned error"});else if(m.message==="TimeoutError"||[403,404,405].includes(m.statusCode))I=!0;return x?.debug("AWS SDK Instance Metadata","using v1 fallback (initial)"),$(y,{...w,timeout:T})}return $(y,{...w,headers:{[Ic]:j},timeout:T})}}},Dc=async(c)=>E({...c,path:Kc,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"21600"}}),Gc=async(c)=>(await E({...c,path:Tc})).toString(),Lc=async(c,I,x)=>{let N=JSON.parse((await E({...I,path:Tc+c})).toString());if(!G(N))throw new k.CredentialsProviderError("Invalid response received from instance metadata service.",{logger:x.logger});return L(N)};var xc=O(()=>{a();D();W();X();b();P();i();Nc=u(r(),1),k=u(_(),1)});var Oc=()=>{};var Qc=O(()=>{D();P();B();p();xc();X();Oc()});Qc();export{Q as providerConfigFromInit,E as httpRequest,F as getInstanceMetadataEndpoint,YI as fromInstanceMetadata,kc as fromContainerMetadata,J as Endpoint,q as ENV_CMDS_RELATIVE_URI,H as ENV_CMDS_FULL_URI,M as ENV_CMDS_AUTH_TOKEN,Hc as DEFAULT_TIMEOUT,qc as DEFAULT_MAX_RETRIES};
4
4
 
5
- //# debugId=DBFD3F24A7910AC364756E2164756E21
5
+ //# debugId=D22911391055948F64756E2164756E21
@@ -19,6 +19,6 @@
19
19
  "export * from \"./fromContainerMetadata\";\nexport * from \"./fromInstanceMetadata\";\nexport * from \"./remoteProvider/RemoteProviderInit\";\nexport * from \"./types\";\nexport { httpRequest } from \"./remoteProvider/httpRequest\";\nexport { getInstanceMetadataEndpoint } from \"./utils/getInstanceMetadataEndpoint\";\nexport { Endpoint } from \"./config/Endpoint\";\n"
20
20
  ],
21
21
  "mappings": ";iQACA,WAAS,UACT,YAAS,QACF,GAAS,CAAW,CAAC,EAAS,CACjC,OAAO,IAAI,QAAQ,CAAC,EAAS,IAA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