go.ketch.com/lib/goja@v0.0.1/README.md (about)

     1  goja
     2  ====
     3  
     4  ECMAScript 5.1(+) implementation in Go.
     5  
     6  [![Go Reference](https://pkg.go.dev/badge/go.ketch.com/lib/goja.svg)](https://pkg.go.dev/go.ketch.com/lib/goja)
     7  
     8  Goja is an implementation of ECMAScript 5.1 in pure Go with emphasis on standard compliance and
     9  performance.
    10  
    11  This project was largely inspired by [otto](https://github.com/robertkrimen/otto).
    12  
    13  Minimum required Go version is 1.16.
    14  
    15  Features
    16  --------
    17  
    18   * Full ECMAScript 5.1 support (including regex and strict mode).
    19   * Passes nearly all [tc39 tests](https://github.com/tc39/test262) for the features implemented so far. The goal is to
    20     pass all of them. See .tc39_test262_checkout.sh for the latest working commit id.
    21   * Capable of running Babel, Typescript compiler and pretty much anything written in ES5.
    22   * Sourcemaps.
    23   * Most of ES6 functionality, still work in progress, see https://go.ketch.com/lib/goja/milestone/1?closed=1
    24   
    25  Known incompatibilities and caveats
    26  -----------------------------------
    27  
    28  ### WeakMap
    29  WeakMap is implemented by embedding references to the values into the keys. This means that as long
    30  as the key is reachable all values associated with it in any weak maps also remain reachable and therefore
    31  cannot be garbage collected even if they are not otherwise referenced, even after the WeakMap is gone.
    32  The reference to the value is dropped either when the key is explicitly removed from the WeakMap or when the
    33  key becomes unreachable.
    34  
    35  To illustrate this:
    36  
    37  ```javascript
    38  var m = new WeakMap();
    39  var key = {};
    40  var value = {/* a very large object */};
    41  m.set(key, value);
    42  value = undefined;
    43  m = undefined; // The value does NOT become garbage-collectable at this point
    44  key = undefined; // Now it does
    45  // m.delete(key); // This would work too
    46  ```
    47  
    48  The reason for it is the limitation of the Go runtime. At the time of writing (version 1.15) having a finalizer
    49  set on an object which is part of a reference cycle makes the whole cycle non-garbage-collectable. The solution
    50  above is the only reasonable way I can think of without involving finalizers. This is the third attempt
    51  (see https://go.ketch.com/lib/goja/issues/250 and https://go.ketch.com/lib/goja/issues/199 for more details).
    52  
    53  Note, this does not have any effect on the application logic, but may cause a higher-than-expected memory usage.
    54  
    55  ### WeakRef and FinalizationRegistry
    56  For the reason mentioned above implementing WeakRef and FinalizationRegistry does not seem to be possible at this stage.
    57  
    58  ### JSON
    59  `JSON.parse()` uses the standard Go library which operates in UTF-8. Therefore, it cannot correctly parse broken UTF-16
    60  surrogate pairs, for example:
    61  
    62  ```javascript
    63  JSON.parse(`"\\uD800"`).charCodeAt(0).toString(16) // returns "fffd" instead of "d800"
    64  ```
    65  
    66  ### Date
    67  Conversion from calendar date to epoch timestamp uses the standard Go library which uses `int`, rather than `float` as per
    68  ECMAScript specification. This means if you pass arguments that overflow int to the `Date()` constructor or  if there is
    69  an integer overflow, the result will be incorrect, for example:
    70  
    71  ```javascript
    72  Date.UTC(1970, 0, 1, 80063993375, 29, 1, -288230376151711740) // returns 29256 instead of 29312
    73  ```
    74  
    75  FAQ
    76  ---
    77  
    78  ### How fast is it?
    79  
    80  Although it's faster than many scripting language implementations in Go I have seen 
    81  (for example it's 6-7 times faster than otto on average) it is not a
    82  replacement for V8 or SpiderMonkey or any other general-purpose JavaScript engine.
    83  You can find some benchmarks [here](https://go.ketch.com/lib/goja/issues/2).
    84  
    85  ### Why would I want to use it over a V8 wrapper?
    86  
    87  It greatly depends on your usage scenario. If most of the work is done in javascript
    88  (for example crypto or any other heavy calculations) you are definitely better off with V8.
    89  
    90  If you need a scripting language that drives an engine written in Go so that
    91  you need to make frequent calls between Go and javascript passing complex data structures
    92  then the cgo overhead may outweigh the benefits of having a faster javascript engine.
    93  
    94  Because it's written in pure Go there are no cgo dependencies, it's very easy to build and it
    95  should run on any platform supported by Go.
    96  
    97  It gives you a much better control over execution environment so can be useful for research.
    98  
    99  ### Is it goroutine-safe?
   100  
   101  No. An instance of goja.Runtime can only be used by a single goroutine
   102  at a time. You can create as many instances of Runtime as you like but 
   103  it's not possible to pass object values between runtimes.
   104  
   105  ### Where is setTimeout()?
   106  
   107  setTimeout() assumes concurrent execution of code which requires an execution
   108  environment, for example an event loop similar to nodejs or a browser.
   109  There is a [separate project](https://github.com/dop251/goja_nodejs) aimed at providing some NodeJS functionality,
   110  and it includes an event loop.
   111  
   112  ### Can you implement (feature X from ES6 or higher)?
   113  
   114  I will be adding features in their dependency order and as quickly as time permits. Please do not ask
   115  for ETAs. Features that are open in the [milestone](https://go.ketch.com/lib/goja/milestone/1) are either in progress
   116  or will be worked on next.
   117  
   118  The ongoing work is done in separate feature branches which are merged into master when appropriate.
   119  Every commit in these branches represents a relatively stable state (i.e. it compiles and passes all enabled tc39 tests),
   120  however because the version of tc39 tests I use is quite old, it may be not as well tested as the ES5.1 functionality. Because there are (usually) no major breaking changes between ECMAScript revisions
   121  it should not break your existing code. You are encouraged to give it a try and report any bugs found. Please do not submit fixes though without discussing it first, as the code could be changed in the meantime.
   122  
   123  ### How do I contribute?
   124  
   125  Before submitting a pull request please make sure that:
   126  
   127  - You followed ECMA standard as close as possible. If adding a new feature make sure you've read the specification,
   128  do not just base it on a couple of examples that work fine.
   129  - Your change does not have a significant negative impact on performance (unless it's a bugfix and it's unavoidable)
   130  - It passes all relevant tc39 tests.
   131  
   132  Current Status
   133  --------------
   134  
   135   * There should be no breaking changes in the API, however it may be extended.
   136   * Some of the AnnexB functionality is missing.
   137  
   138  Basic Example
   139  -------------
   140  
   141  Run JavaScript and get the result value.
   142  
   143  ```go
   144  vm := goja.New()
   145  v, err := vm.RunString("2 + 2")
   146  if err != nil {
   147      panic(err)
   148  }
   149  if num := v.Export().(int64); num != 4 {
   150      panic(num)
   151  }
   152  ```
   153  
   154  Passing Values to JS
   155  --------------------
   156  Any Go value can be passed to JS using Runtime.ToValue() method. See the method's [documentation](https://pkg.go.dev/go.ketch.com/lib/goja#Runtime.ToValue) for more details.
   157  
   158  Exporting Values from JS
   159  ------------------------
   160  A JS value can be exported into its default Go representation using Value.Export() method.
   161  
   162  Alternatively it can be exported into a specific Go variable using [Runtime.ExportTo()](https://pkg.go.dev/go.ketch.com/lib/goja#Runtime.ExportTo) method.
   163  
   164  Within a single export operation the same Object will be represented by the same Go value (either the same map, slice or
   165  a pointer to the same struct). This includes circular objects and makes it possible to export them.
   166  
   167  Calling JS functions from Go
   168  ----------------------------
   169  There are 2 approaches:
   170  
   171  - Using [AssertFunction()](https://pkg.go.dev/go.ketch.com/lib/goja#AssertFunction):
   172  ```go
   173  vm := New()
   174  _, err := vm.RunString(`
   175  function sum(a, b) {
   176      return a+b;
   177  }
   178  `)
   179  if err != nil {
   180      panic(err)
   181  }
   182  sum, ok := AssertFunction(vm.Get("sum"))
   183  if !ok {
   184      panic("Not a function")
   185  }
   186  
   187  res, err := sum(Undefined(), vm.ToValue(40), vm.ToValue(2))
   188  if err != nil {
   189      panic(err)
   190  }
   191  fmt.Println(res)
   192  // Output: 42
   193  ```
   194  - Using [Runtime.ExportTo()](https://pkg.go.dev/go.ketch.com/lib/goja#Runtime.ExportTo):
   195  ```go
   196  const SCRIPT = `
   197  function f(param) {
   198      return +param + 2;
   199  }
   200  `
   201  
   202  vm := New()
   203  _, err := vm.RunString(SCRIPT)
   204  if err != nil {
   205      panic(err)
   206  }
   207  
   208  var fn func(string) string
   209  err = vm.ExportTo(vm.Get("f"), &fn)
   210  if err != nil {
   211      panic(err)
   212  }
   213  
   214  fmt.Println(fn("40")) // note, _this_ value in the function will be undefined.
   215  // Output: 42
   216  ```
   217  
   218  The first one is more low level and allows specifying _this_ value, whereas the second one makes the function look like
   219  a normal Go function.
   220  
   221  Mapping struct field and method names
   222  -------------------------------------
   223  By default, the names are passed through as is which means they are capitalised. This does not match
   224  the standard JavaScript naming convention, so if you need to make your JS code look more natural or if you are
   225  dealing with a 3rd party library, you can use a [FieldNameMapper](https://pkg.go.dev/go.ketch.com/lib/goja#FieldNameMapper):
   226  
   227  ```go
   228  vm := New()
   229  vm.SetFieldNameMapper(TagFieldNameMapper("json", true))
   230  type S struct {
   231      Field int `json:"field"`
   232  }
   233  vm.Set("s", S{Field: 42})
   234  res, _ := vm.RunString(`s.field`) // without the mapper it would have been s.Field
   235  fmt.Println(res.Export())
   236  // Output: 42
   237  ```
   238  
   239  There are two standard mappers: [TagFieldNameMapper](https://pkg.go.dev/go.ketch.com/lib/goja#TagFieldNameMapper) and
   240  [UncapFieldNameMapper](https://pkg.go.dev/go.ketch.com/lib/goja#UncapFieldNameMapper), or you can use your own implementation.
   241  
   242  Native Constructors
   243  -------------------
   244  
   245  In order to implement a constructor function in Go use `func (goja.ConstructorCall) *goja.Object`.
   246  See [Runtime.ToValue()](https://pkg.go.dev/go.ketch.com/lib/goja#Runtime.ToValue) documentation for more details.
   247  
   248  Regular Expressions
   249  -------------------
   250  
   251  Goja uses the embedded Go regexp library where possible, otherwise it falls back to [regexp2](https://github.com/dlclark/regexp2).
   252  
   253  Exceptions
   254  ----------
   255  
   256  Any exception thrown in JavaScript is returned as an error of type *Exception. It is possible to extract the value thrown
   257  by using the Value() method:
   258  
   259  ```go
   260  vm := New()
   261  _, err := vm.RunString(`
   262  
   263  throw("Test");
   264  
   265  `)
   266  
   267  if jserr, ok := err.(*Exception); ok {
   268      if jserr.Value().Export() != "Test" {
   269          panic("wrong value")
   270      }
   271  } else {
   272      panic("wrong type")
   273  }
   274  ```
   275  
   276  If a native Go function panics with a Value, it is thrown as a Javascript exception (and therefore can be caught):
   277  
   278  ```go
   279  var vm *Runtime
   280  
   281  func Test() {
   282      panic(vm.ToValue("Error"))
   283  }
   284  
   285  vm = New()
   286  vm.Set("Test", Test)
   287  _, err := vm.RunString(`
   288  
   289  try {
   290      Test();
   291  } catch(e) {
   292      if (e !== "Error") {
   293          throw e;
   294      }
   295  }
   296  
   297  `)
   298  
   299  if err != nil {
   300      panic(err)
   301  }
   302  ```
   303  
   304  Interrupting
   305  ------------
   306  
   307  ```go
   308  func TestInterrupt(t *testing.T) {
   309      const SCRIPT = `
   310      var i = 0;
   311      for (;;) {
   312          i++;
   313      }
   314      `
   315  
   316      vm := New()
   317      time.AfterFunc(200 * time.Millisecond, func() {
   318          vm.Interrupt("halt")
   319      })
   320  
   321      _, err := vm.RunString(SCRIPT)
   322      if err == nil {
   323          t.Fatal("Err is nil")
   324      }
   325      // err is of type *InterruptError and its Value() method returns whatever has been passed to vm.Interrupt()
   326  }
   327  ```
   328  
   329  NodeJS Compatibility
   330  --------------------
   331  
   332  There is a [separate project](https://github.com/dop251/goja_nodejs) aimed at providing some of the NodeJS functionality.