@u-gotcha/eventbus 0.1.0 → 0.2.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/README.md +104 -0
- package/dist/eventbus-type.d.ts +14 -3
- package/dist/eventbus-type.d.ts.map +1 -1
- package/dist/eventbus.d.ts +10 -1
- package/dist/eventbus.d.ts.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +24 -12
- package/dist/index.js.map +1 -1
- package/package.json +25 -7
package/README.md
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# @u-gotcha/eventbus
|
|
2
|
+
|
|
3
|
+
Type-safe event bus for TypeScript. Topics and payloads are checked at compile time, and listener errors never escape `publish`.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @u-gotcha/eventbus
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
Define a map from topic names to payload types, then create a bus with it.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { EventBus } from "@u-gotcha/eventbus";
|
|
17
|
+
|
|
18
|
+
interface Events {
|
|
19
|
+
"user:login": { id: string };
|
|
20
|
+
"config:loaded": { theme: "dark" | "light" };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const bus = new EventBus<Events>();
|
|
24
|
+
|
|
25
|
+
const unsubscribe = bus.subscribe("user:login", (message) => {
|
|
26
|
+
console.log(message.payload.id); // typed as string
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
bus.publish({ topic: "user:login", payload: { id: "u1" } });
|
|
30
|
+
// -> u1
|
|
31
|
+
|
|
32
|
+
unsubscribe();
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
### Wait for several topics: `whenAll`
|
|
36
|
+
|
|
37
|
+
`whenAll` calls the listener once every listed topic has been published at least once, then resets and waits again.
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
bus.whenAll(["user:login", "config:loaded"], ([login, config]) => {
|
|
41
|
+
console.log(login.payload.id, config.payload.theme);
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
bus.publish({ topic: "config:loaded", payload: { theme: "dark" } });
|
|
45
|
+
bus.publish({ topic: "user:login", payload: { id: "u2" } });
|
|
46
|
+
// -> u2 dark
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## API
|
|
50
|
+
|
|
51
|
+
### `new EventBus<M>(onError?)`
|
|
52
|
+
|
|
53
|
+
Creates a bus. `M` maps each topic name to its payload type.
|
|
54
|
+
`onError` handles errors thrown by listeners. Defaults to `console.error`.
|
|
55
|
+
|
|
56
|
+
### `subscribe(topic, listener)`
|
|
57
|
+
|
|
58
|
+
Registers a listener for one topic. Returns a function that unsubscribes it.
|
|
59
|
+
|
|
60
|
+
### `publish(message, onError?)`
|
|
61
|
+
|
|
62
|
+
Calls every listener of `message.topic`. An `onError` passed here is used instead of the bus-wide one for this call.
|
|
63
|
+
|
|
64
|
+
### `whenAll(topics, listener)`
|
|
65
|
+
|
|
66
|
+
Registers a listener for several topics. Returns a function that unsubscribes from all of them.
|
|
67
|
+
|
|
68
|
+
- The listener is called when every topic has been published at least once since the last call.
|
|
69
|
+
- After the listener is called, it waits for every topic again.
|
|
70
|
+
- If a topic is published more than once while waiting, the latest message is used.
|
|
71
|
+
- Messages are passed in the order of `topics`, not in the order they were published.
|
|
72
|
+
- Messages published before `whenAll` was called are not counted.
|
|
73
|
+
- Passing the same topic twice is a type error.
|
|
74
|
+
|
|
75
|
+
### `Publisher<M>` / `Subscriber<M>`
|
|
76
|
+
|
|
77
|
+
Interfaces that expose only `publish`, or only `subscribe` and `whenAll`. Use them to limit what each part of your app can do with the bus.
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
import type { Publisher, Subscriber } from "@u-gotcha/eventbus";
|
|
81
|
+
|
|
82
|
+
const publisher: Publisher<Events> = bus;
|
|
83
|
+
const subscriber: Subscriber<Events> = bus;
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Behavior
|
|
87
|
+
|
|
88
|
+
- **Errors never escape `publish`**: errors thrown by listeners, including rejected promises from async listeners, are passed to `onError`. Other listeners still run.
|
|
89
|
+
- **Errors in `onError`** are logged with `console.error` and do not escape either.
|
|
90
|
+
- **Stable during publish**: listeners added or removed while a `publish` is running do not affect that `publish`. They take effect from the next one.
|
|
91
|
+
|
|
92
|
+
## Changes in 0.2.0
|
|
93
|
+
|
|
94
|
+
- Added `whenAll`.
|
|
95
|
+
- The function returned by `subscribe` now returns `void` instead of `boolean`.
|
|
96
|
+
|
|
97
|
+
## License
|
|
98
|
+
|
|
99
|
+
MIT
|
|
100
|
+
|
|
101
|
+
## Note
|
|
102
|
+
|
|
103
|
+
This README was drafted with AI assistance.
|
|
104
|
+
The library code and tests were written by the author, with AI used as a code reviewer.
|
package/dist/eventbus-type.d.ts
CHANGED
|
@@ -17,11 +17,16 @@ type Message<M extends object, T extends keyof M> = {
|
|
|
17
17
|
* @param message 購読したいトピックに対応したメッセージ型
|
|
18
18
|
*/
|
|
19
19
|
type Listener<M extends object, T extends keyof M> = (message: Message<M, T>) => void | Promise<void>;
|
|
20
|
+
/** トピックの配列から、同じ順番のメッセージのタプルを作る */
|
|
21
|
+
type Messages<M extends object, T extends readonly (keyof M)[]> = {
|
|
22
|
+
[I in keyof T]: T[I] extends keyof M ? Message<M, T[I]> : never;
|
|
23
|
+
};
|
|
24
|
+
/** 全部そろったときに呼ばれる関数。メッセージのタプルを受け取る */
|
|
25
|
+
type AllListener<M extends object, T extends readonly (keyof M)[]> = (messages: Messages<M, T>) => void | Promise<void>;
|
|
20
26
|
/**
|
|
21
27
|
* 実行後にイベントハンドラーを購読解除するための関数
|
|
22
|
-
* @returns イベントハンドラーが削除できたかどうか
|
|
23
28
|
*/
|
|
24
|
-
type UnSubscriber = () =>
|
|
29
|
+
type UnSubscriber = () => void;
|
|
25
30
|
/**
|
|
26
31
|
* イベントの発行側がイベント発行時に発生するエラーに対して処理するためのエラーハンドラー
|
|
27
32
|
* @param message エラー発生時に発行していたメッセージオブジェクト
|
|
@@ -29,6 +34,10 @@ type UnSubscriber = () => boolean;
|
|
|
29
34
|
* @param error listenerの実行時に発生したエラー
|
|
30
35
|
*/
|
|
31
36
|
type OnError<M extends object> = <K extends keyof M>(message: Message<M, K>, listener: Listener<M, K>, error: unknown) => void;
|
|
37
|
+
/** タプルに同じ要素が2回以上あれば true */
|
|
38
|
+
type HasDuplicate<T extends readonly unknown[]> = T extends readonly [infer Head, ...infer Rest] ? Head extends Rest[number] ? true : HasDuplicate<Rest> : false;
|
|
39
|
+
/** 重複があれば、エラーメッセージの文字列型にする */
|
|
40
|
+
type NoDuplicate<T extends readonly unknown[]> = HasDuplicate<T> extends true ? "topicsに同じトピックが重複しています" : unknown;
|
|
32
41
|
/**
|
|
33
42
|
* EventBusに対して発行のみを許可するためのインターフェース
|
|
34
43
|
* @example
|
|
@@ -53,6 +62,8 @@ interface Publisher<M extends object> {
|
|
|
53
62
|
interface Subscriber<M extends object> {
|
|
54
63
|
/** トピックに対するリスナーを購読する */
|
|
55
64
|
subscribe<T extends keyof M>(topic: T, listener: Listener<M, T>): UnSubscriber;
|
|
65
|
+
/** 複数のトピックに対するリスナーを購読する */
|
|
66
|
+
whenAll<const T extends readonly (keyof M)[]>(topics: T & NoDuplicate<T>, listener: AllListener<M, T>): UnSubscriber;
|
|
56
67
|
}
|
|
57
|
-
export type { Message, Listener, UnSubscriber, OnError, Publisher, Subscriber, };
|
|
68
|
+
export type { Message, Listener, UnSubscriber, OnError, Publisher, Subscriber, Messages, AllListener, NoDuplicate };
|
|
58
69
|
//# sourceMappingURL=eventbus-type.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"eventbus-type.d.ts","sourceRoot":"","sources":["../src/eventbus-type.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,KAAK,OAAO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C,CAAC,EAAE,CAAC,CAAC,GAAG,YAAY,CAAC;IAE/E,2BAA2B;IAC3B,OAAO,CAAC,KAAK,CAAC,CAAC,SAAS,SAAS,CAAC,MAAM,CAAC,CAAC,EAAE,EACxC,MAAM,EAAE,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,EAC1B,QAAQ,EAAE,WAAW,CAAC,CAAC,EAAE,CAAC,CAAC,GAC5B,YAAY,CAAA;CAClB;AAED,YAAY,EACR,OAAO,EACP,QAAQ,EACR,YAAY,EACZ,OAAO,EACP,SAAS,EACT,UAAU,EACV,QAAQ,EACR,WAAW,EACX,WAAW,EACd,CAAC"}
|
package/dist/eventbus.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Message, Listener, UnSubscriber, OnError } from "./eventbus-type";
|
|
1
|
+
import type { Message, Listener, UnSubscriber, OnError, AllListener, NoDuplicate } from "./eventbus-type.js";
|
|
2
2
|
/**
|
|
3
3
|
* メッセージとイベントハンドラーを結ぶためのEventBus
|
|
4
4
|
*/
|
|
@@ -22,6 +22,15 @@ declare class EventBus<M extends object> {
|
|
|
22
22
|
* @param onError listener実行中に例外が発生した際に実行させたエラーハンドラー
|
|
23
23
|
*/
|
|
24
24
|
publish<K extends keyof M>(message: Message<M, K>, onError?: OnError<M>): void;
|
|
25
|
+
/**
|
|
26
|
+
* 関連する全てのイベントが実行されたことを確認してから実行するlisetnerを定義する。
|
|
27
|
+
*
|
|
28
|
+
* @this Subscriber
|
|
29
|
+
* @param topics
|
|
30
|
+
* @param listener
|
|
31
|
+
* @returns 実行後に関連するトピックの購読を解除する関数
|
|
32
|
+
*/
|
|
33
|
+
whenAll<const T extends readonly (keyof M)[]>(topics: T & NoDuplicate<T>, listener: AllListener<M, T>): UnSubscriber;
|
|
25
34
|
}
|
|
26
35
|
export { EventBus };
|
|
27
36
|
//# sourceMappingURL=eventbus.d.ts.map
|
package/dist/eventbus.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"eventbus.d.ts","sourceRoot":"","sources":["../src/eventbus.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACR,OAAO,EACP,QAAQ,EACR,YAAY,EACZ,OAAO,
|
|
1
|
+
{"version":3,"file":"eventbus.d.ts","sourceRoot":"","sources":["../src/eventbus.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACR,OAAO,EACP,QAAQ,EACR,YAAY,EACZ,OAAO,EAEP,WAAW,EACX,WAAW,EACd,MAAM,oBAAoB,CAAC;AAS5B;;GAEG;AACH,cAAM,QAAQ,CAAC,CAAC,SAAS,MAAM;;IAO3B;;;OAGG;gBACS,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;IAkChC;;;;;OAKG;IACH,SAAS,CAAC,CAAC,SAAS,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,YAAY;IAQ9E;;;;OAIG;IACH,OAAO,CAAC,CAAC,SAAS,MAAM,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,IAAI;IAiB9E;;;;;;;OAOG;IACH,OAAO,CAAC,KAAK,CAAC,CAAC,SAAS,SAAS,CAAC,MAAM,CAAC,CAAC,EAAE,EACxC,MAAM,EAAE,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,EAC1B,QAAQ,EAAE,WAAW,CAAC,CAAC,EAAE,CAAC,CAAC,GAC5B,YAAY;CAqClB;AAID,OAAO,EAAE,QAAQ,EAAE,CAAC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export * from "./eventbus";
|
|
2
|
-
export type * from "./eventbus-type";
|
|
1
|
+
export * from "./eventbus.js";
|
|
2
|
+
export type * from "./eventbus-type.js";
|
|
3
3
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,eAAe,CAAC;AAC9B,mBAAmB,oBAAoB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -5,24 +5,36 @@ var e = class {
|
|
|
5
5
|
constructor(e) {
|
|
6
6
|
this.#t = e ?? console.error;
|
|
7
7
|
}
|
|
8
|
+
#n(e, t, n) {
|
|
9
|
+
let r = (r) => {
|
|
10
|
+
try {
|
|
11
|
+
e(t, n, r);
|
|
12
|
+
} catch (e) {
|
|
13
|
+
console.error(`topic「${String(t.topic)}」のエラーハンドラで例外が発生しました。`, e);
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
try {
|
|
17
|
+
let e = n(t);
|
|
18
|
+
e instanceof Promise && e.catch((e) => r(e));
|
|
19
|
+
} catch (e) {
|
|
20
|
+
r(e);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
8
23
|
subscribe(e, t) {
|
|
9
24
|
let n = this.#e.get(e) ?? /* @__PURE__ */ new Set();
|
|
10
25
|
return n.add(t), this.#e.set(e, n), () => n.delete(t);
|
|
11
26
|
}
|
|
12
27
|
publish(e, t) {
|
|
13
|
-
let n = t ?? this.#t, r = Array.from(this.#e.get(e.topic) ?? [])
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
28
|
+
let n = t ?? this.#t, r = Array.from(this.#e.get(e.topic) ?? []);
|
|
29
|
+
for (let t of r) this.#n(n, e, t);
|
|
30
|
+
}
|
|
31
|
+
whenAll(e, t) {
|
|
32
|
+
let n = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Set(), i = Array.from(new Set(e)), a = i.map((e) => this.subscribe(e, (a) => {
|
|
33
|
+
if (n.set(e, a), r.add(e), !(r.size < i.length)) return r.clear(), t(i.map((e) => n.get(e)));
|
|
34
|
+
}));
|
|
35
|
+
return () => {
|
|
36
|
+
for (let e of a) e();
|
|
19
37
|
};
|
|
20
|
-
for (let t of r) try {
|
|
21
|
-
let n = t(e);
|
|
22
|
-
n instanceof Promise && n.catch((e) => i(t, e));
|
|
23
|
-
} catch (e) {
|
|
24
|
-
i(t, e);
|
|
25
|
-
}
|
|
26
38
|
}
|
|
27
39
|
};
|
|
28
40
|
export { e as EventBus };
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["EventBus","#onError","onError","listeners","#listenerMap","topic","
|
|
1
|
+
{"version":3,"file":"index.js","names":["EventBus","#onError","onError","errorHandler","message","listener","error","err","result","listeners","#listenerMap","topic","#assertError","latest","arrived","topicArray","topics","unsubscribers","t","unsubscribe"],"sources":["../src/eventbus.ts"],"sourcesContent":["import type {\n Message,\n Listener,\n UnSubscriber,\n OnError,\n Messages,\n AllListener,\n NoDuplicate\n} from \"./eventbus-type.js\";\n\n\n/** \n * 内部で使用するサブスクライバーの型\\\n * 内部で持つフィールドに型を持たせられないための対策\n */\ntype AnyListener = (message: never) => void | Promise<void>;\n\n/**\n * メッセージとイベントハンドラーを結ぶためのEventBus\n */\nclass EventBus<M extends object> {\n\n // トピックとトピックを購読したい関数の集合\n #listenerMap: Map<keyof M, Set<AnyListener>> = new Map();\n // EventBus全体で処理する共通のエラーハンドラー\n #onError: OnError<M>;\n\n /**\n * @param onError EventBus共通で処理したい関数。\\\n * 指定がない場合はエラーをログに出力するのみ(console.error)となる。\n */\n constructor(onError?: OnError<M>) {\n this.#onError = onError ?? console.error;\n }\n\n /**\n * 同期・非同期の両方で使う、例外を外に漏らさないエラー処理\n * @param onError ハンドリングしたいエラーハンドラー\n * @param message 発行されたメッセージ\n * @param listener 実際にエラーを放出したリスナー\n */\n #assertError<K extends keyof M>(\n onError: OnError<M>, message: Message<M, K>, listener: Listener<M, K>): void {\n\n const errorHandler = (error: unknown) => {\n try {\n onError(message, listener, error);\n } catch (err: unknown) {\n console.error(\n `topic「${String(message.topic)}」のエラーハンドラで例外が発生しました。`,\n err,\n );\n }\n }\n\n try {\n const result = listener(message);\n if (result instanceof Promise) {\n result.catch(error => errorHandler(error));\n }\n } catch (error: unknown) {\n errorHandler(error);\n }\n }\n\n /**\n * 購読したいメッセージを受け取って処理させたい関数を登録するためのsubscriber\n * @param topic 購読したいメッセージのキー\n * @param listener メッセージを受け取って処理させたい関数\n * @returns listenerをEventBusから解除するためのdispose関数\n */\n subscribe<K extends keyof M>(topic: K, listener: Listener<M, K>): UnSubscriber {\n const listeners = this.#listenerMap.get(topic) ?? new Set();\n listeners.add(listener);\n this.#listenerMap.set(topic, listeners);\n // 動的にTopicが増える設計の場合はset自体も削除する必要あり\n return () => listeners.delete(listener);\n }\n\n /**\n * イベントを発行しEventBusが管理しているlistenerを実行させる\n * @param message イベントとして飛ばしたいトピックとデータをまとめたメッセージ\n * @param onError listener実行中に例外が発生した際に実行させたエラーハンドラー\n */\n publish<K extends keyof M>(message: Message<M, K>, onError?: OnError<M>): void {\n\n const errorHandler = onError ?? this.#onError;\n // 元々登録されているlistenerを配列に変換して保持する\n // publish実行時点でのlistenerに対して操作を行うため、\n // subscribe内でのsubscribeやunsubscribeの影響を受けない\n const listeners = Array.from(this.#listenerMap.get(message.topic) ?? []);\n\n // #NOTE: listenerの引数の型であるMessage<M, K>のKをフィールドが持てないため、\n // AnyListener型で保持している。K自体は間違いなくmessage.topicの型であるため、\n // 型アサーションでListener<M, K>[]に変換している。\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n for (const listener of listeners as Listener<M, K>[]) {\n this.#assertError(errorHandler, message, listener);\n }\n }\n\n /**\n * 関連する全てのイベントが実行されたことを確認してから実行するlisetnerを定義する。\n * \n * @this Subscriber\n * @param topics \n * @param listener \n * @returns 実行後に関連するトピックの購読を解除する関数\n */\n whenAll<const T extends readonly (keyof M)[]>(\n topics: T & NoDuplicate<T>,\n listener: AllListener<M, T>,\n ): UnSubscriber {\n\n // トピックに対応したメッセージを管理するためのMap\n const latest = new Map<keyof M, Message<M, keyof M>>();\n // listenerに紐づくトピック全体を保持するためのSet\n const arrived = new Set<keyof M>();\n\n // トピックの重複を排除する\n const topicArray = Array.from(new Set(topics));\n\n const unsubscribers = topicArray.map((topic) =>\n\n // トピックごとにlistenerを登録していく\n this.subscribe(topic, (message) => {\n\n // それぞれのlistenerがお互いのtopicの状況を監視する\n latest.set(topic, message);\n arrived.add(topic);\n // まだ全部そろっていなければ待つ\n if (arrived.size < topicArray.length) {\n return;\n }\n // そろったらリセットしてから呼ぶ\n arrived.clear();\n // #NOTE: topicsの順にlatestから取り出すので、各要素は対応するトピックのMessage\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n const messages = topicArray.map((t) => latest.get(t)) as Messages<M, T>;\n return listener(messages);\n }),\n );\n\n return () => {\n for (const unsubscribe of unsubscribers) {\n unsubscribe();\n }\n };\n }\n}\n\n\n\nexport { EventBus };\n"],"mappings":";AAoBA,IAAMA,IAAN,MAAiC;CAG7B,qBAA+C,IAAI,IAAI;CAEvD;CAMA,YAAY,GAAsB;EAC9B,KAAKC,KAAWC,KAAW,QAAQ;CACvC;CAQA,GACI,GAAqB,GAAwB,GAAgC;EAE7E,IAAMC,KAAgB,MAAmB;GACrC,IAAI;IACA,EAAQC,GAASC,GAAUC,CAAK;GACpC,SAASC,GAAc;IACnB,QAAQ,MACJ,SAAS,OAAOH,EAAQ,KAAK,EAAE,uBAC/BG,CACJ;GACJ;EACJ;EAEA,IAAI;GACA,IAAMC,IAASH,EAASD,CAAO;GAC/B,AAAII,aAAkB,WAClBA,EAAO,OAAM,MAASL,EAAaG,CAAK,CAAC;EAEjD,SAASA,GAAgB;GACrB,EAAaA,CAAK;EACtB;CACJ;CAQA,UAA6B,GAAU,GAAwC;EAC3E,IAAMG,IAAY,KAAKC,GAAa,IAAIC,CAAK,qBAAK,IAAI,IAAI;EAI1D,OAHAF,EAAU,IAAIJ,CAAQ,GACtB,KAAKK,GAAa,IAAIC,GAAOF,CAAS,SAEzBA,EAAU,OAAOJ,CAAQ;CAC1C;CAOA,QAA2B,GAAwB,GAA4B;EAE3E,IAAMF,IAAeD,KAAW,KAAKD,IAI/BQ,IAAY,MAAM,KAAK,KAAKC,GAAa,IAAIN,EAAQ,KAAK,KAAK,CAAC,CAAC;EAMvE,KAAK,IAAMC,KAAYI,GACnB,KAAKG,GAAaT,GAAcC,GAASC,CAAQ;CAEzD;CAUA,QACI,GACA,GACY;EAGZ,IAAMQ,oBAAS,IAAI,IAAkC,GAE/CC,oBAAU,IAAI,IAAa,GAG3BC,IAAa,MAAM,KAAK,IAAI,IAAIC,CAAM,CAAC,GAEvCC,IAAgBF,EAAW,KAAK,MAGlC,KAAK,UAAUJ,IAAQ,MAAY;GAM/B,IAHAE,EAAO,IAAIF,GAAOP,CAAO,GACzBU,EAAQ,IAAIH,CAAK,GAEb,IAAQ,OAAOI,EAAW,SAQ9B,OAJAD,EAAQ,MAAM,GAIPT,EADUU,EAAW,KAAK,MAAMF,EAAO,IAAIK,CAAC,CACnC,CAAQ;EAC5B,CAAC,CACL;EAEA,aAAa;GACT,KAAK,IAAMC,KAAeF,GACtB,EAAY;EAEpB;CACJ;AACJ"}
|
package/package.json
CHANGED
|
@@ -1,25 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@u-gotcha/eventbus",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Type-safe event bus",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Type-safe event bus for TypeScript with compile-time checked topics and payloads, safe error handling and multi-topic listeners",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"eventbus",
|
|
7
|
+
"event-bus",
|
|
8
|
+
"events",
|
|
9
|
+
"pubsub",
|
|
10
|
+
"publish-subscribe",
|
|
11
|
+
"emitter",
|
|
12
|
+
"typescript",
|
|
13
|
+
"type-safe"
|
|
14
|
+
],
|
|
5
15
|
"license": "MIT",
|
|
16
|
+
"author": "umeko_gotcha",
|
|
6
17
|
"repository": {
|
|
7
18
|
"type": "git",
|
|
8
19
|
"url": "git+https://github.com/umeko-gotcha/common-ts.git",
|
|
9
20
|
"directory": "packages/eventbus"
|
|
10
21
|
},
|
|
11
|
-
"
|
|
22
|
+
"homepage": "https://github.com/umeko-gotcha/common-ts/tree/main/packages/eventbus#readme",
|
|
23
|
+
"bugs": {
|
|
24
|
+
"url": "https://github.com/umeko-gotcha/common-ts/issues"
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"type": "module",
|
|
12
30
|
"exports": {
|
|
13
31
|
".": {
|
|
14
32
|
"types": "./dist/index.d.ts",
|
|
15
33
|
"import": "./dist/index.js"
|
|
16
34
|
}
|
|
17
35
|
},
|
|
18
|
-
"files": [
|
|
36
|
+
"files": [
|
|
37
|
+
"dist"
|
|
38
|
+
],
|
|
19
39
|
"scripts": {
|
|
20
40
|
"build": "vite build && tsc -p tsconfig.json",
|
|
21
41
|
"prepublishOnly": "npm run build"
|
|
22
|
-
}
|
|
23
|
-
"keywords": [],
|
|
24
|
-
"type": "module"
|
|
42
|
+
}
|
|
25
43
|
}
|