开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
main
分支 (1)
标签 (27)
main
cel/v0.0.1
expr/v0.0.1
gpython/v0.0.1
javascript/v0.0.6
lua/v0.0.6
source/consul/v0.0.1
source/etcd/v0.0.1
source/git/v0.0.1
source/http/v0.0.1
source/redis/v0.0.1
source/s3/v0.0.1
starlark/v0.0.1
tcl/v0.0.1
wazero/v0.0.1
yaegi/v0.0.1
v0.0.6
javascript/v0.0.5
lua/v0.0.5
v0.0.5
v0.0.4
main
分支 (1)
标签 (27)
main
cel/v0.0.1
expr/v0.0.1
gpython/v0.0.1
javascript/v0.0.6
lua/v0.0.6
source/consul/v0.0.1
source/etcd/v0.0.1
source/git/v0.0.1
source/http/v0.0.1
source/redis/v0.0.1
source/s3/v0.0.1
starlark/v0.0.1
tcl/v0.0.1
wazero/v0.0.1
yaegi/v0.0.1
v0.0.6
javascript/v0.0.5
lua/v0.0.5
v0.0.5
v0.0.4
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
main
分支 (1)
标签 (27)
main
cel/v0.0.1
expr/v0.0.1
gpython/v0.0.1
javascript/v0.0.6
lua/v0.0.6
source/consul/v0.0.1
source/etcd/v0.0.1
source/git/v0.0.1
source/http/v0.0.1
source/redis/v0.0.1
source/s3/v0.0.1
starlark/v0.0.1
tcl/v0.0.1
wazero/v0.0.1
yaegi/v0.0.1
v0.0.6
javascript/v0.0.5
lua/v0.0.5
v0.0.5
v0.0.4
go-scripts
/
javascript
/
javascript_engine.go
go-scripts
/
javascript
/
javascript_engine.go
javascript_engine.go 16.09 KB
一键复制 编辑 原始数据 按行查看 历史
tx7do 提交于 2026年06月09日 10:20 +08:00 . feat(engine): 添加热重载功能并重构脚本源接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
package js
import (
"context"
"fmt"
"sync"
"github.com/dop251/goja"
scriptEngine "github.com/tx7do/go-scripts"
"github.com/tx7do/go-scripts/source"
)
func init() {
_ = scriptEngine.Register(scriptEngine.JavaScriptType, func() (scriptEngine.Engine, error) {
return newJavascriptEngine()
})
}
// engine is the JavaScript script engine implementation.
//
// Lock ordering convention:
// - Always acquire `mu` (or its read lock) before `execMu`.
// - Release in reverse order (execMu first, then mu).
// - Never acquire `mu` while holding `execMu` to avoid deadlocks.
//
// This convention protects the consistency of runtime / programs / initialized.
type engine struct {
runtime *goja.Runtime // the JavaScript runtime
programs []*goja.Program // compiled programs queued for execution
source source.Reader // optional script source (File / S3 / Mem / ...)
initialized bool
lastError error
mu sync.RWMutex // protects initialized, programs and source
execMu sync.Mutex // protects runtime
lastErrorMu sync.RWMutex // protects lastError
// Hot reload state
watchers map[string]context.CancelFunc // key -> cancel func for the watch goroutine
watchersMu sync.Mutex // protects watchers
}
// newJavascriptEngine creates a JavaScript engine instance.
func newJavascriptEngine() (*engine, error) {
return &engine{
initialized: false,
watchers: make(map[string]context.CancelFunc),
}, nil
}
// GetType returns the script engine type.
func (e *engine) GetType() scriptEngine.Type {
return scriptEngine.JavaScriptType
}
// Init initializes the engine.
func (e *engine) Init(_ context.Context) error {
newRt := goja.New()
e.mu.Lock()
defer e.mu.Unlock()
if e.initialized {
e.setLastError(ErrJavascriptEngineAlreadyInitialized)
return ErrJavascriptEngineAlreadyInitialized
}
e.execMu.Lock()
defer e.execMu.Unlock()
e.runtime = newRt
e.initialized = true
e.lastError = nil
return nil
}
// Close destroys the engine and releases underlying resources.
func (e *engine) Close() error {
e.mu.Lock()
defer e.mu.Unlock()
if !e.initialized {
e.setLastError(ErrJavascriptEngineNotInitialized)
return ErrJavascriptEngineNotInitialized
}
// Stop all active watchers.
e.stopAllWatchers()
e.execMu.Lock()
defer e.execMu.Unlock()
e.initialized = false
e.runtime = nil
e.programs = nil
e.lastErrorMu.Lock()
e.lastError = nil
e.lastErrorMu.Unlock()
return nil
}
// ClearPrograms drops all cached compiled programs.
func (e *engine) ClearPrograms() {
e.mu.Lock()
defer e.mu.Unlock()
//e.program = nil
e.programs = nil
}
// IsInitialized reports whether the engine has been initialized.
func (e *engine) IsInitialized() bool {
e.mu.RLock()
defer e.mu.RUnlock()
return e.initialized
}
////////////////////////////////////////////////////////////////////////////////
// ScriptSource injection & access
////////////////////////////////////////////////////////////////////////////////
// SetSource binds a ScriptSource (FileSource / S3 / Mem / Multi / ...) to the
// engine. Subsequent Load / LoadMulti / ExecuteFromKey / ExecuteFromKeys calls
// read through it. Passing nil clears any previously bound source.
func (e *engine) SetSource(source source.Reader) {
e.mu.Lock()
defer e.mu.Unlock()
e.source = source
}
// GetSource returns the currently bound ScriptSource, or nil if none has been set.
func (e *engine) GetSource() source.Reader {
e.mu.RLock()
defer e.mu.RUnlock()
return e.source
}
////////////////////////////////////////////////////////////////////////////////
// Script loading
////////////////////////////////////////////////////////////////////////////////
// Load loads a single script from the bound Source using the given key
// (path / object key / script id, ...). The loaded program is appended to the
// queue consumed later by Execute.
func (e *engine) Load(ctx context.Context, key string) error {
if !e.IsInitialized() {
e.setLastError(ErrJavascriptEngineNotInitialized)
return ErrJavascriptEngineNotInitialized
}
e.mu.RLock()
src := e.source
e.mu.RUnlock()
if src == nil {
err := fmt.Errorf("javascript engine: no source bound")
e.setLastError(err)
return err
}
code, err := src.Load(ctx, key)
if err != nil {
e.setLastError(err)
return err
}
return e.LoadString(ctx, key, code)
}
// LoadMulti loads multiple scripts from the bound Source in order. It aborts on
// the first error.
func (e *engine) LoadMulti(ctx context.Context, keys []string) error {
for _, k := range keys {
if err := e.Load(ctx, k); err != nil {
return err
}
}
return nil
}
// LoadString compiles and queues an inline script. `name` is used for
// diagnostics (stack traces, error messages); it is not used to look up the
// script on disk. LoadString does NOT go through the bound Source.
func (e *engine) LoadString(_ context.Context, name string, code string) error {
if !e.IsInitialized() {
e.setLastError(ErrJavascriptEngineNotInitialized)
return ErrJavascriptEngineNotInitialized
}
program, err := goja.Compile(name, code, true)
if err != nil {
e.setLastError(err)
return err
}
e.mu.Lock()
defer e.mu.Unlock()
if !e.initialized {
e.setLastError(ErrJavascriptEngineNotInitialized)
return ErrJavascriptEngineNotInitialized
}
e.programs = append(e.programs, program)
e.ClearError()
return nil
}
////////////////////////////////////////////////////////////////////////////////
// Script execution
////////////////////////////////////////////////////////////////////////////////
// Execute runs every program previously loaded via Load/LoadMulti/LoadString
// and returns the collected results in order.
func (e *engine) Execute(ctx context.Context) (any, error) {
if !e.IsInitialized() {
e.setLastError(ErrJavascriptEngineNotInitialized)
return nil, ErrJavascriptEngineNotInitialized
}
// Snapshot the programs slice so concurrent LoadXxx calls cannot mutate it
// while we iterate.
e.mu.RLock()
progs := make([]*goja.Program, len(e.programs))
copy(progs, e.programs)
e.mu.RUnlock()
if len(progs) == 0 {
e.setLastError(ErrJavascriptNoProgramLoaded)
return nil, ErrJavascriptNoProgramLoaded
}
results := make([]any, 0, len(progs))
for _, p := range progs {
res, err := e.RunProgram(ctx, p)
if err != nil {
// RunProgram already recorded lastError.
return nil, err
}
results = append(results, res)
}
e.ClearError()
return results, nil
}
// ExecuteFromKey loads the script identified by `key` from the bound Source
// and immediately runs it, all in one step. The bound Source must be non-nil.
func (e *engine) ExecuteFromKey(ctx context.Context, key string) (any, error) {
if !e.IsInitialized() {
e.setLastError(ErrJavascriptEngineNotInitialized)
return nil, ErrJavascriptEngineNotInitialized
}
e.mu.RLock()
src := e.source
e.mu.RUnlock()
if src == nil {
err := fmt.Errorf("javascript engine: no source bound")
e.setLastError(err)
return nil, err
}
code, err := src.Load(ctx, key)
if err != nil {
e.setLastError(err)
return nil, err
}
return e.ExecuteString(ctx, key, code)
}
// ExecuteFromKeys is the multi-key variant of ExecuteFromKey; results are
// returned in the same order as `keys`.
func (e *engine) ExecuteFromKeys(ctx context.Context, keys []string) ([]any, error) {
results := make([]any, 0, len(keys))
for _, k := range keys {
res, err := e.ExecuteFromKey(ctx, k)
if err != nil {
return nil, err
}
results = append(results, res)
}
return results, nil
}
// ExecuteString compiles and immediately runs the inline script (name+code),
// bypassing the bound Source. `name` is used for diagnostics (stack traces).
func (e *engine) ExecuteString(ctx context.Context, name string, code string) (any, error) {
if !e.IsInitialized() {
e.setLastError(ErrJavascriptEngineNotInitialized)
return nil, ErrJavascriptEngineNotInitialized
}
// Compile with the given name so stack traces point to a meaningful label.
program, err := goja.Compile(name, code, true)
if err != nil {
e.setLastError(err)
return nil, err
}
done := make(chan struct{})
defer close(done)
go func() {
select {
case <-ctx.Done():
e.execMu.Lock()
rt := e.runtime
e.execMu.Unlock()
if rt != nil {
rt.Interrupt(ctx.Err())
}
case <-done:
}
}()
result, err := e.withRuntime(func(rt *goja.Runtime) (any, error) {
var retErr error
defer func() {
if r := recover(); r != nil {
retErr = fmt.Errorf("panic in ExecuteString: %v", r)
}
}()
val, runErr := rt.RunProgram(program)
if runErr != nil || val == nil {
return nil, runErr
}
return val.Export(), retErr
})
if err != nil {
e.setLastError(err)
return nil, err
}
e.ClearError()
return result, nil
}
////////////////////////////////////////////////////////////////////////////////
// Globals, functions, modules
////////////////////////////////////////////////////////////////////////////////
// RegisterGlobal registers a global variable in the JavaScript runtime.
func (e *engine) RegisterGlobal(name string, value any) error {
if !e.IsInitialized() {
e.setLastError(ErrJavascriptEngineNotInitialized)
return ErrJavascriptEngineNotInitialized
}
e.execMu.Lock()
defer e.execMu.Unlock()
if e.runtime == nil {
e.setLastError(ErrJavascriptRuntimeNotInitialized)
return ErrJavascriptRuntimeNotInitialized
}
_ = e.runtime.Set(name, value)
e.ClearError()
return nil
}
// GetGlobal reads a global variable from the JavaScript runtime.
func (e *engine) GetGlobal(name string) (any, error) {
if !e.IsInitialized() {
e.setLastError(ErrJavascriptEngineNotInitialized)
return nil, ErrJavascriptEngineNotInitialized
}
e.execMu.Lock()
defer e.execMu.Unlock()
if e.runtime == nil {
e.setLastError(ErrJavascriptRuntimeNotInitialized)
return nil, ErrJavascriptRuntimeNotInitialized
}
val := e.runtime.Get(name)
if val == nil {
err := fmt.Errorf("global variable %s not found", name)
e.setLastError(err)
return nil, err
}
result := val.Export()
e.ClearError()
return result, nil
}
// RegisterFunction registers a global function in the JavaScript runtime.
func (e *engine) RegisterFunction(name string, fn any) error {
if !e.IsInitialized() {
e.setLastError(ErrJavascriptEngineNotInitialized)
return ErrJavascriptEngineNotInitialized
}
e.execMu.Lock()
defer e.execMu.Unlock()
if e.runtime == nil {
e.setLastError(ErrJavascriptRuntimeNotInitialized)
return ErrJavascriptRuntimeNotInitialized
}
_ = e.runtime.Set(name, fn)
e.ClearError()
return nil
}
// CallFunction calls the named function with args and returns its result.
func (e *engine) CallFunction(ctx context.Context, name string, args ...any) (any, error) {
if !e.IsInitialized() {
e.setLastError(ErrJavascriptEngineNotInitialized)
return nil, ErrJavascriptEngineNotInitialized
}
done := make(chan struct{})
defer close(done)
go func() {
select {
case <-ctx.Done():
e.execMu.Lock()
rt := e.runtime
e.execMu.Unlock()
if rt != nil {
rt.Interrupt(ctx.Err())
}
case <-done:
}
}()
result, err := e.withRuntime(func(rt *goja.Runtime) (any, error) {
var (
res any
retErr error
)
defer func() {
if r := recover(); r != nil {
retErr = fmt.Errorf("panic in CallFunction %s: %v", name, r)
}
}()
v := rt.Get(name)
if v == nil {
return nil, fmt.Errorf("function %s not found", name)
}
fn, ok := goja.AssertFunction(v)
if !ok {
return nil, fmt.Errorf("%s is not a function", name)
}
vals := make([]goja.Value, len(args))
for i, a := range args {
vals[i] = rt.ToValue(a)
}
callRes, callErr := fn(goja.Undefined(), vals...)
if callErr != nil {
return nil, callErr
}
if callRes == nil {
return nil, nil
}
res = callRes.Export()
return res, retErr
})
if err != nil {
e.setLastError(err)
return nil, err
}
e.ClearError()
return result, nil
}
// RegisterModule registers a module (map[string]any or raw value) under name.
func (e *engine) RegisterModule(name string, module any) error {
if !e.IsInitialized() {
e.setLastError(ErrJavascriptEngineNotInitialized)
return ErrJavascriptEngineNotInitialized
}
e.execMu.Lock()
defer e.execMu.Unlock()
if e.runtime == nil {
e.setLastError(ErrJavascriptRuntimeNotInitialized)
return ErrJavascriptRuntimeNotInitialized
}
moduleObj := e.runtime.NewObject()
if m, ok := module.(map[string]any); ok {
for k, v := range m {
_ = moduleObj.Set(k, v)
}
_ = e.runtime.Set(name, moduleObj)
} else {
_ = e.runtime.Set(name, module)
}
e.ClearError()
return nil
}
////////////////////////////////////////////////////////////////////////////////
// Error handling
////////////////////////////////////////////////////////////////////////////////
// GetLastError returns the last error recorded by the engine.
func (e *engine) GetLastError() error {
e.lastErrorMu.RLock()
defer e.lastErrorMu.RUnlock()
return e.lastError
}
// setLastError records the last error under lastErrorMu.
func (e *engine) setLastError(err error) {
e.lastErrorMu.Lock()
defer e.lastErrorMu.Unlock()
e.lastError = err
}
// ClearError clears the last recorded error.
func (e *engine) ClearError() {
e.lastErrorMu.Lock()
defer e.lastErrorMu.Unlock()
e.lastError = nil
}
// withRuntime runs fn while holding execMu, providing safe access to the runtime.
func (e *engine) withRuntime(fn func(rt *goja.Runtime) (any, error)) (any, error) {
e.execMu.Lock()
defer e.execMu.Unlock()
if e.runtime == nil {
return nil, ErrJavascriptRuntimeNotInitialized
}
return fn(e.runtime)
}
// RunProgram runs a compiled goja program with context cancellation support.
func (e *engine) RunProgram(ctx context.Context, program *goja.Program) (any, error) {
if !e.IsInitialized() {
e.setLastError(ErrJavascriptEngineNotInitialized)
return nil, ErrJavascriptEngineNotInitialized
}
done := make(chan struct{})
defer close(done)
go func() {
select {
case <-ctx.Done():
e.execMu.Lock()
rt := e.runtime
e.execMu.Unlock()
if rt != nil {
rt.Interrupt(ctx.Err())
}
case <-done:
}
}()
result, err := e.withRuntime(func(rt *goja.Runtime) (any, error) {
val, err := rt.RunProgram(program)
if err != nil || val == nil {
return nil, err
}
return val.Export(), nil
})
if err != nil {
e.setLastError(err)
return nil, err
}
e.ClearError()
return result, nil
}
////////////////////////////////////////////////////////////////////////////////
// Hot Reload (Watch)
////////////////////////////////////////////////////////////////////////////////
// StartWatch starts watching the script identified by `key` for changes.
// When the source reports a change, the script is automatically reloaded.
// Returns an error if the source is not bound or doesn't implement Watcher.
func (e *engine) StartWatch(ctx context.Context, key string) error {
if !e.IsInitialized() {
e.setLastError(ErrJavascriptEngineNotInitialized)
return ErrJavascriptEngineNotInitialized
}
e.mu.RLock()
src := e.source
e.mu.RUnlock()
if src == nil {
err := fmt.Errorf("javascript engine: no source bound")
e.setLastError(err)
return err
}
watcher, ok := src.(source.Watcher)
if !ok {
err := fmt.Errorf("javascript engine: source does not implement Watcher")
e.setLastError(err)
return err
}
// Stop existing watch for the same key if any.
e.StopWatch(key)
watchCtx, cancel := context.WithCancel(ctx)
e.watchersMu.Lock()
e.watchers[key] = cancel
e.watchersMu.Unlock()
go func() {
ch, err := watcher.Watch(watchCtx, key)
if err != nil {
cancel()
return
}
for range ch {
// Reload the script on change signal.
if loadErr := e.Load(watchCtx, key); loadErr != nil {
// Log but don't stop watching; the source may recover.
scriptEngine.GetLogger().Warn(watchCtx, "javascript engine: hot reload failed",
"key", key, "error", loadErr)
}
}
}()
return nil
}
// StopWatch stops watching the script identified by `key`.
func (e *engine) StopWatch(key string) error {
e.watchersMu.Lock()
defer e.watchersMu.Unlock()
if cancel, ok := e.watchers[key]; ok {
cancel()
delete(e.watchers, key)
}
return nil
}
// stopAllWatchers cancels all active watch goroutines. Called by Close.
func (e *engine) stopAllWatchers() {
e.watchersMu.Lock()
defer e.watchersMu.Unlock()
for key, cancel := range e.watchers {
cancel()
delete(e.watchers, key)
}
}
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

这是一个用 Go 实现的脚本引擎,支持多种脚本语言(当前支持:Lua、JavaScript),旨在让宿主程序能够无缝加载并执行脚本以扩展行为或做快速原型开发。
MIT
使用 MIT 开源许可协议
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/tx7do/go-scripts.git
git@gitee.com:tx7do/go-scripts.git
tx7do
go-scripts
go-scripts
main
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /