@logosdx/hooks 1.0.0-beta.1 → 1.0.0-beta.2

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.
@@ -0,0 +1,906 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: Object.getOwnPropertyDescriptor(all, name).get
9
+ });
10
+ }
11
+ _export(exports, {
12
+ get HookEngine () {
13
+ return HookEngine;
14
+ },
15
+ get HookError () {
16
+ return HookError;
17
+ },
18
+ get isHookError () {
19
+ return isHookError;
20
+ }
21
+ });
22
+ var _utils = require("@logosdx/utils");
23
+ function _array_like_to_array(arr, len) {
24
+ if (len == null || len > arr.length) len = arr.length;
25
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
26
+ return arr2;
27
+ }
28
+ function _array_with_holes(arr) {
29
+ if (Array.isArray(arr)) return arr;
30
+ }
31
+ function _array_without_holes(arr) {
32
+ if (Array.isArray(arr)) return _array_like_to_array(arr);
33
+ }
34
+ function _assert_this_initialized(self) {
35
+ if (self === void 0) {
36
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
37
+ }
38
+ return self;
39
+ }
40
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
41
+ try {
42
+ var info = gen[key](arg);
43
+ var value = info.value;
44
+ } catch (error) {
45
+ reject(error);
46
+ return;
47
+ }
48
+ if (info.done) {
49
+ resolve(value);
50
+ } else {
51
+ Promise.resolve(value).then(_next, _throw);
52
+ }
53
+ }
54
+ function _async_to_generator(fn) {
55
+ return function() {
56
+ var self = this, args = arguments;
57
+ return new Promise(function(resolve, reject) {
58
+ var gen = fn.apply(self, args);
59
+ function _next(value) {
60
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
61
+ }
62
+ function _throw(err) {
63
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
64
+ }
65
+ _next(undefined);
66
+ });
67
+ };
68
+ }
69
+ function _call_super(_this, derived, args) {
70
+ derived = _get_prototype_of(derived);
71
+ return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
72
+ }
73
+ function _check_private_redeclaration(obj, privateCollection) {
74
+ if (privateCollection.has(obj)) {
75
+ throw new TypeError("Cannot initialize the same private elements twice on an object");
76
+ }
77
+ }
78
+ function _class_apply_descriptor_get(receiver, descriptor) {
79
+ if (descriptor.get) {
80
+ return descriptor.get.call(receiver);
81
+ }
82
+ return descriptor.value;
83
+ }
84
+ function _class_apply_descriptor_set(receiver, descriptor, value) {
85
+ if (descriptor.set) {
86
+ descriptor.set.call(receiver, value);
87
+ } else {
88
+ if (!descriptor.writable) {
89
+ throw new TypeError("attempted to set read only private field");
90
+ }
91
+ descriptor.value = value;
92
+ }
93
+ }
94
+ function _class_call_check(instance, Constructor) {
95
+ if (!(instance instanceof Constructor)) {
96
+ throw new TypeError("Cannot call a class as a function");
97
+ }
98
+ }
99
+ function _class_extract_field_descriptor(receiver, privateMap, action) {
100
+ if (!privateMap.has(receiver)) {
101
+ throw new TypeError("attempted to " + action + " private field on non-instance");
102
+ }
103
+ return privateMap.get(receiver);
104
+ }
105
+ function _class_private_field_get(receiver, privateMap) {
106
+ var descriptor = _class_extract_field_descriptor(receiver, privateMap, "get");
107
+ return _class_apply_descriptor_get(receiver, descriptor);
108
+ }
109
+ function _class_private_field_init(obj, privateMap, value) {
110
+ _check_private_redeclaration(obj, privateMap);
111
+ privateMap.set(obj, value);
112
+ }
113
+ function _class_private_field_set(receiver, privateMap, value) {
114
+ var descriptor = _class_extract_field_descriptor(receiver, privateMap, "set");
115
+ _class_apply_descriptor_set(receiver, descriptor, value);
116
+ return value;
117
+ }
118
+ function _class_private_method_get(receiver, privateSet, fn) {
119
+ if (!privateSet.has(receiver)) {
120
+ throw new TypeError("attempted to get private field on non-instance");
121
+ }
122
+ return fn;
123
+ }
124
+ function _class_private_method_init(obj, privateSet) {
125
+ _check_private_redeclaration(obj, privateSet);
126
+ privateSet.add(obj);
127
+ }
128
+ function _construct(Parent, args, Class) {
129
+ if (_is_native_reflect_construct()) {
130
+ _construct = Reflect.construct;
131
+ } else {
132
+ _construct = function construct(Parent, args, Class) {
133
+ var a = [
134
+ null
135
+ ];
136
+ a.push.apply(a, args);
137
+ var Constructor = Function.bind.apply(Parent, a);
138
+ var instance = new Constructor();
139
+ if (Class) _set_prototype_of(instance, Class.prototype);
140
+ return instance;
141
+ };
142
+ }
143
+ return _construct.apply(null, arguments);
144
+ }
145
+ function _defineProperties(target, props) {
146
+ for(var i = 0; i < props.length; i++){
147
+ var descriptor = props[i];
148
+ descriptor.enumerable = descriptor.enumerable || false;
149
+ descriptor.configurable = true;
150
+ if ("value" in descriptor) descriptor.writable = true;
151
+ Object.defineProperty(target, descriptor.key, descriptor);
152
+ }
153
+ }
154
+ function _create_class(Constructor, protoProps, staticProps) {
155
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
156
+ if (staticProps) _defineProperties(Constructor, staticProps);
157
+ return Constructor;
158
+ }
159
+ function _define_property(obj, key, value) {
160
+ if (key in obj) {
161
+ Object.defineProperty(obj, key, {
162
+ value: value,
163
+ enumerable: true,
164
+ configurable: true,
165
+ writable: true
166
+ });
167
+ } else {
168
+ obj[key] = value;
169
+ }
170
+ return obj;
171
+ }
172
+ function _get_prototype_of(o) {
173
+ _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
174
+ return o.__proto__ || Object.getPrototypeOf(o);
175
+ };
176
+ return _get_prototype_of(o);
177
+ }
178
+ function _inherits(subClass, superClass) {
179
+ if (typeof superClass !== "function" && superClass !== null) {
180
+ throw new TypeError("Super expression must either be null or a function");
181
+ }
182
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
183
+ constructor: {
184
+ value: subClass,
185
+ writable: true,
186
+ configurable: true
187
+ }
188
+ });
189
+ if (superClass) _set_prototype_of(subClass, superClass);
190
+ }
191
+ function _instanceof(left, right) {
192
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
193
+ return !!right[Symbol.hasInstance](left);
194
+ } else {
195
+ return left instanceof right;
196
+ }
197
+ }
198
+ function _is_native_function(fn) {
199
+ return Function.toString.call(fn).indexOf("[native code]") !== -1;
200
+ }
201
+ function _iterable_to_array(iter) {
202
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
203
+ }
204
+ function _iterable_to_array_limit(arr, i) {
205
+ var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
206
+ if (_i == null) return;
207
+ var _arr = [];
208
+ var _n = true;
209
+ var _d = false;
210
+ var _s, _e;
211
+ try {
212
+ for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
213
+ _arr.push(_s.value);
214
+ if (i && _arr.length === i) break;
215
+ }
216
+ } catch (err) {
217
+ _d = true;
218
+ _e = err;
219
+ } finally{
220
+ try {
221
+ if (!_n && _i["return"] != null) _i["return"]();
222
+ } finally{
223
+ if (_d) throw _e;
224
+ }
225
+ }
226
+ return _arr;
227
+ }
228
+ function _non_iterable_rest() {
229
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
230
+ }
231
+ function _non_iterable_spread() {
232
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
233
+ }
234
+ function _object_spread(target) {
235
+ for(var i = 1; i < arguments.length; i++){
236
+ var source = arguments[i] != null ? arguments[i] : {};
237
+ var ownKeys = Object.keys(source);
238
+ if (typeof Object.getOwnPropertySymbols === "function") {
239
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
240
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
241
+ }));
242
+ }
243
+ ownKeys.forEach(function(key) {
244
+ _define_property(target, key, source[key]);
245
+ });
246
+ }
247
+ return target;
248
+ }
249
+ function _possible_constructor_return(self, call) {
250
+ if (call && (_type_of(call) === "object" || typeof call === "function")) {
251
+ return call;
252
+ }
253
+ return _assert_this_initialized(self);
254
+ }
255
+ function _set_prototype_of(o, p) {
256
+ _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
257
+ o.__proto__ = p;
258
+ return o;
259
+ };
260
+ return _set_prototype_of(o, p);
261
+ }
262
+ function _sliced_to_array(arr, i) {
263
+ return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
264
+ }
265
+ function _to_consumable_array(arr) {
266
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
267
+ }
268
+ function _type_of(obj) {
269
+ "@swc/helpers - typeof";
270
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
271
+ }
272
+ function _unsupported_iterable_to_array(o, minLen) {
273
+ if (!o) return;
274
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
275
+ var n = Object.prototype.toString.call(o).slice(8, -1);
276
+ if (n === "Object" && o.constructor) n = o.constructor.name;
277
+ if (n === "Map" || n === "Set") return Array.from(n);
278
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
279
+ }
280
+ function _wrap_native_super(Class) {
281
+ var _cache = typeof Map === "function" ? new Map() : undefined;
282
+ _wrap_native_super = function wrapNativeSuper(Class) {
283
+ if (Class === null || !_is_native_function(Class)) return Class;
284
+ if (typeof Class !== "function") {
285
+ throw new TypeError("Super expression must either be null or a function");
286
+ }
287
+ if (typeof _cache !== "undefined") {
288
+ if (_cache.has(Class)) return _cache.get(Class);
289
+ _cache.set(Class, Wrapper);
290
+ }
291
+ function Wrapper() {
292
+ return _construct(Class, arguments, _get_prototype_of(this).constructor);
293
+ }
294
+ Wrapper.prototype = Object.create(Class.prototype, {
295
+ constructor: {
296
+ value: Wrapper,
297
+ enumerable: false,
298
+ writable: true,
299
+ configurable: true
300
+ }
301
+ });
302
+ return _set_prototype_of(Wrapper, Class);
303
+ };
304
+ return _wrap_native_super(Class);
305
+ }
306
+ function _is_native_reflect_construct() {
307
+ try {
308
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
309
+ } catch (_) {}
310
+ return (_is_native_reflect_construct = function() {
311
+ return !!result;
312
+ })();
313
+ }
314
+ function _ts_generator(thisArg, body) {
315
+ var f, y, t, _ = {
316
+ label: 0,
317
+ sent: function() {
318
+ if (t[0] & 1) throw t[1];
319
+ return t[1];
320
+ },
321
+ trys: [],
322
+ ops: []
323
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
324
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
325
+ return this;
326
+ }), g;
327
+ function verb(n) {
328
+ return function(v) {
329
+ return step([
330
+ n,
331
+ v
332
+ ]);
333
+ };
334
+ }
335
+ function step(op) {
336
+ if (f) throw new TypeError("Generator is already executing.");
337
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
338
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
339
+ if (y = 0, t) op = [
340
+ op[0] & 2,
341
+ t.value
342
+ ];
343
+ switch(op[0]){
344
+ case 0:
345
+ case 1:
346
+ t = op;
347
+ break;
348
+ case 4:
349
+ _.label++;
350
+ return {
351
+ value: op[1],
352
+ done: false
353
+ };
354
+ case 5:
355
+ _.label++;
356
+ y = op[1];
357
+ op = [
358
+ 0
359
+ ];
360
+ continue;
361
+ case 7:
362
+ op = _.ops.pop();
363
+ _.trys.pop();
364
+ continue;
365
+ default:
366
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
367
+ _ = 0;
368
+ continue;
369
+ }
370
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
371
+ _.label = op[1];
372
+ break;
373
+ }
374
+ if (op[0] === 6 && _.label < t[1]) {
375
+ _.label = t[1];
376
+ t = op;
377
+ break;
378
+ }
379
+ if (t && _.label < t[2]) {
380
+ _.label = t[2];
381
+ _.ops.push(op);
382
+ break;
383
+ }
384
+ if (t[2]) _.ops.pop();
385
+ _.trys.pop();
386
+ continue;
387
+ }
388
+ op = body.call(thisArg, _);
389
+ } catch (e) {
390
+ op = [
391
+ 6,
392
+ e
393
+ ];
394
+ y = 0;
395
+ } finally{
396
+ f = t = 0;
397
+ }
398
+ if (op[0] & 5) throw op[1];
399
+ return {
400
+ value: op[0] ? op[1] : void 0,
401
+ done: true
402
+ };
403
+ }
404
+ }
405
+ function _ts_values(o) {
406
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
407
+ if (m) return m.call(o);
408
+ if (o && typeof o.length === "number") return {
409
+ next: function() {
410
+ if (o && i >= o.length) o = void 0;
411
+ return {
412
+ value: o && o[i++],
413
+ done: !o
414
+ };
415
+ }
416
+ };
417
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
418
+ }
419
+ var HookError = /*#__PURE__*/ function(Error1) {
420
+ "use strict";
421
+ _inherits(HookError, Error1);
422
+ function HookError(message) {
423
+ _class_call_check(this, HookError);
424
+ var _this;
425
+ _this = _call_super(this, HookError, [
426
+ message
427
+ ]), /** Name of the hook where the error occurred */ _define_property(_this, "hookName", void 0), /** Original error if `fail()` was called with an Error instance */ _define_property(_this, "originalError", void 0);
428
+ return _this;
429
+ }
430
+ return HookError;
431
+ }(_wrap_native_super(Error));
432
+ var isHookError = function(error) {
433
+ var _error_constructor;
434
+ return (error === null || error === void 0 ? void 0 : (_error_constructor = error.constructor) === null || _error_constructor === void 0 ? void 0 : _error_constructor.name) === HookError.name;
435
+ };
436
+ var _hooks = /*#__PURE__*/ new WeakMap(), _hookOpts = /*#__PURE__*/ new WeakMap(), _handleFail = /*#__PURE__*/ new WeakMap(), _registered = /*#__PURE__*/ new WeakMap(), /**
437
+ * Validate that a hook is registered (if registration is enabled).
438
+ */ _assertRegistered = /*#__PURE__*/ new WeakSet();
439
+ var HookEngine = /*#__PURE__*/ function() {
440
+ "use strict";
441
+ function HookEngine() {
442
+ var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
443
+ _class_call_check(this, HookEngine);
444
+ _class_private_method_init(this, _assertRegistered);
445
+ _class_private_field_init(this, _hooks, {
446
+ writable: true,
447
+ value: new Map()
448
+ });
449
+ _class_private_field_init(this, _hookOpts, {
450
+ writable: true,
451
+ value: new WeakMap()
452
+ });
453
+ _class_private_field_init(this, _handleFail, {
454
+ writable: true,
455
+ value: void 0
456
+ });
457
+ _class_private_field_init(this, _registered, {
458
+ writable: true,
459
+ value: null
460
+ });
461
+ var _options_handleFail;
462
+ _class_private_field_set(this, _handleFail, (_options_handleFail = options.handleFail) !== null && _options_handleFail !== void 0 ? _options_handleFail : function(message) {
463
+ throw new HookError(message);
464
+ });
465
+ }
466
+ _create_class(HookEngine, [
467
+ {
468
+ /**
469
+ * Register hook names for runtime validation.
470
+ * Once any hooks are registered, all hooks must be registered before use.
471
+ *
472
+ * @param names - Hook names to register
473
+ * @returns this (for chaining)
474
+ *
475
+ * @example
476
+ * const hooks = new HookEngine<FetchLifecycle>()
477
+ * .register('preRequest', 'postRequest', 'rateLimit');
478
+ *
479
+ * hooks.on('preRequest', cb); // OK
480
+ * hooks.on('preRequset', cb); // Error: not registered (typo caught!)
481
+ */ key: "register",
482
+ value: function register() {
483
+ for(var _len = arguments.length, names = new Array(_len), _key = 0; _key < _len; _key++){
484
+ names[_key] = arguments[_key];
485
+ }
486
+ (0, _utils.assert)(names.length > 0, 'register() requires at least one hook name');
487
+ if (_class_private_field_get(this, _registered) === null) {
488
+ _class_private_field_set(this, _registered, new Set());
489
+ }
490
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
491
+ try {
492
+ for(var _iterator = names[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
493
+ var name = _step.value;
494
+ (0, _utils.assert)(typeof name === 'string', "Hook name must be a string, got ".concat(typeof name === "undefined" ? "undefined" : _type_of(name)));
495
+ _class_private_field_get(this, _registered).add(name);
496
+ }
497
+ } catch (err) {
498
+ _didIteratorError = true;
499
+ _iteratorError = err;
500
+ } finally{
501
+ try {
502
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
503
+ _iterator.return();
504
+ }
505
+ } finally{
506
+ if (_didIteratorError) {
507
+ throw _iteratorError;
508
+ }
509
+ }
510
+ }
511
+ return this;
512
+ }
513
+ },
514
+ {
515
+ /**
516
+ * Subscribe to a lifecycle hook.
517
+ *
518
+ * @param name - Name of the lifecycle hook
519
+ * @param cbOrOpts - Callback function or options object
520
+ * @returns Cleanup function to remove the subscription
521
+ *
522
+ * @example
523
+ * // Simple callback
524
+ * const cleanup = hooks.on('preRequest', async (ctx) => {
525
+ * console.log('Request:', ctx.args[0]);
526
+ * });
527
+ *
528
+ * // With options
529
+ * hooks.on('analytics', {
530
+ * callback: async (ctx) => { track(ctx.args); },
531
+ * once: true, // Remove after first run
532
+ * ignoreOnFail: true // Don't throw if callback fails
533
+ * });
534
+ *
535
+ * // Remove subscription
536
+ * cleanup();
537
+ */ key: "on",
538
+ value: function on(name, cbOrOpts) {
539
+ var callback = typeof cbOrOpts === 'function' ? cbOrOpts : cbOrOpts === null || cbOrOpts === void 0 ? void 0 : cbOrOpts.callback;
540
+ var opts = typeof cbOrOpts === 'function' ? {} : cbOrOpts;
541
+ (0, _utils.assert)(typeof name === 'string', '"name" must be a string');
542
+ (0, _utils.assert)((0, _utils.isFunction)(callback) || (0, _utils.isObject)(cbOrOpts), '"cbOrOpts" must be a callback or options');
543
+ (0, _utils.assert)((0, _utils.isFunction)(callback), 'callback must be a function');
544
+ _class_private_method_get(this, _assertRegistered, assertRegistered).call(this, name, 'on');
545
+ var _class_private_field_get_get;
546
+ var hooks = (_class_private_field_get_get = _class_private_field_get(this, _hooks).get(name)) !== null && _class_private_field_get_get !== void 0 ? _class_private_field_get_get : new Set();
547
+ hooks.add(callback);
548
+ _class_private_field_get(this, _hooks).set(name, hooks);
549
+ _class_private_field_get(this, _hookOpts).set(callback, opts);
550
+ return function() {
551
+ hooks.delete(callback);
552
+ };
553
+ }
554
+ },
555
+ {
556
+ /**
557
+ * Subscribe to a lifecycle hook that fires only once.
558
+ * Sugar for `on(name, { callback, once: true })`.
559
+ *
560
+ * @param name - Name of the lifecycle hook
561
+ * @param callback - Callback function
562
+ * @returns Cleanup function to remove the subscription
563
+ *
564
+ * @example
565
+ * // Log only the first request
566
+ * hooks.once('preRequest', async (ctx) => {
567
+ * console.log('First request:', ctx.args[0]);
568
+ * });
569
+ */ key: "once",
570
+ value: function once(name, callback) {
571
+ return this.on(name, {
572
+ callback: callback,
573
+ once: true
574
+ });
575
+ }
576
+ },
577
+ {
578
+ key: "emit",
579
+ value: /**
580
+ * Emit a lifecycle hook, running all subscribed callbacks.
581
+ *
582
+ * @param name - Name of the lifecycle hook to emit
583
+ * @param args - Arguments to pass to callbacks
584
+ * @returns EmitResult with final args, result, and earlyReturn flag
585
+ *
586
+ * @example
587
+ * const result = await hooks.emit('cacheCheck', url);
588
+ *
589
+ * if (result.earlyReturn && result.result) {
590
+ * return result.result; // Use cached value
591
+ * }
592
+ *
593
+ * // Continue with modified args
594
+ * const [modifiedUrl] = result.args;
595
+ */ function emit(name) {
596
+ for(var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
597
+ args[_key - 1] = arguments[_key];
598
+ }
599
+ return _async_to_generator(function() {
600
+ var _this, earlyReturn, hooks, context, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _this1, _loop, _iterator, _step, _ret, err;
601
+ return _ts_generator(this, function(_state) {
602
+ switch(_state.label){
603
+ case 0:
604
+ _this = this;
605
+ _class_private_method_get(this, _assertRegistered, assertRegistered).call(this, name, 'emit');
606
+ earlyReturn = false;
607
+ hooks = _class_private_field_get(this, _hooks).get(name);
608
+ context = {
609
+ args: args,
610
+ removeHook: function removeHook() {},
611
+ returnEarly: function returnEarly() {
612
+ earlyReturn = true;
613
+ },
614
+ setArgs: function(next) {
615
+ (0, _utils.assert)(Array.isArray(next), "setArgs: args for '".concat(String(name), "' must be an array"));
616
+ context.args = next;
617
+ },
618
+ setResult: function(next) {
619
+ context.result = next;
620
+ },
621
+ fail: function() {
622
+ for(var _len = arguments.length, failArgs = new Array(_len), _key = 0; _key < _len; _key++){
623
+ failArgs[_key] = arguments[_key];
624
+ }
625
+ var _handler_prototype;
626
+ var handler = _class_private_field_get(_this, _handleFail);
627
+ // Check if handler is a constructor (class or function with prototype)
628
+ var isConstructor = typeof handler === 'function' && ((_handler_prototype = handler.prototype) === null || _handler_prototype === void 0 ? void 0 : _handler_prototype.constructor) === handler;
629
+ var _attemptSync = _sliced_to_array((0, _utils.attemptSync)(function() {
630
+ if (isConstructor) {
631
+ throw _construct(handler, _to_consumable_array(failArgs));
632
+ }
633
+ handler.apply(void 0, _to_consumable_array(failArgs));
634
+ }), 2), error = _attemptSync[1];
635
+ if (error) {
636
+ if (_instanceof(error, HookError)) {
637
+ error.hookName = String(name);
638
+ }
639
+ throw error;
640
+ }
641
+ // If handler didn't throw, we need to throw something
642
+ throw new HookError('ctx.fail() handler did not throw');
643
+ }
644
+ };
645
+ if (!hooks || hooks.size === 0) {
646
+ return [
647
+ 2,
648
+ {
649
+ args: context.args,
650
+ result: context.result,
651
+ earlyReturn: false
652
+ }
653
+ ];
654
+ }
655
+ _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
656
+ _state.label = 1;
657
+ case 1:
658
+ _state.trys.push([
659
+ 1,
660
+ 6,
661
+ 7,
662
+ 8
663
+ ]);
664
+ _loop = function() {
665
+ var fn, _class_private_field_get_get, opts, _ref, _$err;
666
+ return _ts_generator(this, function(_state) {
667
+ switch(_state.label){
668
+ case 0:
669
+ fn = _step.value;
670
+ context.removeHook = function() {
671
+ return hooks.delete(fn);
672
+ };
673
+ opts = (_class_private_field_get_get = _class_private_field_get(_this1, _hookOpts).get(fn)) !== null && _class_private_field_get_get !== void 0 ? _class_private_field_get_get : {
674
+ callback: fn
675
+ };
676
+ return [
677
+ 4,
678
+ (0, _utils.attempt)(function() {
679
+ return fn(_object_spread({}, context));
680
+ })
681
+ ];
682
+ case 1:
683
+ _ref = _sliced_to_array.apply(void 0, [
684
+ _state.sent(),
685
+ 2
686
+ ]), _$err = _ref[1];
687
+ if (opts.once) context.removeHook();
688
+ if (_$err && opts.ignoreOnFail !== true) {
689
+ throw _$err;
690
+ }
691
+ if (earlyReturn) return [
692
+ 2,
693
+ "break"
694
+ ];
695
+ return [
696
+ 2
697
+ ];
698
+ }
699
+ });
700
+ };
701
+ _iterator = hooks[Symbol.iterator]();
702
+ _state.label = 2;
703
+ case 2:
704
+ if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [
705
+ 3,
706
+ 5
707
+ ];
708
+ _this1 = this;
709
+ return [
710
+ 5,
711
+ _ts_values(_loop())
712
+ ];
713
+ case 3:
714
+ _ret = _state.sent();
715
+ if (_ret === "break") return [
716
+ 3,
717
+ 5
718
+ ];
719
+ _state.label = 4;
720
+ case 4:
721
+ _iteratorNormalCompletion = true;
722
+ return [
723
+ 3,
724
+ 2
725
+ ];
726
+ case 5:
727
+ return [
728
+ 3,
729
+ 8
730
+ ];
731
+ case 6:
732
+ err = _state.sent();
733
+ _didIteratorError = true;
734
+ _iteratorError = err;
735
+ return [
736
+ 3,
737
+ 8
738
+ ];
739
+ case 7:
740
+ try {
741
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
742
+ _iterator.return();
743
+ }
744
+ } finally{
745
+ if (_didIteratorError) {
746
+ throw _iteratorError;
747
+ }
748
+ }
749
+ return [
750
+ 7
751
+ ];
752
+ case 8:
753
+ return [
754
+ 2,
755
+ {
756
+ args: context.args,
757
+ result: context.result,
758
+ earlyReturn: earlyReturn
759
+ }
760
+ ];
761
+ }
762
+ });
763
+ }).call(this);
764
+ }
765
+ },
766
+ {
767
+ /**
768
+ * Clear all registered hooks.
769
+ *
770
+ * @example
771
+ * hooks.on('preRequest', validator);
772
+ * hooks.on('postRequest', logger);
773
+ *
774
+ * // Reset for testing
775
+ * hooks.clear();
776
+ */ key: "clear",
777
+ value: function clear() {
778
+ _class_private_field_get(this, _hooks).clear();
779
+ _class_private_field_set(this, _hookOpts, new WeakMap());
780
+ _class_private_field_set(this, _registered, null);
781
+ }
782
+ },
783
+ {
784
+ /**
785
+ * Wrap a function with pre/post lifecycle hooks.
786
+ *
787
+ * - Pre hook: emitted with function args, can modify args or returnEarly with result
788
+ * - Post hook: emitted with [result, ...args], can modify result
789
+ *
790
+ * @param fn - The async function to wrap
791
+ * @param hooks - Object with optional pre and post hook names
792
+ * @returns Wrapped function with same signature
793
+ *
794
+ * @example
795
+ * interface Lifecycle {
796
+ * preRequest(url: string, opts: RequestInit): Promise<Response>;
797
+ * postRequest(result: Response, url: string, opts: RequestInit): Promise<Response>;
798
+ * }
799
+ *
800
+ * const hooks = new HookEngine<Lifecycle>();
801
+ *
802
+ * // Add cache check in pre hook
803
+ * hooks.on('preRequest', async (ctx) => {
804
+ * const cached = cache.get(ctx.args[0]);
805
+ * if (cached) {
806
+ * ctx.setResult(cached);
807
+ * ctx.returnEarly();
808
+ * }
809
+ * });
810
+ *
811
+ * // Log result in post hook
812
+ * hooks.on('postRequest', async (ctx) => {
813
+ * const [result, url] = ctx.args;
814
+ * console.log(`Fetched ${url}:`, result.status);
815
+ * });
816
+ *
817
+ * // Wrap the fetch function
818
+ * const wrappedFetch = hooks.wrap(
819
+ * async (url: string, opts: RequestInit) => fetch(url, opts),
820
+ * { pre: 'preRequest', post: 'postRequest' }
821
+ * );
822
+ */ key: "wrap",
823
+ value: function wrap(fn, hooks) {
824
+ var _this = this;
825
+ (0, _utils.assert)(hooks.pre || hooks.post, 'wrap() requires at least one of "pre" or "post" hooks');
826
+ if (hooks.pre) _class_private_method_get(this, _assertRegistered, assertRegistered).call(this, hooks.pre, 'wrap');
827
+ if (hooks.post) _class_private_method_get(this, _assertRegistered, assertRegistered).call(this, hooks.post, 'wrap');
828
+ return function() {
829
+ for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
830
+ args[_key] = arguments[_key];
831
+ }
832
+ return _async_to_generator(function() {
833
+ var currentArgs, result, preResult, postResult;
834
+ return _ts_generator(this, function(_state) {
835
+ switch(_state.label){
836
+ case 0:
837
+ currentArgs = args;
838
+ if (!hooks.pre) return [
839
+ 3,
840
+ 2
841
+ ];
842
+ return [
843
+ 4,
844
+ this.emit.apply(this, [
845
+ hooks.pre
846
+ ].concat(_to_consumable_array(currentArgs)))
847
+ ];
848
+ case 1:
849
+ preResult = _state.sent();
850
+ currentArgs = preResult.args;
851
+ if (preResult.earlyReturn && preResult.result !== undefined) {
852
+ return [
853
+ 2,
854
+ preResult.result
855
+ ];
856
+ }
857
+ _state.label = 2;
858
+ case 2:
859
+ return [
860
+ 4,
861
+ fn.apply(void 0, _to_consumable_array(currentArgs))
862
+ ];
863
+ case 3:
864
+ // Execute function
865
+ result = _state.sent();
866
+ if (!hooks.post) return [
867
+ 3,
868
+ 5
869
+ ];
870
+ return [
871
+ 4,
872
+ this.emit.apply(this, [
873
+ hooks.post
874
+ ].concat(_to_consumable_array([
875
+ result
876
+ ].concat(_to_consumable_array(currentArgs)))))
877
+ ];
878
+ case 4:
879
+ postResult = _state.sent();
880
+ if (postResult.result !== undefined) {
881
+ return [
882
+ 2,
883
+ postResult.result
884
+ ];
885
+ }
886
+ _state.label = 5;
887
+ case 5:
888
+ return [
889
+ 2,
890
+ result
891
+ ];
892
+ }
893
+ });
894
+ }).call(_this);
895
+ };
896
+ }
897
+ }
898
+ ]);
899
+ return HookEngine;
900
+ }();
901
+ function assertRegistered(name, method) {
902
+ if (_class_private_field_get(this, _registered) !== null && !_class_private_field_get(this, _registered).has(name)) {
903
+ var registered = _to_consumable_array(_class_private_field_get(this, _registered)).map(String).join(', ');
904
+ throw new Error('Hook "'.concat(String(name), '" is not registered. ') + 'Call register("'.concat(String(name), '") before using ').concat(method, "(). ") + "Registered hooks: ".concat(registered || '(none)'));
905
+ }
906
+ }