esbuild-plugin-glsl
Version:
An esbuild plugin that adds support for shader imports.
13 lines (12 loc) • 2.34 kB
JavaScript
/**
* esbuild-plugin-glsl v1.4.0 build Thu Mar 20 2025
* https://github.com/vanruesc/esbuild-plugin-glsl
* Copyright 2020 Raoul van Rüschen
* @license Zlib
*/
function E(n,a=null){let g=/(?:\/\*[\s\S]*?\*\/)|(?:\/\/.*\n)/g,s=/(?:\/[/*]!)|(?:@license)|(?:@preserve)/m;if(a===null)return n.replace(g,"");let e=0;for(let r of n.matchAll(g))if(s.test(r[0])){let i=`[[LEGAL_COMMENT_${e++}]]`;a.push({contents:r[0],placeholder:i}),n=n.replace(r[0],i)}else n=n.replace(r[0],"");return n}function L(n,a){let g=/\s*([{}=*,+/><&|[\]()\\!?:;-])\s*/g,s=/(\w<\w+>)\s*(\w)/g,e=n.replace(/\r/g,""),r=[];e=E(e,a?r:null);let i=!0,o=!1;e=e.split(/\n+/).reduce((l,t)=>(t=t.trim().replace(/\s{2,}|\t/," "),t.startsWith("#")?(o&&l.push(`
`),l.push(t,`
`),o=!1):t.length>0&&(t=t.replace(g,"$1"),!i&&/\w/.test(t[0])&&(t=" "+t),t=t.replace(s,"$1 $2"),l.push(t),i=!/\w/.test(t[t.length-1]),o=!0),l),[]).join("");for(let l of r)e=e.replace(l.placeholder,`
${l.contents.trim()}
`);return e.replace(/\n{2,}/g,`
`).trim()}import*as O from"fs";import*as y from"util";import*as h from"path";var R=y.promisify(O.readFile);async function w(n,a,g){let s=await R(n,"utf8");if(!g)return{contents:s};let e=[],r=[],i=new Set,o=/#include +["']([.\\/\w-]+)["']/g,l=/\r|\n|\r\n/g,t=o.exec(s);for(;t!==null;){let u=t[0],d=t[1],c=h.join(h.dirname(n),d);try{let m=a.get(c);if(m===void 0){let p=await w(c,a,g);p.warnings?.forEach(f=>r.push(f)),p.watchFiles?.forEach(f=>i.add(f)),m=p.contents,a.set(c,m)}e.push({file:c,contents:m,target:u}),i.add(c),t=o.exec(s)}catch{if(t===null)break;let p=s.split(l),f=p.indexOf(t[0]),x=p[f];r.push({text:`File from <${t[0]}> not found`,location:{file:d,line:f+1,length:d.length,column:x.indexOf(d),lineText:x}}),e.push({file:c,contents:"",target:t[0]}),t=o.exec(s)}}for(let u of e)s=s.replace(u.target,u.contents);return a.set(n,s),{contents:s,warnings:r,watchFiles:[...i]}}function F({minify:n,resolveIncludes:a=!0,preserveLegalComments:g}={}){let s=new Map;return{name:"glsl",setup(e){async function r(i){let{contents:o,warnings:l,watchFiles:t}=await w(i.path,s,a);return n??=e.initialOptions.minify??!1,g??=e.initialOptions.legalComments!=="none",o=n?`export default \`${L(o,g)}\``:`export default \`${o}\``,{contents:o,warnings:l,watchFiles:t,loader:"js"}}e.onLoad({filter:/\.(?:frag|vert|glsl|wgsl)$/},r)}}}export{F as default,F as glsl};