Documentation
¶
Overview ¶
Package resource holds the presentation-neutral resource document a terminal resource provider returns, and the validation and sanitization Sidecar runs before any provider-supplied byte reaches view state.
Nothing here knows about Jira, HTTP, subprocesses, or the protocol envelope. The wire shapes in wire.go are the JSON the protocol document specifies; the domain types are what the rest of Sidecar is allowed to see. Every path from wire to domain goes through Sanitize*, so a caller cannot accidentally hand unvalidated provider text to a renderer.
See docs/reference/terminal-resource-provider-protocol.md.
Index ¶
- Constants
- func ClampFreshFor(seconds float64) time.Duration
- func ClampResolveTimeout(d time.Duration) time.Duration
- func DefaultRetryable(code Code) bool
- func EncodeFilters(in []FilterValue) string
- func FilterMap(in []FilterValue) map[string]string
- func RenderSafeMarkdown(r *markdown.Renderer, text string, width int) []string
- func SafeMarkdownSource(text string) string
- func SanitizeBody(s string, maxBytes int) string
- func SanitizeBodyText(s string, maxBytes int) (string, bool)
- func SanitizeDocument(w *WireDocument) (Document, *StructuralError)
- func SanitizeLine(s string, maxChars int) string
- func SanitizeURL(raw string) string
- func StripOSC(s string) string
- func StripRenderedOSC(lines []string) []string
- type Body
- type Code
- type Document
- type Error
- type Field
- type FieldKind
- type FilterValue
- type Format
- type Reference
- type Section
- type Shape
- type Status
- type StructuralError
- type TimelineItem
- type Tone
- type WireBody
- type WireDocument
- type WireError
- type WireField
- type WireSection
- type WireStatus
- type WireTimelineItem
Constants ¶
const ( // MaxResponseBytes caps one invocation's stdout. MaxResponseBytes = 256 * 1024 // MaxBodyBytes caps the sanitized body text. MaxBodyBytes = 64 * 1024 // MaxFields caps the ordered label/value grid. MaxFields = 24 // MaxFieldLabelChars and MaxFieldValueChars bound one grid cell. MaxFieldLabelChars = 64 MaxFieldValueChars = 512 // MaxTitleChars and MaxSubtitleChars bound the header lines. MaxTitleChars = 300 MaxSubtitleChars = 120 // MaxIdentityChars and MaxLocatorChars bound the two identifiers that can // reach persisted state. MaxIdentityChars = 200 MaxLocatorChars = 200 // MaxURLChars bounds sourceUrl and docsUrl. MaxURLChars = 2048 // MaxMatchersPerProvider, MaxPatternChars, MaxMatchesPerLine and // MaxProviders bound the scanner's exposure to configuration. MaxMatchersPerProvider = 32 MaxPatternChars = 512 MaxMatchesPerLine = 32 MaxProviders = 16 )
Bounds from the protocol document's "Limits" table. They are defaults the host owns: a provider must never assume anything larger. Character bounds count runes, not bytes, so a multi-byte title is truncated where a reader would expect.
const ( // MaxStatusLabelChars bounds status.label, which renders as one pill. MaxStatusLabelChars = 64 // MaxMessageChars bounds a typed error's display message. MaxMessageChars = 512 // MaxSetupHintChars bounds the copyable setup hint. MaxSetupHintChars = 512 // MaxProviderKindChars, MaxProviderNameChars and MaxProviderVersionChars // bound the informational describe strings. MaxProviderKindChars = 64 MaxProviderNameChars = 64 MaxProviderVersionChars = 64 // MaxMatcherIDChars bounds a matcher ID, which is persisted in resource // references. MaxMatcherIDChars = 64 // MaxInstanceIDChars bounds a configured provider instance ID, which is // also persisted. MaxInstanceIDChars = 64 )
The rest of the Limits table. These were host choices during the draft and are now published values the protocol document points back at, so changing one changes the contract.
const ( // MaxCollectionIDChars bounds a plugin-declared collection ID. It matches // pluginhost.MaxCollectionIDChars; this package cannot import that one, so // a test over there pins the two together. MaxCollectionIDChars = 64 // MaxQueryChars bounds a collection tab's persisted query — user-typed text // that survives a relaunch, so it is bounded on the way out as well as in. MaxQueryChars = 512 // MaxViewIDChars and MaxSortIDChars bound the declared view and sort key a // collection tab remembers. MaxViewIDChars = 64 MaxSortIDChars = 64 // MaxFilters, MaxFilterIDChars and MaxFilterValueChars bound the applied // filter set a collection tab remembers. They match // pluginhost.MaxFilters/MaxFilterIDChars/MaxFilterValueChars; this package // cannot import that one, so a test over there pins them together. MaxFilters = 8 MaxFilterIDChars = 32 MaxFilterValueChars = 64 )
Bounds on the collection shape of a Reference. They are stated here, beside the document shape's, because both shapes reach persisted state through one value and a bound that lived only in the plugin host would not be checked on the way back off disk.
const ( DescribeTimeout = 5 * time.Second DefaultResolveTimeout = 10 * time.Second MinResolveTimeout = time.Second MaxResolveTimeout = 60 * time.Second )
Timeouts. describe is local and must be fast; resolve may cross a network.
const ( DefaultFreshFor = 60 * time.Second MinFreshFor = 10 * time.Second MaxFreshFor = 15 * time.Minute )
Freshness clamps for the provider's freshForSeconds hint. Absent or zero means "no hint" and takes the default; anything else is clamped into [MinFreshFor, MaxFreshFor].
const ( // MaxSections bounds how many sections one document may carry. MaxSections = 8 // MaxTimelineItems bounds one timeline section. MaxTimelineItems = 200 // MaxSectionTitleChars bounds a section heading. MaxSectionTitleChars = 64 // MaxTimelineTitleChars and MaxTimelineTextChars bound one timeline entry. MaxTimelineTitleChars = 120 MaxTimelineTextChars = 512 )
Section limits, from the plugin protocol's Limits table.
const Protocol = "sidecar.terminal-resource/v1"
Protocol identifies the wire contract Sidecar speaks. A response that does not carry exactly this string is a transport failure, not a service failure.
Variables ¶
This section is empty.
Functions ¶
func ClampFreshFor ¶
ClampFreshFor turns a provider's freshForSeconds hint into a duration the cache will honor. Negative and absurd values are not errors; they are hints the host declines to follow.
func ClampResolveTimeout ¶
ClampResolveTimeout brings a configured timeout into range. A non-positive value means "unset" and takes the default.
func DefaultRetryable ¶
DefaultRetryable is the protocol table's default for a code. It is only ever a fallback: a response's own `retryable` field is authoritative, and the host must not infer retryability from the code when the provider stated it.
func EncodeFilters ¶ added in v1.14.0
func EncodeFilters(in []FilterValue) string
EncodeFilters renders an applied set as one canonical, comparable string: url.Values form, sorted by key and percent-escaped. It exists because contentlink.Ref travels through every open journey as a comparable value, and one more string keeps it comparable where a map would not.
func FilterMap ¶ added in v1.14.0
func FilterMap(in []FilterValue) map[string]string
FilterMap projects an applied set onto the map shape the protocol sends.
func RenderSafeMarkdown ¶
RenderSafeMarkdown renders provider body text through the shared renderer with the resource sanitizer on both sides. The renderer is passed in so this package does not own renderer lifetime or caching.
func SafeMarkdownSource ¶
SafeMarkdownSource rewrites Markdown source so that parsing it cannot produce a link destination:
- `<` is escaped, which removes raw HTML, HTML comments, and `<...>` autolinks in one move;
- `` and `![alt][ref]` collapse to their alt text;
- `[label](dest)`, `[label][ref]` and `[label][]` collapse to their label;
- link reference definitions are dropped, and a shortcut `[label]` whose definition was dropped loses its brackets;
- fenced code blocks and inline code spans are copied verbatim, since code cannot create a link and rewriting it would corrupt what it shows.
A bare URL in running text is deliberately left alone: its visible form is the URL, so rewriting it would change what the user reads. The post-render StripOSC pass is what makes it inert.
One known cosmetic limit: an indented (four-space) code block is not detected, so bracket syntax inside one is rewritten like ordinary text. That is a display wart, never a safety hole.
func SanitizeBody ¶
SanitizeBody prepares multi-line provider text and discards the truncation flag. Use SanitizeBodyText when the caller needs to tell the user the body was cut.
func SanitizeBodyText ¶
SanitizeBodyText prepares multi-line provider text: OSC removed, invalid UTF-8 replaced, CRLF normalized, every control character except newline and tab stripped, and the result bounded to maxBytes bytes on a rune boundary. It reports whether anything was cut.
func SanitizeDocument ¶
func SanitizeDocument(w *WireDocument) (Document, *StructuralError)
SanitizeDocument enforces every bound in the Limits table and returns a document safe to hand to view state.
It truncates rather than refusing. A provider is not required to pre-truncate to the host's numbers, and the numbers are deliberately not sent in the request, so a slightly-too-long document still shows the user their ticket: body text is cut at a rune boundary and marked truncated, fields past the count limit are dropped, and over-long single-line strings are cut.
The only failures are structural: a resource with no identity or no title cannot be keyed or labelled, and no amount of truncation fixes that.
func SanitizeLine ¶
SanitizeLine prepares a single-line provider string: OSC removed, invalid UTF-8 replaced, every control character stripped (including newlines and tabs, which have no meaning in a title or a field value), surrounding space trimmed, and the result bounded to maxChars runes.
func SanitizeURL ¶
SanitizeURL validates a provider-supplied URL. Only absolute http and https URLs with a host survive; everything else — file:, ssh:, data:, javascript:, scheme-relative, malformed, oversize, or control-bearing — becomes the empty string. An invalid URL is never an error: the resource simply has no source action.
func StripOSC ¶
StripOSC removes every OSC sequence from a provider-supplied string, using the same routine that protects terminal text. It fails closed: a string that still contains an OSC introducer after removal becomes empty rather than reaching a renderer.
func StripRenderedOSC ¶
StripRenderedOSC removes every OSC sequence from already-rendered lines. It is the last gate before a provider body reaches a view.
Types ¶
type Body ¶
type Body struct {
Format Format
Text string
// Truncated reports that the provider's body exceeded MaxBodyBytes and was
// cut at a rune boundary. The host shows the user what it kept and says so;
// it does not refuse a document for being long.
Truncated bool
}
Body is the optional long-form text of a resource.
type Code ¶
type Code string
Code is a stable v1 protocol error code. It is control flow; the message beside it is not.
const ( CodeNotFound Code = "not_found" CodeForbidden Code = "forbidden" CodeRateLimited Code = "rate_limited" CodeInvalidConfig Code = "invalid_config" // CodeInvalidRequest is the host having sent something this provider cannot // process: an unsupported protocol, an unknown method, missing or malformed // params, an unknown matcher id. It stays distinct from CodeInternal // because it is the host's fault, not the provider's, and no retry of the // same request will ever work. CodeInvalidRequest Code = "invalid_request" CodeInternal Code = "internal" )
The stable v1 codes. Anything else coerces to CodeInternal.
func CoerceCode ¶
CoerceCode maps an arbitrary provider string onto a known code. An empty or unrecognized code is CodeInternal: the host would rather say "something went wrong" than invent a meaning a provider did not commit to.
type Document ¶
type Document struct {
// Identity is the provider-stable canonical ID. It may differ from the
// locator that produced the lookup; the host re-keys the tab when it does.
Identity string
Title string
Subtitle string
// Status is nil when the provider supplied none.
Status *Status
Fields []Field
// Body is nil when the provider supplied none.
Body *Body
SourceURL string
// UpdatedAt is the zero time when absent or unparseable. An unparseable
// timestamp is dropped, never an error.
UpdatedAt time.Time
// FreshFor is the clamped freshness hint the cache honors.
FreshFor time.Duration
// Sections are the titled blocks under the card. Empty for every document
// a frozen-protocol provider returns.
Sections []Section
}
Document is the whole of what a provider may put on screen. Every string in it has already been through Sanitize*: valid UTF-8, bounded, control-free, and OSC-free. SourceURL, when non-empty, is a validated http/https URL.
type Error ¶
type Error struct {
Code Code
Message string
Retryable bool
// SetupHint is copyable text only.
SetupHint string
}
Error is a typed failure a provider reported, or one the host synthesized on its behalf. It is displayed, not interpreted: Message and SetupHint are text the user reads and may copy, and Sidecar never executes SetupHint.
func SanitizeError ¶
SanitizeError turns a provider's typed failure into a host one. It never fails: an empty or unknown code becomes internal.
type Field ¶
type Field struct {
Label string
Value string
// Kind is a presentation hint. M1 owns what it does with it; M0's job is
// only to carry and bound it, never to lose it.
Kind FieldKind
}
Field is one ordered label/value pair in the bounded grid.
type FieldKind ¶
type FieldKind string
FieldKind tells the host how to present a field value. It never changes validation: a timestamp that does not parse is still shown as the text the provider sent, because the alternative is silently hiding a value the user can see in the service itself.
const ( FieldKindText FieldKind = "text" FieldKindTimestamp FieldKind = "timestamp" FieldKindUser FieldKind = "user" )
Stable v1 field kinds. Anything else coerces to FieldKindText.
func CoerceFieldKind ¶
CoerceFieldKind maps an arbitrary provider string onto a known kind.
type FilterValue ¶ added in v1.14.0
FilterValue is one applied filter. Both halves are bounded because both survive a relaunch.
func DecodeFilters ¶ added in v1.14.0
func DecodeFilters(encoded string) []FilterValue
DecodeFilters is the inverse. Anything unparseable is no filters at all: a half-read applied set would send the plugin a scope nobody chose.
func FilterValues ¶ added in v1.14.0
func FilterValues(in map[string]string) []FilterValue
FilterValues is the inverse: a map becomes the sorted slice a reference carries.
func SortFilterValues ¶ added in v1.14.0
func SortFilterValues(in []FilterValue) []FilterValue
SortFilterValues returns the applied set in a stable order, dropping empty ids and keeping the LAST value for a repeated one. Callers hand it whatever they have; this is the only spelling of an applied set that reaches state.
type Format ¶
type Format string
Format is how a body's text should be interpreted.
Stable v1 formats. Anything else coerces to FormatText, which is the safer of the two: unknown markup is shown, never interpreted.
func CoerceFormat ¶
CoerceFormat maps an arbitrary provider string onto a known format.
type Reference ¶
type Reference struct {
Instance string
Matcher string
// Locator is the matched locator in ShapeMatched and the row ID in
// ShapeItem. It is empty in ShapeCollection.
Locator string
// Collection is the plugin-declared collection ID. Non-empty is what makes
// a reference one of the two plugin shapes.
Collection string
// Query, View, Sort and CursorID are a collection tab's view position,
// restored verbatim so relaunch reopens the list the user was reading
// rather than the collection's default page.
Query string
View string
Sort string
CursorID string
// Filters is the applied filter set, sorted by ID. It is a slice rather
// than a map because a reference is copied everywhere and compared as a
// value: a map would alias between two tabs and would give one state two
// spellings depending on iteration order.
Filters []FilterValue
}
Reference is what a plugin-shaped tab points at, and the only plugin-shaped value that reaches persisted state. It carries no secret: a locator such as CASH-1245 and a user-typed query are the minimum needed to restore the pane the user had open.
func (Reference) Equal ¶ added in v1.14.0
Equal reports whether two references name the same thing in the same view position. It exists because a reference carries an applied filter set, which makes the struct uncomparable with ==; every field still takes part, so this is value equality and not a looser identity test.
func (Reference) IsCollection ¶ added in v1.14.0
IsCollection reports the collection-tab shape.
func (Reference) IsPlugin ¶ added in v1.14.0
IsPlugin reports either of the two shapes that talk to a protocol plugin's list/get methods, which is what decides whether a tab renders as the shared browser or as the resource card.
func (Reference) Shape ¶ added in v1.14.0
Shape reports which alternative this reference is, or ShapeInvalid when it is none or several. Deciding it in one place is what stops each caller from growing its own idea of what "a collection tab" means.
func (Reference) Valid ¶
Valid reports whether a reference is well-formed enough to send to a plugin. It is a bounds check, not an existence check.
Exactly one shape. A reference naming both a matcher and a collection, or neither, is refused rather than sent under a guess: which one the sender meant is not something the host can infer, and inferring it is how a restored tab silently becomes a different tab.
type Section ¶ added in v1.14.0
type Section struct {
Title string
// Body is nil unless this is a body section.
Body *Body
// Fields is empty unless this is a field-grid section.
Fields []Field
// Items is empty unless this is a timeline section.
Items []TimelineItem
}
Section is one titled block under a document. It is exactly one of a body, a field grid, or a timeline — never two — because the host draws each with a different renderer and a section that claimed to be both would have to pick one anyway. Sanitization picks in the declared order rather than refusing, so a plugin that sends two still shows the user something.
func SanitizeSections ¶ added in v1.14.0
func SanitizeSections(wire []WireSection) []Section
SanitizeSections enforces every section bound and returns blocks safe to render. Like the rest of Sanitize* it truncates rather than refusing: a section past the count limit is dropped, an over-long heading is cut, and a section carrying nothing at all disappears instead of drawing an empty rule.
type Shape ¶ added in v1.14.0
type Shape int
Shape names which of a Reference's alternatives is set.
const ( // ShapeInvalid is a reference that is no shape, or more than one. ShapeInvalid Shape = iota // ShapeMatched is {instance, matcher, locator}: what a scanned span // produces and what `resolve` consumes. It is the frozen resource // protocol's only shape and is unchanged by the plugin protocol. ShapeMatched // ShapeCollection is {instance, collection} plus the user-owned view // position: what a plugin's collection tab points at. `list` consumes it. ShapeCollection // ShapeItem is {instance, collection, locator}: one row of a collection, // which `get` consumes. It is a distinct shape rather than a matched // document because a plugin row is addressed by its collection and ID, and // there is no matcher anywhere in that journey to invent. ShapeItem )
type StructuralError ¶
type StructuralError struct {
Detail string
}
StructuralError is a response that violates the protocol's shape rules — something the host can neither render nor truncate its way out of, such as a resource with no identity or no title.
It is deliberately not a *Error: the protocol classifies these as transport failures attributed to the provider's implementation, not as typed service failures the user can act on. The transport layer wraps it.
func (*StructuralError) Error ¶
func (e *StructuralError) Error() string
type TimelineItem ¶ added in v1.14.0
TimelineItem is one entry in a timeline section. When is rendered relatively and is the zero time when absent or unparseable.
type Tone ¶
type Tone string
Tone is the coarse severity of a status pill. It is presentation-neutral on purpose: the host maps it to a palette, the provider does not choose colors.
const ( ToneNeutral Tone = "neutral" ToneInfo Tone = "info" ToneSuccess Tone = "success" ToneWarning Tone = "warning" ToneDanger Tone = "danger" )
Stable v1 tones. Anything else coerces to ToneNeutral.
func CoerceTone ¶
CoerceTone maps an arbitrary provider string onto a known tone.
type WireDocument ¶
type WireDocument struct {
Identity string `json:"identity"`
Title string `json:"title"`
Subtitle string `json:"subtitle,omitempty"`
Status *WireStatus `json:"status,omitempty"`
Fields []WireField `json:"fields,omitempty"`
Body *WireBody `json:"body,omitempty"`
SourceURL string `json:"sourceUrl,omitempty"`
UpdatedAt string `json:"updatedAt,omitempty"`
FreshForSeconds float64 `json:"freshForSeconds,omitempty"`
// Sections is the plugin protocol's extension to the resource object. A
// frozen-protocol provider never sends it and a document without it renders
// exactly as it did before.
Sections []WireSection `json:"sections,omitempty"`
}
WireDocument is the `resource` object of a success response.
type WireError ¶
type WireError struct {
Code string `json:"code"`
Message string `json:"message,omitempty"`
Retryable *bool `json:"retryable,omitempty"`
SetupHint string `json:"setupHint,omitempty"`
}
WireError is the `error` object of a typed failure response. Retryable is a pointer so an omitted value takes the code's documented default rather than silently reading as false.
type WireField ¶
type WireField struct {
Label string `json:"label"`
Value string `json:"value"`
Kind string `json:"kind,omitempty"`
}
WireField is one `{label, value, kind}` triple.
type WireSection ¶ added in v1.14.0
type WireSection struct {
Title string `json:"title,omitempty"`
Body *WireBody `json:"body,omitempty"`
Fields []WireField `json:"fields,omitempty"`
Items []WireTimelineItem `json:"items,omitempty"`
}
WireSection is the `sections[]` element of a get or resolve response.
type WireStatus ¶
WireStatus is `{label, tone}`.
type WireTimelineItem ¶ added in v1.14.0
type WireTimelineItem struct {
When string `json:"when,omitempty"`
Title string `json:"title,omitempty"`
Text string `json:"text,omitempty"`
}
WireTimelineItem is `{when, title, text}`.