@remotex-labs/xjet 1.2.2 → 1.2.3
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/bash.js +1 -1
- package/dist/bash.js.map +1 -1
- package/dist/index.d.ts +24 -3
- package/dist/index.js.map +1 -1
- package/dist/shared.d.ts +59 -33
- package/dist/shared.js +1 -1
- package/dist/shared.js.map +4 -4
- package/package.json +1 -1
package/dist/shared.d.ts
CHANGED
|
@@ -16,6 +16,11 @@ import { Struct } from '@remotex-labs/xstruct';
|
|
|
16
16
|
/**
|
|
17
17
|
* Imports
|
|
18
18
|
*/
|
|
19
|
+
import '@components/require.component';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Import will remove at compile time
|
|
23
|
+
*/
|
|
19
24
|
export {};
|
|
20
25
|
|
|
21
26
|
/**
|
|
@@ -3258,7 +3263,58 @@ declare function spyOnProxyGet<T extends Record<string | symbol, unknown>, K ext
|
|
|
3258
3263
|
*
|
|
3259
3264
|
* @since 1.0.0
|
|
3260
3265
|
*/
|
|
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]
|
|
3266
|
+
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]>;
|
|
3267
|
+
|
|
3268
|
+
/**
|
|
3269
|
+
* Import will remove at compile time
|
|
3270
|
+
*/
|
|
3271
|
+
/**
|
|
3272
|
+
* Represents a mockable function interface with a customizable return type, context,
|
|
3273
|
+
* and argument list. This interface extends `MockState` to facilitate tracking
|
|
3274
|
+
* and testing of function behaviors and states.
|
|
3275
|
+
*
|
|
3276
|
+
* @template F - The function / class type being mocked
|
|
3277
|
+
*
|
|
3278
|
+
* @remarks
|
|
3279
|
+
* This interface is useful for creating test doubles or mock implementations that simulate
|
|
3280
|
+
* complex behaviors (allows for both `function-like` behavior and `constructor-like` behavior)
|
|
3281
|
+
* while tracking interactions and state information.
|
|
3282
|
+
*
|
|
3283
|
+
* @see MockState
|
|
3284
|
+
*
|
|
3285
|
+
* @since 1.0.0
|
|
3286
|
+
*/
|
|
3287
|
+
interface MockableFunctionInterface<F extends FunctionType> extends MockState<F> {
|
|
3288
|
+
/**
|
|
3289
|
+
* Constructor signature when the mocked item is used with 'new'
|
|
3290
|
+
*/
|
|
3291
|
+
new (...args: Parameters<F>): ReturnType<F>;
|
|
3292
|
+
/**
|
|
3293
|
+
* Function call signature preserving 'this' context and parameters
|
|
3294
|
+
*/
|
|
3295
|
+
(this: ThisParameterType<F>, ...args: Parameters<F>): ReturnType<F>;
|
|
3296
|
+
}
|
|
3297
|
+
/**
|
|
3298
|
+
* Makes properties of a type or its resolved promise value optional.
|
|
3299
|
+
*
|
|
3300
|
+
* @template T - The type to transform
|
|
3301
|
+
*
|
|
3302
|
+
* @remarks
|
|
3303
|
+
* If T is a Promise-like type, this utility unwraps it and makes the resolved value's
|
|
3304
|
+
* properties optional. Otherwise, it directly makes T's properties optional.
|
|
3305
|
+
*
|
|
3306
|
+
* @example
|
|
3307
|
+
* ```ts
|
|
3308
|
+
* // Makes properties of User optional
|
|
3309
|
+
* type MaybeUser = PartialResolvedType<User>;
|
|
3310
|
+
*
|
|
3311
|
+
* // Makes properties of resolved User optional
|
|
3312
|
+
* type MaybeAsyncUser = PartialResolvedType<Promise<User>>;
|
|
3313
|
+
* ```
|
|
3314
|
+
*
|
|
3315
|
+
* @since 1.2.2
|
|
3316
|
+
*/
|
|
3317
|
+
type PartialResolvedType<T> = T extends PromiseLike<infer U> ? Promise<Partial<U>> : Partial<T>;
|
|
3262
3318
|
|
|
3263
3319
|
/**
|
|
3264
3320
|
* Interface representing the internal state of a mock proxy.
|
|
@@ -3422,7 +3478,7 @@ declare function fnImplementation<ReturnType, Args extends Array<unknown>, Conte
|
|
|
3422
3478
|
*
|
|
3423
3479
|
* @since 1.2.2
|
|
3424
3480
|
*/
|
|
3425
|
-
declare function mockImplementation<F extends abstract new (...args: any) => any>(method: F, implementation?: (...args: ConstructorParameters<F>) =>
|
|
3481
|
+
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
3482
|
/**
|
|
3427
3483
|
* Creates a mock implementation of the provided function.
|
|
3428
3484
|
*
|
|
@@ -3457,7 +3513,7 @@ declare function mockImplementation<F extends abstract new (...args: any) => any
|
|
|
3457
3513
|
*
|
|
3458
3514
|
* @since 1.2.2
|
|
3459
3515
|
*/
|
|
3460
|
-
declare function mockImplementation<F extends FunctionType>(method: F, implementation?: (...args: Parameters<F>) =>
|
|
3516
|
+
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
3517
|
/**
|
|
3462
3518
|
* Creates a mock for an element with an optional custom implementation.
|
|
3463
3519
|
*
|
|
@@ -3507,36 +3563,6 @@ declare function mockImplementation<F extends FunctionType>(method: F, implement
|
|
|
3507
3563
|
*/
|
|
3508
3564
|
declare function mockImplementation<Element = unknown>(item: Element, implementation?: () => Element): MockState<() => Element>;
|
|
3509
3565
|
|
|
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
3566
|
/**
|
|
3541
3567
|
* Import will remove at compile time
|
|
3542
3568
|
*/
|
package/dist/shared.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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=>{original.cache[original.resolve(moduleName)]||original(moduleName);let resolved=original.cache[original.resolve(moduleName)];if(resolved?.internal)return resolved.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&&(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
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.
|