mds-cli 0.5.1

MDS (Markdown Script) compiler — command-line interface
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
# MDS - Markdown Script

[![CI](https://github.com/dean0x/mdscript/actions/workflows/ci.yml/badge.svg)](https://github.com/dean0x/mdscript/actions/workflows/ci.yml)
[![crates.io](https://img.shields.io/crates/v/mds-cli.svg)](https://crates.io/crates/mds-cli)
[![npm](https://img.shields.io/npm/v/@mdscript/mds.svg)](https://www.npmjs.com/package/@mdscript/mds)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

LLM prompts grow into copy-pasted walls of text that drift across agents, models, and environments. MDS gives you variables, functions, imports, and conditionals so you can write prompts once and compose them everywhere, compiled to clean Markdown.

Built for AI engineers who manage prompt libraries across agents, models, and environments.

## Quick Start

**Install the CLI** (Rust):

```bash
cargo install mds-cli
```

**Or install via npm** (Node or browser):

```bash
npm install @mdscript/mds
```

**Create and compile a starter template**:

```bash
mds init                       # creates hello.mds
mds build hello.mds            # compiles to hello.md
mds build hello.mds -o -       # stdout
```

**For multi-file prompt libraries**, templates compose via `@import` — for example:

```
---
model: claude-sonnet
tools: [search, calculator]
---

@import "./safety.mds" as guard
@import "./personas.mds" as persona

{{persona.code_reviewer("TypeScript")}}

{{guard.safety_rules()}}

## Available Tools

@for tool in tools:
- **{{tool}}**
@end

@if model == "claude-sonnet":
Use extended thinking for complex tasks.
@end
```

See [`examples/prompt-library/`](examples/prompt-library/) for a complete reusable
prompt library using `@export`/`@import` (personas, formatting, guardrails). If
imports from cross-directory libraries are rejected with a containment error, see
[Project root](#project-root).

Unlike general-purpose template engines, MDS is Markdown-native: no delimiters to escape, no runtime to configure. The compiler catches undefined variables, import cycles, and arity mismatches at build time, not in production.

## Features

- **Variables**: YAML frontmatter or runtime `--set KEY=VALUE` flags
- **Conditionals**: `@if`/`@elseif`/`@else`/`@end` with negation and equality comparisons
- **Loops**: `@for item in list:` iteration over arrays and objects
- **Functions**: `@define` reusable blocks with parameters
- **Imports/Exports**: modular prompt libraries with alias, merge, and selective imports
- **Messages**: `@message role: … @end` blocks compile to a JSON `[{role, content}]` array (`.json`); all other templates compile to Markdown (`.md`) — output format is intrinsic to the template content
- **Security**: path traversal guards, symlink rejection, file size limits
- **Rich errors**: source-span diagnostics with line/column context

## CLI Reference

```
mds build [FILE|DIR] [OPTIONS]  Compile an MDS template or directory to Markdown / JSON
mds watch [FILE|DIR] [OPTIONS]  Watch and auto-recompile on save
mds check [FILE|DIR] [OPTIONS]  Validate without rendering
mds fmt [FILE|DIR] [OPTIONS]    Reformat MDS file(s) in place (opinionated, safety-gated)
mds lint [FILE|DIR] [OPTIONS]   Static-analysis lint (10 rules; --fix, --format json)
mds init [FILENAME]             Create a starter MDS file

Global options:
  -q, --quiet                 Suppress status and diagnostic output; errors always print; exit codes unaffected

Build/Watch options:
  -o, --output <PATH>         Output file, or "-" for stdout (build and single-file watch only;
                              rejected in directory watch mode — use --out-dir instead)
  --out-dir <DIR>             Output directory (build/single-file watch: <stem>.md or <stem>.json;
                              dir-mode watch: mirrors source subtree)
  --vars <FILE>               JSON file with variable overrides (reloaded each rebuild)
                              A key repeated at any depth warns with its path; the last value wins.
  --set KEY=VALUE             Set a single variable (repeatable); value coerced to number/bool/null/array when possible
                              Repeating a key warns; the last value wins.
  --set-string KEY=VALUE      Set a single variable as a string, bypassing type coercion (repeatable)
                              Repeating a key warns; the last value wins.
  --source-map                Write a Source Map v3 sidecar (<output-file>.map, e.g. -o out.md → out.md.map); output is
                              byte-identical to a no-flag build. Ignored for messages-mode
                              templates (no renderable output). See ⚠ privacy note below.
  --inline                    Embed the source map as a sourceMappingURL data-URI comment
                              at the end of the output; no sidecar is written.
                              Requires --source-map.
  --no-source-map             Suppress source-map generation for this invocation, even when
                              build.source_map=true is set in mds.json.
  --embed-sources             Include original source text in the map's sourcesContent field.
                              Requires --source-map. ⚠ Embeds full template text — avoid if
                              templates contain secrets or PII.

Watch-only options:
  --clear                     Clear terminal before the first line each rebuild prints
                              (only when stderr is a TTY)
  --debounce <MS>             Quiet period in milliseconds before a rebuild (default: 100).
                              Each file change restarts the window, so a save burst longer
                              than MS still coalesces into a single rebuild. The window is
                              capped at max(10 × MS, 1000) ms, so a file written to
                              continuously still rebuilds. 0 disables coalescing (every
                              event rebuilds). Values above 60000 are clamped. At any
                              value, a rebuild waits while a watched file is empty after
                              having had content (as during a truncate-then-write save)
                              until it is written, or for about 1000 ms, after which the
                              empty file is compiled — longer only while a debounce window
                              opened before then is still collecting events, by at most
                              that window's cap.
  --poll-interval <MS>        Liveness-probe interval in milliseconds (default: 1000).
                              0 disables self-heal (native events only). Clamped to ≥50ms.
                              The watcher self-heals after a watched dir/root is deleted and
                              recreated; --poll-interval controls how quickly it detects recovery.

Fmt options:
  --check                     Read-only: exit non-zero if any file would change; never writes
  --diff                      Read-only: print a unified diff of pending changes; never writes
                              (colorized only when stdout is a terminal). Combines with --check —
                              --diff controls what's printed, --check controls the exit code.

Exit codes:
  0   Success (or clean Ctrl+C in watch mode; or a clean `fmt --check` / `fmt --diff` preview)
  1   Template error (syntax, undefined variable, arity mismatch), or `fmt --check` found a
      file that would change
  2   I/O error (file not found, not an MDS file, a source that cannot be read, an output
      that cannot be written, an output directory that cannot be created, a stale `.map`
      sidecar or `.json` that cannot be read or removed, stdin that cannot be read or is not
      UTF-8), or invalid CLI argument (clap parse error)
  3   Resource limit exceeded (stdin over 10 MiB included; a directory run exits 3 when
      any of its files exceeds one)
  101 Internal compiler error: a panic, a bug in mds. It wins over every other code. A panic
      while one file of a directory run or a watch session compiles fails that file alone:
      the run goes on, and `mds watch` keeps watching; both exit 101 when they end
```

A closed pipe never changes the exit code of `mds build`, `mds check`, `mds fmt`, `mds init` or
`mds lint`: `mds build page.mds -o - | head -n 1` exits 0 once `head` has read its line, and a
closed stderr leaves every output written. The failures listed under exit code 2 exit at least 2
— the CLI's own write, delete and stdin failures as `mds::io` errors — also in directory mode,
where the other files are still processed; a directory run whose failures are only template
errors exits 1. A directory run with a file over a resource limit exits 3, as that file alone
does, whatever else failed: `mds build`, `mds check`, `mds fmt` and `mds lint` agree.
`mds lint` exits at least 2 for an I/O failure: a failed `--fix` rewrite, stdin that cannot be
read, and a stdout write that fails other than by a closed pipe. The stdout failure is reported
once, as `mds::io`, and lifts even a clean run (changed in v0.5.0; previously a clean
`mds lint --format json` into such a stdout exited 0). In directory mode each file whose
`--fix --diff` diff it lost counts under `with errors`, as `mds fmt --diff <dir>` counts it
failed. A failed `--fix` rewrite — of a file argument or of a file in a directory — and a stdin
read failure are `mds::io` too. A source over 10 MiB — stdin, a file argument or a file in a
directory — is `mds::resource_limit`, exit 3, in every mode and format, except that
`mds lint --fix --format json -` refuses stdin before reading it; a directory still lints its
other files. A `--vars` file over 10 MiB is `mds::resource_limit`, exit 3, too. A file
argument's `mds.json`, and in directory mode each file's, loads before the file is read, so a
malformed one is that file's `mds::io` error even when the file is also unreadable or over the
cap. Under `--format json`, every exit except a usage error or a panic that ends the run prints
exactly one JSON document on stdout — the error document for a failure that stops the run,
such as a `--vars` file that cannot load or a directory with nothing to lint — and
`--fix --diff` prints its diffs before it (changed in v0.5.0; these failures printed only on
stderr).

**Never over an MDS module or an input** (changed in v0.5.0; previously such an output replaced the file and exited 0): `mds build` and `mds watch` never write an
output over an MDS module a template can import — a `.mds` file, or a `.md` file whose
frontmatter declares `type: mds` — nor over a file the run reads: the entry, a module it imports, the `--vars` file or the
`mds.json` in force (`mds build chat.mds --vars chat.json`, a messages template whose output is
`chat.json`) — in directory mode also the `mds.json` nearest each source, which `mds build
<source>` would hold in force. In directory mode, this input rule applies per source: its own compile's entry and imported modules.
The `--vars` file and the `mds.json` files named above count too. It is refused (`mds::io`, `cannot write <file>: refusing to replace an MDS module (an output that declares type: mds is a generated module, and is rebuilt from its source)`
or `… refusing to replace a file this run reads`) and left as it is: `mds build <file>` exits 2,
`mds build <dir>` goes on with the other files and exits 2, and `mds watch` reports it and
keeps watching. Any other file there is written over as before. An output whose own
frontmatter declares `type: mds` — a template that generates a module — is a module itself, so
it rewrites its output on every build and rebuild, and replaces a module written by hand at
that path the same way; it is never written over a file the run reads either.
A generator may replace a module that another source of the same directory run imports.
A source compiled before the generator reads the module as it was.

**Directory mode** (`mds build <dir>` / `mds check <dir>`): every non-partial `.mds` file under the directory is compiled, with two automatic exclusions: directories whose name starts with `.` (e.g. `.git`, `.github`, `.claude`, `.cursor`) and `node_modules` are skipped during traversal. `_`-prefixed files are partials — tracked as dependencies but never emitted to their own output. Output mirrors the source subtree (e.g. `src/a/b/foo.mds` → `dist/a/b/foo.md`). Symlinks are rejected. Errors are per-file and do not abort the run; a summary (`N built, N failed`; `N passed, N failed` for `check`) is printed on a successful run or when any file fails; the exit code is non-zero if any file fails. Under `--quiet`, the summary is suppressed on a fully-successful run but is always emitted when any file fails, so the non-zero exit is never unexplained. If **every** `.mds` file is under a default-excluded directory, the command exits non-zero and prints a diagnostic carrying the skip count — even under `--quiet` — because this is the silent CI green-pass failure mode for prompt-template libraries stored under `.github/prompts/`, `.claude/`, or `.cursor/rules/`. A genuinely empty directory (no `.mds` files anywhere) also exits non-zero (`1`) with `no .mds files found in <dir>; nothing was built` (`…checked` for `check`), likewise even under `--quiet` — an empty tree is treated as a misconfiguration, not a success. (Changed in v0.4.3; previously exited 0.) A directory whose `.mds` files are all `_`-prefixed partials is treated the same way — `build`/`check` exit `1` with `<n> .mds file(s) found in <dir> but all are _-prefixed partials; nothing was built` (`…checked`), even under `--quiet`, while `mds fmt` and `mds lint` are unaffected since they format and lint partials. (Changed in v0.4.3; previously `0 built, 0 failed`, exit 0.) `mds watch <dir>` is the exception: it starts on an empty tree and compiles files created later. When a file's kind changes, `mds build <dir>` with `--out-dir` (or `build.output_dir`) removes the old `.json` only while it holds exactly the messages output mds writes, and never removes the old `.md`; anything else at that name is kept, with a warning. `mds watch <dir>` removes the output of a deleted source, and the old output of a file whose kind changed, only when that session wrote the file and it is unchanged; any other file is kept, with a notice. The output extension is intrinsic: `.md` for Markdown templates, `.json` for templates with `@message` blocks.

`mds fmt <dir>` follows the same directory-mode conventions (recursive, symlinks rejected, continue-on-error, non-zero exit summary) with one deliberate difference: it formats `_`-prefixed **partials too** — formatting rewrites source, not compiled output, and a partial's source is just as much a candidate for reformatting as any other file.

### Live preview with `mds watch`

Watch a single file and recompile whenever it (or any of its imports) changes:

```bash
mds watch system.mds            # recompiles to system.md on every save
mds watch system.mds -o -       # stream output to stdout
mds watch system.mds --clear    # clear terminal before each rebuild
mds watch system.mds --vars vars.json  # with variable overrides
```

Watch an entire directory:

```bash
mds watch src/                  # compile each .mds next to its source
mds watch src/ --out-dir dist   # mirror source subtree under dist/
                                # src/a/b/foo.mds → dist/a/b/foo.md  (not dist/foo.md)
```

`mds watch src/` starts even when `src/` has no `.mds` files yet; files created later are
compiled as they appear (unlike `build`/`check`/`fmt`/`lint`, which exit non-zero on an empty
tree).

> **Changed in v0.4.0:** Directory mode with `--out-dir` or `mds.json output_dir`
> now mirrors the source subtree instead of writing flat stems. Old flat outputs are
> orphaned and must be removed manually.

**Single-file mode** tracks transitive imports: editing any `@import`-ed file triggers a
recompile of the entry. **Directory mode** tracks a reverse-dependency graph: editing a
shared partial rebuilds **all transitive importers** automatically.

- `_`-prefixed files are **partials**: tracked in the dependency graph and their importers
  are rebuilt when edited, but the partial itself never emits its own `.md` output.
- **Cross-root imports**: if a file imports a partial located outside the watched root
  (e.g. `../shared/_x.mds`), editing that external partial rebuilds its in-root importers.
  The external file is never compiled to its own output.
- **`.md` modules**: a `.md` file whose frontmatter says `type: mds`, which a source
  imports, is a dependency like a partial, below the directory or outside it. Editing it
  rebuilds its importers at once, under `--poll-interval 0` too, and it never gets an
  output of its own. An edit that makes it a plain `.md` is reported through the sources
  that import it, and never again under its own path.
- **Removals**: `mds watch` removes only an output it wrote in this session, and only while
  it still holds exactly what was written — when its source is deleted (directory mode), or
  when an edit changes the template's kind and the output moves to `<name>.json` or
  `<name>.md` (both modes; an explicit `-o` keeps its path). A hand-written `todo.json`
  beside `todo.mds`, or an output you edited, is kept, with
  `Kept <file>: not written by this session` or `Kept <file>: changed since it was written`.
  Each file is the output of the source it was last written for: beside their sources
  `a.b.mds` and `a.mds` both write `a.md`, and deleting one keeps the `a.md` written for
  the other, with `Kept <file>: not written by this source`.
  A partial has no output, so a `_p.md` beside a deleted `_p.mds` is left as it is, and
  nothing is printed for it.
  A save that unlinks the source and creates it again within one batch — some editors,
  `git checkout`, `git stash` — is an edit and removes nothing.
- **Change of kind**: when an edit changes the template's kind mid-session, the new kind's
  output is written only where nothing is, or over the file this session wrote there for
  that template while it is unchanged (both modes). A hand-written `chat.md` beside
  `chat.mds` is never overwritten: it is kept with `Kept <file>: not written by this
  session; not overwritten`, the old output stays as it was, and the next save tries
  again. The startup write, and `-o`, write over whatever is there but an MDS module or a
  file the session reads, as `mds build` does.
- **Truncating saves**: an editor that saves by truncating the file and then writing it
  leaves it empty for a moment. While a watched file — the entry, an import, the `--vars`
  file, any source of a watched directory — is empty after having content, rebuilds wait
  (in directory mode, the whole batch waits), at every `--debounce`: nothing is compiled
  or printed until the file is written, so no empty output is published in between. A
  file still empty one second after the watcher first saw it emptied is compiled as it
  is, however many events arrive meanwhile and under `--poll-interval 0` too — later only
  while a debounce window opened before that second ended is still collecting events, by
  at most the window's cap of max(10 × `--debounce`, 1000) ms. A rebuild
  that empties an output it had written with content prints
  `Wrote an empty output: <file>` (not under `--quiet`).
- **Lost events**: when the operating system says it lost events (an overflowed inotify
  queue, a macOS event stream that must rescan), a directory watch looks at once for what
  they would have said — a source created or removed, a watched file or the `--vars` file
  changed — and rebuilds with it, under `--poll-interval 0` too.

- Status lines and warnings go to stderr (pipe-safe). Compiled content only goes to stdout when `-o -`.
- `--quiet` suppresses status lines and the warnings of a compile. Compile errors and failure
  reports still print (`warning: could not remove …`, `warning: failed to watch …`,
  `warning: watch error …`), and the watcher keeps running.
- Ctrl+C exits with code 0 and prints `Stopped watching.` The exit code is 101 when a compile
  panicked during the session: the watcher takes that as a failed compile and keeps watching.
- With `-o -`, a reader that goes away ends the session: `mds watch page.mds -o - | head -n 1`
  prints `Stopped watching (stdout closed).` (not under `--quiet`) and exits 0 at the next write —
  unless that is the startup write and stderr has also failed for another reason than a closed
  pipe: the session was not watching yet, so it exits 2, as the other commands do.
  A stdout write that fails for another reason is reported as `mds::io` — once however many writes
  in a row it fails, and again if stdout fails anew after a write has landed — and watching
  continues; the next rebuild writes again, even when its output has not changed. A closed stderr
  does not stop the watcher, and once it is watching, no output failure changes its exit code.
- `--vars` file is reloaded from disk on every rebuild; edits to it trigger a recompile.

### Formatting with `mds fmt`

An opinionated, safety-gated auto-formatter. Every rewrite is guaranteed **compile-equivalent**:
before writing anything, `mds fmt` re-compiles the formatted source and refuses to write if it
would change compiled output — a formatter bug surfaces as a clean error, never a silent
corruption of your template.

```bash
mds fmt template.mds            # format a file in place
mds fmt .                       # format every .mds file recursively (partials included)
mds fmt --check template.mds    # exit 1 if the file would change; never writes — for CI
mds fmt --diff template.mds     # print a unified diff of pending changes; never writes
mds fmt --check --diff .        # show diffs for every file that would change; exit 1 if any would
printf '@if ready:   \nGo\n@end\n' | mds fmt -   # format from stdin, write to stdout; creates no file
```

What it normalizes:

- CRLF → LF, everywhere (including inside frontmatter and code fences)
- Trailing whitespace on `@if`/`@for`/`@define`/… directive lines is stripped
- Exactly one final newline (empty or whitespace-only input formats to an empty file)

What it deliberately leaves untouched:

- Trailing whitespace on body-text content lines — two trailing spaces are a Markdown hard line
  break; stripping them would change rendered output
- Blank-line structure within the file body, frontmatter, and code fences — the formatter does
  not add or remove blank lines; blank-line layout is the template author's choice
- The byte-for-byte content of `@message`/`@define` bodies — whitespace inside these bodies
  reaches compiled output verbatim and must not be altered

Directory mode formats every `.mds` file recursively, **including `_`-prefixed partials**,
continuing past per-file errors and printing a summary
(`N formatted, M unchanged, K failed`, or `N would reformat, M unchanged, K failed` under `--check`). A file
is only written (and its mtime touched) when its content actually changes. Status lines and
summaries go to stderr; `--diff` output and stdin filter-mode content go to stdout; `--quiet`
suppresses status but never errors. A directory with no `.mds` files exits 1 with
`no .mds files found in <dir>; nothing was formatted`, even under `--quiet`.
Reads a `fmt` section from `mds.json`
(`{"fmt": {"sort_frontmatter_keys": true}}`) for forward compatibility — the field doesn't drive
any formatting behavior yet; frontmatter key sorting is deferred to a future version.

### Static analysis with `mds lint`

A 10-rule static analyzer that catches common template authoring issues:

```bash
mds lint template.mds           # lint a single file
mds lint .                      # lint all .mds files recursively (partials included)
mds lint --fix template.mds     # auto-fix fixable issues in place
mds lint --format json .        # machine-readable JSON output (stdout)
mds lint --quiet template.mds   # suppress output; exits 1 on warnings, 2 on errors
mds lint --quiet .              # directory lint: silent on clean/warn-only; summary prints on errors or resource limits
```

Directory mode (`mds lint <dir>`) lints every `.mds` file recursively (partials included) and
prints one summary line to stderr after processing all files:
`N clean, N with warnings, N with errors, N resource-limited`.
A directory with no `.mds` files exits 2 (lint's usage-error code) with
`no .mds files found in <dir>; nothing was linted` on stderr — under `--format json`, the error
document on stdout instead — even under `--quiet`, and prints no summary.
Under `--quiet`, the summary is suppressed when the worst outcome is warnings or clean; it is
always printed when any file has errors or hits a resource limit, so the non-zero exit is never
unexplained in those cases. Two exits are deliberately left unexplained under `--quiet`, because
in both the signal is status output rather than an error: a warn-only run (`mds lint --quiet
<dir>`) exits 1 with no diagnostics or summary on stderr, and `mds lint --fix --check --quiet
<dir>` with pending fixes exits 1 with zero stderr bytes. One known limitation: the depth-limit
warning for directory trees deeper than 64 levels is emitted regardless of `--quiet`. The JSON
stdout envelope is unchanged in directory mode (no `"summary"` key added).

Rules (configure via `mds.json` `lint.rules`; severities differ per rule):

| Rule | Severity | Description |
|------|----------|-------------|
| `unused-variable` | warn | Frontmatter variable defined but never referenced in the body |
| `unused-import` | warn | `@import` that is never referenced (Tier B: report-only in practice — no `fix_removals` wired; a file with imports is never structural-standalone) |
| `unused-function` | warn | `@define` function that is never called (Tier B: auto-fixed only for standalone files) |
| `shadow-variable` | off/info | Inner-scope variable shadows an outer-scope variable (must be enabled via `mds.json`) |
| `empty-block` | warn | `@if`/`@elseif`/`@else`/`@for`/`@define`/`@message` body is empty or whitespace-only (auto-fixable) |
| `legacy-interpolation` | warn | Single-brace `{x}` syntax from MDS v0.x; migrates to `{{x}}` automatically (auto-fixable) |
| `redundant-else` | warn | `@else` body is structurally identical to the `@if`/`@elseif` then-body |
| `unreachable-branch` | **error** | Branch condition is always-true or always-false (auto-fixable) |
| `duplicate-import` | **error** | Same file imported more than once (auto-fixable) |
| `duplicate-export` | **error** | Same export name defined more than once (auto-fixable) |

Exit codes: `0` = clean, `1` = warnings only, `2` = errors, analysis failure or I/O failure, `3` = resource limit, `101` = internal compiler error (a panic). With `--quiet`, diagnostics and status output are suppressed (the directory summary still prints when any file has errors or hits a resource limit); exit codes are unaffected. `info`-severity findings (e.g. `shadow-variable`) never raise the exit code regardless of `--quiet`.
JSON output shape: `{"files":[{"file":"…","diagnostics":[…]}],"truncated":false,"version":1}`.

## Project root

The compiler enforces import containment: every resolved import path must stay inside
the **project root**. The root is discovered by walking upward from the template's
directory until a `.git` or `.mdsroot` marker is found. In most repositories the
`.git` directory already serves as the marker.

**When imports are rejected with a containment error**, the likely cause is that the
inferred root is too narrow. This happens when your template sits in a subdirectory
that has its own marker closer to it than the repository's `.git`. To pin the root to
a specific directory, create a `.mdsroot` marker there:

```bash
touch .mdsroot
```

An empty file works. A common pattern is to place `.mdsroot` at the root of a prompt
library that lives inside a larger monorepo, so that templates can freely import from
any directory in the library.

The nearest-ancestor marker wins, regardless of which kind it is — placing `.mdsroot`
in a subdirectory narrows the boundary rather than widening it. If you need a wider
boundary, place `.mdsroot` higher up.

## Bundler Integration

Import `.mds` templates directly in Vite, Rollup, Webpack, and Rspack projects:

```ts
import systemPrompt from './prompts/system.mds';
// systemPrompt is the compiled Markdown string
```

| Package | Bundler | Version |
|---------|---------|---------|
| [`@mdscript/vite-plugin`](packages/vite-plugin/README.md) | Vite | ^5 \|\| ^6 \|\| ^7 \|\| ^8 |
| [`@mdscript/rollup-plugin`](packages/rollup-plugin/README.md) | Rollup | ^3 \|\| ^4 |
| [`@mdscript/webpack-loader`](packages/webpack-loader/README.md) | Webpack | ^5 |
| [`@mdscript/rspack-loader`](packages/rspack-loader/README.md) | Rspack | ^1 |

All plugins require `@mdscript/mds` as a peer dependency and accept `{ vars?: Record<string, unknown> }` for runtime template variables. See each package README for configuration details.

TypeScript module declarations (`.mds` → `string | MdsMessage[]`) are provided by `@mdscript/bundler-utils/mds`. The kind is intrinsic to the template content: Markdown templates produce a `string`; templates with `@message` blocks produce an `MdsMessage[]`.

## Library Usage

### TypeScript / JavaScript

```ts
import { init, compile, compileFile, isMdsError } from '@mdscript/mds';

await init();

// Compile a string — result is a discriminated union based on template content
const result = compile('---\nname: World\n---\nHello {{name}}!\n');
if (result.kind === 'markdown') {
  console.log(result.output);      // string
} else {
  console.log(result.messages);    // { role: string; content: string }[]
}

// Override variables at runtime
const result2 = compile(source, { vars: { env: 'production' } });

// Compile a file (resolves @import directives)
const fileResult = await compileFile('./prompts/system.mds');
if (fileResult.kind === 'markdown') {
  console.log(fileResult.output, fileResult.dependencies);
} else {
  console.log(fileResult.messages, fileResult.dependencies);
}

// Source Map v3 (Markdown templates only)
const smResult = compile(source, { sourceMap: true });
if (smResult.kind === 'markdown' && smResult.sourceMap) {
  console.log(smResult.sourceMap.version);   // 3
  console.log(smResult.sourceMap.mappings);  // Base64-VLQ string
}
// ⚠ Privacy: sourcesContent embeds the full template source — only use in trusted environments.
const smWithContent = compile(source, { sourceMap: true, sourcesContent: true });

// Error handling
try {
  compile('Hello {{undefined_var}}!');
} catch (err) {
  if (isMdsError(err)) console.error(err.code, err.span);
}
```

`@mdscript/mds` uses a native addon on Node.js with an automatic WASM fallback, and runs in the browser via WASM.

### Rust

```rust
let output = mds::compile(Path::new("template.mds"), None)?;
let output = mds::compile_str("---\nname: World\n---\nHello {{name}}!\n")?;
let formatted = mds::format_str("Hello   {{name}}!\n")?;
```

## Examples

Runnable templates, a Node.js API demo, and Vite/Rollup/Webpack/Rspack integration apps
live in [`examples/`](examples/).

## Language Reference

See [spec.md](spec.md) for the full MDS v0.4.0 language specification.

## Contributing

Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for the local
workflow and quality gates. By participating you agree to the
[Contributor Covenant 2.1](CODE_OF_CONDUCT.md).

## Security

Please report vulnerabilities privately via GitHub's
[private vulnerability reporting](https://github.com/dean0x/mdscript/security/advisories/new),
not public issues. See [SECURITY.md](SECURITY.md) for the security model, built-in
resource limits, and supported versions.

## License

MIT. See [LICENSE](LICENSE).