@context-action/core 0.7.3 → 0.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2024 Jun Woo Bang
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/dist/index.cjs CHANGED
@@ -50,6 +50,15 @@ async function executeSequential(context, createController) {
50
50
  const controller = createController(registration, i);
51
51
  try {
52
52
  if (context.aborted) break;
53
+ if (registration.config.condition) try {
54
+ if (!registration.config.condition(context.payload)) {
55
+ i++;
56
+ continue;
57
+ }
58
+ } catch {
59
+ i++;
60
+ continue;
61
+ }
53
62
  const result = registration.handler(context.payload, controller);
54
63
  if (registration.config.blocking) {
55
64
  const handlerResult = result instanceof Promise ? await result : result;
@@ -66,7 +75,6 @@ async function executeSequential(context, createController) {
66
75
  timestamp: handlerError.timestamp,
67
76
  severity: "non-blocking"
68
77
  });
69
- return void 0;
70
78
  });
71
79
  nonBlockingPromises.push(promiseWithErrorHandling);
72
80
  } else if (result !== void 0 && !context.terminated) context.results.push(result);
@@ -74,8 +82,20 @@ async function executeSequential(context, createController) {
74
82
  if (context.terminated) break;
75
83
  /** Handle jump to priority AFTER handler execution */
76
84
  if (context.jumpToPriority !== void 0) {
77
- const jumpIndex = context.handlers.findIndex((handler) => handler.config.priority === context.jumpToPriority);
78
- if (jumpIndex !== -1) {
85
+ context.jumpCount = (context.jumpCount || 0) + 1;
86
+ if (context.jumpCount > (context.maxJumps || 10)) {
87
+ console.error(`[ActionRegister] ERROR: Maximum jump limit (${context.maxJumps || 10}) exceeded. Aborting to prevent infinite loop. Check your jumpToPriority logic and conditions.`);
88
+ context.aborted = true;
89
+ context.abortReason = `Maximum jump limit exceeded (${context.jumpCount} jumps)`;
90
+ context.jumpToPriority = void 0;
91
+ break;
92
+ }
93
+ const jumpIndex = context.handlers.findIndex((handler) => (handler.config.priority || 0) <= context.jumpToPriority);
94
+ if (jumpIndex !== -1 && jumpIndex !== i) {
95
+ if (jumpIndex < i) {
96
+ const targetHandler = context.handlers[jumpIndex];
97
+ if (targetHandler && !targetHandler.config.condition) console.warn(`[ActionRegister] WARNING: Backward jumpToPriority to handler '${targetHandler.config.id || "unnamed"}' without condition. This may cause infinite loops! Consider adding a condition to prevent re-execution. Jump count: ${context.jumpCount}/${context.maxJumps || 10}`);
98
+ }
79
99
  i = jumpIndex;
80
100
  context.jumpToPriority = void 0;
81
101
  continue;
@@ -86,19 +106,18 @@ async function executeSequential(context, createController) {
86
106
  } else i++;
87
107
  } catch (error) {
88
108
  const handlerError = handleExecutionError(error, registration);
89
- throw handlerError.error;
109
+ errors.push(handlerError);
110
+ if (registration.config.blocking) throw handlerError.error;
111
+ i++;
90
112
  }
91
113
  }
92
114
  if (nonBlockingPromises.length > 0) await Promise.allSettled(nonBlockingPromises);
93
- if (errors.length > 0) {
94
- const handlerErrors = errors.map((err) => ({
95
- handlerId: err.handlerId,
96
- error: err.error,
97
- timestamp: err.timestamp,
98
- severity: "non-blocking"
99
- }));
100
- context.collectedErrors = handlerErrors;
101
- }
115
+ if (errors.length > 0) context.collectedErrors = errors.map((err) => ({
116
+ handlerId: err.handlerId,
117
+ error: err.error,
118
+ timestamp: err.timestamp,
119
+ severity: "non-blocking"
120
+ }));
102
121
  }
103
122
  /**
104
123
  * Execute handlers in parallel mode (all at once)
@@ -126,12 +145,27 @@ async function executeParallel(context, createController) {
126
145
  const handlerPromises = runnableHandlers.map(async (registration, _index) => {
127
146
  const controller = createController(registration, _index);
128
147
  try {
148
+ if (registration.config.condition) try {
149
+ if (!registration.config.condition(context.payload)) return {
150
+ success: true,
151
+ handlerId: registration.id,
152
+ result: void 0,
153
+ terminated: false,
154
+ skipped: true
155
+ };
156
+ } catch {
157
+ return {
158
+ success: true,
159
+ handlerId: registration.id,
160
+ result: void 0,
161
+ terminated: false,
162
+ skipped: true
163
+ };
164
+ }
129
165
  const result = registration.handler(context.payload, controller);
130
166
  let handlerResult;
131
- if (result instanceof Promise) {
132
- const resolved = await result;
133
- handlerResult = resolved;
134
- } else handlerResult = result;
167
+ if (result instanceof Promise) handlerResult = await result;
168
+ else handlerResult = result;
135
169
  /** Collect result if handler returned something and pipeline wasn't terminated */
136
170
  if (handlerResult !== void 0 && !context.terminated) context.results.push(handlerResult);
137
171
  return {
@@ -154,22 +188,15 @@ async function executeParallel(context, createController) {
154
188
  const results = await Promise.allSettled(handlerPromises);
155
189
  /** Check for any rejected blocking handlers */
156
190
  const failures = results.filter((result, index) => {
157
- if (result.status === "rejected") {
158
- const registration = runnableHandlers[index];
159
- return registration?.config.blocking ?? false;
160
- }
191
+ if (result.status === "rejected") return runnableHandlers[index]?.config.blocking ?? false;
161
192
  return false;
162
193
  });
163
- if (failures.length > 0) {
164
- const firstFailure = failures[0];
165
- throw firstFailure.reason;
166
- }
194
+ if (failures.length > 0) throw failures[0].reason;
167
195
  /** Check if any handler terminated the pipeline */
168
196
  const terminatedResults = results.filter((result) => result.status === "fulfilled" && result.value.terminated);
169
197
  if (terminatedResults.length > 0) {
170
198
  context.terminated = true;
171
- const firstTerminated = terminatedResults[0];
172
- context.terminationResult = firstTerminated.value.result;
199
+ context.terminationResult = terminatedResults[0].value.result;
173
200
  }
174
201
  }
175
202
  /**
@@ -200,12 +227,29 @@ async function executeRace(context, createController) {
200
227
  const handlerPromises = runnableHandlers.map(async (registration, _index) => {
201
228
  const controller = createController(registration, _index);
202
229
  try {
230
+ if (registration.config.condition) try {
231
+ if (!registration.config.condition(context.payload)) return {
232
+ success: true,
233
+ handlerId: registration.id,
234
+ registration,
235
+ result: void 0,
236
+ terminated: false,
237
+ skipped: true
238
+ };
239
+ } catch {
240
+ return {
241
+ success: true,
242
+ handlerId: registration.id,
243
+ registration,
244
+ result: void 0,
245
+ terminated: false,
246
+ skipped: true
247
+ };
248
+ }
203
249
  const result = registration.handler(context.payload, controller);
204
250
  let handlerResult;
205
- if (result instanceof Promise) {
206
- const resolved = await result;
207
- handlerResult = resolved;
208
- } else handlerResult = result;
251
+ if (result instanceof Promise) handlerResult = await result;
252
+ else handlerResult = result;
209
253
  return {
210
254
  success: true,
211
255
  handlerId: registration.id,
@@ -628,8 +672,7 @@ var OperationQueue = class {
628
672
  * 🆕 작업 완료 신호 - 대기 중인 프로세스들에게 알림
629
673
  */
630
674
  notifyOperationComplete() {
631
- const resolvers = this.pendingResolvers.splice(0);
632
- resolvers.forEach((resolve) => resolve());
675
+ this.pendingResolvers.splice(0).forEach((resolve) => resolve());
633
676
  }
634
677
  /**
635
678
  * 🆕 새로운 작업 추가 신호 - processQueue에서 호출
@@ -686,8 +729,7 @@ var OperationQueue = class {
686
729
  });
687
730
  this.queue = [];
688
731
  this.processingPromise = null;
689
- const resolvers = this.pendingResolvers.splice(0);
690
- resolvers.forEach((resolve) => resolve());
732
+ this.pendingResolvers.splice(0).forEach((resolve) => resolve());
691
733
  }
692
734
  /**
693
735
  * 큐 크기 조회
@@ -726,6 +768,7 @@ var ActionRegister = class {
726
768
  this.executionMode = "sequential";
727
769
  this.actionExecutionModes = /* @__PURE__ */ new Map();
728
770
  this.unregisterFunctions = /* @__PURE__ */ new Map();
771
+ this.lastRegisteredTimestamps = /* @__PURE__ */ new Map();
729
772
  this.filterCacheDisabled = true;
730
773
  this.handlerIdCounter = 0;
731
774
  this.controllerPool = [];
@@ -761,8 +804,7 @@ var ActionRegister = class {
761
804
  */
762
805
  register(action, handler, config = {}) {
763
806
  const handlerId = config.id || this.generateHandlerId(action);
764
- const unregisterFn = this._performRegistrationSync(action, handler, config, handlerId);
765
- return unregisterFn;
807
+ return this._performRegistrationSync(action, handler, config, handlerId);
766
808
  }
767
809
  /**
768
810
  * 🆕 Unified logging method with cached debug mode check
@@ -846,8 +888,9 @@ var ActionRegister = class {
846
888
  once: config.once ?? false,
847
889
  debounce: config.debounce ?? void 0,
848
890
  throttle: config.throttle ?? void 0,
849
- replaceExisting: config.replaceExisting ?? false,
850
- cleanup: config.cleanup
891
+ replaceExisting: config.replaceExisting ?? true,
892
+ cleanup: config.cleanup,
893
+ condition: config.condition
851
894
  },
852
895
  id: handlerId
853
896
  };
@@ -861,18 +904,16 @@ var ActionRegister = class {
861
904
  if (existingIndex !== -1) {
862
905
  const existing = pipeline[existingIndex];
863
906
  const existingUnregister = this.unregisterFunctions.get(handlerId);
864
- if (config.replaceExisting) {
865
- if (existingUnregister) {
866
- existingUnregister();
867
- this.unregisterFunctions.delete(handlerId);
868
- }
869
- if (existing && typeof existing.cleanup === "function") try {
870
- existing.cleanup();
907
+ if (registration.config.replaceExisting) {
908
+ if (existing && existing.config.cleanup && typeof existing.config.cleanup === "function") try {
909
+ existing.config.cleanup();
871
910
  } catch (cleanupError) {
872
911
  this.log(`Cleanup error for replaced handler: ${String(action)}`, cleanupError, "warn");
873
912
  }
913
+ if (existingUnregister) this.unregisterFunctions.delete(handlerId);
874
914
  pipeline[existingIndex] = registration;
875
915
  pipeline.sort((a, b) => b.config.priority - a.config.priority);
916
+ this.lastRegisteredTimestamps.set(action, /* @__PURE__ */ new Date());
876
917
  const newUnregister = this.createUnregisterFunction(action, handlerId, registration);
877
918
  this.unregisterFunctions.set(handlerId, newUnregister);
878
919
  this.log(`Handler replaced: ${String(action)}`, {
@@ -902,6 +943,7 @@ var ActionRegister = class {
902
943
  }
903
944
  pipeline.push(registration);
904
945
  pipeline.sort((a, b) => b.config.priority - a.config.priority);
946
+ this.lastRegisteredTimestamps.set(action, /* @__PURE__ */ new Date());
905
947
  const unregister = this.createUnregisterFunction(action, handlerId, registration);
906
948
  this.unregisterFunctions.set(handlerId, unregister);
907
949
  this.log(`Handler registered: ${String(action)}`, {
@@ -979,12 +1021,10 @@ var ActionRegister = class {
979
1021
  }
980
1022
  }
981
1023
  if (debounceMs !== void 0) {
982
- const shouldProceed = await this.actionGuard.debounce(actionKey, debounceMs);
983
- if (!shouldProceed) return;
1024
+ if (!await this.actionGuard.debounce(actionKey, debounceMs)) return;
984
1025
  }
985
1026
  if (throttleMs !== void 0) {
986
- const shouldProceed = this.actionGuard.throttle(actionKey, throttleMs);
987
- if (!shouldProceed) return;
1027
+ if (!this.actionGuard.throttle(actionKey, throttleMs)) return;
988
1028
  }
989
1029
  const currentExecutionMode = options?.executionMode || this.actionExecutionModes.get(action) || this.executionMode;
990
1030
  const context = {
@@ -995,6 +1035,8 @@ var ActionRegister = class {
995
1035
  abortReason: void 0,
996
1036
  currentIndex: 0,
997
1037
  jumpToPriority: void 0,
1038
+ jumpCount: 0,
1039
+ maxJumps: 10,
998
1040
  executionMode: currentExecutionMode,
999
1041
  results: [],
1000
1042
  terminated: false,
@@ -1086,6 +1128,8 @@ var ActionRegister = class {
1086
1128
  abortReason: void 0,
1087
1129
  currentIndex: 0,
1088
1130
  jumpToPriority: void 0,
1131
+ jumpCount: 0,
1132
+ maxJumps: 10,
1089
1133
  executionMode: currentExecutionMode,
1090
1134
  results: [],
1091
1135
  terminated: false,
@@ -1111,8 +1155,7 @@ var ActionRegister = class {
1111
1155
  let errors = [];
1112
1156
  try {
1113
1157
  await this.executePipeline(context, autoAbortController, options?.autoAbort);
1114
- const contextWithErrors = context;
1115
- errors = contextWithErrors.collectedErrors || [];
1158
+ errors = context.collectedErrors || [];
1116
1159
  const executedCount = Math.min(context.currentIndex + (context.aborted ? 0 : 1), filteredHandlers.length);
1117
1160
  for (let i = 0; i < executedCount; i++) {
1118
1161
  const handler = filteredHandlers[i];
@@ -1121,8 +1164,7 @@ var ActionRegister = class {
1121
1164
  if (handlerResult) handlerResult.executed = true;
1122
1165
  }
1123
1166
  } catch (error) {
1124
- const contextWithErrors = context;
1125
- errors = contextWithErrors.collectedErrors || [];
1167
+ errors = context.collectedErrors || [];
1126
1168
  executionError = error instanceof Error ? error : new Error(String(error));
1127
1169
  errors.push({
1128
1170
  handlerId: "pipeline",
@@ -1198,8 +1240,7 @@ var ActionRegister = class {
1198
1240
  }
1199
1241
  }
1200
1242
  if (debounceMs !== void 0) {
1201
- const shouldProceed = await this.actionGuard.debounce(actionKey, debounceMs);
1202
- if (!shouldProceed) return {
1243
+ if (!await this.actionGuard.debounce(actionKey, debounceMs)) return {
1203
1244
  success: false,
1204
1245
  aborted: true,
1205
1246
  abortReason: "Debounced execution",
@@ -1221,8 +1262,7 @@ var ActionRegister = class {
1221
1262
  };
1222
1263
  }
1223
1264
  if (throttleMs !== void 0) {
1224
- const shouldProceed = this.actionGuard.throttle(actionKey, throttleMs);
1225
- if (!shouldProceed) return {
1265
+ if (!this.actionGuard.throttle(actionKey, throttleMs)) return {
1226
1266
  success: false,
1227
1267
  aborted: true,
1228
1268
  abortReason: "Throttled execution",
@@ -1272,7 +1312,11 @@ var ActionRegister = class {
1272
1312
  if (autoAbortController && autoAbortOptions?.allowHandlerAbort) autoAbortController.abort(reason);
1273
1313
  };
1274
1314
  controller.modifyPayload = (modifier) => {
1275
- context.payload = modifier(context.payload);
1315
+ try {
1316
+ context.payload = modifier(context.payload);
1317
+ } catch (modificationError) {
1318
+ this.log("Payload modification error", modificationError, "warn");
1319
+ }
1276
1320
  };
1277
1321
  controller.getPayload = () => context.payload;
1278
1322
  controller.jumpToPriority = (priority) => {
@@ -1306,7 +1350,7 @@ var ActionRegister = class {
1306
1350
  if (!filterOptions) return handlers;
1307
1351
  const handlerIdSet = filterOptions.handlerIds ? new Set(filterOptions.handlerIds) : null;
1308
1352
  const excludeIdSet = filterOptions.excludeHandlerIds ? new Set(filterOptions.excludeHandlerIds) : null;
1309
- const filtered = handlers.filter((registration) => {
1353
+ return handlers.filter((registration) => {
1310
1354
  const config = registration.config;
1311
1355
  if (handlerIdSet && !handlerIdSet.has(config.id)) return false;
1312
1356
  if (excludeIdSet && excludeIdSet.has(config.id)) return false;
@@ -1318,14 +1362,14 @@ var ActionRegister = class {
1318
1362
  if (filterOptions.custom && !filterOptions.custom(config)) return false;
1319
1363
  return true;
1320
1364
  });
1321
- return filtered;
1322
1365
  }
1323
1366
  processResults(context, resultOptions) {
1324
- if (!resultOptions || !resultOptions.collect) return void 0;
1325
1367
  const results = context.results;
1326
1368
  if (context.terminated && context.terminationResult !== void 0) return context.terminationResult;
1369
+ if (!resultOptions) return results.length > 0 ? results[results.length - 1] : void 0;
1370
+ if (!resultOptions.collect && !resultOptions.strategy) return;
1327
1371
  const limitedResults = resultOptions.maxResults ? results.slice(0, resultOptions.maxResults) : results;
1328
- if (limitedResults.length === 0) return void 0;
1372
+ if (limitedResults.length === 0) return;
1329
1373
  switch (resultOptions.strategy) {
1330
1374
  case "first": return limitedResults[0];
1331
1375
  case "last": return limitedResults[limitedResults.length - 1];
@@ -1336,7 +1380,9 @@ var ActionRegister = class {
1336
1380
  case "custom":
1337
1381
  if (resultOptions.merger) return resultOptions.merger(limitedResults);
1338
1382
  throw new Error("Custom result strategy requires a merger function");
1339
- default: return limitedResults;
1383
+ default:
1384
+ if (resultOptions.collect) return limitedResults;
1385
+ return limitedResults[limitedResults.length - 1];
1340
1386
  }
1341
1387
  }
1342
1388
  async executePipeline(context, autoAbortController, autoAbortOptions) {
@@ -1373,6 +1419,10 @@ var ActionRegister = class {
1373
1419
  });
1374
1420
  }
1375
1421
  });
1422
+ if (pipeline.length === 0) {
1423
+ this.pipelines.delete(action);
1424
+ this.lastRegisteredTimestamps.delete(action);
1425
+ }
1376
1426
  }
1377
1427
  /**
1378
1428
  * Get the number of registered handlers for an action
@@ -1426,6 +1476,7 @@ var ActionRegister = class {
1426
1476
  */
1427
1477
  clearAction(action) {
1428
1478
  this.pipelines.delete(action);
1479
+ this.lastRegisteredTimestamps.delete(action);
1429
1480
  }
1430
1481
  /**
1431
1482
  * Remove all handlers for all actions
@@ -1436,6 +1487,7 @@ var ActionRegister = class {
1436
1487
  */
1437
1488
  clearAll() {
1438
1489
  this.pipelines.clear();
1490
+ this.lastRegisteredTimestamps.clear();
1439
1491
  }
1440
1492
  /**
1441
1493
  * Get the name of this action register
@@ -1483,13 +1535,13 @@ var ActionRegister = class {
1483
1535
  priority,
1484
1536
  handlers: handlers.map((h) => ({ id: h.config.id }))
1485
1537
  }));
1486
- const executionStats = void 0;
1487
1538
  return {
1488
1539
  action,
1489
1540
  handlerCount: pipeline.length,
1490
1541
  totalHandlers: pipeline.length,
1491
1542
  handlersByPriority,
1492
- executionStats
1543
+ executionStats: void 0,
1544
+ lastRegistered: this.lastRegisteredTimestamps.get(action)
1493
1545
  };
1494
1546
  }
1495
1547
  /**
@@ -1570,6 +1622,10 @@ var ActionRegister = class {
1570
1622
  if (index !== -1) {
1571
1623
  pipeline.splice(index, 1);
1572
1624
  this.unregisterFunctions.delete(handlerId);
1625
+ if (pipeline.length === 0) {
1626
+ this.pipelines.delete(action);
1627
+ this.lastRegisteredTimestamps.delete(action);
1628
+ }
1573
1629
  if (registration.config.cleanup && typeof registration.config.cleanup === "function") try {
1574
1630
  registration.config.cleanup();
1575
1631
  } catch (cleanupError) {
@@ -1577,7 +1633,8 @@ var ActionRegister = class {
1577
1633
  }
1578
1634
  this.log(`Handler unregistered: ${String(action)}`, {
1579
1635
  handlerId,
1580
- remainingHandlers: pipeline.length
1636
+ remainingHandlers: pipeline.length,
1637
+ actionRemoved: pipeline.length === 0
1581
1638
  });
1582
1639
  }
1583
1640
  };
@@ -1610,15 +1667,14 @@ var ActionRegister = class {
1610
1667
  * @public
1611
1668
  */
1612
1669
  destroy() {
1613
- this.unregisterFunctions.forEach((unregister) => {
1614
- try {
1615
- unregister();
1616
- } catch (error) {
1617
- this.log("Error during unregister in destroy", error, "error");
1618
- }
1619
- });
1620
1670
  this.unregisterFunctions.clear();
1671
+ for (const [action, pipeline] of this.pipelines.entries()) for (const registration of pipeline) if (registration.config.cleanup && typeof registration.config.cleanup === "function") try {
1672
+ registration.config.cleanup();
1673
+ } catch (cleanupError) {
1674
+ this.log(`Cleanup error for handler during destroy: ${String(action)}`, cleanupError, "warn");
1675
+ }
1621
1676
  this.pipelines.clear();
1677
+ this.lastRegisteredTimestamps.clear();
1622
1678
  this.actionGuard.destroy();
1623
1679
  this.dispatchQueue?.clear?.();
1624
1680
  this.actionExecutionModes.clear();
package/dist/index.d.cts CHANGED
@@ -22,6 +22,7 @@ interface HandlerConfig {
22
22
  throttle?: number;
23
23
  replaceExisting?: boolean;
24
24
  cleanup?: () => void;
25
+ condition?: (payload: any) => boolean;
25
26
  }
26
27
  interface HandlerRegistration<T = any, R = void> {
27
28
  handler: ActionHandler<T, R>;
@@ -37,6 +38,8 @@ interface PipelineContext<T = any, R = void> {
37
38
  abortReason: string | undefined;
38
39
  currentIndex: number;
39
40
  jumpToPriority: number | undefined;
41
+ jumpCount?: number;
42
+ maxJumps?: number;
40
43
  executionMode: ExecutionMode;
41
44
  results: R[];
42
45
  terminated: boolean;
@@ -161,6 +164,7 @@ declare class ActionRegister<T extends ActionPayloadMap = ActionPayloadMap> {
161
164
  private executionMode;
162
165
  private actionExecutionModes;
163
166
  private unregisterFunctions;
167
+ private lastRegisteredTimestamps;
164
168
  readonly name: string;
165
169
  private readonly registryConfig;
166
170
  private readonly isDebugMode;