mock-service-cli-ultra 4.8.0 → 4.9.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/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  [![release status](https://github.com/chandq/mock-service-cli/actions/workflows/release.yml/badge.svg)](https://github.com/chandq/mock-service-cli/actions/workflows/release.yml)
2
2
  [![Coverage Status](https://coveralls.io/repos/github/chandq/mock-service-cli/badge.svg?branch=master)](https://coveralls.io/github/chandq/mock-service-cli?branch=master)
3
3
  [![mock-service-cli](https://img.shields.io/github/package-json/v/chandq/mock-service-cli?style=flat-square)](https://www.npmjs.com/package/mock-service-cli)
4
- [![license:MIT](https://img.shields.io/npm/l/vue.svg?sanitize=true)](https://github.com/chandq/mock-service-cli/blob/master/LICENSE.md)
4
+ [![license:MIT](https://img.shields.io/npm/l/vue.svg?sanitize=true)](https://github.com/chandq/mock-service-cli/blob/master/LICENSE)
5
5
 
6
6
  # 🦅 mock-service-cli
7
7
 
@@ -93,7 +93,8 @@ npx mock-service-cli [options] [path]
93
93
  | `-R` 或 `--static-server` | 启用单目录静态服务器,指定静态资源目录 | - |
94
94
  | `--spa-fallback <path>` | 单目录模式显式启用 SPA 回退 | - |
95
95
  | `--static-config <file>` | 使用自包含 JSON 配置启动静态服务器 | - |
96
- | `-w` 或 `--open` | 自动打开 API 概览页、文件浏览器页 | false |
96
+ | `-w` 或 `--open` | 自动打开可用的 Web 页面或 API 概览页 | false |
97
+ | `--watch-depth <n>` | 限制静态服务器文件监听递归深度(非负整数) | 无限 |
97
98
  | `-e` 或 `--explorer` | 启用文件浏览器服务器,指定要浏览的目录 | ./ |
98
99
  | `--edit` | 启用文件浏览器的新建、重命名、删除和上传操作 | false |
99
100
  | `--auth <password>` | 为文件浏览器启用密码认证(仅可搭配 `--explorer`) | - |
@@ -132,8 +133,9 @@ mock-service-cli --static-config ./static-server.json
132
133
  ```
133
134
 
134
135
  静态服务器会监听资源变化并向 HTML 页面注入热更新客户端:CSS 文件更新时替换样式表,其余变更刷新页面。
135
- 默认不打开浏览器;在配置中设置 `"open": true` 或提供页面路径即可打开。完整配置字段和示例见
136
+ 默认不打开浏览器;使用 `-w/--open` 可自动打开静态服务器页面。也可在配置中设置 `"open": true` 或提供页面路径。完整配置字段和示例见
136
137
  [`docs/static-server.config.example.json`](./docs/static-server.config.example.json):支持忽略规则、SPA 回退、挂载目录、代理、HTTPS、CORS、响应头和自定义浏览器命令。
138
+ `watch.depth` 可限制 chokidar 递归监听层数;未设置时为无限深度,大目录建议显式设置有限值。命令行 `--watch-depth <n>` 优先于配置文件。
137
139
  配置文件只在顶层保留服务器级字段。所有应用都放在 `mounts` 中,并可独立设置 `directory`、`spaFallback`、`proxy`、`cors`、`headers`、`requestHeaders` 和 `secure`。mount 未设置 `path` 时默认挂载到 `/`;`directory` 可省略,但该应用必须配置至少一条代理。代理键使用完整公开路径,例如 `/api/app`。
138
140
  `headers` 是发送给客户端的响应头。`requestHeaders` 是发送给该应用全部代理上游的请求头;也可放在单个 `proxy` 规则中,覆盖或追加 mount 级请求头。代理规则使用 `{ "target": "http://...", "rewrite": true }`;`rewrite` 为 true 时只移除匹配的完整代理前缀并保留剩余路径和 query string。应用级 `secure` 控制其代理 HTTPS 目标的证书校验,默认 `false`。配置模式不接受 `--proxy-options`、`--rewrite` 或 `--spa-fallback`。
139
141
  未设置 `spaFallback` 时,应用目录会显示可点击的目录索引;可直接访问其中的 HTML 文件。mount 未命中的路由不会继续进入其他应用的 SPA fallback。
@@ -147,6 +149,9 @@ mock-service-cli -D ./dist
147
149
 
148
150
  # 指定公共路径和端口
149
151
  mock-service-cli -D ./dist -b /app -P 9090
152
+
153
+ # 自动打开 Web 页面
154
+ mock-service-cli -D ./dist --open
150
155
  ```
151
156
 
152
157
  ### HTTP 代理
@@ -322,6 +327,12 @@ socket.on('mock-dir-stat', data => {
322
327
 
323
328
  欢迎提交 Issue 和 Pull Request!
324
329
 
330
+ - **[CONTRIBUTING.md](CONTRIBUTING.md)** - 开发指南、代码规范、提交规范
331
+ - **[CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md)** - 社区行为准则
332
+ - **[SECURITY.md](SECURITY.md)** - 安全漏洞报告方式(请勿公开提交安全问题)
333
+ - **Issue 模板** - Bug 反馈 / 功能建议(新建 Issue 时自动弹出)
334
+ - **PR 模板** - 提交 Pull Request 时自动填充
335
+
325
336
  ## 📄 许可证
326
337
 
327
- MIT License - 详见 [LICENSE.md](LICENSE.md)
338
+ MIT License - 详见 [LICENSE](LICENSE)
package/dist/meta.json CHANGED
@@ -1041,7 +1041,7 @@
1041
1041
  "format": "cjs"
1042
1042
  },
1043
1043
  "src/lib/utils.js": {
1044
- "bytes": 12567,
1044
+ "bytes": 15764,
1045
1045
  "imports": [
1046
1046
  {
1047
1047
  "path": "fs",
@@ -1067,12 +1067,17 @@
1067
1067
  "path": "net",
1068
1068
  "kind": "require-call",
1069
1069
  "external": true
1070
+ },
1071
+ {
1072
+ "path": "child_process",
1073
+ "kind": "require-call",
1074
+ "external": true
1070
1075
  }
1071
1076
  ],
1072
1077
  "format": "cjs"
1073
1078
  },
1074
1079
  "src/lib/packageInfo.js": {
1075
- "bytes": 541,
1080
+ "bytes": 529,
1076
1081
  "imports": [
1077
1082
  {
1078
1083
  "path": "fs",
@@ -1088,7 +1093,7 @@
1088
1093
  "format": "cjs"
1089
1094
  },
1090
1095
  "src/bin/mock-service-cli": {
1091
- "bytes": 13903,
1096
+ "bytes": 14310,
1092
1097
  "imports": [
1093
1098
  {
1094
1099
  "path": "node_modules/colors/safe.js",
@@ -7344,7 +7349,7 @@
7344
7349
  "format": "cjs"
7345
7350
  },
7346
7351
  "src/lib/mockServer.js": {
7347
- "bytes": 17620,
7352
+ "bytes": 18262,
7348
7353
  "imports": [
7349
7354
  {
7350
7355
  "path": "node_modules/express/index.js",
@@ -7420,7 +7425,7 @@
7420
7425
  "format": "cjs"
7421
7426
  },
7422
7427
  "src/lib/staticServer.js": {
7423
- "bytes": 34916,
7428
+ "bytes": 35926,
7424
7429
  "imports": [
7425
7430
  {
7426
7431
  "path": "node_modules/express/index.js",
@@ -8174,7 +8179,7 @@
8174
8179
  "format": "cjs"
8175
8180
  },
8176
8181
  "src/lib/archiveService.js": {
8177
- "bytes": 9667,
8182
+ "bytes": 9713,
8178
8183
  "imports": [
8179
8184
  {
8180
8185
  "path": "fs",
@@ -8210,7 +8215,7 @@
8210
8215
  "format": "cjs"
8211
8216
  },
8212
8217
  "src/lib/fileExplorerServer.js": {
8213
- "bytes": 26109,
8218
+ "bytes": 25942,
8214
8219
  "imports": [
8215
8220
  {
8216
8221
  "path": "node_modules/express/index.js",
@@ -8499,6 +8504,11 @@
8499
8504
  "kind": "require-call",
8500
8505
  "external": true
8501
8506
  },
8507
+ {
8508
+ "path": "child_process",
8509
+ "kind": "require-call",
8510
+ "external": true
8511
+ },
8502
8512
  {
8503
8513
  "path": "fs",
8504
8514
  "kind": "require-call",
@@ -9727,13 +9737,13 @@
9727
9737
  "bytesInOutput": 4540
9728
9738
  },
9729
9739
  "src/lib/utils.js": {
9730
- "bytesInOutput": 7057
9740
+ "bytesInOutput": 8483
9731
9741
  },
9732
9742
  "src/lib/packageInfo.js": {
9733
9743
  "bytesInOutput": 429
9734
9744
  },
9735
9745
  "src/bin/mock-service-cli": {
9736
- "bytesInOutput": 10724
9746
+ "bytesInOutput": 11080
9737
9747
  },
9738
9748
  "node_modules/depd/index.js": {
9739
9749
  "bytesInOutput": 6779
@@ -10846,10 +10856,10 @@
10846
10856
  "bytesInOutput": 721
10847
10857
  },
10848
10858
  "src/lib/mockServer.js": {
10849
- "bytesInOutput": 11363
10859
+ "bytesInOutput": 11845
10850
10860
  },
10851
10861
  "src/lib/staticServer.js": {
10852
- "bytesInOutput": 27469
10862
+ "bytesInOutput": 28120
10853
10863
  },
10854
10864
  "node_modules/busboy/lib/utils.js": {
10855
10865
  "bytesInOutput": 8707
@@ -10972,13 +10982,13 @@
10972
10982
  "bytesInOutput": 7774
10973
10983
  },
10974
10984
  "src/lib/fileExplorerServer.js": {
10975
- "bytesInOutput": 19335
10985
+ "bytesInOutput": 19196
10976
10986
  },
10977
10987
  "src/runtime.js": {
10978
10988
  "bytesInOutput": 507
10979
10989
  }
10980
10990
  },
10981
- "bytes": 1737829
10991
+ "bytes": 1740605
10982
10992
  }
10983
10993
  }
10984
10994
  }
package/dist/runtime.js CHANGED
@@ -12,8 +12,8 @@ GFS4: `),console.error(m)});fs[gracefulQueue]||(queue=global[gracefulQueue]||[],
12
12
  see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0001");let{srcStat,destStat}=await stat.checkPaths(src,dest,"copy",opts);if(await stat.checkParentPaths(src,srcStat,dest,"copy"),!await runFilter(src,dest,opts))return;let destParent=path.dirname(dest);await pathExists(destParent)||await mkdirs(destParent),await getStatsAndPerformCopy(destStat,src,dest,opts)}async function runFilter(src,dest,opts){return opts.filter?opts.filter(src,dest):!0}async function getStatsAndPerformCopy(destStat,src,dest,opts){let srcStat=await(opts.dereference?fs.stat:fs.lstat)(src);if(srcStat.isDirectory())return onDir(srcStat,destStat,src,dest,opts);if(srcStat.isFile()||srcStat.isCharacterDevice()||srcStat.isBlockDevice())return onFile(srcStat,destStat,src,dest,opts);if(srcStat.isSymbolicLink())return onLink(destStat,src,dest,opts);throw srcStat.isSocket()?new Error(`Cannot copy a socket file: ${src}`):srcStat.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${src}`):new Error(`Unknown file: ${src}`)}async function onFile(srcStat,destStat,src,dest,opts){if(!destStat)return copyFile(srcStat,src,dest,opts);if(opts.overwrite)return await fs.unlink(dest),copyFile(srcStat,src,dest,opts);if(opts.errorOnExist)throw new Error(`'${dest}' already exists`)}async function copyFile(srcStat,src,dest,opts){if(await fs.copyFile(src,dest),opts.preserveTimestamps){fileIsNotWritable(srcStat.mode)&&await makeFileWritable(dest,srcStat.mode);let updatedSrcStat=await fs.stat(src);await utimesMillis(dest,updatedSrcStat.atime,updatedSrcStat.mtime)}return fs.chmod(dest,srcStat.mode)}function fileIsNotWritable(srcMode){return(srcMode&128)===0}function makeFileWritable(dest,srcMode){return fs.chmod(dest,srcMode|128)}async function onDir(srcStat,destStat,src,dest,opts){destStat||await fs.mkdir(dest),await asyncIteratorConcurrentProcess(await fs.opendir(src),async item=>{let srcItem=path.join(src,item.name),destItem=path.join(dest,item.name);if(await runFilter(srcItem,destItem,opts)){let{destStat:destStat2}=await stat.checkPaths(srcItem,destItem,"copy",opts);await getStatsAndPerformCopy(destStat2,srcItem,destItem,opts)}}),destStat||await fs.chmod(dest,srcStat.mode)}async function onLink(destStat,src,dest,opts){let resolvedSrc=await fs.readlink(src);if(opts.dereference&&(resolvedSrc=path.resolve(process.cwd(),resolvedSrc)),!destStat)return fs.symlink(resolvedSrc,dest);let resolvedDest=null;try{resolvedDest=await fs.readlink(dest)}catch(e){if(e.code==="EINVAL"||e.code==="UNKNOWN")return fs.symlink(resolvedSrc,dest);throw e}if(opts.dereference&&(resolvedDest=path.resolve(process.cwd(),resolvedDest)),resolvedSrc!==resolvedDest){if(stat.isSrcSubdir(resolvedSrc,resolvedDest))throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`);if(stat.isSrcSubdir(resolvedDest,resolvedSrc))throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)}return await fs.unlink(dest),fs.symlink(resolvedSrc,dest)}module2.exports=copy}});var require_copy_sync=__commonJS({"node_modules/fs-extra/lib/copy/copy-sync.js"(exports2,module2){"use strict";var fs=require_graceful_fs(),path=require("path"),mkdirsSync=require_mkdirs().mkdirsSync,utimesMillisSync=require_utimes().utimesMillisSync,stat=require_stat();function copySync(src,dest,opts){typeof opts=="function"&&(opts={filter:opts}),opts=opts||{},opts.clobber="clobber"in opts?!!opts.clobber:!0,opts.overwrite="overwrite"in opts?!!opts.overwrite:opts.clobber,opts.preserveTimestamps&&process.arch==="ia32"&&process.emitWarning(`Using the preserveTimestamps option in 32-bit node is not recommended;
13
13
 
14
14
  see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0002");let{srcStat,destStat}=stat.checkPathsSync(src,dest,"copy",opts);if(stat.checkParentPathsSync(src,srcStat,dest,"copy"),opts.filter&&!opts.filter(src,dest))return;let destParent=path.dirname(dest);return fs.existsSync(destParent)||mkdirsSync(destParent),getStats(destStat,src,dest,opts)}function getStats(destStat,src,dest,opts){let srcStat=(opts.dereference?fs.statSync:fs.lstatSync)(src);if(srcStat.isDirectory())return onDir(srcStat,destStat,src,dest,opts);if(srcStat.isFile()||srcStat.isCharacterDevice()||srcStat.isBlockDevice())return onFile(srcStat,destStat,src,dest,opts);if(srcStat.isSymbolicLink())return onLink(destStat,src,dest,opts);throw srcStat.isSocket()?new Error(`Cannot copy a socket file: ${src}`):srcStat.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${src}`):new Error(`Unknown file: ${src}`)}function onFile(srcStat,destStat,src,dest,opts){return destStat?mayCopyFile(srcStat,src,dest,opts):copyFile(srcStat,src,dest,opts)}function mayCopyFile(srcStat,src,dest,opts){if(opts.overwrite)return fs.unlinkSync(dest),copyFile(srcStat,src,dest,opts);if(opts.errorOnExist)throw new Error(`'${dest}' already exists`)}function copyFile(srcStat,src,dest,opts){return fs.copyFileSync(src,dest),opts.preserveTimestamps&&handleTimestamps(srcStat.mode,src,dest),setDestMode(dest,srcStat.mode)}function handleTimestamps(srcMode,src,dest){return fileIsNotWritable(srcMode)&&makeFileWritable(dest,srcMode),setDestTimestamps(src,dest)}function fileIsNotWritable(srcMode){return(srcMode&128)===0}function makeFileWritable(dest,srcMode){return setDestMode(dest,srcMode|128)}function setDestMode(dest,srcMode){return fs.chmodSync(dest,srcMode)}function setDestTimestamps(src,dest){let updatedSrcStat=fs.statSync(src);return utimesMillisSync(dest,updatedSrcStat.atime,updatedSrcStat.mtime)}function onDir(srcStat,destStat,src,dest,opts){return destStat?copyDir(src,dest,opts):mkDirAndCopy(srcStat.mode,src,dest,opts)}function mkDirAndCopy(srcMode,src,dest,opts){return fs.mkdirSync(dest),copyDir(src,dest,opts),setDestMode(dest,srcMode)}function copyDir(src,dest,opts){let dir=fs.opendirSync(src);try{let dirent;for(;(dirent=dir.readSync())!==null;)copyDirItem(dirent.name,src,dest,opts)}finally{dir.closeSync()}}function copyDirItem(item,src,dest,opts){let srcItem=path.join(src,item),destItem=path.join(dest,item);if(opts.filter&&!opts.filter(srcItem,destItem))return;let{destStat}=stat.checkPathsSync(srcItem,destItem,"copy",opts);return getStats(destStat,srcItem,destItem,opts)}function onLink(destStat,src,dest,opts){let resolvedSrc=fs.readlinkSync(src);if(opts.dereference&&(resolvedSrc=path.resolve(process.cwd(),resolvedSrc)),destStat){let resolvedDest;try{resolvedDest=fs.readlinkSync(dest)}catch(err){if(err.code==="EINVAL"||err.code==="UNKNOWN")return fs.symlinkSync(resolvedSrc,dest);throw err}if(opts.dereference&&(resolvedDest=path.resolve(process.cwd(),resolvedDest)),resolvedSrc!==resolvedDest){if(stat.isSrcSubdir(resolvedSrc,resolvedDest))throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`);if(stat.isSrcSubdir(resolvedDest,resolvedSrc))throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)}return copyLink(resolvedSrc,dest)}else return fs.symlinkSync(resolvedSrc,dest)}function copyLink(resolvedSrc,dest){return fs.unlinkSync(dest),fs.symlinkSync(resolvedSrc,dest)}module2.exports=copySync}});var require_copy2=__commonJS({"node_modules/fs-extra/lib/copy/index.js"(exports2,module2){"use strict";var u=require_universalify().fromPromise;module2.exports={copy:u(require_copy()),copySync:require_copy_sync()}}});var require_remove=__commonJS({"node_modules/fs-extra/lib/remove/index.js"(exports2,module2){"use strict";var fs=require_graceful_fs(),u=require_universalify().fromCallback;function remove(path,callback){fs.rm(path,{recursive:!0,force:!0},callback)}function removeSync(path){fs.rmSync(path,{recursive:!0,force:!0})}module2.exports={remove:u(remove),removeSync}}});var require_empty=__commonJS({"node_modules/fs-extra/lib/empty/index.js"(exports2,module2){"use strict";var u=require_universalify().fromPromise,fs=require_fs(),path=require("path"),mkdir=require_mkdirs(),remove=require_remove(),emptyDir=u(async function(dir){let items;try{items=await fs.readdir(dir)}catch{return mkdir.mkdirs(dir)}return Promise.all(items.map(item=>remove.remove(path.join(dir,item))))});function emptyDirSync(dir){let items;try{items=fs.readdirSync(dir)}catch{return mkdir.mkdirsSync(dir)}items.forEach(item=>{item=path.join(dir,item),remove.removeSync(item)})}module2.exports={emptyDirSync,emptydirSync:emptyDirSync,emptyDir,emptydir:emptyDir}}});var require_file=__commonJS({"node_modules/fs-extra/lib/ensure/file.js"(exports2,module2){"use strict";var u=require_universalify().fromPromise,path=require("path"),fs=require_fs(),mkdir=require_mkdirs();async function createFile(file){let stats;try{stats=await fs.stat(file)}catch{}if(stats&&stats.isFile())return;let dir=path.dirname(file),dirStats=null;try{dirStats=await fs.stat(dir)}catch(err){if(err.code==="ENOENT"){await mkdir.mkdirs(dir),await fs.writeFile(file,"");return}else throw err}dirStats.isDirectory()?await fs.writeFile(file,""):await fs.readdir(dir)}function createFileSync(file){let stats;try{stats=fs.statSync(file)}catch{}if(stats&&stats.isFile())return;let dir=path.dirname(file);try{fs.statSync(dir).isDirectory()||fs.readdirSync(dir)}catch(err){if(err&&err.code==="ENOENT")mkdir.mkdirsSync(dir);else throw err}fs.writeFileSync(file,"")}module2.exports={createFile:u(createFile),createFileSync}}});var require_link=__commonJS({"node_modules/fs-extra/lib/ensure/link.js"(exports2,module2){"use strict";var u=require_universalify().fromPromise,path=require("path"),fs=require_fs(),mkdir=require_mkdirs(),{pathExists}=require_path_exists(),{areIdentical}=require_stat();async function createLink(srcpath,dstpath){let dstStat;try{dstStat=await fs.lstat(dstpath,{bigint:!0})}catch{}let srcStat;try{srcStat=await fs.lstat(srcpath,{bigint:!0})}catch(err){throw err.message=err.message.replace("lstat","ensureLink"),err}if(dstStat&&areIdentical(srcStat,dstStat))return;let dir=path.dirname(dstpath);await pathExists(dir)||await mkdir.mkdirs(dir),await fs.link(srcpath,dstpath)}function createLinkSync(srcpath,dstpath){let dstStat;try{dstStat=fs.lstatSync(dstpath,{bigint:!0})}catch{}try{let srcStat=fs.lstatSync(srcpath,{bigint:!0});if(dstStat&&areIdentical(srcStat,dstStat))return}catch(err){throw err.message=err.message.replace("lstat","ensureLink"),err}let dir=path.dirname(dstpath);return fs.existsSync(dir)||mkdir.mkdirsSync(dir),fs.linkSync(srcpath,dstpath)}module2.exports={createLink:u(createLink),createLinkSync}}});var require_symlink_paths=__commonJS({"node_modules/fs-extra/lib/ensure/symlink-paths.js"(exports2,module2){"use strict";var path=require("path"),fs=require_fs(),{pathExists}=require_path_exists(),u=require_universalify().fromPromise;async function symlinkPaths(srcpath,dstpath){if(path.isAbsolute(srcpath)){try{await fs.lstat(srcpath)}catch(err){throw err.message=err.message.replace("lstat","ensureSymlink"),err}return{toCwd:srcpath,toDst:srcpath}}let dstdir=path.dirname(dstpath),relativeToDst=path.join(dstdir,srcpath);if(await pathExists(relativeToDst))return{toCwd:relativeToDst,toDst:srcpath};try{await fs.lstat(srcpath)}catch(err){throw err.message=err.message.replace("lstat","ensureSymlink"),err}return{toCwd:srcpath,toDst:path.relative(dstdir,srcpath)}}function symlinkPathsSync(srcpath,dstpath){if(path.isAbsolute(srcpath)){if(!fs.existsSync(srcpath))throw new Error("absolute srcpath does not exist");return{toCwd:srcpath,toDst:srcpath}}let dstdir=path.dirname(dstpath),relativeToDst=path.join(dstdir,srcpath);if(fs.existsSync(relativeToDst))return{toCwd:relativeToDst,toDst:srcpath};if(!fs.existsSync(srcpath))throw new Error("relative srcpath does not exist");return{toCwd:srcpath,toDst:path.relative(dstdir,srcpath)}}module2.exports={symlinkPaths:u(symlinkPaths),symlinkPathsSync}}});var require_symlink_type=__commonJS({"node_modules/fs-extra/lib/ensure/symlink-type.js"(exports2,module2){"use strict";var fs=require_fs(),u=require_universalify().fromPromise;async function symlinkType(srcpath,type){if(type)return type;let stats;try{stats=await fs.lstat(srcpath)}catch{return"file"}return stats&&stats.isDirectory()?"dir":"file"}function symlinkTypeSync(srcpath,type){if(type)return type;let stats;try{stats=fs.lstatSync(srcpath)}catch{return"file"}return stats&&stats.isDirectory()?"dir":"file"}module2.exports={symlinkType:u(symlinkType),symlinkTypeSync}}});var require_symlink=__commonJS({"node_modules/fs-extra/lib/ensure/symlink.js"(exports2,module2){"use strict";var u=require_universalify().fromPromise,path=require("path"),fs=require_fs(),{mkdirs,mkdirsSync}=require_mkdirs(),{symlinkPaths,symlinkPathsSync}=require_symlink_paths(),{symlinkType,symlinkTypeSync}=require_symlink_type(),{pathExists}=require_path_exists(),{areIdentical}=require_stat();async function createSymlink(srcpath,dstpath,type){let stats;try{stats=await fs.lstat(dstpath)}catch{}if(stats&&stats.isSymbolicLink()){let srcStat;if(path.isAbsolute(srcpath))srcStat=await fs.stat(srcpath,{bigint:!0});else{let dstdir=path.dirname(dstpath),relativeToDst=path.join(dstdir,srcpath);try{srcStat=await fs.stat(relativeToDst,{bigint:!0})}catch{srcStat=await fs.stat(srcpath,{bigint:!0})}}let dstStat=await fs.stat(dstpath,{bigint:!0});if(areIdentical(srcStat,dstStat))return}let relative=await symlinkPaths(srcpath,dstpath);srcpath=relative.toDst;let toType=await symlinkType(relative.toCwd,type),dir=path.dirname(dstpath);return await pathExists(dir)||await mkdirs(dir),fs.symlink(srcpath,dstpath,toType)}function createSymlinkSync(srcpath,dstpath,type){let stats;try{stats=fs.lstatSync(dstpath)}catch{}if(stats&&stats.isSymbolicLink()){let srcStat;if(path.isAbsolute(srcpath))srcStat=fs.statSync(srcpath,{bigint:!0});else{let dstdir=path.dirname(dstpath),relativeToDst=path.join(dstdir,srcpath);try{srcStat=fs.statSync(relativeToDst,{bigint:!0})}catch{srcStat=fs.statSync(srcpath,{bigint:!0})}}let dstStat=fs.statSync(dstpath,{bigint:!0});if(areIdentical(srcStat,dstStat))return}let relative=symlinkPathsSync(srcpath,dstpath);srcpath=relative.toDst,type=symlinkTypeSync(relative.toCwd,type);let dir=path.dirname(dstpath);return fs.existsSync(dir)||mkdirsSync(dir),fs.symlinkSync(srcpath,dstpath,type)}module2.exports={createSymlink:u(createSymlink),createSymlinkSync}}});var require_ensure=__commonJS({"node_modules/fs-extra/lib/ensure/index.js"(exports2,module2){"use strict";var{createFile,createFileSync}=require_file(),{createLink,createLinkSync}=require_link(),{createSymlink,createSymlinkSync}=require_symlink();module2.exports={createFile,createFileSync,ensureFile:createFile,ensureFileSync:createFileSync,createLink,createLinkSync,ensureLink:createLink,ensureLinkSync:createLinkSync,createSymlink,createSymlinkSync,ensureSymlink:createSymlink,ensureSymlinkSync:createSymlinkSync}}});var require_utils2=__commonJS({"node_modules/jsonfile/utils.js"(exports2,module2){function stringify(obj,{EOL=`
15
- `,finalEOL=!0,replacer=null,spaces}={}){let EOF=finalEOL?EOL:"";return JSON.stringify(obj,replacer,spaces).replace(/\n/g,EOL)+EOF}function stripBom(content){return Buffer.isBuffer(content)&&(content=content.toString("utf8")),content.replace(/^\uFEFF/,"")}module2.exports={stringify,stripBom}}});var require_jsonfile=__commonJS({"node_modules/jsonfile/index.js"(exports2,module2){var _fs;try{_fs=require_graceful_fs()}catch{_fs=require("fs")}var universalify=require_universalify(),{stringify,stripBom}=require_utils2();async function _readFile(file,options={}){typeof options=="string"&&(options={encoding:options});let fs=options.fs||_fs,shouldThrow="throws"in options?options.throws:!0,data=await universalify.fromCallback(fs.readFile)(file,options);data=stripBom(data);let obj;try{obj=JSON.parse(data,options?options.reviver:null)}catch(err){if(shouldThrow)throw err.message=`${file}: ${err.message}`,err;return null}return obj}var readFile=universalify.fromPromise(_readFile);function readFileSync(file,options={}){typeof options=="string"&&(options={encoding:options});let fs=options.fs||_fs,shouldThrow="throws"in options?options.throws:!0;try{let content=fs.readFileSync(file,options);return content=stripBom(content),JSON.parse(content,options.reviver)}catch(err){if(shouldThrow)throw err.message=`${file}: ${err.message}`,err;return null}}async function _writeFile(file,obj,options={}){let fs=options.fs||_fs,str=stringify(obj,options);await universalify.fromCallback(fs.writeFile)(file,str,options)}var writeFile=universalify.fromPromise(_writeFile);function writeFileSync(file,obj,options={}){let fs=options.fs||_fs,str=stringify(obj,options);return fs.writeFileSync(file,str,options)}var jsonfile={readFile,readFileSync,writeFile,writeFileSync};module2.exports=jsonfile}});var require_jsonfile2=__commonJS({"node_modules/fs-extra/lib/json/jsonfile.js"(exports2,module2){"use strict";var jsonFile=require_jsonfile();module2.exports={readJson:jsonFile.readFile,readJsonSync:jsonFile.readFileSync,writeJson:jsonFile.writeFile,writeJsonSync:jsonFile.writeFileSync}}});var require_output_file=__commonJS({"node_modules/fs-extra/lib/output-file/index.js"(exports2,module2){"use strict";var u=require_universalify().fromPromise,fs=require_fs(),path=require("path"),mkdir=require_mkdirs(),pathExists=require_path_exists().pathExists;async function outputFile(file,data,encoding="utf-8"){let dir=path.dirname(file);return await pathExists(dir)||await mkdir.mkdirs(dir),fs.writeFile(file,data,encoding)}function outputFileSync(file,...args){let dir=path.dirname(file);fs.existsSync(dir)||mkdir.mkdirsSync(dir),fs.writeFileSync(file,...args)}module2.exports={outputFile:u(outputFile),outputFileSync}}});var require_output_json=__commonJS({"node_modules/fs-extra/lib/json/output-json.js"(exports2,module2){"use strict";var{stringify}=require_utils2(),{outputFile}=require_output_file();async function outputJson(file,data,options={}){let str=stringify(data,options);await outputFile(file,str,options)}module2.exports=outputJson}});var require_output_json_sync=__commonJS({"node_modules/fs-extra/lib/json/output-json-sync.js"(exports2,module2){"use strict";var{stringify}=require_utils2(),{outputFileSync}=require_output_file();function outputJsonSync(file,data,options){let str=stringify(data,options);outputFileSync(file,str,options)}module2.exports=outputJsonSync}});var require_json=__commonJS({"node_modules/fs-extra/lib/json/index.js"(exports2,module2){"use strict";var u=require_universalify().fromPromise,jsonFile=require_jsonfile2();jsonFile.outputJson=u(require_output_json());jsonFile.outputJsonSync=require_output_json_sync();jsonFile.outputJSON=jsonFile.outputJson;jsonFile.outputJSONSync=jsonFile.outputJsonSync;jsonFile.writeJSON=jsonFile.writeJson;jsonFile.writeJSONSync=jsonFile.writeJsonSync;jsonFile.readJSON=jsonFile.readJson;jsonFile.readJSONSync=jsonFile.readJsonSync;module2.exports=jsonFile}});var require_move=__commonJS({"node_modules/fs-extra/lib/move/move.js"(exports2,module2){"use strict";var fs=require_fs(),path=require("path"),{copy}=require_copy2(),{remove}=require_remove(),{mkdirp}=require_mkdirs(),{pathExists}=require_path_exists(),stat=require_stat();async function move(src,dest,opts={}){let overwrite=opts.overwrite||opts.clobber||!1,{srcStat,isChangingCase=!1}=await stat.checkPaths(src,dest,"move",opts);await stat.checkParentPaths(src,srcStat,dest,"move");let destParent=path.dirname(dest);return path.parse(destParent).root!==destParent&&await mkdirp(destParent),doRename(src,dest,overwrite,isChangingCase)}async function doRename(src,dest,overwrite,isChangingCase){if(!isChangingCase){if(overwrite)await remove(dest);else if(await pathExists(dest))throw new Error("dest already exists.")}try{await fs.rename(src,dest)}catch(err){if(err.code!=="EXDEV")throw err;await moveAcrossDevice(src,dest,overwrite)}}async function moveAcrossDevice(src,dest,overwrite){return await copy(src,dest,{overwrite,errorOnExist:!0,preserveTimestamps:!0}),remove(src)}module2.exports=move}});var require_move_sync=__commonJS({"node_modules/fs-extra/lib/move/move-sync.js"(exports2,module2){"use strict";var fs=require_graceful_fs(),path=require("path"),copySync=require_copy2().copySync,removeSync=require_remove().removeSync,mkdirpSync=require_mkdirs().mkdirpSync,stat=require_stat();function moveSync(src,dest,opts){opts=opts||{};let overwrite=opts.overwrite||opts.clobber||!1,{srcStat,isChangingCase=!1}=stat.checkPathsSync(src,dest,"move",opts);return stat.checkParentPathsSync(src,srcStat,dest,"move"),isParentRoot(dest)||mkdirpSync(path.dirname(dest)),doRename(src,dest,overwrite,isChangingCase)}function isParentRoot(dest){let parent=path.dirname(dest);return path.parse(parent).root===parent}function doRename(src,dest,overwrite,isChangingCase){if(isChangingCase)return rename(src,dest,overwrite);if(overwrite)return removeSync(dest),rename(src,dest,overwrite);if(fs.existsSync(dest))throw new Error("dest already exists.");return rename(src,dest,overwrite)}function rename(src,dest,overwrite){try{fs.renameSync(src,dest)}catch(err){if(err.code!=="EXDEV")throw err;return moveAcrossDevice(src,dest,overwrite)}}function moveAcrossDevice(src,dest,overwrite){return copySync(src,dest,{overwrite,errorOnExist:!0,preserveTimestamps:!0}),removeSync(src)}module2.exports=moveSync}});var require_move2=__commonJS({"node_modules/fs-extra/lib/move/index.js"(exports2,module2){"use strict";var u=require_universalify().fromPromise;module2.exports={move:u(require_move()),moveSync:require_move_sync()}}});var require_lib=__commonJS({"node_modules/fs-extra/lib/index.js"(exports2,module2){"use strict";module2.exports={...require_fs(),...require_copy2(),...require_empty(),...require_ensure(),...require_json(),...require_mkdirs(),...require_move2(),...require_output_file(),...require_path_exists(),...require_remove()}}});var require_minimist=__commonJS({"node_modules/minimist/index.js"(exports2,module2){"use strict";function hasKey(obj,keys){var o=obj;keys.slice(0,-1).forEach(function(key2){o=o[key2]||{}});var key=keys[keys.length-1];return key in o}function isNumber(x){return typeof x=="number"||/^0x[0-9a-f]+$/i.test(x)?!0:/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x)}function isConstructorOrProto(obj,key){return key==="constructor"&&typeof obj[key]=="function"||key==="__proto__"}module2.exports=function(args,opts){opts||(opts={});var flags={bools:{},strings:{},unknownFn:null};typeof opts.unknown=="function"&&(flags.unknownFn=opts.unknown),typeof opts.boolean=="boolean"&&opts.boolean?flags.allBools=!0:[].concat(opts.boolean).filter(Boolean).forEach(function(key2){flags.bools[key2]=!0});var aliases={};function aliasIsBoolean(key2){return aliases[key2].some(function(x){return flags.bools[x]})}Object.keys(opts.alias||{}).forEach(function(key2){aliases[key2]=[].concat(opts.alias[key2]),aliases[key2].forEach(function(x){aliases[x]=[key2].concat(aliases[key2].filter(function(y){return x!==y}))})}),[].concat(opts.string).filter(Boolean).forEach(function(key2){flags.strings[key2]=!0,aliases[key2]&&[].concat(aliases[key2]).forEach(function(k){flags.strings[k]=!0})});var defaults=opts.default||{},argv={_:[]};function argDefined(key2,arg2){return flags.allBools&&/^--[^=]+$/.test(arg2)||flags.strings[key2]||flags.bools[key2]||aliases[key2]}function setKey(obj,keys,value2){for(var o=obj,i2=0;i2<keys.length-1;i2++){var key2=keys[i2];if(isConstructorOrProto(o,key2))return;o[key2]===void 0&&(o[key2]={}),(o[key2]===Object.prototype||o[key2]===Number.prototype||o[key2]===String.prototype)&&(o[key2]={}),o[key2]===Array.prototype&&(o[key2]=[]),o=o[key2]}var lastKey=keys[keys.length-1];isConstructorOrProto(o,lastKey)||((o===Object.prototype||o===Number.prototype||o===String.prototype)&&(o={}),o===Array.prototype&&(o=[]),o[lastKey]===void 0||flags.bools[lastKey]||typeof o[lastKey]=="boolean"?o[lastKey]=value2:Array.isArray(o[lastKey])?o[lastKey].push(value2):o[lastKey]=[o[lastKey],value2])}function setArg(key2,val,arg2){if(!(arg2&&flags.unknownFn&&!argDefined(key2,arg2)&&flags.unknownFn(arg2)===!1)){var value2=!flags.strings[key2]&&isNumber(val)?Number(val):val;setKey(argv,key2.split("."),value2),(aliases[key2]||[]).forEach(function(x){setKey(argv,x.split("."),value2)})}}Object.keys(flags.bools).forEach(function(key2){setArg(key2,defaults[key2]===void 0?!1:defaults[key2])});var notFlags=[];args.indexOf("--")!==-1&&(notFlags=args.slice(args.indexOf("--")+1),args=args.slice(0,args.indexOf("--")));for(var i=0;i<args.length;i++){var arg=args[i],key,next;if(/^--.+=/.test(arg)){var m=arg.match(/^--([^=]+)=([\s\S]*)$/);key=m[1];var value=m[2];flags.bools[key]&&(value=value!=="false"),setArg(key,value,arg)}else if(/^--no-.+/.test(arg))key=arg.match(/^--no-(.+)/)[1],setArg(key,!1,arg);else if(/^--.+/.test(arg))key=arg.match(/^--(.+)/)[1],next=args[i+1],next!==void 0&&!/^(-|--)[^-]/.test(next)&&!flags.bools[key]&&!flags.allBools&&(!aliases[key]||!aliasIsBoolean(key))?(setArg(key,next,arg),i+=1):/^(true|false)$/.test(next)?(setArg(key,next==="true",arg),i+=1):setArg(key,flags.strings[key]?"":!0,arg);else if(/^-[^-]+/.test(arg)){for(var letters=arg.slice(1,-1).split(""),broken=!1,j=0;j<letters.length;j++){if(next=arg.slice(j+2),next==="-"){setArg(letters[j],next,arg);continue}if(/[A-Za-z]/.test(letters[j])&&next[0]==="="){setArg(letters[j],next.slice(1),arg),broken=!0;break}if(/[A-Za-z]/.test(letters[j])&&/-?\d+(\.\d*)?(e-?\d+)?$/.test(next)){setArg(letters[j],next,arg),broken=!0;break}if(letters[j+1]&&letters[j+1].match(/\W/)){setArg(letters[j],arg.slice(j+2),arg),broken=!0;break}else setArg(letters[j],flags.strings[letters[j]]?"":!0,arg)}key=arg.slice(-1)[0],!broken&&key!=="-"&&(args[i+1]&&!/^(-|--)[^-]/.test(args[i+1])&&!flags.bools[key]&&(!aliases[key]||!aliasIsBoolean(key))?(setArg(key,args[i+1],arg),i+=1):args[i+1]&&/^(true|false)$/.test(args[i+1])?(setArg(key,args[i+1]==="true",arg),i+=1):setArg(key,flags.strings[key]?"":!0,arg))}else if((!flags.unknownFn||flags.unknownFn(arg)!==!1)&&argv._.push(flags.strings._||!isNumber(arg)?arg:Number(arg)),opts.stopEarly){argv._.push.apply(argv._,args.slice(i+1));break}}return Object.keys(defaults).forEach(function(k){hasKey(argv,k.split("."))||(setKey(argv,k.split("."),defaults[k]),(aliases[k]||[]).forEach(function(x){setKey(argv,x.split("."),defaults[k])}))}),opts["--"]?argv["--"]=notFlags.slice():notFlags.forEach(function(k){argv._.push(k)}),argv}}});var require_utils3=__commonJS({"src/lib/utils.js"(exports2,module2){var fs=require("fs"),colors=require_safe(),path=require("path"),os=require("os"),net=require("net"),getLogger=function(logFileDirPath){let options={flags:"a",encoding:"utf8"},output=fs.createWriteStream(path.resolve(logFileDirPath||path.resolve(process.cwd()),"./stdout.log"),options),errorOutput=fs.createWriteStream(path.resolve(logFileDirPath||path.resolve(process.cwd()),"./stderr.log"),options),logger2=new console.Console(output,errorOutput);return{log:(...args)=>logger2.log.call(null,`[${dateFormat("YYYY-mm-dd HH:MM:SS:fff")}] - `,...args),error:(...args)=>logger2.error.call(null,`[${dateFormat("YYYY-mm-dd HH:MM:SS:fff")}] - `,...args)}};function dateFormat(fmt,date=new Date){let ret,opt={"Y+":date.getFullYear().toString(),"m+":(date.getMonth()+1).toString(),"d+":date.getDate().toString(),"H+":date.getHours().toString(),"M+":date.getMinutes().toString(),"S+":date.getSeconds().toString(),"f+":date.getMilliseconds().toString()};for(let k in opt)ret=new RegExp("("+k+")").exec(fmt),ret&&(fmt=fmt.replace(ret[1],ret[1].length===1?opt[k]:opt[k].padStart(ret[1].length,"0")));return fmt}function logger(isSilent=!1){let logObj=null;return isSilent?logObj={info:function(){},assert:function(){}}:logObj={info:console.log,assert:console.assert},logObj}var SupportMethods=["GET","POST","PUT","DELETE","HEAD","PATCH","OPTIONS","COPY","LINK","UNLINK","PURGE"],DefaultHeaders="Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Data-Type,X-Requested-With,X-Data-Type,X-Auth-Token,Token",isValidMethod=function(m){return SupportMethods.includes(String(m).toLocaleUpperCase())},getFileLatestContent=function(filePath){try{return delete require.cache[require.resolve(filePath)],require(path.resolve(process.cwd(),filePath))}catch(error){return console.error(colors.red("[error]:"),error),"getFileLatestContent_ERROR"}},filePath2ApiUrl=function(filePath){return filePath.split(path.sep).join("/")},getDataType=function(data){return Object.prototype.toString.call(data).slice(8,-1).toLowerCase()},isEmptyObj=function(obj){return getDataType(obj)==="object"&&Object.keys(obj).length===0},writeStream=function(filePath,data){return new Promise((resolve,reject)=>{let writerStream=fs.createWriteStream(filePath);writerStream.write(data,"utf-8"),writerStream.end(),writerStream.on("finish",()=>{}),writerStream.on("close",()=>{setTimeout(()=>{resolve(data)})}),writerStream.on("error",err=>{getLogger(path.resolve(process.cwd())).error(filePath,require.cache[require.resolve(filePath)],err),reject(err)})})},readStream=function(filePath){let data="";return new Promise((resovle,reject)=>{let readerStream=fs.createReadStream(filePath);readerStream.setEncoding("UTF8"),readerStream.on("data",function(chunk){data+=chunk}),readerStream.on("end",function(){resovle(data)}),readerStream.on("error",function(err){reject(err),console.log(err.stack)})})},debounce=(func,wait)=>{let timeout,canceled=!1,f=function(...args){canceled||(clearTimeout(timeout),timeout=setTimeout(()=>{func.call(this,...args)},wait))};return f.cancel=()=>{clearTimeout(timeout),canceled=!0},f},throttle=(func,wait,immediate)=>{let timeout,canceled=!1,lastCalledTime=0,f=function(...args){if(canceled)return;let now=Date.now(),call=()=>{lastCalledTime=now,func.call(this,...args)};if(lastCalledTime===0){if(immediate)return call();lastCalledTime=now;return}lastCalledTime+wait-now>0?(clearTimeout(timeout),timeout=setTimeout(()=>call(),wait)):call()};return f.cancel=()=>{clearTimeout(timeout),canceled=!0},f};function getServerHost(){return process.env.SERVER_HOST==="0.0.0.0"?"0.0.0.0":"127.0.0.1"}function normalizeRemoteAddress(address){let value=String(address||"").trim().replace(/^\[|\]$/g,"");return value.toLowerCase().startsWith("::ffff:")?value.slice(7):value}function ipToBigInt(address){let version=net.isIP(address);if(version===4)return address.split(".").reduce((value,part)=>(value<<8n)+BigInt(Number(part)),0n);if(version!==6)return null;let[head="",tail=""]=address.toLowerCase().split("::"),headParts=head?head.split(":"):[],tailParts=tail?tail.split(":"):[];return[...headParts,...Array(Math.max(0,8-headParts.length-tailParts.length)).fill("0"),...tailParts].reduce((value,part)=>(value<<16n)+BigInt(parseInt(part||"0",16)),0n)}function parseAllowlistRule(value){let[address,prefixValue]=value.split("/"),normalizedAddress=normalizeRemoteAddress(address),version=net.isIP(normalizedAddress),maxPrefix=version===4?32:128,prefix=prefixValue===void 0?maxPrefix:Number(prefixValue);return!version||!Number.isInteger(prefix)||prefix<0||prefix>maxPrefix?null:{address:normalizedAddress,version,prefix,value:ipToBigInt(normalizedAddress)}}function parseHostAllowlist(filePath){let content=fs.readFileSync(filePath,"utf8"),rules=[];if(content.split(/\r?\n/).forEach((rawLine,index)=>{let line=rawLine.trim();if(!line||line.startsWith("#"))return;let rule=parseAllowlistRule(line);if(!rule)throw new Error(`Invalid IP allowlist rule at line ${index+1}: ${rawLine}`);rules.push(rule)}),rules.length===0)throw new Error("IP allowlist must contain at least one valid IP or CIDR rule");return rules}function isLoopbackAddress(address){let normalized=normalizeRemoteAddress(address);return normalized==="127.0.0.1"||normalized==="::1"}function isAddressAllowed(address,rules=[]){let normalized=normalizeRemoteAddress(address);if(isLoopbackAddress(normalized))return!0;let version=net.isIP(normalized),value=ipToBigInt(normalized);return!version||value===null?!1:rules.some(rule=>{if(rule.version!==version)return!1;let remainingBits=BigInt((rule.version===4?32:128)-rule.prefix);return value>>remainingBits===rule.value>>remainingBits})}function getHostAllowlist(){if(!process.env.HOST_ALLOWLIST)return[];try{return JSON.parse(process.env.HOST_ALLOWLIST).map(rule=>typeof rule=="string"?parseAllowlistRule(rule):rule).filter(Boolean)}catch{return[]}}function hostAllowlistMiddleware(){let rules=getHostAllowlist();return rules.length===0?(req,res,next)=>next():(req,res,next)=>{if(!isAddressAllowed(req.socket&&req.socket.remoteAddress,rules))return res.status(403).send("Access denied by host allowlist");next()}}function getServerUrls(port,pathname=""){let normalizedPath=pathname&&pathname!=="/"?pathname:"",urls=[`http://localhost:${port}${normalizedPath}`,`http://127.0.0.1:${port}${normalizedPath}`];if(getServerHost()!=="0.0.0.0"||getHostAllowlist().length>0)return urls;let addresses=new Set(urls);return Object.values(os.networkInterfaces()).forEach(networkInterface=>{(networkInterface||[]).forEach(details=>{details.family==="IPv4"&&!details.internal&&addresses.add(`http://${details.address}:${port}${normalizedPath}`)})}),Array.from(addresses)}module2.exports={getLogger,dateFormat,logger,SupportMethods,DefaultHeaders,isValidMethod,getFileLatestContent,filePath2ApiUrl,getDataType,isEmptyObj,writeStream,readStream,debounce,throttle,getServerHost,getServerUrls,normalizeRemoteAddress,parseHostAllowlist,isAddressAllowed,getHostAllowlist,hostAllowlistMiddleware}}});var require_packageInfo=__commonJS({"src/lib/packageInfo.js"(exports2,module2){var{readFileSync}=require("fs"),path=require("path");function getPackageVersion(){let packagePaths=[path.resolve(__dirname,"../package.json"),path.resolve(__dirname,"../../package.json")];for(let packagePath of packagePaths)try{return JSON.parse(readFileSync(packagePath,"utf8")).version}catch{}return"unknown"}module2.exports={getPackageVersion}}});var require_mock_service_cli=__commonJS({"src/bin/mock-service-cli"(exports2){var colors=require_safe(),portfinder=require_portfinder(),{resolve}=require("path"),{existsSync}=require_lib(),argv=require_minimist()(process.argv.slice(2)),{logger,parseHostAllowlist}=require_utils3(),{getPackageVersion}=require_packageInfo(),spawn=require("child_process").spawn,node=process.execPath;process.title="mock-service-cli";(argv.h||argv.help)&&(console.log(["usage: mock-service-cli [options]","","PS: Mock File\u4EC5\u652F\u6301commonjs\u89C4\u8303\u7684js\u3001cjs\u6587\u4EF6\uFF0C\u4E0D\u652F\u6301ES Module","options:"," -p --port Mock server port to use. If 0, look for open port. [8090]"," -d Specify mock directory, default [./mock] directory,"," Also watch js files changes and support hot reload"," -f --file Specify the input data source, support javascript "," The priority is over the directory watches"," -s --silent Suppress log messages from output"," -S --socket-server Whether start socket server or not, default false."," -a --api-stat Whether print api url and file path or not, default false."," -t --track Whether record operation info by write file, default false."," -o --cors-origin Allow origin by cors, list separated by commas, must not be * when withCredential is true",' .If specified, cors-headers will be "Authorization,Content-Type,Accept,Origin,User-Agent,DNT',' ,Cache-Control,X-Mx-ReqToken,X-Data-Type,X-Requested-With,X-Data-Type,X-Auth-Token,Token", default *.'," -H --cors-headers When start Mock Server, optionally provide CORS headers list separated by commas. default *"," -A --append-headers When start Mock/Web/Static Server, optionally add response headers list separated by commas."," For example: X-Frame-options=DENY,content-security-policy=frame-ancestors",""," -O --proxy-options Optionally provide proxy options list separated by commas."," -r --rewrite rewrite http or https request url prefix of proxy, default false.",""," -D --web-dir Enable web server, specify web directory, default [./dist] directory"," -P --web-port Web server port to use. If 0, look for open port. [9090]"," -b --web-baseurl Specify website public path when enabled web server.",""," -R --static-server Specify static resource file directory when enabled static server."," --spa-fallback <path> Enable SPA fallback for -R mode using a root-relative HTML path."," --static-config <file> Self-contained static server configuration for root apps, mounts, proxy and fallback."," --host [file] Bind all web services to all IPv4 interfaces, or restrict them with an IP allowlist file."," --edit Enable file create, rename, and delete operations in file explorer."," --auth <password> Require a password for file explorer access.",""," -h --help Print this list and exit."," -v --version Print the version and exit."," -w --open Open API overview page automatically, default false."," -e --explorer Enable file explorer server, specify directory to browse, default [./]."].join(`
16
- `)),process.exit());argv.host!==void 0&&typeof argv.host!="boolean"&&typeof argv.host!="string"&&(console.error("--host must be a boolean flag or an IP allowlist file path"),process.exit(1));argv.edit!==void 0&&typeof argv.edit!="boolean"&&(console.error("--edit is a boolean flag"),process.exit(1));argv.auth!==void 0&&(typeof argv.auth!="string"||!argv.auth)&&(console.error("--auth requires a non-empty password string"),process.exit(1));argv.auth&&!(argv.e||argv.explorer)&&(console.error("--auth can only be used with --explorer"),process.exit(1));argv["static-config"]!==void 0&&(typeof argv["static-config"]!="string"||!argv["static-config"])&&(console.error("--static-config requires a JSON file path"),process.exit(1));var staticDirectoryArg=argv.R!==void 0?argv.R:argv["static-server"];staticDirectoryArg!==void 0&&staticDirectoryArg!==!0&&typeof staticDirectoryArg!="string"&&(console.error("-R/--static-server requires a directory path"),process.exit(1));argv["spa-fallback"]!==void 0&&(typeof argv["spa-fallback"]!="string"||!argv["spa-fallback"])&&(console.error("--spa-fallback requires a root-relative HTML path"),process.exit(1));argv["static-config"]&&typeof staticDirectoryArg=="string"&&(console.error("--static-config cannot be combined with -R <directory>"),process.exit(1));!argv["static-config"]&&staticDirectoryArg===!0&&(console.error("-R requires a directory path unless --static-config is provided"),process.exit(1));argv["static-config"]&&(argv.O||argv["proxy-options"]||argv.r||argv.rewrite)&&(console.error("--proxy-options/--rewrite cannot be used with --static-config"),process.exit(1));var hostAllowlist=[];if(typeof argv.host=="string"){let allowlistPath=resolve(process.cwd(),argv.host);existsSync(allowlistPath)||(console.error(`host allowlist file does not exist: ${allowlistPath}`),process.exit(1));try{hostAllowlist=parseHostAllowlist(allowlistPath).map(rule=>`${rule.address}/${rule.prefix}`)}catch(error){console.error(`Invalid host allowlist file: ${error.message}`),process.exit(1)}}var explorerAuthPassword=argv.auth;delete argv.auth;process.env.ARGV=JSON.stringify(argv);var port=argv.p||argv.port,watchDir=argv.d,specifiedFile=argv.f||argv.file,version=argv.v||argv.version,isStartSocketServer=argv.S||!1,rewrite=argv.r||argv.rewrite||!1,isOpenApiOverview=argv.w||argv.open||!1,explorerDir=argv.e||argv.explorer,log=null,managedServerProcess=null,managedServerShutdown=!1;!argv.s&&!argv.silent?log=logger(!1):colors&&(process.env.SILENT=!0,log=logger(!0));var injectEnvVariable=(envName,envArgs)=>{envArgs&&(process.env[envName]=envArgs)};function resolveServerEntry(fileName){let builtEntry=resolve(__dirname,`./${fileName}.js`);if(existsSync(builtEntry))return builtEntry;let sourceEntry=resolve(__dirname,`../lib/${fileName}.js`);return existsSync(sourceEntry)?sourceEntry:builtEntry}isStartSocketServer&&(process.env.SOCKET_SERVER=!0);isOpenApiOverview&&(process.env.OPEN_API_OVERVIEW=!0);version&&(log.info("v"+getPackageVersion()),process.exit());injectEnvVariable("PREFIX_REWRITE",rewrite);injectEnvVariable("CORS_ORIGIN",argv.o||argv["cors-origin"]);injectEnvVariable("CORS_HEADERS",argv.H||argv["cors-headers"]);injectEnvVariable("WEB_PUBLIC_PATH",argv.b||argv["web-baseurl"]);typeof staticDirectoryArg=="string"&&injectEnvVariable("STATIC_DIRECTORY",staticDirectoryArg);if(argv["static-config"]){let staticConfigPath=resolve(process.cwd(),argv["static-config"]);existsSync(staticConfigPath)||(console.error(`static-config: \u6587\u4EF6 ${staticConfigPath} \u4E0D\u5B58\u5728`),process.exit(1)),process.env.STATIC_CONFIG=staticConfigPath}injectEnvVariable("EXPLORER_DIRECTORY",explorerDir);process.env.SERVER_HOST=argv.host===!0||hostAllowlist.length>0?"0.0.0.0":"127.0.0.1";hostAllowlist.length>0&&(process.env.HOST_ALLOWLIST=JSON.stringify(hostAllowlist));process.env.EXPLORER_EDIT=argv.edit===!0?"true":"false";explorerAuthPassword&&(process.env.EXPLORER_AUTH=explorerAuthPassword);var proxyArg=argv.O||argv["proxy-options"];if(proxyArg){let proxyTable={};if(proxyArg.endsWith(".js")||proxyArg.endsWith(".json")){let proxyOptFile=resolve(process.cwd(),proxyArg);existsSync(proxyOptFile)||(console.error(`proxy-options: \u6587\u4EF6 ${proxyOptFile} \u4E0D\u5B58\u5728`),process.exit());let proxyObj=require(proxyOptFile);Object.keys(proxyObj).forEach(function(h){proxyTable[h]=proxyObj[h]},exports2)}else try{proxyArg.split(/\s*,\s*/).forEach(function(h){let[origin,target]=h.split("|");proxyTable[origin]=target},exports2)}catch(error){throw console.warn(colors.yellow(`
15
+ `,finalEOL=!0,replacer=null,spaces}={}){let EOF=finalEOL?EOL:"";return JSON.stringify(obj,replacer,spaces).replace(/\n/g,EOL)+EOF}function stripBom(content){return Buffer.isBuffer(content)&&(content=content.toString("utf8")),content.replace(/^\uFEFF/,"")}module2.exports={stringify,stripBom}}});var require_jsonfile=__commonJS({"node_modules/jsonfile/index.js"(exports2,module2){var _fs;try{_fs=require_graceful_fs()}catch{_fs=require("fs")}var universalify=require_universalify(),{stringify,stripBom}=require_utils2();async function _readFile(file,options={}){typeof options=="string"&&(options={encoding:options});let fs=options.fs||_fs,shouldThrow="throws"in options?options.throws:!0,data=await universalify.fromCallback(fs.readFile)(file,options);data=stripBom(data);let obj;try{obj=JSON.parse(data,options?options.reviver:null)}catch(err){if(shouldThrow)throw err.message=`${file}: ${err.message}`,err;return null}return obj}var readFile=universalify.fromPromise(_readFile);function readFileSync(file,options={}){typeof options=="string"&&(options={encoding:options});let fs=options.fs||_fs,shouldThrow="throws"in options?options.throws:!0;try{let content=fs.readFileSync(file,options);return content=stripBom(content),JSON.parse(content,options.reviver)}catch(err){if(shouldThrow)throw err.message=`${file}: ${err.message}`,err;return null}}async function _writeFile(file,obj,options={}){let fs=options.fs||_fs,str=stringify(obj,options);await universalify.fromCallback(fs.writeFile)(file,str,options)}var writeFile=universalify.fromPromise(_writeFile);function writeFileSync(file,obj,options={}){let fs=options.fs||_fs,str=stringify(obj,options);return fs.writeFileSync(file,str,options)}var jsonfile={readFile,readFileSync,writeFile,writeFileSync};module2.exports=jsonfile}});var require_jsonfile2=__commonJS({"node_modules/fs-extra/lib/json/jsonfile.js"(exports2,module2){"use strict";var jsonFile=require_jsonfile();module2.exports={readJson:jsonFile.readFile,readJsonSync:jsonFile.readFileSync,writeJson:jsonFile.writeFile,writeJsonSync:jsonFile.writeFileSync}}});var require_output_file=__commonJS({"node_modules/fs-extra/lib/output-file/index.js"(exports2,module2){"use strict";var u=require_universalify().fromPromise,fs=require_fs(),path=require("path"),mkdir=require_mkdirs(),pathExists=require_path_exists().pathExists;async function outputFile(file,data,encoding="utf-8"){let dir=path.dirname(file);return await pathExists(dir)||await mkdir.mkdirs(dir),fs.writeFile(file,data,encoding)}function outputFileSync(file,...args){let dir=path.dirname(file);fs.existsSync(dir)||mkdir.mkdirsSync(dir),fs.writeFileSync(file,...args)}module2.exports={outputFile:u(outputFile),outputFileSync}}});var require_output_json=__commonJS({"node_modules/fs-extra/lib/json/output-json.js"(exports2,module2){"use strict";var{stringify}=require_utils2(),{outputFile}=require_output_file();async function outputJson(file,data,options={}){let str=stringify(data,options);await outputFile(file,str,options)}module2.exports=outputJson}});var require_output_json_sync=__commonJS({"node_modules/fs-extra/lib/json/output-json-sync.js"(exports2,module2){"use strict";var{stringify}=require_utils2(),{outputFileSync}=require_output_file();function outputJsonSync(file,data,options){let str=stringify(data,options);outputFileSync(file,str,options)}module2.exports=outputJsonSync}});var require_json=__commonJS({"node_modules/fs-extra/lib/json/index.js"(exports2,module2){"use strict";var u=require_universalify().fromPromise,jsonFile=require_jsonfile2();jsonFile.outputJson=u(require_output_json());jsonFile.outputJsonSync=require_output_json_sync();jsonFile.outputJSON=jsonFile.outputJson;jsonFile.outputJSONSync=jsonFile.outputJsonSync;jsonFile.writeJSON=jsonFile.writeJson;jsonFile.writeJSONSync=jsonFile.writeJsonSync;jsonFile.readJSON=jsonFile.readJson;jsonFile.readJSONSync=jsonFile.readJsonSync;module2.exports=jsonFile}});var require_move=__commonJS({"node_modules/fs-extra/lib/move/move.js"(exports2,module2){"use strict";var fs=require_fs(),path=require("path"),{copy}=require_copy2(),{remove}=require_remove(),{mkdirp}=require_mkdirs(),{pathExists}=require_path_exists(),stat=require_stat();async function move(src,dest,opts={}){let overwrite=opts.overwrite||opts.clobber||!1,{srcStat,isChangingCase=!1}=await stat.checkPaths(src,dest,"move",opts);await stat.checkParentPaths(src,srcStat,dest,"move");let destParent=path.dirname(dest);return path.parse(destParent).root!==destParent&&await mkdirp(destParent),doRename(src,dest,overwrite,isChangingCase)}async function doRename(src,dest,overwrite,isChangingCase){if(!isChangingCase){if(overwrite)await remove(dest);else if(await pathExists(dest))throw new Error("dest already exists.")}try{await fs.rename(src,dest)}catch(err){if(err.code!=="EXDEV")throw err;await moveAcrossDevice(src,dest,overwrite)}}async function moveAcrossDevice(src,dest,overwrite){return await copy(src,dest,{overwrite,errorOnExist:!0,preserveTimestamps:!0}),remove(src)}module2.exports=move}});var require_move_sync=__commonJS({"node_modules/fs-extra/lib/move/move-sync.js"(exports2,module2){"use strict";var fs=require_graceful_fs(),path=require("path"),copySync=require_copy2().copySync,removeSync=require_remove().removeSync,mkdirpSync=require_mkdirs().mkdirpSync,stat=require_stat();function moveSync(src,dest,opts){opts=opts||{};let overwrite=opts.overwrite||opts.clobber||!1,{srcStat,isChangingCase=!1}=stat.checkPathsSync(src,dest,"move",opts);return stat.checkParentPathsSync(src,srcStat,dest,"move"),isParentRoot(dest)||mkdirpSync(path.dirname(dest)),doRename(src,dest,overwrite,isChangingCase)}function isParentRoot(dest){let parent=path.dirname(dest);return path.parse(parent).root===parent}function doRename(src,dest,overwrite,isChangingCase){if(isChangingCase)return rename(src,dest,overwrite);if(overwrite)return removeSync(dest),rename(src,dest,overwrite);if(fs.existsSync(dest))throw new Error("dest already exists.");return rename(src,dest,overwrite)}function rename(src,dest,overwrite){try{fs.renameSync(src,dest)}catch(err){if(err.code!=="EXDEV")throw err;return moveAcrossDevice(src,dest,overwrite)}}function moveAcrossDevice(src,dest,overwrite){return copySync(src,dest,{overwrite,errorOnExist:!0,preserveTimestamps:!0}),removeSync(src)}module2.exports=moveSync}});var require_move2=__commonJS({"node_modules/fs-extra/lib/move/index.js"(exports2,module2){"use strict";var u=require_universalify().fromPromise;module2.exports={move:u(require_move()),moveSync:require_move_sync()}}});var require_lib=__commonJS({"node_modules/fs-extra/lib/index.js"(exports2,module2){"use strict";module2.exports={...require_fs(),...require_copy2(),...require_empty(),...require_ensure(),...require_json(),...require_mkdirs(),...require_move2(),...require_output_file(),...require_path_exists(),...require_remove()}}});var require_minimist=__commonJS({"node_modules/minimist/index.js"(exports2,module2){"use strict";function hasKey(obj,keys){var o=obj;keys.slice(0,-1).forEach(function(key2){o=o[key2]||{}});var key=keys[keys.length-1];return key in o}function isNumber(x){return typeof x=="number"||/^0x[0-9a-f]+$/i.test(x)?!0:/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x)}function isConstructorOrProto(obj,key){return key==="constructor"&&typeof obj[key]=="function"||key==="__proto__"}module2.exports=function(args,opts){opts||(opts={});var flags={bools:{},strings:{},unknownFn:null};typeof opts.unknown=="function"&&(flags.unknownFn=opts.unknown),typeof opts.boolean=="boolean"&&opts.boolean?flags.allBools=!0:[].concat(opts.boolean).filter(Boolean).forEach(function(key2){flags.bools[key2]=!0});var aliases={};function aliasIsBoolean(key2){return aliases[key2].some(function(x){return flags.bools[x]})}Object.keys(opts.alias||{}).forEach(function(key2){aliases[key2]=[].concat(opts.alias[key2]),aliases[key2].forEach(function(x){aliases[x]=[key2].concat(aliases[key2].filter(function(y){return x!==y}))})}),[].concat(opts.string).filter(Boolean).forEach(function(key2){flags.strings[key2]=!0,aliases[key2]&&[].concat(aliases[key2]).forEach(function(k){flags.strings[k]=!0})});var defaults=opts.default||{},argv={_:[]};function argDefined(key2,arg2){return flags.allBools&&/^--[^=]+$/.test(arg2)||flags.strings[key2]||flags.bools[key2]||aliases[key2]}function setKey(obj,keys,value2){for(var o=obj,i2=0;i2<keys.length-1;i2++){var key2=keys[i2];if(isConstructorOrProto(o,key2))return;o[key2]===void 0&&(o[key2]={}),(o[key2]===Object.prototype||o[key2]===Number.prototype||o[key2]===String.prototype)&&(o[key2]={}),o[key2]===Array.prototype&&(o[key2]=[]),o=o[key2]}var lastKey=keys[keys.length-1];isConstructorOrProto(o,lastKey)||((o===Object.prototype||o===Number.prototype||o===String.prototype)&&(o={}),o===Array.prototype&&(o=[]),o[lastKey]===void 0||flags.bools[lastKey]||typeof o[lastKey]=="boolean"?o[lastKey]=value2:Array.isArray(o[lastKey])?o[lastKey].push(value2):o[lastKey]=[o[lastKey],value2])}function setArg(key2,val,arg2){if(!(arg2&&flags.unknownFn&&!argDefined(key2,arg2)&&flags.unknownFn(arg2)===!1)){var value2=!flags.strings[key2]&&isNumber(val)?Number(val):val;setKey(argv,key2.split("."),value2),(aliases[key2]||[]).forEach(function(x){setKey(argv,x.split("."),value2)})}}Object.keys(flags.bools).forEach(function(key2){setArg(key2,defaults[key2]===void 0?!1:defaults[key2])});var notFlags=[];args.indexOf("--")!==-1&&(notFlags=args.slice(args.indexOf("--")+1),args=args.slice(0,args.indexOf("--")));for(var i=0;i<args.length;i++){var arg=args[i],key,next;if(/^--.+=/.test(arg)){var m=arg.match(/^--([^=]+)=([\s\S]*)$/);key=m[1];var value=m[2];flags.bools[key]&&(value=value!=="false"),setArg(key,value,arg)}else if(/^--no-.+/.test(arg))key=arg.match(/^--no-(.+)/)[1],setArg(key,!1,arg);else if(/^--.+/.test(arg))key=arg.match(/^--(.+)/)[1],next=args[i+1],next!==void 0&&!/^(-|--)[^-]/.test(next)&&!flags.bools[key]&&!flags.allBools&&(!aliases[key]||!aliasIsBoolean(key))?(setArg(key,next,arg),i+=1):/^(true|false)$/.test(next)?(setArg(key,next==="true",arg),i+=1):setArg(key,flags.strings[key]?"":!0,arg);else if(/^-[^-]+/.test(arg)){for(var letters=arg.slice(1,-1).split(""),broken=!1,j=0;j<letters.length;j++){if(next=arg.slice(j+2),next==="-"){setArg(letters[j],next,arg);continue}if(/[A-Za-z]/.test(letters[j])&&next[0]==="="){setArg(letters[j],next.slice(1),arg),broken=!0;break}if(/[A-Za-z]/.test(letters[j])&&/-?\d+(\.\d*)?(e-?\d+)?$/.test(next)){setArg(letters[j],next,arg),broken=!0;break}if(letters[j+1]&&letters[j+1].match(/\W/)){setArg(letters[j],arg.slice(j+2),arg),broken=!0;break}else setArg(letters[j],flags.strings[letters[j]]?"":!0,arg)}key=arg.slice(-1)[0],!broken&&key!=="-"&&(args[i+1]&&!/^(-|--)[^-]/.test(args[i+1])&&!flags.bools[key]&&(!aliases[key]||!aliasIsBoolean(key))?(setArg(key,args[i+1],arg),i+=1):args[i+1]&&/^(true|false)$/.test(args[i+1])?(setArg(key,args[i+1]==="true",arg),i+=1):setArg(key,flags.strings[key]?"":!0,arg))}else if((!flags.unknownFn||flags.unknownFn(arg)!==!1)&&argv._.push(flags.strings._||!isNumber(arg)?arg:Number(arg)),opts.stopEarly){argv._.push.apply(argv._,args.slice(i+1));break}}return Object.keys(defaults).forEach(function(k){hasKey(argv,k.split("."))||(setKey(argv,k.split("."),defaults[k]),(aliases[k]||[]).forEach(function(x){setKey(argv,x.split("."),defaults[k])}))}),opts["--"]?argv["--"]=notFlags.slice():notFlags.forEach(function(k){argv._.push(k)}),argv}}});var require_utils3=__commonJS({"src/lib/utils.js"(exports2,module2){var fs=require("fs"),colors=require_safe(),path=require("path"),os=require("os"),net=require("net"),{spawnSync,spawn}=require("child_process"),getLogger=function(logFileDirPath){let options={flags:"a",encoding:"utf8"},output=fs.createWriteStream(path.resolve(logFileDirPath||path.resolve(process.cwd()),"./stdout.log"),options),errorOutput=fs.createWriteStream(path.resolve(logFileDirPath||path.resolve(process.cwd()),"./stderr.log"),options),logger2=new console.Console(output,errorOutput);return{log:(...args)=>logger2.log.call(null,`[${dateFormat("YYYY-mm-dd HH:MM:SS:fff")}] - `,...args),error:(...args)=>logger2.error.call(null,`[${dateFormat("YYYY-mm-dd HH:MM:SS:fff")}] - `,...args)}};function dateFormat(fmt,date=new Date){let ret,opt={"Y+":date.getFullYear().toString(),"m+":(date.getMonth()+1).toString(),"d+":date.getDate().toString(),"H+":date.getHours().toString(),"M+":date.getMinutes().toString(),"S+":date.getSeconds().toString(),"f+":date.getMilliseconds().toString()};for(let k in opt)ret=new RegExp("("+k+")").exec(fmt),ret&&(fmt=fmt.replace(ret[1],ret[1].length===1?opt[k]:opt[k].padStart(ret[1].length,"0")));return fmt}function logger(isSilent=!1){let logObj=null;return isSilent?logObj={info:function(){},assert:function(){}}:logObj={info:console.log,assert:console.assert},logObj}function isWindowsHiddenByAttrib(filePath){let result;try{result=spawnSync("attrib",[filePath],{encoding:"utf8",windowsHide:!0,timeout:5e3})}catch{return!1}if(result.error||result.status!==0)return!1;let line=String(result.stdout||"").split(/\r?\n/)[0]||"",pathStart=line.search(/[A-Za-z]:[\\/]|\\\\/);return(pathStart===-1?line:line.slice(0,pathStart)).toUpperCase().includes("H")}function isHiddenPath(filePath){if(typeof filePath!="string"||!filePath)return!1;let name=path.basename(filePath);return name.startsWith(".")&&name!=="."&&name!==".."?!0:process.platform==="win32"?isWindowsHiddenByAttrib(filePath):/(^|[\\/])\.[^\\/.]/.test(filePath)}function openPathInFileManager(fullPath,options={}){let platform=options.platform||process.platform,spawnFn=options.spawn||spawn,command,args;switch(platform){case"darwin":command="open",args=[fullPath];break;case"win32":command="explorer.exe",args=[fullPath];break;case"linux":command="xdg-open",args=[fullPath];break;default:return Promise.resolve({ok:!1,unsupported:!0,error:new Error("Unsupported platform")})}return new Promise(resolve=>{let child=spawnFn(command,args,{detached:!0,stdio:"ignore"}),settled=!1,done=result=>{settled||(settled=!0,resolve(result))};child.once("error",error=>done({ok:!1,unsupported:!1,error})),child.once("spawn",()=>{child.unref(),done({ok:!0,command,args})})})}var SupportMethods=["GET","POST","PUT","DELETE","HEAD","PATCH","OPTIONS","COPY","LINK","UNLINK","PURGE"],DefaultHeaders="Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Data-Type,X-Requested-With,X-Data-Type,X-Auth-Token,Token",isValidMethod=function(m){return SupportMethods.includes(String(m).toLocaleUpperCase())},getFileLatestContent=function(filePath){try{return delete require.cache[require.resolve(filePath)],require(path.resolve(process.cwd(),filePath))}catch(error){return console.error(colors.red("[error]:"),error),"getFileLatestContent_ERROR"}},filePath2ApiUrl=function(filePath){return filePath.split(path.sep).join("/")},getDataType=function(data){return Object.prototype.toString.call(data).slice(8,-1).toLowerCase()},isEmptyObj=function(obj){return getDataType(obj)==="object"&&Object.keys(obj).length===0},writeStream=function(filePath,data){return new Promise((resolve,reject)=>{let writerStream=fs.createWriteStream(filePath);writerStream.write(data,"utf-8"),writerStream.end(),writerStream.on("finish",()=>{}),writerStream.on("close",()=>{setTimeout(()=>{resolve(data)})}),writerStream.on("error",err=>{getLogger(path.resolve(process.cwd())).error(filePath,require.cache[require.resolve(filePath)],err),reject(err)})})},readStream=function(filePath){let data="";return new Promise((resovle,reject)=>{let readerStream=fs.createReadStream(filePath);readerStream.setEncoding("UTF8"),readerStream.on("data",function(chunk){data+=chunk}),readerStream.on("end",function(){resovle(data)}),readerStream.on("error",function(err){reject(err),console.log(err.stack)})})},debounce=(func,wait)=>{let timeout,canceled=!1,f=function(...args){canceled||(clearTimeout(timeout),timeout=setTimeout(()=>{func.call(this,...args)},wait))};return f.cancel=()=>{clearTimeout(timeout),canceled=!0},f},throttle=(func,wait,immediate)=>{let timeout,canceled=!1,lastCalledTime=0,f=function(...args){if(canceled)return;let now=Date.now(),call=()=>{lastCalledTime=now,func.call(this,...args)};if(lastCalledTime===0){if(immediate)return call();lastCalledTime=now;return}lastCalledTime+wait-now>0?(clearTimeout(timeout),timeout=setTimeout(()=>call(),wait)):call()};return f.cancel=()=>{clearTimeout(timeout),canceled=!0},f};function getServerHost(){return process.env.SERVER_HOST==="0.0.0.0"?"0.0.0.0":"127.0.0.1"}function normalizeRemoteAddress(address){let value=String(address||"").trim().replace(/^\[|\]$/g,"");return value.toLowerCase().startsWith("::ffff:")?value.slice(7):value}function ipToBigInt(address){let version=net.isIP(address);if(version===4)return address.split(".").reduce((value,part)=>(value<<8n)+BigInt(Number(part)),0n);if(version!==6)return null;let[head="",tail=""]=address.toLowerCase().split("::"),headParts=head?head.split(":"):[],tailParts=tail?tail.split(":"):[];return[...headParts,...Array(Math.max(0,8-headParts.length-tailParts.length)).fill("0"),...tailParts].reduce((value,part)=>(value<<16n)+BigInt(parseInt(part||"0",16)),0n)}function parseAllowlistRule(value){let[address,prefixValue]=value.split("/"),normalizedAddress=normalizeRemoteAddress(address),version=net.isIP(normalizedAddress),maxPrefix=version===4?32:128,prefix=prefixValue===void 0?maxPrefix:Number(prefixValue);return!version||!Number.isInteger(prefix)||prefix<0||prefix>maxPrefix?null:{address:normalizedAddress,version,prefix,value:ipToBigInt(normalizedAddress)}}function parseHostAllowlist(filePath){let content=fs.readFileSync(filePath,"utf8"),rules=[];if(content.split(/\r?\n/).forEach((rawLine,index)=>{let line=rawLine.trim();if(!line||line.startsWith("#"))return;let rule=parseAllowlistRule(line);if(!rule)throw new Error(`Invalid IP allowlist rule at line ${index+1}: ${rawLine}`);rules.push(rule)}),rules.length===0)throw new Error("IP allowlist must contain at least one valid IP or CIDR rule");return rules}function isLoopbackAddress(address){let normalized=normalizeRemoteAddress(address);return normalized==="127.0.0.1"||normalized==="::1"}function isAddressAllowed(address,rules=[]){let normalized=normalizeRemoteAddress(address);if(isLoopbackAddress(normalized))return!0;let version=net.isIP(normalized),value=ipToBigInt(normalized);return!version||value===null?!1:rules.some(rule=>{if(rule.version!==version)return!1;let remainingBits=BigInt((rule.version===4?32:128)-rule.prefix);return value>>remainingBits===rule.value>>remainingBits})}function getHostAllowlist(){if(!process.env.HOST_ALLOWLIST)return[];try{return JSON.parse(process.env.HOST_ALLOWLIST).map(rule=>typeof rule=="string"?parseAllowlistRule(rule):rule).filter(Boolean)}catch{return[]}}function hostAllowlistMiddleware(){let rules=getHostAllowlist();return rules.length===0?(req,res,next)=>next():(req,res,next)=>{if(!isAddressAllowed(req.socket&&req.socket.remoteAddress,rules))return res.status(403).send("Access denied by host allowlist");next()}}function getServerUrls(port,pathname=""){let normalizedPath=pathname&&pathname!=="/"?pathname:"",urls=[`http://localhost:${port}${normalizedPath}`,`http://127.0.0.1:${port}${normalizedPath}`];if(getServerHost()!=="0.0.0.0"||getHostAllowlist().length>0)return urls;let addresses=new Set(urls);return Object.values(os.networkInterfaces()).forEach(networkInterface=>{(networkInterface||[]).forEach(details=>{details.family==="IPv4"&&!details.internal&&addresses.add(`http://${details.address}:${port}${normalizedPath}`)})}),Array.from(addresses)}module2.exports={getLogger,dateFormat,logger,SupportMethods,DefaultHeaders,isValidMethod,getFileLatestContent,filePath2ApiUrl,getDataType,isEmptyObj,writeStream,readStream,debounce,throttle,getServerHost,getServerUrls,normalizeRemoteAddress,parseHostAllowlist,isAddressAllowed,getHostAllowlist,hostAllowlistMiddleware,isHiddenPath,openPathInFileManager}}});var require_packageInfo=__commonJS({"src/lib/packageInfo.js"(exports2,module2){var{readFileSync}=require("fs"),path=require("path");function getPackageVersion(){let packagePaths=[path.resolve(__dirname,"../package.json"),path.resolve(__dirname,"../../package.json")];for(let packagePath of packagePaths)try{return JSON.parse(readFileSync(packagePath,"utf8")).version}catch{}return"unknown"}module2.exports={getPackageVersion}}});var require_mock_service_cli=__commonJS({"src/bin/mock-service-cli"(exports2){var colors=require_safe(),portfinder=require_portfinder(),{resolve}=require("path"),{existsSync}=require_lib(),argv=require_minimist()(process.argv.slice(2)),{logger,parseHostAllowlist}=require_utils3(),{getPackageVersion}=require_packageInfo(),spawn=require("child_process").spawn,node=process.execPath;process.title="mock-service-cli";(argv.h||argv.help)&&(console.log(["usage: mock-service-cli [options]","","PS: Mock File\u4EC5\u652F\u6301commonjs\u89C4\u8303\u7684js\u3001cjs\u6587\u4EF6\uFF0C\u4E0D\u652F\u6301ES Module","options:"," -p --port Mock server port to use. If 0, look for open port. [8090]"," -d Specify mock directory, default [./mock] directory,"," Also watch js files changes and support hot reload"," -f --file Specify the input data source, support javascript "," The priority is over the directory watches"," -s --silent Suppress log messages from output"," -S --socket-server Whether start socket server or not, default false."," -a --api-stat Whether print api url and file path or not, default false."," -t --track Whether record operation info by write file, default false."," -o --cors-origin Allow origin by cors, list separated by commas, must not be * when withCredential is true",' .If specified, cors-headers will be "Authorization,Content-Type,Accept,Origin,User-Agent,DNT',' ,Cache-Control,X-Mx-ReqToken,X-Data-Type,X-Requested-With,X-Data-Type,X-Auth-Token,Token", default *.'," -H --cors-headers When start Mock Server, optionally provide CORS headers list separated by commas. default *"," -A --append-headers When start Mock/Web/Static Server, optionally add response headers list separated by commas."," For example: X-Frame-options=DENY,content-security-policy=frame-ancestors",""," -O --proxy-options Optionally provide proxy options list separated by commas."," -r --rewrite rewrite http or https request url prefix of proxy, default false.",""," -D --web-dir Enable web server, specify web directory, default [./dist] directory"," -P --web-port Web server port to use. If 0, look for open port. [9090]"," -b --web-baseurl Specify website public path when enabled web server.",""," -R --static-server Specify static resource file directory when enabled static server."," --watch-depth <n> Limit static server watch recursion depth (non-negative integer)."," --spa-fallback <path> Enable SPA fallback for -R mode using a root-relative HTML path."," --static-config <file> Self-contained static server configuration for root apps, mounts, proxy and fallback."," --host [file] Bind all web services to all IPv4 interfaces, or restrict them with an IP allowlist file."," --edit Enable file create, rename, and delete operations in file explorer."," --auth <password> Require a password for file explorer access.",""," -h --help Print this list and exit."," -v --version Print the version and exit."," -w --open Open the available web page/API overview automatically, default false."," -e --explorer Enable file explorer server, specify directory to browse, default [./]."].join(`
16
+ `)),process.exit());argv.host!==void 0&&typeof argv.host!="boolean"&&typeof argv.host!="string"&&(console.error("--host must be a boolean flag or an IP allowlist file path"),process.exit(1));argv.edit!==void 0&&typeof argv.edit!="boolean"&&(console.error("--edit is a boolean flag"),process.exit(1));argv.auth!==void 0&&(typeof argv.auth!="string"||!argv.auth)&&(console.error("--auth requires a non-empty password string"),process.exit(1));argv.auth&&!(argv.e||argv.explorer)&&(console.error("--auth can only be used with --explorer"),process.exit(1));argv["static-config"]!==void 0&&(typeof argv["static-config"]!="string"||!argv["static-config"])&&(console.error("--static-config requires a JSON file path"),process.exit(1));var staticDirectoryArg=argv.R!==void 0?argv.R:argv["static-server"];staticDirectoryArg!==void 0&&staticDirectoryArg!==!0&&typeof staticDirectoryArg!="string"&&(console.error("-R/--static-server requires a directory path"),process.exit(1));argv["spa-fallback"]!==void 0&&(typeof argv["spa-fallback"]!="string"||!argv["spa-fallback"])&&(console.error("--spa-fallback requires a root-relative HTML path"),process.exit(1));if(argv["watch-depth"]!==void 0){let watchDepth=Number(argv["watch-depth"]);(!Number.isInteger(watchDepth)||watchDepth<0)&&(console.error("--watch-depth requires a non-negative integer"),process.exit(1)),process.env.WATCH_DEPTH=String(watchDepth)}argv["static-config"]&&typeof staticDirectoryArg=="string"&&(console.error("--static-config cannot be combined with -R <directory>"),process.exit(1));!argv["static-config"]&&staticDirectoryArg===!0&&(console.error("-R requires a directory path unless --static-config is provided"),process.exit(1));argv["static-config"]&&(argv.O||argv["proxy-options"]||argv.r||argv.rewrite)&&(console.error("--proxy-options/--rewrite cannot be used with --static-config"),process.exit(1));var hostAllowlist=[];if(typeof argv.host=="string"){let allowlistPath=resolve(process.cwd(),argv.host);existsSync(allowlistPath)||(console.error(`host allowlist file does not exist: ${allowlistPath}`),process.exit(1));try{hostAllowlist=parseHostAllowlist(allowlistPath).map(rule=>`${rule.address}/${rule.prefix}`)}catch(error){console.error(`Invalid host allowlist file: ${error.message}`),process.exit(1)}}var explorerAuthPassword=argv.auth;delete argv.auth;process.env.ARGV=JSON.stringify(argv);var port=argv.p||argv.port,watchDir=argv.d,specifiedFile=argv.f||argv.file,version=argv.v||argv.version,isStartSocketServer=argv.S||!1,rewrite=argv.r||argv.rewrite||!1,isOpenApiOverview=argv.w||argv.open||!1,explorerDir=argv.e||argv.explorer,log=null,managedServerProcess=null,managedServerShutdown=!1;!argv.s&&!argv.silent?log=logger(!1):colors&&(process.env.SILENT=!0,log=logger(!0));var injectEnvVariable=(envName,envArgs)=>{envArgs&&(process.env[envName]=envArgs)};function resolveServerEntry(fileName){let builtEntry=resolve(__dirname,`./${fileName}.js`);if(existsSync(builtEntry))return builtEntry;let sourceEntry=resolve(__dirname,`../lib/${fileName}.js`);return existsSync(sourceEntry)?sourceEntry:builtEntry}isStartSocketServer&&(process.env.SOCKET_SERVER=!0);isOpenApiOverview&&(process.env.OPEN_API_OVERVIEW=!0);version&&(log.info("v"+getPackageVersion()),process.exit());injectEnvVariable("PREFIX_REWRITE",rewrite);injectEnvVariable("CORS_ORIGIN",argv.o||argv["cors-origin"]);injectEnvVariable("CORS_HEADERS",argv.H||argv["cors-headers"]);injectEnvVariable("WEB_PUBLIC_PATH",argv.b||argv["web-baseurl"]);typeof staticDirectoryArg=="string"&&injectEnvVariable("STATIC_DIRECTORY",staticDirectoryArg);if(argv["static-config"]){let staticConfigPath=resolve(process.cwd(),argv["static-config"]);existsSync(staticConfigPath)||(console.error(`static-config: \u6587\u4EF6 ${staticConfigPath} \u4E0D\u5B58\u5728`),process.exit(1)),process.env.STATIC_CONFIG=staticConfigPath}injectEnvVariable("EXPLORER_DIRECTORY",explorerDir);process.env.SERVER_HOST=argv.host===!0||hostAllowlist.length>0?"0.0.0.0":"127.0.0.1";hostAllowlist.length>0&&(process.env.HOST_ALLOWLIST=JSON.stringify(hostAllowlist));process.env.EXPLORER_EDIT=argv.edit===!0?"true":"false";explorerAuthPassword&&(process.env.EXPLORER_AUTH=explorerAuthPassword);var proxyArg=argv.O||argv["proxy-options"];if(proxyArg){let proxyTable={};if(proxyArg.endsWith(".js")||proxyArg.endsWith(".json")){let proxyOptFile=resolve(process.cwd(),proxyArg);existsSync(proxyOptFile)||(console.error(`proxy-options: \u6587\u4EF6 ${proxyOptFile} \u4E0D\u5B58\u5728`),process.exit());let proxyObj=require(proxyOptFile);Object.keys(proxyObj).forEach(function(h){proxyTable[h]=proxyObj[h]},exports2)}else try{proxyArg.split(/\s*,\s*/).forEach(function(h){let[origin,target]=h.split("|");proxyTable[origin]=target},exports2)}catch(error){throw console.warn(colors.yellow(`
17
17
  Parse web proxy options Failed:`,error)),error}process.env.PROXY_OPTIONS=JSON.stringify(proxyTable)}argv.D||argv["web-dir"]?(process.env.WEB_ROOT=resolve(process.cwd(),argv.D||argv["web-dir"]),existsSync(process.env.WEB_ROOT)||(console.error(`web-dir: \u76EE\u5F55 ${process.env.WEB_ROOT} \u4E0D\u5B58\u5728`),process.exit()),portfinder.basePort=argv.P||argv["web-port"]||9090,portfinder.getPort(function(err,webPort){if(err)throw err;process.env.WEB_PORT=webPort,portfinder.basePort=port||8090,portfinder.getPort(function(err2,port2){if(err2)throw err2;process.env.PORT=port2,initServe()})})):(portfinder.basePort=port||8090,portfinder.getPort(function(err,port2){if(err)throw err;process.env.PORT=port2,initServe()}));function watchMockFiles(watchDir2){let nodemon=require("nodemon");nodemon({script:resolveServerEntry("mockServer"),watch:[watchDir2],ext:"cjs,js,json"}),nodemon.on("start",function(){}).on("quit",function(){process.exit()}).on("restart",function(files){process.env.RESTARTED=!0,log.info([colors.green(`
18
18
  nodemon: mockServer restarted due to: `),files,colors.green(" have changed"),`
19
19
  `].join(""))})}function startManagedServer(fileName){managedServerProcess=spawn(node,[resolveServerEntry(fileName)],{stdio:"inherit"});let shutdown=signal=>{managedServerShutdown||(managedServerShutdown=!0,managedServerProcess.kill(signal))};process.once("SIGINT",()=>shutdown("SIGINT")),process.once("SIGTERM",()=>shutdown("SIGTERM")),managedServerProcess.once("exit",(code,signal)=>{managedServerShutdown&&process.exit(signal?1:code||0)}),managedServerProcess.once("error",error=>{console.error(colors.red(`Unable to start ${fileName}: ${error.message}`)),process.exit(1)})}function startMockServer(){startManagedServer("mockServer")}function startStaticServer(){startManagedServer("staticServer")}function startFileExplorerServer(){startManagedServer("fileExplorerServer")}function initServe(){explorerDir?(process.env.EXPLORER_DIRECTORY=resolve(process.cwd(),explorerDir),existsSync(process.env.EXPLORER_DIRECTORY)||(console.error(`explorer: \u76EE\u5F55 ${process.env.EXPLORER_DIRECTORY} \u4E0D\u5B58\u5728`),process.exit()),startFileExplorerServer()):specifiedFile?(process.env.SPECIFIED_FILE=resolve(process.cwd(),specifiedFile),isStartSocketServer?startMockServer():watchMockFiles(process.env.SPECIFIED_FILE)):watchDir?(process.env.SPECIFIED_DIR=resolve(process.cwd(),watchDir),isStartSocketServer?startMockServer():watchMockFiles(process.env.SPECIFIED_DIR)):process.env.STATIC_DIRECTORY||process.env.STATIC_CONFIG?(process.env.STATIC_DIRECTORY&&(process.env.STATIC_DIRECTORY=resolve(process.cwd(),process.env.STATIC_DIRECTORY)),startStaticServer()):(watchDir=process.env.SPECIFIED_DIR=resolve(process.cwd(),"./mock"),isStartSocketServer||(process.env.STATIC_DIRECTORY||process.env.WEB_ROOT)&&!existsSync(resolve(process.cwd(),watchDir))?startMockServer():watchMockFiles(watchDir))}}});var require_depd=__commonJS({"node_modules/depd/index.js"(exports2,module2){var relative=require("path").relative;module2.exports=depd;var basePath=process.cwd();function containsNamespace(str,namespace){for(var vals=str.split(/[ ,]+/),ns=String(namespace).toLowerCase(),i=0;i<vals.length;i++){var val=vals[i];if(val&&(val==="*"||val.toLowerCase()===ns))return!0}return!1}function convertDataDescriptorToAccessor(obj,prop,message){var descriptor=Object.getOwnPropertyDescriptor(obj,prop),value=descriptor.value;return descriptor.get=function(){return value},descriptor.writable&&(descriptor.set=function(val){return value=val}),delete descriptor.value,delete descriptor.writable,Object.defineProperty(obj,prop,descriptor),descriptor}function createArgumentsString(arity){for(var str="",i=0;i<arity;i++)str+=", arg"+i;return str.substr(2)}function createStackString(stack){var str=this.name+": "+this.namespace;this.message&&(str+=" deprecated "+this.message);for(var i=0;i<stack.length;i++)str+=`
@@ -112,7 +112,7 @@ Content-Length: `+length+`\r
112
112
  `+Object.keys(headers).map(h=>`${h}: ${headers[h]}`).join(`\r
113
113
  `)+`\r
114
114
  \r
115
- `+message)}function abortHandshakeOrEmitwsClientError(server,req,socket,code,message){if(server.listenerCount("wsClientError")){let err=new Error(message);Error.captureStackTrace(err,abortHandshakeOrEmitwsClientError),server.emit("wsClientError",err,socket,req)}else abortHandshake(socket,code,message)}}});var require_ws2=__commonJS({"node_modules/socket.io-adapter/node_modules/ws/index.js"(exports2,module2){"use strict";var WebSocket=require_websocket4();WebSocket.createWebSocketStream=require_stream2();WebSocket.Server=require_websocket_server2();WebSocket.Receiver=require_receiver2();WebSocket.Sender=require_sender2();WebSocket.WebSocket=WebSocket;WebSocket.WebSocketServer=WebSocket.Server;module2.exports=WebSocket}});var require_dist2=__commonJS({"node_modules/socket.io-adapter/dist/index.js"(exports2){"use strict";var _a;Object.defineProperty(exports2,"__esModule",{value:!0});exports2.SessionAwareAdapter=exports2.Adapter=void 0;var events_1=require("events"),yeast_1=require_yeast(),WebSocket=require_ws2(),canPreComputeFrame=typeof((_a=WebSocket?.Sender)===null||_a===void 0?void 0:_a.frame)=="function",Adapter=class extends events_1.EventEmitter{constructor(nsp){super(),this.nsp=nsp,this.rooms=new Map,this.sids=new Map,this.encoder=nsp.server.encoder}init(){}close(){}serverCount(){return Promise.resolve(1)}addAll(id,rooms){this.sids.has(id)||this.sids.set(id,new Set);for(let room of rooms)this.sids.get(id).add(room),this.rooms.has(room)||(this.rooms.set(room,new Set),this.emit("create-room",room)),this.rooms.get(room).has(id)||(this.rooms.get(room).add(id),this.emit("join-room",room,id))}del(id,room){this.sids.has(id)&&this.sids.get(id).delete(room),this._del(room,id)}_del(room,id){let _room=this.rooms.get(room);_room!=null&&(_room.delete(id)&&this.emit("leave-room",room,id),_room.size===0&&this.rooms.delete(room)&&this.emit("delete-room",room))}delAll(id){if(this.sids.has(id)){for(let room of this.sids.get(id))this._del(room,id);this.sids.delete(id)}}broadcast(packet,opts){let flags=opts.flags||{},packetOpts={preEncoded:!0,volatile:flags.volatile,compress:flags.compress};packet.nsp=this.nsp.name;let encodedPackets=this._encode(packet,packetOpts);this.apply(opts,socket=>{typeof socket.notifyOutgoingListeners=="function"&&socket.notifyOutgoingListeners(packet),socket.client.writeToEngine(encodedPackets,packetOpts)})}broadcastWithAck(packet,opts,clientCountCallback,ack){let flags=opts.flags||{},packetOpts={preEncoded:!0,volatile:flags.volatile,compress:flags.compress};packet.nsp=this.nsp.name,packet.id=this.nsp._ids++;let encodedPackets=this._encode(packet,packetOpts),clientCount=0;this.apply(opts,socket=>{clientCount++,socket.acks.set(packet.id,ack),typeof socket.notifyOutgoingListeners=="function"&&socket.notifyOutgoingListeners(packet),socket.client.writeToEngine(encodedPackets,packetOpts)}),clientCountCallback(clientCount)}_encode(packet,packetOpts){let encodedPackets=this.encoder.encode(packet);if(canPreComputeFrame&&encodedPackets.length===1&&typeof encodedPackets[0]=="string"){let data=Buffer.from("4"+encodedPackets[0]);packetOpts.wsPreEncodedFrame=WebSocket.Sender.frame(data,{readOnly:!1,mask:!1,rsv1:!1,opcode:1,fin:!0})}return encodedPackets}sockets(rooms){let sids=new Set;return this.apply({rooms},socket=>{sids.add(socket.id)}),Promise.resolve(sids)}socketRooms(id){return this.sids.get(id)}fetchSockets(opts){let sockets=[];return this.apply(opts,socket=>{sockets.push(socket)}),Promise.resolve(sockets)}addSockets(opts,rooms){this.apply(opts,socket=>{socket.join(rooms)})}delSockets(opts,rooms){this.apply(opts,socket=>{rooms.forEach(room=>socket.leave(room))})}disconnectSockets(opts,close){this.apply(opts,socket=>{socket.disconnect(close)})}apply(opts,callback){let rooms=opts.rooms,except=this.computeExceptSids(opts.except);if(rooms.size){let ids=new Set;for(let room of rooms)if(this.rooms.has(room))for(let id of this.rooms.get(room)){if(ids.has(id)||except.has(id))continue;let socket=this.nsp.sockets.get(id);socket&&(callback(socket),ids.add(id))}}else for(let[id]of this.sids){if(except.has(id))continue;let socket=this.nsp.sockets.get(id);socket&&callback(socket)}}computeExceptSids(exceptRooms){let exceptSids=new Set;if(exceptRooms&&exceptRooms.size>0)for(let room of exceptRooms)this.rooms.has(room)&&this.rooms.get(room).forEach(sid=>exceptSids.add(sid));return exceptSids}serverSideEmit(packet){console.warn("this adapter does not support the serverSideEmit() functionality")}persistSession(session){}restoreSession(pid,offset){return null}};exports2.Adapter=Adapter;var SessionAwareAdapter=class extends Adapter{constructor(nsp){super(nsp),this.nsp=nsp,this.sessions=new Map,this.packets=[],this.maxDisconnectionDuration=nsp.server.opts.connectionStateRecovery.maxDisconnectionDuration,setInterval(()=>{let threshold=Date.now()-this.maxDisconnectionDuration;this.sessions.forEach((session,sessionId)=>{session.disconnectedAt<threshold&&this.sessions.delete(sessionId)});for(let i=this.packets.length-1;i>=0;i--)if(this.packets[i].emittedAt<threshold){this.packets.splice(0,i+1);break}},60*1e3).unref()}persistSession(session){session.disconnectedAt=Date.now(),this.sessions.set(session.pid,session)}restoreSession(pid,offset){let session=this.sessions.get(pid);if(!session)return null;if(session.disconnectedAt+this.maxDisconnectionDuration<Date.now())return this.sessions.delete(pid),null;let index=this.packets.findIndex(packet=>packet.id===offset);if(index===-1)return null;let missedPackets=[];for(let i=index+1;i<this.packets.length;i++){let packet=this.packets[i];shouldIncludePacket(session.rooms,packet.opts)&&missedPackets.push(packet.data)}return Promise.resolve(Object.assign(Object.assign({},session),{missedPackets}))}broadcast(packet,opts){var _a2;let isEventPacket=packet.type===2,withoutAcknowledgement=packet.id===void 0,notVolatile=((_a2=opts.flags)===null||_a2===void 0?void 0:_a2.volatile)===void 0;if(isEventPacket&&withoutAcknowledgement&&notVolatile){let id=(0,yeast_1.yeast)();packet.data.push(id),this.packets.push({id,opts,data:packet.data,emittedAt:Date.now()})}super.broadcast(packet,opts)}};exports2.SessionAwareAdapter=SessionAwareAdapter;function shouldIncludePacket(sessionRooms,opts){let included=opts.rooms.size===0||sessionRooms.some(room=>opts.rooms.has(room)),notExcluded=sessionRooms.every(room=>!opts.except.has(room));return included&&notExcluded}}});var require_parent_namespace=__commonJS({"node_modules/socket.io/dist/parent-namespace.js"(exports2){"use strict";var __importDefault=exports2&&exports2.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports2,"__esModule",{value:!0});exports2.ParentNamespace=void 0;var namespace_1=require_namespace(),socket_io_adapter_1=require_dist2(),debug_1=__importDefault(require_src8()),debug=(0,debug_1.default)("socket.io:parent-namespace"),ParentNamespace=class _ParentNamespace extends namespace_1.Namespace{constructor(server){super(server,"/_"+_ParentNamespace.count++),this.children=new Set}_initAdapter(){this.adapter=new ParentBroadcastAdapter(this)}emit(ev,...args){return this.children.forEach(nsp=>{nsp.emit(ev,...args)}),!0}createChild(name){debug("creating child namespace %s",name);let namespace=new namespace_1.Namespace(this.server,name);if(this._fns.forEach(fn=>namespace.use(fn)),this.listeners("connect").forEach(listener=>namespace.on("connect",listener)),this.listeners("connection").forEach(listener=>namespace.on("connection",listener)),this.children.add(namespace),this.server._opts.cleanupEmptyChildNamespaces){let remove=namespace._remove;namespace._remove=socket=>{remove.call(namespace,socket),namespace.sockets.size===0&&(debug("closing child namespace %s",name),namespace.adapter.close(),this.server._nsps.delete(namespace.name),this.children.delete(namespace))}}return this.server._nsps.set(name,namespace),this.server.sockets.emitReserved("new_namespace",namespace),namespace}fetchSockets(){throw new Error("fetchSockets() is not supported on parent namespaces")}};exports2.ParentNamespace=ParentNamespace;ParentNamespace.count=0;var ParentBroadcastAdapter=class extends socket_io_adapter_1.Adapter{broadcast(packet,opts){this.nsp.children.forEach(nsp=>{nsp.adapter.broadcast(packet,opts)})}}}});var require_uws=__commonJS({"node_modules/socket.io/dist/uws.js"(exports2){"use strict";var __importDefault=exports2&&exports2.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports2,"__esModule",{value:!0});exports2.patchAdapter=patchAdapter;exports2.restoreAdapter=restoreAdapter;exports2.serveFile=serveFile;var socket_io_adapter_1=require_dist2(),fs_1=require("fs"),debug_1=__importDefault(require_src8()),debug=(0,debug_1.default)("socket.io:adapter-uws"),SEPARATOR="",{addAll,del,broadcast}=socket_io_adapter_1.Adapter.prototype;function patchAdapter(app){socket_io_adapter_1.Adapter.prototype.addAll=function(id,rooms){let isNew=!this.sids.has(id);addAll.call(this,id,rooms);let socket=this.nsp.sockets.get(id)||this.nsp._preConnectSockets.get(id);if(socket){if(socket.conn.transport.name==="websocket"){subscribe(this.nsp.name,socket,isNew,rooms);return}isNew&&socket.conn.on("upgrade",()=>{let rooms2=this.sids.get(id);rooms2&&subscribe(this.nsp.name,socket,isNew,rooms2)})}},socket_io_adapter_1.Adapter.prototype.del=function(id,room){del.call(this,id,room);let socket=this.nsp.sockets.get(id)||this.nsp._preConnectSockets.get(id);if(socket&&socket.conn.transport.name==="websocket"){let sessionId=socket.conn.id,websocket=socket.conn.transport.socket,topic=`${this.nsp.name}${SEPARATOR}${room}`;debug("unsubscribe connection %s from topic %s",sessionId,topic),websocket.unsubscribe(topic)}},socket_io_adapter_1.Adapter.prototype.broadcast=function(packet,opts){if(!(opts.rooms.size<=1&&opts.except.size===0)){broadcast.call(this,packet,opts);return}let flags=opts.flags||{},basePacketOpts={preEncoded:!0,volatile:flags.volatile,compress:flags.compress};packet.nsp=this.nsp.name;let encodedPackets=this.encoder.encode(packet),topic=opts.rooms.size===0?this.nsp.name:`${this.nsp.name}${SEPARATOR}${opts.rooms.keys().next().value}`;debug("fast publish to %s",topic),encodedPackets.forEach(encodedPacket=>{let isBinary=typeof encodedPacket!="string";app.publish(topic,isBinary?encodedPacket:"4"+encodedPacket,isBinary)}),this.apply(opts,socket=>{socket.conn.transport.name!=="websocket"&&socket.client.writeToEngine(encodedPackets,basePacketOpts)})}}function subscribe(namespaceName,socket,isNew,rooms){let sessionId=socket.conn.id,websocket=socket.conn.transport.socket;isNew&&(debug("subscribe connection %s to topic %s",sessionId,namespaceName),websocket.subscribe(namespaceName)),rooms.forEach(room=>{let topic=`${namespaceName}${SEPARATOR}${room}`;debug("subscribe connection %s to topic %s",sessionId,topic),websocket.subscribe(topic)})}function restoreAdapter(){socket_io_adapter_1.Adapter.prototype.addAll=addAll,socket_io_adapter_1.Adapter.prototype.del=del,socket_io_adapter_1.Adapter.prototype.broadcast=broadcast}var toArrayBuffer=buffer=>{let{buffer:arrayBuffer,byteOffset,byteLength}=buffer;return arrayBuffer.slice(byteOffset,byteOffset+byteLength)};function serveFile(res,filepath){let{size}=(0,fs_1.statSync)(filepath),readStream=(0,fs_1.createReadStream)(filepath),destroyReadStream=()=>!readStream.destroyed&&readStream.destroy(),onError=error=>{throw destroyReadStream(),error},onDataChunk=chunk=>{let arrayBufferChunk=toArrayBuffer(chunk);res.cork(()=>{let lastOffset=res.getWriteOffset(),[ok,done]=res.tryEnd(arrayBufferChunk,size);!done&&!ok&&(readStream.pause(),res.onWritable(offset=>{let[ok2,done2]=res.tryEnd(arrayBufferChunk.slice(offset-lastOffset),size);return!done2&&ok2&&readStream.resume(),ok2}))})};res.onAborted(destroyReadStream),readStream.on("data",onDataChunk).on("error",onError).on("end",destroyReadStream)}}});var require_package=__commonJS({"node_modules/socket.io/package.json"(exports2,module2){module2.exports={name:"socket.io",version:"4.8.3",description:"node.js realtime framework server",keywords:["realtime","framework","websocket","tcp","events","socket","io"],files:["dist/","client-dist/","wrapper.mjs","!**/*.tsbuildinfo"],directories:{doc:"docs/",example:"example/",lib:"lib/",test:"test/"},type:"commonjs",main:"./dist/index.js",exports:{".":{types:"./dist/index.d.ts",import:"./wrapper.mjs",require:"./dist/index.js"},"./package.json":"./package.json"},types:"./dist/index.d.ts",license:"MIT",homepage:"https://github.com/socketio/socket.io/tree/main/packages/socket.io#readme",repository:{type:"git",url:"git+https://github.com/socketio/socket.io.git"},bugs:{url:"https://github.com/socketio/socket.io/issues"},scripts:{compile:"rimraf ./dist && tsc",test:"npm run format:check && npm run compile && npm run test:types && npm run test:unit","test:types":"tsd","test:unit":"nyc mocha --import=tsx --reporter spec --slow 200 --bail --timeout 10000 test/index.ts","format:check":'prettier --check "lib/**/*.ts" "test/**/*.ts"',"format:fix":'prettier --write "lib/**/*.ts" "test/**/*.ts"',prepack:"npm run compile"},dependencies:{accepts:"~1.3.4",base64id:"~2.0.0",cors:"~2.8.5",debug:"~4.4.1","engine.io":"~6.6.0","socket.io-adapter":"~2.5.2","socket.io-parser":"~4.2.4"},contributors:[{name:"Guillermo Rauch",email:"rauchg@gmail.com"},{name:"Arnout Kazemier",email:"info@3rd-eden.com"},{name:"Vladimir Dronnikov",email:"dronnikov@gmail.com"},{name:"Einar Otto Stangvik",email:"einaros@gmail.com"}],engines:{node:">=10.2.0"},tsd:{directory:"test"}}}});var require_dist3=__commonJS({"node_modules/socket.io/dist/index.js"(exports2,module2){"use strict";var __createBinding=exports2&&exports2.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__setModuleDefault=exports2&&exports2.__setModuleDefault||(Object.create?(function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}):function(o,v){o.default=v}),__importStar=exports2&&exports2.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.prototype.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__importDefault=exports2&&exports2.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports2,"__esModule",{value:!0});exports2.Namespace=exports2.Socket=exports2.Server=void 0;var http_1=__importDefault(require("http")),fs_1=require("fs"),zlib_1=require("zlib"),accepts=require_accepts(),stream_1=require("stream"),path=require("path"),engine_io_1=require_engine_io(),client_1=require_client(),events_1=require("events"),namespace_1=require_namespace();Object.defineProperty(exports2,"Namespace",{enumerable:!0,get:function(){return namespace_1.Namespace}});var parent_namespace_1=require_parent_namespace(),socket_io_adapter_1=require_dist2(),parser=__importStar(require_cjs2()),debug_1=__importDefault(require_src8()),socket_1=require_socket2();Object.defineProperty(exports2,"Socket",{enumerable:!0,get:function(){return socket_1.Socket}});var typed_events_1=require_typed_events(),uws_1=require_uws(),cors_1=__importDefault(require_lib4()),debug=(0,debug_1.default)("socket.io:server"),clientVersion=require_package().version,dotMapRegex=/\.map/,Server=class _Server extends typed_events_1.StrictEventEmitter{constructor(srv,opts={}){super(),this._nsps=new Map,this.parentNsps=new Map,this.parentNamespacesFromRegExp=new Map,typeof srv=="object"&&srv instanceof Object&&!srv.listen&&(opts=srv,srv=void 0),this.path(opts.path||"/socket.io"),this.connectTimeout(opts.connectTimeout||45e3),this.serveClient(opts.serveClient!==!1),this._parser=opts.parser||parser,this.encoder=new this._parser.Encoder,this.opts=opts,opts.connectionStateRecovery?(opts.connectionStateRecovery=Object.assign({maxDisconnectionDuration:120*1e3,skipMiddlewares:!0},opts.connectionStateRecovery),this.adapter(opts.adapter||socket_io_adapter_1.SessionAwareAdapter)):this.adapter(opts.adapter||socket_io_adapter_1.Adapter),opts.cleanupEmptyChildNamespaces=!!opts.cleanupEmptyChildNamespaces,this.sockets=this.of("/"),(srv||typeof srv=="number")&&this.attach(srv),this.opts.cors&&(this._corsMiddleware=(0,cors_1.default)(this.opts.cors))}get _opts(){return this.opts}serveClient(v){return arguments.length?(this._serveClient=v,this):this._serveClient}_checkNamespace(name,auth,fn){if(this.parentNsps.size===0)return fn(!1);let keysIterator=this.parentNsps.keys(),run=()=>{let nextFn=keysIterator.next();if(nextFn.done)return fn(!1);nextFn.value(name,auth,(err,allow)=>{if(err||!allow)return run();if(this._nsps.has(name))return debug("dynamic namespace %s already exists",name),fn(this._nsps.get(name));let namespace=this.parentNsps.get(nextFn.value).createChild(name);debug("dynamic namespace %s was created",name),fn(namespace)})};run()}path(v){if(!arguments.length)return this._path;this._path=v.replace(/\/$/,"");let escapedPath=this._path.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");return this.clientPathRegex=new RegExp("^"+escapedPath+"/socket\\.io(\\.msgpack|\\.esm)?(\\.min)?\\.js(\\.map)?(?:\\?|$)"),this}connectTimeout(v){return v===void 0?this._connectTimeout:(this._connectTimeout=v,this)}adapter(v){if(!arguments.length)return this._adapter;this._adapter=v;for(let nsp of this._nsps.values())nsp._initAdapter();return this}listen(srv,opts={}){return this.attach(srv,opts)}attach(srv,opts={}){if(typeof srv=="function"){let msg="You are trying to attach socket.io to an express request handler function. Please pass a http.Server instance.";throw new Error(msg)}if(Number(srv)==srv&&(srv=Number(srv)),typeof srv=="number"){debug("creating http server and binding to %d",srv);let port=srv;srv=http_1.default.createServer((req,res)=>{res.writeHead(404),res.end()}),srv.listen(port)}return Object.assign(opts,this.opts),opts.path=opts.path||this._path,this.initEngine(srv,opts),this}attachApp(app,opts={}){Object.assign(opts,this.opts),opts.path=opts.path||this._path,debug("creating uWebSockets.js-based engine with opts %j",opts);let engine=new engine_io_1.uServer(opts);engine.attach(app,opts),this.bind(engine),this._serveClient&&app.get(`${this._path}/*`,(res,req)=>{if(!this.clientPathRegex.test(req.getUrl())){req.setYield(!0);return}let filename=req.getUrl().replace(this._path,"").replace(/\?.*$/,"").replace(/^\//,""),isMap=dotMapRegex.test(filename),type=isMap?"map":"source",expectedEtag='"'+clientVersion+'"',weakEtag="W/"+expectedEtag,etag=req.getHeader("if-none-match");if(etag&&(expectedEtag===etag||weakEtag===etag)){debug("serve client %s 304",type),res.writeStatus("304 Not Modified"),res.end();return}debug("serve client %s",type),res.writeHeader("cache-control","public, max-age=0"),res.writeHeader("content-type","application/"+(isMap?"json":"javascript")+"; charset=utf-8"),res.writeHeader("etag",expectedEtag);let filepath=path.join(__dirname,"../client-dist/",filename);(0,uws_1.serveFile)(res,filepath)}),(0,uws_1.patchAdapter)(app)}initEngine(srv,opts){debug("creating engine.io instance with opts %j",opts),this.eio=(0,engine_io_1.attach)(srv,opts),this._serveClient&&this.attachServe(srv),this.httpServer=srv,this.bind(this.eio)}attachServe(srv){debug("attaching client serving req handler");let evs=srv.listeners("request").slice(0);srv.removeAllListeners("request"),srv.on("request",(req,res)=>{if(this.clientPathRegex.test(req.url))this._corsMiddleware?this._corsMiddleware(req,res,()=>{this.serve(req,res)}):this.serve(req,res);else for(let i=0;i<evs.length;i++)evs[i].call(srv,req,res)})}serve(req,res){let filename=req.url.replace(this._path,"").replace(/\?.*$/,""),isMap=dotMapRegex.test(filename),type=isMap?"map":"source",expectedEtag='"'+clientVersion+'"',weakEtag="W/"+expectedEtag,etag=req.headers["if-none-match"];if(etag&&(expectedEtag===etag||weakEtag===etag)){debug("serve client %s 304",type),res.writeHead(304),res.end();return}debug("serve client %s",type),res.setHeader("Cache-Control","public, max-age=0"),res.setHeader("Content-Type","application/"+(isMap?"json":"javascript")+"; charset=utf-8"),res.setHeader("ETag",expectedEtag),_Server.sendFile(filename,req,res)}static sendFile(filename,req,res){let readStream=(0,fs_1.createReadStream)(path.join(__dirname,"../client-dist/",filename)),encoding=accepts(req).encodings(["br","gzip","deflate"]),onError=err=>{err&&res.end()};switch(encoding){case"br":res.writeHead(200,{"content-encoding":"br"}),(0,stream_1.pipeline)(readStream,(0,zlib_1.createBrotliCompress)(),res,onError);break;case"gzip":res.writeHead(200,{"content-encoding":"gzip"}),(0,stream_1.pipeline)(readStream,(0,zlib_1.createGzip)(),res,onError);break;case"deflate":res.writeHead(200,{"content-encoding":"deflate"}),(0,stream_1.pipeline)(readStream,(0,zlib_1.createDeflate)(),res,onError);break;default:res.writeHead(200),(0,stream_1.pipeline)(readStream,res,onError)}}bind(engine){return this.engine=engine,this.engine.on("connection",this.onconnection.bind(this)),this}onconnection(conn){debug("incoming connection with id %s",conn.id);let client=new client_1.Client(this,conn);return conn.protocol===3&&client.connect("/"),this}of(name,fn){if(typeof name=="function"||name instanceof RegExp){let parentNsp=new parent_namespace_1.ParentNamespace(this);return debug("initializing parent namespace %s",parentNsp.name),typeof name=="function"?this.parentNsps.set(name,parentNsp):(this.parentNsps.set((nsp2,conn,next)=>next(null,name.test(nsp2)),parentNsp),this.parentNamespacesFromRegExp.set(name,parentNsp)),fn&&parentNsp.on("connect",fn),parentNsp}String(name)[0]!=="/"&&(name="/"+name);let nsp=this._nsps.get(name);if(!nsp){for(let[regex,parentNamespace]of this.parentNamespacesFromRegExp)if(regex.test(name))return debug("attaching namespace %s to parent namespace %s",name,regex),parentNamespace.createChild(name);debug("initializing namespace %s",name),nsp=new namespace_1.Namespace(this,name),this._nsps.set(name,nsp),name!=="/"&&this.sockets.emitReserved("new_namespace",nsp)}return fn&&nsp.on("connect",fn),nsp}async close(fn){if(await Promise.allSettled([...this._nsps.values()].map(async nsp=>{nsp.sockets.forEach(socket=>{socket._onclose("server shutting down")}),await nsp.adapter.close()})),this.engine.close(),(0,uws_1.restoreAdapter)(),this.httpServer)return new Promise(resolve=>{this.httpServer.close(err=>{fn&&fn(err),err&&debug("server was not running"),resolve()})});fn&&fn()}use(fn){return this.sockets.use(fn),this}to(room){return this.sockets.to(room)}in(room){return this.sockets.in(room)}except(room){return this.sockets.except(room)}send(...args){return this.sockets.emit("message",...args),this}write(...args){return this.sockets.emit("message",...args),this}serverSideEmit(ev,...args){return this.sockets.serverSideEmit(ev,...args)}serverSideEmitWithAck(ev,...args){return this.sockets.serverSideEmitWithAck(ev,...args)}allSockets(){return this.sockets.allSockets()}compress(compress){return this.sockets.compress(compress)}get volatile(){return this.sockets.volatile}get local(){return this.sockets.local}timeout(timeout){return this.sockets.timeout(timeout)}fetchSockets(){return this.sockets.fetchSockets()}socketsJoin(room){return this.sockets.socketsJoin(room)}socketsLeave(room){return this.sockets.socketsLeave(room)}disconnectSockets(close=!1){return this.sockets.disconnectSockets(close)}};exports2.Server=Server;var emitterMethods=Object.keys(events_1.EventEmitter.prototype).filter(function(key){return typeof events_1.EventEmitter.prototype[key]=="function"});emitterMethods.forEach(function(fn){Server.prototype[fn]=function(){return this.sockets[fn].apply(this.sockets,arguments)}});module2.exports=(srv,opts)=>new Server(srv,opts);module2.exports.Server=Server;module2.exports.Namespace=namespace_1.Namespace;module2.exports.Socket=socket_1.Socket}});var require_listCacheClear=__commonJS({"node_modules/lodash/_listCacheClear.js"(exports2,module2){function listCacheClear(){this.__data__=[],this.size=0}module2.exports=listCacheClear}});var require_eq=__commonJS({"node_modules/lodash/eq.js"(exports2,module2){function eq(value,other){return value===other||value!==value&&other!==other}module2.exports=eq}});var require_assocIndexOf=__commonJS({"node_modules/lodash/_assocIndexOf.js"(exports2,module2){var eq=require_eq();function assocIndexOf(array,key){for(var length=array.length;length--;)if(eq(array[length][0],key))return length;return-1}module2.exports=assocIndexOf}});var require_listCacheDelete=__commonJS({"node_modules/lodash/_listCacheDelete.js"(exports2,module2){var assocIndexOf=require_assocIndexOf(),arrayProto=Array.prototype,splice=arrayProto.splice;function listCacheDelete(key){var data=this.__data__,index=assocIndexOf(data,key);if(index<0)return!1;var lastIndex=data.length-1;return index==lastIndex?data.pop():splice.call(data,index,1),--this.size,!0}module2.exports=listCacheDelete}});var require_listCacheGet=__commonJS({"node_modules/lodash/_listCacheGet.js"(exports2,module2){var assocIndexOf=require_assocIndexOf();function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]}module2.exports=listCacheGet}});var require_listCacheHas=__commonJS({"node_modules/lodash/_listCacheHas.js"(exports2,module2){var assocIndexOf=require_assocIndexOf();function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}module2.exports=listCacheHas}});var require_listCacheSet=__commonJS({"node_modules/lodash/_listCacheSet.js"(exports2,module2){var assocIndexOf=require_assocIndexOf();function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?(++this.size,data.push([key,value])):data[index][1]=value,this}module2.exports=listCacheSet}});var require_ListCache=__commonJS({"node_modules/lodash/_ListCache.js"(exports2,module2){var listCacheClear=require_listCacheClear(),listCacheDelete=require_listCacheDelete(),listCacheGet=require_listCacheGet(),listCacheHas=require_listCacheHas(),listCacheSet=require_listCacheSet();function ListCache(entries){var index=-1,length=entries==null?0:entries.length;for(this.clear();++index<length;){var entry=entries[index];this.set(entry[0],entry[1])}}ListCache.prototype.clear=listCacheClear;ListCache.prototype.delete=listCacheDelete;ListCache.prototype.get=listCacheGet;ListCache.prototype.has=listCacheHas;ListCache.prototype.set=listCacheSet;module2.exports=ListCache}});var require_stackClear=__commonJS({"node_modules/lodash/_stackClear.js"(exports2,module2){var ListCache=require_ListCache();function stackClear(){this.__data__=new ListCache,this.size=0}module2.exports=stackClear}});var require_stackDelete=__commonJS({"node_modules/lodash/_stackDelete.js"(exports2,module2){function stackDelete(key){var data=this.__data__,result=data.delete(key);return this.size=data.size,result}module2.exports=stackDelete}});var require_stackGet=__commonJS({"node_modules/lodash/_stackGet.js"(exports2,module2){function stackGet(key){return this.__data__.get(key)}module2.exports=stackGet}});var require_stackHas=__commonJS({"node_modules/lodash/_stackHas.js"(exports2,module2){function stackHas(key){return this.__data__.has(key)}module2.exports=stackHas}});var require_freeGlobal=__commonJS({"node_modules/lodash/_freeGlobal.js"(exports2,module2){var freeGlobal=typeof global=="object"&&global&&global.Object===Object&&global;module2.exports=freeGlobal}});var require_root=__commonJS({"node_modules/lodash/_root.js"(exports2,module2){var freeGlobal=require_freeGlobal(),freeSelf=typeof self=="object"&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")();module2.exports=root}});var require_Symbol=__commonJS({"node_modules/lodash/_Symbol.js"(exports2,module2){var root=require_root(),Symbol2=root.Symbol;module2.exports=Symbol2}});var require_getRawTag=__commonJS({"node_modules/lodash/_getRawTag.js"(exports2,module2){var Symbol2=require_Symbol(),objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,nativeObjectToString=objectProto.toString,symToStringTag=Symbol2?Symbol2.toStringTag:void 0;function getRawTag(value){var isOwn=hasOwnProperty.call(value,symToStringTag),tag=value[symToStringTag];try{value[symToStringTag]=void 0;var unmasked=!0}catch{}var result=nativeObjectToString.call(value);return unmasked&&(isOwn?value[symToStringTag]=tag:delete value[symToStringTag]),result}module2.exports=getRawTag}});var require_objectToString=__commonJS({"node_modules/lodash/_objectToString.js"(exports2,module2){var objectProto=Object.prototype,nativeObjectToString=objectProto.toString;function objectToString(value){return nativeObjectToString.call(value)}module2.exports=objectToString}});var require_baseGetTag=__commonJS({"node_modules/lodash/_baseGetTag.js"(exports2,module2){var Symbol2=require_Symbol(),getRawTag=require_getRawTag(),objectToString=require_objectToString(),nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag=Symbol2?Symbol2.toStringTag:void 0;function baseGetTag(value){return value==null?value===void 0?undefinedTag:nullTag:symToStringTag&&symToStringTag in Object(value)?getRawTag(value):objectToString(value)}module2.exports=baseGetTag}});var require_isObject=__commonJS({"node_modules/lodash/isObject.js"(exports2,module2){function isObject(value){var type=typeof value;return value!=null&&(type=="object"||type=="function")}module2.exports=isObject}});var require_isFunction=__commonJS({"node_modules/lodash/isFunction.js"(exports2,module2){var baseGetTag=require_baseGetTag(),isObject=require_isObject(),asyncTag="[object AsyncFunction]",funcTag="[object Function]",genTag="[object GeneratorFunction]",proxyTag="[object Proxy]";function isFunction(value){if(!isObject(value))return!1;var tag=baseGetTag(value);return tag==funcTag||tag==genTag||tag==asyncTag||tag==proxyTag}module2.exports=isFunction}});var require_coreJsData=__commonJS({"node_modules/lodash/_coreJsData.js"(exports2,module2){var root=require_root(),coreJsData=root["__core-js_shared__"];module2.exports=coreJsData}});var require_isMasked=__commonJS({"node_modules/lodash/_isMasked.js"(exports2,module2){var coreJsData=require_coreJsData(),maskSrcKey=(function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""})();function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}module2.exports=isMasked}});var require_toSource=__commonJS({"node_modules/lodash/_toSource.js"(exports2,module2){var funcProto=Function.prototype,funcToString=funcProto.toString;function toSource(func){if(func!=null){try{return funcToString.call(func)}catch{}try{return func+""}catch{}}return""}module2.exports=toSource}});var require_baseIsNative=__commonJS({"node_modules/lodash/_baseIsNative.js"(exports2,module2){var isFunction=require_isFunction(),isMasked=require_isMasked(),isObject=require_isObject(),toSource=require_toSource(),reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,funcProto=Function.prototype,objectProto=Object.prototype,funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function baseIsNative(value){if(!isObject(value)||isMasked(value))return!1;var pattern=isFunction(value)?reIsNative:reIsHostCtor;return pattern.test(toSource(value))}module2.exports=baseIsNative}});var require_getValue=__commonJS({"node_modules/lodash/_getValue.js"(exports2,module2){function getValue(object,key){return object?.[key]}module2.exports=getValue}});var require_getNative=__commonJS({"node_modules/lodash/_getNative.js"(exports2,module2){var baseIsNative=require_baseIsNative(),getValue=require_getValue();function getNative(object,key){var value=getValue(object,key);return baseIsNative(value)?value:void 0}module2.exports=getNative}});var require_Map=__commonJS({"node_modules/lodash/_Map.js"(exports2,module2){var getNative=require_getNative(),root=require_root(),Map2=getNative(root,"Map");module2.exports=Map2}});var require_nativeCreate=__commonJS({"node_modules/lodash/_nativeCreate.js"(exports2,module2){var getNative=require_getNative(),nativeCreate=getNative(Object,"create");module2.exports=nativeCreate}});var require_hashClear=__commonJS({"node_modules/lodash/_hashClear.js"(exports2,module2){var nativeCreate=require_nativeCreate();function hashClear(){this.__data__=nativeCreate?nativeCreate(null):{},this.size=0}module2.exports=hashClear}});var require_hashDelete=__commonJS({"node_modules/lodash/_hashDelete.js"(exports2,module2){function hashDelete(key){var result=this.has(key)&&delete this.__data__[key];return this.size-=result?1:0,result}module2.exports=hashDelete}});var require_hashGet=__commonJS({"node_modules/lodash/_hashGet.js"(exports2,module2){var nativeCreate=require_nativeCreate(),HASH_UNDEFINED="__lodash_hash_undefined__",objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty;function hashGet(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0}module2.exports=hashGet}});var require_hashHas=__commonJS({"node_modules/lodash/_hashHas.js"(exports2,module2){var nativeCreate=require_nativeCreate(),objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty;function hashHas(key){var data=this.__data__;return nativeCreate?data[key]!==void 0:hasOwnProperty.call(data,key)}module2.exports=hashHas}});var require_hashSet=__commonJS({"node_modules/lodash/_hashSet.js"(exports2,module2){var nativeCreate=require_nativeCreate(),HASH_UNDEFINED="__lodash_hash_undefined__";function hashSet(key,value){var data=this.__data__;return this.size+=this.has(key)?0:1,data[key]=nativeCreate&&value===void 0?HASH_UNDEFINED:value,this}module2.exports=hashSet}});var require_Hash=__commonJS({"node_modules/lodash/_Hash.js"(exports2,module2){var hashClear=require_hashClear(),hashDelete=require_hashDelete(),hashGet=require_hashGet(),hashHas=require_hashHas(),hashSet=require_hashSet();function Hash(entries){var index=-1,length=entries==null?0:entries.length;for(this.clear();++index<length;){var entry=entries[index];this.set(entry[0],entry[1])}}Hash.prototype.clear=hashClear;Hash.prototype.delete=hashDelete;Hash.prototype.get=hashGet;Hash.prototype.has=hashHas;Hash.prototype.set=hashSet;module2.exports=Hash}});var require_mapCacheClear=__commonJS({"node_modules/lodash/_mapCacheClear.js"(exports2,module2){var Hash=require_Hash(),ListCache=require_ListCache(),Map2=require_Map();function mapCacheClear(){this.size=0,this.__data__={hash:new Hash,map:new(Map2||ListCache),string:new Hash}}module2.exports=mapCacheClear}});var require_isKeyable=__commonJS({"node_modules/lodash/_isKeyable.js"(exports2,module2){function isKeyable(value){var type=typeof value;return type=="string"||type=="number"||type=="symbol"||type=="boolean"?value!=="__proto__":value===null}module2.exports=isKeyable}});var require_getMapData=__commonJS({"node_modules/lodash/_getMapData.js"(exports2,module2){var isKeyable=require_isKeyable();function getMapData(map,key){var data=map.__data__;return isKeyable(key)?data[typeof key=="string"?"string":"hash"]:data.map}module2.exports=getMapData}});var require_mapCacheDelete=__commonJS({"node_modules/lodash/_mapCacheDelete.js"(exports2,module2){var getMapData=require_getMapData();function mapCacheDelete(key){var result=getMapData(this,key).delete(key);return this.size-=result?1:0,result}module2.exports=mapCacheDelete}});var require_mapCacheGet=__commonJS({"node_modules/lodash/_mapCacheGet.js"(exports2,module2){var getMapData=require_getMapData();function mapCacheGet(key){return getMapData(this,key).get(key)}module2.exports=mapCacheGet}});var require_mapCacheHas=__commonJS({"node_modules/lodash/_mapCacheHas.js"(exports2,module2){var getMapData=require_getMapData();function mapCacheHas(key){return getMapData(this,key).has(key)}module2.exports=mapCacheHas}});var require_mapCacheSet=__commonJS({"node_modules/lodash/_mapCacheSet.js"(exports2,module2){var getMapData=require_getMapData();function mapCacheSet(key,value){var data=getMapData(this,key),size=data.size;return data.set(key,value),this.size+=data.size==size?0:1,this}module2.exports=mapCacheSet}});var require_MapCache=__commonJS({"node_modules/lodash/_MapCache.js"(exports2,module2){var mapCacheClear=require_mapCacheClear(),mapCacheDelete=require_mapCacheDelete(),mapCacheGet=require_mapCacheGet(),mapCacheHas=require_mapCacheHas(),mapCacheSet=require_mapCacheSet();function MapCache(entries){var index=-1,length=entries==null?0:entries.length;for(this.clear();++index<length;){var entry=entries[index];this.set(entry[0],entry[1])}}MapCache.prototype.clear=mapCacheClear;MapCache.prototype.delete=mapCacheDelete;MapCache.prototype.get=mapCacheGet;MapCache.prototype.has=mapCacheHas;MapCache.prototype.set=mapCacheSet;module2.exports=MapCache}});var require_stackSet=__commonJS({"node_modules/lodash/_stackSet.js"(exports2,module2){var ListCache=require_ListCache(),Map2=require_Map(),MapCache=require_MapCache(),LARGE_ARRAY_SIZE=200;function stackSet(key,value){var data=this.__data__;if(data instanceof ListCache){var pairs=data.__data__;if(!Map2||pairs.length<LARGE_ARRAY_SIZE-1)return pairs.push([key,value]),this.size=++data.size,this;data=this.__data__=new MapCache(pairs)}return data.set(key,value),this.size=data.size,this}module2.exports=stackSet}});var require_Stack=__commonJS({"node_modules/lodash/_Stack.js"(exports2,module2){var ListCache=require_ListCache(),stackClear=require_stackClear(),stackDelete=require_stackDelete(),stackGet=require_stackGet(),stackHas=require_stackHas(),stackSet=require_stackSet();function Stack(entries){var data=this.__data__=new ListCache(entries);this.size=data.size}Stack.prototype.clear=stackClear;Stack.prototype.delete=stackDelete;Stack.prototype.get=stackGet;Stack.prototype.has=stackHas;Stack.prototype.set=stackSet;module2.exports=Stack}});var require_setCacheAdd=__commonJS({"node_modules/lodash/_setCacheAdd.js"(exports2,module2){var HASH_UNDEFINED="__lodash_hash_undefined__";function setCacheAdd(value){return this.__data__.set(value,HASH_UNDEFINED),this}module2.exports=setCacheAdd}});var require_setCacheHas=__commonJS({"node_modules/lodash/_setCacheHas.js"(exports2,module2){function setCacheHas(value){return this.__data__.has(value)}module2.exports=setCacheHas}});var require_SetCache=__commonJS({"node_modules/lodash/_SetCache.js"(exports2,module2){var MapCache=require_MapCache(),setCacheAdd=require_setCacheAdd(),setCacheHas=require_setCacheHas();function SetCache(values){var index=-1,length=values==null?0:values.length;for(this.__data__=new MapCache;++index<length;)this.add(values[index])}SetCache.prototype.add=SetCache.prototype.push=setCacheAdd;SetCache.prototype.has=setCacheHas;module2.exports=SetCache}});var require_arraySome=__commonJS({"node_modules/lodash/_arraySome.js"(exports2,module2){function arraySome(array,predicate){for(var index=-1,length=array==null?0:array.length;++index<length;)if(predicate(array[index],index,array))return!0;return!1}module2.exports=arraySome}});var require_cacheHas=__commonJS({"node_modules/lodash/_cacheHas.js"(exports2,module2){function cacheHas(cache,key){return cache.has(key)}module2.exports=cacheHas}});var require_equalArrays=__commonJS({"node_modules/lodash/_equalArrays.js"(exports2,module2){var SetCache=require_SetCache(),arraySome=require_arraySome(),cacheHas=require_cacheHas(),COMPARE_PARTIAL_FLAG=1,COMPARE_UNORDERED_FLAG=2;function equalArrays(array,other,bitmask,customizer,equalFunc,stack){var isPartial=bitmask&COMPARE_PARTIAL_FLAG,arrLength=array.length,othLength=other.length;if(arrLength!=othLength&&!(isPartial&&othLength>arrLength))return!1;var arrStacked=stack.get(array),othStacked=stack.get(other);if(arrStacked&&othStacked)return arrStacked==other&&othStacked==array;var index=-1,result=!0,seen=bitmask&COMPARE_UNORDERED_FLAG?new SetCache:void 0;for(stack.set(array,other),stack.set(other,array);++index<arrLength;){var arrValue=array[index],othValue=other[index];if(customizer)var compared=isPartial?customizer(othValue,arrValue,index,other,array,stack):customizer(arrValue,othValue,index,array,other,stack);if(compared!==void 0){if(compared)continue;result=!1;break}if(seen){if(!arraySome(other,function(othValue2,othIndex){if(!cacheHas(seen,othIndex)&&(arrValue===othValue2||equalFunc(arrValue,othValue2,bitmask,customizer,stack)))return seen.push(othIndex)})){result=!1;break}}else if(!(arrValue===othValue||equalFunc(arrValue,othValue,bitmask,customizer,stack))){result=!1;break}}return stack.delete(array),stack.delete(other),result}module2.exports=equalArrays}});var require_Uint8Array=__commonJS({"node_modules/lodash/_Uint8Array.js"(exports2,module2){var root=require_root(),Uint8Array2=root.Uint8Array;module2.exports=Uint8Array2}});var require_mapToArray=__commonJS({"node_modules/lodash/_mapToArray.js"(exports2,module2){function mapToArray(map){var index=-1,result=Array(map.size);return map.forEach(function(value,key){result[++index]=[key,value]}),result}module2.exports=mapToArray}});var require_setToArray=__commonJS({"node_modules/lodash/_setToArray.js"(exports2,module2){function setToArray(set){var index=-1,result=Array(set.size);return set.forEach(function(value){result[++index]=value}),result}module2.exports=setToArray}});var require_equalByTag=__commonJS({"node_modules/lodash/_equalByTag.js"(exports2,module2){var Symbol2=require_Symbol(),Uint8Array2=require_Uint8Array(),eq=require_eq(),equalArrays=require_equalArrays(),mapToArray=require_mapToArray(),setToArray=require_setToArray(),COMPARE_PARTIAL_FLAG=1,COMPARE_UNORDERED_FLAG=2,boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",mapTag="[object Map]",numberTag="[object Number]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",symbolProto=Symbol2?Symbol2.prototype:void 0,symbolValueOf=symbolProto?symbolProto.valueOf:void 0;function equalByTag(object,other,tag,bitmask,customizer,equalFunc,stack){switch(tag){case dataViewTag:if(object.byteLength!=other.byteLength||object.byteOffset!=other.byteOffset)return!1;object=object.buffer,other=other.buffer;case arrayBufferTag:return!(object.byteLength!=other.byteLength||!equalFunc(new Uint8Array2(object),new Uint8Array2(other)));case boolTag:case dateTag:case numberTag:return eq(+object,+other);case errorTag:return object.name==other.name&&object.message==other.message;case regexpTag:case stringTag:return object==other+"";case mapTag:var convert=mapToArray;case setTag:var isPartial=bitmask&COMPARE_PARTIAL_FLAG;if(convert||(convert=setToArray),object.size!=other.size&&!isPartial)return!1;var stacked=stack.get(object);if(stacked)return stacked==other;bitmask|=COMPARE_UNORDERED_FLAG,stack.set(object,other);var result=equalArrays(convert(object),convert(other),bitmask,customizer,equalFunc,stack);return stack.delete(object),result;case symbolTag:if(symbolValueOf)return symbolValueOf.call(object)==symbolValueOf.call(other)}return!1}module2.exports=equalByTag}});var require_arrayPush=__commonJS({"node_modules/lodash/_arrayPush.js"(exports2,module2){function arrayPush(array,values){for(var index=-1,length=values.length,offset=array.length;++index<length;)array[offset+index]=values[index];return array}module2.exports=arrayPush}});var require_isArray=__commonJS({"node_modules/lodash/isArray.js"(exports2,module2){var isArray=Array.isArray;module2.exports=isArray}});var require_baseGetAllKeys=__commonJS({"node_modules/lodash/_baseGetAllKeys.js"(exports2,module2){var arrayPush=require_arrayPush(),isArray=require_isArray();function baseGetAllKeys(object,keysFunc,symbolsFunc){var result=keysFunc(object);return isArray(object)?result:arrayPush(result,symbolsFunc(object))}module2.exports=baseGetAllKeys}});var require_arrayFilter=__commonJS({"node_modules/lodash/_arrayFilter.js"(exports2,module2){function arrayFilter(array,predicate){for(var index=-1,length=array==null?0:array.length,resIndex=0,result=[];++index<length;){var value=array[index];predicate(value,index,array)&&(result[resIndex++]=value)}return result}module2.exports=arrayFilter}});var require_stubArray=__commonJS({"node_modules/lodash/stubArray.js"(exports2,module2){function stubArray(){return[]}module2.exports=stubArray}});var require_getSymbols=__commonJS({"node_modules/lodash/_getSymbols.js"(exports2,module2){var arrayFilter=require_arrayFilter(),stubArray=require_stubArray(),objectProto=Object.prototype,propertyIsEnumerable=objectProto.propertyIsEnumerable,nativeGetSymbols=Object.getOwnPropertySymbols,getSymbols=nativeGetSymbols?function(object){return object==null?[]:(object=Object(object),arrayFilter(nativeGetSymbols(object),function(symbol){return propertyIsEnumerable.call(object,symbol)}))}:stubArray;module2.exports=getSymbols}});var require_baseTimes=__commonJS({"node_modules/lodash/_baseTimes.js"(exports2,module2){function baseTimes(n,iteratee){for(var index=-1,result=Array(n);++index<n;)result[index]=iteratee(index);return result}module2.exports=baseTimes}});var require_isObjectLike=__commonJS({"node_modules/lodash/isObjectLike.js"(exports2,module2){function isObjectLike(value){return value!=null&&typeof value=="object"}module2.exports=isObjectLike}});var require_baseIsArguments=__commonJS({"node_modules/lodash/_baseIsArguments.js"(exports2,module2){var baseGetTag=require_baseGetTag(),isObjectLike=require_isObjectLike(),argsTag="[object Arguments]";function baseIsArguments(value){return isObjectLike(value)&&baseGetTag(value)==argsTag}module2.exports=baseIsArguments}});var require_isArguments=__commonJS({"node_modules/lodash/isArguments.js"(exports2,module2){var baseIsArguments=require_baseIsArguments(),isObjectLike=require_isObjectLike(),objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,propertyIsEnumerable=objectProto.propertyIsEnumerable,isArguments=baseIsArguments((function(){return arguments})())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")};module2.exports=isArguments}});var require_stubFalse=__commonJS({"node_modules/lodash/stubFalse.js"(exports2,module2){function stubFalse(){return!1}module2.exports=stubFalse}});var require_isBuffer=__commonJS({"node_modules/lodash/isBuffer.js"(exports2,module2){var root=require_root(),stubFalse=require_stubFalse(),freeExports=typeof exports2=="object"&&exports2&&!exports2.nodeType&&exports2,freeModule=freeExports&&typeof module2=="object"&&module2&&!module2.nodeType&&module2,moduleExports=freeModule&&freeModule.exports===freeExports,Buffer2=moduleExports?root.Buffer:void 0,nativeIsBuffer=Buffer2?Buffer2.isBuffer:void 0,isBuffer=nativeIsBuffer||stubFalse;module2.exports=isBuffer}});var require_isIndex=__commonJS({"node_modules/lodash/_isIndex.js"(exports2,module2){var MAX_SAFE_INTEGER=9007199254740991,reIsUint=/^(?:0|[1-9]\d*)$/;function isIndex(value,length){var type=typeof value;return length=length??MAX_SAFE_INTEGER,!!length&&(type=="number"||type!="symbol"&&reIsUint.test(value))&&value>-1&&value%1==0&&value<length}module2.exports=isIndex}});var require_isLength=__commonJS({"node_modules/lodash/isLength.js"(exports2,module2){var MAX_SAFE_INTEGER=9007199254740991;function isLength(value){return typeof value=="number"&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}module2.exports=isLength}});var require_baseIsTypedArray=__commonJS({"node_modules/lodash/_baseIsTypedArray.js"(exports2,module2){var baseGetTag=require_baseGetTag(),isLength=require_isLength(),isObjectLike=require_isObjectLike(),argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",weakMapTag="[object WeakMap]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0;typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;function baseIsTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[baseGetTag(value)]}module2.exports=baseIsTypedArray}});var require_baseUnary=__commonJS({"node_modules/lodash/_baseUnary.js"(exports2,module2){function baseUnary(func){return function(value){return func(value)}}module2.exports=baseUnary}});var require_nodeUtil=__commonJS({"node_modules/lodash/_nodeUtil.js"(exports2,module2){var freeGlobal=require_freeGlobal(),freeExports=typeof exports2=="object"&&exports2&&!exports2.nodeType&&exports2,freeModule=freeExports&&typeof module2=="object"&&module2&&!module2.nodeType&&module2,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=(function(){try{var types=freeModule&&freeModule.require&&freeModule.require("util").types;return types||freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch{}})();module2.exports=nodeUtil}});var require_isTypedArray=__commonJS({"node_modules/lodash/isTypedArray.js"(exports2,module2){var baseIsTypedArray=require_baseIsTypedArray(),baseUnary=require_baseUnary(),nodeUtil=require_nodeUtil(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;module2.exports=isTypedArray}});var require_arrayLikeKeys=__commonJS({"node_modules/lodash/_arrayLikeKeys.js"(exports2,module2){var baseTimes=require_baseTimes(),isArguments=require_isArguments(),isArray=require_isArray(),isBuffer=require_isBuffer(),isIndex=require_isIndex(),isTypedArray=require_isTypedArray(),objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty;function arrayLikeKeys(value,inherited){var isArr=isArray(value),isArg=!isArr&&isArguments(value),isBuff=!isArr&&!isArg&&isBuffer(value),isType=!isArr&&!isArg&&!isBuff&&isTypedArray(value),skipIndexes=isArr||isArg||isBuff||isType,result=skipIndexes?baseTimes(value.length,String):[],length=result.length;for(var key in value)(inherited||hasOwnProperty.call(value,key))&&!(skipIndexes&&(key=="length"||isBuff&&(key=="offset"||key=="parent")||isType&&(key=="buffer"||key=="byteLength"||key=="byteOffset")||isIndex(key,length)))&&result.push(key);return result}module2.exports=arrayLikeKeys}});var require_isPrototype=__commonJS({"node_modules/lodash/_isPrototype.js"(exports2,module2){var objectProto=Object.prototype;function isPrototype(value){var Ctor=value&&value.constructor,proto=typeof Ctor=="function"&&Ctor.prototype||objectProto;return value===proto}module2.exports=isPrototype}});var require_overArg=__commonJS({"node_modules/lodash/_overArg.js"(exports2,module2){function overArg(func,transform){return function(arg){return func(transform(arg))}}module2.exports=overArg}});var require_nativeKeys=__commonJS({"node_modules/lodash/_nativeKeys.js"(exports2,module2){var overArg=require_overArg(),nativeKeys=overArg(Object.keys,Object);module2.exports=nativeKeys}});var require_baseKeys=__commonJS({"node_modules/lodash/_baseKeys.js"(exports2,module2){var isPrototype=require_isPrototype(),nativeKeys=require_nativeKeys(),objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty;function baseKeys(object){if(!isPrototype(object))return nativeKeys(object);var result=[];for(var key in Object(object))hasOwnProperty.call(object,key)&&key!="constructor"&&result.push(key);return result}module2.exports=baseKeys}});var require_isArrayLike=__commonJS({"node_modules/lodash/isArrayLike.js"(exports2,module2){var isFunction=require_isFunction(),isLength=require_isLength();function isArrayLike(value){return value!=null&&isLength(value.length)&&!isFunction(value)}module2.exports=isArrayLike}});var require_keys=__commonJS({"node_modules/lodash/keys.js"(exports2,module2){var arrayLikeKeys=require_arrayLikeKeys(),baseKeys=require_baseKeys(),isArrayLike=require_isArrayLike();function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}module2.exports=keys}});var require_getAllKeys=__commonJS({"node_modules/lodash/_getAllKeys.js"(exports2,module2){var baseGetAllKeys=require_baseGetAllKeys(),getSymbols=require_getSymbols(),keys=require_keys();function getAllKeys(object){return baseGetAllKeys(object,keys,getSymbols)}module2.exports=getAllKeys}});var require_equalObjects=__commonJS({"node_modules/lodash/_equalObjects.js"(exports2,module2){var getAllKeys=require_getAllKeys(),COMPARE_PARTIAL_FLAG=1,objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty;function equalObjects(object,other,bitmask,customizer,equalFunc,stack){var isPartial=bitmask&COMPARE_PARTIAL_FLAG,objProps=getAllKeys(object),objLength=objProps.length,othProps=getAllKeys(other),othLength=othProps.length;if(objLength!=othLength&&!isPartial)return!1;for(var index=objLength;index--;){var key=objProps[index];if(!(isPartial?key in other:hasOwnProperty.call(other,key)))return!1}var objStacked=stack.get(object),othStacked=stack.get(other);if(objStacked&&othStacked)return objStacked==other&&othStacked==object;var result=!0;stack.set(object,other),stack.set(other,object);for(var skipCtor=isPartial;++index<objLength;){key=objProps[index];var objValue=object[key],othValue=other[key];if(customizer)var compared=isPartial?customizer(othValue,objValue,key,other,object,stack):customizer(objValue,othValue,key,object,other,stack);if(!(compared===void 0?objValue===othValue||equalFunc(objValue,othValue,bitmask,customizer,stack):compared)){result=!1;break}skipCtor||(skipCtor=key=="constructor")}if(result&&!skipCtor){var objCtor=object.constructor,othCtor=other.constructor;objCtor!=othCtor&&"constructor"in object&&"constructor"in other&&!(typeof objCtor=="function"&&objCtor instanceof objCtor&&typeof othCtor=="function"&&othCtor instanceof othCtor)&&(result=!1)}return stack.delete(object),stack.delete(other),result}module2.exports=equalObjects}});var require_DataView=__commonJS({"node_modules/lodash/_DataView.js"(exports2,module2){var getNative=require_getNative(),root=require_root(),DataView2=getNative(root,"DataView");module2.exports=DataView2}});var require_Promise=__commonJS({"node_modules/lodash/_Promise.js"(exports2,module2){var getNative=require_getNative(),root=require_root(),Promise2=getNative(root,"Promise");module2.exports=Promise2}});var require_Set=__commonJS({"node_modules/lodash/_Set.js"(exports2,module2){var getNative=require_getNative(),root=require_root(),Set2=getNative(root,"Set");module2.exports=Set2}});var require_WeakMap=__commonJS({"node_modules/lodash/_WeakMap.js"(exports2,module2){var getNative=require_getNative(),root=require_root(),WeakMap2=getNative(root,"WeakMap");module2.exports=WeakMap2}});var require_getTag=__commonJS({"node_modules/lodash/_getTag.js"(exports2,module2){var DataView2=require_DataView(),Map2=require_Map(),Promise2=require_Promise(),Set2=require_Set(),WeakMap2=require_WeakMap(),baseGetTag=require_baseGetTag(),toSource=require_toSource(),mapTag="[object Map]",objectTag="[object Object]",promiseTag="[object Promise]",setTag="[object Set]",weakMapTag="[object WeakMap]",dataViewTag="[object DataView]",dataViewCtorString=toSource(DataView2),mapCtorString=toSource(Map2),promiseCtorString=toSource(Promise2),setCtorString=toSource(Set2),weakMapCtorString=toSource(WeakMap2),getTag=baseGetTag;(DataView2&&getTag(new DataView2(new ArrayBuffer(1)))!=dataViewTag||Map2&&getTag(new Map2)!=mapTag||Promise2&&getTag(Promise2.resolve())!=promiseTag||Set2&&getTag(new Set2)!=setTag||WeakMap2&&getTag(new WeakMap2)!=weakMapTag)&&(getTag=function(value){var result=baseGetTag(value),Ctor=result==objectTag?value.constructor:void 0,ctorString=Ctor?toSource(Ctor):"";if(ctorString)switch(ctorString){case dataViewCtorString:return dataViewTag;case mapCtorString:return mapTag;case promiseCtorString:return promiseTag;case setCtorString:return setTag;case weakMapCtorString:return weakMapTag}return result});module2.exports=getTag}});var require_baseIsEqualDeep=__commonJS({"node_modules/lodash/_baseIsEqualDeep.js"(exports2,module2){var Stack=require_Stack(),equalArrays=require_equalArrays(),equalByTag=require_equalByTag(),equalObjects=require_equalObjects(),getTag=require_getTag(),isArray=require_isArray(),isBuffer=require_isBuffer(),isTypedArray=require_isTypedArray(),COMPARE_PARTIAL_FLAG=1,argsTag="[object Arguments]",arrayTag="[object Array]",objectTag="[object Object]",objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty;function baseIsEqualDeep(object,other,bitmask,customizer,equalFunc,stack){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=objIsArr?arrayTag:getTag(object),othTag=othIsArr?arrayTag:getTag(other);objTag=objTag==argsTag?objectTag:objTag,othTag=othTag==argsTag?objectTag:othTag;var objIsObj=objTag==objectTag,othIsObj=othTag==objectTag,isSameTag=objTag==othTag;if(isSameTag&&isBuffer(object)){if(!isBuffer(other))return!1;objIsArr=!0,objIsObj=!1}if(isSameTag&&!objIsObj)return stack||(stack=new Stack),objIsArr||isTypedArray(object)?equalArrays(object,other,bitmask,customizer,equalFunc,stack):equalByTag(object,other,objTag,bitmask,customizer,equalFunc,stack);if(!(bitmask&COMPARE_PARTIAL_FLAG)){var objIsWrapped=objIsObj&&hasOwnProperty.call(object,"__wrapped__"),othIsWrapped=othIsObj&&hasOwnProperty.call(other,"__wrapped__");if(objIsWrapped||othIsWrapped){var objUnwrapped=objIsWrapped?object.value():object,othUnwrapped=othIsWrapped?other.value():other;return stack||(stack=new Stack),equalFunc(objUnwrapped,othUnwrapped,bitmask,customizer,stack)}}return isSameTag?(stack||(stack=new Stack),equalObjects(object,other,bitmask,customizer,equalFunc,stack)):!1}module2.exports=baseIsEqualDeep}});var require_baseIsEqual=__commonJS({"node_modules/lodash/_baseIsEqual.js"(exports2,module2){var baseIsEqualDeep=require_baseIsEqualDeep(),isObjectLike=require_isObjectLike();function baseIsEqual(value,other,bitmask,customizer,stack){return value===other?!0:value==null||other==null||!isObjectLike(value)&&!isObjectLike(other)?value!==value&&other!==other:baseIsEqualDeep(value,other,bitmask,customizer,baseIsEqual,stack)}module2.exports=baseIsEqual}});var require_isEqual=__commonJS({"node_modules/lodash/isEqual.js"(exports2,module2){var baseIsEqual=require_baseIsEqual();function isEqual(value,other){return baseIsEqual(value,other)}module2.exports=isEqual}});var require_manageMockFiles=__commonJS({"src/lib/manageMockFiles.js"(exports2,module2){var fsa=require_lib(),fs=require("fs"),path=require("path"),isEqual=require_isEqual(),colors=require_safe(),{getFileLatestContent,SupportMethods,filePath2ApiUrl,logger,getDataType,getLogger,writeStream}=require_utils3(),log=logger(process.env.SILENT),processArgv=process.env.ARGV?JSON.parse(process.env.ARGV):{},methodRegExp=new RegExp(`(${SupportMethods.join("|")}) +(.*)`,"i"),normalizeApiPath=apiUrl=>path.posix.normalize(String(apiUrl||"").trim()).replace(/\/+$/,"")||"/",logFile=(isWriteLogFile=!1,mockDir)=>isWriteLogFile?getLogger(mockDir):{log:function(){},error:function(){}},genMockFiles=async function({url:apiUrl,method,data:resJsonData,dir:mockDir}){let type=getDataType(resJsonData);if(!apiUrl||!method||!resJsonData||!mockDir){log.info(colors.red([`\u53C2\u6570: apiUrl: ${apiUrl}, method: ${method}, mockDir: ${mockDir} `,"\u5FC5\u987B\u662F\u6709\u6548\u503C"].join(",")));return}else if(!["object","array"].includes(type)||type==="object"&&Object.keys(resJsonData).length===0||type==="array"&&resJsonData.length===0){log.info(`\u53C2\u6570: apiUrl: ${apiUrl}, method: ${method}, resJsonData:`,resJsonData,colors.red("\uFF0C \u53C2\u6570\u5B57\u6BB5resJsonData\u5FC5\u987B\u662F\u975E\u7A7A\u7684\u6570\u7EC4\u6216\u5BF9\u8C61\uFF01"));return}apiUrl=apiUrl.trim().split("?")[0];let LOGGER=logFile(processArgv.t||processArgv.track,mockDir),normalizeApiUrl=filePath2ApiUrl(normalizeApiPath(apiUrl)),mockListFilePath=path.resolve(process.cwd(),`${mockDir}/mock-list.json`),mockFilePath=path.resolve(process.cwd(),`${mockDir}/${encodeURIComponent(normalizeApiPath(apiUrl))}.json`),newMockListContent={};fsa.pathExistsSync(mockListFilePath)?newMockListContent=getFileLatestContent(mockListFilePath):fsa.ensureFileSync(mockListFilePath);let isChange=!1;if(newMockListContent.hasOwnProperty(normalizeApiUrl)?newMockListContent[normalizeApiUrl].includes(method)||(newMockListContent[normalizeApiUrl].push(method),isChange=!0):(newMockListContent[normalizeApiUrl]=[method],isChange=!0),isChange&&Object.keys(newMockListContent).length>0&&fs.writeFileSync(mockListFilePath,JSON.stringify(newMockListContent,null,2)),fsa.pathExistsSync(mockFilePath)){let mockFileContent=getFileLatestContent(mockFilePath);if(mockFileContent.hasOwnProperty(method)&&isEqual(mockFileContent[method],resJsonData))return;mockFileContent[method]=resJsonData;try{await writeStream(mockFilePath,JSON.stringify(mockFileContent,null,2))}catch{LOGGER.error(`Update file: ${method} ${apiUrl} ${mockFilePath}`)}LOGGER.log(`Update file: ${method} ${apiUrl} ${mockFilePath}`)}else{try{await writeStream(mockFilePath,JSON.stringify({[method]:resJsonData},null,2))}catch{LOGGER.error(`New file: ${method} ${apiUrl} ${mockFilePath}`)}LOGGER.log(`New file: ${method} ${apiUrl} ${mockFilePath}`)}},collectMockDataFromJsFile=function(mockDataMap,filePath){let fileObject=getFileLatestContent(filePath);Object.keys(fileObject).forEach(item=>{let reqMethod="get",reqUrl=item;if(methodRegExp.exec(item)){let[,method,url]=methodRegExp.exec(item);reqMethod=method.toLowerCase(),reqUrl=normalizeApiPath(url)}typeof fileObject[item]=="function"?mockDataMap[`${reqMethod} ${reqUrl}`]=String(fileObject[item]):typeof fileObject[item]=="object"&&(mockDataMap[`${reqMethod} ${reqUrl}`]=fileObject[item])})},deepCollectMockData=function(mockDataMap,specialDir="../mock"){let files=fs.readdirSync(path.resolve(process.cwd(),specialDir),{withFileTypes:!0}),curFilesSize=files.length;for(let index=0;index<curFilesSize;index++){let el=files[index],filePath=path.normalize(`${specialDir}/${el.name}`);if(el.isFile()||deepCollectMockData(mockDataMap,filePath),el.name.endsWith(".json")&&el.name!=="mock-list.json"){let fileObject=getFileLatestContent(filePath);Object.keys(fileObject).forEach(method=>{mockDataMap[`${method.toLocaleLowerCase()} ${normalizeApiPath(decodeURIComponent(el.name).split(".json")[0])}`]=fileObject[method]});continue}el.name.endsWith(".js")&&collectMockDataFromJsFile(mockDataMap,filePath)}},getMockStatFromDir=dirPath=>{if(!fsa.pathExistsSync(dirPath)){getLogger(path.resolve(process.cwd())).error(`\u5165\u53C2\u65E0\u6548\uFF0C${dirPath} \u76EE\u5F55\u4E0D\u5B58\u5728`);return}let mockDataMap={};deepCollectMockData(mockDataMap,dirPath);let mockListFilePath=path.resolve(process.cwd(),`${dirPath}/mock-list.json`);if(Object.keys(mockDataMap).length>0&&!fsa.pathExistsSync(mockListFilePath)){fsa.ensureFileSync(mockListFilePath);let reverseMockList={};Object.keys(mockDataMap).forEach(it=>{if(methodRegExp.exec(it)){let[,method,url]=methodRegExp.exec(it),normalizedUrl=normalizeApiPath(url);normalizedUrl.trim()&&method.trim()&&(reverseMockList.hasOwnProperty(normalizedUrl)?reverseMockList[normalizedUrl].push(method):reverseMockList[normalizedUrl]=[method])}}),writeStream(mockListFilePath,JSON.stringify(reverseMockList,null,2))}return mockDataMap},getMockStatFromFile=filePath=>{if(!fsa.pathExistsSync(filePath)){getLogger(path.resolve(process.cwd())).error(`\u5165\u53C2\u65E0\u6548\uFF0C${filePath} \u6587\u4EF6\u4E0D\u5B58\u5728`);return}let mockDataMap={};return collectMockDataFromJsFile(mockDataMap,filePath),mockDataMap},hasMockApi=function(mockDataMap,apiUrl,method){if(!apiUrl||!method||!mockDataMap||!(mockDataMap instanceof Object)){getLogger(path.resolve(process.cwd())).error(`\u5165\u53C2\u65E0\u6548\uFF0C${mockDataMap} \u5FC5\u987B\u662F mock\u6570\u636E\u7684Object\u5BF9\u8C61`);return}return mockDataMap.hasOwnProperty(`${method.toLocaleLowerCase()} ${normalizeApiPath(apiUrl)}`)};module2.exports={genMockFiles,getMockStatFromDir,getMockStatFromFile,hasMockApi}}});var require_asyncTaskQueue=__commonJS({"src/lib/asyncTaskQueue.js"(exports2,module2){var AsyncTaskQueue=class{constructor(isSaveItem=!1){this.list=[],this.index=0,this.isStop=!1,this.isParallel=!1,this.isSaveItem=isSaveItem}next(){if(this.index>=this.list.length-1||this.isStop)return;this.isSaveItem||this.list.splice(this.index,1,"");let cur=this.list[++this.index];cur(this.next.bind(this))}add(...fn){this.list.push(...fn)}run(){let cur=this.list[this.index];typeof cur=="function"&&cur(this.next.bind(this))}parallelRun(){this.isParallel=!0;for(let fn of this.list)fn(this.next.bind(this))}stop(){this.isStop=!0}retry(){this.isStop=!1,this.run()}goOn(){this.isStop=!1,this.next()}};module2.exports=AsyncTaskQueue}});var require_mockServer=__commonJS({"src/lib/mockServer.js"(exports2,module2){var express=require_express2(),{readdirSync,existsSync}=require("fs"),path=require("path"),colors=require_safe(),portfinder=require_portfinder(),{exec}=require("child_process"),{createProxyMiddleware}=require_dist(),{Server}=require_dist3(),{dateFormat,logger,SupportMethods,DefaultHeaders,getFileLatestContent,filePath2ApiUrl,isEmptyObj,getServerHost,getServerUrls,hostAllowlistMiddleware,getHostAllowlist,isAddressAllowed}=require_utils3(),{getPackageVersion}=require_packageInfo(),{genMockFiles,getMockStatFromDir,getMockStatFromFile}=require_manageMockFiles(),registeredApis=[],methodRegExp=new RegExp(`((${SupportMethods.join("|")}) +)?([^?]*)`,"i"),app=express(),log=logger(process.env.SILENT),argv=JSON.parse(process.env.ARGV),socketServer=null,httpServer=null,webServer=null,shuttingDown=!1,corsOrigin=[],corsHeaders="",httpsRE=/^https:\/\//,count=0,fileCount=0,mockDirStat={},mockFileStat={},includesWebServe=process.env.STATIC_DIRECTORY||process.env.WEB_ROOT,mockFileOrDir=process.env.SPECIFIED_FILE||process.env.SPECIFIED_DIR;process.env.PORT?init():(portfinder.basePort=8090,portfinder.getPort(function(err,port){if(err)throw err;process.env.PORT=port,init()}));function init(){process.env.CORS_ORIGIN&&(process.env.CORS_ORIGIN.split(/\s*,\s*/).forEach(function(h){corsOrigin.push(h)},this),corsHeaders=DefaultHeaders),process.env.CORS_HEADERS&&process.env.CORS_HEADERS.split(/\s*,\s*/).forEach(function(h){corsHeaders+=corsHeaders?", "+h:h},this),app.use(hostAllowlistMiddleware()),app.use(crossDomain()),app.use(express.json()),app.get("/favicon-api-overview.svg",(req,res)=>{res.sendFile(path.resolve(__dirname,"./favicon-api-overview.svg"))}),app.get("/__api-overview",(req,res)=>{let htmlPath=path.resolve(__dirname,"./api-overview.html");existsSync(htmlPath)?res.sendFile(htmlPath):res.status(404).send("API overview page not found")}),app.get("/__api-data",(req,res)=>{let groupedApis={};registeredApis.forEach(api=>{let dirPath=path.dirname(api.file);groupedApis[dirPath]||(groupedApis[dirPath]=[]),groupedApis[dirPath].push(api)}),res.json({apis:registeredApis,groupedApis,port:process.env.PORT})});let requireMockServe=!0;process.env.SPECIFIED_FILE?composeRouteFromJsFile(process.env.SPECIFIED_FILE):includesWebServe&&!existsSync(path.resolve(process.cwd(),process.env.SPECIFIED_DIR))?requireMockServe=!1:parseMockFiles(process.env.SPECIFIED_DIR),requireMockServe&&argv.a&&log.info(colors.yellow(`${fileCount} mock file are parsed in total.`)),startServer()}function crossDomain(){return(req,res,next)=>{if(typeof argv.A=="string"){let resHeaders={};argv.A.split(/\s*,\s*/).forEach(function(h){let[key,value]=h.split("=");resHeaders[key]=value},this);for(let key in resHeaders)resHeaders.hasOwnProperty(key)&&res.header(key,resHeaders[key])}res.header("Access-Control-Allow-Credentials",!0),res.header("Access-Control-Allow-Origin",corsOrigin.includes(req.headers.origin)?req.headers.origin:"*"),res.header("Access-Control-Allow-Methods",SupportMethods.join(",")),res.header("Access-Control-Allow-Headers",corsHeaders||"*"),req.method==="OPTIONS"&&res.status(200),next()}}function composeRouteFromJsFile(file){let fileObject=getFileLatestContent(file);argv.a&&log.info(colors.green(`Mockfile ${++fileCount}: `),file,colors.yellow("all API URL is follows: ")),fileObject!=="getFileLatestContent_ERROR"&&Object.keys(fileObject).forEach(item=>{let reqMethod="get",reqUrl=item,[,,method,url]=methodRegExp.exec(item);method&&(reqMethod=method.toLowerCase()),reqUrl=url,argv.a&&log.info(colors.grey(`path ${String(++count).padStart(3," ")}: `),colors.cyan(reqMethod.padEnd(8," ")),colors.cyan(reqUrl),colors.grey(typeof fileObject[item])),log.assert(typeof app[reqMethod]=="function",colors.red(`${file}, ${reqMethod}`)),typeof fileObject[item]=="function"?app[reqMethod](reqUrl,fileObject[item]):typeof fileObject[item]=="object"&&app[reqMethod](reqUrl,function(req,res){res.json(fileObject[item])}),registeredApis.push({method:reqMethod.toUpperCase(),url:reqUrl,file,data:fileObject[item]})})}function parseMockFiles(specialDir="../mock"){let files=readdirSync(path.resolve(process.cwd(),specialDir),{withFileTypes:!0}),curFilesSize=files.length;for(let index=0;index<curFilesSize;index++){let el=files[index],filePath=path.normalize(`${specialDir}/${el.name}`);if(el.isFile()||parseMockFiles(filePath),el.name.endsWith(".json")&&el.name!=="mock-list.json"){argv.a&&log.info(colors.green(`Mockfile ${++fileCount}: `),filePath,colors.yellow("all API URL is follows: "));let fileObject=getFileLatestContent(filePath);if(fileObject==="getFileLatestContent_ERROR")continue;Object.keys(fileObject).forEach(method=>{let apiUrl=filePath2ApiUrl(decodeURIComponent(el.name.split(".")[0]));argv.a&&log.info(colors.grey(`path ${String(++count).padStart(3," ")}: `),colors.cyan(method.padEnd(8," ")),colors.cyan(apiUrl),colors.grey(typeof fileObject[method])),log.assert(typeof app[method]=="function",colors.red(`${filePath}, ${method}`)),app[method](apiUrl,function(req,res){res.json(fileObject[method])}),registeredApis.push({method:method.toUpperCase(),url:apiUrl,file:filePath,data:fileObject[method]})});continue}!el.name.endsWith(".js")&&!el.name.endsWith(".cjs")||composeRouteFromJsFile(filePath)}}function startServer(){let webApp=null,webPublicPath="/",proxyTable={};if(process.env.WEB_ROOT){if(webApp=express(),webApp.use(hostAllowlistMiddleware()),process.env.PROXY_OPTIONS)try{let options=JSON.parse(process.env.PROXY_OPTIONS);Object.keys(options).forEach(function(prefix){proxyTable[prefix]=options[prefix];let opts={target:options[prefix],changeOrigin:!0,ws:!0};httpsRE.test(options[prefix])&&(opts.secure=!1),process.env.PREFIX_REWRITE&&(opts.pathRewrite=path2=>path2.replace(new RegExp(`^${prefix}`),"")),webApp.use(prefix,createProxyMiddleware(opts))},this)}catch(error){console.warn(colors.yellow(`
115
+ `+message)}function abortHandshakeOrEmitwsClientError(server,req,socket,code,message){if(server.listenerCount("wsClientError")){let err=new Error(message);Error.captureStackTrace(err,abortHandshakeOrEmitwsClientError),server.emit("wsClientError",err,socket,req)}else abortHandshake(socket,code,message)}}});var require_ws2=__commonJS({"node_modules/socket.io-adapter/node_modules/ws/index.js"(exports2,module2){"use strict";var WebSocket=require_websocket4();WebSocket.createWebSocketStream=require_stream2();WebSocket.Server=require_websocket_server2();WebSocket.Receiver=require_receiver2();WebSocket.Sender=require_sender2();WebSocket.WebSocket=WebSocket;WebSocket.WebSocketServer=WebSocket.Server;module2.exports=WebSocket}});var require_dist2=__commonJS({"node_modules/socket.io-adapter/dist/index.js"(exports2){"use strict";var _a;Object.defineProperty(exports2,"__esModule",{value:!0});exports2.SessionAwareAdapter=exports2.Adapter=void 0;var events_1=require("events"),yeast_1=require_yeast(),WebSocket=require_ws2(),canPreComputeFrame=typeof((_a=WebSocket?.Sender)===null||_a===void 0?void 0:_a.frame)=="function",Adapter=class extends events_1.EventEmitter{constructor(nsp){super(),this.nsp=nsp,this.rooms=new Map,this.sids=new Map,this.encoder=nsp.server.encoder}init(){}close(){}serverCount(){return Promise.resolve(1)}addAll(id,rooms){this.sids.has(id)||this.sids.set(id,new Set);for(let room of rooms)this.sids.get(id).add(room),this.rooms.has(room)||(this.rooms.set(room,new Set),this.emit("create-room",room)),this.rooms.get(room).has(id)||(this.rooms.get(room).add(id),this.emit("join-room",room,id))}del(id,room){this.sids.has(id)&&this.sids.get(id).delete(room),this._del(room,id)}_del(room,id){let _room=this.rooms.get(room);_room!=null&&(_room.delete(id)&&this.emit("leave-room",room,id),_room.size===0&&this.rooms.delete(room)&&this.emit("delete-room",room))}delAll(id){if(this.sids.has(id)){for(let room of this.sids.get(id))this._del(room,id);this.sids.delete(id)}}broadcast(packet,opts){let flags=opts.flags||{},packetOpts={preEncoded:!0,volatile:flags.volatile,compress:flags.compress};packet.nsp=this.nsp.name;let encodedPackets=this._encode(packet,packetOpts);this.apply(opts,socket=>{typeof socket.notifyOutgoingListeners=="function"&&socket.notifyOutgoingListeners(packet),socket.client.writeToEngine(encodedPackets,packetOpts)})}broadcastWithAck(packet,opts,clientCountCallback,ack){let flags=opts.flags||{},packetOpts={preEncoded:!0,volatile:flags.volatile,compress:flags.compress};packet.nsp=this.nsp.name,packet.id=this.nsp._ids++;let encodedPackets=this._encode(packet,packetOpts),clientCount=0;this.apply(opts,socket=>{clientCount++,socket.acks.set(packet.id,ack),typeof socket.notifyOutgoingListeners=="function"&&socket.notifyOutgoingListeners(packet),socket.client.writeToEngine(encodedPackets,packetOpts)}),clientCountCallback(clientCount)}_encode(packet,packetOpts){let encodedPackets=this.encoder.encode(packet);if(canPreComputeFrame&&encodedPackets.length===1&&typeof encodedPackets[0]=="string"){let data=Buffer.from("4"+encodedPackets[0]);packetOpts.wsPreEncodedFrame=WebSocket.Sender.frame(data,{readOnly:!1,mask:!1,rsv1:!1,opcode:1,fin:!0})}return encodedPackets}sockets(rooms){let sids=new Set;return this.apply({rooms},socket=>{sids.add(socket.id)}),Promise.resolve(sids)}socketRooms(id){return this.sids.get(id)}fetchSockets(opts){let sockets=[];return this.apply(opts,socket=>{sockets.push(socket)}),Promise.resolve(sockets)}addSockets(opts,rooms){this.apply(opts,socket=>{socket.join(rooms)})}delSockets(opts,rooms){this.apply(opts,socket=>{rooms.forEach(room=>socket.leave(room))})}disconnectSockets(opts,close){this.apply(opts,socket=>{socket.disconnect(close)})}apply(opts,callback){let rooms=opts.rooms,except=this.computeExceptSids(opts.except);if(rooms.size){let ids=new Set;for(let room of rooms)if(this.rooms.has(room))for(let id of this.rooms.get(room)){if(ids.has(id)||except.has(id))continue;let socket=this.nsp.sockets.get(id);socket&&(callback(socket),ids.add(id))}}else for(let[id]of this.sids){if(except.has(id))continue;let socket=this.nsp.sockets.get(id);socket&&callback(socket)}}computeExceptSids(exceptRooms){let exceptSids=new Set;if(exceptRooms&&exceptRooms.size>0)for(let room of exceptRooms)this.rooms.has(room)&&this.rooms.get(room).forEach(sid=>exceptSids.add(sid));return exceptSids}serverSideEmit(packet){console.warn("this adapter does not support the serverSideEmit() functionality")}persistSession(session){}restoreSession(pid,offset){return null}};exports2.Adapter=Adapter;var SessionAwareAdapter=class extends Adapter{constructor(nsp){super(nsp),this.nsp=nsp,this.sessions=new Map,this.packets=[],this.maxDisconnectionDuration=nsp.server.opts.connectionStateRecovery.maxDisconnectionDuration,setInterval(()=>{let threshold=Date.now()-this.maxDisconnectionDuration;this.sessions.forEach((session,sessionId)=>{session.disconnectedAt<threshold&&this.sessions.delete(sessionId)});for(let i=this.packets.length-1;i>=0;i--)if(this.packets[i].emittedAt<threshold){this.packets.splice(0,i+1);break}},60*1e3).unref()}persistSession(session){session.disconnectedAt=Date.now(),this.sessions.set(session.pid,session)}restoreSession(pid,offset){let session=this.sessions.get(pid);if(!session)return null;if(session.disconnectedAt+this.maxDisconnectionDuration<Date.now())return this.sessions.delete(pid),null;let index=this.packets.findIndex(packet=>packet.id===offset);if(index===-1)return null;let missedPackets=[];for(let i=index+1;i<this.packets.length;i++){let packet=this.packets[i];shouldIncludePacket(session.rooms,packet.opts)&&missedPackets.push(packet.data)}return Promise.resolve(Object.assign(Object.assign({},session),{missedPackets}))}broadcast(packet,opts){var _a2;let isEventPacket=packet.type===2,withoutAcknowledgement=packet.id===void 0,notVolatile=((_a2=opts.flags)===null||_a2===void 0?void 0:_a2.volatile)===void 0;if(isEventPacket&&withoutAcknowledgement&&notVolatile){let id=(0,yeast_1.yeast)();packet.data.push(id),this.packets.push({id,opts,data:packet.data,emittedAt:Date.now()})}super.broadcast(packet,opts)}};exports2.SessionAwareAdapter=SessionAwareAdapter;function shouldIncludePacket(sessionRooms,opts){let included=opts.rooms.size===0||sessionRooms.some(room=>opts.rooms.has(room)),notExcluded=sessionRooms.every(room=>!opts.except.has(room));return included&&notExcluded}}});var require_parent_namespace=__commonJS({"node_modules/socket.io/dist/parent-namespace.js"(exports2){"use strict";var __importDefault=exports2&&exports2.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports2,"__esModule",{value:!0});exports2.ParentNamespace=void 0;var namespace_1=require_namespace(),socket_io_adapter_1=require_dist2(),debug_1=__importDefault(require_src8()),debug=(0,debug_1.default)("socket.io:parent-namespace"),ParentNamespace=class _ParentNamespace extends namespace_1.Namespace{constructor(server){super(server,"/_"+_ParentNamespace.count++),this.children=new Set}_initAdapter(){this.adapter=new ParentBroadcastAdapter(this)}emit(ev,...args){return this.children.forEach(nsp=>{nsp.emit(ev,...args)}),!0}createChild(name){debug("creating child namespace %s",name);let namespace=new namespace_1.Namespace(this.server,name);if(this._fns.forEach(fn=>namespace.use(fn)),this.listeners("connect").forEach(listener=>namespace.on("connect",listener)),this.listeners("connection").forEach(listener=>namespace.on("connection",listener)),this.children.add(namespace),this.server._opts.cleanupEmptyChildNamespaces){let remove=namespace._remove;namespace._remove=socket=>{remove.call(namespace,socket),namespace.sockets.size===0&&(debug("closing child namespace %s",name),namespace.adapter.close(),this.server._nsps.delete(namespace.name),this.children.delete(namespace))}}return this.server._nsps.set(name,namespace),this.server.sockets.emitReserved("new_namespace",namespace),namespace}fetchSockets(){throw new Error("fetchSockets() is not supported on parent namespaces")}};exports2.ParentNamespace=ParentNamespace;ParentNamespace.count=0;var ParentBroadcastAdapter=class extends socket_io_adapter_1.Adapter{broadcast(packet,opts){this.nsp.children.forEach(nsp=>{nsp.adapter.broadcast(packet,opts)})}}}});var require_uws=__commonJS({"node_modules/socket.io/dist/uws.js"(exports2){"use strict";var __importDefault=exports2&&exports2.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports2,"__esModule",{value:!0});exports2.patchAdapter=patchAdapter;exports2.restoreAdapter=restoreAdapter;exports2.serveFile=serveFile;var socket_io_adapter_1=require_dist2(),fs_1=require("fs"),debug_1=__importDefault(require_src8()),debug=(0,debug_1.default)("socket.io:adapter-uws"),SEPARATOR="",{addAll,del,broadcast}=socket_io_adapter_1.Adapter.prototype;function patchAdapter(app){socket_io_adapter_1.Adapter.prototype.addAll=function(id,rooms){let isNew=!this.sids.has(id);addAll.call(this,id,rooms);let socket=this.nsp.sockets.get(id)||this.nsp._preConnectSockets.get(id);if(socket){if(socket.conn.transport.name==="websocket"){subscribe(this.nsp.name,socket,isNew,rooms);return}isNew&&socket.conn.on("upgrade",()=>{let rooms2=this.sids.get(id);rooms2&&subscribe(this.nsp.name,socket,isNew,rooms2)})}},socket_io_adapter_1.Adapter.prototype.del=function(id,room){del.call(this,id,room);let socket=this.nsp.sockets.get(id)||this.nsp._preConnectSockets.get(id);if(socket&&socket.conn.transport.name==="websocket"){let sessionId=socket.conn.id,websocket=socket.conn.transport.socket,topic=`${this.nsp.name}${SEPARATOR}${room}`;debug("unsubscribe connection %s from topic %s",sessionId,topic),websocket.unsubscribe(topic)}},socket_io_adapter_1.Adapter.prototype.broadcast=function(packet,opts){if(!(opts.rooms.size<=1&&opts.except.size===0)){broadcast.call(this,packet,opts);return}let flags=opts.flags||{},basePacketOpts={preEncoded:!0,volatile:flags.volatile,compress:flags.compress};packet.nsp=this.nsp.name;let encodedPackets=this.encoder.encode(packet),topic=opts.rooms.size===0?this.nsp.name:`${this.nsp.name}${SEPARATOR}${opts.rooms.keys().next().value}`;debug("fast publish to %s",topic),encodedPackets.forEach(encodedPacket=>{let isBinary=typeof encodedPacket!="string";app.publish(topic,isBinary?encodedPacket:"4"+encodedPacket,isBinary)}),this.apply(opts,socket=>{socket.conn.transport.name!=="websocket"&&socket.client.writeToEngine(encodedPackets,basePacketOpts)})}}function subscribe(namespaceName,socket,isNew,rooms){let sessionId=socket.conn.id,websocket=socket.conn.transport.socket;isNew&&(debug("subscribe connection %s to topic %s",sessionId,namespaceName),websocket.subscribe(namespaceName)),rooms.forEach(room=>{let topic=`${namespaceName}${SEPARATOR}${room}`;debug("subscribe connection %s to topic %s",sessionId,topic),websocket.subscribe(topic)})}function restoreAdapter(){socket_io_adapter_1.Adapter.prototype.addAll=addAll,socket_io_adapter_1.Adapter.prototype.del=del,socket_io_adapter_1.Adapter.prototype.broadcast=broadcast}var toArrayBuffer=buffer=>{let{buffer:arrayBuffer,byteOffset,byteLength}=buffer;return arrayBuffer.slice(byteOffset,byteOffset+byteLength)};function serveFile(res,filepath){let{size}=(0,fs_1.statSync)(filepath),readStream=(0,fs_1.createReadStream)(filepath),destroyReadStream=()=>!readStream.destroyed&&readStream.destroy(),onError=error=>{throw destroyReadStream(),error},onDataChunk=chunk=>{let arrayBufferChunk=toArrayBuffer(chunk);res.cork(()=>{let lastOffset=res.getWriteOffset(),[ok,done]=res.tryEnd(arrayBufferChunk,size);!done&&!ok&&(readStream.pause(),res.onWritable(offset=>{let[ok2,done2]=res.tryEnd(arrayBufferChunk.slice(offset-lastOffset),size);return!done2&&ok2&&readStream.resume(),ok2}))})};res.onAborted(destroyReadStream),readStream.on("data",onDataChunk).on("error",onError).on("end",destroyReadStream)}}});var require_package=__commonJS({"node_modules/socket.io/package.json"(exports2,module2){module2.exports={name:"socket.io",version:"4.8.3",description:"node.js realtime framework server",keywords:["realtime","framework","websocket","tcp","events","socket","io"],files:["dist/","client-dist/","wrapper.mjs","!**/*.tsbuildinfo"],directories:{doc:"docs/",example:"example/",lib:"lib/",test:"test/"},type:"commonjs",main:"./dist/index.js",exports:{".":{types:"./dist/index.d.ts",import:"./wrapper.mjs",require:"./dist/index.js"},"./package.json":"./package.json"},types:"./dist/index.d.ts",license:"MIT",homepage:"https://github.com/socketio/socket.io/tree/main/packages/socket.io#readme",repository:{type:"git",url:"git+https://github.com/socketio/socket.io.git"},bugs:{url:"https://github.com/socketio/socket.io/issues"},scripts:{compile:"rimraf ./dist && tsc",test:"npm run format:check && npm run compile && npm run test:types && npm run test:unit","test:types":"tsd","test:unit":"nyc mocha --import=tsx --reporter spec --slow 200 --bail --timeout 10000 test/index.ts","format:check":'prettier --check "lib/**/*.ts" "test/**/*.ts"',"format:fix":'prettier --write "lib/**/*.ts" "test/**/*.ts"',prepack:"npm run compile"},dependencies:{accepts:"~1.3.4",base64id:"~2.0.0",cors:"~2.8.5",debug:"~4.4.1","engine.io":"~6.6.0","socket.io-adapter":"~2.5.2","socket.io-parser":"~4.2.4"},contributors:[{name:"Guillermo Rauch",email:"rauchg@gmail.com"},{name:"Arnout Kazemier",email:"info@3rd-eden.com"},{name:"Vladimir Dronnikov",email:"dronnikov@gmail.com"},{name:"Einar Otto Stangvik",email:"einaros@gmail.com"}],engines:{node:">=10.2.0"},tsd:{directory:"test"}}}});var require_dist3=__commonJS({"node_modules/socket.io/dist/index.js"(exports2,module2){"use strict";var __createBinding=exports2&&exports2.__createBinding||(Object.create?(function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]})),__setModuleDefault=exports2&&exports2.__setModuleDefault||(Object.create?(function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}):function(o,v){o.default=v}),__importStar=exports2&&exports2.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)k!=="default"&&Object.prototype.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__importDefault=exports2&&exports2.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports2,"__esModule",{value:!0});exports2.Namespace=exports2.Socket=exports2.Server=void 0;var http_1=__importDefault(require("http")),fs_1=require("fs"),zlib_1=require("zlib"),accepts=require_accepts(),stream_1=require("stream"),path=require("path"),engine_io_1=require_engine_io(),client_1=require_client(),events_1=require("events"),namespace_1=require_namespace();Object.defineProperty(exports2,"Namespace",{enumerable:!0,get:function(){return namespace_1.Namespace}});var parent_namespace_1=require_parent_namespace(),socket_io_adapter_1=require_dist2(),parser=__importStar(require_cjs2()),debug_1=__importDefault(require_src8()),socket_1=require_socket2();Object.defineProperty(exports2,"Socket",{enumerable:!0,get:function(){return socket_1.Socket}});var typed_events_1=require_typed_events(),uws_1=require_uws(),cors_1=__importDefault(require_lib4()),debug=(0,debug_1.default)("socket.io:server"),clientVersion=require_package().version,dotMapRegex=/\.map/,Server=class _Server extends typed_events_1.StrictEventEmitter{constructor(srv,opts={}){super(),this._nsps=new Map,this.parentNsps=new Map,this.parentNamespacesFromRegExp=new Map,typeof srv=="object"&&srv instanceof Object&&!srv.listen&&(opts=srv,srv=void 0),this.path(opts.path||"/socket.io"),this.connectTimeout(opts.connectTimeout||45e3),this.serveClient(opts.serveClient!==!1),this._parser=opts.parser||parser,this.encoder=new this._parser.Encoder,this.opts=opts,opts.connectionStateRecovery?(opts.connectionStateRecovery=Object.assign({maxDisconnectionDuration:120*1e3,skipMiddlewares:!0},opts.connectionStateRecovery),this.adapter(opts.adapter||socket_io_adapter_1.SessionAwareAdapter)):this.adapter(opts.adapter||socket_io_adapter_1.Adapter),opts.cleanupEmptyChildNamespaces=!!opts.cleanupEmptyChildNamespaces,this.sockets=this.of("/"),(srv||typeof srv=="number")&&this.attach(srv),this.opts.cors&&(this._corsMiddleware=(0,cors_1.default)(this.opts.cors))}get _opts(){return this.opts}serveClient(v){return arguments.length?(this._serveClient=v,this):this._serveClient}_checkNamespace(name,auth,fn){if(this.parentNsps.size===0)return fn(!1);let keysIterator=this.parentNsps.keys(),run=()=>{let nextFn=keysIterator.next();if(nextFn.done)return fn(!1);nextFn.value(name,auth,(err,allow)=>{if(err||!allow)return run();if(this._nsps.has(name))return debug("dynamic namespace %s already exists",name),fn(this._nsps.get(name));let namespace=this.parentNsps.get(nextFn.value).createChild(name);debug("dynamic namespace %s was created",name),fn(namespace)})};run()}path(v){if(!arguments.length)return this._path;this._path=v.replace(/\/$/,"");let escapedPath=this._path.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&");return this.clientPathRegex=new RegExp("^"+escapedPath+"/socket\\.io(\\.msgpack|\\.esm)?(\\.min)?\\.js(\\.map)?(?:\\?|$)"),this}connectTimeout(v){return v===void 0?this._connectTimeout:(this._connectTimeout=v,this)}adapter(v){if(!arguments.length)return this._adapter;this._adapter=v;for(let nsp of this._nsps.values())nsp._initAdapter();return this}listen(srv,opts={}){return this.attach(srv,opts)}attach(srv,opts={}){if(typeof srv=="function"){let msg="You are trying to attach socket.io to an express request handler function. Please pass a http.Server instance.";throw new Error(msg)}if(Number(srv)==srv&&(srv=Number(srv)),typeof srv=="number"){debug("creating http server and binding to %d",srv);let port=srv;srv=http_1.default.createServer((req,res)=>{res.writeHead(404),res.end()}),srv.listen(port)}return Object.assign(opts,this.opts),opts.path=opts.path||this._path,this.initEngine(srv,opts),this}attachApp(app,opts={}){Object.assign(opts,this.opts),opts.path=opts.path||this._path,debug("creating uWebSockets.js-based engine with opts %j",opts);let engine=new engine_io_1.uServer(opts);engine.attach(app,opts),this.bind(engine),this._serveClient&&app.get(`${this._path}/*`,(res,req)=>{if(!this.clientPathRegex.test(req.getUrl())){req.setYield(!0);return}let filename=req.getUrl().replace(this._path,"").replace(/\?.*$/,"").replace(/^\//,""),isMap=dotMapRegex.test(filename),type=isMap?"map":"source",expectedEtag='"'+clientVersion+'"',weakEtag="W/"+expectedEtag,etag=req.getHeader("if-none-match");if(etag&&(expectedEtag===etag||weakEtag===etag)){debug("serve client %s 304",type),res.writeStatus("304 Not Modified"),res.end();return}debug("serve client %s",type),res.writeHeader("cache-control","public, max-age=0"),res.writeHeader("content-type","application/"+(isMap?"json":"javascript")+"; charset=utf-8"),res.writeHeader("etag",expectedEtag);let filepath=path.join(__dirname,"../client-dist/",filename);(0,uws_1.serveFile)(res,filepath)}),(0,uws_1.patchAdapter)(app)}initEngine(srv,opts){debug("creating engine.io instance with opts %j",opts),this.eio=(0,engine_io_1.attach)(srv,opts),this._serveClient&&this.attachServe(srv),this.httpServer=srv,this.bind(this.eio)}attachServe(srv){debug("attaching client serving req handler");let evs=srv.listeners("request").slice(0);srv.removeAllListeners("request"),srv.on("request",(req,res)=>{if(this.clientPathRegex.test(req.url))this._corsMiddleware?this._corsMiddleware(req,res,()=>{this.serve(req,res)}):this.serve(req,res);else for(let i=0;i<evs.length;i++)evs[i].call(srv,req,res)})}serve(req,res){let filename=req.url.replace(this._path,"").replace(/\?.*$/,""),isMap=dotMapRegex.test(filename),type=isMap?"map":"source",expectedEtag='"'+clientVersion+'"',weakEtag="W/"+expectedEtag,etag=req.headers["if-none-match"];if(etag&&(expectedEtag===etag||weakEtag===etag)){debug("serve client %s 304",type),res.writeHead(304),res.end();return}debug("serve client %s",type),res.setHeader("Cache-Control","public, max-age=0"),res.setHeader("Content-Type","application/"+(isMap?"json":"javascript")+"; charset=utf-8"),res.setHeader("ETag",expectedEtag),_Server.sendFile(filename,req,res)}static sendFile(filename,req,res){let readStream=(0,fs_1.createReadStream)(path.join(__dirname,"../client-dist/",filename)),encoding=accepts(req).encodings(["br","gzip","deflate"]),onError=err=>{err&&res.end()};switch(encoding){case"br":res.writeHead(200,{"content-encoding":"br"}),(0,stream_1.pipeline)(readStream,(0,zlib_1.createBrotliCompress)(),res,onError);break;case"gzip":res.writeHead(200,{"content-encoding":"gzip"}),(0,stream_1.pipeline)(readStream,(0,zlib_1.createGzip)(),res,onError);break;case"deflate":res.writeHead(200,{"content-encoding":"deflate"}),(0,stream_1.pipeline)(readStream,(0,zlib_1.createDeflate)(),res,onError);break;default:res.writeHead(200),(0,stream_1.pipeline)(readStream,res,onError)}}bind(engine){return this.engine=engine,this.engine.on("connection",this.onconnection.bind(this)),this}onconnection(conn){debug("incoming connection with id %s",conn.id);let client=new client_1.Client(this,conn);return conn.protocol===3&&client.connect("/"),this}of(name,fn){if(typeof name=="function"||name instanceof RegExp){let parentNsp=new parent_namespace_1.ParentNamespace(this);return debug("initializing parent namespace %s",parentNsp.name),typeof name=="function"?this.parentNsps.set(name,parentNsp):(this.parentNsps.set((nsp2,conn,next)=>next(null,name.test(nsp2)),parentNsp),this.parentNamespacesFromRegExp.set(name,parentNsp)),fn&&parentNsp.on("connect",fn),parentNsp}String(name)[0]!=="/"&&(name="/"+name);let nsp=this._nsps.get(name);if(!nsp){for(let[regex,parentNamespace]of this.parentNamespacesFromRegExp)if(regex.test(name))return debug("attaching namespace %s to parent namespace %s",name,regex),parentNamespace.createChild(name);debug("initializing namespace %s",name),nsp=new namespace_1.Namespace(this,name),this._nsps.set(name,nsp),name!=="/"&&this.sockets.emitReserved("new_namespace",nsp)}return fn&&nsp.on("connect",fn),nsp}async close(fn){if(await Promise.allSettled([...this._nsps.values()].map(async nsp=>{nsp.sockets.forEach(socket=>{socket._onclose("server shutting down")}),await nsp.adapter.close()})),this.engine.close(),(0,uws_1.restoreAdapter)(),this.httpServer)return new Promise(resolve=>{this.httpServer.close(err=>{fn&&fn(err),err&&debug("server was not running"),resolve()})});fn&&fn()}use(fn){return this.sockets.use(fn),this}to(room){return this.sockets.to(room)}in(room){return this.sockets.in(room)}except(room){return this.sockets.except(room)}send(...args){return this.sockets.emit("message",...args),this}write(...args){return this.sockets.emit("message",...args),this}serverSideEmit(ev,...args){return this.sockets.serverSideEmit(ev,...args)}serverSideEmitWithAck(ev,...args){return this.sockets.serverSideEmitWithAck(ev,...args)}allSockets(){return this.sockets.allSockets()}compress(compress){return this.sockets.compress(compress)}get volatile(){return this.sockets.volatile}get local(){return this.sockets.local}timeout(timeout){return this.sockets.timeout(timeout)}fetchSockets(){return this.sockets.fetchSockets()}socketsJoin(room){return this.sockets.socketsJoin(room)}socketsLeave(room){return this.sockets.socketsLeave(room)}disconnectSockets(close=!1){return this.sockets.disconnectSockets(close)}};exports2.Server=Server;var emitterMethods=Object.keys(events_1.EventEmitter.prototype).filter(function(key){return typeof events_1.EventEmitter.prototype[key]=="function"});emitterMethods.forEach(function(fn){Server.prototype[fn]=function(){return this.sockets[fn].apply(this.sockets,arguments)}});module2.exports=(srv,opts)=>new Server(srv,opts);module2.exports.Server=Server;module2.exports.Namespace=namespace_1.Namespace;module2.exports.Socket=socket_1.Socket}});var require_listCacheClear=__commonJS({"node_modules/lodash/_listCacheClear.js"(exports2,module2){function listCacheClear(){this.__data__=[],this.size=0}module2.exports=listCacheClear}});var require_eq=__commonJS({"node_modules/lodash/eq.js"(exports2,module2){function eq(value,other){return value===other||value!==value&&other!==other}module2.exports=eq}});var require_assocIndexOf=__commonJS({"node_modules/lodash/_assocIndexOf.js"(exports2,module2){var eq=require_eq();function assocIndexOf(array,key){for(var length=array.length;length--;)if(eq(array[length][0],key))return length;return-1}module2.exports=assocIndexOf}});var require_listCacheDelete=__commonJS({"node_modules/lodash/_listCacheDelete.js"(exports2,module2){var assocIndexOf=require_assocIndexOf(),arrayProto=Array.prototype,splice=arrayProto.splice;function listCacheDelete(key){var data=this.__data__,index=assocIndexOf(data,key);if(index<0)return!1;var lastIndex=data.length-1;return index==lastIndex?data.pop():splice.call(data,index,1),--this.size,!0}module2.exports=listCacheDelete}});var require_listCacheGet=__commonJS({"node_modules/lodash/_listCacheGet.js"(exports2,module2){var assocIndexOf=require_assocIndexOf();function listCacheGet(key){var data=this.__data__,index=assocIndexOf(data,key);return index<0?void 0:data[index][1]}module2.exports=listCacheGet}});var require_listCacheHas=__commonJS({"node_modules/lodash/_listCacheHas.js"(exports2,module2){var assocIndexOf=require_assocIndexOf();function listCacheHas(key){return assocIndexOf(this.__data__,key)>-1}module2.exports=listCacheHas}});var require_listCacheSet=__commonJS({"node_modules/lodash/_listCacheSet.js"(exports2,module2){var assocIndexOf=require_assocIndexOf();function listCacheSet(key,value){var data=this.__data__,index=assocIndexOf(data,key);return index<0?(++this.size,data.push([key,value])):data[index][1]=value,this}module2.exports=listCacheSet}});var require_ListCache=__commonJS({"node_modules/lodash/_ListCache.js"(exports2,module2){var listCacheClear=require_listCacheClear(),listCacheDelete=require_listCacheDelete(),listCacheGet=require_listCacheGet(),listCacheHas=require_listCacheHas(),listCacheSet=require_listCacheSet();function ListCache(entries){var index=-1,length=entries==null?0:entries.length;for(this.clear();++index<length;){var entry=entries[index];this.set(entry[0],entry[1])}}ListCache.prototype.clear=listCacheClear;ListCache.prototype.delete=listCacheDelete;ListCache.prototype.get=listCacheGet;ListCache.prototype.has=listCacheHas;ListCache.prototype.set=listCacheSet;module2.exports=ListCache}});var require_stackClear=__commonJS({"node_modules/lodash/_stackClear.js"(exports2,module2){var ListCache=require_ListCache();function stackClear(){this.__data__=new ListCache,this.size=0}module2.exports=stackClear}});var require_stackDelete=__commonJS({"node_modules/lodash/_stackDelete.js"(exports2,module2){function stackDelete(key){var data=this.__data__,result=data.delete(key);return this.size=data.size,result}module2.exports=stackDelete}});var require_stackGet=__commonJS({"node_modules/lodash/_stackGet.js"(exports2,module2){function stackGet(key){return this.__data__.get(key)}module2.exports=stackGet}});var require_stackHas=__commonJS({"node_modules/lodash/_stackHas.js"(exports2,module2){function stackHas(key){return this.__data__.has(key)}module2.exports=stackHas}});var require_freeGlobal=__commonJS({"node_modules/lodash/_freeGlobal.js"(exports2,module2){var freeGlobal=typeof global=="object"&&global&&global.Object===Object&&global;module2.exports=freeGlobal}});var require_root=__commonJS({"node_modules/lodash/_root.js"(exports2,module2){var freeGlobal=require_freeGlobal(),freeSelf=typeof self=="object"&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")();module2.exports=root}});var require_Symbol=__commonJS({"node_modules/lodash/_Symbol.js"(exports2,module2){var root=require_root(),Symbol2=root.Symbol;module2.exports=Symbol2}});var require_getRawTag=__commonJS({"node_modules/lodash/_getRawTag.js"(exports2,module2){var Symbol2=require_Symbol(),objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,nativeObjectToString=objectProto.toString,symToStringTag=Symbol2?Symbol2.toStringTag:void 0;function getRawTag(value){var isOwn=hasOwnProperty.call(value,symToStringTag),tag=value[symToStringTag];try{value[symToStringTag]=void 0;var unmasked=!0}catch{}var result=nativeObjectToString.call(value);return unmasked&&(isOwn?value[symToStringTag]=tag:delete value[symToStringTag]),result}module2.exports=getRawTag}});var require_objectToString=__commonJS({"node_modules/lodash/_objectToString.js"(exports2,module2){var objectProto=Object.prototype,nativeObjectToString=objectProto.toString;function objectToString(value){return nativeObjectToString.call(value)}module2.exports=objectToString}});var require_baseGetTag=__commonJS({"node_modules/lodash/_baseGetTag.js"(exports2,module2){var Symbol2=require_Symbol(),getRawTag=require_getRawTag(),objectToString=require_objectToString(),nullTag="[object Null]",undefinedTag="[object Undefined]",symToStringTag=Symbol2?Symbol2.toStringTag:void 0;function baseGetTag(value){return value==null?value===void 0?undefinedTag:nullTag:symToStringTag&&symToStringTag in Object(value)?getRawTag(value):objectToString(value)}module2.exports=baseGetTag}});var require_isObject=__commonJS({"node_modules/lodash/isObject.js"(exports2,module2){function isObject(value){var type=typeof value;return value!=null&&(type=="object"||type=="function")}module2.exports=isObject}});var require_isFunction=__commonJS({"node_modules/lodash/isFunction.js"(exports2,module2){var baseGetTag=require_baseGetTag(),isObject=require_isObject(),asyncTag="[object AsyncFunction]",funcTag="[object Function]",genTag="[object GeneratorFunction]",proxyTag="[object Proxy]";function isFunction(value){if(!isObject(value))return!1;var tag=baseGetTag(value);return tag==funcTag||tag==genTag||tag==asyncTag||tag==proxyTag}module2.exports=isFunction}});var require_coreJsData=__commonJS({"node_modules/lodash/_coreJsData.js"(exports2,module2){var root=require_root(),coreJsData=root["__core-js_shared__"];module2.exports=coreJsData}});var require_isMasked=__commonJS({"node_modules/lodash/_isMasked.js"(exports2,module2){var coreJsData=require_coreJsData(),maskSrcKey=(function(){var uid=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return uid?"Symbol(src)_1."+uid:""})();function isMasked(func){return!!maskSrcKey&&maskSrcKey in func}module2.exports=isMasked}});var require_toSource=__commonJS({"node_modules/lodash/_toSource.js"(exports2,module2){var funcProto=Function.prototype,funcToString=funcProto.toString;function toSource(func){if(func!=null){try{return funcToString.call(func)}catch{}try{return func+""}catch{}}return""}module2.exports=toSource}});var require_baseIsNative=__commonJS({"node_modules/lodash/_baseIsNative.js"(exports2,module2){var isFunction=require_isFunction(),isMasked=require_isMasked(),isObject=require_isObject(),toSource=require_toSource(),reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reIsHostCtor=/^\[object .+?Constructor\]$/,funcProto=Function.prototype,objectProto=Object.prototype,funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function baseIsNative(value){if(!isObject(value)||isMasked(value))return!1;var pattern=isFunction(value)?reIsNative:reIsHostCtor;return pattern.test(toSource(value))}module2.exports=baseIsNative}});var require_getValue=__commonJS({"node_modules/lodash/_getValue.js"(exports2,module2){function getValue(object,key){return object?.[key]}module2.exports=getValue}});var require_getNative=__commonJS({"node_modules/lodash/_getNative.js"(exports2,module2){var baseIsNative=require_baseIsNative(),getValue=require_getValue();function getNative(object,key){var value=getValue(object,key);return baseIsNative(value)?value:void 0}module2.exports=getNative}});var require_Map=__commonJS({"node_modules/lodash/_Map.js"(exports2,module2){var getNative=require_getNative(),root=require_root(),Map2=getNative(root,"Map");module2.exports=Map2}});var require_nativeCreate=__commonJS({"node_modules/lodash/_nativeCreate.js"(exports2,module2){var getNative=require_getNative(),nativeCreate=getNative(Object,"create");module2.exports=nativeCreate}});var require_hashClear=__commonJS({"node_modules/lodash/_hashClear.js"(exports2,module2){var nativeCreate=require_nativeCreate();function hashClear(){this.__data__=nativeCreate?nativeCreate(null):{},this.size=0}module2.exports=hashClear}});var require_hashDelete=__commonJS({"node_modules/lodash/_hashDelete.js"(exports2,module2){function hashDelete(key){var result=this.has(key)&&delete this.__data__[key];return this.size-=result?1:0,result}module2.exports=hashDelete}});var require_hashGet=__commonJS({"node_modules/lodash/_hashGet.js"(exports2,module2){var nativeCreate=require_nativeCreate(),HASH_UNDEFINED="__lodash_hash_undefined__",objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty;function hashGet(key){var data=this.__data__;if(nativeCreate){var result=data[key];return result===HASH_UNDEFINED?void 0:result}return hasOwnProperty.call(data,key)?data[key]:void 0}module2.exports=hashGet}});var require_hashHas=__commonJS({"node_modules/lodash/_hashHas.js"(exports2,module2){var nativeCreate=require_nativeCreate(),objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty;function hashHas(key){var data=this.__data__;return nativeCreate?data[key]!==void 0:hasOwnProperty.call(data,key)}module2.exports=hashHas}});var require_hashSet=__commonJS({"node_modules/lodash/_hashSet.js"(exports2,module2){var nativeCreate=require_nativeCreate(),HASH_UNDEFINED="__lodash_hash_undefined__";function hashSet(key,value){var data=this.__data__;return this.size+=this.has(key)?0:1,data[key]=nativeCreate&&value===void 0?HASH_UNDEFINED:value,this}module2.exports=hashSet}});var require_Hash=__commonJS({"node_modules/lodash/_Hash.js"(exports2,module2){var hashClear=require_hashClear(),hashDelete=require_hashDelete(),hashGet=require_hashGet(),hashHas=require_hashHas(),hashSet=require_hashSet();function Hash(entries){var index=-1,length=entries==null?0:entries.length;for(this.clear();++index<length;){var entry=entries[index];this.set(entry[0],entry[1])}}Hash.prototype.clear=hashClear;Hash.prototype.delete=hashDelete;Hash.prototype.get=hashGet;Hash.prototype.has=hashHas;Hash.prototype.set=hashSet;module2.exports=Hash}});var require_mapCacheClear=__commonJS({"node_modules/lodash/_mapCacheClear.js"(exports2,module2){var Hash=require_Hash(),ListCache=require_ListCache(),Map2=require_Map();function mapCacheClear(){this.size=0,this.__data__={hash:new Hash,map:new(Map2||ListCache),string:new Hash}}module2.exports=mapCacheClear}});var require_isKeyable=__commonJS({"node_modules/lodash/_isKeyable.js"(exports2,module2){function isKeyable(value){var type=typeof value;return type=="string"||type=="number"||type=="symbol"||type=="boolean"?value!=="__proto__":value===null}module2.exports=isKeyable}});var require_getMapData=__commonJS({"node_modules/lodash/_getMapData.js"(exports2,module2){var isKeyable=require_isKeyable();function getMapData(map,key){var data=map.__data__;return isKeyable(key)?data[typeof key=="string"?"string":"hash"]:data.map}module2.exports=getMapData}});var require_mapCacheDelete=__commonJS({"node_modules/lodash/_mapCacheDelete.js"(exports2,module2){var getMapData=require_getMapData();function mapCacheDelete(key){var result=getMapData(this,key).delete(key);return this.size-=result?1:0,result}module2.exports=mapCacheDelete}});var require_mapCacheGet=__commonJS({"node_modules/lodash/_mapCacheGet.js"(exports2,module2){var getMapData=require_getMapData();function mapCacheGet(key){return getMapData(this,key).get(key)}module2.exports=mapCacheGet}});var require_mapCacheHas=__commonJS({"node_modules/lodash/_mapCacheHas.js"(exports2,module2){var getMapData=require_getMapData();function mapCacheHas(key){return getMapData(this,key).has(key)}module2.exports=mapCacheHas}});var require_mapCacheSet=__commonJS({"node_modules/lodash/_mapCacheSet.js"(exports2,module2){var getMapData=require_getMapData();function mapCacheSet(key,value){var data=getMapData(this,key),size=data.size;return data.set(key,value),this.size+=data.size==size?0:1,this}module2.exports=mapCacheSet}});var require_MapCache=__commonJS({"node_modules/lodash/_MapCache.js"(exports2,module2){var mapCacheClear=require_mapCacheClear(),mapCacheDelete=require_mapCacheDelete(),mapCacheGet=require_mapCacheGet(),mapCacheHas=require_mapCacheHas(),mapCacheSet=require_mapCacheSet();function MapCache(entries){var index=-1,length=entries==null?0:entries.length;for(this.clear();++index<length;){var entry=entries[index];this.set(entry[0],entry[1])}}MapCache.prototype.clear=mapCacheClear;MapCache.prototype.delete=mapCacheDelete;MapCache.prototype.get=mapCacheGet;MapCache.prototype.has=mapCacheHas;MapCache.prototype.set=mapCacheSet;module2.exports=MapCache}});var require_stackSet=__commonJS({"node_modules/lodash/_stackSet.js"(exports2,module2){var ListCache=require_ListCache(),Map2=require_Map(),MapCache=require_MapCache(),LARGE_ARRAY_SIZE=200;function stackSet(key,value){var data=this.__data__;if(data instanceof ListCache){var pairs=data.__data__;if(!Map2||pairs.length<LARGE_ARRAY_SIZE-1)return pairs.push([key,value]),this.size=++data.size,this;data=this.__data__=new MapCache(pairs)}return data.set(key,value),this.size=data.size,this}module2.exports=stackSet}});var require_Stack=__commonJS({"node_modules/lodash/_Stack.js"(exports2,module2){var ListCache=require_ListCache(),stackClear=require_stackClear(),stackDelete=require_stackDelete(),stackGet=require_stackGet(),stackHas=require_stackHas(),stackSet=require_stackSet();function Stack(entries){var data=this.__data__=new ListCache(entries);this.size=data.size}Stack.prototype.clear=stackClear;Stack.prototype.delete=stackDelete;Stack.prototype.get=stackGet;Stack.prototype.has=stackHas;Stack.prototype.set=stackSet;module2.exports=Stack}});var require_setCacheAdd=__commonJS({"node_modules/lodash/_setCacheAdd.js"(exports2,module2){var HASH_UNDEFINED="__lodash_hash_undefined__";function setCacheAdd(value){return this.__data__.set(value,HASH_UNDEFINED),this}module2.exports=setCacheAdd}});var require_setCacheHas=__commonJS({"node_modules/lodash/_setCacheHas.js"(exports2,module2){function setCacheHas(value){return this.__data__.has(value)}module2.exports=setCacheHas}});var require_SetCache=__commonJS({"node_modules/lodash/_SetCache.js"(exports2,module2){var MapCache=require_MapCache(),setCacheAdd=require_setCacheAdd(),setCacheHas=require_setCacheHas();function SetCache(values){var index=-1,length=values==null?0:values.length;for(this.__data__=new MapCache;++index<length;)this.add(values[index])}SetCache.prototype.add=SetCache.prototype.push=setCacheAdd;SetCache.prototype.has=setCacheHas;module2.exports=SetCache}});var require_arraySome=__commonJS({"node_modules/lodash/_arraySome.js"(exports2,module2){function arraySome(array,predicate){for(var index=-1,length=array==null?0:array.length;++index<length;)if(predicate(array[index],index,array))return!0;return!1}module2.exports=arraySome}});var require_cacheHas=__commonJS({"node_modules/lodash/_cacheHas.js"(exports2,module2){function cacheHas(cache,key){return cache.has(key)}module2.exports=cacheHas}});var require_equalArrays=__commonJS({"node_modules/lodash/_equalArrays.js"(exports2,module2){var SetCache=require_SetCache(),arraySome=require_arraySome(),cacheHas=require_cacheHas(),COMPARE_PARTIAL_FLAG=1,COMPARE_UNORDERED_FLAG=2;function equalArrays(array,other,bitmask,customizer,equalFunc,stack){var isPartial=bitmask&COMPARE_PARTIAL_FLAG,arrLength=array.length,othLength=other.length;if(arrLength!=othLength&&!(isPartial&&othLength>arrLength))return!1;var arrStacked=stack.get(array),othStacked=stack.get(other);if(arrStacked&&othStacked)return arrStacked==other&&othStacked==array;var index=-1,result=!0,seen=bitmask&COMPARE_UNORDERED_FLAG?new SetCache:void 0;for(stack.set(array,other),stack.set(other,array);++index<arrLength;){var arrValue=array[index],othValue=other[index];if(customizer)var compared=isPartial?customizer(othValue,arrValue,index,other,array,stack):customizer(arrValue,othValue,index,array,other,stack);if(compared!==void 0){if(compared)continue;result=!1;break}if(seen){if(!arraySome(other,function(othValue2,othIndex){if(!cacheHas(seen,othIndex)&&(arrValue===othValue2||equalFunc(arrValue,othValue2,bitmask,customizer,stack)))return seen.push(othIndex)})){result=!1;break}}else if(!(arrValue===othValue||equalFunc(arrValue,othValue,bitmask,customizer,stack))){result=!1;break}}return stack.delete(array),stack.delete(other),result}module2.exports=equalArrays}});var require_Uint8Array=__commonJS({"node_modules/lodash/_Uint8Array.js"(exports2,module2){var root=require_root(),Uint8Array2=root.Uint8Array;module2.exports=Uint8Array2}});var require_mapToArray=__commonJS({"node_modules/lodash/_mapToArray.js"(exports2,module2){function mapToArray(map){var index=-1,result=Array(map.size);return map.forEach(function(value,key){result[++index]=[key,value]}),result}module2.exports=mapToArray}});var require_setToArray=__commonJS({"node_modules/lodash/_setToArray.js"(exports2,module2){function setToArray(set){var index=-1,result=Array(set.size);return set.forEach(function(value){result[++index]=value}),result}module2.exports=setToArray}});var require_equalByTag=__commonJS({"node_modules/lodash/_equalByTag.js"(exports2,module2){var Symbol2=require_Symbol(),Uint8Array2=require_Uint8Array(),eq=require_eq(),equalArrays=require_equalArrays(),mapToArray=require_mapToArray(),setToArray=require_setToArray(),COMPARE_PARTIAL_FLAG=1,COMPARE_UNORDERED_FLAG=2,boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",mapTag="[object Map]",numberTag="[object Number]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",symbolTag="[object Symbol]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",symbolProto=Symbol2?Symbol2.prototype:void 0,symbolValueOf=symbolProto?symbolProto.valueOf:void 0;function equalByTag(object,other,tag,bitmask,customizer,equalFunc,stack){switch(tag){case dataViewTag:if(object.byteLength!=other.byteLength||object.byteOffset!=other.byteOffset)return!1;object=object.buffer,other=other.buffer;case arrayBufferTag:return!(object.byteLength!=other.byteLength||!equalFunc(new Uint8Array2(object),new Uint8Array2(other)));case boolTag:case dateTag:case numberTag:return eq(+object,+other);case errorTag:return object.name==other.name&&object.message==other.message;case regexpTag:case stringTag:return object==other+"";case mapTag:var convert=mapToArray;case setTag:var isPartial=bitmask&COMPARE_PARTIAL_FLAG;if(convert||(convert=setToArray),object.size!=other.size&&!isPartial)return!1;var stacked=stack.get(object);if(stacked)return stacked==other;bitmask|=COMPARE_UNORDERED_FLAG,stack.set(object,other);var result=equalArrays(convert(object),convert(other),bitmask,customizer,equalFunc,stack);return stack.delete(object),result;case symbolTag:if(symbolValueOf)return symbolValueOf.call(object)==symbolValueOf.call(other)}return!1}module2.exports=equalByTag}});var require_arrayPush=__commonJS({"node_modules/lodash/_arrayPush.js"(exports2,module2){function arrayPush(array,values){for(var index=-1,length=values.length,offset=array.length;++index<length;)array[offset+index]=values[index];return array}module2.exports=arrayPush}});var require_isArray=__commonJS({"node_modules/lodash/isArray.js"(exports2,module2){var isArray=Array.isArray;module2.exports=isArray}});var require_baseGetAllKeys=__commonJS({"node_modules/lodash/_baseGetAllKeys.js"(exports2,module2){var arrayPush=require_arrayPush(),isArray=require_isArray();function baseGetAllKeys(object,keysFunc,symbolsFunc){var result=keysFunc(object);return isArray(object)?result:arrayPush(result,symbolsFunc(object))}module2.exports=baseGetAllKeys}});var require_arrayFilter=__commonJS({"node_modules/lodash/_arrayFilter.js"(exports2,module2){function arrayFilter(array,predicate){for(var index=-1,length=array==null?0:array.length,resIndex=0,result=[];++index<length;){var value=array[index];predicate(value,index,array)&&(result[resIndex++]=value)}return result}module2.exports=arrayFilter}});var require_stubArray=__commonJS({"node_modules/lodash/stubArray.js"(exports2,module2){function stubArray(){return[]}module2.exports=stubArray}});var require_getSymbols=__commonJS({"node_modules/lodash/_getSymbols.js"(exports2,module2){var arrayFilter=require_arrayFilter(),stubArray=require_stubArray(),objectProto=Object.prototype,propertyIsEnumerable=objectProto.propertyIsEnumerable,nativeGetSymbols=Object.getOwnPropertySymbols,getSymbols=nativeGetSymbols?function(object){return object==null?[]:(object=Object(object),arrayFilter(nativeGetSymbols(object),function(symbol){return propertyIsEnumerable.call(object,symbol)}))}:stubArray;module2.exports=getSymbols}});var require_baseTimes=__commonJS({"node_modules/lodash/_baseTimes.js"(exports2,module2){function baseTimes(n,iteratee){for(var index=-1,result=Array(n);++index<n;)result[index]=iteratee(index);return result}module2.exports=baseTimes}});var require_isObjectLike=__commonJS({"node_modules/lodash/isObjectLike.js"(exports2,module2){function isObjectLike(value){return value!=null&&typeof value=="object"}module2.exports=isObjectLike}});var require_baseIsArguments=__commonJS({"node_modules/lodash/_baseIsArguments.js"(exports2,module2){var baseGetTag=require_baseGetTag(),isObjectLike=require_isObjectLike(),argsTag="[object Arguments]";function baseIsArguments(value){return isObjectLike(value)&&baseGetTag(value)==argsTag}module2.exports=baseIsArguments}});var require_isArguments=__commonJS({"node_modules/lodash/isArguments.js"(exports2,module2){var baseIsArguments=require_baseIsArguments(),isObjectLike=require_isObjectLike(),objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty,propertyIsEnumerable=objectProto.propertyIsEnumerable,isArguments=baseIsArguments((function(){return arguments})())?baseIsArguments:function(value){return isObjectLike(value)&&hasOwnProperty.call(value,"callee")&&!propertyIsEnumerable.call(value,"callee")};module2.exports=isArguments}});var require_stubFalse=__commonJS({"node_modules/lodash/stubFalse.js"(exports2,module2){function stubFalse(){return!1}module2.exports=stubFalse}});var require_isBuffer=__commonJS({"node_modules/lodash/isBuffer.js"(exports2,module2){var root=require_root(),stubFalse=require_stubFalse(),freeExports=typeof exports2=="object"&&exports2&&!exports2.nodeType&&exports2,freeModule=freeExports&&typeof module2=="object"&&module2&&!module2.nodeType&&module2,moduleExports=freeModule&&freeModule.exports===freeExports,Buffer2=moduleExports?root.Buffer:void 0,nativeIsBuffer=Buffer2?Buffer2.isBuffer:void 0,isBuffer=nativeIsBuffer||stubFalse;module2.exports=isBuffer}});var require_isIndex=__commonJS({"node_modules/lodash/_isIndex.js"(exports2,module2){var MAX_SAFE_INTEGER=9007199254740991,reIsUint=/^(?:0|[1-9]\d*)$/;function isIndex(value,length){var type=typeof value;return length=length??MAX_SAFE_INTEGER,!!length&&(type=="number"||type!="symbol"&&reIsUint.test(value))&&value>-1&&value%1==0&&value<length}module2.exports=isIndex}});var require_isLength=__commonJS({"node_modules/lodash/isLength.js"(exports2,module2){var MAX_SAFE_INTEGER=9007199254740991;function isLength(value){return typeof value=="number"&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}module2.exports=isLength}});var require_baseIsTypedArray=__commonJS({"node_modules/lodash/_baseIsTypedArray.js"(exports2,module2){var baseGetTag=require_baseGetTag(),isLength=require_isLength(),isObjectLike=require_isObjectLike(),argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",weakMapTag="[object WeakMap]",arrayBufferTag="[object ArrayBuffer]",dataViewTag="[object DataView]",float32Tag="[object Float32Array]",float64Tag="[object Float64Array]",int8Tag="[object Int8Array]",int16Tag="[object Int16Array]",int32Tag="[object Int32Array]",uint8Tag="[object Uint8Array]",uint8ClampedTag="[object Uint8ClampedArray]",uint16Tag="[object Uint16Array]",uint32Tag="[object Uint32Array]",typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=!0;typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dataViewTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=!1;function baseIsTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&!!typedArrayTags[baseGetTag(value)]}module2.exports=baseIsTypedArray}});var require_baseUnary=__commonJS({"node_modules/lodash/_baseUnary.js"(exports2,module2){function baseUnary(func){return function(value){return func(value)}}module2.exports=baseUnary}});var require_nodeUtil=__commonJS({"node_modules/lodash/_nodeUtil.js"(exports2,module2){var freeGlobal=require_freeGlobal(),freeExports=typeof exports2=="object"&&exports2&&!exports2.nodeType&&exports2,freeModule=freeExports&&typeof module2=="object"&&module2&&!module2.nodeType&&module2,moduleExports=freeModule&&freeModule.exports===freeExports,freeProcess=moduleExports&&freeGlobal.process,nodeUtil=(function(){try{var types=freeModule&&freeModule.require&&freeModule.require("util").types;return types||freeProcess&&freeProcess.binding&&freeProcess.binding("util")}catch{}})();module2.exports=nodeUtil}});var require_isTypedArray=__commonJS({"node_modules/lodash/isTypedArray.js"(exports2,module2){var baseIsTypedArray=require_baseIsTypedArray(),baseUnary=require_baseUnary(),nodeUtil=require_nodeUtil(),nodeIsTypedArray=nodeUtil&&nodeUtil.isTypedArray,isTypedArray=nodeIsTypedArray?baseUnary(nodeIsTypedArray):baseIsTypedArray;module2.exports=isTypedArray}});var require_arrayLikeKeys=__commonJS({"node_modules/lodash/_arrayLikeKeys.js"(exports2,module2){var baseTimes=require_baseTimes(),isArguments=require_isArguments(),isArray=require_isArray(),isBuffer=require_isBuffer(),isIndex=require_isIndex(),isTypedArray=require_isTypedArray(),objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty;function arrayLikeKeys(value,inherited){var isArr=isArray(value),isArg=!isArr&&isArguments(value),isBuff=!isArr&&!isArg&&isBuffer(value),isType=!isArr&&!isArg&&!isBuff&&isTypedArray(value),skipIndexes=isArr||isArg||isBuff||isType,result=skipIndexes?baseTimes(value.length,String):[],length=result.length;for(var key in value)(inherited||hasOwnProperty.call(value,key))&&!(skipIndexes&&(key=="length"||isBuff&&(key=="offset"||key=="parent")||isType&&(key=="buffer"||key=="byteLength"||key=="byteOffset")||isIndex(key,length)))&&result.push(key);return result}module2.exports=arrayLikeKeys}});var require_isPrototype=__commonJS({"node_modules/lodash/_isPrototype.js"(exports2,module2){var objectProto=Object.prototype;function isPrototype(value){var Ctor=value&&value.constructor,proto=typeof Ctor=="function"&&Ctor.prototype||objectProto;return value===proto}module2.exports=isPrototype}});var require_overArg=__commonJS({"node_modules/lodash/_overArg.js"(exports2,module2){function overArg(func,transform){return function(arg){return func(transform(arg))}}module2.exports=overArg}});var require_nativeKeys=__commonJS({"node_modules/lodash/_nativeKeys.js"(exports2,module2){var overArg=require_overArg(),nativeKeys=overArg(Object.keys,Object);module2.exports=nativeKeys}});var require_baseKeys=__commonJS({"node_modules/lodash/_baseKeys.js"(exports2,module2){var isPrototype=require_isPrototype(),nativeKeys=require_nativeKeys(),objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty;function baseKeys(object){if(!isPrototype(object))return nativeKeys(object);var result=[];for(var key in Object(object))hasOwnProperty.call(object,key)&&key!="constructor"&&result.push(key);return result}module2.exports=baseKeys}});var require_isArrayLike=__commonJS({"node_modules/lodash/isArrayLike.js"(exports2,module2){var isFunction=require_isFunction(),isLength=require_isLength();function isArrayLike(value){return value!=null&&isLength(value.length)&&!isFunction(value)}module2.exports=isArrayLike}});var require_keys=__commonJS({"node_modules/lodash/keys.js"(exports2,module2){var arrayLikeKeys=require_arrayLikeKeys(),baseKeys=require_baseKeys(),isArrayLike=require_isArrayLike();function keys(object){return isArrayLike(object)?arrayLikeKeys(object):baseKeys(object)}module2.exports=keys}});var require_getAllKeys=__commonJS({"node_modules/lodash/_getAllKeys.js"(exports2,module2){var baseGetAllKeys=require_baseGetAllKeys(),getSymbols=require_getSymbols(),keys=require_keys();function getAllKeys(object){return baseGetAllKeys(object,keys,getSymbols)}module2.exports=getAllKeys}});var require_equalObjects=__commonJS({"node_modules/lodash/_equalObjects.js"(exports2,module2){var getAllKeys=require_getAllKeys(),COMPARE_PARTIAL_FLAG=1,objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty;function equalObjects(object,other,bitmask,customizer,equalFunc,stack){var isPartial=bitmask&COMPARE_PARTIAL_FLAG,objProps=getAllKeys(object),objLength=objProps.length,othProps=getAllKeys(other),othLength=othProps.length;if(objLength!=othLength&&!isPartial)return!1;for(var index=objLength;index--;){var key=objProps[index];if(!(isPartial?key in other:hasOwnProperty.call(other,key)))return!1}var objStacked=stack.get(object),othStacked=stack.get(other);if(objStacked&&othStacked)return objStacked==other&&othStacked==object;var result=!0;stack.set(object,other),stack.set(other,object);for(var skipCtor=isPartial;++index<objLength;){key=objProps[index];var objValue=object[key],othValue=other[key];if(customizer)var compared=isPartial?customizer(othValue,objValue,key,other,object,stack):customizer(objValue,othValue,key,object,other,stack);if(!(compared===void 0?objValue===othValue||equalFunc(objValue,othValue,bitmask,customizer,stack):compared)){result=!1;break}skipCtor||(skipCtor=key=="constructor")}if(result&&!skipCtor){var objCtor=object.constructor,othCtor=other.constructor;objCtor!=othCtor&&"constructor"in object&&"constructor"in other&&!(typeof objCtor=="function"&&objCtor instanceof objCtor&&typeof othCtor=="function"&&othCtor instanceof othCtor)&&(result=!1)}return stack.delete(object),stack.delete(other),result}module2.exports=equalObjects}});var require_DataView=__commonJS({"node_modules/lodash/_DataView.js"(exports2,module2){var getNative=require_getNative(),root=require_root(),DataView2=getNative(root,"DataView");module2.exports=DataView2}});var require_Promise=__commonJS({"node_modules/lodash/_Promise.js"(exports2,module2){var getNative=require_getNative(),root=require_root(),Promise2=getNative(root,"Promise");module2.exports=Promise2}});var require_Set=__commonJS({"node_modules/lodash/_Set.js"(exports2,module2){var getNative=require_getNative(),root=require_root(),Set2=getNative(root,"Set");module2.exports=Set2}});var require_WeakMap=__commonJS({"node_modules/lodash/_WeakMap.js"(exports2,module2){var getNative=require_getNative(),root=require_root(),WeakMap2=getNative(root,"WeakMap");module2.exports=WeakMap2}});var require_getTag=__commonJS({"node_modules/lodash/_getTag.js"(exports2,module2){var DataView2=require_DataView(),Map2=require_Map(),Promise2=require_Promise(),Set2=require_Set(),WeakMap2=require_WeakMap(),baseGetTag=require_baseGetTag(),toSource=require_toSource(),mapTag="[object Map]",objectTag="[object Object]",promiseTag="[object Promise]",setTag="[object Set]",weakMapTag="[object WeakMap]",dataViewTag="[object DataView]",dataViewCtorString=toSource(DataView2),mapCtorString=toSource(Map2),promiseCtorString=toSource(Promise2),setCtorString=toSource(Set2),weakMapCtorString=toSource(WeakMap2),getTag=baseGetTag;(DataView2&&getTag(new DataView2(new ArrayBuffer(1)))!=dataViewTag||Map2&&getTag(new Map2)!=mapTag||Promise2&&getTag(Promise2.resolve())!=promiseTag||Set2&&getTag(new Set2)!=setTag||WeakMap2&&getTag(new WeakMap2)!=weakMapTag)&&(getTag=function(value){var result=baseGetTag(value),Ctor=result==objectTag?value.constructor:void 0,ctorString=Ctor?toSource(Ctor):"";if(ctorString)switch(ctorString){case dataViewCtorString:return dataViewTag;case mapCtorString:return mapTag;case promiseCtorString:return promiseTag;case setCtorString:return setTag;case weakMapCtorString:return weakMapTag}return result});module2.exports=getTag}});var require_baseIsEqualDeep=__commonJS({"node_modules/lodash/_baseIsEqualDeep.js"(exports2,module2){var Stack=require_Stack(),equalArrays=require_equalArrays(),equalByTag=require_equalByTag(),equalObjects=require_equalObjects(),getTag=require_getTag(),isArray=require_isArray(),isBuffer=require_isBuffer(),isTypedArray=require_isTypedArray(),COMPARE_PARTIAL_FLAG=1,argsTag="[object Arguments]",arrayTag="[object Array]",objectTag="[object Object]",objectProto=Object.prototype,hasOwnProperty=objectProto.hasOwnProperty;function baseIsEqualDeep(object,other,bitmask,customizer,equalFunc,stack){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=objIsArr?arrayTag:getTag(object),othTag=othIsArr?arrayTag:getTag(other);objTag=objTag==argsTag?objectTag:objTag,othTag=othTag==argsTag?objectTag:othTag;var objIsObj=objTag==objectTag,othIsObj=othTag==objectTag,isSameTag=objTag==othTag;if(isSameTag&&isBuffer(object)){if(!isBuffer(other))return!1;objIsArr=!0,objIsObj=!1}if(isSameTag&&!objIsObj)return stack||(stack=new Stack),objIsArr||isTypedArray(object)?equalArrays(object,other,bitmask,customizer,equalFunc,stack):equalByTag(object,other,objTag,bitmask,customizer,equalFunc,stack);if(!(bitmask&COMPARE_PARTIAL_FLAG)){var objIsWrapped=objIsObj&&hasOwnProperty.call(object,"__wrapped__"),othIsWrapped=othIsObj&&hasOwnProperty.call(other,"__wrapped__");if(objIsWrapped||othIsWrapped){var objUnwrapped=objIsWrapped?object.value():object,othUnwrapped=othIsWrapped?other.value():other;return stack||(stack=new Stack),equalFunc(objUnwrapped,othUnwrapped,bitmask,customizer,stack)}}return isSameTag?(stack||(stack=new Stack),equalObjects(object,other,bitmask,customizer,equalFunc,stack)):!1}module2.exports=baseIsEqualDeep}});var require_baseIsEqual=__commonJS({"node_modules/lodash/_baseIsEqual.js"(exports2,module2){var baseIsEqualDeep=require_baseIsEqualDeep(),isObjectLike=require_isObjectLike();function baseIsEqual(value,other,bitmask,customizer,stack){return value===other?!0:value==null||other==null||!isObjectLike(value)&&!isObjectLike(other)?value!==value&&other!==other:baseIsEqualDeep(value,other,bitmask,customizer,baseIsEqual,stack)}module2.exports=baseIsEqual}});var require_isEqual=__commonJS({"node_modules/lodash/isEqual.js"(exports2,module2){var baseIsEqual=require_baseIsEqual();function isEqual(value,other){return baseIsEqual(value,other)}module2.exports=isEqual}});var require_manageMockFiles=__commonJS({"src/lib/manageMockFiles.js"(exports2,module2){var fsa=require_lib(),fs=require("fs"),path=require("path"),isEqual=require_isEqual(),colors=require_safe(),{getFileLatestContent,SupportMethods,filePath2ApiUrl,logger,getDataType,getLogger,writeStream}=require_utils3(),log=logger(process.env.SILENT),processArgv=process.env.ARGV?JSON.parse(process.env.ARGV):{},methodRegExp=new RegExp(`(${SupportMethods.join("|")}) +(.*)`,"i"),normalizeApiPath=apiUrl=>path.posix.normalize(String(apiUrl||"").trim()).replace(/\/+$/,"")||"/",logFile=(isWriteLogFile=!1,mockDir)=>isWriteLogFile?getLogger(mockDir):{log:function(){},error:function(){}},genMockFiles=async function({url:apiUrl,method,data:resJsonData,dir:mockDir}){let type=getDataType(resJsonData);if(!apiUrl||!method||!resJsonData||!mockDir){log.info(colors.red([`\u53C2\u6570: apiUrl: ${apiUrl}, method: ${method}, mockDir: ${mockDir} `,"\u5FC5\u987B\u662F\u6709\u6548\u503C"].join(",")));return}else if(!["object","array"].includes(type)||type==="object"&&Object.keys(resJsonData).length===0||type==="array"&&resJsonData.length===0){log.info(`\u53C2\u6570: apiUrl: ${apiUrl}, method: ${method}, resJsonData:`,resJsonData,colors.red("\uFF0C \u53C2\u6570\u5B57\u6BB5resJsonData\u5FC5\u987B\u662F\u975E\u7A7A\u7684\u6570\u7EC4\u6216\u5BF9\u8C61\uFF01"));return}apiUrl=apiUrl.trim().split("?")[0];let LOGGER=logFile(processArgv.t||processArgv.track,mockDir),normalizeApiUrl=filePath2ApiUrl(normalizeApiPath(apiUrl)),mockListFilePath=path.resolve(process.cwd(),`${mockDir}/mock-list.json`),mockFilePath=path.resolve(process.cwd(),`${mockDir}/${encodeURIComponent(normalizeApiPath(apiUrl))}.json`),newMockListContent={};fsa.pathExistsSync(mockListFilePath)?newMockListContent=getFileLatestContent(mockListFilePath):fsa.ensureFileSync(mockListFilePath);let isChange=!1;if(newMockListContent.hasOwnProperty(normalizeApiUrl)?newMockListContent[normalizeApiUrl].includes(method)||(newMockListContent[normalizeApiUrl].push(method),isChange=!0):(newMockListContent[normalizeApiUrl]=[method],isChange=!0),isChange&&Object.keys(newMockListContent).length>0&&fs.writeFileSync(mockListFilePath,JSON.stringify(newMockListContent,null,2)),fsa.pathExistsSync(mockFilePath)){let mockFileContent=getFileLatestContent(mockFilePath);if(mockFileContent.hasOwnProperty(method)&&isEqual(mockFileContent[method],resJsonData))return;mockFileContent[method]=resJsonData;try{await writeStream(mockFilePath,JSON.stringify(mockFileContent,null,2))}catch{LOGGER.error(`Update file: ${method} ${apiUrl} ${mockFilePath}`)}LOGGER.log(`Update file: ${method} ${apiUrl} ${mockFilePath}`)}else{try{await writeStream(mockFilePath,JSON.stringify({[method]:resJsonData},null,2))}catch{LOGGER.error(`New file: ${method} ${apiUrl} ${mockFilePath}`)}LOGGER.log(`New file: ${method} ${apiUrl} ${mockFilePath}`)}},collectMockDataFromJsFile=function(mockDataMap,filePath){let fileObject=getFileLatestContent(filePath);Object.keys(fileObject).forEach(item=>{let reqMethod="get",reqUrl=item;if(methodRegExp.exec(item)){let[,method,url]=methodRegExp.exec(item);reqMethod=method.toLowerCase(),reqUrl=normalizeApiPath(url)}typeof fileObject[item]=="function"?mockDataMap[`${reqMethod} ${reqUrl}`]=String(fileObject[item]):typeof fileObject[item]=="object"&&(mockDataMap[`${reqMethod} ${reqUrl}`]=fileObject[item])})},deepCollectMockData=function(mockDataMap,specialDir="../mock"){let files=fs.readdirSync(path.resolve(process.cwd(),specialDir),{withFileTypes:!0}),curFilesSize=files.length;for(let index=0;index<curFilesSize;index++){let el=files[index],filePath=path.normalize(`${specialDir}/${el.name}`);if(el.isFile()||deepCollectMockData(mockDataMap,filePath),el.name.endsWith(".json")&&el.name!=="mock-list.json"){let fileObject=getFileLatestContent(filePath);Object.keys(fileObject).forEach(method=>{mockDataMap[`${method.toLocaleLowerCase()} ${normalizeApiPath(decodeURIComponent(el.name).split(".json")[0])}`]=fileObject[method]});continue}el.name.endsWith(".js")&&collectMockDataFromJsFile(mockDataMap,filePath)}},getMockStatFromDir=dirPath=>{if(!fsa.pathExistsSync(dirPath)){getLogger(path.resolve(process.cwd())).error(`\u5165\u53C2\u65E0\u6548\uFF0C${dirPath} \u76EE\u5F55\u4E0D\u5B58\u5728`);return}let mockDataMap={};deepCollectMockData(mockDataMap,dirPath);let mockListFilePath=path.resolve(process.cwd(),`${dirPath}/mock-list.json`);if(Object.keys(mockDataMap).length>0&&!fsa.pathExistsSync(mockListFilePath)){fsa.ensureFileSync(mockListFilePath);let reverseMockList={};Object.keys(mockDataMap).forEach(it=>{if(methodRegExp.exec(it)){let[,method,url]=methodRegExp.exec(it),normalizedUrl=normalizeApiPath(url);normalizedUrl.trim()&&method.trim()&&(reverseMockList.hasOwnProperty(normalizedUrl)?reverseMockList[normalizedUrl].push(method):reverseMockList[normalizedUrl]=[method])}}),writeStream(mockListFilePath,JSON.stringify(reverseMockList,null,2))}return mockDataMap},getMockStatFromFile=filePath=>{if(!fsa.pathExistsSync(filePath)){getLogger(path.resolve(process.cwd())).error(`\u5165\u53C2\u65E0\u6548\uFF0C${filePath} \u6587\u4EF6\u4E0D\u5B58\u5728`);return}let mockDataMap={};return collectMockDataFromJsFile(mockDataMap,filePath),mockDataMap},hasMockApi=function(mockDataMap,apiUrl,method){if(!apiUrl||!method||!mockDataMap||!(mockDataMap instanceof Object)){getLogger(path.resolve(process.cwd())).error(`\u5165\u53C2\u65E0\u6548\uFF0C${mockDataMap} \u5FC5\u987B\u662F mock\u6570\u636E\u7684Object\u5BF9\u8C61`);return}return mockDataMap.hasOwnProperty(`${method.toLocaleLowerCase()} ${normalizeApiPath(apiUrl)}`)};module2.exports={genMockFiles,getMockStatFromDir,getMockStatFromFile,hasMockApi}}});var require_asyncTaskQueue=__commonJS({"src/lib/asyncTaskQueue.js"(exports2,module2){var AsyncTaskQueue=class{constructor(isSaveItem=!1){this.list=[],this.index=0,this.isStop=!1,this.isParallel=!1,this.isSaveItem=isSaveItem}next(){if(this.index>=this.list.length-1||this.isStop)return;this.isSaveItem||this.list.splice(this.index,1,"");let cur=this.list[++this.index];cur(this.next.bind(this))}add(...fn){this.list.push(...fn)}run(){let cur=this.list[this.index];typeof cur=="function"&&cur(this.next.bind(this))}parallelRun(){this.isParallel=!0;for(let fn of this.list)fn(this.next.bind(this))}stop(){this.isStop=!0}retry(){this.isStop=!1,this.run()}goOn(){this.isStop=!1,this.next()}};module2.exports=AsyncTaskQueue}});var require_mockServer=__commonJS({"src/lib/mockServer.js"(exports2,module2){var express=require_express2(),{readdirSync,existsSync}=require("fs"),path=require("path"),colors=require_safe(),portfinder=require_portfinder(),{exec,spawn}=require("child_process"),{createProxyMiddleware}=require_dist(),{Server}=require_dist3(),{dateFormat,logger,SupportMethods,DefaultHeaders,getFileLatestContent,filePath2ApiUrl,isEmptyObj,getServerHost,getServerUrls,hostAllowlistMiddleware,getHostAllowlist,isAddressAllowed}=require_utils3(),{getPackageVersion}=require_packageInfo(),{genMockFiles,getMockStatFromDir,getMockStatFromFile}=require_manageMockFiles(),registeredApis=[],methodRegExp=new RegExp(`((${SupportMethods.join("|")}) +)?([^?]*)`,"i"),app=express(),log=logger(process.env.SILENT),argv=JSON.parse(process.env.ARGV),socketServer=null,httpServer=null,webServer=null,shuttingDown=!1,corsOrigin=[],corsHeaders="",httpsRE=/^https:\/\//,count=0,fileCount=0,mockDirStat={},mockFileStat={},includesWebServe=process.env.STATIC_DIRECTORY||process.env.WEB_ROOT,mockFileOrDir=process.env.SPECIFIED_FILE||process.env.SPECIFIED_DIR;process.env.PORT?init():(portfinder.basePort=8090,portfinder.getPort(function(err,port){if(err)throw err;process.env.PORT=port,init()}));function init(){process.env.CORS_ORIGIN&&(process.env.CORS_ORIGIN.split(/\s*,\s*/).forEach(function(h){corsOrigin.push(h)},this),corsHeaders=DefaultHeaders),process.env.CORS_HEADERS&&process.env.CORS_HEADERS.split(/\s*,\s*/).forEach(function(h){corsHeaders+=corsHeaders?", "+h:h},this),app.use(hostAllowlistMiddleware()),app.use(crossDomain()),app.use(express.json()),app.get("/favicon-api-overview.svg",(req,res)=>{res.sendFile(path.resolve(__dirname,"./favicon-api-overview.svg"))}),app.get("/__api-overview",(req,res)=>{let htmlPath=path.resolve(__dirname,"./api-overview.html");existsSync(htmlPath)?res.sendFile(htmlPath):res.status(404).send("API overview page not found")}),app.get("/__api-data",(req,res)=>{let groupedApis={};registeredApis.forEach(api=>{let dirPath=path.dirname(api.file);groupedApis[dirPath]||(groupedApis[dirPath]=[]),groupedApis[dirPath].push(api)}),res.json({apis:registeredApis,groupedApis,port:process.env.PORT})});let requireMockServe=!0;process.env.SPECIFIED_FILE?composeRouteFromJsFile(process.env.SPECIFIED_FILE):includesWebServe&&!existsSync(path.resolve(process.cwd(),process.env.SPECIFIED_DIR))?requireMockServe=!1:parseMockFiles(process.env.SPECIFIED_DIR),requireMockServe&&argv.a&&log.info(colors.yellow(`${fileCount} mock file are parsed in total.`)),startServer()}function crossDomain(){return(req,res,next)=>{if(typeof argv.A=="string"){let resHeaders={};argv.A.split(/\s*,\s*/).forEach(function(h){let[key,value]=h.split("=");resHeaders[key]=value},this);for(let key in resHeaders)resHeaders.hasOwnProperty(key)&&res.header(key,resHeaders[key])}res.header("Access-Control-Allow-Credentials",!0),res.header("Access-Control-Allow-Origin",corsOrigin.includes(req.headers.origin)?req.headers.origin:"*"),res.header("Access-Control-Allow-Methods",SupportMethods.join(",")),res.header("Access-Control-Allow-Headers",corsHeaders||"*"),req.method==="OPTIONS"&&res.status(200),next()}}function composeRouteFromJsFile(file){let fileObject=getFileLatestContent(file);argv.a&&log.info(colors.green(`Mockfile ${++fileCount}: `),file,colors.yellow("all API URL is follows: ")),fileObject!=="getFileLatestContent_ERROR"&&Object.keys(fileObject).forEach(item=>{let reqMethod="get",reqUrl=item,[,,method,url]=methodRegExp.exec(item);method&&(reqMethod=method.toLowerCase()),reqUrl=url,argv.a&&log.info(colors.grey(`path ${String(++count).padStart(3," ")}: `),colors.cyan(reqMethod.padEnd(8," ")),colors.cyan(reqUrl),colors.grey(typeof fileObject[item])),log.assert(typeof app[reqMethod]=="function",colors.red(`${file}, ${reqMethod}`)),typeof fileObject[item]=="function"?app[reqMethod](reqUrl,fileObject[item]):typeof fileObject[item]=="object"&&app[reqMethod](reqUrl,function(req,res){res.json(fileObject[item])}),registeredApis.push({method:reqMethod.toUpperCase(),url:reqUrl,file,data:fileObject[item]})})}function parseMockFiles(specialDir="../mock"){let files=readdirSync(path.resolve(process.cwd(),specialDir),{withFileTypes:!0}),curFilesSize=files.length;for(let index=0;index<curFilesSize;index++){let el=files[index],filePath=path.normalize(`${specialDir}/${el.name}`);if(el.isFile()||parseMockFiles(filePath),el.name.endsWith(".json")&&el.name!=="mock-list.json"){argv.a&&log.info(colors.green(`Mockfile ${++fileCount}: `),filePath,colors.yellow("all API URL is follows: "));let fileObject=getFileLatestContent(filePath);if(fileObject==="getFileLatestContent_ERROR")continue;Object.keys(fileObject).forEach(method=>{let apiUrl=filePath2ApiUrl(decodeURIComponent(el.name.split(".")[0]));argv.a&&log.info(colors.grey(`path ${String(++count).padStart(3," ")}: `),colors.cyan(method.padEnd(8," ")),colors.cyan(apiUrl),colors.grey(typeof fileObject[method])),log.assert(typeof app[method]=="function",colors.red(`${filePath}, ${method}`)),app[method](apiUrl,function(req,res){res.json(fileObject[method])}),registeredApis.push({method:method.toUpperCase(),url:apiUrl,file:filePath,data:fileObject[method]})});continue}!el.name.endsWith(".js")&&!el.name.endsWith(".cjs")||composeRouteFromJsFile(filePath)}}function startServer(){let webApp=null,webPublicPath="/",proxyTable={};if(process.env.WEB_ROOT){if(webApp=express(),webApp.use(hostAllowlistMiddleware()),process.env.PROXY_OPTIONS)try{let options=JSON.parse(process.env.PROXY_OPTIONS);Object.keys(options).forEach(function(prefix){proxyTable[prefix]=options[prefix];let opts={target:options[prefix],changeOrigin:!0,ws:!0};httpsRE.test(options[prefix])&&(opts.secure=!1),process.env.PREFIX_REWRITE&&(opts.pathRewrite=path2=>path2.replace(new RegExp(`^${prefix}`),"")),webApp.use(prefix,createProxyMiddleware(opts))},this)}catch(error){console.warn(colors.yellow(`
116
116
  Enable web proxy Failed:`,error))}typeof argv.A=="string"&&webApp.use((req,res,next)=>{let resHeaders={};argv.A.split(/\s*,\s*/).forEach(function(h){let[key,value]=h.split("=");resHeaders[key]=value},this);for(let key in resHeaders)resHeaders.hasOwnProperty(key)&&res.header(key,resHeaders[key]);next()}),process.env.WEB_PUBLIC_PATH&&(webPublicPath=process.env.WEB_PUBLIC_PATH),webApp.use(webPublicPath,express.static(process.env.WEB_ROOT));let defaultStaticEntry=`${process.env.WEB_ROOT}/index.html`;existsSync(defaultStaticEntry)?webApp.use((req,res)=>{res.sendFile(defaultStaticEntry)}):webApp.use(webPublicPath,(req,res)=>{res.status(200).send(`Hi, welcome to web server entrance ui, you can test http proxy on browser console or api request tools. Examples as follows:<br />
117
117
  fetch("http://localhost:${process.env.WEB_PORT}/api/permission/auth/login", {
118
118
  method: 'post',
@@ -128,16 +128,16 @@ ${process.env.RESTARTED?"Restarting":"Starting"} up mock-server, serving `),colo
128
128
  \u{1F30D} mock-server version: `),colors.cyan(getPackageVersion()),`
129
129
  `].join("")),console.info(colors.yellow(`
130
130
  Mock server available on:
131
- `)),getServerUrls(process.env.PORT).forEach(url=>{console.info(" "+url.replace(String(process.env.PORT),colors.green(process.env.PORT)))}),console.info(" "+colors.blue("API Overview: ")+"http://localhost:"+colors.green(process.env.PORT)+colors.green("/__api-overview"))),process.env.OPEN_API_OVERVIEW&&!process.env.RESTARTED){let apiOverviewUrl=`http://localhost:${process.env.PORT}/__api-overview`;console.info(colors.yellow(`
132
- Opening API overview page...`));let openCommand;switch(process.platform){case"darwin":openCommand=`open ${apiOverviewUrl}`;break;case"win32":openCommand=`start ${apiOverviewUrl}`;break;case"linux":openCommand=`xdg-open ${apiOverviewUrl}`;break;default:console.warn(colors.yellow(`Could not automatically open browser. Please visit: ${apiOverviewUrl}`));return}exec(openCommand,error=>{error&&console.warn(colors.yellow(`Could not automatically open browser. Please visit: ${apiOverviewUrl}`))})}}),webApp&&!process.env.RESTARTED&&(webServer=webApp.listen(Number.parseInt(process.env.WEB_PORT,10),getServerHost(),()=>{console.info(colors.yellow(`
131
+ `)),getServerUrls(process.env.PORT).forEach(url=>{console.info(" "+url.replace(String(process.env.PORT),colors.green(process.env.PORT)))}),console.info(" "+colors.blue("API Overview: ")+"http://localhost:"+colors.green(process.env.PORT)+colors.green("/__api-overview"))),process.env.OPEN_API_OVERVIEW&&!webApp&&!process.env.RESTARTED){let apiOverviewUrl=`http://localhost:${process.env.PORT}/__api-overview`;console.info(colors.yellow(`
132
+ Opening API overview page...`));let openCommand;switch(process.platform){case"darwin":openCommand=`open ${apiOverviewUrl}`;break;case"win32":openCommand=`start ${apiOverviewUrl}`;break;case"linux":openCommand=`xdg-open ${apiOverviewUrl}`;break;default:console.warn(colors.yellow(`Could not automatically open browser. Please visit: ${apiOverviewUrl}`));return}exec(openCommand,error=>{error&&console.warn(colors.yellow(`Could not automatically open browser. Please visit: ${apiOverviewUrl}`))})}}),webApp&&!process.env.RESTARTED&&(webServer=webApp.listen(Number.parseInt(process.env.WEB_PORT,10),getServerHost(),()=>{if(console.info(colors.yellow(`
133
133
  Web server available on:
134
- `)),getServerUrls(process.env.WEB_PORT,webPublicPath).forEach(url=>{console.info(" "+url.replace(String(process.env.WEB_PORT),colors.green(process.env.WEB_PORT)))}),isEmptyObj(proxyTable)||(console.info(colors.yellow(`
135
- Enable proxy at web server on:`)),Object.keys(proxyTable).forEach(prefix=>{console.info(` ${prefix} -> ${proxyTable[prefix]}`)}))}))}function closeServer(server){return new Promise(resolve=>{if(!server||!server.listening)return resolve();server.close(()=>resolve()),typeof server.closeAllConnections=="function"&&server.closeAllConnections()})}async function shutdown(){if(!shuttingDown){shuttingDown=!0;try{socketServer?(await socketServer.close(),socketServer=null):await closeServer(httpServer),await closeServer(webServer)}finally{log.info(colors.red("mock-server process stopped.")),process.exit()}}}process.platform==="win32"&&require("readline").createInterface({input:process.stdin,output:process.stdout}).on("SIGINT",function(){process.emit("SIGINT")});process.once("SIGINT",shutdown);process.once("SIGTERM",shutdown);module2.exports={composeRouteFromJsFile,parseMockFiles}}});var require_staticServer=__commonJS({"src/lib/staticServer.js"(exports2,module2){var express=require_express2(),{closeSync,existsSync,lstatSync,openSync,promises:fsPromises,readFileSync,readSync}=require("fs"),path=require("path"),http=require("http"),https=require("https"),mime=require_mime(),{spawn}=require("child_process"),chokidar=require("chokidar"),{createProxyMiddleware}=require_dist(),colors=require_safe(),portfinder=require_portfinder(),{dateFormat,logger,getServerHost,getServerUrls,hostAllowlistMiddleware}=require_utils3(),log=logger(process.env.SILENT),argv=JSON.parse(process.env.ARGV),LIVE_RELOAD_PATH="/__mock-service-cli/live-reload",LIVE_RELOAD_CLIENT_PATH="/__mock-service-cli/live-reload.js",STATIC_FAVICON_PATH="/__mock-service-cli/favicon.svg",TEXT_SAMPLE_SIZE=8192;function isPlainObject(value){return!!value&&typeof value=="object"&&!Array.isArray(value)}function detectTextCharset(filePath,stats){if(stats.size===0)return"utf-8";let buffer=Buffer.allocUnsafe(Math.min(stats.size,TEXT_SAMPLE_SIZE)),fileDescriptor;try{fileDescriptor=openSync(filePath,"r");let bytesRead=readSync(fileDescriptor,buffer,0,buffer.length,0),sample=buffer.subarray(0,bytesRead);if(sample[0]===255&&sample[1]===254)return"utf-16le";if(sample[0]===254&&sample[1]===255)return"utf-16be";for(let byte of sample)if(byte===0||byte<9||byte>13&&byte<32)return null;return new TextDecoder("utf-8",{fatal:!0}).decode(sample),"utf-8"}catch{return null}finally{fileDescriptor!==void 0&&closeSync(fileDescriptor)}}function setStaticHeaders(res,filePath,stats){res.setHeader("Content-Disposition","inline");let contentType=mime.lookup(filePath);if(!contentType||contentType==="application/octet-stream"){let charset=detectTextCharset(filePath,stats);charset&&res.setHeader("Content-Type",`text/plain; charset=${charset}`)}}function parseHeaderList(value){return typeof value!="string"?{}:value.split(/\s*,\s*/).reduce((headers,item)=>{let separator=item.indexOf("=");return separator<=0||(headers[item.slice(0,separator).trim()]=item.slice(separator+1).trim()),headers},{})}function parseProxyOptions(){if(!process.env.PROXY_OPTIONS)return{};try{let value=JSON.parse(process.env.PROXY_OPTIONS);return isPlainObject(value)?value:{}}catch(error){throw new Error(`Invalid proxy options: ${error.message}`)}}function normalizePublicPath(value,label,allowEmptyRoot){if(typeof value!="string")throw new Error(`${label} must be a path`);if(!value&&allowEmptyRoot)return"/";if(!value)throw new Error(`${label} must be a non-empty path`);let normalized="/"+value.replace(/^\/+|\/+$/g,"");if(normalized!=="/"&&(normalized.includes("..")||normalized.includes("?")||normalized.includes("#")))throw new Error(`${label} must be a root-relative path`);return normalized}function normalizeAccessLog(value,label,configDir){if(value===void 0)return null;if(!isPlainObject(value))throw new Error(`${label}.accessLog must be an object`);let accessLog={};if(["success","failure"].forEach(name=>{if(value[name]!==void 0){if(typeof value[name]!="string"||!value[name])throw new Error(`${label}.accessLog.${name} must be a file path`);accessLog[name]=path.resolve(configDir,value[name])}}),Object.keys(accessLog).length===0)throw new Error(`${label}.accessLog requires success or failure`);return accessLog}function normalizeRequestHeaders(value,label){if(value===void 0)return{};if(!isPlainObject(value))throw new Error(`${label} must be an object`);return Object.entries(value).reduce((headers,[name,headerValue])=>{if(!name||headerValue===null||typeof headerValue=="object")throw new Error(`${label}.${name} must be a primitive value`);return headers[name]=String(headerValue),headers},{})}function normalizeApplicationOptions(value,label,configDir){if(value.cors!==void 0&&typeof value.cors!="boolean")throw new Error(`${label}.cors must be boolean`);if(value.headers!==void 0&&!isPlainObject(value.headers))throw new Error(`${label}.headers must be an object`);if(value.secure!==void 0&&typeof value.secure!="boolean")throw new Error(`${label}.secure must be boolean`);return{cors:value.cors===!0,headers:isPlainObject(value.headers)?value.headers:{},secure:value.secure===!0,requestHeaders:normalizeRequestHeaders(value.requestHeaders,`${label}.requestHeaders`),accessLog:normalizeAccessLog(value.accessLog,label,configDir)}}function normalizeSpaFallback(value,directory,label){if(value===void 0||value===!1)return!1;if(typeof value!="string"||!value||!value.startsWith("/")||value.includes(".."))throw new Error(`${label} must be a root-relative path`);if(!directory)throw new Error(`${label} requires an application directory`);let fallbackPath=getStaticPath(directory,value);if(!fallbackPath||!/\.html?$/i.test(fallbackPath))throw new Error(`${label} does not exist: ${value}`);return value}function normalizeProxyTable(value,label,allowStringValues){if(value===void 0)return{};if(!isPlainObject(value))throw new Error(`${label} must be an object`);return Object.entries(value).reduce((table,[prefix,rule])=>{let normalizedPrefix=normalizePublicPath(prefix,`${label} route`);if(Object.prototype.hasOwnProperty.call(table,normalizedPrefix))throw new Error(`Duplicate proxy route: ${normalizedPrefix}`);let target=rule,rewrite=!1,requestHeaders={};if(isPlainObject(rule)){if(target=rule.target,rewrite=rule.rewrite===!0,requestHeaders=normalizeRequestHeaders(rule.requestHeaders,`${label}[${prefix}].requestHeaders`),rule.rewrite!==void 0&&typeof rule.rewrite!="boolean")throw new Error(`${label}[${prefix}].rewrite must be boolean`)}else if(!allowStringValues||typeof rule!="string")throw new Error(`${label}[${prefix}] must contain target and rewrite`);if(typeof target!="string"||!/^https?:\/\//.test(target))throw new Error(`Invalid proxy target for ${prefix}`);return table[normalizedPrefix]={target,rewrite,requestHeaders},table},{})}function hasPathPrefix(prefix,requestPath){return prefix==="/"||requestPath===prefix||requestPath.startsWith(`${prefix}/`)}function validateMountPaths(mounts){if(mounts.filter(mount=>mount.path==="/").length>1)throw new Error("mounts can only contain one root path");let nonRootMounts=mounts.filter(mount=>mount.path!=="/");nonRootMounts.forEach((mount,index)=>{nonRootMounts.forEach((other,otherIndex)=>{if(index!==otherIndex&&hasPathPrefix(mount.path,other.path))throw new Error(`mounts paths cannot overlap: ${mount.path} and ${other.path}`)})})}function normalizeConfig(){let defaults={open:!1,browser:"default",watch:{ignore:["**/node_modules/**","**/.git/**"],delay:100,fullReload:!1},injectTag:"body",https:!1},cliDirectory=process.env.STATIC_DIRECTORY?path.resolve(process.env.STATIC_DIRECTORY):null;if(process.env.STATIC_CONFIG&&argv["spa-fallback"]!==void 0)throw new Error("--spa-fallback cannot be used with --static-config");let cliSpaFallback=process.env.STATIC_CONFIG?!1:normalizeSpaFallback(argv["spa-fallback"],cliDirectory,"spaFallback");if(!process.env.STATIC_CONFIG){if(!cliDirectory)throw new Error("Static server requires -R <directory> or --static-config <file>");if(!existsSync(cliDirectory)||!lstatSync(cliDirectory).isDirectory())throw new Error(`static-server: directory does not exist: ${cliDirectory}`);let cliProxy=normalizeProxyTable(parseProxyOptions(),"proxy",!0);return(argv.r||argv.rewrite)&&Object.values(cliProxy).forEach(rule=>rule.rewrite=!0),{...defaults,configDir:process.cwd(),mounts:[{path:"/",directory:cliDirectory,spaFallback:cliSpaFallback,proxy:cliProxy,cors:!1,headers:{},secure:!1,requestHeaders:{},accessLog:null}]}}let configPath=path.resolve(process.env.STATIC_CONFIG),supplied;try{supplied=JSON.parse(readFileSync(configPath,"utf8"))}catch(error){throw new Error(`Unable to read static config: ${error.message}`)}if(!isPlainObject(supplied))throw new Error("Static config must contain a JSON object");let configDir=path.dirname(configPath),watch=isPlainObject(supplied.watch)?supplied.watch:{};if(process.env.PROXY_OPTIONS)throw new Error("--proxy-options/--rewrite cannot be used with --static-config");let suppliedRootField=["directory","spaFallback","proxy","cors","headers","secure","requestHeaders","accessLog"].find(field=>supplied[field]!==void 0);if(suppliedRootField)throw new Error(`${suppliedRootField} must be declared on a mount in static config`);let mounts=supplied.mounts===void 0?[]:supplied.mounts;if(!Array.isArray(mounts))throw new Error("mounts must be an array");if(mounts.length===0)throw new Error("Static config requires at least one mount");let normalizedMounts=mounts.map((mount,index)=>{if(!isPlainObject(mount))throw new Error(`mounts[${index}] must be an object`);let mountPath=mount.path===void 0?"/":normalizePublicPath(mount.path,`mounts[${index}].path`,!0);if(mount.directory!==void 0&&typeof mount.directory!="string")throw new Error(`mounts[${index}].directory must be a string`);let directory=mount.directory===void 0?null:path.resolve(configDir,mount.directory);if(directory&&(!existsSync(directory)||!lstatSync(directory).isDirectory()))throw new Error(`Mount directory does not exist: ${directory}`);let normalizedMount={path:mountPath,directory,spaFallback:normalizeSpaFallback(mount.spaFallback,directory,`mounts[${index}].spaFallback`),proxy:normalizeProxyTable(mount.proxy,`mounts[${index}].proxy`,!1),...normalizeApplicationOptions(mount,`mounts[${index}]`,configDir)};if(!normalizedMount.directory&&Object.keys(normalizedMount.proxy).length===0)throw new Error(`mounts[${index}] requires directory or proxy`);if(normalizedMount.accessLog&&!normalizedMount.spaFallback)throw new Error(`mounts[${index}].accessLog requires spaFallback`);return normalizedMount});validateMountPaths(normalizedMounts);let httpsConfig=supplied.https,normalizedHttps=!1;if(httpsConfig===!0)throw new Error("https requires cert and key paths");if(isPlainObject(httpsConfig)&&httpsConfig.enable!==!1){if(typeof httpsConfig.cert!="string"||typeof httpsConfig.key!="string")throw new Error("https requires cert and key paths");normalizedHttps={cert:path.resolve(configDir,httpsConfig.cert),key:path.resolve(configDir,httpsConfig.key),passphrase:typeof httpsConfig.passphrase=="string"?httpsConfig.passphrase:void 0}}return{...defaults,open:supplied.open===void 0?defaults.open:supplied.open,browser:supplied.browser===void 0?defaults.browser:supplied.browser,configDir,watch:{ignore:Array.isArray(watch.ignore)?watch.ignore:defaults.watch.ignore,delay:Number.isFinite(watch.delay)&&watch.delay>=0?watch.delay:defaults.watch.delay,fullReload:watch.fullReload===!0},injectTag:supplied.injectTag==="head"?"head":"body",mounts:normalizedMounts,https:normalizedHttps}}function getStaticPath(root,requestPath){let pathname;try{pathname=decodeURIComponent(requestPath)}catch{return null}let candidate=path.resolve(root,`.${pathname}`),relative=path.relative(root,candidate);return relative.startsWith("..")||path.isAbsolute(relative)||!existsSync(candidate)||lstatSync(candidate).isDirectory()?null:candidate}function getStaticDirectory(root,requestPath){let pathname;try{pathname=decodeURIComponent(requestPath)}catch{return null}let candidate=path.resolve(root,`.${pathname}`),relative=path.relative(root,candidate);return relative.startsWith("..")||path.isAbsolute(relative)||!existsSync(candidate)?null:lstatSync(candidate).isDirectory()?candidate:null}function escapeHtml(value){return String(value).replace(/[&<>"']/g,character=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[character])}function isHiddenDirectoryEntry(entry){return entry.name.startsWith(".")&&entry.name!=="."&&entry.name!==".."}function joinPublicPath(basePath,localPath){return basePath==="/"?localPath:`${basePath}${localPath==="/"?"/":localPath}`.replace(/\/+/g,"/")}async function getDirectoryIndexData(directoryPath,requestPath,showHidden,basePath){let visibleEntries=(await fsPromises.readdir(directoryPath,{withFileTypes:!0})).filter(entry=>showHidden||!isHiddenDirectoryEntry(entry));visibleEntries.sort((left,right)=>left.isDirectory()!==right.isDirectory()?left.isDirectory()?-1:1:left.name.localeCompare(right.name));let decodedPath=decodeURIComponent(requestPath),normalizedPath=decodedPath==="/"?"/":`/${decodedPath.replace(/^\/+|\/+$/g,"")}/`,parentPath=normalizedPath==="/"?null:normalizedPath.split("/").slice(0,-2).join("/")||"/";return{currentPath:normalizedPath,parentPath,basePath,showHidden,entries:visibleEntries.map(entry=>({name:entry.name,isDirectory:entry.isDirectory(),isHidden:isHiddenDirectoryEntry(entry)}))}}function encodeDirectoryPath(directoryPath){return directoryPath==="/"?"/":`/${directoryPath.split("/").filter(Boolean).map(segment=>encodeURIComponent(segment)).join("/")}/`}function renderDirectoryIndex(data){let normalizedPath=data.currentPath,publicCurrentPath=joinPublicPath(data.basePath,normalizedPath),publicParentPath=data.parentPath?joinPublicPath(data.basePath,data.parentPath):null,encodedDirectoryPath=encodeDirectoryPath(publicCurrentPath),encodedApplicationRootPath=encodeDirectoryPath(joinPublicPath(data.basePath,"/")),withVisibility=url=>data.showHidden?`${url}?showHidden=1`:url,breadcrumbParts=normalizedPath.split("/").filter(Boolean),breadcrumbPath="",breadcrumb=[`<a href="${withVisibility(encodedApplicationRootPath)}">\u6839\u76EE\u5F55</a>`,...breadcrumbParts.map(part=>(breadcrumbPath+=`/${part}`,`<a href="${withVisibility(encodeDirectoryPath(joinPublicPath(data.basePath,breadcrumbPath)))}">${escapeHtml(part)}</a>`))].join('<span aria-hidden="true"> / </span>'),items=data.entries.map(entry=>{let suffix=entry.isDirectory?"/":"",href=`${encodedDirectoryPath}${encodeURIComponent(entry.name)}${suffix}`.replace(/\/+/g,"/"),target=entry.isDirectory?withVisibility(href):href;return`<li${entry.isHidden?' class="is-hidden"':""}><a href="${target}">${entry.isDirectory?"\u{1F4C1}":"\u{1F4C4}"} ${escapeHtml(entry.name)}${suffix}</a></li>`}).join(""),parent=data.parentPath?`<p id="directoryParent"><a href="${withVisibility(encodeDirectoryPath(publicParentPath))}">\u2190 \u8FD4\u56DE\u4E0A\u7EA7</a></p>`:'<p id="directoryParent" hidden></p>',visibilityToggle=`<a class="visibility-toggle" href="${data.showHidden?encodedDirectoryPath:`${encodedDirectoryPath}?showHidden=1`}">${data.showHidden?"\u9690\u85CF\u9690\u85CF\u9879\u76EE":"\u663E\u793A\u9690\u85CF\u9879\u76EE"}</a>`;return`<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><link rel="icon" type="image/svg+xml" href="${STATIC_FAVICON_PATH}"><title>\u76EE\u5F55\u7D22\u5F15 ${escapeHtml(publicCurrentPath)}</title><style>body{font:14px system-ui,sans-serif;margin:32px;max-width:900px}a{color:#2563eb;text-decoration:none}a:hover{text-decoration:underline}.directory-header{display:flex;align-items:center;gap:12px;margin:12px 0;flex-wrap:wrap}.directory-header h1{font-size:20px;margin:0}.directory-header nav{color:#4b5563;min-width:0;flex:1;overflow-wrap:anywhere}.directory-header nav span{padding:0 5px;color:#9ca3af}.visibility-toggle{color:#374151;border:1px solid #d1d5db;border-radius:4px;background:#f9fafb;padding:5px 8px;white-space:nowrap}.visibility-toggle:hover{background:#f3f4f6;text-decoration:none}.is-hidden{opacity:.55}ul{list-style:none;padding:0}li{padding:7px 0;border-bottom:1px solid #eee}</style></head><body><header class="directory-header"><h1>\u76EE\u5F55\u7D22\u5F15</h1><nav aria-label="\u8DEF\u5F84\u5BFC\u822A">${breadcrumb}</nav>${visibilityToggle}</header>${parent}<ul>${items||"<li>\uFF08\u7A7A\u76EE\u5F55\uFF09</li>"}</ul></body></html>`}function getLiveReloadClient(config){let delay=JSON.stringify(config.watch.delay),fullReload=JSON.stringify(config.watch.fullReload);return`(function(){const delay=${delay};const fullReload=${fullReload};let source;let timer;const dispose=function(){clearTimeout(timer);if(source){source.close();source=null}};const connect=function(){if(source)return;source=new EventSource('${LIVE_RELOAD_PATH}');source.onmessage=function(event){let change;try{change=JSON.parse(event.data)}catch(_){return}clearTimeout(timer);timer=setTimeout(function(){if(!fullReload&&change.type==='css'){const target=new URL(change.path,location.href).pathname;let updated=false;document.querySelectorAll('link[rel~="stylesheet"][href]').forEach(function(link){if(new URL(link.href,location.href).pathname===target){const url=new URL(link.href,location.href);url.searchParams.set('mock-service-cli-reload',Date.now());link.href=url.href;updated=true}});if(updated)return}location.reload()},delay)}};window.addEventListener('pagehide',dispose);window.addEventListener('pageshow',connect);connect()})();`}function injectLiveReload(html,config){if(!/<link\b[^>]*\brel\s*=\s*["'][^"']*\bicon\b[^"']*["'][^>]*>/i.test(html)){let favicon=`<link rel="icon" type="image/svg+xml" href="${STATIC_FAVICON_PATH}">`,headIndex=html.toLowerCase().lastIndexOf("</head>");html=headIndex===-1?`${favicon}${html}`:`${html.slice(0,headIndex)}${favicon}${html.slice(headIndex)}`}let script=`<script src="${LIVE_RELOAD_CLIENT_PATH}" data-mock-service-cli-live-reload="true"></script>`,closingTag=config.injectTag==="head"?"</head>":"</body>",index=html.toLowerCase().lastIndexOf(closingTag);return index===-1?`${html}${script}`:`${html.slice(0,index)}${script}${html.slice(index)}`}function openBrowser(url,browser){if(!browser||browser===!1)return;let command,args;if(isPlainObject(browser)){if(typeof browser.command!="string"||!browser.command)return;command=browser.command,args=Array.isArray(browser.args)?browser.args.map(String):[],args.push(url)}else browser!=="default"?(command=String(browser),args=[url]):process.platform==="darwin"?(command="open",args=[url]):process.platform==="win32"?(command="cmd",args=["/c","start","",url]):(command="xdg-open",args=[url]);spawn(command,args,{detached:!0,stdio:"ignore"}).unref()}function createStaticServer(config){let app=express(),cliHeaders=parseHeaderList(argv.A||argv["append-headers"]),clients=new Set,watchers=[],pendingChanges=[],reloadTimer=null,closing=!1,pendingLogWrites=new Set,applications=config.mounts.map(mount=>({...mount,basePath:mount.path})),rootApplication=applications.find(application=>application.basePath==="/"&&application.directory),root=rootApplication?rootApplication.directory:null;app.use(hostAllowlistMiddleware()),app.use((req,res,next)=>{Object.entries(cliHeaders).forEach(([key,value])=>res.setHeader(key,String(value))),next()});function applyApplicationOptions(application){return(req,res,next)=>(Object.entries({...application.headers,...cliHeaders}).forEach(([key,value])=>res.setHeader(key,String(value))),application.cors&&(res.setHeader("Access-Control-Allow-Origin","*"),res.setHeader("Access-Control-Allow-Methods","GET,HEAD,OPTIONS"),res.setHeader("Access-Control-Allow-Headers","*"),req.method==="OPTIONS")?res.status(204).end():next())}function writeAccessLog(application,req,res){if(!application.accessLog)return;let logFile=res.statusCode>=400?application.accessLog.failure:application.accessLog.success;if(!logFile)return;let entry=`${JSON.stringify({timestamp:new Date().toISOString(),application:application.basePath,method:req.method,url:req.originalUrl||req.url,status:res.statusCode})}
134
+ `)),getServerUrls(process.env.WEB_PORT,webPublicPath).forEach(url=>{console.info(" "+url.replace(String(process.env.WEB_PORT),colors.green(process.env.WEB_PORT)))}),process.env.OPEN_API_OVERVIEW){let webUrl=`http://localhost:${process.env.WEB_PORT}${webPublicPath==="/"?"/":webPublicPath}`,command=process.platform==="darwin"?"open":process.platform==="win32"?"cmd":"xdg-open",args=process.platform==="win32"?["/c","start","",webUrl]:[webUrl],child=spawn(command,args,{detached:!0,stdio:"ignore"});child.once("error",()=>console.warn(colors.yellow(`Could not automatically open browser. Please visit: ${webUrl}`))),child.unref()}isEmptyObj(proxyTable)||(console.info(colors.yellow(`
135
+ Enable proxy at web server on:`)),Object.keys(proxyTable).forEach(prefix=>{console.info(` ${prefix} -> ${proxyTable[prefix]}`)}))}))}function closeServer(server){return new Promise(resolve=>{if(!server||!server.listening)return resolve();server.close(()=>resolve()),typeof server.closeAllConnections=="function"&&server.closeAllConnections()})}async function shutdown(){if(!shuttingDown){shuttingDown=!0;try{socketServer?(await socketServer.close(),socketServer=null):await closeServer(httpServer),await closeServer(webServer)}finally{log.info(colors.red("mock-server process stopped.")),process.exit()}}}process.platform==="win32"&&require("readline").createInterface({input:process.stdin,output:process.stdout}).on("SIGINT",function(){process.emit("SIGINT")});process.once("SIGINT",shutdown);process.once("SIGTERM",shutdown);module2.exports={composeRouteFromJsFile,parseMockFiles}}});var require_staticServer=__commonJS({"src/lib/staticServer.js"(exports2,module2){var express=require_express2(),{closeSync,existsSync,lstatSync,openSync,promises:fsPromises,readFileSync,readSync}=require("fs"),path=require("path"),http=require("http"),https=require("https"),mime=require_mime(),{spawn}=require("child_process"),chokidar=require("chokidar"),{createProxyMiddleware}=require_dist(),colors=require_safe(),portfinder=require_portfinder(),{dateFormat,logger,getServerHost,getServerUrls,hostAllowlistMiddleware,isHiddenPath}=require_utils3(),log=logger(process.env.SILENT),argv=JSON.parse(process.env.ARGV),LIVE_RELOAD_PATH="/__mock-service-cli/live-reload",LIVE_RELOAD_CLIENT_PATH="/__mock-service-cli/live-reload.js",STATIC_FAVICON_PATH="/__mock-service-cli/favicon.svg",TEXT_SAMPLE_SIZE=8192;function isPlainObject(value){return!!value&&typeof value=="object"&&!Array.isArray(value)}function detectTextCharset(filePath,stats){if(stats.size===0)return"utf-8";let buffer=Buffer.allocUnsafe(Math.min(stats.size,TEXT_SAMPLE_SIZE)),fileDescriptor;try{fileDescriptor=openSync(filePath,"r");let bytesRead=readSync(fileDescriptor,buffer,0,buffer.length,0),sample=buffer.subarray(0,bytesRead);if(sample[0]===255&&sample[1]===254)return"utf-16le";if(sample[0]===254&&sample[1]===255)return"utf-16be";for(let byte of sample)if(byte===0||byte<9||byte>13&&byte<32)return null;return new TextDecoder("utf-8",{fatal:!0}).decode(sample),"utf-8"}catch{return null}finally{fileDescriptor!==void 0&&closeSync(fileDescriptor)}}function setStaticHeaders(res,filePath,stats){res.setHeader("Content-Disposition","inline");let contentType=mime.lookup(filePath);if(!contentType||contentType==="application/octet-stream"){let charset=detectTextCharset(filePath,stats);charset&&res.setHeader("Content-Type",`text/plain; charset=${charset}`)}}function parseHeaderList(value){return typeof value!="string"?{}:value.split(/\s*,\s*/).reduce((headers,item)=>{let separator=item.indexOf("=");return separator<=0||(headers[item.slice(0,separator).trim()]=item.slice(separator+1).trim()),headers},{})}function parseProxyOptions(){if(!process.env.PROXY_OPTIONS)return{};try{let value=JSON.parse(process.env.PROXY_OPTIONS);return isPlainObject(value)?value:{}}catch(error){throw new Error(`Invalid proxy options: ${error.message}`)}}function normalizePublicPath(value,label,allowEmptyRoot){if(typeof value!="string")throw new Error(`${label} must be a path`);if(!value&&allowEmptyRoot)return"/";if(!value)throw new Error(`${label} must be a non-empty path`);let normalized="/"+value.replace(/^\/+|\/+$/g,"");if(normalized!=="/"&&(normalized.includes("..")||normalized.includes("?")||normalized.includes("#")))throw new Error(`${label} must be a root-relative path`);return normalized}function normalizeAccessLog(value,label,configDir){if(value===void 0)return null;if(!isPlainObject(value))throw new Error(`${label}.accessLog must be an object`);let accessLog={};if(["success","failure"].forEach(name=>{if(value[name]!==void 0){if(typeof value[name]!="string"||!value[name])throw new Error(`${label}.accessLog.${name} must be a file path`);accessLog[name]=path.resolve(configDir,value[name])}}),Object.keys(accessLog).length===0)throw new Error(`${label}.accessLog requires success or failure`);return accessLog}function normalizeRequestHeaders(value,label){if(value===void 0)return{};if(!isPlainObject(value))throw new Error(`${label} must be an object`);return Object.entries(value).reduce((headers,[name,headerValue])=>{if(!name||headerValue===null||typeof headerValue=="object")throw new Error(`${label}.${name} must be a primitive value`);return headers[name]=String(headerValue),headers},{})}function normalizeApplicationOptions(value,label,configDir){if(value.cors!==void 0&&typeof value.cors!="boolean")throw new Error(`${label}.cors must be boolean`);if(value.headers!==void 0&&!isPlainObject(value.headers))throw new Error(`${label}.headers must be an object`);if(value.secure!==void 0&&typeof value.secure!="boolean")throw new Error(`${label}.secure must be boolean`);return{cors:value.cors===!0,headers:isPlainObject(value.headers)?value.headers:{},secure:value.secure===!0,requestHeaders:normalizeRequestHeaders(value.requestHeaders,`${label}.requestHeaders`),accessLog:normalizeAccessLog(value.accessLog,label,configDir)}}function normalizeSpaFallback(value,directory,label){if(value===void 0||value===!1)return!1;if(typeof value!="string"||!value||!value.startsWith("/")||value.includes(".."))throw new Error(`${label} must be a root-relative path`);if(!directory)throw new Error(`${label} requires an application directory`);let fallbackPath=getStaticPath(directory,value);if(!fallbackPath||!/\.html?$/i.test(fallbackPath))throw new Error(`${label} does not exist: ${value}`);return value}function normalizeProxyTable(value,label,allowStringValues){if(value===void 0)return{};if(!isPlainObject(value))throw new Error(`${label} must be an object`);return Object.entries(value).reduce((table,[prefix,rule])=>{let normalizedPrefix=normalizePublicPath(prefix,`${label} route`);if(Object.prototype.hasOwnProperty.call(table,normalizedPrefix))throw new Error(`Duplicate proxy route: ${normalizedPrefix}`);let target=rule,rewrite=!1,requestHeaders={};if(isPlainObject(rule)){if(target=rule.target,rewrite=rule.rewrite===!0,requestHeaders=normalizeRequestHeaders(rule.requestHeaders,`${label}[${prefix}].requestHeaders`),rule.rewrite!==void 0&&typeof rule.rewrite!="boolean")throw new Error(`${label}[${prefix}].rewrite must be boolean`)}else if(!allowStringValues||typeof rule!="string")throw new Error(`${label}[${prefix}] must contain target and rewrite`);if(typeof target!="string"||!/^https?:\/\//.test(target))throw new Error(`Invalid proxy target for ${prefix}`);return table[normalizedPrefix]={target,rewrite,requestHeaders},table},{})}function hasPathPrefix(prefix,requestPath){return prefix==="/"||requestPath===prefix||requestPath.startsWith(`${prefix}/`)}function validateMountPaths(mounts){if(mounts.filter(mount=>mount.path==="/").length>1)throw new Error("mounts can only contain one root path");let nonRootMounts=mounts.filter(mount=>mount.path!=="/");nonRootMounts.forEach((mount,index)=>{nonRootMounts.forEach((other,otherIndex)=>{if(index!==otherIndex&&hasPathPrefix(mount.path,other.path))throw new Error(`mounts paths cannot overlap: ${mount.path} and ${other.path}`)})})}function normalizeConfig(){let defaults={open:!1,browser:"default",watch:{ignore:["**/node_modules/**","**/.git/**"],delay:100,fullReload:!1,depth:void 0},injectTag:"body",https:!1};if(process.env.WATCH_DEPTH!==void 0){let cliDepth=Number(process.env.WATCH_DEPTH);if(!Number.isInteger(cliDepth)||cliDepth<0)throw new Error("watch.depth must be a non-negative integer")}let cliDirectory=process.env.STATIC_DIRECTORY?path.resolve(process.env.STATIC_DIRECTORY):null;if(process.env.STATIC_CONFIG&&argv["spa-fallback"]!==void 0)throw new Error("--spa-fallback cannot be used with --static-config");let cliSpaFallback=process.env.STATIC_CONFIG?!1:normalizeSpaFallback(argv["spa-fallback"],cliDirectory,"spaFallback");if(!process.env.STATIC_CONFIG){if(!cliDirectory)throw new Error("Static server requires -R <directory> or --static-config <file>");if(!existsSync(cliDirectory)||!lstatSync(cliDirectory).isDirectory())throw new Error(`static-server: directory does not exist: ${cliDirectory}`);let cliProxy=normalizeProxyTable(parseProxyOptions(),"proxy",!0);return(argv.r||argv.rewrite)&&Object.values(cliProxy).forEach(rule=>rule.rewrite=!0),{...defaults,open:process.env.OPEN_API_OVERVIEW?!0:defaults.open,watch:{...defaults.watch,depth:process.env.WATCH_DEPTH===void 0?void 0:Number(process.env.WATCH_DEPTH)},configDir:process.cwd(),mounts:[{path:"/",directory:cliDirectory,spaFallback:cliSpaFallback,proxy:cliProxy,cors:!1,headers:{},secure:!1,requestHeaders:{},accessLog:null}]}}let configPath=path.resolve(process.env.STATIC_CONFIG),supplied;try{supplied=JSON.parse(readFileSync(configPath,"utf8"))}catch(error){throw new Error(`Unable to read static config: ${error.message}`)}if(!isPlainObject(supplied))throw new Error("Static config must contain a JSON object");let configDir=path.dirname(configPath),watch=isPlainObject(supplied.watch)?supplied.watch:{},depthValue=process.env.WATCH_DEPTH!==void 0?Number(process.env.WATCH_DEPTH):watch.depth;if(depthValue!==void 0&&(!Number.isInteger(depthValue)||depthValue<0))throw new Error("watch.depth must be a non-negative integer");if(process.env.PROXY_OPTIONS)throw new Error("--proxy-options/--rewrite cannot be used with --static-config");let suppliedRootField=["directory","spaFallback","proxy","cors","headers","secure","requestHeaders","accessLog"].find(field=>supplied[field]!==void 0);if(suppliedRootField)throw new Error(`${suppliedRootField} must be declared on a mount in static config`);let mounts=supplied.mounts===void 0?[]:supplied.mounts;if(!Array.isArray(mounts))throw new Error("mounts must be an array");if(mounts.length===0)throw new Error("Static config requires at least one mount");let normalizedMounts=mounts.map((mount,index)=>{if(!isPlainObject(mount))throw new Error(`mounts[${index}] must be an object`);let mountPath=mount.path===void 0?"/":normalizePublicPath(mount.path,`mounts[${index}].path`,!0);if(mount.directory!==void 0&&typeof mount.directory!="string")throw new Error(`mounts[${index}].directory must be a string`);let directory=mount.directory===void 0?null:path.resolve(configDir,mount.directory);if(directory&&(!existsSync(directory)||!lstatSync(directory).isDirectory()))throw new Error(`Mount directory does not exist: ${directory}`);let normalizedMount={path:mountPath,directory,spaFallback:normalizeSpaFallback(mount.spaFallback,directory,`mounts[${index}].spaFallback`),proxy:normalizeProxyTable(mount.proxy,`mounts[${index}].proxy`,!1),...normalizeApplicationOptions(mount,`mounts[${index}]`,configDir)};if(!normalizedMount.directory&&Object.keys(normalizedMount.proxy).length===0)throw new Error(`mounts[${index}] requires directory or proxy`);if(normalizedMount.accessLog&&!normalizedMount.spaFallback)throw new Error(`mounts[${index}].accessLog requires spaFallback`);return normalizedMount});validateMountPaths(normalizedMounts);let httpsConfig=supplied.https,normalizedHttps=!1;if(httpsConfig===!0)throw new Error("https requires cert and key paths");if(isPlainObject(httpsConfig)&&httpsConfig.enable!==!1){if(typeof httpsConfig.cert!="string"||typeof httpsConfig.key!="string")throw new Error("https requires cert and key paths");normalizedHttps={cert:path.resolve(configDir,httpsConfig.cert),key:path.resolve(configDir,httpsConfig.key),passphrase:typeof httpsConfig.passphrase=="string"?httpsConfig.passphrase:void 0}}return{...defaults,open:process.env.OPEN_API_OVERVIEW?supplied.open||!0:supplied.open===void 0?defaults.open:supplied.open,browser:supplied.browser===void 0?defaults.browser:supplied.browser,configDir,watch:{ignore:Array.isArray(watch.ignore)?watch.ignore:defaults.watch.ignore,delay:Number.isFinite(watch.delay)&&watch.delay>=0?watch.delay:defaults.watch.delay,fullReload:watch.fullReload===!0,depth:depthValue},injectTag:supplied.injectTag==="head"?"head":"body",mounts:normalizedMounts,https:normalizedHttps}}function getStaticPath(root,requestPath){let pathname;try{pathname=decodeURIComponent(requestPath)}catch{return null}let candidate=path.resolve(root,`.${pathname}`),relative=path.relative(root,candidate);return relative.startsWith("..")||path.isAbsolute(relative)||!existsSync(candidate)||lstatSync(candidate).isDirectory()?null:candidate}function getStaticDirectory(root,requestPath){let pathname;try{pathname=decodeURIComponent(requestPath)}catch{return null}let candidate=path.resolve(root,`.${pathname}`),relative=path.relative(root,candidate);return relative.startsWith("..")||path.isAbsolute(relative)||!existsSync(candidate)?null:lstatSync(candidate).isDirectory()?candidate:null}function escapeHtml(value){return String(value).replace(/[&<>"']/g,character=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[character])}function joinPublicPath(basePath,localPath){return basePath==="/"?localPath:`${basePath}${localPath==="/"?"/":localPath}`.replace(/\/+/g,"/")}async function getDirectoryIndexData(directoryPath,requestPath,showHidden,basePath){let visibleEntries=(await fsPromises.readdir(directoryPath,{withFileTypes:!0})).map(entry=>({entry,hidden:isHiddenPath(path.join(directoryPath,entry.name))})).filter(item=>showHidden||!item.hidden);visibleEntries.sort((left,right)=>left.entry.isDirectory()!==right.entry.isDirectory()?left.entry.isDirectory()?-1:1:left.entry.name.localeCompare(right.entry.name));let decodedPath=decodeURIComponent(requestPath),normalizedPath=decodedPath==="/"?"/":`/${decodedPath.replace(/^\/+|\/+$/g,"")}/`,parentPath=normalizedPath==="/"?null:normalizedPath.split("/").slice(0,-2).join("/")||"/";return{currentPath:normalizedPath,parentPath,basePath,showHidden,entries:visibleEntries.map(({entry,hidden})=>({name:entry.name,isDirectory:entry.isDirectory(),isHidden:hidden}))}}function encodeDirectoryPath(directoryPath){return directoryPath==="/"?"/":`/${directoryPath.split("/").filter(Boolean).map(segment=>encodeURIComponent(segment)).join("/")}/`}function renderDirectoryIndex(data){let normalizedPath=data.currentPath,publicCurrentPath=joinPublicPath(data.basePath,normalizedPath),publicParentPath=data.parentPath?joinPublicPath(data.basePath,data.parentPath):null,encodedDirectoryPath=encodeDirectoryPath(publicCurrentPath),encodedApplicationRootPath=encodeDirectoryPath(joinPublicPath(data.basePath,"/")),withVisibility=url=>data.showHidden?`${url}?showHidden=1`:url,breadcrumbParts=normalizedPath.split("/").filter(Boolean),breadcrumbPath="",breadcrumb=[`<a href="${withVisibility(encodedApplicationRootPath)}">\u6839\u76EE\u5F55</a>`,...breadcrumbParts.map(part=>(breadcrumbPath+=`/${part}`,`<a href="${withVisibility(encodeDirectoryPath(joinPublicPath(data.basePath,breadcrumbPath)))}">${escapeHtml(part)}</a>`))].join('<span aria-hidden="true"> / </span>'),items=data.entries.map(entry=>{let suffix=entry.isDirectory?"/":"",href=`${encodedDirectoryPath}${encodeURIComponent(entry.name)}${suffix}`.replace(/\/+/g,"/"),target=entry.isDirectory?withVisibility(href):href;return`<li${entry.isHidden?' class="is-hidden"':""}><a href="${target}">${entry.isDirectory?"\u{1F4C1}":"\u{1F4C4}"} ${escapeHtml(entry.name)}${suffix}</a></li>`}).join(""),parent=data.parentPath?`<p id="directoryParent"><a href="${withVisibility(encodeDirectoryPath(publicParentPath))}">\u2190 \u8FD4\u56DE\u4E0A\u7EA7</a></p>`:'<p id="directoryParent" hidden></p>',visibilityToggle=`<a class="visibility-toggle" href="${data.showHidden?encodedDirectoryPath:`${encodedDirectoryPath}?showHidden=1`}">${data.showHidden?"\u9690\u85CF\u9690\u85CF\u9879\u76EE":"\u663E\u793A\u9690\u85CF\u9879\u76EE"}</a>`;return`<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><link rel="icon" type="image/svg+xml" href="${STATIC_FAVICON_PATH}"><title>\u76EE\u5F55\u7D22\u5F15 ${escapeHtml(publicCurrentPath)}</title><style>body{font:14px system-ui,sans-serif;margin:32px;max-width:900px}a{color:#2563eb;text-decoration:none}a:hover{text-decoration:underline}.directory-header{display:flex;align-items:center;gap:12px;margin:12px 0;flex-wrap:wrap}.directory-header h1{font-size:20px;margin:0}.directory-header nav{color:#4b5563;min-width:0;flex:1;overflow-wrap:anywhere}.directory-header nav span{padding:0 5px;color:#9ca3af}.visibility-toggle{color:#374151;border:1px solid #d1d5db;border-radius:4px;background:#f9fafb;padding:5px 8px;white-space:nowrap}.visibility-toggle:hover{background:#f3f4f6;text-decoration:none}.is-hidden{opacity:.55}ul{list-style:none;padding:0}li{padding:7px 0;border-bottom:1px solid #eee}</style></head><body><header class="directory-header"><h1>\u76EE\u5F55\u7D22\u5F15</h1><nav aria-label="\u8DEF\u5F84\u5BFC\u822A">${breadcrumb}</nav>${visibilityToggle}</header>${parent}<ul>${items||"<li>\uFF08\u7A7A\u76EE\u5F55\uFF09</li>"}</ul></body></html>`}function getLiveReloadClient(config){let delay=JSON.stringify(config.watch.delay),fullReload=JSON.stringify(config.watch.fullReload);return`(function(){const delay=${delay};const fullReload=${fullReload};let source;let timer;const dispose=function(){clearTimeout(timer);if(source){source.close();source=null}};const connect=function(){if(source)return;source=new EventSource('${LIVE_RELOAD_PATH}');source.onmessage=function(event){let change;try{change=JSON.parse(event.data)}catch(_){return}clearTimeout(timer);timer=setTimeout(function(){if(!fullReload&&change.type==='css'){const target=new URL(change.path,location.href).pathname;let updated=false;document.querySelectorAll('link[rel~="stylesheet"][href]').forEach(function(link){if(new URL(link.href,location.href).pathname===target){const url=new URL(link.href,location.href);url.searchParams.set('mock-service-cli-reload',Date.now());link.href=url.href;updated=true}});if(updated)return}location.reload()},delay)}};window.addEventListener('pagehide',dispose);window.addEventListener('pageshow',connect);connect()})();`}function injectLiveReload(html,config){if(!/<link\b[^>]*\brel\s*=\s*["'][^"']*\bicon\b[^"']*["'][^>]*>/i.test(html)){let favicon=`<link rel="icon" type="image/svg+xml" href="${STATIC_FAVICON_PATH}">`,headIndex=html.toLowerCase().lastIndexOf("</head>");html=headIndex===-1?`${favicon}${html}`:`${html.slice(0,headIndex)}${favicon}${html.slice(headIndex)}`}let script=`<script src="${LIVE_RELOAD_CLIENT_PATH}" data-mock-service-cli-live-reload="true"></script>`,closingTag=config.injectTag==="head"?"</head>":"</body>",index=html.toLowerCase().lastIndexOf(closingTag);return index===-1?`${html}${script}`:`${html.slice(0,index)}${script}${html.slice(index)}`}function openBrowser(url,browser){if(!browser||browser===!1)return;let command,args;if(isPlainObject(browser)){if(typeof browser.command!="string"||!browser.command)return;command=browser.command,args=Array.isArray(browser.args)?browser.args.map(String):[],args.push(url)}else browser!=="default"?(command=String(browser),args=[url]):process.platform==="darwin"?(command="open",args=[url]):process.platform==="win32"?(command="cmd",args=["/c","start","",url]):(command="xdg-open",args=[url]);spawn(command,args,{detached:!0,stdio:"ignore"}).unref()}function createStaticServer(config){let app=express(),cliHeaders=parseHeaderList(argv.A||argv["append-headers"]),clients=new Set,watchers=[],pendingChanges=[],reloadTimer=null,closing=!1,pendingLogWrites=new Set,applications=config.mounts.map(mount=>({...mount,basePath:mount.path})),rootApplication=applications.find(application=>application.basePath==="/"&&application.directory),root=rootApplication?rootApplication.directory:null;app.use(hostAllowlistMiddleware()),app.use((req,res,next)=>{Object.entries(cliHeaders).forEach(([key,value])=>res.setHeader(key,String(value))),next()});function applyApplicationOptions(application){return(req,res,next)=>(Object.entries({...application.headers,...cliHeaders}).forEach(([key,value])=>res.setHeader(key,String(value))),application.cors&&(res.setHeader("Access-Control-Allow-Origin","*"),res.setHeader("Access-Control-Allow-Methods","GET,HEAD,OPTIONS"),res.setHeader("Access-Control-Allow-Headers","*"),req.method==="OPTIONS")?res.status(204).end():next())}function writeAccessLog(application,req,res){if(!application.accessLog)return;let logFile=res.statusCode>=400?application.accessLog.failure:application.accessLog.success;if(!logFile)return;let entry=`${JSON.stringify({timestamp:new Date().toISOString(),application:application.basePath,method:req.method,url:req.originalUrl||req.url,status:res.statusCode})}
136
136
  `,write=fsPromises.mkdir(path.dirname(logFile),{recursive:!0}).then(()=>fsPromises.appendFile(logFile,entry,"utf8")).catch(error=>log.info(colors.red(`static-server access log failed: ${error.message}`)));pendingLogWrites.add(write),write.finally(()=>pendingLogWrites.delete(write))}function createAccessLogMiddleware(application){return application.accessLog?(req,res,next)=>{res.once("finish",()=>writeAccessLog(application,req,res)),next()}:(_req,_res,next)=>next()}app.get(LIVE_RELOAD_PATH,(req,res)=>{res.status(200).set({"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"}),res.flushHeaders(),res.write(`retry: 1000
137
137
 
138
138
  `),clients.add(res);let removeClient=()=>clients.delete(res);req.once("close",removeClient),res.once("close",removeClient)}),app.get(LIVE_RELOAD_CLIENT_PATH,(req,res)=>{res.type("application/javascript").set("Cache-Control","no-store").send(getLiveReloadClient(config))}),app.get(STATIC_FAVICON_PATH,(req,res)=>{res.sendFile(path.resolve(__dirname,"./favicon-static-server.svg"))});let proxyRoutes=[],proxyOwners=new Map;applications.forEach(application=>{Object.entries(application.proxy||{}).forEach(([prefix,rule])=>{if(proxyOwners.has(prefix))throw new Error(`Duplicate proxy route: ${prefix}`);proxyOwners.set(prefix,application.basePath),proxyRoutes.push({prefix,application,...rule})})}),proxyRoutes.sort((left,right)=>right.prefix.length-left.prefix.length),proxyRoutes.forEach(route=>{let pathRewrite=route.rewrite?requestPath=>route.prefix==="/"?requestPath:requestPath===route.prefix?"/":requestPath.startsWith(`${route.prefix}/`)?requestPath.slice(route.prefix.length)||"/":requestPath:void 0;app.use(route.prefix,applyApplicationOptions(route.application),createAccessLogMiddleware(route.application),createProxyMiddleware({target:route.target,changeOrigin:!0,ws:!0,secure:route.application.secure,headers:{...route.application.requestHeaders,...route.requestHeaders},pathRewrite}))});let sendHtml=async(filePath,res,next)=>{try{let html=await fsPromises.readFile(filePath,"utf8");res.type("html").send(injectLiveReload(html,config))}catch(error){next(error)}};function createApplicationRouter(application){let router=express.Router();if(router.use(applyApplicationOptions(application)),router.use(createAccessLogMiddleware(application)),router.get("*",async(req,res,next)=>{if(req.path.startsWith("/__mock-service-cli/"))return next();let filePath=getStaticPath(application.directory,req.path);if(filePath&&/\.html?$/i.test(filePath))return sendHtml(filePath,res,next);if(!application.spaFallback){let directoryPath=getStaticDirectory(application.directory,req.path);if(directoryPath)try{let data=await getDirectoryIndexData(directoryPath,req.path,req.query.showHidden==="1",application.basePath);return res.type("html").set("Cache-Control","no-store").send(injectLiveReload(renderDirectoryIndex(data),config))}catch(error){return next(error)}}next()}),router.use(express.static(application.directory,{dotfiles:"allow",index:!1,redirect:!1,setHeaders:setStaticHeaders})),application.spaFallback){let fallbackPath=getStaticPath(application.directory,application.spaFallback);if(!fallbackPath||!/\.html?$/i.test(fallbackPath))throw new Error(`SPA fallback does not exist: ${application.spaFallback}`);router.get("*",(req,res,next)=>{if(req.path.startsWith("/__mock-service-cli/"))return next();sendHtml(fallbackPath,res,next)})}return router}applications.filter(application=>application.basePath!=="/"&&application.directory).forEach(application=>{let router=createApplicationRouter(application);app.use(application.basePath,(req,res,next)=>{router.handle(req,res,error=>{if(error)return next(error);if(!res.headersSent)return res.status(404).send("Not Found")})})}),rootApplication&&app.use(createApplicationRouter(rootApplication)),app.use((req,res)=>res.status(404).send("Not Found")),app.use((error,req,res,_next)=>{log.info(colors.red(`static-server request failed: ${error.message}`)),res.status(500).send("Static server request failed")});function toUrlPath(changedPath){let mount=config.mounts.find(item=>{if(!item.directory)return!1;let relative=path.relative(item.directory,changedPath);return!relative.startsWith("..")&&!path.isAbsolute(relative)});if(mount){let relative=path.relative(mount.directory,changedPath).split(path.sep).join("/");return`${mount.path.replace(/\/$/,"")}/${relative}`.replace(/\/+/g,"/")}if(root){let rootRelative=path.relative(root,changedPath);if(!rootRelative.startsWith("..")&&!path.isAbsolute(rootRelative))return`/${rootRelative.split(path.sep).join("/")}`}return"/"}function notifyClients(){let changes=pendingChanges;pendingChanges=[];let cssOnly=changes.length>0&&changes.every(change=>/\.css$/i.test(change)),payload=JSON.stringify({type:!config.watch.fullReload&&cssOnly?"css":"reload",path:changes[0]||"/"});clients.forEach(client=>client.write(`data: ${payload}
139
139
 
140
- `))}function scheduleReload(changedPath){pendingChanges.push(toUrlPath(changedPath)),clearTimeout(reloadTimer),reloadTimer=setTimeout(notifyClients,config.watch.delay)}function startWatchers(){let targets=[...new Set(applications.map(application=>application.directory).filter(Boolean))];if(targets.length===0)return Promise.resolve();let usePolling=process.platform==="win32"&&Number.parseInt(process.versions.node,10)>=24,watcher=chokidar.watch(targets,{ignoreInitial:!0,ignored:config.watch.ignore,usePolling,interval:usePolling?250:void 0,binaryInterval:usePolling?250:void 0,awaitWriteFinish:{stabilityThreshold:Math.max(config.watch.delay,50),pollInterval:20}});return watcher.on("all",(event,changedPath)=>{["add","change","unlink","addDir","unlinkDir"].includes(event)&&scheduleReload(changedPath)}),watchers.push(watcher),new Promise((resolve,reject)=>{let ready=!1;watcher.once("ready",()=>{ready=!0,resolve()}),watcher.on("error",error=>{log.info(colors.red(`static-server watcher failed: ${error.message}`)),ready||reject(error)})})}let server=config.https?https.createServer({cert:readFileSync(config.https.cert),key:readFileSync(config.https.key),passphrase:config.https.passphrase},app):http.createServer(app);return server.on("close",()=>clients.clear()),{server,root,protocol:config.https?"https":"http",proxyRoutes,startWatchers,close:async()=>{closing||(closing=!0,clearTimeout(reloadTimer),clients.forEach(client=>client.end()),await Promise.all(watchers.map(watcher=>watcher.close())),await Promise.all([...pendingLogWrites]),await new Promise(resolve=>{if(!server.listening)return resolve();server.close(resolve),typeof server.closeAllConnections=="function"&&server.closeAllConnections()}))}}}function startServer(){let config=normalizeConfig(),instance=createStaticServer(config),port=Number.parseInt(process.env.PORT,10),shuttingDown=!1,shutdown=()=>{shuttingDown||(shuttingDown=!0,instance.close().finally(()=>{log.info(colors.red("static-server process stopped.")),process.exit()}))};process.once("SIGINT",shutdown),process.once("SIGTERM",shutdown),process.platform==="win32"&&require("readline").createInterface({input:process.stdin,output:process.stdout}).on("SIGINT",function(){process.emit("SIGINT")}),instance.startWatchers().then(()=>{shuttingDown||instance.server.listen(port,getServerHost(),()=>{let urls=getServerUrls(port).map(url=>url.replace(/^http:/,`${instance.protocol}:`));if(console.info([colors.yellow(`
140
+ `))}function scheduleReload(changedPath){pendingChanges.push(toUrlPath(changedPath)),clearTimeout(reloadTimer),reloadTimer=setTimeout(notifyClients,config.watch.delay)}function startWatchers(){let targets=[...new Set(applications.map(application=>application.directory).filter(Boolean))];if(targets.length===0)return Promise.resolve();let usePolling=process.platform==="win32"&&Number.parseInt(process.versions.node,10)>=24,watcher=chokidar.watch(targets,{ignoreInitial:!0,ignored:config.watch.ignore,depth:config.watch.depth,usePolling,interval:usePolling?250:void 0,binaryInterval:usePolling?250:void 0,awaitWriteFinish:{stabilityThreshold:Math.max(config.watch.delay,50),pollInterval:20}});return watcher.on("all",(event,changedPath)=>{["add","change","unlink","addDir","unlinkDir"].includes(event)&&scheduleReload(changedPath)}),watchers.push(watcher),new Promise((resolve,reject)=>{let ready=!1;watcher.once("ready",()=>{ready=!0,resolve()}),watcher.on("error",error=>{log.info(colors.red(`static-server watcher failed: ${error.message}`)),ready||reject(error)})})}let server=config.https?https.createServer({cert:readFileSync(config.https.cert),key:readFileSync(config.https.key),passphrase:config.https.passphrase},app):http.createServer(app);return server.on("close",()=>clients.clear()),{server,root,protocol:config.https?"https":"http",proxyRoutes,startWatchers,close:async()=>{closing||(closing=!0,clearTimeout(reloadTimer),clients.forEach(client=>client.end()),await Promise.all(watchers.map(watcher=>watcher.close())),await Promise.all([...pendingLogWrites]),await new Promise(resolve=>{if(!server.listening)return resolve();server.close(resolve),typeof server.closeAllConnections=="function"&&server.closeAllConnections()}))}}}function startServer(){let config=normalizeConfig(),instance=createStaticServer(config),port=Number.parseInt(process.env.PORT,10),shuttingDown=!1,shutdown=()=>{shuttingDown||(shuttingDown=!0,instance.close().finally(()=>{log.info(colors.red("static-server process stopped.")),process.exit()}))};process.once("SIGINT",shutdown),process.once("SIGTERM",shutdown),process.platform==="win32"&&require("readline").createInterface({input:process.stdin,output:process.stdout}).on("SIGINT",function(){process.emit("SIGINT")}),instance.startWatchers().then(()=>{shuttingDown||instance.server.listen(port,getServerHost(),()=>{let urls=getServerUrls(port).map(url=>url.replace(/^http:/,`${instance.protocol}:`));if(console.info([colors.yellow(`
141
141
  Starting up Static Server, serving `),colors.cyan(instance.root||config.configDir),colors.yellow(` ${dateFormat("YYYY-mm-dd HH:MM:SS",new Date)}`)].join("")),console.info(colors.yellow(`
142
142
  Static Server available on:
143
143
  `)),urls.forEach(url=>console.info(" "+url.replace(String(port),colors.green(port)))),instance.proxyRoutes.length>0&&(log.info(colors.yellow(`
@@ -153,8 +153,8 @@ Starting up Static Server, serving `),colors.cyan(instance.root||config.configDi
153
153
  [...extracted.files];
154
154
  parentPort.postMessage({ success: true });
155
155
  })().catch(error => parentPort.postMessage({ error: error.message }));
156
- `;function isArchivePath(filePath){return hasArchiveExtension(filePath,extensions)}function isCompressedTar(filePath){return/\.(tar\.gz|tgz|tar\.bz2|tbz|tbz2|tar\.xz|txz)$/i.test(filePath)}function parse7ZipList(output){let separator=output.indexOf("----------");return separator<0?[]:output.slice(separator+10).split(/\r?\n\r?\n/).map(block=>{let values={};return block.split(/\r?\n/).forEach(line=>{let index=line.indexOf(" = ");index>0&&(values[line.slice(0,index)]=line.slice(index+3))}),values}).filter(values=>values.Path).map(values=>({path:values.Path.replace(/\\/g,"/"),isDirectory:values.Folder==="+"||String(values.Attributes||"").startsWith("D"),size:Number(values.Size||0),packedSize:Number(values["Packed Size"]||0),encrypted:values.Encrypted==="+",modified:values.Modified||null,attributes:values.Attributes||""}))}function run7Zip(args,onProcess){return new Promise((resolve,reject)=>{try{process.platform!=="win32"&&chmodSync(path7za,493)}catch(error){return reject(createArchiveError(`Unable to prepare bundled 7-Zip binary: ${error.message}`,500))}let child=spawn(path7za,args,{stdio:["ignore","pipe","pipe"]}),stderr="",stdout="";onProcess&&onProcess(child),child.stdout.on("data",chunk=>{stdout+=chunk.toString()}),child.stderr.on("data",chunk=>{stderr+=chunk.toString()}),child.once("error",reject),child.once("close",code=>{if(code===0)return resolve(stdout);reject(createArchiveError(stderr.trim()||`7-Zip exited with code ${code}`,422))})})}async function list7Zip(fullPath){let output=await run7Zip(["l","-slt","--",fullPath]),entries=parse7ZipList(output);if(!isCompressedTar(fullPath))return entries;let tempRoot=await fsPromises.mkdtemp(path.join(os.tmpdir(),"mock-service-cli-archive-list-"));try{await run7Zip(["e","-y",`-o${tempRoot}`,"--",fullPath]);let tarName=(await fsPromises.readdir(tempRoot)).find(name=>/\.tar$/i.test(name));return tarName?await list7Zip(path.join(tempRoot,tarName)):entries}finally{rmSync(tempRoot,{recursive:!0,force:!0})}}async function listRar(fullPath){let list=(await createExtractorFromFile({filepath:fullPath})).getFileList();if(list.arcHeader.flags&&list.arcHeader.flags.headerEncrypted)throw createArchiveError("Encrypted archives are not supported",422);return[...list.fileHeaders].map(header=>({path:header.name.replace(/\\/g,"/"),isDirectory:!!(header.flags&&header.flags.directory),size:Number(header.unpSize||0),packedSize:Number(header.packSize||0),encrypted:!!(header.flags&&header.flags.encrypted),modified:header.time||null,attributes:""}))}async function listEntries(fullPath){return path.extname(fullPath).toLowerCase()===".rar"?listRar(fullPath):list7Zip(fullPath)}async function extractRar(job,sourcePath,targetPath){await new Promise((resolve,reject)=>{let worker=new Worker(RAR_EXTRACT_WORKER,{eval:!0,workerData:{sourcePath,targetPath}}),settled=!1,finish=(callback,value)=>{settled||(settled=!0,job.child=null,callback(value))};job.child={kill:()=>worker.terminate()},worker.on("message",message=>{message&&message.success?finish(resolve):finish(reject,createArchiveError(message&&message.error||"RAR extraction failed",422))}),worker.on("error",error=>finish(reject,error)),worker.on("exit",code=>{if(!settled&&code!==0){let message=job.cancelled?"Archive job cancelled":"RAR extraction stopped";finish(reject,createArchiveError(message,499))}})})}async function extract(job,sourcePath,targetPath){if(path.extname(sourcePath).toLowerCase()===".rar")return extractRar(job,sourcePath,targetPath);await run7Zip(["x","-y",`-o${targetPath}`,"--",sourcePath],child=>{job.child=child})}module2.exports={capabilities,extract,isArchivePath,listEntries}}});var require_archiveService=__commonJS({"src/lib/archiveService.js"(exports2,module2){var{createWriteStream,existsSync,lstatSync,mkdirSync,promises:fsPromises,realpathSync,renameSync,rmSync}=require("fs"),path=require("path"),crypto=require("crypto"),archiver=require("archiver"),archiveProvider=require_ultra(),{createArchiveError,isInside,isSafeArchiveEntry}=require_archiveShared(),MAX_ARCHIVE_SIZE=2*1024*1024*1024,MAX_ARCHIVE_ENTRIES=1e4,MAX_COMPRESSION_RATIO=100,ArchiveService=class{constructor({rootPath,resolvePath,getChildPath}){this.rootPath=rootPath,this.resolvePath=resolvePath,this.getChildPath=getChildPath,this.jobs=new Map}resolveExistingFile(inputPath){let fullPath=this.resolvePath(inputPath);if(!existsSync(fullPath))throw createArchiveError("Path not found",404);let stats=lstatSync(fullPath);if(!stats.isFile())throw createArchiveError("Archive path must be a file");if(!archiveProvider.isArchivePath(fullPath))throw createArchiveError("Unsupported archive format");if(stats.size>MAX_ARCHIVE_SIZE)throw createArchiveError("Archive exceeds 2GB limit",413);return fullPath}async listArchive(inputPath){let fullPath=this.resolveExistingFile(inputPath),entries=await archiveProvider.listEntries(fullPath);return this.assertEntriesSafe(entries,fullPath),{path:inputPath,name:path.basename(fullPath),entries,totalEntries:entries.length,totalSize:entries.reduce((total,entry)=>total+entry.size,0),totalPackedSize:entries.reduce((total,entry)=>total+entry.packedSize,0)}}assertEntriesSafe(entries,fullPath){if(!entries.length)throw createArchiveError("Archive contains no entries",422);if(entries.length>MAX_ARCHIVE_ENTRIES)throw createArchiveError("Archive contains too many entries",413);if(entries.some(entry=>entry.encrypted))throw createArchiveError("Encrypted archives are not supported",422);if(entries.some(entry=>entry.isSymbolicLink||!isSafeArchiveEntry(entry.path)))throw createArchiveError("Archive contains an unsafe entry path",422);let totalSize=entries.reduce((total,entry)=>total+entry.size,0),packedSize=Math.max(lstatSync(fullPath).size,1);if(totalSize>MAX_ARCHIVE_SIZE)throw createArchiveError("Archive expands beyond 2GB limit",413);if(totalSize/packedSize>MAX_COMPRESSION_RATIO)throw createArchiveError("Archive compression ratio exceeds limit",413)}startJob(type,payload){let id=crypto.randomUUID(),job={id,type,status:"queued",progress:{processedEntries:0,totalEntries:0},createdAt:new Date().toISOString(),result:null,error:null,cancelled:!1,child:null,archive:null};return this.jobs.set(id,job),setImmediate(async()=>{if(!job.cancelled){job.status="running";try{job.result=type==="create"?await this.createArchive(job,payload):await this.extractArchive(job,payload),job.status=job.cancelled?"cancelled":"completed"}catch(error){job.status=job.cancelled?"cancelled":"failed",job.error=error.message}finally{job.child=null,job.archive=null,job.finishedAt=new Date().toISOString()}}}),job}getJob(id){return this.jobs.get(id)}getCapabilities(){return archiveProvider.capabilities}cancelJob(id){let job=this.getJob(id);if(!job)throw createArchiveError("Archive job not found",404);return["completed","failed","cancelled"].includes(job.status)||(job.cancelled=!0,job.status="cancelled",job.child&&job.child.kill("SIGTERM"),job.archive&&job.archive.abort()),job}async createArchive(job,payload){let format=payload.format==="tar.gz"?"tar.gz":payload.format;if(!archiveProvider.capabilities.createFormats.includes(format)){let formats=archiveProvider.capabilities.createFormats.join(" and ");throw createArchiveError(`Supported creation formats are ${formats}`)}if(!Array.isArray(payload.sources)||payload.sources.length===0)throw createArchiveError("Sources must be a non-empty array");let sourcePaths=payload.sources.map(source=>this.resolvePath(source));sourcePaths.forEach(source=>{if(!existsSync(source))throw createArchiveError("Source path not found",404);if(lstatSync(source).isSymbolicLink())throw createArchiveError("Symbolic links cannot be archived");let realPath=realpathSync(source);if(!isInside(this.rootPath,realPath))throw createArchiveError("Access denied",403)}),await Promise.all(sourcePaths.map(source=>this.assertSourceTreeSafe(source)));let destinationPath=payload.destinationPath||path.posix.dirname(payload.sources[0]),archiveName=String(payload.name||"").trim(),requiredExtension=format==="zip"?".zip":".tar.gz",safeName=archiveName.endsWith(requiredExtension)?archiveName:`${archiveName}${requiredExtension}`,outputPath=this.getChildPath(destinationPath,safeName);if(existsSync(outputPath))throw createArchiveError("Archive path already exists",409);if(job.progress.totalEntries=sourcePaths.length,await new Promise((resolve,reject)=>{let output=createWriteStream(outputPath,{flags:"wx"}),archive=format==="zip"?archiver("zip",{zlib:{level:9}}):archiver("tar",{gzip:!0,gzipOptions:{level:9}});job.archive=archive,output.on("close",resolve),output.on("error",reject),archive.on("error",reject),archive.on("progress",progress=>{job.progress.processedEntries=progress.entries.processed,job.progress.totalEntries=progress.entries.total}),archive.pipe(output),sourcePaths.forEach(source=>{lstatSync(source).isDirectory()?archive.directory(source,path.basename(source)):archive.file(source,{name:path.basename(source)})}),archive.finalize()}).catch(error=>{throw rmSync(outputPath,{force:!0}),error}),job.cancelled)throw rmSync(outputPath,{force:!0}),createArchiveError("Archive job cancelled",499);return{path:outputPath,name:path.basename(outputPath)}}async extractArchive(job,payload){let sourcePath=this.resolveExistingFile(payload.path),destinationPath=this.resolvePath(payload.destinationPath||"/");if(!existsSync(destinationPath)||!lstatSync(destinationPath).isDirectory())throw createArchiveError("Extraction destination must be an existing directory",404);let listing=await this.listArchive(payload.path);job.progress.totalEntries=listing.totalEntries;let tempRoot=await fsPromises.mkdtemp(path.join(destinationPath,".mock-service-cli-archive-")),tempOutput=path.join(tempRoot,"output");mkdirSync(tempOutput);try{if(await archiveProvider.extract(job,sourcePath,tempOutput),job.cancelled)throw createArchiveError("Archive job cancelled",499);await this.assertExtractedTreeSafe(tempOutput);let outputEntries=await fsPromises.readdir(tempOutput);if(!outputEntries.length)throw createArchiveError("Archive produced no files",422);outputEntries.forEach(name=>{if(existsSync(path.join(destinationPath,name)))throw createArchiveError(`Destination already contains ${name}`,409)});for(let name of outputEntries)renameSync(path.join(tempOutput,name),path.join(destinationPath,name));return job.progress.processedEntries=job.progress.totalEntries,{destinationPath,entries:outputEntries}}finally{rmSync(tempRoot,{recursive:!0,force:!0})}}async assertExtractedTreeSafe(root){let rootRealPath=realpathSync(root),walk=async current=>{let entries=await fsPromises.readdir(current,{withFileTypes:!0});for(let entry of entries){let child=path.join(current,entry.name),stats=await fsPromises.lstat(child);if(stats.isSymbolicLink())throw createArchiveError("Archive contains symbolic links",422);let realPath=realpathSync(child);if(!isInside(rootRealPath,realPath))throw createArchiveError("Archive extracted outside its destination",422);stats.isDirectory()&&await walk(child)}};await walk(root)}async assertSourceTreeSafe(source){let stats=await fsPromises.lstat(source);if(stats.isSymbolicLink())throw createArchiveError("Symbolic links cannot be archived");if(!stats.isDirectory())return;let entries=await fsPromises.readdir(source,{withFileTypes:!0});await Promise.all(entries.map(entry=>this.assertSourceTreeSafe(path.join(source,entry.name))))}};module2.exports={ArchiveService,isArchivePath:archiveProvider.isArchivePath}}});var require_fileExplorerServer=__commonJS({"src/lib/fileExplorerServer.js"(){var express=require_express2(),{existsSync,readFileSync,statSync,lstatSync,rmSync,mkdirSync,writeFileSync,renameSync,realpathSync,copyFileSync,unlinkSync,constants:fsConstants,promises:fsPromises}=require("fs"),path=require("path"),os=require("os"),crypto=require("crypto"),multer=require_multer(),{UAParser}=require_ua_parser(),colors=require_safe(),portfinder=require_portfinder(),{exec,execFile}=require("child_process"),{dateFormat,logger,getServerHost,getServerUrls,hostAllowlistMiddleware,normalizeRemoteAddress}=require_utils3(),{getPackageVersion}=require_packageInfo(),{ArchiveService}=require_archiveService(),app=express(),log=logger(process.env.SILENT),argv=JSON.parse(process.env.ARGV),explorerRoot=path.resolve(process.env.EXPLORER_DIRECTORY||process.cwd()),explorerRootRealPath=realpathSync(explorerRoot),explorerRootId=crypto.createHash("sha256").update(explorerRootRealPath).digest("hex"),port=argv.p||argv.port,isEditMode=process.env.EXPLORER_EDIT==="true",explorerPassword=process.env.EXPLORER_AUTH||"",isAuthEnabled=!!explorerPassword,visitorKeys=new Set,httpServer=null,shuttingDown=!1,MAX_UPLOAD_FILE_SIZE=2*1024*1024*1024,MAX_UPLOAD_TOTAL_SIZE=2*1024*1024*1024,MAX_UPLOAD_FILE_COUNT=100,MAX_MULTIPART_OVERHEAD_SIZE=2*1024*1024,upload=multer({dest:path.join(os.tmpdir(),"mock-service-cli-upload"),preservePath:!0,limits:{fileSize:MAX_UPLOAD_FILE_SIZE,files:MAX_UPLOAD_FILE_COUNT,fields:10}}),archiveService=new ArchiveService({rootPath:explorerRootRealPath,resolvePath:resolveExplorerPath,getChildPath});function isPathInsideRoot(fullPath,resolvedRoot=explorerRootRealPath){let relativePath=path.relative(resolvedRoot,fullPath);return relativePath===""||!relativePath.startsWith("..")&&!path.isAbsolute(relativePath)}function normalizeExplorerInputPath(inputPath){let decodedPath=decodeURIComponent(String(inputPath||"/")).replace(/\\/g,"/");return!decodedPath||decodedPath==="."?"/":decodedPath.startsWith("/")?decodedPath:`/${decodedPath}`}function resolveExplorerPath(inputPath){let relativePath=normalizeExplorerInputPath(inputPath).replace(/^\/+/,""),fullPath=path.resolve(explorerRoot,relativePath);if(!isPathInsideRoot(fullPath,explorerRoot)){let error=new Error("Access denied");throw error.statusCode=403,error}if(!existsSync(fullPath))return fullPath;let realPath=realpathSync(fullPath);if(!isPathInsideRoot(realPath)){let error=new Error("Access denied");throw error.statusCode=403,error}return realPath}function validateEntryName(name){if(typeof name!="string")return"Name must be a string";let normalizedName=name.trim();if(!normalizedName||normalizedName==="."||normalizedName==="..")return"Invalid name";if(/[/\\\0<>:"|?*]/.test(normalizedName))return"Name contains invalid characters";if(process.platform==="win32"){let upperName=normalizedName.replace(/[. ]+$/g,"").split(".")[0].toUpperCase();if(new Set(["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]).has(upperName)||normalizedName.endsWith(" ")||normalizedName.endsWith("."))return"Name is not supported on Windows"}return null}function getChildPath(parentPath,name){let nameError=validateEntryName(name);if(nameError){let error=new Error(nameError);throw error.statusCode=400,error}let parentFullPath=resolveExplorerPath(parentPath||"/");if(!existsSync(parentFullPath)||!statSync(parentFullPath).isDirectory()){let error=new Error("Parent directory not found");throw error.statusCode=404,error}let childPath=path.resolve(parentFullPath,name.trim());if(!isPathInsideRoot(childPath)){let error=new Error("Access denied");throw error.statusCode=403,error}return childPath}function requireEditMode(req,res,next){if(!isEditMode)return res.status(403).json({error:"File explorer is read-only. Restart with --edit to modify files."});next()}function isValidExplorerPassword(value){if(!isAuthEnabled)return!0;let provided=Buffer.from(String(value||"")),expected=Buffer.from(explorerPassword);return provided.length===expected.length&&crypto.timingSafeEqual(provided,expected)}function getExplorerPassword(req){return req.get("x-file-explorer-password")||req.body&&req.body.password}function requireExplorerAuth(req,res,next){if(!isValidExplorerPassword(getExplorerPassword(req)))return res.status(401).json({error:"Authentication required"});next()}function logExplorerVisit(req){let userAgent=req.get("user-agent")||"",ip=normalizeRemoteAddress(req.socket&&req.socket.remoteAddress),visitorKey=`${ip}
157
- ${userAgent}`;if(visitorKeys.has(visitorKey))return;visitorKeys.add(visitorKey);let parsed=new UAParser(userAgent).getResult(),browser=[parsed.browser.name,parsed.browser.version].filter(Boolean).join(" ")||"Unknown",operatingSystem=[parsed.os.name,parsed.os.version].filter(Boolean).join(" ")||"Unknown";log.info(`File explorer visitor: ip=${ip}, os=${operatingSystem}, browser=${browser}, userAgent=${userAgent}`)}function getUploadTargetPath(parentPath,originalName){let normalizedName=String(originalName||"").replace(/\\/g,"/").replace(/^\/+/,""),parts=normalizedName.split("/").filter(Boolean);if(parts.length===0||normalizedName!==parts.join("/")){let error=new Error("Invalid upload path");throw error.statusCode=400,error}parts.forEach(part=>{let nameError=validateEntryName(part);if(nameError){let error=new Error(nameError);throw error.statusCode=400,error}});let parentFullPath=resolveExplorerPath(parentPath||"/");if(!existsSync(parentFullPath)||!statSync(parentFullPath).isDirectory()){let error=new Error("Parent directory not found");throw error.statusCode=404,error}let targetPath=path.resolve(parentFullPath,...parts);if(!isPathInsideRoot(targetPath)){let error=new Error("Access denied");throw error.statusCode=403,error}return{targetPath,parentFullPath,parts}}function ensureUploadParent(parentFullPath,parts){let current=parentFullPath;parts.slice(0,-1).forEach(part=>{if(current=path.join(current,part),existsSync(current)){let stats=lstatSync(current);if(!stats.isDirectory()||stats.isSymbolicLink()||!isPathInsideRoot(realpathSync(current))){let error=new Error("Upload path is not a safe directory");throw error.statusCode=403,error}}else mkdirSync(current)})}function moveUploadedFile(sourcePath,targetPath){copyFileSync(sourcePath,targetPath,fsConstants.COPYFILE_EXCL),unlinkSync(sourcePath)}function cleanupUploadedTempFiles(files=[]){files.forEach(file=>{file&&file.path&&existsSync(file.path)&&rmSync(file.path,{force:!0})})}function enforceUploadRequestSize(req,res,next){let contentLength=Number(req.get("content-length"));if(Number.isFinite(contentLength)&&contentLength>MAX_UPLOAD_TOTAL_SIZE+MAX_MULTIPART_OVERHEAD_SIZE)return res.status(413).json({error:"Total upload size exceeds 2GB limit"});next()}function deleteExplorerPath(targetPath){let fullPath=resolveExplorerPath(targetPath);if(path.resolve(fullPath)===explorerRootRealPath){let error=new Error("Cannot delete explorer root");throw error.statusCode=400,error}if(!existsSync(fullPath)){let error=new Error("Path not found");throw error.statusCode=404,error}rmSync(fullPath,{recursive:!0,force:!1})}process.env.PORT?init():(portfinder.basePort=port||8090,portfinder.getPort(function(err,foundPort){if(err)throw err;process.env.PORT=foundPort,init()}));function init(){app.use(hostAllowlistMiddleware()),app.use(express.json());let faviconInstanceId=crypto.randomUUID(),explorerFaviconUrl=`/favicon-file-explorer.svg?instance=${faviconInstanceId}`,loginFaviconUrl=`/favicon-file-explorer-login.svg?instance=${faviconInstanceId}`,sendFavicon=(filename,res)=>{res.type("image/svg+xml").set("Cache-Control","no-store").sendFile(path.resolve(__dirname,filename))},sendExplorerPage=(filename,faviconUrl,res)=>{let htmlPath=path.resolve(__dirname,filename);if(!existsSync(htmlPath))return res.status(404).send("File explorer page not found");res.type("html").send(readFileSync(htmlPath,"utf8").replace("__FILE_EXPLORER_FAVICON_URL__",faviconUrl))};app.get("/favicon-file-explorer.svg",(req,res)=>sendFavicon("./favicon-file-explorer.svg",res)),app.get("/favicon-file-explorer-login.svg",(req,res)=>sendFavicon("./favicon-file-explorer-login.svg",res)),app.get("/",(req,res)=>sendExplorerPage("./file-explorer.html",explorerFaviconUrl,res)),app.get("/__login",(req,res)=>sendExplorerPage("./file-explorer-login.html",loginFaviconUrl,res)),app.post("/__api/auth/verify",(req,res)=>{if(!isValidExplorerPassword(getExplorerPassword(req)))return res.status(401).json({error:"Invalid password"});res.json({success:!0,authEnabled:isAuthEnabled})}),app.use("/__api",requireExplorerAuth),app.get("/__api/config",(req,res)=>{logExplorerVisit(req),res.json({editMode:isEditMode,authEnabled:isAuthEnabled,rootId:explorerRootId})}),app.get("/__api/archive/capabilities",requireEditMode,(req,res)=>{res.json(archiveService.getCapabilities())}),app.get("/__api/health",(req,res)=>{res.json({success:!0})}),app.get("/__api/list",async(req,res)=>{let dirPath=normalizeExplorerInputPath(req.query.path||"/"),fullPath;try{fullPath=resolveExplorerPath(dirPath)}catch(error){return res.status(error.statusCode||500).json({error:error.message})}if(!existsSync(fullPath))return res.status(404).json({error:"Path not found"});try{if(!(await fsPromises.lstat(fullPath)).isDirectory())return res.status(400).json({error:"Not a directory"});let files=await fsPromises.readdir(fullPath,{withFileTypes:!0}),result=await Promise.all(files.map(async file=>{let filePath=path.join(fullPath,file.name),fileStats,hasError=!1;try{fileStats=await fsPromises.lstat(filePath)}catch{hasError=!0}let relativePath=path.posix.join(dirPath,file.name),isDirectory=hasError?file.isDirectory():fileStats.isDirectory();return{name:file.name,path:relativePath.replace(/\\/g,"/"),isDirectory,size:hasError?0:fileStats.size,mtime:hasError?new Date:fileStats.mtime,birthtime:hasError?new Date:fileStats.birthtime,isHidden:file.name.startsWith("."),error:hasError?"Cannot access file":null}}));result.sort((a,b)=>a.isDirectory!==b.isDirectory?a.isDirectory?-1:1:a.name.localeCompare(b.name)),res.json({currentPath:dirPath,parentPath:dirPath==="/"?null:path.posix.dirname(dirPath),files:result})}catch(error){res.status(500).json({error:error.message})}}),app.get("/__api/file",(req,res)=>{let filePath=normalizeExplorerInputPath(req.query.path||"/"),fullPath;try{fullPath=resolveExplorerPath(filePath)}catch(error){return res.status(error.statusCode||500).json({error:error.message})}if(!existsSync(fullPath))return res.status(404).json({error:"File not found"});let stats=statSync(fullPath);if(stats.isDirectory())return res.status(400).json({error:"Is a directory"});if(req.query.download==="1")return res.download(fullPath,path.basename(filePath));let ext=path.extname(filePath).toLowerCase(),imageExts=[".jpg",".jpeg",".png",".gif",".bmp",".webp",".svg",".ico"],textExts=[".txt",".json",".js",".css",".html",".xml",".md",".csv",".yaml",".yml",".log"];if(imageExts.includes(ext))res.sendFile(fullPath);else if(textExts.includes(ext)||stats.size<1024*1024)try{let content=readFileSync(fullPath,"utf-8");res.json({name:path.basename(filePath),type:"text",content,size:stats.size})}catch{res.download(fullPath)}else res.download(fullPath)}),app.post("/__api/open-in-explorer",(req,res)=>{let filePath=normalizeExplorerInputPath(req.body.path||"/"),fullPath;try{fullPath=resolveExplorerPath(filePath)}catch(error){return res.status(error.statusCode||500).json({error:error.message})}if(!existsSync(fullPath))return res.status(404).json({error:"Path not found"});let command,args;switch(process.platform){case"darwin":command="open",args=[fullPath];break;case"win32":command="explorer.exe",args=[fullPath];break;case"linux":command="xdg-open",args=[fullPath];break;default:return res.status(400).json({error:"Unsupported platform"})}execFile(command,args,error=>{if(error)return console.error(colors.red(`Failed to open in explorer: ${error.message}`)),res.status(500).json({error:"Failed to open in explorer"});res.json({success:!0,path:fullPath})})}),app.post("/__api/path",requireEditMode,(req,res)=>{let parentPath=req.body&&req.body.parentPath||"/",name=req.body&&req.body.name,type=req.body&&req.body.type||"file";if(type!=="file"&&type!=="directory")return res.status(400).json({error:"Invalid type"});let fullPath;try{fullPath=getChildPath(parentPath,name)}catch(error){return res.status(error.statusCode||500).json({error:error.message})}if(existsSync(fullPath))return res.status(409).json({error:"Path already exists"});try{type==="directory"?mkdirSync(fullPath):writeFileSync(fullPath,""),res.json({success:!0,path:fullPath})}catch(error){console.error(colors.red(`Failed to create path: ${error.message}`)),res.status(500).json({error:"Failed to create path"})}}),app.patch("/__api/path",requireEditMode,(req,res)=>{let sourcePath=req.body&&req.body.path,name=req.body&&req.body.name,fullPath,nextPath;try{if(fullPath=resolveExplorerPath(sourcePath),path.resolve(fullPath)===explorerRootRealPath)return res.status(400).json({error:"Cannot rename explorer root"});if(!existsSync(fullPath))return res.status(404).json({error:"Path not found"});nextPath=getChildPath(path.posix.dirname(normalizeExplorerInputPath(sourcePath||"/")),name)}catch(error){return res.status(error.statusCode||500).json({error:error.message})}if(existsSync(nextPath))return res.status(409).json({error:"Path already exists"});try{renameSync(fullPath,nextPath),res.json({success:!0,path:sourcePath,nextPath})}catch(error){console.error(colors.red(`Failed to rename path: ${error.message}`)),res.status(500).json({error:"Failed to rename path"})}}),app.delete("/__api/path",requireEditMode,(req,res)=>{let targetPath=req.body&&req.body.path||"/";try{deleteExplorerPath(targetPath),res.json({success:!0,path:targetPath})}catch(error){console.error(colors.red(`Failed to delete path: ${error.message}`)),res.status(error.statusCode||500).json({error:error.statusCode?error.message:"Failed to delete path"})}}),app.delete("/__api/paths",requireEditMode,(req,res)=>{let paths=req.body&&req.body.paths||[];if(!Array.isArray(paths)||paths.length===0)return res.status(400).json({error:"Paths must be a non-empty array"});let deleted=[];try{paths.forEach(targetPath=>{deleteExplorerPath(targetPath),deleted.push(targetPath)}),res.json({success:!0,deleted})}catch(error){console.error(colors.red(`Failed to delete paths: ${error.message}`)),res.status(error.statusCode||500).json({error:error.statusCode?error.message:"Failed to delete paths",deleted})}}),app.post("/__api/upload",requireEditMode,enforceUploadRequestSize,upload.any(),(req,res)=>{let parentPath=req.body&&req.body.parentPath||"/",files=req.files||[];if(!files.length)return res.status(400).json({error:"No files uploaded"});if(files.reduce((sum,file)=>sum+file.size,0)>MAX_UPLOAD_TOTAL_SIZE)return cleanupUploadedTempFiles(files),res.status(413).json({error:"Total upload size exceeds 2GB limit"});let uploaded=[],failed=[];files.forEach(file=>{try{let{targetPath,parentFullPath,parts}=getUploadTargetPath(parentPath,file.originalname);if(existsSync(targetPath)){failed.push({name:file.originalname,error:"Path already exists",statusCode:409});return}if(ensureUploadParent(parentFullPath,parts),existsSync(targetPath)){failed.push({name:file.originalname,error:"Path already exists",statusCode:409});return}moveUploadedFile(file.path,targetPath),uploaded.push({name:file.originalname,path:path.posix.join(normalizeExplorerInputPath(parentPath),...parts)})}catch(error){failed.push({name:file.originalname,error:error.message,statusCode:error.statusCode||500})}finally{existsSync(file.path)&&rmSync(file.path,{force:!0})}}),res.status(failed.length?207:200).json({success:failed.length===0,uploaded,failed})}),app.get("/__api/archive/preview",requireEditMode,async(req,res)=>{try{let preview=await archiveService.listArchive(normalizeExplorerInputPath(req.query.path||"/"));res.json(preview)}catch(error){res.status(error.statusCode||500).json({error:error.message})}}),app.post("/__api/archive/jobs",requireEditMode,(req,res)=>{let payload=req.body||{},operation=payload.operation;if(operation!=="create"&&operation!=="extract")return res.status(400).json({error:"Archive operation must be create or extract"});try{let job=archiveService.startJob(operation,payload);res.status(202).json({id:job.id,status:job.status,type:job.type})}catch(error){res.status(error.statusCode||500).json({error:error.message})}}),app.get("/__api/archive/jobs/:id",requireEditMode,(req,res)=>{let job=archiveService.getJob(req.params.id);if(!job)return res.status(404).json({error:"Archive job not found"});res.json({id:job.id,type:job.type,status:job.status,progress:job.progress,result:job.result,error:job.error,createdAt:job.createdAt,finishedAt:job.finishedAt||null})}),app.delete("/__api/archive/jobs/:id",requireEditMode,(req,res)=>{try{let job=archiveService.cancelJob(req.params.id);res.json({id:job.id,status:job.status})}catch(error){res.status(error.statusCode||500).json({error:error.message})}}),app.use((error,req,res,next)=>{if(error instanceof multer.MulterError){cleanupUploadedTempFiles(req.files);let statusCode=error.code==="LIMIT_FILE_SIZE"||error.code==="LIMIT_FILE_COUNT"?413:400;return res.status(statusCode).json({error:error.message})}if(error)return console.error(colors.red(`File explorer request failed: ${error.message}`)),res.status(error.statusCode||500).json({error:error.message||"Request failed"});next()}),startServer()}function startServer(){httpServer=require("http").createServer(app),httpServer.requestTimeout=0,httpServer.listen(Number.parseInt(process.env.PORT,10),getServerHost(),()=>{if(console.info([colors.yellow(`
156
+ `;function isArchivePath(filePath){return hasArchiveExtension(filePath,extensions)}function isCompressedTar(filePath){return/\.(tar\.gz|tgz|tar\.bz2|tbz|tbz2|tar\.xz|txz)$/i.test(filePath)}function parse7ZipList(output){let separator=output.indexOf("----------");return separator<0?[]:output.slice(separator+10).split(/\r?\n\r?\n/).map(block=>{let values={};return block.split(/\r?\n/).forEach(line=>{let index=line.indexOf(" = ");index>0&&(values[line.slice(0,index)]=line.slice(index+3))}),values}).filter(values=>values.Path).map(values=>({path:values.Path.replace(/\\/g,"/"),isDirectory:values.Folder==="+"||String(values.Attributes||"").startsWith("D"),size:Number(values.Size||0),packedSize:Number(values["Packed Size"]||0),encrypted:values.Encrypted==="+",modified:values.Modified||null,attributes:values.Attributes||""}))}function run7Zip(args,onProcess){return new Promise((resolve,reject)=>{try{process.platform!=="win32"&&chmodSync(path7za,493)}catch(error){return reject(createArchiveError(`Unable to prepare bundled 7-Zip binary: ${error.message}`,500))}let child=spawn(path7za,args,{stdio:["ignore","pipe","pipe"]}),stderr="",stdout="";onProcess&&onProcess(child),child.stdout.on("data",chunk=>{stdout+=chunk.toString()}),child.stderr.on("data",chunk=>{stderr+=chunk.toString()}),child.once("error",reject),child.once("close",code=>{if(code===0)return resolve(stdout);reject(createArchiveError(stderr.trim()||`7-Zip exited with code ${code}`,422))})})}async function list7Zip(fullPath){let output=await run7Zip(["l","-slt","--",fullPath]),entries=parse7ZipList(output);if(!isCompressedTar(fullPath))return entries;let tempRoot=await fsPromises.mkdtemp(path.join(os.tmpdir(),"mock-service-cli-archive-list-"));try{await run7Zip(["e","-y",`-o${tempRoot}`,"--",fullPath]);let tarName=(await fsPromises.readdir(tempRoot)).find(name=>/\.tar$/i.test(name));return tarName?await list7Zip(path.join(tempRoot,tarName)):entries}finally{rmSync(tempRoot,{recursive:!0,force:!0})}}async function listRar(fullPath){let list=(await createExtractorFromFile({filepath:fullPath})).getFileList();if(list.arcHeader.flags&&list.arcHeader.flags.headerEncrypted)throw createArchiveError("Encrypted archives are not supported",422);return[...list.fileHeaders].map(header=>({path:header.name.replace(/\\/g,"/"),isDirectory:!!(header.flags&&header.flags.directory),size:Number(header.unpSize||0),packedSize:Number(header.packSize||0),encrypted:!!(header.flags&&header.flags.encrypted),modified:header.time||null,attributes:""}))}async function listEntries(fullPath){return path.extname(fullPath).toLowerCase()===".rar"?listRar(fullPath):list7Zip(fullPath)}async function extractRar(job,sourcePath,targetPath){await new Promise((resolve,reject)=>{let worker=new Worker(RAR_EXTRACT_WORKER,{eval:!0,workerData:{sourcePath,targetPath}}),settled=!1,finish=(callback,value)=>{settled||(settled=!0,job.child=null,callback(value))};job.child={kill:()=>worker.terminate()},worker.on("message",message=>{message&&message.success?finish(resolve):finish(reject,createArchiveError(message&&message.error||"RAR extraction failed",422))}),worker.on("error",error=>finish(reject,error)),worker.on("exit",code=>{if(!settled&&code!==0){let message=job.cancelled?"Archive job cancelled":"RAR extraction stopped";finish(reject,createArchiveError(message,499))}})})}async function extract(job,sourcePath,targetPath){if(path.extname(sourcePath).toLowerCase()===".rar")return extractRar(job,sourcePath,targetPath);await run7Zip(["x","-y",`-o${targetPath}`,"--",sourcePath],child=>{job.child=child})}module2.exports={capabilities,extract,isArchivePath,listEntries}}});var require_archiveService=__commonJS({"src/lib/archiveService.js"(exports2,module2){var{createWriteStream,existsSync,lstatSync,mkdirSync,promises:fsPromises,realpathSync,renameSync,rmSync}=require("fs"),path=require("path"),crypto=require("crypto"),archiver=require("archiver"),archiveProvider=require_ultra(),{createArchiveError,isInside,isSafeArchiveEntry}=require_archiveShared(),MAX_ARCHIVE_SIZE=2*1024*1024*1024,MAX_ARCHIVE_ENTRIES=1e4,MAX_COMPRESSION_RATIO=100,ArchiveService=class{constructor({rootPath,resolvePath,getChildPath}){this.rootPath=rootPath,this.resolvePath=resolvePath,this.getChildPath=getChildPath,this.jobs=new Map}resolveExistingFile(inputPath){let fullPath=this.resolvePath(inputPath);if(!existsSync(fullPath))throw createArchiveError("Path not found",404);let stats=lstatSync(fullPath);if(!stats.isFile())throw createArchiveError("Archive path must be a file");if(!archiveProvider.isArchivePath(fullPath))throw createArchiveError("Unsupported archive format");if(stats.size>MAX_ARCHIVE_SIZE)throw createArchiveError("Archive exceeds 2GB limit",413);return fullPath}async listArchive(inputPath){let fullPath=this.resolveExistingFile(inputPath),entries=await archiveProvider.listEntries(fullPath);return this.assertEntriesSafe(entries,fullPath),{path:inputPath,name:path.basename(fullPath),entries,totalEntries:entries.length,totalSize:entries.reduce((total,entry)=>total+entry.size,0),totalPackedSize:entries.reduce((total,entry)=>total+entry.packedSize,0)}}assertEntriesSafe(entries,fullPath){if(!entries.length)throw createArchiveError("Archive contains no entries",422);if(entries.length>MAX_ARCHIVE_ENTRIES)throw createArchiveError("Archive contains too many entries",413);if(entries.some(entry=>entry.encrypted))throw createArchiveError("Encrypted archives are not supported",422);if(entries.some(entry=>entry.isSymbolicLink||!isSafeArchiveEntry(entry.path)))throw createArchiveError("Archive contains an unsafe entry path",422);let totalSize=entries.reduce((total,entry)=>total+entry.size,0),packedSize=Math.max(lstatSync(fullPath).size,1);if(totalSize>MAX_ARCHIVE_SIZE)throw createArchiveError("Archive expands beyond 2GB limit",413);if(totalSize/packedSize>MAX_COMPRESSION_RATIO)throw createArchiveError("Archive compression ratio exceeds limit",413)}startJob(type,payload){let id=crypto.randomUUID(),job={id,type,status:"queued",progress:{processedEntries:0,totalEntries:0},createdAt:new Date().toISOString(),result:null,error:null,cancelled:!1,child:null,archive:null};return this.jobs.set(id,job),setImmediate(async()=>{if(!job.cancelled){job.status="running";try{job.result=type==="create"?await this.createArchive(job,payload):await this.extractArchive(job,payload),job.status=job.cancelled?"cancelled":"completed"}catch(error){job.status=job.cancelled?"cancelled":"failed",job.error=error.message}finally{job.child=null,job.archive=null,job.finishedAt=new Date().toISOString()}}}),job}getJob(id){return this.jobs.get(id)}getCapabilities(){return archiveProvider.capabilities}cancelJob(id){let job=this.getJob(id);if(!job)throw createArchiveError("Archive job not found",404);return["completed","failed","cancelled"].includes(job.status)||(job.cancelled=!0,job.status="cancelled",job.child&&job.child.kill("SIGTERM"),job.archive&&job.archive.abort()),job}async createArchive(job,payload){let format=payload.format==="tar.gz"?"tar.gz":payload.format;if(!archiveProvider.capabilities.createFormats.includes(format)){let formats=archiveProvider.capabilities.createFormats.join(" and ");throw createArchiveError(`Supported creation formats are ${formats}`)}if(!Array.isArray(payload.sources)||payload.sources.length===0)throw createArchiveError("Sources must be a non-empty array");let sourcePaths=payload.sources.map(source=>this.resolvePath(source));sourcePaths.forEach(source=>{if(!existsSync(source))throw createArchiveError("Source path not found",404);if(lstatSync(source).isSymbolicLink())throw createArchiveError("Symbolic links cannot be archived");let realPath=realpathSync(source);if(!isInside(this.rootPath,realPath))throw createArchiveError("Access denied",403)}),await Promise.all(sourcePaths.map(source=>this.assertSourceTreeSafe(source)));let destinationPath=payload.destinationPath||path.posix.dirname(payload.sources[0]),archiveName=String(payload.name||"").trim(),requiredExtension=format==="zip"?".zip":".tar.gz",safeName=archiveName.endsWith(requiredExtension)?archiveName:`${archiveName}${requiredExtension}`,outputPath=this.getChildPath(destinationPath,safeName);if(existsSync(outputPath))throw createArchiveError("Archive path already exists",409);if(job.progress.totalEntries=sourcePaths.length,await new Promise((resolve,reject)=>{let output=createWriteStream(outputPath,{flags:"wx"}),archive=format==="zip"?archiver("zip",{zlib:{level:9}}):archiver("tar",{gzip:!0,gzipOptions:{level:9}});job.archive=archive,output.on("close",resolve),output.on("error",reject),archive.on("error",reject),archive.on("progress",progress=>{job.progress.processedEntries=progress.entries.processed,job.progress.totalEntries=progress.entries.total}),archive.pipe(output),sourcePaths.forEach(source=>{lstatSync(source).isDirectory()?archive.directory(source,path.basename(source)):archive.file(source,{name:path.basename(source)})}),archive.finalize()}).catch(error=>{throw rmSync(outputPath,{force:!0}),error}),job.cancelled)throw rmSync(outputPath,{force:!0}),createArchiveError("Archive job cancelled",499);return{path:outputPath,name:path.basename(outputPath)}}async extractArchive(job,payload){let sourcePath=this.resolveExistingFile(payload.path),destinationPath=this.resolvePath(payload.destinationPath||"/");if(!existsSync(destinationPath)||!lstatSync(destinationPath).isDirectory())throw createArchiveError("Extraction destination must be an existing directory",404);let listing=await this.listArchive(payload.path);job.progress.totalEntries=listing.totalEntries;let tempRoot=await fsPromises.mkdtemp(path.join(destinationPath,".mock-service-cli-archive-")),tempOutput=path.join(tempRoot,"output");mkdirSync(tempOutput);try{if(await archiveProvider.extract(job,sourcePath,tempOutput),job.cancelled)throw createArchiveError("Archive job cancelled",499);await this.assertExtractedTreeSafe(tempOutput);let outputEntries=await fsPromises.readdir(tempOutput);if(!outputEntries.length)throw createArchiveError("Archive produced no files",422);outputEntries.forEach(name=>{if(existsSync(path.join(destinationPath,name)))throw createArchiveError(`Destination already contains ${name}`,409)});for(let name of outputEntries)renameSync(path.join(tempOutput,name),path.join(destinationPath,name));return job.progress.processedEntries=job.progress.totalEntries,{destinationPath,entries:outputEntries}}finally{rmSync(tempRoot,{recursive:!0,force:!0})}}async assertExtractedTreeSafe(root){let rootRealPath=realpathSync(root),walk=async current=>{let entries=await fsPromises.readdir(current,{withFileTypes:!0});for(let entry of entries){let child=path.join(current,entry.name),stats=await fsPromises.lstat(child);if(stats.isSymbolicLink())throw createArchiveError("Archive contains symbolic links",422);let realPath=realpathSync(child);if(!isInside(rootRealPath,realPath))throw createArchiveError("Archive extracted outside its destination",422);stats.isDirectory()&&await walk(child)}};await walk(root)}async assertSourceTreeSafe(source){let stats=await fsPromises.lstat(source);if(stats.isSymbolicLink())throw createArchiveError("Symbolic links cannot be archived");if(!stats.isDirectory())return;let entries=await fsPromises.readdir(source,{withFileTypes:!0});await Promise.all(entries.map(entry=>this.assertSourceTreeSafe(path.join(source,entry.name))))}};module2.exports={ArchiveService,isArchivePath:archiveProvider.isArchivePath}}});var require_fileExplorerServer=__commonJS({"src/lib/fileExplorerServer.js"(){var express=require_express2(),{existsSync,readFileSync,statSync,lstatSync,rmSync,mkdirSync,writeFileSync,renameSync,realpathSync,copyFileSync,unlinkSync,constants:fsConstants,promises:fsPromises}=require("fs"),path=require("path"),os=require("os"),crypto=require("crypto"),multer=require_multer(),{UAParser}=require_ua_parser(),colors=require_safe(),portfinder=require_portfinder(),{exec}=require("child_process"),{dateFormat,logger,getServerHost,getServerUrls,hostAllowlistMiddleware,isHiddenPath,normalizeRemoteAddress,openPathInFileManager}=require_utils3(),{getPackageVersion}=require_packageInfo(),{ArchiveService}=require_archiveService(),app=express(),log=logger(process.env.SILENT),argv=JSON.parse(process.env.ARGV),explorerRoot=path.resolve(process.env.EXPLORER_DIRECTORY||process.cwd()),explorerRootRealPath=realpathSync(explorerRoot),explorerRootId=crypto.createHash("sha256").update(explorerRootRealPath).digest("hex"),port=argv.p||argv.port,isEditMode=process.env.EXPLORER_EDIT==="true",explorerPassword=process.env.EXPLORER_AUTH||"",isAuthEnabled=!!explorerPassword,visitorKeys=new Set,httpServer=null,shuttingDown=!1,MAX_UPLOAD_FILE_SIZE=2*1024*1024*1024,MAX_UPLOAD_TOTAL_SIZE=2*1024*1024*1024,MAX_UPLOAD_FILE_COUNT=100,MAX_MULTIPART_OVERHEAD_SIZE=2*1024*1024,upload=multer({dest:path.join(os.tmpdir(),"mock-service-cli-upload"),preservePath:!0,limits:{fileSize:MAX_UPLOAD_FILE_SIZE,files:MAX_UPLOAD_FILE_COUNT,fields:10}}),archiveService=new ArchiveService({rootPath:explorerRootRealPath,resolvePath:resolveExplorerPath,getChildPath});function isPathInsideRoot(fullPath,resolvedRoot=explorerRootRealPath){let relativePath=path.relative(resolvedRoot,fullPath);return relativePath===""||!relativePath.startsWith("..")&&!path.isAbsolute(relativePath)}function normalizeExplorerInputPath(inputPath){let decodedPath=decodeURIComponent(String(inputPath||"/")).replace(/\\/g,"/");return!decodedPath||decodedPath==="."?"/":decodedPath.startsWith("/")?decodedPath:`/${decodedPath}`}function resolveExplorerPath(inputPath){let relativePath=normalizeExplorerInputPath(inputPath).replace(/^\/+/,""),fullPath=path.resolve(explorerRoot,relativePath);if(!isPathInsideRoot(fullPath,explorerRoot)){let error=new Error("Access denied");throw error.statusCode=403,error}if(!existsSync(fullPath))return fullPath;let realPath=realpathSync(fullPath);if(!isPathInsideRoot(realPath)){let error=new Error("Access denied");throw error.statusCode=403,error}return realPath}function validateEntryName(name){if(typeof name!="string")return"Name must be a string";let normalizedName=name.trim();if(!normalizedName||normalizedName==="."||normalizedName==="..")return"Invalid name";if(/[/\\\0<>:"|?*]/.test(normalizedName))return"Name contains invalid characters";if(process.platform==="win32"){let upperName=normalizedName.replace(/[. ]+$/g,"").split(".")[0].toUpperCase();if(new Set(["CON","PRN","AUX","NUL","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","LPT1","LPT2","LPT3","LPT4","LPT5","LPT6","LPT7","LPT8","LPT9"]).has(upperName)||normalizedName.endsWith(" ")||normalizedName.endsWith("."))return"Name is not supported on Windows"}return null}function getChildPath(parentPath,name){let nameError=validateEntryName(name);if(nameError){let error=new Error(nameError);throw error.statusCode=400,error}let parentFullPath=resolveExplorerPath(parentPath||"/");if(!existsSync(parentFullPath)||!statSync(parentFullPath).isDirectory()){let error=new Error("Parent directory not found");throw error.statusCode=404,error}let childPath=path.resolve(parentFullPath,name.trim());if(!isPathInsideRoot(childPath)){let error=new Error("Access denied");throw error.statusCode=403,error}return childPath}function requireEditMode(req,res,next){if(!isEditMode)return res.status(403).json({error:"File explorer is read-only. Restart with --edit to modify files."});next()}function isValidExplorerPassword(value){if(!isAuthEnabled)return!0;let provided=Buffer.from(String(value||"")),expected=Buffer.from(explorerPassword);return provided.length===expected.length&&crypto.timingSafeEqual(provided,expected)}function getExplorerPassword(req){return req.get("x-file-explorer-password")||req.body&&req.body.password}function requireExplorerAuth(req,res,next){if(!isValidExplorerPassword(getExplorerPassword(req)))return res.status(401).json({error:"Authentication required"});next()}function logExplorerVisit(req){let userAgent=req.get("user-agent")||"",ip=normalizeRemoteAddress(req.socket&&req.socket.remoteAddress),visitorKey=`${ip}
157
+ ${userAgent}`;if(visitorKeys.has(visitorKey))return;visitorKeys.add(visitorKey);let parsed=new UAParser(userAgent).getResult(),browser=[parsed.browser.name,parsed.browser.version].filter(Boolean).join(" ")||"Unknown",operatingSystem=[parsed.os.name,parsed.os.version].filter(Boolean).join(" ")||"Unknown";log.info(`File explorer visitor: ip=${ip}, os=${operatingSystem}, browser=${browser}, userAgent=${userAgent}`)}function getUploadTargetPath(parentPath,originalName){let normalizedName=String(originalName||"").replace(/\\/g,"/").replace(/^\/+/,""),parts=normalizedName.split("/").filter(Boolean);if(parts.length===0||normalizedName!==parts.join("/")){let error=new Error("Invalid upload path");throw error.statusCode=400,error}parts.forEach(part=>{let nameError=validateEntryName(part);if(nameError){let error=new Error(nameError);throw error.statusCode=400,error}});let parentFullPath=resolveExplorerPath(parentPath||"/");if(!existsSync(parentFullPath)||!statSync(parentFullPath).isDirectory()){let error=new Error("Parent directory not found");throw error.statusCode=404,error}let targetPath=path.resolve(parentFullPath,...parts);if(!isPathInsideRoot(targetPath)){let error=new Error("Access denied");throw error.statusCode=403,error}return{targetPath,parentFullPath,parts}}function ensureUploadParent(parentFullPath,parts){let current=parentFullPath;parts.slice(0,-1).forEach(part=>{if(current=path.join(current,part),existsSync(current)){let stats=lstatSync(current);if(!stats.isDirectory()||stats.isSymbolicLink()||!isPathInsideRoot(realpathSync(current))){let error=new Error("Upload path is not a safe directory");throw error.statusCode=403,error}}else mkdirSync(current)})}function moveUploadedFile(sourcePath,targetPath){copyFileSync(sourcePath,targetPath,fsConstants.COPYFILE_EXCL),unlinkSync(sourcePath)}function cleanupUploadedTempFiles(files=[]){files.forEach(file=>{file&&file.path&&existsSync(file.path)&&rmSync(file.path,{force:!0})})}function enforceUploadRequestSize(req,res,next){let contentLength=Number(req.get("content-length"));if(Number.isFinite(contentLength)&&contentLength>MAX_UPLOAD_TOTAL_SIZE+MAX_MULTIPART_OVERHEAD_SIZE)return res.status(413).json({error:"Total upload size exceeds 2GB limit"});next()}function deleteExplorerPath(targetPath){let fullPath=resolveExplorerPath(targetPath);if(path.resolve(fullPath)===explorerRootRealPath){let error=new Error("Cannot delete explorer root");throw error.statusCode=400,error}if(!existsSync(fullPath)){let error=new Error("Path not found");throw error.statusCode=404,error}rmSync(fullPath,{recursive:!0,force:!1})}process.env.PORT?init():(portfinder.basePort=port||8090,portfinder.getPort(function(err,foundPort){if(err)throw err;process.env.PORT=foundPort,init()}));function init(){app.use(hostAllowlistMiddleware()),app.use(express.json());let faviconInstanceId=crypto.randomUUID(),explorerFaviconUrl=`/favicon-file-explorer.svg?instance=${faviconInstanceId}`,loginFaviconUrl=`/favicon-file-explorer-login.svg?instance=${faviconInstanceId}`,sendFavicon=(filename,res)=>{res.type("image/svg+xml").set("Cache-Control","no-store").sendFile(path.resolve(__dirname,filename))},sendExplorerPage=(filename,faviconUrl,res)=>{let htmlPath=path.resolve(__dirname,filename);if(!existsSync(htmlPath))return res.status(404).send("File explorer page not found");res.type("html").send(readFileSync(htmlPath,"utf8").replace("__FILE_EXPLORER_FAVICON_URL__",faviconUrl))};app.get("/favicon-file-explorer.svg",(req,res)=>sendFavicon("./favicon-file-explorer.svg",res)),app.get("/favicon-file-explorer-login.svg",(req,res)=>sendFavicon("./favicon-file-explorer-login.svg",res)),app.get("/",(req,res)=>sendExplorerPage("./file-explorer.html",explorerFaviconUrl,res)),app.get("/__login",(req,res)=>sendExplorerPage("./file-explorer-login.html",loginFaviconUrl,res)),app.post("/__api/auth/verify",(req,res)=>{if(!isValidExplorerPassword(getExplorerPassword(req)))return res.status(401).json({error:"Invalid password"});res.json({success:!0,authEnabled:isAuthEnabled})}),app.use("/__api",requireExplorerAuth),app.get("/__api/config",(req,res)=>{logExplorerVisit(req),res.json({editMode:isEditMode,authEnabled:isAuthEnabled,rootId:explorerRootId})}),app.get("/__api/archive/capabilities",requireEditMode,(req,res)=>{res.json(archiveService.getCapabilities())}),app.get("/__api/health",(req,res)=>{res.json({success:!0})}),app.get("/__api/list",async(req,res)=>{let dirPath=normalizeExplorerInputPath(req.query.path||"/"),fullPath;try{fullPath=resolveExplorerPath(dirPath)}catch(error){return res.status(error.statusCode||500).json({error:error.message})}if(!existsSync(fullPath))return res.status(404).json({error:"Path not found"});try{if(!(await fsPromises.lstat(fullPath)).isDirectory())return res.status(400).json({error:"Not a directory"});let files=await fsPromises.readdir(fullPath,{withFileTypes:!0}),result=await Promise.all(files.map(async file=>{let filePath=path.join(fullPath,file.name),fileStats,hasError=!1;try{fileStats=await fsPromises.lstat(filePath)}catch{hasError=!0}let relativePath=path.posix.join(dirPath,file.name),isDirectory=hasError?file.isDirectory():fileStats.isDirectory();return{name:file.name,path:relativePath.replace(/\\/g,"/"),isDirectory,size:hasError?0:fileStats.size,mtime:hasError?new Date:fileStats.mtime,birthtime:hasError?new Date:fileStats.birthtime,isHidden:isHiddenPath(filePath),error:hasError?"Cannot access file":null}}));result.sort((a,b)=>a.isDirectory!==b.isDirectory?a.isDirectory?-1:1:a.name.localeCompare(b.name)),res.json({currentPath:dirPath,parentPath:dirPath==="/"?null:path.posix.dirname(dirPath),files:result})}catch(error){res.status(500).json({error:error.message})}}),app.get("/__api/file",(req,res)=>{let filePath=normalizeExplorerInputPath(req.query.path||"/"),fullPath;try{fullPath=resolveExplorerPath(filePath)}catch(error){return res.status(error.statusCode||500).json({error:error.message})}if(!existsSync(fullPath))return res.status(404).json({error:"File not found"});let stats=statSync(fullPath);if(stats.isDirectory())return res.status(400).json({error:"Is a directory"});if(req.query.download==="1")return res.download(fullPath,path.basename(filePath));let ext=path.extname(filePath).toLowerCase(),imageExts=[".jpg",".jpeg",".png",".gif",".bmp",".webp",".svg",".ico"],textExts=[".txt",".json",".js",".css",".html",".xml",".md",".csv",".yaml",".yml",".log"];if(imageExts.includes(ext))res.sendFile(fullPath);else if(textExts.includes(ext)||stats.size<1024*1024)try{let content=readFileSync(fullPath,"utf-8");res.json({name:path.basename(filePath),type:"text",content,size:stats.size})}catch{res.download(fullPath)}else res.download(fullPath)}),app.post("/__api/open-in-explorer",async(req,res)=>{let filePath=normalizeExplorerInputPath(req.body.path||"/"),fullPath;try{fullPath=resolveExplorerPath(filePath)}catch(error){return res.status(error.statusCode||500).json({error:error.message})}if(!existsSync(fullPath))return res.status(404).json({error:"Path not found"});let result=await openPathInFileManager(fullPath);if(!result.ok)return result.unsupported?res.status(400).json({error:"Unsupported platform"}):(console.error(colors.red(`Failed to open in explorer: ${result.error.message}`)),res.status(500).json({error:"Failed to open in explorer"}));res.json({success:!0,path:fullPath})}),app.post("/__api/path",requireEditMode,(req,res)=>{let parentPath=req.body&&req.body.parentPath||"/",name=req.body&&req.body.name,type=req.body&&req.body.type||"file";if(type!=="file"&&type!=="directory")return res.status(400).json({error:"Invalid type"});let fullPath;try{fullPath=getChildPath(parentPath,name)}catch(error){return res.status(error.statusCode||500).json({error:error.message})}if(existsSync(fullPath))return res.status(409).json({error:"Path already exists"});try{type==="directory"?mkdirSync(fullPath):writeFileSync(fullPath,""),res.json({success:!0,path:fullPath})}catch(error){console.error(colors.red(`Failed to create path: ${error.message}`)),res.status(500).json({error:"Failed to create path"})}}),app.patch("/__api/path",requireEditMode,(req,res)=>{let sourcePath=req.body&&req.body.path,name=req.body&&req.body.name,fullPath,nextPath;try{if(fullPath=resolveExplorerPath(sourcePath),path.resolve(fullPath)===explorerRootRealPath)return res.status(400).json({error:"Cannot rename explorer root"});if(!existsSync(fullPath))return res.status(404).json({error:"Path not found"});nextPath=getChildPath(path.posix.dirname(normalizeExplorerInputPath(sourcePath||"/")),name)}catch(error){return res.status(error.statusCode||500).json({error:error.message})}if(existsSync(nextPath))return res.status(409).json({error:"Path already exists"});try{renameSync(fullPath,nextPath),res.json({success:!0,path:sourcePath,nextPath})}catch(error){console.error(colors.red(`Failed to rename path: ${error.message}`)),res.status(500).json({error:"Failed to rename path"})}}),app.delete("/__api/path",requireEditMode,(req,res)=>{let targetPath=req.body&&req.body.path||"/";try{deleteExplorerPath(targetPath),res.json({success:!0,path:targetPath})}catch(error){console.error(colors.red(`Failed to delete path: ${error.message}`)),res.status(error.statusCode||500).json({error:error.statusCode?error.message:"Failed to delete path"})}}),app.delete("/__api/paths",requireEditMode,(req,res)=>{let paths=req.body&&req.body.paths||[];if(!Array.isArray(paths)||paths.length===0)return res.status(400).json({error:"Paths must be a non-empty array"});let deleted=[];try{paths.forEach(targetPath=>{deleteExplorerPath(targetPath),deleted.push(targetPath)}),res.json({success:!0,deleted})}catch(error){console.error(colors.red(`Failed to delete paths: ${error.message}`)),res.status(error.statusCode||500).json({error:error.statusCode?error.message:"Failed to delete paths",deleted})}}),app.post("/__api/upload",requireEditMode,enforceUploadRequestSize,upload.any(),(req,res)=>{let parentPath=req.body&&req.body.parentPath||"/",files=req.files||[];if(!files.length)return res.status(400).json({error:"No files uploaded"});if(files.reduce((sum,file)=>sum+file.size,0)>MAX_UPLOAD_TOTAL_SIZE)return cleanupUploadedTempFiles(files),res.status(413).json({error:"Total upload size exceeds 2GB limit"});let uploaded=[],failed=[];files.forEach(file=>{try{let{targetPath,parentFullPath,parts}=getUploadTargetPath(parentPath,file.originalname);if(existsSync(targetPath)){failed.push({name:file.originalname,error:"Path already exists",statusCode:409});return}if(ensureUploadParent(parentFullPath,parts),existsSync(targetPath)){failed.push({name:file.originalname,error:"Path already exists",statusCode:409});return}moveUploadedFile(file.path,targetPath),uploaded.push({name:file.originalname,path:path.posix.join(normalizeExplorerInputPath(parentPath),...parts)})}catch(error){failed.push({name:file.originalname,error:error.message,statusCode:error.statusCode||500})}finally{existsSync(file.path)&&rmSync(file.path,{force:!0})}}),res.status(failed.length?207:200).json({success:failed.length===0,uploaded,failed})}),app.get("/__api/archive/preview",requireEditMode,async(req,res)=>{try{let preview=await archiveService.listArchive(normalizeExplorerInputPath(req.query.path||"/"));res.json(preview)}catch(error){res.status(error.statusCode||500).json({error:error.message})}}),app.post("/__api/archive/jobs",requireEditMode,(req,res)=>{let payload=req.body||{},operation=payload.operation;if(operation!=="create"&&operation!=="extract")return res.status(400).json({error:"Archive operation must be create or extract"});try{let job=archiveService.startJob(operation,payload);res.status(202).json({id:job.id,status:job.status,type:job.type})}catch(error){res.status(error.statusCode||500).json({error:error.message})}}),app.get("/__api/archive/jobs/:id",requireEditMode,(req,res)=>{let job=archiveService.getJob(req.params.id);if(!job)return res.status(404).json({error:"Archive job not found"});res.json({id:job.id,type:job.type,status:job.status,progress:job.progress,result:job.result,error:job.error,createdAt:job.createdAt,finishedAt:job.finishedAt||null})}),app.delete("/__api/archive/jobs/:id",requireEditMode,(req,res)=>{try{let job=archiveService.cancelJob(req.params.id);res.json({id:job.id,status:job.status})}catch(error){res.status(error.statusCode||500).json({error:error.message})}}),app.use((error,req,res,next)=>{if(error instanceof multer.MulterError){cleanupUploadedTempFiles(req.files);let statusCode=error.code==="LIMIT_FILE_SIZE"||error.code==="LIMIT_FILE_COUNT"?413:400;return res.status(statusCode).json({error:error.message})}if(error)return console.error(colors.red(`File explorer request failed: ${error.message}`)),res.status(error.statusCode||500).json({error:error.message||"Request failed"});next()}),startServer()}function startServer(){httpServer=require("http").createServer(app),httpServer.requestTimeout=0,httpServer.listen(Number.parseInt(process.env.PORT,10),getServerHost(),()=>{if(console.info([colors.yellow(`
158
158
  Starting up file-explorer-server, serving `),colors.cyan(explorerRoot),colors.yellow(` ${dateFormat("YYYY-mm-dd HH:MM:SS",new Date)}`)].join("")),console.info([colors.yellow(`
159
159
  \u{1F30D} file-explorer-server version: `),colors.cyan(getPackageVersion()),`
160
160
  `].join("")),console.info(colors.yellow(`
@@ -4,7 +4,8 @@
4
4
  "watch": {
5
5
  "ignore": ["**/node_modules/**", "**/.git/**"],
6
6
  "delay": 100,
7
- "fullReload": false
7
+ "fullReload": false,
8
+ "depth": 3
8
9
  },
9
10
  "injectTag": "body",
10
11
  "mounts": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mock-service-cli-ultra",
3
- "version": "4.8.0",
3
+ "version": "4.9.0",
4
4
  "description": "🦅 Local Mock/Static/SPA server, Http?s request proxy, API overview page, File explorer (Ultra archive formats)",
5
5
  "main": "./dist/mockServer.js",
6
6
  "bin": {