@context-action/core 0.8.0 → 0.8.4

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.js CHANGED
@@ -314,27 +314,91 @@ var ActionGuard = class {
314
314
  this.guards = /* @__PURE__ */ new Map();
315
315
  this.maxIdleTime = 6e4;
316
316
  this.cleanupIntervalMs = 3e4;
317
+ this.maxGuards = 1e3;
318
+ this.accessOrder = [];
317
319
  if (autoCleanup) this.startAutoCleanup();
318
320
  }
319
321
  /**
320
322
  * Start automatic cleanup of idle guard states
321
- *
323
+ *
322
324
  * @internal
323
325
  */
324
326
  startAutoCleanup() {
325
327
  this.cleanupInterval = setInterval(() => {
326
- const now = Date.now();
327
- const keysToDelete = [];
328
- this.guards.forEach((state, key) => {
328
+ this.performCleanup();
329
+ }, this.cleanupIntervalMs);
330
+ }
331
+ /**
332
+ * 🔧 Optimized cleanup with early exit and batched operations
333
+ *
334
+ * @internal
335
+ */
336
+ performCleanup() {
337
+ const guardCount = this.guards.size;
338
+ if (guardCount === 0) return;
339
+ const now = Date.now();
340
+ const keysToDelete = [];
341
+ if (guardCount <= 10) this.guards.forEach((state, key) => {
342
+ const isIdle = now - state.lastExecuted > this.maxIdleTime;
343
+ const hasActiveTimers = state.debounceTimer || state.throttleTimer;
344
+ if (isIdle && !hasActiveTimers) keysToDelete.push(key);
345
+ });
346
+ else {
347
+ const entriesToCheck = Math.min(this.accessOrder.length, Math.ceil(guardCount / 4));
348
+ for (let i = 0; i < entriesToCheck; i++) {
349
+ const key = this.accessOrder[i];
350
+ if (!key) continue;
351
+ const state = this.guards.get(key);
352
+ if (!state) {
353
+ keysToDelete.push(key);
354
+ continue;
355
+ }
329
356
  const isIdle = now - state.lastExecuted > this.maxIdleTime;
330
357
  const hasActiveTimers = state.debounceTimer || state.throttleTimer;
331
358
  if (isIdle && !hasActiveTimers) keysToDelete.push(key);
332
- });
333
- if (keysToDelete.length > 0) {
334
- keysToDelete.forEach((key) => this.guards.delete(key));
335
- if (typeof process !== "undefined" && process.env?.DEBUG_CONTEXT_ACTION) console.debug(`[ActionGuard] Cleaned up ${keysToDelete.length} idle guards`);
336
359
  }
337
- }, this.cleanupIntervalMs);
360
+ }
361
+ if (keysToDelete.length > 0) {
362
+ keysToDelete.forEach((key) => {
363
+ this.guards.delete(key);
364
+ const accessIndex = this.accessOrder.indexOf(key);
365
+ if (accessIndex !== -1) this.accessOrder.splice(accessIndex, 1);
366
+ });
367
+ if (typeof process !== "undefined" && process.env?.DEBUG_CONTEXT_ACTION) console.debug(`[ActionGuard] Cleaned up ${keysToDelete.length} idle guards`);
368
+ }
369
+ }
370
+ /**
371
+ * 🔧 Update access order for LRU tracking
372
+ *
373
+ * @internal
374
+ */
375
+ updateAccessOrder(key) {
376
+ const existingIndex = this.accessOrder.indexOf(key);
377
+ if (existingIndex !== -1) this.accessOrder.splice(existingIndex, 1);
378
+ this.accessOrder.push(key);
379
+ }
380
+ /**
381
+ * 🔧 Evict oldest guards if max limit exceeded
382
+ *
383
+ * @internal
384
+ */
385
+ evictIfNeeded() {
386
+ if (this.guards.size >= this.maxGuards) {
387
+ const evictCount = Math.ceil(this.maxGuards * .1);
388
+ this.accessOrder.slice(0, evictCount).forEach((key) => {
389
+ const state = this.guards.get(key);
390
+ if (state) {
391
+ if (state.debounceTimer) {
392
+ clearTimeout(state.debounceTimer);
393
+ if (state.debounceResolve) state.debounceResolve(false);
394
+ }
395
+ if (state.throttleTimer) clearTimeout(state.throttleTimer);
396
+ }
397
+ this.guards.delete(key);
398
+ });
399
+ this.accessOrder = this.accessOrder.slice(evictCount);
400
+ if (typeof process !== "undefined" && process.env?.DEBUG_CONTEXT_ACTION) console.debug(`[ActionGuard] Evicted ${evictCount} oldest guards due to limit`);
401
+ }
338
402
  }
339
403
  /**
340
404
  * Apply debouncing to an action
@@ -359,6 +423,7 @@ var ActionGuard = class {
359
423
  * @internal
360
424
  */
361
425
  async debounce(actionKey, debounceMs) {
426
+ this.evictIfNeeded();
362
427
  /** Get or create guard state for this action */
363
428
  let state = this.guards.get(actionKey);
364
429
  if (!state) {
@@ -373,6 +438,7 @@ var ActionGuard = class {
373
438
  };
374
439
  this.guards.set(actionKey, state);
375
440
  }
441
+ this.updateAccessOrder(actionKey);
376
442
  /** Clear any existing debounce timer to restart the delay period */
377
443
  if (state.debounceTimer) {
378
444
  clearTimeout(state.debounceTimer);
@@ -417,6 +483,7 @@ var ActionGuard = class {
417
483
  * @internal
418
484
  */
419
485
  throttle(actionKey, throttleMs) {
486
+ this.evictIfNeeded();
420
487
  /** Get or create guard state for this action */
421
488
  let state = this.guards.get(actionKey);
422
489
  if (!state) {
@@ -431,6 +498,7 @@ var ActionGuard = class {
431
498
  };
432
499
  this.guards.set(actionKey, state);
433
500
  }
501
+ this.updateAccessOrder(actionKey);
434
502
  const now = Date.now();
435
503
  const timeSinceLastExecution = now - state.lastExecuted;
436
504
  /** Check if enough time has passed since last execution */
@@ -548,6 +616,7 @@ var ActionGuard = class {
548
616
  this.cleanupInterval = void 0;
549
617
  }
550
618
  this.clearAll();
619
+ this.accessOrder = [];
551
620
  }
552
621
  /**
553
622
  * 🆕 Get statistics about active guards
@@ -632,7 +701,11 @@ var OperationQueue = class {
632
701
  * - 작업 완료 시 대기 중인 프로세스에게 자동 알림
633
702
  */
634
703
  async processQueue() {
635
- if (this.processingPromise) return this.processingPromise;
704
+ if (this.processingPromise) {
705
+ await this.processingPromise;
706
+ if (this.queue.length > 0 && !this.processingPromise) return this.processQueue();
707
+ return;
708
+ }
636
709
  this.processingPromise = this._doProcess();
637
710
  try {
638
711
  await this.processingPromise;
@@ -761,6 +834,35 @@ var OperationQueue = class {
761
834
  *
762
835
  * @public
763
836
  */
837
+ /**
838
+ * Type guard to determine if an object is DispatchOptions
839
+ * Extracted as utility function for reuse and performance
840
+ *
841
+ * @param obj - Object to check
842
+ * @returns True if object is DispatchOptions
843
+ * @internal
844
+ */
845
+ function isDispatchOptions(obj) {
846
+ if (!obj || typeof obj !== "object") return false;
847
+ if ("debounce" in obj && typeof obj.debounce === "number") return true;
848
+ if ("throttle" in obj && typeof obj.throttle === "number") return true;
849
+ if ("executionMode" in obj) return true;
850
+ if ("signal" in obj && obj.signal instanceof AbortSignal) return true;
851
+ if ("immediate" in obj && typeof obj.immediate === "boolean") return true;
852
+ if ("queuePriority" in obj && typeof obj.queuePriority === "number") return true;
853
+ if ("timeout" in obj && typeof obj.timeout === "number") return true;
854
+ if ("retryOnError" in obj && typeof obj.retryOnError === "object") return true;
855
+ if ("autoAbort" in obj && typeof obj.autoAbort === "object") return true;
856
+ if ("filter" in obj && typeof obj.filter === "object" && obj.filter !== null) {
857
+ const filter = obj.filter;
858
+ if ("handlerIds" in filter || "excludeHandlerIds" in filter || "priority" in filter || "custom" in filter) return true;
859
+ }
860
+ if ("result" in obj && typeof obj.result === "object" && obj.result !== null) {
861
+ const result = obj.result;
862
+ if ("strategy" in result || "merger" in result || "collect" in result || "maxResults" in result || "includeErrors" in result) return true;
863
+ }
864
+ return false;
865
+ }
764
866
  var ActionRegister = class {
765
867
  constructor(config = {}) {
766
868
  this.pipelines = /* @__PURE__ */ new Map();
@@ -809,18 +911,16 @@ var ActionRegister = class {
809
911
  * @public
810
912
  */
811
913
  get actions() {
812
- return new Proxy({}, { get: (target, prop) => {
914
+ if (!this._actionsProxy) this._actionsProxy = new Proxy({}, { get: (_target, prop) => {
813
915
  if (typeof prop === "string" && this.pipelines.has(prop)) {
814
916
  const actionKey = prop;
815
917
  return (payloadOrOptions, options) => {
816
- const isDispatchOptions = (obj) => {
817
- return obj && typeof obj === "object" && ("debounce" in obj || "throttle" in obj || "executionMode" in obj || "signal" in obj || "immediate" in obj || "filter" in obj || "result" in obj);
818
- };
819
918
  if (payloadOrOptions && isDispatchOptions(payloadOrOptions)) return this.dispatch(actionKey, void 0, payloadOrOptions);
820
919
  else return this.dispatch(actionKey, payloadOrOptions, options);
821
920
  };
822
921
  }
823
922
  } });
923
+ return this._actionsProxy;
824
924
  }
825
925
  /**
826
926
  * Actions-based dispatching with result collection
@@ -846,18 +946,16 @@ var ActionRegister = class {
846
946
  * @returns Proxy object with action functions that return ExecutionResult
847
947
  */
848
948
  get actionsWithResult() {
849
- return new Proxy({}, { get: (target, prop) => {
949
+ if (!this._actionsWithResultProxy) this._actionsWithResultProxy = new Proxy({}, { get: (_target, prop) => {
850
950
  if (typeof prop === "string" && this.pipelines.has(prop)) {
851
951
  const actionKey = prop;
852
952
  return (payloadOrOptions, options) => {
853
- const isDispatchOptions = (obj) => {
854
- return obj && typeof obj === "object" && ("debounce" in obj || "throttle" in obj || "executionMode" in obj || "signal" in obj || "immediate" in obj || "filter" in obj || "result" in obj);
855
- };
856
953
  if (payloadOrOptions && isDispatchOptions(payloadOrOptions)) return this.dispatchWithResult(actionKey, void 0, payloadOrOptions);
857
954
  else return this.dispatchWithResult(actionKey, payloadOrOptions, options);
858
955
  };
859
956
  }
860
957
  } });
958
+ return this._actionsWithResultProxy;
861
959
  }
862
960
  /**
863
961
  * Register an action handler with optional configuration
@@ -1056,6 +1154,10 @@ var ActionRegister = class {
1056
1154
  pipelineMap: Object.fromEntries(Array.from(this.pipelines.entries()).map(([k, v]) => [k, v.length]))
1057
1155
  });
1058
1156
  if (!pipeline || pipeline.length === 0) {
1157
+ const warningMessage = `⚠️ Action '${String(action)}' has no registered handlers. This action will be ignored.`;
1158
+ console.warn(warningMessage);
1159
+ console.warn("💡 Tip: Register a handler using registry.register() before dispatching this action.");
1160
+ console.warn("📋 Available actions:", Array.from(this.pipelines.keys()));
1059
1161
  this.log(`No handlers found for action '${String(action)}', dispatch cancelled`, {}, "warn");
1060
1162
  return;
1061
1163
  }
@@ -1152,26 +1254,32 @@ var ActionRegister = class {
1152
1254
  errors: []
1153
1255
  };
1154
1256
  const pipeline = this.pipelines.get(action);
1155
- if (!pipeline || pipeline.length === 0) return {
1156
- success: true,
1157
- aborted: false,
1158
- abortReason: void 0,
1159
- terminated: false,
1160
- result: void 0,
1161
- successResults: [],
1162
- results: [],
1163
- failedResults: [],
1164
- execution: {
1165
- duration: 0,
1166
- handlersExecuted: 0,
1167
- handlersSkipped: 0,
1168
- handlersFailed: 0,
1169
- startTime: _startTime,
1170
- endTime: _startTime
1171
- },
1172
- handlers: [],
1173
- errors: []
1174
- };
1257
+ if (!pipeline || pipeline.length === 0) {
1258
+ const warningMessage = `⚠️ Action '${String(action)}' has no registered handlers. This action will be ignored.`;
1259
+ console.warn(warningMessage);
1260
+ console.warn("💡 Tip: Register a handler using registry.register() before dispatching this action.");
1261
+ console.warn("📋 Available actions:", Array.from(this.pipelines.keys()));
1262
+ return {
1263
+ success: true,
1264
+ aborted: false,
1265
+ abortReason: void 0,
1266
+ terminated: false,
1267
+ result: void 0,
1268
+ successResults: [],
1269
+ results: [],
1270
+ failedResults: [],
1271
+ execution: {
1272
+ duration: 0,
1273
+ handlersExecuted: 0,
1274
+ handlersSkipped: 0,
1275
+ handlersFailed: 0,
1276
+ startTime: _startTime,
1277
+ endTime: _startTime
1278
+ },
1279
+ handlers: [],
1280
+ errors: []
1281
+ };
1282
+ }
1175
1283
  const filteredHandlers = options?.filter ? this.filterHandlers(pipeline, options.filter) : pipeline;
1176
1284
  const actionKey = String(action);
1177
1285
  const guardResult = await this.applyActionGuardControlsWithResult(actionKey, filteredHandlers, options, _startTime, pipeline.length);