fastevent 2.0.2 → 2.1.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/dist/devTools.js +1 -1
- package/dist/devTools.js.map +1 -1
- package/dist/devTools.mjs +1 -1
- package/dist/devTools.mjs.map +1 -1
- package/dist/eventbus/index.d.mts +1005 -0
- package/dist/eventbus/index.d.ts +1005 -0
- package/dist/eventbus/index.js +2 -0
- package/dist/eventbus/index.js.map +1 -0
- package/dist/eventbus/index.mjs +2 -0
- package/dist/eventbus/index.mjs.map +1 -0
- package/dist/executors/index.d.mts +147 -0
- package/dist/executors/index.d.ts +147 -0
- package/dist/executors/index.js +2 -0
- package/dist/executors/index.js.map +1 -0
- package/dist/executors/index.mjs +2 -0
- package/dist/executors/index.mjs.map +1 -0
- package/dist/index.d.mts +255 -144
- package/dist/index.d.ts +255 -144
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/pipes/index.d.mts +115 -0
- package/dist/pipes/index.d.ts +115 -0
- package/dist/pipes/index.js +2 -0
- package/dist/pipes/index.js.map +1 -0
- package/dist/pipes/index.mjs +2 -0
- package/dist/pipes/index.mjs.map +1 -0
- package/package.json +18 -3
- package/readme.md +217 -772
package/dist/index.d.ts
CHANGED
|
@@ -3,7 +3,6 @@ type FastListenerPipe = (listener: FastEventListener) => FastEventListener;
|
|
|
3
3
|
interface FaseEventMessageExtends {
|
|
4
4
|
}
|
|
5
5
|
interface FastEventMeta {
|
|
6
|
-
priority?: number;
|
|
7
6
|
}
|
|
8
7
|
type FastEventMessage<Events extends Record<string, any> = Record<string, any>, M = any> = ({
|
|
9
8
|
[K in keyof Events]: {
|
|
@@ -16,7 +15,7 @@ type FastEventEmitMessage<Events extends Record<string, any> = Record<string, an
|
|
|
16
15
|
[K in keyof Events]: {
|
|
17
16
|
type: Exclude<K, number | symbol>;
|
|
18
17
|
payload?: Events[K];
|
|
19
|
-
meta?: FastEventMeta & M & Record<string, any>;
|
|
18
|
+
meta?: Partial<FastEventMeta> & M & Record<string, any>;
|
|
20
19
|
};
|
|
21
20
|
}[Exclude<keyof Events, number | symbol>]) & FaseEventMessageExtends;
|
|
22
21
|
type FastEventListener<T extends string = string, P = any, M = any, C = any> = (this: C, message: FastEventMessage<{
|
|
@@ -35,7 +34,7 @@ type FastListenerNode = {
|
|
|
35
34
|
type FastEventSubscriber = {
|
|
36
35
|
off: () => void;
|
|
37
36
|
/**
|
|
38
|
-
* 为什么要有一个listener引用?
|
|
37
|
+
* 为什么要有一个listener引用? 主要用于移除监听器时使用
|
|
39
38
|
*
|
|
40
39
|
* - 正常情况下
|
|
41
40
|
* const subscriber = emitter.on('event', listener)
|
|
@@ -51,11 +50,11 @@ type FastEventSubscriber = {
|
|
|
51
50
|
* subscriber.off() 可以正常生效
|
|
52
51
|
* scope.off('event', listener) // 无法生效
|
|
53
52
|
* scope.off(listener) // 无法生效
|
|
54
|
-
* 因为在scope
|
|
55
|
-
* 因此在事件注册表中登记的不是listener
|
|
53
|
+
* 因为在scope中,为了让监听器可以处理scope的逻辑,对listener进行了包装,
|
|
54
|
+
* 因此在事件注册表中登记的不是listener,而是经过包装的监听器
|
|
56
55
|
* subscriber.off() 可以正常生效
|
|
57
56
|
* 如果要使用scope.off或emitter.off
|
|
58
|
-
* 需要使用subscriber.listener, subscriber.listener
|
|
57
|
+
* 需要使用subscriber.listener, subscriber.listener记录了原始的监听器引用
|
|
59
58
|
* subscriber.listener===listener
|
|
60
59
|
*
|
|
61
60
|
* scope.off('event', subscriber.listener) // 生效
|
|
@@ -66,26 +65,24 @@ type FastEventSubscriber = {
|
|
|
66
65
|
};
|
|
67
66
|
type FastListeners = FastListenerNode;
|
|
68
67
|
type FastEventOptions<Meta = Record<string, any>, Context = any> = {
|
|
69
|
-
id
|
|
70
|
-
debug
|
|
71
|
-
delimiter
|
|
72
|
-
context
|
|
73
|
-
ignoreErrors
|
|
74
|
-
meta
|
|
75
|
-
onAddListener?: (type: string
|
|
76
|
-
onRemoveListener?: (type: string
|
|
68
|
+
id: string;
|
|
69
|
+
debug: boolean;
|
|
70
|
+
delimiter: string;
|
|
71
|
+
context: Context;
|
|
72
|
+
ignoreErrors: boolean;
|
|
73
|
+
meta: Meta;
|
|
74
|
+
onAddListener?: (type: string, listener: FastEventListener, options: FastEventListenOptions<Record<string, any>, Meta>) => boolean | FastEventSubscriber | void;
|
|
75
|
+
onRemoveListener?: (type: string, listener: FastEventListener) => void;
|
|
77
76
|
onClearListeners?: () => void;
|
|
78
|
-
onListenerError?: ((
|
|
79
|
-
onBeforeExecuteListener?: (message: FastEventMessage<any, Meta>, args: FastEventListenerArgs<Meta>) => boolean | void;
|
|
77
|
+
onListenerError?: ((error: Error, listener: FastEventListener, message: FastEventMessage<any, Meta>, args: FastEventListenerArgs<Meta> | undefined) => void);
|
|
78
|
+
onBeforeExecuteListener?: (message: FastEventMessage<any, Meta>, args: FastEventListenerArgs<Meta>) => boolean | void | any[];
|
|
80
79
|
onAfterExecuteListener?: (message: FastEventMessage<any, Meta>, returns: any[], listeners: FastListenerNode[]) => void;
|
|
81
80
|
/**
|
|
82
81
|
* 全局执行器
|
|
83
|
-
* allSettled: 使用Promise.allSettled()执行所有监听器
|
|
84
|
-
* race: 使用Promise.race()执行所有监听器,只有第一个执行完成就返回,其他监听器执行结果会被忽略
|
|
85
|
-
* balance: 尽可能平均执行各个侦听器
|
|
86
|
-
* sequence: 按照侦听器添加顺序依次执行
|
|
87
82
|
*/
|
|
88
|
-
executor?:
|
|
83
|
+
executor?: FastListenerExecutor;
|
|
84
|
+
onMessage?: FastEventListener;
|
|
85
|
+
expandEmitResults?: boolean;
|
|
89
86
|
};
|
|
90
87
|
interface FastEvents {
|
|
91
88
|
}
|
|
@@ -100,7 +97,6 @@ type FastEventListenOptions<Events extends Record<string, any> = Record<string,
|
|
|
100
97
|
off?: (message: FastEventMessage<Events, Meta>, args: FastEventListenerArgs<Meta>) => boolean;
|
|
101
98
|
pipes?: FastListenerPipe[];
|
|
102
99
|
};
|
|
103
|
-
type FastListenerExecutorArgs = 'default' | 'allSettled' | 'race' | 'balance' | 'first' | 'last' | 'random' | IFastListenerExecutor;
|
|
104
100
|
type FastEventListenerArgs<M = Record<string, any>> = {
|
|
105
101
|
retain?: boolean;
|
|
106
102
|
meta?: Partial<M> & Record<string, any>;
|
|
@@ -109,10 +105,14 @@ type FastEventListenerArgs<M = Record<string, any>> = {
|
|
|
109
105
|
*
|
|
110
106
|
* allSettled: 使用Promise.allSettled()执行所有监听器
|
|
111
107
|
* race: 使用Promise.race()执行所有监听器,只有第一个执行完成就返回,其他监听器执行结果会被忽略
|
|
112
|
-
* balance:
|
|
113
|
-
* sequence:
|
|
108
|
+
* balance: 尽可能平均执行各个监听器
|
|
109
|
+
* sequence: 按照监听器添加顺序依次执行
|
|
110
|
+
*/
|
|
111
|
+
executor?: FastListenerExecutor;
|
|
112
|
+
/**
|
|
113
|
+
* 当emit参数解析完成后的回调,用于修改emit参数
|
|
114
114
|
*/
|
|
115
|
-
|
|
115
|
+
parseArgs?: (message: FastEventMessage, args: FastEventListenerArgs) => void;
|
|
116
116
|
};
|
|
117
117
|
type Merge<T extends object, U extends object> = {
|
|
118
118
|
[K in keyof T | keyof U]: K extends keyof U ? U[K] : K extends keyof T ? T[K] : never;
|
|
@@ -120,26 +120,155 @@ type Merge<T extends object, U extends object> = {
|
|
|
120
120
|
type RequiredItems<T extends object, Items extends string[]> = Omit<T, Items[number]> & {
|
|
121
121
|
[K in Items[number] & keyof T]-?: Exclude<T[K], undefined>;
|
|
122
122
|
};
|
|
123
|
+
type Expand<T> = T extends infer O ? {
|
|
124
|
+
[K in keyof O]: O[K];
|
|
125
|
+
} : never;
|
|
126
|
+
type OptionalItems<T, K extends keyof T> = Expand<Omit<T, K> & {
|
|
127
|
+
[P in K]?: T[P];
|
|
128
|
+
}>;
|
|
129
|
+
type DeepPartial<T> = {
|
|
130
|
+
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
|
|
131
|
+
};
|
|
123
132
|
type Fallback<T, F> = [
|
|
124
133
|
T
|
|
125
134
|
] extends [never] ? F : T extends undefined ? F : T;
|
|
126
|
-
type
|
|
135
|
+
type ChangeFieldType<Record, Name extends string, Type = any> = Expand<Omit<Record, Name> & {
|
|
136
|
+
[K in Name]: Type;
|
|
137
|
+
}>;
|
|
138
|
+
type OverrideOptions<T> = ChangeFieldType<Required<T>, 'context', never>;
|
|
139
|
+
type ObjectKeys<T, I = string> = {
|
|
140
|
+
[P in keyof T]: P extends I ? P : never;
|
|
141
|
+
}[keyof T];
|
|
142
|
+
/**
|
|
143
|
+
* 从类型数组中移除重复项,返回保留唯一类型的元组
|
|
144
|
+
* @template T - 输入的任意类型数组(元组)
|
|
145
|
+
* @template Result - 内部使用的累积结果数组(默认空数组)
|
|
146
|
+
* @returns {any[]} 去重后的类型元组,保留首次出现的顺序
|
|
147
|
+
*
|
|
148
|
+
* @example
|
|
149
|
+
* type T1 = Unique<[number, string, number]>; // [number, string]
|
|
150
|
+
* type T2 = Unique<[1, 2, 2, 3]>; // [1, 2, 3]
|
|
151
|
+
* type T3 = Unique<['a', 'b', 'a']>; // ['a', 'b']
|
|
152
|
+
*/
|
|
153
|
+
type Unique<T extends any[], Result extends any[] = []> = T extends [infer First, ...infer Rest] ? First extends Result[number] ? Unique<Rest, Result> : Unique<Rest, [...Result, First]> : Result;
|
|
154
|
+
type Overloads<T> = Unique<T extends {
|
|
155
|
+
(...args: infer A1): infer R1;
|
|
156
|
+
(...args: infer A2): infer R2;
|
|
157
|
+
(...args: infer A3): infer R3;
|
|
158
|
+
(...args: infer A4): infer R4;
|
|
159
|
+
(...args: infer A5): infer R5;
|
|
160
|
+
(...args: infer A6): infer R6;
|
|
161
|
+
(...args: infer A7): infer R7;
|
|
162
|
+
(...args: infer A8): infer R8;
|
|
163
|
+
} ? [
|
|
164
|
+
(...args: A1) => R1,
|
|
165
|
+
((...args: A2) => R2),
|
|
166
|
+
((...args: A3) => R3),
|
|
167
|
+
((...args: A4) => R4),
|
|
168
|
+
((...args: A5) => R5),
|
|
169
|
+
((...args: A6) => R6),
|
|
170
|
+
((...args: A7) => R7),
|
|
171
|
+
((...args: A8) => R8)
|
|
172
|
+
] : T extends {
|
|
173
|
+
(...args: infer A1): infer R1;
|
|
174
|
+
(...args: infer A2): infer R2;
|
|
175
|
+
(...args: infer A3): infer R3;
|
|
176
|
+
(...args: infer A4): infer R4;
|
|
177
|
+
(...args: infer A5): infer R5;
|
|
178
|
+
(...args: infer A6): infer R6;
|
|
179
|
+
(...args: infer A7): infer R7;
|
|
180
|
+
} ? [
|
|
181
|
+
(...args: A1) => R1,
|
|
182
|
+
((...args: A2) => R2),
|
|
183
|
+
((...args: A3) => R3),
|
|
184
|
+
((...args: A4) => R4),
|
|
185
|
+
((...args: A5) => R5),
|
|
186
|
+
((...args: A6) => R6),
|
|
187
|
+
((...args: A7) => R7)
|
|
188
|
+
] : T extends {
|
|
189
|
+
(...args: infer A1): infer R1;
|
|
190
|
+
(...args: infer A2): infer R2;
|
|
191
|
+
(...args: infer A3): infer R3;
|
|
192
|
+
(...args: infer A4): infer R4;
|
|
193
|
+
(...args: infer A5): infer R5;
|
|
194
|
+
(...args: infer A6): infer R6;
|
|
195
|
+
} ? [
|
|
196
|
+
(...args: A1) => R1,
|
|
197
|
+
((...args: A2) => R2),
|
|
198
|
+
((...args: A3) => R3),
|
|
199
|
+
((...args: A4) => R4),
|
|
200
|
+
((...args: A5) => R5),
|
|
201
|
+
((...args: A6) => R6)
|
|
202
|
+
] : T extends {
|
|
203
|
+
(...args: infer A1): infer R1;
|
|
204
|
+
(...args: infer A2): infer R2;
|
|
205
|
+
(...args: infer A3): infer R3;
|
|
206
|
+
(...args: infer A4): infer R4;
|
|
207
|
+
(...args: infer A5): infer R5;
|
|
208
|
+
} ? [
|
|
209
|
+
(...args: A1) => R1,
|
|
210
|
+
((...args: A2) => R2),
|
|
211
|
+
((...args: A3) => R3),
|
|
212
|
+
((...args: A4) => R4),
|
|
213
|
+
((...args: A5) => R5)
|
|
214
|
+
] : T extends {
|
|
215
|
+
(...args: infer A1): infer R1;
|
|
216
|
+
(...args: infer A2): infer R2;
|
|
217
|
+
(...args: infer A3): infer R3;
|
|
218
|
+
(...args: infer A4): infer R4;
|
|
219
|
+
} ? [
|
|
220
|
+
(...args: A1) => R1,
|
|
221
|
+
((...args: A2) => R2),
|
|
222
|
+
((...args: A3) => R3),
|
|
223
|
+
((...args: A4) => R4)
|
|
224
|
+
] : T extends {
|
|
225
|
+
(...args: infer A1): infer R1;
|
|
226
|
+
(...args: infer A2): infer R2;
|
|
227
|
+
(...args: infer A3): infer R3;
|
|
228
|
+
} ? [
|
|
229
|
+
((...args: A1) => R1),
|
|
230
|
+
((...args: A2) => R2),
|
|
231
|
+
((...args: A3) => R3)
|
|
232
|
+
] : T extends {
|
|
233
|
+
(...args: infer A1): infer R1;
|
|
234
|
+
(...args: infer A2): infer R2;
|
|
235
|
+
} ? [
|
|
236
|
+
((...args: A1) => R1),
|
|
237
|
+
((...args: A2) => R2)
|
|
238
|
+
] : T extends {
|
|
239
|
+
(...args: infer A1): infer R1;
|
|
240
|
+
} ? [
|
|
241
|
+
(...args: A1) => R1
|
|
242
|
+
] : [
|
|
243
|
+
T
|
|
244
|
+
]>;
|
|
245
|
+
type Dict<V = any> = Record<Exclude<string, number | symbol>, V>;
|
|
246
|
+
|
|
247
|
+
type FastListenerExecutor = (listeners: FastListenerMeta[], message: FastEventMessage, args: FastEventListenerArgs, execute: (listener: FastEventListener, message: FastEventMessage, args: FastEventListenerArgs, catchErrors?: boolean) => Promise<any> | any) => Promise<any[]> | any[];
|
|
127
248
|
|
|
128
|
-
type FastEventScopeOptions<Meta, Context> = {
|
|
129
|
-
meta
|
|
130
|
-
context
|
|
131
|
-
executor?:
|
|
249
|
+
type FastEventScopeOptions<Meta = Record<string, any>, Context = any> = {
|
|
250
|
+
meta: FastEventScopeMeta & FastEventMeta & Meta;
|
|
251
|
+
context: Context;
|
|
252
|
+
executor?: FastListenerExecutor;
|
|
253
|
+
onMessage?: FastEventListener;
|
|
132
254
|
};
|
|
133
255
|
type FastEventScopeMeta = {
|
|
134
256
|
scope: string;
|
|
135
257
|
};
|
|
136
|
-
declare class FastEventScope<Events extends Record<string, any> = Record<string, any>, Meta extends Record<string, any> = Record<string, any>, Context =
|
|
137
|
-
|
|
258
|
+
declare class FastEventScope<Events extends Record<string, any> = Record<string, any>, Meta extends Record<string, any> = Record<string, any>, Context = never, Types extends keyof Events = keyof Events, FinalMeta extends Record<string, any> = FastEventMeta & FastEventScopeMeta & Meta> {
|
|
259
|
+
__FastEventScope__: boolean;
|
|
260
|
+
private _options;
|
|
261
|
+
types: {
|
|
262
|
+
events: Events;
|
|
263
|
+
meta: FinalMeta;
|
|
264
|
+
context: Fallback<Context, typeof this>;
|
|
265
|
+
};
|
|
138
266
|
prefix: string;
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
get
|
|
267
|
+
emitter: FastEvent<Events>;
|
|
268
|
+
constructor(options?: DeepPartial<FastEventScopeOptions<FinalMeta, Context>>);
|
|
269
|
+
get context(): Fallback<Context, typeof this>;
|
|
270
|
+
get options(): FastEventScopeOptions<FinalMeta, Context>;
|
|
271
|
+
bind(emitter: FastEvent<any>, prefix: string, options?: DeepPartial<FastEventScopeOptions<FinalMeta, Context>>): void;
|
|
143
272
|
/**
|
|
144
273
|
* 获取作用域监听器
|
|
145
274
|
* 当启用作用域时,对原始监听器进行包装,添加作用域前缀处理逻辑
|
|
@@ -150,14 +279,20 @@ declare class FastEventScope<Events extends Record<string, any> = Record<string,
|
|
|
150
279
|
private _getScopeListener;
|
|
151
280
|
private _getScopeType;
|
|
152
281
|
private _fixScopeType;
|
|
153
|
-
on<T extends Types = Types>(type: T,
|
|
154
|
-
on<T extends string>(type: T,
|
|
155
|
-
on(type: '**',
|
|
156
|
-
|
|
157
|
-
|
|
282
|
+
on<T extends Types = Types>(type: T, options?: FastEventListenOptions<Events, FinalMeta>): FastEventSubscriber;
|
|
283
|
+
on<T extends string>(type: T, options?: FastEventListenOptions<Events, FinalMeta>): FastEventSubscriber;
|
|
284
|
+
on(type: '**', options?: FastEventListenOptions<Events, FinalMeta>): FastEventSubscriber;
|
|
285
|
+
on<T extends Types = Types>(type: T, listener: FastEventListener<Exclude<T, number | symbol>, Events[T], FinalMeta, Fallback<Context, typeof this>>, options?: FastEventListenOptions): FastEventSubscriber;
|
|
286
|
+
on<T extends string>(type: T, listener: FastEventListener<string, any, FinalMeta, Fallback<Context, typeof this>>, options?: FastEventListenOptions): FastEventSubscriber;
|
|
287
|
+
on(type: '**', listener: FastEventAnyListener<Events, FinalMeta, Fallback<Context, typeof this>>, options?: FastEventListenOptions): FastEventSubscriber;
|
|
288
|
+
once<T extends Types = Types>(type: T, options?: FastEventListenOptions<Events, FinalMeta>): FastEventSubscriber;
|
|
289
|
+
once<T extends string>(type: T, options?: FastEventListenOptions<Events, FinalMeta>): FastEventSubscriber;
|
|
290
|
+
once<T extends Types = Types>(type: T, listener: FastEventListener<Exclude<T, number | symbol>, Events[T], FinalMeta, Fallback<Context, typeof this>>, options?: FastEventListenOptions): FastEventSubscriber;
|
|
291
|
+
once<T extends string>(type: T, listener: FastEventListener<string, any, FinalMeta, Fallback<Context, typeof this>>, options?: FastEventListenOptions): FastEventSubscriber;
|
|
292
|
+
onAny(options?: Pick<FastEventListenOptions, 'prepend'>): FastEventSubscriber;
|
|
158
293
|
onAny<P = any>(listener: FastEventAnyListener<{
|
|
159
294
|
[K: string]: P;
|
|
160
|
-
}, FinalMeta, Context
|
|
295
|
+
}, FinalMeta, Fallback<Context, typeof this>>, options?: Pick<FastEventListenOptions, 'prepend'>): FastEventSubscriber;
|
|
161
296
|
off(listener: FastEventListener<any, any, any>): void;
|
|
162
297
|
off(type: string, listener: FastEventListener<any, any, any>): void;
|
|
163
298
|
off(type: Types, listener: FastEventListener<any, any, any>): void;
|
|
@@ -165,6 +300,8 @@ declare class FastEventScope<Events extends Record<string, any> = Record<string,
|
|
|
165
300
|
off(type: Types): void;
|
|
166
301
|
offAll(): void;
|
|
167
302
|
clear(): void;
|
|
303
|
+
emit(type: Types, directive: symbol): void;
|
|
304
|
+
emit(type: string, directive: symbol): void;
|
|
168
305
|
emit<R = any>(type: Types, payload?: Events[Types], options?: FastEventListenerArgs<FinalMeta>): R[];
|
|
169
306
|
emit<R = any, T extends string = string>(type: T, payload?: T extends Types ? Events[Types] : any, options?: FastEventListenerArgs<FinalMeta>): R[];
|
|
170
307
|
emit<R = any>(message: FastEventEmitMessage<Events, FinalMeta>, options?: FastEventListenerArgs<FinalMeta>): R[];
|
|
@@ -215,7 +352,13 @@ declare class FastEventScope<Events extends Record<string, any> = Record<string,
|
|
|
215
352
|
* profileScope.emit('update', { name: 'John' });
|
|
216
353
|
* ```
|
|
217
354
|
*/
|
|
218
|
-
scope<E extends Record<string, any> = Record<string, any>, P extends string = string, M extends Record<string, any> = Record<string, any>, C = Context>(prefix: P, options?: FastEventScopeOptions<Partial<FinalMeta> & M, C
|
|
355
|
+
scope<E extends Record<string, any> = Record<string, any>, P extends string = string, M extends Record<string, any> = Record<string, any>, C = Context>(prefix: P, options?: DeepPartial<FastEventScopeOptions<Partial<FinalMeta> & M, C>>): FastEventScope<ScopeEvents<Events, P> & E, FinalMeta & M, C>;
|
|
356
|
+
scope<E extends Record<string, any> = Record<string, any>, P extends string = string, M extends Record<string, any> = Record<string, any>, C = Context, ScopeInstance extends FastEventScope<any, any, any> = FastEventScope<ScopeEvents<ScopeEvents<Events, P> & E, P> & E, FinalMeta & M, C>>(prefix: P, scopeObj: ScopeInstance, options?: DeepPartial<FastEventScopeOptions<Partial<FinalMeta> & M, C>>): ScopeInstance;
|
|
357
|
+
/**
|
|
358
|
+
* 当on/once/onAny未指定监听器时,此为默认监听器
|
|
359
|
+
* @param message
|
|
360
|
+
*/
|
|
361
|
+
onMessage(message: FastEventMessage<Events, FinalMeta>, args: FastEventListenerArgs<FinalMeta>): void;
|
|
219
362
|
}
|
|
220
363
|
|
|
221
364
|
/**
|
|
@@ -225,7 +368,8 @@ declare class FastEventScope<Events extends Record<string, any> = Record<string,
|
|
|
225
368
|
* @template Meta - 事件元数据类型,默认为任意键值对对象
|
|
226
369
|
* @template Types - 事件类型的键名类型,默认为Events的键名类型
|
|
227
370
|
*/
|
|
228
|
-
declare class FastEvent<Events extends Record<string, any> = Record<string, any>, Meta extends Record<string, any> = Record<string, any>, Context = never, AllEvents extends Record<string, any> = Events & FastEvents, Types extends keyof AllEvents = Exclude<keyof (AllEvents), number | symbol
|
|
371
|
+
declare class FastEvent<Events extends Record<string, any> = Record<string, any>, Meta extends Record<string, any> = Record<string, any>, Context = never, AllEvents extends Record<string, any> = Events & FastEvents, Types extends keyof AllEvents = Expand<Exclude<keyof (AllEvents), number | symbol>>> {
|
|
372
|
+
__FastEvent__: boolean;
|
|
229
373
|
/** 事件监听器树结构,存储所有注册的事件监听器 */
|
|
230
374
|
listeners: FastListeners;
|
|
231
375
|
/** 事件发射器的配置选项 */
|
|
@@ -234,11 +378,15 @@ declare class FastEvent<Events extends Record<string, any> = Record<string, any>
|
|
|
234
378
|
private _delimiter;
|
|
235
379
|
/** 事件监听器执行时的上下文对象 */
|
|
236
380
|
private _context;
|
|
237
|
-
/**
|
|
381
|
+
/** 保留的事件消息映射,Key是事件名称,Value是保留的事件消息 */
|
|
238
382
|
retainedMessages: Map<string, any>;
|
|
239
383
|
/** 当前注册的监听器总数 */
|
|
240
384
|
listenerCount: number;
|
|
241
|
-
|
|
385
|
+
types: {
|
|
386
|
+
events: AllEvents;
|
|
387
|
+
meta: Expand<FastEventMeta & Meta & Record<string, any>>;
|
|
388
|
+
context: Expand<Fallback<Context, typeof this>>;
|
|
389
|
+
};
|
|
242
390
|
/**
|
|
243
391
|
* 创建FastEvent实例
|
|
244
392
|
* @param options - 事件发射器的配置选项
|
|
@@ -250,17 +398,28 @@ declare class FastEvent<Events extends Record<string, any> = Record<string, any>
|
|
|
250
398
|
* - context: null - 监听器执行上下文
|
|
251
399
|
* - ignoreErrors: true - 是否忽略监听器执行错误
|
|
252
400
|
*/
|
|
253
|
-
constructor(options?: FastEventOptions<Meta, Context
|
|
401
|
+
constructor(options?: Partial<FastEventOptions<Meta, Context>>);
|
|
254
402
|
/** 获取事件发射器的配置选项 */
|
|
255
|
-
get options():
|
|
256
|
-
get context(): Context
|
|
403
|
+
get options(): FastEventOptions<Meta, Context>;
|
|
404
|
+
get context(): Fallback<Context, typeof this>;
|
|
405
|
+
get meta(): Meta;
|
|
257
406
|
/** 获取事件发射器的唯一标识符 */
|
|
258
407
|
get id(): string;
|
|
408
|
+
/**
|
|
409
|
+
* 添加事件监听器到事件树中
|
|
410
|
+
* @param parts - 事件路径数组
|
|
411
|
+
* @param listener - 事件监听器函数
|
|
412
|
+
* @param options - 监听器配置选项
|
|
413
|
+
* @param options.count - 监听器触发次数限制
|
|
414
|
+
* @param options.prepend - 是否将监听器添加到监听器列表开头
|
|
415
|
+
* @returns [节点, 监听器索引] - 返回监听器所在节点和在节点监听器列表中的索引
|
|
416
|
+
* @private
|
|
417
|
+
*/
|
|
259
418
|
private _addListener;
|
|
260
419
|
private _enableDevTools;
|
|
261
420
|
/**
|
|
262
421
|
*
|
|
263
|
-
* 根据parts
|
|
422
|
+
* 根据parts路径遍历监听器树,并在最后的节点上执行回调函数
|
|
264
423
|
*
|
|
265
424
|
* @param parts
|
|
266
425
|
* @param callback
|
|
@@ -354,7 +513,7 @@ declare class FastEvent<Events extends Record<string, any> = Record<string, any>
|
|
|
354
513
|
* 此方法供子类继承
|
|
355
514
|
*
|
|
356
515
|
*/
|
|
357
|
-
onMessage(message: FastEventMessage): void;
|
|
516
|
+
onMessage(message: FastEventMessage<AllEvents, Meta>, args: FastEventListenerArgs<Meta>): void;
|
|
358
517
|
off(listener: FastEventListener<any, any, any>): void;
|
|
359
518
|
off(type: string, listener: FastEventListener<any, any, any>): void;
|
|
360
519
|
off(type: Types, listener: FastEventListener<any, any, any>): void;
|
|
@@ -368,7 +527,7 @@ declare class FastEvent<Events extends Record<string, any> = Record<string, any>
|
|
|
368
527
|
* - 如果没有提供prefix,则清除所有监听器
|
|
369
528
|
* - 同时会清空保留的事件(_retainedEvents)
|
|
370
529
|
* - 重置监听器对象为空
|
|
371
|
-
|
|
530
|
+
|
|
372
531
|
* @example
|
|
373
532
|
*
|
|
374
533
|
* ```ts
|
|
@@ -386,7 +545,19 @@ declare class FastEvent<Events extends Record<string, any> = Record<string, any>
|
|
|
386
545
|
*/
|
|
387
546
|
private _removeRetainedEvents;
|
|
388
547
|
clear(prefix?: string): void;
|
|
389
|
-
|
|
548
|
+
/**
|
|
549
|
+
* 发送最后一次事件的消息给对应的监听器
|
|
550
|
+
*
|
|
551
|
+
* @param type - 事件类型,支持通配符(*)匹配
|
|
552
|
+
* @private
|
|
553
|
+
*
|
|
554
|
+
* 处理流程:
|
|
555
|
+
* 1. 如果事件类型包含通配符,则遍历所有保留的消息,匹配符合模式的事件
|
|
556
|
+
* 2. 如果是普通事件类型,则直接获取对应的保留消息
|
|
557
|
+
* 3. 遍历匹配到的消息,查找对应路径的监听器节点
|
|
558
|
+
* 4. 执行所有匹配到的监听器
|
|
559
|
+
*/
|
|
560
|
+
private _emitRetainMessage;
|
|
390
561
|
/**
|
|
391
562
|
* 遍历监听器节点树
|
|
392
563
|
* @param node 当前遍历的监听器节点
|
|
@@ -408,6 +579,8 @@ declare class FastEvent<Events extends Record<string, any> = Record<string, any>
|
|
|
408
579
|
* 执行单个监听器函数
|
|
409
580
|
* @param listener - 要执行的监听器函数或包装过的监听器对象
|
|
410
581
|
* @param message - 事件消息对象,包含type、payload和meta
|
|
582
|
+
* @param args - 监听器参数
|
|
583
|
+
* @param catchErrors - 是否捕获并处理执行过程中的错误
|
|
411
584
|
* @returns 监听器的执行结果或错误对象(如果配置了ignoreErrors)
|
|
412
585
|
* @private
|
|
413
586
|
*
|
|
@@ -424,23 +597,18 @@ declare class FastEvent<Events extends Record<string, any> = Record<string, any>
|
|
|
424
597
|
private _executeListener;
|
|
425
598
|
private _getListenerExecutor;
|
|
426
599
|
/**
|
|
427
|
-
*
|
|
428
|
-
* @param
|
|
429
|
-
* @param
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
* 执行监听器节点中的所有监听函数
|
|
434
|
-
* @param node - FastListenerNode类型的监听器节点
|
|
435
|
-
* @param payload - 事件携带的数据
|
|
436
|
-
* @param type - 事件类型
|
|
437
|
-
* @returns 返回所有监听函数的执行结果数组
|
|
600
|
+
* 执行监听器节点列表中的所有监听器函数
|
|
601
|
+
* @param nodes 监听器节点列表
|
|
602
|
+
* @param message 事件消息对象
|
|
603
|
+
* @param args 监听器参数
|
|
604
|
+
* @param args 监听器参数
|
|
605
|
+
* @returns 所有监听器函数的执行结果数组
|
|
438
606
|
* @private
|
|
439
607
|
*
|
|
440
|
-
*
|
|
441
|
-
*
|
|
442
|
-
*
|
|
443
|
-
*
|
|
608
|
+
* 执行流程:
|
|
609
|
+
* 1. 将所有节点中的监听器函数展平为一维数组
|
|
610
|
+
* 2. 通过执行器执行所有监听器函数
|
|
611
|
+
* 3. 更新监听器的执行次数,并移除达到执行次数限制的监听器
|
|
444
612
|
*/
|
|
445
613
|
private _executeListeners;
|
|
446
614
|
/**
|
|
@@ -495,8 +663,14 @@ declare class FastEvent<Events extends Record<string, any> = Record<string, any>
|
|
|
495
663
|
* payload: { userId: 123 },
|
|
496
664
|
* meta: { time: Date.now() }
|
|
497
665
|
* }, true);
|
|
666
|
+
*
|
|
667
|
+
* // 清除保留事件
|
|
668
|
+
* emitter.emit("user/login")
|
|
669
|
+
*
|
|
498
670
|
* ```
|
|
499
671
|
*/
|
|
672
|
+
emit<T extends Types = Types>(type: T, directive: symbol): any[];
|
|
673
|
+
emit(type: string, directive: symbol): any[];
|
|
500
674
|
emit<R = any, T extends Types = Types>(type: T, payload?: AllEvents[T], retain?: boolean): R[];
|
|
501
675
|
emit<R = any, T extends string = string>(type: T, payload?: T extends Types ? AllEvents[Types] : any, retain?: boolean): R[];
|
|
502
676
|
emit<R = any, T extends string = string>(message: FastEventEmitMessage<{
|
|
@@ -631,90 +805,27 @@ declare class FastEvent<Events extends Record<string, any> = Record<string, any>
|
|
|
631
805
|
* userEvents.offAll(); // 清理 'user' 前缀下的所有事件
|
|
632
806
|
* ```
|
|
633
807
|
*/
|
|
634
|
-
scope<E extends Record<string, any> = Record<string, any>, P extends string = string, M extends Record<string, any> = Record<string, any>, C = Context>(prefix: P, options?: FastEventScopeOptions<M, C
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
interface FastEventListenerDecorators {
|
|
638
|
-
queue: string;
|
|
639
|
-
}
|
|
640
|
-
type FastQueuePriority = 'none';
|
|
641
|
-
type FastQueueOverflows = "drop" | "expand" | 'slide' | 'throw';
|
|
642
|
-
type QueueListenerPipeOptions = {
|
|
643
|
-
size?: number;
|
|
644
|
-
maxExpandSize?: number;
|
|
645
|
-
expandOverflow?: Omit<FastQueueOverflows, 'expand'>;
|
|
646
|
-
overflow?: FastQueueOverflows;
|
|
647
|
-
lifetime?: number;
|
|
648
|
-
onEnter?: (newMessage: FastEventMessage, messages: [FastEventMessage, number][]) => void;
|
|
649
|
-
onDrop?: (message: FastEventMessage) => void;
|
|
650
|
-
};
|
|
651
|
-
declare const queue: (options?: QueueListenerPipeOptions) => FastListenerPipe;
|
|
652
|
-
declare const dropping: (size?: number) => FastListenerPipe;
|
|
653
|
-
declare const sliding: (size?: number) => FastListenerPipe;
|
|
654
|
-
declare const expanding: (options?: Omit<QueueListenerPipeOptions, "overflow">) => FastListenerPipe;
|
|
655
|
-
|
|
656
|
-
interface RetryListenerPipeOptions {
|
|
657
|
-
interval?: number;
|
|
658
|
-
drop?: (message: FastEventMessage, error: Error) => void;
|
|
659
|
-
}
|
|
660
|
-
/**
|
|
661
|
-
* 创建一个重试管道,在监听器执行失败时自动重试
|
|
662
|
-
* @param count 最大重试次数
|
|
663
|
-
* @param options 配置选项
|
|
664
|
-
* @returns FastListenerPipe
|
|
665
|
-
*/
|
|
666
|
-
declare const retry: (count: number, options?: RetryListenerPipeOptions) => FastListenerPipe;
|
|
667
|
-
|
|
668
|
-
/**
|
|
669
|
-
* 创建一个超时装饰器,限制监听器函数的执行时间
|
|
670
|
-
* @param ms 超时时间(毫秒)
|
|
671
|
-
* @param defaultValue 可选的默认返回值,如果提供则超时时返回此值,否则抛出TimeoutError
|
|
672
|
-
* @returns 装饰器函数
|
|
673
|
-
*/
|
|
674
|
-
declare const timeout: <T = any>(ms: number, defaultValue?: T) => FastListenerPipe;
|
|
675
|
-
|
|
676
|
-
interface DebounceOptions {
|
|
677
|
-
/**
|
|
678
|
-
* 当消息被丢弃时的回调函数
|
|
679
|
-
*/
|
|
680
|
-
drop?: (message: FastEventMessage) => void;
|
|
808
|
+
scope<E extends Record<string, any> = Record<string, any>, P extends string = string, M extends Record<string, any> = Record<string, any>, C = Context>(prefix: P, options?: DeepPartial<FastEventScopeOptions<Meta & M, C>>): FastEventScope<ScopeEvents<AllEvents, P> & E, Meta & M, C>;
|
|
809
|
+
scope<E extends Record<string, any> = Record<string, any>, P extends string = string, M extends Record<string, any> = Record<string, any>, C = Context, ScopeObject extends FastEventScope<any, any, any> = FastEventScope<ScopeEvents<AllEvents, P> & E, Meta & M, C>>(prefix: P, scopeObj: ScopeObject, options?: DeepPartial<FastEventScopeOptions<Meta & M, C>>): ScopeObject;
|
|
681
810
|
}
|
|
682
|
-
/**
|
|
683
|
-
* 创建一个防抖动装饰器,限制监听器函数的执行频率
|
|
684
|
-
* @param ms 防抖动时间(毫秒)
|
|
685
|
-
* @param options 可选的配置项
|
|
686
|
-
* @returns 装饰器函数
|
|
687
|
-
*/
|
|
688
|
-
declare const debounce: (ms: number, options?: DebounceOptions) => FastListenerPipe;
|
|
689
|
-
|
|
690
|
-
interface ThrottleOptions {
|
|
691
|
-
/**
|
|
692
|
-
* 当消息被丢弃时的回调函数
|
|
693
|
-
*/
|
|
694
|
-
drop?: (message: FastEventMessage) => void;
|
|
695
|
-
}
|
|
696
|
-
/**
|
|
697
|
-
* 创建一个节流装饰器,限制监听器函数的执行频率
|
|
698
|
-
* @param interval 节流时间间隔(毫秒)
|
|
699
|
-
* @param options 可选的配置项
|
|
700
|
-
* @returns 装饰器函数
|
|
701
|
-
*/
|
|
702
|
-
declare const throttle: (interval: number, options?: ThrottleOptions) => FastListenerPipe;
|
|
703
|
-
|
|
704
|
-
/**
|
|
705
|
-
* 创建一个memorize pipe,用于缓存上一次的返回值
|
|
706
|
-
* @param predicate 可选的判断函数,用于决定是否使用缓存
|
|
707
|
-
* @returns FastListenerPipe
|
|
708
|
-
*/
|
|
709
|
-
declare function memorize(predicate?: (message: FastEventMessage, args: FastEventListenerArgs) => boolean | Promise<boolean>): FastListenerPipe;
|
|
710
811
|
|
|
812
|
+
declare const __FastEvent__: unique symbol;
|
|
813
|
+
declare const __FastEventScope__: unique symbol;
|
|
711
814
|
declare class FastEventError extends Error {
|
|
815
|
+
constructor(message?: string);
|
|
712
816
|
}
|
|
713
817
|
declare class TimeoutError extends FastEventError {
|
|
714
818
|
}
|
|
819
|
+
declare class UnboundError extends FastEventError {
|
|
820
|
+
}
|
|
715
821
|
declare class AbortError extends FastEventError {
|
|
716
822
|
}
|
|
823
|
+
declare class CancelError extends FastEventError {
|
|
824
|
+
}
|
|
717
825
|
declare class QueueOverflowError extends FastEventError {
|
|
718
826
|
}
|
|
827
|
+
declare const FastEventDirectives: {
|
|
828
|
+
clearRetain: symbol;
|
|
829
|
+
};
|
|
719
830
|
|
|
720
|
-
export { AbortError, type
|
|
831
|
+
export { AbortError, CancelError, type ChangeFieldType, type DeepPartial, type Dict, type Expand, type Fallback, type FaseEventMessageExtends, FastEvent, type FastEventAnyListener, FastEventDirectives, type FastEventEmitMessage, FastEventError, type FastEventListenOptions, type FastEventListener, type FastEventListenerArgs, type FastEventMessage, type FastEventMeta, type FastEventOptions, FastEventScope, type FastEventScopeMeta, type FastEventScopeOptions, type FastEventSubscriber, type FastEvents, type FastListenerMeta, type FastListenerNode, type FastListeners, type Merge, type ObjectKeys, type OptionalItems, type Overloads, type OverrideOptions, type PickScopeEvents, QueueOverflowError, type RequiredItems, type ScopeEvents, TimeoutError, UnboundError, type Unique, __FastEventScope__, __FastEvent__ };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var O=Object.defineProperty;var B=(s,t,e)=>t in s?O(s,t,{enumerable:true,configurable:true,writable:true,value:e}):s[t]=e;var c=(s,t)=>O(s,"name",{value:t,configurable:true});var V=(s,t)=>{for(var e in t)O(s,e,{get:t[e],enumerable:true});};var h=(s,t,e)=>B(s,typeof t!="symbol"?t+"":t,e);function y(s,t,e,i){let n,r,o,l={};typeof s[0]=="object"?(n=s[0].type,r=s[0].payload,l=typeof s[1]=="boolean"?{retain:s[1]}:s[1]||{},o=s[0].meta):(n=s[0],r=s[1],l=typeof s[2]=="boolean"?{retain:s[2]}:s[2]||{}),o=Object.assign({},t,e,l.meta,o),Object.keys(o).length===0&&(o=void 0);let u={type:n,payload:r,meta:o};return l.executor===void 0&&(l.executor=i),[u,l]}c(y,"handleEmitArgs");function _(s,t){return Object.defineProperty(s,"name",{value:t||"anonymous",configurable:true}),s}c(_,"renameFn");var L=class L{constructor(t,e,i){h(this,"emitter");h(this,"prefix");h(this,"options");h(this,"events");this.emitter=t,this.prefix=e,this.options=Object.assign({},{scope:e},i),e.length>0&&!e.endsWith(t.options.delimiter)&&(this.prefix=e+t.options.delimiter);}get context(){return this.options.context}_getScopeListener(t){let e=this.prefix;if(e.length===0)return t;let i=this;return _(function(r,o){if(r.type.startsWith(e))return t.call(i.context||i.emitter.context,Object.assign({},r,{type:r.type.substring(e.length)}),o)},t.name)}_getScopeType(t){return t===void 0?void 0:this.prefix+t}_fixScopeType(t){return t.startsWith(this.prefix)?t.substring(this.prefix.length):t}on(){let t=[...arguments];return t[0]=this._getScopeType(t[0]),t[1]=this._getScopeListener(t[1]),this.emitter.on(...t)}once(){return this.on(arguments[0],arguments[1],Object.assign({},arguments[2],{count:1}))}onAny(t,e){return this.on("**",t,e)}off(){let t=arguments;typeof t[0]=="string"&&(t[0]=this._getScopeType(t[0])),this.emitter.off(...t);}offAll(){this.emitter.offAll(this.prefix.substring(0,this.prefix.length-1));}clear(){this.emitter.clear(this.prefix.substring(0,this.prefix.length-1));}emit(){let[t,e]=y(arguments,this.emitter.options.meta,this.options.meta,this.options.executor);return t.type=this._getScopeType(t.type),this.emitter.emit(t,e)}async emitAsync(){return (await Promise.allSettled(this.emit.apply(this,arguments))).map(e=>e.status==="fulfilled"?e.value:e.reason)}async waitFor(){let t=arguments[0],e=arguments[1],i=await this.emitter.waitFor(this._getScopeType(t),e);return Object.assign({},i,{type:this._fixScopeType(i.type)})}scope(t,e){let i=Object.assign({},this.options.meta,e?.meta),n=e?.context!==void 0?e.context:this.context,r=Object.assign({},this.options,e,{meta:Object.keys(i).length===0?void 0:i,context:n});return new L(this.emitter,this.prefix+t,r)}};c(L,"FastEventScope");var w=L;function R(s,t){if(s.length!==t.length&&s.length>0&&t[t.length-1]!=="**")return false;let e=[...t];t.length>0&&t[t.length-1]==="**"&&e.splice(t.length-1,1,...Array.from({length:s.length-t.length+1}).fill("*"));for(let i=0;i<s.length;i++)if(e[i]!=="*"&&e[i]!==s[i])return false;return true}c(R,"isPathMatched");function N(s,t){let e=[];for(;;){let i=s.findIndex(n=>t(n));if(i===-1){e.push(i);break}s.splice(i,1);}return e}c(N,"removeItem");var v={};V(v,{allSettled:()=>k,balance:()=>$,first:()=>q,last:()=>H,race:()=>X,random:()=>G});var k=c((s,t,e,i)=>Promise.allSettled(s.map(n=>i(n[0],t,e))),"allSettled"),X=c((s,t,e,i)=>{let n,r;return (!e||e&&!e.abortSignal)&&(r=new AbortController,e||(e={}),e.abortSignal=r.signal),[Promise.race(s.map(l=>(l[2]--,Promise.resolve(i(l[0],t,e)).then(u=>(n||(n=l,l[2]++),r?.abort(),u)))))]},"race"),$=c((s,t,e,i)=>{let n,r=0;return s.forEach((o,l)=>{o[2]--,(n===void 0||n>o[2])&&(n=o[2],r=l);}),s[r][2]++,[i(s[r][0],t,e)]},"balance"),q=c((s,t,e,i)=>(s.forEach(n=>n[2]--),s[0][2]++,[i(s[0][0],t,e)]),"first"),H=c((s,t,e,i)=>(s.forEach(n=>n[2]--),s[s.length-1][2]++,[i(s[s.length-1][0],t,e)]),"last"),G=c((s,t,e,i)=>{let n=Math.floor(Math.random()*s.length);return s.forEach(r=>r[2]--),s[n][2]++,[i(s[n][0],t,e)]},"random");function a(s){return s&&typeof s=="function"}c(a,"isFunction");var M=class M extends Error{};c(M,"FastEventError");var x=M,A=class A extends x{};c(A,"TimeoutError");var b=A,j=class j extends x{};c(j,"AbortError");var E=j,C=class C extends x{};c(C,"QueueOverflowError");var T=C;var F=class F{constructor(t){h(this,"listeners",{__listeners:[]});h(this,"_options");h(this,"_delimiter","/");h(this,"_context");h(this,"retainedMessages",new Map);h(this,"listenerCount",0);h(this,"events");this._options=Object.assign({debug:false,id:Math.random().toString(36).substring(2),delimiter:"/",context:null,ignoreErrors:true,meta:void 0},t),this._delimiter=this._options.delimiter,this._context=this._options.context,this._enableDevTools();}get options(){return this._options}get context(){return this._context}get id(){return this._options.id}_addListener(t,e,i){let{count:n,prepend:r}=i;return this._forEachNodes(t,o=>{let l=[e,n,0];r?o.__listeners.splice(0,0,l):o.__listeners.push(l),this.listenerCount++,a(this._options.onAddListener)&&this._options.onAddListener(t,e);})}_enableDevTools(){this.options.debug&&globalThis.__FLEXEVENT_DEVTOOLS__&&globalThis.__FLEXEVENT_DEVTOOLS__.add(this);}_forEachNodes(t,e){if(t.length===0)return;let i=this.listeners;for(let n=0;n<t.length;n++){let r=t[n];if(r in i||(i[r]={__listeners:[]}),n===t.length-1){let o=i[r];return e(o,i),o}else i=i[r];}}_removeListener(t,e,i){i&&N(t.__listeners,n=>{n=Array.isArray(n)?n[0]:n;let r=n===i;return r&&(this.listenerCount--,a(this._options.onRemoveListener)&&this._options.onRemoveListener(e,i)),r});}_pipeListener(t,e){return e.forEach(i=>{t=_(i(t),t.name);}),t}on(){let t=arguments[0],e=a(arguments[1])?arguments[1]:this.onMessage.bind(this),i=Object.assign({count:0,prepend:false},a(arguments[1])?arguments[2]:arguments[1]);if(t.length===0)throw new Error("event type cannot be empty");let n=t.split(this._delimiter);if(i.pipes&&i.pipes.length>0&&(e=this._pipeListener(e,i.pipes)),a(i.filter)||a(i.off)){let l=e;e=_(function(u,f){if(a(i.off)&&i.off.call(this,u,f)){o();return}if(a(i.filter)){if(i.filter.call(this,u,f))return l.call(this,u,f)}else return l.call(this,u,f)},e.name);}let r=this._addListener(n,e,i),o=c(()=>r&&this._removeListener(r,n,e),"off");return r&&!t.includes("*")&&this._emitForLastEvent(t),{off:o,listener:e}}once(){return a(arguments[1])?this.on(arguments[0],arguments[1],Object.assign({},arguments[2],{count:1})):this.on(arguments[0],Object.assign({},arguments[2],{count:1}))}onAny(){return this.on("**",arguments[0],arguments[1])}onMessage(t){}off(){let t=arguments,e=a(t[0])?void 0:t[0],i=a(t[0])?t[0]:t[1],n=e?e.split(this._delimiter):[],r=e?e.includes("*"):false;if(e&&!r)this._traverseToPath(this.listeners,n,o=>{i?this._removeListener(o,n,i):e&&(o.__listeners=[]);});else {let o=r?[]:n;this._traverseListeners(this.listeners,o,(l,u)=>{(i!==void 0||r&&R(l,n))&&(i?this._removeListener(u,n,i):u.__listeners=[]);});}}offAll(t){if(t){let e=t.split(this._delimiter),i=0;this._traverseListeners(this.listeners,e,(n,r)=>{i+=r.__listeners.length,r.__listeners=[];}),this.listenerCount-=i,this._removeRetainedEvents(t);}else {let e=0;this._traverseListeners(this.listeners,[],(i,n)=>{e+=n.__listeners.length;}),this.listenerCount-=e,this.retainedMessages.clear(),this.listeners={__listeners:[]};}a(this._options.onClearListeners)&&this._options.onClearListeners.call(this);}_removeRetainedEvents(t){t||this.retainedMessages.clear(),t?.endsWith(this._delimiter)&&(t+=this._delimiter),this.retainedMessages.delete(t);for(let e of this.retainedMessages.keys())e.startsWith(t)&&this.retainedMessages.delete(e);}clear(t){this.offAll(t),this._removeRetainedEvents(t);}_emitForLastEvent(t){if(this.retainedMessages.has(t)){let e=this.retainedMessages.get(t),i=t.split(this._delimiter),n=[];this._traverseToPath(this.listeners,i,r=>{n.push(r);}),this._executeListeners(n,e);}}_traverseToPath(t,e,i,n=0,r){if(n>=e.length){i(t);return}let o=e[n];if(r===true){this._traverseToPath(t,e,i,n+1,true);return}"*"in t&&this._traverseToPath(t["*"],e,i,n+1),"**"in t&&this._traverseToPath(t["**"],e,i,n+1,true),o in t&&this._traverseToPath(t[o],e,i,n+1);}_traverseListeners(t,e,i){let n=t;e&&e.length>0&&this._traverseToPath(t,e,o=>{n=o;});let r=c((o,l,u)=>{l(u,o);for(let[f,m]of Object.entries(o))f.startsWith("__")||m&&r(m,l,[...u,f]);},"traverseNodes");r(n,i,[]);}_onListenerError(t,e,i,n){if(n instanceof Error&&(n._emitter=`${t.name||"anonymous"}:${e.type}`),a(this._options.onListenerError))try{this._options.onListenerError.call(this,t,n,e,i);}catch{}if(this._options.ignoreErrors)return n;throw n}_executeListener(t,e,i){try{if(i&&i.abortSignal&&i.abortSignal.aborted)return this._onListenerError(t,e,i,new E(t.name));let n=t.call(this._context||this,e,i);return n&&n instanceof Promise&&(n=n.catch(r=>this._onListenerError(t,e,i,r))),n}catch(n){return this._onListenerError(t,e,i,n)}}_getListenerExecutor(t){if(!t)return;let e=t.executor||this._options.executor;if(a(e))return e;if(e&&e in v)return v[e]}_executeListeners(t,e,i){if(!t||t.length===0)return [];let n=t.reduce((r,o)=>r.concat(o.__listeners.map((l,u)=>[l,u,o.__listeners])),[]);try{let r=this._getListenerExecutor(i);return r?r(n.map(o=>o[0]),e,i,this._executeListener.bind(this)):n.map(o=>this._executeListener(o[0][0],e,i))}finally{for(let r=n.length-1;r>=0;r--){let o=n[r][0];o[2]++,o[1]>0&&o[1]<=o[2]&&n[r][2].splice(r,1);}}}emit(){let[t,e]=y(arguments,this.options.meta),i=t.type.split(this._delimiter);e.retain&&this.retainedMessages.set(t.type,t);let n=[],r=[];if(this._traverseToPath(this.listeners,i,o=>{r.push(o);}),a(this._options.onBeforeExecuteListener)&&this._options.onBeforeExecuteListener.call(this,t,e)===false)throw new Error("emit "+t.type+" is aborted");return n.push(...this._executeListeners(r,t,e)),a(this._options.onAfterExecuteListener)&&this._options.onAfterExecuteListener.call(this,t,n,r),n}async emitAsync(){return (await Promise.allSettled(this.emit.apply(this,arguments))).map(e=>e.status==="fulfilled"?e.value:e.reason)}waitFor(){let t=arguments[0],e=arguments[1];return new Promise((i,n)=>{let r,o,l=c(u=>{clearTimeout(r),o.off(),i(u);},"listener");e&&e>0&&(r=setTimeout(()=>{o&&o.off(),n(new Error("wait for event<"+t+"> is timeout"));},e)),o=this.on(t,l);})}scope(t,e){return new w(this,t,e)}};c(F,"FastEvent");var W=F;var D=c(s=>{let{lifetime:t,size:e,overflow:i,maxExpandSize:n,expandOverflow:r,onEnter:o,onDrop:l}=Object.assign({size:10,maxExpandSize:100,overflow:"expand",expandOverflow:"slide",lifetime:0},s),u=[],f=e,m=false,P=c(p=>{a(o)?o(p,u):u.push(t>0?[p,Date.now()]:[p,0]);},"pushMessage"),z=c(p=>{switch(u.length>=n&&i==="expand"?r:i){case "drop":return a(l)&&l(p),false;case "expand":return f=Math.min(f+e,n),P(p),true;case "slide":let d=u.shift();return a(l)&&d&&l(d[0]),P(p),true;case "throw":throw a(l)&&l(p),new T;default:return false}},"handleOverflow");return p=>async function(g,d){if(m){u.length<f?P(g):z(g);return}m=true;try{for(await p.call(this,g,d);u.length>0;){let[S,I]=u.shift()||[void 0,0];if(S){if(t>0&&Date.now()-I>t){a(l)&&l(S);continue}await p.call(this,S,d);}}}finally{m=false;}}},"queue"),bt=c((s=10)=>D({size:s,overflow:"drop"}),"dropping"),Et=c((s=10)=>D({size:s,overflow:"slide"}),"sliding"),Tt=c(s=>D(Object.assign({},s,{overflow:"expand"})),"expanding");var Mt=c((s,t)=>{let{interval:e=1e3,drop:i}=t||{};return n=>async function(r,o){let l=0,u;for(;l<=s;)try{return await n.call(this,r,o)}catch(f){if(u=f,l<s)await new Promise(m=>{setTimeout(m,e);}),l++;else throw a(i)&&i(r,u),u}}},"retry");var Ft=c((s,t)=>e=>async function(i,n){let r,o=new Promise((u,f)=>{r=setTimeout(()=>{t!==void 0?u(t):f(new b);},s);}),l=Promise.resolve(e.call(this,i,n));try{return await Promise.race([l,o])}finally{clearTimeout(r);}},"timeout");var Nt=c((s,t)=>e=>{let i=false,n=null;return async function(r,o){if(i){t?.drop&&t.drop(r);return}try{i=!0;let l=await e.call(this,r,o);return n=setTimeout(()=>{i=!1,n=null;},s),l}catch(l){throw i=false,n&&(clearTimeout(n),n=null),l}}},"debounce");var It=c((s,t)=>e=>{let i=0;return async function(n,r){let o=Date.now();if(o-i<s){t?.drop&&t.drop(n);return}return i=o,await e.call(this,n,r)}},"throttle");function kt(s){let t,e=false,i,n=typeof s=="function";return function(r){return async function(o,l){if(e){if(typeof s=="function"){if(await s(o,l))return t}else if(o.payload===i)return t}let u=await r.call(this,o,l);return t=u,n||(i=o.payload),e=true,u}}}c(kt,"memorize");exports.AbortError=E;exports.FastEvent=W;exports.FastEventError=x;exports.FastEventScope=w;exports.QueueOverflowError=T;exports.TimeoutError=b;exports.debounce=Nt;exports.dropping=bt;exports.expanding=Tt;exports.memorize=kt;exports.queue=D;exports.retry=Mt;exports.sliding=Et;exports.throttle=It;exports.timeout=Ft;//# sourceMappingURL=index.js.map
|
|
1
|
+
'use strict';var R=Object.defineProperty;var $=(r,e,t)=>e in r?R(r,e,{enumerable:true,configurable:true,writable:true,value:t}):r[e]=t;var a=(r,e)=>R(r,"name",{value:e,configurable:true});var f=(r,e,t)=>$(r,typeof e!="symbol"?e+"":e,t);var G=Symbol.for("__FastEvent__"),H=Symbol.for("__FastEventScope__"),S=class S extends Error{constructor(e){super(e);}};a(S,"FastEventError");var m=S,A=class A extends m{};a(A,"TimeoutError");var F=A,M=class M extends m{};a(M,"UnboundError");var d=M,T=class T extends m{};a(T,"AbortError");var _=T,j=class j extends m{};a(j,"CancelError");var x=j,w=class w extends m{};a(w,"QueueOverflowError");var C=w,y={clearRetain:Symbol.for("ClearRetain")};function b(r,e,t,s){let i,n={},o={};return typeof r[0]=="object"?(Object.assign(o,r[0]),n=typeof r[1]=="boolean"?{retain:r[1]}:r[1]||{},i=r[0].meta):(o.type=r[0],o.payload=r[1],n=typeof r[2]=="boolean"?{retain:r[2]}:r[2]||{}),i=Object.assign({},e,t,n.meta,i),Object.keys(i).length===0&&(i=void 0),o.meta=i,n.executor===void 0&&(n.executor=s),[o,n]}a(b,"parseEmitArgs");function D(r){return r?typeof r=="object"&&"__FastEventScope__"in r:false}a(D,"isFastEventScope");function L(r,e,t){let s=r[0],i=D(r[1])?r[1]:void 0,n=(i?r[2]:r[1])||{};return n.meta=Object.assign({},e,n?.meta),n.context=n.context!==void 0?n.context:t,[s,i,n]}a(L,"parseScopeArgs");function g(r,e){return Object.defineProperty(r,"name",{value:e||"anonymous",configurable:true}),r}a(g,"renameFn");var v=class v{constructor(e){f(this,"__FastEventScope__",true);f(this,"_options",{});f(this,"types",{events:void 0,meta:void 0,context:void 0});f(this,"prefix","");f(this,"emitter");this._options=Object.assign({},e);}get context(){return this.options.context||this}get options(){return this._options}bind(e,t,s){this.emitter=e,this._options=Object.assign(this._options,{scope:t},s),t.length>0&&!t.endsWith(e.options.delimiter)&&(this.prefix=t+e.options.delimiter);}_getScopeListener(e){let t=this.prefix;if(t.length===0)return e;e||(e=(this._options.onMessage||this.onMessage).bind(this));let s=this;return g(function(n,o){if(n.type.startsWith(t))return e.call(s.context,Object.assign({},n,{type:n.type.substring(t.length)}),o)},e.name)}_getScopeType(e){return e===void 0?void 0:this.prefix+e}_fixScopeType(e){return e.startsWith(this.prefix)?e.substring(this.prefix.length):e}on(){if(!this.emitter)throw new d;let e=[...arguments];return e[0]=this._getScopeType(e[0]),e[1]=this._getScopeListener(e[1]),this.emitter.on(...e)}once(){return this.on(arguments[0],arguments[1],Object.assign({},arguments[2],{count:1}))}onAny(){return this.on("**",...arguments)}off(){let e=arguments;typeof e[0]=="string"&&(e[0]=this._getScopeType(e[0])),this.emitter.off(...e);}offAll(){this.emitter.offAll(this.prefix.substring(0,this.prefix.length-1));}clear(){this.emitter.clear(this.prefix.substring(0,this.prefix.length-1));}emit(){if(arguments.length===2&&typeof arguments[0]=="string"&&arguments[1]===y.clearRetain)return this.emitter.emit(this._getScopeType(arguments[0]));let[e,t]=b(arguments,this.emitter.options.meta,this.options.meta,this.options.executor);return e.type=this._getScopeType(e.type),this.emitter.emit(e,t)}async emitAsync(){return (await Promise.allSettled(this.emit.apply(this,arguments))).map(t=>t.status==="fulfilled"?t.value:t.reason)}async waitFor(){let e=arguments[0],t=arguments[1],s=await this.emitter.waitFor(this._getScopeType(e),t);return Object.assign({},s,{type:this._fixScopeType(s.type)})}scope(){let[e,t,s]=L(arguments,this.options.meta,this.options.context),i;return t?i=t:i=new v,i.bind(this.emitter,this.prefix+e,s),i}onMessage(e,t){}};a(v,"FastEventScope");var E=v;function O(r,e){if(r.length!==e.length&&r.length>0&&e[e.length-1]!=="**")return false;let t=[...e];e.length>0&&e[e.length-1]==="**"&&t.splice(e.length-1,1,...Array.from({length:r.length-e.length+1}).fill("*"));for(let s=0;s<r.length;s++)if(t[s]!=="*"&&t[s]!==r[s])return false;return true}a(O,"isPathMatched");function W(r,e){let t=[];for(;;){let s=r.findIndex(i=>e(i));if(s===-1){t.push(s);break}r.splice(s,1);}return t}a(W,"removeItem");function h(r){return r&&typeof r=="function"}a(h,"isFunction");var q=Symbol.for("__expandable__");function N(r){return r&&r[q]}a(N,"isExpandable");function V(r){for(let e=0;e<r.length;e++){let t=r[e];Array.isArray(t)&&N(t)&&(r.splice(e,1,...t),e+=t.length-1);}return r}a(V,"expandEmitResults");function I(r){return r&&typeof r=="object"&&"off"in r&&"listener"in r}a(I,"isSubsctiber");function B(r,e){return r.catch(t=>(e&&e(t),Promise.resolve(t)))}a(B,"tryReturnError");var P=class P{constructor(e){f(this,"__FastEvent__",true);f(this,"listeners",{__listeners:[]});f(this,"_options");f(this,"_delimiter","/");f(this,"_context");f(this,"retainedMessages",new Map);f(this,"listenerCount",0);f(this,"types",{events:void 0,meta:void 0,context:void 0});this._options=Object.assign({debug:false,id:Math.random().toString(36).substring(2),delimiter:"/",context:null,ignoreErrors:true,meta:void 0,expandEmitResults:true},e),this._delimiter=this._options.delimiter,this._context=this._options.context,this._enableDevTools();}get options(){return this._options}get context(){return this.options.context||this}get meta(){return this.options.meta}get id(){return this._options.id}_addListener(e,t,s){let{count:i,prepend:n}=s,o=0;return [this._forEachNodes(e,u=>{let l=[t,i,0];n?(u.__listeners.splice(0,0,l),o=0):(u.__listeners.push(l),o=u.__listeners.length-1),this.listenerCount++;}),o]}_enableDevTools(){this.options.debug&&globalThis.__FLEXEVENT_DEVTOOLS__&&globalThis.__FLEXEVENT_DEVTOOLS__.add(this);}_forEachNodes(e,t){if(e.length===0)return;let s=this.listeners;for(let i=0;i<e.length;i++){let n=e[i];if(n in s||(s[n]={__listeners:[]}),i===e.length-1){let o=s[n];return t(o,s),o}else s=s[n];}}_removeListener(e,t,s){s&&W(e.__listeners,i=>{i=Array.isArray(i)?i[0]:i;let n=i===s;return n&&(this.listenerCount--,h(this._options.onRemoveListener)&&this._options.onRemoveListener(t.join(this._delimiter),s)),n});}_pipeListener(e,t){return t.forEach(s=>{e=g(s(e),e.name);}),e}on(){let e=arguments[0],t=h(arguments[1])?arguments[1]:(this._options.onMessage||this.onMessage).bind(this),s=Object.assign({count:0,prepend:false},h(arguments[1])?arguments[2]:arguments[1]);if(e.length===0)throw new Error("event type cannot be empty");if(h(this._options.onAddListener)){let u=this._options.onAddListener(e,t,s);if(u===false)throw new x;if(I(u))return u}let i=e.split(this._delimiter);if(s.pipes&&s.pipes.length>0&&(t=this._pipeListener(t,s.pipes)),h(s.filter)||h(s.off)){let u=t;t=g(function(l,p){if(h(s.off)&&s.off.call(this,l,p)){c();return}if(h(s.filter)){if(s.filter.call(this,l,p))return u.call(this,l,p)}else return u.call(this,l,p)},t.name);}let[n,o]=this._addListener(i,t,s),c=a(()=>n&&this._removeListener(n,i,t),"off");return this._emitRetainMessage(e,n,o),{off:c,listener:t}}once(){return h(arguments[1])?this.on(arguments[0],arguments[1],Object.assign({},arguments[2],{count:1})):this.on(arguments[0],Object.assign({},arguments[2],{count:1}))}onAny(){return this.on("**",arguments[0],arguments[1])}onMessage(e,t){}off(){let e=arguments,t=h(e[0])?void 0:e[0],s=h(e[0])?e[0]:e[1],i=t?t.split(this._delimiter):[],n=t?t.includes("*"):false;if(t&&!n)this._traverseToPath(this.listeners,i,o=>{s?this._removeListener(o,i,s):t&&(o.__listeners=[]);});else {let o=n?[]:i;this._traverseListeners(this.listeners,o,(c,u)=>{(s!==void 0||n&&O(c,i))&&(s?this._removeListener(u,i,s):u.__listeners=[]);});}}offAll(e){if(e){let t=e.split(this._delimiter),s=0;this._traverseListeners(this.listeners,t,(i,n)=>{s+=n.__listeners.length,n.__listeners=[];}),this.listenerCount-=s,this._removeRetainedEvents(e);}else {let t=0;this._traverseListeners(this.listeners,[],(s,i)=>{t+=i.__listeners.length;}),this.listenerCount-=t,this.retainedMessages.clear(),this.listeners={__listeners:[]};}h(this._options.onClearListeners)&&this._options.onClearListeners.call(this);}_removeRetainedEvents(e){e||this.retainedMessages.clear(),e?.endsWith(this._delimiter)&&(e+=this._delimiter),this.retainedMessages.delete(e);for(let t of this.retainedMessages.keys())t.startsWith(e)&&this.retainedMessages.delete(t);}clear(e){this.offAll(e),this._removeRetainedEvents(e);}_emitRetainMessage(e,t,s){let i=[];if(e.includes("*")){let n=e.split(this._delimiter);this.retainedMessages.forEach((o,c)=>{let u=c.split(this._delimiter);O(u,n)&&i.push(o);});}else this.retainedMessages.has(e)&&i.push(this.retainedMessages.get(e));t&&i.forEach(n=>{this._executeListeners([t],n,{},o=>o[0]===t.__listeners[s][0]);});}_traverseToPath(e,t,s,i=0,n){if(i>=t.length){s(e);return}let o=t[i];if(n===true){this._traverseToPath(e,t,s,i+1,true);return}"*"in e&&this._traverseToPath(e["*"],t,s,i+1),"**"in e&&this._traverseToPath(e["**"],t,s,i+1,true),o in e&&this._traverseToPath(e[o],t,s,i+1);}_traverseListeners(e,t,s){let i=e;t&&t.length>0&&this._traverseToPath(e,t,o=>{i=o;});let n=a((o,c,u)=>{c(u,o);for(let[l,p]of Object.entries(o))l.startsWith("__")||p&&n(p,c,[...u,l]);},"traverseNodes");n(i,s,[]);}_onListenerError(e,t,s,i){if(i instanceof Error&&(i._emitter=`${e.name||"anonymous"}:${t.type}`),h(this._options.onListenerError))try{this._options.onListenerError.call(this,i,e,t,s);}catch{}if(this._options.ignoreErrors)return i;throw i}_executeListener(e,t,s,i=false){try{if(s&&s.abortSignal&&s.abortSignal.aborted)return this._onListenerError(e,t,s,new _(e.name));let n=e.call(this.context,t,s);return i&&n&&n instanceof Promise&&(n=B(n,o=>this._onListenerError(e,t,s,o))),n}catch(n){return this._onListenerError(e,t,s,n)}}_getListenerExecutor(e){if(!e)return;let t=e.executor||this._options.executor;if(h(t))return t}_executeListeners(e,t,s,i){if(!e||e.length===0)return [];let n=e.reduce((o,c)=>o.concat(c.__listeners.filter(u=>h(i)?i(u,c):true).map((u,l)=>[u,l,c.__listeners])),[]);try{let o=this._getListenerExecutor(s);if(o){let c=o(n.map(u=>u[0]),t,s,this._executeListener.bind(this));return Array.isArray(c)?c:[c]}else return n.map(c=>this._executeListener(c[0][0],t,s,!0))}finally{for(let o=n.length-1;o>=0;o--){let c=n[o][0];c[2]++,c[1]>0&&c[1]<=c[2]&&n[o][2].splice(o,1);}}}emit(){if(arguments.length===2&&typeof arguments[0]=="string"&&arguments[1]===y.clearRetain)return this.retainedMessages.delete(arguments[0]),[];let[e,t]=b(arguments,this.options.meta);h(t.parseArgs)&&t.parseArgs(e,t);let s=e.type.split(this._delimiter);t.retain&&this.retainedMessages.set(e.type,e);let i=[],n=[];if(this._traverseToPath(this.listeners,s,o=>{n.push(o);}),h(this._options.onBeforeExecuteListener)){let o=this._options.onBeforeExecuteListener.call(this,e,t);if(Array.isArray(o))return o;if(o===false)throw new _(e.type)}return i.push(...this._executeListeners(n,e,t)),h(this._options.onAfterExecuteListener)&&this._options.onAfterExecuteListener.call(this,e,i,n),this._options.expandEmitResults&&V(i),i}async emitAsync(){return (await Promise.allSettled(this.emit.apply(this,arguments))).map(t=>t.status==="fulfilled"?t.value:t.reason)}waitFor(){let e=arguments[0],t=arguments[1];return new Promise((s,i)=>{let n,o,c=a(u=>{clearTimeout(n),o.off(),s(u);},"listener");t&&t>0&&(n=setTimeout(()=>{o&&o.off(),i(new Error("wait for event<"+e+"> is timeout"));},t)),o=this.on(e,c);})}scope(){let[e,t,s]=L(arguments,this.options.meta,this.options.context),i;return t?i=t:i=new E,i.bind(this,e,s),i}};a(P,"FastEvent");var X=P;exports.AbortError=_;exports.CancelError=x;exports.FastEvent=X;exports.FastEventDirectives=y;exports.FastEventError=m;exports.FastEventScope=E;exports.QueueOverflowError=C;exports.TimeoutError=F;exports.UnboundError=d;exports.__FastEventScope__=H;exports.__FastEvent__=G;//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|