UNPKG

instant-mocha

Version:

Build tests with Webpack and run them with Mocha in one command

7 lines (6 loc) 7.82 kB
#!/usr/bin/env node "use strict";var _=Object.defineProperty;var $=e=>{throw TypeError(e)};var V=(e,t,n)=>t in e?_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var s=(e,t)=>_(e,"name",{value:t,configurable:!0});var S=(e,t,n)=>V(e,typeof t!="symbol"?t+"":t,n),k=(e,t,n)=>t.has(e)||$("Cannot "+n);var q=(e,t,n)=>(k(e,t,"read from private field"),n?n.call(e):t.get(e)),T=(e,t,n)=>t.has(e)?$("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),F=(e,t,n,o)=>(k(e,t,"write to private field"),o?o.call(e,n):t.set(e,n),n);var d,de=require("module"),C=require("mocha/lib/cli/run.js"),B=require("mocha/lib/cli/options.js"),Q=require("yargs/yargs"),E=require("path"),j=require("assert"),z=require("mocha/lib/cli/collect-files.js"),I=require("os"),H=require("mocha"),v=require("mocha/lib/suite.js"),P=require("memfs"),D=require("fs-require"),J=require("@cspotcode/source-map-support"),W=require("webpack"),K=require("fs"),G=require("url"),me=typeof document!="undefined"?document.currentScript:null,u=require;function X(e,t=1,n={}){const{indent:o=" ",includeEmptyLines:r=!1}=n;if(typeof e!="string")throw new TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof e}\``);if(typeof t!="number")throw new TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof t}\``);if(t<0)throw new RangeError(`Expected \`count\` to be at least 0, got \`${t}\``);if(typeof o!="string")throw new TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof o}\``);if(t===0)return e;const i=r?/^/gm:/^(?!\s*$)/gm;return e.replace(i,o.repeat(t))}s(X,"indentString");function Y(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}s(Y,"escapeStringRegexp");const M=/\s+at.*[(\s](.*)\)?/,Z=/^(?:(?:(?:node|node:[\w/]+|(?:(?:node:)?internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)(?:\.js)?:\d+:\d+)|native)/,ee=typeof I.homedir=="undefined"?"":I.homedir().replace(/\\/g,"/");function te(e,{pretty:t=!1,basePath:n}={}){const o=n&&new RegExp(`(at | \\()${Y(n.replace(/\\/g,"/"))}`,"g");if(typeof e=="string")return e.replace(/\\/g,"/").split(` `).filter(r=>{const i=r.match(M);if(i===null||!i[1])return!0;const a=i[1];return a.includes(".app/Contents/Resources/electron.asar")||a.includes(".app/Contents/Resources/default_app.asar")||a.includes("node_modules/electron/dist/resources/electron.asar")||a.includes("node_modules/electron/dist/resources/default_app.asar")?!1:!Z.test(a)}).filter(r=>r.trim()!=="").map(r=>(o&&(r=r.replace(o,"$1")),t&&(r=r.replace(M,(i,a)=>i.replace(a,a.replace(ee,"~")))),r)).join(` `)}s(te,"cleanStack");const ne=s(e=>e.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g,""),"cleanInternalStack"),R=class R extends Error{constructor(n){if(!Array.isArray(n))throw new TypeError(`Expected input to be an Array, got ${typeof n}`);n=n.map(r=>r instanceof Error?r:r!==null&&typeof r=="object"?Object.assign(new Error(r.message),r):new Error(r));let o=n.map(r=>typeof r.stack=="string"&&r.stack.length>0?ne(te(r.stack)):String(r)).join(` `);o=` `+X(o,4);super(o);T(this,d);S(this,"name","AggregateError");F(this,d,n)}get errors(){return q(this,d).slice()}};d=new WeakMap,s(R,"AggregateError");let h=R;const f=P.createFsFromVolume(new P.Volume);f.join=E.join;let A;const re=s(e=>{const t=D.createFsRequire(f,{fs:!0});return A=t.id,t(e)},"mRequire");J.install({environment:"node",retrieveFile(e){const t=`fs-require://${A}/`;if(e.startsWith(t)&&(e=e.slice(t.length-1)),f.existsSync(e))return f.readFileSync(e).toString()}});function ie(e){const t=new H(e);function n(){return new Promise(o=>{this.run.call(this,o)})}return s(n,"$run"),t.$run=n,t.loadFilesAsync=s(async function(){const{suite:r,files:i}=this;this.lazyLoadFiles(!0);for(let a of i)a=E.posix.resolve(a),r.emit(v.constants.EVENT_FILE_PRE_REQUIRE,global,a,this),r.emit(v.constants.EVENT_FILE_REQUIRE,await re(a),a,this),r.emit(v.constants.EVENT_FILE_POST_REQUIRE,global,a,this)},"loadFilesAsync"),t}s(ie,"createMochaInstance");async function L(e){const t=ie(e);return t.files=["/main.js"],await t.loadFilesAsync(),await t.$run()}s(L,"runMocha");function oe(e,t){var n,o,r;const i={...e};if(i.entry=t,i.output={...e.output,path:"/",publicPath:"",filename:"main.js",globalObject:"this",libraryTarget:"commonjs2"},(n=i.optimization)!=null&&n.runtimeChunk&&(i.optimization.runtimeChunk=void 0),!Array.isArray(i.externals)){const{externals:l}=i;i.externals=[],l&&i.externals.push(l)}if(((o=W.version)==null?void 0:o.split(".")[0])>"4")i.externalsPresets||(i.externalsPresets={}),i.externalsPresets.node=!0,Object.assign(i.output,{chunkLoading:"require",chunkFormat:"commonjs"});else{const l=u("webpack/lib/LoaderTargetPlugin"),m=u("webpack/lib/FunctionModulePlugin"),g=u("webpack/lib/node/NodeTemplatePlugin"),c=u("webpack/lib/node/ReadFileCompileWasmTemplatePlugin"),b=u("webpack/lib/node/NodeTargetPlugin"),U=(r=i.target)!=null?r:"web";i.target=p=>{new g().apply(p),new c(i.output).apply(p),new m(i.output).apply(p),new b().apply(p),new l(U).apply(p)}}const a=W(i);a.outputFileSystem=f;function y(){return new Promise((l,m)=>{this.run((g,c)=>{if(g){m(g);return}if(c.hasErrors()){m(new h(c.compilation.errors));return}if(c.hasWarnings())for(const b of c.compilation.warnings)console.log(b);l(c)})})}return s(y,"$run"),a.$run=y,a}s(oe,"createWebpackCompiler");function ae(e){return new Function("id","return import(id);")(e)}s(ae,"importESM");async function se(e){try{return u(e)}catch(t){if(t.code==="ERR_REQUIRE_ESM"){process.platform==="win32"&&(e=G.pathToFileURL(e).href);const{default:n}=await ae(e);return n}throw new Error(`Faild to load Webpack configuration: ${e}`)}}s(se,"loadWebpackConfig");async function ce(e,t){j(K.existsSync(e),`Invalid Webpack configuration path: ${e}`);const n=await se(e);if(typeof n=="function"){const o={};t.watch?o.WEBPACK_WATCH=!0:o.WEBPACK_BUILD=!0;const r={env:o};return t.mode&&(r.mode=t.mode),t.watch&&(r.watch=t.watch),n(o,r)}return t.mode&&(n.mode=t.mode),n}s(ce,"getWebpackConfig");const w="\x1B[",N=`${w}2J`,ue=process.platform==="win32"?`${N}${w}0f`:`${N}${w}3J${w}H`;async function le(e){j(e.webpackConfig,"Webpack configuration path must be passed in");const t=E.resolve(e.webpackConfig),n=await ce(t,e),o=z({ignore:[],file:[],...e});e.watch&&(n.plugins||(n.plugins=[]),n.plugins.unshift({apply(i){i.hooks.watchRun.tap("InstantMocha",()=>{process.stdout.write(ue)})}}));const r=oe(n,Array.isArray(o)?o:o.files);if(e.watch)r.watch({},(i,a)=>{if(i){console.log(i);return}if(a.hasErrors()){console.log(new h(a.compilation.errors));return}if(a.hasWarnings())for(const y of a.compilation.warnings)console.log(y);setImmediate(()=>{L(e)})});else return await r.$run(),await L(e)}s(le,"instantMocha");const{version:pe}=u("../package.json"),x="instant-mocha options",O=B.loadOptions(process.argv.slice(2));Q().scriptName("instant-mocha").command({...C,command:["$0 [spec..]"],describe:"Build tests with Webpack and run them with Mocha",builder(e){const t=new Set(["watch","watch-files","watch-ignore"]),n=Object.assign(Object.create(e),{options(o){const r={};for(const i in o)t.has(i)||(r[i]=o[i]);return e.options.call(this,r)}});C.builder(n)},async handler(e){try{await le(e)>0&&process.exit(1)}catch(t){console.error(t),process.exit(1)}}}).options({"webpack-config":{description:"Path to Webpack configuration",group:x,type:"string",default:"webpack.config.js"},watch:{description:"Watch mode",group:x},mode:{description:"Mode passed to webpack development|production",group:x,type:"string",alias:"m"}}).help("help","Show usage information & exit").alias("help","h").version("version","Show version number & exit",pe).alias("version","V").wrap(process.stdout.columns?Math.min(process.stdout.columns,80):80).config(O).parse(O._);