fastevent 2.2.12 → 2.3.1

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/index.d.ts CHANGED
@@ -1,5 +1,17 @@
1
1
  type FastListenerPipe = (listener: TypedFastEventListener) => TypedFastEventListener;
2
2
 
3
+ type Expand$1<T> = T extends infer O ? {
4
+ [K in keyof O]: O[K];
5
+ } : never;
6
+ type ContainsWildcard<T extends string> = T extends `${string}/*/${string}` ? true : T extends `${string}/*` ? true : T extends `*/${string}` ? true : T extends `*` ? true : false;
7
+ type ReplaceWildcard<T extends string> = T extends `*${infer Rest}` ? `${string}${ReplaceWildcard<Rest>}` : T extends `${infer Head}*${infer Rest}` ? `${Head}${string}${ReplaceWildcard<Rest>}` : T;
8
+ type WildcardKeys<T> = {
9
+ [K in keyof T]: K extends string ? (ContainsWildcard<K> extends true ? K : never) : never;
10
+ }[keyof T];
11
+ type ExpandWildcard<T extends Record<string, any>> = Expand$1<T & {
12
+ [K in WildcardKeys<T> as ReplaceWildcard<K>]: T[K];
13
+ }>;
14
+
3
15
  type MergeUnion<T> = (T extends any ? (x: T) => void : never) extends (x: infer U) => void ? {
4
16
  [K in keyof U]: U[K];
5
17
  } : never;
@@ -14,9 +26,10 @@ type MatchEventType<T extends string, Events extends Record<string, any>> = Merg
14
26
  [K in keyof Events]: MatchPattern<T, K & string> extends never ? never : {
15
27
  [P in K]: Events[K];
16
28
  };
17
- }[keyof Events] extends infer Result ? Result extends Record<string, any> ? Result : any : any, {
29
+ }[keyof Events] extends infer Result ? Result extends Record<string, any> ? Result : Record<string, any> : Record<string, any>, {
18
30
  [K in T]: any;
19
31
  }>>;
32
+ type MatchEventPayload<Events extends Record<string, any>, T> = T extends keyof Events ? Events[T] : T extends string ? T extends keyof MatchEventType<T, Events> ? MatchEventType<T, Events>[T] : any : any;
20
33
 
21
34
  type Split<S extends string, Delimiter extends string> = S extends `${infer Head}${Delimiter}${infer Tail}` ? [Head, ...Split<Tail, Delimiter>] : [S];
22
35
  type MatchPatternAndGetRemainder<KeyParts extends string[], PrefixParts extends string[], Result extends string[] = []> = PrefixParts['length'] extends 0 ? KeyParts['length'] extends 0 ? never : KeyParts : KeyParts['length'] extends 0 ? never : KeyParts[0] extends PrefixParts[0] | '*' ? MatchPatternAndGetRemainder<Slice<KeyParts, 1>, Slice<PrefixParts, 1>, Result> : never;
@@ -57,9 +70,11 @@ type FastEventEmitMessage<Events extends Record<string, any> = Record<string, an
57
70
  meta?: DeepPartial<FastEventMeta & M & Record<string, any>>;
58
71
  };
59
72
  }[Exclude<keyof Events, number | symbol>] & FastEventMessageExtends;
60
- type TypedFastEventListener<T extends string = string, P = any, M = any, C = any> = (this: C, message: TypedFastEventMessage<{
61
- [K in T]: P;
62
- }, M>, args: FastEventListenerArgs<M>) => any | Promise<any>;
73
+ type FastMessagePayload<P = any> = {
74
+ type: P;
75
+ __IS_FAST_MESSAGE__: true;
76
+ };
77
+ type TypedFastEventListener<T extends string = string, P = any, M = any, C = any> = (this: C, message: TypedFastEventMessage<Record<T, P>, M>, args: FastEventListenerArgs<M>) => any | Promise<any>;
63
78
  type TypedFastEventAnyListener<Events extends Record<string, any> = Record<string, any>, Meta = never, Context = any> = (this: Context, message: TypedFastEventMessage<Events, Meta>, args: FastEventListenerArgs<Meta>) => any | Promise<any>;
64
79
  type FastEventListeners<Events extends Record<string, any> = Record<string, any>, M = any, C = any> = {
65
80
  [K in keyof Events]: TypedFastEventListener<Exclude<K, number | symbol>, Events[K], M, C>;
@@ -132,6 +147,16 @@ type FastEventOptions<Meta = Record<string, any>, Context = never> = {
132
147
  executor?: FastListenerExecutor;
133
148
  onMessage?: TypedFastEventListener;
134
149
  expandEmitResults?: boolean;
150
+ /**
151
+ * 对接收到的消息进行转换,用于将消息转换成其他格式
152
+ *
153
+ * new FastEvent({
154
+ * transform:(message)=>{
155
+ * message.payload
156
+ * }
157
+ * })
158
+ */
159
+ transform?: (message: FastEventMessage) => any;
135
160
  };
136
161
  interface FastEvents {
137
162
  }
@@ -149,6 +174,9 @@ type FastEventListenOptions<Events extends Record<string, any> = Record<string,
149
174
  */
150
175
  tag?: string;
151
176
  };
177
+ declare enum FastEventListenerFlags {
178
+ Transformed = 1
179
+ }
152
180
  type FastEventListenerArgs<M = Record<string, any>> = {
153
181
  retain?: boolean;
154
182
  meta?: DeepPartial<M> & Record<string, any>;
@@ -165,6 +193,17 @@ type FastEventListenerArgs<M = Record<string, any>> = {
165
193
  * 当emit参数解析完成后的回调,用于修改emit参数
166
194
  */
167
195
  parseArgs?: (message: TypedFastEventMessage, args: FastEventListenerArgs) => void;
196
+ /**
197
+ * 额外的标识
198
+ *
199
+ * - 1: transformed 当消息是经过transform转换后的消息时的标识
200
+ *
201
+ */
202
+ flags?: FastEventListenerFlags;
203
+ /**
204
+ * 如果消息经过转换前的原主题
205
+ */
206
+ rawEventType?: string;
168
207
  };
169
208
  type Merge<T extends object, U extends object> = {
170
209
  [K in keyof T | keyof U]: K extends keyof U ? U[K] : K extends keyof T ? T[K] : never;
@@ -254,6 +293,52 @@ type RecordValues<R extends Record<string, any>> = R[keyof R];
254
293
  type RecordPrefix<P extends string, R extends Record<string, any>> = {
255
294
  [K in keyof R as K extends `${P}/${infer S}` ? S : never]: R[K];
256
295
  };
296
+ /**
297
+ * 声明事件类型时,一般情况下,K=事件名称,V=事件Payload参数类型
298
+ *
299
+ * AssertFastMessage用于声明V是一个FastMessage类型,而不是Payload类型
300
+ *
301
+ * 一般配合transform参数使用
302
+ *
303
+ * 例如:
304
+ * type CustomEvents = {
305
+ click: { x: number; y: number };
306
+ }
307
+ const emitter = new FastEvent<CustomEvents>();
308
+ emitter.on('click', (message) => {
309
+ // typeof message.payload === { x: number; y: number }
310
+ })
311
+ const emitter = new FastEvent<CustomEvents>({
312
+ transform:(message)=>{
313
+ if(message.type === 'click'){
314
+ return message.payload
315
+ }else{
316
+ return message
317
+ }
318
+ }
319
+ });
320
+ emitter.on('click', (message) => {
321
+ // typeof message === { x: number; y: number }
322
+ }
323
+ */
324
+ type AssertFastMessage<M> = {
325
+ type: M;
326
+ __IS_FAST_MESSAGE__: true;
327
+ };
328
+ type NotPayload<M> = AssertFastMessage<M>;
329
+ type PickPayload<M> = M extends FastMessagePayload ? M['type'] : M;
330
+ type AtPayloads<Events extends Record<string, any>> = {
331
+ [K in keyof Events]: PickPayload<Events[K]>;
332
+ };
333
+ type PickTransformedEvents<T extends Record<string, any>> = ExpandWildcard<{
334
+ [key in keyof T as T[key] extends FastMessagePayload ? key : never]: T[key];
335
+ }>;
336
+ type OmitTransformedEvents<T extends Record<string, any>> = {
337
+ [key in keyof T as T[key] extends FastMessagePayload ? never : key]: T[key];
338
+ };
339
+ type TransformedEvents<Events extends Record<string, any>> = {
340
+ [K in keyof Events]: NotPayload<Events[K]>;
341
+ };
257
342
 
258
343
  type FastListenerExecutor = (listeners: FastListenerMeta[], message: TypedFastEventMessage, args: FastEventListenerArgs, execute: (listener: TypedFastEventListener, message: TypedFastEventMessage, args: FastEventListenerArgs, catchErrors?: boolean) => Promise<any> | any) => Promise<any[]> | any[];
259
344
 
@@ -262,6 +347,16 @@ type FastEventScopeOptions<Meta = Record<string, any>, Context = never> = {
262
347
  context: Context;
263
348
  executor?: FastListenerExecutor;
264
349
  onMessage?: TypedFastEventListener;
350
+ /**
351
+ * 对接收到的消息进行转换,用于将消息转换成其他格式
352
+ *
353
+ * new FastEvent({
354
+ * transform:(message)=>{
355
+ * message.payload
356
+ * }
357
+ * })
358
+ */
359
+ transform?: (message: FastEventMessage) => any;
265
360
  };
266
361
  interface FastEventScopeMeta {
267
362
  scope: string;
@@ -303,15 +398,17 @@ declare class FastEventScope<Events extends Record<string, any> = Record<string,
303
398
  private _getScopeType;
304
399
  private _fixScopeType;
305
400
  on<T extends Types = Types>(type: T, options?: FastEventListenOptions<Events, FinalMeta>): FastEventSubscriber;
306
- on<T extends string>(type: T, options?: FastEventListenOptions<Events, FinalMeta>): FastEventSubscriber;
401
+ on<T extends Exclude<string, Types>>(type: T, options?: FastEventListenOptions<Events, FinalMeta>): FastEventSubscriber;
307
402
  on(type: '**', options?: FastEventListenOptions<Events, FinalMeta>): FastEventSubscriber;
308
- on<T extends Types = Types>(type: T, listener: TypedFastEventListener<Exclude<T, number | symbol>, Events[T], FinalMeta, Fallback<Context, typeof this>>, options?: FastEventListenOptions): FastEventSubscriber;
309
- on<T extends string>(type: T, listener: TypedFastEventListener<Exclude<keyof MatchEventType<T, Events>, number | symbol>, RecordValues<MatchEventType<T, Events>>, FinalMeta, Fallback<Context, typeof this>>, options?: FastEventListenOptions): FastEventSubscriber;
403
+ on<T extends keyof OmitTransformedEvents<Events>>(type: T, listener: TypedFastEventListener<Exclude<T, number | symbol>, Events[T], FinalMeta, Fallback<Context, typeof this>>, options?: FastEventListenOptions): FastEventSubscriber;
404
+ on<T extends keyof PickTransformedEvents<Events>>(type: T, listener: (message: PickPayload<RecordValues<MatchEventType<Exclude<T, number | symbol>, Events>>>, args: FastEventListenerArgs<Meta>) => any | Promise<any>, options?: FastEventListenOptions<Events, Meta>): FastEventSubscriber;
405
+ on<T extends Exclude<string, Types>>(type: T, listener: TypedFastEventAnyListener<MatchEventType<T, Events>, Meta, Fallback<Context, typeof this>>, options?: FastEventListenOptions): FastEventSubscriber;
310
406
  on(type: '**', listener: TypedFastEventAnyListener<Events, FinalMeta, Fallback<Context, typeof this>>, options?: FastEventListenOptions): FastEventSubscriber;
311
407
  once<T extends Types = Types>(type: T, options?: FastEventListenOptions<Events, FinalMeta>): FastEventSubscriber;
312
- once<T extends string>(type: T, options?: FastEventListenOptions<Events, FinalMeta>): FastEventSubscriber;
313
- once<T extends Types = Types>(type: T, listener: TypedFastEventListener<Exclude<T, number | symbol>, Events[T], FinalMeta, Fallback<Context, typeof this>>, options?: FastEventListenOptions): FastEventSubscriber;
314
- once<T extends string>(type: T, listener: TypedFastEventListener<string, any, FinalMeta, Fallback<Context, typeof this>>, options?: FastEventListenOptions): FastEventSubscriber;
408
+ once<T extends Exclude<string, Types>>(type: T, options?: FastEventListenOptions<Events, FinalMeta>): FastEventSubscriber;
409
+ once<T extends keyof OmitTransformedEvents<Events>>(type: T, listener: TypedFastEventListener<Exclude<T, number | symbol>, Events[T], FinalMeta, Fallback<Context, typeof this>>, options?: FastEventListenOptions): FastEventSubscriber;
410
+ once<T extends keyof PickTransformedEvents<Events>>(type: T, listener: (message: PickPayload<RecordValues<MatchEventType<Exclude<T, number | symbol>, Events>>>, args: FastEventListenerArgs<Meta>) => any | Promise<any>, options?: FastEventListenOptions<Events, Meta>): FastEventSubscriber;
411
+ once<T extends Exclude<string, Types>>(type: T, listener: TypedFastEventAnyListener<MatchEventType<T, Events>, Meta, Fallback<Context, typeof this>>, options?: FastEventListenOptions): FastEventSubscriber;
315
412
  onAny(options?: Pick<FastEventListenOptions, 'prepend'>): FastEventSubscriber;
316
413
  onAny<P = any>(listener: TypedFastEventAnyListener<{
317
414
  [K: string]: P;
@@ -325,19 +422,21 @@ declare class FastEventScope<Events extends Record<string, any> = Record<string,
325
422
  clear(): void;
326
423
  emit(type: Types, directive: symbol): void;
327
424
  emit(type: string, directive: symbol): void;
328
- emit<R = any, T extends Types = Types>(type: T, payload?: Events[T], retain?: boolean): R[];
329
- emit<R = any, T extends string = string>(type: T, payload?: T extends Types ? Events[T] : RecordValues<MatchEventType<T, Events>>, retain?: boolean): R[];
330
- emit<R = any>(type: Types, payload?: Events[Types], options?: FastEventListenerArgs<FinalMeta>): R[];
331
- emit<R = any, T extends string = string>(type: T, payload?: T extends Types ? Events[T] : RecordValues<MatchEventType<T, Events>>, options?: FastEventListenerArgs<FinalMeta>): R[];
332
- emit<R = any>(message: FastEventEmitMessage<Events, FinalMeta>, options?: FastEventListenerArgs<FinalMeta>): R[];
425
+ emit<R = any, T extends Types = Types>(type: T, payload?: PickPayload<Events[T]>, retain?: boolean): R[];
426
+ emit<R = any, T extends string = string>(type: T, payload?: PickPayload<T extends Types ? Events[T] : RecordValues<MatchEventType<T, Events>>>, retain?: boolean): R[];
427
+ emit<R = any, T extends string = string>(type: T, payload?: PickPayload<T extends Types ? Events[T] : RecordValues<MatchEventType<T, Events>>>, options?: FastEventListenerArgs<FinalMeta>): R[];
428
+ emit<R = any>(message: FastEventEmitMessage<AtPayloads<Events>, FinalMeta>, options?: FastEventListenerArgs<FinalMeta>): R[];
333
429
  emit<R = any, T extends string = string>(message: FastEventEmitMessage<{
334
- [K in T]: K extends Types ? Events[K] : any;
430
+ [K in T]: PickPayload<K extends Types ? Events[K] : any>;
335
431
  }, FinalMeta>, options?: FastEventListenerArgs<FinalMeta>): R[];
336
- emitAsync<R = any, T extends Types = Types>(type: T, payload?: Events[T], retain?: boolean): Promise<[R | Error][]>;
337
- emitAsync<R = any, T extends string = string>(type: T, payload?: T extends Types ? Events[T] : any, retain?: boolean): Promise<[R | Error][]>;
338
- emitAsync<R = any, T extends Types = Types>(type: T, payload?: Events[T], options?: FastEventListenerArgs<FinalMeta>): Promise<[R | Error][]>;
339
- emitAsync<R = any, T extends string = string>(type: T, payload?: T extends Types ? Events[T] : any, options?: FastEventListenerArgs<FinalMeta>): Promise<[R | Error][]>;
340
- emitAsync<R = any>(message: TypedFastEventMessage<Events, FinalMeta>, options?: FastEventListenerArgs<FinalMeta>): Promise<[R | Error][]>;
432
+ private _transformMessage;
433
+ emitAsync<R = any, T extends Types = Types>(type: T, payload?: PickPayload<Events[T]>, retain?: boolean): Promise<[R | Error][]>;
434
+ emitAsync<R = any, T extends string = string>(type: T, payload?: PickPayload<T extends Types ? Events[T] : any>, retain?: boolean): Promise<[R | Error][]>;
435
+ emitAsync<R = any, T extends Types = Types>(type: T, payload?: PickPayload<Events[T]>, options?: FastEventListenerArgs<FinalMeta>): Promise<[R | Error][]>;
436
+ emitAsync<R = any, T extends string = string>(type: T, payload?: PickPayload<T extends Types ? Events[T] : any>, options?: FastEventListenerArgs<FinalMeta>): Promise<[R | Error][]>;
437
+ emitAsync<R = any, T extends string = string>(message: FastEventEmitMessage<{
438
+ [K in T]: PickPayload<K extends Types ? Events[K] : any>;
439
+ }, FinalMeta>, options?: FastEventListenerArgs<FinalMeta>): Promise<[R | Error][]>;
341
440
  waitFor<T extends Types>(type: T, timeout?: number): Promise<TypedFastEventMessage<{
342
441
  [key in T]: Events[T];
343
442
  }, FinalMeta>>;
@@ -501,8 +600,9 @@ declare class FastEvent<Events extends Record<string, any> = Record<string, any>
501
600
  on<T extends Types = Types>(type: T, options?: FastEventListenOptions<AllEvents, Meta>): FastEventSubscriber;
502
601
  on<T extends string>(type: T, options?: FastEventListenOptions<AllEvents, Meta>): FastEventSubscriber;
503
602
  on(type: '**', options?: FastEventListenOptions<AllEvents, Meta>): FastEventSubscriber;
504
- on<T extends Types = Types>(type: T, listener: TypedFastEventListener<Exclude<T, number | symbol>, AllEvents[T], Meta, Fallback<Context, typeof this>>, options?: FastEventListenOptions<AllEvents, Meta>): FastEventSubscriber;
505
- on<T extends string>(type: T, listener: TypedFastEventAnyListener<MatchEventType<T, AllEvents>, Meta, Fallback<Context, typeof this>>, options?: FastEventListenOptions<AllEvents, Meta>): FastEventSubscriber;
603
+ on<T extends keyof OmitTransformedEvents<AllEvents>>(type: T, listener: TypedFastEventListener<Exclude<T, number | symbol>, AllEvents[T], Meta, Fallback<Context, typeof this>>, options?: FastEventListenOptions<AllEvents, Meta>): FastEventSubscriber;
604
+ on<T extends keyof PickTransformedEvents<AllEvents>>(type: T, listener: (message: PickPayload<RecordValues<MatchEventType<Exclude<T, number | symbol>, AllEvents>>>, args: FastEventListenerArgs<Meta>) => any | Promise<any>, options?: FastEventListenOptions<AllEvents, Meta>): FastEventSubscriber;
605
+ on<T extends Exclude<string, Types>>(type: T, listener: TypedFastEventAnyListener<MatchEventType<T, AllEvents>, Meta, Fallback<Context, typeof this>>, options?: FastEventListenOptions<AllEvents, Meta>): FastEventSubscriber;
506
606
  on(type: '**', listener: TypedFastEventAnyListener<Record<string, any>, Meta, Fallback<Context, typeof this>>, options?: FastEventListenOptions<AllEvents, Meta>): FastEventSubscriber;
507
607
  /**
508
608
  * 注册一次性事件监听器
@@ -527,8 +627,9 @@ declare class FastEvent<Events extends Record<string, any> = Record<string, any>
527
627
  */
528
628
  once<T extends Types = Types>(type: T, options?: FastEventListenOptions<AllEvents, Meta>): FastEventSubscriber;
529
629
  once<T extends string>(type: T, options?: FastEventListenOptions<AllEvents, Meta>): FastEventSubscriber;
530
- once<T extends Types = Types>(type: T, listener: TypedFastEventListener<Exclude<T, number | symbol>, AllEvents[T], Meta, Fallback<Context, typeof this>>, options?: FastEventListenOptions<AllEvents, Meta>): FastEventSubscriber;
531
- once<T extends string>(type: T, listener: TypedFastEventAnyListener<MatchEventType<T, AllEvents>, Meta, Fallback<Context, typeof this>>, options?: FastEventListenOptions<AllEvents, Meta>): FastEventSubscriber;
630
+ once<T extends keyof OmitTransformedEvents<AllEvents>>(type: T, listener: TypedFastEventListener<Exclude<T, number | symbol>, AllEvents[T], Meta, Fallback<Context, typeof this>>, options?: FastEventListenOptions<AllEvents, Meta>): FastEventSubscriber;
631
+ once<T extends keyof PickTransformedEvents<AllEvents>>(type: T, listener: (message: PickPayload<RecordValues<MatchEventType<Exclude<T, number | symbol>, AllEvents>>>, args: FastEventListenerArgs<Meta>) => any | Promise<any>, options?: FastEventListenOptions<AllEvents, Meta>): FastEventSubscriber;
632
+ once<T extends Exclude<string, Types>>(type: T, listener: TypedFastEventAnyListener<MatchEventType<T, AllEvents>, Meta, Fallback<Context, typeof this>>, options?: FastEventListenOptions<AllEvents, Meta>): FastEventSubscriber;
532
633
  /**
533
634
  * 注册一个监听器,用于监听所有事件
534
635
  * @param listener 事件监听器函数,可以接收任意类型的事件数据
@@ -614,6 +715,7 @@ declare class FastEvent<Events extends Record<string, any> = Record<string, any>
614
715
  private _traverseToPath;
615
716
  private _traverseListeners;
616
717
  private _onListenerError;
718
+ private _setListenerFlags;
617
719
  /**
618
720
  * 执行单个监听器函数
619
721
  * @param listener - 要执行的监听器函数或包装过的监听器对象
@@ -716,16 +818,16 @@ declare class FastEvent<Events extends Record<string, any> = Record<string, any>
716
818
  */
717
819
  emit<T extends Types = Types>(type: T, directive: symbol): any[];
718
820
  emit(type: string, directive: symbol): any[];
719
- emit<R = any, T extends Types = Types>(type: T, payload?: AllEvents[T], retain?: boolean): R[];
720
- emit<R = any, T extends string = string>(type: T, payload?: T extends Types ? AllEvents[T] : RecordValues<MatchEventType<T, AllEvents>>, retain?: boolean): R[];
821
+ emit<R = any, T extends Types = Types>(type: T, payload?: PickPayload<AllEvents[T]>, retain?: boolean): R[];
822
+ emit<R = any, T extends string = string>(type: T, payload: PickPayload<T extends Types ? AllEvents[T] : RecordValues<MatchEventType<T, AllEvents>>>, retain?: boolean): R[];
721
823
  emit<R = any, T extends string = string>(message: FastEventEmitMessage<{
722
824
  [K in T]: K extends Types ? AllEvents[K] : any;
723
825
  }, Meta>, retain?: boolean): R[];
724
826
  emit<R = any>(message: FastEventEmitMessage<AllEvents, Meta>, retain?: boolean): R[];
725
- emit<R = any, T extends Types = Types>(type: T, payload?: AllEvents[T], options?: FastEventListenerArgs<Meta>): R[];
726
- emit<R = any, T extends string = string>(type: T, payload?: T extends Types ? AllEvents[T] : RecordValues<MatchEventType<T, AllEvents>>, options?: FastEventListenerArgs<Meta>): R[];
827
+ emit<R = any, T extends Types = Types>(type: T, payload?: PickPayload<AllEvents[T]>, options?: FastEventListenerArgs<Meta>): R[];
828
+ emit<R = any, T extends string = string>(type: T, payload: PickPayload<T extends Types ? AllEvents[T] : RecordValues<MatchEventType<T, AllEvents>>>, options?: FastEventListenerArgs<Meta>): R[];
727
829
  emit<R = any, T extends string = string>(message: FastEventEmitMessage<{
728
- [K in T]: K extends Types ? AllEvents[K] : any;
830
+ [K in T]: PickPayload<K extends Types ? AllEvents[K] : any>;
729
831
  }, Meta>, options?: FastEventListenerArgs<Meta>): R[];
730
832
  emit<R = any>(message: FastEventEmitMessage<AllEvents, Meta>, options?: FastEventListenerArgs<Meta>): R[];
731
833
  /**
@@ -764,16 +866,16 @@ declare class FastEvent<Events extends Record<string, any> = Record<string, any>
764
866
  * });
765
867
  * ```
766
868
  */
767
- emitAsync<R = any, T extends Types = Types>(type: T, payload?: AllEvents[T], retain?: boolean): Promise<[R | Error][]>;
768
- emitAsync<R = any, T extends string = string>(type: T, payload?: T extends Types ? AllEvents[T] : any, retain?: boolean): Promise<[R | Error][]>;
869
+ emitAsync<R = any, T extends Types = Types>(type: T, payload?: PickPayload<AllEvents[T]>, retain?: boolean): Promise<[R | Error][]>;
870
+ emitAsync<R = any, T extends string = string>(type: T, payload?: PickPayload<T extends Types ? AllEvents[T] : any>, retain?: boolean): Promise<[R | Error][]>;
769
871
  emitAsync<R = any, T extends string = string>(message: FastEventEmitMessage<{
770
- [K in T]: K extends Types ? AllEvents[K] : any;
872
+ [K in T]: PickPayload<K extends Types ? AllEvents[K] : any>;
771
873
  }, Meta>, retain?: boolean): Promise<[R | Error][]>;
772
874
  emitAsync<R = any>(message: FastEventEmitMessage<AllEvents, Meta>, retain?: boolean): Promise<[R | Error][]>;
773
- emitAsync<R = any, T extends string = string>(type: T, payload?: T extends Types ? AllEvents[T] : any, options?: FastEventListenerArgs<Meta>): Promise<[R | Error][]>;
774
- emitAsync<R = any, T extends Types = Types>(type: T, payload?: AllEvents[T], options?: FastEventListenerArgs<Meta>): Promise<[R | Error][]>;
875
+ emitAsync<R = any, T extends string = string>(type: T, payload?: PickPayload<T extends Types ? AllEvents[T] : any>, options?: FastEventListenerArgs<Meta>): Promise<[R | Error][]>;
876
+ emitAsync<R = any, T extends Types = Types>(type: T, payload?: PickPayload<AllEvents[T]>, options?: FastEventListenerArgs<Meta>): Promise<[R | Error][]>;
775
877
  emitAsync<R = any, T extends string = string>(message: FastEventEmitMessage<{
776
- [K in T]: K extends Types ? AllEvents[K] : any;
878
+ [K in T]: PickPayload<K extends Types ? AllEvents[K] : any>;
777
879
  }, Meta>, options?: FastEventListenerArgs<Meta>): Promise<[R | Error][]>;
778
880
  emitAsync<R = any>(message: FastEventEmitMessage<AllEvents, Meta>, options?: FastEventListenerArgs<Meta>): Promise<[R | Error][]>;
779
881
  /**
@@ -958,4 +1060,4 @@ declare function isClass(target: unknown): target is new (...args: any[]) => any
958
1060
 
959
1061
  declare function isFastEvent(target: any): target is FastEvent;
960
1062
 
961
- export { AbortError, CancelError, type ChangeFieldType, type DeepPartial, type Dict, type Expand, type Fallback, FastEvent, FastEventDirectives, type FastEventEmitMessage, FastEventError, type FastEventListenOptions, type FastEventListener, type FastEventListenerArgs, type FastEventListeners, type FastEventMessage, type FastEventMessageExtends, type FastEventMeta, type FastEventOptions, FastEventScope, type FastEventScopeMeta, type FastEventScopeOptions, type FastEventSubscriber, type FastEvents, type FastListenerMeta, type FastListenerNode, type FastListeners, type MatchEventType, type Merge, type MergeUnion, type ObjectKeys, type OptionalItems, type Overloads, type OverrideOptions, QueueOverflowError, type RecordPrefix, type RecordValues, type RequiredItems, type ScopeEvents, TimeoutError, type TypedFastEventAnyListener, type TypedFastEventListener, type TypedFastEventMessage, type TypedFastEventMessageOptional, UnboundError, type Union, type Unique, __FastEventScope__, __FastEvent__, __expandable__, expandable, isClass, isExpandable, isFastEvent, isFastEventMessage, isFastEventScope, isFunction, isPathMatched, isString, isSubsctiber };
1063
+ export { AbortError, type AssertFastMessage, type AtPayloads, CancelError, type ChangeFieldType, type DeepPartial, type Dict, type Expand, type ExpandWildcard, type Fallback, FastEvent, FastEventDirectives, type FastEventEmitMessage, FastEventError, type FastEventListenOptions, type FastEventListener, type FastEventListenerArgs, FastEventListenerFlags, type FastEventListeners, type FastEventMessage, type FastEventMessageExtends, type FastEventMeta, type FastEventOptions, FastEventScope, type FastEventScopeMeta, type FastEventScopeOptions, type FastEventSubscriber, type FastEvents, type FastListenerMeta, type FastListenerNode, type FastListeners, type FastMessagePayload, type MatchEventPayload, type MatchEventType, type Merge, type MergeUnion, type NotPayload, type ObjectKeys, type OmitTransformedEvents, type OptionalItems, type Overloads, type OverrideOptions, type PickPayload, type PickTransformedEvents, QueueOverflowError, type RecordPrefix, type RecordValues, type RequiredItems, type ScopeEvents, TimeoutError, type TransformedEvents, type TypedFastEventAnyListener, type TypedFastEventListener, type TypedFastEventMessage, type TypedFastEventMessageOptional, UnboundError, type Union, type Unique, __FastEventScope__, __FastEvent__, __expandable__, expandable, isClass, isExpandable, isFastEvent, isFastEventMessage, isFastEventScope, isFunction, isPathMatched, isString, isSubsctiber };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var P=Object.defineProperty;var q=(n,e,t)=>e in n?P(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var u=(n,e)=>P(n,"name",{value:e,configurable:true});var p=(n,e,t)=>q(n,typeof e!="symbol"?e+"":e,t);var G=Symbol.for("__FastEvent__"),H=Symbol.for("__FastEventScope__"),S=class S extends Error{constructor(e){super(e);}};u(S,"FastEventError");var m=S,A=class A extends m{};u(A,"TimeoutError");var R=A,M=class M extends m{};u(M,"UnboundError");var d=M,T=class T extends m{};u(T,"AbortError");var _=T,j=class j extends m{};u(j,"CancelError");var x=j,O=class O extends m{};u(O,"QueueOverflowError");var C=O,y={clearRetain:Symbol.for("ClearRetain")};function b(n,e,t,s){let i,r={},o={};return typeof n[0]=="object"?(Object.assign(o,n[0]),r=typeof n[1]=="boolean"?{retain:n[1]}:n[1]||{},i=n[0].meta):(o.type=n[0],o.payload=n[1],r=typeof n[2]=="boolean"?{retain:n[2]}:n[2]||{}),i=Object.assign({},e,t,r.meta,i),Object.keys(i).length===0&&(i=void 0),o.meta=i,r.executor===void 0&&(r.executor=s),[o,r]}u(b,"parseEmitArgs");function W(n){return n?typeof n=="object"&&"__FastEventScope__"in n:false}u(W,"isFastEventScope");function L(n,e,t){let s=n[0],i=W(n[1])?n[1]:void 0,r=(i?n[2]:n[1])||{};return r.meta=Object.assign({},e,r?.meta),r.context=r.context!==void 0?r.context:t,[s,i,r]}u(L,"parseScopeArgs");function g(n,e){return Object.defineProperty(n,"name",{value:e||"anonymous",configurable:true}),n}u(g,"renameFn");var v=class v{constructor(e){p(this,"__FastEventScope__",true);p(this,"_options",{});p(this,"types",{events:void 0,meta:void 0,context:void 0,message:void 0,listeners:void 0,anyListener:void 0});p(this,"prefix","");p(this,"emitter");this._options=Object.assign({},this._initOptions(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);}_initOptions(e){return e}_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(r,o){if(r.type.startsWith(t))return e.call(s.context,Object.assign({},r,{type:r.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){}};u(v,"FastEventScope");var E=v;function w(n,e){if(n.length!==e.length&&n.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:n.length-e.length+1}).fill("*"));for(let s=0;s<n.length;s++)if(t[s]!=="*"&&t[s]!==n[s])return false;return true}u(w,"isPathMatched");function D(n,e){let t=[];for(;;){let s=n.findIndex(i=>e(i));if(s===-1){t.push(s);break}n.splice(s,1);}return t}u(D,"removeItem");function c(n){return n&&typeof n=="function"}u(c,"isFunction");var N=Symbol.for("__expandable__");function ge(n){return n[N]=true,n}u(ge,"expandable");function V(n){return n&&n[N]}u(V,"isExpandable");function I(n){for(let e=0;e<n.length;e++){let t=n[e];Array.isArray(t)&&V(t)&&(n.splice(e,1,...t),e+=t.length-1);}return n}u(I,"expandEmitResults");function B(n){return n&&typeof n=="object"&&"off"in n&&"listener"in n}u(B,"isSubsctiber");function X(n,e){return n.catch(t=>(e&&e(t),Promise.resolve(t)))}u(X,"tryReturnError");var F=class F{constructor(e){p(this,"__FastEvent__",true);p(this,"listeners",{__listeners:[]});p(this,"_options");p(this,"_delimiter","/");p(this,"_context");p(this,"retainedMessages",new Map);p(this,"listenerCount",0);p(this,"types",{events:void 0,meta:void 0,context:void 0,message:void 0,listeners:void 0,anyListener: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},this._initOptions(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}_initOptions(e){return e}_addListener(e,t,s){let{count:i,prepend:r}=s,o=0;return [this._forEachNodes(e,f=>{let h=[t,i,0,s.tag,s.flags];r?(f.__listeners.splice(0,0,h),o=0):(f.__listeners.push(h),o=f.__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 r=e[i];if(r in s||(s[r]={__listeners:[]}),i===e.length-1){let o=s[r];return t(o,s),o}else s=s[r];}}_removeListener(e,t,s){s&&D(e.__listeners,i=>{i=Array.isArray(i)?i[0]:i;let r=i===s;return r&&(this.listenerCount--,c(this._options.onRemoveListener)&&this._options.onRemoveListener(t.join(this._delimiter),s)),r});}_pipeListener(e,t){return t.forEach(s=>{e=g(s(e),e.name);}),e}on(){let e=arguments[0],t=c(arguments[1])?arguments[1]:(this._options.onMessage||this.onMessage).bind(this),s=Object.assign({count:0,flags:0,prepend:false},c(arguments[1])?arguments[2]:arguments[1]);if(e.length===0)throw new Error("event type cannot be empty");if(c(this._options.onAddListener)){let f=this._options.onAddListener(e,t,s);if(f===false)throw new x;if(B(f))return f}let i=e.split(this._delimiter);if(s.pipes&&s.pipes.length>0&&(t=this._pipeListener(t,s.pipes)),c(s.filter)||c(s.off)){let f=t;t=g(function(h,l){if(c(s.off)&&s.off.call(this,h,l)){a();return}if(c(s.filter)){if(s.filter.call(this,h,l))return f.call(this,h,l)}else return f.call(this,h,l)},t.name);}let[r,o]=this._addListener(i,t,s),a=u(()=>r&&this._removeListener(r,i,t),"off");return this._emitRetainMessage(e,r,o),{off:a,listener:t}}once(){return c(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=c(e[0])?void 0:e[0],s=c(e[0])?e[0]:e[1],i=t?t.split(this._delimiter):[],r=t?t.includes("*"):false;if(t&&!r)this._traverseToPath(this.listeners,i,o=>{s?this._removeListener(o,i,s):t&&(o.__listeners=[]);});else {let o=r?[]:i;this._traverseListeners(this.listeners,o,(a,f)=>{(s!==void 0||r&&w(a,i))&&(s?this._removeListener(f,i,s):f.__listeners=[]);});}}offAll(e){if(e){let t=e.split(this._delimiter),s=0;this._traverseListeners(this.listeners,t,(i,r)=>{s+=r.__listeners.length,r.__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:[]};}c(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 r=e.split(this._delimiter);this.retainedMessages.forEach((o,a)=>{let f=a.split(this._delimiter);w(f,r)&&i.push(o);});}else this.retainedMessages.has(e)&&i.push(this.retainedMessages.get(e));t&&i.forEach(r=>{this._executeListeners([t],r,{},o=>o[0]===t.__listeners[s][0]);});}_traverseToPath(e,t,s,i=0,r){if(i>=t.length){s(e);return}let o=t[i];if(r===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 r=u((o,a,f)=>{a(f,o);for(let[h,l]of Object.entries(o))h.startsWith("__")||l&&r(l,a,[...f,h]);},"traverseNodes");r(i,s,[]);}_onListenerError(e,t,s,i){if(i instanceof Error&&(i._emitter=`${e.name||"anonymous"}:${t.type}`),c(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 r=e.call(this.context,t,s);return i&&r&&r instanceof Promise&&(r=X(r,o=>this._onListenerError(e,t,s,o))),r}catch(r){return this._onListenerError(e,t,s,r)}}_getListenerExecutor(e){if(!e)return;let t=e.executor||this._options.executor;if(c(t))return t}_executeListeners(e,t,s,i){if(!e||e.length===0)return [];let r=e.reduce((a,f)=>a.concat(f.__listeners.filter(h=>c(i)?i(h,f):true).map((h,l)=>[h,l,f.__listeners])),[]);this._decListenerExecCount(r);let o=this._getListenerExecutor(s);if(o){let a=o(r.map(f=>f[0]),t,s,this._executeListener.bind(this));return Array.isArray(a)?a:[a]}else return r.map(a=>this._executeListener(a[0][0],t,s,true))}_decListenerExecCount(e){for(let t=e.length-1;t>=0;t--){let s=e[t][0];s[2]++,s[1]>0&&s[1]<=s[2]&&e[t][2].splice(t,1);}}getListeners(e){let t=[],s=e.split(this._delimiter);return this._traverseToPath(this.listeners,s,i=>{t.push(i);}),t[0].__listeners}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);c(t.parseArgs)&&t.parseArgs(e,t);let s=e.type.split(this._delimiter);t.retain&&this.retainedMessages.set(e.type,e);let i=[],r=[];if(this._traverseToPath(this.listeners,s,o=>{r.push(o);}),c(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(r,e,t)),c(this._options.onAfterExecuteListener)&&this._options.onAfterExecuteListener.call(this,e,i,r),this._options.expandEmitResults&&I(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 r,o,a=u(f=>{clearTimeout(r),o&&o.off(),s(f);},"listener");t&&t>0&&(r=setTimeout(()=>{o&&o.off(),i(new Error("wait for event<"+e+"> is timeout"));},t)),o=this.on(e,a);})}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}};u(F,"FastEvent");var $=F;function Xe(n){return n?typeof n=="object"&&"type"in n:false}u(Xe,"isFastEventMessage");function ze(n){return n&&typeof n=="string"}u(ze,"isString");function Je(n){return typeof n=="function"&&(n.toString().startsWith("class ")||n.prototype?.constructor===n)}u(Je,"isClass");function Ze(n){return n?typeof n=="object"&&"__FastEvent__"in n:false}u(Ze,"isFastEvent");exports.AbortError=_;exports.CancelError=x;exports.FastEvent=$;exports.FastEventDirectives=y;exports.FastEventError=m;exports.FastEventScope=E;exports.QueueOverflowError=C;exports.TimeoutError=R;exports.UnboundError=d;exports.__FastEventScope__=H;exports.__FastEvent__=G;exports.__expandable__=N;exports.expandable=ge;exports.isClass=Je;exports.isExpandable=V;exports.isFastEvent=Ze;exports.isFastEventMessage=Xe;exports.isFastEventScope=W;exports.isFunction=c;exports.isPathMatched=w;exports.isString=ze;exports.isSubsctiber=B;//# sourceMappingURL=index.js.map
1
+ 'use strict';var R=Object.defineProperty;var z=(i,t,e)=>t in i?R(i,t,{enumerable:true,configurable:true,writable:true,value:e}):i[t]=e;var f=(i,t)=>R(i,"name",{value:t,configurable:true});var h=(i,t,e)=>z(i,typeof t!="symbol"?t+"":t,e);var H=Symbol.for("__FastEvent__"),J=Symbol.for("__FastEventScope__"),S=class S extends Error{constructor(t){super(t);}};f(S,"FastEventError");var m=S,A=class A extends m{};f(A,"TimeoutError");var C=A,M=class M extends m{};f(M,"UnboundError");var x=M,w=class w extends m{};f(w,"AbortError");var d=w,F=class F extends m{};f(F,"CancelError");var y=F,j=class j extends m{};f(j,"QueueOverflowError");var W=j,b={clearRetain:Symbol.for("ClearRetain")};var _=function(i){return i[i.Transformed=1]="Transformed",i}({});function L(i,t,e,s){let n,r={},o={};return typeof i[0]=="object"?(Object.assign(o,i[0]),r=typeof i[1]=="boolean"?{retain:i[1]}:i[1]||{},n=i[0].meta):(o.type=i[0],o.payload=i[1],r=typeof i[2]=="boolean"?{retain:i[2]}:i[2]||{}),n=Object.assign({},t,e,r.meta,n),Object.keys(n).length===0&&(n=void 0),o.meta=n,r.executor===void 0&&(r.executor=s),[o,r]}f(L,"parseEmitArgs");function D(i){return i?typeof i=="object"&&"__FastEventScope__"in i:false}f(D,"isFastEventScope");function E(i,t,e){let s=i[0],n=D(i[1])?i[1]:void 0,r=(n?i[2]:i[1])||{};return r.meta=Object.assign({},t,r?.meta),r.context=r.context!==void 0?r.context:e,[s,n,r]}f(E,"parseScopeArgs");function g(i,t){return Object.defineProperty(i,"name",{value:t||"anonymous",configurable:true}),i}f(g,"renameFn");function u(i){return i&&typeof i=="function"}f(u,"isFunction");var T=class T{constructor(t){h(this,"__FastEventScope__",true);h(this,"_options",{});h(this,"types",{events:void 0,meta:void 0,context:void 0,message:void 0,listeners:void 0,anyListener:void 0});h(this,"prefix","");h(this,"emitter");this._options=Object.assign({},this._initOptions(t));}get context(){return this.options.context||this}get options(){return this._options}bind(t,e,s){this.emitter=t,this._options=Object.assign(this._options,{scope:e},s),e.length>0&&!e.endsWith(t.options.delimiter)&&(this.prefix=e+t.options.delimiter);}_initOptions(t){return t}_getScopeListener(t){let e=this.prefix;if(e.length===0)return t;t||(t=(this._options.onMessage||this.onMessage).bind(this));let s=this;return g(function(r,o){let p=o.rawEventType||r.type;if(p.startsWith(e)){let c=((o.flags||0)&_.Transformed)>0?r:Object.assign({},r,{type:p.substring(e.length)});return t.call(s.context,c,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(){if(!this.emitter)throw new x;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(){return this.on("**",...arguments)}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(){if(arguments.length===2&&typeof arguments[0]=="string"&&arguments[1]===b.clearRetain)return this.emitter.emit(this._getScopeType(arguments[0]));let[t,e]=L(arguments,this.emitter.options.meta,this.options.meta,this.options.executor);return t.type=this._getScopeType(t.type),this._transformMessage(t,e),this.emitter.emit(t,e)}_transformMessage(t,e){return u(this._options.transform)&&(e.rawEventType=t.type,e.flags=(e.flags||0)|_.Transformed,t.payload=this._options.transform.call(this,t)),t}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],s=await this.emitter.waitFor(this._getScopeType(t),e);return Object.assign({},s,{type:this._fixScopeType(s.type)})}scope(){let[t,e,s]=E(arguments,this.options.meta,this.options.context),n;return e?n=e:n=new T,n.bind(this.emitter,this.prefix+t,s),n}onMessage(t,e){}};f(T,"FastEventScope");var v=T;function O(i,t){if(i.length!==t.length&&i.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:i.length-t.length+1}).fill("*"));for(let s=0;s<i.length;s++)if(e[s]!=="*"&&e[s]!==i[s])return false;return true}f(O,"isPathMatched");function N(i,t){let e=[];for(;;){let s=i.findIndex(n=>t(n));if(s===-1){e.push(s);break}i.splice(s,1);}return e}f(N,"removeItem");var V=Symbol.for("__expandable__");function vt(i){return i[V]=true,i}f(vt,"expandable");function I(i){return i&&i[V]}f(I,"isExpandable");function B(i){for(let t=0;t<i.length;t++){let e=i[t];Array.isArray(e)&&I(e)&&(i.splice(t,1,...e),t+=e.length-1);}return i}f(B,"expandEmitResults");function X(i){return i&&typeof i=="object"&&"off"in i&&"listener"in i}f(X,"isSubsctiber");function $(i,t){return i.catch(e=>(t&&t(e),Promise.resolve(e)))}f($,"tryReturnError");var P=class P{constructor(t){h(this,"__FastEvent__",true);h(this,"listeners",{__listeners:[]});h(this,"_options");h(this,"_delimiter","/");h(this,"_context");h(this,"retainedMessages",new Map);h(this,"listenerCount",0);h(this,"types",{events:void 0,meta:void 0,context:void 0,message:void 0,listeners:void 0,anyListener: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},this._initOptions(t)),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}_initOptions(t){return t}_addListener(t,e,s){let{count:n,prepend:r}=s,o=0;return [this._forEachNodes(t,a=>{let c=[e,n,0,s.tag,s.flags];r?(a.__listeners.splice(0,0,c),o=0):(a.__listeners.push(c),o=a.__listeners.length-1),this.listenerCount++;}),o]}_enableDevTools(){this.options.debug&&globalThis.__FLEXEVENT_DEVTOOLS__&&globalThis.__FLEXEVENT_DEVTOOLS__.add(this);}_forEachNodes(t,e){if(t.length===0)return;let s=this.listeners;for(let n=0;n<t.length;n++){let r=t[n];if(r in s||(s[r]={__listeners:[]}),n===t.length-1){let o=s[r];return e(o,s),o}else s=s[r];}}_removeListener(t,e,s){s&&N(t.__listeners,n=>{n=Array.isArray(n)?n[0]:n;let r=n===s;return r&&(this.listenerCount--,u(this._options.onRemoveListener)&&this._options.onRemoveListener(e.join(this._delimiter),s)),r});}_pipeListener(t,e){return e.forEach(s=>{t=g(s(t),t.name);}),t}on(){let t=arguments[0],e=u(arguments[1])?arguments[1]:(this._options.onMessage||this.onMessage).bind(this),s=Object.assign({count:0,flags:0,prepend:false},u(arguments[1])?arguments[2]:arguments[1]);if(t.length===0)throw new Error("event type cannot be empty");if(u(this._options.onAddListener)){let a=this._options.onAddListener(t,e,s);if(a===false)throw new y;if(X(a))return a}let n=t.split(this._delimiter);if(s.pipes&&s.pipes.length>0&&(e=this._pipeListener(e,s.pipes)),u(s.filter)||u(s.off)){let a=e;e=g(function(c,l){if(u(s.off)&&s.off.call(this,c,l)){p();return}if(u(s.filter)){if(s.filter.call(this,c,l))return a.call(this,c,l)}else return a.call(this,c,l)},e.name);}let[r,o]=this._addListener(n,e,s),p=f(()=>r&&this._removeListener(r,n,e),"off");return this._emitRetainMessage(t,r,o),{off:p,listener:e}}once(){return u(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,e){}off(){let t=arguments,e=u(t[0])?void 0:t[0],s=u(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=>{s?this._removeListener(o,n,s):e&&(o.__listeners=[]);});else {let o=r?[]:n;this._traverseListeners(this.listeners,o,(p,a)=>{(s!==void 0||r&&O(p,n))&&(s?this._removeListener(a,n,s):a.__listeners=[]);});}}offAll(t){if(t){let e=t.split(this._delimiter),s=0;this._traverseListeners(this.listeners,e,(n,r)=>{s+=r.__listeners.length,r.__listeners=[];}),this.listenerCount-=s,this._removeRetainedEvents(t);}else {let e=0;this._traverseListeners(this.listeners,[],(s,n)=>{e+=n.__listeners.length;}),this.listenerCount-=e,this.retainedMessages.clear(),this.listeners={__listeners:[]};}u(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);}_emitRetainMessage(t,e,s){let n=[];if(t.includes("*")){let r=t.split(this._delimiter);this.retainedMessages.forEach((o,p)=>{let a=p.split(this._delimiter);O(a,r)&&n.push(o);});}else this.retainedMessages.has(t)&&n.push(this.retainedMessages.get(t));e&&n.forEach(r=>{this._executeListeners([e],r,{},o=>o[0]===e.__listeners[s][0]);});}_traverseToPath(t,e,s,n=0,r){if(n>=e.length){s(t);return}let o=e[n];if(r===true){this._traverseToPath(t,e,s,n+1,true);return}"*"in t&&this._traverseToPath(t["*"],e,s,n+1),"**"in t&&this._traverseToPath(t["**"],e,s,n+1,true),o in t&&this._traverseToPath(t[o],e,s,n+1);}_traverseListeners(t,e,s){let n=t;e&&e.length>0&&this._traverseToPath(t,e,o=>{n=o;});let r=f((o,p,a)=>{p(a,o);for(let[c,l]of Object.entries(o))c.startsWith("__")||l&&r(l,p,[...a,c]);},"traverseNodes");r(n,s,[]);}_onListenerError(t,e,s,n){if(n instanceof Error&&(n._emitter=`${t.name||"anonymous"}:${e.type}`),u(this._options.onListenerError))try{this._options.onListenerError.call(this,n,t,e,s);}catch{}if(this._options.ignoreErrors)return n;throw n}_setListenerFlags(t,e){return !t||t===0?e:t|e}_executeListener(t,e,s,n=false){try{if(s&&s.abortSignal&&s.abortSignal.aborted)return this._onListenerError(t,e,s,new d(t.name));let r=((s?.flags||0)&_.Transformed)>0,o=t.call(this.context,r?e.payload:e,s);return n&&o&&o instanceof Promise&&(o=$(o,p=>this._onListenerError(t,e,s,p))),o}catch(r){return this._onListenerError(t,e,s,r)}}_getListenerExecutor(t){if(!t)return;let e=t.executor||this._options.executor;if(u(e))return e}_executeListeners(t,e,s,n){if(!t||t.length===0)return [];let r=t.reduce((p,a)=>p.concat(a.__listeners.filter(c=>u(n)?n(c,a):true).map((c,l)=>[c,l,a.__listeners])),[]);u(this._options.transform)&&(s||(s={}),s.rawEventType=e.type,e.payload=this._options.transform.call(this,e),s.flags=this._setListenerFlags(s.flags,_.Transformed)),this._decListenerExecCount(r);let o=this._getListenerExecutor(s);if(o){let p=o(r.map(a=>a[0]),e,s,this._executeListener.bind(this));return Array.isArray(p)?p:[p]}else return r.map(p=>this._executeListener(p[0][0],e,s,true))}_decListenerExecCount(t){for(let e=t.length-1;e>=0;e--){let s=t[e][0];s[2]++,s[1]>0&&s[1]<=s[2]&&t[e][2].splice(e,1);}}getListeners(t){let e=[],s=t.split(this._delimiter);return this._traverseToPath(this.listeners,s,n=>{e.push(n);}),e[0].__listeners}emit(){if(arguments.length===2&&typeof arguments[0]=="string"&&arguments[1]===b.clearRetain)return this.retainedMessages.delete(arguments[0]),[];let[t,e]=L(arguments,this.options.meta);u(e.parseArgs)&&e.parseArgs(t,e);let s=t.type.split(this._delimiter);e.retain&&this.retainedMessages.set(t.type,t);let n=[],r=[];if(this._traverseToPath(this.listeners,s,o=>{r.push(o);}),u(this._options.onBeforeExecuteListener)){let o=this._options.onBeforeExecuteListener.call(this,t,e);if(Array.isArray(o))return o;if(o===false)throw new d(t.type)}return u(this._options.transform)&&(t.payload=this._options.transform.call(this,t),e.rawEventType=t.type,e.flags=(e.flags||0)|_.Transformed),n.push(...this._executeListeners(r,t,e)),u(this._options.onAfterExecuteListener)&&this._options.onAfterExecuteListener.call(this,t,n,r),this._options.expandEmitResults&&B(n),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((s,n)=>{let r,o,p=f(a=>{clearTimeout(r),o&&o.off(),s(a);},"listener");e&&e>0&&(r=setTimeout(()=>{o&&o.off(),n(new Error("wait for event<"+t+"> is timeout"));},e)),o=this.on(t,p);})}scope(){let[t,e,s]=E(arguments,this.options.meta,this.options.context),n;return e?n=e:n=new v,n.bind(this,t,s),n}};f(P,"FastEvent");var q=P;function Jt(i){return i?typeof i=="object"&&"type"in i:false}f(Jt,"isFastEventMessage");function Zt(i){return i&&typeof i=="string"}f(Zt,"isString");function Qt(i){return typeof i=="function"&&(i.toString().startsWith("class ")||i.prototype?.constructor===i)}f(Qt,"isClass");function se(i){return i?typeof i=="object"&&"__FastEvent__"in i:false}f(se,"isFastEvent");exports.AbortError=d;exports.CancelError=y;exports.FastEvent=q;exports.FastEventDirectives=b;exports.FastEventError=m;exports.FastEventListenerFlags=_;exports.FastEventScope=v;exports.QueueOverflowError=W;exports.TimeoutError=C;exports.UnboundError=x;exports.__FastEventScope__=J;exports.__FastEvent__=H;exports.__expandable__=V;exports.expandable=vt;exports.isClass=Qt;exports.isExpandable=I;exports.isFastEvent=se;exports.isFastEventMessage=Jt;exports.isFastEventScope=D;exports.isFunction=u;exports.isPathMatched=O;exports.isString=Zt;exports.isSubsctiber=X;//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map