plug

package
v0.3.0-beta.9 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

Documentation

Overview

Package plug is the public SDK for writing Krate plugins in Go. A plugin is a standalone main package that calls plug.Serve with the hooks it implements; the Krate compiler launches it as a subprocess over HashiCorp go-plugin (net/rpc). The plugin author ships per-platform binaries, typically inside an npm package whose config points Krate at the right binary for the host.

Hook contracts mirror the JavaScript plugin surface: the compiler hands each hook a JSON context and expects the concrete Go types described below. Hook contexts are mutable - edit fields (or the *ast.Program for AfterParse) and return nil. Dispatch marshals the changed state back for the host to apply.

Index

Constants

View Source
const (
	// ProtocolVersion identifies the wire contract between host and plugin.
	ProtocolVersion = 1
	// MagicCookieKey and MagicCookieValue distinguish a Krate plugin process
	// from any other executable the host may be pointed at.
	MagicCookieKey   = "KRATE_PLUGIN_MAGIC_COOKIE"
	MagicCookieValue = "f58a3d1f-9c86-4b2a-9e7f-8b3c2a1d4e5f"
	// PluginName is the go-plugin plugin type name in the plugin map.
	PluginName = "krate"
)

Handshake constants shared by the plugin binary and the Krate host.

Variables

HandshakeConfig is the go-plugin handshake both sides must agree on.

Functions

func Serve

func Serve(name string, hooks Hooks)

Serve launches the plugin subprocess protocol. Call it from main and do not return after invoking it; the plugin exits when the host shuts it down.

Types

type Bridge

type Bridge struct {
	Impl PluginServer
}

Bridge adapts the plugin binary and the Krate host to go-plugin. On the server side Server returns the Dispatch service; on the client side Client returns an RPCClient bound to the running subprocess.

func (*Bridge) Client

func (b *Bridge) Client(broker *plugin.MuxBroker, c *rpc.Client) (interface{}, error)

func (*Bridge) Server

func (b *Bridge) Server(*plugin.MuxBroker) (interface{}, error)

type BuildArgs

type BuildArgs struct {
	Result
	Root           string           `json:"root"`
	OutDir         string           `json:"outDir"`
	Config         interface{}      `json:"config,omitempty"`
	Pages          []string         `json:"pages"`
	GeneratedPages *[]GeneratedPage `json:"generatedPages,omitempty"`
	DevMode        bool             `json:"devMode"`
}

BuildArgs is passed to BeforeBuild and GenerateRoutes.

type BuildResultArgs

type BuildResultArgs struct {
	Result
	Root   string       `json:"root"`
	OutDir string       `json:"outDir"`
	Config interface{}  `json:"config,omitempty"`
	Pages  []PageResult `json:"pages"`
	CSS    string       `json:"css"`
}

BuildResultArgs is passed to AfterBuild with every page's results.

type DispatchRequest

type DispatchRequest struct {
	Kind string          `json:"kind"`
	Hook string          `json:"hook"`
	Args json.RawMessage `json:"args"`
}

DispatchRequest is the gob-encoded unit of RPC. Kind distinguishes build hooks from serve-time hooks; the plugin returns a uniform result envelope.

type File

type File struct {
	Path    string `json:"path"`
	Content string `json:"content"`
}

File is a single file written to the output directory.

type GeneratedPage

type GeneratedPage struct {
	Path  string `json:"path"`
	Route string `json:"route"`
}

GeneratedPage is a page file produced by a plugin that should enter the normal page pipeline.

type Hooks

type Hooks struct {
	// BeforeBuild runs before pages are compiled. Files/GeneratedPages set on
	// the context are applied by the host.
	BeforeBuild func(ctx *BuildArgs) error

	// AfterParse runs after a page's source parses. ctx.Program carries the
	// parsed program; edit it in place and the host renders the edited tree.
	AfterParse func(ctx *ParseArgs) error

	// AfterMarkdownParse runs after markdown pages render to HTML. ctx.HTML is
	// the rendered markup before layout wrapping.
	AfterMarkdownParse func(ctx *MarkdownArgs) error

	// AfterRender runs after a page renders but before layout wrapping.
	AfterRender func(ctx *RenderArgs) error

	// GenerateRoutes runs after BeforeBuild. Set ctx.Routes to synthesize
	// virtual pages alongside real source pages.
	GenerateRoutes func(ctx *BuildArgs) error

	// AfterPage runs after a page is fully built including layout wrapping.
	AfterPage func(ctx *PageArgs) error

	// AfterBuild runs once after every page is built.
	AfterBuild func(ctx *BuildResultArgs) error

	// ServeRequest runs at request time before a page is served. Set ctx.Action
	// to "rewrite" (with ctx.NewURL) to rewrite the path or "respond" (with
	// Status/Headers/Body) to short-circuit.
	ServeRequest func(ctx *ServeRequestArgs) error

	// ServeResponse runs at request time after a non-streaming response has
	// been buffered. Edit Status/Headers/Body on the context to rewrite it.
	ServeResponse func(ctx *ServeResponseArgs) error
}

Hooks groups the optional hook implementations a plugin provides. Only non-nil hooks are invoked. Every hook receives a mutable context pointer; return an error to abort the build/serve operation.

type MarkdownArgs

type MarkdownArgs struct {
	Result
	Page  string `json:"page"`
	HTML  string `json:"html"`
	Title string `json:"title"`
	Route string `json:"route"`
}

MarkdownArgs is passed to AfterMarkdownParse.

type PageArgs

type PageArgs struct {
	Result
	Page     string `json:"page"`
	OutName  string `json:"outName"`
	HTML     string `json:"html"`
	HeadHTML string `json:"headHTML"`
	HasJS    bool   `json:"hasJS"`
}

PageArgs is passed to AfterPage with the final page output.

type PageResult

type PageResult struct {
	Page     string `json:"page"`
	OutName  string `json:"outName"`
	HTML     string `json:"html"`
	HeadHTML string `json:"headHTML"`
	HasJS    bool   `json:"hasJS"`
}

PageResult describes one built page in AfterBuild.

type ParseArgs

type ParseArgs struct {
	Result
	Page    string       `json:"page"`
	Program *ast.Program `json:"-"`
}

ParseArgs is passed to AfterParse. Program is reconstructed from the kind-tagged document the host sends; editing it and returning modifies the build.

func (*ParseArgs) UnmarshalJSON

func (p *ParseArgs) UnmarshalJSON(data []byte) error

UnmarshalJSON hydrates the context, decoding the "program" document via the astjson codec into a live *ast.Program for the hook to edit.

type PluginServer

type PluginServer interface {
	Dispatch(req DispatchRequest, out *json.RawMessage) error
}

PluginServer is the net/rpc service object a plugin binary serves.

type RPCClient

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

RPCClient is the host-side handle to a running plugin.

func (*RPCClient) Close

func (c *RPCClient) Close() error

Close terminates the RPC connection.

func (*RPCClient) Dispatch

func (c *RPCClient) Dispatch(kind, hook string, args json.RawMessage) (json.RawMessage, error)

Dispatch sends one hook invocation to the plugin and returns the raw output envelope JSON. Kind must be "build" or "serve".

type RenderArgs

type RenderArgs struct {
	Result
	Page     string `json:"page"`
	HTML     string `json:"html"`
	HeadHTML string `json:"headHTML"`
	HasJS    bool   `json:"hasJS"`
	RawCSS   string `json:"rawCSS"`
}

RenderArgs is passed to AfterRender. HTML, HeadHTML and RawCSS are filled from the host and are mutable; their final values are applied by the host.

type Result

type Result struct {
	Files          []File          `json:"files,omitempty"`
	Routes         []Route         `json:"routes,omitempty"`
	GeneratedPages []GeneratedPage `json:"generatedPages,omitempty"`
	HTML           *string         `json:"html,omitempty"`
	HeadHTML       *string         `json:"headHTML,omitempty"`
	RawCSS         *string         `json:"rawCSS,omitempty"`
	Scripts        []string        `json:"scripts,omitempty"`
	MetaTags       []string        `json:"metaTags,omitempty"`
	// Ast is the edited program document for AfterParse. Set by Dispatch from
	// ParseArgs.Program; plugins do not construct it directly.
	Ast json.RawMessage `json:"ast,omitempty"`
}

Result is embedded in every hook context. Dispatch collects whatever the hook set and returns it to the host in the unified output envelope.

type Route

type Route struct {
	Path    string            `json:"path"`
	Content string            `json:"content"`
	Title   string            `json:"title"`
	Layout  string            `json:"layout,omitempty"`
	Data    map[string]string `json:"data,omitempty"`
}

Route is a virtual page synthesized by a plugin.

type ServeRequestArgs

type ServeRequestArgs struct {
	Result
	URL     string            `json:"url"`
	Method  string            `json:"method"`
	Path    string            `json:"path"`
	Headers map[string]string `json:"headers"`
	// Action is "continue", "rewrite", or "respond".
	Action string `json:"action,omitempty"`
	Status int    `json:"status,omitempty"`
	NewURL string `json:"newURL,omitempty"`
	Body   string `json:"body,omitempty"`
}

ServeRequestArgs is the request-time context for the ServeRequest hook.

type ServeResponseArgs

type ServeResponseArgs struct {
	Result
	URL     string            `json:"url"`
	Method  string            `json:"method"`
	Path    string            `json:"path"`
	Status  int               `json:"status"`
	Headers map[string]string `json:"headers"`
	Body    string            `json:"body"`
}

ServeResponseArgs is the request-time context for the ServeResponse hook. It wraps a buffered non-streaming response.

Jump to

Keyboard shortcuts

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