@orpc/experimental-publisher 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 oRPC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,81 @@
1
+ <div align="center">
2
+ <image align="center" src="https://orpc.unnoq.com/logo.webp" width=280 alt="oRPC logo" />
3
+ </div>
4
+
5
+ <h1></h1>
6
+
7
+ <div align="center">
8
+ <a href="https://codecov.io/gh/unnoq/orpc">
9
+ <img alt="codecov" src="https://codecov.io/gh/unnoq/orpc/branch/main/graph/badge.svg">
10
+ </a>
11
+ <a href="https://www.npmjs.com/package/@orpc/experimental-publisher">
12
+ <img alt="weekly downloads" src="https://img.shields.io/npm/dw/%40orpc%2Fexperimental-publisher?logo=npm" />
13
+ </a>
14
+ <a href="https://github.com/unnoq/orpc/blob/main/LICENSE">
15
+ <img alt="MIT License" src="https://img.shields.io/github/license/unnoq/orpc?logo=open-source-initiative" />
16
+ </a>
17
+ <a href="https://discord.gg/TXEbwRBvQn">
18
+ <img alt="Discord" src="https://img.shields.io/discord/1308966753044398161?color=7389D8&label&logo=discord&logoColor=ffffff" />
19
+ </a>
20
+ <a href="https://deepwiki.com/unnoq/orpc">
21
+ <img src="https://deepwiki.com/badge.svg" alt="Ask DeepWiki">
22
+ </a>
23
+ </div>
24
+
25
+ <h3 align="center">Typesafe APIs Made Simple 🪄</h3>
26
+
27
+ **oRPC is a powerful combination of RPC and OpenAPI**, makes it easy to build APIs that are end-to-end type-safe and adhere to OpenAPI standards
28
+
29
+ ---
30
+
31
+ ## Highlights
32
+
33
+ - **🔗 End-to-End Type Safety**: Ensure type-safe inputs, outputs, and errors from client to server.
34
+ - **📘 First-Class OpenAPI**: Built-in support that fully adheres to the OpenAPI standard.
35
+ - **📝 Contract-First Development**: Optionally define your API contract before implementation.
36
+ - **🔍 First-Class OpenTelemetry**: Seamlessly integrate with OpenTelemetry for observability.
37
+ - **⚙️ Framework Integrations**: Seamlessly integrate with TanStack Query (React, Vue, Solid, Svelte, Angular), SWR, Pinia Colada, and more.
38
+ - **🚀 Server Actions**: Fully compatible with React Server Actions on Next.js, TanStack Start, and other platforms.
39
+ - **🔠 Standard Schema Support**: Works out of the box with Zod, Valibot, ArkType, and other schema validators.
40
+ - **🗃️ Native Types**: Supports native types like Date, File, Blob, BigInt, URL, and more.
41
+ - **⏱️ Lazy Router**: Enhance cold start times with our lazy routing feature.
42
+ - **📡 SSE & Streaming**: Enjoy full type-safe support for SSE and streaming.
43
+ - **🌍 Multi-Runtime Support**: Fast and lightweight on Cloudflare, Deno, Bun, Node.js, and beyond.
44
+ - **🔌 Extendability**: Easily extend functionality with plugins, middleware, and interceptors.
45
+
46
+ ## Documentation
47
+
48
+ You can find the full documentation [here](https://orpc.unnoq.com).
49
+
50
+ ## Packages
51
+
52
+ - [@orpc/contract](https://www.npmjs.com/package/@orpc/contract): Build your API contract.
53
+ - [@orpc/server](https://www.npmjs.com/package/@orpc/server): Build your API or implement API contract.
54
+ - [@orpc/client](https://www.npmjs.com/package/@orpc/client): Consume your API on the client with type-safety.
55
+ - [@orpc/openapi](https://www.npmjs.com/package/@orpc/openapi): Generate OpenAPI specs and handle OpenAPI requests.
56
+ - [@orpc/otel](https://www.npmjs.com/package/@orpc/otel): [OpenTelemetry](https://opentelemetry.io/) integration for observability.
57
+ - [@orpc/nest](https://www.npmjs.com/package/@orpc/nest): Deeply integrate oRPC with [NestJS](https://nestjs.com/).
58
+ - [@orpc/react](https://www.npmjs.com/package/@orpc/react): Utilities for integrating oRPC with React and React Server Actions.
59
+ - [@orpc/tanstack-query](https://www.npmjs.com/package/@orpc/tanstack-query): [TanStack Query](https://tanstack.com/query/latest) integration.
60
+ - [@orpc/experimental-react-swr](https://www.npmjs.com/package/@orpc/experimental-react-swr): [SWR](https://swr.vercel.app/) integration.
61
+ - [@orpc/vue-colada](https://www.npmjs.com/package/@orpc/vue-colada): Integration with [Pinia Colada](https://pinia-colada.esm.dev/).
62
+ - [@orpc/hey-api](https://www.npmjs.com/package/@orpc/hey-api): [Hey API](https://heyapi.dev/) integration.
63
+ - [@orpc/zod](https://www.npmjs.com/package/@orpc/zod): More schemas that [Zod](https://zod.dev/) doesn't support yet.
64
+ - [@orpc/valibot](https://www.npmjs.com/package/@orpc/valibot): OpenAPI spec generation from [Valibot](https://valibot.dev/).
65
+ - [@orpc/arktype](https://www.npmjs.com/package/@orpc/arktype): OpenAPI spec generation from [ArkType](https://arktype.io/).
66
+
67
+ ## `@orpc/experimental-publisher`
68
+
69
+ Event Publisher with multiple adapter support, resume support, and more.
70
+
71
+ ## Sponsors
72
+
73
+ <p align="center">
74
+ <a href="https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg">
75
+ <img src='https://cdn.jsdelivr.net/gh/unnoq/unnoq/sponsors.svg'/>
76
+ </a>
77
+ </p>
78
+
79
+ ## License
80
+
81
+ Distributed under the MIT License. See [LICENSE](https://github.com/unnoq/orpc/blob/main/LICENSE) for more information.
@@ -0,0 +1,76 @@
1
+ import { StandardRPCJsonSerializerOptions, StandardRPCJsonSerializer, StandardRPCJsonSerializedMetaItem } from '@orpc/client/standard';
2
+ import Redis from 'ioredis';
3
+ import { PublisherOptions, Publisher, PublisherSubscribeListenerOptions } from '../index.mjs';
4
+ import { getEventMeta } from '@orpc/standard-server';
5
+ import '@orpc/shared';
6
+
7
+ type SerializedPayload = {
8
+ json: object;
9
+ meta: StandardRPCJsonSerializedMetaItem[];
10
+ eventMeta: ReturnType<typeof getEventMeta>;
11
+ };
12
+ interface IORedisPublisherOptions extends PublisherOptions, StandardRPCJsonSerializerOptions {
13
+ /**
14
+ * Redis commander instance (used for execute short-lived commands)
15
+ */
16
+ commander: Redis;
17
+ /**
18
+ * redis listener instance (used for listening to events)
19
+ *
20
+ * @remark
21
+ * - `lazyConnect: true` option is supported
22
+ */
23
+ listener: Redis;
24
+ /**
25
+ * How long (in seconds) to retain events for replay.
26
+ *
27
+ * @remark
28
+ * This allows new subscribers to "catch up" on missed events using `lastEventId`.
29
+ * Note that event cleanup is deferred for performance reasons — meaning some
30
+ * expired events may still be available for a short period of time, and listeners
31
+ * might still receive them.
32
+ *
33
+ * @default NaN (disabled)
34
+ */
35
+ resumeRetentionSeconds?: number;
36
+ /**
37
+ * The prefix to use for Redis keys.
38
+ *
39
+ * @default orpc:publisher:
40
+ */
41
+ prefix?: string;
42
+ }
43
+ declare class IORedisPublisher<T extends Record<string, object>> extends Publisher<T> {
44
+ protected readonly commander: Redis;
45
+ protected readonly listener: Redis;
46
+ protected readonly prefix: string;
47
+ protected readonly serializer: StandardRPCJsonSerializer;
48
+ protected readonly retentionSeconds: number;
49
+ protected readonly listenerPromiseMap: Map<string, Promise<any>>;
50
+ protected readonly listenersMap: Map<string, Set<(payload: any) => void>>;
51
+ protected redisListener: ((channel: string, message: string) => void) | undefined;
52
+ protected get isResumeEnabled(): boolean;
53
+ /**
54
+ * The exactness of the `XTRIM` command.
55
+ *
56
+ * @internal
57
+ */
58
+ xtrimExactness: '~' | '=';
59
+ /**
60
+ * Useful for measuring memory usage.
61
+ *
62
+ * @internal
63
+ *
64
+ */
65
+ get size(): number;
66
+ constructor({ commander, listener, resumeRetentionSeconds, prefix, ...options }: IORedisPublisherOptions);
67
+ protected lastCleanupTimes: Map<string, number>;
68
+ publish<K extends keyof T & string>(event: K, payload: T[K]): Promise<void>;
69
+ protected subscribeListener<K extends keyof T & string>(event: K, originalListener: (payload: T[K]) => void, options?: PublisherSubscribeListenerOptions): Promise<() => Promise<void>>;
70
+ protected prefixKey(key: string): string;
71
+ protected serializePayload(payload: object): SerializedPayload;
72
+ protected deserializePayload(id: string | undefined, { json, meta, eventMeta }: SerializedPayload): any;
73
+ }
74
+
75
+ export { IORedisPublisher };
76
+ export type { IORedisPublisherOptions };
@@ -0,0 +1,76 @@
1
+ import { StandardRPCJsonSerializerOptions, StandardRPCJsonSerializer, StandardRPCJsonSerializedMetaItem } from '@orpc/client/standard';
2
+ import Redis from 'ioredis';
3
+ import { PublisherOptions, Publisher, PublisherSubscribeListenerOptions } from '../index.js';
4
+ import { getEventMeta } from '@orpc/standard-server';
5
+ import '@orpc/shared';
6
+
7
+ type SerializedPayload = {
8
+ json: object;
9
+ meta: StandardRPCJsonSerializedMetaItem[];
10
+ eventMeta: ReturnType<typeof getEventMeta>;
11
+ };
12
+ interface IORedisPublisherOptions extends PublisherOptions, StandardRPCJsonSerializerOptions {
13
+ /**
14
+ * Redis commander instance (used for execute short-lived commands)
15
+ */
16
+ commander: Redis;
17
+ /**
18
+ * redis listener instance (used for listening to events)
19
+ *
20
+ * @remark
21
+ * - `lazyConnect: true` option is supported
22
+ */
23
+ listener: Redis;
24
+ /**
25
+ * How long (in seconds) to retain events for replay.
26
+ *
27
+ * @remark
28
+ * This allows new subscribers to "catch up" on missed events using `lastEventId`.
29
+ * Note that event cleanup is deferred for performance reasons — meaning some
30
+ * expired events may still be available for a short period of time, and listeners
31
+ * might still receive them.
32
+ *
33
+ * @default NaN (disabled)
34
+ */
35
+ resumeRetentionSeconds?: number;
36
+ /**
37
+ * The prefix to use for Redis keys.
38
+ *
39
+ * @default orpc:publisher:
40
+ */
41
+ prefix?: string;
42
+ }
43
+ declare class IORedisPublisher<T extends Record<string, object>> extends Publisher<T> {
44
+ protected readonly commander: Redis;
45
+ protected readonly listener: Redis;
46
+ protected readonly prefix: string;
47
+ protected readonly serializer: StandardRPCJsonSerializer;
48
+ protected readonly retentionSeconds: number;
49
+ protected readonly listenerPromiseMap: Map<string, Promise<any>>;
50
+ protected readonly listenersMap: Map<string, Set<(payload: any) => void>>;
51
+ protected redisListener: ((channel: string, message: string) => void) | undefined;
52
+ protected get isResumeEnabled(): boolean;
53
+ /**
54
+ * The exactness of the `XTRIM` command.
55
+ *
56
+ * @internal
57
+ */
58
+ xtrimExactness: '~' | '=';
59
+ /**
60
+ * Useful for measuring memory usage.
61
+ *
62
+ * @internal
63
+ *
64
+ */
65
+ get size(): number;
66
+ constructor({ commander, listener, resumeRetentionSeconds, prefix, ...options }: IORedisPublisherOptions);
67
+ protected lastCleanupTimes: Map<string, number>;
68
+ publish<K extends keyof T & string>(event: K, payload: T[K]): Promise<void>;
69
+ protected subscribeListener<K extends keyof T & string>(event: K, originalListener: (payload: T[K]) => void, options?: PublisherSubscribeListenerOptions): Promise<() => Promise<void>>;
70
+ protected prefixKey(key: string): string;
71
+ protected serializePayload(payload: object): SerializedPayload;
72
+ protected deserializePayload(id: string | undefined, { json, meta, eventMeta }: SerializedPayload): any;
73
+ }
74
+
75
+ export { IORedisPublisher };
76
+ export type { IORedisPublisherOptions };
@@ -0,0 +1,171 @@
1
+ import { StandardRPCJsonSerializer } from '@orpc/client/standard';
2
+ import { stringifyJSON } from '@orpc/shared';
3
+ import { getEventMeta, withEventMeta } from '@orpc/standard-server';
4
+ import { P as Publisher } from '../shared/experimental-publisher.BOyYBkgn.mjs';
5
+
6
+ class IORedisPublisher extends Publisher {
7
+ commander;
8
+ listener;
9
+ prefix;
10
+ serializer;
11
+ retentionSeconds;
12
+ listenerPromiseMap = /* @__PURE__ */ new Map();
13
+ listenersMap = /* @__PURE__ */ new Map();
14
+ redisListener;
15
+ get isResumeEnabled() {
16
+ return Number.isFinite(this.retentionSeconds) && this.retentionSeconds > 0;
17
+ }
18
+ /**
19
+ * The exactness of the `XTRIM` command.
20
+ *
21
+ * @internal
22
+ */
23
+ xtrimExactness = "~";
24
+ /**
25
+ * Useful for measuring memory usage.
26
+ *
27
+ * @internal
28
+ *
29
+ */
30
+ get size() {
31
+ let size = this.redisListener ? 1 : 0;
32
+ for (const listeners of this.listenersMap) {
33
+ size += listeners[1].size || 1;
34
+ }
35
+ return size;
36
+ }
37
+ constructor({ commander, listener, resumeRetentionSeconds, prefix, ...options }) {
38
+ super(options);
39
+ this.commander = commander;
40
+ this.listener = listener;
41
+ this.prefix = prefix ?? "orpc:publisher:";
42
+ this.retentionSeconds = resumeRetentionSeconds ?? Number.NaN;
43
+ this.serializer = new StandardRPCJsonSerializer(options);
44
+ }
45
+ lastCleanupTimes = /* @__PURE__ */ new Map();
46
+ async publish(event, payload) {
47
+ const key = this.prefixKey(event);
48
+ const serialized = this.serializePayload(payload);
49
+ let id;
50
+ if (this.isResumeEnabled) {
51
+ const now = Date.now();
52
+ for (const [key2, lastCleanupTime] of this.lastCleanupTimes) {
53
+ if (lastCleanupTime + this.retentionSeconds * 1e3 < now) {
54
+ this.lastCleanupTimes.delete(key2);
55
+ }
56
+ }
57
+ if (!this.lastCleanupTimes.has(key)) {
58
+ this.lastCleanupTimes.set(key, now);
59
+ const result = await this.commander.multi().xadd(key, "*", "data", stringifyJSON(serialized)).xtrim(key, "MINID", this.xtrimExactness, `${now - this.retentionSeconds * 1e3}-0`).expire(key, this.retentionSeconds * 2).exec();
60
+ if (result) {
61
+ for (const [error] of result) {
62
+ if (error) {
63
+ throw error;
64
+ }
65
+ }
66
+ }
67
+ id = result[0][1];
68
+ } else {
69
+ const result = await this.commander.xadd(key, "*", "data", stringifyJSON(serialized));
70
+ id = result;
71
+ }
72
+ }
73
+ await this.commander.publish(key, stringifyJSON({ ...serialized, id }));
74
+ }
75
+ async subscribeListener(event, originalListener, options) {
76
+ const key = this.prefixKey(event);
77
+ const lastEventId = options?.lastEventId;
78
+ let pendingPayloads = [];
79
+ const resumePayloadIds = /* @__PURE__ */ new Set();
80
+ const listener = (payload) => {
81
+ if (pendingPayloads) {
82
+ pendingPayloads.push(payload);
83
+ return;
84
+ }
85
+ const payloadId = getEventMeta(payload)?.id;
86
+ if (payloadId !== void 0 && resumePayloadIds.has(payloadId)) {
87
+ return;
88
+ }
89
+ originalListener(payload);
90
+ };
91
+ if (!this.redisListener) {
92
+ this.redisListener = (channel, message) => {
93
+ try {
94
+ const listeners2 = this.listenersMap.get(channel);
95
+ if (listeners2) {
96
+ const { id, ...rest } = JSON.parse(message);
97
+ const payload = this.deserializePayload(id, rest);
98
+ for (const listener2 of listeners2) {
99
+ listener2(payload);
100
+ }
101
+ }
102
+ } catch {
103
+ }
104
+ };
105
+ this.listener.on("message", this.redisListener);
106
+ }
107
+ await this.listenerPromiseMap.get(key);
108
+ let listeners = this.listenersMap.get(key);
109
+ if (!listeners) {
110
+ try {
111
+ const promise = this.listener.subscribe(key);
112
+ this.listenerPromiseMap.set(key, promise);
113
+ await promise;
114
+ this.listenersMap.set(key, listeners = /* @__PURE__ */ new Set());
115
+ } finally {
116
+ this.listenerPromiseMap.delete(key);
117
+ }
118
+ }
119
+ listeners.add(listener);
120
+ void (async () => {
121
+ try {
122
+ if (this.isResumeEnabled && typeof lastEventId === "string") {
123
+ const results = await this.commander.xread("STREAMS", key, lastEventId);
124
+ if (results && results[0]) {
125
+ const [_, items] = results[0];
126
+ for (const [id, fields] of items) {
127
+ const serialized = fields[1];
128
+ const payload = this.deserializePayload(id, JSON.parse(serialized));
129
+ resumePayloadIds.add(id);
130
+ originalListener(payload);
131
+ }
132
+ }
133
+ }
134
+ } catch {
135
+ } finally {
136
+ const pending = pendingPayloads;
137
+ pendingPayloads = void 0;
138
+ for (const payload of pending) {
139
+ listener(payload);
140
+ }
141
+ }
142
+ })();
143
+ return async () => {
144
+ listeners.delete(listener);
145
+ if (listeners.size === 0) {
146
+ this.listenersMap.delete(key);
147
+ if (this.redisListener && this.listenersMap.size === 0) {
148
+ this.listener.off("message", this.redisListener);
149
+ this.redisListener = void 0;
150
+ }
151
+ await this.listener.unsubscribe(key);
152
+ }
153
+ };
154
+ }
155
+ prefixKey(key) {
156
+ return `${this.prefix}${key}`;
157
+ }
158
+ serializePayload(payload) {
159
+ const eventMeta = getEventMeta(payload);
160
+ const [json, meta] = this.serializer.serialize(payload);
161
+ return { json, meta, eventMeta };
162
+ }
163
+ deserializePayload(id, { json, meta, eventMeta }) {
164
+ return withEventMeta(
165
+ this.serializer.deserialize(json, meta),
166
+ id === void 0 ? { ...eventMeta } : { ...eventMeta, id }
167
+ );
168
+ }
169
+ }
170
+
171
+ export { IORedisPublisher };
@@ -0,0 +1,39 @@
1
+ import { PublisherOptions, Publisher, PublisherSubscribeListenerOptions } from '../index.mjs';
2
+ import '@orpc/shared';
3
+
4
+ interface MemoryPublisherOptions extends PublisherOptions {
5
+ /**
6
+ * How long (in seconds) to retain events for replay.
7
+ *
8
+ * @remark
9
+ * This allows new subscribers to "catch up" on missed events using `lastEventId`.
10
+ * Note that event cleanup is deferred for performance reasons — meaning some
11
+ * expired events may still be available for a short period of time, and listeners
12
+ * might still receive them.
13
+ *
14
+ * @default NaN (disabled)
15
+ */
16
+ resumeRetentionSeconds?: number;
17
+ }
18
+ declare class MemoryPublisher<T extends Record<string, object>> extends Publisher<T> {
19
+ private readonly eventPublisher;
20
+ private readonly idGenerator;
21
+ private readonly retentionSeconds;
22
+ private readonly events;
23
+ /**
24
+ * Useful for measuring memory usage.
25
+ *
26
+ * @internal
27
+ *
28
+ */
29
+ get size(): number;
30
+ protected get isResumeEnabled(): boolean;
31
+ constructor({ resumeRetentionSeconds, ...options }?: MemoryPublisherOptions);
32
+ publish<K extends keyof T & string>(event: K, payload: T[K]): Promise<void>;
33
+ protected subscribeListener<K extends keyof T & string>(event: K, listener: (payload: T[K]) => void, options?: PublisherSubscribeListenerOptions): Promise<() => Promise<void>>;
34
+ protected lastCleanupTime: number | null;
35
+ protected cleanup(): void;
36
+ }
37
+
38
+ export { MemoryPublisher };
39
+ export type { MemoryPublisherOptions };
@@ -0,0 +1,39 @@
1
+ import { PublisherOptions, Publisher, PublisherSubscribeListenerOptions } from '../index.js';
2
+ import '@orpc/shared';
3
+
4
+ interface MemoryPublisherOptions extends PublisherOptions {
5
+ /**
6
+ * How long (in seconds) to retain events for replay.
7
+ *
8
+ * @remark
9
+ * This allows new subscribers to "catch up" on missed events using `lastEventId`.
10
+ * Note that event cleanup is deferred for performance reasons — meaning some
11
+ * expired events may still be available for a short period of time, and listeners
12
+ * might still receive them.
13
+ *
14
+ * @default NaN (disabled)
15
+ */
16
+ resumeRetentionSeconds?: number;
17
+ }
18
+ declare class MemoryPublisher<T extends Record<string, object>> extends Publisher<T> {
19
+ private readonly eventPublisher;
20
+ private readonly idGenerator;
21
+ private readonly retentionSeconds;
22
+ private readonly events;
23
+ /**
24
+ * Useful for measuring memory usage.
25
+ *
26
+ * @internal
27
+ *
28
+ */
29
+ get size(): number;
30
+ protected get isResumeEnabled(): boolean;
31
+ constructor({ resumeRetentionSeconds, ...options }?: MemoryPublisherOptions);
32
+ publish<K extends keyof T & string>(event: K, payload: T[K]): Promise<void>;
33
+ protected subscribeListener<K extends keyof T & string>(event: K, listener: (payload: T[K]) => void, options?: PublisherSubscribeListenerOptions): Promise<() => Promise<void>>;
34
+ protected lastCleanupTime: number | null;
35
+ protected cleanup(): void;
36
+ }
37
+
38
+ export { MemoryPublisher };
39
+ export type { MemoryPublisherOptions };
@@ -0,0 +1,82 @@
1
+ import { EventPublisher, SequentialIdGenerator, compareSequentialIds } from '@orpc/shared';
2
+ import { withEventMeta, getEventMeta } from '@orpc/standard-server';
3
+ import { P as Publisher } from '../shared/experimental-publisher.BOyYBkgn.mjs';
4
+
5
+ class MemoryPublisher extends Publisher {
6
+ eventPublisher = new EventPublisher();
7
+ idGenerator = new SequentialIdGenerator();
8
+ retentionSeconds;
9
+ events = /* @__PURE__ */ new Map();
10
+ /**
11
+ * Useful for measuring memory usage.
12
+ *
13
+ * @internal
14
+ *
15
+ */
16
+ get size() {
17
+ let size = this.eventPublisher.size;
18
+ for (const events of this.events) {
19
+ size += events[1].length || 1;
20
+ }
21
+ return size;
22
+ }
23
+ get isResumeEnabled() {
24
+ return Number.isFinite(this.retentionSeconds) && this.retentionSeconds > 0;
25
+ }
26
+ constructor({ resumeRetentionSeconds, ...options } = {}) {
27
+ super(options);
28
+ this.retentionSeconds = resumeRetentionSeconds ?? Number.NaN;
29
+ }
30
+ async publish(event, payload) {
31
+ this.cleanup();
32
+ if (this.isResumeEnabled) {
33
+ const now = Date.now();
34
+ const expiresAt = now + this.retentionSeconds * 1e3;
35
+ let events = this.events.get(event);
36
+ if (!events) {
37
+ this.events.set(event, events = []);
38
+ }
39
+ payload = withEventMeta(payload, { ...getEventMeta(payload), id: this.idGenerator.generate() });
40
+ events.push({ expiresAt, payload });
41
+ }
42
+ this.eventPublisher.publish(event, payload);
43
+ }
44
+ async subscribeListener(event, listener, options) {
45
+ if (this.isResumeEnabled && typeof options?.lastEventId === "string") {
46
+ const events = this.events.get(event);
47
+ if (events) {
48
+ for (const { payload } of events) {
49
+ const id = getEventMeta(payload)?.id;
50
+ if (typeof id === "string" && compareSequentialIds(id, options.lastEventId) > 0) {
51
+ listener(payload);
52
+ }
53
+ }
54
+ }
55
+ }
56
+ const syncUnsub = this.eventPublisher.subscribe(event, listener);
57
+ return async () => {
58
+ syncUnsub();
59
+ };
60
+ }
61
+ lastCleanupTime = null;
62
+ cleanup() {
63
+ if (!this.isResumeEnabled) {
64
+ return;
65
+ }
66
+ const now = Date.now();
67
+ if (this.lastCleanupTime !== null && this.lastCleanupTime + this.retentionSeconds * 1e3 > now) {
68
+ return;
69
+ }
70
+ this.lastCleanupTime = now;
71
+ for (const [event, events] of this.events) {
72
+ const validEvents = events.filter((event2) => event2.expiresAt > now);
73
+ if (validEvents.length > 0) {
74
+ this.events.set(event, validEvents);
75
+ } else {
76
+ this.events.delete(event);
77
+ }
78
+ }
79
+ }
80
+ }
81
+
82
+ export { MemoryPublisher };
@@ -0,0 +1,64 @@
1
+ import { StandardRPCJsonSerializerOptions, StandardRPCJsonSerializer, StandardRPCJsonSerializedMetaItem } from '@orpc/client/standard';
2
+ import { Redis } from '@upstash/redis';
3
+ import { PublisherOptions, Publisher, PublisherSubscribeListenerOptions } from '../index.mjs';
4
+ import { getEventMeta } from '@orpc/standard-server';
5
+ import '@orpc/shared';
6
+
7
+ type SerializedPayload = {
8
+ json: object;
9
+ meta: StandardRPCJsonSerializedMetaItem[];
10
+ eventMeta: ReturnType<typeof getEventMeta>;
11
+ };
12
+ interface UpstashRedisPublisherOptions extends PublisherOptions, StandardRPCJsonSerializerOptions {
13
+ /**
14
+ * How long (in seconds) to retain events for replay.
15
+ *
16
+ * @remark
17
+ * This allows new subscribers to "catch up" on missed events using `lastEventId`.
18
+ * Note that event cleanup is deferred for performance reasons — meaning some
19
+ * expired events may still be available for a short period of time, and listeners
20
+ * might still receive them.
21
+ *
22
+ * @default NaN (disabled)
23
+ */
24
+ resumeRetentionSeconds?: number;
25
+ /**
26
+ * The prefix to use for Redis keys.
27
+ *
28
+ * @default orpc:publisher:
29
+ */
30
+ prefix?: string;
31
+ }
32
+ declare class UpstashRedisPublisher<T extends Record<string, object>> extends Publisher<T> {
33
+ protected readonly redis: Redis;
34
+ protected readonly prefix: string;
35
+ protected readonly serializer: StandardRPCJsonSerializer;
36
+ protected readonly retentionSeconds: number;
37
+ protected readonly listenersMap: Map<string, Set<(payload: any) => void>>;
38
+ protected readonly subscriptionPromiseMap: Map<string, Promise<void>>;
39
+ protected readonly subscriptionsMap: Map<string, any>;
40
+ protected get isResumeEnabled(): boolean;
41
+ /**
42
+ * The exactness of the `XTRIM` command.
43
+ *
44
+ * @internal
45
+ */
46
+ xtrimExactness: '~' | '=';
47
+ /**
48
+ * Useful for measuring memory usage.
49
+ *
50
+ * @internal
51
+ *
52
+ */
53
+ get size(): number;
54
+ constructor(redis: Redis, { resumeRetentionSeconds, prefix, ...options }?: UpstashRedisPublisherOptions);
55
+ protected lastCleanupTimes: Map<string, number>;
56
+ publish<K extends keyof T & string>(event: K, payload: T[K]): Promise<void>;
57
+ protected subscribeListener<K extends keyof T & string>(event: K, originalListener: (payload: T[K]) => void, options?: PublisherSubscribeListenerOptions): Promise<() => Promise<void>>;
58
+ protected prefixKey(key: string): string;
59
+ protected serializePayload(payload: object): SerializedPayload;
60
+ protected deserializePayload(id: string | undefined, { json, meta, eventMeta }: SerializedPayload): any;
61
+ }
62
+
63
+ export { UpstashRedisPublisher };
64
+ export type { UpstashRedisPublisherOptions };
@@ -0,0 +1,64 @@
1
+ import { StandardRPCJsonSerializerOptions, StandardRPCJsonSerializer, StandardRPCJsonSerializedMetaItem } from '@orpc/client/standard';
2
+ import { Redis } from '@upstash/redis';
3
+ import { PublisherOptions, Publisher, PublisherSubscribeListenerOptions } from '../index.js';
4
+ import { getEventMeta } from '@orpc/standard-server';
5
+ import '@orpc/shared';
6
+
7
+ type SerializedPayload = {
8
+ json: object;
9
+ meta: StandardRPCJsonSerializedMetaItem[];
10
+ eventMeta: ReturnType<typeof getEventMeta>;
11
+ };
12
+ interface UpstashRedisPublisherOptions extends PublisherOptions, StandardRPCJsonSerializerOptions {
13
+ /**
14
+ * How long (in seconds) to retain events for replay.
15
+ *
16
+ * @remark
17
+ * This allows new subscribers to "catch up" on missed events using `lastEventId`.
18
+ * Note that event cleanup is deferred for performance reasons — meaning some
19
+ * expired events may still be available for a short period of time, and listeners
20
+ * might still receive them.
21
+ *
22
+ * @default NaN (disabled)
23
+ */
24
+ resumeRetentionSeconds?: number;
25
+ /**
26
+ * The prefix to use for Redis keys.
27
+ *
28
+ * @default orpc:publisher:
29
+ */
30
+ prefix?: string;
31
+ }
32
+ declare class UpstashRedisPublisher<T extends Record<string, object>> extends Publisher<T> {
33
+ protected readonly redis: Redis;
34
+ protected readonly prefix: string;
35
+ protected readonly serializer: StandardRPCJsonSerializer;
36
+ protected readonly retentionSeconds: number;
37
+ protected readonly listenersMap: Map<string, Set<(payload: any) => void>>;
38
+ protected readonly subscriptionPromiseMap: Map<string, Promise<void>>;
39
+ protected readonly subscriptionsMap: Map<string, any>;
40
+ protected get isResumeEnabled(): boolean;
41
+ /**
42
+ * The exactness of the `XTRIM` command.
43
+ *
44
+ * @internal
45
+ */
46
+ xtrimExactness: '~' | '=';
47
+ /**
48
+ * Useful for measuring memory usage.
49
+ *
50
+ * @internal
51
+ *
52
+ */
53
+ get size(): number;
54
+ constructor(redis: Redis, { resumeRetentionSeconds, prefix, ...options }?: UpstashRedisPublisherOptions);
55
+ protected lastCleanupTimes: Map<string, number>;
56
+ publish<K extends keyof T & string>(event: K, payload: T[K]): Promise<void>;
57
+ protected subscribeListener<K extends keyof T & string>(event: K, originalListener: (payload: T[K]) => void, options?: PublisherSubscribeListenerOptions): Promise<() => Promise<void>>;
58
+ protected prefixKey(key: string): string;
59
+ protected serializePayload(payload: object): SerializedPayload;
60
+ protected deserializePayload(id: string | undefined, { json, meta, eventMeta }: SerializedPayload): any;
61
+ }
62
+
63
+ export { UpstashRedisPublisher };
64
+ export type { UpstashRedisPublisherOptions };
@@ -0,0 +1,175 @@
1
+ import { StandardRPCJsonSerializer } from '@orpc/client/standard';
2
+ import { getEventMeta, withEventMeta } from '@orpc/standard-server';
3
+ import { P as Publisher } from '../shared/experimental-publisher.BOyYBkgn.mjs';
4
+ import '@orpc/shared';
5
+
6
+ class UpstashRedisPublisher extends Publisher {
7
+ constructor(redis, { resumeRetentionSeconds, prefix, ...options } = {}) {
8
+ super(options);
9
+ this.redis = redis;
10
+ this.prefix = prefix ?? "orpc:publisher:";
11
+ this.retentionSeconds = resumeRetentionSeconds ?? Number.NaN;
12
+ this.serializer = new StandardRPCJsonSerializer(options);
13
+ }
14
+ prefix;
15
+ serializer;
16
+ retentionSeconds;
17
+ listenersMap = /* @__PURE__ */ new Map();
18
+ subscriptionPromiseMap = /* @__PURE__ */ new Map();
19
+ subscriptionsMap = /* @__PURE__ */ new Map();
20
+ // Upstash subscription objects
21
+ get isResumeEnabled() {
22
+ return Number.isFinite(this.retentionSeconds) && this.retentionSeconds > 0;
23
+ }
24
+ /**
25
+ * The exactness of the `XTRIM` command.
26
+ *
27
+ * @internal
28
+ */
29
+ xtrimExactness = "~";
30
+ /**
31
+ * Useful for measuring memory usage.
32
+ *
33
+ * @internal
34
+ *
35
+ */
36
+ get size() {
37
+ let size = 0;
38
+ for (const listeners of this.listenersMap) {
39
+ size += listeners[1].size || 1;
40
+ }
41
+ return size;
42
+ }
43
+ lastCleanupTimes = /* @__PURE__ */ new Map();
44
+ async publish(event, payload) {
45
+ const key = this.prefixKey(event);
46
+ const serialized = this.serializePayload(payload);
47
+ let id;
48
+ if (this.isResumeEnabled) {
49
+ const now = Date.now();
50
+ for (const [key2, lastCleanupTime] of this.lastCleanupTimes) {
51
+ if (lastCleanupTime + this.retentionSeconds * 1e3 < now) {
52
+ this.lastCleanupTimes.delete(key2);
53
+ }
54
+ }
55
+ if (!this.lastCleanupTimes.has(key)) {
56
+ this.lastCleanupTimes.set(key, now);
57
+ const results = await this.redis.multi().xadd(key, "*", { data: serialized }).xtrim(key, { strategy: "MINID", exactness: this.xtrimExactness, threshold: `${now - this.retentionSeconds * 1e3}-0` }).expire(key, this.retentionSeconds * 2).exec();
58
+ id = results[0];
59
+ } else {
60
+ const result = await this.redis.xadd(key, "*", { data: serialized });
61
+ id = result;
62
+ }
63
+ }
64
+ await this.redis.publish(key, { ...serialized, id });
65
+ }
66
+ async subscribeListener(event, originalListener, options) {
67
+ const key = this.prefixKey(event);
68
+ const lastEventId = options?.lastEventId;
69
+ let pendingPayloads = [];
70
+ const resumePayloadIds = /* @__PURE__ */ new Set();
71
+ const listener = (payload) => {
72
+ if (pendingPayloads) {
73
+ pendingPayloads.push(payload);
74
+ return;
75
+ }
76
+ const payloadId = getEventMeta(payload)?.id;
77
+ if (payloadId !== void 0 && resumePayloadIds.has(payloadId)) {
78
+ return;
79
+ }
80
+ originalListener(payload);
81
+ };
82
+ await this.subscriptionPromiseMap.get(key);
83
+ let subscription = this.subscriptionsMap.get(key);
84
+ if (!subscription) {
85
+ subscription = this.redis.subscribe(key);
86
+ subscription.on("message", (event2) => {
87
+ try {
88
+ const listeners2 = this.listenersMap.get(event2.channel);
89
+ if (listeners2) {
90
+ const { id, ...rest } = event2.message;
91
+ const payload = this.deserializePayload(id, rest);
92
+ for (const listener2 of listeners2) {
93
+ listener2(payload);
94
+ }
95
+ }
96
+ } catch {
97
+ }
98
+ });
99
+ let resolvePromise;
100
+ let rejectPromise;
101
+ const promise = new Promise((resolve, reject) => {
102
+ resolvePromise = resolve;
103
+ rejectPromise = reject;
104
+ });
105
+ subscription.on("error", (error) => {
106
+ rejectPromise(error);
107
+ });
108
+ subscription.on("subscribe", () => {
109
+ resolvePromise();
110
+ });
111
+ try {
112
+ this.subscriptionPromiseMap.set(key, promise);
113
+ await promise;
114
+ this.subscriptionsMap.set(key, subscription);
115
+ } finally {
116
+ this.subscriptionPromiseMap.delete(key);
117
+ }
118
+ }
119
+ let listeners = this.listenersMap.get(key);
120
+ if (!listeners) {
121
+ this.listenersMap.set(key, listeners = /* @__PURE__ */ new Set());
122
+ }
123
+ listeners.add(listener);
124
+ void (async () => {
125
+ try {
126
+ if (this.isResumeEnabled && typeof lastEventId === "string") {
127
+ const results = await this.redis.xread(key, lastEventId);
128
+ if (results && results[0]) {
129
+ const [_, items] = results[0];
130
+ for (const [id, fields] of items) {
131
+ const serialized = fields[1];
132
+ const payload = this.deserializePayload(id, serialized);
133
+ resumePayloadIds.add(id);
134
+ originalListener(payload);
135
+ }
136
+ }
137
+ }
138
+ } catch {
139
+ } finally {
140
+ const pending = pendingPayloads;
141
+ pendingPayloads = void 0;
142
+ for (const payload of pending) {
143
+ listener(payload);
144
+ }
145
+ }
146
+ })();
147
+ return async () => {
148
+ listeners.delete(listener);
149
+ if (listeners.size === 0) {
150
+ this.listenersMap.delete(key);
151
+ const subscription2 = this.subscriptionsMap.get(key);
152
+ if (subscription2) {
153
+ this.subscriptionsMap.delete(key);
154
+ await subscription2.unsubscribe();
155
+ }
156
+ }
157
+ };
158
+ }
159
+ prefixKey(key) {
160
+ return `${this.prefix}${key}`;
161
+ }
162
+ serializePayload(payload) {
163
+ const eventMeta = getEventMeta(payload);
164
+ const [json, meta] = this.serializer.serialize(payload);
165
+ return { json, meta, eventMeta };
166
+ }
167
+ deserializePayload(id, { json, meta, eventMeta }) {
168
+ return withEventMeta(
169
+ this.serializer.deserialize(json, meta),
170
+ id === void 0 ? { ...eventMeta } : { ...eventMeta, id }
171
+ );
172
+ }
173
+ }
174
+
175
+ export { UpstashRedisPublisher };
@@ -0,0 +1,76 @@
1
+ import { AsyncIteratorClass } from '@orpc/shared';
2
+
3
+ interface PublisherOptions {
4
+ /**
5
+ * Maximum number of events to buffer for async iterator subscribers.
6
+ *
7
+ * If the buffer exceeds this limit, the oldest event is dropped.
8
+ * This prevents unbounded memory growth if consumers process events slowly.
9
+ *
10
+ * Set to:
11
+ * - `0`: Disable buffering. Events must be consumed before the next one arrives.
12
+ * - `1`: Only keep the latest event. Useful for real-time updates where only the most recent value matters.
13
+ * - `Infinity`: Keep all events. Ensures no data loss, but may lead to high memory usage.
14
+ *
15
+ * @default 100
16
+ */
17
+ maxBufferedEvents?: number;
18
+ }
19
+ interface PublisherSubscribeListenerOptions {
20
+ /**
21
+ * Resume from a specific event ID
22
+ */
23
+ lastEventId?: string | undefined;
24
+ }
25
+ interface PublisherSubscribeIteratorOptions extends PublisherSubscribeListenerOptions, PublisherOptions {
26
+ /**
27
+ * Abort signal, automatically unsubscribes on abort
28
+ */
29
+ signal?: AbortSignal | undefined | null;
30
+ }
31
+ declare abstract class Publisher<T extends Record<string, object>> {
32
+ private readonly maxBufferedEvents;
33
+ constructor(options?: PublisherOptions);
34
+ /**
35
+ * Publish an event to subscribers
36
+ */
37
+ abstract publish<K extends keyof T & string>(event: K, payload: T[K]): Promise<void>;
38
+ /**
39
+ * Subscribes to a specific event using a callback function.
40
+ * Returns an unsubscribe function to remove the listener.
41
+ *
42
+ * @remarks
43
+ * This method should be protected to avoid conflicts with `subscribe` method
44
+ */
45
+ protected abstract subscribeListener<K extends keyof T & string>(event: K, listener: (payload: T[K]) => void, options?: PublisherSubscribeListenerOptions): Promise<() => Promise<void>>;
46
+ /**
47
+ * Subscribes to a specific event using a callback function.
48
+ * Returns an unsubscribe function to remove the listener.
49
+ *
50
+ * @example
51
+ * ```ts
52
+ * const unsubscribe = publisher.subscribe('event', (payload) => {
53
+ * console.log(payload)
54
+ * })
55
+ *
56
+ * // Later
57
+ * unsubscribe()
58
+ * ```
59
+ */
60
+ subscribe<K extends keyof T & string>(event: K, listener: (payload: T[K]) => void, options?: PublisherSubscribeListenerOptions): Promise<() => Promise<void>>;
61
+ /**
62
+ * Subscribes to a specific event using an async iterator.
63
+ * Useful for `for await...of` loops with optional buffering and abort support.
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * for await (const payload of publisher.subscribe('event', { signal })) {
68
+ * console.log(payload)
69
+ * }
70
+ * ```
71
+ */
72
+ subscribe<K extends keyof T & string>(event: K, options?: PublisherSubscribeIteratorOptions): AsyncIteratorClass<T[K], void, void>;
73
+ }
74
+
75
+ export { Publisher };
76
+ export type { PublisherOptions, PublisherSubscribeIteratorOptions, PublisherSubscribeListenerOptions };
@@ -0,0 +1,76 @@
1
+ import { AsyncIteratorClass } from '@orpc/shared';
2
+
3
+ interface PublisherOptions {
4
+ /**
5
+ * Maximum number of events to buffer for async iterator subscribers.
6
+ *
7
+ * If the buffer exceeds this limit, the oldest event is dropped.
8
+ * This prevents unbounded memory growth if consumers process events slowly.
9
+ *
10
+ * Set to:
11
+ * - `0`: Disable buffering. Events must be consumed before the next one arrives.
12
+ * - `1`: Only keep the latest event. Useful for real-time updates where only the most recent value matters.
13
+ * - `Infinity`: Keep all events. Ensures no data loss, but may lead to high memory usage.
14
+ *
15
+ * @default 100
16
+ */
17
+ maxBufferedEvents?: number;
18
+ }
19
+ interface PublisherSubscribeListenerOptions {
20
+ /**
21
+ * Resume from a specific event ID
22
+ */
23
+ lastEventId?: string | undefined;
24
+ }
25
+ interface PublisherSubscribeIteratorOptions extends PublisherSubscribeListenerOptions, PublisherOptions {
26
+ /**
27
+ * Abort signal, automatically unsubscribes on abort
28
+ */
29
+ signal?: AbortSignal | undefined | null;
30
+ }
31
+ declare abstract class Publisher<T extends Record<string, object>> {
32
+ private readonly maxBufferedEvents;
33
+ constructor(options?: PublisherOptions);
34
+ /**
35
+ * Publish an event to subscribers
36
+ */
37
+ abstract publish<K extends keyof T & string>(event: K, payload: T[K]): Promise<void>;
38
+ /**
39
+ * Subscribes to a specific event using a callback function.
40
+ * Returns an unsubscribe function to remove the listener.
41
+ *
42
+ * @remarks
43
+ * This method should be protected to avoid conflicts with `subscribe` method
44
+ */
45
+ protected abstract subscribeListener<K extends keyof T & string>(event: K, listener: (payload: T[K]) => void, options?: PublisherSubscribeListenerOptions): Promise<() => Promise<void>>;
46
+ /**
47
+ * Subscribes to a specific event using a callback function.
48
+ * Returns an unsubscribe function to remove the listener.
49
+ *
50
+ * @example
51
+ * ```ts
52
+ * const unsubscribe = publisher.subscribe('event', (payload) => {
53
+ * console.log(payload)
54
+ * })
55
+ *
56
+ * // Later
57
+ * unsubscribe()
58
+ * ```
59
+ */
60
+ subscribe<K extends keyof T & string>(event: K, listener: (payload: T[K]) => void, options?: PublisherSubscribeListenerOptions): Promise<() => Promise<void>>;
61
+ /**
62
+ * Subscribes to a specific event using an async iterator.
63
+ * Useful for `for await...of` loops with optional buffering and abort support.
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * for await (const payload of publisher.subscribe('event', { signal })) {
68
+ * console.log(payload)
69
+ * }
70
+ * ```
71
+ */
72
+ subscribe<K extends keyof T & string>(event: K, options?: PublisherSubscribeIteratorOptions): AsyncIteratorClass<T[K], void, void>;
73
+ }
74
+
75
+ export { Publisher };
76
+ export type { PublisherOptions, PublisherSubscribeIteratorOptions, PublisherSubscribeListenerOptions };
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ export { P as Publisher } from './shared/experimental-publisher.BOyYBkgn.mjs';
2
+ import '@orpc/shared';
@@ -0,0 +1,57 @@
1
+ import { AsyncIteratorClass } from '@orpc/shared';
2
+
3
+ class Publisher {
4
+ maxBufferedEvents;
5
+ constructor(options = {}) {
6
+ this.maxBufferedEvents = options.maxBufferedEvents ?? 100;
7
+ }
8
+ subscribe(event, listenerOrOptions, listenerOptions) {
9
+ if (typeof listenerOrOptions === "function") {
10
+ return this.subscribeListener(event, listenerOrOptions, listenerOptions);
11
+ }
12
+ const signal = listenerOrOptions?.signal;
13
+ const maxBufferedEvents = listenerOrOptions?.maxBufferedEvents ?? this.maxBufferedEvents;
14
+ signal?.throwIfAborted();
15
+ const bufferedEvents = [];
16
+ const pullResolvers = [];
17
+ const unsubscribePromise = this.subscribe(event, (payload) => {
18
+ const resolver = pullResolvers.shift();
19
+ if (resolver) {
20
+ resolver[0]({ done: false, value: payload });
21
+ } else {
22
+ bufferedEvents.push(payload);
23
+ if (bufferedEvents.length > maxBufferedEvents) {
24
+ bufferedEvents.shift();
25
+ }
26
+ }
27
+ });
28
+ const abortListener = (event2) => {
29
+ pullResolvers.forEach((resolver) => resolver[1](event2.target.reason));
30
+ pullResolvers.length = 0;
31
+ bufferedEvents.length = 0;
32
+ unsubscribePromise.then((unsubscribe) => unsubscribe()).catch(() => {
33
+ });
34
+ };
35
+ signal?.addEventListener("abort", abortListener, { once: true });
36
+ return new AsyncIteratorClass(async () => {
37
+ await unsubscribePromise;
38
+ if (signal?.aborted) {
39
+ throw signal.reason;
40
+ }
41
+ if (bufferedEvents.length > 0) {
42
+ return { done: false, value: bufferedEvents.shift() };
43
+ }
44
+ return new Promise((resolve, reject) => {
45
+ pullResolvers.push([resolve, reject]);
46
+ });
47
+ }, async () => {
48
+ signal?.removeEventListener("abort", abortListener);
49
+ pullResolvers.forEach((resolver) => resolver[0]({ done: true, value: void 0 }));
50
+ pullResolvers.length = 0;
51
+ bufferedEvents.length = 0;
52
+ await unsubscribePromise.then((unsubscribe) => unsubscribe());
53
+ });
54
+ }
55
+ }
56
+
57
+ export { Publisher as P };
package/package.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "name": "@orpc/experimental-publisher",
3
+ "type": "module",
4
+ "version": "0.0.0",
5
+ "license": "MIT",
6
+ "homepage": "https://orpc.unnoq.com",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/unnoq/orpc.git",
10
+ "directory": "packages/publisher"
11
+ },
12
+ "keywords": [
13
+ "unnoq",
14
+ "orpc"
15
+ ],
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.mts",
19
+ "import": "./dist/index.mjs",
20
+ "default": "./dist/index.mjs"
21
+ },
22
+ "./memory": {
23
+ "types": "./dist/adapters/memory.d.mts",
24
+ "import": "./dist/adapters/memory.mjs",
25
+ "default": "./dist/adapters/memory.mjs"
26
+ },
27
+ "./ioredis": {
28
+ "types": "./dist/adapters/ioredis.d.mts",
29
+ "import": "./dist/adapters/ioredis.mjs",
30
+ "default": "./dist/adapters/ioredis.mjs"
31
+ },
32
+ "./upstash-redis": {
33
+ "types": "./dist/adapters/upstash-redis.d.mts",
34
+ "import": "./dist/adapters/upstash-redis.mjs",
35
+ "default": "./dist/adapters/upstash-redis.mjs"
36
+ }
37
+ },
38
+ "files": [
39
+ "dist"
40
+ ],
41
+ "peerDependencies": {
42
+ "@upstash/redis": ">=1.35.6",
43
+ "ioredis": ">=5.8.1"
44
+ },
45
+ "peerDependenciesMeta": {
46
+ "@upstash/redis": {
47
+ "optional": true
48
+ },
49
+ "ioredis": {
50
+ "optional": true
51
+ }
52
+ },
53
+ "dependencies": {
54
+ "@orpc/client": "1.9.4",
55
+ "@orpc/shared": "1.9.4",
56
+ "@orpc/standard-server": "1.9.4"
57
+ },
58
+ "devDependencies": {
59
+ "@upstash/redis": "^1.35.6",
60
+ "ioredis": "^5.8.1"
61
+ },
62
+ "scripts": {
63
+ "build": "unbuild",
64
+ "build:watch": "pnpm run build --watch",
65
+ "type:check": "tsc -b"
66
+ }
67
+ }