@p10i/flowmatter 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -73,18 +73,30 @@ Build a glob relative to the current directory:
73
73
  flowmatter "docs/**/*.md" --output site --title "Order processing"
74
74
  ```
75
75
 
76
+ The explicit `build` command is equivalent and is preferable in automation:
77
+
78
+ ```sh
79
+ flowmatter build "docs/**/*.md" --output site --title "Order processing"
80
+ ```
81
+
76
82
  The default output directory is `flowmatter-dist`. It contains `flow.html`
77
83
  and one `.html` page per source file with the same relative path. Existing
78
84
  generated files are not overwritten unless `--force` is passed.
79
85
 
80
86
  ```text
81
- Usage: flowmatter <folder-or-glob> [options]
82
-
83
- Options:
87
+ Usage: flowmatter build <folder-or-glob> [options]
88
+ flowmatter <folder-or-glob> [options]
89
+ flowmatter validate <folder-or-glob> [--json]
90
+ flowmatter schema
91
+ flowmatter example
92
+ flowmatter skill
93
+
94
+ Build options:
84
95
  -o, --output <directory> Output directory (default: flowmatter-dist)
85
96
  --flow <filename> Flow HTML filename (default: flow.html)
86
97
  --title <title> Override the flow title
87
98
  -f, --force Overwrite generated files
99
+ --json Print the build result as JSON
88
100
  -h, --help Show help
89
101
  -v, --version Show the package version
90
102
  ```
@@ -93,10 +105,60 @@ Malformed frontmatter, duplicate IDs, conflicting module definitions, missing
93
105
  relation targets, invalid generated flow data, and output collisions fail the
94
106
  build with a nonzero exit code.
95
107
 
108
+ ## Agent discovery
109
+
110
+ Agents can inspect the supported frontmatter, retrieve a complete multi-file
111
+ example, and validate their work without creating output files:
112
+
113
+ ```sh
114
+ flowmatter --help
115
+ flowmatter schema
116
+ flowmatter example
117
+ flowmatter skill
118
+ flowmatter validate "docs/**/*.md" --json
119
+ flowmatter build "docs/**/*.md" --output site --json
120
+ ```
121
+
122
+ `schema` and `example` print only formatted JSON. `skill` prints the bundled
123
+ standards-compliant Agent Skill. The example has a `files`
124
+ object whose keys are relative paths and whose values are complete Markdown
125
+ documents. JSON validation reports have this shape:
126
+
127
+ ```json
128
+ {
129
+ "valid": false,
130
+ "errors": [
131
+ {
132
+ "code": "missing_relation_target",
133
+ "path": "orders/place.md",
134
+ "message": "orders/place.md: relation target \"capture-payment\" does not exist"
135
+ }
136
+ ],
137
+ "warnings": [],
138
+ "stats": null
139
+ }
140
+ ```
141
+
142
+ The schema and example can also be imported from the package:
143
+
144
+ ```js
145
+ import schema from "@p10i/flowmatter/schema/frontmatter.schema.json" with { type: "json" };
146
+ import example from "@p10i/flowmatter/examples/order-processing.json" with { type: "json" };
147
+ ```
148
+
149
+ The skill is exported as `@p10i/flowmatter/skills/flowmatter/SKILL.md` for
150
+ agent tooling that installs skills from package resources.
151
+
152
+ The recommended agent loop is: inspect help, inspect the schema and example,
153
+ generate Markdown, run JSON validation until it succeeds, then build.
154
+
96
155
  ## Library
97
156
 
98
157
  ```js
99
- import { buildSite } from "@p10i/flowmatter";
158
+ import { buildSite, validateSite } from "@p10i/flowmatter";
159
+
160
+ const validation = await validateSite({ input: "docs/**/*.md" });
161
+ if (!validation.valid) console.error(validation.errors);
100
162
 
101
163
  const result = await buildSite({
102
164
  input: "docs/**/*.md",
@@ -1,40 +1,47 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { buildSite, FlowmatterError } from "../src/index.mjs";
3
+ import { readFile } from "node:fs/promises";
4
+ import { buildSite, FlowmatterError, validateSite } from "../src/index.mjs";
4
5
 
5
- const HELP = `Usage: flowmatter <folder-or-glob> [options]
6
+ const HELP = `Usage: flowmatter build <folder-or-glob> [options]
7
+ flowmatter <folder-or-glob> [options]
8
+ flowmatter validate <folder-or-glob> [--json]
9
+ flowmatter schema
10
+ flowmatter example
11
+ flowmatter skill
6
12
 
7
13
  Generate a flowjob map and standalone HTML pages from Markdown files.
8
14
 
9
- Options:
15
+ Build options:
10
16
  -o, --output <directory> Output directory (default: flowmatter-dist)
11
17
  --flow <filename> Flow HTML filename (default: flow.html)
12
18
  --title <title> Override the flow title
13
19
  -f, --force Overwrite generated files
20
+ --json Print the build result as JSON
14
21
  -h, --help Show this help
15
22
  -v, --version Show the package version`;
16
23
 
17
24
  function fail(message, exitCode = 2) {
18
- console.error(message);
25
+ console.error(`flowmatter: ${message}`);
19
26
  process.exitCode = exitCode;
20
27
  }
21
28
 
22
29
  function takeValue(args, index, option) {
23
30
  const value = args[index + 1];
24
- if (!value || value.startsWith("-")) {
25
- throw new Error(`${option} requires a value`);
26
- }
31
+ if (!value || value.startsWith("-")) throw new Error(`${option} requires a value`);
27
32
  return value;
28
33
  }
29
34
 
30
- function parseArgs(args) {
31
- const options = { force: false };
35
+ function parseInputOptions(args) {
36
+ const options = { force: false, json: false };
32
37
  const inputs = [];
33
38
 
34
39
  for (let index = 0; index < args.length; index += 1) {
35
40
  const argument = args[index];
36
41
  if (argument === "-f" || argument === "--force") {
37
42
  options.force = true;
43
+ } else if (argument === "--json") {
44
+ options.json = true;
38
45
  } else if (argument === "-o" || argument === "--output") {
39
46
  options.outputDir = takeValue(args, index, argument);
40
47
  index += 1;
@@ -45,36 +52,93 @@ function parseArgs(args) {
45
52
  options.title = takeValue(args, index, argument);
46
53
  index += 1;
47
54
  } else if (argument.startsWith("-")) {
48
- throw new Error(`Unknown option: ${argument}`);
55
+ throw new Error(`unknown option ${argument}`);
49
56
  } else {
50
57
  inputs.push(argument);
51
58
  }
52
59
  }
53
60
 
54
- if (inputs.length !== 1) {
55
- throw new Error("Exactly one folder or glob is required");
56
- }
61
+ if (inputs.length !== 1) throw new Error("exactly one folder or glob is required");
57
62
  return { input: inputs[0], ...options };
58
63
  }
59
64
 
60
- const args = process.argv.slice(2);
61
- if (args.includes("-h") || args.includes("--help")) {
62
- console.log(HELP);
63
- } else if (args.includes("-v") || args.includes("--version")) {
64
- console.log("0.1.0");
65
- } else {
66
- try {
67
- const result = await buildSite(parseArgs(args));
68
- console.log(
69
- `Generated ${result.pageCount} page${result.pageCount === 1 ? "" : "s"} and ${result.flowPath}`,
70
- );
71
- } catch (error) {
72
- if (error instanceof FlowmatterError) {
73
- fail(error.message, 1);
74
- } else if (error instanceof Error) {
75
- fail(error.message);
65
+ async function printBundledJson(relativePath) {
66
+ const value = JSON.parse(await readFile(new URL(relativePath, import.meta.url), "utf8"));
67
+ console.log(JSON.stringify(value, null, 2));
68
+ }
69
+
70
+ async function main() {
71
+ const args = process.argv.slice(2);
72
+ if (args.includes("-h") || args.includes("--help")) {
73
+ console.log(HELP);
74
+ return;
75
+ }
76
+ if (args.includes("-v") || args.includes("--version")) {
77
+ const manifest = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
78
+ console.log(manifest.version);
79
+ return;
80
+ }
81
+
82
+ const command = args[0];
83
+ if (["schema", "example", "skill"].includes(command)) {
84
+ if (args.length !== 1) throw new Error(`${command} does not accept arguments or options`);
85
+ if (command === "skill") {
86
+ process.stdout.write(await readFile(new URL("../skills/flowmatter/SKILL.md", import.meta.url), "utf8"));
87
+ return;
88
+ }
89
+ await printBundledJson(command === "schema"
90
+ ? "../schema/frontmatter.schema.json"
91
+ : "../examples/order-processing.json");
92
+ return;
93
+ }
94
+
95
+ if (command === "validate") {
96
+ const parsed = parseInputOptions(args.slice(1));
97
+ if (parsed.force || parsed.outputDir || parsed.flowFile) {
98
+ throw new Error("validate only accepts --title and --json");
99
+ }
100
+ const validation = await validateSite(parsed);
101
+ if (parsed.json) {
102
+ const { flow, ...report } = validation;
103
+ console.log(JSON.stringify(report));
104
+ }
105
+ else if (validation.valid) {
106
+ console.log(`${parsed.input} is valid (${validation.stats.files} files, ${validation.stats.relations} relations)`);
76
107
  } else {
77
- throw error;
108
+ console.log(validation.errors.map((error) => error.message).join("\n"));
78
109
  }
110
+ if (!validation.valid) process.exitCode = 1;
111
+ return;
112
+ }
113
+
114
+ const parsed = parseInputOptions(command === "build" ? args.slice(1) : args);
115
+ const { json, ...buildOptions } = parsed;
116
+ const result = await buildSite(buildOptions);
117
+ if (json) {
118
+ console.log(JSON.stringify({
119
+ ok: true,
120
+ flowPath: result.flowPath,
121
+ outputDir: result.outputDir,
122
+ pageCount: result.pageCount,
123
+ pages: result.pages,
124
+ }));
125
+ } else {
126
+ console.log(`Generated ${result.pageCount} page${result.pageCount === 1 ? "" : "s"} and ${result.flowPath}`);
79
127
  }
80
128
  }
129
+
130
+ main().catch((error) => {
131
+ if (process.argv.includes("--json")) {
132
+ console.error(JSON.stringify({
133
+ ok: false,
134
+ error: {
135
+ code: error instanceof FlowmatterError ? error.code : "runtime_error",
136
+ path: error instanceof FlowmatterError ? error.path : null,
137
+ message: error instanceof Error ? error.message : String(error),
138
+ },
139
+ }));
140
+ } else {
141
+ fail(error instanceof Error ? error.message : String(error), error instanceof FlowmatterError ? 1 : 2);
142
+ }
143
+ process.exitCode ||= error instanceof FlowmatterError ? 1 : 2;
144
+ });
@@ -0,0 +1,6 @@
1
+ {
2
+ "files": {
3
+ "orders/place.md": "---\nid: place-order\ntitle: Place order\nmodule:\n id: orders\n name: Orders\n type: application\nrelations:\n - id: capture-call\n to: capture-payment\n type: capturePayment()\n relationType: call\n---\n\n# Place order\n\nValidate the order and request payment.\n",
4
+ "payments/capture.md": "---\nid: capture-payment\ntitle: Capture payment\nmodule:\n id: payments\n name: Payments\n type: integration\n---\n\n# Capture payment\n\nAuthorize and capture the payment.\n"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,15 +1,23 @@
1
1
  {
2
2
  "name": "@p10i/flowmatter",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Generate flowjob maps and linked HTML pages from Markdown frontmatter.",
5
5
  "type": "module",
6
- "exports": "./src/index.mjs",
6
+ "exports": {
7
+ ".": "./src/index.mjs",
8
+ "./schema/frontmatter.schema.json": "./schema/frontmatter.schema.json",
9
+ "./examples/order-processing.json": "./examples/order-processing.json",
10
+ "./skills/flowmatter/SKILL.md": "./skills/flowmatter/SKILL.md"
11
+ },
7
12
  "bin": {
8
13
  "flowmatter": "bin/flowmatter.mjs"
9
14
  },
10
15
  "files": [
11
16
  "bin/",
12
17
  "src/",
18
+ "schema/",
19
+ "examples/",
20
+ "skills/",
13
21
  "README.md",
14
22
  "LICENSE"
15
23
  ],
@@ -0,0 +1,69 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://github.com/piontkovsk11andre1/flowmatter/schema/frontmatter.schema.json",
4
+ "title": "Flowmatter Markdown frontmatter",
5
+ "description": "Frontmatter fields supported by one Flowmatter Markdown document.",
6
+ "type": "object",
7
+ "properties": {
8
+ "id": {
9
+ "type": "string",
10
+ "pattern": "\\S",
11
+ "description": "Stable document ID. Defaults to the relative Markdown path without its extension."
12
+ },
13
+ "title": {
14
+ "type": "string",
15
+ "pattern": "\\S",
16
+ "description": "Display title. Defaults to the first level-one heading, then the filename."
17
+ },
18
+ "module": {
19
+ "description": "Parent flowjob module. A string is shorthand for a named module with a slug-derived ID.",
20
+ "oneOf": [
21
+ {
22
+ "type": "string",
23
+ "pattern": "\\S"
24
+ },
25
+ {
26
+ "type": "object",
27
+ "properties": {
28
+ "id": { "type": "string", "pattern": "\\S" },
29
+ "name": { "type": "string", "pattern": "\\S" },
30
+ "type": { "type": "string", "pattern": "\\S" }
31
+ },
32
+ "additionalProperties": true
33
+ }
34
+ ]
35
+ },
36
+ "relations": {
37
+ "type": "array",
38
+ "description": "Directed relations from this document to documents selected by ID.",
39
+ "items": {
40
+ "type": "object",
41
+ "required": ["to", "type"],
42
+ "properties": {
43
+ "id": {
44
+ "type": "string",
45
+ "pattern": "\\S",
46
+ "description": "Stable relation ID. Defaults to <document-id>:<one-based-index>."
47
+ },
48
+ "to": {
49
+ "type": "string",
50
+ "pattern": "\\S",
51
+ "description": "Target document ID."
52
+ },
53
+ "type": {
54
+ "type": "string",
55
+ "pattern": "\\S",
56
+ "description": "Flow label."
57
+ },
58
+ "relationType": {
59
+ "type": "string",
60
+ "pattern": "\\S",
61
+ "description": "Optional flowjob relation styling/filter key."
62
+ }
63
+ },
64
+ "additionalProperties": true
65
+ }
66
+ }
67
+ },
68
+ "additionalProperties": true
69
+ }
@@ -0,0 +1,53 @@
1
+ ---
2
+ name: flowmatter
3
+ description: Generate and validate interactive flow maps and linked standalone HTML pages from relationships in Markdown frontmatter. Use when creating, editing, checking, or rendering a set of Flowmatter Markdown documents.
4
+ license: ISC
5
+ compatibility: Requires Node.js 20 or newer and the @p10i/flowmatter package.
6
+ metadata:
7
+ author: p10i
8
+ version: "0.1.1"
9
+ ---
10
+
11
+ # Flowmatter
12
+
13
+ Use Flowmatter to model directed relationships between Markdown documents and
14
+ render one interactive flowjob map plus linked standalone HTML pages.
15
+
16
+ ## Workflow
17
+
18
+ 1. Confirm the CLI is available with `flowmatter --version`. If it is not
19
+ installed, use `npx --package @p10i/flowmatter flowmatter` as the command.
20
+ 2. Run `flowmatter schema` and inspect the complete frontmatter schema.
21
+ 3. Run `flowmatter example` and inspect both files in the returned `files`
22
+ object. Relations require at least two documents unless they are self-links.
23
+ 4. Inspect the target Markdown files before editing them.
24
+ 5. Give documents stable `id` values when relations refer to them. Keep module
25
+ IDs and definitions consistent across files.
26
+ 6. Define each outgoing relation in its source document with non-empty `to`
27
+ and `type` values. The `to` value must equal a target document ID.
28
+ 7. Run `flowmatter validate <folder-or-glob> --json` before building.
29
+ 8. Resolve every item in `errors` and repeat validation until `valid` is true.
30
+ 9. Run `flowmatter build <folder-or-glob> --output <directory> --json`.
31
+ 10. Report the generated `flowPath`, page count, and output directory.
32
+
33
+ Always quote glob inputs so Flowmatter receives the pattern. Do not use
34
+ `--force` unless overwriting existing generated files is explicitly intended.
35
+ Do not edit generated HTML when the source Markdown can be corrected instead.
36
+
37
+ ## Minimal frontmatter
38
+
39
+ ```yaml
40
+ ---
41
+ id: place-order
42
+ title: Place order
43
+ module: Orders
44
+ relations:
45
+ - to: capture-payment
46
+ type: capturePayment()
47
+ relationType: call
48
+ ---
49
+ ```
50
+
51
+ Fields may be inferred, but explicit stable IDs are preferable for documents
52
+ that participate in relations. Use the schema output as the authoritative
53
+ field reference and JSON validation diagnostics as the authoritative check.
package/src/index.mjs CHANGED
@@ -32,9 +32,11 @@ article code { font-family: "SFMono-Regular", Consolas, monospace; }
32
32
  `;
33
33
 
34
34
  export class FlowmatterError extends Error {
35
- constructor(message) {
35
+ constructor(message, { code = "invalid_input", path: errorPath = null } = {}) {
36
36
  super(message);
37
37
  this.name = "FlowmatterError";
38
+ this.code = code;
39
+ this.path = errorPath;
38
40
  }
39
41
  }
40
42
 
@@ -75,16 +77,25 @@ function describeModule(value, relativePath) {
75
77
  return { id: slugify(value), name: value.trim() };
76
78
  }
77
79
  if (!isObject(value)) {
78
- throw new FlowmatterError(`${relativePath}: "module" must be a string or object`);
80
+ throw new FlowmatterError(`${relativePath}: "module" must be a string or object`, {
81
+ code: "invalid_module",
82
+ path: relativePath,
83
+ });
79
84
  }
80
85
 
81
86
  const id = value.id ?? (isNonEmptyString(value.name) ? slugify(value.name) : fallbackId);
82
87
  const name = value.name ?? (isNonEmptyString(value.id) ? value.id : fallbackName);
83
88
  if (!isNonEmptyString(id) || !isNonEmptyString(name)) {
84
- throw new FlowmatterError(`${relativePath}: module "id" and "name" must be non-empty strings`);
89
+ throw new FlowmatterError(`${relativePath}: module "id" and "name" must be non-empty strings`, {
90
+ code: "invalid_module",
91
+ path: relativePath,
92
+ });
85
93
  }
86
94
  if (value.type !== undefined && !isNonEmptyString(value.type)) {
87
- throw new FlowmatterError(`${relativePath}: module "type" must be a non-empty string`);
95
+ throw new FlowmatterError(`${relativePath}: module "type" must be a non-empty string`, {
96
+ code: "invalid_module",
97
+ path: relativePath,
98
+ });
88
99
  }
89
100
  return { id: id.trim(), name: name.trim(), ...(value.type ? { type: value.type.trim() } : {}) };
90
101
  }
@@ -92,19 +103,31 @@ function describeModule(value, relativePath) {
92
103
  function parseRelations(value, relativePath) {
93
104
  if (value === undefined) return [];
94
105
  if (!Array.isArray(value)) {
95
- throw new FlowmatterError(`${relativePath}: "relations" must be an array`);
106
+ throw new FlowmatterError(`${relativePath}: "relations" must be an array`, {
107
+ code: "invalid_relations",
108
+ path: relativePath,
109
+ });
96
110
  }
97
111
 
98
112
  return value.map((relation, index) => {
99
113
  const location = `${relativePath}: relations[${index}]`;
100
- if (!isObject(relation)) throw new FlowmatterError(`${location} must be an object`);
101
- if (!isNonEmptyString(relation.to)) throw new FlowmatterError(`${location}.to must be a non-empty string`);
102
- if (!isNonEmptyString(relation.type)) throw new FlowmatterError(`${location}.type must be a non-empty string`);
114
+ if (!isObject(relation)) {
115
+ throw new FlowmatterError(`${location} must be an object`, { code: "invalid_relation", path: relativePath });
116
+ }
117
+ if (!isNonEmptyString(relation.to)) {
118
+ throw new FlowmatterError(`${location}.to must be a non-empty string`, { code: "invalid_relation", path: relativePath });
119
+ }
120
+ if (!isNonEmptyString(relation.type)) {
121
+ throw new FlowmatterError(`${location}.type must be a non-empty string`, { code: "invalid_relation", path: relativePath });
122
+ }
103
123
  if (relation.id !== undefined && !isNonEmptyString(relation.id)) {
104
- throw new FlowmatterError(`${location}.id must be a non-empty string`);
124
+ throw new FlowmatterError(`${location}.id must be a non-empty string`, { code: "invalid_relation", path: relativePath });
105
125
  }
106
126
  if (relation.relationType !== undefined && !isNonEmptyString(relation.relationType)) {
107
- throw new FlowmatterError(`${location}.relationType must be a non-empty string`);
127
+ throw new FlowmatterError(`${location}.relationType must be a non-empty string`, {
128
+ code: "invalid_relation",
129
+ path: relativePath,
130
+ });
108
131
  }
109
132
  return {
110
133
  ...(relation.id ? { id: relation.id.trim() } : {}),
@@ -151,31 +174,50 @@ async function readDocuments(input, cwd) {
151
174
  .sort((left, right) => left.localeCompare(right));
152
175
 
153
176
  if (markdownFiles.length === 0) {
154
- throw new FlowmatterError(`No Markdown files matched "${input}"`);
177
+ throw new FlowmatterError(`No Markdown files matched "${input}"`, { code: "no_markdown_files", path: input });
155
178
  }
156
179
 
157
180
  const documents = await Promise.all(markdownFiles.map(async (sourcePath) => {
158
181
  const relativePath = toPosix(path.relative(baseDir, sourcePath));
159
182
  if (relativePath === ".." || relativePath.startsWith("../")) {
160
- throw new FlowmatterError(`${sourcePath}: matched file is outside the input root`);
183
+ throw new FlowmatterError(`${sourcePath}: matched file is outside the input root`, {
184
+ code: "outside_input_root",
185
+ path: sourcePath,
186
+ });
161
187
  }
162
188
 
163
189
  let parsed;
164
190
  try {
165
191
  parsed = matter(await readFile(sourcePath, "utf8"));
166
192
  } catch (error) {
167
- throw new FlowmatterError(`${relativePath}: invalid frontmatter (${error.message})`);
193
+ throw new FlowmatterError(`${relativePath}: invalid frontmatter (${error.message})`, {
194
+ code: "invalid_frontmatter",
195
+ path: relativePath,
196
+ });
168
197
  }
169
198
 
170
199
  if (!isObject(parsed.data)) {
171
- throw new FlowmatterError(`${relativePath}: frontmatter must be an object`);
200
+ throw new FlowmatterError(`${relativePath}: frontmatter must be an object`, {
201
+ code: "invalid_frontmatter",
202
+ path: relativePath,
203
+ });
172
204
  }
173
205
 
174
206
  const fallbackId = relativePath.replace(/\.md$/i, "");
175
207
  const id = parsed.data.id ?? fallbackId;
176
208
  const title = parsed.data.title ?? titleFromContent(parsed.content, path.posix.basename(fallbackId));
177
- if (!isNonEmptyString(id)) throw new FlowmatterError(`${relativePath}: "id" must be a non-empty string`);
178
- if (!isNonEmptyString(title)) throw new FlowmatterError(`${relativePath}: "title" must be a non-empty string`);
209
+ if (!isNonEmptyString(id)) {
210
+ throw new FlowmatterError(`${relativePath}: "id" must be a non-empty string`, {
211
+ code: "invalid_document_id",
212
+ path: relativePath,
213
+ });
214
+ }
215
+ if (!isNonEmptyString(title)) {
216
+ throw new FlowmatterError(`${relativePath}: "title" must be a non-empty string`, {
217
+ code: "invalid_document_title",
218
+ path: relativePath,
219
+ });
220
+ }
179
221
 
180
222
  return {
181
223
  id: id.trim(),
@@ -200,6 +242,7 @@ function compile(documents, title) {
200
242
  if (byId.has(document.id)) {
201
243
  throw new FlowmatterError(
202
244
  `${document.relativePath}: duplicate document id "${document.id}" (also used by ${byId.get(document.id).relativePath})`,
245
+ { code: "duplicate_document_id", path: document.relativePath },
203
246
  );
204
247
  }
205
248
  byId.set(document.id, document);
@@ -209,7 +252,10 @@ function compile(documents, title) {
209
252
  existing.name !== document.module.name
210
253
  || (existing.type && document.module.type && existing.type !== document.module.type)
211
254
  )) {
212
- throw new FlowmatterError(`${document.relativePath}: module "${document.module.id}" conflicts with an earlier definition`);
255
+ throw new FlowmatterError(`${document.relativePath}: module "${document.module.id}" conflicts with an earlier definition`, {
256
+ code: "conflicting_module",
257
+ path: document.relativePath,
258
+ });
213
259
  }
214
260
  if (!existing) modules.set(document.module.id, { ...document.module, submodules: [] });
215
261
  if (existing && !existing.type && document.module.type) existing.type = document.module.type;
@@ -221,11 +267,17 @@ function compile(documents, title) {
221
267
  document.relations.forEach((relation, index) => {
222
268
  const target = byId.get(relation.to);
223
269
  if (!target) {
224
- throw new FlowmatterError(`${document.relativePath}: relation target "${relation.to}" does not exist`);
270
+ throw new FlowmatterError(`${document.relativePath}: relation target "${relation.to}" does not exist`, {
271
+ code: "missing_relation_target",
272
+ path: document.relativePath,
273
+ });
225
274
  }
226
275
  const id = relation.id ?? `${document.id}:${index + 1}`;
227
276
  if (flowIds.has(id)) {
228
- throw new FlowmatterError(`${document.relativePath}: duplicate relation id "${id}" (also used by ${flowIds.get(id)})`);
277
+ throw new FlowmatterError(`${document.relativePath}: duplicate relation id "${id}" (also used by ${flowIds.get(id)})`, {
278
+ code: "duplicate_relation_id",
279
+ path: document.relativePath,
280
+ });
229
281
  }
230
282
  flowIds.set(id, document.relativePath);
231
283
  flows.push({
@@ -247,11 +299,42 @@ function compile(documents, title) {
247
299
  const validation = validateFlow(flow);
248
300
  if (!validation.valid) {
249
301
  const diagnostics = validation.errors.map((error) => error.message ?? String(error)).join("; ");
250
- throw new FlowmatterError(`Generated flow is invalid: ${diagnostics}`);
302
+ throw new FlowmatterError(`Generated flow is invalid: ${diagnostics}`, { code: "invalid_flow" });
251
303
  }
252
304
  return { byId, flow };
253
305
  }
254
306
 
307
+ export async function validateSite({ input, title, cwd = process.cwd() } = {}) {
308
+ try {
309
+ if (!isNonEmptyString(input)) throw new FlowmatterError("A folder or glob input is required");
310
+ if (title !== undefined && !isNonEmptyString(title)) {
311
+ throw new FlowmatterError("The title must be a non-empty string");
312
+ }
313
+ const { baseDir, documents } = await readDocuments(input, path.resolve(cwd));
314
+ const siteTitle = title?.trim() ?? titleFromContent("", path.basename(baseDir));
315
+ const { flow } = compile(documents, siteTitle);
316
+ return {
317
+ valid: true,
318
+ errors: [],
319
+ warnings: [],
320
+ stats: {
321
+ files: documents.length,
322
+ modules: flow.modules.length,
323
+ relations: flow.flows.length,
324
+ },
325
+ flow,
326
+ };
327
+ } catch (error) {
328
+ if (!(error instanceof FlowmatterError)) throw error;
329
+ return {
330
+ valid: false,
331
+ errors: [{ code: error.code, path: error.path, message: error.message }],
332
+ warnings: [],
333
+ stats: null,
334
+ };
335
+ }
336
+ }
337
+
255
338
  function escapeHtml(value) {
256
339
  return String(value)
257
340
  .replaceAll("&", "&amp;")