@geekmidas/constructs 10.0.0-alpha.154 → 10.0.0-alpha.156

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 (220) hide show
  1. package/README.md +23 -0
  2. package/dist/{Construct-DorKS0Ua.cjs → Construct-B8yWxGlR.cjs} +2 -2
  3. package/dist/{Construct-DorKS0Ua.cjs.map → Construct-B8yWxGlR.cjs.map} +1 -1
  4. package/dist/{Construct-DySlwh8o.d.mts → Construct-BMk_CRSD.d.mts} +2 -2
  5. package/dist/{Construct-DySlwh8o.d.mts.map → Construct-BMk_CRSD.d.mts.map} +1 -1
  6. package/dist/{Construct-CGuc_Ijk.mjs → Construct-CRV3RN2U.mjs} +11 -2
  7. package/dist/{Construct-CGuc_Ijk.mjs.map → Construct-CRV3RN2U.mjs.map} +1 -1
  8. package/dist/{Cron-D8mB_cPX.d.mts → Cron-D6Y7BBt3.d.mts} +5 -5
  9. package/dist/{Cron-D8mB_cPX.d.mts.map → Cron-D6Y7BBt3.d.mts.map} +1 -1
  10. package/dist/{CronBuilder-Cmajva3g.d.mts → CronBuilder-4BZhkChG.d.mts} +5 -5
  11. package/dist/{CronBuilder-Cmajva3g.d.mts.map → CronBuilder-4BZhkChG.d.mts.map} +1 -1
  12. package/dist/{CronBuilder-B_NSP-Y5.cjs → CronBuilder-B4DYaEjl.cjs} +4 -4
  13. package/dist/{CronBuilder-B_NSP-Y5.cjs.map → CronBuilder-B4DYaEjl.cjs.map} +1 -1
  14. package/dist/{CronBuilder-BJ5LoadF.mjs → CronBuilder-CukJuL3b.mjs} +3 -3
  15. package/dist/{CronBuilder-BJ5LoadF.mjs.map → CronBuilder-CukJuL3b.mjs.map} +1 -1
  16. package/dist/{Endpoint-BbHh3Qoc.d.mts → Endpoint-BUoDD96P.d.mts} +5 -5
  17. package/dist/{Endpoint-BbHh3Qoc.d.mts.map → Endpoint-BUoDD96P.d.mts.map} +1 -1
  18. package/dist/{Endpoint-sUOU7uLx.mjs → Endpoint-BuKHHVZc.mjs} +3 -3
  19. package/dist/{Endpoint-sUOU7uLx.mjs.map → Endpoint-BuKHHVZc.mjs.map} +1 -1
  20. package/dist/{Endpoint-52z1P0Ue.cjs → Endpoint-D2ckHqIx.cjs} +3 -3
  21. package/dist/{Endpoint-52z1P0Ue.cjs.map → Endpoint-D2ckHqIx.cjs.map} +1 -1
  22. package/dist/{EndpointFactory-qcLzi4f-.d.mts → EndpointFactory-BbVOeryo.d.mts} +5 -5
  23. package/dist/{EndpointFactory-qcLzi4f-.d.mts.map → EndpointFactory-BbVOeryo.d.mts.map} +1 -1
  24. package/dist/{EndpointFactory-Bzi9Sl7r.mjs → EndpointFactory-BsJUlUyL.mjs} +4 -4
  25. package/dist/{EndpointFactory-Bzi9Sl7r.mjs.map → EndpointFactory-BsJUlUyL.mjs.map} +1 -1
  26. package/dist/{EndpointFactory-Cf_Cs1ym.cjs → EndpointFactory-c4tHjQKM.cjs} +5 -5
  27. package/dist/{EndpointFactory-Cf_Cs1ym.cjs.map → EndpointFactory-c4tHjQKM.cjs.map} +1 -1
  28. package/dist/{Function-DfMzTGS4.d.mts → Function-BKReud5p.d.mts} +3 -3
  29. package/dist/{Function-DfMzTGS4.d.mts.map → Function-BKReud5p.d.mts.map} +1 -1
  30. package/dist/{HonoEndpointAdaptor-DR3j7S35.mjs → HonoEndpointAdaptor-BC7CZ7Cr.mjs} +7 -6
  31. package/dist/HonoEndpointAdaptor-BC7CZ7Cr.mjs.map +1 -0
  32. package/dist/{HonoEndpointAdaptor-BXBdb2Bt.cjs → HonoEndpointAdaptor-BGEW1Tu8.cjs} +9 -8
  33. package/dist/HonoEndpointAdaptor-BGEW1Tu8.cjs.map +1 -0
  34. package/dist/{ObjectSubscriberBuilder-Cv8C7yS1.d.mts → ObjectSubscriberBuilder-DfzXQEKW.d.mts} +4 -4
  35. package/dist/{ObjectSubscriberBuilder-Cv8C7yS1.d.mts.map → ObjectSubscriberBuilder-DfzXQEKW.d.mts.map} +1 -1
  36. package/dist/ObjectSubscriberBuilder-LWkey_oq.d.cts.map +1 -1
  37. package/dist/{ProcessorBuilder-CwfP-M33.d.mts → ProcessorBuilder-D4oYvZeG.d.mts} +2 -2
  38. package/dist/{ProcessorBuilder-CwfP-M33.d.mts.map → ProcessorBuilder-D4oYvZeG.d.mts.map} +1 -1
  39. package/dist/{Queue-u8w8_HpE.mjs → Queue-0FpvxdOa.mjs} +2 -2
  40. package/dist/{Queue-u8w8_HpE.mjs.map → Queue-0FpvxdOa.mjs.map} +1 -1
  41. package/dist/{Queue-BnK3UH8r.d.mts → Queue-B8HGg439.d.mts} +3 -3
  42. package/dist/{Queue-BnK3UH8r.d.mts.map → Queue-B8HGg439.d.mts.map} +1 -1
  43. package/dist/{Queue-D4Iaidrs.cjs → Queue-DZpV13LN.cjs} +2 -2
  44. package/dist/{Queue-D4Iaidrs.cjs.map → Queue-DZpV13LN.cjs.map} +1 -1
  45. package/dist/{QueueBuilder-2wP5lEC8.mjs → QueueBuilder-Bmyay_Di.mjs} +2 -2
  46. package/dist/{QueueBuilder-2wP5lEC8.mjs.map → QueueBuilder-Bmyay_Di.mjs.map} +1 -1
  47. package/dist/{QueueBuilder-DmwFtLzQ.d.mts → QueueBuilder-CVS_qPuo.d.mts} +2 -2
  48. package/dist/{QueueBuilder-DmwFtLzQ.d.mts.map → QueueBuilder-CVS_qPuo.d.mts.map} +1 -1
  49. package/dist/{QueueBuilder-BxsZ9o5z.cjs → QueueBuilder-FXkSDah1.cjs} +2 -2
  50. package/dist/{QueueBuilder-BxsZ9o5z.cjs.map → QueueBuilder-FXkSDah1.cjs.map} +1 -1
  51. package/dist/{Subscriber-CW_Dl-YR.d.mts → Subscriber-CtQXhcL7.d.mts} +3 -3
  52. package/dist/{Subscriber-CW_Dl-YR.d.mts.map → Subscriber-CtQXhcL7.d.mts.map} +1 -1
  53. package/dist/{SubscriberBuilder-CWzKwX1p.cjs → SubscriberBuilder-Bfn-iDSk.cjs} +4 -3
  54. package/dist/SubscriberBuilder-Bfn-iDSk.cjs.map +1 -0
  55. package/dist/{SubscriberBuilder-BL_GTcwh.mjs → SubscriberBuilder-CxG1OOug.mjs} +4 -3
  56. package/dist/SubscriberBuilder-CxG1OOug.mjs.map +1 -0
  57. package/dist/{Topic-DN2gYJ-p.mjs → Topic-DoEdDgh7.mjs} +2 -2
  58. package/dist/{Topic-DN2gYJ-p.mjs.map → Topic-DoEdDgh7.mjs.map} +1 -1
  59. package/dist/{Topic-Dp9Q7Lj2.cjs → Topic-t5GhqaeT.cjs} +2 -2
  60. package/dist/{Topic-Dp9Q7Lj2.cjs.map → Topic-t5GhqaeT.cjs.map} +1 -1
  61. package/dist/adaptors/aws.cjs +28 -16
  62. package/dist/adaptors/aws.cjs.map +1 -1
  63. package/dist/adaptors/aws.d.cts +141 -0
  64. package/dist/adaptors/aws.d.cts.map +1 -1
  65. package/dist/adaptors/aws.d.mts +147 -6
  66. package/dist/adaptors/aws.d.mts.map +1 -1
  67. package/dist/adaptors/aws.mjs +21 -15
  68. package/dist/adaptors/aws.mjs.map +1 -1
  69. package/dist/adaptors/hono.cjs +1 -1
  70. package/dist/adaptors/hono.d.mts +2 -2
  71. package/dist/adaptors/hono.mjs +1 -1
  72. package/dist/adaptors/testing.cjs +230 -14
  73. package/dist/adaptors/testing.cjs.map +1 -1
  74. package/dist/adaptors/testing.d.cts +81 -2
  75. package/dist/adaptors/testing.d.cts.map +1 -1
  76. package/dist/adaptors/testing.d.mts +89 -10
  77. package/dist/adaptors/testing.d.mts.map +1 -1
  78. package/dist/adaptors/testing.mjs +221 -12
  79. package/dist/adaptors/testing.mjs.map +1 -1
  80. package/dist/apigateway-Dyjy_JwI.mjs +329 -0
  81. package/dist/apigateway-Dyjy_JwI.mjs.map +1 -0
  82. package/dist/apigateway-zHDoMwlI.cjs +370 -0
  83. package/dist/apigateway-zHDoMwlI.cjs.map +1 -0
  84. package/dist/auth-BqWz2JxC.d.cts.map +1 -1
  85. package/dist/auth-DnB9H9KL.d.mts.map +1 -1
  86. package/dist/auth.cjs +7 -21
  87. package/dist/auth.cjs.map +1 -1
  88. package/dist/auth.mjs +6 -20
  89. package/dist/auth.mjs.map +1 -1
  90. package/dist/{cache-e3tfMQ9g.d.mts → cache-CCHcO9Oo.d.mts} +2 -2
  91. package/dist/cache-CCHcO9Oo.d.mts.map +1 -0
  92. package/dist/cache-CQjMNPrC.d.cts.map +1 -1
  93. package/dist/cache.cjs +3 -19
  94. package/dist/cache.cjs.map +1 -1
  95. package/dist/cache.d.mts +1 -1
  96. package/dist/cache.mjs +2 -18
  97. package/dist/cache.mjs.map +1 -1
  98. package/dist/crons/index.cjs +4 -3
  99. package/dist/crons/index.cjs.map +1 -1
  100. package/dist/crons/index.d.cts.map +1 -1
  101. package/dist/crons/index.d.mts +2 -2
  102. package/dist/crons/index.d.mts.map +1 -1
  103. package/dist/crons/index.mjs +4 -3
  104. package/dist/crons/index.mjs.map +1 -1
  105. package/dist/database/kysely.cjs +1 -1
  106. package/dist/database/kysely.d.mts +1 -1
  107. package/dist/email.cjs +4 -16
  108. package/dist/email.cjs.map +1 -1
  109. package/dist/email.d.cts.map +1 -1
  110. package/dist/email.d.mts.map +1 -1
  111. package/dist/email.mjs +2 -14
  112. package/dist/email.mjs.map +1 -1
  113. package/dist/endpoints/index.cjs +4 -4
  114. package/dist/endpoints/index.d.cts +1 -1
  115. package/dist/endpoints/index.d.cts.map +1 -1
  116. package/dist/endpoints/index.d.mts +4 -4
  117. package/dist/endpoints/index.d.mts.map +1 -1
  118. package/dist/endpoints/index.mjs +4 -4
  119. package/dist/file-server.cjs +1 -1
  120. package/dist/file-server.d.mts +1 -1
  121. package/dist/file-server.mjs +1 -1
  122. package/dist/functions/index.cjs +1 -1
  123. package/dist/functions/index.d.mts +2 -2
  124. package/dist/functions/index.mjs +1 -1
  125. package/dist/{functions-BvIDQKAA.mjs → functions-BF039DT8.mjs} +2 -2
  126. package/dist/{functions-BvIDQKAA.mjs.map → functions-BF039DT8.mjs.map} +1 -1
  127. package/dist/{functions-DLF6-IK8.cjs → functions-BqAq_0xQ.cjs} +3 -3
  128. package/dist/{functions-DLF6-IK8.cjs.map → functions-BqAq_0xQ.cjs.map} +1 -1
  129. package/dist/{inbox-CjxpLVkH.d.mts → inbox-YOdxlyfj.d.mts} +2 -2
  130. package/dist/{inbox-CjxpLVkH.d.mts.map → inbox-YOdxlyfj.d.mts.map} +1 -1
  131. package/dist/inbox.cjs +1 -1
  132. package/dist/inbox.d.mts +1 -1
  133. package/dist/inbox.mjs +1 -1
  134. package/dist/{index-DCkDQkwj.d.mts → index-BoQ3-M-K.d.mts} +4 -4
  135. package/dist/{index-DCkDQkwj.d.mts.map → index-BoQ3-M-K.d.mts.map} +1 -1
  136. package/dist/index.cjs +1 -1
  137. package/dist/index.d.mts +1 -1
  138. package/dist/index.mjs +1 -1
  139. package/dist/{kysely-CukArHJ0.cjs → kysely-CeoQdAkg.cjs} +2 -2
  140. package/dist/{kysely-CukArHJ0.cjs.map → kysely-CeoQdAkg.cjs.map} +1 -1
  141. package/dist/{kysely-DE4kADWD.d.mts → kysely-De5rAC-E.d.mts} +2 -2
  142. package/dist/{kysely-DE4kADWD.d.mts.map → kysely-De5rAC-E.d.mts.map} +1 -1
  143. package/dist/optionalPeers-D7Wt6dnF.mjs +140 -0
  144. package/dist/optionalPeers-D7Wt6dnF.mjs.map +1 -0
  145. package/dist/optionalPeers-DuNQXXe1.cjs +223 -0
  146. package/dist/optionalPeers-DuNQXXe1.cjs.map +1 -0
  147. package/dist/origins-C7T9covD.cjs +24 -0
  148. package/dist/origins-C7T9covD.cjs.map +1 -0
  149. package/dist/origins-CX6Ot7ax.mjs +19 -0
  150. package/dist/origins-CX6Ot7ax.mjs.map +1 -0
  151. package/dist/{pattern-QFaUIr77.cjs → pattern-HnNOPhE2.cjs} +2 -2
  152. package/dist/{pattern-QFaUIr77.cjs.map → pattern-HnNOPhE2.cjs.map} +1 -1
  153. package/dist/{pattern-C1CEcglD.mjs → pattern-YSqfAhXm.mjs} +2 -2
  154. package/dist/{pattern-C1CEcglD.mjs.map → pattern-YSqfAhXm.mjs.map} +1 -1
  155. package/dist/privateAddress-Bg5fUsbp.mjs +21 -0
  156. package/dist/privateAddress-Bg5fUsbp.mjs.map +1 -0
  157. package/dist/privateAddress-CqGyuFHn.cjs +26 -0
  158. package/dist/privateAddress-CqGyuFHn.cjs.map +1 -0
  159. package/dist/processors/index.cjs +1 -1
  160. package/dist/processors/index.d.mts +1 -1
  161. package/dist/processors/index.mjs +1 -1
  162. package/dist/queue/index.cjs +2 -2
  163. package/dist/queue/index.d.mts +2 -2
  164. package/dist/queue/index.mjs +2 -2
  165. package/dist/{readRequestBody-BTIl3k-D.mjs → readRequestBody-BmKnPl0a.mjs} +26 -4
  166. package/dist/readRequestBody-BmKnPl0a.mjs.map +1 -0
  167. package/dist/{readRequestBody-Dej_L3c4.cjs → readRequestBody-CN9GVdeE.cjs} +26 -4
  168. package/dist/readRequestBody-CN9GVdeE.cjs.map +1 -0
  169. package/dist/{requestLogger-BZcXwdBs.cjs → requestLogger-CnoYd-Ah.cjs} +4 -63
  170. package/dist/requestLogger-CnoYd-Ah.cjs.map +1 -0
  171. package/dist/{requestLogger-pA4gi3E1.mjs → requestLogger-D2JS7pPM.mjs} +3 -56
  172. package/dist/requestLogger-D2JS7pPM.mjs.map +1 -0
  173. package/dist/rest-api.cjs +1 -1
  174. package/dist/rest-api.d.mts +2 -2
  175. package/dist/rest-api.mjs +1 -1
  176. package/dist/{rolldown-runtime-y5ARvAq5.cjs → rolldown-runtime-Ctb5zv51.cjs} +15 -0
  177. package/dist/{runSubscriber-DyHWp_Lf.mjs → runSubscriber-HEqXkin1.mjs} +3 -2
  178. package/dist/runSubscriber-HEqXkin1.mjs.map +1 -0
  179. package/dist/{runSubscriber-CC_2C9F2.cjs → runSubscriber-sVJfLA0-.cjs} +3 -2
  180. package/dist/runSubscriber-sVJfLA0-.cjs.map +1 -0
  181. package/dist/subscribers/index.cjs +6 -6
  182. package/dist/subscribers/index.cjs.map +1 -1
  183. package/dist/subscribers/index.d.cts +1 -1
  184. package/dist/subscribers/index.d.mts +3 -3
  185. package/dist/subscribers/index.mjs +3 -3
  186. package/dist/subscribers/index.mjs.map +1 -1
  187. package/dist/topic/index.cjs +1 -1
  188. package/dist/topic/index.d.mts +1 -1
  189. package/dist/topic/index.mjs +1 -1
  190. package/dist/websocket-api-BvKS9x-l.mjs +1711 -0
  191. package/dist/websocket-api-BvKS9x-l.mjs.map +1 -0
  192. package/dist/websocket-api-C3dWKNxO.d.cts +1181 -0
  193. package/dist/websocket-api-C3dWKNxO.d.cts.map +1 -0
  194. package/dist/websocket-api-CAQA_QOE.cjs +1890 -0
  195. package/dist/websocket-api-CAQA_QOE.cjs.map +1 -0
  196. package/dist/websocket-api-CDAxOTQZ.d.mts +1181 -0
  197. package/dist/websocket-api-CDAxOTQZ.d.mts.map +1 -0
  198. package/dist/websocket-api.cjs +31 -1121
  199. package/dist/websocket-api.d.cts +2 -699
  200. package/dist/websocket-api.d.mts +2 -699
  201. package/dist/websocket-api.mjs +2 -1102
  202. package/dist/worker.cjs +4 -4
  203. package/dist/worker.d.mts +9 -9
  204. package/dist/worker.mjs +4 -4
  205. package/package.json +41 -31
  206. package/dist/HonoEndpointAdaptor-BXBdb2Bt.cjs.map +0 -1
  207. package/dist/HonoEndpointAdaptor-DR3j7S35.mjs.map +0 -1
  208. package/dist/SubscriberBuilder-BL_GTcwh.mjs.map +0 -1
  209. package/dist/SubscriberBuilder-CWzKwX1p.cjs.map +0 -1
  210. package/dist/cache-e3tfMQ9g.d.mts.map +0 -1
  211. package/dist/readRequestBody-BTIl3k-D.mjs.map +0 -1
  212. package/dist/readRequestBody-Dej_L3c4.cjs.map +0 -1
  213. package/dist/requestLogger-BZcXwdBs.cjs.map +0 -1
  214. package/dist/requestLogger-pA4gi3E1.mjs.map +0 -1
  215. package/dist/runSubscriber-CC_2C9F2.cjs.map +0 -1
  216. package/dist/runSubscriber-DyHWp_Lf.mjs.map +0 -1
  217. package/dist/websocket-api.cjs.map +0 -1
  218. package/dist/websocket-api.d.cts.map +0 -1
  219. package/dist/websocket-api.d.mts.map +0 -1
  220. package/dist/websocket-api.mjs.map +0 -1
@@ -1,1102 +1,2 @@
1
- import { t as onShutdown } from "./shutdown-C7xa8x9S.mjs";
2
- import { edgeTo, idsOf, servicesOf } from "./construct-interface.mjs";
3
- import { n as envParserFor } from "./surfaceEnv-wMT5QzgZ.mjs";
4
- import { canonicalId, provideKey, serviceKey, trustsOrigin } from "@geekmidas/manifest";
5
- import { DEFAULT_LOGGER } from "@geekmidas/logger/console";
6
- import { randomBytes } from "node:crypto";
7
- import { ServiceDiscovery, runWithRequestContext } from "@geekmidas/services";
8
- import { HttpError } from "@geekmidas/errors";
9
- import { toJsonSchema } from "@geekmidas/schema/conversion";
10
- //#region src/websocket/frame.ts
11
- /**
12
- * The shape a surface's frames take on the wire.
13
- *
14
- * By default a frame is `{ "action": …, "id"?: …, "data": … }` — API
15
- * Gateway's shape. A surface that names a discriminator — `frame: {
16
- * discriminator: 'type' }` — sends and reads flat frames instead: the action
17
- * under that key, and the data's own fields beside it.
18
- *
19
- * ```json
20
- * {"type":"chat.message.created","chatId":"c1","message":{…}}
21
- * ```
22
- *
23
- * A flat frame has no `id` of its own: every field but the discriminator is
24
- * the data, so a reply is paired by its action, not an echoed id.
25
- */
26
- /** A declared message whose schema does not describe an object. */
27
- var WebSocketMessageNotAnObject = class extends Error {
28
- surface;
29
- action;
30
- discriminator;
31
- constructor(surface, action, discriminator) {
32
- super(`${surface} sends flat frames, keyed by '${discriminator}', so each message's fields sit beside it — but '${action}' is not an object schema. Declare it as an object (z.object({ … })), or drop \`frame\` to send { action, data }.`);
33
- this.surface = surface;
34
- this.action = action;
35
- this.discriminator = discriminator;
36
- this.name = "WebSocketMessageNotAnObject";
37
- }
38
- };
39
- /** A declared message whose schema has a field named the discriminator. */
40
- var WebSocketMessageDeclaresDiscriminator = class extends Error {
41
- surface;
42
- action;
43
- discriminator;
44
- constructor(surface, action, discriminator) {
45
- super(`${surface}'s '${action}' message declares a '${discriminator}' field, which is where its flat frames keep the action. Rename the field, or give \`frame.discriminator\` a key no message uses.`);
46
- this.surface = surface;
47
- this.action = action;
48
- this.discriminator = discriminator;
49
- this.name = "WebSocketMessageDeclaresDiscriminator";
50
- }
51
- };
52
- /** Data sent in a flat frame that is not an object. */
53
- var WebSocketDataNotAnObject = class extends Error {
54
- surface;
55
- action;
56
- discriminator;
57
- constructor(surface, action, discriminator) {
58
- super(`${surface} sends flat frames, keyed by '${discriminator}', and '${action}''s data is not an object, so it has no fields to put beside it. Send an object. Nothing was sent.`);
59
- this.surface = surface;
60
- this.action = action;
61
- this.discriminator = discriminator;
62
- this.name = "WebSocketDataNotAnObject";
63
- }
64
- };
65
- /** Data sent in a flat frame that carries the discriminator itself. */
66
- var WebSocketDataHasDiscriminator = class extends Error {
67
- surface;
68
- action;
69
- discriminator;
70
- constructor(surface, action, discriminator) {
71
- super(`'${action}''s data on ${surface} has a '${discriminator}' field, which is where its flat frames keep the action. Rename the field. Nothing was sent.`);
72
- this.surface = surface;
73
- this.action = action;
74
- this.discriminator = discriminator;
75
- this.name = "WebSocketDataHasDiscriminator";
76
- }
77
- };
78
- /** How one surface writes and reads its frames. */
79
- var FrameShape = class {
80
- surface;
81
- discriminator;
82
- constructor(surface, discriminator) {
83
- this.surface = surface;
84
- this.discriminator = discriminator;
85
- }
86
- /** The key an inbound frame names its action under. */
87
- get key() {
88
- return this.discriminator ?? "action";
89
- }
90
- /**
91
- * The frame for `action`'s `data`, serialised.
92
- *
93
- * @throws {WebSocketDataNotAnObject}, {WebSocketDataHasDiscriminator} for
94
- * a flat frame whose data cannot sit beside the discriminator.
95
- */
96
- encode(action, data, id) {
97
- const { discriminator } = this;
98
- if (discriminator === void 0) return JSON.stringify({
99
- action,
100
- ...id !== void 0 ? { id } : {},
101
- data
102
- });
103
- if (!isRecord(data)) throw new WebSocketDataNotAnObject(this.surface, action, discriminator);
104
- if (Object.hasOwn(data, discriminator)) throw new WebSocketDataHasDiscriminator(this.surface, action, discriminator);
105
- return JSON.stringify({
106
- [discriminator]: action,
107
- ...data
108
- });
109
- }
110
- /** A parsed frame's action, id and data — `undefined` when it names none. */
111
- decode(frame) {
112
- if (!isRecord(frame)) return void 0;
113
- const { discriminator } = this;
114
- if (discriminator === void 0) {
115
- if (typeof frame.action !== "string") return void 0;
116
- return {
117
- action: frame.action,
118
- ...isId(frame.id) ? { id: frame.id } : {},
119
- data: frame.data
120
- };
121
- }
122
- const { [discriminator]: action, ...data } = frame;
123
- if (typeof action !== "string") return void 0;
124
- return {
125
- action,
126
- data
127
- };
128
- }
129
- /** The id a frame that names no action carried, to echo on its error. */
130
- idOf(frame) {
131
- if (this.discriminator !== void 0 || !isRecord(frame)) return void 0;
132
- return isId(frame.id) ? frame.id : void 0;
133
- }
134
- /**
135
- * Refuse a declared message a flat frame cannot carry: one that is not an
136
- * object, or that has a field named the discriminator.
137
- *
138
- * @throws {WebSocketMessageNotAnObject}, {WebSocketMessageDeclaresDiscriminator}
139
- */
140
- check(messages) {
141
- const { discriminator } = this;
142
- if (discriminator === void 0) return;
143
- for (const [action, schema] of Object.entries(messages)) {
144
- const shape = objectShape(toJsonSchema(schema));
145
- if (!shape) throw new WebSocketMessageNotAnObject(this.surface, action, discriminator);
146
- if (shape.has(discriminator)) throw new WebSocketMessageDeclaresDiscriminator(this.surface, action, discriminator);
147
- }
148
- }
149
- };
150
- /**
151
- * The fields a JSON Schema's object declares, or `undefined` when it is not
152
- * an object. A union or intersection is one when each of its members is.
153
- */
154
- function objectShape(schema) {
155
- if (!isRecord(schema)) return void 0;
156
- const members = schema.anyOf ?? schema.oneOf ?? schema.allOf;
157
- if (Array.isArray(members) && members.length > 0) {
158
- const fields = /* @__PURE__ */ new Set();
159
- for (const member of members) {
160
- const shape = objectShape(member);
161
- if (!shape) return void 0;
162
- for (const field of shape) fields.add(field);
163
- }
164
- return fields;
165
- }
166
- if (schema.type !== "object") return void 0;
167
- return new Set(isRecord(schema.properties) ? Object.keys(schema.properties) : []);
168
- }
169
- function isRecord(value) {
170
- return typeof value === "object" && value !== null && !Array.isArray(value);
171
- }
172
- function isId(value) {
173
- return typeof value === "string" || typeof value === "number";
174
- }
175
- //#endregion
176
- //#region src/websocket/publisher.ts
177
- /** A message sent on an action the surface does not declare. */
178
- var UnknownWebSocketMessage = class extends Error {
179
- surface;
180
- action;
181
- declared;
182
- constructor(surface, action, declared) {
183
- super(`${surface} sends no '${action}' message. It declares ${declared.map((a) => `'${a}'`).join(", ")} — send one of them, or add '${action}' to its messages.`);
184
- this.surface = surface;
185
- this.action = action;
186
- this.declared = declared;
187
- this.name = "UnknownWebSocketMessage";
188
- }
189
- };
190
- /** A message whose data its action's schema refused. */
191
- var InvalidWebSocketMessage = class extends Error {
192
- surface;
193
- action;
194
- issues;
195
- constructor(surface, action, issues) {
196
- super(`${surface}'s '${action}' message was refused by its schema: ${issues.map((issue) => issue.message).join("; ")}. Nothing was sent.`);
197
- this.surface = surface;
198
- this.action = action;
199
- this.issues = issues;
200
- this.name = "InvalidWebSocketMessage";
201
- }
202
- };
203
- /**
204
- * How anything reaches a socket — `services.realtime` in an endpoint, and
205
- * `sockets` in a route of the surface itself.
206
- *
207
- * A message is `{ action, data }`, the shape a client's frames arrive in —
208
- * or, where the surface names a `frame.discriminator`, flat: `{ [key]: action,
209
- * ...data }`.
210
- * Where the surface declares its messages, `action` is one of them and
211
- * `data` is typed and checked by its schema before anything is sent; where it
212
- * declares none, any action and any JSON value go. A message is serialised
213
- * once, whatever the number of sockets it goes to. An id whose process has
214
- * gone is dropped silently, as API Gateway's `postToConnection` to a closed
215
- * connection is a no-op the sender rarely wants to handle.
216
- */
217
- var WebSocketPublisher = class {
218
- sink;
219
- declared;
220
- frame;
221
- constructor(sink, declared, frame = new FrameShape(declared?.surface ?? "")) {
222
- this.sink = sink;
223
- this.declared = declared;
224
- this.frame = frame;
225
- }
226
- /** Send `action`'s message to each connection. */
227
- async send(ids, action, data) {
228
- const payload = await this.payload(action, data);
229
- await this.sink.send(listOf(ids), payload);
230
- }
231
- /** Send `action`'s message to every open connection, on every process. */
232
- async broadcast(action, data, options = {}) {
233
- const payload = await this.payload(action, data);
234
- await this.sink.broadcast(payload, options.except?.length ? options.except : void 0);
235
- }
236
- /** Close each connection, with a close code and reason its client sees. */
237
- async close(ids, code = 1e3, reason = "") {
238
- await this.sink.close(listOf(ids), code, reason);
239
- }
240
- /**
241
- * The frame, checked by the action's schema where the surface declares
242
- * its messages.
243
- *
244
- * @throws {UnknownWebSocketMessage}, {InvalidWebSocketMessage}, and for a
245
- * flat frame {WebSocketDataNotAnObject}, {WebSocketDataHasDiscriminator}
246
- */
247
- async payload(action, data) {
248
- if (!this.declared) return this.frame.encode(action, data);
249
- const { surface, messages } = this.declared;
250
- const schema = messages[action];
251
- if (!schema) throw new UnknownWebSocketMessage(surface, action, Object.keys(messages));
252
- const result = await schema["~standard"].validate(data);
253
- if (result.issues) throw new InvalidWebSocketMessage(surface, action, result.issues);
254
- return this.frame.encode(action, result.value);
255
- }
256
- };
257
- function listOf(ids) {
258
- return typeof ids === "string" ? [ids] : ids;
259
- }
260
- //#endregion
261
- //#region src/websocket/core.ts
262
- /** Two routes answer one action. */
263
- var DuplicateWebSocketRoute = class extends Error {
264
- surface;
265
- action;
266
- constructor(surface, action) {
267
- super(`Two routes on ${surface} answer '${action}'. Each action has one handler — rename one of them.`);
268
- this.surface = surface;
269
- this.action = action;
270
- this.name = "DuplicateWebSocketRoute";
271
- }
272
- };
273
- var WebSocketCore = class {
274
- options;
275
- surface;
276
- /** How frames are read and written — what an adaptor decodes replies by. */
277
- frame;
278
- /** `sockets` in every handler. */
279
- sockets;
280
- routes = /* @__PURE__ */ new Map();
281
- lifecycle = {};
282
- /**
283
- * @throws {DuplicateWebSocketRoute} when two routes answer one action, and
284
- * the frame checks of `FrameShape.check` for declared messages.
285
- */
286
- constructor(options) {
287
- this.options = options;
288
- this.surface = options.surface;
289
- for (const route of options.routes) {
290
- if (route.surface.id !== options.surface) continue;
291
- if (route.kind === "message") {
292
- if (this.routes.has(route.action)) throw new DuplicateWebSocketRoute(options.surface, route.action);
293
- this.routes.set(route.action, route);
294
- } else {
295
- if (this.lifecycle[route.kind]) throw new DuplicateWebSocketRoute(options.surface, route.action);
296
- this.lifecycle[route.kind] = route;
297
- }
298
- }
299
- this.frame = new FrameShape(options.surface, options.frame?.discriminator);
300
- if (options.messages) this.frame.check(options.messages);
301
- this.sockets = new WebSocketPublisher(options.sink, options.messages ? {
302
- surface: options.surface,
303
- messages: options.messages
304
- } : void 0, this.frame);
305
- }
306
- /**
307
- * Run the connect handler for a handshake: accepted with the connection's
308
- * `data` (what the handler returned, `{}` for nothing), or refused with
309
- * the status of the `HttpError` it threw — 500 for anything else. A surface
310
- * with no connect handler accepts every handshake, and verifies no session.
311
- */
312
- async connect(request, options = {}) {
313
- const { connectionId, headers, query } = request;
314
- const route = this.lifecycle.connect;
315
- if (!route) return {
316
- accepted: true,
317
- connection: {
318
- id: connectionId,
319
- data: {}
320
- }
321
- };
322
- try {
323
- const session = "session" in request ? request.session : this.options.authenticator ? await this.options.authenticator.verify(headers, this.options.envParser) : null;
324
- const returned = await this.run(route, connectionId, (base) => ({
325
- ...base,
326
- connectionId,
327
- headers,
328
- query,
329
- session
330
- }), options);
331
- return {
332
- accepted: true,
333
- connection: {
334
- id: connectionId,
335
- data: returned && typeof returned === "object" ? returned : {}
336
- }
337
- };
338
- } catch (error) {
339
- if (error instanceof HttpError) return {
340
- accepted: false,
341
- status: error.statusCode,
342
- statusText: error.statusMessage,
343
- error
344
- };
345
- this.options.logger.error({
346
- err: error,
347
- connectionId
348
- }, "WebSocket connect handler failed");
349
- return {
350
- accepted: false,
351
- status: 500,
352
- statusText: "Internal Server Error",
353
- error
354
- };
355
- }
356
- }
357
- /**
358
- * Parse, validate and run one inbound frame. The reply — the handler's
359
- * return, encoded — and every `$error` are written with `write`; an error
360
- * is a frame, never a close. A binary frame is refused: frames are text.
361
- */
362
- async message(connection, raw, write, options = {}) {
363
- if (typeof raw !== "string") return this.error(write, {}, "Frames are JSON text.");
364
- let parsed;
365
- try {
366
- parsed = JSON.parse(raw);
367
- } catch {
368
- return this.error(write, {}, "Frames are JSON.");
369
- }
370
- const frame = this.frame.decode(parsed);
371
- if (!frame) return this.error(write, { id: this.frame.idOf(parsed) }, `A frame names its \`${this.frame.key}\`.`);
372
- const { action, id } = frame;
373
- const route = this.routes.get(action) ?? this.routes.get("$default");
374
- if (!route) return this.error(write, {
375
- action,
376
- id
377
- }, `No route answers '${action}'.`);
378
- let body = frame.data;
379
- if (route.schema) {
380
- const result = await route.schema["~standard"].validate(frame.data);
381
- if (result.issues) return this.error(write, {
382
- action,
383
- id
384
- }, "The frame was invalid.", result.issues);
385
- body = result.value;
386
- }
387
- try {
388
- const returned = await this.run(route, connection.id, (base) => ({
389
- ...base,
390
- connection,
391
- body,
392
- reply: (message) => write(JSON.stringify(message))
393
- }), options);
394
- if (returned !== void 0) write(this.frame.encode(action, returned, id));
395
- return {
396
- ok: true,
397
- action,
398
- ...id !== void 0 ? { id } : {},
399
- returned
400
- };
401
- } catch (error) {
402
- if (error instanceof HttpError) return this.error(write, {
403
- action,
404
- id
405
- }, error.message, void 0, error);
406
- this.options.logger.error({
407
- err: error,
408
- connectionId: connection.id,
409
- action
410
- }, "WebSocket route failed");
411
- return this.error(write, {
412
- action,
413
- id
414
- }, "The route failed.", void 0, error);
415
- }
416
- }
417
- /**
418
- * Run the disconnect handler for a connection that has closed. What it
419
- * throws is logged and returned, never thrown: the socket is gone either
420
- * way.
421
- */
422
- async disconnect(connection, close, options = {}) {
423
- const route = this.lifecycle.disconnect;
424
- if (!route) return { ok: true };
425
- try {
426
- await this.run(route, connection.id, (base) => ({
427
- ...base,
428
- connection,
429
- ...close
430
- }), options);
431
- return { ok: true };
432
- } catch (error) {
433
- this.options.logger.error({
434
- err: error,
435
- connectionId: connection.id
436
- }, "WebSocket disconnect handler failed");
437
- return {
438
- ok: false,
439
- error
440
- };
441
- }
442
- }
443
- /** Run a handler with its services, inside a request context of its own. */
444
- async run(route, connectionId, context, options) {
445
- const logger = this.options.logger.child({
446
- connectionId,
447
- action: route.action
448
- });
449
- return runWithRequestContext({
450
- logger,
451
- requestId: connectionId,
452
- startTime: Date.now(),
453
- operation: `ws ${route.action}`
454
- }, async () => {
455
- const services = await this.services(route, options.services);
456
- return route.handler(context({
457
- services,
458
- logger,
459
- sockets: this.sockets
460
- }));
461
- });
462
- }
463
- /** The route's services: the overrides it names, the rest registered. */
464
- async services(route, overrides = {}) {
465
- const given = {};
466
- const wanted = route.services.filter((service) => {
467
- if (!Object.hasOwn(overrides, service.serviceName)) return true;
468
- given[service.serviceName] = overrides[service.serviceName];
469
- return false;
470
- });
471
- return {
472
- ...wanted.length ? await ServiceDiscovery.getInstance(this.options.envParser).register([...wanted]) : {},
473
- ...given
474
- };
475
- }
476
- error(write, at, message, issues, error) {
477
- write(this.frame.encode("$error", {
478
- message,
479
- ...issues ? { issues } : {}
480
- }, at.id));
481
- return {
482
- ok: false,
483
- ...at.action !== void 0 ? { action: at.action } : {},
484
- ...at.id !== void 0 ? { id: at.id } : {},
485
- message,
486
- ...issues ? { issues } : {},
487
- ...error !== void 0 ? { error } : {}
488
- };
489
- }
490
- };
491
- //#endregion
492
- //#region src/websocket/route.ts
493
- /**
494
- * A handler bound to a WebSocket surface — what `realtime.route('chat.send')
495
- * …handle()` returns, and what a file exports.
496
- *
497
- * Carries `surface` and `constructs` the way an endpoint does, so discovery
498
- * records what its process reaches without knowing what a route is.
499
- */
500
- var WebSocketRoute = class {
501
- kind;
502
- action;
503
- surface;
504
- services;
505
- constructs;
506
- handler;
507
- schema;
508
- __IS_WEBSOCKET_ROUTE__ = true;
509
- static isRoute(value) {
510
- return Boolean(value && value.__IS_WEBSOCKET_ROUTE__ === true);
511
- }
512
- constructor(kind, action, surface, services, constructs, handler, schema) {
513
- this.kind = kind;
514
- this.action = action;
515
- this.surface = surface;
516
- this.services = services;
517
- this.constructs = constructs;
518
- this.handler = handler;
519
- this.schema = schema;
520
- }
521
- };
522
- /** The builder `connect()`, `disconnect()` and `route()` start. */
523
- var WebSocketRouteBuilder = class WebSocketRouteBuilder {
524
- kind;
525
- action;
526
- surface;
527
- _services;
528
- _constructs;
529
- schema;
530
- constructor(kind, action, surface, _services = [], _constructs = [], schema) {
531
- this.kind = kind;
532
- this.action = action;
533
- this.surface = surface;
534
- this._services = _services;
535
- this._constructs = _constructs;
536
- this.schema = schema;
537
- }
538
- /** The schema a frame's `data` must satisfy before the handler runs. */
539
- body(schema) {
540
- return new WebSocketRouteBuilder(this.kind, this.action, this.surface, this._services, this._constructs, schema);
541
- }
542
- /** What the handler reaches, as `services.<id>` — per route, as an endpoint's. */
543
- dependsOn(constructs) {
544
- return new WebSocketRouteBuilder(this.kind, this.action, this.surface, [...this._services, ...servicesOf(constructs)], idsOf(constructs, this._constructs), this.schema);
545
- }
546
- /**
547
- * The handler. A message handler's return value, when there is one, is
548
- * sent back to the connection as the reply to that frame; a connect
549
- * handler's is kept as the connection's `data`.
550
- */
551
- handle(handler) {
552
- return new WebSocketRoute(this.kind, this.action, this.surface, this._services, this._constructs, handler, this.schema);
553
- }
554
- };
555
- /** The instance a connection id was issued by: everything before its dot. */
556
- function instanceOf(connectionId) {
557
- const dot = connectionId.indexOf(".");
558
- return dot > 0 ? connectionId.slice(0, dot) : void 0;
559
- }
560
- /**
561
- * A publisher's sink over a transport: a send goes to the instance each
562
- * connection id names, a broadcast to every instance. What `services.<id>`
563
- * sends through, and what the Node adaptor's own `sockets` do.
564
- */
565
- var TransportSink = class {
566
- transport;
567
- local;
568
- constructor(transport, local) {
569
- this.transport = transport;
570
- this.local = local;
571
- }
572
- send(ids, payload) {
573
- return this.each(ids, (group) => ({
574
- kind: "send",
575
- ids: group,
576
- payload
577
- }));
578
- }
579
- async broadcast(payload, except) {
580
- await this.transport.publish("*", {
581
- kind: "broadcast",
582
- payload,
583
- ...except?.length ? { except } : {}
584
- });
585
- }
586
- close(ids, code, reason) {
587
- return this.each(ids, (group) => ({
588
- kind: "close",
589
- ids: group,
590
- code,
591
- reason
592
- }));
593
- }
594
- /** One delivery per process that holds any of `ids`. */
595
- async each(ids, delivery) {
596
- const byInstance = /* @__PURE__ */ new Map();
597
- for (const id of ids) {
598
- const instance = instanceOf(id);
599
- if (!instance) continue;
600
- const group = byInstance.get(instance) ?? [];
601
- group.push(id);
602
- byInstance.set(instance, group);
603
- }
604
- await Promise.all([...byInstance].map(([instance, group]) => this.local?.instance === instance ? this.local.deliver(delivery(group)) : this.transport.publish(instance, delivery(group))));
605
- }
606
- };
607
- /** A connection string names no transport this package knows. */
608
- var UnsupportedWebSocketTransport = class extends Error {
609
- connectionString;
610
- constructor(connectionString) {
611
- super(`'${redact(connectionString)}' is not a WebSocket publisher connection string. Use redis://, rediss:// or memory:// — gkm composes it as <ID>_PUBLISHER_CONNECTION_STRING.`);
612
- this.connectionString = connectionString;
613
- this.name = "UnsupportedWebSocketTransport";
614
- }
615
- };
616
- /** The scheme alone, so an error never prints a password. */
617
- function redact(connectionString) {
618
- const scheme = connectionString.split("://")[0];
619
- return scheme && scheme !== connectionString ? `${scheme}://…` : connectionString.slice(0, 12);
620
- }
621
- const key = Symbol.for("@geekmidas/constructs/websocket/memory");
622
- const registry = globalThis;
623
- registry[key] ??= /* @__PURE__ */ new Map();
624
- const channels = registry[key];
625
- /**
626
- * In one process: the server and whoever sends meet in a map, keyed by the
627
- * channel the connection string names.
628
- */
629
- var MemoryTransport = class {
630
- channel;
631
- subscribed = /* @__PURE__ */ new Set();
632
- constructor(channel) {
633
- this.channel = channel;
634
- }
635
- async publish(instance, delivery) {
636
- const instances = channels.get(this.channel);
637
- if (!instances) return;
638
- if (instance === "*") {
639
- for (const receive of instances.values()) receive(delivery);
640
- return;
641
- }
642
- instances.get(instance)?.(delivery);
643
- }
644
- async subscribe(instance, receive) {
645
- let instances = channels.get(this.channel);
646
- if (!instances) {
647
- instances = /* @__PURE__ */ new Map();
648
- channels.set(this.channel, instances);
649
- }
650
- instances.set(instance, receive);
651
- this.subscribed.add(instance);
652
- }
653
- async close() {
654
- const instances = channels.get(this.channel);
655
- for (const instance of this.subscribed) instances?.delete(instance);
656
- this.subscribed.clear();
657
- }
658
- };
659
- /**
660
- * Over Redis pub/sub: one channel per instance and one for broadcasts, under
661
- * a prefix that keeps two surfaces — or two projects on one Redis — apart.
662
- * Channels are not scoped by database index, so the prefix is what does it.
663
- *
664
- * Publishing and subscribing take separate connections, because a connection
665
- * that has subscribed can do nothing else.
666
- */
667
- var RedisTransport = class {
668
- client;
669
- prefix;
670
- subscriber;
671
- closed;
672
- constructor(client, prefix) {
673
- this.client = client;
674
- this.prefix = prefix;
675
- }
676
- channel(instance) {
677
- return `${this.prefix}:${instance}`;
678
- }
679
- async publish(instance, delivery) {
680
- await this.client.publish(this.channel(instance), JSON.stringify(delivery));
681
- }
682
- async subscribe(instance, receive) {
683
- const subscriber = this.client.duplicate();
684
- this.subscriber = subscriber;
685
- const own = this.channel(instance);
686
- const every = this.channel("*");
687
- subscriber.on("message", (channel, message) => {
688
- if (channel !== own && channel !== every) return;
689
- receive(JSON.parse(message));
690
- });
691
- await subscriber.subscribe(own, every);
692
- }
693
- /** Idempotent: the server and a shutdown hook may both close it. */
694
- close() {
695
- this.closed ??= Promise.all([this.subscriber?.quit(), this.client.quit()]).then(() => void 0);
696
- return this.closed;
697
- }
698
- };
699
- /**
700
- * The transport a connection string names.
701
- *
702
- * `redis://` and `rediss://` take an optional `channel` query parameter, the
703
- * prefix every channel is named under; `memory://<channel>` is in-process.
704
- * Absent, the channel is `fallback` — the surface's own.
705
- */
706
- async function transportFromConnectionString(connectionString, fallback) {
707
- if (connectionString.startsWith("memory://")) return new MemoryTransport(connectionString.slice(9) || fallback);
708
- const url = URL.canParse(connectionString) ? new URL(connectionString) : void 0;
709
- if (!url) throw new UnsupportedWebSocketTransport(connectionString);
710
- if (url.protocol === "redis:" || url.protocol === "rediss:") {
711
- const channel = url.searchParams.get("channel") || fallback;
712
- url.searchParams.delete("channel");
713
- const { Redis } = await import("ioredis");
714
- return new RedisTransport(new Redis(url.toString(), {
715
- maxRetriesPerRequest: null,
716
- lazyConnect: false
717
- }), channel);
718
- }
719
- throw new UnsupportedWebSocketTransport(connectionString);
720
- }
721
- //#endregion
722
- //#region src/websocket/server.ts
723
- /**
724
- * The Node adaptor: the process that holds a WebSocket surface's sockets.
725
- *
726
- * Node's own `http` server and `ws`, nothing between them. This owns what
727
- * only a real socket has — the upgrade, the Origin check, connection ids,
728
- * the heartbeat, backpressure — and hands the rest to the surface's
729
- * `WebSocketCore`: a handshake to `connect()`, each frame to `message()`, a
730
- * close to `disconnect()`. The HTTP server is whatever the entry started —
731
- * the generated one serves `/health` on the same port — and this attaches to
732
- * its `upgrade` event.
733
- */
734
- /** Close codes a client sees. */
735
- const CLOSE = {
736
- normal: 1e3,
737
- /** The process is stopping; reconnect and land on another. */
738
- serviceRestart: 1012,
739
- /** It stopped reading, and what was queued for it passed the limit. */
740
- tooSlow: 1013
741
- };
742
- var WebSocketSurfaceServer = class WebSocketSurfaceServer {
743
- wss;
744
- options;
745
- /** This process, as connection ids name it. */
746
- instance = randomBytes(6).toString("hex");
747
- /** Where each handshake, frame and close is handed. */
748
- core;
749
- held = /* @__PURE__ */ new Map();
750
- heartbeat;
751
- trusted;
752
- next = 0;
753
- closing = false;
754
- constructor(wss, options) {
755
- this.wss = wss;
756
- this.options = options;
757
- this.core = options.core(new TransportSink(options.transport, {
758
- instance: this.instance,
759
- deliver: (delivery) => this.deliver(delivery)
760
- }));
761
- this.trusted = [...options.trustedOrigins, ...ownOrigins(options.url)];
762
- this.heartbeat = setInterval(() => this.beat(), options.heartbeatMs ?? 3e4);
763
- this.heartbeat.unref();
764
- }
765
- static async start(options) {
766
- const { WebSocketServer } = await import("ws");
767
- const wss = new WebSocketServer({
768
- noServer: true,
769
- maxPayload: options.maxPayload ?? 1048576,
770
- perMessageDeflate: false,
771
- clientTracking: false
772
- });
773
- const server = new WebSocketSurfaceServer(wss, options);
774
- await options.transport.subscribe(server.instance, (delivery) => server.deliver(delivery));
775
- return server;
776
- }
777
- /** `sockets` in a route: local sends skip the transport. */
778
- get publisher() {
779
- return this.core.sockets;
780
- }
781
- /** How many sockets this process holds. */
782
- get size() {
783
- return this.held.size;
784
- }
785
- /** Take over `server`'s upgrades. */
786
- attach(server) {
787
- server.on("upgrade", (request, socket, head) => {
788
- this.upgrade(request, socket, head);
789
- });
790
- }
791
- /** Upgrade one request, or refuse it with a status line. */
792
- async upgrade(request, socket, head) {
793
- if (this.closing) return refuse(socket, 503, "Service Unavailable");
794
- const origin = request.headers.origin;
795
- if (origin && !trustsOrigin(origin, this.trusted)) return refuse(socket, 403, "Forbidden");
796
- const outcome = await this.core.connect({
797
- connectionId: `${this.instance}.${(this.next++).toString(36)}`,
798
- headers: headersOf(request),
799
- query: new URL(request.url ?? "/", "http://localhost").searchParams
800
- });
801
- if (!outcome.accepted) return refuse(socket, outcome.status, outcome.statusText);
802
- if (socket.destroyed) return;
803
- this.wss.handleUpgrade(request, socket, head, (ws) => this.open(ws, outcome.connection));
804
- }
805
- open(socket, connection) {
806
- const held = {
807
- socket,
808
- connection,
809
- alive: true
810
- };
811
- this.held.set(connection.id, held);
812
- const write = (payload) => this.write(held, payload);
813
- socket.on("pong", () => {
814
- held.alive = true;
815
- });
816
- socket.on("message", (raw, isBinary) => {
817
- held.alive = true;
818
- this.core.message(connection, isBinary ? bytesOf(raw) : raw.toString(), write);
819
- });
820
- socket.on("error", () => socket.terminate());
821
- socket.on("close", (code, reason) => {
822
- this.held.delete(connection.id);
823
- this.core.disconnect(connection, {
824
- code,
825
- reason: reason.toString()
826
- });
827
- });
828
- }
829
- /** Write, unless the socket has stopped reading and its queue is full. */
830
- write(held, payload) {
831
- const { socket } = held;
832
- if (socket.readyState !== socket.OPEN) return;
833
- if (socket.bufferedAmount > (this.options.maxBufferedBytes ?? 4194304)) {
834
- socket.close(CLOSE.tooSlow, "Too slow");
835
- return;
836
- }
837
- socket.send(payload);
838
- }
839
- /** What the transport, or a local publisher, asked of this process. */
840
- deliver(delivery) {
841
- switch (delivery.kind) {
842
- case "send":
843
- for (const id of delivery.ids) {
844
- const held = this.held.get(id);
845
- if (held) this.write(held, delivery.payload);
846
- }
847
- return;
848
- case "broadcast": {
849
- const except = delivery.except ? new Set(delivery.except) : void 0;
850
- for (const [id, held] of this.held) if (!except?.has(id)) this.write(held, delivery.payload);
851
- return;
852
- }
853
- case "close":
854
- for (const id of delivery.ids) this.held.get(id)?.socket.close(delivery.code, delivery.reason);
855
- return;
856
- }
857
- }
858
- /** Drop every socket that missed the last ping, and ping the rest. */
859
- beat() {
860
- for (const [id, held] of this.held) {
861
- if (!held.alive) {
862
- held.socket.terminate();
863
- this.held.delete(id);
864
- continue;
865
- }
866
- held.alive = false;
867
- held.socket.ping();
868
- }
869
- }
870
- /**
871
- * Stop: refuse new upgrades, close every socket with `code` — 1012 tells
872
- * a client to reconnect, and it lands on a process that is still up — and
873
- * leave the transport.
874
- */
875
- async close(code = CLOSE.serviceRestart, reason = "Restarting") {
876
- if (this.closing) return;
877
- this.closing = true;
878
- clearInterval(this.heartbeat);
879
- const closed = [...this.held.values()].map(({ socket }) => new Promise((resolve) => {
880
- if (socket.readyState === socket.CLOSED) return resolve();
881
- socket.once("close", () => resolve());
882
- socket.close(code, reason);
883
- setTimeout(() => {
884
- socket.terminate();
885
- resolve();
886
- }, 2e3).unref();
887
- }));
888
- await Promise.all(closed);
889
- await this.options.transport.close();
890
- this.wss.close();
891
- }
892
- };
893
- /**
894
- * The origins a client of the surface's own address sends: the `https://`
895
- * one a native socket derives from `wss://`, and the address's own.
896
- */
897
- function ownOrigins(url) {
898
- if (!url || !URL.canParse(url)) return [];
899
- const own = new URL(url);
900
- const web = new URL(url.replace(/^ws(s?):/i, "http$1:"));
901
- return [.../* @__PURE__ */ new Set([`${own.protocol}//${own.host}`, web.origin])];
902
- }
903
- /** A binary frame's bytes, however `ws` delivered them. */
904
- function bytesOf(raw) {
905
- if (Array.isArray(raw)) return Buffer.concat(raw);
906
- return raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw;
907
- }
908
- function headersOf(request) {
909
- const headers = new Headers();
910
- for (const [name, value] of Object.entries(request.headers)) {
911
- if (value === void 0) continue;
912
- for (const one of Array.isArray(value) ? value : [value]) headers.append(name, one);
913
- }
914
- return headers;
915
- }
916
- function refuse(socket, status, message) {
917
- if (!socket.destroyed) socket.end(`HTTP/1.1 ${status} ${message}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
918
- }
919
- //#endregion
920
- //#region src/websocket-api.ts
921
- /** A replica count that is not a whole number of at least one. */
922
- var InvalidReplicaCount = class extends Error {
923
- id;
924
- replicas;
925
- constructor(id, replicas) {
926
- super(`${id} asks for ${replicas} replicas. A surface runs on at least one process — give a whole number of 1 or more.`);
927
- this.id = id;
928
- this.replicas = replicas;
929
- this.name = "InvalidReplicaCount";
930
- }
931
- };
932
- var WebSocketApi = class WebSocketApi {
933
- config;
934
- authenticator;
935
- id;
936
- keys;
937
- logger;
938
- envParser;
939
- telemetry;
940
- /**
941
- * The shape its frames take — `{ action, data }`, or flat under
942
- * `discriminator`. What a client of the surface decodes by.
943
- */
944
- frame;
945
- /**
946
- * The surface as a dependency: `services.<id>` is its publisher, so an
947
- * endpoint sends to a socket the way a route beside it does.
948
- */
949
- service;
950
- constructor(id, config, authenticator) {
951
- this.config = config;
952
- this.authenticator = authenticator;
953
- const canonical = canonicalId(id);
954
- this.id = canonical;
955
- const replicas = config.replicas ?? 1;
956
- if (!Number.isInteger(replicas) || replicas < 1) throw new InvalidReplicaCount(canonical, replicas);
957
- const frame = new FrameShape(canonical, config.frame?.discriminator);
958
- if (config.messages) frame.check(config.messages);
959
- this.frame = config.frame ? { discriminator: config.frame.discriminator } : {};
960
- this.keys = {
961
- url: provideKey(canonical, "url"),
962
- trustedOrigins: provideKey(canonical, "trustedOrigins"),
963
- publisherConnectionString: provideKey(canonical, "publisherConnectionString")
964
- };
965
- this.logger = config.logger ?? DEFAULT_LOGGER;
966
- this.telemetry = config.telemetry;
967
- this.envParser = envParserFor(config.envParser ? {
968
- id: canonical,
969
- envParser: config.envParser
970
- } : void 0);
971
- const envVar = this.keys.publisherConnectionString;
972
- const channel = channelOf(canonical);
973
- const declared = this.declared;
974
- this.service = {
975
- serviceName: serviceKey(canonical),
976
- async register({ envParser }) {
977
- const { connectionString } = envParser.create((get) => ({ connectionString: get(envVar).string() })).parse();
978
- const transport = await transportFromConnectionString(connectionString, channel);
979
- onShutdown(() => transport.close());
980
- return new WebSocketPublisher(new TransportSink(transport), declared, frame);
981
- }
982
- };
983
- }
984
- /** The handler a connection's upgrade runs: refuse it, or say who it is. */
985
- connect() {
986
- return new WebSocketRouteBuilder("connect", "$connect", { id: this.id });
987
- }
988
- /** The handler a closed connection runs. */
989
- disconnect() {
990
- return new WebSocketRouteBuilder("disconnect", "$disconnect", { id: this.id });
991
- }
992
- /**
993
- * The handler for frames whose `action` — or, for flat frames, whose
994
- * discriminator — is `action`. `$default` answers
995
- * any action nothing else does.
996
- */
997
- route(action) {
998
- return new WebSocketRouteBuilder("message", action, { id: this.id });
999
- }
1000
- /** What authenticates a connection — its session reaches `connect()`. */
1001
- auth(construct) {
1002
- return new WebSocketApi(this.id, this.config, construct);
1003
- }
1004
- /**
1005
- * Serve it: the routes exported by `modules` that were built from this
1006
- * surface, on whatever HTTP server `attach` is handed.
1007
- *
1008
- * `app` answers plain HTTP — the generated entry puts `/health` in front
1009
- * of it — and `attach` takes over the server's upgrades. The sockets are
1010
- * closed with 1012 when the server shuts down.
1011
- */
1012
- async server(options) {
1013
- const { Hono } = await import("hono");
1014
- const { connectionString, origins, url } = options.envParser.create((get) => ({
1015
- connectionString: get(this.keys.publisherConnectionString).string().default(`memory://${channelOf(this.id)}`),
1016
- origins: get(this.keys.trustedOrigins).string().default("").transform((value) => value.split(",").map((origin) => origin.trim()).filter(Boolean)),
1017
- url: get(this.keys.url).string().optional()
1018
- })).parse();
1019
- const server = await WebSocketSurfaceServer.start({
1020
- core: (sink) => this.core({
1021
- envParser: options.envParser,
1022
- sink,
1023
- ...options.modules ? { modules: options.modules } : {}
1024
- }),
1025
- transport: await transportFromConnectionString(connectionString, channelOf(this.id)),
1026
- trustedOrigins: origins,
1027
- ...url ? { url } : {},
1028
- ...this.config.heartbeat ? { heartbeatMs: this.config.heartbeat * 1e3 } : {},
1029
- ...this.config.maxPayload ? { maxPayload: this.config.maxPayload } : {}
1030
- });
1031
- onShutdown(() => server.close());
1032
- const app = new Hono();
1033
- app.get("/health", (c) => c.json({
1034
- status: "ok",
1035
- connections: server.size
1036
- }));
1037
- app.get("/", (c) => c.json({
1038
- surface: this.id,
1039
- connections: server.size
1040
- }, 426, { Upgrade: "websocket" }));
1041
- return {
1042
- app,
1043
- attach: (http) => server.attach(http),
1044
- release: () => server.close(),
1045
- server
1046
- };
1047
- }
1048
- /**
1049
- * The surface with no socket in it — what every runtime serves. The
1050
- * routes exported by `modules` that were built from this surface answer
1051
- * its frames; `sink` is where its handlers' `sockets` send.
1052
- *
1053
- * `server()` is the Node adaptor over it. Another runtime (a Lambda
1054
- * behind API Gateway, a test) builds one with a sink of its own and
1055
- * calls `connect()`, `message()` and `disconnect()` per connection id.
1056
- *
1057
- * @throws {DuplicateWebSocketRoute} when two routes answer one action.
1058
- */
1059
- core(options) {
1060
- return new WebSocketCore({
1061
- surface: this.id,
1062
- routes: (options.modules ?? []).flatMap((module) => Object.values(module).filter(WebSocketRoute.isRoute)),
1063
- sink: options.sink,
1064
- envParser: options.envParser,
1065
- logger: this.logger,
1066
- ...this.config.frame ? { frame: this.config.frame } : {},
1067
- ...this.declared ? { messages: this.declared.messages } : {},
1068
- ...this.authenticator ? { authenticator: this.authenticator } : {}
1069
- });
1070
- }
1071
- /** The declared messages, with the surface they are checked for. */
1072
- get declared() {
1073
- return this.config.messages ? {
1074
- surface: this.id,
1075
- messages: this.config.messages
1076
- } : void 0;
1077
- }
1078
- declare() {
1079
- return [{
1080
- kind: "websocket-api",
1081
- id: this.id,
1082
- path: this.config.path,
1083
- ...this.config.subdomain ? { subdomain: this.config.subdomain } : {},
1084
- ...this.authenticator ? { auth: edgeTo(this.authenticator) } : {},
1085
- ...this.config.telemetry ? { telemetry: this.config.telemetry.id } : {},
1086
- ...this.config.replicas && this.config.replicas > 1 ? { replicas: this.config.replicas } : {},
1087
- provides: [
1088
- this.keys.url,
1089
- this.keys.trustedOrigins,
1090
- this.keys.publisherConnectionString
1091
- ]
1092
- }];
1093
- }
1094
- };
1095
- /** The prefix a surface's channels are named under. */
1096
- function channelOf(id) {
1097
- return `gkm:ws:${id}`;
1098
- }
1099
- //#endregion
1100
- export { CLOSE, DuplicateWebSocketRoute, InvalidReplicaCount, InvalidWebSocketMessage, MemoryTransport, RedisTransport, TransportSink, UnknownWebSocketMessage, UnsupportedWebSocketTransport, WebSocketApi, WebSocketCore, WebSocketDataHasDiscriminator, WebSocketDataNotAnObject, WebSocketMessageDeclaresDiscriminator, WebSocketMessageNotAnObject, WebSocketPublisher, WebSocketRoute, WebSocketRouteBuilder, WebSocketSurfaceServer, transportFromConnectionString };
1101
-
1102
- //# sourceMappingURL=websocket-api.mjs.map
1
+ import { A as WebSocketMessageNotAnObject, C as WebSocketCore, D as WebSocketDataHasDiscriminator, E as WebSocketPublisher, O as WebSocketDataNotAnObject, S as DuplicateWebSocketRoute, T as UnknownWebSocketMessage, _ as LIMIT_CLOSE, a as MemoryTransport, b as TokenBucket, c as UnsupportedWebSocketTransport, d as WebSocketRouteBuilder, f as InvalidWebSocketRequest, g as InvalidWebSocketLimit, h as DEFAULT_WEBSOCKET_LIMITS, i as WebSocketSurfaceServer, k as WebSocketMessageDeclaresDiscriminator, l as transportFromConnectionString, m as TestWebSocketPublisher, n as WebSocketApi, o as RedisTransport, p as RecordingSink, r as CLOSE, s as TransportSink, t as InvalidReplicaCount, u as WebSocketRoute, v as MemoryLimitStore, w as InvalidWebSocketMessage, x as resolveLimits, y as RedisLimitStore } from "./websocket-api-BvKS9x-l.mjs";
2
+ export { CLOSE, DEFAULT_WEBSOCKET_LIMITS, DuplicateWebSocketRoute, InvalidReplicaCount, InvalidWebSocketLimit, InvalidWebSocketMessage, InvalidWebSocketRequest, LIMIT_CLOSE, MemoryLimitStore, MemoryTransport, RecordingSink, RedisLimitStore, RedisTransport, TestWebSocketPublisher, TokenBucket, TransportSink, UnknownWebSocketMessage, UnsupportedWebSocketTransport, WebSocketApi, WebSocketCore, WebSocketDataHasDiscriminator, WebSocketDataNotAnObject, WebSocketMessageDeclaresDiscriminator, WebSocketMessageNotAnObject, WebSocketPublisher, WebSocketRoute, WebSocketRouteBuilder, WebSocketSurfaceServer, resolveLimits, transportFromConnectionString };