xshell 0.0.39 → 0.0.42
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 +0 -1
- package/file.js +6 -6
- package/file.js.map +1 -1
- package/i18n/dict.js +1 -0
- package/i18n/dict.js.map +1 -1
- package/i18n/index.js +15 -4
- package/i18n/index.js.map +1 -1
- package/i18n/scanner/index.js +3 -3
- package/i18n/scanner/index.js.map +1 -1
- package/net.browser.js +14 -10
- package/net.browser.js.map +1 -1
- package/net.js +18 -12
- package/net.js.map +1 -1
- package/package.json +7 -7
- package/process.d.ts +2 -2
- package/process.js +5 -5
- package/process.js.map +1 -1
- package/repl.js +1 -5
- package/repl.js.map +1 -1
- package/server.js +6 -2
- package/server.js.map +1 -1
- package/tsconfig.json +1 -1
- package/ufs.d.ts +1 -3
- package/ufs.js +2 -6
- package/ufs.js.map +1 -1
- package/utils.d.ts +2 -0
- package/utils.js +17 -1
- package/utils.js.map +1 -1
package/net.js
CHANGED
|
@@ -90,7 +90,7 @@ async function request(url, { queries, body, type = 'application/json', proxy, m
|
|
|
90
90
|
resolveWithFullResponse: true,
|
|
91
91
|
headers: {
|
|
92
92
|
'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',
|
|
93
|
-
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/
|
|
93
|
+
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36',
|
|
94
94
|
...body ? { 'content-type': type } : {},
|
|
95
95
|
...cookies ? {
|
|
96
96
|
cookie: Object.entries(cookies)
|
|
@@ -163,7 +163,7 @@ async function request(url, { queries, body, type = 'application/json', proxy, m
|
|
|
163
163
|
// --- decode body
|
|
164
164
|
if (encoding === 'binary')
|
|
165
165
|
return resp.body;
|
|
166
|
-
encoding
|
|
166
|
+
encoding ||= /charset=(.*)/.exec(resp.headers['content-type'])?.[1] || 'utf-8';
|
|
167
167
|
if (/utf-?8/i.test(encoding))
|
|
168
168
|
return resp.body.toString('utf-8');
|
|
169
169
|
return iconv_lite_1.default.decode(resp.body, encoding);
|
|
@@ -297,15 +297,14 @@ exports.connect_websocket = connect_websocket;
|
|
|
297
297
|
被调方在创建 Remote 对象时传入 funcs 注册处理函数,并使用 Remote.handle 方法处理 WebSocket message
|
|
298
298
|
*/
|
|
299
299
|
class Remote {
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
}
|
|
300
|
+
url;
|
|
301
|
+
websocket;
|
|
302
|
+
id = 0;
|
|
303
|
+
/** 被调方的 message 处理器 */
|
|
304
|
+
funcs;
|
|
305
|
+
/** 调用方发起的 rpc 对应响应的 message 处理器 */
|
|
306
|
+
handlers = [];
|
|
307
|
+
print = false;
|
|
309
308
|
get connected() {
|
|
310
309
|
return this.websocket?.readyState === ws_1.WebSocket.OPEN;
|
|
311
310
|
}
|
|
@@ -315,7 +314,7 @@ class Remote {
|
|
|
315
314
|
const len_json = dv.getUint32(0, true);
|
|
316
315
|
let offset = 4 + len_json;
|
|
317
316
|
let message = JSON.parse(decoder.decode(buf.subarray(4, offset)));
|
|
318
|
-
message.args
|
|
317
|
+
message.args ||= [];
|
|
319
318
|
if (message.bins) {
|
|
320
319
|
let args = message.args;
|
|
321
320
|
for (const ibin of message.bins) {
|
|
@@ -357,6 +356,11 @@ class Remote {
|
|
|
357
356
|
...bufs
|
|
358
357
|
]);
|
|
359
358
|
}
|
|
359
|
+
constructor({ url, funcs = {}, websocket, } = {}) {
|
|
360
|
+
this.url = url;
|
|
361
|
+
this.funcs = funcs;
|
|
362
|
+
this.websocket = websocket;
|
|
363
|
+
}
|
|
360
364
|
async connect() {
|
|
361
365
|
this.websocket = await connect_websocket(this.url, {
|
|
362
366
|
on_message: this.handle.bind(this)
|
|
@@ -374,6 +378,8 @@ class Remote {
|
|
|
374
378
|
}
|
|
375
379
|
/** 调用 remote 中的 func, 返回结果由 handler 处理,处理 done message 之后的返回值作为 call 函数的返回值 */
|
|
376
380
|
async call(message, handler) {
|
|
381
|
+
if (this.websocket?.readyState !== ws_1.WebSocket.OPEN)
|
|
382
|
+
throw new Error('websocket 连接已断开,无法调用 remote.call');
|
|
377
383
|
return new Promise((resolve, reject) => {
|
|
378
384
|
this.handlers[this.id] = async (message) => {
|
|
379
385
|
const { error, done } = message;
|
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,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,GAAG;gBACH,OAAO,IAAI,CAAC,GAAG,CAAC,eAAe,CAAC,aAAa,CAAC,CAAA;;gBAE9C,OAAO,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,aAAa,CAAC,CAAA;QAEjD,IA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C,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"]}
|
|
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,GAAG;gBACH,OAAO,IAAI,CAAC,GAAG,CAAC,eAAe,CAAC,aAAa,CAAC,CAAA;;gBAE9C,OAAO,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,aAAa,CAAC,CAAA;QAEjD,IAAI,OAAiB,CAAA;QACrB,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,aAAa,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,KAAK,EAAE,QAAQ,EAAE,EAAE;YAClE,IAAI,KAAK;gBAAE,MAAM,KAAK,CAAA;YACtB,OAAO,GAAG,QAAQ,CAAA;QACtB,CAAC,CAAC,CAAA;QACF,OAAO,OAAO,CAAA;IAClB,CAAC;CACJ,CAAA;AAKY,QAAA,QAAQ,GAAG,gCAAe,CAAC,QAAQ,CAAC;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;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;AAvND,wBAuNC","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/100.0.4896.60 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 if (this.websocket?.readyState !== WebSocket.OPEN)\n throw new Error('websocket 连接已断开,无法调用 remote.call')\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.42",
|
|
4
4
|
"main": "./index.js",
|
|
5
5
|
"bin": {
|
|
6
6
|
"xshell": "./xshell.js",
|
|
@@ -68,7 +68,7 @@
|
|
|
68
68
|
"@babel/core": "^7.17.8",
|
|
69
69
|
"@babel/parser": "^7.17.8",
|
|
70
70
|
"@babel/traverse": "^7.17.3",
|
|
71
|
-
"@koa/cors": "^3.
|
|
71
|
+
"@koa/cors": "^3.3.0",
|
|
72
72
|
"byte-size": "^8.1.0",
|
|
73
73
|
"chalk": "^4.1.2",
|
|
74
74
|
"chardet": "^1.4.0",
|
|
@@ -78,7 +78,7 @@
|
|
|
78
78
|
"colors": "^1.4.0",
|
|
79
79
|
"commander": "^8.3.0",
|
|
80
80
|
"ejs": "^3.1.6",
|
|
81
|
-
"emoji-regex": "^10.0
|
|
81
|
+
"emoji-regex": "^10.1.0",
|
|
82
82
|
"fs-extra": "^10.0.1",
|
|
83
83
|
"fs-monkey": "^1.0.3",
|
|
84
84
|
"gulp-sort": "^2.0.0",
|
|
@@ -96,8 +96,8 @@
|
|
|
96
96
|
"ora": "=5.4.1",
|
|
97
97
|
"promise-retry": "^2.0.1",
|
|
98
98
|
"qs": "^6.10.3",
|
|
99
|
-
"react": "^
|
|
100
|
-
"react-i18next": "^11.16.
|
|
99
|
+
"react": "^18.0.0",
|
|
100
|
+
"react-i18next": "^11.16.2",
|
|
101
101
|
"readdir-enhanced": "^6.0.4",
|
|
102
102
|
"request": "^2.88.2",
|
|
103
103
|
"request-promise-native": "^1.0.9",
|
|
@@ -126,7 +126,7 @@
|
|
|
126
126
|
"@types/js-cookie": "^3.0.1",
|
|
127
127
|
"@types/koa": "^2.13.4",
|
|
128
128
|
"@types/koa-compress": "^4.0.3",
|
|
129
|
-
"@types/lodash": "^4.14.
|
|
129
|
+
"@types/lodash": "^4.14.181",
|
|
130
130
|
"@types/node": "^17.0.23",
|
|
131
131
|
"@types/promise-retry": "^1.1.3",
|
|
132
132
|
"@types/qs": "^6.9.7",
|
|
@@ -137,7 +137,7 @@
|
|
|
137
137
|
"@types/stream-buffers": "^3.0.4",
|
|
138
138
|
"@types/tampermonkey": "^4.0.5",
|
|
139
139
|
"@types/vinyl-fs": "^2.4.12",
|
|
140
|
-
"@types/vscode": "^1.
|
|
140
|
+
"@types/vscode": "^1.66.0",
|
|
141
141
|
"@types/ws": "^8.5.3",
|
|
142
142
|
"source-map-loader": "^3.0.1",
|
|
143
143
|
"ts-loader": "^9.2.8"
|
package/process.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { type ChildProcess } from 'child_process';
|
|
|
3
3
|
import './prototype.js';
|
|
4
4
|
import { Encoding } from './file.js';
|
|
5
5
|
import { inspect } from './utils.js';
|
|
6
|
-
export declare const
|
|
6
|
+
export declare const fpd_root: string;
|
|
7
7
|
export declare const exe_node: string;
|
|
8
8
|
interface StartOptions {
|
|
9
9
|
/** `'d:/'` */
|
|
@@ -35,7 +35,7 @@ interface StartOptions {
|
|
|
35
35
|
- stdio?: `'pipe'` when 'ignore' then ignore stdio processing
|
|
36
36
|
- detached?: `false` whether to break the connection with child (ignore stdio, unref)
|
|
37
37
|
*/
|
|
38
|
-
export declare function start(exe: string, args?: string[], { cwd, encoding, print, stdio, detached, env, }?: StartOptions): ChildProcess
|
|
38
|
+
export declare function start(exe: string, args?: string[], { cwd, encoding, print, stdio, detached, env, }?: StartOptions): Promise<ChildProcess>;
|
|
39
39
|
export interface CallOptions extends StartOptions {
|
|
40
40
|
throw_code?: boolean;
|
|
41
41
|
input?: string;
|
package/process.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.call_node = exports.call = exports.start = exports.exe_node = exports.
|
|
3
|
+
exports.call_node = exports.call = exports.start = exports.exe_node = exports.fpd_root = void 0;
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
5
|
const child_process_1 = require("child_process");
|
|
6
6
|
const iconv_lite_1 = tslib_1.__importDefault(require("iconv-lite"));
|
|
7
7
|
require("./prototype.js");
|
|
8
8
|
const utils_js_1 = require("./utils.js");
|
|
9
|
-
exports.
|
|
9
|
+
exports.fpd_root = `${__dirname}/`.to_slash();
|
|
10
10
|
exports.exe_node = process.execPath.to_slash();
|
|
11
11
|
/** start process
|
|
12
12
|
- exe: .exe path or filename (full path is recommanded to skip path searching for better perf)
|
|
@@ -19,7 +19,7 @@ exports.exe_node = process.execPath.to_slash();
|
|
|
19
19
|
- stdio?: `'pipe'` when 'ignore' then ignore stdio processing
|
|
20
20
|
- detached?: `false` whether to break the connection with child (ignore stdio, unref)
|
|
21
21
|
*/
|
|
22
|
-
function start(exe, args = [], { cwd = exports.
|
|
22
|
+
async function start(exe, args = [], { cwd = exports.fpd_root, encoding = 'utf-8', print = true, stdio = 'pipe', detached = false, env, } = {}) {
|
|
23
23
|
const options = {
|
|
24
24
|
cwd,
|
|
25
25
|
shell: false,
|
|
@@ -97,7 +97,7 @@ async function call(exe, args = [], options = {}) {
|
|
|
97
97
|
'');
|
|
98
98
|
if (print.command)
|
|
99
99
|
console.log(cmd.blue);
|
|
100
|
-
let child = start(exe, args, {
|
|
100
|
+
let child = await start(exe, args, {
|
|
101
101
|
...options,
|
|
102
102
|
print: false,
|
|
103
103
|
});
|
|
@@ -132,7 +132,7 @@ async function call(exe, args = [], options = {}) {
|
|
|
132
132
|
}
|
|
133
133
|
})()
|
|
134
134
|
]);
|
|
135
|
-
const message = `process(${child.pid}) (${cmd}) exited ${code}${signal ? `, by signal ${signal}` : ''}.`;
|
|
135
|
+
const message = `process (${child.pid}) (${cmd}) exited ${code}${signal ? `, by signal ${signal}` : ''}.`;
|
|
136
136
|
if (print.code || code || signal)
|
|
137
137
|
console.log(message[code || signal ? 'red' : 'blue']);
|
|
138
138
|
const result = {
|
package/process.js.map
CHANGED
|
@@ -1 +1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7C,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"]}
|
|
1
|
+
{"version":3,"file":"process.js","sourceRoot":"","sources":["process.ts"],"names":[],"mappings":";;;;AAAA,iDAIsB;AAGtB,oEAA8B;AAE9B,0BAAuB;AAEvB,yCAAoC;AAEvB,QAAA,QAAQ,GAAG,GAAG,SAAS,GAAG,CAAC,QAAQ,EAAE,CAAA;AAErC,QAAA,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,QAAQ,EAAE,CAAA;AA6BnD;;;;;;;;;;EAUE;AACK,KAAK,UAAU,KAAK,CAAE,GAAW,EAAE,OAAiB,EAAG,EAAE,EAC5D,GAAG,GAAG,gB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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 fpd_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 async function start (exe: string, args: string[] = [ ], {\n cwd = fpd_root,\n \n encoding = 'utf-8',\n \n print = true,\n \n stdio = 'pipe',\n \n detached = false,\n \n env,\n}: StartOptions = { }): Promise<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 = await start(exe, args, {\n ...options,\n print: false,\n })\n \n if (input)\n child.stdin.write(input)\n \n // --- collect output\n let stdouts: (string | Buffer)[] = [ ]\n let stderrs: (string | Buffer)[] = [ ]\n \n let code: number | null, \n signal: NodeJS.Signals\n \n await Promise.all([\n new Promise<void>(resolve => {\n child.once('exit', (_code, _signal) => {\n code = _code\n signal = _signal\n resolve()\n })\n }),\n (async () => {\n if (stdio[1] === 'pipe')\n for await (const chunk of child.stdout as AsyncIterable<string | Buffer>) {\n if (encoding !== 'binary' && print.stdout)\n process.stdout.write(chunk)\n stdouts.push(chunk)\n }\n })(),\n (async () => {\n if (stdio[2] === 'pipe')\n for await (const chunk of child.stderr as AsyncIterable<string | Buffer>) {\n if (encoding !== 'binary' && print.stderr)\n process.stderr.write(chunk)\n stderrs.push(chunk)\n }\n })()\n ])\n \n const message = `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
|
@@ -3,7 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.pollute_module_default_export = exports.pollute_module_exports = exports.pollute_global = exports.exit = exports.stop = exports.start_repl = exports.repl_code = exports.eval_ts = exports.load_tsconfig = exports.ts_options_commonjs_repl = exports.ts_options_commonjs = exports.ts_options = exports.compile_ts = exports.generate_code = exports.parse_code = exports.set_printing_compiled_js = exports.set_inspection_limit = void 0;
|
|
4
4
|
const tslib_1 = require("tslib");
|
|
5
5
|
const vm_1 = tslib_1.__importDefault(require("vm"));
|
|
6
|
-
const fs_1 = tslib_1.__importDefault(require("fs"));
|
|
7
6
|
const repl_1 = tslib_1.__importDefault(require("repl"));
|
|
8
7
|
const process_1 = tslib_1.__importDefault(require("process"));
|
|
9
8
|
const typescript_1 = tslib_1.__importDefault(require("typescript"));
|
|
@@ -228,7 +227,7 @@ async function compile_ts({ fp, code, print = printing_compiled_js, save = false
|
|
|
228
227
|
}
|
|
229
228
|
exports.compile_ts = compile_ts;
|
|
230
229
|
async function load_tsconfig() {
|
|
231
|
-
const fp = `${process_js_1.
|
|
230
|
+
const fp = `${process_js_1.fpd_root}tsconfig.json`;
|
|
232
231
|
({ config: { compilerOptions: exports.ts_options } } = typescript_1.default.parseConfigFileTextToJson(fp, await (0, file_js_1.fread)(fp, { print: false })));
|
|
233
232
|
exports.ts_options_commonjs = {
|
|
234
233
|
...exports.ts_options,
|
|
@@ -276,9 +275,6 @@ async function start_repl() {
|
|
|
276
275
|
log_mod_loaded('prototype');
|
|
277
276
|
log_mod_loaded('utils');
|
|
278
277
|
log_mod_loaded('file');
|
|
279
|
-
const mfs = (0, file_js_1.create_mfs)();
|
|
280
|
-
(0, file_js_1.set_ufs)(new file_js_1.UFS([mfs, fs_1.default]));
|
|
281
|
-
log_mod_loaded('ufs');
|
|
282
278
|
log_mod_loaded('process');
|
|
283
279
|
log_mod_loaded('net');
|
|
284
280
|
// --- prevent from exiting
|