@remotex-labs/xjet 1.3.1 → 1.3.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/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}),__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(`
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(thisArg,...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(${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(parent,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}
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=Reflect.get(parent,prop),!method)throw new Error(`Property '${String(key)}' does not exist in the provided object`);let descriptor=Object.getOwnPropertyDescriptor(parent,key);if(typeof method!="function"||descriptor?.get)return mockDescriptorProperty(parent,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(parent,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
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