mdat 3.1.0 → 3.2.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/dist/bin/cli.js CHANGED
@@ -1,1224 +1,13 @@
1
1
  #!/usr/bin/env node
2
- import { createLogger, getChildLogger, injectionHelper } from "lognow";
2
+ import { S as version, a as expand, b as setLogger$1, d as templates_default, f as ensureArray, l as createReadme, r as collapse, s as strip, t as check, u as createReadmeInteractive, x as name, y as log } from "../lib-BkjaGFsm.js";
3
+ import { createLogger } from "lognow";
3
4
  import picocolors from "picocolors";
4
5
  import prettyMilliseconds from "pretty-ms";
5
- import { getMdatReports, getSoleRule, mdatCollapse, mdatDiff, mdatExpand, mdatSplit, mdatStrip, reporterMdat, rulesSchema, setLogger } from "remark-mdat";
6
- import { read, write } from "to-vfile";
6
+ import { getMdatReports, reporterMdat } from "remark-mdat";
7
+ import { write } from "to-vfile";
7
8
  import yargs from "yargs";
8
9
  import { hideBin } from "yargs/helpers";
9
- import { remark } from "remark";
10
- import remarkGfm from "remark-gfm";
11
- import { cosmiconfig, defaultLoaders } from "cosmiconfig";
12
- import { TypeScriptLoader } from "cosmiconfig-typescript-loader";
13
- import fs from "node:fs/promises";
14
- import path from "node:path";
15
- import plur from "plur";
16
- import { deepmerge } from "deepmerge-ts";
17
- import { defineTemplate, getMetadata, helpers, setLogger as setLogger$1, templates } from "metascope";
18
- import { z } from "zod";
19
- import { globby } from "globby";
20
- import { isFile, isFileSync } from "path-type";
21
- import { promisify } from "node:util";
22
- import { brotliCompress, gzip } from "node:zlib";
23
- import prettyBytes from "pretty-bytes";
24
- import { toc } from "mdast-util-toc";
25
- import "vfile";
26
- import { Configuration } from "unified-engine";
27
- import untildify from "untildify";
28
- import { confirm, group, intro, note, outro, select } from "@clack/prompts";
29
10
 
30
- //#region package.json
31
- var name = "mdat";
32
- var version = "3.1.0";
33
-
34
- //#endregion
35
- //#region src/lib/deep-merge-defined.ts
36
- function stripUndefinedDeep(object) {
37
- if (Array.isArray(object)) return object.map((v) => v !== null && typeof v === "object" ? stripUndefinedDeep(v) : v).filter((v) => v !== void 0);
38
- return Object.entries(object).map(([k, v]) => [k, v !== null && typeof v === "object" ? stripUndefinedDeep(v) : v]).reduce((acc, [k, v]) => v === void 0 ? acc : {
39
- ...acc,
40
- [k]: v
41
- }, {});
42
- }
43
- function deepMergeDefined(...objects) {
44
- const stripped = objects.map((v, i) => i === 0 ? v : stripUndefinedDeep(v));
45
- return deepmerge(...stripped);
46
- }
47
-
48
- //#endregion
49
- //#region src/lib/log.ts
50
- /**
51
- * The default logger instance for the library.
52
- */
53
- let log = createLogger({
54
- logToConsole: { showTime: false },
55
- name
56
- });
57
- setLogger(getChildLogger(log, "remark-mdat"));
58
- setLogger$1(getChildLogger(log, "metascope"));
59
- /**
60
- * Set the logger instance for the module. Export this for library consumers to
61
- * inject their own logger.
62
- *
63
- * @param logger - Accepts either a LogLayer instance or a Console- or
64
- * Stream-like log target
65
- */
66
- function setLogger$2(logger) {
67
- log = injectionHelper(logger);
68
- setLogger(getChildLogger(log, "remark-mdat"));
69
- setLogger$1(getChildLogger(log, "metascope"));
70
- }
71
-
72
- //#endregion
73
- //#region src/lib/mdat-json-loader.ts
74
- /**
75
- * Lets arbitrary JSON objects (like from package.json) become reasonably good
76
- * mdat rule sets HOWEVER cosmiconfig treats package.json as a special case and
77
- * will always load only specific keys from it So we have to intercept and load
78
- * them manually in config.ts
79
- */
80
- function mdatJsonLoader(filePath, content) {
81
- const defaultJsonLoader = defaultLoaders[".json"];
82
- return flattenJson(defaultJsonLoader(filePath, content));
83
- }
84
- function flattenJson(jsonObject, parentKey = "", result = {}) {
85
- for (const [key, value] of Object.entries(jsonObject)) {
86
- const fullPath = parentKey === "" ? key : `${parentKey}.${key}`;
87
- if (typeof value === "object" && value !== null && !Array.isArray(value)) flattenJson(value, fullPath, result);
88
- else if (value === null) result[fullPath] = "null";
89
- else result[fullPath] = value.toString();
90
- }
91
- return result;
92
- }
93
-
94
- //#endregion
95
- //#region src/lib/context.ts
96
- let metascopeMetadata;
97
- /**
98
- * Get a bunch of platform-agnostic local metadata via metascope, exposed
99
- * primarily for plugin developers. Result is memoized the result.
100
- *
101
- * @throws {Error} If no package.json is found
102
- */
103
- async function getContextMetadata() {
104
- if (metascopeMetadata !== void 0) return metascopeMetadata;
105
- metascopeMetadata = await getMetadata({
106
- absolute: false,
107
- offline: true,
108
- recursive: false,
109
- sources: [
110
- "arduinoLibraryProperties",
111
- "cinderCinderblockXml",
112
- "codemetaJson",
113
- "gitConfig",
114
- "githubActions",
115
- "gitStats",
116
- "goGoMod",
117
- "goGoreleaserYaml",
118
- "javaPomXml",
119
- "licenseFile",
120
- "metadataFile",
121
- "metascope",
122
- "nodePackageJson",
123
- "obsidianPluginManifestJson",
124
- "openframeworksAddonConfigMk",
125
- "openframeworksInstallXml",
126
- "processingLibraryProperties",
127
- "processingSketchProperties",
128
- "publiccodeYaml",
129
- "pythonPkgInfo",
130
- "pythonPyprojectToml",
131
- "pythonSetupCfg",
132
- "pythonSetupPy",
133
- "readmeFile",
134
- "rubyGemspec",
135
- "rustCargoToml",
136
- "xcodeInfoPlist",
137
- "xcodeProjectPbxproj"
138
- ]
139
- });
140
- return metascopeMetadata;
141
- }
142
- const GIT_PREFIX_REGEX = /^git\+/v;
143
- const GIT_SUFFIX_REGEX = /\.git$/v;
144
- const TRAILING_SLASH_REGEX = /\/$/v;
145
- const PACKAGE_MANAGER_REGEX = /^(?<name>[^@]+)@(?<version>[^+]+)/v;
146
- const readmeMetadataTemplate = defineTemplate((context) => {
147
- const { githubActions, gitStats, licenseFile, metascope, nodePackageJson } = context;
148
- const codemeta = templates.codemetaJson(context, {});
149
- const nodePackage = helpers.firstOf(nodePackageJson)?.data;
150
- const licenseFileData = helpers.firstOf(licenseFile);
151
- const ciActionFilePath = helpers.ensureArray(githubActions).find((entry) => entry.data.name.toLowerCase() === "ci")?.source;
152
- const repoUrl = codemeta.codeRepository?.replace(GIT_PREFIX_REGEX, "").replace(GIT_SUFFIX_REGEX, "").replace(TRAILING_SLASH_REGEX, "");
153
- const bin = (() => {
154
- if (nodePackage === void 0) return;
155
- const binField = nodePackage.bin;
156
- if (binField === void 0) return;
157
- if (typeof binField === "string") return [nodePackage.name];
158
- const names = Object.keys(binField);
159
- return names.length > 0 ? names : void 0;
160
- })();
161
- const engines = (() => {
162
- const raw = nodePackage?.engines;
163
- if (raw === void 0) return;
164
- const entries = Object.entries(raw).filter((entry) => entry[1] !== void 0);
165
- return entries.length > 0 ? Object.fromEntries(entries) : void 0;
166
- })();
167
- const peerDependencies = (() => {
168
- if (nodePackage === void 0) return;
169
- const peers = nodePackage.peerDependencies;
170
- if (peers === void 0) return;
171
- const entries = Object.entries(peers).filter((entry) => entry[1] !== void 0);
172
- if (entries.length === 0) return;
173
- const meta = nodePackage.peerDependenciesMeta;
174
- return entries.map(([name, version]) => ({
175
- name,
176
- optional: meta?.[name]?.optional === true,
177
- version
178
- }));
179
- })();
180
- const developmentDependencies = (() => {
181
- if (nodePackage === void 0) return;
182
- const runtimes = helpers.ensureArray(nodePackage.devEngines?.runtime).map(({ name, version }) => ({
183
- name,
184
- version
185
- }));
186
- const packageManagers = helpers.ensureArray(nodePackage.devEngines?.packageManager).map(({ name, version }) => ({
187
- name,
188
- version
189
- }));
190
- const pinnedPackageManager = nodePackage.packageManager === void 0 ? void 0 : PACKAGE_MANAGER_REGEX.exec(nodePackage.packageManager)?.groups;
191
- if (pinnedPackageManager?.name !== void 0 && pinnedPackageManager.version !== void 0 && packageManagers.every((entry) => entry.name !== pinnedPackageManager.name)) packageManagers.push({
192
- name: pinnedPackageManager.name,
193
- version: pinnedPackageManager.version
194
- });
195
- if (runtimes.length === 0 && packageManagers.length === 0) return;
196
- return {
197
- packageManagers: packageManagers.length > 0 ? packageManagers : void 0,
198
- runtimes: runtimes.length > 0 ? runtimes : void 0
199
- };
200
- })();
201
- const firstAuthor = helpers.firstOf(helpers.ensureArray(codemeta.author));
202
- return {
203
- author: helpers.firstOf(helpers.mixedStringsToArray(helpers.toBasicNames(codemeta.author))),
204
- authorUrl: firstAuthor?.url,
205
- bin,
206
- ciActionFileName: ciActionFilePath === void 0 ? void 0 : path.basename(ciActionFilePath),
207
- description: codemeta.description,
208
- developmentDependencies,
209
- engines,
210
- isPublicNpmPackage: nodePackage?.private !== true && (nodePackage?.name.startsWith("@") && nodePackage.publishConfig?.access === "public" || true),
211
- issuesUrl: codemeta.issueTracker,
212
- license: helpers.toBasicLicense(helpers.firstOf(helpers.ensureArray(codemeta.license))),
213
- licenseFilePath: licenseFileData?.source,
214
- licenseUrl: licenseFileData?.data.match?.spdxUrl,
215
- name: codemeta.name,
216
- operatingSystem: codemeta.operatingSystem,
217
- peerDependencies,
218
- projectDirectory: metascope?.data.options.path === void 0 ? void 0 : `file://${metascope.data.options.path}`,
219
- repositoryUrl: repoUrl,
220
- runtimePlatform: codemeta.runtimePlatform,
221
- usesGitLfs: helpers.firstOf(gitStats)?.data.hasLfs === true,
222
- usesPnpm: helpers.usesPnpm(nodePackageJson)
223
- };
224
- });
225
- let readmeMetadata;
226
- /**
227
- * Nice data for readme rules
228
- *
229
- * @public
230
- */
231
- async function getReadmeMetadata() {
232
- if (readmeMetadata !== void 0) return readmeMetadata;
233
- const contextMetadata = await getContextMetadata();
234
- readmeMetadata = readmeMetadataTemplate(contextMetadata, {});
235
- return readmeMetadata;
236
- }
237
-
238
- //#endregion
239
- //#region src/lib/readme/rules/badges.ts
240
- var badges_default = { badges: { async content(options) {
241
- const validOptions = z.object({
242
- custom: z.record(z.string(), z.object({
243
- image: z.string(),
244
- link: z.string()
245
- })).optional(),
246
- npm: z.array(z.string()).optional()
247
- }).optional().parse(options);
248
- const metadata = await getReadmeMetadata();
249
- const { ciActionFileName, license, licenseUrl, name, repositoryUrl, usesGitLfs } = metadata;
250
- const badges = [];
251
- if (validOptions?.npm === void 0) {
252
- if (metadata.isPublicNpmPackage) badges.push(`[![NPM Package ${name}](https://img.shields.io/npm/v/${name}.svg)](https://www.npmjs.com/package/${name})`);
253
- } else for (const packageName of validOptions.npm) badges.push(`[![NPM Package ${packageName}](https://img.shields.io/npm/v/${packageName}.svg)](https://www.npmjs.com/package/${packageName})`);
254
- if (license !== void 0 && licenseUrl !== void 0) badges.push(`[![License: ${license}](https://img.shields.io/badge/License-${license.replaceAll("-", "--")}-yellow.svg)](${licenseUrl})`);
255
- if (ciActionFileName !== void 0 && repositoryUrl !== void 0) badges.push(`[![CI](${repositoryUrl}/actions/workflows/${ciActionFileName}/badge.svg)](${repositoryUrl}/actions/workflows/${ciActionFileName})`);
256
- if (usesGitLfs) badges.push("![Git LFS](https://img.shields.io/badge/Git%20LFS-enabled-F64935?logo=gitlfs&logoColor=white)");
257
- if (validOptions?.custom !== void 0) for (const [badgeName, { image, link }] of Object.entries(validOptions.custom)) badges.push(`[![${badgeName}](${image})](${link})`);
258
- return badges.join("\n");
259
- } } };
260
-
261
- //#endregion
262
- //#region src/lib/readme/rules/banner.ts
263
- var banner_default = { banner: { async content(options) {
264
- const validOptions = z.object({
265
- alt: z.string().optional(),
266
- src: z.string().optional()
267
- }).optional().parse(options);
268
- const src = validOptions?.src ?? await getBannerSrc();
269
- if (src === void 0) throw new Error("Banner image not found at any typical location, consider adding something at ./assets/banner.webp");
270
- if (!isUrl(src) && !await isFile(src)) throw new Error(`Banner image not found at "${src}"`);
271
- let alt = validOptions?.alt;
272
- if (alt === void 0) {
273
- const { name: packageName } = await getReadmeMetadata();
274
- if (packageName === void 0) throw new Error("Banner image alt text not available");
275
- alt = `${packageName} banner`;
276
- }
277
- return `![${alt}](${src})`;
278
- } } };
279
- async function getBannerSrc() {
280
- const { projectDirectory } = await getReadmeMetadata();
281
- if (projectDirectory === void 0) throw new Error("No project directory found");
282
- const [firstPath] = await globby([
283
- ".",
284
- "assets",
285
- "media",
286
- "readme-assets",
287
- "readme-media",
288
- "readme",
289
- "images",
290
- ".github/assets"
291
- ].map((location) => path.join(projectDirectory, location)), {
292
- deep: 1,
293
- expandDirectories: {
294
- extensions: [
295
- "png",
296
- "gif",
297
- "jpg",
298
- "jpeg",
299
- "svg",
300
- "webp"
301
- ],
302
- files: [
303
- "banner",
304
- "cover",
305
- "demo",
306
- "header",
307
- "hero",
308
- "image",
309
- "logo",
310
- "overview",
311
- "readme",
312
- "screenshot",
313
- "screenshots",
314
- "splash"
315
- ]
316
- }
317
- });
318
- return firstPath === void 0 ? void 0 : path.relative(process.cwd(), firstPath);
319
- }
320
- function isUrl(text, lenient = true) {
321
- if (typeof text !== "string") throw new TypeError("Expected a string");
322
- text = text.trim();
323
- if (text.includes(" ")) return false;
324
- if (URL.canParse(text)) return true;
325
- return lenient && URL.canParse(`https://${text}`);
326
- }
327
-
328
- //#endregion
329
- //#region src/lib/readme/rules/code.ts
330
- const LEADING_DOT_REGEX = /^\./v;
331
- var code_default = { code: { async content(options) {
332
- const validOptions = z.object({
333
- file: z.string(),
334
- language: z.string().optional(),
335
- trim: z.boolean().default(true)
336
- }).parse(options);
337
- const lang = (path.extname(validOptions.file) ?? "").replace(LEADING_DOT_REGEX, "");
338
- const exampleCode = await fs.readFile(path.join(process.cwd(), validOptions.file), "utf8");
339
- return `\`\`\`${lang}\n${validOptions.trim ? exampleCode.trim() : exampleCode}\n\`\`\``;
340
- } } };
341
-
342
- //#endregion
343
- //#region src/lib/readme/rules/contributing.ts
344
- var contributing_default = { contributing: { async content() {
345
- const { issuesUrl } = await getReadmeMetadata();
346
- if (issuesUrl === void 0) throw new Error("Could not find \"bugs.url\" entry in package.json");
347
- return [
348
- "## Contributing",
349
- "",
350
- `[Issues](${issuesUrl}) are welcome and appreciated.`,
351
- "",
352
- "Please open an issue to discuss changes before submitting a pull request. Unsolicited PRs (especially AI-generated ones) are unlikely to be merged.",
353
- "",
354
- "This repository uses [@kitschpatrol/shared-config](https://github.com/kitschpatrol/shared-config) (via its `ksc` CLI) for linting and formatting, plus [MDAT](https://github.com/kitschpatrol/mdat) for readme placeholder expansion."
355
- ].join("\n");
356
- } } };
357
-
358
- //#endregion
359
- //#region src/lib/readme/rules/dependencies.ts
360
- const PLATFORM_INFO = {
361
- bun: {
362
- display: "Bun",
363
- url: "https://bun.sh/"
364
- },
365
- deno: {
366
- display: "Deno",
367
- url: "https://deno.land/"
368
- },
369
- go: {
370
- display: "Go",
371
- url: "https://go.dev/"
372
- },
373
- java: {
374
- display: "Java",
375
- url: "https://www.java.com/"
376
- },
377
- node: {
378
- display: "Node.js",
379
- url: "https://nodejs.org/en"
380
- },
381
- python: {
382
- display: "Python",
383
- url: "https://www.python.org/"
384
- },
385
- ruby: {
386
- display: "Ruby",
387
- url: "https://www.ruby-lang.org/"
388
- },
389
- rust: {
390
- display: "Rust",
391
- url: "https://www.rust-lang.org/"
392
- }
393
- };
394
- var dependencies_default = { dependencies: { async content() {
395
- const { engines, operatingSystem, peerDependencies, runtimePlatform } = await getReadmeMetadata();
396
- const platformItems = [];
397
- if (engines !== void 0) for (const [name, version] of Object.entries(engines)) {
398
- const info = PLATFORM_INFO[name.toLowerCase()];
399
- const display = info ? `[${info.display}](${info.url})` : name;
400
- platformItems.push(`- ${display} ${version}`);
401
- }
402
- if (runtimePlatform !== void 0) for (const entry of runtimePlatform) {
403
- const spaceIndex = entry.indexOf(" ");
404
- const platformKey = spaceIndex > 0 ? entry.slice(0, spaceIndex) : entry;
405
- const version = spaceIndex > 0 ? entry.slice(spaceIndex + 1) : void 0;
406
- if (engines?.[platformKey] !== void 0) continue;
407
- const info = PLATFORM_INFO[platformKey.toLowerCase()];
408
- const display = info ? `[${info.display}](${info.url})` : platformKey;
409
- platformItems.push(version === void 0 || version === "" ? `- ${display}` : `- ${display} ${version}`);
410
- }
411
- if (operatingSystem !== void 0 && operatingSystem.length > 0) platformItems.push(`- Supported platforms: ${operatingSystem.join(", ")}`);
412
- const peerItems = [];
413
- if (peerDependencies !== void 0) for (const { name, optional, version } of peerDependencies) {
414
- const npmUrl = `https://www.npmjs.com/package/${name}`;
415
- const optionalSuffix = optional ? " _(optional)_" : "";
416
- peerItems.push(`- [${name}](${npmUrl}) ${version}${optionalSuffix}`);
417
- }
418
- const hasPlatform = platformItems.length > 0;
419
- const hasPeers = peerItems.length > 0;
420
- if (!hasPlatform && !hasPeers) return "";
421
- const sections = ["## Dependencies"];
422
- if (hasPlatform && hasPeers) sections.push("", "### Platform", "", ...platformItems, "", "### Peer Dependencies", "", ...peerItems);
423
- else if (hasPlatform) sections.push("", ...platformItems);
424
- else sections.push("", ...peerItems);
425
- return sections.join("\n");
426
- } } };
427
-
428
- //#endregion
429
- //#region src/lib/readme/rules/description.ts
430
- /**
431
- * Simple alias for short-description
432
- */
433
- var description_default = { description: { async content() {
434
- const { description } = await getReadmeMetadata();
435
- if (description === void 0) throw new Error("Could not find \"description\" entry in package.json");
436
- return `**${description}**`;
437
- } } };
438
-
439
- //#endregion
440
- //#region src/lib/readme/rules/development-dependencies.ts
441
- const TOOL_INFO = {
442
- bun: {
443
- display: "Bun",
444
- url: "https://bun.sh/"
445
- },
446
- deno: {
447
- display: "Deno",
448
- url: "https://deno.land/"
449
- },
450
- node: {
451
- display: "Node.js",
452
- url: "https://nodejs.org/en"
453
- },
454
- npm: {
455
- display: "npm",
456
- url: "https://www.npmjs.com/"
457
- },
458
- pnpm: {
459
- display: "pnpm",
460
- url: "https://pnpm.io/"
461
- },
462
- yarn: {
463
- display: "Yarn",
464
- url: "https://yarnpkg.com/"
465
- }
466
- };
467
- var development_dependencies_default = { "development-dependencies": { async content() {
468
- const { developmentDependencies } = await getReadmeMetadata();
469
- if (developmentDependencies === void 0) return "";
470
- const { packageManagers, runtimes } = developmentDependencies;
471
- const items = [];
472
- for (const { name, version } of [...runtimes ?? [], ...packageManagers ?? []]) {
473
- const info = TOOL_INFO[name.toLowerCase()];
474
- const display = info ? `[${info.display}](${info.url})` : name;
475
- items.push(version === void 0 || version === "" ? `- ${display}` : `- ${display} ${version}`);
476
- }
477
- return [
478
- "## Development Dependencies",
479
- "",
480
- ...items
481
- ].join("\n");
482
- } } };
483
-
484
- //#endregion
485
- //#region src/lib/readme/rules/dev-dependencies.ts
486
- /**
487
- * Simple alias for `development-dependencies`
488
- */
489
- var dev_dependencies_default = { "dev-dependencies": getSoleRule(development_dependencies_default) };
490
-
491
- //#endregion
492
- //#region src/lib/readme/rules/license.ts
493
- var license_default = { license: { async content() {
494
- const { author, authorUrl, license, licenseFilePath } = await getReadmeMetadata();
495
- if (author === void 0) throw new Error("Could not find author name in project");
496
- if (license === void 0 || licenseFilePath === void 0) throw new Error("Could not find license for project");
497
- return `## License\n[${license}](${licenseFilePath}) © ${authorUrl === void 0 ? author : `[${author}](${authorUrl})`}`;
498
- } } };
499
-
500
- //#endregion
501
- //#region src/lib/readme/rules/footer.ts
502
- var footer_default = { footer: { content: [getSoleRule(contributing_default), getSoleRule(license_default)] } };
503
-
504
- //#endregion
505
- //#region src/lib/readme/rules/short-description.ts
506
- /**
507
- * Simple alias for `description` rule, to match nomenclature in
508
- * [standard-readme](https://github.com/RichardLitt/standard-readme/blob/main/spec.md#short-description)
509
- * spec.
510
- */
511
- var short_description_default = { "short-description": getSoleRule(description_default) };
512
-
513
- //#endregion
514
- //#region src/lib/readme/rules/title.ts
515
- var title_default = { title: {
516
- async content(options) {
517
- const { postfix, prefix, titleCase } = z.object({
518
- postfix: z.string().optional().default(""),
519
- prefix: z.string().optional().default(""),
520
- titleCase: z.boolean().optional().default(false)
521
- }).parse(options ?? {});
522
- const { name: packageName } = await getReadmeMetadata();
523
- if (packageName === void 0) throw new Error("Could not find project name");
524
- return `# ${prefix}${titleCase ? makeTitleCase(packageName) : packageName}${postfix}`;
525
- },
526
- order: 2
527
- } };
528
- const SPLIT_FOR_TITLE_CASE_REGEX = /[ _\-]+/v;
529
- function makeTitleCase(text) {
530
- return text.split(SPLIT_FOR_TITLE_CASE_REGEX).filter(Boolean).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
531
- }
532
-
533
- //#endregion
534
- //#region src/lib/readme/rules/header.ts
535
- var header_default = { header: {
536
- content: [
537
- getSoleRule(title_default),
538
- getSoleRule(banner_default),
539
- getSoleRule(badges_default),
540
- getSoleRule(short_description_default)
541
- ],
542
- order: 2
543
- } };
544
-
545
- //#endregion
546
- //#region src/lib/readme/rules/install.ts
547
- var install_default = { install: { async content() {
548
- const { bin, engines, isPublicNpmPackage, name, runtimePlatform, usesPnpm } = await getReadmeMetadata();
549
- if (name === void 0) throw new Error("Could not find project name");
550
- const lines = ["## Install"];
551
- if (isPublicNpmPackage || engines?.node !== void 0 || runtimePlatform?.includes("node")) {
552
- const pmAdd = usesPnpm ? "pnpm add" : "npm install";
553
- const pmx = usesPnpm ? "pnpx" : "npx";
554
- lines.push("", "```sh", `${pmAdd} ${name}`, "```");
555
- if (bin !== void 0 && bin.length > 0) lines.push("", "Or run it directly:", "", "```sh", `${pmx} ${name}`, "```");
556
- } else if (runtimePlatform?.some((p) => p.startsWith("python"))) lines.push("", "```sh", `pip install ${name}`, "```");
557
- else if (runtimePlatform?.some((p) => p.startsWith("rust"))) lines.push("", "```sh", `cargo install ${name}`, "```");
558
- else if (runtimePlatform?.some((p) => p.startsWith("go"))) lines.push("", "```sh", `go install ${name}@latest`, "```");
559
- else if (runtimePlatform?.some((p) => p.startsWith("ruby"))) lines.push("", "```sh", `gem install ${name}`, "```");
560
- else throw new Error("Could not determine project ecosystem for install instructions");
561
- return lines.join("\n");
562
- } } };
563
-
564
- //#endregion
565
- //#region src/lib/readme/rules/utilities/size/size-report.ts
566
- const brotliCompressAsync = promisify(brotliCompress);
567
- const gzipCompressAsync = promisify(gzip);
568
- /**
569
- * Creates a SizeInfo object with formatted values
570
- *
571
- * @param bytes - Size in bytes
572
- * @param originalSize - Original file size for percentage calculation
573
- */
574
- function createSizeInfo(bytes, originalSize) {
575
- const percent = originalSize === 0 ? 0 : (originalSize - bytes) / originalSize * 100;
576
- return {
577
- bytes,
578
- bytesPretty: prettyBytes(bytes, { maximumFractionDigits: 1 }),
579
- percent,
580
- percentPretty: `${Math.round(percent)}%`
581
- };
582
- }
583
- /**
584
- * Analyzes a file's size and its compressed sizes using Brotli and Gzip
585
- *
586
- * @param filePath - Path to the file to analyze
587
- *
588
- * @returns Promise containing detailed size report
589
- * @throws {Error} If file cannot be read or compressed
590
- */
591
- async function createSizeReport(filePath) {
592
- try {
593
- const fileContent = await fs.readFile(filePath);
594
- const originalSize = fileContent.length;
595
- const [brotliCompressed, gzipCompressed] = await Promise.all([brotliCompressAsync(fileContent), gzipCompressAsync(fileContent)]);
596
- return {
597
- brotli: createSizeInfo(brotliCompressed.length, originalSize),
598
- gzip: createSizeInfo(gzipCompressed.length, originalSize),
599
- original: createSizeInfo(originalSize, originalSize)
600
- };
601
- } catch (error) {
602
- throw new Error(`Failed to analyze file: ${error instanceof Error ? error.message : "Unknown error"}`, { cause: error });
603
- }
604
- }
605
-
606
- //#endregion
607
- //#region src/lib/readme/rules/size.ts
608
- const optionsSchema$1 = z.object({
609
- compression: z.enum([
610
- "none",
611
- "brotli",
612
- "gzip"
613
- ]).optional().default("none"),
614
- file: z.string()
615
- });
616
- function getSizeForCompression(report, compression) {
617
- switch (compression) {
618
- case "brotli": return report.brotli.bytesPretty;
619
- case "gzip": return report.gzip.bytesPretty;
620
- case "none": return report.original.bytesPretty;
621
- }
622
- }
623
- var size_default = { size: { async content(options) {
624
- const validOptions = optionsSchema$1.parse(options);
625
- const fullPath = path.join(process.cwd(), validOptions.file);
626
- return getSizeForCompression(await createSizeReport(fullPath), validOptions.compression);
627
- } } };
628
-
629
- //#endregion
630
- //#region src/lib/readme/rules/size-table.ts
631
- const fileSchema = z.union([z.string(), z.array(z.string())]).transform((files) => Array.isArray(files) ? files : [files]);
632
- const optionsSchema = z.union([z.object({
633
- brotli: z.boolean().optional().default(true),
634
- file: fileSchema,
635
- gzip: z.boolean().optional().default(true),
636
- original: z.boolean().optional().default(true),
637
- showPercentage: z.boolean().optional().default(false)
638
- }), z.object({
639
- brotli: z.boolean().optional().default(true),
640
- files: fileSchema,
641
- gzip: z.boolean().optional().default(true),
642
- original: z.boolean().optional().default(true),
643
- showPercentage: z.boolean().optional().default(false)
644
- })]).transform((options) => {
645
- if ("file" in options) {
646
- const { file, ...rest } = options;
647
- return {
648
- files: file,
649
- ...rest
650
- };
651
- }
652
- return options;
653
- });
654
- function formatMarkdownTable(reports, options) {
655
- const headers = ["File"];
656
- if (options.original) headers.push("Original");
657
- if (options.gzip) headers.push("Gzip");
658
- if (options.brotli) headers.push("Brotli");
659
- const separators = headers.map(() => "---");
660
- const rows = reports.map(([file, report]) => {
661
- const row = [path.basename(file)];
662
- if (options.original) row.push(report.original.bytesPretty);
663
- if (options.gzip) row.push(options.showPercentage ? `${report.gzip.bytesPretty} (${report.gzip.percentPretty})` : report.gzip.bytesPretty);
664
- if (options.brotli) row.push(options.showPercentage ? `${report.brotli.bytesPretty} (${report.brotli.percentPretty})` : report.brotli.bytesPretty);
665
- return row;
666
- });
667
- return [
668
- `| ${headers.join(" | ")} |`,
669
- `| ${separators.join(" | ")} |`,
670
- ...rows.map((row) => `| ${row.join(" | ")} |`)
671
- ].join("\n");
672
- }
673
- var size_table_default = { "size-table": { async content(options) {
674
- const validOptions = optionsSchema.parse(options);
675
- return formatMarkdownTable(await Promise.all(validOptions.files.map(async (file) => {
676
- const fullPath = path.join(process.cwd(), file);
677
- return [file, await createSizeReport(fullPath)];
678
- })), {
679
- brotli: validOptions.brotli,
680
- gzip: validOptions.gzip,
681
- original: validOptions.original,
682
- showPercentage: validOptions.showPercentage
683
- });
684
- } } };
685
-
686
- //#endregion
687
- //#region src/lib/readme/rules/table-of-contents.ts
688
- var table_of_contents_default = { "table-of-contents": {
689
- async content(options, { tree }) {
690
- const validOptions = z.object({ depth: z.union([
691
- z.literal(1),
692
- z.literal(2),
693
- z.literal(3),
694
- z.literal(4),
695
- z.literal(5),
696
- z.literal(6)
697
- ]).optional() }).optional().parse(options);
698
- const result = toc(tree, {
699
- heading: null,
700
- maxDepth: validOptions?.depth ?? 3,
701
- tight: true
702
- });
703
- if (result.map === void 0) throw new Error("Could not generate table of contents");
704
- const heading = `## Table of contents`;
705
- const rootWrapper = {
706
- children: result.map.children,
707
- type: "root"
708
- };
709
- return [heading, remark().use(remarkGfm).stringify(rootWrapper).replaceAll("\n\n", "\n")].join("\n");
710
- },
711
- order: 1
712
- } };
713
-
714
- //#endregion
715
- //#region src/lib/readme/rules/toc.ts
716
- /**
717
- * Simple alias for table-of-contents
718
- */
719
- var toc_default = { toc: getSoleRule(table_of_contents_default) };
720
-
721
- //#endregion
722
- //#region src/lib/readme/rules/index.ts
723
- var rules_default = {
724
- ...badges_default,
725
- ...banner_default,
726
- ...code_default,
727
- ...contributing_default,
728
- ...dependencies_default,
729
- ...description_default,
730
- ...dev_dependencies_default,
731
- ...development_dependencies_default,
732
- ...footer_default,
733
- ...header_default,
734
- ...install_default,
735
- ...license_default,
736
- ...short_description_default,
737
- ...size_default,
738
- ...size_table_default,
739
- ...table_of_contents_default,
740
- ...title_default,
741
- ...toc_default
742
- };
743
-
744
- //#endregion
745
- //#region src/lib/config.ts
746
- let _configExplorer;
747
- let _additionalConfigExplorer;
748
- function getConfigExplorer() {
749
- _configExplorer ??= cosmiconfig("mdat", { loaders: { ".ts": TypeScriptLoader() } });
750
- return _configExplorer;
751
- }
752
- function getAdditionalConfigExplorer() {
753
- _additionalConfigExplorer ??= cosmiconfig("mdat", { loaders: {
754
- ".json": mdatJsonLoader,
755
- ".ts": TypeScriptLoader()
756
- } });
757
- return _additionalConfigExplorer;
758
- }
759
- /**
760
- * Load and validate mdat configuration. Uses cosmiconfig to search in the usual
761
- * places. Merge precedence: Base Defaults < Defaults < Searched Config <
762
- * Additional Config
763
- */
764
- async function loadConfig(options) {
765
- const { additionalConfig, defaults = rules_default, searchFrom } = options ?? {};
766
- let finalConfig = { mdat: `Powered by the Markdown Autophagic Template system: [mdat](https://github.com/kitschpatrol/mdat).` };
767
- finalConfig = deepMergeDefined(finalConfig, defaults);
768
- const results = await getConfigExplorer().search(searchFrom);
769
- if (results) {
770
- const { config, filepath } = results;
771
- let possibleRules = config;
772
- log.debug(`Using config from "${filepath}"`);
773
- if (typeof config === "string" && filepath.endsWith("package.json")) {
774
- log.debug(`Detected shared config string: "${config}"`);
775
- const { default: sharedConfig } = await import(config);
776
- possibleRules = sharedConfig;
777
- }
778
- const validated = validateConfig(possibleRules);
779
- if (validated) finalConfig = deepMergeDefined(finalConfig, validated);
780
- }
781
- if (additionalConfig !== void 0) {
782
- const additionalConfigArray = Array.isArray(additionalConfig) ? additionalConfig : [additionalConfig];
783
- for (const configOrPath of additionalConfigArray) {
784
- let loaded;
785
- if (typeof configOrPath === "string") {
786
- let loadResults;
787
- if (path.basename(configOrPath).endsWith("package.json")) {
788
- const packageJson = await fs.readFile(configOrPath, "utf8");
789
- loadResults = {
790
- config: mdatJsonLoader(configOrPath, packageJson),
791
- filepath: configOrPath
792
- };
793
- } else loadResults = await getAdditionalConfigExplorer().load(configOrPath);
794
- if (loadResults === null || loadResults === void 0) continue;
795
- const { config: loadedConfig, filepath } = loadResults;
796
- log.debug(`Loaded additional config from "${filepath}"`);
797
- loaded = loadedConfig;
798
- } else loaded = configOrPath;
799
- if (loaded === void 0) continue;
800
- log.debug("Merging config");
801
- const validated = validateConfig(loaded);
802
- if (validated) finalConfig = deepMergeDefined(finalConfig, validated);
803
- }
804
- }
805
- const prettyRules = Object.keys(finalConfig).toSorted().map((rule) => `"${picocolors.green(picocolors.bold(rule))}"`);
806
- log.debug(`Loaded ${picocolors.bold(prettyRules.length)} mdat comment expansion ${plur("rule", prettyRules.length)}:`);
807
- for (const rule of prettyRules) log.debug(`\t${rule}`);
808
- return finalConfig;
809
- }
810
- function validateConfig(value) {
811
- if (rulesSchema.safeParse(value).success) return value;
812
- log.warn(`Config has the wrong shape. Ignoring and using default configuration:\n${JSON.stringify(value, void 0, 2)}`);
813
- }
814
-
815
- //#endregion
816
- //#region src/lib/format.ts
817
- let cachedPrettier;
818
- const configCache = /* @__PURE__ */ new Map();
819
- /**
820
- * Format a markdown string with Prettier, using config discovered from the file
821
- * path. Requires `prettier` to be installed as a peer dependency.
822
- */
823
- async function formatWithPrettier(content, filePath) {
824
- if (cachedPrettier === void 0) try {
825
- cachedPrettier = await import("prettier");
826
- } catch {
827
- throw new Error("The --format flag requires `prettier` to be installed. Run: pnpm add -D prettier");
828
- }
829
- const configKey = filePath === void 0 || filePath === "" ? process.cwd() : path.dirname(filePath);
830
- let config = configCache.get(configKey);
831
- if (config === void 0 && !configCache.has(configKey)) {
832
- config = await cachedPrettier.resolveConfig(filePath ?? process.cwd());
833
- configCache.set(configKey, config);
834
- if (config) log.debug(`Resolved Prettier config for "${configKey}"`);
835
- }
836
- return cachedPrettier.format(content, {
837
- ...config,
838
- filepath: filePath,
839
- parser: "markdown"
840
- });
841
- }
842
-
843
- //#endregion
844
- //#region src/lib/utilities.ts
845
- function zeroPad(n, nMax) {
846
- const places = nMax === 0 ? 1 : Math.floor(Math.log10(Math.abs(nMax)) + 1);
847
- return n.toString().padStart(places, "0");
848
- }
849
- async function getInputOutputPaths(inputs, output, name, extension) {
850
- const paths = [];
851
- for (const [index, file] of inputs.entries()) {
852
- const inputOutputPath = await getInputOutputPath(file, output, name, extension, name !== void 0 && name !== "" && inputs.length > 1 ? `-${zeroPad(index + 1, inputs.length)}` : "");
853
- paths.push(inputOutputPath);
854
- }
855
- return paths;
856
- }
857
- async function getInputOutputPath(input, output, name, extension, nameSuffix = "") {
858
- const resolvedInput = expandPath(input);
859
- if (!isFileSync(resolvedInput)) throw new Error(`Input file not found: "${resolvedInput}"`);
860
- const resolvedOutput = output === void 0 || output === "" ? void 0 : expandPath(output);
861
- if (resolvedOutput !== void 0) {
862
- if (isFileSync(resolvedOutput)) throw new Error(`Output path must be a directory, received a file path: "${resolvedOutput}"`);
863
- await fs.mkdir(resolvedOutput, { recursive: true });
864
- }
865
- return {
866
- input: resolvedInput,
867
- name: `${name === void 0 || name === "" ? path.basename(resolvedInput, path.extname(resolvedInput)) : path.basename(name, path.extname(name))}${nameSuffix}${extension === void 0 ? name !== void 0 && path.extname(name) !== "" ? path.extname(name) : path.extname(input) : `.${extension}`}`,
868
- output: resolvedOutput ?? path.dirname(resolvedInput)
869
- };
870
- }
871
- function expandPath(file) {
872
- return untildify(file);
873
- }
874
- function ensureArray(value) {
875
- if (value === void 0 || value === null) return [];
876
- return Array.isArray(value) ? value : [value];
877
- }
878
- const README_SEARCH_REGEX = /^readme(?:\.\w+)?$/iv;
879
- /**
880
- * Finds a readme file in the current working directory (case-insensitive).
881
- */
882
- async function findReadme() {
883
- log.debug("Searching for readme in current directory...");
884
- const readme = (await fs.readdir(process.cwd())).find((entry) => README_SEARCH_REGEX.test(entry));
885
- if (readme !== void 0) {
886
- const absolutePath = path.resolve(readme);
887
- log.debug(`Found readme at "${absolutePath}"`);
888
- return absolutePath;
889
- }
890
- }
891
- /**
892
- * Searches up for a readme.md file.
893
- *
894
- * @throws {Error} If no readme is found
895
- */
896
- async function findReadmeThrows() {
897
- const readme = await findReadme();
898
- if (readme === void 0) throw new Error("No readme found");
899
- return readme;
900
- }
901
- let cachedAmbientRemarkConfig;
902
- async function loadAmbientRemarkConfig() {
903
- if (cachedAmbientRemarkConfig !== void 0) return cachedAmbientRemarkConfig;
904
- const ambientConfig = new Configuration({
905
- cwd: process.cwd(),
906
- detectConfig: true,
907
- packageField: "remarkConfig",
908
- rcName: ".remarkrc"
909
- });
910
- const configResult = await new Promise((resolve) => {
911
- ambientConfig.load("", (error, result) => {
912
- if (error) {
913
- log.error(String(error));
914
- resolve(void 0);
915
- return;
916
- }
917
- resolve(result);
918
- });
919
- });
920
- if (configResult) {
921
- const { filePath } = configResult;
922
- if (filePath === void 0) log.debug("No ambient Remark configuration file found");
923
- else log.debug(`Found and loaded ambient Remark configuration from "${filePath}"`);
924
- cachedAmbientRemarkConfig = stripLintPlugins(configResult);
925
- return cachedAmbientRemarkConfig;
926
- }
927
- log.debug("No ambient Remark configuration found");
928
- cachedAmbientRemarkConfig = {
929
- filePath: void 0,
930
- plugins: [],
931
- settings: {}
932
- };
933
- return cachedAmbientRemarkConfig;
934
- }
935
- /**
936
- * Strip remark-lint plugins from an ambient config. Lint plugins only produce
937
- * VFile warnings and never modify the AST or output — running them during
938
- * expansion is pure overhead.
939
- */
940
- function stripLintPlugins(config) {
941
- return {
942
- ...config,
943
- plugins: config.plugins.filter((entry) => {
944
- const plugin = Array.isArray(entry) ? entry[0] : entry;
945
- if (typeof plugin !== "function") return true;
946
- const { name } = plugin;
947
- return name !== "remarkLint" && !name.startsWith("remark-lint:") && name !== "remarkValidateLinks";
948
- })
949
- };
950
- }
951
-
952
- //#endregion
953
- //#region src/lib/processors.ts
954
- async function processFiles(files, loader, processorGetter, name, output, config) {
955
- const [resolvedConfig, localRemarkConfig] = await Promise.all([loader({ additionalConfig: config }), loadAmbientRemarkConfig()]);
956
- const resolvedFiles = ensureArray(files);
957
- const inputOutputPaths = await getInputOutputPaths(resolvedFiles, output, name, "md");
958
- const resolvedProcessor = processorGetter(resolvedConfig, localRemarkConfig);
959
- return await Promise.all(inputOutputPaths.map(async ({ input, name: outputName, output: outputDirectory }) => {
960
- const inputFile = await read(input);
961
- const result = await resolvedProcessor.process(inputFile);
962
- result.dirname = outputDirectory;
963
- result.basename = outputName;
964
- return result;
965
- }));
966
- }
967
- function getExpandProcessor(config, ambientRemarkConfig) {
968
- return remark().use({ settings: {
969
- bullet: "-",
970
- emphasis: "_"
971
- } }).use(remarkGfm).use(ambientRemarkConfig).use(() => async function(tree, file) {
972
- mdatSplit(tree, file);
973
- mdatCollapse(tree, file);
974
- await mdatExpand(tree, file, config);
975
- });
976
- }
977
- function getCollapseProcessor(_config, ambientRemarkConfig) {
978
- return remark().use({ settings: {
979
- bullet: "-",
980
- emphasis: "_"
981
- } }).use(remarkGfm).use(ambientRemarkConfig).use(() => function(tree, file) {
982
- mdatSplit(tree, file);
983
- mdatCollapse(tree, file);
984
- });
985
- }
986
- function getStripProcessor(_config, ambientRemarkConfig) {
987
- return remark().use({ settings: {
988
- bullet: "-",
989
- emphasis: "_"
990
- } }).use(remarkGfm).use(ambientRemarkConfig).use(() => function(tree, file) {
991
- mdatSplit(tree, file);
992
- mdatStrip(tree, file);
993
- });
994
- }
995
-
996
- //#endregion
997
- //#region src/lib/readme/templates/mdat-readme-compound.md?raw
998
- var mdat_readme_compound_default = "<!-- header -->\n\n<!-- table-of-contents -->\n\n## Overview\n\n## Getting started\n\n### Dependencies\n\n### Installation\n\n## Usage\n\n### Library\n\n#### API\n\n#### Examples\n\n### CLI\n\n#### Commands\n\n#### Examples\n\n## Background\n\n### Motivation\n\n### Implementation notes\n\n### Similar projects\n\n## The future\n\n## Maintainers\n\n_List maintainer(s) for a repository, along with one way of contacting them (e.g. GitHub link or email)._\n\n## Acknowledgments\n\n_State anyone or anything that significantly helped with the development of your project. State public contact hyper-links if applicable._\n\n<!-- footer -->\n";
999
-
1000
- //#endregion
1001
- //#region src/lib/readme/templates/mdat-readme.md?raw
1002
- var mdat_readme_default = "<!-- title -->\n\n<!-- banner -->\n\n<!-- badges -->\n\n<!-- short-description -->\n\n<!-- table-of-contents -->\n\n## Overview\n\n## Getting started\n\n### Dependencies\n\n### Installation\n\n## Usage\n\n### Library\n\n#### API\n\n#### Examples\n\n### CLI\n\n#### Commands\n\n#### Examples\n\n## Background\n\n### Motivation\n\n### Implementation notes\n\n### Similar projects\n\n## The future\n\n## Maintainers\n\n_List maintainer(s) for a repository, along with one way of contacting them (e.g. GitHub link or email)._\n\n## Acknowledgments\n\n_State anyone or anything that significantly helped with the development of your project. State public contact hyper-links if applicable._\n\n<!-- contributing -->\n\n<!-- license -->\n";
1003
-
1004
- //#endregion
1005
- //#region src/lib/readme/templates/standard-readme-basic-compound.md?raw
1006
- var standard_readme_basic_compound_default = "<!-- header -->\n\n## Install\n\n```sh\n# Code block illustrating how to install.\n```\n\n## Usage\n\n```ts\n// Code block illustrating common usage.\n// Consider using the <!-- code({ src: \"path/to/example.ts\" }) --> comment as well.\n```\n\n<!-- footer -->\n";
1007
-
1008
- //#endregion
1009
- //#region src/lib/readme/templates/standard-readme-basic.md?raw
1010
- var standard_readme_basic_default = "<!-- title -->\n\n<!-- short-description -->\n\n<!-- table-of-contents -->\n\n## Install\n\n```sh\n# Code block illustrating how to install.\n```\n\n## Usage\n\n```ts\n// Code block illustrating common usage.\n// Consider using the <!-- code({ src: \"path/to/example.ts\" })--> comment as well.\n```\n\n<!-- contributing -->\n\n<!-- license -->\n";
1011
-
1012
- //#endregion
1013
- //#region src/lib/readme/templates/standard-readme-full-compound.md?raw
1014
- var standard_readme_full_compound_default = "<!-- header -->\n\n_Long description goes here._\n\n_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._\n\n<!-- table-of-contents -->\n\n## Background\n\n_Cover motivation. Cover abstract dependencies. Cover intellectual provenance: A See Also section is also fitting._\n\n### See also\n\n## Install\n\n```sh\n# Code block illustrating how to install.\n```\n\n### Dependencies\n\n_Required if there are unusual dependencies or dependencies that must be manually installed._\n\n## Usage\n\n```ts\n// Code block illustrating common usage.\n// Consider using the <!-- code({ src: \"path/to/example.ts\" })--> comment as well.\n```\n\n```ts\n// If importable, code block indicating both import functionality and usage.\n```\n\n### CLI\n\n```ts\n// If CLI compatible, code block indicating common usage.\n```\n\n## _Extra Sections (Rename)_\n\n## Security\n\n## API\n\n_Describe exported functions and objects._\n\n- _Describe signatures, return types, callbacks, and events._\n- _Cover types covered where not obvious._\n- _Describe caveats._\n- _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._\n\n## Maintainers\n\n_List maintainer(s) for a repository, along with one way of contacting them (e.g. GitHub link or email)._\n\n## Thanks\n\n_State anyone or anything that significantly helped with the development of your project. State public contact hyper-links if applicable._\n\n<!-- footer -->\n";
1015
-
1016
- //#endregion
1017
- //#region src/lib/readme/templates/standard-readme-full.md?raw
1018
- var standard_readme_full_default = "<!-- title -->\n\n<!-- banner -->\n\n<!-- badges -->\n\n<!-- short-description -->\n\n_Long description goes here._\n\n_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._\n\n<!-- table-of-contents -->\n\n## Background\n\n_Cover motivation. Cover abstract dependencies. Cover intellectual provenance: A See Also section is also fitting._\n\n### See also\n\n## Install\n\n```sh\n# Code block illustrating how to install.\n```\n\n### Dependencies\n\n_Required if there are unusual dependencies or dependencies that must be manually installed._\n\n## Usage\n\n```ts\n// Code block illustrating common usage.\n// Consider using the <!-- code({ src: \"path/to/example.ts\" })--> comment as well.\n```\n\n```ts\n// If importable, code block indicating both import functionality and usage.\n```\n\n### CLI\n\n```ts\n// If CLI compatible, code block indicating common usage.\n```\n\n## _Extra Sections (Rename)_\n\n## Security\n\n## API\n\n_Describe exported functions and objects._\n\n- _Describe signatures, return types, callbacks, and events._\n- _Cover types covered where not obvious._\n- _Describe caveats._\n- _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._\n\n## Maintainers\n\n_List maintainer(s) for a repository, along with one way of contacting them (e.g. GitHub link or email)._\n\n## Thanks\n\n_State anyone or anything that significantly helped with the development of your project. State public contact hyper-links if applicable._\n\n<!-- contributing -->\n\n<!-- license -->\n";
1019
-
1020
- //#endregion
1021
- //#region src/lib/readme/templates/index.ts
1022
- var templates_default = {
1023
- "MDAT Readme": {
1024
- content: {
1025
- compound: mdat_readme_compound_default,
1026
- explicit: mdat_readme_default
1027
- },
1028
- description: "The house style. An expansive starting point. Prune to your context and taste.",
1029
- exampleLink: "https://github.com/kitschpatrol/mdat/blob/main/readme.md"
1030
- },
1031
- "Standard Readme Basic": {
1032
- content: {
1033
- compound: standard_readme_basic_compound_default,
1034
- explicit: standard_readme_basic_default
1035
- },
1036
- description: "Includes only the \"required\" sections from the Standard Readme specification.",
1037
- exampleLink: "https://github.com/RichardLitt/standard-readme/blob/main/example-readmes/minimal-readme.md"
1038
- },
1039
- "Standard Readme Full": {
1040
- content: {
1041
- compound: standard_readme_full_compound_default,
1042
- explicit: standard_readme_full_default
1043
- },
1044
- description: "Includes all sections from the Standard Readme specification.",
1045
- exampleLink: "https://github.com/RichardLitt/standard-readme/blob/main/example-readmes/maximal-readme.md"
1046
- }
1047
- };
1048
-
1049
- //#endregion
1050
- //#region src/lib/readme/create.ts
1051
- /**
1052
- * Creates a new readme file interactively.
1053
- *
1054
- * @returns Path to the created readme file.
1055
- */
1056
- async function createReadmeInteractive() {
1057
- const readmePath = await findReadme();
1058
- intro(`Running ${picocolors.bold("mdat create")} interactively`);
1059
- const newReadmePath = await createReadme(await group({
1060
- async overwrite() {
1061
- if (readmePath === void 0) return true;
1062
- if (await confirm({
1063
- message: `Found an existing readme at "${picocolors.blue(readmePath)}". Do you want to overwrite it?`,
1064
- active: "Overwrite",
1065
- inactive: "Exit"
1066
- }) === false) throw new Error("`mdat create` was cancelled to avoid an overwrite - no changes were made");
1067
- return true;
1068
- },
1069
- template: async () => select({
1070
- message: "Which template would you like to use?",
1071
- options: getTemplateOptions()
1072
- }),
1073
- compound: async () => select({
1074
- message: "Do you want to use \"compound comments\" where possible, which combine several expansions into a single comment block?",
1075
- options: [{
1076
- label: `Yes: Combine things like ${picocolors.green("<!-- title -->")} and ${picocolors.green("<!-- badges -->")} in a single ${picocolors.green("<!-- header -->")} comment.`,
1077
- value: true
1078
- }, {
1079
- label: "No: Use individual MDAT expansion comments for each section.",
1080
- value: false
1081
- }]
1082
- }),
1083
- expand: async () => confirm({
1084
- initialValue: true,
1085
- message: "Do you want to run `mdat expand` now to expand the template with content from your project metadata?"
1086
- })
1087
- }, { onCancel() {
1088
- throw new Error("`mdat create` was cancelled - no changes were made");
1089
- } }));
1090
- note(`Readme created: "${picocolors.blue(picocolors.bold(newReadmePath))}"`);
1091
- outro("Done!");
1092
- return newReadmePath;
1093
- }
1094
- /**
1095
- * Creates a new readme file with the given options.
1096
- *
1097
- * @returns Path to the created readme file.
1098
- */
1099
- async function createReadme(options) {
1100
- const resolvedOptions = deepMergeDefined({
1101
- compound: true,
1102
- output: process.cwd(),
1103
- overwrite: true,
1104
- expand: true,
1105
- template: Object.keys(templates_default)[0]
1106
- }, options ?? {});
1107
- const templateString = getTemplateForConfig(resolvedOptions.template, resolvedOptions.compound);
1108
- const readmePath = path.join(resolvedOptions.output, "readme.md");
1109
- if (!resolvedOptions.overwrite) {
1110
- let exists = true;
1111
- try {
1112
- await fs.access(readmePath);
1113
- } catch {
1114
- exists = false;
1115
- }
1116
- if (exists) throw new Error(`Readme already exists at "${readmePath}". Use the overwrite option to replace it.`);
1117
- }
1118
- await fs.writeFile(readmePath, templateString, "utf8");
1119
- if (resolvedOptions.expand) {
1120
- const [result] = await expand(readmePath);
1121
- if (result === void 0) throw new Error(`Failed to expand readme at "${readmePath}"`);
1122
- await write(result);
1123
- }
1124
- return readmePath;
1125
- }
1126
- function getTemplateForConfig(templateKey, compound) {
1127
- if (!Object.hasOwn(templates_default, templateKey)) throw new Error(`Unknown template "${templateKey}". Available templates: ${Object.keys(templates_default).join(", ")}`);
1128
- return templates_default[templateKey].content[compound ? "compound" : "explicit"];
1129
- }
1130
- function getTemplateOptions() {
1131
- return Object.entries(templates_default).map(([key, value]) => ({
1132
- label: key,
1133
- hint: value.description,
1134
- value: key
1135
- }));
1136
- }
1137
-
1138
- //#endregion
1139
- //#region src/lib/api.ts
1140
- /**
1141
- * Expand MDAT comments in one or more Markdown files. If no files are provided,
1142
- * auto-finds the closest readme.md. Writing is the responsibility of the caller
1143
- * (e.g. via `await write(result)`)
1144
- *
1145
- * @returns An array of VFiles
1146
- */
1147
- async function expand(files, name, output, config, options) {
1148
- files ??= await findReadmeThrows();
1149
- const results = await processFiles(files, loadConfig, getExpandProcessor, name, output, config);
1150
- if (options?.format) await formatResults(results);
1151
- return results;
1152
- }
1153
- /**
1154
- * Collapse MDAT comments in one or more Markdown files. If no files are
1155
- * provided, auto-finds the closest readme.md. Writing is the responsibility of
1156
- * the caller (e.g. via `await write(result)`)
1157
- *
1158
- * @returns An array of VFiles
1159
- */
1160
- async function collapse(files, name, output, config, options) {
1161
- files ??= await findReadmeThrows();
1162
- const results = await processFiles(files, loadConfig, getCollapseProcessor, name, output, config);
1163
- if (options?.format) await formatResults(results);
1164
- return results;
1165
- }
1166
- /**
1167
- * Strips MDAT comments in one or more Markdown files without touching other
1168
- * content. Does _not_ automatically expand Mdat content before stripping the
1169
- * tags. If no files are provided, auto-finds the closest readme.md. Writing is
1170
- * the responsibility of the caller (e.g. via `await write(result)`)
1171
- *
1172
- * @returns An array of VFiles
1173
- */
1174
- async function strip(files, name, output, config, options) {
1175
- files ??= await findReadmeThrows();
1176
- const results = await processFiles(files, loadConfig, getStripProcessor, name, output, config);
1177
- if (options?.format) await formatResults(results);
1178
- return results;
1179
- }
1180
- /**
1181
- * Dry-run expand and compare with file on disk. If no files are provided,
1182
- * auto-finds the closest readme.md.
1183
- *
1184
- * @returns Per-file sync status and expanded VFiles
1185
- */
1186
- async function check(files, config, options) {
1187
- files ??= await findReadmeThrows();
1188
- const { read } = await import("to-vfile");
1189
- const resolvedFiles = Array.isArray(files) ? files : [files];
1190
- const [originals, results] = await Promise.all([Promise.all(resolvedFiles.map(async (f) => read(f))), processFiles(files, loadConfig, getExpandProcessor, void 0, void 0, config)]);
1191
- if (options?.format) await formatResults(results);
1192
- return results.map((result, i) => {
1193
- const original = originals[i];
1194
- if (original === void 0) throw new Error(`Missing original file for comparison at index ${i}`);
1195
- return compareWithDiff(original, result, options);
1196
- });
1197
- }
1198
- function compareWithDiff(original, result, options) {
1199
- const inSync = original.toString().replaceAll("\r\n", "\n") === result.toString();
1200
- if (!inSync) {
1201
- const parser = remark().use(remarkGfm);
1202
- const originalTree = parser.parse(original.toString());
1203
- mdatSplit(originalTree, original);
1204
- const expandedTree = parser.parse(result.toString());
1205
- mdatSplit(expandedTree, result);
1206
- const diffResults = mdatDiff(originalTree, original, expandedTree, result);
1207
- if (options?.format && diffResults.every((r) => r.status === "ok")) {
1208
- const message = result.message("Formatting differences outside mdat tags", { source: "diff" });
1209
- message.fatal = false;
1210
- }
1211
- }
1212
- return {
1213
- inSync,
1214
- result
1215
- };
1216
- }
1217
- async function formatResults(results) {
1218
- for (const file of results) file.value = await formatWithPrettier(file.toString(), file.path === "" ? void 0 : file.path);
1219
- }
1220
-
1221
- //#endregion
1222
11
  //#region src/bin/options.ts
1223
12
  const nameOption = { name: {
1224
13
  alias: "n",
@@ -1294,7 +83,7 @@ const startTime = performance.now();
1294
83
  const yargsInstance = yargs(hideBin(process.argv));
1295
84
  try {
1296
85
  await yargsInstance.scriptName("mdat").usage("$0 [command] [files..] [options]", "Work with MDAT placeholder comments in Markdown files.").option(verboseOption).middleware((argv) => {
1297
- setLogger$2(createLogger({
86
+ setLogger$1(createLogger({
1298
87
  logToConsole: {
1299
88
  showLevel: false,
1300
89
  showName: false,