mirror of
https://github.com/sub-store-org/Sub-Store.git
synced 2026-11-27 23:13:43 +00:00
feat: 新增操作 修改响应, 可用于修改最终发出的响应
This commit is contained in:
8 files changed
+578
-94
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "sub-store",
|
||||
"version": "2.23.9",
|
||||
"version": "2.23.10",
|
||||
"description": "Advanced Subscription Manager for QX, Loon, Surge, Stash and Shadowrocket.",
|
||||
"main": "src/main.js",
|
||||
"packageManager": "pnpm@11.0.9",
|
||||
|
||||
@@ -13,7 +13,11 @@ import {
|
||||
getRandomPort,
|
||||
numberToString,
|
||||
} from '@/utils';
|
||||
import PROXY_PROCESSORS, { ApplyProcessor } from './processors';
|
||||
import PROXY_PROCESSORS, {
|
||||
ApplyProcessor,
|
||||
ApplyResponseTransformer,
|
||||
isResponseTransformerType,
|
||||
} from './processors';
|
||||
import PROXY_PREPROCESSORS from './preprocessors';
|
||||
import PROXY_PRODUCERS from './producers';
|
||||
import PROXY_PARSERS from './parsers';
|
||||
@@ -114,6 +118,16 @@ async function processFn(
|
||||
) {
|
||||
let context = {};
|
||||
for (const item of operators) {
|
||||
if (isResponseTransformerType(item.type)) {
|
||||
$.log(
|
||||
`Skipping response transformer during proxy/file processing: "${
|
||||
item.type
|
||||
}" with arguments:\n >>> ${
|
||||
JSON.stringify(item.args, null, 2) || 'None'
|
||||
}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (item.disabled) {
|
||||
$.log(
|
||||
`Skipping disabled operator: "${
|
||||
@@ -128,94 +142,7 @@ async function processFn(
|
||||
let script;
|
||||
let $arguments = {};
|
||||
if (item.type.indexOf('Script') !== -1) {
|
||||
const { mode, content } = item.args;
|
||||
if (mode === 'link') {
|
||||
let url = content || '';
|
||||
// extract link arguments
|
||||
const rawArgs = url.split('#');
|
||||
if (rawArgs.length > 1) {
|
||||
try {
|
||||
// 支持 `#${encodeURIComponent(JSON.stringify({arg1: "1"}))}`
|
||||
$arguments = JSON.parse(decodeURIComponent(rawArgs[1]));
|
||||
} catch (e) {
|
||||
for (const pair of rawArgs[1].split('&')) {
|
||||
const key = pair.split('=')[0];
|
||||
const value = pair.split('=')[1];
|
||||
// 部分兼容之前的逻辑 const value = pair.split('=')[1] || true;
|
||||
$arguments[key] =
|
||||
value == null || value === ''
|
||||
? true
|
||||
: decodeURIComponent(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
url = `${url.split('#')[0]}${
|
||||
rawArgs[2]
|
||||
? `#${rawArgs[2]}`
|
||||
: $arguments?.noCache != null ||
|
||||
$arguments?.insecure != null
|
||||
? `#${rawArgs[1]}`
|
||||
: ''
|
||||
}`;
|
||||
const downloadUrlMatch = url
|
||||
.split('#')[0]
|
||||
.match(/^\/api\/(file|module)\/(.+)/);
|
||||
if (downloadUrlMatch) {
|
||||
let type = '';
|
||||
try {
|
||||
type = downloadUrlMatch?.[1];
|
||||
let name = downloadUrlMatch?.[2];
|
||||
if (name == null) {
|
||||
throw new Error(`本地 ${type} URL 无效: ${url}`);
|
||||
}
|
||||
name = decodeURIComponent(name);
|
||||
const key = type === 'module' ? MODULES_KEY : FILES_KEY;
|
||||
const item = findByName($.read(key), name);
|
||||
if (!item) {
|
||||
throw new Error(`找不到 ${type}: ${name}`);
|
||||
}
|
||||
|
||||
if (type === 'module') {
|
||||
script = item.content;
|
||||
} else {
|
||||
script = await produceArtifact({
|
||||
type: 'file',
|
||||
name,
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
$.error(
|
||||
`Error when loading ${type}: ${item.args.content}.\n Reason: ${err}`,
|
||||
);
|
||||
throw new Error(`无法加载 ${type}: ${url}`);
|
||||
}
|
||||
} else if (url?.startsWith('/')) {
|
||||
try {
|
||||
const fs = eval(`require("fs")`);
|
||||
script = fs.readFileSync(url.split('#')[0], 'utf8');
|
||||
// $.info(`Script loaded: >>>\n ${script}`);
|
||||
} catch (err) {
|
||||
$.error(
|
||||
`Error when reading local script: ${item.args.content}.\n Reason: ${err}`,
|
||||
);
|
||||
throw new Error(`无法从该路径读取脚本文件: ${url}`);
|
||||
}
|
||||
} else {
|
||||
// if this is a remote script, download it
|
||||
try {
|
||||
script = await download(url);
|
||||
// $.info(`Script loaded: >>>\n ${script}`);
|
||||
} catch (err) {
|
||||
$.error(
|
||||
`Error when downloading remote script: ${item.args.content}.\n Reason: ${err}`,
|
||||
);
|
||||
throw new Error(`无法下载脚本: ${url}`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
script = content;
|
||||
$arguments = item.args.arguments || {};
|
||||
}
|
||||
({ script, $arguments } = await loadScriptItem(item));
|
||||
}
|
||||
|
||||
if (!PROXY_PROCESSORS[item.type]) {
|
||||
@@ -246,6 +173,172 @@ async function processFn(
|
||||
return proxies;
|
||||
}
|
||||
|
||||
async function processResponseFn(
|
||||
response,
|
||||
operators = [],
|
||||
targetPlatform,
|
||||
source,
|
||||
$options,
|
||||
) {
|
||||
let context = {};
|
||||
let output = normalizeResponse(response);
|
||||
for (const item of operators) {
|
||||
if (!isResponseTransformerType(item.type)) continue;
|
||||
if (item.disabled) {
|
||||
$.log(
|
||||
`Skipping disabled response transformer: "${
|
||||
item.type
|
||||
}" with arguments:\n >>> ${
|
||||
JSON.stringify(item.args, null, 2) || 'None'
|
||||
}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const { script, $arguments } = await loadScriptItem(item);
|
||||
$.log(
|
||||
`Applying "${item.type}" with arguments:\n >>> ${
|
||||
JSON.stringify(item.args, null, 2) || 'None'
|
||||
}`,
|
||||
);
|
||||
const transformer = PROXY_PROCESSORS[item.type](
|
||||
script,
|
||||
targetPlatform,
|
||||
$arguments,
|
||||
source,
|
||||
$options,
|
||||
context,
|
||||
);
|
||||
output = normalizeResponse(
|
||||
await ApplyResponseTransformer(transformer, output),
|
||||
);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
async function loadScriptItem(item) {
|
||||
let script;
|
||||
let $arguments = {};
|
||||
const { mode, content } = item.args || {};
|
||||
if (mode === 'link') {
|
||||
let url = content || '';
|
||||
// extract link arguments
|
||||
const rawArgs = url.split('#');
|
||||
if (rawArgs.length > 1) {
|
||||
try {
|
||||
// 支持 `#${encodeURIComponent(JSON.stringify({arg1: "1"}))}`
|
||||
$arguments = JSON.parse(decodeURIComponent(rawArgs[1]));
|
||||
} catch (e) {
|
||||
for (const pair of rawArgs[1].split('&')) {
|
||||
const key = pair.split('=')[0];
|
||||
const value = pair.split('=')[1];
|
||||
// 部分兼容之前的逻辑 const value = pair.split('=')[1] || true;
|
||||
$arguments[key] =
|
||||
value == null || value === ''
|
||||
? true
|
||||
: decodeURIComponent(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
url = `${url.split('#')[0]}${
|
||||
rawArgs[2]
|
||||
? `#${rawArgs[2]}`
|
||||
: $arguments?.noCache != null || $arguments?.insecure != null
|
||||
? `#${rawArgs[1]}`
|
||||
: ''
|
||||
}`;
|
||||
const downloadUrlMatch = url
|
||||
.split('#')[0]
|
||||
.match(/^\/api\/(file|module)\/(.+)/);
|
||||
if (downloadUrlMatch) {
|
||||
let type = '';
|
||||
try {
|
||||
type = downloadUrlMatch?.[1];
|
||||
let name = downloadUrlMatch?.[2];
|
||||
if (name == null) {
|
||||
throw new Error(`本地 ${type} URL 无效: ${url}`);
|
||||
}
|
||||
name = decodeURIComponent(name);
|
||||
const key = type === 'module' ? MODULES_KEY : FILES_KEY;
|
||||
const localItem = findByName($.read(key), name);
|
||||
if (!localItem) {
|
||||
throw new Error(`找不到 ${type}: ${name}`);
|
||||
}
|
||||
|
||||
if (type === 'module') {
|
||||
script = localItem.content;
|
||||
} else {
|
||||
script = await produceArtifact({
|
||||
type: 'file',
|
||||
name,
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
$.error(
|
||||
`Error when loading ${type}: ${item.args.content}.\n Reason: ${err}`,
|
||||
);
|
||||
throw new Error(`无法加载 ${type}: ${url}`);
|
||||
}
|
||||
} else if (url?.startsWith('/')) {
|
||||
try {
|
||||
const fs = eval(`require("fs")`);
|
||||
script = fs.readFileSync(url.split('#')[0], 'utf8');
|
||||
// $.info(`Script loaded: >>>\n ${script}`);
|
||||
} catch (err) {
|
||||
$.error(
|
||||
`Error when reading local script: ${item.args.content}.\n Reason: ${err}`,
|
||||
);
|
||||
throw new Error(`无法从该路径读取脚本文件: ${url}`);
|
||||
}
|
||||
} else {
|
||||
// if this is a remote script, download it
|
||||
try {
|
||||
script = await download(url);
|
||||
// $.info(`Script loaded: >>>\n ${script}`);
|
||||
} catch (err) {
|
||||
$.error(
|
||||
`Error when downloading remote script: ${item.args.content}.\n Reason: ${err}`,
|
||||
);
|
||||
throw new Error(`无法下载脚本: ${url}`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
script = content;
|
||||
$arguments = item.args?.arguments || {};
|
||||
}
|
||||
return { script, $arguments };
|
||||
}
|
||||
|
||||
function normalizeResponse(response = {}) {
|
||||
let headers = response.header || response.headers || {};
|
||||
if (!headers || typeof headers !== 'object') headers = {};
|
||||
const normalized = {
|
||||
status: response.status || response.statusCode || 200,
|
||||
body: Object.prototype.hasOwnProperty.call(response, 'body')
|
||||
? response.body
|
||||
: '',
|
||||
};
|
||||
Object.defineProperty(normalized, 'headers', {
|
||||
enumerable: true,
|
||||
get() {
|
||||
return headers;
|
||||
},
|
||||
set(value) {
|
||||
headers = value && typeof value === 'object' ? value : {};
|
||||
},
|
||||
});
|
||||
Object.defineProperty(normalized, 'header', {
|
||||
enumerable: true,
|
||||
get() {
|
||||
return headers;
|
||||
},
|
||||
set(value) {
|
||||
headers = value && typeof value === 'object' ? value : {};
|
||||
},
|
||||
});
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function produce(proxies, targetPlatform, type, opts = {}) {
|
||||
const producer = PROXY_PRODUCERS[targetPlatform];
|
||||
if (!producer) {
|
||||
@@ -518,6 +611,7 @@ function getRootHeaderProxyLabel(proxy) {
|
||||
export const ProxyUtils = {
|
||||
parse,
|
||||
process: processFn,
|
||||
processResponse: processResponseFn,
|
||||
produce,
|
||||
ipAddress,
|
||||
getRandomPort,
|
||||
|
||||
@@ -23,6 +23,12 @@ import {
|
||||
normalizeFlowHeader,
|
||||
} from '@/utils/flow';
|
||||
|
||||
export const RESPONSE_TRANSFORMER = 'Response Transformer';
|
||||
|
||||
export function isResponseTransformerType(type) {
|
||||
return type === RESPONSE_TRANSFORMER;
|
||||
}
|
||||
|
||||
function trimWrap(str) {
|
||||
if (str.startsWith('<') && str.endsWith('>')) {
|
||||
return str.slice(1, -1);
|
||||
@@ -1098,6 +1104,51 @@ function ScriptFilter(
|
||||
};
|
||||
}
|
||||
|
||||
function ResponseTransformer(
|
||||
script,
|
||||
targetPlatform,
|
||||
$arguments,
|
||||
source,
|
||||
$options,
|
||||
context,
|
||||
) {
|
||||
context.source = source;
|
||||
context.env = env;
|
||||
return {
|
||||
name: RESPONSE_TRANSFORMER,
|
||||
func: async (res) => {
|
||||
let output = res;
|
||||
await (async function () {
|
||||
const transformFunction = createDynamicFunction(
|
||||
'transformFunction',
|
||||
script,
|
||||
$arguments,
|
||||
$options,
|
||||
);
|
||||
output = transformFunction(res, context);
|
||||
})();
|
||||
return output;
|
||||
},
|
||||
shortcutFunc: async (res) => {
|
||||
let output = res;
|
||||
await (async function () {
|
||||
const transformFunction = createDynamicFunction(
|
||||
'transformFunction',
|
||||
`async function transformFunction(res = {}, context) {
|
||||
let $res = res
|
||||
${script}
|
||||
return $res
|
||||
}`,
|
||||
$arguments,
|
||||
$options,
|
||||
);
|
||||
output = transformFunction(res, context);
|
||||
})();
|
||||
return output;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export default {
|
||||
'Useless Filter': UselessFilter,
|
||||
'Region Filter': RegionFilter,
|
||||
@@ -1113,10 +1164,46 @@ export default {
|
||||
'Regex Rename Operator': RegexRenameOperator,
|
||||
'Regex Delete Operator': RegexDeleteOperator,
|
||||
'Script Operator': ScriptOperator,
|
||||
[RESPONSE_TRANSFORMER]: ResponseTransformer,
|
||||
'Handle Duplicate Operator': HandleDuplicateOperator,
|
||||
'Resolve Domain Operator': ResolveDomainOperator,
|
||||
};
|
||||
|
||||
export async function ApplyResponseTransformer(transformer, res) {
|
||||
let output = res;
|
||||
try {
|
||||
const output_ = await transformer.func(output);
|
||||
if (output_) output = output_;
|
||||
} catch (err) {
|
||||
let funcErr = '';
|
||||
const funcErrMsg = `${err.message ?? err}`;
|
||||
if (!funcErrMsg.includes('$res is not defined')) {
|
||||
$.error(
|
||||
`Cannot apply ${transformer.name}(function transformFunction)! Reason: ${err}`,
|
||||
);
|
||||
funcErr = `执行 function transformFunction 失败 ${funcErrMsg}; `;
|
||||
}
|
||||
try {
|
||||
const output_ = await transformer.shortcutFunc(output);
|
||||
if (output_) output = output_;
|
||||
} catch (shortcutErr) {
|
||||
$.error(
|
||||
`Cannot apply ${transformer.name}(shortcut script)! Reason: ${shortcutErr}`,
|
||||
);
|
||||
let shortcutErrText = '';
|
||||
const shortcutErrMsg = `${shortcutErr.message ?? shortcutErr}`;
|
||||
if (funcErr && shortcutErrMsg === funcErrMsg) {
|
||||
shortcutErrText = '';
|
||||
funcErr = `执行失败 ${funcErrMsg}`;
|
||||
} else {
|
||||
shortcutErrText = `执行快捷脚本失败 ${shortcutErrMsg}`;
|
||||
}
|
||||
throw new Error(`响应修改 ${funcErr}${shortcutErrText}`);
|
||||
}
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
async function ApplyFilter(filter, objs) {
|
||||
// select proxies
|
||||
let selected = FULL(objs.length, true);
|
||||
|
||||
@@ -11,6 +11,7 @@ import { produceArtifact } from '@/restful/sync';
|
||||
import { isIPv4, isIPv6 } from '@/utils';
|
||||
import { getISO } from '@/utils/geo';
|
||||
import env from '@/utils/env';
|
||||
import { applyResponseTransformers } from '@/restful/response-transformer';
|
||||
|
||||
function buildEmptyNezhaPayload() {
|
||||
return JSON.stringify(
|
||||
@@ -417,7 +418,15 @@ async function downloadSubscription(req, res) {
|
||||
if ($options?._res?.status) {
|
||||
res.status($options._res.status);
|
||||
}
|
||||
res.send(output);
|
||||
const body = await applyResponseTransformers({
|
||||
res,
|
||||
body: output,
|
||||
process: sub.process,
|
||||
targetPlatform: platform,
|
||||
source: { [sub.name]: sub },
|
||||
$options,
|
||||
});
|
||||
res.send(body);
|
||||
} catch (err) {
|
||||
$.notify(
|
||||
`🌍 Sub-Store 下载订阅失败`,
|
||||
@@ -736,7 +745,15 @@ async function downloadCollection(req, res) {
|
||||
if ($options?._res?.status) {
|
||||
res.status($options._res.status);
|
||||
}
|
||||
res.send(output);
|
||||
const body = await applyResponseTransformers({
|
||||
res,
|
||||
body: output,
|
||||
process: collection.process,
|
||||
targetPlatform: platform,
|
||||
source: { _collection: collection },
|
||||
$options,
|
||||
});
|
||||
res.send(body);
|
||||
} catch (err) {
|
||||
$.notify(
|
||||
`🌍 Sub-Store 下载组合订阅失败`,
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
import { produceArtifact } from '@/restful/sync';
|
||||
import { archiveFile } from '@/utils/archive';
|
||||
import { formatDateTime } from '@/utils';
|
||||
import { applyResponseTransformers } from '@/restful/response-transformer';
|
||||
|
||||
export default function register($app) {
|
||||
if (!$.read(FILES_KEY)) $.write([], FILES_KEY);
|
||||
@@ -202,7 +203,14 @@ async function getFile(req, res, next) {
|
||||
if (output?.$options?._res?.status) {
|
||||
res.status(output.$options._res.status);
|
||||
}
|
||||
res.send(output?.$content ?? '');
|
||||
const body = await applyResponseTransformers({
|
||||
res,
|
||||
body: output?.$content ?? '',
|
||||
process: file.process,
|
||||
source: { $file: file },
|
||||
$options: output?.$options ?? $options,
|
||||
});
|
||||
res.send(body);
|
||||
} catch (err) {
|
||||
$.notify(
|
||||
`🌍 Sub-Store 下载文件失败`,
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { ProxyUtils } from '@/core/proxy-utils';
|
||||
|
||||
function getCurrentHeaders(res) {
|
||||
return typeof res.getHeaders === 'function' ? { ...res.getHeaders() } : {};
|
||||
}
|
||||
|
||||
function setHeaders(res, currentHeaders, nextHeaders = {}) {
|
||||
for (const key of Object.keys(currentHeaders)) {
|
||||
if (!Object.prototype.hasOwnProperty.call(nextHeaders, key)) {
|
||||
res.removeHeader(key);
|
||||
}
|
||||
}
|
||||
for (const [key, value] of Object.entries(nextHeaders)) {
|
||||
if (value == null) {
|
||||
res.removeHeader(key);
|
||||
} else {
|
||||
res.set(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function setStatus(res, status) {
|
||||
const statusCode = Number(status);
|
||||
if (
|
||||
Number.isInteger(statusCode) &&
|
||||
statusCode >= 100 &&
|
||||
statusCode <= 599
|
||||
) {
|
||||
res.status(statusCode);
|
||||
}
|
||||
}
|
||||
|
||||
export async function applyResponseTransformers({
|
||||
res,
|
||||
body,
|
||||
process,
|
||||
targetPlatform,
|
||||
source,
|
||||
$options,
|
||||
}) {
|
||||
const currentHeaders = getCurrentHeaders(res);
|
||||
const transformed = await ProxyUtils.processResponse(
|
||||
{
|
||||
status: res.statusCode || 200,
|
||||
headers: currentHeaders,
|
||||
body,
|
||||
},
|
||||
process || [],
|
||||
targetPlatform,
|
||||
source,
|
||||
$options,
|
||||
);
|
||||
setHeaders(res, currentHeaders, transformed.header || transformed.headers);
|
||||
setStatus(res, transformed.status || transformed.statusCode);
|
||||
return transformed.body;
|
||||
}
|
||||
@@ -48,6 +48,9 @@ function createResponse(routePath) {
|
||||
delete this.headers[key];
|
||||
return this;
|
||||
},
|
||||
getHeaders() {
|
||||
return this.headers;
|
||||
},
|
||||
send(payload) {
|
||||
this.sent = payload;
|
||||
return this;
|
||||
@@ -63,7 +66,7 @@ function createResponse(routePath) {
|
||||
};
|
||||
}
|
||||
|
||||
async function downloadSubscription(query) {
|
||||
async function requestDownloadSubscription(query) {
|
||||
const handler = getHandler('/download/:name');
|
||||
const res = createResponse('/download/:name');
|
||||
|
||||
@@ -80,6 +83,11 @@ async function downloadSubscription(query) {
|
||||
res,
|
||||
);
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
async function downloadSubscription(query) {
|
||||
const res = await requestDownloadSubscription(query);
|
||||
return res.sent;
|
||||
}
|
||||
|
||||
@@ -224,4 +232,44 @@ describe('download routes', function () {
|
||||
'Shared Mihomo=external,exec="/usr/local/bin/mihomo"',
|
||||
);
|
||||
});
|
||||
|
||||
it('applies shortcut response transformers before sending subscription output', async function () {
|
||||
state[SUBS_KEY][0].process = [
|
||||
{
|
||||
type: 'Response Transformer',
|
||||
args: {
|
||||
mode: 'script',
|
||||
content:
|
||||
"$res.status = 202\n$res.header['x-test'] = 'ok'\n$res.body = 'changed'",
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const res = await requestDownloadSubscription({ target: 'JSON' });
|
||||
|
||||
expect(res.statusCode).to.equal(202);
|
||||
expect(res.headers['x-test']).to.equal('ok');
|
||||
expect(res.sent).to.equal('changed');
|
||||
});
|
||||
|
||||
it('applies transformFunction response transformers before sending subscription output', async function () {
|
||||
state[SUBS_KEY][0].process = [
|
||||
{
|
||||
type: 'Response Transformer',
|
||||
args: {
|
||||
mode: 'script',
|
||||
content: `async function transformFunction(res, context) {
|
||||
res.status = 201;
|
||||
res.body = context.source['local-vless'].name;
|
||||
return res;
|
||||
}`,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const res = await requestDownloadSubscription({ target: 'JSON' });
|
||||
|
||||
expect(res.statusCode).to.equal(201);
|
||||
expect(res.sent).to.equal('local-vless');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,174 @@
|
||||
import { expect } from 'chai';
|
||||
import { after, before, beforeEach, describe, it } from 'mocha';
|
||||
|
||||
import { FILES_KEY } from '@/constants';
|
||||
|
||||
let $;
|
||||
let registerFileRoutes;
|
||||
let originalError;
|
||||
let originalInfo;
|
||||
let originalNotify;
|
||||
let originalRead;
|
||||
let originalWarn;
|
||||
let originalWrite;
|
||||
let state;
|
||||
|
||||
function createRouteApp() {
|
||||
const handlers = new Map();
|
||||
const methods = ['get', 'post', 'put', 'patch', 'delete'];
|
||||
|
||||
const app = {
|
||||
handlers,
|
||||
route(pattern) {
|
||||
const chain = {};
|
||||
methods.forEach((method) => {
|
||||
chain[method] = (handler) => {
|
||||
handlers.set(`${method.toUpperCase()} ${pattern}`, handler);
|
||||
return chain;
|
||||
};
|
||||
});
|
||||
return chain;
|
||||
},
|
||||
};
|
||||
|
||||
methods.forEach((method) => {
|
||||
app[method] = (pattern, handler) => {
|
||||
handlers.set(`${method.toUpperCase()} ${pattern}`, handler);
|
||||
return app;
|
||||
};
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
function getHandler(pattern) {
|
||||
const app = createRouteApp();
|
||||
registerFileRoutes(app);
|
||||
return app.handlers.get(`GET ${pattern}`);
|
||||
}
|
||||
|
||||
function createResponse(routePath) {
|
||||
return {
|
||||
headers: {},
|
||||
req: {
|
||||
route: {
|
||||
path: routePath,
|
||||
},
|
||||
},
|
||||
sent: null,
|
||||
statusCode: 200,
|
||||
removeHeader(key) {
|
||||
delete this.headers[key];
|
||||
return this;
|
||||
},
|
||||
getHeaders() {
|
||||
return this.headers;
|
||||
},
|
||||
send(payload) {
|
||||
this.sent = payload;
|
||||
return this;
|
||||
},
|
||||
set(key, value) {
|
||||
this.headers[key] = value;
|
||||
return this;
|
||||
},
|
||||
status(code) {
|
||||
this.statusCode = code;
|
||||
return this;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function requestFile(query = {}) {
|
||||
const handler = getHandler('/api/file/:name');
|
||||
const res = createResponse('/api/file/:name');
|
||||
|
||||
await handler(
|
||||
{
|
||||
body: {},
|
||||
headers: {},
|
||||
method: 'GET',
|
||||
params: { name: 'local-file' },
|
||||
path: '/api/file/local-file',
|
||||
query,
|
||||
url: '/api/file/local-file',
|
||||
},
|
||||
res,
|
||||
);
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
describe('file routes', function () {
|
||||
before(async function () {
|
||||
({ default: $ } = require('@/core/app'));
|
||||
({ default: registerFileRoutes } = require('@/restful/file'));
|
||||
|
||||
originalRead = $.read.bind($);
|
||||
originalWrite = $.write.bind($);
|
||||
originalInfo = $.info.bind($);
|
||||
originalWarn = $.warn.bind($);
|
||||
originalError = $.error.bind($);
|
||||
originalNotify = $.notify.bind($);
|
||||
});
|
||||
|
||||
after(function () {
|
||||
if ($) {
|
||||
$.read = originalRead;
|
||||
$.write = originalWrite;
|
||||
$.info = originalInfo;
|
||||
$.warn = originalWarn;
|
||||
$.error = originalError;
|
||||
$.notify = originalNotify;
|
||||
}
|
||||
});
|
||||
|
||||
beforeEach(function () {
|
||||
state = {
|
||||
[FILES_KEY]: [
|
||||
{
|
||||
name: 'local-file',
|
||||
source: 'local',
|
||||
content: 'base',
|
||||
process: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
$.read = (key) => state[key] || [];
|
||||
$.write = (data, key) => {
|
||||
state[key] = data;
|
||||
return true;
|
||||
};
|
||||
$.info = () => {};
|
||||
$.warn = () => {};
|
||||
$.error = () => {};
|
||||
$.notify = () => {};
|
||||
});
|
||||
|
||||
it('passes Script Operator $options changes to response transformers', async function () {
|
||||
state[FILES_KEY][0].process = [
|
||||
{
|
||||
type: 'Script Operator',
|
||||
args: {
|
||||
mode: 'script',
|
||||
content:
|
||||
"$options.fromOperator = 'carried'\n$content = `${$content}-script`",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'Response Transformer',
|
||||
args: {
|
||||
mode: 'script',
|
||||
content:
|
||||
"$res.header['x-from-options'] = $options.fromOperator\n$res.body = `${$res.body}-${$options.fromOperator}`",
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const res = await requestFile();
|
||||
|
||||
expect(res.headers['x-from-options']).to.equal('carried');
|
||||
expect(res.sent).to.equal('base-script-carried');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user