frontend

package
v0.0.0-...-e0cb5ea Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package frontend turns TypeScript and modern JavaScript source into the JavaScript dialect the engine executes.

For the run path bento uses esbuild's single-file transform, which is pure Go and fast. It strips TypeScript types, lowers recent syntax to a stable target, and leaves module semantics intact. The heavier typescript-go frontend is used for type checking and for the ahead-of-time compile path, not here.

Index

Constants

View Source
const (
	TypeAny           = adapter.TypeAny
	TypeUnknown       = adapter.TypeUnknown
	TypeNever         = adapter.TypeNever
	TypeVoid          = adapter.TypeVoid
	TypeUndefined     = adapter.TypeUndefined
	TypeNull          = adapter.TypeNull
	TypeBoolean       = adapter.TypeBoolean
	TypeNumber        = adapter.TypeNumber
	TypeBigInt        = adapter.TypeBigInt
	TypeString        = adapter.TypeString
	TypeSymbol        = adapter.TypeSymbol
	TypeLiteral       = adapter.TypeLiteral
	TypeObject        = adapter.TypeObject
	TypeUnion         = adapter.TypeUnion
	TypeIntersection  = adapter.TypeIntersection
	TypeTypeParameter = adapter.TypeTypeParameter
	TypeEnum          = adapter.TypeEnum
)

TypeFlags values.

View Source
const (
	NodeUnknown = adapter.NodeUnknown

	NodeSourceFile           = adapter.NodeSourceFile
	NodeFunctionDeclaration  = adapter.NodeFunctionDeclaration
	NodeFunctionExpression   = adapter.NodeFunctionExpression
	NodeArrowFunction        = adapter.NodeArrowFunction
	NodeMethodDeclaration    = adapter.NodeMethodDeclaration
	NodeGetAccessor          = adapter.NodeGetAccessor
	NodeSetAccessor          = adapter.NodeSetAccessor
	NodeConstructor          = adapter.NodeConstructor
	NodeClassDeclaration     = adapter.NodeClassDeclaration
	NodeInterfaceDeclaration = adapter.NodeInterfaceDeclaration
	NodeTypeAliasDeclaration = adapter.NodeTypeAliasDeclaration
	NodeEnumDeclaration      = adapter.NodeEnumDeclaration
	NodeVariableStatement    = adapter.NodeVariableStatement
	NodeVariableDeclaration  = adapter.NodeVariableDeclaration
	NodeParameter            = adapter.NodeParameter
	NodePropertyDeclaration  = adapter.NodePropertyDeclaration

	NodeBlock               = adapter.NodeBlock
	NodeReturnStatement     = adapter.NodeReturnStatement
	NodeIfStatement         = adapter.NodeIfStatement
	NodeForStatement        = adapter.NodeForStatement
	NodeForOfStatement      = adapter.NodeForOfStatement
	NodeForInStatement      = adapter.NodeForInStatement
	NodeWhileStatement      = adapter.NodeWhileStatement
	NodeSwitchStatement     = adapter.NodeSwitchStatement
	NodeTryStatement        = adapter.NodeTryStatement
	NodeThrowStatement      = adapter.NodeThrowStatement
	NodeExpressionStatement = adapter.NodeExpressionStatement

	NodeIdentifier               = adapter.NodeIdentifier
	NodeCallExpression           = adapter.NodeCallExpression
	NodeNewExpression            = adapter.NodeNewExpression
	NodePropertyAccessExpression = adapter.NodePropertyAccessExpression
	NodeElementAccessExpression  = adapter.NodeElementAccessExpression
	NodeBinaryExpression         = adapter.NodeBinaryExpression
	NodePrefixUnaryExpression    = adapter.NodePrefixUnaryExpression
	NodePostfixUnaryExpression   = adapter.NodePostfixUnaryExpression
	NodeConditionalExpression    = adapter.NodeConditionalExpression
	NodeTemplateExpression       = adapter.NodeTemplateExpression
	NodeObjectLiteralExpression  = adapter.NodeObjectLiteralExpression
	NodeArrayLiteralExpression   = adapter.NodeArrayLiteralExpression
	NodeAwaitExpression          = adapter.NodeAwaitExpression
	NodeYieldExpression          = adapter.NodeYieldExpression
	NodeSpreadElement            = adapter.NodeSpreadElement
	NodeParenthesizedExpression  = adapter.NodeParenthesizedExpression
	NodeAsExpression             = adapter.NodeAsExpression
	NodeTypeAssertion            = adapter.NodeTypeAssertion

	// Literals and keyword-valued expressions.
	NodeNumericLiteral                = adapter.NodeNumericLiteral
	NodeStringLiteral                 = adapter.NodeStringLiteral
	NodeBigIntLiteral                 = adapter.NodeBigIntLiteral
	NodeNoSubstitutionTemplateLiteral = adapter.NodeNoSubstitutionTemplateLiteral
	NodeTrueKeyword                   = adapter.NodeTrueKeyword
	NodeFalseKeyword                  = adapter.NodeFalseKeyword
	NodeNullKeyword                   = adapter.NodeNullKeyword

	// Class-body keywords.
	NodeThisKeyword  = adapter.NodeThisKeyword
	NodeSuperKeyword = adapter.NodeSuperKeyword

	NodeWithStatement = adapter.NodeWithStatement
)

NodeKind values. The full set lives in the adapter package; these are the kinds the partitioner and lowering branch on today, aliased so a consumer names frontend.NodeFunctionDeclaration.

View Source
const (
	SymbolVariable  = adapter.SymbolVariable
	SymbolFunction  = adapter.SymbolFunction
	SymbolClass     = adapter.SymbolClass
	SymbolInterface = adapter.SymbolInterface
	SymbolTypeAlias = adapter.SymbolTypeAlias
	SymbolEnum      = adapter.SymbolEnum
	SymbolNamespace = adapter.SymbolNamespace
	SymbolMethod    = adapter.SymbolMethod
	SymbolProperty  = adapter.SymbolProperty
	SymbolAlias     = adapter.SymbolAlias
)

SymbolFlags values.

View Source
const (
	FileTS   = adapter.FileTS
	FileTSX  = adapter.FileTSX
	FileJS   = adapter.FileJS
	FileJSX  = adapter.FileJSX
	FileDTS  = adapter.FileDTS
	FileJSON = adapter.FileJSON
)

FileKind values.

View Source
const (
	ImportRelative = adapter.ImportRelative
	ImportBare     = adapter.ImportBare
	ImportNode     = adapter.ImportNode
	ImportGo       = adapter.ImportGo
	ImportJSON     = adapter.ImportJSON
	ImportAsset    = adapter.ImportAsset
)

ImportKind values.

View Source
const (
	CategoryError      = adapter.CategoryError
	CategoryWarning    = adapter.CategoryWarning
	CategorySuggestion = adapter.CategorySuggestion
	CategoryMessage    = adapter.CategoryMessage
)

DiagnosticCategory values.

View Source
const (
	LiteralNone    = adapter.LiteralNone
	LiteralString  = adapter.LiteralString
	LiteralNumber  = adapter.LiteralNumber
	LiteralBoolean = adapter.LiteralBoolean
	LiteralBigInt  = adapter.LiteralBigInt
)

LiteralKind values.

Variables

View Source
var ErrNoRoots = errors.New(
	"frontend: Load requires at least one root file (tsconfig include discovery is a later slice)")

ErrNoRoots reports that Load was called with no entry files. tsconfig include discovery, which fills the root set from the project when none is given, is a later slice; until then a caller names its roots explicitly.

View Source
var ErrRealAdapterUnavailable = errors.New(
	"frontend: real typescript-go adapter unavailable (no fork revision pinned); " +
		"use frontend.Wrap with a supplied adapter")

ErrRealAdapterUnavailable reports that no real typescript-go-backed checker can be constructed in this build. It is a defensive guard only: bento consumes typescript-go through the tamnd/typescript fork, whose public shim exposes the checker, so the real adapter is always available and RealAdapterAvailable returns true (see pkg/frontend/adapter/version.go). The error remains so a build that somehow dropped the pin fails loudly rather than nil-crashing.

View Source
var ErrTopLevelAwait = errors.New("top-level await requires the ES module format")

ErrTopLevelAwait reports that a source uses top-level await, which cannot be represented in the CommonJS output format. The runtime catches this and runs the module through the native ES module path instead, where top-level await is legal. It is returned by Transpile, wrapped, so callers test with errors.Is.

Functions

This section is empty.

Types

type ConfigOverrides

type ConfigOverrides struct {
	Strict       *bool
	SkipLibCheck *bool
	AllowJS      *bool
	CheckJS      *bool
	Paths        map[string][]string
}

ConfigOverrides are compiler-option overrides applied on top of the resolved tsconfig. Zero-valued fields leave the tsconfig value in place.

type Diagnostic

type Diagnostic struct {
	Code     int
	Category DiagnosticCategory
	Message  string
	File     *SourceFile
	Span     Span
	Related  []Diagnostic
}

Diagnostic is a checker or parser diagnostic, passed through from typescript-go without rewording so bento errors match tsc byte for byte.

type DiagnosticCategory

type DiagnosticCategory = adapter.DiagnosticCategory

Classification enum aliases. The underlying values live in the adapter package.

type FileKind

type FileKind = adapter.FileKind

Classification enum aliases. The underlying values live in the adapter package.

type FileSystem

type FileSystem interface {
	ReadFile(path string) (string, bool)
	FileExists(path string) bool
	DirectoryExists(path string) bool
}

FileSystem replaces the real file system for a load. A nil FileSystem reads through the OS. Tests and the bundler feed virtual modules through it.

type ForClauses

type ForClauses struct {
	Init, Cond, Incr, Body    Node
	HasInit, HasCond, HasIncr bool
}

ForClauses is a for statement's four parts read by role. Body is always present. Init, Cond, and Incr each carry a node only when the source wrote that clause, reported by the matching HasInit, HasCond, HasIncr flag, so a caller lowers for(;;), for(let i=0;;i++), and every other shape without guessing which clauses a bare child list dropped.

type ImportKind

type ImportKind = adapter.ImportKind

Classification enum aliases. The underlying values live in the adapter package.

type LiteralKind

type LiteralKind = adapter.LiteralKind

Classification enum aliases. The underlying values live in the adapter package.

type LiteralValue

type LiteralValue = adapter.LiteralValue

Classification enum aliases. The underlying values live in the adapter package.

type LoadOptions

type LoadOptions struct {
	// Dir is the project root; tsconfig discovery starts here.
	Dir string
	// ConfigPath, if set, names a tsconfig explicitly and skips discovery.
	ConfigPath string
	// Roots are entry files; if empty they come from the tsconfig include set.
	Roots []string
	// Overrides are compiler-option overrides applied on top of the tsconfig.
	Overrides ConfigOverrides
	// FS, if non-nil, replaces the real file system.
	FS FileSystem
}

LoadOptions controls how a typed program is loaded. It mirrors the parts of a tsconfig bento honors, plus bento-specific knobs. It is named LoadOptions rather than Options because the transpile path already owns frontend.Options.

type Node

type Node interface {
	Kind() NodeKind
	Pos() Pos
	End() Pos
	File() SourceFile
}

Node is an opaque handle to an AST node. Consumers ask the Program about it rather than reading its fields, so the concrete typescript-go node shape stays behind the adapter.

type NodeKind

type NodeKind = adapter.NodeKind

Classification enum aliases. The underlying values live in the adapter package.

type Options

type Options struct {
	// Filename is the original path, used for diagnostics and loader detection.
	Filename string
	// SourceMap requests an inline source map appended to Code.
	SourceMap bool
}

Options controls a transpile.

type Param

type Param struct {
	Name     string
	Type     Type
	Optional bool
}

Param is one parameter of a signature.

type Pos

type Pos int

Pos is a byte offset into a file's text.

type Position

type Position struct {
	Line   int
	Column int
}

Position is a resolved line and column: 1-based line, 0-based column, the convention tsc uses so bento diagnostics line up with it.

type Program

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

Program is bento's typed-program handle. It wraps an adapter.TSAdapter and an opaque program handle, and turns the adapter's handle-returning calls into the value-returning queries the partitioner and lowering consume. The interners map opaque type and symbol handles to small integer ids, so a bento Type or Symbol carries an id, never a typescript-go object, and the program looks the handle back up when a follow-up structural query comes in.

func Load

func Load(opts LoadOptions) (*Program, error)

Load discovers or reads the tsconfig, constructs the compiler host, builds the typescript-go program, runs the binder, and wraps the result in a bento Program. It does not force a full type check; the checker runs lazily on first query.

It returns ErrRealAdapterUnavailable while the real adapter is blocked upstream. The wiring above it (tsconfig resolution, host construction, root discovery) is stable and lands in follow-up slices; the one missing piece is the adapter.TSAdapter implementation, which is why the failure is a single clear error rather than a panic.

func Wrap

Wrap builds a Program over a given adapter and program handle. Load uses it with the real adapter, the only implementation; taking an interface keeps the typescript-go coupling behind the adapter package rather than leaking it here. It is the single constructor for a Program so the interners are always initialized.

func (*Program) Aliased

func (p *Program) Aliased(s Symbol) Symbol

Aliased follows an import or export alias to the symbol it ultimately names.

func (*Program) Children

func (p *Program) Children(n Node) []Node

Children returns the direct child nodes of a node, so a consumer can walk a body without ever touching a typescript-go node.

func (*Program) Declarations

func (p *Program) Declarations(s Symbol) []Node

Declarations returns the declaration nodes for a symbol; a symbol can have several, for overloads or merged interfaces.

func (*Program) DeclaredTypeAt

func (p *Program) DeclaredTypeAt(n Node) (declared, narrowed Type, ok bool)

DeclaredTypeAt returns the un-narrowed declared type of the variable used at n alongside the narrowed type from TypeAt, so the partitioner can tell when a branch relies on narrowing.

func (*Program) Diagnostics

func (p *Program) Diagnostics() []Diagnostic

Diagnostics returns all syntactic and semantic diagnostics for the program, passed through from the checker so bento output matches tsc.

func (*Program) ElementType

func (p *Program) ElementType(t Type) (Type, bool)

ElementType returns the element type of an array or tuple type, and ok=false for a non-array.

func (*Program) ForClauses

func (p *Program) ForClauses(n Node) ForClauses

ForClauses returns a for statement's initializer, condition, incrementor, and body by role, with a flag for each of the three optional header clauses. It reads roles straight off the node, so an omitted clause is reported as absent rather than silently collapsing onto another role the way a bare child walk would. The node must be a for statement.

func (*Program) Imports

func (p *Program) Imports(f SourceFile) []ResolvedImport

Imports returns the resolved imports of a source file, each mapping a written specifier to the file it resolved to and the kind of import it is.

func (*Program) IntersectionMembers

func (p *Program) IntersectionMembers(t Type) []Type

IntersectionMembers returns the constituent types of an intersection, or a single-element slice for a non-intersection. It is how the lowerer sees through a branded alias (number & { __brand }) to the underlying primitive a go: defined type projects to (section 6.11).

func (*Program) LineColumn

func (p *Program) LineColumn(f SourceFile, at Pos) Position

LineColumn resolves a byte offset in a file to a Position.

func (*Program) LiteralValue

func (p *Program) LiteralValue(t Type) (LiteralValue, bool)

LiteralValue returns the literal value of a literal type, so lowering can fold closed unions into integer tags and refine integers.

func (*Program) Properties

func (p *Program) Properties(t Type) []Property

Properties returns the named members of an object type, each with its own type and optionality.

func (*Program) Revision

func (p *Program) Revision() string

Revision reports the pinned typescript-go revision the backing adapter was built against, empty for the fake or a not-yet-pinned real adapter.

func (*Program) ShorthandValueSymbolAt

func (p *Program) ShorthandValueSymbolAt(n Node) (Symbol, bool)

ShorthandValueSymbolAt returns the local binding an object-literal shorthand member reads, so the use walk can credit `{ x }` to the outer `x` rather than to the property the shorthand declares. It reports false for a node that is not a shorthand member.

func (*Program) SignatureAt

func (p *Program) SignatureAt(n Node) (Signature, bool)

SignatureAt returns the signature the checker resolved for a specific call, new expression, or function declaration node, after overload resolution.

func (*Program) Signatures

func (p *Program) Signatures(t Type) (call, construct []Signature)

Signatures returns the call signatures and construct signatures of a function type separately, because lowering emits a Go func for the former and a constructor for the latter.

func (*Program) SourceFiles

func (p *Program) SourceFiles() []Node

SourceFiles returns the top-level node of each file, the roots a consumer walks to enumerate declarations. The synthetic ambient library bento injects (its Node global declarations) is filtered out here, so it is invisible to every consumer the way lib.d.ts is: it supplies globals to the checker but is not a file the program lists, lowers, or reports on.

func (*Program) SymbolAt

func (p *Program) SymbolAt(n Node) (Symbol, bool)

SymbolAt returns the symbol a name node resolves to, and ok=false for a node that resolves to no symbol.

func (*Program) Text

func (p *Program) Text(n Node) string

Text returns n's own source text with no leading trivia, the identifier name, literal, or operator token lowering emits into the generated Go.

func (*Program) TypeAt

func (p *Program) TypeAt(n Node) Type

TypeAt returns the type of the expression at n, with flow narrowing applied at n's exact position. This is the query the partitioner runs on every parameter, local, and return, and the query lowering runs on every expression.

func (*Program) TypeOfSymbol

func (p *Program) TypeOfSymbol(s Symbol) Type

TypeOfSymbol returns the declared type of a symbol at its declaration.

func (*Program) TypeSymbol

func (p *Program) TypeSymbol(t Type) (Symbol, bool)

TypeSymbol returns the symbol a type was declared by, and ok=false for an anonymous type. Lowering uses it to walk from a class instance type back to the class declaration that names it.

func (*Program) UnionMembers

func (p *Program) UnionMembers(t Type) []Type

UnionMembers returns the constituent types of a union, or a single-element slice for a non-union.

func (*Program) Widen

func (p *Program) Widen(t Type) Type

Widen returns the widened type of a literal type, turning the literal 42 into number, which the partitioner uses when a literal escapes its context.

type Property

type Property struct {
	Name     string
	Type     Type
	Optional bool
	Readonly bool
}

Property is one member of an object type.

type ResolvedImport

type ResolvedImport struct {
	Specifier string
	Resolved  SourceFile
	Kind      ImportKind
}

ResolvedImport is one edge in the module graph.

type Result

type Result struct {
	// Code is the emitted JavaScript.
	Code string
	// SourceMap is the inline or external source map, empty when disabled.
	SourceMap string
}

Result is the outcome of transpiling one source file.

func Transpile

func Transpile(source string, opts Options) (Result, error)

Transpile converts one TypeScript or JavaScript file to CommonJS JavaScript targeting a stable syntax level the engine supports. The loader is chosen from the file extension so .ts, .tsx, .jsx, .mts, and .cts all work.

func TranspileESM

func TranspileESM(source string, opts Options) (Result, error)

TranspileESM converts one TypeScript or JavaScript file to ES module output, preserving import and export statements and top-level await so the engine can link and run it natively. It is the path for modules the CommonJS format cannot express.

type Signature

type Signature struct {
	Params     []Param
	Return     Type
	TypeParams []Type
	RestParam  *Param
	MinArgs    int
}

Signature is bento's view of a call or construct signature. Lowering reads it to emit a Go function signature; the partitioner reads it to decide whether every parameter and the return are lowerable.

type SourceFile

type SourceFile struct {
	Path string
	Kind FileKind
}

SourceFile identifies a file in the program and lets consumers turn offsets into human positions for diagnostics and source maps.

type Span

type Span struct {
	Start Pos
	End   Pos
}

Span is a half-open byte range in a file.

type Symbol

type Symbol struct {
	Name  string
	Flags SymbolFlags
	// contains filtered or unexported fields
}

Symbol is bento's view of a bound declaration. Identity is by the opaque id, so two Symbol values name the same symbol when their ids are equal.

type SymbolFlags

type SymbolFlags = adapter.SymbolFlags

Classification enum aliases. The underlying values live in the adapter package.

type Type

type Type struct {
	Flags TypeFlags
	// contains filtered or unexported fields
}

Type is bento's view of a TypeScript type: a small handle carrying the coarse flags eagerly, with structural detail fetched through Program methods so the typescript-go type object never crosses the adapter boundary.

func (Type) Identity

func (t Type) Identity() int

Identity returns a small integer stable within one Program that is equal for two Type values naming the same underlying type. It is enough to break cycles when a consumer walks a recursive type (an object whose field type refers back to itself) without exposing the typescript-go type object. Two Type values from different programs may share an id, so use it only within one program's traversal.

type TypeFlags

type TypeFlags = adapter.TypeFlags

Classification enum aliases. The underlying values live in the adapter package.

Directories

Path Synopsis
Package adapter is the only bento package that is allowed to import microsoft/typescript-go.
Package adapter is the only bento package that is allowed to import microsoft/typescript-go.

Jump to

Keyboard shortcuts

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