0
Fork 0
mirror of https://github.com/dop251/goja.git synced 2026-11-17 19:47:16 +00:00
ECMAScript/JavaScript engine in pure Go
  • Go 99.8%
  • Perl 0.2%
Find a file
Shounak Joshi c18a77e471
Fixed setUTCMilliseconds and setMilliseconds computing from the wrong second before the epoch (#865)
* Fixed setUTCMilliseconds and setMilliseconds computing from the wrong second before the epoch.

Both setters took the second of the time value with `tv / 1e3`, and Go's
integer division truncates towards zero: a time value before the epoch was
placed in the second after it, so -4 ms was treated as being in the second
that follows the epoch.

The seconds of a time value before the epoch are now the ones of the second
it belongs to.

	new Date(-4).setUTCMilliseconds(2)   -998   (was 2)
	new Date(-1).setUTCMilliseconds(0)  -1000   (was 0)
	new Date(-765).setUTCMilliseconds(1000000)  999000   (was 1000000)
	new Date(-4).setUTCMilliseconds(-2)  -1002   (was -2)

The other setters (setUTCSeconds to setUTCFullYear, setTime) and the getters
are not affected.

* Simplify the before-epoch check as suggested by dop251
History 2026-11-17 13:25:07 +00:00
.github/workflows Update actions/checkout and actions/setup-go to v7 2026-10-22 10:20:40 +07:00
ast Don't name functions assigned to an identifier in parentheses 2026-11-02 17:32:59 -03:00
file Improved cross-OS compatibility for sourcemap URL resolution. 2025-03-05 21:57:36 +00:00
ftoa fix(ftoa): don't let rounding carry overwrite the sign in toPrecision/toExponential 2026-11-15 12:31:48 -04:00
goja Removed the usage of deprecated ioutil package. Bumped minimum Go version to 1.16. 2022-08-13 11:31:03 +01:00
parser Fix #860 issues 2-4 (#879) 2026-11-16 23:46:14 +00:00
testdata Initial commit 2016-11-04 22:06:38 +00:00
token Implemented logical assignment operators. Closes #647. 2025-03-07 17:58:08 +00:00
unistring Got rid of deprecated reflect.SliceHeader, reflect.StringHeader and reflect.PtrTo 2026-06-03 13:58:02 +01:00
.gitignore Initial commit 2016-11-04 22:06:38 +00:00
.tc39_test262_checkout.sh Fix tc39 tests on Windows 2026-08-25 22:17:54 +03:00
array.go Follow Object Environment Record semantics for binding lookups and fix 2026-10-18 12:31:03 +01:00
array_sparse.go Follow Object Environment Record semantics for binding lookups and fix 2026-10-18 12:31:03 +01:00
array_sparse_test.go Fixed export of sparse arrays when there are index properties on the prototype chain. Fixes #765 2026-10-04 20:49:18 +01:00
array_test.go Fix the list of Array.prototype[Symbol.unscopables] properties 2026-11-08 03:09:04 +05:00
base64.go Refactored and optimised base64 decoding (50-1500% improvement in throughput). 2026-09-01 14:25:49 +01:00
builtin_array.go Fix the list of Array.prototype[Symbol.unscopables] properties 2026-11-08 03:09:04 +05:00
builtin_array_circular_test.go Fix stack overflow when converting arrays with circular references to primitives (#695) 2026-01-06 13:18:23 +00:00
builtin_arrray_test.go Handle nil FunctionCall.Arguments values and made sure FunctionCall.This is never nil. 2026-11-04 19:41:12 +00:00
builtin_bigint.go Fixed parsing of number literals overflowing int64 and BigInts 2026-10-28 21:31:08 +00:00
builtin_bigint_test.go Fixed parsing of number literals overflowing int64 and BigInts 2026-10-28 21:31:08 +00:00
builtin_boolean.go Implemented template-backed objects and used them for most of the built-ins. Closes #524, closes #459. 2023-09-06 17:07:31 +01:00
builtin_date.go Fixed setUTCMilliseconds and setMilliseconds computing from the wrong second before the epoch (#865) 2026-11-17 13:25:07 +00:00
builtin_error.go Follow Object Environment Record semantics for binding lookups and fix 2026-10-18 12:31:03 +01:00
builtin_function.go Handle nil FunctionCall.Arguments values and made sure FunctionCall.This is never nil. 2026-11-04 19:41:12 +00:00
builtin_function_test.go Fixed bound function length calculation for negative float values. Fixes #768 2026-10-04 19:29:05 +01:00
builtin_global.go Return -0 from parseInt when the sign is negative and the integer is 0 2026-10-20 11:24:48 +00:00
builtin_global_test.go Return -0 from parseInt when the sign is negative and the integer is 0 2026-10-20 11:24:48 +00:00
builtin_iterator.go Implement Iterator.zip and Iterator.zipKeyed 2026-10-12 22:27:44 -03:00
builtin_iterator_test.go Implement Iterator.zip and Iterator.zipKeyed 2026-10-12 22:27:44 -03:00
builtin_json.go Fix JSON.stringify indentation after an empty array or object 2026-10-17 04:30:34 +06:00
builtin_json_test.go Fix JSON.stringify indentation after an empty array or object 2026-10-17 04:30:34 +06:00
builtin_map.go Fixed re-definition of data property as an accessor and vice versa. 2026-11-07 15:34:02 +00:00
builtin_map_test.go Implement Map and WeakMap getOrInsert and getOrInsertComputed (#789) 2026-10-12 14:32:30 +01:00
builtin_math.go Implement Float16Array, Math.f16round and DataView float16 methods (#845) 2026-11-03 15:15:21 +00:00
builtin_math_test.go Return a Number from Math.sign when the argument converts to NaN or zero (#812) 2026-10-20 14:02:21 +01:00
builtin_number.go Implemented template-backed objects and used them for most of the built-ins. Closes #524, closes #459. 2023-09-06 17:07:31 +01:00
builtin_object.go Fixes for issues 1, 2, 5, 7, 8, 9, 10, 13 from #848. 2026-11-04 15:41:26 +00:00
builtin_promise.go Handle nil FunctionCall.Arguments values and made sure FunctionCall.This is never nil. 2026-11-04 19:41:12 +00:00
builtin_proxy.go Follow Object Environment Record semantics for binding lookups and fix 2026-10-18 12:31:03 +01:00
builtin_proxy_test.go Fixes for issues 1, 2, 5, 7, 8, 9, 10, 13 from #848. 2026-11-04 15:41:26 +00:00
builtin_reflect.go Implemented template-backed objects and used them for most of the built-ins. Closes #524, closes #459. 2023-09-06 17:07:31 +01:00
builtin_regexp.go Fully switched to regexp2. 2026-10-27 14:59:15 +00:00
builtin_set.go Fixed re-definition of data property as an accessor and vice versa. 2026-11-07 15:34:02 +00:00
builtin_set_test.go Avoid using createIterResultObject for internal iterations, such as for-of loops 2026-10-04 18:43:10 +01:00
builtin_string.go Handle nil FunctionCall.Arguments values and made sure FunctionCall.This is never nil. 2026-11-04 19:41:12 +00:00
builtin_string_test.go Fix replaceAll with an empty search string hanging on non-ASCII strings 2026-11-03 03:05:26 +07:00
builtin_symbol.go Allow non-registered symbols as WeakMap keys and WeakSet values 2026-10-12 16:27:34 -03:00
builtin_typedarrays.go Fixes for issues 1, 2, 5, 7, 8, 9, 10, 13 from #848. 2026-11-04 15:41:26 +00:00
builtin_typedarrays_test.go Refactored TypedArrays index, lastIndex and fill so that they do not do virtual calls in a loop, shows about 6x performance increase for 4096-byte arrays. Also fixed matching of -0 (see https://github.com/dop251/goja/pull/818) 2026-10-21 13:54:44 +01:00
builtin_weakmap.go Allow non-registered symbols as WeakMap keys and WeakSet values 2026-10-12 16:27:34 -03:00
builtin_weakmap_test.go Allow non-registered symbols as WeakMap keys and WeakSet values 2026-10-12 16:27:34 -03:00
builtin_weakset.go Allow non-registered symbols as WeakMap keys and WeakSet values 2026-10-12 16:27:34 -03:00
builtin_weakset_test.go Fixed the order in which the adder function and the iterator are obtained in {Weak}{Set,Map} constructors. 2022-10-25 17:54:01 +01:00
compiler.go Fixed 'arguments' binding creation when referenced from an arrow func or in strict eval. 2026-11-08 15:33:18 +00:00
compiler_expr.go Fix #860 issues 2-4 (#879) 2026-11-16 23:46:14 +00:00
compiler_stmt.go Fix for issue 11 from #848 2026-11-04 16:12:58 +00:00
compiler_test.go Fix #860 issues 2-4 (#879) 2026-11-16 23:46:14 +00:00
date.go Check TimeClip range before converting dates to milliseconds. Fixes #756 (#776) 2026-10-07 17:06:01 +01:00
date_parser.go Reimplement date parser (#611) 2024-09-26 22:44:04 +01:00
date_test.go Fixed setUTCMilliseconds and setMilliseconds computing from the wrong second before the epoch (#865) 2026-11-17 13:25:07 +00:00
destruct.go Follow Object Environment Record semantics for binding lookups and fix 2026-10-18 12:31:03 +01:00
export_cycle_test.go Fix stack overflow when exporting a Map or Set that contains itself 2026-10-20 09:01:12 -07:00
extract_failed_tests.sh Added toString tag to Reflect, allowed tests without id to run. Closes #416. 2022-08-14 12:37:52 +01:00
extract_passed_tests.sh Add initial support for regexp named groups 2025-04-13 21:03:05 +02:00
float16.go Implement Float16Array, Math.f16round and DataView float16 methods (#845) 2026-11-03 15:15:21 +00:00
float16_test.go Implement Float16Array, Math.f16round and DataView float16 methods (#845) 2026-11-03 15:15:21 +00:00
for_await_test.go Slight for-await optimisations 2026-09-30 20:57:58 +01:00
func.go Propagate exceptions from PromiseResolve() as a throw at await expression 2026-11-07 15:07:02 +00:00
func_test.go Fixes for issues 1, 2, 5, 7, 8, 9, 10, 13 from #848. 2026-11-04 15:41:26 +00:00
go.mod Fully switched to regexp2. 2026-10-27 14:59:15 +00:00
go.sum Fully switched to regexp2. 2026-10-27 14:59:15 +00:00
ipow.go Check for overflows in ipow() 2023-07-06 17:16:28 +01:00
LICENSE Initial commit 2016-11-04 22:06:38 +00:00
map.go Implement Map and WeakMap getOrInsert and getOrInsertComputed (#789) 2026-10-12 14:32:30 +01:00
map_test.go Implemented BigInt (#597) 2024-08-22 16:59:48 +01:00
normalize_surrogates_test.go Preserve lone UTF-16 surrogates during normalization (#825) 2026-10-26 13:26:50 +00:00
object.go Fixed re-definition of data property as an accessor and vice versa. 2026-11-07 15:34:02 +00:00
object_args.go Follow Object Environment Record semantics for binding lookups and fix 2026-10-18 12:31:03 +01:00
object_dynamic.go Follow Object Environment Record semantics for binding lookups and fix 2026-10-18 12:31:03 +01:00
object_dynamic_test.go Support defining 'length' on dynamic arrays via Object.defineProperty 2026-10-17 19:09:10 -05:00
object_goarray_reflect.go Follow Object Environment Record semantics for binding lookups and fix 2026-10-18 12:31:03 +01:00
object_goarray_reflect_test.go Refactored conversion to primitive. Always use String() method if defined. Closes #423. 2022-08-06 13:04:48 +01:00
object_gomap.go Follow Object Environment Record semantics for binding lookups and fix 2026-10-18 12:31:03 +01:00
object_gomap_reflect.go Refactored handling of pointers in Runtime.ToValue(). 2026-10-23 13:19:31 +01:00
object_gomap_reflect_test.go Refactored handling of pointers in Runtime.ToValue(). 2026-10-23 13:19:31 +01:00
object_gomap_test.go Refactored tests 2021-12-03 10:59:52 +00:00
object_goreflect.go Follow Object Environment Record semantics for binding lookups and fix 2026-10-18 12:31:03 +01:00
object_goreflect_test.go Refactored handling of pointers in Runtime.ToValue(). 2026-10-23 13:19:31 +01:00
object_goslice.go Follow Object Environment Record semantics for binding lookups and fix 2026-10-18 12:31:03 +01:00
object_goslice_reflect.go Update the length property when it's accessed, rather than on grow/shrink. Maintain pointer type of a wrapped *[]any. Fixes #521. 2023-06-21 11:08:01 +01:00
object_goslice_reflect_test.go Refactored handling of pointers in Runtime.ToValue(). 2026-10-23 13:19:31 +01:00
object_goslice_test.go Update the length property when it's accessed, rather than on grow/shrink. Maintain pointer type of a wrapped *[]any. Fixes #521. 2023-06-21 11:08:01 +01:00
object_template.go Follow Object Environment Record semantics for binding lookups and fix 2026-10-18 12:31:03 +01:00
object_test.go Added Object.GetIdx() to access indexed properties of arrays without converting the key to string 2026-10-23 14:32:38 +01:00
profiler.go Collect profiler samples after stop 2023-06-26 12:30:09 +01:00
profiler_test.go Collect profiler samples after stop 2023-06-26 12:30:09 +01:00
proxy.go Fixes for issues 1, 2, 5, 7, 8, 9, 10, 13 from #848. 2026-11-04 15:41:26 +00:00
README.md Fully switched to regexp2. 2026-10-27 14:59:15 +00:00
regexp.go Fully switched to regexp2. 2026-10-27 14:59:15 +00:00
regexp_test.go Fully switched to regexp2. 2026-10-27 14:59:15 +00:00
runtime.go Handle nil FunctionCall.Arguments values and made sure FunctionCall.This is never nil. 2026-11-04 19:41:12 +00:00
runtime_test.go Fixed re-definition of data property as an accessor and vice versa. 2026-11-07 15:34:02 +00:00
staticcheck.conf Added staticcheck (#364) 2022-01-08 12:50:12 +00:00
string.go Lazy string concatenation (#819) 2026-10-21 15:06:35 +01:00
string_ascii.go Fixed conversion to BigInt. Refactored BigInt hash to make it alloc-free. 2026-10-27 23:49:16 +00:00
string_concat.go Fully switched to regexp2. 2026-10-27 14:59:15 +00:00
string_concat_test.go Lazy string concatenation (#819) 2026-10-21 15:06:35 +01:00
string_imported.go Fully switched to regexp2. 2026-10-27 14:59:15 +00:00
string_test.go Fix unicode string builder capacity overflow in String.prototype.repeat (#831) 2026-11-02 13:59:44 +00:00
string_unicode.go Fix replaceAll with an empty search string hanging on non-ASCII strings 2026-11-03 03:05:26 +07:00
tc39_norace_test.go Added staticcheck (#364) 2022-01-08 12:50:12 +00:00
tc39_race_test.go Fixed formatting for go 1.17 2021-09-11 13:26:42 +01:00
tc39_test.go Implement Float16Array, Math.f16round and DataView float16 methods (#845) 2026-11-03 15:15:21 +00:00
typedarrays.go Avoid constructing slices with a past-the-end data pointer. 2026-11-05 00:25:51 +00:00
typedarrays_test.go Avoid constructing slices with a past-the-end data pointer. 2026-11-05 00:25:51 +00:00
value.go Implement Float16Array, Math.f16round and DataView float16 methods (#845) 2026-11-03 15:15:21 +00:00
vm.go Fix #860 issues 2-4 (#879) 2026-11-16 23:46:14 +00:00
vm_test.go Do not convert to primitive twice on unary minus operation. 2026-11-10 20:48:30 +00:00

goja

ECMAScript 5.1(+) implementation in Go.

Go Reference

Goja is an implementation of ECMAScript 5.1 in pure Go with emphasis on standard compliance and performance.

This project was largely inspired by otto.

The minimum required Go version is 1.26.

Features

  • Full ECMAScript 5.1 support (including regex and strict mode).
  • Passes nearly all tc39 tests for the features implemented so far. The goal is to pass all of them. See .tc39_test262_checkout.sh for the latest working commit id.
  • Capable of running Babel, Typescript compiler and pretty much anything written in ES5.
  • Sourcemaps.
  • Most of ES6 functionality, still work in progress, see https://github.com/dop251/goja/milestone/1?closed=1

Known incompatibilities and caveats

JSON

JSON.parse() uses the standard Go library which operates in UTF-8. Therefore, it cannot correctly parse broken UTF-16 surrogate pairs, for example:

JSON.parse(`"\\uD800"`).charCodeAt(0).toString(16) // returns "fffd" instead of "d800"

Date

Conversion from calendar date to epoch timestamp uses the standard Go library which uses int, rather than float as per ECMAScript specification. This means if you pass arguments that overflow int to the Date() constructor or if there is an integer overflow, the result will be incorrect, for example:

Date.UTC(1970, 0, 1, 80063993375, 29, 1, -288230376151711740) // returns 29256 instead of 29312

FAQ

How fast is it?

Although it's faster than many scripting language implementations in Go I have seen (for example it's 6-7 times faster than otto on average) it is not a replacement for V8 or SpiderMonkey or any other general-purpose JavaScript engine. You can find some benchmarks here.

Why would I want to use it over a V8 wrapper?

It greatly depends on your usage scenario. If most of the work is done in javascript (for example crypto or any other heavy calculations) you are definitely better off with V8.

If you need a scripting language that drives an engine written in Go so that you need to make frequent calls between Go and javascript passing complex data structures then the cgo overhead may outweigh the benefits of having a faster javascript engine.

Because it's written in pure Go there are no cgo dependencies, it's very easy to build and it should run on any platform supported by Go.

It gives you a much better control over execution environment so can be useful for research.

Is it goroutine-safe?

No. An instance of goja.Runtime can only be used by a single goroutine at a time. You can create as many instances of Runtime as you like but it's not possible to pass object values between runtimes.

Where is setTimeout()/setInterval()?

setTimeout() and setInterval() are common functions to provide concurrent execution in ECMAScript environments, but the two functions are not part of the ECMAScript standard. Browsers and NodeJS just happen to provide similar, but not identical, functions. The hosting application need to control the environment for concurrent execution, e.g. an event loop, and supply the functionality to script code.

There is a separate project aimed at providing some NodeJS functionality, and it includes an event loop.

Can you implement (feature X from ES6 or higher)?

I will be adding features in their dependency order and as quickly as time permits. Please do not ask for ETAs. Features that are open in the milestone are either in progress or will be worked on next.

The ongoing work is done in separate feature branches which are merged into master when appropriate. Every commit in these branches represents a relatively stable state (i.e. it compiles and passes all enabled tc39 tests), 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 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.

How do I contribute?

Before submitting a pull request please make sure that:

  • You followed ECMA standard as close as possible. If adding a new feature make sure you've read the specification, do not just base it on a couple of examples that work fine.
  • Your change does not have a significant negative impact on performance (unless it's a bugfix and it's unavoidable)
  • It passes all relevant tc39 tests.

Current Status

  • There should be no breaking changes in the API, however it may be extended.
  • Some of the AnnexB functionality is missing.

Basic Example

Run JavaScript and get the result value.

vm := goja.New()
v, err := vm.RunString("2 + 2")
if err != nil {
    panic(err)
}
if num := v.Export().(int64); num != 4 {
    panic(num)
}

Passing Values to JS

Any Go value can be passed to JS using Runtime.ToValue() method. See the method's documentation for more details.

Exporting Values from JS

A JS value can be exported into its default Go representation using Value.Export() method.

Alternatively it can be exported into a specific Go variable using Runtime.ExportTo() method.

Within a single export operation the same Object will be represented by the same Go value (either the same map, slice or a pointer to the same struct). This includes circular objects and makes it possible to export them.

Calling JS functions from Go

There are 2 approaches:

const SCRIPT = `
function sum(a, b) {
    return +a + b;
}
`

vm := goja.New()
_, err := vm.RunString(SCRIPT)
if err != nil {
    panic(err)
}
sum, ok := goja.AssertFunction(vm.Get("sum"))
if !ok {
    panic("Not a function")
}

res, err := sum(goja.Undefined(), vm.ToValue(40), vm.ToValue(2))
if err != nil {
    panic(err)
}
fmt.Println(res)
// Output: 42
const SCRIPT = `
function sum(a, b) {
    return +a + b;
}
`

vm := goja.New()
_, err := vm.RunString(SCRIPT)
if err != nil {
    panic(err)
}

var sum func(int, int) int
err = vm.ExportTo(vm.Get("sum"), &sum)
if err != nil {
    panic(err)
}

fmt.Println(sum(40, 2)) // note, _this_ value in the function will be undefined.
// Output: 42

The first one is more low level and allows specifying this value, whereas the second one makes the function look like a normal Go function.

Mapping struct field and method names

By default, the names are passed through as is which means they are capitalised. This does not match the standard JavaScript naming convention, so if you need to make your JS code look more natural or if you are dealing with a 3rd party library, you can use a FieldNameMapper:

vm := goja.New()
vm.SetFieldNameMapper(TagFieldNameMapper("json", true))
type S struct {
    Field int `json:"field"`
}
vm.Set("s", S{Field: 42})
res, _ := vm.RunString(`s.field`) // without the mapper it would have been s.Field
fmt.Println(res.Export())
// Output: 42

There are two standard mappers: TagFieldNameMapper and UncapFieldNameMapper, or you can use your own implementation.

Native Constructors

In order to implement a constructor function in Go use func (goja.ConstructorCall) *goja.Object. See Runtime.ToValue() documentation for more details.

Regular Expressions

Goja uses regexp2 library. There are a few known incompatibilities, but they are mostly edge cases and should not affect general usage. See tc39_test.go for the list of exclusions. Any new incompatibilities should be reported as bugs.

Exceptions

Any exception thrown in JavaScript is returned as an error of type *Exception. It is possible to extract the value thrown by using the Value() method:

vm := goja.New()
_, err := vm.RunString(`

throw("Test");

`)

if jserr, ok := err.(*Exception); ok {
    if jserr.Value().Export() != "Test" {
        panic("wrong value")
    }
} else {
    panic("wrong type")
}

If a native Go function panics with a Value, it is thrown as a Javascript exception (and therefore can be caught):

var vm *Runtime

func Test() {
    panic(vm.ToValue("Error"))
}

vm = goja.New()
vm.Set("Test", Test)
_, err := vm.RunString(`

try {
    Test();
} catch(e) {
    if (e !== "Error") {
        throw e;
    }
}

`)

if err != nil {
    panic(err)
}

Interrupting

func TestInterrupt(t *testing.T) {
    const SCRIPT = `
    var i = 0;
    for (;;) {
        i++;
    }
    `

    vm := goja.New()
    time.AfterFunc(200 * time.Millisecond, func() {
        vm.Interrupt("halt")
    })

    _, err := vm.RunString(SCRIPT)
    if err == nil {
        t.Fatal("Err is nil")
    }
    // err is of type *InterruptError and its Value() method returns whatever has been passed to vm.Interrupt()
}

NodeJS Compatibility

There is a separate project aimed at providing some of the NodeJS functionality.