Documentation
¶
Overview ¶
Package browser defines the persistent browser session metadata model used by the planned `tap browser ...` workflow.
Phase 1 establishes the durable state contract before the runtime is added:
- A session is one persistent browser instance, either local or remote.
- A tab is a named tracked browser target within a session.
- Stored metadata is the source of truth for names and selection defaults.
- Each command must reconcile metadata against live targets before acting.
- Untracked live browser tabs are ignored by default.
- Missing tracked targets become stale until they are recreated or removed.
The package also defines the initial local-vs-remote capability matrix used by CLI help text and README documentation:
- Local sessions own their browser process and profile directory.
- Remote sessions bind metadata to an explicit CDP WebSocket endpoint.
- Remote session creation validates the endpoint up front.
- Remote session close removes tap metadata only and never kills the remote browser process.
Package browser manages alternative browser backends for CDP-based automation.
Index ¶
- Constants
- Variables
- func BackTarget(ctx context.Context, debugURL string, targetID string) error
- func CapabilitiesForMode(mode Mode) map[Operation]Capability
- func CheckProcess(record *ProcessRecord) error
- func CheckProcessContext(ctx context.Context, record *ProcessRecord) error
- func ClearCookiesTarget(ctx context.Context, debugURL string, targetID string) error
- func ClearIntercept(ctx context.Context, debugURL string, targetID string) error
- func ClickTarget(ctx context.Context, debugURL string, targetID string, sel string) error
- func ClickTargetByBackendNodeID(ctx context.Context, debugURL, targetID string, ...) error
- func CloseTarget(ctx context.Context, debugURL string, targetID string) error
- func CreateTarget(ctx context.Context, debugURL string, url string) (string, error)
- func DefaultStateRoot() (string, error)
- func DialogTarget(ctx context.Context, debugURL string, targetID string, accept bool, ...) error
- func DiscoverUserChromeDebugURL() (string, string, error)
- func EnableNetworkLog(ctx context.Context, debugURL string, targetID string, filter NetworkFilter) (<-chan NetworkEntry, func(), error)
- func EvalTarget(ctx context.Context, debugURL string, targetID string, js string) (any, error)
- func FillTarget(ctx context.Context, debugURL string, targetID string, fields []FillField, ...) error
- func FillTargetByBackendNodeID(ctx context.Context, debugURL, targetID string, ...) error
- func ForwardTarget(ctx context.Context, debugURL string, targetID string) error
- func GenerateOwnershipToken() (string, error)
- func GetHTMLTarget(ctx context.Context, debugURL string, targetID string, sel string) (string, string, error)
- func GetResponseBody(ctx context.Context, debugURL string, targetID string, requestID string) ([]byte, error)
- func HoverTarget(ctx context.Context, debugURL string, targetID string, sel string) error
- func IsListenAddrInUse(err error) bool
- func KeypressTarget(ctx context.Context, debugURL string, targetID string, keys string) error
- func KillProcess(record *ProcessRecord) error
- func NavigateTarget(ctx context.Context, debugURL string, targetID string, url string) error
- func PDFTarget(ctx context.Context, debugURL string, targetID string, landscape bool, ...) ([]byte, error)
- func ProxyEndpointForListenAddr(listenAddr string) string
- func ProxyHTTPBaseForListenAddr(listenAddr string) string
- func ReloadTarget(ctx context.Context, debugURL string, targetID string) error
- func ResolveDebugURL(ctx context.Context, endpoint string) (string, error)
- func ResolveDebugURLFromDevToolsFile(path string) (string, error)
- func ResolveElectronDebugURL(ctx context.Context, port int) (string, error)
- func ScreenshotTarget(ctx context.Context, debugURL string, targetID string) ([]byte, error)
- func ScrollTarget(ctx context.Context, debugURL string, targetID string, sel string, ...) error
- func SelectTarget(ctx context.Context, debugURL string, targetID string, sel string, ...) error
- func SelectTargetByBackendNodeID(ctx context.Context, debugURL, targetID string, ...) error
- func SetCookieTarget(ctx context.Context, debugURL string, targetID string, ...) error
- func SetInterceptRules(ctx context.Context, debugURL string, targetID string, rules []InterceptRule) (func(), error)
- func ShouldReuseProxyDaemon(record *ProxyDaemonRecord, discoveredUpstreamWSURL string, ...) bool
- func ShutdownProxyDaemon(ctx context.Context, record *ProxyDaemonRecord) error
- func TypeTarget(ctx context.Context, debugURL string, targetID string, sel string, text string) error
- func TypeTargetByBackendNodeID(ctx context.Context, debugURL, targetID string, ...) error
- func ValidateInterceptRules(rules []InterceptRule) error
- func ValidateSessionName(name string) error
- func ValidateTabName(name string) error
- func WaitForProxyDaemonExit(ctx context.Context, record *ProxyDaemonRecord) error
- func WaitForTarget(ctx context.Context, debugURL string, targetID string, sel string, ...) error
- type Capability
- type ChromeInfo
- type CookieEntry
- type DefaultContextKind
- type DefaultContextRecord
- type ElectronProcess
- type FillField
- type FillInput
- type FormField
- type InterceptRule
- type Lightpanda
- func (lp *Lightpanda) Cleanup() error
- func (lp *Lightpanda) EnsureInstalled(ctx context.Context) error
- func (lp *Lightpanda) Installed() bool
- func (lp *Lightpanda) ReadMeta() (*Meta, error)
- func (lp *Lightpanda) Running() bool
- func (lp *Lightpanda) Start(ctx context.Context) error
- func (lp *Lightpanda) Stop()
- func (lp *Lightpanda) Update(ctx context.Context) error
- func (lp *Lightpanda) WSURL() string
- type LocalConfig
- type Manager
- func (m *Manager) AdoptTab(ctx context.Context, sessionName string, tabName string, targetID string, ...) error
- func (m *Manager) Back(ctx context.Context, sessionName string, tabName string) error
- func (m *Manager) ClearCookies(ctx context.Context, sessionName string, tabName string) error
- func (m *Manager) ClearDefaultContext(_ context.Context) error
- func (m *Manager) Click(ctx context.Context, sessionName string, tabName string, sel string) error
- func (m *Manager) ClickElement(ctx context.Context, sessionName, tabName, arg string) error
- func (m *Manager) CloseSession(ctx context.Context, name string) error
- func (m *Manager) CloseTab(ctx context.Context, sessionName string, tabName string) error
- func (m *Manager) CreateSession(ctx context.Context, name string, mode Mode, opts SessionOptions) error
- func (m *Manager) CreateTab(ctx context.Context, sessionName string, tabName string, url string) error
- func (m *Manager) DefaultContext(_ context.Context) (*DefaultContextRecord, error)
- func (m *Manager) Dialog(ctx context.Context, sessionName string, tabName string, accept bool, ...) error
- func (m *Manager) Evaluate(ctx context.Context, sessionName string, tabName string, js string) (any, error)
- func (m *Manager) Fill(ctx context.Context, sessionName string, tabName string, fields []FillField, ...) error
- func (m *Manager) FillElements(ctx context.Context, sessionName, tabName string, inputs []FillInput, ...) error
- func (m *Manager) Forms(ctx context.Context, sessionName string, tabName string) ([]FormField, error)
- func (m *Manager) Forward(ctx context.Context, sessionName string, tabName string) error
- func (m *Manager) GetCookies(ctx context.Context, sessionName string, tabName string) ([]CookieEntry, error)
- func (m *Manager) GetSession(_ context.Context, name string) (*SessionRecord, error)
- func (m *Manager) Hover(ctx context.Context, sessionName string, tabName string, sel string) error
- func (m *Manager) Keypress(ctx context.Context, sessionName string, tabName string, keys string) error
- func (m *Manager) ListSessions(_ context.Context) (*SessionList, error)
- func (m *Manager) ListTabs(_ context.Context, sessionName string) (*TabList, error)
- func (m *Manager) Navigate(ctx context.Context, sessionName string, tabName string, url string) error
- func (m *Manager) NetworkClearIntercept(ctx context.Context, sessionName string, tabName string) error
- func (m *Manager) NetworkGetBody(ctx context.Context, sessionName string, tabName string, requestID string) ([]byte, error)
- func (m *Manager) NetworkIntercept(ctx context.Context, sessionName string, tabName string, rules []InterceptRule) error
- func (m *Manager) NetworkLog(ctx context.Context, sessionName string, tabName string, filter NetworkFilter) (<-chan NetworkEntry, func(), error)
- func (m *Manager) NetworkWait(ctx context.Context, sessionName string, tabName string, filter NetworkFilter, ...) (*NetworkEntry, error)
- func (m *Manager) PDF(ctx context.Context, sessionName string, tabName string, landscape bool, ...) (*PDFResult, error)
- func (m *Manager) Reconcile(ctx context.Context, sessionName string) error
- func (m *Manager) Reload(ctx context.Context, sessionName string, tabName string) error
- func (m *Manager) ResolveTarget(ctx context.Context, sessionName string, tabName string) (ResolvedTarget, error)
- func (m *Manager) Screenshot(ctx context.Context, sessionName string, tabName string) (*ScreenshotResult, error)
- func (m *Manager) Scroll(ctx context.Context, sessionName string, tabName string, sel string, ...) error
- func (m *Manager) Select(ctx context.Context, sessionName string, tabName string, sel string, ...) error
- func (m *Manager) SelectElement(ctx context.Context, sessionName, tabName, arg, value string) error
- func (m *Manager) SelectTab(ctx context.Context, sessionName string, tabName string) error
- func (m *Manager) SetCookie(ctx context.Context, sessionName string, tabName string, ...) error
- func (m *Manager) SetDefaultContext(_ context.Context, sessionName string, kind DefaultContextKind) error
- func (m *Manager) Snapshot(ctx context.Context, sessionName string, tabName string, opts SnapshotOptions) (*SnapshotResult, error)
- func (m *Manager) Type(ctx context.Context, sessionName string, tabName string, sel string, ...) error
- func (m *Manager) TypeElement(ctx context.Context, sessionName, tabName, arg, text string) error
- func (m *Manager) WaitFor(ctx context.Context, sessionName string, tabName string, sel string, ...) error
- type Meta
- type Mode
- type NetworkEntry
- type NetworkFilter
- type Operation
- type PDFResult
- type ProcessRecord
- type Proxy
- type ProxyConfig
- type ProxyDaemonHealth
- type ProxyDaemonRecord
- type RemoteConfig
- type ResolvedTarget
- type ScreenshotResult
- type SessionList
- type SessionOptions
- type SessionRecord
- type SnapshotNode
- type SnapshotOptions
- type SnapshotRef
- type SnapshotResult
- type State
- func (s *State) ClearDefaultContext()
- func (s *State) CreateSession(session *SessionRecord) error
- func (s *State) DeleteSession(name string) error
- func (s *State) DeleteTab(sessionName string, tabName string) error
- func (s *State) MarkDefaultContextHealthy(sessionName string, now time.Time)
- func (s *State) MarkDefaultContextStale(sessionName string, reason string, now time.Time)
- func (s *State) Normalize()
- func (s *State) ReconcileSession(sessionName string, liveTargetIDs []string, now time.Time) error
- func (s *State) ResolveSession(name string) (*SessionRecord, error)
- func (s *State) ResolveSessionByPreference(name string) (*SessionRecord, error)
- func (s *State) SelectTab(sessionName string, tabName string) error
- func (s *State) SetDefaultContext(sessionName string, kind DefaultContextKind, now time.Time) error
- func (s *State) UpsertTab(sessionName string, tab *TabRecord) error
- func (s *State) Validate() error
- type Store
- func (s *Store) Load() (*State, error)
- func (s *Store) Root() string
- func (s *Store) Save(state *State) error
- func (s *Store) Update(fn func(*State) error) error
- func (s *Store) UpdateSession(sessionName string, fn func(*State, *SessionRecord) error) error
- func (s *Store) WithSessionLock(sessionName string, fn func() error) error
- type TabList
- type TabRecord
- type TabStatus
- type TargetInfo
Constants ¶
const ( AttachStateDetached = "detached" AttachStateAttachedReady = "attached-ready" AttachStateAttachedStale = "attached-stale" )
const ( // StateVersion is the current on-disk schema version for browser metadata. StateVersion = 1 // DefaultSessionName is the session used when --session is omitted. DefaultSessionName = "default" // EnvStateRoot overrides the default durable state directory. EnvStateRoot = "TAP_BROWSER_STATE_DIR" )
const (
DefaultProxyListenAddr = "127.0.0.1:12345"
)
const TargetTypePage = "page"
Variables ¶
var ( ErrSessionNotFound = errors.New("browser session not found") ErrNoTabs = errors.New("no tracked tabs found") ErrAmbiguousTab = errors.New("browser tab selection is ambiguous") ErrTabNotFound = errors.New("browser tab not found") ErrClosedTabSelected = errors.New("browser tab is closed") ErrStaleTabSelected = errors.New("browser tab is stale") ErrDefaultContextNotSet = errors.New("default browser context is not set") ErrDefaultContextInvalid = errors.New("default browser context is invalid") )
Functions ¶
func BackTarget ¶ added in v0.3.0
BackTarget navigates the tab backwards in history.
func CapabilitiesForMode ¶ added in v0.1.7
func CapabilitiesForMode(mode Mode) map[Operation]Capability
CapabilitiesForMode returns the documented capability contract for the given mode.
func CheckProcess ¶ added in v0.1.7
func CheckProcess(record *ProcessRecord) error
CheckProcess verifies that the process described by record is alive and its debug endpoint is reachable.
func CheckProcessContext ¶ added in v0.1.7
func CheckProcessContext(ctx context.Context, record *ProcessRecord) error
CheckProcessContext is like CheckProcess but accepts a context for cancellation.
func ClearCookiesTarget ¶ added in v0.3.0
ClearCookiesTarget deletes all cookies for the current page.
func ClearIntercept ¶ added in v0.2.0
ClearIntercept disables the Fetch domain on a target.
func ClickTarget ¶ added in v0.3.0
ClickTarget dispatches a real mouse click on the first element matching sel. chromedp.Click sends the full mouseMoved → mousePressed → mouseReleased sequence.
func ClickTargetByBackendNodeID ¶ added in v0.4.2
func CloseTarget ¶ added in v0.1.7
CloseTarget closes the browser tab identified by targetID.
func CreateTarget ¶ added in v0.1.7
CreateTarget creates a new browser tab navigated to url and returns its target ID.
func DefaultStateRoot ¶ added in v0.1.7
DefaultStateRoot returns the durable directory used for browser metadata. Uses $XDG_CACHE_HOME/tap/browser, falling back to ~/.cache/tap/browser.
func DialogTarget ¶ added in v0.3.0
func DialogTarget(ctx context.Context, debugURL string, targetID string, accept bool, promptText string) error
DialogTarget accepts or dismisses a pending JavaScript dialog (alert/confirm/prompt). For prompt dialogs, promptText is entered before accepting.
func DiscoverUserChromeDebugURL ¶ added in v0.4.0
DiscoverUserChromeDebugURL resolves the browser WebSocket URL for an already running user Chrome/Chromium instance that has remote debugging enabled. It reads the DevToolsActivePort file from common user-data directories.
func EnableNetworkLog ¶ added in v0.2.0
func EnableNetworkLog(ctx context.Context, debugURL string, targetID string, filter NetworkFilter) (<-chan NetworkEntry, func(), error)
EnableNetworkLog enables the Network domain on a target and streams completed request/response entries to the returned channel. The channel is buffered (256 entries); if the buffer fills, new entries are dropped.
Call the returned cancel func to stop capturing and close the channel. The caller should drain the channel or call cancel to avoid goroutine leaks.
func EvalTarget ¶ added in v0.1.7
EvalTarget evaluates JavaScript in the context of an existing browser tab and returns the result.
func FillTarget ¶ added in v0.1.7
func FillTarget(ctx context.Context, debugURL string, targetID string, fields []FillField, submitSelector string) error
FillTarget fills form fields in a browser tab using React-compatible value setting.
func FillTargetByBackendNodeID ¶ added in v0.4.2
func ForwardTarget ¶ added in v0.3.0
ForwardTarget navigates the tab forwards in history.
func GenerateOwnershipToken ¶ added in v0.4.0
func GetHTMLTarget ¶ added in v0.3.0
func GetHTMLTarget(ctx context.Context, debugURL string, targetID string, sel string) (string, string, error)
GetHTMLTarget returns the outerHTML of the element matching sel, or the full page HTML if sel is empty.
func GetResponseBody ¶ added in v0.2.0
func GetResponseBody(ctx context.Context, debugURL string, targetID string, requestID string) ([]byte, error)
GetResponseBody fetches the response body for a completed request by its ID.
func HoverTarget ¶ added in v0.3.0
HoverTarget moves the mouse to the center of the element matching sel, dispatching mouseMoved events that trigger CSS :hover states and mouseenter listeners.
func IsListenAddrInUse ¶ added in v0.4.0
func KeypressTarget ¶ added in v0.3.0
KeypressTarget sends key events to the page (not a specific element). The keys string uses chromedp/kb constants: "\r" for Enter, "\t" for Tab, "\u001b" for Escape, etc. Regular characters are sent as-is.
func KillProcess ¶ added in v0.1.7
func KillProcess(record *ProcessRecord) error
KillProcess terminates the Chrome process described by record. It sends a graceful shutdown signal first and falls back to forceful termination after a grace period.
func NavigateTarget ¶ added in v0.1.7
NavigateTarget navigates an existing browser tab to url and waits for the body to be ready.
func PDFTarget ¶ added in v0.3.0
func PDFTarget(ctx context.Context, debugURL string, targetID string, landscape bool, printBackground bool, scale float64) ([]byte, error)
PDFTarget saves the current page as PDF and returns the bytes.
func ProxyEndpointForListenAddr ¶ added in v0.4.0
func ProxyHTTPBaseForListenAddr ¶ added in v0.4.0
func ReloadTarget ¶ added in v0.3.0
ReloadTarget reloads the current page in the tab.
func ResolveDebugURL ¶ added in v0.4.0
ResolveDebugURL accepts either a CDP browser WebSocket URL or an HTTP(S) DevTools base URL (for example http://127.0.0.1:9222) and returns the browser WebSocket URL that chromedp expects.
func ResolveDebugURLFromDevToolsFile ¶ added in v0.4.0
ResolveDebugURLFromDevToolsFile parses a DevToolsActivePort file and returns the browser WebSocket URL.
func ResolveElectronDebugURL ¶ added in v0.4.0
ResolveElectronDebugURL queries /json/version at the given port and returns the WebSocket debug URL. Electron (and Chrome) publish the exact WS URL including the browser UUID path in the webSocketDebuggerUrl field.
func ScreenshotTarget ¶ added in v0.1.7
ScreenshotTarget captures a full-page screenshot of an existing browser tab and returns the PNG bytes.
func ScrollTarget ¶ added in v0.3.0
func ScrollTarget(ctx context.Context, debugURL string, targetID string, sel string, x, y float64) error
ScrollTarget scrolls the element matching sel into view. If sel is empty, scrolls to the given x,y pixel coordinates.
func SelectTarget ¶ added in v0.3.0
func SelectTarget(ctx context.Context, debugURL string, targetID string, sel string, value string) error
SelectTarget selects an option in a <select> element by value, dispatching focus, input, and change events.
func SelectTargetByBackendNodeID ¶ added in v0.4.2
func SetCookieTarget ¶ added in v0.3.0
func SetCookieTarget(ctx context.Context, debugURL string, targetID string, name, value, domain, path string) error
SetCookieTarget sets a cookie on the page.
func SetInterceptRules ¶ added in v0.2.0
func SetInterceptRules(ctx context.Context, debugURL string, targetID string, rules []InterceptRule) (func(), error)
SetInterceptRules enables Fetch domain interception with the given rules. It replaces any previously set rules. The returned cancel func stops the interception goroutine and disables the Fetch domain.
Pass nil/empty rules to effectively disable interception (or use ClearIntercept).
func ShouldReuseProxyDaemon ¶ added in v0.4.0
func ShouldReuseProxyDaemon(record *ProxyDaemonRecord, discoveredUpstreamWSURL string, health ProxyDaemonHealth) bool
func ShutdownProxyDaemon ¶ added in v0.4.0
func ShutdownProxyDaemon(ctx context.Context, record *ProxyDaemonRecord) error
func TypeTarget ¶ added in v0.3.0
func TypeTarget(ctx context.Context, debugURL string, targetID string, sel string, text string) error
TypeTarget sends individual key events to the element matching sel. Unlike FillTarget which sets .value directly, this dispatches keyDown/keyUp per character — behaving like a real user typing.
func TypeTargetByBackendNodeID ¶ added in v0.4.2
func ValidateInterceptRules ¶ added in v0.2.0
func ValidateInterceptRules(rules []InterceptRule) error
ValidateInterceptRules checks that rules are well-formed.
func ValidateSessionName ¶ added in v0.1.7
ValidateSessionName checks the user-facing session naming rules.
func ValidateTabName ¶ added in v0.1.7
ValidateTabName checks the user-facing tab naming rules.
func WaitForProxyDaemonExit ¶ added in v0.4.0
func WaitForProxyDaemonExit(ctx context.Context, record *ProxyDaemonRecord) error
Types ¶
type Capability ¶ added in v0.1.7
Capability describes whether an operation is supported for a session mode.
type ChromeInfo ¶ added in v0.3.2
ChromeInfo holds information about an installed Chrome browser.
func DetectChrome ¶ added in v0.3.2
func DetectChrome() *ChromeInfo
DetectChrome finds a Chrome/Chromium installation and returns its path and version. It reuses the same discovery logic as the browser launcher (findChrome). Returns nil if no Chrome is found.
type CookieEntry ¶ added in v0.3.0
type CookieEntry struct {
Name string `json:"name"`
Value string `json:"value"`
Domain string `json:"domain"`
Path string `json:"path"`
Expires float64 `json:"expires"`
HTTPOnly bool `json:"httpOnly"`
Secure bool `json:"secure"`
Session bool `json:"session"`
SameSite string `json:"sameSite,omitempty"`
}
CookieEntry represents a browser cookie for JSON output.
func GetCookiesTarget ¶ added in v0.3.0
GetCookiesTarget returns all cookies for the current page.
type DefaultContextKind ¶ added in v0.4.0
type DefaultContextKind string
const ( DefaultContextManaged DefaultContextKind = "managed" DefaultContextAttached DefaultContextKind = "attached" )
type DefaultContextRecord ¶ added in v0.4.0
type DefaultContextRecord struct {
SessionName string `json:"session_name"`
Kind DefaultContextKind `json:"kind"`
Stale bool `json:"stale,omitempty"`
Reason string `json:"reason,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
}
DefaultContextRecord stores the persisted default browser context resolution.
type ElectronProcess ¶ added in v0.4.0
ElectronProcess describes a running process that exposes a CDP debug port.
func ScanElectronProcesses ¶ added in v0.4.0
func ScanElectronProcesses(ctx context.Context) ([]ElectronProcess, error)
ScanElectronProcesses returns all running processes that have --remote-debugging-port=PORT in their command line. It works for Electron apps, CEF-based apps, and any Chromium-derived binary launched with a debug port. Returns an empty slice (not an error) when no matching processes exist.
type FillInput ¶ added in v0.4.2
FillInput represents a fill target (CSS selector or snapshot ref) and value.
type FormField ¶ added in v0.1.7
type FormField struct {
Selector string `json:"selector"`
Tag string `json:"tag"`
Type string `json:"type,omitempty"`
Name string `json:"name,omitempty"`
ID string `json:"id,omitempty"`
Placeholder string `json:"placeholder,omitempty"`
Value string `json:"value,omitempty"`
Label string `json:"label,omitempty"`
Required bool `json:"required,omitempty"`
Disabled bool `json:"disabled,omitempty"`
Role string `json:"role,omitempty"`
}
FormField describes a fillable form element on the page.
type InterceptRule ¶ added in v0.2.0
type InterceptRule struct {
Filter NetworkFilter `json:"filter"`
Block bool `json:"block,omitempty"`
AddHeaders map[string]string `json:"addHeaders,omitempty"`
MockStatus int `json:"mockStatus,omitempty"`
MockBody string `json:"mockBody,omitempty"`
MockHeaders map[string]string `json:"mockHeaders,omitempty"`
}
InterceptRule defines how to modify or block requests matching a filter. Block and MockBody are mutually exclusive.
type Lightpanda ¶
type Lightpanda struct {
// contains filtered or unexported fields
}
Lightpanda manages the Lightpanda browser process.
func NewLightpanda ¶
func NewLightpanda(binDir, port string) *Lightpanda
NewLightpanda creates a new Lightpanda manager. binDir is where the binary is stored; if empty, defaults to ~/.cache/tap/lightpanda/. port is the CDP port; if empty, defaults to 9222.
func (*Lightpanda) Cleanup ¶
func (lp *Lightpanda) Cleanup() error
Cleanup removes the downloaded binary and its metadata.
func (*Lightpanda) EnsureInstalled ¶
func (lp *Lightpanda) EnsureInstalled(ctx context.Context) error
EnsureInstalled downloads the Lightpanda binary if it doesn't exist or is empty.
func (*Lightpanda) Installed ¶ added in v0.3.2
func (lp *Lightpanda) Installed() bool
Installed reports whether the Lightpanda binary exists and is non-empty.
func (*Lightpanda) ReadMeta ¶ added in v0.3.2
func (lp *Lightpanda) ReadMeta() (*Meta, error)
ReadMeta reads the metadata file for the installed binary. Returns nil if no metadata file exists.
func (*Lightpanda) Running ¶
func (lp *Lightpanda) Running() bool
Running reports whether the Lightpanda server is currently running.
func (*Lightpanda) Start ¶
func (lp *Lightpanda) Start(ctx context.Context) error
Start launches the Lightpanda server and waits for it to be ready. It is safe to call multiple times — subsequent calls are no-ops if already running.
func (*Lightpanda) Update ¶ added in v0.3.2
func (lp *Lightpanda) Update(ctx context.Context) error
Update re-downloads the Lightpanda binary regardless of whether it exists.
func (*Lightpanda) WSURL ¶
func (lp *Lightpanda) WSURL() string
WSURL returns the WebSocket URL for the running Lightpanda instance.
type LocalConfig ¶ added in v0.1.7
LocalConfig freezes local launch settings into session metadata.
type Manager ¶ added in v0.1.7
type Manager struct {
// contains filtered or unexported fields
}
Manager coordinates browser session lifecycle, tab management, and browser actions using the metadata store and CDP transport layer.
func NewManager ¶ added in v0.1.7
NewManager creates a session manager backed by the given store.
func (*Manager) AdoptTab ¶ added in v0.4.0
func (m *Manager) AdoptTab(ctx context.Context, sessionName string, tabName string, targetID string, url string) error
AdoptTab registers an existing CDP target as a tracked tab without creating a new browser target. Use this to import pre-existing Electron windows or other targets that were not launched by tap. targetID must be a live target reachable through the session's debug URL.
func (*Manager) ClearCookies ¶ added in v0.3.0
ClearCookies deletes all cookies for the current page in a tracked tab.
func (*Manager) ClearDefaultContext ¶ added in v0.4.0
ClearDefaultContext removes the persisted default browser context.
func (*Manager) Click ¶ added in v0.3.0
Click dispatches a real mouse click on the element matching sel in a tracked tab.
func (*Manager) ClickElement ¶ added in v0.4.2
ClickElement clicks an element by CSS selector or snapshot ref (e.g. @e12).
func (*Manager) CloseSession ¶ added in v0.1.7
CloseSession terminates a browser session, kills the local process if applicable, and removes all related metadata.
func (*Manager) CloseTab ¶ added in v0.1.7
CloseTab closes a browser tab and removes it from session metadata.
func (*Manager) CreateSession ¶ added in v0.1.7
func (m *Manager) CreateSession(ctx context.Context, name string, mode Mode, opts SessionOptions) error
CreateSession launches or connects to a browser and persists session metadata.
func (*Manager) CreateTab ¶ added in v0.1.7
func (m *Manager) CreateTab(ctx context.Context, sessionName string, tabName string, url string) error
CreateTab opens a new browser tab and tracks it in session metadata.
func (*Manager) DefaultContext ¶ added in v0.4.0
func (m *Manager) DefaultContext(_ context.Context) (*DefaultContextRecord, error)
DefaultContext returns the persisted default browser context metadata.
func (*Manager) Dialog ¶ added in v0.3.0
func (m *Manager) Dialog(ctx context.Context, sessionName string, tabName string, accept bool, promptText string) error
Dialog accepts or dismisses a pending JavaScript dialog in a tracked tab.
func (*Manager) Evaluate ¶ added in v0.1.7
func (m *Manager) Evaluate(ctx context.Context, sessionName string, tabName string, js string) (any, error)
Evaluate runs JavaScript in a tracked tab and returns the result.
func (*Manager) Fill ¶ added in v0.1.7
func (m *Manager) Fill(ctx context.Context, sessionName string, tabName string, fields []FillField, submitSelector string) error
Fill sets values in form fields of a tracked tab.
func (*Manager) FillElements ¶ added in v0.4.2
func (m *Manager) FillElements(ctx context.Context, sessionName, tabName string, inputs []FillInput, submitArg string) error
FillElements fills values by CSS selector or snapshot refs.
func (*Manager) Forms ¶ added in v0.1.7
func (m *Manager) Forms(ctx context.Context, sessionName string, tabName string) ([]FormField, error)
Forms discovers fillable form elements in a tracked tab.
func (*Manager) GetCookies ¶ added in v0.3.0
func (m *Manager) GetCookies(ctx context.Context, sessionName string, tabName string) ([]CookieEntry, error)
GetCookies returns all cookies for the current page in a tracked tab.
func (*Manager) GetSession ¶ added in v0.1.7
GetSession resolves a session by name or the persisted default context.
func (*Manager) Hover ¶ added in v0.3.0
Hover moves the mouse to the element matching sel in a tracked tab.
func (*Manager) Keypress ¶ added in v0.3.0
func (m *Manager) Keypress(ctx context.Context, sessionName string, tabName string, keys string) error
Keypress sends key events to the page in a tracked tab.
func (*Manager) ListSessions ¶ added in v0.1.7
func (m *Manager) ListSessions(_ context.Context) (*SessionList, error)
ListSessions returns all tracked sessions sorted by name.
func (*Manager) ListTabs ¶ added in v0.1.7
ListTabs returns all tracked tabs for a session sorted by creation time.
func (*Manager) Navigate ¶ added in v0.1.7
func (m *Manager) Navigate(ctx context.Context, sessionName string, tabName string, url string) error
Navigate changes the URL of a tracked tab.
func (*Manager) NetworkClearIntercept ¶ added in v0.2.0
func (m *Manager) NetworkClearIntercept(ctx context.Context, sessionName string, tabName string) error
NetworkClearIntercept removes all Fetch domain interception rules from a tracked tab.
func (*Manager) NetworkGetBody ¶ added in v0.2.0
func (m *Manager) NetworkGetBody(ctx context.Context, sessionName string, tabName string, requestID string) ([]byte, error)
NetworkGetBody fetches the response body for a completed request by its request ID from a tracked tab.
func (*Manager) NetworkIntercept ¶ added in v0.2.0
func (m *Manager) NetworkIntercept(ctx context.Context, sessionName string, tabName string, rules []InterceptRule) error
NetworkIntercept sets Fetch domain interception rules on a tracked tab. Replaces any previously set rules (cancels the old interception goroutine).
func (*Manager) NetworkLog ¶ added in v0.2.0
func (m *Manager) NetworkLog(ctx context.Context, sessionName string, tabName string, filter NetworkFilter) (<-chan NetworkEntry, func(), error)
NetworkLog starts capturing network requests for a tracked tab and streams completed entries to the returned channel. Call cancel to stop capturing.
func (*Manager) NetworkWait ¶ added in v0.2.0
func (m *Manager) NetworkWait(ctx context.Context, sessionName string, tabName string, filter NetworkFilter, includeBody bool) (*NetworkEntry, error)
NetworkWait blocks until a network request matching the filter completes in a tracked tab. If includeBody is true, the response body is fetched before returning. The caller controls the timeout via ctx.
func (*Manager) PDF ¶ added in v0.3.0
func (m *Manager) PDF(ctx context.Context, sessionName string, tabName string, landscape bool, printBackground bool, scale float64) (*PDFResult, error)
PDF saves the current page as PDF from a tracked tab.
func (*Manager) Reconcile ¶ added in v0.1.7
Reconcile refreshes tab liveness by comparing metadata against live CDP targets.
func (*Manager) ResolveTarget ¶ added in v0.3.0
func (m *Manager) ResolveTarget(ctx context.Context, sessionName string, tabName string) (ResolvedTarget, error)
ResolveTarget resolves a session and tab to their CDP connection details. Exported for commands that need direct CDP access (e.g., text extraction).
func (*Manager) Screenshot ¶ added in v0.1.7
func (m *Manager) Screenshot(ctx context.Context, sessionName string, tabName string) (*ScreenshotResult, error)
Screenshot captures a full-page PNG of a tracked tab.
func (*Manager) Scroll ¶ added in v0.3.0
func (m *Manager) Scroll(ctx context.Context, sessionName string, tabName string, sel string, x, y float64) error
Scroll scrolls to the element matching sel, or to absolute x,y if sel is empty.
func (*Manager) Select ¶ added in v0.3.0
func (m *Manager) Select(ctx context.Context, sessionName string, tabName string, sel string, value string) error
Select selects an option by value in a <select> element in a tracked tab.
func (*Manager) SelectElement ¶ added in v0.4.2
SelectElement selects option value by CSS selector or snapshot ref.
func (*Manager) SelectTab ¶ added in v0.1.7
SelectTab persists the default tab used when --tab is omitted.
func (*Manager) SetCookie ¶ added in v0.3.0
func (m *Manager) SetCookie(ctx context.Context, sessionName string, tabName string, name, value, domain, path string) error
SetCookie sets a cookie in a tracked tab.
func (*Manager) SetDefaultContext ¶ added in v0.4.0
func (m *Manager) SetDefaultContext(_ context.Context, sessionName string, kind DefaultContextKind) error
SetDefaultContext persists the default browser context resolution.
func (*Manager) Snapshot ¶ added in v0.4.2
func (m *Manager) Snapshot(ctx context.Context, sessionName string, tabName string, opts SnapshotOptions) (*SnapshotResult, error)
Snapshot captures and persists the latest semantic page snapshot for a tab.
func (*Manager) Type ¶ added in v0.3.0
func (m *Manager) Type(ctx context.Context, sessionName string, tabName string, sel string, text string) error
Type sends individual key events to the element matching sel in a tracked tab.
func (*Manager) TypeElement ¶ added in v0.4.2
TypeElement types into an element by CSS selector or snapshot ref.
type NetworkEntry ¶ added in v0.2.0
type NetworkEntry struct {
RequestID string `json:"requestId"`
URL string `json:"url"`
Method string `json:"method"`
Status int64 `json:"status"`
MIMEType string `json:"mimeType,omitempty"`
ResourceType string `json:"resourceType,omitempty"`
ReqHeaders map[string]string `json:"reqHeaders,omitempty"`
ResHeaders map[string]string `json:"resHeaders,omitempty"`
Body string `json:"body,omitempty"`
Error string `json:"error,omitempty"`
Timestamp time.Time `json:"timestamp"`
}
NetworkEntry represents a captured network request/response pair.
func WaitForRequest ¶ added in v0.2.0
func WaitForRequest(ctx context.Context, debugURL string, targetID string, filter NetworkFilter, includeBody bool) (*NetworkEntry, error)
WaitForRequest enables the Network domain and blocks until a request matching the filter completes (response received + loading finished/failed). It returns the first matching NetworkEntry. If includeBody is true, the response body is fetched before returning.
The caller controls the timeout via ctx (e.g. context.WithTimeout).
type NetworkFilter ¶ added in v0.2.0
type NetworkFilter struct {
URLPattern string `json:"urlPattern,omitempty"`
Methods []string `json:"methods,omitempty"`
ResourceTypes []string `json:"resourceTypes,omitempty"`
}
NetworkFilter specifies criteria for matching network requests.
type Operation ¶ added in v0.1.7
type Operation string
Operation is a user-facing browser action supported by the session manager.
type ProcessRecord ¶ added in v0.1.7
type ProcessRecord struct {
PID int `json:"pid,omitempty"`
DebugURL string `json:"debug_url,omitempty"`
OwnershipToken string `json:"ownership_token,omitempty"`
StartedAt time.Time `json:"started_at,omitempty"`
}
ProcessRecord stores the launch markers needed for later ownership checks.
func LaunchBrowser ¶ added in v0.1.7
func LaunchBrowser(ctx context.Context, config LocalConfig) (*ProcessRecord, error)
LaunchBrowser starts a managed Chrome process with remote debugging enabled. The returned ProcessRecord contains the PID, debug WebSocket URL, and an ownership token that later calls can use for verification.
func LaunchElectronApp ¶ added in v0.4.0
func LaunchElectronApp(ctx context.Context, binaryPath string, extra []string) (*ProcessRecord, error)
LaunchElectronApp starts an Electron (or Electron-based) binary with --remote-debugging-port=0 prepended to the argument list. The OS assigns a free port; the debug WebSocket URL is extracted from stderr exactly as with Chrome. extra holds any additional arguments to pass to the binary.
The returned ProcessRecord contains the PID and debug URL. The process is released (detached) so it survives tap exit; callers are responsible for tracking lifecycle via the PID and debug URL.
type Proxy ¶ added in v0.4.0
type Proxy struct {
// contains filtered or unexported fields
}
func NewProxy ¶ added in v0.4.0
func NewProxy(cfg ProxyConfig) *Proxy
type ProxyConfig ¶ added in v0.4.0
ProxyConfig configures the local CDP proxy.
type ProxyDaemonHealth ¶ added in v0.4.0
type ProxyDaemonHealth struct {
CheckedAt time.Time `json:"checked_at"`
PIDAlive bool `json:"pid_alive"`
DaemonReachable bool `json:"daemon_reachable"`
UpstreamReachable bool `json:"upstream_reachable"`
Healthy bool `json:"healthy"`
Status string `json:"status"`
Reason string `json:"reason,omitempty"`
}
func CheckProxyDaemon ¶ added in v0.4.0
func CheckProxyDaemon(ctx context.Context, record *ProxyDaemonRecord) ProxyDaemonHealth
func WaitForProxyDaemonHealth ¶ added in v0.4.0
func WaitForProxyDaemonHealth(ctx context.Context, record *ProxyDaemonRecord) (ProxyDaemonHealth, error)
type ProxyDaemonRecord ¶ added in v0.4.0
type ProxyDaemonRecord struct {
PID int `json:"pid,omitempty"`
ListenAddr string `json:"listen_addr,omitempty"`
Endpoint string `json:"endpoint,omitempty"`
UpstreamWSURL string `json:"upstream_ws_url,omitempty"`
OwnershipToken string `json:"ownership_token,omitempty"`
State string `json:"state,omitempty"`
Status string `json:"status,omitempty"`
LastHealthCheckAt time.Time `json:"last_health_check_at,omitempty"`
LastHealthyAt time.Time `json:"last_healthy_at,omitempty"`
LastError string `json:"last_error,omitempty"`
StartedAt time.Time `json:"started_at,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
}
ProxyDaemonRecord stores the internal CDP proxy metadata used for attached Chrome.
type RemoteConfig ¶ added in v0.1.7
type RemoteConfig struct {
WSURL string `json:"ws_url"`
}
RemoteConfig freezes the remote reconnect endpoint into session metadata.
type ResolvedTarget ¶ added in v0.3.0
type ResolvedTarget = resolvedTarget
ResolvedTarget holds the result of resolving a session and tab for CDP I/O.
type ScreenshotResult ¶ added in v0.1.7
ScreenshotResult holds the screenshot data and resolved names.
type SessionList ¶ added in v0.1.7
type SessionList struct {
Sessions []*SessionRecord
}
SessionList holds the result of listing sessions.
type SessionOptions ¶ added in v0.1.7
type SessionOptions struct {
// Headless controls whether a local browser launches headlessly.
Headless bool
// WSURL is the remote browser WebSocket endpoint (remote mode only).
WSURL string
}
SessionOptions holds optional settings for session creation.
type SessionRecord ¶ added in v0.1.7
type SessionRecord struct {
Name string `json:"name"`
Mode Mode `json:"mode"`
Local *LocalConfig `json:"local,omitempty"`
Remote *RemoteConfig `json:"remote,omitempty"`
Process *ProcessRecord `json:"process,omitempty"`
SelectedTab string `json:"selected_tab,omitempty"`
Tabs map[string]*TabRecord `json:"tabs,omitempty"`
Capabilities map[Operation]Capability `json:"capabilities,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
LastReconciledAt time.Time `json:"last_reconciled_at,omitempty"`
}
SessionRecord stores one persistent browser session and its tracked tabs.
func NewLocalSession ¶ added in v0.1.7
func NewLocalSession(name string, profileDir string, headless bool, now time.Time) (*SessionRecord, error)
NewLocalSession builds a validated local session record.
func NewRemoteSession ¶ added in v0.1.7
NewRemoteSession builds a validated remote session record.
func (*SessionRecord) ResolveTab ¶ added in v0.1.7
func (s *SessionRecord) ResolveTab(name string) (*TabRecord, error)
ResolveTab returns an explicit tab, the selected tab, or the only live tracked tab when exactly one live tab exists.
type SnapshotNode ¶ added in v0.4.2
type SnapshotNode struct {
Ref string `json:"ref,omitempty"`
Role string `json:"role,omitempty"`
Name string `json:"name,omitempty"`
Value string `json:"value,omitempty"`
Description string `json:"description,omitempty"`
States []string `json:"states,omitempty"`
Children []int `json:"children,omitempty"`
}
SnapshotNode is one node in the compact semantic tree.
type SnapshotOptions ¶ added in v0.4.2
type SnapshotOptions struct {
InteractiveOnly bool
Selector string
Depth int64
Mode string // auto | ax
}
SnapshotOptions controls browser snapshot generation.
type SnapshotRef ¶ added in v0.4.2
type SnapshotRef struct {
Ref string `json:"ref"`
BackendDOMNodeID int64 `json:"backendDomNodeId,omitempty"`
AXNodeID string `json:"axNodeId,omitempty"`
FrameID string `json:"frameId,omitempty"`
SelectorHint string `json:"selectorHint,omitempty"`
Role string `json:"role,omitempty"`
Name string `json:"name,omitempty"`
}
SnapshotRef maps an element ref to backend IDs for follow-up actions.
type SnapshotResult ¶ added in v0.4.2
type SnapshotResult struct {
URL string `json:"url"`
Title string `json:"title,omitempty"`
Mode string `json:"mode"`
GeneratedAt time.Time `json:"generatedAt"`
DocumentKey string `json:"documentKey"`
Nodes []SnapshotNode `json:"nodes"`
Refs []SnapshotRef `json:"refs"`
}
SnapshotResult is an AI-friendly semantic snapshot of the current page.
func SnapshotTarget ¶ added in v0.4.2
func SnapshotTarget(ctx context.Context, debugURL, targetID string, opts SnapshotOptions) (*SnapshotResult, error)
SnapshotTarget builds an AX-powered semantic snapshot for a target tab.
type State ¶ added in v0.1.7
type State struct {
Version int `json:"version"`
DefaultContext *DefaultContextRecord `json:"default_context,omitempty"`
ProxyDaemon *ProxyDaemonRecord `json:"proxy_daemon,omitempty"`
Sessions map[string]*SessionRecord `json:"sessions"`
}
State is the durable browser session metadata written to disk.
func NewState ¶ added in v0.1.7
func NewState() *State
NewState returns an empty metadata state with initialized maps.
func (*State) ClearDefaultContext ¶ added in v0.4.0
func (s *State) ClearDefaultContext()
func (*State) CreateSession ¶ added in v0.1.7
func (s *State) CreateSession(session *SessionRecord) error
CreateSession adds a new named session.
func (*State) DeleteSession ¶ added in v0.1.7
DeleteSession removes a session.
func (*State) DeleteTab ¶ added in v0.1.7
DeleteTab removes a tracked tab and advances selection to the next live tab.
func (*State) MarkDefaultContextHealthy ¶ added in v0.4.0
func (*State) MarkDefaultContextStale ¶ added in v0.4.0
func (*State) Normalize ¶ added in v0.1.7
func (s *State) Normalize()
Normalize repairs nil maps and empty versions loaded from disk.
func (*State) ReconcileSession ¶ added in v0.1.7
ReconcileSession updates tab liveness after reloading or reconnecting a browser session.
func (*State) ResolveSession ¶ added in v0.1.7
func (s *State) ResolveSession(name string) (*SessionRecord, error)
ResolveSession returns the session matching name, or the "default" session when name is empty. Callers that need persisted-context resolution should use ResolveSessionByPreference or Manager.resolveSessionName instead.
func (*State) ResolveSessionByPreference ¶ added in v0.4.0
func (s *State) ResolveSessionByPreference(name string) (*SessionRecord, error)
func (*State) SelectTab ¶ added in v0.1.7
SelectTab persists the default live tab used when --tab is omitted.
func (*State) SetDefaultContext ¶ added in v0.4.0
type Store ¶ added in v0.1.7
type Store struct {
// contains filtered or unexported fields
}
Store manages durable browser metadata with atomic writes and file locks.
func NewStore ¶ added in v0.1.7
NewStore initializes a metadata store rooted at the provided directory.
func (*Store) Update ¶ added in v0.1.7
Update takes an exclusive store lock, mutates the current state, and saves it.
func (*Store) UpdateSession ¶ added in v0.1.7
UpdateSession combines session-scoped locking with durable store mutation.
type TabList ¶ added in v0.1.7
TabList holds the result of listing tabs including the current selection.
type TabRecord ¶ added in v0.1.7
type TabRecord struct {
Name string `json:"name"`
TargetID string `json:"target_id,omitempty"`
URL string `json:"url,omitempty"`
Status TabStatus `json:"status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
LastSeenAt time.Time `json:"last_seen_at,omitempty"`
}
TabRecord stores the durable metadata for a tracked browser target.
type TabStatus ¶ added in v0.1.7
type TabStatus string
TabStatus tracks whether a named tab can be used directly.
type TargetInfo ¶ added in v0.1.7
TargetInfo holds metadata about a CDP target (browser tab).
func ListTargets ¶ added in v0.1.7
func ListTargets(ctx context.Context, debugURL string) ([]TargetInfo, error)
ListTargets enumerates page targets in a browser reachable at debugURL.
func ListTargetsHTTP ¶ added in v0.4.0
func ListTargetsHTTP(ctx context.Context, debugURL string) ([]TargetInfo, error)
ListTargetsHTTP enumerates page targets via the HTTP /json/list endpoint. This is more compatible with Electron apps and CEF-based browsers that may not support the Target.getTargets CDP command over the browser WebSocket.