@geekmidas/cli 10.0.0-alpha.174 → 10.0.0-alpha.176

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 (215) hide show
  1. package/dist/{EndpointGenerator-CSKhAD6W.mjs → EndpointGenerator-DMq6ameY.mjs} +6 -2
  2. package/dist/EndpointGenerator-DMq6ameY.mjs.map +1 -0
  3. package/dist/{EndpointGenerator-C1h_wExz.cjs → EndpointGenerator-yx7_SoXT.cjs} +6 -2
  4. package/dist/EndpointGenerator-yx7_SoXT.cjs.map +1 -0
  5. package/dist/{GoDaddyProvider-gn-UeZl_.cjs → GoDaddyProvider-CLRtSbuA.cjs} +2 -2
  6. package/dist/{GoDaddyProvider-gn-UeZl_.cjs.map → GoDaddyProvider-CLRtSbuA.cjs.map} +1 -1
  7. package/dist/{GoDaddyProvider-BxQYQT7E.mjs → GoDaddyProvider-DuqG_Wcy.mjs} +2 -2
  8. package/dist/{GoDaddyProvider-BxQYQT7E.mjs.map → GoDaddyProvider-DuqG_Wcy.mjs.map} +1 -1
  9. package/dist/{HostingerProvider-znlxfl_p.cjs → HostingerProvider-Cbqb6bQN.cjs} +2 -2
  10. package/dist/{HostingerProvider-znlxfl_p.cjs.map → HostingerProvider-Cbqb6bQN.cjs.map} +1 -1
  11. package/dist/{HostingerProvider-B-FP4-z6.mjs → HostingerProvider-CiA6uPeg.mjs} +2 -2
  12. package/dist/{HostingerProvider-B-FP4-z6.mjs.map → HostingerProvider-CiA6uPeg.mjs.map} +1 -1
  13. package/dist/{LegacyStateStore-Bds2IJbE.mjs → LegacyStateStore-BuTTsqfo.mjs} +2 -2
  14. package/dist/{LegacyStateStore-Bds2IJbE.mjs.map → LegacyStateStore-BuTTsqfo.mjs.map} +1 -1
  15. package/dist/{LegacyStateStore-bS6W95Cq.cjs → LegacyStateStore-BwNm_jmw.cjs} +2 -2
  16. package/dist/{LegacyStateStore-bS6W95Cq.cjs.map → LegacyStateStore-BwNm_jmw.cjs.map} +1 -1
  17. package/dist/{LocalStateStore-Zvirfsr4.mjs → LocalStateStore-DYoAtXrf.mjs} +2 -2
  18. package/dist/{LocalStateStore-Zvirfsr4.mjs.map → LocalStateStore-DYoAtXrf.mjs.map} +1 -1
  19. package/dist/{LocalStateStore-DN0_SCii.cjs → LocalStateStore-aEaoJuaR.cjs} +2 -2
  20. package/dist/{LocalStateStore-DN0_SCii.cjs.map → LocalStateStore-aEaoJuaR.cjs.map} +1 -1
  21. package/dist/{OpenApiTsGenerator-5xPn-p65.mjs → OpenApiTsGenerator-C_JqxkWt.mjs} +2 -2
  22. package/dist/{OpenApiTsGenerator-5xPn-p65.mjs.map → OpenApiTsGenerator-C_JqxkWt.mjs.map} +1 -1
  23. package/dist/{OpenApiTsGenerator-CzrLGzC0.cjs → OpenApiTsGenerator-gM70-7qw.cjs} +2 -2
  24. package/dist/{OpenApiTsGenerator-CzrLGzC0.cjs.map → OpenApiTsGenerator-gM70-7qw.cjs.map} +1 -1
  25. package/dist/{S3StateStore-CxNPJKqU.mjs → S3StateStore-BC8iBPAY.mjs} +4 -4
  26. package/dist/{S3StateStore-CxNPJKqU.mjs.map → S3StateStore-BC8iBPAY.mjs.map} +1 -1
  27. package/dist/{S3StateStore-Cs_ONSe7.cjs → S3StateStore-D_V_QOU-.cjs} +4 -4
  28. package/dist/{S3StateStore-Cs_ONSe7.cjs.map → S3StateStore-D_V_QOU-.cjs.map} +1 -1
  29. package/dist/{SSMStateStore-CzF_ghlT.cjs → SSMStateStore-DKxVa6_D.cjs} +2 -2
  30. package/dist/{SSMStateStore-CzF_ghlT.cjs.map → SSMStateStore-DKxVa6_D.cjs.map} +1 -1
  31. package/dist/{SSMStateStore-CK52ONQn.mjs → SSMStateStore-vpbJWC-B.mjs} +2 -2
  32. package/dist/{SSMStateStore-CK52ONQn.mjs.map → SSMStateStore-vpbJWC-B.mjs.map} +1 -1
  33. package/dist/{SubscriberGenerator-DMi4siph.cjs → SubscriberGenerator-DXh1Touk.cjs} +7 -3
  34. package/dist/SubscriberGenerator-DXh1Touk.cjs.map +1 -0
  35. package/dist/{SubscriberGenerator-CfZWX0lT.mjs → SubscriberGenerator-NxcLNeDJ.mjs} +7 -3
  36. package/dist/SubscriberGenerator-NxcLNeDJ.mjs.map +1 -0
  37. package/dist/{add-DD5bYU31.cjs → add-D96Ox7kG.cjs} +4 -4
  38. package/dist/{add-DD5bYU31.cjs.map → add-D96Ox7kG.cjs.map} +1 -1
  39. package/dist/{add-D570rDKN.mjs → add-DBmlnNKr.mjs} +4 -4
  40. package/dist/{add-D570rDKN.mjs.map → add-DBmlnNKr.mjs.map} +1 -1
  41. package/dist/{apps-CIKiSUxH.cjs → apps-FB2XppkH.cjs} +5 -5
  42. package/dist/{apps-CIKiSUxH.cjs.map → apps-FB2XppkH.cjs.map} +1 -1
  43. package/dist/{apps-iHK70h_F.mjs → apps-iMCuJRmp.mjs} +5 -5
  44. package/dist/{apps-iHK70h_F.mjs.map → apps-iMCuJRmp.mjs.map} +1 -1
  45. package/dist/{bundler-Cdhf7lv3.mjs → bundler-BkdPQxcw.mjs} +6 -6
  46. package/dist/{bundler-Cdhf7lv3.mjs.map → bundler-BkdPQxcw.mjs.map} +1 -1
  47. package/dist/{bundler-CMieQ_0t.cjs → bundler-D2YOzGbK.cjs} +6 -6
  48. package/dist/{bundler-CMieQ_0t.cjs.map → bundler-D2YOzGbK.cjs.map} +1 -1
  49. package/dist/{cli-DHnkkrXz.cjs → cli-4dCD3ByQ.cjs} +4 -4
  50. package/dist/{cli-DHnkkrXz.cjs.map → cli-4dCD3ByQ.cjs.map} +1 -1
  51. package/dist/{cli-CcWMO_-0.mjs → cli-D7aYkTrO.mjs} +4 -4
  52. package/dist/{cli-CcWMO_-0.mjs.map → cli-D7aYkTrO.mjs.map} +1 -1
  53. package/dist/{compose-D8cd13Eo.cjs → compose-BlEELe3Q.cjs} +9 -9
  54. package/dist/{compose-D8cd13Eo.cjs.map → compose-BlEELe3Q.cjs.map} +1 -1
  55. package/dist/{compose-SAxadQy7.cjs → compose-CfsQ4khN.cjs} +223 -18
  56. package/dist/compose-CfsQ4khN.cjs.map +1 -0
  57. package/dist/{compose-DsFvWwAu.mjs → compose-DKp1s6XP.mjs} +5 -5
  58. package/dist/{compose-DsFvWwAu.mjs.map → compose-DKp1s6XP.mjs.map} +1 -1
  59. package/dist/{compose-CFCSlSXx.mjs → compose-hcFa0rWb.mjs} +209 -16
  60. package/dist/compose-hcFa0rWb.mjs.map +1 -0
  61. package/dist/{databases-CuTL1e7s.cjs → databases-BOuB-zg4.cjs} +2 -2
  62. package/dist/{databases-CuTL1e7s.cjs.map → databases-BOuB-zg4.cjs.map} +1 -1
  63. package/dist/{databases-zN-gEox0.mjs → databases-SFnPaOGM.mjs} +2 -2
  64. package/dist/{databases-zN-gEox0.mjs.map → databases-SFnPaOGM.mjs.map} +1 -1
  65. package/dist/deploy/public.cjs +10 -10
  66. package/dist/deploy/public.d.cts.map +1 -1
  67. package/dist/deploy/public.d.mts.map +1 -1
  68. package/dist/deploy/public.mjs +10 -10
  69. package/dist/{deploy-DnkGdwUd.cjs → deploy-B-Ky0iUC.cjs} +17 -16
  70. package/dist/{deploy-DnkGdwUd.cjs.map → deploy-B-Ky0iUC.cjs.map} +1 -1
  71. package/dist/{deploy-CyrHJ5tR.mjs → deploy-gRkLgV35.mjs} +17 -16
  72. package/dist/{deploy-CyrHJ5tR.mjs.map → deploy-gRkLgV35.mjs.map} +1 -1
  73. package/dist/{destroy-C2VQEDji.mjs → destroy-2f3L-pMt.mjs} +7 -7
  74. package/dist/{destroy-C2VQEDji.mjs.map → destroy-2f3L-pMt.mjs.map} +1 -1
  75. package/dist/{destroy-Qb0MuIV4.cjs → destroy-CiHXpKPS.cjs} +7 -7
  76. package/dist/{destroy-Qb0MuIV4.cjs.map → destroy-CiHXpKPS.cjs.map} +1 -1
  77. package/dist/{dns-BMtL2ytM.mjs → dns-CjzC-jTr.mjs} +22 -8
  78. package/dist/dns-CjzC-jTr.mjs.map +1 -0
  79. package/dist/{dns-DSzsbU2g.cjs → dns-DsOsv1gk.cjs} +30 -10
  80. package/dist/dns-DsOsv1gk.cjs.map +1 -0
  81. package/dist/{docker-aJbcdGKT.cjs → docker-ALmOF9Ye.cjs} +79 -10
  82. package/dist/docker-ALmOF9Ye.cjs.map +1 -0
  83. package/dist/{docker-D89imkq2.mjs → docker-Bu083Pc8.mjs} +74 -11
  84. package/dist/docker-Bu083Pc8.mjs.map +1 -0
  85. package/dist/{dokploy-QAThjPQL.mjs → dokploy--YjmpGf4.mjs} +2 -2
  86. package/dist/{dokploy-QAThjPQL.mjs.map → dokploy--YjmpGf4.mjs.map} +1 -1
  87. package/dist/{dokploy-DvG19W0p.cjs → dokploy-Cg2NOSax.cjs} +2 -2
  88. package/dist/{dokploy-DvG19W0p.cjs.map → dokploy-Cg2NOSax.cjs.map} +1 -1
  89. package/dist/{drivers-wcDnzf7l.mjs → drivers-BQRb3KsL.mjs} +85 -4
  90. package/dist/drivers-BQRb3KsL.mjs.map +1 -0
  91. package/dist/{drivers-BhdC9Efj.cjs → drivers-DP7__dJX.cjs} +134 -5
  92. package/dist/drivers-DP7__dJX.cjs.map +1 -0
  93. package/dist/{eas-DvKir935.cjs → eas-CUDPiJmf.cjs} +2 -2
  94. package/dist/{eas-DvKir935.cjs.map → eas-CUDPiJmf.cjs.map} +1 -1
  95. package/dist/{eas-VxFCgjQa.mjs → eas-CtE3eftL.mjs} +2 -2
  96. package/dist/{eas-VxFCgjQa.mjs.map → eas-CtE3eftL.mjs.map} +1 -1
  97. package/dist/{encryption-D88IRxkV.cjs → encryption-B72rAliE.cjs} +2 -2
  98. package/dist/{encryption-D88IRxkV.cjs.map → encryption-B72rAliE.cjs.map} +1 -1
  99. package/dist/{encryption-_GRjwxGO.mjs → encryption-BNqwJ2Mr.mjs} +2 -2
  100. package/dist/{encryption-_GRjwxGO.mjs.map → encryption-BNqwJ2Mr.mjs.map} +1 -1
  101. package/dist/{engine-7oDEgerp.cjs → engine-BfKsVd1h.cjs} +11 -10
  102. package/dist/engine-BfKsVd1h.cjs.map +1 -0
  103. package/dist/{engine-CQfdAI92.mjs → engine-D5eAK0_u.mjs} +11 -10
  104. package/dist/engine-D5eAK0_u.mjs.map +1 -0
  105. package/dist/{github-BE-0zZ0H.mjs → github-BQJEjYTv.mjs} +19 -10
  106. package/dist/github-BQJEjYTv.mjs.map +1 -0
  107. package/dist/{github-CaUfjXXt.cjs → github-BpAQd9XJ.cjs} +19 -10
  108. package/dist/github-BpAQd9XJ.cjs.map +1 -0
  109. package/dist/{googlePlay-FCJulaVY.cjs → googlePlay-CGoKjrGj.cjs} +4 -4
  110. package/dist/{googlePlay-FCJulaVY.cjs.map → googlePlay-CGoKjrGj.cjs.map} +1 -1
  111. package/dist/{googlePlay-DrBrk6dZ.mjs → googlePlay-CMMDk65f.mjs} +4 -4
  112. package/dist/{googlePlay-DrBrk6dZ.mjs.map → googlePlay-CMMDk65f.mjs.map} +1 -1
  113. package/dist/index.cjs +186 -90
  114. package/dist/index.cjs.map +1 -1
  115. package/dist/index.mjs +186 -90
  116. package/dist/index.mjs.map +1 -1
  117. package/dist/{local-BclGW_Zo.cjs → local-BkiJKXwa.cjs} +2 -2
  118. package/dist/{local-BclGW_Zo.cjs.map → local-BkiJKXwa.cjs.map} +1 -1
  119. package/dist/{local-DbxB0Fg4.mjs → local-DoENgulS.mjs} +2 -2
  120. package/dist/{local-DbxB0Fg4.mjs.map → local-DoENgulS.mjs.map} +1 -1
  121. package/dist/{migrate-lidIEoZm.mjs → migrate-BLJIigAS.mjs} +5 -5
  122. package/dist/{migrate-lidIEoZm.mjs.map → migrate-BLJIigAS.mjs.map} +1 -1
  123. package/dist/{migrate-C2Kjfwui.mjs → migrate-BODEFlT7.mjs} +2 -2
  124. package/dist/{migrate-C2Kjfwui.mjs.map → migrate-BODEFlT7.mjs.map} +1 -1
  125. package/dist/{migrate-z_MuES4x.cjs → migrate-D-0i_3u-.cjs} +5 -5
  126. package/dist/{migrate-z_MuES4x.cjs.map → migrate-D-0i_3u-.cjs.map} +1 -1
  127. package/dist/{migrate-D2mp7qyM.cjs → migrate-DMpbu7Td.cjs} +2 -2
  128. package/dist/{migrate-D2mp7qyM.cjs.map → migrate-DMpbu7Td.cjs.map} +1 -1
  129. package/dist/{notes-Cs0rVvlG.cjs → notes-CsPeouTH.cjs} +2 -2
  130. package/dist/{notes-Cs0rVvlG.cjs.map → notes-CsPeouTH.cjs.map} +1 -1
  131. package/dist/{notes-Dw9BWRJP.mjs → notes-DcRTv0Pb.mjs} +2 -2
  132. package/dist/{notes-Dw9BWRJP.mjs.map → notes-DcRTv0Pb.mjs.map} +1 -1
  133. package/dist/openapi.cjs +2 -2
  134. package/dist/openapi.mjs +2 -2
  135. package/dist/{projectBucket-DHuBZDPJ.mjs → projectBucket-CZ5XnmoT.mjs} +2 -2
  136. package/dist/{projectBucket-DHuBZDPJ.mjs.map → projectBucket-CZ5XnmoT.mjs.map} +1 -1
  137. package/dist/{projectBucket-BvcErpo0.cjs → projectBucket-Dl2KUhdO.cjs} +2 -2
  138. package/dist/{projectBucket-BvcErpo0.cjs.map → projectBucket-Dl2KUhdO.cjs.map} +1 -1
  139. package/dist/{publish-yslBcYWN.mjs → publish-ClymwMkS.mjs} +2 -2
  140. package/dist/{publish-yslBcYWN.mjs.map → publish-ClymwMkS.mjs.map} +1 -1
  141. package/dist/{publish-DzMQWBW8.cjs → publish-D8CS0q_Q.cjs} +2 -2
  142. package/dist/{publish-DzMQWBW8.cjs.map → publish-D8CS0q_Q.cjs.map} +1 -1
  143. package/dist/{ready-DcD0SCnV.cjs → ready-Bgj2cf4j.cjs} +5 -5
  144. package/dist/{ready-DcD0SCnV.cjs.map → ready-Bgj2cf4j.cjs.map} +1 -1
  145. package/dist/{ready-COJHr1Yi.mjs → ready-D1gctv-5.mjs} +5 -5
  146. package/dist/{ready-COJHr1Yi.mjs.map → ready-D1gctv-5.mjs.map} +1 -1
  147. package/dist/{resolve-Dfind5fY.mjs → resolve-CoaQmANg.mjs} +4 -4
  148. package/dist/{resolve-Dfind5fY.mjs.map → resolve-CoaQmANg.mjs.map} +1 -1
  149. package/dist/{resolve-CQvEtM5c.cjs → resolve-Dn1n69kp.cjs} +4 -4
  150. package/dist/{resolve-CQvEtM5c.cjs.map → resolve-Dn1n69kp.cjs.map} +1 -1
  151. package/dist/{rollback-DUbm19zl.cjs → rollback-BNP1XKtz.cjs} +5 -5
  152. package/dist/{rollback-DUbm19zl.cjs.map → rollback-BNP1XKtz.cjs.map} +1 -1
  153. package/dist/{rollback-j8X0RdpU.mjs → rollback-o85w39I-.mjs} +5 -5
  154. package/dist/{rollback-j8X0RdpU.mjs.map → rollback-o85w39I-.mjs.map} +1 -1
  155. package/dist/{s3-Ba3WIaGU.cjs → s3-BF1qsk-S.cjs} +2 -2
  156. package/dist/{s3-Ba3WIaGU.cjs.map → s3-BF1qsk-S.cjs.map} +1 -1
  157. package/dist/{s3-Bs1qUnxt.mjs → s3-XW71srQO.mjs} +2 -2
  158. package/dist/{s3-Bs1qUnxt.mjs.map → s3-XW71srQO.mjs.map} +1 -1
  159. package/dist/sandbox/migrate-worker.cjs +1 -1
  160. package/dist/sandbox/migrate-worker.mjs +1 -1
  161. package/dist/{serverSetup-Drh_mhxR.cjs → serverSetup-Bi6BAQvQ.cjs} +5 -5
  162. package/dist/{serverSetup-Drh_mhxR.cjs.map → serverSetup-Bi6BAQvQ.cjs.map} +1 -1
  163. package/dist/{serverSetup-DUrSo7HL.mjs → serverSetup-ClkJ0dhD.mjs} +5 -5
  164. package/dist/{serverSetup-DUrSo7HL.mjs.map → serverSetup-ClkJ0dhD.mjs.map} +1 -1
  165. package/dist/{sniffer-zsLNtFK0.cjs → sniffer-5BEd0W-2.cjs} +6 -6
  166. package/dist/{sniffer-zsLNtFK0.cjs.map → sniffer-5BEd0W-2.cjs.map} +1 -1
  167. package/dist/{sniffer-DgjWtfBW.mjs → sniffer-CwA19f8u.mjs} +6 -6
  168. package/dist/{sniffer-DgjWtfBW.mjs.map → sniffer-CwA19f8u.mjs.map} +1 -1
  169. package/dist/{snsSubscriptions-CGO6EO7H.cjs → snsSubscriptions-D_oK-FKK.cjs} +3 -3
  170. package/dist/{snsSubscriptions-CGO6EO7H.cjs.map → snsSubscriptions-D_oK-FKK.cjs.map} +1 -1
  171. package/dist/{snsSubscriptions-BLfWAnzg.mjs → snsSubscriptions-DlNwAo6l.mjs} +3 -3
  172. package/dist/{snsSubscriptions-BLfWAnzg.mjs.map → snsSubscriptions-DlNwAo6l.mjs.map} +1 -1
  173. package/dist/{sst-Bih36ADr.cjs → sst-BDaYh-cJ.cjs} +4 -4
  174. package/dist/{sst-Bih36ADr.cjs.map → sst-BDaYh-cJ.cjs.map} +1 -1
  175. package/dist/{sst-B2h4rE6j.mjs → sst-DmjCAYmq.mjs} +4 -4
  176. package/dist/{sst-B2h4rE6j.mjs.map → sst-DmjCAYmq.mjs.map} +1 -1
  177. package/dist/{stack-DI4qbrtn.mjs → stack-HULMMZlf.mjs} +23 -163
  178. package/dist/stack-HULMMZlf.mjs.map +1 -0
  179. package/dist/{stack-D0CC6_b-.cjs → stack-UtZKqaoh.cjs} +23 -193
  180. package/dist/stack-UtZKqaoh.cjs.map +1 -0
  181. package/dist/{stage--Z6-pM9E.cjs → stage-2YFzi0j2.cjs} +5 -5
  182. package/dist/{stage--Z6-pM9E.cjs.map → stage-2YFzi0j2.cjs.map} +1 -1
  183. package/dist/{stage-C-qe-Lye.mjs → stage-D_2SKwyr.mjs} +5 -5
  184. package/dist/{stage-C-qe-Lye.mjs.map → stage-D_2SKwyr.mjs.map} +1 -1
  185. package/dist/target/public.cjs +1 -1
  186. package/dist/target/public.mjs +1 -1
  187. package/dist/{terminal-CnhNSW3v.cjs → terminal-DywyNR4M.cjs} +2 -2
  188. package/dist/{terminal-CnhNSW3v.cjs.map → terminal-DywyNR4M.cjs.map} +1 -1
  189. package/dist/{terminal-DtO0Eh3g.mjs → terminal-J3kNRlry.mjs} +2 -2
  190. package/dist/{terminal-DtO0Eh3g.mjs.map → terminal-J3kNRlry.mjs.map} +1 -1
  191. package/dist/vitest.cjs +1 -1
  192. package/dist/vitest.mjs +1 -1
  193. package/package.json +15 -15
  194. package/dist/EndpointGenerator-C1h_wExz.cjs.map +0 -1
  195. package/dist/EndpointGenerator-CSKhAD6W.mjs.map +0 -1
  196. package/dist/SubscriberGenerator-CfZWX0lT.mjs.map +0 -1
  197. package/dist/SubscriberGenerator-DMi4siph.cjs.map +0 -1
  198. package/dist/compose-CFCSlSXx.mjs.map +0 -1
  199. package/dist/compose-SAxadQy7.cjs.map +0 -1
  200. package/dist/dns-BMtL2ytM.mjs.map +0 -1
  201. package/dist/dns-DSzsbU2g.cjs.map +0 -1
  202. package/dist/docker-D89imkq2.mjs.map +0 -1
  203. package/dist/docker-aJbcdGKT.cjs.map +0 -1
  204. package/dist/drivers-BhdC9Efj.cjs.map +0 -1
  205. package/dist/drivers-wcDnzf7l.mjs.map +0 -1
  206. package/dist/engine-7oDEgerp.cjs.map +0 -1
  207. package/dist/engine-CQfdAI92.mjs.map +0 -1
  208. package/dist/github-BE-0zZ0H.mjs.map +0 -1
  209. package/dist/github-CaUfjXXt.cjs.map +0 -1
  210. package/dist/stack-D0CC6_b-.cjs.map +0 -1
  211. package/dist/stack-DI4qbrtn.mjs.map +0 -1
  212. package/dist/types-Bl_CwZC9.cjs +0 -90
  213. package/dist/types-Bl_CwZC9.cjs.map +0 -1
  214. package/dist/types-Y1NfWlyG.mjs +0 -61
  215. package/dist/types-Y1NfWlyG.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"EndpointGenerator-CSKhAD6W.mjs","names":[],"sources":["../src/generators/clientTelemetry.ts","../src/generators/telemetry.ts","../src/generators/EndpointGenerator.ts"],"sourcesContent":["/**\n * Whether a generated client propagates trace context by default.\n *\n * `false` (the default) prints a client that sends no trace headers unless\n * its caller passes `telemetry`. Anything else prints that default into\n * `createApi`: `true`, or `{ sampleRate }` — the stage's rate, for the page\n * views no OpenTelemetry SDK is tracing. A caller's own `telemetry` option\n * still wins.\n */\n\nimport { GkmError } from '../errors';\nexport type ClientTelemetryDefault = boolean | { sampleRate: number };\n\n/** A `sampleRate` outside 0–1, which no sampler can honour. */\nexport class InvalidClientTelemetrySampleRate extends GkmError {\n\tconstructor(readonly sampleRate: number) {\n\t\tsuper(\n\t\t\t`The client's telemetry sample rate must be a number from 0 to 1, got ${sampleRate}. Pass the stage's rate, such as 0.1, or leave it out for 1.`,\n\t\t);\n\t\tthis.name = 'InvalidClientTelemetrySampleRate';\n\t}\n}\n\n/** The `telemetry` default as the generated module prints it. */\nexport function printTelemetryDefault(\n\ttelemetry: ClientTelemetryDefault,\n): string {\n\tif (typeof telemetry === 'boolean') return String(telemetry);\n\tconst { sampleRate } = telemetry;\n\tif (!Number.isFinite(sampleRate) || sampleRate < 0 || sampleRate > 1) {\n\t\tthrow new InvalidClientTelemetrySampleRate(sampleRate);\n\t}\n\treturn `{ sampleRate: ${sampleRate} }`;\n}\n\n/**\n * `--telemetry [rate]` for a client default, as `gkm openapi` takes it — and\n * as a site's Dockerfile passes it to the `gkm openapi --app` it runs.\n */\nexport function telemetryArgs(telemetry?: ClientTelemetryDefault): string[] {\n\tif (!telemetry) return [];\n\tif (telemetry === true) return ['--telemetry'];\n\treturn ['--telemetry', String(telemetry.sampleRate)];\n}\n\n/** What `--telemetry [rate]` parsed to: on, at a rate when one was given. */\nexport function parseTelemetryFlag(\n\tvalue: boolean | string | undefined,\n): ClientTelemetryDefault | undefined {\n\tif (value === undefined || value === false) return undefined;\n\tif (value === true) return true;\n\treturn { sampleRate: Number(value) };\n}\n","import { existsSync, realpathSync } from 'node:fs';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative, resolve } from 'node:path';\nimport type { TelemetryDeclaration } from '@geekmidas/manifest';\nimport { GkmError } from '../errors';\n\n/**\n * One route's own telemetry — an endpoint's `.telemetry({ ignore, attributes })`.\n */\nexport interface TelemetryRoute {\n\tmethod: string;\n\t/** The route as the surface serves it — `/users/:id`. */\n\tpath: string;\n\tignore?: boolean;\n\tattributes?: Readonly<Record<string, string>>;\n}\n\n/** Each endpoint's own `.telemetry({ ignore, attributes })`, as routes. */\nexport function routeTelemetry(\n\tendpoints: readonly {\n\t\tmethod: string;\n\t\troute: string;\n\t\ttelemetry?: Omit<TelemetryRoute, 'method' | 'path'>;\n\t}[],\n): TelemetryRoute[] {\n\treturn endpoints.flatMap((endpoint) =>\n\t\tendpoint.telemetry\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tmethod: endpoint.method,\n\t\t\t\t\t\tpath: endpoint.route,\n\t\t\t\t\t\t...endpoint.telemetry,\n\t\t\t\t\t},\n\t\t\t\t]\n\t\t\t: [],\n\t);\n}\n\n/**\n * What an entry starts OpenTelemetry with, decided at build time from the\n * process's edge to a `Telemetry` node.\n *\n * Only built for a process with that edge — every other process gets the\n * stub, which loads nothing — and only once the packages it needs resolve:\n * a process that uses the node and cannot load them fails the build with\n * {@link TelemetryPackagesMissing}.\n */\nexport interface TelemetryContext {\n\t/** `service.name` — the surface or worker; `OTEL_SERVICE_NAME` overrides it. */\n\tserviceName: string;\n\t/** `service.namespace` — the workspace the app is part of. */\n\tserviceNamespace?: string;\n\t/** The node's `ignorePaths`. */\n\tignorePaths: readonly string[];\n\t/** The node's `attributes`, on every span and log record. */\n\tattributes: Readonly<Record<string, string>>;\n\t/** Each route that says something of its own. */\n\troutes: readonly TelemetryRoute[];\n}\n\n/**\n * Every package `@geekmidas/telescope/instrumentation` loads at runtime.\n *\n * All of them, rather than one as a proxy: the production bundle follows each\n * import, and a single missing one fails the build rather than the telemetry.\n */\nexport const TELEMETRY_PACKAGES = [\n\t'@opentelemetry/api',\n\t'@opentelemetry/auto-instrumentations-node',\n\t'@opentelemetry/exporter-logs-otlp-http',\n\t'@opentelemetry/exporter-metrics-otlp-http',\n\t'@opentelemetry/exporter-trace-otlp-http',\n\t'@opentelemetry/instrumentation-pino',\n\t'@opentelemetry/resources',\n\t'@opentelemetry/sdk-logs',\n\t'@opentelemetry/sdk-metrics',\n\t'@opentelemetry/sdk-node',\n\t'@opentelemetry/sdk-trace-base',\n\t'@opentelemetry/sdk-trace-node',\n\t'@opentelemetry/semantic-conventions',\n] as const;\n\n/**\n * The directory of `name` as `node_modules` lookup finds it from `fromDir`,\n * symlinks resolved — or undefined.\n *\n * The directory walk alone, not `require.resolve`: that also searches\n * `NODE_PATH`, which a package manager's bin shim sets to its own store, so a\n * `gkm build` run through one would find packages the app never installed —\n * and the bundler, which does not look there, would then fail on them.\n */\nfunction packageDir(fromDir: string, name: string): string | undefined {\n\tfor (let dir = resolve(fromDir); ; dir = dirname(dir)) {\n\t\tconst candidate = join(dir, 'node_modules', name);\n\t\tif (existsSync(join(candidate, 'package.json'))) {\n\t\t\treturn realpathSync(candidate);\n\t\t}\n\t\tif (dirname(dir) === dir) return undefined;\n\t}\n}\n\n/**\n * The telemetry packages that do not resolve the way the bundler will resolve\n * them — telescope from the app, and the OpenTelemetry packages from\n * telescope, where a peer is linked under pnpm, which need not be where the\n * app sees it. Empty when every one does.\n */\nexport function missingTelemetryPackages(appRoot: string): string[] {\n\tconst telescope = packageDir(appRoot, '@geekmidas/telescope');\n\tif (!telescope) return ['@geekmidas/telescope', ...TELEMETRY_PACKAGES];\n\n\treturn TELEMETRY_PACKAGES.filter((pkg) => !packageDir(telescope, pkg));\n}\n\n/**\n * An app uses a `Telemetry` construct and cannot load what it needs to.\n *\n * Failed at build, not at startup: a process that was given telemetry and\n * quietly ran without it is an outage nobody can see into.\n */\nexport class TelemetryPackagesMissing extends GkmError {\n\treadonly command: string;\n\n\tconstructor(\n\t\treadonly app: string,\n\t\treadonly missing: readonly string[],\n\t\t/** The app's directory, relative to where the command is run. */\n\t\treadonly dir: string,\n\t) {\n\t\tconst command = `pnpm --dir ${dir || '.'} add ${missing.join(' ')}`;\n\t\tsuper(\n\t\t\t`'${app}' uses a Telemetry construct, and ${missing.join(', ')} ` +\n\t\t\t\t`${missing.length === 1 ? 'does' : 'do'} not resolve from it — its ` +\n\t\t\t\t'server would start without exporting a span. Add them to the app ' +\n\t\t\t\t`and build again:\\n\\n ${command}\\n`,\n\t\t);\n\t\tthis.name = 'TelemetryPackagesMissing';\n\t\tthis.command = command;\n\t}\n}\n\n/**\n * The telemetry half of a build context: undefined for a process with no\n * edge to a `Telemetry` node, and — for one with an edge — what its entry\n * starts with, once every package it needs resolves.\n */\nexport function telemetryFor(options: {\n\t/** The node the process emits through — see `telemetryOf`. */\n\tnode: TelemetryDeclaration | undefined;\n\tappRoot: string;\n\t/** The app's name, for the error. */\n\tapp: string;\n\t/** Where `pnpm` is run from, for the error's command. */\n\tcwd?: string;\n\tserviceName: string;\n\tworkspaceName?: string;\n\troutes?: readonly TelemetryRoute[];\n}): TelemetryContext | undefined {\n\tconst { node } = options;\n\tif (!node) return undefined;\n\n\tconst missing = missingTelemetryPackages(options.appRoot);\n\tif (missing.length > 0) {\n\t\tthrow new TelemetryPackagesMissing(\n\t\t\toptions.app,\n\t\t\tmissing,\n\t\t\trelative(options.cwd ?? process.cwd(), options.appRoot),\n\t\t);\n\t}\n\n\treturn {\n\t\tserviceName: options.serviceName,\n\t\t...(options.workspaceName && { serviceNamespace: options.workspaceName }),\n\t\tignorePaths: [...(node.ignorePaths ?? [])],\n\t\tattributes: { ...node.attributes },\n\t\troutes: [...(options.routes ?? [])],\n\t};\n}\n\nconst HEADER = `/**\n * Generated by gkm, for the production entry and the \\`gkm dev\\` one alike.\n *\n * Starts OpenTelemetry when OTEL_EXPORTER_OTLP_ENDPOINT names a collector, and\n * does nothing otherwise: without it, the telemetry packages are not loaded.\n * The standard OTEL_* variables (OTEL_TRACES_SAMPLER, OTEL_TRACES_SAMPLER_ARG,\n * OTEL_EXPORTER_OTLP_HEADERS, OTEL_RESOURCE_ATTRIBUTES, OTEL_SERVICE_NAME)\n * configure the rest.\n */\n\nimport type { MiddlewareHandler } from 'hono';\n\nexport interface StartTelemetryOptions {\n /** Requests whose spans would only be noise: health checks, by default. */\n ignorePaths?: string[];\n /**\n * The API's own sites — the origins its CORS allows — read on each request.\n * Their \\`traceparent\\` is continued, as is an internal caller's; anyone\n * else's starts a new trace linked to the one it claimed.\n */\n trustedOrigins?: () => readonly string[];\n}\n`;\n\n/** `/users/:id` as a pattern over a request's path. */\nfunction routePattern(path: string): string {\n\tconst body = path\n\t\t.split('/')\n\t\t.map((segment) => {\n\t\t\tif (segment.startsWith(':')) return '[^/]+';\n\t\t\tif (segment === '*') return '.*';\n\t\t\treturn segment.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\t\t})\n\t\t.join('/');\n\treturn `^${body}/?$`;\n}\n\n/**\n * The entry's `telemetry.ts`: a `startTelemetry()` the server awaits before it\n * imports the app, so the libraries the app loads are instrumented. It returns\n * the Hono middleware that traces each request, or undefined when telemetry is\n * off — the server mounts it ahead of every route.\n *\n * Without a context — a process with no edge to a `Telemetry` node — it is a\n * stub that loads nothing and says nothing: telemetry is not something that\n * process was given.\n *\n * Failing to start telemetry warns (a named `TelemetryUnavailable`, through\n * `process.emitWarning`) and never stops the server: an outage in observability\n * is not a reason to have an outage in the service.\n */\nexport function generateTelemetryModule(\n\ttelemetry: TelemetryContext | undefined,\n): string {\n\tif (!telemetry) {\n\t\treturn `${HEADER}\n// This process has no Telemetry construct, so there is nothing to start.\nexport async function startTelemetry(\n _options: StartTelemetryOptions = {},\n): Promise<MiddlewareHandler | undefined> {\n return undefined;\n}\n`;\n\t}\n\n\tconst options = [\n\t\t`serviceName: ${JSON.stringify(telemetry.serviceName)},`,\n\t\t...(telemetry.serviceNamespace\n\t\t\t? [`serviceNamespace: ${JSON.stringify(telemetry.serviceNamespace)},`]\n\t\t\t: []),\n\t\t// The stage the deploy set, so one service's stages stay apart.\n\t\t'deploymentEnvironment: process.env.STAGE,',\n\t\t...(Object.keys(telemetry.attributes).length\n\t\t\t? [`resourceAttributes: ${JSON.stringify(telemetry.attributes)},`]\n\t\t\t: []),\n\t\t// The exporters read OTEL_EXPORTER_OTLP_* themselves, and the SDK reads\n\t\t// OTEL_TRACES_SAMPLER — so no endpoint and no ratio are printed here.\n\t\t// The server's own shutdown decides when the process exits.\n\t\t'handleSignals: false,',\n\t\t// Neither is left to module-load hooks, which see nothing inside a\n\t\t// bundle: @geekmidas/logger emits each record through the logs API\n\t\t// itself, and the middleware returned below opens each request's span.\n\t\t// Hooked as well where they can be, every record and request would be\n\t\t// sent twice.\n\t\t'instrumentPino: false,',\n\t\t'incomingHttpSpans: false,',\n\t];\n\n\tconst routes = telemetry.routes.map((route) => ({\n\t\tmethod: route.method.toUpperCase(),\n\t\tpattern: routePattern(route.path),\n\t\t...(route.ignore ? { ignore: true } : {}),\n\t\t...(route.attributes && Object.keys(route.attributes).length\n\t\t\t? { attributes: route.attributes }\n\t\t\t: {}),\n\t}));\n\tconst withAttributes = routes.some((route) => 'attributes' in route);\n\n\treturn `${HEADER}\n/** Telemetry was asked for and cannot start. The server runs without it. */\nexport class TelemetryUnavailable extends Error {\n constructor(readonly reason: string, options?: { cause?: unknown }) {\n super(\n \\`OTEL_EXPORTER_OTLP_ENDPOINT is set, but \\${reason} This server exports no traces, metrics or logs until that is fixed.\\`,\n options,\n );\n this.name = 'TelemetryUnavailable';\n }\n}\n\n/** The Telemetry construct's own ignored paths, beside the entry's. */\nconst IGNORE_PATHS: string[] = ${JSON.stringify(telemetry.ignorePaths)};\n\n/** Each route's own .telemetry({ ignore, attributes }). */\nconst ROUTES: {\n method: string;\n pattern: string;\n ignore?: boolean;\n attributes?: Record<string, string>;\n}[] = ${JSON.stringify(routes)};\n\nconst MATCHERS = ROUTES.map((route) => ({ ...route, regex: new RegExp(route.pattern) }));\n\nfunction routeOf(method: string, path: string) {\n return MATCHERS.find(\n (route) => (route.method === method || route.method === 'ALL' || route.method === 'ANY') && route.regex.test(path),\n );\n}\n\nexport async function startTelemetry(\n options: StartTelemetryOptions = {},\n): Promise<MiddlewareHandler | undefined> {\n if (!process.env.OTEL_EXPORTER_OTLP_ENDPOINT) return undefined;\n\n let instrumentation;\n try {\n instrumentation = await import('@geekmidas/telescope/instrumentation');\n } catch (cause) {\n process.emitWarning(\n new TelemetryUnavailable(\n '@geekmidas/telescope/instrumentation or an @opentelemetry package it needs could not be loaded. Install them in the app and rebuild.',\n { cause },\n ),\n );\n return undefined;\n }\n\n instrumentation.setupTelemetry({\n ${options.join('\\n ')}\n });\n\n // Flush what is buffered when the process is told to stop. When nothing\n // else handles the signal, re-raise it once flushed, so the process still\n // stops the way it would have without this listener.\n for (const signal of ['SIGTERM', 'SIGINT'] as const) {\n process.once(signal, () => {\n void instrumentation.flushTelemetry().finally(() => {\n if (process.listenerCount(signal) === 0) process.kill(process.pid, signal);\n });\n });\n }\n\n // A SERVER span per request, opened by the app itself rather than by\n // hooking node:http: \\`GET /users/:id\\`, continuing an incoming traceparent\n // from the API's own sites and internal callers (a new, linked trace from\n // anyone else), with the handler — its logs, fetches and queries — running\n // inside it.\n const spans = instrumentation.honoTelemetryMiddleware({\n ignorePaths: [...(options.ignorePaths ?? []), ...IGNORE_PATHS],\n trustedOrigins: options.trustedOrigins,\n ...(MATCHERS.some((route) => route.ignore)\n ? { shouldSkip: (c) => routeOf(c.req.method, c.req.path)?.ignore === true }\n : {}),\n });\n${\n\twithAttributes\n\t\t? `\n // A route's own attributes, on the span the middleware just opened.\n const { trace } = await import('@opentelemetry/api');\n return (c, next) =>\n spans(c, async () => {\n const attributes = routeOf(c.req.method, c.req.path)?.attributes;\n if (attributes) trace.getActiveSpan()?.setAttributes(attributes);\n await next();\n });\n`\n\t\t: ` return spans;\n`\n}}\n`;\n}\n\n/**\n * What an entry starts telemetry with, before it imports the app — shared by\n * the production server, a self-serving surface's server and the `gkm dev`\n * entry, so the three cannot start it differently. Defines `requestSpans`.\n */\nexport function startTelemetryCode(ignorePaths: readonly string[]): string {\n\treturn `// The API's own sites, known once the app has read its configuration: the\n// origins its CORS allows are the ones whose trace context is continued.\nlet trustedOrigins: readonly string[] = [];\n\n// Before the app is imported, so the libraries it loads are instrumented.\nconst { startTelemetry } = await import('./telemetry.js');\nconst requestSpans = await startTelemetry({\n ignorePaths: ${JSON.stringify(ignorePaths)},\n trustedOrigins: () => trustedOrigins,\n});\n`;\n}\n\n/** Mounts `requestSpans` on `app` ahead of every route. */\nexport function mountRequestSpansCode(app: string): string {\n\treturn `// The span middleware goes on before any route, so every request runs in it.\nif (requestSpans) ${app}.use('*', requestSpans);\n`;\n}\n\n/** Writes the entry's `telemetry.ts` beside it. */\nexport async function writeTelemetryModule(\n\toutputDir: string,\n\ttelemetry: TelemetryContext | undefined,\n): Promise<void> {\n\tawait mkdir(outputDir, { recursive: true });\n\tawait writeFile(\n\t\tjoin(outputDir, 'telemetry.ts'),\n\t\tgenerateTelemetryModule(telemetry),\n\t);\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Endpoint } from '@geekmidas/constructs/endpoints';\nimport type { BuildContext } from '../build/types';\nimport type { RouteInfo } from '../types';\nimport type { StorageDrivers } from './drivers';\nimport {\n\tConstructGenerator,\n\ttype GeneratedConstruct,\n\ttype GeneratorOptions,\n} from './Generator';\nimport {\n\tmountRequestSpansCode,\n\tstartTelemetryCode,\n\twriteTelemetryModule,\n} from './telemetry';\n\n/**\n * How a generated entry gets its logger and environment parser.\n *\n * From the surface it serves, when there is one: the surface holds both as\n * *objects*, and discovery already recorded which module declares it, so the\n * entry imports that module and reads them off it.\n *\n * The alternative — the shape this replaces — was naming both in config as\n * module paths, `envParser: './config/env#envParser'`, and printing an import\n * for each. Two strings per app, checked by nothing, describing files the\n * surface was already holding the contents of.\n *\n * Falls back to the configured paths for an app that declares no surface.\n */\nexport function runtimeFor(\n\tcontext: BuildContext,\n\tfromDir: string,\n\t/**\n\t * The construct that owns the thing being generated.\n\t *\n\t * An endpoint's surface, or the worker that handed out the cron factory.\n\t * Omitted for the app entry itself, which belongs to the primary surface.\n\t */\n\towner?: string,\n): { imports: string; bindings: string } {\n\tconst module = owner\n\t\t? (context.owners?.[owner] ?? context.surface?.module)\n\t\t: context.surface?.module;\n\n\tif (module) {\n\t\tconst specifier = importSpecifier(fromDir, module.specifier);\n\n\t\t// Bound to the same names the rest of the entry already uses, so what\n\t\t// changes is where they come from and nothing else.\n\t\treturn {\n\t\t\timports: `import { ${module.exportName} as __surface } from '${specifier}';`,\n\t\t\tbindings: [\n\t\t\t\t'// What this construct was declared with. Objects, not module paths:',\n\t\t\t\t'// the entry imports the owner, so there is nothing to print.',\n\t\t\t\t'const envParser = __surface.envParser;',\n\t\t\t\t'const logger = __surface.logger;',\n\t\t\t].join('\\n'),\n\t\t};\n\t}\n\n\t// No fallback. Every runnable comes from a factory a `RestApi` or a `Worker`\n\t// handed out, and that construct holds the objects — so there is no longer a\n\t// case where the only thing we know about a logger is a module path somebody\n\t// typed into config.\n\tthrow new Error(\n\t\t`No owner to take a logger and an environment parser from${\n\t\t\towner ? ` for \"${owner}\"` : ''\n\t\t}. Build it from a \\`RestApi\\` or a \\`Worker\\`.`,\n\t);\n}\n\n/** A relative specifier ESM will accept: always prefixed, never bare. */\nfunction importSpecifier(fromDir: string, target: string): string {\n\tconst rel = relative(fromDir, target).replace(/\\.ts$/, '.js');\n\n\treturn rel.startsWith('.') ? rel : `./${rel}`;\n}\n\n/**\n * CORS for a surface, derived rather than hand-written.\n *\n * Who may call a surface is already in the graph — every construct that\n * declared an edge to it — and reaches the process as one comma-separated\n * value. An application that maintained this by hand maintained a list that was\n * wrong in two directions at once: it trusted origins nothing was serving, and\n * it could not name hosts a deploy had not chosen yet.\n *\n * Only the parts a graph cannot answer are configurable, and every one has a\n * default: a surface that says nothing about CORS still gets it.\n */\nexport function corsFor(surface: BuildContext['surface']): {\n\timports: string;\n\tsetup: string;\n} {\n\tif (!surface) return { imports: '', setup: '' };\n\n\tconst cors = surface.cors ?? {};\n\t// `traceparent` and `tracestate` always: a site's client sends them when\n\t// its telemetry is on, and a preflight that refused them would fail every\n\t// request it makes rather than only its tracing. The API decides whether\n\t// to continue the trace (it does only for these same origins), so allowing\n\t// the headers grants nothing on its own.\n\tconst allowHeaders = [\n\t\t...new Set([\n\t\t\t'content-type',\n\t\t\t'authorization',\n\t\t\t'traceparent',\n\t\t\t'tracestate',\n\t\t\t...(cors.allowHeaders ?? []),\n\t\t]),\n\t];\n\n\treturn {\n\t\timports: `import { cors } from 'hono/cors';\nimport { trustsOrigin } from '@geekmidas/constructs/endpoints';`,\n\t\tsetup: `\n // Who may call ${surface.id}, read off the graph rather than listed here.\n {\n const { origins } = envParser\n .create((get) => ({\n origins: get('${surface.trustedOriginsKey}')\n .string()\n .default('')\n .transform((value: string) =>\n value.split(',').map((origin) => origin.trim()).filter(Boolean),\n ),\n }))\n .parse();\n\n // The same origins are the ones whose trace context the request spans\n // continue — the server reads them back from \\`createApp\\`.\n trustedOrigins.push(...origins);\n\n // An exact origin, or any one label in place of a wildcard site's \\`*\\`.\n honoApp.use('*', cors({\n origin: (origin) => (trustsOrigin(origin, origins) ? origin : null),\n allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],\n allowHeaders: ${JSON.stringify(allowHeaders)},${\n\t\t\t\tcors.exposeHeaders\n\t\t\t\t\t? `\\n exposeHeaders: ${JSON.stringify(cors.exposeHeaders)},`\n\t\t\t\t\t: ''\n\t\t\t}\n credentials: ${cors.credentials ?? true},\n maxAge: ${cors.maxAge ?? 86400},\n }));\n }\n`,\n\t};\n}\n\nexport class EndpointGenerator extends ConstructGenerator<\n\tEndpoint<any, any, any, any, any, any, any, any, any, any, any, any>,\n\tRouteInfo[]\n> {\n\tisConstruct(\n\t\tvalue: any,\n\t): value is Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany\n\t> {\n\t\treturn Endpoint.isEndpoint(value);\n\t}\n\n\tasync build(\n\t\tcontext: BuildContext,\n\t\tconstructs: GeneratedConstruct<\n\t\t\tEndpoint<any, any, any, any, any, any, any, any, any, any, any, any>\n\t\t>[],\n\t\toutputDir: string,\n\t\toptions?: GeneratorOptions,\n\t): Promise<RouteInfo[]> {\n\t\tconst target = options?.target ?? 'aws';\n\t\tconst root = options?.root ?? process.cwd();\n\t\tconst enableOpenApi = options?.enableOpenApi || false;\n\t\tconst logger = console;\n\t\tconst routes: RouteInfo[] = [];\n\n\t\tif (constructs.length === 0) {\n\t\t\treturn routes;\n\t\t}\n\n\t\tif (target === 'server') {\n\t\t\t// Generate endpoints.ts and app.ts\n\t\t\tawait this.generateEndpointsFile(outputDir, constructs);\n\t\t\tconst appFile = await this.generateAppFile(outputDir, context);\n\n\t\t\troutes.push({\n\t\t\t\tpath: '*',\n\t\t\t\tmethod: 'ALL',\n\t\t\t\thandler: relative(root, appFile),\n\t\t\t\tauthorizer: 'none',\n\t\t\t});\n\n\t\t\tlogger.log(\n\t\t\t\t`Generated server with ${constructs.length} endpoints${enableOpenApi ? ' (OpenAPI enabled)' : ''}`,\n\t\t\t);\n\n\t\t\treturn routes;\n\t\t}\n\n\t\t// One Lambda per endpoint, behind an HTTP API.\n\t\tconst routesDir = join(outputDir, 'routes');\n\t\tawait mkdir(routesDir, { recursive: true });\n\n\t\tfor (const { key, construct, path } of constructs) {\n\t\t\tconst handlerFile = await this.generateHandlerFile(\n\t\t\t\troutesDir,\n\t\t\t\tpath.relative,\n\t\t\t\tkey,\n\t\t\t\tcontext,\n\t\t\t);\n\n\t\t\tconst routeInfo: RouteInfo = {\n\t\t\t\tpath: construct._path,\n\t\t\t\tmethod: construct.method,\n\t\t\t\thandler: relative(root, handlerFile).replace(/\\.ts$/, '.handler'),\n\t\t\t\ttimeout: construct.timeout,\n\t\t\t\tmemorySize: construct.memorySize,\n\t\t\t\tenvironment: await construct.getEnvironment({\n\t\t\t\t\tmarkOptional: context.markOptional,\n\t\t\t\t}),\n\t\t\t\tdependencies: construct.constructs,\n\t\t\t\tauthorizer: construct.authorizer?.name ?? 'none',\n\t\t\t};\n\n\t\t\troutes.push(routeInfo);\n\t\t\tlogger.log(`Generated handler for ${routeInfo.method} ${routeInfo.path}`);\n\t\t}\n\n\t\treturn routes;\n\t}\n\n\tprivate async generateHandlerFile(\n\t\toutputDir: string,\n\t\tsourceFile: string,\n\t\texportName: string,\n\t\tcontext: BuildContext,\n\t): Promise<string> {\n\t\tconst handlerPath = join(outputDir, `${exportName}.ts`);\n\n\t\tconst relativePath = relative(dirname(handlerPath), sourceFile);\n\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\tawait writeFile(\n\t\t\thandlerPath,\n\t\t\tthis.generateAWSApiGatewayV2Handler(\n\t\t\t\timportPath,\n\t\t\t\texportName,\n\t\t\t\tcontext.storageDrivers,\n\t\t\t),\n\t\t);\n\t\treturn handlerPath;\n\t}\n\n\tprivate async generateEndpointsFile(\n\t\toutputDir: string,\n\t\tendpoints: GeneratedConstruct<\n\t\t\tEndpoint<any, any, any, any, any, any, any, any, any, any, any, any>\n\t\t>[],\n\t): Promise<string> {\n\t\tconst endpointsFileName = 'endpoints.ts';\n\t\tconst endpointsPath = join(outputDir, endpointsFileName);\n\n\t\t// Group imports by file\n\t\tconst importsByFile = new Map<string, string[]>();\n\n\t\tfor (const { path, key } of endpoints) {\n\t\t\tconst relativePath = relative(dirname(endpointsPath), path.relative);\n\t\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\t\tif (!importsByFile.has(importPath)) {\n\t\t\t\timportsByFile.set(importPath, []);\n\t\t\t}\n\t\t\timportsByFile.get(importPath)?.push(key);\n\t\t}\n\n\t\t// Generate import statements for endpoints\n\t\tconst endpointImports = Array.from(importsByFile.entries())\n\t\t\t.map(\n\t\t\t\t([importPath, exports]) =>\n\t\t\t\t\t`import { ${exports.join(', ')} } from '${importPath}';`,\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\tconst allExportNames = endpoints.map(({ key }) => key);\n\n\t\t// One registration for every build, production included: each endpoint\n\t\t// is served by HonoEndpoint, which is what `gkm dev` and a feature test\n\t\t// serve it with. Production used to generate its own handlers per\n\t\t// \"tier\", and each was a hand-copy of the adaptor that drifted from it —\n\t\t// a session left undefined, an HttpError answered 500, an auditor\n\t\t// hard-coded to undefined, cookies a handler set never sent.\n\t\tconst content = `import type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { HonoEndpoint } from '@geekmidas/constructs/hono';\nimport { Endpoint } from '@geekmidas/constructs/endpoints';\nimport { ServiceDiscovery } from '@geekmidas/services';\nimport type { Hono } from 'hono';\n${endpointImports}\n\nexport const endpoints: Endpoint<any, any, any, any, any, any, any, any, any, any, any, any>[] = [\n ${allExportNames.join(',\\n ')}\n];\n\nexport async function setupEndpoints(\n app: Hono,\n envParser: EnvironmentParser<any>,\n logger: Logger,\n enableOpenApi: boolean = true,\n): Promise<void> {\n const serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n\n // Configure OpenAPI options based on enableOpenApi flag\n const openApiOptions: any = enableOpenApi ? {\n docsPath: '/__docs',\n openApiOptions: {\n title: 'API Documentation',\n version: '1.0.0',\n description: 'Generated API documentation'\n }\n } : { docsPath: false };\n\n HonoEndpoint.addRoutes(endpoints, serviceDiscovery, app, openApiOptions);\n\n // Add Swagger UI if OpenAPI is enabled\n if (enableOpenApi) {\n try {\n const { swaggerUI } = await import('@hono/swagger-ui');\n app.get('/__docs/ui', swaggerUI({ url: '/__docs' }));\n } catch {\n // @hono/swagger-ui not installed, skip Swagger UI\n }\n }\n}\n`;\n\n\t\tawait writeFile(endpointsPath, content);\n\n\t\treturn endpointsPath;\n\t}\n\n\tprivate async generateAppFile(\n\t\toutputDir: string,\n\t\tcontext: BuildContext,\n\t): Promise<string> {\n\t\t// What both entries start telemetry from — the production server and\n\t\t// `gkm dev`'s — decided by the surface's edge to a `Telemetry` node.\n\t\tawait writeTelemetryModule(outputDir, context.telemetry);\n\n\t\t// Use production generator if in production mode\n\t\tif (context.production?.enabled) {\n\t\t\treturn this.generateProductionAppFile(outputDir, context);\n\t\t}\n\n\t\tconst appFileName = 'app.ts';\n\t\tconst appPath = join(outputDir, appFileName);\n\n\t\t// The logger and the env parser, from the surface that already holds them.\n\t\tconst runtime = runtimeFor(context, dirname(appPath));\n\n\t\t// Generate telescope imports and setup if enabled\n\t\tconst telescopeEnabled = context.telescope?.enabled;\n\t\tconst telescopeWebSocketEnabled = context.telescope?.websocket;\n\t\tconst usesExternalTelescope = !!context.telescope?.telescopePath;\n\n\t\t// Generate imports based on whether telescope is external or inline\n\t\tconst telescopeFromSurface =\n\t\t\t!!context.surface?.module && !usesExternalTelescope;\n\n\t\tlet telescopeImports = '';\n\t\tif (telescopeEnabled) {\n\t\t\tif (telescopeFromSurface) {\n\t\t\t\t// The entry already imports the surface, which may or may not have\n\t\t\t\t// been given a Telescope — an object, so only the running entry can\n\t\t\t\t// tell. The inline one stands in when it was not.\n\t\t\t\ttelescopeImports = `import { Telescope, InMemoryStorage } from '@geekmidas/telescope';\nimport { createApi, createMiddleware } from '@geekmidas/telescope/hono';`;\n\t\t\t} else if (usesExternalTelescope) {\n\t\t\t\tconst relativeTelescopePath = relative(\n\t\t\t\t\tdirname(appPath),\n\t\t\t\t\tcontext.telescope?.telescopePath!,\n\t\t\t\t);\n\t\t\t\ttelescopeImports = `import ${context.telescope?.telescopeImportPattern} from '${relativeTelescopePath}';\nimport { createApi, createMiddleware } from '@geekmidas/telescope/hono';`;\n\t\t\t} else {\n\t\t\t\ttelescopeImports = `import { Telescope, InMemoryStorage } from '@geekmidas/telescope';\nimport { createApi, createMiddleware } from '@geekmidas/telescope/hono';`;\n\t\t\t}\n\t\t}\n\n\t\t// The database's read-only JSON API, from the declared database. The\n\t\t// client comes from the construct, so what it reads is by definition what\n\t\t// the handlers write to.\n\t\tconst databaseApi = context.databaseApi;\n\t\tconst databaseApiImports = databaseApi\n\t\t\t? `import { snifferContext } from '@geekmidas/constructs';\nimport { createIntrospectionHandler } from '@geekmidas/db/introspect';\nimport { ${databaseApi.database.exportName} as __introspectedDb } from '${importSpecifier(dirname(appPath), databaseApi.database.specifier)}';`\n\t\t\t: '';\n\n\t\t// Generate imports for server hooks\n\t\tconst cors = corsFor(context.surface);\n\t\tlet hooksImports = '';\n\t\tlet beforeSetupCall = '';\n\t\tlet afterSetupCall = '';\n\t\tif (context.hooks?.serverHooksPath) {\n\t\t\tconst relativeHooksPath = relative(\n\t\t\t\tdirname(appPath),\n\t\t\t\tcontext.hooks.serverHooksPath,\n\t\t\t);\n\t\t\thooksImports = `import * as serverHooks from '${relativeHooksPath}';`;\n\t\t\tbeforeSetupCall = `\n // Call beforeSetup hook if defined\n if (typeof serverHooks.beforeSetup === 'function') {\n await serverHooks.beforeSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t\tafterSetupCall = `\n // Call afterSetup hook if defined\n if (typeof serverHooks.afterSetup === 'function') {\n await serverHooks.afterSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t}\n\n\t\tconst telescopeWebSocketSetupCode = telescopeWebSocketEnabled\n\t\t\t? `\n // Setup WebSocket for real-time telescope updates\n try {\n const { createNodeWebSocket } = await import('@hono/node-ws');\n const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app: honoApp });\n // Add WebSocket route directly to main app (sub-app routes don't support WS upgrade)\n honoApp.get('${context.telescope?.path}/ws', upgradeWebSocket(() => ({\n onOpen: (_event: Event, ws: any) => {\n telescope.addWsClient(ws);\n },\n onClose: (_event: Event, ws: any) => {\n telescope.removeWsClient(ws);\n },\n onMessage: (event: MessageEvent, ws: any) => {\n try {\n const data = JSON.parse(event.data);\n if (data.type === 'ping') {\n ws.send(JSON.stringify({ type: 'pong' }));\n }\n } catch {\n // Ignore invalid messages\n }\n },\n })));\n // Store injectWebSocket for server entry to call after serve()\n (honoApp as any).__injectWebSocket = injectWebSocket;\n logger.info('Telescope WebSocket enabled');\n } catch (e) {\n logger.warn({ err: e }, 'WebSocket support not available - install @hono/node-ws for real-time updates');\n }\n`\n\t\t\t: '';\n\n\t\t// Generate telescope setup - either use external instance or create inline\n\t\tlet telescopeSetup = '';\n\t\tif (telescopeEnabled) {\n\t\t\tif (telescopeFromSurface || usesExternalTelescope) {\n\t\t\t\t// Use external telescope instance - no need to create one\n\t\t\t\ttelescopeSetup = `\n${telescopeWebSocketSetupCode}\n // Add telescope middleware (before endpoints to capture all requests)\n honoApp.use('*', createMiddleware(telescope));\n\n // Mount Telescope's JSON API\n const telescopeApi = createApi(telescope);\n honoApp.route('${context.telescope?.path}', telescopeApi);\n`;\n\t\t\t} else {\n\t\t\t\t// Create inline telescope instance\n\t\t\t\ttelescopeSetup = `\n // Setup Telescope for debugging/monitoring\n const telescopeStorage = new InMemoryStorage({ maxEntries: ${context.telescope?.maxEntries} });\n const telescope = new Telescope({\n enabled: true,\n path: '${context.telescope?.path}',\n ignorePatterns: ${JSON.stringify(context.telescope?.ignore)},\n recordBody: ${context.telescope?.recordBody},\n storage: telescopeStorage,\n });\n${telescopeWebSocketSetupCode}\n // Add telescope middleware (before endpoints to capture all requests)\n honoApp.use('*', createMiddleware(telescope));\n\n // Mount Telescope's JSON API\n const telescopeApi = createApi(telescope);\n honoApp.route('${context.telescope?.path}', telescopeApi);\n`;\n\t\t\t}\n\t\t}\n\n\t\tconst databaseApiSetup = databaseApi\n\t\t\t? `\n // The database's structure and rows as JSON, read-only, for whatever tool\n // the developer points at it. Dev only: it answers anyone who can reach the\n // port.\n const databaseApi = createIntrospectionHandler({\n db: await __introspectedDb.service.register({ envParser, context: snifferContext }),\n basePath: '${databaseApi.path}',\n });\n honoApp.all('${databaseApi.path}/*', (c) => databaseApi(c.req.raw));\n`\n\t\t\t: '';\n\n\t\tconst content = `/**\n * Generated server application\n *\n * ⚠️ WARNING: This is for LOCAL DEVELOPMENT ONLY\n * The subscriber polling mechanism is not production-ready.\n * For production, use AWS Lambda with SQS/SNS event sources.\n */\nimport { Hono } from 'hono';\nimport type { Hono as HonoType } from 'hono';\nimport { setupEndpoints } from './endpoints.js';\nimport { setupSubscribers } from './subscribers.js';\nimport { setupQueues } from './queues.js';\nimport { setupCrons } from './crons.js';\n${context.devProcessors ? \"import { setupProcessors } from './processors.js';\\n\" : ''}${runtime.imports}\n${telescopeImports}\n${databaseApiImports}\n${hooksImports}\n${cors.imports}\n${context.storageDrivers?.imports ?? ''}\n\n${runtime.bindings}\n${\n\ttelescopeEnabled && telescopeFromSurface\n\t\t? `// The surface's own Telescope, or the one \\`telescope\\` config describes.\nconst telescope =\n __surface.telescope ??\n new Telescope({\n enabled: true,\n path: '${context.telescope?.path}',\n ignorePatterns: ${JSON.stringify(context.telescope?.ignore)},\n recordBody: ${context.telescope?.recordBody},\n storage: new InMemoryStorage({ maxEntries: ${context.telescope?.maxEntries} }),\n });`\n\t\t: ''\n}\n\n${\n\tcontext.storageDrivers?.setup\n\t\t? `// Which drivers exist — storage, cache, events — is the entry point's\n// decision: the scheme in each injected URL picks one, so no construct and no\n// application module names a provider.\n${context.storageDrivers.setup}\n`\n\t\t: ''\n}\n${\n\tcontext.surface\n\t\t? `// Who this server is to Postgres: application_name on every connection.\nprocess.env.GKM_APP_NAME ??= ${JSON.stringify(context.surface.id)};\n\n`\n\t\t: ''\n}export interface ServerApp {\n app: HonoType;\n /** The origins this API's CORS allows: its own sites. */\n trustedOrigins: readonly string[];\n start: (options?: {\n port?: number;\n /** Returns the server, so a shutdown can stop it taking requests. */\n serve: (app: HonoType, port: number) => unknown;\n }) => Promise<void>;\n}\n\n/**\n * Create and configure the Hono application\n *\n * @param app - Optional Hono app instance to configure (creates new one if not provided)\n * @param enableOpenApi - Enable OpenAPI documentation (default: true)\n * @returns Server app with configured Hono app and start function\n *\n * @example\n * // With Bun\n * import { createApp } from './.gkm/server/app.js';\n *\n * const { app, start } = await createApp();\n *\n * await start({\n * port: 3000,\n * serve: (app, port) => {\n * Bun.serve({ port, fetch: app.fetch });\n * }\n * });\n *\n * @example\n * // With Node.js (using @hono/node-server)\n * import { serve } from '@hono/node-server';\n * import { createApp } from './.gkm/server/app.js';\n *\n * const { app, start } = await createApp();\n *\n * await start({\n * port: 3000,\n * serve: (app, port) => {\n * serve({ fetch: app.fetch, port });\n * }\n * });\n */\nexport async function createApp(app?: HonoType, enableOpenApi: boolean = true): Promise<ServerApp> {\n const honoApp = app || new Hono();\n const trustedOrigins: string[] = [];\n${telescopeSetup}${cors.setup}${beforeSetupCall}${databaseApiSetup}${\n\tcontext.devProcessors\n\t\t? `\n // The file servers' processors this app holds, where the local edge sends\n // each pattern on their hosts. Ahead of the endpoints, so none shadows them.\n setupProcessors(honoApp, envParser);\n`\n\t\t: ''\n}\n // Setup HTTP endpoints\n await setupEndpoints(honoApp, envParser, logger, enableOpenApi);\n${afterSetupCall}\n\n return {\n app: honoApp,\n trustedOrigins,\n async start(options) {\n if (!options?.serve) {\n throw new Error(\n 'serve function is required. Pass a serve function for your runtime:\\\\n' +\n ' - Bun: (app, port) => Bun.serve({ port, fetch: app.fetch })\\\\n' +\n ' - Node: (app, port) => serve({ fetch: app.fetch, port })'\n );\n }\n\n const port = options.port ?? 3000;\n\n // Mount pushed subscribers' routes and start polled ones. What comes\n // back subscribes the routes, once the server can answer them.\n const subscribeForPush = await setupSubscribers(honoApp, envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start subscribers');\n return async (_port: number) => {};\n });\n\n // Start queue workers in background (non-blocking, local development only)\n await setupQueues(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start queue workers');\n });\n\n // Schedule this app's crons. Caught like the others: a scheduler that\n // cannot start is not a reason for the HTTP server not to.\n await setupCrons(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to schedule crons');\n });\n\n logger.info({ port }, 'Starting server');\n\n // Start HTTP server using provided serve function\n await options.serve(honoApp, port);\n\n logger.info({ port }, 'Server started');\n\n await subscribeForPush(port);\n }\n };\n}\n\n// Default export for convenience\nexport default createApp;\n`;\n\n\t\tawait writeFile(appPath, content);\n\n\t\treturn appPath;\n\t}\n\n\t/**\n\t * One Lambda, one endpoint — and no environment import.\n\t *\n\t * The endpoint was built from its surface, so it carries the parser the\n\t * adaptor needs. This used to read\n\t * `import { envParser } from '../../config/env'`, a line the build wrote\n\t * because a generator can print a module specifier and cannot print an\n\t * object. Nothing has to be printed now, which is also why nothing has to be\n\t * named in config.\n\t */\n\tprivate generateAWSApiGatewayV2Handler(\n\t\timportPath: string,\n\t\texportName: string,\n\t\tdrivers?: StorageDrivers,\n\t): string {\n\t\treturn `import { AmazonApiGatewayV2Endpoint } from '@geekmidas/constructs/aws';\nimport { ${exportName} } from '${importPath}';\n${drivers?.imports ?? ''}\n${drivers?.setup ? `\\n// The handler registers the drivers its target needs.\\n${drivers.setup}\\n` : ''}\nconst adapter = new AmazonApiGatewayV2Endpoint(${exportName});\n\nexport const handler = adapter.handler;\n`;\n\t}\n\n\t/**\n\t * Generate a production-optimized app.ts file\n\t * No dev tools (Telescope, Studio, WebSocket), includes health checks and graceful shutdown\n\t */\n\tprivate async generateProductionAppFile(\n\t\toutputDir: string,\n\t\tcontext: BuildContext,\n\t): Promise<string> {\n\t\tconst appFileName = 'app.ts';\n\t\tconst appPath = join(outputDir, appFileName);\n\n\t\t// The app entry belongs to the primary surface, so no owner is named.\n\t\tconst runtime = runtimeFor(context, dirname(appPath));\n\n\t\tconst production = context.production!;\n\t\tconst healthCheckPath = production.healthCheck;\n\t\tconst enableGracefulShutdown = production.gracefulShutdown;\n\t\tconst enableOpenApi = production.openapi;\n\t\tconst includeSubscribers = production.subscribers === 'include';\n\n\t\t// Generate imports for server hooks\n\t\tconst cors = corsFor(context.surface);\n\t\tlet hooksImports = '';\n\t\tlet beforeSetupCall = '';\n\t\tlet afterSetupCall = '';\n\t\tif (context.hooks?.serverHooksPath) {\n\t\t\tconst relativeHooksPath = relative(\n\t\t\t\tdirname(appPath),\n\t\t\t\tcontext.hooks.serverHooksPath,\n\t\t\t);\n\t\t\thooksImports = `import * as serverHooks from '${relativeHooksPath}';`;\n\t\t\tbeforeSetupCall = `\n // Call beforeSetup hook if defined\n if (typeof serverHooks.beforeSetup === 'function') {\n await serverHooks.beforeSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t\tafterSetupCall = `\n // Call afterSetup hook if defined\n if (typeof serverHooks.afterSetup === 'function') {\n await serverHooks.afterSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t}\n\n\t\t// Subscriber + queue setup code (background workers share the same flag)\n\t\tconst subscriberSetup = includeSubscribers\n\t\t\t? `\n // Mount pushed subscribers' routes and start polled ones. What comes\n // back subscribes the routes, once the server can answer them.\n const subscribeForPush = await setupSubscribers(honoApp, envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start subscribers');\n return async (_port: number) => {};\n });\n\n // Start queue workers in background\n await setupQueues(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to start queue workers');\n });\n\n // Schedule this app's crons. Caught like the others: a scheduler that\n // cannot start is not a reason for the HTTP server not to.\n await setupCrons(envParser, logger).catch((error) => {\n logger.error({ err: error }, 'Failed to schedule crons');\n });\n`\n\t\t\t: '';\n\n\t\tconst subscriberImport = includeSubscribers\n\t\t\t? `import { setupSubscribers } from './subscribers.js';\nimport { setupQueues } from './queues.js';\nimport { setupCrons } from './crons.js';`\n\t\t\t: '';\n\n\t\t// Graceful shutdown code\n\t\tconst gracefulShutdownCode = enableGracefulShutdown\n\t\t\t? `\n // Graceful shutdown: stop taking requests, let in-flight ones finish, then\n // close what constructs opened (database pools) — so a rolling deploy does\n // not leave the old task holding connections. Bounded by\n // GKM_SHUTDOWN_TIMEOUT_MS, 8s by default: under Docker's 10s stop timeout,\n // so the process exits on its own terms rather than being killed mid-drain.\n let isShuttingDown = false;\n\n const shutdown = async () => {\n if (isShuttingDown) return;\n isShuttingDown = true;\n const deadline = Number(process.env.GKM_SHUTDOWN_TIMEOUT_MS) || 8000;\n logger.info({ deadline }, 'Graceful shutdown initiated');\n setTimeout(() => {\n logger.warn({ deadline }, 'Shutdown deadline reached, exiting');\n process.exit(1);\n }, deadline).unref();\n await new Promise<void>((resolve) => {\n const close = (server as { close?: (done: () => void) => void } | undefined)?.close;\n if (typeof close === 'function') close.call(server, () => resolve());\n else resolve();\n });\n await runShutdownHooks((error) => logger.error({ err: error }, 'Shutdown hook failed'));\n process.exit(0);\n };\n\n process.on('SIGTERM', shutdown);\n process.on('SIGINT', shutdown);\n`\n\t\t\t: '';\n\n\t\tconst content = `/**\n * Generated production server application\n *\n * This is a production-optimized build without dev tools.\n * - No Telescope debugging dashboard\n * - No Studio database browser\n * - No WebSocket updates\n * - Includes health checks and graceful shutdown\n */\nimport { Hono } from 'hono';\nimport type { Hono as HonoType } from 'hono';\n${enableGracefulShutdown ? \"import { runShutdownHooks } from '@geekmidas/constructs';\\n\" : ''}import { setupEndpoints } from './endpoints.js';\n${subscriberImport}\n${runtime.imports}\n${runtime.bindings}\n${hooksImports}\n${cors.imports}\n${context.storageDrivers?.imports ?? ''}\n\n${\n\tcontext.storageDrivers?.setup\n\t\t? `// The entry point registers the drivers its target needs.\n${context.storageDrivers.setup}\n`\n\t\t: ''\n}\n${\n\tcontext.surface\n\t\t? `// Who this server is to Postgres: application_name on every connection.\nprocess.env.GKM_APP_NAME ??= ${JSON.stringify(context.surface.id)};\n\n`\n\t\t: ''\n}export interface ServerApp {\n app: HonoType;\n /** The origins this API's CORS allows: its own sites. */\n trustedOrigins: readonly string[];\n start: (options?: {\n port?: number;\n serve: (app: HonoType, port: number) => void | Promise<void>;\n }) => Promise<void>;\n}\n\n/**\n * Create and configure the production Hono application\n */\nexport async function createApp(app?: HonoType): Promise<ServerApp> {\n const honoApp = app || new Hono();\n const trustedOrigins: string[] = [];\n\n // Health check endpoint (always first)\n honoApp.get('${healthCheckPath}', (c) => c.json({ status: 'ok', timestamp: Date.now() }));\n honoApp.get('/ready', (c) => c.json({ ready: true }));\n\n // An HttpError a handler or a session callback throws — a 401, a 404 —\n // answers with its own status, as it does under gkm dev. The optimized\n // handlers do not catch, so without this every one of them was a 500.\n // Anything else is a 500 that says nothing about why, and is logged.\n honoApp.onError((error, c) => {\n const http = error as {\n isHttpError?: boolean;\n statusCode?: number;\n statusMessage?: string;\n code?: string;\n details?: unknown;\n };\n if (http.isHttpError === true && typeof http.statusCode === 'number') {\n return c.json(\n {\n name: error.name,\n message: error.message,\n statusCode: http.statusCode,\n statusMessage: http.statusMessage,\n code: http.code,\n details: http.details,\n },\n http.statusCode as 500,\n );\n }\n logger.error({ err: error }, 'Unhandled error');\n return c.json({ message: 'Internal Server Error' }, 500);\n });\n${cors.setup}${beforeSetupCall}\n // Setup HTTP endpoints (OpenAPI: ${enableOpenApi})\n await setupEndpoints(honoApp, envParser, logger, ${enableOpenApi});\n${afterSetupCall}\n return {\n app: honoApp,\n trustedOrigins,\n async start(options) {\n if (!options?.serve) {\n throw new Error(\n 'serve function is required. Pass a serve function for your runtime:\\\\n' +\n ' - Bun: (app, port) => Bun.serve({ port, fetch: app.fetch })\\\\n' +\n ' - Node: (app, port) => serve({ fetch: app.fetch, port })'\n );\n }\n\n const port = options.port ?? Number(process.env.PORT) ?? 3000;\n let server: unknown;\n${gracefulShutdownCode}${subscriberSetup}\n logger.info({ port }, 'Starting production server');\n\n // Start HTTP server using provided serve function\n server = await options.serve(honoApp, port);\n\n logger.info({ port }, 'Production server started');\n${includeSubscribers ? '\\n await subscribeForPush(port);' : ''}\n }\n };\n}\n\n// Default export for convenience\nexport default createApp;\n`;\n\n\t\tawait writeFile(appPath, content);\n\n\t\t// Also generate the production server entry point\n\t\tawait this.generateProductionServerEntry(outputDir, context);\n\n\t\treturn appPath;\n\t}\n\n\t/**\n\t * Generate production server.ts entry point\n\t */\n\tprivate async generateProductionServerEntry(\n\t\toutputDir: string,\n\t\tcontext: BuildContext,\n\t): Promise<void> {\n\t\tconst serverPath = join(outputDir, 'server.ts');\n\n\t\t// `telemetry.ts` beside it was written with `app.ts`, for this entry\n\t\t// and the `gkm dev` one alike, which start it the same way.\n\t\tconst content = `#!/usr/bin/env node\n/**\n * Production server entry point\n * Generated by 'gkm build --production'\n */\nimport { serve } from '@hono/node-server';\nimport { Hono } from 'hono';\n\n${startTelemetryCode([context.production?.healthCheck ?? '/health', '/ready'])}\nconst { createApp } = await import('./app.js');\n\nconst port = Number(process.env.PORT) || 3000;\n\nconst app = new Hono();\n${mountRequestSpansCode('app')}\nconst created = await createApp(app);\ntrustedOrigins = created.trustedOrigins;\nconst { start } = created;\n\nawait start({\n port,\n serve: (app, port) => serve({ fetch: app.fetch, port }),\n});\n`;\n\n\t\tawait writeFile(serverPath, content);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAcA,IAAa,mCAAb,cAAsD,SAAS;CACzC;CAArB,YAAY,YAA6B;EACxC,MACC,wEAAwE,WAAW,6DACpF;EAHoB,KAAA,aAAA;EAIpB,KAAK,OAAO;CACb;AACD;;AAGA,SAAgB,sBACf,WACS;CACT,IAAI,OAAO,cAAc,WAAW,OAAO,OAAO,SAAS;CAC3D,MAAM,EAAE,eAAe;CACvB,IAAI,CAAC,OAAO,SAAS,UAAU,KAAK,aAAa,KAAK,aAAa,GAClE,MAAM,IAAI,iCAAiC,UAAU;CAEtD,OAAO,iBAAiB,WAAW;AACpC;;;;;AAMA,SAAgB,cAAc,WAA8C;CAC3E,IAAI,CAAC,WAAW,OAAO,CAAC;CACxB,IAAI,cAAc,MAAM,OAAO,CAAC,aAAa;CAC7C,OAAO,CAAC,eAAe,OAAO,UAAU,UAAU,CAAC;AACpD;;AAGA,SAAgB,mBACf,OACqC;CACrC,IAAI,UAAU,KAAA,KAAa,UAAU,OAAO,OAAO,KAAA;CACnD,IAAI,UAAU,MAAM,OAAO;CAC3B,OAAO,EAAE,YAAY,OAAO,KAAK,EAAE;AACpC;;;;AClCA,SAAgB,eACf,WAKmB;CACnB,OAAO,UAAU,SAAS,aACzB,SAAS,YACN,CACA;EACC,QAAQ,SAAS;EACjB,MAAM,SAAS;EACf,GAAG,SAAS;CACb,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;;;;;;;;;EAef,uBAAuB,gBAAgB;;;;;;;EAOvC,qBAAqB,0CAA0C,GAAG;;;;;;;;EASlE,MAAM,UAAU,SAAS,OAAO;EAGhC,MAAM,KAAK,8BAA8B,WAAW,OAAO;EAE3D,OAAO;CACR;;;;CAKA,MAAc,8BACb,WACA,SACgB;EAChB,MAAM,aAAa,KAAK,WAAW,WAAW;EAI9C,MAAM,UAAU;;;;;;;;EAQhB,mBAAmB,CAAC,QAAQ,YAAY,eAAe,WAAW,QAAQ,CAAC,EAAE;;;;;;EAM7E,sBAAsB,KAAK,EAAE;;;;;;;;;;EAW7B,MAAM,UAAU,YAAY,OAAO;CACpC;AACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"SubscriberGenerator-CfZWX0lT.mjs","names":[],"sources":["../src/reconcile/inboxRelay.ts","../src/generators/subscriberRoute.ts","../src/reconcile/fakes.ts","../src/generators/SubscriberGenerator.ts"],"sourcesContent":["/**\n * Receiving mail locally: Mailpit's webhook, and the worker it posts to.\n *\n * Deployed, SES stores each message and publishes its receipt notification on\n * the inbox's topic. Locally Mailpit receives it, and its webhook posts each\n * message to one route — `POST /__gkm/inbox` on the worker that runs the\n * inbox subscribers — which hands it to the same receiver `mailbox.receive`\n * calls in a feature test (`receiveMail` in `@geekmidas/constructs/inbox`).\n *\n * Shared by every local stage and the local compose stack: each asks this\n * module which worker relays and with what token, and supplies only how that\n * worker is reached from its Mailpit — the host's gateway, or the stack's\n * network.\n */\n\nimport { createHash } from 'node:crypto';\nimport { type ConstructManifest, providedKeyFor } from '@geekmidas/manifest';\nimport { GkmError } from '../errors';\nimport type { BoundSubscriber } from './discover';\n\n/** The route Mailpit posts each message it receives to. */\nexport const INBOX_ROUTE = '/__gkm/inbox';\n\n/** The env key the relaying worker reads its token from. */\nexport const INBOX_RELAY_TOKEN_KEY = 'GKM_INBOX_RELAY_TOKEN';\n\n/**\n * Inbox subscribers in more than one worker. Mailpit posts to one webhook, so\n * locally one worker receives for every inbox — #343 lifts this.\n */\nexport class InboxSubscribersSpanWorkers extends GkmError {\n\tconstructor(readonly workers: readonly string[]) {\n\t\tsuper(\n\t\t\t`Inbox subscribers run in ${workers.map((w) => `'${w}'`).join(' and ')}, ` +\n\t\t\t\t`and locally mail is received by one worker: Mailpit posts each ` +\n\t\t\t\t`message to a single webhook. Bind every worker.inbox(…) to one ` +\n\t\t\t\t`worker for now (#343).`,\n\t\t);\n\t\tthis.name = 'InboxSubscribersSpanWorkers';\n\t}\n}\n\n/**\n * The worker whose route Mailpit posts to: the one that runs every inbox\n * subscriber. `undefined` when no inbox has a subscriber.\n */\nexport function inboxRelayWorker(\n\tmanifest: ConstructManifest,\n\tsubscribers: Readonly<Record<string, readonly BoundSubscriber[]>>,\n): string | undefined {\n\tconst topicKeys = new Set<string>();\n\tfor (const declaration of Object.values(manifest)) {\n\t\tif (declaration.kind !== 'inbox') continue;\n\t\ttopicKeys.add(\n\t\t\tprovidedKeyFor(declaration.topic, 'topic', 'publisherConnectionString'),\n\t\t);\n\t}\n\tif (topicKeys.size === 0) return undefined;\n\n\tconst workers = Object.keys(subscribers)\n\t\t.sort()\n\t\t.filter((worker) =>\n\t\t\t(subscribers[worker] ?? []).some(({ connectionKey }) =>\n\t\t\t\ttopicKeys.has(connectionKey),\n\t\t\t),\n\t\t);\n\tif (workers.length > 1) throw new InboxSubscribersSpanWorkers(workers);\n\treturn workers[0];\n}\n\n/**\n * The token Mailpit presents in the webhook's query — it cannot send a\n * header. Derived as a bucket's webhook token is: from the stage's seed where\n * one is given, and the project; not salted by the stage, since `gkm dev` and\n * `gkm test` share one Mailpit.\n */\nexport function inboxRelayToken(project: string, seed?: string): string {\n\treturn createHash('sha256')\n\t\t.update(`${seed ? `${seed}:` : ''}${project}:inbox-webhook`)\n\t\t.digest('base64url')\n\t\t.slice(0, 32);\n}\n\n/** Mailpit's `MP_WEBHOOK_URL`: the relay route at `base`, with the token. */\nexport function inboxWebhookUrl(base: string, token: string): string {\n\treturn `${base.replace(/\\/+$/, '')}${INBOX_ROUTE}?token=${encodeURIComponent(token)}`;\n}\n","/**\n * Where SNS pushes a topic subscriber's messages, on the server that runs it:\n * named after the subscriber's export.\n *\n * One definition for both sides — the generated server mounts the route, and\n * the stack exposes exactly these paths on a worker's host — so the path the\n * edge lets through and the path the worker answers cannot drift.\n */\nexport const SUBSCRIBER_ROUTE_PREFIX = '/__gkm/subscribers/';\n\n/** The route a subscriber's pushes arrive on. */\nexport function subscriberRoute(exportName: string): string {\n\treturn `${SUBSCRIBER_ROUTE_PREFIX}${exportName}`;\n}\n\n/**\n * Where the deploy hands a server the SNS subscriptions it made for its\n * routes: a JSON object of subscriber export → subscription ARN. Against SNS\n * itself a server mounts a route only for a subscription recorded here, and\n * refuses a notification that names another.\n */\nexport const SNS_SUBSCRIPTIONS_KEY = 'GKM_SNS_SUBSCRIPTIONS';\n\n/**\n * Where a local object store posts a bucket's events, on the process that runs\n * the bucket's subscribers: named after the bucket. Never on a public host —\n * MinIO reaches it over the stack's network, or the host's.\n */\nexport const OBJECTS_ROUTE_PREFIX = '/__gkm/objects/';\n\n/** The route a bucket's events are posted to. */\nexport function objectsRoute(bucketId: string): string {\n\treturn `${OBJECTS_ROUTE_PREFIX}${bucketId}`;\n}\n","/**\n * Fakes, read from where the convention puts them.\n *\n * `test/fakes/<id>.ts` default-exports `fake.app(…)` or `fake.image(…)` for an\n * external API, and `fake.credential(…)` for a credential. The construct never\n * names it — that is what keeps a fake out of a deployed bundle — so this is\n * the one place it is found, by the same rule that finds a database's factory\n * in `test/factories/<id>.ts`.\n */\n\nimport { access } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { ConstructManifest } from '@geekmidas/manifest';\nimport { kebabCase } from '@geekmidas/manifest';\nimport { GkmError } from '../errors';\nimport type { Plan } from './plan';\n\n/** Where a project keeps its external APIs' fakes, relative to its root. */\nexport const DEFAULT_FAKES_DIR = 'test/fakes';\n\n/** One external API's fake, as the local target needs it. */\nexport interface LocalFake {\n\t/** The file it was read from — what the harness and `gkm dev` import. */\n\tfile: string;\n\t/** The image to run, for a fake the provider publishes. */\n\timage?: string;\n\t/** The port that image listens on inside its container. */\n\tport?: number;\n\t/** What the fake accepts, as the JSON `<ID>_CREDENTIALS` holds. */\n\tcredentials: string;\n}\n\n/** The marker `fake.app` and `fake.image` set — the same registered symbol. */\nconst FAKE = Symbol.for('@geekmidas/constructs/fake');\n\ninterface FakeExport {\n\tkind: 'app' | 'image' | 'credential';\n\timage?: string;\n\tport?: number;\n\tcredentials: unknown;\n}\n\n/**\n * The fake for every external API the manifest declares, keyed by id.\n *\n * @throws {NoFake} when an external API has no file, since a local stage would\n * otherwise have nothing to call.\n * @throws {NotAFake} when the file's default export is not one.\n */\nexport async function readFakes(\n\troot: string,\n\tmanifest: ConstructManifest,\n): Promise<Record<string, LocalFake>> {\n\tconst fakes: Record<string, LocalFake> = {};\n\n\tfor (const [id, declaration] of Object.entries(manifest)) {\n\t\tif (declaration?.kind !== 'external-api') continue;\n\n\t\tconst file = await fakeFile(join(root, DEFAULT_FAKES_DIR), id);\n\t\tif (!file) throw new NoFake(id, `${fakeBase(root, id)}.ts`);\n\t\tconst value = await importFake(file);\n\t\tif (value.kind === 'credential') throw new NotAFake(file);\n\n\t\tfakes[id] = {\n\t\t\tfile,\n\t\t\t...(value.kind === 'image'\n\t\t\t\t? { image: value.image, port: value.port }\n\t\t\t\t: {}),\n\t\t\tcredentials: JSON.stringify(value.credentials),\n\t\t};\n\t}\n\n\treturn fakes;\n}\n\n/**\n * Each credential's fake value, as the JSON `<ID>_CREDENTIALS` holds, keyed by\n * id — for the credentials that have a fake. Unlike an external API's, a\n * credential's fake is optional here: a stage that stores the real value\n * needs none. The test stage's own check (`assertTestCredentials`) is what\n * refuses one with neither.\n *\n * @throws {NotAFake} when the file's default export is not a credential's fake.\n */\nexport async function readCredentialFakes(\n\troot: string,\n\tmanifest: ConstructManifest,\n): Promise<Record<string, string>> {\n\tconst values: Record<string, string> = {};\n\n\tfor (const [id, declaration] of Object.entries(manifest)) {\n\t\tif (declaration?.kind !== 'credential') continue;\n\n\t\tconst file = await fakeFile(join(root, DEFAULT_FAKES_DIR), id);\n\t\tif (!file) continue;\n\t\tconst value = await importFake(file);\n\t\tif (value.kind !== 'credential') throw new NotAFake(file);\n\n\t\tvalues[id] = JSON.stringify(value.credentials);\n\t}\n\n\treturn values;\n}\n\n/**\n * A credential the test stage has no value for: no fake, and nothing stored.\n * Raised when the stage is set up, before a test reaches it — not as a schema\n * error inside the handler that first asked.\n */\nexport class CredentialHasNoTestValue extends GkmError {\n\tconstructor(\n\t\treadonly id: string,\n\t\treadonly key: string,\n\t\treadonly file: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${id}' is a credential, and the test stage has no value for ${key}: ` +\n\t\t\t\t`no fake, and none stored — a stage set up fresh, as CI's ` +\n\t\t\t\t`auto-setup does, holds no third party's credentials. Give it a ` +\n\t\t\t\t`fake: create ${file}, default-exporting ` +\n\t\t\t\t`fake.credential(…) from @geekmidas/constructs/credential. It is ` +\n\t\t\t\t`read only by gkm test and gkm dev --fake; a deployed stage still ` +\n\t\t\t\t`needs the real value (gkm secrets:add --stage <stage>).`,\n\t\t);\n\t\tthis.name = 'CredentialHasNoTestValue';\n\t}\n}\n\n/**\n * Every credential the test stage must hand its suite, with the value it\n * resolved — a fake's, or one the stage stores.\n *\n * @throws {CredentialHasNoTestValue} for the first one with neither.\n */\nexport function assertTestCredentials(\n\troot: string,\n\tplan: Pick<Plan, 'resources'>,\n\tenv: Readonly<Record<string, string | undefined>>,\n): Record<string, string> {\n\tconst values: Record<string, string> = {};\n\n\tfor (const { id, kind, envKey } of plan.resources) {\n\t\tif (kind !== 'credential') continue;\n\n\t\tconst value = env[envKey];\n\t\tif (value === undefined) {\n\t\t\tthrow new CredentialHasNoTestValue(\n\t\t\t\tid,\n\t\t\t\tenvKey,\n\t\t\t\t`${fakeBase(root, id)}.ts`,\n\t\t\t);\n\t\t}\n\t\tvalues[envKey] = value;\n\t}\n\n\treturn values;\n}\n\n/** `<root>/test/fakes/<id>`, without an extension. */\nfunction fakeBase(root: string, id: string): string {\n\treturn join(root, DEFAULT_FAKES_DIR, kebabCase(id));\n}\n\n/** The first of `<id>.ts`, `.mts`, `.js`, `.mjs` that exists. */\nasync function fakeFile(\n\tfolder: string,\n\tid: string,\n): Promise<string | undefined> {\n\tconst base = join(folder, kebabCase(id));\n\tfor (const extension of ['.ts', '.mts', '.js', '.mjs']) {\n\t\tconst file = `${base}${extension}`;\n\t\tconst exists = await access(file).then(\n\t\t\t() => true,\n\t\t\t() => false,\n\t\t);\n\t\tif (exists) return file;\n\t}\n\n\treturn undefined;\n}\n\n/**\n * A fake file's default export.\n *\n * @throws {NotAFake} when it is not a fake.\n */\nasync function importFake(file: string): Promise<FakeExport> {\n\tconst module = (await import(pathToFileURL(file).href)) as {\n\t\tdefault?: unknown;\n\t};\n\tconst value = module.default;\n\tif (!isFakeExport(value)) throw new NotAFake(file);\n\treturn value;\n}\n\nfunction isFakeExport(value: unknown): value is FakeExport {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t(value as { [FAKE]?: unknown })[FAKE] === true\n\t);\n}\n\n/** An external API with no fake for a local stage to call. */\nexport class NoFake extends GkmError {\n\tconstructor(\n\t\treadonly id: string,\n\t\treadonly file: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${id}' is an external API, and a local stage calls its fake rather ` +\n\t\t\t\t`than the provider — but there is none. Create ${file}, ` +\n\t\t\t\t`default-exporting fake.app(…) or fake.image(…) from ` +\n\t\t\t\t`@geekmidas/constructs/external-api.`,\n\t\t);\n\t\tthis.name = 'NoFake';\n\t}\n}\n\n/** A file in the fakes folder whose default export is not a fake. */\nexport class NotAFake extends GkmError {\n\tconstructor(readonly file: string) {\n\t\tsuper(\n\t\t\t`${file} is where a fake lives, and its default export is not one ` +\n\t\t\t\t`for its construct. For an external API, export default ` +\n\t\t\t\t`fake.app(handler, { credentials }) or ` +\n\t\t\t\t`fake.image(image, { port, credentials }); for a credential, ` +\n\t\t\t\t`fake.credential(value).`,\n\t\t);\n\t\tthis.name = 'NotAFake';\n\t}\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Subscriber } from '@geekmidas/constructs/subscribers';\nimport { canonicalId, INBOX_EVENT, providedKeyFor } from '@geekmidas/manifest';\nimport type { BuildContext } from '../build/types';\nimport {\n\tsubscriberConnectionKey,\n\tsubscriberTokenKey,\n} from '../reconcile/edges.js';\nimport { INBOX_RELAY_TOKEN_KEY, INBOX_ROUTE } from '../reconcile/inboxRelay';\nimport type { SubscriberInfo } from '../types';\nimport { runtimeFor } from './EndpointGenerator.js';\nimport {\n\tConstructGenerator,\n\ttype GeneratedConstruct,\n\ttype GeneratorOptions,\n} from './Generator';\nimport {\n\tOBJECTS_ROUTE_PREFIX,\n\tSNS_SUBSCRIPTIONS_KEY,\n\tSUBSCRIBER_ROUTE_PREFIX,\n} from './subscriberRoute.js';\n\nexport class SubscriberGenerator extends ConstructGenerator<\n\tSubscriber<any, any, any, any, any, any, any>,\n\tSubscriberInfo[]\n> {\n\tisConstruct(\n\t\tvalue: any,\n\t): value is Subscriber<any, any, any, any, any, any, any> {\n\t\treturn Subscriber.isSubscriber(value);\n\t}\n\n\tasync build(\n\t\tcontext: BuildContext,\n\t\tconstructs: GeneratedConstruct<\n\t\t\tSubscriber<any, any, any, any, any, any, any>\n\t\t>[],\n\t\toutputDir: string,\n\t\toptions?: GeneratorOptions,\n\t): Promise<SubscriberInfo[]> {\n\t\tconst target = options?.target ?? 'aws';\n\t\tconst logger = console;\n\t\tconst subscriberInfos: SubscriberInfo[] = [];\n\n\t\tfor (const { key, construct } of constructs) {\n\t\t\tassertDoesNotFeedItself(key, construct);\n\t\t}\n\n\t\tif (target === 'server') {\n\t\t\t// Generate subscribers.ts for server-based polling (even if empty).\n\t\t\t// A bucket's subscriber is pushed to by the topic the storage\n\t\t\t// publishes to, whatever broker carries the app's own events.\n\t\t\tawait this.generateServerSubscribersFile(\n\t\t\t\toutputDir,\n\t\t\t\tconstructs,\n\t\t\t\t(context.eventsBackends?.includes('sns') ?? false) ||\n\t\t\t\t\tconstructs.some(({ construct }) => construct.bucketName),\n\t\t\t);\n\n\t\t\tlogger.log(\n\t\t\t\t`Generated server subscribers file with ${constructs.length} subscribers (polling mode)`,\n\t\t\t);\n\n\t\t\t// Return empty array as server subscribers don't have individual handlers\n\t\t\treturn subscriberInfos;\n\t\t}\n\n\t\tif (constructs.length === 0) {\n\t\t\treturn subscriberInfos;\n\t\t}\n\n\t\t// Create subscribers subdirectory\n\t\tconst subscribersDir = join(outputDir, 'subscribers');\n\t\tawait mkdir(subscribersDir, { recursive: true });\n\n\t\t// Generate subscriber handlers\n\t\tfor (const { key, construct, path } of constructs) {\n\t\t\tconst handlerFile = await this.generateSubscriberHandler(\n\t\t\t\tsubscribersDir,\n\t\t\t\tpath.relative,\n\t\t\t\tkey,\n\t\t\t\tconstruct,\n\t\t\t\tcontext,\n\t\t\t\tconstruct.owner,\n\t\t\t);\n\n\t\t\tsubscriberInfos.push({\n\t\t\t\tname: key,\n\t\t\t\thandler: relative(options?.root ?? process.cwd(), handlerFile).replace(\n\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t'.handler',\n\t\t\t\t),\n\t\t\t\tsubscribedEvents: construct.subscribedEvents || [],\n\t\t\t\t// A subscriber bound to a topic (via `s.topic(topic)`) records the\n\t\t\t\t// binding so infra wires the SNS subscription.\n\t\t\t\t...(construct.topicName\n\t\t\t\t\t? { transport: 'topic' as const, topic: construct.topicName }\n\t\t\t\t\t: {}),\n\t\t\t\t// A subscriber bound to a bucket records it, and the keys it\n\t\t\t\t// watches, so infra wires the bucket's notifications.\n\t\t\t\t...(construct.bucketName\n\t\t\t\t\t? {\n\t\t\t\t\t\t\ttransport: 'topic' as const,\n\t\t\t\t\t\t\tbucket: construct.bucketName,\n\t\t\t\t\t\t\t...construct.objectFilter,\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t// An inbox's subscriber is a topic subscriber, delivered what SES\n\t\t\t\t// publishes rather than what a producer wrote.\n\t\t\t\t...(construct.inboxName ? { inbox: construct.inboxName } : {}),\n\t\t\t\ttimeout: construct.timeout,\n\t\t\t\tmemorySize: construct.memorySize,\n\t\t\t\tenvironment: await construct.getEnvironment({\n\t\t\t\t\tmarkOptional: context.markOptional,\n\t\t\t\t}),\n\t\t\t\tdependencies: construct.constructs,\n\t\t\t});\n\n\t\t\tlogger.log(`Generated subscriber handler: ${key}`);\n\t\t}\n\n\t\treturn subscriberInfos;\n\t}\n\n\tprivate async generateSubscriberHandler(\n\t\toutputDir: string,\n\t\tsourceFile: string,\n\t\texportName: string,\n\t\t_subscriber: Subscriber<any, any, any, any, any, any, any>,\n\t\tcontext: BuildContext,\n\t\t/** The construct that owns this — its worker, or its surface. */\n\t\towner: string | undefined,\n\t): Promise<string> {\n\t\tconst handlerFileName = `${exportName}.ts`;\n\t\tconst handlerPath = join(outputDir, handlerFileName);\n\n\t\tconst relativePath = relative(dirname(handlerPath), sourceFile);\n\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\t// Imports the construct that owns this, and binds `envParser` and\n\t\t// `logger` off it — the objects it was declared with, rather than a\n\t\t// module path printed in from config.\n\t\tconst runtime = runtimeFor(context, dirname(handlerPath), owner);\n\n\t\tconst content = `import { AWSLambdaSubscriber } from '@geekmidas/constructs/aws';\nimport { ${exportName} } from '${importPath}';\n${runtime.imports}\n${context.storageDrivers?.imports ?? ''}\n${runtime.bindings}\n${context.storageDrivers?.setup ? `\\n// The handler registers the drivers its target needs.\\n${context.storageDrivers.setup}\\n` : ''}\nconst adapter = new AWSLambdaSubscriber(envParser, ${exportName});\n\nexport const handler = adapter.handler;\n`;\n\n\t\tawait writeFile(handlerPath, content);\n\t\treturn handlerPath;\n\t}\n\n\tprivate async generateServerSubscribersFile(\n\t\toutputDir: string,\n\t\tsubscribers: GeneratedConstruct<\n\t\t\tSubscriber<any, any, any, any, any, any, any>\n\t\t>[],\n\t\t/**\n\t\t * The broker is SNS, so a subscriber is pushed to over HTTP. Only then is\n\t\t * the push code generated: it imports the SNS client, which a bundle for\n\t\t * any other broker must never have to resolve.\n\t\t */\n\t\tpush: boolean,\n\t): Promise<string> {\n\t\tawait mkdir(outputDir, { recursive: true });\n\t\tconst subscribersPath = join(outputDir, 'subscribers.ts');\n\n\t\t// Nothing to run, so nothing to import. Every app gets this file, and\n\t\t// `@geekmidas/events` is only installed by one that declared a Topic or\n\t\t// a Queue — importing it here crashed every dev server that had not.\n\t\tif (subscribers.length === 0) {\n\t\t\tawait writeFile(\n\t\t\t\tsubscribersPath,\n\t\t\t\t`/**\n * Generated subscribers setup — this app declares none.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\n\nexport async function setupSubscribers(\n _app: unknown,\n _envParser: EnvironmentParser<any>,\n _logger: Logger,\n): Promise<(port: number) => Promise<void>> {\n return async () => {};\n}\n\nexport function subscribersStatus(): { failed: string[]; connections: unknown[] } {\n return { failed: [], connections: [] };\n}\n\nexport async function stopSubscribers(): Promise<void> {}\n`,\n\t\t\t);\n\t\t\treturn subscribersPath;\n\t\t}\n\n\t\tconst importsByFile = new Map<string, string[]>();\n\t\tfor (const { path, key } of subscribers) {\n\t\t\tconst importPath = relative(\n\t\t\t\tdirname(subscribersPath),\n\t\t\t\tpath.relative,\n\t\t\t).replace(/\\.ts$/, '.js');\n\t\t\timportsByFile.set(importPath, [\n\t\t\t\t...(importsByFile.get(importPath) ?? []),\n\t\t\t\tkey,\n\t\t\t]);\n\t\t}\n\t\tconst imports = Array.from(importsByFile.entries())\n\t\t\t.map(\n\t\t\t\t([importPath, exports]) =>\n\t\t\t\t\t`import { ${exports.join(', ')} } from '${importPath}';`,\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\t// Each subscriber reaches the topic it is bound to, by that topic's own\n\t\t// key — resolved here, at build time, from the binding. A bucket's\n\t\t// subscriber reaches the bucket's events, which carry no `type`\n\t\t// attribute for SNS to filter on: it filters what it is sent itself.\n\t\t// So does an inbox's: SES publishes its receipt notification bare.\n\t\tconst entries = subscribers\n\t\t\t.map(({ key, construct }) => {\n\t\t\t\tconst connectionKey = subscriberConnectionKey(construct);\n\t\t\t\tconst tokenKey = subscriberTokenKey(construct);\n\t\t\t\tconst topic = construct.topicName ?? construct.bucketName;\n\t\t\t\tconst bucket = construct.bucketName\n\t\t\t\t\t? canonicalId(construct.bucketName)\n\t\t\t\t\t: undefined;\n\t\t\t\treturn ` { id: '${key}', subscriber: ${key}, topic: ${\n\t\t\t\t\ttopic ? `'${topic}'` : 'undefined'\n\t\t\t\t}, connectionKey: ${\n\t\t\t\t\tconnectionKey ? `'${connectionKey}'` : 'undefined'\n\t\t\t\t}, filtered: ${\n\t\t\t\t\tconstruct.bucketName || construct.inboxName ? 'false' : 'true'\n\t\t\t\t}, bucket: ${\n\t\t\t\t\tbucket ? `'${bucket}'` : 'undefined'\n\t\t\t\t}, tokenKey: ${tokenKey ? `'${tokenKey}'` : 'undefined'}, inbox: ${\n\t\t\t\t\tconstruct.inboxName\n\t\t\t\t\t\t? JSON.stringify({\n\t\t\t\t\t\t\t\tid: construct.inboxName,\n\t\t\t\t\t\t\t\tdomainKey: providedKeyFor(\n\t\t\t\t\t\t\t\t\tconstruct.inboxName,\n\t\t\t\t\t\t\t\t\t'inbox',\n\t\t\t\t\t\t\t\t\t'domain',\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\taddressing: construct.inboxAddressing ?? { addresses: [] },\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t: 'undefined'\n\t\t\t\t} },`;\n\t\t\t})\n\t\t\t.join('\\n');\n\n\t\t// The route Mailpit posts what an inbox receives to — generated only\n\t\t// for an app with an inbox subscriber, so no other bundle ever names\n\t\t// the inbox's module.\n\t\tconst receives = subscribers.some(({ construct }) => construct.inboxName);\n\n\t\tconst content = `/**\n * Generated subscribers setup.\n *\n * Each subscriber is run against the topic it is bound to, through that\n * topic's own connection string:\n *\n * - **sns://** — pushed, not polled. The subscriber gets an HTTP route on this\n * server, subscribed to the topic with a filter policy of the events it\n * named, so SNS fans out to each subscriber. The route runs the subscriber\n * through the same adaptor a Lambda subscription does. Against SNS itself\n * the deploy made the subscription and recorded its ARN in\n * ${SNS_SUBSCRIPTIONS_KEY}: a route is mounted only for a recorded one, its\n * confirmation goes through the API, and nothing is subscribed from here.\n * Against an emulator, where nothing deploys, the route subscribes itself.\n * - **anything else** (pgboss://, rabbitmq://, sqs://) — polled. On pg-boss\n * each subscriber drains a queue of its own, \\`<topic>/<subscriber>\\`, so\n * every subscriber sees every event; replicas of one subscriber share it.\n *\n * A bucket's subscriber is polled the same way, under the bucket's name, when\n * the bucket is in a local object store: the store posts each event to\n * \\`${OBJECTS_ROUTE_PREFIX}<Bucket>\\` on this server, with the bucket's token, and\n * the event is relayed onto the broker as \\`object.created\\` or\n * \\`object.deleted\\` — so every subscriber of the bucket sees it.\n *\n * GKM_SUBSCRIBERS=off (\\`gkm dev --no-subscribers\\`) runs none of them.\n * GKM_SUBSCRIBER_PUSH_URL is the address an emulator pushes to, defaulting to\n * this server through host.docker.internal.\n */\nimport { timingSafeEqual } from 'node:crypto';\nimport { connect } from 'node:net';\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { EventConnectionFactory, Publisher, Subscriber } from '@geekmidas/events';\nimport type { EventConnection } from '@geekmidas/events';\nimport { ServiceDiscovery } from '@geekmidas/services';\n${receives ? \"import { type ReceivingInbox, receiveMail } from '@geekmidas/constructs/inbox';\\n\" : ''}${imports}\n\nconst subscribers = [\n${entries}\n];\n\n// What was opened, and what could not be: a worker's health check reads both,\n// and its shutdown closes what was opened.\nconst connections = new Map<string, EventConnection>();\nconst failed: string[] = [];\n\n/**\n * The subscriptions the deploy made against SNS itself, by subscriber: which\n * routes to mount, and the ARN each one's notifications must name.\n */\nfunction recordedSubscriptions(logger: Logger): Record<string, string> {\n const raw = process.env.${SNS_SUBSCRIPTIONS_KEY};\n if (!raw) return {};\n try {\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;\n } catch {}\n logger.error('${SNS_SUBSCRIPTIONS_KEY} is not a JSON object of subscriber → subscription ARN');\n return {};\n}\n\n/** The route a subscriber's pushes arrive on. */\nexport const SUBSCRIBER_ROUTE = (id: string) => \\`${SUBSCRIBER_ROUTE_PREFIX}\\${id}\\`;\n\n/** The route a local object store posts a bucket's events to. */\nexport const OBJECTS_ROUTE = (bucket: string) => \\`${OBJECTS_ROUTE_PREFIX}\\${bucket}\\`;\n\n// The buckets whose events this server relays: one route each, however many\n// subscribers watch the bucket.\nconst relays = new Set<string>();\n\n/**\n * Mount the route a local object store posts one bucket's events to, and\n * relay each event onto the broker under the bucket's name.\n *\n * Answered 2xx only once every event is published: the store keeps what it\n * was not told it delivered, and sends it again.\n */\nasync function mountObjectRelay(\n app: { post: (path: string, handler: (c: any) => unknown) => unknown },\n relay: { bucket: string; topic: string; connection: EventConnection; tokenKey: string },\n logger: Logger,\n): Promise<void> {\n const token = process.env[relay.tokenKey];\n if (!token) {\n logger.error(\n { bucket: relay.bucket, tokenKey: relay.tokenKey },\n 'No token for this bucket: the events its object store posts cannot be received',\n );\n failed.push(\\`\\${relay.bucket}#events\\`);\n return;\n }\n const { toObjectEvents } = await import('@geekmidas/storage/events');\n const publisher = await Publisher.fromConnection(relay.connection, { topic: relay.topic });\n const expected = Buffer.from(\\`Bearer \\${token}\\`);\n\n app.post(OBJECTS_ROUTE(relay.bucket), async (c: any) => {\n // Compared in constant time: the route is not public, but it is the one\n // way to put an event in front of every subscriber of the bucket.\n const given = Buffer.from(c.req.header('authorization') ?? '');\n if (given.length !== expected.length || !timingSafeEqual(given, expected)) {\n return c.json({ status: 'refused' }, 401);\n }\n\n let messages: Awaited<ReturnType<typeof toObjectEvents>>;\n try {\n messages = toObjectEvents(JSON.parse(await c.req.text()));\n } catch (error) {\n logger.warn({ err: error, bucket: relay.bucket }, 'Refused an object notification that did not parse');\n return c.json({ status: 'malformed' }, 400);\n }\n\n try {\n if (messages.length > 0) await publisher.publish(messages as any);\n } catch (error) {\n // The store sends it again.\n logger.error({ err: error, bucket: relay.bucket }, 'Failed to relay object events');\n return c.json({ status: 'failed' }, 500);\n }\n return c.json({ status: 'ok', relayed: messages.length }, 200);\n });\n logger.info({ bucket: relay.bucket }, 'Relaying object events');\n}\n\n${\n\treceives\n\t\t? `// The inboxes this server receives for locally, by id.\nconst inboxRelays = new Map<string, ReceivingInbox>();\n\n/**\n * Mount the route Mailpit posts each message it receives to, and hand the\n * message to the receiver a receipt rule stands for: each inbox one of its\n * envelope recipients is addressed to gets the receipt notification on its\n * topic. Mailpit names envelope recipients missing from the headers as Bcc.\n */\nfunction mountInboxRelay(\n app: { post: (path: string, handler: (c: any) => unknown) => unknown },\n logger: Logger,\n): void {\n const token = process.env.${INBOX_RELAY_TOKEN_KEY};\n if (!token) {\n logger.error('No ${INBOX_RELAY_TOKEN_KEY}: the mail Mailpit posts cannot be received');\n failed.push('inbox');\n return;\n }\n const expected = Buffer.from(token);\n\n app.post('${INBOX_ROUTE}', async (c: any) => {\n const given = Buffer.from(c.req.query('token') ?? '');\n if (given.length !== expected.length || !timingSafeEqual(given, expected)) {\n return c.json({ status: 'refused' }, 401);\n }\n\n let message: { key: string; from: string; recipients: string[] };\n try {\n const summary = JSON.parse(await c.req.text());\n const addresses = (list: unknown) =>\n Array.isArray(list) ? list.map((a: any) => a?.Address).filter(Boolean) : [];\n message = {\n key: String(summary.ID),\n from: summary.From?.Address ?? '',\n recipients: [...addresses(summary.To), ...addresses(summary.Cc), ...addresses(summary.Bcc)],\n };\n } catch (error) {\n logger.warn({ err: error }, 'Refused a Mailpit webhook that did not parse');\n return c.json({ status: 'malformed' }, 400);\n }\n\n try {\n const received = await receiveMail(\n { ...message, store: 'mailpit' },\n [...inboxRelays.values()],\n );\n return c.json({ status: 'ok', received }, 200);\n } catch (error) {\n logger.error({ err: error, message: message.key }, 'Failed to receive mail');\n return c.json({ status: 'failed' }, 500);\n }\n });\n logger.info({ inboxes: [...inboxRelays.keys()] }, 'Receiving mail from Mailpit');\n}\n\n`\n\t\t: ''\n}/** Resolves once something is accepting connections on the port. */\nasync function listening(port: number): Promise<void> {\n for (let attempt = 0; attempt < 100; attempt++) {\n const open = await new Promise<boolean>((resolve) => {\n const socket = connect(port, '127.0.0.1');\n socket.once('connect', () => { socket.end(); resolve(true); });\n socket.once('error', () => resolve(false));\n });\n if (open) return;\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n}\n\n/**\n * Mount each pushed subscriber's route and start each polled one. Returns what\n * to run once the server is listening: subscribing a route makes SNS send its\n * confirmation at once, so the route has to be reachable first.\n */\nexport async function setupSubscribers(\n app: { post: (path: string, handler: (c: any) => unknown) => unknown },\n envParser: EnvironmentParser<any>,\n logger: Logger,\n): Promise<(port: number) => Promise<void>> {\n if (process.env.GKM_SUBSCRIBERS === 'off') {\n logger.info('Subscribers are off (--no-subscribers)');\n return async () => {};\n }\n\n const serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n const recorded = recordedSubscriptions(logger);\n const afterListening: ((port: number) => Promise<void>)[] = [];\n\n for (const { id, subscriber, topic, connectionKey, filtered, bucket, tokenKey, inbox } of subscribers) {\n const events = subscriber.subscribedEvents || [];\n if (events.length === 0) {\n logger.warn({ subscriber: id }, 'Subscriber has no subscribed events, skipping');\n continue;\n }\n const connectionString = connectionKey ? process.env[connectionKey] : undefined;\n if (!connectionString) {\n logger.error(\n { subscriber: id, connectionKey },\n 'No connection string for the topic or bucket this subscriber is bound to',\n );\n failed.push(id);\n continue;\n }\n\n try {\n${\n\tpush\n\t\t? ` if (connectionString.startsWith('sns:')) {\n const { SNSConnection, snsUrl, subscribeHttpEndpoint, confirmSubscription } = await import('@geekmidas/events/sns');\n const { SnsPushSubscriberAdaptor } = await import('@geekmidas/constructs/subscribers');\n const address = snsUrl.parse(connectionString);\n const route = SUBSCRIBER_ROUTE(id);\n const mount = (adaptor: InstanceType<typeof SnsPushSubscriberAdaptor>) =>\n app.post(route, async (c: any) => {\n const body = JSON.parse(await c.req.text());\n const response = await adaptor.handle(body, {\n subscriptionArn: c.req.header('x-amz-sns-subscription-arn'),\n });\n return c.json(response.body, response.status);\n });\n\n if (!address.endpoint) {\n // SNS itself: the deploy subscribed this route and recorded the ARN.\n // Nothing is subscribed from here, so this server's credentials need\n // only sns:ConfirmSubscription on the topic.\n const subscriptionArn = recorded[id];\n if (!subscriptionArn) {\n logger.error(\n { subscriber: id },\n 'No subscription recorded for this subscriber in ${SNS_SUBSCRIPTIONS_KEY}: deploy it so SNS has a route to push to',\n );\n failed.push(id);\n continue;\n }\n const connection = await SNSConnection.fromConnectionString(connectionString);\n mount(\n new SnsPushSubscriberAdaptor(envParser, subscriber, {\n topicArn: address.topicArn,\n verify: true,\n subscriptionArn,\n // As the topic's owner, so only the owner can unsubscribe the\n // route — not whoever holds a notification's UnsubscribeURL.\n confirm: (message) => confirmSubscription(connection, message),\n }),\n );\n logger.info({ subscriber: id, events }, 'Subscriber mounted for push');\n continue;\n }\n\n // An emulator signs nothing, and nothing deploys its subscriptions:\n // decided by the address this server was configured with, never by\n // anything a request says about itself.\n mount(\n new SnsPushSubscriberAdaptor(envParser, subscriber, {\n topicArn: address.topicArn,\n verify: false,\n emulatorEndpoint: address.endpoint,\n }),\n );\n\n afterListening.push(async (port) => {\n const base =\n process.env.GKM_SUBSCRIBER_PUSH_URL ?? \\`http://host.docker.internal:\\${port}\\`;\n const connection = await SNSConnection.fromConnectionString(connectionString);\n await subscribeHttpEndpoint(connection, {\n endpoint: new URL(route, base).toString(),\n ...(filtered ? { events } : {}),\n });\n logger.info({ subscriber: id, events }, 'Subscriber subscribed for push');\n });\n continue;\n }\n`\n\t\t: ` if (connectionString.startsWith('sns:')) {\n // Built for a broker other than SNS, so this entry registered no SNS\n // driver and has no push route to offer.\n logger.error(\n { subscriber: id, connectionKey },\n 'This build has no SNS driver: it was built for a target whose broker is not SNS',\n );\n failed.push(id);\n continue;\n }\n`\n}\n\n let connection = connections.get(connectionString);\n if (!connection) {\n connection = await EventConnectionFactory.fromConnectionString(connectionString);\n connections.set(connectionString, connection);\n }\n // Named, so a broker with one address for everything (pg-boss) gives\n // this subscriber a queue of its own: fan-out, not competition.\n const eventSubscriber = await Subscriber.fromConnection(connection, {\n topic,\n subscription: id,\n });\n const services = subscriber.services.length > 0\n ? await serviceDiscovery.register(subscriber.services)\n : {};\n // The subscriber's database — the worker's, or its own — as \\`db\\`. A\n // pushed subscriber gets it from the adaptor above instead.\n const db = subscriber.databaseService\n ? (await serviceDiscovery.register([subscriber.databaseService]))[\n subscriber.databaseService.serviceName\n ]\n : undefined;\n\n await eventSubscriber.subscribe(events, async (event) => {\n try {\n await subscriber.handler({\n events: [event],\n services: services as any,\n logger: subscriber.logger,\n db,\n } as any);\n } catch (error) {\n logger.error({ err: error, event, subscriber: id }, 'Failed to process event');\n // Rethrown so the transport keeps the event for a retry — as a queue\n // consumer's failure does, and as a pushed subscriber's 500 does.\n throw error;\n }\n });\n logger.info({ subscriber: id, events }, 'Subscriber started polling');\n\n // A bucket in a local object store publishes nothing for this to poll:\n // the store posts its events here, and they are relayed onto the broker.\n if (bucket && tokenKey && topic && !relays.has(bucket)) {\n relays.add(bucket);\n await mountObjectRelay(app, { bucket, topic, connection, tokenKey }, logger);\n }${\n\t\t\t\treceives\n\t\t\t\t\t? `\n // An inbox polled here is a local one: Mailpit posts what it receives\n // to this server, which announces it on the inbox's topic.\n const domain = inbox ? process.env[inbox.domainKey] : undefined;\n if (inbox && topic && domain && !inboxRelays.has(inbox.id)) {\n const publisher = await Publisher.fromConnection(connection, { topic });\n inboxRelays.set(inbox.id, {\n id: inbox.id,\n addressing: inbox.addressing,\n domain,\n publish: async (payload) => {\n await publisher.publish([{ type: '${INBOX_EVENT}', payload }] as any);\n },\n });\n }`\n\t\t\t\t\t: ''\n\t\t\t}\n } catch (error) {\n // The message too: a missing module's code alone does not say which.\n logger.error(\n { err: error, subscriber: id },\n 'Failed to set up subscriber',\n );\n failed.push(id);\n }\n }\n\n${receives ? ' if (inboxRelays.size > 0) mountInboxRelay(app, logger);\\n\\n' : ''} return async (port) => {\n if (afterListening.length === 0) return;\n await listening(port);\n for (const subscribe of afterListening) {\n await subscribe(port).catch((error) => {\n logger.error({ err: error }, 'Failed to subscribe for push');\n });\n }\n };\n}\n\n/** The subscribers that could not start, and the connections that did. */\nexport function subscribersStatus(): { failed: string[]; connections: EventConnection[] } {\n return { failed: [...failed], connections: [...connections.values()] };\n}\n\n/**\n * Stop polling, let the events in flight finish, and close each broker\n * connection — pg-boss's graceful stop does all three. The caller bounds it.\n */\nexport async function stopSubscribers(): Promise<void> {\n const open = [...connections.values()];\n connections.clear();\n await Promise.all(open.map((connection) => connection.close()));\n}\n`;\n\n\t\tawait writeFile(subscribersPath, content);\n\t\treturn subscribersPath;\n\t}\n}\n\n/**\n * A bucket's subscriber that writes back into the keys it watches.\n *\n * Every write it makes is a new object event, which runs it again — forever,\n * and billed per run. The rule is the one the build can check: a subscriber\n * that depends on the bucket it watches must watch a prefix, so what it writes\n * can go elsewhere. A thumbnailer watching `uploads/` writes `thumbnails/`.\n */\nexport class ObjectSubscriberFeedsItself extends Error {\n\tconstructor(\n\t\treadonly subscriber: string,\n\t\treadonly bucket: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${subscriber}' watches every key in '${bucket}' and depends on it, ` +\n\t\t\t\t`so each object it writes runs it again. Watch a prefix — ` +\n\t\t\t\t`.on([...], { prefix: 'uploads/' }) — and write outside it.`,\n\t\t);\n\t\tthis.name = 'ObjectSubscriberFeedsItself';\n\t}\n}\n\nfunction assertDoesNotFeedItself(\n\tkey: string,\n\tconstruct: Subscriber<any, any, any, any, any, any, any>,\n): void {\n\tconst bucket = construct.bucketName;\n\tif (!bucket || construct.objectFilter?.prefix) return;\n\tconst depends = (construct.constructs ?? []).some(\n\t\t(id: string) => canonicalId(id) === canonicalId(bucket),\n\t);\n\tif (depends) throw new ObjectSubscriberFeedsItself(key, bucket);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,cAAc;;AAG3B,MAAa,wBAAwB;;;;;AAMrC,IAAa,8BAAb,cAAiD,SAAS;CACpC;CAArB,YAAY,SAAqC;EAChD,MACC,4BAA4B,QAAQ,KAAK,MAAM,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,OAAO,EAAE,uJAIxE;EANoB,KAAA,UAAA;EAOpB,KAAK,OAAO;CACb;AACD;;;;;AAMA,SAAgB,iBACf,UACA,aACqB;CACrB,MAAM,4BAAY,IAAI,IAAY;CAClC,KAAK,MAAM,eAAe,OAAO,OAAO,QAAQ,GAAG;EAClD,IAAI,YAAY,SAAS,SAAS;EAClC,UAAU,IACT,eAAe,YAAY,OAAO,SAAS,2BAA2B,CACvE;CACD;CACA,IAAI,UAAU,SAAS,GAAG,OAAO,KAAA;CAEjC,MAAM,UAAU,OAAO,KAAK,WAAW,CAAC,CACtC,KAAK,CAAC,CACN,QAAQ,YACP,YAAY,WAAW,CAAC,EAAA,CAAG,MAAM,EAAE,oBACnC,UAAU,IAAI,aAAa,CAC5B,CACD;CACD,IAAI,QAAQ,SAAS,GAAG,MAAM,IAAI,4BAA4B,OAAO;CACrE,OAAO,QAAQ;AAChB;;;;;;;AAQA,SAAgB,gBAAgB,SAAiB,MAAuB;CACvE,OAAO,WAAW,QAAQ,CAAC,CACzB,OAAO,GAAG,OAAO,GAAG,KAAK,KAAK,KAAK,QAAQ,eAAe,CAAC,CAC3D,OAAO,WAAW,CAAC,CACnB,MAAM,GAAG,EAAE;AACd;;AAGA,SAAgB,gBAAgB,MAAc,OAAuB;CACpE,OAAO,GAAG,KAAK,QAAQ,QAAQ,EAAE,IAAI,YAAY,SAAS,mBAAmB,KAAK;AACnF;;;;;;;;;;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uBAE7B,sBAAsB;;;;;;cAM/B,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAoCtB,GACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAkDA,OACG;;;;;;;;;;;;;;;;;;;;;;iEAsB6D,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA4CnF;;;;;;;;;;EAWH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SA+CG,WACG;;;;;;;;;;;gDAWyC,YAAY;;;WAIrD,GACH;;;;;;;;;;;EAWF,WAAW,kEAAkE,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;EA2BhF,MAAM,UAAU,iBAAiB,OAAO;EACxC,OAAO;CACR;AACD;;;;;;;;;AAUA,IAAa,8BAAb,cAAiD,MAAM;CAE5C;CACA;CAFV,YACC,YACA,QACC;EACD,MACC,IAAI,WAAW,0BAA0B,OAAO,yIAGjD;EAPS,KAAA,aAAA;EACA,KAAA,SAAA;EAOT,KAAK,OAAO;CACb;AACD;AAEA,SAAS,wBACR,KACA,WACO;CACP,MAAM,SAAS,UAAU;CACzB,IAAI,CAAC,UAAU,UAAU,cAAc,QAAQ;CAI/C,KAHiB,UAAU,cAAc,CAAC,EAAA,CAAG,MAC3C,OAAe,YAAY,EAAE,MAAM,YAAY,MAAM,CAE7C,GAAG,MAAM,IAAI,4BAA4B,KAAK,MAAM;AAC/D"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"SubscriberGenerator-DMi4siph.cjs","names":["GkmError","providedKeyFor","createHash","join","GkmError","kebabCase","access","pathToFileURL","ConstructGenerator","Subscriber","join","mkdir","relative","dirname","runtimeFor","writeFile","subscriberConnectionKey","subscriberTokenKey","canonicalId","providedKeyFor","INBOX_EVENT"],"sources":["../src/reconcile/inboxRelay.ts","../src/generators/subscriberRoute.ts","../src/reconcile/fakes.ts","../src/generators/SubscriberGenerator.ts"],"sourcesContent":["/**\n * Receiving mail locally: Mailpit's webhook, and the worker it posts to.\n *\n * Deployed, SES stores each message and publishes its receipt notification on\n * the inbox's topic. Locally Mailpit receives it, and its webhook posts each\n * message to one route — `POST /__gkm/inbox` on the worker that runs the\n * inbox subscribers — which hands it to the same receiver `mailbox.receive`\n * calls in a feature test (`receiveMail` in `@geekmidas/constructs/inbox`).\n *\n * Shared by every local stage and the local compose stack: each asks this\n * module which worker relays and with what token, and supplies only how that\n * worker is reached from its Mailpit — the host's gateway, or the stack's\n * network.\n */\n\nimport { createHash } from 'node:crypto';\nimport { type ConstructManifest, providedKeyFor } from '@geekmidas/manifest';\nimport { GkmError } from '../errors';\nimport type { BoundSubscriber } from './discover';\n\n/** The route Mailpit posts each message it receives to. */\nexport const INBOX_ROUTE = '/__gkm/inbox';\n\n/** The env key the relaying worker reads its token from. */\nexport const INBOX_RELAY_TOKEN_KEY = 'GKM_INBOX_RELAY_TOKEN';\n\n/**\n * Inbox subscribers in more than one worker. Mailpit posts to one webhook, so\n * locally one worker receives for every inbox — #343 lifts this.\n */\nexport class InboxSubscribersSpanWorkers extends GkmError {\n\tconstructor(readonly workers: readonly string[]) {\n\t\tsuper(\n\t\t\t`Inbox subscribers run in ${workers.map((w) => `'${w}'`).join(' and ')}, ` +\n\t\t\t\t`and locally mail is received by one worker: Mailpit posts each ` +\n\t\t\t\t`message to a single webhook. Bind every worker.inbox(…) to one ` +\n\t\t\t\t`worker for now (#343).`,\n\t\t);\n\t\tthis.name = 'InboxSubscribersSpanWorkers';\n\t}\n}\n\n/**\n * The worker whose route Mailpit posts to: the one that runs every inbox\n * subscriber. `undefined` when no inbox has a subscriber.\n */\nexport function inboxRelayWorker(\n\tmanifest: ConstructManifest,\n\tsubscribers: Readonly<Record<string, readonly BoundSubscriber[]>>,\n): string | undefined {\n\tconst topicKeys = new Set<string>();\n\tfor (const declaration of Object.values(manifest)) {\n\t\tif (declaration.kind !== 'inbox') continue;\n\t\ttopicKeys.add(\n\t\t\tprovidedKeyFor(declaration.topic, 'topic', 'publisherConnectionString'),\n\t\t);\n\t}\n\tif (topicKeys.size === 0) return undefined;\n\n\tconst workers = Object.keys(subscribers)\n\t\t.sort()\n\t\t.filter((worker) =>\n\t\t\t(subscribers[worker] ?? []).some(({ connectionKey }) =>\n\t\t\t\ttopicKeys.has(connectionKey),\n\t\t\t),\n\t\t);\n\tif (workers.length > 1) throw new InboxSubscribersSpanWorkers(workers);\n\treturn workers[0];\n}\n\n/**\n * The token Mailpit presents in the webhook's query — it cannot send a\n * header. Derived as a bucket's webhook token is: from the stage's seed where\n * one is given, and the project; not salted by the stage, since `gkm dev` and\n * `gkm test` share one Mailpit.\n */\nexport function inboxRelayToken(project: string, seed?: string): string {\n\treturn createHash('sha256')\n\t\t.update(`${seed ? `${seed}:` : ''}${project}:inbox-webhook`)\n\t\t.digest('base64url')\n\t\t.slice(0, 32);\n}\n\n/** Mailpit's `MP_WEBHOOK_URL`: the relay route at `base`, with the token. */\nexport function inboxWebhookUrl(base: string, token: string): string {\n\treturn `${base.replace(/\\/+$/, '')}${INBOX_ROUTE}?token=${encodeURIComponent(token)}`;\n}\n","/**\n * Where SNS pushes a topic subscriber's messages, on the server that runs it:\n * named after the subscriber's export.\n *\n * One definition for both sides — the generated server mounts the route, and\n * the stack exposes exactly these paths on a worker's host — so the path the\n * edge lets through and the path the worker answers cannot drift.\n */\nexport const SUBSCRIBER_ROUTE_PREFIX = '/__gkm/subscribers/';\n\n/** The route a subscriber's pushes arrive on. */\nexport function subscriberRoute(exportName: string): string {\n\treturn `${SUBSCRIBER_ROUTE_PREFIX}${exportName}`;\n}\n\n/**\n * Where the deploy hands a server the SNS subscriptions it made for its\n * routes: a JSON object of subscriber export → subscription ARN. Against SNS\n * itself a server mounts a route only for a subscription recorded here, and\n * refuses a notification that names another.\n */\nexport const SNS_SUBSCRIPTIONS_KEY = 'GKM_SNS_SUBSCRIPTIONS';\n\n/**\n * Where a local object store posts a bucket's events, on the process that runs\n * the bucket's subscribers: named after the bucket. Never on a public host —\n * MinIO reaches it over the stack's network, or the host's.\n */\nexport const OBJECTS_ROUTE_PREFIX = '/__gkm/objects/';\n\n/** The route a bucket's events are posted to. */\nexport function objectsRoute(bucketId: string): string {\n\treturn `${OBJECTS_ROUTE_PREFIX}${bucketId}`;\n}\n","/**\n * Fakes, read from where the convention puts them.\n *\n * `test/fakes/<id>.ts` default-exports `fake.app(…)` or `fake.image(…)` for an\n * external API, and `fake.credential(…)` for a credential. The construct never\n * names it — that is what keeps a fake out of a deployed bundle — so this is\n * the one place it is found, by the same rule that finds a database's factory\n * in `test/factories/<id>.ts`.\n */\n\nimport { access } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport type { ConstructManifest } from '@geekmidas/manifest';\nimport { kebabCase } from '@geekmidas/manifest';\nimport { GkmError } from '../errors';\nimport type { Plan } from './plan';\n\n/** Where a project keeps its external APIs' fakes, relative to its root. */\nexport const DEFAULT_FAKES_DIR = 'test/fakes';\n\n/** One external API's fake, as the local target needs it. */\nexport interface LocalFake {\n\t/** The file it was read from — what the harness and `gkm dev` import. */\n\tfile: string;\n\t/** The image to run, for a fake the provider publishes. */\n\timage?: string;\n\t/** The port that image listens on inside its container. */\n\tport?: number;\n\t/** What the fake accepts, as the JSON `<ID>_CREDENTIALS` holds. */\n\tcredentials: string;\n}\n\n/** The marker `fake.app` and `fake.image` set — the same registered symbol. */\nconst FAKE = Symbol.for('@geekmidas/constructs/fake');\n\ninterface FakeExport {\n\tkind: 'app' | 'image' | 'credential';\n\timage?: string;\n\tport?: number;\n\tcredentials: unknown;\n}\n\n/**\n * The fake for every external API the manifest declares, keyed by id.\n *\n * @throws {NoFake} when an external API has no file, since a local stage would\n * otherwise have nothing to call.\n * @throws {NotAFake} when the file's default export is not one.\n */\nexport async function readFakes(\n\troot: string,\n\tmanifest: ConstructManifest,\n): Promise<Record<string, LocalFake>> {\n\tconst fakes: Record<string, LocalFake> = {};\n\n\tfor (const [id, declaration] of Object.entries(manifest)) {\n\t\tif (declaration?.kind !== 'external-api') continue;\n\n\t\tconst file = await fakeFile(join(root, DEFAULT_FAKES_DIR), id);\n\t\tif (!file) throw new NoFake(id, `${fakeBase(root, id)}.ts`);\n\t\tconst value = await importFake(file);\n\t\tif (value.kind === 'credential') throw new NotAFake(file);\n\n\t\tfakes[id] = {\n\t\t\tfile,\n\t\t\t...(value.kind === 'image'\n\t\t\t\t? { image: value.image, port: value.port }\n\t\t\t\t: {}),\n\t\t\tcredentials: JSON.stringify(value.credentials),\n\t\t};\n\t}\n\n\treturn fakes;\n}\n\n/**\n * Each credential's fake value, as the JSON `<ID>_CREDENTIALS` holds, keyed by\n * id — for the credentials that have a fake. Unlike an external API's, a\n * credential's fake is optional here: a stage that stores the real value\n * needs none. The test stage's own check (`assertTestCredentials`) is what\n * refuses one with neither.\n *\n * @throws {NotAFake} when the file's default export is not a credential's fake.\n */\nexport async function readCredentialFakes(\n\troot: string,\n\tmanifest: ConstructManifest,\n): Promise<Record<string, string>> {\n\tconst values: Record<string, string> = {};\n\n\tfor (const [id, declaration] of Object.entries(manifest)) {\n\t\tif (declaration?.kind !== 'credential') continue;\n\n\t\tconst file = await fakeFile(join(root, DEFAULT_FAKES_DIR), id);\n\t\tif (!file) continue;\n\t\tconst value = await importFake(file);\n\t\tif (value.kind !== 'credential') throw new NotAFake(file);\n\n\t\tvalues[id] = JSON.stringify(value.credentials);\n\t}\n\n\treturn values;\n}\n\n/**\n * A credential the test stage has no value for: no fake, and nothing stored.\n * Raised when the stage is set up, before a test reaches it — not as a schema\n * error inside the handler that first asked.\n */\nexport class CredentialHasNoTestValue extends GkmError {\n\tconstructor(\n\t\treadonly id: string,\n\t\treadonly key: string,\n\t\treadonly file: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${id}' is a credential, and the test stage has no value for ${key}: ` +\n\t\t\t\t`no fake, and none stored — a stage set up fresh, as CI's ` +\n\t\t\t\t`auto-setup does, holds no third party's credentials. Give it a ` +\n\t\t\t\t`fake: create ${file}, default-exporting ` +\n\t\t\t\t`fake.credential(…) from @geekmidas/constructs/credential. It is ` +\n\t\t\t\t`read only by gkm test and gkm dev --fake; a deployed stage still ` +\n\t\t\t\t`needs the real value (gkm secrets:add --stage <stage>).`,\n\t\t);\n\t\tthis.name = 'CredentialHasNoTestValue';\n\t}\n}\n\n/**\n * Every credential the test stage must hand its suite, with the value it\n * resolved — a fake's, or one the stage stores.\n *\n * @throws {CredentialHasNoTestValue} for the first one with neither.\n */\nexport function assertTestCredentials(\n\troot: string,\n\tplan: Pick<Plan, 'resources'>,\n\tenv: Readonly<Record<string, string | undefined>>,\n): Record<string, string> {\n\tconst values: Record<string, string> = {};\n\n\tfor (const { id, kind, envKey } of plan.resources) {\n\t\tif (kind !== 'credential') continue;\n\n\t\tconst value = env[envKey];\n\t\tif (value === undefined) {\n\t\t\tthrow new CredentialHasNoTestValue(\n\t\t\t\tid,\n\t\t\t\tenvKey,\n\t\t\t\t`${fakeBase(root, id)}.ts`,\n\t\t\t);\n\t\t}\n\t\tvalues[envKey] = value;\n\t}\n\n\treturn values;\n}\n\n/** `<root>/test/fakes/<id>`, without an extension. */\nfunction fakeBase(root: string, id: string): string {\n\treturn join(root, DEFAULT_FAKES_DIR, kebabCase(id));\n}\n\n/** The first of `<id>.ts`, `.mts`, `.js`, `.mjs` that exists. */\nasync function fakeFile(\n\tfolder: string,\n\tid: string,\n): Promise<string | undefined> {\n\tconst base = join(folder, kebabCase(id));\n\tfor (const extension of ['.ts', '.mts', '.js', '.mjs']) {\n\t\tconst file = `${base}${extension}`;\n\t\tconst exists = await access(file).then(\n\t\t\t() => true,\n\t\t\t() => false,\n\t\t);\n\t\tif (exists) return file;\n\t}\n\n\treturn undefined;\n}\n\n/**\n * A fake file's default export.\n *\n * @throws {NotAFake} when it is not a fake.\n */\nasync function importFake(file: string): Promise<FakeExport> {\n\tconst module = (await import(pathToFileURL(file).href)) as {\n\t\tdefault?: unknown;\n\t};\n\tconst value = module.default;\n\tif (!isFakeExport(value)) throw new NotAFake(file);\n\treturn value;\n}\n\nfunction isFakeExport(value: unknown): value is FakeExport {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t(value as { [FAKE]?: unknown })[FAKE] === true\n\t);\n}\n\n/** An external API with no fake for a local stage to call. */\nexport class NoFake extends GkmError {\n\tconstructor(\n\t\treadonly id: string,\n\t\treadonly file: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${id}' is an external API, and a local stage calls its fake rather ` +\n\t\t\t\t`than the provider — but there is none. Create ${file}, ` +\n\t\t\t\t`default-exporting fake.app(…) or fake.image(…) from ` +\n\t\t\t\t`@geekmidas/constructs/external-api.`,\n\t\t);\n\t\tthis.name = 'NoFake';\n\t}\n}\n\n/** A file in the fakes folder whose default export is not a fake. */\nexport class NotAFake extends GkmError {\n\tconstructor(readonly file: string) {\n\t\tsuper(\n\t\t\t`${file} is where a fake lives, and its default export is not one ` +\n\t\t\t\t`for its construct. For an external API, export default ` +\n\t\t\t\t`fake.app(handler, { credentials }) or ` +\n\t\t\t\t`fake.image(image, { port, credentials }); for a credential, ` +\n\t\t\t\t`fake.credential(value).`,\n\t\t);\n\t\tthis.name = 'NotAFake';\n\t}\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Subscriber } from '@geekmidas/constructs/subscribers';\nimport { canonicalId, INBOX_EVENT, providedKeyFor } from '@geekmidas/manifest';\nimport type { BuildContext } from '../build/types';\nimport {\n\tsubscriberConnectionKey,\n\tsubscriberTokenKey,\n} from '../reconcile/edges.js';\nimport { INBOX_RELAY_TOKEN_KEY, INBOX_ROUTE } from '../reconcile/inboxRelay';\nimport type { SubscriberInfo } from '../types';\nimport { runtimeFor } from './EndpointGenerator.js';\nimport {\n\tConstructGenerator,\n\ttype GeneratedConstruct,\n\ttype GeneratorOptions,\n} from './Generator';\nimport {\n\tOBJECTS_ROUTE_PREFIX,\n\tSNS_SUBSCRIPTIONS_KEY,\n\tSUBSCRIBER_ROUTE_PREFIX,\n} from './subscriberRoute.js';\n\nexport class SubscriberGenerator extends ConstructGenerator<\n\tSubscriber<any, any, any, any, any, any, any>,\n\tSubscriberInfo[]\n> {\n\tisConstruct(\n\t\tvalue: any,\n\t): value is Subscriber<any, any, any, any, any, any, any> {\n\t\treturn Subscriber.isSubscriber(value);\n\t}\n\n\tasync build(\n\t\tcontext: BuildContext,\n\t\tconstructs: GeneratedConstruct<\n\t\t\tSubscriber<any, any, any, any, any, any, any>\n\t\t>[],\n\t\toutputDir: string,\n\t\toptions?: GeneratorOptions,\n\t): Promise<SubscriberInfo[]> {\n\t\tconst target = options?.target ?? 'aws';\n\t\tconst logger = console;\n\t\tconst subscriberInfos: SubscriberInfo[] = [];\n\n\t\tfor (const { key, construct } of constructs) {\n\t\t\tassertDoesNotFeedItself(key, construct);\n\t\t}\n\n\t\tif (target === 'server') {\n\t\t\t// Generate subscribers.ts for server-based polling (even if empty).\n\t\t\t// A bucket's subscriber is pushed to by the topic the storage\n\t\t\t// publishes to, whatever broker carries the app's own events.\n\t\t\tawait this.generateServerSubscribersFile(\n\t\t\t\toutputDir,\n\t\t\t\tconstructs,\n\t\t\t\t(context.eventsBackends?.includes('sns') ?? false) ||\n\t\t\t\t\tconstructs.some(({ construct }) => construct.bucketName),\n\t\t\t);\n\n\t\t\tlogger.log(\n\t\t\t\t`Generated server subscribers file with ${constructs.length} subscribers (polling mode)`,\n\t\t\t);\n\n\t\t\t// Return empty array as server subscribers don't have individual handlers\n\t\t\treturn subscriberInfos;\n\t\t}\n\n\t\tif (constructs.length === 0) {\n\t\t\treturn subscriberInfos;\n\t\t}\n\n\t\t// Create subscribers subdirectory\n\t\tconst subscribersDir = join(outputDir, 'subscribers');\n\t\tawait mkdir(subscribersDir, { recursive: true });\n\n\t\t// Generate subscriber handlers\n\t\tfor (const { key, construct, path } of constructs) {\n\t\t\tconst handlerFile = await this.generateSubscriberHandler(\n\t\t\t\tsubscribersDir,\n\t\t\t\tpath.relative,\n\t\t\t\tkey,\n\t\t\t\tconstruct,\n\t\t\t\tcontext,\n\t\t\t\tconstruct.owner,\n\t\t\t);\n\n\t\t\tsubscriberInfos.push({\n\t\t\t\tname: key,\n\t\t\t\thandler: relative(options?.root ?? process.cwd(), handlerFile).replace(\n\t\t\t\t\t/\\.ts$/,\n\t\t\t\t\t'.handler',\n\t\t\t\t),\n\t\t\t\tsubscribedEvents: construct.subscribedEvents || [],\n\t\t\t\t// A subscriber bound to a topic (via `s.topic(topic)`) records the\n\t\t\t\t// binding so infra wires the SNS subscription.\n\t\t\t\t...(construct.topicName\n\t\t\t\t\t? { transport: 'topic' as const, topic: construct.topicName }\n\t\t\t\t\t: {}),\n\t\t\t\t// A subscriber bound to a bucket records it, and the keys it\n\t\t\t\t// watches, so infra wires the bucket's notifications.\n\t\t\t\t...(construct.bucketName\n\t\t\t\t\t? {\n\t\t\t\t\t\t\ttransport: 'topic' as const,\n\t\t\t\t\t\t\tbucket: construct.bucketName,\n\t\t\t\t\t\t\t...construct.objectFilter,\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t// An inbox's subscriber is a topic subscriber, delivered what SES\n\t\t\t\t// publishes rather than what a producer wrote.\n\t\t\t\t...(construct.inboxName ? { inbox: construct.inboxName } : {}),\n\t\t\t\ttimeout: construct.timeout,\n\t\t\t\tmemorySize: construct.memorySize,\n\t\t\t\tenvironment: await construct.getEnvironment({\n\t\t\t\t\tmarkOptional: context.markOptional,\n\t\t\t\t}),\n\t\t\t\tdependencies: construct.constructs,\n\t\t\t});\n\n\t\t\tlogger.log(`Generated subscriber handler: ${key}`);\n\t\t}\n\n\t\treturn subscriberInfos;\n\t}\n\n\tprivate async generateSubscriberHandler(\n\t\toutputDir: string,\n\t\tsourceFile: string,\n\t\texportName: string,\n\t\t_subscriber: Subscriber<any, any, any, any, any, any, any>,\n\t\tcontext: BuildContext,\n\t\t/** The construct that owns this — its worker, or its surface. */\n\t\towner: string | undefined,\n\t): Promise<string> {\n\t\tconst handlerFileName = `${exportName}.ts`;\n\t\tconst handlerPath = join(outputDir, handlerFileName);\n\n\t\tconst relativePath = relative(dirname(handlerPath), sourceFile);\n\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\t// Imports the construct that owns this, and binds `envParser` and\n\t\t// `logger` off it — the objects it was declared with, rather than a\n\t\t// module path printed in from config.\n\t\tconst runtime = runtimeFor(context, dirname(handlerPath), owner);\n\n\t\tconst content = `import { AWSLambdaSubscriber } from '@geekmidas/constructs/aws';\nimport { ${exportName} } from '${importPath}';\n${runtime.imports}\n${context.storageDrivers?.imports ?? ''}\n${runtime.bindings}\n${context.storageDrivers?.setup ? `\\n// The handler registers the drivers its target needs.\\n${context.storageDrivers.setup}\\n` : ''}\nconst adapter = new AWSLambdaSubscriber(envParser, ${exportName});\n\nexport const handler = adapter.handler;\n`;\n\n\t\tawait writeFile(handlerPath, content);\n\t\treturn handlerPath;\n\t}\n\n\tprivate async generateServerSubscribersFile(\n\t\toutputDir: string,\n\t\tsubscribers: GeneratedConstruct<\n\t\t\tSubscriber<any, any, any, any, any, any, any>\n\t\t>[],\n\t\t/**\n\t\t * The broker is SNS, so a subscriber is pushed to over HTTP. Only then is\n\t\t * the push code generated: it imports the SNS client, which a bundle for\n\t\t * any other broker must never have to resolve.\n\t\t */\n\t\tpush: boolean,\n\t): Promise<string> {\n\t\tawait mkdir(outputDir, { recursive: true });\n\t\tconst subscribersPath = join(outputDir, 'subscribers.ts');\n\n\t\t// Nothing to run, so nothing to import. Every app gets this file, and\n\t\t// `@geekmidas/events` is only installed by one that declared a Topic or\n\t\t// a Queue — importing it here crashed every dev server that had not.\n\t\tif (subscribers.length === 0) {\n\t\t\tawait writeFile(\n\t\t\t\tsubscribersPath,\n\t\t\t\t`/**\n * Generated subscribers setup — this app declares none.\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\n\nexport async function setupSubscribers(\n _app: unknown,\n _envParser: EnvironmentParser<any>,\n _logger: Logger,\n): Promise<(port: number) => Promise<void>> {\n return async () => {};\n}\n\nexport function subscribersStatus(): { failed: string[]; connections: unknown[] } {\n return { failed: [], connections: [] };\n}\n\nexport async function stopSubscribers(): Promise<void> {}\n`,\n\t\t\t);\n\t\t\treturn subscribersPath;\n\t\t}\n\n\t\tconst importsByFile = new Map<string, string[]>();\n\t\tfor (const { path, key } of subscribers) {\n\t\t\tconst importPath = relative(\n\t\t\t\tdirname(subscribersPath),\n\t\t\t\tpath.relative,\n\t\t\t).replace(/\\.ts$/, '.js');\n\t\t\timportsByFile.set(importPath, [\n\t\t\t\t...(importsByFile.get(importPath) ?? []),\n\t\t\t\tkey,\n\t\t\t]);\n\t\t}\n\t\tconst imports = Array.from(importsByFile.entries())\n\t\t\t.map(\n\t\t\t\t([importPath, exports]) =>\n\t\t\t\t\t`import { ${exports.join(', ')} } from '${importPath}';`,\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\t// Each subscriber reaches the topic it is bound to, by that topic's own\n\t\t// key — resolved here, at build time, from the binding. A bucket's\n\t\t// subscriber reaches the bucket's events, which carry no `type`\n\t\t// attribute for SNS to filter on: it filters what it is sent itself.\n\t\t// So does an inbox's: SES publishes its receipt notification bare.\n\t\tconst entries = subscribers\n\t\t\t.map(({ key, construct }) => {\n\t\t\t\tconst connectionKey = subscriberConnectionKey(construct);\n\t\t\t\tconst tokenKey = subscriberTokenKey(construct);\n\t\t\t\tconst topic = construct.topicName ?? construct.bucketName;\n\t\t\t\tconst bucket = construct.bucketName\n\t\t\t\t\t? canonicalId(construct.bucketName)\n\t\t\t\t\t: undefined;\n\t\t\t\treturn ` { id: '${key}', subscriber: ${key}, topic: ${\n\t\t\t\t\ttopic ? `'${topic}'` : 'undefined'\n\t\t\t\t}, connectionKey: ${\n\t\t\t\t\tconnectionKey ? `'${connectionKey}'` : 'undefined'\n\t\t\t\t}, filtered: ${\n\t\t\t\t\tconstruct.bucketName || construct.inboxName ? 'false' : 'true'\n\t\t\t\t}, bucket: ${\n\t\t\t\t\tbucket ? `'${bucket}'` : 'undefined'\n\t\t\t\t}, tokenKey: ${tokenKey ? `'${tokenKey}'` : 'undefined'}, inbox: ${\n\t\t\t\t\tconstruct.inboxName\n\t\t\t\t\t\t? JSON.stringify({\n\t\t\t\t\t\t\t\tid: construct.inboxName,\n\t\t\t\t\t\t\t\tdomainKey: providedKeyFor(\n\t\t\t\t\t\t\t\t\tconstruct.inboxName,\n\t\t\t\t\t\t\t\t\t'inbox',\n\t\t\t\t\t\t\t\t\t'domain',\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\taddressing: construct.inboxAddressing ?? { addresses: [] },\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t: 'undefined'\n\t\t\t\t} },`;\n\t\t\t})\n\t\t\t.join('\\n');\n\n\t\t// The route Mailpit posts what an inbox receives to — generated only\n\t\t// for an app with an inbox subscriber, so no other bundle ever names\n\t\t// the inbox's module.\n\t\tconst receives = subscribers.some(({ construct }) => construct.inboxName);\n\n\t\tconst content = `/**\n * Generated subscribers setup.\n *\n * Each subscriber is run against the topic it is bound to, through that\n * topic's own connection string:\n *\n * - **sns://** — pushed, not polled. The subscriber gets an HTTP route on this\n * server, subscribed to the topic with a filter policy of the events it\n * named, so SNS fans out to each subscriber. The route runs the subscriber\n * through the same adaptor a Lambda subscription does. Against SNS itself\n * the deploy made the subscription and recorded its ARN in\n * ${SNS_SUBSCRIPTIONS_KEY}: a route is mounted only for a recorded one, its\n * confirmation goes through the API, and nothing is subscribed from here.\n * Against an emulator, where nothing deploys, the route subscribes itself.\n * - **anything else** (pgboss://, rabbitmq://, sqs://) — polled. On pg-boss\n * each subscriber drains a queue of its own, \\`<topic>/<subscriber>\\`, so\n * every subscriber sees every event; replicas of one subscriber share it.\n *\n * A bucket's subscriber is polled the same way, under the bucket's name, when\n * the bucket is in a local object store: the store posts each event to\n * \\`${OBJECTS_ROUTE_PREFIX}<Bucket>\\` on this server, with the bucket's token, and\n * the event is relayed onto the broker as \\`object.created\\` or\n * \\`object.deleted\\` — so every subscriber of the bucket sees it.\n *\n * GKM_SUBSCRIBERS=off (\\`gkm dev --no-subscribers\\`) runs none of them.\n * GKM_SUBSCRIBER_PUSH_URL is the address an emulator pushes to, defaulting to\n * this server through host.docker.internal.\n */\nimport { timingSafeEqual } from 'node:crypto';\nimport { connect } from 'node:net';\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { EventConnectionFactory, Publisher, Subscriber } from '@geekmidas/events';\nimport type { EventConnection } from '@geekmidas/events';\nimport { ServiceDiscovery } from '@geekmidas/services';\n${receives ? \"import { type ReceivingInbox, receiveMail } from '@geekmidas/constructs/inbox';\\n\" : ''}${imports}\n\nconst subscribers = [\n${entries}\n];\n\n// What was opened, and what could not be: a worker's health check reads both,\n// and its shutdown closes what was opened.\nconst connections = new Map<string, EventConnection>();\nconst failed: string[] = [];\n\n/**\n * The subscriptions the deploy made against SNS itself, by subscriber: which\n * routes to mount, and the ARN each one's notifications must name.\n */\nfunction recordedSubscriptions(logger: Logger): Record<string, string> {\n const raw = process.env.${SNS_SUBSCRIPTIONS_KEY};\n if (!raw) return {};\n try {\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed;\n } catch {}\n logger.error('${SNS_SUBSCRIPTIONS_KEY} is not a JSON object of subscriber → subscription ARN');\n return {};\n}\n\n/** The route a subscriber's pushes arrive on. */\nexport const SUBSCRIBER_ROUTE = (id: string) => \\`${SUBSCRIBER_ROUTE_PREFIX}\\${id}\\`;\n\n/** The route a local object store posts a bucket's events to. */\nexport const OBJECTS_ROUTE = (bucket: string) => \\`${OBJECTS_ROUTE_PREFIX}\\${bucket}\\`;\n\n// The buckets whose events this server relays: one route each, however many\n// subscribers watch the bucket.\nconst relays = new Set<string>();\n\n/**\n * Mount the route a local object store posts one bucket's events to, and\n * relay each event onto the broker under the bucket's name.\n *\n * Answered 2xx only once every event is published: the store keeps what it\n * was not told it delivered, and sends it again.\n */\nasync function mountObjectRelay(\n app: { post: (path: string, handler: (c: any) => unknown) => unknown },\n relay: { bucket: string; topic: string; connection: EventConnection; tokenKey: string },\n logger: Logger,\n): Promise<void> {\n const token = process.env[relay.tokenKey];\n if (!token) {\n logger.error(\n { bucket: relay.bucket, tokenKey: relay.tokenKey },\n 'No token for this bucket: the events its object store posts cannot be received',\n );\n failed.push(\\`\\${relay.bucket}#events\\`);\n return;\n }\n const { toObjectEvents } = await import('@geekmidas/storage/events');\n const publisher = await Publisher.fromConnection(relay.connection, { topic: relay.topic });\n const expected = Buffer.from(\\`Bearer \\${token}\\`);\n\n app.post(OBJECTS_ROUTE(relay.bucket), async (c: any) => {\n // Compared in constant time: the route is not public, but it is the one\n // way to put an event in front of every subscriber of the bucket.\n const given = Buffer.from(c.req.header('authorization') ?? '');\n if (given.length !== expected.length || !timingSafeEqual(given, expected)) {\n return c.json({ status: 'refused' }, 401);\n }\n\n let messages: Awaited<ReturnType<typeof toObjectEvents>>;\n try {\n messages = toObjectEvents(JSON.parse(await c.req.text()));\n } catch (error) {\n logger.warn({ err: error, bucket: relay.bucket }, 'Refused an object notification that did not parse');\n return c.json({ status: 'malformed' }, 400);\n }\n\n try {\n if (messages.length > 0) await publisher.publish(messages as any);\n } catch (error) {\n // The store sends it again.\n logger.error({ err: error, bucket: relay.bucket }, 'Failed to relay object events');\n return c.json({ status: 'failed' }, 500);\n }\n return c.json({ status: 'ok', relayed: messages.length }, 200);\n });\n logger.info({ bucket: relay.bucket }, 'Relaying object events');\n}\n\n${\n\treceives\n\t\t? `// The inboxes this server receives for locally, by id.\nconst inboxRelays = new Map<string, ReceivingInbox>();\n\n/**\n * Mount the route Mailpit posts each message it receives to, and hand the\n * message to the receiver a receipt rule stands for: each inbox one of its\n * envelope recipients is addressed to gets the receipt notification on its\n * topic. Mailpit names envelope recipients missing from the headers as Bcc.\n */\nfunction mountInboxRelay(\n app: { post: (path: string, handler: (c: any) => unknown) => unknown },\n logger: Logger,\n): void {\n const token = process.env.${INBOX_RELAY_TOKEN_KEY};\n if (!token) {\n logger.error('No ${INBOX_RELAY_TOKEN_KEY}: the mail Mailpit posts cannot be received');\n failed.push('inbox');\n return;\n }\n const expected = Buffer.from(token);\n\n app.post('${INBOX_ROUTE}', async (c: any) => {\n const given = Buffer.from(c.req.query('token') ?? '');\n if (given.length !== expected.length || !timingSafeEqual(given, expected)) {\n return c.json({ status: 'refused' }, 401);\n }\n\n let message: { key: string; from: string; recipients: string[] };\n try {\n const summary = JSON.parse(await c.req.text());\n const addresses = (list: unknown) =>\n Array.isArray(list) ? list.map((a: any) => a?.Address).filter(Boolean) : [];\n message = {\n key: String(summary.ID),\n from: summary.From?.Address ?? '',\n recipients: [...addresses(summary.To), ...addresses(summary.Cc), ...addresses(summary.Bcc)],\n };\n } catch (error) {\n logger.warn({ err: error }, 'Refused a Mailpit webhook that did not parse');\n return c.json({ status: 'malformed' }, 400);\n }\n\n try {\n const received = await receiveMail(\n { ...message, store: 'mailpit' },\n [...inboxRelays.values()],\n );\n return c.json({ status: 'ok', received }, 200);\n } catch (error) {\n logger.error({ err: error, message: message.key }, 'Failed to receive mail');\n return c.json({ status: 'failed' }, 500);\n }\n });\n logger.info({ inboxes: [...inboxRelays.keys()] }, 'Receiving mail from Mailpit');\n}\n\n`\n\t\t: ''\n}/** Resolves once something is accepting connections on the port. */\nasync function listening(port: number): Promise<void> {\n for (let attempt = 0; attempt < 100; attempt++) {\n const open = await new Promise<boolean>((resolve) => {\n const socket = connect(port, '127.0.0.1');\n socket.once('connect', () => { socket.end(); resolve(true); });\n socket.once('error', () => resolve(false));\n });\n if (open) return;\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n}\n\n/**\n * Mount each pushed subscriber's route and start each polled one. Returns what\n * to run once the server is listening: subscribing a route makes SNS send its\n * confirmation at once, so the route has to be reachable first.\n */\nexport async function setupSubscribers(\n app: { post: (path: string, handler: (c: any) => unknown) => unknown },\n envParser: EnvironmentParser<any>,\n logger: Logger,\n): Promise<(port: number) => Promise<void>> {\n if (process.env.GKM_SUBSCRIBERS === 'off') {\n logger.info('Subscribers are off (--no-subscribers)');\n return async () => {};\n }\n\n const serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n const recorded = recordedSubscriptions(logger);\n const afterListening: ((port: number) => Promise<void>)[] = [];\n\n for (const { id, subscriber, topic, connectionKey, filtered, bucket, tokenKey, inbox } of subscribers) {\n const events = subscriber.subscribedEvents || [];\n if (events.length === 0) {\n logger.warn({ subscriber: id }, 'Subscriber has no subscribed events, skipping');\n continue;\n }\n const connectionString = connectionKey ? process.env[connectionKey] : undefined;\n if (!connectionString) {\n logger.error(\n { subscriber: id, connectionKey },\n 'No connection string for the topic or bucket this subscriber is bound to',\n );\n failed.push(id);\n continue;\n }\n\n try {\n${\n\tpush\n\t\t? ` if (connectionString.startsWith('sns:')) {\n const { SNSConnection, snsUrl, subscribeHttpEndpoint, confirmSubscription } = await import('@geekmidas/events/sns');\n const { SnsPushSubscriberAdaptor } = await import('@geekmidas/constructs/subscribers');\n const address = snsUrl.parse(connectionString);\n const route = SUBSCRIBER_ROUTE(id);\n const mount = (adaptor: InstanceType<typeof SnsPushSubscriberAdaptor>) =>\n app.post(route, async (c: any) => {\n const body = JSON.parse(await c.req.text());\n const response = await adaptor.handle(body, {\n subscriptionArn: c.req.header('x-amz-sns-subscription-arn'),\n });\n return c.json(response.body, response.status);\n });\n\n if (!address.endpoint) {\n // SNS itself: the deploy subscribed this route and recorded the ARN.\n // Nothing is subscribed from here, so this server's credentials need\n // only sns:ConfirmSubscription on the topic.\n const subscriptionArn = recorded[id];\n if (!subscriptionArn) {\n logger.error(\n { subscriber: id },\n 'No subscription recorded for this subscriber in ${SNS_SUBSCRIPTIONS_KEY}: deploy it so SNS has a route to push to',\n );\n failed.push(id);\n continue;\n }\n const connection = await SNSConnection.fromConnectionString(connectionString);\n mount(\n new SnsPushSubscriberAdaptor(envParser, subscriber, {\n topicArn: address.topicArn,\n verify: true,\n subscriptionArn,\n // As the topic's owner, so only the owner can unsubscribe the\n // route — not whoever holds a notification's UnsubscribeURL.\n confirm: (message) => confirmSubscription(connection, message),\n }),\n );\n logger.info({ subscriber: id, events }, 'Subscriber mounted for push');\n continue;\n }\n\n // An emulator signs nothing, and nothing deploys its subscriptions:\n // decided by the address this server was configured with, never by\n // anything a request says about itself.\n mount(\n new SnsPushSubscriberAdaptor(envParser, subscriber, {\n topicArn: address.topicArn,\n verify: false,\n emulatorEndpoint: address.endpoint,\n }),\n );\n\n afterListening.push(async (port) => {\n const base =\n process.env.GKM_SUBSCRIBER_PUSH_URL ?? \\`http://host.docker.internal:\\${port}\\`;\n const connection = await SNSConnection.fromConnectionString(connectionString);\n await subscribeHttpEndpoint(connection, {\n endpoint: new URL(route, base).toString(),\n ...(filtered ? { events } : {}),\n });\n logger.info({ subscriber: id, events }, 'Subscriber subscribed for push');\n });\n continue;\n }\n`\n\t\t: ` if (connectionString.startsWith('sns:')) {\n // Built for a broker other than SNS, so this entry registered no SNS\n // driver and has no push route to offer.\n logger.error(\n { subscriber: id, connectionKey },\n 'This build has no SNS driver: it was built for a target whose broker is not SNS',\n );\n failed.push(id);\n continue;\n }\n`\n}\n\n let connection = connections.get(connectionString);\n if (!connection) {\n connection = await EventConnectionFactory.fromConnectionString(connectionString);\n connections.set(connectionString, connection);\n }\n // Named, so a broker with one address for everything (pg-boss) gives\n // this subscriber a queue of its own: fan-out, not competition.\n const eventSubscriber = await Subscriber.fromConnection(connection, {\n topic,\n subscription: id,\n });\n const services = subscriber.services.length > 0\n ? await serviceDiscovery.register(subscriber.services)\n : {};\n // The subscriber's database — the worker's, or its own — as \\`db\\`. A\n // pushed subscriber gets it from the adaptor above instead.\n const db = subscriber.databaseService\n ? (await serviceDiscovery.register([subscriber.databaseService]))[\n subscriber.databaseService.serviceName\n ]\n : undefined;\n\n await eventSubscriber.subscribe(events, async (event) => {\n try {\n await subscriber.handler({\n events: [event],\n services: services as any,\n logger: subscriber.logger,\n db,\n } as any);\n } catch (error) {\n logger.error({ err: error, event, subscriber: id }, 'Failed to process event');\n // Rethrown so the transport keeps the event for a retry — as a queue\n // consumer's failure does, and as a pushed subscriber's 500 does.\n throw error;\n }\n });\n logger.info({ subscriber: id, events }, 'Subscriber started polling');\n\n // A bucket in a local object store publishes nothing for this to poll:\n // the store posts its events here, and they are relayed onto the broker.\n if (bucket && tokenKey && topic && !relays.has(bucket)) {\n relays.add(bucket);\n await mountObjectRelay(app, { bucket, topic, connection, tokenKey }, logger);\n }${\n\t\t\t\treceives\n\t\t\t\t\t? `\n // An inbox polled here is a local one: Mailpit posts what it receives\n // to this server, which announces it on the inbox's topic.\n const domain = inbox ? process.env[inbox.domainKey] : undefined;\n if (inbox && topic && domain && !inboxRelays.has(inbox.id)) {\n const publisher = await Publisher.fromConnection(connection, { topic });\n inboxRelays.set(inbox.id, {\n id: inbox.id,\n addressing: inbox.addressing,\n domain,\n publish: async (payload) => {\n await publisher.publish([{ type: '${INBOX_EVENT}', payload }] as any);\n },\n });\n }`\n\t\t\t\t\t: ''\n\t\t\t}\n } catch (error) {\n // The message too: a missing module's code alone does not say which.\n logger.error(\n { err: error, subscriber: id },\n 'Failed to set up subscriber',\n );\n failed.push(id);\n }\n }\n\n${receives ? ' if (inboxRelays.size > 0) mountInboxRelay(app, logger);\\n\\n' : ''} return async (port) => {\n if (afterListening.length === 0) return;\n await listening(port);\n for (const subscribe of afterListening) {\n await subscribe(port).catch((error) => {\n logger.error({ err: error }, 'Failed to subscribe for push');\n });\n }\n };\n}\n\n/** The subscribers that could not start, and the connections that did. */\nexport function subscribersStatus(): { failed: string[]; connections: EventConnection[] } {\n return { failed: [...failed], connections: [...connections.values()] };\n}\n\n/**\n * Stop polling, let the events in flight finish, and close each broker\n * connection — pg-boss's graceful stop does all three. The caller bounds it.\n */\nexport async function stopSubscribers(): Promise<void> {\n const open = [...connections.values()];\n connections.clear();\n await Promise.all(open.map((connection) => connection.close()));\n}\n`;\n\n\t\tawait writeFile(subscribersPath, content);\n\t\treturn subscribersPath;\n\t}\n}\n\n/**\n * A bucket's subscriber that writes back into the keys it watches.\n *\n * Every write it makes is a new object event, which runs it again — forever,\n * and billed per run. The rule is the one the build can check: a subscriber\n * that depends on the bucket it watches must watch a prefix, so what it writes\n * can go elsewhere. A thumbnailer watching `uploads/` writes `thumbnails/`.\n */\nexport class ObjectSubscriberFeedsItself extends Error {\n\tconstructor(\n\t\treadonly subscriber: string,\n\t\treadonly bucket: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${subscriber}' watches every key in '${bucket}' and depends on it, ` +\n\t\t\t\t`so each object it writes runs it again. Watch a prefix — ` +\n\t\t\t\t`.on([...], { prefix: 'uploads/' }) — and write outside it.`,\n\t\t);\n\t\tthis.name = 'ObjectSubscriberFeedsItself';\n\t}\n}\n\nfunction assertDoesNotFeedItself(\n\tkey: string,\n\tconstruct: Subscriber<any, any, any, any, any, any, any>,\n): void {\n\tconst bucket = construct.bucketName;\n\tif (!bucket || construct.objectFilter?.prefix) return;\n\tconst depends = (construct.constructs ?? []).some(\n\t\t(id: string) => canonicalId(id) === canonicalId(bucket),\n\t);\n\tif (depends) throw new ObjectSubscriberFeedsItself(key, bucket);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,cAAc;;AAG3B,MAAa,wBAAwB;;;;;AAMrC,IAAa,8BAAb,cAAiDA,eAAAA,SAAS;CACpC;CAArB,YAAY,SAAqC;EAChD,MACC,4BAA4B,QAAQ,KAAK,MAAM,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,OAAO,EAAE,uJAIxE;EANoB,KAAA,UAAA;EAOpB,KAAK,OAAO;CACb;AACD;;;;;AAMA,SAAgB,iBACf,UACA,aACqB;CACrB,MAAM,4BAAY,IAAI,IAAY;CAClC,KAAK,MAAM,eAAe,OAAO,OAAO,QAAQ,GAAG;EAClD,IAAI,YAAY,SAAS,SA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