loadVM compiles and runs script source in a new Goja VM, returning a ready VMWrapper. scriptLabel is used in compile error messages (e.g. "room-42"). afterLoad, if non-nil, is called with the raw runtime after RunProgram succeeds; it runs under scriptLoadTimeout and is intended for onLoad() hooks.
(scriptLabel string, source string, afterLoad func(*goja.Runtime) error)
| 49 | // afterLoad, if non-nil, is called with the raw runtime after RunProgram |
| 50 | // succeeds; it runs under scriptLoadTimeout and is intended for onLoad() hooks. |
| 51 | func loadVM(scriptLabel string, source string, afterLoad func(*goja.Runtime) error) (*VMWrapper, error) { |
| 52 | vm := goja.New() |
| 53 | setAllScriptingFunctions(vm) |
| 54 | |
| 55 | prg, err := goja.Compile(scriptLabel, source, false) |
| 56 | if err != nil { |
| 57 | return nil, fmt.Errorf("Compile: %w", err) |
| 58 | } |
| 59 | |
| 60 | tmr := time.AfterFunc(scriptLoadTimeout, func() { |
| 61 | vm.Interrupt(errTimeout) |
| 62 | }) |
| 63 | _, err = vm.RunProgram(prg) |
| 64 | vm.ClearInterrupt() |
| 65 | tmr.Stop() |
| 66 | if err != nil { |
| 67 | return nil, wrapVMError("RunProgram", err) |
| 68 | } |
| 69 | |
| 70 | if afterLoad != nil { |
| 71 | tmr = time.AfterFunc(scriptLoadTimeout, func() { |
| 72 | vm.Interrupt(errTimeout) |
| 73 | }) |
| 74 | err = afterLoad(vm) |
| 75 | vm.ClearInterrupt() |
| 76 | tmr.Stop() |
| 77 | if err != nil { |
| 78 | return nil, wrapVMError("onLoad", err) |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | vmw := newVMWrapper(vm, 0) |
| 83 | vmw.loadedAt = time.Now() |
| 84 | return vmw, nil |
| 85 | } |
| 86 | |
| 87 | // wrapVMError wraps a VM execution error with a context prefix and logs it. |
| 88 | func wrapVMError(context string, err error) error { |
no test coverage detected