Documentation
¶
Overview ¶
Package types defines the core data types for api-style-spec.
These Go types are the source of truth for the api-style-spec format. JSON Schema is generated from these types using invopop/jsonschema.
Main types:
- APIStyleSpec: Root type for a style specification
- Rule: Individual style rule with enforcement and judge criteria
- LintReport: Results from deterministic linting
- Violation: A single rule violation
Index ¶
- Constants
- func DefaultConformanceLevels() map[string]ConformanceLevel
- type APIStyleSpec
- type CasingRules
- type Category
- type ConformanceLevel
- type Enforcement
- type EnforcementOptions
- type EnforcementType
- type Examples
- type Exception
- type ExceptionScope
- type FileLintReport
- type ForbiddenTerm
- type GivenPaths
- type JudgeCriteria
- type Lexicon
- type LintReport
- type MultiLintReport
- type Reference
- type ReportMetadata
- type ReportStatus
- type Rule
- type RuleOverride
- type Scope
- type Severity
- type SpecMetadata
- type SpectralThen
- type Status
- type Violation
- type ViolationSummary
Constants ¶
const ( ReportStatusPass = StatusPass ReportStatusFail = StatusFail )
Deprecated aliases for backwards compatibility.
Variables ¶
This section is empty.
Functions ¶
func DefaultConformanceLevels ¶
func DefaultConformanceLevels() map[string]ConformanceLevel
DefaultConformanceLevels returns the standard bronze/silver/gold levels.
Types ¶
type APIStyleSpec ¶
type APIStyleSpec struct {
// Schema is the JSON Schema URI for validation.
Schema string `json:"$schema,omitempty"`
// Version is the semantic version of this specification.
Version string `json:"version"`
// Name is a unique identifier for this style spec.
Name string `json:"name"`
// Description provides context about this style specification.
Description string `json:"description,omitempty"`
// Extends lists parent profiles to inherit rules from.
Extends []string `json:"extends,omitempty"`
// Rules are the style rules defined in this specification.
Rules []Rule `json:"rules"`
// Overrides modify inherited rules from extended profiles.
Overrides map[string]RuleOverride `json:"overrides,omitempty"`
// Lexicon defines approved and forbidden terminology.
Lexicon *Lexicon `json:"lexicon,omitempty"`
// ConformanceLevels define graduated compliance tiers.
ConformanceLevels map[string]ConformanceLevel `json:"conformanceLevels,omitempty"`
// Exceptions are approved rule waivers.
Exceptions []Exception `json:"exceptions,omitempty"`
// Categories defines available rule categories with metadata.
Categories []Category `json:"categories,omitempty"`
// Metadata contains additional specification information.
Metadata *SpecMetadata `json:"metadata,omitempty"`
}
APIStyleSpec is the root type for an API style specification. This is the source of truth from which JSON Schema is generated.
type CasingRules ¶
type CasingRules struct {
// Paths defines casing for URL paths (e.g., "kebab-case").
Paths string `json:"paths,omitempty"`
// Parameters defines casing for query/path parameters.
Parameters string `json:"parameters,omitempty"`
// Properties defines casing for JSON properties.
Properties string `json:"properties,omitempty"`
// Headers defines casing for HTTP headers.
Headers string `json:"headers,omitempty"`
}
CasingRules defines naming conventions for different API elements.
type Category ¶
type Category struct {
// ID is the category identifier (e.g., "uri-design").
ID string `json:"id"`
// Title is the display name.
Title string `json:"title"`
// Description explains what this category covers.
Description string `json:"description,omitempty"`
// Order determines display ordering (lower = first).
Order int `json:"order,omitempty"`
}
Category defines a grouping for related rules.
type ConformanceLevel ¶
type ConformanceLevel struct {
// Description explains what this level represents.
Description string `json:"description,omitempty"`
// RequiredCategories lists category IDs that must pass.
RequiredCategories []string `json:"requiredCategories,omitempty"`
// RequiredRules lists specific rule IDs that must pass.
RequiredRules []string `json:"requiredRules,omitempty"`
// MaxErrors is the maximum allowed error-severity violations.
MaxErrors int `json:"maxErrors"`
// MaxWarnings is the maximum allowed warning-severity violations.
MaxWarnings int `json:"maxWarnings"`
// Extends inherits requirements from another level.
Extends string `json:"extends,omitempty"`
}
ConformanceLevel defines a graduated compliance tier.
type Enforcement ¶
type Enforcement struct {
// Type is the enforcement mechanism.
Type EnforcementType `json:"type"`
// Function is the Spectral function name (for type=spectral).
Function string `json:"function,omitempty"`
// Options are function-specific configuration options.
Options *EnforcementOptions `json:"options,omitempty"`
// Given is the JSONPath expression(s) for targeting nodes (Spectral-style).
// Can be a single string or array of strings.
Given *GivenPaths `json:"given,omitempty"`
// Then defines the assertion to apply (Spectral-style).
Then *SpectralThen `json:"then,omitempty"`
// Pattern is the regex pattern (for type=regex).
Pattern string `json:"pattern,omitempty"`
// CustomFunction is the name of a custom Go function (for type=custom).
CustomFunction string `json:"customFunction,omitempty"`
}
Enforcement defines deterministic rule checking configuration.
type EnforcementOptions ¶
type EnforcementOptions struct {
// Match is a regex pattern to match against (for pattern function).
Match string `json:"match,omitempty"`
// NotMatch is a regex pattern that should not match.
NotMatch string `json:"notMatch,omitempty"`
// Min is a minimum value (for length function).
Min *int `json:"min,omitempty"`
// Max is a maximum value (for length function).
Max *int `json:"max,omitempty"`
// Values is a list of allowed values (for enumeration function).
Values []string `json:"values,omitempty"`
// Type specifies the expected casing type (for casing function).
// Values: flat, camel, pascal, kebab, cobol, snake, macro
Type string `json:"type,omitempty"`
// Separator is used for casing validation.
Separator string `json:"separator,omitempty"`
// Schema is a JSON Schema for validation (for schema function).
Schema string `json:"schema,omitempty"`
}
EnforcementOptions contains common options for enforcement functions.
type EnforcementType ¶
type EnforcementType string
EnforcementType defines how a rule is enforced.
const ( // EnforcementSpectral uses Spectral/vacuum for linting. EnforcementSpectral EnforcementType = "spectral" // EnforcementCustom uses a custom Go function. EnforcementCustom EnforcementType = "custom" // EnforcementRegex uses regular expression matching. EnforcementRegex EnforcementType = "regex" // EnforcementNone means the rule is LLM-only (no deterministic check). EnforcementNone EnforcementType = "none" )
type Examples ¶
type Examples struct {
// Good shows correct usage patterns.
Good []string `json:"good,omitempty"`
// Bad shows incorrect usage patterns.
Bad []string `json:"bad,omitempty"`
}
Examples provides good and bad usage patterns for a rule.
type Exception ¶
type Exception struct {
// ID is a unique identifier for this exception.
ID string `json:"id"`
// RuleID is the rule being waived.
RuleID string `json:"ruleId"`
// AppliesTo defines the scope of the exception.
AppliesTo *ExceptionScope `json:"appliesTo,omitempty"`
// Reason explains why this exception was granted.
Reason string `json:"reason"`
// ApprovedBy identifies who approved the exception.
ApprovedBy string `json:"approvedBy,omitempty"`
// ApprovedOn is when the exception was granted.
ApprovedOn *time.Time `json:"approvedOn,omitempty"`
// ExpiresOn is when the exception expires (nil = never).
ExpiresOn *time.Time `json:"expiresOn,omitempty"`
// Ticket links to an issue tracker for tracking.
Ticket string `json:"ticket,omitempty"`
}
Exception defines an approved waiver for a specific rule violation.
type ExceptionScope ¶
type ExceptionScope struct {
// API limits the exception to a specific API name.
API string `json:"api,omitempty"`
// Path limits the exception to specific paths (glob supported).
Path string `json:"path,omitempty"`
// Operation limits the exception to specific operations.
Operation string `json:"operation,omitempty"`
// Paths lists multiple paths (alternative to single Path).
Paths []string `json:"paths,omitempty"`
}
ExceptionScope defines where an exception applies.
type FileLintReport ¶ added in v0.2.0
type FileLintReport struct {
// File is the path to the linted specification.
File string `json:"file"`
// Report contains the lint results for this file.
*LintReport
}
FileLintReport wraps a LintReport with file path information.
type ForbiddenTerm ¶
type ForbiddenTerm struct {
// Term is the forbidden word or phrase.
Term string `json:"term"`
// ReplaceWith suggests the preferred alternative.
ReplaceWith string `json:"replaceWith,omitempty"`
// Reason explains why this term is forbidden.
Reason string `json:"reason,omitempty"`
}
ForbiddenTerm defines a term that should not be used.
type GivenPaths ¶
type GivenPaths struct {
// Paths contains one or more JSONPath expressions.
Paths []string `json:"paths"`
}
GivenPaths represents JSONPath expressions for Spectral rules. Can be marshaled as a single string or array of strings.
func NewGivenPath ¶
func NewGivenPath(path string) *GivenPaths
NewGivenPath creates a GivenPaths with a single path.
func NewGivenPaths ¶
func NewGivenPaths(paths ...string) *GivenPaths
NewGivenPaths creates a GivenPaths with multiple paths.
type JudgeCriteria ¶
type JudgeCriteria struct {
// Prompt is the evaluation instruction for the LLM.
Prompt string `json:"prompt"`
// Weight influences scoring (0.0-1.0, default 1.0).
Weight float64 `json:"weight,omitempty"`
// RequiresContext indicates if broader context is needed for evaluation.
RequiresContext bool `json:"requiresContext,omitempty"`
// Category overrides the rule's category for evaluation grouping.
Category string `json:"category,omitempty"`
}
JudgeCriteria defines LLM evaluation parameters for a rule.
type Lexicon ¶
type Lexicon struct {
// Approved lists terms that should be used.
Approved []string `json:"approved,omitempty"`
// Forbidden lists terms that should not be used, with replacements.
Forbidden []ForbiddenTerm `json:"forbidden,omitempty"`
// Aliases maps equivalent terms.
Aliases map[string]string `json:"aliases,omitempty"`
// CasingRules defines naming conventions for different contexts.
CasingRules *CasingRules `json:"casingRules,omitempty"`
}
Lexicon defines approved and forbidden terminology for API design.
type LintReport ¶
type LintReport struct {
// Status is the overall pass/fail result.
Status ReportStatus `json:"status"`
// ConformanceLevel is the highest level achieved (if levels are defined).
ConformanceLevel string `json:"conformanceLevel,omitempty"`
// Summary provides violation counts by severity.
Summary *ViolationSummary `json:"summary"`
// Violations lists all findings.
Violations []Violation `json:"violations"`
// IgnoredViolations lists violations that were suppressed by exceptions.
IgnoredViolations []Violation `json:"ignoredViolations,omitempty"`
// Metadata includes timing, versions, and other context.
Metadata *ReportMetadata `json:"metadata,omitempty"`
}
LintReport contains the results of deterministic linting.
func NewLintReport ¶
func NewLintReport() *LintReport
NewLintReport creates a new LintReport with initialized fields.
func (*LintReport) AddViolation ¶
func (r *LintReport) AddViolation(v Violation)
AddViolation adds a violation and updates the summary.
func (*LintReport) HasBlockingViolations ¶
func (r *LintReport) HasBlockingViolations() bool
HasBlockingViolations returns true if there are error-level violations.
type MultiLintReport ¶ added in v0.2.0
type MultiLintReport struct {
// Status is the overall pass/fail result across all files.
Status Status `json:"status"`
// Summary provides aggregate violation counts across all files.
Summary *ViolationSummary `json:"summary"`
// FileReports contains individual reports for each file.
FileReports []FileLintReport `json:"fileReports"`
// Metadata includes timing, versions, and other context.
Metadata *ReportMetadata `json:"metadata,omitempty"`
}
MultiLintReport contains results from linting multiple files.
func NewMultiLintReport ¶ added in v0.2.0
func NewMultiLintReport() *MultiLintReport
NewMultiLintReport creates a new MultiLintReport with initialized fields.
func (*MultiLintReport) AddFileReport ¶ added in v0.2.0
func (r *MultiLintReport) AddFileReport(file string, report *LintReport)
AddFileReport adds a file report and updates the aggregate summary.
func (*MultiLintReport) FailedFileCount ¶ added in v0.2.0
func (r *MultiLintReport) FailedFileCount() int
FailedFileCount returns the number of files that failed linting.
func (*MultiLintReport) FileCount ¶ added in v0.2.0
func (r *MultiLintReport) FileCount() int
FileCount returns the number of files that were linted.
func (*MultiLintReport) HasBlockingViolations ¶ added in v0.2.0
func (r *MultiLintReport) HasBlockingViolations() bool
HasBlockingViolations returns true if any file has error-level violations.
type Reference ¶
type Reference struct {
// Title is the display text for the reference.
Title string `json:"title"`
// URL is the link to the external resource.
URL string `json:"url"`
}
Reference links to external documentation.
type ReportMetadata ¶
type ReportMetadata struct {
// SpecFile is the path to the linted specification.
SpecFile string `json:"specFile,omitempty"`
// SpecVersion is the OpenAPI version of the spec.
SpecVersion string `json:"specVersion,omitempty"`
// Profile is the style profile used.
Profile string `json:"profile,omitempty"`
// ProfileVersion is the version of the profile.
ProfileVersion string `json:"profileVersion,omitempty"`
// Duration is how long linting took.
Duration time.Duration `json:"duration,omitempty"`
// DurationMS is duration in milliseconds (for JSON serialization).
DurationMS int64 `json:"durationMs,omitempty"`
// Timestamp is when linting was performed.
Timestamp time.Time `json:"timestamp"`
// ToolVersion is the api-style-spec version.
ToolVersion string `json:"toolVersion,omitempty"`
// RulesEvaluated is the count of rules that were checked.
RulesEvaluated int `json:"rulesEvaluated,omitempty"`
}
ReportMetadata contains context about the linting run.
type ReportStatus ¶
type ReportStatus = Status
ReportStatus is an alias for Status (deprecated, use Status).
type Rule ¶
type Rule struct {
// ID is a unique identifier for the rule (e.g., "URI-001").
ID string `json:"id"`
// Title is a short, descriptive name for the rule.
Title string `json:"title"`
// Category groups related rules (e.g., "uri-design", "naming", "security").
Category string `json:"category"`
// Severity indicates the importance of violations.
Severity Severity `json:"severity"`
// Scope defines what part of the spec this rule applies to.
Scope Scope `json:"scope,omitempty"`
// Rationale explains why this rule exists and its benefits.
Rationale string `json:"rationale,omitempty"`
// Examples provides good and bad usage patterns.
Examples *Examples `json:"examples,omitempty"`
// Enforcement defines deterministic checking configuration.
Enforcement *Enforcement `json:"enforcement,omitempty"`
// Judge defines LLM evaluation criteria for this rule.
Judge *JudgeCriteria `json:"judge,omitempty"`
// References links to external documentation.
References []Reference `json:"references,omitempty"`
// Tags are labels for filtering and grouping rules.
Tags []string `json:"tags,omitempty"`
// Recommended indicates if this rule is part of the recommended set.
Recommended bool `json:"recommended,omitempty"`
}
Rule defines a single API style guideline.
type RuleOverride ¶
type RuleOverride struct {
// Severity overrides the rule's severity.
Severity *Severity `json:"severity,omitempty"`
// Disabled completely disables the rule.
Disabled bool `json:"disabled,omitempty"`
// Rationale provides context for the override.
Rationale string `json:"rationale,omitempty"`
}
RuleOverride modifies an inherited rule.
type Scope ¶
type Scope string
Scope defines what part of an OpenAPI specification a rule applies to.
const ( // ScopePath applies to path definitions. ScopePath Scope = "path" // ScopeOperation applies to individual operations (GET, POST, etc.). ScopeOperation Scope = "operation" // ScopeParameter applies to parameters. ScopeParameter Scope = "parameter" // ScopeSchema applies to schema definitions. ScopeSchema Scope = "schema" // ScopeResponse applies to response definitions. ScopeResponse Scope = "response" // ScopeInfo applies to the info section. ScopeInfo Scope = "info" // ScopeSecurity applies to security definitions. ScopeSecurity Scope = "security" // ScopeGlobal applies to the entire specification. ScopeGlobal Scope = "global" )
type Severity ¶
type Severity string
Severity represents the severity level of a rule violation.
const ( // SeverityError indicates a critical violation that should block approval. SeverityError Severity = "error" // SeverityWarn indicates a significant issue that should be addressed. SeverityWarn Severity = "warn" // SeverityInfo indicates an informational finding. SeverityInfo Severity = "info" // SeverityHint indicates a suggestion for improvement. SeverityHint Severity = "hint" )
func (Severity) IsBlocking ¶
IsBlocking returns true if this severity level blocks approval.
type SpecMetadata ¶
type SpecMetadata struct {
// Author is the creator of this specification.
Author string `json:"author,omitempty"`
// License is the license for this specification.
License string `json:"license,omitempty"`
// Repository is the source repository URL.
Repository string `json:"repository,omitempty"`
// Website is a documentation website URL.
Website string `json:"website,omitempty"`
// URL is an alias for website/repository for external reference.
URL string `json:"url,omitempty"`
// Contact is contact information.
Contact string `json:"contact,omitempty"`
// LastUpdated is when the specification was last modified.
LastUpdated string `json:"lastUpdated,omitempty"`
}
SpecMetadata contains additional specification information.
type SpectralThen ¶
type SpectralThen struct {
// Field is the field to check within the matched node.
Field string `json:"field,omitempty"`
// Function is the assertion function to apply.
Function string `json:"function,omitempty"`
// FunctionOptions are options for the function.
FunctionOptions map[string]string `json:"functionOptions,omitempty"`
}
SpectralThen defines a Spectral-compatible assertion.
type Violation ¶
type Violation struct {
// RuleID is the identifier of the violated rule.
RuleID string `json:"ruleId"`
// Severity indicates the importance of this violation.
Severity Severity `json:"severity"`
// Message describes what went wrong.
Message string `json:"message"`
// Path is the JSONPath to the violation location.
Path string `json:"path"`
// Line is the line number in the source file (1-indexed).
Line int `json:"line,omitempty"`
// Column is the column number in the source file (1-indexed).
Column int `json:"column,omitempty"`
// EndLine is the ending line for multi-line issues.
EndLine int `json:"endLine,omitempty"`
// EndColumn is the ending column for multi-line issues.
EndColumn int `json:"endColumn,omitempty"`
// Suggestion provides guidance for fixing the violation.
Suggestion string `json:"suggestion,omitempty"`
// RuleTitle is the human-readable rule name.
RuleTitle string `json:"ruleTitle,omitempty"`
// Category is the rule's category.
Category string `json:"category,omitempty"`
}
Violation represents a single rule violation.
type ViolationSummary ¶
type ViolationSummary struct {
// Errors is the count of error-severity violations.
Errors int `json:"errors"`
// Warnings is the count of warning-severity violations.
Warnings int `json:"warnings"`
// Infos is the count of info-severity violations.
Infos int `json:"infos"`
// Hints is the count of hint-severity violations.
Hints int `json:"hints"`
// Total is the sum of all violations.
Total int `json:"total"`
}
ViolationSummary counts violations by severity.