api

package
v0.1.1-nightly.2026060... Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultBaseURL is the production Trace API origin.
	DefaultBaseURL = "https://trace.io"

	// BaseURLEnvVar overrides the Trace API origin for local development.
	BaseURLEnvVar = "TRACE_API_BASE_URL"

	// AuthBaseURLEnvVar overrides only the auth/login origin (device flow,
	// auth-tokens management, keyring key). Falls back to BaseURLEnvVar when
	// unset, which is the right behavior for single-host deployments. Split
	// hosts (e.g. auth on us.console.partial.to, data on partial.to) set
	// both.
	AuthBaseURLEnvVar = "TRACE_AUTH_BASE_URL"
)

Variables

View Source
var ErrInsecureHTTP = errors.New("refusing to use insecure http:// base URL for authentication (use --insecure-http-auth to override)")

ErrInsecureHTTP is returned when the base URL uses HTTP without an explicit opt-in.

View Source
var OriginOnly = NormalizeOriginURL

OriginOnly is a backwards-compatible alias for NormalizeOriginURL. Callers reading raw URLs (e.g. TRACE_SEARCH_URL) and feeding them into tokenmanager.TokenRequest.Resource use this to strip path/query/fragment before the lib's stricter origin-only validator runs.

Functions

func AuthBaseURL

func AuthBaseURL() string

AuthBaseURL returns the origin used for the device-flow login, auth-token management endpoints, and the keyring key under which the bearer token is stored. TRACE_AUTH_BASE_URL takes precedence; otherwise it falls back to BaseURL() so single-host deployments keep working unchanged.

The result is canonicalised — lowercased scheme/host, default port stripped, path/query/fragment dropped, trailing slash collapsed — so the value that flows into store.SaveToken keys matches what tokenmanager.New emits after its own NormalizeOriginURL pass. Without this, a user setting TRACE_AUTH_BASE_URL=https:...443/ would log in successfully (saved under the raw form) but every subsequent data-API command would resolve "not logged in" because the manager probes under the normalised "https://auth.example.com".

func BaseURL

func BaseURL() string

BaseURL returns the effective Trace API base URL. TRACE_API_BASE_URL takes precedence over the production default.

func CheckResponse

func CheckResponse(resp *http.Response) error

CheckResponse returns an error if the response status code indicates failure. For non-2xx responses, it reads and parses the error message from the body and returns it as an *HTTPError. The caller is responsible for closing resp.Body.

func DecodeJSON

func DecodeJSON(resp *http.Response, dest any) error

DecodeJSON reads the response body and decodes it into dest. It limits the body size to protect against unbounded reads. The caller is responsible for closing resp.Body.

func IsHTTPErrorStatus

func IsHTTPErrorStatus(err error, status int) bool

IsHTTPErrorStatus reports whether err wraps an *HTTPError with the given HTTP status.

func IsSplitHost

func IsSplitHost() bool

IsSplitHost reports whether the CLI is configured for split-host — i.e. TRACE_AUTH_BASE_URL points at a different origin than the data API. Both sides are canonicalised via NormalizeOriginURL before comparison: AuthBaseURL already does this internally, but BaseURL only trims whitespace and a trailing slash, so a cosmetically- different TRACE_API_BASE_URL (uppercase host, explicit :443, path suffix) would otherwise look split when it isn't.

func NormalizeOriginURL

func NormalizeOriginURL(raw string) string

NormalizeOriginURL canonicalises a URL to a lowercase scheme+host origin with default ports stripped. Path, query, and fragment are dropped.

func RequireSecureURL

func RequireSecureURL(baseURL string) error

RequireSecureURL returns ErrInsecureHTTP if the base URL uses the http scheme. Call this before making authenticated requests unless --insecure-http-auth is set.

func ResolveURL

func ResolveURL(path string) (string, error)

ResolveURL joins an API-relative path against the effective base URL.

func ResolveURLFromBase

func ResolveURLFromBase(baseURL, path string) (string, error)

ResolveURLFromBase joins an API-relative path against an explicit base URL. Only http and https schemes are accepted.

Types

type Client

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

Client is an authenticated HTTP client for the Trace API. It attaches the bearer token to all outgoing requests via the Authorization header.

func NewClient

func NewClient(token string) *Client

NewClient creates a new authenticated API client with an explicit bearer token.

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, path string) (*http.Response, error)

Delete sends an authenticated DELETE request to the given API-relative path.

func (*Client) Get

func (c *Client) Get(ctx context.Context, path string) (*http.Response, error)

Get sends an authenticated GET request to the given API-relative path.

func (*Client) GetStream

func (c *Client) GetStream(ctx context.Context, path string, headers http.Header) (*http.Response, error)

GetStream sends an authenticated GET request with optional extra headers. Unlike Get, it does not limit response body size — the caller owns the response and must close it.

func (*Client) ListRepositories

func (c *Client) ListRepositories(ctx context.Context, sort RepositorySort) ([]Repository, error)

ListRepositories lists the authenticated user's repositories. An empty sort uses the server default.

func (*Client) ListTokens

func (c *Client) ListTokens(ctx context.Context) ([]Token, error)

ListTokens returns the authenticated user's non-expired API tokens. Backed by GET /api/v1/auth/tokens.

func (*Client) Patch

func (c *Client) Patch(ctx context.Context, path string, body any) (*http.Response, error)

Patch sends an authenticated PATCH request with a JSON body to the given API-relative path.

func (*Client) Post

func (c *Client) Post(ctx context.Context, path string, body any) (*http.Response, error)

Post sends an authenticated POST request with a JSON body to the given API-relative path.

func (*Client) Put

func (c *Client) Put(ctx context.Context, path string, body any) (*http.Response, error)

Put sends an authenticated PUT request with a JSON body to the given API-relative path.

func (*Client) RevokeCurrentToken

func (c *Client) RevokeCurrentToken(ctx context.Context) error

RevokeCurrentToken revokes the bearer token used to authenticate this client. Backed by DELETE /api/v1/auth/tokens/current.

func (*Client) RevokeToken

func (c *Client) RevokeToken(ctx context.Context, id string) error

RevokeToken revokes the API token with the given id. Backed by DELETE /api/v1/auth/tokens/{id}.

type ErrorResponse

type ErrorResponse struct {
	Error json.RawMessage `json:"error"`
}

ErrorResponse represents a standard API error response.

type HTTPError

type HTTPError struct {
	StatusCode int
	Message    string
}

HTTPError is returned by CheckResponse for non-2xx responses. Callers can use errors.As to inspect the HTTP status, or IsHTTPErrorStatus for a quick check.

func (*HTTPError) Error

func (e *HTTPError) Error() string

type RepositoriesResponse

type RepositoriesResponse struct {
	Repositories []Repository `json:"repositories"`
}

RepositoriesResponse is the envelope returned by GET /api/v1/repositories.

type Repository

type Repository struct {
	FullName        string `json:"full_name"`
	CheckpointCount int    `json:"checkpoint_count"`
}

Repository is a single entry returned by GET /api/v1/repositories. Only fields currently consumed by callers are decoded; extras are ignored.

type RepositorySort

type RepositorySort string
const (
	RepositorySortRecent RepositorySort = "recent"
	RepositorySortName   RepositorySort = "name"
)

type Token

type Token struct {
	ID         string  `json:"id"`
	UserID     string  `json:"user_id"`
	Name       string  `json:"name"`
	Scope      string  `json:"scope"`
	ExpiresAt  string  `json:"expires_at"`
	LastUsedAt *string `json:"last_used_at"`
	CreatedAt  string  `json:"created_at"`
}

Token is a single API token row returned by GET /api/v1/auth/tokens. Plaintext token values are never returned by the server — only metadata.

type TokensResponse

type TokensResponse struct {
	Tokens []Token `json:"tokens"`
}

TokensResponse is the envelope returned by GET /api/v1/auth/tokens.

type TrailCreateRequest

type TrailCreateRequest struct {
	Title      string   `json:"title"`
	Body       string   `json:"body,omitempty"`
	BranchName string   `json:"branch_name"`
	Base       string   `json:"base,omitempty"`
	Status     string   `json:"status,omitempty"`
	Assignees  []string `json:"assignees,omitempty"`
	Labels     []string `json:"labels,omitempty"`
	Priority   string   `json:"priority,omitempty"`
	Type       string   `json:"type,omitempty"`
}

TrailCreateRequest is the body for POST /api/v1/trails/:host/:owner/:repo.

type TrailCreateResponse

type TrailCreateResponse struct {
	Trail         TrailResource `json:"trail"`
	BranchCreated bool          `json:"branch_created"`
}

TrailCreateResponse is the response from POST /api/v1/trails/:org/:repo.

type TrailDetailResponse

type TrailDetailResponse struct {
	Trail       TrailResource     `json:"trail"`
	Discussion  trail.Discussion  `json:"discussion"`
	Checkpoints trail.Checkpoints `json:"checkpoints"`
}

TrailDetailResponse is the response from GET /api/v1/trails/:org/:repo/:trailId.

type TrailListResponse

type TrailListResponse struct {
	Trails        []TrailResource `json:"trails"`
	RepoFullName  string          `json:"repo_full_name"`
	DefaultBranch string          `json:"default_branch"`
	UpdatedAt     time.Time       `json:"updated_at"`
}

TrailListResponse is the response from GET /api/v1/trails/:org/:repo.

type TrailResource

type TrailResource struct {
	ID              string           `json:"id,omitempty"`
	Number          int              `json:"number,omitempty"`
	Branch          string           `json:"branch"`
	Base            string           `json:"base"`
	Title           string           `json:"title"`
	Body            string           `json:"body"`
	Status          string           `json:"status"`
	Author          *trail.Author    `json:"author"`
	Assignees       []string         `json:"assignees"`
	Labels          []string         `json:"labels"`
	Priority        string           `json:"priority,omitempty"`
	Type            string           `json:"type,omitempty"`
	Reviewers       []trail.Reviewer `json:"reviewers,omitempty"`
	CreatedAt       time.Time        `json:"created_at"`
	UpdatedAt       time.Time        `json:"updated_at"`
	MergedAt        *time.Time       `json:"merged_at,omitempty"`
	CommentCount    int              `json:"comment_count,omitempty"`
	UnresolvedCount int              `json:"unresolved_count,omitempty"`
	CheckpointCount int              `json:"checkpoint_count,omitempty"`
	CommitsAhead    int              `json:"commits_ahead,omitempty"`
}

TrailResource represents a single trail from the API.

func (*TrailResource) ToMetadata

func (r *TrailResource) ToMetadata() *trail.Metadata

ToMetadata converts a TrailResource to a trail.Metadata for display.

type TrailUpdateRequest

type TrailUpdateRequest struct {
	Branch    *string   `json:"branch,omitempty"`
	Base      *string   `json:"base,omitempty"`
	Status    *string   `json:"status,omitempty"`
	Title     *string   `json:"title,omitempty"`
	Body      *string   `json:"body,omitempty"`
	Assignees *[]string `json:"assignees,omitempty"`
	Labels    *[]string `json:"labels,omitempty"`
	Priority  *string   `json:"priority,omitempty"`
	Type      *string   `json:"type,omitempty"`
}

TrailUpdateRequest is the body for PATCH /api/v1/trails/:host/:owner/:repo/:trailId. Pointer fields distinguish "not provided" (nil) from "set to value". For slices, *[]string is used so nil means "no change" while &[]string{} means "clear".

type TrailUpdateResponse

type TrailUpdateResponse struct {
	Trail TrailResource `json:"trail"`
}

TrailUpdateResponse is the response from PATCH /api/v1/trails/:org/:repo/:trailId.

Jump to

Keyboard shortcuts

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