@discordjs/brokers 0.2.0-dev.1665706585-bf9aa18.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 +191 -0
- package/README.md +120 -0
- package/dist/index.d.ts +224 -0
- package/dist/index.js +233 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +211 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +82 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2022 Noel Buechler
|
|
179
|
+
Copyright 2022 Charlotte Cristea
|
|
180
|
+
|
|
181
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
182
|
+
you may not use this file except in compliance with the License.
|
|
183
|
+
You may obtain a copy of the License at
|
|
184
|
+
|
|
185
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
186
|
+
|
|
187
|
+
Unless required by applicable law or agreed to in writing, software
|
|
188
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
189
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
190
|
+
See the License for the specific language governing permissions and
|
|
191
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
<br />
|
|
3
|
+
<p>
|
|
4
|
+
<a href="https://discord.js.org"><img src="https://discord.js.org/static/logo.svg" width="546" alt="discord.js" /></a>
|
|
5
|
+
</p>
|
|
6
|
+
<br />
|
|
7
|
+
<p>
|
|
8
|
+
<a href="https://discord.gg/djs"><img src="https://img.shields.io/discord/222078108977594368?color=5865F2&logo=discord&logoColor=white" alt="Discord server" /></a>
|
|
9
|
+
<a href="https://www.npmjs.com/package/@discordjs/brokers"><img src="https://img.shields.io/npm/v/@discordjs/brokers.svg?maxAge=3600" alt="npm version" /></a>
|
|
10
|
+
<a href="https://www.npmjs.com/package/@discordjs/brokers"><img src="https://img.shields.io/npm/dt/@discordjs/brokers.svg?maxAge=3600" alt="npm downloads" /></a>
|
|
11
|
+
<a href="https://github.com/discordjs/discord.js/actions"><img src="https://github.com/discordjs/discord.js/actions/workflows/test.yml/badge.svg" alt="Build status" /></a>
|
|
12
|
+
<a href="https://codecov.io/gh/discordjs/discord.js" ><img src="https://codecov.io/gh/discordjs/discord.js/branch/main/graph/badge.svg?precision=2&flag=brokers" alt="Code coverage" /></a>
|
|
13
|
+
</p>
|
|
14
|
+
<p>
|
|
15
|
+
<a href="https://vercel.com/?utm_source=discordjs&utm_campaign=oss"><img src="https://raw.githubusercontent.com/discordjs/discord.js/main/.github/powered-by-vercel.svg" alt="Vercel" /></a>
|
|
16
|
+
</p>
|
|
17
|
+
</div>
|
|
18
|
+
|
|
19
|
+
## About
|
|
20
|
+
|
|
21
|
+
`@discordjs/brokers` is a powerful set of message brokers
|
|
22
|
+
|
|
23
|
+
## Installation
|
|
24
|
+
|
|
25
|
+
**Node.js 16.9.0 or newer is required.**
|
|
26
|
+
|
|
27
|
+
```sh-session
|
|
28
|
+
npm install @discordjs/brokers
|
|
29
|
+
yarn add @discordjs/brokers
|
|
30
|
+
pnpm add @discordjs/brokers
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Example usage
|
|
34
|
+
|
|
35
|
+
### pub sub
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
// publisher.js
|
|
39
|
+
import { PubSubRedisBroker } from '@discordjs/brokers';
|
|
40
|
+
import Redis from 'ioredis';
|
|
41
|
+
|
|
42
|
+
const broker = new PubSubRedisBroker({ redisClient: new Redis() });
|
|
43
|
+
|
|
44
|
+
await broker.publish('test', 'Hello World!');
|
|
45
|
+
await broker.destroy();
|
|
46
|
+
|
|
47
|
+
// subscriber.js
|
|
48
|
+
import { PubSubRedisBroker } from '@discordjs/brokers';
|
|
49
|
+
import Redis from 'ioredis';
|
|
50
|
+
|
|
51
|
+
const broker = new PubSubRedisBroker({ redisClient: new Redis() });
|
|
52
|
+
broker.on('test', ({ data, ack }) => {
|
|
53
|
+
console.log(data);
|
|
54
|
+
void ack();
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
await broker.subscribe('subscribers', ['test']);
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### RPC
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
// caller.js
|
|
64
|
+
import { RPCRedisBroker } from '@discordjs/brokers';
|
|
65
|
+
import Redis from 'ioredis';
|
|
66
|
+
|
|
67
|
+
const broker = new RPCRedisBroker({ redisClient: new Redis() });
|
|
68
|
+
|
|
69
|
+
console.log(await broker.call('testcall', 'Hello World!'));
|
|
70
|
+
await broker.destroy();
|
|
71
|
+
|
|
72
|
+
// responder.js
|
|
73
|
+
import { RPCRedisBroker } from '@discordjs/brokers';
|
|
74
|
+
import Redis from 'ioredis';
|
|
75
|
+
|
|
76
|
+
const broker = new RPCRedisBroker({ redisClient: new Redis() });
|
|
77
|
+
broker.on('testcall', ({ data, ack, reply }) => {
|
|
78
|
+
console.log('responder', data);
|
|
79
|
+
void ack();
|
|
80
|
+
void reply(`Echo: ${data}`);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
await broker.subscribe('responders', ['testcall']);
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Links
|
|
87
|
+
|
|
88
|
+
- [Website][website] ([source][website-source])
|
|
89
|
+
- [Documentation][documentation]
|
|
90
|
+
- [Guide][guide] ([source][guide-source])
|
|
91
|
+
See also the [Update Guide][guide-update], including updated and removed items in the library.
|
|
92
|
+
- [discord.js Discord server][discord]
|
|
93
|
+
- [Discord API Discord server][discord-api]
|
|
94
|
+
- [GitHub][source]
|
|
95
|
+
- [npm][npm]
|
|
96
|
+
- [Related libraries][related-libs]
|
|
97
|
+
|
|
98
|
+
## Contributing
|
|
99
|
+
|
|
100
|
+
Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the
|
|
101
|
+
[documentation][documentation].
|
|
102
|
+
See [the contribution guide][contributing] if you'd like to submit a PR.
|
|
103
|
+
|
|
104
|
+
## Help
|
|
105
|
+
|
|
106
|
+
If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle
|
|
107
|
+
nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord].
|
|
108
|
+
|
|
109
|
+
[website]: https://discord.js.org/
|
|
110
|
+
[website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website
|
|
111
|
+
[documentation]: https://discord.js.org/#/docs/brokers
|
|
112
|
+
[guide]: https://discordjs.guide/
|
|
113
|
+
[guide-source]: https://github.com/discordjs/guide
|
|
114
|
+
[guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html
|
|
115
|
+
[discord]: https://discord.gg/djs
|
|
116
|
+
[discord-api]: https://discord.gg/discord-api
|
|
117
|
+
[source]: https://github.com/discordjs/discord.js/tree/main/packages/brokers
|
|
118
|
+
[npm]: https://www.npmjs.com/package/@discordjs/brokers
|
|
119
|
+
[related-libs]: https://discord.com/developers/docs/topics/community-resources#libraries
|
|
120
|
+
[contributing]: https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer';
|
|
2
|
+
import { AsyncEventEmitter } from '@vladfrangu/async_event_emitter';
|
|
3
|
+
import { Redis } from 'ioredis';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Base options for a broker implementation
|
|
7
|
+
*/
|
|
8
|
+
interface BaseBrokerOptions {
|
|
9
|
+
/**
|
|
10
|
+
* How long to block for messages when polling
|
|
11
|
+
*/
|
|
12
|
+
blockTimeout?: number;
|
|
13
|
+
/**
|
|
14
|
+
* Function to use for decoding messages
|
|
15
|
+
*/
|
|
16
|
+
decode?: (data: Buffer) => unknown;
|
|
17
|
+
/**
|
|
18
|
+
* Function to use for encoding messages
|
|
19
|
+
*/
|
|
20
|
+
encode?: (data: unknown) => Buffer;
|
|
21
|
+
/**
|
|
22
|
+
* Max number of messages to poll at once
|
|
23
|
+
*/
|
|
24
|
+
maxChunk?: number;
|
|
25
|
+
/**
|
|
26
|
+
* Unique consumer name. See: https://redis.io/commands/xreadgroup/
|
|
27
|
+
*/
|
|
28
|
+
name?: string;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Default broker options
|
|
32
|
+
*/
|
|
33
|
+
declare const DefaultBrokerOptions: Required<BaseBrokerOptions>;
|
|
34
|
+
declare type ToEventMap<TRecord extends Record<string, any>, TResponses extends Record<keyof TRecord, any> | undefined = undefined> = {
|
|
35
|
+
[TKey in keyof TRecord]: [
|
|
36
|
+
event: TResponses extends Record<keyof TRecord, any> ? {
|
|
37
|
+
ack(): Promise<void>;
|
|
38
|
+
reply(data: TResponses[TKey]): Promise<void>;
|
|
39
|
+
} : {
|
|
40
|
+
ack(): Promise<void>;
|
|
41
|
+
} & {
|
|
42
|
+
data: TRecord[TKey];
|
|
43
|
+
}
|
|
44
|
+
];
|
|
45
|
+
} & {
|
|
46
|
+
[K: string]: any;
|
|
47
|
+
};
|
|
48
|
+
interface IBaseBroker<TEvents extends Record<string, any>> {
|
|
49
|
+
/**
|
|
50
|
+
* Subscribes to the given events, grouping them by the given group name
|
|
51
|
+
*/
|
|
52
|
+
subscribe(group: string, events: (keyof TEvents)[]): Promise<void>;
|
|
53
|
+
/**
|
|
54
|
+
* Unsubscribes from the given events - it's required to pass the same group name as when subscribing for proper cleanup
|
|
55
|
+
*/
|
|
56
|
+
unsubscribe(group: string, events: (keyof TEvents)[]): Promise<void>;
|
|
57
|
+
}
|
|
58
|
+
interface IPubSubBroker<TEvents extends Record<string, any>> extends IBaseBroker<TEvents>, AsyncEventEmitter<ToEventMap<TEvents>> {
|
|
59
|
+
/**
|
|
60
|
+
* Publishes an event
|
|
61
|
+
*/
|
|
62
|
+
publish<T extends keyof TEvents>(event: T, data: TEvents[T]): Promise<void>;
|
|
63
|
+
}
|
|
64
|
+
interface IRPCBroker<TEvents extends Record<string, any>, TResponses extends Record<keyof TEvents, any>> extends IBaseBroker<TEvents>, AsyncEventEmitter<ToEventMap<TEvents, TResponses>> {
|
|
65
|
+
/**
|
|
66
|
+
* Makes an RPC call
|
|
67
|
+
*/
|
|
68
|
+
call<T extends keyof TEvents>(event: T, data: TEvents[T], timeoutDuration?: number): Promise<TResponses[T]>;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
declare module 'ioredis' {
|
|
72
|
+
interface Redis {
|
|
73
|
+
xreadgroupBuffer(...args: (Buffer | string)[]): Promise<[Buffer, [Buffer, Buffer[]][]][] | null>;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Options specific for a Redis broker
|
|
78
|
+
*/
|
|
79
|
+
interface RedisBrokerOptions extends BaseBrokerOptions {
|
|
80
|
+
/**
|
|
81
|
+
* The Redis client to use
|
|
82
|
+
*/
|
|
83
|
+
redisClient: Redis;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Helper class with shared Redis logic
|
|
87
|
+
*/
|
|
88
|
+
declare abstract class BaseRedisBroker<TEvents extends Record<string, any>> extends AsyncEventEmitter<ToEventMap<TEvents>> implements IBaseBroker<TEvents> {
|
|
89
|
+
/**
|
|
90
|
+
* Used for Redis queues, see the 3rd argument taken by {@link https://redis.io/commands/xadd | xadd }
|
|
91
|
+
*/
|
|
92
|
+
static readonly STREAM_DATA_KEY = "data";
|
|
93
|
+
/**
|
|
94
|
+
* Options this broker is using
|
|
95
|
+
*/
|
|
96
|
+
protected readonly options: Required<RedisBrokerOptions>;
|
|
97
|
+
/**
|
|
98
|
+
* Events this broker has subscribed to
|
|
99
|
+
*/
|
|
100
|
+
protected readonly subscribedEvents: Set<string>;
|
|
101
|
+
/**
|
|
102
|
+
* Internal copy of the Redis client being used to read incoming payloads
|
|
103
|
+
*/
|
|
104
|
+
protected readonly streamReadClient: Redis;
|
|
105
|
+
/**
|
|
106
|
+
* Whether this broker is currently polling events
|
|
107
|
+
*/
|
|
108
|
+
protected listening: boolean;
|
|
109
|
+
constructor(options: RedisBrokerOptions);
|
|
110
|
+
/**
|
|
111
|
+
* {@inheritDoc IBaseBroker.subscribe}
|
|
112
|
+
*/
|
|
113
|
+
subscribe(group: string, events: (keyof TEvents)[]): Promise<void>;
|
|
114
|
+
/**
|
|
115
|
+
* {@inheritDoc IBaseBroker.unsubscribe}
|
|
116
|
+
*/
|
|
117
|
+
unsubscribe(group: string, events: (keyof TEvents)[]): Promise<void>;
|
|
118
|
+
/**
|
|
119
|
+
* Begins polling for events, firing them to {@link BaseRedisBroker.listen}
|
|
120
|
+
*/
|
|
121
|
+
protected listen(group: string): Promise<void>;
|
|
122
|
+
/**
|
|
123
|
+
* Destroys the broker, closing all connections
|
|
124
|
+
*/
|
|
125
|
+
destroy(): Promise<void>;
|
|
126
|
+
/**
|
|
127
|
+
* Handles an incoming Redis event
|
|
128
|
+
*/
|
|
129
|
+
protected abstract emitEvent(id: Buffer, group: string, event: string, data: unknown): unknown;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* PubSub broker powered by Redis
|
|
134
|
+
*
|
|
135
|
+
* @example
|
|
136
|
+
* ```ts
|
|
137
|
+
* // publisher.js
|
|
138
|
+
* import { PubSubRedisBroker } from '@discordjs/brokers';
|
|
139
|
+
* import Redis from 'ioredis';
|
|
140
|
+
*
|
|
141
|
+
* const broker = new PubSubRedisBroker({ redisClient: new Redis() });
|
|
142
|
+
*
|
|
143
|
+
* await broker.publish('test', 'Hello World!');
|
|
144
|
+
* await broker.destroy();
|
|
145
|
+
*
|
|
146
|
+
* // subscriber.js
|
|
147
|
+
* import { PubSubRedisBroker } from '@discordjs/brokers';
|
|
148
|
+
* import Redis from 'ioredis';
|
|
149
|
+
*
|
|
150
|
+
* const broker = new PubSubRedisBroker({ redisClient: new Redis() });
|
|
151
|
+
* broker.on('test', ({ data, ack }) => {
|
|
152
|
+
* console.log(data);
|
|
153
|
+
* void ack();
|
|
154
|
+
* });
|
|
155
|
+
*
|
|
156
|
+
* await broker.subscribe('subscribers', ['test']);
|
|
157
|
+
* ```
|
|
158
|
+
*/
|
|
159
|
+
declare class PubSubRedisBroker<TEvents extends Record<string, any>> extends BaseRedisBroker<TEvents> implements IPubSubBroker<TEvents> {
|
|
160
|
+
/**
|
|
161
|
+
* {@inheritDoc IPubSubBroker.publish}
|
|
162
|
+
*/
|
|
163
|
+
publish<T extends keyof TEvents>(event: T, data: TEvents[T]): Promise<void>;
|
|
164
|
+
protected emitEvent(id: Buffer, group: string, event: string, data: unknown): void;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
interface InternalPromise {
|
|
168
|
+
reject(error: any): void;
|
|
169
|
+
resolve(data: any): void;
|
|
170
|
+
timeout: NodeJS.Timeout;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Options specific for an RPC Redis broker
|
|
174
|
+
*/
|
|
175
|
+
interface RPCRedisBrokerOptions extends RedisBrokerOptions {
|
|
176
|
+
timeout?: number;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Default values used for the {@link RPCRedisBrokerOptions}
|
|
180
|
+
*/
|
|
181
|
+
declare const DefaultRPCRedisBrokerOptions: Required<Omit<RPCRedisBrokerOptions, 'redisClient'>>;
|
|
182
|
+
/**
|
|
183
|
+
* RPC broker powered by Redis
|
|
184
|
+
*
|
|
185
|
+
* @example
|
|
186
|
+
* ```ts
|
|
187
|
+
* // caller.js
|
|
188
|
+
* import { RPCRedisBroker } from '@discordjs/brokers';
|
|
189
|
+
* import Redis from 'ioredis';
|
|
190
|
+
*
|
|
191
|
+
* const broker = new RPCRedisBroker({ redisClient: new Redis() });
|
|
192
|
+
*
|
|
193
|
+
* console.log(await broker.call('testcall', 'Hello World!'));
|
|
194
|
+
* await broker.destroy();
|
|
195
|
+
*
|
|
196
|
+
* // responder.js
|
|
197
|
+
* import { RPCRedisBroker } from '@discordjs/brokers';
|
|
198
|
+
* import Redis from 'ioredis';
|
|
199
|
+
*
|
|
200
|
+
* const broker = new RPCRedisBroker({ redisClient: new Redis() });
|
|
201
|
+
* broker.on('testcall', ({ data, ack, reply }) => {
|
|
202
|
+
* console.log('responder', data);
|
|
203
|
+
* void ack();
|
|
204
|
+
* void reply(`Echo: ${data}`);
|
|
205
|
+
* });
|
|
206
|
+
*
|
|
207
|
+
* await broker.subscribe('responders', ['testcall']);
|
|
208
|
+
* ```
|
|
209
|
+
*/
|
|
210
|
+
declare class RPCRedisBroker<TEvents extends Record<string, any>, TResponses extends Record<keyof TEvents, any>> extends BaseRedisBroker<TEvents> implements IRPCBroker<TEvents, TResponses> {
|
|
211
|
+
/**
|
|
212
|
+
* Options this broker is using
|
|
213
|
+
*/
|
|
214
|
+
protected readonly options: Required<RPCRedisBrokerOptions>;
|
|
215
|
+
protected readonly promises: Map<string, InternalPromise>;
|
|
216
|
+
constructor(options: RPCRedisBrokerOptions);
|
|
217
|
+
/**
|
|
218
|
+
* {@inheritDoc IRPCBroker.call}
|
|
219
|
+
*/
|
|
220
|
+
call<T extends keyof TEvents>(event: T, data: TEvents[T], timeoutDuration?: number): Promise<TResponses[T]>;
|
|
221
|
+
protected emitEvent(id: Buffer, group: string, event: string, data: unknown): void;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export { BaseBrokerOptions, BaseRedisBroker, DefaultBrokerOptions, DefaultRPCRedisBrokerOptions, IBaseBroker, IPubSubBroker, IRPCBroker, PubSubRedisBroker, RPCRedisBroker, RPCRedisBrokerOptions, RedisBrokerOptions, ToEventMap };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
7
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
21
|
+
var __publicField = (obj, key, value) => {
|
|
22
|
+
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
23
|
+
return value;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
// src/index.ts
|
|
27
|
+
var src_exports = {};
|
|
28
|
+
__export(src_exports, {
|
|
29
|
+
BaseRedisBroker: () => BaseRedisBroker,
|
|
30
|
+
DefaultBrokerOptions: () => DefaultBrokerOptions,
|
|
31
|
+
DefaultRPCRedisBrokerOptions: () => DefaultRPCRedisBrokerOptions,
|
|
32
|
+
PubSubRedisBroker: () => PubSubRedisBroker,
|
|
33
|
+
RPCRedisBroker: () => RPCRedisBroker
|
|
34
|
+
});
|
|
35
|
+
module.exports = __toCommonJS(src_exports);
|
|
36
|
+
|
|
37
|
+
// src/brokers/redis/BaseRedis.ts
|
|
38
|
+
var import_node_fs = require("fs");
|
|
39
|
+
var import_node_path = require("path");
|
|
40
|
+
var import_async_event_emitter = require("@vladfrangu/async_event_emitter");
|
|
41
|
+
var import_ioredis = require("ioredis");
|
|
42
|
+
|
|
43
|
+
// src/brokers/Broker.ts
|
|
44
|
+
var import_node_buffer = require("buffer");
|
|
45
|
+
var import_node_crypto = require("crypto");
|
|
46
|
+
var import_msgpack = require("@msgpack/msgpack");
|
|
47
|
+
var DefaultBrokerOptions = {
|
|
48
|
+
name: (0, import_node_crypto.randomBytes)(20).toString("hex"),
|
|
49
|
+
maxChunk: 10,
|
|
50
|
+
blockTimeout: 5e3,
|
|
51
|
+
encode: (data) => {
|
|
52
|
+
const encoded = (0, import_msgpack.encode)(data);
|
|
53
|
+
return import_node_buffer.Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength);
|
|
54
|
+
},
|
|
55
|
+
decode: (data) => (0, import_msgpack.decode)(data)
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
// src/brokers/redis/BaseRedis.ts
|
|
59
|
+
var BaseRedisBroker = class extends import_async_event_emitter.AsyncEventEmitter {
|
|
60
|
+
options;
|
|
61
|
+
subscribedEvents = /* @__PURE__ */ new Set();
|
|
62
|
+
streamReadClient;
|
|
63
|
+
listening = false;
|
|
64
|
+
constructor(options) {
|
|
65
|
+
super();
|
|
66
|
+
this.options = { ...DefaultBrokerOptions, ...options };
|
|
67
|
+
options.redisClient.defineCommand("xcleangroup", {
|
|
68
|
+
numberOfKeys: 1,
|
|
69
|
+
lua: (0, import_node_fs.readFileSync)((0, import_node_path.resolve)(__dirname, "..", "..", "..", "scripts", "xcleangroup.lua"), "utf8")
|
|
70
|
+
});
|
|
71
|
+
this.streamReadClient = options.redisClient.duplicate();
|
|
72
|
+
}
|
|
73
|
+
async subscribe(group, events) {
|
|
74
|
+
await Promise.all(
|
|
75
|
+
events.map(async (event) => {
|
|
76
|
+
this.subscribedEvents.add(event);
|
|
77
|
+
try {
|
|
78
|
+
return await this.options.redisClient.xgroup("CREATE", event, group, 0, "MKSTREAM");
|
|
79
|
+
} catch (error) {
|
|
80
|
+
if (!(error instanceof import_ioredis.ReplyError)) {
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
})
|
|
85
|
+
);
|
|
86
|
+
void this.listen(group);
|
|
87
|
+
}
|
|
88
|
+
async unsubscribe(group, events) {
|
|
89
|
+
const commands = Array.from({ length: events.length * 2 });
|
|
90
|
+
for (let idx = 0; idx < commands.length; idx += 2) {
|
|
91
|
+
const event = events[idx / 2];
|
|
92
|
+
commands[idx] = ["xgroup", "delconsumer", event, group, this.options.name];
|
|
93
|
+
commands[idx + 1] = ["xcleangroup", event, group];
|
|
94
|
+
}
|
|
95
|
+
await this.options.redisClient.pipeline(commands).exec();
|
|
96
|
+
for (const event of events) {
|
|
97
|
+
this.subscribedEvents.delete(event);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
async listen(group) {
|
|
101
|
+
if (this.listening) {
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
this.listening = true;
|
|
105
|
+
while (true) {
|
|
106
|
+
try {
|
|
107
|
+
const data = await this.streamReadClient.xreadgroupBuffer(
|
|
108
|
+
"GROUP",
|
|
109
|
+
group,
|
|
110
|
+
this.options.name,
|
|
111
|
+
"COUNT",
|
|
112
|
+
String(this.options.maxChunk),
|
|
113
|
+
"BLOCK",
|
|
114
|
+
String(this.options.blockTimeout),
|
|
115
|
+
"STREAMS",
|
|
116
|
+
...this.subscribedEvents,
|
|
117
|
+
...Array.from({ length: this.subscribedEvents.size }, () => ">")
|
|
118
|
+
);
|
|
119
|
+
if (!data) {
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
for (const [event, info] of data) {
|
|
123
|
+
for (const [id, packet] of info) {
|
|
124
|
+
const idx = packet.findIndex((value, idx2) => value.toString("utf8") === "data" && idx2 % 2 === 0);
|
|
125
|
+
if (idx < 0) {
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
const data2 = packet[idx + 1];
|
|
129
|
+
if (!data2) {
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
this.emitEvent(id, group, event.toString("utf8"), this.options.decode(data2));
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
} catch (error) {
|
|
136
|
+
this.emit("error", error);
|
|
137
|
+
break;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
this.listening = false;
|
|
141
|
+
}
|
|
142
|
+
async destroy() {
|
|
143
|
+
this.streamReadClient.disconnect();
|
|
144
|
+
this.options.redisClient.disconnect();
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
__name(BaseRedisBroker, "BaseRedisBroker");
|
|
148
|
+
__publicField(BaseRedisBroker, "STREAM_DATA_KEY", "data");
|
|
149
|
+
|
|
150
|
+
// src/brokers/redis/PubSubRedis.ts
|
|
151
|
+
var PubSubRedisBroker = class extends BaseRedisBroker {
|
|
152
|
+
async publish(event, data) {
|
|
153
|
+
await this.options.redisClient.xadd(
|
|
154
|
+
event,
|
|
155
|
+
"*",
|
|
156
|
+
BaseRedisBroker.STREAM_DATA_KEY,
|
|
157
|
+
this.options.encode(data)
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
emitEvent(id, group, event, data) {
|
|
161
|
+
const payload = {
|
|
162
|
+
data,
|
|
163
|
+
ack: async () => {
|
|
164
|
+
await this.options.redisClient.xack(event, group, id);
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
this.emit(event, payload);
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
__name(PubSubRedisBroker, "PubSubRedisBroker");
|
|
171
|
+
|
|
172
|
+
// src/brokers/redis/RPCRedis.ts
|
|
173
|
+
var import_node_timers = require("timers");
|
|
174
|
+
var DefaultRPCRedisBrokerOptions = {
|
|
175
|
+
...DefaultBrokerOptions,
|
|
176
|
+
timeout: 5e3
|
|
177
|
+
};
|
|
178
|
+
var RPCRedisBroker = class extends BaseRedisBroker {
|
|
179
|
+
options;
|
|
180
|
+
promises = /* @__PURE__ */ new Map();
|
|
181
|
+
constructor(options) {
|
|
182
|
+
super(options);
|
|
183
|
+
this.options = { ...DefaultRPCRedisBrokerOptions, ...options };
|
|
184
|
+
this.streamReadClient.on("messageBuffer", (channel, message) => {
|
|
185
|
+
const [, id] = channel.toString().split(":");
|
|
186
|
+
if (id && this.promises.has(id)) {
|
|
187
|
+
const { resolve: resolve2, timeout } = this.promises.get(id);
|
|
188
|
+
resolve2(this.options.decode(message));
|
|
189
|
+
(0, import_node_timers.clearTimeout)(timeout);
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
async call(event, data, timeoutDuration = this.options.timeout) {
|
|
194
|
+
const id = await this.options.redisClient.xadd(
|
|
195
|
+
event,
|
|
196
|
+
"*",
|
|
197
|
+
BaseRedisBroker.STREAM_DATA_KEY,
|
|
198
|
+
this.options.encode(data)
|
|
199
|
+
);
|
|
200
|
+
const rpcChannel = `${event}:${id}`;
|
|
201
|
+
const timedOut = new Error(`timed out after ${timeoutDuration}ms`);
|
|
202
|
+
await this.streamReadClient.subscribe(rpcChannel);
|
|
203
|
+
return new Promise((resolve2, reject) => {
|
|
204
|
+
const timeout = (0, import_node_timers.setTimeout)(() => reject(timedOut), timeoutDuration).unref();
|
|
205
|
+
this.promises.set(id, { resolve: resolve2, reject, timeout });
|
|
206
|
+
}).finally(() => {
|
|
207
|
+
void this.streamReadClient.unsubscribe(rpcChannel);
|
|
208
|
+
this.promises.delete(id);
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
emitEvent(id, group, event, data) {
|
|
212
|
+
const payload = {
|
|
213
|
+
data,
|
|
214
|
+
ack: async () => {
|
|
215
|
+
await this.options.redisClient.xack(event, group, id);
|
|
216
|
+
},
|
|
217
|
+
reply: async (data2) => {
|
|
218
|
+
await this.options.redisClient.publish(`${event}:${id.toString()}`, this.options.encode(data2));
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
this.emit(event, payload);
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
__name(RPCRedisBroker, "RPCRedisBroker");
|
|
225
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
226
|
+
0 && (module.exports = {
|
|
227
|
+
BaseRedisBroker,
|
|
228
|
+
DefaultBrokerOptions,
|
|
229
|
+
DefaultRPCRedisBrokerOptions,
|
|
230
|
+
PubSubRedisBroker,
|
|
231
|
+
RPCRedisBroker
|
|
232
|
+
});
|
|
233
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/brokers/redis/BaseRedis.ts","../src/brokers/Broker.ts","../src/brokers/redis/PubSubRedis.ts","../src/brokers/redis/RPCRedis.ts"],"sourcesContent":["export * from './brokers/redis/BaseRedis.js';\nexport * from './brokers/redis/PubSubRedis.js';\nexport * from './brokers/redis/RPCRedis.js';\n\nexport * from './brokers/Broker.js';\n","import type { Buffer } from 'node:buffer';\nimport { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { AsyncEventEmitter } from '@vladfrangu/async_event_emitter';\nimport type { Redis } from 'ioredis';\nimport { ReplyError } from 'ioredis';\nimport type { BaseBrokerOptions, IBaseBroker, ToEventMap } from '../Broker.js';\nimport { DefaultBrokerOptions } from '../Broker.js';\n\n// For some reason ioredis doesn't have this typed, but it exists\ndeclare module 'ioredis' {\n\tinterface Redis {\n\t\txreadgroupBuffer(...args: (Buffer | string)[]): Promise<[Buffer, [Buffer, Buffer[]][]][] | null>;\n\t}\n}\n\n/**\n * Options specific for a Redis broker\n */\nexport interface RedisBrokerOptions extends BaseBrokerOptions {\n\t/**\n\t * The Redis client to use\n\t */\n\tredisClient: Redis;\n}\n\n/**\n * Helper class with shared Redis logic\n */\nexport abstract class BaseRedisBroker<TEvents extends Record<string, any>>\n\textends AsyncEventEmitter<ToEventMap<TEvents>>\n\timplements IBaseBroker<TEvents>\n{\n\t/**\n\t * Used for Redis queues, see the 3rd argument taken by {@link https://redis.io/commands/xadd | xadd }\n\t */\n\tpublic static readonly STREAM_DATA_KEY = 'data';\n\n\t/**\n\t * Options this broker is using\n\t */\n\tprotected readonly options: Required<RedisBrokerOptions>;\n\n\t/**\n\t * Events this broker has subscribed to\n\t */\n\tprotected readonly subscribedEvents = new Set<string>();\n\n\t/**\n\t * Internal copy of the Redis client being used to read incoming payloads\n\t */\n\tprotected readonly streamReadClient: Redis;\n\n\t/**\n\t * Whether this broker is currently polling events\n\t */\n\tprotected listening = false;\n\n\tpublic constructor(options: RedisBrokerOptions) {\n\t\tsuper();\n\t\tthis.options = { ...DefaultBrokerOptions, ...options };\n\t\toptions.redisClient.defineCommand('xcleangroup', {\n\t\t\tnumberOfKeys: 1,\n\t\t\tlua: readFileSync(resolve(__dirname, '..', '..', '..', 'scripts', 'xcleangroup.lua'), 'utf8'),\n\t\t});\n\t\tthis.streamReadClient = options.redisClient.duplicate();\n\t}\n\n\t/**\n\t * {@inheritDoc IBaseBroker.subscribe}\n\t */\n\tpublic async subscribe(group: string, events: (keyof TEvents)[]): Promise<void> {\n\t\tawait Promise.all(\n\t\t\t// eslint-disable-next-line consistent-return\n\t\t\tevents.map(async (event) => {\n\t\t\t\tthis.subscribedEvents.add(event as string);\n\t\t\t\ttry {\n\t\t\t\t\treturn await this.options.redisClient.xgroup('CREATE', event as string, group, 0, 'MKSTREAM');\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!(error instanceof ReplyError)) {\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t\tvoid this.listen(group);\n\t}\n\n\t/**\n\t * {@inheritDoc IBaseBroker.unsubscribe}\n\t */\n\tpublic async unsubscribe(group: string, events: (keyof TEvents)[]): Promise<void> {\n\t\tconst commands: unknown[][] = Array.from({ length: events.length * 2 });\n\t\tfor (let idx = 0; idx < commands.length; idx += 2) {\n\t\t\tconst event = events[idx / 2];\n\t\t\tcommands[idx] = ['xgroup', 'delconsumer', event as string, group, this.options.name];\n\t\t\tcommands[idx + 1] = ['xcleangroup', event as string, group];\n\t\t}\n\n\t\tawait this.options.redisClient.pipeline(commands).exec();\n\n\t\tfor (const event of events) {\n\t\t\tthis.subscribedEvents.delete(event as string);\n\t\t}\n\t}\n\n\t/**\n\t * Begins polling for events, firing them to {@link BaseRedisBroker.listen}\n\t */\n\tprotected async listen(group: string): Promise<void> {\n\t\tif (this.listening) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.listening = true;\n\t\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n\t\twhile (true) {\n\t\t\ttry {\n\t\t\t\tconst data = await this.streamReadClient.xreadgroupBuffer(\n\t\t\t\t\t'GROUP',\n\t\t\t\t\tgroup,\n\t\t\t\t\tthis.options.name,\n\t\t\t\t\t'COUNT',\n\t\t\t\t\tString(this.options.maxChunk),\n\t\t\t\t\t'BLOCK',\n\t\t\t\t\tString(this.options.blockTimeout),\n\t\t\t\t\t'STREAMS',\n\t\t\t\t\t...this.subscribedEvents,\n\t\t\t\t\t...Array.from({ length: this.subscribedEvents.size }, () => '>'),\n\t\t\t\t);\n\n\t\t\t\tif (!data) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tfor (const [event, info] of data) {\n\t\t\t\t\tfor (const [id, packet] of info) {\n\t\t\t\t\t\tconst idx = packet.findIndex((value, idx) => value.toString('utf8') === 'data' && idx % 2 === 0);\n\t\t\t\t\t\tif (idx < 0) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst data = packet[idx + 1];\n\t\t\t\t\t\tif (!data) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis.emitEvent(id, group, event.toString('utf8'), this.options.decode(data));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthis.emit('error', error);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tthis.listening = false;\n\t}\n\n\t/**\n\t * Destroys the broker, closing all connections\n\t */\n\tpublic async destroy() {\n\t\tthis.streamReadClient.disconnect();\n\t\tthis.options.redisClient.disconnect();\n\t}\n\n\t/**\n\t * Handles an incoming Redis event\n\t */\n\tprotected abstract emitEvent(id: Buffer, group: string, event: string, data: unknown): unknown;\n}\n","import { Buffer } from 'node:buffer';\nimport { randomBytes } from 'node:crypto';\nimport { encode, decode } from '@msgpack/msgpack';\nimport type { AsyncEventEmitter } from '@vladfrangu/async_event_emitter';\n\n/**\n * Base options for a broker implementation\n */\nexport interface BaseBrokerOptions {\n\t/**\n\t * How long to block for messages when polling\n\t */\n\tblockTimeout?: number;\n\t/**\n\t * Function to use for decoding messages\n\t */\n\t// eslint-disable-next-line @typescript-eslint/method-signature-style\n\tdecode?: (data: Buffer) => unknown;\n\t/**\n\t * Function to use for encoding messages\n\t */\n\t// eslint-disable-next-line @typescript-eslint/method-signature-style\n\tencode?: (data: unknown) => Buffer;\n\t/**\n\t * Max number of messages to poll at once\n\t */\n\tmaxChunk?: number;\n\t/**\n\t * Unique consumer name. See: https://redis.io/commands/xreadgroup/\n\t */\n\tname?: string;\n}\n\n/**\n * Default broker options\n */\nexport const DefaultBrokerOptions: Required<BaseBrokerOptions> = {\n\tname: randomBytes(20).toString('hex'),\n\tmaxChunk: 10,\n\tblockTimeout: 5_000,\n\tencode: (data): Buffer => {\n\t\tconst encoded = encode(data);\n\t\treturn Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength);\n\t},\n\tdecode: (data): unknown => decode(data),\n};\n\nexport type ToEventMap<\n\tTRecord extends Record<string, any>,\n\tTResponses extends Record<keyof TRecord, any> | undefined = undefined,\n> = {\n\t[TKey in keyof TRecord]: [\n\t\tevent: TResponses extends Record<keyof TRecord, any>\n\t\t\t? { ack(): Promise<void>; reply(data: TResponses[TKey]): Promise<void> }\n\t\t\t: { ack(): Promise<void> } & { data: TRecord[TKey] },\n\t];\n} & { [K: string]: any };\n\nexport interface IBaseBroker<TEvents extends Record<string, any>> {\n\t/**\n\t * Subscribes to the given events, grouping them by the given group name\n\t */\n\tsubscribe(group: string, events: (keyof TEvents)[]): Promise<void>;\n\t/**\n\t * Unsubscribes from the given events - it's required to pass the same group name as when subscribing for proper cleanup\n\t */\n\tunsubscribe(group: string, events: (keyof TEvents)[]): Promise<void>;\n}\n\nexport interface IPubSubBroker<TEvents extends Record<string, any>>\n\textends IBaseBroker<TEvents>,\n\t\tAsyncEventEmitter<ToEventMap<TEvents>> {\n\t/**\n\t * Publishes an event\n\t */\n\tpublish<T extends keyof TEvents>(event: T, data: TEvents[T]): Promise<void>;\n}\n\nexport interface IRPCBroker<TEvents extends Record<string, any>, TResponses extends Record<keyof TEvents, any>>\n\textends IBaseBroker<TEvents>,\n\t\tAsyncEventEmitter<ToEventMap<TEvents, TResponses>> {\n\t/**\n\t * Makes an RPC call\n\t */\n\tcall<T extends keyof TEvents>(event: T, data: TEvents[T], timeoutDuration?: number): Promise<TResponses[T]>;\n}\n","import type { Buffer } from 'node:buffer';\nimport type { IPubSubBroker } from '../Broker.js';\nimport { BaseRedisBroker } from './BaseRedis.js';\n\n/**\n * PubSub broker powered by Redis\n *\n * @example\n * ```ts\n * // publisher.js\n * import { PubSubRedisBroker } from '@discordjs/brokers';\n * import Redis from 'ioredis';\n *\n * const broker = new PubSubRedisBroker({ redisClient: new Redis() });\n *\n * await broker.publish('test', 'Hello World!');\n * await broker.destroy();\n *\n * // subscriber.js\n * import { PubSubRedisBroker } from '@discordjs/brokers';\n * import Redis from 'ioredis';\n *\n * const broker = new PubSubRedisBroker({ redisClient: new Redis() });\n * \tbroker.on('test', ({ data, ack }) => {\n * \tconsole.log(data);\n * \tvoid ack();\n * });\n *\n * await broker.subscribe('subscribers', ['test']);\n * ```\n */\nexport class PubSubRedisBroker<TEvents extends Record<string, any>>\n\textends BaseRedisBroker<TEvents>\n\timplements IPubSubBroker<TEvents>\n{\n\t/**\n\t * {@inheritDoc IPubSubBroker.publish}\n\t */\n\tpublic async publish<T extends keyof TEvents>(event: T, data: TEvents[T]): Promise<void> {\n\t\tawait this.options.redisClient.xadd(\n\t\t\tevent as string,\n\t\t\t'*',\n\t\t\tBaseRedisBroker.STREAM_DATA_KEY,\n\t\t\tthis.options.encode(data),\n\t\t);\n\t}\n\n\tprotected emitEvent(id: Buffer, group: string, event: string, data: unknown) {\n\t\tconst payload: { ack(): Promise<void>; data: unknown } = {\n\t\t\tdata,\n\t\t\tack: async () => {\n\t\t\t\tawait this.options.redisClient.xack(event, group, id);\n\t\t\t},\n\t\t};\n\n\t\tthis.emit(event, payload);\n\t}\n}\n","import type { Buffer } from 'node:buffer';\nimport { clearTimeout, setTimeout } from 'node:timers';\nimport type { IRPCBroker } from '../Broker.js';\nimport { DefaultBrokerOptions } from '../Broker.js';\nimport type { RedisBrokerOptions } from './BaseRedis.js';\nimport { BaseRedisBroker } from './BaseRedis.js';\n\ninterface InternalPromise {\n\treject(error: any): void;\n\tresolve(data: any): void;\n\ttimeout: NodeJS.Timeout;\n}\n\n/**\n * Options specific for an RPC Redis broker\n */\nexport interface RPCRedisBrokerOptions extends RedisBrokerOptions {\n\ttimeout?: number;\n}\n\n/**\n * Default values used for the {@link RPCRedisBrokerOptions}\n */\nexport const DefaultRPCRedisBrokerOptions: Required<Omit<RPCRedisBrokerOptions, 'redisClient'>> = {\n\t...DefaultBrokerOptions,\n\ttimeout: 5_000,\n};\n\n/**\n * RPC broker powered by Redis\n *\n * @example\n * ```ts\n * // caller.js\n * import { RPCRedisBroker } from '@discordjs/brokers';\n * import Redis from 'ioredis';\n *\n * const broker = new RPCRedisBroker({ redisClient: new Redis() });\n *\n * console.log(await broker.call('testcall', 'Hello World!'));\n * await broker.destroy();\n *\n * // responder.js\n * import { RPCRedisBroker } from '@discordjs/brokers';\n * import Redis from 'ioredis';\n *\n * const broker = new RPCRedisBroker({ redisClient: new Redis() });\n * broker.on('testcall', ({ data, ack, reply }) => {\n * \tconsole.log('responder', data);\n * \tvoid ack();\n * \tvoid reply(`Echo: ${data}`);\n * });\n *\n * await broker.subscribe('responders', ['testcall']);\n * ```\n */\nexport class RPCRedisBroker<TEvents extends Record<string, any>, TResponses extends Record<keyof TEvents, any>>\n\textends BaseRedisBroker<TEvents>\n\timplements IRPCBroker<TEvents, TResponses>\n{\n\t/**\n\t * Options this broker is using\n\t */\n\tprotected override readonly options: Required<RPCRedisBrokerOptions>;\n\n\tprotected readonly promises = new Map<string, InternalPromise>();\n\n\tpublic constructor(options: RPCRedisBrokerOptions) {\n\t\tsuper(options);\n\t\tthis.options = { ...DefaultRPCRedisBrokerOptions, ...options };\n\n\t\tthis.streamReadClient.on('messageBuffer', (channel: Buffer, message: Buffer) => {\n\t\t\tconst [, id] = channel.toString().split(':');\n\t\t\tif (id && this.promises.has(id)) {\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/unbound-method\n\t\t\t\tconst { resolve, timeout } = this.promises.get(id)!;\n\t\t\t\tresolve(this.options.decode(message));\n\t\t\t\tclearTimeout(timeout);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * {@inheritDoc IRPCBroker.call}\n\t */\n\tpublic async call<T extends keyof TEvents>(\n\t\tevent: T,\n\t\tdata: TEvents[T],\n\t\ttimeoutDuration: number = this.options.timeout,\n\t): Promise<TResponses[T]> {\n\t\tconst id = await this.options.redisClient.xadd(\n\t\t\tevent as string,\n\t\t\t'*',\n\t\t\tBaseRedisBroker.STREAM_DATA_KEY,\n\t\t\tthis.options.encode(data),\n\t\t);\n\t\t// This id! assertion is valid. From redis docs:\n\t\t// \"The command returns a Null reply when used with the NOMKSTREAM option and the key doesn't exist.\"\n\t\t// See: https://redis.io/commands/xadd/\n\t\tconst rpcChannel = `${event as string}:${id!}`;\n\n\t\t// Construct the error here for better stack traces\n\t\tconst timedOut = new Error(`timed out after ${timeoutDuration}ms`);\n\n\t\tawait this.streamReadClient.subscribe(rpcChannel);\n\t\treturn new Promise<TResponses[T]>((resolve, reject) => {\n\t\t\tconst timeout = setTimeout(() => reject(timedOut), timeoutDuration).unref();\n\n\t\t\tthis.promises.set(id!, { resolve, reject, timeout });\n\t\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\t}).finally(() => {\n\t\t\tvoid this.streamReadClient.unsubscribe(rpcChannel);\n\t\t\tthis.promises.delete(id!);\n\t\t});\n\t}\n\n\tprotected emitEvent(id: Buffer, group: string, event: string, data: unknown) {\n\t\tconst payload: { ack(): Promise<void>; data: unknown; reply(data: unknown): Promise<void> } = {\n\t\t\tdata,\n\t\t\tack: async () => {\n\t\t\t\tawait this.options.redisClient.xack(event, group, id);\n\t\t\t},\n\t\t\treply: async (data) => {\n\t\t\t\tawait this.options.redisClient.publish(`${event}:${id.toString()}`, this.options.encode(data));\n\t\t\t},\n\t\t};\n\n\t\tthis.emit(event, payload);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;A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DED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
3
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
4
|
+
var __publicField = (obj, key, value) => {
|
|
5
|
+
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
6
|
+
return value;
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
// ../../node_modules/tsup/assets/esm_shims.js
|
|
10
|
+
import { fileURLToPath } from "url";
|
|
11
|
+
import path from "path";
|
|
12
|
+
var getFilename = /* @__PURE__ */ __name(() => fileURLToPath(import.meta.url), "getFilename");
|
|
13
|
+
var getDirname = /* @__PURE__ */ __name(() => path.dirname(getFilename()), "getDirname");
|
|
14
|
+
var __dirname = /* @__PURE__ */ getDirname();
|
|
15
|
+
|
|
16
|
+
// src/brokers/redis/BaseRedis.ts
|
|
17
|
+
import { readFileSync } from "node:fs";
|
|
18
|
+
import { resolve } from "node:path";
|
|
19
|
+
import { AsyncEventEmitter } from "@vladfrangu/async_event_emitter";
|
|
20
|
+
import { ReplyError } from "ioredis";
|
|
21
|
+
|
|
22
|
+
// src/brokers/Broker.ts
|
|
23
|
+
import { Buffer as Buffer2 } from "node:buffer";
|
|
24
|
+
import { randomBytes } from "node:crypto";
|
|
25
|
+
import { encode, decode } from "@msgpack/msgpack";
|
|
26
|
+
var DefaultBrokerOptions = {
|
|
27
|
+
name: randomBytes(20).toString("hex"),
|
|
28
|
+
maxChunk: 10,
|
|
29
|
+
blockTimeout: 5e3,
|
|
30
|
+
encode: (data) => {
|
|
31
|
+
const encoded = encode(data);
|
|
32
|
+
return Buffer2.from(encoded.buffer, encoded.byteOffset, encoded.byteLength);
|
|
33
|
+
},
|
|
34
|
+
decode: (data) => decode(data)
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// src/brokers/redis/BaseRedis.ts
|
|
38
|
+
var BaseRedisBroker = class extends AsyncEventEmitter {
|
|
39
|
+
options;
|
|
40
|
+
subscribedEvents = /* @__PURE__ */ new Set();
|
|
41
|
+
streamReadClient;
|
|
42
|
+
listening = false;
|
|
43
|
+
constructor(options) {
|
|
44
|
+
super();
|
|
45
|
+
this.options = { ...DefaultBrokerOptions, ...options };
|
|
46
|
+
options.redisClient.defineCommand("xcleangroup", {
|
|
47
|
+
numberOfKeys: 1,
|
|
48
|
+
lua: readFileSync(resolve(__dirname, "..", "..", "..", "scripts", "xcleangroup.lua"), "utf8")
|
|
49
|
+
});
|
|
50
|
+
this.streamReadClient = options.redisClient.duplicate();
|
|
51
|
+
}
|
|
52
|
+
async subscribe(group, events) {
|
|
53
|
+
await Promise.all(
|
|
54
|
+
events.map(async (event) => {
|
|
55
|
+
this.subscribedEvents.add(event);
|
|
56
|
+
try {
|
|
57
|
+
return await this.options.redisClient.xgroup("CREATE", event, group, 0, "MKSTREAM");
|
|
58
|
+
} catch (error) {
|
|
59
|
+
if (!(error instanceof ReplyError)) {
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
})
|
|
64
|
+
);
|
|
65
|
+
void this.listen(group);
|
|
66
|
+
}
|
|
67
|
+
async unsubscribe(group, events) {
|
|
68
|
+
const commands = Array.from({ length: events.length * 2 });
|
|
69
|
+
for (let idx = 0; idx < commands.length; idx += 2) {
|
|
70
|
+
const event = events[idx / 2];
|
|
71
|
+
commands[idx] = ["xgroup", "delconsumer", event, group, this.options.name];
|
|
72
|
+
commands[idx + 1] = ["xcleangroup", event, group];
|
|
73
|
+
}
|
|
74
|
+
await this.options.redisClient.pipeline(commands).exec();
|
|
75
|
+
for (const event of events) {
|
|
76
|
+
this.subscribedEvents.delete(event);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
async listen(group) {
|
|
80
|
+
if (this.listening) {
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
this.listening = true;
|
|
84
|
+
while (true) {
|
|
85
|
+
try {
|
|
86
|
+
const data = await this.streamReadClient.xreadgroupBuffer(
|
|
87
|
+
"GROUP",
|
|
88
|
+
group,
|
|
89
|
+
this.options.name,
|
|
90
|
+
"COUNT",
|
|
91
|
+
String(this.options.maxChunk),
|
|
92
|
+
"BLOCK",
|
|
93
|
+
String(this.options.blockTimeout),
|
|
94
|
+
"STREAMS",
|
|
95
|
+
...this.subscribedEvents,
|
|
96
|
+
...Array.from({ length: this.subscribedEvents.size }, () => ">")
|
|
97
|
+
);
|
|
98
|
+
if (!data) {
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
for (const [event, info] of data) {
|
|
102
|
+
for (const [id, packet] of info) {
|
|
103
|
+
const idx = packet.findIndex((value, idx2) => value.toString("utf8") === "data" && idx2 % 2 === 0);
|
|
104
|
+
if (idx < 0) {
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
const data2 = packet[idx + 1];
|
|
108
|
+
if (!data2) {
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
this.emitEvent(id, group, event.toString("utf8"), this.options.decode(data2));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
} catch (error) {
|
|
115
|
+
this.emit("error", error);
|
|
116
|
+
break;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
this.listening = false;
|
|
120
|
+
}
|
|
121
|
+
async destroy() {
|
|
122
|
+
this.streamReadClient.disconnect();
|
|
123
|
+
this.options.redisClient.disconnect();
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
__name(BaseRedisBroker, "BaseRedisBroker");
|
|
127
|
+
__publicField(BaseRedisBroker, "STREAM_DATA_KEY", "data");
|
|
128
|
+
|
|
129
|
+
// src/brokers/redis/PubSubRedis.ts
|
|
130
|
+
var PubSubRedisBroker = class extends BaseRedisBroker {
|
|
131
|
+
async publish(event, data) {
|
|
132
|
+
await this.options.redisClient.xadd(
|
|
133
|
+
event,
|
|
134
|
+
"*",
|
|
135
|
+
BaseRedisBroker.STREAM_DATA_KEY,
|
|
136
|
+
this.options.encode(data)
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
emitEvent(id, group, event, data) {
|
|
140
|
+
const payload = {
|
|
141
|
+
data,
|
|
142
|
+
ack: async () => {
|
|
143
|
+
await this.options.redisClient.xack(event, group, id);
|
|
144
|
+
}
|
|
145
|
+
};
|
|
146
|
+
this.emit(event, payload);
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
__name(PubSubRedisBroker, "PubSubRedisBroker");
|
|
150
|
+
|
|
151
|
+
// src/brokers/redis/RPCRedis.ts
|
|
152
|
+
import { clearTimeout, setTimeout } from "node:timers";
|
|
153
|
+
var DefaultRPCRedisBrokerOptions = {
|
|
154
|
+
...DefaultBrokerOptions,
|
|
155
|
+
timeout: 5e3
|
|
156
|
+
};
|
|
157
|
+
var RPCRedisBroker = class extends BaseRedisBroker {
|
|
158
|
+
options;
|
|
159
|
+
promises = /* @__PURE__ */ new Map();
|
|
160
|
+
constructor(options) {
|
|
161
|
+
super(options);
|
|
162
|
+
this.options = { ...DefaultRPCRedisBrokerOptions, ...options };
|
|
163
|
+
this.streamReadClient.on("messageBuffer", (channel, message) => {
|
|
164
|
+
const [, id] = channel.toString().split(":");
|
|
165
|
+
if (id && this.promises.has(id)) {
|
|
166
|
+
const { resolve: resolve2, timeout } = this.promises.get(id);
|
|
167
|
+
resolve2(this.options.decode(message));
|
|
168
|
+
clearTimeout(timeout);
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
async call(event, data, timeoutDuration = this.options.timeout) {
|
|
173
|
+
const id = await this.options.redisClient.xadd(
|
|
174
|
+
event,
|
|
175
|
+
"*",
|
|
176
|
+
BaseRedisBroker.STREAM_DATA_KEY,
|
|
177
|
+
this.options.encode(data)
|
|
178
|
+
);
|
|
179
|
+
const rpcChannel = `${event}:${id}`;
|
|
180
|
+
const timedOut = new Error(`timed out after ${timeoutDuration}ms`);
|
|
181
|
+
await this.streamReadClient.subscribe(rpcChannel);
|
|
182
|
+
return new Promise((resolve2, reject) => {
|
|
183
|
+
const timeout = setTimeout(() => reject(timedOut), timeoutDuration).unref();
|
|
184
|
+
this.promises.set(id, { resolve: resolve2, reject, timeout });
|
|
185
|
+
}).finally(() => {
|
|
186
|
+
void this.streamReadClient.unsubscribe(rpcChannel);
|
|
187
|
+
this.promises.delete(id);
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
emitEvent(id, group, event, data) {
|
|
191
|
+
const payload = {
|
|
192
|
+
data,
|
|
193
|
+
ack: async () => {
|
|
194
|
+
await this.options.redisClient.xack(event, group, id);
|
|
195
|
+
},
|
|
196
|
+
reply: async (data2) => {
|
|
197
|
+
await this.options.redisClient.publish(`${event}:${id.toString()}`, this.options.encode(data2));
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
this.emit(event, payload);
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
__name(RPCRedisBroker, "RPCRedisBroker");
|
|
204
|
+
export {
|
|
205
|
+
BaseRedisBroker,
|
|
206
|
+
DefaultBrokerOptions,
|
|
207
|
+
DefaultRPCRedisBrokerOptions,
|
|
208
|
+
PubSubRedisBroker,
|
|
209
|
+
RPCRedisBroker
|
|
210
|
+
};
|
|
211
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/tsup/assets/esm_shims.js","../src/brokers/redis/BaseRedis.ts","../src/brokers/Broker.ts","../src/brokers/redis/PubSubRedis.ts","../src/brokers/redis/RPCRedis.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport { fileURLToPath } from 'url'\nimport path from 'path'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","import type { Buffer } from 'node:buffer';\nimport { readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { AsyncEventEmitter } from '@vladfrangu/async_event_emitter';\nimport type { Redis } from 'ioredis';\nimport { ReplyError } from 'ioredis';\nimport type { BaseBrokerOptions, IBaseBroker, ToEventMap } from '../Broker.js';\nimport { DefaultBrokerOptions } from '../Broker.js';\n\n// For some reason ioredis doesn't have this typed, but it exists\ndeclare module 'ioredis' {\n\tinterface Redis {\n\t\txreadgroupBuffer(...args: (Buffer | string)[]): Promise<[Buffer, [Buffer, Buffer[]][]][] | null>;\n\t}\n}\n\n/**\n * Options specific for a Redis broker\n */\nexport interface RedisBrokerOptions extends BaseBrokerOptions {\n\t/**\n\t * The Redis client to use\n\t */\n\tredisClient: Redis;\n}\n\n/**\n * Helper class with shared Redis logic\n */\nexport abstract class BaseRedisBroker<TEvents extends Record<string, any>>\n\textends AsyncEventEmitter<ToEventMap<TEvents>>\n\timplements IBaseBroker<TEvents>\n{\n\t/**\n\t * Used for Redis queues, see the 3rd argument taken by {@link https://redis.io/commands/xadd | xadd }\n\t */\n\tpublic static readonly STREAM_DATA_KEY = 'data';\n\n\t/**\n\t * Options this broker is using\n\t */\n\tprotected readonly options: Required<RedisBrokerOptions>;\n\n\t/**\n\t * Events this broker has subscribed to\n\t */\n\tprotected readonly subscribedEvents = new Set<string>();\n\n\t/**\n\t * Internal copy of the Redis client being used to read incoming payloads\n\t */\n\tprotected readonly streamReadClient: Redis;\n\n\t/**\n\t * Whether this broker is currently polling events\n\t */\n\tprotected listening = false;\n\n\tpublic constructor(options: RedisBrokerOptions) {\n\t\tsuper();\n\t\tthis.options = { ...DefaultBrokerOptions, ...options };\n\t\toptions.redisClient.defineCommand('xcleangroup', {\n\t\t\tnumberOfKeys: 1,\n\t\t\tlua: readFileSync(resolve(__dirname, '..', '..', '..', 'scripts', 'xcleangroup.lua'), 'utf8'),\n\t\t});\n\t\tthis.streamReadClient = options.redisClient.duplicate();\n\t}\n\n\t/**\n\t * {@inheritDoc IBaseBroker.subscribe}\n\t */\n\tpublic async subscribe(group: string, events: (keyof TEvents)[]): Promise<void> {\n\t\tawait Promise.all(\n\t\t\t// eslint-disable-next-line consistent-return\n\t\t\tevents.map(async (event) => {\n\t\t\t\tthis.subscribedEvents.add(event as string);\n\t\t\t\ttry {\n\t\t\t\t\treturn await this.options.redisClient.xgroup('CREATE', event as string, group, 0, 'MKSTREAM');\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!(error instanceof ReplyError)) {\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}),\n\t\t);\n\t\tvoid this.listen(group);\n\t}\n\n\t/**\n\t * {@inheritDoc IBaseBroker.unsubscribe}\n\t */\n\tpublic async unsubscribe(group: string, events: (keyof TEvents)[]): Promise<void> {\n\t\tconst commands: unknown[][] = Array.from({ length: events.length * 2 });\n\t\tfor (let idx = 0; idx < commands.length; idx += 2) {\n\t\t\tconst event = events[idx / 2];\n\t\t\tcommands[idx] = ['xgroup', 'delconsumer', event as string, group, this.options.name];\n\t\t\tcommands[idx + 1] = ['xcleangroup', event as string, group];\n\t\t}\n\n\t\tawait this.options.redisClient.pipeline(commands).exec();\n\n\t\tfor (const event of events) {\n\t\t\tthis.subscribedEvents.delete(event as string);\n\t\t}\n\t}\n\n\t/**\n\t * Begins polling for events, firing them to {@link BaseRedisBroker.listen}\n\t */\n\tprotected async listen(group: string): Promise<void> {\n\t\tif (this.listening) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.listening = true;\n\t\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n\t\twhile (true) {\n\t\t\ttry {\n\t\t\t\tconst data = await this.streamReadClient.xreadgroupBuffer(\n\t\t\t\t\t'GROUP',\n\t\t\t\t\tgroup,\n\t\t\t\t\tthis.options.name,\n\t\t\t\t\t'COUNT',\n\t\t\t\t\tString(this.options.maxChunk),\n\t\t\t\t\t'BLOCK',\n\t\t\t\t\tString(this.options.blockTimeout),\n\t\t\t\t\t'STREAMS',\n\t\t\t\t\t...this.subscribedEvents,\n\t\t\t\t\t...Array.from({ length: this.subscribedEvents.size }, () => '>'),\n\t\t\t\t);\n\n\t\t\t\tif (!data) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tfor (const [event, info] of data) {\n\t\t\t\t\tfor (const [id, packet] of info) {\n\t\t\t\t\t\tconst idx = packet.findIndex((value, idx) => value.toString('utf8') === 'data' && idx % 2 === 0);\n\t\t\t\t\t\tif (idx < 0) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst data = packet[idx + 1];\n\t\t\t\t\t\tif (!data) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tthis.emitEvent(id, group, event.toString('utf8'), this.options.decode(data));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthis.emit('error', error);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tthis.listening = false;\n\t}\n\n\t/**\n\t * Destroys the broker, closing all connections\n\t */\n\tpublic async destroy() {\n\t\tthis.streamReadClient.disconnect();\n\t\tthis.options.redisClient.disconnect();\n\t}\n\n\t/**\n\t * Handles an incoming Redis event\n\t */\n\tprotected abstract emitEvent(id: Buffer, group: string, event: string, data: unknown): unknown;\n}\n","import { Buffer } from 'node:buffer';\nimport { randomBytes } from 'node:crypto';\nimport { encode, decode } from '@msgpack/msgpack';\nimport type { AsyncEventEmitter } from '@vladfrangu/async_event_emitter';\n\n/**\n * Base options for a broker implementation\n */\nexport interface BaseBrokerOptions {\n\t/**\n\t * How long to block for messages when polling\n\t */\n\tblockTimeout?: number;\n\t/**\n\t * Function to use for decoding messages\n\t */\n\t// eslint-disable-next-line @typescript-eslint/method-signature-style\n\tdecode?: (data: Buffer) => unknown;\n\t/**\n\t * Function to use for encoding messages\n\t */\n\t// eslint-disable-next-line @typescript-eslint/method-signature-style\n\tencode?: (data: unknown) => Buffer;\n\t/**\n\t * Max number of messages to poll at once\n\t */\n\tmaxChunk?: number;\n\t/**\n\t * Unique consumer name. See: https://redis.io/commands/xreadgroup/\n\t */\n\tname?: string;\n}\n\n/**\n * Default broker options\n */\nexport const DefaultBrokerOptions: Required<BaseBrokerOptions> = {\n\tname: randomBytes(20).toString('hex'),\n\tmaxChunk: 10,\n\tblockTimeout: 5_000,\n\tencode: (data): Buffer => {\n\t\tconst encoded = encode(data);\n\t\treturn Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength);\n\t},\n\tdecode: (data): unknown => decode(data),\n};\n\nexport type ToEventMap<\n\tTRecord extends Record<string, any>,\n\tTResponses extends Record<keyof TRecord, any> | undefined = undefined,\n> = {\n\t[TKey in keyof TRecord]: [\n\t\tevent: TResponses extends Record<keyof TRecord, any>\n\t\t\t? { ack(): Promise<void>; reply(data: TResponses[TKey]): Promise<void> }\n\t\t\t: { ack(): Promise<void> } & { data: TRecord[TKey] },\n\t];\n} & { [K: string]: any };\n\nexport interface IBaseBroker<TEvents extends Record<string, any>> {\n\t/**\n\t * Subscribes to the given events, grouping them by the given group name\n\t */\n\tsubscribe(group: string, events: (keyof TEvents)[]): Promise<void>;\n\t/**\n\t * Unsubscribes from the given events - it's required to pass the same group name as when subscribing for proper cleanup\n\t */\n\tunsubscribe(group: string, events: (keyof TEvents)[]): Promise<void>;\n}\n\nexport interface IPubSubBroker<TEvents extends Record<string, any>>\n\textends IBaseBroker<TEvents>,\n\t\tAsyncEventEmitter<ToEventMap<TEvents>> {\n\t/**\n\t * Publishes an event\n\t */\n\tpublish<T extends keyof TEvents>(event: T, data: TEvents[T]): Promise<void>;\n}\n\nexport interface IRPCBroker<TEvents extends Record<string, any>, TResponses extends Record<keyof TEvents, any>>\n\textends IBaseBroker<TEvents>,\n\t\tAsyncEventEmitter<ToEventMap<TEvents, TResponses>> {\n\t/**\n\t * Makes an RPC call\n\t */\n\tcall<T extends keyof TEvents>(event: T, data: TEvents[T], timeoutDuration?: number): Promise<TResponses[T]>;\n}\n","import type { Buffer } from 'node:buffer';\nimport type { IPubSubBroker } from '../Broker.js';\nimport { BaseRedisBroker } from './BaseRedis.js';\n\n/**\n * PubSub broker powered by Redis\n *\n * @example\n * ```ts\n * // publisher.js\n * import { PubSubRedisBroker } from '@discordjs/brokers';\n * import Redis from 'ioredis';\n *\n * const broker = new PubSubRedisBroker({ redisClient: new Redis() });\n *\n * await broker.publish('test', 'Hello World!');\n * await broker.destroy();\n *\n * // subscriber.js\n * import { PubSubRedisBroker } from '@discordjs/brokers';\n * import Redis from 'ioredis';\n *\n * const broker = new PubSubRedisBroker({ redisClient: new Redis() });\n * \tbroker.on('test', ({ data, ack }) => {\n * \tconsole.log(data);\n * \tvoid ack();\n * });\n *\n * await broker.subscribe('subscribers', ['test']);\n * ```\n */\nexport class PubSubRedisBroker<TEvents extends Record<string, any>>\n\textends BaseRedisBroker<TEvents>\n\timplements IPubSubBroker<TEvents>\n{\n\t/**\n\t * {@inheritDoc IPubSubBroker.publish}\n\t */\n\tpublic async publish<T extends keyof TEvents>(event: T, data: TEvents[T]): Promise<void> {\n\t\tawait this.options.redisClient.xadd(\n\t\t\tevent as string,\n\t\t\t'*',\n\t\t\tBaseRedisBroker.STREAM_DATA_KEY,\n\t\t\tthis.options.encode(data),\n\t\t);\n\t}\n\n\tprotected emitEvent(id: Buffer, group: string, event: string, data: unknown) {\n\t\tconst payload: { ack(): Promise<void>; data: unknown } = {\n\t\t\tdata,\n\t\t\tack: async () => {\n\t\t\t\tawait this.options.redisClient.xack(event, group, id);\n\t\t\t},\n\t\t};\n\n\t\tthis.emit(event, payload);\n\t}\n}\n","import type { Buffer } from 'node:buffer';\nimport { clearTimeout, setTimeout } from 'node:timers';\nimport type { IRPCBroker } from '../Broker.js';\nimport { DefaultBrokerOptions } from '../Broker.js';\nimport type { RedisBrokerOptions } from './BaseRedis.js';\nimport { BaseRedisBroker } from './BaseRedis.js';\n\ninterface InternalPromise {\n\treject(error: any): void;\n\tresolve(data: any): void;\n\ttimeout: NodeJS.Timeout;\n}\n\n/**\n * Options specific for an RPC Redis broker\n */\nexport interface RPCRedisBrokerOptions extends RedisBrokerOptions {\n\ttimeout?: number;\n}\n\n/**\n * Default values used for the {@link RPCRedisBrokerOptions}\n */\nexport const DefaultRPCRedisBrokerOptions: Required<Omit<RPCRedisBrokerOptions, 'redisClient'>> = {\n\t...DefaultBrokerOptions,\n\ttimeout: 5_000,\n};\n\n/**\n * RPC broker powered by Redis\n *\n * @example\n * ```ts\n * // caller.js\n * import { RPCRedisBroker } from '@discordjs/brokers';\n * import Redis from 'ioredis';\n *\n * const broker = new RPCRedisBroker({ redisClient: new Redis() });\n *\n * console.log(await broker.call('testcall', 'Hello World!'));\n * await broker.destroy();\n *\n * // responder.js\n * import { RPCRedisBroker } from '@discordjs/brokers';\n * import Redis from 'ioredis';\n *\n * const broker = new RPCRedisBroker({ redisClient: new Redis() });\n * broker.on('testcall', ({ data, ack, reply }) => {\n * \tconsole.log('responder', data);\n * \tvoid ack();\n * \tvoid reply(`Echo: ${data}`);\n * });\n *\n * await broker.subscribe('responders', ['testcall']);\n * ```\n */\nexport class RPCRedisBroker<TEvents extends Record<string, any>, TResponses extends Record<keyof TEvents, any>>\n\textends BaseRedisBroker<TEvents>\n\timplements IRPCBroker<TEvents, TResponses>\n{\n\t/**\n\t * Options this broker is using\n\t */\n\tprotected override readonly options: Required<RPCRedisBrokerOptions>;\n\n\tprotected readonly promises = new Map<string, InternalPromise>();\n\n\tpublic constructor(options: RPCRedisBrokerOptions) {\n\t\tsuper(options);\n\t\tthis.options = { ...DefaultRPCRedisBrokerOptions, ...options };\n\n\t\tthis.streamReadClient.on('messageBuffer', (channel: Buffer, message: Buffer) => {\n\t\t\tconst [, id] = channel.toString().split(':');\n\t\t\tif (id && this.promises.has(id)) {\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/unbound-method\n\t\t\t\tconst { resolve, timeout } = this.promises.get(id)!;\n\t\t\t\tresolve(this.options.decode(message));\n\t\t\t\tclearTimeout(timeout);\n\t\t\t}\n\t\t});\n\t}\n\n\t/**\n\t * {@inheritDoc IRPCBroker.call}\n\t */\n\tpublic async call<T extends keyof TEvents>(\n\t\tevent: T,\n\t\tdata: TEvents[T],\n\t\ttimeoutDuration: number = this.options.timeout,\n\t): Promise<TResponses[T]> {\n\t\tconst id = await this.options.redisClient.xadd(\n\t\t\tevent as string,\n\t\t\t'*',\n\t\t\tBaseRedisBroker.STREAM_DATA_KEY,\n\t\t\tthis.options.encode(data),\n\t\t);\n\t\t// This id! assertion is valid. From redis docs:\n\t\t// \"The command returns a Null reply when used with the NOMKSTREAM option and the key doesn't exist.\"\n\t\t// See: https://redis.io/commands/xadd/\n\t\tconst rpcChannel = `${event as string}:${id!}`;\n\n\t\t// Construct the error here for better stack traces\n\t\tconst timedOut = new Error(`timed out after ${timeoutDuration}ms`);\n\n\t\tawait this.streamReadClient.subscribe(rpcChannel);\n\t\treturn new Promise<TResponses[T]>((resolve, reject) => {\n\t\t\tconst timeout = setTimeout(() => reject(timedOut), timeoutDuration).unref();\n\n\t\t\tthis.promises.set(id!, { resolve, reject, timeout });\n\t\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\t}).finally(() => {\n\t\t\tvoid this.streamReadClient.unsubscribe(rpcChannel);\n\t\t\tthis.promises.delete(id!);\n\t\t});\n\t}\n\n\tprotected emitEvent(id: Buffer, group: string, event: string, data: unknown) {\n\t\tconst payload: { ack(): Promise<void>; data: unknown; reply(data: unknown): Promise<void> } = {\n\t\t\tdata,\n\t\t\tack: async () => {\n\t\t\t\tawait this.options.redisClient.xack(event, group, id);\n\t\t\t},\n\t\t\treply: async (data) => {\n\t\t\t\tawait this.options.redisClient.publish(`${event}:${id.toString()}`, this.options.encode(data));\n\t\t\t},\n\t\t};\n\n\t\tthis.emit(event, payload);\n\t}\n}\n"],"mappings":";;;;;;;;;AACA,SAAS,qBAAqB;AAC9B,OAAO,UAAU;AAE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Q,OAAOA,KAAI,CAAC;AAAA,MAC9F;AAAA,IACD;AAEA,SAAK,KAAK,OAAO,OAAO;AAAA,EACzB;AACD;AAzEa;","names":["Buffer","idx","data","resolve","data"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@discordjs/brokers",
|
|
3
|
+
"version": "0.2.0-dev.1665706585-bf9aa18.0",
|
|
4
|
+
"description": "Powerful set of message brokers",
|
|
5
|
+
"scripts": {
|
|
6
|
+
"test": "vitest run",
|
|
7
|
+
"build": "tsup",
|
|
8
|
+
"lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --format=pretty",
|
|
9
|
+
"format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix --format=pretty",
|
|
10
|
+
"fmt": "yarn format",
|
|
11
|
+
"docs": "api-extractor run --local",
|
|
12
|
+
"prepack": "yarn lint && yarn test && yarn build",
|
|
13
|
+
"changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/brokers/*'",
|
|
14
|
+
"release": "cliff-jumper"
|
|
15
|
+
},
|
|
16
|
+
"main": "./dist/index.js",
|
|
17
|
+
"module": "./dist/index.mjs",
|
|
18
|
+
"typings": "./dist/index.d.ts",
|
|
19
|
+
"exports": {
|
|
20
|
+
"import": "./dist/index.mjs",
|
|
21
|
+
"require": "./dist/index.js",
|
|
22
|
+
"types": "./dist/index.d.ts"
|
|
23
|
+
},
|
|
24
|
+
"directories": {
|
|
25
|
+
"lib": "src",
|
|
26
|
+
"test": "__tests__"
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"dist"
|
|
30
|
+
],
|
|
31
|
+
"contributors": [
|
|
32
|
+
"Crawl <icrawltogo@gmail.com>",
|
|
33
|
+
"Amish Shah <amishshah.2k@gmail.com>",
|
|
34
|
+
"SpaceEEC <spaceeec@yahoo.com>",
|
|
35
|
+
"Vlad Frangu <kingdgrizzle@gmail.com>",
|
|
36
|
+
"Aura Roman <kyradiscord@gmail.com>",
|
|
37
|
+
"DD <didinele.dev@gmail.com>"
|
|
38
|
+
],
|
|
39
|
+
"license": "Apache-2.0",
|
|
40
|
+
"keywords": [
|
|
41
|
+
"discord",
|
|
42
|
+
"api",
|
|
43
|
+
"message",
|
|
44
|
+
"brokers",
|
|
45
|
+
"redis",
|
|
46
|
+
"discordapp",
|
|
47
|
+
"discordjs"
|
|
48
|
+
],
|
|
49
|
+
"repository": {
|
|
50
|
+
"type": "git",
|
|
51
|
+
"url": "git+https://github.com/discordjs/discord.js.git"
|
|
52
|
+
},
|
|
53
|
+
"bugs": {
|
|
54
|
+
"url": "https://github.com/discordjs/discord.js/issues"
|
|
55
|
+
},
|
|
56
|
+
"homepage": "https://discord.js.org",
|
|
57
|
+
"dependencies": {
|
|
58
|
+
"@msgpack/msgpack": "^2.8.0",
|
|
59
|
+
"@vladfrangu/async_event_emitter": "^2.1.2",
|
|
60
|
+
"ioredis": "^5.2.3"
|
|
61
|
+
},
|
|
62
|
+
"devDependencies": {
|
|
63
|
+
"@favware/cliff-jumper": "^1.8.8",
|
|
64
|
+
"@microsoft/api-extractor": "^7.32.1",
|
|
65
|
+
"@types/node": "^16.11.52",
|
|
66
|
+
"@vitest/coverage-c8": "^0.22.1",
|
|
67
|
+
"cross-env": "^7.0.3",
|
|
68
|
+
"eslint": "^8.25.0",
|
|
69
|
+
"eslint-config-neon": "^0.1.38",
|
|
70
|
+
"eslint-formatter-pretty": "^4.1.0",
|
|
71
|
+
"prettier": "^2.7.1",
|
|
72
|
+
"tsup": "^6.2.3",
|
|
73
|
+
"typescript": "^4.8.4",
|
|
74
|
+
"vitest": "^0.22.1"
|
|
75
|
+
},
|
|
76
|
+
"engines": {
|
|
77
|
+
"node": ">=16.9.0"
|
|
78
|
+
},
|
|
79
|
+
"publishConfig": {
|
|
80
|
+
"access": "public"
|
|
81
|
+
}
|
|
82
|
+
}
|