@executablemd/cli 0.2.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Taras Mankovski
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/esm/cli.js ADDED
@@ -0,0 +1,215 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * CLI — run an executable markdown document.
4
+ *
5
+ * Usage:
6
+ * xmd run <document.md> [options]
7
+ * xmd <document.md> [options] (run is the default command)
8
+ *
9
+ * Examples:
10
+ * xmd run core/examples/hello-world.md
11
+ * xmd core/examples/hello-world.md --verbose
12
+ * xmd run core/examples/hello-world.md --journal events.jsonl
13
+ */
14
+ import { main, exit, spawn, each, createSignal, until } from "effection";
15
+ import { InMemoryStream, } from "@executablemd/durable-streams";
16
+ import { forEach } from "@effectionx/stream-helpers";
17
+ import { open } from "node:fs/promises";
18
+ import { inspect } from "node:util";
19
+ import process from "node:process";
20
+ import { program, object, field, cli, commands } from "configliere";
21
+ import { z } from "zod";
22
+ import { runDocument, useNormalizedOutput, useTerminalOutput } from "@executablemd/core";
23
+ import { FileStream } from "./file-stream.js";
24
+ // ---------------------------------------------------------------------------
25
+ // Workaround: field.default exists at runtime but is missing from the .d.ts
26
+ // ---------------------------------------------------------------------------
27
+ const defaults = (value) => (mods) => ({ ...mods, default: value });
28
+ // ---------------------------------------------------------------------------
29
+ // Program schema
30
+ // ---------------------------------------------------------------------------
31
+ const runConfig = object({
32
+ docPath: {
33
+ description: "markdown document to execute",
34
+ ...field(z.string(), cli.argument()),
35
+ },
36
+ componentDir: {
37
+ description: "component search directory",
38
+ ...field(z.array(z.string()), defaults(["components", "."]), field.array()),
39
+ },
40
+ verbose: {
41
+ description: "log journal entries to stderr",
42
+ aliases: ["-V"],
43
+ ...field(z.boolean(), defaults(false)),
44
+ },
45
+ journal: {
46
+ description: "write a diagnostic JSONL trace (path must not exist)",
47
+ aliases: ["-j"],
48
+ ...field(z.string().optional()),
49
+ },
50
+ raw: {
51
+ description: "output raw markdown without normalization or terminal formatting",
52
+ ...field(z.boolean(), defaults(false)),
53
+ },
54
+ });
55
+ const xmd = program({
56
+ name: "xmd",
57
+ version: "0.2.0",
58
+ config: commands({ run: runConfig }, { default: "run" }),
59
+ });
60
+ // ---------------------------------------------------------------------------
61
+ // Journal entry formatting
62
+ // ---------------------------------------------------------------------------
63
+ const pretty = (value) => inspect(value, {
64
+ colors: true,
65
+ compact: true,
66
+ breakLength: Infinity,
67
+ depth: 2,
68
+ maxStringLength: 200,
69
+ });
70
+ function formatYieldResult(event) {
71
+ const { result, description } = event;
72
+ if (result.status !== "ok" || result.value === undefined)
73
+ return "";
74
+ const v = result.value;
75
+ switch (description.type) {
76
+ case "import_component":
77
+ return " " + pretty({ path: v.path });
78
+ case "eval":
79
+ return " " + pretty(v.value ?? {});
80
+ case "exec":
81
+ return " " + pretty({ exitCode: v.exitCode, stdout: v.stdout, stderr: v.stderr });
82
+ default:
83
+ return " " + pretty(v);
84
+ }
85
+ }
86
+ function summarizeEvent(event) {
87
+ if (event.type === "yield") {
88
+ const desc = event.description;
89
+ const status = event.result.status;
90
+ const detail = status === "err" && "error" in event.result
91
+ ? ` (${event.result.error.message})`
92
+ : formatYieldResult(event);
93
+ return `[yield] ${desc.type}:${desc.name} → ${status}${detail}`;
94
+ }
95
+ const status = event.result.status;
96
+ const detail = status === "err" && "error" in event.result ? ` (${event.result.error.message})` : "";
97
+ return `[close] ${event.coroutineId} → ${status}${detail}`;
98
+ }
99
+ // ---------------------------------------------------------------------------
100
+ // Document runner
101
+ // ---------------------------------------------------------------------------
102
+ function* createJournalFile(filePath) {
103
+ let handle;
104
+ try {
105
+ handle = yield* until(open(filePath, "wx"));
106
+ }
107
+ catch (error) {
108
+ const isExistingFile = error instanceof Error &&
109
+ (("code" in error && error.code === "EEXIST") || error.message.startsWith("EEXIST:"));
110
+ if (isExistingFile) {
111
+ throw new Error(`Journal trace already exists: ${filePath}. Remove it or choose another path.`, { cause: error });
112
+ }
113
+ throw error;
114
+ }
115
+ yield* until(handle.close());
116
+ }
117
+ function* run(config) {
118
+ const { docPath, componentDir, verbose, journal, raw } = config;
119
+ // Every CLI invocation starts from an empty stream. --journal writes
120
+ // current-run diagnostics only; existing traces are never loaded.
121
+ let stream;
122
+ if (journal) {
123
+ yield* createJournalFile(journal);
124
+ stream = new FileStream(journal);
125
+ }
126
+ else {
127
+ stream = new InMemoryStream();
128
+ }
129
+ // Wire --verbose observability via Signal.
130
+ // FileStream.onAppend fires after each persist; the signal fans out
131
+ // to the stderr writer below. Persistence is handled by FileStream
132
+ // itself — the signal is purely for observability.
133
+ const signal = verbose ? createSignal() : undefined;
134
+ if (signal && stream instanceof FileStream) {
135
+ stream.onAppend = (event) => signal.send(event);
136
+ }
137
+ else if (signal && stream instanceof InMemoryStream) {
138
+ stream.onAppend = (event) => signal.send(event);
139
+ }
140
+ // Spawn verbose stderr writer
141
+ const writer = signal
142
+ ? yield* spawn(function* () {
143
+ for (const event of yield* each(signal)) {
144
+ console.error(summarizeEvent(event));
145
+ yield* each.next();
146
+ }
147
+ })
148
+ : spawn(function* () { });
149
+ // ---------------------------------------------------------------------------
150
+ // Output middleware (spec §9).
151
+ //
152
+ // Middleware is installed on the DocumentOutput Api via Api.around() before
153
+ // runDocument is called. runDocument owns the channel internally —
154
+ // the CLI just installs transformations and consumes the returned stream.
155
+ // ---------------------------------------------------------------------------
156
+ if (!raw) {
157
+ yield* useNormalizedOutput();
158
+ }
159
+ if (process.stdout.isTTY && !raw) {
160
+ yield* useTerminalOutput();
161
+ }
162
+ // Run the document — returns a DocumentExecution.
163
+ // yield* execution waits for completion. execution.output streams chunks.
164
+ const execution = yield* runDocument({
165
+ docPath,
166
+ stream,
167
+ componentDirs: componentDir,
168
+ });
169
+ // Consume the output stream with forEach.
170
+ // Interactive TTY: write each chunk as it arrives.
171
+ // Piped: collect and write the full output at the end.
172
+ const fullOutput = yield* forEach(function* (chunk) {
173
+ if (process.stdout.isTTY) {
174
+ process.stdout.write(chunk);
175
+ }
176
+ }, execution.output);
177
+ // When piped (not TTY), write the full output at the end.
178
+ if (!process.stdout.isTTY) {
179
+ process.stdout.write(fullOutput);
180
+ }
181
+ // Close the signal so the writer drains remaining events and exits.
182
+ if (signal) {
183
+ signal.close();
184
+ yield* writer;
185
+ }
186
+ }
187
+ // ---------------------------------------------------------------------------
188
+ // Entry point
189
+ // ---------------------------------------------------------------------------
190
+ await main(function* (args) {
191
+ const parser = xmd.createParser({ args });
192
+ switch (parser.type) {
193
+ case "help":
194
+ console.log(parser.print());
195
+ yield* exit(0);
196
+ break;
197
+ case "version":
198
+ console.log(parser.print());
199
+ yield* exit(0);
200
+ break;
201
+ case "main": {
202
+ const parsed = parser.parse();
203
+ if (!parsed.ok) {
204
+ console.error(parsed.error.message);
205
+ yield* exit(1);
206
+ break;
207
+ }
208
+ switch (parsed.value.name) {
209
+ case "run":
210
+ yield* run(parsed.value.config);
211
+ break;
212
+ }
213
+ }
214
+ }
215
+ });
@@ -0,0 +1,24 @@
1
+ import { until } from "effection";
2
+ import { appendFile } from "node:fs/promises";
3
+ function cloneEvent(event) {
4
+ return structuredClone(event);
5
+ }
6
+ export class FileStream {
7
+ events;
8
+ filePath;
9
+ onAppend = null;
10
+ constructor(filePath) {
11
+ this.filePath = filePath;
12
+ this.events = [];
13
+ }
14
+ // deno-lint-ignore require-yield
15
+ *readAll() {
16
+ return this.events.map(cloneEvent);
17
+ }
18
+ *append(event) {
19
+ const cloned = cloneEvent(event);
20
+ yield* until(appendFile(this.filePath, JSON.stringify(cloned) + "\n"));
21
+ this.events.push(cloned);
22
+ this.onAppend?.(cloneEvent(cloned));
23
+ }
24
+ }
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "@executablemd/cli",
3
+ "version": "0.2.0",
4
+ "description": "The xmd command-line interface for executable.md.",
5
+ "homepage": "https://executable.md",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/taras/executable.md.git"
9
+ },
10
+ "license": "MIT",
11
+ "bugs": {
12
+ "url": "https://github.com/taras/executable.md/issues"
13
+ },
14
+ "scripts": {},
15
+ "bin": {
16
+ "xmd": "./esm/cli.js"
17
+ },
18
+ "dependencies": {
19
+ "@effectionx/stream-helpers": "0.8.3",
20
+ "@executablemd/core": "^0.2.0",
21
+ "@executablemd/durable-streams": "^0.2.0",
22
+ "configliere": "^0.2.3",
23
+ "effection": "4.1.0-alpha.7",
24
+ "zod": "^4.3.6"
25
+ },
26
+ "_generatedBy": "dnt@dev"
27
+ }
package/types/cli.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * CLI — run an executable markdown document.
4
+ *
5
+ * Usage:
6
+ * xmd run <document.md> [options]
7
+ * xmd <document.md> [options] (run is the default command)
8
+ *
9
+ * Examples:
10
+ * xmd run core/examples/hello-world.md
11
+ * xmd core/examples/hello-world.md --verbose
12
+ * xmd run core/examples/hello-world.md --journal events.jsonl
13
+ */
14
+ export {};
@@ -0,0 +1,10 @@
1
+ import type { Operation } from "effection";
2
+ import type { DurableStream, DurableEvent } from "@executablemd/durable-streams";
3
+ export declare class FileStream implements DurableStream {
4
+ private events;
5
+ private filePath;
6
+ onAppend: ((event: DurableEvent) => void) | null;
7
+ constructor(filePath: string);
8
+ readAll(): Operation<DurableEvent[]>;
9
+ append(event: DurableEvent): Operation<void>;
10
+ }