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