@remotex-labs/xjet 1.0.1 → 1.1.1

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/README.md CHANGED
@@ -4,11 +4,12 @@
4
4
  [![npm version](https://img.shields.io/npm/v/@remotex-labs/xjet.svg)](https://www.npmjs.com/package/@remotex-labs/xjet)
5
5
  [![License: MPL 2.0](https://img.shields.io/badge/License-MPL_2.0-brightgreen.svg)](https://opensource.org/licenses/MPL-2.0)
6
6
  [![Node.js CI](https://github.com/remotex-labs/xJet/actions/workflows/node.js.yml/badge.svg)](https://github.com/remotex-labs/xJet/actions/workflows/node.js.yml)
7
+ [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/remotex-labs/xJet)
7
8
 
8
9
  ## Overview
9
10
 
10
- xJet is a powerful, flexible testing framework for JavaScript and TypeScript applications.
11
- Its mission is to help you "Run Automated Tests Anywhere, Effortlessly".
11
+ xJet is a powerful, flexible testing framework for JavaScript and TypeScript applications.
12
+ Its mission is to help you "Run Automated Tests Anywhere, Effortlessly."
12
13
 
13
14
  ## Features
14
15
 
@@ -24,50 +25,63 @@ Its mission is to help you "Run Automated Tests Anywhere, Effortlessly".
24
25
  npm install @remotex-labs/xjet
25
26
  ```
26
27
 
27
- ## Usage
28
+ ## 🚀 Quick Start
28
29
 
29
- ### Basic Test Example
30
+ Create a test file and start writing tests immediately:
30
31
 
31
32
  ```ts
32
33
  // example.test.ts
33
- describe('Calculator', () => { test('should add two numbers correctly', () => {
34
- const result = 1 + 2; expect(result).toBe(3);
35
- });
36
-
37
- it('should subtract two numbers correctly', () => {
38
- const result = 5 - 2; expect(result).toBe(3); });
34
+ describe('Calculator', () => {
35
+ test('should add two numbers correctly', () => {
36
+ const result = 1 + 2; expect(result).toBe(3);
37
+ });
38
+
39
+ it('should subtract two numbers correctly', () => {
40
+ const result = 5 - 2; expect(result).toBe(3);
41
+ });
39
42
  });
40
43
  ```
41
44
 
42
- ### Running Tests
45
+ ## 📚 Documentation
43
46
 
44
- ```bash
45
- xJet
46
- ```
47
+ For comprehensive guides and reference, check our [documentation](https://remotex-labs.github.io/xJet/):
47
48
 
48
- Run:
49
+ - [CLI Options](https://remotex-labs.github.io/xJet/configuration/cli)
50
+ - [Test Structure](https://remotex-labs.github.io/xJet/tests/test)
51
+ - [Mocking APIs](https://remotex-labs.github.io/xJet/mocks/mock)
52
+ - [Timer Manipulation](https://remotex-labs.github.io/xJet/mocks/timer)
53
+ - [Matchers Reference](https://remotex-labs.github.io/xJet/xjet-expect/equality)
49
54
 
50
- ![Run](./docs/src/public/images/run.png)
55
+ Run:
51
56
 
52
- ![Run](./docs/src/public/images/run1.png)
57
+ ![Run](./docs/public/images/run.png)
53
58
 
54
- ![Run](./docs/src/public/images/run2.png)
59
+ ![Run](./docs/public/images/run1.png)
55
60
 
61
+ ![Run](./docs/public/images/run2.png)
56
62
 
57
63
  ## Documentation
64
+
58
65
  For complete API documentation, examples, and guides, visit: [xJet Documentation](https://remotex-labs.github.io/xJet/)
59
66
 
60
- ## Compatibility
67
+ ## 🔍 Compatibility
68
+
61
69
  - Node.js 20+
62
70
  - All modern browsers (via bundlers)
63
71
  - TypeScript 4.5+
64
72
 
65
- ## Contributing
66
- Contributions are welcome!\
67
- Please see our [Contributing Guide](CONTRIBUTING.md) for details.
73
+ ## 🤝 Contributing
74
+
75
+ Contributions are welcome! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
68
76
 
69
- ## License
70
- This project is licensed under the Mozilla Public License 2.0 see the [LICENSE](LICENSE) file for details.
77
+ ## 📄 License
78
+
79
+ This project is licensed under the Mozilla Public License 2.0 - see the [LICENSE](LICENSE) file for details.
80
+
81
+ ## 💖 Acknowledgements
71
82
 
72
- ## Acknowledgments
73
83
  - Built with TypeScript
84
+ - Inspired by testing frameworks like Jest and Mocha
85
+ - Powered by the esbuild ecosystem
86
+
87
+ Made with ❤️ by the remotex-labs/xJet team
package/dist/bash.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- var at=Object.create;var ne=Object.defineProperty;var ct=Object.getOwnPropertyDescriptor;var Ce=(i,e)=>(e=Symbol[i])?e:Symbol.for("Symbol."+i),B=i=>{throw TypeError(i)};var pt=(i,e,t)=>e in i?ne(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var o=(i,e)=>ne(i,"name",{value:e,configurable:!0});var k=i=>[,,,at(i?.[Ce("metadata")]??null)],Fe=["class","method","getter","setter","accessor","field","value","get","set"],_=i=>i!==void 0&&typeof i!="function"?B("Function expected"):i,ut=(i,e,t,r,s)=>({kind:Fe[i],name:e,metadata:r,addInitializer:n=>t._?B("Already initialized"):s.push(_(n||null))}),ft=(i,e)=>pt(e,Ce("metadata"),i[3]),x=(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},v=(i,e,t,r,s,n)=>{var a,c,y,I,F,p=e&7,te=!!(e&8),S=!!(e&16),re=p>3?i.length+1:p?te?1:2:0,be=Fe[p+5],Pe=p>3&&(i[re-1]=[]),ot=i[re]||(i[re]=[]),g=p&&(!S&&!te&&(s=s.prototype),p<5&&(p>3||!S)&&ct(p<4?s:{get[t](){return Re(this,n)},set[t](l){return Ae(this,n,l)}},t));p?S&&p<4&&o(n,(p>2?"set ":p>1?"get ":"")+t):o(s,t);for(var se=r.length-1;se>=0;se--)I=ut(p,t,y={},i[3],ot),p&&(I.static=te,I.private=S,F=I.access={has:S?l=>mt(s,l):l=>t in l},p^3&&(F.get=S?l=>(p^1?Re:dt)(l,s,p^4?n:g.get):l=>l[t]),p>2&&(F.set=S?(l,ie)=>Ae(l,s,ie,p^4?n:g.set):(l,ie)=>l[t]=ie)),c=(0,r[se])(p?p<4?S?n:g[be]:p>4?void 0:{get:g.get,set:g.set}:s,I),y._=1,p^4||c===void 0?_(c)&&(p>4?Pe.unshift(c):p?S?n=c:g[be]=c:s=c):typeof c!="object"||c===null?B("Object expected"):(_(a=c.get)&&(g.get=a),_(a=c.set)&&(g.set=a),_(a=c.init)&&Pe.unshift(a));return p||ft(i,s),g&&ne(s,t,g),S?p^4?n:g:s};var oe=(i,e,t)=>e.has(i)||B("Cannot "+t),mt=(i,e)=>Object(e)!==e?B('Cannot use the "in" operator on this value'):i.has(e),Re=(i,e,t)=>(oe(i,e,"read from private field"),t?t.call(i):e.get(i));var Ae=(i,e,t,r)=>(oe(i,e,"write to private field"),r?r.call(i,t):e.set(i,t),t),dt=(i,e,t)=>(oe(i,e,"access private method"),t);import{dirname as St,join as It,relative as Oe}from"path";var ae=new Map,$e=new Map;function E(i){return function(e){$e.set(e,i||{})}}o(E,"Injectable");function f(i,...e){if(ae.has(i))return ae.get(i);let t=$e.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"&&ae.set(i,r),r}o(f,"inject");import{xterm as ue}from"@remotex-labs/xansi/xterm.component";import lt from"url";import{dirname as ht}from"path";import{normalize as ce}from"path";import{readFileSync as gt}from"fs";import{SourceService as yt}from"@remotex-labs/xmap";var Me,pe;Me=[E({scope:"singleton"})];var u=class{static{o(this,"FrameworkService")}filePath;distPath;rootPath;frameworkSourceMap;sourceMaps=new Map;constructor(){this.filePath=lt.fileURLToPath(import.meta.url),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=ce(e),this.sourceMaps.has(e))return this.sourceMaps.get(e)}setSource(e,t){let r=ce(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=ce(e),r=`${e}.map`;if(!this.sourceMaps.has(t))try{let s=gt(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 ht(this.filePath)}initializeSourceMap(e,t){if(e?.includes('"mappings": ""'))return;let r=new yt(e,this.filePath);this.sourceMaps.set(t,r)}};pe=k(null),u=v(pe,0,"FrameworkService",Me,u),x(pe,1,u);import{Bias as kt}from"@remotex-labs/xmap";import{highlightCode as xt}from"@remotex-labs/xmap/highlighter.component";import{parseErrorStack as vt}from"@remotex-labs/xmap/parser.component";import{formatErrorCode as Et}from"@remotex-labs/xmap/formatter.component";var Tt=/\s{2,}/g,wt=/^https?:\/\//,bt=/^file:\/\//;function fe(i){if(i.fileName?.includes(this.framework.rootPath)&&(i.fileName=Oe(this.framework.rootPath,i.fileName)),!i.fileName)return i.source??"";let e=i.line&&i.column?ue.gray(`[${i.line}:${i.column}]`):"";return`at ${i.functionName??""} ${ue.darkGray(i.fileName)} ${e}`.replace(Tt," ").trim()}o(fe,"formatStackFrame");function Pt(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(wt.test(t))return`${t}#L${s}`;if(r){let c=Oe(St(this.framework.distPath),It(this.framework.distPath,t)).replace(/\\/g,"/");return`${r}${c}#L${s}`}return`${t}#L${s}`}return i.fileName?i.fileName.replace(bt,""):""}o(Pt,"getSourceLocation");function Rt(i){return Et({...i,code:xt(i.code)},{color:ue.brightPink})}o(Rt,"highlightPositionCode");function At(i,e){return this.code||(this.code=e.code,this.source=e.source,this.formatCode=Rt(e)),fe.call(this,{...i,line:e.line,column:e.column,functionName:e.name??i.functionName,fileName:Pt.call(this,i,e)})}o(At,"formatFrameWithPosition");function Ct(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 fe.call(this,i);let r=t.getPositionWithCode(i.line??0,i.column??0,kt.LOWER_BOUND,e);return r&&!this.withFrameworkFrames&&this.framework.isFrameworkFile(r)?"":r?(this.line=r.line,this.column=r.column,At.call(this,i,r)):fe.call(this,i)}o(Ct,"stackEntry");function me(i,e={}){let t={code:"",source:"",framework:f(u),formatCode:"",withNativeFrames:!1,withFrameworkFrames:!1,...e,...globalThis.VERBOSE&&{withNativeFrames:!0,withFrameworkFrames:!0}};return{stacks:vt(i).stack.map(n=>Ct.call(t,n,e)).filter(Boolean),code:t.code,line:t.line??0,column:t.column??0,source:t.source,formatCode:t.formatCode}}o(me,"parseStackTrace");function J(i,e={}){let t=me(i,e),r=[`
2
+ var pt=Object.create;var oe=Object.defineProperty;var ft=Object.getOwnPropertyDescriptor;var $e=(i,e)=>(e=Symbol[i])?e:Symbol.for("Symbol."+i),J=i=>{throw TypeError(i)};var mt=(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=>[,,,pt(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,lt=(i,e,t,r,s)=>({kind:Me[i],name:e,metadata:r,addInitializer:n=>t._?J("Already initialized"):s.push(B(n||null))}),dt=(i,e)=>mt(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]=[]),ut=i[se]||(i[se]=[]),S=u&&(!I&&!re&&(s=s.prototype),u<5&&(u>3||!I)&&ft(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=lt(u,t,l={},i[3],ut),u&&(d.static=re,d.private=I,$=d.access={has:I?g=>ht(s,g):g=>t in g},u^3&&($.get=I?g=>(u^1?Ce:gt)(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||dt(i,s),S&&oe(s,t,S),I?u^4?n:S:s};var ae=(i,e,t)=>e.has(i)||J("Cannot "+t),ht=(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),gt=(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,De=new Map;function x(i){return function(e){De.set(e,i||{})}}o(x,"Injectable");function p(i,...e){if(ce.has(i))return ce.get(i);let t=De.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 yt from"url";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 Oe,pe;Oe=[x({scope:"singleton"})];var f=class{static{o(this,"FrameworkService")}filePath;distPath;rootPath;frameworkSourceMap;sourceMaps=new Map;constructor(){this.filePath=yt.fileURLToPath(import.meta.url),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",Oe,f),v(pe,1,f);import{Bias as xt}from"@remotex-labs/xmap";import{highlightCode as Et}from"@remotex-labs/xmap/highlighter.component";import{parseErrorStack as wt}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:Et(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:wt(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}
@@ -9,37 +9,37 @@ ${i.name}: ${i.message}
9
9
  `),t.stacks.length>0&&r.push(`Enhanced Stack Trace:
10
10
  ${t.stacks.join(`
11
11
  `)}
12
- `),r.join("")}o(J,"formatStack");function U(i,e={}){let t=me(i,e);return t.stacks.length<1&&(t=me(i,{withFrameworkFrames:!0})),{code:t.code,line:t.line,column:t.column,source:t.source,stacks:" "+t.stacks.join(`
13
- `),formatCode:t.formatCode}}o(U,"stackMetadata");var h=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=J(e,t)}};function De(i){if(i instanceof AggregateError){console.error("AggregateError:",i.message);for(let e of i.errors)e instanceof Error&&!(e instanceof h)?console.error(J(e,{withFrameworkFrames:!0,withNativeFrames:!0})):console.error(e);return}i instanceof Error&&!(i instanceof h)?console.error(J(i,{withFrameworkFrames:!0,withNativeFrames:!0})):console.error(i)}o(De,"formatErrors");process.on("uncaughtException",i=>{De(i),process.exit(2)});process.on("unhandledRejection",i=>{De(i),process.exit(2)});import Be from"yargs";import{resolve as Ut}from"path";import{hideBin as Gt}from"yargs/helpers";import{xterm as je}from"@remotex-labs/xansi/xterm.component";var Ft=`
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 Le(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(Le,"formatErrors");process.on("uncaughtException",i=>{Le(i),process.exit(2)});process.on("unhandledRejection",i=>{Le(i),process.exit(2)});import qe from"yargs";import{resolve as Wt}from"path";import{hideBin as Xt}from"yargs/helpers";import{xterm as Ne}from"@remotex-labs/xansi/xterm.component";var Dt=`
14
14
  ___ _
15
15
  |_ | | |
16
16
  __ __ | | ___| |_
17
17
  \\ \\/ / | |/ _ \\ __|
18
18
  > </\\__/ / __/ |_
19
19
  /_/\\_\\____/ \\___|\\__|
20
- `;function G(){return`${je.burntOrange(Ft)}
21
- Version: ${je.brightPink("1.0.1")}
22
- `}o(G,"bannerComponent");import{existsSync as qt}from"fs";import{version as $t}from"process";var Le={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${$t.slice(1)}`],packages:"bundle",platform:"browser",external:[]}};import{dirname as Bt}from"path";import{createRequire as Jt}from"module";import{Script as Mt,createContext as Ot}from"vm";async function $(i,e={},t={}){let r=new Mt(i,t),s=Ot(e);return await r.runInContext(s,{breakOnSigint:!0,displayErrors:!1})}o($,"sandboxExecute");var b=class i extends h{constructor(t,r){if(t instanceof h)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:
20
+ `;function z(){return`${Ne.burntOrange(Dt)}
21
+ Version: ${Ne.brightPink("1.1.1")}
22
+ `}o(z,"bannerComponent");import{existsSync as zt}from"fs";import{version as Ot}from"process";var _e={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${Ot.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 Lt}from"vm";async function M(i,e={},t={}){let r=new jt(i,t),s=Lt(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 Ne}from"process";import{build as Lt}from"esbuild";var d=class extends h{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 Dt}from"@remotex-labs/xmap/formatter.component";import{highlightCode as jt}from"@remotex-labs/xmap/highlighter.component";var z=class extends h{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+=`
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 Nt}from"@remotex-labs/xmap/formatter.component";import{highlightCode as _t}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+=Dt(jt(t.location.lineText.trim()),{startLine:t.location.line}),this.formattedStack+=`
28
+ `,this.formattedStack+=Nt(_t(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 Nt={write:!1,bundle:!0,minify:!0,outdir:`${Ne()}`,format:"esm",target:"esnext",platform:"browser",sourcemap:"external",mangleQuoted:!0,sourcesContent:!0,preserveSymlinks:!0};async function _t(i,e={}){try{return await Lt({absWorkingDir:Ne(),...Nt,...e,metafile:!0,entryPoints:i})}catch(t){throw new z(t)}}o(_t,"buildFiles");async function le(i,e={}){let t=await _t(i,e),r=[],s=t.outputFiles??[],n=f(u);for(let a of s){let c=a.path.replace(/\.(map)$/,""),y=a.path.endsWith(".js.map"),I=a.path.endsWith(".js");y?n.setSource(a.text,c):I&&r.push({path:c,code:a.text+`//# sourceURL=${c}`})}return r}o(le,"transpileFiles");async function W(i,e={}){let r=(await le([i],e)).shift();if(!r)throw new d("Failed to transpile file: No output generated");return r}o(W,"transpileFile");async function _e(i){let e={minify:!1,format:"cjs",outdir:Bt(i),platform:"node",logLevel:"silent",packages:"external",minifySyntax:!0,preserveSymlinks:!0,minifyWhitespace:!0,minifyIdentifiers:!1},t={exports:{}},{code:r,path:s}=await W(i,e),n=Jt(s);try{await $(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(_e,"parseConfigurationFile");async function X(i="",e){let t={...Le};if(i&&qt(i)){let r=await _e(i);r&&(t={...t,...r,exclude:[...t.exclude??[],...r.exclude??[]]})}return{...t,...e}}o(X,"configuration");var zt="xJet/config.xjet.ts",he={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:zt,normalize:!0,coerce:o(i=>Ut(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"}},Wt=[["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 Xt(){let i=Be(process.argv).options({config:he.config}).parseSync();return(await X(i.config,i)).userArgv??{}}o(Xt,"getUserArgv");async function Je(i){let e=await Xt(),t=Be(Gt(i)),r=t.showHelp;t.showHelp=function(n){return console.log(G()),this.group(Object.keys(he),"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(he).epilogue("For more information, check the documentation").help().alias("help","h").strict().version();return Wt.forEach(([n,a])=>{s.example(n,a)}),s.parseSync()}o(Je,"parseArguments");import{join as jr}from"path";import{exit as we}from"process";import{accessSync as pr}from"fs";import{readFile as ur,watch as fr}from"fs/promises";import{dirname as mr,join as dr,normalize as lr}from"path";import{join as Kt,relative as Ht}from"path";import{existsSync as Vt,readdirSync as Qt}from"fs";function ge(i){return Ht(f(u).rootPath,i)}o(ge,"getRelativePath");function qe(i,e,t,r,s={}){if(!Vt(i))return{};let n=Qt(i,{withFileTypes:!0});for(let a of n){let c=Kt(i,a.name),y=ge(c);if(T(y,t))continue;if(a.isDirectory()){qe(c,e,t,r,s);continue}if((r.length===0||T(y,r))&&T(c,e)){let F=y,p=F.replace(/\.[^/.]+$/,"");s[p]=F}}return s}o(qe,"collectFilesFromDir");function Ue(i,e){let t=P(e?.suites??[]),r=P(e?.files??[]),s=P(e?.exclude??[]);return qe(i,r,s,t)}o(Ue,"getSpecFiles");var Yt=/\?/g,Zt=/\{([^}]+)\}/g,er=/(?:\/|^)\*{2}(?:\/|$)/g,tr=/(?<!\.)\*/g,rr=/\\\[([^\]]+)\\\]/g,sr=/[.+$|[\]\\]/g;function ir(i){let e=o(r=>r.replace(sr,"\\$&"),"escapeRegexChars"),t=o(r=>r.replace(Yt,".").replace(er,".*/?").replace(tr,"[^/]+").replace(rr,(s,n)=>`[${n}]`).replace(Zt,(s,n)=>`(${n.split(",").join("|")})`),"convertGlobToRegex");return new RegExp(`^${t(e(i))}$`)}o(ir,"compileGlobPattern");function nr(i){let e=/[*?[\]{}!@+()|\]]/.test(i),t=/{[^}]+}/.test(i),r=/@\([^)]+\)/.test(i);return e||t||r}o(nr,"isGlob");function T(i,e){return e.some(t=>t.test(i))}o(T,"matchesAny");function P(i){return i.map(e=>{if(e instanceof RegExp)return e;if(nr(e))return ir(e);let t=ge(e).replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${t}$`)})}o(P,"compilePatterns");import{relative as Ge}from"path";import{readFileSync as or}from"fs";import{pathToFileURL as ar}from"url";import{createRequire as cr}from"module";var ze=new Map;function We(i="tsconfig.json"){let e=or(i,"utf8"),r=JSON.parse(e).compilerOptions?.paths;if(r)for(let[s,n]of Object.entries(r))Array.isArray(n)&&n.length>0&&ze.set(s.replace("*",""),n[0].replace("*",""))}o(We,"updateAliases");function Xe(i){let e=f(u);for(let[t,r]of ze.entries())if(i.includes(t)){let s=i.replace(t,r);return Ge(e.rootPath,s)}try{let r=cr(ar(e.rootPath+"/__placeholder__.js").href).resolve(i);if(r)return Ge(e.rootPath,r)}catch{return}}o(Xe,"resolveImport");var K=class i{constructor(e,t,r){this.testsFile=t;this.exec=r;We(),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=f(u);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=fr(this.framework.rootPath,{recursive:!0});for await(let{filename:r}of t){if(!r)continue;let s=lr(r);T(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 pr(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(T(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 ur(e,"utf-8"),s=[];for(let n of r.matchAll(i.IMPORT_REGEX)){let a=n.groups?.path;if(!a)continue;let c=Xe(a)??dr(mr(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(T(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 Z}from"@remotex-labs/xansi/xterm.component";import{existsSync as xr}from"fs";import{createRequire as vr}from"module";var M=(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))(M||{});import{dirname as hr}from"path";import{mkdirSync as gr,writeFileSync as yr}from"fs";var O=class{constructor(e,t){this.logLevel=e;this.outFilePath=t}static{o(this,"AbstractReporter")}};var D=class extends O{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=hr(this.outFilePath);gr(t,{recursive:!0}),yr(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 Sr}from"path";import{mkdirSync as Ir,writeFileSync as kr}from"fs";var H=class extends D{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=Sr(this.outFilePath);Ir(t,{recursive:!0}),kr(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)}
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={..._e};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 _r}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(E(l,t))continue;if(a.isDirectory()){Ge(c,e,t,r,s);continue}if((r.length===0||E(l,r))&&E(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 E(i,e){return e.some(t=>t.test(i))}o(E,"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);E(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(E(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(E(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 Er}from"fs";import{createRequire as wr}from"module";var D=(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))(D||{});import{dirname as Sr}from"path";import{mkdirSync as Ir,writeFileSync as kr}from"fs";var O=class{constructor(e,t){this.logLevel=e;this.outFilePath=t}static{o(this,"AbstractReporter")}};var j=class extends O{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
- ${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,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}};import{ANSI as ye,writeRaw as He}from"@remotex-labs/xansi";import{xterm as w}from"@remotex-labs/xansi/xterm.component";import{ShadowRenderer as Ve}from"@remotex-labs/xansi/shadow.service";import{xterm as j}from"@remotex-labs/xansi/xterm.component";var V=4,m={todo:j.hex("#da5aec"),failed:j.hex("#F08080"),passed:j.hex("#90EE90"),skipped:j.hex("#fcaa63"),running:j.hex("#FFD966"),pending:j.hex("#808080")},Ke={5:m.pending("[ Pending ]"),0:m.running("[ RUNNING ]"),4:m.skipped("[ SKIPPED ]"),3:m.passed("[ PASSED ]"),2:m.failed("[ FAILED ]")};var q=class extends O{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 Ve(r-V-1,s,1,0),this.status=new Ve(V,s,r-V,0)}init(e,t){He(ye.HIDE_CURSOR),He(ye.CLEAR_SCREEN_UP),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)+w.gray(` [${e.ancestry.join(" > ")}]`)),r.push(...e.message.split(`
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,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}};import{ANSI as Se,writeRaw as Qe}from"@remotex-labs/xansi";import{xterm as w}from"@remotex-labs/xansi/xterm.component";import{ShadowRenderer as Ye}from"@remotex-labs/xansi/shadow.service";import{xterm as L}from"@remotex-labs/xansi/xterm.component";var Q=4,m={todo:L.hex("#da5aec"),failed:L.hex("#F08080"),passed:L.hex("#90EE90"),skipped:L.hex("#fcaa63"),running:L.hex("#FFD966"),pending:L.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 O{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)+w.gray(` [${e.ancestry.join(" > ")}]`)),r.push(...e.message.split(`
37
37
  `).map(s=>" ".repeat(2)+s)),e.invocation&&r.push(w.gray(`at (${e.invocation.source}:${e.invocation.line}:${e.invocation.column})`));for(let s of r)t.details.push(s);t.details.push(""),this.renderSuites()}suiteStart(e){let t=this.ensureSuite(e.runner,e.suite);t.title=this.getPrefix(0,e.runner,e.suite),this.renderSuites()}suiteEnd(e){this.suites.total+=1;let t=this.ensureSuite(e.runner,e.suite),r=3;e.error?(this.suites.failed+=1,r=2):t.total===t.skipped+t.todo?(this.suites.skipped+=1,r=4):t.failed>0?(this.suites.failed+=1,r=2):this.suites.passed+=1;let s=this.getPrefix(r,e.runner,e.suite);s+=` ${(e.duration/1e3).toFixed(3)} s`,t.title=s,e.error&&t.details.push(...this.parseError(e.error)),this.renderSuites()}describeEnd(e){let t=this.ensureSuite(e.runner,e.suite);if(e.errors?.length){t.failed+=1;for(let r of e.errors)t.details.push(...this.parseError(r))}}testStart(e){let t=this.ensureSuite(e.runner,e.suite);(e.todo||e.skipped)&&this.incrementTestCounters(e.todo?"todo":"skipped",t)}testEnd(e){let t=this.ensureSuite(e.runner,e.suite);if(e.errors&&e.errors.length>0){this.incrementTestCounters("failed",t);let r=m.failed(`\u25CF ${e.ancestry.join(" > ")} > ${e.description}`);r+=w.gray(` (${(e.duration/1e3).toFixed(3)} s)`),t.details.push(r);for(let s of e.errors)t.details.push(...this.parseError(s))}else this.incrementTestCounters("passed",t)}finish(){this.updateInterval?.close(),this.updateState(),this.info.clearScreen(),this.status.clearScreen(),this.info.flushToTerminal(),this.status.flushToTerminal()}getSuiteKey(e,t){return`${e}::${t}`}ensureSuite(e,t){return this.suiteMap.get(this.getSuiteKey(e,t))}createTests(){return{total:0,passed:0,failed:0,skipped:0,todo:0}}createSuites(){return{total:0,passed:0,failed:0,skipped:0}}parseError(e){let t=["",...e.message.split(`
38
38
  `),""];return t.push(...e.formatCode.split(`
39
39
  `).map(r=>w.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: ${w.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,ye.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?"":w.burntOrange(` [ ${t.padEnd(this.maxRunnerNameLength)} ]`);return`${Ke[e]}${s} ${w.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=w.cyanBright;break;case 4:t=m.running;break}return t(`[ ${e.level.toLowerCase()} ]`)}};async function Er(i){return W(i,{minify:!1,format:"cjs",platform:"node",logLevel:"silent",packages:"external"})}o(Er,"transpile");async function Tr(i){let{code:e,path:t}=await Er(i);try{let r={exports:{default:void 0}},s=vr(t),n={Error,Buffer,RegExp,module:r,process,console,require:s,setTimeout,setInterval};return await $(e,n,{filename:t}),r.exports.default}catch(r){throw new b(r)}}o(Tr,"parseExternalReporter");async function Qe(i){let{reporter:e,outputFile:t}=i,r={json:D,junit:H,default:q};if(r[e]||!xr(e)){let n=r[e]||q;return new n(M[i.logLevel]??0,t)}let s=await Tr(e);if(!s)throw new d(`Reporter at "${e}" does not have a valid default export`);if(typeof s!="function")throw new d(`Reporter at "${e}" is not a valid constructor`);try{return new s(4,t)}catch(n){throw new b(n)}}o(Qe,"getReporter");var Q=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=f(u);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:M[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,U(s,t))):this.structuredError(r,U(r,t))}catch(r){return this.structuredError(r,U(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{relative as Pr}from"path";import*as Rr from"process";import{createRequire as Ar}from"module";import{serializeError as Cr}from"@remotex-labs/xjet-expect";import br from"events";import{serializeError as Fn}from"@remotex-labs/xjet-expect";import{Struct as L}from"@remotex-labs/xstruct";var wr=new L({line:"UInt32LE",column:"UInt32LE",source:"string"}),Se=new L({kind:"UInt8:4",suiteId:{type:"string",size:14},runnerId:{type:"string",size:14},timestamp:"string"}),Ye=new L({level:"UInt8",message:{type:"string",lengthType:"UInt32LE"},ancestry:{type:"string",lengthType:"UInt32LE"},invocation:wr}),Ie=new L({error:{type:"string",lengthType:"UInt32LE"}}),Ze=new L({type:"UInt8:5",todo:"UInt8:1",skipped:"UInt8:1",duration:"UInt32LE",ancestry:{type:"string",lengthType:"UInt32LE"},description:{type:"string",lengthType:"UInt32LE"}}),et=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 tt={1:Ye,2:Ie,3:Ze,4:et};function rt(i){let e=Se.size,t=Se.toObject(i,c=>{e+=c}),r=t.kind,s=tt[r];if(!s)throw new Error(`Unknown packet kind: ${r}`);let n=i.subarray(e),a=s.toObject(n);return{...t,...a}}o(rt,"decodePacket");var st,xe;st=[E({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())}}};xe=k(null),R=v(xe,0,"QueueService",st,R),x(xe,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 br;framework=f(u);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=rt(e),r=this.suites.get(t.suiteId);if(!r)throw new d(`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 d(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 d("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 it,ve,Fr;it=[E({scope:"singleton"})];var A=class extends(Fr=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=Pr(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={exports:{}},n=Ar(t),a=Object.freeze({...Rr,stdout:{write:o(()=>{},"write")},stderr:{write:o(()=>{},"write")}}),c={Buffer,module:s,require:n,setTimeout,setInterval,clearTimeout,clearInterval,process:a,__XJET:{runtime:{bail:this.config.bail,path:this.suites.get(r),filter:this.config.filter,timeout:this.config.timeout,suiteId:r,runnerId:this.runnerId,randomize:this.config.randomize}},dispatch:this.dispatch.bind(this)};await $(e,c)}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(Cr(c)),suiteId:s,runnerId:this.runnerId,timestamp:new Date},this.suites.get(s))}})}};ve=k(Fr),A=v(ve,0,"LocalService",it,A),x(ve,1,A);import $r from"yargs";import{relative as Mr}from"path";import{serializeError as Or}from"@remotex-labs/xjet-expect";var Y=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}`)}};async function Ee(i,e,t,r){let s=typeof i=="function"?Promise.resolve(i()):Promise.resolve(i);if(e===-1||!globalThis?.setTimeout)return s;let n,a=new Promise((c,y)=>{n=globalThis?.setTimeout?.(()=>y(new Y(e,t,r)),e)});try{return await Promise.race([s,a])}finally{globalThis?.clearTimeout?.(n)}}o(Ee,"withTimeout");var nt,Te,Dr;nt=[E({scope:"singleton"})];var C=class extends(Dr=N){static{o(this,"ExternalService")}runners=new Map;async initTarget(){if(!this.config.testRunners||this.config.testRunners.length===0)throw new d("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 d(`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=Mr(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(Or(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){return`globalThis.__XJET = ${JSON.stringify(t)}; ${e}`}};Te=k(Dr),C=v(Te,0,"ExternalService",nt,C),x(Te,1,C);var Lr={js:`
44
- `},Nr={js:"state.run({})"},ee=class{constructor(e){this.config=e;this.target=this.createTarget()}static{o(this,"SuitesService")}target;framework=f(u);async executeSuites(){let e=Ue(this.framework.rootPath,this.config);if(Object.keys(e).length===0)throw this.config.suites.length>0?Z.redBright("No test files found for ")+Z.greenBright(this.config.suites.join(", ")):Z.redBright("No test files found for ")+Z.greenBright(this.config.files.join(", "));await this.target.initTarget?.();let t=new Q(this.target,await Qe(this.config));await this.exec(t,e),this.config.watch&&await this.watchForChanges(t,e),await this.target.freeTarget?.(),t.hasError&&we(1),t.hasSuiteError&&we(2),we(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?f(C,this.config):f(A,this.config)}async watchForChanges(e,t){await new K(this.config,t,this.exec.bind(this,e)).init()}async transpileSuites(e){return await le(e,{...this.config.build,banner:Lr,footer:Nr,format:"cjs",minify:!1,inject:[jr(this.framework.distPath,"shared.js")],logLevel:"silent",sourcemap:!0,keepNames:!0,minifySyntax:!0,preserveSymlinks:!0,minifyWhitespace:!0,minifyIdentifiers:!1})}};async function _r(i){let e=await Je(i);e.verbose&&(globalThis.VERBOSE=!0);let t=await X(e.config,e);t.verbose&&(globalThis.VERBOSE=!0),["json","junit"].includes(t.reporter)?globalThis.NO_COLOR=!0:console.log(G()),await new ee(t).executeSuites()}o(_r,"main");_r(process.argv);
42
+ Time: ${w.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?"":w.burntOrange(` [ ${t.padEnd(this.maxRunnerNameLength)} ]`);return`${Ve[e]}${s} ${w.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=w.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=wr(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]||!Er(e)){let n=r[e]||U;return new n(D[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:D[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{relative as Cr}from"path";import*as Fr from"process";import{createRequire as $r}from"module";import{serializeError as Mr}from"@remotex-labs/xjet-expect";import Ar from"events";import{serializeError as Dn}from"@remotex-labs/xjet-expect";import{Struct as N}from"@remotex-labs/xstruct";var Rr=new N({line:"UInt32LE",column:"UInt32LE",source:"string"}),Ie=new N({kind:"UInt8:4",suiteId:{type:"string",size:14},runnerId:{type:"string",size:14},timestamp:"string"}),et=new N({level:"UInt8",message:{type:"string",lengthType:"UInt32LE"},ancestry:{type:"string",lengthType:"UInt32LE"},invocation:Rr}),ke=new N({error:{type:"string",lengthType:"UInt32LE"}}),tt=new N({type:"UInt8:5",todo:"UInt8:1",skipped:"UInt8:1",duration:"UInt32LE",ancestry:{type:"string",lengthType:"UInt32LE"},description:{type:"string",lengthType:"UInt32LE"}}),rt=new N({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 _=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 ot,xe,Dr;ot=[x({scope:"singleton"})];var A=class extends(Dr=_){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=Cr(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={exports:{}},n=$r(t),a=Object.freeze({...Fr,stdout:{write:o(()=>{},"write")},stderr:{write:o(()=>{},"write")}}),c={Buffer,module:s,require:n,setTimeout,setInterval,clearTimeout,clearInterval,process:a,__XJET:{runtime:{bail:this.config.bail,path:this.suites.get(r),filter:this.config.filter,timeout:this.config.timeout,suiteId:r,runnerId:this.runnerId,randomize:this.config.randomize}},dispatch:this.dispatch.bind(this)};await M(e,c)}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(Mr(c)),suiteId:s,runnerId:this.runnerId,timestamp:new Date},this.suites.get(s))}})}};xe=k(Dr),A=T(xe,0,"LocalService",ot,A),v(xe,1,A);import Or from"yargs";import{relative as jr}from"path";import{serializeError as Lr}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 at,Ee;at=[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(){globalThis.setTimeout=this.originalSetTimeout,globalThis.clearTimeout=this.originalClearTimeout,globalThis.setInterval=this.originalSetInterval,globalThis.clearInterval=this.originalClearInterval,Date.now=this.originalDateNow}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)}}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}}}};Ee=k(null),C=T(Ee,0,"TimerService",at,C),v(Ee,1,C);async function we(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(we,"withTimeout");var ct,be,Nr;ct=[x({scope:"singleton"})];var F=class extends(Nr=_){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=Or(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=jr(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 we(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(Lr(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 we(r?.dispatch?.(Buffer.from(n),t),r?.dispatchTimeout??5e3,`dispatch of runner "${r.name}"`)}prepareTestCodeWithContext(e,t){return`globalThis.__XJET = ${JSON.stringify(t)}; ${e}`}};be=k(Nr),F=T(be,0,"ExternalService",ct,F),v(be,1,F);var Br={js:`
44
+ `},Jr={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:Br,footer:Jr,format:"cjs",minify:!1,inject:[_r(this.framework.distPath,"shared.js")],logLevel:"silent",sourcemap:!0,keepNames:!0,minifySyntax:!0,preserveSymlinks:!0,minifyWhitespace:!0,minifyIdentifiers:!1})}};async function qr(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(qr,"main");qr(process.argv);
45
45
  //# sourceMappingURL=bash.js.map