@solana/subscribable 6.9.0 → 6.10.0-canary-20260507151050
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/README.md +54 -14
- package/dist/index.browser.cjs +96 -10
- package/dist/index.browser.cjs.map +1 -1
- package/dist/index.browser.mjs +97 -12
- package/dist/index.browser.mjs.map +1 -1
- package/dist/index.native.mjs +97 -12
- package/dist/index.native.mjs.map +1 -1
- package/dist/index.node.cjs +96 -10
- package/dist/index.node.cjs.map +1 -1
- package/dist/index.node.mjs +97 -12
- package/dist/index.node.mjs.map +1 -1
- package/dist/types/reactive-store.d.ts +122 -25
- package/dist/types/reactive-store.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/reactive-store.ts +225 -40
package/README.md
CHANGED
|
@@ -29,26 +29,38 @@ dataPublisher.on('error', e => {
|
|
|
29
29
|
|
|
30
30
|
### `ReactiveStore<T>`
|
|
31
31
|
|
|
32
|
-
This type represents a reactive store that holds the latest value published to a data channel. It exposes a `{
|
|
32
|
+
This type represents a reactive store that holds the latest value published to a data channel. It exposes a `{ getUnifiedState, retry, subscribe }` contract compatible with `useSyncExternalStore`, Svelte stores, and other reactive primitives.
|
|
33
|
+
|
|
34
|
+
`getUnifiedState()` returns a discriminated snapshot of the store's lifecycle:
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
type ReactiveState<T> =
|
|
38
|
+
| { data: undefined; error: undefined; status: 'loading' }
|
|
39
|
+
| { data: T; error: undefined; status: 'loaded' }
|
|
40
|
+
| { data: T | undefined; error: unknown; status: 'error' }
|
|
41
|
+
| { data: T | undefined; error: undefined; status: 'retrying' };
|
|
42
|
+
```
|
|
33
43
|
|
|
34
44
|
```ts
|
|
35
45
|
const store: ReactiveStore<AccountInfo> = /* ... */;
|
|
36
46
|
|
|
37
|
-
// React
|
|
38
|
-
const state = useSyncExternalStore(store.subscribe,
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
}
|
|
47
|
+
// React — snapshot identity is stable between updates, so it can be passed directly.
|
|
48
|
+
const state = useSyncExternalStore(store.subscribe, store.getUnifiedState);
|
|
49
|
+
if (state.status === 'error') return <ErrorMessage error={state.error} onRetry={store.retry} />;
|
|
50
|
+
if (state.status === 'loading') return <Spinner />;
|
|
51
|
+
return <View data={state.data} />;
|
|
42
52
|
|
|
43
53
|
// Vue
|
|
44
|
-
const
|
|
45
|
-
const error = shallowRef(store.getError());
|
|
54
|
+
const snapshot = shallowRef(store.getUnifiedState());
|
|
46
55
|
store.subscribe(() => {
|
|
47
|
-
|
|
48
|
-
error.value = store.getError();
|
|
56
|
+
snapshot.value = store.getUnifiedState();
|
|
49
57
|
});
|
|
50
58
|
```
|
|
51
59
|
|
|
60
|
+
`retry()` re-opens the stream after an error. When the underlying store supports restart (see [`createReactiveStoreFromDataPublisherFactory`](#createreactivestorefromdatapublisherfactory-abortsignal-createdatapublisher-datachannelname-errorchannelname-)), the store transitions to `status: 'retrying'` and reconnects. Stores that cannot be restarted throw a `SolanaError` with code `SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED` instead.
|
|
61
|
+
|
|
62
|
+
The individual `getState()` and `getError()` getters on `ReactiveStore<T>` are `@deprecated` — prefer `getUnifiedState()`, which exposes the same information with a stable snapshot identity and `status` discriminator.
|
|
63
|
+
|
|
52
64
|
### `TypedEventEmitter<TEventMap>`
|
|
53
65
|
|
|
54
66
|
This type allows you to type `addEventListener` and `removeEventListener` so that the call signature of the listener matches the event type given.
|
|
@@ -105,7 +117,9 @@ Things to note:
|
|
|
105
117
|
|
|
106
118
|
### `createReactiveStoreFromDataPublisher({ abortSignal, dataChannelName, dataPublisher, errorChannelName })`
|
|
107
119
|
|
|
108
|
-
|
|
120
|
+
> **Deprecated.** Prefer [`createReactiveStoreFromDataPublisherFactory`](#createreactivestorefromdatapublisherfactory-abortsignal-createdatapublisher-datachannelname-errorchannelname-) — it supports `retry()`. Because this function accepts a ready-made `DataPublisher` rather than a factory, it cannot restart the underlying source, and calling `retry()` on the returned store throws a `SolanaError` with code `SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED`.
|
|
121
|
+
|
|
122
|
+
Returns a `ReactiveStore` given a data publisher. The store holds the most recent message published to `dataChannelName` and notifies subscribers on each update. When a message is published to `errorChannelName`, the store transitions to `status: 'error'` preserving the last known value. Triggering the abort signal disconnects the store from the data publisher.
|
|
109
123
|
|
|
110
124
|
```ts
|
|
111
125
|
const store = createReactiveStoreFromDataPublisher({
|
|
@@ -115,16 +129,42 @@ const store = createReactiveStoreFromDataPublisher({
|
|
|
115
129
|
errorChannelName: 'error',
|
|
116
130
|
});
|
|
117
131
|
const unsubscribe = store.subscribe(() => {
|
|
118
|
-
console.log('State updated:', store.
|
|
132
|
+
console.log('State updated:', store.getUnifiedState());
|
|
119
133
|
});
|
|
120
134
|
```
|
|
121
135
|
|
|
122
136
|
Things to note:
|
|
123
137
|
|
|
124
|
-
- `
|
|
125
|
-
- On error, `
|
|
138
|
+
- `getUnifiedState()` starts in `status: 'loading'` until the first notification arrives.
|
|
139
|
+
- On error, `status` becomes `'error'` with the last known value preserved on `data`. Only the first error is captured.
|
|
126
140
|
- The function returned by `subscribe` is idempotent — calling it multiple times is safe.
|
|
127
141
|
|
|
142
|
+
### `createReactiveStoreFromDataPublisherFactory({ abortSignal, createDataPublisher, dataChannelName, errorChannelName })`
|
|
143
|
+
|
|
144
|
+
Returns a `ReactiveStore` that wires itself to a fresh `DataPublisher` on construction and on every `retry()`. Unlike `createReactiveStoreFromDataPublisher`, this variant accepts an async factory so the store can tear down a broken stream and open a new one without losing subscribers or the last known value.
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
const store = createReactiveStoreFromDataPublisherFactory({
|
|
148
|
+
abortSignal: AbortSignal.timeout(60_000),
|
|
149
|
+
async createDataPublisher() {
|
|
150
|
+
return await openMyConnection();
|
|
151
|
+
},
|
|
152
|
+
dataChannelName: 'notification',
|
|
153
|
+
errorChannelName: 'error',
|
|
154
|
+
});
|
|
155
|
+
store.subscribe(() => {
|
|
156
|
+
const snapshot = store.getUnifiedState();
|
|
157
|
+
if (snapshot.status === 'error') store.retry();
|
|
158
|
+
});
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
Things to note:
|
|
162
|
+
|
|
163
|
+
- `createDataPublisher` is called once on construction and again on every `retry()`.
|
|
164
|
+
- `retry()` is a no-op unless the store is in `status: 'error'`; otherwise the store transitions to `status: 'retrying'` (preserving stale data) and reconnects.
|
|
165
|
+
- If `createDataPublisher` rejects, the store transitions to `status: 'error'` with the rejection as the error. Call `retry()` to try again.
|
|
166
|
+
- Triggering the caller's `abortSignal` disconnects the store permanently; subsequent `retry()` calls are no-ops.
|
|
167
|
+
|
|
128
168
|
### `demultiplexDataPublisher(publisher, sourceChannelName, messageTransformer)`
|
|
129
169
|
|
|
130
170
|
Given a channel that carries messages for multiple subscribers on a single channel name, this function returns a new `DataPublisher` that splits them into multiple channel names.
|
package/dist/index.browser.cjs
CHANGED
|
@@ -195,44 +195,129 @@ function demultiplexDataPublisher(publisher, sourceChannelName, messageTransform
|
|
|
195
195
|
}
|
|
196
196
|
};
|
|
197
197
|
}
|
|
198
|
-
|
|
199
|
-
|
|
198
|
+
var LOADING_STATE = Object.freeze({
|
|
199
|
+
data: void 0,
|
|
200
|
+
error: void 0,
|
|
201
|
+
status: "loading"
|
|
202
|
+
});
|
|
200
203
|
function createReactiveStoreFromDataPublisher({
|
|
201
204
|
abortSignal,
|
|
202
205
|
dataChannelName,
|
|
203
206
|
dataPublisher,
|
|
204
207
|
errorChannelName
|
|
205
208
|
}) {
|
|
206
|
-
let currentState;
|
|
207
|
-
let currentError;
|
|
209
|
+
let currentState = LOADING_STATE;
|
|
208
210
|
const subscribers = /* @__PURE__ */ new Set();
|
|
209
211
|
const abortController = new o();
|
|
210
212
|
abortSignal.addEventListener("abort", () => abortController.abort(abortSignal.reason));
|
|
213
|
+
function notify() {
|
|
214
|
+
subscribers.forEach((cb) => cb());
|
|
215
|
+
}
|
|
211
216
|
dataPublisher.on(
|
|
212
217
|
dataChannelName,
|
|
213
218
|
(data) => {
|
|
214
|
-
currentState = data;
|
|
215
|
-
|
|
219
|
+
currentState = { data, error: void 0, status: "loaded" };
|
|
220
|
+
notify();
|
|
216
221
|
},
|
|
217
222
|
{ signal: abortController.signal }
|
|
218
223
|
);
|
|
219
224
|
dataPublisher.on(
|
|
220
225
|
errorChannelName,
|
|
221
226
|
(err) => {
|
|
222
|
-
if (
|
|
223
|
-
|
|
227
|
+
if (currentState.status === "error") return;
|
|
228
|
+
currentState = { data: currentState.data, error: err, status: "error" };
|
|
224
229
|
abortController.abort(err);
|
|
225
|
-
|
|
230
|
+
notify();
|
|
226
231
|
},
|
|
227
232
|
{ signal: abortController.signal }
|
|
228
233
|
);
|
|
229
234
|
return {
|
|
230
235
|
getError() {
|
|
231
|
-
return
|
|
236
|
+
return currentState.error;
|
|
237
|
+
},
|
|
238
|
+
getState() {
|
|
239
|
+
return currentState.data;
|
|
240
|
+
},
|
|
241
|
+
getUnifiedState() {
|
|
242
|
+
return currentState;
|
|
243
|
+
},
|
|
244
|
+
retry() {
|
|
245
|
+
throw new errors.SolanaError(errors.SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED);
|
|
246
|
+
},
|
|
247
|
+
subscribe(callback) {
|
|
248
|
+
subscribers.add(callback);
|
|
249
|
+
return () => {
|
|
250
|
+
subscribers.delete(callback);
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
function createReactiveStoreFromDataPublisherFactory({
|
|
256
|
+
abortSignal,
|
|
257
|
+
createDataPublisher,
|
|
258
|
+
dataChannelName,
|
|
259
|
+
errorChannelName
|
|
260
|
+
}) {
|
|
261
|
+
let currentState = LOADING_STATE;
|
|
262
|
+
const subscribers = /* @__PURE__ */ new Set();
|
|
263
|
+
const outerController = new o();
|
|
264
|
+
abortSignal.addEventListener("abort", () => outerController.abort(abortSignal.reason));
|
|
265
|
+
function notify() {
|
|
266
|
+
subscribers.forEach((cb) => cb());
|
|
267
|
+
}
|
|
268
|
+
function connect() {
|
|
269
|
+
if (outerController.signal.aborted) return;
|
|
270
|
+
const innerController = new o();
|
|
271
|
+
const forwardAbort = () => innerController.abort(outerController.signal.reason);
|
|
272
|
+
outerController.signal.addEventListener("abort", forwardAbort, { signal: innerController.signal });
|
|
273
|
+
createDataPublisher().then(
|
|
274
|
+
(publisher) => {
|
|
275
|
+
if (innerController.signal.aborted) return;
|
|
276
|
+
publisher.on(
|
|
277
|
+
dataChannelName,
|
|
278
|
+
(data) => {
|
|
279
|
+
currentState = { data, error: void 0, status: "loaded" };
|
|
280
|
+
notify();
|
|
281
|
+
},
|
|
282
|
+
{ signal: innerController.signal }
|
|
283
|
+
);
|
|
284
|
+
publisher.on(
|
|
285
|
+
errorChannelName,
|
|
286
|
+
(err) => {
|
|
287
|
+
if (currentState.status === "error") return;
|
|
288
|
+
currentState = { data: currentState.data, error: err, status: "error" };
|
|
289
|
+
innerController.abort(err);
|
|
290
|
+
notify();
|
|
291
|
+
},
|
|
292
|
+
{ signal: innerController.signal }
|
|
293
|
+
);
|
|
294
|
+
},
|
|
295
|
+
(err) => {
|
|
296
|
+
if (innerController.signal.aborted) return;
|
|
297
|
+
currentState = { data: currentState.data, error: err, status: "error" };
|
|
298
|
+
innerController.abort(err);
|
|
299
|
+
notify();
|
|
300
|
+
}
|
|
301
|
+
);
|
|
302
|
+
}
|
|
303
|
+
connect();
|
|
304
|
+
return {
|
|
305
|
+
getError() {
|
|
306
|
+
return currentState.error;
|
|
232
307
|
},
|
|
233
308
|
getState() {
|
|
309
|
+
return currentState.data;
|
|
310
|
+
},
|
|
311
|
+
getUnifiedState() {
|
|
234
312
|
return currentState;
|
|
235
313
|
},
|
|
314
|
+
retry() {
|
|
315
|
+
if (outerController.signal.aborted) return;
|
|
316
|
+
if (currentState.status !== "error") return;
|
|
317
|
+
currentState = { data: currentState.data, error: void 0, status: "retrying" };
|
|
318
|
+
notify();
|
|
319
|
+
connect();
|
|
320
|
+
},
|
|
236
321
|
subscribe(callback) {
|
|
237
322
|
subscribers.add(callback);
|
|
238
323
|
return () => {
|
|
@@ -244,6 +329,7 @@ function createReactiveStoreFromDataPublisher({
|
|
|
244
329
|
|
|
245
330
|
exports.createAsyncIterableFromDataPublisher = createAsyncIterableFromDataPublisher;
|
|
246
331
|
exports.createReactiveStoreFromDataPublisher = createReactiveStoreFromDataPublisher;
|
|
332
|
+
exports.createReactiveStoreFromDataPublisherFactory = createReactiveStoreFromDataPublisherFactory;
|
|
247
333
|
exports.demultiplexDataPublisher = demultiplexDataPublisher;
|
|
248
334
|
exports.getDataPublisherFromEventEmitter = getDataPublisherFromEventEmitter;
|
|
249
335
|
//# sourceMappingURL=index.browser.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../event-target-impl/src/index.browser.ts","../src/async-iterable.ts","../src/data-publisher.ts","../src/demultiplex.ts","../src/reactive-store.ts"],"names":["AbortController","EventTarget","SolanaError","SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING","SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE"],"mappings":";;;;;;;AAAO,IAAMA,IAAkB,UAAA,CAAW,eAAA;AAAnC,IACMC,IAAc,UAAA,CAAW,WAAA;;;AC6DtC,IAAI,oBAAA;AACJ,SAAS,wBAAA,GAA2B;AAGhC,EAAA,OAAO,MAAA;AAAA,IACH,OAAA,CAAA,GAAA,CAAA,QAAA,KAAyB,eACnB,sGAAA,GAEA;AAAA,GACV;AACJ;AAEA,IAAM,gBAAgB,MAAA,EAAO;AA4CtB,SAAS,oCAAA,CAA4C;AAAA,EACxD,WAAA;AAAA,EACA,eAAA;AAAA,EACA,aAAA;AAAA,EACA;AACJ,CAAA,EAAiC;A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AAE,MAAA,EAAQ,eAAA,CAAgB,MAAA;AAAO,GACrC;AAEA,EAAA,OAAO;AAAA,IACH,QAAA,GAAoB;AAChB,MAAA,OAAO,YAAA;AAAA,IACX,CAAA;AAAA,IACA,QAAA,GAA8B;AAC1B,MAAA,OAAO,YAAA;AAAA,IACX,CAAA;AAAA,IACA,UAAU,QAAA,EAAkC;AACxC,MAAA,WAAA,CAAY,IAAI,QAAQ,CAAA;AACxB,MAAA,OAAO,MAAM;AACT,QAAA,WAAA,CAAY,OAAO,QAAQ,CAAA;AAAA,MAC/B,CAAA;AAAA,IACJ;AAAA,GACJ;AACJ","file":"index.browser.cjs","sourcesContent":["export const AbortController = globalThis.AbortController;\nexport const EventTarget = globalThis.EventTarget;\n","import {\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\n\nimport { DataPublisher } from './data-publisher';\n\ntype Config = Readonly<{\n /**\n * Triggering this abort signal will cause all iterators spawned from this iterator to return\n * once they have published all queued messages.\n */\n abortSignal: AbortSignal;\n /**\n * Messages from this channel of `dataPublisher` will be the ones yielded through the iterators.\n *\n * Messages only begin to be queued after the first time an iterator begins to poll. Channel\n * messages published before that time will be dropped.\n */\n dataChannelName: string;\n // FIXME: It would be nice to be able to constrain the type of `dataPublisher` to one that\n // definitely supports the `dataChannelName` and `errorChannelName` channels, and\n // furthermore publishes `TData` on the `dataChannelName` channel. This is more difficult\n // than it should be: https://tsplay.dev/NlZelW\n dataPublisher: DataPublisher;\n /**\n * Messages from this channel of `dataPublisher` will be the ones thrown through the iterators.\n *\n * Any new iterators created after the first error is encountered will reject with that error\n * when polled.\n */\n errorChannelName: string;\n}>;\n\nconst enum PublishType {\n DATA,\n ERROR,\n}\n\ntype IteratorKey = symbol;\ntype IteratorState<TData> =\n | {\n __hasPolled: false;\n publishQueue: (\n | {\n __type: PublishType.DATA;\n data: TData;\n }\n | {\n __type: PublishType.ERROR;\n err: unknown;\n }\n )[];\n }\n | {\n __hasPolled: true;\n onData: (data: TData) => void;\n onError: Parameters<ConstructorParameters<typeof Promise>[0]>[1];\n };\n\nlet EXPLICIT_ABORT_TOKEN: symbol;\nfunction createExplicitAbortToken() {\n // This function is an annoying workaround to prevent `process.env.NODE_ENV` from appearing at\n // the top level of this module and thwarting an optimizing compiler's attempt to tree-shake.\n return Symbol(\n process.env.NODE_ENV !== \"production\"\n ? \"This symbol is thrown from a socket's iterator when the connection is explicitly \" +\n 'aborted by the user'\n : undefined,\n );\n}\n\nconst UNINITIALIZED = Symbol();\n\n/**\n * Returns an `AsyncIterable` given a data publisher.\n *\n * The iterable will produce iterators that vend messages published to `dataChannelName` and will\n * throw the first time a message is published to `errorChannelName`. Triggering the abort signal\n * will cause all iterators spawned from this iterator to return once they have published all queued\n * messages.\n *\n * Things to note:\n *\n * - If a message is published over a channel before the `AsyncIterator` attached to it has polled\n * for the next result, the message will be queued in memory.\n * - Messages only begin to be queued after the first time an iterator begins to poll. Channel\n * messages published before that time will be dropped.\n * - If there are messages in the queue and an error occurs, all queued messages will be vended to\n * the iterator before the error is thrown.\n * - If there are messages in the queue and the abort signal fires, all queued messages will be\n * vended to the iterator after which it will return.\n * - Any new iterators created after the first error is encountered will reject with that error when\n * polled.\n *\n * @param config\n *\n * @example\n * ```ts\n * const iterable = createAsyncIterableFromDataPublisher({\n * abortSignal: AbortSignal.timeout(10_000),\n * dataChannelName: 'message',\n * dataPublisher,\n * errorChannelName: 'error',\n * });\n * try {\n * for await (const message of iterable) {\n * console.log('Got message', message);\n * }\n * } catch (e) {\n * console.error('An error was published to the error channel', e);\n * } finally {\n * console.log(\"It's been 10 seconds; that's enough for now.\");\n * }\n * ```\n */\nexport function createAsyncIterableFromDataPublisher<TData>({\n abortSignal,\n dataChannelName,\n dataPublisher,\n errorChannelName,\n}: Config): AsyncIterable<TData> {\n const iteratorState: Map<IteratorKey, IteratorState<TData>> = new Map();\n function publishErrorToAllIterators(reason: unknown) {\n for (const [iteratorKey, state] of iteratorState.entries()) {\n if (state.__hasPolled) {\n iteratorState.delete(iteratorKey);\n state.onError(reason);\n } else {\n state.publishQueue.push({\n __type: PublishType.ERROR,\n err: reason,\n });\n }\n }\n }\n const abortController = new AbortController();\n abortSignal.addEventListener('abort', () => {\n abortController.abort();\n publishErrorToAllIterators((EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken()));\n });\n const options = { signal: abortController.signal } as const;\n let firstError: unknown = UNINITIALIZED;\n dataPublisher.on(\n errorChannelName,\n err => {\n if (firstError === UNINITIALIZED) {\n firstError = err;\n abortController.abort();\n publishErrorToAllIterators(err);\n }\n },\n options,\n );\n dataPublisher.on(\n dataChannelName,\n data => {\n iteratorState.forEach((state, iteratorKey) => {\n if (state.__hasPolled) {\n const { onData } = state;\n iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });\n onData(data as TData);\n } else {\n state.publishQueue.push({\n __type: PublishType.DATA,\n data: data as TData,\n });\n }\n });\n },\n options,\n );\n return {\n async *[Symbol.asyncIterator]() {\n if (abortSignal.aborted) {\n return;\n }\n if (firstError !== UNINITIALIZED) {\n throw firstError;\n }\n const iteratorKey = Symbol();\n iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });\n try {\n while (true) {\n const state = iteratorState.get(iteratorKey);\n if (!state) {\n // There should always be state by now.\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING);\n }\n if (state.__hasPolled) {\n // You should never be able to poll twice in a row.\n throw new SolanaError(\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,\n );\n }\n const publishQueue = state.publishQueue;\n try {\n if (publishQueue.length) {\n state.publishQueue = [];\n for (const item of publishQueue) {\n if (item.__type === PublishType.DATA) {\n yield item.data;\n } else {\n throw item.err;\n }\n }\n } else {\n yield await new Promise<TData>((resolve, reject) => {\n iteratorState.set(iteratorKey, {\n __hasPolled: true,\n onData: resolve,\n onError: reject,\n });\n });\n }\n } catch (e) {\n if (e === (EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken())) {\n return;\n } else {\n throw e;\n }\n }\n }\n } finally {\n iteratorState.delete(iteratorKey);\n }\n },\n };\n}\n","import { TypedEventEmitter, TypedEventTarget } from './event-emitter';\n\ntype UnsubscribeFn = () => void;\n\n/**\n * Represents an object with an `on` function that you can call to subscribe to certain data over a\n * named channel.\n *\n * @example\n * ```ts\n * let dataPublisher: DataPublisher<{ error: SolanaError }>;\n * dataPublisher.on('data', handleData); // ERROR. `data` is not a known channel name.\n * dataPublisher.on('error', e => {\n * console.error(e);\n * }); // OK.\n * ```\n */\nexport interface DataPublisher<TDataByChannelName extends Record<string, unknown> = Record<string, unknown>> {\n /**\n * Call this to subscribe to data over a named channel.\n *\n * @param channelName The name of the channel on which to subscribe for messages\n * @param subscriber The function to call when a message becomes available\n * @param options.signal An abort signal you can fire to unsubscribe\n *\n * @returns A function that you can call to unsubscribe\n */\n on<const TChannelName extends keyof TDataByChannelName>(\n channelName: TChannelName,\n subscriber: (data: TDataByChannelName[TChannelName]) => void,\n options?: { signal: AbortSignal },\n ): UnsubscribeFn;\n}\n\n/**\n * Returns an object with an `on` function that you can call to subscribe to certain data over a\n * named channel.\n *\n * The `on` function returns an unsubscribe function.\n *\n * @example\n * ```ts\n * const socketDataPublisher = getDataPublisherFromEventEmitter(new WebSocket('wss://api.devnet.solana.com'));\n * const unsubscribe = socketDataPublisher.on('message', message => {\n * if (JSON.parse(message.data).id === 42) {\n * console.log('Got response 42');\n * unsubscribe();\n * }\n * });\n * ```\n */\nexport function getDataPublisherFromEventEmitter<TEventMap extends Record<string, Event>>(\n eventEmitter: TypedEventEmitter<TEventMap> | TypedEventTarget<TEventMap>,\n): DataPublisher<{\n [TEventType in keyof TEventMap]: TEventMap[TEventType] extends CustomEvent ? TEventMap[TEventType]['detail'] : null;\n}> {\n return {\n on(channelName, subscriber, options) {\n function innerListener(ev: Event) {\n if (ev instanceof CustomEvent) {\n const data = (ev as CustomEvent<TEventMap[typeof channelName]>).detail;\n (subscriber as unknown as (data: TEventMap[typeof channelName]) => void)(data);\n } else {\n (subscriber as () => void)();\n }\n }\n eventEmitter.addEventListener(channelName, innerListener, options);\n return () => {\n eventEmitter.removeEventListener(channelName, innerListener);\n };\n },\n };\n}\n","import { EventTarget } from '@solana/event-target-impl';\n\nimport { DataPublisher, getDataPublisherFromEventEmitter } from './data-publisher';\n\n/**\n * Given a channel that carries messages for multiple subscribers on a single channel name, this\n * function returns a new {@link DataPublisher} that splits them into multiple channel names.\n *\n * @param messageTransformer A function that receives the message as the first argument, and returns\n * a tuple of the derived channel name and the message.\n *\n * @example\n * Imagine a channel that carries multiple notifications whose destination is contained within the\n * message itself.\n *\n * ```ts\n * const demuxedDataPublisher = demultiplexDataPublisher(channel, 'message', message => {\n * const destinationChannelName = `notification-for:${message.subscriberId}`;\n * return [destinationChannelName, message];\n * });\n * ```\n *\n * Now you can subscribe to _only_ the messages you are interested in, without having to subscribe\n * to the entire `'message'` channel and filter out the messages that are not for you.\n *\n * ```ts\n * demuxedDataPublisher.on(\n * 'notification-for:123',\n * message => {\n * console.log('Got a message for subscriber 123', message);\n * },\n * { signal: AbortSignal.timeout(5_000) },\n * );\n * ```\n */\nexport function demultiplexDataPublisher<\n TDataPublisher extends DataPublisher,\n const TChannelName extends Parameters<TDataPublisher['on']>[0],\n>(\n publisher: TDataPublisher,\n sourceChannelName: TChannelName,\n messageTransformer: (\n // FIXME: Deriving the type of the message from `TDataPublisher` and `TChannelName` would\n // help callers to constrain their transform functions.\n message: unknown,\n ) => [destinationChannelName: string, message: unknown] | void,\n): DataPublisher {\n let innerPublisherState:\n | {\n readonly dispose: () => void;\n numSubscribers: number;\n }\n | undefined;\n const eventTarget = new EventTarget();\n const demultiplexedDataPublisher = getDataPublisherFromEventEmitter(eventTarget);\n return {\n ...demultiplexedDataPublisher,\n on(channelName, subscriber, options) {\n if (!innerPublisherState) {\n const innerPublisherUnsubscribe = publisher.on(sourceChannelName, sourceMessage => {\n const transformResult = messageTransformer(sourceMessage);\n if (!transformResult) {\n return;\n }\n const [destinationChannelName, message] = transformResult;\n eventTarget.dispatchEvent(\n new CustomEvent(destinationChannelName, {\n detail: message,\n }),\n );\n });\n innerPublisherState = {\n dispose: innerPublisherUnsubscribe,\n numSubscribers: 0,\n };\n }\n innerPublisherState.numSubscribers++;\n const unsubscribe = demultiplexedDataPublisher.on(channelName, subscriber, options);\n let isActive = true;\n function handleUnsubscribe() {\n if (!isActive) {\n return;\n }\n isActive = false;\n options?.signal.removeEventListener('abort', handleUnsubscribe);\n innerPublisherState!.numSubscribers--;\n if (innerPublisherState!.numSubscribers === 0) {\n innerPublisherState!.dispose();\n innerPublisherState = undefined;\n }\n unsubscribe();\n }\n options?.signal.addEventListener('abort', handleUnsubscribe);\n return handleUnsubscribe;\n },\n };\n}\n","import { AbortController } from '@solana/event-target-impl';\n\nimport { DataPublisher } from './data-publisher';\n\ntype Config = Readonly<{\n /**\n * Triggering this abort signal will cause the store to stop updating and will disconnect it from\n * the underlying data publisher.\n */\n abortSignal: AbortSignal;\n /**\n * Messages from this channel of `dataPublisher` will be used to update the store's state.\n */\n dataChannelName: string;\n // FIXME: It would be nice to be able to constrain the type of `dataPublisher` to one that\n // definitely supports the `dataChannelName` and `errorChannelName` channels, and\n // furthermore publishes `TData` on the `dataChannelName` channel. This is more difficult\n // than it should be: https://tsplay.dev/NlZelW\n dataPublisher: DataPublisher;\n /**\n * Messages from this channel of `dataPublisher` will cause subscribers to be notified without\n * updating the state, so that they can respond to the error condition.\n */\n errorChannelName: string;\n}>;\n\n/**\n * A reactive store that holds the latest value published to a data channel and allows external\n * systems to subscribe to changes. Compatible with `useSyncExternalStore`, Svelte stores, Solid's\n * `from()`, and other reactive primitives that expect a `{ subscribe, getState }` contract.\n *\n * @example\n * ```ts\n * // React — throw error from snapshot function to surface via Error Boundary\n * const state = useSyncExternalStore(store.subscribe, () => {\n * if (store.getError()) throw store.getError();\n * return store.getState();\n * });\n *\n * // Vue — check error reactively in a composable\n * const data = shallowRef(store.getState());\n * const error = shallowRef(store.getError());\n * store.subscribe(() => {\n * data.value = store.getState();\n * error.value = store.getError();\n * });\n * ```\n *\n * @see {@link createReactiveStoreFromDataPublisher}\n */\nexport type ReactiveStore<T> = {\n /**\n * Returns the error published to the error channel, or `undefined` if no error has occurred.\n * Once set, the error is preserved — subsequent errors do not overwrite it.\n */\n getError(): unknown;\n /**\n * Returns the most recent value published to the data channel, or `undefined` if no\n * notification has arrived yet. On error, continues to return the last known value.\n */\n getState(): T | undefined;\n /**\n * Registers a callback to be called whenever the state changes or an error is received.\n * Returns an unsubscribe function. Safe to call multiple times.\n */\n subscribe(callback: () => void): () => void;\n};\n\n/**\n * Returns a {@link ReactiveStore} given a data publisher.\n *\n * The store will update its state with each message published to `dataChannelName` and notify all\n * subscribers. When a message is published to `errorChannelName`, subscribers are notified so they\n * can react to the error condition, but the last-known state is preserved. Triggering the abort\n * signal disconnects the store from the data publisher.\n *\n * Things to note:\n *\n * - `getState()` returns `undefined` until the first notification arrives.\n * - On error, `getState()` continues to return the last known value and `getError()` returns the\n * error. Only the first error is captured.\n * - The function returned by `subscribe` is idempotent — calling it multiple times is safe.\n *\n * @param config\n *\n * @example\n * ```ts\n * const store = createReactiveStoreFromDataPublisher({\n * abortSignal: AbortSignal.timeout(10_000),\n * dataChannelName: 'notification',\n * dataPublisher,\n * errorChannelName: 'error',\n * });\n * const unsubscribe = store.subscribe(() => {\n * console.log('State updated:', store.getState());\n * });\n * ```\n */\nexport function createReactiveStoreFromDataPublisher<TData>({\n abortSignal,\n dataChannelName,\n dataPublisher,\n errorChannelName,\n}: Config): ReactiveStore<TData> {\n let currentState: TData | undefined;\n let currentError: unknown;\n const subscribers = new Set<() => void>();\n\n const abortController = new AbortController();\n abortSignal.addEventListener('abort', () => abortController.abort(abortSignal.reason));\n\n dataPublisher.on(\n dataChannelName,\n data => {\n currentState = data as TData;\n subscribers.forEach(cb => cb());\n },\n { signal: abortController.signal },\n );\n dataPublisher.on(\n errorChannelName,\n err => {\n if (currentError !== undefined) return;\n currentError = err;\n // Abort the signal passed to dataPublisher, which stops the subscriptions\n abortController.abort(err);\n subscribers.forEach(cb => cb());\n },\n { signal: abortController.signal },\n );\n\n return {\n getError(): unknown {\n return currentError;\n },\n getState(): TData | undefined {\n return currentState;\n },\n subscribe(callback: () => void): () => void {\n subscribers.add(callback);\n return () => {\n subscribers.delete(callback);\n };\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../event-target-impl/src/index.browser.ts","../src/async-iterable.ts","../src/data-publisher.ts","../src/demultiplex.ts","../src/reactive-store.ts"],"names":["AbortController","EventTarget","SolanaError","SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING","SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE","SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED"],"mappings":";;;;;;;AAAO,IAAMA,IAAkB,UAAA,CAAW,eAAA;AAAnC,IACMC,IAAc,UAAA,CAAW,WAAA;;;AC6DtC,IAAI,oBAAA;AACJ,SAAS,wBAAA,GAA2B;AAGhC,EAAA,OAAO,MAAA;AAAA,IACH,OAAA,CAAA,GAAA,CAAA,QAAA,KAAyB,eACnB,sGAAA,GAEA;AAAA,GACV;AACJ;AAEA,IAAM,gBAAgB,MAAA,EAAO;AA4CtB,SAAS,oCAAA,CAA4C;AAAA,EACxD,WAAA;AAAA,EACA,eAAA;AAAA,EACA,aAAA;AAAA,EACA;AACJ,CA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O;AACH,QAAA,IAAI,eAAA,CAAgB,OAAO,OAAA,EAAS;AACpC,QAAA,YAAA,GAAe,EAAE,IAAA,EAAM,YAAA,CAAa,MAAM,KAAA,EAAO,GAAA,EAAK,QAAQ,OAAA,EAAQ;AACtE,QAAA,eAAA,CAAgB,MAAM,GAAG,CAAA;AACzB,QAAA,MAAA,EAAO;AAAA,MACX;AAAA,KACJ;AAAA,EACJ;AAEA,EAAA,OAAA,EAAQ;AAER,EAAA,OAAO;AAAA,IACH,QAAA,GAAoB;AAChB,MAAA,OAAO,YAAA,CAAa,KAAA;AAAA,IACxB,CAAA;AAAA,IACA,QAAA,GAA8B;AAC1B,MAAA,OAAO,YAAA,CAAa,IAAA;AAAA,IACxB,CAAA;AAAA,IACA,eAAA,GAAwC;AACpC,MAAA,OAAO,YAAA;AAAA,IACX,CAAA;AAAA,IACA,KAAA,GAAc;AACV,MAAA,IAAI,eAAA,CAAgB,OAAO,OAAA,EAAS;AACpC,MAAA,IAAI,YAAA,CAAa,WAAW,OAAA,EAAS;AACrC,MAAA,YAAA,GAAe,EAAE,IAAA,EAAM,YAAA,CAAa,MAAM,KAAA,EAAO,MAAA,EAAW,QAAQ,UAAA,EAAW;AAC/E,MAAA,MAAA,EAAO;AACP,MAAA,OAAA,EAAQ;AAAA,IACZ,CAAA;AAAA,IACA,UAAU,QAAA,EAAkC;AACxC,MAAA,WAAA,CAAY,IAAI,QAAQ,CAAA;AACxB,MAAA,OAAO,MAAM;AACT,QAAA,WAAA,CAAY,OAAO,QAAQ,CAAA;AAAA,MAC/B,CAAA;AAAA,IACJ;AAAA,GACJ;AACJ","file":"index.browser.cjs","sourcesContent":["export const AbortController = globalThis.AbortController;\nexport const EventTarget = globalThis.EventTarget;\n","import {\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\n\nimport { DataPublisher } from './data-publisher';\n\ntype Config = Readonly<{\n /**\n * Triggering this abort signal will cause all iterators spawned from this iterator to return\n * once they have published all queued messages.\n */\n abortSignal: AbortSignal;\n /**\n * Messages from this channel of `dataPublisher` will be the ones yielded through the iterators.\n *\n * Messages only begin to be queued after the first time an iterator begins to poll. Channel\n * messages published before that time will be dropped.\n */\n dataChannelName: string;\n // FIXME: It would be nice to be able to constrain the type of `dataPublisher` to one that\n // definitely supports the `dataChannelName` and `errorChannelName` channels, and\n // furthermore publishes `TData` on the `dataChannelName` channel. This is more difficult\n // than it should be: https://tsplay.dev/NlZelW\n dataPublisher: DataPublisher;\n /**\n * Messages from this channel of `dataPublisher` will be the ones thrown through the iterators.\n *\n * Any new iterators created after the first error is encountered will reject with that error\n * when polled.\n */\n errorChannelName: string;\n}>;\n\nconst enum PublishType {\n DATA,\n ERROR,\n}\n\ntype IteratorKey = symbol;\ntype IteratorState<TData> =\n | {\n __hasPolled: false;\n publishQueue: (\n | {\n __type: PublishType.DATA;\n data: TData;\n }\n | {\n __type: PublishType.ERROR;\n err: unknown;\n }\n )[];\n }\n | {\n __hasPolled: true;\n onData: (data: TData) => void;\n onError: Parameters<ConstructorParameters<typeof Promise>[0]>[1];\n };\n\nlet EXPLICIT_ABORT_TOKEN: symbol;\nfunction createExplicitAbortToken() {\n // This function is an annoying workaround to prevent `process.env.NODE_ENV` from appearing at\n // the top level of this module and thwarting an optimizing compiler's attempt to tree-shake.\n return Symbol(\n process.env.NODE_ENV !== \"production\"\n ? \"This symbol is thrown from a socket's iterator when the connection is explicitly \" +\n 'aborted by the user'\n : undefined,\n );\n}\n\nconst UNINITIALIZED = Symbol();\n\n/**\n * Returns an `AsyncIterable` given a data publisher.\n *\n * The iterable will produce iterators that vend messages published to `dataChannelName` and will\n * throw the first time a message is published to `errorChannelName`. Triggering the abort signal\n * will cause all iterators spawned from this iterator to return once they have published all queued\n * messages.\n *\n * Things to note:\n *\n * - If a message is published over a channel before the `AsyncIterator` attached to it has polled\n * for the next result, the message will be queued in memory.\n * - Messages only begin to be queued after the first time an iterator begins to poll. Channel\n * messages published before that time will be dropped.\n * - If there are messages in the queue and an error occurs, all queued messages will be vended to\n * the iterator before the error is thrown.\n * - If there are messages in the queue and the abort signal fires, all queued messages will be\n * vended to the iterator after which it will return.\n * - Any new iterators created after the first error is encountered will reject with that error when\n * polled.\n *\n * @param config\n *\n * @example\n * ```ts\n * const iterable = createAsyncIterableFromDataPublisher({\n * abortSignal: AbortSignal.timeout(10_000),\n * dataChannelName: 'message',\n * dataPublisher,\n * errorChannelName: 'error',\n * });\n * try {\n * for await (const message of iterable) {\n * console.log('Got message', message);\n * }\n * } catch (e) {\n * console.error('An error was published to the error channel', e);\n * } finally {\n * console.log(\"It's been 10 seconds; that's enough for now.\");\n * }\n * ```\n */\nexport function createAsyncIterableFromDataPublisher<TData>({\n abortSignal,\n dataChannelName,\n dataPublisher,\n errorChannelName,\n}: Config): AsyncIterable<TData> {\n const iteratorState: Map<IteratorKey, IteratorState<TData>> = new Map();\n function publishErrorToAllIterators(reason: unknown) {\n for (const [iteratorKey, state] of iteratorState.entries()) {\n if (state.__hasPolled) {\n iteratorState.delete(iteratorKey);\n state.onError(reason);\n } else {\n state.publishQueue.push({\n __type: PublishType.ERROR,\n err: reason,\n });\n }\n }\n }\n const abortController = new AbortController();\n abortSignal.addEventListener('abort', () => {\n abortController.abort();\n publishErrorToAllIterators((EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken()));\n });\n const options = { signal: abortController.signal } as const;\n let firstError: unknown = UNINITIALIZED;\n dataPublisher.on(\n errorChannelName,\n err => {\n if (firstError === UNINITIALIZED) {\n firstError = err;\n abortController.abort();\n publishErrorToAllIterators(err);\n }\n },\n options,\n );\n dataPublisher.on(\n dataChannelName,\n data => {\n iteratorState.forEach((state, iteratorKey) => {\n if (state.__hasPolled) {\n const { onData } = state;\n iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });\n onData(data as TData);\n } else {\n state.publishQueue.push({\n __type: PublishType.DATA,\n data: data as TData,\n });\n }\n });\n },\n options,\n );\n return {\n async *[Symbol.asyncIterator]() {\n if (abortSignal.aborted) {\n return;\n }\n if (firstError !== UNINITIALIZED) {\n throw firstError;\n }\n const iteratorKey = Symbol();\n iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });\n try {\n while (true) {\n const state = iteratorState.get(iteratorKey);\n if (!state) {\n // There should always be state by now.\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING);\n }\n if (state.__hasPolled) {\n // You should never be able to poll twice in a row.\n throw new SolanaError(\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,\n );\n }\n const publishQueue = state.publishQueue;\n try {\n if (publishQueue.length) {\n state.publishQueue = [];\n for (const item of publishQueue) {\n if (item.__type === PublishType.DATA) {\n yield item.data;\n } else {\n throw item.err;\n }\n }\n } else {\n yield await new Promise<TData>((resolve, reject) => {\n iteratorState.set(iteratorKey, {\n __hasPolled: true,\n onData: resolve,\n onError: reject,\n });\n });\n }\n } catch (e) {\n if (e === (EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken())) {\n return;\n } else {\n throw e;\n }\n }\n }\n } finally {\n iteratorState.delete(iteratorKey);\n }\n },\n };\n}\n","import { TypedEventEmitter, TypedEventTarget } from './event-emitter';\n\ntype UnsubscribeFn = () => void;\n\n/**\n * Represents an object with an `on` function that you can call to subscribe to certain data over a\n * named channel.\n *\n * @example\n * ```ts\n * let dataPublisher: DataPublisher<{ error: SolanaError }>;\n * dataPublisher.on('data', handleData); // ERROR. `data` is not a known channel name.\n * dataPublisher.on('error', e => {\n * console.error(e);\n * }); // OK.\n * ```\n */\nexport interface DataPublisher<TDataByChannelName extends Record<string, unknown> = Record<string, unknown>> {\n /**\n * Call this to subscribe to data over a named channel.\n *\n * @param channelName The name of the channel on which to subscribe for messages\n * @param subscriber The function to call when a message becomes available\n * @param options.signal An abort signal you can fire to unsubscribe\n *\n * @returns A function that you can call to unsubscribe\n */\n on<const TChannelName extends keyof TDataByChannelName>(\n channelName: TChannelName,\n subscriber: (data: TDataByChannelName[TChannelName]) => void,\n options?: { signal: AbortSignal },\n ): UnsubscribeFn;\n}\n\n/**\n * Returns an object with an `on` function that you can call to subscribe to certain data over a\n * named channel.\n *\n * The `on` function returns an unsubscribe function.\n *\n * @example\n * ```ts\n * const socketDataPublisher = getDataPublisherFromEventEmitter(new WebSocket('wss://api.devnet.solana.com'));\n * const unsubscribe = socketDataPublisher.on('message', message => {\n * if (JSON.parse(message.data).id === 42) {\n * console.log('Got response 42');\n * unsubscribe();\n * }\n * });\n * ```\n */\nexport function getDataPublisherFromEventEmitter<TEventMap extends Record<string, Event>>(\n eventEmitter: TypedEventEmitter<TEventMap> | TypedEventTarget<TEventMap>,\n): DataPublisher<{\n [TEventType in keyof TEventMap]: TEventMap[TEventType] extends CustomEvent ? TEventMap[TEventType]['detail'] : null;\n}> {\n return {\n on(channelName, subscriber, options) {\n function innerListener(ev: Event) {\n if (ev instanceof CustomEvent) {\n const data = (ev as CustomEvent<TEventMap[typeof channelName]>).detail;\n (subscriber as unknown as (data: TEventMap[typeof channelName]) => void)(data);\n } else {\n (subscriber as () => void)();\n }\n }\n eventEmitter.addEventListener(channelName, innerListener, options);\n return () => {\n eventEmitter.removeEventListener(channelName, innerListener);\n };\n },\n };\n}\n","import { EventTarget } from '@solana/event-target-impl';\n\nimport { DataPublisher, getDataPublisherFromEventEmitter } from './data-publisher';\n\n/**\n * Given a channel that carries messages for multiple subscribers on a single channel name, this\n * function returns a new {@link DataPublisher} that splits them into multiple channel names.\n *\n * @param messageTransformer A function that receives the message as the first argument, and returns\n * a tuple of the derived channel name and the message.\n *\n * @example\n * Imagine a channel that carries multiple notifications whose destination is contained within the\n * message itself.\n *\n * ```ts\n * const demuxedDataPublisher = demultiplexDataPublisher(channel, 'message', message => {\n * const destinationChannelName = `notification-for:${message.subscriberId}`;\n * return [destinationChannelName, message];\n * });\n * ```\n *\n * Now you can subscribe to _only_ the messages you are interested in, without having to subscribe\n * to the entire `'message'` channel and filter out the messages that are not for you.\n *\n * ```ts\n * demuxedDataPublisher.on(\n * 'notification-for:123',\n * message => {\n * console.log('Got a message for subscriber 123', message);\n * },\n * { signal: AbortSignal.timeout(5_000) },\n * );\n * ```\n */\nexport function demultiplexDataPublisher<\n TDataPublisher extends DataPublisher,\n const TChannelName extends Parameters<TDataPublisher['on']>[0],\n>(\n publisher: TDataPublisher,\n sourceChannelName: TChannelName,\n messageTransformer: (\n // FIXME: Deriving the type of the message from `TDataPublisher` and `TChannelName` would\n // help callers to constrain their transform functions.\n message: unknown,\n ) => [destinationChannelName: string, message: unknown] | void,\n): DataPublisher {\n let innerPublisherState:\n | {\n readonly dispose: () => void;\n numSubscribers: number;\n }\n | undefined;\n const eventTarget = new EventTarget();\n const demultiplexedDataPublisher = getDataPublisherFromEventEmitter(eventTarget);\n return {\n ...demultiplexedDataPublisher,\n on(channelName, subscriber, options) {\n if (!innerPublisherState) {\n const innerPublisherUnsubscribe = publisher.on(sourceChannelName, sourceMessage => {\n const transformResult = messageTransformer(sourceMessage);\n if (!transformResult) {\n return;\n }\n const [destinationChannelName, message] = transformResult;\n eventTarget.dispatchEvent(\n new CustomEvent(destinationChannelName, {\n detail: message,\n }),\n );\n });\n innerPublisherState = {\n dispose: innerPublisherUnsubscribe,\n numSubscribers: 0,\n };\n }\n innerPublisherState.numSubscribers++;\n const unsubscribe = demultiplexedDataPublisher.on(channelName, subscriber, options);\n let isActive = true;\n function handleUnsubscribe() {\n if (!isActive) {\n return;\n }\n isActive = false;\n options?.signal.removeEventListener('abort', handleUnsubscribe);\n innerPublisherState!.numSubscribers--;\n if (innerPublisherState!.numSubscribers === 0) {\n innerPublisherState!.dispose();\n innerPublisherState = undefined;\n }\n unsubscribe();\n }\n options?.signal.addEventListener('abort', handleUnsubscribe);\n return handleUnsubscribe;\n },\n };\n}\n","import { SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED, SolanaError } from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\n\nimport { DataPublisher } from './data-publisher';\n\ntype Config = Readonly<{\n /**\n * Triggering this abort signal will cause the store to stop updating and will disconnect it from\n * the underlying data publisher.\n */\n abortSignal: AbortSignal;\n /**\n * Messages from this channel of `dataPublisher` will be used to update the store's state.\n */\n dataChannelName: string;\n // FIXME: It would be nice to be able to constrain the type of `dataPublisher` to one that\n // definitely supports the `dataChannelName` and `errorChannelName` channels, and\n // furthermore publishes `TData` on the `dataChannelName` channel. This is more difficult\n // than it should be: https://tsplay.dev/NlZelW\n dataPublisher: DataPublisher;\n /**\n * Messages from this channel of `dataPublisher` will cause subscribers to be notified without\n * updating the state, so that they can respond to the error condition.\n */\n errorChannelName: string;\n}>;\n\ntype FactoryConfig = Readonly<{\n /**\n * Triggering this abort signal will cause the store to stop updating and will disconnect it from\n * any active {@link DataPublisher}. Subsequent calls to {@link ReactiveStore.retry | `retry()`}\n * are no-ops once this signal has fired.\n */\n abortSignal: AbortSignal;\n /**\n * An async factory that produces a fresh {@link DataPublisher} each time it is invoked. Called\n * once on construction and again on every {@link ReactiveStore.retry | `retry()`}. Rejections\n * surface as a store error.\n */\n createDataPublisher: () => Promise<DataPublisher>;\n /**\n * Messages from this channel of the produced `DataPublisher` will be used to update the store's\n * state.\n */\n dataChannelName: string;\n /**\n * Messages from this channel of the produced `DataPublisher` will transition the store to an\n * error state, preserving the last known value.\n */\n errorChannelName: string;\n}>;\n\n/**\n * The lifecycle state of a {@link ReactiveStore} as a single snapshot.\n *\n * - `loading`: the store is waiting for its first value. `data` is `undefined`.\n * - `loaded`: a value has been received and no error is active. `data` is defined.\n * - `error`: the stream failed. `data` is the last known value (or `undefined` if no value ever\n * arrived), and `error` holds the failure.\n * - `retrying`: a {@link ReactiveStore.retry | `retry()`} is in progress after a previous error.\n * `error` is cleared; `data` is preserved from before the failure if present.\n */\nexport type ReactiveState<T> =\n | { readonly data: T | undefined; readonly error: undefined; readonly status: 'retrying' }\n | { readonly data: T | undefined; readonly error: unknown; readonly status: 'error' }\n | { readonly data: T; readonly error: undefined; readonly status: 'loaded' }\n | { readonly data: undefined; readonly error: undefined; readonly status: 'loading' };\n\nconst LOADING_STATE: ReactiveState<never> = Object.freeze({\n data: undefined,\n error: undefined,\n status: 'loading',\n});\n\n/**\n * A reactive store that holds the latest value published to a data channel and allows external\n * systems to subscribe to changes. Compatible with `useSyncExternalStore`, Svelte stores, Solid's\n * `from()`, and other reactive primitives that expect a `{ subscribe, getUnifiedState }` contract.\n *\n * @example\n * ```ts\n * // React — the unified state snapshot has stable identity per update, making it suitable as\n * // the second argument to `useSyncExternalStore`.\n * const state = useSyncExternalStore(store.subscribe, store.getUnifiedState);\n * if (state.status === 'error') return <ErrorMessage error={state.error} onRetry={store.retry} />;\n * if (state.status === 'loading') return <Spinner />;\n * return <View data={state.data} />;\n * ```\n *\n * @see {@link createReactiveStoreFromDataPublisherFactory}\n */\nexport type ReactiveStore<T> = {\n /**\n * Returns the error published to the error channel, or `undefined` if no error has occurred.\n *\n * @deprecated Use {@link ReactiveStore.getUnifiedState | `getUnifiedState()`} instead. This\n * getter returns only the error field and cannot narrow the relationship between the current\n * value, error, and status.\n */\n getError(): unknown;\n /**\n * Returns the most recent value published to the data channel, or `undefined` if no\n * notification has arrived yet. On error, continues to return the last known value.\n *\n * @deprecated Use {@link ReactiveStore.getUnifiedState | `getUnifiedState()`} instead. This\n * getter returns only the value field and does not surface lifecycle status (e.g. `retrying`).\n */\n getState(): T | undefined;\n /**\n * Returns the current lifecycle snapshot: `{ data, error, status }`. The returned object has\n * stable identity between state changes, making it safe to pass directly as the\n * `getSnapshot` argument to React's `useSyncExternalStore`.\n *\n * @see {@link ReactiveState}\n */\n getUnifiedState(): ReactiveState<T>;\n /**\n * Re-opens the stream after an error. No-op when the store is not in the `error` state.\n */\n retry(): void;\n /**\n * Registers a callback to be called whenever the state changes or an error is received.\n * Returns an unsubscribe function. Safe to call multiple times.\n */\n subscribe(callback: () => void): () => void;\n};\n\n/**\n * Returns a {@link ReactiveStore} given a data publisher.\n *\n * The store will update its state with each message published to `dataChannelName` and notify all\n * subscribers. When a message is published to `errorChannelName`, subscribers are notified so they\n * can react to the error condition, but the last-known state is preserved. Triggering the abort\n * signal disconnects the store from the data publisher.\n *\n * Things to note:\n *\n * - `getUnifiedState()` starts in `status: 'loading'` until the first notification arrives.\n * - On error, `getUnifiedState().data` continues to return the last known value and `error` holds\n * the failure. Only the first error is captured.\n * - The function returned by `subscribe` is idempotent — calling it multiple times is safe.\n * - Because a `DataPublisher` instance cannot be restarted, {@link ReactiveStore.retry | `retry()`}\n * on the returned store throws a\n * {@link SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED | `SolanaError`}.\n *\n * @param config\n *\n * @deprecated Use {@link createReactiveStoreFromDataPublisherFactory} instead. That variant accepts\n * a factory function for the underlying {@link DataPublisher} and can therefore support\n * {@link ReactiveStore.retry | `retry()`}.\n */\nexport function createReactiveStoreFromDataPublisher<TData>({\n abortSignal,\n dataChannelName,\n dataPublisher,\n errorChannelName,\n}: Config): ReactiveStore<TData> {\n let currentState: ReactiveState<TData> = LOADING_STATE;\n const subscribers = new Set<() => void>();\n\n const abortController = new AbortController();\n abortSignal.addEventListener('abort', () => abortController.abort(abortSignal.reason));\n\n function notify() {\n subscribers.forEach(cb => cb());\n }\n\n dataPublisher.on(\n dataChannelName,\n data => {\n currentState = { data: data as TData, error: undefined, status: 'loaded' };\n notify();\n },\n { signal: abortController.signal },\n );\n dataPublisher.on(\n errorChannelName,\n err => {\n if (currentState.status === 'error') return;\n currentState = { data: currentState.data, error: err, status: 'error' };\n abortController.abort(err);\n notify();\n },\n { signal: abortController.signal },\n );\n\n return {\n getError(): unknown {\n return currentState.error;\n },\n getState(): TData | undefined {\n return currentState.data;\n },\n getUnifiedState(): ReactiveState<TData> {\n return currentState;\n },\n retry(): void {\n throw new SolanaError(SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED);\n },\n subscribe(callback: () => void): () => void {\n subscribers.add(callback);\n return () => {\n subscribers.delete(callback);\n };\n },\n };\n}\n\n/**\n * Returns a {@link ReactiveStore} that wires itself to a fresh {@link DataPublisher} on\n * construction and on every {@link ReactiveStore.retry | `retry()`}.\n *\n * Unlike {@link createReactiveStoreFromDataPublisher}, this variant accepts a `createDataPublisher`\n * factory rather than a ready-made publisher. That lets the store tear down a broken stream and\n * open a new one without losing subscribers or the last known value.\n *\n * Things to note:\n *\n * - `getUnifiedState()` starts in `status: 'loading'` until the first notification arrives.\n * - On error, the store transitions to `status: 'error'` preserving the last known value. Only the\n * first error per connection window is captured — a subsequent `retry()` resets that window.\n * - `retry()` is a no-op unless the store is currently in `status: 'error'`. When it fires, the\n * store transitions to `status: 'retrying'` (preserving stale data), invokes\n * `createDataPublisher()`, and wires up a fresh connection. If the factory rejects, the store\n * transitions to `status: 'error'` with the rejection reason.\n * - Triggering the caller's `abortSignal` disconnects the store permanently; subsequent `retry()`\n * calls are no-ops.\n *\n * @param config\n *\n * @example\n * ```ts\n * const store = createReactiveStoreFromDataPublisherFactory({\n * abortSignal,\n * async createDataPublisher() {\n * return getDataPublisherFromEventEmitter(new WebSocket(url));\n * },\n * dataChannelName: 'message',\n * errorChannelName: 'error',\n * });\n * const unsubscribe = store.subscribe(() => {\n * const snapshot = store.getUnifiedState();\n * if (snapshot.status === 'error') console.error('Connection failed:', snapshot.error);\n * else if (snapshot.status === 'loaded') console.log('Latest:', snapshot.data);\n * });\n * // Call `store.retry()` to recover after an error — e.g. from a user-triggered \"Retry\" button.\n * ```\n */\nexport function createReactiveStoreFromDataPublisherFactory<TData>({\n abortSignal,\n createDataPublisher,\n dataChannelName,\n errorChannelName,\n}: FactoryConfig): ReactiveStore<TData> {\n let currentState: ReactiveState<TData> = LOADING_STATE;\n const subscribers = new Set<() => void>();\n\n const outerController = new AbortController();\n abortSignal.addEventListener('abort', () => outerController.abort(abortSignal.reason));\n\n function notify() {\n subscribers.forEach(cb => cb());\n }\n\n function connect() {\n if (outerController.signal.aborted) return;\n // Inner signal is passed to data publisher\n const innerController = new AbortController();\n // Forward an abort from the outer signal to the inner one, so that when the caller aborts, we disconnect\n // Scope this forwarder to the inner signal so it's removed on reconnection\n // and we don't accumulate listeners on the outer signal across retries.\n const forwardAbort = () => innerController.abort(outerController.signal.reason);\n outerController.signal.addEventListener('abort', forwardAbort, { signal: innerController.signal });\n createDataPublisher().then(\n publisher => {\n if (innerController.signal.aborted) return;\n publisher.on(\n dataChannelName,\n data => {\n currentState = { data: data as TData, error: undefined, status: 'loaded' };\n notify();\n },\n { signal: innerController.signal },\n );\n publisher.on(\n errorChannelName,\n err => {\n if (currentState.status === 'error') return;\n currentState = { data: currentState.data, error: err, status: 'error' };\n innerController.abort(err);\n notify();\n },\n { signal: innerController.signal },\n );\n },\n err => {\n if (innerController.signal.aborted) return;\n currentState = { data: currentState.data, error: err, status: 'error' };\n innerController.abort(err);\n notify();\n },\n );\n }\n\n connect();\n\n return {\n getError(): unknown {\n return currentState.error;\n },\n getState(): TData | undefined {\n return currentState.data;\n },\n getUnifiedState(): ReactiveState<TData> {\n return currentState;\n },\n retry(): void {\n if (outerController.signal.aborted) return;\n if (currentState.status !== 'error') return;\n currentState = { data: currentState.data, error: undefined, status: 'retrying' };\n notify();\n connect();\n },\n subscribe(callback: () => void): () => void {\n subscribers.add(callback);\n return () => {\n subscribers.delete(callback);\n };\n },\n };\n}\n"]}
|
package/dist/index.browser.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { SolanaError, SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING, SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE } from '@solana/errors';
|
|
1
|
+
import { SolanaError, SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING, SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE, SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED } from '@solana/errors';
|
|
2
2
|
|
|
3
3
|
// src/async-iterable.ts
|
|
4
4
|
|
|
@@ -193,44 +193,129 @@ function demultiplexDataPublisher(publisher, sourceChannelName, messageTransform
|
|
|
193
193
|
}
|
|
194
194
|
};
|
|
195
195
|
}
|
|
196
|
-
|
|
197
|
-
|
|
196
|
+
var LOADING_STATE = Object.freeze({
|
|
197
|
+
data: void 0,
|
|
198
|
+
error: void 0,
|
|
199
|
+
status: "loading"
|
|
200
|
+
});
|
|
198
201
|
function createReactiveStoreFromDataPublisher({
|
|
199
202
|
abortSignal,
|
|
200
203
|
dataChannelName,
|
|
201
204
|
dataPublisher,
|
|
202
205
|
errorChannelName
|
|
203
206
|
}) {
|
|
204
|
-
let currentState;
|
|
205
|
-
let currentError;
|
|
207
|
+
let currentState = LOADING_STATE;
|
|
206
208
|
const subscribers = /* @__PURE__ */ new Set();
|
|
207
209
|
const abortController = new o();
|
|
208
210
|
abortSignal.addEventListener("abort", () => abortController.abort(abortSignal.reason));
|
|
211
|
+
function notify() {
|
|
212
|
+
subscribers.forEach((cb) => cb());
|
|
213
|
+
}
|
|
209
214
|
dataPublisher.on(
|
|
210
215
|
dataChannelName,
|
|
211
216
|
(data) => {
|
|
212
|
-
currentState = data;
|
|
213
|
-
|
|
217
|
+
currentState = { data, error: void 0, status: "loaded" };
|
|
218
|
+
notify();
|
|
214
219
|
},
|
|
215
220
|
{ signal: abortController.signal }
|
|
216
221
|
);
|
|
217
222
|
dataPublisher.on(
|
|
218
223
|
errorChannelName,
|
|
219
224
|
(err) => {
|
|
220
|
-
if (
|
|
221
|
-
|
|
225
|
+
if (currentState.status === "error") return;
|
|
226
|
+
currentState = { data: currentState.data, error: err, status: "error" };
|
|
222
227
|
abortController.abort(err);
|
|
223
|
-
|
|
228
|
+
notify();
|
|
224
229
|
},
|
|
225
230
|
{ signal: abortController.signal }
|
|
226
231
|
);
|
|
227
232
|
return {
|
|
228
233
|
getError() {
|
|
229
|
-
return
|
|
234
|
+
return currentState.error;
|
|
235
|
+
},
|
|
236
|
+
getState() {
|
|
237
|
+
return currentState.data;
|
|
238
|
+
},
|
|
239
|
+
getUnifiedState() {
|
|
240
|
+
return currentState;
|
|
241
|
+
},
|
|
242
|
+
retry() {
|
|
243
|
+
throw new SolanaError(SOLANA_ERROR__SUBSCRIBABLE__RETRY_NOT_SUPPORTED);
|
|
244
|
+
},
|
|
245
|
+
subscribe(callback) {
|
|
246
|
+
subscribers.add(callback);
|
|
247
|
+
return () => {
|
|
248
|
+
subscribers.delete(callback);
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
function createReactiveStoreFromDataPublisherFactory({
|
|
254
|
+
abortSignal,
|
|
255
|
+
createDataPublisher,
|
|
256
|
+
dataChannelName,
|
|
257
|
+
errorChannelName
|
|
258
|
+
}) {
|
|
259
|
+
let currentState = LOADING_STATE;
|
|
260
|
+
const subscribers = /* @__PURE__ */ new Set();
|
|
261
|
+
const outerController = new o();
|
|
262
|
+
abortSignal.addEventListener("abort", () => outerController.abort(abortSignal.reason));
|
|
263
|
+
function notify() {
|
|
264
|
+
subscribers.forEach((cb) => cb());
|
|
265
|
+
}
|
|
266
|
+
function connect() {
|
|
267
|
+
if (outerController.signal.aborted) return;
|
|
268
|
+
const innerController = new o();
|
|
269
|
+
const forwardAbort = () => innerController.abort(outerController.signal.reason);
|
|
270
|
+
outerController.signal.addEventListener("abort", forwardAbort, { signal: innerController.signal });
|
|
271
|
+
createDataPublisher().then(
|
|
272
|
+
(publisher) => {
|
|
273
|
+
if (innerController.signal.aborted) return;
|
|
274
|
+
publisher.on(
|
|
275
|
+
dataChannelName,
|
|
276
|
+
(data) => {
|
|
277
|
+
currentState = { data, error: void 0, status: "loaded" };
|
|
278
|
+
notify();
|
|
279
|
+
},
|
|
280
|
+
{ signal: innerController.signal }
|
|
281
|
+
);
|
|
282
|
+
publisher.on(
|
|
283
|
+
errorChannelName,
|
|
284
|
+
(err) => {
|
|
285
|
+
if (currentState.status === "error") return;
|
|
286
|
+
currentState = { data: currentState.data, error: err, status: "error" };
|
|
287
|
+
innerController.abort(err);
|
|
288
|
+
notify();
|
|
289
|
+
},
|
|
290
|
+
{ signal: innerController.signal }
|
|
291
|
+
);
|
|
292
|
+
},
|
|
293
|
+
(err) => {
|
|
294
|
+
if (innerController.signal.aborted) return;
|
|
295
|
+
currentState = { data: currentState.data, error: err, status: "error" };
|
|
296
|
+
innerController.abort(err);
|
|
297
|
+
notify();
|
|
298
|
+
}
|
|
299
|
+
);
|
|
300
|
+
}
|
|
301
|
+
connect();
|
|
302
|
+
return {
|
|
303
|
+
getError() {
|
|
304
|
+
return currentState.error;
|
|
230
305
|
},
|
|
231
306
|
getState() {
|
|
307
|
+
return currentState.data;
|
|
308
|
+
},
|
|
309
|
+
getUnifiedState() {
|
|
232
310
|
return currentState;
|
|
233
311
|
},
|
|
312
|
+
retry() {
|
|
313
|
+
if (outerController.signal.aborted) return;
|
|
314
|
+
if (currentState.status !== "error") return;
|
|
315
|
+
currentState = { data: currentState.data, error: void 0, status: "retrying" };
|
|
316
|
+
notify();
|
|
317
|
+
connect();
|
|
318
|
+
},
|
|
234
319
|
subscribe(callback) {
|
|
235
320
|
subscribers.add(callback);
|
|
236
321
|
return () => {
|
|
@@ -240,6 +325,6 @@ function createReactiveStoreFromDataPublisher({
|
|
|
240
325
|
};
|
|
241
326
|
}
|
|
242
327
|
|
|
243
|
-
export { createAsyncIterableFromDataPublisher, createReactiveStoreFromDataPublisher, demultiplexDataPublisher, getDataPublisherFromEventEmitter };
|
|
328
|
+
export { createAsyncIterableFromDataPublisher, createReactiveStoreFromDataPublisher, createReactiveStoreFromDataPublisherFactory, demultiplexDataPublisher, getDataPublisherFromEventEmitter };
|
|
244
329
|
//# sourceMappingURL=index.browser.mjs.map
|
|
245
330
|
//# sourceMappingURL=index.browser.mjs.map
|