@remotex-labs/xjet 1.3.6 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bash.js CHANGED
@@ -18,7 +18,7 @@ __ __ | | ___| |_
18
18
  > </\\__/ / __/ |_
19
19
  /_/\\_\\____/ \\___|\\__|
20
20
  `;function z(){return`${Le.burntOrange(Ot)}
21
- Version: ${Le.brightPink("1.3.6")}
21
+ Version: ${Le.brightPink("1.4.0")}
22
22
  `}o(z,"bannerComponent");import{existsSync as zt}from"fs";import{version as Dt}from"process";var Ne={bail:!1,files:["**/*.test.ts","**/*.spec.ts"],watch:!1,suites:[],filter:[],verbose:!1,timeout:5e3,parallel:1,exclude:[/node_modules/],reporter:"default",randomize:!1,build:{target:[`node${Dt.slice(1)}`],packages:"bundle",platform:"browser",external:[]}};import{dirname as Ut}from"path";import{createRequire as Gt}from"module";import{Script as jt,createContext as _t}from"vm";async function M(i,e={},t={}){let r=new jt(i,t),s=_t(e);return await r.runInContext(s,{breakOnSigint:!0,displayErrors:!1})}o(M,"sandboxExecute");var b=class i extends y{constructor(t,r){if(t instanceof y)return t;super(t.message,"VMRuntimeError");this.originalError=t;t instanceof AggregateError&&Array.isArray(t.errors)&&(this.errors=t.errors.map(s=>new i(s,r))),this.stack=t.stack,this.message=t.message,this.reformatStack(t,r)}static{o(this,"VMRuntimeError")}errors=[];[Symbol.for("nodejs.util.inspect.custom")](){if(this.errors&&this.errors.length>0){let t=this.errors.map(r=>`${r.formattedStack??r.stack}`).join("");return`VMRuntimeError Contains ${this.errors.length} nested errors:
23
23
  ${t}
24
24
  `}return this.formattedStack??this.stack}};import{cwd as Be}from"process";import{build as Bt}from"esbuild";var h=class extends y{static{o(this,"xJetError")}constructor(e,t={withFrameworkFrames:!0}){super(e),this.reformatStack(this,t)}};import{xterm as de}from"@remotex-labs/xansi/xterm.component";import{formatCode as Lt}from"@remotex-labs/xmap/formatter.component";import{highlightCode as Nt}from"@remotex-labs/xmap/highlighter.component";var W=class extends y{static{o(this,"esBuildError")}constructor(e){super("esBuildError build failed","esBuildError"),e.aggregateErrors?this.formatAggregateErrors(e.aggregateErrors):this.reformatStack(e,{withFrameworkFrames:!0})}formatAggregateErrors(e){this.formattedStack="";for(let t of e)this.formattedStack+=`
@@ -39,7 +39,7 @@ ${this.escapeXml(t.stack)}</failure>`).join(""):""}formatDuration(e){return((e??
39
39
  `).map(r=>E.dim(r)),""),t.push(...e.stack.split(`
40
40
  `),""),t}incrementTestCounters(e,t){t.total+=1,this.tests.total+=1,t[e]+=1,this.tests[e]+=1}updateState(){let e=[],t=[];this.suites.failed>0&&e.push(m.failed(`${this.suites.failed} failed`)),this.suites.passed>0&&e.push(m.passed(`${this.suites.passed} passed`)),this.suites.skipped>0&&e.push(m.skipped(`${this.suites.skipped} skipped`)),this.suites.total>0&&e.push(`${this.suites.total} total`),this.tests.failed>0&&t.push(m.failed(`${this.tests.failed} failed`)),this.tests.passed>0&&t.push(m.passed(`${this.tests.passed} passed`)),this.tests.skipped>0&&t.push(m.skipped(`${this.tests.skipped} skipped`)),this.tests.todo>0&&t.push(m.todo(`${this.tests.todo} todo`)),this.tests.total>0&&t.push(`${this.tests.total} total`);let r=((Date.now()-this.startTime)/1e3).toFixed(3);this.status.writeBlock(0,0,`Suites: ${e.length?e.join(", "):"No suites yet"}
41
41
  Tests: ${t.length?t.join(", "):"No tests yet"}
42
- Time: ${E.lightOrange(`${r} s`)}`,!0),this.status.render()}renderSuites(){let e=0;for(let[,t]of this.suiteMap){this.info.writeText(e++,0,t.title,!0);for(let r of t.details)this.info.writeText(e++,2,Se.CLEAR_LINE+r,!0)}e>this.info.height?this.info.scroll=e-this.info.height:this.info.render(),this.updateState()}getPrefix(e,t,r){let s=this.isSingleRunner?"":E.burntOrange(` [ ${t.padEnd(this.maxRunnerNameLength)} ]`);return`${Ve[e]}${s} ${E.dim(r)}`}getLogPrefix(e){let t=m.pending;switch(e.levelId){case 1:t=m.failed;break;case 2:t=m.skipped;break;case 3:t=E.cyanBright;break;case 4:t=m.running;break}return t(`[ ${e.level.toLowerCase()} ]`)}};async function br(i){return X(i,{minify:!1,format:"cjs",platform:"node",logLevel:"silent",packages:"external"})}o(br,"transpile");async function Pr(i){let{code:e,path:t}=await br(i);try{let r={exports:{default:void 0}},s=Er(t),n={Error,Buffer,RegExp,module:r,process,console,require:s,setTimeout,setInterval};return await M(e,n,{filename:t}),r.exports.default}catch(r){throw new b(r)}}o(Pr,"parseExternalReporter");async function Ze(i){let{reporter:e,outputFile:t}=i,r={json:j,junit:V,default:U};if(r[e]||!wr(e)){let n=r[e]||U;return new n(O[i.logLevel]??0,t)}let s=await Pr(e);if(!s)throw new h(`Reporter at "${e}" does not have a valid default export`);if(typeof s!="function")throw new h(`Reporter at "${e}" is not a valid constructor`);try{return new s(4,t)}catch(n){throw new b(n)}}o(Ze,"getReporter");var Y=class{constructor(e,t){this.target=e;this.reporter=t;this.target.on("log",this.handleLog.bind(this)),this.target.on("error",this.handleSuiteError.bind(this)),this.target.on("status",this.handleSuiteStatus.bind(this)),this.target.on("events",this.handleSuiteEvent.bind(this))}static{o(this,"MessageService")}framework=p(f);error=!1;suiteError=!1;get hasSuiteError(){return this.suiteError}get hasError(){return this.error}handleLog(e,t){let s=this.framework.getSourceMap(e.invocation.source)?.getPositionWithCode(e.invocation.line,e.invocation.column),n={level:O[e.level]??"UNKNOWN",suite:t,runner:this.target.getRunnerName(e.runnerId),levelId:e.level,message:e.message,ancestry:e.ancestry.split(","),timestamp:new Date(e.timestamp)};s&&(n.invocation={code:s.code,line:s.line,column:s.column,source:s.source}),this.reporter.log?.(n)}handleSuiteError(e,t){this.target.completeSuite(e.runnerId+e.suiteId,!0);let r={suite:t,error:this.decodeError(e.error,{linesBefore:2,linesAfter:3}),runner:this.target.getRunnerName(e.runnerId),duration:0,timestamp:new Date(e.timestamp)};this.suiteError=!0,this.reporter.suiteEnd?.(r)}handleSuiteStatus(e,t){let r={suite:t,runner:this.target.getRunnerName(e.runnerId),timestamp:new Date(e.timestamp)};switch(e.type){case 4:this.reporter.suiteStart?.(r);break;case 3:this.target.completeSuite(e.runnerId+e.suiteId,!1),r.duration=e.duration,this.reporter.suiteEnd?.(r);break;case 1:case 2:{let s=r;s.ancestry=e.ancestry.split(","),s.description=e.description,e.todo&&(s.todo=!0),e.skipped&&(s.skipped=!0),e.type===1?this.reporter.testStart?.(s):this.reporter.describeStart?.(s);break}}}handleSuiteEvent(e,t){let r={suite:t,passed:!0,runner:this.target.getRunnerName(e.runnerId),duration:e.duration,ancestry:e.ancestry.split(","),timestamp:new Date(e.timestamp),description:e.description};e.errors&&(r.errors=this.decodeError(e.errors,{linesBefore:2,linesAfter:3}),r.passed=!1,this.error=!0),e.type===1?this.reporter.testEnd?.(r):this.reporter.describeEnd?.(r)}decodeError(e,t={}){try{let r=JSON.parse(e);return Array.isArray(r)?r.map(s=>this.structuredError(s,G(s,t))):this.structuredError(r,G(r,t))}catch(r){return this.structuredError(r,G(r,t))}}structuredError(e,t){return{name:e.name,line:t.line,code:t.code,formatCode:t.formatCode,stack:t.stacks,column:t.column,message:e.message,matcherResult:e.matcherResult}}};import*as Cr from"process";import{pathToFileURL as Fr}from"url";import{createRequire as $r}from"module";import{dirname as ot,relative as Mr,resolve as Or}from"path";import{serializeError as Dr}from"@remotex-labs/xjet-expect";import Ar from"events";import{serializeError as _n}from"@remotex-labs/xjet-expect";import{Struct as L}from"@remotex-labs/xstruct";var Rr=new L({line:"UInt32LE",column:"UInt32LE",source:"string"}),Ie=new L({kind:"UInt8:4",suiteId:{type:"string",size:14},runnerId:{type:"string",size:14},timestamp:"string"}),et=new L({level:"UInt8",message:{type:"string",lengthType:"UInt32LE"},ancestry:{type:"string",lengthType:"UInt32LE"},invocation:Rr}),ke=new L({error:{type:"string",lengthType:"UInt32LE"}}),tt=new L({type:"UInt8:5",todo:"UInt8:1",skipped:"UInt8:1",duration:"UInt32LE",ancestry:{type:"string",lengthType:"UInt32LE"},description:{type:"string",lengthType:"UInt32LE"}}),rt=new L({type:"UInt8:5",passed:"UInt8:1",duration:"UInt32LE",ancestry:{type:"string",lengthType:"UInt32LE"},description:{type:"string",lengthType:"UInt32LE"},errors:{type:"string",lengthType:"UInt32LE"}});var st={1:et,2:ke,3:tt,4:rt};function it(i){let e=Ie.size,t=Ie.toObject(i,c=>{e+=c}),r=t.kind,s=st[r];if(!s)throw new Error(`Unknown packet kind: ${r}`);let n=i.subarray(e),a=s.toObject(n);return{...t,...a}}o(it,"decodePacket");var nt,Te;nt=[x({scope:"singleton"})];var R=class{static{o(this,"QueueService")}paused=!0;activeCount=0;concurrencyLimit;queue=[];constructor(e){this.concurrencyLimit=e&&e>0?e:1}get size(){return this.queue.length}get running(){return this.activeCount}get isPaused(){return this.paused}stop(){this.paused=!0}start(){this.paused&&(this.paused=!1,this.processQueue())}clear(){let e=this.queue.length;return this.queue.forEach(t=>{"reject"in t&&t.reject()}),this.queue=[],e}enqueue(e,t){return new Promise((r,s)=>{let n=o(async()=>{try{let a=await e();r(a)}catch(a){s(a)}finally{this.activeCount--,this.processQueue()}},"wrappedTask");this.queue.push({task:n,runnerId:t,reject:s,resolve:r}),this.paused||this.processQueue()})}removeTasksByRunner(e){let t=this.queue.length;return this.queue=this.queue.filter(r=>r.runnerId!==e),t-this.queue.length}processQueue(){if(!this.paused)for(;this.activeCount<this.concurrencyLimit&&this.queue.length>0;){let e=this.queue.shift();e&&(this.activeCount++,e.task())}}};Te=k(null),R=T(Te,0,"QueueService",nt,R),v(Te,1,R);var N=class{constructor(e){this.config=e;this.queue=new R(this.config.parallel)}static{o(this,"AbstractTarget")}queue;runningSuites=new Map;suites=new Map;eventEmitter=new Ar;framework=p(f);get numberActiveTask(){return this.queue.size}on(e,t){return this.eventEmitter.on(e,t),this}completeSuite(e,t=!1){let r=this.runningSuites.get(e);r&&(this.runningSuites.delete(e),t&&this.config.bail?(this.queue.stop(),this.queue.clear(),r.reject()):r.resolve())}dispatch(e){let t=it(e),r=this.suites.get(t.suiteId);if(!r)throw new h(`Runner '${t.runnerId}' in test suite '${t.suiteId}' is not registered`);switch(t.kind){case 1:this.eventEmitter.emit("log",t,r);break;case 2:this.completeSuite(t.runnerId+t.suiteId,!0),this.eventEmitter.emit("error",t,r);break;case 3:this.eventEmitter.emit("status",t,r);break;case 4:this.eventEmitter.emit("events",t,r);break;default:let s=`Invalid schema type '${t.kind}' detected for runner '${t.runnerId}' in test suite '${t.suiteId}'`;throw new h(s)}}generateId(){return Math.random().toString(36).substring(2,9)+Math.random().toString(36).substring(2,9)}setSuites(e){if(this.suites.clear(),!e)throw new h("Suites must be provided to register them in the target");for(let[t,r]of Object.entries(e)){let s=this.generateId();this.suites.set(s,r),this.suites.set(t,s)}}};var at,xe,jr;at=[x({scope:"singleton"})];var A=class extends(jr=N){static{o(this,"LocalService")}runnerId=this.generateId();getRunnerName(){return"local"}getRunners(){return[{id:this.runnerId,name:this.getRunnerName()}]}async executeSuites(e,t){this.setSuites(t);let r=[];for(let s of e){let n=Mr(this.framework.rootPath,s.path).replace(/\.[^/.]+$/,"");r.push(this.queue.enqueue(async()=>this.executeTestWithErrorHandling(s.code,s.path,n)))}this.queue.start(),await Promise.allSettled(r)}async executeInSandbox(e,t,r){let s=this.suites.get(r),n={exports:{}},a=$r(t),c=Object.freeze({...Cr,stdout:{write:o(()=>{},"write")},stderr:{write:o(()=>{},"write")}}),l={Buffer,module:n,require:a,setTimeout,setInterval,clearTimeout,clearInterval,process:c,dispatch:this.dispatch.bind(this),__dirname:ot(s),__filename:s,import_meta:{url:Fr(s),dirname:ot(Or(s)),filename:s},__XJET:{runtime:{bail:this.config.bail,path:s,filter:this.config.filter,timeout:this.config.timeout,suiteId:r,runnerId:this.runnerId,randomize:this.config.randomize}}};await M(e,l)}executeTestWithErrorHandling(e,t,r){let s=this.suites.get(r);return new Promise(async(n,a)=>{try{this.runningSuites.set(this.runnerId+s,{resolve:n,reject:a}),await this.executeInSandbox(e,t,s)}catch(c){this.completeSuite(this.runnerId+s,!0),this.eventEmitter.emit("error",{kind:2,error:JSON.stringify(Dr(c)),suiteId:s,runnerId:this.runnerId,timestamp:new Date},this.suites.get(s))}})}};xe=k(jr),A=T(xe,0,"LocalService",at,A),v(xe,1,A);import _r from"yargs";import{pathToFileURL as Lr}from"url";import{dirname as Nr,relative as Br}from"path";import{serializeError as Jr}from"@remotex-labs/xjet-expect";var Z=class extends Error{static{o(this,"TimeoutError")}constructor(e,t,r=""){super(`Exceeded timeout of ${e} ms at ${t}`),Object.setPrototypeOf(this,new.target.prototype),this.name="xJetTimeoutError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="xJetFailingError",r&&(this.stack=`${this.name}: ${this.message}
42
+ Time: ${E.lightOrange(`${r} s`)}`,!0),this.status.render()}renderSuites(){let e=0;for(let[,t]of this.suiteMap){this.info.writeText(e++,0,t.title,!0);for(let r of t.details)this.info.writeText(e++,2,Se.CLEAR_LINE+r,!0)}e>this.info.height?this.info.scroll=e-this.info.height:this.info.render(),this.updateState()}getPrefix(e,t,r){let s=this.isSingleRunner?"":E.burntOrange(` [ ${t.padEnd(this.maxRunnerNameLength)} ]`);return`${Ve[e]}${s} ${E.dim(r)}`}getLogPrefix(e){let t=m.pending;switch(e.levelId){case 1:t=m.failed;break;case 2:t=m.skipped;break;case 3:t=E.cyanBright;break;case 4:t=m.running;break}return t(`[ ${e.level.toLowerCase()} ]`)}};async function br(i){return X(i,{minify:!1,format:"cjs",platform:"node",logLevel:"silent",packages:"external"})}o(br,"transpile");async function Pr(i){let{code:e,path:t}=await br(i);try{let r={exports:{default:void 0}},s=Er(t),n={Error,Buffer,RegExp,module:r,process,console,require:s,setTimeout,setInterval};return await M(e,n,{filename:t}),r.exports.default}catch(r){throw new b(r)}}o(Pr,"parseExternalReporter");async function Ze(i){let{reporter:e,outputFile:t}=i,r={json:j,junit:V,default:U};if(r[e]||!wr(e)){let n=r[e]||U;return new n(O[i.logLevel]??0,t)}let s=await Pr(e);if(!s)throw new h(`Reporter at "${e}" does not have a valid default export`);if(typeof s!="function")throw new h(`Reporter at "${e}" is not a valid constructor`);try{return new s(4,t)}catch(n){throw new b(n)}}o(Ze,"getReporter");var Y=class{constructor(e,t){this.target=e;this.reporter=t;this.target.on("log",this.handleLog.bind(this)),this.target.on("error",this.handleSuiteError.bind(this)),this.target.on("status",this.handleSuiteStatus.bind(this)),this.target.on("events",this.handleSuiteEvent.bind(this))}static{o(this,"MessageService")}framework=p(f);error=!1;suiteError=!1;get hasSuiteError(){return this.suiteError}get hasError(){return this.error}handleLog(e,t){let s=this.framework.getSourceMap(e.invocation.source)?.getPositionWithCode(e.invocation.line,e.invocation.column),n={level:O[e.level]??"UNKNOWN",suite:t,runner:this.target.getRunnerName(e.runnerId),levelId:e.level,message:e.message,ancestry:e.ancestry.split(","),timestamp:new Date(e.timestamp)};s&&(n.invocation={code:s.code,line:s.line,column:s.column,source:s.source}),this.reporter.log?.(n)}handleSuiteError(e,t){this.target.completeSuite(e.runnerId+e.suiteId,!0);let r={suite:t,error:this.decodeError(e.error,{linesBefore:2,linesAfter:3}),runner:this.target.getRunnerName(e.runnerId),duration:0,timestamp:new Date(e.timestamp)};this.suiteError=!0,this.reporter.suiteEnd?.(r)}handleSuiteStatus(e,t){let r={suite:t,runner:this.target.getRunnerName(e.runnerId),timestamp:new Date(e.timestamp)};switch(e.type){case 4:this.reporter.suiteStart?.(r);break;case 3:this.target.completeSuite(e.runnerId+e.suiteId,!1),r.duration=e.duration,this.reporter.suiteEnd?.(r);break;case 1:case 2:{let s=r;s.ancestry=e.ancestry.split(","),s.description=e.description,e.todo&&(s.todo=!0),e.skipped&&(s.skipped=!0),e.type===1?this.reporter.testStart?.(s):this.reporter.describeStart?.(s);break}}}handleSuiteEvent(e,t){let r={suite:t,passed:!0,runner:this.target.getRunnerName(e.runnerId),duration:e.duration,ancestry:e.ancestry.split(","),timestamp:new Date(e.timestamp),description:e.description};e.errors&&(r.errors=this.decodeError(e.errors,{linesBefore:2,linesAfter:3}),r.passed=!1,this.error=!0),e.type===1?this.reporter.testEnd?.(r):this.reporter.describeEnd?.(r)}decodeError(e,t={}){try{let r=JSON.parse(e);return Array.isArray(r)?r.map(s=>this.structuredError(s,G(s,t))):this.structuredError(r,G(r,t))}catch(r){return this.structuredError(r,G(r,t))}}structuredError(e,t){return{name:e.name,line:t.line,code:t.code,formatCode:t.formatCode,stack:t.stacks,column:t.column,message:e.message,matcherResult:e.matcherResult}}};import*as Cr from"process";import{pathToFileURL as Fr}from"url";import{createRequire as $r}from"module";import{dirname as ot,relative as Mr,resolve as Or}from"path";import{serializeError as Dr}from"@remotex-labs/xjet-expect";import Ar from"events";import{serializeError as _n}from"@remotex-labs/xjet-expect";import{Struct as L}from"@remotex-labs/xstruct";var Rr=new L({line:"UInt32LE",column:"UInt32LE",source:"string"}),Ie=new L({kind:"UInt8:4",suiteId:{type:"string",size:14},runnerId:{type:"string",size:14},timestamp:"string"}),et=new L({level:"UInt8",message:{type:"string",lengthType:"UInt32LE"},ancestry:{type:"string",lengthType:"UInt32LE"},invocation:Rr}),ke=new L({error:{type:"string",lengthType:"UInt32LE"}}),tt=new L({type:"UInt8:5",todo:"UInt8:1",skipped:"UInt8:1",duration:"UInt32LE",ancestry:{type:"string",lengthType:"UInt32LE"},description:{type:"string",lengthType:"UInt32LE"}}),rt=new L({type:"UInt8:5",passed:"UInt8:1",duration:"UInt32LE",ancestry:{type:"string",lengthType:"UInt32LE"},description:{type:"string",lengthType:"UInt32LE"},errors:{type:"string",lengthType:"UInt32LE"}});var st={1:et,2:ke,3:tt,4:rt};function it(i){let e=Ie.size,t=Ie.toObject(i,c=>{e+=c}),r=t.kind,s=st[r];if(!s)throw new Error(`Unknown packet kind: ${r}`);let n=i.subarray(e),a=s.toObject(n);return{...t,...a}}o(it,"decodePacket");var nt,Te;nt=[x({scope:"singleton"})];var R=class{static{o(this,"QueueService")}paused=!0;activeCount=0;concurrencyLimit;queue=[];constructor(e){this.concurrencyLimit=e&&e>0?e:1}get size(){return this.queue.length}get running(){return this.activeCount}get isPaused(){return this.paused}stop(){this.paused=!0}start(){this.paused&&(this.paused=!1,this.processQueue())}clear(){let e=this.queue.length;return this.queue.forEach(t=>{"reject"in t&&t.reject()}),this.queue=[],e}enqueue(e,t){return new Promise((r,s)=>{let n=o(async()=>{try{let a=await e();r(a)}catch(a){s(a)}finally{this.activeCount--,this.processQueue()}},"wrappedTask");this.queue.push({task:n,runnerId:t,reject:s,resolve:r}),this.paused||this.processQueue()})}removeTasksByRunner(e){let t=this.queue.length;return this.queue=this.queue.filter(r=>r.runnerId!==e),t-this.queue.length}processQueue(){if(!this.paused)for(;this.activeCount<this.concurrencyLimit&&this.queue.length>0;){let e=this.queue.shift();e&&(this.activeCount++,e.task())}}};Te=k(null),R=T(Te,0,"QueueService",nt,R),v(Te,1,R);var N=class{constructor(e){this.config=e;this.queue=new R(this.config.parallel)}static{o(this,"AbstractTarget")}queue;runningSuites=new Map;suites=new Map;eventEmitter=new Ar;framework=p(f);get numberActiveTask(){return this.queue.size}on(e,t){return this.eventEmitter.on(e,t),this}completeSuite(e,t=!1){let r=this.runningSuites.get(e);r&&(this.runningSuites.delete(e),t&&this.config.bail?(this.queue.stop(),this.queue.clear(),r.reject()):r.resolve())}dispatch(e){let t=it(e),r=this.suites.get(t.suiteId);if(!r)throw new h(`Runner '${t.runnerId}' in test suite '${t.suiteId}' is not registered`);switch(t.kind){case 1:this.eventEmitter.emit("log",t,r);break;case 2:this.completeSuite(t.runnerId+t.suiteId,!0),this.eventEmitter.emit("error",t,r);break;case 3:this.eventEmitter.emit("status",t,r);break;case 4:this.eventEmitter.emit("events",t,r);break;default:let s=`Invalid schema type '${t.kind}' detected for runner '${t.runnerId}' in test suite '${t.suiteId}'`;throw new h(s)}}generateId(){return Math.random().toString(36).substring(2,9)+Math.random().toString(36).substring(2,9)}setSuites(e){if(this.suites.clear(),!e)throw new h("Suites must be provided to register them in the target");for(let[t,r]of Object.entries(e)){let s=this.generateId();this.suites.set(s,r),this.suites.set(t,s)}}};var at,xe,jr;at=[x({scope:"singleton"})];var A=class extends(jr=N){static{o(this,"LocalService")}runnerId=this.generateId();getRunnerName(){return"local"}getRunners(){return[{id:this.runnerId,name:this.getRunnerName()}]}async executeSuites(e,t){this.setSuites(t);let r=[];for(let s of e){let n=Mr(this.framework.rootPath,s.path).replace(/\.[^/.]+$/,"");r.push(this.queue.enqueue(async()=>this.executeTestWithErrorHandling(s.code,s.path,n)))}this.queue.start(),await Promise.allSettled(r)}async executeInSandbox(e,t,r){let s=this.suites.get(r),n={exports:{}},a=$r(t),c=Object.freeze({...Cr,stdout:{write:o(()=>{},"write")},stderr:{write:o(()=>{},"write")}}),l={...globalThis,Buffer,module:n,require:a,setTimeout,setInterval,clearTimeout,clearInterval,process:c,dispatch:this.dispatch.bind(this),__dirname:ot(s),__filename:s,import_meta:{url:Fr(s),dirname:ot(Or(s)),filename:s},__XJET:{runtime:{bail:this.config.bail,path:s,filter:this.config.filter,timeout:this.config.timeout,suiteId:r,runnerId:this.runnerId,randomize:this.config.randomize}}};await M(e,l)}executeTestWithErrorHandling(e,t,r){let s=this.suites.get(r);return new Promise(async(n,a)=>{try{this.runningSuites.set(this.runnerId+s,{resolve:n,reject:a}),await this.executeInSandbox(e,t,s)}catch(c){this.completeSuite(this.runnerId+s,!0),this.eventEmitter.emit("error",{kind:2,error:JSON.stringify(Dr(c)),suiteId:s,runnerId:this.runnerId,timestamp:new Date},this.suites.get(s))}})}};xe=k(jr),A=T(xe,0,"LocalService",at,A),v(xe,1,A);import _r from"yargs";import{pathToFileURL as Lr}from"url";import{dirname as Nr,relative as Br}from"path";import{serializeError as Jr}from"@remotex-labs/xjet-expect";var Z=class extends Error{static{o(this,"TimeoutError")}constructor(e,t,r=""){super(`Exceeded timeout of ${e} ms at ${t}`),Object.setPrototypeOf(this,new.target.prototype),this.name="xJetTimeoutError",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="xJetFailingError",r&&(this.stack=`${this.name}: ${this.message}
43
43
  ${r}`)}};var ct,we;ct=[x({scope:"singleton"})];var C=class{static{o(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 e=o((a,c=0,...l)=>{let d=this.nextId++;return this.timers.set(d,{id:d,callback:a,time:this.now+c,interval:null,args:l??[]}),d},"setTimeout"),t=o((a,c=0)=>{let l=this.nextId++;return this.timers.set(l,{id:l,callback:a,time:this.now+c,interval:c,args:[]}),l},"setInterval"),r=o(a=>{this.timers.delete(a)},"clearTimeout"),s=o(a=>{this.timers.delete(a)},"clearInterval"),n=globalThis;n.setTimeout=e,n.setInterval=t,n.clearTimeout=r,n.clearInterval=s}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(e){this.now+=e,this.runDueTimers()}runAllTimers(){for(;this.timers.size>0;)this.now=Math.min(...Array.from(this.timers.values()).map(e=>e.time)),this.runDueTimers()}runOnlyPendingTimers(){let e=new Set(this.timers.keys());for(;e.size>0;){let t=Array.from(this.timers.values()).filter(r=>e.has(r.id)).map(r=>r.time);if(t.length===0)break;this.now=Math.min(...t),this.runDueTimers(e);for(let r of e)this.timers.has(r)||e.delete(r)}}async runAllTimersAsync(){await Promise.resolve(),this.runAllTimers()}async runOnlyPendingTimersAsync(){await Promise.resolve(),this.runOnlyPendingTimers()}runDueTimers(e){let t=!0;for(;t;){t=!1;let r=Array.from(this.timers.values()).sort((s,n)=>s.time-n.time);for(let s of r)if(this.timers.has(s.id)&&!(e&&!e.has(s.id))&&s.time<=this.now){if(s.interval!==null)for(;s.time<=this.now;)s.callback(),s.time+=s.interval;else s.callback(),this.timers.delete(s.id);t=!0}}}};we=k(null),C=T(we,0,"TimerService",ct,C),v(we,1,C);async function Ee(i,e,t,r){let s=p(C),n=typeof i=="function"?Promise.resolve(i()):Promise.resolve(i);if(e===-1||!s.originalSetTimeout)return n;let a,c=new Promise((l,d)=>{a=s.originalSetTimeout?.(()=>d(new Z(e,t,r)),e)});try{return await Promise.race([n,c])}finally{s.originalClearTimeout?.(a)}}o(Ee,"withTimeout");var ut,be,qr;ut=[x({scope:"singleton"})];var F=class extends(qr=N){static{o(this,"ExternalService")}runners=new Map;async initTarget(){if(!this.config.testRunners||this.config.testRunners.length===0)throw new h("No test runners configured");let e={};this.config.userArgv&&(e=_r(process.argv.slice(2)).options(this.config.userArgv).parseSync()),await Promise.all(this.config.testRunners.map(t=>this.connectRunner(t,e)))}async freeTarget(){let e=[],t=Array.from(this.runners.values());for(let r=0;r<t.length;r++){let s=t[r];s?.disconnect&&e.push(s?.disconnect?.())}await Promise.allSettled(e)}getRunnerName(e){let t=this.runners.get(e)?.name;if(!t)throw new h(`Runner with ID "${e}" not found`);return t}getRunners(){return Array.from(this.runners.values()).map(e=>({id:e.id,name:e.name}))}async executeSuites(e,t){this.setSuites(t);let r=[];for(let s of e){let n=Br(this.framework.rootPath,s.path).replace(/\.[^/.]+$/,"");this.runners.forEach((a,c)=>{r.push(this.queue.enqueue(async()=>this.executeTestWithErrorHandling(s.code,n,a),c))})}this.queue.start(),await Promise.allSettled(r)}async connectRunner(e,t){e.id=this.generateId(),await Ee(e.connect(this.dispatch.bind(this),e.id,t),e?.connectionTimeout??5e3,`connection of runner "${e.name}"`),this.runners.set(e.id,e)}executeTestWithErrorHandling(e,t,r){let s=this.suites.get(t);return new Promise(async(n,a)=>{try{this.runningSuites.set(r.id+s,{resolve:n,reject:a}),await this.executeInRunner(e,s,r)}catch(c){this.completeSuite(r.id+s,!0),this.eventEmitter.emit("error",{kind:2,error:JSON.stringify(Jr(c)),suiteId:s,runnerId:r.id,timestamp:new Date},this.suites.get(s))}})}async executeInRunner(e,t,r){let s={runtime:{bail:this.config.bail,path:this.suites.get(t),filter:this.config.filter,timeout:this.config.timeout,suiteId:t,runnerId:r.id,randomize:this.config.randomize}},n=this.prepareTestCodeWithContext(e,s);await Ee(r?.dispatch?.(Buffer.from(n),t),r?.dispatchTimeout??5e3,`dispatch of runner "${r.name}"`)}prepareTestCodeWithContext(e,t){let r=t.runtime.path,s=Nr(r);return`globalThis.import_meta = { url: "${Lr(r)}", dirname: "${s}", filename: "${r}" };__dirname=${JSON.stringify(s)};__filename=${JSON.stringify(r)};globalThis.__XJET = ${JSON.stringify(t)}; ${e}`}};be=k(qr),F=T(be,0,"ExternalService",ut,F),v(be,1,F);var Gr={js:`
44
44
  `},zr={js:"state.run({})"},te=class{constructor(e){this.config=e;this.target=this.createTarget()}static{o(this,"SuitesService")}target;framework=p(f);async executeSuites(){let e=ze(this.framework.rootPath,this.config);if(Object.keys(e).length===0)throw this.config.suites.length>0?ee.redBright("No test files found for ")+ee.greenBright(this.config.suites.join(", ")):ee.redBright("No test files found for ")+ee.greenBright(this.config.files.join(", "));await this.target.initTarget?.();let t=new Y(this.target,await Ze(this.config));await this.exec(t,e),this.config.watch&&await this.watchForChanges(t,e),await this.target.freeTarget?.(),t.hasError&&Pe(1),t.hasSuiteError&&Pe(2),Pe(0)}async exec(e,t){e.reporter.init?.(Object.values(t),e.target.getRunners());let r=await this.transpileSuites(t);await this.target.executeSuites(r,t),e.reporter.finish?.()}createTarget(){return this.config.testRunners&&this.config.testRunners.length>0?p(F,this.config):p(A,this.config)}async watchForChanges(e,t){await new H(this.config,t,this.exec.bind(this,e)).init()}async transpileSuites(e){return await he(e,{...this.config.build,banner:Gr,footer:zr,format:"cjs",minify:!1,inject:[Ur(this.framework.distPath,"shared.js")],logLevel:"silent",sourcemap:!0,minifySyntax:!0,preserveSymlinks:!0,minifyWhitespace:!0,minifyIdentifiers:!1,define:{"import.meta":"import_meta"}})}};async function Wr(i){let e=await Ue(i);e.verbose&&(globalThis.VERBOSE=!0);let t=await K(e.config,e);t.verbose&&(globalThis.VERBOSE=!0),["json","junit"].includes(t.reporter)?globalThis.NO_COLOR=!0:console.log(z()),await new te(t).executeSuites()}o(Wr,"main");Wr(process.argv);
45
45
  //# sourceMappingURL=bash.js.map