Documentation
¶
Overview ¶
Package static exports a Fletch (or plain router) app as a static site.
Every page of a Fletch app is an http.Handler, so the exporter renders the app in process, captures the responses, and writes them out with the host files a static host needs: redirects, headers, and a 404 page. Per-request CSP nonces become SHA-256 hashes, and static-safety checks (S001 to S016) catch pages that cannot work without a server.
The package does not import the root fletch module; it takes any App, which *fletch.App satisfies.
Index ¶
- Constants
- Variables
- func BasePath(ctx context.Context) string
- func Describe(ctx context.Context, opts ...PageOpt)
- func Drafts(ctx context.Context) bool
- func Exporting(ctx context.Context) bool
- func FromFS(fsys fs.FS) http.Handler
- func InvalidateOn(ctx context.Context, sub Subscriber, pre *Prerenderer) (cancel func(), err error)
- func NetlifyConfig(dir string) string
- func PagesWorkflow(outDir string) string
- func Preview(fsys fs.FS, o PreviewOptions) (http.Handler, error)
- func WranglerAssets(dir string, slash SlashPolicy) string
- func WranglerProxy(dir string, slash SlashPolicy, proxy []string) string
- func WriteNetlifyConfig(projectDir, outDir string) (file string, created bool, err error)
- func WritePagesWorkflow(projectDir, outDir string) (file string, created bool, err error)
- func WriteWranglerConfig(projectDir, name, compatDate, outDir string, slash SlashPolicy, ...) (file string, created bool, err error)
- type App
- type BackendOption
- type Built
- type Check
- type Diagnostic
- type ExportOptions
- type File
- type FileReport
- type Header
- type HeaderRule
- type Invalidation
- type Limits
- type Manifest
- type ManifestLive
- type Option
- func Assets(dir string) Option
- func Backend(url string, opts ...BackendOption) Option
- func Base(path string) Option
- func CSPStrict() Option
- func Checks(checks ...Check) Option
- func Exclude(globs ...string) Option
- func NotFound(path string) Option
- func Page(path string) Option
- func Paths(route string, fn PathsFunc) Option
- func Public(dir string) Option
- func Redirect(from, to string, status int) Option
- func Rewrite(from, to string) Option
- func Search(opts ...search.Option) Option
- func TrailingSlash(p SlashPolicy) Option
- func URL(u string) Option
- type PageOpt
- type PageReport
- type Params
- type PathsFunc
- type PrerenderError
- type PrerenderOption
- func Revalidate(d time.Duration) PrerenderOption
- func Routes(globs ...string) PrerenderOption
- func SkipCookies(names ...string) PrerenderOption
- func SkipRequest(fn func(*http.Request) bool) PrerenderOption
- func Warm(m WarmMode) PrerenderOption
- func WithErrorReporter(fn func(path string, err error)) PrerenderOption
- type Prerenderer
- type PreviewOptions
- type RedirectRule
- type Report
- type ShellMode
- type Site
- type SlashPolicy
- type Subscriber
- type Target
- type Timings
- type Topology
- type TopologyShell
- type VerifyOptions
- type VerifyReport
- type WarmMode
Constants ¶
const ( CodeLive = "S001" // a Live route or data-f-live markup CodeCSRF = "S002" // a same-origin POST form with a CSRF field CodeSetCookie = "S003" // Set-Cookie on a response CodeStatus = "S004" // an unexpected status or a bad 404 probe CodeBrokenLink = "S005" // a broken link or a missing #fragment CodeNondeterministic = "S006" // two renders differ (--verify) CodeInlineHandler = "S007" // on*= or style= under a hash CSP CodeScriptOrigin = "S008" // a cross-origin script origin was allowlisted CodePrivateCache = "S009" // private/no-store or Vary: Cookie CodeBaseLiteral = "S010" // a root-relative URL in inline JS with Base set CodePathCollision = "S011" // two URLs on one output file CodeHostLimit = "S012" // a host limit or a host-file merge conflict CodeNonceReuse = "S013" // the nonce appears outside nonce attributes CodeHeaderLost = "S014" // the target cannot express a header CodeContentType = "S015" // Content-Type and file extension disagree CodeNotPublic = "S016" // an exported or linked page needs auth or is excluded // Split deploy (static.Backend): export-time proofs. CodeSplitConfig = "S017" // a split-deploy option names nothing or is malformed CodeLiveEndpoint = "S018" // the backend does not serve a shell's Live endpoint or contract for the site CodeCORS = "S019" // the Live endpoint's CORS preflight does not allow the site CodeRewritten = "S020" // links and forms were rewritten to the backend (info) CodeCrossSite = "S021" // Credentials with a backend on another site CodeTargetSplit = "S022" // the target cannot proxy or rewrite as asked CodeShellAuth = "S023" // a Live shell's Mount needs a user or redirects CodeSplitCSP = "S024" // CSP sources the backend needs (added, or missing under CSPStrict) CodeBackendURL = "S025" // the backend URL is unusable CodeSplitConflict = "S026" // a path is both Dynamic and exported or rewritten CodeShellLeak = "S027" // a shell carries a session id or CSRF token // Split deploy: network verification (verify-backend). CodeProtocol = "S031" // the backend speaks another Live protocol CodeBuildSkew = "S032" // the backend runs another build (warning; error with --require-build-match) CodeTemplate = "S033" // the backend serves another template than the shell was built from CodeLiveProbe = "S034" // the Live probe failed over WebSocket (and SSE) CodeProxyRules = "S035" // the site does not proxy to the backend CodeUnreachable = "S036" // the backend is down or not ready )
Diagnostic codes. Each is documented in docs/static.md.
const ( CSPNone = "none" CSPGlobal = "global" CSPPerPath = "per-path" CSPMeta = "meta" )
CSP emission strategies, recorded in the Report.
const ( LivePrefix = "/_fletch/live" ContractPath = "/_fletch/contract" // ManifestFile is where a split export describes itself, relative to // the site root. verify-backend and the preview read it. ManifestFile = "_fletch/static.json" )
Paths a Fletch backend owns in every split topology.
const ( // TopologySeparate serves the site and the backend from two origins; // shells join the backend's absolute Live endpoint. TopologySeparate = "separate" // TopologyProxy has the static host proxy Dynamic paths, Live // endpoints and the contract to the backend, so everything is // same-origin. TopologyProxy = "proxy" // TopologyMixed proxies HTTP paths but joins Live on the backend // origin (LiveDirect). TopologyMixed = "mixed" )
Topologies of a split deploy, as recorded in the Manifest.
const LastExportFile = ".fletch/static/last-export.json"
LastExportFile is where the export command keeps a copy of its Report, outside the output directory, for the dev dashboard and agents.
const WorkerFile = "fletch-proxy.js"
WorkerFile is the Cloudflare Worker a proxied split export writes next to its assets. .assetsignore keeps it from being uploaded as an asset.
Variables ¶
var ErrExport = errors.New("static: export has errors")
ErrExport is wrapped by the error Export returns when an error diagnostic not named in ExportOptions.Allow was found. The Report lists them.
var ErrVerify = errors.New("static: backend verification failed")
ErrVerify is wrapped by the error VerifyBackend returns when an error diagnostic was found.
var TargetNames = []string{"cloudflare", "vercel", "netlify", "github-pages", "plain"}
TargetNames lists the built-in targets in the order commands show them.
Functions ¶
func BasePath ¶
BasePath returns the export's base path, such as "/repo", or "" outside an export. Code that builds URLs inside inline scripts uses it, because the base rewrite only reaches HTML attributes and CSS.
func Describe ¶
Describe records facts about the page being rendered for the sitemap and diagnostics. Outside an export it does nothing.
func Exporting ¶
Exporting reports whether ctx belongs to a request made by an export, so a handler can skip side effects such as analytics counters.
func FromFS ¶
FromFS serves an export written by the plain target (fletch export --target plain), usually embedded in the binary:
//go:embed all:dist
var dist embed.FS
site, _ := fs.Sub(dist, "dist")
mux.Handle("/", static.FromFS(site))
It reads static-manifest.json for clean URLs, redirects and header rules, answers 404 with 404.html, sends a strong ETag with 304 on a match, and serves Brotli or gzip from a .br/.gz sibling or compressed once in memory. Without a manifest it maps /x to x, x.html or x/index.html. FromFS panics if the manifest is not valid JSON, as the embedded export is fixed at build time.
func InvalidateOn ¶
func InvalidateOn(ctx context.Context, sub Subscriber, pre *Prerenderer) (cancel func(), err error)
InvalidateOn calls pre.Invalidate for every message sub delivers, so a publish on one node drops the snapshots on all of them. It runs until cancel is called or ctx is done.
func NetlifyConfig ¶
NetlifyConfig is the netlify.toml snippet for an export into dir.
func PagesWorkflow ¶
PagesWorkflow is the GitHub Actions workflow that exports the site with Go alone and deploys it to GitHub Pages.
func Preview ¶
Preview returns a handler that serves an export the way its host would: Cloudflare and Netlify run _redirects, _headers and their URL handling; Vercel runs .vercel/output/config.json (or vercel.json); GitHub Pages serves files, clean .html URLs and the redirect stubs; plain serves files. All answer misses with 404.html. It is the production behavior, not a plain file server.
func WranglerAssets ¶
func WranglerAssets(dir string, slash SlashPolicy) string
WranglerAssets is the wrangler.jsonc assets block for an export into dir.
func WranglerProxy ¶ added in v0.2.0
func WranglerProxy(dir string, slash SlashPolicy, proxy []string) string
WranglerProxy is the wrangler.jsonc block for a proxied split export into dir: the generated Worker as main, the assets binding it falls back to, and run_worker_first for the proxied globs.
func WriteNetlifyConfig ¶
WriteNetlifyConfig creates projectDir/netlify.toml with the publish directory. It never overwrites a file: created is false when one exists.
func WritePagesWorkflow ¶
WritePagesWorkflow creates projectDir/.github/workflows/pages.yml. It never overwrites a file: created is false when one exists.
func WriteWranglerConfig ¶
func WriteWranglerConfig(projectDir, name, compatDate, outDir string, slash SlashPolicy, proxy ...string) (file string, created bool, err error)
WriteWranglerConfig creates projectDir/wrangler.jsonc with the assets block, or with WranglerProxy when proxy lists the globs of a proxied split export. It never overwrites a file: created is false when one exists.
Types ¶
type App ¶
App is what the exporter renders. *fletch.App satisfies it, and so does any type that wraps a *router.Router.
type BackendOption ¶ added in v0.2.0
type BackendOption func(*backendConfig)
BackendOption configures Backend.
func Credentials ¶ added in v0.2.0
func Credentials() BackendOption
Credentials makes Live and backend requests carry the user's cookies. Lax cookies reach only a same-site backend, so a backend on another site is S021 unless Proxy is set.
func Dynamic ¶ added in v0.2.0
func Dynamic(globs ...string) BackendOption
Dynamic declares backend-owned paths: they are not exported, links to them are legal (and point at the backend unless proxied), and each must match a backend route (S016). A glob ending in /* matches everything below it.
func LiveDirect ¶ added in v0.2.0
func LiveDirect() BackendOption
LiveDirect keeps Live on the backend origin under Proxy, for hosts that proxy HTTP but not WebSockets.
func LiveShell ¶ added in v0.2.0
func LiveShell(route string, mode ShellMode) BackendOption
LiveShell sets the shell mode of one Live route, by name or path. Default Render.
func Proxy ¶ added in v0.2.0
func Proxy(prefixes ...string) BackendOption
Proxy has the static host proxy backend paths, so the browser sees one origin. With no prefixes it proxies the Dynamic globs; Live endpoints and the contract are always added (Live unless LiveDirect).
type Built ¶
type Built struct {
URL string `json:"url"`
Base string `json:"base,omitempty"`
Slash SlashPolicy `json:"-"`
Files []File `json:"files"`
Redirects []RedirectRule `json:"redirects"`
Headers []HeaderRule `json:"headers"`
// CNAME is the custom domain a GitHub Pages export writes to CNAME.
CNAME string `json:"cname,omitempty"`
// Rewrites are static.Rewrite rules: status-200 host rewrites.
Rewrites []RedirectRule `json:"rewrites,omitempty"`
// Split describes the backend of a split deploy, and the proxy rules
// a target writes for it. It is nil without static.Backend.
Split *Manifest `json:"split,omitempty"`
// HostFiles holds public/_redirects and public/_headers, which a target
// merges with its generated rules or copies verbatim.
HostFiles map[string][]byte `json:"-"`
}
Built is a finished export, ready for a Target.
type Check ¶
type Check func(ctx context.Context, s *Built) []Diagnostic
Check is an extra check run over the finished export, such as an SEO preset. Its diagnostics are reported like the built-in ones.
type Diagnostic ¶
type Diagnostic struct {
ax.Diagnostic
// Route is the route name and pattern, such as "docs.show /docs/{slug...}".
Route string `json:"route,omitempty"`
// Path is the URL path the problem was found on.
Path string `json:"path,omitempty"`
// Allowed marks an error that --allow turned into a non-failing one.
Allowed bool `json:"allowed,omitempty"`
}
Diagnostic is an ax.Diagnostic with the route and URL path it is about.
func (Diagnostic) Failing ¶
func (d Diagnostic) Failing() bool
Failing reports whether d fails an export.
type ExportOptions ¶
type ExportOptions struct {
// Out is the output directory. Default "dist".
Out string
// Target writes the host files. Default Cloudflare().
Target Target
// URL overrides the URL option and APP_URL.
URL string
// Base overrides the Base option.
Base string
// Host exports the routes of this Host group too, and sends it as the
// request Host.
Host string
// Drafts makes Drafts(ctx) true in handlers.
Drafts bool
// NoIndex writes a Disallow robots.txt and an X-Robots-Tag header, for
// preview deploys.
NoIndex bool
// Verify renders everything twice and reports differences (S006).
Verify bool
// Allow lists codes whose errors do not fail the export.
Allow []string
// DryRun builds and checks but writes nothing.
DryRun bool
// PageTimeout bounds one render. Default 30s.
PageTimeout time.Duration
// Workers is the number of concurrent renders. Default GOMAXPROCS.
Workers int
// VercelJSON makes the vercel target write plain files and a
// vercel.json, for projects that Vercel builds from Git, instead of the
// Build Output API layout.
VercelJSON bool
// CNAME is the custom domain the github-pages target writes to CNAME.
// Default: the host of the site URL, unless it is a github.io, localhost
// or loopback address.
CNAME string
// Backend overrides the static.Backend URL and turns split mode on
// when the Site declares no Backend.
Backend string
// VerifyBackend checks the deployed backend over the network, as
// VerifyBackend does, before anything is written; its diagnostics join
// the Report.
VerifyBackend bool
// RequireBuildMatch makes a backend on another build an error (S032)
// under VerifyBackend.
RequireBuildMatch bool
// Pagefind runs the pagefind binary, which must be on PATH, over the
// written site before it replaces the previous export. It writes its own
// index to /pagefind/, next to any static.Search index.
Pagefind bool
}
ExportOptions are the per-run settings, usually from the export command's flags. Zero values take the Site's options or the defaults.
type File ¶
type File struct {
// Path is slash-separated and relative to the output root, such as
// "docs/intro.html".
Path string `json:"path"`
// URL is the URL path the file answers, such as "/docs/intro".
URL string `json:"url"`
ContentType string `json:"content_type,omitempty"`
// Kind is "page", "file", "asset", "public", "generated" or "404".
Kind string `json:"kind"`
Route string `json:"route,omitempty"`
Data []byte `json:"-"`
}
File is one exported file.
type FileReport ¶
type FileReport struct {
Path string `json:"path"`
Kind string `json:"kind"`
Bytes int `json:"bytes"`
SHA256 string `json:"sha256"`
}
FileReport is one written file.
type HeaderRule ¶
HeaderRule sets headers on every URL that matches Path; a * matches the rest of the path.
type Invalidation ¶
type Invalidation struct {
Paths []string `json:"paths"`
}
Invalidation is the message InvalidateOn acts on.
type Limits ¶
type Limits struct {
// Headers reports whether the host sets response headers from a file.
Headers bool `json:"headers"`
// Redirects reports whether the host runs redirect rules from a file.
Redirects bool `json:"redirects"`
MaxStaticRedirects int `json:"max_static_redirects,omitempty"`
MaxDynamicRedirects int `json:"max_dynamic_redirects,omitempty"`
MaxRedirectLine int `json:"max_redirect_line,omitempty"`
MaxHeaderRules int `json:"max_header_rules,omitempty"`
MaxHeaderLine int `json:"max_header_line,omitempty"`
// RedirectPages reports whether the host gets redirects as HTML stub
// pages instead of rules.
RedirectPages bool `json:"redirect_pages,omitempty"`
// MaxTotalRules is a budget shared by every redirect and header rule.
MaxTotalRules int `json:"max_total_rules,omitempty"`
}
Limits describe what a host can express. A zero count means no limit.
type Manifest ¶ added in v0.2.0
type Manifest struct {
Version int `json:"version"`
Site string `json:"site"`
Backend string `json:"backend"`
Topology string `json:"topology"`
Credentials bool `json:"credentials"`
Proto int `json:"proto,omitempty"`
Build string `json:"build,omitempty"`
Live []ManifestLive `json:"live"`
Dynamic []string `json:"dynamic"`
Proxy []string `json:"proxy"`
Rewrites []RedirectRule `json:"rewrites,omitempty"`
}
Manifest is /_fletch/static.json: what a split export expects of its backend. verify-backend compares a deployed backend's contract to it.
func LoadManifest ¶ added in v0.2.0
LoadManifest reads _fletch/static.json from an export directory, for any target layout.
type ManifestLive ¶ added in v0.2.0
type ManifestLive struct {
Name string `json:"name,omitempty"`
// Path is the Live page's route path, the key of the backend contract.
Path string `json:"path"`
// Page is the URL path of the exported shell.
Page string `json:"page"`
// Endpoint is what the shell joins: absolute, or relative to the site
// under Proxy.
Endpoint string `json:"endpoint"`
FP string `json:"fp"`
Mode string `json:"mode"`
}
ManifestLive is one exported Live shell.
type Option ¶
type Option func(*config)
Option configures a Site.
func Backend ¶ added in v0.2.0
func Backend(url string, opts ...BackendOption) Option
Backend declares the Fletch backend that serves what a static site cannot: Live pages (exported as shells that join it at run time), Dynamic paths, and forms. url is its origin, such as "https://app.example.com"; --backend overrides it and $FLETCH_BACKEND_URL is the fallback. The export proves in process that the backend accepts the site, and fails with S017 to S027 when it would not.
func Base ¶
Base serves the site under a path prefix, such as "/repo" for a GitHub project page. Root-relative URLs in HTML and CSS are prefixed.
func CSPStrict ¶
func CSPStrict() Option
CSPStrict makes a cross-origin script that the nonce allowed an error (S008) instead of adding its origin to script-src.
func Exclude ¶
Exclude leaves out every path that matches one of globs. A glob ending in /* matches everything below it; otherwise * stays inside one segment.
func NotFound ¶
NotFound names the path whose response becomes 404.html. By default the exporter requests a path no app serves and keeps the app's own 404 page.
func Paths ¶
Paths lists the parameter sets of a route with path parameters. route is a route name, or a pattern such as "/blog/{slug}".
func Rewrite ¶ added in v0.2.0
Rewrite serves the exported file to at every path matching from, with status 200, as a host rule: an SPA fallback such as Rewrite("/docs-app/*", "/docs-app/index.html"). It needs no Backend.
func Search ¶
Search builds a full-text search index of the exported pages: the index in /_search/index.json (sharded above 1 MiB) and the browser client in /_search/client.js. Pages marked noindex are left out; opts narrow it further, such as search.Include("/docs/*"). See package search.
func TrailingSlash ¶
func TrailingSlash(p SlashPolicy) Option
TrailingSlash sets the canonical URL form and file layout. Default Never.
func URL ¶
URL sets the site's public URL, such as "https://fletch.page". It sets the Host and scheme of every rendered request, so absolute URLs, canonical tags and the sitemap come out right. --url and ExportOptions.URL override it; APP_URL is the fallback.
type PageOpt ¶
type PageOpt func(*pageMeta)
PageOpt describes the page being rendered; see Describe.
type PageReport ¶
type PageReport struct {
URL string `json:"url"`
File string `json:"file"`
Route string `json:"route,omitempty"`
Source string `json:"source"`
}
PageReport is one exported HTML page.
type Params ¶
Params is one set of path parameters for a route, keyed by parameter name. It is an alias so a plain map[string]string, such as the one a content collection builds, needs no conversion.
type PathsFunc ¶
PathsFunc lists the parameter sets of a route with path parameters. A plain func(context.Context) ([]map[string]string, error) is assignable to it.
type PrerenderError ¶
type PrerenderError struct {
Diagnostics []Diagnostic
}
PrerenderError lists the safety checks a prerender failed.
func (*PrerenderError) Error ¶
func (e *PrerenderError) Error() string
func (*PrerenderError) Unwrap ¶
func (e *PrerenderError) Unwrap() error
Unwrap makes errors.Is(err, ErrExport) true, as for a failed export.
type PrerenderOption ¶
type PrerenderOption interface {
// contains filtered or unexported methods
}
PrerenderOption configures a Prerenderer. Every Option is one too, so Paths, Page, Exclude, URL and CSPStrict work the same as for New.
func Revalidate ¶
func Revalidate(d time.Duration) PrerenderOption
Revalidate re-renders a snapshot older than d in the background while the old one is still served. Zero, the default, keeps snapshots until Invalidate or Refresh.
func Routes ¶
func Routes(globs ...string) PrerenderOption
Routes limits prerendering to the planned paths that match one of globs, such as "/pricing" or "/blog/*". Without it the whole plan is served from memory.
func SkipCookies ¶
func SkipCookies(names ...string) PrerenderOption
SkipCookies names the session cookies whose presence sends a request to the live handler, replacing the default "fletch_session" and "session".
func SkipRequest ¶
func SkipRequest(fn func(*http.Request) bool) PrerenderOption
SkipRequest sends every request for which fn returns true to the live handler.
func Warm ¶
func Warm(m WarmMode) PrerenderOption
Warm picks when the plan is rendered. Default AtBoot.
func WithErrorReporter ¶
func WithErrorReporter(fn func(path string, err error)) PrerenderOption
WithErrorReporter receives the renders that failed or could not be cached after Warm: a failed re-render (the stale snapshot is kept), or a page that looks per-user and is served live.
type Prerenderer ¶
type Prerenderer struct {
// contains filtered or unexported fields
}
Prerenderer serves pages of a dynamic app from in-memory snapshots made by the export engine: the same plan, render, CSP hash pass and safety checks.
func Prerender ¶
func Prerender(app App, opts ...PrerenderOption) *Prerenderer
Prerender returns a Prerenderer for app. Install its Middleware inside secure.New and call Warm at startup:
pre := static.Prerender(app, static.Routes("/", "/pricing", "/blog/*"))
app.Use(pre.Middleware())
app.OnStart(pre.Warm)
func (*Prerenderer) Invalidate ¶
func (p *Prerenderer) Invalidate(paths ...string)
Invalidate drops the snapshots of paths; each renders again on its next cacheable request. A path not yet planned that matches Routes, such as a new blog post, joins the plan.
func (*Prerenderer) Middleware ¶
func (p *Prerenderer) Middleware() func(http.Handler) http.Handler
Middleware serves planned paths from their snapshots. Requests that are not GET or HEAD, carry a query string, Authorization or a session cookie, and the engine's own renders go to next.
type PreviewOptions ¶
type PreviewOptions struct {
// Target is the host to emulate: "cloudflare" (default), "vercel",
// "netlify", "github-pages" or "plain".
Target string
// Base is the path prefix the site is served under.
Base string
// Slash is the export's policy; it picks Cloudflare's html_handling.
Slash SlashPolicy
// Backend overrides the backend of a split export's _fletch/static.json
// for the paths the host proxies.
Backend string
}
PreviewOptions configure Preview.
type RedirectRule ¶
type RedirectRule struct {
From string `json:"from"`
To string `json:"to"`
Status int `json:"status"`
}
RedirectRule is one redirect rule. From may end in /* to match everything below it; a * at the end of To is replaced by the matched rest.
type Report ¶
type Report struct {
Target string `json:"target"`
URL string `json:"url"`
Base string `json:"base,omitempty"`
Out string `json:"out"`
DryRun bool `json:"dry_run,omitempty"`
Pages []PageReport `json:"pages"`
Files []FileReport `json:"files"`
Redirects []RedirectRule `json:"redirects"`
Headers []HeaderRule `json:"headers"`
CSP string `json:"csp"`
Rewrites []RedirectRule `json:"rewrites,omitempty"`
Split *Manifest `json:"split,omitempty"`
Diagnostics []Diagnostic `json:"diagnostics"`
Notes []string `json:"notes,omitempty"`
Timings Timings `json:"timings"`
}
Report describes one export: what was written, the rules, the CSP strategy, every diagnostic, and timings. --json prints it.
type ShellMode ¶ added in v0.2.0
type ShellMode int
ShellMode picks how a Live page is exported under a Backend.
type Site ¶
type Site struct {
// contains filtered or unexported fields
}
Site is a configured exporter for one app.
func (*Site) Commands ¶
Commands returns the export, preview, verify-backend and topology commands, for app.Command.
type SlashPolicy ¶
type SlashPolicy int
SlashPolicy picks the canonical form of page URLs and the file layout.
const ( // Never serves /pricing from pricing.html. It is the default and serves // the same URL with no redirect on every supported host. Never SlashPolicy = iota // Always serves /pricing/ from pricing/index.html. Always )
func (SlashPolicy) String ¶
func (p SlashPolicy) String() string
String returns "never" or "always".
type Subscriber ¶
type Subscriber interface {
Subscribe(ctx context.Context, fn func(Invalidation)) (cancel func(), err error)
}
Subscriber delivers Invalidation messages. A pubsub.TypedTopic of Invalidation satisfies it, so this package needs no pubsub import:
topic := pubsub.Bind(bus, pubsub.NewTopic[static.Invalidation]("static.invalidate"))
cancel, err := static.InvalidateOn(ctx, topic, pre)
// on publish, from any node:
topic.Publish(ctx, static.Invalidation{Paths: []string{"/blog", "/blog/new-post"}})
type Target ¶
type Target interface {
Name() string
// Limits are the host's rule budgets and capabilities.
Limits() Limits
// Write writes s into out.
Write(ctx context.Context, s *Built, out *os.Root) error
}
Target writes an export for one kind of host.
func Cloudflare ¶
func Cloudflare() Target
Cloudflare returns the target for Cloudflare Workers Static Assets and Pages: _redirects, _headers and 404.html.
func GitHubPages ¶
func GitHubPages() Target
GitHubPages returns the target for GitHub Pages: .nojekyll, 404.html, a CNAME file for a custom domain, and HTML stub pages for redirects, because the host has no redirect or header rules. Page policies go into <meta>.
func Netlify ¶
func Netlify() Target
Netlify returns the target for Netlify: _redirects, _headers and 404.html. Netlify documents no rule-count limit, so S012 covers only conflicts with public/_redirects and public/_headers.
func Plain ¶
func Plain() Target
Plain returns the target for hosts with no rule files (S3, nginx, Caddy): the files, 404.html, and static-manifest.json listing redirects and headers for a custom pipeline.
func TargetByName ¶
TargetByName returns a built-in target: "cloudflare", "vercel", "netlify", "github-pages" (or "gh-pages") or "plain".
func Vercel ¶
func Vercel() Target
Vercel returns the target for Vercel. It writes the Build Output API v3 layout, .vercel/output/static and .vercel/output/config.json, which `vercel deploy --prebuilt` uploads without framework detection. Set ExportOptions.VercelJSON to write plain files and a vercel.json instead, for projects that Vercel builds from Git.
type Timings ¶
type Timings struct {
PlanMS float64 `json:"plan_ms"`
RenderMS float64 `json:"render_ms"`
WriteMS float64 `json:"write_ms"`
TotalMS float64 `json:"total_ms"`
}
Timings are in milliseconds.
type Topology ¶ added in v0.2.0
type Topology struct {
Target string `json:"target"`
Site string `json:"site"`
Backend string `json:"backend,omitempty"`
Mode string `json:"mode"`
LiveBase string `json:"live_base,omitempty"`
// Origins are what the backend's fletch.StaticFrontend.Origins must
// allow.
Origins []string `json:"origins"`
Credentials bool `json:"credentials"`
Dynamic []string `json:"dynamic"`
Proxy []string `json:"proxy"`
Rewrites []RedirectRule `json:"rewrites"`
LiveShells []TopologyShell `json:"live_shells"`
Diagnostics []Diagnostic `json:"diagnostics"`
}
Topology is a Site's split-deploy setup as an export with the given options would resolve it, for `topology` and agents. It renders nothing.
type TopologyShell ¶ added in v0.2.0
type TopologyShell struct {
Route string `json:"route,omitempty"`
Path string `json:"path"`
Endpoint string `json:"endpoint"`
Mode string `json:"mode"`
}
TopologyShell is one Live route and how it is exported.
type VerifyOptions ¶ added in v0.2.0
type VerifyOptions struct {
// Manifest is the export's _fletch/static.json. Required.
Manifest *Manifest
// Site and Backend override the manifest's origins.
Site, Backend string
// RequireBuildMatch makes a backend on another build an error (S032).
RequireBuildMatch bool
// SiteCheck also checks the deployed site: that it proxies to the
// backend (S035, proxy topologies) and serves this export's manifest
// (S033). Run it after the static deploy.
SiteCheck bool
// Timeout bounds each request and the Live probe. Default 10s.
Timeout time.Duration
// Client sends the HTTP requests. Default: a client with Timeout that
// does not follow redirects.
Client *http.Client
}
VerifyOptions configure VerifyBackend.
type VerifyReport ¶ added in v0.2.0
type VerifyReport struct {
Site string `json:"site"`
Backend string `json:"backend"`
Topology string `json:"topology"`
Build string `json:"build,omitempty"`
Diagnostics []Diagnostic `json:"diagnostics"`
}
VerifyReport is the outcome of VerifyBackend.
func VerifyBackend ¶ added in v0.2.0
func VerifyBackend(ctx context.Context, o VerifyOptions) (*VerifyReport, error)
VerifyBackend checks over the network that a deployed backend serves what the export expects: it is ready (S036), its contract allows the site with the same protocol (S018, S031), build (S032) and templates (S033), CORS preflights pass (S019), and a Live probe joins over WebSocket or SSE (S034). The error wraps ErrVerify when it failed.
func (*VerifyReport) Failed ¶ added in v0.2.0
func (r *VerifyReport) Failed() bool
Failed reports whether an error diagnostic was found.
Source Files
¶
- assets.go
- base.go
- commands.go
- commands_split.go
- context.go
- csp.go
- diag.go
- export.go
- fromfs.go
- headers.go
- invalidate.go
- pattern.go
- plan.go
- prerender.go
- preview.go
- preview_split.go
- preview_vercel.go
- probe.go
- proofs.go
- render.go
- report.go
- scan.go
- search_export.go
- sitemap.go
- split.go
- splitexport.go
- static.go
- target.go
- target_ghpages.go
- target_netlify.go
- target_split.go
- target_vercel.go
- topology.go
- verify.go
Directories
¶
| Path | Synopsis |
|---|---|
|
content
module
|
|
|
highlight
module
|
|
|
deploy
|
|
|
cloudflare
Package cloudflare uploads an exported static site to Cloudflare Workers Static Assets with the direct-upload API, using only the standard library.
|
Package cloudflare uploads an exported static site to Cloudflare Workers Static Assets with the direct-upload API, using only the standard library. |
|
netlify
Package netlify uploads an exported static site to Netlify with the file-digest Deploy API, using only the standard library.
|
Package netlify uploads an exported static site to Netlify with the file-digest Deploy API, using only the standard library. |
|
Package feed renders RSS 2.0, Atom 1.0 and JSON Feed 1.1 documents and serves them as http handlers.
|
Package feed renders RSS 2.0, Atom 1.0 and JSON Feed 1.1 documents and serves them as http handlers. |
|
og
module
|
|
|
Package search builds a static full-text search index from exported HTML pages and ships a small client script that queries it in the browser.
|
Package search builds a static full-text search index from exported HTML pages and ships a small client script that queries it in the browser. |
|
Package seo checks the search-engine and social metadata of an export.
|
Package seo checks the search-engine and social metadata of an export. |
|
Package statictest exports an app inside a test and asserts on the result: files, headers and redirects as the host's preview serves them, and diagnostics.
|
Package statictest exports an app inside a test and asserts on the result: files, headers and redirects as the host's preview serves them, and diagnostics. |