UNPKG

youzanyun-devtool-worker

Version:

80 lines (79 loc) 3.17 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const axios_1 = tslib_1.__importDefault(require("axios")); const https_1 = tslib_1.__importDefault(require("https")); const get_1 = tslib_1.__importDefault(require("lodash/get")); let dpDeveloperDecorate; class DpDeveloperDecorate { static getInstance() { if (!dpDeveloperDecorate) { dpDeveloperDecorate = new DpDeveloperDecorate(); } return dpDeveloperDecorate; } async run(ctx, port) { let requestHeader = JSON.parse(JSON.stringify(ctx.headers)); let webviewCookies; if (ctx.headers['x-webview-cookie']) { webviewCookies = JSON.parse(ctx.headers['x-webview-cookie']); const newStr = Object.keys(webviewCookies).map(key => `${key}=${webviewCookies[key]}`).join('; '); requestHeader['cookie'] = `${newStr}; ${requestHeader['cookie']}`; Object.keys(webviewCookies).forEach(item => { ctx.cookies.set(item, webviewCookies[item], { domain: '.youzan.com' }); }); } requestHeader['accept-encoding'] = 'gzip, deflate'; const config = { method: ctx.method, url: ctx.href, headers: requestHeader, data: ctx.isJsonHeader ? ctx.request.body : ctx.req, responseType: "text", validateStatus: function (status) { return true; }, maxRedirects: 0, httpsAgent: new https_1.default.Agent({ rejectUnauthorized: false }), }; let axiosRes = await (0, axios_1.default)(config); if (axiosRes.status < 200 || axiosRes.status >= 300) { ctx.status = axiosRes.status; let header = JSON.parse(JSON.stringify(axiosRes.headers)); delete header["content-length"]; ctx.set(header); ctx.body = axiosRes.data; } const kdtId = (0, get_1.default)(webviewCookies, 'kdtId') || ctx.cookies.get('kdt_id') || ctx.cookies.get('kdtId'); const interceptA = ` <script src="https://b.yzcdn.cn/yzy/zepto.min.js"></script> <script> window._global = window._global || {}; window._global.kdtId=${kdtId}; window.onload = function() { Zepto(function($) { $('body').on('click', 'a', e => { e.preventDefault() }); }) Zepto.ajax({ url: 'https://www.youzan.com/v2/account/team/change.html?kdt_id=${kdtId}' }) } </script> `; const content = axiosRes.data; const jsReg = /<\/head>/g; let index = -1; let matches; while ((matches = jsReg.exec(content)) !== null) { index = matches.index; } const finalContent = content.substring(0, index) + interceptA + content.substring(index); let header = JSON.parse(JSON.stringify(axiosRes.headers)); delete header["content-length"]; ctx.set(header); ctx.body = finalContent; } } exports.default = DpDeveloperDecorate;