als-require
Version:
A utility for using CommonJS require in the browser and creating bundles.
10 lines • 4.83 kB
JavaScript
let Require=(()=>{let p={};function orderKeys(e,s){var t=[];for(let r of e){let n;t.forEach((e,t)=>{s.contents[e].children.includes(r)&&(n=t)}),void 0!==n?t.splice(n+1,0,r):t.push(r)}return t}function getFullPath(e,t){var n,e=e.split("/"),r=[];for(n of[...t.split("/").slice(0,-1),...e])".."===n?0<r.length&&".."!==r[r.length-1]?r.pop():r.push(n):"."!==n&&r.push(n);t=r.join("/");return t.endsWith(".js")?t:t+".js"}async function getNodeModules(e,a,c,l,t,u){var n=l.standartNodeModules;if(0!==e.length)for(let{match:o,modulePath:i}of e){let s=new RegExp(`require\\((["'\`])${i}["'\`]\\)`);var h=()=>{c=c.replace(s,"{}"),t.warn(`The module "${i}" can't be imported and will be replaced with {}`)};if(i.startsWith("node:")||n.includes(i))h();else{let n,e,t,r=i;i.includes("/")&&(d=i.split("/"),r=d.shift(),e=d.join("/"));var d=`/node_modules/${r}/package.json`;!1===(await fetch(d,{method:"HEAD"})).ok?h():(t=p[d]||({main:h="index.js"}=await l.fetch(d,"json"),p[d]=h),(n=(n=e?`/node_modules/${r}/`+e:`/node_modules/${r}/`+t).replace(/\/\.?\//g,"/")).endsWith(".js")||(n+=".js"),u||l.isCyclyc(n,i),a.push(n),c=c&&c.replace(o,o.replace(s,(e,t)=>`require(${t}${n}${t})`)))}}return c}async function getContents({contents:r,fullPath:e},i,a,c,s=[]){let l=async o=>{if(void 0===r[o]){if(!i.contents[o]){let e=await i.fetch(o),r=[],s=[];e=e.replace(/^(?!\/\/|\/\*.*\*\/).*require\(["'`](.*)["'`]\)/gm,(e,t)=>{var n;return t.startsWith(".")?(n=getFullPath(t,o),a||i.isCyclyc(n,o),r.push(n),e.replace(t,n)):(s.push({match:e,modulePath:t}),e)}),e=await getNodeModules(s,r,e,i,c,a),i.contents[o]={content:e,children:r}}let{content:e,children:t}=i.contents[o],n={content:e,children:t,path:o};s.forEach(e=>{e(n)}),r[o]=n.content,await Promise.all(t.map(e=>l(e)))}};await l(e)}function parseError(e,i,a){let[t,...n]=e.stack.split("\n");throw n=n.map(e=>{var t=e.match(/<anonymous>:(\d*):(\d*)\)$/);if(t){let n=Number(t[1]);if(n+1!==a){var r,s,t=Number(t[2]),o=Object.entries(i).filter(([,{from:e,to:t}])=>n>=e&&n<=t);if(0!==o.length)return[o,{from:r,to:s}]=o[0],` at ${e.match(/at\s(.*?)\s/)[1]} ${o} (${n-r-2}:${t})`}}}).filter(Boolean),e.stack=t+"\n"+n.join("\n"),e}function getFn(r,e={}){var{scriptBefore:e="",scriptAfter:t="",parameters:n=[]}=e;e=[parseError.toString(),`function require(path) {
if(typeof modules[path] === 'function' && modules[path].name === '____') modules[path] = modules[path]()
return modules[path] || null
};`,e].join("\n");let s={},o=3+e.split("\n").length,i;e=[e,"try {",r.keys.map((e,t)=>{var n=function buildFn(e,t){return`modules['${t}'] = function ____(){
const module = { exports: {} }
const exports = module.exports
${e}
return module.exports;
};`}(r.contents[e],e);return t===r.keys.length-1&&(i=e),s[e]={from:o+1},o+=n.split("\n").length,s[e].to=o,n}).join("\n"),`let result = modules['${i}']()`,t,"return result","} catch (error) { parseError(error, modulesLines, curLastLine) }"].join("\n"),n.push("modules={}","curLastLine = "+o,"modulesLines = "+JSON.stringify(s)),t=new Function(n.join(","),e);return t}class Require{static standartNodeModules=["assert","async_hooks","buffer","child_process","cluster","console","constants","crypto","dgram","diagnostics_channel","dns","domain","events","fs","http","http2","https","inspector","module","net","os","path","perf_hooks","process","punycode","querystring","readline","repl","stream","string_decoder","sys","timers","timers/promises","tls","trace_events","tty","url","util","v8","vm","wasi","worker_threads","zlib","test","abort_controller"];static contents={};static plugins=[];static cyclicDependencies=!1;static logger=console;static version;static isCyclyc(e,t){if(this.contents[e]&&this.contents[e].children.includes(t))throw`cyclic dependency between ${t} and `+e}static async fetch(e,t="text"){this.version&&(e+="?version="+this.version);e=await fetch(e);return e.ok||console.error("HTTP error! status: "+e.status),e[t]()}static async getModule(e,t={},...n){e=new Require(e);return await e.getContent(t),(await e.fn(t))(...n)}constructor(e,t={}){this.contents={},this.path=e,this.fullPath=getFullPath(e,location.pathname),this.contentReady=!1,this.options=t}async getContent(e={}){var{plugins:e=[],cyclicDependencies:t=Require.cyclicDependencies,logger:n=Require.logger}={...this.options,...e},e=[...Require.plugins,...e].filter(e=>"function"==typeof e);return this.contentReady||(await getContents(this,Require,t,n,e),this.keys=orderKeys(Object.keys(this.contents),Require).reverse(),this.contentReady=!0),this}fn(e={}){return getFn(this,e)}}return Require.orderKeys=orderKeys,Require.getFullPath=getFullPath,Require.getNodeModules=getNodeModules,Require.getContents=getContents,Require.parseError=parseError,Require.getFn=getFn,Require.Require=Require})();
const require=(e,t,...n)=>Require.getModule(e,t,...n);