vite-plugin-bundle-obfuscator
Version:
JavaScript obfuscator plugin for Vite environments
3 lines (2 loc) • 5.8 kB
JavaScript
import{fileURLToPath as V}from"url";import I from"path";var W=()=>V(import.meta.url),U=()=>I.dirname(W()),m=U();import*as S from"vite";import{Worker as X}from"node:worker_threads";import q from"node:path";import J from"node:os";import{gzipSync as Q}from"node:zlib";import Y from"javascript-obfuscator";function G(t){return Object.prototype.toString.call(t)==="[object RegExp]"}function K(t){return Object.prototype.toString.call(t)==="[object String]"}function p(t){return Object.prototype.toString.call(t)==="[object Object]"}function v(t){return Array.isArray(t)}function E(t){let e=Object.prototype.toString.call(t);return e==="[object Function]"||e==="[object AsyncFunction]"}function b(t){return Object.prototype.toString.call(t)==="[object Boolean]"}function R(t,e){for(let o of e)if(G(o)){if(o.test(t))return!0}else if(K(o)&&t.includes(o))return!0;return!1}var k={excludes:[],enable:!0,log:!0,apply:"build",autoExcludeNodeModules:!1,threadPool:!1,options:{compact:!0,controlFlowFlattening:!0,controlFlowFlatteningThreshold:1,deadCodeInjection:!1,debugProtection:!1,debugProtectionInterval:0,disableConsoleOutput:!1,identifierNamesGenerator:"hexadecimal",log:!1,numbersToExpressions:!1,renameGlobals:!1,selfDefending:!0,simplify:!0,splitStrings:!1,ignoreImports:!0,stringArray:!0,stringArrayCallsTransform:!0,stringArrayCallsTransformThreshold:.5,stringArrayEncoding:[],stringArrayIndexShift:!0,stringArrayRotate:!0,stringArrayShuffle:!0,stringArrayWrappersCount:1,stringArrayWrappersChainedCalls:!0,stringArrayWrappersParametersMaxCount:2,stringArrayWrappersType:"variable",stringArrayThreshold:.75,unicodeEscapeSequence:!1}},L="node_modules",x="vendor-modules",M="vendor-",C=(n=>(n.B="B",n.KB="KB",n.MB="MB",n))(C||{}),g=Object.freeze({info:"\x1B[36m",warn:"\x1B[33m",success:"\x1B[32m"});var h=class{constructor(e){this._log=e?console.log.bind(console):this.noop}noop(){}forceLog(...e){console.log(...e)}info(e){this._log(e)}};function j(){return S?.version?Number(S.version.split(".")[0]):2}function Z(t){let e=Math.floor(t/36e5),o=Math.floor(t%36e5/6e4),n=Math.floor(t%6e4/1e3);return[e?`${e}h `:"",o?`${o}m `:"",n||!e&&!o?`${n}s`:""].filter(Boolean).join("")}function T(t){return b(t)?t:p(t)&&"enable"in t?t.enable:!1}function F(t){return T(t.threadPool)}function _(t){return T(t.autoExcludeNodeModules)}function N(t){let{autoExcludeNodeModules:e}=t;return b(e)?[]:p(e)&&e.enable?e.manualChunks||[]:[]}function O(t){return M+t}function P(t){let{threadPool:e}=t,o=J.cpus().length;return b(e)?o:p(e)&&e.enable&&e.size?e.size:o}function A(t,e){let o=[];return Object.entries(e).forEach(([n,r])=>{"code"in r&&r.code&&!R(n,t.excludes)&&o.push([n,r])}),o}function w(t,e){for(let o of e)if(t.includes(o))return O(o);return x}function $(t,e,o){let n=new h(t.log);n.info(`obfuscating ${e}...`);let r=Y.obfuscate(o.code,t.options).getObfuscatedCode();return n.info(`obfuscation complete for ${e}.`),r}function D(t,e){return new Promise((o,n)=>{let r=new X(q.join(m,"./worker/index.mjs"));r.postMessage({config:t,chunk:e}),r.on("message",i=>{e.forEach(([s,c])=>{let u=i.find(a=>a.fileName===s);u&&u.obfuscatedCode&&(c.code=u.obfuscatedCode)}),o(i),r.unref()}),r.on("error",i=>{n(i),r.unref()})})}function B(t){let e=Object.values(C),o=0;for(;t>=1024&&o<e.length-1;)t/=1024,o++;return{value:Number(t.toFixed(2)),unit:e[o]}}var z=class{constructor(e){this._log=e,this.originalSize=this.createEmptySizeResult(),this.obfuscatedSize=this.createEmptySizeResult(),this.startTime=0,this.endTime=0}createEmptySizeResult(){return{original:{value:0,unit:"B"},gzip:{value:0,unit:"B"}}}start(e){this.startTime=performance.now(),this.originalSize=this.calculateBundleSize(e)}end(e){this.obfuscatedSize=this.calculateBundleSize(e),this.endTime=performance.now(),this.logResult()}calculateBundleSize(e){let{totalSize:o,gzipSize:n}=e.reduce((r,[,i])=>{if(i.code){let{code:s}=i;r.totalSize+=Buffer.byteLength(s,"utf-8"),r.gzipSize+=Q(s,{level:9}).byteLength}return r},{totalSize:0,gzipSize:0});return{original:B(o),gzip:B(n)}}analyze(){let{originalSize:e,obfuscatedSize:o}=this,n=Z(this.endTime-this.startTime),r=((o.original.value-e.original.value)/e.original.value*100).toFixed(2),i=((o.gzip.value-e.gzip.value)/e.gzip.value*100).toFixed(2);return`\u2713 obfuscated in ${n} | \u{1F4E6} ${e.original.value}${e.original.unit} (gzip: ${e.gzip.value}${e.gzip.unit}) \u2192 \u{1F512} ${o.original.value}${o.original.unit} (gzip: ${o.gzip.value}${o.gzip.unit}) | \u{1F4C8} ${r}% (gzip: ${i}%)`}logResult(){this._log.forceLog(g.success+"%s\x1B[0m",this.analyze())}};function ee(t){let e={...k,...t},o=new h(e.log),n=i=>{if(!e.enable||!_(e))return;i.build=i.build||{},i.build.rollupOptions=i.build.rollupOptions||{};let{output:s}=i.build.rollupOptions,c=[...N(e)],u=()=>{e.excludes.push(x,...c.map(O))},a=l=>{if(l.includes(L))return w(l,c)};if(!s){u(),i.build.rollupOptions.output={manualChunks:a};return}if(v(s)){o.forceLog(g.warn,"rollupOptions.output is an array, ignoring autoExcludeNodeModules configuration.");return}if(p(s)){if(!s.manualChunks)u(),s.manualChunks=a;else if(p(s.manualChunks))o.forceLog(g.warn,"rollupOptions.output.manualChunks is an object, ignoring autoExcludeNodeModules configuration.");else if(E(s.manualChunks)){let l=s.manualChunks;u(),s.manualChunks=(d,f)=>a(d)||l(d,f)}}},r=async(i,{bundle:s})=>{if(!e.enable||!s)return i;o.forceLog(g.info+`
starting obfuscation process...`);let c=new z(o),u=A(e,s);if(c.start(u),F(e)){let a=Math.min(P(e),u.length),l=Math.ceil(u.length/a),d=[];for(let f=0;f<a;f++){let H=u.slice(f*l,(f+1)*l);d.push(D(e,H))}await Promise.all(d)}else u.forEach(([a,l])=>{l.code=$(e,a,l)});return c.end(u),i};return{name:"vite-plugin-bundle-obfuscator",apply:e.apply,config:n,transformIndexHtml:j()>=5?{order:"post",handler:r}:{enforce:"post",transform:r}}}export{ee as default};