vite-plugin-bundle-obfuscator
Version:
JavaScript obfuscator plugin for Vite environments
3 lines (2 loc) • 9.62 kB
JavaScript
import fe from"path";import{fileURLToPath as ge}from"url";var de=()=>ge(import.meta.url),me=()=>fe.dirname(de()),O=me();import*as $ from"vite";import{Worker as Oe}from"worker_threads";import N from"path";import ke from"os";import{gzipSync as Ce}from"zlib";import Z from"javascript-obfuscator";import Re from"@jridgewell/remapping";import{existsSync as j,readFileSync as be}from"fs";import{dirname as he,resolve as k}from"path";var{toString:C}=Object.prototype;function V(t){return C.call(t)==="[object RegExp]"}function U(t){return C.call(t)==="[object String]"}function h(t){return C.call(t)==="[object Object]"}function R(t){return Array.isArray(t)}function T(t){let e=C.call(t);return e==="[object Function]"||e==="[object AsyncFunction]"}function F(t){return C.call(t)==="[object Boolean]"}function J(t,e){return e?R(e)?e.some(n=>U(n)?t.includes(n):V(n)?n.test(t):!1):U(e)?t.includes(e):V(e)?e.test(t):!1:!1}function G(t){return!!t.build?.lib}function ye(t){if(!j(t))return!1;try{let e=JSON.parse(be(t,"utf-8"));return!!{...e.dependencies,...e.devDependencies}?.nuxt}catch{return!1}}function xe(t){return[k(t,"nuxt.config.js"),k(t,"nuxt.config.ts"),k(t,"nuxt.config.mjs"),k(t,"nuxt.config.cjs")].some(e=>j(e))}function*Se(t){let e=t;for(;;){yield e;let n=he(e);if(n===e)break;e=n}}function ze(t){let e=t?.plugins;return Array.isArray(e)?e.some(n=>typeof n?.name=="string"&&(n.name==="nuxt"||n.name.startsWith("nuxt:"))):!1}function K(t={}){if(ze(t))return!0;let e=t.root||process.cwd();for(let n of Se(e)){if(xe(n))return!0;let o=k(n,"package.json");if(j(o))return ye(o)}return!1}var X={excludes:[],enable:!0,log:!0,apply:"build",autoExcludeNodeModules:!1,threadPool:!1,obfuscateWorker:!1,obfuscateWorkerExcludes:[],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}},q="node_modules",L="vendor-modules",Q="vendor-",_=(o=>(o.B="B",o.KB="KB",o.MB="MB",o))(_||{}),S=Object.freeze({info:"\x1B[36m",warn:"\x1B[33m",success:"\x1B[32m"});var x=class{constructor(e){this._log=e?console.log.bind(console):this.noop}noop(){}forceLog(...e){console.log(...e)}info(e){this._log(e)}};function ee(){return $?.version?Number($.version.split(".")[0]):2}function ve(t){let e=Math.floor(t/36e5),n=Math.floor(t%36e5/6e4),o=Math.floor(t%6e4/1e3);return[e?`${e}h `:"",n?`${n}m `:"",o||!e&&!n?`${o}s`:""].filter(Boolean).join("")}function A(t){return F(t)?t:h(t)&&"enable"in t?t.enable:!1}function te(t){return A(t.threadPool)}function ne(t){return A(t.autoExcludeNodeModules)}function oe(t){let{autoExcludeNodeModules:e}=t;return F(e)?[]:h(e)&&e.enable?e.manualChunks||[]:[]}function I(t){return Q+t}function re(t){let{threadPool:e}=t,n=ke.cpus().length;return F(e)?n:h(e)&&e.enable&&e.size?e.size:n}function ie(t,e){let n=[];return Object.entries(e).forEach(([o,r])=>{"code"in r&&r.code&&!J(o,t.excludes)&&n.push([o,r])}),n}function se(t,e){for(let n of e)if(t.includes(n))return I(n);return L}function Be(t,e,n){return t?e?(n?.("composing source maps..."),Re([e,t],()=>null)):t:e}var v=class t{constructor(){this.obfuscatedFiles=new Set}static getInstance(){return t.instance||(t.instance=new t),t.instance}markAsObfuscated(e){e&&this.obfuscatedFiles.add(e)}isObfuscated(e){return e?this.obfuscatedFiles.has(e):!1}getAllObfuscatedFiles(){return Array.from(this.obfuscatedFiles)}clear(){this.obfuscatedFiles.clear()}serialize(){return Array.from(this.obfuscatedFiles)}updateFromSerialized(e){!e||!Array.isArray(e)||e.forEach(n=>{this.obfuscatedFiles.add(n)})}};function ae(t,e,n){let o=new x(t.log),r=v.getInstance();if(r.isObfuscated(e))return o.info(`skipping ${e} (already in obfuscated registry)`),{code:n.code,map:n.map};o.info(`obfuscating ${e}...`);let u=t.options.sourceMap?{...t.options,inputFileName:e,sourceMapFileName:`${N.basename(e)}.map`}:t.options,s=Z.obfuscate(n.code,u);return o.info(`obfuscation complete for ${e}.`),r.markAsObfuscated(e),o.info(`added ${e} to obfuscated files registry`),{code:s.getObfuscatedCode(),map:Be(JSON.parse(JSON.stringify(n.map)||"null"),JSON.parse(s.getSourceMap()||"null"),o.info.bind(o))}}function ue(t,e,n){let o=new x(t.log),r=v.getInstance();if(r.isObfuscated(e))return o.info(`skipping ${e} (already in obfuscated registry)`),{code:n,map:null};o.info(`obfuscating ${e}...`);let u=t.options.sourceMap?{...t.options,inputFileName:e,sourceMapFileName:`${N.basename(e)}.map`}:t.options,s=Z.obfuscate(n,u);return o.info(`obfuscation complete for ${e}.`),r.markAsObfuscated(e),o.info(`added ${e} to obfuscated files registry`),{code:s.getObfuscatedCode(),map:JSON.parse(s.getSourceMap()||"null")}}function le(t,e){return new Promise((n,o)=>{let r=new Oe(N.join(O,"./worker/index.mjs")),u=v.getInstance();r.postMessage({config:t,chunk:JSON.parse(JSON.stringify(e)),registryState:u.serialize()}),r.on("message",s=>{s.results&&Array.isArray(s.results)&&e.forEach(([z,M])=>{let y=s.results.find(w=>w.fileName===z);y&&y.obfuscatedCode&&(M.code=y.obfuscatedCode,M.map=y.map||null)}),s.registryState&&Array.isArray(s.registryState)&&u.updateFromSerialized(s.registryState),n(s),r.unref()}),r.on("error",s=>{o(s),r.unref()})})}function Y(t){let e=Object.values(_),n=0;for(;t>=1024&&n<e.length-1;)t/=1024,n++;return{value:Number(t.toFixed(2)),unit:e[n]}}var B=class{constructor(e){this._log=e,this.originalSize=this.createEmptySizeResult(),this.obfuscatedSize=this.createEmptySizeResult(),this.originalBytes={total:0,gzip:0},this.obfuscatedBytes={total:0,gzip:0},this.startTime=0,this.endTime=0}createEmptySizeResult(){return{original:{value:0,unit:"B"},gzip:{value:0,unit:"B"}}}start(e){this.startTime=performance.now();let{size:n,bytes:o}=this.calculateBundleSize(e);this.originalSize=n,this.originalBytes=o}end(e){let{size:n,bytes:o}=this.calculateBundleSize(e);this.obfuscatedSize=n,this.obfuscatedBytes=o,this.endTime=performance.now(),this.logResult()}calculateBundleSize(e){let{totalSize:n,gzipSize:o}=e.reduce((r,[,u])=>{if(u.code){let{code:s}=u;r.totalSize+=Buffer.byteLength(s,"utf-8"),r.gzipSize+=Ce(s,{level:9}).byteLength}return r},{totalSize:0,gzipSize:0});return{size:{original:Y(n),gzip:Y(o)},bytes:{total:n,gzip:o}}}analyze(){let{originalSize:e,obfuscatedSize:n,originalBytes:o,obfuscatedBytes:r}=this,u=ve(this.endTime-this.startTime),s=o.total>0?((r.total-o.total)/o.total*100).toFixed(2):"0.00",z=o.gzip>0?((r.gzip-o.gzip)/o.gzip*100).toFixed(2):"0.00";return`\u2713 obfuscated in ${u} | \u{1F4E6} ${e.original.value}${e.original.unit} (gzip: ${e.gzip.value}${e.gzip.unit}) \u2192 \u{1F512} ${n.original.value}${n.original.unit} (gzip: ${n.gzip.value}${n.gzip.unit}) | \u{1F4C8} ${s}% (gzip: ${z}%)`}logResult(){this._log.forceLog(S.success+"%s\x1B[0m",this.analyze())}};function Me(t){let e={...X,...t},n=new x(e.log),o=!1,r=!1,u=!1,s=async(i,l={})=>{let a=l.config??e,f=l.log??n;f.forceLog(S.info+`
starting obfuscation process...`);let b=new B(f),p=ie(a,i);if(b.start(p),te(a)){let g=Math.min(re(a),p.length),c=Math.ceil(p.length/g),d=[];for(let m=0;m<g;m++){let D=p.slice(m*c,(m+1)*c);d.push(le(a,D))}await Promise.all(d)}else p.forEach(([g,c])=>{let{code:d,map:m}=ae(a,g,c);c.code=d,c.map=m});b.end(p)},z=(i,l)=>{if(u=!!l.isSsrBuild,o=G(i),r=K(i),e.enable&&A(e.obfuscateWorker)){let g=i.worker?.plugins;i.worker=i.worker||{},i.worker.plugins=()=>{let c=g??[],d=T(c)?c():c,m=(R(d)?d:[d]).filter(Boolean);return m.some(E=>h(E)&&"name"in E&&E.name==="vite-plugin-bundle-obfuscator:worker")?m:[...m,{name:"vite-plugin-bundle-obfuscator:worker",apply:e.apply,enforce:"post",async generateBundle(E,H){if(!e.enable||!H||u)return;let W={...e,excludes:[...e.excludes,...e.obfuscateWorkerExcludes]};await s(H,{config:W,log:new x(W.log)})}}]}}if(!e.enable||!ne(e)||o||r)return;i.build=i.build||{},i.build.rollupOptions=i.build.rollupOptions||{};let{output:a}=i.build.rollupOptions,f=[...oe(e)],b=()=>{e.excludes.push(L,...f.map(I))},p=g=>{if(g.includes(q))return se(g,f)};if(!a){b(),i.build.rollupOptions.output={manualChunks:p};return}if(R(a)){n.forceLog(S.warn,"rollupOptions.output is an array, ignoring autoExcludeNodeModules configuration.");return}if(h(a)){if(!a.manualChunks)b(),a.manualChunks=p;else if(h(a.manualChunks))n.forceLog(S.warn,"rollupOptions.output.manualChunks is an object, ignoring autoExcludeNodeModules configuration.");else if(T(a.manualChunks)){let g=a.manualChunks;b(),a.manualChunks=(c,d)=>p(c)||g(c,d)}}},M=i=>{let l=i.build.sourcemap;if(l){let a=i.build.rollupOptions?.output,f=R(a)?void 0:a?.sourcemapBaseUrl;e.options={...e.options,sourceMap:!0,sourceMapMode:l==="inline"?"inline":"separate",...f&&{sourceMapBaseUrl:f}}}},y=async(i,{bundle:l})=>(!e.enable||!l||r||u||await s(l),i),w=async(i,l)=>{!e.enable||!l||o||!r||u||await s(l)},ce=(i,l)=>{if(!e.enable||!o||u)return null;let a=new B(n),f=[[l.name,{code:i}]];a.start(f);let{code:b,map:p}=ue(e,l.name,i);return a.end(f),{code:b,map:p}},pe=()=>ee()>=5?{order:"post",handler:y}:{enforce:"post",transform:y};return{name:"vite-plugin-bundle-obfuscator",apply:e.apply,config:z,configResolved:M,renderChunk:ce,transformIndexHtml:pe(),generateBundle:w}}export{Me as default};