xshell 0.0.18 → 0.0.20
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.js +1 -2
- package/file.js.map +1 -1
- package/i18n/README.md +283 -0
- package/i18n/dict.d.ts +30 -0
- package/i18n/dict.js +34 -0
- package/i18n/dict.js.map +1 -0
- package/i18n/i18n-scan.d.ts +2 -0
- package/i18n/i18n-scan.js +21 -0
- package/i18n/i18n-scan.js.map +1 -0
- package/i18n/i18n.ico +0 -0
- package/i18n/index.d.ts +65 -0
- package/i18n/index.js +118 -0
- package/i18n/index.js.map +1 -0
- package/i18n/rwdict.d.ts +42 -0
- package/i18n/rwdict.js +110 -0
- package/i18n/rwdict.js.map +1 -0
- package/i18n/scanner/checker.d.ts +5 -0
- package/i18n/scanner/checker.js +73 -0
- package/i18n/scanner/checker.js.map +1 -0
- package/i18n/scanner/index.d.ts +52 -0
- package/i18n/scanner/index.js +319 -0
- package/i18n/scanner/index.js.map +1 -0
- package/i18n/scanner/parser.d.ts +3 -0
- package/i18n/scanner/parser.js +154 -0
- package/i18n/scanner/parser.js.map +1 -0
- package/i18n/utils.d.ts +1 -0
- package/i18n/utils.js +14 -0
- package/i18n/utils.js.map +1 -0
- package/net.js +2 -4
- package/net.js.map +1 -1
- package/package.json +37 -10
- package/repl.js +4 -8
- package/repl.js.map +1 -1
- package/server.d.ts +1 -0
- package/server.js +2 -3
- package/server.js.map +1 -1
- package/ufs.js +3 -3
- package/ufs.js.map +1 -1
- package/tsconfig.json +0 -68
package/net.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"net.js","sourceRoot":"","sources":["net.ts"],"names":[],"mappings":";;;;AAGA,iGAAoD;AAEpD,0DAA6E;AAE7E,+EAAyC;AAEzC,yEAA8B;AAC9B,mEAA6B;AAC7B,yDAAmB;AACnB,+CAAwD;AA2C/C,uFA3CA,qBAAM,OA2CA;AAlCf,uBAAoB;AAEpB,mCAA+C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,CAAA;IAEzD,OAAO,YAAY,CAAC,GAAG,EAAE;QACrB,IAAI,EAAE;YACF,IAAI;YACJ,IAAI;YACJ,KAAK,EAAE,MAAM;YACb,MAAM;SACT;KACJ,CAAC,CAAA;AACN,CAAC;AAfD,kBAeC;AAGD,SAAgB,QAAQ,CAAE,IAAY,EAAE,IAAW;IAC/C,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAE,GAAG,CAAC,EAAE,CAAC,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC;QAChD,OAAO,CAAC,+BAA+B,EAAE,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC;QACtE,CAAC;YACG,OAAO,CAAC,+BAA+B,EAAE,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,CAAA;IAC7E,OAAO,GAAG,CAAA;AACd,CAAC;AAND,4BAMC","sourcesContent":["import request_lib from 'request'\nimport type { OptionsWithUri, OptionsWithUrl } from 'request'\n\nimport request_promise from 'request-promise-native'\nimport type { FullResponse } from 'request-promise-native'\nimport { RequestError, StatusCodeError } from 'request-promise-native/errors'\n\nimport promise_retry from 'promise-retry'\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'\nimport type { Encoding } from './file'\nimport { inspect, output_width } from './utils'\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 gzip: true,\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 if (!url.startsWith('http'))\n url = 'http://' + url\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/93.0.4577.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 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}` : '' ) +\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"]}
|
|
1
|
+
{"version":3,"file":"net.js","sourceRoot":"","sources":["net.ts"],"names":[],"mappings":";;;;AAGA,iGAAoD;AAEpD,0DAA6E;AAE7E,+EAAyC;AAEzC,yEAA8B;AAC9B,mEAA6B;AAC7B,yDAAmB;AACnB,+CAAwD;AA2C/C,uFA3CA,qBAAM,OA2CA;AAlCf,uBAAoB;AAEpB,mCAA+C;AAE/C,IAAY,OAGX;AAHD,WAAY,OAAO;IACf,4CAAiC,CAAA;IACjC,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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G,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,CAAE,CAAC,CAAE,EAAE,CAAC,CAAA;AACpE,CAAC;AArBD,0BAqBC;AAKD,kDAAkD;AAClD;;;;;;EAME;AACK,KAAK,UAAU,GAAG,CACrB,IAAY,EACZ,IAAY,EACZ,EAAE,GAAG,GAAG,+BAA+B,EAAE,KAAK,EAAE,MAAM,GAAG,KAAK,EAAE,MAAM,GAAG,KAAK,KAA0D,EAAG;IAE3I,IAAI,CAAC,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAA;IAEzD,OAAO,YAAY,CAAC,GAAG,EAAE;QACrB,IAAI,EAAE;YACF,IAAI;YACJ,IAAI;YACJ,KAAK,EAAE,MAAM;YACb,MAAM;SACT;KACJ,CAAC,CAAA;AACN,CAAC;AAfD,kBAeC;AAGD,SAAgB,QAAQ,CAAE,IAAY,EAAE,IAAW;IAC/C,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAE,GAAG,CAAC,EAAE,CAAC,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC;QAChD,OAAO,CAAC,+BAA+B,EAAE,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC;QACtE,CAAC;YACG,OAAO,CAAC,+BAA+B,EAAE,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,CAAA;IAC7E,OAAO,GAAG,CAAA;AACd,CAAC;AAND,4BAMC","sourcesContent":["import request_lib from 'request'\nimport type { OptionsWithUri, OptionsWithUrl } from 'request'\n\nimport request_promise from 'request-promise-native'\nimport type { FullResponse } from 'request-promise-native'\nimport { RequestError, StatusCodeError } from 'request-promise-native/errors'\n\nimport promise_retry from 'promise-retry'\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'\nimport type { Encoding } from './file'\nimport { inspect, output_width } from './utils'\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 gzip: true,\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 if (!url.startsWith('http'))\n url = 'http://' + url\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/93.0.4577.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 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}` : '' ) +\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"]}
|
package/package.json
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "xshell",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.20",
|
|
4
4
|
"main": "./index.js",
|
|
5
5
|
"bin": {
|
|
6
|
-
"xshell": "./xshell.js"
|
|
6
|
+
"xshell": "./xshell.js",
|
|
7
|
+
"i18n-scan": "./i18n/i18n-scan.js"
|
|
7
8
|
},
|
|
8
9
|
"description": "xshell is a shell designed to provide a brand new human-computer interaction experience.",
|
|
9
10
|
"keywords": [
|
|
10
11
|
"shell",
|
|
11
12
|
"node",
|
|
12
13
|
"repl",
|
|
14
|
+
"i18n",
|
|
13
15
|
"interactive programming"
|
|
14
16
|
],
|
|
15
17
|
"type": "commonjs",
|
|
@@ -63,25 +65,42 @@
|
|
|
63
65
|
]
|
|
64
66
|
},
|
|
65
67
|
"dependencies": {
|
|
68
|
+
"@babel/core": "^7.15.0",
|
|
69
|
+
"@babel/parser": "^7.15.3",
|
|
70
|
+
"@babel/traverse": "^7.15.0",
|
|
66
71
|
"@koa/cors": "^3.1.0",
|
|
67
72
|
"byte-size": "^8.1.0",
|
|
68
73
|
"chalk": "^4.1.2",
|
|
69
74
|
"chardet": "^1.4.0",
|
|
70
75
|
"cheerio": "^1.0.0-rc.10",
|
|
76
|
+
"cli-table3": "^0.6.0",
|
|
77
|
+
"cli-truncate": "=2.1.0",
|
|
78
|
+
"colors": "^1.4.0",
|
|
79
|
+
"commander": "^8.1.0",
|
|
80
|
+
"ejs": "^3.1.6",
|
|
71
81
|
"emoji-regex": "^10.0.0",
|
|
72
82
|
"fs-extra": "^10.0.0",
|
|
73
83
|
"fs-monkey": "^1.0.3",
|
|
84
|
+
"gulp-sort": "^2.0.0",
|
|
85
|
+
"hash-string": "^1.0.0",
|
|
86
|
+
"i18next-scanner": "^3.0.0",
|
|
87
|
+
"i18next": "^20.5.0",
|
|
74
88
|
"iconv-lite": "^0.6.3",
|
|
75
|
-
"
|
|
89
|
+
"js-cookie": "^3.0.0",
|
|
76
90
|
"koa-compress": "^5.1.0",
|
|
77
91
|
"koa-useragent": "^4.0.0",
|
|
92
|
+
"koa": "^2.13.4",
|
|
78
93
|
"lodash": "^4.17.21",
|
|
94
|
+
"map-stream": "0.0.7",
|
|
79
95
|
"memfs": "^3.4.0",
|
|
96
|
+
"ora": "=5.4.1",
|
|
80
97
|
"promise-retry": "^2.0.1",
|
|
81
98
|
"qs": "^6.10.1",
|
|
99
|
+
"react-i18next": "^11.11.4",
|
|
100
|
+
"react": "^17.0.2",
|
|
82
101
|
"readdir-enhanced": "^6.0.4",
|
|
83
|
-
"request": "^2.88.2",
|
|
84
102
|
"request-promise-native": "^1.0.9",
|
|
103
|
+
"request": "^2.88.2",
|
|
85
104
|
"resolve-path": "^1.4.0",
|
|
86
105
|
"rimraf": "^3.0.2",
|
|
87
106
|
"stream-buffers": "^3.0.2",
|
|
@@ -89,25 +108,33 @@
|
|
|
89
108
|
"tough-cookie": "^4.0.0",
|
|
90
109
|
"tslib": "^2.3.1",
|
|
91
110
|
"typescript": "^4.5.2",
|
|
92
|
-
"upath": "^2.0.1"
|
|
111
|
+
"upath": "^2.0.1",
|
|
112
|
+
"vinyl-fs": "^3.0.3",
|
|
113
|
+
"vinyl": "^2.2.1"
|
|
93
114
|
},
|
|
94
115
|
"devDependencies": {
|
|
116
|
+
"@babel/types": "^7.15.0",
|
|
117
|
+
"@types/babel__traverse": "^7.14.2",
|
|
95
118
|
"@types/chardet": "^0.8.1",
|
|
96
119
|
"@types/cheerio": "^0.22.30",
|
|
120
|
+
"@types/ejs": "^3.1.0",
|
|
121
|
+
"@types/express": "^4.17.13",
|
|
97
122
|
"@types/fs-extra": "^9.0.13",
|
|
98
|
-
"@types/
|
|
123
|
+
"@types/gulp-sort": "0.0.33",
|
|
124
|
+
"@types/js-cookie": "^2.2.7",
|
|
99
125
|
"@types/koa-compress": "^4.0.3",
|
|
126
|
+
"@types/koa": "^2.13.4",
|
|
100
127
|
"@types/lodash": "^4.14.177",
|
|
101
128
|
"@types/node": "^16.11.10",
|
|
102
129
|
"@types/promise-retry": "^1.1.3",
|
|
103
130
|
"@types/qs": "^6.9.7",
|
|
104
|
-
"@types/
|
|
131
|
+
"@types/react": "^17.0.19",
|
|
105
132
|
"@types/request-promise-native": "^1.0.18",
|
|
133
|
+
"@types/request": "^2.48.7",
|
|
106
134
|
"@types/rimraf": "^3.0.2",
|
|
107
135
|
"@types/stream-buffers": "^3.0.4",
|
|
108
136
|
"@types/tampermonkey": "^4.0.5",
|
|
109
|
-
"@types/
|
|
110
|
-
"
|
|
111
|
-
"ts-loader": "^9.2.6"
|
|
137
|
+
"@types/vinyl-fs": "^2.4.12",
|
|
138
|
+
"@types/vscode": "^1.62.0"
|
|
112
139
|
}
|
|
113
140
|
}
|
package/repl.js
CHANGED
|
@@ -93,10 +93,7 @@ function trans_import_2_require(import_decl) {
|
|
|
93
93
|
// var { element2: element2_, element3 } = __importDefault(require("mod"))
|
|
94
94
|
factory.createVariableStatement([], [factory.createVariableDeclaration(factory.createObjectBindingPattern(
|
|
95
95
|
// ImportSpecifier[] -> ObjectBindingPattern.BindingElement[]
|
|
96
|
-
import_clause.namedBindings.elements.map(import_specifier =>
|
|
97
|
-
var _a;
|
|
98
|
-
return factory.createBindingElement(undefined, import_specifier.propertyName, import_specifier.name, ((_a = import_specifier.propertyName) === null || _a === void 0 ? void 0 : _a.text) === 'default' ? require_module_stmt : undefined);
|
|
99
|
-
})), undefined, undefined, require_module_stmt)]),
|
|
96
|
+
import_clause.namedBindings.elements.map(import_specifier => factory.createBindingElement(undefined, import_specifier.propertyName, import_specifier.name, import_specifier.propertyName?.text === 'default' ? require_module_stmt : undefined))), undefined, undefined, require_module_stmt)]),
|
|
100
97
|
// Object.assign(global, { element2_, element3 })
|
|
101
98
|
factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier('Object'), 'assign'), [],
|
|
102
99
|
// ImportSpecifier[] -> ObjectBindingPattern.BindingElement[]
|
|
@@ -111,13 +108,12 @@ function trans_import_2_require(import_decl) {
|
|
|
111
108
|
}
|
|
112
109
|
/** export function foo () { } */
|
|
113
110
|
function trans_export_stmt(stmt) {
|
|
114
|
-
var _a;
|
|
115
111
|
if (typescript_1.default.isExportAssignment(stmt))
|
|
116
112
|
return factory.createExpressionStatement(stmt.expression);
|
|
117
113
|
function is_export_modifier(modifier) {
|
|
118
114
|
return modifier.flags & ModifierFlags.Export || modifier.flags & ModifierFlags.ExportDefault || modifier.kind === SyntaxKind.ExportKeyword;
|
|
119
115
|
}
|
|
120
|
-
if (
|
|
116
|
+
if (stmt.modifiers?.some(modifier => is_export_modifier(modifier))) {
|
|
121
117
|
// @ts-ignore
|
|
122
118
|
stmt.modifiers = factory.createNodeArray(stmt.modifiers.filter(modifier => !is_export_modifier(modifier)));
|
|
123
119
|
return stmt;
|
|
@@ -349,9 +345,9 @@ async function exit() {
|
|
|
349
345
|
exports.exit = exit;
|
|
350
346
|
async function pollute_global() {
|
|
351
347
|
Object.assign(global, {
|
|
352
|
-
__importDefault: (mod) => ((mod
|
|
348
|
+
__importDefault: (mod) => ((mod?.__esModule) ? mod : { default: mod }),
|
|
353
349
|
__importStar: (mod) => {
|
|
354
|
-
if (mod
|
|
350
|
+
if (mod?.__esModule)
|
|
355
351
|
return mod;
|
|
356
352
|
let result = {};
|
|
357
353
|
if (mod != null)
|
package/repl.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"repl.js","sourceRoot":"","sources":["repl.ts"],"names":[],"mappings":";;;;AAAA,6DAAuB;AACvB,yDAAoB;AACpB,6DAAuB;AACvB,mEAA6B;AAC7B,yDAAmB;AAGnB,yEAA2B;AAiB3B,uBAAoB;AACpB,mCAA6E;AAC7E,iCAA2E;AAC3E,6CAAsC;AAYtC,+BAA+B;AAE/B,cAAI,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,GAAI,EAAE,CAAA;AAChD,IAAI;IACA,cAAI,CAAC,OAAO,CAAC,cAAc,CAAC,eAAe,GAAG,KAAK,CAAA;CACtD;AAAC,MAAM;IACJ,OAAO,CAAC,KAAK,CAAC,uDAAuD,CAAC,CAAA;CACzE;AACD,cAAI,CAAC,OAAO,CAAC,cAAc,CAAC,WAAW,GAAO,oBAAY,CAAA;AAC1D,cAAI,CAAC,OAAO,CAAC,cAAc,CAAC,MAAM,GAAY,IAAI,CAAA;AAClD,cAAI,CAAC,OAAO,CAAC,cAAc,CAAC,OAAO,GAAW,KAAK,CAAA;AACnD,cAAI,CAAC,OAAO,CAAC,cAAc,CAAC,OAAO,GAAW,IAAI,CAAA;AAClD,cAAI,CAAC,OAAO,CAAC,cAAc,CAAC,KAAK,GAAa,CAAC,CAAA;AAC/C,cAAI,CAAC,OAAO,CAAC,cAAc,CAAC,MAAM,GAAY,KAAK,CAAA;AACnD,cAAI,CAAC,OAAO,CAAC,cAAc,CAAC,SAAS,GAAS,IAAI,CAAA;AAElD,cAAI,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,GAAI,OAAO,CAAA;AACrC,cAAI,CAAC,OAAO,CAAC,MAAM,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AC9D,6BAA6B,CAAC,mBAAmB,EAAG,UAAU,CAAC;QAE/D,6BAA6B,CAAC,IAAI,EAAE,IAAI,CAAC;QAEzC,sBAAsB,CAAC,gBAAgB,CAAC;QACxC,sBAAsB,CAAC,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,mBAAW,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,qEAAa,MAAM,GAAC,CACvB,CAAA;AACL,CAAC;AALD,wDAKC;AAEM,KAAK,UAAU,6BAA6B,CAAE,MAAc,EAAE,IAAY;IAC7E,MAAM,CAAC,IAAI,CAAC,GAAG,CACX,qEAAa,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 util from 'util'\nimport nvm from 'vm'\nimport repl from 'repl'\nimport process from 'process'\nimport fs from 'fs'\n\n\nimport ts from 'typescript'\nimport type {\n SourceFile,\n Node,\n Statement, \n Modifier,\n SyntaxKind as TSyntaxKind,\n Identifier,\n StringLiteral,\n ExpressionStatement,\n ObjectBindingPattern,\n BindingElement,\n} from 'typescript'\n\nimport type { Context } from 'koa'\n\n\nimport './prototype'\nimport { log_section, log_line, delay, inspect, output_width } from './utils'\nimport { fread, fwrite, fwatchers, create_mfs, set_ufs, UFS } from './file'\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// ------------ inspect options\n\nutil.inspect.defaultOptions.maxArrayLength = 40\ntry {\n util.inspect.defaultOptions.maxStringLength = 10000\n} catch {\n console.error('set util.inspect.defaultOptions.maxStringLength error')\n}\nutil.inspect.defaultOptions.breakLength = output_width\nutil.inspect.defaultOptions.colors = true\nutil.inspect.defaultOptions.compact = false\nutil.inspect.defaultOptions.getters = true\nutil.inspect.defaultOptions.depth = 2\nutil.inspect.defaultOptions.sorted = false\nutil.inspect.defaultOptions.showProxy = true\n\nutil.inspect.styles.number = 'green'\nutil.inspect.styles.string = 'cyan'\nutil.inspect.styles.boolean = 'blue'\nutil.inspect.styles.date = 'magenta'\nutil.inspect.styles.special = 'white'\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\n\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 lastExpression = get_expr_of_stmt(statements.last)\n if (is_expr_stmt(lastExpression))\n return [ ...statements.slice(0, -1), factory.createReturnStatement(lastExpression.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: string, ...args: any[]) {\n log_line()\n \n // --- run code\n global.__ = await global['eval_' + type](...args)\n \n log_line()\n \n if (type !== 'shell')\n console.log(\n inspect(global.__, { limit: inspection_limit })\n )\n \n \n console.log('\\n'.repeat(2))\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(20)}loaded`)\n}\n\n"]}
|
|
1
|
+
{"version":3,"file":"repl.js","sourceRoot":"","sources":["repl.ts"],"names":[],"mappings":";;;;AAAA,6DAAuB;AACvB,yDAAoB;AACpB,6DAAuB;AACvB,mEAA6B;AAC7B,yDAAmB;AAGnB,yEAA2B;AAiB3B,uBAAoB;AACpB,mCAA6E;AAC7E,iCAA2E;AAC3E,6CAAsC;AAYtC,+BAA+B;AAE/B,cAAI,CAAC,OAAO,CAAC,cAAc,CAAC,cAAc,GAAI,EAAE,CAAA;AAChD,IAAI;IACA,cAAI,CAAC,OAAO,CAAC,cAAc,CAAC,eAAe,GAAG,KAAK,CAAA;CACtD;AAAC,MAAM;IACJ,OAAO,CAAC,KAAK,CAAC,uDAAuD,CAAC,CAAA;CACzE;AACD,cAAI,CAAC,OAAO,CAAC,cAAc,CAAC,WAAW,GAAO,oBAAY,CAAA;AAC1D,cAAI,CAAC,OAAO,CAAC,cAAc,CAAC,MAAM,GAAY,IAAI,CAAA;AAClD,cAAI,CAAC,OAAO,CAAC,cAAc,CAAC,OAAO,GAAW,KAAK,CAAA;AACnD,cAAI,CAAC,OAA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\n\nimport ts from 'typescript'\nimport type {\n SourceFile,\n Node,\n Statement, \n Modifier,\n SyntaxKind as TSyntaxKind,\n Identifier,\n StringLiteral,\n ExpressionStatement,\n ObjectBindingPattern,\n BindingElement,\n} from 'typescript'\n\nimport type { Context } from 'koa'\n\n\nimport './prototype'\nimport { log_section, log_line, delay, inspect, output_width } from './utils'\nimport { fread, fwrite, fwatchers, create_mfs, set_ufs, UFS } from './file'\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// ------------ inspect options\n\nutil.inspect.defaultOptions.maxArrayLength = 40\ntry {\n util.inspect.defaultOptions.maxStringLength = 10000\n} catch {\n console.error('set util.inspect.defaultOptions.maxStringLength error')\n}\nutil.inspect.defaultOptions.breakLength = output_width\nutil.inspect.defaultOptions.colors = true\nutil.inspect.defaultOptions.compact = false\nutil.inspect.defaultOptions.getters = true\nutil.inspect.defaultOptions.depth = 2\nutil.inspect.defaultOptions.sorted = false\nutil.inspect.defaultOptions.showProxy = true\n\nutil.inspect.styles.number = 'green'\nutil.inspect.styles.string = 'cyan'\nutil.inspect.styles.boolean = 'blue'\nutil.inspect.styles.date = 'magenta'\nutil.inspect.styles.special = 'white'\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\n\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 lastExpression = get_expr_of_stmt(statements.last)\n if (is_expr_stmt(lastExpression))\n return [ ...statements.slice(0, -1), factory.createReturnStatement(lastExpression.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: string, ...args: any[]) {\n log_line()\n \n // --- run code\n global.__ = await global['eval_' + type](...args)\n \n log_line()\n \n if (type !== 'shell')\n console.log(\n inspect(global.__, { limit: inspection_limit })\n )\n \n \n console.log('\\n'.repeat(2))\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(20)}loaded`)\n}\n\n"]}
|
package/server.d.ts
CHANGED
package/server.js
CHANGED
|
@@ -97,7 +97,6 @@ exports.server = {
|
|
|
97
97
|
request.body = req.body;
|
|
98
98
|
},
|
|
99
99
|
async router(ctx, next) {
|
|
100
|
-
var _a;
|
|
101
100
|
let { request } = ctx;
|
|
102
101
|
const _path = request._path = decodeURIComponent(request.path);
|
|
103
102
|
Object.defineProperty(request, 'path', {
|
|
@@ -115,9 +114,9 @@ exports.server = {
|
|
|
115
114
|
// ------------ log
|
|
116
115
|
this.logger(ctx);
|
|
117
116
|
// ------------ repl_router hook
|
|
118
|
-
if (await
|
|
117
|
+
if (await global.repl_router?.(ctx))
|
|
119
118
|
return;
|
|
120
|
-
await
|
|
119
|
+
await next?.();
|
|
121
120
|
},
|
|
122
121
|
/** args are array http://localhost/repl/rpc?func=to_json&args=aaa&args=bbb
|
|
123
122
|
should use POST when arg is number, otherwise type will be string
|
package/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["server.ts"],"names":[],"mappings":";;;;AAAA,+BAGa;AAEb,6DAAuB;AACvB,yDAAkD;AAClD,+BAAgC;AAEhC,gBAAgB;AAChB,+DAAyB;AACzB,wEAAkC;AAClC,yDAAmB;AACnB,6EAAyC;AAGzC,2BAA2B;AAC3B,2DAAqB;AAGrB,kEAA+B;AAC/B,6EAAsC;AACtC,iDAGsB;AAiBtB,mCAAiE;AACjE,iCAAsC;AAetC,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,CAAC,IAAI,CAAC,CACxB,CAAA;QAED,GAAG,CAAC,GAAG,CAAC,IAAA,sBAAW,EAAC;YAChB,EAAE,EAAE;gBACA,4DAA4D;gBAC5D,MAAM,EAAE;oBACJ,CAAC,cAAI,CAAC,SAAS,CAAC,iBAAiB,CAAC,EAAE,cAAI,CAAC,SAAS,CAAC,gBAAgB;oBACnE,CAAC,cAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC,EAAE,CAAC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,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 { default as nodefs, type Stats } from 'fs'\nimport { promisify } from 'util'\n\n// --- 3rd party\nimport upath from 'upath'\nimport invoke from 'lodash/invoke'\nimport qs from 'qs'\nimport resolve_safely from 'resolve-path'\n\n\n// --- koa & koa middleware\nimport Koa from 'koa'\nimport type { Context, Next } 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'\nimport { stream_to_buffer, inspect, output_width } from './utils'\nimport { ufs, type UFS } from './file'\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 { func, args = [], ignore = false, async: _async = false }: { func: string, args: any[] | string, ignore: boolean | string, async: boolean | string } = { ...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 }: {\n fs?: (typeof nodefs) | UFS\n root: string\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 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 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,6DAAuB;AACvB,yDAAkD;AAClD,+BAAgC;AAEhC,gBAAgB;AAChB,+DAAyB;AACzB,wEAAkC;AAClC,yDAAmB;AACnB,6EAAyC;AAGzC,2BAA2B;AAC3B,2DAAqB;AAGrB,kEAA+B;AAC/B,6EAAsC;AACtC,iDAGsB;AAiBtB,mCAAiE;AACjE,iCAAsC;AAetC,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,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,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 { default as nodefs, type Stats } from 'fs'\nimport { promisify } from 'util'\n\n// --- 3rd party\nimport upath from 'upath'\nimport invoke from 'lodash/invoke'\nimport qs from 'qs'\nimport resolve_safely from 'resolve-path'\n\n\n// --- koa & koa middleware\nimport Koa from 'koa'\nimport type { Context, Next } 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'\nimport { stream_to_buffer, inspect, output_width } from './utils'\nimport { ufs, type UFS } from './file'\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 { func, args = [], ignore = false, async: _async = false }: { func: string, args: any[] | string, ignore: boolean | string, async: boolean | string } = { ...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 }: {\n fs?: (typeof nodefs) | UFS\n root: string\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 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 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"]}
|