@oxog/utils 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/README.md +101 -43
  3. package/dist/chunk-25WW2FCA.js +34 -0
  4. package/dist/chunk-25WW2FCA.js.map +1 -0
  5. package/dist/chunk-DEVWOLUI.cjs +112 -0
  6. package/dist/chunk-DEVWOLUI.cjs.map +1 -0
  7. package/dist/chunk-IUDFQZIP.js +99 -0
  8. package/dist/chunk-IUDFQZIP.js.map +1 -0
  9. package/dist/chunk-PZ5AY32C.js +9 -0
  10. package/dist/chunk-PZ5AY32C.js.map +1 -0
  11. package/dist/chunk-Q7SFCCGT.cjs +11 -0
  12. package/dist/chunk-Q7SFCCGT.cjs.map +1 -0
  13. package/dist/chunk-SWG777R6.cjs +40 -0
  14. package/dist/chunk-SWG777R6.cjs.map +1 -0
  15. package/dist/index.cjs +482 -191
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts +288 -15
  18. package/dist/index.d.ts +288 -15
  19. package/dist/index.js +428 -186
  20. package/dist/index.js.map +1 -1
  21. package/dist/plugins/async.cjs +90 -107
  22. package/dist/plugins/async.cjs.map +1 -1
  23. package/dist/plugins/async.d.cts +19 -6
  24. package/dist/plugins/async.d.ts +19 -6
  25. package/dist/plugins/async.js +89 -106
  26. package/dist/plugins/async.js.map +1 -1
  27. package/dist/plugins/deep.cjs +183 -59
  28. package/dist/plugins/deep.cjs.map +1 -1
  29. package/dist/plugins/deep.d.cts +25 -7
  30. package/dist/plugins/deep.d.ts +25 -7
  31. package/dist/plugins/deep.js +183 -59
  32. package/dist/plugins/deep.js.map +1 -1
  33. package/dist/plugins/guard.cjs +2 -0
  34. package/dist/plugins/guard.cjs.map +1 -1
  35. package/dist/plugins/guard.js +2 -0
  36. package/dist/plugins/guard.js.map +1 -1
  37. package/dist/plugins/transform.cjs +6 -3
  38. package/dist/plugins/transform.cjs.map +1 -1
  39. package/dist/plugins/transform.js +6 -3
  40. package/dist/plugins/transform.js.map +1 -1
  41. package/dist/{types-XmRC5wYO.d.cts → types-B-i5UbJo.d.cts} +24 -7
  42. package/dist/{types-XmRC5wYO.d.ts → types-B-i5UbJo.d.ts} +24 -7
  43. package/package.json +15 -10
package/dist/index.d.ts CHANGED
@@ -1,10 +1,12 @@
1
- import { P as Plugin } from './types-XmRC5wYO.js';
1
+ import { P as Plugin } from './types-B-i5UbJo.js';
2
2
 
3
3
  /**
4
4
  * Safely access a deeply nested property in an object.
5
5
  *
6
6
  * Returns the value at the specified path, or the default value
7
7
  * if the path doesn't exist. Supports both dot notation and array syntax.
8
+ * `null`/`undefined` values and functions are treated as missing. Inherited
9
+ * `__proto__`, `constructor` and `prototype` are never traversed.
8
10
  *
9
11
  * @param obj - The source object to access
10
12
  * @param path - The path to the property (dot notation: 'a.b.c')
@@ -41,7 +43,13 @@ declare function get<T, P extends string, D = undefined>(obj: T, path: P, defaul
41
43
  * Immutable property setter.
42
44
  *
43
45
  * Creates a new object with the value at the specified path updated.
44
- * The original object is not modified.
46
+ * The original object is not modified; arrays along the path are copied as
47
+ * arrays and untouched branches are shared with the original.
48
+ * Supports dot and bracket notation (`'items[0].id'`). Missing containers are
49
+ * created as arrays for numeric bracket segments and as objects otherwise.
50
+ *
51
+ * @throws {InvalidPathError} if the path contains `__proto__`, `constructor`
52
+ * or `prototype` (prototype pollution protection).
45
53
  *
46
54
  * @param obj - The source object
47
55
  * @param path - The path to update (dot notation)
@@ -71,7 +79,10 @@ declare function set<T, P extends string>(obj: T, path: P, value: any): T;
71
79
  * Mutable property setter.
72
80
  *
73
81
  * Updates the value at the specified path by mutating the original object.
74
- * Use this only when mutation is intentional.
82
+ * Use this only when mutation is intentional. Path syntax is the same as {@link set}.
83
+ *
84
+ * @throws {InvalidPathError} if the path contains `__proto__`, `constructor`
85
+ * or `prototype` (prototype pollution protection).
75
86
  *
76
87
  * @param obj - The source object (will be mutated)
77
88
  * @param path - The path to update (dot notation)
@@ -91,8 +102,9 @@ declare function setMut<T, P extends string>(obj: T, path: P, value: any): T;
91
102
  /**
92
103
  * Check if a path exists in an object.
93
104
  *
94
- * Returns true if the path resolves to a value that is not undefined.
95
- * For arrays, returns true even for out-of-bounds indices.
105
+ * Returns true if every segment of the path is an own property and the
106
+ * final value is not undefined. Inherited properties (`toString`,
107
+ * `constructor`, ...) and out-of-bounds array indexes return false.
96
108
  *
97
109
  * @param obj - The source object
98
110
  * @param path - The path to check (dot notation)
@@ -285,7 +297,7 @@ declare namespace object {
285
297
  *
286
298
  * @see {@link keyBy} for indexing by property
287
299
  */
288
- declare function groupBy<T, K extends keyof T>(arr: T[], key: K | ((item: T) => string)): Record<string, T[]>;
300
+ declare function groupBy<T, K extends keyof T>(arr: T[], key: K | ((item: T) => string | number)): Record<string, T[]>;
289
301
  /**
290
302
  * Create an object keyed by a property value.
291
303
  *
@@ -316,7 +328,7 @@ declare function groupBy<T, K extends keyof T>(arr: T[], key: K | ((item: T) =>
316
328
  *
317
329
  * @see {@link groupBy} for grouping
318
330
  */
319
- declare function keyBy<T, K extends keyof T>(arr: T[], key: K | ((item: T) => string)): Record<string, T>;
331
+ declare function keyBy<T, K extends keyof T>(arr: T[], key: K | ((item: T) => string | number)): Record<string, T>;
320
332
  /**
321
333
  * Split array into chunks of specified size.
322
334
  *
@@ -334,6 +346,7 @@ declare function keyBy<T, K extends keyof T>(arr: T[], key: K | ((item: T) => st
334
346
  * ```typescript
335
347
  * chunk([1, 2, 3], 1); // [[1], [2], [3]]
336
348
  * chunk([1, 2, 3], 5); // [[1, 2, 3]]
349
+ * chunk([1, 2, 3], 0); // []
337
350
  * ```
338
351
  */
339
352
  declare function chunk<T>(arr: T[], size: number): T[][];
@@ -383,7 +396,7 @@ declare function uniq<T>(arr: T[]): T[];
383
396
  *
384
397
  * @see {@link uniq} for simple deduplication
385
398
  */
386
- declare function uniqBy<T, K extends keyof T>(arr: T[], key: K | ((item: T) => string)): T[];
399
+ declare function uniqBy<T, K extends keyof T>(arr: T[], key: K | ((item: T) => unknown)): T[];
387
400
  /**
388
401
  * Flatten nested arrays up to specified depth.
389
402
  *
@@ -481,7 +494,7 @@ declare function last<T>(arr: T[], n?: number): T | T[] | undefined;
481
494
  * @example Get one random element
482
495
  * ```typescript
483
496
  * const arr = [1, 2, 3, 4, 5];
484
- * sample(arr); // Random element (e.g., 3)
497
+ * sample(arr); // One random element in an array (e.g., [3])
485
498
  * ```
486
499
  *
487
500
  * @example Get multiple random elements
@@ -608,7 +621,9 @@ declare function capitalize(str: string): string;
608
621
  * Truncate string to specified length with optional suffix.
609
622
  *
610
623
  * @param str - String to truncate
611
- * @param length - Number of characters to keep before adding suffix
624
+ * @param length - Number of characters (UTF-16 code units) to keep before
625
+ * adding the suffix. A surrogate pair is never split, so slightly fewer
626
+ * units may be kept.
612
627
  * @param suffix - Suffix to append when truncated (default: '...')
613
628
  * @returns Truncated string
614
629
  *
@@ -690,19 +705,145 @@ declare namespace string {
690
705
  export { string_camelCase as camelCase, string_capitalize as capitalize, string_kebabCase as kebabCase, string_pascalCase as pascalCase, string_slugify as slugify, string_snakeCase as snakeCase, string_template as template, string_truncate as truncate };
691
706
  }
692
707
 
708
+ type EventHandler = (...args: any[]) => void;
709
+ /**
710
+ * Simple event bus for inter-plugin communication.
711
+ *
712
+ * Allows plugins to emit and listen to events, enabling
713
+ * communication between different parts of the system.
714
+ */
715
+ declare class EventBus {
716
+ private listeners;
717
+ private scopedHandlers;
718
+ /**
719
+ * Register an event listener.
720
+ *
721
+ * @param event - Event name to listen for
722
+ * @param handler - Function to call when event is emitted
723
+ */
724
+ on(event: string, handler: (...args: any[]) => void): void;
725
+ /**
726
+ * Unregister an event listener.
727
+ *
728
+ * @param event - Event name
729
+ * @param handler - Function to remove
730
+ */
731
+ off(event: string, handler: (...args: any[]) => void): void;
732
+ /**
733
+ * Emit an event to all registered listeners.
734
+ *
735
+ * @param event - Event name to emit
736
+ * @param args - Arguments to pass to handlers
737
+ */
738
+ emit(event: string, ...args: any[]): void;
739
+ /**
740
+ * Remove all listeners for an event or all events.
741
+ *
742
+ * @param event - Event name to clear (if not provided, clears all)
743
+ */
744
+ removeAllListeners(event?: string): void;
745
+ /**
746
+ * Get the number of listeners for an event.
747
+ *
748
+ * @param event - Event name
749
+ * @returns Number of listeners
750
+ */
751
+ listenerCount(event: string): number;
752
+ /**
753
+ * Register an event listener with a scope (e.g., plugin name).
754
+ * Scoped listeners can be removed all at once using removeScope().
755
+ *
756
+ * @param scope - Scope identifier (e.g., plugin name)
757
+ * @param event - Event name to listen for
758
+ * @param handler - Function to call when event is emitted
759
+ */
760
+ onScoped(scope: string, event: string, handler: EventHandler): void;
761
+ /**
762
+ * Remove all listeners registered under a specific scope.
763
+ * Useful for cleanup when a plugin is unregistered.
764
+ *
765
+ * @param scope - Scope identifier to remove
766
+ */
767
+ removeScope(scope: string): void;
768
+ /**
769
+ * Check if a scope has any registered listeners.
770
+ *
771
+ * @param scope - Scope identifier
772
+ * @returns True if scope has listeners
773
+ */
774
+ hasScope(scope: string): boolean;
775
+ }
776
+ /**
777
+ * Scoped event bus wrapper for plugins.
778
+ * Automatically tracks all listeners under a scope for easy cleanup.
779
+ */
780
+ declare class ScopedEventBus {
781
+ private readonly eventBus;
782
+ private readonly scope;
783
+ constructor(eventBus: EventBus, scope: string);
784
+ /**
785
+ * Register an event listener (automatically scoped).
786
+ */
787
+ on(event: string, handler: EventHandler): void;
788
+ /**
789
+ * Unregister an event listener.
790
+ */
791
+ off(event: string, handler: EventHandler): void;
792
+ /**
793
+ * Emit an event.
794
+ */
795
+ emit(event: string, ...args: any[]): void;
796
+ /**
797
+ * Remove all listeners registered by this scoped bus.
798
+ */
799
+ destroy(): void;
800
+ }
801
+
802
+ /**
803
+ * Plugin lifecycle states.
804
+ */
805
+ type PluginState = 'registered' | 'initializing' | 'active' | 'error' | 'destroyed';
806
+ /**
807
+ * Kernel initialization state.
808
+ */
809
+ type KernelState = 'idle' | 'initializing' | 'initialized' | 'destroyed';
810
+ /**
811
+ * Options for kernel initialization.
812
+ */
813
+ interface KernelOptions<TContext> {
814
+ /**
815
+ * Initial context value. If not provided, an empty object is used.
816
+ */
817
+ context?: TContext;
818
+ }
693
819
  /**
694
820
  * Micro-kernel for plugin system.
695
821
  *
696
822
  * Manages plugin registration, initialization, and lifecycle.
697
823
  * Provides event bus for inter-plugin communication.
824
+ *
825
+ * Features:
826
+ * - Plugin state tracking (registered, initializing, active, error, destroyed)
827
+ * - Automatic scoped event listeners (cleaned up on unregister)
828
+ * - Topological sorting for dependency resolution
829
+ * - Circular dependency detection
830
+ * - Partial initialization rollback
831
+ * - Race condition prevention
832
+ * - Late plugin registration support
698
833
  */
699
834
  declare class Kernel<TContext = unknown> {
700
835
  private plugins;
701
836
  private context;
702
837
  private eventBus;
838
+ private state;
839
+ private initPromise;
840
+ constructor(options?: KernelOptions<TContext>);
703
841
  /**
704
842
  * Register a plugin with the kernel.
705
843
  *
844
+ * If the kernel is already initialized, the plugin will be
845
+ * automatically initialized after registration.
846
+ *
706
847
  * @param plugin - Plugin to register
707
848
  * @throws {PluginAlreadyRegisteredError} If plugin name already exists
708
849
  * @throws {PluginDependencyMissingError} If plugin dependencies are not met
@@ -711,17 +852,39 @@ declare class Kernel<TContext = unknown> {
711
852
  /**
712
853
  * Initialize all registered plugins.
713
854
  *
714
- * Calls onInit() for each plugin that has it.
715
- * Plugins are initialized in the order they were registered.
855
+ * Plugins are initialized in topological order based on dependencies.
856
+ * If initialization fails, already initialized plugins are rolled back.
857
+ *
858
+ * @throws {CircularDependencyError} If circular dependency detected
859
+ * @throws {PluginInitializationError} If a plugin fails to initialize
716
860
  */
717
861
  init(): Promise<void>;
862
+ private doInit;
863
+ /**
864
+ * Initialize a single plugin.
865
+ */
866
+ private initPlugin;
867
+ /**
868
+ * Destroy a single plugin.
869
+ */
870
+ private destroyPlugin;
871
+ /**
872
+ * Topological sort of plugins based on dependencies.
873
+ * Detects circular dependencies.
874
+ *
875
+ * @returns Plugins sorted in dependency order
876
+ * @throws {CircularDependencyError} If circular dependency detected
877
+ */
878
+ private topologicalSort;
718
879
  /**
719
880
  * Unregister a plugin.
720
881
  *
882
+ * Automatically cleans up event listeners registered by this plugin.
883
+ *
721
884
  * @param name - Plugin name to unregister
722
885
  * @throws {PluginNotFoundError} If plugin doesn't exist
723
886
  */
724
- unregister(name: string): void;
887
+ unregister(name: string): Promise<void>;
725
888
  /**
726
889
  * Get the shared context object.
727
890
  *
@@ -735,6 +898,13 @@ declare class Kernel<TContext = unknown> {
735
898
  * @returns Plugin instance or undefined
736
899
  */
737
900
  getPlugin(name: string): Plugin<TContext> | undefined;
901
+ /**
902
+ * Get the state of a registered plugin.
903
+ *
904
+ * @param name - Plugin name
905
+ * @returns Plugin state or undefined if not found
906
+ */
907
+ getPluginState(name: string): PluginState | undefined;
738
908
  /**
739
909
  * Check if a plugin is registered.
740
910
  *
@@ -748,6 +918,27 @@ declare class Kernel<TContext = unknown> {
748
918
  * @returns Array of plugin names
749
919
  */
750
920
  listPlugins(): string[];
921
+ /**
922
+ * Get the kernel's current state.
923
+ *
924
+ * @returns Current kernel state
925
+ */
926
+ getState(): KernelState;
927
+ /**
928
+ * Check if kernel is initialized.
929
+ *
930
+ * @returns True if kernel is initialized
931
+ */
932
+ isInitialized(): boolean;
933
+ /**
934
+ * Get the scoped event bus for a plugin.
935
+ * Listeners registered through this bus are automatically
936
+ * cleaned up when the plugin is unregistered.
937
+ *
938
+ * @param pluginName - Plugin name
939
+ * @returns Scoped event bus or undefined
940
+ */
941
+ getScopedEventBus(pluginName: string): ScopedEventBus | undefined;
751
942
  /**
752
943
  * Register an event listener.
753
944
  *
@@ -772,9 +963,91 @@ declare class Kernel<TContext = unknown> {
772
963
  /**
773
964
  * Destroy the kernel and all plugins.
774
965
  *
775
- * Unregisters all plugins and cleans up resources.
966
+ * Unregisters all plugins in reverse dependency order and cleans up resources.
776
967
  */
777
968
  destroy(): Promise<void>;
778
969
  }
779
970
 
780
- export { Kernel, Plugin, array, camelCase, capitalize, chunk, compact, entries, first, flatten, fromEntries, get, groupBy, has, kebabCase, keyBy, keys, last, merge, object, omit, pascalCase, pick, sample, set, setMut, slugify, snakeCase, string, template, truncate, uniq, uniqBy, values };
971
+ /**
972
+ * Base error class for all @oxog/utils errors.
973
+ */
974
+ declare class UtilsError extends Error {
975
+ code: string;
976
+ constructor(message: string, code: string);
977
+ }
978
+ /**
979
+ * Error thrown when an invalid path is provided to get/set/has functions.
980
+ */
981
+ declare class InvalidPathError extends UtilsError {
982
+ constructor(path: string);
983
+ }
984
+ /**
985
+ * Error thrown when a circular reference is detected during deep operations.
986
+ */
987
+ declare class CircularReferenceError extends UtilsError {
988
+ constructor();
989
+ }
990
+ /**
991
+ * Error thrown when an operation times out.
992
+ */
993
+ declare class TimeoutError extends UtilsError {
994
+ constructor(ms: number);
995
+ }
996
+ /**
997
+ * Error thrown when a plugin is already registered.
998
+ */
999
+ declare class PluginAlreadyRegisteredError extends UtilsError {
1000
+ constructor(name: string);
1001
+ }
1002
+ /**
1003
+ * Error thrown when a requested plugin is not found.
1004
+ */
1005
+ declare class PluginNotFoundError extends UtilsError {
1006
+ constructor(name: string);
1007
+ }
1008
+ /**
1009
+ * Error thrown when a plugin dependency is missing.
1010
+ */
1011
+ declare class PluginDependencyMissingError extends UtilsError {
1012
+ constructor(plugin: string, dependency: string);
1013
+ }
1014
+ /**
1015
+ * Error thrown when retry attempts are exhausted.
1016
+ */
1017
+ declare class MaxRetriesExceededError extends UtilsError {
1018
+ /** Number of attempts that were made. */
1019
+ readonly attempts: number;
1020
+ /**
1021
+ * @param attempts - Number of attempts that were made
1022
+ * @param cause - The error thrown by the last attempt (available as `error.cause`)
1023
+ */
1024
+ constructor(attempts: number, cause?: unknown);
1025
+ }
1026
+ /**
1027
+ * Error thrown when circular dependency is detected between plugins.
1028
+ */
1029
+ declare class CircularDependencyError extends UtilsError {
1030
+ constructor(cycle: string[]);
1031
+ }
1032
+ /**
1033
+ * Error thrown when plugin initialization fails.
1034
+ */
1035
+ declare class PluginInitializationError extends UtilsError {
1036
+ readonly pluginName: string;
1037
+ readonly cause: Error;
1038
+ constructor(pluginName: string, cause: Error);
1039
+ }
1040
+ /**
1041
+ * Error thrown when kernel is already initialized.
1042
+ */
1043
+ declare class KernelAlreadyInitializedError extends UtilsError {
1044
+ constructor();
1045
+ }
1046
+ /**
1047
+ * Error thrown when kernel is currently initializing (race condition prevention).
1048
+ */
1049
+ declare class KernelInitializingError extends UtilsError {
1050
+ constructor();
1051
+ }
1052
+
1053
+ export { CircularDependencyError, CircularReferenceError, EventBus, InvalidPathError, Kernel, KernelAlreadyInitializedError, KernelInitializingError, type KernelOptions, MaxRetriesExceededError, Plugin, PluginAlreadyRegisteredError, PluginDependencyMissingError, PluginInitializationError, PluginNotFoundError, type PluginState, ScopedEventBus, TimeoutError, UtilsError, array, camelCase, capitalize, chunk, compact, entries, first, flatten, fromEntries, get, groupBy, has, kebabCase, keyBy, keys, last, merge, object, omit, pascalCase, pick, sample, set, setMut, slugify, snakeCase, string, template, truncate, uniq, uniqBy, values };