metalsmith-markdown-partials 2.5.0 → 2.5.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.
Files changed (3) hide show
  1. package/README.md +6 -3
  2. package/package.json +13 -12
  3. package/src/index.js +187 -0
package/README.md CHANGED
@@ -7,9 +7,15 @@ A Metalsmith plugin that enables the use of Markdown partials.
7
7
  [![license: MIT][license-badge]][license-url]
8
8
  [![coverage][coverage-badge]][coverage-url]
9
9
  [![ESM/CommonJS][modules-badge]][npm-url]
10
+ [![Known Vulnerabilities](https://snyk.io/test/npm/metalsmith-markdown-partials/badge.svg)](https://snyk.io/test/npm/metalsmith-markdown-partials)
10
11
 
11
12
  Markdown fragments are inserted into the contents of a page markdown file by replacing an include marker with markdown partials. This allows for modular markdown and promotes reuse of content.
12
13
 
14
+ ## Features
15
+ - This plugin supports both ESM and CommonJS environments with no configuration needed:
16
+ - ESM: `import mdPartials from 'metalsmith-markdown-partials'`
17
+ - CommonJS: `const mdPartials = require('metalsmith-markdown-partials')`
18
+
13
19
  ## Installation
14
20
 
15
21
  ```js
@@ -19,9 +25,6 @@ $ npm install --save metalsmith-markdown-partials
19
25
  ## Usage
20
26
 
21
27
  ```js
22
- var mdPartials = require('metalsmith-markdown-partials');
23
-
24
- ...
25
28
  .use(mdPartials({
26
29
  libraryPath: './markdown-partials/',
27
30
  fileSuffix: '.md.njk',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "metalsmith-markdown-partials",
3
- "version": "2.5.0",
3
+ "version": "2.5.1",
4
4
  "description": "A Metalsmith plugin that allows the use of partial markdown files",
5
5
  "keywords": [
6
6
  "metalsmith-plugin",
@@ -22,8 +22,9 @@
22
22
  "url": "git+https://github.com/wernerglinka/metalsmith-markdown-partials.git"
23
23
  },
24
24
  "files": [
25
+ "src",
25
26
  "lib",
26
- "LICENSE.md",
27
+ "LICENSE",
27
28
  "README.md"
28
29
  ],
29
30
  "author": {
@@ -38,16 +39,16 @@
38
39
  "scripts": {
39
40
  "build": "microbundle --entry src/index.js --output lib/index.js --target node -f esm,cjs --strict --generateTypes=false",
40
41
  "changelog": "auto-changelog -u --commit-limit false --ignore-commit-pattern '^((dev|chore|ci):|Release)'",
41
- "coverage": "npm test && c8 report --reporter=text-lcov > ./coverage.info",
42
+ "coverage": "c8 --include=src/**/*.js --reporter=lcov --reporter=text-summary mocha 'test/index.js' 'test/cjs.test.cjs' -t 15000",
42
43
  "format": "prettier --write \"**/*.{yml,md,js,json}\"",
43
44
  "format:check": "prettier --list-different \"**/*.{yml,md,js,json}\"",
44
45
  "lint": "eslint --fix .",
45
46
  "lint:check": "eslint --fix-dry-run .",
46
47
  "prepublishOnly": "npm run build",
47
- "update-coverage": "node scripts/update-coverage-badge.js",
48
- "prerelease": "npm run update-coverage && git add README.md && git commit -m \"Update coverage badge in README\" || true",
49
- "release": "npm run build && GITHUB_TOKEN=$(grep GITHUB_TOKEN .env | cut -d '=' -f2) ./node_modules/.bin/release-it . ",
50
- "release:check": "npm run lint:check && npm run build && GITHUB_TOKEN=$(grep GITHUB_TOKEN .env | cut -d '=' -f2) ./node_modules/.bin/release-it . --dry-run",
48
+ "release:patch": "release-it patch",
49
+ "release:minor": "release-it minor",
50
+ "release:major": "release-it major",
51
+ "release:check": "npm run lint:check && npm run build && release-it --dry-run",
51
52
  "test": "c8 --include=src/**/*.js mocha 'test/index.js' 'test/cjs.test.cjs' -t 15000",
52
53
  "test:esm": "c8 --include=src/**/*.js mocha test/index.js -t 15000",
53
54
  "test:cjs": "c8 --include=src/**/*.js mocha test/cjs.test.cjs -t 15000",
@@ -57,13 +58,13 @@
57
58
  "devDependencies": {
58
59
  "auto-changelog": "^2.5.0",
59
60
  "c8": "^10.1.3",
60
- "eslint": "^9.26.0",
61
- "eslint-config-prettier": "^10.1.5",
61
+ "eslint": "^9.32.0",
62
+ "eslint-config-prettier": "^10.1.8",
62
63
  "metalsmith": "^2.6.3",
63
64
  "microbundle": "^0.15.1",
64
- "mocha": "^11.2.2",
65
- "prettier": "^3.5.3",
66
- "release-it": "19.0.2"
65
+ "mocha": "^11.7.1",
66
+ "prettier": "^3.6.2",
67
+ "release-it": "19.0.4"
67
68
  },
68
69
  "peerDependencies": {
69
70
  "metalsmith": "^2.5.1"
package/src/index.js ADDED
@@ -0,0 +1,187 @@
1
+ /**
2
+ * A Metalsmith plugin to merge markdown partials into main markdown files.
3
+ *
4
+ * @module metalsmith-markdown-partials
5
+ */
6
+
7
+ /**
8
+ * @typedef {Object} Options
9
+ * @property {String} libraryPath - Path to the markdown partials library (defaults to './src/content/md-library/')
10
+ * @property {String} fileSuffix - File suffix for markdown files (defaults to '.md')
11
+ */
12
+
13
+ // Define debug namespace at the top of the file
14
+ const debugNs = 'metalsmith-markdown-partials';
15
+
16
+ /** @type {Options} */
17
+ const defaults = {
18
+ libraryPath: './src/content/md-library/',
19
+ fileSuffix: '.md'
20
+ };
21
+
22
+ /**
23
+ * Normalize plugin options by merging with defaults
24
+ * @param {Options} [options] - User provided options
25
+ * @returns {Options} Normalized options
26
+ */
27
+ function normalizeOptions(options) {
28
+ return Object.assign({}, defaults, options || {});
29
+ }
30
+
31
+ /**
32
+ * Extract markdown partials from files and prepare them for insertion
33
+ *
34
+ * @param {Object} files - The metalsmith file object
35
+ * @param {Options} options - Plugin options
36
+ * @param {Function} debug - Debug function
37
+ * @returns {Array} Array with all markdown include objects
38
+ */
39
+ function getMarkdownIncludes(files, options, debug) {
40
+ const markdownIncludes = [];
41
+
42
+ // Extract the library name from the path
43
+ const libraryPath = options.libraryPath.slice(0, -1).split('/');
44
+ const libraryName = libraryPath[libraryPath.length - 1];
45
+
46
+ debug('Processing markdown files with libraryName: %s', libraryName);
47
+
48
+ // Regex for matching include markers
49
+ const markerRegex = /\{#md\s*".+?"\s*#\}/g;
50
+ const markerStart = '{#md';
51
+ const markerEnd = '#}';
52
+
53
+ // Set to track already processed partials to prevent duplicates
54
+ const processedPartials = new Set();
55
+
56
+ Object.keys(files).forEach((file) => {
57
+ /*
58
+ * checks if string 'file' ends with options.fileSuffix
59
+ * when metalsmith-in-place or metalsmith-layouts are used
60
+ * the suffix depends on what templating language is used
61
+ * for example with Nunjucks it would be .md.njk
62
+ *
63
+ * Also check that file does NOT start with libraryName as
64
+ * the markdown partials library is also located in the content folder
65
+ */
66
+ if (file.endsWith(options.fileSuffix) && !file.startsWith(libraryName)) {
67
+ const str = files[file].contents.toString();
68
+
69
+ // Check if markers are present
70
+ const matches = str.match(markerRegex);
71
+ if (!matches) {return;}
72
+
73
+ debug('Found %d markdown partials in %s', matches.length, file);
74
+
75
+ // Process each marker in the file
76
+ matches.forEach((marker) => {
77
+ // Extract the filename from the marker
78
+ const markerFileName = marker.replaceAll(' ', '').replace(`${markerStart}"`, '').replace(`"${markerEnd}`, '');
79
+ const partialKey = `${libraryName}/${markerFileName}`;
80
+
81
+ // Check if partial file exists
82
+ if (!files[partialKey]) {
83
+ debug('Warning: Partial file not found: %s', partialKey);
84
+ return;
85
+ }
86
+
87
+ // Skip if we've already processed this exact marker+file combination
88
+ const combinedKey = `${file}:${marker}`;
89
+ if (processedPartials.has(combinedKey)) {return;}
90
+
91
+ processedPartials.add(combinedKey);
92
+
93
+ // Get the replacement content
94
+ const replacementString = files[partialKey].contents.toString();
95
+
96
+ markdownIncludes.push({
97
+ marker,
98
+ markerReplacement: replacementString,
99
+ file
100
+ });
101
+ });
102
+ }
103
+ });
104
+
105
+ // Remove markdown-partials from metalsmith build process
106
+ Object.keys(files).forEach((file) => {
107
+ if (file.startsWith(libraryName)) {
108
+ delete files[file];
109
+ }
110
+ });
111
+
112
+ debug('Processed %d markdown includes', markdownIncludes.length);
113
+ return markdownIncludes;
114
+ }
115
+
116
+ /**
117
+ * Replace markers with their markdown replacement strings
118
+ *
119
+ * @param {Object} files - The metalsmith file object
120
+ * @param {Array} markdownIncludes - Array with all markdown include objects
121
+ * @param {Function} debug - Debug function
122
+ * @return {void}
123
+ */
124
+ function resolveMarkdownIncludes(files, markdownIncludes, debug) {
125
+ // replace all markers with their markdown replacements
126
+ markdownIncludes.forEach((markdownInclude) => {
127
+ const fileData = files[markdownInclude.file];
128
+
129
+ // replace the include marker with the actual include file content
130
+ try {
131
+ const contents = fileData.contents.toString();
132
+ fileData.contents = Buffer.from(contents.replace(markdownInclude.marker, markdownInclude.markerReplacement));
133
+ debug('Replaced marker in %s', markdownInclude.file);
134
+ } catch (e) {
135
+ debug('Error replacing marker in %s: %s', markdownInclude.file, e.message);
136
+ console.error(`Error replacing marker in ${markdownInclude.file}:`, e);
137
+ }
138
+ });
139
+ }
140
+
141
+ /**
142
+ * A Metalsmith plugin to merge markdown partials into main markdown file
143
+ *
144
+ * A marker of the form {#md "<file name>.md" #} indicates where the partial
145
+ * must be inserted and also provides the file name of the replacement markdown.
146
+ *
147
+ * @param {Options} [options] - Plugin options
148
+ * @returns {import('metalsmith').Plugin} Metalsmith plugin function
149
+ * @example
150
+ * // In your metalsmith build:
151
+ * .use(markdownPartials({
152
+ * libraryPath: './src/content/md-partials/',
153
+ * fileSuffix: '.md.njk'
154
+ * }))
155
+ */
156
+ function initMarkdownPartials(options) {
157
+ options = normalizeOptions(options);
158
+
159
+ return function markdownPartials(files, metalsmith, done) {
160
+ // Use metalsmith's debug method if available
161
+ const debug = metalsmith.debug ? metalsmith.debug(debugNs) : () => {};
162
+ debug('Running with options: %o', options);
163
+
164
+ try {
165
+ // Get all markdown includes
166
+ const markdownIncludes = getMarkdownIncludes(files, options, debug);
167
+
168
+ // Replace include markers with their respective replacement
169
+ if (markdownIncludes.length) {
170
+ resolveMarkdownIncludes(files, markdownIncludes, debug);
171
+ }
172
+
173
+ setImmediate(done);
174
+ } catch (err) {
175
+ debug('Error processing markdown partials: %s', err.message);
176
+ setImmediate(() => done(err));
177
+ }
178
+ };
179
+ }
180
+
181
+ // ESM export
182
+ export default initMarkdownPartials;
183
+
184
+ // CommonJS export compatibility
185
+ if (typeof module !== 'undefined') {
186
+ module.exports = initMarkdownPartials;
187
+ }