UNPKG

@lark-project/cli

Version:

飞书项目插件开发工具

72 lines (71 loc) 3.18 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.prepareProxy = void 0; const path_1 = __importDefault(require("path")); const fs_extra_1 = __importDefault(require("fs-extra")); const chalk_1 = __importDefault(require("chalk")); const env_1 = require("../../utils/env"); const onProxyError = (proxy) => { return (err, req, res) => { const host = req.headers && req.headers.host; console.log(`Proxy error: Could not proxy request ${chalk_1.default.cyan(req.url)} from ${chalk_1.default.cyan(host)} to ${chalk_1.default.cyan(proxy)}.`); console.log(`See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (${chalk_1.default.cyan(err === null || err === void 0 ? void 0 : err.code)}).`); if (res.writeHead && !res.headersSent) { res.writeHead(500); } res.end(`Proxy error: Could not proxy request ${req.url} from ${host} to ${proxy} (${err === null || err === void 0 ? void 0 : err.code}).`); }; }; const prepareProxy = (proxy, pluginPublicFolder, servedPathname) => { // `proxy` lets you specify alternate servers for specific requests. if (!proxy) { return undefined; } if (typeof proxy !== 'string') { throw new Error(chalk_1.default.red(`When specified, "proxy" in package.json must be a string.\nInstead, the type of "proxy" was "${typeof proxy}".\nEither remove "proxy" from package.json, or make it a string.`)); } const sockPath = env_1.env.sockPath; const isDefaultSockHost = !env_1.env.sockHost; function mayProxy(pathname) { const maybePublicPath = path_1.default.resolve(pluginPublicFolder, pathname.replace(new RegExp('^' + servedPathname), '')); const isPublicFileRequest = fs_extra_1.default.existsSync(maybePublicPath); const isWdsEndpointRequest = isDefaultSockHost && pathname.startsWith(sockPath); return !(isPublicFileRequest || isWdsEndpointRequest); } if (!/^http(s)?:\/\//.test(proxy)) { throw new Error(chalk_1.default.red('When "proxy" is specified in package.json it must start with either http:// or https://')); } let target; if (env_1.env.platform === 'win32') { target = ''; } else { target = proxy; } return [ { target, logLevel: 'silent', context: function (pathname, req) { return (req.method !== 'GET' || Boolean(mayProxy(pathname) && req.headers.accept && req.headers.accept.indexOf('text/html') === -1)); }, onProxyReq: proxyReq => { if (proxyReq.getHeader('origin')) { proxyReq.setHeader('origin', target); } }, onError: onProxyError(target), secure: false, changeOrigin: true, ws: true, xfwd: true, }, ]; }; exports.prepareProxy = prepareProxy;