@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.cjs CHANGED
@@ -1,14 +1,12 @@
1
1
  'use strict';
2
2
 
3
- var __defProp = Object.defineProperty;
4
- var __export = (target, all) => {
5
- for (var name in all)
6
- __defProp(target, name, { get: all[name], enumerable: true });
7
- };
3
+ var chunkDEVWOLUI_cjs = require('./chunk-DEVWOLUI.cjs');
4
+ var chunkSWG777R6_cjs = require('./chunk-SWG777R6.cjs');
5
+ var chunkQ7SFCCGT_cjs = require('./chunk-Q7SFCCGT.cjs');
8
6
 
9
7
  // src/plugins/core/object.ts
10
8
  var object_exports = {};
11
- __export(object_exports, {
9
+ chunkQ7SFCCGT_cjs.__export(object_exports, {
12
10
  entries: () => entries,
13
11
  fromEntries: () => fromEntries,
14
12
  get: () => get,
@@ -25,12 +23,14 @@ function get(obj, path, defaultValue) {
25
23
  if (obj == null) {
26
24
  return defaultValue;
27
25
  }
28
- const keys2 = path.toString().split(/[\.\[]/g).map((k) => k.replace(/[\]']/g, "")).filter((k) => k !== "");
29
26
  let result = obj;
30
- for (const key of keys2) {
27
+ for (const { key } of chunkSWG777R6_cjs.parsePath(path)) {
31
28
  if (result == null) {
32
29
  return defaultValue;
33
30
  }
31
+ if (chunkSWG777R6_cjs.UNSAFE_KEYS.has(key) && !chunkSWG777R6_cjs.hasOwn(Object(result), key)) {
32
+ return defaultValue;
33
+ }
34
34
  result = result[key];
35
35
  }
36
36
  if (typeof result === "function") {
@@ -42,35 +42,24 @@ function set(obj, path, value) {
42
42
  if (obj == null || typeof obj !== "object") {
43
43
  return obj;
44
44
  }
45
- const keys2 = path.toString().split(".");
46
- const deepSet = (current, keyIndex) => {
47
- if (keyIndex === keys2.length) {
48
- return value;
49
- }
50
- const key = keys2[keyIndex];
51
- const isLast = keyIndex === keys2.length - 1;
52
- if (isLast) {
53
- const arrayMatch = key.match(/^(.+)\[(\d+)\]$/);
54
- if (arrayMatch) {
55
- const [, arrayPath, index] = arrayMatch;
56
- const arrayIndex = parseInt(index, 10);
57
- const arrayValue = current?.[arrayPath];
58
- if (Array.isArray(arrayValue)) {
59
- return {
60
- ...current,
61
- [arrayPath]: [
62
- ...arrayValue.slice(0, arrayIndex),
63
- value,
64
- ...arrayValue.slice(arrayIndex + 1)
65
- ]
66
- };
67
- }
68
- }
69
- return { ...current, [key]: value };
45
+ const segments = chunkSWG777R6_cjs.parsePath(path);
46
+ if (segments.length === 0) {
47
+ return obj;
48
+ }
49
+ if (chunkSWG777R6_cjs.hasUnsafeSegment(segments)) {
50
+ throw new chunkDEVWOLUI_cjs.InvalidPathError(String(path));
51
+ }
52
+ const deepSet = (current, index) => {
53
+ const { key } = segments[index];
54
+ const copy = Array.isArray(current) ? current.slice() : { ...current };
55
+ if (index === segments.length - 1) {
56
+ copy[key] = value;
57
+ return copy;
70
58
  }
71
- const nextValue = current?.[key];
72
- const nestedObj = nextValue != null && typeof nextValue === "object" ? nextValue : {};
73
- return { ...current, [key]: deepSet(nestedObj, keyIndex + 1) };
59
+ const next = current[key];
60
+ const child = next != null && typeof next === "object" ? next : segments[index + 1].index ? [] : {};
61
+ copy[key] = deepSet(child, index + 1);
62
+ return copy;
74
63
  };
75
64
  return deepSet(obj, 0);
76
65
  }
@@ -78,29 +67,31 @@ function setMut(obj, path, value) {
78
67
  if (obj == null || typeof obj !== "object") {
79
68
  return obj;
80
69
  }
81
- const keys2 = path.toString().split(".");
82
- let result = obj;
83
- for (let i = 0; i < keys2.length - 1; i++) {
84
- const key = keys2[i];
85
- if (result[key] == null || typeof result[key] !== "object") {
86
- result[key] = {};
70
+ const segments = chunkSWG777R6_cjs.parsePath(path);
71
+ if (segments.length === 0) {
72
+ return obj;
73
+ }
74
+ if (chunkSWG777R6_cjs.hasUnsafeSegment(segments)) {
75
+ throw new chunkDEVWOLUI_cjs.InvalidPathError(String(path));
76
+ }
77
+ let current = obj;
78
+ for (let i = 0; i < segments.length - 1; i++) {
79
+ const { key } = segments[i];
80
+ if (current[key] == null || typeof current[key] !== "object") {
81
+ current[key] = segments[i + 1].index ? [] : {};
87
82
  }
88
- result = result[key];
83
+ current = current[key];
89
84
  }
90
- result[keys2[keys2.length - 1]] = value;
85
+ current[segments[segments.length - 1].key] = value;
91
86
  return obj;
92
87
  }
93
88
  function has(obj, path) {
94
89
  if (obj == null) {
95
90
  return false;
96
91
  }
97
- const keys2 = path.toString().split(/[\.\[]/g).map((k) => k.replace(/[\]']/g, "")).filter((k) => k !== "");
98
92
  let result = obj;
99
- for (const key of keys2) {
100
- if (Array.isArray(result) && /^\d+$/.test(key)) {
101
- return true;
102
- }
103
- if (result == null || !(key in result)) {
93
+ for (const { key } of chunkSWG777R6_cjs.parsePath(path)) {
94
+ if (result == null || !chunkSWG777R6_cjs.hasOwn(Object(result), key)) {
104
95
  return false;
105
96
  }
106
97
  result = result[key];
@@ -111,7 +102,7 @@ function pick(obj, keys2) {
111
102
  const result = {};
112
103
  for (const key of keys2) {
113
104
  if (key in obj) {
114
- result[key] = obj[key];
105
+ chunkSWG777R6_cjs.assignOwn(result, key, obj[key]);
115
106
  }
116
107
  }
117
108
  return result;
@@ -124,11 +115,11 @@ function omit(obj, keys2) {
124
115
  return result;
125
116
  }
126
117
  function merge(target, ...sources) {
127
- const DANGEROUS_KEYS = ["__proto__", "constructor", "prototype"];
128
118
  const result = { ...target };
129
119
  for (const source of sources) {
120
+ if (source == null) continue;
130
121
  for (const key of Object.keys(source)) {
131
- if (DANGEROUS_KEYS.includes(key)) continue;
122
+ if (chunkSWG777R6_cjs.UNSAFE_KEYS.has(key)) continue;
132
123
  result[key] = source[key];
133
124
  }
134
125
  }
@@ -149,7 +140,7 @@ function fromEntries(entries2) {
149
140
 
150
141
  // src/plugins/core/array.ts
151
142
  var array_exports = {};
152
- __export(array_exports, {
143
+ chunkQ7SFCCGT_cjs.__export(array_exports, {
153
144
  chunk: () => chunk,
154
145
  compact: () => compact,
155
146
  first: () => first,
@@ -165,10 +156,11 @@ function groupBy(arr, key) {
165
156
  const result = {};
166
157
  for (const item of arr) {
167
158
  const groupKey = typeof key === "function" ? key(item) : String(item[key]);
168
- if (!result[groupKey]) {
169
- result[groupKey] = [];
159
+ if (chunkSWG777R6_cjs.hasOwn(result, groupKey)) {
160
+ result[groupKey].push(item);
161
+ } else {
162
+ chunkSWG777R6_cjs.assignOwn(result, groupKey, [item]);
170
163
  }
171
- result[groupKey].push(item);
172
164
  }
173
165
  return result;
174
166
  }
@@ -176,12 +168,16 @@ function keyBy(arr, key) {
176
168
  const result = {};
177
169
  for (const item of arr) {
178
170
  const keyValue = typeof key === "function" ? key(item) : String(item[key]);
179
- result[keyValue] = item;
171
+ chunkSWG777R6_cjs.assignOwn(result, keyValue, item);
180
172
  }
181
173
  return result;
182
174
  }
183
175
  function chunk(arr, size) {
184
176
  const result = [];
177
+ size = Math.trunc(size);
178
+ if (!(size >= 1)) {
179
+ return result;
180
+ }
185
181
  for (let i = 0; i < arr.length; i += size) {
186
182
  result.push(arr.slice(i, i + size));
187
183
  }
@@ -217,18 +213,19 @@ function compact(arr) {
217
213
  return arr.filter(Boolean);
218
214
  }
219
215
  function first(arr, n = 1) {
220
- if (arr.length === 0) return void 0;
221
216
  if (n === 1) return arr[0];
222
- const result = arr.slice(0, n);
223
- return result.length === 1 ? result[0] : result;
217
+ if (arr.length === 0) return void 0;
218
+ return arr.slice(0, Math.max(0, Math.trunc(n) || 0));
224
219
  }
225
220
  function last(arr, n = 1) {
226
- if (arr.length === 0) return void 0;
227
221
  if (n === 1) return arr[arr.length - 1];
228
- return arr.slice(-n);
222
+ if (arr.length === 0) return void 0;
223
+ const count = Math.max(0, Math.trunc(n) || 0);
224
+ return count === 0 ? [] : arr.slice(-count);
229
225
  }
230
226
  function sample(arr, n = 1) {
231
- if (arr.length === 0) return [];
227
+ n = Math.max(0, Math.trunc(n) || 0);
228
+ if (arr.length === 0 || n === 0) return [];
232
229
  if (n >= arr.length) return [...arr];
233
230
  const shuffled = [...arr];
234
231
  for (let i = shuffled.length - 1; i > 0; i--) {
@@ -240,7 +237,7 @@ function sample(arr, n = 1) {
240
237
 
241
238
  // src/plugins/core/string.ts
242
239
  var string_exports = {};
243
- __export(string_exports, {
240
+ chunkQ7SFCCGT_cjs.__export(string_exports, {
244
241
  camelCase: () => camelCase,
245
242
  capitalize: () => capitalize,
246
243
  kebabCase: () => kebabCase,
@@ -270,91 +267,99 @@ function capitalize(str) {
270
267
  }
271
268
  function truncate(str, length, suffix = "...") {
272
269
  if (str.length <= length) return str;
273
- return str.slice(0, length) + suffix;
270
+ let end = Math.max(0, Math.trunc(length) || 0);
271
+ if (end > 0 && isHighSurrogate(str.charCodeAt(end - 1)) && isLowSurrogate(str.charCodeAt(end))) {
272
+ end--;
273
+ }
274
+ return str.slice(0, end) + suffix;
274
275
  }
276
+ var isHighSurrogate = (code) => code >= 55296 && code <= 56319;
277
+ var isLowSurrogate = (code) => code >= 56320 && code <= 57343;
275
278
  function slugify(str) {
276
- const charMap = {
277
- // Turkish
278
- "\u015F": "s",
279
- "\u015E": "s",
280
- "\u0131": "i",
281
- "\u0130": "i",
282
- "\u011F": "g",
283
- "\u011E": "g",
284
- "\xFC": "u",
285
- "\xDC": "u",
286
- "\xF6": "o",
287
- "\xD6": "o",
288
- "\xE7": "c",
289
- "\xC7": "c",
290
- // Russian (Cyrillic to Latin - basic transliteration)
291
- "\u0430": "a",
292
- "\u0431": "b",
293
- "\u0432": "v",
294
- "\u0433": "g",
295
- "\u0434": "d",
296
- "\u0435": "e",
297
- "\u0451": "yo",
298
- "\u0436": "zh",
299
- "\u0437": "z",
300
- "\u0438": "i",
301
- "\u0439": "y",
302
- "\u043A": "k",
303
- "\u043B": "l",
304
- "\u043C": "m",
305
- "\u043D": "n",
306
- "\u043E": "o",
307
- "\u043F": "p",
308
- "\u0440": "r",
309
- "\u0441": "s",
310
- "\u0442": "t",
311
- "\u0443": "u",
312
- "\u0444": "f",
313
- "\u0445": "h",
314
- "\u0446": "ts",
315
- "\u0447": "ch",
316
- "\u0448": "sh",
317
- "\u0449": "shch",
318
- "\u044A": "",
319
- "\u044B": "y",
320
- "\u044C": "",
321
- "\u044D": "e",
322
- "\u044E": "yu",
323
- "\u044F": "ya",
324
- // Greek (basic)
325
- "\u03B1": "a",
326
- "\u03B2": "b",
327
- "\u03B3": "g",
328
- "\u03B4": "d",
329
- "\u03B5": "e",
330
- "\u03B6": "z",
331
- "\u03B7": "i",
332
- "\u03B8": "th",
333
- "\u03B9": "i",
334
- "\u03BA": "k",
335
- "\u03BB": "l",
336
- "\u03BC": "m",
337
- "\u03BD": "n",
338
- "\u03BE": "x",
339
- "\u03BF": "o",
340
- "\u03C0": "p",
341
- "\u03C1": "r",
342
- "\u03C3": "s",
343
- "\u03C4": "t",
344
- "\u03C5": "y",
345
- "\u03C6": "f",
346
- "\u03C7": "ch",
347
- "\u03C8": "ps",
348
- "\u03C9": "o"
279
+ const transliterate = (input) => {
280
+ let out = "";
281
+ for (const char of input) {
282
+ out += chunkSWG777R6_cjs.hasOwn(SLUG_CHAR_MAP, char) ? SLUG_CHAR_MAP[char] : char;
283
+ }
284
+ return out;
349
285
  };
350
- return str.split("").map((char) => charMap[char] || char).join("").toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[\s\-_]+/g, "-").replace(/[^a-z0-9-]/g, "").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
286
+ return transliterate(transliterate(str.toLowerCase()).normalize("NFD").replace(/[\u0300-\u036f]/g, "")).replace(/[\s\-_]+/g, "-").replace(/[^a-z0-9-]/g, "").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
351
287
  }
288
+ var SLUG_CHAR_MAP = {
289
+ // Turkish
290
+ "\u015F": "s",
291
+ "\u0131": "i",
292
+ "\u011F": "g",
293
+ "\xFC": "u",
294
+ "\xF6": "o",
295
+ "\xE7": "c",
296
+ // Russian (Cyrillic to Latin - basic transliteration)
297
+ "\u0430": "a",
298
+ "\u0431": "b",
299
+ "\u0432": "v",
300
+ "\u0433": "g",
301
+ "\u0434": "d",
302
+ "\u0435": "e",
303
+ "\u0451": "yo",
304
+ "\u0436": "zh",
305
+ "\u0437": "z",
306
+ "\u0438": "i",
307
+ "\u0439": "y",
308
+ "\u043A": "k",
309
+ "\u043B": "l",
310
+ "\u043C": "m",
311
+ "\u043D": "n",
312
+ "\u043E": "o",
313
+ "\u043F": "p",
314
+ "\u0440": "r",
315
+ "\u0441": "s",
316
+ "\u0442": "t",
317
+ "\u0443": "u",
318
+ "\u0444": "f",
319
+ "\u0445": "h",
320
+ "\u0446": "ts",
321
+ "\u0447": "ch",
322
+ "\u0448": "sh",
323
+ "\u0449": "shch",
324
+ "\u044A": "",
325
+ "\u044B": "y",
326
+ "\u044C": "",
327
+ "\u044D": "e",
328
+ "\u044E": "yu",
329
+ "\u044F": "ya",
330
+ // Greek (basic)
331
+ "\u03B1": "a",
332
+ "\u03B2": "b",
333
+ "\u03B3": "g",
334
+ "\u03B4": "d",
335
+ "\u03B5": "e",
336
+ "\u03B6": "z",
337
+ "\u03B7": "i",
338
+ "\u03B8": "th",
339
+ "\u03B9": "i",
340
+ "\u03BA": "k",
341
+ "\u03BB": "l",
342
+ "\u03BC": "m",
343
+ "\u03BD": "n",
344
+ "\u03BE": "x",
345
+ "\u03BF": "o",
346
+ "\u03C0": "p",
347
+ "\u03C1": "r",
348
+ "\u03C3": "s",
349
+ "\u03C2": "s",
350
+ "\u03C4": "t",
351
+ "\u03C5": "y",
352
+ "\u03C6": "f",
353
+ "\u03C7": "ch",
354
+ "\u03C8": "ps",
355
+ "\u03C9": "o"
356
+ };
352
357
  function template(str, data) {
353
358
  return str.replace(/\{\{([^}]+)\}\}/g, (match, path) => {
354
359
  const keys2 = path.trim().split(".");
355
360
  let value = data;
356
361
  for (const key of keys2) {
357
- if (value == null) {
362
+ if (value == null || !chunkSWG777R6_cjs.hasOwn(Object(value), key)) {
358
363
  return "";
359
364
  }
360
365
  value = value[key];
@@ -366,6 +371,7 @@ function template(str, data) {
366
371
  // src/utils/eventBus.ts
367
372
  var EventBus = class {
368
373
  listeners = /* @__PURE__ */ new Map();
374
+ scopedHandlers = /* @__PURE__ */ new Map();
369
375
  /**
370
376
  * Register an event listener.
371
377
  *
@@ -432,105 +438,294 @@ var EventBus = class {
432
438
  listenerCount(event) {
433
439
  return this.listeners.get(event)?.size ?? 0;
434
440
  }
435
- };
436
-
437
- // src/errors.ts
438
- var UtilsError = class extends Error {
439
- code;
440
- constructor(message, code) {
441
- super(message);
442
- this.name = "UtilsError";
443
- this.code = code;
444
- Error.captureStackTrace(this, this.constructor);
441
+ /**
442
+ * Register an event listener with a scope (e.g., plugin name).
443
+ * Scoped listeners can be removed all at once using removeScope().
444
+ *
445
+ * @param scope - Scope identifier (e.g., plugin name)
446
+ * @param event - Event name to listen for
447
+ * @param handler - Function to call when event is emitted
448
+ */
449
+ onScoped(scope, event, handler) {
450
+ this.on(event, handler);
451
+ if (!this.scopedHandlers.has(scope)) {
452
+ this.scopedHandlers.set(scope, /* @__PURE__ */ new Map());
453
+ }
454
+ const scopeMap = this.scopedHandlers.get(scope);
455
+ if (!scopeMap.has(event)) {
456
+ scopeMap.set(event, /* @__PURE__ */ new Set());
457
+ }
458
+ scopeMap.get(event).add(handler);
445
459
  }
446
- };
447
- var PluginAlreadyRegisteredError = class extends UtilsError {
448
- constructor(name) {
449
- super(`Plugin "${name}" already registered`, "PLUGIN_ALREADY_REGISTERED");
450
- this.name = "PluginAlreadyRegisteredError";
460
+ /**
461
+ * Remove all listeners registered under a specific scope.
462
+ * Useful for cleanup when a plugin is unregistered.
463
+ *
464
+ * @param scope - Scope identifier to remove
465
+ */
466
+ removeScope(scope) {
467
+ const scopeMap = this.scopedHandlers.get(scope);
468
+ if (!scopeMap) return;
469
+ for (const [event, handlers] of scopeMap) {
470
+ for (const handler of handlers) {
471
+ this.off(event, handler);
472
+ }
473
+ }
474
+ this.scopedHandlers.delete(scope);
451
475
  }
452
- };
453
- var PluginNotFoundError = class extends UtilsError {
454
- constructor(name) {
455
- super(`Plugin "${name}" not found`, "PLUGIN_NOT_FOUND");
456
- this.name = "PluginNotFoundError";
476
+ /**
477
+ * Check if a scope has any registered listeners.
478
+ *
479
+ * @param scope - Scope identifier
480
+ * @returns True if scope has listeners
481
+ */
482
+ hasScope(scope) {
483
+ return this.scopedHandlers.has(scope);
457
484
  }
458
485
  };
459
- var PluginDependencyMissingError = class extends UtilsError {
460
- constructor(plugin, dependency) {
461
- super(`Plugin "${plugin}" requires "${dependency}" to be registered first`, "PLUGIN_DEPENDENCY_MISSING");
462
- this.name = "PluginDependencyMissingError";
486
+ var ScopedEventBus = class {
487
+ constructor(eventBus, scope) {
488
+ this.eventBus = eventBus;
489
+ this.scope = scope;
490
+ }
491
+ /**
492
+ * Register an event listener (automatically scoped).
493
+ */
494
+ on(event, handler) {
495
+ this.eventBus.onScoped(this.scope, event, handler);
496
+ }
497
+ /**
498
+ * Unregister an event listener.
499
+ */
500
+ off(event, handler) {
501
+ this.eventBus.off(event, handler);
502
+ }
503
+ /**
504
+ * Emit an event.
505
+ */
506
+ emit(event, ...args) {
507
+ this.eventBus.emit(event, ...args);
508
+ }
509
+ /**
510
+ * Remove all listeners registered by this scoped bus.
511
+ */
512
+ destroy() {
513
+ this.eventBus.removeScope(this.scope);
463
514
  }
464
515
  };
465
516
 
466
517
  // src/kernel.ts
467
518
  var Kernel = class {
468
519
  plugins = /* @__PURE__ */ new Map();
469
- context = {};
520
+ context;
470
521
  eventBus = new EventBus();
522
+ state = "idle";
523
+ initPromise = null;
524
+ constructor(options) {
525
+ this.context = options?.context ?? {};
526
+ }
471
527
  /**
472
528
  * Register a plugin with the kernel.
473
529
  *
530
+ * If the kernel is already initialized, the plugin will be
531
+ * automatically initialized after registration.
532
+ *
474
533
  * @param plugin - Plugin to register
475
534
  * @throws {PluginAlreadyRegisteredError} If plugin name already exists
476
535
  * @throws {PluginDependencyMissingError} If plugin dependencies are not met
477
536
  */
478
537
  register(plugin) {
479
538
  if (this.plugins.has(plugin.name)) {
480
- throw new PluginAlreadyRegisteredError(plugin.name);
539
+ throw new chunkDEVWOLUI_cjs.PluginAlreadyRegisteredError(plugin.name);
481
540
  }
482
541
  if (plugin.dependencies) {
483
542
  for (const dep of plugin.dependencies) {
484
543
  if (!this.plugins.has(dep)) {
485
- throw new PluginDependencyMissingError(plugin.name, dep);
544
+ throw new chunkDEVWOLUI_cjs.PluginDependencyMissingError(plugin.name, dep);
486
545
  }
487
546
  }
488
547
  }
489
- this.plugins.set(plugin.name, plugin);
548
+ const scopedBus = new ScopedEventBus(this.eventBus, plugin.name);
549
+ const entry = {
550
+ plugin,
551
+ state: "registered",
552
+ scopedBus
553
+ };
554
+ this.plugins.set(plugin.name, entry);
490
555
  try {
491
556
  plugin.install(this);
492
557
  } catch (error) {
493
558
  this.plugins.delete(plugin.name);
559
+ scopedBus.destroy();
494
560
  throw error;
495
561
  }
496
562
  this.eventBus.emit("plugin:registered", { name: plugin.name, version: plugin.version });
563
+ if (this.state === "initialized") {
564
+ this.initPlugin(entry).catch((error) => {
565
+ entry.state = "error";
566
+ this.eventBus.emit("plugin:error", { name: plugin.name, error });
567
+ });
568
+ }
497
569
  }
498
570
  /**
499
571
  * Initialize all registered plugins.
500
572
  *
501
- * Calls onInit() for each plugin that has it.
502
- * Plugins are initialized in the order they were registered.
573
+ * Plugins are initialized in topological order based on dependencies.
574
+ * If initialization fails, already initialized plugins are rolled back.
575
+ *
576
+ * @throws {CircularDependencyError} If circular dependency detected
577
+ * @throws {PluginInitializationError} If a plugin fails to initialize
503
578
  */
504
579
  async init() {
505
- for (const plugin of this.plugins.values()) {
506
- if (plugin.onInit) {
507
- try {
508
- await plugin.onInit(this.context);
509
- } catch (error) {
510
- if (plugin.onError) {
511
- plugin.onError(error);
580
+ if (this.state === "initialized") {
581
+ return;
582
+ }
583
+ if (this.state === "initializing") {
584
+ return this.initPromise;
585
+ }
586
+ if (this.state === "destroyed") {
587
+ throw new Error("Cannot initialize destroyed kernel");
588
+ }
589
+ this.state = "initializing";
590
+ this.initPromise = this.doInit();
591
+ try {
592
+ await this.initPromise;
593
+ } catch (error) {
594
+ if (this.state === "initializing") {
595
+ this.state = "idle";
596
+ }
597
+ throw error;
598
+ } finally {
599
+ this.initPromise = null;
600
+ }
601
+ }
602
+ async doInit() {
603
+ const sortedEntries = this.topologicalSort();
604
+ const initializedStack = [];
605
+ for (const entry of sortedEntries) {
606
+ if (entry.state === "error" || entry.state === "destroyed") {
607
+ entry.state = "registered";
608
+ }
609
+ }
610
+ for (const entry of sortedEntries) {
611
+ try {
612
+ await this.initPlugin(entry);
613
+ initializedStack.push(entry);
614
+ } catch (error) {
615
+ entry.state = "error";
616
+ for (const initialized of initializedStack.reverse()) {
617
+ try {
618
+ await this.destroyPlugin(initialized);
619
+ } catch (destroyError) {
620
+ console.error(
621
+ `Error during rollback of plugin "${initialized.plugin.name}":`,
622
+ destroyError
623
+ );
512
624
  }
513
- throw error;
514
625
  }
626
+ this.state = "idle";
627
+ throw new chunkDEVWOLUI_cjs.PluginInitializationError(
628
+ entry.plugin.name,
629
+ error instanceof Error ? error : new Error(String(error))
630
+ );
515
631
  }
516
632
  }
633
+ this.state = "initialized";
517
634
  this.eventBus.emit("kernel:initialized");
518
635
  }
636
+ /**
637
+ * Initialize a single plugin.
638
+ */
639
+ async initPlugin(entry) {
640
+ if (entry.state !== "registered") {
641
+ return;
642
+ }
643
+ entry.state = "initializing";
644
+ this.eventBus.emit("plugin:initializing", { name: entry.plugin.name });
645
+ if (entry.plugin.onInit) {
646
+ try {
647
+ await entry.plugin.onInit(this.context);
648
+ } catch (error) {
649
+ if (entry.plugin.onError) {
650
+ entry.plugin.onError(error);
651
+ }
652
+ throw error;
653
+ }
654
+ }
655
+ entry.state = "active";
656
+ this.eventBus.emit("plugin:initialized", { name: entry.plugin.name });
657
+ }
658
+ /**
659
+ * Destroy a single plugin.
660
+ */
661
+ async destroyPlugin(entry) {
662
+ if (entry.state === "destroyed") {
663
+ return;
664
+ }
665
+ entry.scopedBus.destroy();
666
+ if (entry.plugin.onDestroy) {
667
+ await entry.plugin.onDestroy();
668
+ }
669
+ entry.state = "destroyed";
670
+ }
671
+ /**
672
+ * Topological sort of plugins based on dependencies.
673
+ * Detects circular dependencies.
674
+ *
675
+ * @returns Plugins sorted in dependency order
676
+ * @throws {CircularDependencyError} If circular dependency detected
677
+ */
678
+ topologicalSort() {
679
+ const result = [];
680
+ const visited = /* @__PURE__ */ new Set();
681
+ const visiting = /* @__PURE__ */ new Set();
682
+ const visit = (name, path) => {
683
+ if (visited.has(name)) return;
684
+ if (visiting.has(name)) {
685
+ const cycleStart = path.indexOf(name);
686
+ const cycle = [...path.slice(cycleStart), name];
687
+ throw new chunkDEVWOLUI_cjs.CircularDependencyError(cycle);
688
+ }
689
+ const entry = this.plugins.get(name);
690
+ if (!entry) return;
691
+ visiting.add(name);
692
+ const currentPath = [...path, name];
693
+ if (entry.plugin.dependencies) {
694
+ for (const dep of entry.plugin.dependencies) {
695
+ visit(dep, currentPath);
696
+ }
697
+ }
698
+ visiting.delete(name);
699
+ visited.add(name);
700
+ result.push(entry);
701
+ };
702
+ for (const name of this.plugins.keys()) {
703
+ visit(name, []);
704
+ }
705
+ return result;
706
+ }
519
707
  /**
520
708
  * Unregister a plugin.
521
709
  *
710
+ * Automatically cleans up event listeners registered by this plugin.
711
+ *
522
712
  * @param name - Plugin name to unregister
523
713
  * @throws {PluginNotFoundError} If plugin doesn't exist
524
714
  */
525
- unregister(name) {
526
- const plugin = this.plugins.get(name);
527
- if (!plugin) {
528
- throw new PluginNotFoundError(name);
715
+ async unregister(name) {
716
+ const entry = this.plugins.get(name);
717
+ if (!entry) {
718
+ throw new chunkDEVWOLUI_cjs.PluginNotFoundError(name);
529
719
  }
530
- this.plugins.delete(name);
531
- if (plugin.onDestroy) {
532
- plugin.onDestroy();
720
+ for (const [otherName, otherEntry] of this.plugins) {
721
+ if (otherName !== name && otherEntry.plugin.dependencies?.includes(name)) {
722
+ throw new Error(
723
+ `Cannot unregister plugin "${name}": plugin "${otherName}" depends on it`
724
+ );
725
+ }
533
726
  }
727
+ await this.destroyPlugin(entry);
728
+ this.plugins.delete(name);
534
729
  this.eventBus.emit("plugin:unregistered", { name });
535
730
  }
536
731
  /**
@@ -548,7 +743,16 @@ var Kernel = class {
548
743
  * @returns Plugin instance or undefined
549
744
  */
550
745
  getPlugin(name) {
551
- return this.plugins.get(name);
746
+ return this.plugins.get(name)?.plugin;
747
+ }
748
+ /**
749
+ * Get the state of a registered plugin.
750
+ *
751
+ * @param name - Plugin name
752
+ * @returns Plugin state or undefined if not found
753
+ */
754
+ getPluginState(name) {
755
+ return this.plugins.get(name)?.state;
552
756
  }
553
757
  /**
554
758
  * Check if a plugin is registered.
@@ -567,6 +771,33 @@ var Kernel = class {
567
771
  listPlugins() {
568
772
  return Array.from(this.plugins.keys());
569
773
  }
774
+ /**
775
+ * Get the kernel's current state.
776
+ *
777
+ * @returns Current kernel state
778
+ */
779
+ getState() {
780
+ return this.state;
781
+ }
782
+ /**
783
+ * Check if kernel is initialized.
784
+ *
785
+ * @returns True if kernel is initialized
786
+ */
787
+ isInitialized() {
788
+ return this.state === "initialized";
789
+ }
790
+ /**
791
+ * Get the scoped event bus for a plugin.
792
+ * Listeners registered through this bus are automatically
793
+ * cleaned up when the plugin is unregistered.
794
+ *
795
+ * @param pluginName - Plugin name
796
+ * @returns Scoped event bus or undefined
797
+ */
798
+ getScopedEventBus(pluginName) {
799
+ return this.plugins.get(pluginName)?.scopedBus;
800
+ }
570
801
  /**
571
802
  * Register an event listener.
572
803
  *
@@ -597,18 +828,78 @@ var Kernel = class {
597
828
  /**
598
829
  * Destroy the kernel and all plugins.
599
830
  *
600
- * Unregisters all plugins and cleans up resources.
831
+ * Unregisters all plugins in reverse dependency order and cleans up resources.
601
832
  */
602
833
  async destroy() {
603
- const pluginNames = Array.from(this.plugins.keys());
604
- for (const name of pluginNames) {
605
- this.unregister(name);
834
+ if (this.state === "destroyed") {
835
+ return;
836
+ }
837
+ const sortedEntries = this.topologicalSort().reverse();
838
+ for (const entry of sortedEntries) {
839
+ try {
840
+ await this.destroyPlugin(entry);
841
+ } catch (error) {
842
+ console.error(`Error destroying plugin "${entry.plugin.name}":`, error);
843
+ }
606
844
  }
845
+ this.plugins.clear();
846
+ this.state = "destroyed";
847
+ this.eventBus.emit("kernel:destroyed");
607
848
  this.eventBus.removeAllListeners();
608
849
  }
609
850
  };
610
851
 
852
+ Object.defineProperty(exports, "CircularDependencyError", {
853
+ enumerable: true,
854
+ get: function () { return chunkDEVWOLUI_cjs.CircularDependencyError; }
855
+ });
856
+ Object.defineProperty(exports, "CircularReferenceError", {
857
+ enumerable: true,
858
+ get: function () { return chunkDEVWOLUI_cjs.CircularReferenceError; }
859
+ });
860
+ Object.defineProperty(exports, "InvalidPathError", {
861
+ enumerable: true,
862
+ get: function () { return chunkDEVWOLUI_cjs.InvalidPathError; }
863
+ });
864
+ Object.defineProperty(exports, "KernelAlreadyInitializedError", {
865
+ enumerable: true,
866
+ get: function () { return chunkDEVWOLUI_cjs.KernelAlreadyInitializedError; }
867
+ });
868
+ Object.defineProperty(exports, "KernelInitializingError", {
869
+ enumerable: true,
870
+ get: function () { return chunkDEVWOLUI_cjs.KernelInitializingError; }
871
+ });
872
+ Object.defineProperty(exports, "MaxRetriesExceededError", {
873
+ enumerable: true,
874
+ get: function () { return chunkDEVWOLUI_cjs.MaxRetriesExceededError; }
875
+ });
876
+ Object.defineProperty(exports, "PluginAlreadyRegisteredError", {
877
+ enumerable: true,
878
+ get: function () { return chunkDEVWOLUI_cjs.PluginAlreadyRegisteredError; }
879
+ });
880
+ Object.defineProperty(exports, "PluginDependencyMissingError", {
881
+ enumerable: true,
882
+ get: function () { return chunkDEVWOLUI_cjs.PluginDependencyMissingError; }
883
+ });
884
+ Object.defineProperty(exports, "PluginInitializationError", {
885
+ enumerable: true,
886
+ get: function () { return chunkDEVWOLUI_cjs.PluginInitializationError; }
887
+ });
888
+ Object.defineProperty(exports, "PluginNotFoundError", {
889
+ enumerable: true,
890
+ get: function () { return chunkDEVWOLUI_cjs.PluginNotFoundError; }
891
+ });
892
+ Object.defineProperty(exports, "TimeoutError", {
893
+ enumerable: true,
894
+ get: function () { return chunkDEVWOLUI_cjs.TimeoutError; }
895
+ });
896
+ Object.defineProperty(exports, "UtilsError", {
897
+ enumerable: true,
898
+ get: function () { return chunkDEVWOLUI_cjs.UtilsError; }
899
+ });
900
+ exports.EventBus = EventBus;
611
901
  exports.Kernel = Kernel;
902
+ exports.ScopedEventBus = ScopedEventBus;
612
903
  exports.array = array_exports;
613
904
  exports.camelCase = camelCase;
614
905
  exports.capitalize = capitalize;