packitup 0.2.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/packitup.js CHANGED
@@ -1 +1 @@
1
- (moduleDict=>{const caches={__proto__:null},proc={moduleDict:moduleDict,workdir:"/packitup"},simpRequire=moduleId=>{if(moduleId in caches)return caches[moduleId];const module={exports:{}};return(0,moduleDict["/modules/"+moduleId+".js"])(simpRequire,module.exports,module,proc),caches[moduleId]=module.exports,module.exports};simpRequire.original="function"==typeof require?require:simpRequire,proc.isMain="object"==typeof module&&simpRequire.original.main===module;const Module=simpRequire("module"),factory=()=>{new Module("/packitup/src/index.js");return Module._load("/packitup/src/index.js",void 0,!0)};"object"==typeof exports?module.exports=factory():"function"==typeof define?define("packitup",[],factory):globalThis.PackItUp=factory()})({"/packitup/src/index.js"(require,exports,module){const build=require("./lib/build.js"),builder=require("./lib/builder.js"),cli=require("./lib/cli.js");module.exports={...build,...builder},require.main===module&&cli.main()},"/packitup/src/lib/build-template.js"(require,exports,module){module.exports=(moduleDict,mainfile,projectName,globalExport,isesm)=>{const caches={__proto__:null},proc={moduleDict:moduleDict,workdir:"/"+projectName},simpRequire=moduleId=>{if(moduleId in caches)return caches[moduleId];const module={exports:{}};return(0,moduleDict["/modules/"+moduleId+".js"])(simpRequire,module.exports,module,proc),caches[moduleId]=module.exports,module.exports};simpRequire.original="function"==typeof require?require:simpRequire,proc.isMain="object"==typeof module&&simpRequire.original.main===module;const Module=simpRequire("module"),factory=()=>{new Module(mainfile);return Module._load(mainfile,void 0,!0)};if(isesm)return factory();"object"==typeof exports?module.exports=factory():"function"==typeof define?define(projectName,[],factory):globalThis[globalExport]=factory()}},"/packitup/src/lib/build.js"(require,exports,module){const fs=require("fs"),{sep:pathSep,join:pathJoin,resolve:resolve,relative:relative}=require("path"),templateFunction=require("./build-template.js"),{moduleDict:mdict}=module.$build$?require("[build]"):{},search=(path,rule)=>{const listdir=fs.readdirSync(path),result=[];for(const filename of listdir){const file=path+pathSep+filename;if(fs.statSync(file).isDirectory()){let subfiles=search(file,rule);subfiles=subfiles.filter(filePath=>rule.test(filePath)),result.push(...subfiles);continue}rule.test(file)&&result.push(file)}return result},build=(allJS,main,options={})=>{const{projectName:projectName="project",globalExportName:globalExportName=projectName,esmExport:esmExport="export default module;",dontPack:dontPack=[],move:move=path=>path,node_modules:node_modules=[]}=options,moduleMap={};for(let filePath of allJS){if(filePath.startsWith("./")&&(filePath=filePath.slice(2)),dontPack.some(dont=>dont.test(filePath)))continue;const saveFilePath=move(pathSep+projectName+pathSep+filePath);filePath&&(moduleMap[saveFilePath]=fs.readFileSync(filePath))}for(const[realPath,virtualPath]of node_modules)moduleMap[virtualPath]=fs.readFileSync(realPath);mdict&&Object.entries(mdict).forEach(([key,value])=>{key.startsWith("/modules/")&&(value=String(value).match(/\{([\S\s]*)\}/)[1],moduleMap[key]=value)});const moduleDict=(()=>{const mapping=[];for(const[key,value]of Object.entries(moduleMap)){const pathKey=JSON.stringify(key);key.endsWith(".js")?mapping.push(`${pathKey}(require,exports,module){${value}}`):key.endsWith(".json")?mapping.push(`${pathKey}:${value}`):mapping.push(`${pathKey}:${JSON.stringify(value)}`)}return`{${mapping}}`})(),template=`(${templateFunction})`,esmTemplate=esmExport,projectNameStr=JSON.stringify(projectName),globalExportNameStr=JSON.stringify(globalExportName);return{umd:`${template}(${moduleDict},${JSON.stringify(main)},${projectNameStr},${globalExportNameStr});`,esm:`const module=${`${template}(${moduleDict},${JSON.stringify(main)},${projectNameStr},${globalExportNameStr},1)`};${esmTemplate}`,options:options}};module.exports={build:build,buildDirectory:(directory,options={})=>{if(!options.projectName){let projectName=resolve(directory);const paths=projectName.split(pathSep);let index=1;do{projectName=paths[paths.length-index],index++}while(["src","lib"].includes(projectName)&&index<paths.length);options.projectName=projectName}options.extensions||(options.extensions=[".js",".json",".txt",".svg",".xml",".html"]);const test=path=>options.extensions.some(ext=>path.endsWith(ext)),allJS=search(directory,{test:test}),parentDirectory=resolve(directory).split(pathSep).slice(0,-1).join(pathSep);if(fs.readdirSync(parentDirectory).includes("node_modules")){const nmPath=pathJoin(parentDirectory,"node_modules"),node_modules=search(nmPath,{test:test}).map(direct=>[direct,relative(directory,direct).replace(/^\.\.\//g,"/")]);options.node_modules=node_modules}return build(allJS,pathSep+pathJoin(options.projectName,directory,"index.js"),options)}}},"/packitup/src/lib/builder.js"(require,exports,module){const fs=require("fs"),path=require("path"),{buildDirectory:buildDirectory}=require("./build.js");exports.outputBundle=options=>{let{sourcePath:sourcePath,umdFile:umdFile,esmFile:esmFile,distPath:distPath,esmTemplate:esmTemplate}=options;esmTemplate&&(options.esmExport=fs.readFileSync(esmTemplate));const dist=buildDirectory(sourcePath,options),projectName=dist.options.projectName;distPath.endsWith(path.sep)||(distPath+=path.sep),umdFile??=distPath+projectName+".js",esmFile??=distPath+projectName+".mjs",fs.writeFileSync(umdFile,dist.umd),fs.writeFileSync(esmFile,dist.esm)}},"/packitup/src/lib/cli.js"(require,exports,module){require("path"),require("fs");const{outputBundle:outputBundle}=require("./builder.js");function parseArgs(){const args=process.argv.slice(2),options={},positional=[];return{index:0,curr:args[0],next(){this.index++,this.curr=args[this.index]},peek(n=1){return args[this.index+n]},parse(){for(;this.curr;)this.parseArgument()},parseArgument(){if(this.curr.startsWith("--")){const key=this.curr.slice(2),nextArg=this.peek();return nextArg&&!nextArg.startsWith("--")?(this.next(),void(options[key]=nextArg)):void(options[key]=!0)}this.curr.startsWith("-")?options[this.curr.slice(1)]=!0:(positional.push(this.curr),this.next())}}.parse(),{options:options,positional:positional}}function showHelp(){console.log("\nšŸ“¦ PackItUp - JavaScript Packager\n\nATTENTION: If you're running for the first time, please cd to module path and run \"npm run install\".\n\nUsage: packitup [command] [options]\n\nCommands:\n build <input-directory> [output-directory] Pack a directory\n\nOptions:\n --name <projectName> Specify project name\n --umd <fileName> Specify UMD output file name\n --esm <fileName> Specify ESM output file name\n --esm-template <template> Specify ESM output template\n --dont-export Specify don't export files\n --move-from Move files from this directory\n --move-to Move files to this directory\n --help Show this help message\n\n")}module.exports={parseArgs:parseArgs,main:async function(){const{options:options,positional:positional}=parseArgs();(options.help||0===positional.length)&&(showHelp(),process.exit(0));const command=positional[0];switch(command){case"build":{const input=positional[1],output=positional[2]||".";input||(console.error("āŒ Error: Please specify input directory"),showHelp(),process.exit(1)),console.log(`šŸš€ Starting pack: ${input} → ${output}`),outputBundle({sourcePath:input,projectName:options.name,distPath:output,umdFile:options.umd,esmFile:options.esm,move:options.move?pth=>options["move-from"]&&pth.startsWith(options["move-from"])?pth.replace(options["move-from"],options["move-to"]||options["move-from"]):pth:void 0,dontExport:(options["dont-export"]??"").split(" "),esmTemplate:options["esm-template"]}),console.log("āœ… Pack complete!");break}default:console.error(`āŒ Unknown command: ${command}`),showHelp(),process.exit(1)}}}},"/modules/[build].js"(require,exports,module){module.exports=arguments[3]},"/modules/module.js"(require,exports,module){const proc=require("[build]"),{moduleDict:moduleDict}=proc,path=require("path");let mainModule;function updateChildren(parent,child,scan){const children=parent?.children;!children||scan&&children.includes(child)||children.push(child)}function raiseModuleNotFound(request){const modname=request.replaceAll("'","\\'");throw new Error("Cannot find module '"+modname+"'")}function Module(id="",parent){this.id=id,this.path=path.dirname(id),this.exports={},updateChildren(parent,this,!1),this.filename=null,this.loaded=!1,this.children=[]}Module.Module=Module,Module._nodeModulePaths=function(from){const paths=[];for(let current=from=path.resolve(from);current!==path.dirname(current);current=path.dirname(current))paths.push(path.join(current,"node_modules"));return paths.push("/node_modules"),paths},Module._cache=Object.create(null),Module._extensions=Object.create(null),Module.builtinModules=["_http_agent","_http_client","_http_common","_http_incoming","_http_outgoing","_http_server","_stream_duplex","_stream_passthrough","_stream_readable","_stream_transform","_stream_wrap","_stream_writable","_tls_common","_tls_wrap","assert","assert/strict","async_hooks","buffer","child_process","cluster","console","constants","crypto","dgram","diagnostics_channel","dns","dns/promises","domain","events","fs","fs/promises","http","http2","https","inspector","inspector/promises","module","net","os","path","path/posix","path/win32","perf_hooks","process","punycode","querystring","readline","readline/promises","repl","stream","stream/consumers","stream/promises","stream/web","string_decoder","sys","timers","timers/promises","tls","trace_events","tty","url","util","util/types","v8","vm","wasi","worker_threads","zlib","node:sea","node:sqlite","node:test","node:test/reporters"];const SpecialModules=["module","[build]"];Module._load=function(request,parent,isMain){if(Module.builtinModules.includes(request))return require.original(request);if(SpecialModules.includes(request))return require(request);const filename=function(request,parent){if([".","..",""].some(start=>request.startsWith(start+path.sep))){const requestPath=request.startsWith(path.sep)?request:path.resolve(request);if(requestPath in moduleDict)return requestPath;const extensions=Object.keys(Module._extensions);for(const extension of extensions){const withext=requestPath+extension;if(withext in moduleDict)return withext}const indexPath=path.join(requestPath,"index");for(const extension of extensions){const withext=indexPath+extension;if(withext in moduleDict)return withext}raiseModuleNotFound(request)}if(parent)for(const maybeNm of parent.paths){const[moduleName,...subdirs]=request.split(path.sep),subdir=subdirs.length?path.join(...subdirs):".",maybe=path.join(maybeNm,moduleName),packageJSON=moduleDict[path.join(maybe,"package.json")];if(packageJSON){if(packageJSON.exports){const{exports:exports}=packageJSON;if("string"==typeof exports)return path.join(maybe,exports);if("object"==typeof exports&&exports[subdir]){const entry=exports[subdir];if("string"==typeof entry)return path.join(maybe,entry);if("object"==typeof entry){if(entry.require)return path.join(maybe,entry.require);if(entry.default)return path.join(maybe,entry.default)}}}if(packageJSON.main)return path.join(maybe,packageJSON.main)}const indexPath=path.join(maybe,request,"index.js");if(indexPath in moduleDict)return indexPath}raiseModuleNotFound(request)}(request,parent),cachedModule=Module._cache[filename];if(void 0!==cachedModule){if(updateChildren(parent,cachedModule,!0),cachedModule.loaded)return cachedModule.exports;if(!cachedModule[kIsCachedByESMLoader])return getExportsForCircularRequire(cachedModule);if(cachedModule[kModuleCircularVisited])return getExportsForCircularRequire(cachedModule);cachedModule[kModuleCircularVisited]=!0}const module=cachedModule||new Module(filename,parent);return cachedModule||(isMain&&(proc.isMain&&(mainModule=module,Module.prototype.require.main=null),module.id="."),Module._cache[filename]=module,module.load(filename)),module.exports},Module.prototype.load=function(filename){this.filename??=filename,this.paths??=Module._nodeModulePaths(path.dirname(filename));const extension=filename.includes(".")?"."+filename.split(".").slice(-1)[0]:"";Module._extensions[extension](this,filename),this.loaded=!0},Module.prototype.require=function(id){return request=id,parent=this,isMain=!1,Module._load.call({__proto__:null,parentFilename:parent?.filename,id:request},request,parent,isMain);var request,parent,isMain},Module.prototype.require.main=null,Object.assign(Module._extensions,{".js":function(module,filename){function require(path){return module.require(path)}require.main=mainModule,require.extensions=Module._extensions,require.cache=Module._cache;const factory=moduleDict[filename],oldworkdir=proc.workdir;proc.workdir=path.dirname(filename),factory(require,module.exports,module),proc.workdir=oldworkdir},".json":function(module,filename){module.exports=moduleDict[filename]}}),Module.prototype.$build$=!0,module.exports=Module},"/modules/path.js"(require,exports,module){const proc=require("[build]");module.exports={sep:"/",delimiter:":",normalize(path){if(!path)return".";let result=path.replace(/\/+/g,"/");result.startsWith("./")&&(result=result.slice(2)),result=result.replace(/\/\.\//g,"/"),result.endsWith("/.")&&(result=result.slice(0,-2));const parts=result.split("/"),newParts=[];for(const part of parts)".."===part?newParts.length>0&&newParts.pop():""!==part&&"."!==part&&newParts.push(part);return result=newParts.join("/"),path.startsWith("/")?result="/"+result:path.startsWith("./")&&(result="./"+result),""===result?".":(path.endsWith("/")&&!result.endsWith("/")&&"."!==result&&(result+="/"),result)},join(...paths){if(0===paths.length)return".";let result="";for(const segment of paths)segment&&(""===result?result=segment:result+="/"+segment);return this.normalize(result)},resolve(...paths){if(0===paths.length)return proc.workdir||"/";let result="",isAbsolute=!1;for(let i=paths.length-1;i>=0;i--){const path=paths[i];path&&(path.startsWith("/")?(result=path,isAbsolute=!0):result=""===result?path:path+"/"+result)}return isAbsolute||(result=(proc.workdir||"/")+"/"+result),this.normalize(result)},dirname(path){if(!path||"."===path||".."===path)return".";if("/"===path)return"/";let cleanPath=path;for(;cleanPath.endsWith("/")&&cleanPath.length>1;)cleanPath=cleanPath.slice(0,-1);const lastSlash=cleanPath.lastIndexOf("/");if(-1===lastSlash)return".";if(0===lastSlash)return"/";return cleanPath.slice(0,lastSlash)||"/"},basename(path,ext){if(!path)return"";const lastSlash=path.lastIndexOf("/");let filename=-1===lastSlash?path:path.slice(lastSlash+1);return""===filename?"":(ext&&"string"==typeof ext&&filename.endsWith(ext)&&(filename=filename.slice(0,-ext.length)),filename)},extname(path){if(!path)return"";const lastSlash=path.lastIndexOf("/"),filename=-1===lastSlash?path:path.slice(lastSlash+1),lastDot=filename.lastIndexOf(".");return lastDot<=0?"":filename.slice(lastDot)},isAbsolute:path=>path&&path.startsWith("/"),relative(from,to){if(!from||!to)return"";const fromPath=this.normalize(from),toPath=this.normalize(to);if(fromPath===toPath)return"";const fromParts=fromPath.split("/").filter(part=>part&&"."!==part),toParts=toPath.split("/").filter(part=>part&&"."!==part);let commonLength=0;const minLength=Math.min(fromParts.length,toParts.length);for(let i=0;i<minLength&&fromParts[i]===toParts[i];i++)commonLength++;const upLevels=fromParts.length-commonLength,remainingParts=toParts.slice(commonLength);let result="";for(let i=0;i<upLevels;i++)result+="../";return result+=remainingParts.join("/"),result||"."},parse(path){if(!path)return{root:"",dir:"",base:"",ext:"",name:""};const root=path.startsWith("/")?"/":"",dir=this.dirname(path),base=this.basename(path),ext=this.extname(path),name=ext?base.slice(0,-ext.length):base;return{root:root,dir:dir,base:base,ext:ext,name:name}},format(pathObject){if(!pathObject||"object"!=typeof pathObject)throw new TypeError("pathObject must be an object");const{root:root="",dir:dir="",base:base="",name:name="",ext:ext=""}=pathObject;if(dir){return this.join(dir,base||name+ext)}return root+(name||base)+ext},get posix(){return this},get win32(){return{...this,sep:"\\",delimiter:";",normalize:path=>this.normalize(path.replace(/\\/g,"/")).replace(/\//g,"\\"),isAbsolute:path=>/^[A-Za-z]:\\/.test(path)||/^\\\\/.test(path)||path.startsWith("\\")}}}}});
1
+ (moduleDict=>{const caches={__proto__:null},proc={moduleDict:moduleDict,workdir:"/packitup"},simpRequire=moduleId=>{if(moduleId in caches)return caches[moduleId];const module={exports:{}};return(0,moduleDict["/modules/"+moduleId+".js"])(simpRequire,module.exports,module,proc),caches[moduleId]=module.exports,module.exports};simpRequire.original="function"==typeof require?require:simpRequire,proc.isMain="object"==typeof module&&simpRequire.original.main===module;const Module=simpRequire("module"),factory=()=>{new Module("/packitup/src/index.js");return Module._load("/packitup/src/index.js",void 0,!0)};"object"==typeof exports?module.exports=factory():"function"==typeof define?define("packitup",[],factory):globalThis.PackItUp=factory()})({"/packitup/src/index.js"(require,exports,module){const build=require("./lib/build.js"),builder=require("./lib/builder.js"),cli=require("./lib/cli.js");module.exports={...build,...builder},require.main===module&&cli.main()},"/packitup/src/lib/build-template.js"(require,exports,module){module.exports=(moduleDict,mainfile,projectName,globalExport,isesm)=>{const caches={__proto__:null},proc={moduleDict:moduleDict,workdir:"/"+projectName},simpRequire=moduleId=>{if(moduleId in caches)return caches[moduleId];const module={exports:{}};return(0,moduleDict["/modules/"+moduleId+".js"])(simpRequire,module.exports,module,proc),caches[moduleId]=module.exports,module.exports};simpRequire.original="function"==typeof require?require:simpRequire,proc.isMain="object"==typeof module&&simpRequire.original.main===module;const Module=simpRequire("module"),factory=()=>{new Module(mainfile);return Module._load(mainfile,void 0,!0)};if(isesm)return factory();"object"==typeof exports?module.exports=factory():"function"==typeof define?define(projectName,[],factory):globalThis[globalExport]=factory()}},"/packitup/src/lib/build.js"(require,exports,module){const fs=require("fs"),{sep:pathSep,join:pathJoin,resolve:resolve,relative:relative}=require("path"),templateFunction=require("./build-template.js"),{moduleDict:mdict}=module.$build$?require("[build]"):{},search=(path,rule)=>{const listdir=fs.readdirSync(path),result=[];for(const filename of listdir){const file=path+pathSep+filename;if(fs.statSync(file).isDirectory()){let subfiles=search(file,rule);subfiles=subfiles.filter(filePath=>rule.test(filePath)),result.push(...subfiles);continue}rule.test(file)&&result.push(file)}return result},build=(allJS,main,options={})=>{const{projectName:projectName="project",globalExportName:globalExportName=projectName,esmExport:esmExport="export default module;",dontPack:dontPack=[],move:move=path=>path,node_modules:node_modules=[]}=options,moduleMap={};for(let filePath of allJS){if(filePath.startsWith("./")&&(filePath=filePath.slice(2)),dontPack.some(dont=>dont.test(filePath)))continue;const saveFilePath=move(pathSep+projectName+pathSep+filePath);filePath&&(moduleMap[saveFilePath]=fs.readFileSync(filePath))}for(const[realPath,virtualPath]of node_modules)moduleMap[virtualPath]=fs.readFileSync(realPath);mdict&&Object.entries(mdict).forEach(([key,value])=>{key.startsWith("/modules/")&&(value=String(value).match(/\{([\S\s]*)\}/)[1],moduleMap[key]=value)});const moduleDict=(()=>{const mapping=[];for(const[key,value]of Object.entries(moduleMap)){const pathKey=JSON.stringify(key);key.endsWith(".js")?mapping.push(`${pathKey}(require,exports,module){${value}}`):key.endsWith(".json")?mapping.push(`${pathKey}:${value}`):mapping.push(`${pathKey}:${JSON.stringify(value)}`)}return`{${mapping}}`})(),template=`(${templateFunction})`,esmTemplate=esmExport,projectNameStr=JSON.stringify(projectName),globalExportNameStr=JSON.stringify(globalExportName);return{umd:`${template}(${moduleDict},${JSON.stringify(main)},${projectNameStr},${globalExportNameStr});`,esm:`const module=${`${template}(${moduleDict},${JSON.stringify(main)},${projectNameStr},${globalExportNameStr},1)`};${esmTemplate}`,options:options}};module.exports={build:build,buildDirectory:(directory,options={})=>{if(!options.projectName){let projectName=resolve(directory);const paths=projectName.split(pathSep);let index=1;do{projectName=paths[paths.length-index],index++}while(["src","lib"].includes(projectName)&&index<paths.length);options.projectName=projectName}options.extensions||(options.extensions=[".js",".json",".txt",".svg",".xml",".html"]);const test=path=>options.extensions.some(ext=>path.endsWith(ext)),allJS=search(directory,{test:test}),parentDirectory=resolve(directory).split(pathSep).slice(0,-1).join(pathSep);if(fs.readdirSync(parentDirectory).includes("node_modules")){const nmPath=pathJoin(parentDirectory,"node_modules"),node_modules=search(nmPath,{test:test}).map(direct=>[direct,relative(directory,direct).replace(/^\.\.\//g,"/")]);options.node_modules=node_modules}return build(allJS,pathSep+pathJoin(options.projectName,directory,"index.js"),options)}}},"/packitup/src/lib/builder.js"(require,exports,module){const fs=require("fs"),path=require("path"),{buildDirectory:buildDirectory}=require("./build.js");exports.outputBundle=options=>{let{sourcePath:sourcePath,umdFile:umdFile,esmFile:esmFile,distPath:distPath,esmTemplate:esmTemplate}=options;esmTemplate&&(options.esmExport=fs.readFileSync(esmTemplate));const dist=buildDirectory(sourcePath,options),projectName=dist.options.projectName;distPath.endsWith(path.sep)||(distPath+=path.sep),umdFile??=distPath+projectName+".js",esmFile??=distPath+projectName+".mjs",fs.writeFileSync(umdFile,dist.umd),fs.writeFileSync(esmFile,dist.esm)}},"/packitup/src/lib/cli.js"(require,exports,module){require("path"),require("fs");const{outputBundle:outputBundle}=require("./builder.js");function parseArgs(){const args=process.argv.slice(2),options={},positional=[];return{index:0,curr:args[0],next(){this.index++,this.curr=args[this.index]},peek(n=1){return args[this.index+n]},parse(){for(;this.curr;)this.parseArgument()},parseArgument(){if(this.curr.startsWith("--")){const key=this.curr.slice(2),nextArg=this.peek();return nextArg&&!nextArg.startsWith("--")?(this.next(),void(options[key]=nextArg)):void(options[key]=!0)}this.curr.startsWith("-")?options[this.curr.slice(1)]=!0:(positional.push(this.curr),this.next())}}.parse(),{options:options,positional:positional}}function showHelp(){console.log("\nšŸ“¦ PackItUp - JavaScript Packager\n\nATTENTION: If you're running for the first time, please cd to module path and run \"npm run install\".\n\nUsage: packitup [command] [options]\n\nCommands:\n build <input-directory> [output-directory] Pack a directory\n\nOptions:\n --name <projectName> Specify project name\n --umd <fileName> Specify UMD output file name\n --esm <fileName> Specify ESM output file name\n --esm-template <template> Specify ESM output template\n --dont-export Specify don't export files\n --global-export Specify export to global object's variable name.\n --move-from Move files from this directory\n --move-to Move files to this directory\n --help Show this help message\n\n")}module.exports={parseArgs:parseArgs,main:async function(){const{options:options,positional:positional}=parseArgs();(options.help||0===positional.length)&&(showHelp(),process.exit(0));const command=positional[0];switch(command){case"build":{const input=positional[1],output=positional[2]||".";input||(console.error("āŒ Error: Please specify input directory"),showHelp(),process.exit(1)),console.log(`šŸš€ Starting pack: ${input} → ${output}`),outputBundle({sourcePath:input,projectName:options.name,distPath:output,umdFile:options.umd,esmFile:options.esm,globalExportName:options["global-export"],move:options.move?pth=>options["move-from"]&&pth.startsWith(options["move-from"])?pth.replace(options["move-from"],options["move-to"]||options["move-from"]):pth:void 0,dontExport:(options["dont-export"]??"").split(" "),esmTemplate:options["esm-template"]}),console.log("āœ… Pack complete!");break}default:console.error(`āŒ Unknown command: ${command}`),showHelp(),process.exit(1)}}}},"/modules/[build].js"(require,exports,module){module.exports=arguments[3]},"/modules/module.js"(require,exports,module){const proc=require("[build]"),{moduleDict:moduleDict}=proc,path=require("path");let mainModule;function updateChildren(parent,child,scan){const children=parent?.children;!children||scan&&children.includes(child)||children.push(child)}function raiseModuleNotFound(request){const modname=request.replaceAll("'","\\'");throw new Error("Cannot find module '"+modname+"'")}function Module(id="",parent){this.id=id,this.path=path.dirname(id),this.exports={},updateChildren(parent,this,!1),this.filename=null,this.loaded=!1,this.children=[]}Module.Module=Module,Module._nodeModulePaths=function(from){const paths=[];for(let current=from=path.resolve(from);current!==path.dirname(current);current=path.dirname(current))paths.push(path.join(current,"node_modules"));return paths.push("/node_modules"),paths},Module._cache=Object.create(null),Module._extensions=Object.create(null),Module.builtinModules=["_http_agent","_http_client","_http_common","_http_incoming","_http_outgoing","_http_server","_stream_duplex","_stream_passthrough","_stream_readable","_stream_transform","_stream_wrap","_stream_writable","_tls_common","_tls_wrap","assert","assert/strict","async_hooks","buffer","child_process","cluster","console","constants","crypto","dgram","diagnostics_channel","dns","dns/promises","domain","events","fs","fs/promises","http","http2","https","inspector","inspector/promises","module","net","os","path","path/posix","path/win32","perf_hooks","process","punycode","querystring","readline","readline/promises","repl","stream","stream/consumers","stream/promises","stream/web","string_decoder","sys","timers","timers/promises","tls","trace_events","tty","url","util","util/types","v8","vm","wasi","worker_threads","zlib","node:sea","node:sqlite","node:test","node:test/reporters"];const SpecialModules=["module","[build]"];Module._load=function(request,parent,isMain){if(Module.builtinModules.includes(request))return require.original(request);if(SpecialModules.includes(request))return require(request);const filename=function(request,parent){if([".","..",""].some(start=>request.startsWith(start+path.sep))){const requestPath=request.startsWith(path.sep)?request:path.resolve(request);if(requestPath in moduleDict)return requestPath;const extensions=Object.keys(Module._extensions);for(const extension of extensions){const withext=requestPath+extension;if(withext in moduleDict)return withext}const indexPath=path.join(requestPath,"index");for(const extension of extensions){const withext=indexPath+extension;if(withext in moduleDict)return withext}raiseModuleNotFound(request)}if(parent)for(const maybeNm of parent.paths){const[moduleName,...subdirs]=request.split(path.sep),subdir=subdirs.length?path.join(...subdirs):".",maybe=path.join(maybeNm,moduleName),packageJSON=moduleDict[path.join(maybe,"package.json")];if(packageJSON){if(packageJSON.exports){const{exports:exports}=packageJSON;if("string"==typeof exports)return path.join(maybe,exports);if("object"==typeof exports&&exports[subdir]){const entry=exports[subdir];if("string"==typeof entry)return path.join(maybe,entry);if("object"==typeof entry){if(entry.require)return path.join(maybe,entry.require);if(entry.default)return path.join(maybe,entry.default)}}}if(packageJSON.main)return path.join(maybe,packageJSON.main)}const indexPath=path.join(maybe,request,"index.js");if(indexPath in moduleDict)return indexPath}raiseModuleNotFound(request)}(request,parent),cachedModule=Module._cache[filename];if(void 0!==cachedModule){if(updateChildren(parent,cachedModule,!0),cachedModule.loaded)return cachedModule.exports;if(!cachedModule[kIsCachedByESMLoader])return getExportsForCircularRequire(cachedModule);if(cachedModule[kModuleCircularVisited])return getExportsForCircularRequire(cachedModule);cachedModule[kModuleCircularVisited]=!0}const module=cachedModule||new Module(filename,parent);return cachedModule||(isMain&&(proc.isMain&&(mainModule=module,Module.prototype.require.main=null),module.id="."),Module._cache[filename]=module,module.load(filename)),module.exports},Module.prototype.load=function(filename){this.filename??=filename,this.paths??=Module._nodeModulePaths(path.dirname(filename));const extension=filename.includes(".")?"."+filename.split(".").slice(-1)[0]:"";Module._extensions[extension](this,filename),this.loaded=!0},Module.prototype.require=function(id){return request=id,parent=this,isMain=!1,Module._load.call({__proto__:null,parentFilename:parent?.filename,id:request},request,parent,isMain);var request,parent,isMain},Module.prototype.require.main=null,Object.assign(Module._extensions,{".js":function(module,filename){function require(path){return module.require(path)}require.main=mainModule,require.extensions=Module._extensions,require.cache=Module._cache;const factory=moduleDict[filename],oldworkdir=proc.workdir;proc.workdir=path.dirname(filename),factory(require,module.exports,module),proc.workdir=oldworkdir},".json":function(module,filename){module.exports=moduleDict[filename]}}),Module.prototype.$build$=!0,module.exports=Module},"/modules/path.js"(require,exports,module){const proc=require("[build]");module.exports={sep:"/",delimiter:":",normalize(path){if(!path)return".";let result=path.replace(/\/+/g,"/");result.startsWith("./")&&(result=result.slice(2)),result=result.replace(/\/\.\//g,"/"),result.endsWith("/.")&&(result=result.slice(0,-2));const parts=result.split("/"),newParts=[];for(const part of parts)".."===part?newParts.length>0&&newParts.pop():""!==part&&"."!==part&&newParts.push(part);return result=newParts.join("/"),path.startsWith("/")?result="/"+result:path.startsWith("./")&&(result="./"+result),""===result?".":(path.endsWith("/")&&!result.endsWith("/")&&"."!==result&&(result+="/"),result)},join(...paths){if(0===paths.length)return".";let result="";for(const segment of paths)segment&&(""===result?result=segment:result+="/"+segment);return this.normalize(result)},resolve(...paths){if(0===paths.length)return proc.workdir||"/";let result="",isAbsolute=!1;for(let i=paths.length-1;i>=0;i--){const path=paths[i];path&&(path.startsWith("/")?(result=path,isAbsolute=!0):result=""===result?path:path+"/"+result)}return isAbsolute||(result=(proc.workdir||"/")+"/"+result),this.normalize(result)},dirname(path){if(!path||"."===path||".."===path)return".";if("/"===path)return"/";let cleanPath=path;for(;cleanPath.endsWith("/")&&cleanPath.length>1;)cleanPath=cleanPath.slice(0,-1);const lastSlash=cleanPath.lastIndexOf("/");if(-1===lastSlash)return".";if(0===lastSlash)return"/";return cleanPath.slice(0,lastSlash)||"/"},basename(path,ext){if(!path)return"";const lastSlash=path.lastIndexOf("/");let filename=-1===lastSlash?path:path.slice(lastSlash+1);return""===filename?"":(ext&&"string"==typeof ext&&filename.endsWith(ext)&&(filename=filename.slice(0,-ext.length)),filename)},extname(path){if(!path)return"";const lastSlash=path.lastIndexOf("/"),filename=-1===lastSlash?path:path.slice(lastSlash+1),lastDot=filename.lastIndexOf(".");return lastDot<=0?"":filename.slice(lastDot)},isAbsolute:path=>path&&path.startsWith("/"),relative(from,to){if(!from||!to)return"";const fromPath=this.normalize(from),toPath=this.normalize(to);if(fromPath===toPath)return"";const fromParts=fromPath.split("/").filter(part=>part&&"."!==part),toParts=toPath.split("/").filter(part=>part&&"."!==part);let commonLength=0;const minLength=Math.min(fromParts.length,toParts.length);for(let i=0;i<minLength&&fromParts[i]===toParts[i];i++)commonLength++;const upLevels=fromParts.length-commonLength,remainingParts=toParts.slice(commonLength);let result="";for(let i=0;i<upLevels;i++)result+="../";return result+=remainingParts.join("/"),result||"."},parse(path){if(!path)return{root:"",dir:"",base:"",ext:"",name:""};const root=path.startsWith("/")?"/":"",dir=this.dirname(path),base=this.basename(path),ext=this.extname(path),name=ext?base.slice(0,-ext.length):base;return{root:root,dir:dir,base:base,ext:ext,name:name}},format(pathObject){if(!pathObject||"object"!=typeof pathObject)throw new TypeError("pathObject must be an object");const{root:root="",dir:dir="",base:base="",name:name="",ext:ext=""}=pathObject;if(dir){return this.join(dir,base||name+ext)}return root+(name||base)+ext},get posix(){return this},get win32(){return{...this,sep:"\\",delimiter:";",normalize:path=>this.normalize(path.replace(/\\/g,"/")).replace(/\//g,"\\"),isAbsolute:path=>/^[A-Za-z]:\\/.test(path)||/^\\\\/.test(path)||path.startsWith("\\")}}}}});
package/dist/packitup.mjs CHANGED
@@ -1 +1 @@
1
- const module=(moduleDict=>{const caches={__proto__:null},proc={moduleDict:moduleDict,workdir:"/packitup"},simpRequire=moduleId=>{if(moduleId in caches)return caches[moduleId];const module={exports:{}};return(0,moduleDict["/modules/"+moduleId+".js"])(simpRequire,module.exports,module,proc),caches[moduleId]=module.exports,module.exports};simpRequire.original="function"==typeof require?require:simpRequire,proc.isMain="object"==typeof module&&simpRequire.original.main===module;const Module=simpRequire("module"),factory=()=>{new Module("/packitup/src/index.js");return Module._load("/packitup/src/index.js",void 0,!0)};return factory()})({"/packitup/src/index.js"(require,exports,module){const build=require("./lib/build.js"),builder=require("./lib/builder.js"),cli=require("./lib/cli.js");module.exports={...build,...builder},require.main===module&&cli.main()},"/packitup/src/lib/build-template.js"(require,exports,module){module.exports=(moduleDict,mainfile,projectName,globalExport,isesm)=>{const caches={__proto__:null},proc={moduleDict:moduleDict,workdir:"/"+projectName},simpRequire=moduleId=>{if(moduleId in caches)return caches[moduleId];const module={exports:{}};return(0,moduleDict["/modules/"+moduleId+".js"])(simpRequire,module.exports,module,proc),caches[moduleId]=module.exports,module.exports};simpRequire.original="function"==typeof require?require:simpRequire,proc.isMain="object"==typeof module&&simpRequire.original.main===module;const Module=simpRequire("module"),factory=()=>{new Module(mainfile);return Module._load(mainfile,void 0,!0)};if(isesm)return factory();"object"==typeof exports?module.exports=factory():"function"==typeof define?define(projectName,[],factory):globalThis[globalExport]=factory()}},"/packitup/src/lib/build.js"(require,exports,module){const fs=require("fs"),{sep:pathSep,join:pathJoin,resolve:resolve,relative:relative}=require("path"),templateFunction=require("./build-template.js"),{moduleDict:mdict}=module.$build$?require("[build]"):{},search=(path,rule)=>{const listdir=fs.readdirSync(path),result=[];for(const filename of listdir){const file=path+pathSep+filename;if(fs.statSync(file).isDirectory()){let subfiles=search(file,rule);subfiles=subfiles.filter(filePath=>rule.test(filePath)),result.push(...subfiles);continue}rule.test(file)&&result.push(file)}return result},build=(allJS,main,options={})=>{const{projectName:projectName="project",globalExportName:globalExportName=projectName,esmExport:esmExport="export default module;",dontPack:dontPack=[],move:move=path=>path,node_modules:node_modules=[]}=options,moduleMap={};for(let filePath of allJS){if(filePath.startsWith("./")&&(filePath=filePath.slice(2)),dontPack.some(dont=>dont.test(filePath)))continue;const saveFilePath=move(pathSep+projectName+pathSep+filePath);filePath&&(moduleMap[saveFilePath]=fs.readFileSync(filePath))}for(const[realPath,virtualPath]of node_modules)moduleMap[virtualPath]=fs.readFileSync(realPath);mdict&&Object.entries(mdict).forEach(([key,value])=>{key.startsWith("/modules/")&&(value=String(value).match(/\{([\S\s]*)\}/)[1],moduleMap[key]=value)});const moduleDict=(()=>{const mapping=[];for(const[key,value]of Object.entries(moduleMap)){const pathKey=JSON.stringify(key);key.endsWith(".js")?mapping.push(`${pathKey}(require,exports,module){${value}}`):key.endsWith(".json")?mapping.push(`${pathKey}:${value}`):mapping.push(`${pathKey}:${JSON.stringify(value)}`)}return`{${mapping}}`})(),template=`(${templateFunction})`,esmTemplate=esmExport,projectNameStr=JSON.stringify(projectName),globalExportNameStr=JSON.stringify(globalExportName);return{umd:`${template}(${moduleDict},${JSON.stringify(main)},${projectNameStr},${globalExportNameStr});`,esm:`const module=${`${template}(${moduleDict},${JSON.stringify(main)},${projectNameStr},${globalExportNameStr},1)`};${esmTemplate}`,options:options}};module.exports={build:build,buildDirectory:(directory,options={})=>{if(!options.projectName){let projectName=resolve(directory);const paths=projectName.split(pathSep);let index=1;do{projectName=paths[paths.length-index],index++}while(["src","lib"].includes(projectName)&&index<paths.length);options.projectName=projectName}options.extensions||(options.extensions=[".js",".json",".txt",".svg",".xml",".html"]);const test=path=>options.extensions.some(ext=>path.endsWith(ext)),allJS=search(directory,{test:test}),parentDirectory=resolve(directory).split(pathSep).slice(0,-1).join(pathSep);if(fs.readdirSync(parentDirectory).includes("node_modules")){const nmPath=pathJoin(parentDirectory,"node_modules"),node_modules=search(nmPath,{test:test}).map(direct=>[direct,relative(directory,direct).replace(/^\.\.\//g,"/")]);options.node_modules=node_modules}return build(allJS,pathSep+pathJoin(options.projectName,directory,"index.js"),options)}}},"/packitup/src/lib/builder.js"(require,exports,module){const fs=require("fs"),path=require("path"),{buildDirectory:buildDirectory}=require("./build.js");exports.outputBundle=options=>{let{sourcePath:sourcePath,umdFile:umdFile,esmFile:esmFile,distPath:distPath,esmTemplate:esmTemplate}=options;esmTemplate&&(options.esmExport=fs.readFileSync(esmTemplate));const dist=buildDirectory(sourcePath,options),projectName=dist.options.projectName;distPath.endsWith(path.sep)||(distPath+=path.sep),umdFile??=distPath+projectName+".js",esmFile??=distPath+projectName+".mjs",fs.writeFileSync(umdFile,dist.umd),fs.writeFileSync(esmFile,dist.esm)}},"/packitup/src/lib/cli.js"(require,exports,module){require("path"),require("fs");const{outputBundle:outputBundle}=require("./builder.js");function parseArgs(){const args=process.argv.slice(2),options={},positional=[];return{index:0,curr:args[0],next(){this.index++,this.curr=args[this.index]},peek(n=1){return args[this.index+n]},parse(){for(;this.curr;)this.parseArgument()},parseArgument(){if(this.curr.startsWith("--")){const key=this.curr.slice(2),nextArg=this.peek();return nextArg&&!nextArg.startsWith("--")?(this.next(),void(options[key]=nextArg)):void(options[key]=!0)}this.curr.startsWith("-")?options[this.curr.slice(1)]=!0:(positional.push(this.curr),this.next())}}.parse(),{options:options,positional:positional}}function showHelp(){console.log("\nšŸ“¦ PackItUp - JavaScript Packager\n\nATTENTION: If you're running for the first time, please cd to module path and run \"npm run install\".\n\nUsage: packitup [command] [options]\n\nCommands:\n build <input-directory> [output-directory] Pack a directory\n\nOptions:\n --name <projectName> Specify project name\n --umd <fileName> Specify UMD output file name\n --esm <fileName> Specify ESM output file name\n --esm-template <template> Specify ESM output template\n --dont-export Specify don't export files\n --move-from Move files from this directory\n --move-to Move files to this directory\n --help Show this help message\n\n")}module.exports={parseArgs:parseArgs,main:async function(){const{options:options,positional:positional}=parseArgs();(options.help||0===positional.length)&&(showHelp(),process.exit(0));const command=positional[0];switch(command){case"build":{const input=positional[1],output=positional[2]||".";input||(console.error("āŒ Error: Please specify input directory"),showHelp(),process.exit(1)),console.log(`šŸš€ Starting pack: ${input} → ${output}`),outputBundle({sourcePath:input,projectName:options.name,distPath:output,umdFile:options.umd,esmFile:options.esm,move:options.move?pth=>options["move-from"]&&pth.startsWith(options["move-from"])?pth.replace(options["move-from"],options["move-to"]||options["move-from"]):pth:void 0,dontExport:(options["dont-export"]??"").split(" "),esmTemplate:options["esm-template"]}),console.log("āœ… Pack complete!");break}default:console.error(`āŒ Unknown command: ${command}`),showHelp(),process.exit(1)}}}},"/modules/[build].js"(require,exports,module){module.exports=arguments[3]},"/modules/module.js"(require,exports,module){const proc=require("[build]"),{moduleDict:moduleDict}=proc,path=require("path");let mainModule;function updateChildren(parent,child,scan){const children=parent?.children;!children||scan&&children.includes(child)||children.push(child)}function raiseModuleNotFound(request){const modname=request.replaceAll("'","\\'");throw new Error("Cannot find module '"+modname+"'")}function Module(id="",parent){this.id=id,this.path=path.dirname(id),this.exports={},updateChildren(parent,this,!1),this.filename=null,this.loaded=!1,this.children=[]}Module.Module=Module,Module._nodeModulePaths=function(from){const paths=[];for(let current=from=path.resolve(from);current!==path.dirname(current);current=path.dirname(current))paths.push(path.join(current,"node_modules"));return paths.push("/node_modules"),paths},Module._cache=Object.create(null),Module._extensions=Object.create(null),Module.builtinModules=["_http_agent","_http_client","_http_common","_http_incoming","_http_outgoing","_http_server","_stream_duplex","_stream_passthrough","_stream_readable","_stream_transform","_stream_wrap","_stream_writable","_tls_common","_tls_wrap","assert","assert/strict","async_hooks","buffer","child_process","cluster","console","constants","crypto","dgram","diagnostics_channel","dns","dns/promises","domain","events","fs","fs/promises","http","http2","https","inspector","inspector/promises","module","net","os","path","path/posix","path/win32","perf_hooks","process","punycode","querystring","readline","readline/promises","repl","stream","stream/consumers","stream/promises","stream/web","string_decoder","sys","timers","timers/promises","tls","trace_events","tty","url","util","util/types","v8","vm","wasi","worker_threads","zlib","node:sea","node:sqlite","node:test","node:test/reporters"];const SpecialModules=["module","[build]"];Module._load=function(request,parent,isMain){if(Module.builtinModules.includes(request))return require.original(request);if(SpecialModules.includes(request))return require(request);const filename=function(request,parent){if([".","..",""].some(start=>request.startsWith(start+path.sep))){const requestPath=request.startsWith(path.sep)?request:path.resolve(request);if(requestPath in moduleDict)return requestPath;const extensions=Object.keys(Module._extensions);for(const extension of extensions){const withext=requestPath+extension;if(withext in moduleDict)return withext}const indexPath=path.join(requestPath,"index");for(const extension of extensions){const withext=indexPath+extension;if(withext in moduleDict)return withext}raiseModuleNotFound(request)}if(parent)for(const maybeNm of parent.paths){const[moduleName,...subdirs]=request.split(path.sep),subdir=subdirs.length?path.join(...subdirs):".",maybe=path.join(maybeNm,moduleName),packageJSON=moduleDict[path.join(maybe,"package.json")];if(packageJSON){if(packageJSON.exports){const{exports:exports}=packageJSON;if("string"==typeof exports)return path.join(maybe,exports);if("object"==typeof exports&&exports[subdir]){const entry=exports[subdir];if("string"==typeof entry)return path.join(maybe,entry);if("object"==typeof entry){if(entry.require)return path.join(maybe,entry.require);if(entry.default)return path.join(maybe,entry.default)}}}if(packageJSON.main)return path.join(maybe,packageJSON.main)}const indexPath=path.join(maybe,request,"index.js");if(indexPath in moduleDict)return indexPath}raiseModuleNotFound(request)}(request,parent),cachedModule=Module._cache[filename];if(void 0!==cachedModule){if(updateChildren(parent,cachedModule,!0),cachedModule.loaded)return cachedModule.exports;if(!cachedModule[kIsCachedByESMLoader])return getExportsForCircularRequire(cachedModule);if(cachedModule[kModuleCircularVisited])return getExportsForCircularRequire(cachedModule);cachedModule[kModuleCircularVisited]=!0}const module=cachedModule||new Module(filename,parent);return cachedModule||(isMain&&(proc.isMain&&(mainModule=module,Module.prototype.require.main=null),module.id="."),Module._cache[filename]=module,module.load(filename)),module.exports},Module.prototype.load=function(filename){this.filename??=filename,this.paths??=Module._nodeModulePaths(path.dirname(filename));const extension=filename.includes(".")?"."+filename.split(".").slice(-1)[0]:"";Module._extensions[extension](this,filename),this.loaded=!0},Module.prototype.require=function(id){return request=id,parent=this,isMain=!1,Module._load.call({__proto__:null,parentFilename:parent?.filename,id:request},request,parent,isMain);var request,parent,isMain},Module.prototype.require.main=null,Object.assign(Module._extensions,{".js":function(module,filename){function require(path){return module.require(path)}require.main=mainModule,require.extensions=Module._extensions,require.cache=Module._cache;const factory=moduleDict[filename],oldworkdir=proc.workdir;proc.workdir=path.dirname(filename),factory(require,module.exports,module),proc.workdir=oldworkdir},".json":function(module,filename){module.exports=moduleDict[filename]}}),Module.prototype.$build$=!0,module.exports=Module},"/modules/path.js"(require,exports,module){const proc=require("[build]");module.exports={sep:"/",delimiter:":",normalize(path){if(!path)return".";let result=path.replace(/\/+/g,"/");result.startsWith("./")&&(result=result.slice(2)),result=result.replace(/\/\.\//g,"/"),result.endsWith("/.")&&(result=result.slice(0,-2));const parts=result.split("/"),newParts=[];for(const part of parts)".."===part?newParts.length>0&&newParts.pop():""!==part&&"."!==part&&newParts.push(part);return result=newParts.join("/"),path.startsWith("/")?result="/"+result:path.startsWith("./")&&(result="./"+result),""===result?".":(path.endsWith("/")&&!result.endsWith("/")&&"."!==result&&(result+="/"),result)},join(...paths){if(0===paths.length)return".";let result="";for(const segment of paths)segment&&(""===result?result=segment:result+="/"+segment);return this.normalize(result)},resolve(...paths){if(0===paths.length)return proc.workdir||"/";let result="",isAbsolute=!1;for(let i=paths.length-1;i>=0;i--){const path=paths[i];path&&(path.startsWith("/")?(result=path,isAbsolute=!0):result=""===result?path:path+"/"+result)}return isAbsolute||(result=(proc.workdir||"/")+"/"+result),this.normalize(result)},dirname(path){if(!path||"."===path||".."===path)return".";if("/"===path)return"/";let cleanPath=path;for(;cleanPath.endsWith("/")&&cleanPath.length>1;)cleanPath=cleanPath.slice(0,-1);const lastSlash=cleanPath.lastIndexOf("/");if(-1===lastSlash)return".";if(0===lastSlash)return"/";return cleanPath.slice(0,lastSlash)||"/"},basename(path,ext){if(!path)return"";const lastSlash=path.lastIndexOf("/");let filename=-1===lastSlash?path:path.slice(lastSlash+1);return""===filename?"":(ext&&"string"==typeof ext&&filename.endsWith(ext)&&(filename=filename.slice(0,-ext.length)),filename)},extname(path){if(!path)return"";const lastSlash=path.lastIndexOf("/"),filename=-1===lastSlash?path:path.slice(lastSlash+1),lastDot=filename.lastIndexOf(".");return lastDot<=0?"":filename.slice(lastDot)},isAbsolute:path=>path&&path.startsWith("/"),relative(from,to){if(!from||!to)return"";const fromPath=this.normalize(from),toPath=this.normalize(to);if(fromPath===toPath)return"";const fromParts=fromPath.split("/").filter(part=>part&&"."!==part),toParts=toPath.split("/").filter(part=>part&&"."!==part);let commonLength=0;const minLength=Math.min(fromParts.length,toParts.length);for(let i=0;i<minLength&&fromParts[i]===toParts[i];i++)commonLength++;const upLevels=fromParts.length-commonLength,remainingParts=toParts.slice(commonLength);let result="";for(let i=0;i<upLevels;i++)result+="../";return result+=remainingParts.join("/"),result||"."},parse(path){if(!path)return{root:"",dir:"",base:"",ext:"",name:""};const root=path.startsWith("/")?"/":"",dir=this.dirname(path),base=this.basename(path),ext=this.extname(path),name=ext?base.slice(0,-ext.length):base;return{root:root,dir:dir,base:base,ext:ext,name:name}},format(pathObject){if(!pathObject||"object"!=typeof pathObject)throw new TypeError("pathObject must be an object");const{root:root="",dir:dir="",base:base="",name:name="",ext:ext=""}=pathObject;if(dir){return this.join(dir,base||name+ext)}return root+(name||base)+ext},get posix(){return this},get win32(){return{...this,sep:"\\",delimiter:";",normalize:path=>this.normalize(path.replace(/\\/g,"/")).replace(/\//g,"\\"),isAbsolute:path=>/^[A-Za-z]:\\/.test(path)||/^\\\\/.test(path)||path.startsWith("\\")}}}}});export const{build:build,buildDirectory:buildDirectory,outputBundle:outputBundle}=module;
1
+ const module=(moduleDict=>{const caches={__proto__:null},proc={moduleDict:moduleDict,workdir:"/packitup"},simpRequire=moduleId=>{if(moduleId in caches)return caches[moduleId];const module={exports:{}};return(0,moduleDict["/modules/"+moduleId+".js"])(simpRequire,module.exports,module,proc),caches[moduleId]=module.exports,module.exports};simpRequire.original="function"==typeof require?require:simpRequire,proc.isMain="object"==typeof module&&simpRequire.original.main===module;const Module=simpRequire("module"),factory=()=>{new Module("/packitup/src/index.js");return Module._load("/packitup/src/index.js",void 0,!0)};return factory()})({"/packitup/src/index.js"(require,exports,module){const build=require("./lib/build.js"),builder=require("./lib/builder.js"),cli=require("./lib/cli.js");module.exports={...build,...builder},require.main===module&&cli.main()},"/packitup/src/lib/build-template.js"(require,exports,module){module.exports=(moduleDict,mainfile,projectName,globalExport,isesm)=>{const caches={__proto__:null},proc={moduleDict:moduleDict,workdir:"/"+projectName},simpRequire=moduleId=>{if(moduleId in caches)return caches[moduleId];const module={exports:{}};return(0,moduleDict["/modules/"+moduleId+".js"])(simpRequire,module.exports,module,proc),caches[moduleId]=module.exports,module.exports};simpRequire.original="function"==typeof require?require:simpRequire,proc.isMain="object"==typeof module&&simpRequire.original.main===module;const Module=simpRequire("module"),factory=()=>{new Module(mainfile);return Module._load(mainfile,void 0,!0)};if(isesm)return factory();"object"==typeof exports?module.exports=factory():"function"==typeof define?define(projectName,[],factory):globalThis[globalExport]=factory()}},"/packitup/src/lib/build.js"(require,exports,module){const fs=require("fs"),{sep:pathSep,join:pathJoin,resolve:resolve,relative:relative}=require("path"),templateFunction=require("./build-template.js"),{moduleDict:mdict}=module.$build$?require("[build]"):{},search=(path,rule)=>{const listdir=fs.readdirSync(path),result=[];for(const filename of listdir){const file=path+pathSep+filename;if(fs.statSync(file).isDirectory()){let subfiles=search(file,rule);subfiles=subfiles.filter(filePath=>rule.test(filePath)),result.push(...subfiles);continue}rule.test(file)&&result.push(file)}return result},build=(allJS,main,options={})=>{const{projectName:projectName="project",globalExportName:globalExportName=projectName,esmExport:esmExport="export default module;",dontPack:dontPack=[],move:move=path=>path,node_modules:node_modules=[]}=options,moduleMap={};for(let filePath of allJS){if(filePath.startsWith("./")&&(filePath=filePath.slice(2)),dontPack.some(dont=>dont.test(filePath)))continue;const saveFilePath=move(pathSep+projectName+pathSep+filePath);filePath&&(moduleMap[saveFilePath]=fs.readFileSync(filePath))}for(const[realPath,virtualPath]of node_modules)moduleMap[virtualPath]=fs.readFileSync(realPath);mdict&&Object.entries(mdict).forEach(([key,value])=>{key.startsWith("/modules/")&&(value=String(value).match(/\{([\S\s]*)\}/)[1],moduleMap[key]=value)});const moduleDict=(()=>{const mapping=[];for(const[key,value]of Object.entries(moduleMap)){const pathKey=JSON.stringify(key);key.endsWith(".js")?mapping.push(`${pathKey}(require,exports,module){${value}}`):key.endsWith(".json")?mapping.push(`${pathKey}:${value}`):mapping.push(`${pathKey}:${JSON.stringify(value)}`)}return`{${mapping}}`})(),template=`(${templateFunction})`,esmTemplate=esmExport,projectNameStr=JSON.stringify(projectName),globalExportNameStr=JSON.stringify(globalExportName);return{umd:`${template}(${moduleDict},${JSON.stringify(main)},${projectNameStr},${globalExportNameStr});`,esm:`const module=${`${template}(${moduleDict},${JSON.stringify(main)},${projectNameStr},${globalExportNameStr},1)`};${esmTemplate}`,options:options}};module.exports={build:build,buildDirectory:(directory,options={})=>{if(!options.projectName){let projectName=resolve(directory);const paths=projectName.split(pathSep);let index=1;do{projectName=paths[paths.length-index],index++}while(["src","lib"].includes(projectName)&&index<paths.length);options.projectName=projectName}options.extensions||(options.extensions=[".js",".json",".txt",".svg",".xml",".html"]);const test=path=>options.extensions.some(ext=>path.endsWith(ext)),allJS=search(directory,{test:test}),parentDirectory=resolve(directory).split(pathSep).slice(0,-1).join(pathSep);if(fs.readdirSync(parentDirectory).includes("node_modules")){const nmPath=pathJoin(parentDirectory,"node_modules"),node_modules=search(nmPath,{test:test}).map(direct=>[direct,relative(directory,direct).replace(/^\.\.\//g,"/")]);options.node_modules=node_modules}return build(allJS,pathSep+pathJoin(options.projectName,directory,"index.js"),options)}}},"/packitup/src/lib/builder.js"(require,exports,module){const fs=require("fs"),path=require("path"),{buildDirectory:buildDirectory}=require("./build.js");exports.outputBundle=options=>{let{sourcePath:sourcePath,umdFile:umdFile,esmFile:esmFile,distPath:distPath,esmTemplate:esmTemplate}=options;esmTemplate&&(options.esmExport=fs.readFileSync(esmTemplate));const dist=buildDirectory(sourcePath,options),projectName=dist.options.projectName;distPath.endsWith(path.sep)||(distPath+=path.sep),umdFile??=distPath+projectName+".js",esmFile??=distPath+projectName+".mjs",fs.writeFileSync(umdFile,dist.umd),fs.writeFileSync(esmFile,dist.esm)}},"/packitup/src/lib/cli.js"(require,exports,module){require("path"),require("fs");const{outputBundle:outputBundle}=require("./builder.js");function parseArgs(){const args=process.argv.slice(2),options={},positional=[];return{index:0,curr:args[0],next(){this.index++,this.curr=args[this.index]},peek(n=1){return args[this.index+n]},parse(){for(;this.curr;)this.parseArgument()},parseArgument(){if(this.curr.startsWith("--")){const key=this.curr.slice(2),nextArg=this.peek();return nextArg&&!nextArg.startsWith("--")?(this.next(),void(options[key]=nextArg)):void(options[key]=!0)}this.curr.startsWith("-")?options[this.curr.slice(1)]=!0:(positional.push(this.curr),this.next())}}.parse(),{options:options,positional:positional}}function showHelp(){console.log("\nšŸ“¦ PackItUp - JavaScript Packager\n\nATTENTION: If you're running for the first time, please cd to module path and run \"npm run install\".\n\nUsage: packitup [command] [options]\n\nCommands:\n build <input-directory> [output-directory] Pack a directory\n\nOptions:\n --name <projectName> Specify project name\n --umd <fileName> Specify UMD output file name\n --esm <fileName> Specify ESM output file name\n --esm-template <template> Specify ESM output template\n --dont-export Specify don't export files\n --global-export Specify export to global object's variable name.\n --move-from Move files from this directory\n --move-to Move files to this directory\n --help Show this help message\n\n")}module.exports={parseArgs:parseArgs,main:async function(){const{options:options,positional:positional}=parseArgs();(options.help||0===positional.length)&&(showHelp(),process.exit(0));const command=positional[0];switch(command){case"build":{const input=positional[1],output=positional[2]||".";input||(console.error("āŒ Error: Please specify input directory"),showHelp(),process.exit(1)),console.log(`šŸš€ Starting pack: ${input} → ${output}`),outputBundle({sourcePath:input,projectName:options.name,distPath:output,umdFile:options.umd,esmFile:options.esm,globalExportName:options["global-export"],move:options.move?pth=>options["move-from"]&&pth.startsWith(options["move-from"])?pth.replace(options["move-from"],options["move-to"]||options["move-from"]):pth:void 0,dontExport:(options["dont-export"]??"").split(" "),esmTemplate:options["esm-template"]}),console.log("āœ… Pack complete!");break}default:console.error(`āŒ Unknown command: ${command}`),showHelp(),process.exit(1)}}}},"/modules/[build].js"(require,exports,module){module.exports=arguments[3]},"/modules/module.js"(require,exports,module){const proc=require("[build]"),{moduleDict:moduleDict}=proc,path=require("path");let mainModule;function updateChildren(parent,child,scan){const children=parent?.children;!children||scan&&children.includes(child)||children.push(child)}function raiseModuleNotFound(request){const modname=request.replaceAll("'","\\'");throw new Error("Cannot find module '"+modname+"'")}function Module(id="",parent){this.id=id,this.path=path.dirname(id),this.exports={},updateChildren(parent,this,!1),this.filename=null,this.loaded=!1,this.children=[]}Module.Module=Module,Module._nodeModulePaths=function(from){const paths=[];for(let current=from=path.resolve(from);current!==path.dirname(current);current=path.dirname(current))paths.push(path.join(current,"node_modules"));return paths.push("/node_modules"),paths},Module._cache=Object.create(null),Module._extensions=Object.create(null),Module.builtinModules=["_http_agent","_http_client","_http_common","_http_incoming","_http_outgoing","_http_server","_stream_duplex","_stream_passthrough","_stream_readable","_stream_transform","_stream_wrap","_stream_writable","_tls_common","_tls_wrap","assert","assert/strict","async_hooks","buffer","child_process","cluster","console","constants","crypto","dgram","diagnostics_channel","dns","dns/promises","domain","events","fs","fs/promises","http","http2","https","inspector","inspector/promises","module","net","os","path","path/posix","path/win32","perf_hooks","process","punycode","querystring","readline","readline/promises","repl","stream","stream/consumers","stream/promises","stream/web","string_decoder","sys","timers","timers/promises","tls","trace_events","tty","url","util","util/types","v8","vm","wasi","worker_threads","zlib","node:sea","node:sqlite","node:test","node:test/reporters"];const SpecialModules=["module","[build]"];Module._load=function(request,parent,isMain){if(Module.builtinModules.includes(request))return require.original(request);if(SpecialModules.includes(request))return require(request);const filename=function(request,parent){if([".","..",""].some(start=>request.startsWith(start+path.sep))){const requestPath=request.startsWith(path.sep)?request:path.resolve(request);if(requestPath in moduleDict)return requestPath;const extensions=Object.keys(Module._extensions);for(const extension of extensions){const withext=requestPath+extension;if(withext in moduleDict)return withext}const indexPath=path.join(requestPath,"index");for(const extension of extensions){const withext=indexPath+extension;if(withext in moduleDict)return withext}raiseModuleNotFound(request)}if(parent)for(const maybeNm of parent.paths){const[moduleName,...subdirs]=request.split(path.sep),subdir=subdirs.length?path.join(...subdirs):".",maybe=path.join(maybeNm,moduleName),packageJSON=moduleDict[path.join(maybe,"package.json")];if(packageJSON){if(packageJSON.exports){const{exports:exports}=packageJSON;if("string"==typeof exports)return path.join(maybe,exports);if("object"==typeof exports&&exports[subdir]){const entry=exports[subdir];if("string"==typeof entry)return path.join(maybe,entry);if("object"==typeof entry){if(entry.require)return path.join(maybe,entry.require);if(entry.default)return path.join(maybe,entry.default)}}}if(packageJSON.main)return path.join(maybe,packageJSON.main)}const indexPath=path.join(maybe,request,"index.js");if(indexPath in moduleDict)return indexPath}raiseModuleNotFound(request)}(request,parent),cachedModule=Module._cache[filename];if(void 0!==cachedModule){if(updateChildren(parent,cachedModule,!0),cachedModule.loaded)return cachedModule.exports;if(!cachedModule[kIsCachedByESMLoader])return getExportsForCircularRequire(cachedModule);if(cachedModule[kModuleCircularVisited])return getExportsForCircularRequire(cachedModule);cachedModule[kModuleCircularVisited]=!0}const module=cachedModule||new Module(filename,parent);return cachedModule||(isMain&&(proc.isMain&&(mainModule=module,Module.prototype.require.main=null),module.id="."),Module._cache[filename]=module,module.load(filename)),module.exports},Module.prototype.load=function(filename){this.filename??=filename,this.paths??=Module._nodeModulePaths(path.dirname(filename));const extension=filename.includes(".")?"."+filename.split(".").slice(-1)[0]:"";Module._extensions[extension](this,filename),this.loaded=!0},Module.prototype.require=function(id){return request=id,parent=this,isMain=!1,Module._load.call({__proto__:null,parentFilename:parent?.filename,id:request},request,parent,isMain);var request,parent,isMain},Module.prototype.require.main=null,Object.assign(Module._extensions,{".js":function(module,filename){function require(path){return module.require(path)}require.main=mainModule,require.extensions=Module._extensions,require.cache=Module._cache;const factory=moduleDict[filename],oldworkdir=proc.workdir;proc.workdir=path.dirname(filename),factory(require,module.exports,module),proc.workdir=oldworkdir},".json":function(module,filename){module.exports=moduleDict[filename]}}),Module.prototype.$build$=!0,module.exports=Module},"/modules/path.js"(require,exports,module){const proc=require("[build]");module.exports={sep:"/",delimiter:":",normalize(path){if(!path)return".";let result=path.replace(/\/+/g,"/");result.startsWith("./")&&(result=result.slice(2)),result=result.replace(/\/\.\//g,"/"),result.endsWith("/.")&&(result=result.slice(0,-2));const parts=result.split("/"),newParts=[];for(const part of parts)".."===part?newParts.length>0&&newParts.pop():""!==part&&"."!==part&&newParts.push(part);return result=newParts.join("/"),path.startsWith("/")?result="/"+result:path.startsWith("./")&&(result="./"+result),""===result?".":(path.endsWith("/")&&!result.endsWith("/")&&"."!==result&&(result+="/"),result)},join(...paths){if(0===paths.length)return".";let result="";for(const segment of paths)segment&&(""===result?result=segment:result+="/"+segment);return this.normalize(result)},resolve(...paths){if(0===paths.length)return proc.workdir||"/";let result="",isAbsolute=!1;for(let i=paths.length-1;i>=0;i--){const path=paths[i];path&&(path.startsWith("/")?(result=path,isAbsolute=!0):result=""===result?path:path+"/"+result)}return isAbsolute||(result=(proc.workdir||"/")+"/"+result),this.normalize(result)},dirname(path){if(!path||"."===path||".."===path)return".";if("/"===path)return"/";let cleanPath=path;for(;cleanPath.endsWith("/")&&cleanPath.length>1;)cleanPath=cleanPath.slice(0,-1);const lastSlash=cleanPath.lastIndexOf("/");if(-1===lastSlash)return".";if(0===lastSlash)return"/";return cleanPath.slice(0,lastSlash)||"/"},basename(path,ext){if(!path)return"";const lastSlash=path.lastIndexOf("/");let filename=-1===lastSlash?path:path.slice(lastSlash+1);return""===filename?"":(ext&&"string"==typeof ext&&filename.endsWith(ext)&&(filename=filename.slice(0,-ext.length)),filename)},extname(path){if(!path)return"";const lastSlash=path.lastIndexOf("/"),filename=-1===lastSlash?path:path.slice(lastSlash+1),lastDot=filename.lastIndexOf(".");return lastDot<=0?"":filename.slice(lastDot)},isAbsolute:path=>path&&path.startsWith("/"),relative(from,to){if(!from||!to)return"";const fromPath=this.normalize(from),toPath=this.normalize(to);if(fromPath===toPath)return"";const fromParts=fromPath.split("/").filter(part=>part&&"."!==part),toParts=toPath.split("/").filter(part=>part&&"."!==part);let commonLength=0;const minLength=Math.min(fromParts.length,toParts.length);for(let i=0;i<minLength&&fromParts[i]===toParts[i];i++)commonLength++;const upLevels=fromParts.length-commonLength,remainingParts=toParts.slice(commonLength);let result="";for(let i=0;i<upLevels;i++)result+="../";return result+=remainingParts.join("/"),result||"."},parse(path){if(!path)return{root:"",dir:"",base:"",ext:"",name:""};const root=path.startsWith("/")?"/":"",dir=this.dirname(path),base=this.basename(path),ext=this.extname(path),name=ext?base.slice(0,-ext.length):base;return{root:root,dir:dir,base:base,ext:ext,name:name}},format(pathObject){if(!pathObject||"object"!=typeof pathObject)throw new TypeError("pathObject must be an object");const{root:root="",dir:dir="",base:base="",name:name="",ext:ext=""}=pathObject;if(dir){return this.join(dir,base||name+ext)}return root+(name||base)+ext},get posix(){return this},get win32(){return{...this,sep:"\\",delimiter:";",normalize:path=>this.normalize(path.replace(/\\/g,"/")).replace(/\//g,"\\"),isAbsolute:path=>/^[A-Za-z]:\\/.test(path)||/^\\\\/.test(path)||path.startsWith("\\")}}}}});export const{build:build,buildDirectory:buildDirectory,outputBundle:outputBundle}=module;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "packitup",
3
- "version": "0.2.4",
3
+ "version": "0.3.0",
4
4
  "description": "A JavaScript packager with a complete module system. Currently supports CommonJS modules and can export to ES modules.",
5
5
  "keywords": [
6
6
  "javascript",