xshell 1.0.6 → 1.0.7
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/file.d.ts +19 -10
- package/file.js +14 -22
- package/file.js.map +1 -1
- package/i18n/i18n-scan.js +0 -0
- package/net.browser.d.ts +1 -1
- package/net.browser.js +1 -1
- package/net.browser.js.map +1 -1
- package/net.d.ts +1 -1
- package/net.js +1 -1
- package/net.js.map +1 -1
- package/package.json +136 -137
- package/patches/@types__byte-size@8.1.0.patch +14 -0
- package/patches/koa@2.14.1.patch +34 -0
- package/process.js +1 -1
- package/process.js.map +1 -1
- package/server.d.ts +0 -2
- package/server.js +8 -20
- package/server.js.map +1 -1
- package/tsconfig.json +1 -1
package/process.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"process.js","sourceRoot":"","sources":["process.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,KAAK,EAGR,MAAM,eAAe,CAAA;AAEtB,OAAO,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAA;AAE7B,OAAO,KAAK,MAAM,YAAY,CAAA;AAE9B,OAAO,EAAE,CAAC,EAAE,MAAM,oBAAoB,CAAA;AAEtC,OAAO,gBAAgB,CAAA;AAEvB,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAGpC,MAAM,CAAC,MAAM,UAAU,GAAG,OAAO,CAAC,QAAQ,CAAC,QAAQ,EAAE,CAAA;AA0CrD;;;;;;;;;;EAUE;AACF,MAAM,CAAC,KAAK,UAAU,KAAK,CAAE,GAAW,EAAE,OAAiB,EAAG,EAAE,EAC5D,GAAG,EAEH,QAAQ,GAAG,OAAO,EAElB,KAAK,GAAG,IAAI,EAEZ,KAAK,GAAG,MAAM,EAEd,QAAQ,GAAG,KAAK,EAEhB,GAAG,EAEH,MAAM,EAAE,OAAO,GAAG,IAAI,MACR,EAAG;IACjB,MAAM,OAAO,GAAiB;QAC1B,GAAG;QACH,KAAK,E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AAM,EACb,OAAO,GAAG,KAAK,EACf,cAAc,GAAG,KAAK,EACtB,GAAG,QAAQ,KACM,EAAG;IAExB,OAAO,IAAI,CAAC,UAAU,EAAE;QACpB,GAAI,cAAc,CAAC,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,CAAC,EAAG;QAC/C,GAAI,OAAO,CAAC,CAAC,CAAC,CAAC,0CAA0C,CAAC,CAAC,CAAC,CAAC,EAAG;QAChE,GAAI,KAAK,CAAC,CAAC,CAAC,CAAC,WAAW,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,EAAG;QACtC,GAAI,OAAO,CAAC,CAAC,CAAC;YACV,MAAM,CAAC,CAAC,CAAC,yBAAyB,OAAO,EAAE,CAAC,CAAC,CAAC,qBAAqB,OAAO,EAAE;SAC/E,CAAC,CAAC,CAAC,EAAG;QACP,GAAI,MAAM,CAAC,CAAC,CAAC;YACT,sBAAsB;YACtB,0CAA0C;SAC7C,CAAC,CAAC,CAAC,EAAG;QACP,KAAK;QACL,GAAI,IAAI;KACX,EAAE;QACC,KAAK;QACL,GAAG,QAAQ;KACd,CAAC,CAAA;AACN,CAAC;AAGD,MAAM,eAAe,GAAG;IACpB,CAAC,WAAW,CAAC,EAAE,MAAM;IACrB,CAAC,UAAU,CAAC,EAAE,MAAM;CACd,CAAA","sourcesContent":["import {\n spawn,\n type SpawnOptions,\n type ChildProcess\n} from 'child_process'\nimport { Readable } from 'stream'\nimport { userInfo } from 'os'\n\nimport iconv from 'iconv-lite'\n\nimport { t } from './i18n/instance.js'\n\nimport './prototype.js'\nimport { Encoding } from './file.js'\nimport { inspect } from './utils.js'\n\n\nexport const exe_nodejs = process.execPath.to_slash()\n\n\n// ------------------------------------ start & call\ninterface StartOptions {\n /** `继承当前工作目录 process.cwd()` 子进程的工作目录 `inherit the cwd` cwd of the child process. */\n cwd?: string\n \n /** `process.env` 覆盖/添加到 process.env 的环境变量 overwrite/add to process.env */\n env?: Record<string, string>\n \n /** `'utf-8'` 子进程输出编码 child output encoding */\n encoding?: Encoding\n \n /** `true` print 选项,支持设置细项 print option (with details) */\n print?: boolean | {\n stdout: boolean\n stderr: boolean\n command: boolean\n code: boolean\n }\n \n /** `'pipe'` 设置为 'ignore' 时忽略 stdio 处理 when 'ignore' then ignore stdio processing */\n stdio?: 'pipe' | 'ignore' | ['pipe' | 'ignore' | 'inherit', 'pipe' | 'ignore' | 'inherit', 'pipe' | 'ignore' | 'inherit']\n \n /** `false` 是否断开和 child 的关系 (ignore stdio, unref) whether to break the connection with child (ignore stdio, unref) */\n detached?: boolean\n \n /** 为 true 时会设置 UV_PROCESS_WINDOWS_HIDE \n 然后设置启动进程的参数 CREATE_NO_WINDOW, 和 SW_HIDE \n d:/0/libuv/src/win/process.c \n CREATE_NO_WINDOW:\n The process is a console application that is being run without a console window. \n Therefore, the console handle for the application is not set.\n This flag is ignored if the application is not a console application, or \n if it is used with either CREATE_NEW_CONSOLE or DETACHED_PROCESS.\n \n 具体有什么用还不清楚\n */\n window?: boolean\n}\n\n/** start process \n - exe: .exe 路径或文件名 (建议使用完整路径,跳过 path 搜索,性能更高) path or filename (full path is recommanded to skip path searching for better perf)\n - args: `[]` 参数列表 arguments list\n - options\n - cwd?: `fp_root`\n - env?: `process.env` 覆盖/添加到 process.env 的环境变量 overwrite/add to process.env\n - encoding?: `'utf-8'` 子进程输出编码 child output encoding\n - print?: `true` print 选项,支持设置细项 print option (with details)\n - stdio?: `'pipe'` 设置为 'ignore' 时忽略 stdio 处理 when 'ignore' then ignore stdio processing\n - detached?: `false` 是否断开和 child 的关系 (ignore stdio, unref) whether to break the connection with child (ignore stdio, unref)\n*/\nexport async function start (exe: string, args: string[] = [ ], {\n cwd,\n \n encoding = 'utf-8',\n \n print = true,\n \n stdio = 'pipe',\n \n detached = false,\n \n env,\n \n window: _window = true,\n}: StartOptions = { }): Promise<ChildProcess> {\n const options: SpawnOptions = {\n cwd,\n shell: false,\n windowsHide: !_window,\n stdio,\n ... env ? {\n env: { ...process.env, ...env }\n } : { },\n }\n \n if (typeof print === 'boolean')\n print = {\n stdout: print,\n stderr: print,\n command: print,\n code: print,\n }\n \n if (typeof stdio === 'string')\n stdio = [stdio, stdio, stdio]\n \n if (print.command)\n console.log((\n (short_exe_names[exe] || (exe.includes(' ') ? exe.quote() : exe)) +\n (args.length ? \n ' ' + args.filter(arg => arg !== '--suppressApplicationTitle')\n .map(arg => arg.includes(' ') ? arg.quote() : arg)\n .join(' ')\n :\n '')\n ).blue)\n \n if (detached) {\n let child = spawn(exe, args, {\n ...options,\n stdio: 'ignore',\n detached: true,\n })\n \n child.unref()\n return child\n }\n \n let child = spawn(exe, args, options)\n \n // 防止 child spawn 失败时 crash nodejs 进程\n child.on('error', error => {\n console.error(error)\n })\n \n if (stdio[0] === 'pipe')\n child.stdin.setDefaultEncoding('utf8')\n \n if (\n stdio.every(s => \n s === 'ignore')\n )\n return child\n \n if (encoding !== 'binary') {\n if (stdio[1] === 'pipe') {\n if (encoding === 'utf-8')\n child.stdout.setEncoding('utf-8')\n else\n child.stdout = child.stdout.pipe(\n iconv.decodeStream(encoding)\n ) as any as Readable\n \n if (print.stdout)\n child.stdout.pipe(process.stdout, { end: false })\n }\n \n if (stdio[2] === 'pipe') {\n if (encoding === 'utf-8')\n child.stderr.setEncoding('utf-8')\n else\n child.stderr = child.stderr.pipe(\n iconv.decodeStream(encoding)\n ) as any as Readable\n \n if (print.stderr)\n child.stderr.pipe(process.stderr, { end: false })\n }\n }\n \n return child\n}\n\n\nexport interface CallOptions extends StartOptions {\n throw_code?: boolean\n input?: string\n}\n\nexport interface CallResult <TOutput extends string | Buffer = string> {\n pid: number\n stdout: TOutput\n stderr: TOutput\n code: number | null\n signal: NodeJS.Signals | null\n child: ChildProcess\n [inspect.custom] (): string\n}\n\n\n/** call process for result\n - exe: .exe 路径或文件名 (建议使用路径,跳过 path 搜索,性能更高) path or filename (full path is recommanded to skip path searching for better perf)\n - args: `[]` 参数列表 arguments list\n - options?:\n - cwd?: `'d:/'`\n - env?: `process.env` 覆盖/添加到 process.env 的环境变量 overwrite/add to process.env\n - encoding?: `'utf-8'` 子进程输出编码, 设置为 binary 时返回 stdout, stderr 类型为 Buffer; 否则是 string \n child output encoding. When set to binary, return stdout, stderr is of type Buffer; otherwise it is string\n - print?: `true` print 选项,支持设置细项 print option (with details)\n - stdio?: `'pipe'` 设置为 'ignore' 时忽略 stdio 处理 when 'ignore' then ignore stdio processing\n - input?: string, start 子进程之后写入到子进程 stdin 中的内容 After starting the sub-process, write to the content of the sub-process STDIN\n - detached?: `false` 是否断开和 child 的关系 (ignore stdio, unref) whether to break the connection with child (ignore stdio, unref)\n - throw_code?: `true` code 不为 0 时是否抛出异常 whether to throw Error when code is not 0 */\nexport async function call (exe: string, args?: string[]): Promise<CallResult<string>>\nexport async function call (exe: string, args?: string[], options?: CallOptions & { encoding: 'binary' }): Promise<CallResult<Buffer>>\nexport async function call (exe: string, args?: string[], options?: CallOptions): Promise<CallResult<string>>\nexport async function call (exe: string, args: string[] = [ ], options: CallOptions = { }): Promise<CallResult<string | Buffer>> {\n const {\n encoding = 'utf-8', \n throw_code = true,\n input,\n } = options\n \n let {\n stdio = 'pipe',\n print = true\n } = options\n \n if (typeof print === 'boolean')\n print = {\n command: print,\n stdout: print,\n stderr: print,\n code: print,\n }\n \n if (typeof stdio === 'string')\n stdio = [stdio, stdio, stdio]\n \n const cmd = \n (short_exe_names[exe] || (exe.includes(' ') ? exe.quote() : exe)) + \n (args.length ? (\n ' ' + args.map(arg => arg.includes(' ') ? arg.quote() : arg)\n .join(' '))\n :\n '')\n \n if (print.command)\n console.log(cmd.blue)\n \n let child = await start(exe, args, {\n ...options,\n print: false,\n })\n \n if (input)\n child.stdin.write(input)\n \n // --- collect output\n let stdouts: (string | Buffer)[] = [ ]\n let stderrs: (string | Buffer)[] = [ ]\n \n let code: number | null, \n signal: NodeJS.Signals\n \n await Promise.all([\n new Promise<void>(resolve => {\n child.once('exit', (_code, _signal) => {\n code = _code\n signal = _signal\n resolve()\n })\n }),\n (async () => {\n if (stdio[1] === 'pipe')\n for await (const chunk of child.stdout as AsyncIterable<string | Buffer>) {\n if (encoding !== 'binary' && print.stdout)\n process.stdout.write(chunk)\n stdouts.push(chunk)\n }\n })(),\n (async () => {\n if (stdio[2] === 'pipe')\n for await (const chunk of child.stderr as AsyncIterable<string | Buffer>) {\n if (encoding !== 'binary' && print.stderr)\n process.stderr.write(chunk)\n stderrs.push(chunk)\n }\n })()\n ])\n \n const message = `${t('进程')} ${cmd} ` + (\n code ? \n `(pid: ${child.pid}) ${ throw_code ? t('异常结束') : t('结束') }, code: ${code}${ signal ? `, signal: ${ signal }` : '' }`\n :\n t('正常结束'))\n \n if (print.code || (throw_code && (code || signal)))\n console.log(message[(throw_code && (code || signal)) ? 'red' : 'blue'])\n \n const result = {\n pid: child.pid,\n \n stdout: encoding === 'binary' ?\n Buffer.concat(stdouts as Buffer[])\n :\n (stdouts as string[]).join(''),\n \n stderr: encoding === 'binary' ?\n Buffer.concat(stderrs as Buffer[])\n :\n (stderrs as string[]).join(''),\n \n code,\n \n signal,\n \n child,\n \n [inspect.custom] () {\n return inspect(this, { omit: ['child'] })\n }\n }\n \n if (code && throw_code)\n throw Object.assign(\n new Error(message), \n result\n )\n \n return result\n}\n\n\n/** call node <js> for result\n - js: .js 路径 (相对路径根据 cwd 解析) path (relative path will resolve based on cwd)\n - args: `[]` 参数列表 arguments list\n - options\n - cwd?: `'d:/'`\n - env?: `process.env` 覆盖/添加到 process.env 的环境变量 overwrite/add to process.env\n - encoding?: `'utf-8'` 子进程输出编码 child process output encoding\n - print?: `true` print 选项,支持设置细项 print option (with details)\n - stdio?: `'pipe'` 设置为 'ignore' 时忽略 stdio 处理 when 'ignore' then ignore stdio processing\n - detached?: `false` 是否断开和 child 的关系 (ignore stdio, unref) whether to break the connection with child (ignore stdio, unref)\n - throw_code?: `true` code 不为 0 时是否抛出异常 whether to throw Error when code is not 0 */\nexport async function call_nodejs (js: string, args: string[] = [], options?: CallOptions) {\n return call(exe_nodejs, [js, ...args], options)\n}\n\n\n// ------------------------------------ term\nexport interface TermOptions {\n /** `d:/t/` */\n cwd?: string\n \n /** `true` 打印参数 */\n print?: boolean\n \n title?: string\n \n // 不支持 background, 在 WinTerm 中后台创建标签页,而非创建并切换到该标签页\n // 不支持 icon\n // 不支持 env, WindowsTerminal 在调用 CreateProcess API 时没有传入 env\n}\n\nexport const exe_winterm = `C:/Users/${userInfo().username}/AppData/Local/Microsoft/WindowsApps/wt.exe`\n\n/** 新建 terminal 窗口执行进程 New Terminal window execution process\n - exe: exe 文件路径 exe file path\n - args: 调用参数 call parameter\n - options?: WinTermOptions\n*/\nexport function term (exe: string, args: string[] = [], {\n cwd = 'd:/t/',\n \n print = true,\n \n title,\n \n // env\n}: TermOptions = { }) {\n \n \n return start(\n exe_winterm,\n [\n 'new-tab',\n \n '-d', cwd,\n \n ... title ? ['--suppressApplicationTitle', '--title', title] : [ ],\n \n exe,\n \n ...args.map(arg => \n arg.replaceAll(';', '\\\\;')), \n ],\n {\n print,\n detached: true,\n cwd,\n // env\n }\n )\n}\n\n\nexport interface TermNodeOptions extends TermOptions {\n /** nodejs debugger port */\n inspect?: number\n \n /** break at first line */\n break?: boolean\n \n /** 使用 ts-node 直接运行 use ts-node to run directly */\n tsnode?: boolean\n \n /** `false` --experimental-specifier-resolution=node */\n resolve?: boolean\n \n /** `false` --trace-warnings */\n trace_warnings?: boolean\n}\n\n\n/** 在 term tab 中创建 node.exe 进程 create the node.exe process in term tab */\nexport async function term_nodejs (\n fp_js: string, \n args: string[] = [ ],\n {\n title, \n inspect, \n tsnode = false,\n break: _break,\n resolve = false,\n trace_warnings = false,\n ..._options\n }: TermNodeOptions = { }\n) {\n return term(exe_nodejs, [\n ... trace_warnings ? ['--trace-warnings'] : [ ],\n ... resolve ? ['--experimental-specifier-resolution=node'] : [ ],\n ... title ? [`--title=${title}`] : [ ],\n ... inspect ? [\n _break ? `--inspect-brk=0.0.0.0:${inspect}` : `--inspect=0.0.0.0:${inspect}`\n ] : [ ],\n ... tsnode ? [\n '--loader=ts-node/esm',\n '--experimental-specifier-resolution=node'\n ] : [ ],\n fp_js,\n ... args\n ], {\n title,\n ..._options,\n })\n}\n\n\nconst short_exe_names = {\n [exe_winterm]: 'term',\n [exe_nodejs]: 'node',\n} as const\n\n"]}
|
|
1
|
+
{"version":3,"file":"process.js","sourceRoot":"","sources":["process.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,KAAK,EAGR,MAAM,eAAe,CAAA;AAEtB,OAAO,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAA;AAE7B,OAAO,KAAK,MAAM,YAAY,CAAA;AAE9B,OAAO,EAAE,CAAC,EAAE,MAAM,oBAAoB,CAAA;AAEtC,OAAO,gBAAgB,CAAA;AAEvB,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAGpC,MAAM,CAAC,MAAM,UAAU,GAAG,OAAO,CAAC,QAAQ,CAAC,QAAQ,EAAE,CAAA;AA0CrD;;;;;;;;;;EAUE;AACF,MAAM,CAAC,KAAK,UAAU,KAAK,CAAE,GAAW,EAAE,OAAiB,EAAG,EAAE,EAC5D,GAAG,EAEH,QAAQ,GAAG,OAAO,EAElB,KAAK,GAAG,IAAI,EAEZ,KAAK,GAAG,MAAM,EAEd,QAAQ,GAAG,KAAK,EAEhB,GAAG,EAEH,MAAM,EAAE,OAAO,GAAG,IAAI,MACR,EAAG;IACjB,MAAM,OAAO,GAAiB;QAC1B,GAAG;QACH,KAAK,EAAE,KAAK;QACZ,WAAW,EAAE,CAAC,OAAO;QACrB,KAAK;QACL,GAAI,GAAG,CAAC,CAAC,CAAC;YACN,GAAG,EAAE,EAAE,GAAG,OAAO,CAAC,GAAG,EAAE,GAAG,GAAG,EAAE;SAClC,CAAC,CAAC,CAAC,EAAG;KACV,CAAA;IAED,IAAI,OAAO,KAAK,KAAK,SAAS;QAC1B,KAAK,GAAG;YACJ,MAAM,EAAE,KAAK;YACb,MAAM,EAAE,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QAChE,GAAI,KAAK,CAAC,CAAC,CAAC,CAAC,WAAW,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,EAAG;QACtC,GAAI,OAAO,CAAC,CAAC,CAAC;YACV,MAAM,CAAC,CAAC,CAAC,yBAAyB,OAAO,EAAE,CAAC,CAAC,CAAC,qBAAqB,OAAO,EAAE;SAC/E,CAAC,CAAC,CAAC,EAAG;QACP,GAAI,MAAM,CAAC,CAAC,CAAC;YACT,sBAAsB;YACtB,0CAA0C;SAC7C,CAAC,CAAC,CAAC,EAAG;QACP,KAAK;QACL,GAAI,IAAI;KACX,EAAE;QACC,KAAK;QACL,GAAG,QAAQ;KACd,CAAC,CAAA;AACN,CAAC;AAGD,MAAM,eAAe,GAAG;IACpB,CAAC,WAAW,CAAC,EAAE,MAAM;IACrB,CAAC,UAAU,CAAC,EAAE,MAAM;CACd,CAAA","sourcesContent":["import {\n spawn,\n type SpawnOptions,\n type ChildProcess\n} from 'child_process'\nimport { Readable } from 'stream'\nimport { userInfo } from 'os'\n\nimport iconv from 'iconv-lite'\n\nimport { t } from './i18n/instance.js'\n\nimport './prototype.js'\nimport { Encoding } from './file.js'\nimport { inspect } from './utils.js'\n\n\nexport const exe_nodejs = process.execPath.to_slash()\n\n\n// ------------------------------------ start & call\ninterface StartOptions {\n /** `继承当前工作目录 process.cwd()` 子进程的工作目录 `inherit the cwd` cwd of the child process. */\n cwd?: string\n \n /** `process.env` 覆盖/添加到 process.env 的环境变量 overwrite/add to process.env */\n env?: Record<string, string>\n \n /** `'utf-8'` 子进程输出编码 child output encoding */\n encoding?: Encoding\n \n /** `true` print 选项,支持设置细项 print option (with details) */\n print?: boolean | {\n stdout: boolean\n stderr: boolean\n command: boolean\n code: boolean\n }\n \n /** `'pipe'` 设置为 'ignore' 时忽略 stdio 处理 when 'ignore' then ignore stdio processing */\n stdio?: 'pipe' | 'ignore' | ['pipe' | 'ignore' | 'inherit', 'pipe' | 'ignore' | 'inherit', 'pipe' | 'ignore' | 'inherit']\n \n /** `false` 是否断开和 child 的关系 (ignore stdio, unref) whether to break the connection with child (ignore stdio, unref) */\n detached?: boolean\n \n /** 为 true 时会设置 UV_PROCESS_WINDOWS_HIDE \n 然后设置启动进程的参数 CREATE_NO_WINDOW, 和 SW_HIDE \n d:/0/libuv/src/win/process.c \n CREATE_NO_WINDOW:\n The process is a console application that is being run without a console window. \n Therefore, the console handle for the application is not set.\n This flag is ignored if the application is not a console application, or \n if it is used with either CREATE_NEW_CONSOLE or DETACHED_PROCESS.\n \n 具体有什么用还不清楚\n */\n window?: boolean\n}\n\n/** start process \n - exe: .exe 路径或文件名 (建议使用完整路径,跳过 path 搜索,性能更高) path or filename (full path is recommanded to skip path searching for better perf)\n - args: `[]` 参数列表 arguments list\n - options\n - cwd?: `fp_root`\n - env?: `process.env` 覆盖/添加到 process.env 的环境变量 overwrite/add to process.env\n - encoding?: `'utf-8'` 子进程输出编码 child output encoding\n - print?: `true` print 选项,支持设置细项 print option (with details)\n - stdio?: `'pipe'` 设置为 'ignore' 时忽略 stdio 处理 when 'ignore' then ignore stdio processing\n - detached?: `false` 是否断开和 child 的关系 (ignore stdio, unref) whether to break the connection with child (ignore stdio, unref)\n*/\nexport async function start (exe: string, args: string[] = [ ], {\n cwd,\n \n encoding = 'utf-8',\n \n print = true,\n \n stdio = 'pipe',\n \n detached = false,\n \n env,\n \n window: _window = true,\n}: StartOptions = { }): Promise<ChildProcess> {\n const options: SpawnOptions = {\n cwd,\n shell: false,\n windowsHide: !_window,\n stdio,\n ... env ? {\n env: { ...process.env, ...env }\n } : { },\n }\n \n if (typeof print === 'boolean')\n print = {\n stdout: print,\n stderr: print,\n command: print,\n code: print,\n }\n \n if (typeof stdio === 'string')\n stdio = [stdio, stdio, stdio]\n \n if (print.command)\n console.log((\n (short_exe_names[exe] || (exe.includes(' ') ? exe.quote() : exe)) +\n (args.length ? \n ' ' + args.filter(arg => arg !== '--suppressApplicationTitle')\n .map(arg => arg.includes(' ') ? arg.quote() : arg)\n .join(' ')\n :\n '')\n ).blue)\n \n if (detached) {\n let child = spawn(exe, args, {\n ...options,\n stdio: 'ignore',\n detached: true,\n })\n \n child.unref()\n return child\n }\n \n let child = spawn(exe, args, options)\n \n // 防止 child spawn 失败时 crash nodejs 进程\n child.on('error', error => {\n console.error(error)\n })\n \n if (stdio[0] === 'pipe')\n child.stdin.setDefaultEncoding('utf8')\n \n if (\n stdio.every(s => \n s === 'ignore')\n )\n return child\n \n if (encoding !== 'binary') {\n if (stdio[1] === 'pipe') {\n if (encoding === 'utf-8')\n child.stdout.setEncoding('utf-8')\n else\n child.stdout = child.stdout.pipe(\n iconv.decodeStream(encoding)\n ) as any as Readable\n \n if (print.stdout)\n child.stdout.pipe(process.stdout, { end: false })\n }\n \n if (stdio[2] === 'pipe') {\n if (encoding === 'utf-8')\n child.stderr.setEncoding('utf-8')\n else\n child.stderr = child.stderr.pipe(\n iconv.decodeStream(encoding)\n ) as any as Readable\n \n if (print.stderr)\n child.stderr.pipe(process.stderr, { end: false })\n }\n }\n \n return child\n}\n\n\nexport interface CallOptions extends StartOptions {\n throw_code?: boolean\n input?: string\n}\n\nexport interface CallResult <TOutput extends string | Buffer = string> {\n pid: number\n stdout: TOutput\n stderr: TOutput\n code: number | null\n signal: NodeJS.Signals | null\n child: ChildProcess\n [inspect.custom] (): string\n}\n\n\n/** call process for result\n - exe: .exe 路径或文件名 (建议使用路径,跳过 path 搜索,性能更高) path or filename (full path is recommanded to skip path searching for better perf)\n - args: `[]` 参数列表 arguments list\n - options?:\n - cwd?: `'d:/'`\n - env?: `process.env` 覆盖/添加到 process.env 的环境变量 overwrite/add to process.env\n - encoding?: `'utf-8'` 子进程输出编码, 设置为 binary 时返回 stdout, stderr 类型为 Buffer; 否则是 string \n child output encoding. When set to binary, return stdout, stderr is of type Buffer; otherwise it is string\n - print?: `true` print 选项,支持设置细项 print option (with details)\n - stdio?: `'pipe'` 设置为 'ignore' 时忽略 stdio 处理 when 'ignore' then ignore stdio processing\n - input?: string, start 子进程之后写入到子进程 stdin 中的内容 After starting the sub-process, write to the content of the sub-process STDIN\n - detached?: `false` 是否断开和 child 的关系 (ignore stdio, unref) whether to break the connection with child (ignore stdio, unref)\n - throw_code?: `true` code 不为 0 时是否抛出异常 whether to throw Error when code is not 0 */\nexport async function call (exe: string, args?: string[]): Promise<CallResult<string>>\nexport async function call (exe: string, args?: string[], options?: CallOptions & { encoding: 'binary' }): Promise<CallResult<Buffer>>\nexport async function call (exe: string, args?: string[], options?: CallOptions): Promise<CallResult<string>>\nexport async function call (exe: string, args: string[] = [ ], options: CallOptions = { }): Promise<CallResult<string | Buffer>> {\n const {\n encoding = 'utf-8', \n throw_code = true,\n input,\n } = options\n \n let {\n stdio = 'pipe',\n print = true\n } = options\n \n if (typeof print === 'boolean')\n print = {\n command: print,\n stdout: print,\n stderr: print,\n code: print,\n }\n \n if (typeof stdio === 'string')\n stdio = [stdio, stdio, stdio]\n \n const cmd = \n (short_exe_names[exe] || (exe.includes(' ') ? exe.quote() : exe)) + \n (args.length ? (\n ' ' + args.map(arg => arg.includes(' ') ? arg.quote() : arg)\n .join(' '))\n :\n '')\n \n if (print.command)\n console.log(cmd.blue)\n \n let child = await start(exe, args, {\n ...options,\n print: false,\n })\n \n if (input)\n child.stdin.write(input)\n \n // --- collect output\n let stdouts: (string | Buffer)[] = [ ]\n let stderrs: (string | Buffer)[] = [ ]\n \n let code: number | null, \n signal: NodeJS.Signals\n \n await Promise.all([\n new Promise<void>(resolve => {\n child.once('exit', (_code, _signal) => {\n code = _code\n signal = _signal\n resolve()\n })\n }),\n (async () => {\n if (stdio[1] === 'pipe')\n for await (const chunk of child.stdout as AsyncIterable<string | Buffer>) {\n if (encoding !== 'binary' && print.stdout)\n process.stdout.write(chunk)\n stdouts.push(chunk)\n }\n })(),\n (async () => {\n if (stdio[2] === 'pipe')\n for await (const chunk of child.stderr as AsyncIterable<string | Buffer>) {\n if (encoding !== 'binary' && print.stderr)\n process.stderr.write(chunk)\n stderrs.push(chunk)\n }\n })()\n ])\n \n const message = `${t('进程')} ${cmd} ` + (\n code ? \n `(pid: ${child.pid}) ${ throw_code ? t('异常结束') : t('结束') }, code: ${code}${ signal ? `, signal: ${ signal }` : '' }`\n :\n t('正常结束'))\n \n if (print.code || (throw_code && (code || signal)))\n console.log(message[(throw_code && (code || signal)) ? 'red' : 'blue'])\n \n const result = {\n pid: child.pid,\n \n stdout: encoding === 'binary' ?\n Buffer.concat(stdouts as Buffer[])\n :\n (stdouts as string[]).join(''),\n \n stderr: encoding === 'binary' ?\n Buffer.concat(stderrs as Buffer[])\n :\n (stderrs as string[]).join(''),\n \n code,\n \n signal,\n \n child,\n \n [inspect.custom] () {\n return inspect(this, { omit: ['child'] })\n }\n }\n \n if (code && throw_code)\n throw Object.assign(new Error(message), { result })\n \n return result\n}\n\n\n/** call node <js> for result\n - js: .js 路径 (相对路径根据 cwd 解析) path (relative path will resolve based on cwd)\n - args: `[]` 参数列表 arguments list\n - options\n - cwd?: `'d:/'`\n - env?: `process.env` 覆盖/添加到 process.env 的环境变量 overwrite/add to process.env\n - encoding?: `'utf-8'` 子进程输出编码 child process output encoding\n - print?: `true` print 选项,支持设置细项 print option (with details)\n - stdio?: `'pipe'` 设置为 'ignore' 时忽略 stdio 处理 when 'ignore' then ignore stdio processing\n - detached?: `false` 是否断开和 child 的关系 (ignore stdio, unref) whether to break the connection with child (ignore stdio, unref)\n - throw_code?: `true` code 不为 0 时是否抛出异常 whether to throw Error when code is not 0 */\nexport async function call_nodejs (js: string, args: string[] = [], options?: CallOptions) {\n return call(exe_nodejs, [js, ...args], options)\n}\n\n\n// ------------------------------------ term\nexport interface TermOptions {\n /** `d:/t/` */\n cwd?: string\n \n /** `true` 打印参数 */\n print?: boolean\n \n title?: string\n \n // 不支持 background, 在 WinTerm 中后台创建标签页,而非创建并切换到该标签页\n // 不支持 icon\n // 不支持 env, WindowsTerminal 在调用 CreateProcess API 时没有传入 env\n}\n\nexport const exe_winterm = `C:/Users/${userInfo().username}/AppData/Local/Microsoft/WindowsApps/wt.exe`\n\n/** 新建 terminal 窗口执行进程 New Terminal window execution process\n - exe: exe 文件路径 exe file path\n - args: 调用参数 call parameter\n - options?: WinTermOptions\n*/\nexport function term (exe: string, args: string[] = [], {\n cwd = 'd:/t/',\n \n print = true,\n \n title,\n \n // env\n}: TermOptions = { }) {\n \n \n return start(\n exe_winterm,\n [\n 'new-tab',\n \n '-d', cwd,\n \n ... title ? ['--suppressApplicationTitle', '--title', title] : [ ],\n \n exe,\n \n ...args.map(arg => \n arg.replaceAll(';', '\\\\;')), \n ],\n {\n print,\n detached: true,\n cwd,\n // env\n }\n )\n}\n\n\nexport interface TermNodeOptions extends TermOptions {\n /** nodejs debugger port */\n inspect?: number\n \n /** break at first line */\n break?: boolean\n \n /** 使用 ts-node 直接运行 use ts-node to run directly */\n tsnode?: boolean\n \n /** `false` --experimental-specifier-resolution=node */\n resolve?: boolean\n \n /** `false` --trace-warnings */\n trace_warnings?: boolean\n}\n\n\n/** 在 term tab 中创建 node.exe 进程 create the node.exe process in term tab */\nexport async function term_nodejs (\n fp_js: string, \n args: string[] = [ ],\n {\n title, \n inspect, \n tsnode = false,\n break: _break,\n resolve = false,\n trace_warnings = false,\n ..._options\n }: TermNodeOptions = { }\n) {\n return term(exe_nodejs, [\n ... trace_warnings ? ['--trace-warnings'] : [ ],\n ... resolve ? ['--experimental-specifier-resolution=node'] : [ ],\n ... title ? [`--title=${title}`] : [ ],\n ... inspect ? [\n _break ? `--inspect-brk=0.0.0.0:${inspect}` : `--inspect=0.0.0.0:${inspect}`\n ] : [ ],\n ... tsnode ? [\n '--loader=ts-node/esm',\n '--experimental-specifier-resolution=node'\n ] : [ ],\n fp_js,\n ... args\n ], {\n title,\n ..._options,\n })\n}\n\n\nconst short_exe_names = {\n [exe_winterm]: 'term',\n [exe_nodejs]: 'node',\n} as const\n\n"]}
|
package/server.d.ts
CHANGED
package/server.js
CHANGED
|
@@ -109,13 +109,10 @@ export class Server {
|
|
|
109
109
|
process request.ip
|
|
110
110
|
*/
|
|
111
111
|
async parse(ctx) {
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
if (
|
|
115
|
-
|
|
116
|
-
if (buf.length)
|
|
117
|
-
req.body = buf;
|
|
118
|
-
}
|
|
112
|
+
let { req, request } = ctx;
|
|
113
|
+
const buf = await stream_to_buffer(req);
|
|
114
|
+
if (buf.length)
|
|
115
|
+
req.body = buf;
|
|
119
116
|
// --- parse request.ip
|
|
120
117
|
request.ip = (request.headers['x-real-ip'] || request.ip).replace(/^::ffff:/, '');
|
|
121
118
|
// --- parse body
|
|
@@ -184,7 +181,6 @@ export class Server {
|
|
|
184
181
|
return t;
|
|
185
182
|
})().pad(40) + ' ';
|
|
186
183
|
// --- https/2.0
|
|
187
|
-
// if (req.tunnel) `tunnel/${http_version}`.pad(10).cyan
|
|
188
184
|
s += `${`${protocol.pad(5)}/${http_version}`.pad(10)} `;
|
|
189
185
|
// --- method
|
|
190
186
|
method = method.toLowerCase();
|
|
@@ -278,11 +274,9 @@ export class Server {
|
|
|
278
274
|
// ;(error as any).status = 500
|
|
279
275
|
// throw error
|
|
280
276
|
// }
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
response.set('accept-ranges', 'bytes');
|
|
285
|
-
}
|
|
277
|
+
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Ranges
|
|
278
|
+
// advertise server support of partial requests
|
|
279
|
+
response.set('accept-ranges', 'bytes');
|
|
286
280
|
if (!response.get('cache-control'))
|
|
287
281
|
response.set('cache-control', 'max-age=0, must-revalidate');
|
|
288
282
|
if (!response.get('last-modified'))
|
|
@@ -297,12 +291,7 @@ export class Server {
|
|
|
297
291
|
// 以上会自动设置 response.body = null
|
|
298
292
|
return path;
|
|
299
293
|
}
|
|
300
|
-
if (request.headers.range)
|
|
301
|
-
if (req.tunnel) {
|
|
302
|
-
response.status = 400;
|
|
303
|
-
response.body = '';
|
|
304
|
-
return;
|
|
305
|
-
}
|
|
294
|
+
if (request.headers.range)
|
|
306
295
|
try {
|
|
307
296
|
const range_header = request.headers.range;
|
|
308
297
|
const range_value = /=(.*)$/.exec(range_header)[1];
|
|
@@ -325,7 +314,6 @@ export class Server {
|
|
|
325
314
|
response.set('content-range', `bytes */${stats.size}`);
|
|
326
315
|
response.body = fs.createReadStream(path);
|
|
327
316
|
}
|
|
328
|
-
}
|
|
329
317
|
else {
|
|
330
318
|
response.set('content-length', String(stats.size));
|
|
331
319
|
response.body = fs.createReadStream(path);
|
package/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,IAAI,kBAAkB,EAA6B,MAAM,MAAM,CAAA;AACpF,OAAO,IAAI,MAAM,MAAM,CAAA;AACvB,OAAO,EAAE,OAAO,IAAI,MAAM,EAAc,MAAM,IAAI,CAAA;AAClD,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAA;AAEhC,gBAAgB;AAChB,OAAO,KAAK,MAAM,OAAO,CAAA;AACzB,OAAO,EAAE,MAAM,IAAI,CAAA;AACnB,OAAO,cAAc,MAAM,cAAc,CAAA;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,IAAI,CAAA;AAEpC,2BAA2B;AAC3B,OAAO,EAAE,OAAO,IAAI,GAAG,EAA2B,MAAM,KAAK,CAAA;AAE7D,OAAO,OAAO,MAAM,WAAW,CAAA;AAC/B,OAAO,WAAW,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,SAAS,IAAI,YAAY,EAAyB,MAAM,eAAe,CAAA;AAmBhF,OAAO,EAAE,gBAAgB,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAgBpE,yBAAyB;AACzB,MAAM,OAAO,MAAM;IACf,GAAG,CAAK;IAER,OAAO,CAA6B;IAEpC,IAAI,CAAQ;IAEZ,WAAW,CAAY;IAEvB,SAAS,CAAkB;IAE3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C,gBAAgB,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAA;aAC5D;YAAC,OAAO,GAAG,EAAE;gBACV,QAAQ,CAAC,MAAM,GAAG,GAAG,CAAA;gBACrB,QAAQ,CAAC,GAAG,CAAC,gBAAgB,EAAE,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAA;gBAClD,QAAQ,CAAC,GAAG,CAAC,eAAe,EAAE,WAAW,KAAK,CAAC,IAAI,EAAE,CAAC,CAAA;gBACtD,QAAQ,CAAC,IAAI,GAAG,EAAE,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAA;aAC5C;SACJ;aAAM;YACH,QAAQ,CAAC,GAAG,CAAC,gBAAgB,EAAE,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAA;YAClD,QAAQ,CAAC,IAAI,GAAG,EAAE,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAA;SAC5C;QAED,OAAO,IAAI,CAAA;IACf,CAAC;CACJ","sourcesContent":["import { createServer as http_create_server, type Server as HttpServer } from 'http'\nimport zlib from 'zlib'\nimport { default as nodefs, type Stats } from 'fs'\nimport { promisify } from 'util'\n\n// --- 3rd party\nimport upath from 'upath'\nimport qs from 'qs'\nimport resolve_safely from 'resolve-path'\nimport { WebSocketServer } from 'ws'\n\n// --- koa & koa middleware\nimport { default as Koa, type Context, type Next } from 'koa'\n\nimport KoaCors from '@koa/cors'\nimport KoaCompress from 'koa-compress'\nimport { userAgent as KoaUserAgent, type UserAgentContext } from 'koa-useragent'\n\n\ndeclare module 'koa' {\n interface Request {\n /** 经过 decodeURIComponent 后,在路径重写之前的路径 */\n _path: string\n \n body: any\n }\n \n interface Context {\n compress: boolean\n userAgent: UserAgentContext['userAgent'] & { isWechat: boolean }\n }\n}\n\n// --- my libs\nimport { request as _request, type Remote } from './net.js'\nimport { stream_to_buffer, inspect, output_width } from './utils.js'\nimport { type UFS } from './file.js'\n\n\ndeclare module 'http' {\n interface IncomingMessage {\n tunnel?: boolean\n id?: string\n body?: Buffer\n }\n \n interface ServerResponse {\n body?: Buffer\n }\n}\n\n// ------------ my server\nexport class Server {\n app: Koa\n \n handler: ReturnType<Koa['callback']>\n \n port: number\n \n server_http: HttpServer\n \n server_ws?: WebSocketServer\n \n remote?: Remote\n \n \n constructor (port: number, { remote }: { remote?: Remote } = { }) {\n this.port = port\n if (remote)\n this.remote = remote\n }\n \n /** start http server and listen */\n async start () {\n // --- init koa app\n let app = new Koa()\n \n app.on('error', (error, ctx) => {\n console.error(error)\n console.log(ctx)\n })\n \n app.use(this.entry.bind(this))\n \n app.use(KoaCompress({\n br: {\n chunkSize: 64 * 1024,\n \n // https://nodejs.org/api/zlib.html#zlib_class_brotlioptions\n params: {\n [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,\n [zlib.constants.BROTLI_PARAM_QUALITY]: 3 // 默认为 11 (最大压缩),会导致 news/get 生成的 14 mb 的 json 压缩时长高达 24s\n },\n },\n threshold: 512\n }))\n \n app.use(KoaCors({ credentials: true }))\n app.use(KoaUserAgent)\n \n app.use(this._router.bind(this))\n \n this.app = app\n \n this.handler = this.app.callback()\n \n this.server_http = http_create_server(this.handler)\n \n \n // websocket rpc\n if (this.remote) {\n this.server_ws = new WebSocketServer({\n noServer: true,\n skipUTF8Validation: true,\n perMessageDeflate: true\n })\n \n this.server_ws.on('connection', (ws: WebSocket, request) => {\n ws.addEventListener('message', event => {\n this.remote.handle(event.data, ws as any)\n })\n })\n \n this.server_http.on('upgrade', (request, socket, head) => {\n // url 只有路径部分\n const {\n url, \n headers: { host = '', 'user-agent': ua },\n } = request\n \n const ip = (request.socket.remoteAddress as string).replace(/^::ffff:/, '')\n \n console.log(`${new Date().to_time_str()} ${(ip || '').pad(40)} ${(ua || '').limit(40)} ${'websocket'.pad(10).magenta} ${'connect'.pad(10).magenta}${host.pad(20)} ${url.pad(60).yellow}`)\n \n switch (url) {\n case '/':\n this.server_ws.handleUpgrade(request, socket, head, ws => {\n ws.binaryType = 'arraybuffer'\n this.server_ws.emit('connection', ws, request)\n })\n return\n \n default:\n console.log(`${' '.repeat(13)} connect 404: ${url}`.red)\n socket.destroy()\n }\n })\n }\n \n \n await new Promise<void>(resolve => {\n this.server_http.listen(this.port, resolve)\n })\n }\n \n \n stop () {\n this.server_http.close()\n }\n \n \n async entry (ctx: Context, next: Next) {\n let { response } = ctx\n \n await this.parse(ctx)\n \n // ------------ next\n try {\n await next()\n } catch (error) {\n if (error.status !== 404)\n console.error(error)\n response.status = error.status || 500\n response.body = inspect(error, { colors: false })\n response.type = 'text/plain'\n }\n }\n \n \n /** \n parse req.body to request.body \n process request.ip\n */\n async parse (ctx: Context) {\n const {\n req,\n req: { tunnel },\n } = ctx\n \n let { request } = ctx\n \n if (!tunnel) {\n const buf = await stream_to_buffer(req)\n if (buf.length)\n req.body = buf\n }\n \n // --- parse request.ip\n request.ip = (request.headers['x-real-ip'] as string || request.ip).replace(/^::ffff:/, '')\n \n \n // --- parse body\n if (!req.body)\n return\n \n if (ctx.is('application/json') || ctx.is('text/plain'))\n request.body = JSON.parse(\n req.body.toString()\n )\n else if (ctx.is('application/x-www-form-urlencoded'))\n request.body = qs.parse(\n req.body.toString()\n )\n else if (ctx.is('multipart/form-data')) {\n throw new Error('multipart/form-data is not supported')\n } else\n request.body = req.body\n }\n \n \n async _router (ctx: Context, next: Next) {\n let { request } = ctx\n const _path = request._path = decodeURIComponent(request.path)\n Object.defineProperty(request, 'path', {\n value: _path,\n configurable: true,\n enumerable: true,\n writable: true\n })\n \n // ------------ log\n this.logger(ctx)\n \n // ------------ repl_router hook\n if (await global.repl_router?.(ctx))\n return\n \n if (await this.router(ctx))\n return\n \n await next?.()\n }\n \n \n async router (ctx: Context): Promise<boolean> {\n return false\n }\n \n \n logger (ctx: Context) {\n const { request } = ctx\n const {\n query, \n body, \n path, _path, \n protocol,\n host,\n req: { httpVersion: http_version },\n ip,\n } = request\n \n let { method } = request\n \n const ua = ctx.userAgent\n \n \n let s = ''\n \n // --- time\n s += `${new Date().to_time_str()} `\n \n \n // --- ip\n s += (ip || '').pad(40) + ' '\n \n \n // --- ua\n s += (() => {\n let t = ''\n if (ua.isMobile)\n t += 'mobile'\n if (ua.isDesktop)\n t += 'desktop'\n if (ua.isBot)\n t += `${ t ? ' ' : '' }${'robot'.blue}`\n if (ua.platform !== 'unknown' && !ua.os.startsWith('Windows'))\n t += '/' + ua.platform.toLowerCase().replace('apple mac', 'mac')\n if (ua.os !== 'unknown' && ua.platform !== 'Android')\n t += '/' + ua.os.toLowerCase()\n if (ua.browser !== 'unknown')\n t += '/' + ua.browser.toLowerCase()\n if (ua.isWechat)\n t += '/weixin'\n if (ua.version !== 'unknown')\n t += '/' + ua.version.split('.').slice(0, 2).join('.')\n return t\n })().pad(40) + ' '\n \n \n // --- https/2.0\n // if (req.tunnel) `tunnel/${http_version}`.pad(10).cyan\n s += `${`${protocol.pad(5)}/${http_version}`.pad(10)} `\n \n \n // --- method\n method = method.toLowerCase()\n s += method === 'get' ? method.pad(10) : method.pad(10).yellow\n \n \n // --- host\n s += `${host.pad(20)} `\n \n \n // --- path\n s += (() => {\n if (path.toLowerCase() !== _path.toLowerCase())\n return `${_path.blue} → ${path}`\n if (!path.includes('.'))\n return path.yellow\n return path\n })()\n \n \n // --- query\n if (Object.keys(query).length) {\n let t = inspect(query, { compact: true })\n .replace('[Object: null prototype] ', '')\n \n if (t.endsWith('\\n'))\n t = t.slice(0, -1)\n \n s += (s + t).width > output_width ? '\\n' : ' '\n \n s += t\n }\n \n \n // --- body\n if (body && Object.keys(body).length)\n s += '\\n' + inspect(body).replace('[Object: null prototype] ', '')\n \n \n // --- print log\n console.log(s)\n }\n \n \n async try_send (\n ctx: Context, \n fp: string,\n {\n fs,\n root,\n log_404,\n }: {\n fs?: (typeof nodefs) | UFS\n root: string\n log_404?: boolean\n }) {\n const {\n request: { _path, path, method },\n response,\n } = ctx\n \n if (!(typeof response.body === 'undefined') || response.status !== 404)\n return true\n \n if (method !== 'HEAD' && method !== 'GET')\n return false\n \n function _log_404 () {\n let s = `${' '.repeat(13)} ${method.toLowerCase()} 404: ${path}`\n if (_path !== path)\n s += ` ${_path.bracket()}`\n console.log(s.red)\n }\n \n try {\n await this.fsend(ctx, fp, { fs, root })\n return true\n } catch (error) {\n if (error.status !== 404)\n throw error\n if (log_404)\n _log_404()\n return false\n }\n }\n \n \n /** send file at `path` with the given `options` to the koa `ctx`. */\n async fsend (\n ctx: Context,\n path: string,\n {\n fs = nodefs,\n root,\n absolute\n }: {\n /** `fs` */\n fs?: (typeof nodefs) | UFS\n \n root?: string\n \n /** `false` */\n absolute?: boolean\n \n } = { } as any\n ) {\n const { request, response, req } = ctx\n \n if (!absolute && !root)\n throw new Error('fsend with `!absolute && !root`')\n \n if (absolute)\n path = upath.resolve(path)\n else {\n if (path.startsWith(root))\n path = path.slice(root.length)\n \n if (path.startsWith('/'))\n path = path.slice(1)\n \n try {\n path = upath.normalize(\n resolve_safely(root, path)\n )\n } catch (error) {\n error.message += `, path: ${path}`\n throw error\n }\n }\n \n \n // stat\n let stats: Stats\n try {\n stats = await promisify(fs.stat)(path)\n } catch (error) {\n if (['ENOENT', 'ENAMETOOLONG', 'ENOTDIR'].includes(error.code)) {\n error.status = 404\n throw error\n }\n \n error.status = 500\n error.message = `fs.stat 出错: ${error.message}`\n throw error\n }\n \n \n // size limit\n // if (stats.size >= 100 * 2**20) {\n // let error = new Error('body.length >= 100 mb')\n // ;(error as any).status = 500\n // throw error\n // }\n \n \n if (!req.tunnel) {\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Ranges\n // advertise server support of partial requests\n response.set('accept-ranges', 'bytes')\n }\n \n if (!response.get('cache-control'))\n response.set('cache-control', 'max-age=0, must-revalidate')\n \n if (!response.get('last-modified'))\n response.set('last-modified', (stats.mtime || new Date()).toUTCString())\n \n const fext = path.fext\n \n if (!response.type)\n response.type = fext\n \n if (fext === '.pdf')\n response.set('content-disposition', `attachment; filename=\"${encodeURIComponent(path.fname)}\"`)\n \n if (request.fresh) {\n response.status = 304\n // 以上会自动设置 response.body = null\n return path\n }\n \n if (request.headers.range) {\n if (req.tunnel) {\n response.status = 400\n response.body = ''\n return\n }\n \n try {\n const range_header = request.headers.range\n const range_value = /=(.*)$/.exec(range_header)[1]\n const range = /^[\\w]*?(\\d*)-(\\d*)$/.exec(range_value)\n \n let start = range[1] ? parseInt(range[1]) : undefined\n let end = range[2] ? parseInt(range[2]) : stats.size - 1\n \n if (typeof start == 'undefined') {\n start = (stats.size - end)\n end = (stats.size - 1)\n }\n \n const chunksize = (end - start + 1)\n \n response.status = 206\n response.set('content-length', String(chunksize))\n response.set('content-range', `bytes ${start}-${end}/${stats.size}`)\n response.body = fs.createReadStream(path, { start, end })\n } catch (err) {\n response.status = 416\n response.set('content-length', String(stats.size))\n response.set('content-range', `bytes */${stats.size}`)\n response.body = fs.createReadStream(path)\n }\n } else {\n response.set('content-length', String(stats.size))\n response.body = fs.createReadStream(path)\n }\n \n return path\n }\n}\n\n"]}
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,IAAI,kBAAkB,EAA6B,MAAM,MAAM,CAAA;AACpF,OAAO,IAAI,MAAM,MAAM,CAAA;AACvB,OAAO,EAAE,OAAO,IAAI,MAAM,EAAc,MAAM,IAAI,CAAA;AAClD,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAA;AAEhC,gBAAgB;AAChB,OAAO,KAAK,MAAM,OAAO,CAAA;AACzB,OAAO,EAAE,MAAM,IAAI,CAAA;AACnB,OAAO,cAAc,MAAM,cAAc,CAAA;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,IAAI,CAAA;AAEpC,2BAA2B;AAC3B,OAAO,EAAE,OAAO,IAAI,GAAG,EAA2B,MAAM,KAAK,CAAA;AAE7D,OAAO,OAAO,MAAM,WAAW,CAAA;AAC/B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,gBAAgB,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAA;aAC5D;YAAC,OAAO,GAAG,EAAE;gBACV,QAAQ,CAAC,MAAM,GAAG,GAAG,CAAA;gBACrB,QAAQ,CAAC,GAAG,CAAC,gBAAgB,EAAE,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAA;gBAClD,QAAQ,CAAC,GAAG,CAAC,eAAe,EAAE,WAAW,KAAK,CAAC,IAAI,EAAE,CAAC,CAAA;gBACtD,QAAQ,CAAC,IAAI,GAAG,EAAE,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAA;aAC5C;aACA;YACD,QAAQ,CAAC,GAAG,CAAC,gBAAgB,EAAE,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAA;YAClD,QAAQ,CAAC,IAAI,GAAG,EAAE,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAA;SAC5C;QAED,OAAO,IAAI,CAAA;IACf,CAAC;CACJ","sourcesContent":["import { createServer as http_create_server, type Server as HttpServer } from 'http'\nimport zlib from 'zlib'\nimport { default as nodefs, type Stats } from 'fs'\nimport { promisify } from 'util'\n\n// --- 3rd party\nimport upath from 'upath'\nimport qs from 'qs'\nimport resolve_safely from 'resolve-path'\nimport { WebSocketServer } from 'ws'\n\n// --- koa & koa middleware\nimport { default as Koa, type Context, type Next } from 'koa'\n\nimport KoaCors from '@koa/cors'\nimport KoaCompress from 'koa-compress'\nimport { userAgent as KoaUserAgent, type UserAgentContext } from 'koa-useragent'\n\n\ndeclare module 'koa' {\n interface Request {\n /** 经过 decodeURIComponent 后,在路径重写之前的路径 */\n _path: string\n \n body: any\n }\n \n interface Context {\n compress: boolean\n userAgent: UserAgentContext['userAgent'] & { isWechat: boolean }\n }\n}\n\n// --- my libs\nimport { request as _request, type Remote } from './net.js'\nimport { stream_to_buffer, inspect, output_width } from './utils.js'\nimport { type UFS } from './file.js'\n\n\ndeclare module 'http' {\n interface IncomingMessage {\n body?: Buffer\n }\n \n interface ServerResponse {\n body?: Buffer\n }\n}\n\n// ------------ my server\nexport class Server {\n app: Koa\n \n handler: ReturnType<Koa['callback']>\n \n port: number\n \n server_http: HttpServer\n \n server_ws?: WebSocketServer\n \n remote?: Remote\n \n \n constructor (port: number, { remote }: { remote?: Remote } = { }) {\n this.port = port\n if (remote)\n this.remote = remote\n }\n \n /** start http server and listen */\n async start () {\n // --- init koa app\n let app = new Koa()\n \n app.on('error', (error, ctx) => {\n console.error(error)\n console.log(ctx)\n })\n \n app.use(this.entry.bind(this))\n \n app.use(KoaCompress({\n br: {\n chunkSize: 64 * 1024,\n \n // https://nodejs.org/api/zlib.html#zlib_class_brotlioptions\n params: {\n [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,\n [zlib.constants.BROTLI_PARAM_QUALITY]: 3 // 默认为 11 (最大压缩),会导致 news/get 生成的 14 mb 的 json 压缩时长高达 24s\n },\n },\n threshold: 512\n }))\n \n app.use(KoaCors({ credentials: true }))\n app.use(KoaUserAgent)\n \n app.use(this._router.bind(this))\n \n this.app = app\n \n this.handler = this.app.callback()\n \n this.server_http = http_create_server(this.handler)\n \n \n // websocket rpc\n if (this.remote) {\n this.server_ws = new WebSocketServer({\n noServer: true,\n skipUTF8Validation: true,\n perMessageDeflate: true\n })\n \n this.server_ws.on('connection', (ws: WebSocket, request) => {\n ws.addEventListener('message', event => {\n this.remote.handle(event.data, ws as any)\n })\n })\n \n this.server_http.on('upgrade', (request, socket, head) => {\n // url 只有路径部分\n const {\n url, \n headers: { host = '', 'user-agent': ua },\n } = request\n \n const ip = (request.socket.remoteAddress as string).replace(/^::ffff:/, '')\n \n console.log(`${new Date().to_time_str()} ${(ip || '').pad(40)} ${(ua || '').limit(40)} ${'websocket'.pad(10).magenta} ${'connect'.pad(10).magenta}${host.pad(20)} ${url.pad(60).yellow}`)\n \n switch (url) {\n case '/':\n this.server_ws.handleUpgrade(request, socket, head, ws => {\n ws.binaryType = 'arraybuffer'\n this.server_ws.emit('connection', ws, request)\n })\n return\n \n default:\n console.log(`${' '.repeat(13)} connect 404: ${url}`.red)\n socket.destroy()\n }\n })\n }\n \n \n await new Promise<void>(resolve => {\n this.server_http.listen(this.port, resolve)\n })\n }\n \n \n stop () {\n this.server_http.close()\n }\n \n \n async entry (ctx: Context, next: Next) {\n let { response } = ctx\n \n await this.parse(ctx)\n \n // ------------ next\n try {\n await next()\n } catch (error) {\n if (error.status !== 404)\n console.error(error)\n response.status = error.status || 500\n response.body = inspect(error, { colors: false })\n response.type = 'text/plain'\n }\n }\n \n \n /** \n parse req.body to request.body \n process request.ip\n */\n async parse (ctx: Context) {\n let { req, request } = ctx\n \n const buf = await stream_to_buffer(req)\n if (buf.length)\n req.body = buf\n \n // --- parse request.ip\n request.ip = (request.headers['x-real-ip'] as string || request.ip).replace(/^::ffff:/, '')\n \n \n // --- parse body\n if (!req.body)\n return\n \n if (ctx.is('application/json') || ctx.is('text/plain'))\n request.body = JSON.parse(\n req.body.toString()\n )\n else if (ctx.is('application/x-www-form-urlencoded'))\n request.body = qs.parse(\n req.body.toString()\n )\n else if (ctx.is('multipart/form-data')) {\n throw new Error('multipart/form-data is not supported')\n } else\n request.body = req.body\n }\n \n \n async _router (ctx: Context, next: Next) {\n let { request } = ctx\n const _path = request._path = decodeURIComponent(request.path)\n Object.defineProperty(request, 'path', {\n value: _path,\n configurable: true,\n enumerable: true,\n writable: true\n })\n \n // ------------ log\n this.logger(ctx)\n \n // ------------ repl_router hook\n if (await global.repl_router?.(ctx))\n return\n \n if (await this.router(ctx))\n return\n \n await next?.()\n }\n \n \n async router (ctx: Context): Promise<boolean> {\n return false\n }\n \n \n logger (ctx: Context) {\n const { request } = ctx\n const {\n query, \n body, \n path, _path, \n protocol,\n host,\n req: { httpVersion: http_version },\n ip,\n } = request\n \n let { method } = request\n \n const ua = ctx.userAgent\n \n \n let s = ''\n \n // --- time\n s += `${new Date().to_time_str()} `\n \n \n // --- ip\n s += (ip || '').pad(40) + ' '\n \n \n // --- ua\n s += (() => {\n let t = ''\n if (ua.isMobile)\n t += 'mobile'\n if (ua.isDesktop)\n t += 'desktop'\n if (ua.isBot)\n t += `${ t ? ' ' : '' }${'robot'.blue}`\n if (ua.platform !== 'unknown' && !ua.os.startsWith('Windows'))\n t += '/' + ua.platform.toLowerCase().replace('apple mac', 'mac')\n if (ua.os !== 'unknown' && ua.platform !== 'Android')\n t += '/' + ua.os.toLowerCase()\n if (ua.browser !== 'unknown')\n t += '/' + ua.browser.toLowerCase()\n if (ua.isWechat)\n t += '/weixin'\n if (ua.version !== 'unknown')\n t += '/' + ua.version.split('.').slice(0, 2).join('.')\n return t\n })().pad(40) + ' '\n \n \n // --- https/2.0\n s += `${`${protocol.pad(5)}/${http_version}`.pad(10)} `\n \n \n // --- method\n method = method.toLowerCase()\n s += method === 'get' ? method.pad(10) : method.pad(10).yellow\n \n \n // --- host\n s += `${host.pad(20)} `\n \n \n // --- path\n s += (() => {\n if (path.toLowerCase() !== _path.toLowerCase())\n return `${_path.blue} → ${path}`\n if (!path.includes('.'))\n return path.yellow\n return path\n })()\n \n \n // --- query\n if (Object.keys(query).length) {\n let t = inspect(query, { compact: true })\n .replace('[Object: null prototype] ', '')\n \n if (t.endsWith('\\n'))\n t = t.slice(0, -1)\n \n s += (s + t).width > output_width ? '\\n' : ' '\n \n s += t\n }\n \n \n // --- body\n if (body && Object.keys(body).length)\n s += '\\n' + inspect(body).replace('[Object: null prototype] ', '')\n \n \n // --- print log\n console.log(s)\n }\n \n \n async try_send (\n ctx: Context, \n fp: string,\n {\n fs,\n root,\n log_404,\n }: {\n fs?: (typeof nodefs) | UFS\n root: string\n log_404?: boolean\n }) {\n const {\n request: { _path, path, method },\n response,\n } = ctx\n \n if (!(typeof response.body === 'undefined') || response.status !== 404)\n return true\n \n if (method !== 'HEAD' && method !== 'GET')\n return false\n \n function _log_404 () {\n let s = `${' '.repeat(13)} ${method.toLowerCase()} 404: ${path}`\n if (_path !== path)\n s += ` ${_path.bracket()}`\n console.log(s.red)\n }\n \n try {\n await this.fsend(ctx, fp, { fs, root })\n return true\n } catch (error) {\n if (error.status !== 404)\n throw error\n if (log_404)\n _log_404()\n return false\n }\n }\n \n \n /** send file at `path` with the given `options` to the koa `ctx`. */\n async fsend (\n ctx: Context,\n path: string,\n {\n fs = nodefs,\n root,\n absolute\n }: {\n /** `fs` */\n fs?: (typeof nodefs) | UFS\n \n root?: string\n \n /** `false` */\n absolute?: boolean\n \n } = { } as any\n ) {\n const { request, response, req } = ctx\n \n if (!absolute && !root)\n throw new Error('fsend with `!absolute && !root`')\n \n if (absolute)\n path = upath.resolve(path)\n else {\n if (path.startsWith(root))\n path = path.slice(root.length)\n \n if (path.startsWith('/'))\n path = path.slice(1)\n \n try {\n path = upath.normalize(\n resolve_safely(root, path)\n )\n } catch (error) {\n error.message += `, path: ${path}`\n throw error\n }\n }\n \n \n // stat\n let stats: Stats\n try {\n stats = await promisify(fs.stat)(path)\n } catch (error) {\n if (['ENOENT', 'ENAMETOOLONG', 'ENOTDIR'].includes(error.code)) {\n error.status = 404\n throw error\n }\n \n error.status = 500\n error.message = `fs.stat 出错: ${error.message}`\n throw error\n }\n \n \n // size limit\n // if (stats.size >= 100 * 2**20) {\n // let error = new Error('body.length >= 100 mb')\n // ;(error as any).status = 500\n // throw error\n // }\n \n \n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Ranges\n // advertise server support of partial requests\n response.set('accept-ranges', 'bytes')\n \n if (!response.get('cache-control'))\n response.set('cache-control', 'max-age=0, must-revalidate')\n \n if (!response.get('last-modified'))\n response.set('last-modified', (stats.mtime || new Date()).toUTCString())\n \n const fext = path.fext\n \n if (!response.type)\n response.type = fext\n \n if (fext === '.pdf')\n response.set('content-disposition', `attachment; filename=\"${encodeURIComponent(path.fname)}\"`)\n \n if (request.fresh) {\n response.status = 304\n // 以上会自动设置 response.body = null\n return path\n }\n \n if (request.headers.range)\n try {\n const range_header = request.headers.range\n const range_value = /=(.*)$/.exec(range_header)[1]\n const range = /^[\\w]*?(\\d*)-(\\d*)$/.exec(range_value)\n \n let start = range[1] ? parseInt(range[1]) : undefined\n let end = range[2] ? parseInt(range[2]) : stats.size - 1\n \n if (typeof start == 'undefined') {\n start = (stats.size - end)\n end = (stats.size - 1)\n }\n \n const chunksize = (end - start + 1)\n \n response.status = 206\n response.set('content-length', String(chunksize))\n response.set('content-range', `bytes ${start}-${end}/${stats.size}`)\n response.body = fs.createReadStream(path, { start, end })\n } catch (err) {\n response.status = 416\n response.set('content-length', String(stats.size))\n response.set('content-range', `bytes */${stats.size}`)\n response.body = fs.createReadStream(path)\n }\n else {\n response.set('content-length', String(stats.size))\n response.body = fs.createReadStream(path)\n }\n \n return path\n }\n}\n\n"]}
|