MCPcopy
hub / github.com/chavyleung/scripts / apiRunScript

Function apiRunScript

chavy.box.js:865–925  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

863}
864
865async function apiRunScript() {
866 // 取消勿扰模式
867 $.isMute = false
868 const opts = $.toObj($request.body)
869 const httpapi = $.getdata('@chavy_boxjs_userCfgs.httpapi')
870 const ishttpapi = /.*?@.*?:[0-9]+/.test(httpapi)
871 let script_text = null
872 if (opts.isRemote) {
873 await $.getScript(opts.url).then((script) => (script_text = script))
874 } else {
875 script_text = opts.script
876 }
877 if (opts.argument) {
878 script_text = `globalThis.$argument=\`${opts.argument}\`;${script_text}`
879 }
880 if (
881 $.isSurge() &&
882 !$.isLoon() &&
883 !$.isShadowrocket() &&
884 !$.isStash() &&
885 ishttpapi
886 ) {
887 const runOpts = { timeout: opts.timeout }
888 await $.runScript(script_text, runOpts).then(
889 (resp) => ($.json = JSON.parse(resp))
890 )
891 } else {
892 const result = await new Promise((resolve) => {
893 $eval_env.resolve = resolve
894 // 避免被执行脚本误认为是 rewrite 环境
895 // 所以需要 `$request = undefined`
896 $eval_env.request = $request
897 $request = undefined
898 // 重写 console.log, 把日志记录到 $eval_env.cached_logs
899 $eval_env.cached_logs = []
900 console.cloned_log = console.log
901 console.log = (l) => {
902 console.cloned_log(l)
903 $eval_env.cached_logs.push(l)
904 }
905 // 重写脚本内的 $done, 调用 $done() 即是调用 $eval_env.resolve()
906 script_text = script_text.replace(/\$done/g, '$eval_env.resolve')
907 script_text = script_text.replace(/\$\.done/g, '$eval_env.resolve')
908 try {
909 eval(script_text)
910 } catch (e) {
911 $eval_env.cached_logs.push(e)
912 resolve()
913 }
914 })
915 // 还原 console.log
916 console.log = console.cloned_log
917 // 还原 $request
918 $request = $eval_env.request
919 // 返回数据
920 $.json = {
921 result,
922 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

Used in the wild real call sites across dependent graphs

searching dependent graphs…