webapi

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 31 Imported by: 0

Documentation

Overview

Package webapi installs Web APIs into a moejs runtime that runs on an event loop (package eventloop): fetch with streamed response bodies, the Streams, URL and URLSearchParams, Headers, Request and Response, AbortController and AbortSignal with EventTarget and Event, DOMException, and performance.now. A bare runtime has none of them: the host installs them explicitly, and fetch reaches only the network the host's http.Client and Allow hook permit.

rt := moejs.NewRuntime(moejs.Options{})
loop, err := eventloop.New(rt, eventloop.Options{})
api, err := webapi.Install(loop, webapi.Options{
	Client: http.DefaultClient,
	Allow:  webapi.AllowHosts("api.openai.com", "*.anthropic.com"),
})
defer api.Close()
err = loop.Run(func(rt *moejs.Runtime) error { ... })

The globals are created when JavaScript first reads them, so a runtime that never uses one pays only for its name. They are writable and configurable properties of the global object, as Web IDL defines them, also when the runtime shares the frozen builtins.

Event loop

Every promise of the package settles on the loop, in a task of its tasks phase, and the jobs that queues run before the next task. A fetch waiting for its response and a body read waiting for its chunk keep Run alive; a response body nobody reads does not. The objects belong to the runtime and are used on the loop only, like every JavaScript value; the Go side (the request, its body) runs on goroutines of its own and hands its results to the loop.

Streaming

A response body is a ReadableStream whose source reads the http.Response's Body on a goroutine, from the stream's first read on, at most one chunk ahead of what JavaScript took: the chunk read ahead waits until the stream takes it, and the next read runs while JavaScript works on it. Each chunk is a Uint8Array over the bytes the read returned, not copied again, charged to the runtime's memory limit (moejs.Options.MemoryLimit) in the task that hands it over. text(), json(), arrayBuffer() and bytes() hand the whole body over in one task, so a body larger than the limit stops the loop with the limit's error, and Go reads little more of it than the limit. reader.cancel(), the request's AbortSignal, Close and the end of the body close the Body at once, also while a read of it is blocked, and cancel the request's context; an abort errors the stream with the signal's reason, so pending reads reject with it (an AbortError by default). A network error before the response is a TypeError "fetch failed" whose cause names the Go error; one during the body errors the stream with a TypeError "terminated". See the package's documentation in docs/guide.md for the whole contract and the deviations from the specifications.

Index

Constants

This section is empty.

Variables

View Source
var ErrClosed = errors.New("webapi: closed")

ErrClosed is the cause of the error of a fetch that Close stopped or that started after Close.

View Source
var ErrNoNetwork = errors.New("webapi: fetch has no network (Options.Client is nil)")

ErrNoNetwork is the cause of a fetch's TypeError when Options.Client is nil.

Functions

func AllowHosts

func AllowHosts(hosts ...string) func(*http.Request) error

AllowHosts returns an Allow hook that approves the requests to the given hosts and rejects every other one. A host is matched case-insensitively against the request URL's hostname, and against the Host header's when the script set one: both must be allowed. "*.example.com" matches every subdomain of example.com, not example.com itself; "*" matches every host.

Types

type API

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

API is the Web APIs installed in one runtime.

func Install

func Install(loop *eventloop.Loop, opts Options) (*API, error)

Install installs the Web APIs as globals of the loop's runtime, as the package documentation describes. It is called once per runtime, while the loop does not run or on the loop.

func (*API) Close

func (a *API) Close()

Close stops every fetch in flight, whose promise or body read rejects with a TypeError, and closes every response body JavaScript has not read to its end, so that no request, goroutine or connection outlives the runtime's use. A fetch after Close rejects: Close is for a runtime that is dropped; a runtime that goes back to a pool ends its run's requests with the context of SetContext instead. Close also ends what the installation reports to the memory limit's measurements: the runtime drops it at its next measurement. Close may be called from any goroutine; the promises settle when the loop next runs. Terminating the loop does not stop the requests in flight: call Close as well.

func (*API) SetContext

func (a *API) SetContext(ctx context.Context)

SetContext makes ctx a parent of the requests of the fetches started from now on, with Options.Context, for a host that pools runtimes: canceling ctx when a run ends fails the fetches of that run still in flight, as a network error does (the error's cause is ctx's), and closes their response bodies at once, so that nothing of the run keeps the loop or a connection, while the runtime keeps fetching in its next run with the context set then. nil leaves Options.Context alone. It may be called from any goroutine.

type Options

type Options struct {
	// Client sends the requests of fetch. Nil means no network: every
	// fetch rejects with a TypeError. The package copies the Client to
	// follow the redirect mode of a request, and calls the Client's own
	// CheckRedirect, when set, after its own checks.
	Client *http.Client
	// Allow, when not nil, approves each request before it is sent,
	// including each redirect: an error rejects the fetch with a TypeError
	// whose cause has the error's message. It sees the request as it is
	// sent, its Host when the script set that header too. It is called on
	// the request's goroutine, so concurrently for concurrent fetches.
	// AllowHosts returns one for a list of hosts. A nil Allow approves
	// every request: fetch reaches every address the Client can, the
	// intranet, loopback and 169.254.169.254 (cloud metadata) included, so
	// a host that runs scripts it does not trust sets one.
	Allow func(*http.Request) error
	// Context is the parent of every request's context: canceling it
	// fails the fetches in flight as a network error does. Nil means
	// context.Background(). API.SetContext adds a parent for the
	// fetches of one run.
	Context context.Context
}

Options configures Install.

Directories

Path Synopsis
internal
whatwgurl
Package whatwgurl implements the URL Standard (https://url.spec.whatwg.org/): the basic URL parser with the state overrides of the URL API's setters, the host parser with domain to ASCII (UTS #46, Unicode 17.0.0), the URL serializer, origins, and application/x-www-form-urlencoded.
Package whatwgurl implements the URL Standard (https://url.spec.whatwg.org/): the basic URL parser with the state overrides of the URL API's setters, the host parser with domain to ASCII (UTS #46, Unicode 17.0.0), the URL serializer, origins, and application/x-www-form-urlencoded.

Jump to

Keyboard shortcuts

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