MCPcopy Create free account
hub / github.com/chavyleung/scripts / apiRunScript

Function apiRunScript

box/chavy.boxjs.js:920–980  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

918}
919
920async function apiRunScript() {
921 // 取消勿扰模式
922 $.isMute = false
923 const opts = $.toObj($request.body)
924 const httpapi = $.getdata('@chavy_boxjs_userCfgs.httpapi')
925 const ishttpapi = /.*?@.*?:[0-9]+/.test(httpapi)
926 let script_text = null
927 if (opts.isRemote) {
928 await $.getScript(opts.url).then((script) => (script_text = script))
929 } else {
930 script_text = opts.script
931 }
932 if (opts.argument) {
933 script_text = `globalThis.$argument=\`${opts.argument}\`;${script_text}`
934 }
935 if (
936 $.isSurge() &&
937 !$.isLoon() &&
938 !$.isShadowrocket() &&
939 !$.isStash() &&
940 ishttpapi
941 ) {
942 const runOpts = { timeout: opts.timeout }
943 await $.runScript(script_text, runOpts).then(
944 (resp) => ($.json = JSON.parse(resp))
945 )
946 } else {
947 const result = await new Promise((resolve) => {
948 $eval_env.resolve = resolve
949 // 避免被执行脚本误认为是 rewrite 环境
950 // 所以需要 `$request = undefined`
951 $eval_env.request = $request
952 $request = undefined
953 // 重写 console.log, 把日志记录到 $eval_env.cached_logs
954 $eval_env.cached_logs = []
955 console.cloned_log = console.log
956 console.log = (l) => {
957 console.cloned_log(l)
958 $eval_env.cached_logs.push(l)
959 }
960 // 重写脚本内的 $done, 调用 $done() 即是调用 $eval_env.resolve()
961 script_text = script_text.replace(/\$done/g, '$eval_env.resolve')
962 script_text = script_text.replace(/\$\.done/g, '$eval_env.resolve')
963 try {
964 eval(script_text)
965 } catch (e) {
966 $eval_env.cached_logs.push(e)
967 resolve()
968 }
969 })
970 // 还原 console.log
971 console.log = console.cloned_log
972 // 还原 $request
973 $request = $eval_env.request
974 // 返回数据
975 $.json = {
976 result,
977 output: $eval_env.cached_logs.join('\n')

Callers

nothing calls this directly

Calls 8

toObjMethod · 0.45
getdataMethod · 0.45
getScriptMethod · 0.45
isSurgeMethod · 0.45
isLoonMethod · 0.45
isShadowrocketMethod · 0.45
isStashMethod · 0.45
runScriptMethod · 0.45

Tested by

no test coverage detected