@remotex-labs/xjet 1.3.5 → 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 +14 -14
- package/dist/bash.js.map +4 -4
- package/dist/index.js.map +1 -1
- package/dist/shared.js.map +1 -1
- package/package.json +1 -1
package/dist/bash.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
${s instanceof Error?s.message:String(s)}`)}}setSourceFile(e){let t=ue(e),r=`${e}.map`;if(!this.sourceMaps.has(t))try{let s=
|
|
4
|
-
${s instanceof Error?s.message:String(s)}`)}}getRootDir(){return process.cwd()}getDistDir(){return
|
|
2
|
+
var ft=Object.create;var oe=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var $e=(i,e)=>(e=Symbol[i])?e:Symbol.for("Symbol."+i),J=i=>{throw TypeError(i)};var lt=(i,e,t)=>e in i?oe(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var o=(i,e)=>oe(i,"name",{value:e,configurable:!0});var k=i=>[,,,ft(i?.[$e("metadata")]??null)],Me=["class","method","getter","setter","accessor","field","value","get","set"],B=i=>i!==void 0&&typeof i!="function"?J("Function expected"):i,dt=(i,e,t,r,s)=>({kind:Me[i],name:e,metadata:r,addInitializer:n=>t._?J("Already initialized"):s.push(B(n||null))}),ht=(i,e)=>lt(e,$e("metadata"),i[3]),v=(i,e,t,r)=>{for(var s=0,n=i[e>>1],a=n&&n.length;s<a;s++)e&1?n[s].call(t):r=n[s].call(t,r);return r},T=(i,e,t,r,s,n)=>{var a,c,l,d,$,u=e&7,re=!!(e&8),I=!!(e&16),se=u>3?i.length+1:u?re?1:2:0,Re=Me[u+5],Ae=u>3&&(i[se-1]=[]),pt=i[se]||(i[se]=[]),S=u&&(!I&&!re&&(s=s.prototype),u<5&&(u>3||!I)&&mt(u<4?s:{get[t](){return Ce(this,n)},set[t](g){return Fe(this,n,g)}},t));u?I&&u<4&&o(n,(u>2?"set ":u>1?"get ":"")+t):o(s,t);for(var ie=r.length-1;ie>=0;ie--)d=dt(u,t,l={},i[3],pt),u&&(d.static=re,d.private=I,$=d.access={has:I?g=>gt(s,g):g=>t in g},u^3&&($.get=I?g=>(u^1?Ce:yt)(g,s,u^4?n:S.get):g=>g[t]),u>2&&($.set=I?(g,ne)=>Fe(g,s,ne,u^4?n:S.set):(g,ne)=>g[t]=ne)),c=(0,r[ie])(u?u<4?I?n:S[Re]:u>4?void 0:{get:S.get,set:S.set}:s,d),l._=1,u^4||c===void 0?B(c)&&(u>4?Ae.unshift(c):u?I?n=c:S[Re]=c:s=c):typeof c!="object"||c===null?J("Object expected"):(B(a=c.get)&&(S.get=a),B(a=c.set)&&(S.set=a),B(a=c.init)&&Ae.unshift(a));return u||ht(i,s),S&&oe(s,t,S),I?u^4?n:S:s};var ae=(i,e,t)=>e.has(i)||J("Cannot "+t),gt=(i,e)=>Object(e)!==e?J('Cannot use the "in" operator on this value'):i.has(e),Ce=(i,e,t)=>(ae(i,e,"read from private field"),t?t.call(i):e.get(i));var Fe=(i,e,t,r)=>(ae(i,e,"write to private field"),r?r.call(i,t):e.set(i,t),t),yt=(i,e,t)=>(ae(i,e,"access private method"),t);import{dirname as vt,join as Tt,relative as je}from"path";var ce=new Map,Oe=new Map;function x(i){return function(e){Oe.set(e,i||{})}}o(x,"Injectable");function p(i,...e){if(ce.has(i))return ce.get(i);let t=Oe.get(i);if(!t)throw new Error(`Cannot inject ${i.name} \u2013 not marked @Injectable`);let r=t.factory?t.factory(...e):new i(...e);return t?.scope==="singleton"&&ce.set(i,r),r}o(p,"inject");import{xterm as fe}from"@remotex-labs/xansi/xterm.component";import{dirname as St}from"path";import{normalize as ue}from"path";import{readFileSync as It}from"fs";import{SourceService as kt}from"@remotex-labs/xmap";var De,pe;De=[x({scope:"singleton"})];var f=class{static{o(this,"FrameworkService")}filePath;distPath;rootPath;frameworkSourceMap;sourceMaps=new Map;constructor(){this.filePath=import.meta.filename??__filename,this.setSourceFile(this.filePath),this.frameworkSourceMap=this.getSourceMap(this.filePath),this.rootPath=this.getRootDir(),this.distPath=this.getDistDir()}isFrameworkFile(e){let{source:t,sourceRoot:r}=e,s=t?.toLowerCase();return!!(t&&s.includes("xjet")&&!s.includes("xjet.config")||r&&r.includes("xJet"))}getSourceMap(e){if(e=ue(e),this.sourceMaps.has(e))return this.sourceMaps.get(e)}setSource(e,t){let r=ue(t);try{return this.initializeSourceMap(e,r)}catch(s){throw new Error(`Failed to initialize SourceService: ${r}
|
|
3
|
+
${s instanceof Error?s.message:String(s)}`)}}setSourceFile(e){let t=ue(e),r=`${e}.map`;if(!this.sourceMaps.has(t))try{let s=It(r,"utf-8");return this.initializeSourceMap(s,t)}catch(s){throw new Error(`Failed to initialize SourceService: ${t}
|
|
4
|
+
${s instanceof Error?s.message:String(s)}`)}}getRootDir(){return process.cwd()}getDistDir(){return St(this.filePath)}initializeSourceMap(e,t){if(e?.includes('"mappings": ""'))return;let r=new kt(e,this.filePath);this.sourceMaps.set(t,r)}};pe=k(null),f=T(pe,0,"FrameworkService",De,f),v(pe,1,f);import{Bias as xt}from"@remotex-labs/xmap";import{highlightCode as wt}from"@remotex-labs/xmap/highlighter.component";import{parseErrorStack as Et}from"@remotex-labs/xmap/parser.component";import{formatErrorCode as bt}from"@remotex-labs/xmap/formatter.component";var Pt=/\s{2,}/g,Rt=/^https?:\/\//,At=/^file:\/\//;function me(i){if(i.fileName?.includes(this.framework.rootPath)&&(i.fileName=je(this.framework.rootPath,i.fileName)),!i.fileName)return i.source??"";let e=i.line&&i.column?fe.gray(`[${i.line}:${i.column}]`):"";return`at ${i.functionName??""} ${fe.darkGray(i.fileName)} ${e}`.replace(Pt," ").trim()}o(me,"formatStackFrame");function Ct(i,e){let{source:t,sourceRoot:r,line:s}=e;if(t){let n=t.lastIndexOf("http://"),a=t.lastIndexOf("https://");if(Math.max(n,a)!==-1)return`${t.substring(Math.max(n,a))}#L${s}`;if(Rt.test(t))return`${t}#L${s}`;if(r){let c=je(vt(this.framework.distPath),Tt(this.framework.distPath,t)).replace(/\\/g,"/");return`${r}${c}#L${s}`}return`${t}#L${s}`}return i.fileName?i.fileName.replace(At,""):""}o(Ct,"getSourceLocation");function Ft(i){return bt({...i,code:wt(i.code)},{color:fe.brightPink})}o(Ft,"highlightPositionCode");function $t(i,e){return this.code||(this.code=e.code,this.source=e.source,this.formatCode=Ft(e)),me.call(this,{...i,line:e.line,column:e.column,functionName:e.name??i.functionName,fileName:Ct.call(this,i,e)})}o($t,"formatFrameWithPosition");function Mt(i,e){if(!this.withNativeFrames&&i.native||!i.line&&!i.column&&!i.fileName&&!i.functionName)return"";let t=this.framework.getSourceMap(i.fileName??"");if(!t)return me.call(this,i);let r=t.getPositionWithCode(i.line??0,i.column??0,xt.LOWER_BOUND,e);return r&&!this.withFrameworkFrames&&this.framework.isFrameworkFile(r)?"":r?(this.line=r.line,this.column=r.column,$t.call(this,i,r)):me.call(this,i)}o(Mt,"stackEntry");function le(i,e={}){let t={code:"",source:"",framework:p(f),formatCode:"",withNativeFrames:!1,withFrameworkFrames:!1,...e,...globalThis.VERBOSE&&{withNativeFrames:!0,withFrameworkFrames:!0}};return{stacks:Et(i).stack.map(n=>Mt.call(t,n,e)).filter(Boolean),code:t.code,line:t.line??0,column:t.column??0,source:t.source,formatCode:t.formatCode}}o(le,"parseStackTrace");function q(i,e={}){let t=le(i,e),r=[`
|
|
5
5
|
${i.name}: ${i.message}
|
|
6
6
|
|
|
7
7
|
`];return t.formatCode&&r.push(`${t.formatCode}
|
|
@@ -10,27 +10,27 @@ ${i.name}: ${i.message}
|
|
|
10
10
|
${t.stacks.join(`
|
|
11
11
|
`)}
|
|
12
12
|
`),r.join("")}o(q,"formatStack");function G(i,e={}){let t=le(i,e);return t.stacks.length<1&&(t=le(i,{withFrameworkFrames:!0})),{code:t.code,line:t.line,column:t.column,source:t.source,stacks:" "+t.stacks.join(`
|
|
13
|
-
`),formatCode:t.formatCode}}o(G,"stackMetadata");var y=class extends Error{static{o(this,"xJetBaseError")}formattedStack;constructor(e,t="xJetError"){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=t,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}get formatStack(){return this.formattedStack}toJSON(){let e={};for(let t of Object.keys(this)){let r=this[t];r&&(e[t]=r)}return e.name=this.name,e.stack=this.stack,e.message=this.message,e}[Symbol.for("nodejs.util.inspect.custom")](){return this.formattedStack??this.stack}reformatStack(e,t){this.formattedStack=q(e,t)}};function _e(i){if(i instanceof AggregateError){console.error("AggregateError:",i.message);for(let e of i.errors)e instanceof Error&&!(e instanceof y)?console.error(q(e,{withFrameworkFrames:!0,withNativeFrames:!0})):console.error(e);return}i instanceof Error&&!(i instanceof y)?console.error(q(i,{withFrameworkFrames:!0,withNativeFrames:!0})):console.error(i)}o(_e,"formatErrors");process.on("uncaughtException",i=>{_e(i),process.exit(2)});process.on("unhandledRejection",i=>{_e(i),process.exit(2)});import qe from"yargs";import{resolve as
|
|
13
|
+
`),formatCode:t.formatCode}}o(G,"stackMetadata");var y=class extends Error{static{o(this,"xJetBaseError")}formattedStack;constructor(e,t="xJetError"){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name=t,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}get formatStack(){return this.formattedStack}toJSON(){let e={};for(let t of Object.keys(this)){let r=this[t];r&&(e[t]=r)}return e.name=this.name,e.stack=this.stack,e.message=this.message,e}[Symbol.for("nodejs.util.inspect.custom")](){return this.formattedStack??this.stack}reformatStack(e,t){this.formattedStack=q(e,t)}};function _e(i){if(i instanceof AggregateError){console.error("AggregateError:",i.message);for(let e of i.errors)e instanceof Error&&!(e instanceof y)?console.error(q(e,{withFrameworkFrames:!0,withNativeFrames:!0})):console.error(e);return}i instanceof Error&&!(i instanceof y)?console.error(q(i,{withFrameworkFrames:!0,withNativeFrames:!0})):console.error(i)}o(_e,"formatErrors");process.on("uncaughtException",i=>{_e(i),process.exit(2)});process.on("unhandledRejection",i=>{_e(i),process.exit(2)});import qe from"yargs";import{resolve as Wt}from"path";import{hideBin as Xt}from"yargs/helpers";import{xterm as Le}from"@remotex-labs/xansi/xterm.component";var Ot=`
|
|
14
14
|
___ _
|
|
15
15
|
|_ | | |
|
|
16
16
|
__ __ | | ___| |_
|
|
17
17
|
\\ \\/ / | |/ _ \\ __|
|
|
18
18
|
> </\\__/ / __/ |_
|
|
19
19
|
/_/\\_\\____/ \\___|\\__|
|
|
20
|
-
`;function z(){return`${Le.burntOrange(
|
|
21
|
-
Version: ${Le.brightPink("1.
|
|
22
|
-
`}o(z,"bannerComponent");import{existsSync as
|
|
20
|
+
`;function z(){return`${Le.burntOrange(Ot)}
|
|
21
|
+
Version: ${Le.brightPink("1.4.0")}
|
|
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
|
-
`}return this.formattedStack??this.stack}};import{cwd as Be}from"process";import{build as
|
|
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+=`
|
|
25
25
|
${this.name}:
|
|
26
26
|
${de.lightCoral(`${t.text}: ${t.notes.pop()?.text}`)}
|
|
27
27
|
|
|
28
|
-
`,this.formattedStack+=
|
|
28
|
+
`,this.formattedStack+=Lt(Nt(t.location.lineText.trim()),{startLine:t.location.line}),this.formattedStack+=`
|
|
29
29
|
|
|
30
30
|
`,this.formattedStack+=`at ${de.dim(t.location.file)} ${de.gray(`[${t.location.line}:${t.location.column}]`)}
|
|
31
31
|
|
|
32
|
-
`}};var Bt={write:!1,bundle:!0,minify:!0,outdir:`${Be()}`,format:"esm",target:"esnext",platform:"browser",sourcemap:"external",mangleQuoted:!0,sourcesContent:!0,preserveSymlinks:!0};async function Jt(i,e={}){try{return await Nt({absWorkingDir:Be(),...Bt,...e,metafile:!0,entryPoints:i})}catch(t){throw new W(t)}}o(Jt,"buildFiles");async function he(i,e={}){let t=await Jt(i,e),r=[],s=t.outputFiles??[],n=p(f);for(let a of s){let c=a.path.replace(/\.(map)$/,""),l=a.path.endsWith(".js.map"),d=a.path.endsWith(".js");l?n.setSource(a.text,c):d&&r.push({path:c,code:a.text+`//# sourceURL=${c}`})}return r}o(he,"transpileFiles");async function X(i,e={}){let r=(await he([i],e)).shift();if(!r)throw new h("Failed to transpile file: No output generated");return r}o(X,"transpileFile");async function Je(i){let e={minify:!1,format:"cjs",outdir:qt(i),platform:"node",logLevel:"silent",packages:"external",minifySyntax:!0,preserveSymlinks:!0,minifyWhitespace:!0,minifyIdentifiers:!1},t={exports:{}},{code:r,path:s}=await X(i,e),n=Ut(s);try{await M(r,{Error,module:t,Buffer,RegExp,require:n,console,setTimeout,setInterval},{filename:s})}catch(a){throw a instanceof Error?new b(a):a}return t.exports.default??{}}o(Je,"parseConfigurationFile");async function K(i="",e){let t={...Ne};if(i&&Gt(i)){let r=await Je(i);r&&(t={...t,...r,exclude:[...t.exclude??[],...r.exclude??[]]})}return{...t,...e}}o(K,"configuration");var Xt="xJet/config.xjet.ts",ge={files:{describe:"Glob patterns or file paths used to discover test files",type:"string",array:!0},suites:{alias:"s",describe:"Filter pattern for test suite files. Only matching files from `files` will run.",type:"string",array:!0},filter:{alias:"f",describe:"Run only tests or suites matching these names",type:"string",array:!0},config:{alias:"c",describe:"Path to xJet configuration file (.ts or .js)",type:"string",default:Xt,normalize:!0,coerce:o(i=>zt(i),"coerce")},reporter:{alias:"r",describe:'Reporter for test results. Built-in: "spec", "json", "junit". Can also be a custom module path.',type:"string"},outputFile:{describe:'Optional file path to write reporter output (e.g., "reports/junit.xml")',type:"string"},verbose:{alias:"v",describe:"Include full stack traces, including internal frames",type:"boolean"},logLevel:{alias:"l",describe:"Set the logging verbosity level (Silent, Error, Warn, Info, Debug)",type:"string",choices:["Silent","Error","Warn","Info","Debug"]},timeout:{alias:"t",describe:"Maximum time (ms) a single test can run before failing",type:"number"},bail:{alias:"b",describe:"Stop running tests after the first failure",type:"boolean"},watch:{alias:"w",describe:"Watch files for changes and re-run tests automatically",type:"boolean"},randomize:{describe:"Randomize the order of test execution",type:"boolean"}},Kt=[["xJet --config ./xjet.config.ts","Run tests with custom configuration"],['xJet --filter "auth.*" --verbose',"Run auth-related tests with verbose logging"],['xJet --suites "src/**/*.test.ts"',"Run specific test suites"],['xJet --files "src/**/*.test.ts"',"Run pattern to collect test files"],["xJet --watch --coverage","Run tests in watch mode with coverage"]];async function Ht(){let i=qe(process.argv).options({config:ge.config}).parseSync();return(await K(i.config,i)).userArgv??{}}o(Ht,"getUserArgv");async function Ue(i){let e=await Ht(),t=qe(Wt(i)),r=t.showHelp;t.showHelp=function(n){return console.log(z()),this.group(Object.keys(ge),"xJet Options:"),this.group(Object.keys(e),"user Options:"),r.call(this,n)};let s=t.usage("Usage: xJet [files..] [options]").command("* [files..]","Specific test files to run (supports glob patterns)",n=>n.positional("files",{describe:"Specific test files to run (supports glob patterns)",type:"string",array:!0})).options(e).options(ge).epilogue("For more information, check the documentation").help().alias("help","h").strict().version();return Kt.forEach(([n,a])=>{s.example(n,a)}),s.parseSync()}o(Ue,"parseArguments");import{join as qr}from"path";import{exit as Pe}from"process";import{accessSync as fr}from"fs";import{readFile as mr,watch as lr}from"fs/promises";import{dirname as dr,join as hr,normalize as gr}from"path";import{join as Vt,relative as Qt}from"path";import{existsSync as Yt,readdirSync as Zt}from"fs";function ye(i){return Qt(p(f).rootPath,i)}o(ye,"getRelativePath");function Ge(i,e,t,r,s={}){if(!Yt(i))return{};let n=Zt(i,{withFileTypes:!0});for(let a of n){let c=Vt(i,a.name),l=ye(c);if(w(l,t))continue;if(a.isDirectory()){Ge(c,e,t,r,s);continue}if((r.length===0||w(l,r))&&w(c,e)){let $=l,u=$.replace(/\.[^/.]+$/,"");s[u]=$}}return s}o(Ge,"collectFilesFromDir");function ze(i,e){let t=P(e?.suites??[]),r=P(e?.files??[]),s=P(e?.exclude??[]);return Ge(i,r,s,t)}o(ze,"getSpecFiles");var er=/\?/g,tr=/\{([^}]+)\}/g,rr=/(?:\/|^)\*{2}(?:\/|$)/g,sr=/(?<!\.)\*/g,ir=/\\\[([^\]]+)\\\]/g,nr=/[.+$|[\]\\]/g;function or(i){let e=o(r=>r.replace(nr,"\\$&"),"escapeRegexChars"),t=o(r=>r.replace(er,".").replace(rr,".*/?").replace(sr,"[^/]+").replace(ir,(s,n)=>`[${n}]`).replace(tr,(s,n)=>`(${n.split(",").join("|")})`),"convertGlobToRegex");return new RegExp(`^${t(e(i))}$`)}o(or,"compileGlobPattern");function ar(i){let e=/[*?[\]{}!@+()|\]]/.test(i),t=/{[^}]+}/.test(i),r=/@\([^)]+\)/.test(i);return e||t||r}o(ar,"isGlob");function w(i,e){return e.some(t=>t.test(i))}o(w,"matchesAny");function P(i){return i.map(e=>{if(e instanceof RegExp)return e;if(ar(e))return or(e);let t=ye(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${t}$`)})}o(P,"compilePatterns");import{relative as We}from"path";import{readFileSync as cr}from"fs";import{pathToFileURL as ur}from"url";import{createRequire as pr}from"module";var Xe=new Map;function Ke(i="tsconfig.json"){let e=cr(i,"utf8"),r=JSON.parse(e).compilerOptions?.paths;if(r)for(let[s,n]of Object.entries(r))Array.isArray(n)&&n.length>0&&Xe.set(s.replace("*",""),n[0].replace("*",""))}o(Ke,"updateAliases");function He(i){let e=p(f);for(let[t,r]of Xe.entries())if(i.includes(t)){let s=i.replace(t,r);return We(e.rootPath,s)}try{let r=pr(ur(e.rootPath+"/__placeholder__.js").href).resolve(i);if(r)return We(e.rootPath,r)}catch{return}}o(He,"resolveImport");var H=class i{constructor(e,t,r){this.testsFile=t;this.exec=r;Ke(),this.patterns=P(e?.files??[]),this.excludes=P(e?.exclude??[])}static{o(this,"WatchService")}static IMPORT_REGEX=/(?:from|import)\s+['"](?<path>[^'"]+)['"]/g;static FILE_EXTENSION_REGEX=/\.[^/.]+$/;framework=p(f);dependencyGraph=new Map;dependenciesCache=new Map;debounceTimer=null;patterns;excludes;async init(){await Promise.all(Object.values(this.testsFile).map(r=>this.updateGraph(r)));let e=new Set,t=lr(this.framework.rootPath,{recursive:!0});for await(let{filename:r}of t){if(!r)continue;let s=gr(r);w(s,this.excludes)||(e.add(s),this.debounce(()=>this.handleChangedFiles([...e],e)))}}debounce(e,t=400){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(e,t)}fileExists(e){try{return fr(e),!0}catch{return!1}}removeFileFromGraph(e){this.dependencyGraph.delete(e),this.dependenciesCache.delete(e);for(let t of this.dependencyGraph.values())t.delete(e)}async handleChangedFiles(e,t){t.clear();let r={};for(let s of e){if(!this.fileExists(s)){this.removeFileFromGraph(s);continue}if(w(s,this.patterns)){await this.updateGraph(s);let n=s.replace(i.FILE_EXTENSION_REGEX,"");r[n]=s}this.dependencyGraph.has(s)&&(await this.updateGraph(s),this.dependencyGraph.get(s)?.forEach(n=>{let a=n.replace(i.FILE_EXTENSION_REGEX,"");r[a]=n}))}Object.keys(r).length>0&&await this.exec(r)}async getTestDependencies(e,t=!1){if(!t&&this.dependenciesCache.has(e))return this.dependenciesCache.get(e);try{let r=await mr(e,"utf-8"),s=[];for(let n of r.matchAll(i.IMPORT_REGEX)){let a=n.groups?.path;if(!a)continue;let c=He(a)??hr(dr(e),a);s.push(c.endsWith(".ts")?c:`${c}.ts`)}return this.dependenciesCache.set(e,s),s}catch{return this.dependenciesCache.set(e,[]),[]}}async linkDependency(e,t){for(let r of t){let s=this.dependencyGraph.get(r)??new Set,n=s.size;if(e.forEach(a=>s.add(a)),this.dependencyGraph.has(r)||this.dependencyGraph.set(r,s),s.size>n){let a=await this.getTestDependencies(r);a.length>0&&await this.linkDependency(e,a)}}}async updateGraph(e){if(w(e,this.patterns)){let r=await this.getTestDependencies(e,!0);await this.linkDependency([e],r)}else if(this.dependencyGraph.has(e)){let r=[...this.dependencyGraph.get(e)],s=await this.getTestDependencies(e,!0);await this.linkDependency(r,s)}}};import{xterm as ee}from"@remotex-labs/xansi/xterm.component";import{existsSync as xr}from"fs";import{createRequire as wr}from"module";var O=(n=>(n[n.Silent=0]="Silent",n[n.Error=1]="Error",n[n.Warn=2]="Warn",n[n.Info=3]="Info",n[n.Debug=4]="Debug",n))(O||{});import{dirname as yr}from"path";import{mkdirSync as Sr,writeFileSync as Ir}from"fs";var D=class{constructor(e,t){this.logLevel=e;this.outFilePath=t}static{o(this,"AbstractReporter")}};var j=class extends D{static{o(this,"JsonReporter")}testResults={};init(e,t){for(let r of e)for(let s of t)this.testResults[s.name]=this.testResults[s.name]??{},this.testResults[s.name][r]={runner:s.name,suiteName:r,timestamp:new Date,rootDescribe:{tests:[],ancestry:[],describes:[],description:"",timestamp:new Date}}}suiteStart(e){let t=e.suite,r=e.runner;this.testResults[r][t]={runner:e.runner,suiteName:t,timestamp:e.timestamp,rootDescribe:{tests:[],ancestry:[],describes:[],description:"",timestamp:e.timestamp}}}suiteEnd(e){let t=this.getSuite(e.runner,e.suite);t.duration=e.duration,t.rootDescribe.duration=e.duration,e.error&&(t.errors=t.errors??[],t.errors.push(e.error))}describeStart(e){if(e.description==="")return;let t={tests:[],describes:[],skipped:e.skipped??!1,ancestry:e.ancestry,timestamp:e.timestamp,description:e.description},r=this.getSuite(e.runner,e.suite),s=this.findParentDescribe(r,e.ancestry);s?s.describes.push(t):r.rootDescribe.describes.push(t)}describeEnd(e){let t=this.getSuite(e.runner,e.suite),r=this.findParentDescribe(t,e.ancestry);r&&(e.errors&&e.errors.length>0&&(r.errors=r.errors??[],r.errors.push(...e.errors)),r.duration=e.duration)}testStart(e){if(!e.skipped&&!e.todo)return;let t=this.getSuite(e.runner,e.suite),r=this.findParentDescribe(t,e.ancestry);if(!r)return;let s={todo:e.todo,skipped:e.skipped,ancestry:e.ancestry,timestamp:e.timestamp,description:e.description};r.tests.push(s)}testEnd(e){let t=this.getSuite(e.runner,e.suite),r=this.findParentDescribe(t,e.ancestry);if(!r)return;let s={passed:e.passed,errors:e.errors??[],ancestry:e.ancestry,duration:e.duration,timestamp:e.timestamp,description:e.description};r.tests.push(s)}finish(){let e=JSON.stringify(this.testResults,null,4);if(this.outFilePath){let t=yr(this.outFilePath);Sr(t,{recursive:!0}),Ir(this.outFilePath,e)}console.log(e)}getSuite(e,t){if(!this.testResults[e]||!this.testResults[e][t])throw new Error(`Suite not found: ${e} -> ${t}`);return this.testResults[e][t]}findParentDescribe(e,t){if(t.length===0)return e.rootDescribe;let r=e.rootDescribe.describes??[],s;for(let n of t){if(s=r.find(a=>a.description===n),!s)return e.rootDescribe;r=s.describes}return s}};import{dirname as kr}from"path";import{mkdirSync as vr,writeFileSync as Tr}from"fs";var V=class extends j{static{o(this,"JunitReporter")}xmlParts=['<?xml version="1.0" encoding="UTF-8"?>'];finish(){this.xmlParts.push("<testsuites>"),Object.entries(this.testResults).forEach(([t,r])=>{this.xmlParts.push(`<testsuites name="${t}">`),Object.values(r).forEach(s=>{this.convertSuiteToXml(s)}),this.xmlParts.push("</testsuites>")}),this.xmlParts.push("</testsuites>");let e=this.xmlParts.join(`
|
|
33
|
-
`);if(this.outFilePath){let t=
|
|
32
|
+
`}};var Jt={write:!1,bundle:!0,minify:!0,outdir:`${Be()}`,format:"esm",target:"esnext",platform:"browser",sourcemap:"external",mangleQuoted:!0,sourcesContent:!0,preserveSymlinks:!0};async function qt(i,e={}){try{return await Bt({absWorkingDir:Be(),...Jt,...e,metafile:!0,entryPoints:i})}catch(t){throw new W(t)}}o(qt,"buildFiles");async function he(i,e={}){let t=await qt(i,e),r=[],s=t.outputFiles??[],n=p(f);for(let a of s){let c=a.path.replace(/\.(map)$/,""),l=a.path.endsWith(".js.map"),d=a.path.endsWith(".js");l?n.setSource(a.text,c):d&&r.push({path:c,code:a.text+`//# sourceURL=${c}`})}return r}o(he,"transpileFiles");async function X(i,e={}){let r=(await he([i],e)).shift();if(!r)throw new h("Failed to transpile file: No output generated");return r}o(X,"transpileFile");async function Je(i){let e={minify:!1,format:"cjs",outdir:Ut(i),platform:"node",logLevel:"silent",packages:"external",minifySyntax:!0,preserveSymlinks:!0,minifyWhitespace:!0,minifyIdentifiers:!1},t={exports:{}},{code:r,path:s}=await X(i,e),n=Gt(s);try{await M(r,{Error,module:t,Buffer,RegExp,require:n,console,setTimeout,setInterval},{filename:s})}catch(a){throw a instanceof Error?new b(a):a}return t.exports.default??{}}o(Je,"parseConfigurationFile");async function K(i="",e){let t={...Ne};if(i&&zt(i)){let r=await Je(i);r&&(t={...t,...r,exclude:[...t.exclude??[],...r.exclude??[]]})}return{...t,...e}}o(K,"configuration");var Kt="xJet/config.xjet.ts",ge={files:{describe:"Glob patterns or file paths used to discover test files",type:"string",array:!0},suites:{alias:"s",describe:"Filter pattern for test suite files. Only matching files from `files` will run.",type:"string",array:!0},filter:{alias:"f",describe:"Run only tests or suites matching these names",type:"string",array:!0},config:{alias:"c",describe:"Path to xJet configuration file (.ts or .js)",type:"string",default:Kt,normalize:!0,coerce:o(i=>Wt(i),"coerce")},reporter:{alias:"r",describe:'Reporter for test results. Built-in: "spec", "json", "junit". Can also be a custom module path.',type:"string"},outputFile:{describe:'Optional file path to write reporter output (e.g., "reports/junit.xml")',type:"string"},verbose:{alias:"v",describe:"Include full stack traces, including internal frames",type:"boolean"},logLevel:{alias:"l",describe:"Set the logging verbosity level (Silent, Error, Warn, Info, Debug)",type:"string",choices:["Silent","Error","Warn","Info","Debug"]},timeout:{alias:"t",describe:"Maximum time (ms) a single test can run before failing",type:"number"},bail:{alias:"b",describe:"Stop running tests after the first failure",type:"boolean"},watch:{alias:"w",describe:"Watch files for changes and re-run tests automatically",type:"boolean"},randomize:{describe:"Randomize the order of test execution",type:"boolean"}},Ht=[["xJet --config ./xjet.config.ts","Run tests with custom configuration"],['xJet --filter "auth.*" --verbose',"Run auth-related tests with verbose logging"],['xJet --suites "src/**/*.test.ts"',"Run specific test suites"],['xJet --files "src/**/*.test.ts"',"Run pattern to collect test files"],["xJet --watch --coverage","Run tests in watch mode with coverage"]];async function Vt(){let i=qe(process.argv).options({config:ge.config}).parseSync();return(await K(i.config,i)).userArgv??{}}o(Vt,"getUserArgv");async function Ue(i){let e=await Vt(),t=qe(Xt(i)),r=t.showHelp;t.showHelp=function(n){return console.log(z()),this.group(Object.keys(ge),"xJet Options:"),this.group(Object.keys(e),"user Options:"),r.call(this,n)};let s=t.usage("Usage: xJet [files..] [options]").command("* [files..]","Specific test files to run (supports glob patterns)",n=>n.positional("files",{describe:"Specific test files to run (supports glob patterns)",type:"string",array:!0})).options(e).options(ge).epilogue("For more information, check the documentation").help().alias("help","h").strict().version();return Ht.forEach(([n,a])=>{s.example(n,a)}),s.parseSync()}o(Ue,"parseArguments");import{join as Ur}from"path";import{exit as Pe}from"process";import{accessSync as mr}from"fs";import{readFile as lr,watch as dr}from"fs/promises";import{dirname as hr,join as gr,normalize as yr}from"path";import{join as Qt,relative as Yt}from"path";import{existsSync as Zt,readdirSync as er}from"fs";function ye(i){return Yt(p(f).rootPath,i)}o(ye,"getRelativePath");function Ge(i,e,t,r,s={}){if(!Zt(i))return{};let n=er(i,{withFileTypes:!0});for(let a of n){let c=Qt(i,a.name),l=ye(c);if(w(l,t))continue;if(a.isDirectory()){Ge(c,e,t,r,s);continue}if((r.length===0||w(l,r))&&w(c,e)){let $=l,u=$.replace(/\.[^/.]+$/,"");s[u]=$}}return s}o(Ge,"collectFilesFromDir");function ze(i,e){let t=P(e?.suites??[]),r=P(e?.files??[]),s=P(e?.exclude??[]);return Ge(i,r,s,t)}o(ze,"getSpecFiles");var tr=/\?/g,rr=/\{([^}]+)\}/g,sr=/(?:\/|^)\*{2}(?:\/|$)/g,ir=/(?<!\.)\*/g,nr=/\\\[([^\]]+)\\\]/g,or=/[.+$|[\]\\]/g;function ar(i){let e=o(r=>r.replace(or,"\\$&"),"escapeRegexChars"),t=o(r=>r.replace(tr,".").replace(sr,".*/?").replace(ir,"[^/]+").replace(nr,(s,n)=>`[${n}]`).replace(rr,(s,n)=>`(${n.split(",").join("|")})`),"convertGlobToRegex");return new RegExp(`^${t(e(i))}$`)}o(ar,"compileGlobPattern");function cr(i){let e=/[*?[\]{}!@+()|\]]/.test(i),t=/{[^}]+}/.test(i),r=/@\([^)]+\)/.test(i);return e||t||r}o(cr,"isGlob");function w(i,e){return e.some(t=>t.test(i))}o(w,"matchesAny");function P(i){return i.map(e=>{if(e instanceof RegExp)return e;if(cr(e))return ar(e);let t=ye(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${t}$`)})}o(P,"compilePatterns");import{relative as We}from"path";import{readFileSync as ur}from"fs";import{pathToFileURL as pr}from"url";import{createRequire as fr}from"module";var Xe=new Map;function Ke(i="tsconfig.json"){let e=ur(i,"utf8"),r=JSON.parse(e).compilerOptions?.paths;if(r)for(let[s,n]of Object.entries(r))Array.isArray(n)&&n.length>0&&Xe.set(s.replace("*",""),n[0].replace("*",""))}o(Ke,"updateAliases");function He(i){let e=p(f);for(let[t,r]of Xe.entries())if(i.includes(t)){let s=i.replace(t,r);return We(e.rootPath,s)}try{let r=fr(pr(e.rootPath+"/__placeholder__.js").href).resolve(i);if(r)return We(e.rootPath,r)}catch{return}}o(He,"resolveImport");var H=class i{constructor(e,t,r){this.testsFile=t;this.exec=r;Ke(),this.patterns=P(e?.files??[]),this.excludes=P(e?.exclude??[])}static{o(this,"WatchService")}static IMPORT_REGEX=/(?:from|import)\s+['"](?<path>[^'"]+)['"]/g;static FILE_EXTENSION_REGEX=/\.[^/.]+$/;framework=p(f);dependencyGraph=new Map;dependenciesCache=new Map;debounceTimer=null;patterns;excludes;async init(){await Promise.all(Object.values(this.testsFile).map(r=>this.updateGraph(r)));let e=new Set,t=dr(this.framework.rootPath,{recursive:!0});for await(let{filename:r}of t){if(!r)continue;let s=yr(r);w(s,this.excludes)||(e.add(s),this.debounce(()=>this.handleChangedFiles([...e],e)))}}debounce(e,t=400){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(e,t)}fileExists(e){try{return mr(e),!0}catch{return!1}}removeFileFromGraph(e){this.dependencyGraph.delete(e),this.dependenciesCache.delete(e);for(let t of this.dependencyGraph.values())t.delete(e)}async handleChangedFiles(e,t){t.clear();let r={};for(let s of e){if(!this.fileExists(s)){this.removeFileFromGraph(s);continue}if(w(s,this.patterns)){await this.updateGraph(s);let n=s.replace(i.FILE_EXTENSION_REGEX,"");r[n]=s}this.dependencyGraph.has(s)&&(await this.updateGraph(s),this.dependencyGraph.get(s)?.forEach(n=>{let a=n.replace(i.FILE_EXTENSION_REGEX,"");r[a]=n}))}Object.keys(r).length>0&&await this.exec(r)}async getTestDependencies(e,t=!1){if(!t&&this.dependenciesCache.has(e))return this.dependenciesCache.get(e);try{let r=await lr(e,"utf-8"),s=[];for(let n of r.matchAll(i.IMPORT_REGEX)){let a=n.groups?.path;if(!a)continue;let c=He(a)??gr(hr(e),a);s.push(c.endsWith(".ts")?c:`${c}.ts`)}return this.dependenciesCache.set(e,s),s}catch{return this.dependenciesCache.set(e,[]),[]}}async linkDependency(e,t){for(let r of t){let s=this.dependencyGraph.get(r)??new Set,n=s.size;if(e.forEach(a=>s.add(a)),this.dependencyGraph.has(r)||this.dependencyGraph.set(r,s),s.size>n){let a=await this.getTestDependencies(r);a.length>0&&await this.linkDependency(e,a)}}}async updateGraph(e){if(w(e,this.patterns)){let r=await this.getTestDependencies(e,!0);await this.linkDependency([e],r)}else if(this.dependencyGraph.has(e)){let r=[...this.dependencyGraph.get(e)],s=await this.getTestDependencies(e,!0);await this.linkDependency(r,s)}}};import{xterm as ee}from"@remotex-labs/xansi/xterm.component";import{existsSync as wr}from"fs";import{createRequire as Er}from"module";var O=(n=>(n[n.Silent=0]="Silent",n[n.Error=1]="Error",n[n.Warn=2]="Warn",n[n.Info=3]="Info",n[n.Debug=4]="Debug",n))(O||{});import{dirname as Sr}from"path";import{mkdirSync as Ir,writeFileSync as kr}from"fs";var D=class{constructor(e,t){this.logLevel=e;this.outFilePath=t}static{o(this,"AbstractReporter")}};var j=class extends D{static{o(this,"JsonReporter")}testResults={};init(e,t){for(let r of e)for(let s of t)this.testResults[s.name]=this.testResults[s.name]??{},this.testResults[s.name][r]={runner:s.name,suiteName:r,timestamp:new Date,rootDescribe:{tests:[],ancestry:[],describes:[],description:"",timestamp:new Date}}}suiteStart(e){let t=e.suite,r=e.runner;this.testResults[r][t]={runner:e.runner,suiteName:t,timestamp:e.timestamp,rootDescribe:{tests:[],ancestry:[],describes:[],description:"",timestamp:e.timestamp}}}suiteEnd(e){let t=this.getSuite(e.runner,e.suite);t.duration=e.duration,t.rootDescribe.duration=e.duration,e.error&&(t.errors=t.errors??[],t.errors.push(e.error))}describeStart(e){if(e.description==="")return;let t={tests:[],describes:[],skipped:e.skipped??!1,ancestry:e.ancestry,timestamp:e.timestamp,description:e.description},r=this.getSuite(e.runner,e.suite),s=this.findParentDescribe(r,e.ancestry);s?s.describes.push(t):r.rootDescribe.describes.push(t)}describeEnd(e){let t=this.getSuite(e.runner,e.suite),r=this.findParentDescribe(t,e.ancestry);r&&(e.errors&&e.errors.length>0&&(r.errors=r.errors??[],r.errors.push(...e.errors)),r.duration=e.duration)}testStart(e){if(!e.skipped&&!e.todo)return;let t=this.getSuite(e.runner,e.suite),r=this.findParentDescribe(t,e.ancestry);if(!r)return;let s={todo:e.todo,skipped:e.skipped,ancestry:e.ancestry,timestamp:e.timestamp,description:e.description};r.tests.push(s)}testEnd(e){let t=this.getSuite(e.runner,e.suite),r=this.findParentDescribe(t,e.ancestry);if(!r)return;let s={passed:e.passed,errors:e.errors??[],ancestry:e.ancestry,duration:e.duration,timestamp:e.timestamp,description:e.description};r.tests.push(s)}finish(){let e=JSON.stringify(this.testResults,null,4);if(this.outFilePath){let t=Sr(this.outFilePath);Ir(t,{recursive:!0}),kr(this.outFilePath,e)}console.log(e)}getSuite(e,t){if(!this.testResults[e]||!this.testResults[e][t])throw new Error(`Suite not found: ${e} -> ${t}`);return this.testResults[e][t]}findParentDescribe(e,t){if(t.length===0)return e.rootDescribe;let r=e.rootDescribe.describes??[],s;for(let n of t){if(s=r.find(a=>a.description===n),!s)return e.rootDescribe;r=s.describes}return s}};import{dirname as vr}from"path";import{mkdirSync as Tr,writeFileSync as xr}from"fs";var V=class extends j{static{o(this,"JunitReporter")}xmlParts=['<?xml version="1.0" encoding="UTF-8"?>'];finish(){this.xmlParts.push("<testsuites>"),Object.entries(this.testResults).forEach(([t,r])=>{this.xmlParts.push(`<testsuites name="${t}">`),Object.values(r).forEach(s=>{this.convertSuiteToXml(s)}),this.xmlParts.push("</testsuites>")}),this.xmlParts.push("</testsuites>");let e=this.xmlParts.join(`
|
|
33
|
+
`);if(this.outFilePath){let t=vr(this.outFilePath);Tr(t,{recursive:!0}),xr(this.outFilePath,e)}console.log(e)}convertSuiteToXml(e){let t=e.rootDescribe,r=this.countTests(t),s=this.countFailures(t),n=this.countSkipped(t),a=this.formatDuration(e.duration),c=[`name="${e.suiteName}"`,`tests="${r}"`,`failures="${s}"`,`skipped="${n}"`,`time="${a}"`].join(" ");this.xmlParts.push(`<testsuite ${c}>`),this.convertDescribeToXml(t),this.xmlParts.push("</testsuite>")}convertDescribeToXml(e){e.tests.forEach(t=>this.convertTestToXml(t)),e.describes.forEach(t=>this.convertDescribeToXml(t))}convertTestToXml(e){let t=this.formatDuration(e.duration),r=e.description,n=`classname="${e.ancestry.join(".")||"root"}" name="${r}" time="${t}"`;if(e.skipped||e.todo){let c=e.todo?"TODO":"Skipped";this.xmlParts.push(`<testcase ${n}><skipped message="${c}" /></testcase>`);return}if(e.passed){this.xmlParts.push(`<testcase ${n} />`);return}let a=this.formatErrors(e.errors);this.xmlParts.push(`<testcase ${n}>${a}</testcase>`)}formatErrors(e){return e?.length?e.map(t=>`<failure message="${t.name}">${this.escapeXml(t.message)}
|
|
34
34
|
${t.formatCode}
|
|
35
35
|
|
|
36
36
|
${this.escapeXml(t.stack)}</failure>`).join(""):""}formatDuration(e){return((e??0)/1e3).toFixed(3)}countTests(e){return e.tests.length+e.describes.reduce((t,r)=>t+this.countTests(r),0)}countSkipped(e){return e.tests.filter(r=>r.skipped||r.todo).length+e.describes.reduce((r,s)=>r+this.countSkipped(s),0)}countFailures(e){return e.tests.filter(r=>!r.passed&&!r.skipped&&!r.todo).length+e.describes.reduce((r,s)=>r+this.countFailures(s),0)}escapeXml(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}};import{ANSI as Se,writeRaw as Qe}from"@remotex-labs/xansi";import{xterm as E}from"@remotex-labs/xansi/xterm.component";import{ShadowRenderer as Ye}from"@remotex-labs/xansi/shadow.service";import{xterm as _}from"@remotex-labs/xansi/xterm.component";var Q=4,m={todo:_.hex("#da5aec"),failed:_.hex("#F08080"),passed:_.hex("#90EE90"),skipped:_.hex("#fcaa63"),running:_.hex("#FFD966"),pending:_.hex("#808080")},Ve={5:m.pending("[ Pending ]"),0:m.running("[ RUNNING ]"),4:m.skipped("[ SKIPPED ]"),3:m.passed("[ PASSED ]"),2:m.failed("[ FAILED ]")};var U=class extends D{static{o(this,"ConsoleReporter")}startTime=Date.now();isSingleRunner=!1;updateInterval;maxRunnerNameLength=0;info;status;tests=this.createTests();suites=this.createSuites();suiteMap=new Map;constructor(e,t){super(e,t);let r=process.stdout.rows??24,s=process.stdout.columns??80;this.info=new Ye(r-Q-1,s,1,0),this.status=new Ye(Q,s,r-Q,0)}init(e,t){Qe(Se.HIDE_CURSOR),Qe(Se.CLEAR_SCREEN),this.suiteMap.clear(),this.startTime=Date.now(),this.tests=this.createTests(),this.suites=this.createSuites(),this.isSingleRunner=t.length<2,this.updateInterval=setInterval(this.updateState.bind(this),230),this.maxRunnerNameLength=Math.max(...t.map(r=>r.name.length));for(let r of e)for(let s of t){let n=this.getSuiteKey(s.name,r),a=this.getPrefix(5,s.name,r);this.suiteMap.set(n,{todo:0,total:0,passed:0,failed:0,skipped:0,title:a,details:[]})}this.renderSuites()}log(e){if(e.levelId>this.logLevel||this.logLevel===0)return;let t=this.ensureSuite(e.runner,e.suite),r=[""];r.push(this.getLogPrefix(e)+E.gray(` [${e.ancestry.join(" > ")}]`)),r.push(...e.message.split(`
|
|
@@ -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
|
|
43
|
-
${r}`)}};var
|
|
44
|
-
`},
|
|
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
|
+
${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
|
+
`},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
|