"添加前端模板和运行代码模块"

This commit is contained in:
Codex
2026-06-01 13:43:09 +08:00
parent 24045274ad
commit 8092c4b1f8
587 changed files with 99761 additions and 0 deletions

View File

@@ -0,0 +1,92 @@
// @ts-nocheck
// ES模块格式支持import/export语句
// 保存原始console.log
const originalConsoleLog = console.log;
let logs = [];
// 替换console.log以捕获日志
console.log = function() {
// 将参数转换为字符串并连接它们
const message = Array.from(arguments).map(arg =>
typeof arg === 'object' && arg !== null ? JSON.stringify(arg) : String(arg)
).join(' ');
// 存储日志
logs.push(message);
// 如果显示日志,也输出到原始控制台
if ({{SHOW_LOGS}}) {
originalConsoleLog.apply(console, arguments);
}
};
// 异步读取输入参数的函数
async function readInputParams() {
let input = {};
try {
const inputFile = Deno.env.get("INPUT_JSON_FILE");
if (inputFile) {
const inputJson = await Deno.readTextFile(inputFile);
input = JSON.parse(inputJson);
console.log("接收到的参数:", JSON.stringify(input));
} else {
// 兼容旧的环境变量方式
const inputJson = Deno.env.get("INPUT_JSON");
if (inputJson) {
input = JSON.parse(inputJson);
console.log("接收到的参数:", JSON.stringify(input));
}
}
} catch (error) {
console.error("解析输入参数失败:", error);
}
return input;
}
// 用户代码
{{USER_CODE}}
// 执行handler函数并获取结果
let result = null;
// 异步立即执行函数
(async () => {
// 读取输入参数
const input = await readInputParams();
try {
// 优先检查main函数
if (typeof main === 'function') {
// 检查main是否是异步函数
if (main.constructor.name === 'AsyncFunction') {
result = await main(input);
} else {
result = main(input);
}
} else if (typeof handler === 'function') {
// 如果没有main函数检查handler
if (handler.constructor.name === 'AsyncFunction') {
result = await handler(input);
} else {
result = handler(input);
}
}else{
throw new Error("没有找到main或handler函数");
}
// 打印最终输出为JSON
originalConsoleLog(JSON.stringify({
logs: logs,
result: result !== undefined ? (typeof result === 'object' ? JSON.stringify(result) : String(result)) : null,
error: null
}));
} catch (error) {
// 处理错误
originalConsoleLog(JSON.stringify({
logs: logs,
result: null,
error: error.toString()
}));
}
})();

View File

@@ -0,0 +1,93 @@
// @ts-nocheck
// 普通脚本格式
// 保存原始console.log
const originalConsoleLog = console.log;
let logs = [];
// 替换console.log以捕获日志
console.log = function() {
// 将参数转换为字符串并连接它们
const message = Array.from(arguments).map(arg =>
typeof arg === 'object' && arg !== null ? JSON.stringify(arg) : String(arg)
).join(' ');
// 存储日志
logs.push(message);
// 如果显示日志,也输出到原始控制台
if ({{SHOW_LOGS}}) {
originalConsoleLog.apply(console, arguments);
}
};
// 异步读取输入参数的函数
async function readInputParams() {
let input = {};
try {
const inputFile = Deno.env.get("INPUT_JSON_FILE");
if (inputFile) {
const inputJson = await Deno.readTextFile(inputFile);
input = JSON.parse(inputJson);
console.log("接收到的参数:", JSON.stringify(input));
} else {
// 兼容旧的环境变量方式
const inputJson = Deno.env.get("INPUT_JSON");
if (inputJson) {
input = JSON.parse(inputJson);
console.log("接收到的参数:", JSON.stringify(input));
}
}
} catch (error) {
console.error("解析输入参数失败:", error);
}
return input;
}
// 异步立即执行函数
(async () => {
// 读取输入参数
const input = await readInputParams();
try {
// 用户代码开始
{{USER_CODE}}
// 用户代码结束
// 执行函数并获取结果
let result = null;
// 优先检查main函数
if (typeof main === 'function') {
// 检查main是否是异步函数
if (main.constructor.name === 'AsyncFunction') {
result = await main(input);
} else {
result = main(input);
}
} else if (typeof handler === 'function') {
// 如果没有main函数检查handler
if (handler.constructor.name === 'AsyncFunction') {
result = await handler(input);
} else {
result = handler(input);
}
} else {
throw new Error("没有找到main或handler函数");
}
// 打印最终输出为JSON
originalConsoleLog(JSON.stringify({
logs: logs,
result: result !== undefined ? (typeof result === 'object' ? JSON.stringify(result) : String(result)) : null,
error: null
}));
} catch (error) {
// 处理错误
originalConsoleLog(JSON.stringify({
logs: logs,
result: null,
error: error.toString()
}));
}
})();

View File

@@ -0,0 +1,134 @@
import sys
import json
import os
import logging
from io import StringIO
# 保存原始的stdout
original_stdout = sys.stdout
logs = []
# 创建一个StringIO对象来捕获输出
class LogCapture:
def __init__(self, show_logs=False):
self.buffer = StringIO()
self.show_logs = show_logs
def write(self, text):
if text.strip(): # 忽略空行
logs.append(text.rstrip())
if self.show_logs:
original_stdout.write(text)
def flush(self):
self.buffer.flush()
if self.show_logs:
original_stdout.flush()
# 替换sys.stdout为我们的捕获器
sys.stdout = LogCapture(show_logs={{SHOW_LOGS}})
# 配置logging将日志输出重定向到我们的捕获器
class LoggingHandler(logging.Handler):
def emit(self, record):
msg = self.format(record)
print(f"[{record.levelname}] {msg}")
# 配置根日志记录器
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
# 移除所有现有的处理程序
for handler in root_logger.handlers[:]:
root_logger.removeHandler(handler)
# 添加我们自定义的处理程序
handler = LoggingHandler()
handler.setFormatter(logging.Formatter('%(message)s'))
root_logger.addHandler(handler)
# 从环境变量获取输入参数
args = {}
has_input = False
try:
# 优先从临时文件读取参数
input_file = os.environ.get('INPUT_JSON_FILE')
if input_file:
with open(input_file, 'r', encoding='utf-8') as f:
input_json = f.read()
args = json.loads(input_json)
has_input = True
print(f"接收到的参数: {args}")
else:
# 兼容旧的环境变量方式
input_json = os.environ.get('INPUT_JSON')
if input_json:
args = json.loads(input_json)
has_input = True
print(f"接收到的参数: {args}")
# 确保参数同时可以通过args直接访问也可以通过args.get("params")访问
# 如果args中没有params键但有其他键则将整个args作为params的值
if has_input and "params" not in args and len(args) > 0:
args["params"] = args.copy()
# 如果params存在但为None则初始化为空字典
elif has_input and args.get("params") is None:
args["params"] = {}
except Exception as e:
print(f"解析输入参数失败: {e}")
# 用户代码开始
{{USER_CODE}}
try:
# 执行handler函数或main函数并获取结果
result = None
if 'handler' in globals() and callable(globals()['handler']):
# 优先使用 handler 函数
try:
if has_input:
result = handler(args)
else:
# handler 函数不接受参数,无参数调用
result = handler()
# 确保结果不为 None
if result is None:
print("警告: handler 函数返回了 None")
except Exception as e:
print(f"执行 handler 函数时出错: {e}")
elif 'main' in globals() and callable(globals()['main']):
# 如果没有 handler 函数,尝试使用 main 函数
try:
result = main(args)
except Exception as e:
print(f"执行 main 函数时出错: {e}")
# 打印最终输出为JSON
sys.stdout = original_stdout
# 根据结果类型选择合适的处理方式
result_json = None
if result is not None:
if isinstance(result, (dict, list)):
# 如果是字典或列表,直接使用 json.dumps 序列化
result_json = json.dumps(result)
elif isinstance(result, (int, float, bool)) or result is None:
# 如果是基本类型,直接传递给外层 JSON
result_json = result
else:
# 其他类型(如字符串)转换为字符串
result_json = str(result)
print(json.dumps({
'logs': logs,
'result': result_json,
'error': None
}))
except Exception as e:
# 处理错误
import traceback
error_msg = f"{str(e)}\n{traceback.format_exc()}"
# 处理错误
sys.stdout = original_stdout
print(json.dumps({
'logs': logs,
'result': None,
'error': error_msg
}))

View File

@@ -0,0 +1,96 @@
// TypeScript类型声明
// @ts-nocheck
type LogFunction = (...args: any[]) => void;
type Handler = (input: any) => any;
// Save original console.log
const originalConsoleLog: LogFunction = console.log;
let logs: string[] = [];
// Replace console.log to capture logs
console.log = function(...args: any[]): void {
// Convert arguments to string and join them
const message = args.map(arg =>
typeof arg === 'object' && arg !== null ? JSON.stringify(arg) : String(arg)
).join(' ');
// Store log
logs.push(message);
// Also log to original console if showing logs
if ({{SHOW_LOGS}}) {
originalConsoleLog.apply(console, args);
}
};
// 异步读取输入参数的函数
async function readInputParams(): Promise<any> {
let input: any = {};
try {
const inputFile = Deno.env.get("INPUT_JSON_FILE");
if (inputFile) {
const inputJson = await Deno.readTextFile(inputFile);
input = JSON.parse(inputJson);
console.log("接收到的参数:", JSON.stringify(input));
} else {
// 兼容旧的环境变量方式
const inputJson = Deno.env.get("INPUT_JSON");
if (inputJson) {
input = JSON.parse(inputJson);
console.log("接收到的参数:", JSON.stringify(input));
}
}
} catch (error) {
console.error("解析输入参数失败:", error);
}
return input;
}
async function executeHandler() {
try {
// Add the original code
{{USER_CODE}}
// 读取输入参数
const input = await readInputParams();
// Execute handler function and get result
let result: any = null;
// 优先检查main函数
if (typeof main === 'function') {
// 检查main是否是异步函数
if (main.constructor.name === 'AsyncFunction') {
result = await (main as (input: any) => Promise<any>)(input);
} else {
result = (main as Handler)(input);
}
} else if (typeof handler === 'function') {
// 如果没有main函数检查handler
if (handler.constructor.name === 'AsyncFunction') {
result = await (handler as (input: any) => Promise<any>)(input);
} else {
result = (handler as Handler)(input);
}
} else {
throw new Error("没有找到main或handler函数");
}
// Print final output as JSON
originalConsoleLog(JSON.stringify({
logs: logs,
result: result !== undefined ? (typeof result === 'object' ? JSON.stringify(result) : String(result)) : null,
error: null
}));
} catch (error) {
// Handle errors
originalConsoleLog(JSON.stringify({
logs: logs,
result: null,
error: String(error)
}));
}
}
// 执行并等待结果
executeHandler();