UNPKG

moduloze

Version:

Convert CommonJS (CJS) modules to UMD and ESM formats

5 lines 6.04 kB
/*! Moduloze: umd.js v0.9.1 (c) 2022 Kyle Simpson MIT License: http://getify.mit-license.org */ !function UMD(e,r,t,n){"function"==typeof define&&define.amd?(t=Object.values(t),define(e,t,n)):"undefined"!=typeof module&&module.exports?(t=Object.keys(t).map((e=>require(e))),module.exports=n(...t)):(t=Object.values(t).map((e=>r[e])),r[e]=n(...t))}("UMD","undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:new Function("return this")(),{fs:"NodeFS",path:"NodePath","@babel/traverse":"BabelTraverse","@babel/types":"BabelTypes","@babel/generator":"BabelGenerator","@babel/parser":"BableParser",toposort:"TopoSort","./helpers.js":"Helpers","./analysis.js":"Analysis"},(function DEF(e,r,t,n,i,o,a,s,l){"use strict";var d=e,p=r,{default:u}=t,c=n,{default:f}=i,{parse:m}=o,g=a,{expandHomeDir:y,addRelativeCurrentDir:b,generateName:h,rootRelativePath:v,qualifyDepPaths:x,isPathBasedSpecifier:D}=s,{identifyRequiresAndExports:j,analyzeRequires:S,analyzeExports:w}=l;let C={};C=build,C.build=build,C.bundle=function bundle(e,r){try{r=sortDependencies(e,r)}catch(r){if(!e.ignoreCircularDependency)throw new Error("Circular dependency not supported in UMD builds/bundles")}var t,n=m(P);u(n,{Program:{exit(e){t=e}}});var i=t.get("body.0.expression.arguments.1");for(let n of r){if(n.autoGenerated)continue;let r=c.clone(n.ast.program.body[0],!0,!0),o=r.expression.arguments[2].properties;if(o.length>0){let r=p.dirname(p.resolve(e.from,n.pathStr));for(let t of o)if(D(t.key.value)){let n=t.key.value,i=p.resolve(r,n),o=b(v(e.from,i));t.key.value=o}}t.pushContainer("body",r);let a=t.get("body.1.expression"),s=c.clone(a.get("arguments.0").node,!0,!0),l=c.clone(a.get("arguments.2").node,!0,!0),d=c.clone(a.get("arguments.3").node,!0,!0);i.pushContainer("elements",c.ArrayExpression([s,l,d])),t.get("body.1").remove()}return f(n)},C.index=function index(e,r,t){try{r=sortDependencies(e,r)}catch(r){if(!e.ignoreCircularDependency)throw new Error("Circular dependency not supported in UMD builds/bundles")}var n=Object.keys(t).find((e=>/\.cjs$/.test(e)))?"cjs":"js",i=`./index.${n}`,o="cjs"==n?"index.js":"index.cjs",a=t[i||o]||"Index",s=Object.entries(t).filter((([e])=>!e.startsWith(":::")&&r.find((r=>r.origPathStr==e))&&![i,o].includes(e)));i=renameCJS(e,i);var l={},d=m(E);return u(d,{Program:{exit(r){var t=r.get("body.0.expression");t.get("arguments.0").replaceWith(c.StringLiteral(a));var n=t.get("arguments.3"),i=n.get("body"),o=[],d=t.get("arguments.2");for(let[r,t]of s){let i,a=t;r.startsWith(":::")?i=r.slice(3):(i=r,i=b(i),i=renameCJS(e,i)),l[i]=i,d.node.properties.push(c.ObjectProperty(c.StringLiteral(i),c.StringLiteral(a))),n.node.params.push(c.Identifier(a)),o.push(c.ObjectProperty(c.Identifier(a),c.Identifier(a),!1,!0))}i.pushContainer("body",c.ReturnStatement(c.ObjectExpression(o))),i.node.directives.push(c.Directive(c.DirectiveLiteral("use strict")))}}}),{autoGenerated:!0,...f(d),ast:d,depMap:t,refDeps:l,pathStr:i,origPathStr:i,name:a}},C.sortDependencies=sortDependencies;var E=d.readFileSync(p.join(__dirname,"umd-template.js"),"utf-8"),P=d.readFileSync(p.join(__dirname,"umd-bundle-template.js"),"utf-8");function build(e,r,t,n){n={...n};var{programAST:i,programPath:o,convertRequires:a,convertExports:s}=j(r,t),l=e.from,d=p.resolve(l,y(r)),g=v(l,d),x=n[g];if(!x){if(!e.ignoreUnknownDependency)throw new Error(`Unknown module: ${r}`);x=h(),n[r]=x,g=r}var S={},w=!1;for(let r of a){let t;if(D(r.specifier)){let i=p.resolve(p.dirname(d),y(r.specifier)),o=v(l,i);if(o==g)throw new Error(`Module dependency is an illegal self-reference: ${r.specifier}`);t=n[o];let a=v(p.dirname(d),y(r.specifier));if(!t){if("remove-require-unique"!=r.umdType&&!e.ignoreUnknownDependency)throw new Error(`Unknown dependency: ${r.specifier}`);t=h(),n[o]=t}S[o]=a}else{let i=`:::${r.specifier}`;if(t=n[i],!t){if("remove-require-unique"!=r.umdType&&!e.ignoreUnknownDependency)throw new Error(`Unknown dependency: ${r.specifier}`);t=h(),n[i]=t}S[i]=i}"remove-require-unique"==r.umdType?r.context.statement.remove():"default-require"==r.umdType?t!=r.binding.target?r.context.requireCall.replaceWith(c.Identifier(t)):r.context.declarator.remove():r.context.requireCall.replaceWith(c.Identifier(t))}if(s.length>0){let e=c.Identifier(o.scope.generateUidIdentifier("exp").name);s[0].context.statement.insertBefore(c.VariableDeclaration("let",[c.VariableDeclarator(e,c.ObjectExpression([]))])),o.pushContainer("body",c.ReturnStatement(e));for(let r of s)"default-assignment"==r.umdType&&registerDefaultExport(r.context.exportsExpression),r.context.exportsExpression.replaceWith(e)}var C=m(E);u(C,{Program:{exit(r){var t=r.get("body.0.expression");t.get("arguments.0").replaceWith(c.StringLiteral(x));var i=Object.entries(S),o=t.get("arguments.3");if(i.length>0){let r=t.get("arguments.2");for(let[t,a]of i){let i,s=n[t];t.startsWith(":::")?i=t.slice(3):(i=a,i=b(i),i=renameCJS(e,i)),r.node.properties.push(c.ObjectProperty(c.StringLiteral(i),c.StringLiteral(s))),o.node.params.push(c.Identifier(s))}}}}});var P=c.clone(C.program.body[0],!0,!0);o.unshiftContainer("body",P);var q=o.get("body.0.expression.arguments.3.body");for(i.program.directives.length>0&&"use strict"==i.program.directives[0].value.value&&(q.node.directives.push(c.Directive(c.DirectiveLiteral("use strict"))),i.program.directives.shift());i.program.body.length>1;){let e=o.get("body.1"),r=c.cloneDeep(e.node);q.pushContainer("body",r),e.remove()}return{...f(i),ast:i,depMap:n,refDeps:S,pathStr:renameCJS(e,g),origPathStr:g,name:x};function registerDefaultExport(e){if(w)throw new Error("Multiple re-assignments of 'module.exports' not allowed in the same module");w=!0}}function sortDependencies(e,r){r=r.filter((e=>!e.autoGenerated));var t={};for(let e of r)t[e.pathStr]=e;var n=[];for(let i of r)for(let r of Object.keys(i.refDeps))r=renameCJS(e,r),r in t&&n.push([i,t[r]]);return g.array(r,n).reverse()}function renameCJS(e,r){return e[".cjs"]?r.replace(/\.cjs$/,".js"):r}return C}));