@solana/subscribable 6.3.1 → 6.3.2-canary-20260313112147

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solana/subscribable",
3
- "version": "6.3.1",
3
+ "version": "6.3.2-canary-20260313112147",
4
4
  "description": "Helpers for creating subscription-based event emitters",
5
5
  "homepage": "https://www.solanakit.com/api#solanasubscribable",
6
6
  "exports": {
@@ -33,7 +33,8 @@
33
33
  "types": "./dist/types/index.d.ts",
34
34
  "type": "commonjs",
35
35
  "files": [
36
- "./dist/"
36
+ "./dist/",
37
+ "./src/"
37
38
  ],
38
39
  "sideEffects": false,
39
40
  "keywords": [
@@ -55,7 +56,7 @@
55
56
  "maintained node versions"
56
57
  ],
57
58
  "dependencies": {
58
- "@solana/errors": "6.3.1"
59
+ "@solana/errors": "6.3.2-canary-20260313112147"
59
60
  },
60
61
  "peerDependencies": {
61
62
  "typescript": "^5.0.0"
@@ -0,0 +1,231 @@
1
+ import {
2
+ SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,
3
+ SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING,
4
+ SolanaError,
5
+ } from '@solana/errors';
6
+ import { AbortController } from '@solana/event-target-impl';
7
+
8
+ import { DataPublisher } from './data-publisher';
9
+
10
+ type Config = Readonly<{
11
+ /**
12
+ * Triggering this abort signal will cause all iterators spawned from this iterator to return
13
+ * once they have published all queued messages.
14
+ */
15
+ abortSignal: AbortSignal;
16
+ /**
17
+ * Messages from this channel of `dataPublisher` will be the ones yielded through the iterators.
18
+ *
19
+ * Messages only begin to be queued after the first time an iterator begins to poll. Channel
20
+ * messages published before that time will be dropped.
21
+ */
22
+ dataChannelName: string;
23
+ // FIXME: It would be nice to be able to constrain the type of `dataPublisher` to one that
24
+ // definitely supports the `dataChannelName` and `errorChannelName` channels, and
25
+ // furthermore publishes `TData` on the `dataChannelName` channel. This is more difficult
26
+ // than it should be: https://tsplay.dev/NlZelW
27
+ dataPublisher: DataPublisher;
28
+ /**
29
+ * Messages from this channel of `dataPublisher` will be the ones thrown through the iterators.
30
+ *
31
+ * Any new iterators created after the first error is encountered will reject with that error
32
+ * when polled.
33
+ */
34
+ errorChannelName: string;
35
+ }>;
36
+
37
+ const enum PublishType {
38
+ DATA,
39
+ ERROR,
40
+ }
41
+
42
+ type IteratorKey = symbol;
43
+ type IteratorState<TData> =
44
+ | {
45
+ __hasPolled: false;
46
+ publishQueue: (
47
+ | {
48
+ __type: PublishType.DATA;
49
+ data: TData;
50
+ }
51
+ | {
52
+ __type: PublishType.ERROR;
53
+ err: unknown;
54
+ }
55
+ )[];
56
+ }
57
+ | {
58
+ __hasPolled: true;
59
+ onData: (data: TData) => void;
60
+ onError: Parameters<ConstructorParameters<typeof Promise>[0]>[1];
61
+ };
62
+
63
+ let EXPLICIT_ABORT_TOKEN: symbol;
64
+ function createExplicitAbortToken() {
65
+ // This function is an annoying workaround to prevent `process.env.NODE_ENV` from appearing at
66
+ // the top level of this module and thwarting an optimizing compiler's attempt to tree-shake.
67
+ return Symbol(
68
+ __DEV__
69
+ ? "This symbol is thrown from a socket's iterator when the connection is explicitly " +
70
+ 'aborted by the user'
71
+ : undefined,
72
+ );
73
+ }
74
+
75
+ const UNINITIALIZED = Symbol();
76
+
77
+ /**
78
+ * Returns an `AsyncIterable` given a data publisher.
79
+ *
80
+ * The iterable will produce iterators that vend messages published to `dataChannelName` and will
81
+ * throw the first time a message is published to `errorChannelName`. Triggering the abort signal
82
+ * will cause all iterators spawned from this iterator to return once they have published all queued
83
+ * messages.
84
+ *
85
+ * Things to note:
86
+ *
87
+ * - If a message is published over a channel before the `AsyncIterator` attached to it has polled
88
+ * for the next result, the message will be queued in memory.
89
+ * - Messages only begin to be queued after the first time an iterator begins to poll. Channel
90
+ * messages published before that time will be dropped.
91
+ * - If there are messages in the queue and an error occurs, all queued messages will be vended to
92
+ * the iterator before the error is thrown.
93
+ * - If there are messages in the queue and the abort signal fires, all queued messages will be
94
+ * vended to the iterator after which it will return.
95
+ * - Any new iterators created after the first error is encountered will reject with that error when
96
+ * polled.
97
+ *
98
+ * @param config
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * const iterable = createAsyncIterableFromDataPublisher({
103
+ * abortSignal: AbortSignal.timeout(10_000),
104
+ * dataChannelName: 'message',
105
+ * dataPublisher,
106
+ * errorChannelName: 'error',
107
+ * });
108
+ * try {
109
+ * for await (const message of iterable) {
110
+ * console.log('Got message', message);
111
+ * }
112
+ * } catch (e) {
113
+ * console.error('An error was published to the error channel', e);
114
+ * } finally {
115
+ * console.log("It's been 10 seconds; that's enough for now.");
116
+ * }
117
+ * ```
118
+ */
119
+ export function createAsyncIterableFromDataPublisher<TData>({
120
+ abortSignal,
121
+ dataChannelName,
122
+ dataPublisher,
123
+ errorChannelName,
124
+ }: Config): AsyncIterable<TData> {
125
+ const iteratorState: Map<IteratorKey, IteratorState<TData>> = new Map();
126
+ function publishErrorToAllIterators(reason: unknown) {
127
+ for (const [iteratorKey, state] of iteratorState.entries()) {
128
+ if (state.__hasPolled) {
129
+ iteratorState.delete(iteratorKey);
130
+ state.onError(reason);
131
+ } else {
132
+ state.publishQueue.push({
133
+ __type: PublishType.ERROR,
134
+ err: reason,
135
+ });
136
+ }
137
+ }
138
+ }
139
+ const abortController = new AbortController();
140
+ abortSignal.addEventListener('abort', () => {
141
+ abortController.abort();
142
+ publishErrorToAllIterators((EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken()));
143
+ });
144
+ const options = { signal: abortController.signal } as const;
145
+ let firstError: unknown = UNINITIALIZED;
146
+ dataPublisher.on(
147
+ errorChannelName,
148
+ err => {
149
+ if (firstError === UNINITIALIZED) {
150
+ firstError = err;
151
+ abortController.abort();
152
+ publishErrorToAllIterators(err);
153
+ }
154
+ },
155
+ options,
156
+ );
157
+ dataPublisher.on(
158
+ dataChannelName,
159
+ data => {
160
+ iteratorState.forEach((state, iteratorKey) => {
161
+ if (state.__hasPolled) {
162
+ const { onData } = state;
163
+ iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });
164
+ onData(data as TData);
165
+ } else {
166
+ state.publishQueue.push({
167
+ __type: PublishType.DATA,
168
+ data: data as TData,
169
+ });
170
+ }
171
+ });
172
+ },
173
+ options,
174
+ );
175
+ return {
176
+ async *[Symbol.asyncIterator]() {
177
+ if (abortSignal.aborted) {
178
+ return;
179
+ }
180
+ if (firstError !== UNINITIALIZED) {
181
+ throw firstError;
182
+ }
183
+ const iteratorKey = Symbol();
184
+ iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });
185
+ try {
186
+ while (true) {
187
+ const state = iteratorState.get(iteratorKey);
188
+ if (!state) {
189
+ // There should always be state by now.
190
+ throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING);
191
+ }
192
+ if (state.__hasPolled) {
193
+ // You should never be able to poll twice in a row.
194
+ throw new SolanaError(
195
+ SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,
196
+ );
197
+ }
198
+ const publishQueue = state.publishQueue;
199
+ try {
200
+ if (publishQueue.length) {
201
+ state.publishQueue = [];
202
+ for (const item of publishQueue) {
203
+ if (item.__type === PublishType.DATA) {
204
+ yield item.data;
205
+ } else {
206
+ throw item.err;
207
+ }
208
+ }
209
+ } else {
210
+ yield await new Promise<TData>((resolve, reject) => {
211
+ iteratorState.set(iteratorKey, {
212
+ __hasPolled: true,
213
+ onData: resolve,
214
+ onError: reject,
215
+ });
216
+ });
217
+ }
218
+ } catch (e) {
219
+ if (e === (EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken())) {
220
+ return;
221
+ } else {
222
+ throw e;
223
+ }
224
+ }
225
+ }
226
+ } finally {
227
+ iteratorState.delete(iteratorKey);
228
+ }
229
+ },
230
+ };
231
+ }
@@ -0,0 +1,73 @@
1
+ import { TypedEventEmitter, TypedEventTarget } from './event-emitter';
2
+
3
+ type UnsubscribeFn = () => void;
4
+
5
+ /**
6
+ * Represents an object with an `on` function that you can call to subscribe to certain data over a
7
+ * named channel.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * let dataPublisher: DataPublisher<{ error: SolanaError }>;
12
+ * dataPublisher.on('data', handleData); // ERROR. `data` is not a known channel name.
13
+ * dataPublisher.on('error', e => {
14
+ * console.error(e);
15
+ * }); // OK.
16
+ * ```
17
+ */
18
+ export interface DataPublisher<TDataByChannelName extends Record<string, unknown> = Record<string, unknown>> {
19
+ /**
20
+ * Call this to subscribe to data over a named channel.
21
+ *
22
+ * @param channelName The name of the channel on which to subscribe for messages
23
+ * @param subscriber The function to call when a message becomes available
24
+ * @param options.signal An abort signal you can fire to unsubscribe
25
+ *
26
+ * @returns A function that you can call to unsubscribe
27
+ */
28
+ on<const TChannelName extends keyof TDataByChannelName>(
29
+ channelName: TChannelName,
30
+ subscriber: (data: TDataByChannelName[TChannelName]) => void,
31
+ options?: { signal: AbortSignal },
32
+ ): UnsubscribeFn;
33
+ }
34
+
35
+ /**
36
+ * Returns an object with an `on` function that you can call to subscribe to certain data over a
37
+ * named channel.
38
+ *
39
+ * The `on` function returns an unsubscribe function.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * const socketDataPublisher = getDataPublisherFromEventEmitter(new WebSocket('wss://api.devnet.solana.com'));
44
+ * const unsubscribe = socketDataPublisher.on('message', message => {
45
+ * if (JSON.parse(message.data).id === 42) {
46
+ * console.log('Got response 42');
47
+ * unsubscribe();
48
+ * }
49
+ * });
50
+ * ```
51
+ */
52
+ export function getDataPublisherFromEventEmitter<TEventMap extends Record<string, Event>>(
53
+ eventEmitter: TypedEventEmitter<TEventMap> | TypedEventTarget<TEventMap>,
54
+ ): DataPublisher<{
55
+ [TEventType in keyof TEventMap]: TEventMap[TEventType] extends CustomEvent ? TEventMap[TEventType]['detail'] : null;
56
+ }> {
57
+ return {
58
+ on(channelName, subscriber, options) {
59
+ function innerListener(ev: Event) {
60
+ if (ev instanceof CustomEvent) {
61
+ const data = (ev as CustomEvent<TEventMap[typeof channelName]>).detail;
62
+ (subscriber as unknown as (data: TEventMap[typeof channelName]) => void)(data);
63
+ } else {
64
+ (subscriber as () => void)();
65
+ }
66
+ }
67
+ eventEmitter.addEventListener(channelName, innerListener, options);
68
+ return () => {
69
+ eventEmitter.removeEventListener(channelName, innerListener);
70
+ };
71
+ },
72
+ };
73
+ }
@@ -0,0 +1,97 @@
1
+ import { EventTarget } from '@solana/event-target-impl';
2
+
3
+ import { DataPublisher, getDataPublisherFromEventEmitter } from './data-publisher';
4
+
5
+ /**
6
+ * Given a channel that carries messages for multiple subscribers on a single channel name, this
7
+ * function returns a new {@link DataPublisher} that splits them into multiple channel names.
8
+ *
9
+ * @param messageTransformer A function that receives the message as the first argument, and returns
10
+ * a tuple of the derived channel name and the message.
11
+ *
12
+ * @example
13
+ * Imagine a channel that carries multiple notifications whose destination is contained within the
14
+ * message itself.
15
+ *
16
+ * ```ts
17
+ * const demuxedDataPublisher = demultiplexDataPublisher(channel, 'message', message => {
18
+ * const destinationChannelName = `notification-for:${message.subscriberId}`;
19
+ * return [destinationChannelName, message];
20
+ * });
21
+ * ```
22
+ *
23
+ * Now you can subscribe to _only_ the messages you are interested in, without having to subscribe
24
+ * to the entire `'message'` channel and filter out the messages that are not for you.
25
+ *
26
+ * ```ts
27
+ * demuxedDataPublisher.on(
28
+ * 'notification-for:123',
29
+ * message => {
30
+ * console.log('Got a message for subscriber 123', message);
31
+ * },
32
+ * { signal: AbortSignal.timeout(5_000) },
33
+ * );
34
+ * ```
35
+ */
36
+ export function demultiplexDataPublisher<
37
+ TDataPublisher extends DataPublisher,
38
+ const TChannelName extends Parameters<TDataPublisher['on']>[0],
39
+ >(
40
+ publisher: TDataPublisher,
41
+ sourceChannelName: TChannelName,
42
+ messageTransformer: (
43
+ // FIXME: Deriving the type of the message from `TDataPublisher` and `TChannelName` would
44
+ // help callers to constrain their transform functions.
45
+ message: unknown,
46
+ ) => [destinationChannelName: string, message: unknown] | void,
47
+ ): DataPublisher {
48
+ let innerPublisherState:
49
+ | {
50
+ readonly dispose: () => void;
51
+ numSubscribers: number;
52
+ }
53
+ | undefined;
54
+ const eventTarget = new EventTarget();
55
+ const demultiplexedDataPublisher = getDataPublisherFromEventEmitter(eventTarget);
56
+ return {
57
+ ...demultiplexedDataPublisher,
58
+ on(channelName, subscriber, options) {
59
+ if (!innerPublisherState) {
60
+ const innerPublisherUnsubscribe = publisher.on(sourceChannelName, sourceMessage => {
61
+ const transformResult = messageTransformer(sourceMessage);
62
+ if (!transformResult) {
63
+ return;
64
+ }
65
+ const [destinationChannelName, message] = transformResult;
66
+ eventTarget.dispatchEvent(
67
+ new CustomEvent(destinationChannelName, {
68
+ detail: message,
69
+ }),
70
+ );
71
+ });
72
+ innerPublisherState = {
73
+ dispose: innerPublisherUnsubscribe,
74
+ numSubscribers: 0,
75
+ };
76
+ }
77
+ innerPublisherState.numSubscribers++;
78
+ const unsubscribe = demultiplexedDataPublisher.on(channelName, subscriber, options);
79
+ let isActive = true;
80
+ function handleUnsubscribe() {
81
+ if (!isActive) {
82
+ return;
83
+ }
84
+ isActive = false;
85
+ options?.signal.removeEventListener('abort', handleUnsubscribe);
86
+ innerPublisherState!.numSubscribers--;
87
+ if (innerPublisherState!.numSubscribers === 0) {
88
+ innerPublisherState!.dispose();
89
+ innerPublisherState = undefined;
90
+ }
91
+ unsubscribe();
92
+ }
93
+ options?.signal.addEventListener('abort', handleUnsubscribe);
94
+ return handleUnsubscribe;
95
+ },
96
+ };
97
+ }
@@ -0,0 +1,55 @@
1
+ type EventMap = Record<string, Event>;
2
+ type Listener<TEvent extends Event> = ((evt: TEvent) => void) | { handleEvent(object: TEvent): void };
3
+
4
+ /**
5
+ * This type allows you to type `addEventListener` and `removeEventListener` so that the call
6
+ * signature of the listener matches the event type given.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * const emitter: TypedEventEmitter<{ message: MessageEvent }> = new WebSocket('wss://api.devnet.solana.com');
11
+ * emitter.addEventListener('data', handleData); // ERROR. `data` is not a known event type.
12
+ * emitter.addEventListener('message', message => {
13
+ * console.log(message.origin); // OK. `message` is a `MessageEvent` so it has an `origin` property.
14
+ * });
15
+ * ```
16
+ */
17
+ export interface TypedEventEmitter<TEventMap extends EventMap> {
18
+ addEventListener<const TEventType extends keyof TEventMap>(
19
+ type: TEventType,
20
+ listener: Listener<TEventMap[TEventType]>,
21
+ options?: AddEventListenerOptions | boolean,
22
+ ): void;
23
+ removeEventListener<const TEventType extends keyof TEventMap>(
24
+ type: TEventType,
25
+ listener: Listener<TEventMap[TEventType]>,
26
+ options?: EventListenerOptions | boolean,
27
+ ): void;
28
+ }
29
+
30
+ // Why not just extend the interface above, rather than to copy/paste it?
31
+ // See https://github.com/microsoft/TypeScript/issues/60008
32
+ /**
33
+ * This type is a superset of `TypedEventEmitter` that allows you to constrain calls to
34
+ * `dispatchEvent`.
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * const target: TypedEventTarget<{ candyVended: CustomEvent<{ flavour: string }> }> = new EventTarget();
39
+ * target.dispatchEvent(new CustomEvent('candyVended', { detail: { flavour: 'raspberry' } })); // OK.
40
+ * target.dispatchEvent(new CustomEvent('candyVended', { detail: { flavor: 'raspberry' } })); // ERROR. Misspelling in detail.
41
+ * ```
42
+ */
43
+ export interface TypedEventTarget<TEventMap extends EventMap> {
44
+ addEventListener<const TEventType extends keyof TEventMap>(
45
+ type: TEventType,
46
+ listener: Listener<TEventMap[TEventType]>,
47
+ options?: AddEventListenerOptions | boolean,
48
+ ): void;
49
+ dispatchEvent<TEventType extends keyof TEventMap>(ev: TEventMap[TEventType]): void;
50
+ removeEventListener<const TEventType extends keyof TEventMap>(
51
+ type: TEventType,
52
+ listener: Listener<TEventMap[TEventType]>,
53
+ options?: EventListenerOptions | boolean,
54
+ ): void;
55
+ }
package/src/index.ts ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * This package contains utilities for creating subscription-based event targets. These differ from
3
+ * the `EventTarget` interface in that the method you use to add a listener returns an unsubscribe
4
+ * function. It is primarily intended for internal use -- particularly for those building
5
+ * {@link RpcSubscriptionChannel | RpcSubscriptionChannels} and associated infrastructure.
6
+ *
7
+ * @packageDocumentation
8
+ */
9
+ export * from './async-iterable';
10
+ export * from './data-publisher';
11
+ export * from './demultiplex';
12
+ export * from './event-emitter';