@p10i/flowmatter 0.1.0 → 0.1.2

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
@@ -1,6 +1,6 @@
1
1
  # flowmatter
2
2
 
3
- `flowmatter` turns a folder or glob of Markdown files into one interactive
3
+ `flowmatter` turns Markdown files selected by path, folder, or glob into one interactive
4
4
  [flowjob](https://github.com/piontkovsk11andre1/flowjob) map and a mirrored tree
5
5
  of linked, standalone HTML pages.
6
6
 
@@ -16,7 +16,7 @@ npm install @p10i/flowmatter
16
16
 
17
17
  ## Markdown schema
18
18
 
19
- Each Markdown file is a flowjob submodule. Its frontmatter defines its stable
19
+ Each non-config Markdown file is a flowjob submodule. Its frontmatter defines its stable
20
20
  identity, parent module, and outgoing relations:
21
21
 
22
22
  ```markdown
@@ -43,6 +43,30 @@ Validate the order and request payment.
43
43
  flow label. `relations[].id` and `relations[].relationType` are optional; an
44
44
  omitted relation ID is generated as `<document-id>:<one-based-index>`.
45
45
 
46
+ To give a connection its own **View** page, set `viewUrl: ../notes/retry-policy.md` on the relation. The path is relative to the declaring document; include the target in the build inputs. A referenced plain Markdown file needs no frontmatter: it renders once in the output directory without becoming a graph item. Multiple connections can share the page.
47
+
48
+ Any input document can define map-wide styles in its frontmatter:
49
+
50
+ ```yaml
51
+ relationTypes:
52
+ call: { label: Call, color: "#1565c0" }
53
+ ```
54
+
55
+ A relation with `relationType: call` uses that style; its `type` remains the individual connection label. Definitions merge by type and property across documents. Identical values are allowed, and conflicting values report both paths. An undeclared type keeps the default style. Optional `color` and `previewColor` accept quoted hex colors (3, 4, 6 or 8 digits).
56
+
57
+ For a shared palette, include a Markdown file such as `styles.md`:
58
+
59
+ ```yaml
60
+ ---
61
+ flowmatter: config
62
+ relationTypes:
63
+ - { id: call, label: Call, color: "#1565c0" }
64
+ - { id: event, label: Event, color: "#c60" }
65
+ ---
66
+ ```
67
+
68
+ Either declaration form works in ordinary documents and config files. Lists are read in declaration order. A config contributes only definitions: it has no node, page, or target ID. Include at least one ordinary document.
69
+
46
70
  The following values are inferred when omitted:
47
71
 
48
72
  | Field | Default |
@@ -61,6 +85,24 @@ module: Orders
61
85
 
62
86
  ## CLI
63
87
 
88
+ ### Preview while editing
89
+
90
+ `flowmatter serve docs --port 4173` serves the map at `http://127.0.0.1:4173/` and watches the same files, directories and quoted globs accepted by `build`. Refresh the browser after editing. New and removed pages are reflected together with the rebuilt map. Invalid edits are reported in the terminal; after startup, the last successful preview stays available until the inputs are valid again. The preview is in memory. Use `build` to write a distributable site, and Ctrl+C to stop serving.
91
+
92
+ ### Module colors
93
+
94
+ A module can open its own documentation: set `module: {name: Orders, viewUrl: ./Overview.md}` on any one of its items. Include the overview in the build inputs. Plain Markdown overviews render as pages without becoming map items. Declarations for the same module must resolve to the same page.
95
+
96
+ Use `module.type` to select a graph card palette. The definition can live on the same page or in a shared config document. Like `relationTypes`, `moduleTypes` accepts a mapping or a list and merges declarations across pages.
97
+
98
+ ```yaml
99
+ module: {name: Orders, type: domain}
100
+ moduleTypes:
101
+ domain: {accent: '#287768', headerBg: '#D9F0EA', headerFg: '#123D36'}
102
+ ```
103
+
104
+ Dark mode derives the card tint from `accent`.
105
+
64
106
  Build every Markdown file under a directory:
65
107
 
66
108
  ```sh
@@ -73,18 +115,33 @@ Build a glob relative to the current directory:
73
115
  flowmatter "docs/**/*.md" --output site --title "Order processing"
74
116
  ```
75
117
 
118
+ The explicit `build` command is equivalent and is preferable in automation:
119
+
120
+ ```sh
121
+ flowmatter build styles.md "docs/**/*.md" --output site --title "Order processing"
122
+ ```
123
+
76
124
  The default output directory is `flowmatter-dist`. It contains `flow.html`
77
- and one `.html` page per source file with the same relative path. Existing
125
+ and one `.html` page per non-config document. Each input must match Markdown;
126
+ overlapping paths are processed once. Mirrored paths, inferred IDs, and the
127
+ default title use the common ancestor of the input roots (a file's parent,
128
+ the selected directory, or the directory before a glob's first wildcard). Existing
78
129
  generated files are not overwritten unless `--force` is passed.
79
130
 
80
131
  ```text
81
- Usage: flowmatter <folder-or-glob> [options]
82
-
83
- Options:
132
+ Usage: flowmatter build <path-or-glob>... [options]
133
+ flowmatter <path-or-glob>... [options]
134
+ flowmatter validate <path-or-glob>... [--json]
135
+ flowmatter schema
136
+ flowmatter example
137
+ flowmatter skill
138
+
139
+ Build options:
84
140
  -o, --output <directory> Output directory (default: flowmatter-dist)
85
141
  --flow <filename> Flow HTML filename (default: flow.html)
86
142
  --title <title> Override the flow title
87
143
  -f, --force Overwrite generated files
144
+ --json Print the build result as JSON
88
145
  -h, --help Show help
89
146
  -v, --version Show the package version
90
147
  ```
@@ -93,13 +150,64 @@ Malformed frontmatter, duplicate IDs, conflicting module definitions, missing
93
150
  relation targets, invalid generated flow data, and output collisions fail the
94
151
  build with a nonzero exit code.
95
152
 
153
+ ## Agent discovery
154
+
155
+ Agents can inspect the supported frontmatter, retrieve a complete multi-file
156
+ example, and validate their work without creating output files:
157
+
158
+ ```sh
159
+ flowmatter --help
160
+ flowmatter schema
161
+ flowmatter example
162
+ flowmatter skill
163
+ flowmatter validate "docs/**/*.md" --json
164
+ flowmatter build "docs/**/*.md" --output site --json
165
+ ```
166
+
167
+ `schema` and `example` print only formatted JSON. `skill` prints the bundled
168
+ standards-compliant Agent Skill. The example has a `files`
169
+ object whose keys are relative paths and whose values are complete Markdown
170
+ documents. JSON validation reports have this shape:
171
+
172
+ ```json
173
+ {
174
+ "valid": false,
175
+ "errors": [
176
+ {
177
+ "code": "missing_relation_target",
178
+ "path": "orders/place.md",
179
+ "message": "orders/place.md: relation target \"capture-payment\" does not exist"
180
+ }
181
+ ],
182
+ "warnings": [],
183
+ "stats": null
184
+ }
185
+ ```
186
+
187
+ The schema and example can also be imported from the package:
188
+
189
+ ```js
190
+ import schema from "@p10i/flowmatter/schema/frontmatter.schema.json" with { type: "json" };
191
+ import example from "@p10i/flowmatter/examples/order-processing.json" with { type: "json" };
192
+ ```
193
+
194
+ The skill is exported as `@p10i/flowmatter/skills/flowmatter/SKILL.md` for
195
+ agent tooling that installs skills from package resources.
196
+
197
+ The recommended agent loop is: inspect help, inspect the schema and example,
198
+ generate Markdown, run JSON validation until it succeeds, then build.
199
+
96
200
  ## Library
97
201
 
98
202
  ```js
99
- import { buildSite } from "@p10i/flowmatter";
203
+ import { buildSite, validateSite } from "@p10i/flowmatter";
204
+
205
+ const input = ["styles.md", "docs/**/*.md"]; // A single string also works.
206
+ const validation = await validateSite({ input });
207
+ if (!validation.valid) console.error(validation.errors);
100
208
 
101
209
  const result = await buildSite({
102
- input: "docs/**/*.md",
210
+ input,
103
211
  outputDir: "site",
104
212
  title: "Order processing",
105
213
  });
@@ -1,40 +1,52 @@
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 <path-or-glob>... [options]
7
+ flowmatter <path-or-glob>... [options]
8
+ flowmatter validate <path-or-glob>... [--json]
9
+ flowmatter serve <path-or-glob>... [--port 4173] [--title <title>] [--flow <filename>]
10
+ flowmatter schema
11
+ flowmatter example
12
+ flowmatter skill
6
13
 
7
14
  Generate a flowjob map and standalone HTML pages from Markdown files.
8
15
 
9
- Options:
16
+ Build options:
10
17
  -o, --output <directory> Output directory (default: flowmatter-dist)
11
18
  --flow <filename> Flow HTML filename (default: flow.html)
12
19
  --title <title> Override the flow title
13
20
  -f, --force Overwrite generated files
21
+ --json Print the build result as JSON
14
22
  -h, --help Show this help
15
23
  -v, --version Show the package version`;
16
24
 
17
25
  function fail(message, exitCode = 2) {
18
- console.error(message);
26
+ console.error(`flowmatter: ${message}`);
19
27
  process.exitCode = exitCode;
20
28
  }
21
29
 
22
30
  function takeValue(args, index, option) {
23
31
  const value = args[index + 1];
24
- if (!value || value.startsWith("-")) {
25
- throw new Error(`${option} requires a value`);
26
- }
32
+ if (!value || value.startsWith("-")) throw new Error(`${option} requires a value`);
27
33
  return value;
28
34
  }
29
35
 
30
- function parseArgs(args) {
31
- const options = { force: false };
36
+ function parseInputOptions(args, serve = false) {
37
+ const options = { force: false, json: false };
32
38
  const inputs = [];
33
39
 
34
40
  for (let index = 0; index < args.length; index += 1) {
35
41
  const argument = args[index];
36
- if (argument === "-f" || argument === "--force") {
42
+ if (serve && argument === '--port') {
43
+ const raw = takeValue(args,index++,argument);
44
+ if (!/^\d+$/.test(raw) || Number(raw)>65535) throw new Error('Expected --port 0–65535');
45
+ options.port = Number(raw);
46
+ } else if (argument === "-f" || argument === "--force") {
37
47
  options.force = true;
48
+ } else if (argument === "--json") {
49
+ options.json = true;
38
50
  } else if (argument === "-o" || argument === "--output") {
39
51
  options.outputDir = takeValue(args, index, argument);
40
52
  index += 1;
@@ -45,36 +57,102 @@ function parseArgs(args) {
45
57
  options.title = takeValue(args, index, argument);
46
58
  index += 1;
47
59
  } else if (argument.startsWith("-")) {
48
- throw new Error(`Unknown option: ${argument}`);
60
+ throw new Error(`unknown option ${argument}`);
49
61
  } else {
50
62
  inputs.push(argument);
51
63
  }
52
64
  }
53
65
 
54
- if (inputs.length !== 1) {
55
- throw new Error("Exactly one folder or glob is required");
56
- }
57
- return { input: inputs[0], ...options };
66
+ if (!inputs.length) throw new Error("at least one Markdown path or glob is required");
67
+ return { input: inputs, ...options };
58
68
  }
59
69
 
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);
70
+ async function printBundledJson(relativePath) {
71
+ const value = JSON.parse(await readFile(new URL(relativePath, import.meta.url), "utf8"));
72
+ console.log(JSON.stringify(value, null, 2));
73
+ }
74
+
75
+ async function main() {
76
+ const args = process.argv.slice(2);
77
+ if (args.includes("-h") || args.includes("--help")) {
78
+ console.log(HELP);
79
+ return;
80
+ }
81
+ if (args.includes("-v") || args.includes("--version")) {
82
+ const manifest = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
83
+ console.log(manifest.version);
84
+ return;
85
+ }
86
+
87
+ const command = args[0];
88
+ if (command === 'serve') {
89
+ const options = parseInputOptions(args.slice(1),true);
90
+ if (options.outputDir || options.force || options.json) throw new Error('serve accepts --flow, --title and --port');
91
+ const {serveSite} = await import('../src/serve.mjs');
92
+ const preview = await serveSite(options);
93
+ console.log(`Serving ${preview.url} (watching Markdown; refresh to see changes)`);
94
+ for (const signal of ['SIGINT','SIGTERM']) process.once(signal,()=>preview.close());
95
+ return;
96
+ }
97
+ if (["schema", "example", "skill"].includes(command)) {
98
+ if (args.length !== 1) throw new Error(`${command} does not accept arguments or options`);
99
+ if (command === "skill") {
100
+ process.stdout.write(await readFile(new URL("../skills/flowmatter/SKILL.md", import.meta.url), "utf8"));
101
+ return;
102
+ }
103
+ await printBundledJson(command === "schema"
104
+ ? "../schema/frontmatter.schema.json"
105
+ : "../examples/order-processing.json");
106
+ return;
107
+ }
108
+
109
+ if (command === "validate") {
110
+ const parsed = parseInputOptions(args.slice(1));
111
+ if (parsed.force || parsed.outputDir || parsed.flowFile) {
112
+ throw new Error("validate only accepts --title and --json");
113
+ }
114
+ const validation = await validateSite(parsed);
115
+ if (parsed.json) {
116
+ const { flow, ...report } = validation;
117
+ console.log(JSON.stringify(report));
118
+ }
119
+ else if (validation.valid) {
120
+ console.log(`Valid: ${parsed.input.join(", ")} (${validation.stats.files} files, ${validation.stats.relations} relations)`);
76
121
  } else {
77
- throw error;
122
+ console.log(validation.errors.map((error) => error.message).join("\n"));
78
123
  }
124
+ if (!validation.valid) process.exitCode = 1;
125
+ return;
126
+ }
127
+
128
+ const parsed = parseInputOptions(command === "build" ? args.slice(1) : args);
129
+ const { json, ...buildOptions } = parsed;
130
+ const result = await buildSite(buildOptions);
131
+ if (json) {
132
+ console.log(JSON.stringify({
133
+ ok: true,
134
+ flowPath: result.flowPath,
135
+ outputDir: result.outputDir,
136
+ pageCount: result.pageCount,
137
+ pages: result.pages,
138
+ }));
139
+ } else {
140
+ console.log(`Generated ${result.pageCount} page${result.pageCount === 1 ? "" : "s"} and ${result.flowPath}`);
79
141
  }
80
142
  }
143
+
144
+ main().catch((error) => {
145
+ if (process.argv.includes("--json")) {
146
+ console.error(JSON.stringify({
147
+ ok: false,
148
+ error: {
149
+ code: error instanceof FlowmatterError ? error.code : "runtime_error",
150
+ path: error instanceof FlowmatterError ? error.path : null,
151
+ message: error instanceof Error ? error.message : String(error),
152
+ },
153
+ }));
154
+ } else {
155
+ fail(error instanceof Error ? error.message : String(error), error instanceof FlowmatterError ? 1 : 2);
156
+ }
157
+ process.exitCode ||= error instanceof FlowmatterError ? 1 : 2;
158
+ });
@@ -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.2",
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
  ],
@@ -38,7 +46,7 @@
38
46
  "access": "public"
39
47
  },
40
48
  "dependencies": {
41
- "@p10i/flowjob": "0.1.2",
49
+ "@p10i/flowjob": "0.1.4",
42
50
  "glob": "13.0.6",
43
51
  "glob-parent": "6.0.2",
44
52
  "gray-matter": "4.0.3",
@@ -0,0 +1,130 @@
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
+ "flowmatter": {
9
+ "const": "config",
10
+ "description": "Contribute global relation types without creating a document node or HTML page."
11
+ },
12
+ "id": {
13
+ "type": "string",
14
+ "pattern": "\\S",
15
+ "description": "Stable document ID. Defaults to the relative Markdown path without its extension."
16
+ },
17
+ "title": {
18
+ "type": "string",
19
+ "pattern": "\\S",
20
+ "description": "Display title. Defaults to the first level-one heading, then the filename."
21
+ },
22
+ "module": {
23
+ "description": "Parent flowjob module. A string is shorthand for a named module with a slug-derived ID.",
24
+ "oneOf": [
25
+ {
26
+ "type": "string",
27
+ "pattern": "\\S"
28
+ },
29
+ {
30
+ "type": "object",
31
+ "properties": {
32
+ "id": { "type": "string", "pattern": "\\S" },
33
+ "name": { "type": "string", "pattern": "\\S" },
34
+ "viewUrl": { "type": "string", "description": "Local path to a selected Markdown overview, relative to this source file." },
35
+ "type": { "type": "string", "pattern": "\\S" }
36
+ },
37
+ "additionalProperties": true
38
+ }
39
+ ]
40
+ },
41
+ "moduleTypes": {
42
+ "description": "Map-wide module styles selected by module.type.",
43
+ "oneOf": [
44
+ { "type": "object", "propertyNames": { "$ref": "#/$defs/typeId" }, "additionalProperties": { "$ref": "#/$defs/moduleStyle", "unevaluatedProperties": false } },
45
+ { "type": "array", "items": { "$ref": "#/$defs/moduleStyle", "properties": { "id": { "$ref": "#/$defs/typeId" } }, "required": ["id"], "unevaluatedProperties": false } }
46
+ ]
47
+ },
48
+ "relationTypes": {
49
+ "description": "Map-wide styles in a keyed mapping or an ordered list. Repeated IDs merge by property; conflicting values are errors.",
50
+ "oneOf": [
51
+ {
52
+ "type": "object",
53
+ "propertyNames": { "$ref": "#/$defs/typeId" },
54
+ "additionalProperties": { "$ref": "#/$defs/style", "unevaluatedProperties": false }
55
+ },
56
+ {
57
+ "type": "array",
58
+ "items": {
59
+ "$ref": "#/$defs/style",
60
+ "properties": { "id": { "$ref": "#/$defs/typeId" } },
61
+ "required": ["id"],
62
+ "unevaluatedProperties": false
63
+ }
64
+ }
65
+ ]
66
+ },
67
+ "relations": {
68
+ "type": "array",
69
+ "description": "Directed relations from this document to documents selected by ID.",
70
+ "items": {
71
+ "type": "object",
72
+ "required": ["to", "type"],
73
+ "properties": {
74
+ "id": {
75
+ "type": "string",
76
+ "pattern": "\\S",
77
+ "description": "Stable relation ID. Defaults to <document-id>:<one-based-index>."
78
+ },
79
+ "to": {
80
+ "type": "string",
81
+ "pattern": "\\S",
82
+ "description": "Target document ID."
83
+ },
84
+ "type": {
85
+ "type": "string",
86
+ "pattern": "\\S",
87
+ "description": "Flow label."
88
+ },
89
+ "relationType": {
90
+ "type": "string",
91
+ "pattern": "\\S",
92
+ "description": "Optional flowjob relation styling/filter key."
93
+ },
94
+ "viewUrl": {
95
+ "type": "string",
96
+ "pattern": "^(?!/)[^\\\\:\\u0000-\\u001f]*\\.(?:[mM][dD]|html)$",
97
+ "description": "Local path relative to this Markdown file. Select an included .md file or its generated .html path; write literal filenames, not URL-encoded segments. A referenced file without Flowmatter document fields renders only as a page."
98
+ }
99
+ },
100
+ "additionalProperties": true
101
+ }
102
+ }
103
+ },
104
+ "$defs": {
105
+ "typeId": { "type": "string", "pattern": "^\\S(?:[\\s\\S]*\\S)?$" },
106
+ "moduleStyle": {
107
+ "type": "object",
108
+ "properties": {
109
+ "label": {"type":"string","pattern":"\\S"},
110
+ "accent": {"$ref":"#/$defs/hexColor"}, "surface": {"$ref":"#/$defs/hexColor"},
111
+ "headerBg": {"$ref":"#/$defs/hexColor"}, "headerFg": {"$ref":"#/$defs/hexColor"}, "footerFg": {"$ref":"#/$defs/hexColor"}
112
+ }
113
+ },
114
+ "style": {
115
+ "type": "object",
116
+ "properties": {
117
+ "label": { "type": "string", "pattern": "\\S" },
118
+ "hint": { "type": "string", "pattern": "\\S", "description": "Short description shown under the connection filter label." },
119
+ "color": { "$ref": "#/$defs/hexColor" },
120
+ "previewColor": { "$ref": "#/$defs/hexColor" }
121
+ }
122
+ },
123
+ "hexColor": {
124
+ "type": "string",
125
+ "description": "CSS hex color; quote it in YAML so # does not start a comment.",
126
+ "pattern": "^#(?:[0-9A-Fa-f]{3,4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$"
127
+ }
128
+ },
129
+ "additionalProperties": true
130
+ }
@@ -0,0 +1,77 @@
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 <path-or-glob>... --json` with all inputs, including shared configs. Overlapping paths count once. Inferred document IDs are relative to the common input root.
29
+ 8. Resolve every item in `errors` and repeat validation until `valid` is true.
30
+ 9. Run `flowmatter build <path-or-glob>... --output <directory> --json` with the same inputs.
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
+ `serve` as a replacement for the final build: `flowmatter serve <inputs> --port 4173` is a loopback editing preview; refresh after changes. Do not use
35
+ `--force` unless overwriting existing generated files is explicitly intended.
36
+ Do not edit generated HTML when the source Markdown can be corrected instead.
37
+
38
+ ## Minimal frontmatter
39
+
40
+ ```yaml
41
+ ---
42
+ id: place-order
43
+ title: Place order
44
+ module: Orders
45
+ relations:
46
+ - to: capture-payment
47
+ type: capturePayment()
48
+ relationType: call
49
+ ---
50
+ ```
51
+
52
+ Fields may be inferred, but explicit stable IDs are preferable for documents
53
+ that participate in relations. Use the schema output as the authoritative
54
+ field reference and JSON validation diagnostics as the authoritative check.
55
+
56
+ For a colored map, declare `relationTypes` in ordinary document frontmatter, e.g. `call: {label: Call, color: "#1565c0"}` under that key. Declarations merge across the input set; do not assign conflicting values to the same property.
57
+
58
+ Alternatively, use an ordered list such as `relationTypes: [{id: call, label: Call, color: "#1565c0"}]`. For a shared palette, put either form in Markdown frontmatter with `flowmatter: config`. Config files create no node or page; never use them as relation targets.
59
+
60
+ ## View pages and module colors
61
+
62
+ Each graph item opens its own generated page. To give a module header and a connection their own **View** pages, use frontmatter like this in `orders/place.md`:
63
+
64
+ ```yaml
65
+ module: {name: Orders, type: domain, viewUrl: ./Overview.md}
66
+ moduleTypes:
67
+ domain: {accent: '#287768', headerBg: '#D9F0EA', headerFg: '#123D36'}
68
+ relations:
69
+ - to: capture-payment
70
+ type: requests payment
71
+ relationType: call
72
+ viewUrl: ../notes/payment-handoff.md
73
+ ```
74
+
75
+ - **Module:** Declare `module.viewUrl` on one item in the module. If repeated, the declarations must resolve to the same page. `module.type` selects the card palette; `moduleTypes` can also live in a shared config and merges by ID and property like `relationTypes`.
76
+ - **Connection:** `to` is the destination item's ID; `viewUrl` is the document explaining the connection. For grouped connections, use the same view URL on every member if the group should offer **View**.
77
+ - **Inputs:** Resolve view paths relative to the declaring Markdown file. Include both the overview and the connection note in validation and build inputs. Use plain Markdown without graph frontmatter for these pages: Flowmatter renders them once without adding map items. Use `flowmatter: config` only for declarations that should produce no page.
package/src/index.mjs CHANGED
@@ -7,34 +7,39 @@ import matter from "gray-matter";
7
7
  import { marked } from "marked";
8
8
 
9
9
  const PAGE_STYLE = `
10
- :root { color-scheme: light dark; font-family: Inter, ui-sans-serif, system-ui, sans-serif; line-height: 1.6; }
11
- body { margin: 0; background: #f4f1ea; color: #27241f; }
12
- main { width: min(52rem, calc(100% - 2rem)); margin: 0 auto; padding: 3rem 0 5rem; }
13
- header { border-bottom: 1px solid #c9c1b3; margin-bottom: 2rem; padding-bottom: 1.25rem; }
14
- h1, h2, h3 { font-family: Georgia, "Times New Roman", serif; line-height: 1.15; }
15
- h1 { font-size: clamp(2.2rem, 7vw, 4.5rem); letter-spacing: -.04em; margin: .25rem 0; }
16
- a { color: #9a3f22; text-underline-offset: .18em; }
17
- .eyebrow { color: #70685d; font-size: .78rem; font-weight: 700; letter-spacing: .12em; text-transform: uppercase; }
18
- .relations { display: grid; gap: 1rem; grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr)); margin: 2.5rem 0; }
19
- .relation-card { background: #fffaf0; border: 1px solid #d8cebd; border-radius: .35rem; padding: 1rem 1.2rem; }
20
- .relation-card h2 { font-size: 1rem; margin: 0 0 .65rem; }
21
- .relation-card ul { margin: 0; padding-left: 1.2rem; }
10
+ :root { color-scheme: light dark; font-family: Aptos, "Segoe UI Variable", "Segoe UI", sans-serif; line-height: 1.55;
11
+ --surface: #fcfeff; --text: #142236; --muted: #58708f; --border: #b9cde9; --tint: #e7f0ff; --link: #1855aa; }
12
+ @media (prefers-color-scheme: dark) { :root {
13
+ --surface: #0a121f; --text: #e8f1ff; --muted: #9ab2d5; --border: #294266; --tint: #111d32; --link: #8ab9ff; } }
14
+ body { margin: 0; background: var(--surface); color: var(--text); }
15
+ main { box-sizing: border-box; width: 100%; min-height: 100vh; margin: 0; padding: calc(.5rem + 5px) calc(.75rem + 5px); overflow-wrap: anywhere; }
16
+ h1, h2, h3 { line-height: 1.25; }
17
+ h1 { font-size: clamp(1.5rem, 4vw, 2rem); margin: .5em 0; }
18
+ a { color: var(--link); text-underline-offset: .18em; }
19
+ a:focus-visible { outline: 2px solid var(--link); outline-offset: 2px; }
20
+ .eyebrow, .relations { font-size: .875rem; }
21
+ .eyebrow { color: var(--muted); font-weight: 600; }
22
+ .relations { border-top: 1px solid var(--border); margin-top: 2rem; padding-top: .75rem; }
23
+ .relations small, article :not(pre) > code { border-radius: .35rem; padding: .1em .4em; background: var(--tint); }
24
+ .relations small { color: var(--muted); }
25
+ .relations section { margin: .4rem 0; }
26
+ .relations h2 { font-size: inherit; margin: 0; }
27
+ .relations ul { margin: .15rem 0; padding-left: 1.25rem; }
22
28
  article img { height: auto; max-width: 100%; }
23
- article pre { overflow-x: auto; padding: 1rem; background: #25231f; color: #f9f3e8; }
29
+ article pre { overflow-x: auto; padding: .75rem; border: 1px solid var(--border); border-radius: .5rem; background: var(--tint); }
30
+ article table { display: block; max-width: 100%; overflow-x: auto; border-collapse: collapse; }
31
+ article th, article td { border: 1px solid var(--border); text-align: start; padding: .35rem .6rem; }
32
+ article th { background: var(--tint); }
33
+ article blockquote { margin-inline: 0; padding-inline: 1rem; border-inline-start: 3px solid var(--border); color: var(--muted); }
24
34
  article code { font-family: "SFMono-Regular", Consolas, monospace; }
25
- @media (prefers-color-scheme: dark) {
26
- body { background: #1d1b18; color: #eee7db; }
27
- header { border-color: #4b453c; }
28
- a { color: #ef9b7c; }
29
- .eyebrow { color: #aaa195; }
30
- .relation-card { background: #292620; border-color: #514a40; }
31
- }
32
35
  `;
33
36
 
34
37
  export class FlowmatterError extends Error {
35
- constructor(message) {
38
+ constructor(message, { code = "invalid_input", path: errorPath = null } = {}) {
36
39
  super(message);
37
40
  this.name = "FlowmatterError";
41
+ this.code = code;
42
+ this.path = errorPath;
38
43
  }
39
44
  }
40
45
 
@@ -75,46 +80,162 @@ function describeModule(value, relativePath) {
75
80
  return { id: slugify(value), name: value.trim() };
76
81
  }
77
82
  if (!isObject(value)) {
78
- throw new FlowmatterError(`${relativePath}: "module" must be a string or object`);
83
+ throw new FlowmatterError(`${relativePath}: "module" must be a string or object`, {
84
+ code: "invalid_module",
85
+ path: relativePath,
86
+ });
79
87
  }
80
88
 
81
89
  const id = value.id ?? (isNonEmptyString(value.name) ? slugify(value.name) : fallbackId);
82
90
  const name = value.name ?? (isNonEmptyString(value.id) ? value.id : fallbackName);
83
91
  if (!isNonEmptyString(id) || !isNonEmptyString(name)) {
84
- throw new FlowmatterError(`${relativePath}: module "id" and "name" must be non-empty strings`);
92
+ throw new FlowmatterError(`${relativePath}: module "id" and "name" must be non-empty strings`, {
93
+ code: "invalid_module",
94
+ path: relativePath,
95
+ });
85
96
  }
86
97
  if (value.type !== undefined && !isNonEmptyString(value.type)) {
87
- throw new FlowmatterError(`${relativePath}: module "type" must be a non-empty string`);
98
+ throw new FlowmatterError(`${relativePath}: module "type" must be a non-empty string`, {
99
+ code: "invalid_module",
100
+ path: relativePath,
101
+ });
88
102
  }
89
103
  return { id: id.trim(), name: name.trim(), ...(value.type ? { type: value.type.trim() } : {}) };
90
104
  }
91
105
 
106
+ function mergeTypes(types, source, fieldName) {
107
+ const { relativePath } = source;
108
+ const relationTypes = source[fieldName];
109
+ const modules = fieldName === 'moduleTypes';
110
+ if (relationTypes === undefined) return;
111
+ const isMapping = (value) => isObject(value) && Object.getPrototypeOf(value) === Object.prototype;
112
+ const invalid = (message) => {
113
+ throw new FlowmatterError(`${relativePath}: ${message}`, { code: modules ? 'invalid_module_types' : 'invalid_relation_types', path: relativePath });
114
+ };
115
+ const list = Array.isArray(relationTypes);
116
+ if (!list && !isMapping(relationTypes)) invalid(`${fieldName} must be a mapping or a list of definitions`);
117
+
118
+ for (const [index, definition] of Object.entries(relationTypes)) {
119
+ const location = `${fieldName}[${list ? index : JSON.stringify(index)}]`;
120
+ if (!isMapping(definition)) invalid(`${location} must be an object`);
121
+ const key = list ? definition.id : index;
122
+ if (!isNonEmptyString(key) || key !== key.trim()) invalid(`${location}${list ? '.id' : ''} needs a non-empty ID without surrounding whitespace`);
123
+ if (!types.has(key)) types.set(key, { style: {}, sources: new Map() });
124
+ const { style, sources } = types.get(key);
125
+ for (const [field, value] of Object.entries(definition)) {
126
+ if (list && field === "id") continue;
127
+ if (field === "label" || (!modules && field === "hint")) {
128
+ if (!isNonEmptyString(value)) invalid(`${location}.${field} must be a non-empty string`);
129
+ } else if ((modules ? ['accent','surface','headerBg','headerFg','footerFg'] : ['color','previewColor']).includes(field)) {
130
+ if (typeof value !== "string" || !/^#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i.test(value)) {
131
+ invalid(`${location}.${field} must be a hex color with 3, 4, 6, or 8 digits`);
132
+ }
133
+ } else {
134
+ invalid(`${location}.${field} is not a supported property`);
135
+ }
136
+ if (sources.has(field) && style[field] !== value) {
137
+ throw new FlowmatterError(`${relativePath}: ${location}.${field} (${key}) conflicts with the declaration in ${sources.get(field)}`, {
138
+ code: modules ? 'conflicting_module_type' : 'conflicting_relation_type', path: relativePath,
139
+ });
140
+ }
141
+ if (!sources.has(field)) {
142
+ style[field] = value;
143
+ sources.set(field, relativePath);
144
+ }
145
+ }
146
+ }
147
+ }
148
+
92
149
  function parseRelations(value, relativePath) {
93
150
  if (value === undefined) return [];
94
151
  if (!Array.isArray(value)) {
95
- throw new FlowmatterError(`${relativePath}: "relations" must be an array`);
152
+ throw new FlowmatterError(`${relativePath}: "relations" must be an array`, {
153
+ code: "invalid_relations",
154
+ path: relativePath,
155
+ });
96
156
  }
97
157
 
98
158
  return value.map((relation, index) => {
99
159
  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`);
160
+ if (!isObject(relation)) {
161
+ throw new FlowmatterError(`${location} must be an object`, { code: "invalid_relation", path: relativePath });
162
+ }
163
+ if (!isNonEmptyString(relation.to)) {
164
+ throw new FlowmatterError(`${location}.to must be a non-empty string`, { code: "invalid_relation", path: relativePath });
165
+ }
166
+ if (!isNonEmptyString(relation.type)) {
167
+ throw new FlowmatterError(`${location}.type must be a non-empty string`, { code: "invalid_relation", path: relativePath });
168
+ }
103
169
  if (relation.id !== undefined && !isNonEmptyString(relation.id)) {
104
- throw new FlowmatterError(`${location}.id must be a non-empty string`);
170
+ throw new FlowmatterError(`${location}.id must be a non-empty string`, { code: "invalid_relation", path: relativePath });
105
171
  }
106
172
  if (relation.relationType !== undefined && !isNonEmptyString(relation.relationType)) {
107
- throw new FlowmatterError(`${location}.relationType must be a non-empty string`);
173
+ throw new FlowmatterError(`${location}.relationType must be a non-empty string`, {
174
+ code: "invalid_relation",
175
+ path: relativePath,
176
+ });
108
177
  }
109
178
  return {
110
179
  ...(relation.id ? { id: relation.id.trim() } : {}),
111
180
  to: relation.to.trim(),
112
181
  type: relation.type.trim(),
182
+ ...(relation.viewUrl !== undefined ? { viewPath: relation.viewUrl } : {}),
113
183
  ...(relation.relationType ? { relationType: relation.relationType.trim() } : {}),
114
184
  };
115
185
  });
116
186
  }
117
187
 
188
+ function pageUrl(relativePath) {
189
+ return `./${relativePath.split("/").map(encodeURIComponent).join("/")}`;
190
+ }
191
+
192
+ function resolveRelationViews(sources) {
193
+ const bySource = new Map(sources.map(source => [source.relativePath, source]));
194
+ const byPage = new Map();
195
+ for (const source of sources) {
196
+ if (source.config) continue;
197
+ const page = source.outputRelativePath;
198
+ if (byPage.has(page)) {
199
+ throw new FlowmatterError(`${source.relativePath} and ${byPage.get(page).relativePath} both render to ${page}`, {
200
+ code: "output_collision", path: source.relativePath,
201
+ });
202
+ }
203
+ byPage.set(page, source);
204
+ }
205
+ for (const [page, source] of byPage) {
206
+ for (let dir = path.posix.dirname(page); dir !== "."; dir = path.posix.dirname(dir)) {
207
+ if (byPage.has(dir)) throw new FlowmatterError(`${source.relativePath}: output directory ${dir} conflicts with the page for ${byPage.get(dir).relativePath}`, {
208
+ code: "output_collision", path: source.relativePath,
209
+ });
210
+ }
211
+ function resolveView(ref, field, code) {
212
+ if (ref === undefined) return;
213
+ const fail = message => {
214
+ throw new FlowmatterError(`${source.relativePath}: ${field} ${message}`, {
215
+ code, path: source.relativePath,
216
+ });
217
+ };
218
+ if (!isNonEmptyString(ref) || ref.startsWith("/") || /[\\:\x00-\x1f]/.test(ref) || !/\.(?:[mM][dD]|html)$/.test(ref)) {
219
+ fail("must be a local relative .md path or generated .html path");
220
+ }
221
+ const key = path.posix.join(path.posix.dirname(source.relativePath), ref);
222
+ if (key.startsWith("../")) fail(`points outside the input root: ${ref}`);
223
+ const target = /\.md$/i.test(ref) ? bySource.get(key) : byPage.get(key);
224
+ if (!target) fail(`does not match a page in the selected inputs: ${ref}`);
225
+ if (target.config) fail(`references a configuration file: ${ref}`);
226
+ if (/[\\:\x00-\x1f]/.test(target.outputRelativePath)) fail(`references a path Flowjob cannot display: ${key}`);
227
+ if (!target.explicitGraph) target.pageOnly = true;
228
+ return pageUrl(target.outputRelativePath);
229
+ }
230
+ if (source.moduleViewPath !== undefined) {
231
+ source.module.viewUrl = resolveView(source.moduleViewPath, 'module.viewUrl', 'invalid_module_view_url');
232
+ }
233
+ source.relations.forEach((relation, index) => {
234
+ if (relation.viewPath !== undefined) relation.viewUrl = resolveView(relation.viewPath, `relations[${index}].viewUrl`, 'invalid_relation_view_url');
235
+ });
236
+ }
237
+ }
238
+
118
239
  async function pathExists(filePath) {
119
240
  try {
120
241
  await access(filePath);
@@ -144,43 +265,83 @@ async function resolveInput(input, cwd) {
144
265
  return { baseDir, files };
145
266
  }
146
267
 
147
- async function readDocuments(input, cwd) {
148
- const { baseDir, files } = await resolveInput(input, cwd);
149
- const markdownFiles = [...new Set(files.map((file) => path.resolve(file)))]
150
- .filter((file) => /\.md$/i.test(file))
151
- .sort((left, right) => left.localeCompare(right));
152
-
153
- if (markdownFiles.length === 0) {
154
- throw new FlowmatterError(`No Markdown files matched "${input}"`);
268
+ export async function resolveMarkdownInputs(input, cwd) {
269
+ const inputs = Array.isArray(input) ? input : [input];
270
+ if (!inputs.length || !inputs.every(isNonEmptyString)) throw new FlowmatterError("One or more Markdown paths or globs are required");
271
+ const files = new Set();
272
+ let baseDir;
273
+ for (const spec of new Set(inputs)) {
274
+ const resolved = await resolveInput(spec, cwd);
275
+ const matches = resolved.files.filter((file) => /\.md$/i.test(file));
276
+ if (!matches.length) throw new FlowmatterError(`No Markdown files matched "${spec}"`, { code: "no_markdown_files", path: spec });
277
+ for (const file of matches) files.add(path.resolve(file));
278
+ baseDir ??= resolved.baseDir;
279
+ if (path.parse(baseDir).root !== path.parse(resolved.baseDir).root) throw new FlowmatterError("Inputs must share a filesystem root");
280
+ while (true) {
281
+ const relative = path.relative(baseDir, resolved.baseDir);
282
+ if (relative !== ".." && !relative.startsWith(`..${path.sep}`)) break;
283
+ baseDir = path.dirname(baseDir);
284
+ }
155
285
  }
286
+ const markdownFiles = [...files].sort((left, right) => left.localeCompare(right));
287
+ return {baseDir, markdownFiles};
288
+ }
156
289
 
157
- const documents = await Promise.all(markdownFiles.map(async (sourcePath) => {
290
+ async function readDocuments(input, cwd) {
291
+ const {baseDir, markdownFiles} = await resolveMarkdownInputs(input, cwd);
292
+
293
+ const sources = await Promise.all(markdownFiles.map(async (sourcePath) => {
158
294
  const relativePath = toPosix(path.relative(baseDir, sourcePath));
159
295
  if (relativePath === ".." || relativePath.startsWith("../")) {
160
- throw new FlowmatterError(`${sourcePath}: matched file is outside the input root`);
296
+ throw new FlowmatterError(`${sourcePath}: matched file is outside the input root`, {
297
+ code: "outside_input_root",
298
+ path: sourcePath,
299
+ });
161
300
  }
162
301
 
163
302
  let parsed;
164
303
  try {
165
304
  parsed = matter(await readFile(sourcePath, "utf8"));
166
305
  } catch (error) {
167
- throw new FlowmatterError(`${relativePath}: invalid frontmatter (${error.message})`);
306
+ throw new FlowmatterError(`${relativePath}: invalid frontmatter (${error.message})`, {
307
+ code: "invalid_frontmatter",
308
+ path: relativePath,
309
+ });
168
310
  }
169
311
 
170
312
  if (!isObject(parsed.data)) {
171
- throw new FlowmatterError(`${relativePath}: frontmatter must be an object`);
313
+ throw new FlowmatterError(`${relativePath}: frontmatter must be an object`, {
314
+ code: "invalid_frontmatter",
315
+ path: relativePath,
316
+ });
172
317
  }
173
318
 
319
+ if (parsed.data.flowmatter === "config") return { config: true, relativePath, relationTypes: parsed.data.relationTypes, moduleTypes: parsed.data.moduleTypes };
320
+
174
321
  const fallbackId = relativePath.replace(/\.md$/i, "");
175
322
  const id = parsed.data.id ?? fallbackId;
176
323
  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`);
324
+ if (!isNonEmptyString(id)) {
325
+ throw new FlowmatterError(`${relativePath}: "id" must be a non-empty string`, {
326
+ code: "invalid_document_id",
327
+ path: relativePath,
328
+ });
329
+ }
330
+ if (!isNonEmptyString(title)) {
331
+ throw new FlowmatterError(`${relativePath}: "title" must be a non-empty string`, {
332
+ code: "invalid_document_title",
333
+ path: relativePath,
334
+ });
335
+ }
179
336
 
180
337
  return {
181
338
  id: id.trim(),
339
+ explicitGraph: ["id", "title", "module", "relations", "relationTypes", "moduleTypes"].some(key => Object.hasOwn(parsed.data, key)),
182
340
  title: title.trim(),
183
341
  module: describeModule(parsed.data.module, relativePath),
342
+ moduleViewPath: parsed.data.module?.viewUrl,
343
+ relationTypes: parsed.data.relationTypes,
344
+ moduleTypes: parsed.data.moduleTypes,
184
345
  relations: parseRelations(parsed.data.relations, relativePath),
185
346
  content: parsed.content,
186
347
  sourcePath,
@@ -188,18 +349,29 @@ async function readDocuments(input, cwd) {
188
349
  outputRelativePath: relativePath.replace(/\.md$/i, ".html"),
189
350
  };
190
351
  }));
191
- return { baseDir, documents };
352
+ const relationTypes = new Map();
353
+ const moduleTypes = new Map();
354
+ for (const source of sources) {
355
+ mergeTypes(relationTypes, source, 'relationTypes');
356
+ mergeTypes(moduleTypes, source, 'moduleTypes');
357
+ }
358
+ const documents = sources.filter((source) => !source.config);
359
+ resolveRelationViews(sources);
360
+ if (!documents.length) throw new FlowmatterError("Inputs contain only configuration; at least one document is required", { code: "no_documents" });
361
+ return { baseDir, documents, relationTypes, moduleTypes };
192
362
  }
193
363
 
194
- function compile(documents, title) {
364
+ function compile(documents, title, relationTypes, moduleTypes) {
195
365
  const byId = new Map();
196
366
  const modules = new Map();
197
367
  const flowIds = new Map();
198
368
 
199
- for (const document of documents) {
369
+ const graphDocuments = documents.filter(document => !document.pageOnly);
370
+ for (const document of graphDocuments) {
200
371
  if (byId.has(document.id)) {
201
372
  throw new FlowmatterError(
202
373
  `${document.relativePath}: duplicate document id "${document.id}" (also used by ${byId.get(document.id).relativePath})`,
374
+ { code: "duplicate_document_id", path: document.relativePath },
203
375
  );
204
376
  }
205
377
  byId.set(document.id, document);
@@ -207,30 +379,42 @@ function compile(documents, title) {
207
379
  const existing = modules.get(document.module.id);
208
380
  if (existing && (
209
381
  existing.name !== document.module.name
382
+ || (existing.viewUrl && document.module.viewUrl && existing.viewUrl !== document.module.viewUrl)
210
383
  || (existing.type && document.module.type && existing.type !== document.module.type)
211
384
  )) {
212
- throw new FlowmatterError(`${document.relativePath}: module "${document.module.id}" conflicts with an earlier definition`);
385
+ throw new FlowmatterError(`${document.relativePath}: module "${document.module.id}" conflicts with an earlier definition`, {
386
+ code: "conflicting_module",
387
+ path: document.relativePath,
388
+ });
213
389
  }
214
390
  if (!existing) modules.set(document.module.id, { ...document.module, submodules: [] });
215
391
  if (existing && !existing.type && document.module.type) existing.type = document.module.type;
216
- modules.get(document.module.id).submodules.push({ id: document.id, name: document.title });
392
+ if (existing && !existing.viewUrl && document.module.viewUrl) existing.viewUrl = document.module.viewUrl;
393
+ modules.get(document.module.id).submodules.push({ id: document.id, name: document.title, viewUrl: pageUrl(document.outputRelativePath) });
217
394
  }
218
395
 
219
396
  const flows = [];
220
- for (const document of documents) {
397
+ for (const document of graphDocuments) {
221
398
  document.relations.forEach((relation, index) => {
222
399
  const target = byId.get(relation.to);
223
400
  if (!target) {
224
- throw new FlowmatterError(`${document.relativePath}: relation target "${relation.to}" does not exist`);
401
+ throw new FlowmatterError(`${document.relativePath}: relation target "${relation.to}" does not exist`, {
402
+ code: "missing_relation_target",
403
+ path: document.relativePath,
404
+ });
225
405
  }
226
406
  const id = relation.id ?? `${document.id}:${index + 1}`;
227
407
  if (flowIds.has(id)) {
228
- throw new FlowmatterError(`${document.relativePath}: duplicate relation id "${id}" (also used by ${flowIds.get(id)})`);
408
+ throw new FlowmatterError(`${document.relativePath}: duplicate relation id "${id}" (also used by ${flowIds.get(id)})`, {
409
+ code: "duplicate_relation_id",
410
+ path: document.relativePath,
411
+ });
229
412
  }
230
413
  flowIds.set(id, document.relativePath);
231
414
  flows.push({
232
415
  id,
233
416
  type: relation.type,
417
+ ...(relation.viewUrl ? { viewUrl: relation.viewUrl } : {}),
234
418
  ...(relation.relationType ? { relationType: relation.relationType } : {}),
235
419
  from: { module: document.module.id, submodule: document.id },
236
420
  to: { module: target.module.id, submodule: target.id },
@@ -242,16 +426,48 @@ function compile(documents, title) {
242
426
  schemaVersion: 1,
243
427
  title,
244
428
  modules: [...modules.values()],
429
+ ...(moduleTypes.size ? { moduleTypes: Object.fromEntries([...moduleTypes].map(([key,{style}])=>[key,style])) } : {}),
430
+ ...(relationTypes.size ? { relationTypes: Object.fromEntries([...relationTypes].map(([key, { style }]) => [key, style])) } : {}),
245
431
  flows,
246
432
  };
247
433
  const validation = validateFlow(flow);
248
434
  if (!validation.valid) {
249
435
  const diagnostics = validation.errors.map((error) => error.message ?? String(error)).join("; ");
250
- throw new FlowmatterError(`Generated flow is invalid: ${diagnostics}`);
436
+ throw new FlowmatterError(`Generated flow is invalid: ${diagnostics}`, { code: "invalid_flow" });
251
437
  }
252
438
  return { byId, flow };
253
439
  }
254
440
 
441
+ export async function validateSite({ input, title, cwd = process.cwd() } = {}) {
442
+ try {
443
+ if (title !== undefined && !isNonEmptyString(title)) {
444
+ throw new FlowmatterError("The title must be a non-empty string");
445
+ }
446
+ const { baseDir, documents, relationTypes, moduleTypes } = await readDocuments(input, path.resolve(cwd));
447
+ const siteTitle = title?.trim() ?? titleFromContent("", path.basename(baseDir));
448
+ const { flow } = compile(documents, siteTitle, relationTypes, moduleTypes);
449
+ return {
450
+ valid: true,
451
+ errors: [],
452
+ warnings: [],
453
+ stats: {
454
+ files: documents.length,
455
+ modules: flow.modules.length,
456
+ relations: flow.flows.length,
457
+ },
458
+ flow,
459
+ };
460
+ } catch (error) {
461
+ if (!(error instanceof FlowmatterError)) throw error;
462
+ return {
463
+ valid: false,
464
+ errors: [{ code: error.code, path: error.path, message: error.message }],
465
+ warnings: [],
466
+ stats: null,
467
+ };
468
+ }
469
+ }
470
+
255
471
  function escapeHtml(value) {
256
472
  return String(value)
257
473
  .replaceAll("&", "&amp;")
@@ -274,22 +490,24 @@ function renderRelationList(title, relations, currentOutputPath) {
274
490
  return `<section class="relation-card"><h2>${escapeHtml(title)}</h2><ul>${items}</ul></section>`;
275
491
  }
276
492
 
277
- function renderPage(document, documents, byId, flowPath) {
493
+ function renderPage(document, documents, byId) {
278
494
  const outgoing = document.relations.map((relation) => ({ document: byId.get(relation.to), type: relation.type }));
279
- const incoming = documents.flatMap((candidate) => candidate.relations
495
+ const incoming = document.pageOnly ? [] : documents.flatMap((candidate) => candidate.relations
280
496
  .filter((relation) => relation.to === document.id)
281
497
  .map((relation) => ({ document: candidate, type: relation.type })));
282
498
 
283
499
  const sourceToOutput = new Map(documents.map((candidate) => [candidate.sourcePath, candidate.outputPath]));
284
- const body = marked.parse(document.content, {
285
- walkTokens(token) {
500
+ const tokens = marked.lexer(document.content);
501
+ const first = tokens.find(token => token.type !== "space");
502
+ const hasTitle = first?.type === "heading" && first.depth === 1;
503
+ marked.walkTokens(tokens, token => {
286
504
  if (token.type !== "link" || !isNonEmptyString(token.href)) return;
287
505
  const match = token.href.match(/^([^?#]+\.md)([?#].*)?$/i);
288
506
  if (!match || path.isAbsolute(match[1])) return;
289
507
  const targetOutput = sourceToOutput.get(path.resolve(path.dirname(document.sourcePath), match[1]));
290
508
  if (targetOutput) token.href = `${relativeHref(document.outputPath, targetOutput)}${match[2] ?? ""}`;
291
- },
292
509
  });
510
+ const body = marked.parser(tokens);
293
511
  const relations = [
294
512
  renderRelationList("Leads to", outgoing, document.outputPath),
295
513
  renderRelationList("Reached from", incoming, document.outputPath),
@@ -306,26 +524,23 @@ function renderPage(document, documents, byId, flowPath) {
306
524
  <body>
307
525
  <main>
308
526
  <header>
309
- <div class="eyebrow">${escapeHtml(document.module.name)} · <a href="${escapeHtml(relativeHref(document.outputPath, flowPath))}">Open flow</a></div>
310
- <h1>${escapeHtml(document.title)}</h1>
527
+ <div class="eyebrow">${escapeHtml(document.module.name)}</div>
311
528
  </header>
312
- ${relations ? `<aside class="relations" aria-label="Relations">${relations}</aside>` : ""}
313
- <article>${body}</article>
529
+ <article>${hasTitle ? "" : `<h1>${escapeHtml(document.title)}</h1>`}${body}</article>
530
+ ${relations ? `<footer class="relations" aria-label="Relations">${relations}</footer>` : ""}
314
531
  </main>
315
532
  </body>
316
533
  </html>
317
534
  `;
318
535
  }
319
536
 
320
- export async function buildSite({
537
+ export async function renderSite({
321
538
  input,
322
539
  outputDir = "flowmatter-dist",
323
540
  flowFile = "flow.html",
324
541
  title,
325
- force = false,
326
542
  cwd = process.cwd(),
327
543
  } = {}) {
328
- if (!isNonEmptyString(input)) throw new FlowmatterError("A folder or glob input is required");
329
544
  if (!isNonEmptyString(outputDir)) throw new FlowmatterError("The output directory must be a non-empty string");
330
545
  if (!isNonEmptyString(flowFile) || path.basename(flowFile) !== flowFile || !/\.html?$/i.test(flowFile)) {
331
546
  throw new FlowmatterError("The flow filename must be an HTML filename without a directory");
@@ -334,27 +549,34 @@ export async function buildSite({
334
549
  throw new FlowmatterError("The title must be a non-empty string");
335
550
  }
336
551
 
337
- const { baseDir, documents } = await readDocuments(input, path.resolve(cwd));
552
+ const { baseDir, documents, relationTypes, moduleTypes } = await readDocuments(input, path.resolve(cwd));
338
553
  const outputRoot = path.resolve(cwd, outputDir);
339
554
  const flowPath = path.join(outputRoot, flowFile);
340
555
  for (const document of documents) {
341
556
  document.outputPath = path.join(outputRoot, document.outputRelativePath);
342
- if (path.resolve(document.outputPath) === path.resolve(flowPath)) {
343
- throw new FlowmatterError(`${document.relativePath}: rendered page conflicts with ${flowFile}`);
557
+ if (document.outputRelativePath === flowFile || document.outputRelativePath.startsWith(`${flowFile}/`)) {
558
+ throw new FlowmatterError(`${document.relativePath}: rendered page conflicts with ${flowFile}`, {
559
+ code: "output_collision", path: document.relativePath,
560
+ });
344
561
  }
345
562
  }
346
563
 
347
564
  const siteTitle = title?.trim() ?? titleFromContent("", path.basename(baseDir));
348
- const { byId, flow } = compile(documents, siteTitle);
565
+ const { byId, flow } = compile(documents, siteTitle, relationTypes, moduleTypes);
349
566
  const outputs = [
350
567
  { path: flowPath, content: buildFlow(flow, { title: siteTitle }) },
351
568
  ...documents.map((document) => ({
352
569
  path: document.outputPath,
353
- content: renderPage(document, documents, byId, flowPath),
570
+ content: renderPage(document, documents, byId),
354
571
  })),
355
572
  ];
356
573
 
357
- if (!force) {
574
+ return {flow, flowPath, outputDir: outputRoot, pageCount: documents.length, pages: documents.map(document => document.outputPath), outputs};
575
+ }
576
+
577
+ export async function buildSite(options = {}) {
578
+ const {outputs, ...result} = await renderSite(options);
579
+ if (!options.force) {
358
580
  for (const output of outputs) {
359
581
  if (await pathExists(output.path)) {
360
582
  throw new FlowmatterError(`${output.path} already exists; use --force to overwrite generated files`);
@@ -367,11 +589,5 @@ export async function buildSite({
367
589
  await writeFile(output.path, output.content, "utf8");
368
590
  }
369
591
 
370
- return {
371
- flow,
372
- flowPath,
373
- outputDir: outputRoot,
374
- pageCount: documents.length,
375
- pages: documents.map((document) => document.outputPath),
376
- };
592
+ return result;
377
593
  }
package/src/serve.mjs ADDED
@@ -0,0 +1,56 @@
1
+ import http from 'node:http';
2
+ import path from 'node:path';
3
+ import {stat} from 'node:fs/promises';
4
+ import {renderSite, resolveMarkdownInputs} from './index.mjs';
5
+
6
+ // Re-resolve the input set on every poll so atomic saves, additions, and removals
7
+ // work for globs as well as directories on bind-mounted filesystems.
8
+ export async function serveSite({input, cwd = process.cwd(), title, flowFile = 'flow.html', port = 4173,
9
+ interval = 500, log = console.error}) {
10
+ async function fingerprint() {
11
+ const {markdownFiles} = await resolveMarkdownInputs(input, cwd);
12
+ return JSON.stringify(await Promise.all(markdownFiles.map(async file => {
13
+ const s = await stat(file, {bigint:true});
14
+ return [file, String(s.ino), String(s.size), String(s.ctimeNs), String(s.mtimeNs)];
15
+ })));
16
+ }
17
+ async function render() {
18
+ const site = await renderSite({input,cwd,title,flowFile});
19
+ return new Map(site.outputs.map(({path:file,content}) => ['/' + path.relative(site.outputDir,file).split(path.sep).join('/'),content]));
20
+ }
21
+ let seen = await fingerprint(), pages = await render(), stopped = false, timer, lastError;
22
+ async function poll() {
23
+ try {
24
+ const next = await fingerprint();
25
+ if (next !== seen) {
26
+ seen = next;
27
+ pages = await render(); // Publish the entire new generation together.
28
+ log(`Rebuilt ${pages.size - 1} pages`);
29
+ }
30
+ lastError = undefined;
31
+ } catch (error) {
32
+ if (lastError !== error.message) log(`Preview rebuild failed: ${error.message}`);
33
+ lastError = error.message;
34
+ } finally {
35
+ if (!stopped) timer = setTimeout(poll,interval);
36
+ }
37
+ }
38
+ const server = http.createServer((req,res) => {
39
+ if (!['GET','HEAD'].includes(req.method)) {res.writeHead(405,{Allow:'GET, HEAD'}).end(); return;}
40
+ let key;
41
+ try {key = decodeURIComponent(req.url.split('?')[0]);} catch {res.writeHead(400).end(); return;}
42
+ const page = pages.get(key === '/' ? '/' + flowFile : key);
43
+ if (page === undefined) {res.writeHead(404).end(); return;}
44
+ res.writeHead(200,{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store'});
45
+ res.end(req.method === 'HEAD' ? undefined : page);
46
+ });
47
+ await new Promise((resolve,reject) => {
48
+ server.once('error',reject);
49
+ server.listen(port,'127.0.0.1',resolve);
50
+ });
51
+ timer = setTimeout(poll,interval);
52
+ return {url:`http://127.0.0.1:${server.address().port}/`, close() {
53
+ stopped = true; clearTimeout(timer);
54
+ return new Promise(resolve => server.close(resolve));
55
+ }};
56
+ }