context.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package boxctx
  2. import (
  3. "context"
  4. "time"
  5. "github.com/sagernet/sing-box/script/jsc"
  6. "github.com/sagernet/sing/common/logger"
  7. "github.com/dop251/goja"
  8. )
  9. type Context struct {
  10. class jsc.Class[*Module, *Context]
  11. Context context.Context
  12. Logger logger.ContextLogger
  13. Tag string
  14. StartedAt time.Time
  15. ErrorHandler func(error)
  16. }
  17. func FromRuntime(runtime *goja.Runtime) *Context {
  18. contextValue := runtime.Get("context")
  19. if contextValue == nil {
  20. return nil
  21. }
  22. context, isContext := contextValue.Export().(*Context)
  23. if !isContext {
  24. return nil
  25. }
  26. return context
  27. }
  28. func MustFromRuntime(runtime *goja.Runtime) *Context {
  29. context := FromRuntime(runtime)
  30. if context == nil {
  31. panic(runtime.NewTypeError("Missing sing-box context"))
  32. }
  33. return context
  34. }
  35. func createContext(module *Module) jsc.Class[*Module, *Context] {
  36. class := jsc.NewClass[*Module, *Context](module)
  37. class.DefineMethod("toString", (*Context).toString)
  38. return class
  39. }
  40. func (c *Context) toString(call goja.FunctionCall) any {
  41. return "[sing-box Context]"
  42. }