workers

package
v0.2.711 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 31 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package workers holds the non-Cobra pieces of cfctl's Workers commands: reading wrangler config files, turning them into upload metadata and bindings, building multipart script uploads, static-asset manifests, and the tail WebSocket client.

Index

Constants

View Source
const MaxAssetFiles = 100000

MaxAssetFiles is the per-version file count limit.

View Source
const MaxAssetSize = 25 << 20

MaxAssetSize is Cloudflare's per-file limit for Workers static assets.

View Source
const MaxWSMessage = 64 << 20

MaxWSMessage bounds a reassembled message.

View Source
const TailProtocol = "trace-v1"

TailProtocol is the tail WebSocket subprotocol.

Variables

View Source
var ConfigNames = []string{"wrangler.json", "wrangler.jsonc", "wrangler.toml"}

ConfigNames are the wrangler config files looked for, in wrangler's order.

View Source
var ErrWSClosed = errors.New("websocket closed")

ErrWSClosed is returned by ReadMessage after a close frame.

Functions

func BuildUpload

func BuildUpload(metadata map[string]any, mods []Module) ([]byte, string, error)

BuildUpload encodes metadata plus modules as the multipart/form-data body the script and version upload endpoints take.

func Bundle

func Bundle(ctx context.Context, entry, outDir string, minify, nodeCompat, sourcemap bool) (string, error)

Bundle runs esbuild (which must be on PATH) to bundle entry into a single ES module in outDir, and returns the output path.

func ContentTypeFor

func ContentTypeFor(name string, esm bool) string

ContentTypeFor returns the upload content type for a module file name.

func FindConfig

func FindConfig(dir string) string

FindConfig returns the first wrangler config file in dir, or "".

func FormatTailPretty

func FormatTailPretty(raw []byte, loc *time.Location) string

FormatTailPretty renders a tail message like `wrangler tail --format pretty`.

func HashAsset

func HashAsset(data []byte, ext string) string

HashAsset is the content key for a file: the first 32 hex chars of SHA-256 over the base64 contents plus the extension (wrangler uses BLAKE3 over the same input; the API treats the hash as an opaque key).

func IsModuleSyntax

func IsModuleSyntax(src []byte) bool

IsModuleSyntax reports whether a script looks like an ES module (has an import or export statement) rather than a service-worker script.

func RelativeImports

func RelativeImports(src []byte) []string

RelativeImports returns the relative module specifiers a JS module imports.

func StripJSONC

func StripJSONC(in []byte) []byte

StripJSONC removes // and /* */ comments and trailing commas from JSONC, leaving string contents untouched.

Types

type AssetEntry

type AssetEntry struct {
	Hash string `json:"hash"`
	Size int64  `json:"size"`
	// contains filtered or unexported fields
}

AssetEntry is one manifest entry ({hash, size}) plus where it came from.

type Assets

type Assets struct {
	Dir string
	// Manifest maps "/path/in/site.html" to its entry.
	Manifest map[string]AssetEntry
	// Headers and Redirects hold _headers / _redirects contents, which are
	// sent in the assets config instead of being uploaded.
	Headers, Redirects string
	// contains filtered or unexported fields
}

Assets is a scanned static-assets directory.

func ScanAssets

func ScanAssets(dir string) (*Assets, error)

ScanAssets walks dir and builds the upload manifest. It skips _headers, _redirects, .assetsignore, and anything .assetsignore matches, plus node_modules, .git and .DS_Store.

func (*Assets) Count

func (a *Assets) Count() int

Count returns the number of files in the manifest.

func (*Assets) FileFor

func (a *Assets) FileFor(hash string) (string, string, bool)

FileFor returns the local path and content type for a hash the API asked for.

func (*Assets) Paths

func (a *Assets) Paths() []string

Paths returns the manifest paths, sorted.

func (*Assets) Payload

func (a *Assets) Payload() map[string]AssetEntry

Payload returns the manifest in the API's {path: {hash, size}} shape.

type AssetsConfig

type AssetsConfig struct {
	Directory        string `json:"directory"`
	Binding          string `json:"binding"`
	HTMLHandling     string `json:"html_handling"`
	NotFoundHandling string `json:"not_found_handling"`
	RunWorkerFirst   any    `json:"run_worker_first"`
}

AssetsConfig is wrangler's [assets] table.

type Binding

type Binding = map[string]any

Binding is one entry of the upload metadata's "bindings" array.

func MergeBindings

func MergeBindings(base, extra []Binding) []Binding

MergeBindings appends extra to base, replacing any base binding with the same name.

func ParseBindingFlag

func ParseBindingFlag(kind, val string) (Binding, error)

ParseBindingFlag parses the shorthand binding flags:

--var NAME=value          plain_text
--kv NAME=namespace_id    kv_namespace
--r2 NAME=bucket          r2_bucket
--d1 NAME=database_id     d1
--service NAME=worker[#entrypoint]
--queue NAME=queue_name
--ai NAME
--binding '{"type":...}'  any binding as JSON

func VarBinding

func VarBinding(name string, v any) Binding

VarBinding turns a [vars] entry into a plain_text (strings) or json binding.

type Config

type Config struct {
	Path string `json:"-"`
	Dir  string `json:"-"`
	Env  string `json:"-"`

	Name               string                   `json:"name"`
	Main               string                   `json:"main"`
	CompatibilityDate  string                   `json:"compatibility_date"`
	CompatibilityFlags []string                 `json:"compatibility_flags"`
	WorkersDev         *bool                    `json:"workers_dev"`
	PreviewURLs        *bool                    `json:"preview_urls"`
	Routes             []Route                  `json:"-"`
	Triggers           struct{ Crons []string } `json:"triggers"`
	Vars               map[string]any           `json:"vars"`
	UsageModel         string                   `json:"usage_model"`
	Logpush            *bool                    `json:"logpush"`
	Limits             map[string]any           `json:"limits"`
	Placement          map[string]any           `json:"placement"`
	Observability      map[string]any           `json:"observability"`
	TailConsumers      []map[string]any         `json:"tail_consumers"`
	Assets             *AssetsConfig            `json:"assets"`
	Migrations         []Migration              `json:"migrations"`
	KeepVars           bool                     `json:"keep_vars"`

	Raw map[string]any `json:"-"`
}

Config is the subset of a wrangler config file cfctl understands. Raw keeps the merged (top-level + env) table for anything not modelled here.

func LoadConfig

func LoadConfig(path, env string) (*Config, error)

LoadConfig reads a wrangler.toml / wrangler.json / wrangler.jsonc file and applies [env.<env>] when env is set.

func (*Config) AssetsDir

func (c *Config) AssetsDir() string

AssetsDir returns the assets directory resolved against the config's directory.

func (*Config) Bindings

func (c *Config) Bindings() ([]Binding, error)

Bindings returns the upload bindings described by the config (vars, KV, R2, D1, services, Durable Objects, queues, ...). Unknown binding tables are ignored; pass them with --binding instead.

func (*Config) MainPath

func (c *Config) MainPath() string

MainPath returns the entry point resolved against the config's directory.

type Migration

type Migration struct {
	Tag              string           `json:"tag"`
	NewClasses       []string         `json:"new_classes,omitempty"`
	NewSqliteClasses []string         `json:"new_sqlite_classes,omitempty"`
	RenamedClasses   []map[string]any `json:"renamed_classes,omitempty"`
	DeletedClasses   []string         `json:"deleted_classes,omitempty"`
	TransferredClass []map[string]any `json:"transferred_classes,omitempty"`
}

Migration is one Durable Object migration step.

type Module

type Module struct {
	Name        string // part name / module specifier, e.g. "index.js"
	ContentType string
	Data        []byte
}

Module is one file uploaded with a Worker.

func LoadModules

func LoadModules(main string, extra []string, esm *bool, sourceMaps bool) (mods []Module, isESM bool, err error)

LoadModules reads the main script plus extra module files. Extra module names are their paths relative to the main script's directory.

type Route

type Route struct {
	Pattern      string `json:"pattern"`
	ZoneName     string `json:"zone_name,omitempty"`
	ZoneID       string `json:"zone_id,omitempty"`
	CustomDomain bool   `json:"custom_domain,omitempty"`
}

Route is one entry of wrangler's routes: a bare pattern, or a table with zone_name/zone_id or custom_domain.

type TailEvent

type TailEvent struct {
	Outcome        string `json:"outcome"`
	ScriptName     string `json:"scriptName"`
	EventTimestamp int64  `json:"eventTimestamp"`
	Exceptions     []struct {
		Name      string `json:"name"`
		Message   string `json:"message"`
		Timestamp int64  `json:"timestamp"`
	} `json:"exceptions"`
	Logs []struct {
		Message   []any  `json:"message"`
		Level     string `json:"level"`
		Timestamp int64  `json:"timestamp"`
	} `json:"logs"`
	Event map[string]any `json:"event"`
}

TailEvent is one trace-v1 message (only the fields cfctl prints).

type TailFilterOptions

type TailFilterOptions struct {
	Status   []string // ok, error, canceled
	Methods  []string
	Headers  []string // "name" or "name:value"
	ClientIP []string
	Search   string
	Sampling float64 // 0 < rate <= 1; 0 = unset
}

TailFilterOptions are the tail filters wrangler exposes.

func (TailFilterOptions) Filters

func (o TailFilterOptions) Filters() ([]map[string]any, error)

Filters builds the filter list sent to the tail API.

type WSConn

type WSConn struct {

	// Protocol is the subprotocol the server picked.
	Protocol string
	// contains filtered or unexported fields
}

WSConn is a client WebSocket connection.

func DialWS

func DialWS(ctx context.Context, rawURL, protocol string, header http.Header, handshakeTimeout time.Duration) (*WSConn, error)

DialWS opens a WebSocket to rawURL (ws://, wss://, http:// or https://).

func (*WSConn) Close

func (c *WSConn) Close() error

Close sends a close frame and closes the connection.

func (*WSConn) Ping

func (c *WSConn) Ping() error

Ping sends a ping frame.

func (*WSConn) ReadMessage

func (c *WSConn) ReadMessage() ([]byte, error)

ReadMessage returns the next text or binary message, answering pings and close frames along the way.

func (*WSConn) WriteText

func (c *WSConn) WriteText(b []byte) error

WriteText sends a text message.

Jump to

Keyboard shortcuts

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