Without Vite
The Vite plugin reads files, finds the names your modules export, serves modules that don't exist on disk and reloads pages as you edit. compile does none of that. It takes text and returns Svelte source, never touches the filesystem and runs in a browser, a worker or Node. Everything below is what a build tool, a playground or an editor that isn't Vite supplies to get the same output.
Import the compiler from mdsvex/compile, highlighting from mdsvex/highlight and math from mdsvex/math. None of them loads Vite or a Node builtin, and neither does mdsvex/host, which holds the pieces of the plugin a host needs beside the compiler. The root mdsvex is the Vite plugin, and its types import vite, so take compile from mdsvex/compile in a project without Vite.
What a host supplies
Each feature, and what a host gives compile for it:
metadata nothing
unwrap_images the option
a highlighter from mdsvex/highlight, with its languages loaded up front, see highlighting
a renderer from load_math in mdsvex/math, see math
import_images: true, then a bundler that imports images, see images as imports
routes, and base as a string or { import, from }, see links
the text of each file in sources, or read and resolve with compile_async, see code from a file
snippets, then serving each of result.snippets as a module, see code that runs
each module as its specifier and the names it exports, see below
plugins, as for the Vite plugin, and compile_async for one that defers work
read and resolve, with compile_async, see loading files
watching dependencies on the result, see below
nothing, it is data on the result, see plugin data
the template option of that compile, in place of ?template=
Finding the names a module exports
compile takes templates, components and directives as a specifier and the names that module exports (see compile), and writes the specifier into the output as given. The Vite plugin finds the names by reading each module's exports without running it.
read_exports from mdsvex/host does the same for you, with the TypeScript stripper you already have:
import { read_exports } from 'mdsvex/host';
import ts from 'typescript';
const strip = (code) =>
ts.transpileModule(code, { compilerOptions: { target: ts.ScriptTarget.ESNext } }).outputText;
const { names, stars, namespaces } = read_exports(source, 'svelte', strip);For a .svelte file it reads the <script module>. Without a stripper it reads the code as JavaScript. stars lists the export * from specifiers whose names it can't see, and namespaces the export * as name from ones, which is how a module declares its directives.
namesincludesdefault. Leave it out for a template, whose default export is the template itself.- For a document used as a template, read the exports of its compiled
codeand leave outmetadataas well.
Virtual ids, ?metadata and ?data
The Vite plugin writes mdsvex:components, mdsvex:template/<name> and the other mdsvex:* ids in place of real paths and resolves them itself. compile writes whatever specifier you give it, so a host can use real paths and skip this.
To match the plugin's output, mdsvex/host exports the prefixes (COMPONENTS_ID, DIRECTIVES_ID, TEMPLATE_ID, TEMPLATE_DIRECTIVES_ID, PLUGIN_ID, PLUGIN_COMPONENTS_ID), and manifest_resolver(manifest) returns the file an id and an imported name stand for.
A template given as { component, components } has one id for two files, so the id stands for a module that merges them. template_module(main, extra, names) writes its code: everything main exports, and over it the names that extra exports.
import { template_module } from 'mdsvex/host';
template_module('/site/src/Post.svelte', '/site/src/theme.js', ['p']);
// export * from "/site/src/Post.svelte";
// export { default } from "/site/src/Post.svelte";
// export { p } from "/site/src/theme.js";The manifest has all three: templates[name].file, and extra.file and extra.names.
metadata_module(source, parse) builds the first from the text of the document, with your frontmatter parser or undefined, and data_module(result.metadata, result.data) the second from a compile of it.
The editor manifest
The editor reads node_modules/.mdsvex/manifest.json, which the Vite plugin writes, or else mdsvex.config.json, which can't hold functions.
A host can write the manifest itself. queue_manifest(build, output) writes it a little after the last change and only when it changed, manifest_json gives the exact text the plugin writes, and MANIFEST_PATH is where it goes.
read_json_config(config, file, root, host, options?) turns the parsed JSON of an mdsvex.config.json into the manifest the plugin would write for the same options. file is the path of the config, and root the absolute project root the manifest records, where the plugin would have the Vite root. host resolves and scans the modules the config names, which is all of it that touches files:
import { read_json_config } from 'mdsvex/host';
const { manifest, errors } = read_json_config(json, '/site/mdsvex.config.json', '/site', {
resolve: (specifier, importer) => resolve_file(specifier, importer), // a path, or null
scan: (file) => scan_file(file) // { names, directives }
});scan returns the names the file exports, which read_exports finds, and the specifier of its export * as directives, or null. options.extensions gives the document extensions of a config with no extensions key. errors lists what is wrong with the config, and the manifest leaves those parts out.
Vite only
These need a dev server or Vite's config, so they stay with the plugin:
links.base: true reads Vite's base. Give compile the base as a string, or as { import, from } for a base known when the page renders.
?metadata and ?data imports In dev the plugin serves a document only when Vite would serve the file, so a request can't read files outside the project.
compile with sourcemap: true maps its own output, and mappings_to_v3 from @mdsvex/render/sourcemap turns that into a v3 map. Chaining it with the Svelte compiler's map is up to your bundler.
?template= on an import Use the template option of the compile.
of documents, of the files a fence shows and of template and component modules. A host that rebuilds watches dependencies instead, see below.
Files and plugins that wait
compile reads nothing and waits for nothing. There are two ways to give a document the files it shows and the work its plugins defer:
compile_asyncdoes it in one call. Passreadandresolveand it reads the files fences show withsrc=and what plugins load, then waits for deferred work. Use it for a build where the host can read files, in Node or a worker with a virtual filesystem.- Compiling in steps hands the waiting to you:
parse, thensettlefor deferred work, then read each ofparsed.needsyourself andrender. Use it when files arrive another way, such as a fetch or an editor's open buffers, or to compile other documents while one waits. The playground compiles this way.
The result's dependencies are absolute paths: what plugins read or named, and, when compile_async read them, the files fences show and the module of the template. Compiling in steps, you know the files you read for needs yourself. To rebuild as the Vite plugin does in dev, watch those files, and when one changes call session.invalidate([path]) on your CompilerSession, so what ctx.cached kept from it goes, then compile the documents that list it again. With compile_async, pass that session as its third argument.
Compiling in steps
A host that is not Vite, such as a playground or another bundler, compiles in steps so it can fetch what a document needs between them. This is what the Vite plugin does:
import { CompilerSession, compile_inputs } from 'mdsvex/compile';
const session = new CompilerSession();
const inputs = compile_inputs(options); // the options compile takes
const parsed = session.parse(source, inputs);
// 1. what the plugins deferred, undefined when there is nothing to wait for
await session.settle(parsed);
// 2. what the document needs: the files its fences show with src=, and images
for (const need of parsed.needs ?? []) {
if (need.type === 'source') sources[need.spec] = await read(need.spec);
}
inputs.sources = sources;
// 3. the render, with the same result compile gives
const { code, data } = session.render(parsed, inputs);parseruns the parser and the plugins. TheParsedit returns holds the document, itsmetadata, thedataits plugins wrote so far andneeds.settlewaits for deferred work and applies it, and returnsundefinedwhen there was none, so a document without any stays synchronous. A document whose plugins deferred work throws if it renders before.- Read
needsaftersettle. Deferred work and adocumenthook can add an image or a fence withsrc=, or change one, andsettlemakesneeds,snippetsandmathagain from the settled tree. Only what the inputs of theparseturned on is looked for. rendergives whatcompilegives. AParsedrenders once.- The session compiles other documents while one waits. Each
Parsedholds its own document. parsed.dependencies, anddependencieson the result, are the absolute paths its plugins read or named, for the host to watch. When one changes, callsession.invalidate([path])before compiling the documents that depend on it again, so whatctx.cachedkept from it goes.readandresolveoptions give pluginsctx.readandctx.resolve.