mdat 0.2.0 → 0.3.1
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 +303 -3
- package/dist/api.d.ts +7 -24
- package/dist/config.d.ts +33 -8
- package/dist/index.d.ts +4 -2
- package/dist/index.js +33 -3
- package/dist/readme/api.d.ts +13 -0
- package/dist/readme/rules/badges.d.ts +8 -0
- package/dist/readme/rules/banner.d.ts +7 -0
- package/dist/readme/rules/cli-help/index.d.ts +6 -0
- package/dist/readme/rules/cli-help/utilities/get-help-markdown.d.ts +4 -0
- package/dist/readme/rules/cli-help/utilities/help-cst-to-object.d.ts +35 -0
- package/dist/readme/rules/cli-help/utilities/help-object-to-markdown.d.ts +7 -0
- package/dist/readme/rules/cli-help/utilities/help-string-to-cst.d.ts +13 -0
- package/dist/readme/rules/cli-help/utilities/infer-command.d.ts +7 -0
- package/dist/readme/rules/code.d.ts +6 -0
- package/dist/readme/rules/contributing.d.ts +8 -0
- package/dist/readme/rules/footer.d.ts +11 -0
- package/dist/readme/rules/header.d.ts +11 -0
- package/dist/readme/rules/index.d.ts +71 -0
- package/dist/readme/rules/license.d.ts +8 -0
- package/dist/readme/rules/short-description.d.ts +8 -0
- package/dist/readme/rules/table-of-contents.d.ts +9 -0
- package/dist/readme/rules/title.d.ts +9 -0
- package/dist/readme/rules/tldraw.d.ts +6 -0
- package/dist/readme/rules/toc.d.ts +14 -0
- package/dist/utilities.d.ts +11 -0
- package/package.json +20 -8
- package/readme.md +504 -47
package/bin/cli.js
CHANGED
|
@@ -1,4 +1,304 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{defaultLoaders as
|
|
3
|
-
${JSON.stringify(
|
|
4
|
-
${JSON.stringify(
|
|
2
|
+
import{defaultLoaders as Qt}from"cosmiconfig";function ye(t,e){let n=Qt[".json"],i=n(t,e);return Xe(i)}function Xe(t,e="",n={}){for(let[i,o]of Object.entries(t)){let a=e?`${e}.${i}`:i;typeof o=="object"&&o!==null&&!Array.isArray(o)?Xe(o,a,n):o===null?n[a]="null":n[a]=o.toString()}return n}import{findUp as Xt}from"find-up";import en from"node:fs";import x from"node:path";import{packageUp as tn}from"package-up";import{isFileSync as et}from"path-type";import{packageDirectory as nn}from"pkg-dir";import{log as tt}from"remark-mdat";import on from"untildify";function rn(t,e){let n=e===0?1:Math.floor(Math.log10(Math.abs(e))+1);return t.toString().padStart(n,"0")}function we(t,e,n,i){let o=[];for(let[a,r]of t.entries()){let s=n&&t.length>1?`-${rn(a+1,t.length+1)}`:"",d=W(r,e,n,i,s);o.push(d)}return o}function W(t,e,n,i,o=""){let a=nt(t),r=e?nt(e):void 0;if(!et(a))throw new Error(`Input file not found: "${a}"`);if(r){if(et(r))throw new Error(`Output path must be a directory, received a file path: "${r}"`);en.mkdirSync(r,{recursive:!0})}let s=n?x.basename(n,x.extname(n)):x.basename(a,x.extname(a)),d=`.${i??(n&&x.extname(n)!==""?x.extname(n):x.extname(t)===""?"":x.extname(t))}`,m=`${s}${o}${d}`,c=r??x.dirname(a);return{input:a,name:m,output:c}}function nt(t){return on(t)}async function G(){tt.info("Searching for package directory...");let t=await nn()??process.cwd(),e=await Xt("readme.md",{stopAt:t,type:"file"});if(e!==void 0)return tt.info(`Found closest readme at "${e}"`),e}async function Y(){return tn()}import ot from"chalk";import{cosmiconfig as it}from"cosmiconfig";import an from"node:fs/promises";import st from"node:path";import sn from"plur";import{readPackage as dn}from"read-pkg";import{deepMergeDefined as be,log as y,optionsSchema as mn,rulesSchema as cn}from"remark-mdat";import{z as K}from"zod";var rt=mn.merge(K.object({assetsPath:K.string().optional(),packageFile:K.string().optional(),readmeFile:K.string().optional()})).describe("Config Extension");async function k(t){let{additionalConfig:e,additionalRules:n,searchFrom:i}=t??{},o={addMetaComment:!1,assetsPath:"./assets",closingPrefix:"/",keywordPrefix:"",metaCommentIdentifier:"+",packageFile:await Y(),readmeFile:await G(),rules:{mdat:"Powered by the Markdown Autophagic Template system: [mdat](https://github.com/kitschpatrol/mdat)."}},a=it("mdat"),r=await a.search(i);if(r){let{config:s,filepath:d}=r;y.info(`Using config from "${d}"`);let m=at(s,rt);m&&(o=be(o,m))}if(e!==void 0){let s=Array.isArray(e)?e:[e];for(let d of s){let m;if(typeof d=="string"){let p=await a.load(d);if(p==null)continue;let{config:u,filepath:g}=p;y.info(`Loaded additional config from "${g}"`),m=u}else m=d;if(m===void 0)continue;y.info("Merging configuration object");let c=at(m,rt);c!==void 0&&(o=be(o,c))}}if(n!==void 0){let s=Array.isArray(n)?n:[n],d=it("mdat",{loaders:{".json":ye}});for(let m of s){let c;if(typeof m=="string"){let u;if(st.basename(m).endsWith("package.json")){let he=await an.readFile(m,"utf8");u={config:ye(m,he),filepath:m}}else u=await d.load(m);if(u==null)continue;let{config:g,filepath:C}=u;y.info(`Loaded additional config from "${C}"`),c=g}else c=m;if(c===void 0)continue;y.info("Merging rules into configuration object");let p=pn(c,cn);p!==void 0&&(o=be(o,p))}}if(o.rules){let s=Object.keys(o.rules).sort().map(d=>`"${ot.bold.green(d)}"`);y.info(`Loaded ${ot.bold(s.length)} mdat comment expansion ${sn("rule",s.length)}:`);for(let d of s)y.info(` ${d}`)}else y.error("No rules loaded from additional configurations or rules, using default.");return Z=o,o}function pn(t,e){if(e.safeParse(t).success)return{rules:t};y.error(`Rules object has the wrong shape. Ignoring and using default configuration:
|
|
3
|
+
${JSON.stringify(t,void 0,2)}`)}function at(t,e){if(e.safeParse(t).success)return t;y.error(`Config object has the wrong shape. Ignoring and using default configuration:
|
|
4
|
+
${JSON.stringify(t,void 0,2)}`)}var Z;async function w(){return Z===void 0&&(y.warn("getConfig(): config was undefined"),Z??=await k()),Z}var Ce;async function h(){let{packageFile:t}=await w();if(t===void 0)throw new Error("No packageFile found or set in config");if(Ce??=await dn({cwd:st.dirname(t)}),Ce===void 0)throw new Error("No package.json found");return Ce}import{remark as dt}from"remark";import mt from"remark-gfm";import{mdatClean as ln,mdatSplit as un,default as fn}from"remark-mdat";import{read as Q}from"to-vfile";import{VFile as Mo}from"vfile";async function X(t,e,n,i,o){let a=await k({additionalConfig:i,additionalRules:o});i=a;let r=we(t,n,e,"md"),s=[],d=ct(a);for(let{input:m,name:c,output:p}of r){let u=await Q(m),g=await d.process(u);g.dirname=p,g.basename=c,s.push(g)}return s}async function xe(t,e,n,i,o){let a=await k({additionalConfig:i,additionalRules:o});i=a;let r=W(t,n,e,"md"),s=await Q(r.input),d=await ct(a).process(s);return d.dirname=r.output,d.basename=r.name,d}async function ke(t,e,n,i){let o=await k({additionalConfig:i});i=o;let a=we(t,n,e,"md"),r=[],s=pt(o);for(let{input:d,name:m,output:c}of a){let p=await Q(d),u=await s.process(p);u.dirname=c,u.basename=m,r.push(u)}return r}async function Re(t,e,n,i){let o=await k({additionalConfig:i});i=o;let a=W(t,n,e,"md"),r=await Q(a.input),s=await pt(o).process(r);return s.dirname=a.output,s.basename=a.name,s}function ct(t){return dt().use({settings:{bullet:"-",emphasis:"_"}}).use(mt).use(fn,t??{})}function pt(t){let{closingPrefix:e,keywordPrefix:n,metaCommentIdentifier:i}=t;return dt().use({settings:{bullet:"-",emphasis:"_"}}).use(mt).use(()=>function(a,r){un(a,r),ln(a,r,{closingPrefix:e,keywordPrefix:n,metaCommentIdentifier:i})})}import{z as V}from"zod";var ee={badges:{async content(t){var r;let e=V.object({custom:V.record(V.object({image:V.string(),link:V.string()})).optional()}).optional().parse(t),n=await h(),{name:i}=n,o=[];!n.private&&((r=n.publishConfig)==null?void 0:r.access)==="public"&&o.push(`[](https://npmjs.com/package/${i})`);let{license:a}=n;if(a!==void 0&&o.push(`[](https://opensource.org/licenses/${a})`),(e==null?void 0:e.custom)!==void 0)for(let[s,{image:d,link:m}]of Object.entries(e.custom))o.push(`[](${m})`);return o.join(`
|
|
5
|
+
`)},order:3,required:!1}};import{globby as gn}from"globby";import te from"node:path";import{isFile as hn}from"path-type";import{readPackage as yn}from"read-pkg";import{z as Pe}from"zod";async function wn(t){let{packageFile:e}=await w();if(e===void 0)throw new Error("No package.json found");let n=te.dirname(e),i=t===void 0?[".","assets","media","readme-assets","readme-media","readme","images"]:[t],o=["banner","header","logo","readme","cover","screenshot","screenshots","demo","overview","image","hero"],a=["png","gif","jpg","jpeg","svg","webp"],r=await gn(i.map(s=>te.join(n,s)),{expandDirectories:{extensions:a,files:o}});if(r.length>0)return te.relative(process.cwd(),r[0])}var ne={banner:{async content(t){let e=Pe.object({alt:Pe.string().optional(),src:Pe.string().optional()}).optional().parse(t),{assetsPath:n,packageFile:i}=await w();if(i===void 0)throw new Error("No package.json found");let o=(e==null?void 0:e.src)??await wn(n);if(o===void 0||!await hn(o))throw new Error(`Banner image not found at ${o===void 0?"any typical location, consider adding something at ./assets/banner.webp":`"${o}"`}`);let a=(e==null?void 0:e.alt)??`${(await yn({cwd:te.dirname(i)})).name} banner`;if(a===void 0||a==="undefined banner")throw new Error("Banner image alt text not available");return``},order:2}};import{CstParser as bn,Lexer as S,createToken as f}from"chevrotain";var ve=f({name:"flag",pattern:/--[\w-_]+/}),$e=f({name:"alias",pattern:/-[A-Za-z]/}),lt=f({group:S.SKIPPED,name:"comma",pattern:/,/}),F=f({name:"word",pattern:/\S+/}),J=f({name:"argument",pattern:/<\S+>|\[\S+]/}),Ee=f({name:"type",pattern:/\[(boolean|string|array)]/}),Le=f({name:"defaultInfo",pattern:/\[default]/}),Te=f({name:"required",pattern:/\[required]/}),Ne=f({name:"defaultInfoDescription",pattern:/\[default:\s.+?]/}),Fe=f({name:"choices",pattern:/\[choices:\s.+?]/}),Oe=f({group:S.SKIPPED,name:"whiteSpace",pattern:/\s/}),ut=f({group:S.SKIPPED,name:"startProgramDescription",pattern:/\n\n/,push_mode:"PROGRAM_DESCRIPTION_MODE"}),_e=f({name:"programDescription",pattern:/.+/}),ft=f({group:S.SKIPPED,name:"endProgramDescription",pattern:/\n\n/,pop_mode:!0}),je=f({name:"startOptionsSection",pattern:/Options:\n/,push_mode:"SECTION_MODE"}),Ae=f({name:"startPositionalsSection",pattern:/Positionals:\n/,push_mode:"SECTION_MODE"}),De=f({name:"startCommandsSection",pattern:/Commands:\n/,push_mode:"SECTION_MODE"}),Ie=f({name:"startRow",pattern:/ {2,}/,push_mode:"ROW_MODE"}),Me=f({name:"rowDescription",pattern:/ {2}\w.+ {2}/}),Ue=f({name:"rowDescriptionTerminal",pattern:/ {2}\w.+/}),gt=f({group:S.SKIPPED,name:"endRow",pattern:/\n/,pop_mode:!0}),ht=f({group:S.SKIPPED,name:"endSection",pattern:/\n+/,pop_mode:!0}),Cn=new S({defaultMode:"DEFAULT_MODE",modes:{DEFAULT_MODE:[je,Ae,De,ut,J,F,Oe],PROGRAM_DESCRIPTION_MODE:[ft,_e],ROW_MODE:[gt,lt,Ee,Me,Ue,Ne,Le,Te,Fe,ve,$e,J,F,Oe],SECTION_MODE:[Ie,ht]}}),xn=[ve,$e,lt,F,J,Ee,Le,Te,Ne,Fe,Oe,ut,_e,ft,je,Ae,De,Ie,Me,Ue,gt,ht];function kn(t){return Cn.tokenize(t.trim())}var Se=class extends bn{programHelp=this.RULE("programHelp",()=>{this.AT_LEAST_ONE(()=>{this.CONSUME(F,{LABEL:"commandName"})}),this.MANY1(()=>{this.CONSUME(J)}),this.OPTION(()=>{this.CONSUME(_e,{LABEL:"description"})}),this.OPTION1(()=>{this.SUBRULE(this.commandsSection)}),this.OPTION2(()=>{this.SUBRULE(this.positionalsSection)}),this.OPTION3(()=>{this.SUBRULE(this.optionsSection)})});positionalsSection=this.RULE("positionalsSection",()=>{this.CONSUME(Ae),this.MANY(()=>{this.SUBRULE(this.sectionRow)})});commandsSection=this.RULE("commandsSection",()=>{this.CONSUME(De),this.MANY1(()=>{this.SUBRULE1(this.sectionRow)})});optionsSection=this.RULE("optionsSection",()=>{this.CONSUME(je),this.MANY2(()=>{this.SUBRULE2(this.sectionRow)})});sectionRow=this.RULE("sectionRow",()=>{this.CONSUME(Ie),this.OPTION(()=>{this.CONSUME(F,{LABEL:"parentCommandName"})}),this.MANY(()=>{this.CONSUME1(F,{LABEL:"commandName"})}),this.MANY1(()=>{this.OR([{ALT:()=>this.CONSUME(J)},{ALT:()=>this.CONSUME($e)},{ALT:()=>this.CONSUME(ve)},{ALT:()=>this.CONSUME(Me,{LABEL:"description"})},{ALT:()=>this.CONSUME(Ue,{LABEL:"description"})},{ALT:()=>this.CONSUME(Ee)},{ALT:()=>this.CONSUME(Te)},{ALT:()=>this.CONSUME(Ne)},{ALT:()=>this.CONSUME(Le)},{ALT:()=>this.CONSUME(Fe)}])})});constructor(){super(xn),this.performSelfAnalysis()}},N=new Se;function yt(t){let e=kn(t);N.input=e.tokens;let n=N.programHelp();if(N.errors.length>0)throw new Error(`Errors parsing CLI command help text output: ${JSON.stringify(N.errors,void 0,2)}`);return n}var Ve=class extends N.getBaseCstVisitorConstructor(){constructor(){super(),this.validateVisitor()}programHelp(e){let{command:n,subcommand:i}=Pn(this.getString(e.commandName));return{arguments:this.getArray(e.argument),commandName:n,commands:e.commandsSection?this.visit(e.commandsSection):void 0,description:this.getString(e.description),options:e.optionsSection?this.visit(e.optionsSection):void 0,positionals:e.positionalsSection?this.visit(e.positionalsSection):void 0,subcommandName:i}}positionalsSection(e){return e.sectionRow.map(n=>this.positionalParentCommandToArguments(this.visit(n)))}commandsSection(e){return e.sectionRow.map(n=>this.visit(n))}optionsSection(e){return e.sectionRow.map(n=>this.visit(n))}sectionRow(e){return{aliases:this.getArray(e.alias),arguments:this.getArray(e.argument),choices:this.splitChoices(this.getString(e.choices)),commandName:this.getString(e.commandName),default:e.defaultInfo?!0:void 0,defaultValue:this.getString(e.defaultInfoDescription,!0),description:this.getString(e.description,!0),flags:this.getArray(e.flag),parentCommandName:this.getString(e.parentCommandName),required:e.required?!0:void 0,type:this.getString(e.type,!0)}}positionalParentCommandToArguments(e){let{arguments:n,parentCommandName:i,...o}=e;return i===void 0?e:{arguments:[i,...n??[]],...o}}getString(e,n=!1){if(e!==void 0)return e.map(i=>n?this.clean(i.image):i.image).join(" ")}getArray(e){if(e!==void 0)return e.map(n=>n.image)}clean(e){return e.replaceAll(/^[\s[]*(default:)?\s*|[\s\]]*$/g,"")}splitChoices(e){if(e!==void 0)return this.clean(e.replaceAll(/^\[choices:\s/g,"")).split(", ")}},Rn=new Ve;function wt(t){return Rn.visit(t)}function Pn(t){if(t===void 0)throw new Error('Could not find "commandName" entry in help');let e=t.split(" ");if(e.length===0&&t===void 0)throw new Error('Could not find "commandName" entry in help');if(e.length===1)return{command:e[0],subcommand:void 0};let n=e.at(-1);return{command:e.slice(0,-1).join(" "),subcommand:n}}function bt(t,e=!1){var i,o,a;let n=[];if(e){let r=(i=t.commands)==null?void 0:i.find(m=>m.default),s=(o=t.commands)==null?void 0:o.find(m=>m.commandName===void 0),d=`${t.commandName}${t.subcommandName?` ${t.subcommandName}`:""}`;n.push(`#### Command: \`${d}\``),s!=null&&s.description&&n.push(s==null?void 0:s.description),n.push(`This section lists top-level commands for \`${d}\`.`),r&&n.push(`If no command is provided, \`${r.parentCommandName} ${r.commandName}\` is run by default.`),n.push("Usage:"),s&&n.push(`\`\`\`txt
|
|
6
|
+
${s.parentCommandName}${s.arguments?` ${s.arguments.join(" ")}`:""}
|
|
7
|
+
\`\`\``),t.commands=(a=t.commands)==null?void 0:a.filter(m=>m!==s)}else n.push(`#### Subcommand: \`${t.commandName} ${t.subcommandName}\``),n.push(t.description),n.push("Usage:"),n.push(`\`\`\`txt
|
|
8
|
+
${t.commandName} ${t.subcommandName}${t.arguments?` ${t.arguments.join(" ")}`:""}
|
|
9
|
+
\`\`\``);return t.positionals&&!e&&n.push(Je(["Positional Argument","Description","Type","Default"],t.positionals.map(r=>[r.arguments?[r.arguments.map(s=>`\`${s}\``)].join(" "):"",`${r.description??""}${r.required?" _(Required.)_":" _(Optional.)_"}`,r.type?`\`${r.type}\``:"",r.defaultValue?r.defaultValue.includes(" ")?r.defaultValue:`\`${r.defaultValue}\``:""]))),t.commands&&n.push(Je(["Command","Argument","Description"],t.commands.map(r=>{var s;return[`\`${r.commandName??(r.default?"[default]":"")}\``,r.arguments?(s=r.arguments)==null?void 0:s.map(d=>`\`${d}\``).join(" "):"",`${r.description??""}${r.default?" _(Default command.)_":""}`]}))),t.options&&!e&&n.push(Je(["Option","Alias","Argument","Description","Type","Default"],t.options.map(r=>[r.flags?r.flags.map(s=>`\`${s}\``).join(" "):"",r.aliases?r.aliases.map(s=>`\`${s}\``).join(" "):"",r.arguments?r.arguments.map(s=>`\`${s}\``).join(" "):"",r.description??"",r.type?`\`${r.type}\``:"",r.defaultValue?r.defaultValue.includes(" ")?r.defaultValue:`\`${r.defaultValue}\``:""]))),e&&n.push("_See the sections below for more information on each subcommand._"),n.join(`
|
|
10
|
+
|
|
11
|
+
`)}function Je(t,e){let n=On(e);t=t.filter((o,a)=>!n.includes(a)),e=e.map(o=>o.filter((a,r)=>!n.includes(r)));let i="";i+=`| ${t.join(" | ")} |
|
|
12
|
+
`,i+=`| ${t.map(()=>"---").join(" | ")} |
|
|
13
|
+
`;for(let o of e)i+=`| ${o.join(" | ")} |
|
|
14
|
+
`;return i}function On(t){var i;let e=[],n=((i=t[0])==null?void 0:i.length)||0;for(let o=0;o<n;o++){let a=!0;for(let r of t)if(r[o]!==""){a=!1;break}a&&e.push(o)}return e}import{execaCommand as Sn}from"execa";import{log as Ct}from"remark-mdat";async function Be(t){let e=`${t} --help`,n;try{let{stderr:o,stdout:a}=await Sn(e);n=a,(n===void 0||n==="")&&(n=o)}catch(o){if(o instanceof Error)throw new TypeError(`Error running CLI help command: ${e}
|
|
15
|
+
${o.message}
|
|
16
|
+
`)}if(n===void 0||n==="")throw new Error(`No result from running CLI help command: ${e}
|
|
17
|
+
`);let i;try{let o=yt(n);i=wt(o)}catch(o){o instanceof Error&&(i=void 0,Ct.warn(`Error parsing help output for command: ${t}
|
|
18
|
+
${o.message}`),Ct.warn("Falling back to basic cli help text output."))}return i===void 0?$n(n):vn(t,i)}async function vn(t,e){let n=(e.commands&&e.commands.some(a=>a.default))??!1,i=bt(e,n),o=t.split(" ")[0];if(e.commands)for(let a of e.commands){if(!a.parentCommandName||!a.commandName)continue;let r=await Be(`${o} ${a.commandName}`);i+=`
|
|
19
|
+
|
|
20
|
+
${r}`}return i}function $n(t){return`\`\`\`txt
|
|
21
|
+
${t}
|
|
22
|
+
\`\`\``}import{isExecutable as En}from"is-executable";import Ln from"node:path";import{log as Tn}from"remark-mdat";import Nn from"which";async function xt(t){return t??=await Fn(),jn(t)}async function Fn(){let t=await h();if(t!=null&&t.bin){let e=typeof t.bin=="string"?t.bin:String(Object.values(t.bin).at(0));if(_n(e))return Tn.info(`Inferred <!-- cli-help --> command to run from package.json: ${e}`),e}throw new Error(`Could not infer which command to run for the <!-- cli-help --> rule. Please pass a "cliCommand" option to the expansion comment, e.g. <!-- cli-help {cliCommend: './dist/bin.js'} -->`)}function _n(t){let e=Ln.parse(t);return e.root!==""||e.dir!==""}async function jn(t){let e=await Nn(t,{nothrow:!0});if(e===null&&(e=await An(t)??void 0),e!==void 0&&await En(e))return e;throw new Error(`The cli-help rule noticed that "${e}" is not executable.`)}async function An(t){var n;let e=await h();return((n=e==null?void 0:e.bin)==null?void 0:n[t])??void 0}import{z as kt}from"zod";var Rt={"cli-help":{async content(t){let e=kt.object({cliCommand:kt.string().optional()}).optional().parse(t),n=await xt(e==null?void 0:e.cliCommand);return Be(n)}}};import Dn from"node:fs/promises";import Pt from"node:path";import{z as qe}from"zod";var Ot={code:{async content(t){let e=qe.object({file:qe.string(),language:qe.string().optional()}).parse(t),n=Pt.extname(e.file)??"",i=await Dn.readFile(Pt.join(process.cwd(),e.file),"utf8");return`\`\`\`${n}
|
|
23
|
+
${i}
|
|
24
|
+
\`\`\``}}};var oe={contributing:{async content(){var n;let t=await h(),e=(n=t==null?void 0:t.bugs)==null?void 0:n.url;if(e===void 0)throw new Error('Could not find "bugs.url" entry in package.json');return`## Contributing
|
|
25
|
+
[Issues](${e}) and pull requests are welcome.`},order:15,required:!0}};var ie={license:{async content(){let t=await h(),{author:e,license:n}=t;if((e==null?void 0:e.name)===void 0)throw new Error('Could not find "author.name" entry in package.json');if(n===void 0)throw new Error('Could not find "license" entry in package.json');return`## License
|
|
26
|
+
[${n}](license.txt) \xA9 ${e.name}`},order:16,required:!0}};import{getSoleRule as St}from"remark-mdat";var vt={footer:{content:[St(oe),St(ie)],order:17}};var re={"short-description":{async content(){let t=await h();if(t.description===void 0)throw new Error('Could not find "description" entry in package.json');return`**${t.description}**`},order:4,required:!0}};import{z as ae}from"zod";var se={title:{applicationOrder:2,async content(t){let{postfix:e,prefix:n,titleCase:i}=ae.object({postfix:ae.string().optional().default(""),prefix:ae.string().optional().default(""),titleCase:ae.boolean().optional().default(!1)}).parse(t??{}),{name:o}=await h();return`# ${n}${i?In(o):o}${e}`},order:1,required:!0}};function In(t){return t.split(/[ _-]/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}import{getSoleRule as de}from"remark-mdat";var $t={header:{applicationOrder:2,content:[de(se),de(ne),de(ee),de(re)],order:1}};import{toc as Mn}from"mdast-util-toc";import{remark as Un}from"remark";import Vn from"remark-gfm";import{z as R}from"zod";var me={"table-of-contents":{applicationOrder:1,async content(t,e){let n=R.object({maxDepth:R.union([R.literal(1),R.literal(2),R.literal(3),R.literal(4),R.literal(5),R.literal(6)]).optional()}).optional().parse(t),i=Mn(e,{heading:null,maxDepth:(n==null?void 0:n.maxDepth)??3,tight:!0}),o="## Table of contents";if(i.map===void 0)throw new Error("Could not generate table of contents");let a={children:i.map.children,type:"root"},r=Un().use(Vn).stringify(a).replaceAll(`
|
|
27
|
+
|
|
28
|
+
`,`
|
|
29
|
+
`);return[o,r].join(`
|
|
30
|
+
`)},order:6}};import{tldrawToImage as Et}from"@kitschpatrol/tldraw-cli";import Jn from"node:crypto";import _ from"node:fs/promises";import b from"node:path";import{isFile as He}from"path-type";import{z as ze}from"zod";var Ft={tldraw:{async content(t){let{alt:e="tldraw diagram",src:n}=ze.object({alt:ze.string().optional(),src:ze.string()}).parse(t),{assetsPath:i}=await w();if(i===void 0)throw new Error("No assets path found");await _.mkdir(i,{recursive:!0});let o=await He(n)?await Tt(n):void 0;if(o!==void 0){let m=b.basename(n,b.extname(n)),c=b.join(i,`${m}-${o}-light.svg`),p=b.join(i,`${m}-${o}-dark.svg`);if(await He(c)&&await He(p))return Lt(c,p,e)}let[a]=await Et(n,{dark:!1,format:"svg",output:i,transparent:!0});o??=await Tt(a);let r=`${Nt(a)}-${o}-light.svg`;await _.rename(a,r);let[s]=await Et(n,{dark:!0,format:"svg",output:i,transparent:!0}),d=`${Nt(s)}-${o}-dark.svg`;if(await _.rename(s,d),o!==void 0){let m=b.basename(d),c=b.basename(r),p=c.replace(`${o}-light.svg`,""),u=await _.readdir(i);for(let g of u){let C=b.basename(g);C!==m&&C!==c&&C.startsWith(p)&&C.endsWith(".svg")&&await _.rm(b.join(i,C))}}return Lt(r,d,e)}}};async function Lt(t,e,n){let{readmeFile:i}=await w();if(i===void 0)throw new Error("No readme file found");let o=b.dirname(i),a=b.relative(o,t);return`<picture>
|
|
31
|
+
<source media="(prefers-color-scheme: dark)" srcset="${b.relative(o,e)}">
|
|
32
|
+
<source media="(prefers-color-scheme: light)" srcset="${a}">
|
|
33
|
+
<img alt="${n}" src="${a}">
|
|
34
|
+
</picture>`}async function Tt(t){let e=await _.readFile(t),n=Jn.createHash("sha1");return n.update(e),n.digest("hex").slice(0,8)}function Nt(t){return t.replace(/\.[^./]+$/,"")}import{getSoleRule as Bn}from"remark-mdat";var _t={toc:{applicationOrder:1,content:[Bn(me)]}};var jt={...ee,...ne,...Rt,...Ot,...oe,...vt,...$t,...ie,...re,...me,...Ft,..._t,...se};async function j(t,e,n,i){let o=await Ge({additionalConfig:n,additionalRules:i});return xe(o.readmeFile,t,e,o)}async function We(t){let e=await Ge({additionalConfig:t});return Re(e.readmeFile,void 0,void 0,e)}async function Ge(t){let e={addMetaComment:!0,rules:jt},{additionalConfig:n=[],...i}=t??{},o=Array.isArray(n)?n:[n],a=await k({additionalConfig:[e,...o],...i});if(a.packageFile===void 0||a.readmeFile===void 0)throw new Error("Package and readme files are required in `mdat readme` config");return a}var At=`<!-- header -->
|
|
35
|
+
|
|
36
|
+
<!-- table-of-contents -->
|
|
37
|
+
|
|
38
|
+
## Overview
|
|
39
|
+
|
|
40
|
+
## Getting started
|
|
41
|
+
|
|
42
|
+
### Dependencies
|
|
43
|
+
|
|
44
|
+
### Installation
|
|
45
|
+
|
|
46
|
+
## Usage
|
|
47
|
+
|
|
48
|
+
### Library
|
|
49
|
+
|
|
50
|
+
#### API
|
|
51
|
+
|
|
52
|
+
#### Examples
|
|
53
|
+
|
|
54
|
+
### CLI
|
|
55
|
+
|
|
56
|
+
#### Commands
|
|
57
|
+
|
|
58
|
+
#### Examples
|
|
59
|
+
|
|
60
|
+
## Background
|
|
61
|
+
|
|
62
|
+
### Motivation
|
|
63
|
+
|
|
64
|
+
### Implementation notes
|
|
65
|
+
|
|
66
|
+
### Similar projects
|
|
67
|
+
|
|
68
|
+
## The future
|
|
69
|
+
|
|
70
|
+
## Maintainers
|
|
71
|
+
|
|
72
|
+
_List maintainer(s) for a repository, along with one way of contacting them (e.g. GitHub link or email)._
|
|
73
|
+
|
|
74
|
+
## Acknowledgements
|
|
75
|
+
|
|
76
|
+
_State anyone or anything that significantly helped with the development of your project. State public contact hyper-links if applicable._
|
|
77
|
+
|
|
78
|
+
<!-- footer -->
|
|
79
|
+
`;var Dt=`<!-- title -->
|
|
80
|
+
|
|
81
|
+
<!-- banner -->
|
|
82
|
+
|
|
83
|
+
<!-- badges -->
|
|
84
|
+
|
|
85
|
+
<!-- short-description -->
|
|
86
|
+
|
|
87
|
+
<!-- table-of-contents -->
|
|
88
|
+
|
|
89
|
+
## Overview
|
|
90
|
+
|
|
91
|
+
## Getting started
|
|
92
|
+
|
|
93
|
+
### Dependencies
|
|
94
|
+
|
|
95
|
+
### Installation
|
|
96
|
+
|
|
97
|
+
## Usage
|
|
98
|
+
|
|
99
|
+
### Library
|
|
100
|
+
|
|
101
|
+
#### API
|
|
102
|
+
|
|
103
|
+
#### Examples
|
|
104
|
+
|
|
105
|
+
### CLI
|
|
106
|
+
|
|
107
|
+
#### Commands
|
|
108
|
+
|
|
109
|
+
#### Examples
|
|
110
|
+
|
|
111
|
+
## Background
|
|
112
|
+
|
|
113
|
+
### Motivation
|
|
114
|
+
|
|
115
|
+
### Implementation notes
|
|
116
|
+
|
|
117
|
+
### Similar projects
|
|
118
|
+
|
|
119
|
+
## The future
|
|
120
|
+
|
|
121
|
+
## Maintainers
|
|
122
|
+
|
|
123
|
+
_List maintainer(s) for a repository, along with one way of contacting them (e.g. GitHub link or email)._
|
|
124
|
+
|
|
125
|
+
## Acknowledgements
|
|
126
|
+
|
|
127
|
+
_State anyone or anything that significantly helped with the development of your project. State public contact hyper-links if applicable._
|
|
128
|
+
|
|
129
|
+
<!-- contributing -->
|
|
130
|
+
|
|
131
|
+
<!-- license -->
|
|
132
|
+
`;var It=`<!-- header -->
|
|
133
|
+
|
|
134
|
+
## Install
|
|
135
|
+
|
|
136
|
+
\`\`\`ts
|
|
137
|
+
Code block illustrating how to install.
|
|
138
|
+
\`\`\`
|
|
139
|
+
|
|
140
|
+
## Usage
|
|
141
|
+
|
|
142
|
+
\`\`\`ts
|
|
143
|
+
Code block illustrating common usage.
|
|
144
|
+
Consider using the <!-- code { src: "path/to/example.ts" } --> comment as well.
|
|
145
|
+
\`\`\`
|
|
146
|
+
|
|
147
|
+
<!-- footer -->
|
|
148
|
+
`;var Mt=`<!-- title -->
|
|
149
|
+
|
|
150
|
+
<!-- short-description -->
|
|
151
|
+
|
|
152
|
+
<!-- table-of-contents -->
|
|
153
|
+
|
|
154
|
+
## Install
|
|
155
|
+
|
|
156
|
+
\`\`\`ts
|
|
157
|
+
Code block illustrating how to install.
|
|
158
|
+
\`\`\`
|
|
159
|
+
|
|
160
|
+
## Usage
|
|
161
|
+
|
|
162
|
+
\`\`\`ts
|
|
163
|
+
Code block illustrating common usage.
|
|
164
|
+
Consider using the <!-- code { src: "path/to/example.ts" } --> comment as well.
|
|
165
|
+
\`\`\`
|
|
166
|
+
|
|
167
|
+
<!-- contributing -->
|
|
168
|
+
|
|
169
|
+
<!-- license -->
|
|
170
|
+
`;var Ut=`<!-- header -->
|
|
171
|
+
|
|
172
|
+
_Long description goes here._
|
|
173
|
+
|
|
174
|
+
_No heading. Cover the main reasons for building the repository. This should describe your module in broad terms, generally in just a few paragraphs; more detail of the module's routines or methods, lengthy code examples, or other in-depth material should be given in subsequent sections._
|
|
175
|
+
|
|
176
|
+
<!-- table-of-contents -->
|
|
177
|
+
|
|
178
|
+
## Background
|
|
179
|
+
|
|
180
|
+
_Cover motivation. Cover abstract dependencies. Cover intellectual provenance: A See Also section is also fitting._
|
|
181
|
+
|
|
182
|
+
### See also
|
|
183
|
+
|
|
184
|
+
## Install
|
|
185
|
+
|
|
186
|
+
\`\`\`ts
|
|
187
|
+
Code block illustrating how to install.
|
|
188
|
+
\`\`\`
|
|
189
|
+
|
|
190
|
+
### Dependencies
|
|
191
|
+
|
|
192
|
+
_Required if there are unusual dependencies or dependencies that must be manually installed._
|
|
193
|
+
|
|
194
|
+
## Usage
|
|
195
|
+
|
|
196
|
+
\`\`\`ts
|
|
197
|
+
Code block illustrating common usage.
|
|
198
|
+
Consider using the <!-- code { src: "path/to/example.ts" } --> comment as well.
|
|
199
|
+
\`\`\`
|
|
200
|
+
|
|
201
|
+
\`\`\`ts
|
|
202
|
+
If importable, code block indicating both import functionality and usage.
|
|
203
|
+
\`\`\`
|
|
204
|
+
|
|
205
|
+
### CLI
|
|
206
|
+
|
|
207
|
+
\`\`\`ts
|
|
208
|
+
If CLI compatible, code block indicating common usage.
|
|
209
|
+
\`\`\`
|
|
210
|
+
|
|
211
|
+
## _Extra Sections (Rename)_
|
|
212
|
+
|
|
213
|
+
## Security
|
|
214
|
+
|
|
215
|
+
## API
|
|
216
|
+
|
|
217
|
+
_Describe exported functions and objects._
|
|
218
|
+
|
|
219
|
+
- _Describe signatures, return types, callbacks, and events._
|
|
220
|
+
- _Cover types covered where not obvious._
|
|
221
|
+
- _Describe caveats._
|
|
222
|
+
- _If using an external API generator (like go-doc, js-doc, or so on), point to an external API.md file. This can be the only item in the section, if present._
|
|
223
|
+
|
|
224
|
+
## Maintainers
|
|
225
|
+
|
|
226
|
+
_List maintainer(s) for a repository, along with one way of contacting them (e.g. GitHub link or email)._
|
|
227
|
+
|
|
228
|
+
## Thanks
|
|
229
|
+
|
|
230
|
+
_State anyone or anything that significantly helped with the development of your project. State public contact hyper-links if applicable._
|
|
231
|
+
|
|
232
|
+
<!-- footer -->
|
|
233
|
+
`;var Vt=`<!-- title -->
|
|
234
|
+
|
|
235
|
+
<!-- banner -->
|
|
236
|
+
|
|
237
|
+
<!-- badges -->
|
|
238
|
+
|
|
239
|
+
<!-- short-description -->
|
|
240
|
+
|
|
241
|
+
_Long description goes here._
|
|
242
|
+
|
|
243
|
+
_No heading. Cover the main reasons for building the repository. This should describe your module in broad terms, generally in just a few paragraphs; more detail of the module's routines or methods, lengthy code examples, or other in-depth material should be given in subsequent sections._
|
|
244
|
+
|
|
245
|
+
<!-- table-of-contents -->
|
|
246
|
+
|
|
247
|
+
## Background
|
|
248
|
+
|
|
249
|
+
_Cover motivation. Cover abstract dependencies. Cover intellectual provenance: A See Also section is also fitting._
|
|
250
|
+
|
|
251
|
+
### See also
|
|
252
|
+
|
|
253
|
+
## Install
|
|
254
|
+
|
|
255
|
+
\`\`\`ts
|
|
256
|
+
Code block illustrating how to install.
|
|
257
|
+
\`\`\`
|
|
258
|
+
|
|
259
|
+
### Dependencies
|
|
260
|
+
|
|
261
|
+
_Required if there are unusual dependencies or dependencies that must be manually installed._
|
|
262
|
+
|
|
263
|
+
## Usage
|
|
264
|
+
|
|
265
|
+
\`\`\`ts
|
|
266
|
+
Code block illustrating common usage.
|
|
267
|
+
Consider using the <!-- code { src: "path/to/example.ts" } --> comment as well.
|
|
268
|
+
\`\`\`
|
|
269
|
+
|
|
270
|
+
\`\`\`ts
|
|
271
|
+
If importable, code block indicating both import functionality and usage.
|
|
272
|
+
\`\`\`
|
|
273
|
+
|
|
274
|
+
### CLI
|
|
275
|
+
|
|
276
|
+
\`\`\`ts
|
|
277
|
+
If CLI compatible, code block indicating common usage.
|
|
278
|
+
\`\`\`
|
|
279
|
+
|
|
280
|
+
## _Extra Sections (Rename)_
|
|
281
|
+
|
|
282
|
+
## Security
|
|
283
|
+
|
|
284
|
+
## API
|
|
285
|
+
|
|
286
|
+
_Describe exported functions and objects._
|
|
287
|
+
|
|
288
|
+
- _Describe signatures, return types, callbacks, and events._
|
|
289
|
+
- _Cover types covered where not obvious._
|
|
290
|
+
- _Describe caveats._
|
|
291
|
+
- _If using an external API generator (like go-doc, js-doc, or so on), point to an external API.md file. This can be the only item in the section, if present._
|
|
292
|
+
|
|
293
|
+
## Maintainers
|
|
294
|
+
|
|
295
|
+
_List maintainer(s) for a repository, along with one way of contacting them (e.g. GitHub link or email)._
|
|
296
|
+
|
|
297
|
+
## Thanks
|
|
298
|
+
|
|
299
|
+
_State anyone or anything that significantly helped with the development of your project. State public contact hyper-links if applicable._
|
|
300
|
+
|
|
301
|
+
<!-- contributing -->
|
|
302
|
+
|
|
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}
|
package/dist/api.d.ts
CHANGED
|
@@ -1,37 +1,20 @@
|
|
|
1
|
-
import { type
|
|
1
|
+
import { type ConfigToLoad, type RulesToLoad } from './config';
|
|
2
2
|
import { VFile } from 'vfile';
|
|
3
|
-
/**
|
|
4
|
-
* Generously accept either string paths to .ts, .js, or .json files with
|
|
5
|
-
* `MdatOptions` type default exports. Takes a single value, or an array of values which
|
|
6
|
-
* will be merged right to left.
|
|
7
|
-
*/
|
|
8
|
-
export type ExpandConfig<T extends MdatOptions = MdatOptions> = Array<T | string> | T | string;
|
|
9
|
-
/**
|
|
10
|
-
* Generously accept either string paths to .ts, .js, or .json files with
|
|
11
|
-
* `MdatOptions` type default exports. Takes a single value, or an array of values which
|
|
12
|
-
* will be merged right to left.
|
|
13
|
-
*/
|
|
14
|
-
export type CleanConfig<T extends Partial<MdatCleanOptions> = Partial<MdatCleanOptions>> = Array<T | string> | T | string;
|
|
15
|
-
/**
|
|
16
|
-
* Generously accept either string paths to .ts, .js, or .json files with
|
|
17
|
-
* `Rules` type default exports.
|
|
18
|
-
*/
|
|
19
|
-
export type ExpandRules = Array<Rules | string> | Rules | string;
|
|
20
3
|
/**
|
|
21
4
|
* Writing is the responsibility of the caller (e.g. via `await write(result)`)
|
|
22
5
|
*/
|
|
23
|
-
export declare function expandFiles(files: string[], name?: string, output?: string, config?:
|
|
6
|
+
export declare function expandFiles(files: string[], name?: string, output?: string, config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile[]>;
|
|
24
7
|
/**
|
|
25
8
|
* Writing is the responsibility of the caller (e.g. via `await write(result)`)
|
|
26
9
|
*/
|
|
27
|
-
export declare function expandFile(file: string, name?: string, output?: string, config?:
|
|
28
|
-
export declare function expandString(markdown: string, config?:
|
|
10
|
+
export declare function expandFile(file: string, name?: string, output?: string, config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile>;
|
|
11
|
+
export declare function expandString(markdown: string, config?: ConfigToLoad, rules?: RulesToLoad): Promise<VFile>;
|
|
29
12
|
/**
|
|
30
13
|
* Writing is the responsibility of the caller (e.g. via `await write(result)`)
|
|
31
14
|
*/
|
|
32
|
-
export declare function cleanFiles(files: string[], name?: string, output?: string, config?:
|
|
15
|
+
export declare function cleanFiles(files: string[], name?: string, output?: string, config?: ConfigToLoad): Promise<VFile[]>;
|
|
33
16
|
/**
|
|
34
17
|
* Writing is the responsibility of the caller (e.g. via `await write(result)`)
|
|
35
18
|
*/
|
|
36
|
-
export declare function cleanFile(file: string, name?: string, output?: string, config?:
|
|
37
|
-
export declare function cleanString(markdown: string, config:
|
|
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>;
|
package/dist/config.d.ts
CHANGED
|
@@ -1,6 +1,31 @@
|
|
|
1
|
+
import { type NormalizedPackageJson } from 'read-pkg';
|
|
1
2
|
import { type Options, type Rules } from 'remark-mdat';
|
|
2
|
-
|
|
3
|
-
|
|
3
|
+
export type Config = {
|
|
4
|
+
assetsPath?: string;
|
|
5
|
+
packageFile?: string;
|
|
6
|
+
readmeFile?: string;
|
|
7
|
+
} & Options;
|
|
8
|
+
export type ConfigLoaded = {
|
|
9
|
+
addMetaComment: boolean;
|
|
10
|
+
assetsPath: string;
|
|
11
|
+
closingPrefix: string;
|
|
12
|
+
keywordPrefix: string;
|
|
13
|
+
metaCommentIdentifier: string;
|
|
14
|
+
packageFile: string | undefined;
|
|
15
|
+
readmeFile: string | undefined;
|
|
16
|
+
rules: Rules;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Generously accept either string paths to .ts, .js, or .json files with
|
|
20
|
+
* `Config` type default exports. Takes a single value, or an array of values which
|
|
21
|
+
* will be merged right to left.
|
|
22
|
+
*/
|
|
23
|
+
export type ConfigToLoad = Array<Config | string> | Config | string;
|
|
24
|
+
/**
|
|
25
|
+
* Generously accept either string paths to .ts, .js, or .json files with
|
|
26
|
+
* `Rules` type default exports.
|
|
27
|
+
*/
|
|
28
|
+
export type RulesToLoad = Array<Rules | string> | Rules | string;
|
|
4
29
|
/**
|
|
5
30
|
* Load and validate mdat configuration / rule sets
|
|
6
31
|
* Uses cosmiconfig to search in the usual places.
|
|
@@ -8,7 +33,7 @@ export type MdatConfig = Options;
|
|
|
8
33
|
*
|
|
9
34
|
* Generic to accommodate additional Config options, so set T to your custom config type if needed. You must provide a matching configExtensionSchema as well.
|
|
10
35
|
*/
|
|
11
|
-
export declare function loadConfig
|
|
36
|
+
export declare function loadConfig(options?: {
|
|
12
37
|
/**
|
|
13
38
|
* Additional Config objects to merge.
|
|
14
39
|
*
|
|
@@ -16,16 +41,16 @@ export declare function loadConfig<T extends MdatConfig>(options?: {
|
|
|
16
41
|
* Accepts an individual item, or an array. Objects in the array will be merged right to left.
|
|
17
42
|
*
|
|
18
43
|
*/
|
|
19
|
-
additionalConfig?:
|
|
44
|
+
additionalConfig?: ConfigToLoad;
|
|
20
45
|
/**
|
|
21
46
|
* Additional Rules objects to merge.
|
|
22
47
|
*
|
|
23
48
|
* Strings are treated as paths to `ts`, `js`, or `json` files with `Rules` type default exports. These will be dynamically loaded by Cosmiconfig.
|
|
24
49
|
* Accepts an individual item, or an array. Objects in the array will be merged right to left, and take precedence over any rules in previously loaded Config objects as well.
|
|
25
50
|
*/
|
|
26
|
-
additionalRules?:
|
|
27
|
-
/** Additional zod schema that will be merged with the top level of the config schema and used for config validation. Default mdat-remark options schema is used if not provided. Useful if extending config for things like mdat-readme. */
|
|
28
|
-
configExtensionSchema?: z.ZodObject<any>;
|
|
51
|
+
additionalRules?: RulesToLoad;
|
|
29
52
|
/** Search for config in specific directories, mainly useful for testing. Cosmiconfig default search paths used if unset. */
|
|
30
53
|
searchFrom?: string;
|
|
31
|
-
}): Promise<
|
|
54
|
+
}): Promise<ConfigLoaded>;
|
|
55
|
+
export declare function getConfig(): Promise<ConfigLoaded>;
|
|
56
|
+
export declare function getPackageJson(): Promise<NormalizedPackageJson>;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,2 +1,4 @@
|
|
|
1
|
-
export {
|
|
2
|
-
export { type
|
|
1
|
+
export { cleanFile, cleanFiles, cleanString, expandFile, expandFiles, expandString } from './api';
|
|
2
|
+
export { type Config, loadConfig } from './config';
|
|
3
|
+
export { cleanReadme, expandReadme, expandReadmeString, loadConfigReadme } from './readme/api';
|
|
4
|
+
export { type Rules } from 'remark-mdat';
|