UNPKG

vite-plugin-bundle-obfuscator

Version:
3 lines (2 loc) 10.3 kB
"use strict";var xe=Object.create;var L=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var Oe=Object.getPrototypeOf,ke=Object.prototype.hasOwnProperty;var Ce=(t,e)=>{for(var n in e)L(t,n,{get:e[n],enumerable:!0})},J=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ze(e))!ke.call(t,r)&&r!==n&&L(t,r,{get:()=>e[r],enumerable:!(o=Se(e,r))||o.enumerable});return t};var C=(t,e,n)=>(n=t!=null?xe(Oe(t)):{},J(e||!t||!t.__esModule?L(n,"default",{value:t,enumerable:!0}):n,t)),ve=t=>J(L({},"__esModule",{value:!0}),t);var Ae={};Ce(Ae,{default:()=>be});module.exports=ve(Ae);var I=C(require("vite")),ne=require("worker_threads"),P=C(require("path")),oe=C(require("os")),re=require("zlib"),H=C(require("javascript-obfuscator")),ie=C(require("@jridgewell/remapping"));var z=require("fs"),h=require("path"),{toString:v}=Object.prototype;function G(t){return v.call(t)==="[object RegExp]"}function K(t){return v.call(t)==="[object String]"}function y(t){return v.call(t)==="[object Object]"}function R(t){return Array.isArray(t)}function $(t){let e=v.call(t);return e==="[object Function]"||e==="[object AsyncFunction]"}function A(t){return v.call(t)==="[object Boolean]"}function X(t,e){return e?R(e)?e.some(n=>K(n)?t.includes(n):G(n)?n.test(t):!1):K(e)?t.includes(e):G(e)?e.test(t):!1:!1}function q(t){return!!t.build?.lib}function Re(t){if(!(0,z.existsSync)(t))return!1;try{let e=JSON.parse((0,z.readFileSync)(t,"utf-8"));return!!{...e.dependencies,...e.devDependencies}?.nuxt}catch{return!1}}function Be(t){return[(0,h.resolve)(t,"nuxt.config.js"),(0,h.resolve)(t,"nuxt.config.ts"),(0,h.resolve)(t,"nuxt.config.mjs"),(0,h.resolve)(t,"nuxt.config.cjs")].some(e=>(0,z.existsSync)(e))}function*Me(t){let e=t;for(;;){yield e;let n=(0,h.dirname)(e);if(n===e)break;e=n}}function Ee(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 Q(t={}){if(Ee(t))return!0;let e=t.root||process.cwd();for(let n of Me(e)){if(Be(n))return!0;let o=(0,h.resolve)(n,"package.json");if((0,z.existsSync)(o))return Re(o)}return!1}var Y={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}},Z="node_modules",w="vendor-modules",ee="vendor-",N=(o=>(o.B="B",o.KB="KB",o.MB="MB",o))(N||{}),O=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 se(){return I?.version?Number(I.version.split(".")[0]):2}function Fe(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 j(t){return A(t)?t:y(t)&&"enable"in t?t.enable:!1}function ae(t){return j(t.threadPool)}function ue(t){return j(t.autoExcludeNodeModules)}function le(t){let{autoExcludeNodeModules:e}=t;return A(e)?[]:y(e)&&e.enable?e.manualChunks||[]:[]}function D(t){return ee+t}function ce(t){let{threadPool:e}=t,n=oe.default.cpus().length;return A(e)?n:y(e)&&e.enable&&e.size?e.size:n}function pe(t,e){let n=[];return Object.entries(e).forEach(([o,r])=>{"code"in r&&r.code&&!X(o,t.excludes)&&n.push([o,r])}),n}function fe(t,e){for(let n of e)if(t.includes(n))return D(n);return w}function Le(t,e,n){return t?e?(n?.("composing source maps..."),(0,ie.default)([e,t],()=>null)):t:e}var B=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 ge(t,e,n){let o=new S(t.log),r=B.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:`${P.default.basename(e)}.map`}:t.options,s=H.default.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:Le(JSON.parse(JSON.stringify(n.map)||"null"),JSON.parse(s.getSourceMap()||"null"),o.info.bind(o))}}function de(t,e,n){let o=new S(t.log),r=B.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:`${P.default.basename(e)}.map`}:t.options,s=H.default.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 me(t,e){return new Promise((n,o)=>{let r=new ne.Worker(P.default.join(__dirname,"./worker/index.js")),u=B.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(([k,E])=>{let x=s.results.find(T=>T.fileName===k);x&&x.obfuscatedCode&&(E.code=x.obfuscatedCode,E.map=x.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 te(t){let e=Object.values(N),n=0;for(;t>=1024&&n<e.length-1;)t/=1024,n++;return{value:Number(t.toFixed(2)),unit:e[n]}}var M=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+=(0,re.gzipSync)(s,{level:9}).byteLength}return r},{totalSize:0,gzipSize:0});return{size:{original:te(n),gzip:te(o)},bytes:{total:n,gzip:o}}}analyze(){let{originalSize:e,obfuscatedSize:n,originalBytes:o,obfuscatedBytes:r}=this,u=Fe(this.endTime-this.startTime),s=o.total>0?((r.total-o.total)/o.total*100).toFixed(2):"0.00",k=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: ${k}%)`}logResult(){this._log.forceLog(O.success+"%s\x1B[0m",this.analyze())}};function be(t){let e={...Y,...t},n=new S(e.log),o=!1,r=!1,u=!1,s=async(i,l={})=>{let a=l.config??e,f=l.log??n;f.forceLog(O.info+` starting obfuscation process...`);let b=new M(f),p=pe(a,i);if(b.start(p),ae(a)){let g=Math.min(ce(a),p.length),c=Math.ceil(p.length/g),d=[];for(let m=0;m<g;m++){let W=p.slice(m*c,(m+1)*c);d.push(me(a,W))}await Promise.all(d)}else p.forEach(([g,c])=>{let{code:d,map:m}=ge(a,g,c);c.code=d,c.map=m});b.end(p)},k=(i,l)=>{if(u=!!l.isSsrBuild,o=q(i),r=Q(i),e.enable&&j(e.obfuscateWorker)){let g=i.worker?.plugins;i.worker=i.worker||{},i.worker.plugins=()=>{let c=g??[],d=$(c)?c():c,m=(R(d)?d:[d]).filter(Boolean);return m.some(F=>y(F)&&"name"in F&&F.name==="vite-plugin-bundle-obfuscator:worker")?m:[...m,{name:"vite-plugin-bundle-obfuscator:worker",apply:e.apply,enforce:"post",async generateBundle(F,V){if(!e.enable||!V||u)return;let U={...e,excludes:[...e.excludes,...e.obfuscateWorkerExcludes]};await s(V,{config:U,log:new S(U.log)})}}]}}if(!e.enable||!ue(e)||o||r)return;i.build=i.build||{},i.build.rollupOptions=i.build.rollupOptions||{};let{output:a}=i.build.rollupOptions,f=[...le(e)],b=()=>{e.excludes.push(w,...f.map(D))},p=g=>{if(g.includes(Z))return fe(g,f)};if(!a){b(),i.build.rollupOptions.output={manualChunks:p};return}if(R(a)){n.forceLog(O.warn,"rollupOptions.output is an array, ignoring autoExcludeNodeModules configuration.");return}if(y(a)){if(!a.manualChunks)b(),a.manualChunks=p;else if(y(a.manualChunks))n.forceLog(O.warn,"rollupOptions.output.manualChunks is an object, ignoring autoExcludeNodeModules configuration.");else if($(a.manualChunks)){let g=a.manualChunks;b(),a.manualChunks=(c,d)=>p(c)||g(c,d)}}},E=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}}}},x=async(i,{bundle:l})=>(!e.enable||!l||r||u||await s(l),i),T=async(i,l)=>{!e.enable||!l||o||!r||u||await s(l)},he=(i,l)=>{if(!e.enable||!o||u)return null;let a=new M(n),f=[[l.name,{code:i}]];a.start(f);let{code:b,map:p}=de(e,l.name,i);return a.end(f),{code:b,map:p}},ye=()=>se()>=5?{order:"post",handler:x}:{enforce:"post",transform:x};return{name:"vite-plugin-bundle-obfuscator",apply:e.apply,config:k,configResolved:E,renderChunk:he,transformIndexHtml:ye(),generateBundle:T}}