effect-durable-agent 0.1.0-alpha.8 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/README.md +5 -5
  2. package/dist/assert-never-CoyUpoRB.js +18 -0
  3. package/dist/assert-never-CoyUpoRB.js.map +1 -0
  4. package/dist/{commands-Ce1ec6kH.d.ts → commands-BUquEZVP.d.ts} +31 -12
  5. package/dist/{compaction-BgDr5VJy.js → compaction-63iEDHHl.js} +63 -13
  6. package/dist/compaction-63iEDHHl.js.map +1 -0
  7. package/dist/{context-projection-n6Rdup0N.d.ts → context-projection-Bezx3drD.d.ts} +16 -40
  8. package/dist/{core-CYT6DBaS.d.ts → core-BcimKMIv.d.ts} +5 -3
  9. package/dist/delivery-2ZILvoRD.js +507 -0
  10. package/dist/delivery-2ZILvoRD.js.map +1 -0
  11. package/dist/delivery-D3MxW4wg.d.ts +3026 -0
  12. package/dist/domain/command-queues.d.ts +81 -2
  13. package/dist/domain/command-queues.js +1 -1
  14. package/dist/domain/command-queues.js.map +1 -1
  15. package/dist/domain/context-projection.d.ts +1 -1
  16. package/dist/domain/context-projection.js +1 -1
  17. package/dist/domain/context-projection.js.map +1 -1
  18. package/dist/domain/message-transcript.d.ts +36 -2
  19. package/dist/domain/message-transcript.js +10 -2
  20. package/dist/domain/message-transcript.js.map +1 -1
  21. package/dist/domain/model-usage.d.ts +1 -1
  22. package/dist/domain/model-usage.js +1 -1
  23. package/dist/domain/reduced-state-schema.d.ts +3 -992
  24. package/dist/domain/reduced-state-schema.js +126 -7
  25. package/dist/domain/reduced-state-schema.js.map +1 -1
  26. package/dist/domain/reduced-state.d.ts +2 -2
  27. package/dist/domain/reduced-state.js +936 -2
  28. package/dist/domain/reduced-state.js.map +1 -0
  29. package/dist/domain/run-scheduling.d.ts +2 -0
  30. package/dist/domain/run-scheduling.js +127 -0
  31. package/dist/domain/run-scheduling.js.map +1 -0
  32. package/dist/{durable-br2C1bWK.d.ts → durable-168Womqp.d.ts} +8535 -2859
  33. package/dist/{durable-BGFvX7Mh.js → durable-D13w1Qr3.js} +229 -15
  34. package/dist/durable-D13w1Qr3.js.map +1 -0
  35. package/dist/{envelope-DxQzo5rN.js → envelope-BCzKUq_z.js} +12 -3
  36. package/dist/envelope-BCzKUq_z.js.map +1 -0
  37. package/dist/{envelope-DkZyMIgp.d.ts → envelope-Che6KatU.d.ts} +70 -7
  38. package/dist/{event-factory-DTFdy0Cb.js → event-factory-_vF1bIJ7.js} +7 -3
  39. package/dist/event-factory-_vF1bIJ7.js.map +1 -0
  40. package/dist/{events-LZFNoESe.d.ts → events-DwTARLMv.d.ts} +139 -137
  41. package/dist/{id-generator-Ckl8_XWW.d.ts → id-generator-BKGoKjt-.d.ts} +3 -3
  42. package/dist/in-memory-CeODnZhE.js +150 -0
  43. package/dist/in-memory-CeODnZhE.js.map +1 -0
  44. package/dist/index.d.ts +8 -8
  45. package/dist/index.js +6 -6
  46. package/dist/interpreter-DKGJ1sSx.js +1452 -0
  47. package/dist/interpreter-DKGJ1sSx.js.map +1 -0
  48. package/dist/{keep-alive-Chl5SJxy.d.ts → keep-alive-_zFCUvt3.d.ts} +1 -2
  49. package/dist/{model-resolver-BPPJAsuh.d.ts → model-resolver-DeBDK8XO.d.ts} +11 -5
  50. package/dist/{model-usage-CdBEkTwU.d.ts → model-usage-0GeHwaaU.d.ts} +2 -3
  51. package/dist/records--54mZEBx.js +675 -0
  52. package/dist/records--54mZEBx.js.map +1 -0
  53. package/dist/reduced-state-B1cvy8N_.d.ts +51110 -0
  54. package/dist/reduced-state-schema-B98exWxQ.d.ts +2338 -0
  55. package/dist/{reducer-registry-aFjz_ZLT.d.ts → reducer-registry-DhGVzHBV.d.ts} +12 -6
  56. package/dist/run-scheduling-wakeup-Mjic4tb_.d.ts +24 -0
  57. package/dist/services/compaction.d.ts +2 -2
  58. package/dist/services/compaction.js +2 -2
  59. package/dist/services/id-generator.d.ts +1 -1
  60. package/dist/services/id-generator.js +6 -12
  61. package/dist/services/id-generator.js.map +1 -1
  62. package/dist/services/keep-alive.d.ts +1 -1
  63. package/dist/services/keep-alive.js.map +1 -1
  64. package/dist/services/model-call.d.ts +15 -0
  65. package/dist/services/model-call.js +15 -0
  66. package/dist/services/model-call.js.map +1 -0
  67. package/dist/services/model-resolver.d.ts +1 -1
  68. package/dist/services/model-resolver.js +1 -1
  69. package/dist/services/model-resolver.js.map +1 -1
  70. package/dist/services/prompt-projector.d.ts +2 -2
  71. package/dist/services/prompt-projector.js +49 -5
  72. package/dist/services/prompt-projector.js.map +1 -1
  73. package/dist/services/reducer-registry.d.ts +1 -1
  74. package/dist/services/reducer-registry.js +19 -6
  75. package/dist/services/reducer-registry.js.map +1 -1
  76. package/dist/services/run-scheduler.d.ts +2 -0
  77. package/dist/services/run-scheduler.js +25 -0
  78. package/dist/services/run-scheduler.js.map +1 -0
  79. package/dist/services/run-scheduling-wakeup.d.ts +2 -0
  80. package/dist/services/run-scheduling-wakeup.js +13 -0
  81. package/dist/services/run-scheduling-wakeup.js.map +1 -0
  82. package/dist/services/runtime-layer.d.ts +18 -31
  83. package/dist/services/runtime-layer.js +19 -13
  84. package/dist/services/runtime-layer.js.map +1 -1
  85. package/dist/services/runtime.d.ts +1 -1
  86. package/dist/services/runtime.js +31 -20
  87. package/dist/services/runtime.js.map +1 -1
  88. package/dist/services/session-event-observer.d.ts +1 -1
  89. package/dist/services/session-event-observer.js.map +1 -1
  90. package/dist/services/session-query.d.ts +1 -1
  91. package/dist/services/session-query.js +57 -10
  92. package/dist/services/session-query.js.map +1 -1
  93. package/dist/services/session-state.d.ts +1 -1
  94. package/dist/services/session-state.js +1 -1
  95. package/dist/services/session-store.d.ts +2 -2
  96. package/dist/services/session-store.js +127 -37
  97. package/dist/services/session-store.js.map +1 -1
  98. package/dist/services/sink-checkpoint-store.d.ts +1 -1
  99. package/dist/services/sink-checkpoint-store.js +2 -1
  100. package/dist/services/sink-checkpoint-store.js.map +1 -1
  101. package/dist/services/sink-registry.d.ts +2 -2
  102. package/dist/services/sink-registry.js +1 -1
  103. package/dist/services/span-names.d.ts +1 -1
  104. package/dist/services/span-names.js +6 -1
  105. package/dist/services/span-names.js.map +1 -1
  106. package/dist/services/tool-registry.d.ts +2 -2
  107. package/dist/services/tool-registry.js +12 -3
  108. package/dist/services/tool-registry.js.map +1 -1
  109. package/dist/services/tracing.d.ts +3 -3
  110. package/dist/services/tracing.js +2 -2
  111. package/dist/services/tracing.js.map +1 -1
  112. package/dist/{session-event-observer-DaFMKKNc.d.ts → session-event-observer-DlP9ITB2.d.ts} +3 -3
  113. package/dist/{session-state-aIqe9CLa.js → session-state-BehvUVyq.js} +669 -160
  114. package/dist/session-state-BehvUVyq.js.map +1 -0
  115. package/dist/session-store-BL6sfrnn.d.ts +3326 -0
  116. package/dist/{sink-checkpoint-store-M7qIxoSH.d.ts → sink-checkpoint-store-DvuHwvx_.d.ts} +3 -4
  117. package/dist/sink-registry-DskRcyOS.js +345 -0
  118. package/dist/sink-registry-DskRcyOS.js.map +1 -0
  119. package/dist/subscription-DZNWFDTV.d.ts +966 -0
  120. package/dist/subscription-DmO3BcdT.js +505 -0
  121. package/dist/subscription-DmO3BcdT.js.map +1 -0
  122. package/dist/testkit/layers.d.ts +31 -22
  123. package/dist/testkit/layers.js +23 -14
  124. package/dist/testkit/layers.js.map +1 -1
  125. package/dist/testkit/transcript.d.ts +226 -0
  126. package/dist/testkit/transcript.js +1475 -0
  127. package/dist/testkit/transcript.js.map +1 -0
  128. package/dist/{tool-registry-BJaVNtw4.d.ts → tool-registry-CHHUU9BN.d.ts} +44 -8
  129. package/dist/{tracing-BXHAkxkx.d.ts → tracing-BwjbF285.d.ts} +1 -2
  130. package/dist/transcript.d.ts +101 -0
  131. package/dist/transcript.js +107 -0
  132. package/dist/transcript.js.map +1 -0
  133. package/dist/types/commands.d.ts +2 -2
  134. package/dist/types/commands.js +8 -3
  135. package/dist/types/commands.js.map +1 -1
  136. package/dist/types/core.d.ts +2 -2
  137. package/dist/types/core.js +3 -1
  138. package/dist/types/core.js.map +1 -1
  139. package/dist/types/events/durable.d.ts +2 -2
  140. package/dist/types/events/durable.js +2 -2
  141. package/dist/types/events.d.ts +5 -5
  142. package/dist/types/events.js +3 -3
  143. package/dist/types/tracing.d.ts +1 -1
  144. package/dist/types/tracing.js.map +1 -1
  145. package/dist/websocket/events.d.ts +2 -0
  146. package/dist/websocket/events.js +2 -0
  147. package/dist/websocket.d.ts +2123 -2552
  148. package/dist/websocket.js +628 -442
  149. package/dist/websocket.js.map +1 -1
  150. package/dist/window-read-Brov9VdQ.d.ts +113 -0
  151. package/dist/window-read-DPFAA1hM.js +264 -0
  152. package/dist/window-read-DPFAA1hM.js.map +1 -0
  153. package/package.json +42 -14
  154. package/dist/command-queues-DdDB_aYM.d.ts +0 -462
  155. package/dist/compaction-BEor3jKv.d.ts +0 -165
  156. package/dist/compaction-BgDr5VJy.js.map +0 -1
  157. package/dist/durable-BGFvX7Mh.js.map +0 -1
  158. package/dist/envelope-DxQzo5rN.js.map +0 -1
  159. package/dist/event-factory-DTFdy0Cb.js.map +0 -1
  160. package/dist/event-factory-pFzsPlDs.d.ts +0 -87
  161. package/dist/index-BVVgDSdq.d.ts +0 -1
  162. package/dist/message-transcript-DQNlzxle.d.ts +0 -32
  163. package/dist/prompt-projector-f4ElyXCE.d.ts +0 -39
  164. package/dist/reduced-state-DF0-6mbR.js +0 -921
  165. package/dist/reduced-state-DF0-6mbR.js.map +0 -1
  166. package/dist/runtime-DbTCb32-.d.ts +0 -63
  167. package/dist/session-query-l8xpJYp8.d.ts +0 -45
  168. package/dist/session-state-YHFzOGDf.d.ts +0 -861
  169. package/dist/session-state-aIqe9CLa.js.map +0 -1
  170. package/dist/session-store-Cpi_NwTR.d.ts +0 -206
  171. package/dist/sink-registry-NDgeyzO0.js +0 -272
  172. package/dist/sink-registry-NDgeyzO0.js.map +0 -1
  173. package/dist/sink-registry-T1wOUuzq.d.ts +0 -133
@@ -0,0 +1,507 @@
1
+ import { Position, SequenceNumber } from "./types/core.js";
2
+ import { d as PositionedEvent, g as UnixEpochMillis, i as EventEnvelope } from "./envelope-BCzKUq_z.js";
3
+ import { U as EDADurableEvent } from "./durable-D13w1Qr3.js";
4
+ import { EDAEphemeralEvent } from "./types/events.js";
5
+ import * as Effect from "effect/Effect";
6
+ import * as Schema from "effect/Schema";
7
+ //#region src/websocket/protocol.ts
8
+ const PositiveInt = Schema.Int.check(Schema.isGreaterThan(0));
9
+ const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
10
+ /** Current EDA live-event WebSocket wire protocol version. */
11
+ const EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION = 1;
12
+ /** Flow-control policy announced by the server in the hello frame. */
13
+ const EDAWebSocketWireFlowControl = Schema.Struct({
14
+ ackTimeoutMs: PositiveInt,
15
+ /** Deprecated: servers no longer send heartbeat frames. Kept so deployed clients can decode hello. */
16
+ heartbeatIntervalMs: PositiveInt,
17
+ maxFrameBytes: PositiveInt,
18
+ maxFrameEvents: PositiveInt,
19
+ maxInFlightFrames: PositiveInt,
20
+ /** Suggested client-originated ping cadence; absent on servers that still send heartbeats. */
21
+ pingIntervalMs: Schema.optionalKey(PositiveInt),
22
+ subscriberBufferCapacityEvents: PositiveInt
23
+ });
24
+ /**
25
+ * Canonical client liveness ping message.
26
+ *
27
+ * The exact string matters: hibernation-capable hosts register it with
28
+ * WebSocket auto-response so the runtime answers without waking the object.
29
+ */
30
+ const EDA_WEB_SOCKET_PING_MESSAGE = "{\"_tag\":\"ping\"}";
31
+ /** Canonical server pong message paired with {@link EDA_WEB_SOCKET_PING_MESSAGE}. */
32
+ const EDA_WEB_SOCKET_PONG_MESSAGE = "{\"_tag\":\"pong\"}";
33
+ /** Client liveness ping; hosts answer with a pong and never ACK-track it. */
34
+ const EDAWebSocketWirePingFrame = Schema.Struct({ _tag: Schema.Literal("ping") });
35
+ /** Server liveness pong; clients may ignore it and must not ACK it. */
36
+ const EDAWebSocketWirePongFrame = Schema.Struct({ _tag: Schema.Literal("pong") });
37
+ const EDAWebSocketWireHelloFrame = Schema.Struct({
38
+ _tag: Schema.Literal("hello"),
39
+ protocolVersion: Schema.Literal(1),
40
+ subscriberId: Schema.NonEmptyString,
41
+ resumeSeq: NonNegativeInt,
42
+ flowControl: EDAWebSocketWireFlowControl
43
+ });
44
+ const EDAWebSocketWireHeartbeatFrame = Schema.Struct({
45
+ _tag: Schema.Literal("heartbeat"),
46
+ serverTimeMs: NonNegativeInt,
47
+ durableThroughSeq: NonNegativeInt
48
+ });
49
+ const EDAWebSocketWireLaggedFrame = Schema.Struct({
50
+ _tag: Schema.Literal("lagged"),
51
+ resumeSeq: NonNegativeInt,
52
+ reason: Schema.Literals(["buffer-overflow", "ack-timeout"])
53
+ });
54
+ const EDAWebSocketWireErrorFrame = Schema.Struct({
55
+ _tag: Schema.Literal("error"),
56
+ message: Schema.String
57
+ });
58
+ /**
59
+ * Client acknowledgement. `frameId` is the transport receipt: it cumulatively frees flow-control
60
+ * capacity. On a transcript socket `appliedUpdateSeq` is the client's applied cut, the last
61
+ * transcript update it applied completely, and `durableThroughSeq` is that update's
62
+ * `throughSeq`; both advance only on complete updates, never on a partial chunked transfer.
63
+ * Raw event sockets ignore `appliedUpdateSeq`.
64
+ */
65
+ const EDAWebSocketWireAckFrame = Schema.Struct({
66
+ _tag: Schema.Literal("ack"),
67
+ frameId: PositiveInt,
68
+ durableThroughSeq: NonNegativeInt,
69
+ appliedUpdateSeq: Schema.optionalKey(NonNegativeInt)
70
+ });
71
+ const EDAWebSocketWireClientFrame = Schema.Union([EDAWebSocketWireAckFrame, EDAWebSocketWirePingFrame]);
72
+ /** Complete framework-owned event union present on every EDA WebSocket. */
73
+ const EDAFrameworkWebSocketEvent = Schema.Union([EDADurableEvent, EDAEphemeralEvent]);
74
+ const makeEDAWebSocketDomainSchemas = (event) => {
75
+ const positionedEvent = Schema.Struct({
76
+ position: Position,
77
+ event
78
+ });
79
+ const eventsFrame = Schema.Struct({
80
+ _tag: Schema.Literal("events"),
81
+ frameId: PositiveInt,
82
+ events: Schema.NonEmptyArray(positionedEvent),
83
+ durableThroughSeq: NonNegativeInt
84
+ });
85
+ return {
86
+ event,
87
+ positionedEvent,
88
+ eventsFrame,
89
+ serverFrame: Schema.Union([
90
+ EDAWebSocketWireHelloFrame,
91
+ eventsFrame,
92
+ EDAWebSocketWireHeartbeatFrame,
93
+ EDAWebSocketWirePongFrame,
94
+ EDAWebSocketWireLaggedFrame,
95
+ EDAWebSocketWireErrorFrame
96
+ ])
97
+ };
98
+ };
99
+ makeEDAWebSocketDomainSchemas(EventEnvelope);
100
+ const makeEDAWebSocketWireProtocolFromEventSchema = (event) => {
101
+ const domain = makeEDAWebSocketDomainSchemas(event);
102
+ const encodeDomainServerFrame = Schema.encodeSync(domain.serverFrame);
103
+ const encodeUnknownDomainServerFrame = Schema.encodeUnknownSync(domain.serverFrame);
104
+ const encodeServerFrame = (frame) => JSON.stringify(encodeDomainServerFrame(frame));
105
+ return {
106
+ domain,
107
+ wire: {
108
+ event: Schema.toEncoded(domain.event),
109
+ positionedEvent: Schema.toEncoded(domain.positionedEvent),
110
+ eventsFrame: Schema.toEncoded(domain.eventsFrame),
111
+ serverFrame: Schema.toEncoded(domain.serverFrame),
112
+ clientFrame: EDAWebSocketWireClientFrame
113
+ },
114
+ encodeServerFrame,
115
+ host: { encodeServerFrame: (frame) => JSON.stringify(encodeUnknownDomainServerFrame(frame)) }
116
+ };
117
+ };
118
+ /** Strict framework-only protocol used when an app registers no custom events. */
119
+ const edaFrameworkWebSocketWireProtocol = makeEDAWebSocketWireProtocolFromEventSchema(EDAFrameworkWebSocketEvent);
120
+ /**
121
+ * Bind the generic EDA WebSocket transport to one app's custom event schema.
122
+ *
123
+ * Framework durable and ephemeral events are included automatically. Future EDA
124
+ * apps register only their custom events. Servers use the returned domain schemas
125
+ * and typed encoder; external consumers decode with the wire schemas. Pass the
126
+ * returned `host` adapter to the selected host package.
127
+ */
128
+ const makeEDAWebSocketWireProtocol = (options) => makeEDAWebSocketWireProtocolFromEventSchema(Schema.Union([EDAFrameworkWebSocketEvent, options.appEvents]));
129
+ //#endregion
130
+ //#region src/websocket/messages.ts
131
+ /** Current EDA live-event WebSocket protocol version. */
132
+ const EDA_WEB_SOCKET_PROTOCOL_VERSION = 1;
133
+ /** WebSocket close code used when a subscriber cannot keep up with live delivery. */
134
+ const EDA_WS_CLOSE_LAGGED = 4008;
135
+ /** WebSocket close code used for normal host-driven shutdown. */
136
+ const EDA_WS_CLOSE_GOING_AWAY = 1001;
137
+ /** WebSocket close code used for malformed client protocol messages. */
138
+ const EDA_WS_CLOSE_PROTOCOL_ERROR = 1002;
139
+ /** WebSocket close code used when the host cannot send a frame. */
140
+ const EDA_WS_CLOSE_SEND_FAILED = 1011;
141
+ /** WebSocket close code used for unsupported binary messages. */
142
+ const EDA_WS_CLOSE_UNSUPPORTED_DATA = 1003;
143
+ /** Live subscriber identity persisted in WebSocket attachments. */
144
+ const SubscriberId = Schema.NonEmptyString.pipe(Schema.brand("SubscriberId"));
145
+ /** Per-connection monotonically increasing server frame id. */
146
+ const FrameId = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).pipe(Schema.brand("FrameId"));
147
+ /** Flow-control policy announced by the server in the hello frame. */
148
+ const EDAWebSocketFlowControl = EDAWebSocketWireFlowControl;
149
+ /** Default bounded policy sized for fast model deltas and large durable tool/message events. */
150
+ const defaultEDAWebSocketFlowControl = {
151
+ ackTimeoutMs: 3e4,
152
+ heartbeatIntervalMs: 1e4,
153
+ maxFrameBytes: 262144,
154
+ maxFrameEvents: 1,
155
+ maxInFlightFrames: 16,
156
+ pingIntervalMs: 3e4,
157
+ subscriberBufferCapacityEvents: 2048
158
+ };
159
+ /** First server frame; announces protocol and flow-control policy. */
160
+ const EDAWebSocketHelloFrame = Schema.Struct({
161
+ ...EDAWebSocketWireHelloFrame.fields,
162
+ subscriberId: SubscriberId,
163
+ resumeSeq: SequenceNumber
164
+ });
165
+ /** Ordered positioned events delivered to the client. */
166
+ const EDAWebSocketEventsFrame = Schema.Struct({
167
+ _tag: Schema.Literal("events"),
168
+ frameId: FrameId,
169
+ events: Schema.NonEmptyArray(PositionedEvent),
170
+ durableThroughSeq: SequenceNumber
171
+ });
172
+ /**
173
+ * Deprecated idle server keepalive frame.
174
+ *
175
+ * Servers no longer send heartbeats; the schema remains so deployed clients
176
+ * keep decoding the server frame union. Liveness is client-originated via
177
+ * {@link EDAWebSocketPingFrame} and the host-level auto-response pong.
178
+ */
179
+ const EDAWebSocketHeartbeatFrame = Schema.Struct({
180
+ ...EDAWebSocketWireHeartbeatFrame.fields,
181
+ serverTimeMs: UnixEpochMillis,
182
+ durableThroughSeq: SequenceNumber
183
+ });
184
+ /** Client liveness ping; hosts answer with a pong and never ACK-track it. */
185
+ const EDAWebSocketPingFrame = EDAWebSocketWirePingFrame;
186
+ /** Server liveness pong; clients may ignore it and must not ACK it. */
187
+ const EDAWebSocketPongFrame = EDAWebSocketWirePongFrame;
188
+ /** Optional final frame sent before a lag-close. */
189
+ const EDAWebSocketLaggedFrame = Schema.Struct({
190
+ ...EDAWebSocketWireLaggedFrame.fields,
191
+ resumeSeq: SequenceNumber
192
+ });
193
+ /** Optional final frame sent before a protocol/internal close. */
194
+ const EDAWebSocketErrorFrame = EDAWebSocketWireErrorFrame;
195
+ /** Server-to-client application frame union. */
196
+ const EDAWebSocketServerFrame = Schema.Union([
197
+ EDAWebSocketHelloFrame,
198
+ EDAWebSocketEventsFrame,
199
+ EDAWebSocketHeartbeatFrame,
200
+ EDAWebSocketPongFrame,
201
+ EDAWebSocketLaggedFrame,
202
+ EDAWebSocketErrorFrame
203
+ ]);
204
+ /** Client acknowledgement after applying a server frame. */
205
+ const EDAWebSocketAckFrame = Schema.Struct({
206
+ ...EDAWebSocketWireAckFrame.fields,
207
+ frameId: FrameId,
208
+ durableThroughSeq: SequenceNumber
209
+ });
210
+ /** Client-to-server application frame union. */
211
+ const EDAWebSocketClientFrame = Schema.Union([EDAWebSocketAckFrame, EDAWebSocketPingFrame]);
212
+ /** Serialize a server frame for a text WebSocket message. */
213
+ const encodeEDAWebSocketServerFrame = (frame, protocol) => (protocol ?? edaFrameworkWebSocketWireProtocol.host).encodeServerFrame(frame);
214
+ /** Decode an inbound text WebSocket message at the host boundary. */
215
+ const decodeEDAWebSocketClientMessage = (input) => Effect.try({
216
+ try: () => JSON.parse(input),
217
+ catch: (error) => error
218
+ }).pipe(Effect.flatMap((json) => Schema.decodeUnknownEffect(EDAWebSocketWireClientFrame)(json)), Effect.flatMap((frame) => Schema.decodeUnknownEffect(EDAWebSocketClientFrame)(frame)));
219
+ /** Short close reason that fits the WebSocket protocol reason limit. */
220
+ const laggedCloseReason = (seq) => `lag;seq=${seq}`;
221
+ //#endregion
222
+ //#region src/websocket/delivery.ts
223
+ /** Slow subscriber reasons that intentionally close only the lagging socket. */
224
+ const SubscriberLagReason = Schema.Literals(["buffer-overflow", "ack-timeout"]);
225
+ /** One sent-but-unacknowledged events frame. */
226
+ const EDAWebSocketInFlightFrame = Schema.Struct({
227
+ frameId: FrameId,
228
+ durableThroughSeq: SequenceNumber,
229
+ sentAtMs: Schema.Number
230
+ });
231
+ /** Compact consecutive host-suppressed receipts blocked by a visible ACK. */
232
+ const EDAWebSocketSuppressedRange = Schema.Struct({
233
+ fromFrameId: FrameId,
234
+ throughFrameId: FrameId,
235
+ durableThroughSeq: SequenceNumber
236
+ });
237
+ /** Complete delivery bookkeeping persisted in the WebSocket attachment. */
238
+ const EDAWebSocketDeliveryCheckpoint = Schema.Struct({
239
+ lastAckedSeq: SequenceNumber,
240
+ lastAckedFrameId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
241
+ lastSentFrameId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
242
+ nextFrameId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
243
+ sentDurableThroughSeq: SequenceNumber,
244
+ inFlight: Schema.Array(EDAWebSocketInFlightFrame),
245
+ /** Host-projected receipts waiting behind an earlier client-visible ACK. */
246
+ suppressed: Schema.optionalKey(Schema.Array(EDAWebSocketSuppressedRange))
247
+ });
248
+ /** Build delivery state for a newly accepted connection. */
249
+ const makeWebSocketDeliveryState = (input) => ({
250
+ subscriberId: input.subscriberId,
251
+ policy: input.policy,
252
+ lastAckedSeq: input.resumeSeq,
253
+ lastAckedFrameId: 0,
254
+ lastSentFrameId: 0,
255
+ nextFrameId: 1,
256
+ sentDurableThroughSeq: input.resumeSeq,
257
+ inFlight: [],
258
+ suppressed: [],
259
+ pendingEphemeral: []
260
+ });
261
+ /** Rebuild exact ACK bookkeeping from a hibernating WebSocket attachment. */
262
+ const restoreWebSocketDeliveryState = (input) => ({
263
+ subscriberId: input.subscriberId,
264
+ policy: input.policy,
265
+ ...input.checkpoint,
266
+ pendingEphemeral: [],
267
+ suppressed: input.checkpoint.suppressed ?? []
268
+ });
269
+ /** Project in-memory delivery state into the attachment-safe checkpoint. */
270
+ const checkpointWebSocketDeliveryState = (state) => ({
271
+ lastAckedSeq: state.lastAckedSeq,
272
+ lastAckedFrameId: state.lastAckedFrameId,
273
+ lastSentFrameId: state.lastSentFrameId,
274
+ nextFrameId: state.nextFrameId,
275
+ sentDurableThroughSeq: state.sentDurableThroughSeq,
276
+ inFlight: state.inFlight,
277
+ ...state.suppressed.length === 0 ? {} : { suppressed: state.suppressed }
278
+ });
279
+ /** First frame for a freshly accepted connection. Restores never re-send hello. */
280
+ const deliveryHelloFrame = (state) => EDAWebSocketHelloFrame.make({
281
+ _tag: "hello",
282
+ protocolVersion: EDA_WEB_SOCKET_PROTOCOL_VERSION,
283
+ subscriberId: state.subscriberId,
284
+ resumeSeq: state.lastAckedSeq,
285
+ flowControl: state.policy
286
+ });
287
+ /** Deliver committed durable events read from the store. */
288
+ const onDurableEvents = (state, events, head, nowMs) => {
289
+ const stale = staleAckResult(state, nowMs);
290
+ if (stale !== void 0) return stale;
291
+ let next = state;
292
+ const frames = [];
293
+ let batch = [];
294
+ const flushBatch = () => {
295
+ if (batch.length === 0) return;
296
+ const sent = sendEventsFrame(next, batch, nowMs);
297
+ next = sent.state;
298
+ frames.push(sent.frame);
299
+ batch = [];
300
+ };
301
+ for (const event of events) {
302
+ if (event.event.durability === "durable" && event.position.seq <= next.sentDurableThroughSeq) continue;
303
+ if (batch.length === 0 && windowCapacity(next) <= 0) break;
304
+ batch.push(event);
305
+ if (batch.length >= next.policy.maxFrameEvents) flushBatch();
306
+ }
307
+ flushBatch();
308
+ return sentResult(next, frames, windowCapacity(next) > 0 && next.sentDurableThroughSeq < head ? next.sentDurableThroughSeq : void 0);
309
+ };
310
+ /** Deliver one live ephemeral event, buffering only while this isolate is active. */
311
+ const onEphemeralEvent = (state, event, nowMs) => {
312
+ const stale = staleAckResult(state, nowMs);
313
+ if (stale !== void 0) return stale;
314
+ if (windowCapacity(state) > 0 && state.pendingEphemeral.length === 0) {
315
+ const sent = sendEventsFrame(state, [event], nowMs);
316
+ return sentResult(sent.state, [sent.frame]);
317
+ }
318
+ const pendingEphemeral = [...state.pendingEphemeral, event];
319
+ if (pendingEphemeral.length > state.policy.subscriberBufferCapacityEvents) return laggedResult(state, "buffer-overflow");
320
+ return {
321
+ state: {
322
+ ...state,
323
+ pendingEphemeral
324
+ },
325
+ actions: []
326
+ };
327
+ };
328
+ /** Apply one client ACK, reopen the window, and drain buffered ephemeral events. */
329
+ const onClientAck = (state, ack, nowMs) => {
330
+ const validated = applyAck(state, ack);
331
+ if (validated._tag === "close") return validated.result;
332
+ if (validated._tag === "ignore") return {
333
+ state,
334
+ actions: []
335
+ };
336
+ return reopenDeliveryWindow(validated.state, nowMs);
337
+ };
338
+ /**
339
+ * Apply one exact host-suppressed receipt without cumulatively ACKing any
340
+ * earlier client-visible frame.
341
+ */
342
+ const onHostSuppressedFrame = (state, frame, nowMs) => {
343
+ const receipt = state.inFlight.find((candidate) => candidate.frameId === frame.frameId);
344
+ if (receipt === void 0 || receipt.durableThroughSeq !== frame.durableThroughSeq) return protocolClose(state, "Host suppressed an unknown frame receipt").result;
345
+ const next = advanceSuppressedReceipts({
346
+ ...state,
347
+ inFlight: state.inFlight.filter((candidate) => candidate.frameId !== frame.frameId),
348
+ suppressed: insertSuppressedReceipt(state.suppressed, receipt)
349
+ });
350
+ return reopenDeliveryWindow(next, nowMs);
351
+ };
352
+ const reopenDeliveryWindow = (state, nowMs) => {
353
+ let next = state;
354
+ const frames = [];
355
+ while (next.pendingEphemeral.length > 0 && windowCapacity(next) > 0) {
356
+ const [head, ...rest] = next.pendingEphemeral;
357
+ if (head === void 0) break;
358
+ const sent = sendEventsFrame({
359
+ ...next,
360
+ pendingEphemeral: rest
361
+ }, [head], nowMs);
362
+ next = sent.state;
363
+ frames.push(sent.frame);
364
+ }
365
+ const stale = staleAckResult(next, nowMs);
366
+ if (stale !== void 0) return stale;
367
+ return sentResult(next, frames, windowCapacity(next) > 0 && next.pendingEphemeral.length === 0 ? next.sentDurableThroughSeq : void 0, true);
368
+ };
369
+ const applyAck = (state, ack) => {
370
+ if (ack.frameId <= state.lastAckedFrameId) return ack.durableThroughSeq > state.lastAckedSeq ? protocolClose(state, "Duplicate ACK attempted to advance durable seq") : { _tag: "ignore" };
371
+ if (ack.frameId > state.lastSentFrameId) return protocolClose(state, "ACK referenced an unsent frame");
372
+ if (ack.durableThroughSeq < state.lastAckedSeq) return protocolClose(state, "ACK durable seq moved backwards");
373
+ const acknowledgedVisible = state.inFlight.filter((frame) => frame.frameId <= ack.frameId);
374
+ if (acknowledgedVisible.length === 0) return protocolClose(state, "ACK referenced no in-flight frames");
375
+ if (state.suppressed.some((range) => range.fromFrameId <= ack.frameId && ack.frameId <= range.throughFrameId)) return protocolClose(state, "ACK referenced a host-suppressed frame");
376
+ const acknowledgedSuppressed = state.suppressed.filter((range) => range.throughFrameId <= ack.frameId);
377
+ const acknowledged = [...acknowledgedVisible, ...acknowledgedSuppressed];
378
+ const allowedDurableSeq = SequenceNumber.make(acknowledged.reduce((max, receipt) => Math.max(max, receipt.durableThroughSeq), state.lastAckedSeq));
379
+ if (ack.durableThroughSeq > allowedDurableSeq) return protocolClose(state, "ACK durable seq exceeded sent frame boundary");
380
+ return {
381
+ _tag: "apply",
382
+ state: advanceSuppressedReceipts({
383
+ ...state,
384
+ inFlight: state.inFlight.filter((frame) => frame.frameId > ack.frameId),
385
+ lastAckedFrameId: ack.frameId,
386
+ lastAckedSeq: ack.durableThroughSeq,
387
+ suppressed: state.suppressed.filter((range) => range.throughFrameId > ack.frameId)
388
+ })
389
+ };
390
+ };
391
+ const advanceSuppressedReceipts = (state) => {
392
+ let lastAckedFrameId = state.lastAckedFrameId;
393
+ let lastAckedSeq = state.lastAckedSeq;
394
+ let consumed = 0;
395
+ for (const range of state.suppressed) {
396
+ if (range.fromFrameId !== lastAckedFrameId + 1) break;
397
+ lastAckedFrameId = range.throughFrameId;
398
+ lastAckedSeq = SequenceNumber.make(Math.max(lastAckedSeq, range.durableThroughSeq));
399
+ consumed += 1;
400
+ }
401
+ return consumed === 0 ? state : {
402
+ ...state,
403
+ lastAckedFrameId,
404
+ lastAckedSeq,
405
+ suppressed: state.suppressed.slice(consumed)
406
+ };
407
+ };
408
+ const insertSuppressedReceipt = (ranges, receipt) => {
409
+ const inserted = [...ranges, EDAWebSocketSuppressedRange.make({
410
+ fromFrameId: receipt.frameId,
411
+ throughFrameId: receipt.frameId,
412
+ durableThroughSeq: receipt.durableThroughSeq
413
+ })].sort((left, right) => left.fromFrameId - right.fromFrameId);
414
+ const compacted = [];
415
+ for (const range of inserted) {
416
+ const previous = compacted.at(-1);
417
+ if (previous === void 0 || range.fromFrameId > previous.throughFrameId + 1) {
418
+ compacted.push(range);
419
+ continue;
420
+ }
421
+ compacted[compacted.length - 1] = EDAWebSocketSuppressedRange.make({
422
+ fromFrameId: previous.fromFrameId,
423
+ throughFrameId: FrameId.make(Math.max(previous.throughFrameId, range.throughFrameId)),
424
+ durableThroughSeq: SequenceNumber.make(Math.max(previous.durableThroughSeq, range.durableThroughSeq))
425
+ });
426
+ }
427
+ return compacted;
428
+ };
429
+ const windowCapacity = (state) => state.policy.maxInFlightFrames - state.inFlight.length;
430
+ const sendEventsFrame = (state, events, nowMs) => {
431
+ const [first, ...rest] = events;
432
+ if (first === void 0) throw new Error("Cannot send an empty events frame");
433
+ const frameId = FrameId.make(state.nextFrameId);
434
+ const durableThroughSeq = SequenceNumber.make(events.reduce((max, event) => event.event.durability === "durable" ? Math.max(max, event.position.seq) : max, state.sentDurableThroughSeq));
435
+ const frame = EDAWebSocketEventsFrame.make({
436
+ _tag: "events",
437
+ frameId,
438
+ events: [first, ...rest],
439
+ durableThroughSeq
440
+ });
441
+ return {
442
+ state: {
443
+ ...state,
444
+ inFlight: [...state.inFlight, {
445
+ frameId,
446
+ durableThroughSeq,
447
+ sentAtMs: nowMs
448
+ }],
449
+ lastSentFrameId: frameId,
450
+ nextFrameId: frameId + 1,
451
+ sentDurableThroughSeq: durableThroughSeq
452
+ },
453
+ frame
454
+ };
455
+ };
456
+ const sentResult = (state, frames, catchUpAfterSeq, stateChanged = frames.length > 0) => ({
457
+ state,
458
+ actions: [
459
+ ...stateChanged ? [{ _tag: "Persist" }] : [],
460
+ ...frames.length > 0 ? [{
461
+ _tag: "Send",
462
+ frames
463
+ }] : [],
464
+ ...catchUpAfterSeq === void 0 ? [] : [{
465
+ _tag: "ReadEventPage",
466
+ afterSeq: catchUpAfterSeq
467
+ }]
468
+ ]
469
+ });
470
+ /** Lazily enforce the ACK deadline: no resident timer, checked on each transition. */
471
+ const staleAckResult = (state, nowMs) => state.inFlight.some((frame) => frame.sentAtMs + state.policy.ackTimeoutMs <= nowMs) ? laggedResult(state, "ack-timeout") : void 0;
472
+ const laggedResult = (state, reason) => ({
473
+ state,
474
+ actions: [{
475
+ _tag: "Send",
476
+ frames: [EDAWebSocketLaggedFrame.make({
477
+ _tag: "lagged",
478
+ resumeSeq: state.lastAckedSeq,
479
+ reason
480
+ })]
481
+ }, {
482
+ _tag: "Close",
483
+ code: EDA_WS_CLOSE_LAGGED,
484
+ reason: laggedCloseReason(state.lastAckedSeq)
485
+ }]
486
+ });
487
+ const protocolClose = (state, message) => ({
488
+ _tag: "close",
489
+ result: {
490
+ state,
491
+ actions: [{
492
+ _tag: "Send",
493
+ frames: [EDAWebSocketErrorFrame.make({
494
+ _tag: "error",
495
+ message: message.slice(0, 120)
496
+ })]
497
+ }, {
498
+ _tag: "Close",
499
+ code: EDA_WS_CLOSE_PROTOCOL_ERROR,
500
+ reason: "protocol"
501
+ }]
502
+ }
503
+ });
504
+ //#endregion
505
+ export { FrameId as A, EDAWebSocketWireFlowControl as B, EDAWebSocketServerFrame as C, EDA_WS_CLOSE_PROTOCOL_ERROR as D, EDA_WS_CLOSE_LAGGED as E, laggedCloseReason as F, EDAWebSocketWirePongFrame as G, EDAWebSocketWireHelloFrame as H, EDAFrameworkWebSocketEvent as I, EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION as J, EDA_WEB_SOCKET_PING_MESSAGE as K, EDAWebSocketWireAckFrame as L, decodeEDAWebSocketClientMessage as M, defaultEDAWebSocketFlowControl as N, EDA_WS_CLOSE_SEND_FAILED as O, encodeEDAWebSocketServerFrame as P, EDAWebSocketWireClientFrame as R, EDAWebSocketPongFrame as S, EDA_WS_CLOSE_GOING_AWAY as T, EDAWebSocketWireLaggedFrame as U, EDAWebSocketWireHeartbeatFrame as V, EDAWebSocketWirePingFrame as W, makeEDAWebSocketWireProtocol as X, edaFrameworkWebSocketWireProtocol as Y, EDAWebSocketFlowControl as _, checkpointWebSocketDeliveryState as a, EDAWebSocketLaggedFrame as b, onClientAck as c, onHostSuppressedFrame as d, restoreWebSocketDeliveryState as f, EDAWebSocketEventsFrame as g, EDAWebSocketErrorFrame as h, SubscriberLagReason as i, SubscriberId as j, EDA_WS_CLOSE_UNSUPPORTED_DATA as k, onDurableEvents as l, EDAWebSocketClientFrame as m, EDAWebSocketInFlightFrame as n, deliveryHelloFrame as o, EDAWebSocketAckFrame as p, EDA_WEB_SOCKET_PONG_MESSAGE as q, EDAWebSocketSuppressedRange as r, makeWebSocketDeliveryState as s, EDAWebSocketDeliveryCheckpoint as t, onEphemeralEvent as u, EDAWebSocketHeartbeatFrame as v, EDA_WEB_SOCKET_PROTOCOL_VERSION as w, EDAWebSocketPingFrame as x, EDAWebSocketHelloFrame as y, EDAWebSocketWireErrorFrame as z };
506
+
507
+ //# sourceMappingURL=delivery-2ZILvoRD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delivery-2ZILvoRD.js","names":[],"sources":["../src/websocket/protocol.ts","../src/websocket/messages.ts","../src/websocket/delivery.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\n\nimport { Position } from \"../types/core\";\nimport { EDADurableEvent, EDAEphemeralEvent, EventEnvelope } from \"../types/events\";\n\nconst PositiveInt = Schema.Int.check(Schema.isGreaterThan(0));\nconst NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\n\n/** Current EDA live-event WebSocket wire protocol version. */\nexport const EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION = 1 as const;\n\n/** Flow-control policy announced by the server in the hello frame. */\nexport const EDAWebSocketWireFlowControl = Schema.Struct({\n ackTimeoutMs: PositiveInt,\n /** Deprecated: servers no longer send heartbeat frames. Kept so deployed clients can decode hello. */\n heartbeatIntervalMs: PositiveInt,\n maxFrameBytes: PositiveInt,\n maxFrameEvents: PositiveInt,\n maxInFlightFrames: PositiveInt,\n /** Suggested client-originated ping cadence; absent on servers that still send heartbeats. */\n pingIntervalMs: Schema.optionalKey(PositiveInt),\n subscriberBufferCapacityEvents: PositiveInt,\n});\nexport type EDAWebSocketWireFlowControl = typeof EDAWebSocketWireFlowControl.Type;\n\n/**\n * Canonical client liveness ping message.\n *\n * The exact string matters: hibernation-capable hosts register it with\n * WebSocket auto-response so the runtime answers without waking the object.\n */\nexport const EDA_WEB_SOCKET_PING_MESSAGE = '{\"_tag\":\"ping\"}';\n\n/** Canonical server pong message paired with {@link EDA_WEB_SOCKET_PING_MESSAGE}. */\nexport const EDA_WEB_SOCKET_PONG_MESSAGE = '{\"_tag\":\"pong\"}';\n\n/** Client liveness ping; hosts answer with a pong and never ACK-track it. */\nexport const EDAWebSocketWirePingFrame = Schema.Struct({\n _tag: Schema.Literal(\"ping\"),\n});\nexport type EDAWebSocketWirePingFrame = typeof EDAWebSocketWirePingFrame.Type;\n\n/** Server liveness pong; clients may ignore it and must not ACK it. */\nexport const EDAWebSocketWirePongFrame = Schema.Struct({\n _tag: Schema.Literal(\"pong\"),\n});\nexport type EDAWebSocketWirePongFrame = typeof EDAWebSocketWirePongFrame.Type;\n\nexport const EDAWebSocketWireHelloFrame = Schema.Struct({\n _tag: Schema.Literal(\"hello\"),\n protocolVersion: Schema.Literal(EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION),\n subscriberId: Schema.NonEmptyString,\n resumeSeq: NonNegativeInt,\n flowControl: EDAWebSocketWireFlowControl,\n});\nexport type EDAWebSocketWireHelloFrame = typeof EDAWebSocketWireHelloFrame.Type;\n\nexport const EDAWebSocketWireHeartbeatFrame = Schema.Struct({\n _tag: Schema.Literal(\"heartbeat\"),\n serverTimeMs: NonNegativeInt,\n durableThroughSeq: NonNegativeInt,\n});\nexport type EDAWebSocketWireHeartbeatFrame = typeof EDAWebSocketWireHeartbeatFrame.Type;\n\nexport const EDAWebSocketWireLaggedFrame = Schema.Struct({\n _tag: Schema.Literal(\"lagged\"),\n resumeSeq: NonNegativeInt,\n reason: Schema.Literals([\"buffer-overflow\", \"ack-timeout\"]),\n});\nexport type EDAWebSocketWireLaggedFrame = typeof EDAWebSocketWireLaggedFrame.Type;\n\nexport const EDAWebSocketWireErrorFrame = Schema.Struct({\n _tag: Schema.Literal(\"error\"),\n message: Schema.String,\n});\nexport type EDAWebSocketWireErrorFrame = typeof EDAWebSocketWireErrorFrame.Type;\n\n/**\n * Client acknowledgement. `frameId` is the transport receipt: it cumulatively frees flow-control\n * capacity. On a transcript socket `appliedUpdateSeq` is the client's applied cut, the last\n * transcript update it applied completely, and `durableThroughSeq` is that update's\n * `throughSeq`; both advance only on complete updates, never on a partial chunked transfer.\n * Raw event sockets ignore `appliedUpdateSeq`.\n */\nexport const EDAWebSocketWireAckFrame = Schema.Struct({\n _tag: Schema.Literal(\"ack\"),\n frameId: PositiveInt,\n durableThroughSeq: NonNegativeInt,\n appliedUpdateSeq: Schema.optionalKey(NonNegativeInt),\n});\nexport type EDAWebSocketWireAckFrame = typeof EDAWebSocketWireAckFrame.Type;\n\nexport const EDAWebSocketWireClientFrame = Schema.Union([\n EDAWebSocketWireAckFrame,\n EDAWebSocketWirePingFrame,\n]);\nexport type EDAWebSocketWireClientFrame = typeof EDAWebSocketWireClientFrame.Type;\n\n/** Exhaustive decision table for a concrete WebSocket event union. */\nexport type EDAWebSocketEventConsumerPolicy<\n Event extends { readonly type: string },\n Disposition,\n> = Readonly<Record<Event[\"type\"], Disposition>>;\n\n/** Complete framework-owned event union present on every EDA WebSocket. */\nexport const EDAFrameworkWebSocketEvent = Schema.Union([EDADurableEvent, EDAEphemeralEvent]);\nexport type EDAFrameworkWebSocketEvent = typeof EDAFrameworkWebSocketEvent.Type;\n\nconst makeEDAWebSocketDomainSchemas = <\n EventSchema extends Schema.Codec<EventEnvelope, unknown, never, never>,\n>(\n event: EventSchema,\n) => {\n const positionedEvent = Schema.Struct({\n position: Position,\n event,\n });\n const eventsFrame = Schema.Struct({\n _tag: Schema.Literal(\"events\"),\n frameId: PositiveInt,\n events: Schema.NonEmptyArray(positionedEvent),\n durableThroughSeq: NonNegativeInt,\n });\n const serverFrame = Schema.Union([\n EDAWebSocketWireHelloFrame,\n eventsFrame,\n EDAWebSocketWireHeartbeatFrame,\n EDAWebSocketWirePongFrame,\n EDAWebSocketWireLaggedFrame,\n EDAWebSocketWireErrorFrame,\n ]);\n return { event, positionedEvent, eventsFrame, serverFrame };\n};\n\ntype EDAWebSocketDomainSchemas<\n EventSchema extends Schema.Codec<EventEnvelope, unknown, never, never>,\n> = ReturnType<typeof makeEDAWebSocketDomainSchemas<EventSchema>>;\n\nconst EDAWebSocketHostDomain = makeEDAWebSocketDomainSchemas(EventEnvelope);\n\n/** Domain frame shape accepted by an app-bound encoder at the EDA host boundary. */\nexport type EDAWebSocketServerFrameInput = typeof EDAWebSocketHostDomain.serverFrame.Type;\n\n/** Minimal typed encoder surface consumed by an EDA host. */\nexport interface EDAWebSocketServerFrameEncoder {\n readonly encodeServerFrame: (frame: EDAWebSocketServerFrameInput) => string;\n}\n\n/** App-bound domain schemas, wire schemas, and encoders for protocol version 1. */\nexport interface EDAWebSocketWireProtocol<\n EventSchema extends Schema.Codec<EventEnvelope, unknown, never, never>,\n> {\n /** Exact app-bound schemas whose `Type` values are used inside the server. */\n readonly domain: EDAWebSocketDomainSchemas<EventSchema>;\n /** Exact app-bound schemas whose `Type` values are the serialized JSON representation. */\n readonly wire: {\n readonly event: Schema.toEncoded<EventSchema>;\n readonly positionedEvent: Schema.toEncoded<\n EDAWebSocketDomainSchemas<EventSchema>[\"positionedEvent\"]\n >;\n readonly eventsFrame: Schema.toEncoded<EDAWebSocketDomainSchemas<EventSchema>[\"eventsFrame\"]>;\n readonly serverFrame: Schema.toEncoded<EDAWebSocketDomainSchemas<EventSchema>[\"serverFrame\"]>;\n readonly clientFrame: typeof EDAWebSocketWireClientFrame;\n };\n /** Serialize one exact app-bound domain frame to a JSON text message. */\n readonly encodeServerFrame: (\n frame: Schema.Schema.Type<EDAWebSocketDomainSchemas<EventSchema>[\"serverFrame\"]>,\n ) => string;\n /** Validate broad host frames against the app event union before serialization. */\n readonly host: EDAWebSocketServerFrameEncoder;\n}\n\nconst makeEDAWebSocketWireProtocolFromEventSchema = <\n EventSchema extends Schema.Codec<EventEnvelope, unknown, never, never>,\n>(\n event: EventSchema,\n): EDAWebSocketWireProtocol<EventSchema> => {\n const domain = makeEDAWebSocketDomainSchemas(event);\n const encodeDomainServerFrame = Schema.encodeSync(domain.serverFrame);\n const encodeUnknownDomainServerFrame = Schema.encodeUnknownSync(domain.serverFrame);\n const encodeServerFrame = (frame: typeof domain.serverFrame.Type): string =>\n JSON.stringify(encodeDomainServerFrame(frame));\n const host: EDAWebSocketServerFrameEncoder = {\n encodeServerFrame: (frame) => JSON.stringify(encodeUnknownDomainServerFrame(frame)),\n };\n\n return {\n domain,\n wire: {\n event: Schema.toEncoded(domain.event),\n positionedEvent: Schema.toEncoded(domain.positionedEvent),\n eventsFrame: Schema.toEncoded(domain.eventsFrame),\n serverFrame: Schema.toEncoded(domain.serverFrame),\n clientFrame: EDAWebSocketWireClientFrame,\n },\n encodeServerFrame,\n host,\n };\n};\n\n/** Strict framework-only protocol used when an app registers no custom events. */\nexport const edaFrameworkWebSocketWireProtocol: EDAWebSocketWireProtocol<\n typeof EDAFrameworkWebSocketEvent\n> = makeEDAWebSocketWireProtocolFromEventSchema(EDAFrameworkWebSocketEvent);\n\n/**\n * Bind the generic EDA WebSocket transport to one app's custom event schema.\n *\n * Framework durable and ephemeral events are included automatically. Future EDA\n * apps register only their custom events. Servers use the returned domain schemas\n * and typed encoder; external consumers decode with the wire schemas. Pass the\n * returned `host` adapter to the selected host package.\n */\nexport const makeEDAWebSocketWireProtocol = <\n AppEventSchema extends Schema.Codec<EventEnvelope, unknown, never, never>,\n>(options: {\n readonly appEvents: AppEventSchema;\n}): EDAWebSocketWireProtocol<\n Schema.Union<readonly [typeof EDAFrameworkWebSocketEvent, AppEventSchema]>\n> =>\n makeEDAWebSocketWireProtocolFromEventSchema(\n Schema.Union([EDAFrameworkWebSocketEvent, options.appEvents]),\n );\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport {\n EDA_WEB_SOCKET_PING_MESSAGE,\n EDA_WEB_SOCKET_PONG_MESSAGE,\n EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION,\n EDAWebSocketWireAckFrame,\n EDAWebSocketWireClientFrame,\n EDAWebSocketWireErrorFrame,\n EDAWebSocketWireFlowControl,\n EDAWebSocketWireHeartbeatFrame,\n EDAWebSocketWireHelloFrame,\n EDAWebSocketWireLaggedFrame,\n EDAWebSocketWirePingFrame,\n EDAWebSocketWirePongFrame,\n edaFrameworkWebSocketWireProtocol,\n type EDAWebSocketServerFrameEncoder,\n} from \"./protocol\";\n\nexport { EDA_WEB_SOCKET_PING_MESSAGE, EDA_WEB_SOCKET_PONG_MESSAGE };\n\nimport { SequenceNumber } from \"../types/core\";\nimport { PositionedEvent, UnixEpochMillis } from \"../types/events\";\n\n/** Current EDA live-event WebSocket protocol version. */\nexport const EDA_WEB_SOCKET_PROTOCOL_VERSION = EDA_WEB_SOCKET_WIRE_PROTOCOL_VERSION;\n\n/** WebSocket close code used when a subscriber cannot keep up with live delivery. */\nexport const EDA_WS_CLOSE_LAGGED = 4008;\n\n/** WebSocket close code used for normal host-driven shutdown. */\nexport const EDA_WS_CLOSE_GOING_AWAY = 1001;\n\n/** WebSocket close code used for malformed client protocol messages. */\nexport const EDA_WS_CLOSE_PROTOCOL_ERROR = 1002;\n\n/** WebSocket close code used when the host cannot send a frame. */\nexport const EDA_WS_CLOSE_SEND_FAILED = 1011;\n\n/** WebSocket close code used for unsupported binary messages. */\nexport const EDA_WS_CLOSE_UNSUPPORTED_DATA = 1003;\n\n/** Live subscriber identity persisted in WebSocket attachments. */\nexport const SubscriberId = Schema.NonEmptyString.pipe(Schema.brand(\"SubscriberId\"));\nexport type SubscriberId = typeof SubscriberId.Type;\n\n/** Per-connection monotonically increasing server frame id. */\nexport const FrameId = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).pipe(\n Schema.brand(\"FrameId\"),\n);\nexport type FrameId = typeof FrameId.Type;\n\n/** Flow-control policy announced by the server in the hello frame. */\nexport const EDAWebSocketFlowControl = EDAWebSocketWireFlowControl;\nexport type EDAWebSocketFlowControl = typeof EDAWebSocketFlowControl.Type;\n\n/** Default bounded policy sized for fast model deltas and large durable tool/message events. */\nexport const defaultEDAWebSocketFlowControl: EDAWebSocketFlowControl = {\n ackTimeoutMs: 30_000,\n // Deprecated wire-compat field: servers no longer schedule or send heartbeats.\n heartbeatIntervalMs: 10_000,\n maxFrameBytes: 256 * 1024,\n maxFrameEvents: 1,\n maxInFlightFrames: 16,\n pingIntervalMs: 30_000,\n subscriberBufferCapacityEvents: 2_048,\n};\n\n/** First server frame; announces protocol and flow-control policy. */\nexport const EDAWebSocketHelloFrame = Schema.Struct({\n ...EDAWebSocketWireHelloFrame.fields,\n subscriberId: SubscriberId,\n resumeSeq: SequenceNumber,\n});\nexport type EDAWebSocketHelloFrame = typeof EDAWebSocketHelloFrame.Type;\n\n/** Ordered positioned events delivered to the client. */\nexport const EDAWebSocketEventsFrame = Schema.Struct({\n _tag: Schema.Literal(\"events\"),\n frameId: FrameId,\n events: Schema.NonEmptyArray(PositionedEvent),\n durableThroughSeq: SequenceNumber,\n});\nexport type EDAWebSocketEventsFrame = typeof EDAWebSocketEventsFrame.Type;\n\n/**\n * Deprecated idle server keepalive frame.\n *\n * Servers no longer send heartbeats; the schema remains so deployed clients\n * keep decoding the server frame union. Liveness is client-originated via\n * {@link EDAWebSocketPingFrame} and the host-level auto-response pong.\n */\nexport const EDAWebSocketHeartbeatFrame = Schema.Struct({\n ...EDAWebSocketWireHeartbeatFrame.fields,\n serverTimeMs: UnixEpochMillis,\n durableThroughSeq: SequenceNumber,\n});\nexport type EDAWebSocketHeartbeatFrame = typeof EDAWebSocketHeartbeatFrame.Type;\n\n/** Client liveness ping; hosts answer with a pong and never ACK-track it. */\nexport const EDAWebSocketPingFrame = EDAWebSocketWirePingFrame;\nexport type EDAWebSocketPingFrame = typeof EDAWebSocketPingFrame.Type;\n\n/** Server liveness pong; clients may ignore it and must not ACK it. */\nexport const EDAWebSocketPongFrame = EDAWebSocketWirePongFrame;\nexport type EDAWebSocketPongFrame = typeof EDAWebSocketPongFrame.Type;\n\n/** Optional final frame sent before a lag-close. */\nexport const EDAWebSocketLaggedFrame = Schema.Struct({\n ...EDAWebSocketWireLaggedFrame.fields,\n resumeSeq: SequenceNumber,\n});\nexport type EDAWebSocketLaggedFrame = typeof EDAWebSocketLaggedFrame.Type;\n\n/** Optional final frame sent before a protocol/internal close. */\nexport const EDAWebSocketErrorFrame = EDAWebSocketWireErrorFrame;\nexport type EDAWebSocketErrorFrame = typeof EDAWebSocketErrorFrame.Type;\n\n/** Server-to-client application frame union. */\nexport const EDAWebSocketServerFrame = Schema.Union([\n EDAWebSocketHelloFrame,\n EDAWebSocketEventsFrame,\n EDAWebSocketHeartbeatFrame,\n EDAWebSocketPongFrame,\n EDAWebSocketLaggedFrame,\n EDAWebSocketErrorFrame,\n]);\nexport type EDAWebSocketServerFrame = typeof EDAWebSocketServerFrame.Type;\n\n/** Client acknowledgement after applying a server frame. */\nexport const EDAWebSocketAckFrame = Schema.Struct({\n ...EDAWebSocketWireAckFrame.fields,\n frameId: FrameId,\n durableThroughSeq: SequenceNumber,\n});\nexport type EDAWebSocketAckFrame = typeof EDAWebSocketAckFrame.Type;\n\n/** Client-to-server application frame union. */\nexport const EDAWebSocketClientFrame = Schema.Union([EDAWebSocketAckFrame, EDAWebSocketPingFrame]);\nexport type EDAWebSocketClientFrame = typeof EDAWebSocketClientFrame.Type;\n\n/** Serialize a server frame for a text WebSocket message. */\nexport const encodeEDAWebSocketServerFrame = (\n frame: EDAWebSocketServerFrame,\n protocol?: EDAWebSocketServerFrameEncoder,\n): string => (protocol ?? edaFrameworkWebSocketWireProtocol.host).encodeServerFrame(frame);\n\n/** Decode an inbound text WebSocket message at the host boundary. */\nexport const decodeEDAWebSocketClientMessage = (\n input: string,\n): Effect.Effect<EDAWebSocketClientFrame, unknown> =>\n Effect.try({\n try: () => JSON.parse(input) as unknown,\n catch: (error) => error,\n }).pipe(\n Effect.flatMap((json) => Schema.decodeUnknownEffect(EDAWebSocketWireClientFrame)(json)),\n Effect.flatMap((frame) => Schema.decodeUnknownEffect(EDAWebSocketClientFrame)(frame)),\n );\n\n/** Short close reason that fits the WebSocket protocol reason limit. */\nexport const laggedCloseReason = (seq: SequenceNumber): string => `lag;seq=${seq}`;\n","import * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport type { PositionedEvent } from \"../types/events\";\nimport {\n EDA_WEB_SOCKET_PROTOCOL_VERSION,\n EDA_WS_CLOSE_LAGGED,\n EDA_WS_CLOSE_PROTOCOL_ERROR,\n EDAWebSocketEventsFrame,\n EDAWebSocketErrorFrame,\n EDAWebSocketHelloFrame,\n EDAWebSocketLaggedFrame,\n FrameId,\n SubscriberId,\n laggedCloseReason,\n type EDAWebSocketAckFrame,\n type EDAWebSocketFlowControl,\n type EDAWebSocketServerFrame,\n} from \"./messages\";\n\n/** Slow subscriber reasons that intentionally close only the lagging socket. */\nexport const SubscriberLagReason = Schema.Literals([\"buffer-overflow\", \"ack-timeout\"]);\nexport type SubscriberLagReason = typeof SubscriberLagReason.Type;\n\n/** One sent-but-unacknowledged events frame. */\nexport const EDAWebSocketInFlightFrame = Schema.Struct({\n frameId: FrameId,\n durableThroughSeq: SequenceNumber,\n sentAtMs: Schema.Number,\n});\nexport type EDAWebSocketInFlightFrame = typeof EDAWebSocketInFlightFrame.Type;\n\n/** Compact consecutive host-suppressed receipts blocked by a visible ACK. */\nexport const EDAWebSocketSuppressedRange = Schema.Struct({\n fromFrameId: FrameId,\n throughFrameId: FrameId,\n durableThroughSeq: SequenceNumber,\n});\nexport type EDAWebSocketSuppressedRange = typeof EDAWebSocketSuppressedRange.Type;\n\n/** Complete delivery bookkeeping persisted in the WebSocket attachment. */\nexport const EDAWebSocketDeliveryCheckpoint = Schema.Struct({\n lastAckedSeq: SequenceNumber,\n lastAckedFrameId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n lastSentFrameId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n nextFrameId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),\n sentDurableThroughSeq: SequenceNumber,\n inFlight: Schema.Array(EDAWebSocketInFlightFrame),\n /** Host-projected receipts waiting behind an earlier client-visible ACK. */\n suppressed: Schema.optionalKey(Schema.Array(EDAWebSocketSuppressedRange)),\n});\nexport type EDAWebSocketDeliveryCheckpoint = typeof EDAWebSocketDeliveryCheckpoint.Type;\n\n/** In-memory delivery state for one accepted event WebSocket. */\nexport interface EDAWebSocketDeliveryState extends EDAWebSocketDeliveryCheckpoint {\n readonly subscriberId: SubscriberId;\n readonly policy: EDAWebSocketFlowControl;\n /** Ephemeral events are live-only and intentionally absent from the attachment. */\n readonly pendingEphemeral: ReadonlyArray<PositionedEvent>;\n readonly suppressed: ReadonlyArray<EDAWebSocketSuppressedRange>;\n}\n\n/** Explicit instructions emitted by the pure delivery state machine. */\nexport type EDAWebSocketDeliveryAction =\n | { readonly _tag: \"Persist\" }\n | { readonly _tag: \"Send\"; readonly frames: ReadonlyArray<EDAWebSocketServerFrame> }\n | { readonly _tag: \"ReadEventPage\"; readonly afterSeq: SequenceNumber }\n | { readonly _tag: \"Close\"; readonly code: number; readonly reason: string };\n\n/** Result of one pure delivery transition. */\nexport interface EDAWebSocketDeliveryResult {\n readonly state: EDAWebSocketDeliveryState;\n readonly actions: ReadonlyArray<EDAWebSocketDeliveryAction>;\n}\n\nexport interface MakeDeliveryStateInput {\n readonly subscriberId: SubscriberId;\n readonly resumeSeq: SequenceNumber;\n readonly policy: EDAWebSocketFlowControl;\n}\n\n/** Build delivery state for a newly accepted connection. */\nexport const makeWebSocketDeliveryState = (\n input: MakeDeliveryStateInput,\n): EDAWebSocketDeliveryState => ({\n subscriberId: input.subscriberId,\n policy: input.policy,\n lastAckedSeq: input.resumeSeq,\n lastAckedFrameId: 0,\n lastSentFrameId: 0,\n nextFrameId: 1,\n sentDurableThroughSeq: input.resumeSeq,\n inFlight: [],\n suppressed: [],\n pendingEphemeral: [],\n});\n\n/** Rebuild exact ACK bookkeeping from a hibernating WebSocket attachment. */\nexport const restoreWebSocketDeliveryState = (input: {\n readonly subscriberId: SubscriberId;\n readonly policy: EDAWebSocketFlowControl;\n readonly checkpoint: EDAWebSocketDeliveryCheckpoint;\n}): EDAWebSocketDeliveryState => ({\n subscriberId: input.subscriberId,\n policy: input.policy,\n ...input.checkpoint,\n pendingEphemeral: [],\n suppressed: input.checkpoint.suppressed ?? [],\n});\n\n/** Project in-memory delivery state into the attachment-safe checkpoint. */\nexport const checkpointWebSocketDeliveryState = (\n state: EDAWebSocketDeliveryState,\n): EDAWebSocketDeliveryCheckpoint => ({\n lastAckedSeq: state.lastAckedSeq,\n lastAckedFrameId: state.lastAckedFrameId,\n lastSentFrameId: state.lastSentFrameId,\n nextFrameId: state.nextFrameId,\n sentDurableThroughSeq: state.sentDurableThroughSeq,\n inFlight: state.inFlight,\n ...(state.suppressed.length === 0 ? {} : { suppressed: state.suppressed }),\n});\n\n/** First frame for a freshly accepted connection. Restores never re-send hello. */\nexport const deliveryHelloFrame = (state: EDAWebSocketDeliveryState): EDAWebSocketHelloFrame =>\n EDAWebSocketHelloFrame.make({\n _tag: \"hello\",\n protocolVersion: EDA_WEB_SOCKET_PROTOCOL_VERSION,\n subscriberId: state.subscriberId,\n resumeSeq: state.lastAckedSeq,\n flowControl: state.policy,\n });\n\n/** Deliver committed durable events read from the store. */\nexport const onDurableEvents = (\n state: EDAWebSocketDeliveryState,\n events: ReadonlyArray<PositionedEvent>,\n head: SequenceNumber,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const stale = staleAckResult(state, nowMs);\n if (stale !== undefined) return stale;\n\n let next = state;\n const frames: EDAWebSocketServerFrame[] = [];\n let batch: PositionedEvent[] = [];\n\n const flushBatch = (): void => {\n if (batch.length === 0) return;\n const sent = sendEventsFrame(next, batch, nowMs);\n next = sent.state;\n frames.push(sent.frame);\n batch = [];\n };\n\n for (const event of events) {\n if (event.event.durability === \"durable\" && event.position.seq <= next.sentDurableThroughSeq) {\n continue;\n }\n if (batch.length === 0 && windowCapacity(next) <= 0) break;\n batch.push(event);\n if (batch.length >= next.policy.maxFrameEvents) flushBatch();\n }\n flushBatch();\n\n return sentResult(\n next,\n frames,\n windowCapacity(next) > 0 && next.sentDurableThroughSeq < head\n ? next.sentDurableThroughSeq\n : undefined,\n );\n};\n\n/** Deliver one live ephemeral event, buffering only while this isolate is active. */\nexport const onEphemeralEvent = (\n state: EDAWebSocketDeliveryState,\n event: PositionedEvent,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const stale = staleAckResult(state, nowMs);\n if (stale !== undefined) return stale;\n\n if (windowCapacity(state) > 0 && state.pendingEphemeral.length === 0) {\n const sent = sendEventsFrame(state, [event], nowMs);\n return sentResult(sent.state, [sent.frame]);\n }\n\n const pendingEphemeral = [...state.pendingEphemeral, event];\n if (pendingEphemeral.length > state.policy.subscriberBufferCapacityEvents) {\n return laggedResult(state, \"buffer-overflow\");\n }\n return { state: { ...state, pendingEphemeral }, actions: [] };\n};\n\n/** Apply one client ACK, reopen the window, and drain buffered ephemeral events. */\nexport const onClientAck = (\n state: EDAWebSocketDeliveryState,\n ack: EDAWebSocketAckFrame,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const validated = applyAck(state, ack);\n if (validated._tag === \"close\") return validated.result;\n if (validated._tag === \"ignore\") return { state, actions: [] };\n\n return reopenDeliveryWindow(validated.state, nowMs);\n};\n\n/**\n * Apply one exact host-suppressed receipt without cumulatively ACKing any\n * earlier client-visible frame.\n */\nexport const onHostSuppressedFrame = (\n state: EDAWebSocketDeliveryState,\n frame: Pick<EDAWebSocketEventsFrame, \"durableThroughSeq\" | \"frameId\">,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n const receipt = state.inFlight.find((candidate) => candidate.frameId === frame.frameId);\n if (receipt === undefined || receipt.durableThroughSeq !== frame.durableThroughSeq) {\n return protocolClose(state, \"Host suppressed an unknown frame receipt\").result;\n }\n const next = advanceSuppressedReceipts({\n ...state,\n inFlight: state.inFlight.filter((candidate) => candidate.frameId !== frame.frameId),\n suppressed: insertSuppressedReceipt(state.suppressed, receipt),\n });\n return reopenDeliveryWindow(next, nowMs);\n};\n\nconst reopenDeliveryWindow = (\n state: EDAWebSocketDeliveryState,\n nowMs: number,\n): EDAWebSocketDeliveryResult => {\n let next = state;\n const frames: EDAWebSocketServerFrame[] = [];\n while (next.pendingEphemeral.length > 0 && windowCapacity(next) > 0) {\n const [head, ...rest] = next.pendingEphemeral;\n if (head === undefined) break;\n const sent = sendEventsFrame({ ...next, pendingEphemeral: rest }, [head], nowMs);\n next = sent.state;\n frames.push(sent.frame);\n }\n\n const stale = staleAckResult(next, nowMs);\n if (stale !== undefined) return stale;\n\n return sentResult(\n next,\n frames,\n windowCapacity(next) > 0 && next.pendingEphemeral.length === 0\n ? next.sentDurableThroughSeq\n : undefined,\n true,\n );\n};\n\ntype AckValidation =\n | { readonly _tag: \"ignore\" }\n | { readonly _tag: \"close\"; readonly result: EDAWebSocketDeliveryResult }\n | { readonly _tag: \"apply\"; readonly state: EDAWebSocketDeliveryState };\n\nconst applyAck = (state: EDAWebSocketDeliveryState, ack: EDAWebSocketAckFrame): AckValidation => {\n if (ack.frameId <= state.lastAckedFrameId) {\n return ack.durableThroughSeq > state.lastAckedSeq\n ? protocolClose(state, \"Duplicate ACK attempted to advance durable seq\")\n : { _tag: \"ignore\" };\n }\n if (ack.frameId > state.lastSentFrameId) {\n return protocolClose(state, \"ACK referenced an unsent frame\");\n }\n if (ack.durableThroughSeq < state.lastAckedSeq) {\n return protocolClose(state, \"ACK durable seq moved backwards\");\n }\n const acknowledgedVisible = state.inFlight.filter((frame) => frame.frameId <= ack.frameId);\n if (acknowledgedVisible.length === 0) {\n return protocolClose(state, \"ACK referenced no in-flight frames\");\n }\n if (\n state.suppressed.some(\n (range) => range.fromFrameId <= ack.frameId && ack.frameId <= range.throughFrameId,\n )\n ) {\n return protocolClose(state, \"ACK referenced a host-suppressed frame\");\n }\n const acknowledgedSuppressed = state.suppressed.filter(\n (range) => range.throughFrameId <= ack.frameId,\n );\n const acknowledged = [...acknowledgedVisible, ...acknowledgedSuppressed];\n const allowedDurableSeq = SequenceNumber.make(\n acknowledged.reduce<number>(\n (max, receipt) => Math.max(max, receipt.durableThroughSeq),\n state.lastAckedSeq,\n ),\n );\n if (ack.durableThroughSeq > allowedDurableSeq) {\n return protocolClose(state, \"ACK durable seq exceeded sent frame boundary\");\n }\n return {\n _tag: \"apply\",\n state: advanceSuppressedReceipts({\n ...state,\n inFlight: state.inFlight.filter((frame) => frame.frameId > ack.frameId),\n lastAckedFrameId: ack.frameId,\n lastAckedSeq: ack.durableThroughSeq,\n suppressed: state.suppressed.filter((range) => range.throughFrameId > ack.frameId),\n }),\n };\n};\n\nconst advanceSuppressedReceipts = (state: EDAWebSocketDeliveryState): EDAWebSocketDeliveryState => {\n let lastAckedFrameId = state.lastAckedFrameId;\n let lastAckedSeq = state.lastAckedSeq;\n let consumed = 0;\n for (const range of state.suppressed) {\n if (range.fromFrameId !== lastAckedFrameId + 1) break;\n lastAckedFrameId = range.throughFrameId;\n lastAckedSeq = SequenceNumber.make(Math.max(lastAckedSeq, range.durableThroughSeq));\n consumed += 1;\n }\n return consumed === 0\n ? state\n : {\n ...state,\n lastAckedFrameId,\n lastAckedSeq,\n suppressed: state.suppressed.slice(consumed),\n };\n};\n\nconst insertSuppressedReceipt = (\n ranges: ReadonlyArray<EDAWebSocketSuppressedRange>,\n receipt: EDAWebSocketInFlightFrame,\n): ReadonlyArray<EDAWebSocketSuppressedRange> => {\n const inserted = [\n ...ranges,\n EDAWebSocketSuppressedRange.make({\n fromFrameId: receipt.frameId,\n throughFrameId: receipt.frameId,\n durableThroughSeq: receipt.durableThroughSeq,\n }),\n ].sort((left, right) => left.fromFrameId - right.fromFrameId);\n const compacted: EDAWebSocketSuppressedRange[] = [];\n for (const range of inserted) {\n const previous = compacted.at(-1);\n if (previous === undefined || range.fromFrameId > previous.throughFrameId + 1) {\n compacted.push(range);\n continue;\n }\n compacted[compacted.length - 1] = EDAWebSocketSuppressedRange.make({\n fromFrameId: previous.fromFrameId,\n throughFrameId: FrameId.make(Math.max(previous.throughFrameId, range.throughFrameId)),\n durableThroughSeq: SequenceNumber.make(\n Math.max(previous.durableThroughSeq, range.durableThroughSeq),\n ),\n });\n }\n return compacted;\n};\n\nconst windowCapacity = (state: EDAWebSocketDeliveryState): number =>\n state.policy.maxInFlightFrames - state.inFlight.length;\n\nconst sendEventsFrame = (\n state: EDAWebSocketDeliveryState,\n events: ReadonlyArray<PositionedEvent>,\n nowMs: number,\n): { readonly state: EDAWebSocketDeliveryState; readonly frame: EDAWebSocketEventsFrame } => {\n const [first, ...rest] = events;\n if (first === undefined) throw new Error(\"Cannot send an empty events frame\");\n const frameId = FrameId.make(state.nextFrameId);\n const durableThroughSeq = SequenceNumber.make(\n events.reduce<number>(\n (max, event) =>\n event.event.durability === \"durable\" ? Math.max(max, event.position.seq) : max,\n state.sentDurableThroughSeq,\n ),\n );\n const frame = EDAWebSocketEventsFrame.make({\n _tag: \"events\",\n frameId,\n events: [first, ...rest],\n durableThroughSeq,\n });\n return {\n state: {\n ...state,\n inFlight: [...state.inFlight, { frameId, durableThroughSeq, sentAtMs: nowMs }],\n lastSentFrameId: frameId,\n nextFrameId: frameId + 1,\n sentDurableThroughSeq: durableThroughSeq,\n },\n frame,\n };\n};\n\nconst sentResult = (\n state: EDAWebSocketDeliveryState,\n frames: ReadonlyArray<EDAWebSocketServerFrame>,\n catchUpAfterSeq?: SequenceNumber,\n stateChanged = frames.length > 0,\n): EDAWebSocketDeliveryResult => ({\n state,\n actions: [\n ...(stateChanged ? ([{ _tag: \"Persist\" }] as const) : []),\n ...(frames.length > 0 ? ([{ _tag: \"Send\", frames }] as const) : []),\n ...(catchUpAfterSeq === undefined\n ? []\n : ([{ _tag: \"ReadEventPage\", afterSeq: catchUpAfterSeq }] as const)),\n ],\n});\n\n/** Lazily enforce the ACK deadline: no resident timer, checked on each transition. */\nconst staleAckResult = (\n state: EDAWebSocketDeliveryState,\n nowMs: number,\n): EDAWebSocketDeliveryResult | undefined =>\n state.inFlight.some((frame) => frame.sentAtMs + state.policy.ackTimeoutMs <= nowMs)\n ? laggedResult(state, \"ack-timeout\")\n : undefined;\n\nconst laggedResult = (\n state: EDAWebSocketDeliveryState,\n reason: SubscriberLagReason,\n): EDAWebSocketDeliveryResult => ({\n state,\n actions: [\n {\n _tag: \"Send\",\n frames: [\n EDAWebSocketLaggedFrame.make({\n _tag: \"lagged\",\n resumeSeq: state.lastAckedSeq,\n reason,\n }),\n ],\n },\n { _tag: \"Close\", code: EDA_WS_CLOSE_LAGGED, reason: laggedCloseReason(state.lastAckedSeq) },\n ],\n});\n\nconst protocolClose = (\n state: EDAWebSocketDeliveryState,\n message: string,\n): { readonly _tag: \"close\"; readonly result: EDAWebSocketDeliveryResult } => ({\n _tag: \"close\",\n result: {\n state,\n actions: [\n {\n _tag: \"Send\",\n frames: [EDAWebSocketErrorFrame.make({ _tag: \"error\", message: message.slice(0, 120) })],\n },\n { _tag: \"Close\", code: EDA_WS_CLOSE_PROTOCOL_ERROR, reason: \"protocol\" },\n ],\n },\n});\n"],"mappings":";;;;;;;AAKA,MAAM,cAAc,OAAO,IAAI,MAAM,OAAO,cAAc,CAAC,CAAC;AAC5D,MAAM,iBAAiB,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC;;AAGxE,MAAa,uCAAuC;;AAGpD,MAAa,8BAA8B,OAAO,OAAO;CACvD,cAAc;;CAEd,qBAAqB;CACrB,eAAe;CACf,gBAAgB;CAChB,mBAAmB;;CAEnB,gBAAgB,OAAO,YAAY,WAAW;CAC9C,gCAAgC;AAClC,CAAC;;;;;;;AASD,MAAa,8BAA8B;;AAG3C,MAAa,8BAA8B;;AAG3C,MAAa,4BAA4B,OAAO,OAAO,EACrD,MAAM,OAAO,QAAQ,MAAM,EAC7B,CAAC;;AAID,MAAa,4BAA4B,OAAO,OAAO,EACrD,MAAM,OAAO,QAAQ,MAAM,EAC7B,CAAC;AAGD,MAAa,6BAA6B,OAAO,OAAO;CACtD,MAAM,OAAO,QAAQ,OAAO;CAC5B,iBAA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