eleva 1.0.0-alpha → 1.0.0-rc.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.
@@ -1,46 +1,64 @@
1
1
  "use strict";
2
2
 
3
3
  /**
4
- * 🔒 TemplateEngine: Secure interpolation & dynamic attribute parsing.
4
+ * @class 🔒 TemplateEngine
5
+ * @classdesc A secure template engine that handles interpolation and dynamic attribute parsing.
6
+ * Provides a safe way to evaluate expressions in templates while preventing XSS attacks.
7
+ * All methods are static and can be called directly on the class.
5
8
  *
6
- * This class provides methods to parse template strings by replacing
7
- * interpolation expressions with dynamic data values and to evaluate expressions
8
- * within a given data context.
9
+ * @example
10
+ * const template = "Hello, {{name}}!";
11
+ * const data = { name: "World" };
12
+ * const result = TemplateEngine.parse(template, data); // Returns: "Hello, World!"
9
13
  */
10
14
  export class TemplateEngine {
11
15
  /**
12
- * Parses a template string and replaces interpolation expressions with corresponding values.
16
+ * @private {RegExp} Regular expression for matching template expressions in the format {{ expression }}
17
+ * @type {RegExp}
18
+ */
19
+ static expressionPattern = /\{\{\s*(.*?)\s*\}\}/g;
20
+
21
+ /**
22
+ * Parses a template string, replacing expressions with their evaluated values.
23
+ * Expressions are evaluated in the provided data context.
13
24
  *
14
- * @param {string} template - The template string containing expressions in the format {{ expression }}.
15
- * @param {object} data - The data object to use for evaluating expressions.
16
- * @returns {string} The resulting string with evaluated values.
25
+ * @public
26
+ * @static
27
+ * @param {string} template - The template string to parse.
28
+ * @param {Record<string, unknown>} data - The data context for evaluating expressions.
29
+ * @returns {string} The parsed template with expressions replaced by their values.
30
+ * @example
31
+ * const result = TemplateEngine.parse("{{user.name}} is {{user.age}} years old", {
32
+ * user: { name: "John", age: 30 }
33
+ * }); // Returns: "John is 30 years old"
17
34
  */
18
35
  static parse(template, data) {
19
- return template.replace(/\{\{\s*(.*?)\s*\}\}/g, (_, expr) => {
20
- const value = this.evaluate(expr, data);
21
- return value === undefined ? "" : value;
22
- });
36
+ if (typeof template !== "string") return template;
37
+ return template.replace(this.expressionPattern, (_, expression) =>
38
+ this.evaluate(expression, data)
39
+ );
23
40
  }
24
41
 
25
42
  /**
26
- * Evaluates an expression using the provided data context.
43
+ * Evaluates an expression in the context of the provided data object.
44
+ * Note: This does not provide a true sandbox and evaluated expressions may access global scope.
45
+ * The use of the `with` statement is necessary for expression evaluation but has security implications.
46
+ * Expressions should be carefully validated before evaluation.
27
47
  *
28
- * @param {string} expr - The JavaScript expression to evaluate.
29
- * @param {object} data - The data context for evaluating the expression.
30
- * @returns {*} The result of the evaluated expression, or an empty string if undefined or on error.
48
+ * @public
49
+ * @static
50
+ * @param {string} expression - The expression to evaluate.
51
+ * @param {Record<string, unknown>} data - The data context for evaluation.
52
+ * @returns {unknown} The result of the evaluation, or an empty string if evaluation fails.
53
+ * @example
54
+ * const result = TemplateEngine.evaluate("user.name", { user: { name: "John" } }); // Returns: "John"
55
+ * const age = TemplateEngine.evaluate("user.age", { user: { age: 30 } }); // Returns: 30
31
56
  */
32
- static evaluate(expr, data) {
57
+ static evaluate(expression, data) {
58
+ if (typeof expression !== "string") return expression;
33
59
  try {
34
- const keys = Object.keys(data);
35
- const values = keys.map((k) => data[k]);
36
- const result = new Function(...keys, `return ${expr}`)(...values);
37
- return result === undefined ? "" : result;
38
- } catch (error) {
39
- console.error(`Template evaluation error:`, {
40
- expression: expr,
41
- data,
42
- error: error.message,
43
- });
60
+ return new Function("data", `with(data) { return ${expression}; }`)(data);
61
+ } catch {
44
62
  return "";
45
63
  }
46
64
  }
@@ -1,86 +1,353 @@
1
1
  /**
2
- * 🧩 Eleva Core: Signal-based component runtime framework with lifecycle, scoped styles, and plugins.
2
+ * @typedef {Object} ComponentDefinition
3
+ * @property {function(ComponentContext): (Record<string, unknown>|Promise<Record<string, unknown>>)} [setup]
4
+ * Optional setup function that initializes the component's state and returns reactive data
5
+ * @property {(function(ComponentContext): string|Promise<string>)} template
6
+ * Required function that defines the component's HTML structure
7
+ * @property {(function(ComponentContext): string)|string} [style]
8
+ * Optional function or string that provides component-scoped CSS styles
9
+ * @property {Record<string, ComponentDefinition>} [children]
10
+ * Optional object defining nested child components
11
+ */
12
+ /**
13
+ * @typedef {Object} ComponentContext
14
+ * @property {Record<string, unknown>} props
15
+ * Component properties passed during mounting
16
+ * @property {Emitter} emitter
17
+ * Event emitter instance for component event handling
18
+ * @property {function<T>(value: T): Signal<T>} signal
19
+ * Factory function to create reactive Signal instances
20
+ * @property {function(LifecycleHookContext): Promise<void>} [onBeforeMount]
21
+ * Hook called before component mounting
22
+ * @property {function(LifecycleHookContext): Promise<void>} [onMount]
23
+ * Hook called after component mounting
24
+ * @property {function(LifecycleHookContext): Promise<void>} [onBeforeUpdate]
25
+ * Hook called before component update
26
+ * @property {function(LifecycleHookContext): Promise<void>} [onUpdate]
27
+ * Hook called after component update
28
+ * @property {function(UnmountHookContext): Promise<void>} [onUnmount]
29
+ * Hook called during component unmounting
30
+ */
31
+ /**
32
+ * @typedef {Object} LifecycleHookContext
33
+ * @property {HTMLElement} container
34
+ * The DOM element where the component is mounted
35
+ * @property {ComponentContext} context
36
+ * The component's reactive state and context data
37
+ */
38
+ /**
39
+ * @typedef {Object} UnmountHookContext
40
+ * @property {HTMLElement} container
41
+ * The DOM element where the component is mounted
42
+ * @property {ComponentContext} context
43
+ * The component's reactive state and context data
44
+ * @property {{
45
+ * watchers: Array<() => void>, // Signal watcher cleanup functions
46
+ * listeners: Array<() => void>, // Event listener cleanup functions
47
+ * children: Array<MountResult> // Child component instances
48
+ * }} cleanup
49
+ * Object containing cleanup functions and instances
50
+ */
51
+ /**
52
+ * @typedef {Object} MountResult
53
+ * @property {HTMLElement} container
54
+ * The DOM element where the component is mounted
55
+ * @property {ComponentContext} data
56
+ * The component's reactive state and context data
57
+ * @property {function(): Promise<void>} unmount
58
+ * Function to clean up and unmount the component
59
+ */
60
+ /**
61
+ * @typedef {Object} ElevaPlugin
62
+ * @property {function(Eleva, Record<string, unknown>): void} install
63
+ * Function that installs the plugin into the Eleva instance
64
+ * @property {string} name
65
+ * Unique identifier name for the plugin
66
+ */
67
+ /**
68
+ * @class 🧩 Eleva
69
+ * @classdesc A modern, signal-based component runtime framework that provides lifecycle hooks,
70
+ * scoped styles, and plugin support. Eleva manages component registration, plugin integration,
71
+ * event handling, and DOM rendering with a focus on performance and developer experience.
72
+ *
73
+ * @example
74
+ * // Basic component creation and mounting
75
+ * const app = new Eleva("myApp");
76
+ * app.component("myComponent", {
77
+ * setup: (ctx) => ({ count: ctx.signal(0) }),
78
+ * template: (ctx) => `<div>Hello ${ctx.props.name}</div>`
79
+ * });
80
+ * app.mount(document.getElementById("app"), "myComponent", { name: "World" });
3
81
  *
4
- * The Eleva class is the core of the framework. It manages component registration,
5
- * plugin integration, lifecycle hooks, event handling, and DOM rendering.
82
+ * @example
83
+ * // Using lifecycle hooks
84
+ * app.component("lifecycleDemo", {
85
+ * setup: () => {
86
+ * return {
87
+ * onMount: ({ container, context }) => {
88
+ * console.log('Component mounted!');
89
+ * }
90
+ * };
91
+ * },
92
+ * template: `<div>Lifecycle Demo</div>`
93
+ * });
6
94
  */
7
95
  export class Eleva {
8
96
  /**
9
- * Creates a new Eleva instance.
97
+ * Creates a new Eleva instance with the specified name and configuration.
98
+ *
99
+ * @public
100
+ * @param {string} name - The unique identifier name for this Eleva instance.
101
+ * @param {Record<string, unknown>} [config={}] - Optional configuration object for the instance.
102
+ * May include framework-wide settings and default behaviors.
103
+ * @throws {Error} If the name is not provided or is not a string.
104
+ * @returns {Eleva} A new Eleva instance.
105
+ *
106
+ * @example
107
+ * const app = new Eleva("myApp");
108
+ * app.component("myComponent", {
109
+ * setup: (ctx) => ({ count: ctx.signal(0) }),
110
+ * template: (ctx) => `<div>Hello ${ctx.props.name}!</div>`
111
+ * });
112
+ * app.mount(document.getElementById("app"), "myComponent", { name: "World" });
10
113
  *
11
- * @param {string} name - The name of the Eleva instance.
12
- * @param {object} [config={}] - Optional configuration for the instance.
13
114
  */
14
- constructor(name: string, config?: object);
15
- name: string;
16
- config: object;
17
- _components: {};
18
- _plugins: any[];
19
- _lifecycleHooks: string[];
20
- _isMounted: boolean;
21
- emitter: Emitter;
22
- renderer: Renderer;
115
+ constructor(name: string, config?: Record<string, unknown>);
116
+ /** @public {string} The unique identifier name for this Eleva instance */
117
+ public name: string;
118
+ /** @public {Object<string, unknown>} Optional configuration object for the Eleva instance */
119
+ public config: Record<string, unknown>;
120
+ /** @public {Emitter} Instance of the event emitter for handling component events */
121
+ public emitter: Emitter;
122
+ /** @public {typeof Signal} Static reference to the Signal class for creating reactive state */
123
+ public signal: typeof Signal;
124
+ /** @public {Renderer} Instance of the renderer for handling DOM updates and patching */
125
+ public renderer: Renderer;
126
+ /** @private {Map<string, ComponentDefinition>} Registry of all component definitions by name */
127
+ private _components;
128
+ /** @private {Map<string, ElevaPlugin>} Collection of installed plugin instances by name */
129
+ private _plugins;
130
+ /** @private {boolean} Flag indicating if the root component is currently mounted */
131
+ private _isMounted;
23
132
  /**
24
133
  * Integrates a plugin with the Eleva framework.
134
+ * The plugin's install function will be called with the Eleva instance and provided options.
135
+ * After installation, the plugin will be available for use by components.
25
136
  *
26
- * @param {object} [plugin] - The plugin object which should have an install function.
27
- * @param {object} [options={}] - Optional options to pass to the plugin.
28
- * @returns {Eleva} The Eleva instance (for chaining).
137
+ * @public
138
+ * @param {ElevaPlugin} plugin - The plugin object which must have an `install` function.
139
+ * @param {Object<string, unknown>} [options={}] - Optional configuration options for the plugin.
140
+ * @returns {Eleva} The Eleva instance (for method chaining).
141
+ * @example
142
+ * app.use(myPlugin, { option1: "value1" });
29
143
  */
30
- use(plugin?: object, options?: object): Eleva;
144
+ public use(plugin: ElevaPlugin, options?: {
145
+ [x: string]: unknown;
146
+ }): Eleva;
31
147
  /**
32
- * Registers a component with the Eleva instance.
148
+ * Registers a new component with the Eleva instance.
149
+ * The component will be available for mounting using its registered name.
33
150
  *
34
- * @param {string} name - The name of the component.
35
- * @param {object} definition - The component definition including setup, template, style, and children.
36
- * @returns {Eleva} The Eleva instance (for chaining).
151
+ * @public
152
+ * @param {string} name - The unique name of the component to register.
153
+ * @param {ComponentDefinition} definition - The component definition including setup, template, style, and children.
154
+ * @returns {Eleva} The Eleva instance (for method chaining).
155
+ * @throws {Error} If the component name is already registered.
156
+ * @example
157
+ * app.component("myButton", {
158
+ * template: (ctx) => `<button>${ctx.props.text}</button>`,
159
+ * style: `button { color: blue; }`
160
+ * });
37
161
  */
38
- component(name: string, definition: object): Eleva;
162
+ public component(name: string, definition: ComponentDefinition): Eleva;
39
163
  /**
40
164
  * Mounts a registered component to a DOM element.
165
+ * This will initialize the component, set up its reactive state, and render it to the DOM.
41
166
  *
42
- * @param {string|HTMLElement} selectorOrElement - A CSS selector string or DOM element where the component will be mounted.
43
- * @param {string} compName - The name of the component to mount.
44
- * @param {object} [props={}] - Optional properties to pass to the component.
45
- * @returns {object|Promise<object>} An object representing the mounted component instance, or a Promise that resolves to it for asynchronous setups.
46
- * @throws Will throw an error if the container or component is not found.
47
- */
48
- mount(selectorOrElement: string | HTMLElement, compName: string, props?: object): object | Promise<object>;
49
- /**
50
- * Prepares default no-operation lifecycle hook functions.
51
- *
52
- * @returns {object} An object with keys for lifecycle hooks mapped to empty functions.
53
- * @private
167
+ * @public
168
+ * @param {HTMLElement} container - The DOM element where the component will be mounted.
169
+ * @param {string|ComponentDefinition} compName - The name of the registered component or a direct component definition.
170
+ * @param {Object<string, unknown>} [props={}] - Optional properties to pass to the component.
171
+ * @returns {Promise<MountResult>}
172
+ * A Promise that resolves to an object containing:
173
+ * - container: The mounted component's container element
174
+ * - data: The component's reactive state and context
175
+ * - unmount: Function to clean up and unmount the component
176
+ * @throws {Error} If the container is not found, or component is not registered.
177
+ * @example
178
+ * const instance = await app.mount(document.getElementById("app"), "myComponent", { text: "Click me" });
179
+ * // Later...
180
+ * instance.unmount();
54
181
  */
55
- private _prepareLifecycleHooks;
182
+ public mount(container: HTMLElement, compName: string | ComponentDefinition, props?: {
183
+ [x: string]: unknown;
184
+ }): Promise<MountResult>;
56
185
  /**
57
186
  * Processes DOM elements for event binding based on attributes starting with "@".
187
+ * This method handles the event delegation system and ensures proper cleanup of event listeners.
58
188
  *
59
- * @param {HTMLElement} container - The container element in which to search for events.
60
- * @param {object} context - The current context containing event handler definitions.
61
189
  * @private
190
+ * @param {HTMLElement} container - The container element in which to search for event attributes.
191
+ * @param {ComponentContext} context - The current component context containing event handler definitions.
192
+ * @param {Array<() => void>} listeners - Array to collect cleanup functions for each event listener.
193
+ * @returns {void}
62
194
  */
63
195
  private _processEvents;
64
196
  /**
65
197
  * Injects scoped styles into the component's container.
198
+ * The styles are automatically prefixed to prevent style leakage to other components.
66
199
  *
67
- * @param {HTMLElement} container - The container element.
68
- * @param {string} compName - The component name used to identify the style element.
69
- * @param {Function} styleFn - A function that returns CSS styles as a string.
70
- * @param {object} context - The current context for style interpolation.
71
200
  * @private
201
+ * @param {HTMLElement} container - The container element where styles should be injected.
202
+ * @param {string} compName - The component name used to identify the style element.
203
+ * @param {(function(ComponentContext): string)|string} styleDef - The component's style definition (function or string).
204
+ * @param {ComponentContext} context - The current component context for style interpolation.
205
+ * @returns {void}
72
206
  */
73
207
  private _injectStyles;
74
208
  /**
75
- * Mounts child components within the parent component's container.
209
+ * Extracts props from an element's attributes that start with the specified prefix.
210
+ * This method is used to collect component properties from DOM elements.
211
+ *
212
+ * @private
213
+ * @param {HTMLElement} element - The DOM element to extract props from
214
+ * @param {string} prefix - The prefix to look for in attributes
215
+ * @returns {Record<string, string>} An object containing the extracted props
216
+ * @example
217
+ * // For an element with attributes:
218
+ * // <div :name="John" :age="25">
219
+ * // Returns: { name: "John", age: "25" }
220
+ */
221
+ private _extractProps;
222
+ /**
223
+ * Mounts all components within the parent component's container.
224
+ * This method handles mounting of explicitly defined children components.
225
+ *
226
+ * The mounting process follows these steps:
227
+ * 1. Cleans up any existing component instances
228
+ * 2. Mounts explicitly defined children components
76
229
  *
77
- * @param {HTMLElement} container - The parent container element.
78
- * @param {object} children - An object mapping child component selectors to their definitions.
79
- * @param {Array} childInstances - An array to store the mounted child component instances.
80
230
  * @private
231
+ * @param {HTMLElement} container - The container element to mount components in
232
+ * @param {Object<string, ComponentDefinition>} children - Map of selectors to component definitions for explicit children
233
+ * @param {Array<MountResult>} childInstances - Array to store all mounted component instances
234
+ * @returns {Promise<void>}
235
+ *
236
+ * @example
237
+ * // Explicit children mounting:
238
+ * const children = {
239
+ * 'UserProfile': UserProfileComponent,
240
+ * '#settings-panel': "settings-panel"
241
+ * };
81
242
  */
82
- private _mountChildren;
243
+ private _mountComponents;
83
244
  }
245
+ export type ComponentDefinition = {
246
+ /**
247
+ * Optional setup function that initializes the component's state and returns reactive data
248
+ */
249
+ setup?: ((arg0: ComponentContext) => (Record<string, unknown> | Promise<Record<string, unknown>>)) | undefined;
250
+ /**
251
+ * Required function that defines the component's HTML structure
252
+ */
253
+ template: ((arg0: ComponentContext) => string | Promise<string>);
254
+ /**
255
+ * Optional function or string that provides component-scoped CSS styles
256
+ */
257
+ style?: string | ((arg0: ComponentContext) => string) | undefined;
258
+ /**
259
+ * Optional object defining nested child components
260
+ */
261
+ children?: Record<string, ComponentDefinition> | undefined;
262
+ };
263
+ export type ComponentContext = {
264
+ /**
265
+ * Component properties passed during mounting
266
+ */
267
+ props: Record<string, unknown>;
268
+ /**
269
+ * Event emitter instance for component event handling
270
+ */
271
+ emitter: Emitter;
272
+ /**
273
+ * <T>(value: T): Signal<T>} signal
274
+ * Factory function to create reactive Signal instances
275
+ */
276
+ "": Function;
277
+ /**
278
+ * Hook called before component mounting
279
+ */
280
+ onBeforeMount?: ((arg0: LifecycleHookContext) => Promise<void>) | undefined;
281
+ /**
282
+ * Hook called after component mounting
283
+ */
284
+ onMount?: ((arg0: LifecycleHookContext) => Promise<void>) | undefined;
285
+ /**
286
+ * Hook called before component update
287
+ */
288
+ onBeforeUpdate?: ((arg0: LifecycleHookContext) => Promise<void>) | undefined;
289
+ /**
290
+ * Hook called after component update
291
+ */
292
+ onUpdate?: ((arg0: LifecycleHookContext) => Promise<void>) | undefined;
293
+ /**
294
+ * Hook called during component unmounting
295
+ */
296
+ onUnmount?: ((arg0: UnmountHookContext) => Promise<void>) | undefined;
297
+ };
298
+ export type LifecycleHookContext = {
299
+ /**
300
+ * The DOM element where the component is mounted
301
+ */
302
+ container: HTMLElement;
303
+ /**
304
+ * The component's reactive state and context data
305
+ */
306
+ context: ComponentContext;
307
+ };
308
+ export type UnmountHookContext = {
309
+ /**
310
+ * The DOM element where the component is mounted
311
+ */
312
+ container: HTMLElement;
313
+ /**
314
+ * The component's reactive state and context data
315
+ */
316
+ context: ComponentContext;
317
+ /**
318
+ * Object containing cleanup functions and instances
319
+ */
320
+ cleanup: {
321
+ watchers: Array<() => void>;
322
+ listeners: Array<() => void>;
323
+ children: Array<MountResult>;
324
+ };
325
+ };
326
+ export type MountResult = {
327
+ /**
328
+ * The DOM element where the component is mounted
329
+ */
330
+ container: HTMLElement;
331
+ /**
332
+ * The component's reactive state and context data
333
+ */
334
+ data: ComponentContext;
335
+ /**
336
+ * Function to clean up and unmount the component
337
+ */
338
+ unmount: () => Promise<void>;
339
+ };
340
+ export type ElevaPlugin = {
341
+ /**
342
+ * Function that installs the plugin into the Eleva instance
343
+ */
344
+ install: (arg0: Eleva, arg1: Record<string, unknown>) => void;
345
+ /**
346
+ * Unique identifier name for the plugin
347
+ */
348
+ name: string;
349
+ };
84
350
  import { Emitter } from "../modules/Emitter.js";
351
+ import { Signal } from "../modules/Signal.js";
85
352
  import { Renderer } from "../modules/Renderer.js";
86
353
  //# sourceMappingURL=Eleva.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Eleva.d.ts","sourceRoot":"","sources":["../../src/core/Eleva.js"],"names":[],"mappings":"AAOA;;;;;GAKG;AACH;IACE;;;;;OAKG;IACH,kBAHW,MAAM,WACN,MAAM,EAiBhB;IAdC,aAAgB;IAChB,eAAoB;IACpB,gBAAqB;IACrB,gBAAkB;IAClB,0BAMC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,EAAE,OAAO,CAAC,KAAG,IAAI;;;;UAE9C,MAAM;;wBAvEI,uBAAuB;uBADxB,sBAAsB;yBAEpB,wBAAwB"}
@@ -1,34 +1,66 @@
1
1
  /**
2
- * 🎙️ Emitter: Robust inter-component communication with event bubbling.
2
+ * @class 📡 Emitter
3
+ * @classdesc A robust event emitter that enables inter-component communication through a publish-subscribe pattern.
4
+ * Components can emit events and listen for events from other components, facilitating loose coupling
5
+ * and reactive updates across the application.
6
+ * Events are handled synchronously in the order they were registered, with proper cleanup
7
+ * of unsubscribed handlers.
8
+ * Event names should follow the format 'namespace:action' (e.g., 'user:login', 'cart:update').
3
9
  *
4
- * Implements a basic publish-subscribe pattern for event handling,
5
- * allowing components to communicate through custom events.
10
+ * @example
11
+ * const emitter = new Emitter();
12
+ * emitter.on('user:login', (user) => console.log(`User logged in: ${user.name}`));
13
+ * emitter.emit('user:login', { name: 'John' }); // Logs: "User logged in: John"
6
14
  */
7
15
  export class Emitter {
8
- /** @type {Object.<string, Function[]>} */
9
- events: {
10
- [x: string]: Function[];
11
- };
16
+ /** @private {Map<string, Set<(data: unknown) => void>>} Map of event names to their registered handler functions */
17
+ private _events;
12
18
  /**
13
- * Registers an event handler for the specified event.
19
+ * Registers an event handler for the specified event name.
20
+ * The handler will be called with the event data when the event is emitted.
21
+ * Event names should follow the format 'namespace:action' for consistency.
14
22
  *
15
- * @param {string} event - The name of the event.
16
- * @param {Function} handler - The function to call when the event is emitted.
23
+ * @public
24
+ * @param {string} event - The name of the event to listen for (e.g., 'user:login').
25
+ * @param {(data: unknown) => void} handler - The callback function to invoke when the event occurs.
26
+ * @returns {() => void} A function to unsubscribe the event handler.
27
+ * @example
28
+ * const unsubscribe = emitter.on('user:login', (user) => console.log(user));
29
+ * // Later...
30
+ * unsubscribe(); // Stops listening for the event
17
31
  */
18
- on(event: string, handler: Function): void;
32
+ public on(event: string, handler: (data: unknown) => void): () => void;
19
33
  /**
20
- * Removes a previously registered event handler.
34
+ * Removes an event handler for the specified event name.
35
+ * If no handler is provided, all handlers for the event are removed.
36
+ * Automatically cleans up empty event sets to prevent memory leaks.
21
37
  *
22
- * @param {string} event - The name of the event.
23
- * @param {Function} handler - The handler function to remove.
38
+ * @public
39
+ * @param {string} event - The name of the event to remove handlers from.
40
+ * @param {(data: unknown) => void} [handler] - The specific handler function to remove.
41
+ * @returns {void}
42
+ * @example
43
+ * // Remove a specific handler
44
+ * emitter.off('user:login', loginHandler);
45
+ * // Remove all handlers for an event
46
+ * emitter.off('user:login');
24
47
  */
25
- off(event: string, handler: Function): void;
48
+ public off(event: string, handler?: (data: unknown) => void): void;
26
49
  /**
27
- * Emits an event, invoking all handlers registered for that event.
50
+ * Emits an event with the specified data to all registered handlers.
51
+ * Handlers are called synchronously in the order they were registered.
52
+ * If no handlers are registered for the event, the emission is silently ignored.
28
53
  *
29
- * @param {string} event - The event name.
30
- * @param {...*} args - Additional arguments to pass to the event handlers.
54
+ * @public
55
+ * @param {string} event - The name of the event to emit.
56
+ * @param {...unknown} args - Optional arguments to pass to the event handlers.
57
+ * @returns {void}
58
+ * @example
59
+ * // Emit an event with data
60
+ * emitter.emit('user:login', { name: 'John', role: 'admin' });
61
+ * // Emit an event with multiple arguments
62
+ * emitter.emit('cart:update', { items: [] }, { total: 0 });
31
63
  */
32
- emit(event: string, ...args: any[]): void;
64
+ public emit(event: string, ...args: unknown[]): void;
33
65
  }
34
66
  //# sourceMappingURL=Emitter.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Emitter.d.ts","sourceRoot":"","sources":["../../src/modules/Emitter.js"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH;IAKI,0CAA0C;IAC1C;;MAAgB;IAGlB;;;;;OAKG;IACH,UAHW,MAAM,2BAKhB;IAED;;;;;OAKG;IACH,WAHW,MAAM,2BAOhB;IAED;;;;;OAKG;IACH,YAHW,MAAM,WACH,GAAC,EAAA,QAId;CACF"}
1
+ {"version":3,"file":"Emitter.d.ts","sourceRoot":"","sources":["../../src/modules/Emitter.js"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;GAaG;AACH;IAOI,oHAAoH;IACpH,gBAAwB;IAG1B;;;;;;;;;;;;;OAaG;IACH,iBARW,MAAM,WACN,CAAC,IAAI,EAAE,OAAO,KAAK,IAAI,GACrB,MAAM,IAAI,CAWtB;IAED;;;;;;;;;;;;;;OAcG;IACH,kBATW,MAAM,YACN,CAAC,IAAI,EAAE,OAAO,KAAK,IAAI,GACrB,IAAI,CAiBhB;IAED;;;;;;;;;;;;;;OAcG;IACH,mBATW,MAAM,WACH,OAAO,EAAA,GACR,IAAI,CAUhB;CACF"}