md2x 0.7.5 → 0.7.7

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/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{b as t,c as r,e,f as a,g as n,h as m,i as d,j as p,k as i,l as f,m as s,n as l,o as O,p as u,q as x,r as T}from"./chunks/chunk-54X5GPSM.js";import"./chunks/chunk-US45GBOT.js";import*as o from"path";import{fileURLToPath as M}from"url";var g=M(import.meta.url),w=o.dirname(g);globalThis.__md2x_module_dir__=w;export{n as NodeDocxExporter,p as NodeHtmlExporter,d as NodeImageExporter,m as NodePdfExporter,x as convert,T as convertFile,r as frontMatterToOptions,i as markdownToDocxBuffer,e as markdownToHtml,l as markdownToHtmlBuffer,s as markdownToHtmlString,O as markdownToImageBuffer,u as markdownToImageBuffers,f as markdownToPdfBuffer,a as markdownToStandaloneHtml,t as parseFrontMatter};
1
+ import{b as t,c as r,f as e,g as a,h as n,i as m,j as d,k as p,l as i,m as f,n as s,o as l,p as O,q as u,r as x,s as T}from"./chunks/chunk-HHNNUKAW.js";import"./chunks/chunk-UZ7TETMS.js";import*as o from"path";import{fileURLToPath as M}from"url";var g=M(import.meta.url),w=o.dirname(g);globalThis.__md2x_module_dir__=w;export{n as NodeDocxExporter,p as NodeHtmlExporter,d as NodeImageExporter,m as NodePdfExporter,x as convert,T as convertFile,r as frontMatterToOptions,i as markdownToDocxBuffer,e as markdownToHtml,l as markdownToHtmlBuffer,s as markdownToHtmlString,O as markdownToImageBuffer,u as markdownToImageBuffers,f as markdownToPdfBuffer,a as markdownToStandaloneHtml,t as parseFrontMatter};
package/dist/md2x.js CHANGED
@@ -1,10 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import{a as k,b as $,c as S,d as T,q as O}from"./chunks/chunk-54X5GPSM.js";import"./chunks/chunk-US45GBOT.js";import*as a from"fs";import*as n from"path";import{fileURLToPath as U,pathToFileURL as q}from"url";var I=U(import.meta.url),P=n.dirname(I);globalThis.__md2x_module_dir__=P;function N(){return globalThis.__md2x_module_dir__||P}function H(o,e){let t={},s=(m=>{let i=String(m||"").trim();if(!i)return"";try{if(i.toLowerCase().startsWith("file://"))return U(i)}catch{}return n.isAbsolute(i)?i:n.join(e,i)})(o);if(!s||!a.existsSync(s))return t;let r=m=>{let i;try{i=a.statSync(m)}catch{return}if(i.isDirectory()){let x=[];try{x=a.readdirSync(m)}catch{return}for(let E of x)r(n.join(m,E));return}if(!i.isFile())return;let u="";try{u=a.readFileSync(m,"utf-8")}catch{return}let h=n.relative(s,m).split(n.sep).join("/"),g=n.basename(m);t[h]=u,t[g]=u,t[`./${h}`]=u;try{t[q(m).href]=u}catch{}};return r(s),t}function W(o,e){let t={};for(let p of o)Object.assign(t,H(p,e));return t}function X(o){let e=n.extname(o).toLowerCase();return e===".pdf"?"pdf":e===".docx"?"docx":e===".html"||e===".htm"?"html":e===".png"?"png":e===".jpg"?"jpg":e===".jpeg"?"jpeg":e===".webp"?"webp":null}function M(){return["default",...k.themes.map(t=>t.id).sort().filter(t=>t!=="default")]}function B(o){return o.join(", ")}function F(){let o=M();console.log(`
2
+ import{a as S,b as U,c as $,d as T,r as k}from"./chunks/chunk-HHNNUKAW.js";import"./chunks/chunk-UZ7TETMS.js";import*as a from"fs";import*as s from"path";import{fileURLToPath as F,pathToFileURL as q}from"url";var I=F(import.meta.url),L=s.dirname(I);globalThis.__md2x_module_dir__=L;function N(){return globalThis.__md2x_module_dir__||L}function H(o,e){let t={},n=(m=>{let i=String(m||"").trim();if(!i)return"";try{if(i.toLowerCase().startsWith("file://"))return F(i)}catch{}return s.isAbsolute(i)?i:s.join(e,i)})(o);if(!n||!a.existsSync(n))return t;let r=m=>{let i;try{i=a.statSync(m)}catch{return}if(i.isDirectory()){let u=[];try{u=a.readdirSync(m)}catch{return}for(let R of u)r(s.join(m,R));return}if(!i.isFile())return;let c="";try{c=a.readFileSync(m,"utf-8")}catch{return}let g=s.relative(n,m).split(s.sep).join("/"),x=s.basename(m);t[g]=c,t[x]=c,t[`./${g}`]=c;try{t[q(m).href]=c}catch{}};return r(n),t}function W(o,e){let t={};for(let p of o)Object.assign(t,H(p,e));return t}async function X(o){try{let e=await fetch(o);if(!e.ok)return console.error(`Warning: Failed to fetch templates from URL: ${e.status} ${e.statusText}`),{};let t=await e.json();return typeof t!="object"||t===null?(console.error("Warning: Templates URL did not return a valid JSON object"),{}):t}catch(e){return console.error(`Warning: Failed to fetch templates from URL: ${e instanceof Error?e.message:String(e)}`),{}}}function J(o){let e=s.extname(o).toLowerCase();return e===".pdf"?"pdf":e===".docx"?"docx":e===".html"||e===".htm"?"html":e===".png"?"png":e===".jpg"?"jpg":e===".jpeg"?"jpeg":e===".webp"?"webp":null}function y(){return["default",...S.themes.map(t=>t.id).sort().filter(t=>t!=="default")]}function P(o){return o.join(", ")}function O(){let o=y();console.log(`
3
3
  md2x - Convert Markdown to PDF, DOCX, HTML, or Image
4
4
 
5
5
  Usage:
6
6
  npx md2x <input.md> [output] [options]
7
7
  md2x <input.md> [output] [options]
8
+ md2x --mcp (Start MCP server mode)
8
9
 
9
10
  Arguments:
10
11
  input.md Input markdown file (required)
@@ -16,6 +17,7 @@ Options:
16
17
  -t, --theme Theme name (default: "default")
17
18
  -h, --help Show this help message
18
19
  -v, --version Show version number
20
+ --mcp Start MCP (Model Context Protocol) server mode
19
21
  --diagram-mode img | live | none (default: img for DOCX; live for HTML/Image)
20
22
  --live-runtime inline | cdn (HTML + diagramMode=live; default: cdn)
21
23
  --live-runtime-url Custom runtime URL when --live-runtime cdn
@@ -32,10 +34,11 @@ Examples:
32
34
  npx md2x README.md -f html -o output.html
33
35
  npx md2x README.md -f png -o output.png
34
36
  npx md2x --list-themes
37
+ npx md2x --mcp
35
38
 
36
39
  Available Themes:
37
- ${B(o)}
38
- `)}function z(){let o=N(),e=[n.join(o,"../package.json"),n.join(o,"../../package.json")];for(let t of e)try{let p=JSON.parse(a.readFileSync(t,"utf-8"));if(p?.version){console.log(`md2x v${p.version}`);return}}catch{}console.log("md2x v1.0.0")}function J(){let o=M();console.log(`
40
+ ${P(o)}
41
+ `)}function z(){let o=N(),e=[s.join(o,"../package.json"),s.join(o,"../../package.json")];for(let t of e)try{let p=JSON.parse(a.readFileSync(t,"utf-8"));if(p?.version){console.log(`md2x v${p.version}`);return}}catch{}console.log("md2x v1.0.0")}function K(){let o=y();console.log(`
39
42
  Available Themes:
40
- `),o.forEach(e=>{console.log(` - ${e}`)}),console.log("")}function K(o){let e={input:"",output:"",theme:"default",format:"pdf",help:!1,version:!1,listThemes:!1,diagramMode:"live",templatesDir:[],liveRuntime:void 0,liveRuntimeBaseUrl:void 0,hrPageBreak:null,_explicit:new Set},t=0,p=[];for(;t<o.length;){let s=o[t];if(s==="--"){t++;continue}if(s==="-h"||s==="--help")e.help=!0;else if(s==="-v"||s==="--version")e.version=!0;else if(s==="--list-themes")e.listThemes=!0;else if(s==="--diagram-mode")if(t++,t<o.length){let r=String(o[t]).toLowerCase();r!=="img"&&r!=="live"&&r!=="none"&&(console.error(`Error: Invalid --diagram-mode "${o[t]}". Must be "img", "live", or "none".`),process.exit(1)),e.diagramMode=r,e._explicit.add("diagramMode")}else console.error("Error: --diagram-mode requires a value (img | live | none)"),process.exit(1);else if(s==="-o"||s==="--output")t++,t<o.length?e.output=o[t]:(console.error("Error: --output requires a file path"),process.exit(1));else if(s==="-t"||s==="--theme")t++,t<o.length?(e.theme=o[t],e._explicit.add("theme")):(console.error("Error: --theme requires a theme name"),process.exit(1));else if(s==="-f"||s==="--format")if(t++,t<o.length){let r=o[t].toLowerCase();r!=="pdf"&&r!=="docx"&&r!=="html"&&r!=="png"&&r!=="jpg"&&r!=="jpeg"&&r!=="webp"&&(console.error(`Error: Invalid format "${o[t]}". Must be "pdf", "docx", "html", "png", "jpg/jpeg", or "webp".`),process.exit(1)),e.format=r,e._explicit.add("format")}else console.error("Error: --format requires a format (pdf, docx, html, png, jpg/jpeg, or webp)"),process.exit(1);else if(s==="--hr-page-break")if(t++,t<o.length){let r=o[t].toLowerCase();r!=="true"&&r!=="false"&&(console.error(`Error: Invalid --hr-page-break "${o[t]}". Must be "true" or "false".`),process.exit(1)),e.hrPageBreak=r==="true",e._explicit.add("hrPageBreak")}else console.error("Error: --hr-page-break requires a value (true | false)"),process.exit(1);else if(s==="--templates-dir")if(t++,t<o.length){let r=String(o[t]).trim();r||(console.error("Error: --templates-dir requires a non-empty path"),process.exit(1)),e.templatesDir.push(r),e._explicit.add("templatesDir")}else console.error("Error: --templates-dir requires a path"),process.exit(1);else if(s==="--live-runtime")if(t++,t<o.length){let r=String(o[t]).toLowerCase();r!=="inline"&&r!=="cdn"&&(console.error(`Error: Invalid --live-runtime "${o[t]}". Must be "inline" or "cdn".`),process.exit(1)),e.liveRuntime=r,e._explicit.add("liveRuntime")}else console.error("Error: --live-runtime requires a value (inline | cdn)"),process.exit(1);else if(s==="--live-runtime-url")if(t++,t<o.length){let r=String(o[t]).trim();r||(console.error("Error: --live-runtime-url requires a non-empty URL"),process.exit(1)),e.liveRuntimeBaseUrl=r,e._explicit.add("liveRuntimeBaseUrl")}else console.error("Error: --live-runtime-url requires a URL"),process.exit(1);else s.startsWith("-")?(console.error(`Error: Unknown option: ${s}`),process.exit(1)):p.push(s);t++}return p.length>0&&(e.input=p[0]),p.length>1&&!e.output&&(e.output=p[1]),e}async function V(){let o=process.argv.slice(2),e=K(o);e.help&&(F(),process.exit(0)),e.version&&(z(),process.exit(0)),e.listThemes&&(J(),process.exit(0)),e.input||(console.error(`Error: Input file is required
41
- `),F(),process.exit(1));let t=n.resolve(e.input);a.existsSync(t)||(console.error(`Error: Input file not found: ${t}`),process.exit(1));try{a.accessSync(t,a.constants.R_OK)}catch{console.error(`Error: Cannot read input file: ${t}`),process.exit(1)}let p=a.readFileSync(t,"utf-8"),s=$(p),r=s.hasFrontMatter?S(s.data):{},m=!e._explicit.has("format")&&e.output?X(e.output):null,i=e._explicit.has("format")?e.format:r.format??m??e.format,u=e._explicit.has("theme")?e.theme:r.theme??e.theme,b=i==="png"||i==="jpg"||i==="jpeg"||i==="webp",h=i==="docx"?"img":"live",g=e._explicit.has("diagramMode")?e.diagramMode:r.diagramMode??h,x=e._explicit.has("templatesDir")?{...r.templates??{},...W(e.templatesDir,n.dirname(t))}:r.templates??{},E=e._explicit.has("liveRuntime")?e.liveRuntime:r.liveRuntime??e.liveRuntime,L=e._explicit.has("liveRuntimeBaseUrl")?e.liveRuntimeBaseUrl:r.liveRuntimeBaseUrl??e.liveRuntimeBaseUrl,_=e._explicit.has("hrPageBreak")?e.hrPageBreak:r.hrAsPageBreak??!(i==="html"||i==="png"||i==="jpg"||i==="jpeg"||i==="webp"),D=M();D.length>0&&!D.includes(u)&&(console.error(`Error: Unknown theme: ${u}`),console.error(`Available themes: ${B(D)}`),console.error("Tip: run `npx md2x --list-themes` to see the full list."),process.exit(1)),console.log(`Converting: ${n.basename(t)}`),console.log(`Format: ${i.toUpperCase()}`),console.log(`Theme: ${u}`),console.log(`HR as page break: ${_}`),(i==="pdf"||i==="html"||i==="png"||i==="jpg"||i==="jpeg"||i==="webp")&&console.log(`Diagram mode: ${g}`);try{let l=e.output,c=T(i);if(l)l=n.resolve(l);else{let f=n.dirname(t),R=n.basename(t,n.extname(t));l=n.join(f,`${R}${c}`)}let y=n.dirname(l);a.existsSync(y)||a.mkdirSync(y,{recursive:!0});let A=b?{...r.image??{},type:i==="jpg"?"jpeg":i,split:r.image?.split??"auto"}:void 0,d=await O(s.content,{format:i,theme:u,diagramMode:g,hrAsPageBreak:_,basePath:n.dirname(t),title:r.title??n.basename(t,n.extname(t)),pdf:r.pdf,standalone:r.standalone,baseTag:r.baseTag,liveRuntime:E,liveRuntimeBaseUrl:L,cdn:r.cdn,templates:x,image:A,skipFrontMatter:!0});if(b){let f=d.buffers&&d.buffers.length>0?d.buffers:[d.buffer];if(f.length<=1){a.writeFileSync(l,f[0]),console.log(`Output: ${l}`),console.log("Done!");return}let R=l.endsWith(c)?l.slice(0,-c.length):l,w=[];for(let v=0;v<f.length;v++){let C=String(v+1).padStart(3,"0"),j=`${R}.part-${C}${c}`;a.writeFileSync(j,f[v]),w.push(j)}console.log(`Output: ${w[0]} (+${w.length-1} parts)`),console.log("Done!");return}a.writeFileSync(l,d.buffer),console.log(`Output: ${l}`),console.log("Done!")}catch(l){let c=l instanceof Error?l.message:String(l);console.error(`Error during conversion: ${c}`),process.exit(1)}}V().catch(o=>{console.error("Unexpected error:",o),process.exit(1)});
43
+ `),o.forEach(e=>{console.log(` - ${e}`)}),console.log("")}function V(o){let e={input:"",output:"",theme:"default",format:"pdf",help:!1,version:!1,listThemes:!1,mcp:!1,diagramMode:"live",templatesDir:[],templatesUrl:void 0,liveRuntime:void 0,liveRuntimeBaseUrl:void 0,hrPageBreak:null,_explicit:new Set},t=0,p=[];for(;t<o.length;){let n=o[t];if(n==="--"){t++;continue}if(n==="-h"||n==="--help")e.help=!0;else if(n==="-v"||n==="--version")e.version=!0;else if(n==="--list-themes")e.listThemes=!0;else if(n==="--mcp")e.mcp=!0;else if(n==="--diagram-mode")if(t++,t<o.length){let r=String(o[t]).toLowerCase();r!=="img"&&r!=="live"&&r!=="none"&&(console.error(`Error: Invalid --diagram-mode "${o[t]}". Must be "img", "live", or "none".`),process.exit(1)),e.diagramMode=r,e._explicit.add("diagramMode")}else console.error("Error: --diagram-mode requires a value (img | live | none)"),process.exit(1);else if(n==="-o"||n==="--output")t++,t<o.length?e.output=o[t]:(console.error("Error: --output requires a file path"),process.exit(1));else if(n==="-t"||n==="--theme")t++,t<o.length?(e.theme=o[t],e._explicit.add("theme")):(console.error("Error: --theme requires a theme name"),process.exit(1));else if(n==="-f"||n==="--format")if(t++,t<o.length){let r=o[t].toLowerCase();r!=="pdf"&&r!=="docx"&&r!=="html"&&r!=="png"&&r!=="jpg"&&r!=="jpeg"&&r!=="webp"&&(console.error(`Error: Invalid format "${o[t]}". Must be "pdf", "docx", "html", "png", "jpg/jpeg", or "webp".`),process.exit(1)),e.format=r,e._explicit.add("format")}else console.error("Error: --format requires a format (pdf, docx, html, png, jpg/jpeg, or webp)"),process.exit(1);else if(n==="--hr-page-break")if(t++,t<o.length){let r=o[t].toLowerCase();r!=="true"&&r!=="false"&&(console.error(`Error: Invalid --hr-page-break "${o[t]}". Must be "true" or "false".`),process.exit(1)),e.hrPageBreak=r==="true",e._explicit.add("hrPageBreak")}else console.error("Error: --hr-page-break requires a value (true | false)"),process.exit(1);else if(n==="--templates-dir")if(t++,t<o.length){let r=String(o[t]).trim();r||(console.error("Error: --templates-dir requires a non-empty path"),process.exit(1)),e.templatesDir.push(r),e._explicit.add("templatesDir")}else console.error("Error: --templates-dir requires a path"),process.exit(1);else if(n==="--templates-url")if(t++,t<o.length){let r=String(o[t]).trim();r||(console.error("Error: --templates-url requires a non-empty URL"),process.exit(1)),e.templatesUrl=r,e._explicit.add("templatesUrl")}else console.error("Error: --templates-url requires a URL"),process.exit(1);else if(n==="--live-runtime")if(t++,t<o.length){let r=String(o[t]).toLowerCase();r!=="inline"&&r!=="cdn"&&(console.error(`Error: Invalid --live-runtime "${o[t]}". Must be "inline" or "cdn".`),process.exit(1)),e.liveRuntime=r,e._explicit.add("liveRuntime")}else console.error("Error: --live-runtime requires a value (inline | cdn)"),process.exit(1);else if(n==="--live-runtime-url")if(t++,t<o.length){let r=String(o[t]).trim();r||(console.error("Error: --live-runtime-url requires a non-empty URL"),process.exit(1)),e.liveRuntimeBaseUrl=r,e._explicit.add("liveRuntimeBaseUrl")}else console.error("Error: --live-runtime-url requires a URL"),process.exit(1);else n.startsWith("-")?(console.error(`Error: Unknown option: ${n}`),process.exit(1)):p.push(n);t++}return p.length>0&&(e.input=p[0]),p.length>1&&!e.output&&(e.output=p[1]),e}async function G(){let o=process.argv.slice(2),e=V(o);if(e.mcp){let{startMcpServer:l}=await import("./chunks/mcp-server-V5MM5C5I.js");await l();return}e.help&&(O(),process.exit(0)),e.version&&(z(),process.exit(0)),e.listThemes&&(K(),process.exit(0)),e.input||(console.error(`Error: Input file is required
44
+ `),O(),process.exit(1));let t=s.resolve(e.input);a.existsSync(t)||(console.error(`Error: Input file not found: ${t}`),process.exit(1));try{a.accessSync(t,a.constants.R_OK)}catch{console.error(`Error: Cannot read input file: ${t}`),process.exit(1)}let p=a.readFileSync(t,"utf-8"),n=U(p),r=n.hasFrontMatter?$(n.data):{},m=!e._explicit.has("format")&&e.output?J(e.output):null,i=e._explicit.has("format")?e.format:r.format??m??e.format,c=e._explicit.has("theme")?e.theme:r.theme??e.theme,b=i==="png"||i==="jpg"||i==="jpeg"||i==="webp",g=i==="docx"?"img":"live",x=e._explicit.has("diagramMode")?e.diagramMode:r.diagramMode??g,u={};e._explicit.has("templatesUrl")&&e.templatesUrl&&(u=await X(e.templatesUrl)),e._explicit.has("templatesDir")&&Object.assign(u,W(e.templatesDir,s.dirname(t))),r.templates&&Object.assign(u,r.templates);let R=e._explicit.has("liveRuntime")?e.liveRuntime:r.liveRuntime??e.liveRuntime,C=e._explicit.has("liveRuntimeBaseUrl")?e.liveRuntimeBaseUrl:r.liveRuntimeBaseUrl??e.liveRuntimeBaseUrl,D=e._explicit.has("hrPageBreak")?e.hrPageBreak:r.hrAsPageBreak??!(i==="html"||i==="png"||i==="jpg"||i==="jpeg"||i==="webp"),E=y();E.length>0&&!E.includes(c)&&(console.error(`Error: Unknown theme: ${c}`),console.error(`Available themes: ${P(E)}`),console.error("Tip: run `npx md2x --list-themes` to see the full list."),process.exit(1)),console.log(`Converting: ${s.basename(t)}`),console.log(`Format: ${i.toUpperCase()}`),console.log(`Theme: ${c}`),console.log(`HR as page break: ${D}`),(i==="pdf"||i==="html"||i==="png"||i==="jpg"||i==="jpeg"||i==="webp")&&console.log(`Diagram mode: ${x}`);try{let l=e.output,f=T(i);if(l)l=s.resolve(l);else{let d=s.dirname(t),w=s.basename(t,s.extname(t));l=s.join(d,`${w}${f}`)}let j=s.dirname(l);a.existsSync(j)||a.mkdirSync(j,{recursive:!0});let B=b?{...r.image??{},type:i==="jpg"?"jpeg":i,split:r.image?.split??"auto"}:void 0,h=await k(n.content,{format:i,theme:c,diagramMode:x,hrAsPageBreak:D,basePath:s.dirname(t),title:r.title??s.basename(t,s.extname(t)),pdf:r.pdf,standalone:r.standalone,baseTag:r.baseTag,liveRuntime:R,liveRuntimeBaseUrl:C,cdn:r.cdn,templates:u,image:B,skipFrontMatter:!0});if(b){let d=h.buffers&&h.buffers.length>0?h.buffers:[h.buffer];if(d.length<=1){a.writeFileSync(l,d[0]),console.log(`Output: ${l}`),console.log("Done!");return}let w=l.endsWith(f)?l.slice(0,-f.length):l,M=[];for(let v=0;v<d.length;v++){let A=String(v+1).padStart(3,"0"),_=`${w}.part-${A}${f}`;a.writeFileSync(_,d[v]),M.push(_)}console.log(`Output: ${M[0]} (+${M.length-1} parts)`),console.log("Done!");return}a.writeFileSync(l,h.buffer),console.log(`Output: ${l}`),console.log("Done!")}catch(l){let f=l instanceof Error?l.message:String(l);console.error(`Error during conversion: ${f}`),process.exit(1)}}G().catch(o=>{console.error("Unexpected error:",o),process.exit(1)});
@@ -4,7 +4,7 @@
4
4
  `,u++);continue}}e+=p}return e}function qt(r){let e="",t=!1,n=!1,i=!1;for(let o=0;o<r.length;o++){let s=r[o];if(i){e+=s,i=!1;continue}if(s==="\\\\"){e+=s,i=!0;continue}if(!n&&s==="'"){t=!t,e+=s;continue}if(!t&&s==='"'){n=!n,e+=s;continue}if(!t&&!n&&s===","){let a=o+1;for(;a<r.length&&/\s/.test(r[a]);)a++;let c=r[a];if(c==="}"||c==="]")continue}e+=s}return e}function Vt(r){let e="",t=!1,n=!1,i=!1;for(let o=0;o<r.length;o++){let s=r[o];if(i){e+=s,i=!1;continue}if(s==="\\\\"){e+=s,i=!0;continue}if(!n&&s==="'"){t=!t,e+='"';continue}if(!t&&s==='"'){n=!n,e+=s;continue}if(t&&s==='"'){e+='\\\\"';continue}e+=s}return e}function Gt(r){let e="",t=0,n=!1,i=!1,o=!1,s=c=>/[A-Za-z_$]/.test(c),a=c=>/[A-Za-z0-9_$-]/.test(c);for(;t<r.length;){let c=r[t];if(o){e+=c,o=!1,t++;continue}if(c==="\\\\"){e+=c,o=!0,t++;continue}if(!i&&c==="'"){n=!n,e+=c,t++;continue}if(!n&&c==='"'){i=!i,e+=c,t++;continue}if(!n&&!i){let u=e.length-1;for(;u>=0&&/\s/.test(e[u]);)u--;let p=u>=0?e[u]:"";if((p==="{"||p===","||p==="")&&s(c)){let h=t+1;for(;h<r.length&&a(r[h]);)h++;let d=h;for(;d<r.length&&/\s/.test(r[d]);)d++;if(r[d]===":"){let w=r.slice(t,h);e+=`"${w}"`,t=h;continue}}}e+=c,t++}return e}function be(r){let e=zt(String(r||"").trim());if(!e)throw new Error("Empty md2x block");let t=Wt(e.trim().startsWith("{")?e:`{${e}
5
5
  }`);try{let u=JSON.parse(t);if(!Ye(u))throw new Error("md2x config must be an object");let p=String(u.type||"").trim(),f=String(u.template||"").trim();if(!p||p!=="vue"&&p!=="html"&&p!=="svelte")throw new Error('md2x.type must be "vue", "html", or "svelte"');if(!f)throw new Error("md2x.template is required");let h=typeof u.allowTemplateAssets=="boolean"?u.allowTemplateAssets:typeof u.allowCdn=="boolean"?u.allowCdn:void 0,d=typeof u.allowScripts=="boolean"?u.allowScripts:void 0;return{type:p,template:f,data:u.data,allowTemplateAssets:h,allowScripts:d}}catch{}let n=qt(Gt(Vt(t))),i;try{i=JSON.parse(n)}catch(u){throw new Error(`Invalid md2x config (expected object literal): ${u.message}`)}if(!Ye(i))throw new Error("md2x config must be an object");let o=String(i.type||"").trim(),s=String(i.template||"").trim();if(!o||o!=="vue"&&o!=="html"&&o!=="svelte")throw new Error('md2x.type must be "vue", "html", or "svelte"');if(!s)throw new Error("md2x.template is required");let a=typeof i.allowTemplateAssets=="boolean"?i.allowTemplateAssets:typeof i.allowCdn=="boolean"?i.allowCdn:void 0,c=typeof i.allowScripts=="boolean"?i.allowScripts:void 0;return{type:o,template:s,data:i.data,allowTemplateAssets:a,allowScripts:c}}function Jt(r){return JSON.stringify(r).replace(/</g,"\\u003c")}function O(r,e){let t=Jt(e??null);return String(r||"").split("templateData").join(`(${t})`)}function ie(r){if(!Array.isArray(r))return[];let e=[],t=new Set;for(let n of r){if(typeof n!="string")continue;let i=n.trim();i&&(t.has(i)||(t.add(i),e.push(i)))}return e}function Yt(r){if(!r||typeof r!="object")return null;let e=r.assets;if(!e||typeof e!="object")return null;let t=ie(e.scripts),n=ie(e.styles);return!t.length&&!n.length?null:{assets:{scripts:t,styles:n}}}function X(r){let e=String(r||"");if(!e)return{source:e,templateConfig:null};let t=0;for(e.charCodeAt(0)===65279&&(t=1);t<e.length&&/\s/.test(e[t]);)t++;if(e.slice(t,t+4)!=="<!--")return{source:e,templateConfig:null};let n=e.indexOf("-->",t+4);if(n===-1)return{source:e,templateConfig:null};let i=e.slice(t+4,n).trim(),o="TemplateConfig:";if(!i.startsWith(o))return{source:e,templateConfig:null};let s=i.slice(o.length).trim(),a=e.slice(n+3);a.startsWith(`\r
6
6
  `)?a=a.slice(2):(a.startsWith(`
7
- `)||a.startsWith("\r"))&&(a=a.slice(1));let c=e.slice(0,t)+a;if(!s)return{source:c,templateConfig:null};try{let u=JSON.parse(s);return{source:c,templateConfig:Yt(u)}}catch(u){return{source:c,templateConfig:null,error:u.message}}}function Ke(r){let e=String(r||"").trim();if(!e)return e;try{return new URL(e,document.baseURI).href}catch{return e}}async function Kt(r){let e=Ke(r);if(!e)return;let t=globalThis.CSS?.escape?globalThis.CSS.escape(e):e.replace(/"/g,'\\"');document.querySelector(`link[rel="stylesheet"][href="${t}"]`)||await new Promise(i=>{let o=document.createElement("link");o.rel="stylesheet",o.href=e,o.onload=()=>i(),o.onerror=()=>i(),document.head.appendChild(o)})}async function Z(r){let e=ie(r?.assets?.scripts),t=ie(r?.assets?.styles);for(let n of t)await Kt(n);for(let n of e)await xe(Ke(n))}async function xe(r,e){if(e&&globalThis[e])return;let t=globalThis.CSS?.escape?globalThis.CSS.escape(r):r.replace(/"/g,'\\"'),n=document.querySelector(`script[src="${t}"]`);if(n){if(n.__md2xLoaded)return;await new Promise((i,o)=>{n.addEventListener("load",()=>i(),{once:!0}),n.addEventListener("error",()=>o(new Error("Failed to load script: "+r)),{once:!0})}),n.__md2xLoaded=!0;return}await new Promise((i,o)=>{let s=document.createElement("script");s.src=r,s.async=!1,s.onload=()=>{s.__md2xLoaded=!0,i()},s.onerror=()=>{s.__md2xLoaded=!0,o(new Error("Failed to load script: "+r))},document.head.appendChild(s)})}var oe=class extends G{constructor(){super("md2x");this.htmlRenderer=new ne;this.vueReady=null;this.svelteCompilerReady=null}getTemplateSource(t,n,i){let o=String(i||"").trim(),s=Ot(n,o),a=t??{},c=[];s&&c.push(s),o&&o!==s&&c.push(o);try{s&&c.push(new URL(s,document.baseURI).href)}catch{}try{o&&c.push(new URL(o,document.baseURI).href)}catch{}for(let u of c){let p=a[u];if(typeof p=="string")return{templateRef:s||o,source:p}}return{templateRef:s||o,source:null}}async ensureVueRuntime(t){if(this.vueReady)return this.vueReady;let n=t?.vue||"https://unpkg.com/vue@3/dist/vue.global.js",i=t?.vueSfcLoader||"https://cdn.jsdelivr.net/npm/vue3-sfc-loader/dist/vue3-sfc-loader.js";return this.vueReady=(async()=>{await xe(n,"Vue"),await xe(i,"vue3-sfc-loader")})(),this.vueReady}async ensureSvelteCompiler(t){if(this.svelteCompilerReady)return this.svelteCompilerReady;let n=t?.svelteCompiler||"https://esm.sh/svelte@5/compiler";return this.svelteCompilerReady=(async()=>await J(n))(),this.svelteCompilerReady}async renderAsErrorPng(t,n){let i=`<div style="font-family: sans-serif; font-size: 12px; color: #b00020;">
7
+ `)||a.startsWith("\r"))&&(a=a.slice(1));let c=e.slice(0,t)+a;if(!s)return{source:c,templateConfig:null};try{let u=JSON.parse(s);return{source:c,templateConfig:Yt(u)}}catch(u){return{source:c,templateConfig:null,error:u.message}}}function Ke(r){let e=String(r||"").trim();if(!e)return e;try{return new URL(e,document.baseURI).href}catch{return e}}async function Kt(r){let e=Ke(r);if(!e)return;let t=globalThis.CSS?.escape?globalThis.CSS.escape(e):e.replace(/"/g,'\\"');document.querySelector(`link[rel="stylesheet"][href="${t}"]`)||await new Promise(i=>{let o=document.createElement("link");o.rel="stylesheet",o.href=e,o.onload=()=>i(),o.onerror=()=>i(),document.head.appendChild(o)})}async function Z(r){let e=ie(r?.assets?.scripts),t=ie(r?.assets?.styles);for(let n of t)await Kt(n);for(let n of e)await xe(Ke(n))}async function xe(r,e){if(e&&globalThis[e])return;let t=globalThis.CSS?.escape?globalThis.CSS.escape(r):r.replace(/"/g,'\\"'),n=document.querySelector(`script[src="${t}"]`);if(n){if(n.__md2xLoaded)return;await new Promise((i,o)=>{n.addEventListener("load",()=>i(),{once:!0}),n.addEventListener("error",()=>o(new Error("Failed to load script: "+r)),{once:!0})}),n.__md2xLoaded=!0;return}await new Promise((i,o)=>{let s=document.createElement("script");s.src=r,s.async=!1,s.onload=()=>{s.__md2xLoaded=!0,i()},s.onerror=()=>{s.__md2xLoaded=!0,o(new Error("Failed to load script: "+r))},document.head.appendChild(s)})}var oe=class extends G{constructor(){super("md2x");this.htmlRenderer=new ne;this.vueReady=null;this.svelteCompilerReady=null}getTemplateSource(t,n,i){let o=String(i||"").trim(),s=Ot(n,o),a=t??{},c=[];s&&c.push(s),o&&o!==s&&c.push(o);try{s&&c.push(new URL(s,document.baseURI).href)}catch{}try{o&&c.push(new URL(o,document.baseURI).href)}catch{}for(let u of c){let p=a[u];if(typeof p=="string")return{templateRef:s||o,source:p}}return{templateRef:s||o,source:null}}async ensureVueRuntime(t){if(this.vueReady)return this.vueReady;let n=t?.vue||"https://cdn.jsdelivr.net/npm/vue/dist/vue.global.js",i=t?.vueSfcLoader||"https://cdn.jsdelivr.net/npm/vue3-sfc-loader/dist/vue3-sfc-loader.js";return this.vueReady=(async()=>{await xe(n,"Vue"),await xe(i,"vue3-sfc-loader")})(),this.vueReady}async ensureSvelteCompiler(t){if(this.svelteCompilerReady)return this.svelteCompilerReady;let n=t?.svelteCompiler||"https://esm.sh/svelte@5/compiler";return this.svelteCompilerReady=(async()=>await J(n))(),this.svelteCompilerReady}async renderAsErrorPng(t,n){let i=`<div style="font-family: sans-serif; font-size: 12px; color: #b00020;">
8
8
  <div style="font-weight: 600; margin-bottom: 6px;">md2x render error</div>
9
9
  <pre style="white-space: pre-wrap; margin: 0;">${t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}</pre>
10
10
  </div>`;return await this.htmlRenderer.render(i,n)}async runHtmlTemplateScripts(t,n){let i=n??{},o=Array.from(t.querySelectorAll("script")),s=a=>{let c=String(a||"").trim();if(!c)return null;if(typeof i[c]=="string")return i[c];try{let u=new URL(c,document.baseURI).href;if(typeof i[u]=="string")return i[u]}catch{}return null};for(let a of o){let c=a.parentNode;if(!c)continue;if(String(a.getAttribute("type")||"").trim().toLowerCase()==="module")throw new Error('md2x html template: <script type="module"> is not supported for PNG rendering');let p=a.getAttribute("src");if(p){let h=s(p);if(h==null)throw new Error(`md2x html template: external <script src="${p}"> is not supported unless it is provided via templateFiles`);let d=document.createElement("script");for(let w of Array.from(a.attributes||[])){let m=String(w?.name||"");if(m&&!(m==="src"||m==="async"||m==="defer"))try{d.setAttribute(m,w.value)}catch{}}d.textContent=String(h||""),c.replaceChild(d,a);continue}let f=document.createElement("script");for(let h of Array.from(a.attributes||[])){let d=String(h?.name||"");if(d&&!(d==="async"||d==="defer"))try{f.setAttribute(d,h.value)}catch{}}f.textContent=a.textContent||"",c.replaceChild(f,a)}}async renderHtmlTemplate(t,n,i){let{templateRef:o,source:s}=this.getTemplateSource(n,t.type,t.template);if(!s)return await this.renderAsErrorPng(`Missing md2x template: ${o||t.template}`,i);let a=X(s);if(t.allowTemplateAssets){if(a.error)return await this.renderAsErrorPng(`Invalid TemplateConfig JSON: ${a.error}`,i);try{await Z(a.templateConfig)}catch(f){return await this.renderAsErrorPng(`Failed to load TemplateConfig assets: ${f.message}`,i)}}let c=O(a.source,t.data);if(!t.allowScripts)return await this.htmlRenderer.render(c,i);let u=this.createContainer();u.style.cssText="position: absolute; left: -9999px; top: -9999px; display: inline-block; background: transparent; padding: 0; margin: 0;";let p=document.createElement("div");p.style.cssText="display: inline-block;",u.appendChild(p);try{p.innerHTML=c,await this.runHtmlTemplateScripts(p,n);for(let f of Array.from(p.querySelectorAll("script")))try{f.remove()}catch{}try{typeof globalThis.requestAnimationFrame=="function"&&await new Promise(f=>globalThis.requestAnimationFrame(()=>f()))}catch{}try{document.fonts?.ready&&await document.fonts.ready}catch{}return await this.htmlRenderer.render(p.innerHTML,i)}finally{this.removeContainer(u)}}async renderSvelteTemplate(t,n,i,o){let{templateRef:s,source:a}=this.getTemplateSource(n,t.type,t.template);if(!a)return await this.renderAsErrorPng(`Missing md2x template: ${s||t.template}`,o);let c=X(a);if(t.allowTemplateAssets){if(c.error)return await this.renderAsErrorPng(`Invalid TemplateConfig JSON: ${c.error}`,o);try{await Z(c.templateConfig)}catch(A){return await this.renderAsErrorPng(`Failed to load TemplateConfig assets: ${A.message}`,o)}}let u;try{u=await this.ensureSvelteCompiler(i)}catch(A){return await this.renderAsErrorPng(`Svelte compiler unavailable: ${A.message}`,o)}let p=u?.compile||u?.default?.compile||u?.svelte?.compile;if(typeof p!="function")return await this.renderAsErrorPng("Svelte compiler not available (missing compile())",o);let f=O(c.source,t.data),h;try{try{h=p(f,{filename:s||t.template||"md2x.svelte",generate:"client"})}catch{h=p(f,{filename:s||t.template||"md2x.svelte",generate:"dom"})}}catch(A){return await this.renderAsErrorPng(`Failed to compile Svelte template: ${A.message}`,o)}let d=String(h?.js?.code||""),w=String(h?.css?.code||"");if(!d.trim())return await this.renderAsErrorPng("Svelte compile returned no JS output",o);let m=i?.svelteBase||"https://esm.sh/svelte@5/",T=Ee(d,m),E=this.createContainer();E.style.cssText="position: absolute; left: -9999px; top: -9999px; display: inline-block; background: transparent; padding: 0; margin: 0;";let y=document.createElement("div");y.style.cssText="display: inline-block;",E.appendChild(y);let b=null,S=null,R=null;try{try{R=URL.createObjectURL(new Blob([T],{type:"text/javascript"}))}catch(F){throw new Error("Unable to create Blob URL for compiled Svelte module: "+F.message)}let g=(await J(R))?.default;if(typeof g!="function")throw new Error("Compiled Svelte module has no default component export");let v=await J(se(m)),I=v?.mount;if(S=typeof v?.unmount=="function"?v.unmount:null,typeof I!="function")throw new Error("Svelte runtime mount() not available");b=I(g,{target:y});try{typeof globalThis.requestAnimationFrame=="function"&&await new Promise(F=>globalThis.requestAnimationFrame(()=>F()))}catch{}try{document.fonts?.ready&&await document.fonts.ready}catch{}let B=(w.trim()?`<style>${w}</style>`:"")+y.innerHTML;return await this.htmlRenderer.render(B,o)}catch(A){return await this.renderAsErrorPng(`Failed to render Svelte template: ${A.message}`,o)}finally{try{b&&S&&S(b)}catch{}try{R&&URL.revokeObjectURL(R)}catch{}this.removeContainer(E)}}async renderVueTemplate(t,n,i,o){let{templateRef:s,source:a}=this.getTemplateSource(n,t.type,t.template);if(!a)return await this.renderAsErrorPng(`Missing md2x template: ${s||t.template}`,o);let c=X(a);try{await this.ensureVueRuntime(i)}catch(y){return await this.renderAsErrorPng(`Vue runtime unavailable: ${y.message}`,o)}if(t.allowTemplateAssets){if(c.error)return await this.renderAsErrorPng(`Invalid TemplateConfig JSON: ${c.error}`,o);try{await Z(c.templateConfig)}catch(y){return await this.renderAsErrorPng(`Failed to load TemplateConfig assets: ${y.message}`,o)}}let u=globalThis.Vue,p=globalThis["vue3-sfc-loader"];if(!u||!p||typeof p.loadModule!="function")return await this.renderAsErrorPng("Vue runtime not available (missing Vue / vue3-sfc-loader)",o);let f=[],h=O(c.source,t.data),d=s||t.template,w={moduleCache:{vue:u},getFile:async y=>{if(y===d||y.endsWith("/"+d)||y.endsWith("\\"+d))return h;let b=n??{};if(typeof b[y]=="string")return b[y];try{let S=new URL(y,document.baseURI).href;if(typeof b[S]=="string")return b[S]}catch{}return null},addStyle:y=>{typeof y=="string"&&y.trim()&&f.push(y)}},m=this.createContainer();m.style.cssText="position: absolute; left: -9999px; top: -9999px; display: inline-block; background: transparent; padding: 0; margin: 0;";let T=document.createElement("div");T.style.cssText="display: inline-block;",m.appendChild(T);let E=null;try{let y=await p.loadModule(d,w);E=u.createApp({render:()=>u.h(y)}),E.mount(T);try{await u.nextTick()}catch{}try{document.fonts?.ready&&await document.fonts.ready}catch{}let S=(f.length?`<style>${f.join("\\n")}</style>`:"")+T.innerHTML;return await this.htmlRenderer.render(S,o)}finally{try{E&&typeof E.unmount=="function"&&E.unmount()}catch{}this.removeContainer(m)}}async render(t,n){let i=typeof t=="string"?t:t.code;this.validateInput(i);let o=be(i),s=typeof t=="string"?void 0:t.templateFiles,a=typeof t=="string"?void 0:t.cdn;return o.type==="html"?await this.renderHtmlTemplate(o,s,n):o.type==="vue"?await this.renderVueTemplate(o,s,a,n):o.type==="svelte"?await this.renderSvelteTemplate(o,s,a,n):await this.renderAsErrorPng(`Unsupported md2x type: ${o.type}`,n)}};var ae=class extends oe{async mountToDom(e,t,n){let i=typeof e=="string"?e:e.code;this.validateInput(i);let o=be(i),s=typeof e=="string"?void 0:e.templateFiles,a=typeof e=="string"?void 0:e.cdn,{templateRef:c,source:u}=this.getTemplateSource(s,o.type,o.template);if(!u){let d=document.createElement("div");return d.textContent=`Missing md2x template: ${c||o.template}`,{root:d,cleanup:()=>{}}}let p=X(u);if(o.allowTemplateAssets){if(p.error){let d=document.createElement("div");return d.textContent=`Invalid TemplateConfig JSON: ${p.error}`,{root:d,cleanup:()=>{}}}await Z(p.templateConfig)}let f=n??(()=>{let d=document.createElement("div");return d.style.cssText="position: absolute; left: 0; top: 0; display: inline-block; background: transparent; padding: 0; margin: 0;",document.body.appendChild(d),d})();try{f.innerHTML=""}catch{}if(o.type==="html"){let d=document.createElement("div");d.style.cssText="display: inline-block;",f.appendChild(d);let w=O(p.source,o.data);d.innerHTML=w;let m=()=>{try{d.remove()}catch{}n||this.removeContainer(f)};return o.allowScripts&&await this.runHtmlTemplateScripts(d,s),{root:f,cleanup:m}}if(o.type==="vue"){try{await this.ensureVueRuntime(a)}catch(g){let v=document.createElement("div");return v.textContent=`Vue runtime unavailable: ${g.message}`,{root:v,cleanup:()=>{}}}let d=globalThis.Vue,w=globalThis["vue3-sfc-loader"];if(!d||!w||typeof w.loadModule!="function"){let g=document.createElement("div");return g.textContent="Vue runtime not available (missing Vue / vue3-sfc-loader)",{root:g,cleanup:()=>{}}}let m=[],T=O(p.source,o.data),E=c||o.template,y={moduleCache:{vue:d},getFile:async g=>{if(g===E||g.endsWith("/"+E)||g.endsWith("\\"+E))return T;let v=s??{};if(typeof v[g]=="string")return v[g];try{let I=new URL(g,document.baseURI).href;if(typeof v[I]=="string")return v[I]}catch{}return null},addStyle:g=>{typeof g=="string"&&g.trim()&&m.push(g)}},b=document.createElement("div");b.style.cssText="display: inline-block;",f.appendChild(b);let S=null,R=null;try{let g=await w.loadModule(E,y);S=d.createApp({render:()=>d.h(g)}),S.mount(b);try{await d.nextTick()}catch{}try{document.fonts?.ready&&await document.fonts.ready}catch{}m.length&&(R=document.createElement("style"),R.textContent=m.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "md2x",
3
- "version": "0.7.5",
3
+ "version": "0.7.7",
4
4
  "description": "Markdown converter (local, no server). Supports Mermaid/Graphviz/Vega/HTML/SVG rendering, math, and code highlighting.",
5
5
  "type": "module",
6
6
  "private": false,
@@ -56,8 +56,10 @@
56
56
  "node": ">=18"
57
57
  },
58
58
  "dependencies": {
59
+ "@modelcontextprotocol/sdk": "^1.25.3",
59
60
  "js-yaml": "^4.1.1",
60
- "puppeteer": "24.35.0"
61
+ "puppeteer": "24.35.0",
62
+ "zod": "^4.3.6"
61
63
  },
62
64
  "devDependencies": {
63
65
  "@types/js-yaml": "^4.0.9"
@@ -1 +0,0 @@
1
- import{h as a,i as b}from"./chunk-US45GBOT.js";export{a as convertPluginResultToDOCX,b as default};