@remotex-labs/xjet 1.2.2 → 1.3.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.
package/dist/shared.d.ts CHANGED
@@ -3,19 +3,23 @@
3
3
  * This file was automatically generated by xBuild.
4
4
  * DO NOT EDIT MANUALLY.
5
5
  */
6
- import type { FunctionType, RejectedValueType, ResolvedValueType } from '@remotex-labs/xjet-expect';
6
+ import type { FunctionType } from '@remotex-labs/xjet-expect';
7
7
  import type { FunctionLikeType, FunctionType } from '@remotex-labs/xjet-expect';
8
8
  import type { ContextType, FunctionType } from '@remotex-labs/xjet-expect';
9
9
  import { type ContextType, type FunctionLikeType, type FunctionType } from '@remotex-labs/xjet-expect';
10
10
  import type { ContextType } from '@remotex-labs/xjet-expect';
11
11
  import type { FunctionLikeType } from '@remotex-labs/xjet-expect';
12
- import type { FunctionType } from '@remotex-labs/xjet-expect';
13
12
  import type { Struct } from '@remotex-labs/xstruct';
14
13
  import { Struct } from '@remotex-labs/xstruct';
15
14
 
16
15
  /**
17
16
  * Imports
18
17
  */
18
+ import '@shared/components/require.component';
19
+
20
+ /**
21
+ * Import will remove at compile time
22
+ */
19
23
  export {};
20
24
 
21
25
  /**
@@ -538,7 +542,7 @@ declare class MockState<F extends FunctionType = FunctionType> extends Function
538
542
  *
539
543
  * @since 1.0.0
540
544
  */
541
- mockResolvedValue(value: ResolvedValueType<ReturnType<F>>): this;
545
+ mockResolvedValue(value: PromiseValueType<ReturnType<F>>): this;
542
546
  /**
543
547
  * Adds a one-time resolved Promise return value for this mock function.
544
548
  *
@@ -572,7 +576,7 @@ declare class MockState<F extends FunctionType = FunctionType> extends Function
572
576
  *
573
577
  * @since 1.0.0
574
578
  */
575
- mockResolvedValueOnce(value: ResolvedValueType<ReturnType<F>>): this;
579
+ mockResolvedValueOnce(value: PromiseValueType<ReturnType<F>>): this;
576
580
  /**
577
581
  * Sets a rejected Promise return value for this mock function.
578
582
  *
@@ -609,7 +613,7 @@ declare class MockState<F extends FunctionType = FunctionType> extends Function
609
613
  *
610
614
  * @since 1.0.0
611
615
  */
612
- mockRejectedValue(value: RejectedValueType<ReturnType<F>>): this;
616
+ mockRejectedValue(value: PromiseValueType<ReturnType<F>>): this;
613
617
  /**
614
618
  * Adds a one-time rejected Promise return value for this mock function.
615
619
  *
@@ -645,7 +649,7 @@ declare class MockState<F extends FunctionType = FunctionType> extends Function
645
649
  *
646
650
  * @since 1.0.0
647
651
  */
648
- mockRejectedValueOnce(value: RejectedValueType<ReturnType<F>>): this;
652
+ mockRejectedValueOnce(value: PromiseValueType<ReturnType<F>>): this;
649
653
  /**
650
654
  * Initializes the internal state object for the mock function.
651
655
  *
@@ -742,26 +746,6 @@ declare class MockState<F extends FunctionType = FunctionType> extends Function
742
746
  private invokeFunction;
743
747
  }
744
748
 
745
- /**
746
- * Represents an interface for defining bound context and arguments.
747
- *
748
- * @template Context - The type of the bound `this` context, which can be an object, null, or undefined.
749
- * @template Args - The type of the array representing bound arguments.
750
- *
751
- * @remarks
752
- * This interface is designed to store binding metadata, specifically a reference to the bound `this` context
753
- * and any arguments that are pre-applied during function binding. It is often used in scenarios involving
754
- * dynamic contexts or partial application of functions.
755
- *
756
- * @see ContextType
757
- *
758
- * @since 1.0.0
759
- */
760
- interface BoundInterface<Context = unknown | null | undefined, Args = Array<unknown>> {
761
- __boundThis?: Context;
762
- __boundArgs?: Args;
763
- }
764
-
765
749
  /**
766
750
  * Import will remove at compile time
767
751
  */
@@ -868,6 +852,29 @@ interface MocksStateInterface<F extends FunctionType> {
868
852
  */
869
853
  results: Array<MockInvocationResultInterface<ReturnType<F>>>;
870
854
  }
855
+ /**
856
+ * Extracts the resolved value type from a `PromiseLike` type.
857
+ *
858
+ * @template T The input type to inspect.
859
+ *
860
+ * @remarks
861
+ * If `T` extends `PromiseLike<infer U>`, the resulting type is `U | T`, meaning it includes both
862
+ * the resolved value type and the original `PromiseLike` type.
863
+ *
864
+ * If `T` is not a `PromiseLike`, the resulting type is simply `T`.
865
+ *
866
+ * This utility type is useful when you want to support both synchronous and asynchronous values
867
+ * transparently — for example, when a function may return either a raw value or a promise.
868
+ *
869
+ * @example
870
+ * ```ts
871
+ * type A = PromiseValueType<Promise<number>>; // number | Promise<number>
872
+ * type B = PromiseValueType<string>; // string
873
+ * ```
874
+ *
875
+ * @since 1.0.0
876
+ */
877
+ type PromiseValueType<T> = T | (T extends PromiseLike<infer U> ? U | T : never);
871
878
  /**
872
879
  * A utility type that extracts the signature of a function and allows it to be reused in an implementation.
873
880
  *
@@ -898,7 +905,27 @@ interface MocksStateInterface<F extends FunctionType> {
898
905
  *
899
906
  * @since 1.2.2
900
907
  */
901
- type ImplementationType<F extends FunctionType> = FunctionLikeType<ReturnType<F>, Parameters<F>, ThisParameterType<F>>;
908
+ type ImplementationType<F extends FunctionType> = FunctionLikeType<PromiseValueType<ReturnType<F>>, Parameters<F>, ThisParameterType<F>>;
909
+
910
+ /**
911
+ * Represents an interface for defining bound context and arguments.
912
+ *
913
+ * @template Context - The type of the bound `this` context, which can be an object, null, or undefined.
914
+ * @template Args - The type of the array representing bound arguments.
915
+ *
916
+ * @remarks
917
+ * This interface is designed to store binding metadata, specifically a reference to the bound `this` context
918
+ * and any arguments that are pre-applied during function binding. It is often used in scenarios involving
919
+ * dynamic contexts or partial application of functions.
920
+ *
921
+ * @see ContextType
922
+ *
923
+ * @since 1.0.0
924
+ */
925
+ interface BoundInterface<Context = unknown | null | undefined, Args = Array<unknown>> {
926
+ __boundThis?: Context;
927
+ __boundArgs?: Args;
928
+ }
902
929
 
903
930
  /**
904
931
  * Import will remove at compile time
@@ -1858,6 +1885,26 @@ declare class TimerService {
1858
1885
  * @since 1.1.0
1859
1886
  */
1860
1887
  useRealTimers(): void;
1888
+ /**
1889
+ * Clears all active fake timers.
1890
+ *
1891
+ * @remarks
1892
+ * This method removes every timer currently stored in {@link timers},
1893
+ * effectively resetting the fake timer state without advancing time.
1894
+ * It is useful for cleaning up between tests to ensure no lingering
1895
+ * scheduled callbacks remain.
1896
+ *
1897
+ * @example
1898
+ * ```ts
1899
+ * useFakeTimers();
1900
+ * setTimeout(() => console.log('A'), 100);
1901
+ * clearAllTimers(); // removes all scheduled timers
1902
+ * advanceTimersByTime(100); // nothing happens
1903
+ * ```
1904
+ *
1905
+ * @since 1.3.0
1906
+ */
1907
+ clearAllTimers(): void;
1861
1908
  /**
1862
1909
  * Advances the simulated clock by a specific number of milliseconds and
1863
1910
  * executes all timers whose scheduled time has elapsed.
@@ -1928,6 +1975,51 @@ declare class TimerService {
1928
1975
  * @since 1.1.0
1929
1976
  */
1930
1977
  runOnlyPendingTimers(): void;
1978
+ /**
1979
+ * Asynchronous equivalent of {@link runAllTimers}.
1980
+ *
1981
+ * @remarks
1982
+ * This method first yields to the event loop to allow any pending promises
1983
+ * to resolve before executing all remaining fake timers.
1984
+ * It ensures a deterministic sequence when timers and microtasks coexist.
1985
+ *
1986
+ * @example
1987
+ * ```ts
1988
+ * useFakeTimers();
1989
+ * Promise.resolve().then(() => console.log('microtask'));
1990
+ * setTimeout(() => console.log('timer'), 0);
1991
+ * await timerService.runAllTimersAsync();
1992
+ * // Logs:
1993
+ * // microtask
1994
+ * // timer
1995
+ * ```
1996
+ *
1997
+ * @since 1.3.0
1998
+ */
1999
+ runAllTimersAsync(): Promise<void>;
2000
+ /**
2001
+ * Asynchronous equivalent of {@link runOnlyPendingTimers}.
2002
+ *
2003
+ * @remarks
2004
+ * This method first yields to the event loop to allow any pending promises
2005
+ * to resolve before executing only currently pending fake timers.
2006
+ * Timers scheduled during execution will not run until explicitly advanced later.
2007
+ *
2008
+ * @example
2009
+ * ```ts
2010
+ * useFakeTimers();
2011
+ * setTimeout(() => {
2012
+ * console.log('first');
2013
+ * setTimeout(() => console.log('second'), 100);
2014
+ * }, 100);
2015
+ * await timerService.runOnlyPendingTimersAsync();
2016
+ * // Logs:
2017
+ * // first
2018
+ * ```
2019
+ *
2020
+ * @since 1.3.0
2021
+ */
2022
+ runOnlyPendingTimersAsync(): Promise<void>;
1931
2023
  }
1932
2024
  /**
1933
2025
  * Globally enables fake timers using the shared {@link TimerService}.
@@ -1991,6 +2083,31 @@ declare function useRealTimers(): void;
1991
2083
  * @since 1.1.0
1992
2084
  */
1993
2085
  declare function runAllTimers(): void;
2086
+ /**
2087
+ * Removes all scheduled fake timers from the {@link TimerService}.
2088
+ *
2089
+ * @remarks
2090
+ * This function clears all active timers registered in the shared timer service,
2091
+ * effectively canceling any pending callbacks that would have run during
2092
+ * timer advancement.
2093
+ *
2094
+ * It's useful for resetting the fake timer state between test cases to ensure
2095
+ * no lingering timers affect further tests or for scenarios where you
2096
+ * need to abort all pending operations.
2097
+ *
2098
+ * @example
2099
+ * ```ts
2100
+ * useFakeTimers();
2101
+ * setTimeout(() => console.log('A'), 100);
2102
+ * setTimeout(() => console.log('B'), 200);
2103
+ *
2104
+ * clearAllTimers(); // removes all scheduled timers
2105
+ * advanceTimersByTime(1000); // nothing happens, not show any logs
2106
+ * ```
2107
+ *
2108
+ * @since 1.3.0
2109
+ */
2110
+ declare function clearAllTimers(): void;
1994
2111
  /**
1995
2112
  * Executes only the timers that are pending at the time of invocation.
1996
2113
  *
@@ -2038,6 +2155,48 @@ declare function runOnlyPendingTimers(): void;
2038
2155
  * @since 1.1.0
2039
2156
  */
2040
2157
  declare function advanceTimersByTime(ms?: number): void;
2158
+ /**
2159
+ * Asynchronous equivalent of {@link runAllTimers}.
2160
+ *
2161
+ * @remarks
2162
+ * Yields to the event loop before running all pending fake timers.
2163
+ * Useful when working with both Promises and fake timers.
2164
+ *
2165
+ * @example
2166
+ * ```ts
2167
+ * xJet.useFakeTimers();
2168
+ * Promise.resolve().then(() => console.log('promise done'));
2169
+ * setTimeout(() => console.log('timeout done'), 0);
2170
+ * await xJet.runAllTimersAsync();
2171
+ * // Logs:
2172
+ * // promise done
2173
+ * // timeout done
2174
+ * ```
2175
+ *
2176
+ * @since 1.3.0
2177
+ */
2178
+ declare function runAllTimersAsync(): Promise<void>;
2179
+ /**
2180
+ * Asynchronous equivalent of {@link runOnlyPendingTimers}.
2181
+ *
2182
+ * @remarks
2183
+ * Yields to the event loop before running only timers that are currently pending.
2184
+ * Any timers scheduled by those callbacks will not be executed until a later call.
2185
+ *
2186
+ * @example
2187
+ * ```ts
2188
+ * useFakeTimers();
2189
+ * setTimeout(() => {
2190
+ * console.log('first');
2191
+ * setTimeout(() => console.log('second'), 100);
2192
+ * }, 100);
2193
+ * await runOnlyPendingTimersAsync();
2194
+ * // Logs only "first"
2195
+ * ```
2196
+ *
2197
+ * @since 1.3.0
2198
+ */
2199
+ declare function runOnlyPendingTimersAsync(): Promise<void>;
2041
2200
 
2042
2201
  /**
2043
2202
  * Interface representing a single timer stored and executed by the {@link TimerService}.
@@ -3258,7 +3417,66 @@ declare function spyOnProxyGet<T extends Record<string | symbol, unknown>, K ext
3258
3417
  *
3259
3418
  * @since 1.0.0
3260
3419
  */
3261
- declare function spyOnImplementation<T extends object, K extends keyof T>(target: T, key: K): T[K] extends FunctionType ? MockState<(this: ThisParameterType<T[K]>, ...args: Parameters<T[K]>) => ReturnType<T[K]>> : MockState<() => T[K]>;
3420
+ declare function spyOnImplementation<T extends object, K extends keyof T>(target: T, key: K): T[K] extends FunctionType ? MockState<(this: ThisParameterType<T[K]>, ...args: Parameters<T[K]>) => PartialResolvedType<ReturnType<T[K]>>> : MockState<() => T[K]>;
3421
+
3422
+ /**
3423
+ * Import will remove at compile time
3424
+ */
3425
+ /**
3426
+ * Represents a mockable function interface with a customizable return type, context,
3427
+ * and argument list. This interface extends `MockState` to facilitate tracking
3428
+ * and testing of function behaviors and states.
3429
+ *
3430
+ * @template F - The function / class type being mocked
3431
+ *
3432
+ * @remarks
3433
+ * This interface is useful for creating test doubles or mock implementations that simulate
3434
+ * complex behaviors (allows for both `function-like` behavior and `constructor-like` behavior)
3435
+ * while tracking interactions and state information.
3436
+ *
3437
+ * @see MockState
3438
+ *
3439
+ * @since 1.0.0
3440
+ */
3441
+ interface MockableFunctionInterface<F extends FunctionType> extends MockState<F> {
3442
+ /**
3443
+ * Constructor signature when the mocked item is used with 'new'
3444
+ */
3445
+ new (...args: Parameters<F>): ReturnType<F>;
3446
+ /**
3447
+ * Function call signature preserving 'this' context and parameters
3448
+ */
3449
+ (this: ThisParameterType<F>, ...args: Parameters<F>): ReturnType<F>;
3450
+ }
3451
+ /**
3452
+ * Makes properties of a type or its resolved promise value optional.
3453
+ * Converts `never` to `void` to avoid unassignable types.
3454
+ *
3455
+ * @template T - The type to transform
3456
+ *
3457
+ * @remarks
3458
+ * If `T` is a `PromiseLike` type, this utility unwraps it and makes the resolved value's
3459
+ * properties optional.
3460
+ * If `T` is `never`, it is converted to `void`.
3461
+ * Otherwise, it directly makes `T`'s properties optional.
3462
+ *
3463
+ * @example
3464
+ * ```ts
3465
+ * // Makes properties of User optional
3466
+ * type MaybeUser = PartialResolvedType<User>;
3467
+ *
3468
+ * // Makes properties of resolved User optional
3469
+ * type MaybeAsyncUser = PartialResolvedType<Promise<User>>;
3470
+ *
3471
+ * // Never becomes void
3472
+ * type MaybeNever = PartialResolvedType<never>; // void
3473
+ * ```
3474
+ *
3475
+ * @since 1.2.2
3476
+ */
3477
+ type PartialResolvedType<T> = [
3478
+ T
3479
+ ] extends [never] ? void : T extends PromiseLike<infer U> ? Promise<Partial<U>> : Partial<T>;
3262
3480
 
3263
3481
  /**
3264
3482
  * Interface representing the internal state of a mock proxy.
@@ -3422,7 +3640,7 @@ declare function fnImplementation<ReturnType, Args extends Array<unknown>, Conte
3422
3640
  *
3423
3641
  * @since 1.2.2
3424
3642
  */
3425
- declare function mockImplementation<F extends abstract new (...args: any) => any>(method: F, implementation?: (...args: ConstructorParameters<F>) => Partial<InstanceType<F>>): MockState<(...args: ConstructorParameters<F>) => Partial<InstanceType<F>>>;
3643
+ declare function mockImplementation<F extends abstract new (...args: any) => any>(method: F, implementation?: (...args: ConstructorParameters<F>) => PartialResolvedType<InstanceType<F>>): MockState<(...args: ConstructorParameters<F>) => PartialResolvedType<InstanceType<F>>>;
3426
3644
  /**
3427
3645
  * Creates a mock implementation of the provided function.
3428
3646
  *
@@ -3457,7 +3675,7 @@ declare function mockImplementation<F extends abstract new (...args: any) => any
3457
3675
  *
3458
3676
  * @since 1.2.2
3459
3677
  */
3460
- declare function mockImplementation<F extends FunctionType>(method: F, implementation?: (...args: Parameters<F>) => Partial<ReturnType<F>>): MockState<(this: ThisParameterType<F>, ...args: Parameters<F>) => Partial<ReturnType<F>>>;
3678
+ declare function mockImplementation<F extends FunctionType>(method: F, implementation?: (...args: Parameters<F>) => PartialResolvedType<ReturnType<F>>): MockState<(this: ThisParameterType<F>, ...args: Parameters<F>) => PartialResolvedType<ReturnType<F>>>;
3461
3679
  /**
3462
3680
  * Creates a mock for an element with an optional custom implementation.
3463
3681
  *
@@ -3507,36 +3725,6 @@ declare function mockImplementation<F extends FunctionType>(method: F, implement
3507
3725
  */
3508
3726
  declare function mockImplementation<Element = unknown>(item: Element, implementation?: () => Element): MockState<() => Element>;
3509
3727
 
3510
- /**
3511
- * Import will remove at compile time
3512
- */
3513
- /**
3514
- * Represents a mockable function interface with a customizable return type, context,
3515
- * and argument list. This interface extends `MockState` to facilitate tracking
3516
- * and testing of function behaviors and states.
3517
- *
3518
- * @template F - The function / class type being mocked
3519
- *
3520
- * @remarks
3521
- * This interface is useful for creating test doubles or mock implementations that simulate
3522
- * complex behaviors (allows for both `function-like` behavior and `constructor-like` behavior)
3523
- * while tracking interactions and state information.
3524
- *
3525
- * @see MockState
3526
- *
3527
- * @since 1.0.0
3528
- */
3529
- interface MockableFunctionInterface<F extends FunctionType> extends MockState<F> {
3530
- /**
3531
- * Constructor signature when the mocked item is used with 'new'
3532
- */
3533
- new (...args: Parameters<F>): ReturnType<F>;
3534
- /**
3535
- * Function call signature preserving 'this' context and parameters
3536
- */
3537
- (this: ThisParameterType<F>, ...args: Parameters<F>): ReturnType<F>;
3538
- }
3539
-
3540
3728
  /**
3541
3729
  * Import will remove at compile time
3542
3730
  */
@@ -3582,7 +3770,7 @@ interface MockableFunctionInterface<F extends FunctionType> extends MockState<F>
3582
3770
  * @see DeepSearchInterface
3583
3771
  * @since 1.0.0
3584
3772
  */
3585
- declare function deepSearchObject(target: Record<string | symbol, unknown>, element: unknown, key?: string, maxDepth?: number): DeepSearchInterface | null;
3773
+ declare function deepSearchObject(target: Record<string | symbol, unknown>, element: unknown, key?: string | symbol, maxDepth?: number): DeepSearchInterface | null;
3586
3774
  /**
3587
3775
  * Resolves property references that may be affected by ESBuild's `__toESM` transformation.
3588
3776
  *
package/dist/shared.js CHANGED
@@ -1,8 +1,8 @@
1
- var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __knownSymbol=(name,symbol)=>(symbol=Symbol[name])?symbol:Symbol.for("Symbol."+name),__typeError=msg=>{throw TypeError(msg)};var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0});var __decoratorStart=base=>[,,,__create(base?.[__knownSymbol("metadata")]??null)],__decoratorStrings=["class","method","getter","setter","accessor","field","value","get","set"],__expectFn=fn=>fn!==void 0&&typeof fn!="function"?__typeError("Function expected"):fn,__decoratorContext=(kind,name,done,metadata,fns)=>({kind:__decoratorStrings[kind],name,metadata,addInitializer:fn=>done._?__typeError("Already initialized"):fns.push(__expectFn(fn||null))}),__decoratorMetadata=(array,target)=>__defNormalProp(target,__knownSymbol("metadata"),array[3]),__runInitializers=(array,flags,self,value)=>{for(var i=0,fns=array[flags>>1],n=fns&&fns.length;i<n;i++)flags&1?fns[i].call(self):value=fns[i].call(self,value);return value},__decorateElement=(array,flags,name,decorators,target,extra)=>{var fn,it,done,ctx,access,k=flags&7,s=!!(flags&8),p=!!(flags&16),j=k>3?array.length+1:k?s?1:2:0,key=__decoratorStrings[k+5],initializers=k>3&&(array[j-1]=[]),extraInitializers=array[j]||(array[j]=[]),desc=k&&(!p&&!s&&(target=target.prototype),k<5&&(k>3||!p)&&__getOwnPropDesc(k<4?target:{get[name](){return __privateGet(this,extra)},set[name](x){return __privateSet(this,extra,x)}},name));k?p&&k<4&&__name(extra,(k>2?"set ":k>1?"get ":"")+name):__name(target,name);for(var i=decorators.length-1;i>=0;i--)ctx=__decoratorContext(k,name,done={},array[3],extraInitializers),k&&(ctx.static=s,ctx.private=p,access=ctx.access={has:p?x=>__privateIn(target,x):x=>name in x},k^3&&(access.get=p?x=>(k^1?__privateGet:__privateMethod)(x,target,k^4?extra:desc.get):x=>x[name]),k>2&&(access.set=p?(x,y)=>__privateSet(x,target,y,k^4?extra:desc.set):(x,y)=>x[name]=y)),it=(0,decorators[i])(k?k<4?p?extra:desc[key]:k>4?void 0:{get:desc.get,set:desc.set}:target,ctx),done._=1,k^4||it===void 0?__expectFn(it)&&(k>4?initializers.unshift(it):k?p?extra=it:desc[key]=it:target=it):typeof it!="object"||it===null?__typeError("Object expected"):(__expectFn(fn=it.get)&&(desc.get=fn),__expectFn(fn=it.set)&&(desc.set=fn),__expectFn(fn=it.init)&&initializers.unshift(fn));return k||__decoratorMetadata(array,target),desc&&__defProp(target,name,desc),p?k^4?extra:desc:target};var __accessCheck=(obj,member,msg)=>member.has(obj)||__typeError("Cannot "+msg),__privateIn=(member,obj)=>Object(obj)!==obj?__typeError('Cannot use the "in" operator on this value'):member.has(obj),__privateGet=(obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj));var __privateSet=(obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value),__privateMethod=(obj,member,method)=>(__accessCheck(obj,member,"access private method"),method);import{xExpect}from"@remotex-labs/xjet-expect";var DEFAULT_MOCK_NAME="xJet.mock()",MockState=class extends Function{static{__name(this,"MockState")}static mocks=new Set;name;xJetMock=!0;state;queuedImplementations=[];implementation;originalImplementation;restore;constructor(implementation,restore,name){return super(),this.name=name??DEFAULT_MOCK_NAME,this.state=this.initState(),this.implementation=implementation||void 0,this.restore=restore,this.originalImplementation=implementation||(()=>{}),new Proxy(this,{get:this.invokeGet,apply:this.invokeFunction,construct:this.invokeClass})}get mock(){return Object.freeze({...this.state})}get original(){return this.originalImplementation}mockClear(){return this.state=this.initState(),this}mockReset(){return this.mockClear(),this.queuedImplementations=[],this}mockRestore(){this.mockReset();let restore=this.restore?.();return typeof restore=="function"?this.implementation=restore:this.implementation=this.originalImplementation,this}getMockImplementation(){return this.implementation}getNextImplementation(){return this.queuedImplementations.length?this.queuedImplementations.shift():this.implementation}mockImplementation(fn){return this.implementation=fn,this}mockImplementationOnce(fn){return this.queuedImplementations.push(fn),this}mockReturnValue(value){return this.mockImplementation(()=>value),this}mockReturnValueOnce(value){return this.mockImplementationOnce(()=>value),this}mockResolvedValue(value){return this.mockImplementation(()=>Promise.resolve(value)),this}mockResolvedValueOnce(value){return this.mockImplementationOnce(()=>Promise.resolve(value)),this}mockRejectedValue(value){return this.mockImplementation(()=>Promise.reject(value)),this}mockRejectedValueOnce(value){return this.mockImplementationOnce(()=>Promise.reject(value)),this}[Symbol.for("nodejs.util.inspect.custom")](){return`<Mock Constructor ${this.name}>`}initState(){return{calls:[],results:[],lastCall:void 0,contexts:[],instances:[],invocationCallOrder:[]}}invoke(thisArg,args){let thisContext=thisArg,impl=this.getNextImplementation(),argsArray=args;typeof impl=="function"&&(impl.__boundArgs&&argsArray.unshift(...impl.__boundArgs),impl.__boundThis&&(thisContext=impl.__boundThis)),this.state.calls.push(argsArray),this.state.contexts.push(thisContext),this.state.invocationCallOrder.push(this.state.invocationCallOrder.length+1);let result,index=this.state.results.push({value:void 0,type:"incomplete"})-1;if(impl)try{result={type:"return",value:impl.call(void 0,...args)}}catch(error2){result={value:error2,type:"throw"}}else result={type:"return",value:void 0};return this.state.lastCall=args,this.state.results[index]=result,result.value}invokeGet(target,property){return Reflect.has(target,property)?Reflect.get(target,property):Reflect.get(target.originalImplementation,property)}invokeClass(target,argArray,newTarget){let result=target.invoke.call(target,newTarget,argArray),isClassInstance=typeof result=="object"&&result!==null&&"constructor"in result;return target.state.instances.push(isClassInstance?result:newTarget),typeof result=="object"?result:newTarget}invokeFunction(target,thisArg,argumentsList){return target.state.instances.push(thisArg),target.invoke.call(target,thisArg,argumentsList)}};var SINGLETONS=new Map,INJECTABLES=new Map;function Injectable(options){return function(target){INJECTABLES.set(target,options||{})}}__name(Injectable,"Injectable");function inject(token,...args){if(SINGLETONS.has(token))return SINGLETONS.get(token);let metadata=INJECTABLES.get(token);if(!metadata)throw new Error(`Cannot inject ${token.name} \u2013 not marked @Injectable`);let instance=metadata.factory?metadata.factory(...args):new token(...args);return metadata?.scope==="singleton"&&SINGLETONS.set(token,instance),instance}__name(inject,"inject");import{serializeError as serializeError2}from"@remotex-labs/xjet-expect";import{serializeError}from"@remotex-labs/xjet-expect";import{Struct}from"@remotex-labs/xstruct";var invocationSchema=new Struct({line:"UInt32LE",column:"UInt32LE",source:"string"}),headerSchema=new Struct({kind:"UInt8:4",suiteId:{type:"string",size:14},runnerId:{type:"string",size:14},timestamp:"string"}),logSchema=new Struct({level:"UInt8",message:{type:"string",lengthType:"UInt32LE"},ancestry:{type:"string",lengthType:"UInt32LE"},invocation:invocationSchema}),errorSchema=new Struct({error:{type:"string",lengthType:"UInt32LE"}}),statusSchema=new Struct({type:"UInt8:5",todo:"UInt8:1",skipped:"UInt8:1",duration:"UInt32LE",ancestry:{type:"string",lengthType:"UInt32LE"},description:{type:"string",lengthType:"UInt32LE"}}),eventsSchema=new Struct({type:"UInt8:5",passed:"UInt8:1",duration:"UInt32LE",ancestry:{type:"string",lengthType:"UInt32LE"},description:{type:"string",lengthType:"UInt32LE"},errors:{type:"string",lengthType:"UInt32LE"}});var PacketSchemas={1:logSchema,2:errorSchema,3:statusSchema,4:eventsSchema};function encodePacket(kind,data){let schema=PacketSchemas[kind];if(!schema)throw new Error(`Invalid schema kind: ${kind}`);let header={kind,suiteId:globalThis?.__XJET?.runtime?.suiteId??"",runnerId:globalThis?.__XJET?.runtime.runnerId??"",timestamp:new Date().toISOString()};return Buffer.concat([headerSchema.toBuffer(header),schema.toBuffer(data)])}__name(encodePacket,"encodePacket");function encodeErrorSchema(error2,suiteId,runnerId){let header=headerSchema.toBuffer({kind:2,suiteId:suiteId??"",runnerId:runnerId??"",timestamp:new Date().toISOString()}),dataBuffer=errorSchema.toBuffer({error:JSON.stringify(serializeError(error2))});return Buffer.concat([header,dataBuffer])}__name(encodeErrorSchema,"encodeErrorSchema");function emitStatus(type,notification={}){dispatch(encodePacket(3,{type,todo:notification?.todo,skipped:notification?.skipped,duration:notification?.duration,ancestry:notification?.ancestry?.join(","),description:notification?.description}))}__name(emitStatus,"emitStatus");function emitEvent(type,notification){let stringErrors=notification.errors?.map(error2=>serializeError2(error2))||[];dispatch(encodePacket(4,{type,errors:stringErrors.length>0?JSON.stringify(stringErrors):"",ancestry:notification.ancestry.join(""),duration:notification.duration,description:notification.description}))}__name(emitEvent,"emitEvent");var LogLevel=(LogLevel2=>(LogLevel2[LogLevel2.Silent=0]="Silent",LogLevel2[LogLevel2.Error=1]="Error",LogLevel2[LogLevel2.Warn=2]="Warn",LogLevel2[LogLevel2.Info=3]="Info",LogLevel2[LogLevel2.Debug=4]="Debug",LogLevel2))(LogLevel||{});var DescribeModel=class{constructor(description="",describeOptions={skip:!1,only:!1}){this.description=description;this.describeOptions=describeOptions}static{__name(this,"DescribeModel")}ancestry=[];testsStack=[];describesStack=[];startTime=0;hooks={afterAll:[],afterEach:[],beforeAll:[],beforeEach:[]};get options(){return this.describeOptions}get tests(){return[...this.testsStack,...this.describesStack.flatMap(child=>child.tests)]}addHook(type,hook){let hookArray=this.hooks[type];if(!hookArray)throw new Error(`Invalid hook type: ${type}`);hookArray.push(hook)}addTest(test){test&&(test.setAncestry(this.ancestry),this.description&&test.setAncestry([this.description]),test.applyExecutionFlags(this.options.skip,this.options.only),this.testsStack.push(test))}addDescribe(describe){describe&&(describe.inheritFromParentDescribe(this),this.describesStack.push(describe))}async run(context){this.startTime=Date.now(),this.notifyDescribeStatus(this.options.skip);let afterAllErrorsEmpty=!context.afterAllErrors?.length,beforeAllErrorsEmpty=!context.beforeAllErrors?.length;try{context.beforeAllErrors?.length||await this.executeHooks("beforeAll",context);for(let test of this.shuffleTests(this.testsStack)){if(context.hasError)return;await test.run(context,this.executeHooks.bind(this))}for(let describe of this.describesStack){if(context.hasError)return;await describe.run(context)}await this.executeHooks("afterAll",context),context.afterAllErrors?.length?this.notifyDescribeFailure(context.afterAllErrors):this.notifyDescribeAction()}catch(error2){this.notifyDescribeFailure([error2,...context.afterAllErrors]),globalThis.__XJET?.runtime.bail&&(context.hasError=!0)}finally{afterAllErrorsEmpty&&(context.afterAllErrors=[]),beforeAllErrorsEmpty&&(context.beforeAllErrors=[])}}inheritFromParentDescribe(parent){this.ancestry.push(...parent.ancestry),this.hooks.beforeEach=[...parent.hooks.beforeEach,...this.hooks.beforeEach],this.hooks.afterEach=[...parent.hooks.afterEach,...this.hooks.afterEach],parent.description&&this.ancestry.push(parent.description),parent.options.skip&&(this.describeOptions.skip=!0),parent.options.only&&(this.describeOptions.only=!0)}async executeHooks(type,context){if(!this.options.skip){context.beforeAllErrors=context.beforeAllErrors||[],context.afterAllErrors=context.afterAllErrors||[];for(let hook of this.hooks[type])try{await hook.run(context)}catch(error2){await this.handleHookError(type,error2,context)}}}async handleHookError(type,error2,context){if(type==="beforeAll")context.beforeAllErrors.push(error2);else if(type==="afterAll")context.afterAllErrors.push(error2);else throw error2}getExecutionDuration(){return this.startTime===0?0:Date.now()-this.startTime}notifyDescribeStatus(skip=!1){emitStatus(2,{skipped:skip,ancestry:this.ancestry,description:this.description})}notifyDescribeAction(errors=[]){emitEvent(2,{errors,ancestry:this.ancestry,description:this.description,duration:this.getExecutionDuration()})}notifyDescribeFailure(errors){errors?.length&&this.notifyDescribeAction(errors)}shuffleTests(testsToShuffle){if(!(globalThis.__XJET?.runtime.randomize??!1)||testsToShuffle.length<=1)return testsToShuffle;let length=testsToShuffle.length;for(let i=length-1;i>0;i--){let j=Math.floor(Math.random()*(i+1));[testsToShuffle[i],testsToShuffle[j]]=[testsToShuffle[j],testsToShuffle[i]]}return testsToShuffle}};var ExecutionError=class extends Error{static{__name(this,"ExecutionError")}constructor(message){super(message),this.name="xJetExecutionError"}toJSON(){let json={};for(let key of Object.keys(this)){let value=this[key];value&&(json[key]=value)}return json.name=this.name,json.stack=this.stack,json.message=this.message,json}};var _SuiteState_decorators,_init;_SuiteState_decorators=[Injectable({scope:"singleton"})];var _SuiteState=class _SuiteState{static{__name(this,"SuiteState")}onlyMode=!1;currentDescribe;currentTest;hasTests=!1;rootDescribe;filterRegexChain=[];constructor(){this.rootDescribe=new DescribeModel,this.currentDescribe=this.rootDescribe,Array.isArray(__XJET?.runtime.filter)&&__XJET.runtime.filter.length>0&&(this.onlyMode=!0,this.filterRegexChain=__XJET.runtime.filter.map(part=>new RegExp(`^${part}$`)))}static matchesFilter(path,filter){if(filter.length>path.length)return!1;let offset=path.length-filter.length;return filter.every((re,i)=>re.test(path[offset+i]))}get isOnlyMode(){return this.onlyMode}get root(){return this.rootDescribe}get describe(){return this.currentDescribe}get test(){return this.currentTest}set test(test){this.currentTest=test}async run(context){try{let time=Date.now();if(emitStatus(4),!this.hasTests)throw new ExecutionError("Your test suite must contain at least one test");await this.root.run(context),emitStatus(3,{duration:Date.now()-time})}catch(e){dispatch(encodeErrorSchema(e,__XJET.runtime.suiteId,__XJET.runtime.runnerId))}}addDescribe(description,describeFn,flags={},describeArgs=[]){let options={skip:!1,only:!1,...flags};if(options.only&&(this.onlyMode=!0),this.filterRegexChain.length>0){let fullPath=[...this.currentDescribe.ancestry,this.currentDescribe.description,description];_SuiteState.matchesFilter(fullPath,this.filterRegexChain)&&(options.only=!0)}let newDescribe=new DescribeModel(description,options);this.currentDescribe.addDescribe(newDescribe);let previousDescribe=this.currentDescribe;this.currentDescribe=newDescribe;try{describeFn.apply({},describeArgs)}finally{this.currentDescribe=previousDescribe}}addTest(test){if(this.hasTests=!0,test.options.only&&(this.onlyMode=!0),this.currentDescribe.addTest(test),this.filterRegexChain.length>0){let fullPath=[...test.ancestry,test.description];_SuiteState.matchesFilter(fullPath,this.filterRegexChain)&&(test.options.only=!0)}}};_init=__decoratorStart(null),_SuiteState=__decorateElement(_init,0,"SuiteState",_SuiteState_decorators,_SuiteState),__runInitializers(_init,1,_SuiteState);var SuiteState=_SuiteState;import{serialize}from"@remotex-labs/xjet-expect";import{parseErrorStack}from"@remotex-labs/xmap/parser.component";function getInvocationLocation(position=2){let stack=parseErrorStack(new Error).stack[position];if(stack?.line&&stack?.column&&stack?.fileName)return{line:stack.line,column:stack.column,source:stack.fileName}}__name(getInvocationLocation,"getInvocationLocation");function getTrimmedStackString(position=2){let err=new Error;return err.stack?err.stack.split(`
1
+ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __knownSymbol=(name,symbol)=>(symbol=Symbol[name])?symbol:Symbol.for("Symbol."+name),__typeError=msg=>{throw TypeError(msg)};var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0}),__require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __decoratorStart=base=>[,,,__create(base?.[__knownSymbol("metadata")]??null)],__decoratorStrings=["class","method","getter","setter","accessor","field","value","get","set"],__expectFn=fn=>fn!==void 0&&typeof fn!="function"?__typeError("Function expected"):fn,__decoratorContext=(kind,name,done,metadata,fns)=>({kind:__decoratorStrings[kind],name,metadata,addInitializer:fn=>done._?__typeError("Already initialized"):fns.push(__expectFn(fn||null))}),__decoratorMetadata=(array,target)=>__defNormalProp(target,__knownSymbol("metadata"),array[3]),__runInitializers=(array,flags,self,value)=>{for(var i=0,fns=array[flags>>1],n=fns&&fns.length;i<n;i++)flags&1?fns[i].call(self):value=fns[i].call(self,value);return value},__decorateElement=(array,flags,name,decorators,target,extra)=>{var fn,it,done,ctx,access,k=flags&7,s=!!(flags&8),p=!!(flags&16),j=k>3?array.length+1:k?s?1:2:0,key=__decoratorStrings[k+5],initializers=k>3&&(array[j-1]=[]),extraInitializers=array[j]||(array[j]=[]),desc=k&&(!p&&!s&&(target=target.prototype),k<5&&(k>3||!p)&&__getOwnPropDesc(k<4?target:{get[name](){return __privateGet(this,extra)},set[name](x){return __privateSet(this,extra,x)}},name));k?p&&k<4&&__name(extra,(k>2?"set ":k>1?"get ":"")+name):__name(target,name);for(var i=decorators.length-1;i>=0;i--)ctx=__decoratorContext(k,name,done={},array[3],extraInitializers),k&&(ctx.static=s,ctx.private=p,access=ctx.access={has:p?x=>__privateIn(target,x):x=>name in x},k^3&&(access.get=p?x=>(k^1?__privateGet:__privateMethod)(x,target,k^4?extra:desc.get):x=>x[name]),k>2&&(access.set=p?(x,y)=>__privateSet(x,target,y,k^4?extra:desc.set):(x,y)=>x[name]=y)),it=(0,decorators[i])(k?k<4?p?extra:desc[key]:k>4?void 0:{get:desc.get,set:desc.set}:target,ctx),done._=1,k^4||it===void 0?__expectFn(it)&&(k>4?initializers.unshift(it):k?p?extra=it:desc[key]=it:target=it):typeof it!="object"||it===null?__typeError("Object expected"):(__expectFn(fn=it.get)&&(desc.get=fn),__expectFn(fn=it.set)&&(desc.set=fn),__expectFn(fn=it.init)&&initializers.unshift(fn));return k||__decoratorMetadata(array,target),desc&&__defProp(target,name,desc),p?k^4?extra:desc:target};var __accessCheck=(obj,member,msg)=>member.has(obj)||__typeError("Cannot "+msg),__privateIn=(member,obj)=>Object(obj)!==obj?__typeError('Cannot use the "in" operator on this value'):member.has(obj),__privateGet=(obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj));var __privateSet=(obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value),__privateMethod=(obj,member,method)=>(__accessCheck(obj,member,"access private method"),method);if(__require){let original=__require,fn=__name(moduleName=>{let resolvedPath=original.resolve(moduleName),exports=original(moduleName),resolved=original.cache[resolvedPath];if(!resolved||resolved.internal)return exports;let result;return typeof resolved.exports=="function"?result=resolved.exports:typeof resolved.exports=="object"&&resolved.exports!==null?result={...resolved.exports}:result=resolved.exports,resolved.exports=result,resolved.internal=!0,result},"fn");Object.assign(fn,original),globalThis.require=fn}import{xExpect}from"@remotex-labs/xjet-expect";var DEFAULT_MOCK_NAME="xJet.mock()",MockState=class extends Function{static{__name(this,"MockState")}static mocks=new Set;name;xJetMock=!0;state;queuedImplementations=[];implementation;originalImplementation;restore;constructor(implementation,restore,name){return super(),this.name=name??DEFAULT_MOCK_NAME,this.state=this.initState(),this.implementation=implementation||void 0,this.restore=restore,this.originalImplementation=implementation||(()=>{}),new Proxy(this,{get:this.invokeGet,apply:this.invokeFunction,construct:this.invokeClass})}get mock(){return Object.freeze({...this.state})}get original(){return this.originalImplementation}mockClear(){return this.state=this.initState(),this}mockReset(){return this.mockClear(),this.queuedImplementations=[],this}mockRestore(){this.mockReset();let restore=this.restore?.();return typeof restore=="function"?this.implementation=restore:this.implementation=this.originalImplementation,this}getMockImplementation(){return this.implementation}getNextImplementation(){return this.queuedImplementations.length?this.queuedImplementations.shift():this.implementation}mockImplementation(fn){return this.implementation=fn,this}mockImplementationOnce(fn){return this.queuedImplementations.push(fn),this}mockReturnValue(value){return this.mockImplementation(()=>value),this}mockReturnValueOnce(value){return this.mockImplementationOnce(()=>value),this}mockResolvedValue(value){return this.mockImplementation(()=>Promise.resolve(value)),this}mockResolvedValueOnce(value){return this.mockImplementationOnce(()=>Promise.resolve(value)),this}mockRejectedValue(value){return this.mockImplementation(()=>Promise.reject(value)),this}mockRejectedValueOnce(value){return this.mockImplementationOnce(()=>Promise.reject(value)),this}[Symbol.for("nodejs.util.inspect.custom")](){return`<Mock Constructor ${this.name}>`}initState(){return{calls:[],results:[],lastCall:void 0,contexts:[],instances:[],invocationCallOrder:[]}}invoke(thisArg,args){let thisContext=thisArg,impl=this.getNextImplementation(),argsArray=args;typeof impl=="function"&&(impl.__boundArgs&&argsArray.unshift(...impl.__boundArgs),impl.__boundThis&&(thisContext=impl.__boundThis)),this.state.calls.push(argsArray),this.state.contexts.push(thisContext),this.state.invocationCallOrder.push(this.state.invocationCallOrder.length+1);let result,index=this.state.results.push({value:void 0,type:"incomplete"})-1;if(impl)try{result={type:"return",value:impl.call(void 0,...args)}}catch(error2){result={value:error2,type:"throw"}}else result={type:"return",value:void 0};return this.state.lastCall=args,this.state.results[index]=result,result.value}invokeGet(target,property){return Reflect.has(target,property)?Reflect.get(target,property):Reflect.get(target.originalImplementation,property)}invokeClass(target,argArray,newTarget){let result=target.invoke.call(target,newTarget,argArray),isClassInstance=typeof result=="object"&&result!==null&&"constructor"in result;return target.state.instances.push(isClassInstance?result:newTarget),typeof result=="object"?result:newTarget}invokeFunction(target,thisArg,argumentsList){return target.state.instances.push(thisArg),target.invoke.call(target,thisArg,argumentsList)}};var SINGLETONS=new Map,INJECTABLES=new Map;function Injectable(options){return function(target){INJECTABLES.set(target,options||{})}}__name(Injectable,"Injectable");function inject(token,...args){if(SINGLETONS.has(token))return SINGLETONS.get(token);let metadata=INJECTABLES.get(token);if(!metadata)throw new Error(`Cannot inject ${token.name} \u2013 not marked @Injectable`);let instance=metadata.factory?metadata.factory(...args):new token(...args);return metadata?.scope==="singleton"&&SINGLETONS.set(token,instance),instance}__name(inject,"inject");import{serializeError as serializeError2}from"@remotex-labs/xjet-expect";import{serializeError}from"@remotex-labs/xjet-expect";import{Struct}from"@remotex-labs/xstruct";var invocationSchema=new Struct({line:"UInt32LE",column:"UInt32LE",source:"string"}),headerSchema=new Struct({kind:"UInt8:4",suiteId:{type:"string",size:14},runnerId:{type:"string",size:14},timestamp:"string"}),logSchema=new Struct({level:"UInt8",message:{type:"string",lengthType:"UInt32LE"},ancestry:{type:"string",lengthType:"UInt32LE"},invocation:invocationSchema}),errorSchema=new Struct({error:{type:"string",lengthType:"UInt32LE"}}),statusSchema=new Struct({type:"UInt8:5",todo:"UInt8:1",skipped:"UInt8:1",duration:"UInt32LE",ancestry:{type:"string",lengthType:"UInt32LE"},description:{type:"string",lengthType:"UInt32LE"}}),eventsSchema=new Struct({type:"UInt8:5",passed:"UInt8:1",duration:"UInt32LE",ancestry:{type:"string",lengthType:"UInt32LE"},description:{type:"string",lengthType:"UInt32LE"},errors:{type:"string",lengthType:"UInt32LE"}});var PacketSchemas={1:logSchema,2:errorSchema,3:statusSchema,4:eventsSchema};function encodePacket(kind,data){let schema=PacketSchemas[kind];if(!schema)throw new Error(`Invalid schema kind: ${kind}`);let header={kind,suiteId:globalThis?.__XJET?.runtime?.suiteId??"",runnerId:globalThis?.__XJET?.runtime.runnerId??"",timestamp:new Date().toISOString()};return Buffer.concat([headerSchema.toBuffer(header),schema.toBuffer(data)])}__name(encodePacket,"encodePacket");function encodeErrorSchema(error2,suiteId,runnerId){let header=headerSchema.toBuffer({kind:2,suiteId:suiteId??"",runnerId:runnerId??"",timestamp:new Date().toISOString()}),dataBuffer=errorSchema.toBuffer({error:JSON.stringify(serializeError(error2))});return Buffer.concat([header,dataBuffer])}__name(encodeErrorSchema,"encodeErrorSchema");function emitStatus(type,notification={}){dispatch(encodePacket(3,{type,todo:notification?.todo,skipped:notification?.skipped,duration:notification?.duration,ancestry:notification?.ancestry?.join(","),description:notification?.description}))}__name(emitStatus,"emitStatus");function emitEvent(type,notification){let stringErrors=notification.errors?.map(error2=>serializeError2(error2))||[];dispatch(encodePacket(4,{type,errors:stringErrors.length>0?JSON.stringify(stringErrors):"",ancestry:notification.ancestry.join(""),duration:notification.duration,description:notification.description}))}__name(emitEvent,"emitEvent");var LogLevel=(LogLevel2=>(LogLevel2[LogLevel2.Silent=0]="Silent",LogLevel2[LogLevel2.Error=1]="Error",LogLevel2[LogLevel2.Warn=2]="Warn",LogLevel2[LogLevel2.Info=3]="Info",LogLevel2[LogLevel2.Debug=4]="Debug",LogLevel2))(LogLevel||{});var DescribeModel=class{constructor(description="",describeOptions={skip:!1,only:!1}){this.description=description;this.describeOptions=describeOptions}static{__name(this,"DescribeModel")}ancestry=[];testsStack=[];describesStack=[];startTime=0;hooks={afterAll:[],afterEach:[],beforeAll:[],beforeEach:[]};get options(){return this.describeOptions}get tests(){return[...this.testsStack,...this.describesStack.flatMap(child=>child.tests)]}addHook(type,hook){let hookArray=this.hooks[type];if(!hookArray)throw new Error(`Invalid hook type: ${type}`);hookArray.push(hook)}addTest(test){test&&(test.setAncestry(this.ancestry),this.description&&test.setAncestry([this.description]),test.applyExecutionFlags(this.options.skip,this.options.only),this.testsStack.push(test))}addDescribe(describe){describe&&(describe.inheritFromParentDescribe(this),this.describesStack.push(describe))}async run(context){this.startTime=Date.now(),this.notifyDescribeStatus(this.options.skip);let afterAllErrorsEmpty=!context.afterAllErrors?.length,beforeAllErrorsEmpty=!context.beforeAllErrors?.length;try{context.beforeAllErrors?.length||await this.executeHooks("beforeAll",context);for(let test of this.shuffleTests(this.testsStack)){if(context.hasError)return;await test.run(context,this.executeHooks.bind(this))}for(let describe of this.describesStack){if(context.hasError)return;await describe.run(context)}await this.executeHooks("afterAll",context),context.afterAllErrors?.length?this.notifyDescribeFailure(context.afterAllErrors):this.notifyDescribeAction()}catch(error2){this.notifyDescribeFailure([error2,...context.afterAllErrors]),globalThis.__XJET?.runtime.bail&&(context.hasError=!0)}finally{afterAllErrorsEmpty&&(context.afterAllErrors=[]),beforeAllErrorsEmpty&&(context.beforeAllErrors=[])}}inheritFromParentDescribe(parent){this.ancestry.push(...parent.ancestry),this.hooks.beforeEach=[...parent.hooks.beforeEach,...this.hooks.beforeEach],this.hooks.afterEach=[...parent.hooks.afterEach,...this.hooks.afterEach],parent.description&&this.ancestry.push(parent.description),parent.options.skip&&(this.describeOptions.skip=!0),parent.options.only&&(this.describeOptions.only=!0)}async executeHooks(type,context){if(!this.options.skip){context.beforeAllErrors=context.beforeAllErrors||[],context.afterAllErrors=context.afterAllErrors||[];for(let hook of this.hooks[type])try{await hook.run(context)}catch(error2){await this.handleHookError(type,error2,context)}}}async handleHookError(type,error2,context){if(type==="beforeAll")context.beforeAllErrors.push(error2);else if(type==="afterAll")context.afterAllErrors.push(error2);else throw error2}getExecutionDuration(){return this.startTime===0?0:Date.now()-this.startTime}notifyDescribeStatus(skip=!1){emitStatus(2,{skipped:skip,ancestry:this.ancestry,description:this.description})}notifyDescribeAction(errors=[]){emitEvent(2,{errors,ancestry:this.ancestry,description:this.description,duration:this.getExecutionDuration()})}notifyDescribeFailure(errors){errors?.length&&this.notifyDescribeAction(errors)}shuffleTests(testsToShuffle){if(!(globalThis.__XJET?.runtime.randomize??!1)||testsToShuffle.length<=1)return testsToShuffle;let length=testsToShuffle.length;for(let i=length-1;i>0;i--){let j=Math.floor(Math.random()*(i+1));[testsToShuffle[i],testsToShuffle[j]]=[testsToShuffle[j],testsToShuffle[i]]}return testsToShuffle}};var ExecutionError=class extends Error{static{__name(this,"ExecutionError")}constructor(message){super(message),this.name="xJetExecutionError"}toJSON(){let json={};for(let key of Object.keys(this)){let value=this[key];value&&(json[key]=value)}return json.name=this.name,json.stack=this.stack,json.message=this.message,json}};var _SuiteState_decorators,_init;_SuiteState_decorators=[Injectable({scope:"singleton"})];var _SuiteState=class _SuiteState{static{__name(this,"SuiteState")}onlyMode=!1;currentDescribe;currentTest;hasTests=!1;rootDescribe;filterRegexChain=[];constructor(){this.rootDescribe=new DescribeModel,this.currentDescribe=this.rootDescribe,Array.isArray(__XJET?.runtime.filter)&&__XJET.runtime.filter.length>0&&(this.onlyMode=!0,this.filterRegexChain=__XJET.runtime.filter.map(part=>new RegExp(`^${part}$`)))}static matchesFilter(path,filter){if(filter.length>path.length)return!1;let offset=path.length-filter.length;return filter.every((re,i)=>re.test(path[offset+i]))}get isOnlyMode(){return this.onlyMode}get root(){return this.rootDescribe}get describe(){return this.currentDescribe}get test(){return this.currentTest}set test(test){this.currentTest=test}async run(context){try{let time=Date.now();if(emitStatus(4),!this.hasTests)throw new ExecutionError("Your test suite must contain at least one test");await this.root.run(context),emitStatus(3,{duration:Date.now()-time})}catch(e){dispatch(encodeErrorSchema(e,__XJET.runtime.suiteId,__XJET.runtime.runnerId))}finally{xJet.restoreAllMocks()}}addDescribe(description,describeFn,flags={},describeArgs=[]){let options={skip:!1,only:!1,...flags};if(options.only&&(this.onlyMode=!0),this.filterRegexChain.length>0){let fullPath=[...this.currentDescribe.ancestry,this.currentDescribe.description,description];_SuiteState.matchesFilter(fullPath,this.filterRegexChain)&&(options.only=!0)}let newDescribe=new DescribeModel(description,options);this.currentDescribe.addDescribe(newDescribe);let previousDescribe=this.currentDescribe;this.currentDescribe=newDescribe;try{describeFn.apply({},describeArgs)}finally{this.currentDescribe=previousDescribe}}addTest(test){if(this.hasTests=!0,test.options.only&&(this.onlyMode=!0),this.currentDescribe.addTest(test),this.filterRegexChain.length>0){let fullPath=[...test.ancestry,test.description];_SuiteState.matchesFilter(fullPath,this.filterRegexChain)&&(test.options.only=!0)}}};_init=__decoratorStart(null),_SuiteState=__decorateElement(_init,0,"SuiteState",_SuiteState_decorators,_SuiteState),__runInitializers(_init,1,_SuiteState);var SuiteState=_SuiteState;import{serialize}from"@remotex-labs/xjet-expect";import{parseErrorStack}from"@remotex-labs/xmap/parser.component";function getInvocationLocation(position=2){let stack=parseErrorStack(new Error).stack[position];if(stack?.line&&stack?.column&&stack?.fileName)return{line:stack.line,column:stack.column,source:stack.fileName}}__name(getInvocationLocation,"getInvocationLocation");function getTrimmedStackString(position=2){let err=new Error;return err.stack?err.stack.split(`
2
2
  `).slice(position+1).join(`
3
3
  `):""}__name(getTrimmedStackString,"getTrimmedStackString");function createLogHandler(type){return function(...args){let parent=inject(SuiteState).test;parent||(parent=inject(SuiteState).describe);let context=[...parent?.ancestry??[],parent?.description].join(","),formattedArgs=args.map(data=>serialize(data).join(`
4
- `)).join(" "),location=getInvocationLocation();dispatch(encodePacket(1,{level:LogLevel[type],message:formattedArgs,ancestry:context??"",invocation:location}))}}__name(createLogHandler,"createLogHandler");var log=createLogHandler("Info"),info=createLogHandler("Info"),warn=createLogHandler("Warn"),error=createLogHandler("Error"),debug=createLogHandler("Debug");function deepSearchObject(target,element,key,maxDepth=3){let visited=new WeakSet;function search(target2,depth){if(depth>maxDepth||target2==null||typeof target2!="object"&&typeof target2!="function"||visited.has(target2))return null;if(visited.add(target2),key&&key in target2)return{parent:target2,key};for(let[prop,value]of Object.entries(target2)){if(Object.is(value,element))return{parent:target2,key:prop};if(value&&(typeof value=="object"||typeof value=="function")){let found=search(value,depth+1);if(found)return found}}return null}return __name(search,"search"),search(target,0)}__name(deepSearchObject,"deepSearchObject");function getOwnProperty(parent,key){let method=Reflect.get(parent,key),descriptor=Object.getOwnPropertyDescriptor(parent,key);return descriptor?.get&&!descriptor.configurable&&"default"in parent&&Reflect.get(parent.default,key)===method?{parent:parent.default,key}:{parent,key}}__name(getOwnProperty,"getOwnProperty");function mockDescriptorProperty(target,key){let original=Reflect.get(target,key),originalDescriptor=Object.getOwnPropertyDescriptor(target,key)||{},mockInstance=new MockState(()=>original,()=>{Reflect.set(target,key,originalDescriptor.value),Object.defineProperty(target,key,originalDescriptor)},"xJet.spyOn()");return MockState.mocks.add(new WeakRef(mockInstance)),Object.defineProperty(target,key,{get(){return mockInstance.apply(this,[])},set(value){return mockInstance.mockImplementation(()=>value),mockInstance.apply(this,[value])}}),mockInstance}__name(mockDescriptorProperty,"mockDescriptorProperty");function fnImplementation(implementation,restore){return new MockState(implementation,restore,"xJet.fn()")}__name(fnImplementation,"fnImplementation");function mockImplementation(element,implementation){if(!element)throw new ExecutionError("xJet.mock element is not defined");if(typeof element=="function"&&element.xJetMock)return element;let findObject=deepSearchObject(globalThis,element,element?.name);if(!findObject)throw new ExecutionError(`Unable to mock this item: it was not found in any global object.
5
- If you are trying to mock a Proxy object, please use xJet.spyOn() instead.`);let{parent,key}=getOwnProperty(findObject.parent,findObject.key),method=Reflect.get(parent,key);if(typeof method=="function"&&method.prototype&&!Object.getOwnPropertyDescriptor(method,"prototype")?.writable){let mock2=new MockState((...args)=>new method(...args),()=>{Reflect.set(parent,key,method)});return Reflect.set(parent,key,mock2),MockState.mocks.add(new WeakRef(mock2)),implementation&&mock2.mockImplementation(implementation),mock2}if(typeof method=="function"){let mock2=new MockState(method,()=>{Reflect.set(parent,key,method)});return Reflect.set(parent,key,mock2),MockState.mocks.add(new WeakRef(mock2)),implementation&&mock2.mockImplementation(implementation),mock2}let mock=mockDescriptorProperty(parent,key);return implementation&&mock.mockImplementation(implementation),mock}__name(mockImplementation,"mockImplementation");function isProxyProperty(obj,key){return!(key in obj)&&Reflect.get(obj,key)!==void 0}__name(isProxyProperty,"isProxyProperty");function isMockProxy(value){return value&&typeof value=="object"&&"__isMockProxy__"in value}__name(isMockProxy,"isMockProxy");function createMockProxy(target){let state={mocks:new Map,customGetter:null},handler={get(_target,prop,receiver){return prop==="__isMockProxy__"?!0:prop==="__MockMap__"?state:state.customGetter?state.customGetter(target,prop,receiver):state.mocks.has(prop)?state.mocks.get(prop):Reflect.get(target,prop,receiver)}};return new Proxy({},handler)}__name(createMockProxy,"createMockProxy");function spyOnProxyGet(target,prop){let found=deepSearchObject(globalThis,target);if(!found)throw new Error("xJet.spyOn item is not part of any global object");if(!isMockProxy(target)){let{parent,key}=getOwnProperty(found.parent,found.key),method=Reflect.get(parent,key);Reflect.set(parent,key,createMockProxy(method)),target=Reflect.get(parent,key)}let proxy=target,mockState=new MockState(target[prop],()=>{proxy.__MockMap__?.mocks.delete(prop)},"xJet.spyOn(Proxy#get)");return proxy.__MockMap__?.mocks.set(prop,mockState),mockState}__name(spyOnProxyGet,"spyOnProxyGet");function spyOnImplementation(target,prop){if(target==null||typeof target!="object"&&typeof target!="function")throw new ExecutionError("Target must be an object or function");if(prop===null)throw new ExecutionError("Spied property/method key is required");if(isProxyProperty(target,prop))return spyOnProxyGet(target,prop);let{parent,key}=getOwnProperty(target,prop);if(!(key in parent))throw new ExecutionError(`Property/method '${String(key)}' does not exist on target`);let method=Reflect.get(parent,key);if(!method)throw new Error(`Property '${String(key)}' does not exist in the provided object`);if(method.xJetMock)return method;let descriptor=Object.getOwnPropertyDescriptor(target,key);if(typeof method!="function"||descriptor?.get)return mockDescriptorProperty(target,key);let fn=method,protoDesc=Object.getOwnPropertyDescriptor(fn,"prototype");fn.prototype&&protoDesc&&!protoDesc.writable&&(fn=__name((...args)=>new method(...args),"fn"));let mockState=new MockState(fn,()=>{Reflect.set(target,key,method)},"xJet.spyOn()");return MockState.mocks.add(new WeakRef(mockState)),Reflect.set(target,key,mockState),mockState}__name(spyOnImplementation,"spyOnImplementation");var _TimerService_decorators,_init2;_TimerService_decorators=[Injectable({scope:"singleton"})];var TimerService=class{static{__name(this,"TimerService")}timers=new Map;originalDateNow=Date.now;originalSetTimeout=globalThis.setTimeout;originalSetInterval=globalThis.setInterval;originalClearTimeout=globalThis.clearTimeout;originalClearInterval=globalThis.clearInterval;now=0;nextId=1;useFakeTimers(){let setTimeout=__name((cb,delay=0,...args)=>{let id=this.nextId++;return this.timers.set(id,{id,callback:cb,time:this.now+delay,interval:null,args:args??[]}),id},"setTimeout"),setInterval=__name((cb,interval=0)=>{let id=this.nextId++;return this.timers.set(id,{id,callback:cb,time:this.now+interval,interval,args:[]}),id},"setInterval"),clearTimeout=__name(id=>{this.timers.delete(id)},"clearTimeout"),clearInterval=__name(id=>{this.timers.delete(id)},"clearInterval"),global=globalThis;global.setTimeout=setTimeout,global.setInterval=setInterval,global.clearTimeout=clearTimeout,global.clearInterval=clearInterval}useRealTimers(){globalThis.setTimeout=this.originalSetTimeout,globalThis.clearTimeout=this.originalClearTimeout,globalThis.setInterval=this.originalSetInterval,globalThis.clearInterval=this.originalClearInterval,Date.now=this.originalDateNow}advanceTimersByTime(ms){this.now+=ms,this.runDueTimers()}runAllTimers(){for(;this.timers.size>0;)this.now=Math.min(...Array.from(this.timers.values()).map(t=>t.time)),this.runDueTimers()}runOnlyPendingTimers(){let pendingTimers=new Set(this.timers.keys());for(;pendingTimers.size>0;){let nextTimerTimes=Array.from(this.timers.values()).filter(t=>pendingTimers.has(t.id)).map(t=>t.time);if(nextTimerTimes.length===0)break;this.now=Math.min(...nextTimerTimes),this.runDueTimers(pendingTimers);for(let id of pendingTimers)this.timers.has(id)||pendingTimers.delete(id)}}runDueTimers(limitTimers){let executed=!0;for(;executed;){executed=!1;let timers=Array.from(this.timers.values()).sort((a,b)=>a.time-b.time);for(let timer of timers)if(this.timers.has(timer.id)&&!(limitTimers&&!limitTimers.has(timer.id))&&timer.time<=this.now){if(timer.interval!==null)for(;timer.time<=this.now;)timer.callback(),timer.time+=timer.interval;else timer.callback(),this.timers.delete(timer.id);executed=!0}}}};_init2=__decoratorStart(null),TimerService=__decorateElement(_init2,0,"TimerService",_TimerService_decorators,TimerService),__runInitializers(_init2,1,TimerService);function useFakeTimers(){inject(TimerService).useFakeTimers()}__name(useFakeTimers,"useFakeTimers");function useRealTimers(){inject(TimerService).useRealTimers()}__name(useRealTimers,"useRealTimers");function runAllTimers(){inject(TimerService).runAllTimers()}__name(runAllTimers,"runAllTimers");function runOnlyPendingTimers(){inject(TimerService).runOnlyPendingTimers()}__name(runOnlyPendingTimers,"runOnlyPendingTimers");function advanceTimersByTime(ms=0){inject(TimerService).advanceTimersByTime(ms)}__name(advanceTimersByTime,"advanceTimersByTime");var VARIABLE_PATTERN=/\$([#\w.])+/g;function prettyFormat(value){return typeof value=="string"?value:JSON.stringify(value,null,4)}__name(prettyFormat,"prettyFormat");function getValueByPath(data,path){if(!(!path.length||!data))try{return path.reduce((obj,key)=>{if(obj==null||typeof obj!="object")throw new Error("Path traversal failed");return obj[key]},data)}catch{return}}__name(getValueByPath,"getValueByPath");function resolveVariable(token,data,arrayIndex){if(!token||typeof token!="string"||!token.startsWith("$"))return token;if(token==="$#")return String(arrayIndex);let propertyPath=token.slice(1).split("."),resolvedValue=getValueByPath(data,propertyPath);if(resolvedValue==null)return token;if(typeof resolvedValue=="object")try{return JSON.stringify(resolvedValue,(key,value)=>key&&typeof value=="object"?"[Object]":value)}catch{return String(resolvedValue)}return String(resolvedValue)}__name(resolveVariable,"resolveVariable");function interpolateVariables(template,data,arrayIndex){return template.replace(VARIABLE_PATTERN,variableToken=>resolveVariable(variableToken,data,arrayIndex))}__name(interpolateVariables,"interpolateVariables");function printf(description,params,index){let paramIndex=0;return description.includes("$")&&!description.includes("%%")&&(description=interpolateVariables(description,params[0],index)),description.replace(/%([psdifjo#%])/g,(match,format)=>{if(format==="%")return"%";if(format==="#")return String(index);let value=params[paramIndex++];switch(format){case"p":return prettyFormat(value);case"s":return String(value);case"d":return Number(value).toString();case"i":return Math.floor(Number(value)).toString();case"f":return Number(value).toString();case"j":return JSON.stringify(value);case"o":return Object.prototype.toString.call(value);default:return match}})}__name(printf,"printf");function parseTemplate(templateString,inputData){let headings=templateString[0].split("|").map(h=>h.trim());if(headings.length===0||headings.some(h=>h===""))throw new Error("Template string headings must not be empty and should contain pipe delimiters.");if(inputData.length%headings.length!==0)throw new Error("Not enough arguments supplied for given headings.");return Array.from({length:inputData.length/headings.length},(_,rowIndex)=>headings.reduce((acc,heading,columnIndex)=>(acc[heading]=inputData[rowIndex*headings.length+columnIndex],acc),{}))}__name(parseTemplate,"parseTemplate");function each(executor,...args){if(args.length<2)throw new Error("`.each` must be called with at leas 2 argument or Tagged Template Literal.");let cases=args[0]instanceof Array&&args[0].raw!==void 0?parseTemplate(args.shift(),args):args;return(name,blockFn,timeout)=>{cases.forEach((testCase,index)=>{let parseArgs=Array.isArray(testCase)?testCase:[testCase];executor(printf(name,parseArgs,Number(index)),blockFn,parseArgs,timeout)})}}__name(each,"each");var TimeoutError=class extends Error{static{__name(this,"TimeoutError")}constructor(timeout,at,stack=""){super(`Exceeded timeout of ${timeout} ms at ${at}`),Object.setPrototypeOf(this,new.target.prototype),this.name="xJetTimeoutError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="xJetFailingError",stack&&(this.stack=`${this.name}: ${this.message}
4
+ `)).join(" "),location=getInvocationLocation();dispatch(encodePacket(1,{level:LogLevel[type],message:formattedArgs,ancestry:context??"",invocation:location}))}}__name(createLogHandler,"createLogHandler");var log=createLogHandler("Info"),info=createLogHandler("Info"),warn=createLogHandler("Warn"),error=createLogHandler("Error"),debug=createLogHandler("Debug");function deepSearchObject(target,element,key,maxDepth=3){let visited=new WeakSet;function search(target2,depth){if(depth>maxDepth||target2==null||typeof target2!="object"&&typeof target2!="function"||visited.has(target2))return null;if(visited.add(target2),key&&key in target2)return{parent:target2,key};for(let[prop,value]of Object.entries(target2)){if(Object.is(value,element))return{parent:target2,key:prop};if(value&&(typeof value=="object"||typeof value=="function")){let found=search(value,depth+1);if(found)return found}}return null}return __name(search,"search"),search(target,0)}__name(deepSearchObject,"deepSearchObject");function getOwnProperty(parent,key){let method=Reflect.get(parent,key),descriptor=Object.getOwnPropertyDescriptor(parent,key);return descriptor?.get&&!descriptor.configurable&&"default"in parent&&Reflect.get(parent.default,key)===method?{parent:parent.default,key}:{parent,key}}__name(getOwnProperty,"getOwnProperty");function mockDescriptorProperty(target,key){let original=Reflect.get(target,key),originalDescriptor=Object.getOwnPropertyDescriptor(target,key)||{},mockInstance=new MockState(()=>original,()=>{Reflect.set(target,key,originalDescriptor.value),Object.defineProperty(target,key,originalDescriptor)},`xJet.spyOn(${String(key)})`);return MockState.mocks.add(new WeakRef(mockInstance)),Object.defineProperty(target,key,{get(){return mockInstance.apply(this,[])},set(value){return mockInstance.mockImplementation(()=>value),mockInstance.apply(this,[value])}}),mockInstance}__name(mockDescriptorProperty,"mockDescriptorProperty");function fnImplementation(implementation,restore){return new MockState(implementation,restore,"xJet.fn()")}__name(fnImplementation,"fnImplementation");function mockImplementation(element,implementation){if(!element)throw new ExecutionError("xJet.mock element is not defined");if(typeof element=="function"&&element.xJetMock)return element;let findObject=deepSearchObject(globalThis,element,element?.name);if(!findObject)throw new ExecutionError(`Unable to mock this item: it was not found in any global object.
5
+ If you are trying to mock a Proxy object, please use xJet.spyOn() instead.`);let{parent,key}=getOwnProperty(findObject.parent,findObject.key),method=Reflect.get(parent,key);if(typeof method=="function"&&method.prototype&&!Object.getOwnPropertyDescriptor(method,"prototype")?.writable){let mock2=new MockState((...args)=>new method(...args),()=>{Reflect.set(parent,key,method)});return Reflect.set(parent,key,mock2),MockState.mocks.add(new WeakRef(mock2)),implementation&&mock2.mockImplementation(implementation),mock2}if(typeof method=="function"){let mock2=new MockState(method,()=>{Reflect.set(parent,key,method)});return Reflect.set(parent,key,mock2),MockState.mocks.add(new WeakRef(mock2)),implementation&&mock2.mockImplementation(implementation),mock2}let mock=mockDescriptorProperty(parent,key);return implementation&&mock.mockImplementation(implementation),mock}__name(mockImplementation,"mockImplementation");function isProxyProperty(obj,key){return!(key in obj)&&Reflect.get(obj,key)!==void 0}__name(isProxyProperty,"isProxyProperty");function isMockProxy(value){return value&&typeof value=="object"&&"__isMockProxy__"in value}__name(isMockProxy,"isMockProxy");function createMockProxy(target){let state={mocks:new Map,customGetter:null},handler={get(_target,prop,receiver){return prop==="__isMockProxy__"?!0:prop==="__MockMap__"?state:state.customGetter?state.customGetter(target,prop,receiver):state.mocks.has(prop)?state.mocks.get(prop):Reflect.get(target,prop,receiver)}};return new Proxy({},handler)}__name(createMockProxy,"createMockProxy");function spyOnProxyGet(target,prop){let found=deepSearchObject(globalThis,target);if(!found)throw new Error("xJet.spyOn item is not part of any global object");if(!isMockProxy(target)){let{parent,key}=getOwnProperty(found.parent,found.key),method=Reflect.get(parent,key);Reflect.set(parent,key,createMockProxy(method)),target=Reflect.get(parent,key)}let proxy=target,mockState=new MockState(target[prop],()=>{proxy.__MockMap__?.mocks.delete(prop)},"xJet.spyOn(Proxy#get)");return proxy.__MockMap__?.mocks.set(prop,mockState),mockState}__name(spyOnProxyGet,"spyOnProxyGet");function spyOnImplementation(target,prop){if(target==null||typeof target!="object"&&typeof target!="function")throw new ExecutionError("Target must be an object or function");if(prop===null)throw new ExecutionError("Spied property/method key is required");let method=Reflect.get(target,prop);if(method?.xJetMock)return method;if(isProxyProperty(target,prop))return spyOnProxyGet(target,prop);let{parent,key}=getOwnProperty(target,prop);if(!(key in parent))throw new ExecutionError(`Property/method '${String(key)}' does not exist on target`);if(!method)throw new Error(`Property '${String(key)}' does not exist in the provided object`);let descriptor=Object.getOwnPropertyDescriptor(target,key);if(typeof method!="function"||descriptor?.get)return mockDescriptorProperty(target,key);let fn=method,protoDesc=Object.getOwnPropertyDescriptor(fn,"prototype");fn.prototype&&protoDesc&&!protoDesc.writable&&(fn=__name((...args)=>new method(...args),"fn"));let mockState=new MockState(fn,()=>{Reflect.set(target,key,method)},`xJet.spyOn(${String(method.name)})`);return MockState.mocks.add(new WeakRef(mockState)),Reflect.set(target,key,mockState),mockState}__name(spyOnImplementation,"spyOnImplementation");var _TimerService_decorators,_init2;_TimerService_decorators=[Injectable({scope:"singleton"})];var TimerService=class{static{__name(this,"TimerService")}timers=new Map;originalDateNow=Date.now;originalSetTimeout=globalThis.setTimeout;originalSetInterval=globalThis.setInterval;originalClearTimeout=globalThis.clearTimeout;originalClearInterval=globalThis.clearInterval;now=0;nextId=1;useFakeTimers(){let setTimeout=__name((cb,delay=0,...args)=>{let id=this.nextId++;return this.timers.set(id,{id,callback:cb,time:this.now+delay,interval:null,args:args??[]}),id},"setTimeout"),setInterval=__name((cb,interval=0)=>{let id=this.nextId++;return this.timers.set(id,{id,callback:cb,time:this.now+interval,interval,args:[]}),id},"setInterval"),clearTimeout=__name(id=>{this.timers.delete(id)},"clearTimeout"),clearInterval=__name(id=>{this.timers.delete(id)},"clearInterval"),global=globalThis;global.setTimeout=setTimeout,global.setInterval=setInterval,global.clearTimeout=clearTimeout,global.clearInterval=clearInterval}useRealTimers(){this.timers.clear(),globalThis.setTimeout=this.originalSetTimeout,globalThis.clearTimeout=this.originalClearTimeout,globalThis.setInterval=this.originalSetInterval,globalThis.clearInterval=this.originalClearInterval,Date.now=this.originalDateNow}clearAllTimers(){this.timers.clear()}advanceTimersByTime(ms){this.now+=ms,this.runDueTimers()}runAllTimers(){for(;this.timers.size>0;)this.now=Math.min(...Array.from(this.timers.values()).map(t=>t.time)),this.runDueTimers()}runOnlyPendingTimers(){let pendingTimers=new Set(this.timers.keys());for(;pendingTimers.size>0;){let nextTimerTimes=Array.from(this.timers.values()).filter(t=>pendingTimers.has(t.id)).map(t=>t.time);if(nextTimerTimes.length===0)break;this.now=Math.min(...nextTimerTimes),this.runDueTimers(pendingTimers);for(let id of pendingTimers)this.timers.has(id)||pendingTimers.delete(id)}}async runAllTimersAsync(){await Promise.resolve(),this.runAllTimers()}async runOnlyPendingTimersAsync(){await Promise.resolve(),this.runOnlyPendingTimers()}runDueTimers(limitTimers){let executed=!0;for(;executed;){executed=!1;let timers=Array.from(this.timers.values()).sort((a,b)=>a.time-b.time);for(let timer of timers)if(this.timers.has(timer.id)&&!(limitTimers&&!limitTimers.has(timer.id))&&timer.time<=this.now){if(timer.interval!==null)for(;timer.time<=this.now;)timer.callback(),timer.time+=timer.interval;else timer.callback(),this.timers.delete(timer.id);executed=!0}}}};_init2=__decoratorStart(null),TimerService=__decorateElement(_init2,0,"TimerService",_TimerService_decorators,TimerService),__runInitializers(_init2,1,TimerService);function useFakeTimers(){inject(TimerService).useFakeTimers()}__name(useFakeTimers,"useFakeTimers");function useRealTimers(){inject(TimerService).useRealTimers()}__name(useRealTimers,"useRealTimers");function runAllTimers(){inject(TimerService).runAllTimers()}__name(runAllTimers,"runAllTimers");function clearAllTimers(){inject(TimerService).clearAllTimers()}__name(clearAllTimers,"clearAllTimers");function runOnlyPendingTimers(){inject(TimerService).runOnlyPendingTimers()}__name(runOnlyPendingTimers,"runOnlyPendingTimers");function advanceTimersByTime(ms=0){inject(TimerService).advanceTimersByTime(ms)}__name(advanceTimersByTime,"advanceTimersByTime");async function runAllTimersAsync(){await inject(TimerService).runAllTimersAsync()}__name(runAllTimersAsync,"runAllTimersAsync");async function runOnlyPendingTimersAsync(){await inject(TimerService).runOnlyPendingTimersAsync()}__name(runOnlyPendingTimersAsync,"runOnlyPendingTimersAsync");var VARIABLE_PATTERN=/\$([#\w.])+/g;function prettyFormat(value){return typeof value=="string"?value:JSON.stringify(value,null,4)}__name(prettyFormat,"prettyFormat");function getValueByPath(data,path){if(!(!path.length||!data))try{return path.reduce((obj,key)=>{if(obj==null||typeof obj!="object")throw new Error("Path traversal failed");return obj[key]},data)}catch{return}}__name(getValueByPath,"getValueByPath");function resolveVariable(token,data,arrayIndex){if(!token||typeof token!="string"||!token.startsWith("$"))return token;if(token==="$#")return String(arrayIndex);let propertyPath=token.slice(1).split("."),resolvedValue=getValueByPath(data,propertyPath);if(resolvedValue==null)return token;if(typeof resolvedValue=="object")try{return JSON.stringify(resolvedValue,(key,value)=>key&&typeof value=="object"?"[Object]":value)}catch{return String(resolvedValue)}return String(resolvedValue)}__name(resolveVariable,"resolveVariable");function interpolateVariables(template,data,arrayIndex){return template.replace(VARIABLE_PATTERN,variableToken=>resolveVariable(variableToken,data,arrayIndex))}__name(interpolateVariables,"interpolateVariables");function printf(description,params,index){let paramIndex=0;return description.includes("$")&&!description.includes("%%")&&(description=interpolateVariables(description,params[0],index)),description.replace(/%([psdifjo#%])/g,(match,format)=>{if(format==="%")return"%";if(format==="#")return String(index);let value=params[paramIndex++];switch(format){case"p":return prettyFormat(value);case"s":return String(value);case"d":return Number(value).toString();case"i":return Math.floor(Number(value)).toString();case"f":return Number(value).toString();case"j":return JSON.stringify(value);case"o":return Object.prototype.toString.call(value);default:return match}})}__name(printf,"printf");function parseTemplate(templateString,inputData){let headings=templateString[0].split("|").map(h=>h.trim());if(headings.length===0||headings.some(h=>h===""))throw new Error("Template string headings must not be empty and should contain pipe delimiters.");if(inputData.length%headings.length!==0)throw new Error("Not enough arguments supplied for given headings.");return Array.from({length:inputData.length/headings.length},(_,rowIndex)=>headings.reduce((acc,heading,columnIndex)=>(acc[heading]=inputData[rowIndex*headings.length+columnIndex],acc),{}))}__name(parseTemplate,"parseTemplate");function each(executor,...args){if(args.length<2)throw new Error("`.each` must be called with at leas 2 argument or Tagged Template Literal.");let cases=args[0]instanceof Array&&args[0].raw!==void 0?parseTemplate(args.shift(),args):args;return(name,blockFn,timeout)=>{cases.forEach((testCase,index)=>{let parseArgs=Array.isArray(testCase)?testCase:[testCase];executor(printf(name,parseArgs,Number(index)),blockFn,parseArgs,timeout)})}}__name(each,"each");var TimeoutError=class extends Error{static{__name(this,"TimeoutError")}constructor(timeout,at,stack=""){super(`Exceeded timeout of ${timeout} ms at ${at}`),Object.setPrototypeOf(this,new.target.prototype),this.name="xJetTimeoutError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="xJetFailingError",stack&&(this.stack=`${this.name}: ${this.message}
6
6
  ${stack}`)}};async function withTimeout(task,delay,at,stack){let timers=inject(TimerService),taskPromise=typeof task=="function"?Promise.resolve(task()):Promise.resolve(task);if(delay===-1||!timers.originalSetTimeout)return taskPromise;let timeoutId,timeoutPromise=new Promise((_,reject)=>{timeoutId=timers.originalSetTimeout?.(()=>reject(new TimeoutError(delay,at,stack)),delay)});try{return await Promise.race([taskPromise,timeoutPromise])}finally{timers.originalClearTimeout?.(timeoutId)}}__name(withTimeout,"withTimeout");var FailingError=class _FailingError extends ExecutionError{static{__name(this,"FailingError")}constructor(stack){super("Failing test passed even though it was supposed to fail. Remove `.failing` to remove error."),Error.captureStackTrace&&Error.captureStackTrace(this,_FailingError),this.name="xJetFailingError",this.stack=`${this.name}: ${this.message}
7
- ${stack}`}};import{isPromise}from"@remotex-labs/xjet-expect";var TestModel=class{constructor(description,testImplementation,timeoutDuration,testParameters=[],testOptions={}){this.description=description;this.testImplementation=testImplementation;this.timeoutDuration=timeoutDuration;this.testParameters=testParameters;this.testOptions=testOptions}static{__name(this,"TestModel")}ancestry=[];executionLocation="";executionStartTime=0;get options(){return this.testOptions}setExecutionLocation(location){this.executionLocation=location}applyExecutionFlags(skip,only){this.testOptions.skip||=skip,this.testOptions.only||=only}setAncestry(parentTests){this.ancestry.push(...parentTests)}async run(context,runLifecycleHooks,isExclusiveMode=!1){if(inject(SuiteState).test=this,this.executionStartTime=Date.now(),!this.shouldSkipDueToSetupErrors(context)&&!this.determineSkipAction(isExclusiveMode))try{await this.executeTestWithLifecycle(context,runLifecycleHooks),this.validateTestOutcome()}catch(error2){this.notifyTestFailure(error2),globalThis.__XJET?.runtime.bail&&(context.hasError=!0)}finally{inject(SuiteState).test=void 0}}shouldSkipDueToSetupErrors(context){return context.beforeAllErrors&&context.beforeAllErrors.length>0?(this.notifyTestFailure(context.beforeAllErrors),!0):!1}determineSkipAction(isExclusiveMode){return inject(SuiteState).isOnlyMode&&!this.testOptions.only?(this.notifyTestStatus(!0),!0):this.testOptions.skip||this.testOptions.todo?(this.notifyTestStatus(this.testOptions.skip,this.testOptions.todo),!0):isExclusiveMode&&!this.testOptions.only?(this.notifyTestStatus(!0),!0):!1}async executeTestWithLifecycle(context,runLifecycleHooks){await runLifecycleHooks("beforeEach",context),await withTimeout(this.executeTestWithContext(context),this.timeoutDuration,`'${this.timeoutDuration}' test`,this.executionLocation),await runLifecycleHooks("afterEach",context)}validateTestOutcome(){if(this.testOptions.failing)throw new FailingError(this.executionLocation);this.notifyTestAction()}isCallbackStyle(){return this.testImplementation.length===1&&this.testParameters.length===0?!0:this.testImplementation.length===2}getExecutionStrategy(){return isPromise(this.testImplementation)?"ASYNC":this.isCallbackStyle()?"CALLBACK":"SYNC"}async executeTestWithContext(context){switch(this.getExecutionStrategy()){case"ASYNC":case"SYNC":await this.testImplementation.apply(context,this.testParameters);break;case"CALLBACK":await this.executeCallbackStyleTest(context);break}}async executeCallbackStyleTest(context){return new Promise((resolve,reject)=>{let callbackFn=__name(error2=>{error2&&reject(error2),resolve()},"callbackFn"),allParameters=[...this.testParameters];allParameters.push(callbackFn),this.testImplementation.apply(context,allParameters)})}getExecutionDuration(){return this.executionStartTime===0?0:Date.now()-this.executionStartTime}notifyTestStatus(skip=!1,todo=!1){emitStatus(1,{todo,skipped:skip,ancestry:this.ancestry,description:this.description})}notifyTestAction(errors=[]){emitEvent(1,{errors,ancestry:this.ancestry,duration:this.getExecutionDuration(),description:this.description})}notifyTestFailure(error2){this.notifyTestAction(Array.isArray(error2)?error2:[error2])}};var TestDirective=class _TestDirective extends Function{static{__name(this,"TestDirective")}static instance;static ERROR_MESSAGES={SKIP_ONLY:'Cannot use "only" flag on skipped test',ONLY_SKIP:'Cannot use "skip" flag on only test',SKIP_TODO:'Cannot use "todo" flag on skipped test',SKIP_FAILING:'Cannot use "failing" flag on skipped test'};static DEFAULT_TIMEOUT=globalThis.__XJET?.runtime.timeout??5e3;options={};invocationStack="";constructor(){return super(),new Proxy(this,{apply:__name((target,_,args)=>{let[description,block,timeout]=args;this.invocationStack=getTrimmedStackString(2),target.invoke(description,block,[],timeout)},"apply")})}static getInstance(){return _TestDirective.instance||(_TestDirective.instance=new _TestDirective),_TestDirective.instance}get skip(){if(this.options.only)throw new Error(_TestDirective.ERROR_MESSAGES.ONLY_SKIP);return this.options.skip=!0,this}get only(){if(this.options.skip)throw new Error(_TestDirective.ERROR_MESSAGES.SKIP_ONLY);return this.options.only=!0,this}get todo(){if(this.options.skip)throw new Error(_TestDirective.ERROR_MESSAGES.SKIP_TODO);return this.options.todo=!0,this}get failing(){if(this.options.skip)throw new Error(_TestDirective.ERROR_MESSAGES.SKIP_FAILING);return this.options.failing=!0,this}each(...args){return each(this.invoke.bind(this),...args)}invoke(description,block,args=[],timeout){this.validateTestNesting(description),block||(this.options.todo=!0);let test=this.createTest(description,block,args,timeout);this.registerTest(test,this.invocationStack),this.resetFlags()}validateTestNesting(description){let runningTest=inject(SuiteState).test;if(runningTest)throw new Error(`Cannot nest a test inside a test '${description}' in '${runningTest.description}'`)}createTest(description,block,args,timeout){return new TestModel(description,block,timeout??_TestDirective.DEFAULT_TIMEOUT,args,{...this.options})}registerTest(test,location){location&&test.setExecutionLocation(location),inject(SuiteState).addTest(test)}resetFlags(){this.options={}}};var DescribeDirective=class _DescribeDirective extends Function{static{__name(this,"DescribeDirective")}static instance=null;options={};constructor(){return super(),new Proxy(this,{apply(target,thisArg,args){target.invoke(args[0],args[1])}})}static getInstance(){return _DescribeDirective.instance||(_DescribeDirective.instance=new _DescribeDirective),_DescribeDirective.instance}get skip(){if(this.options.only)throw new Error('Cannot use "skip" flag on only test');return this.options.skip=!0,this}get only(){if(this.options.skip)throw new Error('Cannot use "only" flag on skipped test');return this.options.only=!0,this}each(...args){return each(this.invoke.bind(this),...args)}invoke(description,block,args=[]){let suiteState=inject(SuiteState),runningTest=suiteState.test;if(runningTest)throw new Error(`Cannot nest a describe inside a test '${description}' in '${runningTest.description}'`);suiteState.addDescribe(description,block,this.options,args),this.options={}}};import{isPromise as isPromise2}from"@remotex-labs/xjet-expect";var HookModel=class{constructor(hookFunction,timeout){this.hookFunction=hookFunction;this.timeout=timeout}static{__name(this,"HookModel")}location="";setLocation(location){this.location=location}async run(context){return withTimeout(this.executeHook(this.hookFunction,context),this.timeout,"hook while waiting for 'done()' to be called.",this.location)}async executeHook(hook,context){if(isPromise2(hook)&&hook.length>0)throw new Error(`Async hook '${hook.name}' should not use 'done' callback.`);return hook.length>0?this.executeCallbackHook(hook,context):hook.call(context)}executeCallbackHook(hook,context){return new Promise((resolve,reject)=>{hook.call(context,error2=>{error2?reject(error2):resolve()})})}};var DEFAULT_TIMEOUT=globalThis.__XJET?.runtime.timeout??5e3;function createHook(hookType,callback,location,timeout=DEFAULT_TIMEOUT){let hook=new HookModel(callback,timeout);hook.setLocation(location),inject(SuiteState).describe.addHook(hookType,hook)}__name(createHook,"createHook");function afterAllDirective(callback,timeout){createHook("afterAll",callback,getTrimmedStackString(),timeout)}__name(afterAllDirective,"afterAllDirective");function beforeAllDirective(callback,timeout){createHook("beforeAll",callback,getTrimmedStackString(),timeout)}__name(beforeAllDirective,"beforeAllDirective");function afterEachDirective(callback,timeout){createHook("afterEach",callback,getTrimmedStackString(),timeout)}__name(afterEachDirective,"afterEachDirective");function beforeEachDirective(callback,timeout){createHook("beforeEach",callback,getTrimmedStackString(),timeout)}__name(beforeEachDirective,"beforeEachDirective");function clearMocks(method){MockState.mocks.forEach(mock=>{let instance=mock.deref();if(!instance)return MockState.mocks.delete(mock);instance[method]()})}__name(clearMocks,"clearMocks");var setupGlobals=__name(()=>{let globals=globalThis;globals.xJet={fn:fnImplementation,mock:mockImplementation,spyOn:spyOnImplementation,clearAllMocks:__name(()=>clearMocks("mockClear"),"clearAllMocks"),resetAllMocks:__name(()=>clearMocks("mockReset"),"resetAllMocks"),restoreAllMocks:__name(()=>clearMocks("mockRestore"),"restoreAllMocks"),log,info,warn,error,debug,runAllTimers,useFakeTimers,useRealTimers,advanceTimersByTime,runOnlyPendingTimers},globals.expect=xExpect,globals.state=inject(SuiteState),globals.it=TestDirective.getInstance(),globals.test=TestDirective.getInstance(),globals.describe=DescribeDirective.getInstance(),globals.afterAll=afterAllDirective,globals.beforeAll=beforeAllDirective,globals.afterEach=afterEachDirective,globals.beforeEach=beforeEachDirective},"setupGlobals");setupGlobals();
7
+ ${stack}`}};import{isPromise}from"@remotex-labs/xjet-expect";var TestModel=class{constructor(description,testImplementation,timeoutDuration,testParameters=[],testOptions={}){this.description=description;this.testImplementation=testImplementation;this.timeoutDuration=timeoutDuration;this.testParameters=testParameters;this.testOptions=testOptions}static{__name(this,"TestModel")}ancestry=[];executionLocation="";executionStartTime=0;get options(){return this.testOptions}setExecutionLocation(location){this.executionLocation=location}applyExecutionFlags(skip,only){this.testOptions.skip||=skip,this.testOptions.only||=only}setAncestry(parentTests){this.ancestry.push(...parentTests)}async run(context,runLifecycleHooks,isExclusiveMode=!1){if(inject(SuiteState).test=this,this.executionStartTime=Date.now(),!this.shouldSkipDueToSetupErrors(context)&&!this.determineSkipAction(isExclusiveMode))try{await this.executeTestWithLifecycle(context,runLifecycleHooks),this.validateTestOutcome()}catch(error2){this.notifyTestFailure(error2),globalThis.__XJET?.runtime.bail&&(context.hasError=!0)}finally{inject(SuiteState).test=void 0}}shouldSkipDueToSetupErrors(context){return context.beforeAllErrors&&context.beforeAllErrors.length>0?(this.notifyTestFailure(context.beforeAllErrors),!0):!1}determineSkipAction(isExclusiveMode){return inject(SuiteState).isOnlyMode&&!this.testOptions.only?(this.notifyTestStatus(!0),!0):this.testOptions.skip||this.testOptions.todo?(this.notifyTestStatus(this.testOptions.skip,this.testOptions.todo),!0):isExclusiveMode&&!this.testOptions.only?(this.notifyTestStatus(!0),!0):!1}async executeTestWithLifecycle(context,runLifecycleHooks){await runLifecycleHooks("beforeEach",context),await withTimeout(this.executeTestWithContext(context),this.timeoutDuration,`'${this.timeoutDuration}' test`,this.executionLocation),await runLifecycleHooks("afterEach",context)}validateTestOutcome(){if(this.testOptions.failing)throw new FailingError(this.executionLocation);this.notifyTestAction()}isCallbackStyle(){return this.testImplementation.length===1&&this.testParameters.length===0?!0:this.testImplementation.length===2}getExecutionStrategy(){return isPromise(this.testImplementation)?"ASYNC":this.isCallbackStyle()?"CALLBACK":"SYNC"}async executeTestWithContext(context){switch(this.getExecutionStrategy()){case"ASYNC":case"SYNC":await this.testImplementation.apply(context,this.testParameters);break;case"CALLBACK":await this.executeCallbackStyleTest(context);break}}async executeCallbackStyleTest(context){return new Promise((resolve,reject)=>{let callbackFn=__name(error2=>{error2&&reject(error2),resolve()},"callbackFn"),allParameters=[...this.testParameters];allParameters.push(callbackFn),this.testImplementation.apply(context,allParameters)})}getExecutionDuration(){return this.executionStartTime===0?0:Date.now()-this.executionStartTime}notifyTestStatus(skip=!1,todo=!1){emitStatus(1,{todo,skipped:skip,ancestry:this.ancestry,description:this.description})}notifyTestAction(errors=[]){emitEvent(1,{errors,ancestry:this.ancestry,duration:this.getExecutionDuration(),description:this.description})}notifyTestFailure(error2){this.notifyTestAction(Array.isArray(error2)?error2:[error2])}};var TestDirective=class _TestDirective extends Function{static{__name(this,"TestDirective")}static instance;static ERROR_MESSAGES={SKIP_ONLY:'Cannot use "only" flag on skipped test',ONLY_SKIP:'Cannot use "skip" flag on only test',SKIP_TODO:'Cannot use "todo" flag on skipped test',SKIP_FAILING:'Cannot use "failing" flag on skipped test'};static DEFAULT_TIMEOUT=globalThis.__XJET?.runtime.timeout??5e3;options={};invocationStack="";constructor(){return super(),new Proxy(this,{apply:__name((target,_,args)=>{let[description,block,timeout]=args;this.invocationStack=getTrimmedStackString(2),target.invoke(description,block,[],timeout)},"apply")})}static getInstance(){return _TestDirective.instance||(_TestDirective.instance=new _TestDirective),_TestDirective.instance}get skip(){if(this.options.only)throw new Error(_TestDirective.ERROR_MESSAGES.ONLY_SKIP);return this.options.skip=!0,this}get only(){if(this.options.skip)throw new Error(_TestDirective.ERROR_MESSAGES.SKIP_ONLY);return this.options.only=!0,this}get todo(){if(this.options.skip)throw new Error(_TestDirective.ERROR_MESSAGES.SKIP_TODO);return this.options.todo=!0,this}get failing(){if(this.options.skip)throw new Error(_TestDirective.ERROR_MESSAGES.SKIP_FAILING);return this.options.failing=!0,this}each(...args){return each(this.invoke.bind(this),...args)}invoke(description,block,args=[],timeout){this.validateTestNesting(description),block||(this.options.todo=!0);let test=this.createTest(description,block,args,timeout);this.registerTest(test,this.invocationStack),this.resetFlags()}validateTestNesting(description){let runningTest=inject(SuiteState).test;if(runningTest)throw new Error(`Cannot nest a test inside a test '${description}' in '${runningTest.description}'`)}createTest(description,block,args,timeout){return new TestModel(description,block,timeout??_TestDirective.DEFAULT_TIMEOUT,args,{...this.options})}registerTest(test,location){location&&test.setExecutionLocation(location),inject(SuiteState).addTest(test)}resetFlags(){this.options={}}};var DescribeDirective=class _DescribeDirective extends Function{static{__name(this,"DescribeDirective")}static instance=null;options={};constructor(){return super(),new Proxy(this,{apply(target,thisArg,args){target.invoke(args[0],args[1])}})}static getInstance(){return _DescribeDirective.instance||(_DescribeDirective.instance=new _DescribeDirective),_DescribeDirective.instance}get skip(){if(this.options.only)throw new Error('Cannot use "skip" flag on only test');return this.options.skip=!0,this}get only(){if(this.options.skip)throw new Error('Cannot use "only" flag on skipped test');return this.options.only=!0,this}each(...args){return each(this.invoke.bind(this),...args)}invoke(description,block,args=[]){let suiteState=inject(SuiteState),runningTest=suiteState.test;if(runningTest)throw new Error(`Cannot nest a describe inside a test '${description}' in '${runningTest.description}'`);suiteState.addDescribe(description,block,this.options,args),this.options={}}};import{isPromise as isPromise2}from"@remotex-labs/xjet-expect";var HookModel=class{constructor(hookFunction,timeout){this.hookFunction=hookFunction;this.timeout=timeout}static{__name(this,"HookModel")}location="";setLocation(location){this.location=location}async run(context){return withTimeout(this.executeHook(this.hookFunction,context),this.timeout,"hook while waiting for 'done()' to be called.",this.location)}async executeHook(hook,context){if(isPromise2(hook)&&hook.length>0)throw new Error(`Async hook '${hook.name}' should not use 'done' callback.`);return hook.length>0?this.executeCallbackHook(hook,context):hook.call(context)}executeCallbackHook(hook,context){return new Promise((resolve,reject)=>{hook.call(context,error2=>{error2?reject(error2):resolve()})})}};var DEFAULT_TIMEOUT=globalThis.__XJET?.runtime.timeout??5e3;function createHook(hookType,callback,location,timeout=DEFAULT_TIMEOUT){let hook=new HookModel(callback,timeout);hook.setLocation(location),inject(SuiteState).describe.addHook(hookType,hook)}__name(createHook,"createHook");function afterAllDirective(callback,timeout){createHook("afterAll",callback,getTrimmedStackString(),timeout)}__name(afterAllDirective,"afterAllDirective");function beforeAllDirective(callback,timeout){createHook("beforeAll",callback,getTrimmedStackString(),timeout)}__name(beforeAllDirective,"beforeAllDirective");function afterEachDirective(callback,timeout){createHook("afterEach",callback,getTrimmedStackString(),timeout)}__name(afterEachDirective,"afterEachDirective");function beforeEachDirective(callback,timeout){createHook("beforeEach",callback,getTrimmedStackString(),timeout)}__name(beforeEachDirective,"beforeEachDirective");function clearMocks(method){MockState.mocks.forEach(mock=>{let instance=mock.deref();if(!instance)return MockState.mocks.delete(mock);instance[method]()})}__name(clearMocks,"clearMocks");var setupGlobals=__name(()=>{let globals=globalThis;globals.xJet={fn:fnImplementation,mock:mockImplementation,spyOn:spyOnImplementation,clearAllMocks:__name(()=>clearMocks("mockClear"),"clearAllMocks"),resetAllMocks:__name(()=>clearMocks("mockReset"),"resetAllMocks"),restoreAllMocks:__name(()=>clearMocks("mockRestore"),"restoreAllMocks"),log,info,warn,error,debug,runAllTimers,useFakeTimers,useRealTimers,clearAllTimers,runAllTimersAsync,advanceTimersByTime,runOnlyPendingTimers,runOnlyPendingTimersAsync},globals.expect=xExpect,globals.state=inject(SuiteState),globals.it=TestDirective.getInstance(),globals.test=TestDirective.getInstance(),globals.describe=DescribeDirective.getInstance(),globals.afterAll=afterAllDirective,globals.beforeAll=beforeAllDirective,globals.afterEach=afterEachDirective,globals.beforeEach=beforeEachDirective},"setupGlobals");setupGlobals();
8
8
  //# sourceMappingURL=shared.js.map