mdat 0.6.1 → 0.6.3
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 +3 -3
- package/dist/index.js +2 -2
- package/package.json +2 -2
- package/readme.md +5 -5
package/bin/cli.js
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
import{defaultLoaders as vn}from"cosmiconfig";function xe(t,e){let n=vn[".json"],o=n(t,e);return ht(o)}function ht(t,e="",n={}){for(let[o,i]of Object.entries(t)){let r=e?`${e}.${o}`:o;typeof i=="object"&&i!==null&&!Array.isArray(i)?ht(i,r,n):i===null?n[r]="null":n[r]=i.toString()}return n}import Tn from"node:fs";import O from"node:path";import{packageUp as $n}from"package-up";import{isFileSync as yt}from"path-type";import Nn from"untildify";function An(t,e){let n=e===0?1:Math.floor(Math.log10(Math.abs(e))+1);return t.toString().padStart(n,"0")}function bt(t,e,n,o){let i=[];for(let[r,a]of t.entries()){let s=n&&t.length>1?`-${An(r+1,t.length+1)}`:"",d=_n(a,e,n,o,s);i.push(d)}return i}function _n(t,e,n,o,i=""){let r=wt(t),a=e?wt(e):void 0;if(!yt(r))throw new Error(`Input file not found: "${r}"`);if(a){if(yt(a))throw new Error(`Output path must be a directory, received a file path: "${a}"`);Tn.mkdirSync(a,{recursive:!0})}let s=n?O.basename(n,O.extname(n)):O.basename(r,O.extname(r)),d=`.${o??(n&&O.extname(n)!==""?O.extname(n):O.extname(t)===""?"":O.extname(t))}`,m=`${s}${i}${d}`,c=a??O.dirname(r);return{input:r,name:m,output:c}}function wt(t){return Nn(t)}async function X(){return $n()}function Q(t){return t==null?[]:Array.isArray(t)?t:[t]}import Ct from"chalk";import{cosmiconfig as Pt}from"cosmiconfig";import In from"node:fs/promises";import St from"node:path";import Mn from"plur";import{readPackage as Dn}from"read-pkg";import{deepMergeDefined as Ee,log as b,optionsSchema as jn,rulesSchema as Fn}from"remark-mdat";import{z as Le}from"zod";var Ot=jn.merge(Le.object({assetsPath:Le.string().optional(),packageFile:Le.string().optional()})).describe("Config Extension");async function L(t){let{additionalConfig:e,additionalRules:n,searchFrom:o}=t??{},i={addMetaComment:!1,assetsPath:"./assets",closingPrefix:"/",keywordPrefix:"",metaCommentIdentifier:"+",packageFile:await X(),rules:{mdat:"Powered by the Markdown Autophagic Template system: [mdat](https://github.com/kitschpatrol/mdat)."}},r=Pt("mdat"),a=await r.search(o);if(a){let{config:s,filepath:d}=a;b.info(`Using config from "${d}"`);let m=Rt(s,Ot);m&&(i=Ee(i,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 r.load(d);if(p==null)continue;let{config:g,filepath:y}=p;b.info(`Loaded additional config from "${y}"`),m=g}else m=d;if(m===void 0)continue;b.info("Merging configuration object");let c=Rt(m,Ot);c!==void 0&&(i=Ee(i,c))}}if(n!==void 0){let s=Array.isArray(n)?n:[n],d=Pt("mdat",{loaders:{".json":xe}});for(let m of s){let c;if(typeof m=="string"){let g;if(St.basename(m).endsWith("package.json")){let M=await In.readFile(m,"utf8");g={config:xe(m,M),filepath:m}}else g=await d.load(m);if(g==null)continue;let{config:y,filepath:w}=g;b.info(`Loaded additional config from "${w}"`),c=y}else c=m;if(c===void 0)continue;b.info("Merging rules into configuration object");let p=Un(c,Fn);p!==void 0&&(i=Ee(i,p))}}if(i.rules){let s=Object.keys(i.rules).sort().map(d=>`"${Ct.bold.green(d)}"`);b.info(`Loaded ${Ct.bold(s.length)} mdat comment expansion ${Mn("rule",s.length)}:`);for(let d of s)b.info(` ${d}`)}else b.error("No rules loaded from additional configurations or rules, using default.");return ee=i,i}function Un(t,e){if(e.safeParse(t).success)return{rules:t};b.error(`Rules object has the wrong shape. Ignoring and using default configuration:
|
|
3
3
|
${JSON.stringify(t,void 0,2)}`)}function Rt(t,e){if(e.safeParse(t).success)return t;b.error(`Config object has the wrong shape. Ignoring and using default configuration:
|
|
4
4
|
${JSON.stringify(t,void 0,2)}`)}var ee;async function P(){return ee===void 0&&(b.warn("getConfig(): config was undefined"),ee??=await L()),ee}var ve;async function h(){let{packageFile:t}=await P();if(t===void 0)throw new Error("No packageFile found or set in config");if(ve??=await Dn({cwd:St.dirname(t)}),ve===void 0)throw new Error("No package.json found");return ve}import{remark as Te}from"remark";import $e from"remark-gfm";import{mdatCheck as Vn,mdatClean as kt,mdatExpand as Bn,mdatSplit as xt}from"remark-mdat";import{read as Jn}from"to-vfile";import{VFile as Ci}from"vfile";async function S(t,e,n,o,i,r,a){let s=await e({additionalConfig:r,additionalRules:a});r=s;let d=Q(t),m=bt(d,i,o,"md"),c=[],p=n(s);for(let{input:g,name:y,output:w}of m){let M=await Jn(g),Z=await p.process(M);Z.dirname=w,Z.basename=y,c.push(Z)}return c}function te(t){return Te().use({settings:{bullet:"-",emphasis:"_"}}).use($e).use(()=>async function(n,o){xt(n,o),kt(n,o,t),await Bn(n,o,t)})}function ne(t){return Te().use({settings:{bullet:"-",emphasis:"_"}}).use($e).use(()=>function(n,o){xt(n,o),kt(n,o,t)})}function oe(t){return Te().use({settings:{bullet:"-",emphasis:"_"}}).use($e).use(()=>async function(n,o){await Vn(n,o,{...t,paranoid:!1})})}async function Et(t,e,n,o,i){return S(t,L,te,e,n,o,i)}async function Lt(t,e,n,o,i){return S(t,L,oe,e,n,o,i)}async function vt(t,e,n,o,i){return S(t,L,ne,e,n,o,i)}import{z as v}from"zod";var ie={badges:{async content(t){var a;let e=v.object({custom:v.record(v.object({image:v.string(),link:v.string()})).optional(),npm:v.array(v.string()).optional()}).optional().parse(t),n=await h(),{name:o}=n,i=[];if(!n.private&&((a=n.publishConfig)==null?void 0:a.access)==="public"&&i.push(`[](https://npmjs.com/package/${o})`),(e==null?void 0:e.npm)!==void 0)for(let s of e.npm)i.push(`[](https://npmjs.com/package/${s})`);let{license:r}=n;if(r!==void 0&&i.push(`[](https://opensource.org/licenses/${r})`),(e==null?void 0:e.custom)!==void 0)for(let[s,{image:d,link:m}]of Object.entries(e.custom))i.push(`[](${m})`);return i.join(`
|
|
5
|
-
`)},order:3,required:!1}};import{globby as qn}from"globby";import re from"node:path";import{isFile as zn}from"path-type";import{readPackage as Gn}from"read-pkg";import{z as Ne}from"zod";var ae={banner:{async content(t){let e=Ne.object({alt:Ne.string().optional(),src:Ne.string().optional()}).optional().parse(t),{assetsPath:n,packageFile:o}=await P();if(o===void 0)throw new Error("No package.json found");let i=(e==null?void 0:e.src)??await Kn(n);if(i===void 0)throw new Error("Banner image not found at any typical location, consider adding something at ./assets/banner.webp");if(!Tt(i)&&!await zn(i))throw new Error(`Banner image not found at "${i}"`);let r=(e==null?void 0:e.alt)??`${(await Gn({cwd:re.dirname(o)})).name} banner`;if(r===void 0||r==="undefined banner")throw new Error("Banner image alt text not available");return``},order:2}};async function Kn(t){let{packageFile:e}=await P();if(e===void 0)throw new Error("No package.json found");let n=re.dirname(e),o=t===void 0?[".","assets","media","readme-assets","readme-media","readme","images"]:[t],i=["banner","header","logo","readme","cover","screenshot","screenshots","demo","overview","image","hero"],r=["png","gif","jpg","jpeg","svg","webp"],a=await qn(o.map(s=>re.join(n,s)),{expandDirectories:{extensions:r,files:i}});if(a.length>0)return re.relative(process.cwd(),a[0])}function Tt(t,e=!0){if(typeof t!="string")throw new TypeError("Expected a string");if(t=t.trim(),t.includes(" "))return!1;try{return new URL(t),!0}catch{return e?Tt(`https://${t}`,!1):!1}}function $t(t,e=Number.MAX_SAFE_INTEGER){var i;let n=[],o=Wn(t,e);return n.push(Yn(o)),n.push(Zn(t,o)),o.hasMultipleSubcommands&&o.canRecurse&&n.push(Xn(o.fullCommandName)),((i=o.defaultCommand)==null?void 0:i.commandName)!==void 0&&n.push(Qn(o)),n.push(eo(t,o)),t.positionals&&!o.commandsOnly&&n.push(Ae(["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&&n.push(Ae(["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(s=>`\`${s}\``).join(" "):"",`${r.description??""}${r.default?" _(Default command.)_":""}`]}))),t.options&&!o.commandsOnly&&n.push(Ae(["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}\``:""]))),o.
|
|
5
|
+
`)},order:3,required:!1}};import{globby as qn}from"globby";import re from"node:path";import{isFile as zn}from"path-type";import{readPackage as Gn}from"read-pkg";import{z as Ne}from"zod";var ae={banner:{async content(t){let e=Ne.object({alt:Ne.string().optional(),src:Ne.string().optional()}).optional().parse(t),{assetsPath:n,packageFile:o}=await P();if(o===void 0)throw new Error("No package.json found");let i=(e==null?void 0:e.src)??await Kn(n);if(i===void 0)throw new Error("Banner image not found at any typical location, consider adding something at ./assets/banner.webp");if(!Tt(i)&&!await zn(i))throw new Error(`Banner image not found at "${i}"`);let r=(e==null?void 0:e.alt)??`${(await Gn({cwd:re.dirname(o)})).name} banner`;if(r===void 0||r==="undefined banner")throw new Error("Banner image alt text not available");return``},order:2}};async function Kn(t){let{packageFile:e}=await P();if(e===void 0)throw new Error("No package.json found");let n=re.dirname(e),o=t===void 0?[".","assets","media","readme-assets","readme-media","readme","images"]:[t],i=["banner","header","logo","readme","cover","screenshot","screenshots","demo","overview","image","hero"],r=["png","gif","jpg","jpeg","svg","webp"],a=await qn(o.map(s=>re.join(n,s)),{expandDirectories:{extensions:r,files:i}});if(a.length>0)return re.relative(process.cwd(),a[0])}function Tt(t,e=!0){if(typeof t!="string")throw new TypeError("Expected a string");if(t=t.trim(),t.includes(" "))return!1;try{return new URL(t),!0}catch{return e?Tt(`https://${t}`,!1):!1}}function $t(t,e=Number.MAX_SAFE_INTEGER){var i;let n=[],o=Wn(t,e);return n.push(Yn(o)),n.push(Zn(t,o)),o.hasMultipleSubcommands&&o.canRecurse&&n.push(Xn(o.fullCommandName)),((i=o.defaultCommand)==null?void 0:i.commandName)!==void 0&&n.push(Qn(o)),n.push(eo(t,o)),t.positionals&&!o.commandsOnly&&n.push(Ae(["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&&n.push(Ae(["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(s=>`\`${s}\``).join(" "):"",`${r.description??""}${r.default?" _(Default command.)_":""}`]}))),t.options&&!o.commandsOnly&&n.push(Ae(["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}\``:""]))),o.canRecurse&&o.hasMultipleSubcommands&&n.push("_See the sections below for more information on each subcommand._"),n.join(`
|
|
6
6
|
|
|
7
|
-
`)}function Wn(t,e){var m,c;let n=t.subcommandName===void 0,o=t.commands?t.commands.length>1:!1,i=e>1,r=(m=t.commands)==null?void 0:m.find(p=>p.default),a=(c=t.commands)==null?void 0:c.find(p=>p.commandName===void 0),s=`${t.commandName}${t.subcommandName?` ${t.subcommandName}`:""}
|
|
7
|
+
`)}function Wn(t,e){var m,c;let n=t.subcommandName===void 0,o=t.commands?t.commands.length>1:!1,i=e>1,r=(m=t.commands)==null?void 0:m.find(p=>p.default),a=(c=t.commands)==null?void 0:c.find(p=>p.commandName===void 0),s=`${t.commandName}${t.subcommandName?` ${t.subcommandName}`:""}`,d=i&&o&&(r==null?void 0:r.commandName)!==void 0;return{canRecurse:i,commandsOnly:d,defaultCommand:r,fullCommandName:s,hasMultipleSubcommands:o,isTopLevel:n,topLevelCommand:a}}function Yn(t){return`#### ${t.isTopLevel?"Command":"Subcommand"}: \`${t.fullCommandName}\``}function Zn(t,e){var n,o;return e.isTopLevel&&((n=e.topLevelCommand)!=null&&n.description)?(t.commands=(o=t.commands)==null?void 0:o.filter(i=>i!==e.topLevelCommand),e.topLevelCommand.description):t.description??""}function Xn(t){return`This section lists top-level commands for \`${t}\`.`}function Qn(t){var e,n;return`If no command is provided, \`${(e=t.defaultCommand)==null?void 0:e.parentCommandName} ${(n=t.defaultCommand)==null?void 0:n.commandName}\` is run by default.`}function eo(t,e){var o;let n=(o=e.topLevelCommand)!=null&&o.arguments?` ${e.topLevelCommand.arguments.join(" ")}`:`${t.arguments?` ${t.arguments.join(" ")}`:""}`;return`Usage:
|
|
8
8
|
|
|
9
9
|
\`\`\`txt
|
|
10
10
|
${e.fullCommandName}${n}
|
|
@@ -300,4 +300,4 @@ _State anyone or anything that significantly helped with the development of your
|
|
|
300
300
|
<!-- contributing -->
|
|
301
301
|
|
|
302
302
|
<!-- license -->
|
|
303
|
-
`;var $={"Mdat Readme":{content:{compound:un,explicit:fn},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:gn,explicit:hn},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:yn,explicit:wn},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 bn,group as jo,intro as Fo,note as Cn,outro as Uo,select as pt}from"@clack/prompts";import x from"chalk";import Vo from"node:fs/promises";import Pe from"node:path";import{deepMergeDefined as Bo}from"remark-mdat";import{write as Jo}from"to-vfile";async function Pn(){let t=await ct(),e=await X();return{packageDirectory:e===void 0?void 0:Pe.dirname(Pe.resolve(e)),readmePath:t}}async function On(){let{packageDirectory:t,readmePath:e}=await Pn(),n=Pe.resolve(process.cwd());Fo(`Running ${x.bold("mdat readme init")} interactively`);let o=await jo({overwrite:async()=>e===void 0||await bn({message:`Found an existing readme at "${x.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?pt({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: "${x.blue(t)}"`,value:t},{label:`Create in current working directory: "${x.blue(n)}"`,value:n}]}):n,template:async()=>pt({message:"Which template would you like to use?",options:qo()}),compound:async()=>pt({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 ${x.green("<!-- title -->")} and ${x.green("<!-- badges -->")} in a single ${x.green("<!-- header -->")} comment.`,value:!0},{label:"No: Use individual `mdat` expansion comments for each section.",value:!1}]}),expand:async()=>t===void 0?!1:bn({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")}}),i=await lt(o);return t===void 0&&Cn("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."),Cn(`Readme created: "${x.bold.blue(i)}"`),Uo("Done!"),i}async function lt(t){let{packageDirectory:e}=await Pn(),n=Bo({compound:!0,output:e??process.cwd(),overwrite:!0,expand:e!==void 0,template:Object.keys($)[0]},t??{}),o=Ho(n.template,n.compound),i=Pe.join(n.output,"readme.md");await Vo.writeFile(i,o,"utf8");let[r]=await Ce(i);return await Jo(r),i}function Ho(t,e){let o=$[t].content[e?"compound":"explicit"];if(o===void 0||o==="")throw new Error(`No template found for "${t}"`);return o}function qo(){return Object.entries($).map(([t,e])=>({label:t,hint:e.description,value:t}))}var N={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"}},G={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"}},K={name:{alias:"n",defaultDescription:"Same name as input file. Overwrites the input file.",description:"Output file name.",type:"string"}},F={output:{alias:"o",defaultDescription:"Same directory as input file.",description:"Output file directory.",type:"string"}},A={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"}},W={print:{description:"Print the expanded Markdown to stdout instead of saving to a file. Ignores `--output` and `--name` options.",type:"boolean"}},Y={rules:{alias:"r",description:"Path(s) to files containing `mdat` comment expansion rules.",string:!0,type:"array"}},E={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"}},Oe=["files",{array:!0,demandOption:!0,describe:"Markdown file(s) with `mdat` placeholder comments to collapse.",type:"string"}];var ut={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}},ft={assets:{defaultDescription:"./assets",description:"Path to find and save readme-related assets.",string:!0}},Rn={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"}},Sn={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"}},kn={expand:{alias:"e",default:!0,description:"Automatically run `mdat readme` immediately after creating the readme template.",type:"boolean"}},xn={template:{alias:"t",choices:Object.keys($),default:Object.keys($)[0],description:"Specify a template to use for the new readme.",type:"string"}},En={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"}},Re=["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 gt from"chalk";import _ from"pretty-ms";import{getMdatReports as zo,log as u,reporterMdat as U}from"remark-mdat";import{write as Se}from"to-vfile";import Go from"yargs";import{hideBin as Ko}from"yargs/helpers";var I=performance.now(),Ln=Go(Ko(process.argv));try{await Ln.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(...Oe).option(N).option(Y).option(F).option(K).option(G).option(A).option(W).option(E),async({config:t,files:e,meta:n,name:o,output:i,prefix:r,print:a,rules:s,verbose:d})=>{u.verbose=d??!1,ke({name:o,output:i,print:a});let m=V(t,{addMetaComment:n,keywordPrefix:r}),c=await Et(e,o,i,m,s);for(let p of c)a?process.stdout.write(p.toString()):await Se(p);U(c),u.info(`Expanded comments in ${_(performance.now()-I)}.`),process.exitCode=B(c)}).command("check <files..> [options]","Validate a markdown file with `mdat` placeholder comments.",t=>t.positional(...Oe).option(N).option(Y).option(G).option(A).option(E),async({config:t,files:e,meta:n,prefix:o,rules:i,verbose:r})=>{u.verbose=r??!1;let a=V(t,{addMetaComment:n,keywordPrefix:o}),s=await Lt(e,void 0,void 0,a,i);U(s),u.info(`Checked comments in ${_(performance.now()-I)}.`),process.exitCode=B(s)}).command("collapse <files..> [options]","Collapse `mdat` placeholder comments.",t=>t.positional(...Oe).option(N).option(F).option(K).option(A).option(W).option(E),async({config:t,files:e,name:n,output:o,prefix:i,print:r,verbose:a})=>{u.verbose=a??!1,ke({name:n,output:o,print:r});let s=V(t,{keywordPrefix:i}),d=await vt(e,void 0,void 0,s);for(let m of d)r?process.stdout.write(m.toString()):await Se(m);U(d),u.info(`Cleaned comments in ${_(performance.now()-I)}.`),process.exitCode=B(d)}).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(...Re).option(N).option(Y).option(F).option(K).option(ut).option(ft).option(A).option(G).option(W).option(E),async({assets:e,config:n,files:o,meta:i,name:r,output:a,package:s,prefix:d,print:m,rules:c,verbose:p})=>{u.verbose=p??!1,ke({name:r,output:a,print:m});let g=V(n,{addMetaComment:i,assetsPath:e,keywordPrefix:d,packageFile:s}),y=await Ce(o,r,a,g,c);for(let M of y)m?process.stdout.write(M.toString()):await Se(M);U(y);let{packageFile:w}=await P();u.info(`Pulled package metadata from: ${gt.bold.blue(w)}`),u.info(`Expanded readme(s) in ${_(performance.now()-I)}.`),process.exitCode=B(y)}).command("check [files..] [options]","Validate `mdat` placeholder comments in your readme.md.",e=>e.positional(...Re).option(N).option(Y).option(ut).option(ft).option(A).option(G).option(E),async({assets:e,config:n,files:o,meta:i,package:r,prefix:a,rules:s,verbose:d})=>{u.verbose=d??!1;let m=V(n,{addMetaComment:i,assetsPath:e,keywordPrefix:a,packageFile:r}),c=await pn(o,void 0,void 0,m,s);U(c);let{packageFile:p}=await P();u.info(`Pulled package metadata from: ${gt.bold.blue(p)}`),u.info(`Checked readme(s) in ${_(performance.now()-I)}.`),process.exitCode=B(c)}).command("collapse [files..] [options]","Collapse `mdat` placeholder comments in your readme.md.",e=>e.positional(...Re).option(F).option(K).option(W).option(N).option(A).option(E),async({config:e,files:n,name:o,output:i,prefix:r,print:a,verbose:s})=>{u.verbose=s??!1,ke({name:o,output:i,print:a});let d=V(e,{keywordPrefix:r}),m=await ln(n,void 0,void 0,d);for(let c of m)a?process.stdout.write(c.toString()):await Se(c);U(m),u.info(`Cleaned readme(s) in ${_(performance.now()-I)}.`),process.exitCode=B(m)}).command("init [options]","Interactively create a new readme.md file with sensible default `mdat` comment placeholders.",e=>e.option(Rn).option(Sn).option(F).option(kn).option(xn).option(En).option(E),async({compound:e,expand:n,interactive:o,output:i,overwrite:r,template:a,verbose:s})=>{if(u.verbose=s??!1,o)await On();else{let d=await lt({compound:e,expand:n,output:i,overwrite:r,template:a});u.info(`Created readme at "${gt.blue(d)}" in ${_(performance.now()-I)}.`)}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,Ln.terminalWidth()):0).fail(!1).parse()}catch(t){t instanceof Error&&u.error(t.message),process.exitCode=1}function ke(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 V(t,e){return[...Q(t),e]}function B(t){return zo(t).reduce((o,i)=>o+i.errors.length,0)>0?1:0}
|
|
303
|
+
`;var $={"Mdat Readme":{content:{compound:un,explicit:fn},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:gn,explicit:hn},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:yn,explicit:wn},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 bn,group as jo,intro as Fo,note as Cn,outro as Uo,select as pt}from"@clack/prompts";import x from"chalk";import Vo from"node:fs/promises";import Pe from"node:path";import{deepMergeDefined as Bo}from"remark-mdat";import{write as Jo}from"to-vfile";async function Pn(){let t=await ct(),e=await X();return{packageDirectory:e===void 0?void 0:Pe.dirname(Pe.resolve(e)),readmePath:t}}async function On(){let{packageDirectory:t,readmePath:e}=await Pn(),n=Pe.resolve(process.cwd());Fo(`Running ${x.bold("mdat readme init")} interactively`);let o=await jo({overwrite:async()=>e===void 0||await bn({message:`Found an existing readme at "${x.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?pt({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: "${x.blue(t)}"`,value:t},{label:`Create in current working directory: "${x.blue(n)}"`,value:n}]}):n,template:async()=>pt({message:"Which template would you like to use?",options:qo()}),compound:async()=>pt({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 ${x.green("<!-- title -->")} and ${x.green("<!-- badges -->")} in a single ${x.green("<!-- header -->")} comment.`,value:!0},{label:"No: Use individual `mdat` expansion comments for each section.",value:!1}]}),expand:async()=>t===void 0?!1:bn({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")}}),i=await lt(o);return t===void 0&&Cn("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."),Cn(`Readme created: "${x.bold.blue(i)}"`),Uo("Done!"),i}async function lt(t){let{packageDirectory:e}=await Pn(),n=Bo({compound:!0,output:e??process.cwd(),overwrite:!0,expand:e!==void 0,template:Object.keys($)[0]},t??{}),o=Ho(n.template,n.compound),i=Pe.join(n.output,"readme.md");await Vo.writeFile(i,o,"utf8");let[r]=await Ce(i);return await Jo(r),i}function Ho(t,e){let o=$[t].content[e?"compound":"explicit"];if(o===void 0||o==="")throw new Error(`No template found for "${t}"`);return o}function qo(){return Object.entries($).map(([t,e])=>({label:t,hint:e.description,value:t}))}var N={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"}},G={meta:{alias:"m",description:"Embed an extra comment at the top of the generated Markdown warning editors that certain sections of the document have been generated dynamically.",type:"boolean"}},K={name:{alias:"n",defaultDescription:"Same name as input file. Overwrites the input file.",description:"Output file name.",type:"string"}},F={output:{alias:"o",defaultDescription:"Same directory as input file.",description:"Output file directory.",type:"string"}},A={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"}},W={print:{description:"Print the expanded Markdown to stdout instead of saving to a file. Ignores `--output` and `--name` options.",type:"boolean"}},Y={rules:{alias:"r",description:"Path(s) to files containing `mdat` comment expansion rules.",string:!0,type:"array"}},E={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"}},Oe=["files",{array:!0,demandOption:!0,describe:"Markdown file(s) with `mdat` placeholder comments to collapse.",type:"string"}];var ut={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}},ft={assets:{defaultDescription:"./assets",description:"Path to find and save readme-related assets.",string:!0}},Rn={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"}},Sn={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"}},kn={expand:{alias:"e",default:!0,description:"Automatically run `mdat readme` immediately after creating the readme template.",type:"boolean"}},xn={template:{alias:"t",choices:Object.keys($),default:Object.keys($)[0],description:"Specify a template to use for the new readme.",type:"string"}},En={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"}},Re=["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 gt from"chalk";import _ from"pretty-ms";import{getMdatReports as zo,log as u,reporterMdat as U}from"remark-mdat";import{write as Se}from"to-vfile";import Go from"yargs";import{hideBin as Ko}from"yargs/helpers";var I=performance.now(),Ln=Go(Ko(process.argv));try{await Ln.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(...Oe).option(N).option(Y).option(F).option(K).option(G).option(A).option(W).option(E),async({config:t,files:e,meta:n,name:o,output:i,prefix:r,print:a,rules:s,verbose:d})=>{u.verbose=d??!1,ke({name:o,output:i,print:a});let m=V(t,{addMetaComment:n,keywordPrefix:r}),c=await Et(e,o,i,m,s);for(let p of c)a?process.stdout.write(p.toString()):await Se(p);U(c),u.info(`Expanded comments in ${_(performance.now()-I)}.`),process.exitCode=B(c)}).command("check <files..> [options]","Validate a markdown file with `mdat` placeholder comments.",t=>t.positional(...Oe).option(N).option(Y).option(G).option(A).option(E),async({config:t,files:e,meta:n,prefix:o,rules:i,verbose:r})=>{u.verbose=r??!1;let a=V(t,{addMetaComment:n,keywordPrefix:o}),s=await Lt(e,void 0,void 0,a,i);U(s),u.info(`Checked comments in ${_(performance.now()-I)}.`),process.exitCode=B(s)}).command("collapse <files..> [options]","Collapse `mdat` placeholder comments.",t=>t.positional(...Oe).option(N).option(F).option(K).option(A).option(W).option(E),async({config:t,files:e,name:n,output:o,prefix:i,print:r,verbose:a})=>{u.verbose=a??!1,ke({name:n,output:o,print:r});let s=V(t,{keywordPrefix:i}),d=await vt(e,void 0,void 0,s);for(let m of d)r?process.stdout.write(m.toString()):await Se(m);U(d),u.info(`Cleaned comments in ${_(performance.now()-I)}.`),process.exitCode=B(d)}).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(...Re).option(N).option(Y).option(F).option(K).option(ut).option(ft).option(A).option(G).option(W).option(E),async({assets:e,config:n,files:o,meta:i,name:r,output:a,package:s,prefix:d,print:m,rules:c,verbose:p})=>{u.verbose=p??!1,ke({name:r,output:a,print:m});let g=V(n,{addMetaComment:i,assetsPath:e,keywordPrefix:d,packageFile:s}),y=await Ce(o,r,a,g,c);for(let M of y)m?process.stdout.write(M.toString()):await Se(M);U(y);let{packageFile:w}=await P();u.info(`Pulled package metadata from: ${gt.bold.blue(w)}`),u.info(`Expanded readme(s) in ${_(performance.now()-I)}.`),process.exitCode=B(y)}).command("check [files..] [options]","Validate `mdat` placeholder comments in your readme.md.",e=>e.positional(...Re).option(N).option(Y).option(ut).option(ft).option(A).option(G).option(E),async({assets:e,config:n,files:o,meta:i,package:r,prefix:a,rules:s,verbose:d})=>{u.verbose=d??!1;let m=V(n,{addMetaComment:i,assetsPath:e,keywordPrefix:a,packageFile:r}),c=await pn(o,void 0,void 0,m,s);U(c);let{packageFile:p}=await P();u.info(`Pulled package metadata from: ${gt.bold.blue(p)}`),u.info(`Checked readme(s) in ${_(performance.now()-I)}.`),process.exitCode=B(c)}).command("collapse [files..] [options]","Collapse `mdat` placeholder comments in your readme.md.",e=>e.positional(...Re).option(F).option(K).option(W).option(N).option(A).option(E),async({config:e,files:n,name:o,output:i,prefix:r,print:a,verbose:s})=>{u.verbose=s??!1,ke({name:o,output:i,print:a});let d=V(e,{keywordPrefix:r}),m=await ln(n,void 0,void 0,d);for(let c of m)a?process.stdout.write(c.toString()):await Se(c);U(m),u.info(`Cleaned readme(s) in ${_(performance.now()-I)}.`),process.exitCode=B(m)}).command("init [options]","Interactively create a new readme.md file with sensible default `mdat` comment placeholders.",e=>e.option(Rn).option(Sn).option(F).option(kn).option(xn).option(En).option(E),async({compound:e,expand:n,interactive:o,output:i,overwrite:r,template:a,verbose:s})=>{if(u.verbose=s??!1,o)await On();else{let d=await lt({compound:e,expand:n,output:i,overwrite:r,template:a});u.info(`Created readme at "${gt.blue(d)}" in ${_(performance.now()-I)}.`)}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,Ln.terminalWidth()):0).fail(!1).parse()}catch(t){t instanceof Error&&u.error(t.message),process.exitCode=1}function ke(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 V(t,e){return[...Q(t),e]}function B(t){return zo(t).reduce((o,i)=>o+i.errors.length,0)>0?1:0}
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import{defaultLoaders as Ft}from"cosmiconfig";function re(t,e){let n=Ft[".json"],o=n(t,e);return Ve(o)}function Ve(t,e="",n={}){for(let[o,r]of Object.entries(t)){let i=e?`${e}.${o}`:o;typeof r=="object"&&r!==null&&!Array.isArray(r)?Ve(r,i,n):r===null?n[i]="null":n[i]=r.toString()}return n}import jt from"node:fs";import P from"node:path";import{packageUp as Dt}from"package-up";import{isFileSync as Je}from"path-type";import Ut from"untildify";function vt(t,e){let n=e===0?1:Math.floor(Math.log10(Math.abs(e))+1);return t.toString().padStart(n,"0")}function He(t,e,n,o){let r=[];for(let[i,s]of t.entries()){let a=n&&t.length>1?`-${vt(i+1,t.length+1)}`:"",d=It(s,e,n,o,a);r.push(d)}return r}function It(t,e,n,o,r=""){let i=Be(t),s=e?Be(e):void 0;if(!Je(i))throw new Error(`Input file not found: "${i}"`);if(s){if(Je(s))throw new Error(`Output path must be a directory, received a file path: "${s}"`);jt.mkdirSync(s,{recursive:!0})}let a=n?P.basename(n,P.extname(n)):P.basename(i,P.extname(i)),d=`.${o??(n&&P.extname(n)!==""?P.extname(n):P.extname(t)===""?"":P.extname(t))}`,m=`${a}${r}${d}`,p=s??P.dirname(i);return{input:i,name:m,output:p}}function Be(t){return Ut(t)}async function ze(){return Dt()}function qe(t){return t==null?[]:Array.isArray(t)?t:[t]}import Ke from"chalk";import{cosmiconfig as Ge}from"cosmiconfig";import _t from"node:fs/promises";import Ze from"node:path";import Vt from"plur";import{readPackage as Jt}from"read-pkg";import{deepMergeDefined as _,log as h,optionsSchema as Bt,rulesSchema as Ht}from"remark-mdat";import{z as ie}from"zod";var Ye=Bt.merge(ie.object({assetsPath:ie.string().optional(),packageFile:ie.string().optional()})).describe("Config Extension");async function y(t){let{additionalConfig:e,additionalRules:n,searchFrom:o}=t??{},r={addMetaComment:!1,assetsPath:"./assets",closingPrefix:"/",keywordPrefix:"",metaCommentIdentifier:"+",packageFile:await ze(),rules:{mdat:"Powered by the Markdown Autophagic Template system: [mdat](https://github.com/kitschpatrol/mdat)."}},i=Ge("mdat"),s=await i.search(o);if(s){let{config:a,filepath:d}=s;h.info(`Using config from "${d}"`);let m=We(a,Ye);m&&(r=_(r,m))}if(e!==void 0){let a=Array.isArray(e)?e:[e];for(let d of a){let m;if(typeof d=="string"){let f=await i.load(d);if(f==null)continue;let{config:g,filepath:L}=f;h.info(`Loaded additional config from "${L}"`),m=g}else m=d;if(m===void 0)continue;h.info("Merging configuration object");let p=We(m,Ye);p!==void 0&&(r=_(r,p))}}if(n!==void 0){let a=Array.isArray(n)?n:[n],d=Ge("mdat",{loaders:{".json":re}});for(let m of a){let p;if(typeof m=="string"){let g;if(Ze.basename(m).endsWith("package.json")){let oe=await _t.readFile(m,"utf8");g={config:re(m,oe),filepath:m}}else g=await d.load(m);if(g==null)continue;let{config:L,filepath:w}=g;h.info(`Loaded additional config from "${w}"`),p=L}else p=m;if(p===void 0)continue;h.info("Merging rules into configuration object");let f=zt(p,Ht);f!==void 0&&(r=_(r,f))}}if(r.rules){let a=Object.keys(r.rules).sort().map(d=>`"${Ke.bold.green(d)}"`);h.info(`Loaded ${Ke.bold(a.length)} mdat comment expansion ${Vt("rule",a.length)}:`);for(let d of a)h.info(` ${d}`)}else h.error("No rules loaded from additional configurations or rules, using default.");return V=r,r}function zt(t,e){if(e.safeParse(t).success)return{rules:t};h.error(`Rules object has the wrong shape. Ignoring and using default configuration:
|
|
2
2
|
${JSON.stringify(t,void 0,2)}`)}function We(t,e){if(e.safeParse(t).success)return t;h.error(`Config object has the wrong shape. Ignoring and using default configuration:
|
|
3
3
|
${JSON.stringify(t,void 0,2)}`)}var V;async function b(){return V===void 0&&(h.warn("getConfig(): config was undefined"),V??=await y()),V}var se;async function l(){let{packageFile:t}=await b();if(t===void 0)throw new Error("No packageFile found or set in config");if(se??=await Jt({cwd:Ze.dirname(t)}),se===void 0)throw new Error("No package.json found");return se}function qt(t,e){return _(t,e)}import{remark as ae}from"remark";import me from"remark-gfm";import{mdatCheck as Kt,mdatClean as Xe,mdatExpand as Gt,mdatSplit as Qe}from"remark-mdat";import{read as Yt}from"to-vfile";import{VFile as Wt}from"vfile";async function E(t,e,n,o,r,i,s){let a=await e({additionalConfig:i,additionalRules:s});i=a;let d=qe(t),m=He(d,r,o,"md"),p=[],f=n(a);for(let{input:g,name:L,output:w}of m){let oe=await Yt(g),I=await f.process(oe);I.dirname=w,I.basename=L,p.push(I)}return p}async function O(t,e,n,o,r){let i=await e({additionalConfig:o,additionalRules:r});return o=i,n(i).process(new Wt(t))}function $(t){return ae().use({settings:{bullet:"-",emphasis:"_"}}).use(me).use(()=>async function(n,o){Qe(n,o),Xe(n,o,t),await Gt(n,o,t)})}function F(t){return ae().use({settings:{bullet:"-",emphasis:"_"}}).use(me).use(()=>function(n,o){Qe(n,o),Xe(n,o,t)})}function x(t){return ae().use({settings:{bullet:"-",emphasis:"_"}}).use(me).use(()=>async function(n,o){await Kt(n,o,{...t,paranoid:!1})})}async function Zt(t,e,n,o,r){return E(t,y,$,e,n,o,r)}async function Xt(t,e,n){return O(t,y,$,e,n)}async function Qt(t,e,n,o,r){return E(t,y,x,e,n,o,r)}async function en(t,e,n){return O(t,y,x,e,n)}async function tn(t,e,n,o,r){return E(t,y,F,e,n,o,r)}async function nn(t,e,n){return O(t,y,F,e,n)}import{z as k}from"zod";var J={badges:{async content(t){var s;let e=k.object({custom:k.record(k.object({image:k.string(),link:k.string()})).optional(),npm:k.array(k.string()).optional()}).optional().parse(t),n=await l(),{name:o}=n,r=[];if(!n.private&&((s=n.publishConfig)==null?void 0:s.access)==="public"&&r.push(`[](https://npmjs.com/package/${o})`),(e==null?void 0:e.npm)!==void 0)for(let a of e.npm)r.push(`[](https://npmjs.com/package/${a})`);let{license:i}=n;if(i!==void 0&&r.push(`[](https://opensource.org/licenses/${i})`),(e==null?void 0:e.custom)!==void 0)for(let[a,{image:d,link:m}]of Object.entries(e.custom))r.push(`[](${m})`);return r.join(`
|
|
4
|
-
`)},order:3,required:!1}};import{globby as on}from"globby";import B from"node:path";import{isFile as rn}from"path-type";import{readPackage as sn}from"read-pkg";import{z as de}from"zod";var H={banner:{async content(t){let e=de.object({alt:de.string().optional(),src:de.string().optional()}).optional().parse(t),{assetsPath:n,packageFile:o}=await b();if(o===void 0)throw new Error("No package.json found");let r=(e==null?void 0:e.src)??await an(n);if(r===void 0)throw new Error("Banner image not found at any typical location, consider adding something at ./assets/banner.webp");if(!et(r)&&!await rn(r))throw new Error(`Banner image not found at "${r}"`);let i=(e==null?void 0:e.alt)??`${(await sn({cwd:B.dirname(o)})).name} banner`;if(i===void 0||i==="undefined banner")throw new Error("Banner image alt text not available");return``},order:2}};async function an(t){let{packageFile:e}=await b();if(e===void 0)throw new Error("No package.json found");let n=B.dirname(e),o=t===void 0?[".","assets","media","readme-assets","readme-media","readme","images"]:[t],r=["banner","header","logo","readme","cover","screenshot","screenshots","demo","overview","image","hero"],i=["png","gif","jpg","jpeg","svg","webp"],s=await on(o.map(a=>B.join(n,a)),{expandDirectories:{extensions:i,files:r}});if(s.length>0)return B.relative(process.cwd(),s[0])}function et(t,e=!0){if(typeof t!="string")throw new TypeError("Expected a string");if(t=t.trim(),t.includes(" "))return!1;try{return new URL(t),!0}catch{return e?et(`https://${t}`,!1):!1}}function tt(t,e=Number.MAX_SAFE_INTEGER){var r;let n=[],o=mn(t,e);return n.push(dn(o)),n.push(cn(t,o)),o.hasMultipleSubcommands&&o.canRecurse&&n.push(pn(o.fullCommandName)),((r=o.defaultCommand)==null?void 0:r.commandName)!==void 0&&n.push(fn(o)),n.push(un(t,o)),t.positionals&&!o.commandsOnly&&n.push(ce(["Positional Argument","Description","Type","Default"],t.positionals.map(i=>[i.arguments?[i.arguments.map(s=>`\`${s}\``)].join(" "):"",`${i.description??""}${i.required?" _(Required.)_":" _(Optional.)_"}`,i.type?`\`${i.type}\``:"",i.defaultValue?i.defaultValue.includes(" ")?i.defaultValue:`\`${i.defaultValue}\``:""]))),t.commands&&n.push(ce(["Command","Argument","Description"],t.commands.map(i=>{var s;return[`\`${i.commandName??(i.default?"[default]":"")}\``,i.arguments?(s=i.arguments)==null?void 0:s.map(a=>`\`${a}\``).join(" "):"",`${i.description??""}${i.default?" _(Default command.)_":""}`]}))),t.options&&!o.commandsOnly&&n.push(ce(["Option","Alias","Argument","Description","Type","Default"],t.options.map(i=>[i.flags?i.flags.map(s=>`\`${s}\``).join(" "):"",i.aliases?i.aliases.map(s=>`\`${s}\``).join(" "):"",i.arguments?i.arguments.map(s=>`\`${s}\``).join(" "):"",i.description??"",i.type?`\`${i.type}\``:"",i.defaultValue?i.defaultValue.includes(" ")?i.defaultValue:`\`${i.defaultValue}\``:""]))),o.
|
|
4
|
+
`)},order:3,required:!1}};import{globby as on}from"globby";import B from"node:path";import{isFile as rn}from"path-type";import{readPackage as sn}from"read-pkg";import{z as de}from"zod";var H={banner:{async content(t){let e=de.object({alt:de.string().optional(),src:de.string().optional()}).optional().parse(t),{assetsPath:n,packageFile:o}=await b();if(o===void 0)throw new Error("No package.json found");let r=(e==null?void 0:e.src)??await an(n);if(r===void 0)throw new Error("Banner image not found at any typical location, consider adding something at ./assets/banner.webp");if(!et(r)&&!await rn(r))throw new Error(`Banner image not found at "${r}"`);let i=(e==null?void 0:e.alt)??`${(await sn({cwd:B.dirname(o)})).name} banner`;if(i===void 0||i==="undefined banner")throw new Error("Banner image alt text not available");return``},order:2}};async function an(t){let{packageFile:e}=await b();if(e===void 0)throw new Error("No package.json found");let n=B.dirname(e),o=t===void 0?[".","assets","media","readme-assets","readme-media","readme","images"]:[t],r=["banner","header","logo","readme","cover","screenshot","screenshots","demo","overview","image","hero"],i=["png","gif","jpg","jpeg","svg","webp"],s=await on(o.map(a=>B.join(n,a)),{expandDirectories:{extensions:i,files:r}});if(s.length>0)return B.relative(process.cwd(),s[0])}function et(t,e=!0){if(typeof t!="string")throw new TypeError("Expected a string");if(t=t.trim(),t.includes(" "))return!1;try{return new URL(t),!0}catch{return e?et(`https://${t}`,!1):!1}}function tt(t,e=Number.MAX_SAFE_INTEGER){var r;let n=[],o=mn(t,e);return n.push(dn(o)),n.push(cn(t,o)),o.hasMultipleSubcommands&&o.canRecurse&&n.push(pn(o.fullCommandName)),((r=o.defaultCommand)==null?void 0:r.commandName)!==void 0&&n.push(fn(o)),n.push(un(t,o)),t.positionals&&!o.commandsOnly&&n.push(ce(["Positional Argument","Description","Type","Default"],t.positionals.map(i=>[i.arguments?[i.arguments.map(s=>`\`${s}\``)].join(" "):"",`${i.description??""}${i.required?" _(Required.)_":" _(Optional.)_"}`,i.type?`\`${i.type}\``:"",i.defaultValue?i.defaultValue.includes(" ")?i.defaultValue:`\`${i.defaultValue}\``:""]))),t.commands&&n.push(ce(["Command","Argument","Description"],t.commands.map(i=>{var s;return[`\`${i.commandName??(i.default?"[default]":"")}\``,i.arguments?(s=i.arguments)==null?void 0:s.map(a=>`\`${a}\``).join(" "):"",`${i.description??""}${i.default?" _(Default command.)_":""}`]}))),t.options&&!o.commandsOnly&&n.push(ce(["Option","Alias","Argument","Description","Type","Default"],t.options.map(i=>[i.flags?i.flags.map(s=>`\`${s}\``).join(" "):"",i.aliases?i.aliases.map(s=>`\`${s}\``).join(" "):"",i.arguments?i.arguments.map(s=>`\`${s}\``).join(" "):"",i.description??"",i.type?`\`${i.type}\``:"",i.defaultValue?i.defaultValue.includes(" ")?i.defaultValue:`\`${i.defaultValue}\``:""]))),o.canRecurse&&o.hasMultipleSubcommands&&n.push("_See the sections below for more information on each subcommand._"),n.join(`
|
|
5
5
|
|
|
6
|
-
`)}function mn(t,e){var m,p;let n=t.subcommandName===void 0,o=t.commands?t.commands.length>1:!1,r=e>1,i=(m=t.commands)==null?void 0:m.find(f=>f.default),s=(p=t.commands)==null?void 0:p.find(f=>f.commandName===void 0),a=`${t.commandName}${t.subcommandName?` ${t.subcommandName}`:""}
|
|
6
|
+
`)}function mn(t,e){var m,p;let n=t.subcommandName===void 0,o=t.commands?t.commands.length>1:!1,r=e>1,i=(m=t.commands)==null?void 0:m.find(f=>f.default),s=(p=t.commands)==null?void 0:p.find(f=>f.commandName===void 0),a=`${t.commandName}${t.subcommandName?` ${t.subcommandName}`:""}`,d=r&&o&&(i==null?void 0:i.commandName)!==void 0;return{canRecurse:r,commandsOnly:d,defaultCommand:i,fullCommandName:a,hasMultipleSubcommands:o,isTopLevel:n,topLevelCommand:s}}function dn(t){return`#### ${t.isTopLevel?"Command":"Subcommand"}: \`${t.fullCommandName}\``}function cn(t,e){var n,o;return e.isTopLevel&&((n=e.topLevelCommand)!=null&&n.description)?(t.commands=(o=t.commands)==null?void 0:o.filter(r=>r!==e.topLevelCommand),e.topLevelCommand.description):t.description??""}function pn(t){return`This section lists top-level commands for \`${t}\`.`}function fn(t){var e,n;return`If no command is provided, \`${(e=t.defaultCommand)==null?void 0:e.parentCommandName} ${(n=t.defaultCommand)==null?void 0:n.commandName}\` is run by default.`}function un(t,e){var o;let n=(o=e.topLevelCommand)!=null&&o.arguments?` ${e.topLevelCommand.arguments.join(" ")}`:`${t.arguments?` ${t.arguments.join(" ")}`:""}`;return`Usage:
|
|
7
7
|
|
|
8
8
|
\`\`\`txt
|
|
9
9
|
${e.fullCommandName}${n}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mdat",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.3",
|
|
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.6.
|
|
73
|
+
"remark-mdat": "0.6.3"
|
|
74
74
|
},
|
|
75
75
|
"devDependencies": {
|
|
76
76
|
"@types/node": "^20.11.19",
|
package/readme.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
<!--+ Warning: Content
|
|
1
|
+
<!--+ Warning: Content inside HTML comment blocks was generated by mdat and may be overwritten. +-->
|
|
2
2
|
|
|
3
3
|
<!-- header -->
|
|
4
4
|
|
|
@@ -261,7 +261,7 @@ mdat expand <files..> [options]
|
|
|
261
261
|
| `--rules` | `-r` | Path(s) to files containing `mdat` comment expansion rules. | `array` | |
|
|
262
262
|
| `--output` | `-o` | Output file directory. | `string` | Same directory as input file. |
|
|
263
263
|
| `--name` | `-n` | Output file name. | `string` | Same name as input file. Overwrites the input file. |
|
|
264
|
-
| `--meta` | `-m` | Embed an extra comment at the top of the generated Markdown
|
|
264
|
+
| `--meta` | `-m` | Embed an extra comment at the top of the generated Markdown warning editors that certain sections of the document have been generated dynamically. | `boolean` | |
|
|
265
265
|
| `--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` | |
|
|
266
266
|
| `--print` | | Print the expanded Markdown to stdout instead of saving to a file. Ignores `--output` and `--name` options. | `boolean` | |
|
|
267
267
|
| `--verbose` | | Enable verbose logging. All verbose logs and prefixed with their log level and are printed to stderr for ease of redirection. | `boolean` | |
|
|
@@ -286,7 +286,7 @@ mdat check <files..> [options]
|
|
|
286
286
|
| ----------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | ----------------------------------------------------------------------------- |
|
|
287
287
|
| `--config` | | Path(s) to files containing mdat configs. | `array` | Configuration is loaded if found from the usual places, or defaults are used. |
|
|
288
288
|
| `--rules` | `-r` | Path(s) to files containing `mdat` comment expansion rules. | `array` | |
|
|
289
|
-
| `--meta` | `-m` | Embed an extra comment at the top of the generated Markdown
|
|
289
|
+
| `--meta` | `-m` | Embed an extra comment at the top of the generated Markdown warning editors that certain sections of the document have been generated dynamically. | `boolean` | |
|
|
290
290
|
| `--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` | |
|
|
291
291
|
| `--verbose` | | Enable verbose logging. All verbose logs and prefixed with their log level and are printed to stderr for ease of redirection. | `boolean` | |
|
|
292
292
|
| `--help` | `-h` | Show help | `boolean` | |
|
|
@@ -363,7 +363,7 @@ mdat readme expand [files..] [options]
|
|
|
363
363
|
| `--package` | | Path to the package.json file to use to populate the readme. | `string` | The closest package.json file is used by default. |
|
|
364
364
|
| `--assets` | | Path to find and save readme-related assets. | `string` | `./assets` |
|
|
365
365
|
| `--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` | |
|
|
366
|
-
| `--meta` | `-m` | Embed an extra comment at the top of the generated Markdown
|
|
366
|
+
| `--meta` | `-m` | Embed an extra comment at the top of the generated Markdown warning editors that certain sections of the document have been generated dynamically. | `boolean` | |
|
|
367
367
|
| `--print` | | Print the expanded Markdown to stdout instead of saving to a file. Ignores `--output` and `--name` options. | `boolean` | |
|
|
368
368
|
| `--verbose` | | Enable verbose logging. All verbose logs and prefixed with their log level and are printed to stderr for ease of redirection. | `boolean` | |
|
|
369
369
|
| `--help` | `-h` | Show help | `boolean` | |
|
|
@@ -390,7 +390,7 @@ mdat readme check [files..] [options]
|
|
|
390
390
|
| `--package` | | Path to the package.json file to use to populate the readme. | `string` | The closest package.json file is used by default. |
|
|
391
391
|
| `--assets` | | Path to find and save readme-related assets. | `string` | `./assets` |
|
|
392
392
|
| `--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
|
-
| `--meta` | `-m` | Embed an extra comment at the top of the generated Markdown
|
|
393
|
+
| `--meta` | `-m` | Embed an extra comment at the top of the generated Markdown warning editors that certain sections of the document have been generated dynamically. | `boolean` | |
|
|
394
394
|
| `--verbose` | | Enable verbose logging. All verbose logs and prefixed with their log level and are printed to stderr for ease of redirection. | `boolean` | |
|
|
395
395
|
| `--help` | `-h` | Show help | `boolean` | |
|
|
396
396
|
| `--version` | `-v` | Show version number | `boolean` | |
|