约定:文件名 = 主类型名;同一个类型要拆多个文件时用 类型_子项.go。
engine.go 355 → 231 行。原来混了三件不相干的事
engine_globals.go ← bind / lazyGlobal / freeze / defineReadOnly(96 行)
它是「Go 值 → 只读 JS 全局」的转换层,跟脚本缓存毫无关系
engine_console.go ← console.go,跟上面是同一主题
script.go 325 → 100 行,只留公开方法
script_vm.go ← VM 的取、还、装载。上个 commit 合一的三条路径现在住一起
script_static.go ← static.go
errors.go 364 → 150 行
errors_goja.go ← goja 错误的翻译层
errors_hints.go ← missingGlobalHint,一份 JS 运行时知识库,跟错误分类是
两回事;拆出来之后 missing_global_test.go 才有对应源文件
bundle_finalize.go ← esmwrap.go
bundle.go 收下 validIdent / hashVersion(原来住在 engine.go)
Engine.New 原来排在所有私有函数之后,挪到导出方法那一段。
classify 83 → 54 行:四个 errors.As 分支各手搓一个 8 字段的 &Error{},脚本上下文
那三行重复了 4 遍,抽出 gojaError 构造器。
顺带修四处注释漂移:
Session/会话 代码里叫 Instance,注释里大面积残留。engine_globals.go 那条
「注入会话全局对象失败」还是用户可见文案,而公开 API 里根本
没有「会话」这个概念
Extension 文档示例写 Module() string,接口是 Module() (path, source string)。
这是唯一一段教人写扩展的文档,照抄编译不过
doc.go 的 freeze 说白名单「逐层拷贝成只读对象,不会跨 VM 共享可变的 Go map」,
但那只对 map[string]any 成立。结构体指针和 slice 是**共享同一个
对象**的——扩展走的正是这条路,不该被当成隔离保证
42 lines
1.0 KiB
Go
42 lines
1.0 KiB
Go
package jscriptx
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log/slog"
|
|
"strings"
|
|
)
|
|
|
|
// newConsole 造一个绑定到指定脚本的 console 对象,脚本里的 console.log 等
|
|
// 直接落到结构化日志里,带上 script 字段,方便按脚本名检索。
|
|
func newConsole(logger *slog.Logger, script string) map[string]any {
|
|
at := func(level slog.Level) func(args ...any) {
|
|
return func(args ...any) {
|
|
if !logger.Enabled(context.Background(), level) {
|
|
return
|
|
}
|
|
logger.LogAttrs(context.Background(), level, joinArgs(args),
|
|
slog.String("script", script), slog.String("source", "console"))
|
|
}
|
|
}
|
|
return map[string]any{
|
|
"log": at(slog.LevelInfo),
|
|
"info": at(slog.LevelInfo),
|
|
"debug": at(slog.LevelDebug),
|
|
"warn": at(slog.LevelWarn),
|
|
"error": at(slog.LevelError),
|
|
}
|
|
}
|
|
|
|
// joinArgs 按 console 的习惯用空格拼接参数。
|
|
func joinArgs(args []any) string {
|
|
if len(args) == 0 {
|
|
return ""
|
|
}
|
|
parts := make([]string, 0, len(args))
|
|
for _, a := range args {
|
|
parts = append(parts, fmt.Sprintf("%v", a))
|
|
}
|
|
return strings.Join(parts, " ")
|
|
}
|