xshell 0.0.35 → 0.0.38
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 +5 -2
- package/file.js +4 -1
- package/file.js.map +1 -1
- package/net.js +3 -4
- package/net.js.map +1 -1
- package/package.json +7 -7
- package/process.d.ts +5 -6
- package/process.js +59 -39
- package/process.js.map +1 -1
- package/repl.js +4 -3
- package/repl.js.map +1 -1
- package/server.d.ts +12 -8
- package/server.js +27 -21
- package/server.js.map +1 -1
package/file.d.ts
CHANGED
|
@@ -60,7 +60,7 @@ export declare function flist(fpd: string, { filter, deep, absolute, print }?: {
|
|
|
60
60
|
deep?: boolean;
|
|
61
61
|
absolute?: boolean;
|
|
62
62
|
print?: boolean;
|
|
63
|
-
}): Promise<
|
|
63
|
+
}): Promise<string[]>;
|
|
64
64
|
/** delete file or directory (use rimraf to delete directory fast)
|
|
65
65
|
- fp: path
|
|
66
66
|
- options?:
|
|
@@ -107,7 +107,10 @@ export declare function fmkdir(fpd: string, options?: fs.MakeDirectoryOptions &
|
|
|
107
107
|
print?: boolean;
|
|
108
108
|
suppress_existence?: boolean;
|
|
109
109
|
}): Promise<void>;
|
|
110
|
-
/**
|
|
110
|
+
/**
|
|
111
|
+
- fp_real: current real file path
|
|
112
|
+
- fp_link: file path or directory path
|
|
113
|
+
*/
|
|
111
114
|
export declare function flink(fp_real: string, fp_link: string, { junction, print }?: {
|
|
112
115
|
junction?: boolean;
|
|
113
116
|
print?: boolean;
|
package/file.js
CHANGED
|
@@ -209,7 +209,10 @@ async function fmkdir(fpd, options = {}) {
|
|
|
209
209
|
await fs_1.promises.mkdir(fpd, { recursive: true });
|
|
210
210
|
}
|
|
211
211
|
exports.fmkdir = fmkdir;
|
|
212
|
-
/**
|
|
212
|
+
/**
|
|
213
|
+
- fp_real: current real file path
|
|
214
|
+
- fp_link: file path or directory path
|
|
215
|
+
*/
|
|
213
216
|
async function flink(fp_real, fp_link, { junction = false, print = true } = {}) {
|
|
214
217
|
if (!upath_1.default.isAbsolute(fp_real) || !upath_1.default.isAbsolute(fp_link))
|
|
215
218
|
throw new Error('fpd must be absolute path');
|
package/file.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file.js","sourceRoot":"","sources":["file.ts"],"names":[],"mappings":";;;;AAAA,2BAA2C;AAG3C,0DAAwB;AACxB,oEAA8B;AAC9B,uDAA+C;AAC/C,gEAA0B;AAC1B,4DAA2B;AAE3B,6EAAyC;AAGzC,0DAAuB;AAad,cAbF,eAAG,CAaE;AALZ,iDAAwC;AACxC,yCAAmC;AACnC,mDAAwB;AAQxB,SAAgB,UAAU;IACtB,WAAG,GAAG,eAAG,CAAC,kBAAkB,CACxB,IAAI,eAAG,CAAC,MAAM,EAAE,CACnB,CAAA;IAED,WAAG,CAAC,IAAI,GAAG,eAAI,CAAC,IAAI,CAAC,IAAI,CAAC,eAAI,CAAC,CAAA;IAC/B,WAAG,CAAC,MAAM,GAAG,IAAI,CAAA;IAEjB,OAAO,WAAG,CAAA;AACd,CAAC;AATD,gCASC;AAQM,KAAK,UAAU,KAAK,CAAE,EAAU,EAAE,EACrC,GAAG,EACH,QAAQ,GAAG,OAAO,EAClB,KAAK,GAAG,IAAI,KAIQ,EAAG;IAEvB,IAAI,GAAG;QACH,EAAE,GAAG,eAAI,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAA;SACtB,IAAI,CAAC,eAAI,CAAC,UAAU,CAAC,EAAE,CAAC;QACzB,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAA;IAE7E,IAAI,KAAK;QACL,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,EAAE,CAAC,CAAA;IAE9B,MAAM,MAAM,GAAG,MAAM,aAAG,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAA;IAErC,IAAI,QAAQ,KAAK,QAAQ;QACrB,OAAO,MAAM,CAAA;IAEjB,IAAI,QAAQ,KAAK,OAA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AC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAA;QACjC,OAAM;KACT;IAED,MAAM,MAAM,GAAG,GAAG,EAAE,CAAC,IAAI,GAAG,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,kBAAkB,EAAE,UAAU,CAAC,EAAE,CAAA;IAC9E,IAAI,CAAC,MAAM,CAAC,OAAO;QACf,MAAM,KAAK,CAAC,EAAE,EAAE,MAAM,CAAC,CAAA;IAE3B,MAAM,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;AAC1B,CAAC;AAlBD,wBAkBC","sourcesContent":["import { promises as fsp, watch } from 'fs'\nimport type fs from 'fs'\n\nimport path from 'upath'\nimport iconv from 'iconv-lite'\nimport { readdirAsync } from 'readdir-enhanced'\nimport fse from 'fs-extra'\nimport rimraf from 'rimraf'\n\nimport debounce from 'lodash/debounce.js'\n\n\nimport MFS from 'memfs'\ndeclare module 'memfs' {\n interface IFs {\n join: typeof path.join\n is_mfs: true\n }\n}\n\nimport { to_json } from './prototype.js'\nimport { dedent } from './utils.js'\nexport * from './ufs.js'\n\n\nexport { MFS }\n\nexport type Encoding = 'utf-8' | 'gb18030' | 'shift-jis' | 'binary'\n\n\nexport function create_mfs () {\n mfs = MFS.createFsFromVolume(\n new MFS.Volume()\n )\n \n mfs.join = path.join.bind(path)\n mfs.is_mfs = true\n \n return mfs\n}\n\nexport let mfs: MFS.IFs\n\n\nexport async function fread (fp: string): Promise<string>\nexport async function fread (fp: string, { dir, encoding, print }?: { dir?: string, encoding: 'binary', print?: boolean }): Promise<Buffer>\nexport async function fread (fp: string, { dir, encoding, print }?: { dir?: string, encoding?: Encoding | 'auto', print?: boolean }): Promise<string>\nexport async function fread (fp: string, {\n dir, \n encoding = 'utf-8', \n print = true\n}: {\n dir?: string\n encoding?: Encoding | 'auto'\n print?: boolean } = { }\n) {\n if (dir)\n fp = path.join(dir, fp)\n else if (!path.isAbsolute(fp))\n throw new Error('fp must be absolute path, or pass in \\'dir\\' parameter')\n \n if (print)\n console.log(`read: ${fp}`)\n \n const buffer = await fsp.readFile(fp)\n \n if (encoding === 'binary')\n return buffer\n \n if (encoding === 'utf-8')\n return buffer.toString('utf8')\n \n if (encoding === 'auto') {\n const { detect } = await import('chardet')\n encoding = detect(buffer) as any\n if (print)\n console.log(`${fp} probably has encoding: ${encoding.toLowerCase()}`)\n }\n \n return iconv.decode(buffer, encoding)\n}\n\nexport async function fread_lines (fp: string, options: { dir?: string, encoding?: Exclude<Encoding, 'binary'> | 'auto', print?: boolean } = { }) {\n return (await fread(fp, options))\n .split_lines()\n}\n\nexport async function fread_json <T = any> (fp: string, options: { dir?: string, encoding?: Encoding, print?: boolean } = { }): Promise<T> {\n return JSON.parse(\n await fread(fp, options)\n )\n}\n\n\nexport async function fwrite (fp: string, data: Buffer, options?: { dir?: string, print?: boolean }): Promise<void>\nexport async function fwrite (fp: string, data: any, options?: { dir?: string, encoding?: Encoding, print?: boolean }): Promise<void>\nexport async function fwrite (fp: string, data: any, { dir, encoding = 'utf-8', print = true }: { dir?: string, encoding?: Encoding, print?: boolean } = { }) {\n if (dir)\n fp = path.join(dir, fp)\n else if (!path.isAbsolute(fp))\n throw new Error('fp must be absolute path, or pass in \"dir\" parameter')\n \n if (print)\n console.log('write:', fp)\n \n if (encoding === 'gb18030')\n data = iconv.encode(data, encoding)\n \n if (!Buffer.isBuffer(data) && typeof data !== 'string')\n data = to_json(data)\n \n await fsp.writeFile(fp, data)\n}\n\nexport async function fappend (fp: string, data: any, { dir, print = true }: { dir?: string, print?: boolean } = { }) {\n if (dir)\n fp = path.join(dir, fp)\n else if (!path.isAbsolute(fp))\n throw new Error('fp must be absolute path, or pass in \"dir\" parameter')\n \n if (print)\n console.log('append:', fp)\n \n if (!Buffer.isBuffer(data) && typeof data !== 'string')\n throw new Error('data is not Buffer or string')\n \n await fsp.appendFile(fp, data)\n}\n\n\n/**\n - fpd: absolute path of directory\n - optoins?:\n - deep?: `false` recursively\n - absolute?: `false` return absolute path\n - print?: `true`\n - filter?: `true` RegExp | (fp: string) => any\n*/\nexport async function flist (fpd: string, {\n filter, \n deep = false, \n absolute = false,\n print = true\n}: {\n filter?: RegExp | ((fp: string) => any)\n deep?: boolean\n absolute?: boolean\n print?: boolean\n} = { }) {\n if (!path.isAbsolute(fpd))\n throw new Error('fpd must be absolute path')\n \n let fps = await readdirAsync(fpd, {\n ...(absolute ? { basePath: fpd } : { }),\n deep,\n stats: false,\n })\n \n let fps_ = [ ]\n \n const filter_regexp = filter instanceof RegExp\n const filter_fn = Boolean(filter && !filter_regexp)\n \n for (let fp of fps) {\n fp = path.normalize(fp)\n \n if (filter_regexp && !filter.test(fp))\n continue\n \n if (filter_fn && !(filter as Function)(fp))\n continue\n \n if (print)\n console.log(fp)\n \n fps_.push(fp)\n }\n \n return fps_\n}\n\n\n/** delete file or directory (use rimraf to delete directory fast) \n - fp: path\n - options?:\n - print?: `true` (effective only delete single file)\n*/\nexport async function fdelete (fp: string, { print = true, fast = false }: { print?: boolean, fast?: boolean } = { }) {\n if (fp.length < 6) throw new Error(`${fp} too short`)\n if (!path.isAbsolute(fp))\n throw new Error('fpd must be absolute path')\n \n if (fp.is_dir) {\n if (print)\n console.log(`delete directory: ${fp}`.red)\n await new Promise<void>((resolve, reject) => {\n rimraf(fp, { glob: false, disableGlob: true }, error => {\n if (error)\n reject(error)\n else\n resolve()\n })\n })\n } else {\n if (print)\n console.log('delete:', fp)\n await fsp.unlink(fp)\n }\n}\n\n\n/** copy file or direcotry\n - src: src file/directory absolute path\n - dst: dst file/directory absolute path\n @example\n fcopy('d:/temp/camera/', 'd:/camera/')\n*/\nexport async function fcopy (src: string, dst: string, {\n print = true,\n overwrite = true,\n}: {\n print?: boolean\n overwrite?: boolean\n} = { }) {\n if (src.endsWith('/') !== dst.endsWith('/'))\n throw new Error('src and dst must be both file path or directory path')\n \n if (!path.isAbsolute(src) || !path.isAbsolute(dst))\n throw new Error('src and dst must be absolute path')\n \n if (print)\n console.log(`copy: ${src} → ${dst}`)\n \n await fse.copy(src, dst, { overwrite, errorOnExist: true })\n}\n\n\n/** move file or direcotry\n - src: src file/directory absolute path\n - dst: dst file/directory absolute path\n @example\n fmove('d:/temp/camera/', 'd:/camera/')\n*/\nexport async function fmove (src: string, dst: string, {\n overwrite = false,\n print = true\n}: {\n overwrite?: boolean\n print?: boolean\n} = { }) {\n if (src.endsWith('/') !== dst.endsWith('/'))\n throw new Error('src and dst must be both file path or directory path')\n \n if (!path.isAbsolute(src) || !path.isAbsolute(dst))\n throw new Error('src and dst must be absolute path')\n \n if (print)\n console.log(`move: ${src} → ${dst}`)\n \n await fse.move(src, dst, { overwrite })\n}\n\n\n/** rename file \n - fp: current filename/path\n - fp_: new filename/path\n - options?:\n - fpd?: fp and fp_ is in same directory\n - print?: `true`\n - overwrite?: `true` better performance without check\n */\nexport async function frename (\n fp: string, \n fp_: string,\n {\n fpd,\n print = true,\n overwrite = true\n }: {\n fpd?: string\n print?: boolean\n overwrite?: boolean\n } = { }\n) {\n if (fpd) {\n fp = path.join(fpd, fp)\n fp_ = path.join(fpd, fp_)\n } else if (!path.isAbsolute(fp) || !path.isAbsolute(fp_))\n throw new Error('fp and fp_ must be absolute path')\n \n if (print)\n console.log('rename:', fp, '→', fp_)\n \n if (!overwrite && fp_.fexists)\n throw new Error(`file already exists:${fp_}`)\n \n await fsp.rename(fp, fp_)\n}\n\n\nexport async function fmkdir (fpd: string, options: fs.MakeDirectoryOptions & { print?: boolean, suppress_existence?: boolean } = { }) {\n if (!path.isAbsolute(fpd))\n throw new Error('fpd must be absolute path')\n \n options.print ??= true\n \n if (fpd.fexists)\n if (fpd.is_dir) {\n if (options.print && !options.suppress_existence)\n console.log('directory already exists:', fpd)\n return\n } else throw new Error(`file with same name already exists, cannot create directory: ${fpd}`)\n else if (options.print)\n console.log('mkdir:', fpd)\n \n await fsp.mkdir(fpd, { recursive: true })\n}\n\n\n/** - link: can be file path or directory path */\nexport async function flink (\n fp_real: string, \n fp_link: string, \n {\n junction = false,\n print = true \n }: { \n junction?: boolean\n print?: boolean\n} = { }) {\n if (!path.isAbsolute(fp_real) || !path.isAbsolute(fp_link))\n throw new Error('fpd must be absolute path')\n \n if (fp_link.fexists)\n if (fp_link.is_dir)\n fp_link = path.join(fp_link, fp_real.fname)\n else if ( (await fsp.lstat(fp_link)).isSymbolicLink() ) {\n console.log('link already exists:', fp_link)\n return\n } else\n throw new Error('file with same name already exists, cannot create new link')\n \n \n if (print)\n console.log(`source file ${fp_real} linked to ${fp_link}`)\n \n if (junction)\n fsp.symlink(fp_real, fp_link, 'junction')\n else\n fsp.symlink(fp_real, fp_link, fp_real.is_dir ? 'dir' : 'file')\n}\n\n\nexport function link_shortcut (target: string, name: string, { args }: { args?: string[] } = { }) {\n const cmd = dedent`\n $wsh_shell = New-Object -comObject WScript.Shell\n $shortcut = $wsh_shell.CreateShortcut(\"d:/links/#{name}.lnk\")\n $shortcut.TargetPath = '${target}'\n $shortcut.Arguments = \"${args || ''}\"\n $shortcut.WorkingDirectory = '${target.fdir}'\n ${ target.is_dir ? '$shortcut.IconLocation = \"%SystemRoot%\\\\System32\\\\SHELL32.dll,3\"' : '' }\n $shortcut.Save()\n `\n console.log(cmd)\n // await psh(cmd)\n}\n\n\nexport let fwatchers: Record<string, fs.FSWatcher> = { }\n\n/**\n - fp: path of file or directory\n - callback: called when modified\n - exec: call callback when watch is executed\n \n save fs.FSWatcher in watchers, subsequent call will auto close existing watcher for the same fp\n \n https://nodejs.org/dist/latest-v15.x/docs/api/fs.html#fs_fs_watch_filename_options_listener \n The listener callback gets two arguments (event, fname). \n event is either 'rename' or 'change', and filename is the name of the file which triggered the event.\n On most platforms, 'rename' is emitted whenever a filename appears or disappears in the directory.\n \n The listener callback is attached to the 'change' event fired by fs.FSWatcher, but it is not the same thing as the 'change' value of event. \n \n*/\nexport async function fwatch (\n fp: string,\n onchange: (event: string, fname: string) => any, \n { exec = true }: { exec?: boolean } = { }\n) {\n if (!path.isAbsolute(fp))\n throw new Error('fp must be absolute path')\n \n const _watcher = fwatchers[fp]\n if (_watcher)\n _watcher.close()\n \n if (exec)\n await onchange('change', fp.fname)\n \n const debounced_onchange = debounce(\n (event, fname) => {\n console.log(`file changed (${event}): ${fname}`)\n onchange(event, path.normalize(fname))\n },\n 500,\n { leading: false, trailing: true }\n )\n \n let watcher = watch(fp, debounced_onchange)\n watcher.on('error', error => {\n console.error(error)\n })\n return fwatchers[fp] = watcher\n}\n\n\n/** open a file and replace certain pattern */\nexport async function freplace (fp: string, pattern: string | RegExp, replacement: string) {\n await fwrite(\n fp,\n (await fread(fp))\n .replaceAll(pattern, replacement)\n )\n}\n\n/** convert file encoding to UTF-8\n - fp: file absolute path\n - options?:\n - dryrun?: `true`\n - encoding?: `'auto'`\n*/\nexport async function f2utf8 (fp: string, {\n dryrun = true,\n encoding = 'auto',\n}: {\n dryrun?: boolean\n encoding?: Encoding | 'auto'\n} = { }) {\n const text = await fread(fp, { encoding })\n if (dryrun) {\n console.log(text.slice(0, 10000))\n return\n }\n \n const fp_bak = `${fp.fdir}${fp.fname.replace(/(.*?)(\\.[^.]+)?$/, '$1.bak$2')}`\n if (!fp_bak.fexists)\n await fcopy(fp, fp_bak)\n \n await fwrite(fp, text)\n}\n\n"]}
|
|
1
|
+
{"version":3,"file":"file.js","sourceRoot":"","sources":["file.ts"],"names":[],"mappings":";;;;AAAA,2BAA2C;AAG3C,0DAAwB;AACxB,oEAA8B;AAC9B,uDAA+C;AAC/C,gEAA0B;AAC1B,4DAA2B;AAE3B,6EAAyC;AAGzC,0DAAuB;AAad,cAbF,eAAG,CAaE;AALZ,iDAAwC;AACxC,yCAAmC;AACnC,mDAAwB;AAQxB,SAAgB,UAAU;IACtB,WAAG,GAAG,eAAG,CAAC,kBAAkB,CACxB,IAAI,eAAG,CAAC,MAAM,EAAE,CACnB,CAAA;IAED,WAAG,CAAC,IAAI,GAAG,eAAI,CAAC,IAAI,CAAC,IAAI,CAAC,eAAI,CAAC,CAAA;IAC/B,WAAG,CAAC,MAA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;IACxB,CAAC,CAAC,CAAA;IACF,OAAO,iBAAS,CAAC,EAAE,CAAC,GAAG,OAAO,CAAA;AAClC,CAAC;AA7BD,wBA6BC;AAGD,8CAA8C;AACvC,KAAK,UAAU,QAAQ,CAAE,EAAU,EAAE,OAAwB,EAAE,WAAmB;IACrF,MAAM,MAAM,CACR,EAAE,EACF,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC,CAAC;SACZ,UAAU,CAAC,OAAO,EAAE,WAAW,CAAC,CACxC,CAAA;AACL,CAAC;AAND,4BAMC;AAED;;;;;EAKE;AACK,KAAK,UAAU,MAAM,CAAE,EAAU,EAAE,EACtC,MAAM,GAAG,IAAI,EACb,QAAQ,GAAG,MAAM,MAIjB,EAAG;IACH,MAAM,IAAI,GAAG,MAAM,KAAK,CAAC,EAAE,EAAE,EAAE,QAAQ,EAAE,CAAC,CAAA;IAC1C,IAAI,MAAM,EAAE;QACR,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAA;QACjC,OAAM;KACT;IAED,MAAM,MAAM,GAAG,GAAG,EAAE,CAAC,IAAI,GAAG,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,kBAAkB,EAAE,UAAU,CAAC,EAAE,CAAA;IAC9E,IAAI,CAAC,MAAM,CAAC,OAAO;QACf,MAAM,KAAK,CAAC,EAAE,EAAE,MAAM,CAAC,CAAA;IAE3B,MAAM,MAAM,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;AAC1B,CAAC;AAlBD,wBAkBC","sourcesContent":["import { promises as fsp, watch } from 'fs'\nimport type fs from 'fs'\n\nimport path from 'upath'\nimport iconv from 'iconv-lite'\nimport { readdirAsync } from 'readdir-enhanced'\nimport fse from 'fs-extra'\nimport rimraf from 'rimraf'\n\nimport debounce from 'lodash/debounce.js'\n\n\nimport MFS from 'memfs'\ndeclare module 'memfs' {\n interface IFs {\n join: typeof path.join\n is_mfs: true\n }\n}\n\nimport { to_json } from './prototype.js'\nimport { dedent } from './utils.js'\nexport * from './ufs.js'\n\n\nexport { MFS }\n\nexport type Encoding = 'utf-8' | 'gb18030' | 'shift-jis' | 'binary'\n\n\nexport function create_mfs () {\n mfs = MFS.createFsFromVolume(\n new MFS.Volume()\n )\n \n mfs.join = path.join.bind(path)\n mfs.is_mfs = true\n \n return mfs\n}\n\nexport let mfs: MFS.IFs\n\n\nexport async function fread (fp: string): Promise<string>\nexport async function fread (fp: string, { dir, encoding, print }?: { dir?: string, encoding: 'binary', print?: boolean }): Promise<Buffer>\nexport async function fread (fp: string, { dir, encoding, print }?: { dir?: string, encoding?: Encoding | 'auto', print?: boolean }): Promise<string>\nexport async function fread (fp: string, {\n dir, \n encoding = 'utf-8', \n print = true\n}: {\n dir?: string\n encoding?: Encoding | 'auto'\n print?: boolean } = { }\n) {\n if (dir)\n fp = path.join(dir, fp)\n else if (!path.isAbsolute(fp))\n throw new Error('fp must be absolute path, or pass in \\'dir\\' parameter')\n \n if (print)\n console.log(`read: ${fp}`)\n \n const buffer = await fsp.readFile(fp)\n \n if (encoding === 'binary')\n return buffer\n \n if (encoding === 'utf-8')\n return buffer.toString('utf8')\n \n if (encoding === 'auto') {\n const { detect } = await import('chardet')\n encoding = detect(buffer) as any\n if (print)\n console.log(`${fp} probably has encoding: ${encoding.toLowerCase()}`)\n }\n \n return iconv.decode(buffer, encoding)\n}\n\nexport async function fread_lines (fp: string, options: { dir?: string, encoding?: Exclude<Encoding, 'binary'> | 'auto', print?: boolean } = { }) {\n return (await fread(fp, options))\n .split_lines()\n}\n\nexport async function fread_json <T = any> (fp: string, options: { dir?: string, encoding?: Encoding, print?: boolean } = { }): Promise<T> {\n return JSON.parse(\n await fread(fp, options)\n )\n}\n\n\nexport async function fwrite (fp: string, data: Buffer, options?: { dir?: string, print?: boolean }): Promise<void>\nexport async function fwrite (fp: string, data: any, options?: { dir?: string, encoding?: Encoding, print?: boolean }): Promise<void>\nexport async function fwrite (fp: string, data: any, { dir, encoding = 'utf-8', print = true }: { dir?: string, encoding?: Encoding, print?: boolean } = { }) {\n if (dir)\n fp = path.join(dir, fp)\n else if (!path.isAbsolute(fp))\n throw new Error('fp must be absolute path, or pass in \"dir\" parameter')\n \n if (print)\n console.log('write:', fp)\n \n if (encoding === 'gb18030')\n data = iconv.encode(data, encoding)\n \n if (!Buffer.isBuffer(data) && typeof data !== 'string')\n data = to_json(data)\n \n await fsp.writeFile(fp, data)\n}\n\nexport async function fappend (fp: string, data: any, { dir, print = true }: { dir?: string, print?: boolean } = { }) {\n if (dir)\n fp = path.join(dir, fp)\n else if (!path.isAbsolute(fp))\n throw new Error('fp must be absolute path, or pass in \"dir\" parameter')\n \n if (print)\n console.log('append:', fp)\n \n if (!Buffer.isBuffer(data) && typeof data !== 'string')\n throw new Error('data is not Buffer or string')\n \n await fsp.appendFile(fp, data)\n}\n\n\n/**\n - fpd: absolute path of directory\n - optoins?:\n - deep?: `false` recursively\n - absolute?: `false` return absolute path\n - print?: `true`\n - filter?: `true` RegExp | (fp: string) => any\n*/\nexport async function flist (fpd: string, {\n filter, \n deep = false, \n absolute = false,\n print = true\n}: {\n filter?: RegExp | ((fp: string) => any)\n deep?: boolean\n absolute?: boolean\n print?: boolean\n} = { }) {\n if (!path.isAbsolute(fpd))\n throw new Error('fpd must be absolute path')\n \n let fps = await readdirAsync(fpd, {\n ...(absolute ? { basePath: fpd } : { }),\n deep,\n stats: false,\n })\n \n let fps_: string[] = [ ]\n \n const filter_regexp = filter instanceof RegExp\n const filter_fn = Boolean(filter && !filter_regexp)\n \n for (let fp of fps) {\n fp = path.normalize(fp)\n \n if (filter_regexp && !filter.test(fp))\n continue\n \n if (filter_fn && !(filter as Function)(fp))\n continue\n \n if (print)\n console.log(fp)\n \n fps_.push(fp)\n }\n \n return fps_\n}\n\n\n/** delete file or directory (use rimraf to delete directory fast) \n - fp: path\n - options?:\n - print?: `true` (effective only delete single file)\n*/\nexport async function fdelete (fp: string, { print = true, fast = false }: { print?: boolean, fast?: boolean } = { }) {\n if (fp.length < 6) throw new Error(`${fp} too short`)\n if (!path.isAbsolute(fp))\n throw new Error('fpd must be absolute path')\n \n if (fp.is_dir) {\n if (print)\n console.log(`delete directory: ${fp}`.red)\n await new Promise<void>((resolve, reject) => {\n rimraf(fp, { glob: false, disableGlob: true }, error => {\n if (error)\n reject(error)\n else\n resolve()\n })\n })\n } else {\n if (print)\n console.log('delete:', fp)\n await fsp.unlink(fp)\n }\n}\n\n\n/** copy file or direcotry\n - src: src file/directory absolute path\n - dst: dst file/directory absolute path\n @example\n fcopy('d:/temp/camera/', 'd:/camera/')\n*/\nexport async function fcopy (src: string, dst: string, {\n print = true,\n overwrite = true,\n}: {\n print?: boolean\n overwrite?: boolean\n} = { }) {\n if (src.endsWith('/') !== dst.endsWith('/'))\n throw new Error('src and dst must be both file path or directory path')\n \n if (!path.isAbsolute(src) || !path.isAbsolute(dst))\n throw new Error('src and dst must be absolute path')\n \n if (print)\n console.log(`copy: ${src} → ${dst}`)\n \n await fse.copy(src, dst, { overwrite, errorOnExist: true })\n}\n\n\n/** move file or direcotry\n - src: src file/directory absolute path\n - dst: dst file/directory absolute path\n @example\n fmove('d:/temp/camera/', 'd:/camera/')\n*/\nexport async function fmove (src: string, dst: string, {\n overwrite = false,\n print = true\n}: {\n overwrite?: boolean\n print?: boolean\n} = { }) {\n if (src.endsWith('/') !== dst.endsWith('/'))\n throw new Error('src and dst must be both file path or directory path')\n \n if (!path.isAbsolute(src) || !path.isAbsolute(dst))\n throw new Error('src and dst must be absolute path')\n \n if (print)\n console.log(`move: ${src} → ${dst}`)\n \n await fse.move(src, dst, { overwrite })\n}\n\n\n/** rename file \n - fp: current filename/path\n - fp_: new filename/path\n - options?:\n - fpd?: fp and fp_ is in same directory\n - print?: `true`\n - overwrite?: `true` better performance without check\n */\nexport async function frename (\n fp: string, \n fp_: string,\n {\n fpd,\n print = true,\n overwrite = true\n }: {\n fpd?: string\n print?: boolean\n overwrite?: boolean\n } = { }\n) {\n if (fpd) {\n fp = path.join(fpd, fp)\n fp_ = path.join(fpd, fp_)\n } else if (!path.isAbsolute(fp) || !path.isAbsolute(fp_))\n throw new Error('fp and fp_ must be absolute path')\n \n if (print)\n console.log('rename:', fp, '→', fp_)\n \n if (!overwrite && fp_.fexists)\n throw new Error(`file already exists:${fp_}`)\n \n await fsp.rename(fp, fp_)\n}\n\n\nexport async function fmkdir (fpd: string, options: fs.MakeDirectoryOptions & { print?: boolean, suppress_existence?: boolean } = { }) {\n if (!path.isAbsolute(fpd))\n throw new Error('fpd must be absolute path')\n \n options.print ??= true\n \n if (fpd.fexists)\n if (fpd.is_dir) {\n if (options.print && !options.suppress_existence)\n console.log('directory already exists:', fpd)\n return\n } else throw new Error(`file with same name already exists, cannot create directory: ${fpd}`)\n else if (options.print)\n console.log('mkdir:', fpd)\n \n await fsp.mkdir(fpd, { recursive: true })\n}\n\n\n/** \n - fp_real: current real file path\n - fp_link: file path or directory path\n*/\nexport async function flink (\n fp_real: string, \n fp_link: string, \n {\n junction = false,\n print = true \n }: { \n junction?: boolean\n print?: boolean\n} = { }) {\n if (!path.isAbsolute(fp_real) || !path.isAbsolute(fp_link))\n throw new Error('fpd must be absolute path')\n \n if (fp_link.fexists)\n if (fp_link.is_dir)\n fp_link = path.join(fp_link, fp_real.fname)\n else if ( (await fsp.lstat(fp_link)).isSymbolicLink() ) {\n console.log('link already exists:', fp_link)\n return\n } else\n throw new Error('file with same name already exists, cannot create new link')\n \n \n if (print)\n console.log(`source file ${fp_real} linked to ${fp_link}`)\n \n if (junction)\n fsp.symlink(fp_real, fp_link, 'junction')\n else\n fsp.symlink(fp_real, fp_link, fp_real.is_dir ? 'dir' : 'file')\n}\n\n\nexport function link_shortcut (target: string, name: string, { args }: { args?: string[] } = { }) {\n const cmd = dedent`\n $wsh_shell = New-Object -comObject WScript.Shell\n $shortcut = $wsh_shell.CreateShortcut(\"d:/links/#{name}.lnk\")\n $shortcut.TargetPath = '${target}'\n $shortcut.Arguments = \"${args || ''}\"\n $shortcut.WorkingDirectory = '${target.fdir}'\n ${ target.is_dir ? '$shortcut.IconLocation = \"%SystemRoot%\\\\System32\\\\SHELL32.dll,3\"' : '' }\n $shortcut.Save()\n `\n console.log(cmd)\n // await psh(cmd)\n}\n\n\nexport let fwatchers: Record<string, fs.FSWatcher> = { }\n\n/**\n - fp: path of file or directory\n - callback: called when modified\n - exec: call callback when watch is executed\n \n save fs.FSWatcher in watchers, subsequent call will auto close existing watcher for the same fp\n \n https://nodejs.org/dist/latest-v15.x/docs/api/fs.html#fs_fs_watch_filename_options_listener \n The listener callback gets two arguments (event, fname). \n event is either 'rename' or 'change', and filename is the name of the file which triggered the event.\n On most platforms, 'rename' is emitted whenever a filename appears or disappears in the directory.\n \n The listener callback is attached to the 'change' event fired by fs.FSWatcher, but it is not the same thing as the 'change' value of event. \n \n*/\nexport async function fwatch (\n fp: string,\n onchange: (event: string, fname: string) => any, \n { exec = true }: { exec?: boolean } = { }\n) {\n if (!path.isAbsolute(fp))\n throw new Error('fp must be absolute path')\n \n const _watcher = fwatchers[fp]\n if (_watcher)\n _watcher.close()\n \n if (exec)\n await onchange('change', fp.fname)\n \n const debounced_onchange = debounce(\n (event, fname) => {\n console.log(`file changed (${event}): ${fname}`)\n onchange(event, path.normalize(fname))\n },\n 500,\n { leading: false, trailing: true }\n )\n \n let watcher = watch(fp, debounced_onchange)\n watcher.on('error', error => {\n console.error(error)\n })\n return fwatchers[fp] = watcher\n}\n\n\n/** open a file and replace certain pattern */\nexport async function freplace (fp: string, pattern: string | RegExp, replacement: string) {\n await fwrite(\n fp,\n (await fread(fp))\n .replaceAll(pattern, replacement)\n )\n}\n\n/** convert file encoding to UTF-8\n - fp: file absolute path\n - options?:\n - dryrun?: `true`\n - encoding?: `'auto'`\n*/\nexport async function f2utf8 (fp: string, {\n dryrun = true,\n encoding = 'auto',\n}: {\n dryrun?: boolean\n encoding?: Encoding | 'auto'\n} = { }) {\n const text = await fread(fp, { encoding })\n if (dryrun) {\n console.log(text.slice(0, 10000))\n return\n }\n \n const fp_bak = `${fp.fdir}${fp.fname.replace(/(.*?)(\\.[^.]+)?$/, '$1.bak$2')}`\n if (!fp_bak.fexists)\n await fcopy(fp, fp_bak)\n \n await fwrite(fp, text)\n}\n\n"]}
|
package/net.js
CHANGED
|
@@ -273,17 +273,16 @@ on_open, on_close, on_error, on_message }) {
|
|
|
273
273
|
websocket.binaryType = 'arraybuffer';
|
|
274
274
|
return new Promise((resolve, reject) => {
|
|
275
275
|
websocket.addEventListener('open', async (event) => {
|
|
276
|
-
console.log(
|
|
276
|
+
console.log(`websocket opened: ${websocket.url}`);
|
|
277
277
|
await on_open?.(event, websocket);
|
|
278
278
|
resolve(websocket);
|
|
279
279
|
});
|
|
280
280
|
websocket.addEventListener('close', event => {
|
|
281
|
-
console.log(
|
|
281
|
+
console.log(`websocket closed: ${websocket.url} (code = ${event.code}, reason = '${event.reason}')`);
|
|
282
282
|
on_close?.(event, websocket);
|
|
283
283
|
});
|
|
284
284
|
websocket.addEventListener('error', event => {
|
|
285
|
-
const message =
|
|
286
|
-
console.error(message, event);
|
|
285
|
+
const message = `websocket errored: ${websocket.url}`;
|
|
287
286
|
on_error?.(event, websocket);
|
|
288
287
|
reject(Object.assign(new Error(message), { event }));
|
|
289
288
|
});
|
package/net.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"net.js","sourceRoot":"","sources":["net.ts"],"names":[],"mappings":";;;;AAMA,4FAG+B;AAC/B,gEAAgF;AAEhF,0EAAyC;AAEzC,2BAA8B;AAE9B,oEAA8B;AAC9B,8DAA6B;AAC7B,oDAAmB;AACnB,+CAAwD;AA2C/C,uFA3CA,qBAAM,OA2CA;AAlCf,0BAAuB;AAEvB,yCAA0D;AAE1D,IAAY,OAGX;AAHD,WAAY,OAAO;IACf,4CAAkC,CAAA;IAClC,4CAAiC,CAAA;AACrC,CAAC,EAHW,OAAO,GAAP,eAAO,KAAP,eAAO,QAGlB;AAGD,sD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;MAGE;IACF,KAAK,CAAC,MAAM,CAAE,KAA4B,EAAE,SAAoB;QAC5D,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;QACxC,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,IAAI,EAAE,GAAG,OAAO,CAAA;QAElC,IAAI,IAAI,CAAC,KAAK;YACV,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAA;QAExB,IAAI,IAAI,EAAE,QAAQ;YACd,IAAI;gBACA,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAA;gBAEtD,IAAI,CAAC,OAAO;oBACR,MAAM,IAAI,KAAK,CAAC,oBAAoB,IAAI,EAAE,CAAC,CAAA;gBAE/C,MAAM,OAAO,CAAC,OAAO,EAAE,SAAS,CAAC,CAAA;aACpC;YAAC,OAAO,KAAK,EAAE;gBACZ,IAAI,CAAC,IAAI,CACL;oBACI,EAAE,EAAE,OAAO,CAAC,EAAE;oBACd,KAAK;oBACL,IAAI,EAAE,IAAI;iBACb,EACD,SAAS,CACZ,CAAA;gBACD,MAAM,KAAK,CAAA;aACd;aACA,EAAG,QAAQ;YACZ,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC,CAAA;YAC1B,IAAI,IAAI;gBACJ,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,IAAI,CAAA;SAC/B;IACL,CAAC;CACJ;AApND,wBAoNC","sourcesContent":["import {\n default as request_lib,\n type OptionsWithUri,\n type OptionsWithUrl\n} from 'request'\n\nimport {\n default as request_promise,\n type FullResponse,\n} from 'request-promise-native'\nimport { RequestError, StatusCodeError } from 'request-promise-native/errors.js'\n\nimport promise_retry from 'promise-retry'\n\nimport { WebSocket } from 'ws'\n\nimport iconv from 'iconv-lite'\nimport cheerio from 'cheerio'\nimport qs from 'qs'\nimport { Cookie, MemoryCookieStore } from 'tough-cookie'\n\ndeclare module 'tough-cookie' {\n interface MemoryCookieStore {\n idx: Record<string, any>\n }\n}\n\n\nimport './prototype.js'\nimport type { Encoding } from './file.js'\nimport { inspect, output_width, concat } from './utils.js'\n\nexport enum MyProxy {\n socks5 = 'http://localhost:10080',\n whistle = 'http://localhost:8899',\n}\n\n\n// ------------------------------------ Fetch, Request\nconst cookie_store = new MemoryCookieStore()\n\nexport const cookies = {\n store: cookie_store,\n \n jar: request_promise.jar(cookie_store),\n \n get (domain_or_url: string, str = false) {\n if (domain_or_url.startsWith('http'))\n if (str)\n return this.jar.getCookieString(domain_or_url)\n else\n return this.jar.getCookies(domain_or_url)\n \n let cookies: Cookie[]\n this.store.findCookies(domain_or_url, null, true, (error, _cookies) => {\n if (error) throw error\n cookies = _cookies\n })\n return cookies\n },\n}\n\nexport { Cookie }\n\n\nexport const _request = request_promise.defaults({\n // rejectUnauthorized: false,\n \n /** prevent 302 redirect cause error, which is a boolean to set whether status codes other than 2xx should also reject the promise */\n simple: false,\n \n jar: cookies.jar\n})\n\n\nexport async function request_retry (retries: number, request_options: request_promise.OptionsWithUrl) {\n return promise_retry<FullResponse>({\n retries,\n minTimeout: 1000,\n maxTimeout: Infinity,\n factor: 2\n }, async (retry, count) => {\n try {\n return await _request(request_options)\n } catch (error) {\n if (!['ECONNRESET', 'ETIMEDOUT', 'ESOCKETTIMEDOUT'].includes(error.cause?.code)) throw error\n if (count <= retries)\n console.log(`${`retry (${count}) …`.yellow} ${request_options.url.toString().blue.underline}`)\n return retry(error)\n }\n })\n}\n\n\nexport interface RequestOptions {\n method?: 'get' | 'post' | 'put' | 'head' | 'delete' | 'patch'\n \n queries?: Record<string, any>\n \n headers?: Record<string, string>\n \n body?: string | Record<string, any>\n \n type?: 'application/json' | 'application/x-www-form-urlencoded' | 'multipart/form-data'\n \n \n proxy?: boolean | MyProxy | string\n \n encoding?: Encoding\n \n retries?: true | number\n \n timeout?: number\n \n auth?: {\n username: string\n password: string\n }\n \n gzip?: boolean\n \n cookies?: Record<string, string>\n}\n\nexport interface RequestRawOptions extends RequestOptions {\n raw: true\n}\n\n/** \n - url: must be full url\n - options:\n - raw: `false` 传入后返回整个 response\n - encoding: `(response content-type: charset=gb18030) || 'utf-8'` when 'binary' then return buffer\n - type: `'application/json'` request content-type header (if has body)\n - proxy: `false` proxy === true then use MyProxy.whistle\n - retries: `false` could be true (default 3 times) or retry times\n - timeout: `20 * 1000`\n - gzip: `raw -> false; else -> true`\n*/\nexport async function request (url: string | URL): Promise<string>\nexport async function request (url: string | URL, options: RequestRawOptions): Promise<request_lib.Response>\nexport async function request (url: string | URL, options: RequestOptions & { encoding: 'binary' }): Promise<Buffer>\nexport async function request (url: string | URL, options: RequestOptions): Promise<string>\nexport async function request (url: string | URL, {\n queries,\n \n body,\n \n type = 'application/json',\n \n proxy,\n \n method,\n \n headers,\n \n encoding,\n \n raw = false,\n \n retries,\n \n timeout = 20 * 1000,\n \n auth,\n \n gzip,\n \n cookies,\n \n}: RequestOptions & { raw?: boolean } = { }) {\n url = url.toString()\n \n const _body = body // for error log\n \n if (body && !method)\n method = 'post'\n \n if (type === 'application/json' && typeof body !== 'undefined' && (typeof body !== 'string' && !Buffer.isBuffer(body)))\n body = JSON.stringify(body)\n \n // --- proxy\n if (proxy) {\n if (proxy === true)\n proxy = MyProxy.whistle\n } else\n proxy = false\n \n // --- gzip\n if (gzip === undefined)\n gzip = !raw\n \n \n const options: request_lib.Options & { resolveWithFullResponse: boolean } = {\n url,\n \n ... method ? { method: method.toUpperCase() } : { },\n \n proxy,\n \n gzip,\n \n encoding: null,\n \n resolveWithFullResponse: true,\n \n headers: {\n 'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,ja-JP;q=0.6,ja;q=0.5',\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36',\n ... body ? { 'content-type': type } : { }, \n ... cookies ? {\n cookie: Object.entries(cookies)\n .map(([key, value]) => \n `${encodeURIComponent(key)}=${encodeURIComponent(value)}`\n ).join('; ')\n } : { },\n ... headers\n },\n \n ... queries ? { qs: queries } : { },\n \n // --- body\n ... (() => {\n if (!body) return { }\n if (type === 'application/x-www-form-urlencoded') return { form: body }\n if (type === 'multipart/form-data') return { formData: body as Record<string, any> }\n return { body }\n })(),\n \n ... timeout ? { timeout } : { },\n \n ... auth ? { auth } : { },\n }\n \n let resp: request_lib.Response\n \n try {\n if (retries) {\n if (retries === true)\n retries = 3\n \n resp = await request_retry(retries, options)\n } else\n resp = await _request(options)\n \n if (!(200 <= resp.statusCode && resp.statusCode <= 299))\n throw new StatusCodeError(resp.statusCode, resp.body, options, resp)\n \n } catch (error) {\n const {\n name, \n options: { method, url, uri, qs }, \n response,\n }: {\n options: OptionsWithUri & OptionsWithUrl\n response: FullResponse\n } & Error = error\n \n error[inspect.custom] = () => {\n let s = '─'.repeat(output_width / 2) + '\\n' +\n `${(method || 'get').toLowerCase().red} ${String(url || uri).blue.underline}\\n`\n \n if (qs)\n s += `\\n${'request.query:'.blue}\\n` +\n inspect(qs) + '\\n'\n \n if (_body)\n s += `\\n${'request.body:'.blue}\\n` +\n inspect(_body) + '\\n'\n \n if (name === 'StatusCodeError')\n s += `\\n${'response.status:'.yellow} ${String(error.statusCode).red}\\n`\n else if (error instanceof RequestError)\n s += `\\n${'response.cause:'.yellow}\\n` +\n `${inspect(error.cause)}\\n`\n else\n s += `\\n${inspect(error)}\\n`\n \n if (response) {\n s += `\\n${'response.headers:'.yellow}\\n` + \n `${inspect(response.headers)}\\n`\n \n if (response.body)\n s += `\\n${'response.body:'.yellow}\\n` +\n `${inspect(response.body.toString())}\\n`\n }\n \n s += `\\n${'stack:'.yellow}\\n` +\n `${new Error().stack}\\n` +\n '─'.repeat(output_width / 2)\n \n return s\n }\n \n throw error\n }\n \n if (raw)\n return resp\n \n if (!resp.body)\n return resp.body\n \n // --- decode body\n if (encoding === 'binary')\n return resp.body\n \n encoding ||= /charset=(.*)/.exec(resp.headers['content-type'])?.[1] as Encoding || 'utf-8'\n \n if (/utf-?8/i.test(encoding))\n return (resp.body as Buffer).toString('utf-8')\n \n return iconv.decode((resp.body as Buffer), encoding)\n}\n\n\n/** make http request and parse body as json */\nexport async function request_json <T = any> (url: string | URL, options?: RequestOptions): Promise<T> {\n const resp = await request(url, options)\n if (!resp) return\n try {\n return JSON.parse(resp)\n } catch (error) {\n console.log(resp)\n throw error\n }\n}\n\n\n/** use $.html(cheerio_element) to get outer html */\nexport function parse_html (html: string) {\n let $ = cheerio.load(html, { decodeEntities: false })\n \n Object.defineProperty($, inspect.custom, {\n configurable: true,\n enumerable: false,\n value () {\n return this.html()\n }\n })\n \n Object.defineProperty($.prototype, inspect.custom, {\n configurable: true,\n enumerable: false,\n // @ts-ignore\n value (this: cheerio.Cheerio) {\n if (this.length > 1)\n return this.map((index, element) => {\n if (typeof element === 'string') return element\n return $.html(element)\n }).get().join_lines()\n \n return this.toString()\n }\n })\n \n return $\n}\n\n\n/** use $.html(cheerio_element) to get outer html */\nexport async function request_page (url: string | URL, options?: RequestOptions) {\n return parse_html(\n await request(url, options)\n )\n}\n\n\nexport function to_curl (url: string | URL, { queries, headers, method, body, proxy, exe = true }: RequestOptions & { exe?: boolean } = { }) {\n if (proxy === true)\n proxy = process.env.http_proxy\n \n url = url.toString()\n \n if (!url.startsWith('http'))\n url = `http://${url}`\n \n return (exe ? 'curl.exe' : 'curl') + \n ' ' + ( url + (queries ? '?' : '') + qs.stringify(queries) ).quote() +\n // ( typeof proxy === 'undefined' ?\n // ''\n // :\n // ( proxy ? ' --proxy ' + proxy.quote() : ' --noproxy ' + '*'.quote())\n // ) +\n ( proxy ? ` --proxy ${proxy.quote()}` : '' ) +\n ( method && method !== 'get' ? ` -X ${method.toUpperCase()}` : '' ) +\n ( headers ? Object.entries(headers).map( ([key, value]) => ' -H ' + `${key}: ${value}`.quote() ).join('') : '' ) +\n ( body ? ' -H ' + 'content-type: application/json'.quote() : '') +\n ( body ? ' --data ' + JSON.stringify(body).quote() : '')\n}\n\n\n\n\n// ------------------------------------ rpc client\n/** post json to http://localhost:8421/api/rpc\n - func: function name\n - args?: argument array\n - options?:\n - ignore?: `false` wait for execution but do not serialize result to response\n - async?: `false` do not wait for exec\n*/\nexport async function rpc (\n func: string, \n args?: any[], \n { url = 'http://localhost:8421/api/rpc', async: _async = false, ignore = false }: { url?: string, async?: boolean, ignore?: boolean } = { }\n) {\n if (!func) throw new Error('rpc argument error: no func')\n \n return request_json(url, {\n body: {\n func,\n args,\n async: _async,\n ignore,\n }\n })\n}\n\n\nexport function rpc_curl (func: string, args: any[]) {\n const cmd = args.find( arg => typeof arg === 'object') ?\n to_curl('http://localhost:8421/api/rpc', { body: { func, args } })\n :\n to_curl('http://localhost:8421/api/rpc', { queries: { func, args } })\n return cmd\n}\n\n\nlet decoder = new TextDecoder()\n\nlet encoder = new TextEncoder()\n\n\nexport async function connect_websocket (\n url: string | URL,\n {\n protocols,\n max_payload = 2 ** 33, // 8 GB\n on_open,\n on_close,\n on_error,\n on_message\n }: {\n protocols?: string | string[]\n max_payload?: number\n on_open? (event: any, websocket: WebSocket): any\n on_close? (event: { code: number, reason: string }, websocket: WebSocket): any\n on_error? (event: any, websocket: WebSocket): any\n on_message (event: { data: ArrayBuffer }, websocket: WebSocket): any\n }\n) {\n let websocket = new WebSocket(url, protocols, { maxPayload: max_payload })\n \n // https://stackoverflow.com/questions/11821096/what-is-the-difference-between-an-arraybuffer-and-a-blob/39951543\n websocket.binaryType = 'arraybuffer'\n \n return new Promise<WebSocket>((resolve, reject) => {\n websocket.addEventListener('open', async event => {\n console.log(`${websocket.url} opened`)\n \n await on_open?.(event, websocket)\n \n resolve(websocket)\n })\n \n websocket.addEventListener('close', event => {\n console.log(`${websocket.url} closed with code = ${event.code}, reason = '${event.reason}'`)\n on_close?.(event, websocket)\n })\n \n websocket.addEventListener('error', event => {\n const message = `${websocket.url} errored`\n console.error(message, event)\n on_error?.(event, websocket)\n reject(\n Object.assign(\n new Error(message),\n { event }\n )\n )\n })\n \n websocket.addEventListener('message', event => {\n on_message(event as any, websocket)\n })\n })\n}\n\n\n/** 二进制消息格式 \n - json.length (小端序): 4 字节\n - json 数据\n - binary 数据\n*/\nexport interface Message <T extends any[] = any[]> {\n /** 本次 rpc 的 id */\n id?: number\n \n /** rpc 发起方指定被调用的 function name, 多个相同 id, func 的 message 组成一个请求流 */\n func?: string\n \n /** 等待执行,但不要序列化返回 func 的执行结果 (message 中无 args) */\n ignore?: boolean\n \n /** 不等待 func 执行,remote 收到后直接确认返回 (message 中 done = true) */\n async?: boolean\n \n /** 这个数组里面要么是对应的 JS 参数,要么是 Uint8Array 参数对应的 binary length \n args 可以是: \n - rpc 发起方调用 func 的参数,或者请求流 message 携带的数据\n - 作为结果或者响应流的 message 数据,传给请求发起方\n */\n args?: T\n \n /** bins: 哪几个 arg 是 Uint8Array 类型的,如: [0, 3] */\n bins?: number[]\n \n /** 被调方执行 func 产生的错误 */\n error?: Error\n \n /** 如果请求或者响应是一个流,通过这个 flag 表明是最后一个 message, 并且可以销毁 handler 了 */\n done?: boolean\n}\n\n/** 通过创建 Remote 对象对 WebSocket RPC 进行抽象 \n 调用方使用 remote.call 进行调用 \n 被调方在创建 Remote 对象时传入 funcs 注册处理函数,并使用 Remote.handle 方法处理 WebSocket message \n*/\nexport class Remote {\n url: string\n \n websocket: WebSocket\n \n id = 0\n \n /** 被调方的 message 处理器 */\n funcs: Record<\n string, \n (message: Message, websocket?: WebSocket) => void | Promise<void>\n >\n \n /** 调用方发起的 rpc 对应响应的 message 处理器 */\n handlers: ((message: Message) => any)[] = [ ]\n \n print = false\n \n get connected () {\n return this.websocket?.readyState === WebSocket.OPEN\n }\n \n \n static parse <T extends any[] = any[]> (array_buffer: ArrayBuffer) {\n const buf = new Uint8Array(array_buffer as ArrayBuffer)\n const dv = new DataView(array_buffer)\n \n const len_json = dv.getUint32(0, true)\n \n let offset = 4 + len_json\n \n let message: Message<T> = JSON.parse(\n decoder.decode(\n buf.subarray(4, offset)\n )\n )\n \n message.args ||= [ ] as T\n \n if (message.bins) {\n let args = message.args\n \n for (const ibin of message.bins) {\n const len_buf = args[ibin]\n args[ibin] = buf.subarray(offset, offset + len_buf)\n offset += len_buf\n }\n }\n \n return message\n }\n \n \n static pack ({\n id,\n func,\n ignore,\n async: _async,\n done,\n error,\n args: _args = [ ],\n }: Message) {\n let args = [..._args]\n \n let bins: number[] = [ ]\n let bufs: Uint8Array[] = [ ]\n \n for (let i = 0; i < args.length; i++) {\n const arg = args[i]\n if (arg instanceof Uint8Array) {\n bins.push(i)\n bufs.push(arg)\n args[i] = arg.length\n }\n }\n \n const data_json = {\n id,\n ... func ? { func } : { },\n ... ignore ? { ignore } : { },\n ... _async ? { async: _async } : { },\n ... done ? { done } : { },\n ... error ? { error } : { },\n ... args.length ? { args } : { },\n ... bins.length ? { bins } : { },\n }\n \n const str_json = encoder.encode(\n JSON.stringify(data_json)\n )\n \n let dv = new DataView(\n new ArrayBuffer(4)\n )\n \n dv.setUint32(0, str_json.length, true)\n \n return concat([\n dv,\n str_json,\n ... bufs\n ])\n }\n \n \n constructor ({\n url,\n funcs = { },\n websocket,\n }: {\n url?: string\n funcs?: Remote['funcs']\n websocket?: WebSocket\n } = { }) {\n this.url = url\n this.funcs = funcs\n this.websocket = websocket\n }\n \n \n async connect () {\n this.websocket = await connect_websocket(this.url, {\n on_message: this.handle.bind(this)\n })\n }\n \n \n disconnect () {\n this.websocket?.close()\n this.id = 0\n this.handlers = [ ]\n }\n \n \n send (message: Message, websocket = this.websocket) {\n if (!('id' in message))\n message.id = this.id\n \n websocket.send(\n Remote.pack(message)\n )\n }\n \n \n /** 调用 remote 中的 func, 返回结果由 handler 处理,处理 done message 之后的返回值作为 call 函数的返回值 */\n async call <T extends any[] = any[], R = any> (\n message: Message,\n handler: (message: Message<T>) => any\n ) {\n return new Promise<R>((resolve, reject) => {\n this.handlers[this.id] = async (message: Message<T>) => {\n const { error, done } = message\n \n if (error) {\n reject(\n Object.assign(\n new Error(),\n error\n )\n )\n return\n }\n \n let result = await handler(message)\n \n if (done)\n resolve(result)\n }\n \n this.send(message)\n \n this.id++\n })\n }\n \n \n /** 处理接收到的 WebSocket message\n 1. 被调用方接收 message 并开始处理\n 2. 调用方处理 message 响应\n */\n async handle (event: { data: ArrayBuffer }, websocket: WebSocket) {\n const message = Remote.parse(event.data)\n const { func, id, done } = message\n \n if (this.print)\n console.log(message)\n \n if (func) // 作为被调方\n try {\n const handler = this.funcs[func] || this.funcs.default\n \n if (!handler)\n throw new Error(`找不到 rpc handler: ${func}`)\n \n await handler(message, websocket)\n } catch (error) {\n this.send(\n {\n id: message.id,\n error,\n done: true\n },\n websocket\n )\n throw error\n }\n else { // 作为发起方\n this.handlers[id](message)\n if (done)\n this.handlers[id] = null\n }\n }\n}\n\n\n"]}
|
|
1
|
+
{"version":3,"file":"net.js","sourceRoot":"","sources":["net.ts"],"names":[],"mappings":";;;;AAMA,4FAG+B;AAC/B,gEAAgF;AAEhF,0EAAyC;AAEzC,2BAA8B;AAE9B,oEAA8B;AAC9B,8DAA6B;AAC7B,oDAAmB;AACnB,+CAAwD;AA2C/C,uFA3CA,qBAAM,OA2CA;AAlCf,0BAAuB;AAEvB,yCAA0D;AAE1D,IAAY,OAGX;AAHD,WAAY,OAAO;IACf,4CAAkC,CAAA;IAClC,4CAAiC,CAAA;AACrC,CAAC,EAHW,OAAO,GAAP,eAAO,KAAP,eAAO,QAGlB;AAGD,sDAAsD;AACtD,MAAM,YAAY,GAAG,IAAI,gCAAiB,EAAE,CAAA;AAE/B,QAAA,OAAO,GAAG;IACnB,KAAK,EAAE,YAAY;IAEnB,GAAG,EAAE,gCAAe,CAAC,GAAG,CAAC,YAAY,CAAC;IAEtC,GAAG,CAAE,aAAqB,EAAE,GAAG,GAAG,KAAK;QACnC,IAAI,aAAa,CAAC,UAAU,CAAC,MAAM,CAAC;YAChC,IAAI,GAA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AM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAA;gBAEtD,IAAI,CAAC,OAAO;oBACR,MAAM,IAAI,KAAK,CAAC,oBAAoB,IAAI,EAAE,CAAC,CAAA;gBAE/C,MAAM,OAAO,CAAC,OAAO,EAAE,SAAS,CAAC,CAAA;aACpC;YAAC,OAAO,KAAK,EAAE;gBACZ,IAAI,CAAC,IAAI,CACL;oBACI,EAAE,EAAE,OAAO,CAAC,EAAE;oBACd,KAAK;oBACL,IAAI,EAAE,IAAI;iBACb,EACD,SAAS,CACZ,CAAA;gBACD,MAAM,KAAK,CAAA;aACd;aACA,EAAG,QAAQ;YACZ,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC,CAAA;YAC1B,IAAI,IAAI;gBACJ,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,IAAI,CAAA;SAC/B;IACL,CAAC;CACJ;AApND,wBAoNC","sourcesContent":["import {\n default as request_lib,\n type OptionsWithUri,\n type OptionsWithUrl\n} from 'request'\n\nimport {\n default as request_promise,\n type FullResponse,\n} from 'request-promise-native'\nimport { RequestError, StatusCodeError } from 'request-promise-native/errors.js'\n\nimport promise_retry from 'promise-retry'\n\nimport { WebSocket } from 'ws'\n\nimport iconv from 'iconv-lite'\nimport cheerio from 'cheerio'\nimport qs from 'qs'\nimport { Cookie, MemoryCookieStore } from 'tough-cookie'\n\ndeclare module 'tough-cookie' {\n interface MemoryCookieStore {\n idx: Record<string, any>\n }\n}\n\n\nimport './prototype.js'\nimport type { Encoding } from './file.js'\nimport { inspect, output_width, concat } from './utils.js'\n\nexport enum MyProxy {\n socks5 = 'http://localhost:10080',\n whistle = 'http://localhost:8899',\n}\n\n\n// ------------------------------------ Fetch, Request\nconst cookie_store = new MemoryCookieStore()\n\nexport const cookies = {\n store: cookie_store,\n \n jar: request_promise.jar(cookie_store),\n \n get (domain_or_url: string, str = false) {\n if (domain_or_url.startsWith('http'))\n if (str)\n return this.jar.getCookieString(domain_or_url)\n else\n return this.jar.getCookies(domain_or_url)\n \n let cookies: Cookie[]\n this.store.findCookies(domain_or_url, null, true, (error, _cookies) => {\n if (error) throw error\n cookies = _cookies\n })\n return cookies\n },\n}\n\nexport { Cookie }\n\n\nexport const _request = request_promise.defaults({\n // rejectUnauthorized: false,\n \n /** prevent 302 redirect cause error, which is a boolean to set whether status codes other than 2xx should also reject the promise */\n simple: false,\n \n jar: cookies.jar\n})\n\n\nexport async function request_retry (retries: number, request_options: request_promise.OptionsWithUrl) {\n return promise_retry<FullResponse>({\n retries,\n minTimeout: 1000,\n maxTimeout: Infinity,\n factor: 2\n }, async (retry, count) => {\n try {\n return await _request(request_options)\n } catch (error) {\n if (!['ECONNRESET', 'ETIMEDOUT', 'ESOCKETTIMEDOUT'].includes(error.cause?.code)) throw error\n if (count <= retries)\n console.log(`${`retry (${count}) …`.yellow} ${request_options.url.toString().blue.underline}`)\n return retry(error)\n }\n })\n}\n\n\nexport interface RequestOptions {\n method?: 'get' | 'post' | 'put' | 'head' | 'delete' | 'patch'\n \n queries?: Record<string, any>\n \n headers?: Record<string, string>\n \n body?: string | Record<string, any>\n \n type?: 'application/json' | 'application/x-www-form-urlencoded' | 'multipart/form-data'\n \n \n proxy?: boolean | MyProxy | string\n \n encoding?: Encoding\n \n retries?: true | number\n \n timeout?: number\n \n auth?: {\n username: string\n password: string\n }\n \n gzip?: boolean\n \n cookies?: Record<string, string>\n}\n\nexport interface RequestRawOptions extends RequestOptions {\n raw: true\n}\n\n/** \n - url: must be full url\n - options:\n - raw: `false` 传入后返回整个 response\n - encoding: `(response content-type: charset=gb18030) || 'utf-8'` when 'binary' then return buffer\n - type: `'application/json'` request content-type header (if has body)\n - proxy: `false` proxy === true then use MyProxy.whistle\n - retries: `false` could be true (default 3 times) or retry times\n - timeout: `20 * 1000`\n - gzip: `raw -> false; else -> true`\n*/\nexport async function request (url: string | URL): Promise<string>\nexport async function request (url: string | URL, options: RequestRawOptions): Promise<request_lib.Response>\nexport async function request (url: string | URL, options: RequestOptions & { encoding: 'binary' }): Promise<Buffer>\nexport async function request (url: string | URL, options: RequestOptions): Promise<string>\nexport async function request (url: string | URL, {\n queries,\n \n body,\n \n type = 'application/json',\n \n proxy,\n \n method,\n \n headers,\n \n encoding,\n \n raw = false,\n \n retries,\n \n timeout = 20 * 1000,\n \n auth,\n \n gzip,\n \n cookies,\n \n}: RequestOptions & { raw?: boolean } = { }) {\n url = url.toString()\n \n const _body = body // for error log\n \n if (body && !method)\n method = 'post'\n \n if (type === 'application/json' && typeof body !== 'undefined' && (typeof body !== 'string' && !Buffer.isBuffer(body)))\n body = JSON.stringify(body)\n \n // --- proxy\n if (proxy) {\n if (proxy === true)\n proxy = MyProxy.whistle\n } else\n proxy = false\n \n // --- gzip\n if (gzip === undefined)\n gzip = !raw\n \n \n const options: request_lib.Options & { resolveWithFullResponse: boolean } = {\n url,\n \n ... method ? { method: method.toUpperCase() } : { },\n \n proxy,\n \n gzip,\n \n encoding: null,\n \n resolveWithFullResponse: true,\n \n headers: {\n 'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,ja-JP;q=0.6,ja;q=0.5',\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36',\n ... body ? { 'content-type': type } : { }, \n ... cookies ? {\n cookie: Object.entries(cookies)\n .map(([key, value]) => \n `${encodeURIComponent(key)}=${encodeURIComponent(value)}`\n ).join('; ')\n } : { },\n ... headers\n },\n \n ... queries ? { qs: queries } : { },\n \n // --- body\n ... (() => {\n if (!body) return { }\n if (type === 'application/x-www-form-urlencoded') return { form: body }\n if (type === 'multipart/form-data') return { formData: body as Record<string, any> }\n return { body }\n })(),\n \n ... timeout ? { timeout } : { },\n \n ... auth ? { auth } : { },\n }\n \n let resp: request_lib.Response\n \n try {\n if (retries) {\n if (retries === true)\n retries = 3\n \n resp = await request_retry(retries, options)\n } else\n resp = await _request(options)\n \n if (!(200 <= resp.statusCode && resp.statusCode <= 299))\n throw new StatusCodeError(resp.statusCode, resp.body, options, resp)\n \n } catch (error) {\n const {\n name, \n options: { method, url, uri, qs }, \n response,\n }: {\n options: OptionsWithUri & OptionsWithUrl\n response: FullResponse\n } & Error = error\n \n error[inspect.custom] = () => {\n let s = '─'.repeat(output_width / 2) + '\\n' +\n `${(method || 'get').toLowerCase().red} ${String(url || uri).blue.underline}\\n`\n \n if (qs)\n s += `\\n${'request.query:'.blue}\\n` +\n inspect(qs) + '\\n'\n \n if (_body)\n s += `\\n${'request.body:'.blue}\\n` +\n inspect(_body) + '\\n'\n \n if (name === 'StatusCodeError')\n s += `\\n${'response.status:'.yellow} ${String(error.statusCode).red}\\n`\n else if (error instanceof RequestError)\n s += `\\n${'response.cause:'.yellow}\\n` +\n `${inspect(error.cause)}\\n`\n else\n s += `\\n${inspect(error)}\\n`\n \n if (response) {\n s += `\\n${'response.headers:'.yellow}\\n` + \n `${inspect(response.headers)}\\n`\n \n if (response.body)\n s += `\\n${'response.body:'.yellow}\\n` +\n `${inspect(response.body.toString())}\\n`\n }\n \n s += `\\n${'stack:'.yellow}\\n` +\n `${new Error().stack}\\n` +\n '─'.repeat(output_width / 2)\n \n return s\n }\n \n throw error\n }\n \n if (raw)\n return resp\n \n if (!resp.body)\n return resp.body\n \n // --- decode body\n if (encoding === 'binary')\n return resp.body\n \n encoding ||= /charset=(.*)/.exec(resp.headers['content-type'])?.[1] as Encoding || 'utf-8'\n \n if (/utf-?8/i.test(encoding))\n return (resp.body as Buffer).toString('utf-8')\n \n return iconv.decode((resp.body as Buffer), encoding)\n}\n\n\n/** make http request and parse body as json */\nexport async function request_json <T = any> (url: string | URL, options?: RequestOptions): Promise<T> {\n const resp = await request(url, options)\n if (!resp) return\n try {\n return JSON.parse(resp)\n } catch (error) {\n console.log(resp)\n throw error\n }\n}\n\n\n/** use $.html(cheerio_element) to get outer html */\nexport function parse_html (html: string) {\n let $ = cheerio.load(html, { decodeEntities: false })\n \n Object.defineProperty($, inspect.custom, {\n configurable: true,\n enumerable: false,\n value () {\n return this.html()\n }\n })\n \n Object.defineProperty($.prototype, inspect.custom, {\n configurable: true,\n enumerable: false,\n // @ts-ignore\n value (this: cheerio.Cheerio) {\n if (this.length > 1)\n return this.map((index, element) => {\n if (typeof element === 'string') return element\n return $.html(element)\n }).get().join_lines()\n \n return this.toString()\n }\n })\n \n return $\n}\n\n\n/** use $.html(cheerio_element) to get outer html */\nexport async function request_page (url: string | URL, options?: RequestOptions) {\n return parse_html(\n await request(url, options)\n )\n}\n\n\nexport function to_curl (url: string | URL, { queries, headers, method, body, proxy, exe = true }: RequestOptions & { exe?: boolean } = { }) {\n if (proxy === true)\n proxy = process.env.http_proxy\n \n url = url.toString()\n \n if (!url.startsWith('http'))\n url = `http://${url}`\n \n return (exe ? 'curl.exe' : 'curl') + \n ' ' + ( url + (queries ? '?' : '') + qs.stringify(queries) ).quote() +\n // ( typeof proxy === 'undefined' ?\n // ''\n // :\n // ( proxy ? ' --proxy ' + proxy.quote() : ' --noproxy ' + '*'.quote())\n // ) +\n ( proxy ? ` --proxy ${proxy.quote()}` : '' ) +\n ( method && method !== 'get' ? ` -X ${method.toUpperCase()}` : '' ) +\n ( headers ? Object.entries(headers).map( ([key, value]) => ' -H ' + `${key}: ${value}`.quote() ).join('') : '' ) +\n ( body ? ' -H ' + 'content-type: application/json'.quote() : '') +\n ( body ? ' --data ' + JSON.stringify(body).quote() : '')\n}\n\n\n\n\n// ------------------------------------ rpc client\n/** post json to http://localhost:8421/api/rpc\n - func: function name\n - args?: argument array\n - options?:\n - ignore?: `false` wait for execution but do not serialize result to response\n - async?: `false` do not wait for exec\n*/\nexport async function rpc (\n func: string, \n args?: any[], \n { url = 'http://localhost:8421/api/rpc', async: _async = false, ignore = false }: { url?: string, async?: boolean, ignore?: boolean } = { }\n) {\n if (!func) throw new Error('rpc argument error: no func')\n \n return request_json(url, {\n body: {\n func,\n args,\n async: _async,\n ignore,\n }\n })\n}\n\n\nexport function rpc_curl (func: string, args: any[]) {\n const cmd = args.find( arg => typeof arg === 'object') ?\n to_curl('http://localhost:8421/api/rpc', { body: { func, args } })\n :\n to_curl('http://localhost:8421/api/rpc', { queries: { func, args } })\n return cmd\n}\n\n\nlet decoder = new TextDecoder()\n\nlet encoder = new TextEncoder()\n\n\nexport async function connect_websocket (\n url: string | URL,\n {\n protocols,\n max_payload = 2 ** 33, // 8 GB\n on_open,\n on_close,\n on_error,\n on_message\n }: {\n protocols?: string | string[]\n max_payload?: number\n on_open? (event: any, websocket: WebSocket): any\n on_close? (event: { code: number, reason: string }, websocket: WebSocket): any\n on_error? (event: any, websocket: WebSocket): any\n on_message (event: { data: ArrayBuffer }, websocket: WebSocket): any\n }\n) {\n let websocket = new WebSocket(url, protocols, { maxPayload: max_payload })\n \n // https://stackoverflow.com/questions/11821096/what-is-the-difference-between-an-arraybuffer-and-a-blob/39951543\n websocket.binaryType = 'arraybuffer'\n \n return new Promise<WebSocket>((resolve, reject) => {\n websocket.addEventListener('open', async event => {\n console.log(`websocket opened: ${websocket.url}`)\n \n await on_open?.(event, websocket)\n \n resolve(websocket)\n })\n \n websocket.addEventListener('close', event => {\n console.log(`websocket closed: ${websocket.url} (code = ${event.code}, reason = '${event.reason}')`)\n on_close?.(event, websocket)\n })\n \n websocket.addEventListener('error', event => {\n const message = `websocket errored: ${websocket.url}`\n on_error?.(event, websocket)\n reject(\n Object.assign(\n new Error(message),\n { event }\n )\n )\n })\n \n websocket.addEventListener('message', event => {\n on_message(event as any, websocket)\n })\n })\n}\n\n\n/** 二进制消息格式 \n - json.length (小端序): 4 字节\n - json 数据\n - binary 数据\n*/\nexport interface Message <T extends any[] = any[]> {\n /** 本次 rpc 的 id */\n id?: number\n \n /** rpc 发起方指定被调用的 function name, 多个相同 id, func 的 message 组成一个请求流 */\n func?: string\n \n /** 等待执行,但不要序列化返回 func 的执行结果 (message 中无 args) */\n ignore?: boolean\n \n /** 不等待 func 执行,remote 收到后直接确认返回 (message 中 done = true) */\n async?: boolean\n \n /** 这个数组里面要么是对应的 JS 参数,要么是 Uint8Array 参数对应的 binary length \n args 可以是: \n - rpc 发起方调用 func 的参数,或者请求流 message 携带的数据\n - 作为结果或者响应流的 message 数据,传给请求发起方\n */\n args?: T\n \n /** bins: 哪几个 arg 是 Uint8Array 类型的,如: [0, 3] */\n bins?: number[]\n \n /** 被调方执行 func 产生的错误 */\n error?: Error\n \n /** 如果请求或者响应是一个流,通过这个 flag 表明是最后一个 message, 并且可以销毁 handler 了 */\n done?: boolean\n}\n\n/** 通过创建 Remote 对象对 WebSocket RPC 进行抽象 \n 调用方使用 remote.call 进行调用 \n 被调方在创建 Remote 对象时传入 funcs 注册处理函数,并使用 Remote.handle 方法处理 WebSocket message \n*/\nexport class Remote {\n url: string\n \n websocket: WebSocket\n \n id = 0\n \n /** 被调方的 message 处理器 */\n funcs: Record<\n string, \n (message: Message, websocket?: WebSocket) => void | Promise<void>\n >\n \n /** 调用方发起的 rpc 对应响应的 message 处理器 */\n handlers: ((message: Message) => any)[] = [ ]\n \n print = false\n \n get connected () {\n return this.websocket?.readyState === WebSocket.OPEN\n }\n \n \n static parse <T extends any[] = any[]> (array_buffer: ArrayBuffer) {\n const buf = new Uint8Array(array_buffer as ArrayBuffer)\n const dv = new DataView(array_buffer)\n \n const len_json = dv.getUint32(0, true)\n \n let offset = 4 + len_json\n \n let message: Message<T> = JSON.parse(\n decoder.decode(\n buf.subarray(4, offset)\n )\n )\n \n message.args ||= [ ] as T\n \n if (message.bins) {\n let args = message.args\n \n for (const ibin of message.bins) {\n const len_buf = args[ibin]\n args[ibin] = buf.subarray(offset, offset + len_buf)\n offset += len_buf\n }\n }\n \n return message\n }\n \n \n static pack ({\n id,\n func,\n ignore,\n async: _async,\n done,\n error,\n args: _args = [ ],\n }: Message) {\n let args = [..._args]\n \n let bins: number[] = [ ]\n let bufs: Uint8Array[] = [ ]\n \n for (let i = 0; i < args.length; i++) {\n const arg = args[i]\n if (arg instanceof Uint8Array) {\n bins.push(i)\n bufs.push(arg)\n args[i] = arg.length\n }\n }\n \n const data_json = {\n id,\n ... func ? { func } : { },\n ... ignore ? { ignore } : { },\n ... _async ? { async: _async } : { },\n ... done ? { done } : { },\n ... error ? { error } : { },\n ... args.length ? { args } : { },\n ... bins.length ? { bins } : { },\n }\n \n const str_json = encoder.encode(\n JSON.stringify(data_json)\n )\n \n let dv = new DataView(\n new ArrayBuffer(4)\n )\n \n dv.setUint32(0, str_json.length, true)\n \n return concat([\n dv,\n str_json,\n ... bufs\n ])\n }\n \n \n constructor ({\n url,\n funcs = { },\n websocket,\n }: {\n url?: string\n funcs?: Remote['funcs']\n websocket?: WebSocket\n } = { }) {\n this.url = url\n this.funcs = funcs\n this.websocket = websocket\n }\n \n \n async connect () {\n this.websocket = await connect_websocket(this.url, {\n on_message: this.handle.bind(this)\n })\n }\n \n \n disconnect () {\n this.websocket?.close()\n this.id = 0\n this.handlers = [ ]\n }\n \n \n send (message: Message, websocket = this.websocket) {\n if (!('id' in message))\n message.id = this.id\n \n websocket.send(\n Remote.pack(message)\n )\n }\n \n \n /** 调用 remote 中的 func, 返回结果由 handler 处理,处理 done message 之后的返回值作为 call 函数的返回值 */\n async call <T extends any[] = any[], R = any> (\n message: Message,\n handler: (message: Message<T>) => any\n ) {\n return new Promise<R>((resolve, reject) => {\n this.handlers[this.id] = async (message: Message<T>) => {\n const { error, done } = message\n \n if (error) {\n reject(\n Object.assign(\n new Error(),\n error\n )\n )\n return\n }\n \n let result = await handler(message)\n \n if (done)\n resolve(result)\n }\n \n this.send(message)\n \n this.id++\n })\n }\n \n \n /** 处理接收到的 WebSocket message\n 1. 被调用方接收 message 并开始处理\n 2. 调用方处理 message 响应\n */\n async handle (event: { data: ArrayBuffer }, websocket: WebSocket) {\n const message = Remote.parse(event.data)\n const { func, id, done } = message\n \n if (this.print)\n console.log(message)\n \n if (func) // 作为被调方\n try {\n const handler = this.funcs[func] || this.funcs.default\n \n if (!handler)\n throw new Error(`找不到 rpc handler: ${func}`)\n \n await handler(message, websocket)\n } catch (error) {\n this.send(\n {\n id: message.id,\n error,\n done: true\n },\n websocket\n )\n throw error\n }\n else { // 作为发起方\n this.handlers[id](message)\n if (done)\n this.handlers[id] = null\n }\n }\n}\n\n\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "xshell",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.38",
|
|
4
4
|
"main": "./index.js",
|
|
5
5
|
"bin": {
|
|
6
6
|
"xshell": "./xshell.js",
|
|
@@ -65,8 +65,8 @@
|
|
|
65
65
|
]
|
|
66
66
|
},
|
|
67
67
|
"dependencies": {
|
|
68
|
-
"@babel/core": "^7.17.
|
|
69
|
-
"@babel/parser": "^7.17.
|
|
68
|
+
"@babel/core": "^7.17.8",
|
|
69
|
+
"@babel/parser": "^7.17.8",
|
|
70
70
|
"@babel/traverse": "^7.17.3",
|
|
71
71
|
"@koa/cors": "^3.2.0",
|
|
72
72
|
"byte-size": "^8.1.0",
|
|
@@ -97,7 +97,7 @@
|
|
|
97
97
|
"promise-retry": "^2.0.1",
|
|
98
98
|
"qs": "^6.10.3",
|
|
99
99
|
"react": "^17.0.2",
|
|
100
|
-
"react-i18next": "^11.
|
|
100
|
+
"react-i18next": "^11.16.1",
|
|
101
101
|
"readdir-enhanced": "^6.0.4",
|
|
102
102
|
"request": "^2.88.2",
|
|
103
103
|
"request-promise-native": "^1.0.9",
|
|
@@ -107,7 +107,7 @@
|
|
|
107
107
|
"strip-ansi": "=6.0.0",
|
|
108
108
|
"tough-cookie": "^4.0.0",
|
|
109
109
|
"tslib": "^2.3.1",
|
|
110
|
-
"typescript": "^4.6.
|
|
110
|
+
"typescript": "^4.6.3",
|
|
111
111
|
"upath": "^2.0.1",
|
|
112
112
|
"vinyl": "^2.2.1",
|
|
113
113
|
"vinyl-fs": "^3.0.3",
|
|
@@ -127,10 +127,10 @@
|
|
|
127
127
|
"@types/koa": "^2.13.4",
|
|
128
128
|
"@types/koa-compress": "^4.0.3",
|
|
129
129
|
"@types/lodash": "^4.14.180",
|
|
130
|
-
"@types/node": "^17.0.
|
|
130
|
+
"@types/node": "^17.0.23",
|
|
131
131
|
"@types/promise-retry": "^1.1.3",
|
|
132
132
|
"@types/qs": "^6.9.7",
|
|
133
|
-
"@types/react": "^17.0.
|
|
133
|
+
"@types/react": "^17.0.43",
|
|
134
134
|
"@types/request": "^2.48.8",
|
|
135
135
|
"@types/request-promise-native": "^1.0.18",
|
|
136
136
|
"@types/rimraf": "^3.0.2",
|
package/process.d.ts
CHANGED
|
@@ -14,14 +14,13 @@ interface StartOptions {
|
|
|
14
14
|
encoding?: Encoding;
|
|
15
15
|
/** `true` print option (with details) */
|
|
16
16
|
print?: boolean | {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
code
|
|
21
|
-
error?: boolean;
|
|
17
|
+
stdout: boolean;
|
|
18
|
+
stderr: boolean;
|
|
19
|
+
command: boolean;
|
|
20
|
+
code: boolean;
|
|
22
21
|
};
|
|
23
22
|
/** `'pipe'` when 'ignore' then ignore stdio processing */
|
|
24
|
-
stdio?: 'pipe' | 'ignore';
|
|
23
|
+
stdio?: 'pipe' | 'ignore' | ['pipe' | 'ignore' | 'inherit', 'pipe' | 'ignore' | 'inherit', 'pipe' | 'ignore' | 'inherit'];
|
|
25
24
|
/** `false` whether to break the connection with child (ignore stdio, unref) */
|
|
26
25
|
detached?: boolean;
|
|
27
26
|
}
|
package/process.js
CHANGED
|
@@ -29,7 +29,16 @@ function start(exe, args = [], { cwd = exports.fp_root, encoding = 'utf-8', prin
|
|
|
29
29
|
env: { ...process.env, ...env }
|
|
30
30
|
} : {},
|
|
31
31
|
};
|
|
32
|
-
if (print)
|
|
32
|
+
if (typeof print === 'boolean')
|
|
33
|
+
print = {
|
|
34
|
+
stdout: print,
|
|
35
|
+
stderr: print,
|
|
36
|
+
command: print,
|
|
37
|
+
code: print,
|
|
38
|
+
};
|
|
39
|
+
if (typeof stdio === 'string')
|
|
40
|
+
stdio = [stdio, stdio, stdio];
|
|
41
|
+
if (print.command)
|
|
33
42
|
console.log(`${exe} ${args.map(arg => arg.includes(' ') ? arg.quote() : arg).join(' ')}`.blue);
|
|
34
43
|
if (detached) {
|
|
35
44
|
let child = (0, child_process_1.spawn)(exe, args, {
|
|
@@ -41,48 +50,57 @@ function start(exe, args = [], { cwd = exports.fp_root, encoding = 'utf-8', prin
|
|
|
41
50
|
return child;
|
|
42
51
|
}
|
|
43
52
|
let child = (0, child_process_1.spawn)(exe, args, options);
|
|
44
|
-
|
|
45
|
-
child.stdin.setDefaultEncoding('utf8');
|
|
46
|
-
// prevent child spawn error crashing nodejs process
|
|
53
|
+
// 防止 child spawn 失败时 crash nodejs 进程
|
|
47
54
|
child.on('error', error => {
|
|
48
55
|
console.error(error);
|
|
49
56
|
});
|
|
50
|
-
if (stdio === '
|
|
57
|
+
if (stdio[0] === 'pipe')
|
|
58
|
+
child.stdin.setDefaultEncoding('utf8');
|
|
59
|
+
if (stdio.every(s => s === 'ignore'))
|
|
51
60
|
return child;
|
|
52
61
|
if (encoding !== 'binary') {
|
|
53
|
-
if (
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
62
|
+
if (stdio[1] === 'pipe') {
|
|
63
|
+
if (encoding === 'utf-8')
|
|
64
|
+
child.stdout.setEncoding('utf-8');
|
|
65
|
+
else
|
|
66
|
+
child.stdout = child.stdout.pipe(iconv_lite_1.default.decodeStream(encoding));
|
|
67
|
+
if (print.stdout)
|
|
68
|
+
child.stdout.pipe(process.stdout, { end: false });
|
|
60
69
|
}
|
|
61
|
-
if (
|
|
62
|
-
|
|
63
|
-
|
|
70
|
+
if (stdio[2] === 'pipe') {
|
|
71
|
+
if (encoding === 'utf-8')
|
|
72
|
+
child.stderr.setEncoding('utf-8');
|
|
73
|
+
else
|
|
74
|
+
child.stderr = child.stderr.pipe(iconv_lite_1.default.decodeStream(encoding));
|
|
75
|
+
if (print.stderr)
|
|
76
|
+
child.stderr.pipe(process.stderr, { end: false });
|
|
64
77
|
}
|
|
65
78
|
}
|
|
66
79
|
return child;
|
|
67
80
|
}
|
|
68
81
|
exports.start = start;
|
|
69
82
|
async function call(exe, args = [], options = {}) {
|
|
70
|
-
const { encoding = 'utf-8',
|
|
71
|
-
|
|
72
|
-
|
|
83
|
+
const { encoding = 'utf-8', throw_code = true, input, } = options;
|
|
84
|
+
let { stdio = 'pipe', print = true } = options;
|
|
85
|
+
if (typeof print === 'boolean')
|
|
86
|
+
print = {
|
|
73
87
|
command: print,
|
|
74
88
|
stdout: print,
|
|
75
89
|
stderr: print,
|
|
76
90
|
code: print,
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
91
|
+
};
|
|
92
|
+
if (typeof stdio === 'string')
|
|
93
|
+
stdio = [stdio, stdio, stdio];
|
|
94
|
+
const cmd = (exe.includes(' ') ? exe.quote() : exe) +
|
|
95
|
+
(args.length ? (' ' + args.map(arg => arg.includes(' ') ? arg.quote() : arg).join(' '))
|
|
96
|
+
:
|
|
97
|
+
'');
|
|
98
|
+
if (print.command)
|
|
83
99
|
console.log(cmd.blue);
|
|
84
|
-
|
|
85
|
-
|
|
100
|
+
let child = start(exe, args, {
|
|
101
|
+
...options,
|
|
102
|
+
print: false,
|
|
103
|
+
});
|
|
86
104
|
if (input)
|
|
87
105
|
child.stdin.write(input);
|
|
88
106
|
// --- collect output
|
|
@@ -91,29 +109,31 @@ async function call(exe, args = [], options = {}) {
|
|
|
91
109
|
let code, signal;
|
|
92
110
|
await Promise.all([
|
|
93
111
|
new Promise(resolve => {
|
|
94
|
-
child.
|
|
112
|
+
child.once('exit', (_code, _signal) => {
|
|
95
113
|
code = _code;
|
|
96
114
|
signal = _signal;
|
|
97
115
|
resolve();
|
|
98
116
|
});
|
|
99
117
|
}),
|
|
100
118
|
(async () => {
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
119
|
+
if (stdio[1] === 'pipe')
|
|
120
|
+
for await (const chunk of child.stdout) {
|
|
121
|
+
if (encoding !== 'binary' && print.stdout)
|
|
122
|
+
process.stdout.write(chunk);
|
|
123
|
+
stdouts.push(chunk);
|
|
124
|
+
}
|
|
106
125
|
})(),
|
|
107
126
|
(async () => {
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
127
|
+
if (stdio[2] === 'pipe')
|
|
128
|
+
for await (const chunk of child.stderr) {
|
|
129
|
+
if (encoding !== 'binary' && print.stderr)
|
|
130
|
+
process.stderr.write(chunk);
|
|
131
|
+
stderrs.push(chunk);
|
|
132
|
+
}
|
|
113
133
|
})()
|
|
114
134
|
]);
|
|
115
|
-
const message = `process(${child.pid})
|
|
116
|
-
if (
|
|
135
|
+
const message = `process(${child.pid}) (${cmd}) exited ${code}${signal ? `, by signal ${signal}` : ''}.`;
|
|
136
|
+
if (print.code || code || signal)
|
|
117
137
|
console.log(message[code || signal ? 'red' : 'blue']);
|
|
118
138
|
const result = {
|
|
119
139
|
pid: child.pid,
|
package/process.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"process.js","sourceRoot":"","sources":["process.ts"],"names":[],"mappings":";;;;AAAA,iDAIsB;AAGtB,oEAA8B;AAE9B,0BAAuB;AAEvB,yCAAoC;AAEvB,QAAA,OAAO,GAAG,GAAG,SAAS,GAAG,CAAC,QAAQ,EAAE,CAAA;AAEpC,QAAA,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,QAAQ,EAAE,CAAA;AA8BnD;;;;;;;;;;EAUE;AACF,SAAgB,KAAK,CAAE,GAAW,EAAE,OAAiB,EAAE,EAAE,EACrD,GAAG,GAAG,eAA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M,MAAM,CAAC,MAAM,CACf,IAAI,KAAK,CAAC,OAAO,CAAC,EAClB,MAAM,CACT,CAAA;IAEL,OAAO,MAAM,CAAA;AACjB,CAAC;AAlGD,oBAkGC;AAGD;;;;;;;;;;;EAWE;AACK,KAAK,UAAU,SAAS,CAAE,EAAU,EAAE,OAAiB,EAAE,EAAE,OAA0D;IACxH,OAAO,IAAI,CAAC,gBAAQ,EAAE,CAAC,EAAE,EAAE,GAAG,IAAI,CAAC,EAAE,OAAO,CAAC,CAAA;AACjD,CAAC;AAFD,8BAEC","sourcesContent":["import {\n spawn,\n type SpawnOptions,\n type ChildProcess\n} from 'child_process'\nimport { Readable } from 'stream'\n\nimport iconv from 'iconv-lite'\n\nimport './prototype.js'\nimport { Encoding } from './file.js'\nimport { inspect } from './utils.js'\n\nexport const fp_root = `${__dirname}/`.to_slash()\n\nexport const exe_node = process.execPath.to_slash()\n\n\n// ------------------------------------ start & call\ninterface StartOptions {\n /** `'d:/'` */\n cwd?: string\n \n /** `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 option (with details) */\n print?: boolean | {\n command?: boolean\n stdout?: boolean\n stderr?: boolean\n code?: boolean\n error?: boolean\n }\n \n /** `'pipe'` when 'ignore' then ignore stdio processing */\n stdio?: 'pipe' | 'ignore'\n \n /** `false` whether to break the connection with child (ignore stdio, unref) */\n detached?: boolean\n}\n\n/** start process \n - exe: .exe 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` overwrite/add to process.env\n - encoding?: `'utf-8'` child output encoding\n - print?: `true` print option (with details)\n - stdio?: `'pipe'` when 'ignore' then ignore stdio processing\n - detached?: `false` whether to break the connection with child (ignore stdio, unref)\n*/\nexport function start (exe: string, args: string[] = [], {\n cwd = fp_root,\n \n encoding = 'utf-8',\n \n print = true,\n \n stdio = 'pipe',\n \n detached = false,\n \n env,\n \n}: StartOptions = { }): ChildProcess {\n const options: SpawnOptions = {\n cwd,\n shell: false,\n windowsHide: !detached,\n stdio,\n ... env ? {\n env: { ...process.env, ...env }\n } : { },\n }\n \n if (print)\n console.log(`${exe} ${ args.map(arg => arg.includes(' ') ? arg.quote() : arg).join(' ') }`.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 if (stdio === 'pipe')\n child.stdin.setDefaultEncoding('utf8')\n \n // prevent child spawn error crashing nodejs process\n child.on('error', error => {\n console.error(error)\n })\n \n if (stdio === 'ignore')\n return child\n \n if (encoding !== 'binary') {\n if (encoding === 'utf-8') {\n child.stdout.setEncoding('utf-8')\n child.stderr.setEncoding('utf-8')\n } else {\n child.stdout = child.stdout.pipe(\n iconv.decodeStream(encoding)\n ) as any as Readable\n child.stderr = child.stderr.pipe(\n iconv.decodeStream(encoding)\n ) as any as Readable\n }\n \n if (print) {\n child.stdout.pipe(process.stdout, { end: false })\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<T = string> {\n pid: number\n stdout: T\n stderr: T\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 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` overwrite/add to process.env\n - encoding?: `'utf-8'` child output encoding\n - print?: `true` print option (with details)\n - stdio?: `'pipe'` when 'ignore' then ignore stdio processing\n - input?: string\n - detached?: `false` whether to break the connection with child (ignore stdio, unref)\n - throw_code?: `true` whether to throw Error when code is not 0\n*/\nexport async function call (exe: string, args?: string[]): Promise<CallResult<string>>\nexport async function call (exe: string, args?: string[], options?: CallOptions & { encoding?: 'utf-8' | 'gb18030' }): 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 | Buffer>> {\n const {\n encoding = 'utf-8', \n print = true,\n throw_code = true,\n input\n } = options\n \n const print_options = typeof print === 'boolean' ?\n {\n command: print,\n stdout: print,\n stderr: print,\n code: print,\n error: print\n }\n :\n print\n \n const cmd = `${exe} ${ args.map(arg => arg.includes(' ') ? arg.quote() : arg).join(' ') }`\n \n if (print_options.command)\n console.log(cmd.blue)\n \n options.print = false\n \n let child = start(exe, args, options)\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.on('exit', (_code, _signal) => {\n code = _code\n signal = _signal\n resolve()\n })\n }),\n (async () => {\n for await (const chunk of child.stdout as AsyncIterable<string | Buffer>) {\n if (encoding !== 'binary' && print_options.stdout)\n process.stdout.write(chunk)\n stdouts.push(chunk)\n }\n })(),\n (async () => {\n for await (const chunk of child.stderr as AsyncIterable<string | Buffer>) {\n if (encoding !== 'binary' && print_options.stderr)\n process.stderr.write(chunk)\n stderrs.push(chunk)\n }\n })()\n ])\n \n const message = `process(${ child.pid }) '${ cmd }' exited ${ code }${ signal ? `, by signal ${ signal }` : '' }.`\n \n if (print_options.code || code || signal)\n console.log(message[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 path (relative path will resolve based on cwd)\n - args: `[]` arguments list\n - options\n - cwd?: `'d:/'`\n - env?: `process.env` overwrite/add to process.env\n - encoding?: `'utf-8'` child process output encoding\n - print?: `true` print option (with details)\n - stdio?: `'pipe'` when 'ignore' then ignore stdio processing\n - detached?: `false` whether to break the connection with child (ignore stdio, unref)\n - throw_code?: `true` whether to throw Error when code is not 0\n*/\nexport async function call_node (js: string, args: string[] = [], options?: CallOptions & { encoding?: 'utf-8' | 'gb18030' }) {\n return call(exe_node, [js, ...args], options)\n}\n\n"]}
|
|
1
|
+
{"version":3,"file":"process.js","sourceRoot":"","sources":["process.ts"],"names":[],"mappings":";;;;AAAA,iDAIsB;AAGtB,oEAA8B;AAE9B,0BAAuB;AAEvB,yCAAoC;AAEvB,QAAA,OAAO,GAAG,GAAG,SAAS,GAAG,CAAC,QAAQ,EAAE,CAAA;AAEpC,QAAA,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,QAAQ,EAAE,CAAA;AA6BnD;;;;;;;;;;EAUE;AACF,SAAgB,KAAK,CAAE,GAAW,EAAE,OAAiB,EAAG,EAAE,EACtD,GAAG,GAAG,eAAO,EAEb,QAAQ,GAAG,OAAO,EAElB,KAAK,GAAG,IAAI,EAEZ,KAAK,GAAG,MAAM,EAEd,QAAQ,GAAG,KAAK,EAEhB,GAAG,MACW,EAAG;IACjB,MAAM,OAAO,GAAiB;QAC1B,GAAG;QACH,KAAK,EAAE,KAAK;QACZ,WAAW,EAAE,CAAC,QAAQ;QACtB,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,KAAK;YAC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C;gBACI,OAAoB,CAAC,IAAI,CAAC,EAAE,CAAC;QAElC,MAAM,EAAE,QAAQ,KAAK,QAAQ,CAAC,CAAC;YAC3B,MAAM,CAAC,MAAM,CAAC,OAAmB,CAAC;YACtC,CAAC;gBACI,OAAoB,CAAC,IAAI,CAAC,EAAE,CAAC;QAElC,IAAI;QAEJ,MAAM;QAEN,KAAK;QAEL,CAAC,kBAAO,CAAC,MAAM,CAAC;YACZ,OAAO,IAAA,kBAAO,EAAC,IAAI,EAAE,EAAE,IAAI,EAAE,CAAC,OAAO,CAAC,EAAE,CAAC,CAAA;QAC7C,CAAC;KACJ,CAAA;IAED,IAAI,IAAI,IAAI,UAAU;QAClB,MAAM,MAAM,CAAC,MAAM,CACf,IAAI,KAAK,CAAC,OAAO,CAAC,EAClB,MAAM,CACT,CAAA;IAEL,OAAO,MAAM,CAAA;AACjB,CAAC;AAhHD,oBAgHC;AAGD;;;;;;;;;;;EAWE;AACK,KAAK,UAAU,SAAS,CAAE,EAAU,EAAE,OAAiB,EAAE,EAAE,OAA0D;IACxH,OAAO,IAAI,CAAC,gBAAQ,EAAE,CAAC,EAAE,EAAE,GAAG,IAAI,CAAC,EAAE,OAAO,CAAC,CAAA;AACjD,CAAC;AAFD,8BAEC","sourcesContent":["import {\n spawn,\n type SpawnOptions,\n type ChildProcess\n} from 'child_process'\nimport { Readable } from 'stream'\n\nimport iconv from 'iconv-lite'\n\nimport './prototype.js'\nimport { Encoding } from './file.js'\nimport { inspect } from './utils.js'\n\nexport const fp_root = `${__dirname}/`.to_slash()\n\nexport const exe_node = process.execPath.to_slash()\n\n\n// ------------------------------------ start & call\ninterface StartOptions {\n /** `'d:/'` */\n cwd?: string\n \n /** `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 option (with details) */\n print?: boolean | {\n stdout: boolean\n stderr: boolean\n command: boolean\n code: boolean\n }\n \n /** `'pipe'` when 'ignore' then ignore stdio processing */\n stdio?: 'pipe' | 'ignore' | ['pipe' | 'ignore' | 'inherit', 'pipe' | 'ignore' | 'inherit', 'pipe' | 'ignore' | 'inherit']\n \n /** `false` whether to break the connection with child (ignore stdio, unref) */\n detached?: boolean\n}\n\n/** start process \n - exe: .exe 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` overwrite/add to process.env\n - encoding?: `'utf-8'` child output encoding\n - print?: `true` print option (with details)\n - stdio?: `'pipe'` when 'ignore' then ignore stdio processing\n - detached?: `false` whether to break the connection with child (ignore stdio, unref)\n*/\nexport function start (exe: string, args: string[] = [ ], {\n cwd = fp_root,\n \n encoding = 'utf-8',\n \n print = true,\n \n stdio = 'pipe',\n \n detached = false,\n \n env,\n}: StartOptions = { }): ChildProcess {\n const options: SpawnOptions = {\n cwd,\n shell: false,\n windowsHide: !detached,\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(`${exe} ${ args.map(arg => arg.includes(' ') ? arg.quote() : arg).join(' ') }`.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<T = string> {\n pid: number\n stdout: T\n stderr: T\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 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` overwrite/add to process.env\n - encoding?: `'utf-8'` child output encoding\n - print?: `true` print option (with details)\n - stdio?: `'pipe'` when 'ignore' then ignore stdio processing\n - input?: string\n - detached?: `false` whether to break the connection with child (ignore stdio, unref)\n - throw_code?: `true` whether to throw Error when code is not 0\n*/\nexport async function call (exe: string, args?: string[]): Promise<CallResult<string>>\nexport async function call (exe: string, args?: string[], options?: CallOptions & { encoding?: 'utf-8' | 'gb18030' }): 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 | 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 (exe.includes(' ') ? exe.quote() : exe) + \n (args.length ? (\n ' ' + args.map(arg => \n arg.includes(' ') ? arg.quote() : arg\n ).join(' '))\n :\n '')\n \n if (print.command)\n console.log(cmd.blue)\n \n let child = 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 = `process(${child.pid}) (${cmd}) exited ${code}${ signal ? `, by signal ${ signal }` : '' }.`\n \n if (print.code || code || signal)\n console.log(message[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 path (relative path will resolve based on cwd)\n - args: `[]` arguments list\n - options\n - cwd?: `'d:/'`\n - env?: `process.env` overwrite/add to process.env\n - encoding?: `'utf-8'` child process output encoding\n - print?: `true` print option (with details)\n - stdio?: `'pipe'` when 'ignore' then ignore stdio processing\n - detached?: `false` whether to break the connection with child (ignore stdio, unref)\n - throw_code?: `true` whether to throw Error when code is not 0\n*/\nexport async function call_node (js: string, args: string[] = [], options?: CallOptions & { encoding?: 'utf-8' | 'gb18030' }) {\n return call(exe_node, [js, ...args], options)\n}\n\n"]}
|
package/repl.js
CHANGED
|
@@ -13,6 +13,7 @@ const file_js_1 = require("./file.js");
|
|
|
13
13
|
const process_js_1 = require("./process.js");
|
|
14
14
|
(0, utils_js_1.set_inspect_options)();
|
|
15
15
|
const { factory, SyntaxKind, NodeFlags, ModifierFlags, isIdentifier: is_identifier, isNamedImports: is_named_imports, isImportDeclaration: is_import_decl, isAwaitExpression: is_await_expr, isExpressionStatement: is_expr_stmt, isVariableStatement: is_var_stmt, isNamespaceImport: is_namespace_import, isClassDeclaration: is_class_decl, isCallExpression: is_call_expr, isReturnStatement: is_return_stmt, isBinaryExpression: is_binary_expr, isFunctionDeclaration: is_func_decl, createPrinter: create_printer, } = typescript_1.default;
|
|
16
|
+
let server;
|
|
16
17
|
let inspection_limit = 10000;
|
|
17
18
|
let printing_compiled_js = false;
|
|
18
19
|
function set_inspection_limit(limit = 10000) {
|
|
@@ -300,7 +301,8 @@ async function start_repl() {
|
|
|
300
301
|
(async () => {
|
|
301
302
|
// --- http server
|
|
302
303
|
(0, utils_js_1.log_section)('server is initializing', { color: 'green', time: true });
|
|
303
|
-
let {
|
|
304
|
+
let { Server } = await Promise.resolve().then(() => tslib_1.__importStar(require('./server.js')));
|
|
305
|
+
server = new Server(8421, { rpc: true });
|
|
304
306
|
await server.start();
|
|
305
307
|
(0, utils_js_1.log_section)('server initialized', { color: 'green', time: true });
|
|
306
308
|
})(),
|
|
@@ -313,8 +315,7 @@ async function stop() {
|
|
|
313
315
|
(0, utils_js_1.log_section)('xshell is exiting', { color: 'red' });
|
|
314
316
|
for (const key in file_js_1.fwatchers)
|
|
315
317
|
file_js_1.fwatchers[key].close();
|
|
316
|
-
|
|
317
|
-
.server.stop();
|
|
318
|
+
server.stop();
|
|
318
319
|
}
|
|
319
320
|
exports.stop = stop;
|
|
320
321
|
async function exit() {
|
package/repl.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"repl.js","sourceRoot":"","sources":["repl.ts"],"names":[],"mappings":";;;;AAAA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W,CAAC;QACnC,sBAAsB,CAAC,UAAU,CAAC;QAClC,sBAAsB,CAAC,aAAa,CAAC;QACrC,sBAAsB,CAAC,WAAW,CAAC;KACtC,CAAC,CAAA;IAEF,IAAA,sBAAW,EAAC,yBAAyB,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAA;AAC1E,CAAC;AApCD,wCAoCC;AAGM,KAAK,UAAU,sBAAsB,CAAE,MAAc;IACxD,MAAM,CAAC,MAAM,CACT,MAAM,EACN,gEAAa,MAAM,GAAC,CACvB,CAAA;AACL,CAAC;AALD,wDAKC;AAEM,KAAK,UAAU,6BAA6B,CAAE,MAAc,EAAE,IAAY;IAC7E,MAAM,CAAC,IAAI,CAAC,GAAG,CACX,gEAAa,MAAM,GAAC,CACvB,CAAC,OAAO,CAAA;AACb,CAAC;AAJD,sEAIC;AAGD,SAAS,cAAc,CAAE,EAAU;IAC/B,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAA;AACtC,CAAC","sourcesContent":["import nvm from 'vm'\nimport fs from 'fs'\nimport repl from 'repl'\nimport process from 'process'\n\n\n\nimport {\n default as ts,\n type SourceFile,\n type Node,\n type Statement, \n type Modifier,\n type SyntaxKind as TSyntaxKind,\n type Identifier,\n type StringLiteral,\n type ExpressionStatement,\n type ObjectBindingPattern,\n type BindingElement,\n} from 'typescript'\n\nimport type { Context } from 'koa'\n\n\nimport './prototype.js'\nimport { log_section, log_line, delay, inspect, set_inspect_options } from './utils.js'\nimport { fread, fwrite, fwatchers, create_mfs, set_ufs, UFS } from './file.js'\nimport { fp_root } from './process.js'\n\n\ndeclare global {\n var __: any\n \n var started_at: Date\n \n var repl_router: (ctx: Context) => Promise<boolean>\n}\n\n\n\nset_inspect_options()\n\n\n\n\nconst {\n factory,\n \n SyntaxKind, \n NodeFlags,\n ModifierFlags,\n \n isIdentifier: is_identifier, \n isNamedImports: is_named_imports,\n isImportDeclaration: is_import_decl,\n isAwaitExpression: is_await_expr,\n isExpressionStatement: is_expr_stmt,\n isVariableStatement: is_var_stmt,\n isNamespaceImport: is_namespace_import,\n isClassDeclaration: is_class_decl,\n isCallExpression: is_call_expr,\n isReturnStatement: is_return_stmt,\n isBinaryExpression: is_binary_expr,\n isFunctionDeclaration: is_func_decl,\n \n createPrinter: create_printer,\n} = ts\n\n\nlet inspection_limit = 10000\nlet printing_compiled_js = false\n\nexport function set_inspection_limit (limit: number = 10000) {\n if (limit === -1)\n limit = 50 * 10**4\n inspection_limit = limit\n}\n\n\nexport function set_printing_compiled_js (enabled: boolean) {\n printing_compiled_js = enabled\n}\n\n\n// ------------------------------------ Code Compilers, Transformers\nfunction resolve_kind (kind: TSyntaxKind) {\n if (kind === SyntaxKind.VariableStatement) return 'VariableStatement'\n return SyntaxKind[kind]\n}\n\n\nfunction print_ast (nodes: Node[] | Node, sourceFile: SourceFile) {\n function print_node (node: Node) {\n console.log(`${ resolve_kind(node.kind) }: ${ node.getText(sourceFile) }`)\n }\n if (Array.isArray(nodes))\n nodes.forEach( node => { print_node(node) })\n else\n print_node(nodes)\n}\n\n\nexport function parse_code (code: string) {\n return ts.createSourceFile('repl.ts', code, ts.ScriptTarget.ESNext)\n}\n\n\nexport function generate_code (stmts: Statement[]) {\n return create_printer({ omitTrailingSemicolon: true, removeComments: false, newLine: ts.NewLineKind.LineFeed })\n .printFile(\n factory.updateSourceFile(\n ts.createSourceFile('output.ts', '', ts.ScriptTarget.ESNext),\n stmts\n )\n )\n}\n\n\n\nfunction trans_import_2_require (import_decl: Statement) {\n if (!is_import_decl(import_decl)) return import_decl\n \n const { importClause: import_clause, moduleSpecifier: module_specifier } = import_decl\n \n // require('module_specifier')\n const require_module_stmt = factory.createCallExpression( factory.createIdentifier('require'), [ ], [ module_specifier ])\n \n // aaa, bbb as ccc, default as ddd, ...\n // (import_clause.namedBindings as NamedImports).elements\n \n return [\n // import mod from 'mod'\n // global.mod = __importDefault(require(\"mod\")).default\n ... import_clause.name ? [\n factory.createExpressionStatement( factory.createAssignment(\n factory.createPropertyAccessExpression( factory.createIdentifier('global'), import_clause.name),\n factory.createPropertyAccessExpression( factory.createCallExpression( factory.createIdentifier('__importDefault'), [ ], [ require_module_stmt ]), 'default'),\n )\n ) ] : [ ],\n \n // import * as mod from 'mod'\n // global.mod = __importStar(require(\"mod\"))\n ... import_clause.namedBindings && is_namespace_import(import_clause.namedBindings) ? [\n factory.createExpressionStatement( factory.createAssignment(\n factory.createPropertyAccessExpression( factory.createIdentifier('global'), import_clause.namedBindings.name),\n factory.createCallExpression( factory.createIdentifier('__importStar'), [ ], [ require_module_stmt ])\n ))\n ] : [ ],\n \n \n // import { element2 as element2_, element3 as element3_, other, default as mod2 } from 'mod2'\n ... import_clause.namedBindings && is_named_imports(import_clause.namedBindings) ? [\n // var { element2: element2_, element3 } = __importDefault(require(\"mod\"))\n factory.createVariableStatement([ ], [ factory.createVariableDeclaration(\n factory.createObjectBindingPattern(\n // ImportSpecifier[] -> ObjectBindingPattern.BindingElement[]\n import_clause.namedBindings.elements.map( import_specifier => \n factory.createBindingElement(\n undefined, \n import_specifier.propertyName, \n import_specifier.name, \n import_specifier.propertyName?.text === 'default' ? require_module_stmt : undefined\n ))),\n undefined,\n undefined,\n require_module_stmt\n ) ]),\n \n // Object.assign(global, { element2_, element3 })\n factory.createExpressionStatement( factory.createCallExpression(\n factory.createPropertyAccessExpression( factory.createIdentifier('Object'), 'assign'),\n [ ],\n // ImportSpecifier[] -> ObjectBindingPattern.BindingElement[]\n [ factory.createIdentifier('global'), factory.createObjectLiteralExpression( import_clause.namedBindings.elements.map( import_specifier => factory.createShorthandPropertyAssignment(import_specifier.name) ), false) ]\n )),\n \n factory.createExpressionStatement(\n import_clause.namedBindings.elements.length === 1 ? \n // (a)\n factory.createParenthesizedExpression(import_clause.namedBindings.elements[0].name)\n : // ({ a: xxx, b: xxx })\n factory.createObjectLiteralExpression( import_clause.namedBindings.elements.map( import_specifier => factory.createShorthandPropertyAssignment(import_specifier.name) ), false)\n )\n ] : [ ],\n ]\n}\n\n\n/** export function foo () { } */\nfunction trans_export_stmt (stmt: Statement) {\n if (ts.isExportAssignment(stmt))\n return factory.createExpressionStatement(stmt.expression)\n \n function is_export_modifier (modifier: Modifier) {\n return modifier.flags & ModifierFlags.Export || modifier.flags & ModifierFlags.ExportDefault || modifier.kind === SyntaxKind.ExportKeyword\n }\n \n if (stmt.modifiers?.some( modifier => is_export_modifier(modifier) )) {\n // @ts-ignore\n stmt.modifiers = factory.createNodeArray<Modifier>(\n stmt.modifiers.filter( modifier => !is_export_modifier(modifier) )\n )\n return stmt\n }\n \n return stmt\n}\n\n\nfunction trans_require_2_import (stmt: Statement, source_file: SourceFile) {\n if (!is_var_stmt(stmt)) return stmt\n const { name, initializer: require_call } = stmt.declarationList.declarations[0]\n \n if (!is_call_expr(require_call) || require_call.expression.getText(source_file) !== 'require') return stmt\n \n const modpath = require_call.arguments[0] as StringLiteral\n \n // createNamedImports(createImportSpecifier())\n \n return factory.createImportDeclaration(\n undefined, \n undefined,\n factory.createImportClause(false, name as Identifier, undefined),\n modpath\n )\n}\n\n\n/** const a = 123, b = 234, { c, d: e } = obj */\nfunction trans_variable_decl_2_var (var_decl: Statement) {\n if (!is_var_stmt(var_decl)) return var_decl\n // @ts-ignore\n var_decl.declarationList.flags = NodeFlags.None\n return var_decl\n}\n\n\nfunction trans_class_decl_2_expr (class_decl: Statement) {\n if (!is_class_decl(class_decl)) return class_decl\n \n // stmts like 'export class C { }' were moved 'export modifier' in 'trans_export_stmt'\n \n return factory.createVariableStatement(\n [ ],\n factory.createVariableDeclarationList([\n factory.createVariableDeclaration(\n class_decl.name, \n undefined, \n undefined, \n factory.createClassExpression(undefined, undefined, class_decl.name, undefined, undefined, class_decl.members)\n )\n ]))\n}\n\n\nfunction get_expr_of_stmt (statement: Statement): ExpressionStatement | Statement {\n if (is_expr_stmt(statement))\n return statement\n \n if (is_var_stmt(statement)) {\n const { declarations } = statement.declarationList\n return factory.createExpressionStatement(\n declarations.length === 1 ?\n (() => {\n const { name } = declarations[0]\n if (is_identifier(name)) // const a = c\n return name\n else // const { a, b } = c\n return factory.createObjectLiteralExpression(\n name.elements\n .filter(({ name }: BindingElement) => \n is_identifier(name))\n .map(({ name }: BindingElement) => \n factory.createShorthandPropertyAssignment(name as Identifier))\n )\n })()\n :\n factory.createObjectLiteralExpression(\n declarations.map( var_decl => \n factory.createShorthandPropertyAssignment(var_decl.name as Identifier)),\n true)\n )\n }\n \n if (is_func_decl(statement))\n return factory.createExpressionStatement(statement.name)\n \n return statement\n}\n\nfunction trans_return_2_expr (stmt: Statement): Statement {\n if (!is_return_stmt(stmt)) return stmt\n return factory.createExpressionStatement(stmt.expression)\n}\n\n\nfunction assign_var_decl (var_decl: Statement, destination: string = 'global') {\n if (!is_var_stmt(var_decl))\n return [var_decl]\n \n // VariableDeclaration[] -> ObjectLiteral[]\n // const a = 123, b = 234, { c, d: e } = obj\n const obj_literal =\n factory.createObjectLiteralExpression(\n var_decl.declarationList.declarations.map( declaration => \n is_identifier(declaration.name) ?\n [ factory.createShorthandPropertyAssignment(declaration.name) ]\n : // ObjectBindingPattern\n (declaration.name as ObjectBindingPattern).elements.map( (element: BindingElement) => factory.createShorthandPropertyAssignment(element.name as Identifier))\n ).flat()\n , true\n )\n \n \n return [\n var_decl,\n factory.createExpressionStatement( factory.createCallExpression(\n factory.createPropertyAccessExpression( factory.createIdentifier('Object'), 'assign'),\n [ ],\n [ factory.createIdentifier(destination), obj_literal ]\n )),\n factory.createExpressionStatement(obj_literal)\n ]\n}\n\n\nfunction return_last_expr (statements: Statement[]) {\n if (!statements.length) return statements\n \n const last_expr = get_expr_of_stmt(statements.last)\n if (is_expr_stmt(last_expr))\n return [ ...statements.slice(0, -1), factory.createReturnStatement(last_expr.expression) ]\n else\n return statements\n}\n\n\nfunction wrap_await_stmt (statements: Statement[], code: string) {\n function wrap (stmts: Statement[]) {\n return [\n factory.createExpressionStatement(\n factory.createCallExpression(\n factory.createFunctionExpression(\n [ factory.createModifier(SyntaxKind.AsyncKeyword) ],\n undefined,\n 'async_wrapper',\n [ ],\n [ ],\n undefined,\n factory.createBlock(\n return_last_expr(\n stmts.map(statement => assign_var_decl(statement)).flat()\n )\n , true)\n ),\n [ ],\n [ ]\n )\n ),\n ]\n }\n \n if (!code.includes('await')) return statements\n \n if (code.includes('await') && !code.includes('async ')) return wrap(statements)\n \n if (statements.some( stmt => (\n is_expr_stmt(stmt) && is_await_expr(stmt.expression) ||\n is_var_stmt(stmt) && stmt.declarationList.declarations.some( var_decl => \n var_decl.initializer && is_await_expr(var_decl.initializer)\n ) ||\n is_expr_stmt(stmt) && is_call_expr(stmt.expression) && stmt.expression.arguments.some( expr => is_await_expr(expr)) ||\n is_expr_stmt(stmt) && is_binary_expr(stmt.expression) && is_await_expr(stmt.expression.right)\n )))\n return wrap(statements)\n \n return statements\n}\n\n\nexport async function compile_ts ({\n fp, \n code, \n print = printing_compiled_js, \n save = false,\n}: {\n fp?: string\n code?: string\n print?: boolean\n save?: boolean\n} = { }): Promise<string> {\n if (!code && fp)\n code = await fread(fp)\n \n const source_file = parse_code(code)\n \n let statements: Statement[] = [...source_file.statements]\n statements = statements.map(trans_import_2_require).flat()\n statements = statements.map(trans_export_stmt)\n statements = statements.map(trans_class_decl_2_expr)\n statements = wrap_await_stmt(statements, code)\n statements = statements.map(trans_variable_decl_2_var)\n statements = statements.map(trans_return_2_expr)\n \n if (statements.length) {\n const last_stmt = statements[statements.length - 1]\n const last_expr = get_expr_of_stmt(last_stmt)\n if (last_expr !== last_stmt)\n statements = [...statements, last_expr]\n }\n \n \n code = generate_code(statements)\n \n let { diagnostics, outputText: output_text } = ts.transpileModule(code, { compilerOptions: ts_options_commonjs_repl })\n \n if (diagnostics.length) {\n console.log(diagnostics.join('\\n\\n\\n'))\n log_line()\n }\n \n if (print) {\n console.log(output_text)\n log_line()\n }\n \n if (fp && save)\n await fwrite(fp.replace(/\\.ts(x?)$/, '.js$1'), output_text)\n \n return output_text\n}\n\n\n/** tsconfig.compilerOptions */\nexport let ts_options: any\nexport let ts_options_commonjs: any\nexport let ts_options_commonjs_repl: any\n\nexport async function load_tsconfig () {\n const fp = `${fp_root}tsconfig.json`\n ;({ config: { compilerOptions: ts_options } } = ts.parseConfigFileTextToJson(\n fp, \n await fread(fp, { print: false })\n ))\n \n ts_options_commonjs = {\n ...ts_options,\n \n module: 'CommonJS',\n incremental: false,\n \n // determine CommonJS module require method\n esModuleInterop: true,\n }\n \n ts_options_commonjs_repl = {\n ...ts_options,\n \n module: 'CommonJS',\n esModuleInterop: true,\n \n // nvm.runInThisContext doesn't support inline source map\n sourceMap: false,\n }\n}\n\n\nlet eval_id = 0\n\nexport async function eval_ts (code: string) {\n try {\n const js = await compile_ts({ code })\n global.__ = await nvm.runInThisContext(js, `repl/${eval_id++}.ts`)\n \n return global.__\n } catch (error) {\n console.error(error)\n return error\n }\n}\n\n\n// ------------------------------------ repl\nexport async function repl_code (type: 'ts', ...args: any[]) {\n log_line()\n \n // --- run code\n const __ = global.__ = await eval_ts(...(args as [string]))\n \n log_line()\n \n console.log(\n inspect(__, { limit: inspection_limit })\n )\n \n console.log('\\n\\n')\n \n return __\n}\n\n\nexport async function start_repl () {\n // ------------ load library\n log_section('xshell is booting ...', { time: true })\n \n log_mod_loaded('prototype')\n log_mod_loaded('utils')\n log_mod_loaded('file')\n \n const mfs = create_mfs()\n set_ufs(\n new UFS([mfs, fs])\n )\n log_mod_loaded('ufs')\n \n log_mod_loaded('process')\n log_mod_loaded('net')\n \n // --- prevent from exiting\n process.on('uncaughtException', error => {\n console.error(error)\n })\n \n // --- start nodejs repl\n repl.start({\n prompt: '',\n replMode: repl.REPL_MODE_SLOPPY,\n useGlobal: true,\n useColors: true,\n terminal: true,\n })\n \n log_section('repl initialized', { color: 'yellow', time: true })\n \n process.title = 'xshell'\n \n await Promise.all([\n pollute_global(),\n \n load_tsconfig(),\n \n (async () => {\n // --- http server\n log_section('server is initializing', { color: 'green', time: true })\n let { server } = await import('./server.js')\n await server.start()\n log_section('server initialized', { color: 'green', time: true })\n })(),\n ])\n \n log_section('xshell booted successfully', { color: 'red', time: true })\n console.log('xshell is listening at http://0.0.0.0:8421'.green)\n}\n\n\nexport async function stop () {\n log_section('xshell is exiting', { color: 'red' })\n \n for (const key in fwatchers)\n fwatchers[key].close()\n \n ;(await import('./server.js'))\n .server.stop()\n}\n\nexport async function exit () {\n await stop()\n await delay(100)\n process.exit()\n}\n\n\nexport async function pollute_global () {\n Object.assign(global, {\n __importDefault: (mod: any) => ((mod?.__esModule) ? mod : { default: mod }),\n __importStar: (mod: any) => {\n if (mod?.__esModule) return mod\n let result: { default?: any } = { }\n if (mod != null)\n for (let k in mod)\n if (Object.hasOwnProperty.call(mod, k))\n result[k] = mod[k]\n result.default = mod\n return result\n },\n exports: global\n })\n \n await Promise.all([\n pollute_module_default_export('upath', 'path'),\n pollute_module_default_export('cheerio', 'cheerio'),\n \n pollute_module_default_export('lodash/omit.js', 'omit'),\n pollute_module_default_export('lodash/sortBy.js', 'sort_by'),\n pollute_module_default_export('lodash/groupBy.js', 'group_by'),\n \n pollute_module_default_export('qs', 'qs'),\n \n pollute_module_exports('./prototype.js'),\n pollute_module_exports('./utils.js'),\n pollute_module_exports('./process.js'),\n pollute_module_exports('./file.js'),\n pollute_module_exports('./net.js'),\n pollute_module_exports('./server.js'),\n pollute_module_exports('./repl.js'),\n ])\n \n log_section('all modules were loaded', { color: 'green', time: true })\n}\n\n\nexport async function pollute_module_exports (fp_mod: string) {\n Object.assign(\n global,\n await import(fp_mod)\n )\n}\n\nexport async function pollute_module_default_export (fp_mod: string, name: string) {\n global[name] = (\n await import(fp_mod)\n ).default\n}\n\n\nfunction log_mod_loaded (id: string) {\n console.log(`${id.pad(40)}loaded`)\n}\n\n"]}
|
|
1
|
+
{"version":3,"file":"repl.js","sourceRoot":"","sources":["repl.ts"],"names":[],"mappings":";;;;AAAA,oDAAoB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,YAAY,CAAC;QACpC,sBAAsB,CAAC,cAAc,CAAC;QACtC,sBAAsB,CAAC,WAAW,CAAC;QACnC,sBAAsB,CAAC,UAAU,CAAC;QAClC,sBAAsB,CAAC,aAAa,CAAC;QACrC,sBAAsB,CAAC,WAAW,CAAC;KACtC,CAAC,CAAA;IAEF,IAAA,sBAAW,EAAC,yBAAyB,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAA;AAC1E,CAAC;AApCD,wCAoCC;AAGM,KAAK,UAAU,sBAAsB,CAAE,MAAc;IACxD,MAAM,CAAC,MAAM,CACT,MAAM,EACN,gEAAa,MAAM,GAAC,CACvB,CAAA;AACL,CAAC;AALD,wDAKC;AAEM,KAAK,UAAU,6BAA6B,CAAE,MAAc,EAAE,IAAY;IAC7E,MAAM,CAAC,IAAI,CAAC,GAAG,CACX,gEAAa,MAAM,GAAC,CACvB,CAAC,OAAO,CAAA;AACb,CAAC;AAJD,sEAIC;AAGD,SAAS,cAAc,CAAE,EAAU;IAC/B,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAA;AACtC,CAAC","sourcesContent":["import nvm from 'vm'\nimport fs from 'fs'\nimport repl from 'repl'\nimport process from 'process'\n\n\n\nimport {\n default as ts,\n type SourceFile,\n type Node,\n type Statement, \n type Modifier,\n type SyntaxKind as TSyntaxKind,\n type Identifier,\n type StringLiteral,\n type ExpressionStatement,\n type ObjectBindingPattern,\n type BindingElement,\n} from 'typescript'\n\nimport type { Context } from 'koa'\n\n\nimport './prototype.js'\nimport { log_section, log_line, delay, inspect, set_inspect_options } from './utils.js'\nimport { fread, fwrite, fwatchers, create_mfs, set_ufs, UFS } from './file.js'\nimport { fp_root } from './process.js'\n\n\ndeclare global {\n var __: any\n \n var started_at: Date\n \n var repl_router: (ctx: Context) => Promise<boolean>\n}\n\n\n\nset_inspect_options()\n\n\n\n\nconst {\n factory,\n \n SyntaxKind, \n NodeFlags,\n ModifierFlags,\n \n isIdentifier: is_identifier, \n isNamedImports: is_named_imports,\n isImportDeclaration: is_import_decl,\n isAwaitExpression: is_await_expr,\n isExpressionStatement: is_expr_stmt,\n isVariableStatement: is_var_stmt,\n isNamespaceImport: is_namespace_import,\n isClassDeclaration: is_class_decl,\n isCallExpression: is_call_expr,\n isReturnStatement: is_return_stmt,\n isBinaryExpression: is_binary_expr,\n isFunctionDeclaration: is_func_decl,\n \n createPrinter: create_printer,\n} = ts\n\n\nlet server: import('./server').Server\n\nlet inspection_limit = 10000\nlet printing_compiled_js = false\n\nexport function set_inspection_limit (limit: number = 10000) {\n if (limit === -1)\n limit = 50 * 10**4\n inspection_limit = limit\n}\n\n\nexport function set_printing_compiled_js (enabled: boolean) {\n printing_compiled_js = enabled\n}\n\n\n// ------------------------------------ Code Compilers, Transformers\nfunction resolve_kind (kind: TSyntaxKind) {\n if (kind === SyntaxKind.VariableStatement) return 'VariableStatement'\n return SyntaxKind[kind]\n}\n\n\nfunction print_ast (nodes: Node[] | Node, sourceFile: SourceFile) {\n function print_node (node: Node) {\n console.log(`${ resolve_kind(node.kind) }: ${ node.getText(sourceFile) }`)\n }\n if (Array.isArray(nodes))\n nodes.forEach( node => { print_node(node) })\n else\n print_node(nodes)\n}\n\n\nexport function parse_code (code: string) {\n return ts.createSourceFile('repl.ts', code, ts.ScriptTarget.ESNext)\n}\n\n\nexport function generate_code (stmts: Statement[]) {\n return create_printer({ omitTrailingSemicolon: true, removeComments: false, newLine: ts.NewLineKind.LineFeed })\n .printFile(\n factory.updateSourceFile(\n ts.createSourceFile('output.ts', '', ts.ScriptTarget.ESNext),\n stmts\n )\n )\n}\n\n\n\nfunction trans_import_2_require (import_decl: Statement) {\n if (!is_import_decl(import_decl)) return import_decl\n \n const { importClause: import_clause, moduleSpecifier: module_specifier } = import_decl\n \n // require('module_specifier')\n const require_module_stmt = factory.createCallExpression( factory.createIdentifier('require'), [ ], [ module_specifier ])\n \n // aaa, bbb as ccc, default as ddd, ...\n // (import_clause.namedBindings as NamedImports).elements\n \n return [\n // import mod from 'mod'\n // global.mod = __importDefault(require(\"mod\")).default\n ... import_clause.name ? [\n factory.createExpressionStatement( factory.createAssignment(\n factory.createPropertyAccessExpression( factory.createIdentifier('global'), import_clause.name),\n factory.createPropertyAccessExpression( factory.createCallExpression( factory.createIdentifier('__importDefault'), [ ], [ require_module_stmt ]), 'default'),\n )\n ) ] : [ ],\n \n // import * as mod from 'mod'\n // global.mod = __importStar(require(\"mod\"))\n ... import_clause.namedBindings && is_namespace_import(import_clause.namedBindings) ? [\n factory.createExpressionStatement( factory.createAssignment(\n factory.createPropertyAccessExpression( factory.createIdentifier('global'), import_clause.namedBindings.name),\n factory.createCallExpression( factory.createIdentifier('__importStar'), [ ], [ require_module_stmt ])\n ))\n ] : [ ],\n \n \n // import { element2 as element2_, element3 as element3_, other, default as mod2 } from 'mod2'\n ... import_clause.namedBindings && is_named_imports(import_clause.namedBindings) ? [\n // var { element2: element2_, element3 } = __importDefault(require(\"mod\"))\n factory.createVariableStatement([ ], [ factory.createVariableDeclaration(\n factory.createObjectBindingPattern(\n // ImportSpecifier[] -> ObjectBindingPattern.BindingElement[]\n import_clause.namedBindings.elements.map( import_specifier => \n factory.createBindingElement(\n undefined, \n import_specifier.propertyName, \n import_specifier.name, \n import_specifier.propertyName?.text === 'default' ? require_module_stmt : undefined\n ))),\n undefined,\n undefined,\n require_module_stmt\n ) ]),\n \n // Object.assign(global, { element2_, element3 })\n factory.createExpressionStatement( factory.createCallExpression(\n factory.createPropertyAccessExpression( factory.createIdentifier('Object'), 'assign'),\n [ ],\n // ImportSpecifier[] -> ObjectBindingPattern.BindingElement[]\n [ factory.createIdentifier('global'), factory.createObjectLiteralExpression( import_clause.namedBindings.elements.map( import_specifier => factory.createShorthandPropertyAssignment(import_specifier.name) ), false) ]\n )),\n \n factory.createExpressionStatement(\n import_clause.namedBindings.elements.length === 1 ? \n // (a)\n factory.createParenthesizedExpression(import_clause.namedBindings.elements[0].name)\n : // ({ a: xxx, b: xxx })\n factory.createObjectLiteralExpression( import_clause.namedBindings.elements.map( import_specifier => factory.createShorthandPropertyAssignment(import_specifier.name) ), false)\n )\n ] : [ ],\n ]\n}\n\n\n/** export function foo () { } */\nfunction trans_export_stmt (stmt: Statement) {\n if (ts.isExportAssignment(stmt))\n return factory.createExpressionStatement(stmt.expression)\n \n function is_export_modifier (modifier: Modifier) {\n return modifier.flags & ModifierFlags.Export || modifier.flags & ModifierFlags.ExportDefault || modifier.kind === SyntaxKind.ExportKeyword\n }\n \n if (stmt.modifiers?.some( modifier => is_export_modifier(modifier) )) {\n // @ts-ignore\n stmt.modifiers = factory.createNodeArray<Modifier>(\n stmt.modifiers.filter( modifier => !is_export_modifier(modifier) )\n )\n return stmt\n }\n \n return stmt\n}\n\n\nfunction trans_require_2_import (stmt: Statement, source_file: SourceFile) {\n if (!is_var_stmt(stmt)) return stmt\n const { name, initializer: require_call } = stmt.declarationList.declarations[0]\n \n if (!is_call_expr(require_call) || require_call.expression.getText(source_file) !== 'require') return stmt\n \n const modpath = require_call.arguments[0] as StringLiteral\n \n // createNamedImports(createImportSpecifier())\n \n return factory.createImportDeclaration(\n undefined, \n undefined,\n factory.createImportClause(false, name as Identifier, undefined),\n modpath\n )\n}\n\n\n/** const a = 123, b = 234, { c, d: e } = obj */\nfunction trans_variable_decl_2_var (var_decl: Statement) {\n if (!is_var_stmt(var_decl)) return var_decl\n // @ts-ignore\n var_decl.declarationList.flags = NodeFlags.None\n return var_decl\n}\n\n\nfunction trans_class_decl_2_expr (class_decl: Statement) {\n if (!is_class_decl(class_decl)) return class_decl\n \n // stmts like 'export class C { }' were moved 'export modifier' in 'trans_export_stmt'\n \n return factory.createVariableStatement(\n [ ],\n factory.createVariableDeclarationList([\n factory.createVariableDeclaration(\n class_decl.name, \n undefined, \n undefined, \n factory.createClassExpression(undefined, undefined, class_decl.name, undefined, undefined, class_decl.members)\n )\n ]))\n}\n\n\nfunction get_expr_of_stmt (statement: Statement): ExpressionStatement | Statement {\n if (is_expr_stmt(statement))\n return statement\n \n if (is_var_stmt(statement)) {\n const { declarations } = statement.declarationList\n return factory.createExpressionStatement(\n declarations.length === 1 ?\n (() => {\n const { name } = declarations[0]\n if (is_identifier(name)) // const a = c\n return name\n else // const { a, b } = c\n return factory.createObjectLiteralExpression(\n name.elements\n .filter(({ name }: BindingElement) => \n is_identifier(name))\n .map(({ name }: BindingElement) => \n factory.createShorthandPropertyAssignment(name as Identifier))\n )\n })()\n :\n factory.createObjectLiteralExpression(\n declarations.map( var_decl => \n factory.createShorthandPropertyAssignment(var_decl.name as Identifier)),\n true)\n )\n }\n \n if (is_func_decl(statement))\n return factory.createExpressionStatement(statement.name)\n \n return statement\n}\n\nfunction trans_return_2_expr (stmt: Statement): Statement {\n if (!is_return_stmt(stmt)) return stmt\n return factory.createExpressionStatement(stmt.expression)\n}\n\n\nfunction assign_var_decl (var_decl: Statement, destination: string = 'global') {\n if (!is_var_stmt(var_decl))\n return [var_decl]\n \n // VariableDeclaration[] -> ObjectLiteral[]\n // const a = 123, b = 234, { c, d: e } = obj\n const obj_literal =\n factory.createObjectLiteralExpression(\n var_decl.declarationList.declarations.map( declaration => \n is_identifier(declaration.name) ?\n [ factory.createShorthandPropertyAssignment(declaration.name) ]\n : // ObjectBindingPattern\n (declaration.name as ObjectBindingPattern).elements.map( (element: BindingElement) => factory.createShorthandPropertyAssignment(element.name as Identifier))\n ).flat()\n , true\n )\n \n \n return [\n var_decl,\n factory.createExpressionStatement( factory.createCallExpression(\n factory.createPropertyAccessExpression( factory.createIdentifier('Object'), 'assign'),\n [ ],\n [ factory.createIdentifier(destination), obj_literal ]\n )),\n factory.createExpressionStatement(obj_literal)\n ]\n}\n\n\nfunction return_last_expr (statements: Statement[]) {\n if (!statements.length) return statements\n \n const last_expr = get_expr_of_stmt(statements.last)\n if (is_expr_stmt(last_expr))\n return [ ...statements.slice(0, -1), factory.createReturnStatement(last_expr.expression) ]\n else\n return statements\n}\n\n\nfunction wrap_await_stmt (statements: Statement[], code: string) {\n function wrap (stmts: Statement[]) {\n return [\n factory.createExpressionStatement(\n factory.createCallExpression(\n factory.createFunctionExpression(\n [ factory.createModifier(SyntaxKind.AsyncKeyword) ],\n undefined,\n 'async_wrapper',\n [ ],\n [ ],\n undefined,\n factory.createBlock(\n return_last_expr(\n stmts.map(statement => assign_var_decl(statement)).flat()\n )\n , true)\n ),\n [ ],\n [ ]\n )\n ),\n ]\n }\n \n if (!code.includes('await')) return statements\n \n if (code.includes('await') && !code.includes('async ')) return wrap(statements)\n \n if (statements.some( stmt => (\n is_expr_stmt(stmt) && is_await_expr(stmt.expression) ||\n is_var_stmt(stmt) && stmt.declarationList.declarations.some( var_decl => \n var_decl.initializer && is_await_expr(var_decl.initializer)\n ) ||\n is_expr_stmt(stmt) && is_call_expr(stmt.expression) && stmt.expression.arguments.some( expr => is_await_expr(expr)) ||\n is_expr_stmt(stmt) && is_binary_expr(stmt.expression) && is_await_expr(stmt.expression.right)\n )))\n return wrap(statements)\n \n return statements\n}\n\n\nexport async function compile_ts ({\n fp, \n code, \n print = printing_compiled_js, \n save = false,\n}: {\n fp?: string\n code?: string\n print?: boolean\n save?: boolean\n} = { }): Promise<string> {\n if (!code && fp)\n code = await fread(fp)\n \n const source_file = parse_code(code)\n \n let statements: Statement[] = [...source_file.statements]\n statements = statements.map(trans_import_2_require).flat()\n statements = statements.map(trans_export_stmt)\n statements = statements.map(trans_class_decl_2_expr)\n statements = wrap_await_stmt(statements, code)\n statements = statements.map(trans_variable_decl_2_var)\n statements = statements.map(trans_return_2_expr)\n \n if (statements.length) {\n const last_stmt = statements[statements.length - 1]\n const last_expr = get_expr_of_stmt(last_stmt)\n if (last_expr !== last_stmt)\n statements = [...statements, last_expr]\n }\n \n \n code = generate_code(statements)\n \n let { diagnostics, outputText: output_text } = ts.transpileModule(code, { compilerOptions: ts_options_commonjs_repl })\n \n if (diagnostics.length) {\n console.log(diagnostics.join('\\n\\n\\n'))\n log_line()\n }\n \n if (print) {\n console.log(output_text)\n log_line()\n }\n \n if (fp && save)\n await fwrite(fp.replace(/\\.ts(x?)$/, '.js$1'), output_text)\n \n return output_text\n}\n\n\n/** tsconfig.compilerOptions */\nexport let ts_options: any\nexport let ts_options_commonjs: any\nexport let ts_options_commonjs_repl: any\n\nexport async function load_tsconfig () {\n const fp = `${fp_root}tsconfig.json`\n ;({ config: { compilerOptions: ts_options } } = ts.parseConfigFileTextToJson(\n fp, \n await fread(fp, { print: false })\n ))\n \n ts_options_commonjs = {\n ...ts_options,\n \n module: 'CommonJS',\n incremental: false,\n \n // determine CommonJS module require method\n esModuleInterop: true,\n }\n \n ts_options_commonjs_repl = {\n ...ts_options,\n \n module: 'CommonJS',\n esModuleInterop: true,\n \n // nvm.runInThisContext doesn't support inline source map\n sourceMap: false,\n }\n}\n\n\nlet eval_id = 0\n\nexport async function eval_ts (code: string) {\n try {\n const js = await compile_ts({ code })\n global.__ = await nvm.runInThisContext(js, `repl/${eval_id++}.ts`)\n \n return global.__\n } catch (error) {\n console.error(error)\n return error\n }\n}\n\n\n// ------------------------------------ repl\nexport async function repl_code (type: 'ts', ...args: any[]) {\n log_line()\n \n // --- run code\n const __ = global.__ = await eval_ts(...(args as [string]))\n \n log_line()\n \n console.log(\n inspect(__, { limit: inspection_limit })\n )\n \n console.log('\\n\\n')\n \n return __\n}\n\n\nexport async function start_repl () {\n // ------------ load library\n log_section('xshell is booting ...', { time: true })\n \n log_mod_loaded('prototype')\n log_mod_loaded('utils')\n log_mod_loaded('file')\n \n const mfs = create_mfs()\n set_ufs(\n new UFS([mfs, fs])\n )\n log_mod_loaded('ufs')\n \n log_mod_loaded('process')\n log_mod_loaded('net')\n \n // --- prevent from exiting\n process.on('uncaughtException', error => {\n console.error(error)\n })\n \n // --- start nodejs repl\n repl.start({\n prompt: '',\n replMode: repl.REPL_MODE_SLOPPY,\n useGlobal: true,\n useColors: true,\n terminal: true,\n })\n \n log_section('repl initialized', { color: 'yellow', time: true })\n \n process.title = 'xshell'\n \n await Promise.all([\n pollute_global(),\n \n load_tsconfig(),\n \n (async () => {\n // --- http server\n log_section('server is initializing', { color: 'green', time: true })\n let { Server } = await import('./server.js')\n server = new Server(8421, { rpc: true })\n await server.start()\n log_section('server initialized', { color: 'green', time: true })\n })(),\n ])\n \n log_section('xshell booted successfully', { color: 'red', time: true })\n console.log('xshell is listening at http://0.0.0.0:8421'.green)\n}\n\n\nexport async function stop () {\n log_section('xshell is exiting', { color: 'red' })\n \n for (const key in fwatchers)\n fwatchers[key].close()\n \n server.stop()\n}\n\nexport async function exit () {\n await stop()\n await delay(100)\n process.exit()\n}\n\n\nexport async function pollute_global () {\n Object.assign(global, {\n __importDefault: (mod: any) => ((mod?.__esModule) ? mod : { default: mod }),\n __importStar: (mod: any) => {\n if (mod?.__esModule) return mod\n let result: { default?: any } = { }\n if (mod != null)\n for (let k in mod)\n if (Object.hasOwnProperty.call(mod, k))\n result[k] = mod[k]\n result.default = mod\n return result\n },\n exports: global\n })\n \n await Promise.all([\n pollute_module_default_export('upath', 'path'),\n pollute_module_default_export('cheerio', 'cheerio'),\n \n pollute_module_default_export('lodash/omit.js', 'omit'),\n pollute_module_default_export('lodash/sortBy.js', 'sort_by'),\n pollute_module_default_export('lodash/groupBy.js', 'group_by'),\n \n pollute_module_default_export('qs', 'qs'),\n \n pollute_module_exports('./prototype.js'),\n pollute_module_exports('./utils.js'),\n pollute_module_exports('./process.js'),\n pollute_module_exports('./file.js'),\n pollute_module_exports('./net.js'),\n pollute_module_exports('./server.js'),\n pollute_module_exports('./repl.js'),\n ])\n \n log_section('all modules were loaded', { color: 'green', time: true })\n}\n\n\nexport async function pollute_module_exports (fp_mod: string) {\n Object.assign(\n global,\n await import(fp_mod)\n )\n}\n\nexport async function pollute_module_default_export (fp_mod: string, name: string) {\n global[name] = (\n await import(fp_mod)\n ).default\n}\n\n\nfunction log_mod_loaded (id: string) {\n console.log(`${id.pad(40)}loaded`)\n}\n\n"]}
|
package/server.d.ts
CHANGED
|
@@ -26,10 +26,15 @@ declare module 'http' {
|
|
|
26
26
|
body?: Buffer;
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
|
-
export declare
|
|
30
|
-
app: Koa
|
|
31
|
-
handler:
|
|
32
|
-
|
|
29
|
+
export declare class Server {
|
|
30
|
+
app: Koa;
|
|
31
|
+
handler: ReturnType<Koa['callback']>;
|
|
32
|
+
port: number;
|
|
33
|
+
server_http: HttpServer;
|
|
34
|
+
enable_rpc: boolean;
|
|
35
|
+
constructor(port: number, { rpc }: {
|
|
36
|
+
rpc?: boolean;
|
|
37
|
+
});
|
|
33
38
|
/** start http server and listen */
|
|
34
39
|
start(): Promise<void>;
|
|
35
40
|
stop(): void;
|
|
@@ -39,7 +44,8 @@ export declare const server: {
|
|
|
39
44
|
process request.ip
|
|
40
45
|
*/
|
|
41
46
|
parse(ctx: Context): Promise<void>;
|
|
42
|
-
|
|
47
|
+
_router(ctx: Context, next: Next): Promise<void>;
|
|
48
|
+
router(ctx: Context): Promise<boolean>;
|
|
43
49
|
/** args are array http://localhost/repl/rpc?func=to_json&args=aaa&args=bbb
|
|
44
50
|
should use POST when arg is number, otherwise type will be string
|
|
45
51
|
queries:
|
|
@@ -63,6 +69,4 @@ export declare const server: {
|
|
|
63
69
|
/** `false` */
|
|
64
70
|
absolute?: boolean;
|
|
65
71
|
}): Promise<string>;
|
|
66
|
-
}
|
|
67
|
-
export default server;
|
|
68
|
-
export declare type Server = typeof server;
|
|
72
|
+
}
|
package/server.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.
|
|
3
|
+
exports.Server = void 0;
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
5
|
const http_1 = require("http");
|
|
6
6
|
const zlib_1 = tslib_1.__importDefault(require("zlib"));
|
|
@@ -19,10 +19,11 @@ const koa_useragent_1 = require("koa-useragent");
|
|
|
19
19
|
const utils_js_1 = require("./utils.js");
|
|
20
20
|
const file_js_1 = require("./file.js");
|
|
21
21
|
// ------------ my server
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
22
|
+
class Server {
|
|
23
|
+
constructor(port, { rpc = false }) {
|
|
24
|
+
this.port = port;
|
|
25
|
+
this.enable_rpc = rpc;
|
|
26
|
+
}
|
|
26
27
|
/** start http server and listen */
|
|
27
28
|
async start() {
|
|
28
29
|
// --- init koa app
|
|
@@ -44,17 +45,17 @@ exports.server = {
|
|
|
44
45
|
}));
|
|
45
46
|
app.use((0, cors_1.default)({ credentials: true }));
|
|
46
47
|
app.use(koa_useragent_1.userAgent);
|
|
47
|
-
app.use(this.
|
|
48
|
+
app.use(this._router.bind(this));
|
|
48
49
|
this.app = app;
|
|
49
50
|
this.handler = this.app.callback();
|
|
50
|
-
this.
|
|
51
|
+
this.server_http = (0, http_1.createServer)(this.handler);
|
|
51
52
|
await new Promise(resolve => {
|
|
52
|
-
this.
|
|
53
|
+
this.server_http.listen(this.port, resolve);
|
|
53
54
|
});
|
|
54
|
-
}
|
|
55
|
+
}
|
|
55
56
|
stop() {
|
|
56
|
-
this.
|
|
57
|
-
}
|
|
57
|
+
this.server_http.close();
|
|
58
|
+
}
|
|
58
59
|
async entry(ctx, next) {
|
|
59
60
|
let { response } = ctx;
|
|
60
61
|
await this.parse(ctx);
|
|
@@ -69,7 +70,7 @@ exports.server = {
|
|
|
69
70
|
response.body = (0, utils_js_1.inspect)(error, { colors: false });
|
|
70
71
|
response.type = 'text/plain';
|
|
71
72
|
}
|
|
72
|
-
}
|
|
73
|
+
}
|
|
73
74
|
/**
|
|
74
75
|
parse req.body to request.body
|
|
75
76
|
process request.ip
|
|
@@ -95,8 +96,8 @@ exports.server = {
|
|
|
95
96
|
}
|
|
96
97
|
else
|
|
97
98
|
request.body = req.body;
|
|
98
|
-
}
|
|
99
|
-
async
|
|
99
|
+
}
|
|
100
|
+
async _router(ctx, next) {
|
|
100
101
|
let { request } = ctx;
|
|
101
102
|
const _path = request._path = decodeURIComponent(request.path);
|
|
102
103
|
Object.defineProperty(request, 'path', {
|
|
@@ -107,7 +108,7 @@ exports.server = {
|
|
|
107
108
|
});
|
|
108
109
|
const { path } = request;
|
|
109
110
|
// ------------ /repl/rpc
|
|
110
|
-
if (path === '/api/rpc') {
|
|
111
|
+
if (path === '/api/rpc' && this.enable_rpc) {
|
|
111
112
|
await this.rpc(ctx);
|
|
112
113
|
return;
|
|
113
114
|
}
|
|
@@ -116,8 +117,13 @@ exports.server = {
|
|
|
116
117
|
// ------------ repl_router hook
|
|
117
118
|
if (await global.repl_router?.(ctx))
|
|
118
119
|
return;
|
|
120
|
+
if (await this.router(ctx))
|
|
121
|
+
return;
|
|
119
122
|
await next?.();
|
|
120
|
-
}
|
|
123
|
+
}
|
|
124
|
+
async router(ctx) {
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
121
127
|
/** args are array http://localhost/repl/rpc?func=to_json&args=aaa&args=bbb
|
|
122
128
|
should use POST when arg is number, otherwise type will be string
|
|
123
129
|
queries:
|
|
@@ -158,7 +164,7 @@ exports.server = {
|
|
|
158
164
|
error.status = 500;
|
|
159
165
|
throw error;
|
|
160
166
|
}
|
|
161
|
-
}
|
|
167
|
+
}
|
|
162
168
|
logger(ctx) {
|
|
163
169
|
const { request } = ctx;
|
|
164
170
|
const { query, body, path, _path, protocol, host, req: { httpVersion: http_version }, ip, } = request;
|
|
@@ -220,7 +226,7 @@ exports.server = {
|
|
|
220
226
|
s += '\n' + (0, utils_js_1.inspect)(body).replace('[Object: null prototype] ', '');
|
|
221
227
|
// --- print log
|
|
222
228
|
console.log(s);
|
|
223
|
-
}
|
|
229
|
+
}
|
|
224
230
|
async try_send(ctx, fp, { fs = file_js_1.ufs, root, log_404, }) {
|
|
225
231
|
const { request: { _path, path, method }, response, } = ctx;
|
|
226
232
|
if (!(typeof response.body === 'undefined') || response.status !== 404)
|
|
@@ -244,7 +250,7 @@ exports.server = {
|
|
|
244
250
|
_log_404();
|
|
245
251
|
return false;
|
|
246
252
|
}
|
|
247
|
-
}
|
|
253
|
+
}
|
|
248
254
|
/** send file at `path` with the given `options` to the koa `ctx`. */
|
|
249
255
|
async fsend(ctx, path, { fs = fs_1.default, root, absolute } = {}) {
|
|
250
256
|
const { request, response, req } = ctx;
|
|
@@ -339,6 +345,6 @@ exports.server = {
|
|
|
339
345
|
}
|
|
340
346
|
return path;
|
|
341
347
|
}
|
|
342
|
-
}
|
|
343
|
-
exports.
|
|
348
|
+
}
|
|
349
|
+
exports.Server = Server;
|
|
344
350
|
//# sourceMappingURL=server.js.map
|
package/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["server.ts"],"names":[],"mappings":";;;;AAAA,+BAGa;AAEb,wDAAuB;AACvB,oDAGW;AACX,+BAAgC;AAEhC,gBAAgB;AAChB,0DAAyB;AACzB,yEAAqC;AACrC,oDAAmB;AACnB,wEAAyC;AAGzC,2BAA2B;AAC3B,sDAIY;AAEZ,6DAA+B;AAC/B,wEAAsC;AACtC,iDAGsB;AAiBtB,yCAAoE;AACpE,uCAAyC;AAezC,yBAAyB;AACZ,QAAA,MAAM,GAAG;IAClB,GAAG,EAAE,IAAW;IAEhB,OAAO,EAAE,IAAmC;IAE5C,SAAS,EAAE,IAAkB;IAG7B,mCAAmC;IACnC,KAAK,CAAC,KAAK;QACP,mBAAmB;QACnB,IAAI,GAAG,GAAG,IAAI,aAAG,EAAE,CAAA;QAEnB,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;YAC3B,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;YACpB,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;QACpB,CAAC,CAAC,CAAA;QAEF,GAAG,CAAC,GAAG,CACH,IAAI,CAAC,KAAK,CAAC,IAAI,CA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;gBAEnC,QAAQ,CAAC,MAAM,GAAG,GAAG,CAAA;gBACrB,QAAQ,CAAC,GAAG,CAAC,gBAAgB,EAAE,MAAM,CAAC,SAAS,CAAC,CAAC,CAAA;gBACjD,QAAQ,CAAC,GAAG,CAAC,eAAe,EAAE,SAAS,KAAK,IAAI,GAAG,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,CAAA;gBACpE,QAAQ,CAAC,IAAI,GAAG,EAAE,CAAC,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,CAAA;AAGD,kBAAe,cAAM,CAAA","sourcesContent":["import {\n createServer as http_create_server,\n type Server as HttpServer,\n} from 'http'\n\nimport zlib from 'zlib'\nimport {\n default as nodefs,\n type Stats\n} from 'fs'\nimport { promisify } from 'util'\n\n// --- 3rd party\nimport upath from 'upath'\nimport invoke from 'lodash/invoke.js'\nimport qs from 'qs'\nimport resolve_safely from 'resolve-path'\n\n\n// --- koa & koa middleware\nimport {\n default as Koa,\n type Context,\n type Next\n} from 'koa'\n\nimport KoaCors from '@koa/cors'\nimport KoaCompress from 'koa-compress'\nimport {\n userAgent as KoaUserAgent,\n type UserAgentContext\n} from 'koa-useragent'\n\n\ndeclare module 'koa' {\n interface Request {\n _path: string\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 } from './net.js'\nimport { stream_to_buffer, inspect, output_width } from './utils.js'\nimport { ufs, 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 const server = {\n app: null as Koa,\n \n handler: null as ReturnType<Koa['callback']>,\n \n server_80: null as HttpServer,\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(\n this.entry.bind(this)\n )\n \n app.use(KoaCompress({\n br: {\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]: 6 // default 11 (maximized compression), may lead to news/get generated 14mb json taking 24s\n },\n },\n threshold: 512\n }))\n \n app.use(\n KoaCors({ credentials: true })\n )\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_80 = http_create_server(this.handler)\n \n await new Promise<void>(resolve => {\n this.server_80.listen(8421, resolve)\n })\n },\n \n \n stop () {\n this.server_80.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 request,\n req,\n req: { tunnel },\n } = 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) return\n \n if (ctx.is('application/json') || ctx.is('text/plain'))\n request.body = JSON.parse(req.body.toString())\n else if (ctx.is('application/x-www-form-urlencoded'))\n request.body = qs.parse(req.body.toString())\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 const { path } = request\n \n // ------------ /repl/rpc\n if (path === '/api/rpc') {\n await this.rpc(ctx)\n return\n }\n \n \n // ------------ log\n this.logger(ctx)\n \n // ------------ repl_router hook\n if (await global.repl_router?.(ctx))\n return\n \n await next?.()\n },\n \n \n /** args are array http://localhost/repl/rpc?func=to_json&args=aaa&args=bbb \n should use POST when arg is number, otherwise type will be string \n queries:\n - func: function name\n - args?: `[]` args array\n - ignore?: `false` don't serialize result into response\n - async?: `false` don't wait\n */\n async rpc (ctx: Context) {\n const { request: { query, body }, response } = ctx\n \n let {\n func,\n args = [],\n ignore = false,\n async: _async = false\n }: {\n func: string\n args: any[] | string\n ignore: boolean | string\n async: boolean | string\n } = { ...query, ...body }\n \n if (!func) {\n let error = new Error('rpc no func')\n ;(error as any).status = 400\n throw error\n }\n \n if (!Array.isArray(args))\n args = [args]\n \n // ?async=1 or ?async=0 or ?async=false\n if (typeof ignore === 'string')\n ignore = ignore.to_bool()\n \n if (typeof _async === 'string')\n _async = _async.to_bool()\n \n try {\n const presult = invoke(global, func, ...args)\n \n if (_async) {\n response.body = ''\n return\n }\n \n const result = await presult\n \n if (ignore) {\n response.body = ''\n return\n }\n \n response.body = JSON.stringify(result) || ''\n } catch (error) {\n error.status = 500\n throw error\n }\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 = ufs, \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) return true\n \n if (method !== 'HEAD' && method !== 'GET') 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) 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 ? stats.mtime.toUTCString() : 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\nexport default server\n\nexport type Server = typeof server\n"]}
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["server.ts"],"names":[],"mappings":";;;;AAAA,+BAGa;AAEb,wDAAuB;AACvB,oDAGW;AACX,+BAAgC;AAEhC,gBAAgB;AAChB,0DAAyB;AACzB,yEAAqC;AACrC,oDAAmB;AACnB,wEAAyC;AAGzC,2BAA2B;AAC3B,sDAIY;AAEZ,6DAA+B;AAC/B,wEAAsC;AACtC,iDAGsB;AAiBtB,yCAAoE;AACpE,uCAAyC;AAezC,yBAAyB;AACzB,MAAa,MAAM;IAYf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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;AA5eD,wBA4eC","sourcesContent":["import {\n createServer as http_create_server,\n type Server as HttpServer,\n} from 'http'\n\nimport zlib from 'zlib'\nimport {\n default as nodefs,\n type Stats\n} from 'fs'\nimport { promisify } from 'util'\n\n// --- 3rd party\nimport upath from 'upath'\nimport invoke from 'lodash/invoke.js'\nimport qs from 'qs'\nimport resolve_safely from 'resolve-path'\n\n\n// --- koa & koa middleware\nimport {\n default as Koa,\n type Context,\n type Next\n} from 'koa'\n\nimport KoaCors from '@koa/cors'\nimport KoaCompress from 'koa-compress'\nimport {\n userAgent as KoaUserAgent,\n type UserAgentContext\n} from 'koa-useragent'\n\n\ndeclare module 'koa' {\n interface Request {\n _path: string\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 } from './net.js'\nimport { stream_to_buffer, inspect, output_width } from './utils.js'\nimport { ufs, 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 enable_rpc: boolean\n \n \n constructor (port: number, { rpc = false }: { rpc?: boolean }) {\n this.port = port\n this.enable_rpc = rpc\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(\n this.entry.bind(this)\n )\n \n app.use(KoaCompress({\n br: {\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]: 6 // default 11 (maximized compression), may lead to news/get generated 14mb json taking 24s\n },\n },\n threshold: 512\n }))\n \n app.use(\n KoaCors({ credentials: true })\n )\n app.use(KoaUserAgent)\n \n app.use(\n this._router.bind(this)\n )\n \n this.app = app\n \n this.handler = this.app.callback()\n \n this.server_http = http_create_server(this.handler)\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 request,\n req,\n req: { tunnel },\n } = 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) return\n \n if (ctx.is('application/json') || ctx.is('text/plain'))\n request.body = JSON.parse(req.body.toString())\n else if (ctx.is('application/x-www-form-urlencoded'))\n request.body = qs.parse(req.body.toString())\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 const { path } = request\n \n // ------------ /repl/rpc\n if (path === '/api/rpc' && this.enable_rpc) {\n await this.rpc(ctx)\n return\n }\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 /** args are array http://localhost/repl/rpc?func=to_json&args=aaa&args=bbb \n should use POST when arg is number, otherwise type will be string \n queries:\n - func: function name\n - args?: `[]` args array\n - ignore?: `false` don't serialize result into response\n - async?: `false` don't wait\n */\n async rpc (ctx: Context) {\n const { request: { query, body }, response } = ctx\n \n let {\n func,\n args = [],\n ignore = false,\n async: _async = false\n }: {\n func: string\n args: any[] | string\n ignore: boolean | string\n async: boolean | string\n } = { ...query, ...body }\n \n if (!func) {\n let error = new Error('rpc no func')\n ;(error as any).status = 400\n throw error\n }\n \n if (!Array.isArray(args))\n args = [args]\n \n // ?async=1 or ?async=0 or ?async=false\n if (typeof ignore === 'string')\n ignore = ignore.to_bool()\n \n if (typeof _async === 'string')\n _async = _async.to_bool()\n \n try {\n const presult = invoke(global, func, ...args)\n \n if (_async) {\n response.body = ''\n return\n }\n \n const result = await presult\n \n if (ignore) {\n response.body = ''\n return\n }\n \n response.body = JSON.stringify(result) || ''\n } catch (error) {\n error.status = 500\n throw error\n }\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 = ufs, \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) return true\n \n if (method !== 'HEAD' && method !== 'GET') 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) 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 ? stats.mtime.toUTCString() : 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"]}
|