script-js 运行时参考
这一页是 JS 插件作者的手册:
send()怎么写、能调用哪些函数、返回什么、会被什么拦住。 只讲机制,不重复"怎么打包"——打包与签名见开发自己的插件。
1. 执行模型
要点:
| 机制 | 行为 |
|---|---|
| 编译 | 整个文件编译一次,按内容 hash 缓存;顶层代码在裸环境执行(没有 host / msg / config),只允许做函数定义与常量 |
| 执行 | 每次投递新建 goja VM,重跑顶层再调用 send——全局状态不跨调用保留 |
| 同步 | send 必须同步返回结果;不支持 async/await 的"等一等再返回" |
| 中断 | 到点用 vm.Interrupt 强制中断,JS 的 try/catch 拦不住 |
| 并发 | 同一次运行的多个 send 会顺序调用同一个已编译程序;程序对象只读共享,并发安全 |
入口签名(两种写法等价,形参或全局都行):
function send(msg, config, host) {
// msg: 这条通知(见 §2)
// config: 渠道配置对象(config.schema.json 校验后的值)
// host: 宿主能力(见 §4)
return { ok: true };
}JS 语言与内置对象
脚本由 goja 执行:ES5.1 完整实现 + 大部分 ES2015,不是完整的现代浏览器环境。
| 可用 | 说明 |
|---|---|
| ES5.1 内置对象 | Object Array String Number Boolean Date RegExp Math JSON Error |
| 常用 ES2015 语法 | let / const、箭头函数、模板字符串、解构、展开、for...of、class |
| 部分 ES2015+ 内置 | Map Set Promise Symbol(随引擎版本变化,别把它们当契约) |
| 业务逻辑 | 字符串/数组/对象处理、签名参数拼接、响应解析——够用 |
| 不可用 | 替代 |
|---|---|
require / import / npm 包 | 把逻辑写进同一个 send.js;网络用 host.http |
fetch / XMLHttpRequest | host.http.* |
process / 环境变量 / 文件系统 | 一律通过渠道 config 传入 |
setTimeout / setInterval | 没有定时器;需要等待就交给 delay 节点或引擎重试 |
console | host.log(level, value) |
async / await | send() 必须同步返回;宿主负责超时与重试 |
2. msg 的形状
| 字段 | 类型 | 说明 |
|---|---|---|
target | string | 首个接收方的 ID(兼容单目标插件) |
targets | [{kind, id}] | 全部接收方;kind ∈ user/phone/email/chat_id/group/raw |
format | string | text / markdown / card / custom |
payload | object | 消息负载:title / content / markdown / card / attachments / extras |
variables | map<string,string> | 模板与策略变量 |
metadata | map<string,string> | 追踪标签(不参与渲染) |
attachments | [{type,url,name,mime,size}] | 附件引用(只传 URL) |
priority | string | low/normal/high/urgent |
created_at | string | RFC3339 |
config 就是渠道配置原样 JSON(插件 schema 里的字段),可能额外带平台级键(default_target、rate_per_sec 等),脚本不必关心。
3. 返回值契约(决定重试与死信)
// 成功
return { ok: true, external_id: "sms-8891" };
// 失败,但值得重试(网络抖动、对端 5xx、限流)
return { ok: false, retryable: true, error: "upstream 503" };
// 失败且重试没意义(参数错、被拉黑、token 失效)
return { ok: false, retryable: false, error: "invalid access_token" };| 返回值 | 引擎行为 |
|---|---|
{ok:true, external_id?} | 投递成功;external_id 进投递记录(用于对账) |
{ok:false, retryable:true, error?} | 指数退避后重试,直到 max_attempts |
{ok:false, retryable:false, error?} | 直接进死信,可人工重放 |
{ok:false}(省略 retryable) | 视为不可重试 |
非对象 / 缺 ok / 字段类型不符 | 契约错误:error 返回,不可重试 |
| 抛 JS 异常 | 适配器错误:error 返回,不可重试 |
| 执行超时 / 被取消 | 返回 ok:false, retryable:true(error="脚本执行超时/中断") |
网络错误要自己翻译
host.http.* 遇到网络错误是抛异常而不是返回状态码。想重试就 try/catch 后返回 retryable: true;不 catch 就会变成"适配器错误",直接死信。
4. 可用的宿主函数
始终注入(无需声明权限)
| 函数 | 说明 |
|---|---|
host.json.encode(v) | 序列化为 JSON 字符串 |
host.json.decode(s) | 解析 JSON;非法 JSON 抛错 |
host.log(level, v) | 写一条宿主日志;对象里名字含 password/token/secret/key/authorization 的值打码为 ***,整体截断 2KB |
host.time.now() | 当前时间,RFC3339 字符串 |
host.url_encode(s) | 百分号编码(空格 → %20,等价 encodeURIComponent) |
host.http(permissions.http: true)
| 函数 | 签名 |
|---|---|
host.http.get(url, opts?) | 同下,GET |
host.http.post(url, opts?) | 同下,POST |
host.http.put(url, opts?) | 同下,PUT |
host.http.del(url, opts?) | 同下,DELETE |
host.http.request(method, url, opts?) | 任意方法 |
const resp = host.http.post("https://api.example.com/send", {
headers: { "X-Token": config.token }, // 可选
json: { text: "hello" }, // 与 body 二选一,json 优先;自动补 Content-Type
// body: '{"text":"hello"}', // 原样发送字符串
timeoutMs: 3000 // 只能缩短,不能超过插件整体超时
});
resp.status // number,任何状态码都正常返回
resp.text // string,响应体(最多读 1MB)
resp.json // 解析成功时的对象,失败为 undefined
resp.headers // { "content-type": "application/json", ... }规则:
- 任何 HTTP 状态码都不抛异常,成功与否由脚本判断;
- 网络错误 / 读取失败 / 白名单命中失败 → 抛异常;
- 响应体最多 1MB,超出部分丢弃;
- 跟随重定向,但每一跳都重新校验
hosts白名单(最多 10 跳)。
host.crypto(permissions.crypto 非空)
| 函数 | 说明 |
|---|---|
host.crypto.hmac_sha256(key, msg) | HMAC-SHA256 十六进制 |
host.crypto.hmac_sha256_base64(key, msg) | HMAC-SHA256 Base64(钉钉/飞书加签常用) |
host.crypto.sha256(msg) | SHA-256 十六进制 |
host.crypto.base64_encode(s) / base64_decode(s) | Base64 编解码 |
声明的是"组",不是算法
permissions.crypto: ["hmac-sha256"] 只是文档性声明:列表非空即注入整个 crypto 组(含 sha256/base64)。权限粒度到组,不到单个算法。
host.render(permissions.render: true)
host.render("【{{ .msg.priority }}】{{ .msg.payload.title }}")
host.render("主题:{{ .msg.payload.title }}", { custom: 1 }) // 自定义数据Go text/template 语法,函数 json/default/lower/upper/trim;不传第二个参数时上下文是 {msg, config},缺失键按零值渲染。
host.smtp.send(permissions.smtp: true)
host.smtp.send({
server: { host: "smtp.example.com", port: 587, username: "u", password: "p", tls: "starttls" },
from: "bot@example.com",
to: ["ops@example.com"],
cc: [],
subject: "告警",
text: "纯文本正文",
html: "<b>HTML 正文</b>"
}); // 全部收件人送达返回 true,失败抛错host.mqtt.publish(permissions.mqtt: true)
host.mqtt.publish({
host: "broker.internal", port: 1883,
client_id: "herald", username: "u", password: "p", tls: false,
topic: "push/alerts", payload: "hello", qos: 1, retain: false
}); // QoS1 等到 PUBACK 才返回 true连接按 (host,port,client_id,username) 复用长连接;失败抛错,脚本可按错误文本判断是否重试(鉴权、topic 非法通常不可重试)。
没有的东西
不存在:require / import / fetch / XMLHttpRequest / process / fs / Buffer / setTimeout / console / npm 包。网络只能走 host.http(或 host.smtp / host.mqtt),日志只能走 host.log。
5. 规则与限制
权限(plugin.yaml)
permissions:
http: true # host.http.*
crypto: [hmac-sha256] # 非空 → host.crypto.*
render: true # host.render
smtp: false # host.smtp.send
mqtt: false # host.mqtt.publish
hosts: ["oapi.dingtalk.com", "*.example.com"] # 出站域名白名单,空 = 不限未声明组里的对象是 undefined,调用会抛 TypeError。hosts 白名单同时约束 host.http、重定向每一跳与 host.mqtt。
资源限制
| 限制 | 来源 | 缺省 | 超出后果 |
|---|---|---|---|
timeout_ms | plugin.yaml → limits.timeout_ms | 未设则只受投递尝试超时约束(queue.attempt_timeout,默认 15s) | 强制中断,可重试;官方插件取 5–15s |
max_depth | limits.max_depth | 引擎默认调用栈 | 栈溢出 → 脚本异常(不可重试) |
max_input_bytes | limits.max_input_bytes | 不限 | 输入超限 → 适配器错误(不可重试) |
max_steps | limits.max_steps | 仅声明、当前不强制 | 失控脚本靠超时兜底 |
| HTTP 响应体 | 运行时固定 | 1MB | 截断,不报错 |
host.log 输出 | 运行时固定 | 2KB | 截断 |
行为规则
- 脚本只做协议适配:构造请求、签名、解析响应。重试策略、路由、去重都在引擎里,别在脚本中写重试循环。
- 至少一次:同一投递可能被执行多次,脚本的副作用要幂等,或把对端的
external_id带回来。 - 无跨调用状态:每次投递都是全新 VM,顶层会重跑;模块级变量不会保留。
- 顶层不要碰宿主:顶层在裸环境执行,
host还不存在。 - 不要吞异常:不 catch 的异常会被当成适配器 bug,直接死信;要么处理,要么让它按"不可重试"暴露。
- 别把密钥写进日志:
host.log会按字段名打码,但字符串形式的日志不会。
6. 完整示例:带加签的 HTTP 网关
plugin.yaml:
id: acme-im
name: ACME 即时消息
version: 1.0.0
runtime: script-js
entry: send.js
mode: outbound
capabilities: [text, markdown]
permissions:
http: true
crypto: [hmac-sha256]
render: true
hosts: ["im.acme.example.com"]
limits:
timeout_ms: 5000
max_depth: 32
max_input_bytes: 65536send.js:
function send(msg, config, host) {
// 1) 渲染文案:markdown 优先,其次 content,最后退回 title
var text = msg.payload.markdown || msg.payload.content || msg.payload.title || "通知";
if (msg.payload.title && msg.payload.markdown) {
text = "### " + msg.payload.title + "\n\n" + text;
}
// 2) 计算签名(时间戳 + 密钥)
var ts = String(Date.now());
var sign = host.crypto.hmac_sha256_base64(config.secret, ts + "\n" + config.secret);
var url = config.endpoint + "&ts=" + host.url_encode(ts) + "&sign=" + host.url_encode(sign);
// 3) 发请求。网络层异常 = 值得重试;HTTP 状态由脚本判断
var resp;
try {
resp = host.http.post(url, {
json: { msgtype: "markdown", markdown: { text: text } },
timeoutMs: 4000
});
} catch (e) {
return { ok: false, retryable: true, error: "网络错误: " + String(e) };
}
// 4) 业务判定
if (resp.status >= 200 && resp.status < 300 && resp.json && resp.json.code === 0) {
return { ok: true, external_id: String(resp.json.msgid || "") };
}
var retryable = resp.status >= 500 || resp.status === 429;
return {
ok: false,
retryable: retryable,
error: "HTTP " + resp.status + ": " + String(resp.text).slice(0, 200)
};
}
// 可选:试发报告里展示"将要发出的内容"
function describe(msg, config) {
return msg.payload.title || "通知";
}7. 调试与常见错误
| 手段 | 用法 |
|---|---|
| 渠道试发 | POST /v1/admin/channels/{id}/test:真实调一次 send(),返回脱敏后的请求与响应摘要 |
| 日志 | host.log("info", {...}) → 平台日志(/#/logs 或 GET /v1/admin/logs) |
| 单测 | 把 send.js 放进 plugins/<id>/,启动后建渠道试发,失败信息会写进投递记录 |
| 报错 | 原因 |
|---|---|
脚本 xxx 缺少全局 send 函数 | 入口函数没定义,或被 const send = ... 之外的写法包住了 |
send() 返回值不是对象 / 缺少 ok 字段 | 返回值不符合契约(常见于忘记 return) |
目标域名 x 不在 AllowedHosts 白名单内 | permissions.hosts 没写该域名 |
脚本执行超时/中断 | 超过 timeout_ms,或对端太慢;缩短 timeoutMs 或放大 timeout_ms |
host.http is undefined | 没声明 permissions.http: true |
crypto.hmac_sha256: 第 1 个参数必须是字符串 | 参数类型错,注意密钥/消息顺序(key 在前) |