@xynolog/core 0.8.0 → 0.8.2

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.
@@ -1,10 +1,11 @@
1
- import { TRACE_FIELD, USER_FIELD, baseUrl, KeptForFirstReader, EventBus, REPLY_NAMES, isResourceScopedChannel, BusRequestError, relayFrames, asDeclared, RESOURCE_SCOPED_CHANNELS, BUS_OPERATIONS } from './chunk-VWT5CTL7.js';
1
+ import { TransportError, TRACE_FIELD, USER_FIELD, baseUrl, KeptForFirstReader, EventBus, activeTrace, REPLY_NAMES, isResourceScopedChannel, BusRequestError, arrived, relayFrames, asDeclared, RESOURCE_SCOPED_CHANNELS, BUS_OPERATIONS } from './chunk-NZ7SRPXU.js';
2
2
  import { BehaviorSubject } from 'rxjs';
3
- import { map, filter } from 'rxjs/operators';
3
+ import { map } from 'rxjs/operators';
4
4
 
5
5
  function refuseUnscriptedOperation(operation) {
6
- throw new Error(
7
- `No response scripted for bus operation "${operation}". Script one with transport.queueReply('${operation}', <response>) or pass a makeResponse that handles it.`
6
+ throw new TransportError(
7
+ `No response scripted for bus operation "${operation}". Script one with transport.queueReply('${operation}', <response>) or pass a makeResponse that handles it.`,
8
+ "error"
8
9
  );
9
10
  }
10
11
  function isOperation(channel) {
@@ -27,7 +28,7 @@ var FaultyTransport = class {
27
28
  errors$ = this.failures.said$;
28
29
  /** Every request-channel emit, in order — the L2 accounting surface. */
29
30
  requestLog = [];
30
- /** Every frame emitted, a request's echo and its reply included: what a reader is given is gated in `frames`. */
31
+ /** Every frame its stream carries, a request's echo and its reply included, as it arrived (`arrive`). */
31
32
  bus = new EventBus();
32
33
  channels;
33
34
  /** The resources whose scopes are held, each with how many hold it. */
@@ -73,9 +74,10 @@ var FaultyTransport = class {
73
74
  async emit(channel, payload, envelope) {
74
75
  if (this.disposed) return void 0;
75
76
  const name = channel;
77
+ const trace = activeTrace();
78
+ const sent = trace === void 0 ? { ...envelope, payload } : { ...envelope, payload, trace };
76
79
  if (!isOperation(name)) {
77
- const target = envelope?.scope === void 0 ? this.bus : this.bus.scope(envelope.scope);
78
- target.emit(channel, payload, { correlationId: envelope?.correlationId });
80
+ this.arrive(channel, sent);
79
81
  return 1;
80
82
  }
81
83
  const record = payload;
@@ -95,7 +97,7 @@ var FaultyTransport = class {
95
97
  `FaultyTransport: emit rejected by schedule (reject-emit) on ${name}`
96
98
  );
97
99
  }
98
- this.bus.emit(channel, payload, envelope);
100
+ this.arrive(channel, sent);
99
101
  const queue = this.replyQueues.get(name);
100
102
  const response = queue && queue.length > 0 ? queue.shift() : this.makeResponse(name, record);
101
103
  const named = {};
@@ -111,8 +113,9 @@ var FaultyTransport = class {
111
113
  if (this.disposed) return;
112
114
  const replyPayload = response === void 0 ? { ...named } : { ...named, response };
113
115
  const resultChannel = BUS_OPERATIONS[name].result;
114
- this.bus.emit(resultChannel, replyPayload, {
115
- correlationId: envelope?.correlationId
116
+ this.arrive(resultChannel, {
117
+ correlationId: envelope?.correlationId,
118
+ payload: replyPayload
116
119
  });
117
120
  };
118
121
  switch (action.kind) {
@@ -162,11 +165,30 @@ var FaultyTransport = class {
162
165
  { channel }
163
166
  );
164
167
  }
165
- return this.bus.channelStream(channel).pipe(
166
- filter(
167
- (frame) => frame.scope === void 0 ? this.channels.has(channel) : isResourceScopedChannel(channel) && this.scopeRefCounts.has(frame.scope)
168
- )
169
- );
168
+ return this.bus.channelStream(channel);
169
+ }
170
+ /**
171
+ * Whether its stream carries a frame on `channel`, on `scope`: one of no
172
+ * scope on a channel this transport was given, and one of a resource's
173
+ * scope on a resource-scoped channel while that scope is held.
174
+ */
175
+ carries(channel, scope) {
176
+ return scope === void 0 ? this.channels.has(channel) : isResourceScopedChannel(channel) && this.scopeRefCounts.has(scope);
177
+ }
178
+ /**
179
+ * A frame `frame`, sent under its `trace`, arriving on the stream: one the
180
+ * stream does not carry reaches nobody, and one it carries has its arrival
181
+ * marked (`arrived`) and is delivered in the trace that gives.
182
+ */
183
+ arrive(channel, frame) {
184
+ if (!this.carries(channel, frame.scope)) return;
185
+ const { trace: sentUnder, ...sent } = frame;
186
+ arrived(channel, frame.scope, sentUnder, (deliveredIn) => {
187
+ this.bus.emitFrame(
188
+ channel,
189
+ deliveredIn === void 0 ? sent : { ...sent, trace: deliveredIn }
190
+ );
191
+ });
170
192
  }
171
193
  /**
172
194
  * Whether the channels this transport was given name `channel`, as a wire
@@ -224,14 +246,13 @@ var FaultyTransport = class {
224
246
  this,
225
247
  {
226
248
  // A payload that is not its channel's is published as its refusal, as a wire transport's bridge does.
227
- emit: (channel, payload, envelope) => bus.emit(
228
- channel,
229
- asDeclared(channel, payload, envelope.correlationId),
230
- envelope
231
- )
249
+ emitFrame: (channel, frame) => bus.emitFrame(channel, {
250
+ ...frame,
251
+ payload: asDeclared(channel, frame.payload, frame)
252
+ })
232
253
  },
233
254
  [...this.channels, ...RESOURCE_SCOPED_CHANNELS],
234
- // `EventBus.emit` is synchronous, so this never fires.
255
+ // `EventBus.emitFrame` is synchronous, so this never fires.
235
256
  (channel, error) => {
236
257
  throw new Error(
237
258
  `FaultyTransport: the bridge of ${channel} failed`,
@@ -255,5 +276,5 @@ var FaultyTransport = class {
255
276
  };
256
277
 
257
278
  export { FaultyTransport, refuseUnscriptedOperation, retryKeyOf };
258
- //# sourceMappingURL=chunk-JVQYMUSA.js.map
259
- //# sourceMappingURL=chunk-JVQYMUSA.js.map
279
+ //# sourceMappingURL=chunk-PT6P47KV.js.map
280
+ //# sourceMappingURL=chunk-PT6P47KV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/faulty-transport.ts"],"names":[],"mappings":";;;;AA+FO,SAAS,0BAA0B,SAAA,EAA0B;AAClE,EAAA,MAAM,IAAI,cAAA;AAAA,IACR,CAAA,wCAAA,EAA2C,SAAS,CAAA,yCAAA,EACT,SAAS,CAAA,sDAAA,CAAA;AAAA,IAEpD;AAAA,GACF;AACF;AAEA,SAAS,YAAY,OAAA,EAA6C;AAChE,E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AAS,UAAA,CAAW,OAAA,EAAS,KAAA,CAAM,SAAS,KAAK;AAAA,SAClD;AAAA,OACL;AAAA,MACA,CAAC,GAAG,IAAA,CAAK,QAAA,EAAU,GAAG,wBAAwB,CAAA;AAAA;AAAA,MAE9C,CAAC,SAAS,KAAA,KAAU;AAClB,QAAA,MAAM,IAAI,KAAA;AAAA,UACR,kCAAkC,OAAiB,CAAA,OAAA,CAAA;AAAA,UACnD,EAAE,OAAO,KAAA;AAAM,SACjB;AAAA,MACF;AAAA,KACF;AAAA,EACF;AAAA;AAAA,EAIA,OAAA,GAAgB;AACd,IAAA,IAAI,KAAK,QAAA,EAAU;AACnB,IAAA,IAAA,CAAK,QAAA,GAAW,IAAA;AAChB,IAAA,IAAA,CAAK,eAAe,KAAA,EAAM;AAC1B,IAAA,KAAA,MAAW,CAAA,IAAK,IAAA,CAAK,MAAA,EAAQ,YAAA,CAAa,CAAC,CAAA;AAC3C,IAAA,IAAA,CAAK,OAAO,KAAA,EAAM;AAClB,IAAA,IAAA,CAAK,MAAA,CAAO,KAAK,QAAQ,CAAA;AACzB,IAAA,IAAA,CAAK,OAAO,QAAA,EAAS;AACrB,IAAA,IAAA,CAAK,SAAS,GAAA,EAAI;AAElB,IAAA,IAAA,CAAK,IAAI,OAAA,EAAQ;AAAA,EACnB;AACF","file":"chunk-PT6P47KV.js","sourcesContent":["/**\n * FaultyTransport — a seeded, scriptable `ITransport` simulator for the\n * liveness axioms. fast-check draws a fault\n * schedule; the transport applies one `FaultAction` per request-channel emit\n * and synthesizes replies from the `BUS_OPERATIONS` registry, so real\n * compositions (`Bus.request`, SWR caches, live queries) run unmodified against\n * generated wire behavior no hand-written test names.\n *\n * Home is core (not sdk/test-utils) for the same reason as\n * `assertStateUnitAxioms`: it needs only core types, and every layer —\n * including `http-transport`, below sdk — can consume it via\n * `@xynolog/core/testing` without a dependency cycle.\n *\n * Each frame emitted is relayed back in the trace it was sent under, the\n * active trace at the emit (`activeTrace`), as a gateway relays a frame in\n * the trace its sender put on it; a reply carries none. Each frame its\n * stream carries arrives as a frame a wire transport reads arrives: its\n * arrival is marked in the trace it was sent under (`arrived`, the\n * `bus.recv:{channel}` span `@xynolog/observability` registers), and it is\n * delivered in the trace that gives. So a job a claim is answered with is in\n * the trace its reply's arrival began when the installed tracer records that\n * span, as it is over the wire (WORKER-CONTRACT T1).\n *\n * Deterministic-by-construction: no `Date.now`, no randomness of its own —\n * all variation comes in through the schedule (fast-check owns the seed).\n * Time is real `setTimeout` at millisecond scale; properties pass a small\n * explicit `timeoutMs` to `Bus.request`, so nothing waits 30 s.\n */\n\nimport { BehaviorSubject, type Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { activeTrace, arrived } from './active-trace';\nimport { TransportError } from './errors';\nimport { KeptForFirstReader } from './kept-for-first-reader';\nimport type { BaseUrl } from './branded-types';\nimport { baseUrl as makeBaseUrl } from './branded-types';\nimport { TRACE_FIELD, USER_FIELD, type EventMap } from './bus-protocol';\nimport type { Frame } from './event-bus';\nimport type { ITransport } from './transport';\nimport { EventBus } from './event-bus';\nimport {\n BUS_OPERATIONS,\n REPLY_NAMES,\n type BusOperationKey,\n} from './bus-operations';\nimport { asDeclared, type Refused } from './bus';\nimport { BusRequestError } from './bus-request';\nimport { RESOURCE_SCOPED_CHANNELS } from './bridged-channels';\nimport { isResourceScopedChannel } from './bridging';\nimport { relayFrames } from './relay-frames';\nimport type { FaultAction, RequestLogEntry } from './testing-kit';\nimport type { ConnectionState, ResourceId, Envelope } from './types';\n\nexport interface FaultyTransportConfig {\n /**\n * The global channels this transport is given, as a wire transport is\n * given its stream's: a frame of no scope reaches a reader only on one of\n * them, a request's echo and a reply included; it bridges them, beside the\n * resource-scoped channels, into a client's bus, answers `isSubscribed` for\n * them alone, and assumes none of its own. A full client's test gives it `BRIDGED_CHANNELS`; a worker's,\n * the reply channels it awaits and what its claims read\n * (`JOB_CLAIM_CHANNELS`).\n */\n channels: readonly (keyof EventMap)[];\n /**\n * The i-th request-channel emit applies `schedule[i % schedule.length]`.\n * Empty/omitted → every request delivers.\n */\n schedule?: readonly FaultAction[];\n /**\n * Synthesize the `response` value for a delivered reply. Return `undefined`\n * for a void ack (a reply that carries no `response`). Default:\n * `refuseUnscriptedOperation`, which throws a `TransportError` naming the\n * operation.\n */\n makeResponse?: (\n operation: BusOperationKey,\n payload: Record<string, unknown>,\n ) => unknown;\n}\n\n/**\n * The default `makeResponse`: refuse, rather than invent.\n *\n * A `() => ({})` default would answer every unscripted operation with a\n * SUCCESS whose every field is `undefined`. That is not a neutral default —\n * it is a fabricated reply, and it surfaces far from its cause (a caller doing\n * `result.engines.find(...)` reports `undefined is not a function`, naming\n * neither the operation nor the missing script). A shape-correct empty default\n * would be worse still: a hand-written mirror of a wire shape the spec owns,\n * carrying a fallback.\n *\n * So the default names the gap. A test that wants an answer scripts one via\n * `queueReply` or its own `makeResponse`.\n */\nexport function refuseUnscriptedOperation(operation: string): never {\n throw new TransportError(\n `No response scripted for bus operation \"${operation}\". ` +\n `Script one with transport.queueReply('${operation}', <response>) ` +\n `or pass a makeResponse that handles it.`,\n 'error',\n );\n}\n\nfunction isOperation(channel: string): channel is BusOperationKey {\n return channel in BUS_OPERATIONS;\n}\n\n/** Stable request identity: channel + sorted payload minus per-issue fields.\n * The correlation key is not among them — it rides the envelope, so the\n * payload is stable across retries of the same request. */\nexport function retryKeyOf(\n channel: string,\n payload: Record<string, unknown>,\n): string {\n const entries = Object.entries(payload)\n .filter(([k]) => k !== TRACE_FIELD && k !== USER_FIELD)\n .sort(([a], [b]) => (a < b ? -1 : 1));\n return `${channel} ${JSON.stringify(entries)}`;\n}\n\nexport class FaultyTransport implements ITransport {\n readonly baseUrl: BaseUrl = makeBaseUrl('faulty://simulator');\n readonly state$ = new BehaviorSubject<ConnectionState>('open');\n private readonly failures = new KeptForFirstReader<TransportError>();\n /**\n * The failures `fail` reports. Of those reported before its first reader,\n * the latest `ERRORS_KEPT_FOR_FIRST_READER_COUNT` are kept for it, in the\n * order reported; what is still kept when the transport is disposed is\n * dropped.\n */\n readonly errors$: Observable<TransportError> = this.failures.said$;\n\n /** Every request-channel emit, in order — the L2 accounting surface. */\n readonly requestLog: RequestLogEntry[] = [];\n\n /** Every frame its stream carries, a request's echo and its reply included, as it arrived (`arrive`). */\n private readonly bus = new EventBus();\n private readonly channels: ReadonlySet<keyof EventMap>;\n /** The resources whose scopes are held, each with how many hold it. */\n private readonly scopeRefCounts = new Map<ResourceId, number>();\n private readonly schedule: readonly FaultAction[];\n private readonly makeResponse: (\n op: BusOperationKey,\n payload: Record<string, unknown>,\n ) => unknown;\n private readonly replyQueues = new Map<BusOperationKey, unknown[]>();\n private requestCount = 0;\n private readonly timers = new Set<ReturnType<typeof setTimeout>>();\n private disposed = false;\n\n constructor(cfg: FaultyTransportConfig) {\n this.channels = new Set(cfg.channels);\n this.schedule = cfg.schedule ?? [];\n this.makeResponse = cfg.makeResponse ?? refuseUnscriptedOperation;\n }\n\n /**\n * Queue responses for `op`, consumed FIFO — one per request that reaches\n * the simulated gateway — before falling back to `makeResponse`. The queue\n * scripts the GATEWAY; the fault schedule scripts the WIRE. Consequences,\n * deliberately: `duplicate-reply` replays one entry's body twice, and a\n * `drop-reply` still consumes its entry (the gateway answered; the wire ate\n * it) — so \"first reply lost, the retry sees the NEXT page\" is expressible.\n * `reject-emit` consumes nothing: that request never reached the gateway.\n *\n * Each entry is a `response`. A reply that names what it answers for beside\n * its response (`REPLY_NAMES`: the resource a context was gathered for, the\n * reference a search was for) takes that from its request, as a gateway's\n * does: a test queues the response alone.\n */\n queueReply(op: BusOperationKey, ...responses: unknown[]): void {\n const q = this.replyQueues.get(op) ?? [];\n q.push(...responses);\n this.replyQueues.set(op, q);\n }\n\n /**\n * Report `error` on `errors$`, as a transport reports a request the\n * gateway refused. A disposed transport reports nothing.\n */\n fail(error: TransportError): void {\n this.failures.say(error);\n }\n\n // ── Bus primitives ──────────────────────────────────────────────────────\n\n async emit<K extends keyof EventMap>(\n channel: K,\n payload: EventMap[K],\n envelope?: Envelope,\n ): Promise<number | undefined> {\n // The double models exactly one connected participant, so a delivered\n // emit reports `1`; post-dispose it is inert and reports no count.\n if (this.disposed) return undefined;\n const name = channel as string;\n // The frame as it is relayed back: its envelope, and the trace it was sent\n // under, when there is one.\n const trace = activeTrace();\n const sent: Frame<EventMap[K]> =\n trace === undefined\n ? { ...envelope, payload }\n : { ...envelope, payload, trace };\n if (!isOperation(name)) {\n // Non-request channel: forward as it was sent (scoped or global).\n this.arrive(channel, sent);\n return 1;\n }\n\n const record = payload as Record<string, unknown>;\n const action: FaultAction =\n this.schedule.length === 0\n ? { kind: 'deliver' }\n : this.schedule[this.requestCount % this.schedule.length]!;\n this.requestCount += 1;\n this.requestLog.push({\n channel: name,\n action,\n correlationId: envelope?.correlationId,\n retryKey: retryKeyOf(name, record),\n // Copied at emit time, so a caller that mutates its own payload\n // afterwards cannot rewrite the log; nested objects are shared.\n payload: { ...record },\n });\n\n if (action.kind === 'reject-emit') {\n // Models a /bus/emit 4xx: the request never reaches the bus.\n throw new Error(\n `FaultyTransport: emit rejected by schedule (reject-emit) on ${name}`,\n );\n }\n\n // The request itself is observable (handlers-eye view) to a reader of a\n // transport given its channel, then the simulator plays gateway:\n // synthesize the registry reply per the action. The envelope rides along:\n // a handler watching this double must read the same frame it would across\n // a broker.\n this.arrive(channel, sent);\n\n // The gateway's answer is computed ONCE per request that reaches it —\n // the reply QUEUE scripts the gateway, the fault schedule scripts the\n // wire. So `duplicate-reply` replays the same body twice, and a\n // `drop-reply` still consumes its queue entry: the gateway answered, the\n // wire ate it.\n const queue = this.replyQueues.get(name);\n const response =\n queue && queue.length > 0\n ? queue.shift()\n : this.makeResponse(name, record);\n\n // A reply that names what it answers for names what its request did, as a\n // gateway's does. Refused here, where it rejects the emit, rather than in\n // the reply's own microtask, where nobody is awaiting it.\n const named: Record<string, unknown> = {};\n for (const property of REPLY_NAMES[name]) {\n if (record[property] === undefined) {\n throw new Error(\n `FaultyTransport: the reply to ${name} names \"${property}\", which this request does not state`,\n );\n }\n named[property] = record[property];\n }\n\n const reply = (): void => {\n if (this.disposed) return;\n const replyPayload =\n response === undefined ? { ...named } : { ...named, response };\n const resultChannel = BUS_OPERATIONS[name].result as keyof EventMap;\n // The key rides back on the envelope, never inside the reply payload.\n this.arrive(resultChannel, {\n correlationId: envelope?.correlationId,\n payload: replyPayload as EventMap[keyof EventMap],\n });\n };\n\n switch (action.kind) {\n case 'deliver':\n queueMicrotask(reply);\n break;\n case 'duplicate-reply':\n queueMicrotask(reply);\n queueMicrotask(reply);\n break;\n case 'delay': {\n const t = setTimeout(() => {\n this.timers.delete(t);\n reply();\n }, action.ms);\n this.timers.add(t);\n break;\n }\n case 'drop-reply':\n break;\n }\n return 1;\n }\n\n on<K extends keyof EventMap>(\n channel: K,\n handler: (payload: EventMap[K] | Refused) => void,\n ): () => void {\n const sub = this.stream(channel).subscribe(handler);\n return () => sub.unsubscribe();\n }\n\n stream<K extends keyof EventMap>(\n channel: K,\n ): Observable<EventMap[K] | Refused> {\n return this.frames(channel).pipe(map((frame) => frame.payload));\n }\n\n /**\n * The frames on the channel that a wire transport's stream would carry: one\n * of no scope on a channel this transport was given, and one of a\n * resource's scope on a resource-scoped channel while that scope is held.\n * Every other frame is dropped. A stream carries every scope it holds on\n * the one channel, so a reader of one resource's keeps that scope's\n * (`Bus.frames(channel, resourceId)`).\n *\n * A resource-scoped channel is read with no scope held, as a wire\n * transport reads it, and carries nothing until one is. Any other channel\n * not given is refused at the call, as `bus.unsubscribed`: a frame on it\n * could never arrive.\n */\n frames<K extends keyof EventMap>(\n channel: K,\n ): Observable<Frame<EventMap[K] | Refused>> {\n if (!this.channels.has(channel) && !isResourceScopedChannel(channel)) {\n throw new BusRequestError(\n `Transport is not subscribed to ${channel as string} — a frame on it can never arrive on this connection. Give the transport the channel.`,\n 'bus.unsubscribed',\n { channel },\n );\n }\n return this.bus.channelStream(channel);\n }\n\n /**\n * Whether its stream carries a frame on `channel`, on `scope`: one of no\n * scope on a channel this transport was given, and one of a resource's\n * scope on a resource-scoped channel while that scope is held.\n */\n private carries(\n channel: keyof EventMap,\n scope: ResourceId | undefined,\n ): boolean {\n return scope === undefined\n ? this.channels.has(channel)\n : isResourceScopedChannel(channel) && this.scopeRefCounts.has(scope);\n }\n\n /**\n * A frame `frame`, sent under its `trace`, arriving on the stream: one the\n * stream does not carry reaches nobody, and one it carries has its arrival\n * marked (`arrived`) and is delivered in the trace that gives.\n */\n private arrive<K extends keyof EventMap>(\n channel: K,\n frame: Frame<EventMap[K]>,\n ): void {\n if (!this.carries(channel, frame.scope)) return;\n const { trace: sentUnder, ...sent } = frame;\n arrived(channel, frame.scope, sentUnder, (deliveredIn) => {\n this.bus.emitFrame(\n channel,\n deliveredIn === undefined ? sent : { ...sent, trace: deliveredIn },\n );\n });\n }\n\n /**\n * Whether the channels this transport was given name `channel`, as a wire\n * transport answers for its stream's global set: a request whose replies\n * they do not name fails at once, as `bus.unsubscribed`.\n */\n isSubscribed(channel: keyof EventMap): boolean {\n return this.channels.has(channel);\n }\n\n /**\n * Hold `resourceId`'s scope until the returned release, as a wire\n * transport holds it: each acquisition counts, distinct resources compose,\n * the scope is let go at its last release, and a release is idempotent.\n */\n subscribeToResource(resourceId: ResourceId): () => void {\n this.scopeRefCounts.set(\n resourceId,\n (this.scopeRefCounts.get(resourceId) ?? 0) + 1,\n );\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const holds = this.scopeRefCounts.get(resourceId);\n // None once the transport is disposed, which let every scope go.\n if (holds === undefined) return;\n if (holds > 1) this.scopeRefCounts.set(resourceId, holds - 1);\n else this.scopeRefCounts.delete(resourceId);\n };\n }\n\n /**\n * Correlated-reply tracking, exposed for assertions: `Bus.request` registers\n * each cid here before its emit and releases on settle, so a test can pin\n * the tracked set at any point of a request's lifecycle. This double never\n * drops its stream, so it has nothing to replay, and tracking has no\n * behavioral effect.\n */\n readonly pendingReplies = new Set<string>();\n\n trackReply(correlationId: string): () => void {\n this.pendingReplies.add(correlationId);\n let released = false;\n return () => {\n if (released) return;\n released = true;\n this.pendingReplies.delete(correlationId);\n };\n }\n\n /**\n * Publish on `bus` what `frames` delivers on the channels this transport\n * was given and on the resource-scoped ones, as a wire transport's bridge\n * does: a resource's frame while its scope is held, with no scope, since\n * the relay carries none.\n */\n bridgeInto(bus: EventBus): void {\n relayFrames(\n this,\n {\n // A payload that is not its channel's is published as its refusal, as a wire transport's bridge does.\n emitFrame: (channel, frame) =>\n bus.emitFrame(channel, {\n ...frame,\n payload: asDeclared(channel, frame.payload, frame),\n }),\n },\n [...this.channels, ...RESOURCE_SCOPED_CHANNELS],\n // `EventBus.emitFrame` is synchronous, so this never fires.\n (channel, error) => {\n throw new Error(\n `FaultyTransport: the bridge of ${channel as string} failed`,\n { cause: error },\n );\n },\n );\n }\n\n // ── Lifecycle ───────────────────────────────────────────────────────────\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.scopeRefCounts.clear();\n for (const t of this.timers) clearTimeout(t);\n this.timers.clear();\n this.state$.next('closed');\n this.state$.complete();\n this.failures.end();\n // Completes every subject: in-flight busRequests resolve `bus.closed`.\n this.bus.destroy();\n }\n}\n"]}