Skip to content
lsdocs plugin SDK API

lsdocs_plugin_sdk #

Write lsdocs plugins in Rust.

Implement one or more of Parser, Transformer and Renderer, bundle them into a Plugin, and hand it to main:

use lsdocs_plugin_sdk::{Context, Plugin, PluginResult, Transformer};
use lsdocs_plugin_sdk::protocol::{RenderTransformEachParams, RenderTransformEachResult};

struct Shout;

impl Transformer for Shout {
    fn nodes(&self) -> Vec<String> {
        vec!["text".into()]
    }

    async fn apply(
        &self,
        params: RenderTransformEachParams,
        ctx: &Context,
    ) -> PluginResult<RenderTransformEachResult> {
        ctx.info("shouting").await;
        Ok(RenderTransformEachResult { document: params.document, ..Default::default() })
    }
}

fn main() -> std::process::ExitCode {
    lsdocs_plugin_sdk::main(Plugin::new("shout", "0.1.0").transformer(Shout))
}

The capabilities sent to the host follow from what the plugin implements. main speaks the protocol over stdio, or over the pipe in LSDOCS_PIPE when the host sets it, and returns when the host says exit or closes the connection.

The host can also run a Plugin in-process, calling Plugin::parse and friends directly with no serialization.

Submodules

re-export protocol #

pub use lsdocs_protocol as protocol;

Re-export of lsdocs_protocol.

re-export doctree #

pub use lsdocs_protocol::doctree;

Re-export of lsdocs_protocol::doctree.

re-export TRACE_TARGET #

pub use lsdocs_rpc::trace::TARGET as TRACE_TARGET;

Tracing target for wire logs; enable it at TRACE level to log every protocol message.

Re-export of lsdocs_rpc::trace::TARGET.

type alias BoxFuture #

pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

A boxed, sendable future.

type alias PluginResult #

pub type PluginResult<T> = Result<T, PluginError>;

Result of a plugin operation.

struct PluginError #

pub struct PluginError { /* private fields */ }

A plugin operation failed. Any std::error::Error converts into it, so ? works on most errors.

Trait implementations

function new #

pub fn new(message: impl Into<String>) -> Self

Creates an error with the given message.

method message #

pub fn message(&self) -> &str

The error message.

trait Parser #

pub trait Parser: Send + Sync + 'static

Turns source files into documents.

method extensions #

fn extensions(&self) -> Vec<String>;

File extensions handled, without the dot, e.g. ["md"].

method parse #

fn parse(
    &self,
    params: ParseParams,
    ctx: &Context,
) -> impl Future<Output = PluginResult<ParseResult>> + Send;

Parses one file.

trait Transformer #

pub trait Transformer: Send + Sync + 'static

Rewrites documents, optionally using data collected from every document first.

constant READS #

const READS: bool = false;

Whether to run the collect pass. If true, Transformer::read is called for every document before any Transformer::apply, and apply receives everything collected.

method nodes #

fn nodes(&self) -> Vec<String> { ... }

Node kinds this transformer looks at, e.g. ["heading"]. The host skips documents containing none of them. Empty means every document.

method read #

fn read(
    &self,
    _params: ParseTransformEachParams,
    _ctx: &Context,
) -> impl Future<Output = PluginResult<ParseTransformEachResult>> + Send { ... }

Gathers data from one document. Only called if Transformer::READS is true.

method conclude #

fn conclude(
    &self,
    _collected: &Value,
    _ctx: &Context,
) -> impl Future<Output = PluginResult<ParseTransformAllResult>> + Send { ... }

Generates documents from everything collected (a map from each document's source to its collected data), once between the two passes. They join the project: the apply pass, later transformers and rendering see them like any other document. Only called if Transformer::READS is true; none by default.

method apply #

fn apply(
    &self,
    params: RenderTransformEachParams,
    ctx: &Context,
) -> impl Future<Output = PluginResult<RenderTransformEachResult>> + Send;

Transforms one document.

trait Renderer #

pub trait Renderer: Send + Sync + 'static

Turns documents into output files.

method formats #

fn formats(&self) -> Vec<String>;

Output formats produced, e.g. ["html"].

constant RENDERS_ALL #

const RENDERS_ALL: bool = false;

Whether to handle render/transform/all. If true, Renderer::render_all is called once after every document is rendered.

method render #

fn render(
    &self,
    params: RenderParams,
    ctx: &Context,
) -> impl Future<Output = PluginResult<RenderResult>> + Send;

Renders one document.

method render_all #

fn render_all(
    &self,
    _params: RenderTransformAllParams,
    _ctx: &Context,
) -> impl Future<Output = PluginResult<RenderTransformAllResult>> + Send { ... }

Produces output files no single document makes, such as a sitemap, from the list of rendered pages. Only called if Renderer::RENDERS_ALL is true.

trait OutputFiles #

pub trait OutputFiles: Send + Sync + 'static

Writes output files after every document is rendered, without rendering documents itself: an inventory of the documented objects, say. A plugin with output files asks for render/transform/all (its render capability has all and, without a renderer, no formats).

method files #

fn files(
    &self,
    params: RenderTransformAllParams,
    ctx: &Context,
) -> impl Future<Output = PluginResult<RenderTransformAllResult>> + Send;

Produces the files from the list of rendered pages.

struct Plugin #

pub struct Plugin { /* private fields */ }

A plugin: a name, a version, and any of a parser, a transformer and a renderer.

Trait implementations

function new #

pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self

A plugin with no capabilities yet.

method parser #

pub fn parser(self, parser: impl Parser) -> Self

Adds a parser.

method transformer #

pub fn transformer(self, transformer: impl Transformer) -> Self

Adds a transformer.

method renderer #

pub fn renderer(self, renderer: impl Renderer) -> Self

Adds a renderer.

method output_files #

pub fn output_files(self, files: impl OutputFiles) -> Self

Adds output files written after rendering (see OutputFiles).

method max_concurrency #

pub fn max_concurrency(self, n: u32) -> Self

Limits how many requests the plugin works on at once.

method cacheable #

pub fn cacheable(self) -> Self

Lets the host cache the plugin's results: they depend only on each request, the project settings, the plugin's name and version and its settings files. See Capabilities::cache.

method cache_key #

pub fn cache_key(self, key: impl Fn(&Setup) -> Option<String> + Send + Sync + 'static) -> Self

Lets the host cache the plugin's results, as Plugin::cacheable, with a key covering any other input the plugin reads, computed from the session's setup (e.g. a digest of a template file named in the settings). Returning None turns caching off for the session.

method syntax #

pub fn syntax(self, syntax: impl Fn(&Setup) -> Syntax + Send + Sync + 'static) -> Self

Declares the directives and roles the plugin handles (see Capabilities::syntax), computed from the session's setup so they may depend on the plugin's settings.

method settings #

pub fn settings(
    self,
    loader: impl Fn(&ConfigInfo) -> Result<Loaded, String> + Send + Sync + 'static,
) -> Self

Reads the plugin's settings at initialize, from the project's .config/ directory (see config). The settings are Context::settings and Setup::settings; an error fails initialize.

method setup #

pub fn setup(&self, params: &InitializeParams) -> Result<Setup, String>

The setup of the session initialize starts: its params and the settings the plugin's loader reads.

method info #

pub fn info(&self) -> ProgramInfo

The plugin's name and version.

method capabilities_for #

pub fn capabilities_for(&self, setup: &Setup) -> Capabilities

What the plugin can do in the session initialize starts: its Plugin::capabilities plus its cache key and syntax.

method capabilities #

pub fn capabilities(&self) -> Capabilities

What the plugin can do, derived from the parts it has (without a cache key or syntax, which depend on the session; see Plugin::capabilities_for).

method initialize_result #

pub fn initialize_result(&self, setup: &Setup) -> InitializeResult

The answer to initialize.

method parse #

pub async fn parse(&self, params: ParseParams, ctx: &Context) -> PluginResult<ParseResult>

Parses a file. Fails if the plugin has no parser.

method read #

pub async fn read(
    &self,
    params: ParseTransformEachParams,
    ctx: &Context,
) -> PluginResult<ParseTransformEachResult>

Runs the collect pass on a document. Fails if the plugin has no transformer.

method conclude #

pub async fn conclude(
    &self,
    collected: &Value,
    ctx: &Context,
) -> PluginResult<ParseTransformAllResult>

Generates documents from everything collected. Fails if the plugin has no transformer.

method apply #

pub async fn apply(
    &self,
    params: RenderTransformEachParams,
    ctx: &Context,
) -> PluginResult<RenderTransformEachResult>

Transforms a document. Fails if the plugin has no transformer.

method render #

pub async fn render(&self, params: RenderParams, ctx: &Context) -> PluginResult<RenderResult>

Renders a document. Fails if the plugin has no renderer.

method render_all #

pub async fn render_all(
    &self,
    params: RenderTransformAllParams,
    ctx: &Context,
) -> PluginResult<RenderTransformAllResult>

Produces output files after rendering: the renderer's (if it renders all), then the OutputFiles'. Fails if the plugin has neither.

struct Setup #

pub struct Setup

A session's setup: the initialize params and the settings the plugin's loader read (see Plugin::settings).

Trait implementations

field params #

pub params: InitializeParams

The initialize params.

field settings #

pub settings: Value

The plugin's settings (null if it reads none).

field config_files #

pub config_files: Vec<String>

The files they came from, for the host's cache keys.

function with_settings #

pub fn with_settings(params: InitializeParams, settings: Value) -> Self

A setup with these settings, as if a loader had read them (for tests, and plugins built without a loader).

enum Event #

pub enum Event

Something a plugin reports to the host outside of a result.

Trait implementations

variant Log #

Log(LogParams)

A log line.

variant Progress #

Progress(ProgressParams)

Progress on long-running work.

variant Diagnostics #

Diagnostics(DiagnosticsParams)

Diagnostics.

trait EventSink #

pub trait EventSink: Send + Sync + 'static

Where a Context sends Events and requests to the host: the RPC connection, or the host directly for in-process plugins.

method send #

fn send(&self, event: Event) -> BoxFuture<'_, ()>;

Delivers one event.

method parse #

fn parse(&self, params: HostParseParams) -> BoxFuture<'_, Result<ParseResult, String>> { ... }

Asks the host to parse text with another parser (host/parse). The default says it cannot.

struct Context #

pub struct Context { /* private fields */ }

What a plugin operation can see and do besides its params: the project and site, the plugin's options, and reporting to the host.

Trait implementations

function new #

pub fn new(events: Arc<dyn EventSink>, setup: &Setup) -> Self

A context for the session started by initialize.

method project #

pub fn project(&self) -> &ProjectInfo

The project being built: its directory, source directory and files.

method site #

pub fn site(&self) -> &SiteInfo

The site the project renders to: its title and base URL.

method config #

pub fn config(&self) -> &ConfigInfo

Where the plugin's settings are: the project's .config/ directory and the plugin's name in the project config.

method settings #

pub fn settings(&self) -> &Value

The plugin's settings, as its loader read them (null if none; see Plugin::settings).

method parse #

pub async fn parse(
    &self,
    extension: impl Into<String>,
    source: impl Into<String>,
    text: impl Into<String>,
) -> PluginResult<ParseResult>

Parses text with the project's parser for files with extension ("md", "rst", ...), as part of the document source: e.g. a doc comment. The parser gets the declared syntax; the result is not normalized (no generated ids or link targets). See Context::host_parse to name the parser or parse a fragment.

method host_parse #

pub async fn host_parse(&self, params: HostParseParams) -> PluginResult<ParseResult>

Sends a host/parse request: Context::parse with every field, such as the parser's name, a fragment context and the text's origin. Parsers may call it while parsing (an included file in another markup); one that does guards against include cycles itself.

method log #

pub async fn log(&self, level: LogLevel, message: impl Into<String>)

Sends a log line to the host.

method debug #

pub async fn debug(&self, message: impl Into<String>)

Logs at debug level.

method info #

pub async fn info(&self, message: impl Into<String>)

Logs at info level.

method warn #

pub async fn warn(&self, message: impl Into<String>)

Logs at warning level.

method progress #

pub async fn progress(&self, message: impl Into<String>, percentage: Option<u8>)

Reports progress.

method diagnostic #

pub async fn diagnostic(&self, diagnostic: Diagnostic)

Reports a diagnostic outside of any result.

function relative_path #

pub fn relative_path(from: &str, to: &str) -> String

A relative URL from the document from to the file to, both given relative to the source directory with / separators: e.g. from guide/a.md to index.md is ../index.md.

function main #

pub fn main(plugin: Plugin) -> ExitCode

Runs plugin until the host is done with it, then returns an exit code. Use as the body of a plugin's main.

function serve #

pub async fn serve(plugin: Plugin) -> Result<(), Error>

Serves plugin over the pipe named in LSDOCS_PIPE if set, otherwise over stdio. Must run inside a tokio runtime.

function serve_on #

pub async fn serve_on(plugin: Plugin, transport: Transport) -> Result<(), Error>

Serves plugin over a given transport until the host sends exit or closes the connection.