mdeval 1.0.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) Hiroki Osame <hiroki.osame@gmail.com>
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/README.md ADDED
@@ -0,0 +1,100 @@
1
+ <p align="center">
2
+ <img width="160" src=".github/logo.webp">
3
+ </p>
4
+ <h1 align="center">mdeval</h1>
5
+
6
+ Ever wanted dynamic values in your Markdown — package versions, star counts, computed tables — without a separate generation script that's easy to forget about?
7
+
8
+ mdeval embeds JavaScript directly in your Markdown using HTML comments. The logic lives right next to the content it produces, and the file renders normally everywhere — GitHub, editors, any Markdown viewer — because HTML comments are invisible.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ npm i mdeval
14
+ ```
15
+
16
+ ## Quick start
17
+
18
+ mdeval adds two types of HTML comments to your Markdown:
19
+
20
+ A **script block** is where you write JavaScript. It starts with `<!--mdeval` followed by a newline:
21
+
22
+ ```markdown
23
+ <!--mdeval
24
+ import fs from 'node:fs/promises';
25
+ const pkg = JSON.parse(await fs.readFile('package.json', 'utf8'));
26
+ -->
27
+ ```
28
+
29
+ Full Node.js, ESM imports, and top-level `await` are supported.
30
+
31
+ A **value marker** is where the result appears. It starts with `<!--mdeval ` (with a space) followed by a JavaScript expression:
32
+
33
+ ```markdown
34
+ Version: <!--mdeval pkg.version-->1.0.0<!--/mdeval-->
35
+ ```
36
+
37
+ The `1.0.0` between `-->` and `<!--/mdeval-->` is the current value — it gets overwritten with the result of `pkg.version` every time you run mdeval:
38
+
39
+ ```bash
40
+ mdeval README.md
41
+ ```
42
+
43
+ The file is updated in-place. You can pass multiple files at once: `mdeval README.md docs/*.md`
44
+
45
+ ## Notes
46
+
47
+ - A file can have **multiple script blocks** — they're merged into one module, so variables and imports are shared. We recommend placing them at the top to signal the file has generated content.
48
+
49
+ - Markers can be **self-contained** — no script block needed:
50
+
51
+ ```markdown
52
+ <!--mdeval (() => 2 + 2)()-->4<!--/mdeval-->
53
+ ```
54
+
55
+ In large documents, this IIFE pattern lets you keep logic next to the marker it serves instead of in a distant script block.
56
+
57
+ - If your value starts with a heading, list, or other block element, wrap it with **`block()`** so it renders on its own line. `block()` is a global helper that adds newlines before and after the value.
58
+
59
+ - You can **import from other `.md` files**. Only the script blocks are executed — no markers are processed:
60
+
61
+ ```markdown
62
+ <!--mdeval
63
+ import { version } from './data.md';
64
+ -->
65
+ ```
66
+
67
+ This lets you share constants and logic across multiple markdown files.
68
+
69
+ - When processing multiple files (`mdeval a.md b.md`), all files **share the same Node.js runtime** — including the module cache, `globalThis`, and `process.env`. This is the same behavior as any Node.js program using `import()`.
70
+
71
+ ## Caveats
72
+
73
+ - Script code **cannot contain `-->`** — it closes the HTML comment. Rewrite `x-- > y` as `x -= 1; x > y`.
74
+ - Scripts are **JavaScript only** — no TypeScript.
75
+ - Values **cannot contain `<!--mdeval `** or **`<!--/mdeval-->`** — mdeval will throw to prevent document corruption.
76
+
77
+ ## Tip: md-pen
78
+
79
+ [md-pen](https://github.com/privatenumber/md-pen) provides typed utilities for generating tables, lists, and other Markdown structures — useful when markers need to produce formatted output:
80
+
81
+ ```markdown
82
+ <!--mdeval
83
+ import { table, bold, link } from 'md-pen';
84
+ const deps = [['cleye', '^2.3.0'], ['md-pen', '^0.0.2']];
85
+ const depsTable = table(deps.map(([name, v]) => [
86
+ link(`https://npm.im/${name}`, bold(name)), v
87
+ ]));
88
+ -->
89
+
90
+ <!--mdeval block(depsTable)-->
91
+ | Package | Version |
92
+ | - | - |
93
+ | [__cleye__](https://npm.im/cleye) | ^2.3.0 |
94
+ | [__md-pen__](https://npm.im/md-pen) | ^0.0.2 |
95
+ <!--/mdeval-->
96
+ ```
97
+
98
+ ## Agent Skills
99
+
100
+ This package ships with a built-in [agent skill](./skills/mdeval/SKILL.md) for AI coding assistants. Set up [`skills-npm`](https://github.com/antfu/skills-npm) to automatically discover it.
package/dist/cli.mjs ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ var h=Object.defineProperty;var a=(r,o)=>h(r,"name",{value:o,configurable:!0});import{register as g}from"node:module";import u from"node:fs/promises";import w from"node:path";import{cli as E}from"cleye";import{pathToFileURL as y}from"node:url";import{p as M,b as $,E as R,M as b,C,a as S}from"./parse-markdown-ChGEvmW3.mjs";import"md4x";const k=a(r=>{if(r==null)throw new Error(`Cannot interpolate ${r} \u2014 this is likely a bug in your script`);return typeof r=="string"?r:typeof r=="object"?JSON.stringify(r):String(r)},"coerceValue"),v=a(async(r,o)=>{const{markers:e}=M(r);if(e.length===0)return r;const n=await import(y(o).href),f=$(e),m=new Map,d=a((t,l)=>{const i=m.get(t);if(i!==void 0)return i;const s=k(n[`${R}${t}`]);if(s.includes(b)||s.includes(`${C}
3
+ `)||s.includes(S))throw new Error(`Expression "${l}" produced a value containing mdeval comment syntax, which would corrupt the document on re-parse`);return m.set(t,s),s},"resolveValue"),c=[];let p=0;for(const t of e){const l=f.get(t.expression),i=d(l,t.expression);c.push(r.slice(p,t.contentStart),i),p=t.contentEnd}return c.push(r.slice(p)),c.join("")},"processSource");g("#md-loader",import.meta.url),globalThis.block=r=>`
4
+ ${String(r)}
5
+ `;const x=E({name:"mdeval",parameters:["<files...>"]});await Promise.all(x._.files.map(async r=>{try{const o=w.resolve(r),e=await u.readFile(o,"utf8"),n=await v(e,o);n!==e&&(await u.writeFile(o,n,"utf8"),console.log(`Updated: ${r}`))}catch(o){console.error(`Error processing ${r}:`,o instanceof Error?o.message:o),process.exitCode=1}}));
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ var p=Object.defineProperty;var i=(r,o)=>p(r,"name",{value:o,configurable:!0});import c from"node:fs/promises";import{fileURLToPath as m}from"node:url";import{p as f,b as u,E as d}from"./parse-markdown-ChGEvmW3.mjs";import"md4x";const l=i((r,o)=>{const t=r.join(`
3
+ `),s=u(o);if(s.size===0)return t;const e=[...s].map(([n,a])=>`export const ${d}${a} = ${n};`);return`${t}
4
+ ${e.join(`
5
+ `)}`},"generateModule"),$=i(async(r,o,t)=>{if(!r.endsWith(".md"))return t(r,o);const s=await c.readFile(m(r),"utf8"),{scriptBlocks:e,markers:n}=f(s);return e.length===0&&n.length===0?t(r,o):{format:"module",source:l(e,n),shortCircuit:!0}},"load");export{$ as load};
@@ -0,0 +1,3 @@
1
+ var _=Object.defineProperty;var d=(s,t)=>_(s,"name",{value:t,configurable:!0});import{parseAST as R}from"md4x";const x="mdeval",k=`<!--${x}`,O=`${k} `,M=`<!--/${x}-->`,C=`__${x}_`,A="-->",m=`${x}
2
+ `,P=d(s=>{const t=new Map;for(const{expression:e}of s)t.has(e)||t.set(e,t.size);return t},"buildExpressionMap"),S=d((s,t)=>{const e=[],a=[];let l=0;const f=d(r=>{if(!Array.isArray(r))return;const[h,,...c]=r;if(h==="code"){const n=c[0];if(typeof n=="string"&&n.length>0){const o=t.indexOf(n,l);if(o!==-1){a.push([o,o+n.length]),l=o+n.length;return}const i=n.split(`
3
+ `).filter(p=>p.length>0);if(i.length>0){const p=t.indexOf(i[0],l);if(p!==-1){let g=p+i[0].length;for(let E=1;E<i.length;E+=1){const u=t.indexOf(i[E],g);u!==-1&&(g=u+i[E].length)}a.push([p,g]),l=g}}}return}if(h===null&&typeof c[0]=="string"){const n=c[0];n.startsWith(m)&&e.push(n.slice(m.length));const o=`<!--${n}-->`,i=t.indexOf(o,l);i!==-1&&(l=i+o.length);return}for(const n of c)Array.isArray(n)&&f(n)},"walk");for(const r of s.nodes)f(r);return{scriptBlocks:e,codeRanges:a}},"walkAst"),w=d((s,t)=>{let e=0;const a=d(r=>{for(;e<t.length&&t[e][1]<=r;)e+=1;if(e>=t.length)return!1;const[h,c]=t[e];return r>=h&&r<c},"isInCode"),l=[];let f=0;for(;f<s.length;){const r=s.indexOf(O,f);if(r===-1)break;const h=r+O.length,c=s.indexOf(A,h);if(c===-1)break;const n=c+A.length,o=s.indexOf(M,n);if(o===-1){f=n;continue}const i=o+M.length;a(r)||l.push({expression:s.slice(h,c),contentStart:n,contentEnd:o}),f=i}return l},"findMarkers"),y=d(s=>{if(!s.includes(k))return{scriptBlocks:[],markers:[]};const t=R(s),{scriptBlocks:e,codeRanges:a}=S(t,s);return{scriptBlocks:e,markers:w(s,a)}},"parseMarkdown");export{k as C,C as E,O as M,M as a,P as b,y as p};
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "mdeval",
3
+ "version": "1.0.0",
4
+ "description": "Evaluate JavaScript in markdown HTML comments and interpolate results in-place",
5
+ "keywords": [
6
+ "markdown",
7
+ "eval",
8
+ "interpolation",
9
+ "dynamic",
10
+ "readme"
11
+ ],
12
+ "license": "MIT",
13
+ "repository": "privatenumber/mdeval",
14
+ "author": {
15
+ "name": "Hiroki Osame",
16
+ "email": "hiroki.osame@gmail.com"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "skills"
21
+ ],
22
+ "type": "module",
23
+ "bin": "./dist/cli.mjs",
24
+ "imports": {
25
+ "#md-loader": "./dist/md-loader.mjs"
26
+ },
27
+ "engines": {
28
+ "node": ">=20"
29
+ },
30
+ "dependencies": {
31
+ "cleye": "^2.3.0",
32
+ "md4x": "^0.0.25"
33
+ }
34
+ }
@@ -0,0 +1,118 @@
1
+ ---
2
+ name: mdeval
3
+ description: Evaluates JavaScript in markdown HTML comments and interpolates results in-place. Use when editing markdown files that contain mdeval script blocks or value markers, when the user wants computed/dynamic values in markdown, or when maintaining README badges, version numbers, or stats.
4
+ ---
5
+
6
+ # mdeval
7
+
8
+ ## Syntax
9
+
10
+ Two types of HTML comments — invisible when rendered:
11
+
12
+ | Type | Syntax | Purpose |
13
+ |------|--------|---------|
14
+ | Script block | `<!--mdeval\n...\n-->` | Define variables, imports, logic. Starts with `<!--mdeval` + newline |
15
+ | Value marker | `<!--mdeval EXPR-->value<!--/mdeval-->` | Interpolate expression result. Starts with `<!--mdeval ` + space |
16
+
17
+ Script blocks run as ESM with full Node.js access and top-level `await`. All blocks in a file merge into one module — imports and variables are shared across blocks and markers. `import.meta` points to the markdown file.
18
+
19
+ ## Marker Expressions
20
+
21
+ Any JavaScript expression valid on the right side of `const x =`:
22
+
23
+ | Expression | Example |
24
+ |------------|---------|
25
+ | Variable | `<!--mdeval name-->value<!--/mdeval-->` |
26
+ | Property access | `<!--mdeval data.version-->value<!--/mdeval-->` |
27
+ | Computation | `<!--mdeval items.length + " items"-->value<!--/mdeval-->` |
28
+ | IIFE | `<!--mdeval (() => { const x = 1 + 1; return x; })()-->value<!--/mdeval-->` |
29
+
30
+ Duplicate expressions across markers are evaluated once and reused.
31
+
32
+ ## Value Coercion
33
+
34
+ | Type | Result |
35
+ |------|--------|
36
+ | `string` | As-is |
37
+ | `number`, `boolean`, `bigint` | `String(value)` |
38
+ | `object`, `array` | `JSON.stringify(value)` |
39
+ | `undefined`, `null` | Error |
40
+
41
+ ## Patterns
42
+
43
+ ### Read package.json
44
+
45
+ ````markdown
46
+ <!--mdeval
47
+ import fs from 'node:fs/promises';
48
+ const pkg = JSON.parse(await fs.readFile('package.json', 'utf8'));
49
+ -->
50
+
51
+ Version: <!--mdeval pkg.version-->0.0.0<!--/mdeval-->
52
+ ````
53
+
54
+ ### Import from other .md files
55
+
56
+ Only script blocks are executed — markers are not processed:
57
+
58
+ ````markdown
59
+ <!--mdeval
60
+ import { version } from './data.md';
61
+ -->
62
+
63
+ <!--mdeval version-->1.0.0<!--/mdeval-->
64
+ ````
65
+
66
+ ### Generate Markdown with md-pen
67
+
68
+ Use [md-pen](https://github.com/privatenumber/md-pen) for formatted output (tables, lists, headings):
69
+
70
+ ````markdown
71
+ <!--mdeval
72
+ import { table, bold, link } from 'md-pen';
73
+ const deps = [['cleye', '^2.3.0'], ['md-pen', '^0.0.2']];
74
+ const depsTable = table(deps.map(([name, v]) => [link(`https://npm.im/${name}`, bold(name)), v]));
75
+ -->
76
+
77
+ <!--mdeval block(depsTable)-->
78
+ | Package | Version |
79
+ | - | - |
80
+ | [__cleye__](https://npm.im/cleye) | ^2.3.0 |
81
+ <!--/mdeval-->
82
+ ````
83
+
84
+ ## Gotchas
85
+
86
+ **Block-level values need `block()`.** Without it, block elements don't render:
87
+
88
+ ````markdown
89
+ <!-- ❌ Heading stays on same line as comment, won't render -->
90
+ <!--mdeval heading-->### Title<!--/mdeval-->
91
+
92
+ <!-- ✅ block() adds newlines so the heading renders correctly -->
93
+ <!--mdeval block(heading)-->
94
+ ### Title
95
+ <!--/mdeval-->
96
+ ````
97
+
98
+ **Script code cannot contain `-->`** — it closes the HTML comment:
99
+
100
+ ````markdown
101
+ <!-- ❌ --> in the string literal closes the comment prematurely -->
102
+ <!--mdeval
103
+ const x = "<!--/mdeval-->";
104
+ -->
105
+
106
+ <!-- ✅ Build the string without --> -->
107
+ <!--mdeval
108
+ const x = String.fromCharCode(45, 45, 62);
109
+ -->
110
+ ````
111
+
112
+ **Values cannot contain mdeval syntax.** Producing `<!--mdeval ` or `<!--/mdeval-->` in a value throws an error to prevent document corruption on re-parse.
113
+
114
+ **Place scripts at the top.** Order doesn't affect execution — scripts can appear after the markers that reference them — but top placement signals the file contains generated content.
115
+
116
+ **Use IIFEs to co-locate logic.** In large docs, keep marker-specific computation inline instead of in a distant script block: `<!--mdeval (() => { ... })()-->`.
117
+
118
+ **Markers in code blocks are safe.** Fenced, indented, and inline code won't be touched — safe to document mdeval syntax in your own README.