effect-durable-agent 0.1.0-alpha.23 → 0.1.0-alpha.25
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.
- package/dist/delivery-Bb7pkQ9o.js +507 -0
- package/dist/delivery-Bb7pkQ9o.js.map +1 -0
- package/dist/delivery-o6sDIiwO.d.ts +2990 -0
- package/dist/in-memory-IgxnTbGb.js +150 -0
- package/dist/in-memory-IgxnTbGb.js.map +1 -0
- package/dist/{window-read-BDayZf7O.js → interpreter-BdRoYrfL.js} +94 -206
- package/dist/interpreter-BdRoYrfL.js.map +1 -0
- package/dist/services/reducer-registry.js +1 -1
- package/dist/services/runtime-layer.js +3 -3
- package/dist/services/runtime.js +1 -1
- package/dist/services/session-query.js +2 -2
- package/dist/services/session-state.js +1 -1
- package/dist/services/session-store.js +271 -1
- package/dist/services/session-store.js.map +1 -0
- package/dist/services/sink-registry.js +1 -1
- package/dist/{session-state-C6SyphC0.js → session-state-BW0l2aNk.js} +3 -3
- package/dist/{session-state-C6SyphC0.js.map → session-state-BW0l2aNk.js.map} +1 -1
- package/dist/{sink-registry-DtrssBxF.js → sink-registry-D0MetcNq.js} +2 -2
- package/dist/{sink-registry-DtrssBxF.js.map → sink-registry-D0MetcNq.js.map} +1 -1
- package/dist/{subscription-g5W0Ggqx.js → subscription-Dzr5LqPX.js} +5 -3
- package/dist/subscription-Dzr5LqPX.js.map +1 -0
- package/dist/testkit/layers.d.ts +8 -2
- package/dist/testkit/layers.js +7 -3
- package/dist/testkit/layers.js.map +1 -1
- package/dist/testkit/transcript.d.ts +226 -0
- package/dist/testkit/transcript.js +1475 -0
- package/dist/testkit/transcript.js.map +1 -0
- package/dist/transcript.d.ts +25 -101
- package/dist/transcript.js +4 -3
- package/dist/transcript.js.map +1 -1
- package/dist/websocket/events.d.ts +2 -0
- package/dist/websocket/events.js +2 -0
- package/dist/websocket.d.ts +1 -2986
- package/dist/websocket.js +3 -504
- package/dist/websocket.js.map +1 -1
- package/dist/window-read-DBf1Iktt.d.ts +104 -0
- package/dist/window-read-U55aAeuz.js +184 -0
- package/dist/window-read-U55aAeuz.js.map +1 -0
- package/package.json +9 -1
- package/dist/session-store-DuEhcqIC.js +0 -414
- package/dist/session-store-DuEhcqIC.js.map +0 -1
- package/dist/subscription-g5W0Ggqx.js.map +0 -1
- package/dist/window-read-BDayZf7O.js.map +0 -1
package/dist/websocket.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"websocket.js","names":["PositiveInt","NonNegativeInt","PositiveInt","NonNegativeInt"],"sources":["../src/websocket/protocol.ts","../src/websocket/messages.ts","../src/websocket/delivery.ts","../src/websocket/transcript.ts","../src/websocket/transcript-client.ts","../src/websocket/transcript-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","import * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport { TranscriptCursor } from \"../transcript/records\";\nimport {\n TranscriptCoverage,\n TranscriptRequestId,\n TranscriptUpdate,\n} from \"../transcript/subscription\";\nimport {\n EDAWebSocketWireAckFrame,\n EDAWebSocketWireErrorFrame,\n EDAWebSocketWireHelloFrame,\n EDAWebSocketWireLaggedFrame,\n EDAWebSocketWirePingFrame,\n EDAWebSocketWirePongFrame,\n} from \"./protocol\";\n\nconst PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));\nconst NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\n\n// ---------------------------------------------------------------------------------------------\n// Negotiation\n// ---------------------------------------------------------------------------------------------\n\n/**\n * Transcript protocol major. A change of meaning that an older client would misread bumps it;\n * a client that sees another major performs one bounded reload.\n */\nexport const EDA_TRANSCRIPT_PROTOCOL_MAJOR = 1;\n\n/** Additive wire revision within a major; older clients drop fields they do not know. */\nexport const EDA_TRANSCRIPT_WIRE_VERSION = 1;\n\n/**\n * The small, stable envelope a client decodes before any version-specific schema, from the\n * socket hello and from the host's SSR data. Its shape never changes; everything else may.\n */\nexport const EDATranscriptNegotiation = Schema.Struct({\n protocolMajor: PositiveInt,\n wireVersion: PositiveInt,\n /** Optional features this server speaks; clients ignore names they do not know. */\n capabilities: Schema.Array(Schema.String),\n});\nexport type EDATranscriptNegotiation = typeof EDATranscriptNegotiation.Type;\n\n/** What this EDA release speaks. Hosts embed it in SSR data next to the transcript window. */\nexport const edaTranscriptNegotiation: EDATranscriptNegotiation = {\n protocolMajor: EDA_TRANSCRIPT_PROTOCOL_MAJOR,\n wireVersion: EDA_TRANSCRIPT_WIRE_VERSION,\n capabilities: [\"window\", \"page\", \"retain\", \"chunked-updates\", \"active-content\"],\n};\n\n/** Any value carrying the envelope under `negotiation`: a hello frame or SSR data. */\nconst NegotiationCarrier = Schema.Struct({ negotiation: EDATranscriptNegotiation });\n\n/** How a client should treat a server's negotiation envelope. */\nexport type EDATranscriptNegotiationResult =\n | { readonly _tag: \"Compatible\"; readonly remote: EDATranscriptNegotiation }\n /** The server speaks another major: reload once, preserving the viewport and draft. */\n | { readonly _tag: \"MajorMismatch\"; readonly remote: EDATranscriptNegotiation }\n /** No envelope could be decoded: an incompatible or non-transcript peer; also reload. */\n | { readonly _tag: \"Undecodable\" };\n\nconst decodeNegotiationCarrier = Schema.decodeUnknownOption(NegotiationCarrier);\n\n/**\n * Decode only the negotiation envelope from an untrusted hello frame or SSR payload and compare\n * it with this client's major. Run before decoding anything version-specific.\n */\nexport const negotiateEDATranscript = (\n carrier: unknown,\n localMajor: number = EDA_TRANSCRIPT_PROTOCOL_MAJOR,\n): EDATranscriptNegotiationResult => {\n const decoded = decodeNegotiationCarrier(carrier);\n if (decoded._tag === \"None\") return { _tag: \"Undecodable\" };\n const remote = decoded.value.negotiation;\n return remote.protocolMajor === localMajor\n ? { _tag: \"Compatible\", remote }\n : { _tag: \"MajorMismatch\", remote };\n};\n\n// ---------------------------------------------------------------------------------------------\n// Frames\n// ---------------------------------------------------------------------------------------------\n\n/** WebSocket close code: the server lost volatile transfer state; reconnect and resubscribe. */\nexport const EDA_WS_CLOSE_TRANSCRIPT_RESUBSCRIBE = 4009;\n\n/** First frame on a transcript socket: the event-socket hello plus the negotiation envelope. */\nexport const EDATranscriptHelloFrame = Schema.Struct({\n ...EDAWebSocketWireHelloFrame.fields,\n negotiation: EDATranscriptNegotiation,\n});\nexport type EDATranscriptHelloFrame = typeof EDATranscriptHelloFrame.Type;\n\n/** A transcript update that fits one frame. */\nexport const EDATranscriptUpdateFrame = Schema.Struct({\n _tag: Schema.Literal(\"transcript\"),\n frameId: PositiveInt,\n update: TranscriptUpdate,\n});\nexport type EDATranscriptUpdateFrame = typeof EDATranscriptUpdateFrame.Type;\n\n/**\n * One slice of an update too large for a frame. `data` slices concatenated in `index` order are\n * the JSON of one `TranscriptUpdate`; the client applies it only after slice `count - 1` (the\n * completion marker) and discards a transfer that is interrupted.\n */\nexport const EDATranscriptChunkFrame = Schema.Struct({\n _tag: Schema.Literal(\"transcript-chunk\"),\n frameId: PositiveInt,\n updateSeq: PositiveInt,\n index: NonNegativeInt,\n count: PositiveInt,\n data: Schema.String,\n}).check(Schema.makeFilter((chunk) => chunk.index < chunk.count || \"chunk index out of range\"));\nexport type EDATranscriptChunkFrame = typeof EDATranscriptChunkFrame.Type;\n\n/** Every server frame a transcript socket may carry. */\nexport const EDATranscriptServerFrame = Schema.Union([\n EDATranscriptHelloFrame,\n EDATranscriptUpdateFrame,\n EDATranscriptChunkFrame,\n EDAWebSocketWirePongFrame,\n EDAWebSocketWireLaggedFrame,\n EDAWebSocketWireErrorFrame,\n]);\nexport type EDATranscriptServerFrame = typeof EDATranscriptServerFrame.Type;\n\n/**\n * Start or restart the subscription. After SSR, `range` is what the page rendered, `tail` its\n * `!hasNewer`, and `since` its `throughSeq`; a reconnecting client sends what it last applied.\n * Without `range` the server replies with the latest `count` records.\n */\nexport const EDATranscriptSubscribeFrame = Schema.Struct({\n _tag: Schema.Literal(\"subscribe\"),\n requestId: Schema.optionalKey(TranscriptRequestId),\n range: Schema.optionalKey(TranscriptCoverage),\n tail: Schema.optionalKey(Schema.Boolean),\n since: Schema.optionalKey(SequenceNumber),\n count: Schema.optionalKey(PositiveInt),\n});\nexport type EDATranscriptSubscribeFrame = typeof EDATranscriptSubscribeFrame.Type;\n\n/** Extend the coverage from its edge: `cursor` is the coverage's `from` (before) or `to` (after). */\nexport const EDATranscriptPageFrame = Schema.Struct({\n _tag: Schema.Literal(\"page\"),\n requestId: Schema.optionalKey(TranscriptRequestId),\n direction: Schema.Literals([\"before\", \"after\"]),\n cursor: TranscriptCursor,\n count: PositiveInt,\n});\nexport type EDATranscriptPageFrame = typeof EDATranscriptPageFrame.Type;\n\n/** Narrow the coverage to a span inside it, so the server stops sending changes outside it. */\nexport const EDATranscriptRetainFrame = Schema.Struct({\n _tag: Schema.Literal(\"retain\"),\n requestId: Schema.optionalKey(TranscriptRequestId),\n from: TranscriptCursor,\n to: TranscriptCursor,\n});\nexport type EDATranscriptRetainFrame = typeof EDATranscriptRetainFrame.Type;\n\n/** A client request; each is answered by exactly one update, in arrival order. */\nexport const EDATranscriptRequestFrame = Schema.Union([\n EDATranscriptSubscribeFrame,\n EDATranscriptPageFrame,\n EDATranscriptRetainFrame,\n]);\nexport type EDATranscriptRequestFrame = typeof EDATranscriptRequestFrame.Type;\n\n/** Every client frame a transcript socket accepts. */\nexport const EDATranscriptClientFrame = Schema.Union([\n EDAWebSocketWireAckFrame,\n EDAWebSocketWirePingFrame,\n EDATranscriptSubscribeFrame,\n EDATranscriptPageFrame,\n EDATranscriptRetainFrame,\n]);\nexport type EDATranscriptClientFrame = typeof EDATranscriptClientFrame.Type;\n\n// ---------------------------------------------------------------------------------------------\n// Encoding and chunking\n// ---------------------------------------------------------------------------------------------\n\nconst encodeUpdate = Schema.encodeSync(TranscriptUpdate);\nconst encodeServerFrame = Schema.encodeSync(EDATranscriptServerFrame);\n\n/** Serialize one update once; frames embed this text, chunks slice it. */\nexport const encodeEDATranscriptUpdate = (update: TranscriptUpdate): string =>\n JSON.stringify(encodeUpdate(update));\n\n/** Serialize a non-update server frame. */\nexport const encodeEDATranscriptServerFrame = (frame: EDATranscriptServerFrame): string =>\n JSON.stringify(encodeServerFrame(frame));\n\n/** The single-frame form of an encoded update. */\nexport const edaTranscriptUpdateFrameText = (frameId: number, encodedUpdate: string): string =>\n `{\"_tag\":\"transcript\",\"frameId\":${frameId},\"update\":${encodedUpdate}}`;\n\n/** One chunk frame of an encoded update. */\nexport const edaTranscriptChunkFrameText = (input: {\n readonly frameId: number;\n readonly updateSeq: number;\n readonly index: number;\n readonly count: number;\n readonly data: string;\n}): string =>\n `{\"_tag\":\"transcript-chunk\",\"frameId\":${input.frameId},\"updateSeq\":${input.updateSeq},` +\n `\"index\":${input.index},\"count\":${input.count},\"data\":${JSON.stringify(input.data)}}`;\n\nconst textEncoder = new TextEncoder();\n\n/** UTF-8 byte length of a string. */\nexport const utf8ByteLength = (text: string): number => textEncoder.encode(text).byteLength;\n\n/** Bytes a chunk frame spends besides its data, with generous room for large numbers. */\nconst chunkFrameOverheadBytes = 160;\n\n/** Control characters JSON writes as a two-byte escape (`\\b`, `\\t`, `\\n`, `\\f`, `\\r`). */\nconst shortEscapes: ReadonlySet<number> = new Set([0x08, 0x09, 0x0a, 0x0c, 0x0d]);\n\n/** UTF-8 bytes one UTF-16 code unit costs inside a JSON string literal. */\nconst jsonStringUnitBytes = (code: number): number => {\n if (code === 0x22 || code === 0x5c) return 2;\n if (code < 0x20) return shortEscapes.has(code) ? 2 : 6;\n if (code < 0x80) return 1;\n if (code < 0x800) return 2;\n // A lone surrogate half is written as a `\\uXXXX` escape; pairs are costed by the caller.\n if (code >= 0xd800 && code <= 0xdfff) return 6;\n return 3;\n};\n\n/**\n * Split an encoded update into chunk data that each fit a frame of `maxFrameBytes`, never\n * splitting a surrogate pair.\n */\nexport const splitEDATranscriptUpdate = (\n encodedUpdate: string,\n maxFrameBytes: number,\n): ReadonlyArray<string> => {\n const budget = Math.max(16, maxFrameBytes - chunkFrameOverheadBytes);\n const chunks: string[] = [];\n let start = 0;\n let bytes = 0;\n for (let index = 0; index < encodedUpdate.length; index += 1) {\n const code = encodedUpdate.charCodeAt(index);\n const pair =\n code >= 0xd800 && code <= 0xdbff && index + 1 < encodedUpdate.length\n ? encodedUpdate.charCodeAt(index + 1)\n : undefined;\n const isPair = pair !== undefined && pair >= 0xdc00 && pair <= 0xdfff;\n const cost = isPair ? 4 : jsonStringUnitBytes(code);\n if (bytes + cost > budget && index > start) {\n chunks.push(encodedUpdate.slice(start, index));\n start = index;\n bytes = 0;\n }\n bytes += cost;\n if (isPair) index += 1;\n }\n if (start < encodedUpdate.length || chunks.length === 0) chunks.push(encodedUpdate.slice(start));\n return chunks;\n};\n","import * as Exit from \"effect/Exit\";\nimport * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport {\n TranscriptOrder,\n type TranscriptLogIncarnation,\n type TranscriptOrderKey,\n type TranscriptRecordView,\n type TranscriptVersion,\n} from \"../transcript/records\";\nimport {\n TranscriptUpdate,\n transcriptCoverageOf,\n type TranscriptCoverage,\n} from \"../transcript/subscription\";\nimport type {\n TranscriptActiveContent,\n TranscriptReadiness,\n TranscriptWindow,\n} from \"../transcript/window\";\nimport type { EDAWebSocketWireAckFrame } from \"./protocol\";\nimport {\n EDATranscriptChunkFrame,\n EDATranscriptUpdateFrame,\n negotiateEDATranscript,\n type EDATranscriptNegotiationResult,\n type EDATranscriptPageFrame,\n type EDATranscriptRetainFrame,\n type EDATranscriptSubscribeFrame,\n} from \"./transcript\";\n\n/**\n * The window a client holds: always exactly one complete cut. Top-level records are in\n * transcript order; dependencies are keyed by id and ordered as the server listed them.\n */\nexport interface EDATranscriptClientWindow {\n readonly incarnation: TranscriptLogIncarnation;\n readonly version: TranscriptVersion;\n readonly throughSeq: SequenceNumber;\n readonly coverage: TranscriptCoverage | undefined;\n readonly hasOlder: boolean;\n readonly hasNewer: boolean;\n readonly readiness: TranscriptReadiness;\n readonly records: ReadonlyArray<TranscriptRecordView>;\n readonly dependencies: ReadonlyArray<TranscriptRecordView>;\n readonly activeContent: ReadonlyArray<TranscriptActiveContent>;\n}\n\n/**\n * Reference client state for one transcript socket, independent of any UI framework.\n *\n * Hosts feed every server message to `applyEDATranscriptServerMessage`, send the ACK it returns,\n * and render `window`. Chunked updates are assembled here and applied only when complete, so the\n * rendered window never shows a partial update.\n */\nexport interface EDATranscriptClientState {\n readonly window: EDATranscriptClientWindow | undefined;\n /** Highest frame id received on the current socket. */\n readonly lastFrameId: number;\n /** The last update applied on the current socket. */\n readonly appliedUpdateSeq: number;\n readonly assembling:\n | { readonly updateSeq: number; readonly count: number; readonly data: ReadonlyArray<string> }\n | undefined;\n}\n\n/** A client that has rendered nothing yet. */\nexport const emptyEDATranscriptClientState: EDATranscriptClientState = {\n window: undefined,\n lastFrameId: 0,\n appliedUpdateSeq: 0,\n assembling: undefined,\n};\n\n/** Seed a client from the window its page was server-rendered with. */\nexport const edaTranscriptClientFromWindow = (\n window: TranscriptWindow,\n): EDATranscriptClientState => ({\n ...emptyEDATranscriptClientState,\n window: {\n incarnation: window.incarnation,\n version: window.version,\n throughSeq: window.throughSeq,\n coverage: transcriptCoverageOf(window),\n hasOlder: window.hasOlder,\n hasNewer: window.hasNewer,\n readiness: window.readiness,\n records: window.records,\n dependencies: window.dependencies,\n activeContent: window.activeContent ?? [],\n },\n});\n\n/**\n * Prepare for a new socket: per-socket counters restart and any partial transfer is discarded.\n * The applied window is kept; the next `subscribe` asks for changes since it.\n */\nexport const edaTranscriptClientReconnected = (\n state: EDATranscriptClientState,\n): EDATranscriptClientState => ({ ...emptyEDATranscriptClientState, window: state.window });\n\n/** What one server message did. */\nexport type EDATranscriptClientOutcome =\n | { readonly _tag: \"Hello\"; readonly negotiation: EDATranscriptNegotiationResult }\n | { readonly _tag: \"Applied\"; readonly updateSeq: number; readonly requestId?: string }\n | { readonly _tag: \"Partial\" }\n | { readonly _tag: \"Ignored\" }\n /** The stream is unusable (a gap, a bad frame, a protocol close): reconnect and resubscribe. */\n | { readonly _tag: \"Resubscribe\"; readonly reason: string };\n\nexport interface EDATranscriptClientStep {\n readonly state: EDATranscriptClientState;\n readonly outcome: EDATranscriptClientOutcome;\n /** Send this ACK when present: a transport receipt plus the applied cut. */\n readonly ack?: EDAWebSocketWireAckFrame;\n}\n\nconst decodeUpdateFrame = Schema.decodeUnknownExit(EDATranscriptUpdateFrame);\nconst decodeChunkFrame = Schema.decodeUnknownExit(EDATranscriptChunkFrame);\nconst decodeUpdate = Schema.decodeUnknownExit(TranscriptUpdate);\n\nconst peek = (value: unknown): { readonly tag?: string; readonly frameId?: number } => {\n if (typeof value !== \"object\" || value === null) return {};\n const tag = \"_tag\" in value && typeof value._tag === \"string\" ? value._tag : undefined;\n const frameId =\n \"frameId\" in value && typeof value.frameId === \"number\" && Number.isInteger(value.frameId)\n ? value.frameId\n : undefined;\n return {\n ...(tag === undefined ? {} : { tag }),\n ...(frameId === undefined ? {} : { frameId }),\n };\n};\n\n/** Apply one server text message. Frames must arrive in frame-id order without gaps. */\nexport const applyEDATranscriptServerMessage = (\n state: EDATranscriptClientState,\n message: string,\n): EDATranscriptClientStep => {\n let json: unknown;\n try {\n json = JSON.parse(message);\n } catch {\n return resubscribe(state, \"malformed server message\");\n }\n const { tag, frameId } = peek(json);\n switch (tag) {\n case \"hello\":\n return { state, outcome: { _tag: \"Hello\", negotiation: negotiateEDATranscript(json) } };\n case \"pong\":\n return { state, outcome: { _tag: \"Ignored\" } };\n case \"lagged\":\n case \"error\":\n return resubscribe(state, `server sent ${tag}`);\n }\n if (frameId === undefined) return { state, outcome: { _tag: \"Ignored\" } };\n if (frameId !== state.lastFrameId + 1) return resubscribe(state, \"frame gap\");\n const received: EDATranscriptClientState = { ...state, lastFrameId: frameId };\n\n if (tag === \"transcript\") {\n const decoded = decodeUpdateFrame(json);\n if (Exit.isFailure(decoded)) return resubscribe(state, \"undecodable update\");\n if (received.assembling !== undefined)\n return resubscribe(state, \"update interrupted a transfer\");\n return applyUpdate(received, decoded.value.update);\n }\n if (tag === \"transcript-chunk\") {\n const decoded = decodeChunkFrame(json);\n if (Exit.isFailure(decoded)) return resubscribe(state, \"undecodable chunk\");\n const chunk = decoded.value;\n const assembling = received.assembling ?? {\n updateSeq: chunk.updateSeq,\n count: chunk.count,\n data: [],\n };\n if (\n assembling.updateSeq !== chunk.updateSeq ||\n assembling.count !== chunk.count ||\n assembling.data.length !== chunk.index\n ) {\n return resubscribe(state, \"interrupted chunked transfer\");\n }\n const data = [...assembling.data, chunk.data];\n if (data.length < chunk.count) {\n const next = { ...received, assembling: { ...assembling, data } };\n return { state: next, outcome: { _tag: \"Partial\" }, ack: ackOf(next) };\n }\n let updateJson: unknown;\n try {\n updateJson = JSON.parse(data.join(\"\"));\n } catch {\n return resubscribe(state, \"malformed chunked update\");\n }\n const update = decodeUpdate(updateJson);\n if (Exit.isFailure(update) || update.value.updateSeq !== chunk.updateSeq) {\n return resubscribe(state, \"undecodable chunked update\");\n }\n return applyUpdate({ ...received, assembling: undefined }, update.value);\n }\n // A frame kind from a newer server: acknowledge its receipt and ignore it.\n return { state: received, outcome: { _tag: \"Ignored\" }, ack: ackOf(received) };\n};\n\nconst resubscribe = (state: EDATranscriptClientState, reason: string): EDATranscriptClientStep => ({\n state: { ...state, assembling: undefined },\n outcome: { _tag: \"Resubscribe\", reason },\n});\n\nconst ackOf = (state: EDATranscriptClientState): EDAWebSocketWireAckFrame => ({\n _tag: \"ack\",\n frameId: state.lastFrameId,\n durableThroughSeq: state.appliedUpdateSeq === 0 ? 0 : (state.window?.throughSeq ?? 0),\n appliedUpdateSeq: state.appliedUpdateSeq,\n});\n\nconst orderKeyOf = (record: TranscriptRecordView): TranscriptOrderKey | undefined =>\n \"position\" in record && record.position !== undefined\n ? { ...record.position, recordId: record.id }\n : undefined;\n\nconst covered = (\n coverage: TranscriptCoverage | undefined,\n record: TranscriptRecordView,\n): boolean => {\n const key = orderKeyOf(record);\n return (\n coverage !== undefined &&\n key !== undefined &&\n TranscriptOrder(coverage.from, key) <= 0 &&\n TranscriptOrder(key, coverage.to) <= 0\n );\n};\n\nconst applyUpdate = (\n state: EDATranscriptClientState,\n update: TranscriptUpdate,\n): EDATranscriptClientStep => {\n if (update.updateSeq !== state.appliedUpdateSeq + 1) return resubscribe(state, \"update gap\");\n const previous = state.window;\n if (\n update.mode === \"patch\" &&\n (previous === undefined ||\n previous.incarnation !== update.incarnation ||\n previous.version !== update.version)\n ) {\n return resubscribe(state, \"patch without its base\");\n }\n const base = update.mode === \"patch\" ? previous : undefined;\n\n const topLevel = new Map((base?.records ?? []).map((record) => [record.id, record]));\n for (const record of update.records) topLevel.set(record.id, record);\n const records = [...topLevel.values()]\n .filter((record) => covered(update.coverage, record))\n .sort((left, right) => {\n const leftKey = orderKeyOf(left);\n const rightKey = orderKeyOf(right);\n return leftKey === undefined || rightKey === undefined\n ? 0\n : TranscriptOrder(leftKey, rightKey);\n });\n\n const dependencyMap = new Map((base?.dependencies ?? []).map((record) => [record.id, record]));\n for (const record of update.dependencies) dependencyMap.set(record.id, record);\n const dependencies = update.dependencyIds.flatMap((id) => {\n const record = dependencyMap.get(id);\n return record === undefined ? [] : [record];\n });\n if (dependencies.length !== update.dependencyIds.length) {\n return resubscribe(state, \"patch referenced a dependency the client does not hold\");\n }\n\n const window: EDATranscriptClientWindow = {\n incarnation: update.incarnation,\n version: update.version,\n throughSeq: update.throughSeq,\n coverage: update.coverage,\n hasOlder: update.hasOlder,\n hasNewer: update.hasNewer,\n readiness: update.readiness,\n records,\n dependencies,\n activeContent:\n update.readiness._tag !== \"Ready\" ? [] : (update.activeContent ?? base?.activeContent ?? []),\n };\n const next: EDATranscriptClientState = {\n ...state,\n window,\n appliedUpdateSeq: update.updateSeq,\n assembling: undefined,\n };\n return {\n state: next,\n outcome: {\n _tag: \"Applied\",\n updateSeq: update.updateSeq,\n ...(update.requestId === undefined ? {} : { requestId: update.requestId }),\n },\n ack: ackOf(next),\n };\n};\n\n/**\n * The request a client sends first on every socket: changes since the window it holds over the\n * span it holds, or the latest `count` records when it holds none.\n */\nexport const edaTranscriptSubscribeRequest = (\n state: EDATranscriptClientState,\n options?: { readonly count?: number; readonly requestId?: string },\n): EDATranscriptSubscribeFrame => {\n const window = state.window;\n const extra = {\n ...(options?.count === undefined ? {} : { count: options.count }),\n ...(options?.requestId === undefined ? {} : { requestId: options.requestId }),\n };\n return window?.coverage === undefined\n ? { _tag: \"subscribe\", ...extra }\n : {\n _tag: \"subscribe\",\n range: window.coverage,\n tail: !window.hasNewer,\n since: window.throughSeq,\n ...extra,\n };\n};\n\n/** Page from the held coverage's edge, or `undefined` when there is nothing to page from. */\nexport const edaTranscriptPageRequest = (\n state: EDATranscriptClientState,\n direction: \"before\" | \"after\",\n count: number,\n requestId?: string,\n): EDATranscriptPageFrame | undefined => {\n const coverage = state.window?.coverage;\n if (coverage === undefined) return undefined;\n return {\n _tag: \"page\",\n direction,\n cursor: direction === \"before\" ? coverage.from : coverage.to,\n count,\n ...(requestId === undefined ? {} : { requestId }),\n };\n};\n\n/**\n * Keep only the top-level records from `fromIndex` to `toIndex` (inclusive) of the held window;\n * the server confirms with an update whose coverage is the narrowed span.\n */\nexport const edaTranscriptRetainRequest = (\n state: EDATranscriptClientState,\n fromIndex: number,\n toIndex: number,\n requestId?: string,\n): EDATranscriptRetainFrame | undefined => {\n const window = state.window;\n const from = window?.records[fromIndex];\n const to = window?.records[toIndex];\n const fromKey = from === undefined ? undefined : orderKeyOf(from);\n const toKey = to === undefined ? undefined : orderKeyOf(to);\n if (window === undefined || fromKey === undefined || toKey === undefined) return undefined;\n const scope = { incarnation: window.incarnation, version: window.version };\n return {\n _tag: \"retain\",\n from: { ...scope, ...fromKey, anchorSeq: SequenceNumber.make(fromKey.anchorSeq) },\n to: { ...scope, ...toKey, anchorSeq: SequenceNumber.make(toKey.anchorSeq) },\n ...(requestId === undefined ? {} : { requestId }),\n };\n};\n","import * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport { TranscriptSubscriptionBase, type TranscriptUpdate } from \"../transcript/subscription\";\nimport type { EDAWebSocketFlowControl } from \"./messages\";\nimport type { EDAWebSocketWireAckFrame } from \"./protocol\";\nimport {\n EDATranscriptRequestFrame,\n edaTranscriptChunkFrameText,\n edaTranscriptUpdateFrameText,\n splitEDATranscriptUpdate,\n utf8ByteLength,\n} from \"./transcript\";\n\nconst PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));\nconst NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\n\n/** A chunked update whose frames are not all sent yet; its chunk data is volatile. */\nexport const EDATranscriptTransfer = Schema.Struct({\n updateSeq: PositiveInt,\n throughSeq: SequenceNumber,\n count: PositiveInt,\n nextIndex: NonNegativeInt,\n});\nexport type EDATranscriptTransfer = typeof EDATranscriptTransfer.Type;\n\n/**\n * Everything a transcript socket needs to resume after hibernation, persisted in its attachment\n * before every send and after every applied ACK.\n *\n * Transport receipts (`inFlight`, `lastAckedFrameId`) bound frames in flight exactly as on an\n * event socket. The applied cut (`appliedUpdateSeq`, `appliedThroughSeq`) is the last update the\n * client applied completely. `subscription` is the base the next update is planned against, and\n * `requests` are client requests not yet answered. A persisted `transfer` means chunk data was\n * staged in memory; a socket restored with one cannot finish it and is closed.\n */\nexport const EDATranscriptDeliveryCheckpoint = Schema.Struct({\n lastAckedFrameId: NonNegativeInt,\n nextFrameId: PositiveInt,\n inFlight: Schema.Array(Schema.Struct({ frameId: PositiveInt, sentAtMs: Schema.Number })),\n nextUpdateSeq: PositiveInt,\n completedUpdateSeq: NonNegativeInt,\n completedThroughSeq: SequenceNumber,\n appliedUpdateSeq: NonNegativeInt,\n appliedThroughSeq: SequenceNumber,\n transfer: Schema.optionalKey(EDATranscriptTransfer),\n subscription: Schema.optionalKey(TranscriptSubscriptionBase),\n requests: Schema.Array(EDATranscriptRequestFrame),\n});\nexport type EDATranscriptDeliveryCheckpoint = typeof EDATranscriptDeliveryCheckpoint.Type;\n\n/** Bounds on one transcript socket beyond the shared flow-control policy. */\nexport interface EDATranscriptDeliveryLimits {\n /** Largest encoded update staged for one transfer; a larger one closes the socket. */\n readonly maxStagedBytes: number;\n /** Unanswered client requests held at once; more is a protocol violation. */\n readonly maxPendingRequests: number;\n}\n\nexport const defaultEDATranscriptDeliveryLimits: EDATranscriptDeliveryLimits = {\n maxStagedBytes: 8 * 1_048_576,\n maxPendingRequests: 4,\n};\n\n/** In-memory state of one transcript socket. */\nexport interface EDATranscriptDeliveryState extends EDATranscriptDeliveryCheckpoint {\n readonly policy: EDAWebSocketFlowControl;\n /** Chunk data of `transfer` not yet sent, in order. Never persisted. */\n readonly staged: ReadonlyArray<string>;\n}\n\n/** Delivery state for a newly accepted transcript socket. */\nexport const makeTranscriptDeliveryState = (\n policy: EDAWebSocketFlowControl,\n): EDATranscriptDeliveryState => ({\n policy,\n lastAckedFrameId: 0,\n nextFrameId: 1,\n inFlight: [],\n nextUpdateSeq: 1,\n completedUpdateSeq: 0,\n completedThroughSeq: SequenceNumber.make(0),\n appliedUpdateSeq: 0,\n appliedThroughSeq: SequenceNumber.make(0),\n requests: [],\n staged: [],\n});\n\n/**\n * Restore a hibernated transcript socket. A socket that was mid-transfer lost its staged chunks\n * with the isolate and cannot resume: the caller closes it and the client resubscribes.\n */\nexport const restoreTranscriptDeliveryState = (\n policy: EDAWebSocketFlowControl,\n checkpoint: EDATranscriptDeliveryCheckpoint,\n):\n | { readonly _tag: \"Restored\"; readonly state: EDATranscriptDeliveryState }\n | { readonly _tag: \"TransferLost\" } =>\n checkpoint.transfer === undefined\n ? { _tag: \"Restored\", state: { ...checkpoint, policy, staged: [] } }\n : { _tag: \"TransferLost\" };\n\n/** The attachment-safe part of the state. */\nexport const checkpointTranscriptDelivery = (\n state: EDATranscriptDeliveryState,\n): EDATranscriptDeliveryCheckpoint => ({\n lastAckedFrameId: state.lastAckedFrameId,\n nextFrameId: state.nextFrameId,\n inFlight: state.inFlight,\n nextUpdateSeq: state.nextUpdateSeq,\n completedUpdateSeq: state.completedUpdateSeq,\n completedThroughSeq: state.completedThroughSeq,\n appliedUpdateSeq: state.appliedUpdateSeq,\n appliedThroughSeq: state.appliedThroughSeq,\n ...(state.transfer === undefined ? {} : { transfer: state.transfer }),\n ...(state.subscription === undefined ? {} : { subscription: state.subscription }),\n requests: state.requests,\n});\n\n/** Frames that may be sent before the client's next receipt. */\nexport const transcriptDeliveryCapacity = (state: EDATranscriptDeliveryState): number =>\n state.policy.maxInFlightFrames - state.inFlight.length;\n\n/** Lazily enforced ACK deadline: no resident timer, checked on each transition. */\nexport const transcriptAckTimedOut = (state: EDATranscriptDeliveryState, nowMs: number): boolean =>\n state.inFlight.some((frame) => frame.sentAtMs + state.policy.ackTimeoutMs <= nowMs);\n\n/** Result of a transition that may emit frames. */\nexport interface EDATranscriptSendResult {\n readonly state: EDATranscriptDeliveryState;\n /** Encoded frames to send in order, after persisting `state`. */\n readonly frames: ReadonlyArray<string>;\n}\n\n/**\n * Start sending one planned update, captured from its own snapshot.\n *\n * `subscription` becomes the base for the next update immediately: nothing else is sent until\n * this update's last frame is, so the client can only apply later updates on top of it. An\n * update within the frame limit is one frame; a larger one is chunked and as many chunks as\n * flow control allows are sent now, the rest staged.\n */\nexport const startTranscriptUpdate = (\n state: EDATranscriptDeliveryState,\n input: {\n readonly update: TranscriptUpdate;\n readonly encodedUpdate: string;\n readonly subscription: TranscriptSubscriptionBase;\n },\n limits: EDATranscriptDeliveryLimits,\n nowMs: number,\n):\n | ({ readonly _tag: \"Sending\" } & EDATranscriptSendResult)\n | { readonly _tag: \"TooLarge\"; readonly bytes: number } => {\n if (state.transfer !== undefined) {\n throw new Error(\"A transcript update cannot start while another is being transferred\");\n }\n if (input.update.updateSeq !== state.nextUpdateSeq) {\n throw new Error(\"A transcript update must carry the socket's next update seq\");\n }\n const updateSeq = input.update.updateSeq;\n const advanced: EDATranscriptDeliveryState = {\n ...state,\n nextUpdateSeq: updateSeq + 1,\n subscription: input.subscription,\n };\n const single = edaTranscriptUpdateFrameText(state.nextFrameId, input.encodedUpdate);\n if (utf8ByteLength(single) <= state.policy.maxFrameBytes) {\n return {\n _tag: \"Sending\",\n ...sendFrames(\n {\n ...advanced,\n completedUpdateSeq: updateSeq,\n completedThroughSeq: input.update.throughSeq,\n },\n [single],\n nowMs,\n ),\n };\n }\n const bytes = utf8ByteLength(input.encodedUpdate);\n if (bytes > limits.maxStagedBytes) return { _tag: \"TooLarge\", bytes };\n const chunks = splitEDATranscriptUpdate(input.encodedUpdate, state.policy.maxFrameBytes);\n return {\n _tag: \"Sending\",\n ...pumpTranscriptTransfer(\n {\n ...advanced,\n transfer: {\n updateSeq,\n throughSeq: input.update.throughSeq,\n count: chunks.length,\n nextIndex: 0,\n },\n staged: chunks,\n },\n nowMs,\n ),\n };\n};\n\n/** Send staged chunks of the transfer in progress while flow control allows. */\nexport const pumpTranscriptTransfer = (\n state: EDATranscriptDeliveryState,\n nowMs: number,\n): EDATranscriptSendResult => {\n let next = state;\n const frames: string[] = [];\n while (next.transfer !== undefined && transcriptDeliveryCapacity(next) > 0) {\n const transfer: EDATranscriptTransfer = next.transfer;\n const [data, ...rest] = next.staged;\n if (data === undefined) break;\n const text = edaTranscriptChunkFrameText({\n frameId: next.nextFrameId,\n updateSeq: transfer.updateSeq,\n index: transfer.nextIndex,\n count: transfer.count,\n data,\n });\n const nextIndex = transfer.nextIndex + 1;\n const done = nextIndex === transfer.count;\n const { transfer: _sent, ...withoutTransfer } = next;\n const sent = sendFrames(\n done\n ? {\n ...withoutTransfer,\n staged: [],\n completedUpdateSeq: transfer.updateSeq,\n completedThroughSeq: transfer.throughSeq,\n }\n : { ...next, staged: rest, transfer: { ...transfer, nextIndex } },\n [text],\n nowMs,\n );\n next = sent.state;\n frames.push(...sent.frames);\n }\n return { state: next, frames };\n};\n\nconst sendFrames = (\n state: EDATranscriptDeliveryState,\n texts: ReadonlyArray<string>,\n nowMs: number,\n): EDATranscriptSendResult => {\n // Frame texts embed `state.nextFrameId` onwards in order.\n const inFlight = texts.map((_, index) => ({\n frameId: state.nextFrameId + index,\n sentAtMs: nowMs,\n }));\n return {\n state: {\n ...state,\n inFlight: [...state.inFlight, ...inFlight],\n nextFrameId: state.nextFrameId + texts.length,\n },\n frames: texts,\n };\n};\n\n/** Outcome of one client ACK on a transcript socket. */\nexport type EDATranscriptAckResult =\n | { readonly _tag: \"Applied\"; readonly state: EDATranscriptDeliveryState }\n | { readonly _tag: \"Ignored\" }\n | { readonly _tag: \"ProtocolError\"; readonly message: string };\n\n/**\n * Apply one ACK. The receipt frees flow-control capacity cumulatively; the applied cut may only\n * name an update whose frames were all sent, and never moves backwards.\n */\nexport const onTranscriptAck = (\n state: EDATranscriptDeliveryState,\n ack: EDAWebSocketWireAckFrame,\n): EDATranscriptAckResult => {\n const appliedUpdateSeq = ack.appliedUpdateSeq ?? state.appliedUpdateSeq;\n const advancesApplied = appliedUpdateSeq > state.appliedUpdateSeq;\n if (ack.frameId <= state.lastAckedFrameId) {\n return advancesApplied\n ? { _tag: \"ProtocolError\", message: \"Duplicate ACK attempted to advance the applied cut\" }\n : { _tag: \"Ignored\" };\n }\n if (ack.frameId >= state.nextFrameId) {\n return { _tag: \"ProtocolError\", message: \"ACK referenced an unsent frame\" };\n }\n if (appliedUpdateSeq < state.appliedUpdateSeq) {\n return { _tag: \"ProtocolError\", message: \"ACK applied cut moved backwards\" };\n }\n if (appliedUpdateSeq > state.completedUpdateSeq) {\n return { _tag: \"ProtocolError\", message: \"ACK applied an incomplete update\" };\n }\n // `throughSeq` may fall between updates (a new incarnation, a building window), so it is not\n // monotonic; it must match the update it names when that update is the last one completed.\n if (\n advancesApplied &&\n appliedUpdateSeq === state.completedUpdateSeq &&\n ack.durableThroughSeq !== state.completedThroughSeq\n ) {\n return { _tag: \"ProtocolError\", message: \"ACK applied cut names another update's seq\" };\n }\n return {\n _tag: \"Applied\",\n state: {\n ...state,\n lastAckedFrameId: ack.frameId,\n inFlight: state.inFlight.filter((frame) => frame.frameId > ack.frameId),\n appliedUpdateSeq,\n appliedThroughSeq: advancesApplied\n ? SequenceNumber.make(ack.durableThroughSeq)\n : state.appliedThroughSeq,\n },\n };\n};\n\n/** Queue one client request, or report that the client exceeded its request bound. */\nexport const enqueueTranscriptRequest = (\n state: EDATranscriptDeliveryState,\n request: EDATranscriptRequestFrame,\n limits: EDATranscriptDeliveryLimits,\n): EDATranscriptDeliveryState | undefined =>\n state.requests.length >= limits.maxPendingRequests\n ? undefined\n : { ...state, requests: [...state.requests, request] };\n"],"mappings":";;;;;;;;;;AAKA,MAAMA,gBAAc,OAAO,IAAI,MAAM,OAAO,cAAc,CAAC,CAAC;AAC5D,MAAMC,mBAAiB,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC;;AAGxE,MAAa,uCAAuC;;AAGpD,MAAa,8BAA8B,OAAO,OAAO;CACvD,cAAcD;;CAEd,qBAAqBA;CACrB,eAAeA;CACf,gBAAgBA;CAChB,mBAAmBA;;CAEnB,gBAAgB,OAAO,YAAYA,aAAW;CAC9C,gCAAgCA;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,iBAAiB,OAAO,QAAA,CAA4C;CACpE,cAAc,OAAO;CACrB,WAAWC;CACX,aAAa;AACf,CAAC;AAGD,MAAa,i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,MAAM,KAAK,GAAG,WAAW;EACxC,SAAS,MAAM,cAAc;EAC7B,UAAU;CACZ,EAAE;CACF,OAAO;EACL,OAAO;GACL,GAAG;GACH,UAAU,CAAC,GAAG,MAAM,UAAU,GAAG,QAAQ;GACzC,aAAa,MAAM,cAAc,MAAM;EACzC;EACA,QAAQ;CACV;AACF;;;;;AAYA,MAAa,mBACX,OACA,QAC2B;CAC3B,MAAM,mBAAmB,IAAI,oBAAoB,MAAM;CACvD,MAAM,kBAAkB,mBAAmB,MAAM;CACjD,IAAI,IAAI,WAAW,MAAM,kBACvB,OAAO,kBACH;EAAE,MAAM;EAAiB,SAAS;CAAqD,IACvF,EAAE,MAAM,UAAU;CAExB,IAAI,IAAI,WAAW,MAAM,aACvB,OAAO;EAAE,MAAM;EAAiB,SAAS;CAAiC;CAE5E,IAAI,mBAAmB,MAAM,kBAC3B,OAAO;EAAE,MAAM;EAAiB,SAAS;CAAkC;CAE7E,IAAI,mBAAmB,MAAM,oBAC3B,OAAO;EAAE,MAAM;EAAiB,SAAS;CAAmC;CAI9E,IACE,mBACA,qBAAqB,MAAM,sBAC3B,IAAI,sBAAsB,MAAM,qBAEhC,OAAO;EAAE,MAAM;EAAiB,SAAS;CAA6C;CAExF,OAAO;EACL,MAAM;EACN,OAAO;GACL,GAAG;GACH,kBAAkB,IAAI;GACtB,UAAU,MAAM,SAAS,QAAQ,UAAU,MAAM,UAAU,IAAI,OAAO;GACtE;GACA,mBAAmB,kBACf,eAAe,KAAK,IAAI,iBAAiB,IACzC,MAAM;EACZ;CACF;AACF;;AAGA,MAAa,4BACX,OACA,SACA,WAEA,MAAM,SAAS,UAAU,OAAO,qBAC5B,KAAA,IACA;CAAE,GAAG;CAAO,UAAU,CAAC,GAAG,MAAM,UAAU,OAAO;AAAE"}
|
|
1
|
+
{"version":3,"file":"websocket.js","names":["PositiveInt","NonNegativeInt"],"sources":["../src/websocket/transcript.ts","../src/websocket/transcript-client.ts","../src/websocket/transcript-delivery.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport { TranscriptCursor } from \"../transcript/records\";\nimport {\n TranscriptCoverage,\n TranscriptRequestId,\n TranscriptUpdate,\n} from \"../transcript/subscription\";\nimport {\n EDAWebSocketWireAckFrame,\n EDAWebSocketWireErrorFrame,\n EDAWebSocketWireHelloFrame,\n EDAWebSocketWireLaggedFrame,\n EDAWebSocketWirePingFrame,\n EDAWebSocketWirePongFrame,\n} from \"./protocol\";\n\nconst PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));\nconst NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\n\n// ---------------------------------------------------------------------------------------------\n// Negotiation\n// ---------------------------------------------------------------------------------------------\n\n/**\n * Transcript protocol major. A change of meaning that an older client would misread bumps it;\n * a client that sees another major performs one bounded reload.\n */\nexport const EDA_TRANSCRIPT_PROTOCOL_MAJOR = 1;\n\n/** Additive wire revision within a major; older clients drop fields they do not know. */\nexport const EDA_TRANSCRIPT_WIRE_VERSION = 1;\n\n/**\n * The small, stable envelope a client decodes before any version-specific schema, from the\n * socket hello and from the host's SSR data. Its shape never changes; everything else may.\n */\nexport const EDATranscriptNegotiation = Schema.Struct({\n protocolMajor: PositiveInt,\n wireVersion: PositiveInt,\n /** Optional features this server speaks; clients ignore names they do not know. */\n capabilities: Schema.Array(Schema.String),\n});\nexport type EDATranscriptNegotiation = typeof EDATranscriptNegotiation.Type;\n\n/** What this EDA release speaks. Hosts embed it in SSR data next to the transcript window. */\nexport const edaTranscriptNegotiation: EDATranscriptNegotiation = {\n protocolMajor: EDA_TRANSCRIPT_PROTOCOL_MAJOR,\n wireVersion: EDA_TRANSCRIPT_WIRE_VERSION,\n capabilities: [\"window\", \"page\", \"retain\", \"chunked-updates\", \"active-content\"],\n};\n\n/** Any value carrying the envelope under `negotiation`: a hello frame or SSR data. */\nconst NegotiationCarrier = Schema.Struct({ negotiation: EDATranscriptNegotiation });\n\n/** How a client should treat a server's negotiation envelope. */\nexport type EDATranscriptNegotiationResult =\n | { readonly _tag: \"Compatible\"; readonly remote: EDATranscriptNegotiation }\n /** The server speaks another major: reload once, preserving the viewport and draft. */\n | { readonly _tag: \"MajorMismatch\"; readonly remote: EDATranscriptNegotiation }\n /** No envelope could be decoded: an incompatible or non-transcript peer; also reload. */\n | { readonly _tag: \"Undecodable\" };\n\nconst decodeNegotiationCarrier = Schema.decodeUnknownOption(NegotiationCarrier);\n\n/**\n * Decode only the negotiation envelope from an untrusted hello frame or SSR payload and compare\n * it with this client's major. Run before decoding anything version-specific.\n */\nexport const negotiateEDATranscript = (\n carrier: unknown,\n localMajor: number = EDA_TRANSCRIPT_PROTOCOL_MAJOR,\n): EDATranscriptNegotiationResult => {\n const decoded = decodeNegotiationCarrier(carrier);\n if (decoded._tag === \"None\") return { _tag: \"Undecodable\" };\n const remote = decoded.value.negotiation;\n return remote.protocolMajor === localMajor\n ? { _tag: \"Compatible\", remote }\n : { _tag: \"MajorMismatch\", remote };\n};\n\n// ---------------------------------------------------------------------------------------------\n// Frames\n// ---------------------------------------------------------------------------------------------\n\n/** WebSocket close code: the server lost volatile transfer state; reconnect and resubscribe. */\nexport const EDA_WS_CLOSE_TRANSCRIPT_RESUBSCRIBE = 4009;\n\n/** First frame on a transcript socket: the event-socket hello plus the negotiation envelope. */\nexport const EDATranscriptHelloFrame = Schema.Struct({\n ...EDAWebSocketWireHelloFrame.fields,\n negotiation: EDATranscriptNegotiation,\n});\nexport type EDATranscriptHelloFrame = typeof EDATranscriptHelloFrame.Type;\n\n/** A transcript update that fits one frame. */\nexport const EDATranscriptUpdateFrame = Schema.Struct({\n _tag: Schema.Literal(\"transcript\"),\n frameId: PositiveInt,\n update: TranscriptUpdate,\n});\nexport type EDATranscriptUpdateFrame = typeof EDATranscriptUpdateFrame.Type;\n\n/**\n * One slice of an update too large for a frame. `data` slices concatenated in `index` order are\n * the JSON of one `TranscriptUpdate`; the client applies it only after slice `count - 1` (the\n * completion marker) and discards a transfer that is interrupted.\n */\nexport const EDATranscriptChunkFrame = Schema.Struct({\n _tag: Schema.Literal(\"transcript-chunk\"),\n frameId: PositiveInt,\n updateSeq: PositiveInt,\n index: NonNegativeInt,\n count: PositiveInt,\n data: Schema.String,\n}).check(Schema.makeFilter((chunk) => chunk.index < chunk.count || \"chunk index out of range\"));\nexport type EDATranscriptChunkFrame = typeof EDATranscriptChunkFrame.Type;\n\n/** Every server frame a transcript socket may carry. */\nexport const EDATranscriptServerFrame = Schema.Union([\n EDATranscriptHelloFrame,\n EDATranscriptUpdateFrame,\n EDATranscriptChunkFrame,\n EDAWebSocketWirePongFrame,\n EDAWebSocketWireLaggedFrame,\n EDAWebSocketWireErrorFrame,\n]);\nexport type EDATranscriptServerFrame = typeof EDATranscriptServerFrame.Type;\n\n/**\n * Start or restart the subscription. After SSR, `range` is what the page rendered, `tail` its\n * `!hasNewer`, and `since` its `throughSeq`; a reconnecting client sends what it last applied.\n * Without `range` the server replies with the latest `count` records.\n */\nexport const EDATranscriptSubscribeFrame = Schema.Struct({\n _tag: Schema.Literal(\"subscribe\"),\n requestId: Schema.optionalKey(TranscriptRequestId),\n range: Schema.optionalKey(TranscriptCoverage),\n tail: Schema.optionalKey(Schema.Boolean),\n since: Schema.optionalKey(SequenceNumber),\n count: Schema.optionalKey(PositiveInt),\n});\nexport type EDATranscriptSubscribeFrame = typeof EDATranscriptSubscribeFrame.Type;\n\n/** Extend the coverage from its edge: `cursor` is the coverage's `from` (before) or `to` (after). */\nexport const EDATranscriptPageFrame = Schema.Struct({\n _tag: Schema.Literal(\"page\"),\n requestId: Schema.optionalKey(TranscriptRequestId),\n direction: Schema.Literals([\"before\", \"after\"]),\n cursor: TranscriptCursor,\n count: PositiveInt,\n});\nexport type EDATranscriptPageFrame = typeof EDATranscriptPageFrame.Type;\n\n/** Narrow the coverage to a span inside it, so the server stops sending changes outside it. */\nexport const EDATranscriptRetainFrame = Schema.Struct({\n _tag: Schema.Literal(\"retain\"),\n requestId: Schema.optionalKey(TranscriptRequestId),\n from: TranscriptCursor,\n to: TranscriptCursor,\n});\nexport type EDATranscriptRetainFrame = typeof EDATranscriptRetainFrame.Type;\n\n/** A client request; each is answered by exactly one update, in arrival order. */\nexport const EDATranscriptRequestFrame = Schema.Union([\n EDATranscriptSubscribeFrame,\n EDATranscriptPageFrame,\n EDATranscriptRetainFrame,\n]);\nexport type EDATranscriptRequestFrame = typeof EDATranscriptRequestFrame.Type;\n\n/** Every client frame a transcript socket accepts. */\nexport const EDATranscriptClientFrame = Schema.Union([\n EDAWebSocketWireAckFrame,\n EDAWebSocketWirePingFrame,\n EDATranscriptSubscribeFrame,\n EDATranscriptPageFrame,\n EDATranscriptRetainFrame,\n]);\nexport type EDATranscriptClientFrame = typeof EDATranscriptClientFrame.Type;\n\n// ---------------------------------------------------------------------------------------------\n// Encoding and chunking\n// ---------------------------------------------------------------------------------------------\n\nconst encodeUpdate = Schema.encodeSync(TranscriptUpdate);\nconst encodeServerFrame = Schema.encodeSync(EDATranscriptServerFrame);\n\n/** Serialize one update once; frames embed this text, chunks slice it. */\nexport const encodeEDATranscriptUpdate = (update: TranscriptUpdate): string =>\n JSON.stringify(encodeUpdate(update));\n\n/** Serialize a non-update server frame. */\nexport const encodeEDATranscriptServerFrame = (frame: EDATranscriptServerFrame): string =>\n JSON.stringify(encodeServerFrame(frame));\n\n/** The single-frame form of an encoded update. */\nexport const edaTranscriptUpdateFrameText = (frameId: number, encodedUpdate: string): string =>\n `{\"_tag\":\"transcript\",\"frameId\":${frameId},\"update\":${encodedUpdate}}`;\n\n/** One chunk frame of an encoded update. */\nexport const edaTranscriptChunkFrameText = (input: {\n readonly frameId: number;\n readonly updateSeq: number;\n readonly index: number;\n readonly count: number;\n readonly data: string;\n}): string =>\n `{\"_tag\":\"transcript-chunk\",\"frameId\":${input.frameId},\"updateSeq\":${input.updateSeq},` +\n `\"index\":${input.index},\"count\":${input.count},\"data\":${JSON.stringify(input.data)}}`;\n\nconst textEncoder = new TextEncoder();\n\n/** UTF-8 byte length of a string. */\nexport const utf8ByteLength = (text: string): number => textEncoder.encode(text).byteLength;\n\n/** Bytes a chunk frame spends besides its data, with generous room for large numbers. */\nconst chunkFrameOverheadBytes = 160;\n\n/** Control characters JSON writes as a two-byte escape (`\\b`, `\\t`, `\\n`, `\\f`, `\\r`). */\nconst shortEscapes: ReadonlySet<number> = new Set([0x08, 0x09, 0x0a, 0x0c, 0x0d]);\n\n/** UTF-8 bytes one UTF-16 code unit costs inside a JSON string literal. */\nconst jsonStringUnitBytes = (code: number): number => {\n if (code === 0x22 || code === 0x5c) return 2;\n if (code < 0x20) return shortEscapes.has(code) ? 2 : 6;\n if (code < 0x80) return 1;\n if (code < 0x800) return 2;\n // A lone surrogate half is written as a `\\uXXXX` escape; pairs are costed by the caller.\n if (code >= 0xd800 && code <= 0xdfff) return 6;\n return 3;\n};\n\n/**\n * Split an encoded update into chunk data that each fit a frame of `maxFrameBytes`, never\n * splitting a surrogate pair.\n */\nexport const splitEDATranscriptUpdate = (\n encodedUpdate: string,\n maxFrameBytes: number,\n): ReadonlyArray<string> => {\n const budget = Math.max(16, maxFrameBytes - chunkFrameOverheadBytes);\n const chunks: string[] = [];\n let start = 0;\n let bytes = 0;\n for (let index = 0; index < encodedUpdate.length; index += 1) {\n const code = encodedUpdate.charCodeAt(index);\n const pair =\n code >= 0xd800 && code <= 0xdbff && index + 1 < encodedUpdate.length\n ? encodedUpdate.charCodeAt(index + 1)\n : undefined;\n const isPair = pair !== undefined && pair >= 0xdc00 && pair <= 0xdfff;\n const cost = isPair ? 4 : jsonStringUnitBytes(code);\n if (bytes + cost > budget && index > start) {\n chunks.push(encodedUpdate.slice(start, index));\n start = index;\n bytes = 0;\n }\n bytes += cost;\n if (isPair) index += 1;\n }\n if (start < encodedUpdate.length || chunks.length === 0) chunks.push(encodedUpdate.slice(start));\n return chunks;\n};\n","import * as Exit from \"effect/Exit\";\nimport * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport {\n TranscriptOrder,\n type TranscriptLogIncarnation,\n type TranscriptOrderKey,\n type TranscriptRecordView,\n type TranscriptVersion,\n} from \"../transcript/records\";\nimport {\n TranscriptUpdate,\n transcriptCoverageOf,\n type TranscriptCoverage,\n} from \"../transcript/subscription\";\nimport type {\n TranscriptActiveContent,\n TranscriptReadiness,\n TranscriptWindow,\n} from \"../transcript/window\";\nimport type { EDAWebSocketWireAckFrame } from \"./protocol\";\nimport {\n EDATranscriptChunkFrame,\n EDATranscriptUpdateFrame,\n negotiateEDATranscript,\n type EDATranscriptNegotiationResult,\n type EDATranscriptPageFrame,\n type EDATranscriptRetainFrame,\n type EDATranscriptSubscribeFrame,\n} from \"./transcript\";\n\n/**\n * The window a client holds: always exactly one complete cut. Top-level records are in\n * transcript order; dependencies are keyed by id and ordered as the server listed them.\n */\nexport interface EDATranscriptClientWindow {\n readonly incarnation: TranscriptLogIncarnation;\n readonly version: TranscriptVersion;\n readonly throughSeq: SequenceNumber;\n readonly coverage: TranscriptCoverage | undefined;\n readonly hasOlder: boolean;\n readonly hasNewer: boolean;\n readonly readiness: TranscriptReadiness;\n readonly records: ReadonlyArray<TranscriptRecordView>;\n readonly dependencies: ReadonlyArray<TranscriptRecordView>;\n readonly activeContent: ReadonlyArray<TranscriptActiveContent>;\n}\n\n/**\n * Reference client state for one transcript socket, independent of any UI framework.\n *\n * Hosts feed every server message to `applyEDATranscriptServerMessage`, send the ACK it returns,\n * and render `window`. Chunked updates are assembled here and applied only when complete, so the\n * rendered window never shows a partial update.\n */\nexport interface EDATranscriptClientState {\n readonly window: EDATranscriptClientWindow | undefined;\n /** Highest frame id received on the current socket. */\n readonly lastFrameId: number;\n /** The last update applied on the current socket. */\n readonly appliedUpdateSeq: number;\n readonly assembling:\n | { readonly updateSeq: number; readonly count: number; readonly data: ReadonlyArray<string> }\n | undefined;\n}\n\n/** A client that has rendered nothing yet. */\nexport const emptyEDATranscriptClientState: EDATranscriptClientState = {\n window: undefined,\n lastFrameId: 0,\n appliedUpdateSeq: 0,\n assembling: undefined,\n};\n\n/** Seed a client from the window its page was server-rendered with. */\nexport const edaTranscriptClientFromWindow = (\n window: TranscriptWindow,\n): EDATranscriptClientState => ({\n ...emptyEDATranscriptClientState,\n window: {\n incarnation: window.incarnation,\n version: window.version,\n throughSeq: window.throughSeq,\n coverage: transcriptCoverageOf(window),\n hasOlder: window.hasOlder,\n hasNewer: window.hasNewer,\n readiness: window.readiness,\n records: window.records,\n dependencies: window.dependencies,\n activeContent: window.activeContent ?? [],\n },\n});\n\n/**\n * Prepare for a new socket: per-socket counters restart and any partial transfer is discarded.\n * The applied window is kept; the next `subscribe` asks for changes since it.\n */\nexport const edaTranscriptClientReconnected = (\n state: EDATranscriptClientState,\n): EDATranscriptClientState => ({ ...emptyEDATranscriptClientState, window: state.window });\n\n/** What one server message did. */\nexport type EDATranscriptClientOutcome =\n | { readonly _tag: \"Hello\"; readonly negotiation: EDATranscriptNegotiationResult }\n | { readonly _tag: \"Applied\"; readonly updateSeq: number; readonly requestId?: string }\n | { readonly _tag: \"Partial\" }\n | { readonly _tag: \"Ignored\" }\n /** The stream is unusable (a gap, a bad frame, a protocol close): reconnect and resubscribe. */\n | { readonly _tag: \"Resubscribe\"; readonly reason: string };\n\nexport interface EDATranscriptClientStep {\n readonly state: EDATranscriptClientState;\n readonly outcome: EDATranscriptClientOutcome;\n /** Send this ACK when present: a transport receipt plus the applied cut. */\n readonly ack?: EDAWebSocketWireAckFrame;\n}\n\nconst decodeUpdateFrame = Schema.decodeUnknownExit(EDATranscriptUpdateFrame);\nconst decodeChunkFrame = Schema.decodeUnknownExit(EDATranscriptChunkFrame);\nconst decodeUpdate = Schema.decodeUnknownExit(TranscriptUpdate);\n\nconst peek = (value: unknown): { readonly tag?: string; readonly frameId?: number } => {\n if (typeof value !== \"object\" || value === null) return {};\n const tag = \"_tag\" in value && typeof value._tag === \"string\" ? value._tag : undefined;\n const frameId =\n \"frameId\" in value && typeof value.frameId === \"number\" && Number.isInteger(value.frameId)\n ? value.frameId\n : undefined;\n return {\n ...(tag === undefined ? {} : { tag }),\n ...(frameId === undefined ? {} : { frameId }),\n };\n};\n\n/** Apply one server text message. Frames must arrive in frame-id order without gaps. */\nexport const applyEDATranscriptServerMessage = (\n state: EDATranscriptClientState,\n message: string,\n): EDATranscriptClientStep => {\n let json: unknown;\n try {\n json = JSON.parse(message);\n } catch {\n return resubscribe(state, \"malformed server message\");\n }\n const { tag, frameId } = peek(json);\n switch (tag) {\n case \"hello\":\n return { state, outcome: { _tag: \"Hello\", negotiation: negotiateEDATranscript(json) } };\n case \"pong\":\n return { state, outcome: { _tag: \"Ignored\" } };\n case \"lagged\":\n case \"error\":\n return resubscribe(state, `server sent ${tag}`);\n }\n if (frameId === undefined) return { state, outcome: { _tag: \"Ignored\" } };\n if (frameId !== state.lastFrameId + 1) return resubscribe(state, \"frame gap\");\n const received: EDATranscriptClientState = { ...state, lastFrameId: frameId };\n\n if (tag === \"transcript\") {\n const decoded = decodeUpdateFrame(json);\n if (Exit.isFailure(decoded)) return resubscribe(state, \"undecodable update\");\n if (received.assembling !== undefined)\n return resubscribe(state, \"update interrupted a transfer\");\n return applyUpdate(received, decoded.value.update);\n }\n if (tag === \"transcript-chunk\") {\n const decoded = decodeChunkFrame(json);\n if (Exit.isFailure(decoded)) return resubscribe(state, \"undecodable chunk\");\n const chunk = decoded.value;\n const assembling = received.assembling ?? {\n updateSeq: chunk.updateSeq,\n count: chunk.count,\n data: [],\n };\n if (\n assembling.updateSeq !== chunk.updateSeq ||\n assembling.count !== chunk.count ||\n assembling.data.length !== chunk.index\n ) {\n return resubscribe(state, \"interrupted chunked transfer\");\n }\n const data = [...assembling.data, chunk.data];\n if (data.length < chunk.count) {\n const next = { ...received, assembling: { ...assembling, data } };\n return { state: next, outcome: { _tag: \"Partial\" }, ack: ackOf(next) };\n }\n let updateJson: unknown;\n try {\n updateJson = JSON.parse(data.join(\"\"));\n } catch {\n return resubscribe(state, \"malformed chunked update\");\n }\n const update = decodeUpdate(updateJson);\n if (Exit.isFailure(update) || update.value.updateSeq !== chunk.updateSeq) {\n return resubscribe(state, \"undecodable chunked update\");\n }\n return applyUpdate({ ...received, assembling: undefined }, update.value);\n }\n // A frame kind from a newer server: acknowledge its receipt and ignore it.\n return { state: received, outcome: { _tag: \"Ignored\" }, ack: ackOf(received) };\n};\n\nconst resubscribe = (state: EDATranscriptClientState, reason: string): EDATranscriptClientStep => ({\n state: { ...state, assembling: undefined },\n outcome: { _tag: \"Resubscribe\", reason },\n});\n\nconst ackOf = (state: EDATranscriptClientState): EDAWebSocketWireAckFrame => ({\n _tag: \"ack\",\n frameId: state.lastFrameId,\n durableThroughSeq: state.appliedUpdateSeq === 0 ? 0 : (state.window?.throughSeq ?? 0),\n appliedUpdateSeq: state.appliedUpdateSeq,\n});\n\nconst orderKeyOf = (record: TranscriptRecordView): TranscriptOrderKey | undefined =>\n \"position\" in record && record.position !== undefined\n ? { ...record.position, recordId: record.id }\n : undefined;\n\nconst covered = (\n coverage: TranscriptCoverage | undefined,\n record: TranscriptRecordView,\n): boolean => {\n const key = orderKeyOf(record);\n return (\n coverage !== undefined &&\n key !== undefined &&\n TranscriptOrder(coverage.from, key) <= 0 &&\n TranscriptOrder(key, coverage.to) <= 0\n );\n};\n\nconst applyUpdate = (\n state: EDATranscriptClientState,\n update: TranscriptUpdate,\n): EDATranscriptClientStep => {\n if (update.updateSeq !== state.appliedUpdateSeq + 1) return resubscribe(state, \"update gap\");\n const previous = state.window;\n if (\n update.mode === \"patch\" &&\n (previous === undefined ||\n previous.incarnation !== update.incarnation ||\n previous.version !== update.version)\n ) {\n return resubscribe(state, \"patch without its base\");\n }\n const base = update.mode === \"patch\" ? previous : undefined;\n\n const topLevel = new Map((base?.records ?? []).map((record) => [record.id, record]));\n for (const record of update.records) topLevel.set(record.id, record);\n const records = [...topLevel.values()]\n .filter((record) => covered(update.coverage, record))\n .sort((left, right) => {\n const leftKey = orderKeyOf(left);\n const rightKey = orderKeyOf(right);\n return leftKey === undefined || rightKey === undefined\n ? 0\n : TranscriptOrder(leftKey, rightKey);\n });\n\n const dependencyMap = new Map((base?.dependencies ?? []).map((record) => [record.id, record]));\n for (const record of update.dependencies) dependencyMap.set(record.id, record);\n const dependencies = update.dependencyIds.flatMap((id) => {\n const record = dependencyMap.get(id);\n return record === undefined ? [] : [record];\n });\n if (dependencies.length !== update.dependencyIds.length) {\n return resubscribe(state, \"patch referenced a dependency the client does not hold\");\n }\n\n const window: EDATranscriptClientWindow = {\n incarnation: update.incarnation,\n version: update.version,\n throughSeq: update.throughSeq,\n coverage: update.coverage,\n hasOlder: update.hasOlder,\n hasNewer: update.hasNewer,\n readiness: update.readiness,\n records,\n dependencies,\n activeContent:\n update.readiness._tag !== \"Ready\" ? [] : (update.activeContent ?? base?.activeContent ?? []),\n };\n const next: EDATranscriptClientState = {\n ...state,\n window,\n appliedUpdateSeq: update.updateSeq,\n assembling: undefined,\n };\n return {\n state: next,\n outcome: {\n _tag: \"Applied\",\n updateSeq: update.updateSeq,\n ...(update.requestId === undefined ? {} : { requestId: update.requestId }),\n },\n ack: ackOf(next),\n };\n};\n\n/**\n * The request a client sends first on every socket: changes since the window it holds over the\n * span it holds, or the latest `count` records when it holds none.\n */\nexport const edaTranscriptSubscribeRequest = (\n state: EDATranscriptClientState,\n options?: { readonly count?: number; readonly requestId?: string },\n): EDATranscriptSubscribeFrame => {\n const window = state.window;\n const extra = {\n ...(options?.count === undefined ? {} : { count: options.count }),\n ...(options?.requestId === undefined ? {} : { requestId: options.requestId }),\n };\n return window?.coverage === undefined\n ? { _tag: \"subscribe\", ...extra }\n : {\n _tag: \"subscribe\",\n range: window.coverage,\n tail: !window.hasNewer,\n since: window.throughSeq,\n ...extra,\n };\n};\n\n/** Page from the held coverage's edge, or `undefined` when there is nothing to page from. */\nexport const edaTranscriptPageRequest = (\n state: EDATranscriptClientState,\n direction: \"before\" | \"after\",\n count: number,\n requestId?: string,\n): EDATranscriptPageFrame | undefined => {\n const coverage = state.window?.coverage;\n if (coverage === undefined) return undefined;\n return {\n _tag: \"page\",\n direction,\n cursor: direction === \"before\" ? coverage.from : coverage.to,\n count,\n ...(requestId === undefined ? {} : { requestId }),\n };\n};\n\n/**\n * Keep only the top-level records from `fromIndex` to `toIndex` (inclusive) of the held window;\n * the server confirms with an update whose coverage is the narrowed span.\n */\nexport const edaTranscriptRetainRequest = (\n state: EDATranscriptClientState,\n fromIndex: number,\n toIndex: number,\n requestId?: string,\n): EDATranscriptRetainFrame | undefined => {\n const window = state.window;\n const from = window?.records[fromIndex];\n const to = window?.records[toIndex];\n const fromKey = from === undefined ? undefined : orderKeyOf(from);\n const toKey = to === undefined ? undefined : orderKeyOf(to);\n if (window === undefined || fromKey === undefined || toKey === undefined) return undefined;\n const scope = { incarnation: window.incarnation, version: window.version };\n return {\n _tag: \"retain\",\n from: { ...scope, ...fromKey, anchorSeq: SequenceNumber.make(fromKey.anchorSeq) },\n to: { ...scope, ...toKey, anchorSeq: SequenceNumber.make(toKey.anchorSeq) },\n ...(requestId === undefined ? {} : { requestId }),\n };\n};\n","import * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport { TranscriptSubscriptionBase, type TranscriptUpdate } from \"../transcript/subscription\";\nimport type { EDAWebSocketFlowControl } from \"./messages\";\nimport type { EDAWebSocketWireAckFrame } from \"./protocol\";\nimport {\n EDATranscriptRequestFrame,\n edaTranscriptChunkFrameText,\n edaTranscriptUpdateFrameText,\n splitEDATranscriptUpdate,\n utf8ByteLength,\n} from \"./transcript\";\n\nconst PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));\nconst NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\n\n/** A chunked update whose frames are not all sent yet; its chunk data is volatile. */\nexport const EDATranscriptTransfer = Schema.Struct({\n updateSeq: PositiveInt,\n throughSeq: SequenceNumber,\n count: PositiveInt,\n nextIndex: NonNegativeInt,\n});\nexport type EDATranscriptTransfer = typeof EDATranscriptTransfer.Type;\n\n/**\n * Everything a transcript socket needs to resume after hibernation, persisted in its attachment\n * before every send and after every applied ACK.\n *\n * Transport receipts (`inFlight`, `lastAckedFrameId`) bound frames in flight exactly as on an\n * event socket. The applied cut (`appliedUpdateSeq`, `appliedThroughSeq`) is the last update the\n * client applied completely. `subscription` is the base the next update is planned against, and\n * `requests` are client requests not yet answered. A persisted `transfer` means chunk data was\n * staged in memory; a socket restored with one cannot finish it and is closed.\n */\nexport const EDATranscriptDeliveryCheckpoint = Schema.Struct({\n lastAckedFrameId: NonNegativeInt,\n nextFrameId: PositiveInt,\n inFlight: Schema.Array(Schema.Struct({ frameId: PositiveInt, sentAtMs: Schema.Number })),\n nextUpdateSeq: PositiveInt,\n completedUpdateSeq: NonNegativeInt,\n completedThroughSeq: SequenceNumber,\n appliedUpdateSeq: NonNegativeInt,\n appliedThroughSeq: SequenceNumber,\n transfer: Schema.optionalKey(EDATranscriptTransfer),\n subscription: Schema.optionalKey(TranscriptSubscriptionBase),\n requests: Schema.Array(EDATranscriptRequestFrame),\n});\nexport type EDATranscriptDeliveryCheckpoint = typeof EDATranscriptDeliveryCheckpoint.Type;\n\n/** Bounds on one transcript socket beyond the shared flow-control policy. */\nexport interface EDATranscriptDeliveryLimits {\n /** Largest encoded update staged for one transfer; a larger one closes the socket. */\n readonly maxStagedBytes: number;\n /** Unanswered client requests held at once; more is a protocol violation. */\n readonly maxPendingRequests: number;\n}\n\nexport const defaultEDATranscriptDeliveryLimits: EDATranscriptDeliveryLimits = {\n maxStagedBytes: 8 * 1_048_576,\n maxPendingRequests: 4,\n};\n\n/** In-memory state of one transcript socket. */\nexport interface EDATranscriptDeliveryState extends EDATranscriptDeliveryCheckpoint {\n readonly policy: EDAWebSocketFlowControl;\n /** Chunk data of `transfer` not yet sent, in order. Never persisted. */\n readonly staged: ReadonlyArray<string>;\n}\n\n/** Delivery state for a newly accepted transcript socket. */\nexport const makeTranscriptDeliveryState = (\n policy: EDAWebSocketFlowControl,\n): EDATranscriptDeliveryState => ({\n policy,\n lastAckedFrameId: 0,\n nextFrameId: 1,\n inFlight: [],\n nextUpdateSeq: 1,\n completedUpdateSeq: 0,\n completedThroughSeq: SequenceNumber.make(0),\n appliedUpdateSeq: 0,\n appliedThroughSeq: SequenceNumber.make(0),\n requests: [],\n staged: [],\n});\n\n/**\n * Restore a hibernated transcript socket. A socket that was mid-transfer lost its staged chunks\n * with the isolate and cannot resume: the caller closes it and the client resubscribes.\n */\nexport const restoreTranscriptDeliveryState = (\n policy: EDAWebSocketFlowControl,\n checkpoint: EDATranscriptDeliveryCheckpoint,\n):\n | { readonly _tag: \"Restored\"; readonly state: EDATranscriptDeliveryState }\n | { readonly _tag: \"TransferLost\" } =>\n checkpoint.transfer === undefined\n ? { _tag: \"Restored\", state: { ...checkpoint, policy, staged: [] } }\n : { _tag: \"TransferLost\" };\n\n/** The attachment-safe part of the state. */\nexport const checkpointTranscriptDelivery = (\n state: EDATranscriptDeliveryState,\n): EDATranscriptDeliveryCheckpoint => ({\n lastAckedFrameId: state.lastAckedFrameId,\n nextFrameId: state.nextFrameId,\n inFlight: state.inFlight,\n nextUpdateSeq: state.nextUpdateSeq,\n completedUpdateSeq: state.completedUpdateSeq,\n completedThroughSeq: state.completedThroughSeq,\n appliedUpdateSeq: state.appliedUpdateSeq,\n appliedThroughSeq: state.appliedThroughSeq,\n ...(state.transfer === undefined ? {} : { transfer: state.transfer }),\n ...(state.subscription === undefined ? {} : { subscription: state.subscription }),\n requests: state.requests,\n});\n\n/** Frames that may be sent before the client's next receipt. */\nexport const transcriptDeliveryCapacity = (state: EDATranscriptDeliveryState): number =>\n state.policy.maxInFlightFrames - state.inFlight.length;\n\n/** Lazily enforced ACK deadline: no resident timer, checked on each transition. */\nexport const transcriptAckTimedOut = (state: EDATranscriptDeliveryState, nowMs: number): boolean =>\n state.inFlight.some((frame) => frame.sentAtMs + state.policy.ackTimeoutMs <= nowMs);\n\n/** Result of a transition that may emit frames. */\nexport interface EDATranscriptSendResult {\n readonly state: EDATranscriptDeliveryState;\n /** Encoded frames to send in order, after persisting `state`. */\n readonly frames: ReadonlyArray<string>;\n}\n\n/**\n * Start sending one planned update, captured from its own snapshot.\n *\n * `subscription` becomes the base for the next update immediately: nothing else is sent until\n * this update's last frame is, so the client can only apply later updates on top of it. An\n * update within the frame limit is one frame; a larger one is chunked and as many chunks as\n * flow control allows are sent now, the rest staged.\n */\nexport const startTranscriptUpdate = (\n state: EDATranscriptDeliveryState,\n input: {\n readonly update: TranscriptUpdate;\n readonly encodedUpdate: string;\n readonly subscription: TranscriptSubscriptionBase;\n },\n limits: EDATranscriptDeliveryLimits,\n nowMs: number,\n):\n | ({ readonly _tag: \"Sending\" } & EDATranscriptSendResult)\n | { readonly _tag: \"TooLarge\"; readonly bytes: number } => {\n if (state.transfer !== undefined) {\n throw new Error(\"A transcript update cannot start while another is being transferred\");\n }\n if (input.update.updateSeq !== state.nextUpdateSeq) {\n throw new Error(\"A transcript update must carry the socket's next update seq\");\n }\n const updateSeq = input.update.updateSeq;\n const advanced: EDATranscriptDeliveryState = {\n ...state,\n nextUpdateSeq: updateSeq + 1,\n subscription: input.subscription,\n };\n const single = edaTranscriptUpdateFrameText(state.nextFrameId, input.encodedUpdate);\n if (utf8ByteLength(single) <= state.policy.maxFrameBytes) {\n return {\n _tag: \"Sending\",\n ...sendFrames(\n {\n ...advanced,\n completedUpdateSeq: updateSeq,\n completedThroughSeq: input.update.throughSeq,\n },\n [single],\n nowMs,\n ),\n };\n }\n const bytes = utf8ByteLength(input.encodedUpdate);\n if (bytes > limits.maxStagedBytes) return { _tag: \"TooLarge\", bytes };\n const chunks = splitEDATranscriptUpdate(input.encodedUpdate, state.policy.maxFrameBytes);\n return {\n _tag: \"Sending\",\n ...pumpTranscriptTransfer(\n {\n ...advanced,\n transfer: {\n updateSeq,\n throughSeq: input.update.throughSeq,\n count: chunks.length,\n nextIndex: 0,\n },\n staged: chunks,\n },\n nowMs,\n ),\n };\n};\n\n/** Send staged chunks of the transfer in progress while flow control allows. */\nexport const pumpTranscriptTransfer = (\n state: EDATranscriptDeliveryState,\n nowMs: number,\n): EDATranscriptSendResult => {\n let next = state;\n const frames: string[] = [];\n while (next.transfer !== undefined && transcriptDeliveryCapacity(next) > 0) {\n const transfer: EDATranscriptTransfer = next.transfer;\n const [data, ...rest] = next.staged;\n if (data === undefined) break;\n const text = edaTranscriptChunkFrameText({\n frameId: next.nextFrameId,\n updateSeq: transfer.updateSeq,\n index: transfer.nextIndex,\n count: transfer.count,\n data,\n });\n const nextIndex = transfer.nextIndex + 1;\n const done = nextIndex === transfer.count;\n const { transfer: _sent, ...withoutTransfer } = next;\n const sent = sendFrames(\n done\n ? {\n ...withoutTransfer,\n staged: [],\n completedUpdateSeq: transfer.updateSeq,\n completedThroughSeq: transfer.throughSeq,\n }\n : { ...next, staged: rest, transfer: { ...transfer, nextIndex } },\n [text],\n nowMs,\n );\n next = sent.state;\n frames.push(...sent.frames);\n }\n return { state: next, frames };\n};\n\nconst sendFrames = (\n state: EDATranscriptDeliveryState,\n texts: ReadonlyArray<string>,\n nowMs: number,\n): EDATranscriptSendResult => {\n // Frame texts embed `state.nextFrameId` onwards in order.\n const inFlight = texts.map((_, index) => ({\n frameId: state.nextFrameId + index,\n sentAtMs: nowMs,\n }));\n return {\n state: {\n ...state,\n inFlight: [...state.inFlight, ...inFlight],\n nextFrameId: state.nextFrameId + texts.length,\n },\n frames: texts,\n };\n};\n\n/** Outcome of one client ACK on a transcript socket. */\nexport type EDATranscriptAckResult =\n | { readonly _tag: \"Applied\"; readonly state: EDATranscriptDeliveryState }\n | { readonly _tag: \"Ignored\" }\n | { readonly _tag: \"ProtocolError\"; readonly message: string };\n\n/**\n * Apply one ACK. The receipt frees flow-control capacity cumulatively; the applied cut may only\n * name an update whose frames were all sent, and never moves backwards.\n */\nexport const onTranscriptAck = (\n state: EDATranscriptDeliveryState,\n ack: EDAWebSocketWireAckFrame,\n): EDATranscriptAckResult => {\n const appliedUpdateSeq = ack.appliedUpdateSeq ?? state.appliedUpdateSeq;\n const advancesApplied = appliedUpdateSeq > state.appliedUpdateSeq;\n if (ack.frameId <= state.lastAckedFrameId) {\n return advancesApplied\n ? { _tag: \"ProtocolError\", message: \"Duplicate ACK attempted to advance the applied cut\" }\n : { _tag: \"Ignored\" };\n }\n if (ack.frameId >= state.nextFrameId) {\n return { _tag: \"ProtocolError\", message: \"ACK referenced an unsent frame\" };\n }\n if (appliedUpdateSeq < state.appliedUpdateSeq) {\n return { _tag: \"ProtocolError\", message: \"ACK applied cut moved backwards\" };\n }\n if (appliedUpdateSeq > state.completedUpdateSeq) {\n return { _tag: \"ProtocolError\", message: \"ACK applied an incomplete update\" };\n }\n // `throughSeq` may fall between updates (a new incarnation, a building window), so it is not\n // monotonic; it must match the update it names when that update is the last one completed.\n if (\n advancesApplied &&\n appliedUpdateSeq === state.completedUpdateSeq &&\n ack.durableThroughSeq !== state.completedThroughSeq\n ) {\n return { _tag: \"ProtocolError\", message: \"ACK applied cut names another update's seq\" };\n }\n return {\n _tag: \"Applied\",\n state: {\n ...state,\n lastAckedFrameId: ack.frameId,\n inFlight: state.inFlight.filter((frame) => frame.frameId > ack.frameId),\n appliedUpdateSeq,\n appliedThroughSeq: advancesApplied\n ? SequenceNumber.make(ack.durableThroughSeq)\n : state.appliedThroughSeq,\n },\n };\n};\n\n/** Queue one client request, or report that the client exceeded its request bound. */\nexport const enqueueTranscriptRequest = (\n state: EDATranscriptDeliveryState,\n request: EDATranscriptRequestFrame,\n limits: EDATranscriptDeliveryLimits,\n): EDATranscriptDeliveryState | undefined =>\n state.requests.length >= limits.maxPendingRequests\n ? undefined\n : { ...state, requests: [...state.requests, request] };\n"],"mappings":";;;;;;;AAkBA,MAAMA,gBAAc,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC;AACrE,MAAMC,mBAAiB,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC;;;;;AAUxE,MAAa,gCAAgC;;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sBAAsB,MAAM,qBAEhC,OAAO;EAAE,MAAM;EAAiB,SAAS;CAA6C;CAExF,OAAO;EACL,MAAM;EACN,OAAO;GACL,GAAG;GACH,kBAAkB,IAAI;GACtB,UAAU,MAAM,SAAS,QAAQ,UAAU,MAAM,UAAU,IAAI,OAAO;GACtE;GACA,mBAAmB,kBACf,eAAe,KAAK,IAAI,iBAAiB,IACzC,MAAM;EACZ;CACF;AACF;;AAGA,MAAa,4BACX,OACA,SACA,WAEA,MAAM,SAAS,UAAU,OAAO,qBAC5B,KAAA,IACA;CAAE,GAAG;CAAO,UAAU,CAAC,GAAG,MAAM,UAAU,OAAO;AAAE"}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { h as SequenceNumber } from "./core-BcimKMIv.js";
|
|
2
|
+
import { A as TranscriptDefinition, At as TranscriptToolRecord, C as TranscriptVersionMeta, D as TranscriptWindowSelector, E as TranscriptWindowLimits, Ft as TranscriptVersion, H as AssistantRecordId, Nt as TranscriptUserRecord, S as TranscriptReadiness, T as TranscriptWindow, gt as TranscriptOrderKey, jt as TranscriptTopLevelRecord, mt as TranscriptLogIncarnation, t as CommittedDurableEvent, v as TranscriptCursorMismatch, vt as TranscriptRecord, xt as TranscriptRecordId } from "./session-store-CWYZ29CV.js";
|
|
3
|
+
import * as Schema from "effect/Schema";
|
|
4
|
+
import * as Result from "effect/Result";
|
|
5
|
+
//#region src/transcript/plan.d.ts
|
|
6
|
+
/**
|
|
7
|
+
* Secondary keys that resolve to a record through an indexed join, never an in-memory map.
|
|
8
|
+
*
|
|
9
|
+
* - `messageId`: every message id a user submission has carried, including replacement ids.
|
|
10
|
+
* - `idempotencyKey`: a submitting command's caller-owned retry key.
|
|
11
|
+
* - `runId`: every run of a run group, so continuations resolve to the root's group.
|
|
12
|
+
* - `runCommand`: commands owned by a run group; a run that reuses them continues the group.
|
|
13
|
+
* - `toolPart`: `<inferenceId>/<providerPartId>`, linking an assistant tool-call part to its tool.
|
|
14
|
+
*/
|
|
15
|
+
declare const TranscriptAliasNamespace: Schema.Literals<readonly ["messageId", "idempotencyKey", "runId", "runCommand", "toolPart"]>;
|
|
16
|
+
type TranscriptAliasNamespace = typeof TranscriptAliasNamespace.Type;
|
|
17
|
+
/** One alias row: `(namespace, key)` resolves to `recordId` within one version. */
|
|
18
|
+
interface TranscriptAlias {
|
|
19
|
+
readonly namespace: TranscriptAliasNamespace;
|
|
20
|
+
readonly key: string;
|
|
21
|
+
readonly recordId: TranscriptRecordId;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Synchronous indexed reads of one transcript version, as committed before the batch.
|
|
25
|
+
*
|
|
26
|
+
* Adapters back this with indexed storage reads so the interpreter can run inside a synchronous
|
|
27
|
+
* transaction (Cloudflare `storage.transactionSync`). Reads see no uncommitted plan; the
|
|
28
|
+
* interpreter overlays its own in-batch changes.
|
|
29
|
+
*/
|
|
30
|
+
interface TranscriptLookup {
|
|
31
|
+
/** Last seq already projected into this version. Events at or below it are skipped. */
|
|
32
|
+
readonly cursor: SequenceNumber;
|
|
33
|
+
readonly record: (id: TranscriptRecordId) => TranscriptRecord | undefined;
|
|
34
|
+
readonly alias: (namespace: TranscriptAliasNamespace, key: string) => TranscriptRecordId | undefined;
|
|
35
|
+
/** Next free ordinal among records positioned at `anchorSeq`; 0 when none are. */
|
|
36
|
+
readonly nextOrdinal: (anchorSeq: SequenceNumber) => number;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Deterministic changes for one committed batch: the final state of every record the batch
|
|
40
|
+
* touched, in first-touch order, the aliases it introduced, and the new cursor.
|
|
41
|
+
*
|
|
42
|
+
* There are no deletions. Aliases are inserts only: an alias never moves to another record.
|
|
43
|
+
* Applying the plan and advancing the cursor must commit atomically with each other.
|
|
44
|
+
*/
|
|
45
|
+
interface TranscriptChangePlan {
|
|
46
|
+
readonly records: ReadonlyArray<TranscriptRecord>;
|
|
47
|
+
readonly aliases: ReadonlyArray<TranscriptAlias>;
|
|
48
|
+
readonly throughSeq: SequenceNumber;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The interpretation boundary: a pure, synchronous function from a lookup, committed events and
|
|
52
|
+
* a definition to a change plan.
|
|
53
|
+
*
|
|
54
|
+
* It throws `TranscriptProjectionError` when the stored projection is inconsistent with the log.
|
|
55
|
+
* The adapter treats any throw as a recoverable projection failure of that version only.
|
|
56
|
+
*/
|
|
57
|
+
type PlanTranscriptBatch = (lookup: TranscriptLookup, committed: ReadonlyArray<CommittedDurableEvent>, definition: TranscriptDefinition) => TranscriptChangePlan;
|
|
58
|
+
declare const TranscriptProjectionError_base: Schema.Class<TranscriptProjectionError, Schema.TaggedStruct<"TranscriptProjectionError", {
|
|
59
|
+
readonly message: Schema.String;
|
|
60
|
+
}>, import("effect/Cause").YieldableError>;
|
|
61
|
+
/** The stored projection cannot be advanced from the given lookup and batch. */
|
|
62
|
+
declare class TranscriptProjectionError extends TranscriptProjectionError_base {}
|
|
63
|
+
//#endregion
|
|
64
|
+
//#region src/transcript/window-read.d.ts
|
|
65
|
+
/**
|
|
66
|
+
* Synchronous indexed reads of the served version at one cut, as a store provides them.
|
|
67
|
+
*
|
|
68
|
+
* Window assembly (paging, dependency collection, byte budgeting and body references) is shared
|
|
69
|
+
* by every store through `readTranscriptWindowFrom`; a store only supplies these reads.
|
|
70
|
+
*/
|
|
71
|
+
interface TranscriptWindowSource {
|
|
72
|
+
readonly incarnation: TranscriptLogIncarnation;
|
|
73
|
+
/** Maintenance state of the served (active) version; its cursor is the window's `throughSeq`. */
|
|
74
|
+
readonly meta: TranscriptVersionMeta;
|
|
75
|
+
/** False when this release no longer carries the served version (a missed session). */
|
|
76
|
+
readonly carried: boolean;
|
|
77
|
+
/** Top-level records before `key` (or before the end), newest first. */
|
|
78
|
+
readonly topLevelBefore: (key: TranscriptOrderKey | undefined, limit: number, inclusive: boolean) => ReadonlyArray<TranscriptTopLevelRecord>;
|
|
79
|
+
/** Top-level records after `key` (or after the start), oldest first. */
|
|
80
|
+
readonly topLevelAfter: (key: TranscriptOrderKey | undefined, limit: number, inclusive: boolean) => ReadonlyArray<TranscriptTopLevelRecord>;
|
|
81
|
+
readonly record: (id: TranscriptRecordId) => TranscriptRecord | undefined;
|
|
82
|
+
readonly alias: (namespace: TranscriptAliasNamespace, key: string) => TranscriptRecordId | undefined;
|
|
83
|
+
/** Tool records of one assistant (the typed dependency lookup). */
|
|
84
|
+
readonly toolsOf: (assistantId: AssistantRecordId) => ReadonlyArray<TranscriptToolRecord>;
|
|
85
|
+
/** Every user record still waiting for the agent (the pending-membership index). */
|
|
86
|
+
readonly pendingUsers: () => ReadonlyArray<TranscriptUserRecord>;
|
|
87
|
+
}
|
|
88
|
+
/** Readiness of a served version: why its cut may be behind the log. */
|
|
89
|
+
declare const transcriptReadiness: (meta: TranscriptVersionMeta, carried: boolean) => TranscriptReadiness;
|
|
90
|
+
/** The empty window served while no version is servable yet. */
|
|
91
|
+
declare const buildingTranscriptWindow: (incarnation: TranscriptLogIncarnation, version: TranscriptVersion) => TranscriptWindow;
|
|
92
|
+
/**
|
|
93
|
+
* Assemble one window from a source at a single cut.
|
|
94
|
+
*
|
|
95
|
+
* The response never contains anything newer than the served version's cursor: a frozen (failed
|
|
96
|
+
* or no longer carried) version's rows, pending users and session context all stop at its last
|
|
97
|
+
* good cut, which is the degraded-read rule. Bodies above the inline limit become references;
|
|
98
|
+
* if the response still exceeds the byte budget, records are dropped from the far end of the
|
|
99
|
+
* selection, keeping at least one so paging always progresses.
|
|
100
|
+
*/
|
|
101
|
+
declare const readTranscriptWindowFrom: (source: TranscriptWindowSource, selector: TranscriptWindowSelector, limits: TranscriptWindowLimits) => Result.Result<TranscriptWindow, TranscriptCursorMismatch>;
|
|
102
|
+
//#endregion
|
|
103
|
+
export { PlanTranscriptBatch as a, TranscriptChangePlan as c, transcriptReadiness as i, TranscriptLookup as l, buildingTranscriptWindow as n, TranscriptAlias as o, readTranscriptWindowFrom as r, TranscriptAliasNamespace as s, TranscriptWindowSource as t, TranscriptProjectionError as u };
|
|
104
|
+
//# sourceMappingURL=window-read-DBf1Iktt.d.ts.map
|