packitup 0.1.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/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2025 stevena_star
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any purpose
6
+ with or without fee is hereby granted, provided that the above copyright notice
7
+ and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
11
+ FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,107 @@
1
+ # PackItUp 📦
2
+
3
+ (这个文档用AI写的 说实话这个文档我自己都看不懂 我也不确定用的对不对 所以不会用最好还是直接找我)
4
+
5
+ > "Pack it up!" - A simple and straightforward JavaScript packager
6
+
7
+ ## ✨ Features
8
+ - 🔄 **Self-contained** - Can pack itself, truly zero-dependency
9
+ - 🚀 **Single file output** - All code bundled into one file (or two files, a umd export, a esm export)
10
+ - ⚙️ **Virtual module system** - Built-in core module simulation
11
+ - 📁 **Zero configuration** - Works out of the box
12
+
13
+ ## 🚀 Quick Start
14
+
15
+ ### Using npx (recommended, no installation needed)
16
+ ```bash
17
+ npx packitup build ./src ./dist
18
+ ```
19
+
20
+ Local installation in your project
21
+
22
+ ```bash
23
+ # Install as dev dependency
24
+ npm install --save-dev packitup
25
+
26
+ # Then add to package.json scripts:
27
+ {
28
+ "scripts": {
29
+ "build": "npx packitup build ./src ./dist"
30
+ }
31
+ }
32
+
33
+ # Run
34
+ npm run build
35
+ ```
36
+
37
+ 📖 Usage
38
+
39
+ ```bash
40
+ # Basic usage
41
+ npx packitup build <input-directory> [output-directory]
42
+
43
+ # With options
44
+ npx packitup build ./src ./dist --name my-app --umd bundle.js
45
+
46
+ # Show help
47
+ npx packitup --help
48
+ ```
49
+
50
+ ⚙️ Options
51
+
52
+ · --name <projectName> - Specify project name (If not specified, it will be automatically specified according to the file)
53
+ · --umd <fileName> - UMD output filename (default: \[project name\].js)
54
+ · --esm <fileName> - ESM output filename (default: \[project name\].esm.js)
55
+ · --help - Show help message
56
+
57
+ 🔧 API Usage
58
+
59
+ ```javascript
60
+ const { buildDirectory } = require('packitup');
61
+
62
+ const result = buildDirectory('./src', {
63
+ projectName: 'my-app',
64
+ extensions: ['.js', '.json']
65
+ });
66
+
67
+ console.log(result.umd); // UMD bundle size
68
+ console.log(result.esm); // ESM bundle size
69
+ ```
70
+ or esm import
71
+ ```javascript
72
+ impory { buildDirectory } from 'packitup';
73
+
74
+ const result = buildDirectory('./src', {
75
+ projectName: 'my-app',
76
+ extensions: ['.js', '.json']
77
+ });
78
+
79
+ console.log(result.umd); // UMD bundle size
80
+ console.log(result.esm); // ESM bundle size
81
+ ```
82
+ or from global import
83
+ ```javascript
84
+ const { buildDirectory } = PackItUp;
85
+
86
+ const result = buildDirectory('./src', {
87
+ projectName: 'my-app',
88
+ extensions: ['.js', '.json']
89
+ });
90
+
91
+ console.log(result.umd); // UMD bundle size
92
+ console.log(result.esm); // ESM bundle size
93
+ ```
94
+
95
+ 🤔 FAQ
96
+
97
+ Q: Why is there no packitup command?
98
+
99
+ A: PackItUp is designed to work without global installation. Use npx packitup or install locally in your project.
100
+
101
+ Q: Which module systems are supported?
102
+
103
+ A: Currently supports CommonJS, and can export to both UMD and ESM formats.
104
+
105
+ 📄 License
106
+
107
+ ISC License - See LICENSE file
@@ -0,0 +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}=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}=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))}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}),parent=fs.readdirSync(resolve(directory).split(pathSep).slice(0,-1).join(pathSep));if(parent.includes("node_modules")){const node_modules=search(parent,{test:test});allJS.push(...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)}positional.push(this.curr),this.next()}}.parse(),{options:options,positional:positional}}function showHelp(){console.log("\n📦 PackItUp - JavaScript Packager\nUsage: node <script> [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 --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,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("\\")}}}}});
@@ -0,0 +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}=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}=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))}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}),parent=fs.readdirSync(resolve(directory).split(pathSep).slice(0,-1).join(pathSep));if(parent.includes("node_modules")){const node_modules=search(parent,{test:test});allJS.push(...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)}positional.push(this.curr),this.next()}}.parse(),{options:options,positional:positional}}function showHelp(){console.log("\n📦 PackItUp - JavaScript Packager\nUsage: node <script> [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 --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,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 ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "packitup",
3
+ "version": "0.1.0",
4
+ "description": "A JavaScript packager with a complete module system. Currently supports CommonJS modules and can export to ES modules.",
5
+ "keywords": [
6
+ "javascript",
7
+ "packager",
8
+ "bundler",
9
+ "packitup"
10
+ ],
11
+ "license": "ISC",
12
+ "author": "stevena_star",
13
+ "type": "commonjs",
14
+ "main": "./dist/packitup.js",
15
+ "module": "./dist/packitup.mjs",
16
+ "types": "./packitup.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "import": "./dist/packitup.mjs",
20
+ "require": "./dist/packitup.js",
21
+ "default": "./dist/packitup.js"
22
+ },
23
+ "./package.json": "./package.json"
24
+ },
25
+ "unpkg": "./dist/packitup.js",
26
+ "jsdelivr": "./dist/packitup.js",
27
+ "files": [
28
+ "dist",
29
+ "packitup.d.ts",
30
+ "LICENSE",
31
+ "README.md"
32
+ ],
33
+ "scripts": {
34
+ "test": "node . build test test-dist\nnode ./test-dist/test"
35
+ }
36
+ }
package/packitup.d.ts ADDED
@@ -0,0 +1,39 @@
1
+
2
+ export interface Options {
3
+ projectName?: string;
4
+ globalExportName?: string;
5
+ esmExport?: string;
6
+ dontPack?: string[];
7
+ move?: (path: string) => string;
8
+ }
9
+
10
+ export interface BuildDirectoryOptions extends Options {
11
+ extensions?: string[];
12
+ }
13
+
14
+ export interface OutputBundleOptions extends BuildDirectoryOptions {
15
+ sourcePath?: string | string[];
16
+ umdFile?: string;
17
+ esmFile?: string;
18
+ distPath?: string;
19
+ esmTemplate?: string;
20
+ }
21
+
22
+ export interface BuildResult<T extends Options = Options> {
23
+ umd: string;
24
+ esm: string;
25
+ options: T;
26
+ }
27
+
28
+ export function build<T extends Options = Options>(
29
+ allJS: string[],
30
+ main: string,
31
+ options?: T
32
+ ): BuildResult<T>;
33
+
34
+ export function buildDirectory<T extends BuildDirectoryOptions = BuildDirectoryOptions>(
35
+ directory: string,
36
+ options?: T
37
+ ): BuildResult<T>;
38
+
39
+ export function outputBundle(options: OutputBundleOptions): void;