mdat 0.3.1 → 0.4.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/bin/cli.js CHANGED
@@ -1,37 +1,37 @@
1
1
  #!/usr/bin/env node
2
- import{defaultLoaders as Qt}from"cosmiconfig";function ye(t,e){let n=Qt[".json"],i=n(t,e);return Xe(i)}function Xe(t,e="",n={}){for(let[i,o]of Object.entries(t)){let a=e?`${e}.${i}`:i;typeof o=="object"&&o!==null&&!Array.isArray(o)?Xe(o,a,n):o===null?n[a]="null":n[a]=o.toString()}return n}import{findUp as Xt}from"find-up";import en from"node:fs";import x from"node:path";import{packageUp as tn}from"package-up";import{isFileSync as et}from"path-type";import{packageDirectory as nn}from"pkg-dir";import{log as tt}from"remark-mdat";import on from"untildify";function rn(t,e){let n=e===0?1:Math.floor(Math.log10(Math.abs(e))+1);return t.toString().padStart(n,"0")}function we(t,e,n,i){let o=[];for(let[a,r]of t.entries()){let s=n&&t.length>1?`-${rn(a+1,t.length+1)}`:"",d=W(r,e,n,i,s);o.push(d)}return o}function W(t,e,n,i,o=""){let a=nt(t),r=e?nt(e):void 0;if(!et(a))throw new Error(`Input file not found: "${a}"`);if(r){if(et(r))throw new Error(`Output path must be a directory, received a file path: "${r}"`);en.mkdirSync(r,{recursive:!0})}let s=n?x.basename(n,x.extname(n)):x.basename(a,x.extname(a)),d=`.${i??(n&&x.extname(n)!==""?x.extname(n):x.extname(t)===""?"":x.extname(t))}`,m=`${s}${o}${d}`,c=r??x.dirname(a);return{input:a,name:m,output:c}}function nt(t){return on(t)}async function G(){tt.info("Searching for package directory...");let t=await nn()??process.cwd(),e=await Xt("readme.md",{stopAt:t,type:"file"});if(e!==void 0)return tt.info(`Found closest readme at "${e}"`),e}async function Y(){return tn()}import ot from"chalk";import{cosmiconfig as it}from"cosmiconfig";import an from"node:fs/promises";import st from"node:path";import sn from"plur";import{readPackage as dn}from"read-pkg";import{deepMergeDefined as be,log as y,optionsSchema as mn,rulesSchema as cn}from"remark-mdat";import{z as K}from"zod";var rt=mn.merge(K.object({assetsPath:K.string().optional(),packageFile:K.string().optional(),readmeFile:K.string().optional()})).describe("Config Extension");async function k(t){let{additionalConfig:e,additionalRules:n,searchFrom:i}=t??{},o={addMetaComment:!1,assetsPath:"./assets",closingPrefix:"/",keywordPrefix:"",metaCommentIdentifier:"+",packageFile:await Y(),readmeFile:await G(),rules:{mdat:"Powered by the Markdown Autophagic Template system: [mdat](https://github.com/kitschpatrol/mdat)."}},a=it("mdat"),r=await a.search(i);if(r){let{config:s,filepath:d}=r;y.info(`Using config from "${d}"`);let m=at(s,rt);m&&(o=be(o,m))}if(e!==void 0){let s=Array.isArray(e)?e:[e];for(let d of s){let m;if(typeof d=="string"){let p=await a.load(d);if(p==null)continue;let{config:u,filepath:g}=p;y.info(`Loaded additional config from "${g}"`),m=u}else m=d;if(m===void 0)continue;y.info("Merging configuration object");let c=at(m,rt);c!==void 0&&(o=be(o,c))}}if(n!==void 0){let s=Array.isArray(n)?n:[n],d=it("mdat",{loaders:{".json":ye}});for(let m of s){let c;if(typeof m=="string"){let u;if(st.basename(m).endsWith("package.json")){let he=await an.readFile(m,"utf8");u={config:ye(m,he),filepath:m}}else u=await d.load(m);if(u==null)continue;let{config:g,filepath:C}=u;y.info(`Loaded additional config from "${C}"`),c=g}else c=m;if(c===void 0)continue;y.info("Merging rules into configuration object");let p=pn(c,cn);p!==void 0&&(o=be(o,p))}}if(o.rules){let s=Object.keys(o.rules).sort().map(d=>`"${ot.bold.green(d)}"`);y.info(`Loaded ${ot.bold(s.length)} mdat comment expansion ${sn("rule",s.length)}:`);for(let d of s)y.info(` ${d}`)}else y.error("No rules loaded from additional configurations or rules, using default.");return Z=o,o}function pn(t,e){if(e.safeParse(t).success)return{rules:t};y.error(`Rules object has the wrong shape. Ignoring and using default configuration:
3
- ${JSON.stringify(t,void 0,2)}`)}function at(t,e){if(e.safeParse(t).success)return t;y.error(`Config object has the wrong shape. Ignoring and using default configuration:
4
- ${JSON.stringify(t,void 0,2)}`)}var Z;async function w(){return Z===void 0&&(y.warn("getConfig(): config was undefined"),Z??=await k()),Z}var Ce;async function h(){let{packageFile:t}=await w();if(t===void 0)throw new Error("No packageFile found or set in config");if(Ce??=await dn({cwd:st.dirname(t)}),Ce===void 0)throw new Error("No package.json found");return Ce}import{remark as dt}from"remark";import mt from"remark-gfm";import{mdatClean as ln,mdatSplit as un,default as fn}from"remark-mdat";import{read as Q}from"to-vfile";import{VFile as Mo}from"vfile";async function X(t,e,n,i,o){let a=await k({additionalConfig:i,additionalRules:o});i=a;let r=we(t,n,e,"md"),s=[],d=ct(a);for(let{input:m,name:c,output:p}of r){let u=await Q(m),g=await d.process(u);g.dirname=p,g.basename=c,s.push(g)}return s}async function xe(t,e,n,i,o){let a=await k({additionalConfig:i,additionalRules:o});i=a;let r=W(t,n,e,"md"),s=await Q(r.input),d=await ct(a).process(s);return d.dirname=r.output,d.basename=r.name,d}async function ke(t,e,n,i){let o=await k({additionalConfig:i});i=o;let a=we(t,n,e,"md"),r=[],s=pt(o);for(let{input:d,name:m,output:c}of a){let p=await Q(d),u=await s.process(p);u.dirname=c,u.basename=m,r.push(u)}return r}async function Re(t,e,n,i){let o=await k({additionalConfig:i});i=o;let a=W(t,n,e,"md"),r=await Q(a.input),s=await pt(o).process(r);return s.dirname=a.output,s.basename=a.name,s}function ct(t){return dt().use({settings:{bullet:"-",emphasis:"_"}}).use(mt).use(fn,t??{})}function pt(t){let{closingPrefix:e,keywordPrefix:n,metaCommentIdentifier:i}=t;return dt().use({settings:{bullet:"-",emphasis:"_"}}).use(mt).use(()=>function(a,r){un(a,r),ln(a,r,{closingPrefix:e,keywordPrefix:n,metaCommentIdentifier:i})})}import{z as V}from"zod";var ee={badges:{async content(t){var r;let e=V.object({custom:V.record(V.object({image:V.string(),link:V.string()})).optional()}).optional().parse(t),n=await h(),{name:i}=n,o=[];!n.private&&((r=n.publishConfig)==null?void 0:r.access)==="public"&&o.push(`[![NPM Package](https://img.shields.io/npm/v/${i}.svg)](https://npmjs.com/package/${i})`);let{license:a}=n;if(a!==void 0&&o.push(`[![License: ${a}](https://img.shields.io/badge/License-${a}-yellow.svg)](https://opensource.org/licenses/${a})`),(e==null?void 0:e.custom)!==void 0)for(let[s,{image:d,link:m}]of Object.entries(e.custom))o.push(`[![${s}](${d})](${m})`);return o.join(`
5
- `)},order:3,required:!1}};import{globby as gn}from"globby";import te from"node:path";import{isFile as hn}from"path-type";import{readPackage as yn}from"read-pkg";import{z as Pe}from"zod";async function wn(t){let{packageFile:e}=await w();if(e===void 0)throw new Error("No package.json found");let n=te.dirname(e),i=t===void 0?[".","assets","media","readme-assets","readme-media","readme","images"]:[t],o=["banner","header","logo","readme","cover","screenshot","screenshots","demo","overview","image","hero"],a=["png","gif","jpg","jpeg","svg","webp"],r=await gn(i.map(s=>te.join(n,s)),{expandDirectories:{extensions:a,files:o}});if(r.length>0)return te.relative(process.cwd(),r[0])}var ne={banner:{async content(t){let e=Pe.object({alt:Pe.string().optional(),src:Pe.string().optional()}).optional().parse(t),{assetsPath:n,packageFile:i}=await w();if(i===void 0)throw new Error("No package.json found");let o=(e==null?void 0:e.src)??await wn(n);if(o===void 0||!await hn(o))throw new Error(`Banner image not found at ${o===void 0?"any typical location, consider adding something at ./assets/banner.webp":`"${o}"`}`);let a=(e==null?void 0:e.alt)??`${(await yn({cwd:te.dirname(i)})).name} banner`;if(a===void 0||a==="undefined banner")throw new Error("Banner image alt text not available");return`![${a}](${o})`},order:2}};import{CstParser as bn,Lexer as S,createToken as f}from"chevrotain";var ve=f({name:"flag",pattern:/--[\w-_]+/}),$e=f({name:"alias",pattern:/-[A-Za-z]/}),lt=f({group:S.SKIPPED,name:"comma",pattern:/,/}),F=f({name:"word",pattern:/\S+/}),J=f({name:"argument",pattern:/<\S+>|\[\S+]/}),Ee=f({name:"type",pattern:/\[(boolean|string|array)]/}),Le=f({name:"defaultInfo",pattern:/\[default]/}),Te=f({name:"required",pattern:/\[required]/}),Ne=f({name:"defaultInfoDescription",pattern:/\[default:\s.+?]/}),Fe=f({name:"choices",pattern:/\[choices:\s.+?]/}),Oe=f({group:S.SKIPPED,name:"whiteSpace",pattern:/\s/}),ut=f({group:S.SKIPPED,name:"startProgramDescription",pattern:/\n\n/,push_mode:"PROGRAM_DESCRIPTION_MODE"}),_e=f({name:"programDescription",pattern:/.+/}),ft=f({group:S.SKIPPED,name:"endProgramDescription",pattern:/\n\n/,pop_mode:!0}),je=f({name:"startOptionsSection",pattern:/Options:\n/,push_mode:"SECTION_MODE"}),Ae=f({name:"startPositionalsSection",pattern:/Positionals:\n/,push_mode:"SECTION_MODE"}),De=f({name:"startCommandsSection",pattern:/Commands:\n/,push_mode:"SECTION_MODE"}),Ie=f({name:"startRow",pattern:/ {2,}/,push_mode:"ROW_MODE"}),Me=f({name:"rowDescription",pattern:/ {2}\w.+ {2}/}),Ue=f({name:"rowDescriptionTerminal",pattern:/ {2}\w.+/}),gt=f({group:S.SKIPPED,name:"endRow",pattern:/\n/,pop_mode:!0}),ht=f({group:S.SKIPPED,name:"endSection",pattern:/\n+/,pop_mode:!0}),Cn=new S({defaultMode:"DEFAULT_MODE",modes:{DEFAULT_MODE:[je,Ae,De,ut,J,F,Oe],PROGRAM_DESCRIPTION_MODE:[ft,_e],ROW_MODE:[gt,lt,Ee,Me,Ue,Ne,Le,Te,Fe,ve,$e,J,F,Oe],SECTION_MODE:[Ie,ht]}}),xn=[ve,$e,lt,F,J,Ee,Le,Te,Ne,Fe,Oe,ut,_e,ft,je,Ae,De,Ie,Me,Ue,gt,ht];function kn(t){return Cn.tokenize(t.trim())}var Se=class extends bn{programHelp=this.RULE("programHelp",()=>{this.AT_LEAST_ONE(()=>{this.CONSUME(F,{LABEL:"commandName"})}),this.MANY1(()=>{this.CONSUME(J)}),this.OPTION(()=>{this.CONSUME(_e,{LABEL:"description"})}),this.OPTION1(()=>{this.SUBRULE(this.commandsSection)}),this.OPTION2(()=>{this.SUBRULE(this.positionalsSection)}),this.OPTION3(()=>{this.SUBRULE(this.optionsSection)})});positionalsSection=this.RULE("positionalsSection",()=>{this.CONSUME(Ae),this.MANY(()=>{this.SUBRULE(this.sectionRow)})});commandsSection=this.RULE("commandsSection",()=>{this.CONSUME(De),this.MANY1(()=>{this.SUBRULE1(this.sectionRow)})});optionsSection=this.RULE("optionsSection",()=>{this.CONSUME(je),this.MANY2(()=>{this.SUBRULE2(this.sectionRow)})});sectionRow=this.RULE("sectionRow",()=>{this.CONSUME(Ie),this.OPTION(()=>{this.CONSUME(F,{LABEL:"parentCommandName"})}),this.MANY(()=>{this.CONSUME1(F,{LABEL:"commandName"})}),this.MANY1(()=>{this.OR([{ALT:()=>this.CONSUME(J)},{ALT:()=>this.CONSUME($e)},{ALT:()=>this.CONSUME(ve)},{ALT:()=>this.CONSUME(Me,{LABEL:"description"})},{ALT:()=>this.CONSUME(Ue,{LABEL:"description"})},{ALT:()=>this.CONSUME(Ee)},{ALT:()=>this.CONSUME(Te)},{ALT:()=>this.CONSUME(Ne)},{ALT:()=>this.CONSUME(Le)},{ALT:()=>this.CONSUME(Fe)}])})});constructor(){super(xn),this.performSelfAnalysis()}},N=new Se;function yt(t){let e=kn(t);N.input=e.tokens;let n=N.programHelp();if(N.errors.length>0)throw new Error(`Errors parsing CLI command help text output: ${JSON.stringify(N.errors,void 0,2)}`);return n}var Ve=class extends N.getBaseCstVisitorConstructor(){constructor(){super(),this.validateVisitor()}programHelp(e){let{command:n,subcommand:i}=Pn(this.getString(e.commandName));return{arguments:this.getArray(e.argument),commandName:n,commands:e.commandsSection?this.visit(e.commandsSection):void 0,description:this.getString(e.description),options:e.optionsSection?this.visit(e.optionsSection):void 0,positionals:e.positionalsSection?this.visit(e.positionalsSection):void 0,subcommandName:i}}positionalsSection(e){return e.sectionRow.map(n=>this.positionalParentCommandToArguments(this.visit(n)))}commandsSection(e){return e.sectionRow.map(n=>this.visit(n))}optionsSection(e){return e.sectionRow.map(n=>this.visit(n))}sectionRow(e){return{aliases:this.getArray(e.alias),arguments:this.getArray(e.argument),choices:this.splitChoices(this.getString(e.choices)),commandName:this.getString(e.commandName),default:e.defaultInfo?!0:void 0,defaultValue:this.getString(e.defaultInfoDescription,!0),description:this.getString(e.description,!0),flags:this.getArray(e.flag),parentCommandName:this.getString(e.parentCommandName),required:e.required?!0:void 0,type:this.getString(e.type,!0)}}positionalParentCommandToArguments(e){let{arguments:n,parentCommandName:i,...o}=e;return i===void 0?e:{arguments:[i,...n??[]],...o}}getString(e,n=!1){if(e!==void 0)return e.map(i=>n?this.clean(i.image):i.image).join(" ")}getArray(e){if(e!==void 0)return e.map(n=>n.image)}clean(e){return e.replaceAll(/^[\s[]*(default:)?\s*|[\s\]]*$/g,"")}splitChoices(e){if(e!==void 0)return this.clean(e.replaceAll(/^\[choices:\s/g,"")).split(", ")}},Rn=new Ve;function wt(t){return Rn.visit(t)}function Pn(t){if(t===void 0)throw new Error('Could not find "commandName" entry in help');let e=t.split(" ");if(e.length===0&&t===void 0)throw new Error('Could not find "commandName" entry in help');if(e.length===1)return{command:e[0],subcommand:void 0};let n=e.at(-1);return{command:e.slice(0,-1).join(" "),subcommand:n}}function bt(t,e=!1){var i,o,a;let n=[];if(e){let r=(i=t.commands)==null?void 0:i.find(m=>m.default),s=(o=t.commands)==null?void 0:o.find(m=>m.commandName===void 0),d=`${t.commandName}${t.subcommandName?` ${t.subcommandName}`:""}`;n.push(`#### Command: \`${d}\``),s!=null&&s.description&&n.push(s==null?void 0:s.description),n.push(`This section lists top-level commands for \`${d}\`.`),r&&n.push(`If no command is provided, \`${r.parentCommandName} ${r.commandName}\` is run by default.`),n.push("Usage:"),s&&n.push(`\`\`\`txt
6
- ${s.parentCommandName}${s.arguments?` ${s.arguments.join(" ")}`:""}
7
- \`\`\``),t.commands=(a=t.commands)==null?void 0:a.filter(m=>m!==s)}else n.push(`#### Subcommand: \`${t.commandName} ${t.subcommandName}\``),n.push(t.description),n.push("Usage:"),n.push(`\`\`\`txt
2
+ import{defaultLoaders as no}from"cosmiconfig";function ye(t,e){let o=no[".json"],i=o(t,e);return Xe(i)}function Xe(t,e="",o={}){for(let[i,n]of Object.entries(t)){let s=e?`${e}.${i}`:i;typeof n=="object"&&n!==null&&!Array.isArray(n)?Xe(n,s,o):n===null?o[s]="null":o[s]=n.toString()}return o}import io from"node:fs";import x from"node:path";import{packageUp as ro}from"package-up";import{isFileSync as et}from"path-type";import so from"untildify";function ao(t,e){let o=e===0?1:Math.floor(Math.log10(Math.abs(e))+1);return t.toString().padStart(o,"0")}function ot(t,e,o,i){let n=[];for(let[s,r]of t.entries()){let a=o&&t.length>1?`-${ao(s+1,t.length+1)}`:"",c=co(r,e,o,i,a);n.push(c)}return n}function co(t,e,o,i,n=""){let s=tt(t),r=e?tt(e):void 0;if(!et(s))throw new Error(`Input file not found: "${s}"`);if(r){if(et(r))throw new Error(`Output path must be a directory, received a file path: "${r}"`);io.mkdirSync(r,{recursive:!0})}let a=o?x.basename(o,x.extname(o)):x.basename(s,x.extname(s)),c=`.${i??(o&&x.extname(o)!==""?x.extname(o):x.extname(t)===""?"":x.extname(t))}`,d=`${a}${n}${c}`,m=r??x.dirname(s);return{input:s,name:d,output:m}}function tt(t){return so(t)}async function W(){return ro()}function Y(t){return t==null?[]:Array.isArray(t)?t:[t]}import nt from"chalk";import{cosmiconfig as it}from"cosmiconfig";import mo from"node:fs/promises";import at from"node:path";import po from"plur";import{readPackage as lo}from"read-pkg";import{deepMergeDefined as we,log as w,optionsSchema as uo,rulesSchema as fo}from"remark-mdat";import{z as be}from"zod";var rt=uo.merge(be.object({assetsPath:be.string().optional(),packageFile:be.string().optional()})).describe("Config Extension");async function S(t){let{additionalConfig:e,additionalRules:o,searchFrom:i}=t??{},n={addMetaComment:!1,assetsPath:"./assets",closingPrefix:"/",keywordPrefix:"",metaCommentIdentifier:"+",packageFile:await W(),rules:{mdat:"Powered by the Markdown Autophagic Template system: [mdat](https://github.com/kitschpatrol/mdat)."}},s=it("mdat"),r=await s.search(i);if(r){let{config:a,filepath:c}=r;w.info(`Using config from "${c}"`);let d=st(a,rt);d&&(n=we(n,d))}if(e!==void 0){let a=Array.isArray(e)?e:[e];for(let c of a){let d;if(typeof c=="string"){let l=await s.load(c);if(l==null)continue;let{config:f,filepath:h}=l;w.info(`Loaded additional config from "${h}"`),d=f}else d=c;if(d===void 0)continue;w.info("Merging configuration object");let m=st(d,rt);m!==void 0&&(n=we(n,m))}}if(o!==void 0){let a=Array.isArray(o)?o:[o],c=it("mdat",{loaders:{".json":ye}});for(let d of a){let m;if(typeof d=="string"){let f;if(at.basename(d).endsWith("package.json")){let _=await mo.readFile(d,"utf8");f={config:ye(d,_),filepath:d}}else f=await c.load(d);if(f==null)continue;let{config:h,filepath:y}=f;w.info(`Loaded additional config from "${y}"`),m=h}else m=d;if(m===void 0)continue;w.info("Merging rules into configuration object");let l=go(m,fo);l!==void 0&&(n=we(n,l))}}if(n.rules){let a=Object.keys(n.rules).sort().map(c=>`"${nt.bold.green(c)}"`);w.info(`Loaded ${nt.bold(a.length)} mdat comment expansion ${po("rule",a.length)}:`);for(let c of a)w.info(` ${c}`)}else w.error("No rules loaded from additional configurations or rules, using default.");return K=n,n}function go(t,e){if(e.safeParse(t).success)return{rules:t};w.error(`Rules object has the wrong shape. Ignoring and using default configuration:
3
+ ${JSON.stringify(t,void 0,2)}`)}function st(t,e){if(e.safeParse(t).success)return t;w.error(`Config object has the wrong shape. Ignoring and using default configuration:
4
+ ${JSON.stringify(t,void 0,2)}`)}var K;async function C(){return K===void 0&&(w.warn("getConfig(): config was undefined"),K??=await S()),K}var Ce;async function g(){let{packageFile:t}=await C();if(t===void 0)throw new Error("No packageFile found or set in config");if(Ce??=await lo({cwd:at.dirname(t)}),Ce===void 0)throw new Error("No package.json found");return Ce}import{remark as xe}from"remark";import ke from"remark-gfm";import{mdatCheck as ho,mdatClean as dt,mdatExpand as yo,mdatSplit as ct}from"remark-mdat";import{read as wo}from"to-vfile";import{VFile as Un}from"vfile";async function k(t,e,o,i,n,s,r){let a=await e({additionalConfig:s,additionalRules:r});s=a;let c=Y(t),d=ot(c,n,i,"md"),m=[],l=o(a);for(let{input:f,name:h,output:y}of d){let _=await wo(f),G=await l.process(_);G.dirname=y,G.basename=h,m.push(G)}return m}function Z(t){return xe().use({settings:{bullet:"-",emphasis:"_"}}).use(ke).use(()=>async function(o,i){ct(o,i),dt(o,i,t),await yo(o,i,t)})}function Q(t){return xe().use({settings:{bullet:"-",emphasis:"_"}}).use(ke).use(()=>function(o,i){ct(o,i),dt(o,i,t)})}function X(t){return xe().use({settings:{bullet:"-",emphasis:"_"}}).use(ke).use(()=>async function(o,i){await ho(o,i,{...t,paranoid:!1})})}async function mt(t,e,o,i,n){return k(t,S,Z,e,o,i,n)}async function pt(t,e,o,i,n){return k(t,S,X,e,o,i,n)}async function lt(t,e,o,i,n){return k(t,S,Q,e,o,i,n)}import{z as V}from"zod";var ee={badges:{async content(t){var r;let e=V.object({custom:V.record(V.object({image:V.string(),link:V.string()})).optional()}).optional().parse(t),o=await g(),{name:i}=o,n=[];!o.private&&((r=o.publishConfig)==null?void 0:r.access)==="public"&&n.push(`[![NPM Package](https://img.shields.io/npm/v/${i}.svg)](https://npmjs.com/package/${i})`);let{license:s}=o;if(s!==void 0&&n.push(`[![License: ${s}](https://img.shields.io/badge/License-${s}-yellow.svg)](https://opensource.org/licenses/${s})`),(e==null?void 0:e.custom)!==void 0)for(let[a,{image:c,link:d}]of Object.entries(e.custom))n.push(`[![${a}](${c})](${d})`);return n.join(`
5
+ `)},order:3,required:!1}};import{globby as Co}from"globby";import te from"node:path";import{isFile as xo}from"path-type";import{readPackage as ko}from"read-pkg";import{z as Pe}from"zod";async function Po(t){let{packageFile:e}=await C();if(e===void 0)throw new Error("No package.json found");let o=te.dirname(e),i=t===void 0?[".","assets","media","readme-assets","readme-media","readme","images"]:[t],n=["banner","header","logo","readme","cover","screenshot","screenshots","demo","overview","image","hero"],s=["png","gif","jpg","jpeg","svg","webp"],r=await Co(i.map(a=>te.join(o,a)),{expandDirectories:{extensions:s,files:n}});if(r.length>0)return te.relative(process.cwd(),r[0])}var oe={banner:{async content(t){let e=Pe.object({alt:Pe.string().optional(),src:Pe.string().optional()}).optional().parse(t),{assetsPath:o,packageFile:i}=await C();if(i===void 0)throw new Error("No package.json found");let n=(e==null?void 0:e.src)??await Po(o);if(n===void 0||!await xo(n))throw new Error(`Banner image not found at ${n===void 0?"any typical location, consider adding something at ./assets/banner.webp":`"${n}"`}`);let s=(e==null?void 0:e.alt)??`${(await ko({cwd:te.dirname(i)})).name} banner`;if(s===void 0||s==="undefined banner")throw new Error("Banner image alt text not available");return`![${s}](${n})`},order:2}};import{CstParser as Ro,Lexer as v,createToken as p}from"chevrotain";var Se=p({name:"flag",pattern:/--[\w-_]+/}),ve=p({name:"alias",pattern:/-[A-Za-z]/}),ut=p({group:v.SKIPPED,name:"comma",pattern:/,/}),j=p({name:"word",pattern:/\S+/}),J=p({name:"argument",pattern:/<\S+>|\[\S+]/}),Le=p({name:"type",pattern:/\[(boolean|string|array)]/}),Ee=p({name:"defaultInfo",pattern:/\[default]/}),$e=p({name:"required",pattern:/\[required]/}),Te=p({name:"defaultInfoDescription",pattern:/\[default:\s.+?]/}),Ne=p({name:"choices",pattern:/\[choices:\s.+?]/}),Re=p({group:v.SKIPPED,name:"whiteSpace",pattern:/\s/}),ft=p({group:v.SKIPPED,name:"startProgramDescription",pattern:/\n\n/,push_mode:"PROGRAM_DESCRIPTION_MODE"}),_e=p({name:"programDescription",pattern:/.+/}),gt=p({group:v.SKIPPED,name:"endProgramDescription",pattern:/\n\n/,pop_mode:!0}),Ae=p({name:"startOptionsSection",pattern:/Options:\n/,push_mode:"SECTION_MODE"}),je=p({name:"startPositionalsSection",pattern:/Positionals:\n/,push_mode:"SECTION_MODE"}),Fe=p({name:"startCommandsSection",pattern:/Commands:\n/,push_mode:"SECTION_MODE"}),De=p({name:"startRow",pattern:/ {2,}/,push_mode:"ROW_MODE"}),Ie=p({name:"rowDescription",pattern:/ {2}\w.+ {2}/}),Me=p({name:"rowDescriptionTerminal",pattern:/ {2}\w.+/}),ht=p({group:v.SKIPPED,name:"endRow",pattern:/\n/,pop_mode:!0}),yt=p({group:v.SKIPPED,name:"endSection",pattern:/\n+/,pop_mode:!0}),Oo=new v({defaultMode:"DEFAULT_MODE",modes:{DEFAULT_MODE:[Ae,je,Fe,ft,J,j,Re],PROGRAM_DESCRIPTION_MODE:[gt,_e],ROW_MODE:[ht,ut,Le,Ie,Me,Te,Ee,$e,Ne,Se,ve,J,j,Re],SECTION_MODE:[De,yt]}}),So=[Se,ve,ut,j,J,Le,Ee,$e,Te,Ne,Re,ft,_e,gt,Ae,je,Fe,De,Ie,Me,ht,yt];function vo(t){return Oo.tokenize(t.trim())}var Oe=class extends Ro{programHelp=this.RULE("programHelp",()=>{this.AT_LEAST_ONE(()=>{this.CONSUME(j,{LABEL:"commandName"})}),this.MANY1(()=>{this.CONSUME(J)}),this.OPTION(()=>{this.CONSUME(_e,{LABEL:"description"})}),this.OPTION1(()=>{this.SUBRULE(this.commandsSection)}),this.OPTION2(()=>{this.SUBRULE(this.positionalsSection)}),this.OPTION3(()=>{this.SUBRULE(this.optionsSection)})});positionalsSection=this.RULE("positionalsSection",()=>{this.CONSUME(je),this.MANY(()=>{this.SUBRULE(this.sectionRow)})});commandsSection=this.RULE("commandsSection",()=>{this.CONSUME(Fe),this.MANY1(()=>{this.SUBRULE1(this.sectionRow)})});optionsSection=this.RULE("optionsSection",()=>{this.CONSUME(Ae),this.MANY2(()=>{this.SUBRULE2(this.sectionRow)})});sectionRow=this.RULE("sectionRow",()=>{this.CONSUME(De),this.OPTION(()=>{this.CONSUME(j,{LABEL:"parentCommandName"})}),this.MANY(()=>{this.CONSUME1(j,{LABEL:"commandName"})}),this.MANY1(()=>{this.OR([{ALT:()=>this.CONSUME(J)},{ALT:()=>this.CONSUME(ve)},{ALT:()=>this.CONSUME(Se)},{ALT:()=>this.CONSUME(Ie,{LABEL:"description"})},{ALT:()=>this.CONSUME(Me,{LABEL:"description"})},{ALT:()=>this.CONSUME(Le)},{ALT:()=>this.CONSUME($e)},{ALT:()=>this.CONSUME(Te)},{ALT:()=>this.CONSUME(Ee)},{ALT:()=>this.CONSUME(Ne)}])})});constructor(){super(So),this.performSelfAnalysis()}},A=new Oe;function wt(t){let e=vo(t);A.input=e.tokens;let o=A.programHelp();if(A.errors.length>0)throw new Error(`Errors parsing CLI command help text output: ${JSON.stringify(A.errors,void 0,2)}`);return o}var Ue=class extends A.getBaseCstVisitorConstructor(){constructor(){super(),this.validateVisitor()}programHelp(e){let{command:o,subcommand:i}=Eo(this.getString(e.commandName));return{arguments:this.getArray(e.argument),commandName:o,commands:e.commandsSection?this.visit(e.commandsSection):void 0,description:this.getString(e.description),options:e.optionsSection?this.visit(e.optionsSection):void 0,positionals:e.positionalsSection?this.visit(e.positionalsSection):void 0,subcommandName:i}}positionalsSection(e){return e.sectionRow.map(o=>this.positionalParentCommandToArguments(this.visit(o)))}commandsSection(e){return e.sectionRow.map(o=>this.visit(o))}optionsSection(e){return e.sectionRow.map(o=>this.visit(o))}sectionRow(e){return{aliases:this.getArray(e.alias),arguments:this.getArray(e.argument),choices:this.splitChoices(this.getString(e.choices)),commandName:this.getString(e.commandName),default:e.defaultInfo?!0:void 0,defaultValue:this.getString(e.defaultInfoDescription,!0),description:this.getString(e.description,!0),flags:this.getArray(e.flag),parentCommandName:this.getString(e.parentCommandName),required:e.required?!0:void 0,type:this.getString(e.type,!0)}}positionalParentCommandToArguments(e){let{arguments:o,parentCommandName:i,...n}=e;return i===void 0?e:{arguments:[i,...o??[]],...n}}getString(e,o=!1){if(e!==void 0)return e.map(i=>o?this.clean(i.image):i.image).join(" ")}getArray(e){if(e!==void 0)return e.map(o=>o.image)}clean(e){return e.replaceAll(/^[\s[]*(default:)?\s*|[\s\]]*$/g,"")}splitChoices(e){if(e!==void 0)return this.clean(e.replaceAll(/^\[choices:\s/g,"")).split(", ")}},Lo=new Ue;function bt(t){return Lo.visit(t)}function Eo(t){if(t===void 0)throw new Error('Could not find "commandName" entry in help');let e=t.split(" ");if(e.length===0&&t===void 0)throw new Error('Could not find "commandName" entry in help');if(e.length===1)return{command:e[0],subcommand:void 0};let o=e.at(-1);return{command:e.slice(0,-1).join(" "),subcommand:o}}function Ct(t,e=!1){var i,n,s;let o=[];if(e){let r=(i=t.commands)==null?void 0:i.find(d=>d.default),a=(n=t.commands)==null?void 0:n.find(d=>d.commandName===void 0),c=`${t.commandName}${t.subcommandName?` ${t.subcommandName}`:""}`;o.push(`#### Command: \`${c}\``),a!=null&&a.description&&o.push(a==null?void 0:a.description),o.push(`This section lists top-level commands for \`${c}\`.`),r&&o.push(`If no command is provided, \`${r.parentCommandName} ${r.commandName}\` is run by default.`),o.push("Usage:"),a&&o.push(`\`\`\`txt
6
+ ${a.parentCommandName}${a.arguments?` ${a.arguments.join(" ")}`:""}
7
+ \`\`\``),t.commands=(s=t.commands)==null?void 0:s.filter(d=>d!==a)}else o.push(`#### Subcommand: \`${t.commandName} ${t.subcommandName}\``),o.push(t.description),o.push("Usage:"),o.push(`\`\`\`txt
8
8
  ${t.commandName} ${t.subcommandName}${t.arguments?` ${t.arguments.join(" ")}`:""}
9
- \`\`\``);return t.positionals&&!e&&n.push(Je(["Positional Argument","Description","Type","Default"],t.positionals.map(r=>[r.arguments?[r.arguments.map(s=>`\`${s}\``)].join(" "):"",`${r.description??""}${r.required?" _(Required.)_":" _(Optional.)_"}`,r.type?`\`${r.type}\``:"",r.defaultValue?r.defaultValue.includes(" ")?r.defaultValue:`\`${r.defaultValue}\``:""]))),t.commands&&n.push(Je(["Command","Argument","Description"],t.commands.map(r=>{var s;return[`\`${r.commandName??(r.default?"[default]":"")}\``,r.arguments?(s=r.arguments)==null?void 0:s.map(d=>`\`${d}\``).join(" "):"",`${r.description??""}${r.default?" _(Default command.)_":""}`]}))),t.options&&!e&&n.push(Je(["Option","Alias","Argument","Description","Type","Default"],t.options.map(r=>[r.flags?r.flags.map(s=>`\`${s}\``).join(" "):"",r.aliases?r.aliases.map(s=>`\`${s}\``).join(" "):"",r.arguments?r.arguments.map(s=>`\`${s}\``).join(" "):"",r.description??"",r.type?`\`${r.type}\``:"",r.defaultValue?r.defaultValue.includes(" ")?r.defaultValue:`\`${r.defaultValue}\``:""]))),e&&n.push("_See the sections below for more information on each subcommand._"),n.join(`
9
+ \`\`\``);return t.positionals&&!e&&o.push(Ve(["Positional Argument","Description","Type","Default"],t.positionals.map(r=>[r.arguments?[r.arguments.map(a=>`\`${a}\``)].join(" "):"",`${r.description??""}${r.required?" _(Required.)_":" _(Optional.)_"}`,r.type?`\`${r.type}\``:"",r.defaultValue?r.defaultValue.includes(" ")?r.defaultValue:`\`${r.defaultValue}\``:""]))),t.commands&&o.push(Ve(["Command","Argument","Description"],t.commands.map(r=>{var a;return[`\`${r.commandName??(r.default?"[default]":"")}\``,r.arguments?(a=r.arguments)==null?void 0:a.map(c=>`\`${c}\``).join(" "):"",`${r.description??""}${r.default?" _(Default command.)_":""}`]}))),t.options&&!e&&o.push(Ve(["Option","Alias","Argument","Description","Type","Default"],t.options.map(r=>[r.flags?r.flags.map(a=>`\`${a}\``).join(" "):"",r.aliases?r.aliases.map(a=>`\`${a}\``).join(" "):"",r.arguments?r.arguments.map(a=>`\`${a}\``).join(" "):"",r.description??"",r.type?`\`${r.type}\``:"",r.defaultValue?r.defaultValue.includes(" ")?r.defaultValue:`\`${r.defaultValue}\``:""]))),e&&o.push("_See the sections below for more information on each subcommand._"),o.join(`
10
10
 
11
- `)}function Je(t,e){let n=On(e);t=t.filter((o,a)=>!n.includes(a)),e=e.map(o=>o.filter((a,r)=>!n.includes(r)));let i="";i+=`| ${t.join(" | ")} |
11
+ `)}function Ve(t,e){let o=$o(e);t=t.filter((n,s)=>!o.includes(s)),e=e.map(n=>n.filter((s,r)=>!o.includes(r)));let i="";i+=`| ${t.join(" | ")} |
12
12
  `,i+=`| ${t.map(()=>"---").join(" | ")} |
13
- `;for(let o of e)i+=`| ${o.join(" | ")} |
14
- `;return i}function On(t){var i;let e=[],n=((i=t[0])==null?void 0:i.length)||0;for(let o=0;o<n;o++){let a=!0;for(let r of t)if(r[o]!==""){a=!1;break}a&&e.push(o)}return e}import{execaCommand as Sn}from"execa";import{log as Ct}from"remark-mdat";async function Be(t){let e=`${t} --help`,n;try{let{stderr:o,stdout:a}=await Sn(e);n=a,(n===void 0||n==="")&&(n=o)}catch(o){if(o instanceof Error)throw new TypeError(`Error running CLI help command: ${e}
15
- ${o.message}
16
- `)}if(n===void 0||n==="")throw new Error(`No result from running CLI help command: ${e}
17
- `);let i;try{let o=yt(n);i=wt(o)}catch(o){o instanceof Error&&(i=void 0,Ct.warn(`Error parsing help output for command: ${t}
18
- ${o.message}`),Ct.warn("Falling back to basic cli help text output."))}return i===void 0?$n(n):vn(t,i)}async function vn(t,e){let n=(e.commands&&e.commands.some(a=>a.default))??!1,i=bt(e,n),o=t.split(" ")[0];if(e.commands)for(let a of e.commands){if(!a.parentCommandName||!a.commandName)continue;let r=await Be(`${o} ${a.commandName}`);i+=`
19
-
20
- ${r}`}return i}function $n(t){return`\`\`\`txt
13
+ `;for(let n of e)i+=`| ${n.join(" | ")} |
14
+ `;return i}function $o(t){var i;let e=[],o=((i=t[0])==null?void 0:i.length)||0;for(let n=0;n<o;n++){let s=!0;for(let r of t)if(r[n]!==""){s=!1;break}s&&e.push(n)}return e}import{execaCommand as To}from"execa";import{log as xt}from"remark-mdat";async function Je(t){let e=`${t} --help`,o;try{let{stderr:n,stdout:s}=await To(e);o=s,(o===void 0||o==="")&&(o=n)}catch(n){if(n instanceof Error)throw new TypeError(`Error running CLI help command: ${e}
15
+ ${n.message}
16
+ `)}if(o===void 0||o==="")throw new Error(`No result from running CLI help command: ${e}
17
+ `);let i;try{let n=wt(o);i=bt(n)}catch(n){n instanceof Error&&(i=void 0,xt.warn(`Error parsing help output for command: ${t}
18
+ ${n.message}`),xt.warn("Falling back to basic cli help text output."))}return i===void 0?_o(o):No(t,i)}async function No(t,e){let o=(e.commands&&e.commands.some(s=>s.default))??!1,i=Ct(e,o),n=t.split(" ")[0];if(e.commands)for(let s of e.commands){if(!s.parentCommandName||!s.commandName)continue;let r=await Je(`${n} ${s.commandName}`);i+=`
19
+
20
+ ${r}`}return i}function _o(t){return`\`\`\`txt
21
21
  ${t}
22
- \`\`\``}import{isExecutable as En}from"is-executable";import Ln from"node:path";import{log as Tn}from"remark-mdat";import Nn from"which";async function xt(t){return t??=await Fn(),jn(t)}async function Fn(){let t=await h();if(t!=null&&t.bin){let e=typeof t.bin=="string"?t.bin:String(Object.values(t.bin).at(0));if(_n(e))return Tn.info(`Inferred <!-- cli-help --> command to run from package.json: ${e}`),e}throw new Error(`Could not infer which command to run for the <!-- cli-help --> rule. Please pass a "cliCommand" option to the expansion comment, e.g. <!-- cli-help {cliCommend: './dist/bin.js'} -->`)}function _n(t){let e=Ln.parse(t);return e.root!==""||e.dir!==""}async function jn(t){let e=await Nn(t,{nothrow:!0});if(e===null&&(e=await An(t)??void 0),e!==void 0&&await En(e))return e;throw new Error(`The cli-help rule noticed that "${e}" is not executable.`)}async function An(t){var n;let e=await h();return((n=e==null?void 0:e.bin)==null?void 0:n[t])??void 0}import{z as kt}from"zod";var Rt={"cli-help":{async content(t){let e=kt.object({cliCommand:kt.string().optional()}).optional().parse(t),n=await xt(e==null?void 0:e.cliCommand);return Be(n)}}};import Dn from"node:fs/promises";import Pt from"node:path";import{z as qe}from"zod";var Ot={code:{async content(t){let e=qe.object({file:qe.string(),language:qe.string().optional()}).parse(t),n=Pt.extname(e.file)??"",i=await Dn.readFile(Pt.join(process.cwd(),e.file),"utf8");return`\`\`\`${n}
22
+ \`\`\``}import{isExecutable as Ao}from"is-executable";import jo from"node:path";import{log as Fo}from"remark-mdat";import Do from"which";async function kt(t){return t??=await Io(),Uo(t)}async function Io(){let t=await g();if(t!=null&&t.bin){let e=typeof t.bin=="string"?t.bin:String(Object.values(t.bin).at(0));if(Mo(e))return Fo.info(`Inferred <!-- cli-help --> command to run from package.json: ${e}`),e}throw new Error(`Could not infer which command to run for the <!-- cli-help --> rule. Please pass a "cliCommand" option to the expansion comment, e.g. <!-- cli-help {cliCommend: './dist/bin.js'} -->`)}function Mo(t){let e=jo.parse(t);return e.root!==""||e.dir!==""}async function Uo(t){let e=await Do(t,{nothrow:!0});if(e===null&&(e=await Vo(t)??void 0),e!==void 0&&await Ao(e))return e;throw new Error(`The cli-help rule noticed that "${e}" is not executable.`)}async function Vo(t){var o;let e=await g();return((o=e==null?void 0:e.bin)==null?void 0:o[t])??void 0}import{z as Pt}from"zod";var Rt={"cli-help":{async content(t){let e=Pt.object({cliCommand:Pt.string().optional()}).optional().parse(t),o=await kt(e==null?void 0:e.cliCommand);return Je(o)}}};import Jo from"node:fs/promises";import Ot from"node:path";import{z as Be}from"zod";var St={code:{async content(t){let e=Be.object({file:Be.string(),language:Be.string().optional()}).parse(t),o=Ot.extname(e.file)??"",i=await Jo.readFile(Ot.join(process.cwd(),e.file),"utf8");return`\`\`\`${o}
23
23
  ${i}
24
- \`\`\``}}};var oe={contributing:{async content(){var n;let t=await h(),e=(n=t==null?void 0:t.bugs)==null?void 0:n.url;if(e===void 0)throw new Error('Could not find "bugs.url" entry in package.json');return`## Contributing
25
- [Issues](${e}) and pull requests are welcome.`},order:15,required:!0}};var ie={license:{async content(){let t=await h(),{author:e,license:n}=t;if((e==null?void 0:e.name)===void 0)throw new Error('Could not find "author.name" entry in package.json');if(n===void 0)throw new Error('Could not find "license" entry in package.json');return`## License
26
- [${n}](license.txt) \xA9 ${e.name}`},order:16,required:!0}};import{getSoleRule as St}from"remark-mdat";var vt={footer:{content:[St(oe),St(ie)],order:17}};var re={"short-description":{async content(){let t=await h();if(t.description===void 0)throw new Error('Could not find "description" entry in package.json');return`**${t.description}**`},order:4,required:!0}};import{z as ae}from"zod";var se={title:{applicationOrder:2,async content(t){let{postfix:e,prefix:n,titleCase:i}=ae.object({postfix:ae.string().optional().default(""),prefix:ae.string().optional().default(""),titleCase:ae.boolean().optional().default(!1)}).parse(t??{}),{name:o}=await h();return`# ${n}${i?In(o):o}${e}`},order:1,required:!0}};function In(t){return t.split(/[ _-]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}import{getSoleRule as de}from"remark-mdat";var $t={header:{applicationOrder:2,content:[de(se),de(ne),de(ee),de(re)],order:1}};import{toc as Mn}from"mdast-util-toc";import{remark as Un}from"remark";import Vn from"remark-gfm";import{z as R}from"zod";var me={"table-of-contents":{applicationOrder:1,async content(t,e){let n=R.object({maxDepth:R.union([R.literal(1),R.literal(2),R.literal(3),R.literal(4),R.literal(5),R.literal(6)]).optional()}).optional().parse(t),i=Mn(e,{heading:null,maxDepth:(n==null?void 0:n.maxDepth)??3,tight:!0}),o="## Table of contents";if(i.map===void 0)throw new Error("Could not generate table of contents");let a={children:i.map.children,type:"root"},r=Un().use(Vn).stringify(a).replaceAll(`
24
+ \`\`\``}}};var ne={contributing:{async content(){var o;let t=await g(),e=(o=t==null?void 0:t.bugs)==null?void 0:o.url;if(e===void 0)throw new Error('Could not find "bugs.url" entry in package.json');return`## Contributing
25
+ [Issues](${e}) and pull requests are welcome.`},order:15,required:!0}};var ie={license:{async content(){let t=await g(),{author:e,license:o}=t;if((e==null?void 0:e.name)===void 0)throw new Error('Could not find "author.name" entry in package.json');if(o===void 0)throw new Error('Could not find "license" entry in package.json');return`## License
26
+ [${o}](license.txt) \xA9 ${e.name}`},order:16,required:!0}};import{getSoleRule as vt}from"remark-mdat";var Lt={footer:{content:[vt(ne),vt(ie)],order:17}};var re={"short-description":{async content(){let t=await g();if(t.description===void 0)throw new Error('Could not find "description" entry in package.json');return`**${t.description}**`},order:4,required:!0}};import{z as se}from"zod";var ae={title:{applicationOrder:2,async content(t){let{postfix:e,prefix:o,titleCase:i}=se.object({postfix:se.string().optional().default(""),prefix:se.string().optional().default(""),titleCase:se.boolean().optional().default(!1)}).parse(t??{}),{name:n}=await g();return`# ${o}${i?Bo(n):n}${e}`},order:1,required:!0}};function Bo(t){return t.split(/[ _-]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}import{getSoleRule as de}from"remark-mdat";var Et={header:{applicationOrder:2,content:[de(ae),de(oe),de(ee),de(re)],order:1}};import{toc as qo}from"mdast-util-toc";import{remark as Ho}from"remark";import zo from"remark-gfm";import{z as P}from"zod";var ce={"table-of-contents":{applicationOrder:1,async content(t,e){let o=P.object({maxDepth:P.union([P.literal(1),P.literal(2),P.literal(3),P.literal(4),P.literal(5),P.literal(6)]).optional()}).optional().parse(t),i=qo(e,{heading:null,maxDepth:(o==null?void 0:o.maxDepth)??3,tight:!0}),n="## Table of contents";if(i.map===void 0)throw new Error("Could not generate table of contents");let s={children:i.map.children,type:"root"},r=Ho().use(zo).stringify(s).replaceAll(`
27
27
 
28
28
  `,`
29
- `);return[o,r].join(`
30
- `)},order:6}};import{tldrawToImage as Et}from"@kitschpatrol/tldraw-cli";import Jn from"node:crypto";import _ from"node:fs/promises";import b from"node:path";import{isFile as He}from"path-type";import{z as ze}from"zod";var Ft={tldraw:{async content(t){let{alt:e="tldraw diagram",src:n}=ze.object({alt:ze.string().optional(),src:ze.string()}).parse(t),{assetsPath:i}=await w();if(i===void 0)throw new Error("No assets path found");await _.mkdir(i,{recursive:!0});let o=await He(n)?await Tt(n):void 0;if(o!==void 0){let m=b.basename(n,b.extname(n)),c=b.join(i,`${m}-${o}-light.svg`),p=b.join(i,`${m}-${o}-dark.svg`);if(await He(c)&&await He(p))return Lt(c,p,e)}let[a]=await Et(n,{dark:!1,format:"svg",output:i,transparent:!0});o??=await Tt(a);let r=`${Nt(a)}-${o}-light.svg`;await _.rename(a,r);let[s]=await Et(n,{dark:!0,format:"svg",output:i,transparent:!0}),d=`${Nt(s)}-${o}-dark.svg`;if(await _.rename(s,d),o!==void 0){let m=b.basename(d),c=b.basename(r),p=c.replace(`${o}-light.svg`,""),u=await _.readdir(i);for(let g of u){let C=b.basename(g);C!==m&&C!==c&&C.startsWith(p)&&C.endsWith(".svg")&&await _.rm(b.join(i,C))}}return Lt(r,d,e)}}};async function Lt(t,e,n){let{readmeFile:i}=await w();if(i===void 0)throw new Error("No readme file found");let o=b.dirname(i),a=b.relative(o,t);return`<picture>
31
- <source media="(prefers-color-scheme: dark)" srcset="${b.relative(o,e)}">
32
- <source media="(prefers-color-scheme: light)" srcset="${a}">
33
- <img alt="${n}" src="${a}">
34
- </picture>`}async function Tt(t){let e=await _.readFile(t),n=Jn.createHash("sha1");return n.update(e),n.digest("hex").slice(0,8)}function Nt(t){return t.replace(/\.[^./]+$/,"")}import{getSoleRule as Bn}from"remark-mdat";var _t={toc:{applicationOrder:1,content:[Bn(me)]}};var jt={...ee,...ne,...Rt,...Ot,...oe,...vt,...$t,...ie,...re,...me,...Ft,..._t,...se};async function j(t,e,n,i){let o=await Ge({additionalConfig:n,additionalRules:i});return xe(o.readmeFile,t,e,o)}async function We(t){let e=await Ge({additionalConfig:t});return Re(e.readmeFile,void 0,void 0,e)}async function Ge(t){let e={addMetaComment:!0,rules:jt},{additionalConfig:n=[],...i}=t??{},o=Array.isArray(n)?n:[n],a=await k({additionalConfig:[e,...o],...i});if(a.packageFile===void 0||a.readmeFile===void 0)throw new Error("Package and readme files are required in `mdat readme` config");return a}var At=`<!-- header -->
29
+ `);return[n,r].join(`
30
+ `)},order:6}};import{tldrawToImage as $t}from"@kitschpatrol/tldraw-cli";import Go from"node:crypto";import F from"node:fs/promises";import b from"node:path";import{isFile as qe}from"path-type";import{z as He}from"zod";var At={tldraw:{async content(t){let{alt:e="tldraw diagram",src:o}=He.object({alt:He.string().optional(),src:He.string()}).parse(t),{assetsPath:i}=await C();if(i===void 0)throw new Error("No assets path found");await F.mkdir(i,{recursive:!0});let n=await qe(o)?await Nt(o):void 0;if(n!==void 0){let d=b.basename(o,b.extname(o)),m=b.join(i,`${d}-${n}-light.svg`),l=b.join(i,`${d}-${n}-dark.svg`);if(await qe(m)&&await qe(l))return Tt(m,l,e)}let[s]=await $t(o,{dark:!1,format:"svg",output:i,transparent:!0});n??=await Nt(s);let r=`${_t(s)}-${n}-light.svg`;await F.rename(s,r);let[a]=await $t(o,{dark:!0,format:"svg",output:i,transparent:!0}),c=`${_t(a)}-${n}-dark.svg`;if(await F.rename(a,c),n!==void 0){let d=b.basename(c),m=b.basename(r),l=m.replace(`${n}-light.svg`,""),f=await F.readdir(i);for(let h of f){let y=b.basename(h);y!==d&&y!==m&&y.startsWith(l)&&y.endsWith(".svg")&&await F.rm(b.join(i,y))}}return Tt(r,c,e)}}};async function Tt(t,e,o){let{packageFile:i}=await C();if(i===void 0)throw new Error("No package file found");let n=b.dirname(i),s=b.relative(n,t);return`<picture>
31
+ <source media="(prefers-color-scheme: dark)" srcset="${b.relative(n,e)}">
32
+ <source media="(prefers-color-scheme: light)" srcset="${s}">
33
+ <img alt="${o}" src="${s}">
34
+ </picture>`}async function Nt(t){let e=await F.readFile(t),o=Go.createHash("sha1");return o.update(e),o.digest("hex").slice(0,8)}function _t(t){return t.replace(/\.[^./]+$/,"")}import{getSoleRule as Wo}from"remark-mdat";var jt={toc:{applicationOrder:1,content:[Wo(ce)]}};var Ft={...ee,...oe,...Rt,...St,...ne,...Lt,...Et,...ie,...re,...ce,...At,...jt,...ae};async function me(t){let e={addMetaComment:!0,rules:Ft},{additionalConfig:o=[],...i}=t??{},n=Array.isArray(o)?o:[o],s=await S({additionalConfig:[e,...n],...i});if(s.packageFile===void 0)throw new Error("Package file path is required in `mdat readme` config");return s}import{findUp as Yo}from"find-up";import{packageDirectory as Ko}from"pkg-dir";import{log as Dt}from"remark-mdat";async function ze(){Dt.info("Searching for package directory...");let t=await Ko()??process.cwd(),e=await Yo("readme.md",{stopAt:t,type:"file"});if(e!==void 0)return Dt.info(`Found closest readme at "${e}"`),e}async function pe(){let t=await ze();if(t===void 0)throw new Error("No readme found");return t}async function It(t,e){return Ge(void 0,void 0,void 0,t,e)}async function Ge(t,e,o,i,n){return t??=await pe(),k(t,me,Z,e,o,i,n)}async function Mt(t,e,o,i,n){return t??=await pe(),k(t,me,X,e,o,i,n)}async function Ut(t,e,o,i,n){return t??=await pe(),k(t,me,Q,e,o,i,n)}var Vt=`<!-- header -->
35
35
 
36
36
  <!-- table-of-contents -->
37
37
 
@@ -76,7 +76,7 @@ _List maintainer(s) for a repository, along with one way of contacting them (e.g
76
76
  _State anyone or anything that significantly helped with the development of your project. State public contact hyper-links if applicable._
77
77
 
78
78
  <!-- footer -->
79
- `;var Dt=`<!-- title -->
79
+ `;var Jt=`<!-- title -->
80
80
 
81
81
  <!-- banner -->
82
82
 
@@ -129,7 +129,7 @@ _State anyone or anything that significantly helped with the development of your
129
129
  <!-- contributing -->
130
130
 
131
131
  <!-- license -->
132
- `;var It=`<!-- header -->
132
+ `;var Bt=`<!-- header -->
133
133
 
134
134
  ## Install
135
135
 
@@ -145,7 +145,7 @@ Consider using the <!-- code { src: "path/to/example.ts" } --> comment as well.
145
145
  \`\`\`
146
146
 
147
147
  <!-- footer -->
148
- `;var Mt=`<!-- title -->
148
+ `;var qt=`<!-- title -->
149
149
 
150
150
  <!-- short-description -->
151
151
 
@@ -167,7 +167,7 @@ Consider using the <!-- code { src: "path/to/example.ts" } --> comment as well.
167
167
  <!-- contributing -->
168
168
 
169
169
  <!-- license -->
170
- `;var Ut=`<!-- header -->
170
+ `;var Ht=`<!-- header -->
171
171
 
172
172
  _Long description goes here._
173
173
 
@@ -230,7 +230,7 @@ _List maintainer(s) for a repository, along with one way of contacting them (e.g
230
230
  _State anyone or anything that significantly helped with the development of your project. State public contact hyper-links if applicable._
231
231
 
232
232
  <!-- footer -->
233
- `;var Vt=`<!-- title -->
233
+ `;var zt=`<!-- title -->
234
234
 
235
235
  <!-- banner -->
236
236
 
@@ -301,4 +301,4 @@ _State anyone or anything that significantly helped with the development of your
301
301
  <!-- contributing -->
302
302
 
303
303
  <!-- license -->
304
- `;var v={"Mdat Readme":{content:{compound:At,explicit:Dt},description:"The house style. An expansive starting point. Prune to your context and taste.",exampleLink:"https://github.com/kitschpatrol/mdat/blob/main/readme.md"},"Standard Readme Basic":{content:{compound:It,explicit:Mt},description:'Includes only the "required" sections from the Standard Readme specification.',exampleLink:"https://github.com/RichardLitt/standard-readme/blob/main/example-readmes/minimal-readme.md"},"Standard Readme Full":{content:{compound:Ut,explicit:Vt},description:"Includes all sections from the Standard Readme specification.",exampleLink:"https://github.com/RichardLitt/standard-readme/blob/main/example-readmes/maximal-readme.md"}};import{confirm as Jt,group as Zn,intro as Qn,note as Bt,outro as Xn,select as Ye}from"@clack/prompts";import P from"chalk";import eo from"node:fs/promises";import ce from"node:path";import{deepMergeDefined as to}from"remark-mdat";import{write as no}from"to-vfile";async function qt(){let t=await G(),e=await Y();return{packageDirectory:e===void 0?void 0:ce.dirname(ce.resolve(e)),readmePath:t}}async function Ht(){let{packageDirectory:t,readmePath:e}=await qt(),n=ce.resolve(process.cwd());Qn(`Running ${P.bold("mdat readme init")} interactively`);let i=await Zn({overwrite:async()=>e===void 0||await Jt({message:`Found an existing readme at "${P.blue(e)}". Do you want to overwrite it?`,active:"Overwrite",inactive:"Exit"})?!0:(()=>{throw new Error("`mdat readme init` was cancelled to avoid an overwrite - no changes were made")})(),output:async()=>t!==void 0&&t!==n?Ye({initialValue:t,message:"There's a root package directory nearby, do you want to create the readme there instead of the current directory?",options:[{label:`Create in the current package root: "${P.blue(t)}"`,value:t},{label:`Create in current working directory: "${P.blue(n)}"`,value:n}]}):n,template:async()=>Ye({message:"Which template would you like to use?",options:io()}),compound:async()=>Ye({message:'Do you want to use "compound comments" where possible, which combine several expansions into a single comment block?',options:[{label:`Yes: Combine things like ${P.green("<!-- title -->")} and ${P.green("<!-- badges -->")} in a single ${P.green("<!-- header -->")} comment.`,value:!0},{label:"No: Use individual `mdat` expansion comments for each section.",value:!1}]}),expand:async()=>t===void 0?!1:Jt({initialValue:!0,message:"Do you want to run `mdat readme` now to expand the template with content from your package.json?"})},{onCancel(){throw new Error("`mdat readme init` was cancelled - no changes were made")}}),o=await Ke(i);return t===void 0&&Bt("No package.json was found. Once you've created one, you can run `mdat readme` to expand the template with content from your package.json."),Bt(`Readme created: "${P.bold.blue(o)}"`),Xn("Done!"),o}async function Ke(t){let{packageDirectory:e}=await qt(),n=to({compound:!0,output:e??process.cwd(),overwrite:!0,expand:e!==void 0,template:Object.keys(v)[0]},t??{}),i=oo(n.template,n.compound),o=ce.join(n.output,"readme.md");await eo.writeFile(o,i,"utf8");let a=await j(void 0,void 0,{readmeFile:o});return await no(a),o}function oo(t,e){let i=v[t].content[e?"compound":"explicit"];if(i===void 0||i==="")throw new Error(`No template found for "${t}"`);return i}function io(){return Object.entries(v).map(([t,e])=>({label:t,hint:e.description,value:t}))}var $={config:{defaultDescription:"Configuration is loaded if found from the usual places, or defaults are used.",description:"Path(s) to files containing mdat configs.",string:!0,type:"array"}},B={meta:{alias:"m",description:"Embed an extra comment at the top of the generated Markdown noting the date of generation and warning editors that certain sections of the document have been generated dynamically.",type:"boolean"}},q={name:{alias:"n",defaultDescription:"Same name as input file. Overwrites the input file.",description:"Output file name.",type:"string"}},A={output:{alias:"o",defaultDescription:"Same directory as input file.",description:"Output file directory.",type:"string"}},E={prefix:{description:"Require a string prefix before all comments to be considered for expansion. Useful if you have a bunch of non-`mdat` comments in your Markdown file, or if you're willing to trade some verbosity for safety.",type:"string"}},H={print:{description:"Print the expanded Markdown to stdout instead of saving to a file. Ignores `--output` and `--name` options.",type:"boolean"}},z={rules:{alias:"r",description:"Path(s) to files containing `mdat` comment expansion rules.",string:!0,type:"array"}},O={verbose:{describe:"Enable verbose logging. All verbose logs and prefixed with their log level and are printed to stderr for ease of redirection.",type:"boolean"}},pe=["files",{array:!0,demandOption:!0,describe:"Markdown file(s) with `mdat` placeholder comments to collapse.",type:"string"}];var le={readme:{defaultDescription:"The closest readme.md file is used by default.",description:"Path to the readme.md file to expand.",type:"string"}},Ze={package:{defaultDescription:"The closest package.json file is used by default.",description:"Path to the package.json file to use to populate the readme.",string:!0}},Qe={assets:{defaultDescription:"./assets",description:"Path to find and save readme-related assets.",string:!0}},zt={interactive:{alias:"i",default:!0,description:"Run the guided interactive `init` process. Set explicitly to `false` to use default values and skip the prompt.",type:"boolean"}},Wt={overwrite:{default:!1,defaultDescription:"`false`, if an existing readme is found, don't touch it.",description:"Replace an existing readme file if one is found.",type:"boolean"}},Gt={expand:{alias:"e",default:!0,description:"Automatically run `mdat readme` immediately after creating the readme template.",type:"boolean"}},Yt={template:{alias:"t",choices:Object.keys(v),default:Object.keys(v)[0],description:"Specify a template to use for the new readme.",type:"string"}},Kt={compound:{alias:"c",default:!0,description:"Use compound comment version of the template to replace several individual comment placeholders where possible. This combines things like `<!-- title -->`, `<!-- badges -->`, etc. in a single `<!-- header -->` comment. It's less clutter when you're editing, but it's also less explicit. The final readme.md output is identical.",type:"boolean"}};import D from"chalk";import L from"pretty-ms";import{getMdatReports as ro,log as l,reporterMdat as I}from"remark-mdat";import{write as ue}from"to-vfile";import ao from"yargs";import{hideBin as so}from"yargs/helpers";var T=performance.now(),Zt=ao(so(process.argv));try{await Zt.scriptName("mdat").usage("$0 [command] [options]","Work with `mdat` placeholder comments in any Markdown file.").command(["$0 <files..> [options]","expand <files..> [options]"],"Expand `mdat` placeholder comments.",t=>t.positional(...pe).option($).option(z).option(A).option(q).option(B).option(E).option(H).option(O),async({config:t,files:e,meta:n,name:i,output:o,prefix:a,print:r,rules:s,verbose:d})=>{l.verbose=d,fe({name:i,output:o,print:r});let m=ge(e),c=M(t,{addMetaComment:n,keywordPrefix:a}),p=await X(m,i,o,c,s);for(let u of p)r?process.stdout.write(u.toString()):await ue(u);I(p),l.info(`Expanded comments in ${L(performance.now()-T)}.`),process.exitCode=U(p)}).command("check <files..> [options]","Validate a markdown file with `mdat` placeholder comments.",t=>t.positional(...pe).option($).option(z).option(B).option(E).option(O),async({config:t,files:e,meta:n,prefix:i,rules:o,verbose:a})=>{l.verbose=a;let r=ge(e),s=M(t,{addMetaComment:n,keywordPrefix:i}),d=await X(r,void 0,void 0,s,o);I(d),l.info(`Checked comments in ${L(performance.now()-T)}.`),process.exitCode=U(d)}).command("clean <files..> [options]","Collapse `mdat` placeholder comments.",t=>t.positional(...pe).option($).option(A).option(q).option(E).option(H).option(O),async({config:t,files:e,name:n,output:i,prefix:o,print:a,verbose:r})=>{l.verbose=r,fe({name:n,output:i,print:a});let s=ge(e),d=M(t,{keywordPrefix:o}),m=await ke(s,void 0,void 0,d);for(let c of m)a?process.stdout.write(c.toString()):await ue(c);I(m),l.info(`Cleaned comments in ${L(performance.now()-T)}.`),process.exitCode=U(m)}).command("readme [command] [options]","Work with `mdat` comments in your readme.md.",t=>t.command(["$0 [options]","expand [options]"],"Expand `mdat` comment placeholders in your readme.md using a collection of helpful built-in expansion rules.",e=>e.option($).option(z).option(A).option(q).option(le).option(Ze).option(Qe).option(E).option(B).option(H).option(O),async({assets:e,config:n,meta:i,name:o,output:a,package:r,prefix:s,print:d,readme:m,rules:c,verbose:p})=>{l.verbose=p,fe({name:o,output:a,print:d});let u=M(n,{addMetaComment:i,assetsPath:e,keywordPrefix:s,packageFile:r,readmeFile:m}),g=await j(o,a,u,c);d?process.stdout.write(g.toString()):await ue(g),I([g]);let{packageFile:C,readmeFile:he}=await w();l.info(`Expanded comments in readme: ${D.bold.blue(he)}`),l.info(`Pulled package metadata from: ${D.bold.blue(C)}`),l.info(`Expanded readme in ${L(performance.now()-T)}.`),process.exitCode=U([g])}).command("check [options]","Validate `mdat` placeholder comments in your readme.md.",e=>e.option($).option(z).option(le).option(Ze).option(Qe).option(E).option(B).option(O),async({assets:e,config:n,meta:i,package:o,prefix:a,readme:r,rules:s,verbose:d})=>{l.verbose=d;let m=M(n,{addMetaComment:i,assetsPath:e,keywordPrefix:a,packageFile:o,readmeFile:r}),c=await j(void 0,void 0,m,s);I([c]);let{packageFile:p,readmeFile:u}=await w();l.info(`Checked comments in readme: ${D.bold.blue(u)}`),l.info(`Pulled package metadata from: ${D.bold.blue(p)}`),l.info(`Checked readme in ${L(performance.now()-T)}.`),process.exitCode=U([c])}).command("clean [options]","Collapse `mdat` placeholder comments in your readme.md.",e=>e.option(A).option(q).option(H).option($).option(le).option(E).option(O),async({config:e,name:n,output:i,prefix:o,print:a,readme:r,verbose:s})=>{l.verbose=s,fe({name:n,output:i,print:a});let d=M(e,{keywordPrefix:o,readmeFile:r}),m=await We(d);a?process.stdout.write(m.toString()):await ue(m),I([m]);let{readmeFile:c}=await w();l.info(`Cleaned comments in readme: ${D.bold.blue(c)}`),l.info(`Cleaned readme in ${L(performance.now()-T)}.`),process.exitCode=U([m])}).command("init [options]","Interactively create a new readme.md file with sensible `mdat` comment placeholders.",e=>e.option(zt).option(Wt).option(A).option(Gt).option(Yt).option(Kt).option(O),async({compound:e,expand:n,interactive:i,output:o,overwrite:a,template:r,verbose:s})=>{if(l.verbose=s,i)await Ht();else{let d=await Ke({compound:e,expand:n,output:o,overwrite:a,template:r});l.info(`Created readme at "${D.blue(d)}" in ${L(performance.now()-T)}.`)}process.exitCode=0}),()=>{l.error("Root mdat readme command should be unreachable.")}).help().alias("h","help").version().alias("v","version").wrap(process.stdout.isTTY?Math.min(120,Zt.terminalWidth()):0).fail(!1).parse()}catch(t){t instanceof Error&&l.error(t.message),process.exitCode=1}function fe(t){t.print&&t.output&&l.warn("Ignoring --output option because --print is set"),t.print&&t.name&&l.warn("Ignoring --name option because --print is set")}function ge(t){return t==null?[]:Array.isArray(t)?t:[t]}function M(t,e){return[...ge(t),e]}function U(t){return ro(t).reduce((i,o)=>i+o.errors.length,0)>0?1:0}
304
+ `;var L={"Mdat Readme":{content:{compound:Vt,explicit:Jt},description:"The house style. An expansive starting point. Prune to your context and taste.",exampleLink:"https://github.com/kitschpatrol/mdat/blob/main/readme.md"},"Standard Readme Basic":{content:{compound:Bt,explicit:qt},description:'Includes only the "required" sections from the Standard Readme specification.',exampleLink:"https://github.com/RichardLitt/standard-readme/blob/main/example-readmes/minimal-readme.md"},"Standard Readme Full":{content:{compound:Ht,explicit:zt},description:"Includes all sections from the Standard Readme specification.",exampleLink:"https://github.com/RichardLitt/standard-readme/blob/main/example-readmes/maximal-readme.md"}};import{confirm as Gt,group as nn,intro as rn,note as Wt,outro as sn,select as We}from"@clack/prompts";import R from"chalk";import an from"node:fs/promises";import le from"node:path";import{deepMergeDefined as dn}from"remark-mdat";import{write as cn}from"to-vfile";async function Yt(){let t=await ze(),e=await W();return{packageDirectory:e===void 0?void 0:le.dirname(le.resolve(e)),readmePath:t}}async function Kt(){let{packageDirectory:t,readmePath:e}=await Yt(),o=le.resolve(process.cwd());rn(`Running ${R.bold("mdat readme init")} interactively`);let i=await nn({overwrite:async()=>e===void 0||await Gt({message:`Found an existing readme at "${R.blue(e)}". Do you want to overwrite it?`,active:"Overwrite",inactive:"Exit"})?!0:(()=>{throw new Error("`mdat readme init` was cancelled to avoid an overwrite - no changes were made")})(),output:async()=>t!==void 0&&t!==o?We({initialValue:t,message:"There's a root package directory nearby, do you want to create the readme there instead of the current directory?",options:[{label:`Create in the current package root: "${R.blue(t)}"`,value:t},{label:`Create in current working directory: "${R.blue(o)}"`,value:o}]}):o,template:async()=>We({message:"Which template would you like to use?",options:pn()}),compound:async()=>We({message:'Do you want to use "compound comments" where possible, which combine several expansions into a single comment block?',options:[{label:`Yes: Combine things like ${R.green("<!-- title -->")} and ${R.green("<!-- badges -->")} in a single ${R.green("<!-- header -->")} comment.`,value:!0},{label:"No: Use individual `mdat` expansion comments for each section.",value:!1}]}),expand:async()=>t===void 0?!1:Gt({initialValue:!0,message:"Do you want to run `mdat readme` now to expand the template with content from your package.json?"})},{onCancel(){throw new Error("`mdat readme init` was cancelled - no changes were made")}}),n=await Ye(i);return t===void 0&&Wt("No package.json was found. Once you've created one, you can run `mdat readme` to expand the template with content from your package.json."),Wt(`Readme created: "${R.bold.blue(n)}"`),sn("Done!"),n}async function Ye(t){let{packageDirectory:e}=await Yt(),o=dn({compound:!0,output:e??process.cwd(),overwrite:!0,expand:e!==void 0,template:Object.keys(L)[0]},t??{}),i=mn(o.template,o.compound),n=le.join(o.output,"readme.md");await an.writeFile(n,i,"utf8");let s=await It(void 0,void 0,{readmeFile:n});return await cn(s),n}function mn(t,e){let i=L[t].content[e?"compound":"explicit"];if(i===void 0||i==="")throw new Error(`No template found for "${t}"`);return i}function pn(){return Object.entries(L).map(([t,e])=>({label:t,hint:e.description,value:t}))}var E={config:{defaultDescription:"Configuration is loaded if found from the usual places, or defaults are used.",description:"Path(s) to files containing mdat configs.",string:!0,type:"array"}},B={meta:{alias:"m",description:"Embed an extra comment at the top of the generated Markdown noting the date of generation and warning editors that certain sections of the document have been generated dynamically.",type:"boolean"}},q={name:{alias:"n",defaultDescription:"Same name as input file. Overwrites the input file.",description:"Output file name.",type:"string"}},D={output:{alias:"o",defaultDescription:"Same directory as input file.",description:"Output file directory.",type:"string"}},$={prefix:{description:"Require a string prefix before all comments to be considered for expansion. Useful if you have a bunch of non-`mdat` comments in your Markdown file, or if you're willing to trade some verbosity for safety.",type:"string"}},H={print:{description:"Print the expanded Markdown to stdout instead of saving to a file. Ignores `--output` and `--name` options.",type:"boolean"}},z={rules:{alias:"r",description:"Path(s) to files containing `mdat` comment expansion rules.",string:!0,type:"array"}},O={verbose:{describe:"Enable verbose logging. All verbose logs and prefixed with their log level and are printed to stderr for ease of redirection.",type:"boolean"}},ue=["files",{array:!0,demandOption:!0,describe:"Markdown file(s) with `mdat` placeholder comments to collapse.",type:"string"}];var Ke={package:{defaultDescription:"The closest package.json file is used by default.",description:"Path to the package.json file to use to populate the readme.",string:!0}},Ze={assets:{defaultDescription:"./assets",description:"Path to find and save readme-related assets.",string:!0}},Zt={interactive:{alias:"i",default:!0,description:"Run the guided interactive `init` process. Set explicitly to `false` to use default values and skip the prompt.",type:"boolean"}},Qt={overwrite:{default:!1,defaultDescription:"`false`, if an existing readme is found, don't touch it.",description:"Replace an existing readme file if one is found.",type:"boolean"}},Xt={expand:{alias:"e",default:!0,description:"Automatically run `mdat readme` immediately after creating the readme template.",type:"boolean"}},eo={template:{alias:"t",choices:Object.keys(L),default:Object.keys(L)[0],description:"Specify a template to use for the new readme.",type:"string"}},to={compound:{alias:"c",default:!0,description:"Use compound comment version of the template to replace several individual comment placeholders where possible. This combines things like `<!-- title -->`, `<!-- badges -->`, etc. in a single `<!-- header -->` comment. It's less clutter when you're editing, but it's also less explicit. The final readme.md output is identical.",type:"boolean"}},fe=["files",{array:!0,demandOption:!1,describe:"Readme file(s) with `mdat` placeholder comments to collapse. If not provided, the closest readme.md file is used.",type:"string"}];import Qe from"chalk";import T from"pretty-ms";import{getMdatReports as ln,log as u,reporterMdat as I}from"remark-mdat";import{write as ge}from"to-vfile";import un from"yargs";import{hideBin as fn}from"yargs/helpers";var N=performance.now(),oo=un(fn(process.argv));try{await oo.scriptName("mdat").usage("$0 [command]","Work with `mdat` placeholder comments in any Markdown file.").command(["$0 <files..> [options]","expand <files..> [options]"],"Expand `mdat` placeholder comments.",t=>t.positional(...ue).option(E).option(z).option(D).option(q).option(B).option($).option(H).option(O),async({config:t,files:e,meta:o,name:i,output:n,prefix:s,print:r,rules:a,verbose:c})=>{u.verbose=c??!1,he({name:i,output:n,print:r});let d=M(t,{addMetaComment:o,keywordPrefix:s}),m=await mt(e,i,n,d,a);for(let l of m)r?process.stdout.write(l.toString()):await ge(l);I(m),u.info(`Expanded comments in ${T(performance.now()-N)}.`),process.exitCode=U(m)}).command("check <files..> [options]","Validate a markdown file with `mdat` placeholder comments.",t=>t.positional(...ue).option(E).option(z).option(B).option($).option(O),async({config:t,files:e,meta:o,prefix:i,rules:n,verbose:s})=>{u.verbose=s??!1;let r=M(t,{addMetaComment:o,keywordPrefix:i}),a=await pt(e,void 0,void 0,r,n);I(a),u.info(`Checked comments in ${T(performance.now()-N)}.`),process.exitCode=U(a)}).command("collapse <files..> [options]","Collapse `mdat` placeholder comments.",t=>t.positional(...ue).option(E).option(D).option(q).option($).option(H).option(O),async({config:t,files:e,name:o,output:i,prefix:n,print:s,verbose:r})=>{u.verbose=r??!1,he({name:o,output:i,print:s});let a=M(t,{keywordPrefix:n}),c=await lt(e,void 0,void 0,a);for(let d of c)s?process.stdout.write(d.toString()):await ge(d);I(c),u.info(`Cleaned comments in ${T(performance.now()-N)}.`),process.exitCode=U(c)}).command("readme [command]","Work with `mdat` comments in your readme.md.",t=>t.command(["$0 [files..] [options]","expand [files..] [options]"],"Expand `mdat` comment placeholders in your readme.md using a collection of helpful built-in expansion rules.",e=>e.positional(...fe).option(E).option(z).option(D).option(q).option(Ke).option(Ze).option($).option(B).option(H).option(O),async({assets:e,config:o,files:i,meta:n,name:s,output:r,package:a,prefix:c,print:d,rules:m,verbose:l})=>{u.verbose=l??!1,he({name:s,output:r,print:d});let f=M(o,{addMetaComment:n,assetsPath:e,keywordPrefix:c,packageFile:a}),h=await Ge(i,s,r,f,m);for(let _ of h)d?process.stdout.write(_.toString()):await ge(_);I(h);let{packageFile:y}=await C();u.info(`Pulled package metadata from: ${Qe.bold.blue(y)}`),u.info(`Expanded readme(s) in ${T(performance.now()-N)}.`),process.exitCode=U(h)}).command("check [files..] [options]","Validate `mdat` placeholder comments in your readme.md.",e=>e.positional(...fe).option(E).option(z).option(Ke).option(Ze).option($).option(B).option(O),async({assets:e,config:o,files:i,meta:n,package:s,prefix:r,rules:a,verbose:c})=>{u.verbose=c??!1;let d=M(o,{addMetaComment:n,assetsPath:e,keywordPrefix:r,packageFile:s}),m=await Mt(i,void 0,void 0,d,a);I(m);let{packageFile:l}=await C();u.info(`Pulled package metadata from: ${Qe.bold.blue(l)}`),u.info(`Checked readme(s) in ${T(performance.now()-N)}.`),process.exitCode=U(m)}).command("collapse [files..] [options]","Collapse `mdat` placeholder comments in your readme.md.",e=>e.positional(...fe).option(D).option(q).option(H).option(E).option($).option(O),async({config:e,files:o,name:i,output:n,prefix:s,print:r,verbose:a})=>{u.verbose=a??!1,he({name:i,output:n,print:r});let c=M(e,{keywordPrefix:s,readmeFile}),d=await Ut(o,void 0,void 0,c);for(let m of d)r?process.stdout.write(m.toString()):await ge(m);I(d),u.info(`Cleaned readme(s) in ${T(performance.now()-N)}.`),process.exitCode=U(d)}).command("init [options]","Interactively create a new readme.md file with sensible default `mdat` comment placeholders.",e=>e.option(Zt).option(Qt).option(D).option(Xt).option(eo).option(to).option(O),async({compound:e,expand:o,interactive:i,output:n,overwrite:s,template:r,verbose:a})=>{if(u.verbose=a??!1,i)await Kt();else{let c=await Ye({compound:e,expand:o,output:n,overwrite:s,template:r});u.info(`Created readme at "${Qe.blue(c)}" in ${T(performance.now()-N)}.`)}process.exitCode=0}),()=>{u.error("Root mdat readme command should be unreachable.")}).help().alias("h","help").version().alias("v","version").wrap(process.stdout.isTTY?Math.min(120,oo.terminalWidth()):0).fail(!1).parse()}catch(t){t instanceof Error&&u.error(t.message),process.exitCode=1}function he(t){t.print&&t.output&&u.warn("Ignoring --output option because --print is set"),t.print&&t.name&&u.warn("Ignoring --name option because --print is set")}function M(t,e){return[...Y(t),e]}function U(t){return ln(t).reduce((i,n)=>i+n.errors.length,0)>0?1:0}
package/dist/api.d.ts CHANGED
@@ -1,20 +1,11 @@
1
1
  import { type ConfigToLoad, type RulesToLoad } from './config';
2
- import { VFile } from 'vfile';
2
+ import { type VFile } from 'vfile';
3
3
  /**
4
4
  * Writing is the responsibility of the caller (e.g. via `await write(result)`)
5
5
  */
6
- export declare function expandFiles(files: string[], name?: string, output?: string, config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile[]>;
7
- /**
8
- * Writing is the responsibility of the caller (e.g. via `await write(result)`)
9
- */
10
- export declare function expandFile(file: string, name?: string, output?: string, config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile>;
6
+ export declare function expandFiles(files: string | string[], name?: string, output?: string, config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile[]>;
11
7
  export declare function expandString(markdown: string, config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile>;
12
- /**
13
- * Writing is the responsibility of the caller (e.g. via `await write(result)`)
14
- */
15
- export declare function cleanFiles(files: string[], name?: string, output?: string, config?: ConfigToLoad): Promise<VFile[]>;
16
- /**
17
- * Writing is the responsibility of the caller (e.g. via `await write(result)`)
18
- */
19
- export declare function cleanFile(file: string, name?: string, output?: string, config?: ConfigToLoad): Promise<VFile>;
20
- export declare function cleanString(markdown: string, config: ConfigToLoad): Promise<VFile>;
8
+ export declare function checkFiles(files: string | string[], name?: string, output?: string, config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile[]>;
9
+ export declare function checkString(markdown: string, config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile>;
10
+ export declare function collapseFiles(files: string | string[], name?: string, output?: string, config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile[]>;
11
+ export declare function collapseString(markdown: string, config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile>;
package/dist/config.d.ts CHANGED
@@ -3,7 +3,6 @@ import { type Options, type Rules } from 'remark-mdat';
3
3
  export type Config = {
4
4
  assetsPath?: string;
5
5
  packageFile?: string;
6
- readmeFile?: string;
7
6
  } & Options;
8
7
  export type ConfigLoaded = {
9
8
  addMetaComment: boolean;
@@ -12,7 +11,6 @@ export type ConfigLoaded = {
12
11
  keywordPrefix: string;
13
12
  metaCommentIdentifier: string;
14
13
  packageFile: string | undefined;
15
- readmeFile: string | undefined;
16
14
  rules: Rules;
17
15
  };
18
16
  /**
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- export { cleanFile, cleanFiles, cleanString, expandFile, expandFiles, expandString } from './api';
1
+ export { checkFiles, checkString, collapseFiles, collapseString, expandFiles, expandString, } from './api';
2
2
  export { type Config, loadConfig } from './config';
3
- export { cleanReadme, expandReadme, expandReadmeString, loadConfigReadme } from './readme/api';
3
+ export { checkReadmeFiles, checkReadmeString, collapseReadmeFiles, expandReadmeFiles, expandReadmeString, } from './readme/api';
4
+ export { loadConfigReadme } from './readme/config';
4
5
  export { type Rules } from 'remark-mdat';
package/dist/index.js CHANGED
@@ -1,33 +1,33 @@
1
- import{defaultLoaders as st}from"cosmiconfig";function H(t,e){let n=st[".json"],i=n(t,e);return Re(i)}function Re(t,e="",n={}){for(let[i,o]of Object.entries(t)){let a=e?`${e}.${i}`:i;typeof o=="object"&&o!==null&&!Array.isArray(o)?Re(o,a,n):o===null?n[a]="null":n[a]=o.toString()}return n}import{findUp as mt}from"find-up";import dt from"node:fs";import C from"node:path";import{packageUp as ct}from"package-up";import{isFileSync as Se}from"path-type";import{packageDirectory as ut}from"pkg-dir";import{log as ke}from"remark-mdat";import ft from"untildify";function pt(t,e){let n=e===0?1:Math.floor(Math.log10(Math.abs(e))+1);return t.toString().padStart(n,"0")}function z(t,e,n,i){let o=[];for(let[a,r]of t.entries()){let s=n&&t.length>1?`-${pt(a+1,t.length+1)}`:"",m=O(r,e,n,i,s);o.push(m)}return o}function O(t,e,n,i,o=""){let a=$e(t),r=e?$e(e):void 0;if(!Se(a))throw new Error(`Input file not found: "${a}"`);if(r){if(Se(r))throw new Error(`Output path must be a directory, received a file path: "${r}"`);dt.mkdirSync(r,{recursive:!0})}let s=n?C.basename(n,C.extname(n)):C.basename(a,C.extname(a)),m=`.${i??(n&&C.extname(n)!==""?C.extname(n):C.extname(t)===""?"":C.extname(t))}`,d=`${s}${o}${m}`,u=r??C.dirname(a);return{input:a,name:d,output:u}}function $e(t){return ft(t)}async function Ee(){ke.info("Searching for package directory...");let t=await ut()??process.cwd(),e=await mt("readme.md",{stopAt:t,type:"file"});if(e!==void 0)return ke.info(`Found closest readme at "${e}"`),e}async function xe(){return ct()}import Ne from"chalk";import{cosmiconfig as Oe}from"cosmiconfig";import lt from"node:fs/promises";import Te from"node:path";import gt from"plur";import{readPackage as ht}from"read-pkg";import{deepMergeDefined as q,log as g,optionsSchema as yt,rulesSchema as wt}from"remark-mdat";import{z as L}from"zod";var Le=yt.merge(L.object({assetsPath:L.string().optional(),packageFile:L.string().optional(),readmeFile:L.string().optional()})).describe("Config Extension");async function h(t){let{additionalConfig:e,additionalRules:n,searchFrom:i}=t??{},o={addMetaComment:!1,assetsPath:"./assets",closingPrefix:"/",keywordPrefix:"",metaCommentIdentifier:"+",packageFile:await xe(),readmeFile:await Ee(),rules:{mdat:"Powered by the Markdown Autophagic Template system: [mdat](https://github.com/kitschpatrol/mdat)."}},a=Oe("mdat"),r=await a.search(i);if(r){let{config:s,filepath:m}=r;g.info(`Using config from "${m}"`);let d=Fe(s,Le);d&&(o=q(o,d))}if(e!==void 0){let s=Array.isArray(e)?e:[e];for(let m of s){let d;if(typeof m=="string"){let f=await a.load(m);if(f==null)continue;let{config:p,filepath:w}=f;g.info(`Loaded additional config from "${w}"`),d=p}else d=m;if(d===void 0)continue;g.info("Merging configuration object");let u=Fe(d,Le);u!==void 0&&(o=q(o,u))}}if(n!==void 0){let s=Array.isArray(n)?n:[n],m=Oe("mdat",{loaders:{".json":H}});for(let d of s){let u;if(typeof d=="string"){let p;if(Te.basename(d).endsWith("package.json")){let at=await lt.readFile(d,"utf8");p={config:H(d,at),filepath:d}}else p=await m.load(d);if(p==null)continue;let{config:w,filepath:b}=p;g.info(`Loaded additional config from "${b}"`),u=w}else u=d;if(u===void 0)continue;g.info("Merging rules into configuration object");let f=Ct(u,wt);f!==void 0&&(o=q(o,f))}}if(o.rules){let s=Object.keys(o.rules).sort().map(m=>`"${Ne.bold.green(m)}"`);g.info(`Loaded ${Ne.bold(s.length)} mdat comment expansion ${gt("rule",s.length)}:`);for(let m of s)g.info(` ${m}`)}else g.error("No rules loaded from additional configurations or rules, using default.");return F=o,o}function Ct(t,e){if(e.safeParse(t).success)return{rules:t};g.error(`Rules object has the wrong shape. Ignoring and using default configuration:
2
- ${JSON.stringify(t,void 0,2)}`)}function Fe(t,e){if(e.safeParse(t).success)return t;g.error(`Config object has the wrong shape. Ignoring and using default configuration:
3
- ${JSON.stringify(t,void 0,2)}`)}var F;async function R(){return F===void 0&&(g.warn("getConfig(): config was undefined"),F??=await h()),F}var W;async function l(){let{packageFile:t}=await R();if(t===void 0)throw new Error("No packageFile found or set in config");if(W??=await ht({cwd:Te.dirname(t)}),W===void 0)throw new Error("No package.json found");return W}import{remark as Ae}from"remark";import je from"remark-gfm";import{mdatClean as Pt,mdatSplit as bt,default as Rt}from"remark-mdat";import{read as T}from"to-vfile";import{VFile as Me}from"vfile";async function St(t,e,n,i,o){let a=await h({additionalConfig:i,additionalRules:o});i=a;let r=z(t,n,e,"md"),s=[],m=Z(a);for(let{input:d,name:u,output:f}of r){let p=await T(d),w=await m.process(p);w.dirname=f,w.basename=u,s.push(w)}return s}async function Y(t,e,n,i,o){let a=await h({additionalConfig:i,additionalRules:o});i=a;let r=O(t,n,e,"md"),s=await T(r.input),m=await Z(a).process(s);return m.dirname=r.output,m.basename=r.name,m}async function K(t,e,n){let i=await h({additionalConfig:e,additionalRules:n});return e=i,Z(i).process(new Me(t))}async function kt(t,e,n,i){let o=await h({additionalConfig:i});i=o;let a=z(t,n,e,"md"),r=[],s=Q(o);for(let{input:m,name:d,output:u}of a){let f=await T(m),p=await s.process(f);p.dirname=u,p.basename=d,r.push(p)}return r}async function G(t,e,n,i){let o=await h({additionalConfig:i});i=o;let a=O(t,n,e,"md"),r=await T(a.input),s=await Q(o).process(r);return s.dirname=a.output,s.basename=a.name,s}async function $t(t,e){let n=await h({additionalConfig:e});return e=n,Q(n).process(new Me(t))}function Z(t){return Ae().use({settings:{bullet:"-",emphasis:"_"}}).use(je).use(Rt,t??{})}function Q(t){let{closingPrefix:e,keywordPrefix:n,metaCommentIdentifier:i}=t;return Ae().use({settings:{bullet:"-",emphasis:"_"}}).use(je).use(()=>function(a,r){bt(a,r),Pt(a,r,{closingPrefix:e,keywordPrefix:n,metaCommentIdentifier:i})})}import{z as x}from"zod";var A={badges:{async content(t){var r;let e=x.object({custom:x.record(x.object({image:x.string(),link:x.string()})).optional()}).optional().parse(t),n=await l(),{name:i}=n,o=[];!n.private&&((r=n.publishConfig)==null?void 0:r.access)==="public"&&o.push(`[![NPM Package](https://img.shields.io/npm/v/${i}.svg)](https://npmjs.com/package/${i})`);let{license:a}=n;if(a!==void 0&&o.push(`[![License: ${a}](https://img.shields.io/badge/License-${a}-yellow.svg)](https://opensource.org/licenses/${a})`),(e==null?void 0:e.custom)!==void 0)for(let[s,{image:m,link:d}]of Object.entries(e.custom))o.push(`[![${s}](${m})](${d})`);return o.join(`
4
- `)},order:3,required:!1}};import{globby as Et}from"globby";import j from"node:path";import{isFile as xt}from"path-type";import{readPackage as Nt}from"read-pkg";import{z as X}from"zod";async function Ot(t){let{packageFile:e}=await R();if(e===void 0)throw new Error("No package.json found");let n=j.dirname(e),i=t===void 0?[".","assets","media","readme-assets","readme-media","readme","images"]:[t],o=["banner","header","logo","readme","cover","screenshot","screenshots","demo","overview","image","hero"],a=["png","gif","jpg","jpeg","svg","webp"],r=await Et(i.map(s=>j.join(n,s)),{expandDirectories:{extensions:a,files:o}});if(r.length>0)return j.relative(process.cwd(),r[0])}var M={banner:{async content(t){let e=X.object({alt:X.string().optional(),src:X.string().optional()}).optional().parse(t),{assetsPath:n,packageFile:i}=await R();if(i===void 0)throw new Error("No package.json found");let o=(e==null?void 0:e.src)??await Ot(n);if(o===void 0||!await xt(o))throw new Error(`Banner image not found at ${o===void 0?"any typical location, consider adding something at ./assets/banner.webp":`"${o}"`}`);let a=(e==null?void 0:e.alt)??`${(await Nt({cwd:j.dirname(i)})).name} banner`;if(a===void 0||a==="undefined banner")throw new Error("Banner image alt text not available");return`![${a}](${o})`},order:2}};import{CstParser as Lt,Lexer as S,createToken as c}from"chevrotain";var ne=c({name:"flag",pattern:/--[\w-_]+/}),oe=c({name:"alias",pattern:/-[A-Za-z]/}),ve=c({group:S.SKIPPED,name:"comma",pattern:/,/}),$=c({name:"word",pattern:/\S+/}),N=c({name:"argument",pattern:/<\S+>|\[\S+]/}),ie=c({name:"type",pattern:/\[(boolean|string|array)]/}),re=c({name:"defaultInfo",pattern:/\[default]/}),ae=c({name:"required",pattern:/\[required]/}),se=c({name:"defaultInfoDescription",pattern:/\[default:\s.+?]/}),me=c({name:"choices",pattern:/\[choices:\s.+?]/}),ee=c({group:S.SKIPPED,name:"whiteSpace",pattern:/\s/}),De=c({group:S.SKIPPED,name:"startProgramDescription",pattern:/\n\n/,push_mode:"PROGRAM_DESCRIPTION_MODE"}),de=c({name:"programDescription",pattern:/.+/}),Ue=c({group:S.SKIPPED,name:"endProgramDescription",pattern:/\n\n/,pop_mode:!0}),ce=c({name:"startOptionsSection",pattern:/Options:\n/,push_mode:"SECTION_MODE"}),ue=c({name:"startPositionalsSection",pattern:/Positionals:\n/,push_mode:"SECTION_MODE"}),fe=c({name:"startCommandsSection",pattern:/Commands:\n/,push_mode:"SECTION_MODE"}),pe=c({name:"startRow",pattern:/ {2,}/,push_mode:"ROW_MODE"}),le=c({name:"rowDescription",pattern:/ {2}\w.+ {2}/}),ge=c({name:"rowDescriptionTerminal",pattern:/ {2}\w.+/}),_e=c({group:S.SKIPPED,name:"endRow",pattern:/\n/,pop_mode:!0}),Ie=c({group:S.SKIPPED,name:"endSection",pattern:/\n+/,pop_mode:!0}),Ft=new S({defaultMode:"DEFAULT_MODE",modes:{DEFAULT_MODE:[ce,ue,fe,De,N,$,ee],PROGRAM_DESCRIPTION_MODE:[Ue,de],ROW_MODE:[_e,ve,ie,le,ge,se,re,ae,me,ne,oe,N,$,ee],SECTION_MODE:[pe,Ie]}}),Tt=[ne,oe,ve,$,N,ie,re,ae,se,me,ee,De,de,Ue,ce,ue,fe,pe,le,ge,_e,Ie];function At(t){return Ft.tokenize(t.trim())}var te=class extends Lt{programHelp=this.RULE("programHelp",()=>{this.AT_LEAST_ONE(()=>{this.CONSUME($,{LABEL:"commandName"})}),this.MANY1(()=>{this.CONSUME(N)}),this.OPTION(()=>{this.CONSUME(de,{LABEL:"description"})}),this.OPTION1(()=>{this.SUBRULE(this.commandsSection)}),this.OPTION2(()=>{this.SUBRULE(this.positionalsSection)}),this.OPTION3(()=>{this.SUBRULE(this.optionsSection)})});positionalsSection=this.RULE("positionalsSection",()=>{this.CONSUME(ue),this.MANY(()=>{this.SUBRULE(this.sectionRow)})});commandsSection=this.RULE("commandsSection",()=>{this.CONSUME(fe),this.MANY1(()=>{this.SUBRULE1(this.sectionRow)})});optionsSection=this.RULE("optionsSection",()=>{this.CONSUME(ce),this.MANY2(()=>{this.SUBRULE2(this.sectionRow)})});sectionRow=this.RULE("sectionRow",()=>{this.CONSUME(pe),this.OPTION(()=>{this.CONSUME($,{LABEL:"parentCommandName"})}),this.MANY(()=>{this.CONSUME1($,{LABEL:"commandName"})}),this.MANY1(()=>{this.OR([{ALT:()=>this.CONSUME(N)},{ALT:()=>this.CONSUME(oe)},{ALT:()=>this.CONSUME(ne)},{ALT:()=>this.CONSUME(le,{LABEL:"description"})},{ALT:()=>this.CONSUME(ge,{LABEL:"description"})},{ALT:()=>this.CONSUME(ie)},{ALT:()=>this.CONSUME(ae)},{ALT:()=>this.CONSUME(se)},{ALT:()=>this.CONSUME(re)},{ALT:()=>this.CONSUME(me)}])})});constructor(){super(Tt),this.performSelfAnalysis()}},k=new te;function Ve(t){let e=At(t);k.input=e.tokens;let n=k.programHelp();if(k.errors.length>0)throw new Error(`Errors parsing CLI command help text output: ${JSON.stringify(k.errors,void 0,2)}`);return n}var he=class extends k.getBaseCstVisitorConstructor(){constructor(){super(),this.validateVisitor()}programHelp(e){let{command:n,subcommand:i}=Mt(this.getString(e.commandName));return{arguments:this.getArray(e.argument),commandName:n,commands:e.commandsSection?this.visit(e.commandsSection):void 0,description:this.getString(e.description),options:e.optionsSection?this.visit(e.optionsSection):void 0,positionals:e.positionalsSection?this.visit(e.positionalsSection):void 0,subcommandName:i}}positionalsSection(e){return e.sectionRow.map(n=>this.positionalParentCommandToArguments(this.visit(n)))}commandsSection(e){return e.sectionRow.map(n=>this.visit(n))}optionsSection(e){return e.sectionRow.map(n=>this.visit(n))}sectionRow(e){return{aliases:this.getArray(e.alias),arguments:this.getArray(e.argument),choices:this.splitChoices(this.getString(e.choices)),commandName:this.getString(e.commandName),default:e.defaultInfo?!0:void 0,defaultValue:this.getString(e.defaultInfoDescription,!0),description:this.getString(e.description,!0),flags:this.getArray(e.flag),parentCommandName:this.getString(e.parentCommandName),required:e.required?!0:void 0,type:this.getString(e.type,!0)}}positionalParentCommandToArguments(e){let{arguments:n,parentCommandName:i,...o}=e;return i===void 0?e:{arguments:[i,...n??[]],...o}}getString(e,n=!1){if(e!==void 0)return e.map(i=>n?this.clean(i.image):i.image).join(" ")}getArray(e){if(e!==void 0)return e.map(n=>n.image)}clean(e){return e.replaceAll(/^[\s[]*(default:)?\s*|[\s\]]*$/g,"")}splitChoices(e){if(e!==void 0)return this.clean(e.replaceAll(/^\[choices:\s/g,"")).split(", ")}},jt=new he;function Je(t){return jt.visit(t)}function Mt(t){if(t===void 0)throw new Error('Could not find "commandName" entry in help');let e=t.split(" ");if(e.length===0&&t===void 0)throw new Error('Could not find "commandName" entry in help');if(e.length===1)return{command:e[0],subcommand:void 0};let n=e.at(-1);return{command:e.slice(0,-1).join(" "),subcommand:n}}function Be(t,e=!1){var i,o,a;let n=[];if(e){let r=(i=t.commands)==null?void 0:i.find(d=>d.default),s=(o=t.commands)==null?void 0:o.find(d=>d.commandName===void 0),m=`${t.commandName}${t.subcommandName?` ${t.subcommandName}`:""}`;n.push(`#### Command: \`${m}\``),s!=null&&s.description&&n.push(s==null?void 0:s.description),n.push(`This section lists top-level commands for \`${m}\`.`),r&&n.push(`If no command is provided, \`${r.parentCommandName} ${r.commandName}\` is run by default.`),n.push("Usage:"),s&&n.push(`\`\`\`txt
5
- ${s.parentCommandName}${s.arguments?` ${s.arguments.join(" ")}`:""}
6
- \`\`\``),t.commands=(a=t.commands)==null?void 0:a.filter(d=>d!==s)}else n.push(`#### Subcommand: \`${t.commandName} ${t.subcommandName}\``),n.push(t.description),n.push("Usage:"),n.push(`\`\`\`txt
1
+ import{defaultLoaders as dt}from"cosmiconfig";function Y(t,e){let n=dt[".json"],r=n(t,e);return ke(r)}function ke(t,e="",n={}){for(let[r,o]of Object.entries(t)){let s=e?`${e}.${r}`:r;typeof o=="object"&&o!==null&&!Array.isArray(o)?ke(o,s,n):o===null?n[s]="null":n[s]=o.toString()}return n}import mt from"node:fs";import w from"node:path";import{packageUp as ct}from"package-up";import{isFileSync as Le}from"path-type";import ft from"untildify";function ut(t,e){let n=e===0?1:Math.floor(Math.log10(Math.abs(e))+1);return t.toString().padStart(n,"0")}function Ee(t,e,n,r){let o=[];for(let[s,i]of t.entries()){let a=n&&t.length>1?`-${ut(s+1,t.length+1)}`:"",m=pt(i,e,n,r,a);o.push(m)}return o}function pt(t,e,n,r,o=""){let s=xe(t),i=e?xe(e):void 0;if(!Le(s))throw new Error(`Input file not found: "${s}"`);if(i){if(Le(i))throw new Error(`Output path must be a directory, received a file path: "${i}"`);mt.mkdirSync(i,{recursive:!0})}let a=n?w.basename(n,w.extname(n)):w.basename(s,w.extname(s)),m=`.${r??(n&&w.extname(n)!==""?w.extname(n):w.extname(t)===""?"":w.extname(t))}`,d=`${a}${o}${m}`,f=i??w.dirname(s);return{input:s,name:d,output:f}}function xe(t){return ft(t)}async function $e(){return ct()}function Ne(t){return t==null?[]:Array.isArray(t)?t:[t]}import Te from"chalk";import{cosmiconfig as Oe}from"cosmiconfig";import lt from"node:fs/promises";import je from"node:path";import gt from"plur";import{readPackage as ht}from"read-pkg";import{deepMergeDefined as K,log as g,optionsSchema as yt,rulesSchema as Ct}from"remark-mdat";import{z as Z}from"zod";var Fe=yt.merge(Z.object({assetsPath:Z.string().optional(),packageFile:Z.string().optional()})).describe("Config Extension");async function h(t){let{additionalConfig:e,additionalRules:n,searchFrom:r}=t??{},o={addMetaComment:!1,assetsPath:"./assets",closingPrefix:"/",keywordPrefix:"",metaCommentIdentifier:"+",packageFile:await $e(),rules:{mdat:"Powered by the Markdown Autophagic Template system: [mdat](https://github.com/kitschpatrol/mdat)."}},s=Oe("mdat"),i=await s.search(r);if(i){let{config:a,filepath:m}=i;g.info(`Using config from "${m}"`);let d=Ae(a,Fe);d&&(o=K(o,d))}if(e!==void 0){let a=Array.isArray(e)?e:[e];for(let m of a){let d;if(typeof m=="string"){let u=await s.load(m);if(u==null)continue;let{config:l,filepath:b}=u;g.info(`Loaded additional config from "${b}"`),d=l}else d=m;if(d===void 0)continue;g.info("Merging configuration object");let f=Ae(d,Fe);f!==void 0&&(o=K(o,f))}}if(n!==void 0){let a=Array.isArray(n)?n:[n],m=Oe("mdat",{loaders:{".json":Y}});for(let d of a){let f;if(typeof d=="string"){let l;if(je.basename(d).endsWith("package.json")){let W=await lt.readFile(d,"utf8");l={config:Y(d,W),filepath:d}}else l=await m.load(d);if(l==null)continue;let{config:b,filepath:C}=l;g.info(`Loaded additional config from "${C}"`),f=b}else f=d;if(f===void 0)continue;g.info("Merging rules into configuration object");let u=wt(f,Ct);u!==void 0&&(o=K(o,u))}}if(o.rules){let a=Object.keys(o.rules).sort().map(m=>`"${Te.bold.green(m)}"`);g.info(`Loaded ${Te.bold(a.length)} mdat comment expansion ${gt("rule",a.length)}:`);for(let m of a)g.info(` ${m}`)}else g.error("No rules loaded from additional configurations or rules, using default.");return D=o,o}function wt(t,e){if(e.safeParse(t).success)return{rules:t};g.error(`Rules object has the wrong shape. Ignoring and using default configuration:
2
+ ${JSON.stringify(t,void 0,2)}`)}function Ae(t,e){if(e.safeParse(t).success)return t;g.error(`Config object has the wrong shape. Ignoring and using default configuration:
3
+ ${JSON.stringify(t,void 0,2)}`)}var D;async function S(){return D===void 0&&(g.warn("getConfig(): config was undefined"),D??=await h()),D}var Q;async function p(){let{packageFile:t}=await S();if(t===void 0)throw new Error("No packageFile found or set in config");if(Q??=await ht({cwd:je.dirname(t)}),Q===void 0)throw new Error("No package.json found");return Q}import{remark as X}from"remark";import ee from"remark-gfm";import{mdatCheck as Pt,mdatClean as Me,mdatExpand as Rt,mdatSplit as De}from"remark-mdat";import{read as bt}from"to-vfile";import{VFile as St}from"vfile";async function P(t,e,n,r,o,s,i){let a=await e({additionalConfig:s,additionalRules:i});s=a;let m=Ne(t),d=Ee(m,o,r,"md"),f=[],u=n(a);for(let{input:l,name:b,output:C}of d){let W=await bt(l),M=await u.process(W);M.dirname=C,M.basename=b,f.push(M)}return f}async function k(t,e,n,r,o){let s=await e({additionalConfig:r,additionalRules:o});return r=s,n(s).process(new St(t))}function E(t){return X().use({settings:{bullet:"-",emphasis:"_"}}).use(ee).use(()=>async function(n,r){De(n,r),Me(n,r,t),await Rt(n,r,t)})}function F(t){return X().use({settings:{bullet:"-",emphasis:"_"}}).use(ee).use(()=>function(n,r){De(n,r),Me(n,r,t)})}function $(t){return X().use({settings:{bullet:"-",emphasis:"_"}}).use(ee).use(()=>async function(n,r){await Pt(n,r,{...t,paranoid:!1})})}async function kt(t,e,n,r,o){return P(t,h,E,e,n,r,o)}async function Lt(t,e,n){return k(t,h,E,e,n)}async function xt(t,e,n,r,o){return P(t,h,$,e,n,r,o)}async function Et(t,e,n){return k(t,h,$,e,n)}async function $t(t,e,n,r,o){return P(t,h,F,e,n,r,o)}async function Nt(t,e,n){return k(t,h,F,e,n)}import{z as A}from"zod";var v={badges:{async content(t){var i;let e=A.object({custom:A.record(A.object({image:A.string(),link:A.string()})).optional()}).optional().parse(t),n=await p(),{name:r}=n,o=[];!n.private&&((i=n.publishConfig)==null?void 0:i.access)==="public"&&o.push(`[![NPM Package](https://img.shields.io/npm/v/${r}.svg)](https://npmjs.com/package/${r})`);let{license:s}=n;if(s!==void 0&&o.push(`[![License: ${s}](https://img.shields.io/badge/License-${s}-yellow.svg)](https://opensource.org/licenses/${s})`),(e==null?void 0:e.custom)!==void 0)for(let[a,{image:m,link:d}]of Object.entries(e.custom))o.push(`[![${a}](${m})](${d})`);return o.join(`
4
+ `)},order:3,required:!1}};import{globby as Tt}from"globby";import U from"node:path";import{isFile as Ot}from"path-type";import{readPackage as Ft}from"read-pkg";import{z as te}from"zod";async function At(t){let{packageFile:e}=await S();if(e===void 0)throw new Error("No package.json found");let n=U.dirname(e),r=t===void 0?[".","assets","media","readme-assets","readme-media","readme","images"]:[t],o=["banner","header","logo","readme","cover","screenshot","screenshots","demo","overview","image","hero"],s=["png","gif","jpg","jpeg","svg","webp"],i=await Tt(r.map(a=>U.join(n,a)),{expandDirectories:{extensions:s,files:o}});if(i.length>0)return U.relative(process.cwd(),i[0])}var V={banner:{async content(t){let e=te.object({alt:te.string().optional(),src:te.string().optional()}).optional().parse(t),{assetsPath:n,packageFile:r}=await S();if(r===void 0)throw new Error("No package.json found");let o=(e==null?void 0:e.src)??await At(n);if(o===void 0||!await Ot(o))throw new Error(`Banner image not found at ${o===void 0?"any typical location, consider adding something at ./assets/banner.webp":`"${o}"`}`);let s=(e==null?void 0:e.alt)??`${(await Ft({cwd:U.dirname(r)})).name} banner`;if(s===void 0||s==="undefined banner")throw new Error("Banner image alt text not available");return`![${s}](${o})`},order:2}};import{CstParser as jt,Lexer as L,createToken as c}from"chevrotain";var re=c({name:"flag",pattern:/--[\w-_]+/}),ie=c({name:"alias",pattern:/-[A-Za-z]/}),ve=c({group:L.SKIPPED,name:"comma",pattern:/,/}),T=c({name:"word",pattern:/\S+/}),j=c({name:"argument",pattern:/<\S+>|\[\S+]/}),se=c({name:"type",pattern:/\[(boolean|string|array)]/}),ae=c({name:"defaultInfo",pattern:/\[default]/}),de=c({name:"required",pattern:/\[required]/}),me=c({name:"defaultInfoDescription",pattern:/\[default:\s.+?]/}),ce=c({name:"choices",pattern:/\[choices:\s.+?]/}),ne=c({group:L.SKIPPED,name:"whiteSpace",pattern:/\s/}),Ue=c({group:L.SKIPPED,name:"startProgramDescription",pattern:/\n\n/,push_mode:"PROGRAM_DESCRIPTION_MODE"}),fe=c({name:"programDescription",pattern:/.+/}),Ve=c({group:L.SKIPPED,name:"endProgramDescription",pattern:/\n\n/,pop_mode:!0}),ue=c({name:"startOptionsSection",pattern:/Options:\n/,push_mode:"SECTION_MODE"}),pe=c({name:"startPositionalsSection",pattern:/Positionals:\n/,push_mode:"SECTION_MODE"}),le=c({name:"startCommandsSection",pattern:/Commands:\n/,push_mode:"SECTION_MODE"}),ge=c({name:"startRow",pattern:/ {2,}/,push_mode:"ROW_MODE"}),he=c({name:"rowDescription",pattern:/ {2}\w.+ {2}/}),ye=c({name:"rowDescriptionTerminal",pattern:/ {2}\w.+/}),_e=c({group:L.SKIPPED,name:"endRow",pattern:/\n/,pop_mode:!0}),Ie=c({group:L.SKIPPED,name:"endSection",pattern:/\n+/,pop_mode:!0}),Mt=new L({defaultMode:"DEFAULT_MODE",modes:{DEFAULT_MODE:[ue,pe,le,Ue,j,T,ne],PROGRAM_DESCRIPTION_MODE:[Ve,fe],ROW_MODE:[_e,ve,se,he,ye,me,ae,de,ce,re,ie,j,T,ne],SECTION_MODE:[ge,Ie]}}),Dt=[re,ie,ve,T,j,se,ae,de,me,ce,ne,Ue,fe,Ve,ue,pe,le,ge,he,ye,_e,Ie];function vt(t){return Mt.tokenize(t.trim())}var oe=class extends jt{programHelp=this.RULE("programHelp",()=>{this.AT_LEAST_ONE(()=>{this.CONSUME(T,{LABEL:"commandName"})}),this.MANY1(()=>{this.CONSUME(j)}),this.OPTION(()=>{this.CONSUME(fe,{LABEL:"description"})}),this.OPTION1(()=>{this.SUBRULE(this.commandsSection)}),this.OPTION2(()=>{this.SUBRULE(this.positionalsSection)}),this.OPTION3(()=>{this.SUBRULE(this.optionsSection)})});positionalsSection=this.RULE("positionalsSection",()=>{this.CONSUME(pe),this.MANY(()=>{this.SUBRULE(this.sectionRow)})});commandsSection=this.RULE("commandsSection",()=>{this.CONSUME(le),this.MANY1(()=>{this.SUBRULE1(this.sectionRow)})});optionsSection=this.RULE("optionsSection",()=>{this.CONSUME(ue),this.MANY2(()=>{this.SUBRULE2(this.sectionRow)})});sectionRow=this.RULE("sectionRow",()=>{this.CONSUME(ge),this.OPTION(()=>{this.CONSUME(T,{LABEL:"parentCommandName"})}),this.MANY(()=>{this.CONSUME1(T,{LABEL:"commandName"})}),this.MANY1(()=>{this.OR([{ALT:()=>this.CONSUME(j)},{ALT:()=>this.CONSUME(ie)},{ALT:()=>this.CONSUME(re)},{ALT:()=>this.CONSUME(he,{LABEL:"description"})},{ALT:()=>this.CONSUME(ye,{LABEL:"description"})},{ALT:()=>this.CONSUME(se)},{ALT:()=>this.CONSUME(de)},{ALT:()=>this.CONSUME(me)},{ALT:()=>this.CONSUME(ae)},{ALT:()=>this.CONSUME(ce)}])})});constructor(){super(Dt),this.performSelfAnalysis()}},N=new oe;function Je(t){let e=vt(t);N.input=e.tokens;let n=N.programHelp();if(N.errors.length>0)throw new Error(`Errors parsing CLI command help text output: ${JSON.stringify(N.errors,void 0,2)}`);return n}var Ce=class extends N.getBaseCstVisitorConstructor(){constructor(){super(),this.validateVisitor()}programHelp(e){let{command:n,subcommand:r}=Vt(this.getString(e.commandName));return{arguments:this.getArray(e.argument),commandName:n,commands:e.commandsSection?this.visit(e.commandsSection):void 0,description:this.getString(e.description),options:e.optionsSection?this.visit(e.optionsSection):void 0,positionals:e.positionalsSection?this.visit(e.positionalsSection):void 0,subcommandName:r}}positionalsSection(e){return e.sectionRow.map(n=>this.positionalParentCommandToArguments(this.visit(n)))}commandsSection(e){return e.sectionRow.map(n=>this.visit(n))}optionsSection(e){return e.sectionRow.map(n=>this.visit(n))}sectionRow(e){return{aliases:this.getArray(e.alias),arguments:this.getArray(e.argument),choices:this.splitChoices(this.getString(e.choices)),commandName:this.getString(e.commandName),default:e.defaultInfo?!0:void 0,defaultValue:this.getString(e.defaultInfoDescription,!0),description:this.getString(e.description,!0),flags:this.getArray(e.flag),parentCommandName:this.getString(e.parentCommandName),required:e.required?!0:void 0,type:this.getString(e.type,!0)}}positionalParentCommandToArguments(e){let{arguments:n,parentCommandName:r,...o}=e;return r===void 0?e:{arguments:[r,...n??[]],...o}}getString(e,n=!1){if(e!==void 0)return e.map(r=>n?this.clean(r.image):r.image).join(" ")}getArray(e){if(e!==void 0)return e.map(n=>n.image)}clean(e){return e.replaceAll(/^[\s[]*(default:)?\s*|[\s\]]*$/g,"")}splitChoices(e){if(e!==void 0)return this.clean(e.replaceAll(/^\[choices:\s/g,"")).split(", ")}},Ut=new Ce;function Be(t){return Ut.visit(t)}function Vt(t){if(t===void 0)throw new Error('Could not find "commandName" entry in help');let e=t.split(" ");if(e.length===0&&t===void 0)throw new Error('Could not find "commandName" entry in help');if(e.length===1)return{command:e[0],subcommand:void 0};let n=e.at(-1);return{command:e.slice(0,-1).join(" "),subcommand:n}}function He(t,e=!1){var r,o,s;let n=[];if(e){let i=(r=t.commands)==null?void 0:r.find(d=>d.default),a=(o=t.commands)==null?void 0:o.find(d=>d.commandName===void 0),m=`${t.commandName}${t.subcommandName?` ${t.subcommandName}`:""}`;n.push(`#### Command: \`${m}\``),a!=null&&a.description&&n.push(a==null?void 0:a.description),n.push(`This section lists top-level commands for \`${m}\`.`),i&&n.push(`If no command is provided, \`${i.parentCommandName} ${i.commandName}\` is run by default.`),n.push("Usage:"),a&&n.push(`\`\`\`txt
5
+ ${a.parentCommandName}${a.arguments?` ${a.arguments.join(" ")}`:""}
6
+ \`\`\``),t.commands=(s=t.commands)==null?void 0:s.filter(d=>d!==a)}else n.push(`#### Subcommand: \`${t.commandName} ${t.subcommandName}\``),n.push(t.description),n.push("Usage:"),n.push(`\`\`\`txt
7
7
  ${t.commandName} ${t.subcommandName}${t.arguments?` ${t.arguments.join(" ")}`:""}
8
- \`\`\``);return t.positionals&&!e&&n.push(ye(["Positional Argument","Description","Type","Default"],t.positionals.map(r=>[r.arguments?[r.arguments.map(s=>`\`${s}\``)].join(" "):"",`${r.description??""}${r.required?" _(Required.)_":" _(Optional.)_"}`,r.type?`\`${r.type}\``:"",r.defaultValue?r.defaultValue.includes(" ")?r.defaultValue:`\`${r.defaultValue}\``:""]))),t.commands&&n.push(ye(["Command","Argument","Description"],t.commands.map(r=>{var s;return[`\`${r.commandName??(r.default?"[default]":"")}\``,r.arguments?(s=r.arguments)==null?void 0:s.map(m=>`\`${m}\``).join(" "):"",`${r.description??""}${r.default?" _(Default command.)_":""}`]}))),t.options&&!e&&n.push(ye(["Option","Alias","Argument","Description","Type","Default"],t.options.map(r=>[r.flags?r.flags.map(s=>`\`${s}\``).join(" "):"",r.aliases?r.aliases.map(s=>`\`${s}\``).join(" "):"",r.arguments?r.arguments.map(s=>`\`${s}\``).join(" "):"",r.description??"",r.type?`\`${r.type}\``:"",r.defaultValue?r.defaultValue.includes(" ")?r.defaultValue:`\`${r.defaultValue}\``:""]))),e&&n.push("_See the sections below for more information on each subcommand._"),n.join(`
8
+ \`\`\``);return t.positionals&&!e&&n.push(we(["Positional Argument","Description","Type","Default"],t.positionals.map(i=>[i.arguments?[i.arguments.map(a=>`\`${a}\``)].join(" "):"",`${i.description??""}${i.required?" _(Required.)_":" _(Optional.)_"}`,i.type?`\`${i.type}\``:"",i.defaultValue?i.defaultValue.includes(" ")?i.defaultValue:`\`${i.defaultValue}\``:""]))),t.commands&&n.push(we(["Command","Argument","Description"],t.commands.map(i=>{var a;return[`\`${i.commandName??(i.default?"[default]":"")}\``,i.arguments?(a=i.arguments)==null?void 0:a.map(m=>`\`${m}\``).join(" "):"",`${i.description??""}${i.default?" _(Default command.)_":""}`]}))),t.options&&!e&&n.push(we(["Option","Alias","Argument","Description","Type","Default"],t.options.map(i=>[i.flags?i.flags.map(a=>`\`${a}\``).join(" "):"",i.aliases?i.aliases.map(a=>`\`${a}\``).join(" "):"",i.arguments?i.arguments.map(a=>`\`${a}\``).join(" "):"",i.description??"",i.type?`\`${i.type}\``:"",i.defaultValue?i.defaultValue.includes(" ")?i.defaultValue:`\`${i.defaultValue}\``:""]))),e&&n.push("_See the sections below for more information on each subcommand._"),n.join(`
9
9
 
10
- `)}function ye(t,e){let n=vt(e);t=t.filter((o,a)=>!n.includes(a)),e=e.map(o=>o.filter((a,r)=>!n.includes(r)));let i="";i+=`| ${t.join(" | ")} |
11
- `,i+=`| ${t.map(()=>"---").join(" | ")} |
12
- `;for(let o of e)i+=`| ${o.join(" | ")} |
13
- `;return i}function vt(t){var i;let e=[],n=((i=t[0])==null?void 0:i.length)||0;for(let o=0;o<n;o++){let a=!0;for(let r of t)if(r[o]!==""){a=!1;break}a&&e.push(o)}return e}import{execaCommand as Dt}from"execa";import{log as He}from"remark-mdat";async function we(t){let e=`${t} --help`,n;try{let{stderr:o,stdout:a}=await Dt(e);n=a,(n===void 0||n==="")&&(n=o)}catch(o){if(o instanceof Error)throw new TypeError(`Error running CLI help command: ${e}
10
+ `)}function we(t,e){let n=_t(e);t=t.filter((o,s)=>!n.includes(s)),e=e.map(o=>o.filter((s,i)=>!n.includes(i)));let r="";r+=`| ${t.join(" | ")} |
11
+ `,r+=`| ${t.map(()=>"---").join(" | ")} |
12
+ `;for(let o of e)r+=`| ${o.join(" | ")} |
13
+ `;return r}function _t(t){var r;let e=[],n=((r=t[0])==null?void 0:r.length)||0;for(let o=0;o<n;o++){let s=!0;for(let i of t)if(i[o]!==""){s=!1;break}s&&e.push(o)}return e}import{execaCommand as It}from"execa";import{log as ze}from"remark-mdat";async function Pe(t){let e=`${t} --help`,n;try{let{stderr:o,stdout:s}=await It(e);n=s,(n===void 0||n==="")&&(n=o)}catch(o){if(o instanceof Error)throw new TypeError(`Error running CLI help command: ${e}
14
14
  ${o.message}
15
15
  `)}if(n===void 0||n==="")throw new Error(`No result from running CLI help command: ${e}
16
- `);let i;try{let o=Ve(n);i=Je(o)}catch(o){o instanceof Error&&(i=void 0,He.warn(`Error parsing help output for command: ${t}
17
- ${o.message}`),He.warn("Falling back to basic cli help text output."))}return i===void 0?_t(n):Ut(t,i)}async function Ut(t,e){let n=(e.commands&&e.commands.some(a=>a.default))??!1,i=Be(e,n),o=t.split(" ")[0];if(e.commands)for(let a of e.commands){if(!a.parentCommandName||!a.commandName)continue;let r=await we(`${o} ${a.commandName}`);i+=`
16
+ `);let r;try{let o=Je(n);r=Be(o)}catch(o){o instanceof Error&&(r=void 0,ze.warn(`Error parsing help output for command: ${t}
17
+ ${o.message}`),ze.warn("Falling back to basic cli help text output."))}return r===void 0?Bt(n):Jt(t,r)}async function Jt(t,e){let n=(e.commands&&e.commands.some(s=>s.default))??!1,r=He(e,n),o=t.split(" ")[0];if(e.commands)for(let s of e.commands){if(!s.parentCommandName||!s.commandName)continue;let i=await Pe(`${o} ${s.commandName}`);r+=`
18
18
 
19
- ${r}`}return i}function _t(t){return`\`\`\`txt
19
+ ${i}`}return r}function Bt(t){return`\`\`\`txt
20
20
  ${t}
21
- \`\`\``}import{isExecutable as It}from"is-executable";import Vt from"node:path";import{log as Jt}from"remark-mdat";import Bt from"which";async function ze(t){return t??=await Ht(),qt(t)}async function Ht(){let t=await l();if(t!=null&&t.bin){let e=typeof t.bin=="string"?t.bin:String(Object.values(t.bin).at(0));if(zt(e))return Jt.info(`Inferred <!-- cli-help --> command to run from package.json: ${e}`),e}throw new Error(`Could not infer which command to run for the <!-- cli-help --> rule. Please pass a "cliCommand" option to the expansion comment, e.g. <!-- cli-help {cliCommend: './dist/bin.js'} -->`)}function zt(t){let e=Vt.parse(t);return e.root!==""||e.dir!==""}async function qt(t){let e=await Bt(t,{nothrow:!0});if(e===null&&(e=await Wt(t)??void 0),e!==void 0&&await It(e))return e;throw new Error(`The cli-help rule noticed that "${e}" is not executable.`)}async function Wt(t){var n;let e=await l();return((n=e==null?void 0:e.bin)==null?void 0:n[t])??void 0}import{z as qe}from"zod";var We={"cli-help":{async content(t){let e=qe.object({cliCommand:qe.string().optional()}).optional().parse(t),n=await ze(e==null?void 0:e.cliCommand);return we(n)}}};import Yt from"node:fs/promises";import Ye from"node:path";import{z as Ce}from"zod";var Ke={code:{async content(t){let e=Ce.object({file:Ce.string(),language:Ce.string().optional()}).parse(t),n=Ye.extname(e.file)??"",i=await Yt.readFile(Ye.join(process.cwd(),e.file),"utf8");return`\`\`\`${n}
22
- ${i}
23
- \`\`\``}}};var v={contributing:{async content(){var n;let t=await l(),e=(n=t==null?void 0:t.bugs)==null?void 0:n.url;if(e===void 0)throw new Error('Could not find "bugs.url" entry in package.json');return`## Contributing
24
- [Issues](${e}) and pull requests are welcome.`},order:15,required:!0}};var D={license:{async content(){let t=await l(),{author:e,license:n}=t;if((e==null?void 0:e.name)===void 0)throw new Error('Could not find "author.name" entry in package.json');if(n===void 0)throw new Error('Could not find "license" entry in package.json');return`## License
25
- [${n}](license.txt) \xA9 ${e.name}`},order:16,required:!0}};import{getSoleRule as Ge}from"remark-mdat";var Ze={footer:{content:[Ge(v),Ge(D)],order:17}};var U={"short-description":{async content(){let t=await l();if(t.description===void 0)throw new Error('Could not find "description" entry in package.json');return`**${t.description}**`},order:4,required:!0}};import{z as _}from"zod";var I={title:{applicationOrder:2,async content(t){let{postfix:e,prefix:n,titleCase:i}=_.object({postfix:_.string().optional().default(""),prefix:_.string().optional().default(""),titleCase:_.boolean().optional().default(!1)}).parse(t??{}),{name:o}=await l();return`# ${n}${i?Kt(o):o}${e}`},order:1,required:!0}};function Kt(t){return t.split(/[ _-]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}import{getSoleRule as V}from"remark-mdat";var Qe={header:{applicationOrder:2,content:[V(I),V(M),V(A),V(U)],order:1}};import{toc as Gt}from"mdast-util-toc";import{remark as Zt}from"remark";import Qt from"remark-gfm";import{z as P}from"zod";var J={"table-of-contents":{applicationOrder:1,async content(t,e){let n=P.object({maxDepth:P.union([P.literal(1),P.literal(2),P.literal(3),P.literal(4),P.literal(5),P.literal(6)]).optional()}).optional().parse(t),i=Gt(e,{heading:null,maxDepth:(n==null?void 0:n.maxDepth)??3,tight:!0}),o="## Table of contents";if(i.map===void 0)throw new Error("Could not generate table of contents");let a={children:i.map.children,type:"root"},r=Zt().use(Qt).stringify(a).replaceAll(`
21
+ \`\`\``}import{isExecutable as Ht}from"is-executable";import zt from"node:path";import{log as qt}from"remark-mdat";import Gt from"which";async function qe(t){return t??=await Wt(),Kt(t)}async function Wt(){let t=await p();if(t!=null&&t.bin){let e=typeof t.bin=="string"?t.bin:String(Object.values(t.bin).at(0));if(Yt(e))return qt.info(`Inferred <!-- cli-help --> command to run from package.json: ${e}`),e}throw new Error(`Could not infer which command to run for the <!-- cli-help --> rule. Please pass a "cliCommand" option to the expansion comment, e.g. <!-- cli-help {cliCommend: './dist/bin.js'} -->`)}function Yt(t){let e=zt.parse(t);return e.root!==""||e.dir!==""}async function Kt(t){let e=await Gt(t,{nothrow:!0});if(e===null&&(e=await Zt(t)??void 0),e!==void 0&&await Ht(e))return e;throw new Error(`The cli-help rule noticed that "${e}" is not executable.`)}async function Zt(t){var n;let e=await p();return((n=e==null?void 0:e.bin)==null?void 0:n[t])??void 0}import{z as Ge}from"zod";var We={"cli-help":{async content(t){let e=Ge.object({cliCommand:Ge.string().optional()}).optional().parse(t),n=await qe(e==null?void 0:e.cliCommand);return Pe(n)}}};import Qt from"node:fs/promises";import Ye from"node:path";import{z as Re}from"zod";var Ke={code:{async content(t){let e=Re.object({file:Re.string(),language:Re.string().optional()}).parse(t),n=Ye.extname(e.file)??"",r=await Qt.readFile(Ye.join(process.cwd(),e.file),"utf8");return`\`\`\`${n}
22
+ ${r}
23
+ \`\`\``}}};var _={contributing:{async content(){var n;let t=await p(),e=(n=t==null?void 0:t.bugs)==null?void 0:n.url;if(e===void 0)throw new Error('Could not find "bugs.url" entry in package.json');return`## Contributing
24
+ [Issues](${e}) and pull requests are welcome.`},order:15,required:!0}};var I={license:{async content(){let t=await p(),{author:e,license:n}=t;if((e==null?void 0:e.name)===void 0)throw new Error('Could not find "author.name" entry in package.json');if(n===void 0)throw new Error('Could not find "license" entry in package.json');return`## License
25
+ [${n}](license.txt) \xA9 ${e.name}`},order:16,required:!0}};import{getSoleRule as Ze}from"remark-mdat";var Qe={footer:{content:[Ze(_),Ze(I)],order:17}};var J={"short-description":{async content(){let t=await p();if(t.description===void 0)throw new Error('Could not find "description" entry in package.json');return`**${t.description}**`},order:4,required:!0}};import{z as B}from"zod";var H={title:{applicationOrder:2,async content(t){let{postfix:e,prefix:n,titleCase:r}=B.object({postfix:B.string().optional().default(""),prefix:B.string().optional().default(""),titleCase:B.boolean().optional().default(!1)}).parse(t??{}),{name:o}=await p();return`# ${n}${r?Xt(o):o}${e}`},order:1,required:!0}};function Xt(t){return t.split(/[ _-]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}import{getSoleRule as z}from"remark-mdat";var Xe={header:{applicationOrder:2,content:[z(H),z(V),z(v),z(J)],order:1}};import{toc as en}from"mdast-util-toc";import{remark as tn}from"remark";import nn from"remark-gfm";import{z as R}from"zod";var q={"table-of-contents":{applicationOrder:1,async content(t,e){let n=R.object({maxDepth:R.union([R.literal(1),R.literal(2),R.literal(3),R.literal(4),R.literal(5),R.literal(6)]).optional()}).optional().parse(t),r=en(e,{heading:null,maxDepth:(n==null?void 0:n.maxDepth)??3,tight:!0}),o="## Table of contents";if(r.map===void 0)throw new Error("Could not generate table of contents");let s={children:r.map.children,type:"root"},i=tn().use(nn).stringify(s).replaceAll(`
26
26
 
27
27
  `,`
28
- `);return[o,r].join(`
29
- `)},order:6}};import{tldrawToImage as Xe}from"@kitschpatrol/tldraw-cli";import Xt from"node:crypto";import E from"node:fs/promises";import y from"node:path";import{isFile as Pe}from"path-type";import{z as be}from"zod";var ot={tldraw:{async content(t){let{alt:e="tldraw diagram",src:n}=be.object({alt:be.string().optional(),src:be.string()}).parse(t),{assetsPath:i}=await R();if(i===void 0)throw new Error("No assets path found");await E.mkdir(i,{recursive:!0});let o=await Pe(n)?await tt(n):void 0;if(o!==void 0){let d=y.basename(n,y.extname(n)),u=y.join(i,`${d}-${o}-light.svg`),f=y.join(i,`${d}-${o}-dark.svg`);if(await Pe(u)&&await Pe(f))return et(u,f,e)}let[a]=await Xe(n,{dark:!1,format:"svg",output:i,transparent:!0});o??=await tt(a);let r=`${nt(a)}-${o}-light.svg`;await E.rename(a,r);let[s]=await Xe(n,{dark:!0,format:"svg",output:i,transparent:!0}),m=`${nt(s)}-${o}-dark.svg`;if(await E.rename(s,m),o!==void 0){let d=y.basename(m),u=y.basename(r),f=u.replace(`${o}-light.svg`,""),p=await E.readdir(i);for(let w of p){let b=y.basename(w);b!==d&&b!==u&&b.startsWith(f)&&b.endsWith(".svg")&&await E.rm(y.join(i,b))}}return et(r,m,e)}}};async function et(t,e,n){let{readmeFile:i}=await R();if(i===void 0)throw new Error("No readme file found");let o=y.dirname(i),a=y.relative(o,t);return`<picture>
28
+ `);return[o,i].join(`
29
+ `)},order:6}};import{tldrawToImage as et}from"@kitschpatrol/tldraw-cli";import on from"node:crypto";import O from"node:fs/promises";import y from"node:path";import{isFile as be}from"path-type";import{z as Se}from"zod";var rt={tldraw:{async content(t){let{alt:e="tldraw diagram",src:n}=Se.object({alt:Se.string().optional(),src:Se.string()}).parse(t),{assetsPath:r}=await S();if(r===void 0)throw new Error("No assets path found");await O.mkdir(r,{recursive:!0});let o=await be(n)?await nt(n):void 0;if(o!==void 0){let d=y.basename(n,y.extname(n)),f=y.join(r,`${d}-${o}-light.svg`),u=y.join(r,`${d}-${o}-dark.svg`);if(await be(f)&&await be(u))return tt(f,u,e)}let[s]=await et(n,{dark:!1,format:"svg",output:r,transparent:!0});o??=await nt(s);let i=`${ot(s)}-${o}-light.svg`;await O.rename(s,i);let[a]=await et(n,{dark:!0,format:"svg",output:r,transparent:!0}),m=`${ot(a)}-${o}-dark.svg`;if(await O.rename(a,m),o!==void 0){let d=y.basename(m),f=y.basename(i),u=f.replace(`${o}-light.svg`,""),l=await O.readdir(r);for(let b of l){let C=y.basename(b);C!==d&&C!==f&&C.startsWith(u)&&C.endsWith(".svg")&&await O.rm(y.join(r,C))}}return tt(i,m,e)}}};async function tt(t,e,n){let{packageFile:r}=await S();if(r===void 0)throw new Error("No package file found");let o=y.dirname(r),s=y.relative(o,t);return`<picture>
30
30
  <source media="(prefers-color-scheme: dark)" srcset="${y.relative(o,e)}">
31
- <source media="(prefers-color-scheme: light)" srcset="${a}">
32
- <img alt="${n}" src="${a}">
33
- </picture>`}async function tt(t){let e=await E.readFile(t),n=Xt.createHash("sha1");return n.update(e),n.digest("hex").slice(0,8)}function nt(t){return t.replace(/\.[^./]+$/,"")}import{getSoleRule as en}from"remark-mdat";var it={toc:{applicationOrder:1,content:[en(J)]}};var rt={...A,...M,...We,...Ke,...v,...Ze,...Qe,...D,...U,...J,...ot,...it,...I};async function tn(t,e,n,i){let o=await B({additionalConfig:n,additionalRules:i});return Y(o.readmeFile,t,e,o)}async function nn(t,e,n){let i=await B({additionalConfig:e,additionalRules:n});return K(t,i)}async function on(t){let e=await B({additionalConfig:t});return G(e.readmeFile,void 0,void 0,e)}async function B(t){let e={addMetaComment:!0,rules:rt},{additionalConfig:n=[],...i}=t??{},o=Array.isArray(n)?n:[n],a=await h({additionalConfig:[e,...o],...i});if(a.packageFile===void 0||a.readmeFile===void 0)throw new Error("Package and readme files are required in `mdat readme` config");return a}export{G as cleanFile,kt as cleanFiles,on as cleanReadme,$t as cleanString,Y as expandFile,St as expandFiles,tn as expandReadme,nn as expandReadmeString,K as expandString,h as loadConfig,B as loadConfigReadme};
31
+ <source media="(prefers-color-scheme: light)" srcset="${s}">
32
+ <img alt="${n}" src="${s}">
33
+ </picture>`}async function nt(t){let e=await O.readFile(t),n=on.createHash("sha1");return n.update(e),n.digest("hex").slice(0,8)}function ot(t){return t.replace(/\.[^./]+$/,"")}import{getSoleRule as rn}from"remark-mdat";var it={toc:{applicationOrder:1,content:[rn(q)]}};var st={...v,...V,...We,...Ke,..._,...Qe,...Xe,...I,...J,...q,...rt,...it,...H};async function x(t){let e={addMetaComment:!0,rules:st},{additionalConfig:n=[],...r}=t??{},o=Array.isArray(n)?n:[n],s=await h({additionalConfig:[e,...o],...r});if(s.packageFile===void 0)throw new Error("Package file path is required in `mdat readme` config");return s}import{findUp as sn}from"find-up";import{packageDirectory as an}from"pkg-dir";import{log as at}from"remark-mdat";async function dn(){at.info("Searching for package directory...");let t=await an()??process.cwd(),e=await sn("readme.md",{stopAt:t,type:"file"});if(e!==void 0)return at.info(`Found closest readme at "${e}"`),e}async function G(){let t=await dn();if(t===void 0)throw new Error("No readme found");return t}async function mn(t,e,n,r,o){return t??=await G(),P(t,x,E,e,n,r,o)}async function cn(t,e,n){return k(t,x,E,e,n)}async function fn(t,e,n,r,o){return t??=await G(),P(t,x,$,e,n,r,o)}async function un(t,e,n){return k(t,x,$,e,n)}async function pn(t,e,n,r,o){return t??=await G(),P(t,x,F,e,n,r,o)}export{xt as checkFiles,fn as checkReadmeFiles,un as checkReadmeString,Et as checkString,$t as collapseFiles,pn as collapseReadmeFiles,Nt as collapseString,kt as expandFiles,mn as expandReadmeFiles,cn as expandReadmeString,Lt as expandString,h as loadConfig,x as loadConfigReadme};
@@ -0,0 +1,11 @@
1
+ import { type ConfigLoaded, type ConfigToLoad, type RulesToLoad, type loadConfig } from './config';
2
+ import { type Root } from 'mdast';
3
+ import { VFile } from 'vfile';
4
+ type Loader = typeof loadConfig;
5
+ type ProcessorGetter = typeof getCleanProcessor | typeof getExpandProcessor;
6
+ export declare function processFiles(files: string | string[], loader: Loader, processorGetter: ProcessorGetter, name?: string, output?: string, config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile[]>;
7
+ export declare function processString(markdown: string, loader: Loader, processorGetter: ProcessorGetter, config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile>;
8
+ export declare function getExpandProcessor(options: ConfigLoaded): import("unified").Processor<Root, undefined, undefined, Root, string>;
9
+ export declare function getCleanProcessor(options: ConfigLoaded): import("unified").Processor<Root, undefined, undefined, Root, string>;
10
+ export declare function getCheckProcessor(options: ConfigLoaded): import("unified").Processor<Root, undefined, undefined, Root, string>;
11
+ export {};
@@ -1,13 +1,10 @@
1
- import { type ConfigLoaded, type ConfigToLoad, type RulesToLoad, loadConfig } from '../config';
2
- import { type Simplify } from 'type-fest';
1
+ import { type ConfigToLoad, type RulesToLoad } from '../config';
3
2
  import { type VFile } from 'vfile';
4
- type ReadmeConfigLoaded = Simplify<{
5
- packageFile: string;
6
- readmeFile: string;
7
- } & ConfigLoaded>;
8
- export declare function expandReadme(name?: string, output?: string, config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile>;
3
+ export declare function expandReadme(config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile[]>;
4
+ export declare function expandReadmeFiles(files?: string | string[], name?: string, output?: string, config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile[]>;
9
5
  export declare function expandReadmeString(markdown: string, config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile>;
10
- export declare function cleanReadme(config?: ConfigToLoad): Promise<VFile>;
11
- type LoadConfigOptions = Parameters<typeof loadConfig>[0];
12
- export declare function loadConfigReadme(options?: LoadConfigOptions): Promise<ReadmeConfigLoaded>;
13
- export {};
6
+ export declare function checkReadme(config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile[]>;
7
+ export declare function checkReadmeFiles(files?: string | string[], name?: string, output?: string, config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile[]>;
8
+ export declare function checkReadmeString(markdown: string, config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile>;
9
+ export declare function collapseReadme(config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile[]>;
10
+ export declare function collapseReadmeFiles(files?: string | string[], name?: string, output?: string, config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile[]>;
@@ -0,0 +1,8 @@
1
+ import { type ConfigLoaded, loadConfig } from '../config';
2
+ import { type Simplify } from 'type-fest';
3
+ type ReadmeConfigLoaded = Simplify<{
4
+ packageFile: string;
5
+ } & ConfigLoaded>;
6
+ type LoadConfigOptions = Parameters<typeof loadConfig>[0];
7
+ export declare function loadConfigReadme(options?: LoadConfigOptions): Promise<ReadmeConfigLoaded>;
8
+ export {};
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Searches for a readme file in the following order:
3
+ * 1. Searches the current working directly for readme.md
4
+ * 2. If there's no readme.md in the current directory, search up to the closest package directory
5
+ * 3. Give up and return undefined if no readme is found
6
+ *
7
+ * @returns The path to the readme file or undefined if not found
8
+ */
9
+ export declare function findReadme(): Promise<string | undefined>;
10
+ export declare function findReadmeThrows(): Promise<string>;
@@ -9,14 +9,5 @@ export declare function getInputOutputPath(input: string, output: string | undef
9
9
  output: string;
10
10
  };
11
11
  export declare function expandPath(file: string): string;
12
- /**
13
- * Searches for a readme file in the following order:
14
- * 1. Searches the current working directly for readme.md
15
- * 2. If there's no readme.md in the current directory, search up to the closest package directory
16
- * 3. Give up and return undefined if no readme is found
17
- *
18
- * @returns The path to the readme file
19
- * @throws If no readme is found
20
- */
21
- export declare function findReadme(): Promise<string | undefined>;
22
12
  export declare function findPackage(): Promise<string | undefined>;
13
+ export declare function ensureArray<T>(value: T | T[] | undefined): T[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mdat",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "description": "CLI tool and library for using comments as content templates in Markdown files, with helpful presets for readmes.",
6
6
  "repository": {
@@ -70,7 +70,7 @@
70
70
  "which": "^4.0.0",
71
71
  "yargs": "^17.7.2",
72
72
  "zod": "^3.22.4",
73
- "remark-mdat": "0.3.1"
73
+ "remark-mdat": "0.4.0"
74
74
  },
75
75
  "devDependencies": {
76
76
  "@types/node": "^20.11.17",
package/readme.md CHANGED
@@ -22,7 +22,7 @@
22
22
  - [Features](#features)
23
23
  - [1. Minimalist syntax](#1-minimalist-syntax)
24
24
  - [2. Single-comment placeholders](#2-single-comment-placeholders)
25
- - [3. Familiar JSON argument syntax](#3-familiar-json-argument-syntax)
25
+ - [3. Familiar JSON arguments](#3-familiar-json-arguments)
26
26
  - [4. Flexible rule system](#4-flexible-rule-system)
27
27
  - [5. TypeScript native](#5-typescript-native)
28
28
  - [6. Validation](#6-validation)
@@ -54,9 +54,9 @@ This is a CLI tool and library implementing the Markdown Autophagic Template (md
54
54
  <!-- tldraw src: "./assets/mdat-flow.tldr" -->
55
55
 
56
56
  <picture>
57
- <source media="(prefers-color-scheme: dark)" srcset="assets/mdat-flow-c830c457-dark.svg">
58
- <source media="(prefers-color-scheme: light)" srcset="assets/mdat-flow-c830c457-light.svg">
59
- <img alt="tldraw diagram" src="assets/mdat-flow-c830c457-light.svg">
57
+ <source media="(prefers-color-scheme: dark)" srcset="assets/mdat-flow-5607417b-dark.svg">
58
+ <source media="(prefers-color-scheme: light)" srcset="assets/mdat-flow-5607417b-light.svg">
59
+ <img alt="tldraw diagram" src="assets/mdat-flow-5607417b-light.svg">
60
60
  </picture>
61
61
 
62
62
  <!-- /tldraw -->
@@ -137,7 +137,7 @@ When you're roughing out a readme, you can drop in a single opening comment, and
137
137
  <!-- title -->
138
138
  ```
139
139
 
140
- ### 3. Familiar JSON argument syntax
140
+ ### 3. Familiar JSON arguments
141
141
 
142
142
  In the rare instances when you want to pass extra data or configuration into a comment template, you just use a bit of JSON. No need to grok a custom syntax:
143
143
 
@@ -197,7 +197,7 @@ You can also treat any JSON file as a rule set. `mdat` will flatten it to allow
197
197
 
198
198
  ### 5. TypeScript native
199
199
 
200
- `mdat` exports definitions for rule types, and use of [cosmiconfig](https://github.com/cosmiconfig/cosmiconfig) allows configuration to be written in TypeScript.
200
+ `mdat` exports definitions for rule types, and configuration / rule sets may be written directly in TypeScript.
201
201
 
202
202
  ### 6. Validation
203
203
 
@@ -239,15 +239,15 @@ If no command is provided, `mdat expand` is run by default.
239
239
  Usage:
240
240
 
241
241
  ```txt
242
- mdat [command] [options]
242
+ mdat [command]
243
243
  ```
244
244
 
245
- | Command | Argument | Description |
246
- | -------- | ----------------------- | ---------------------------------------------------------- |
247
- | `expand` | `<files..>` `[options]` | Expand `mdat` placeholder comments. _(Default command.)_ |
248
- | `check` | `<files..>` `[options]` | Validate a markdown file with `mdat` placeholder comments. |
249
- | `clean` | `<files..>` `[options]` | Collapse `mdat` placeholder comments. |
250
- | `readme` | `[command]` `[options]` | Work with `mdat` comments in your readme.md. |
245
+ | Command | Argument | Description |
246
+ | ---------- | ----------------------- | ---------------------------------------------------------- |
247
+ | `expand` | `<files..>` `[options]` | Expand `mdat` placeholder comments. _(Default command.)_ |
248
+ | `check` | `<files..>` `[options]` | Validate a markdown file with `mdat` placeholder comments. |
249
+ | `collapse` | `<files..>` `[options]` | Collapse `mdat` placeholder comments. |
250
+ | `readme` | `[command]` | Work with `mdat` comments in your readme.md. |
251
251
 
252
252
  _See the sections below for more information on each subcommand._
253
253
 
@@ -302,14 +302,14 @@ mdat check <files..> [options]
302
302
  | `--help` | `-h` | Show help | `boolean` | |
303
303
  | `--version` | `-v` | Show version number | `boolean` | |
304
304
 
305
- #### Subcommand: `mdat clean`
305
+ #### Subcommand: `mdat collapse`
306
306
 
307
307
  Collapse `mdat` placeholder comments.
308
308
 
309
309
  Usage:
310
310
 
311
311
  ```txt
312
- mdat clean <files..> [options]
312
+ mdat collapse <files..> [options]
313
313
  ```
314
314
 
315
315
  | Positional Argument | Description | Type |
@@ -335,12 +335,12 @@ If no command is provided, `mdat readme expand` is run by default.
335
335
 
336
336
  Usage:
337
337
 
338
- | Command | Argument | Description |
339
- | --------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------- |
340
- | `readme expand` | `[options]` | Expand `mdat` comment placeholders in your readme.md using a collection of helpful built-in expansion rules. _(Default command.)_ |
341
- | `readme check` | `[options]` | Validate `mdat` placeholder comments in your readme.md. |
342
- | `readme clean` | `[options]` | Collapse `mdat` placeholder comments in your readme.md. |
343
- | `readme init` | `[options]` | Interactively create a new readme.md file with sensible `mdat` comment placeholders. |
338
+ | Command | Argument | Description |
339
+ | ----------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
340
+ | `readme expand` | `[files..]` `[options]` | Expand `mdat` comment placeholders in your readme.md using a collection of helpful built-in expansion rules. _(Default command.)_ |
341
+ | `readme check` | `[files..]` `[options]` | Validate `mdat` placeholder comments in your readme.md. |
342
+ | `readme collapse` | `[files..]` `[options]` | Collapse `mdat` placeholder comments in your readme.md. |
343
+ | `readme init` | `[options]` | Interactively create a new readme.md file with sensible `mdat` comment placeholders. |
344
344
 
345
345
  _See the sections below for more information on each subcommand._
346
346
 
@@ -351,16 +351,19 @@ Expand `mdat` comment placeholders in your readme.md using a collection of helpf
351
351
  Usage:
352
352
 
353
353
  ```txt
354
- mdat readme expand [options]
354
+ mdat readme expand [files..] [options]
355
355
  ```
356
356
 
357
+ | Positional Argument | Description | Type |
358
+ | ------------------- | ------------------------------------------------------------------------------------------------------------------------------- | -------- |
359
+ | `files` | Readme file(s) with `mdat` placeholder comments to collapse. If not provided, the closest readme.md file is used. _(Optional.)_ | `string` |
360
+
357
361
  | Option | Alias | Description | Type | Default |
358
362
  | ----------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ----------------------------------------------------------------------------- |
359
363
  | `--config` | | Path(s) to files containing mdat configs. | `array` | Configuration is loaded if found from the usual places, or defaults are used. |
360
364
  | `--rules` | `-r` | Path(s) to files containing `mdat` comment expansion rules. | `array` | |
361
365
  | `--output` | `-o` | Output file directory. | `string` | Same directory as input file. |
362
366
  | `--name` | `-n` | Output file name. | `string` | Same name as input file. Overwrites the input file. |
363
- | `--readme` | | Path to the readme.md file to expand. | `string` | The closest readme.md file is used by default. |
364
367
  | `--package` | | Path to the package.json file to use to populate the readme. | `string` | The closest package.json file is used by default. |
365
368
  | `--assets` | | Path to find and save readme-related assets. | `string` | `./assets` |
366
369
  | `--prefix` | | Require a string prefix before all comments to be considered for expansion. Useful if you have a bunch of non-`mdat` comments in your Markdown file, or if you're willing to trade some verbosity for safety. | `string` | |
@@ -377,14 +380,17 @@ Validate `mdat` placeholder comments in your readme.md.
377
380
  Usage:
378
381
 
379
382
  ```txt
380
- mdat readme check [options]
383
+ mdat readme check [files..] [options]
381
384
  ```
382
385
 
386
+ | Positional Argument | Description | Type |
387
+ | ------------------- | ------------------------------------------------------------------------------------------------------------------------------- | -------- |
388
+ | `files` | Readme file(s) with `mdat` placeholder comments to collapse. If not provided, the closest readme.md file is used. _(Optional.)_ | `string` |
389
+
383
390
  | Option | Alias | Description | Type | Default |
384
391
  | ----------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ----------------------------------------------------------------------------- |
385
392
  | `--config` | | Path(s) to files containing mdat configs. | `array` | Configuration is loaded if found from the usual places, or defaults are used. |
386
393
  | `--rules` | `-r` | Path(s) to files containing `mdat` comment expansion rules. | `array` | |
387
- | `--readme` | | Path to the readme.md file to expand. | `string` | The closest readme.md file is used by default. |
388
394
  | `--package` | | Path to the package.json file to use to populate the readme. | `string` | The closest package.json file is used by default. |
389
395
  | `--assets` | | Path to find and save readme-related assets. | `string` | `./assets` |
390
396
  | `--prefix` | | Require a string prefix before all comments to be considered for expansion. Useful if you have a bunch of non-`mdat` comments in your Markdown file, or if you're willing to trade some verbosity for safety. | `string` | |
@@ -393,23 +399,26 @@ mdat readme check [options]
393
399
  | `--help` | `-h` | Show help | `boolean` | |
394
400
  | `--version` | `-v` | Show version number | `boolean` | |
395
401
 
396
- #### Subcommand: `mdat readme clean`
402
+ #### Subcommand: `mdat readme collapse`
397
403
 
398
404
  Collapse `mdat` placeholder comments in your readme.md.
399
405
 
400
406
  Usage:
401
407
 
402
408
  ```txt
403
- mdat readme clean [options]
409
+ mdat readme collapse [files..] [options]
404
410
  ```
405
411
 
412
+ | Positional Argument | Description | Type |
413
+ | ------------------- | ------------------------------------------------------------------------------------------------------------------------------- | -------- |
414
+ | `files` | Readme file(s) with `mdat` placeholder comments to collapse. If not provided, the closest readme.md file is used. _(Optional.)_ | `string` |
415
+
406
416
  | Option | Alias | Description | Type | Default |
407
417
  | ----------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ----------------------------------------------------------------------------- |
408
418
  | `--output` | `-o` | Output file directory. | `string` | Same directory as input file. |
409
419
  | `--name` | `-n` | Output file name. | `string` | Same name as input file. Overwrites the input file. |
410
420
  | `--print` | | Print the expanded Markdown to stdout instead of saving to a file. Ignores `--output` and `--name` options. | `boolean` | |
411
421
  | `--config` | | Path(s) to files containing mdat configs. | `array` | Configuration is loaded if found from the usual places, or defaults are used. |
412
- | `--readme` | | Path to the readme.md file to expand. | `string` | The closest readme.md file is used by default. |
413
422
  | `--prefix` | | Require a string prefix before all comments to be considered for expansion. Useful if you have a bunch of non-`mdat` comments in your Markdown file, or if you're willing to trade some verbosity for safety. | `string` | |
414
423
  | `--verbose` | | Enable verbose logging. All verbose logs and prefixed with their log level and are printed to stderr for ease of redirection. | `boolean` | |
415
424
  | `--help` | `-h` | Show help | `boolean` | |
@@ -595,7 +604,6 @@ The `mdat` configuration file is a record object allowing you to customize aspec
595
604
  type Config = {
596
605
  assetsPath?: string // where asset-generating rules should store their output, defaults to './assets'
597
606
  packageFile?: string // used by readme rules, found dynamically if undefined
598
- readmeFile?: string // used by readme commands, found dynamically if undefined
599
607
  addMetaComment?: boolean // defaults to true
600
608
  closingPrefix?: string // defaults to '/'
601
609
  keywordPrefix?: string // defaults to ''
@@ -695,7 +703,7 @@ See the [Examples section](../remark-mdat/readme.md#examples) of the `remark-mda
695
703
 
696
704
  - #### `<!-- tldraw -->`
697
705
 
698
- Allows embedding [tldraw](https://www.tldraw.com) files in your readme. Accepts either a path to a local `.tldr` file, or remote [tldraw](https://www.tldraw.com) URLs.
706
+ Allows embedding [tldraw](https://www.tldraw.com) files in your readme. Accepts either a path to a local `.tldr` file, or remote tldraw URLs.
699
707
 
700
708
  Automatically generates both "light" and "dark" SVG variations of the sketch, and emits a `<picture>` element per [GitHub's guidelines](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#specifying-the-theme-an-image-is-shown-to) to present the correctly themed image based on the viewer's preferences.
701
709