feat(foreign): structured invoke, presets, probe and config
F0/F1: safe execution core (exec gate, bounded IO, process-group timeout), structured invoke records, run options, 15 language presets, register/unset/probe/config, view stderr/exit/ms, and node/bash gold tests.
This commit is contained in:
1 parent
c21a28c3bc
commit
e32ff8f6b3
21 files changed
+2301
-282
No files matched your search
@@ -4,10 +4,19 @@
|
||||
|
||||
### Added
|
||||
|
||||
- **`lib/foreign` F0/F1**:`invoke` 结构化记录(`ok`/`code`/`stdout`/`stderr`/`ms`/`timed_out`/`truncated`/`result`);`run`/`run_lang` 新增 `env`/`cwd`/`timeout`/`args`/`max_output`;15 个语言预设;`probe`/`register`/`unset`/`load_config`;`.marqdo/foreign.toml`。
|
||||
- **安全与健壮性**:所有外联入口检查 `exec` 能力;有界 stdout/stderr 读取与截断标记;stdin 写线程;Unix 进程组 / Windows `taskkill /T` 超时清理;shell-like argv 切分。
|
||||
|
||||
### Fixed
|
||||
|
||||
- **外联临时脚本路径**:入口目录为相对路径时,脚本参数现在使用绝对路径,避免 `tests/lib/tests/lib/...` 双拼接。
|
||||
- **外联失败可观测**:解释器不存在时进入 `invoke` 记录,`run` 仍报错;view 显示 stderr / exit / ms。
|
||||
|
||||
### Changed
|
||||
|
||||
- **`langs`** 现在返回「预设 ∪ 注册 ∪ 配置」的已知语言(原集合是子集)。
|
||||
- 大输出从 `Err` 改为「截断 + `truncated=true`」;`subtask` 外联输出同步采用该语义。
|
||||
|
||||
## v1.4.6 — 2026-10-16
|
||||
|
||||
### Highlights
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@ cli = ["dep:clap"]
|
||||
view = ["dep:tiny_http"]
|
||||
net-host = ["dep:ureq", "dep:idna_adapter", "dep:zeroize", "dep:zip"]
|
||||
plugin-host = ["dep:libloading"]
|
||||
exec-host = []
|
||||
exec-host = ["dep:libc"]
|
||||
fs-host = []
|
||||
tty = ["dep:libc"]
|
||||
wasm-core = []
|
||||
|
||||
+79
-6
@@ -8,29 +8,102 @@ Run bound code fences and inline sources via local interpreters.
|
||||
## set_cmd
|
||||
+ `lang`
|
||||
+ `cmd`
|
||||
+ `args`=None
|
||||
|
||||
Bind interpreter command cmd for language lang.
|
||||
Bind interpreter command cmd for language lang; optional extra argv.
|
||||
|
||||
*> host_foreign_set_cmd lang=`lang` cmd=`cmd`*
|
||||
*> host_foreign_set_cmd lang=`lang` cmd=`cmd` args=`args`*
|
||||
|
||||
## run
|
||||
+ `code`
|
||||
+ `stdin`=None
|
||||
+ `env`=None
|
||||
+ `cwd`=None
|
||||
+ `timeout`=None
|
||||
+ `args`=None
|
||||
+ `max_output`=None
|
||||
|
||||
Run a bound code fence value; optional stdin.
|
||||
Run a bound code fence value; optional stdin, env map, cwd, timeout (seconds),
|
||||
extra argv and output cap. Returns stdout text; non-zero exit is an error.
|
||||
|
||||
Caller: [foreign.run] code=`block`
|
||||
|
||||
*> host_foreign_run code=`code` stdin=`stdin`*
|
||||
*> host_foreign_run code=`code` stdin=`stdin` env=`env` cwd=`cwd` timeout=`timeout` args=`args` max_output=`max_output`*
|
||||
|
||||
## run_lang
|
||||
+ `lang`
|
||||
+ `source`
|
||||
+ `stdin`=None
|
||||
+ `env`=None
|
||||
+ `cwd`=None
|
||||
+ `timeout`=None
|
||||
+ `args`=None
|
||||
+ `max_output`=None
|
||||
|
||||
Run source text with language lang; optional stdin.
|
||||
Run source text with language lang; same options as run.
|
||||
|
||||
*> host_foreign_run_lang lang=`lang` source=`source` stdin=`stdin`*
|
||||
*> host_foreign_run_lang lang=`lang` source=`source` stdin=`stdin` env=`env` cwd=`cwd` timeout=`timeout` args=`args` max_output=`max_output`*
|
||||
|
||||
## invoke
|
||||
+ `code`=None
|
||||
+ `lang`=None
|
||||
+ `source`=None
|
||||
+ `stdin`=None
|
||||
+ `input`=None
|
||||
+ `env`=None
|
||||
+ `cwd`=None
|
||||
+ `timeout`=None
|
||||
+ `args`=None
|
||||
+ `output`=auto
|
||||
+ `max_output`=None
|
||||
+ `cmd`=None
|
||||
+ `keep`=False
|
||||
|
||||
Run code or lang+source and return a record map instead of raising on process
|
||||
failure. Fields: ok, code, stdout, stderr, ms, lang, cmd, timed_out, truncated,
|
||||
result, result_error, error, script, cached.
|
||||
|
||||
`input` is encoded as JSON on stdin (mutually exclusive with `stdin`). `output`
|
||||
is auto | text | json | lines. `cmd` overrides the interpreter for this call.
|
||||
|
||||
*> host_foreign_invoke code=`code` lang=`lang` source=`source` stdin=`stdin` input=`input` env=`env` cwd=`cwd` timeout=`timeout` args=`args` output=`output` max_output=`max_output` cmd=`cmd` keep=`keep`*
|
||||
|
||||
## probe
|
||||
+ `lang`=None
|
||||
|
||||
Probe one language, or every known language when lang is omitted. Returns
|
||||
{lang, cmd, path, ok, version, error} (a list when lang is omitted).
|
||||
|
||||
*> host_foreign_probe lang=`lang`*
|
||||
|
||||
## register
|
||||
+ `lang`
|
||||
+ `cmd`=None
|
||||
+ `args`=None
|
||||
+ `template`=None
|
||||
+ `ext`=None
|
||||
+ `env`=None
|
||||
+ `version_args`=None
|
||||
|
||||
Register a language invocation. Provide cmd (+args) or template (placeholders
|
||||
{file}, {dir}, {base}, {inline}, {lang}, {cwd}); they are mutually exclusive.
|
||||
|
||||
*> host_foreign_register lang=`lang` cmd=`cmd` args=`args` template=`template` ext=`ext` env=`env` version_args=`version_args`*
|
||||
|
||||
## unset
|
||||
+ `lang`
|
||||
|
||||
Remove a process-local registration. Presets/config/env still apply.
|
||||
|
||||
*> host_foreign_unset lang=`lang`*
|
||||
|
||||
## load_config
|
||||
+ `path`=None
|
||||
|
||||
Load .marqdo/foreign.toml (or an explicit path); returns the number of language
|
||||
tables read.
|
||||
|
||||
*> host_foreign_load_config path=`path`*
|
||||
|
||||
## langs
|
||||
|
||||
|
||||
+78
-6
@@ -8,29 +8,101 @@ description: 通过本机解释器运行绑定的代码围栏与内联源码
|
||||
## 设置命令
|
||||
+ `语言`
|
||||
+ `命令`
|
||||
+ `参数`=None
|
||||
|
||||
为语言绑定解释器命令。
|
||||
为语言绑定解释器命令;可选附加参数。
|
||||
|
||||
*> host_foreign_set_cmd lang=`语言` cmd=`命令`*
|
||||
*> host_foreign_set_cmd lang=`语言` cmd=`命令` args=`参数`*
|
||||
|
||||
## 运行
|
||||
+ `代码`
|
||||
+ `标准输入`=None
|
||||
+ `环境`=None
|
||||
+ `工作目录`=None
|
||||
+ `超时`=None
|
||||
+ `参数`=None
|
||||
+ `最大输出`=None
|
||||
|
||||
运行已绑定的代码围栏值;可选标准输入。
|
||||
运行已绑定的代码围栏值;可选标准输入、环境表、工作目录、超时(秒)、
|
||||
附加参数与输出上限。返回 stdout 文本;非 0 退出即报错。
|
||||
|
||||
调用例:[外联.运行] 代码=`块`
|
||||
|
||||
*> host_foreign_run code=`代码` stdin=`标准输入`*
|
||||
*> host_foreign_run code=`代码` stdin=`标准输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` max_output=`最大输出`*
|
||||
|
||||
## 按语言运行
|
||||
+ `语言`
|
||||
+ `源码`
|
||||
+ `标准输入`=None
|
||||
+ `环境`=None
|
||||
+ `工作目录`=None
|
||||
+ `超时`=None
|
||||
+ `参数`=None
|
||||
+ `最大输出`=None
|
||||
|
||||
用语言运行源码文本;可选标准输入。
|
||||
用语言运行源码文本;选项同“运行”。
|
||||
|
||||
*> host_foreign_run_lang lang=`语言` source=`源码` stdin=`标准输入`*
|
||||
*> host_foreign_run_lang lang=`语言` source=`源码` stdin=`标准输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` max_output=`最大输出`*
|
||||
|
||||
## 执行
|
||||
+ `代码`=None
|
||||
+ `语言`=None
|
||||
+ `源码`=None
|
||||
+ `标准输入`=None
|
||||
+ `输入`=None
|
||||
+ `环境`=None
|
||||
+ `工作目录`=None
|
||||
+ `超时`=None
|
||||
+ `参数`=None
|
||||
+ `输出`=auto
|
||||
+ `最大输出`=None
|
||||
+ `命令`=None
|
||||
+ `保留`=False
|
||||
|
||||
运行代码或“语言+源码”,返回记录 map,而不是在进程失败时直接报错。
|
||||
字段:ok、code、stdout、stderr、ms、lang、cmd、timed_out、truncated、
|
||||
result、result_error、error、script、cached。
|
||||
|
||||
`输入` 会编码为 JSON 写入 stdin(与 `标准输入` 互斥)。`输出` 可取
|
||||
auto | text | json | lines。`命令` 仅本次覆盖解释器。
|
||||
|
||||
*> host_foreign_invoke code=`代码` lang=`语言` source=`源码` stdin=`标准输入` input=`输入` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` output=`输出` max_output=`最大输出` cmd=`命令` keep=`保留`*
|
||||
|
||||
## 探测
|
||||
+ `语言`=None
|
||||
|
||||
探测一个语言;省略语言时探测所有已知语言。返回
|
||||
{lang, cmd, path, ok, version, error}(省略语言时是列表)。
|
||||
|
||||
*> host_foreign_probe lang=`语言`*
|
||||
|
||||
## 注册
|
||||
+ `语言`
|
||||
+ `命令`=None
|
||||
+ `参数`=None
|
||||
+ `模板`=None
|
||||
+ `扩展名`=None
|
||||
+ `环境`=None
|
||||
+ `版本参数`=None
|
||||
|
||||
注册语言调用。提供命令(+参数)或模板(占位符
|
||||
{file}、{dir}、{base}、{inline}、{lang}、{cwd});二者互斥。
|
||||
|
||||
*> host_foreign_register lang=`语言` cmd=`命令` args=`参数` template=`模板` ext=`扩展名` env=`环境` version_args=`版本参数`*
|
||||
|
||||
## 注销
|
||||
+ `语言`
|
||||
|
||||
移除进程内注册;预设 / 配置 / 环境变量仍然生效。
|
||||
|
||||
*> host_foreign_unset lang=`语言`*
|
||||
|
||||
## 加载配置
|
||||
+ `路径`=None
|
||||
|
||||
加载 .marqdo/foreign.toml(或显式路径);返回读取到的语言表数量。
|
||||
|
||||
*> host_foreign_load_config path=`路径`*
|
||||
|
||||
## 语言表
|
||||
|
||||
|
||||
+47
-5
@@ -124,11 +124,53 @@ pub fn canonical_param(builtin: &str, param: &str) -> String {
|
||||
("host_json_stringify" | "stringify", "indent" | "缩进") => "indent".into(),
|
||||
("host_plot", "steps" | "步数") => "steps".into(),
|
||||
("host_plot", "derivative" | "导数") => "derivative".into(),
|
||||
("host_foreign_run", "code" | "代码") => "code".into(),
|
||||
("host_foreign_run" | "host_foreign_run_lang", "stdin" | "标准输入") => "stdin".into(),
|
||||
("host_foreign_set_cmd" | "host_foreign_run_lang", "lang" | "语言") => "lang".into(),
|
||||
("host_foreign_set_cmd", "cmd" | "命令") => "cmd".into(),
|
||||
("host_foreign_run_lang", "source" | "源码") => "source".into(),
|
||||
("host_foreign_run" | "host_foreign_invoke", "code" | "代码") => "code".into(),
|
||||
(
|
||||
"host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke",
|
||||
"stdin" | "标准输入",
|
||||
) => "stdin".into(),
|
||||
(
|
||||
"host_foreign_set_cmd"
|
||||
| "host_foreign_run_lang"
|
||||
| "host_foreign_invoke"
|
||||
| "host_foreign_probe"
|
||||
| "host_foreign_register"
|
||||
| "host_foreign_unset",
|
||||
"lang" | "语言",
|
||||
) => "lang".into(),
|
||||
(
|
||||
"host_foreign_set_cmd" | "host_foreign_invoke" | "host_foreign_register",
|
||||
"cmd" | "命令",
|
||||
) => "cmd".into(),
|
||||
("host_foreign_run_lang" | "host_foreign_invoke", "source" | "源码") => "source".into(),
|
||||
(
|
||||
"host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke",
|
||||
"env" | "环境",
|
||||
) => "env".into(),
|
||||
(
|
||||
"host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke",
|
||||
"cwd" | "工作目录",
|
||||
) => "cwd".into(),
|
||||
(
|
||||
"host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke",
|
||||
"timeout" | "超时",
|
||||
) => "timeout".into(),
|
||||
(
|
||||
"host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke"
|
||||
| "host_foreign_register",
|
||||
"args" | "参数",
|
||||
) => "args".into(),
|
||||
(
|
||||
"host_foreign_run" | "host_foreign_run_lang" | "host_foreign_invoke",
|
||||
"max_output" | "最大输出",
|
||||
) => "max_output".into(),
|
||||
("host_foreign_invoke", "input" | "输入") => "input".into(),
|
||||
("host_foreign_invoke", "output" | "输出") => "output".into(),
|
||||
("host_foreign_invoke", "keep" | "保留") => "keep".into(),
|
||||
("host_foreign_register", "template" | "模板") => "template".into(),
|
||||
("host_foreign_register", "ext" | "扩展名") => "ext".into(),
|
||||
("host_foreign_register", "version_args" | "版本参数") => "version_args".into(),
|
||||
("host_foreign_load_config", "path" | "路径") => "path".into(),
|
||||
("host_ext_native_path", "name" | "名") => "name".into(),
|
||||
_ => param.to_string(),
|
||||
}
|
||||
|
||||
+42
-23
@@ -1,30 +1,49 @@
|
||||
//! Foreign / code-block helpers (外联).
|
||||
|
||||
/// Default interpreter argv for a language tag (before env / set_cmd).
|
||||
pub fn default_argv(lang: &str) -> Option<Vec<String>> {
|
||||
match lang.to_ascii_lowercase().as_str() {
|
||||
"python" | "python3" | "py" => Some(default_python_argv()),
|
||||
"javascript" | "js" | "node" => Some(vec!["node".into()]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub mod registry;
|
||||
|
||||
pub fn default_python_argv() -> Vec<String> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
vec!["python".into()]
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
vec!["python3".into()]
|
||||
}
|
||||
}
|
||||
pub use registry::{default_argv, default_cmd_display, default_python_argv};
|
||||
|
||||
/// Placeholder shown in the view command box.
|
||||
pub fn default_cmd_display(lang: &str) -> String {
|
||||
default_argv(lang)
|
||||
.map(|a| a.join(" "))
|
||||
.unwrap_or_else(|| lang.to_string())
|
||||
/// Shell-like split: whitespace, single/double quotes, backslash escapes.
|
||||
pub fn split_cmd_line(s: &str) -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
let mut cur = String::new();
|
||||
let mut quote: Option<char> = None;
|
||||
let mut chars = s.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
match quote {
|
||||
Some(q) => {
|
||||
if c == q {
|
||||
quote = None;
|
||||
} else if c == '\\' && q == '"' {
|
||||
if let Some(n) = chars.next() {
|
||||
cur.push(n);
|
||||
}
|
||||
} else {
|
||||
cur.push(c);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if c.is_whitespace() {
|
||||
if !cur.is_empty() {
|
||||
out.push(std::mem::take(&mut cur));
|
||||
}
|
||||
} else if c == '\'' || c == '"' {
|
||||
quote = Some(c);
|
||||
} else if c == '\\' {
|
||||
if let Some(n) = chars.next() {
|
||||
cur.push(n);
|
||||
}
|
||||
} else {
|
||||
cur.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !cur.is_empty() {
|
||||
out.push(cur);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Parse ```lang … opener → language id (first token).
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
//! Language presets and specs for `lib/foreign` (pure data; no process spawning).
|
||||
//!
|
||||
//! The host runner resolves a `LangSpec`, then builds the command. Keeping this
|
||||
//! module free of `std::process` lets the browser/wasm build share the syntax and
|
||||
//! preset tables.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// One language's invocation recipe.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct LangSpec {
|
||||
pub lang: String,
|
||||
/// Simple interpreter prefix; the script path is appended.
|
||||
pub argv: Vec<String>,
|
||||
/// Optional full argv template; supports `{file}`/`{inline}`/… placeholders.
|
||||
pub template: Option<Vec<String>>,
|
||||
pub ext: Option<String>,
|
||||
pub env: Vec<(String, String)>,
|
||||
/// Arguments appended to the executable for `probe` (e.g. `--version`).
|
||||
pub version_args: Vec<String>,
|
||||
/// Persistent session bootstrap available.
|
||||
pub session: bool,
|
||||
/// Directory for resolving a relative interpreter path (config file dir).
|
||||
pub base_dir: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl LangSpec {
|
||||
fn simple(lang: &str, argv: &[&str], ext: &str, version: &[&str], session: bool) -> Self {
|
||||
Self {
|
||||
lang: lang.to_string(),
|
||||
argv: argv.iter().map(|s| (*s).to_string()).collect(),
|
||||
template: None,
|
||||
ext: Some(ext.to_string()),
|
||||
env: Vec::new(),
|
||||
version_args: version.iter().map(|s| (*s).to_string()).collect(),
|
||||
session,
|
||||
base_dir: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn templated(lang: &str, template: &[&str], ext: &str, version: &[&str]) -> Self {
|
||||
Self {
|
||||
lang: lang.to_string(),
|
||||
argv: vec![template[0].to_string()],
|
||||
template: Some(template.iter().map(|s| (*s).to_string()).collect()),
|
||||
ext: Some(ext.to_string()),
|
||||
env: Vec::new(),
|
||||
version_args: version.iter().map(|s| (*s).to_string()).collect(),
|
||||
session: false,
|
||||
base_dir: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn default_python_argv() -> Vec<String> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
vec!["python".into()]
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
vec!["python3".into()]
|
||||
}
|
||||
}
|
||||
|
||||
/// Canonical preset id for a language or alias. Unknown names pass through lowercased.
|
||||
pub fn canonical(lang: &str) -> String {
|
||||
let l = lang.to_ascii_lowercase();
|
||||
match l.as_str() {
|
||||
"python3" | "py" => "python".into(),
|
||||
"javascript" | "js" => "node".into(),
|
||||
"shell" | "sh" => "bash".into(),
|
||||
"rscript" => "r".into(),
|
||||
"pwsh" | "ps1" => "powershell".into(),
|
||||
"sqlite3" => "sqlite".into(),
|
||||
"typescript" => "tsx".into(),
|
||||
_ => l,
|
||||
}
|
||||
}
|
||||
|
||||
/// Built-in preset for a language/alias.
|
||||
pub fn preset_spec(lang: &str) -> Option<LangSpec> {
|
||||
let id = canonical(lang);
|
||||
Some(match id.as_str() {
|
||||
"python" => LangSpec {
|
||||
argv: default_python_argv(),
|
||||
..LangSpec::simple("python", &["python3"], "py", &["--version"], true)
|
||||
},
|
||||
"node" => LangSpec::simple("node", &["node"], "js", &["-v"], true),
|
||||
"deno" => LangSpec::simple("deno", &["deno", "run"], "ts", &["--version"], false),
|
||||
"bun" => LangSpec::simple("bun", &["bun"], "js", &["--version"], false),
|
||||
"ruby" => LangSpec::simple("ruby", &["ruby"], "rb", &["--version"], false),
|
||||
"perl" => LangSpec::simple("perl", &["perl"], "pl", &["--version"], false),
|
||||
"php" => LangSpec::templated("php", &["php", "-r", "{inline}"], "php", &["--version"]),
|
||||
"lua" => LangSpec::simple("lua", &["lua"], "lua", &["-v"], false),
|
||||
"r" => LangSpec::simple("r", &["Rscript"], "R", &["--version"], false),
|
||||
"julia" => LangSpec::simple("julia", &["julia"], "jl", &["--version"], false),
|
||||
"go" => LangSpec::templated("go", &["go", "run", "{file}"], "go", &["version"]),
|
||||
"bash" => LangSpec::simple("bash", &["bash"], "sh", &["--version"], false),
|
||||
"powershell" => {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
LangSpec::simple("powershell", &["powershell"], "ps1", &["--version"], false)
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
LangSpec::simple("powershell", &["pwsh"], "ps1", &["--version"], false)
|
||||
}
|
||||
}
|
||||
"sqlite" => LangSpec::simple("sqlite", &["sqlite3"], "sql", &["--version"], false),
|
||||
"tsx" => LangSpec::simple("tsx", &["tsx"], "ts", &["--version"], false),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Sorted preset ids (for `langs`).
|
||||
pub fn preset_ids() -> Vec<String> {
|
||||
[
|
||||
"python", "node", "deno", "bun", "ruby", "perl", "php", "lua", "r", "julia", "go",
|
||||
"bash", "powershell", "sqlite", "tsx",
|
||||
]
|
||||
.iter()
|
||||
.map(|s| (*s).to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Display string for the command box (e.g. `python3`, `go run`, `php -r`).
|
||||
pub fn default_cmd_display(lang: &str) -> String {
|
||||
match preset_spec(lang) {
|
||||
Some(spec) => {
|
||||
if let Some(t) = &spec.template {
|
||||
let mut parts = Vec::new();
|
||||
for x in t {
|
||||
if x.contains('{') {
|
||||
break;
|
||||
}
|
||||
parts.push(x.clone());
|
||||
}
|
||||
if parts.is_empty() {
|
||||
lang.to_string()
|
||||
} else {
|
||||
parts.join(" ")
|
||||
}
|
||||
} else {
|
||||
spec.argv.join(" ")
|
||||
}
|
||||
}
|
||||
None => lang.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Default argv for v1 compatibility (simple presets only).
|
||||
pub fn default_argv(lang: &str) -> Option<Vec<String>> {
|
||||
preset_spec(lang).map(|s| s.argv)
|
||||
}
|
||||
|
||||
/// Session support for a language (based on preset).
|
||||
pub fn session_supported(lang: &str) -> bool {
|
||||
preset_spec(lang).map(|s| s.session).unwrap_or(false)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn aliases_canonicalize() {
|
||||
assert_eq!(canonical("py"), "python");
|
||||
assert_eq!(canonical("javascript"), "node");
|
||||
assert_eq!(canonical("sh"), "bash");
|
||||
assert_eq!(canonical("unknown"), "unknown");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn presets_cover_docs() {
|
||||
assert_eq!(preset_ids().len(), 15);
|
||||
assert!(preset_spec("python").is_some());
|
||||
assert!(preset_spec("node").is_some());
|
||||
assert!(preset_spec("go").unwrap().template.is_some());
|
||||
assert!(preset_spec("php").unwrap().template.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_uses_template_prefix() {
|
||||
assert_eq!(default_cmd_display("go"), "go run");
|
||||
assert_eq!(default_cmd_display("php"), "php -r");
|
||||
}
|
||||
}
|
||||
+141
-3
@@ -202,6 +202,11 @@ pub enum HostFn {
|
||||
MetaGet = 193,
|
||||
ModuleSource = 194,
|
||||
ArtifactKind = 195,
|
||||
ForeignInvoke = 196,
|
||||
ForeignProbe = 197,
|
||||
ForeignRegister = 198,
|
||||
ForeignUnset = 199,
|
||||
ForeignLoadConfig = 200,
|
||||
}
|
||||
|
||||
|
||||
@@ -394,6 +399,11 @@ impl HostFn {
|
||||
193 => Self::MetaGet,
|
||||
194 => Self::ModuleSource,
|
||||
195 => Self::ArtifactKind,
|
||||
196 => Self::ForeignInvoke,
|
||||
197 => Self::ForeignProbe,
|
||||
198 => Self::ForeignRegister,
|
||||
199 => Self::ForeignUnset,
|
||||
200 => Self::ForeignLoadConfig,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -470,6 +480,11 @@ impl HostFn {
|
||||
"host_foreign_set_cmd" => Self::ForeignSetCmd,
|
||||
"host_foreign_run" => Self::ForeignRun,
|
||||
"host_foreign_run_lang" => Self::ForeignRunLang,
|
||||
"host_foreign_invoke" | "foreign_invoke" => Self::ForeignInvoke,
|
||||
"host_foreign_probe" | "foreign_probe" => Self::ForeignProbe,
|
||||
"host_foreign_register" | "foreign_register" => Self::ForeignRegister,
|
||||
"host_foreign_unset" | "foreign_unset" => Self::ForeignUnset,
|
||||
"host_foreign_load_config" | "foreign_load_config" => Self::ForeignLoadConfig,
|
||||
"host_foreign_langs" => Self::ForeignLangs,
|
||||
"host_dotenv_load" | "load_dotenv" => Self::DotenvLoad,
|
||||
"host_http_request" | "http_request" => Self::HttpRequest,
|
||||
@@ -666,6 +681,11 @@ impl HostFn {
|
||||
Self::ForeignSetCmd => "host_foreign_set_cmd",
|
||||
Self::ForeignRun => "host_foreign_run",
|
||||
Self::ForeignRunLang => "host_foreign_run_lang",
|
||||
Self::ForeignInvoke => "host_foreign_invoke",
|
||||
Self::ForeignProbe => "host_foreign_probe",
|
||||
Self::ForeignRegister => "host_foreign_register",
|
||||
Self::ForeignUnset => "host_foreign_unset",
|
||||
Self::ForeignLoadConfig => "host_foreign_load_config",
|
||||
Self::ForeignLangs => "host_foreign_langs",
|
||||
Self::DotenvLoad => "host_dotenv_load",
|
||||
Self::HttpRequest => "host_http_request",
|
||||
@@ -832,6 +852,9 @@ impl HostFn {
|
||||
Self::ForeignSetCmd => &["lang", "cmd"],
|
||||
Self::ForeignRun => &["code"],
|
||||
Self::ForeignRunLang => &["lang", "source"],
|
||||
Self::ForeignInvoke => &[],
|
||||
Self::ForeignProbe | Self::ForeignLoadConfig => &[],
|
||||
Self::ForeignRegister | Self::ForeignUnset => &["lang"],
|
||||
Self::ForeignLangs => &[],
|
||||
Self::PluginLoad => &["path"],
|
||||
Self::PluginUnload | Self::PluginList => &[],
|
||||
@@ -935,7 +958,35 @@ impl HostFn {
|
||||
Self::PlotPoints => &["path", "grid"],
|
||||
Self::PlotConic => &["b", "h", "k", "path", "grid"],
|
||||
Self::ForeignSetCmd => &["args"],
|
||||
Self::ForeignRun | Self::ForeignRunLang => &["stdin"],
|
||||
Self::ForeignRun | Self::ForeignRunLang => {
|
||||
&["stdin", "env", "cwd", "timeout", "args", "max_output"]
|
||||
}
|
||||
Self::ForeignInvoke => &[
|
||||
"code",
|
||||
"lang",
|
||||
"source",
|
||||
"stdin",
|
||||
"input",
|
||||
"env",
|
||||
"cwd",
|
||||
"timeout",
|
||||
"args",
|
||||
"output",
|
||||
"max_output",
|
||||
"cmd",
|
||||
"keep",
|
||||
],
|
||||
Self::ForeignProbe => &["lang"],
|
||||
Self::ForeignRegister => &[
|
||||
"cmd",
|
||||
"args",
|
||||
"template",
|
||||
"ext",
|
||||
"env",
|
||||
"version_args",
|
||||
],
|
||||
Self::ForeignUnset => &[],
|
||||
Self::ForeignLoadConfig => &["path"],
|
||||
Self::WritebackRecord | Self::WritebackGet | Self::WritebackClear => {
|
||||
&["at_end", "key", "line"]
|
||||
}
|
||||
@@ -1184,7 +1235,12 @@ pub fn call_host(
|
||||
HostFn::ForeignRun => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
foreign::run(ctx, require(bound, "code")?, bound.get("stdin"))
|
||||
foreign::run_with_options(
|
||||
ctx,
|
||||
require(bound, "code")?,
|
||||
bound.get("stdin"),
|
||||
bound,
|
||||
)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
@@ -1195,11 +1251,12 @@ pub fn call_host(
|
||||
HostFn::ForeignRunLang => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
foreign::run_lang(
|
||||
foreign::run_lang_with_options(
|
||||
ctx,
|
||||
require(bound, "lang")?,
|
||||
require(bound, "source")?,
|
||||
bound.get("stdin"),
|
||||
bound,
|
||||
)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
@@ -1208,6 +1265,87 @@ pub fn call_host(
|
||||
Err("foreign unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::ForeignInvoke => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
foreign::invoke(
|
||||
ctx,
|
||||
foreign::InvokeArgs {
|
||||
code: bound.get("code"),
|
||||
lang: bound.get("lang"),
|
||||
source: bound.get("source"),
|
||||
stdin: bound.get("stdin"),
|
||||
input: bound.get("input"),
|
||||
env: bound.get("env"),
|
||||
cwd: bound.get("cwd"),
|
||||
timeout: bound.get("timeout"),
|
||||
args: bound.get("args"),
|
||||
output: bound.get("output"),
|
||||
max_output: bound.get("max_output"),
|
||||
cmd: bound.get("cmd"),
|
||||
keep: bound.get("keep"),
|
||||
},
|
||||
)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("foreign unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::ForeignProbe => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
foreign::probe(ctx, bound.get("lang"))
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("foreign unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::ForeignRegister => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
foreign::register(
|
||||
ctx,
|
||||
require(bound, "lang")?,
|
||||
bound.get("cmd"),
|
||||
bound.get("args"),
|
||||
bound.get("template"),
|
||||
bound.get("ext"),
|
||||
bound.get("env"),
|
||||
bound.get("version_args"),
|
||||
)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("foreign unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::ForeignUnset => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
foreign::unset(ctx, require(bound, "lang")?)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("foreign unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::ForeignLoadConfig => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
foreign::load_config(ctx, bound.get("path"))
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
let _ = (ctx, bound);
|
||||
Err("foreign unavailable in browser wasm".into())
|
||||
}
|
||||
}
|
||||
HostFn::ForeignLangs => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
|
||||
+1468
-224
File diff suppressed because it is too large.
Load diff
+10
-1
@@ -27,7 +27,7 @@ mod secrets;
|
||||
mod stats;
|
||||
mod text_ops;
|
||||
mod time;
|
||||
mod toml_ops;
|
||||
pub(crate) mod toml_ops;
|
||||
mod url_ops;
|
||||
mod uuid_ops;
|
||||
#[cfg(feature = "plugin-host")]
|
||||
@@ -93,6 +93,12 @@ pub struct HostContext {
|
||||
pub plots: Vec<PlotArtifact>,
|
||||
/// lang → interpreter argv (from `set_cmd`).
|
||||
pub foreign_cmds: HashMap<String, Vec<String>>,
|
||||
/// Process-local language registrations (`register` / `set_cmd`).
|
||||
pub foreign_specs: HashMap<String, crate::foreign::registry::LangSpec>,
|
||||
/// Project config specs (`.marqdo/foreign.toml`), lower priority than runtime.
|
||||
pub foreign_config_specs: HashMap<String, crate::foreign::registry::LangSpec>,
|
||||
/// Whether project config has been discovered/loaded.
|
||||
pub foreign_config_loaded: bool,
|
||||
/// Loaded native plugins (ABI v1/v2).
|
||||
pub plugins: PluginState,
|
||||
/// Entry `.mq.md` source text (for ABI host_query / context injection).
|
||||
@@ -128,6 +134,9 @@ impl Default for HostContext {
|
||||
rng: 0xC0FF_EE42_CAFE_BABE,
|
||||
plots: Vec::new(),
|
||||
foreign_cmds: HashMap::new(),
|
||||
foreign_specs: HashMap::new(),
|
||||
foreign_config_specs: HashMap::new(),
|
||||
foreign_config_loaded: false,
|
||||
plugins: PluginState::default(),
|
||||
entry_source: None,
|
||||
entry_path: None,
|
||||
|
||||
+13
-7
@@ -120,8 +120,8 @@ fn republish_child_event(line: &str) {
|
||||
pub(crate) struct ForeignTask {
|
||||
child: Child,
|
||||
temp_script: PathBuf,
|
||||
stdout: JoinHandle<String>,
|
||||
stderr: JoinHandle<String>,
|
||||
stdout: JoinHandle<(String, bool)>,
|
||||
stderr: JoinHandle<(String, bool)>,
|
||||
}
|
||||
|
||||
enum FnState {
|
||||
@@ -392,6 +392,9 @@ fn spawn_fn(
|
||||
let cwd = ctx.cwd.clone();
|
||||
let caps = ctx.caps.clone();
|
||||
let foreign_cmds = ctx.foreign_cmds.clone();
|
||||
let foreign_specs = ctx.foreign_specs.clone();
|
||||
let foreign_config_specs = ctx.foreign_config_specs.clone();
|
||||
let foreign_config_loaded = ctx.foreign_config_loaded;
|
||||
let fs_root = ctx.fs_root.clone();
|
||||
let argv = ctx.argv.clone();
|
||||
|
||||
@@ -407,6 +410,9 @@ fn spawn_fn(
|
||||
host.fs_root = fs_root;
|
||||
host.argv = argv;
|
||||
host.foreign_cmds = foreign_cmds;
|
||||
host.foreign_specs = foreign_specs;
|
||||
host.foreign_config_specs = foreign_config_specs;
|
||||
host.foreign_config_loaded = foreign_config_loaded;
|
||||
host.set_entry_source(Some(&module_path), &source);
|
||||
host.entry_metadata = module.metadata.clone();
|
||||
let mut interp = Interpreter::with_capture(Some(&module_path), false).with_host(host);
|
||||
@@ -587,12 +593,9 @@ fn join_foreign(mut task: ForeignTask) -> Result<Value, String> {
|
||||
.child
|
||||
.wait()
|
||||
.map_err(|e| format!("subtask foreign join: {e}"))?;
|
||||
let stdout = task.stdout.join().unwrap_or_default();
|
||||
let stderr = task.stderr.join().unwrap_or_default();
|
||||
let (stdout, out_trunc) = task.stdout.join().unwrap_or_default();
|
||||
let (stderr, err_trunc) = task.stderr.join().unwrap_or_default();
|
||||
let _ = std::fs::remove_file(&task.temp_script);
|
||||
if stdout.len() > foreign::MAX_OUTPUT || stderr.len() > foreign::MAX_OUTPUT {
|
||||
return Err("subtask foreign output too large".into());
|
||||
}
|
||||
if !status.success() {
|
||||
let code = status.code().unwrap_or(1);
|
||||
let mut msg = format!("subtask foreign failed (exit={code})");
|
||||
@@ -609,6 +612,9 @@ fn join_foreign(mut task: ForeignTask) -> Result<Value, String> {
|
||||
out.pop();
|
||||
}
|
||||
}
|
||||
if out_trunc || err_trunc {
|
||||
out.push_str("\n…(truncated)");
|
||||
}
|
||||
Ok(Value::Text(out))
|
||||
}
|
||||
|
||||
|
||||
+11
-2
@@ -958,13 +958,22 @@ fn debug_js() -> &'static str {
|
||||
})
|
||||
.then(function (r) { return r.json(); })
|
||||
.then(function (data) {
|
||||
var parts = [];
|
||||
if (data.stdout) parts.push(data.stdout);
|
||||
if (data.stderr) parts.push("[stderr]\n" + data.stderr);
|
||||
if (data.error) parts.push(data.error);
|
||||
var meta = [];
|
||||
if (typeof data.code === "number") meta.push("exit " + data.code);
|
||||
if (typeof data.ms === "number") meta.push(data.ms + "ms");
|
||||
if (data.timed_out) meta.push("timed out");
|
||||
if (data.truncated) meta.push("truncated");
|
||||
if (meta.length) parts.push("— " + meta.join(" · "));
|
||||
if (data.ok) {
|
||||
out.classList.remove("err");
|
||||
out.textContent = data.stdout === "" ? "(no stdout)" : data.stdout;
|
||||
} else {
|
||||
out.classList.add("err");
|
||||
out.textContent = data.error || "foreign run failed";
|
||||
}
|
||||
out.textContent = parts.length ? parts.join("\n\n") : "(no output)";
|
||||
})
|
||||
.catch(function (e) {
|
||||
out.classList.add("err");
|
||||
|
||||
+11
-2
@@ -1625,13 +1625,22 @@ pub fn layout(title: &str, nav: &str, main: &str) -> String {
|
||||
}})
|
||||
.then(function (r) {{ return r.json(); }})
|
||||
.then(function (data) {{
|
||||
var parts = [];
|
||||
if (data.stdout) parts.push(data.stdout);
|
||||
if (data.stderr) parts.push("[stderr]\n" + data.stderr);
|
||||
if (data.error) parts.push(data.error);
|
||||
var meta = [];
|
||||
if (typeof data.code === "number") meta.push("exit " + data.code);
|
||||
if (typeof data.ms === "number") meta.push(data.ms + "ms");
|
||||
if (data.timed_out) meta.push("timed out");
|
||||
if (data.truncated) meta.push("truncated");
|
||||
if (meta.length) parts.push("— " + meta.join(" · "));
|
||||
if (data.ok) {{
|
||||
out.classList.remove("err");
|
||||
out.textContent = data.stdout === "" ? "(no stdout)" : data.stdout;
|
||||
}} else {{
|
||||
out.classList.add("err");
|
||||
out.textContent = data.error || "foreign run failed";
|
||||
}}
|
||||
out.textContent = parts.length ? parts.join("\n\n") : "(no output)";
|
||||
}})
|
||||
.catch(function (e) {{
|
||||
out.classList.add("err");
|
||||
|
||||
+9
-2
@@ -595,6 +595,8 @@ fn api_foreign_run(root: &ViewRoot, mut request: Request) -> Result<()> {
|
||||
.and_then(|x| x.as_str())
|
||||
.unwrap_or("python");
|
||||
let source = v.get("source").and_then(|x| x.as_str()).unwrap_or("");
|
||||
let stdin = v.get("stdin").and_then(|x| x.as_str());
|
||||
let timeout = v.get("timeout").and_then(|x| x.as_f64());
|
||||
let cmd = v
|
||||
.get("cmd")
|
||||
.and_then(|x| x.as_str())
|
||||
@@ -603,13 +605,18 @@ fn api_foreign_run(root: &ViewRoot, mut request: Request) -> Result<()> {
|
||||
let json = if source.is_empty() {
|
||||
serde_json::json!({ "ok": false, "error": "missing source" }).to_string()
|
||||
} else {
|
||||
match crate::host::foreign::run_with_cmd_override(
|
||||
match crate::host::foreign::invoke_for_view(
|
||||
&root.root,
|
||||
lang,
|
||||
source,
|
||||
cmd,
|
||||
stdin,
|
||||
timeout,
|
||||
) {
|
||||
Ok(stdout) => serde_json::json!({ "ok": true, "stdout": stdout }).to_string(),
|
||||
Ok(value) => match crate::host::json::value_to_json(&value) {
|
||||
Ok(j) => j.to_string(),
|
||||
Err(e) => serde_json::json!({ "ok": false, "error": e }).to_string(),
|
||||
},
|
||||
Err(error) => serde_json::json!({ "ok": false, "error": error }).to_string(),
|
||||
}
|
||||
};
|
||||
|
||||
@@ -3317,6 +3317,79 @@ fn lib_foreign_zh() {
|
||||
assert_out("tests/lib/外联-python.mq.md", "中文外联");
|
||||
}
|
||||
|
||||
fn node_available() -> bool {
|
||||
Command::new("node")
|
||||
.args(["-e", "process.exit(0)"])
|
||||
.output()
|
||||
.map(|o| o.status.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lib_foreign_invoke() {
|
||||
if !node_available() {
|
||||
eprintln!("skip lib_foreign_invoke: no node on PATH");
|
||||
return;
|
||||
}
|
||||
assert_out("tests/lib/foreign-invoke.mq.md", "False\n3\nboom\nFalse");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lib_foreign_json() {
|
||||
if !node_available() {
|
||||
eprintln!("skip lib_foreign_json: no node on PATH");
|
||||
return;
|
||||
}
|
||||
assert_out("tests/lib/foreign-json.mq.md", "True\n4\n10");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lib_foreign_env_timeout() {
|
||||
if !node_available() {
|
||||
eprintln!("skip lib_foreign_env_timeout: no node on PATH");
|
||||
return;
|
||||
}
|
||||
assert_out(
|
||||
"tests/lib/foreign-env-timeout.mq.md",
|
||||
"fast|node\nFalse\nTrue",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lib_foreign_probe_register() {
|
||||
if !node_available() {
|
||||
eprintln!("skip lib_foreign_probe_register: no node on PATH");
|
||||
return;
|
||||
}
|
||||
assert_out(
|
||||
"tests/lib/foreign-probe-register.mq.md",
|
||||
"True\nnode\ntiny",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lib_foreign_config() {
|
||||
if !node_available() {
|
||||
eprintln!("skip lib_foreign_config: no node on PATH");
|
||||
return;
|
||||
}
|
||||
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
|
||||
.args(["run", "tests/lib/foreign-config.mq.md"])
|
||||
.env(
|
||||
"MARQDO_FOREIGN_CONFIG",
|
||||
root.join("tests/lib/fixtures/foreign.toml"),
|
||||
)
|
||||
.current_dir(&root)
|
||||
.output()
|
||||
.expect("run foreign-config");
|
||||
let code = output.status.code().unwrap_or(1);
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
assert_eq!(code, 0, "foreign-config stderr={stderr}");
|
||||
assert_eq!(stdout.trim_end(), "1\ncfg", "stdout={stdout}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bytecode_lib_math_formula() {
|
||||
assert_out_backend(
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
[tinycfg]
|
||||
template = ["node", "-e", "{inline}"]
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
title: foreign config load
|
||||
import foreign:lib/foreign.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
**载入 = > foreign.load_config**
|
||||
> print text=`载入`
|
||||
|
||||
**运行 = > foreign.invoke lang="tinycfg" source="console.log('cfg')"**
|
||||
> print text=[stdout](`运行`)
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
title: foreign env cwd timeout
|
||||
import foreign:lib/foreign.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`环境` =
|
||||
|
||||
| MODE | NOTE |
|
||||
|------|------|
|
||||
| fast | test |
|
||||
|
||||
`环境检查` =
|
||||
```node
|
||||
console.log(process.env.MODE + "|" + process.env.MARQDO_FOREIGN_LANG);
|
||||
```
|
||||
|
||||
**检查 = > foreign.invoke code=`环境检查` env=`环境`**
|
||||
**检查输出 = > trim [stdout](`检查`)**
|
||||
|
||||
> print text=`检查输出`
|
||||
|
||||
`慢` =
|
||||
```node
|
||||
setTimeout(() => console.log("late"), 5000);
|
||||
```
|
||||
|
||||
**超时 = > foreign.invoke code=`慢` timeout=0.5**
|
||||
|
||||
> print text=[ok](`超时`)
|
||||
> print text=[timed_out](`超时`)
|
||||
@@ -0,0 +1,19 @@
|
||||
---
|
||||
title: foreign invoke record
|
||||
import foreign:lib/foreign.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`失败` =
|
||||
```node
|
||||
process.stderr.write("boom");
|
||||
process.exit(3);
|
||||
```
|
||||
|
||||
**记录 = > foreign.invoke code=`失败`**
|
||||
|
||||
> print text=[ok](`记录`)
|
||||
> print text=[code](`记录`)
|
||||
> print text=[stderr](`记录`)
|
||||
> print text=[truncated](`记录`)
|
||||
@@ -0,0 +1,32 @@
|
||||
---
|
||||
title: foreign invoke JSON input
|
||||
import foreign:lib/foreign.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`数值表` =
|
||||
|
||||
| 数值 |
|
||||
|------|
|
||||
| 1 |
|
||||
| 2 |
|
||||
| 3 |
|
||||
| 4 |
|
||||
|
||||
`统计` =
|
||||
```node
|
||||
let s = "";
|
||||
process.stdin.on("data", d => { s += d; });
|
||||
process.stdin.on("end", () => {
|
||||
const xs = JSON.parse(s);
|
||||
console.log(JSON.stringify({ n: xs.length, sum: xs.reduce((a, b) => a + b, 0) }));
|
||||
});
|
||||
```
|
||||
|
||||
**记录 = > foreign.invoke code=`统计` input=`数值表` output="json"**
|
||||
**统计结果 = [result](`记录`)**
|
||||
|
||||
> print text=[ok](`记录`)
|
||||
> print text=[n](`统计结果`)
|
||||
> print text=[sum](`统计结果`)
|
||||
@@ -0,0 +1,24 @@
|
||||
---
|
||||
title: foreign probe and register
|
||||
import foreign:lib/foreign.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
**探测 = > foreign.probe lang="node"**
|
||||
> print text=[ok](`探测`)
|
||||
> print text=[lang](`探测`)
|
||||
|
||||
`模板` =
|
||||
|
||||
| 步骤 |
|
||||
|------|
|
||||
| node |
|
||||
| "-e" |
|
||||
| {inline} |
|
||||
|
||||
**> foreign.register lang="tiny" template=`模板`**
|
||||
**运行 = > foreign.invoke lang="tiny" source="console.log('tiny')"**
|
||||
**运行输出 = > trim [stdout](`运行`)**
|
||||
> print text=`运行输出`
|
||||
**> foreign.unset lang="tiny"**
|
||||
Reference in new issue
Block a user