mdat 0.3.2 → 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 +32 -32
- package/dist/api.d.ts +6 -15
- package/dist/config.d.ts +0 -2
- package/dist/index.d.ts +3 -2
- package/dist/index.js +24 -24
- package/dist/processors.d.ts +11 -0
- package/dist/readme/api.d.ts +8 -11
- package/dist/readme/config.d.ts +8 -0
- package/dist/readme/utilities.d.ts +10 -0
- package/dist/utilities.d.ts +1 -10
- package/package.json +2 -2
- package/readme.md +34 -26
package/bin/cli.js
CHANGED
|
@@ -1,37 +1,37 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{defaultLoaders as
|
|
3
|
-
${JSON.stringify(t,void 0,2)}`)}function
|
|
4
|
-
${JSON.stringify(t,void 0,2)}`)}var
|
|
5
|
-
`)},order:3,required:!1}};import{globby as
|
|
6
|
-
${
|
|
7
|
-
\`\`\``),t.commands=(
|
|
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(`[](https://npmjs.com/package/${i})`);let{license:s}=o;if(s!==void 0&&n.push(`[](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(`[](${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``},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&&
|
|
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
|
|
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
|
|
14
|
-
`;return i}function
|
|
15
|
-
${
|
|
16
|
-
`)}if(
|
|
17
|
-
`);let i;try{let
|
|
18
|
-
${
|
|
19
|
-
|
|
20
|
-
${r}`}return i}function
|
|
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
|
|
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
|
|
25
|
-
[Issues](${e}) and pull requests are welcome.`},order:15,required:!0}};var ie={license:{async content(){let t=await
|
|
26
|
-
[${
|
|
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[
|
|
30
|
-
`)},order:6}};import{tldrawToImage as
|
|
31
|
-
<source media="(prefers-color-scheme: dark)" srcset="${b.relative(
|
|
32
|
-
<source media="(prefers-color-scheme: light)" srcset="${
|
|
33
|
-
<img alt="${
|
|
34
|
-
</picture>`}async function
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
-
|
|
14
|
-
|
|
15
|
-
export declare function
|
|
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 {
|
|
1
|
+
export { checkFiles, checkString, collapseFiles, collapseString, expandFiles, expandString, } from './api';
|
|
2
2
|
export { type Config, loadConfig } from './config';
|
|
3
|
-
export {
|
|
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
|
|
2
|
-
${JSON.stringify(t,void 0,2)}`)}function
|
|
3
|
-
${JSON.stringify(t,void 0,2)}`)}var
|
|
4
|
-
`)},order:3,required:!1}};import{globby as
|
|
5
|
-
${
|
|
6
|
-
\`\`\``),t.commands=(
|
|
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(`[](https://npmjs.com/package/${r})`);let{license:s}=n;if(s!==void 0&&o.push(`[](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(`[](${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``},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(
|
|
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
|
|
11
|
-
`,
|
|
12
|
-
`;for(let o of e)
|
|
13
|
-
`;return
|
|
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
|
|
17
|
-
${o.message}`),
|
|
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
|
-
${
|
|
19
|
+
${i}`}return r}function Bt(t){return`\`\`\`txt
|
|
20
20
|
${t}
|
|
21
|
-
\`\`\``}import{isExecutable as
|
|
22
|
-
${
|
|
23
|
-
\`\`\``}}};var
|
|
24
|
-
[Issues](${e}) and pull requests are welcome.`},order:15,required:!0}};var
|
|
25
|
-
[${n}](license.txt) \xA9 ${e.name}`},order:16,required:!0}};import{getSoleRule as
|
|
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,
|
|
29
|
-
`)},order:6}};import{tldrawToImage as
|
|
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="${
|
|
32
|
-
<img alt="${n}" src="${
|
|
33
|
-
</picture>`}async function
|
|
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 {};
|
package/dist/readme/api.d.ts
CHANGED
|
@@ -1,13 +1,10 @@
|
|
|
1
|
-
import { type
|
|
2
|
-
import { type Simplify } from 'type-fest';
|
|
1
|
+
import { type ConfigToLoad, type RulesToLoad } from '../config';
|
|
3
2
|
import { type VFile } from 'vfile';
|
|
4
|
-
|
|
5
|
-
|
|
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
|
|
11
|
-
|
|
12
|
-
export declare function
|
|
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>;
|
package/dist/utilities.d.ts
CHANGED
|
@@ -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
|
+
"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.
|
|
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
|
|
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)
|
|
@@ -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
|
|
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
|
|
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]
|
|
242
|
+
mdat [command]
|
|
243
243
|
```
|
|
244
244
|
|
|
245
|
-
| Command
|
|
246
|
-
|
|
|
247
|
-
| `expand`
|
|
248
|
-
| `check`
|
|
249
|
-
| `
|
|
250
|
-
| `readme`
|
|
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
|
|
305
|
+
#### Subcommand: `mdat collapse`
|
|
306
306
|
|
|
307
307
|
Collapse `mdat` placeholder comments.
|
|
308
308
|
|
|
309
309
|
Usage:
|
|
310
310
|
|
|
311
311
|
```txt
|
|
312
|
-
mdat
|
|
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
|
|
339
|
-
|
|
|
340
|
-
| `readme expand`
|
|
341
|
-
| `readme check`
|
|
342
|
-
| `readme
|
|
343
|
-
| `readme init`
|
|
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
|
|
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
|
|
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 ''
|