js

package
v0.2.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 1, 2023 License: Apache-2.0 Imports: 21 Imported by: 0

README

Common-JS for Goja

Use Goja in a CommonJS-style modular environment. Supports "require", "exports", and more, following the Node.js implementation as much as possible.

Features:

  • Customize the environment with your own special extensions.
  • By default "require" supports full URLs and can resolve paths relative to the current module's location. But this can be customized to support your own special resolution and loading method (e.g. loading modules from a database).
  • Optional support for watching changes to all resolved JavaScript files (if they are in the local filesystem), allowing your application to restart or otherwise respond accordingly to live code updates.
  • Optional support for "bind", which is similar to "require" but exports the JavaScript objects, including functions, into a new "goja.Runtime". This is useful for multi-threaded Go environments because a single "goja.Runtime" cannot be used simulatenously by more than one thread. Two variations exist: early binding, which creates the "Runtime" when "bind" is called (low concurrency, high performance), and late binding, which creates the "Runtime" every time the bound object is unbound (high concurrency, lower performance).

Example

start.go:

package main

import (
    "log"
    "os"

    "github.com/dop251/goja"
    "github.com/tliron/kutil/js"
    "github.com/tliron/exturl"
)

func main() {
    urlContext := exturl.NewContext()
    defer urlContext.Release()

    environment := js.NewEnvironment(urlContext, nil)
    defer environment.Release()

    // Implementation of "console.log"
    environment.Extensions = append(environment.Extensions, js.Extension{
        Name: "console",
        Create: func(context *js.Context) goja.Value {
            return context.Environment.Runtime.ToValue(ConsoleAPI{})
        },
    })

    // Support for "bind" (late binding)
    environment.Extensions = append(environment.Extensions, js.Extension{
        Name:   "bind",
        Create: js.CreateLateBindExtension,
    })

    // Start!
    environment.RequireID("./start")
}

var logger = log.New(os.Stdout, "console: ", log.LstdFlags)

type ConsoleAPI struct{}

func (self ConsoleAPI) Log(message string) {
    logger.Println(message)
}

start.js:

const hello = require('./lib/hello');

hello.sayit();

lib/hello.js:

exports.sayit = function() {
    console.log('hi!');
};

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DromedaryCaseMapper dromedaryCaseMapper

Functions

func Call added in v0.1.39

func Call(runtime *goja.Runtime, function JavaScriptFunc, arguments ...any) any

func CreateEarlyBindExtension added in v0.1.39

func CreateEarlyBindExtension(context *Context) goja.Value

CreateExtensionFunc signature

func CreateLateBindExtension added in v0.1.39

func CreateLateBindExtension(context *Context) goja.Value

CreateExtensionFunc signature

Types

type Bind added in v0.1.39

type Bind interface {
	Unbind() (any, *Context, error)
}

type Context added in v0.1.33

type Context struct {
	Environment *Environment
	Parent      *Context
	Module      *Module
	Resolve     ResolveFunc
	Extensions  []goja.Value
}

type CreateExtensionFunc added in v0.1.32

type CreateExtensionFunc func(context *Context) goja.Value

type CreateResolverFunc added in v0.1.32

type CreateResolverFunc func(url exturl.URL, context *Context) ResolveFunc

func NewDefaultResolverCreator added in v0.1.39

func NewDefaultResolverCreator(urlContext *exturl.Context, path []exturl.URL, defaultExtension string) CreateResolverFunc

type EarlyBind added in v0.1.39

type EarlyBind struct {
	Value   any
	Context *Context
}

func (EarlyBind) Unbind added in v0.1.39

func (self EarlyBind) Unbind() (any, *Context, error)

Bind interface

type Environment added in v0.1.32

type Environment struct {
	Runtime        *goja.Runtime
	URLContext     *exturl.Context
	Path           []exturl.URL
	Extensions     []Extension
	Modules        *goja.Object
	Precompile     PrecompileFunc
	CreateResolver CreateResolverFunc
	OnChanged      OnChangedFunc
	Log            commonlog.Logger
	Lock           sync.Mutex
	// contains filtered or unexported fields
}

func NewEnvironment added in v0.1.32

func NewEnvironment(urlContext *exturl.Context, path []exturl.URL) *Environment

func (*Environment) AddModule added in v0.1.33

func (self *Environment) AddModule(url exturl.URL, module *Module)

func (*Environment) Call added in v0.1.39

func (self *Environment) Call(function JavaScriptFunc, arguments ...any) any

func (*Environment) ClearCache added in v0.1.37

func (self *Environment) ClearCache()

func (*Environment) NewChild added in v0.1.39

func (self *Environment) NewChild() *Environment

func (*Environment) NewContext added in v0.1.33

func (self *Environment) NewContext(url exturl.URL, parent *Context) *Context

func (*Environment) NewModule added in v0.1.33

func (self *Environment) NewModule() *Module

func (*Environment) Release added in v0.1.33

func (self *Environment) Release() error

func (*Environment) RequireID added in v0.1.33

func (self *Environment) RequireID(id string) (*goja.Object, error)

func (*Environment) RequireURL added in v0.1.32

func (self *Environment) RequireURL(url exturl.URL) (*goja.Object, error)

func (*Environment) RestartWatcher added in v0.1.41

func (self *Environment) RestartWatcher() error

func (*Environment) StopWatcher added in v0.1.41

func (self *Environment) StopWatcher() error

func (*Environment) Watch added in v0.1.33

func (self *Environment) Watch(path string) error

type Extension added in v0.1.32

type Extension struct {
	Name   string
	Create CreateExtensionFunc
}

type FileAPI added in v0.1.31

type FileAPI struct {
	// contains filtered or unexported fields
}

func NewFileAPI added in v0.1.32

func NewFileAPI(context *exturl.Context) FileAPI

func (FileAPI) Download added in v0.1.32

func (self FileAPI) Download(sourceUrl string, targetPath string) error

func (FileAPI) Exec added in v0.1.31

func (self FileAPI) Exec(name string, arguments ...string) (string, error)

func (FileAPI) JoinFilePath added in v0.1.32

func (self FileAPI) JoinFilePath(elements ...string) string

func (FileAPI) TemporaryDirectory added in v0.1.31

func (self FileAPI) TemporaryDirectory(pattern string, directory string) (string, error)

func (FileAPI) TemporaryFile added in v0.1.31

func (self FileAPI) TemporaryFile(pattern string, directory string) (string, error)

type JavaScriptFunc added in v0.1.39

type JavaScriptFunc = func(goja.FunctionCall) goja.Value

type LateBind added in v0.1.39

type LateBind struct {
	URL        exturl.URL
	ExportName string
	Context    *Context
}

func (LateBind) Unbind added in v0.1.39

func (self LateBind) Unbind() (any, *Context, error)

Bind interface

type Module added in v0.1.33

type Module struct {
	Id           string
	Children     []*Module
	Filename     string
	Path         string
	Paths        []string
	Exports      *goja.Object
	Require      *goja.Object
	IsPreloading bool
	Loaded       bool
}

type OnChangedFunc added in v0.1.33

type OnChangedFunc func(id string, module *Module)

type PrecompileFunc added in v0.1.32

type PrecompileFunc func(url exturl.URL, script string, context *Context) (string, error)

type ResolveFunc added in v0.1.32

type ResolveFunc func(id string, raw bool) (exturl.URL, error)

type ThreadSafeObject added in v0.1.32

type ThreadSafeObject struct {
	// contains filtered or unexported fields
}

func NewThreadSafeObject added in v0.1.32

func NewThreadSafeObject() *ThreadSafeObject

func (*ThreadSafeObject) Delete added in v0.1.32

func (self *ThreadSafeObject) Delete(key string) bool

goja.DynamicObject interface

func (*ThreadSafeObject) Get added in v0.1.32

func (self *ThreadSafeObject) Get(key string) goja.Value

goja.DynamicObject interface

func (*ThreadSafeObject) Has added in v0.1.32

func (self *ThreadSafeObject) Has(key string) bool

goja.DynamicObject interface

func (*ThreadSafeObject) Keys added in v0.1.32

func (self *ThreadSafeObject) Keys() []string

goja.DynamicObject interface

func (*ThreadSafeObject) NewDynamicObject added in v0.1.32

func (self *ThreadSafeObject) NewDynamicObject(runtime *goja.Runtime) *goja.Object

func (*ThreadSafeObject) Set added in v0.1.32

func (self *ThreadSafeObject) Set(key string, value goja.Value) bool

goja.DynamicObject interface

type TranscribeAPI added in v0.1.60

type TranscribeAPI struct{}

func (TranscribeAPI) Atob added in v0.1.60

func (self TranscribeAPI) Atob(b64 string) ([]byte, error)

Decode base64 to bytes

func (TranscribeAPI) Btoa added in v0.1.60

func (self TranscribeAPI) Btoa(bytes []byte) string

Encode bytes as base64

func (TranscribeAPI) BytesToString added in v0.1.60

func (self TranscribeAPI) BytesToString(bytes []byte) string

Another way to achieve this in JavaScript: String.fromCharCode.apply(null, bytes)

func (TranscribeAPI) Decode added in v0.1.60

func (self TranscribeAPI) Decode(code string, format string, all bool) (ard.Value, error)

func (TranscribeAPI) Encode added in v0.1.60

func (self TranscribeAPI) Encode(value any, format string, indent string, writer io.Writer) (string, error)

func (TranscribeAPI) NewXMLDocument added in v0.1.60

func (self TranscribeAPI) NewXMLDocument() *etree.Document

func (TranscribeAPI) StringToBytes added in v0.1.60

func (self TranscribeAPI) StringToBytes(string_ string) []byte

func (TranscribeAPI) ValidateFormat added in v0.1.60

func (self TranscribeAPI) ValidateFormat(code string, format string) error

type UtilAPI added in v0.1.31

type UtilAPI struct{}

func (UtilAPI) DeepCopy added in v0.1.31

func (self UtilAPI) DeepCopy(value ard.Value) ard.Value

func (UtilAPI) DeepEquals added in v0.1.31

func (self UtilAPI) DeepEquals(a ard.Value, b ard.Value) bool

func (UtilAPI) Go added in v0.1.32

func (self UtilAPI) Go(value goja.Value) error

Goroutine

func (UtilAPI) Hash added in v0.1.31

func (self UtilAPI) Hash(value ard.Value) (string, error)

func (UtilAPI) IsType added in v0.1.31

func (self UtilAPI) IsType(value ard.Value, type_ string) (bool, error)

func (UtilAPI) Mutex added in v0.1.31

func (self UtilAPI) Mutex() util.RWLocker

func (UtilAPI) Now added in v0.1.31

func (self UtilAPI) Now() time.Time

func (UtilAPI) Once added in v0.1.42

func (self UtilAPI) Once(name string, value goja.Value) error

func (UtilAPI) Printf added in v0.1.64

func (self UtilAPI) Printf(format string, args ...any)

func (UtilAPI) Sprintf added in v0.1.31

func (self UtilAPI) Sprintf(format string, args ...any) string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL